mirror of
https://github.com/SableClient/Sable.git
synced 2026-12-06 00:32:26 -08:00
chore: resolve merge conflicts with dev; document telemetry consent banner
This commit is contained in:
commit
57eedcbf60
135 files changed
+4042
-719
No files matched your search
@@ -0,0 +1,5 @@
|
||||
---
|
||||
default: minor
|
||||
---
|
||||
|
||||
Bring in Sable Call, our fork of element call, which introduces camera settings, screenshare settings, echo cancellation, noise suppression, automatic gain control, and avatars in calls.
|
||||
@@ -0,0 +1,5 @@
|
||||
---
|
||||
default: minor
|
||||
---
|
||||
|
||||
added a `/sharehistory` command to [share encrypted history with a user](https://github.com/matrix-org/matrix-spec-proposals/blob/rav/proposal/encrypted_history_sharing/proposals/4268-encrypted-history-sharing.md)
|
||||
@@ -0,0 +1,5 @@
|
||||
---
|
||||
default: patch
|
||||
---
|
||||
|
||||
Add Ctrl+F / Cmd+F keyboard shortcut to open Sable search instead of browser find-in-page
|
||||
@@ -0,0 +1,5 @@
|
||||
---
|
||||
default: minor
|
||||
---
|
||||
|
||||
Added a toggle to enable/disable showing the call button for large (> 10 member) rooms.
|
||||
@@ -0,0 +1,5 @@
|
||||
---
|
||||
default: patch
|
||||
---
|
||||
|
||||
Add Vitest testing infrastructure with example tests and contributor documentation
|
||||
@@ -0,0 +1,5 @@
|
||||
---
|
||||
default: minor
|
||||
---
|
||||
|
||||
Added the ability to edit the description of a file and streamlined the image and video ui
|
||||
@@ -0,0 +1,5 @@
|
||||
---
|
||||
default: patch
|
||||
---
|
||||
|
||||
Account switcher: show a confirmation dialog before signing out of an account.
|
||||
@@ -0,0 +1,5 @@
|
||||
---
|
||||
default: patch
|
||||
---
|
||||
|
||||
Fix animated avatars not looping.
|
||||
@@ -0,0 +1,5 @@
|
||||
---
|
||||
default: patch
|
||||
---
|
||||
|
||||
Autocomplete: pressing Enter now selects the highlighted item instead of sending the message. The first item is highlighted on open and ArrowUp/Down navigate the list while keeping typing focus in the editor. Focus returns to the message editor after completing a mention or emoji.
|
||||
@@ -0,0 +1,5 @@
|
||||
---
|
||||
default: patch
|
||||
---
|
||||
|
||||
Fix camera turning on by default when starting a call from the room header button
|
||||
@@ -0,0 +1,5 @@
|
||||
---
|
||||
default: patch
|
||||
---
|
||||
|
||||
Adding account: show a "Cancel" button next to the "Adding account" label so users can abort the flow.
|
||||
@@ -0,0 +1,5 @@
|
||||
---
|
||||
default: patch
|
||||
---
|
||||
|
||||
Message editor: add `autoCapitalize="sentences"` to respect the OS/keyboard capitalisation setting on mobile.
|
||||
@@ -0,0 +1,5 @@
|
||||
---
|
||||
default: patch
|
||||
---
|
||||
|
||||
Fix emoji color bleeding into adjacent text in read receipt display names on Safari/WebKit
|
||||
@@ -0,0 +1,5 @@
|
||||
---
|
||||
default: patch
|
||||
---
|
||||
|
||||
Notifications: add "Favicon Dot: Mentions Only" setting — when enabled, the favicon badge only changes for mentions/keywords, not plain unreads.
|
||||
@@ -0,0 +1,5 @@
|
||||
---
|
||||
default: patch
|
||||
---
|
||||
|
||||
Video and audio messages: volume level is now persisted across page loads via `localStorage` and shared between all media players.
|
||||
@@ -0,0 +1,5 @@
|
||||
---
|
||||
default: patch
|
||||
---
|
||||
|
||||
Fix notification dot badge appearing off-center on sidebar avatars
|
||||
@@ -0,0 +1,5 @@
|
||||
---
|
||||
default: patch
|
||||
---
|
||||
|
||||
Reduced-motion: add `animation-iteration-count: 1` so spinners stop after one cycle instead of running indefinitely at near-zero speed.
|
||||
@@ -0,0 +1,5 @@
|
||||
---
|
||||
default: patch
|
||||
---
|
||||
|
||||
Server picker: prevent iOS from restoring the old server name while the user is actively editing the input.
|
||||
@@ -0,0 +1,5 @@
|
||||
---
|
||||
default: patch
|
||||
---
|
||||
|
||||
Browser tab/PWA: use the correct light (`#ffffff`) and dark (`#1b1a21`) theme-color values via `media` attribute on the meta tags.
|
||||
@@ -0,0 +1,5 @@
|
||||
---
|
||||
default: patch
|
||||
---
|
||||
|
||||
Fix excessive whitespace between the thread root message and replies in the thread drawer
|
||||
@@ -0,0 +1,5 @@
|
||||
---
|
||||
default: patch
|
||||
---
|
||||
|
||||
Fix URL preview scroll arrows appearing when there is no content to scroll
|
||||
@@ -0,0 +1,5 @@
|
||||
---
|
||||
default: patch
|
||||
---
|
||||
|
||||
fix of compatibility of voice messages with element clients and style misshaps
|
||||
@@ -0,0 +1 @@
|
||||
* @7w1 @Just-Insane @hazre
|
||||
@@ -79,6 +79,24 @@ jobs:
|
||||
- name: Run Knip
|
||||
run: pnpm run knip
|
||||
|
||||
tests:
|
||||
name: Tests
|
||||
runs-on: ubuntu-latest
|
||||
if: github.head_ref != 'release'
|
||||
permissions:
|
||||
contents: read
|
||||
steps:
|
||||
- name: Checkout repository
|
||||
uses: actions/checkout@de0fac2e4500dabe0009e67214ff5f5447ce83dd # v6.0.2
|
||||
with:
|
||||
persist-credentials: false
|
||||
|
||||
- name: Setup app
|
||||
uses: ./.github/actions/setup
|
||||
|
||||
- name: Run tests
|
||||
run: pnpm run test:run
|
||||
|
||||
build:
|
||||
name: Build
|
||||
runs-on: ubuntu-latest
|
||||
|
||||
@@ -1,5 +1,6 @@
|
||||
experiment
|
||||
dist
|
||||
coverage
|
||||
node_modules
|
||||
devAssets
|
||||
|
||||
@@ -18,6 +19,7 @@ devAssets
|
||||
*.tfbackend
|
||||
!*.tfbackend.example
|
||||
crash.log
|
||||
build.sh
|
||||
|
||||
# the following line was added with the "git ignore" tool by itsrye.dev, version 0.1.0
|
||||
.lh
|
||||
+4
-1
@@ -37,12 +37,15 @@ It is not always possible to phrase every change in such a manner, but it is des
|
||||
|
||||
Also, we use [ESLint](https://eslint.org/) for clean and stylistically consistent code syntax, so make sure your pull request follow it.
|
||||
|
||||
**Pull requests are not merged unless all quality checks are passing.** At minimum, `format`, `lint`, `typecheck`, and `knip` must all be green before a pull request can be merged. Run these locally before opening or updating a pull request:
|
||||
**Pull requests are not merged unless all quality checks are passing.** At minimum, `format`, `lint`, `typecheck`, `knip`, and `tests` must all be green before a pull request can be merged. Run these locally before opening or updating a pull request:
|
||||
|
||||
- `pnpm run fmt:check`
|
||||
- `pnpm run lint`
|
||||
- `pnpm run typecheck`
|
||||
- `pnpm run knip`
|
||||
- `pnpm run test:run`
|
||||
|
||||
If your change touches logic with testable behaviour, please include tests. See [docs/TESTING.md](./docs/TESTING.md) for a guide on how to write them.
|
||||
|
||||
## Restrictions on Generative AI Usage
|
||||
|
||||
|
||||
@@ -122,6 +122,23 @@ Sentry controls are split across two settings locations:
|
||||
- **Attach debug logs**: Manually attach recent logs to next error report
|
||||
- **Test buttons**: Force an error, test feedback, test message capture
|
||||
|
||||
### 6. First-Login Consent Banner
|
||||
|
||||
When `VITE_SENTRY_DSN` is set and a user has never seen the crash-reporting notice (i.e. `sable_sentry_enabled` is absent from `localStorage`), a dismissible banner slides in from the bottom of the screen on first load. It explains that anonymous crash reports are enabled and links to the Privacy Policy.
|
||||
|
||||
**Actions available in the banner:**
|
||||
|
||||
| Button | Effect |
|
||||
|--------|--------|
|
||||
| **Got it** / × (close) | Sets `sable_sentry_enabled = true` in `localStorage` and dismisses the banner with a fade-out animation. Reporting continues. |
|
||||
| **Opt out** | Sets `sable_sentry_enabled = false` and reloads the page. Sentry is disabled for this user going forward. |
|
||||
|
||||
Once the user has interacted with the banner (either action), it never appears again. The same preference can be changed later in **Settings → General → Diagnostics & Privacy**.
|
||||
|
||||
**Implementation:** `src/app/components/telemetry-consent/TelemetryConsentBanner.tsx` — rendered inside the logged-in client layout so it only appears after a session is established.
|
||||
|
||||
> **Self-hosters**: If you do not set `VITE_SENTRY_DSN`, the banner is never shown and Sentry is entirely disabled at build time. No network requests are made to Sentry.
|
||||
|
||||
## Configuration
|
||||
|
||||
### Environment Variables
|
||||
|
||||
+137
@@ -0,0 +1,137 @@
|
||||
# Testing Guide
|
||||
|
||||
Sable uses [Vitest](https://vitest.dev/) as its test runner and [React Testing Library](https://testing-library.com/docs/react-testing-library/intro/) for component tests. Tests run in a [jsdom](https://github.com/jsdom/jsdom) environment and coverage is collected via V8.
|
||||
|
||||
---
|
||||
|
||||
## Running tests
|
||||
|
||||
```sh
|
||||
# Watch mode — reruns affected tests on file save (recommended during development)
|
||||
pnpm test
|
||||
|
||||
# Single run — equivalent to what CI runs
|
||||
pnpm test:run
|
||||
|
||||
# With browser UI (interactive results viewer)
|
||||
pnpm test:ui
|
||||
|
||||
# With coverage report
|
||||
pnpm test:coverage
|
||||
```
|
||||
|
||||
Coverage reports are written to `coverage/`. Open `coverage/index.html` in your browser for the full HTML report.
|
||||
|
||||
---
|
||||
|
||||
## Writing tests
|
||||
|
||||
### Where to put test files
|
||||
|
||||
Place test files next to the source file they cover, with a `.test.ts` or `.test.tsx` suffix:
|
||||
|
||||
```
|
||||
src/app/utils/colorMXID.ts
|
||||
src/app/utils/colorMXID.test.ts
|
||||
|
||||
src/app/features/room/RoomTimeline.tsx
|
||||
src/app/features/room/RoomTimeline.test.tsx
|
||||
```
|
||||
|
||||
### Testing plain utility functions
|
||||
|
||||
For pure functions in `src/app/utils/`, no special setup is needed — just import and assert:
|
||||
|
||||
```ts
|
||||
import { describe, it, expect } from 'vitest';
|
||||
import { bytesToSize } from './common';
|
||||
|
||||
describe('bytesToSize', () => {
|
||||
it('converts bytes to KB', () => {
|
||||
expect(bytesToSize(1500)).toBe('1.5 KB');
|
||||
});
|
||||
});
|
||||
```
|
||||
|
||||
### Testing React components
|
||||
|
||||
Use `@testing-library/react` to render components inside the jsdom environment. Query by accessible role/text rather than CSS classes or implementation details:
|
||||
|
||||
```tsx
|
||||
import { describe, it, expect } from 'vitest';
|
||||
import { render, screen } from '@testing-library/react';
|
||||
import userEvent from '@testing-library/user-event';
|
||||
import { MyButton } from './MyButton';
|
||||
|
||||
describe('MyButton', () => {
|
||||
it('calls onClick when pressed', async () => {
|
||||
const user = userEvent.setup();
|
||||
const onClick = vi.fn();
|
||||
|
||||
render(<MyButton onClick={onClick}>Click me</MyButton>);
|
||||
|
||||
await user.click(screen.getByRole('button', { name: 'Click me' }));
|
||||
|
||||
expect(onClick).toHaveBeenCalledOnce();
|
||||
});
|
||||
});
|
||||
```
|
||||
|
||||
### Testing hooks
|
||||
|
||||
Use `renderHook` from `@testing-library/react`:
|
||||
|
||||
```ts
|
||||
import { describe, it, expect } from 'vitest';
|
||||
import { renderHook, act } from '@testing-library/react';
|
||||
import { useMyHook } from './useMyHook';
|
||||
|
||||
describe('useMyHook', () => {
|
||||
it('returns the expected initial value', () => {
|
||||
const { result } = renderHook(() => useMyHook());
|
||||
expect(result.current.value).toBe(0);
|
||||
});
|
||||
});
|
||||
```
|
||||
|
||||
### Mocking
|
||||
|
||||
Vitest has Jest-compatible mocking APIs:
|
||||
|
||||
```ts
|
||||
import { vi } from 'vitest';
|
||||
|
||||
// Mock a module
|
||||
vi.mock('./someModule', () => ({ doThing: vi.fn(() => 'mocked') }));
|
||||
|
||||
// Spy on a method
|
||||
const spy = vi.spyOn(console, 'error').mockImplementation(() => {});
|
||||
|
||||
// Restore after test
|
||||
afterEach(() => vi.restoreAllMocks());
|
||||
```
|
||||
|
||||
### Path aliases
|
||||
|
||||
All the project's path aliases work inside tests — you can import using `$utils/`, `$components/`, `$features/`, etc., just like in application code.
|
||||
|
||||
---
|
||||
|
||||
## What to test
|
||||
|
||||
Not every file needs tests. Focus on logic that would be painful to debug when broken:
|
||||
|
||||
| Worth testing | Less valuable |
|
||||
| ----------------------------------------------- | ---------------------------------------------- |
|
||||
| Pure utility functions (`src/app/utils/`) | Purely presentational components with no logic |
|
||||
| Custom hooks with non-trivial state transitions | Thin wrappers around third-party APIs |
|
||||
| State atoms and reducers | Generated or declarative config |
|
||||
| Data transformation / formatting functions | |
|
||||
|
||||
When you fix a bug, consider adding a regression test that would have caught it — the description in the test is useful documentation.
|
||||
|
||||
---
|
||||
|
||||
## CI
|
||||
|
||||
`pnpm test:run` is part of the required quality checks and runs on every pull request alongside `lint`, `typecheck`, and `knip`. A PR with failing tests cannot be merged.
|
||||
+2
-1
@@ -23,7 +23,8 @@
|
||||
property="og:description"
|
||||
content="A Matrix client where you can enjoy the conversation using (not) simple, elegant and secure interface protected by e2ee with the power of open source. And colorful cosmetics. Because yes."
|
||||
/>
|
||||
<meta name="theme-color" content="#000000" />
|
||||
<meta name="theme-color" media="(prefers-color-scheme: light)" content="#ffffff" />
|
||||
<meta name="theme-color" media="(prefers-color-scheme: dark)" content="#1b1a21" />
|
||||
|
||||
<link id="favicon" rel="shortcut icon" href="./public/favicon.png" />
|
||||
|
||||
|
||||
@@ -7,8 +7,9 @@
|
||||
},
|
||||
"ignoreDependencies": [
|
||||
"buffer",
|
||||
"@element-hq/element-call-embedded",
|
||||
"@matrix-org/matrix-sdk-crypto-wasm"
|
||||
"@sableclient/sable-call-embedded",
|
||||
"@matrix-org/matrix-sdk-crypto-wasm",
|
||||
"@testing-library/user-event"
|
||||
],
|
||||
"ignoreBinaries": ["knope"],
|
||||
"rules": {
|
||||
|
||||
+2
-2
@@ -64,6 +64,6 @@ repo = "Sable"
|
||||
[release_notes]
|
||||
# The <!-- commit:$commit_hash --> marker is used by prepare-release.yml
|
||||
change_templates = [
|
||||
"### $summary <!-- commit:$commit_hash -->\n\n$details",
|
||||
# "### $summary <!-- commit:$commit_hash -->\n\n$details",
|
||||
"* $summary <!-- commit:$commit_hash -->",
|
||||
]
|
||||
]
|
||||
+14
-3
@@ -17,6 +17,10 @@
|
||||
"fmt": "prettier --write .",
|
||||
"fmt:check": "prettier --check .",
|
||||
"typecheck": "tsc",
|
||||
"test": "vitest",
|
||||
"test:ui": "vitest --ui",
|
||||
"test:run": "vitest run",
|
||||
"test:coverage": "vitest run --coverage",
|
||||
"knip": "knip",
|
||||
"knope": "knope",
|
||||
"document-change": "knope document-change",
|
||||
@@ -66,7 +70,7 @@
|
||||
"linkify-react": "^4.3.2",
|
||||
"linkifyjs": "^4.3.2",
|
||||
"matrix-js-sdk": "^38.4.0",
|
||||
"matrix-widget-api": "1.13.0",
|
||||
"matrix-widget-api": "^1.16.1",
|
||||
"millify": "^6.1.0",
|
||||
"pdfjs-dist": "^5.4.624",
|
||||
"prismjs": "^1.30.0",
|
||||
@@ -90,13 +94,16 @@
|
||||
},
|
||||
"devDependencies": {
|
||||
"@cloudflare/vite-plugin": "^1.26.0",
|
||||
"@element-hq/element-call-embedded": "0.16.3",
|
||||
"@sableclient/sable-call-embedded": "v1.1.3",
|
||||
"@esbuild-plugins/node-globals-polyfill": "^0.2.3",
|
||||
"@eslint/compat": "2.0.2",
|
||||
"@eslint/js": "9.39.3",
|
||||
"@rollup/plugin-inject": "^5.0.5",
|
||||
"@rollup/plugin-wasm": "^6.2.2",
|
||||
"@sentry/vite-plugin": "^5.1.1",
|
||||
"@testing-library/jest-dom": "^6.9.1",
|
||||
"@testing-library/react": "^16.3.2",
|
||||
"@testing-library/user-event": "^14.6.1",
|
||||
"@types/chroma-js": "^3.1.2",
|
||||
"@types/file-saver": "^2.0.7",
|
||||
"@types/is-hotkey": "^0.1.10",
|
||||
@@ -108,12 +115,15 @@
|
||||
"@types/sanitize-html": "^2.16.0",
|
||||
"@types/ua-parser-js": "^0.7.39",
|
||||
"@vitejs/plugin-react": "^5.1.4",
|
||||
"@vitest/coverage-v8": "^4.1.0",
|
||||
"@vitest/ui": "^4.1.0",
|
||||
"buffer": "^6.0.3",
|
||||
"eslint": "9.39.3",
|
||||
"eslint-config-airbnb-extended": "3.0.1",
|
||||
"eslint-config-prettier": "10.1.8",
|
||||
"eslint-plugin-prettier": "5.5.5",
|
||||
"globals": "17.3.0",
|
||||
"jsdom": "^29.0.0",
|
||||
"knip": "5.85.0",
|
||||
"prettier": "3.8.1",
|
||||
"typescript": "^5.9.3",
|
||||
@@ -123,6 +133,7 @@
|
||||
"vite-plugin-static-copy": "^3.2.0",
|
||||
"vite-plugin-svgr": "4.5.0",
|
||||
"vite-plugin-top-level-await": "^1.6.0",
|
||||
"vitest": "^4.1.0",
|
||||
"wrangler": "^4.70.0"
|
||||
}
|
||||
}
|
||||
}
|
||||
Generated
+862
-12
File diff suppressed because it is too large.
Load diff
@@ -6,6 +6,8 @@ allowBuilds:
|
||||
workerd: true
|
||||
engineStrict: true
|
||||
minimumReleaseAge: 1440
|
||||
minimumReleaseAgeExclude:
|
||||
- '@sableclient/sable-call-embedded'
|
||||
|
||||
overrides:
|
||||
brace-expansion: '>=1.1.12'
|
||||
|
||||
@@ -7,8 +7,8 @@
|
||||
"display": "standalone",
|
||||
"orientation": "portrait",
|
||||
"start_url": "./",
|
||||
"background_color": "#fff",
|
||||
"theme_color": "#fff",
|
||||
"background_color": "#1b1a21",
|
||||
"theme_color": "#1b1a21",
|
||||
"icons": [
|
||||
{
|
||||
"src": "./public/android/android-chrome-36x36.png",
|
||||
|
||||
@@ -9,8 +9,8 @@ import {
|
||||
useCallThemeSync,
|
||||
useCallMemberSoundSync,
|
||||
} from '$hooks/useCallEmbed';
|
||||
import { CallEmbed, useClientWidgetApiEvent, ElementWidgetActions } from '$plugins/call';
|
||||
import { callChatAtom, callEmbedAtom } from '$state/callEmbed';
|
||||
import { CallEmbed } from '$plugins/call';
|
||||
import { useSelectedRoom } from '$hooks/router/useSelectedRoom';
|
||||
import { ScreenSize, useScreenSizeContext } from '$hooks/useScreenSize';
|
||||
import { IncomingCallModal } from './IncomingCallModal';
|
||||
@@ -20,12 +20,13 @@ function CallUtils({ embed }: { embed: CallEmbed }) {
|
||||
|
||||
useCallMemberSoundSync(embed);
|
||||
useCallThemeSync(embed);
|
||||
useCallHangupEvent(
|
||||
embed,
|
||||
useCallback(() => {
|
||||
setCallEmbed(undefined);
|
||||
}, [setCallEmbed])
|
||||
);
|
||||
|
||||
const handleCallEnd = useCallback(() => {
|
||||
setCallEmbed(undefined);
|
||||
}, [setCallEmbed]);
|
||||
|
||||
useCallHangupEvent(embed, handleCallEnd);
|
||||
useClientWidgetApiEvent(embed.call, ElementWidgetActions.Close, handleCallEnd);
|
||||
|
||||
return null;
|
||||
}
|
||||
|
||||
@@ -70,7 +70,7 @@ function makeUIAAction<T>(
|
||||
type SetupVerificationProps = {
|
||||
onComplete: (recoveryKey: string) => void;
|
||||
};
|
||||
function SetupVerification({ onComplete }: SetupVerificationProps) {
|
||||
function SetupVerification({ onComplete }: Readonly<SetupVerificationProps>) {
|
||||
const mx = useMatrixClient();
|
||||
const alive = useAlive();
|
||||
|
||||
@@ -227,7 +227,7 @@ function SetupVerification({ onComplete }: SetupVerificationProps) {
|
||||
type RecoveryKeyDisplayProps = {
|
||||
recoveryKey: string;
|
||||
};
|
||||
function RecoveryKeyDisplay({ recoveryKey }: RecoveryKeyDisplayProps) {
|
||||
function RecoveryKeyDisplay({ recoveryKey }: Readonly<RecoveryKeyDisplayProps>) {
|
||||
const [show, setShow] = useState(false);
|
||||
|
||||
const handleCopy = () => {
|
||||
@@ -241,7 +241,7 @@ function RecoveryKeyDisplay({ recoveryKey }: RecoveryKeyDisplayProps) {
|
||||
FileSaver.saveAs(blob, 'recovery-key.txt');
|
||||
};
|
||||
|
||||
const safeToDisplayKey = show ? recoveryKey : recoveryKey.replace(/[^\s]/g, '*');
|
||||
const safeToDisplayKey = show ? recoveryKey : recoveryKey.replaceAll(/[^\s]/g, '*');
|
||||
|
||||
return (
|
||||
<Box direction="Column" gap="400">
|
||||
|
||||
@@ -85,7 +85,7 @@ export const PdfViewer = as<'div', PdfViewerProps>(
|
||||
if (docState.status !== AsyncStatus.Success) return;
|
||||
const jumpInput = evt.currentTarget.jumpInput as HTMLInputElement;
|
||||
if (!jumpInput) return;
|
||||
const jumpTo = parseInt(jumpInput.value, 10);
|
||||
const jumpTo = Number.parseInt(jumpInput.value, 10);
|
||||
setPageNo(Math.max(1, Math.min(docState.data.numPages, jumpTo)));
|
||||
setJumpAnchor(undefined);
|
||||
};
|
||||
|
||||
@@ -28,7 +28,7 @@ import {
|
||||
VideoContent,
|
||||
} from './message';
|
||||
import { UrlPreviewCard, UrlPreviewHolder } from './url-preview';
|
||||
import { Image, MediaControl, Video } from './media';
|
||||
import { Image, MediaControl, PersistedVolumeVideo } from './media';
|
||||
import { ImageViewer } from './image-viewer';
|
||||
import { PdfViewer } from './Pdf-viewer';
|
||||
import { TextViewer } from './text-viewer';
|
||||
@@ -47,6 +47,7 @@ type RenderMessageContentProps = {
|
||||
htmlReactParserOptions: HTMLReactParserOptions;
|
||||
linkifyOpts: Opts;
|
||||
outlineAttachment?: boolean;
|
||||
hideCaption?: boolean;
|
||||
};
|
||||
|
||||
const getMediaType = (url: string) => {
|
||||
@@ -71,6 +72,7 @@ function RenderMessageContentInternal({
|
||||
htmlReactParserOptions,
|
||||
linkifyOpts,
|
||||
outlineAttachment,
|
||||
hideCaption,
|
||||
}: RenderMessageContentProps) {
|
||||
const content = useMemo(() => getContent<any>(), [getContent]);
|
||||
|
||||
@@ -121,7 +123,7 @@ function RenderMessageContentInternal({
|
||||
|
||||
const renderCaption = () => {
|
||||
const hasCaption = content.body && content.body.trim().length > 0;
|
||||
if (captionPosition === CaptionPosition.Hidden) return null;
|
||||
if (captionPosition === CaptionPosition.Hidden || hideCaption) return null;
|
||||
if (hasCaption && content.filename && content.filename !== content.body) {
|
||||
if (captionPosition !== CaptionPosition.Inline)
|
||||
return (
|
||||
@@ -321,7 +323,7 @@ function RenderMessageContentInternal({
|
||||
)
|
||||
: undefined
|
||||
}
|
||||
renderVideo={(p) => <Video {...p} />}
|
||||
renderVideo={(p) => <PersistedVolumeVideo {...p} />}
|
||||
/>
|
||||
)}
|
||||
outlined={outlineAttachment}
|
||||
|
||||
@@ -9,6 +9,7 @@ export const Editor = style([
|
||||
boxShadow: `inset 0 0 0 ${config.borderWidth.B300} ${color.SurfaceVariant.ContainerLine}`,
|
||||
borderRadius: config.radii.R400,
|
||||
overflow: 'hidden',
|
||||
width: '100%',
|
||||
},
|
||||
]);
|
||||
|
||||
|
||||
@@ -160,6 +160,8 @@ export const CustomEditor = forwardRef<HTMLDivElement, CustomEditorProps>(
|
||||
onKeyDown={handleKeydown}
|
||||
onKeyUp={onKeyUp}
|
||||
onPaste={onPaste}
|
||||
// Defer to OS capitalization setting (respects iOS sentence-case toggle).
|
||||
autoCapitalize="sentences"
|
||||
// keeps focus after pressing send.
|
||||
onBlur={() => {
|
||||
if (mobileOrTablet()) ReactEditor.focus(editor);
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
import { style } from '@vanilla-extract/css';
|
||||
import { globalStyle, style } from '@vanilla-extract/css';
|
||||
import { DefaultReset, color, config } from 'folds';
|
||||
|
||||
export const AutocompleteMenuBase = style([
|
||||
@@ -38,3 +38,11 @@ export const AutocompleteNotice = style([
|
||||
AutocompleteMenuHeader,
|
||||
{ color: color.SurfaceVariant.OnContainer },
|
||||
]);
|
||||
|
||||
export const AutocompleteMenuItems = style({});
|
||||
|
||||
globalStyle(`${AutocompleteMenuItems} button[data-selected='true']`, {
|
||||
backgroundColor: color.SurfaceVariant.ContainerHover,
|
||||
outline: `2px solid ${color.Primary.Main}`,
|
||||
outlineOffset: -2,
|
||||
});
|
||||
@@ -1,6 +1,5 @@
|
||||
import { ReactNode } from 'react';
|
||||
import { ReactNode, useEffect, useLayoutEffect, useRef, useState } from 'react';
|
||||
import FocusTrap from 'focus-trap-react';
|
||||
import { isKeyHotkey } from 'is-hotkey';
|
||||
import { Header, Menu, Scroll, config } from 'folds';
|
||||
|
||||
import { preventScrollWithArrowKey, stopPropagation } from '$utils/keyboard';
|
||||
@@ -8,6 +7,9 @@ import { useAlive } from '$hooks/useAlive';
|
||||
import * as css from './AutocompleteMenu.css';
|
||||
import { BaseAutocompleteMenu } from './BaseAutocompleteMenu';
|
||||
|
||||
export const AUTOCOMPLETE_NAVIGATE_EVENT = 'autocomplete-navigate';
|
||||
export type AutocompleteNavigateDetail = { direction: 1 | -1 };
|
||||
|
||||
type AutocompleteMenuProps = {
|
||||
requestClose: () => void;
|
||||
headerContent: ReactNode;
|
||||
@@ -15,6 +17,9 @@ type AutocompleteMenuProps = {
|
||||
};
|
||||
export function AutocompleteMenu({ headerContent, requestClose, children }: AutocompleteMenuProps) {
|
||||
const alive = useAlive();
|
||||
const itemsRef = useRef<HTMLDivElement>(null);
|
||||
const [selectedIndex, setSelectedIndex] = useState(0);
|
||||
const prevButtonCountRef = useRef(-1);
|
||||
|
||||
const handleDeactivate = () => {
|
||||
if (alive()) {
|
||||
@@ -23,6 +28,41 @@ export function AutocompleteMenu({ headerContent, requestClose, children }: Auto
|
||||
}
|
||||
};
|
||||
|
||||
// Sync data-selected to DOM; reset to index 0 when the item list changes
|
||||
useLayoutEffect(() => {
|
||||
const buttons = Array.from(
|
||||
itemsRef.current?.querySelectorAll<HTMLButtonElement>('button') ?? []
|
||||
);
|
||||
const count = buttons.length;
|
||||
|
||||
let idx = selectedIndex;
|
||||
if (count !== prevButtonCountRef.current) {
|
||||
prevButtonCountRef.current = count;
|
||||
idx = 0;
|
||||
if (selectedIndex !== 0) setSelectedIndex(0);
|
||||
}
|
||||
|
||||
const safeIdx = Math.max(0, Math.min(idx, count - 1));
|
||||
buttons.forEach((btn, i) => {
|
||||
btn.setAttribute('data-selected', String(i === safeIdx));
|
||||
});
|
||||
}, [selectedIndex]);
|
||||
|
||||
// Listen for navigation events dispatched by the editor key handler
|
||||
useEffect(() => {
|
||||
const container = itemsRef.current?.closest('[data-autocomplete-menu]');
|
||||
if (!container) return undefined;
|
||||
const handler = (e: Event) => {
|
||||
const { direction } = (e as CustomEvent<AutocompleteNavigateDetail>).detail;
|
||||
setSelectedIndex((prev) => {
|
||||
const buttons = itemsRef.current?.querySelectorAll('button') ?? [];
|
||||
return Math.max(0, Math.min(prev + direction, buttons.length - 1));
|
||||
});
|
||||
};
|
||||
container.addEventListener(AUTOCOMPLETE_NAVIGATE_EVENT, handler);
|
||||
return () => container.removeEventListener(AUTOCOMPLETE_NAVIGATE_EVENT, handler);
|
||||
}, []);
|
||||
|
||||
return (
|
||||
<BaseAutocompleteMenu>
|
||||
<FocusTrap
|
||||
@@ -32,8 +72,6 @@ export function AutocompleteMenu({ headerContent, requestClose, children }: Auto
|
||||
returnFocusOnDeactivate: false,
|
||||
clickOutsideDeactivates: true,
|
||||
allowOutsideClick: true,
|
||||
isKeyForward: (evt: KeyboardEvent) => isKeyHotkey('arrowdown', evt),
|
||||
isKeyBackward: (evt: KeyboardEvent) => isKeyHotkey('arrowup', evt),
|
||||
escapeDeactivates: stopPropagation,
|
||||
}}
|
||||
>
|
||||
@@ -42,7 +80,13 @@ export function AutocompleteMenu({ headerContent, requestClose, children }: Auto
|
||||
{headerContent}
|
||||
</Header>
|
||||
<Scroll style={{ flexGrow: 1 }} onKeyDown={preventScrollWithArrowKey}>
|
||||
<div style={{ padding: config.space.S200 }}>{children}</div>
|
||||
<div
|
||||
ref={itemsRef}
|
||||
className={css.AutocompleteMenuItems}
|
||||
style={{ padding: config.space.S200 }}
|
||||
>
|
||||
{children}
|
||||
</div>
|
||||
</Scroll>
|
||||
</Menu>
|
||||
</FocusTrap>
|
||||
|
||||
@@ -7,7 +7,9 @@ type BaseAutocompleteMenuProps = {
|
||||
export function BaseAutocompleteMenu({ children }: BaseAutocompleteMenuProps) {
|
||||
return (
|
||||
<div className={css.AutocompleteMenuBase}>
|
||||
<div className={css.AutocompleteMenuContainer}>{children}</div>
|
||||
<div className={css.AutocompleteMenuContainer} data-autocomplete-menu="true">
|
||||
{children}
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -1,5 +1,6 @@
|
||||
import { KeyboardEvent as ReactKeyboardEvent, useEffect, useMemo } from 'react';
|
||||
import { Editor } from 'slate';
|
||||
import { ReactEditor } from 'slate-react';
|
||||
import { Box, MenuItem, Text, toRem } from 'folds';
|
||||
import { Room } from '$types/matrix-sdk';
|
||||
|
||||
@@ -57,13 +58,10 @@ export function EmoticonAutocomplete({
|
||||
|
||||
const [emojiThreshold] = useSetting(settingsAtom, 'emojiSuggestThreshold');
|
||||
|
||||
const searchList = useMemo(() => {
|
||||
const list: Array<EmoticonSearchItem> = [];
|
||||
return list.concat(
|
||||
imagePacks.flatMap((pack) => pack.getImages(ImageUsage.Emoticon)),
|
||||
emojis
|
||||
);
|
||||
}, [imagePacks]);
|
||||
const searchList = useMemo<Array<EmoticonSearchItem>>(
|
||||
() => [...imagePacks.flatMap((pack) => pack.getImages(ImageUsage.Emoticon)), ...emojis],
|
||||
[imagePacks]
|
||||
);
|
||||
|
||||
const [result, search, resetSearch] = useAsyncSearch(
|
||||
searchList,
|
||||
@@ -91,6 +89,7 @@ export function EmoticonAutocomplete({
|
||||
const emoticonEl = createEmoticonElement(key, shortcode);
|
||||
replaceWithElement(editor, query.range, emoticonEl);
|
||||
moveCursor(editor, true);
|
||||
ReactEditor.focus(editor);
|
||||
requestClose();
|
||||
});
|
||||
|
||||
|
||||
@@ -1,5 +1,6 @@
|
||||
import { KeyboardEvent as ReactKeyboardEvent, useCallback, useEffect } from 'react';
|
||||
import { Editor } from 'slate';
|
||||
import { ReactEditor } from 'slate-react';
|
||||
import { Avatar, Icon, Icons, MenuItem, Text } from 'folds';
|
||||
import { JoinRule, MatrixClient } from '$types/matrix-sdk';
|
||||
import { useAtomValue } from 'jotai';
|
||||
@@ -115,6 +116,7 @@ export function RoomMentionAutocomplete({
|
||||
);
|
||||
replaceWithElement(editor, query.range, mentionEl);
|
||||
moveCursor(editor, true);
|
||||
ReactEditor.focus(editor);
|
||||
requestClose();
|
||||
};
|
||||
|
||||
|
||||
@@ -1,5 +1,6 @@
|
||||
import { useEffect, KeyboardEvent as ReactKeyboardEvent } from 'react';
|
||||
import { Editor } from 'slate';
|
||||
import { ReactEditor } from 'slate-react';
|
||||
import { Avatar, Icon, Icons, MenuItem, Text } from 'folds';
|
||||
import { MatrixClient, Room, RoomMember } from '$types/matrix-sdk';
|
||||
|
||||
@@ -113,6 +114,7 @@ export function UserMentionAutocomplete({
|
||||
);
|
||||
replaceWithElement(editor, query.range, mentionEl);
|
||||
moveCursor(editor, true);
|
||||
ReactEditor.focus(editor);
|
||||
requestClose();
|
||||
};
|
||||
|
||||
|
||||
@@ -322,7 +322,7 @@ const parseHeadingNode = (
|
||||
|
||||
const headingMatch = node.name.match(/^h([123456])$/);
|
||||
const [, g1AsLevel] = headingMatch ?? ['h3', '3'];
|
||||
const level = parseInt(g1AsLevel, 10);
|
||||
const level = Number.parseInt(g1AsLevel, 10);
|
||||
|
||||
const mdSequence = node.attribs['data-md'];
|
||||
if (mdSequence !== undefined) {
|
||||
@@ -334,7 +334,7 @@ const parseHeadingNode = (
|
||||
|
||||
return {
|
||||
type: BlockType.Heading,
|
||||
level: (level <= 3 ? level : 3) as HeadingLevel,
|
||||
level: Math.min(level, 3) as HeadingLevel,
|
||||
children,
|
||||
};
|
||||
};
|
||||
|
||||
@@ -128,10 +128,13 @@ export const toMatrixCustomHTML = (
|
||||
|
||||
return `${parsedMarkdown}${toMatrixCustomHTML(n, { ...opts, allowBlockMarkdown: false })}`;
|
||||
};
|
||||
if (Array.isArray(node)) return node.map(parseNode).join('');
|
||||
if (Array.isArray(node))
|
||||
return node.map((element, index, array) => parseNode(element, index, array)).join('');
|
||||
if (Text.isText(node)) return textToCustomHtml(node, opts);
|
||||
|
||||
const children = node.children.map(parseNode).join('');
|
||||
const children = node.children
|
||||
.map((element, index, array) => parseNode(element, index, array))
|
||||
.join('');
|
||||
return elementToCustomHtml(node, children);
|
||||
};
|
||||
|
||||
@@ -193,14 +196,14 @@ export const toPlainText = (node: Descendant | Descendant[], isMarkdown: boolean
|
||||
* @returns boolean
|
||||
*/
|
||||
export const customHtmlEqualsPlainText = (customHtml: string, plain: string): boolean =>
|
||||
customHtml.replace(/<br\/>/g, '\n') === sanitizeText(plain);
|
||||
customHtml.replaceAll('<br/>', '\n') === sanitizeText(plain);
|
||||
|
||||
export const trimCustomHtml = (customHtml: string) => customHtml.replace(/<br\/>$/g, '').trim();
|
||||
export const trimCustomHtml = (customHtml: string) => customHtml.replaceAll(/<br\/>$/g, '').trim();
|
||||
|
||||
export const trimCommand = (cmdName: string, str: string) => {
|
||||
const cmdRegX = new RegExp(`^(\\s+)?(\\/${sanitizeForRegex(cmdName)})([^\\S\n]+)?`);
|
||||
|
||||
const match = str.match(cmdRegX);
|
||||
const match = new RegExp(cmdRegX).exec(str);
|
||||
if (!match) return str;
|
||||
return str.slice(match[0].length);
|
||||
};
|
||||
|
||||
@@ -179,7 +179,7 @@ function EmojiSidebar({
|
||||
packs,
|
||||
saveStickerEmojiBandwidth,
|
||||
onScrollToGroup,
|
||||
}: EmojiSidebarProps) {
|
||||
}: Readonly<EmojiSidebarProps>) {
|
||||
const mx = useMatrixClient();
|
||||
const useAuthentication = useMediaAuthentication();
|
||||
|
||||
@@ -264,7 +264,7 @@ function StickerSidebar({
|
||||
packs,
|
||||
saveStickerEmojiBandwidth,
|
||||
onScrollToGroup,
|
||||
}: StickerSidebarProps) {
|
||||
}: Readonly<StickerSidebarProps>) {
|
||||
const mx = useMatrixClient();
|
||||
const useAuthentication = useMediaAuthentication();
|
||||
|
||||
@@ -316,7 +316,7 @@ function EmojiGroupHolder({
|
||||
previewAtom,
|
||||
onGroupItemClick,
|
||||
children,
|
||||
}: EmojiGroupHolderProps) {
|
||||
}: Readonly<EmojiGroupHolderProps>) {
|
||||
const setPreviewData = useSetAtom(previewAtom);
|
||||
|
||||
const handleEmojiPreview = useCallback(
|
||||
@@ -397,7 +397,7 @@ export function EmojiBoard({
|
||||
onStickerSelect,
|
||||
allowTextCustomEmoji,
|
||||
addToRecentEmoji = true,
|
||||
}: EmojiBoardProps) {
|
||||
}: Readonly<EmojiBoardProps>) {
|
||||
const mx = useMatrixClient();
|
||||
const [saveStickerEmojiBandwidth] = useSetting(settingsAtom, 'saveStickerEmojiBandwidth');
|
||||
|
||||
@@ -589,7 +589,7 @@ export function EmojiBoard({
|
||||
id={SEARCH_GROUP_ID}
|
||||
label={searchedItems.length ? 'Search Results' : 'No Results found'}
|
||||
>
|
||||
{searchedItems.map(renderItem)}
|
||||
{searchedItems.map((element, index) => renderItem(element, index))}
|
||||
</EmojiGroup>
|
||||
)}
|
||||
<div
|
||||
|
||||
@@ -121,7 +121,7 @@ export const EventHistory = as<'div', EventHistoryProps>(
|
||||
[room, setReplyDraft]
|
||||
);
|
||||
|
||||
function MenuOptions({ mEvent }: { mEvent: MatrixEvent }) {
|
||||
function MenuOptions({ mEvent }: Readonly<{ mEvent: MatrixEvent }>) {
|
||||
const setModal = useSetAtom(modalAtom);
|
||||
return (
|
||||
<Menu className={css.MenuOptions}>
|
||||
@@ -177,7 +177,10 @@ export const EventHistory = as<'div', EventHistoryProps>(
|
||||
);
|
||||
}
|
||||
|
||||
function EventItem({ mEvent, EventContent }: { mEvent: MatrixEvent; EventContent: IContent }) {
|
||||
function EventItem({
|
||||
mEvent,
|
||||
EventContent,
|
||||
}: Readonly<{ mEvent: MatrixEvent; EventContent: IContent }>) {
|
||||
const [isHovered, setIsHovered] = useState(false);
|
||||
return (
|
||||
<Box
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
import { VideoHTMLAttributes, forwardRef } from 'react';
|
||||
import { VideoHTMLAttributes, forwardRef, useEffect, useRef } from 'react';
|
||||
import classNames from 'classnames';
|
||||
import * as css from './media.css';
|
||||
|
||||
@@ -8,3 +8,31 @@ export const Video = forwardRef<HTMLVideoElement, VideoHTMLAttributes<HTMLVideoE
|
||||
<video className={classNames(css.Video, className)} {...props} ref={ref} />
|
||||
)
|
||||
);
|
||||
|
||||
export const MEDIA_VOLUME_KEY = 'mediaVolume';
|
||||
|
||||
export function PersistedVolumeVideo({
|
||||
onVolumeChange,
|
||||
...props
|
||||
}: VideoHTMLAttributes<HTMLVideoElement>) {
|
||||
const innerRef = useRef<HTMLVideoElement>(null);
|
||||
|
||||
useEffect(() => {
|
||||
const stored = localStorage.getItem(MEDIA_VOLUME_KEY);
|
||||
if (innerRef.current && stored !== null) {
|
||||
const parsed = parseFloat(stored);
|
||||
if (!Number.isNaN(parsed)) innerRef.current.volume = parsed;
|
||||
}
|
||||
}, []);
|
||||
|
||||
return (
|
||||
<Video
|
||||
{...props}
|
||||
ref={innerRef}
|
||||
onVolumeChange={(e) => {
|
||||
localStorage.setItem(MEDIA_VOLUME_KEY, String((e.target as HTMLVideoElement).volume));
|
||||
onVolumeChange?.(e);
|
||||
}}
|
||||
/>
|
||||
);
|
||||
}
|
||||
@@ -19,7 +19,7 @@ export function RenderBody({
|
||||
highlightRegex,
|
||||
htmlReactParserOptions,
|
||||
linkifyOpts,
|
||||
}: RenderBodyProps) {
|
||||
}: Readonly<RenderBodyProps>) {
|
||||
if (body === '') return <MessageEmptyContent />;
|
||||
if (customBody) {
|
||||
if (customBody === '') return <MessageEmptyContent />;
|
||||
|
||||
@@ -68,10 +68,10 @@ export const ThreadIndicator = as<'div'>(({ ...props }, ref) => (
|
||||
|
||||
type ReplyProps = {
|
||||
room: Room;
|
||||
timelineSet?: EventTimelineSet | undefined;
|
||||
timelineSet?: EventTimelineSet;
|
||||
replyEventId: string;
|
||||
threadRootId?: string | undefined;
|
||||
onClick?: MouseEventHandler | undefined;
|
||||
threadRootId?: string;
|
||||
onClick?: MouseEventHandler;
|
||||
};
|
||||
|
||||
export const Reply = as<'div', ReplyProps>(
|
||||
@@ -119,10 +119,10 @@ export const Reply = as<'div', ReplyProps>(
|
||||
|
||||
if (format === 'org.matrix.custom.html' && formattedBody) {
|
||||
const strippedHtml = trimReplyFromFormattedBody(formattedBody)
|
||||
.replace(/<br\s*\/?>/gi, ' ')
|
||||
.replace(/<\/p>\s*<p[^>]*>/gi, ' ')
|
||||
.replace(/<\/?p[^>]*>/gi, '')
|
||||
.replace(/(?:\r\n|\r|\n)/g, ' ');
|
||||
.replaceAll(/<br\s*\/?>/gi, ' ')
|
||||
.replaceAll(/<\/p>\s*<p[^>]*>/gi, ' ')
|
||||
.replaceAll(/<\/?p[^>]*>/gi, '')
|
||||
.replaceAll(/(?:\r\n|\r|\n)/g, ' ');
|
||||
const parserOpts = getReactCustomHtmlParser(mx, room.roomId, {
|
||||
linkifyOpts: LINKIFY_OPTS,
|
||||
useAuthentication,
|
||||
@@ -130,7 +130,7 @@ export const Reply = as<'div', ReplyProps>(
|
||||
});
|
||||
bodyJSX = parse(strippedHtml, parserOpts) as JSX.Element;
|
||||
} else if (body) {
|
||||
const strippedBody = trimReplyFromBody(body).replace(/(?:\r\n|\r|\n)/g, ' ');
|
||||
const strippedBody = trimReplyFromBody(body).replaceAll(/(?:\r\n|\r|\n)/g, ' ');
|
||||
bodyJSX = scaleSystemEmoji(strippedBody);
|
||||
}
|
||||
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
/* eslint-disable jsx-a11y/media-has-caption */
|
||||
import { ReactNode, useCallback, useRef, useState } from 'react';
|
||||
import { ReactNode, useCallback, useEffect, useRef, useState } from 'react';
|
||||
import { Badge, Chip, Icon, IconButton, Icons, ProgressBar, Spinner, Text, toRem } from 'folds';
|
||||
import { EncryptedAttachmentInfo } from 'browser-encrypt-attachment';
|
||||
import { Range } from 'react-range';
|
||||
@@ -18,6 +18,7 @@ import { useThrottle } from '$hooks/useThrottle';
|
||||
import { secondsToMinutesAndSeconds } from '$utils/common';
|
||||
import { decryptFile, downloadEncryptedMedia, downloadMedia, mxcUrlToHttp } from '$utils/matrix';
|
||||
import { useMediaAuthentication } from '$hooks/useMediaAuthentication';
|
||||
import { MEDIA_VOLUME_KEY } from '$components/media';
|
||||
|
||||
const PLAY_TIME_THROTTLE_OPS = {
|
||||
wait: 500,
|
||||
@@ -60,6 +61,14 @@ export function AudioContent({
|
||||
|
||||
const audioRef = useRef<HTMLAudioElement | null>(null);
|
||||
|
||||
useEffect(() => {
|
||||
const stored = localStorage.getItem(MEDIA_VOLUME_KEY);
|
||||
if (audioRef.current && stored !== null) {
|
||||
const parsed = parseFloat(stored);
|
||||
if (!Number.isNaN(parsed)) audioRef.current.volume = parsed;
|
||||
}
|
||||
}, []);
|
||||
|
||||
const [currentTime, setCurrentTime] = useState(0);
|
||||
// duration in seconds. (NOTE: info.duration is in milliseconds)
|
||||
const infoDuration = info.duration ?? 0;
|
||||
@@ -197,7 +206,14 @@ export function AudioContent({
|
||||
</>
|
||||
),
|
||||
children: (
|
||||
<audio controls={false} autoPlay ref={audioRef}>
|
||||
<audio
|
||||
controls={false}
|
||||
autoPlay
|
||||
ref={audioRef}
|
||||
onVolumeChange={(e) => {
|
||||
localStorage.setItem(MEDIA_VOLUME_KEY, String((e.target as HTMLAudioElement).volume));
|
||||
}}
|
||||
>
|
||||
{srcState.status === AsyncStatus.Success && <source src={srcState.data} type={mimeType} />}
|
||||
</audio>
|
||||
),
|
||||
|
||||
@@ -6,6 +6,8 @@ import {
|
||||
Chip,
|
||||
Icon,
|
||||
Icons,
|
||||
Menu,
|
||||
MenuItem,
|
||||
Modal,
|
||||
Overlay,
|
||||
OverlayBackdrop,
|
||||
@@ -15,6 +17,7 @@ import {
|
||||
Tooltip,
|
||||
TooltipProvider,
|
||||
as,
|
||||
config,
|
||||
} from 'folds';
|
||||
import classNames from 'classnames';
|
||||
import { BlurhashCanvas } from 'react-blurhash';
|
||||
@@ -84,6 +87,7 @@ export const ImageContent = as<'div', ImageContentProps>(
|
||||
const [error, setError] = useState(false);
|
||||
const [viewer, setViewer] = useState(false);
|
||||
const [blurred, setBlurred] = useState(markedAsSpoiler ?? false);
|
||||
const [isHovered, setIsHovered] = useState(false);
|
||||
|
||||
const [srcState, loadSrc] = useAsyncCallback(
|
||||
useCallback(async () => {
|
||||
@@ -119,7 +123,13 @@ export const ImageContent = as<'div', ImageContentProps>(
|
||||
}, [autoPlay, loadSrc]);
|
||||
|
||||
return (
|
||||
<Box className={classNames(css.RelativeBase, className)} {...props} ref={ref}>
|
||||
<Box
|
||||
className={classNames(css.RelativeBase, className)}
|
||||
{...props}
|
||||
ref={ref}
|
||||
onPointerEnter={() => setIsHovered(true)}
|
||||
onPointerLeave={() => setIsHovered(false)}
|
||||
>
|
||||
{srcState.status === AsyncStatus.Success && (
|
||||
<Overlay open={viewer} backdrop={<OverlayBackdrop />}>
|
||||
<OverlayCenter>
|
||||
@@ -156,7 +166,12 @@ export const ImageContent = as<'div', ImageContentProps>(
|
||||
/>
|
||||
)}
|
||||
{!autoPlay && !markedAsSpoiler && srcState.status === AsyncStatus.Idle && (
|
||||
<Box className={css.AbsoluteContainer} alignItems="Center" justifyContent="Center">
|
||||
<Box
|
||||
className={css.AbsoluteContainer}
|
||||
alignItems="Center"
|
||||
justifyContent="Center"
|
||||
onClick={loadSrc}
|
||||
>
|
||||
<Button
|
||||
variant="Secondary"
|
||||
fill="Solid"
|
||||
@@ -183,36 +198,35 @@ export const ImageContent = as<'div', ImageContentProps>(
|
||||
</Box>
|
||||
)}
|
||||
{blurred && !error && srcState.status !== AsyncStatus.Error && (
|
||||
<Box className={css.AbsoluteContainer} alignItems="Center" justifyContent="Center">
|
||||
<TooltipProvider
|
||||
tooltip={
|
||||
typeof spoilerReason === 'string' && (
|
||||
<Tooltip variant="Secondary">
|
||||
<Text>{spoilerReason}</Text>
|
||||
</Tooltip>
|
||||
)
|
||||
<Box
|
||||
className={css.AbsoluteContainer}
|
||||
alignItems="Center"
|
||||
justifyContent="Center"
|
||||
onClick={() => {
|
||||
setBlurred(false);
|
||||
if (srcState.status === AsyncStatus.Idle) {
|
||||
loadSrc();
|
||||
}
|
||||
position="Top"
|
||||
align="Center"
|
||||
}}
|
||||
>
|
||||
<Chip
|
||||
variant="Secondary"
|
||||
radii="Pill"
|
||||
size="500"
|
||||
outlined
|
||||
onClick={() => {
|
||||
setBlurred(false);
|
||||
if (srcState.status === AsyncStatus.Idle) {
|
||||
loadSrc();
|
||||
}
|
||||
}}
|
||||
>
|
||||
{(triggerRef) => (
|
||||
<Chip
|
||||
ref={triggerRef}
|
||||
variant="Secondary"
|
||||
radii="Pill"
|
||||
size="500"
|
||||
outlined
|
||||
onClick={() => {
|
||||
setBlurred(false);
|
||||
if (srcState.status === AsyncStatus.Idle) {
|
||||
loadSrc();
|
||||
}
|
||||
}}
|
||||
>
|
||||
<Text size="B300">Spoiler</Text>
|
||||
</Chip>
|
||||
)}
|
||||
</TooltipProvider>
|
||||
<Text size="B300">
|
||||
{typeof spoilerReason === 'string' && spoilerReason.length > 0
|
||||
? `Spoiler reason: ${spoilerReason}`
|
||||
: `Spoilered`}
|
||||
</Text>
|
||||
</Chip>
|
||||
</Box>
|
||||
)}
|
||||
{(srcState.status === AsyncStatus.Loading || srcState.status === AsyncStatus.Success) &&
|
||||
@@ -223,7 +237,12 @@ export const ImageContent = as<'div', ImageContentProps>(
|
||||
</Box>
|
||||
)}
|
||||
{(error || srcState.status === AsyncStatus.Error) && (
|
||||
<Box className={css.AbsoluteContainer} alignItems="Center" justifyContent="Center">
|
||||
<Box
|
||||
className={css.AbsoluteContainer}
|
||||
alignItems="Center"
|
||||
justifyContent="Center"
|
||||
onClick={handleRetry}
|
||||
>
|
||||
<TooltipProvider
|
||||
tooltip={
|
||||
<Tooltip variant="Critical">
|
||||
@@ -250,6 +269,27 @@ export const ImageContent = as<'div', ImageContentProps>(
|
||||
</TooltipProvider>
|
||||
</Box>
|
||||
)}
|
||||
{isHovered && (
|
||||
<Box style={{ padding: config.space.S200, right: 0, position: 'absolute' }}>
|
||||
<Menu style={{ padding: config.space.S0 }}>
|
||||
<MenuItem
|
||||
size="300"
|
||||
after={<Icon size="200" src={blurred ? Icons.Eye : Icons.EyeBlind} />}
|
||||
radii="300"
|
||||
fill="Soft"
|
||||
variant="Secondary"
|
||||
title={blurred ? 'Reveal Image' : 'Hide Image'}
|
||||
onClick={(e) => {
|
||||
e.preventDefault();
|
||||
if (srcState.status === AsyncStatus.Idle) {
|
||||
loadSrc();
|
||||
setBlurred(false);
|
||||
} else setBlurred(!blurred);
|
||||
}}
|
||||
/>
|
||||
</Menu>
|
||||
</Box>
|
||||
)}
|
||||
{!load && typeof info?.size === 'number' && (
|
||||
<Box className={css.AbsoluteFooter} justifyContent="End" alignContent="Center" gap="200">
|
||||
<Badge variant="Secondary" fill="Soft">
|
||||
|
||||
@@ -6,11 +6,14 @@ import {
|
||||
Chip,
|
||||
Icon,
|
||||
Icons,
|
||||
Menu,
|
||||
MenuItem,
|
||||
Spinner,
|
||||
Text,
|
||||
Tooltip,
|
||||
TooltipProvider,
|
||||
as,
|
||||
config,
|
||||
} from 'folds';
|
||||
import classNames from 'classnames';
|
||||
import { BlurhashCanvas } from 'react-blurhash';
|
||||
@@ -73,6 +76,7 @@ export const VideoContent = as<'div', VideoContentProps>(
|
||||
const [load, setLoad] = useState(false);
|
||||
const [error, setError] = useState(false);
|
||||
const [blurred, setBlurred] = useState(markedAsSpoiler ?? false);
|
||||
const [isHovered, setIsHovered] = useState(false);
|
||||
|
||||
const [srcState, loadSrc] = useAsyncCallback(
|
||||
useCallback(async () => {
|
||||
@@ -107,7 +111,13 @@ export const VideoContent = as<'div', VideoContentProps>(
|
||||
}, [autoPlay, loadSrc]);
|
||||
|
||||
return (
|
||||
<Box className={classNames(css.RelativeBase, className)} {...props} ref={ref}>
|
||||
<Box
|
||||
className={classNames(css.RelativeBase, className)}
|
||||
{...props}
|
||||
ref={ref}
|
||||
onPointerEnter={() => setIsHovered(true)}
|
||||
onPointerLeave={() => setIsHovered(false)}
|
||||
>
|
||||
{typeof blurHash === 'string' && !load && (
|
||||
<BlurhashCanvas
|
||||
style={{ width: '100%', height: '100%' }}
|
||||
@@ -127,7 +137,12 @@ export const VideoContent = as<'div', VideoContentProps>(
|
||||
</Box>
|
||||
)}
|
||||
{!autoPlay && !blurred && srcState.status === AsyncStatus.Idle && (
|
||||
<Box className={css.AbsoluteContainer} alignItems="Center" justifyContent="Center">
|
||||
<Box
|
||||
className={css.AbsoluteContainer}
|
||||
alignItems="Center"
|
||||
justifyContent="Center"
|
||||
onClick={loadSrc}
|
||||
>
|
||||
<Button
|
||||
variant="Secondary"
|
||||
fill="Solid"
|
||||
@@ -147,39 +162,41 @@ export const VideoContent = as<'div', VideoContentProps>(
|
||||
src: srcState.data,
|
||||
onLoadedMetadata: handleLoad,
|
||||
onError: handleError,
|
||||
autoPlay: true,
|
||||
autoPlay: false,
|
||||
controls: true,
|
||||
})}
|
||||
</Box>
|
||||
)}
|
||||
{blurred && !error && srcState.status !== AsyncStatus.Error && (
|
||||
<Box className={css.AbsoluteContainer} alignItems="Center" justifyContent="Center">
|
||||
<TooltipProvider
|
||||
tooltip={
|
||||
typeof spoilerReason === 'string' && (
|
||||
<Tooltip variant="Secondary">
|
||||
<Text>{spoilerReason}</Text>
|
||||
</Tooltip>
|
||||
)
|
||||
<Box
|
||||
className={css.AbsoluteContainer}
|
||||
alignItems="Center"
|
||||
justifyContent="Center"
|
||||
onClick={() => {
|
||||
setBlurred(false);
|
||||
if (srcState.status === AsyncStatus.Idle) {
|
||||
loadSrc();
|
||||
}
|
||||
position="Top"
|
||||
align="Center"
|
||||
}}
|
||||
>
|
||||
<Chip
|
||||
variant="Secondary"
|
||||
radii="Pill"
|
||||
size="500"
|
||||
outlined
|
||||
onClick={() => {
|
||||
setBlurred(false);
|
||||
if (srcState.status === AsyncStatus.Idle) {
|
||||
loadSrc();
|
||||
}
|
||||
}}
|
||||
>
|
||||
{(triggerRef) => (
|
||||
<Chip
|
||||
ref={triggerRef}
|
||||
variant="Secondary"
|
||||
radii="Pill"
|
||||
size="500"
|
||||
outlined
|
||||
onClick={() => {
|
||||
setBlurred(false);
|
||||
}}
|
||||
>
|
||||
<Text size="B300">Spoiler</Text>
|
||||
</Chip>
|
||||
)}
|
||||
</TooltipProvider>
|
||||
<Text size="B300">
|
||||
{typeof spoilerReason === 'string' && spoilerReason.length > 0
|
||||
? `Spoiler reason: ${spoilerReason}`
|
||||
: `Spoilered`}
|
||||
</Text>
|
||||
</Chip>
|
||||
</Box>
|
||||
)}
|
||||
{(srcState.status === AsyncStatus.Loading || srcState.status === AsyncStatus.Success) &&
|
||||
@@ -190,7 +207,12 @@ export const VideoContent = as<'div', VideoContentProps>(
|
||||
</Box>
|
||||
)}
|
||||
{(error || srcState.status === AsyncStatus.Error) && (
|
||||
<Box className={css.AbsoluteContainer} alignItems="Center" justifyContent="Center">
|
||||
<Box
|
||||
className={css.AbsoluteContainer}
|
||||
alignItems="Center"
|
||||
justifyContent="Center"
|
||||
onClick={handleRetry}
|
||||
>
|
||||
<TooltipProvider
|
||||
tooltip={
|
||||
<Tooltip variant="Critical">
|
||||
@@ -217,6 +239,27 @@ export const VideoContent = as<'div', VideoContentProps>(
|
||||
</TooltipProvider>
|
||||
</Box>
|
||||
)}
|
||||
{isHovered && (
|
||||
<Box style={{ padding: config.space.S200, right: 0, position: 'absolute' }}>
|
||||
<Menu style={{ padding: config.space.S0 }}>
|
||||
<MenuItem
|
||||
size="300"
|
||||
after={<Icon size="200" src={blurred ? Icons.Eye : Icons.EyeBlind} />}
|
||||
radii="300"
|
||||
fill="Soft"
|
||||
variant="Secondary"
|
||||
title={blurred ? 'Reveal Video' : 'Hide Video'}
|
||||
onClick={(e) => {
|
||||
e.preventDefault();
|
||||
if (srcState.status === AsyncStatus.Idle) {
|
||||
loadSrc();
|
||||
setBlurred(false);
|
||||
} else setBlurred(!blurred);
|
||||
}}
|
||||
/>
|
||||
</Menu>
|
||||
</Box>
|
||||
)}
|
||||
{!load && typeof info.size === 'number' && (
|
||||
<Box
|
||||
className={css.AbsoluteFooter}
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
import { AvatarImage as FoldsAvatarImage } from 'folds';
|
||||
import { ReactEventHandler, useState } from 'react';
|
||||
import { ReactEventHandler, useState, useEffect } from 'react';
|
||||
import bgColorImg from '$utils/bgColorImg';
|
||||
import { settingsAtom } from '$state/settings';
|
||||
import { useSetting } from '$state/hooks/settings';
|
||||
@@ -15,20 +15,67 @@ type AvatarImageProps = {
|
||||
export function AvatarImage({ src, alt, uniformIcons, onError }: AvatarImageProps) {
|
||||
const [uniformIconsSetting] = useSetting(settingsAtom, 'uniformIcons');
|
||||
const [image, setImage] = useState<HTMLImageElement | undefined>(undefined);
|
||||
const normalizedBg = image ? bgColorImg(image) : undefined;
|
||||
const [processedSrc, setProcessedSrc] = useState<string>(src);
|
||||
|
||||
const useUniformIcons = uniformIconsSetting && uniformIcons === true;
|
||||
const normalizedBg = useUniformIcons && image ? bgColorImg(image) : undefined;
|
||||
|
||||
useEffect(() => {
|
||||
let isMounted = true;
|
||||
let objectUrl: string | null = null;
|
||||
|
||||
const processImage = async () => {
|
||||
try {
|
||||
const res = await fetch(src, { mode: 'cors' });
|
||||
const contentType = res.headers.get('content-type');
|
||||
|
||||
if (contentType && contentType.includes('image/svg+xml')) {
|
||||
const text = await res.text();
|
||||
const parser = new DOMParser();
|
||||
const doc = parser.parseFromString(text, 'image/svg+xml');
|
||||
|
||||
const animations = doc.querySelectorAll('animate, animateTransform, animateMotion');
|
||||
animations.forEach((anim) => anim.setAttribute('repeatCount', 'indefinite'));
|
||||
|
||||
const style = doc.createElementNS('http://www.w3.org/2000/svg', 'style');
|
||||
style.textContent = '* { animation-iteration-count: infinite !important; }';
|
||||
doc.documentElement.appendChild(style);
|
||||
|
||||
const serializer = new XMLSerializer();
|
||||
const newSvgString = serializer.serializeToString(doc);
|
||||
const blob = new Blob([newSvgString], { type: 'image/svg+xml' });
|
||||
|
||||
objectUrl = URL.createObjectURL(blob);
|
||||
if (isMounted) setProcessedSrc(objectUrl);
|
||||
} else if (isMounted) setProcessedSrc(src);
|
||||
} catch {
|
||||
if (isMounted) setProcessedSrc(src);
|
||||
}
|
||||
};
|
||||
|
||||
processImage();
|
||||
|
||||
return () => {
|
||||
isMounted = false;
|
||||
if (objectUrl) {
|
||||
URL.revokeObjectURL(objectUrl);
|
||||
}
|
||||
};
|
||||
}, [src]);
|
||||
|
||||
const handleLoad: ReactEventHandler<HTMLImageElement> = (evt) => {
|
||||
evt.currentTarget.setAttribute('data-image-loaded', 'true');
|
||||
setImage(evt.currentTarget);
|
||||
};
|
||||
|
||||
const isBlobUrl = processedSrc.startsWith('blob:');
|
||||
|
||||
return (
|
||||
<FoldsAvatarImage
|
||||
className={css.RoomAvatar}
|
||||
style={{ backgroundColor: useUniformIcons ? normalizedBg : undefined }}
|
||||
src={src}
|
||||
crossOrigin="anonymous"
|
||||
src={processedSrc}
|
||||
crossOrigin={isBlobUrl ? undefined : 'anonymous'}
|
||||
alt={alt}
|
||||
onError={() => {
|
||||
setImage(undefined);
|
||||
|
||||
@@ -134,8 +134,8 @@ export const SidebarItemBadge = recipe({
|
||||
left: toRem(-6),
|
||||
},
|
||||
false: {
|
||||
top: toRem(-2),
|
||||
left: toRem(-2),
|
||||
top: toRem(-4),
|
||||
left: toRem(-4),
|
||||
},
|
||||
},
|
||||
},
|
||||
@@ -167,9 +167,9 @@ export const SidebarItemBadge = recipe({
|
||||
style: {
|
||||
selectors: {
|
||||
'div:has(> button[data-id]) &': {
|
||||
top: toRem(2),
|
||||
top: toRem(0),
|
||||
left: 'auto',
|
||||
right: toRem(2),
|
||||
right: toRem(0),
|
||||
},
|
||||
},
|
||||
},
|
||||
|
||||
@@ -33,7 +33,7 @@ export const DatePicker = forwardRef<HTMLDivElement, DatePickerProps>(
|
||||
const currentDate = dateFor(selectedYear, selectedMonth, selectedDay);
|
||||
const time = value - currentDate;
|
||||
|
||||
const newDate = dateFor(year, month, mDays < selectedDay ? mDays : selectedDay);
|
||||
const newDate = dateFor(year, month, Math.min(mDays, selectedDay));
|
||||
|
||||
const newValue = newDate + time;
|
||||
handleSubmit(newValue);
|
||||
@@ -60,7 +60,7 @@ export const DatePicker = forwardRef<HTMLDivElement, DatePickerProps>(
|
||||
<Menu className={css.PickerMenu} ref={ref}>
|
||||
<Box direction="Row" gap="200" className={css.PickerContainer}>
|
||||
<PickerColumn title="Day">
|
||||
{Array.from(Array(daysInMonth(selectedMonth, selectedYear)).keys())
|
||||
{Array.from(new Array(daysInMonth(selectedMonth, selectedYear)).keys())
|
||||
.map((i) => i + 1)
|
||||
.map((day) => (
|
||||
<Chip
|
||||
@@ -81,7 +81,7 @@ export const DatePicker = forwardRef<HTMLDivElement, DatePickerProps>(
|
||||
))}
|
||||
</PickerColumn>
|
||||
<PickerColumn title="Month">
|
||||
{Array.from(Array(12).keys())
|
||||
{Array.from(new Array(12).keys())
|
||||
.map((i) => i + 1)
|
||||
.map((month) => (
|
||||
<Chip
|
||||
@@ -106,7 +106,7 @@ export const DatePicker = forwardRef<HTMLDivElement, DatePickerProps>(
|
||||
))}
|
||||
</PickerColumn>
|
||||
<PickerColumn title="Year">
|
||||
{Array.from(Array(yearsRange).keys())
|
||||
{Array.from(new Array(yearsRange).keys())
|
||||
.map((i) => minYear + i)
|
||||
.map((year) => (
|
||||
<Chip
|
||||
|
||||
@@ -64,7 +64,7 @@ export const TimePicker = forwardRef<HTMLDivElement, TimePickerProps>(
|
||||
<Box direction="Row" gap="200" className={css.PickerContainer}>
|
||||
<PickerColumn title="Hour">
|
||||
{hour24Clock
|
||||
? Array.from(Array(24).keys()).map((hour) => (
|
||||
? Array.from(new Array(24).keys()).map((hour) => (
|
||||
<Chip
|
||||
key={hour}
|
||||
size="500"
|
||||
@@ -78,7 +78,7 @@ export const TimePicker = forwardRef<HTMLDivElement, TimePickerProps>(
|
||||
<Text size="T300">{hour < 10 ? `0${hour}` : hour}</Text>
|
||||
</Chip>
|
||||
))
|
||||
: Array.from(Array(12).keys())
|
||||
: Array.from(new Array(12).keys())
|
||||
.map((i) => {
|
||||
if (i === 0) return 12;
|
||||
return i;
|
||||
@@ -102,7 +102,7 @@ export const TimePicker = forwardRef<HTMLDivElement, TimePickerProps>(
|
||||
))}
|
||||
</PickerColumn>
|
||||
<PickerColumn title="Minutes">
|
||||
{Array.from(Array(60).keys()).map((minute) => (
|
||||
{Array.from(new Array(60).keys()).map((minute) => (
|
||||
<Chip
|
||||
key={minute}
|
||||
size="500"
|
||||
@@ -124,7 +124,7 @@ export const TimePicker = forwardRef<HTMLDivElement, TimePickerProps>(
|
||||
<PickerColumn title="Period">
|
||||
<Chip
|
||||
size="500"
|
||||
variant={!selectedPM ? 'Primary' : 'SurfaceVariant'}
|
||||
variant={selectedPM ? 'SurfaceVariant' : 'Primary'}
|
||||
fill="None"
|
||||
radii="300"
|
||||
aria-selected={!selectedPM}
|
||||
|
||||
@@ -32,7 +32,7 @@ import { DescriptionEditor } from './UploadDescriptionEditor';
|
||||
type PreviewImageProps = {
|
||||
fileItem: TUploadItem;
|
||||
};
|
||||
function PreviewImage({ fileItem }: PreviewImageProps) {
|
||||
function PreviewImage({ fileItem }: Readonly<PreviewImageProps>) {
|
||||
const { originalFile, metadata } = fileItem;
|
||||
const fileUrl = useObjectURL(originalFile);
|
||||
|
||||
@@ -53,7 +53,7 @@ function PreviewImage({ fileItem }: PreviewImageProps) {
|
||||
type PreviewVideoProps = {
|
||||
fileItem: TUploadItem;
|
||||
};
|
||||
function PreviewVideo({ fileItem }: PreviewVideoProps) {
|
||||
function PreviewVideo({ fileItem }: Readonly<PreviewVideoProps>) {
|
||||
const { originalFile, metadata } = fileItem;
|
||||
const fileUrl = useObjectURL(originalFile);
|
||||
|
||||
@@ -131,7 +131,7 @@ export function UploadCardRenderer({
|
||||
onRemove,
|
||||
onComplete,
|
||||
roomId,
|
||||
}: UploadCardRendererProps) {
|
||||
}: Readonly<UploadCardRendererProps>) {
|
||||
const mx = useMatrixClient();
|
||||
const mediaConfig = useMediaConfig();
|
||||
const allowSize = mediaConfig['m.upload.size'] || Infinity;
|
||||
|
||||
@@ -53,7 +53,7 @@ export function DescriptionEditor({
|
||||
imagePackRooms,
|
||||
onSave,
|
||||
onCancel,
|
||||
}: DescriptionEditorProps) {
|
||||
}: Readonly<DescriptionEditorProps>) {
|
||||
const editor = useEditor();
|
||||
const [enterForNewline] = useSetting(settingsAtom, 'enterForNewline');
|
||||
const [isMarkdown] = useSetting(settingsAtom, 'isMarkdown');
|
||||
|
||||
@@ -3,10 +3,6 @@ import { IPreviewUrlResponse } from '$types/matrix-sdk';
|
||||
import { Box, Icon, IconButton, Icons, Scroll, Spinner, Text, as, color, config } from 'folds';
|
||||
import { AsyncStatus, useAsyncCallback } from '$hooks/useAsyncCallback';
|
||||
import { useMatrixClient } from '$hooks/useMatrixClient';
|
||||
import {
|
||||
getIntersectionObserverEntry,
|
||||
useIntersectionObserver,
|
||||
} from '$hooks/useIntersectionObserver';
|
||||
import { mxcUrlToHttp, downloadMedia } from '$utils/matrix';
|
||||
import { useMediaAuthentication } from '$hooks/useMediaAuthentication';
|
||||
import * as css from './UrlPreviewCard.css';
|
||||
@@ -242,43 +238,34 @@ export const UrlPreviewCard = as<'div', { url: string; ts: number; mediaType?: s
|
||||
|
||||
export const UrlPreviewHolder = as<'div'>(({ children, ...props }, ref) => {
|
||||
const scrollRef = useRef<HTMLDivElement>(null);
|
||||
const backAnchorRef = useRef<HTMLDivElement>(null);
|
||||
const frontAnchorRef = useRef<HTMLDivElement>(null);
|
||||
const [backVisible, setBackVisible] = useState(true);
|
||||
const [frontVisible, setFrontVisible] = useState(true);
|
||||
const innerBoxRef = useRef<HTMLDivElement>(null);
|
||||
const [canScrollLeft, setCanScrollLeft] = useState(false);
|
||||
const [canScrollRight, setCanScrollRight] = useState(false);
|
||||
|
||||
const intersectionObserver = useIntersectionObserver(
|
||||
useCallback((entries) => {
|
||||
const backAnchor = backAnchorRef.current;
|
||||
const frontAnchor = frontAnchorRef.current;
|
||||
const backEntry = backAnchor && getIntersectionObserverEntry(backAnchor, entries);
|
||||
const frontEntry = frontAnchor && getIntersectionObserverEntry(frontAnchor, entries);
|
||||
if (backEntry) {
|
||||
setBackVisible(backEntry.isIntersecting);
|
||||
}
|
||||
if (frontEntry) {
|
||||
setFrontVisible(frontEntry.isIntersecting);
|
||||
}
|
||||
}, []),
|
||||
useCallback(
|
||||
() => ({
|
||||
root: scrollRef.current,
|
||||
rootMargin: '10px',
|
||||
}),
|
||||
[]
|
||||
)
|
||||
);
|
||||
const updateArrows = useCallback(() => {
|
||||
const scroll = scrollRef.current;
|
||||
if (!scroll) return;
|
||||
const { scrollLeft, scrollWidth, clientWidth } = scroll;
|
||||
setCanScrollLeft(scrollLeft > 1);
|
||||
setCanScrollRight(scrollLeft + clientWidth < scrollWidth - 1);
|
||||
}, []);
|
||||
|
||||
useEffect(() => {
|
||||
const backAnchor = backAnchorRef.current;
|
||||
const frontAnchor = frontAnchorRef.current;
|
||||
if (backAnchor) intersectionObserver?.observe(backAnchor);
|
||||
if (frontAnchor) intersectionObserver?.observe(frontAnchor);
|
||||
const scroll = scrollRef.current;
|
||||
if (!scroll) return undefined;
|
||||
|
||||
updateArrows();
|
||||
scroll.addEventListener('scroll', updateArrows, { passive: true });
|
||||
|
||||
const resizeObserver = new ResizeObserver(updateArrows);
|
||||
resizeObserver.observe(scroll);
|
||||
if (innerBoxRef.current) resizeObserver.observe(innerBoxRef.current);
|
||||
|
||||
return () => {
|
||||
if (backAnchor) intersectionObserver?.unobserve(backAnchor);
|
||||
if (frontAnchor) intersectionObserver?.unobserve(frontAnchor);
|
||||
scroll.removeEventListener('scroll', updateArrows);
|
||||
resizeObserver.disconnect();
|
||||
};
|
||||
}, [intersectionObserver]);
|
||||
}, [updateArrows]);
|
||||
|
||||
const handleScrollBack = () => {
|
||||
const scroll = scrollRef.current;
|
||||
@@ -308,8 +295,7 @@ export const UrlPreviewHolder = as<'div'>(({ children, ...props }, ref) => {
|
||||
>
|
||||
<Scroll ref={scrollRef} direction="Horizontal" size="0" visibility="Hover" hideTrack>
|
||||
<Box shrink="No" alignItems="Center">
|
||||
<div ref={backAnchorRef} />
|
||||
{!backVisible && (
|
||||
{canScrollLeft && (
|
||||
<>
|
||||
<div className={css.UrlPreviewHolderGradient({ position: 'Left' })} />
|
||||
<IconButton
|
||||
@@ -324,10 +310,9 @@ export const UrlPreviewHolder = as<'div'>(({ children, ...props }, ref) => {
|
||||
</IconButton>
|
||||
</>
|
||||
)}
|
||||
<Box alignItems="Inherit" gap="200">
|
||||
<Box ref={innerBoxRef} alignItems="Inherit" gap="200">
|
||||
{children}
|
||||
|
||||
{!frontVisible && (
|
||||
{canScrollRight && (
|
||||
<>
|
||||
<div className={css.UrlPreviewHolderGradient({ position: 'Right' })} />
|
||||
<IconButton
|
||||
@@ -342,7 +327,6 @@ export const UrlPreviewHolder = as<'div'>(({ children, ...props }, ref) => {
|
||||
</IconButton>
|
||||
</>
|
||||
)}
|
||||
<div ref={frontAnchorRef} />
|
||||
</Box>
|
||||
</Box>
|
||||
</Scroll>
|
||||
|
||||
@@ -65,7 +65,7 @@ function UserExtendedSection({
|
||||
profile,
|
||||
htmlReactParserOptions,
|
||||
linkifyOpts,
|
||||
}: UserExtendedSectionProps) {
|
||||
}: Readonly<UserExtendedSectionProps>) {
|
||||
const clamp = (str: any, len: number) => {
|
||||
const stringified = String(str ?? '');
|
||||
return stringified.length > len ? `${stringified.slice(0, len)}...` : stringified;
|
||||
@@ -108,7 +108,7 @@ function UserExtendedSection({
|
||||
return new Intl.DateTimeFormat([], {
|
||||
hour: 'numeric',
|
||||
minute: '2-digit',
|
||||
timeZone: profile.timezone.replace(/^["']|["']$/g, ''),
|
||||
timeZone: profile.timezone.replaceAll(/^["']|["']$/g, ''),
|
||||
}).format(new Date());
|
||||
} catch {
|
||||
return null;
|
||||
@@ -133,7 +133,7 @@ function UserExtendedSection({
|
||||
|
||||
const safetyTrim = rawBio.length > 2048 ? rawBio.slice(0, 2048) : rawBio;
|
||||
|
||||
const visibleText = safetyTrim.replace(/<[^>]*>?/gm, '');
|
||||
const visibleText = safetyTrim.replaceAll(/<[^>]*>?/gm, '');
|
||||
const VISIBLE_LIMIT = 1024;
|
||||
|
||||
if (visibleText.length <= VISIBLE_LIMIT) {
|
||||
@@ -163,7 +163,7 @@ function UserExtendedSection({
|
||||
<Box alignItems="Center" gap="100">
|
||||
<Icon size="50" src={Icons.Clock} style={{ opacity: 0.5 }} />
|
||||
<Text size="T200" priority="400">
|
||||
{localTime} ({profile.timezone.replace(/^["']|["']$/g, '')})
|
||||
{localTime} ({profile.timezone.replaceAll(/^["']|["']$/g, '')})
|
||||
</Text>
|
||||
</Box>
|
||||
)}
|
||||
@@ -252,7 +252,7 @@ type UserRoomProfileProps = {
|
||||
userId: string;
|
||||
initialProfile?: Partial<UserProfile>;
|
||||
};
|
||||
export function UserRoomProfile({ userId, initialProfile }: UserRoomProfileProps) {
|
||||
export function UserRoomProfile({ userId, initialProfile }: Readonly<UserRoomProfileProps>) {
|
||||
const mx = useMatrixClient();
|
||||
const useAuthentication = useMediaAuthentication();
|
||||
const navigate = useNavigate();
|
||||
@@ -296,7 +296,7 @@ export function UserRoomProfile({ userId, initialProfile }: UserRoomProfileProps
|
||||
|
||||
const parsedBanner =
|
||||
typeof extendedProfile.bannerUrl === 'string'
|
||||
? extendedProfile.bannerUrl.replace(/^"|"$/g, '')
|
||||
? extendedProfile.bannerUrl.replaceAll(/^"|"$/g, '')
|
||||
: undefined;
|
||||
|
||||
const bannerHttpUrl = parsedBanner
|
||||
|
||||
@@ -45,7 +45,7 @@ type CreatePackTileProps = {
|
||||
packs: ImagePack[];
|
||||
roomId: string;
|
||||
};
|
||||
function CreatePackTile({ packs, roomId }: CreatePackTileProps) {
|
||||
function CreatePackTile({ packs, roomId }: Readonly<CreatePackTileProps>) {
|
||||
const mx = useMatrixClient();
|
||||
const alive = useAlive();
|
||||
|
||||
@@ -75,9 +75,9 @@ function CreatePackTile({ packs, roomId }: CreatePackTileProps) {
|
||||
const name = nameInput?.value.trim();
|
||||
if (!name) return;
|
||||
|
||||
let packKey = name.replace(/\s/g, '-');
|
||||
let packKey = name.replaceAll(/\s/g, '-');
|
||||
|
||||
const hasPack = (k: string): boolean => !!packs.find((pack) => pack.address?.stateKey === k);
|
||||
const hasPack = (k: string): boolean => packs.some((pack) => pack.address?.stateKey === k);
|
||||
if (hasPack(packKey)) {
|
||||
packKey = suffixRename(packKey, hasPack);
|
||||
}
|
||||
@@ -141,7 +141,7 @@ function CreatePackTile({ packs, roomId }: CreatePackTileProps) {
|
||||
type RoomPacksProps = {
|
||||
onViewPack: (imagePack: ImagePack) => void;
|
||||
};
|
||||
export function RoomPacks({ onViewPack }: RoomPacksProps) {
|
||||
export function RoomPacks({ onViewPack }: Readonly<RoomPacksProps>) {
|
||||
const mx = useMatrixClient();
|
||||
const useAuthentication = useMediaAuthentication();
|
||||
const room = useRoom();
|
||||
@@ -193,7 +193,7 @@ export function RoomPacks({ onViewPack }: RoomPacksProps) {
|
||||
const avatarUrl = avatarMxc ? mxcUrlToHttp(mx, avatarMxc, useAuthentication) : undefined;
|
||||
const { address } = pack;
|
||||
if (!address) return null;
|
||||
const removed = !!removedPacks.find((addr) => packAddressEqual(addr, address));
|
||||
const removed = removedPacks.some((addr) => packAddressEqual(addr, address));
|
||||
|
||||
return (
|
||||
<SequenceCard
|
||||
|
||||
@@ -57,7 +57,7 @@ type EditPowerProps = {
|
||||
onSave: (power: number, tag: MemberPowerTag) => void;
|
||||
onClose: () => void;
|
||||
};
|
||||
function EditPower({ maxPower, power, tag, onSave, onClose }: EditPowerProps) {
|
||||
function EditPower({ maxPower, power, tag, onSave, onClose }: Readonly<EditPowerProps>) {
|
||||
const mx = useMatrixClient();
|
||||
const room = useRoom();
|
||||
const roomToParents = useAtomValue(roomToParentsAtom);
|
||||
@@ -103,7 +103,7 @@ function EditPower({ maxPower, power, tag, onSave, onClose }: EditPowerProps) {
|
||||
const nameInput = target?.nameInput as HTMLInputElement | undefined;
|
||||
if (!powerInput || !nameInput) return;
|
||||
|
||||
const tagPower = parseInt(powerInput.value, 10);
|
||||
const tagPower = Number.parseInt(powerInput.value, 10);
|
||||
if (Number.isNaN(tagPower)) return;
|
||||
|
||||
const tagName = nameInput.value.trim();
|
||||
@@ -307,7 +307,7 @@ type PowersEditorProps = {
|
||||
powerLevels: IPowerLevels;
|
||||
requestClose: () => void;
|
||||
};
|
||||
export function PowersEditor({ powerLevels, requestClose }: PowersEditorProps) {
|
||||
export function PowersEditor({ powerLevels, requestClose }: Readonly<PowersEditorProps>) {
|
||||
const mx = useMatrixClient();
|
||||
const useAuthentication = useMediaAuthentication();
|
||||
const room = useRoom();
|
||||
|
||||
@@ -29,9 +29,8 @@ export const useDraggableItem = (
|
||||
const target = targetRef.current;
|
||||
const dragHandle = dragHandleRef?.current ?? undefined;
|
||||
|
||||
return !target
|
||||
? undefined
|
||||
: draggable({
|
||||
return target
|
||||
? draggable({
|
||||
element: target,
|
||||
dragHandle,
|
||||
getInitialData: () => item,
|
||||
@@ -43,7 +42,8 @@ export const useDraggableItem = (
|
||||
setDragging(false);
|
||||
onDragging(undefined);
|
||||
},
|
||||
});
|
||||
})
|
||||
: undefined;
|
||||
}, [targetRef, dragHandleRef, item, onDragging]);
|
||||
|
||||
return dragging;
|
||||
@@ -72,14 +72,14 @@ export function AfterItemDropTarget({
|
||||
afterSpace,
|
||||
nextRoomId,
|
||||
canDrop,
|
||||
}: AfterItemDropTargetProps) {
|
||||
}: Readonly<AfterItemDropTargetProps>) {
|
||||
const targetRef = useRef<HTMLDivElement>(null);
|
||||
const [dropState, setDropState] = useState<'idle' | 'allow' | 'not-allow'>('idle');
|
||||
|
||||
useEffect(() => {
|
||||
const target = targetRef.current;
|
||||
if (!target) {
|
||||
throw Error('drop target ref is not set properly');
|
||||
throw new Error('drop target ref is not set properly');
|
||||
}
|
||||
|
||||
return dropTargetForElements({
|
||||
@@ -126,7 +126,7 @@ export const useDnDMonitor = (
|
||||
useEffect(() => {
|
||||
const scrollElement = scrollRef.current;
|
||||
if (!scrollElement) {
|
||||
throw Error('Scroll element ref not configured');
|
||||
throw new Error('Scroll element ref not configured');
|
||||
}
|
||||
|
||||
return combine(
|
||||
|
||||
@@ -179,7 +179,7 @@ export function Lobby() {
|
||||
return new Set(sideSpaces);
|
||||
}, [sidebarItems]);
|
||||
|
||||
const [spacesItems, setSpacesItem] = useState<Map<string, IHierarchyRoom>>(() => new Map());
|
||||
const [spacesItems, setSpacesItems] = useState<Map<string, IHierarchyRoom>>(() => new Map());
|
||||
|
||||
useElementSizeObserver(
|
||||
useCallback(() => heroSectionRef.current, []),
|
||||
@@ -302,8 +302,7 @@ export function Lobby() {
|
||||
}
|
||||
|
||||
if (
|
||||
itemRoom &&
|
||||
itemRoom.getJoinRule() === JoinRule.Restricted &&
|
||||
itemRoom?.getJoinRule() === JoinRule.Restricted &&
|
||||
item.parentId !== containerParentId
|
||||
) {
|
||||
// change join rule allow parameter when dragging
|
||||
@@ -394,7 +393,7 @@ export function Lobby() {
|
||||
const handleSpacesFound = useCallback(
|
||||
(sItems: IHierarchyRoom[]) => {
|
||||
setSpaceRooms({ type: 'PUT', roomIds: sItems.map((i) => i.room_id) });
|
||||
setSpacesItem((current) => {
|
||||
setSpacesItems((current) => {
|
||||
const newItems = produce(current, (draft) => {
|
||||
sItems.forEach((item) => draft.set(item.room_id, item));
|
||||
});
|
||||
|
||||
@@ -49,7 +49,7 @@ export function MessageSearch({
|
||||
rooms,
|
||||
senders,
|
||||
scrollRef,
|
||||
}: MessageSearchProps) {
|
||||
}: Readonly<MessageSearchProps>) {
|
||||
const mx = useMatrixClient();
|
||||
const mDirects = useAtomValue(mDirectAtom);
|
||||
const allRooms = useRooms(mx, allRoomsAtom, mDirects);
|
||||
@@ -175,7 +175,7 @@ export function MessageSearch({
|
||||
});
|
||||
};
|
||||
|
||||
const lastVItem = vItems[vItems.length - 1];
|
||||
const lastVItem = vItems.at(-1);
|
||||
const lastVItemIndex: number | undefined = lastVItem?.index;
|
||||
const lastGroupIndex = groups.length - 1;
|
||||
useEffect(() => {
|
||||
@@ -253,7 +253,7 @@ export function MessageSearch({
|
||||
{((msgSearchParams.term && status === 'pending') ||
|
||||
(groups.length > 0 && vItems.length === 0)) && (
|
||||
<Box direction="Column" gap="100">
|
||||
{[...Array(8).keys()].map((key) => (
|
||||
{[...new Array(8).keys()].map((key) => (
|
||||
<SequenceCard variant="SurfaceVariant" key={key} style={{ minHeight: toRem(80) }} />
|
||||
))}
|
||||
</Box>
|
||||
|
||||
@@ -8,6 +8,7 @@ type AudioMessageRecorderProps = {
|
||||
onRequestClose: () => void;
|
||||
onWaveformUpdate: (waveform: number[]) => void;
|
||||
onAudioLengthUpdate: (length: number) => void;
|
||||
onAudioCodecUpdate?: (codec: string) => void;
|
||||
};
|
||||
|
||||
// We use a react voice recorder library to handle the recording of audio messages, as it provides a simple API and handles the complexities of recording audio in the browser.
|
||||
@@ -19,6 +20,7 @@ export function AudioMessageRecorder({
|
||||
onRequestClose,
|
||||
onWaveformUpdate,
|
||||
onAudioLengthUpdate,
|
||||
onAudioCodecUpdate,
|
||||
}: AudioMessageRecorderProps) {
|
||||
const containerRef = useRef<HTMLDivElement>(null);
|
||||
const isDismissedRef = useRef(false);
|
||||
@@ -50,7 +52,7 @@ export function AudioMessageRecorder({
|
||||
borderRadius: config.radii.R400,
|
||||
boxShadow: config.shadow.E200,
|
||||
padding: config.space.S400,
|
||||
minWidth: 300,
|
||||
width: 300,
|
||||
}}
|
||||
>
|
||||
<Text size="H4">Audio Message Recorder</Text>
|
||||
@@ -60,16 +62,20 @@ export function AudioMessageRecorder({
|
||||
audioFile,
|
||||
waveform,
|
||||
audioLength,
|
||||
audioCodec,
|
||||
}: {
|
||||
audioFile: Blob;
|
||||
waveform: number[];
|
||||
audioLength: number;
|
||||
audioCodec: string;
|
||||
}) => {
|
||||
if (isDismissedRef.current) return;
|
||||
// closes the recorder and sends the audio file back to the parent component to be uploaded and sent as a message
|
||||
onRecordingComplete(audioFile);
|
||||
onWaveformUpdate(waveform);
|
||||
onAudioLengthUpdate(audioLength);
|
||||
// Pass the audio codec to the parent component
|
||||
if (onAudioCodecUpdate) onAudioCodecUpdate(audioCodec);
|
||||
}}
|
||||
buttonBackgroundColor={color.SurfaceVariant.Container}
|
||||
buttonHoverBackgroundColor={color.SurfaceVariant.ContainerHover}
|
||||
|
||||
@@ -4,6 +4,7 @@ import { Room } from '$types/matrix-sdk';
|
||||
import { useCallStart, useCallJoined } from '$hooks/useCallEmbed';
|
||||
import { callEmbedAtom } from '$state/callEmbed';
|
||||
import { useMatrixClient } from '$hooks/useMatrixClient';
|
||||
import { useCallPreferences } from '$state/hooks/callPreferences';
|
||||
|
||||
interface RoomCallButtonProps {
|
||||
room: Room;
|
||||
@@ -14,13 +15,14 @@ export function RoomCallButton({ room }: RoomCallButtonProps) {
|
||||
const callEmbed = useAtomValue(callEmbedAtom);
|
||||
const joined = useCallJoined(callEmbed);
|
||||
const mx = useMatrixClient();
|
||||
const { microphone, video, sound } = useCallPreferences();
|
||||
|
||||
const isJoinedInThisRoom = joined && callEmbed?.roomId === room.roomId;
|
||||
|
||||
if (isJoinedInThisRoom) return null;
|
||||
|
||||
const handleStartCall = async () => {
|
||||
startCall(room);
|
||||
startCall(room, { microphone, video, sound });
|
||||
try {
|
||||
const now = Date.now();
|
||||
// TODO not use as any one day someday i swear
|
||||
|
||||
@@ -152,6 +152,7 @@ import { usePowerLevelsContext } from '$hooks/usePowerLevels';
|
||||
import { useRoomCreators } from '$hooks/useRoomCreators';
|
||||
import { useRoomPermissions } from '$hooks/useRoomPermissions';
|
||||
import { AutocompleteNotice } from '$components/editor/autocomplete/AutocompleteNotice';
|
||||
import { getSupportedAudioExtension } from '$plugins/voice-recorder-kit/supportedCodec';
|
||||
import { SchedulePickerDialog } from './schedule-send';
|
||||
import * as css from './schedule-send/SchedulePickerDialog.css';
|
||||
import {
|
||||
@@ -758,11 +759,35 @@ export const RoomInput = forwardRef<HTMLDivElement, RoomInputProps>(
|
||||
|
||||
const handleKeyDown: KeyboardEventHandler = useCallback(
|
||||
(evt) => {
|
||||
if (autocompleteQuery && isKeyHotkey('arrowdown', evt)) {
|
||||
evt.preventDefault();
|
||||
document
|
||||
.querySelector('[data-autocomplete-menu]')
|
||||
?.dispatchEvent(new CustomEvent('autocomplete-navigate', { detail: { direction: 1 } }));
|
||||
return;
|
||||
}
|
||||
if (autocompleteQuery && isKeyHotkey('arrowup', evt)) {
|
||||
evt.preventDefault();
|
||||
document
|
||||
.querySelector('[data-autocomplete-menu]')
|
||||
?.dispatchEvent(
|
||||
new CustomEvent('autocomplete-navigate', { detail: { direction: -1 } })
|
||||
);
|
||||
return;
|
||||
}
|
||||
if (
|
||||
(isKeyHotkey('mod+enter', evt) || (!enterForNewline && isKeyHotkey('enter', evt))) &&
|
||||
!isComposing(evt)
|
||||
) {
|
||||
evt.preventDefault();
|
||||
if (autocompleteQuery) {
|
||||
const selectedItem =
|
||||
document.querySelector<HTMLButtonElement>(
|
||||
'[data-autocomplete-menu] button[data-selected]'
|
||||
) ?? document.querySelector<HTMLButtonElement>('[data-autocomplete-menu] button');
|
||||
selectedItem?.click();
|
||||
return;
|
||||
}
|
||||
submit().catch((error) => {
|
||||
log.error('submit failed', { roomId }, error);
|
||||
});
|
||||
@@ -1148,7 +1173,7 @@ export const RoomInput = forwardRef<HTMLDivElement, RoomInputProps>(
|
||||
onRecordingComplete={(audioBlob) => {
|
||||
const file = new File(
|
||||
[audioBlob],
|
||||
`sable-audio-message-${Date.now()}.ogg`,
|
||||
`sable-audio-message-${Date.now()}.${getSupportedAudioExtension(audioBlob.type)}`,
|
||||
{
|
||||
type: audioBlob.type,
|
||||
}
|
||||
|
||||
@@ -206,7 +206,9 @@ export const timelineToEventsCount = (t: EventTimeline) => {
|
||||
export const getTimelinesEventsCount = (timelines: EventTimeline[]): number => {
|
||||
const timelineEventCountReducer = (count: number, tm: EventTimeline) =>
|
||||
count + timelineToEventsCount(tm);
|
||||
return (timelines || []).filter(Boolean).reduce(timelineEventCountReducer, 0);
|
||||
return (timelines || [])
|
||||
.filter(Boolean)
|
||||
.reduce((accumulator, element) => timelineEventCountReducer(accumulator, element), 0);
|
||||
};
|
||||
|
||||
export const getTimelineAndBaseIndex = (
|
||||
@@ -642,7 +644,12 @@ type ThreadReplyChipProps = {
|
||||
onToggle: () => void;
|
||||
};
|
||||
|
||||
function ThreadReplyChip({ room, mEventId, openThreadId, onToggle }: ThreadReplyChipProps) {
|
||||
function ThreadReplyChip({
|
||||
room,
|
||||
mEventId,
|
||||
openThreadId,
|
||||
onToggle,
|
||||
}: Readonly<ThreadReplyChipProps>) {
|
||||
const mx = useMatrixClient();
|
||||
const useAuthentication = useMediaAuthentication();
|
||||
const nicknames = useAtomValue(nicknamesAtom);
|
||||
@@ -668,7 +675,7 @@ function ThreadReplyChip({ room, mEventId, openThreadId, onToggle }: ThreadReply
|
||||
}
|
||||
});
|
||||
|
||||
const latestReply = replyEvents[replyEvents.length - 1];
|
||||
const latestReply = replyEvents.at(-1);
|
||||
const latestSenderId = latestReply?.getSender() ?? '';
|
||||
const latestSenderName =
|
||||
getMemberDisplayName(room, latestSenderId, nicknames) ??
|
||||
@@ -772,7 +779,7 @@ export function RoomTimeline({
|
||||
roomInputRef,
|
||||
editor,
|
||||
onEditorReset,
|
||||
}: RoomTimelineProps) {
|
||||
}: Readonly<RoomTimelineProps>) {
|
||||
const mx = useMatrixClient();
|
||||
const useAuthentication = useMediaAuthentication();
|
||||
const pushProcessor = useMemo(() => new PushProcessor(mx), [mx]);
|
||||
@@ -842,6 +849,7 @@ export function RoomTimeline({
|
||||
|
||||
const atBottomAnchorRef = useRef<HTMLElement>(null);
|
||||
|
||||
// TODO: The return value of "useState" should be destructured and named symmetrically (typescript:S6754)
|
||||
const [atBottom, setAtBottomState] = useState<boolean>(true);
|
||||
const atBottomRef = useRef(atBottom);
|
||||
// Tracks when atBottom last changed so we can detect rapid true→false flips
|
||||
|
||||
@@ -89,56 +89,106 @@ export const RoomViewFollowing = as<'div', RoomViewFollowingProps>(
|
||||
<Text size="T300" truncate>
|
||||
{names.length === 1 && (
|
||||
<>
|
||||
<b>{names[0]}</b>
|
||||
<Text as="span" size="Inherit" priority="300">
|
||||
<b style={{ WebkitTextFillColor: 'inherit' }}>{names[0]}</b>
|
||||
<Text
|
||||
as="span"
|
||||
size="Inherit"
|
||||
priority="300"
|
||||
style={{ WebkitTextFillColor: 'currentColor' }}
|
||||
>
|
||||
{' is following the conversation.'}
|
||||
</Text>
|
||||
</>
|
||||
)}
|
||||
{names.length === 2 && (
|
||||
<>
|
||||
<b>{names[0]}</b>
|
||||
<Text as="span" size="Inherit" priority="300">
|
||||
<b style={{ WebkitTextFillColor: 'inherit' }}>{names[0]}</b>
|
||||
<Text
|
||||
as="span"
|
||||
size="Inherit"
|
||||
priority="300"
|
||||
style={{ WebkitTextFillColor: 'currentColor' }}
|
||||
>
|
||||
{' and '}
|
||||
</Text>
|
||||
<b>{names[1]}</b>
|
||||
<Text as="span" size="Inherit" priority="300">
|
||||
<b style={{ WebkitTextFillColor: 'inherit' }}>{names[1]}</b>
|
||||
<Text
|
||||
as="span"
|
||||
size="Inherit"
|
||||
priority="300"
|
||||
style={{ WebkitTextFillColor: 'currentColor' }}
|
||||
>
|
||||
{' are following the conversation.'}
|
||||
</Text>
|
||||
</>
|
||||
)}
|
||||
{names.length === 3 && (
|
||||
<>
|
||||
<b>{names[0]}</b>
|
||||
<Text as="span" size="Inherit" priority="300">
|
||||
<b style={{ WebkitTextFillColor: 'inherit' }}>{names[0]}</b>
|
||||
<Text
|
||||
as="span"
|
||||
size="Inherit"
|
||||
priority="300"
|
||||
style={{ WebkitTextFillColor: 'currentColor' }}
|
||||
>
|
||||
{', '}
|
||||
</Text>
|
||||
<b>{names[1]}</b>
|
||||
<Text as="span" size="Inherit" priority="300">
|
||||
<b style={{ WebkitTextFillColor: 'inherit' }}>{names[1]}</b>
|
||||
<Text
|
||||
as="span"
|
||||
size="Inherit"
|
||||
priority="300"
|
||||
style={{ WebkitTextFillColor: 'currentColor' }}
|
||||
>
|
||||
{' and '}
|
||||
</Text>
|
||||
<b>{names[2]}</b>
|
||||
<Text as="span" size="Inherit" priority="300">
|
||||
<b style={{ WebkitTextFillColor: 'inherit' }}>{names[2]}</b>
|
||||
<Text
|
||||
as="span"
|
||||
size="Inherit"
|
||||
priority="300"
|
||||
style={{ WebkitTextFillColor: 'currentColor' }}
|
||||
>
|
||||
{' are following the conversation.'}
|
||||
</Text>
|
||||
</>
|
||||
)}
|
||||
{names.length > 3 && (
|
||||
<>
|
||||
<b>{names[0]}</b>
|
||||
<Text as="span" size="Inherit" priority="300">
|
||||
<b style={{ WebkitTextFillColor: 'inherit' }}>{names[0]}</b>
|
||||
<Text
|
||||
as="span"
|
||||
size="Inherit"
|
||||
priority="300"
|
||||
style={{ WebkitTextFillColor: 'currentColor' }}
|
||||
>
|
||||
{', '}
|
||||
</Text>
|
||||
<b>{names[1]}</b>
|
||||
<Text as="span" size="Inherit" priority="300">
|
||||
<b style={{ WebkitTextFillColor: 'inherit' }}>{names[1]}</b>
|
||||
<Text
|
||||
as="span"
|
||||
size="Inherit"
|
||||
priority="300"
|
||||
style={{ WebkitTextFillColor: 'currentColor' }}
|
||||
>
|
||||
{', '}
|
||||
</Text>
|
||||
<b>{names[2]}</b>
|
||||
<Text as="span" size="Inherit" priority="300">
|
||||
<b style={{ WebkitTextFillColor: 'inherit' }}>{names[2]}</b>
|
||||
<Text
|
||||
as="span"
|
||||
size="Inherit"
|
||||
priority="300"
|
||||
style={{ WebkitTextFillColor: 'currentColor' }}
|
||||
>
|
||||
{' and '}
|
||||
</Text>
|
||||
<b>{names.length - 3} others</b>
|
||||
<Text as="span" size="Inherit" priority="300">
|
||||
<b style={{ WebkitTextFillColor: 'inherit' }}>{names.length - 3} others</b>
|
||||
<Text
|
||||
as="span"
|
||||
size="Inherit"
|
||||
priority="300"
|
||||
style={{ WebkitTextFillColor: 'currentColor' }}
|
||||
>
|
||||
{' are following the conversation.'}
|
||||
</Text>
|
||||
</>
|
||||
|
||||
@@ -340,7 +340,7 @@ const RoomMenu = forwardRef<HTMLDivElement, RoomMenuProps>(({ room, requestClose
|
||||
});
|
||||
RoomMenu.displayName = 'RoomMenu';
|
||||
|
||||
export function RoomViewHeader({ callView }: { callView?: boolean }) {
|
||||
export function RoomViewHeader({ callView }: Readonly<{ callView?: boolean }>) {
|
||||
const navigate = useNavigate();
|
||||
const mx = useMatrixClient();
|
||||
const useAuthentication = useMediaAuthentication();
|
||||
@@ -361,6 +361,8 @@ export function RoomViewHeader({ callView }: { callView?: boolean }) {
|
||||
.getLiveTimeline()
|
||||
.getState(EventTimeline.FORWARDS)
|
||||
?.maySendStateEvent('org.matrix.msc3401.call.member', mx.getUserId()!);
|
||||
const [alwaysShowCallButton] = useSetting(settingsAtom, 'alwaysShowCallButton');
|
||||
const shouldShowCallButton = alwaysShowCallButton || room.getJoinedMemberCount() <= 10;
|
||||
|
||||
const encryptionEvent = useStateEvent(room, StateEvent.RoomEncryption);
|
||||
const encryptedRoom = !!encryptionEvent;
|
||||
@@ -408,14 +410,14 @@ export function RoomViewHeader({ callView }: { callView?: boolean }) {
|
||||
}
|
||||
|
||||
const lastSeenIndex = pinnedIds.indexOf(pinMarker?.last_seen_id);
|
||||
if (lastSeenIndex !== -1) {
|
||||
const newPins = pinnedIds.slice(lastSeenIndex + 1);
|
||||
setUnreadPinsCount(newPins.length);
|
||||
} else {
|
||||
if (lastSeenIndex === -1) {
|
||||
const oldCount = pinMarker?.count ?? 0;
|
||||
const startIndex = Math.max(0, oldCount - 1);
|
||||
const newCount = pinnedIds.length > 0 ? pinnedIds.length - startIndex : 0;
|
||||
setUnreadPinsCount(Math.max(0, newCount));
|
||||
} else {
|
||||
const newPins = pinnedIds.slice(lastSeenIndex + 1);
|
||||
setUnreadPinsCount(newPins.length);
|
||||
}
|
||||
};
|
||||
checkUnreads().catch((err) => {
|
||||
@@ -557,7 +559,7 @@ export function RoomViewHeader({ callView }: { callView?: boolean }) {
|
||||
await mx.setRoomAccountData(room.roomId, AccountDataEvent.SablePinStatus, {
|
||||
hash,
|
||||
count: pinnedIds.length,
|
||||
last_seen_id: pinnedIds[pinnedIds.length - 1],
|
||||
last_seen_id: pinnedIds.at(-1),
|
||||
});
|
||||
};
|
||||
|
||||
@@ -708,7 +710,7 @@ export function RoomViewHeader({ callView }: { callView?: boolean }) {
|
||||
</IconButton>
|
||||
)}
|
||||
</TooltipProvider>
|
||||
{canUseCalls && <RoomCallButton room={room} />}
|
||||
{canUseCalls && shouldShowCallButton && <RoomCallButton room={room} />}
|
||||
<PopOut
|
||||
anchor={pinMenuAnchor}
|
||||
position="Bottom"
|
||||
|
||||
@@ -719,6 +719,7 @@ export function ThreadDrawer({ room, threadRootId, onClose, overlay }: ThreadDra
|
||||
hideTrack={false}
|
||||
style={{
|
||||
maxHeight: '200px',
|
||||
height: 'fit-content',
|
||||
flexShrink: 0,
|
||||
}}
|
||||
>
|
||||
@@ -726,7 +727,7 @@ export function ThreadDrawer({ room, threadRootId, onClose, overlay }: ThreadDra
|
||||
className={css.messageList}
|
||||
direction="Column"
|
||||
style={{
|
||||
padding: `${config.space.S600} 0`,
|
||||
padding: `${config.space.S400} 0 ${config.space.S200} 0`,
|
||||
}}
|
||||
>
|
||||
<ThreadMessage {...sharedMessageProps} mEvent={rootEvent} />
|
||||
@@ -772,7 +773,7 @@ export function ThreadDrawer({ room, threadRootId, onClose, overlay }: ThreadDra
|
||||
<Box
|
||||
className={css.messageList}
|
||||
direction="Column"
|
||||
style={{ padding: `${config.space.S600} 0` }}
|
||||
style={{ padding: `0 0 ${config.space.S600} 0` }}
|
||||
>
|
||||
{replyEvents.map((mEvent, i) => {
|
||||
const prevEvent = i > 0 ? replyEvents[i - 1] : undefined;
|
||||
|
||||
@@ -1,4 +1,11 @@
|
||||
import { KeyboardEventHandler, MouseEventHandler, useCallback, useEffect, useState } from 'react';
|
||||
import {
|
||||
KeyboardEventHandler,
|
||||
MouseEventHandler,
|
||||
useCallback,
|
||||
useEffect,
|
||||
useMemo,
|
||||
useState,
|
||||
} from 'react';
|
||||
import {
|
||||
Box,
|
||||
Chip,
|
||||
@@ -22,8 +29,8 @@ import {
|
||||
ReplacementEvent,
|
||||
RelationType,
|
||||
Room,
|
||||
RoomMessageEventContent,
|
||||
RoomMessageTextEventContent,
|
||||
MsgType,
|
||||
} from '$types/matrix-sdk';
|
||||
import { isKeyHotkey } from 'is-hotkey';
|
||||
import {
|
||||
@@ -49,7 +56,7 @@ import {
|
||||
ANYWHERE_AUTOCOMPLETE_PREFIXES,
|
||||
} from '$components/editor';
|
||||
import { useSetting } from '$state/hooks/settings';
|
||||
import { settingsAtom } from '$state/settings';
|
||||
import { CaptionPosition, settingsAtom } from '$state/settings';
|
||||
import { UseStateProvider } from '$components/UseStateProvider';
|
||||
import { EmojiBoard } from '$components/emoji-board';
|
||||
import { AsyncStatus, useAsyncCallback } from '$hooks/useAsyncCallback';
|
||||
@@ -58,6 +65,13 @@ import { getEditedEvent, getMentionContent, trimReplyFromFormattedBody } from '$
|
||||
import { mobileOrTablet } from '$utils/user-agent';
|
||||
import { useComposingCheck } from '$hooks/useComposingCheck';
|
||||
import { floatingEditor } from '$styles/overrides/Composer.css';
|
||||
import { RenderMessageContent } from '$components/RenderMessageContent';
|
||||
import { getReactCustomHtmlParser, LINKIFY_OPTS } from '$plugins/react-custom-html-parser';
|
||||
import { useSpoilerClickHandler } from '$hooks/useSpoilerClickHandler';
|
||||
import { HTMLReactParserOptions } from 'html-react-parser';
|
||||
import { useMediaAuthentication } from '$hooks/useMediaAuthentication';
|
||||
import { Opts as LinkifyOpts } from 'linkifyjs';
|
||||
import { GetContentCallback } from '$types/matrix/room';
|
||||
|
||||
type MessageEditorProps = {
|
||||
roomId: string;
|
||||
@@ -104,6 +118,7 @@ export const MessageEditor = as<'div', MessageEditorProps>(
|
||||
|
||||
const [saveState, save] = useAsyncCallback(
|
||||
useCallback(async () => {
|
||||
const oldContent = mEvent.getContent();
|
||||
const plainText = toPlainText(editor.children, isMarkdown).trim();
|
||||
const customHtml = trimCustomHtml(
|
||||
toMatrixCustomHTML(editor.children, {
|
||||
@@ -134,13 +149,12 @@ export const MessageEditor = as<'div', MessageEditorProps>(
|
||||
|
||||
const msgtype = mEvent.getContent().msgtype as RoomMessageTextEventContent['msgtype'];
|
||||
|
||||
const newContent: RoomMessageTextEventContent = {
|
||||
const newContent: IContent = {
|
||||
msgtype,
|
||||
body: plainText,
|
||||
};
|
||||
|
||||
const contentBody: RoomMessageTextEventContent &
|
||||
Omit<ReplacementEvent<RoomMessageEventContent>, 'm.relates_to'> = {
|
||||
const contentBody: IContent & Omit<ReplacementEvent<IContent>, 'm.relates_to'> = {
|
||||
msgtype,
|
||||
body: `* ${plainText}`,
|
||||
'm.new_content': newContent,
|
||||
@@ -163,15 +177,35 @@ export const MessageEditor = as<'div', MessageEditorProps>(
|
||||
contentBody.formatted_body = `* ${customHtml}`;
|
||||
}
|
||||
|
||||
const content: RoomMessageEventContent = {
|
||||
...contentBody,
|
||||
const content: IContent = {
|
||||
...oldContent,
|
||||
'm.relates_to': {
|
||||
event_id: eventId,
|
||||
rel_type: RelationType.Replace,
|
||||
},
|
||||
};
|
||||
content.body = contentBody.body;
|
||||
content.format = contentBody.format;
|
||||
content.formatted_body = contentBody.formatted_body;
|
||||
content['m.new_content'] = newContent;
|
||||
if (oldContent.info !== undefined && oldContent.filename?.length > 0) {
|
||||
content.filename = oldContent.filename;
|
||||
content['m.new_content'].filename = oldContent.filename;
|
||||
content.info = oldContent.info;
|
||||
content['m.new_content'].info = oldContent.info;
|
||||
|
||||
return mx.sendMessage(roomId, content);
|
||||
if (oldContent.file !== undefined) content['m.new_content'].file = oldContent.file;
|
||||
if (oldContent.url !== undefined) content['m.new_content'].url = oldContent.url;
|
||||
|
||||
if (oldContent['page.codeberg.everypizza.msc4193.spoiler'] !== undefined) {
|
||||
content['page.codeberg.everypizza.msc4193.spoiler'] =
|
||||
oldContent['page.codeberg.everypizza.msc4193.spoiler'];
|
||||
content['m.new_content']['page.codeberg.everypizza.msc4193.spoiler'] =
|
||||
oldContent['page.codeberg.everypizza.msc4193.spoiler'];
|
||||
}
|
||||
}
|
||||
|
||||
return mx.sendMessage(roomId, content as any);
|
||||
}, [mx, editor, roomId, mEvent, isMarkdown, getPrevBodyAndFormattedBody])
|
||||
);
|
||||
|
||||
@@ -247,6 +281,27 @@ export const MessageEditor = as<'div', MessageEditorProps>(
|
||||
}
|
||||
}, [saveState, onCancel]);
|
||||
|
||||
const useAuthentication = useMediaAuthentication();
|
||||
const linkifyOpts = useMemo<LinkifyOpts>(() => ({ ...LINKIFY_OPTS }), []);
|
||||
const spoilerClickHandler = useSpoilerClickHandler();
|
||||
const htmlReactParserOptions = useMemo<HTMLReactParserOptions>(
|
||||
() =>
|
||||
getReactCustomHtmlParser(mx, mEvent.getRoomId(), {
|
||||
linkifyOpts,
|
||||
useAuthentication,
|
||||
handleSpoilerClick: spoilerClickHandler,
|
||||
}),
|
||||
[linkifyOpts, mEvent, mx, spoilerClickHandler, useAuthentication]
|
||||
);
|
||||
const getContent = (() => mEvent.getContent()) as GetContentCallback;
|
||||
const msgType = mEvent.getContent().msgtype;
|
||||
const [captionPosition] = useSetting(settingsAtom, 'captionPosition');
|
||||
const captionPositionMap = {
|
||||
[CaptionPosition.Above]: 'column-reverse',
|
||||
[CaptionPosition.Below]: 'column',
|
||||
[CaptionPosition.Inline]: 'row',
|
||||
[CaptionPosition.Hidden]: 'row',
|
||||
} satisfies Record<CaptionPosition, React.CSSProperties['flexDirection']>;
|
||||
return (
|
||||
<div {...props} ref={ref} className={`${props.className || ''} ${floatingEditor}`.trim()}>
|
||||
{autocompleteQuery?.prefix === AutocompletePrefix.RoomMention && (
|
||||
@@ -273,100 +328,138 @@ export const MessageEditor = as<'div', MessageEditorProps>(
|
||||
requestClose={handleCloseAutocomplete}
|
||||
/>
|
||||
)}
|
||||
<CustomEditor
|
||||
editor={editor}
|
||||
placeholder="Edit message..."
|
||||
onKeyDown={handleKeyDown}
|
||||
onKeyUp={handleKeyUp}
|
||||
bottom={
|
||||
<>
|
||||
<Box
|
||||
style={{ padding: config.space.S200, paddingTop: 0 }}
|
||||
alignItems="End"
|
||||
justifyContent="SpaceBetween"
|
||||
gap="100"
|
||||
>
|
||||
<Box gap="Inherit">
|
||||
<Chip
|
||||
onClick={handleSave}
|
||||
variant="Primary"
|
||||
radii="Pill"
|
||||
disabled={saveState.status === AsyncStatus.Loading}
|
||||
outlined
|
||||
before={
|
||||
saveState.status === AsyncStatus.Loading ? (
|
||||
<Spinner variant="Primary" fill="Soft" size="100" />
|
||||
) : undefined
|
||||
}
|
||||
<Box
|
||||
style={{
|
||||
display: 'flex',
|
||||
flexDirection: captionPositionMap[captionPosition],
|
||||
}}
|
||||
>
|
||||
{(msgType === MsgType.Image ||
|
||||
msgType === MsgType.Video ||
|
||||
msgType === MsgType.Audio ||
|
||||
msgType === MsgType.File) && (
|
||||
<RenderMessageContent
|
||||
displayName={mEvent.sender?.name ?? ''}
|
||||
msgType={mEvent.getContent().msgtype ?? ''}
|
||||
ts={mEvent.getTs()}
|
||||
getContent={getContent}
|
||||
htmlReactParserOptions={htmlReactParserOptions}
|
||||
hideCaption
|
||||
linkifyOpts={linkifyOpts}
|
||||
/>
|
||||
)}
|
||||
<Box
|
||||
style={
|
||||
captionPosition !== CaptionPosition.Inline
|
||||
? { marginTop: config.space.S400, width: '100%' }
|
||||
: {
|
||||
padding: config.space.S200,
|
||||
wordBreak: 'break-word',
|
||||
maxWidth: '100%',
|
||||
width: '100%',
|
||||
display: 'flex',
|
||||
flexDirection: 'column',
|
||||
justifyContent: 'center',
|
||||
flexShrink: 1,
|
||||
}
|
||||
}
|
||||
>
|
||||
<CustomEditor
|
||||
editor={editor}
|
||||
placeholder="Edit message..."
|
||||
onKeyDown={handleKeyDown}
|
||||
onKeyUp={handleKeyUp}
|
||||
bottom={
|
||||
<>
|
||||
<Box
|
||||
style={{ padding: config.space.S200, paddingTop: 0 }}
|
||||
alignItems="End"
|
||||
justifyContent="SpaceBetween"
|
||||
gap="100"
|
||||
>
|
||||
<Text size="B300">Save</Text>
|
||||
</Chip>
|
||||
<Chip onClick={onCancel} variant="SurfaceVariant" radii="Pill">
|
||||
<Text size="B300">Cancel</Text>
|
||||
</Chip>
|
||||
</Box>
|
||||
<Box gap="Inherit">
|
||||
<IconButton
|
||||
variant="SurfaceVariant"
|
||||
size="300"
|
||||
radii="300"
|
||||
onClick={() => setToolbar(!toolbar)}
|
||||
>
|
||||
<Icon size="400" src={toolbar ? Icons.AlphabetUnderline : Icons.Alphabet} />
|
||||
</IconButton>
|
||||
<UseStateProvider initial={undefined}>
|
||||
{(anchor: RectCords | undefined, setAnchor) => (
|
||||
<PopOut
|
||||
anchor={anchor}
|
||||
alignOffset={-8}
|
||||
position="Top"
|
||||
align="End"
|
||||
content={
|
||||
<EmojiBoard
|
||||
imagePackRooms={imagePackRooms ?? []}
|
||||
returnFocusOnDeactivate={false}
|
||||
onEmojiSelect={handleEmoticonSelect}
|
||||
onCustomEmojiSelect={handleEmoticonSelect}
|
||||
requestClose={() => {
|
||||
setAnchor((v) => {
|
||||
if (v) {
|
||||
if (!mobileOrTablet()) ReactEditor.focus(editor);
|
||||
return undefined;
|
||||
}
|
||||
return v;
|
||||
});
|
||||
}}
|
||||
/>
|
||||
<Box gap="Inherit">
|
||||
<Chip
|
||||
onClick={handleSave}
|
||||
variant="Primary"
|
||||
radii="Pill"
|
||||
disabled={saveState.status === AsyncStatus.Loading}
|
||||
outlined
|
||||
before={
|
||||
saveState.status === AsyncStatus.Loading ? (
|
||||
<Spinner variant="Primary" fill="Soft" size="100" />
|
||||
) : undefined
|
||||
}
|
||||
>
|
||||
<IconButton
|
||||
aria-pressed={anchor !== undefined}
|
||||
onClick={
|
||||
((evt) =>
|
||||
setAnchor(
|
||||
evt.currentTarget.getBoundingClientRect()
|
||||
)) as MouseEventHandler<HTMLButtonElement>
|
||||
}
|
||||
variant="SurfaceVariant"
|
||||
size="300"
|
||||
radii="300"
|
||||
>
|
||||
<Icon size="400" src={Icons.Smile} filled={anchor !== undefined} />
|
||||
</IconButton>
|
||||
</PopOut>
|
||||
)}
|
||||
</UseStateProvider>
|
||||
</Box>
|
||||
</Box>
|
||||
{toolbar && (
|
||||
<div>
|
||||
<Line variant="SurfaceVariant" size="300" />
|
||||
<Toolbar />
|
||||
</div>
|
||||
)}
|
||||
</>
|
||||
}
|
||||
/>
|
||||
<Text size="B300">Save</Text>
|
||||
</Chip>
|
||||
<Chip onClick={onCancel} variant="SurfaceVariant" radii="Pill">
|
||||
<Text size="B300">Cancel</Text>
|
||||
</Chip>
|
||||
</Box>
|
||||
<Box gap="Inherit">
|
||||
<IconButton
|
||||
variant="SurfaceVariant"
|
||||
size="300"
|
||||
radii="300"
|
||||
onClick={() => setToolbar(!toolbar)}
|
||||
>
|
||||
<Icon size="400" src={toolbar ? Icons.AlphabetUnderline : Icons.Alphabet} />
|
||||
</IconButton>
|
||||
<UseStateProvider initial={undefined}>
|
||||
{(anchor: RectCords | undefined, setAnchor) => (
|
||||
<PopOut
|
||||
anchor={anchor}
|
||||
alignOffset={-8}
|
||||
position="Top"
|
||||
align="End"
|
||||
content={
|
||||
<EmojiBoard
|
||||
imagePackRooms={imagePackRooms ?? []}
|
||||
returnFocusOnDeactivate={false}
|
||||
onEmojiSelect={handleEmoticonSelect}
|
||||
onCustomEmojiSelect={handleEmoticonSelect}
|
||||
requestClose={() => {
|
||||
setAnchor((v) => {
|
||||
if (v) {
|
||||
if (!mobileOrTablet()) ReactEditor.focus(editor);
|
||||
return undefined;
|
||||
}
|
||||
return v;
|
||||
});
|
||||
}}
|
||||
/>
|
||||
}
|
||||
>
|
||||
<IconButton
|
||||
aria-pressed={anchor !== undefined}
|
||||
onClick={
|
||||
((evt) =>
|
||||
setAnchor(
|
||||
evt.currentTarget.getBoundingClientRect()
|
||||
)) as MouseEventHandler<HTMLButtonElement>
|
||||
}
|
||||
variant="SurfaceVariant"
|
||||
size="300"
|
||||
radii="300"
|
||||
>
|
||||
<Icon size="400" src={Icons.Smile} filled={anchor !== undefined} />
|
||||
</IconButton>
|
||||
</PopOut>
|
||||
)}
|
||||
</UseStateProvider>
|
||||
</Box>
|
||||
</Box>
|
||||
{toolbar && (
|
||||
<div>
|
||||
<Line variant="SurfaceVariant" size="300" />
|
||||
<Toolbar />
|
||||
</div>
|
||||
)}
|
||||
</>
|
||||
}
|
||||
/>
|
||||
</Box>
|
||||
</Box>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
@@ -155,28 +155,60 @@ export const getAudioMsgContent = (
|
||||
audioLength?: number
|
||||
): AudioMsgContent => {
|
||||
const { file, encInfo } = item;
|
||||
const content: IContent = {
|
||||
let content: IContent = {
|
||||
msgtype: MsgType.Audio,
|
||||
filename: file.name,
|
||||
body: file.name,
|
||||
body: item.body && item.body.length > 0 ? item.body : 'a voice message',
|
||||
format: 'org.matrix.custom.html',
|
||||
formatted_body: file.name,
|
||||
formatted_body: item.body && item.body.length > 0 ? item.body : '<em>a voice message</em>',
|
||||
info: {
|
||||
mimetype: file.type,
|
||||
size: file.size,
|
||||
duration: item.metadata.markedAsSpoiler || !audioLength ? 0 : audioLength * 1000,
|
||||
},
|
||||
|
||||
// Element-compatible unstable extensible-event keys
|
||||
'org.matrix.msc1767.audio': {
|
||||
waveform: waveform?.map((v) => Math.round(v * 1024)), // scale waveform values to fit in 10 bits (0-1024) for more efficient storage, as per MSC1767 spec
|
||||
duration: item.metadata.markedAsSpoiler || !audioLength ? 0 : audioLength * 1000, // if marked as spoiler, set duration to 0 to hide it in clients that support msc1767
|
||||
},
|
||||
'org.matrix.msc1767.text': item.body && item.body.length > 0 ? item.body : 'a voice message',
|
||||
'org.matrix.msc3245.voice.v2': {
|
||||
duration: !audioLength ? 0 : audioLength,
|
||||
waveform: waveform?.map((v) => Math.round(v * 1024)),
|
||||
},
|
||||
// for element compat
|
||||
'org.matrix.msc3245.voice': {},
|
||||
};
|
||||
if (encInfo) {
|
||||
content.file = {
|
||||
...encInfo,
|
||||
url: mxc,
|
||||
};
|
||||
content = {
|
||||
...content,
|
||||
|
||||
// Element-compatible unstable extensible-event keys
|
||||
'org.matrix.msc1767.file': {
|
||||
name: file.name,
|
||||
mimetype: file.type,
|
||||
size: file.size,
|
||||
file: content.file,
|
||||
},
|
||||
};
|
||||
} else {
|
||||
content.url = mxc;
|
||||
content = {
|
||||
...content,
|
||||
|
||||
// Element-compatible unstable extensible-event keys
|
||||
'org.matrix.msc1767.file': {
|
||||
name: file.name,
|
||||
mimetype: file.type,
|
||||
size: file.size,
|
||||
url: content.url,
|
||||
},
|
||||
};
|
||||
}
|
||||
if (item.body && item.body.length > 0) content.body = item.body;
|
||||
if (item.formatted_body && item.formatted_body.length > 0) {
|
||||
|
||||
@@ -407,6 +407,8 @@ export function Search({ requestClose }: SearchProps) {
|
||||
<Text size="T200" priority="300">
|
||||
Type <b>#</b> for rooms, <b>@</b> for DMs and <b>*</b> for spaces. Hotkey:{' '}
|
||||
<b>{isMacOS() ? KeySymbol.Command : 'Ctrl'} + k</b>
|
||||
{' / '}
|
||||
<b>{isMacOS() ? KeySymbol.Command : 'Ctrl'} + f</b>
|
||||
</Text>
|
||||
</Box>
|
||||
</Modal>
|
||||
@@ -423,7 +425,7 @@ export function SearchModalRenderer() {
|
||||
window,
|
||||
useCallback(
|
||||
(event) => {
|
||||
if (isKeyHotkey('mod+k', event)) {
|
||||
if (isKeyHotkey('mod+k', event) || isKeyHotkey('mod+f', event)) {
|
||||
event.preventDefault();
|
||||
if (opened) {
|
||||
setOpen(false);
|
||||
|
||||
@@ -35,7 +35,7 @@ export function HomeserverInfo() {
|
||||
setFederationUrl(newUrl);
|
||||
}
|
||||
})
|
||||
.catch((error2) => setVersion({ error: error2 }));
|
||||
.catch((error_) => setVersion({ error: error_ }));
|
||||
} else {
|
||||
setVersion({ error });
|
||||
}
|
||||
@@ -144,7 +144,7 @@ export function HomeserverInfo() {
|
||||
type AboutProps = {
|
||||
requestClose: () => void;
|
||||
};
|
||||
export function About({ requestClose }: AboutProps) {
|
||||
export function About({ requestClose }: Readonly<AboutProps>) {
|
||||
const mx = useMatrixClient();
|
||||
const devLabel = IS_RELEASE_TAG ? '' : '-dev';
|
||||
const buildLabel = BUILD_HASH ? ` (${BUILD_HASH})` : '';
|
||||
@@ -293,7 +293,7 @@ export function About({ requestClose }: AboutProps) {
|
||||
target="_blank"
|
||||
>
|
||||
Cinny
|
||||
</a>{' '}
|
||||
</a>
|
||||
is ©{' '}
|
||||
<a
|
||||
href="https://github.com/ajbura"
|
||||
|
||||
@@ -18,11 +18,11 @@ export function NameColorEditor({
|
||||
current,
|
||||
onSave,
|
||||
disabled,
|
||||
}: NameColorEditorProps) {
|
||||
}: Readonly<NameColorEditorProps>) {
|
||||
const stripQuotes = (str?: string) => {
|
||||
if (!str) return '';
|
||||
// to solve the silly tuwunel
|
||||
return str.replace(/^["']|["']$/g, '');
|
||||
return str.replaceAll(/^["']|["']$/g, '');
|
||||
};
|
||||
|
||||
const [tempColor, setTempColor] = useState(stripQuotes(current) || '#FFFFFF');
|
||||
|
||||
@@ -64,7 +64,7 @@ type ProfileProps = {
|
||||
profile: UserProfile;
|
||||
userId: string;
|
||||
};
|
||||
function ProfileAvatar({ profile, userId }: ProfileProps) {
|
||||
function ProfileAvatar({ profile, userId }: Readonly<ProfileProps>) {
|
||||
const mx = useMatrixClient();
|
||||
const useAuthentication = useMediaAuthentication();
|
||||
const capabilities = useCapabilities();
|
||||
@@ -218,7 +218,7 @@ function ProfileAvatar({ profile, userId }: ProfileProps) {
|
||||
}
|
||||
|
||||
// eslint-disable-next-line @typescript-eslint/no-unused-vars
|
||||
function ProfileBanner({ profile, userId }: ProfileProps) {
|
||||
function ProfileBanner({ profile, userId }: Readonly<ProfileProps>) {
|
||||
const mx = useMatrixClient();
|
||||
const useAuthentication = useMediaAuthentication();
|
||||
const [alertRemove, setAlertRemove] = useState(false);
|
||||
@@ -387,7 +387,7 @@ function ProfileBanner({ profile, userId }: ProfileProps) {
|
||||
);
|
||||
}
|
||||
|
||||
function ProfileDisplayName({ profile, userId }: ProfileProps) {
|
||||
function ProfileDisplayName({ profile, userId }: Readonly<ProfileProps>) {
|
||||
const mx = useMatrixClient();
|
||||
const capabilities = useCapabilities();
|
||||
const disableSetDisplayname = capabilities['m.set_displayname']?.enabled === false;
|
||||
@@ -479,7 +479,7 @@ function ProfileDisplayName({ profile, userId }: ProfileProps) {
|
||||
);
|
||||
}
|
||||
|
||||
function ProfileExtended({ profile, userId }: ProfileProps) {
|
||||
function ProfileExtended({ profile, userId }: Readonly<ProfileProps>) {
|
||||
const mx = useMatrixClient();
|
||||
const setGlobalProfiles = useSetAtom(profilesCacheAtom);
|
||||
|
||||
@@ -488,12 +488,12 @@ function ProfileExtended({ profile, userId }: ProfileProps) {
|
||||
const currentStatus = presence?.status || '';
|
||||
|
||||
// Keys we don't render here nor handle seperately but still need to exclude
|
||||
const EXCLUDED_KEYS = ['kitty.meow.is_cat', 'kitty.meow.has_cats'];
|
||||
const EXCLUDED_KEYS = new Set(['kitty.meow.is_cat', 'kitty.meow.has_cats']);
|
||||
|
||||
// Unknown fields / unimplemented non-matrix-spec fields
|
||||
// Only renders them, can't edit or set
|
||||
const extendedFields = Object.entries(profile.extended || {}).filter(
|
||||
([key]) => !EXCLUDED_KEYS.includes(key)
|
||||
([key]) => !EXCLUDED_KEYS.has(key)
|
||||
);
|
||||
|
||||
const handleSaveField = useCallback(
|
||||
@@ -585,7 +585,7 @@ function ProfileExtended({ profile, userId }: ProfileProps) {
|
||||
onSave={(htmlBio) => {
|
||||
handleSaveField('moe.sable.app.bio', htmlBio);
|
||||
|
||||
const cleanedHtml = htmlBio.replace(/<br\/><\/blockquote>/g, '</blockquote>');
|
||||
const cleanedHtml = htmlBio.replaceAll('<br/></blockquote>', '</blockquote>');
|
||||
handleSaveField('chat.commet.profile_bio', {
|
||||
format: 'org.matrix.custom.html',
|
||||
formatted_body: cleanedHtml,
|
||||
@@ -642,7 +642,7 @@ type AnimalCosmeticsProps = {
|
||||
profile: UserProfile;
|
||||
userId: string;
|
||||
};
|
||||
function AnimalCosmetics({ profile, userId }: AnimalCosmeticsProps) {
|
||||
function AnimalCosmetics({ profile, userId }: Readonly<AnimalCosmeticsProps>) {
|
||||
const mx = useMatrixClient();
|
||||
const setGlobalProfiles = useSetAtom(profilesCacheAtom);
|
||||
const [renderAnimals, setRenderAnimals] = useSetting(settingsAtom, 'renderAnimals');
|
||||
|
||||
@@ -60,7 +60,7 @@ export const ThemeSelector = as<'div', ThemeSelectorProps>(
|
||||
)
|
||||
);
|
||||
|
||||
function SelectTheme({ disabled }: { disabled?: boolean }) {
|
||||
function SelectTheme({ disabled }: Readonly<{ disabled?: boolean }>) {
|
||||
const themes = useThemes();
|
||||
const themeNames = useThemeNames();
|
||||
const [themeId, setThemeId] = useSetting(settingsAtom, 'themeId');
|
||||
@@ -288,7 +288,7 @@ function ThemeSettings() {
|
||||
max="100"
|
||||
step="1"
|
||||
value={saturation}
|
||||
onChange={(e) => setSaturation(parseInt(e.target.value, 10))}
|
||||
onChange={(e) => setSaturation(Number.parseInt(e.target.value, 10))}
|
||||
style={{
|
||||
width: toRem(160),
|
||||
cursor: 'pointer',
|
||||
@@ -361,7 +361,7 @@ function PageZoomInput() {
|
||||
'value' in evt.target &&
|
||||
typeof evt.target.value === 'string'
|
||||
) {
|
||||
const newZoom = parseInt(evt.target.value, 10);
|
||||
const newZoom = Number.parseInt(evt.target.value, 10);
|
||||
if (Number.isNaN(newZoom)) return;
|
||||
const safeZoom = Math.max(Math.min(newZoom, 150), 75);
|
||||
setPageZoom(safeZoom);
|
||||
@@ -372,7 +372,7 @@ function PageZoomInput() {
|
||||
return (
|
||||
<Input
|
||||
style={{ width: toRem(100) }}
|
||||
variant={pageZoom === parseInt(currentZoom, 10) ? 'Secondary' : 'Success'}
|
||||
variant={pageZoom === Number.parseInt(currentZoom, 10) ? 'Secondary' : 'Success'}
|
||||
size="300"
|
||||
radii="300"
|
||||
type="number"
|
||||
|
||||
@@ -4,11 +4,12 @@ import { InfoCard } from '$components/info-card';
|
||||
import { LanguageSpecificPronouns } from '../cosmetics/LanguageSpecificPronouns';
|
||||
import { Sync } from '../general';
|
||||
import { BandwidthSavingEmojis } from './BandwithSavingEmojis';
|
||||
import { MSC4268HistoryShare } from './MSC4268HistoryShare';
|
||||
|
||||
type ExperimentalProps = {
|
||||
requestClose: () => void;
|
||||
};
|
||||
export function Experimental({ requestClose }: ExperimentalProps) {
|
||||
export function Experimental({ requestClose }: Readonly<ExperimentalProps>) {
|
||||
return (
|
||||
<Page>
|
||||
<PageHeader outlined={false}>
|
||||
@@ -33,8 +34,8 @@ export function Experimental({ requestClose }: ExperimentalProps) {
|
||||
variant="Warning"
|
||||
description={
|
||||
<>
|
||||
The features listed below may be unstable or incomplete,
|
||||
<strong> use at your own risk</strong>.
|
||||
The features listed below may be unstable or incomplete,{' '}
|
||||
<strong>use at your own risk</strong>.
|
||||
<br />
|
||||
Please report any new issues potentially caused by these features!
|
||||
</>
|
||||
@@ -43,6 +44,7 @@ export function Experimental({ requestClose }: ExperimentalProps) {
|
||||
<br />
|
||||
<Box direction="Column" gap="700">
|
||||
<Sync />
|
||||
<MSC4268HistoryShare />
|
||||
<LanguageSpecificPronouns />
|
||||
<BandwidthSavingEmojis />
|
||||
</Box>
|
||||
|
||||
@@ -0,0 +1,42 @@
|
||||
import { SequenceCard } from '$components/sequence-card';
|
||||
import { SettingTile } from '$components/setting-tile';
|
||||
import { useSetting } from '$state/hooks/settings';
|
||||
import { settingsAtom } from '$state/settings';
|
||||
import { Box, Switch, Text } from 'folds';
|
||||
import { SequenceCardStyle } from '../styles.css';
|
||||
|
||||
export function MSC4268HistoryShare() {
|
||||
const [enabledMSC4268Command, setEnabledMSC4268Command] = useSetting(
|
||||
settingsAtom,
|
||||
'enableMSC4268CMD'
|
||||
);
|
||||
|
||||
return (
|
||||
<Box direction="Column" gap="100">
|
||||
<Text size="L400">Enable Sharing of Encrypted History</Text>
|
||||
<SequenceCard
|
||||
className={SequenceCardStyle}
|
||||
variant="SurfaceVariant"
|
||||
direction="Column"
|
||||
gap="100"
|
||||
>
|
||||
<SettingTile
|
||||
title="Enable the /sharehistory command"
|
||||
description="If enabled, this command will allow users to share encrypted history with other newly joined users, as per MSC4268."
|
||||
after={
|
||||
<Switch
|
||||
variant="Primary"
|
||||
value={enabledMSC4268Command}
|
||||
onChange={setEnabledMSC4268Command}
|
||||
title={
|
||||
enabledMSC4268Command
|
||||
? 'Disable /sharehistory command'
|
||||
: 'Enable /sharehistory command'
|
||||
}
|
||||
/>
|
||||
}
|
||||
/>
|
||||
</SequenceCard>
|
||||
</Box>
|
||||
);
|
||||
}
|
||||
@@ -56,7 +56,7 @@ type DateHintProps = {
|
||||
hasChanges: boolean;
|
||||
handleReset: () => void;
|
||||
};
|
||||
function DateHint({ hasChanges, handleReset }: DateHintProps) {
|
||||
function DateHint({ hasChanges, handleReset }: Readonly<DateHintProps>) {
|
||||
const [anchor, setAnchor] = useState<RectCords>();
|
||||
const categoryPadding = { padding: config.space.S200, paddingTop: 0 };
|
||||
|
||||
@@ -223,7 +223,7 @@ type CustomDateFormatProps = {
|
||||
value: string;
|
||||
onChange: (format: string) => void;
|
||||
};
|
||||
function CustomDateFormat({ value, onChange }: CustomDateFormatProps) {
|
||||
function CustomDateFormat({ value, onChange }: Readonly<CustomDateFormatProps>) {
|
||||
const [dateFormatCustom, setDateFormatCustom] = useState(value);
|
||||
|
||||
useEffect(() => {
|
||||
@@ -288,12 +288,12 @@ type PresetDateFormatProps = {
|
||||
value: string;
|
||||
onChange: (format: string) => void;
|
||||
};
|
||||
function PresetDateFormat({ value, onChange }: PresetDateFormatProps) {
|
||||
function PresetDateFormat({ value, onChange }: Readonly<PresetDateFormatProps>) {
|
||||
const [menuCords, setMenuCords] = useState<RectCords>();
|
||||
const dateFormatItems = useDateFormatItems();
|
||||
|
||||
const getDisplayDate = (format: string): string =>
|
||||
format !== '' ? dayjs().format(format) : 'Custom';
|
||||
format === '' ? 'Custom' : dayjs().format(format);
|
||||
|
||||
const handleMenu: MouseEventHandler<HTMLButtonElement> = (evt) => {
|
||||
setMenuCords(evt.currentTarget.getBoundingClientRect());
|
||||
@@ -415,7 +415,7 @@ function DateAndTime() {
|
||||
);
|
||||
}
|
||||
|
||||
function Editor({ isMobile }: { isMobile: boolean }) {
|
||||
function Editor({ isMobile }: Readonly<{ isMobile: boolean }>) {
|
||||
const [enterForNewline, setEnterForNewline] = useSetting(settingsAtom, 'enterForNewline');
|
||||
const [isMarkdown, setIsMarkdown] = useSetting(settingsAtom, 'isMarkdown');
|
||||
const [hideActivity, setHideActivity] = useSetting(settingsAtom, 'hideActivity');
|
||||
@@ -681,7 +681,7 @@ function SelectMessageSpacing() {
|
||||
);
|
||||
}
|
||||
|
||||
function SelectRightSwipeAction({ disabled }: { disabled?: boolean }) {
|
||||
function SelectRightSwipeAction({ disabled }: Readonly<{ disabled?: boolean }>) {
|
||||
const [menuCords, setMenuCords] = useState<RectCords>();
|
||||
const [action, setAction] = useSetting(settingsAtom, 'rightSwipeAction');
|
||||
|
||||
@@ -749,7 +749,7 @@ function SelectRightSwipeAction({ disabled }: { disabled?: boolean }) {
|
||||
);
|
||||
}
|
||||
|
||||
function Gestures({ isMobile }: { isMobile: boolean }) {
|
||||
function Gestures({ isMobile }: Readonly<{ isMobile: boolean }>) {
|
||||
const [mobileGestures, setMobileGestures] = useSetting(settingsAtom, 'mobileGestures');
|
||||
|
||||
return (
|
||||
@@ -788,7 +788,7 @@ function EmojiSelectorThresholdInput() {
|
||||
const val = evt.target.value;
|
||||
setInputValue(val);
|
||||
|
||||
const parsed = parseInt(val, 10);
|
||||
const parsed = Number.parseInt(val, 10);
|
||||
if (!Number.isNaN(parsed) && parsed >= 1 && parsed <= 10) {
|
||||
setEmojiThreshold(parsed);
|
||||
}
|
||||
@@ -809,7 +809,7 @@ function EmojiSelectorThresholdInput() {
|
||||
return (
|
||||
<Input
|
||||
style={{ width: toRem(80) }}
|
||||
variant={parseInt(inputValue, 10) === emojiThreshold ? 'Secondary' : 'Success'}
|
||||
variant={Number.parseInt(inputValue, 10) === emojiThreshold ? 'Secondary' : 'Success'}
|
||||
size="300"
|
||||
radii="300"
|
||||
type="number"
|
||||
@@ -823,6 +823,31 @@ function EmojiSelectorThresholdInput() {
|
||||
);
|
||||
}
|
||||
|
||||
function Calls() {
|
||||
const [alwaysShowCallButton, setAlwaysShowCallButton] = useSetting(
|
||||
settingsAtom,
|
||||
'alwaysShowCallButton'
|
||||
);
|
||||
|
||||
return (
|
||||
<Box direction="Column" gap="100">
|
||||
<Text size="L400">Calls</Text>
|
||||
<SequenceCard className={SequenceCardStyle} variant="SurfaceVariant" direction="Column">
|
||||
<SettingTile
|
||||
title="Show Call Button for Large Rooms"
|
||||
after={
|
||||
<Switch
|
||||
variant="Primary"
|
||||
value={alwaysShowCallButton}
|
||||
onChange={setAlwaysShowCallButton}
|
||||
/>
|
||||
}
|
||||
/>
|
||||
</SequenceCard>
|
||||
</Box>
|
||||
);
|
||||
}
|
||||
|
||||
function Messages() {
|
||||
const [hideMembershipEvents, setHideMembershipEvents] = useSetting(
|
||||
settingsAtom,
|
||||
@@ -1156,7 +1181,7 @@ function DiagnosticsAndPrivacy() {
|
||||
);
|
||||
}
|
||||
|
||||
export function General({ requestClose }: GeneralProps) {
|
||||
export function General({ requestClose }: Readonly<GeneralProps>) {
|
||||
return (
|
||||
<Page>
|
||||
<PageHeader outlined={false}>
|
||||
@@ -1182,6 +1207,7 @@ export function General({ requestClose }: GeneralProps) {
|
||||
<Editor isMobile={mobileOrTablet()} />
|
||||
<Messages />
|
||||
<DiagnosticsAndPrivacy />
|
||||
<Calls />
|
||||
</Box>
|
||||
</PageContent>
|
||||
</Scroll>
|
||||
|
||||
@@ -189,6 +189,10 @@ export function SystemNotification() {
|
||||
const [showUnreadCounts, setShowUnreadCounts] = useSetting(settingsAtom, 'showUnreadCounts');
|
||||
const [badgeCountDMsOnly, setBadgeCountDMsOnly] = useSetting(settingsAtom, 'badgeCountDMsOnly');
|
||||
const [showPingCounts, setShowPingCounts] = useSetting(settingsAtom, 'showPingCounts');
|
||||
const [faviconForMentionsOnly, setFaviconForMentionsOnly] = useSetting(
|
||||
settingsAtom,
|
||||
'faviconForMentionsOnly'
|
||||
);
|
||||
|
||||
// Describe what the current badge combo actually does so users aren't left guessing.
|
||||
const badgeBehaviourSummary = (): string => {
|
||||
@@ -338,6 +342,24 @@ export function SystemNotification() {
|
||||
<Text size="T300" style={{ opacity: 0.7 }}>
|
||||
{badgeBehaviourSummary()}
|
||||
</Text>
|
||||
<SequenceCard
|
||||
className={SequenceCardStyle}
|
||||
variant="SurfaceVariant"
|
||||
direction="Column"
|
||||
gap="400"
|
||||
>
|
||||
<SettingTile
|
||||
title="Favicon Dot: Mentions Only"
|
||||
description="Only change the browser tab favicon when you have mentions or keywords. Unreads without mentions won't affect the favicon."
|
||||
after={
|
||||
<Switch
|
||||
variant="Primary"
|
||||
value={faviconForMentionsOnly}
|
||||
onChange={setFaviconForMentionsOnly}
|
||||
/>
|
||||
}
|
||||
/>
|
||||
</SequenceCard>
|
||||
<SequenceCard
|
||||
className={SequenceCardStyle}
|
||||
variant="SurfaceVariant"
|
||||
|
||||
@@ -30,7 +30,7 @@ import {
|
||||
|
||||
export type CapabilityApprovalCallback = (requested: Set<Capability>) => Promise<Set<Capability>>;
|
||||
|
||||
// Unlike SmallWidgetDriver which auto-grants all capabilities for Element Call,
|
||||
// Unlike CallWidgetDriver which auto-grants all capabilities for Element Call,
|
||||
// this driver provides a capability approval mechanism for untrusted widgets.
|
||||
export class GenericWidgetDriver extends WidgetDriver {
|
||||
private readonly mxClient: MatrixClient;
|
||||
@@ -164,6 +164,18 @@ export class GenericWidgetDriver extends WidgetDriver {
|
||||
await this.mxClient._unstable_updateDelayedEvent(delayId, action);
|
||||
}
|
||||
|
||||
public async cancelScheduledDelayedEvent(delayId: string): Promise<void> {
|
||||
await this.updateDelayedEvent(delayId, UpdateDelayedEventAction.Cancel);
|
||||
}
|
||||
|
||||
public async restartScheduledDelayedEvent(delayId: string): Promise<void> {
|
||||
await this.updateDelayedEvent(delayId, UpdateDelayedEventAction.Restart);
|
||||
}
|
||||
|
||||
public async sendScheduledDelayedEvent(delayId: string): Promise<void> {
|
||||
await this.updateDelayedEvent(delayId, UpdateDelayedEventAction.Send);
|
||||
}
|
||||
|
||||
public async sendToDevice(
|
||||
eventType: string,
|
||||
encrypted: boolean,
|
||||
|
||||
@@ -0,0 +1,126 @@
|
||||
// Integration tests: renderHook exercises the full React lifecycle including
|
||||
// useAlive (cleanup on unmount) and retry-race-condition logic.
|
||||
import { describe, it, expect } from 'vitest';
|
||||
import { renderHook, act } from '@testing-library/react';
|
||||
import { useAsyncCallback, AsyncStatus } from './useAsyncCallback';
|
||||
|
||||
describe('useAsyncCallback', () => {
|
||||
it('starts in Idle state', () => {
|
||||
const { result } = renderHook(() => useAsyncCallback(async () => 'value'));
|
||||
const [state] = result.current;
|
||||
expect(state.status).toBe(AsyncStatus.Idle);
|
||||
});
|
||||
|
||||
it('transitions to Success with returned data', async () => {
|
||||
const { result } = renderHook(() => useAsyncCallback(async () => 42));
|
||||
|
||||
await act(async () => {
|
||||
await result.current[1]();
|
||||
});
|
||||
|
||||
expect(result.current[0]).toEqual({ status: AsyncStatus.Success, data: 42 });
|
||||
});
|
||||
|
||||
it('transitions to Error when the async function throws', async () => {
|
||||
const boom = new Error('boom');
|
||||
const { result } = renderHook(() =>
|
||||
useAsyncCallback(async () => {
|
||||
throw boom;
|
||||
})
|
||||
);
|
||||
|
||||
await act(async () => {
|
||||
await result.current[1]().catch(() => {});
|
||||
});
|
||||
|
||||
expect(result.current[0]).toEqual({ status: AsyncStatus.Error, error: boom });
|
||||
});
|
||||
|
||||
it('ignores the result of a stale (superseded) request', async () => {
|
||||
// Two calls are made. The first resolves AFTER the second — its result should
|
||||
// be discarded so the final state reflects only the second call.
|
||||
let resolveFirst!: (v: string) => void;
|
||||
let resolveSecond!: (v: string) => void;
|
||||
let callCount = 0;
|
||||
|
||||
const { result } = renderHook(() =>
|
||||
useAsyncCallback(async () => {
|
||||
callCount += 1;
|
||||
if (callCount === 1) {
|
||||
return new Promise<string>((res) => {
|
||||
resolveFirst = res;
|
||||
});
|
||||
}
|
||||
return new Promise<string>((res) => {
|
||||
resolveSecond = res;
|
||||
});
|
||||
})
|
||||
);
|
||||
|
||||
// Fire both requests before either resolves
|
||||
act(() => {
|
||||
result.current[1]();
|
||||
});
|
||||
act(() => {
|
||||
result.current[1]();
|
||||
});
|
||||
|
||||
// Resolve the stale first request — its result should be ignored
|
||||
await act(async () => {
|
||||
resolveFirst('stale');
|
||||
await Promise.resolve();
|
||||
});
|
||||
|
||||
// Resolve the fresh second request — this should be the final state
|
||||
await act(async () => {
|
||||
resolveSecond('fresh');
|
||||
await Promise.resolve();
|
||||
});
|
||||
|
||||
const successStates = result.current[0];
|
||||
expect(successStates.status).toBe(AsyncStatus.Success);
|
||||
if (successStates.status === AsyncStatus.Success) {
|
||||
expect(successStates.data).toBe('fresh');
|
||||
}
|
||||
});
|
||||
|
||||
it('does not call setState after the component unmounts', async () => {
|
||||
let resolveAfterUnmount!: (v: string) => void;
|
||||
const stateChanges: string[] = [];
|
||||
|
||||
const { result, unmount } = renderHook(() =>
|
||||
useAsyncCallback(
|
||||
async () =>
|
||||
new Promise<string>((res) => {
|
||||
resolveAfterUnmount = res;
|
||||
})
|
||||
)
|
||||
);
|
||||
|
||||
// Track state changes via the third returned setter
|
||||
const [, callback, setState] = result.current;
|
||||
const originalSetState = setState;
|
||||
// Patch setState to record calls
|
||||
result.current[2] = (s) => {
|
||||
stateChanges.push(typeof s === 'function' ? 'fn' : s.status);
|
||||
originalSetState(s);
|
||||
};
|
||||
|
||||
act(() => {
|
||||
callback();
|
||||
});
|
||||
|
||||
unmount();
|
||||
|
||||
// Resolve after unmount — alive() returns false, so state should NOT be updated
|
||||
await act(async () => {
|
||||
resolveAfterUnmount('late');
|
||||
await Promise.resolve();
|
||||
});
|
||||
|
||||
// Only the Loading state (queued before unmount) may have been emitted;
|
||||
// Success must not appear after unmount.
|
||||
const successCalls = stateChanges.filter((s) => s === AsyncStatus.Success);
|
||||
expect(successCalls).toHaveLength(0);
|
||||
});
|
||||
});
|
||||
+133
-213
@@ -10,7 +10,6 @@ import {
|
||||
Visibility,
|
||||
RoomServerAclEventContent,
|
||||
MsgType,
|
||||
MatrixEvent,
|
||||
} from '$types/matrix-sdk';
|
||||
import { useMemo } from 'react';
|
||||
import { Membership, StateEvent } from '$types/matrix/room';
|
||||
@@ -32,20 +31,21 @@ import { settingsAtom } from '$state/settings';
|
||||
import { useOpenBugReportModal } from '$state/hooks/bugReportModal';
|
||||
import { createRoomEncryptionState } from '$components/create-room';
|
||||
import { parsePronounsInput } from '$utils/pronouns';
|
||||
import { sendFeedback } from '$utils/sendFeedbackToUser';
|
||||
import { useRoomNavigate } from './useRoomNavigate';
|
||||
import { enrichWidgetUrl } from './useRoomWidgets';
|
||||
import { useUserProfile } from './useUserProfile';
|
||||
|
||||
export const SHRUG = '¯\\_(ツ)_/¯';
|
||||
export const SHRUG = String.raw`¯\_(ツ)_/¯`;
|
||||
export const TABLEFLIP = '(╯°□°)╯︵ ┻━┻';
|
||||
export const UNFLIP = '┬─┬ノ( º_ºノ)';
|
||||
|
||||
const FLAG_PAT = '(?:^|\\s)-(\\w+)\\b';
|
||||
const FLAG_PAT = String.raw`(?:^|\s)-(\w+)\b`;
|
||||
const FLAG_REG = new RegExp(FLAG_PAT);
|
||||
const FLAG_REG_G = new RegExp(FLAG_PAT, 'g');
|
||||
|
||||
export const splitPayloadContentAndFlags = (payload: string): [string, string | undefined] => {
|
||||
const flagMatch = payload.match(FLAG_REG);
|
||||
const flagMatch = new RegExp(FLAG_REG).exec(payload);
|
||||
|
||||
if (!flagMatch) {
|
||||
return [payload, undefined];
|
||||
@@ -116,7 +116,7 @@ export const parseTimestampFlag = (input: string): number | undefined => {
|
||||
return undefined;
|
||||
}
|
||||
|
||||
const value = parseFloat(match[1]); // supports decimal values
|
||||
const value = Number.parseFloat(match[1]); // supports decimal values
|
||||
const unit = match[2];
|
||||
|
||||
const now = Date.now(); // in milliseconds
|
||||
@@ -251,6 +251,8 @@ export enum Command {
|
||||
Headpat = 'headpat',
|
||||
// Meta
|
||||
Report = 'bugreport',
|
||||
// Experimental
|
||||
ShareE2EEHistory = 'sharehistory',
|
||||
}
|
||||
|
||||
export type CommandContent = {
|
||||
@@ -264,6 +266,7 @@ export type CommandRecord = Record<Command, CommandContent>;
|
||||
export const useCommands = (mx: MatrixClient, room: Room): CommandRecord => {
|
||||
const { navigateRoom } = useRoomNavigate();
|
||||
const [developerTools] = useSetting(settingsAtom, 'developerTools');
|
||||
const [enableMSC4268CMD] = useSetting(settingsAtom, 'enableMSC4268CMD');
|
||||
const profile = useUserProfile(mx.getSafeUserId());
|
||||
const openBugReport = useOpenBugReportModal();
|
||||
|
||||
@@ -282,7 +285,7 @@ export const useCommands = (mx: MatrixClient, room: Room): CommandRecord => {
|
||||
},
|
||||
[Command.Shrug]: {
|
||||
name: Command.Shrug,
|
||||
description: 'Send ¯\\_(ツ)_/¯ as message',
|
||||
description: String.raw`Send ¯\_(ツ)_/¯ as message`,
|
||||
exe: async () => undefined,
|
||||
},
|
||||
[Command.TableFlip]: {
|
||||
@@ -559,8 +562,7 @@ export const useCommands = (mx: MatrixClient, room: Room): CommandRecord => {
|
||||
room.roomId,
|
||||
token,
|
||||
20,
|
||||
Direction.Forward,
|
||||
undefined
|
||||
Direction.Forward
|
||||
);
|
||||
const { end, chunk } = response;
|
||||
// remove until the latest event;
|
||||
@@ -641,17 +643,6 @@ export const useCommands = (mx: MatrixClient, room: Room): CommandRecord => {
|
||||
const input = payload.trim().toLowerCase();
|
||||
const userId = mx.getSafeUserId();
|
||||
|
||||
const sendFeedback = (msg: string) => {
|
||||
const localNotice = new MatrixEvent({
|
||||
type: 'm.room.message',
|
||||
content: { msgtype: 'm.notice', body: msg },
|
||||
event_id: `~sable-${Date.now()}`,
|
||||
room_id: room.roomId,
|
||||
sender: userId,
|
||||
});
|
||||
(room as any).addLiveEvents([localNotice], { duplicateStrategy: 'ignore' } as any);
|
||||
};
|
||||
|
||||
try {
|
||||
if (input === 'reset' || input === 'clear') {
|
||||
await mx.sendStateEvent(
|
||||
@@ -660,7 +651,7 @@ export const useCommands = (mx: MatrixClient, room: Room): CommandRecord => {
|
||||
{},
|
||||
userId
|
||||
);
|
||||
sendFeedback('Room color has been reset.');
|
||||
sendFeedback('Room color has been reset.', room, userId);
|
||||
return;
|
||||
}
|
||||
|
||||
@@ -671,14 +662,16 @@ export const useCommands = (mx: MatrixClient, room: Room): CommandRecord => {
|
||||
{ color: input },
|
||||
userId
|
||||
);
|
||||
sendFeedback(`Room color set to ${input}.`);
|
||||
sendFeedback(`Room color set to ${input}.`, room, userId);
|
||||
} else {
|
||||
sendFeedback('Invalid format. Use #RRGGBB.');
|
||||
sendFeedback('Invalid format. Use #RRGGBB.', room, userId);
|
||||
}
|
||||
} catch (e: any) {
|
||||
if (e.errcode === 'M_FORBIDDEN') {
|
||||
sendFeedback(
|
||||
'Permission Denied. An admin must enable "Room Colors" in Settings > Cosmetics in app.sable.moe or another supported client.'
|
||||
'Permission Denied. An admin must enable "Room Colors" in Settings > Cosmetics in app.sable.moe or another supported client.',
|
||||
room,
|
||||
userId
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -692,17 +685,6 @@ export const useCommands = (mx: MatrixClient, room: Room): CommandRecord => {
|
||||
const input = payload.trim().toLowerCase();
|
||||
const userId = mx.getSafeUserId();
|
||||
|
||||
const sendFeedback = (msg: string) => {
|
||||
const localNotice = new MatrixEvent({
|
||||
type: 'm.room.message',
|
||||
content: { msgtype: 'm.notice', body: msg },
|
||||
event_id: `~sable-g-${Date.now()}`,
|
||||
room_id: room.roomId,
|
||||
sender: userId,
|
||||
});
|
||||
(room as any).addLiveEvents([localNotice], { duplicateStrategy: 'ignore' } as any);
|
||||
};
|
||||
|
||||
const parents = room
|
||||
.getLiveTimeline()
|
||||
.getState(EventTimeline.FORWARDS)
|
||||
@@ -719,7 +701,7 @@ export const useCommands = (mx: MatrixClient, room: Room): CommandRecord => {
|
||||
{},
|
||||
userId
|
||||
);
|
||||
sendFeedback('Global space color reset.');
|
||||
sendFeedback('Global space color reset.', room, userId);
|
||||
return;
|
||||
}
|
||||
|
||||
@@ -730,14 +712,16 @@ export const useCommands = (mx: MatrixClient, room: Room): CommandRecord => {
|
||||
{ color: input },
|
||||
userId
|
||||
);
|
||||
sendFeedback(`Global space color set to ${input}.`);
|
||||
sendFeedback(`Global space color set to ${input}.`, room, userId);
|
||||
} else {
|
||||
sendFeedback('Invalid format. Use #RRGGBB.');
|
||||
sendFeedback('Invalid format. Use #RRGGBB.', room, userId);
|
||||
}
|
||||
} catch (e: any) {
|
||||
if (e.errcode === 'M_FORBIDDEN') {
|
||||
sendFeedback(
|
||||
'Permission Denied. An admin must enable "Space-Wide Colors" in Settings > Cosmetics in app.sable.moe or another supported client.'
|
||||
'Permission Denied. An admin must enable "Space-Wide Colors" in Settings > Cosmetics in app.sable.moe or another supported client.',
|
||||
room,
|
||||
userId
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -749,25 +733,14 @@ export const useCommands = (mx: MatrixClient, room: Room): CommandRecord => {
|
||||
exe: async (payload) => {
|
||||
const input = payload
|
||||
.trim()
|
||||
.replace(/[;{}<>]/g, '')
|
||||
.replaceAll(/[;{}<>]/g, '')
|
||||
.slice(0, 32);
|
||||
const userId = mx.getSafeUserId();
|
||||
|
||||
const sendFeedback = (msg: string) => {
|
||||
const localNotice = new MatrixEvent({
|
||||
type: 'm.room.message',
|
||||
content: { msgtype: 'm.notice', body: msg },
|
||||
event_id: `~font-${Date.now()}`,
|
||||
room_id: room.roomId,
|
||||
sender: userId,
|
||||
});
|
||||
(room as any).addLiveEvents([localNotice], { duplicateStrategy: 'ignore' } as any);
|
||||
};
|
||||
|
||||
try {
|
||||
if (input.toLowerCase() === 'reset' || input === '') {
|
||||
await mx.sendStateEvent(room.roomId, StateEvent.RoomCosmeticsFont as any, {}, userId);
|
||||
sendFeedback('Room font reset.');
|
||||
sendFeedback('Room font reset.', room, userId);
|
||||
return;
|
||||
}
|
||||
|
||||
@@ -777,11 +750,13 @@ export const useCommands = (mx: MatrixClient, room: Room): CommandRecord => {
|
||||
{ font: input },
|
||||
userId
|
||||
);
|
||||
sendFeedback(`Room font set to "${input}".`);
|
||||
sendFeedback(`Room font set to "${input}".`, room, userId);
|
||||
} catch (e: any) {
|
||||
if (e.errcode === 'M_FORBIDDEN') {
|
||||
sendFeedback(
|
||||
'Permission Denied. An admin must enable "Room Fonts" in Settings > Cosmetics in app.sable.moe or another supported client.'
|
||||
'Permission Denied. An admin must enable "Room Fonts" in Settings > Cosmetics in app.sable.moe or another supported client.',
|
||||
room,
|
||||
userId
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -793,21 +768,10 @@ export const useCommands = (mx: MatrixClient, room: Room): CommandRecord => {
|
||||
exe: async (payload) => {
|
||||
const input = payload
|
||||
.trim()
|
||||
.replace(/[;{}<>]/g, '')
|
||||
.replaceAll(/[;{}<>]/g, '')
|
||||
.slice(0, 32);
|
||||
const userId = mx.getSafeUserId();
|
||||
|
||||
const sendFeedback = (msg: string) => {
|
||||
const localNotice = new MatrixEvent({
|
||||
type: 'm.room.message',
|
||||
content: { msgtype: 'm.notice', body: msg },
|
||||
event_id: `~sfont-${Date.now()}`,
|
||||
room_id: room.roomId,
|
||||
sender: userId,
|
||||
});
|
||||
(room as any).addLiveEvents([localNotice], { duplicateStrategy: 'ignore' } as any);
|
||||
};
|
||||
|
||||
const parents = room
|
||||
.getLiveTimeline()
|
||||
.getState(EventTimeline.FORWARDS)
|
||||
@@ -824,7 +788,7 @@ export const useCommands = (mx: MatrixClient, room: Room): CommandRecord => {
|
||||
{},
|
||||
userId
|
||||
);
|
||||
sendFeedback('Space font reset.');
|
||||
sendFeedback('Space font reset.', room, userId);
|
||||
return;
|
||||
}
|
||||
|
||||
@@ -834,11 +798,13 @@ export const useCommands = (mx: MatrixClient, room: Room): CommandRecord => {
|
||||
{ font: input },
|
||||
userId
|
||||
);
|
||||
sendFeedback(`Space font set to "${input}".`);
|
||||
sendFeedback(`Space font set to "${input}".`, room, userId);
|
||||
} catch (e: any) {
|
||||
if (e.errcode === 'M_FORBIDDEN') {
|
||||
sendFeedback(
|
||||
'Permission Denied. An admin must enable "Space-Wide Fonts" in Settings > Cosmetics in app.sable.moe or another supported client.'
|
||||
'Permission Denied. An admin must enable "Space-Wide Fonts" in Settings > Cosmetics in app.sable.moe or another supported client.',
|
||||
room,
|
||||
userId
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -850,23 +816,12 @@ export const useCommands = (mx: MatrixClient, room: Room): CommandRecord => {
|
||||
exe: async (payload) => {
|
||||
const userId = mx.getSafeUserId();
|
||||
|
||||
const sendFeedback = (msg: string) => {
|
||||
const localNotice = new MatrixEvent({
|
||||
type: 'm.room.message',
|
||||
content: { msgtype: 'm.notice', body: msg },
|
||||
event_id: `~nullptr-widget-${Date.now()}`,
|
||||
room_id: room.roomId,
|
||||
sender: userId,
|
||||
});
|
||||
(room as any).addLiveEvents([localNotice], { duplicateStrategy: 'ignore' } as any);
|
||||
};
|
||||
|
||||
const parts = payload.trim().split(/\s+/);
|
||||
const url = parts[0];
|
||||
const name = parts.slice(1).join(' ') || 'Widget';
|
||||
|
||||
if (!url) {
|
||||
sendFeedback('Usage: /addwidget <url> [name]');
|
||||
sendFeedback('Usage: /addwidget <url> [name]', room, userId);
|
||||
return;
|
||||
}
|
||||
|
||||
@@ -874,7 +829,7 @@ export const useCommands = (mx: MatrixClient, room: Room): CommandRecord => {
|
||||
try {
|
||||
parsedUrl = new URL(url);
|
||||
} catch {
|
||||
sendFeedback('Invalid URL. Please provide a valid widget URL.');
|
||||
sendFeedback('Invalid URL. Please provide a valid widget URL.', room, userId);
|
||||
return;
|
||||
}
|
||||
|
||||
@@ -892,14 +847,16 @@ export const useCommands = (mx: MatrixClient, room: Room): CommandRecord => {
|
||||
} as any,
|
||||
widgetId
|
||||
);
|
||||
sendFeedback(`Widget "${name}" added.`);
|
||||
sendFeedback(`Widget "${name}" added.`, room, userId);
|
||||
} catch (e: any) {
|
||||
if (e.errcode === 'M_FORBIDDEN') {
|
||||
sendFeedback(
|
||||
'Permission denied. You need permission to manage widgets in this room.'
|
||||
'Permission denied. You need permission to manage widgets in this room.',
|
||||
room,
|
||||
userId
|
||||
);
|
||||
} else {
|
||||
sendFeedback(`Failed to add widget: ${e.message || 'Unknown error'}`);
|
||||
sendFeedback(`Failed to add widget: ${e.message || 'Unknown error'}`, room, userId);
|
||||
}
|
||||
}
|
||||
},
|
||||
@@ -913,17 +870,6 @@ export const useCommands = (mx: MatrixClient, room: Room): CommandRecord => {
|
||||
const rawInput = match ? match[1].trim() : payload.trim();
|
||||
const userId = mx.getSafeUserId();
|
||||
|
||||
const sendFeedback = (msg: string) => {
|
||||
const localNotice = new MatrixEvent({
|
||||
type: 'm.room.message',
|
||||
content: { msgtype: 'm.notice', body: msg },
|
||||
event_id: `~pronoun-${Date.now()}`,
|
||||
room_id: room.roomId,
|
||||
sender: userId,
|
||||
});
|
||||
(room as any).addLiveEvents([localNotice], { duplicateStrategy: 'ignore' } as any);
|
||||
};
|
||||
|
||||
try {
|
||||
if (['reset', 'clear', ''].includes(rawInput.toLowerCase())) {
|
||||
await mx.sendStateEvent(
|
||||
@@ -932,7 +878,7 @@ export const useCommands = (mx: MatrixClient, room: Room): CommandRecord => {
|
||||
{},
|
||||
userId
|
||||
);
|
||||
sendFeedback('Room pronouns have been reset.');
|
||||
sendFeedback('Room pronouns have been reset.', room, userId);
|
||||
return;
|
||||
}
|
||||
|
||||
@@ -949,10 +895,10 @@ export const useCommands = (mx: MatrixClient, room: Room): CommandRecord => {
|
||||
.map((p) => (p.language ? `for ${p.language} "${p.summary}" was set` : p.summary))
|
||||
.join(', ');
|
||||
|
||||
sendFeedback(`Room pronouns set: ${feedbackString}`);
|
||||
sendFeedback(`Room pronouns set: ${feedbackString}`, room, userId);
|
||||
} catch (e: any) {
|
||||
if (e.errcode === 'M_FORBIDDEN') {
|
||||
sendFeedback('Permission Denied. Could not update room pronouns.');
|
||||
sendFeedback('Permission Denied. Could not update room pronouns.', room, userId);
|
||||
}
|
||||
}
|
||||
},
|
||||
@@ -966,17 +912,6 @@ export const useCommands = (mx: MatrixClient, room: Room): CommandRecord => {
|
||||
const rawInput = match ? match[1].trim() : payload.trim();
|
||||
const userId = mx.getSafeUserId();
|
||||
|
||||
const sendFeedback = (msg: string) => {
|
||||
const localNotice = new MatrixEvent({
|
||||
type: 'm.room.message',
|
||||
content: { msgtype: 'm.notice', body: msg },
|
||||
event_id: `~gpronoun-${Date.now()}`,
|
||||
room_id: room.roomId,
|
||||
sender: userId,
|
||||
});
|
||||
(room as any).addLiveEvents([localNotice], { duplicateStrategy: 'ignore' } as any);
|
||||
};
|
||||
|
||||
const parents = room
|
||||
.getLiveTimeline()
|
||||
.getState(EventTimeline.FORWARDS)
|
||||
@@ -993,7 +928,7 @@ export const useCommands = (mx: MatrixClient, room: Room): CommandRecord => {
|
||||
{},
|
||||
userId
|
||||
);
|
||||
sendFeedback('Global space pronouns reset.');
|
||||
sendFeedback('Global space pronouns reset.', room, userId);
|
||||
return;
|
||||
}
|
||||
|
||||
@@ -1010,10 +945,10 @@ export const useCommands = (mx: MatrixClient, room: Room): CommandRecord => {
|
||||
.map((p) => (p.language ? `for ${p.language} "${p.summary}" was set` : p.summary))
|
||||
.join(', ');
|
||||
|
||||
sendFeedback(`Global space pronouns set: ${feedbackString}`);
|
||||
sendFeedback(`Global space pronouns set: ${feedbackString}`, room, userId);
|
||||
} catch (e: any) {
|
||||
if (e.errcode === 'M_FORBIDDEN') {
|
||||
sendFeedback('Permission Denied. Could not update space pronouns.');
|
||||
sendFeedback('Permission Denied. Could not update space pronouns.', room, userId);
|
||||
}
|
||||
}
|
||||
},
|
||||
@@ -1039,25 +974,15 @@ export const useCommands = (mx: MatrixClient, room: Room): CommandRecord => {
|
||||
'[Dev only] Send raw message event. Example: /rawmsg {"msgtype":"m.text", "body":"hello"}',
|
||||
exe: async (payload) => {
|
||||
const userId = mx.getSafeUserId();
|
||||
const sendFeedback = (msg: string) => {
|
||||
const localNotice = new MatrixEvent({
|
||||
type: 'm.room.message',
|
||||
content: { msgtype: 'm.notice', body: msg },
|
||||
event_id: `~rawmsg-${Date.now()}`,
|
||||
room_id: room.roomId,
|
||||
sender: userId,
|
||||
});
|
||||
(room as any).addLiveEvents([localNotice], { duplicateStrategy: 'ignore' } as any);
|
||||
};
|
||||
if (!developerTools) {
|
||||
sendFeedback('Command available in Developer Mode only.');
|
||||
sendFeedback('Command available in Developer Mode only.', room, userId);
|
||||
return;
|
||||
}
|
||||
try {
|
||||
const content = JSON.parse(payload);
|
||||
await mx.sendMessage(room.roomId, content);
|
||||
} catch (e: any) {
|
||||
sendFeedback(`Invalid JSON: ${e.message}`);
|
||||
sendFeedback(`Invalid JSON: ${e.message}`, room, userId);
|
||||
}
|
||||
},
|
||||
},
|
||||
@@ -1066,19 +991,9 @@ export const useCommands = (mx: MatrixClient, room: Room): CommandRecord => {
|
||||
description: '[Dev only] Send any raw event. Usage: /raw <type> <json> [-s stateKey]',
|
||||
exe: async (payload) => {
|
||||
const userId = mx.getSafeUserId();
|
||||
const sendFeedback = (msg: string) => {
|
||||
const localNotice = new MatrixEvent({
|
||||
type: 'm.room.message',
|
||||
content: { msgtype: 'm.notice', body: msg },
|
||||
event_id: `~rawevent-${Date.now()}`,
|
||||
room_id: room.roomId,
|
||||
sender: userId,
|
||||
});
|
||||
room.addLiveEvents([localNotice], { duplicateStrategy: 'ignore' } as any);
|
||||
};
|
||||
|
||||
if (!developerTools) {
|
||||
sendFeedback('Command available in Developer Mode only.');
|
||||
sendFeedback('Command available in Developer Mode only.', room, userId);
|
||||
return;
|
||||
}
|
||||
|
||||
@@ -1090,7 +1005,7 @@ export const useCommands = (mx: MatrixClient, room: Room): CommandRecord => {
|
||||
const jsonString = mainPayload.trim().substring(eventType.length).trim();
|
||||
|
||||
if (!eventType || !jsonString) {
|
||||
sendFeedback('Usage: /rawevent <type> <json> [-s stateKey]');
|
||||
sendFeedback('Usage: /rawevent <type> <json> [-s stateKey]', room, userId);
|
||||
return;
|
||||
}
|
||||
|
||||
@@ -1099,13 +1014,17 @@ export const useCommands = (mx: MatrixClient, room: Room): CommandRecord => {
|
||||
|
||||
if (typeof stateKey === 'string') {
|
||||
await mx.sendStateEvent(room.roomId, eventType as any, content, stateKey);
|
||||
sendFeedback(`State event "${eventType}" sent with state key "${stateKey}".`);
|
||||
sendFeedback(
|
||||
`State event "${eventType}" sent with state key "${stateKey}".`,
|
||||
room,
|
||||
userId
|
||||
);
|
||||
} else {
|
||||
await mx.sendEvent(room.roomId, eventType as any, content);
|
||||
sendFeedback(`Event "${eventType}" sent.`);
|
||||
sendFeedback(`Event "${eventType}" sent.`, room, userId);
|
||||
}
|
||||
} catch (e: any) {
|
||||
sendFeedback(`Error: ${e.message}`);
|
||||
sendFeedback(`Error: ${e.message}`, room, userId);
|
||||
}
|
||||
},
|
||||
},
|
||||
@@ -1114,26 +1033,16 @@ export const useCommands = (mx: MatrixClient, room: Room): CommandRecord => {
|
||||
description: '[Dev only] Merge global account data. Usage: /rawacc <type> <json>',
|
||||
exe: async (payload) => {
|
||||
const userId = mx.getSafeUserId();
|
||||
const sendFeedback = (msg: string) => {
|
||||
const localNotice = new MatrixEvent({
|
||||
type: 'm.room.message',
|
||||
content: { msgtype: 'm.notice', body: msg },
|
||||
event_id: `~rawacc-${Date.now()}`,
|
||||
room_id: room.roomId,
|
||||
sender: userId,
|
||||
});
|
||||
(room as any).addLiveEvents([localNotice], { duplicateStrategy: 'ignore' } as any);
|
||||
};
|
||||
|
||||
if (!developerTools) {
|
||||
sendFeedback('Command available in Developer Mode only.');
|
||||
sendFeedback('Command available in Developer Mode only.', room, userId);
|
||||
return;
|
||||
}
|
||||
|
||||
const trimmed = payload.trim();
|
||||
const firstSpaceIndex = trimmed.indexOf(' ');
|
||||
if (firstSpaceIndex === -1) {
|
||||
sendFeedback('Usage: /rawacc <type> <json>');
|
||||
sendFeedback('Usage: /rawacc <type> <json>', room, userId);
|
||||
return;
|
||||
}
|
||||
|
||||
@@ -1149,9 +1058,9 @@ export const useCommands = (mx: MatrixClient, room: Room): CommandRecord => {
|
||||
const mergedContent = { ...existingContent, ...newContent };
|
||||
|
||||
await mx.setAccountData(type as any, mergedContent);
|
||||
sendFeedback(`Account data "${type}" merged successfully.`);
|
||||
sendFeedback(`Account data "${type}" merged successfully.`, room, userId);
|
||||
} catch (e: any) {
|
||||
sendFeedback(`Error: ${e.message}`);
|
||||
sendFeedback(`Error: ${e.message}`, room, userId);
|
||||
}
|
||||
},
|
||||
},
|
||||
@@ -1160,38 +1069,28 @@ export const useCommands = (mx: MatrixClient, room: Room): CommandRecord => {
|
||||
description: '[Dev Only] Remove a key from account data. Usage: /delacc <type> <key>',
|
||||
exe: async (payload) => {
|
||||
const userId = mx.getSafeUserId();
|
||||
const sendFeedback = (msg: string) => {
|
||||
const localNotice = new MatrixEvent({
|
||||
type: 'm.room.message',
|
||||
content: { msgtype: 'm.notice', body: msg },
|
||||
event_id: `~removeacc-${Date.now()}`,
|
||||
room_id: room.roomId,
|
||||
sender: userId,
|
||||
});
|
||||
room.addLiveEvents([localNotice], { duplicateStrategy: 'ignore' } as any);
|
||||
};
|
||||
const parts = payload.trim().split(/\s+/);
|
||||
if (parts.length < 2) {
|
||||
sendFeedback('Usage: /delacc <type> <key>');
|
||||
sendFeedback('Usage: /delacc <type> <key>', room, userId);
|
||||
return;
|
||||
}
|
||||
const [type, key] = parts;
|
||||
try {
|
||||
const existingEvent = mx.getAccountData(type as any);
|
||||
if (!existingEvent) {
|
||||
sendFeedback(`No account data found for type "${type}".`);
|
||||
sendFeedback(`No account data found for type "${type}".`, room, userId);
|
||||
return;
|
||||
}
|
||||
const content = { ...existingEvent.getContent() };
|
||||
if (!(key in content)) {
|
||||
sendFeedback(`Key "${key}" not found in "${type}".`);
|
||||
sendFeedback(`Key "${key}" not found in "${type}".`, room, userId);
|
||||
return;
|
||||
}
|
||||
delete content[key];
|
||||
await mx.setAccountData(type as any, content as any);
|
||||
sendFeedback(`Key "${key}" removed from "${type}".`);
|
||||
sendFeedback(`Key "${key}" removed from "${type}".`, room, userId);
|
||||
} catch (e: any) {
|
||||
sendFeedback(`Error: ${e.message}`);
|
||||
sendFeedback(`Error: ${e.message}`, room, userId);
|
||||
}
|
||||
},
|
||||
},
|
||||
@@ -1200,23 +1099,13 @@ export const useCommands = (mx: MatrixClient, room: Room): CommandRecord => {
|
||||
description: '[Dev Only] Set an extended profile property. Usage: /setext <key> <value>',
|
||||
exe: async (payload) => {
|
||||
const userId = mx.getSafeUserId();
|
||||
const sendFeedback = (msg: string) => {
|
||||
const localNotice = new MatrixEvent({
|
||||
type: 'm.room.message',
|
||||
content: { msgtype: 'm.notice', body: msg },
|
||||
event_id: `~setext-${Date.now()}`,
|
||||
room_id: room.roomId,
|
||||
sender: userId,
|
||||
});
|
||||
room.addLiveEvents([localNotice], { duplicateStrategy: 'ignore' } as any);
|
||||
};
|
||||
if (!developerTools) {
|
||||
sendFeedback('Command available in Developer Mode only.');
|
||||
sendFeedback('Command available in Developer Mode only.', room, userId);
|
||||
return;
|
||||
}
|
||||
const parts = payload.trim().split(/\s+/);
|
||||
if (parts.length < 2) {
|
||||
sendFeedback('Usage: /setext <key> <value>');
|
||||
sendFeedback('Usage: /setext <key> <value>', room, userId);
|
||||
return;
|
||||
}
|
||||
const key = parts[0];
|
||||
@@ -1228,12 +1117,16 @@ export const useCommands = (mx: MatrixClient, room: Room): CommandRecord => {
|
||||
try {
|
||||
if (typeof mx.setExtendedProfileProperty === 'function') {
|
||||
await mx.setExtendedProfileProperty(key, finalValue);
|
||||
sendFeedback(`Extended profile property "${key}" set to: ${finalValue}`);
|
||||
sendFeedback(
|
||||
`Extended profile property "${key}" set to: ${finalValue}`,
|
||||
room,
|
||||
userId
|
||||
);
|
||||
} else {
|
||||
sendFeedback('Error: setExtendedProfileProperty is not supported.');
|
||||
sendFeedback('Error: setExtendedProfileProperty is not supported.', room, userId);
|
||||
}
|
||||
} catch (e: any) {
|
||||
sendFeedback(`Failed to set extended profile: ${e.message}`);
|
||||
sendFeedback(`Failed to set extended profile: ${e.message}`, room, userId);
|
||||
}
|
||||
},
|
||||
},
|
||||
@@ -1244,36 +1137,25 @@ export const useCommands = (mx: MatrixClient, room: Room): CommandRecord => {
|
||||
const userId = mx.getSafeUserId();
|
||||
const key = payload.trim();
|
||||
|
||||
const sendFeedback = (msg: string) => {
|
||||
const localNotice = new MatrixEvent({
|
||||
type: 'm.room.message',
|
||||
content: { msgtype: 'm.notice', body: msg },
|
||||
event_id: `~removeext-${Date.now()}`,
|
||||
room_id: room.roomId,
|
||||
sender: userId,
|
||||
});
|
||||
room.addLiveEvents([localNotice], { duplicateStrategy: 'ignore' } as any);
|
||||
};
|
||||
|
||||
if (!developerTools) {
|
||||
sendFeedback('Command available in Developer Mode only.');
|
||||
sendFeedback('Command available in Developer Mode only.', room, userId);
|
||||
return;
|
||||
}
|
||||
|
||||
if (!key) {
|
||||
sendFeedback('Usage: /delext <key>');
|
||||
sendFeedback('Usage: /delext <key>', room, userId);
|
||||
return;
|
||||
}
|
||||
|
||||
try {
|
||||
if (typeof mx.deleteExtendedProfileProperty === 'function') {
|
||||
await mx.deleteExtendedProfileProperty(key);
|
||||
sendFeedback(`Extended profile property "${key}" removed.`);
|
||||
sendFeedback(`Extended profile property "${key}" removed.`, room, userId);
|
||||
} else {
|
||||
sendFeedback('Error: setExtendedProfileProperty is not supported.');
|
||||
sendFeedback('Error: setExtendedProfileProperty is not supported.', room, userId);
|
||||
}
|
||||
} catch (e: any) {
|
||||
sendFeedback(`Failed to remove property: ${e.message}`);
|
||||
sendFeedback(`Failed to remove property: ${e.message}`, room, userId);
|
||||
}
|
||||
},
|
||||
},
|
||||
@@ -1282,30 +1164,59 @@ export const useCommands = (mx: MatrixClient, room: Room): CommandRecord => {
|
||||
description: 'Force discard the current outbound E2EE session in this room.',
|
||||
exe: async () => {
|
||||
const userId = mx.getSafeUserId();
|
||||
const sendFeedback = (msg: string) => {
|
||||
const localNotice = new MatrixEvent({
|
||||
type: 'm.room.message',
|
||||
content: { msgtype: 'm.notice', body: msg },
|
||||
event_id: `~discard-${Date.now()}`,
|
||||
room_id: room.roomId,
|
||||
sender: userId,
|
||||
});
|
||||
room.addLiveEvents([localNotice], { duplicateStrategy: 'ignore' } as any);
|
||||
};
|
||||
|
||||
try {
|
||||
const crypto = mx.getCrypto();
|
||||
if (!crypto) {
|
||||
sendFeedback('Encryption is not enabled on this client.');
|
||||
sendFeedback('Encryption is not enabled on this client.', room, userId);
|
||||
return;
|
||||
}
|
||||
await crypto.forceDiscardSession(room.roomId);
|
||||
sendFeedback('Outbound encryption session discarded.');
|
||||
sendFeedback('Outbound encryption session discarded.', room, userId);
|
||||
} catch (e: any) {
|
||||
sendFeedback(`Failed to discard session: ${e.message}`);
|
||||
sendFeedback(`Failed to discard session: ${e.message}`, room, userId);
|
||||
}
|
||||
},
|
||||
},
|
||||
// Sharing E2EE History of a room with a user
|
||||
[Command.ShareE2EEHistory]: {
|
||||
name: Command.ShareE2EEHistory,
|
||||
description:
|
||||
'Share E2EE history (MSC4268) of this room with a user. Example: /sharee2eehistory @user:example.org',
|
||||
exe: async (payload) => {
|
||||
const targetUserId = payload.trim();
|
||||
const { roomId } = room;
|
||||
if (!enableMSC4268CMD) {
|
||||
sendFeedback(
|
||||
'This command is disabled. Enable it under experimental settings to use it.',
|
||||
room,
|
||||
mx.getSafeUserId()
|
||||
);
|
||||
return;
|
||||
}
|
||||
if (!targetUserId) {
|
||||
sendFeedback('Usage: /sharee2eehistory @user:example.org', room, mx.getSafeUserId());
|
||||
return;
|
||||
}
|
||||
const crypto = mx.getCrypto();
|
||||
if (!crypto) {
|
||||
sendFeedback('Encryption is not enabled on this client.', room, mx.getSafeUserId());
|
||||
return;
|
||||
}
|
||||
crypto
|
||||
.shareRoomHistoryWithUser(roomId, targetUserId)
|
||||
.then(() => {
|
||||
sendFeedback(
|
||||
`E2EE history shared with ${targetUserId}. (Their client needs to support MSC4268)`,
|
||||
room,
|
||||
mx.getSafeUserId()
|
||||
);
|
||||
})
|
||||
.catch((e) => {
|
||||
sendFeedback(`Failed to share E2EE history: ${e.message}`, room, mx.getSafeUserId());
|
||||
});
|
||||
},
|
||||
},
|
||||
// Cute Events
|
||||
[Command.Hug]: {
|
||||
name: Command.Hug,
|
||||
@@ -1393,7 +1304,16 @@ export const useCommands = (mx: MatrixClient, room: Room): CommandRecord => {
|
||||
},
|
||||
},
|
||||
}),
|
||||
[mx, navigateRoom, room, profile.displayName, profile.avatarUrl, developerTools, openBugReport]
|
||||
[
|
||||
mx,
|
||||
navigateRoom,
|
||||
room,
|
||||
profile.displayName,
|
||||
profile.avatarUrl,
|
||||
developerTools,
|
||||
enableMSC4268CMD,
|
||||
openBugReport,
|
||||
]
|
||||
);
|
||||
|
||||
return commands;
|
||||
|
||||
@@ -0,0 +1,100 @@
|
||||
import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest';
|
||||
import { renderHook, act } from '@testing-library/react';
|
||||
import { useDebounce } from './useDebounce';
|
||||
|
||||
beforeEach(() => {
|
||||
vi.useFakeTimers();
|
||||
});
|
||||
|
||||
afterEach(() => {
|
||||
vi.useRealTimers();
|
||||
});
|
||||
|
||||
describe('useDebounce', () => {
|
||||
it('does not call callback before wait time elapses', () => {
|
||||
const fn = vi.fn();
|
||||
const { result } = renderHook(() => useDebounce(fn, { wait: 200 }));
|
||||
|
||||
act(() => {
|
||||
result.current('a');
|
||||
});
|
||||
|
||||
act(() => {
|
||||
vi.advanceTimersByTime(199);
|
||||
});
|
||||
|
||||
expect(fn).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it('calls callback after wait time elapses', () => {
|
||||
const fn = vi.fn();
|
||||
const { result } = renderHook(() => useDebounce(fn, { wait: 200 }));
|
||||
|
||||
act(() => {
|
||||
result.current('a');
|
||||
});
|
||||
|
||||
act(() => {
|
||||
vi.advanceTimersByTime(200);
|
||||
});
|
||||
|
||||
expect(fn).toHaveBeenCalledOnce();
|
||||
expect(fn).toHaveBeenCalledWith('a');
|
||||
});
|
||||
|
||||
it('resets the timer on each successive call', () => {
|
||||
const fn = vi.fn();
|
||||
const { result } = renderHook(() => useDebounce(fn, { wait: 200 }));
|
||||
|
||||
act(() => {
|
||||
result.current('first');
|
||||
});
|
||||
|
||||
act(() => {
|
||||
vi.advanceTimersByTime(150);
|
||||
result.current('second');
|
||||
});
|
||||
|
||||
// 150ms into the reset timer — should not have fired yet
|
||||
act(() => {
|
||||
vi.advanceTimersByTime(150);
|
||||
});
|
||||
|
||||
expect(fn).not.toHaveBeenCalled();
|
||||
|
||||
// Complete the 200ms wait after the second call
|
||||
act(() => {
|
||||
vi.advanceTimersByTime(50);
|
||||
});
|
||||
|
||||
expect(fn).toHaveBeenCalledOnce();
|
||||
expect(fn).toHaveBeenCalledWith('second');
|
||||
});
|
||||
|
||||
it('only fires once after rapid successive calls', () => {
|
||||
const fn = vi.fn();
|
||||
const { result } = renderHook(() => useDebounce(fn, { wait: 100 }));
|
||||
|
||||
act(() => {
|
||||
result.current(1);
|
||||
result.current(2);
|
||||
result.current(3);
|
||||
vi.advanceTimersByTime(100);
|
||||
});
|
||||
|
||||
expect(fn).toHaveBeenCalledOnce();
|
||||
expect(fn).toHaveBeenCalledWith(3);
|
||||
});
|
||||
|
||||
it('fires immediately on first call when immediate option is set', () => {
|
||||
const fn = vi.fn();
|
||||
const { result } = renderHook(() => useDebounce(fn, { wait: 200, immediate: true }));
|
||||
|
||||
act(() => {
|
||||
result.current('go');
|
||||
});
|
||||
|
||||
expect(fn).toHaveBeenCalledOnce();
|
||||
expect(fn).toHaveBeenCalledWith('go');
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,51 @@
|
||||
// Integration tests: renders a real React component tree via renderHook.
|
||||
import { describe, it, expect } from 'vitest';
|
||||
import { renderHook } from '@testing-library/react';
|
||||
import { usePreviousValue } from './usePreviousValue';
|
||||
|
||||
describe('usePreviousValue', () => {
|
||||
it('returns the initial value on the first render', () => {
|
||||
const { result } = renderHook(() => usePreviousValue('current', 'initial'));
|
||||
expect(result.current).toBe('initial');
|
||||
});
|
||||
|
||||
it('returns the previous value after a prop update', () => {
|
||||
const { result, rerender } = renderHook(
|
||||
({ value }: { value: string }) => usePreviousValue(value, 'initial'),
|
||||
{ initialProps: { value: 'first' } }
|
||||
);
|
||||
|
||||
// Before any update: returns initial
|
||||
expect(result.current).toBe('initial');
|
||||
|
||||
rerender({ value: 'second' });
|
||||
expect(result.current).toBe('first');
|
||||
|
||||
rerender({ value: 'third' });
|
||||
expect(result.current).toBe('second');
|
||||
});
|
||||
|
||||
it('works with numeric values', () => {
|
||||
const { result, rerender } = renderHook(({ n }: { n: number }) => usePreviousValue(n, 0), {
|
||||
initialProps: { n: 1 },
|
||||
});
|
||||
|
||||
expect(result.current).toBe(0);
|
||||
rerender({ n: 42 });
|
||||
expect(result.current).toBe(1);
|
||||
});
|
||||
|
||||
it('works with object values (reference equality)', () => {
|
||||
const a = { x: 1 };
|
||||
const b = { x: 2 };
|
||||
|
||||
const { result, rerender } = renderHook(
|
||||
({ obj }: { obj: { x: number } }) => usePreviousValue(obj, a),
|
||||
{ initialProps: { obj: a } }
|
||||
);
|
||||
|
||||
expect(result.current).toBe(a);
|
||||
rerender({ obj: b });
|
||||
expect(result.current).toBe(a);
|
||||
});
|
||||
});
|
||||
@@ -27,16 +27,16 @@ export const resolveWidgetUrl = (
|
||||
const theme = document.body.classList.contains('dark-theme') ? 'dark' : 'light';
|
||||
|
||||
let resolved = url
|
||||
.replace(/\$matrix_user_id/g, encodeURIComponent(userId))
|
||||
.replace(/\$matrix_room_id/g, encodeURIComponent(roomId))
|
||||
.replace(/\$matrix_display_name/g, encodeURIComponent(displayName))
|
||||
.replace(/\$matrix_avatar_url/g, encodeURIComponent(avatarUrl))
|
||||
.replace(/\$matrix_widget_id/g, encodeURIComponent(widgetId))
|
||||
.replace(/\$org\.matrix\.msc2873\.client_id/g, encodeURIComponent(clientId))
|
||||
.replace(/\$org\.matrix\.msc2873\.client_theme/g, encodeURIComponent(theme))
|
||||
.replace(/\$org\.matrix\.msc2873\.client_language/g, encodeURIComponent(lang))
|
||||
.replace(/\$org\.matrix\.msc3819\.matrix_device_id/g, encodeURIComponent(deviceId))
|
||||
.replace(/\$org\.matrix\.msc4039\.matrix_base_url/g, encodeURIComponent(baseUrl));
|
||||
.replaceAll('$matrix_user_id', encodeURIComponent(userId))
|
||||
.replaceAll('$matrix_room_id', encodeURIComponent(roomId))
|
||||
.replaceAll('$matrix_display_name', encodeURIComponent(displayName))
|
||||
.replaceAll('$matrix_avatar_url', encodeURIComponent(avatarUrl))
|
||||
.replaceAll('$matrix_widget_id', encodeURIComponent(widgetId))
|
||||
.replaceAll('$org.matrix.msc2873.client_id', encodeURIComponent(clientId))
|
||||
.replaceAll('$org.matrix.msc2873.client_theme', encodeURIComponent(theme))
|
||||
.replaceAll('$org.matrix.msc2873.client_language', encodeURIComponent(lang))
|
||||
.replaceAll('$org.matrix.msc3819.matrix_device_id', encodeURIComponent(deviceId))
|
||||
.replaceAll('$org.matrix.msc4039.matrix_base_url', encodeURIComponent(baseUrl));
|
||||
|
||||
try {
|
||||
const u = new URL(resolved);
|
||||
@@ -112,7 +112,7 @@ export const useRoomWidgets = (room: Room): RoomWidget[] => {
|
||||
|
||||
return events.reduce<RoomWidget[]>((widgets, event) => {
|
||||
const content = event.getContent();
|
||||
if (!content || !content.url || Object.keys(content).length === 0) return widgets;
|
||||
if (!content?.url || Object.keys(content).length === 0) return widgets;
|
||||
|
||||
const stateKey = event.getStateKey();
|
||||
if (!stateKey) return widgets;
|
||||
|
||||
@@ -0,0 +1,92 @@
|
||||
import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest';
|
||||
import { renderHook, act } from '@testing-library/react';
|
||||
import { useThrottle } from './useThrottle';
|
||||
|
||||
beforeEach(() => {
|
||||
vi.useFakeTimers();
|
||||
});
|
||||
|
||||
afterEach(() => {
|
||||
vi.useRealTimers();
|
||||
});
|
||||
|
||||
describe('useThrottle', () => {
|
||||
it('fires once after the wait period even when called multiple times', () => {
|
||||
const fn = vi.fn();
|
||||
const { result } = renderHook(() => useThrottle(fn, { wait: 200 }));
|
||||
|
||||
act(() => {
|
||||
result.current('a');
|
||||
result.current('b');
|
||||
result.current('c');
|
||||
});
|
||||
|
||||
expect(fn).not.toHaveBeenCalled();
|
||||
|
||||
act(() => {
|
||||
vi.advanceTimersByTime(200);
|
||||
});
|
||||
|
||||
expect(fn).toHaveBeenCalledOnce();
|
||||
});
|
||||
|
||||
it('fires with the latest args when called multiple times within the wait', () => {
|
||||
const fn = vi.fn();
|
||||
const { result } = renderHook(() => useThrottle(fn, { wait: 200 }));
|
||||
|
||||
act(() => {
|
||||
result.current('first');
|
||||
result.current('second');
|
||||
result.current('third');
|
||||
});
|
||||
|
||||
act(() => {
|
||||
vi.advanceTimersByTime(200);
|
||||
});
|
||||
|
||||
expect(fn).toHaveBeenCalledWith('third');
|
||||
});
|
||||
|
||||
it('does not fire before the wait period ends', () => {
|
||||
const fn = vi.fn();
|
||||
const { result } = renderHook(() => useThrottle(fn, { wait: 300 }));
|
||||
|
||||
act(() => {
|
||||
result.current('x');
|
||||
vi.advanceTimersByTime(299);
|
||||
});
|
||||
|
||||
expect(fn).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it('allows a new invocation after the wait period resets', () => {
|
||||
const fn = vi.fn();
|
||||
const { result } = renderHook(() => useThrottle(fn, { wait: 100 }));
|
||||
|
||||
act(() => {
|
||||
result.current('first-burst');
|
||||
vi.advanceTimersByTime(100);
|
||||
});
|
||||
|
||||
act(() => {
|
||||
result.current('second-burst');
|
||||
vi.advanceTimersByTime(100);
|
||||
});
|
||||
|
||||
expect(fn).toHaveBeenCalledTimes(2);
|
||||
expect(fn).toHaveBeenNthCalledWith(1, 'first-burst');
|
||||
expect(fn).toHaveBeenNthCalledWith(2, 'second-burst');
|
||||
});
|
||||
|
||||
it('fires immediately on first call when immediate option is set', () => {
|
||||
const fn = vi.fn();
|
||||
const { result } = renderHook(() => useThrottle(fn, { wait: 200, immediate: true }));
|
||||
|
||||
act(() => {
|
||||
result.current('now');
|
||||
});
|
||||
|
||||
expect(fn).toHaveBeenCalledOnce();
|
||||
expect(fn).toHaveBeenCalledWith('now');
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,101 @@
|
||||
// Integration tests: uses fake timers to control setTimeout behaviour.
|
||||
import { describe, it, expect, beforeEach, afterEach, vi } from 'vitest';
|
||||
import { renderHook, act } from '@testing-library/react';
|
||||
import { useTimeoutToggle } from './useTimeoutToggle';
|
||||
|
||||
describe('useTimeoutToggle', () => {
|
||||
beforeEach(() => {
|
||||
vi.useFakeTimers();
|
||||
});
|
||||
|
||||
afterEach(() => {
|
||||
vi.useRealTimers();
|
||||
});
|
||||
|
||||
it('starts with the default initial value of false', () => {
|
||||
const { result } = renderHook(() => useTimeoutToggle());
|
||||
expect(result.current[0]).toBe(false);
|
||||
});
|
||||
|
||||
it('becomes true after trigger() is called', () => {
|
||||
const { result } = renderHook(() => useTimeoutToggle());
|
||||
act(() => {
|
||||
result.current[1]();
|
||||
});
|
||||
expect(result.current[0]).toBe(true);
|
||||
});
|
||||
|
||||
it('resets to false after the default 1500ms duration', () => {
|
||||
const { result } = renderHook(() => useTimeoutToggle());
|
||||
|
||||
act(() => {
|
||||
result.current[1]();
|
||||
});
|
||||
expect(result.current[0]).toBe(true);
|
||||
|
||||
act(() => {
|
||||
vi.advanceTimersByTime(1500);
|
||||
});
|
||||
expect(result.current[0]).toBe(false);
|
||||
});
|
||||
|
||||
it('does not reset before the duration has elapsed', () => {
|
||||
const { result } = renderHook(() => useTimeoutToggle(500));
|
||||
|
||||
act(() => {
|
||||
result.current[1]();
|
||||
});
|
||||
|
||||
act(() => {
|
||||
vi.advanceTimersByTime(499);
|
||||
});
|
||||
expect(result.current[0]).toBe(true);
|
||||
|
||||
act(() => {
|
||||
vi.advanceTimersByTime(1);
|
||||
});
|
||||
expect(result.current[0]).toBe(false);
|
||||
});
|
||||
|
||||
it('re-triggering before timeout resets the countdown', () => {
|
||||
const { result } = renderHook(() => useTimeoutToggle(1000));
|
||||
|
||||
act(() => {
|
||||
result.current[1](); // t=0: trigger
|
||||
});
|
||||
|
||||
act(() => {
|
||||
vi.advanceTimersByTime(800); // t=800
|
||||
});
|
||||
|
||||
act(() => {
|
||||
result.current[1](); // t=800: re-trigger, timer resets
|
||||
});
|
||||
|
||||
act(() => {
|
||||
vi.advanceTimersByTime(800); // t=1600 — only 800ms since re-trigger
|
||||
});
|
||||
expect(result.current[0]).toBe(true); // still active
|
||||
|
||||
act(() => {
|
||||
vi.advanceTimersByTime(200); // t=1800 — 1000ms since re-trigger
|
||||
});
|
||||
expect(result.current[0]).toBe(false);
|
||||
});
|
||||
|
||||
it('supports a custom initial value of true (inverted toggle)', () => {
|
||||
const { result } = renderHook(() => useTimeoutToggle(1500, true));
|
||||
|
||||
expect(result.current[0]).toBe(true);
|
||||
|
||||
act(() => {
|
||||
result.current[1](); // trigger → false
|
||||
});
|
||||
expect(result.current[0]).toBe(false);
|
||||
|
||||
act(() => {
|
||||
vi.advanceTimersByTime(1500); // resets back to true
|
||||
});
|
||||
expect(result.current[0]).toBe(true);
|
||||
});
|
||||
});
|
||||
@@ -27,7 +27,7 @@ export type UserProfile = {
|
||||
};
|
||||
|
||||
const normalizeInfo = (info: any): UserProfile => {
|
||||
const knownKeys = [
|
||||
const knownKeys = new Set([
|
||||
'avatar_url',
|
||||
'displayname',
|
||||
'io.fsky.nyx.pronouns',
|
||||
@@ -40,11 +40,11 @@ const normalizeInfo = (info: any): UserProfile => {
|
||||
'moe.sable.app.name_color',
|
||||
'kitty.meow.has_cats',
|
||||
'kitty.meow.is_cat',
|
||||
];
|
||||
]);
|
||||
|
||||
const extended: Record<string, any> = {};
|
||||
Object.entries(info).forEach(([key, value]) => {
|
||||
if (!knownKeys.includes(key)) {
|
||||
if (!knownKeys.has(key)) {
|
||||
extended[key] = value;
|
||||
}
|
||||
});
|
||||
@@ -68,10 +68,10 @@ const normalizeInfo = (info: any): UserProfile => {
|
||||
const isValidHex = (c: any): string | undefined => {
|
||||
if (typeof c !== 'string') return undefined;
|
||||
// silly tuwunel smh
|
||||
const cleaned = c.replace(/["']/g, '').trim();
|
||||
const cleaned = c.replaceAll(/["']/g, '').trim();
|
||||
return /^#([0-9A-F]{3,6})$/i.test(cleaned) ? cleaned : undefined;
|
||||
};
|
||||
const sanitizeFont = (f: string) => f.replace(/[;{}<>]/g, '').slice(0, 32);
|
||||
const sanitizeFont = (f: string) => f.replaceAll(/[;{}<>]/g, '').slice(0, 32);
|
||||
|
||||
export const useUserProfile = (
|
||||
userId: string,
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
import { useCallback, useEffect } from 'react';
|
||||
import { Box, Header, Scroll, Spinner, Text, color } from 'folds';
|
||||
import { Box, Chip, Header, Scroll, Spinner, Text, color } from 'folds';
|
||||
import {
|
||||
Outlet,
|
||||
generatePath,
|
||||
@@ -22,6 +22,7 @@ import { AuthFlowsLoader } from '$components/AuthFlowsLoader';
|
||||
import { AuthFlowsProvider } from '$hooks/useAuthFlows';
|
||||
import { AuthServerProvider } from '$hooks/useAuthServer';
|
||||
import { LOGIN_PATH, REGISTER_PATH, RESET_PASSWORD_PATH } from '$pages/paths';
|
||||
import { getHomePath } from '$pages/pathUtils';
|
||||
import { AutoDiscoveryAction, autoDiscovery } from '../../cs-api';
|
||||
import { ServerPicker } from './ServerPicker';
|
||||
import * as css from './styles.css';
|
||||
@@ -139,9 +140,18 @@ export function AuthLayout() {
|
||||
<Text size="H3">Sable</Text>
|
||||
</Box>
|
||||
{isAddingAccount && (
|
||||
<Text size="T200" priority="300" style={{ marginLeft: 'auto', marginRight: 4 }}>
|
||||
Adding account
|
||||
</Text>
|
||||
<Box gap="200" alignItems="Center" style={{ marginLeft: 'auto' }}>
|
||||
<Text size="T200" priority="300">
|
||||
Adding account
|
||||
</Text>
|
||||
<Chip
|
||||
variant="Surface"
|
||||
radii="300"
|
||||
onClick={() => window.location.assign(getHomePath())}
|
||||
>
|
||||
<Text size="T200">Cancel</Text>
|
||||
</Chip>
|
||||
</Box>
|
||||
)}
|
||||
</Header>
|
||||
<Box className={css.AuthCardContent} direction="Column">
|
||||
|
||||
@@ -1,5 +1,6 @@
|
||||
import {
|
||||
ChangeEventHandler,
|
||||
FocusEventHandler,
|
||||
KeyboardEventHandler,
|
||||
MouseEventHandler,
|
||||
useEffect,
|
||||
@@ -37,10 +38,16 @@ export function ServerPicker({
|
||||
}) {
|
||||
const [serverMenuAnchor, setServerMenuAnchor] = useState<RectCords>();
|
||||
const serverInputRef = useRef<HTMLInputElement>(null);
|
||||
const inputFocusedRef = useRef(false);
|
||||
|
||||
useEffect(() => {
|
||||
// sync input with it outside server changes
|
||||
if (serverInputRef.current && serverInputRef.current.value !== server) {
|
||||
// sync input with outside server changes, but only when not focused
|
||||
// (on iOS, syncing while focused causes the deleted text to reappear)
|
||||
if (
|
||||
!inputFocusedRef.current &&
|
||||
serverInputRef.current &&
|
||||
serverInputRef.current.value !== server
|
||||
) {
|
||||
serverInputRef.current.value = server;
|
||||
}
|
||||
}, [server]);
|
||||
@@ -52,6 +59,18 @@ export function ServerPicker({
|
||||
if (inputServer) debounceServerSelect(inputServer);
|
||||
};
|
||||
|
||||
const handleInputFocus: FocusEventHandler<HTMLInputElement> = () => {
|
||||
inputFocusedRef.current = true;
|
||||
};
|
||||
|
||||
const handleInputBlur: FocusEventHandler<HTMLInputElement> = () => {
|
||||
inputFocusedRef.current = false;
|
||||
// restore the server value if the input was cleared without selecting a new one
|
||||
if (serverInputRef.current && serverInputRef.current.value.trim() === '') {
|
||||
serverInputRef.current.value = server;
|
||||
}
|
||||
};
|
||||
|
||||
const handleKeyDown: KeyboardEventHandler<HTMLInputElement> = (evt) => {
|
||||
if (evt.key === 'ArrowDown') {
|
||||
evt.preventDefault();
|
||||
@@ -86,6 +105,8 @@ export function ServerPicker({
|
||||
defaultValue={server}
|
||||
onChange={handleServerChange}
|
||||
onKeyDown={handleKeyDown}
|
||||
onFocus={handleInputFocus}
|
||||
onBlur={handleInputBlur}
|
||||
size="500"
|
||||
readOnly={!allowCustomServer}
|
||||
onClick={allowCustomServer ? undefined : handleOpenServerMenu}
|
||||
|
||||
@@ -99,6 +99,7 @@ function PageZoomFeature() {
|
||||
function FaviconUpdater() {
|
||||
const roomToUnread = useAtomValue(roomToUnreadAtom);
|
||||
const [usePushNotifications] = useSetting(settingsAtom, 'usePushNotifications');
|
||||
const [faviconForMentionsOnly] = useSetting(settingsAtom, 'faviconForMentionsOnly');
|
||||
const registration = useAtomValue(registrationAtom);
|
||||
|
||||
useEffect(() => {
|
||||
@@ -119,8 +120,10 @@ function FaviconUpdater() {
|
||||
}
|
||||
});
|
||||
|
||||
if (notification) {
|
||||
setFavicon(highlight ? LogoHighlightSVG : LogoUnreadSVG);
|
||||
if (highlight) {
|
||||
setFavicon(LogoHighlightSVG);
|
||||
} else if (!faviconForMentionsOnly && notification) {
|
||||
setFavicon(LogoUnreadSVG);
|
||||
} else {
|
||||
setFavicon(LogoSVG);
|
||||
}
|
||||
@@ -153,7 +156,7 @@ function FaviconUpdater() {
|
||||
} catch {
|
||||
// Likely Firefox/Gecko-based and doesn't support badging API
|
||||
}
|
||||
}, [roomToUnread, usePushNotifications, registration]);
|
||||
}, [roomToUnread, usePushNotifications, registration, faviconForMentionsOnly]);
|
||||
|
||||
return null;
|
||||
}
|
||||
|
||||
Loaded 100 of 135 files, more files were not shown because too many files have changed in this diff.
Show more
Reference in new issue
Block a user