diff --git a/.changeset/add-new-logo.md b/.changeset/add-new-logo.md new file mode 100644 index 000000000..f706f3bac --- /dev/null +++ b/.changeset/add-new-logo.md @@ -0,0 +1,9 @@ +--- +default: minor +--- + +# Introduce the new Sable logo! + +- You may need to reinstall PWAs to recieve the new app icons, if you use them. +- Our logo is [licensed under CC0](https://github.com/SableClient/Sable/blob/dev/TRADEMARKS.md), aka do whatever you want with it! +- Also, there's a script for other us or other forks to replace the icon in the future, if needed. diff --git a/.changeset/add-room-banner-support.md b/.changeset/add-room-banner-support.md new file mode 100644 index 000000000..57ffeb749 --- /dev/null +++ b/.changeset/add-room-banner-support.md @@ -0,0 +1,5 @@ +--- +default: minor +--- + +Add Space banner support per MSC4221. You can now set it from the space settings. diff --git a/.changeset/add_better_misc_data_styling.md b/.changeset/add_better_misc_data_styling.md deleted file mode 100644 index 70e10a2bb..000000000 --- a/.changeset/add_better_misc_data_styling.md +++ /dev/null @@ -1,5 +0,0 @@ ---- -default: fix ---- - -Fix spam-clicking abbreviations crashing sable diff --git a/.changeset/add_graceful_fail_if_msc4140_event_delay_exceeded.md b/.changeset/add_graceful_fail_if_msc4140_event_delay_exceeded.md new file mode 100644 index 000000000..f7c79c885 --- /dev/null +++ b/.changeset/add_graceful_fail_if_msc4140_event_delay_exceeded.md @@ -0,0 +1,5 @@ +--- +default: patch +--- + +Add graceful fail if MSC4140 event delay exceeded diff --git a/.changeset/add_icons_to_room_sidebar.md b/.changeset/add_icons_to_room_sidebar.md new file mode 100644 index 000000000..6487cf2de --- /dev/null +++ b/.changeset/add_icons_to_room_sidebar.md @@ -0,0 +1,5 @@ +--- +default: minor +--- + +Add setting to show icons of the rooms in the Rooms sidebar diff --git a/.changeset/add_multiple_previews.md b/.changeset/add_multiple_previews.md deleted file mode 100644 index 7e1d70782..000000000 --- a/.changeset/add_multiple_previews.md +++ /dev/null @@ -1,5 +0,0 @@ ---- -default: minor ---- - -Reorganize Embed settings and reintroduce multiple embeds diff --git a/.changeset/add_resize-side-panel.md b/.changeset/add_resize-side-panel.md new file mode 100644 index 000000000..0dfb59b64 --- /dev/null +++ b/.changeset/add_resize-side-panel.md @@ -0,0 +1,5 @@ +--- +default: minor +--- + +Add Resize the sidepanels and the thread height of the original object using hoverable tools. diff --git a/.changeset/add_toggle_to_not_join_room_on_initial_click.md b/.changeset/add_toggle_to_not_join_room_on_initial_click.md new file mode 100644 index 000000000..ea6aa750e --- /dev/null +++ b/.changeset/add_toggle_to_not_join_room_on_initial_click.md @@ -0,0 +1,5 @@ +--- +default: minor +--- + +Add toggle to allow one to not join a call in a room by just clicking it in the sidebar. diff --git a/.changeset/better_misc_data_styling.md b/.changeset/better_misc_data_styling.md deleted file mode 100644 index b71cd2949..000000000 --- a/.changeset/better_misc_data_styling.md +++ /dev/null @@ -1,5 +0,0 @@ ---- -default: minor ---- - -Change Misc. data styling in users profile pages diff --git a/.changeset/caddy-cache-headers.md b/.changeset/caddy-cache-headers.md deleted file mode 100644 index 498db7463..000000000 --- a/.changeset/caddy-cache-headers.md +++ /dev/null @@ -1,5 +0,0 @@ ---- -default: patch ---- - -Add cache-control headers in Caddyfile for assets, service worker, and index.html diff --git a/.changeset/change-settings-link-markers.md b/.changeset/change-settings-link-markers.md deleted file mode 100644 index fba906673..000000000 --- a/.changeset/change-settings-link-markers.md +++ /dev/null @@ -1,13 +0,0 @@ ---- -default: patch ---- - -# Change how settings links are shared - -Settings links copied from Sable now stay on the current client URL and include a small Sable marker in the link. That lets Sable recognize settings links copied from other Sable instances without treating unrelated third-party `/settings/...` links as Sable settings links. - -When you send a bare settings link in the composer, Sable now rewrites it into a labeled link so it looks better on non-Sable clients too. For example: `[Settings > Account > Display Name](https://client.example/settings/account?focus=display-name&moe.sable.client.action=settings)`. - -Invalid or malformed settings-looking links now stay normal links instead of being shown as settings chips. - -If you previously set `settingsLinkBaseUrl` in `config.json`, remove it. Sable now derives settings links from the runtime app URL, and the old config key is no longer used. diff --git a/.changeset/feat_right_click_rename_folder.md b/.changeset/feat_right_click_rename_folder.md new file mode 100644 index 000000000..4d34eef28 --- /dev/null +++ b/.changeset/feat_right_click_rename_folder.md @@ -0,0 +1,5 @@ +--- +default: minor +--- + +Added the ability to right click on a folder to rename it. diff --git a/.changeset/fix-drop-redundant-paragraph.md b/.changeset/fix-drop-redundant-paragraph.md new file mode 100644 index 000000000..44403dfd5 --- /dev/null +++ b/.changeset/fix-drop-redundant-paragraph.md @@ -0,0 +1,5 @@ +--- +default: patch +--- + +Drops paragraph tags when messages are only a single paragraph, use markdown (two new lines) to define a new paragraph rather than a line break. diff --git a/.changeset/fix-fallback-body-styling.md b/.changeset/fix-fallback-body-styling.md new file mode 100644 index 000000000..9c80bbcd0 --- /dev/null +++ b/.changeset/fix-fallback-body-styling.md @@ -0,0 +1,5 @@ +--- +default: patch +--- + +Fixed the text wrapping behavior of fallback messages. diff --git a/.changeset/fix-initial-pins.md b/.changeset/fix-initial-pins.md deleted file mode 100644 index 424daeb28..000000000 --- a/.changeset/fix-initial-pins.md +++ /dev/null @@ -1,5 +0,0 @@ ---- -default: patch ---- - -Fix the first pin event in a room looking empty diff --git a/.changeset/fix-line-on-profiles.md b/.changeset/fix-line-on-profiles.md new file mode 100644 index 000000000..576bc6e2f --- /dev/null +++ b/.changeset/fix-line-on-profiles.md @@ -0,0 +1,5 @@ +--- +default: patch +--- + +Fixed the thin line appearing at the top of unstyled profiles. diff --git a/.changeset/fix-matrix-to-link-wrapping.md b/.changeset/fix-matrix-to-link-wrapping.md new file mode 100644 index 000000000..ef186b922 --- /dev/null +++ b/.changeset/fix-matrix-to-link-wrapping.md @@ -0,0 +1,5 @@ +--- +default: patch +--- + +Matrix.to links sent without explicit markdown formatting are sent as raw links instead of html links. diff --git a/.changeset/fix-modal-layout-thing.md b/.changeset/fix-modal-layout-thing.md new file mode 100644 index 000000000..39e911ef6 --- /dev/null +++ b/.changeset/fix-modal-layout-thing.md @@ -0,0 +1,5 @@ +--- +default: minor +--- + +Upgraded the forward modal to use the same modal present for search and added the ability to forward to same room the message is from. diff --git a/.changeset/fix-myroomnick.md b/.changeset/fix-myroomnick.md new file mode 100644 index 000000000..44b1e41e9 --- /dev/null +++ b/.changeset/fix-myroomnick.md @@ -0,0 +1,5 @@ +--- +default: patch +--- + +Fix `/myroomnick` and room cosmetics display name not updating name. diff --git a/.changeset/fix-spoiler-hides-mentions-and-images.md b/.changeset/fix-spoiler-hides-mentions-and-images.md new file mode 100644 index 000000000..cf52327b5 --- /dev/null +++ b/.changeset/fix-spoiler-hides-mentions-and-images.md @@ -0,0 +1,5 @@ +--- +default: patch +--- + +Fix spoilers not hiding nested content like mentions, emoji images, and custom-colored spans. diff --git a/.changeset/fix-status-sticking-issue.md b/.changeset/fix-status-sticking-issue.md deleted file mode 100644 index c954c09ca..000000000 --- a/.changeset/fix-status-sticking-issue.md +++ /dev/null @@ -1,5 +0,0 @@ ---- -default: patch ---- - -Fix status sometimes sticking in member tile diff --git a/.changeset/fix-svg-embeds.md b/.changeset/fix-svg-embeds.md new file mode 100644 index 000000000..8b4f6bf8a --- /dev/null +++ b/.changeset/fix-svg-embeds.md @@ -0,0 +1,5 @@ +--- +default: patch +--- + +Added svgs to the allowed embeds for rendering/sending. diff --git a/.changeset/msc4454.md b/.changeset/msc4454.md deleted file mode 100644 index af548e99e..000000000 --- a/.changeset/msc4454.md +++ /dev/null @@ -1,5 +0,0 @@ ---- -default: patch ---- - -spoilered text now gets replaced with `[Spoiler]` in the plain text fallback, as per MSC4454 diff --git a/.changeset/remove-dynamic-settings-links.md b/.changeset/remove-dynamic-settings-links.md deleted file mode 100644 index 93a2d76e5..000000000 --- a/.changeset/remove-dynamic-settings-links.md +++ /dev/null @@ -1,5 +0,0 @@ ---- -default: patch ---- - -# Hide copied settings links on dynamic rows diff --git a/.changeset/thread-drawer-root-separator.md b/.changeset/thread-drawer-root-separator.md new file mode 100644 index 000000000..f474a72f5 --- /dev/null +++ b/.changeset/thread-drawer-root-separator.md @@ -0,0 +1,5 @@ +--- +default: patch +--- + +Improve thread drawer separation between the pinned root message and replies with a border. diff --git a/.changeset/vlist-hover-transform.md b/.changeset/vlist-hover-transform.md deleted file mode 100644 index bb580175d..000000000 --- a/.changeset/vlist-hover-transform.md +++ /dev/null @@ -1,5 +0,0 @@ ---- -default: patch ---- - -Fix button hover background smearing in virtual list rows by suppressing transform on hover diff --git a/.changeset/workbox-precaching.md b/.changeset/workbox-precaching.md deleted file mode 100644 index 2537469a5..000000000 --- a/.changeset/workbox-precaching.md +++ /dev/null @@ -1,5 +0,0 @@ ---- -default: patch ---- - -Fix Workbox precaching by removing injectionPoint override that was silently disabling all precache entries diff --git a/.github/workflows/flake-lock-fix.yml b/.github/workflows/flake-lock-fix.yml new file mode 100644 index 000000000..39447cfa5 --- /dev/null +++ b/.github/workflows/flake-lock-fix.yml @@ -0,0 +1,68 @@ +name: Fix flake hashes + +on: + workflow_dispatch: + push: + branches: [dev] + paths: ['pnpm-lock.yaml'] + +jobs: + fix: + name: Fix flake hashes + runs-on: ubuntu-latest + permissions: + id-token: write + contents: write + steps: + - name: Generate bot token + id: app-token + uses: actions/create-github-app-token@f8d387b68d61c58ab83c6c016672934102569859 + with: + app-id: ${{ secrets.APP_ID }} + private-key: ${{ secrets.APP_PRIVATE_KEY }} + permission-contents: write + + - name: Checkout dev + uses: actions/checkout@de0fac2e4500dabe0009e67214ff5f5447ce83dd # v6.0.2 + with: + ref: dev + persist-credentials: true + token: ${{ steps.app-token.outputs.token }} + + - name: Install Determinate Nix + uses: DeterminateSystems/determinate-nix-action@bafaa638b9d5ec0e7e3ac1a7fc80453ef1fd265f # v3.20.0 + + - id: check + run: nix flake check -L + continue-on-error: true + + - name: Fix hash mismatches + if: steps.check.outcome == 'failure' + run: determinate-nixd fix hashes --auto-apply + + - name: Get GitHub App User ID + id: get-user-id + run: echo "user-id=$(gh api "/users/${{ steps.app-token.outputs.app-slug }}[bot]" --jq .id)" >> "$GITHUB_OUTPUT" + env: + GH_TOKEN: ${{ steps.app-token.outputs.token }} + + - name: Configure bot git identity + run: | + git config --global user.name '${{ steps.app-token.outputs.app-slug }}[bot]' + git config --global user.email '${{ steps.get-user-id.outputs.user-id }}+${{ steps.app-token.outputs.app-slug }}[bot]@users.noreply.github.com' + gh auth setup-git + env: + GH_TOKEN: ${{ steps.app-token.outputs.token }} + + - name: Commit and push if changed + if: steps.check.outcome == 'failure' + shell: bash + run: | + set -euo pipefail + if git diff --quiet; then + echo "No changes after fix hashes; nothing to commit." + exit 0 + fi + git add --update --ignore-removal . + git commit -m "chore(nix): auto-fix nix hashes" + git push origin HEAD:dev --force-with-lease diff --git a/.github/workflows/prepare-release.yml b/.github/workflows/prepare-release.yml index e88da3a79..ad10769fd 100644 --- a/.github/workflows/prepare-release.yml +++ b/.github/workflows/prepare-release.yml @@ -53,7 +53,7 @@ jobs: }); const pr = prs.data[0]; return pr - ? `([#${pr.number}](${pr.html_url}) by @${pr.user.login})` + ? `([#${pr.number}](<${pr.html_url}>) by @${pr.user.login})` : `(\`${hash}\`)`; } catch { return `(\`${hash}\`)`; diff --git a/.gitignore b/.gitignore index 7ec719709..76af75542 100644 --- a/.gitignore +++ b/.gitignore @@ -26,3 +26,12 @@ build.sh # the following line was added with nvim by Shea because its annoying to clear every so often .vscode/bookmarks.json + +# Nix things +## nix build output +result +## direnv config + local state +.envrc +.direnv +## auto-generated pre-commit config +.pre-commit-config.yaml diff --git a/.vscode/settings.json b/.vscode/settings.json index f2ceb43b5..60018f71d 100644 --- a/.vscode/settings.json +++ b/.vscode/settings.json @@ -12,5 +12,7 @@ }, "[json]": { "editor.defaultFormatter": "oxc.oxc-vscode" - } + }, + "nixEnvSelector.nixFile": "${workspaceFolder}/flake.nix", + "nixEnvSelector.useFlakes": true } diff --git a/CHANGELOG.md b/CHANGELOG.md index 5695f023c..973d89b59 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,5 +1,108 @@ # Sable Client Changelog +## 1.15.3 (2026-05-09) + +### Fixes + +* Self-hosted deployments can set optional `settingsDefaults` in `config.json` to override built-in client settings. See the README for details. ([#785]() by @7w1) +* Updated the math detection to avoid accidental detection when talking about math or spamming dollar signs. ([#779]() by @7w1) +* Added a couple new settings for max incoming inline image height and default height for unspecified. http://localhost:8080/settings/appearance?focus=incoming-inline-images-default-height&moe.sable.client.action=settings ([#772]() by @7w1) +* Fixed links with suppressed previews not having the arrow brackets readded when editing a message. ([#772]() by @7w1) +* Added the ability to cap preview embed size. http://localhost:8080/settings/appearance?focus=link-preview-image-max-height&moe.sable.client.action=settings ([#783]() by @7w1) +* Fix the inconsistent sizing for the read receipt dialog boxes. ([#772]() by @7w1) +* Fixed room avatars set in the settings cosmetics menu not applying. ([#772]() by @7w1) +* Fix room names being overriden when only 1 other person is in a room. ([#784]() by @7w1) +* Fix small text being parsed in code blocks and not being escapeable. ([#782]() by @7w1) +* Fixed the hang when a message that replies to a message has a reply, and you attempt to start a thread on that message. ([#778]() by @7w1) +* Fix RTL/LTR mixed text formatting and alignment in messages ([#743]() by @sinasadeghi83) +* Readded various missing settings from the settings sharing list. ([#765]() by @7w1) +* Various small adjustments to the themed profiles for better consistency. ([#777]() by @7w1) + +## 1.15.2 (2026-05-07) + +### Fixes + +* Adds back the message editor toolbar under an optional setting. No longer uses WYSIWYG, just applies markdown. http://localhost:8080/settings/general?focus=composer-formatting-toolbar&moe.sable.client.action=settings ([#762]() by @7w1) +* Fixed blockquotes needing a double backslash to escape and require a space after the `>` in order to form a blockquote. ([#758]() by @7w1) +* Fix empty messages being displayed as broken messages. ([#754]() by @7w1) +* Reescape arrow brackets when editing a message. ([#763]() by @7w1) +* Fix extraneous markdown escape characters when editing code blocks. ([#762]() by @7w1) +* Fixed jumpting to arbitrary events (e.g. reactions, edits, pins, leaves/joins). ([#759]() by @7w1) +* Fix latex in codeblocks getting parsed. ([#758]() by @7w1) +* Fixed message links being rendered as full links. ([#751]() by @7w1) +* Fixed per-message profile proxies not unwrapping and generally just not working. (`f8a9a8f`) +* Fixed tweak automatic favoriting behavior when entering/leaving the catalog. ([#757]() by @7w1) +* Fix tweaks not applying on built-in themes. ([#756]() by @7w1) +* Added the ability to **underline** using `__underscores__`. ([#761]() by @7w1) + +## 1.15.1 (2026-05-05) + +### Fixes + +* Fix editing messages with custom emojis being converted into html tags. ([#749](https://github.com/SableClient/Sable/pull/749) by @7w1) +* Fix muted rooms appearing as standard unread rooms. ([#750](https://github.com/SableClient/Sable/pull/750) by @7w1) +* Fix the call stack size crash on load when sliding sync is enabled. ([#748](https://github.com/SableClient/Sable/pull/748) by @7w1) + +## 1.15.0 (2026-05-05) + +### Features + +* Add background styling to user profile cards ([#712](https://github.com/SableClient/Sable/pull/712) by @nushea) +* Add preventing url preview cards by surrounding a link in anglebrackets like ([#717](https://github.com/SableClient/Sable/pull/717) by @nushea) +* Reorganize Embed settings and reintroduce multiple embeds ([#667](https://github.com/SableClient/Sable/pull/667) by @nushea) +* Change Misc. data styling in users profile pages ([#663](https://github.com/SableClient/Sable/pull/663) by @nushea) +* add initial support for sending discoverable emojis and sticker ([#730](https://github.com/SableClient/Sable/pull/730) by @dozro) + +#### Themes and tweaks from the catalog ([#633](https://github.com/SableClient/Sable/pull/633) by @7w1) + +Themes are pulled from [a repo](https://github.com/SableClient/themes) now, so you get the full power of CSS instead of a palette. Tweaks are new: CSS overlays that sit on top of whatever theme you are using. + +You'll be prompted to migrate to the new system whenever you update, if you choose not to, you'll be limited to the basic dark/light themes. A few additional themes have been added (Rose Pine variantes, Catpuccin) along with some basic tweaks (circular avatars, monochrome avatars, and square stuff). + +You can share themes and tweaks. For themes uploaded online, simply hit the copy button in settings and paste the link in chat. If the setting is enabled, a preview will be generated. Third party themes (as defined by the config.json) have prominent warning banners and fetching is disabled by default. + +You can also export and share theme files directly, although no previews are generated for these. + +If you're intrested in getting a theme or tweak added to the official catalog, contribute to the themes repo linked above! We're eager to add more! + +#### Markdown parser and render updates ([#727](https://github.com/SableClient/Sable/pull/727) by @7w1) + +Migrated markdown parsing and rendering to use marked, which should fix most (all?) markdown issues involving lists/nested structures, inconsistent/inaccurate code blocks, escape sequences, and all the other bugs with literally everything. + +Added math rendering support via marked and KaTeX, uses standard `$$` and `$` delimiters. Only renders a subset of latex tags that will likely need to be expanded so feel free to make issues if needed. + +Also adds support for sending markdown tables (although they're rendered rather plainly at the moment), sending valid html directly (such as for colored text), and properly escaping anything with backslashes. + +Fixes link previews appearing in code blocks, fixes pmp new line behavior, fixes links not opening in new tabs, and fixes editing arbitrary html messages, probably. + +Finally, the old WYSIWYG editor has been completely removed. + +### Fixes + +* Fix spam-clicking abbreviations crashing sable ([#665](https://github.com/SableClient/Sable/pull/665) by @nushea) +* Add cache-control headers in Caddyfile for assets, service worker, and index.html ([#609](https://github.com/SableClient/Sable/pull/609) by @Just-Insane) +* Fix the first pin event in a room looking empty ([#685](https://github.com/SableClient/Sable/pull/685) by @nushea) +* Fix read receipt scrolling not working ([#631](https://github.com/SableClient/Sable/pull/631) by @Septicity) +* Fix status sometimes sticking in member tile ([#664](https://github.com/SableClient/Sable/pull/664) by @nushea) +* Fix apng files not animating. ([#737](https://github.com/SableClient/Sable/pull/737) by @7w1) +* Some fixes to sync requests being spammed on loading screen and for multi-account background syncing, it should also load faster now! ([#736](https://github.com/SableClient/Sable/pull/736) by @7w1) +* Fix other dmed party not being added as a founder by default when creating a dm. ([#737](https://github.com/SableClient/Sable/pull/737) by @7w1) +* Update verbiage in the credits ([#728](https://github.com/SableClient/Sable/pull/728) by @nushea) +* spoilered text now gets replaced with `[Spoiler]` in the plain text fallback, as per MSC4454 ([#715](https://github.com/SableClient/Sable/pull/715) by @dozro) +* Hide copied settings links on dynamic rows ([#695](https://github.com/SableClient/Sable/pull/695) by @hazre) +* Fix button hover background smearing in virtual list rows by suppressing transform on hover ([#614](https://github.com/SableClient/Sable/pull/614) by @Just-Insane) +* Fix Workbox precaching by removing injectionPoint override that was silently disabling all precache entries ([#611](https://github.com/SableClient/Sable/pull/611) by @Just-Insane) + +#### Change how settings links are shared ([#695](https://github.com/SableClient/Sable/pull/695) by @hazre) + +Settings links copied from Sable now stay on the current client URL and include a small Sable marker in the link. That lets Sable recognize settings links copied from other Sable instances without treating unrelated third-party `/settings/...` links as Sable settings links. + +When you send a bare settings link in the composer, Sable now rewrites it into a labeled link so it looks better on non-Sable clients too. For example: `[Settings > Account > Display Name](https://client.example/settings/account?focus=display-name&moe.sable.client.action=settings)`. + +Invalid or malformed settings-looking links now stay normal links instead of being shown as settings chips. + +If you previously set `settingsLinkBaseUrl` in `config.json`, remove it. Sable now derives settings links from the runtime app URL, and the old config key is no longer used. + ## 1.14.0 (2026-04-10) ### Features diff --git a/README.md b/README.md index 2a1f7d853..6a2434955 100644 --- a/README.md +++ b/README.md @@ -62,6 +62,28 @@ After that, you can copy the dist/ directory to your server and serve it. * In the [`config.json`](config.json), you can modify the default homeservers, feature rooms/spaces, toggle the account switcher, and toggle experimental simplified slilding sync support. +#### Optional default client settings + +While the default settings are recommended for most users, you can optionally add a top-level `"settingsDefaults"` object whose keys match [client settings](src/app/state/settings.ts) (only fields you want to override) to override them. The default settings for any new logins will match these. Existing keys in local storage or users who chose to sync settings with their account data will still have their settings set. + +For example: + +```json +{ + "settingsDefaults": { + "hour24Clock": true, + "pageZoom": 110, + "messageLayout": 2, + "rightSwipeAction": "members", + "captionPosition": "below", + "renderUserCards": "both", + "jumboEmojiSize": "large" + } +} +``` + +Invalid or unknown keys are ignored. + * To deploy on subdirectory, you need to rebuild the app youself after updating the `base` path in [`build.config.ts`](build.config.ts). * For example, if you want to deploy on `https://sable.moe/app`, then set `base: '/app'`. diff --git a/TRADEMARKS.md b/TRADEMARKS.md new file mode 100644 index 000000000..b5ddb4aba --- /dev/null +++ b/TRADEMARKS.md @@ -0,0 +1,63 @@ +# Trademarks + +The Sable name and the Sable logo belong to the FOSS community. + +While our source code is governed by the GNU Affero General Public License (AGPLv3), we believe the Free and Open Source ethos shouldn't stop there. We actually like it when people use, share, and build upon our work. + +## Logo + +The Sable logo is dedicated to the public domain under the CC0 1.0 Universal (Public Domain Dedication). All rights waived. + +The logo may absolutely be: + +- Modified, distorted, or recolored +- Used as part of another logo or mark +- Given a tiny top hat, sunglasses, or a cool jacket +- Used more prominently than your own branding, if you really want to for some reason + +### Permitted Uses + +You are highly encouraged to: + +- Use the name “Sable” in text anywhere you like +- Link to the official repository or documentation +- State in plain text that your project is “based on Sable”, “a fork of Sable”, or “better than Sable” +- Use the name and logo when self-hosting, whether you modified the software or not +- Strip out our branding entirely and replace it with your own. If you’re hosting, you can do whatever you want! + +### Restricted Uses + +We only have two rules to protect the community. You may not: + +- Impersonate the core Sable maintainers or use the Sable name/logo to distribute malware or malicious software. +- Use the Sable name or logo to falsely claim that the core maintainers officially legally endorse your specific corporate product. + +That's literally it. + +## Requirements for Forks and Modifications + +If you modify or build upon the Sable source code: + +You must: + +- Comply with the AGPLv3 license terms (keep open source open!). + +You may: + +- Use the Sable name, logo, or branding in your project’s name or identity (e.g., "Sable-Enterprise", "Sable for Android", "Sable-Lite"). +- Create derivative, similar, or completely wild new logos based on ours. +- Distribute or package the software for platforms not officially supported by us using the Sable name. +- Take this trademark document and derive your own version of it, provided it's for your branding, rather than Sable + +You must not: + +- Feel bad about forking our project. Forks are healthy for FOSS! + +## Community and Social Use + +Community pages, groups, or accounts: + +- Are awesome. +- Can absolutely use the name Sable. +- Can freely use the Sable logo. +- Please just add a tiny disclaimer somewhere that it's a community-run space so people don't yell at us when your server goes down for maintenance. diff --git a/config.json b/config.json index 1bdffb675..2809e4f68 100644 --- a/config.json +++ b/config.json @@ -13,6 +13,9 @@ "webPushAppID": "moe.sable.app.sygnal" }, + "themeCatalogBaseUrl": "https://raw.githubusercontent.com/SableClient/themes/main/", + "themeCatalogApprovedHostPrefixes": ["https://raw.githubusercontent.com/SableClient/themes/"], + "slidingSync": { "enabled": true }, diff --git a/flake.lock b/flake.lock new file mode 100644 index 000000000..536adabd7 --- /dev/null +++ b/flake.lock @@ -0,0 +1,142 @@ +{ + "nodes": { + "flake-compat": { + "flake": false, + "locked": { + "lastModified": 1767039857, + "narHash": "sha256-vNpUSpF5Nuw8xvDLj2KCwwksIbjua2LZCqhV1LNRDns=", + "owner": "NixOS", + "repo": "flake-compat", + "rev": "5edf11c44bc78a0d334f6334cdaf7d60d732daab", + "type": "github" + }, + "original": { + "owner": "NixOS", + "repo": "flake-compat", + "type": "github" + } + }, + "flake-parts": { + "inputs": { + "nixpkgs-lib": "nixpkgs-lib" + }, + "locked": { + "lastModified": 1777988971, + "narHash": "sha256-qIoWPDs+0/8JecyYgE3gpKQxW/4bLW/gp45vow9ioCQ=", + "owner": "hercules-ci", + "repo": "flake-parts", + "rev": "0678d8986be1661af6bb555f3489f2fdfc31f6ff", + "type": "github" + }, + "original": { + "owner": "hercules-ci", + "repo": "flake-parts", + "type": "github" + } + }, + "git-hooks": { + "inputs": { + "flake-compat": "flake-compat", + "gitignore": "gitignore", + "nixpkgs": [ + "nixpkgs" + ] + }, + "locked": { + "lastModified": 1776796298, + "narHash": "sha256-PcRvlWayisPSjd0UcRQbhG8Oqw78AcPE6x872cPRHN8=", + "owner": "cachix", + "repo": "git-hooks.nix", + "rev": "3cfd774b0a530725a077e17354fbdb87ea1c4aad", + "type": "github" + }, + "original": { + "owner": "cachix", + "repo": "git-hooks.nix", + "type": "github" + } + }, + "gitignore": { + "inputs": { + "nixpkgs": [ + "git-hooks", + "nixpkgs" + ] + }, + "locked": { + "lastModified": 1709087332, + "narHash": "sha256-HG2cCnktfHsKV0s4XW83gU3F57gaTljL9KNSuG6bnQs=", + "owner": "hercules-ci", + "repo": "gitignore.nix", + "rev": "637db329424fd7e46cf4185293b9cc8c88c95394", + "type": "github" + }, + "original": { + "owner": "hercules-ci", + "repo": "gitignore.nix", + "type": "github" + } + }, + "nixpkgs": { + "locked": { + "lastModified": 1777954456, + "narHash": "sha256-hGdgeU2Nk87RAuZyYjyDjFL6LK7dAZN5RE9+hrDTkDU=", + "owner": "NixOS", + "repo": "nixpkgs", + "rev": "549bd84d6279f9852cae6225e372cc67fb91a4c1", + "type": "github" + }, + "original": { + "owner": "NixOS", + "ref": "nixos-unstable", + "repo": "nixpkgs", + "type": "github" + } + }, + "nixpkgs-lib": { + "locked": { + "lastModified": 1777168982, + "narHash": "sha256-GOkGPcboWE9BmGCRMLX3worL4EMnsnG8MyKmXNeYuhQ=", + "owner": "nix-community", + "repo": "nixpkgs.lib", + "rev": "f5901329dade4a6ea039af1433fb087bd9c1fe14", + "type": "github" + }, + "original": { + "owner": "nix-community", + "repo": "nixpkgs.lib", + "type": "github" + } + }, + "root": { + "inputs": { + "flake-parts": "flake-parts", + "git-hooks": "git-hooks", + "nixpkgs": "nixpkgs", + "treefmt-nix": "treefmt-nix" + } + }, + "treefmt-nix": { + "inputs": { + "nixpkgs": [ + "nixpkgs" + ] + }, + "locked": { + "lastModified": 1775636079, + "narHash": "sha256-pc20NRoMdiar8oPQceQT47UUZMBTiMdUuWrYu2obUP0=", + "owner": "numtide", + "repo": "treefmt-nix", + "rev": "790751ff7fd3801feeaf96d7dc416a8d581265ba", + "type": "github" + }, + "original": { + "owner": "numtide", + "repo": "treefmt-nix", + "type": "github" + } + } + }, + "root": "root", + "version": 7 +} diff --git a/flake.nix b/flake.nix new file mode 100644 index 000000000..c19856c22 --- /dev/null +++ b/flake.nix @@ -0,0 +1,181 @@ +# SPDX-License-Identifier: AGPL-3.0 +{ + inputs = { + nixpkgs.url = "github:NixOS/nixpkgs/nixos-unstable"; + flake-parts.url = "github:hercules-ci/flake-parts"; + git-hooks.url = "github:cachix/git-hooks.nix"; + git-hooks.inputs.nixpkgs.follows = "nixpkgs"; + treefmt-nix.url = "github:numtide/treefmt-nix"; + treefmt-nix.inputs.nixpkgs.follows = "nixpkgs"; + }; + + outputs = + inputs@{ flake-parts, ... }: + flake-parts.lib.mkFlake { inherit inputs; } { + imports = [ + inputs.git-hooks.flakeModule + inputs.treefmt-nix.flakeModule + ]; + + systems = [ + "x86_64-linux" + "aarch64-linux" + "x86_64-darwin" + "aarch64-darwin" + ]; + + perSystem = + { + config, + pkgs, + lib, + ... + }: + let + self = inputs.self; + + packageJson = builtins.fromJSON (builtins.readFile ./package.json); + + nodejs = pkgs.nodejs_24; + pnpm = pkgs.pnpm_10; + pnpmConfigHook = pkgs.pnpmConfigHook.override { inherit pnpm; }; + + pnpmNativeBuildInputs = [ + nodejs + pnpm + pnpmConfigHook + ]; + + mkPnpmDeps = + { + src, + version, + pnpmInstallFlags, + }: + pkgs.fetchPnpmDeps { + inherit + pnpm + src + version + pnpmInstallFlags + ; + pname = "sable"; + fetcherVersion = 3; + hash = "sha256-IJrBo2/PsHiMBbN7eUu46U6V8flL9KYFDphz5cirfrU="; + }; + + mkPnpmCheck = + name: script: + pkgs.stdenv.mkDerivation (finalAttrs: { + pname = "sable-${name}"; + inherit (packageJson) version; + src = lib.cleanSource ./.; + + pnpmInstallFlags = [ "--ignore-scripts" ]; + + pnpmDeps = mkPnpmDeps { + inherit (finalAttrs) src version pnpmInstallFlags; + }; + + nativeBuildInputs = pnpmNativeBuildInputs; + + buildPhase = '' + runHook preBuild + pnpm run ${script} + runHook postBuild + ''; + + installPhase = '' + runHook preInstall + touch $out + runHook postInstall + ''; + + doCheck = false; + }); + in + { + treefmt = { + projectRootFile = "flake.nix"; + programs = { + nixfmt.enable = true; + oxfmt.enable = true; + }; + settings.global.excludes = [ + "dist" + "node_modules" + "pnpm-lock.yaml" + "pnpm-workspace.yaml" + "package.json" + "LICENSE" + "CHANGELOG.md" + "./changeset" + ]; + }; + pre-commit.settings.hooks = { + treefmt = { + enable = true; + package = config.treefmt.build.wrapper; + }; + }; + + packages.sable = pkgs.stdenv.mkDerivation (finalAttrs: { + pname = "sable"; + inherit (packageJson) version; + src = lib.cleanSource ./.; + + # ignoring knope for building + pnpmInstallFlags = [ "--ignore-scripts" ]; + + pnpmDeps = mkPnpmDeps { + inherit (finalAttrs) src version pnpmInstallFlags; + }; + + nativeBuildInputs = pnpmNativeBuildInputs; + + env.VITE_BUILD_HASH = self.shortRev or self.dirtyShortRev or ""; + env.VITE_IS_RELEASE_TAG = "false"; + + buildPhase = '' + runHook preBuild + pnpm run build + runHook postBuild + ''; + + installPhase = '' + runHook preInstall + cp -r dist $out + runHook postInstall + ''; + }); + + packages.default = config.packages.sable; + + checks = { + build = config.packages.sable; + lint = mkPnpmCheck "lint" "lint"; + fmt = mkPnpmCheck "fmt" "fmt:check"; + test = mkPnpmCheck "test" "test:run"; + typecheck = mkPnpmCheck "typecheck" "typecheck"; + knip = mkPnpmCheck "knip" "knip"; + }; + + devShells.default = pkgs.mkShell { + packages = [ + nodejs + pnpm + pkgs.corepack + pkgs.vitejs + pkgs.oxlint + pkgs.oxfmt + pkgs.knope + pkgs.typescript + pkgs.typescript-language-server + pkgs.nil + pkgs.nixd + ]; + shellHook = config.pre-commit.installationScript; + }; + }; + }; +} diff --git a/index.html b/index.html index c22ea4274..5cca4f038 100644 --- a/index.html +++ b/index.html @@ -35,86 +35,86 @@ - + diff --git a/oxfmt.config.ts b/oxfmt.config.ts index 593c2425c..c193a0268 100644 --- a/oxfmt.config.ts +++ b/oxfmt.config.ts @@ -1,6 +1,6 @@ -import { defineConfig } from 'oxfmt'; +import type { OxfmtConfig } from 'oxfmt'; -export default defineConfig({ +export default { printWidth: 100, tabWidth: 2, singleQuote: true, @@ -15,4 +15,4 @@ export default defineConfig({ 'CHANGELOG.md', './changeset', ], -}); +} satisfies OxfmtConfig; diff --git a/package.json b/package.json index 47bfe902f..2438fcddf 100644 --- a/package.json +++ b/package.json @@ -1,6 +1,6 @@ { "name": "sable", - "version": "1.14.0", + "version": "1.15.3", "description": "An almost stable Matrix client", "type": "module", "packageManager": "pnpm@10.32.1+sha512.a706938f0e89ac1456b6563eab4edf1d1faf3368d1191fc5c59790e96dc918e4456ab2e67d613de1043d2e8c81f87303e6b40d4ffeca9df15ef1ad567348f2be", @@ -70,8 +70,10 @@ "immer": "^9.0.21", "is-hotkey": "^0.2.0", "jotai": "^2.18.0", + "katex": "^0.16.45", "linkify-react": "^4.3.2", "linkifyjs": "^4.3.2", + "marked": "^18.0.2", "matrix-js-sdk": "^38.4.0", "matrix-widget-api": "^1.16.1", "pdfjs-dist": "^5.4.624", diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml index 02f7aba34..ee7836185 100644 --- a/pnpm-lock.yaml +++ b/pnpm-lock.yaml @@ -62,7 +62,7 @@ importers: version: 0.5.7(@vanilla-extract/css@1.18.0) '@vanilla-extract/vite-plugin': specifier: ^5.1.4 - version: 5.1.4(@types/node@24.10.13)(jiti@2.6.1)(terser@5.46.1)(vite@7.3.1(@types/node@24.10.13)(jiti@2.6.1)(terser@5.46.1)(yaml@2.8.2))(yaml@2.8.2) + version: 5.1.4(@types/node@24.10.13)(jiti@2.6.1)(terser@5.47.1)(vite@7.3.1(@types/node@24.10.13)(jiti@2.6.1)(terser@5.47.1)(yaml@2.8.2))(yaml@2.8.2) await-to-js: specifier: ^3.0.0 version: 3.0.0 @@ -135,12 +135,18 @@ importers: jotai: specifier: ^2.18.0 version: 2.18.1(@babel/core@7.29.0)(@babel/template@7.28.6)(@types/react@18.3.28)(react@18.3.1) + katex: + specifier: ^0.16.45 + version: 0.16.45 linkify-react: specifier: ^4.3.2 version: 4.3.2(linkifyjs@4.3.2)(react@18.3.1) linkifyjs: specifier: ^4.3.2 version: 4.3.2 + marked: + specifier: ^18.0.2 + version: 18.0.2 matrix-js-sdk: specifier: ^38.4.0 version: 38.4.0 @@ -201,7 +207,7 @@ importers: devDependencies: '@cloudflare/vite-plugin': specifier: ^1.26.0 - version: 1.27.0(vite@7.3.1(@types/node@24.10.13)(jiti@2.6.1)(terser@5.46.1)(yaml@2.8.2))(workerd@1.20260310.1)(wrangler@4.72.0) + version: 1.27.0(vite@7.3.1(@types/node@24.10.13)(jiti@2.6.1)(terser@5.47.1)(yaml@2.8.2))(workerd@1.20260310.1)(wrangler@4.72.0) '@esbuild-plugins/node-globals-polyfill': specifier: ^0.2.3 version: 0.2.3(esbuild@0.27.3) @@ -252,7 +258,7 @@ importers: version: 0.7.39 '@vitejs/plugin-react': specifier: ^5.1.4 - version: 5.1.4(vite@7.3.1(@types/node@24.10.13)(jiti@2.6.1)(terser@5.46.1)(yaml@2.8.2)) + version: 5.1.4(vite@7.3.1(@types/node@24.10.13)(jiti@2.6.1)(terser@5.47.1)(yaml@2.8.2)) '@vitest/coverage-v8': specifier: ^4.1.0 version: 4.1.0(vitest@4.1.0) @@ -285,25 +291,25 @@ importers: version: 5.9.3 vite: specifier: ^7.3.1 - version: 7.3.1(@types/node@24.10.13)(jiti@2.6.1)(terser@5.46.1)(yaml@2.8.2) + version: 7.3.1(@types/node@24.10.13)(jiti@2.6.1)(terser@5.47.1)(yaml@2.8.2) vite-plugin-compression2: specifier: 2.5.0 version: 2.5.0(rollup@4.59.0) vite-plugin-pwa: specifier: ^1.2.0 - version: 1.2.0(vite@7.3.1(@types/node@24.10.13)(jiti@2.6.1)(terser@5.46.1)(yaml@2.8.2))(workbox-build@7.4.0(@types/babel__core@7.20.5))(workbox-window@7.4.0) + version: 1.2.0(vite@7.3.1(@types/node@24.10.13)(jiti@2.6.1)(terser@5.47.1)(yaml@2.8.2))(workbox-build@7.4.0(@types/babel__core@7.20.5))(workbox-window@7.4.0) vite-plugin-static-copy: specifier: ^3.2.0 - version: 3.2.0(vite@7.3.1(@types/node@24.10.13)(jiti@2.6.1)(terser@5.46.1)(yaml@2.8.2)) + version: 3.2.0(vite@7.3.1(@types/node@24.10.13)(jiti@2.6.1)(terser@5.47.1)(yaml@2.8.2)) vite-plugin-svgr: specifier: 4.5.0 - version: 4.5.0(rollup@4.59.0)(typescript@5.9.3)(vite@7.3.1(@types/node@24.10.13)(jiti@2.6.1)(terser@5.46.1)(yaml@2.8.2)) + version: 4.5.0(rollup@4.59.0)(typescript@5.9.3)(vite@7.3.1(@types/node@24.10.13)(jiti@2.6.1)(terser@5.47.1)(yaml@2.8.2)) vite-plugin-top-level-await: specifier: ^1.6.0 - version: 1.6.0(@swc/helpers@0.5.19)(rollup@4.59.0)(vite@7.3.1(@types/node@24.10.13)(jiti@2.6.1)(terser@5.46.1)(yaml@2.8.2)) + version: 1.6.0(@swc/helpers@0.5.19)(rollup@4.59.0)(vite@7.3.1(@types/node@24.10.13)(jiti@2.6.1)(terser@5.47.1)(yaml@2.8.2)) vitest: specifier: ^4.1.0 - version: 4.1.0(@types/node@24.10.13)(@vitest/ui@4.1.0)(jsdom@29.0.0)(vite@7.3.1(@types/node@24.10.13)(jiti@2.6.1)(terser@5.46.1)(yaml@2.8.2)) + version: 4.1.0(@types/node@24.10.13)(@vitest/ui@4.1.0)(jsdom@29.0.0)(vite@7.3.1(@types/node@24.10.13)(jiti@2.6.1)(terser@5.47.1)(yaml@2.8.2)) wrangler: specifier: ^4.70.0 version: 4.72.0 @@ -313,8 +319,8 @@ packages: '@adobe/css-tools@4.4.4': resolution: {integrity: sha512-Elp+iwUx5rN5+Y8xLt5/GRoG20WGoDCQ/1Fb+1LiGtvwbDavuSk0jhD/eZdckHAuzcDzccnkv+rEjyWfRx18gg==} - '@apideck/better-ajv-errors@0.3.6': - resolution: {integrity: sha512-P+ZygBLZtkp0qqOAJJVX4oX/sFo5JR3eBWwwuqHHhK0GIgQOKWrAfiAaWX0aArHkRWHMuggFEgAZNxVPwPZYaA==} + '@apideck/better-ajv-errors@0.3.7': + resolution: {integrity: sha512-TajUJwGWbDwkCx/CZi7tRE8PVB7simCvKJfHUsSdvps+aTM/PDPP4gkLmKnc+x3CE//y9i/nj74GqdL/hwk7Iw==} engines: {node: '>=10'} peerDependencies: ajv: '>=8' @@ -350,6 +356,10 @@ packages: resolution: {integrity: sha512-T1NCJqT/j9+cn8fvkt7jtwbLBfLC/1y1c7NtCeXFRgzGTsafi68MRv8yzkYSapBnFA6L3U2VSc02ciDzoAJhJg==} engines: {node: '>=6.9.0'} + '@babel/compat-data@7.29.3': + resolution: {integrity: sha512-LIVqM46zQWZhj17qA8wb4nW/ixr2y1Nw+r1etiAWgRM6U1IqP+LNhL1yg440jYZR72jCWcWbLWzIosH+uP1fqg==} + engines: {node: '>=6.9.0'} + '@babel/core@7.29.0': resolution: {integrity: sha512-CGOfOJqWjg2qW/Mb6zNsDm+u5vFQ8DxXfbM09z69p5Z6+mE1ikP2jUXw+j42Pf1XTYED2Rni5f95npYeuwMDQA==} engines: {node: '>=6.9.0'} @@ -366,8 +376,8 @@ packages: resolution: {integrity: sha512-JYtls3hqi15fcx5GaSNL7SCTJ2MNmjrkHXg4FSpOA/grxK8KwyZ5bubHsCq8FXCkua6xhuaaBit+3b7+VZRfcA==} engines: {node: '>=6.9.0'} - '@babel/helper-create-class-features-plugin@7.28.6': - resolution: {integrity: sha512-dTOdvsjnG3xNT9Y0AUg1wAl38y+4Rl4sf9caSQZOXdNqVn+H+HbbJ4IyyHaIqNR6SW9oJpA/RuRjsjCw2IdIow==} + '@babel/helper-create-class-features-plugin@7.29.3': + resolution: {integrity: sha512-RpLYy2sb51oNLjuu1iD3bwBqCBWUzjO0ocp+iaCP/lJtb2CPLcnC2Fftw+4sAzaMELGeWTgExSKADbdo0GFVzA==} engines: {node: '>=6.9.0'} peerDependencies: '@babel/core': ^7.0.0 @@ -468,6 +478,12 @@ packages: peerDependencies: '@babel/core': ^7.0.0 + '@babel/plugin-bugfix-safari-rest-destructuring-rhs-array@7.29.3': + resolution: {integrity: sha512-SRS46DFR4HqzUzCVgi90/xMoL+zeBDBvWdKYXSEzh79kXswNFEglUpMKxR04//dPqwYXWUBJ3mpUd933ru9Kmg==} + engines: {node: '>=6.9.0'} + peerDependencies: + '@babel/core': ^7.0.0 + '@babel/plugin-bugfix-v8-spread-parameters-in-optional-chaining@7.27.1': resolution: {integrity: sha512-oO02gcONcD5O1iTLi/6frMJBIwWEHceWGSGqrpCmEL8nogiS6J9PBlE48CaK20/Jx1LuRml9aDftLgdjXT8+Cw==} engines: {node: '>=6.9.0'} @@ -660,8 +676,8 @@ packages: peerDependencies: '@babel/core': ^7.0.0-0 - '@babel/plugin-transform-modules-systemjs@7.29.0': - resolution: {integrity: sha512-PrujnVFbOdUpw4UHiVwKvKRLMMic8+eC0CuNlxjsyZUiBjhFdPsewdXCkveh2KqBA9/waD0W1b4hXSOBQJezpQ==} + '@babel/plugin-transform-modules-systemjs@7.29.4': + resolution: {integrity: sha512-N7QmZ0xRZfjHOfZeQLJjwgX2zS9pdGHSVl/cjSGlo4dXMqvurfxXDMKY4RqEKzPozV78VMcd0lxyG13mlbKc4w==} engines: {node: '>=6.9.0'} peerDependencies: '@babel/core': ^7.0.0-0 @@ -828,8 +844,8 @@ packages: peerDependencies: '@babel/core': ^7.0.0 - '@babel/preset-env@7.29.2': - resolution: {integrity: sha512-DYD23veRYGvBFhcTY1iUvJnDNpuqNd/BzBwCvzOTKUnJjKg5kpUBh3/u9585Agdkgj+QuygG7jLfOPWMa2KVNw==} + '@babel/preset-env@7.29.5': + resolution: {integrity: sha512-/69t2aEzGKHD76DyLbHysF/QH2LJOB8iFnYO37unDTKBTubzcMRv0f3H5EiN1Q6ajOd/eB7dAInF0qdFVS06kA==} engines: {node: '>=6.9.0'} peerDependencies: '@babel/core': ^7.0.0-0 @@ -3088,8 +3104,8 @@ packages: resolution: {integrity: sha512-RZNwNclF7+MS/8bDg70amg32dyeZGZxiDuQmZxKLAlQjr3jGyLx+4Kkk58UO7D2QdgFIQCovuSuZESne6RG6XQ==} engines: {node: '>= 6.0.0'} - ajv@8.18.0: - resolution: {integrity: sha512-PlXPeEWMXMZ7sPYOHqmDyCJzcfNrUr3fGNKtezX14ykXOEIvyK81d+qydx89KY5O71FKMPaQ2vBfBFI5NHR63A==} + ajv@8.20.0: + resolution: {integrity: sha512-Thbli+OlOj+iMPYFBVBfJ3OmCAnaSyNn4M1vz9T6Gka5Jt9ba/HIR56joy65tY6kx/FCF5VXNB819Y7/GUrBGA==} another-json@0.2.0: resolution: {integrity: sha512-/Ndrl68UQLhnCdsAzEXLMFuOR546o2qbYRqCglaNHbjXrwG1ayTcdwr3zkSGOGtGXDyR5X9nCFfnyG2AFJIsqg==} @@ -3183,6 +3199,11 @@ packages: engines: {node: '>=6.0.0'} hasBin: true + baseline-browser-mapping@2.10.27: + resolution: {integrity: sha512-zEs/ufmZoUd7WftKpKyXaT6RFxpQ5Qm9xytKRHvJfxFV9DFJkZph9RvJ1LcOUi0Z1ZVijMte65JbILeV+8QQEA==} + engines: {node: '>=6.0.0'} + hasBin: true + bidi-js@1.0.3: resolution: {integrity: sha512-RKshQI1R3YQ+n9YJz2QQ147P66ELpa1FQEg20Dk8oW9t2KgLbpDLLp9aGZ7y8WHSshDknG0bknqGw5/tyCs5tw==} @@ -3203,6 +3224,10 @@ packages: resolution: {integrity: sha512-h+DEnpVvxmfVefa4jFbCf5HdH5YMDXRsmKflpf1pILZWRFlTbJpxeU55nJl4Smt5HQaGzg1o6RHFPJaOqnmBDg==} engines: {node: 18 || 20 || >=22} + brace-expansion@5.0.6: + resolution: {integrity: sha512-kLpxurY4Z4r9sgMsyG0Z9uzsBlgiU/EFKhj/h91/8yHu0edo7XuixOIH3VcJ8kkxs6/jPzoI6U9Vj3WqbMQ94g==} + engines: {node: 18 || 20 || >=22} + braces@3.0.3: resolution: {integrity: sha512-yQbXgO/OSZVD2IsiLlro+7Hf6Q18EJrKSEsdoMzKePKXct3gvD8oLcOQdIzGupr5Fj+EDe8gO/lxc1BzfMpxvA==} engines: {node: '>=8'} @@ -3215,6 +3240,11 @@ packages: engines: {node: ^6 || ^7 || ^8 || ^9 || ^10 || ^11 || ^12 || >=13.7} hasBin: true + browserslist@4.28.2: + resolution: {integrity: sha512-48xSriZYYg+8qXna9kwqjIVzuQxi+KYWp2+5nCYnYKPTr0LvD89Jqk2Or5ogxz0NUMfIjhh2lIUX/LyX9B4oIg==} + engines: {node: ^6 || ^7 || ^8 || ^9 || ^10 || ^11 || ^12 || >=13.7} + hasBin: true + bs58@6.0.0: resolution: {integrity: sha512-PD0wEnEYg6ijszw/u8s+iI3H17cTymlrwkKhDhPZq+Sokl3AU4htyBFTjAeNAlCCmg0f53g6ih3jATyCKftTfw==} @@ -3232,8 +3262,8 @@ packages: resolution: {integrity: sha512-Sp1ablJ0ivDkSzjcaJdxEunN5/XvksFJ2sMBFfq6x0ryhQV/2b/KwFe21cMpmHtPOSij8K99/wSfoEuTObmuMQ==} engines: {node: '>= 0.4'} - call-bind@1.0.8: - resolution: {integrity: sha512-oKlSFMcMwpUg2ednkhQ454wfWiU/ul3CkJe/PEHcTKuiX6RpbehUiFMXu13HalGZxfUwCQzZG747YXBn1im9ww==} + call-bind@1.0.9: + resolution: {integrity: sha512-a/hy+pNsFUTR+Iz8TCJvXudKVLAnz/DyeSUo10I5yvFDQJBFU2s9uqQpoSrJlroHUKoKqzg+epxyP9lqFdzfBQ==} engines: {node: '>= 0.4'} call-bound@1.0.4: @@ -3251,6 +3281,9 @@ packages: caniuse-lite@1.0.30001777: resolution: {integrity: sha512-tmN+fJxroPndC74efCdp12j+0rk0RHwV5Jwa1zWaFVyw2ZxAuPeG8ZgWC3Wz7uSjT3qMRQ5XHZ4COgQmsCMJAQ==} + caniuse-lite@1.0.30001792: + resolution: {integrity: sha512-hVLMUZFgR4JJ6ACt1uEESvQN1/dBVqPAKY0hgrV70eN3391K6juAfTjKZLKvOMsx8PxA7gsY1/tLMMTcfFLLpw==} + chai@6.2.2: resolution: {integrity: sha512-NUPRluOfOiTKBKvWPtSD4PhFvWCqOi0BGStNWs57X9js7XGTprSmFoz5F0tWhR4WPjNeR9jXqdC7/UpSJTnlRg==} engines: {node: '>=18'} @@ -3276,6 +3309,10 @@ packages: commander@2.20.3: resolution: {integrity: sha512-GpVkmM8vF2vQUkj2LvZmD35JxeJOLCwJ9cUkugyk2nuhbv3+mJvpLYYt+0+USMxE+oj+ey/lJEnhZw75x/OMcQ==} + commander@8.3.0: + resolution: {integrity: sha512-OkTL9umf+He2DZkUq8f8J9of7yL6RJKI24dVITBmNfZBmri9zYZQrKkuXiKhyfPSu8tUhnVBB1iKXevvnlR4Ww==} + engines: {node: '>= 12'} + common-tags@1.8.2: resolution: {integrity: sha512-gk/Z852D2Wtb//0I+kRFNKKE9dIIVirjoqPoA1wJU+XePVXZfGeBpk45+A1rKO4Q43prqWBNY/MiIeRLbPWUaA==} engines: {node: '>=4.0.0'} @@ -3446,6 +3483,9 @@ packages: electron-to-chromium@1.5.307: resolution: {integrity: sha512-5z3uFKBWjiNR44nFcYdkcXjKMbg5KXNdciu7mhTPo9tB7NbqSNP2sSnGR+fqknZSCwKkBN+oxiiajWs4dT6ORg==} + electron-to-chromium@1.5.352: + resolution: {integrity: sha512-9wHk8x6dyuimoe18EdiDPWKExNdxYqo4fn4FwOVVper6RxT3cmpBwBkWWfSOCYJjQdIco/nPhJhNLmn4Ufg1Yg==} + emojibase-data@15.3.2: resolution: {integrity: sha512-TpDyTDDTdqWIJixV5sTA6OQ0P0JfIIeK2tFRR3q56G9LK65ylAZ7z3KyBXokpvTTJ+mLUXQXbLNyVkjvnTLE+A==} peerDependencies: @@ -3472,8 +3512,8 @@ packages: error-stack-parser-es@1.0.5: resolution: {integrity: sha512-5qucVt2XcuGMcEGgWI7i+yZpmpByQ8J1lHhcL7PwqCwu9FPP3VUXzT4ltHe5i2z9dePwEHcDVOAfSnHsOlCXRA==} - es-abstract@1.24.1: - resolution: {integrity: sha512-zHXBLhP+QehSSbsS9Pt23Gg964240DPd6QCf8WpkqEXxQ7fhdZzYsocOr5u7apWonsS5EjZDmTF+/slGMyasvw==} + es-abstract@1.24.2: + resolution: {integrity: sha512-2FpH9Q5i2RRwyEP1AylXe6nYLR5OhaJTZwmlcP0dL/+JCbgg7yyEo/sEK6HeGZRf3dFpWwThaRHVApXSkW3xeg==} engines: {node: '>= 0.4'} es-define-property@1.0.1: @@ -3549,8 +3589,8 @@ packages: fast-json-stable-stringify@2.1.0: resolution: {integrity: sha512-lhd/wF+Lk98HZoTCtlVraHtfh5XYijIjalXck7saUtuanSDyLMxnHhSXEDJqHxD7msR8D0uCmqlkwjCV8xvwHw==} - fast-uri@3.1.0: - resolution: {integrity: sha512-iPeeDKJSWf4IEOasVVrknXpaBV0IApz/gp7S2bb7Z4Lljbl2MGJRqInZiUrQwV16cpzw/D3S5j5Julj/gT52AA==} + fast-uri@3.1.2: + resolution: {integrity: sha512-rVjf7ArG3LTk+FS6Yw81V1DLuZl1bRbNrev6Tmd/9RaroeeRRJhAt7jg/6YFxbvAQXUCavSoZhPPj6oOx+5KjQ==} fastq@1.20.1: resolution: {integrity: sha512-GGToxJ/w1x32s/D2EKND7kTil4n8OVk/9mycTc4VDza13lOvpUZTGX3mFSCtV9ksdGBVzvsyAVLM6mHFThxXxw==} @@ -3723,8 +3763,8 @@ packages: resolution: {integrity: sha512-NqADB8VjPFLM2V0VvHUewwwsw0ZWBaIdgo+ieHtK3hasLz4qeCRjYcqfB6AQrBggRKppKF8L52/VqdVsO47Dlw==} engines: {node: '>= 0.4'} - hasown@2.0.2: - resolution: {integrity: sha512-0hJU9SCPvmMzIBdZFqNPXWa6dqh7WdH0cII9y+CyS8rG3nL48Bclra9HmKhVVUHyPWNH5Y7xDwAB7bfgSjkUMQ==} + hasown@2.0.3: + resolution: {integrity: sha512-ej4AhfhfL2Q2zpMmLo7U1Uv9+PyhIZpgQLGT1F9miIGmiCJIoCgSmczFdrc97mWT4kVY72KA+WnnhJ5pghSvSg==} engines: {node: '>= 0.4'} hoist-non-react-statics@3.3.2: @@ -3829,8 +3869,8 @@ packages: resolution: {integrity: sha512-1BC0BVFhS/p0qtw6enp8e+8OD0UrK0oFLztSjNzhcKA3WDuJxxAPXzPuPtKkjEY9UUoEWlX/8fgKeu2S8i9JTA==} engines: {node: '>= 0.4'} - is-core-module@2.16.1: - resolution: {integrity: sha512-UfoeMA6fIJ8wTYFEUjelnaGI67v6+N7qXJEvQuIGa99l4xsCruSYOVSQ0uPANn4dAzm8lkYPaKLrrijLq7x23w==} + is-core-module@2.16.2: + resolution: {integrity: sha512-evOr8xfXKxE6qSR0hSXL2r3sd7ALj8+7jQEUvPYcm5sgZFdJ+AYzT6yNmJenvIYQBgIGwfwz08sL8zoL7yq2BA==} engines: {node: '>= 0.4'} is-data-view@1.0.2: @@ -4020,16 +4060,13 @@ packages: json-schema-traverse@1.0.0: resolution: {integrity: sha512-NM8/P9n3XjXhIZn1lLhkFaACTOURQXjWhV4BA/RnOv8xvgqtqpAX9IO4mRQxSx1Rlo4tqzeqb0sOlruaOy3dug==} - json-schema@0.4.0: - resolution: {integrity: sha512-es94M3nTIfsEPisRafak+HDLfHXnKBhV3vU5eqPcS3flIWqcxJWgXHXiey3YrpaNsanY5ei1VoYEbOzijuq9BA==} - json5@2.2.3: resolution: {integrity: sha512-XmOWe7eyHYH14cLdVPoyg+GOH3rYX++KpzrylJwSW98t3Nk+U8XOl8FWKOgwtzdb8lXGf6zYwDUzeHMWfxasyg==} engines: {node: '>=6'} hasBin: true - jsonfile@6.2.0: - resolution: {integrity: sha512-FGuPw30AdOIUTRMC2OMRtQV+jkVj2cfPqSeWXv1NEAJ1qZ5zb1X6z1mFhbfOB/iy3ssJCD+3KuZ8r8C3uVFlAg==} + jsonfile@6.2.1: + resolution: {integrity: sha512-zwOTdL3rFQ/lRdBnntKVOX6k5cKJwEc1HdilT71BWEu7J41gXIB2MRp+vxduPSwZJPWBxEzv4yH1wYLJGUHX4Q==} jsonpointer@5.0.1: resolution: {integrity: sha512-p/nXbhSEcu3pZRdkW1OfJhpsVtW1gd4Wa1fnQc9YLiTfAjn0312eMKimbdIQzuZl9aa9xUGaRlP9T/CJE/ditQ==} @@ -4039,6 +4076,10 @@ packages: resolution: {integrity: sha512-+KJGIyHgkGuIq3IEBNftfhW/LfWhXUIY6OmyVWjliu5KH1y0fw7VQ8YndE2O4qZdMSd9SqbnC8GOcZEy0Om7sA==} engines: {node: '>=18'} + katex@0.16.45: + resolution: {integrity: sha512-pQpZbdBu7wCTmQUh7ufPmLr0pFoObnGUoL/yhtwJDgmmQpbkg/0HSVti25Fu4rmd1oCR6NGWe9vqTWuWv3GcNA==} + hasBin: true + kleur@4.1.5: resolution: {integrity: sha512-o+NO+8WrRiQEE4/7nwRJhN1HWpVmJm511pBHUxPLtp0BUISzlBplORYSmTclCnJvQq2tKu/sgl3xVpkc7ZWuQQ==} engines: {node: '>=6'} @@ -4080,6 +4121,9 @@ packages: lodash@4.17.23: resolution: {integrity: sha512-LgVTMpQtIopCi79SJeDiP0TfWi5CNEc/L/aRdTh3yIvmZXTnheWpKjSZhnvMl8iXbC1tFg9gdHHDMLoV7CnG+w==} + lodash@4.18.1: + resolution: {integrity: sha512-dMInicTPVE8d1e5otfwmmjlxkZoUpiVLwyeTdUsi/Caj/gfzzblBcCE5sRHV/AsjuCmxWrte2TNGSYuCeCq+0Q==} + loglevel@1.9.2: resolution: {integrity: sha512-HgMmCqIJSAKqo68l0rS2AanEWfkxaZ5wNiEFb5ggm08lDs9Xl2KxBlX3PTcaD2chBM1gXAYf491/M2Rv8Jwayg==} engines: {node: '>= 0.6.0'} @@ -4122,6 +4166,11 @@ packages: resolution: {integrity: sha512-hXdUTZYIVOt1Ex//jAQi+wTZZpUpwBj/0QsOzqegb3rGMMeJiSEu5xLHnYfBrRV4RH2+OCSOO95Is/7x1WJ4bw==} engines: {node: '>=10'} + marked@18.0.2: + resolution: {integrity: sha512-NsmlUYBS/Zg57rgDWMYdnre6OTj4e+qq/JS2ot3KrYLSoHLw+sDu0Nm1ZGpRgYAq6c+b1ekaY5NzVchMCQnzcg==} + engines: {node: '>= 20'} + hasBin: true + math-intrinsics@1.1.0: resolution: {integrity: sha512-/IXtbwEk5HTPyEwyKX6hGkYXxM9nbj64B+ilVJnC/R6B0pH5G4V3b0pVbL7DBj4tkhBAppbQUlf6F6Xl9LHu1g==} engines: {node: '>= 0.4'} @@ -4163,6 +4212,10 @@ packages: resolution: {integrity: sha512-oRjTw/97aTBN0RHbYCdtF1MQfvusSIBQM0IZEgzl6426+8jSC0nF1a/GmnVLpfB9yyr6g6FTqWqiZVbxrtaCIg==} engines: {node: 18 || 20 || >=22} + minimatch@10.2.5: + resolution: {integrity: sha512-MULkVLfKGYDFYejP07QOurDLLQpcjk7Fw+7jXS2R2czRQzR56yHRveU5NDJEOviH+hETZKSkIk5c+T23GjFUMg==} + engines: {node: 18 || 20 || >=22} + minimist@1.2.8: resolution: {integrity: sha512-2yyAR8qBkN3YuheJanUpWC5U3bb5osDywNB8RzDVlDwDHbocAJveqqj1u8+SVD7jkWT4yvsHCpWqqWqAxb0zCA==} @@ -4212,6 +4265,9 @@ packages: node-releases@2.0.36: resolution: {integrity: sha512-TdC8FSgHz8Mwtw9g5L4gR/Sh9XhSP/0DEkQxfEFXOpiul5IiHgHan2VhYYb6agDSfp4KuvltmGApc8HMgUrIkA==} + node-releases@2.0.38: + resolution: {integrity: sha512-3qT/88Y3FbH/Kx4szpQQ4HzUbVrHPKTLVpVocKiLfoYvw9XSGOX2FmD2d6DrXbVYyAQTF2HeF6My8jmzx7/CRw==} + normalize-path@3.0.0: resolution: {integrity: sha512-6eZs5Ls3WtCisHWp9S2GUy8dqkpGi4BVSz3GaqiE6ezub0512ESztXUwUB6C6IKbQkY2Pnb/mD4WYojCRwcwLA==} engines: {node: '>=0.10.0'} @@ -4497,8 +4553,8 @@ packages: regjsgen@0.8.0: resolution: {integrity: sha512-RvwtGe3d7LvWiDQXeQw8p5asZUmfU1G/l6WbUXeHta7Y2PEIvBTwH6E2EfmYUK8pxcxEdEmaomqyp0vZZ7C+3Q==} - regjsparser@0.13.0: - resolution: {integrity: sha512-NZQZdC5wOE/H3UT28fVGL+ikOZcEzfMGk/c3iN9UGxzWHMa1op7274oyiUVrAG4B2EuFhus8SvkaYnhvW92p9Q==} + regjsparser@0.13.1: + resolution: {integrity: sha512-dLsljMd9sqwRkby8zhO1gSg3PnJIBFid8f4CQj/sXx+7cKx+E7u0PKhZ+U4wmhx7EfmtvnA318oVaIkAB1lRJw==} hasBin: true require-from-string@2.0.2: @@ -4512,8 +4568,8 @@ packages: resolution: {integrity: sha512-pb/MYmXstAkysRFx8piNI1tGFNQIFA3vkE3Gq4EuA1dF6gHp/+vgZqsCGJapvy8N3Q+4o7FwvquPJcnZ7RYy4g==} engines: {node: '>=4'} - resolve@1.22.11: - resolution: {integrity: sha512-RfqAvLnMl313r7c9oclB1HhUEAezcpLjz95wFH4LVuhk9JF/r22qmVP9AMmOU4vMX7Q8pN8jwNg/CSpdFnMjTQ==} + resolve@1.22.12: + resolution: {integrity: sha512-TyeJ1zif53BPfHootBGwPRYT1RUt6oGWsaQr8UyZW/eAm9bKoijtvruSDEmZHm92CwS9nj7/fWttqPCgzep8CA==} engines: {node: '>= 0.4'} hasBin: true @@ -4529,8 +4585,8 @@ packages: run-parallel@1.2.0: resolution: {integrity: sha512-5l4VyZR86LZ/lDxZTR6jqL8AFE2S0IFLMP26AbjsLVADxHdhB/c0GUsH+y39UfCi3dzz8OlQuPmnaJOMoDHQBA==} - safe-array-concat@1.1.3: - resolution: {integrity: sha512-AURm5f0jYEOydBj7VQlVvDrjeFgthDdEF5H1dP+6mNpoXOMo1quQqJ4wvJDyRZ9+pO3kGWoOdmV08cSv2aJV6Q==} + safe-array-concat@1.1.4: + resolution: {integrity: sha512-wtZlHyOje6OZTGqAoaDKxFkgRtkF9CnHAVnCHKfuj200wAgL+bSJhdsCD2l0Qx/2ekEXjPWcyKkfGb5CPboslg==} engines: {node: '>=0.4'} safe-push-apply@1.0.0: @@ -4592,8 +4648,8 @@ packages: resolution: {integrity: sha512-7++dFhtcx3353uBaq8DDR4NuxBetBzC7ZQOhmTQInHEd6bSrXdiEyzCvG07Z44UYdLShWUyXt5M/yhz8ekcb1A==} engines: {node: '>=8'} - side-channel-list@1.0.0: - resolution: {integrity: sha512-FCLHtRD/gnpCiCHEiJLOwdmFP+wzCmDEkc9y7NsYxeF4u7Btsn1ZuwgwJGxImImHicJArLP4R0yX4c2KCrMrTA==} + side-channel-list@1.0.1: + resolution: {integrity: sha512-mjn/0bi/oUURjc5Xl7IaWi/OJJJumuoJFQJfDDyO46+hBWsfaVM65TBHq2eoZBhzl9EchxOijpkbRC8SVBQU0w==} engines: {node: '>= 0.4'} side-channel-map@1.0.1: @@ -4751,8 +4807,8 @@ packages: resolution: {integrity: sha512-G13vtMYPT/J8A4X2SjdtBTphZlrp1gKv6hZiOjw14RCWg6GbHuQBGtjlx75xLbYV/wEc0D7G5K4rxKP/cXk8Bw==} engines: {node: '>=10'} - terser@5.46.1: - resolution: {integrity: sha512-vzCjQO/rgUuK9sf8VJZvjqiqiHFaZLnOiimmUuOKODxWL8mm/xua7viT7aqX7dgPY60otQjUotzFMmCB4VdmqQ==} + terser@5.47.1: + resolution: {integrity: sha512-tPbLXTI6ohPASb/1YViL428oEHu6/qv1OxqYnfaonVCFHqx4+wCd95pHrQWsL5X4pl90CTyW9piSAsS2L0VoMw==} engines: {node: '>=10'} hasBin: true @@ -4900,6 +4956,7 @@ packages: uuid@10.0.0: resolution: {integrity: sha512-8XkAphELsDnEGrDxUOHB3RGvXz6TeuYSGEZBOjtTtPm2lwhGBjLgOzLHB63IUWfBpNucQjND6d3AOudO+H3RWQ==} + deprecated: uuid@10 and below is no longer supported. For ESM codebases, update to uuid@latest. For CommonJS codebases, use uuid@11 (but be aware this version will likely be deprecated in 2028). hasBin: true uuid@13.0.0: @@ -5207,10 +5264,9 @@ snapshots: '@adobe/css-tools@4.4.4': {} - '@apideck/better-ajv-errors@0.3.6(ajv@8.18.0)': + '@apideck/better-ajv-errors@0.3.7(ajv@8.20.0)': dependencies: - ajv: 8.18.0 - json-schema: 0.4.0 + ajv: 8.20.0 jsonpointer: 5.0.1 leven: 3.1.0 @@ -5258,6 +5314,8 @@ snapshots: '@babel/compat-data@7.29.0': {} + '@babel/compat-data@7.29.3': {} + '@babel/core@7.29.0': dependencies: '@babel/code-frame': 7.29.0 @@ -5298,7 +5356,7 @@ snapshots: lru-cache: 5.1.1 semver: 6.3.1 - '@babel/helper-create-class-features-plugin@7.28.6(@babel/core@7.29.0)': + '@babel/helper-create-class-features-plugin@7.29.3(@babel/core@7.29.0)': dependencies: '@babel/core': 7.29.0 '@babel/helper-annotate-as-pure': 7.27.3 @@ -5325,7 +5383,7 @@ snapshots: '@babel/helper-plugin-utils': 7.28.6 debug: 4.4.3 lodash.debounce: 4.0.8 - resolve: 1.22.11 + resolve: 1.22.12 transitivePeerDependencies: - supports-color @@ -5426,6 +5484,14 @@ snapshots: '@babel/core': 7.29.0 '@babel/helper-plugin-utils': 7.28.6 + '@babel/plugin-bugfix-safari-rest-destructuring-rhs-array@7.29.3(@babel/core@7.29.0)': + dependencies: + '@babel/core': 7.29.0 + '@babel/helper-plugin-utils': 7.28.6 + '@babel/helper-skip-transparent-expression-wrappers': 7.27.1 + transitivePeerDependencies: + - supports-color + '@babel/plugin-bugfix-v8-spread-parameters-in-optional-chaining@7.27.1(@babel/core@7.29.0)': dependencies: '@babel/core': 7.29.0 @@ -5504,7 +5570,7 @@ snapshots: '@babel/plugin-transform-class-properties@7.28.6(@babel/core@7.29.0)': dependencies: '@babel/core': 7.29.0 - '@babel/helper-create-class-features-plugin': 7.28.6(@babel/core@7.29.0) + '@babel/helper-create-class-features-plugin': 7.29.3(@babel/core@7.29.0) '@babel/helper-plugin-utils': 7.28.6 transitivePeerDependencies: - supports-color @@ -5512,7 +5578,7 @@ snapshots: '@babel/plugin-transform-class-static-block@7.28.6(@babel/core@7.29.0)': dependencies: '@babel/core': 7.29.0 - '@babel/helper-create-class-features-plugin': 7.28.6(@babel/core@7.29.0) + '@babel/helper-create-class-features-plugin': 7.29.3(@babel/core@7.29.0) '@babel/helper-plugin-utils': 7.28.6 transitivePeerDependencies: - supports-color @@ -5636,7 +5702,7 @@ snapshots: transitivePeerDependencies: - supports-color - '@babel/plugin-transform-modules-systemjs@7.29.0(@babel/core@7.29.0)': + '@babel/plugin-transform-modules-systemjs@7.29.4(@babel/core@7.29.0)': dependencies: '@babel/core': 7.29.0 '@babel/helper-module-transforms': 7.28.6(@babel/core@7.29.0) @@ -5715,7 +5781,7 @@ snapshots: '@babel/plugin-transform-private-methods@7.28.6(@babel/core@7.29.0)': dependencies: '@babel/core': 7.29.0 - '@babel/helper-create-class-features-plugin': 7.28.6(@babel/core@7.29.0) + '@babel/helper-create-class-features-plugin': 7.29.3(@babel/core@7.29.0) '@babel/helper-plugin-utils': 7.28.6 transitivePeerDependencies: - supports-color @@ -5724,7 +5790,7 @@ snapshots: dependencies: '@babel/core': 7.29.0 '@babel/helper-annotate-as-pure': 7.27.3 - '@babel/helper-create-class-features-plugin': 7.28.6(@babel/core@7.29.0) + '@babel/helper-create-class-features-plugin': 7.29.3(@babel/core@7.29.0) '@babel/helper-plugin-utils': 7.28.6 transitivePeerDependencies: - supports-color @@ -5811,9 +5877,9 @@ snapshots: '@babel/helper-create-regexp-features-plugin': 7.28.5(@babel/core@7.29.0) '@babel/helper-plugin-utils': 7.28.6 - '@babel/preset-env@7.29.2(@babel/core@7.29.0)': + '@babel/preset-env@7.29.5(@babel/core@7.29.0)': dependencies: - '@babel/compat-data': 7.29.0 + '@babel/compat-data': 7.29.3 '@babel/core': 7.29.0 '@babel/helper-compilation-targets': 7.28.6 '@babel/helper-plugin-utils': 7.28.6 @@ -5821,6 +5887,7 @@ snapshots: '@babel/plugin-bugfix-firefox-class-in-computed-class-key': 7.28.5(@babel/core@7.29.0) '@babel/plugin-bugfix-safari-class-field-initializer-scope': 7.27.1(@babel/core@7.29.0) '@babel/plugin-bugfix-safari-id-destructuring-collision-in-function-expression': 7.27.1(@babel/core@7.29.0) + '@babel/plugin-bugfix-safari-rest-destructuring-rhs-array': 7.29.3(@babel/core@7.29.0) '@babel/plugin-bugfix-v8-spread-parameters-in-optional-chaining': 7.27.1(@babel/core@7.29.0) '@babel/plugin-bugfix-v8-static-class-fields-redefine-readonly': 7.28.6(@babel/core@7.29.0) '@babel/plugin-proposal-private-property-in-object': 7.21.0-placeholder-for-preset-env.2(@babel/core@7.29.0) @@ -5852,7 +5919,7 @@ snapshots: '@babel/plugin-transform-member-expression-literals': 7.27.1(@babel/core@7.29.0) '@babel/plugin-transform-modules-amd': 7.27.1(@babel/core@7.29.0) '@babel/plugin-transform-modules-commonjs': 7.28.6(@babel/core@7.29.0) - '@babel/plugin-transform-modules-systemjs': 7.29.0(@babel/core@7.29.0) + '@babel/plugin-transform-modules-systemjs': 7.29.4(@babel/core@7.29.0) '@babel/plugin-transform-modules-umd': 7.27.1(@babel/core@7.29.0) '@babel/plugin-transform-named-capturing-groups-regex': 7.29.0(@babel/core@7.29.0) '@babel/plugin-transform-new-target': 7.27.1(@babel/core@7.29.0) @@ -5935,12 +6002,12 @@ snapshots: optionalDependencies: workerd: 1.20260310.1 - '@cloudflare/vite-plugin@1.27.0(vite@7.3.1(@types/node@24.10.13)(jiti@2.6.1)(terser@5.46.1)(yaml@2.8.2))(workerd@1.20260310.1)(wrangler@4.72.0)': + '@cloudflare/vite-plugin@1.27.0(vite@7.3.1(@types/node@24.10.13)(jiti@2.6.1)(terser@5.47.1)(yaml@2.8.2))(workerd@1.20260310.1)(wrangler@4.72.0)': dependencies: '@cloudflare/unenv-preset': 2.15.0(unenv@2.0.0-rc.24)(workerd@1.20260310.1) miniflare: 4.20260310.0 unenv: 2.0.0-rc.24 - vite: 7.3.1(@types/node@24.10.13)(jiti@2.6.1)(terser@5.46.1)(yaml@2.8.2) + vite: 7.3.1(@types/node@24.10.13)(jiti@2.6.1)(terser@5.47.1)(yaml@2.8.2) wrangler: 4.72.0 ws: 8.18.0 transitivePeerDependencies: @@ -7541,7 +7608,7 @@ snapshots: '@types/resolve': 1.20.2 deepmerge: 4.3.1 is-module: 1.0.0 - resolve: 1.22.11 + resolve: 1.22.12 optionalDependencies: rollup: 4.59.0 @@ -7555,7 +7622,7 @@ snapshots: dependencies: serialize-javascript: 7.0.5 smob: 1.6.1 - terser: 5.46.1 + terser: 5.47.1 optionalDependencies: rollup: 4.59.0 @@ -8056,12 +8123,12 @@ snapshots: transitivePeerDependencies: - supports-color - '@vanilla-extract/compiler@0.3.4(@types/node@24.10.13)(jiti@2.6.1)(terser@5.46.1)(yaml@2.8.2)': + '@vanilla-extract/compiler@0.3.4(@types/node@24.10.13)(jiti@2.6.1)(terser@5.47.1)(yaml@2.8.2)': dependencies: '@vanilla-extract/css': 1.18.0 '@vanilla-extract/integration': 8.0.7 - vite: 7.3.1(@types/node@24.10.13)(jiti@2.6.1)(terser@5.46.1)(yaml@2.8.2) - vite-node: 3.2.4(@types/node@24.10.13)(jiti@2.6.1)(terser@5.46.1)(yaml@2.8.2) + vite: 7.3.1(@types/node@24.10.13)(jiti@2.6.1)(terser@5.47.1)(yaml@2.8.2) + vite-node: 3.2.4(@types/node@24.10.13)(jiti@2.6.1)(terser@5.47.1)(yaml@2.8.2) transitivePeerDependencies: - '@types/node' - babel-plugin-macros @@ -8116,11 +8183,11 @@ snapshots: dependencies: '@vanilla-extract/css': 1.18.0 - '@vanilla-extract/vite-plugin@5.1.4(@types/node@24.10.13)(jiti@2.6.1)(terser@5.46.1)(vite@7.3.1(@types/node@24.10.13)(jiti@2.6.1)(terser@5.46.1)(yaml@2.8.2))(yaml@2.8.2)': + '@vanilla-extract/vite-plugin@5.1.4(@types/node@24.10.13)(jiti@2.6.1)(terser@5.47.1)(vite@7.3.1(@types/node@24.10.13)(jiti@2.6.1)(terser@5.47.1)(yaml@2.8.2))(yaml@2.8.2)': dependencies: - '@vanilla-extract/compiler': 0.3.4(@types/node@24.10.13)(jiti@2.6.1)(terser@5.46.1)(yaml@2.8.2) + '@vanilla-extract/compiler': 0.3.4(@types/node@24.10.13)(jiti@2.6.1)(terser@5.47.1)(yaml@2.8.2) '@vanilla-extract/integration': 8.0.7 - vite: 7.3.1(@types/node@24.10.13)(jiti@2.6.1)(terser@5.46.1)(yaml@2.8.2) + vite: 7.3.1(@types/node@24.10.13)(jiti@2.6.1)(terser@5.47.1)(yaml@2.8.2) transitivePeerDependencies: - '@types/node' - babel-plugin-macros @@ -8136,7 +8203,7 @@ snapshots: - tsx - yaml - '@vitejs/plugin-react@5.1.4(vite@7.3.1(@types/node@24.10.13)(jiti@2.6.1)(terser@5.46.1)(yaml@2.8.2))': + '@vitejs/plugin-react@5.1.4(vite@7.3.1(@types/node@24.10.13)(jiti@2.6.1)(terser@5.47.1)(yaml@2.8.2))': dependencies: '@babel/core': 7.29.0 '@babel/plugin-transform-react-jsx-self': 7.27.1(@babel/core@7.29.0) @@ -8144,7 +8211,7 @@ snapshots: '@rolldown/pluginutils': 1.0.0-rc.3 '@types/babel__core': 7.20.5 react-refresh: 0.18.0 - vite: 7.3.1(@types/node@24.10.13)(jiti@2.6.1)(terser@5.46.1)(yaml@2.8.2) + vite: 7.3.1(@types/node@24.10.13)(jiti@2.6.1)(terser@5.47.1)(yaml@2.8.2) transitivePeerDependencies: - supports-color @@ -8160,7 +8227,7 @@ snapshots: obug: 2.1.1 std-env: 4.0.0 tinyrainbow: 3.1.0 - vitest: 4.1.0(@types/node@24.10.13)(@vitest/ui@4.1.0)(jsdom@29.0.0)(vite@7.3.1(@types/node@24.10.13)(jiti@2.6.1)(terser@5.46.1)(yaml@2.8.2)) + vitest: 4.1.0(@types/node@24.10.13)(@vitest/ui@4.1.0)(jsdom@29.0.0)(vite@7.3.1(@types/node@24.10.13)(jiti@2.6.1)(terser@5.47.1)(yaml@2.8.2)) '@vitest/expect@4.1.0': dependencies: @@ -8171,13 +8238,13 @@ snapshots: chai: 6.2.2 tinyrainbow: 3.1.0 - '@vitest/mocker@4.1.0(vite@7.3.1(@types/node@24.10.13)(jiti@2.6.1)(terser@5.46.1)(yaml@2.8.2))': + '@vitest/mocker@4.1.0(vite@7.3.1(@types/node@24.10.13)(jiti@2.6.1)(terser@5.47.1)(yaml@2.8.2))': dependencies: '@vitest/spy': 4.1.0 estree-walker: 3.0.3 magic-string: 0.30.21 optionalDependencies: - vite: 7.3.1(@types/node@24.10.13)(jiti@2.6.1)(terser@5.46.1)(yaml@2.8.2) + vite: 7.3.1(@types/node@24.10.13)(jiti@2.6.1)(terser@5.47.1)(yaml@2.8.2) '@vitest/pretty-format@4.1.0': dependencies: @@ -8206,7 +8273,7 @@ snapshots: sirv: 3.0.2 tinyglobby: 0.2.15 tinyrainbow: 3.1.0 - vitest: 4.1.0(@types/node@24.10.13)(@vitest/ui@4.1.0)(jsdom@29.0.0)(vite@7.3.1(@types/node@24.10.13)(jiti@2.6.1)(terser@5.46.1)(yaml@2.8.2)) + vitest: 4.1.0(@types/node@24.10.13)(@vitest/ui@4.1.0)(jsdom@29.0.0)(vite@7.3.1(@types/node@24.10.13)(jiti@2.6.1)(terser@5.47.1)(yaml@2.8.2)) '@vitest/utils@4.1.0': dependencies: @@ -8222,10 +8289,10 @@ snapshots: transitivePeerDependencies: - supports-color - ajv@8.18.0: + ajv@8.20.0: dependencies: fast-deep-equal: 3.1.3 - fast-uri: 3.1.0 + fast-uri: 3.1.2 json-schema-traverse: 1.0.0 require-from-string: 2.0.2 @@ -8256,9 +8323,9 @@ snapshots: arraybuffer.prototype.slice@1.0.4: dependencies: array-buffer-byte-length: 1.0.2 - call-bind: 1.0.8 + call-bind: 1.0.9 define-properties: 1.2.1 - es-abstract: 1.24.1 + es-abstract: 1.24.2 es-errors: 1.3.0 get-intrinsic: 1.3.0 is-array-buffer: 3.0.5 @@ -8285,7 +8352,7 @@ snapshots: babel-plugin-polyfill-corejs2@0.4.17(@babel/core@7.29.0): dependencies: - '@babel/compat-data': 7.29.0 + '@babel/compat-data': 7.29.3 '@babel/core': 7.29.0 '@babel/helper-define-polyfill-provider': 0.6.8(@babel/core@7.29.0) semver: 6.3.1 @@ -8317,6 +8384,8 @@ snapshots: baseline-browser-mapping@2.10.0: {} + baseline-browser-mapping@2.10.27: {} + bidi-js@1.0.3: dependencies: require-from-string: 2.0.2 @@ -8333,6 +8402,10 @@ snapshots: dependencies: balanced-match: 4.0.4 + brace-expansion@5.0.6: + dependencies: + balanced-match: 4.0.4 + braces@3.0.3: dependencies: fill-range: 7.1.1 @@ -8347,6 +8420,14 @@ snapshots: node-releases: 2.0.36 update-browserslist-db: 1.2.3(browserslist@4.28.1) + browserslist@4.28.2: + dependencies: + baseline-browser-mapping: 2.10.27 + caniuse-lite: 1.0.30001792 + electron-to-chromium: 1.5.352 + node-releases: 2.0.38 + update-browserslist-db: 1.2.3(browserslist@4.28.2) + bs58@6.0.0: dependencies: base-x: 5.0.1 @@ -8365,7 +8446,7 @@ snapshots: es-errors: 1.3.0 function-bind: 1.1.2 - call-bind@1.0.8: + call-bind@1.0.9: dependencies: call-bind-apply-helpers: 1.0.2 es-define-property: 1.0.1 @@ -8383,6 +8464,8 @@ snapshots: caniuse-lite@1.0.30001777: {} + caniuse-lite@1.0.30001792: {} + chai@6.2.2: {} chokidar@3.6.0: @@ -8407,6 +8490,8 @@ snapshots: commander@2.20.3: {} + commander@8.3.0: {} + common-tags@1.8.2: {} compute-scroll-into-view@3.1.1: {} @@ -8421,7 +8506,7 @@ snapshots: core-js-compat@3.49.0: dependencies: - browserslist: 4.28.1 + browserslist: 4.28.2 cosmiconfig@8.3.6(typescript@5.9.3): dependencies: @@ -8561,6 +8646,8 @@ snapshots: electron-to-chromium@1.5.307: {} + electron-to-chromium@1.5.352: {} + emojibase-data@15.3.2(emojibase@15.3.1): dependencies: emojibase: 15.3.1 @@ -8579,12 +8666,12 @@ snapshots: error-stack-parser-es@1.0.5: {} - es-abstract@1.24.1: + es-abstract@1.24.2: dependencies: array-buffer-byte-length: 1.0.2 arraybuffer.prototype.slice: 1.0.4 available-typed-arrays: 1.0.7 - call-bind: 1.0.8 + call-bind: 1.0.9 call-bound: 1.0.4 data-view-buffer: 1.0.2 data-view-byte-length: 1.0.2 @@ -8603,7 +8690,7 @@ snapshots: has-property-descriptors: 1.0.2 has-proto: 1.2.0 has-symbols: 1.1.0 - hasown: 2.0.2 + hasown: 2.0.3 internal-slot: 1.1.0 is-array-buffer: 3.0.5 is-callable: 1.2.7 @@ -8621,7 +8708,7 @@ snapshots: object.assign: 4.1.7 own-keys: 1.0.1 regexp.prototype.flags: 1.5.4 - safe-array-concat: 1.1.3 + safe-array-concat: 1.1.4 safe-push-apply: 1.0.0 safe-regex-test: 1.1.0 set-proto: 1.0.0 @@ -8653,7 +8740,7 @@ snapshots: es-errors: 1.3.0 get-intrinsic: 1.3.0 has-tostringtag: 1.0.2 - hasown: 2.0.2 + hasown: 2.0.3 es-to-primitive@1.3.0: dependencies: @@ -8725,7 +8812,7 @@ snapshots: fast-json-stable-stringify@2.1.0: {} - fast-uri@3.1.0: {} + fast-uri@3.1.2: {} fastq@1.20.1: dependencies: @@ -8745,7 +8832,7 @@ snapshots: filelist@1.0.6: dependencies: - minimatch: 10.2.4 + minimatch: 10.2.5 fill-range@7.1.1: dependencies: @@ -8804,7 +8891,7 @@ snapshots: dependencies: at-least-node: 1.0.0 graceful-fs: 4.2.11 - jsonfile: 6.2.0 + jsonfile: 6.2.1 universalify: 2.0.1 fsevents@2.3.3: @@ -8814,11 +8901,11 @@ snapshots: function.prototype.name@1.1.8: dependencies: - call-bind: 1.0.8 + call-bind: 1.0.9 call-bound: 1.0.4 define-properties: 1.2.1 functions-have-names: 1.2.3 - hasown: 2.0.2 + hasown: 2.0.3 is-callable: 1.2.7 functions-have-names@1.2.3: {} @@ -8837,7 +8924,7 @@ snapshots: get-proto: 1.0.1 gopd: 1.2.0 has-symbols: 1.1.0 - hasown: 2.0.2 + hasown: 2.0.3 math-intrinsics: 1.1.0 get-own-enumerable-property-symbols@3.0.2: {} @@ -8861,7 +8948,7 @@ snapshots: dependencies: foreground-child: 3.3.1 jackspeak: 4.2.3 - minimatch: 10.2.4 + minimatch: 10.2.5 minipass: 7.1.3 package-json-from-dist: 1.0.1 path-scurry: 2.0.2 @@ -8899,7 +8986,7 @@ snapshots: dependencies: has-symbols: 1.1.0 - hasown@2.0.2: + hasown@2.0.3: dependencies: function-bind: 1.1.2 @@ -8992,7 +9079,7 @@ snapshots: internal-slot@1.1.0: dependencies: es-errors: 1.3.0 - hasown: 2.0.2 + hasown: 2.0.3 side-channel: 1.1.0 intl-messageformat@10.7.18: @@ -9004,7 +9091,7 @@ snapshots: is-array-buffer@3.0.5: dependencies: - call-bind: 1.0.8 + call-bind: 1.0.9 call-bound: 1.0.4 get-intrinsic: 1.3.0 @@ -9033,9 +9120,9 @@ snapshots: is-callable@1.2.7: {} - is-core-module@2.16.1: + is-core-module@2.16.2: dependencies: - hasown: 2.0.2 + hasown: 2.0.3 is-data-view@1.0.2: dependencies: @@ -9094,7 +9181,7 @@ snapshots: call-bound: 1.0.4 gopd: 1.2.0 has-tostringtag: 1.0.2 - hasown: 2.0.2 + hasown: 2.0.3 is-regexp@1.0.0: {} @@ -9210,11 +9297,9 @@ snapshots: json-schema-traverse@1.0.0: {} - json-schema@0.4.0: {} - json5@2.2.3: {} - jsonfile@6.2.0: + jsonfile@6.2.1: dependencies: universalify: 2.0.1 optionalDependencies: @@ -9224,6 +9309,10 @@ snapshots: jwt-decode@4.0.0: {} + katex@0.16.45: + dependencies: + commander: 8.3.0 + kleur@4.1.5: {} knip@5.85.0(@types/node@24.10.13)(typescript@5.9.3): @@ -9264,6 +9353,8 @@ snapshots: lodash@4.17.23: {} + lodash@4.18.1: {} + loglevel@1.9.2: {} loose-envify@1.4.0: @@ -9304,6 +9395,8 @@ snapshots: dependencies: semver: 7.7.4 + marked@18.0.2: {} + math-intrinsics@1.1.0: {} matrix-events-sdk@0.0.1: {} @@ -9361,6 +9454,10 @@ snapshots: dependencies: brace-expansion: 5.0.4 + minimatch@10.2.5: + dependencies: + brace-expansion: 5.0.6 + minimist@1.2.8: {} minipass@7.1.3: {} @@ -9400,6 +9497,8 @@ snapshots: node-releases@2.0.36: {} + node-releases@2.0.38: {} + normalize-path@3.0.0: {} object-assign@4.1.1: {} @@ -9410,7 +9509,7 @@ snapshots: object.assign@4.1.7: dependencies: - call-bind: 1.0.8 + call-bind: 1.0.9 call-bound: 1.0.4 define-properties: 1.2.1 es-object-atoms: 1.1.1 @@ -9735,9 +9834,9 @@ snapshots: reflect.getprototypeof@1.0.10: dependencies: - call-bind: 1.0.8 + call-bind: 1.0.9 define-properties: 1.2.1 - es-abstract: 1.24.1 + es-abstract: 1.24.2 es-errors: 1.3.0 es-object-atoms: 1.1.1 get-intrinsic: 1.3.0 @@ -9752,7 +9851,7 @@ snapshots: regexp.prototype.flags@1.5.4: dependencies: - call-bind: 1.0.8 + call-bind: 1.0.9 define-properties: 1.2.1 es-errors: 1.3.0 get-proto: 1.0.1 @@ -9764,13 +9863,13 @@ snapshots: regenerate: 1.4.2 regenerate-unicode-properties: 10.2.2 regjsgen: 0.8.0 - regjsparser: 0.13.0 + regjsparser: 0.13.1 unicode-match-property-ecmascript: 2.0.0 unicode-match-property-value-ecmascript: 2.2.1 regjsgen@0.8.0: {} - regjsparser@0.13.0: + regjsparser@0.13.1: dependencies: jsesc: 3.1.0 @@ -9780,9 +9879,10 @@ snapshots: resolve-from@4.0.0: {} - resolve@1.22.11: + resolve@1.22.12: dependencies: - is-core-module: 2.16.1 + es-errors: 1.3.0 + is-core-module: 2.16.2 path-parse: 1.0.7 supports-preserve-symlinks-flag: 1.0.0 @@ -9823,9 +9923,9 @@ snapshots: dependencies: queue-microtask: 1.2.3 - safe-array-concat@1.1.3: + safe-array-concat@1.1.4: dependencies: - call-bind: 1.0.8 + call-bind: 1.0.9 call-bound: 1.0.4 get-intrinsic: 1.3.0 has-symbols: 1.1.0 @@ -9921,7 +10021,7 @@ snapshots: shebang-regex@3.0.0: {} - side-channel-list@1.0.0: + side-channel-list@1.0.1: dependencies: es-errors: 1.3.0 object-inspect: 1.13.4 @@ -9945,7 +10045,7 @@ snapshots: dependencies: es-errors: 1.3.0 object-inspect: 1.13.4 - side-channel-list: 1.0.0 + side-channel-list: 1.0.1 side-channel-map: 1.0.1 side-channel-weakmap: 1.0.2 @@ -10025,10 +10125,10 @@ snapshots: string.prototype.matchall@4.0.12: dependencies: - call-bind: 1.0.8 + call-bind: 1.0.9 call-bound: 1.0.4 define-properties: 1.2.1 - es-abstract: 1.24.1 + es-abstract: 1.24.2 es-errors: 1.3.0 es-object-atoms: 1.1.1 get-intrinsic: 1.3.0 @@ -10041,24 +10141,24 @@ snapshots: string.prototype.trim@1.2.10: dependencies: - call-bind: 1.0.8 + call-bind: 1.0.9 call-bound: 1.0.4 define-data-property: 1.1.4 define-properties: 1.2.1 - es-abstract: 1.24.1 + es-abstract: 1.24.2 es-object-atoms: 1.1.1 has-property-descriptors: 1.0.2 string.prototype.trimend@1.0.9: dependencies: - call-bind: 1.0.8 + call-bind: 1.0.9 call-bound: 1.0.4 define-properties: 1.2.1 es-object-atoms: 1.1.1 string.prototype.trimstart@1.0.8: dependencies: - call-bind: 1.0.8 + call-bind: 1.0.9 define-properties: 1.2.1 es-object-atoms: 1.1.1 @@ -10109,7 +10209,7 @@ snapshots: type-fest: 0.16.0 unique-string: 2.0.0 - terser@5.46.1: + terser@5.47.1: dependencies: '@jridgewell/source-map': 0.3.11 acorn: 8.16.0 @@ -10169,7 +10269,7 @@ snapshots: typed-array-byte-length@1.0.3: dependencies: - call-bind: 1.0.8 + call-bind: 1.0.9 for-each: 0.3.5 gopd: 1.2.0 has-proto: 1.2.0 @@ -10178,7 +10278,7 @@ snapshots: typed-array-byte-offset@1.0.4: dependencies: available-typed-arrays: 1.0.7 - call-bind: 1.0.8 + call-bind: 1.0.9 for-each: 0.3.5 gopd: 1.2.0 has-proto: 1.2.0 @@ -10187,7 +10287,7 @@ snapshots: typed-array-length@1.0.7: dependencies: - call-bind: 1.0.8 + call-bind: 1.0.9 for-each: 0.3.5 gopd: 1.2.0 is-typed-array: 1.1.15 @@ -10242,6 +10342,12 @@ snapshots: escalade: 3.2.0 picocolors: 1.1.1 + update-browserslist-db@1.2.3(browserslist@4.28.2): + dependencies: + browserslist: 4.28.2 + escalade: 3.2.0 + picocolors: 1.1.1 + use-sync-external-store@1.6.0(react@18.3.1): dependencies: react: 18.3.1 @@ -10255,13 +10361,13 @@ snapshots: react: 18.3.1 react-dom: 18.3.1(react@18.3.1) - vite-node@3.2.4(@types/node@24.10.13)(jiti@2.6.1)(terser@5.46.1)(yaml@2.8.2): + vite-node@3.2.4(@types/node@24.10.13)(jiti@2.6.1)(terser@5.47.1)(yaml@2.8.2): dependencies: cac: 6.7.14 debug: 4.4.3 es-module-lexer: 1.7.0 pathe: 2.0.3 - vite: 7.3.1(@types/node@24.10.13)(jiti@2.6.1)(terser@5.46.1)(yaml@2.8.2) + vite: 7.3.1(@types/node@24.10.13)(jiti@2.6.1)(terser@5.47.1)(yaml@2.8.2) transitivePeerDependencies: - '@types/node' - jiti @@ -10283,48 +10389,48 @@ snapshots: transitivePeerDependencies: - rollup - vite-plugin-pwa@1.2.0(vite@7.3.1(@types/node@24.10.13)(jiti@2.6.1)(terser@5.46.1)(yaml@2.8.2))(workbox-build@7.4.0(@types/babel__core@7.20.5))(workbox-window@7.4.0): + vite-plugin-pwa@1.2.0(vite@7.3.1(@types/node@24.10.13)(jiti@2.6.1)(terser@5.47.1)(yaml@2.8.2))(workbox-build@7.4.0(@types/babel__core@7.20.5))(workbox-window@7.4.0): dependencies: debug: 4.4.3 pretty-bytes: 6.1.1 tinyglobby: 0.2.15 - vite: 7.3.1(@types/node@24.10.13)(jiti@2.6.1)(terser@5.46.1)(yaml@2.8.2) + vite: 7.3.1(@types/node@24.10.13)(jiti@2.6.1)(terser@5.47.1)(yaml@2.8.2) workbox-build: 7.4.0(@types/babel__core@7.20.5) workbox-window: 7.4.0 transitivePeerDependencies: - supports-color - vite-plugin-static-copy@3.2.0(vite@7.3.1(@types/node@24.10.13)(jiti@2.6.1)(terser@5.46.1)(yaml@2.8.2)): + vite-plugin-static-copy@3.2.0(vite@7.3.1(@types/node@24.10.13)(jiti@2.6.1)(terser@5.47.1)(yaml@2.8.2)): dependencies: chokidar: 3.6.0 p-map: 7.0.4 picocolors: 1.1.1 tinyglobby: 0.2.15 - vite: 7.3.1(@types/node@24.10.13)(jiti@2.6.1)(terser@5.46.1)(yaml@2.8.2) + vite: 7.3.1(@types/node@24.10.13)(jiti@2.6.1)(terser@5.47.1)(yaml@2.8.2) - vite-plugin-svgr@4.5.0(rollup@4.59.0)(typescript@5.9.3)(vite@7.3.1(@types/node@24.10.13)(jiti@2.6.1)(terser@5.46.1)(yaml@2.8.2)): + vite-plugin-svgr@4.5.0(rollup@4.59.0)(typescript@5.9.3)(vite@7.3.1(@types/node@24.10.13)(jiti@2.6.1)(terser@5.47.1)(yaml@2.8.2)): dependencies: '@rollup/pluginutils': 5.3.0(rollup@4.59.0) '@svgr/core': 8.1.0(typescript@5.9.3) '@svgr/plugin-jsx': 8.1.0(@svgr/core@8.1.0(typescript@5.9.3)) - vite: 7.3.1(@types/node@24.10.13)(jiti@2.6.1)(terser@5.46.1)(yaml@2.8.2) + vite: 7.3.1(@types/node@24.10.13)(jiti@2.6.1)(terser@5.47.1)(yaml@2.8.2) transitivePeerDependencies: - rollup - supports-color - typescript - vite-plugin-top-level-await@1.6.0(@swc/helpers@0.5.19)(rollup@4.59.0)(vite@7.3.1(@types/node@24.10.13)(jiti@2.6.1)(terser@5.46.1)(yaml@2.8.2)): + vite-plugin-top-level-await@1.6.0(@swc/helpers@0.5.19)(rollup@4.59.0)(vite@7.3.1(@types/node@24.10.13)(jiti@2.6.1)(terser@5.47.1)(yaml@2.8.2)): dependencies: '@rollup/plugin-virtual': 3.0.2(rollup@4.59.0) '@swc/core': 1.15.18(@swc/helpers@0.5.19) '@swc/wasm': 1.15.18 uuid: 10.0.0 - vite: 7.3.1(@types/node@24.10.13)(jiti@2.6.1)(terser@5.46.1)(yaml@2.8.2) + vite: 7.3.1(@types/node@24.10.13)(jiti@2.6.1)(terser@5.47.1)(yaml@2.8.2) transitivePeerDependencies: - '@swc/helpers' - rollup - vite@7.3.1(@types/node@24.10.13)(jiti@2.6.1)(terser@5.46.1)(yaml@2.8.2): + vite@7.3.1(@types/node@24.10.13)(jiti@2.6.1)(terser@5.47.1)(yaml@2.8.2): dependencies: esbuild: 0.27.3 fdir: 6.5.0(picomatch@4.0.3) @@ -10336,13 +10442,13 @@ snapshots: '@types/node': 24.10.13 fsevents: 2.3.3 jiti: 2.6.1 - terser: 5.46.1 + terser: 5.47.1 yaml: 2.8.2 - vitest@4.1.0(@types/node@24.10.13)(@vitest/ui@4.1.0)(jsdom@29.0.0)(vite@7.3.1(@types/node@24.10.13)(jiti@2.6.1)(terser@5.46.1)(yaml@2.8.2)): + vitest@4.1.0(@types/node@24.10.13)(@vitest/ui@4.1.0)(jsdom@29.0.0)(vite@7.3.1(@types/node@24.10.13)(jiti@2.6.1)(terser@5.47.1)(yaml@2.8.2)): dependencies: '@vitest/expect': 4.1.0 - '@vitest/mocker': 4.1.0(vite@7.3.1(@types/node@24.10.13)(jiti@2.6.1)(terser@5.46.1)(yaml@2.8.2)) + '@vitest/mocker': 4.1.0(vite@7.3.1(@types/node@24.10.13)(jiti@2.6.1)(terser@5.47.1)(yaml@2.8.2)) '@vitest/pretty-format': 4.1.0 '@vitest/runner': 4.1.0 '@vitest/snapshot': 4.1.0 @@ -10359,7 +10465,7 @@ snapshots: tinyexec: 1.0.4 tinyglobby: 0.2.15 tinyrainbow: 3.1.0 - vite: 7.3.1(@types/node@24.10.13)(jiti@2.6.1)(terser@5.46.1)(yaml@2.8.2) + vite: 7.3.1(@types/node@24.10.13)(jiti@2.6.1)(terser@5.47.1)(yaml@2.8.2) why-is-node-running: 2.3.0 optionalDependencies: '@types/node': 24.10.13 @@ -10437,7 +10543,7 @@ snapshots: which-typed-array@1.1.20: dependencies: available-typed-arrays: 1.0.7 - call-bind: 1.0.8 + call-bind: 1.0.9 call-bound: 1.0.4 for-each: 0.3.5 get-proto: 1.0.1 @@ -10464,21 +10570,21 @@ snapshots: workbox-build@7.4.0(@types/babel__core@7.20.5): dependencies: - '@apideck/better-ajv-errors': 0.3.6(ajv@8.18.0) + '@apideck/better-ajv-errors': 0.3.7(ajv@8.20.0) '@babel/core': 7.29.0 - '@babel/preset-env': 7.29.2(@babel/core@7.29.0) + '@babel/preset-env': 7.29.5(@babel/core@7.29.0) '@babel/runtime': 7.29.2 '@rollup/plugin-babel': 5.3.1(@babel/core@7.29.0)(@types/babel__core@7.20.5)(rollup@4.59.0) '@rollup/plugin-node-resolve': 15.3.1(rollup@4.59.0) '@rollup/plugin-replace': 2.4.2(rollup@4.59.0) '@rollup/plugin-terser': 0.4.4(rollup@4.59.0) '@surma/rollup-plugin-off-main-thread': 2.2.3 - ajv: 8.18.0 + ajv: 8.20.0 common-tags: 1.8.2 fast-json-stable-stringify: 2.1.0 fs-extra: 9.1.0 glob: 11.1.0 - lodash: 4.17.23 + lodash: 4.18.1 pretty-bytes: 5.6.0 rollup: 4.59.0 source-map: 0.8.0-beta.0 diff --git a/public/favicon.png b/public/favicon.png index 4205ad01c..4638bcb33 100644 Binary files a/public/favicon.png and b/public/favicon.png differ diff --git a/public/full_res_sable.png b/public/full_res_sable.png index f63c2beab..cb7d599e3 100644 Binary files a/public/full_res_sable.png and b/public/full_res_sable.png differ diff --git a/public/manifest.json b/public/manifest.json index 134a5eb4b..c171e2325 100644 --- a/public/manifest.json +++ b/public/manifest.json @@ -11,163 +11,163 @@ "theme_color": "#1b1a21", "icons": [ { - "src": "./public/svg/cinny-logo-maskable.svg", + "src": "./public/svg/logo-maskable.svg", "sizes": "any", "type": "image/svg+xml", "purpose": "maskable" }, { - "src": "./public/logo-maskable/cinny-logo-maskable-512x512.png", + "src": "./public/logo-maskable/logo-maskable-512x512.png", "sizes": "512x512", "type": "image/png", "purpose": "maskable" }, { - "src": "./public/logo-maskable/cinny-logo-maskable-384x384.png", + "src": "./public/logo-maskable/logo-maskable-384x384.png", "sizes": "384x384", "type": "image/png", "purpose": "maskable" }, { - "src": "./public/logo-maskable/cinny-logo-maskable-256x256.png", + "src": "./public/logo-maskable/logo-maskable-256x256.png", "sizes": "256x256", "type": "image/png", "purpose": "maskable" }, { - "src": "./public/logo-maskable/cinny-logo-maskable-192x192.png", + "src": "./public/logo-maskable/logo-maskable-192x192.png", "sizes": "192x192", "type": "image/png", "purpose": "maskable" }, { - "src": "./public/logo-maskable/cinny-logo-maskable-180x180.png", + "src": "./public/logo-maskable/logo-maskable-180x180.png", "sizes": "180x180", "type": "image/png", "purpose": "maskable" }, { - "src": "./public/logo-maskable/cinny-logo-maskable-167x167.png", + "src": "./public/logo-maskable/logo-maskable-167x167.png", "sizes": "167x167", "type": "image/png", "purpose": "maskable" }, { - "src": "./public/logo-maskable/cinny-logo-maskable-152x152.png", + "src": "./public/logo-maskable/logo-maskable-152x152.png", "sizes": "152x152", "type": "image/png", "purpose": "maskable" }, { - "src": "./public/logo-maskable/cinny-logo-maskable-144x144.png", + "src": "./public/logo-maskable/logo-maskable-144x144.png", "sizes": "144x144", "type": "image/png", "purpose": "maskable" }, { - "src": "./public/logo-maskable/cinny-logo-maskable-120x120.png", + "src": "./public/logo-maskable/logo-maskable-120x120.png", "sizes": "120x120", "type": "image/png", "purpose": "maskable" }, { - "src": "./public/logo-maskable/cinny-logo-maskable-114x114.png", + "src": "./public/logo-maskable/logo-maskable-114x114.png", "sizes": "114x114", "type": "image/png", "purpose": "maskable" }, { - "src": "./public/logo-maskable/cinny-logo-maskable-96x96.png", + "src": "./public/logo-maskable/logo-maskable-96x96.png", "sizes": "96x96", "type": "image/png", "purpose": "maskable" }, { - "src": "./public/logo-maskable/cinny-logo-maskable-76x76.png", + "src": "./public/logo-maskable/logo-maskable-76x76.png", "sizes": "76x76", "type": "image/png", "purpose": "maskable" }, { - "src": "./public/logo-maskable/cinny-logo-maskable-72x72.png", + "src": "./public/logo-maskable/logo-maskable-72x72.png", "sizes": "72x72", "type": "image/png", "purpose": "maskable" }, { - "src": "./public/logo-maskable/cinny-logo-maskable-60x60.png", + "src": "./public/logo-maskable/logo-maskable-60x60.png", "sizes": "60x60", "type": "image/png", "purpose": "maskable" }, { - "src": "./public/logo-maskable/cinny-logo-maskable-57x57.png", + "src": "./public/logo-maskable/logo-maskable-57x57.png", "sizes": "57x57", "type": "image/png", "purpose": "maskable" }, { - "src": "./public/logo-maskable/cinny-logo-maskable-48x48.png", + "src": "./public/logo-maskable/logo-maskable-48x48.png", "sizes": "48x48", "type": "image/png", "purpose": "maskable" }, { - "src": "./public/logo-maskable/cinny-logo-maskable-36x36.png", + "src": "./public/logo-maskable/logo-maskable-36x36.png", "sizes": "36x36", "type": "image/png", "purpose": "maskable" }, { - "src": "./public/svg/cinny-logo.svg", + "src": "./public/svg/logo.svg", "sizes": "any", "type": "image/svg+xml", "purpose": "any" }, { - "src": "./public/logo/cinny-logo-512x512.png", + "src": "./public/logo/logo-512x512.png", "sizes": "512x512", "type": "image/png", "purpose": "any" }, { - "src": "./public/logo/cinny-logo-384x384.png", + "src": "./public/logo/logo-384x384.png", "sizes": "384x384", "type": "image/png", "purpose": "any" }, { - "src": "./public/logo/cinny-logo-256x256.png", + "src": "./public/logo/logo-256x256.png", "sizes": "256x256", "type": "image/png", "purpose": "any" }, { - "src": "./public/logo/cinny-logo-192x192.png", + "src": "./public/logo/logo-192x192.png", "sizes": "192x192", "type": "image/png", "purpose": "any" }, { - "src": "./public/logo/cinny-logo-144x144.png", + "src": "./public/logo/logo-144x144.png", "sizes": "144x144", "type": "image/png", "purpose": "any" }, { - "src": "./public/logo/cinny-logo-96x96.png", + "src": "./public/logo/logo-96x96.png", "sizes": "96x96", "type": "image/png", "purpose": "any" }, { - "src": "./public/logo/cinny-logo-72x72.png", + "src": "./public/logo/logo-72x72.png", "sizes": "72x72", "type": "image/png", "purpose": "any" }, { - "src": "./public/logo/cinny-logo-48x48.png", + "src": "./public/logo/logo-48x48.png", "sizes": "48x48", "type": "image/png", "purpose": "any" diff --git a/public/res/logo-maskable/cinny-logo-maskable-114x114.png b/public/res/logo-maskable/cinny-logo-maskable-114x114.png deleted file mode 100644 index 59463adb8..000000000 Binary files a/public/res/logo-maskable/cinny-logo-maskable-114x114.png and /dev/null differ diff --git a/public/res/logo-maskable/cinny-logo-maskable-120x120.png b/public/res/logo-maskable/cinny-logo-maskable-120x120.png deleted file mode 100644 index 4e185fba3..000000000 Binary files a/public/res/logo-maskable/cinny-logo-maskable-120x120.png and /dev/null differ diff --git a/public/res/logo-maskable/cinny-logo-maskable-144x144.png b/public/res/logo-maskable/cinny-logo-maskable-144x144.png deleted file mode 100644 index f674110ff..000000000 Binary files a/public/res/logo-maskable/cinny-logo-maskable-144x144.png and /dev/null differ diff --git a/public/res/logo-maskable/cinny-logo-maskable-152x152.png b/public/res/logo-maskable/cinny-logo-maskable-152x152.png deleted file mode 100644 index 8de192a1e..000000000 Binary files a/public/res/logo-maskable/cinny-logo-maskable-152x152.png and /dev/null differ diff --git a/public/res/logo-maskable/cinny-logo-maskable-167x167.png b/public/res/logo-maskable/cinny-logo-maskable-167x167.png deleted file mode 100644 index 146db2de3..000000000 Binary files a/public/res/logo-maskable/cinny-logo-maskable-167x167.png and /dev/null differ diff --git a/public/res/logo-maskable/cinny-logo-maskable-180x180.png b/public/res/logo-maskable/cinny-logo-maskable-180x180.png deleted file mode 100644 index 14e2764bd..000000000 Binary files a/public/res/logo-maskable/cinny-logo-maskable-180x180.png and /dev/null differ diff --git a/public/res/logo-maskable/cinny-logo-maskable-192x192.png b/public/res/logo-maskable/cinny-logo-maskable-192x192.png deleted file mode 100644 index 45b3f74d4..000000000 Binary files a/public/res/logo-maskable/cinny-logo-maskable-192x192.png and /dev/null differ diff --git a/public/res/logo-maskable/cinny-logo-maskable-256x256.png b/public/res/logo-maskable/cinny-logo-maskable-256x256.png deleted file mode 100644 index ebfadb35b..000000000 Binary files a/public/res/logo-maskable/cinny-logo-maskable-256x256.png and /dev/null differ diff --git a/public/res/logo-maskable/cinny-logo-maskable-36x36.png b/public/res/logo-maskable/cinny-logo-maskable-36x36.png deleted file mode 100644 index f80ba44c3..000000000 Binary files a/public/res/logo-maskable/cinny-logo-maskable-36x36.png and /dev/null differ diff --git a/public/res/logo-maskable/cinny-logo-maskable-384x384.png b/public/res/logo-maskable/cinny-logo-maskable-384x384.png deleted file mode 100644 index e6fbb3dc0..000000000 Binary files a/public/res/logo-maskable/cinny-logo-maskable-384x384.png and /dev/null differ diff --git a/public/res/logo-maskable/cinny-logo-maskable-48x48.png b/public/res/logo-maskable/cinny-logo-maskable-48x48.png deleted file mode 100644 index 4dd14e8f8..000000000 Binary files a/public/res/logo-maskable/cinny-logo-maskable-48x48.png and /dev/null differ diff --git a/public/res/logo-maskable/cinny-logo-maskable-512x512.png b/public/res/logo-maskable/cinny-logo-maskable-512x512.png deleted file mode 100644 index e4e31a720..000000000 Binary files a/public/res/logo-maskable/cinny-logo-maskable-512x512.png and /dev/null differ diff --git a/public/res/logo-maskable/cinny-logo-maskable-57x57.png b/public/res/logo-maskable/cinny-logo-maskable-57x57.png deleted file mode 100644 index cc23be00a..000000000 Binary files a/public/res/logo-maskable/cinny-logo-maskable-57x57.png and /dev/null differ diff --git a/public/res/logo-maskable/cinny-logo-maskable-60x60.png b/public/res/logo-maskable/cinny-logo-maskable-60x60.png deleted file mode 100644 index 6a11f2073..000000000 Binary files a/public/res/logo-maskable/cinny-logo-maskable-60x60.png and /dev/null differ diff --git a/public/res/logo-maskable/cinny-logo-maskable-72x72.png b/public/res/logo-maskable/cinny-logo-maskable-72x72.png deleted file mode 100644 index 35e533ec3..000000000 Binary files a/public/res/logo-maskable/cinny-logo-maskable-72x72.png and /dev/null differ diff --git a/public/res/logo-maskable/cinny-logo-maskable-76x76.png b/public/res/logo-maskable/cinny-logo-maskable-76x76.png deleted file mode 100644 index 197658153..000000000 Binary files a/public/res/logo-maskable/cinny-logo-maskable-76x76.png and /dev/null differ diff --git a/public/res/logo-maskable/cinny-logo-maskable-96x96.png b/public/res/logo-maskable/cinny-logo-maskable-96x96.png deleted file mode 100644 index 0cd72dbf2..000000000 Binary files a/public/res/logo-maskable/cinny-logo-maskable-96x96.png and /dev/null differ diff --git a/public/res/logo-maskable/logo-maskable-114x114.png b/public/res/logo-maskable/logo-maskable-114x114.png new file mode 100644 index 000000000..def2336ae Binary files /dev/null and b/public/res/logo-maskable/logo-maskable-114x114.png differ diff --git a/public/res/logo-maskable/logo-maskable-120x120.png b/public/res/logo-maskable/logo-maskable-120x120.png new file mode 100644 index 000000000..78e01535f Binary files /dev/null and b/public/res/logo-maskable/logo-maskable-120x120.png differ diff --git a/public/res/logo-maskable/logo-maskable-144x144.png b/public/res/logo-maskable/logo-maskable-144x144.png new file mode 100644 index 000000000..d3cf3a09d Binary files /dev/null and b/public/res/logo-maskable/logo-maskable-144x144.png differ diff --git a/public/res/logo-maskable/logo-maskable-152x152.png b/public/res/logo-maskable/logo-maskable-152x152.png new file mode 100644 index 000000000..f3e493de2 Binary files /dev/null and b/public/res/logo-maskable/logo-maskable-152x152.png differ diff --git a/public/res/logo-maskable/logo-maskable-167x167.png b/public/res/logo-maskable/logo-maskable-167x167.png new file mode 100644 index 000000000..1bfa60cce Binary files /dev/null and b/public/res/logo-maskable/logo-maskable-167x167.png differ diff --git a/public/res/logo-maskable/logo-maskable-180x180.png b/public/res/logo-maskable/logo-maskable-180x180.png new file mode 100644 index 000000000..86c707283 Binary files /dev/null and b/public/res/logo-maskable/logo-maskable-180x180.png differ diff --git a/public/res/logo-maskable/logo-maskable-192x192.png b/public/res/logo-maskable/logo-maskable-192x192.png new file mode 100644 index 000000000..5c06f3a74 Binary files /dev/null and b/public/res/logo-maskable/logo-maskable-192x192.png differ diff --git a/public/res/logo-maskable/logo-maskable-256x256.png b/public/res/logo-maskable/logo-maskable-256x256.png new file mode 100644 index 000000000..4fd058b09 Binary files /dev/null and b/public/res/logo-maskable/logo-maskable-256x256.png differ diff --git a/public/res/logo-maskable/logo-maskable-36x36.png b/public/res/logo-maskable/logo-maskable-36x36.png new file mode 100644 index 000000000..88115eaef Binary files /dev/null and b/public/res/logo-maskable/logo-maskable-36x36.png differ diff --git a/public/res/logo-maskable/logo-maskable-384x384.png b/public/res/logo-maskable/logo-maskable-384x384.png new file mode 100644 index 000000000..73d09b922 Binary files /dev/null and b/public/res/logo-maskable/logo-maskable-384x384.png differ diff --git a/public/res/logo-maskable/logo-maskable-48x48.png b/public/res/logo-maskable/logo-maskable-48x48.png new file mode 100644 index 000000000..389d4d402 Binary files /dev/null and b/public/res/logo-maskable/logo-maskable-48x48.png differ diff --git a/public/res/logo-maskable/logo-maskable-512x512.png b/public/res/logo-maskable/logo-maskable-512x512.png new file mode 100644 index 000000000..30b58a211 Binary files /dev/null and b/public/res/logo-maskable/logo-maskable-512x512.png differ diff --git a/public/res/logo-maskable/logo-maskable-57x57.png b/public/res/logo-maskable/logo-maskable-57x57.png new file mode 100644 index 000000000..699ef9324 Binary files /dev/null and b/public/res/logo-maskable/logo-maskable-57x57.png differ diff --git a/public/res/logo-maskable/logo-maskable-60x60.png b/public/res/logo-maskable/logo-maskable-60x60.png new file mode 100644 index 000000000..92f2f74c3 Binary files /dev/null and b/public/res/logo-maskable/logo-maskable-60x60.png differ diff --git a/public/res/logo-maskable/logo-maskable-72x72.png b/public/res/logo-maskable/logo-maskable-72x72.png new file mode 100644 index 000000000..90806e9b0 Binary files /dev/null and b/public/res/logo-maskable/logo-maskable-72x72.png differ diff --git a/public/res/logo-maskable/logo-maskable-76x76.png b/public/res/logo-maskable/logo-maskable-76x76.png new file mode 100644 index 000000000..04645074e Binary files /dev/null and b/public/res/logo-maskable/logo-maskable-76x76.png differ diff --git a/public/res/logo-maskable/logo-maskable-96x96.png b/public/res/logo-maskable/logo-maskable-96x96.png new file mode 100644 index 000000000..b066c991d Binary files /dev/null and b/public/res/logo-maskable/logo-maskable-96x96.png differ diff --git a/public/res/logo/cinny-logo-144x144.png b/public/res/logo/cinny-logo-144x144.png deleted file mode 100644 index a2d3a55eb..000000000 Binary files a/public/res/logo/cinny-logo-144x144.png and /dev/null differ diff --git a/public/res/logo/cinny-logo-192x192.png b/public/res/logo/cinny-logo-192x192.png deleted file mode 100644 index 827a9d75b..000000000 Binary files a/public/res/logo/cinny-logo-192x192.png and /dev/null differ diff --git a/public/res/logo/cinny-logo-256x256.png b/public/res/logo/cinny-logo-256x256.png deleted file mode 100644 index 46e33befa..000000000 Binary files a/public/res/logo/cinny-logo-256x256.png and /dev/null differ diff --git a/public/res/logo/cinny-logo-36x36.png b/public/res/logo/cinny-logo-36x36.png deleted file mode 100644 index 5b769057a..000000000 Binary files a/public/res/logo/cinny-logo-36x36.png and /dev/null differ diff --git a/public/res/logo/cinny-logo-384x384.png b/public/res/logo/cinny-logo-384x384.png deleted file mode 100644 index ef2bfff13..000000000 Binary files a/public/res/logo/cinny-logo-384x384.png and /dev/null differ diff --git a/public/res/logo/cinny-logo-48x48.png b/public/res/logo/cinny-logo-48x48.png deleted file mode 100644 index 3ceaf5f8d..000000000 Binary files a/public/res/logo/cinny-logo-48x48.png and /dev/null differ diff --git a/public/res/logo/cinny-logo-512x512.png b/public/res/logo/cinny-logo-512x512.png deleted file mode 100644 index 6de474dc1..000000000 Binary files a/public/res/logo/cinny-logo-512x512.png and /dev/null differ diff --git a/public/res/logo/cinny-logo-72x72.png b/public/res/logo/cinny-logo-72x72.png deleted file mode 100644 index 5b12fd929..000000000 Binary files a/public/res/logo/cinny-logo-72x72.png and /dev/null differ diff --git a/public/res/logo/cinny-logo-96x96.png b/public/res/logo/cinny-logo-96x96.png deleted file mode 100644 index be29017f3..000000000 Binary files a/public/res/logo/cinny-logo-96x96.png and /dev/null differ diff --git a/public/res/logo/logo-144x144.png b/public/res/logo/logo-144x144.png new file mode 100644 index 000000000..85456a23d Binary files /dev/null and b/public/res/logo/logo-144x144.png differ diff --git a/public/res/logo/logo-192x192.png b/public/res/logo/logo-192x192.png new file mode 100644 index 000000000..40004e6e7 Binary files /dev/null and b/public/res/logo/logo-192x192.png differ diff --git a/public/res/logo/logo-256x256.png b/public/res/logo/logo-256x256.png new file mode 100644 index 000000000..f25497e84 Binary files /dev/null and b/public/res/logo/logo-256x256.png differ diff --git a/public/res/logo/logo-36x36.png b/public/res/logo/logo-36x36.png new file mode 100644 index 000000000..a861a4717 Binary files /dev/null and b/public/res/logo/logo-36x36.png differ diff --git a/public/res/logo/logo-384x384.png b/public/res/logo/logo-384x384.png new file mode 100644 index 000000000..f65fd79f7 Binary files /dev/null and b/public/res/logo/logo-384x384.png differ diff --git a/public/res/logo/logo-48x48.png b/public/res/logo/logo-48x48.png new file mode 100644 index 000000000..4a1309e7e Binary files /dev/null and b/public/res/logo/logo-48x48.png differ diff --git a/public/res/logo/logo-512x512.png b/public/res/logo/logo-512x512.png new file mode 100644 index 000000000..4638bcb33 Binary files /dev/null and b/public/res/logo/logo-512x512.png differ diff --git a/public/res/logo/logo-72x72.png b/public/res/logo/logo-72x72.png new file mode 100644 index 000000000..8dfdb80a2 Binary files /dev/null and b/public/res/logo/logo-72x72.png differ diff --git a/public/res/logo/logo-96x96.png b/public/res/logo/logo-96x96.png new file mode 100644 index 000000000..97a596404 Binary files /dev/null and b/public/res/logo/logo-96x96.png differ diff --git a/public/res/svg/cinny-highlight.svg b/public/res/svg/cinny-highlight.svg deleted file mode 100644 index f88f9d99d..000000000 --- a/public/res/svg/cinny-highlight.svg +++ /dev/null @@ -1,58 +0,0 @@ - - - - - - - - - diff --git a/public/res/svg/cinny-logo-maskable.svg b/public/res/svg/cinny-logo-maskable.svg deleted file mode 100644 index 1b3b15eb3..000000000 --- a/public/res/svg/cinny-logo-maskable.svg +++ /dev/null @@ -1,60 +0,0 @@ - - - - - - - - - diff --git a/public/res/svg/cinny-logo.svg b/public/res/svg/cinny-logo.svg deleted file mode 100644 index f84fba369..000000000 --- a/public/res/svg/cinny-logo.svg +++ /dev/null @@ -1,49 +0,0 @@ - - - - - - - - - - - diff --git a/public/res/svg/cinny-unread.svg b/public/res/svg/cinny-unread.svg deleted file mode 100644 index 384abdfbf..000000000 --- a/public/res/svg/cinny-unread.svg +++ /dev/null @@ -1,58 +0,0 @@ - - - - - - - - - diff --git a/public/res/svg/highlight.svg b/public/res/svg/highlight.svg new file mode 100644 index 000000000..1c2bfcf10 --- /dev/null +++ b/public/res/svg/highlight.svg @@ -0,0 +1,6 @@ + + + + + + diff --git a/public/res/svg/logo-maskable.svg b/public/res/svg/logo-maskable.svg new file mode 100644 index 000000000..16ad16365 --- /dev/null +++ b/public/res/svg/logo-maskable.svg @@ -0,0 +1,5 @@ + + + + + diff --git a/public/res/svg/logo.svg b/public/res/svg/logo.svg new file mode 100644 index 000000000..8de551f50 --- /dev/null +++ b/public/res/svg/logo.svg @@ -0,0 +1,5 @@ + + + + + diff --git a/public/res/svg/unread.svg b/public/res/svg/unread.svg new file mode 100644 index 000000000..b320ace7b --- /dev/null +++ b/public/res/svg/unread.svg @@ -0,0 +1,6 @@ + + + + + + diff --git a/scripts/replace-logo.sh b/scripts/replace-logo.sh new file mode 100755 index 000000000..5d9231851 --- /dev/null +++ b/scripts/replace-logo.sh @@ -0,0 +1,126 @@ +#!/usr/bin/env bash +set -euo pipefail + +readonly BASE_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")/.." && pwd)" + +usage(){ + cat <&2 + exit 2 + fi + if [[ "${f,,}" != *.svg ]]; then + echo "Input must be an SVG: $f" >&2 + exit 3 + fi +done + +ffmpeg_cmd(){ + local in="$1" out="$2" size="$3" + mkdir -p "$(dirname "$out")" + echo "Generating $out ($size x $size)" + ffmpeg -y -width "$size" -height "$size" -i "$in" "$out" 2>/dev/null +} + +# All inputs are required to be SVG. Use ffmpeg to render SVGs to PNG targets +# and copy SVGs directly to the svg assets directory. + +is_svg(){ + local f="$1" + [[ "${f,,}" == *.svg ]] +} + +echo "Replacing circular icons..." + +declare -a CIRCULAR_TARGETS=( + "512:$BASE_DIR/public/favicon.png" + "2560:$BASE_DIR/public/full_res_sable.png" + "144:$BASE_DIR/public/res/logo/logo-144x144.png" + "192:$BASE_DIR/public/res/logo/logo-192x192.png" + "256:$BASE_DIR/public/res/logo/logo-256x256.png" + "36:$BASE_DIR/public/res/logo/logo-36x36.png" + "384:$BASE_DIR/public/res/logo/logo-384x384.png" + "48:$BASE_DIR/public/res/logo/logo-48x48.png" + "512:$BASE_DIR/public/res/logo/logo-512x512.png" + "72:$BASE_DIR/public/res/logo/logo-72x72.png" + "96:$BASE_DIR/public/res/logo/logo-96x96.png" +) + +for entry in "${CIRCULAR_TARGETS[@]}"; do + size=${entry%%:*} + out=${entry#*:} + ffmpeg_cmd "$CIRCULAR" "$out" "$size" +done + +echo "Replacing maskable icons (using maskless input)..." + +declare -a MASKABLE_TARGETS=( + "114:$BASE_DIR/public/res/logo-maskable/logo-maskable-114x114.png" + "120:$BASE_DIR/public/res/logo-maskable/logo-maskable-120x120.png" + "144:$BASE_DIR/public/res/logo-maskable/logo-maskable-144x144.png" + "152:$BASE_DIR/public/res/logo-maskable/logo-maskable-152x152.png" + "167:$BASE_DIR/public/res/logo-maskable/logo-maskable-167x167.png" + "180:$BASE_DIR/public/res/logo-maskable/logo-maskable-180x180.png" + "192:$BASE_DIR/public/res/logo-maskable/logo-maskable-192x192.png" + "256:$BASE_DIR/public/res/logo-maskable/logo-maskable-256x256.png" + "36:$BASE_DIR/public/res/logo-maskable/logo-maskable-36x36.png" + "384:$BASE_DIR/public/res/logo-maskable/logo-maskable-384x384.png" + "48:$BASE_DIR/public/res/logo-maskable/logo-maskable-48x48.png" + "512:$BASE_DIR/public/res/logo-maskable/logo-maskable-512x512.png" + "57:$BASE_DIR/public/res/logo-maskable/logo-maskable-57x57.png" + "60:$BASE_DIR/public/res/logo-maskable/logo-maskable-60x60.png" + "72:$BASE_DIR/public/res/logo-maskable/logo-maskable-72x72.png" + "76:$BASE_DIR/public/res/logo-maskable/logo-maskable-76x76.png" + "96:$BASE_DIR/public/res/logo-maskable/logo-maskable-96x96.png" +) + +for entry in "${MASKABLE_TARGETS[@]}"; do + size=${entry%%:*} + out=${entry#*:} + ffmpeg_cmd "$MASKLESS" "$out" "$size" +done + +echo "Handling SVG assets in public/res/svg/..." + +SVG_DIR="$BASE_DIR/public/res/svg" +mkdir -p "$SVG_DIR" + +# logo.svg from circular input (inputs are SVG so copy directly) +echo "Copying circular SVG to $SVG_DIR/logo.svg" +cp "$CIRCULAR" "$SVG_DIR/logo.svg" + +# logo-maskable.svg from maskless input +echo "Copying maskable SVG to $SVG_DIR/logo-maskable.svg" +cp "$MASKLESS" "$SVG_DIR/logo-maskable.svg" + +# highlight.svg +cp "$HIGHLIGHT" "$SVG_DIR/highlight.svg" + +# unread.svg +cp "$UNREAD" "$SVG_DIR/unread.svg" + +echo "All done. Please review the generated files." diff --git a/src/app/components/RenderMessageContent.test.tsx b/src/app/components/RenderMessageContent.test.tsx index 191fa23b4..666beab50 100644 --- a/src/app/components/RenderMessageContent.test.tsx +++ b/src/app/components/RenderMessageContent.test.tsx @@ -49,24 +49,6 @@ describe('RenderMessageContent', () => { expect(screen.queryByTestId('client-preview')).not.toBeInTheDocument(); }); - it('still renders url previews for non-settings links', () => { - renderMessage('https://example.com'); - - expect(screen.getByTestId('url-preview-holder')).toBeInTheDocument(); - expect(screen.getByTestId('url-preview-card')).toHaveTextContent('https://example.com'); - }); - - it('still renders url previews for malformed settings-looking links', () => { - renderMessage( - 'https://app.example/settings/account?focus=status&moe.sable.client.action=settings">Settings' - ); - - expect(screen.getByTestId('url-preview-holder')).toBeInTheDocument(); - expect(screen.getByTestId('url-preview-card')).toHaveTextContent( - 'https://app.example/settings/account?focus=status&moe.sable.client.action=settings">Settings' - ); - }); - it('still renders url previews for settings links with unknown focus ids', () => { renderMessage('https://app.example/settings/account?focus=display-name2'); @@ -75,4 +57,39 @@ describe('RenderMessageContent', () => { 'https://app.example/settings/account?focus=display-name2' ); }); + + it('still renders url previews for non-settings links', () => { + renderMessage('https://example.com'); + + expect(screen.getByTestId('url-preview-holder')).toBeInTheDocument(); + expect(screen.getByTestId('url-preview-card')).toHaveTextContent('https://example.com'); + }); + + it('render url previews for text starting with paranthesis', () => { + renderMessage('foo (https://example.com bar'); + + expect(screen.getByTestId('url-preview-holder')).toBeInTheDocument(); + expect(screen.getByTestId('url-preview-card')).toHaveTextContent('https://example.com'); + }); + + it('include ending paranthesis into the url preview per url spec', () => { + renderMessage('foo https://example.com) bar'); + + expect(screen.getByTestId('url-preview-holder')).toBeInTheDocument(); + expect(screen.getByTestId('url-preview-card')).toHaveTextContent('https://example.com)'); + }); + + it('exclude closing paranthesis from the url preview when it marks a []() hyperlink', () => { + renderMessage('[foo](https://example.com) bar'); + + expect(screen.getByTestId('url-preview-holder')).toBeInTheDocument(); + expect(screen.getByTestId('url-preview-card')).toHaveTextContent('https://example.com'); + }); + + it('include inner closing paranthesis from the url preview even within []() hyperlink', () => { + renderMessage('[foo](https://example.com)) bar'); + + expect(screen.getByTestId('url-preview-holder')).toBeInTheDocument(); + expect(screen.getByTestId('url-preview-card')).toHaveTextContent('https://example.com)'); + }); }); diff --git a/src/app/components/RenderMessageContent.tsx b/src/app/components/RenderMessageContent.tsx index 9b51b7aef..9591b2565 100644 --- a/src/app/components/RenderMessageContent.tsx +++ b/src/app/components/RenderMessageContent.tsx @@ -30,7 +30,15 @@ import { UnsupportedContent, VideoContent, } from './message'; -import { UrlPreviewCard, UrlPreviewHolder, ClientPreview, youtubeUrl } from './url-preview'; +import { + UrlPreviewCard, + UrlPreviewHolder, + ClientPreview, + ThemePreviewUrlCard, + TweakPreviewUrlCard, + youtubeUrl, +} from './url-preview'; +import { isHttpsFullSableCssUrl } from '../theme/previewUrls'; import { Image, MediaControl, PersistedVolumeVideo } from './media'; import { ImageViewer } from './image-viewer'; import { PdfViewer } from './Pdf-viewer'; @@ -63,6 +71,10 @@ const getMediaType = (url: string) => { return null; }; +const isSableChatEmbedCandidate = (url: string): boolean => + /^https:\/\//i.test(url) && + (/\.preview\.sable\.css(\?|#|$)/i.test(url) || isHttpsFullSableCssUrl(url)); + const CAPTION_STYLE = { marginTop: config.space.S200 }; function RenderMessageContentInternal({ @@ -85,6 +97,7 @@ function RenderMessageContentInternal({ const [autoplayGifs] = useSetting(settingsAtom, 'autoplayGifs'); const [captionPosition] = useSetting(settingsAtom, 'captionPosition'); + const [themeChatSableWidgets] = useSetting(settingsAtom, 'themeChatSableWidgetsEnabled'); const [multiplePreviews] = useSetting(settingsAtom, 'multiplePreviews'); const settingsLinkBaseUrl = useSettingsLinkBaseUrl(); const captionPositionMap = { @@ -115,6 +128,17 @@ function RenderMessageContentInternal({ ); if (filteredUrls.length === 0) return undefined; + const themePreviewUrls = themeChatSableWidgets + ? filteredUrls.filter( + (u) => /^https:\/\//i.test(u) && /\.preview\.sable\.css(\?|#|$)/i.test(u) + ) + : []; + const themeToRender = themePreviewUrls.filter((u) => /^https:\/\//i.test(u)); + + const tweakCandidateUrls = themeChatSableWidgets + ? filteredUrls.filter((u) => isHttpsFullSableCssUrl(u)) + : []; + const analyzed = filteredUrls.map((url) => ({ url, type: getMediaType(url), @@ -124,11 +148,20 @@ function RenderMessageContentInternal({ const toRender = multiplePreviews ? previewCandidates : [previewCandidates[0]!]; return ( + {themeToRender.map((url) => ( + + ))} + {tweakCandidateUrls.map((url) => ( + + ))} {toRender.map((item) => { const { url, type } = item; + if (themeToRender.includes(url)) return null; + if (tweakCandidateUrls.includes(url)) return null; if (type) { return ; } + if (!themeChatSableWidgets && isSableChatEmbedCandidate(url)) return null; if (clientUrlPreview && youtubeUrl(url)) { return ; } @@ -140,7 +173,7 @@ function RenderMessageContentInternal({ ); }, - [multiplePreviews, settingsLinkBaseUrl, clientUrlPreview, urlPreview, ts] + [multiplePreviews, themeChatSableWidgets, settingsLinkBaseUrl, clientUrlPreview, urlPreview, ts] ); const renderBundledPreviews = useCallback( (bundles: IPreviewUrlResponse[]) => ( @@ -157,7 +190,7 @@ function RenderMessageContentInternal({ ), [urlPreview] ); - const messageUrlsPreview = urlPreview ? renderUrlsPreview : undefined; + const messageUrlsPreview = urlPreview || themeChatSableWidgets ? renderUrlsPreview : undefined; const messageBundlePreview = bundledPreview ? renderBundledPreviews : undefined; const renderCaption = () => { @@ -304,11 +337,15 @@ function RenderMessageContentInternal({ const info = (content as { info?: { mimetype?: string } }).info; const isGif = info?.mimetype === 'image/gif' || + info?.mimetype === 'image/apng' || info?.mimetype === 'image/webp' || (content.body as string)?.toLowerCase().endsWith('.gif') || + (content.body as string)?.toLowerCase().endsWith('.apng') || (content.body as string)?.toLowerCase().endsWith('.webp') || (typeof (content as { url?: string }).url === 'string' && - (content as { url?: string }).url?.toLowerCase().includes('gif')); + ((content as { url?: string }).url?.toLowerCase().endsWith('.gif') || + (content as { url?: string }).url?.toLowerCase().endsWith('.apng') || + (content as { url?: string }).url?.toLowerCase().endsWith('.webp'))); return renderCaptionedAttachment( ({ }); export const createRoomCallState = () => ({ - type: 'org.matrix.msc3401.call', + type: prefix.MATRIX_UNSTABLE_ROOM_TYPE_CALL_PROPERTY_NAME, state_key: '', content: {}, }); diff --git a/src/app/components/editor/Elements.tsx b/src/app/components/editor/Elements.tsx index 22487c03e..410d9aa98 100644 --- a/src/app/components/editor/Elements.tsx +++ b/src/app/components/editor/Elements.tsx @@ -1,4 +1,4 @@ -import { Scroll, Text } from 'folds'; +import { Text } from 'folds'; import type { RenderElementProps, RenderLeafProps } from 'slate-react'; import { useFocused, useSelected, useSlate } from 'slate-react'; import { useAtomValue } from 'jotai'; @@ -130,72 +130,6 @@ export function RenderElement({ attributes, element, children }: RenderElementPr {children} ); - case BlockType.Heading: - if (element.level === 1) - return ( - - {children} - - ); - if (element.level === 2) - return ( - - {children} - - ); - if (element.level === 3) - return ( - - {children} - - ); - return ( - - {children} - - ); - case BlockType.CodeLine: - return
{children}
; - case BlockType.CodeBlock: - return ( - - -
{children}
-
-
- ); - case BlockType.QuoteLine: - return
{children}
; - case BlockType.BlockQuote: - return ( - - {children} - - ); - case BlockType.ListItem: - return ( - - {children} - - ); - case BlockType.OrderedList: - return ( -
    - {children} -
- ); - case BlockType.UnorderedList: - return ( -
    - {children} -
- ); case BlockType.Mention: return ( @@ -220,19 +154,6 @@ export function RenderElement({ attributes, element, children }: RenderElementPr {children} ); - case BlockType.Small: - return ( - - {children} - - ); - case BlockType.HorizontalRule: - return ( -
-
- {children} -
- ); default: return ( - - {child} - - ); - if (leaf.italic) - child = ( - - - {child} - - ); - if (leaf.underline) - child = ( - - - {child} - - ); - if (leaf.strikeThrough) - child = ( - - - {child} - - ); - if (leaf.code) - child = ( - - - {child} - - ); - if (leaf.spoiler) - child = ( - - - {child} - - ); - - if (child !== children) return child; - - return {child}; +export function RenderLeaf({ attributes, children }: RenderLeafProps) { + return {children}; } diff --git a/src/app/components/editor/Toolbar.tsx b/src/app/components/editor/MarkdownToolbar.tsx similarity index 50% rename from src/app/components/editor/Toolbar.tsx rename to src/app/components/editor/MarkdownToolbar.tsx index 4028b13c5..64ebd6e60 100644 --- a/src/app/components/editor/Toolbar.tsx +++ b/src/app/components/editor/MarkdownToolbar.tsx @@ -17,26 +17,21 @@ import { toRem, } from 'folds'; import type { MouseEventHandler, ReactNode } from 'react'; -import { useState } from 'react'; +import { useEffect, useState } from 'react'; +import { useSetting } from '$state/hooks/settings'; +import { settingsAtom } from '$state/settings'; import { ReactEditor, useSlate } from 'slate-react'; import { isMacOS } from '$utils/user-agent'; import { KeySymbol } from '$utils/key-symbol'; -import { useSetting } from '$state/hooks/settings'; -import { settingsAtom } from '$state/settings'; import { stopPropagation } from '$utils/keyboard'; import { floatingToolbar } from '$styles/overrides/Composer.css'; -import type { HeadingLevel } from './slate'; -import { BlockType, MarkType } from './types'; -import * as css from './Editor.css'; import { - headingLevel, - isAnyMarkActive, - isBlockActive, - isMarkActive, - removeAllMark, - toggleBlock, - toggleMark, -} from './utils'; + applyMarkdownBlockPrefix, + applyMarkdownInline, + BLOCK_HOTKEYS, + INLINE_HOTKEYS, +} from './keyboard'; +import * as css from './Editor.css'; function BtnTooltip({ text, shortCode }: { text: string; shortCode?: string }) { return ( @@ -55,49 +50,17 @@ function BtnTooltip({ text, shortCode }: { text: string; shortCode?: string }) { ); } -type MarkButtonProps = { format: MarkType; icon: IconSrc; tooltip: ReactNode }; -export function MarkButton({ format, icon, tooltip }: MarkButtonProps) { - const editor = useSlate(); - const disableInline = isBlockActive(editor, BlockType.CodeBlock); - - if (disableInline) { - removeAllMark(editor); - } - - const handleClick = () => { - toggleMark(editor, format); - ReactEditor.focus(editor); - }; - - return ( - - {(triggerRef) => ( - - - - )} - - ); -} - -type BlockButtonProps = { - format: BlockType; +type MarkdownInlineButtonProps = { + marker: string; icon: IconSrc; tooltip: ReactNode; }; -export function BlockButton({ format, icon, tooltip }: BlockButtonProps) { + +function MarkdownInlineButton({ marker, icon, tooltip }: MarkdownInlineButtonProps) { const editor = useSlate(); const handleClick = () => { - toggleBlock(editor, format, { level: 1 }); + applyMarkdownInline(editor, marker); ReactEditor.focus(editor); }; @@ -108,7 +71,6 @@ export function BlockButton({ format, icon, tooltip }: BlockButtonProps) { ref={triggerRef} variant="SurfaceVariant" onClick={handleClick} - aria-pressed={isBlockActive(editor, format)} size="400" radii="300" > @@ -119,26 +81,52 @@ export function BlockButton({ format, icon, tooltip }: BlockButtonProps) { ); } -export function HeadingBlockButton() { +type MarkdownBlockButtonProps = { + prefix: string; + icon: IconSrc; + tooltip: ReactNode; +}; + +function MarkdownBlockButton({ prefix, icon, tooltip }: MarkdownBlockButtonProps) { + const editor = useSlate(); + + const handleClick = () => { + applyMarkdownBlockPrefix(editor, prefix); + ReactEditor.focus(editor); + }; + + return ( + + {(triggerRef) => ( + + + + )} + + ); +} + +function MarkdownHeadingButton() { const editor = useSlate(); - const level = headingLevel(editor); const [anchor, setAnchor] = useState(); - const isActive = isBlockActive(editor, BlockType.Heading); const modKey = isMacOS() ? KeySymbol.Command : 'Ctrl'; - const handleMenuSelect = (selectedLevel: HeadingLevel) => { + const handleMenuSelect = (prefix: string) => { setAnchor(undefined); - toggleBlock(editor, BlockType.Heading, { level: selectedLevel }); + applyMarkdownBlockPrefix(editor, prefix); ReactEditor.focus(editor); }; const handleMenuOpen: MouseEventHandler = (evt) => { - if (isActive) { - toggleBlock(editor, BlockType.Heading); - return; - } setAnchor(evt.currentTarget.getBoundingClientRect()); }; + return ( ( handleMenuSelect(1)} + onClick={() => handleMenuSelect('# ')} size="400" radii="300" > @@ -180,7 +168,7 @@ export function HeadingBlockButton() { {(triggerRef) => ( handleMenuSelect(2)} + onClick={() => handleMenuSelect('## ')} size="400" radii="300" > @@ -195,7 +183,7 @@ export function HeadingBlockButton() { {(triggerRef) => ( handleMenuSelect(3)} + onClick={() => handleMenuSelect('### ')} size="400" radii="300" > @@ -212,155 +200,131 @@ export function HeadingBlockButton() { style={{ width: 'unset' }} variant="SurfaceVariant" onClick={handleMenuOpen} - aria-pressed={isActive} size="400" radii="300" + aria-haspopup="menu" + aria-expanded={!!anchor} > - - + + ); } -type ExitFormattingProps = { tooltip: ReactNode }; -export function ExitFormatting({ tooltip }: ExitFormattingProps) { - const editor = useSlate(); - - const handleClick = () => { - if (isAnyMarkActive(editor)) { - removeAllMark(editor); - } else if (!isBlockActive(editor, BlockType.Paragraph)) { - toggleBlock(editor, BlockType.Paragraph); - } - ReactEditor.focus(editor); - }; - - return ( - - {(triggerRef) => ( - - {`Exit ${KeySymbol.Hyper}`} - - )} - - ); -} - -export function Toolbar() { - const editor = useSlate(); +export function MarkdownToolbar() { const modKey = isMacOS() ? KeySymbol.Command : 'Ctrl'; - const disableInline = isBlockActive(editor, BlockType.CodeBlock); - - const canEscape = isBlockActive(editor, BlockType.Paragraph) - ? isAnyMarkActive(editor) - : ReactEditor.isFocused(editor); - const [isMarkdown, setIsMarkdown] = useSetting(settingsAtom, 'isMarkdown'); return ( - <> - - } - /> - } - /> - } - /> - } - /> - } - /> - } - /> - - - - } + /> + } + /> + } + /> + } + /> + } + /> + } + /> + + + + } /> - } /> - } /> - } /> - - - {canEscape && ( - <> - - - - } - /> - - - )} - - } - delay={500} - > - {(triggerRef) => ( - setIsMarkdown(!isMarkdown)} - aria-pressed={isMarkdown} - size="300" - radii="300" - disabled={disableInline || !!isAnyMarkActive(editor)} - > - - - )} - - + ); } + +export type MarkdownFormattingToolbarToggleVariant = 'SurfaceVariant' | 'Background'; + +export function MarkdownFormattingToolbarToggle({ + variant, +}: { + variant: MarkdownFormattingToolbarToggleVariant; +}) { + const [editorToolbar] = useSetting(settingsAtom, 'editorToolbar'); + const [composerToolbarOpen, setComposerToolbarOpen] = useSetting( + settingsAtom, + 'composerToolbarOpen' + ); + + useEffect(() => { + if (!editorToolbar) setComposerToolbarOpen(false); + }, [editorToolbar, setComposerToolbarOpen]); + + if (!editorToolbar) return null; + + return ( + setComposerToolbarOpen(!composerToolbarOpen)} + > + + + ); +} + +export function MarkdownFormattingToolbarBottom() { + const [editorToolbar] = useSetting(settingsAtom, 'editorToolbar'); + const [composerToolbarOpen] = useSetting(settingsAtom, 'composerToolbarOpen'); + + if (!editorToolbar || !composerToolbarOpen) return null; + + return ( +
+ + +
+ ); +} diff --git a/src/app/components/editor/autocomplete/RoomMentionAutocomplete.tsx b/src/app/components/editor/autocomplete/RoomMentionAutocomplete.tsx index 90789525c..b7b935f6f 100644 --- a/src/app/components/editor/autocomplete/RoomMentionAutocomplete.tsx +++ b/src/app/components/editor/autocomplete/RoomMentionAutocomplete.tsx @@ -1,5 +1,5 @@ import type { KeyboardEvent as ReactKeyboardEvent } from 'react'; -import { useCallback, useEffect } from 'react'; +import { useCallback, useEffect, useMemo } from 'react'; import type { Editor } from 'slate'; import { ReactEditor } from 'slate-react'; import { Avatar, Icon, Icons, MenuItem, Text } from 'folds'; @@ -9,9 +9,9 @@ import { useAtomValue } from 'jotai'; import { getDirectRoomAvatarUrl } from '$utils/room'; import { useMatrixClient } from '$hooks/useMatrixClient'; -import { getMxIdServer, isRoomAlias } from '$utils/matrix'; -import type { UseAsyncSearchOptions } from '$hooks/useAsyncSearch'; +import { isRoomAlias } from '$utils/matrix'; import { useAsyncSearch } from '$hooks/useAsyncSearch'; +import type { UseAsyncSearchOptions } from '$hooks/useAsyncSearch'; import { onTabPress } from '$utils/keyboard'; import { useKeyDown } from '$hooks/useKeyDown'; import { mDirectAtom } from '$state/mDirectList'; @@ -20,6 +20,7 @@ import { factoryRoomIdByActivity } from '$utils/sort'; import { RoomAvatar, RoomIcon } from '$components/room-avatar'; import { getViaServers } from '$plugins/via-servers'; import { createMentionElement, moveCursor, replaceWithElement } from '$components/editor/utils'; +import { getMxIdServer } from '$utils/mxIdHelper'; import { AutocompleteMenu } from './AutocompleteMenu'; import type { AutocompleteQuery } from './autocompleteQuery'; @@ -83,7 +84,11 @@ export function RoomMentionAutocomplete({ const mx = useMatrixClient(); const mDirects = useAtomValue(mDirectAtom); - const allRooms = useAtomValue(allRoomsAtom).toSorted(factoryRoomIdByActivity(mx)); + const allRoomsFromAtom = useAtomValue(allRoomsAtom); + const allRooms = useMemo( + () => allRoomsFromAtom.toSorted(factoryRoomIdByActivity(mx)), + [allRoomsFromAtom, mx] + ); const [result, search, resetSearch] = useAsyncSearch( allRooms, diff --git a/src/app/components/editor/autocomplete/UserMentionAutocomplete.tsx b/src/app/components/editor/autocomplete/UserMentionAutocomplete.tsx index f8aed1284..1806fb2d7 100644 --- a/src/app/components/editor/autocomplete/UserMentionAutocomplete.tsx +++ b/src/app/components/editor/autocomplete/UserMentionAutocomplete.tsx @@ -11,7 +11,7 @@ import type { SearchItemStrGetter, UseAsyncSearchOptions } from '$hooks/useAsync import { useAsyncSearch } from '$hooks/useAsyncSearch'; import { onTabPress } from '$utils/keyboard'; import { useKeyDown } from '$hooks/useKeyDown'; -import { getMxIdLocalPart, getMxIdServer, isUserId } from '$utils/matrix'; +import { getMxIdLocalPart, isUserId } from '$utils/matrix'; import { getMemberDisplayName, getMemberSearchStr } from '$utils/room'; import { UserAvatar } from '$components/user-avatar'; import { useMediaAuthentication } from '$hooks/useMediaAuthentication'; @@ -19,6 +19,7 @@ import { useMediaAuthentication } from '$hooks/useMediaAuthentication'; import { useAtomValue } from 'jotai'; import { nicknamesAtom } from '$state/nicknames'; import { createMentionElement, moveCursor, replaceWithElement } from '$components/editor/utils'; +import { getMxIdServer } from '$utils/mxIdHelper'; import { AutocompleteMenu } from './AutocompleteMenu'; import type { AutocompleteQuery } from './autocompleteQuery'; import { KnownMembership } from '$types/matrix-sdk'; diff --git a/src/app/components/editor/getLinks.test.ts b/src/app/components/editor/getLinks.test.ts new file mode 100644 index 000000000..7f830a557 --- /dev/null +++ b/src/app/components/editor/getLinks.test.ts @@ -0,0 +1,89 @@ +import { describe, expect, it } from 'vitest'; +import type { Descendant } from 'slate'; +import { getLinks, toPlainText } from './output'; +import type { ParagraphElement } from './slate'; +import { BlockType } from './types'; + +describe('getLinks', () => { + it('extracts URLs from text', () => { + const node: ParagraphElement = { + type: BlockType.Paragraph, + children: [{ text: 'Check out https://example.com for more info' }], + }; + const links = getLinks([node]); + expect(links).toContain('https://example.com'); + }); + + it('excludes URLs in angle brackets (Matrix HTML spoiler)', () => { + const node: ParagraphElement = { + type: BlockType.Paragraph, + children: [{ text: 'Check out for more info' }], + }; + const links = getLinks([node]); + expect(links).toEqual([]); + }); + + it('extracts markdown link URLs', () => { + const node: ParagraphElement = { + type: BlockType.Paragraph, + children: [{ text: 'Check [my link](https://example.com) for more info' }], + }; + const links = getLinks([node]); + expect(links).toContain('https://example.com'); + }); + + it('excludes URLs inside markdown inline code spans', () => { + const node: ParagraphElement = { + type: BlockType.Paragraph, + children: [{ text: 'Do not visit `https://example.com` please' }], + }; + const links = getLinks([node]); + expect(links).toEqual([]); + }); + + it('excludes URLs inside markdown code blocks spanning multiple paragraphs', () => { + const nodes: Descendant[] = [ + { type: BlockType.Paragraph, children: [{ text: '```' }] }, + { type: BlockType.Paragraph, children: [{ text: 'https://example.com' }] }, + { type: BlockType.Paragraph, children: [{ text: '```' }] }, + ]; + const links = getLinks(nodes); + expect(links).toEqual([]); + }); +}); + +describe('toPlainText spoiler handling', () => { + it('replaces ||spoilered text|| with [Spoiler]', () => { + const node: ParagraphElement = { + type: BlockType.Paragraph, + children: [{ text: 'Hello ||spoilered|| world' }], + }; + const plain = toPlainText(node); + expect(plain).toContain('[Spoiler]'); + expect(plain).not.toContain('||spoilered||'); + }); + + it('replaces ||spoilered links|| with [Spoiler]', () => { + const node: ParagraphElement = { + type: BlockType.Paragraph, + children: [{ text: 'Hello ||https://example.com|| world' }], + }; + const plain = toPlainText(node); + expect(plain).toContain('[Spoiler]'); + expect(plain).not.toContain('||https://example.com||'); + }); + + it('extracts non-spoilered markdown link URLs alongside spoilered ones', () => { + const node: ParagraphElement = { + type: BlockType.Paragraph, + children: [ + { + text: 'Check [visible](https://visible.com) and ||https://hidden.com||', + }, + ], + }; + const links = getLinks([node]); + expect(links).toContain('https://visible.com'); + expect(links).not.toContain('https://hidden.com'); + }); +}); diff --git a/src/app/components/editor/index.ts b/src/app/components/editor/index.ts index aae0137d1..46ca31a11 100644 --- a/src/app/components/editor/index.ts +++ b/src/app/components/editor/index.ts @@ -4,6 +4,7 @@ export * from './Editor'; export * from './Elements'; export * from './keyboard'; export * from './output'; -export * from './Toolbar'; + export * from './input'; +export * from './MarkdownToolbar'; export * from './types'; diff --git a/src/app/components/editor/input.ts b/src/app/components/editor/input.ts index b2476e437..471a0e5f5 100644 --- a/src/app/components/editor/input.ts +++ b/src/app/components/editor/input.ts @@ -1,505 +1,67 @@ import type { Descendant } from 'slate'; -import { Text } from 'slate'; -import parse from 'html-dom-parser'; -import type { ChildNode, Element } from 'domhandler'; -import { isText, isTag } from 'domhandler'; -import { sanitizeCustomHtml } from '$utils/sanitize'; import { - parseMatrixToRoom, - parseMatrixToRoomEvent, - parseMatrixToUser, - testMatrixTo, -} from '$plugins/matrix-to'; -import { escapeMarkdownInlineSequences, escapeMarkdownBlockSequences } from '$plugins/markdown'; -import { BlockType, MarkType } from './types'; -import type { - BlockQuoteElement, - CodeBlockElement, - CodeLineElement, - EmoticonElement, - HeadingElement, - HeadingLevel, - HorizontalRuleElement, - InlineElement, - MentionElement, - OrderedListElement, - ParagraphElement, - SmallElement, - UnorderedListElement, -} from './slate'; -import { createEmoticonElement, createMentionElement } from './utils'; + MX_EMOTICON_MD_END, + MX_EMOTICON_MD_SEP, + MX_EMOTICON_MD_START, + validateMxcUrl, +} from '$plugins/markdown/extensions/matrix-emoticon'; +import { BlockType } from './types'; +import type { ParagraphElement } from './slate'; +import { createEmoticonElement } from './utils'; -type ProcessTextCallback = (text: string) => string; +/** Matches placeholders emitted by htmlToMarkdown for <img data-mx-emoticon>. */ +const MX_EMOTICON_MD_TOKEN = new RegExp( + `${MX_EMOTICON_MD_START}([^${MX_EMOTICON_MD_SEP}]+)${MX_EMOTICON_MD_SEP}([^${MX_EMOTICON_MD_END}]+)${MX_EMOTICON_MD_END}`, + 'g' +); -const getText = (node: ChildNode): string => { - if (isText(node)) { - return node.data; - } - if (isTag(node)) { - return node.children.map((child) => getText(child)).join(''); - } - return ''; -}; - -const getInlineNodeMarkType = (node: Element): MarkType | undefined => { - if (node.name === 'b' || node.name === 'strong') { - return MarkType.Bold; - } - - if (node.name === 'i' || node.name === 'em') { - return MarkType.Italic; - } - - if (node.name === 'u') { - return MarkType.Underline; - } - - if (node.name === 's' || node.name === 'del') { - return MarkType.StrikeThrough; - } - - if (node.name === 'code') { - if (node.parent && 'name' in node.parent && node.parent.name === 'pre') { - return undefined; // Don't apply `Code` mark inside a
 tag
+function mergeAdjacentTextNodes(
+  children: ParagraphElement['children']
+): ParagraphElement['children'] {
+  const out: ParagraphElement['children'] = [];
+  for (const c of children) {
+    if ('type' in c) {
+      out.push(c);
+      continue;
     }
-    return MarkType.Code;
-  }
-
-  if (node.name === 'span' && node.attribs['data-mx-spoiler'] !== undefined) {
-    return MarkType.Spoiler;
-  }
-
-  return undefined;
-};
-
-const getInlineMarkElement = (
-  markType: MarkType,
-  node: Element,
-  getChild: (child: ChildNode) => InlineElement[]
-): InlineElement[] => {
-  const children = node.children.flatMap(getChild);
-  const mdSequence = node.attribs['data-md'];
-  if (mdSequence !== undefined) {
-    children.unshift({ text: mdSequence });
-    children.push({ text: mdSequence });
-    return children;
-  }
-  return children.map((child) => {
-    if (Text.isText(child)) {
-      return { ...child, [markType]: true };
-    }
-    return child;
-  });
-};
-
-const getInlineNonMarkElement = (node: Element): MentionElement | EmoticonElement | undefined => {
-  if (node.name === 'img' && node.attribs['data-mx-emoticon'] !== undefined) {
-    const { src, alt } = node.attribs;
-    if (!src) return undefined;
-    return createEmoticonElement(src, alt || 'Unknown Emoji');
-  }
-  if (node.name === 'a') {
-    const encodedHref = node.attribs.href;
-    const href = encodedHref && decodeURIComponent(encodedHref);
-    if (!href) return undefined;
-    if (testMatrixTo(href)) {
-      const userMention = parseMatrixToUser(href);
-      if (userMention) {
-        return createMentionElement(userMention, getText(node) || userMention, false);
-      }
-      const roomMention = parseMatrixToRoom(href);
-      if (roomMention) {
-        return createMentionElement(
-          roomMention.roomIdOrAlias,
-          getText(node) || roomMention.roomIdOrAlias,
-          false,
-          undefined,
-          roomMention.viaServers
-        );
-      }
-      const eventMention = parseMatrixToRoomEvent(href);
-      if (eventMention) {
-        return createMentionElement(
-          eventMention.roomIdOrAlias,
-          getText(node) || eventMention.roomIdOrAlias,
-          false,
-          eventMention.eventId,
-          eventMention.viaServers
-        );
-      }
+    const prev = out[out.length - 1];
+    if (prev && !('type' in prev)) {
+      prev.text += c.text;
+    } else {
+      out.push({ ...c });
     }
   }
-  return undefined;
-};
+  return out.length > 0 ? out : [{ text: '' }];
+}
 
-const getInlineElement = (node: ChildNode, processText: ProcessTextCallback): InlineElement[] => {
-  if (isText(node)) {
-    return [{ text: processText(node.data) }];
-  }
-
-  if (isTag(node)) {
-    const markType = getInlineNodeMarkType(node);
-    if (markType) {
-      return getInlineMarkElement(markType, node, (child) => {
-        if (markType === MarkType.Code) return [{ text: getText(child) }];
-        return getInlineElement(child, processText);
-      });
+function lineToParagraphChildren(line: string): ParagraphElement['children'] {
+  MX_EMOTICON_MD_TOKEN.lastIndex = 0;
+  const parts: ParagraphElement['children'] = [];
+  let last = 0;
+  let match: RegExpExecArray | null;
+  while ((match = MX_EMOTICON_MD_TOKEN.exec(line)) !== null) {
+    if (match.index > last) {
+      parts.push({ text: line.slice(last, match.index) });
     }
-
-    const inlineNode = getInlineNonMarkElement(node);
-    if (inlineNode) return [inlineNode];
-
-    if (node.name === 'a') {
-      const children = node.childNodes.flatMap((child) => getInlineElement(child, processText));
-      children.unshift({ text: '[' });
-      children.push({ text: `](${node.attribs.href})` });
-      return children;
+    const [, src, shortcode] = match;
+    if (src && shortcode && validateMxcUrl(src)) {
+      parts.push(createEmoticonElement(src, shortcode));
+    } else if (shortcode) {
+      parts.push({ text: `:${shortcode.replace(/^:|:$/g, '')}:` });
     }
-
-    return node.childNodes.flatMap((child) => getInlineElement(child, processText));
+    last = MX_EMOTICON_MD_TOKEN.lastIndex;
   }
-
-  return [];
-};
-
-const parseBlockquoteNode = (
-  node: Element,
-  processText: ProcessTextCallback
-): BlockQuoteElement[] | ParagraphElement[] => {
-  const quoteLines: Array = [];
-  let lineHolder: InlineElement[] = [];
-
-  const appendLine = () => {
-    if (lineHolder.length === 0) return;
-
-    quoteLines.push(lineHolder);
-    lineHolder = [];
-  };
-
-  node.children.forEach((child) => {
-    if (isText(child)) {
-      lineHolder.push({ text: processText(child.data) });
-      return;
-    }
-    if (isTag(child)) {
-      if (child.name === 'br') {
-        lineHolder.push({ text: '' });
-        appendLine();
-        return;
-      }
-
-      if (child.name === 'p') {
-        appendLine();
-        quoteLines.push(child.children.flatMap((c) => getInlineElement(c, processText)));
-        return;
-      }
-
-      lineHolder.push(...getInlineElement(child, processText));
-    }
-  });
-  appendLine();
-
-  const mdSequence = node.attribs['data-md'];
-  if (mdSequence !== undefined) {
-    return quoteLines.map((lineChildren) => ({
-      type: BlockType.Paragraph,
-      children: [{ text: `${mdSequence} ` }, ...lineChildren],
-    }));
+  if (last < line.length) {
+    parts.push({ text: line.slice(last) });
   }
+  return mergeAdjacentTextNodes(parts);
+}
 
-  return [
-    {
-      type: BlockType.BlockQuote,
-      children: quoteLines.map((lineChildren) => ({
-        type: BlockType.QuoteLine,
-        children: lineChildren,
-      })),
-    },
-  ];
-};
-const parseCodeBlockNode = (node: Element): CodeBlockElement[] | ParagraphElement[] => {
-  const codeLines = getText(node).trim().split('\n');
-
-  const mdSequence = node.attribs['data-md'];
-  if (mdSequence !== undefined) {
-    const pLines = codeLines.map((text) => ({
-      type: BlockType.Paragraph,
-      children: [{ text }],
-    }));
-    const childCode = node.children[0]!;
-    const className =
-      isTag(childCode) && childCode.tagName === 'code' ? (childCode.attribs.class ?? '') : '';
-    const prefix = { text: `${mdSequence}${className.replace('language-', '')}` };
-    const suffix = { text: mdSequence };
-    return [
-      { type: BlockType.Paragraph, children: [prefix] },
-      ...pLines,
-      { type: BlockType.Paragraph, children: [suffix] },
-    ];
-  }
-
-  return [
-    {
-      type: BlockType.CodeBlock,
-      children: codeLines.map((text) => ({
-        type: BlockType.CodeLine,
-        children: [{ text }],
-      })),
-    },
-  ];
-};
-const parseListNode = (
-  node: Element,
-  processText: ProcessTextCallback
-): OrderedListElement[] | UnorderedListElement[] | ParagraphElement[] => {
-  const listLines: Array = [];
-  let lineHolder: InlineElement[] = [];
-
-  const appendLine = () => {
-    if (lineHolder.length === 0) return;
-
-    listLines.push(lineHolder);
-    lineHolder = [];
-  };
-
-  node.children.forEach((child) => {
-    if (isText(child)) {
-      lineHolder.push({ text: processText(child.data) });
-      return;
-    }
-    if (isTag(child)) {
-      if (child.name === 'br') {
-        lineHolder.push({ text: '' });
-        appendLine();
-        return;
-      }
-
-      if (child.name === 'li') {
-        appendLine();
-        listLines.push(child.children.flatMap((c) => getInlineElement(c, processText)));
-        return;
-      }
-
-      lineHolder.push(...getInlineElement(child, processText));
-    }
-  });
-  appendLine();
-
-  const mdSequence = node.attribs['data-md'];
-  if (mdSequence !== undefined) {
-    const prefix = mdSequence || '-';
-    const [starOrHyphen] = prefix.match(/^\*|-$/) ?? [];
-    return listLines.map((lineChildren) => ({
-      type: BlockType.Paragraph,
-      children: [
-        { text: `${starOrHyphen ? `${starOrHyphen} ` : `${prefix}. `} ` },
-        ...lineChildren,
-      ],
-    }));
-  }
-
-  if (node.name === 'ol') {
-    return [
-      {
-        type: BlockType.OrderedList,
-        children: listLines.map((lineChildren) => ({
-          type: BlockType.ListItem,
-          children: lineChildren,
-        })),
-      },
-    ];
-  }
-
-  return [
-    {
-      type: BlockType.UnorderedList,
-      children: listLines.map((lineChildren) => ({
-        type: BlockType.ListItem,
-        children: lineChildren,
-      })),
-    },
-  ];
-};
-const parseHeadingNode = (
-  node: Element,
-  processText: ProcessTextCallback
-): HeadingElement | ParagraphElement => {
-  const children = node.children.flatMap((child) => getInlineElement(child, processText));
-
-  const headingMatch = node.name.match(/^h([123456])$/);
-  const [, g1AsLevel] = headingMatch ?? ['h3', '3'];
-  const level = Number.parseInt(g1AsLevel!, 10);
-
-  const mdSequence = node.attribs['data-md'];
-  if (mdSequence !== undefined) {
-    return {
-      type: BlockType.Paragraph,
-      children: [{ text: `${mdSequence} ` }, ...children],
-    };
-  }
-
-  return {
-    type: BlockType.Heading,
-    level: Math.min(level, 3) as HeadingLevel,
-    children,
-  };
-};
-
-const parseSmallNode = (
-  node: Element,
-  processText: ProcessTextCallback
-): SmallElement | ParagraphElement => {
-  const children = node.children.flatMap((child) => getInlineElement(child, processText));
-  const mdSequence = node.attribs['data-md'];
-
-  if (mdSequence !== undefined) {
-    return {
-      type: BlockType.Paragraph,
-      children: [{ text: `${mdSequence} ` }, ...children],
-    };
-  }
-
-  return {
-    type: BlockType.Small,
-    children,
-  };
-};
-
-const parseHorizontalRuleNode = (node: Element): HorizontalRuleElement | ParagraphElement => {
-  const mdSequence = node.attribs['data-md'];
-
-  if (mdSequence !== undefined) {
-    return {
-      type: BlockType.Paragraph,
-      children: [{ text: mdSequence }],
-    };
-  }
-
-  return {
-    type: BlockType.HorizontalRule,
-    children: [{ text: '' }],
-  };
-};
-
-export const domToEditorInput = (
-  domNodes: ChildNode[],
-  processText: ProcessTextCallback,
-  processLineStartText: ProcessTextCallback
-): Descendant[] => {
-  const children: Descendant[] = [];
-
-  let lineHolder: InlineElement[] = [];
-
-  const appendLine = () => {
-    if (lineHolder.length === 0) return;
-
-    children.push({
-      type: BlockType.Paragraph,
-      children: lineHolder,
-    });
-    lineHolder = [];
-  };
-
-  domNodes.forEach((node) => {
-    if (isText(node)) {
-      if (lineHolder.length === 0) {
-        // we are inserting first part of line
-        // it may contain block markdown starting data
-        // that we may need to escape.
-        lineHolder.push({ text: processLineStartText(node.data) });
-        return;
-      }
-      lineHolder.push({ text: processText(node.data) });
-      return;
-    }
-    if (isTag(node)) {
-      if (node.name === 'br') {
-        lineHolder.push({ text: '' });
-        appendLine();
-        return;
-      }
-
-      if (node.name === 'sub') {
-        appendLine();
-        children.push(parseSmallNode(node, processText));
-        return;
-      }
-
-      if (node.name === 'hr') {
-        appendLine();
-        children.push(parseHorizontalRuleNode(node));
-        return;
-      }
-
-      if (node.name === 'p') {
-        appendLine();
-        children.push({
-          type: BlockType.Paragraph,
-          children: node.children.flatMap((child) => getInlineElement(child, processText)),
-        });
-        return;
-      }
-
-      if (node.name === 'blockquote') {
-        appendLine();
-        children.push(...parseBlockquoteNode(node, processText));
-        return;
-      }
-      if (node.name === 'pre') {
-        appendLine();
-        children.push(...parseCodeBlockNode(node));
-        return;
-      }
-      if (node.name === 'ol' || node.name === 'ul') {
-        appendLine();
-        children.push(...parseListNode(node, processText));
-        return;
-      }
-
-      if (node.name.match(/^h[123456]$/)) {
-        appendLine();
-        children.push(parseHeadingNode(node, processText));
-        return;
-      }
-
-      lineHolder.push(...getInlineElement(node, processText));
-    }
-  });
-  appendLine();
-
-  return children;
-};
-
-export const htmlToEditorInput = (unsafeHtml: string, markdown?: boolean): Descendant[] => {
-  const sanitizedHtml = sanitizeCustomHtml(unsafeHtml);
-
-  const processText = (partText: string) => {
-    if (!markdown) return partText;
-    return escapeMarkdownInlineSequences(partText);
-  };
-
-  const domNodes = parse(sanitizedHtml);
-  const editorNodes = domToEditorInput(domNodes, processText, (lineStartText: string) => {
-    if (!markdown) return lineStartText;
-    return escapeMarkdownBlockSequences(lineStartText, processText);
-  });
-  return editorNodes;
-};
-
-export const plainToEditorInput = (text: string, markdown?: boolean): Descendant[] => {
-  const editorNodes: Descendant[] = text.split('\n').map((lineText) => {
-    const paragraphNode: ParagraphElement = {
-      type: BlockType.Paragraph,
-      children: [
-        {
-          text: markdown
-            ? escapeMarkdownBlockSequences(lineText, escapeMarkdownInlineSequences)
-            : lineText,
-        },
-      ],
-    };
-    return paragraphNode;
-  });
-  return editorNodes;
+export const plainToEditorInput = (text: string): Descendant[] => {
+  const lines = text.split('\n');
+  return lines.map((lineText) => ({
+    type: BlockType.Paragraph,
+    children: lineToParagraphChildren(lineText),
+  }));
 };
diff --git a/src/app/components/editor/keyboard.ts b/src/app/components/editor/keyboard.ts
index b45e9f9ab..05eb43213 100644
--- a/src/app/components/editor/keyboard.ts
+++ b/src/app/components/editor/keyboard.ts
@@ -1,116 +1,87 @@
 import { isKeyHotkey } from 'is-hotkey';
 import type { KeyboardEvent } from 'react';
-import { Editor, Element as SlateElement, Range, Transforms } from 'slate';
-import { isAnyMarkActive, isBlockActive, removeAllMark, toggleBlock, toggleMark } from './utils';
-import { BlockType, MarkType } from './types';
+import { Editor, Range, Transforms } from 'slate';
 
-export const INLINE_HOTKEYS: Record = {
-  'mod+b': MarkType.Bold,
-  'mod+i': MarkType.Italic,
-  'mod+u': MarkType.Underline,
-  'mod+s': MarkType.StrikeThrough,
-  'mod+[': MarkType.Code,
-  'mod+h': MarkType.Spoiler,
+export const INLINE_HOTKEYS: Record = {
+  'mod+b': '**',
+  'mod+i': '*',
+  'mod+u': '__',
+  'mod+s': '~~',
+  'mod+[': '`',
+  'mod+h': '||',
 };
 const INLINE_KEYS = Object.keys(INLINE_HOTKEYS);
 
-export const BLOCK_HOTKEYS: Record = {
-  'mod+7': BlockType.OrderedList,
-  'mod+8': BlockType.UnorderedList,
-  "mod+'": BlockType.BlockQuote,
-  'mod+;': BlockType.CodeBlock,
+export const BLOCK_HOTKEYS: Record = {
+  'mod+7': '1. ',
+  'mod+8': '- ',
+  "mod+'": '> ',
+  'mod+;': '```\n',
 };
 const BLOCK_KEYS = Object.keys(BLOCK_HOTKEYS);
 const isHeading1 = isKeyHotkey('mod+1');
 const isHeading2 = isKeyHotkey('mod+2');
 const isHeading3 = isKeyHotkey('mod+3');
 
+export const applyMarkdownInline = (editor: Editor, marker: string) => {
+  if (editor.selection && Range.isExpanded(editor.selection)) {
+    const text = Editor.string(editor, editor.selection);
+    Transforms.insertText(editor, `${marker}${text}${marker}`);
+  } else {
+    Transforms.insertText(editor, `${marker}${marker}`);
+    Transforms.move(editor, { distance: marker.length, reverse: true });
+  }
+};
+
+export const applyMarkdownBlockPrefix = (editor: Editor, prefix: string) => {
+  if (editor.selection) {
+    const path = editor.selection.anchor.path;
+    const startPoint = Editor.start(editor, path);
+    Transforms.insertText(editor, prefix, { at: startPoint });
+  }
+};
+
 /**
  * @return boolean true if shortcut is toggled.
  */
 export const toggleKeyboardShortcut = (editor: Editor, event: KeyboardEvent): boolean => {
-  if (isKeyHotkey('backspace', event) && editor.selection && Range.isCollapsed(editor.selection)) {
-    const startPoint = Range.start(editor.selection);
-    if (startPoint.offset !== 0) return false;
-
-    const [parentNode, parentPath] = Editor.parent(editor, startPoint);
-    const parentLocation = { at: parentPath };
-    const [previousNode] = Editor.previous(editor, parentLocation) ?? [];
-    const [nextNode] = Editor.next(editor, parentLocation) ?? [];
-
-    if (Editor.isEditor(parentNode)) return false;
-
-    if (parentNode.type === BlockType.Heading) {
-      toggleBlock(editor, BlockType.Paragraph);
-      return true;
-    }
-    if (
-      parentNode.type === BlockType.CodeLine ||
-      parentNode.type === BlockType.QuoteLine ||
-      parentNode.type === BlockType.ListItem
-    ) {
-      // exit formatting only when line block
-      // is first of last of it's parent
-      if (!previousNode || !nextNode) {
-        toggleBlock(editor, BlockType.Paragraph);
-        return true;
-      }
-    }
-    // Unwrap paragraph children to put them
-    // in previous none paragraph element
-    if (SlateElement.isElement(previousNode) && previousNode.type !== BlockType.Paragraph) {
-      Transforms.unwrapNodes(editor, {
-        at: startPoint,
-      });
-    }
-    Editor.deleteBackward(editor);
-    return true;
-  }
-
-  if (isKeyHotkey('mod+e', event) || isKeyHotkey('escape', event)) {
-    if (isAnyMarkActive(editor)) {
-      removeAllMark(editor);
-      return true;
-    }
-
-    if (!isBlockActive(editor, BlockType.Paragraph)) {
-      toggleBlock(editor, BlockType.Paragraph);
-      return true;
-    }
+  if (isKeyHotkey('escape', event)) {
     return false;
   }
 
   const blockToggled = BLOCK_KEYS.find((hotkey) => {
     if (isKeyHotkey(hotkey, event)) {
       event.preventDefault();
-      toggleBlock(editor, BLOCK_HOTKEYS[hotkey]!);
+      applyMarkdownBlockPrefix(editor, BLOCK_HOTKEYS[hotkey]!);
       return true;
     }
     return false;
   });
   if (blockToggled) return true;
+
   if (isHeading1(event)) {
-    toggleBlock(editor, BlockType.Heading, { level: 1 });
+    event.preventDefault();
+    applyMarkdownBlockPrefix(editor, '# ');
     return true;
   }
   if (isHeading2(event)) {
-    toggleBlock(editor, BlockType.Heading, { level: 2 });
+    event.preventDefault();
+    applyMarkdownBlockPrefix(editor, '## ');
     return true;
   }
   if (isHeading3(event)) {
-    toggleBlock(editor, BlockType.Heading, { level: 3 });
+    event.preventDefault();
+    applyMarkdownBlockPrefix(editor, '### ');
     return true;
   }
 
-  const inlineToggled = isBlockActive(editor, BlockType.CodeBlock)
-    ? false
-    : INLINE_KEYS.find((hotkey) => {
-        if (isKeyHotkey(hotkey, event)) {
-          event.preventDefault();
-          toggleMark(editor, INLINE_HOTKEYS[hotkey]!);
-          return true;
-        }
-        return false;
-      });
+  const inlineToggled = INLINE_KEYS.find((hotkey) => {
+    if (isKeyHotkey(hotkey, event)) {
+      event.preventDefault();
+      applyMarkdownInline(editor, INLINE_HOTKEYS[hotkey]!);
+      return true;
+    }
+    return false;
+  });
   return !!inlineToggled;
 };
diff --git a/src/app/components/editor/output.test.ts b/src/app/components/editor/output.test.ts
new file mode 100644
index 000000000..44a2dddb6
--- /dev/null
+++ b/src/app/components/editor/output.test.ts
@@ -0,0 +1,79 @@
+import { describe, expect, it } from 'vitest';
+import { toMatrixCustomHTML, trimCustomHtml } from '$components/editor/output';
+import { BlockType } from '$components/editor/types';
+
+describe('toMatrixCustomHTML emoticons', () => {
+  it('always serializes custom emoji images with height=32', () => {
+    const html = trimCustomHtml(
+      toMatrixCustomHTML(
+        [
+          {
+            type: BlockType.Paragraph,
+            children: [
+              {
+                type: BlockType.Emoticon,
+                key: 'mxc://example.org/emote',
+                shortcode: 'blobcat',
+                children: [{ text: '' }],
+              } as never,
+            ],
+          } as never,
+        ],
+        {}
+      )
+    );
+
+    expect(html).toContain('data-mx-emoticon');
+    expect(html).toContain('mxc://example.org/emote');
+    expect(html).toContain('height="32"');
+  });
+});
+
+describe('toMatrixCustomHTML matrix.to', () => {
+  it('serializes room mentions as raw matrix.to URL text, not an anchor', () => {
+    const html = trimCustomHtml(
+      toMatrixCustomHTML(
+        [
+          {
+            type: BlockType.Paragraph,
+            children: [
+              {
+                type: BlockType.Mention,
+                id: '!room:example.org',
+                name: 'My room',
+                children: [{ text: '' }],
+              } as never,
+            ],
+          } as never,
+        ],
+        {}
+      )
+    );
+
+    expect(html).toContain('https://matrix.to/#/!room:example.org');
+    expect(html).not.toMatch(/]*matrix\.to/i);
+  });
+
+  it('serializes matrix.to links as raw URL text, not an anchor', () => {
+    const html = trimCustomHtml(
+      toMatrixCustomHTML(
+        [
+          {
+            type: BlockType.Paragraph,
+            children: [
+              {
+                type: BlockType.Link,
+                href: 'https://matrix.to/#/@alice:example.org',
+                children: [{ text: 'Alice' }],
+              } as never,
+            ],
+          } as never,
+        ],
+        {}
+      )
+    );
+
+    expect(html).toContain('https://matrix.to/#/@alice:example.org');
+    expect(html).not.toMatch(/]*matrix\.to/i);
+  });
+});
diff --git a/src/app/components/editor/output.ts b/src/app/components/editor/output.ts
index cf65cdcbc..9bede4d6e 100644
--- a/src/app/components/editor/output.ts
+++ b/src/app/components/editor/output.ts
@@ -2,22 +2,15 @@ import type { Descendant, Editor } from 'slate';
 import { Text } from 'slate';
 import type { MatrixClient } from '$types/matrix-sdk';
 import { sanitizeText } from '$utils/sanitize';
-import {
-  parseBlockMD,
-  parseInlineMD,
-  unescapeMarkdownBlockSequences,
-  unescapeMarkdownInlineSequences,
-} from '$plugins/markdown';
-import { findAndReplace } from '$utils/findAndReplace';
+import { markdownToHtml, injectDataMd } from '$plugins/markdown';
 import { sanitizeForRegex } from '$utils/regex';
 import { isUserId } from '$utils/matrix';
 import type { CustomElement } from './slate';
 import { BlockType } from './types';
+import { getMarkdownCodeSpanRanges, isInsideMarkdownCodeSpan } from './utils';
+import { MATRIX_TO_BASE, testMatrixTo } from '$plugins/matrix-to';
 
 export type OutputOptions = {
-  allowTextFormatting?: boolean;
-  allowInlineMarkdown?: boolean;
-  allowBlockMarkdown?: boolean;
   /**
    * if true it will remove the nickname of the person from the message
    */
@@ -26,50 +19,16 @@ export type OutputOptions = {
    * a map of regex patterns to replace nicknames with, used when stripNickname is true
    */
   nickNameReplacement?: Map;
+  /** When true, markdown HTML omits the leading `

` wrapper (for `m.emote` / `/me`). */ + forEmote?: boolean; }; -const textToCustomHtml = (node: Text, opts: OutputOptions): string => { - let string = sanitizeText(node.text); - if (opts.allowTextFormatting) { - if (node.bold) string = `${string}`; - if (node.italic) string = `${string}`; - if (node.underline) string = `${string}`; - if (node.strikeThrough) string = `${string}`; - if (node.code) string = `${string}`; - if (node.spoiler) string = `${string}`; - } - - if (opts.allowInlineMarkdown && string === sanitizeText(node.text)) { - string = parseInlineMD(string); - } - - return string; -}; +const textToCustomHtml = (node: Text): string => sanitizeText(node.text); const elementToCustomHtml = (node: CustomElement, children: string): string => { switch (node.type) { case BlockType.Paragraph: return `${children}
`; - case BlockType.Heading: - return `${children}`; - case BlockType.CodeLine: - return `${children}\n`; - case BlockType.CodeBlock: - return `

${children}
`; - case BlockType.QuoteLine: - return `${children}
`; - case BlockType.BlockQuote: - return `
${children}
`; - case BlockType.ListItem: - return `
  • ${children}

  • `; - case BlockType.OrderedList: - return `
      ${children}
    `; - case BlockType.UnorderedList: - return `
      ${children}
    `; - case BlockType.Small: - return `${children}`; - case BlockType.HorizontalRule: - return `
    `; case BlockType.Mention: { let fragment = node.id; @@ -81,8 +40,8 @@ const elementToCustomHtml = (node: CustomElement, children: string): string => { fragment += `?${node.viaServers.map((server) => `via=${server}`).join('&')}`; } - const matrixTo = `https://matrix.to/#/${fragment}`; - return `${sanitizeText(node.name)}`; + const matrixTo = `${MATRIX_TO_BASE}#/${fragment}`; + return sanitizeText(matrixTo); } case BlockType.Emoticon: return node.key.startsWith('mxc://') @@ -91,7 +50,9 @@ const elementToCustomHtml = (node: CustomElement, children: string): string => { )}" title="${sanitizeText(node.shortcode)}" height="32" />` : sanitizeText(node.key); case BlockType.Link: - return `${children}`; + return testMatrixTo(node.href) + ? sanitizeText(node.href) + : `${children}`; case BlockType.Command: return `/${sanitizeText(node.command)}`; default: @@ -99,15 +60,6 @@ const elementToCustomHtml = (node: CustomElement, children: string): string => { } }; -const HTML_TAG_REG_G = /<([\w-]+)(?: [^>]*)?(?:(?:\/>)|(?:>.*?<\/\1>))/g; -const ignoreHTMLParseInlineMD = (text: string): string => - findAndReplace( - text, - HTML_TAG_REG_G, - (match) => match[0], - (txt) => parseInlineMD(txt) - ).join(''); - /** * convert slate internal representation to a custom HTML string that can be sent to the server * @param node slate node @@ -120,14 +72,12 @@ export const toMatrixCustomHTML = ( ): string => { let markdownLines = ''; const parseNode = (n: Descendant, index: number, targetNodes: Descendant[]) => { - if (opts.allowBlockMarkdown && 'type' in n && n.type === BlockType.Paragraph) { - let line = toMatrixCustomHTML(n, { - ...opts, - allowInlineMarkdown: false, - allowBlockMarkdown: false, - }) - .replace(/$/, '\n') - .replace(/^(\\*)>/, '$1>'); + if ('type' in n && n.type === BlockType.Paragraph) { + let line = toMatrixCustomHTML(n, opts); + + // Use \n for all paragraphs to prevent extra blank lines from + // accumulating on each edit cycle. + line = line.replace(/$/, '\n').replace(/^(\\*)>/, '$1>'); // strip nicknames if needed if (opts.stripNickname && opts.nickNameReplacement) { @@ -138,21 +88,19 @@ export const toMatrixCustomHTML = ( } markdownLines += line; if (index === targetNodes.length - 1) { - return parseBlockMD(markdownLines, ignoreHTMLParseInlineMD); + const html = markdownToHtml(markdownLines, { emote: opts.forEmote }); + return injectDataMd(html); } return ''; } - const parsedMarkdown = parseBlockMD(markdownLines, ignoreHTMLParseInlineMD); + const parsedMarkdown = markdownToHtml(markdownLines, { emote: opts.forEmote }); markdownLines = ''; - const isCodeLine = 'type' in n && n.type === BlockType.CodeLine; - if (isCodeLine) return `${parsedMarkdown}${toMatrixCustomHTML(n, {})}`; - - return `${parsedMarkdown}${toMatrixCustomHTML(n, { ...opts, allowBlockMarkdown: false })}`; + return `${parsedMarkdown}${toMatrixCustomHTML(n, opts)}`; }; if (Array.isArray(node)) return node.map((element, index, array) => parseNode(element, index, array)).join(''); - if (Text.isText(node)) return textToCustomHtml(node, opts); + if (Text.isText(node)) return textToCustomHtml(node); const children = node.children .map((element, index, array) => parseNode(element, index, array)) @@ -164,22 +112,6 @@ const elementToPlainText = (node: CustomElement, children: string): string => { switch (node.type) { case BlockType.Paragraph: return `${children}\n`; - case BlockType.Heading: - return `${children}\n`; - case BlockType.CodeLine: - return `${children}\n`; - case BlockType.CodeBlock: - return `${children}\n`; - case BlockType.QuoteLine: - return `| ${children}\n`; - case BlockType.BlockQuote: - return `${children}\n`; - case BlockType.ListItem: - return `- ${children}\n`; - case BlockType.OrderedList: - return `${children}\n`; - case BlockType.UnorderedList: - return `${children}\n`; case BlockType.Mention: return node.id; case BlockType.Emoticon: @@ -188,16 +120,16 @@ const elementToPlainText = (node: CustomElement, children: string): string => { return `[${children}](${node.href})`; case BlockType.Command: return `/${node.command}`; - case BlockType.Small: - return `-# ${children}\n`; - case BlockType.HorizontalRule: - return `\n---\n`; default: return children; } }; const SPOILERINPUTREGEX = /\|\|.+?\|\|/g; +const LINK_URL = `(https?:\\/\\/.[A-Za-z0-9-._~:/?#[\\]()@!$&'*+,;%=]+)`; +export const LINKINPUTREGEX = new RegExp(`\\(?(${LINK_URL})\\)?`, 'g'); +const SPOILEREDLINKINPUTREGEX = new RegExp(`<(${LINK_URL})>`, 'g'); +const SPOILEREDLINKDIRECTREGEX = new RegExp(`\\|\\|(${LINK_URL})\\|\\|`, 'g'); /** * convert slate internal representation to a plain text string that can be sent to the server @@ -209,33 +141,57 @@ const SPOILERINPUTREGEX = /\|\|.+?\|\|/g; */ export const toPlainText = ( node: Descendant | Descendant[], - isMarkdown: boolean, stripNickname = false, nickNameReplacement?: Map ): string => { if (Array.isArray(node)) - return node.map((n) => toPlainText(n, isMarkdown, stripNickname, nickNameReplacement)).join(''); + return node.map((n) => toPlainText(n, stripNickname, nickNameReplacement)).join(''); if (Text.isText(node)) { let { text } = node; + text = text.replaceAll(SPOILERINPUTREGEX, '[Spoiler]'); + text = text.replaceAll(SPOILEREDLINKINPUTREGEX, '$1'); + if (stripNickname && nickNameReplacement) { nickNameReplacement?.keys().forEach((key) => { const replacement = nickNameReplacement.get(key) ?? ''; text = text.replaceAll(key, replacement); }); - return isMarkdown - ? unescapeMarkdownBlockSequences(text, unescapeMarkdownInlineSequences) - : text; } - return isMarkdown - ? unescapeMarkdownBlockSequences(text, unescapeMarkdownInlineSequences) - : text; + return text; } - const children = node.children.map((n) => toPlainText(n, isMarkdown)).join(''); + const children = node.children + .map((n) => toPlainText(n, stripNickname, nickNameReplacement)) + .join(''); return elementToPlainText(node, children); }; +/** + * Convert slate internal representation to a raw plain text string without any replacements. + * This is used for link extraction to ensure we have the full context for markdown blocks. + */ +export const toRawText = (node: Descendant | Descendant[]): string => { + if (Array.isArray(node)) return node.map(toRawText).join(''); + if (Text.isText(node)) return node.text; + + const children = node.children.map(toRawText).join(''); + switch (node.type) { + case BlockType.Paragraph: + return `${children}\n`; + case BlockType.Link: + return `[${children}](${node.href})`; + case BlockType.Emoticon: + return node.key.startsWith('mxc://') ? `:${node.shortcode}:` : node.key; + case BlockType.Mention: + return node.id; + case BlockType.Command: + return `/${node.command}`; + default: + return children; + } +}; + /** * Check if customHtml is equals to plainText * by replacing `
    ` with `/n` in customHtml @@ -251,9 +207,11 @@ export const customHtmlEqualsPlainText = (customHtml: string, plain: string): bo export const trimCustomHtml = (customHtml: string) => customHtml.replaceAll(/$/g, '').trim(); export const trimCommand = (cmdName: string, str: string) => { - const cmdRegX = new RegExp(`^(\\s+)?(\\/${sanitizeForRegex(cmdName)})([^\\S\n]+)?`); + const escapedCmd = sanitizeForRegex(cmdName); + // Allow optional leading whitespace and/or

    tag for HTML strings + const cmdRegX = new RegExp(`^(?:\\s+)?(?:

    )?(?:\\/${escapedCmd})(?:[^\\S\n]+)?`, 'i'); - const match = new RegExp(cmdRegX).exec(str); + const match = cmdRegX.exec(str); if (!match) return str; return str.slice(match[0].length); }; @@ -287,7 +245,6 @@ export const getMentions = (mx: MatrixClient, roomId: string, editor: Editor): M const parseMentions = (node: Descendant): void => { if (Text.isText(node)) return; - if (node.type === BlockType.CodeBlock) return; if (node.type === BlockType.Mention) { if (node.name === '@room') { @@ -308,3 +265,44 @@ export const getMentions = (mx: MatrixClient, roomId: string, editor: Editor): M return mentionData; }; + +export const getLinks = (serialized: Descendant | Descendant[]): string[] | undefined => { + const text = toRawText(serialized); + const finalList = new Set(); + + // 1. Find all potential URLs + const urlsMatch = text.matchAll(LINKINPUTREGEX); + const spoileredUrlsMatch = [...text.matchAll(SPOILEREDLINKINPUTREGEX)].map((m) => m[1]); + const directSpoileredUrlsMatch = [...text.matchAll(SPOILEREDLINKDIRECTREGEX)].map((m) => m[1]); + const allSpoilered = new Set([...spoileredUrlsMatch, ...directSpoileredUrlsMatch]); + + const codeSpanRanges = getMarkdownCodeSpanRanges(text); + + for (const match of urlsMatch) { + let url = match[1]!; + const fullMatch = match[0]; + const index = match.index; + + // Clean up surrounding parens from markdown [label](url) or (url) + if (fullMatch.startsWith('(') && fullMatch.endsWith(')')) { + url = fullMatch.substring(1, fullMatch.length - 1); + } else if (fullMatch.startsWith('(')) { + url = fullMatch.substring(1); + } else if (fullMatch.endsWith('/)')) { + url = fullMatch.substring(0, fullMatch.length - 1); + } + + if (allSpoilered.has(url)) continue; + + // Check if it's inside a code span/block + if (isInsideMarkdownCodeSpan(index, index + fullMatch.length, codeSpanRanges)) { + continue; + } + + if (url.startsWith(MATRIX_TO_BASE)) continue; + + finalList.add(url); + } + + return Array.from(finalList); +}; diff --git a/src/app/components/editor/slate.d.ts b/src/app/components/editor/slate.d.ts index 05c8b5aec..7cca18623 100644 --- a/src/app/components/editor/slate.d.ts +++ b/src/app/components/editor/slate.d.ts @@ -3,22 +3,13 @@ import type { ReactEditor } from 'slate-react'; import type { HistoryEditor } from 'slate-history'; import type { BlockType } from './types'; -export type HeadingLevel = 1 | 2 | 3; - export type Editor = BaseEditor & HistoryEditor & ReactEditor; export type Text = { text: string; }; -export type FormattedText = Text & { - bold?: boolean; - italic?: boolean; - underline?: boolean; - strikeThrough?: boolean; - code?: boolean; - spoiler?: boolean; -}; +export type FormattedText = Text; export type LinkElement = { type: BlockType.Link; @@ -47,77 +38,29 @@ export type CommandElement = { children: Text[]; }; -export type InlineElement = Text | LinkElement | MentionElement | EmoticonElement | CommandElement; +export type InlineElement = + | FormattedText + | LinkElement + | MentionElement + | EmoticonElement + | CommandElement; export type ParagraphElement = { type: BlockType.Paragraph; children: InlineElement[]; }; -export type HeadingElement = { - type: BlockType.Heading; - level: HeadingLevel; - children: InlineElement[]; -}; -export type CodeLineElement = { - type: BlockType.CodeLine; - children: Text[]; -}; -export type CodeBlockElement = { - type: BlockType.CodeBlock; - children: CodeLineElement[]; -}; -export type QuoteLineElement = { - type: BlockType.QuoteLine; - children: InlineElement[]; -}; -export type BlockQuoteElement = { - type: BlockType.BlockQuote; - children: QuoteLineElement[]; -}; -export type ListItemElement = { - type: BlockType.ListItem; - children: InlineElement[]; -}; -export type OrderedListElement = { - type: BlockType.OrderedList; - children: ListItemElement[]; -}; -export type UnorderedListElement = { - type: BlockType.UnorderedList; - children: ListItemElement[]; -}; - -export type SmallElement = { - type: BlockType.Small; - children: InlineElement[]; -}; - -export type HorizontalRuleElement = { - type: BlockType.HorizontalRule; - children: Text[]; -}; export type CustomElement = | LinkElement | MentionElement | EmoticonElement | CommandElement - | ParagraphElement - | HeadingElement - | CodeLineElement - | CodeBlockElement - | QuoteLineElement - | BlockQuoteElement - | ListItemElement - | OrderedListElement - | UnorderedListElement - | SmallElement - | HorizontalRuleElement; + | ParagraphElement; declare module 'slate' { interface CustomTypes { Editor: Editor; Element: CustomElement; - Text: FormattedText & Text; + Text: FormattedText; } } diff --git a/src/app/components/editor/types.ts b/src/app/components/editor/types.ts index 52115a3f4..a1cac110d 100644 --- a/src/app/components/editor/types.ts +++ b/src/app/components/editor/types.ts @@ -1,26 +1,7 @@ -export enum MarkType { - Bold = 'bold', - Italic = 'italic', - Underline = 'underline', - StrikeThrough = 'strikeThrough', - Code = 'code', - Spoiler = 'spoiler', -} - export enum BlockType { Paragraph = 'paragraph', - Heading = 'heading', - CodeLine = 'code-line', - CodeBlock = 'code-block', - QuoteLine = 'quote-line', - BlockQuote = 'block-quote', - ListItem = 'list-item', - OrderedList = 'ordered-list', - UnorderedList = 'unordered-list', Mention = 'mention', Emoticon = 'emoticon', Link = 'link', Command = 'command', - Small = 'sub', - HorizontalRule = 'hr', } diff --git a/src/app/components/editor/utils.ts b/src/app/components/editor/utils.ts index 254d7a5b7..03adabd90 100644 --- a/src/app/components/editor/utils.ts +++ b/src/app/components/editor/utils.ts @@ -1,154 +1,14 @@ import type { BasePoint, BaseRange } from 'slate'; import { Editor, Element, Point, Range, Text, Transforms } from 'slate'; -import { BlockType, MarkType } from './types'; +import { BlockType } from './types'; import type { CommandElement, EmoticonElement, FormattedText, - HeadingLevel, LinkElement, MentionElement, } from './slate'; -const ALL_MARK_TYPE: MarkType[] = [ - MarkType.Bold, - MarkType.Code, - MarkType.Italic, - MarkType.Spoiler, - MarkType.StrikeThrough, - MarkType.Underline, -]; - -export const isMarkActive = (editor: Editor, format: MarkType) => { - const marks = Editor.marks(editor); - return marks ? marks[format] === true : false; -}; - -export const isAnyMarkActive = (editor: Editor) => { - const marks = Editor.marks(editor); - return marks && !!ALL_MARK_TYPE.find((type) => marks[type] === true); -}; - -export const toggleMark = (editor: Editor, format: MarkType) => { - const isActive = isMarkActive(editor, format); - - if (isActive) { - Editor.removeMark(editor, format); - } else { - Editor.addMark(editor, format, true); - } -}; - -export const removeAllMark = (editor: Editor) => { - ALL_MARK_TYPE.forEach((mark) => { - if (isMarkActive(editor, mark)) Editor.removeMark(editor, mark); - }); -}; - -export const isBlockActive = (editor: Editor, format: BlockType) => { - const [match] = Editor.nodes(editor, { - match: (node) => Element.isElement(node) && node.type === format, - }); - - return !!match; -}; - -export const headingLevel = (editor: Editor): HeadingLevel | undefined => { - const [nodeEntry] = Editor.nodes(editor, { - match: (node) => Element.isElement(node) && node.type === BlockType.Heading, - }); - const [node] = nodeEntry ?? []; - if (!node) return undefined; - if ('level' in node) return node.level; - return undefined; -}; - -type BlockOption = { level: HeadingLevel }; -const NESTED_BLOCK = new Set([ - BlockType.OrderedList, - BlockType.UnorderedList, - BlockType.BlockQuote, - BlockType.CodeBlock, -]); - -export const toggleBlock = (editor: Editor, format: BlockType, option?: BlockOption) => { - Transforms.collapse(editor, { - edge: 'end', - }); - const isActive = isBlockActive(editor, format); - - Transforms.unwrapNodes(editor, { - match: (node) => Element.isElement(node) && NESTED_BLOCK.has(node.type), - split: true, - }); - - if (isActive) { - Transforms.setNodes(editor, { - type: BlockType.Paragraph, - }); - return; - } - - if (format === BlockType.OrderedList || format === BlockType.UnorderedList) { - Transforms.setNodes(editor, { - type: BlockType.ListItem, - }); - const block = { - type: format, - children: [], - }; - Transforms.wrapNodes(editor, block); - return; - } - if (format === BlockType.CodeBlock) { - Transforms.setNodes(editor, { - type: BlockType.CodeLine, - }); - const block = { - type: format, - children: [], - }; - Transforms.wrapNodes(editor, block); - return; - } - - if (format === BlockType.BlockQuote) { - Transforms.setNodes(editor, { - type: BlockType.QuoteLine, - }); - const block = { - type: format, - children: [], - }; - Transforms.wrapNodes(editor, block); - return; - } - - if (format === BlockType.Heading) { - Transforms.setNodes(editor, { - type: format, - level: option?.level ?? 1, - }); - } - - if (format === BlockType.HorizontalRule) { - Transforms.insertNodes(editor, { - type: BlockType.HorizontalRule, - children: [{ text: '' }], - }); - return; - } - - if (format === BlockType.Small) { - Transforms.setNodes(editor, { type: BlockType.Small }); - return; - } - - Transforms.setNodes(editor, { - type: format, - }); -}; - export const resetEditor = (editor: Editor) => { Transforms.delete(editor, { at: { @@ -157,8 +17,7 @@ export const resetEditor = (editor: Editor) => { }, }); - toggleBlock(editor, BlockType.Paragraph); - removeAllMark(editor); + Transforms.setNodes(editor, { type: BlockType.Paragraph }); }; export const resetEditorHistory = (editor: Editor) => { @@ -286,3 +145,35 @@ export const getBeginCommand = (editor: Editor): string | undefined => { return secondInline.command; return undefined; }; + +export const getMarkdownCodeSpanRanges = (text: string): [number, number][] => { + const ranges: [number, number][] = []; + let openRun: { start: number; length: number } | undefined; + + for (let index = 0; index < text.length; index += 1) { + if (text[index] === '`') { + let runEnd = index; + while (runEnd < text.length && text[runEnd] === '`') { + runEnd += 1; + } + + const runLength = runEnd - index; + if (!openRun) { + openRun = { start: index, length: runLength }; + } else if (openRun.length === runLength) { + ranges.push([openRun.start, runEnd]); + openRun = undefined; + } + + index = runEnd - 1; + } + } + + return ranges; +}; + +export const isInsideMarkdownCodeSpan = ( + start: number, + end: number, + codeSpanRanges: [number, number][] +): boolean => codeSpanRanges.some(([rangeStart, rangeEnd]) => start > rangeStart && end < rangeEnd); diff --git a/src/app/components/event-readers/EventReaders.css.ts b/src/app/components/event-readers/EventReaders.css.ts index 36f47b56e..fa56c221b 100644 --- a/src/app/components/event-readers/EventReaders.css.ts +++ b/src/app/components/event-readers/EventReaders.css.ts @@ -5,6 +5,7 @@ export const EventReaders = style([ DefaultReset, { height: '100%', + width: '280px', }, ]); @@ -18,4 +19,6 @@ export const Header = style({ export const Content = style({ paddingLeft: config.space.S200, paddingBottom: config.space.S400, + width: '100%', + minWidth: 0, }); diff --git a/src/app/components/event-readers/EventReaders.tsx b/src/app/components/event-readers/EventReaders.tsx index b1c2b9d2b..88f7eac57 100644 --- a/src/app/components/event-readers/EventReaders.tsx +++ b/src/app/components/event-readers/EventReaders.tsx @@ -58,9 +58,14 @@ export const EventReaders = as<'div', EventReadersProps>( - - - + + + {latestEventReaders.map((readerId) => { const name = getName(readerId); const avatarMxcUrl = room.getMember(readerId)?.getMxcAvatarUrl(); @@ -79,7 +84,7 @@ export const EventReaders = as<'div', EventReadersProps>( return ( { openProfile( @@ -107,8 +112,8 @@ export const EventReaders = as<'div', EventReadersProps>( ); })} - - + + ); diff --git a/src/app/components/invite-user-prompt/InviteUserPrompt.tsx b/src/app/components/invite-user-prompt/InviteUserPrompt.tsx index 9ab427ab3..0d81bc5d7 100644 --- a/src/app/components/invite-user-prompt/InviteUserPrompt.tsx +++ b/src/app/components/invite-user-prompt/InviteUserPrompt.tsx @@ -27,8 +27,7 @@ import { isKeyHotkey } from 'is-hotkey'; import FocusTrap from 'focus-trap-react'; import { stopPropagation } from '$utils/keyboard'; import { useDirectUsers } from '$hooks/useDirectUsers'; -import { getMxIdLocalPart, getMxIdServer, isUserId } from '$utils/matrix'; - +import { getMxIdLocalPart, isUserId } from '$utils/matrix'; import type { UseAsyncSearchOptions } from '$hooks/useAsyncSearch'; import { useAsyncSearch } from '$hooks/useAsyncSearch'; import { highlightText, makeHighlightRegex } from '$plugins/react-custom-html-parser'; @@ -36,6 +35,7 @@ import { AsyncStatus, useAsyncCallback } from '$hooks/useAsyncCallback'; import { useMatrixClient } from '$hooks/useMatrixClient'; import { BreakWord } from '$styles/Text.css'; import { useAlive } from '$hooks/useAlive'; +import { getMxIdServer } from '$utils/mxIdHelper'; import { KnownMembership } from '$types/matrix-sdk'; const SEARCH_OPTIONS: UseAsyncSearchOptions = { diff --git a/src/app/components/member-tile/MemberTile.tsx b/src/app/components/member-tile/MemberTile.tsx index f6cb1cc94..c74433eb7 100644 --- a/src/app/components/member-tile/MemberTile.tsx +++ b/src/app/components/member-tile/MemberTile.tsx @@ -29,7 +29,7 @@ export const MemberTile = as<'button', MemberTileProps>( const name = getName(room, member, nicknames); const presence = useUserPresence(member.userId ?? ''); - const avatarMxcUrl = member.getMxcAvatarUrl(); + const avatarMxcUrl = member.getMxcAvatarUrl() ?? mx.getUser(member.userId)?.avatarUrl; const avatarUrl = avatarMxcUrl ? mx.mxcUrlToHttp(avatarMxcUrl, 100, 100, 'crop', undefined, false, useAuthentication) : undefined; diff --git a/src/app/components/message/MsgTypeRenderers.tsx b/src/app/components/message/MsgTypeRenderers.tsx index 399228cc2..cb91c3474 100644 --- a/src/app/components/message/MsgTypeRenderers.tsx +++ b/src/app/components/message/MsgTypeRenderers.tsx @@ -2,7 +2,7 @@ import type { CSSProperties, ReactNode } from 'react'; import { useMemo } from 'react'; import { Box, Chip, Icon, Icons, Text, toRem } from 'folds'; import type { IContent, IPreviewUrlResponse } from '$types/matrix-sdk'; -import { JUMBO_EMOJI_REG, URL_REG } from '$utils/regex'; +import { JUMBO_EMOJI_REG } from '$utils/regex'; import { trimReplyFromBody } from '$utils/room'; import type { IAudioContent, @@ -16,10 +16,7 @@ import type { IVideoContent, IVideoInfo, } from '$types/matrix/common'; -import { - MATRIX_SPOILER_PROPERTY_NAME, - MATRIX_SPOILER_REASON_PROPERTY_NAME, -} from '$types/matrix/common'; +import * as prefix from '$unstable/prefixes'; import { FALLBACK_MIMETYPE, getBlobSafeMimeType } from '$utils/mimeTypes'; import { parseGeoUri, scaleYDimension } from '$utils/common'; import { useSetting } from '$state/hooks/settings'; @@ -36,8 +33,10 @@ import { } from './content'; import { MessageTextBody } from './layout'; import { unwrapForwardedContent } from './modals/MessageForward'; +import { LINKINPUTREGEX } from '$components/editor'; +import { MATRIX_TO_BASE } from '$plugins/matrix-to'; -interface BundleContent extends IPreviewUrlResponse { +export interface BundleContent extends IPreviewUrlResponse { matched_url: string; } @@ -92,6 +91,59 @@ type MTextProps = { renderBundledPreviews?: (bundles: IPreviewUrlResponse[]) => ReactNode; style?: CSSProperties; }; + +const getUrlsFromContent = ( + content: Record, + renderUrlsPreview?: (urls: string[]) => ReactNode +): { urls?: string[]; bundleContent?: BundleContent[] } => { + const body = typeof content.body === 'string' ? content.body : ''; + const customBody = + typeof content.formatted_body === 'string' ? content.formatted_body : undefined; + const trimmedBody = trimReplyFromBody(body); + + const urlsMatch = trimmedBody.match(LINKINPUTREGEX); + let urls = urlsMatch ? [...new Set(urlsMatch)] : undefined; + urls = urls?.map( + (url) => + (url.startsWith('(') && url.endsWith(')') && url.substring(1, url.length - 1)) || + (url.startsWith('(') && url.substring(1)) || + (url.endsWith('/)') && url.substring(0, url.length - 1)) || + url + ); + + if (urls && customBody) { + // Filter out URLs that only appear inside or

     tags in the formatted body
    +    const safeHtml = customBody
    +      .replace(/]*>.*?<\/pre>/gs, '')
    +      .replace(/]*>.*?<\/code>/gs, '');
    +    const safeText = safeHtml.replace(/<[^a][^>]*>/g, '');
    +    const safeUrlsMatch = safeText.match(LINKINPUTREGEX);
    +    let safeUrls = safeUrlsMatch ? [...new Set(safeUrlsMatch)] : [];
    +    safeUrls = safeUrls.map(
    +      (url) =>
    +        (url.startsWith('(') && url.endsWith(')') && url.substring(1, url.length - 1)) ||
    +        (url.startsWith('(') && url.substring(1)) ||
    +        (url.endsWith('/)') && url.substring(0, url.length - 1)) ||
    +        url
    +    );
    +    const safeUrlsSet = new Set(safeUrls);
    +    urls = urls.filter((url) => safeUrlsSet.has(url) && !url.startsWith(MATRIX_TO_BASE));
    +  }
    +
    +  let bundleContent = content[
    +    prefix.MATRIX_UNSTABLE_EMBEDDED_LINK_PREVIEW_PROPERTY_NAME
    +  ] as BundleContent[];
    +  try {
    +    bundleContent = bundleContent?.filter((bundle) => !!urls?.includes(bundle.matched_url));
    +    if (renderUrlsPreview && bundleContent)
    +      urls = bundleContent.map((bundle) => bundle.matched_url);
    +  } catch {
    +    urls = [];
    +  }
    +
    +  return { urls, bundleContent };
    +};
    +
     export function MText({
       edited,
       content,
    @@ -105,15 +157,19 @@ export function MText({
       const body = typeof content.body === 'string' ? content.body : '';
       const customBody =
         typeof content.formatted_body === 'string' ? content.formatted_body : undefined;
    +  const cleanedMessage = useMemo(
    +    () => customBody?.replace(/
  • (

    <\/p>)?<\/li>/gi, '


  • '), + [customBody] + ); const trimmedBody = useMemo(() => trimReplyFromBody(body), [body]); const unwrappedForwardedContent = useMemo( - () => unwrapForwardedContent(customBody ?? body), - [customBody, body] + () => unwrapForwardedContent(cleanedMessage ?? customBody ?? body), + [cleanedMessage, customBody, body] ); const isForwarded = useMemo(() => { - const forwardMeta = content['moe.sable.message.forward']; + const forwardMeta = content[prefix.MATRIX_SABLE_UNSTABLE_MESSAGE_FORWARD_META_PROPERTY_NAME]; return typeof forwardMeta === 'object'; }, [content]); @@ -121,14 +177,15 @@ export function MText({ * For the unwrapping of per-message profile fallbacks, we look for tags with the data-mx-profile-fallback attribute */ const unwrappedPerMessageProfileMessage = useMemo( - () => customBody?.replace(/]*data-mx-profile-fallback[^>]*>(.*?):\s*<\/strong>/i, ''), - [customBody] + () => + cleanedMessage?.replace(/]*data-mx-profile-fallback[^>]*>(.*?):\s*<\/strong>/i, ''), + [cleanedMessage] ); const isJumbo = useMemo(() => { if (!trimmedBody || trimmedBody.length >= 500) return false; if ( - (unwrappedPerMessageProfileMessage ?? customBody)?.match( + (unwrappedPerMessageProfileMessage ?? cleanedMessage ?? customBody)?.match( /^(]*data-mx-emoticon[^>]*\/>){1,20}$/i ) ) @@ -141,31 +198,37 @@ export function MText({ } return true; - }, [unwrappedPerMessageProfileMessage, trimmedBody, customBody]); + }, [unwrappedPerMessageProfileMessage, cleanedMessage, trimmedBody, customBody]); - if (!body && !customBody) return ; + const { urls, bundleContent } = getUrlsFromContent(content, renderUrlsPreview); - let bundleContent: BundleContent[] | undefined; - const urlsMatch = trimmedBody.match(URL_REG); - let urls = urlsMatch ? [...new Set(urlsMatch)] : undefined; - bundleContent = content['com.beeper.linkpreviews'] as BundleContent[]; - bundleContent = bundleContent?.filter((bundle) => !!urls?.includes(bundle.matched_url)); - if (renderUrlsPreview && bundleContent) urls = bundleContent.map((bundle) => bundle.matched_url); - - if ((content['com.beeper.per_message_profile'] as PerMessageProfileBeeperFormat)?.has_fallback) { + if ( + ( + content[ + prefix.MATRIX_UNSTABLE_PER_MESSAGE_PROFILE_PROPERTY_NAME + ] as PerMessageProfileBeeperFormat + )?.has_fallback + ) { // unwrap per-message profile fallback if present return ( - - {renderBody({ - body: trimmedBody, - customBody: unwrappedPerMessageProfileMessage, - })} - {edited && } - + <> + + {renderBody({ + body: trimmedBody, + customBody: unwrappedPerMessageProfileMessage, + })} + {edited && } + + {(renderUrlsPreview && urls && urls.length > 0 && renderUrlsPreview(urls)) || + (renderBundledPreviews && + bundleContent && + bundleContent.length > 0 && + renderBundledPreviews(bundleContent as IPreviewUrlResponse[]))} + ); } @@ -189,13 +252,13 @@ export function MText({ return ( <> {renderBody({ body: trimmedBody, - customBody: typeof customBody === 'string' ? customBody : undefined, + customBody: typeof cleanedMessage === 'string' ? cleanedMessage : undefined, })} {edited && } @@ -225,6 +288,13 @@ export function MEmote({ renderBundledPreviews, }: MEmoteProps) { const { body, formatted_body: customBody } = content; + const cleanedMessage = useMemo( + () => + typeof customBody === 'string' + ? customBody.replace(/
  • (

    <\/p>)?<\/li>/gi, '


  • ') + : undefined, + [customBody] + ); const [jumboEmojiSize] = useSetting(settingsAtom, 'jumboEmojiSize'); if (typeof body !== 'string') { @@ -233,23 +303,19 @@ export function MEmote({ const trimmedBody = trimReplyFromBody(body); const isJumbo = JUMBO_EMOJI_REG.test(trimmedBody); - let bundleContent: BundleContent[] | undefined; - const urlsMatch = trimmedBody.match(URL_REG); - const urls = urlsMatch ? [...new Set(urlsMatch)] : undefined; - bundleContent = content['com.beeper.linkpreviews'] as BundleContent[]; - bundleContent = bundleContent?.filter((bundle) => !!urls?.includes(bundle.matched_url)); + const { urls, bundleContent } = getUrlsFromContent(content, renderUrlsPreview); return ( <> {`${displayName} `} {renderBody({ body: trimmedBody, - customBody: typeof customBody === 'string' ? customBody : undefined, + customBody: typeof cleanedMessage === 'string' ? cleanedMessage : undefined, })} {edited && } @@ -277,6 +343,13 @@ export function MNotice({ renderBundledPreviews, }: MNoticeProps) { const { body, formatted_body: customBody } = content; + const cleanedMessage = useMemo( + () => + typeof customBody === 'string' + ? customBody.replace(/
  • (

    <\/p>)?<\/li>/gi, '


  • ') + : undefined, + [customBody] + ); const [jumboEmojiSize] = useSetting(settingsAtom, 'jumboEmojiSize'); if (typeof body !== 'string') { @@ -285,22 +358,18 @@ export function MNotice({ const trimmedBody = trimReplyFromBody(body); const isJumbo = JUMBO_EMOJI_REG.test(trimmedBody); - let bundleContent: BundleContent[] | undefined; - const urlsMatch = trimmedBody.match(URL_REG); - const urls = urlsMatch ? [...new Set(urlsMatch)] : undefined; - bundleContent = content['com.beeper.linkpreviews'] as BundleContent[]; - bundleContent = bundleContent?.filter((bundle) => !!urls?.includes(bundle.matched_url)); + const { urls, bundleContent } = getUrlsFromContent(content, renderUrlsPreview); return ( <> {renderBody({ body: trimmedBody, - customBody: typeof customBody === 'string' ? customBody : undefined, + customBody: typeof cleanedMessage === 'string' ? cleanedMessage : undefined, })} {edited && } @@ -362,8 +431,8 @@ export function MImage({ content, renderImageContent, outlined }: MImageProps) { mimeType: imgInfo?.mimetype, url: mxcUrl, encInfo: content.file, - markedAsSpoiler: content[MATRIX_SPOILER_PROPERTY_NAME], - spoilerReason: content[MATRIX_SPOILER_REASON_PROPERTY_NAME], + markedAsSpoiler: content[prefix.MATRIX_UNSTABLE_SPOILER_PROPERTY_NAME], + spoilerReason: content[prefix.MATRIX_UNSTABLE_SPOILER_REASON_PROPERTY_NAME], })} @@ -434,8 +503,8 @@ export function MVideo({ content, renderAsFile, renderVideoContent, outlined }: mimeType: safeMimeType, url: mxcUrl, encInfo: content.file, - markedAsSpoiler: content[MATRIX_SPOILER_PROPERTY_NAME], - spoilerReason: content[MATRIX_SPOILER_REASON_PROPERTY_NAME], + markedAsSpoiler: content[prefix.MATRIX_UNSTABLE_SPOILER_PROPERTY_NAME], + spoilerReason: content[prefix.MATRIX_UNSTABLE_SPOILER_REASON_PROPERTY_NAME], })} diff --git a/src/app/components/message/Reply.tsx b/src/app/components/message/Reply.tsx index 46537cd4d..86abbacb9 100644 --- a/src/app/components/message/Reply.tsx +++ b/src/app/components/message/Reply.tsx @@ -26,6 +26,8 @@ import { useIgnoredUsers } from '$hooks/useIgnoredUsers'; import { nicknamesAtom } from '$state/nicknames'; import { useMatrixClient } from '$hooks/useMatrixClient'; import { useMemberEventParser } from '$hooks/useMemberEventParser'; +import { useSetting } from '$state/hooks/settings'; +import { settingsAtom } from '$state/settings'; import { useMentionClickHandler } from '$hooks/useMentionClickHandler'; import { useTranslation } from 'react-i18next'; @@ -139,6 +141,14 @@ export const Reply = as<'div', ReplyProps>( const nicknames = useAtomValue(nicknamesAtom); const useAuthentication = useMediaAuthentication(); const settingsLinkBaseUrl = useSettingsLinkBaseUrl(); + const [incomingInlineImagesDefaultHeight] = useSetting( + settingsAtom, + 'incomingInlineImagesDefaultHeight' + ); + const [incomingInlineImagesMaxHeight] = useSetting( + settingsAtom, + 'incomingInlineImagesMaxHeight' + ); const fallbackBody = isRedacted ? : ; @@ -190,6 +200,8 @@ export const Reply = as<'div', ReplyProps>( useAuthentication, nicknames, handleMentionClick: mentionClickHandler, + incomingInlineImagesDefaultHeight, + incomingInlineImagesMaxHeight, }); bodyJSX = parse(sanitizedHtml, parserOpts) as JSX.Element; } else if (hasPlainTextReply) { @@ -231,7 +243,7 @@ export const Reply = as<'div', ReplyProps>( {(pinsAdded?.length > 0 && `pinned ${pinsAdded.length} message${pinsAdded.length > 1 ? 's' : ''}`) || ''} - {(pinsAdded?.length > 0 && pinsRemoved?.length > 0 && `and`) || ''} + {(pinsAdded?.length > 0 && pinsRemoved?.length > 0 && ` and `) || ''} {(pinsRemoved?.length > 0 && `unpinned ${pinsRemoved.length} message${pinsRemoved.length > 1 ? 's' : ''}`) || ''} @@ -280,7 +292,7 @@ export const Reply = as<'div', ReplyProps>( onClick={replyEvent !== null && !isBlockedSender ? onClick : undefined} > {replyEvent !== undefined && !isPendingDecrypt ? ( - + {replyContent} ) : ( diff --git a/src/app/components/message/content/FallbackContent.tsx b/src/app/components/message/content/FallbackContent.tsx index 9bd012a13..638e830c3 100644 --- a/src/app/components/message/content/FallbackContent.tsx +++ b/src/app/components/message/content/FallbackContent.tsx @@ -1,5 +1,7 @@ import { Box, Icon, Icons, Text, as, color, config } from 'folds'; +import { BreakWord } from '$styles/Text.css'; + const warningStyle = { color: color.Warning.Main, opacity: config.opacity.P300 }; const criticalStyle = { color: color.Critical.Main, opacity: config.opacity.P300 }; @@ -18,11 +20,21 @@ export const MessageDeletedContent = as<'div', { children?: never; reason?: stri export const MessageUnsupportedContent = as<'div', { children?: never; body?: string }>( ({ body, ...props }, ref) => ( - + - Unsupported message - {body && `: ${body}`} - {!body && ' (no body)'} + + Unsupported message + {body && `: ${body}`} + {!body && ' (no body)'} + ) ); @@ -51,11 +63,21 @@ export const MessageNotDecryptedContent = as<'div', { children?: never }>(({ ... // display body of the message if it is available, as it may give some clue about why the message is broken export const MessageBrokenContent = as<'div', { children?: never; body?: string }>( ({ body, ...props }, ref) => ( - + - Broken message - {body && `: ${body}`} - {!body && ' (no body)'} + + Broken message + {body && `: ${body}`} + {!body && ' (no body)'} + ) ); diff --git a/src/app/components/message/content/ImageContent.tsx b/src/app/components/message/content/ImageContent.tsx index d5d9ccc41..13868c4bf 100644 --- a/src/app/components/message/content/ImageContent.tsx +++ b/src/app/components/message/content/ImageContent.tsx @@ -19,13 +19,13 @@ import { TooltipProvider, as, config, + toRem, } from 'folds'; import classNames from 'classnames'; import { BlurhashCanvas } from 'react-blurhash'; import FocusTrap from 'focus-trap-react'; import type { EncryptedAttachmentInfo } from 'browser-encrypt-attachment'; import type { IImageInfo } from '$types/matrix/common'; -import { MATRIX_BLUR_HASH_PROPERTY_NAME } from '$types/matrix/common'; import { AsyncStatus, useAsyncCallback } from '$hooks/useAsyncCallback'; import { useMatrixClient } from '$hooks/useMatrixClient'; import { bytesToSize } from '$utils/common'; @@ -36,6 +36,24 @@ import { useMediaAuthentication } from '$hooks/useMediaAuthentication'; import { ModalWide } from '$styles/Modal.css'; import { validBlurHash } from '$utils/blurHash'; import * as css from './style.css'; +import { MATRIX_UNSTABLE_BLUR_HASH_PROPERTY_NAME } from '../../../../unstable/prefixes'; + +function thumbnailDimsForMaxEdge( + maxEdge: number, + w?: number, + h?: number +): { tw: number; th: number } { + const safeEdge = Math.max(1, Math.round(maxEdge)); + const iw = typeof w === 'number' && Number.isFinite(w) && w > 0 ? w : safeEdge; + const ih = typeof h === 'number' && Number.isFinite(h) && h > 0 ? h : safeEdge; + const longest = Math.max(iw, ih); + if (longest <= safeEdge) return { tw: Math.round(iw), th: Math.round(ih) }; + const scale = safeEdge / longest; + return { + tw: Math.max(1, Math.round(iw * scale)), + th: Math.max(1, Math.round(ih * scale)), + }; +} type RenderViewerProps = { src: string; @@ -62,6 +80,10 @@ export type ImageContentProps = { spoilerReason?: string; renderViewer: (props: RenderViewerProps) => ReactNode; renderImage: (props: RenderImageProps) => ReactNode; + matrixThumbnailMaxEdge?: number; + mediaLayout?: 'default' | 'contained'; + containedStripMinPx?: number; + fillsPreviewSlot?: boolean; }; export const ImageContent = as<'div', ImageContentProps>( ( @@ -78,17 +100,22 @@ export const ImageContent = as<'div', ImageContentProps>( spoilerReason, renderViewer, renderImage, + matrixThumbnailMaxEdge, + mediaLayout = 'default', + containedStripMinPx, + fillsPreviewSlot, ...props }, ref ) => { const mx = useMatrixClient(); const useAuthentication = useMediaAuthentication(); - const blurHash = validBlurHash(info?.[MATRIX_BLUR_HASH_PROPERTY_NAME]); + const blurHash = validBlurHash(info?.[MATRIX_UNSTABLE_BLUR_HASH_PROPERTY_NAME]); const [load, setLoad] = useState(false); const [error, setError] = useState(false); const [viewer, setViewer] = useState(false); + const [viewerFullSrc, setViewerFullSrc] = useState(null); const [blurred, setBlurred] = useState(markedAsSpoiler ?? false); const [isHovered, setIsHovered] = useState(false); @@ -96,6 +123,12 @@ export const ImageContent = as<'div', ImageContentProps>( useCallback(async () => { if (url.startsWith('http')) return url; + if (typeof matrixThumbnailMaxEdge === 'number' && matrixThumbnailMaxEdge > 0 && !encInfo) { + const { tw, th } = thumbnailDimsForMaxEdge(matrixThumbnailMaxEdge, info?.w, info?.h); + const thumbUrl = mxcUrlToHttp(mx, url, useAuthentication, tw, th, 'scale', false); + if (thumbUrl) return thumbUrl; + } + const mediaUrl = mxcUrlToHttp(mx, url, useAuthentication); if (!mediaUrl) throw new Error('Invalid media URL'); if (encInfo) { @@ -105,9 +138,33 @@ export const ImageContent = as<'div', ImageContentProps>( return URL.createObjectURL(fileContent); } return mediaUrl; - }, [mx, url, useAuthentication, mimeType, encInfo]) + }, [mx, url, useAuthentication, mimeType, encInfo, matrixThumbnailMaxEdge, info?.w, info?.h]) ); + useEffect(() => { + if (!viewer) { + setViewerFullSrc(null); + return; + } + if ( + typeof matrixThumbnailMaxEdge !== 'number' || + matrixThumbnailMaxEdge <= 0 || + encInfo || + url.startsWith('http') + ) { + return; + } + let cancelled = false; + void (async () => { + const mediaUrl = mxcUrlToHttp(mx, url, useAuthentication); + if (!mediaUrl || cancelled) return; + setViewerFullSrc(mediaUrl); + })(); + return () => { + cancelled = true; + }; + }, [viewer, matrixThumbnailMaxEdge, encInfo, url, mx, useAuthentication]); + const handleLoad = () => { setLoad(true); }; @@ -126,12 +183,36 @@ export const ImageContent = as<'div', ImageContentProps>( }, [autoPlay, loadSrc]); const hasDimensions = typeof info?.w === 'number' && typeof info?.h === 'number'; + const isContained = mediaLayout === 'contained'; + const fillsSlot = Boolean(fillsPreviewSlot && isContained); + const containedReserveStrip = + !fillsSlot && + isContained && + (srcState.status === AsyncStatus.Loading || + srcState.status === AsyncStatus.Error || + error || + (srcState.status === AsyncStatus.Success && !load)); + + const rootClass = isContained ? css.ContainedMediaRoot : css.RelativeBase; + const stripMin = containedStripMinPx ?? 56; + const intrinsicSizingStyle = fillsSlot + ? {} + : isContained + ? { minHeight: containedReserveStrip ? toRem(stripMin) : undefined } + : hasDimensions + ? { aspectRatio: `${info!.w} / ${info!.h}` } + : { minHeight: '150px' }; + + const fillPreviewSlotStyle = fillsSlot + ? ({ width: '100%', height: '100%' } as const) + : undefined; return ( ( onContextMenu={(evt: React.MouseEvent) => evt.stopPropagation()} > {renderViewer({ - src: srcState.data, + src: viewerFullSrc ?? srcState.data, alt: body, requestClose: () => setViewer(false), })} @@ -196,7 +277,7 @@ export const ImageContent = as<'div', ImageContentProps>( {srcState.status === AsyncStatus.Success && ( ( ) => { const mx = useMatrixClient(); const useAuthentication = useMediaAuthentication(); - const blurHash = validBlurHash(info.thumbnail_info?.[MATRIX_BLUR_HASH_PROPERTY_NAME]); + const blurHash = validBlurHash(info.thumbnail_info?.[MATRIX_UNSTABLE_BLUR_HASH_PROPERTY_NAME]); const [load, setLoad] = useState(false); const [error, setError] = useState(false); diff --git a/src/app/components/message/content/style.css.ts b/src/app/components/message/content/style.css.ts index bb5d8484f..66e2889a6 100644 --- a/src/app/components/message/content/style.css.ts +++ b/src/app/components/message/content/style.css.ts @@ -10,6 +10,15 @@ export const RelativeBase = style([ }, ]); +export const ContainedMediaRoot = style([ + DefaultReset, + { + position: 'relative', + width: '100%', + minHeight: 0, + }, +]); + export const AbsoluteContainer = style([ DefaultReset, { diff --git a/src/app/components/message/layout/Base.tsx b/src/app/components/message/layout/Base.tsx index 47e7b9372..edcf609a7 100644 --- a/src/app/components/message/layout/Base.tsx +++ b/src/app/components/message/layout/Base.tsx @@ -48,6 +48,7 @@ export const MessageTextBody = as<'div', css.MessageTextBodyVariants & { notice? className={classNames(css.MessageTextBody({ preWrap, jumboEmoji, emote }), className)} {...props} ref={ref} + dir="auto" > {children} diff --git a/src/app/components/message/layout/layout.css.ts b/src/app/components/message/layout/layout.css.ts index e30e4c8c3..3d1368d20 100644 --- a/src/app/components/message/layout/layout.css.ts +++ b/src/app/components/message/layout/layout.css.ts @@ -229,6 +229,8 @@ export const PronounPill = style({ export const MessageTextBody = recipe({ base: { + unicodeBidi: 'plaintext', + alignSelf: 'start', wordBreak: 'break-word', fontSize: '1rem !important', // Override folds Text component to enable page zoom scaling }, diff --git a/src/app/components/message/modals/GlobalModalManager.tsx b/src/app/components/message/modals/GlobalModalManager.tsx index d422d6e60..c56c99325 100644 --- a/src/app/components/message/modals/GlobalModalManager.tsx +++ b/src/app/components/message/modals/GlobalModalManager.tsx @@ -14,10 +14,14 @@ import { MessageReadReceiptInternal } from './MessageReadRecipts'; export function GlobalModalManager() { const [modal, setModal] = useAtom(modalAtom); - if (!modal) return null; - const close = () => setModal(null); + if (modal?.type === ModalType.Forward) { + return ; + } + + if (!modal) return null; + return ( }> @@ -42,12 +46,6 @@ export function GlobalModalManager() { )} - {modal.type === ModalType.Forward && ( - - - - )} - {modal.type === ModalType.Source && ( diff --git a/src/app/components/message/modals/MessageForward.tsx b/src/app/components/message/modals/MessageForward.tsx index 94df68049..36de4b1f9 100644 --- a/src/app/components/message/modals/MessageForward.tsx +++ b/src/app/components/message/modals/MessageForward.tsx @@ -2,34 +2,20 @@ import { useMatrixClient } from '$hooks/useMatrixClient'; import { modalAtom, ModalType } from '$state/modal'; -import { - Box, - Button, - Dialog, - Header, - Icon, - Icons, - IconButton, - MenuItem, - Text, - config, - Scroll, - as, -} from 'folds'; +import { Icon, Icons, MenuItem, Text, as } from 'folds'; import { useAtomValue, useSetAtom } from 'jotai'; import type { MatrixEvent, Room } from '$types/matrix-sdk'; -import { JoinRule, EventType } from '$types/matrix-sdk'; -import { useEffect, useMemo, useState } from 'react'; +import { useCallback, useMemo, useState } from 'react'; import { allRoomsAtom } from '$state/room-list/roomList'; import { useAllJoinedRoomsSet, useGetRoom } from '$hooks/useGetRoom'; import { factoryRoomIdByActivity } from '$utils/sort'; import * as css from '$features/room/message/styles.css'; import { sanitizeCustomHtml, sanitizeText } from '$utils/sanitize'; -import { getStateEvents } from '$utils/room'; - import { createDebugLogger } from '$utils/debugLogger'; import * as Sentry from '@sentry/react'; - +import { isRoomPrivate } from '$utils/roomVisibility'; +import * as prefix from '$unstable/prefixes'; +import { RoomSearchModal } from '$features/search'; const debugLog = createDebugLogger('MessageForward'); // Message forwarding component @@ -107,33 +93,8 @@ export function MessageForwardInternal({ }: Readonly) { const mx = useMatrixClient(); - const [isTargetSelected, setIsTargetSelected] = useState(false); - const [isForwardSuccess, setIsForwardSuccess] = useState(false); const [isForwarding, setIsForwarding] = useState(false); const [forwardError, setForwardError] = useState(null); - const [targetRoomId, setTargetRoomId] = useState(null); - - // detect if it's a public room or not - const joinRule = room.getJoinRule() ?? JoinRule.Invite; - - const parentSpaceIds = getStateEvents(room, EventType.SpaceParent) - .map((e) => e.getStateKey()) - .filter((id): id is string => Boolean(id)); - - const isInPublicSpace = parentSpaceIds.some((spaceId) => { - const space = mx.getRoom(spaceId); - return Boolean(space?.isSpaceRoom()) && space?.getJoinRule() === JoinRule.Public; - }); - - // A room is private if its join rule is Invite (or other non-public/non-knock/non-restricted), - // or it's Restricted but NOT inside a public space. - const isPrivate = - joinRule === JoinRule.Invite || - (joinRule === JoinRule.Restricted && !isInPublicSpace) || - (joinRule !== JoinRule.Public && - joinRule !== JoinRule.Knock && - joinRule !== JoinRule.Restricted); - const allRooms = useAtomValue(allRoomsAtom); const allJoinedRooms = useAllJoinedRoomsSet(); const getRoom = useGetRoom(allJoinedRooms); @@ -141,221 +102,164 @@ export function MessageForwardInternal({ const forwardTargets = useMemo( () => allRooms - .filter((id) => id !== room.roomId) .filter((id) => { const target = getRoom(id); return !!target && !target.isSpaceRoom() && target.maySendMessage(); }) .sort(factoryRoomIdByActivity(mx)), - [allRooms, room.roomId, getRoom, mx] + [allRooms, getRoom, mx] ); - useEffect(() => { - if (isForwardSuccess) { - setTimeout(() => { - // close the modal if the message was forwarded successfully - onClose(); - }, 2000); - } - }, [isForwardSuccess, onClose]); + const forwardToRoom = useCallback( + (targetRoomId: string) => { + setIsForwarding(true); + setForwardError(null); - // actually forward the message to the selected room - const handleForwardClick = () => { - setIsForwarding(true); - if (!targetRoomId) { - setIsForwarding(false); - return; - } - - const targetRoom = getRoom(targetRoomId); - const eventId = mEvent.getId(); - if (!targetRoom || !eventId) { - setIsForwarding(false); - return; - } - - type SendEventType = Parameters[2]; - type SendEventContent = Parameters[3]; - - const eventType = mEvent.getType() as SendEventType; - const originalContent = mEvent.getContent(); - const isTextMessage = originalContent.msgtype === 'm.text'; - // using reference relation to indicate that this is a forwarded message, - // which allows clients to display it as such - - const originalBody = typeof originalContent.body === 'string' ? originalContent.body : ''; - const originalFormattedBody = - originalContent.format === 'org.matrix.custom.html' && - typeof originalContent.formatted_body === 'string' - ? originalContent.formatted_body - : undefined; - - const bodyModifText = `(Forwarded message from ${ - isPrivate ? 'a private room' : (getRoom(room.roomId)?.name ?? 'a room') - })`; - - let newBodyPlain = ''; - let newBodyHtml = ''; - // transform if msgtype is m.text - if (isTextMessage) { - const quotedBody = originalBody - .split('\n') - .map((line) => `> ${line}`) - .join('\n'); - - newBodyPlain = originalBody.length > 0 ? `${bodyModifText}\n\n${quotedBody}` : bodyModifText; - - const safeHtml = - originalFormattedBody === undefined - ? sanitizeText(originalBody).replaceAll('\n', '
    ') - : sanitizeCustomHtml(originalFormattedBody); - - newBodyHtml = - `
    ` + - `

    ${sanitizeText(bodyModifText)}

    ` + - `
    ${safeHtml}
    ` + - `
    `; - } - // the quoted body - const forwardedTextContent = isTextMessage - ? { - body: newBodyPlain, - format: 'org.matrix.custom.html', - formatted_body: newBodyHtml, - } - : {}; - const baseContent = { ...mEvent.getContent() }; - delete baseContent['m.relates_to']; // remove relations from the forwarded message - delete baseContent['m.mentions']; // remove mentions from forwarded message - delete baseContent['com.beeper.per_message_profile']; // remove per-message profile as that could confuse clients in the target room - let content; - // handle privacy stuff - if (isPrivate) { - // if the message is from a private room, we should strip any media or mentions to avoid leaking information to the target room - // we can still include the original message content in the body of the message, so we'll just use a fallback text/plain content with the original message body - content = { - ...baseContent, - ...forwardedTextContent, - 'moe.sable.message.forward': { - v: 1, - is_forwarded: true, - original_timestamp: mEvent.getTs(), - original_event_private: true, - } satisfies ForwardMeta, - 'com.famedly.app.forwarded': { - origin_server_ts: mEvent.getTs(), - } satisfies MSC2723ForwardMeta, - }; - } else { - content = { - ...baseContent, - ...forwardedTextContent, - 'moe.sable.message.forward': { - v: 1, - is_forwarded: true, - original_timestamp: mEvent.getTs(), - original_room_id: room.roomId, - original_event_id: eventId, - original_event_private: false, - } satisfies ForwardMeta, - 'com.famedly.app.forwarded': { - event_id: eventId, - room_id: room.roomId, - origin_server_ts: mEvent.getTs(), - } satisfies MSC2723ForwardMeta, - }; - } - - const msgtype = originalContent.msgtype ?? 'unknown'; - debugLog.info('ui', 'Forwarding message', { - sourceRoomId: room.roomId, - targetRoomId: targetRoom.roomId, - msgtype, - isPrivate, - }); - Sentry.metrics.count('sable.message.forward.attempt', 1, { attributes: { msgtype } }); - mx.sendEvent(targetRoom.roomId, null, eventType, content as unknown as SendEventContent) - .then(() => { - debugLog.info('ui', 'Message forwarded successfully', { - sourceRoomId: room.roomId, - targetRoomId: targetRoom.roomId, - }); - Sentry.metrics.count('sable.message.forward.success', 1); - setIsForwardSuccess(true); - }) - .catch((err: unknown) => { - const message = err instanceof Error ? err.message : String(err); - debugLog.error('ui', 'Message forward failed', { - sourceRoomId: room.roomId, - targetRoomId: targetRoom.roomId, - error: message, - }); - Sentry.metrics.count('sable.message.forward.error', 1); + const targetRoom = getRoom(targetRoomId); + const eventId = mEvent.getId(); + if (!targetRoom || !eventId) { setIsForwarding(false); - setIsForwardSuccess(false); - setForwardError(message); - }); - }; + return; + } - return ( - -
    - - Forward Message - - - - -
    - - - - {forwardTargets.map((roomId) => { - const target = getRoom(roomId); - if (!target) return null; - return ( - { - setIsTargetSelected(true); - setTargetRoomId(roomId); - }} - variant={targetRoomId === roomId ? 'Success' : 'Surface'} - aria-pressed={targetRoomId === roomId} - size="400" - radii="400" - > - {target.name} - - ); - })} - - - {isTargetSelected && targetRoomId && ( - - )} - {forwardError && ( - - Failed to forward: {forwardError} - - )} - -
    + type SendEventType = Parameters[2]; + type SendEventContent = Parameters[3]; + + const eventType = mEvent.getType() as SendEventType; + const originalContent = mEvent.getContent(); + const isTextMessage = originalContent.msgtype === 'm.text'; + + const originalBody = typeof originalContent.body === 'string' ? originalContent.body : ''; + const originalFormattedBody = + originalContent.format === 'org.matrix.custom.html' && + typeof originalContent.formatted_body === 'string' + ? originalContent.formatted_body + : undefined; + + const bodyModifText = `(Forwarded message from ${ + isRoomPrivate(mx, room) ? 'a private room' : (getRoom(room.roomId)?.name ?? 'a room') + })`; + + let newBodyPlain = ''; + let newBodyHtml = ''; + // transform if msgtype is m.text + if (isTextMessage) { + const quotedBody = originalBody + .split('\n') + .map((line) => `> ${line}`) + .join('\n'); + + newBodyPlain = + originalBody.length > 0 ? `${bodyModifText}\n\n${quotedBody}` : bodyModifText; + + const safeHtml = + originalFormattedBody === undefined + ? sanitizeText(originalBody).replaceAll('\n', '
    ') + : sanitizeCustomHtml(originalFormattedBody); + + newBodyHtml = + `
    ` + + `

    ${sanitizeText(bodyModifText)}

    ` + + `
    ${safeHtml}
    ` + + `
    `; + } + // the quoted body + const forwardedTextContent = isTextMessage + ? { + body: newBodyPlain, + format: 'org.matrix.custom.html', + formatted_body: newBodyHtml, + } + : {}; + const baseContent = { ...mEvent.getContent() }; + delete baseContent['m.relates_to']; // remove relations from the forwarded message + delete baseContent['m.mentions']; // remove mentions from forwarded message + delete baseContent[prefix.MATRIX_UNSTABLE_PER_MESSAGE_PROFILE_PROPERTY_NAME]; // remove per-message profile as that could confuse clients in the target room + let content; + // handle privacy stuff + if (isRoomPrivate(mx, room)) { + // if the message is from a private room, we should strip any media or mentions to avoid leaking information to the target room + // we can still include the original message content in the body of the message, so we'll just use a fallback text/plain content with the original message body + content = { + ...baseContent, + ...forwardedTextContent, + [prefix.MATRIX_SABLE_UNSTABLE_MESSAGE_FORWARD_META_PROPERTY_NAME]: { + v: 1, + is_forwarded: true, + original_timestamp: mEvent.getTs(), + original_event_private: true, + } satisfies ForwardMeta, + [prefix.MATRIX_UNSTABLE_MESSAGE_FORWARD_META_PROPERTY_NAME]: { + origin_server_ts: mEvent.getTs(), + } satisfies MSC2723ForwardMeta, + }; + } else { + content = { + ...baseContent, + ...forwardedTextContent, + [prefix.MATRIX_SABLE_UNSTABLE_MESSAGE_FORWARD_META_PROPERTY_NAME]: { + v: 1, + is_forwarded: true, + original_timestamp: mEvent.getTs(), + original_room_id: room.roomId, + original_event_id: eventId, + original_event_private: false, + } satisfies ForwardMeta, + [prefix.MATRIX_UNSTABLE_MESSAGE_FORWARD_META_PROPERTY_NAME]: { + event_id: eventId, + room_id: room.roomId, + origin_server_ts: mEvent.getTs(), + } satisfies MSC2723ForwardMeta, + }; + } + + const msgtype = originalContent.msgtype ?? 'unknown'; + debugLog.info('ui', 'Forwarding message', { + sourceRoomId: room.roomId, + targetRoomId: targetRoom.roomId, + msgtype, + isPrivate: isRoomPrivate(mx, room), + }); + Sentry.metrics.count('sable.message.forward.attempt', 1, { attributes: { msgtype } }); + mx.sendEvent(targetRoom.roomId, null, eventType, content as unknown as SendEventContent) + .then(() => { + debugLog.info('ui', 'Message forwarded successfully', { + sourceRoomId: room.roomId, + targetRoomId: targetRoom.roomId, + }); + Sentry.metrics.count('sable.message.forward.success', 1); + setIsForwarding(false); + onClose(); + }) + .catch((err: unknown) => { + const message = err instanceof Error ? err.message : String(err); + debugLog.error('ui', 'Message forward failed', { + sourceRoomId: room.roomId, + targetRoomId: targetRoom.roomId, + error: message, + }); + Sentry.metrics.count('sable.message.forward.error', 1); + setIsForwarding(false); + setForwardError(message); + }); + }, + [getRoom, mEvent, mx, onClose, room] ); + + const pickRoom = useMemo( + () => ({ + title: 'Forward message', + eligibleRoomIds: forwardTargets, + onPickRoom: (roomId: string) => { + forwardToRoom(roomId); + }, + errorMessage: forwardError ? `Failed to forward: ${forwardError}` : null, + busy: isForwarding, + }), + [forwardError, forwardTargets, forwardToRoom, isForwarding] + ); + + return ; } type MessageForwardItemProps = { diff --git a/src/app/components/page/Page.tsx b/src/app/components/page/Page.tsx index c6bb22d44..bafa45903 100644 --- a/src/app/components/page/Page.tsx +++ b/src/app/components/page/Page.tsx @@ -44,12 +44,13 @@ export function PageNav({ size, children }: ClientDrawerLayoutProps & css.PageNa ); } -export const PageNavHeader = as<'header', css.PageNavHeaderVariants>( +type PageNavHeaderOwnProps = Pick, 'size'>; + +export const PageNavHeader = as<'header', css.PageNavHeaderVariants & PageNavHeaderOwnProps>( ({ className, outlined, ...props }, ref) => (
    diff --git a/src/app/components/page/style.css.ts b/src/app/components/page/style.css.ts index d35fa651d..7ca01766a 100644 --- a/src/app/components/page/style.css.ts +++ b/src/app/components/page/style.css.ts @@ -6,6 +6,9 @@ import { DefaultReset, color, config, toRem } from 'folds'; export const PageNav = recipe({ variants: { size: { + '100%': { + width: '100%', + }, '400': { width: toRem(256), }, @@ -15,7 +18,7 @@ export const PageNav = recipe({ }, }, defaultVariants: { - size: '400', + size: '100%', }, }); export type PageNavVariants = RecipeVariants; @@ -43,7 +46,7 @@ export const PageNavHeader = recipe({ variants: { outlined: { true: { - borderBottomWidth: 1, + borderBottomWidth: config.borderWidth.B300, }, }, }, diff --git a/src/app/components/theme/ThemeMigrationBanner.tsx b/src/app/components/theme/ThemeMigrationBanner.tsx new file mode 100644 index 000000000..793e84755 --- /dev/null +++ b/src/app/components/theme/ThemeMigrationBanner.tsx @@ -0,0 +1,163 @@ +import { useCallback, useMemo, useState } from 'react'; +import FocusTrap from 'focus-trap-react'; +import { + Box, + Button, + config, + Dialog, + Header, + Icon, + IconButton, + Icons, + Overlay, + OverlayBackdrop, + OverlayCenter, + Text, +} from 'folds'; +import { useStore } from 'jotai/react'; + +import { useOptionalClientConfig } from '$hooks/useClientConfig'; +import { useSetting } from '$state/hooks/settings'; +import { trimTrailingSlash } from '$utils/common'; +import { defaultSettings, settingsAtom } from '$state/settings'; +import { stopPropagation } from '$utils/keyboard'; + +import { usePatchSettings } from '$features/settings/cosmetics/themeSettingsPatch'; +import { DEFAULT_THEME_CATALOG_BASE } from '../../theme/catalogDefaults'; +import { needsLegacyThemeMigration } from '../../theme/legacyToCatalogMap'; +import { runLegacyThemeMigration } from '../../theme/migrateLegacyThemes'; + +export function ThemeMigrationBanner() { + const store = useStore(); + const [themeMigrationDismissed] = useSetting(settingsAtom, 'themeMigrationDismissed'); + const [themeId] = useSetting(settingsAtom, 'themeId'); + const [lightThemeId] = useSetting(settingsAtom, 'lightThemeId'); + const [darkThemeId] = useSetting(settingsAtom, 'darkThemeId'); + const patchSettings = usePatchSettings(); + const clientConfig = useOptionalClientConfig(); + const [busy, setBusy] = useState(false); + const [error, setError] = useState(null); + + const visible = useMemo( + () => + needsLegacyThemeMigration({ + ...defaultSettings, + themeMigrationDismissed: themeMigrationDismissed ?? false, + themeId, + lightThemeId, + darkThemeId, + }), + [themeMigrationDismissed, themeId, lightThemeId, darkThemeId] + ); + + const catalogBase = trimTrailingSlash( + clientConfig?.themeCatalogBaseUrl?.trim() || DEFAULT_THEME_CATALOG_BASE + ); + + const dismiss = useCallback(() => { + patchSettings({ themeMigrationDismissed: true }); + }, [patchSettings]); + + const dismissSafe = useCallback(() => { + if (busy) return; + dismiss(); + }, [busy, dismiss]); + + const migrate = useCallback(async () => { + setError(null); + setBusy(true); + try { + const current = store.get(settingsAtom); + const result = await runLegacyThemeMigration(current, catalogBase); + if (!result.ok) { + setError(result.error); + return; + } + patchSettings(result.partial); + } finally { + setBusy(false); + } + }, [catalogBase, patchSettings, store]); + + if (!visible) return null; + + return ( + }> + + + +
    + + + Update your theme selection + + + + + +
    + + + Older bundled color themes are no longer included in the app. Migrate to the same + looks from the official catalog (downloaded and cached on this device), or dismiss + this reminder. + + {error && ( + + {error} + + )} + + + + + +
    +
    +
    +
    + ); +} diff --git a/src/app/components/theme/ThemePreviewCard.tsx b/src/app/components/theme/ThemePreviewCard.tsx new file mode 100644 index 000000000..2c6026ae2 --- /dev/null +++ b/src/app/components/theme/ThemePreviewCard.tsx @@ -0,0 +1,304 @@ +import { type ReactNode, useCallback, useMemo } from 'react'; +import { + Box, + Button, + Icon, + IconButton, + Icons, + Text, + Tooltip, + TooltipProvider, + toRem, + config, +} from 'folds'; + +import { useTimeoutToggle } from '$hooks/useTimeoutToggle'; +import { copyToClipboard } from '$utils/dom'; +import { buildPreviewStyleBlock, extractSafePreviewCustomProperties } from '../../theme/previewCss'; + +export type ThemePreviewCardProps = { + title: string; + subtitle?: ReactNode; + beforePreview?: ReactNode; + previewCssText: string; + scopeSlug: string; + copyText?: string; + isFavorited?: boolean; + onToggleFavorite?: () => void | Promise; + + systemTheme: boolean; + onApplyLight?: () => void | Promise; + onApplyDark?: () => void | Promise; + onApplyManual?: () => void | Promise; + isAppliedLight?: boolean; + isAppliedDark?: boolean; + isAppliedManual?: boolean; + + onRevert?: () => void; + canRevert?: boolean; + thirdParty?: boolean; + + onExport?: () => void; +}; + +function safeSlug(input: string): string { + return (input || 'theme').replace(/[^a-zA-Z0-9_-]/g, '-') || 'theme'; +} + +export function ThemePreviewCard({ + title, + subtitle, + beforePreview, + previewCssText, + scopeSlug, + copyText, + isFavorited, + onToggleFavorite, + systemTheme, + onApplyLight, + onApplyDark, + onApplyManual, + isAppliedLight, + isAppliedDark, + isAppliedManual, + onRevert, + canRevert, + thirdParty, + onExport, +}: ThemePreviewCardProps) { + const [copied, setCopied] = useTimeoutToggle(); + + const scopeClass = useMemo(() => `sable-theme-preview--${safeSlug(scopeSlug)}`, [scopeSlug]); + + const styleBlock = useMemo(() => { + const vars = extractSafePreviewCustomProperties(previewCssText); + return buildPreviewStyleBlock(vars, scopeClass); + }, [previewCssText, scopeClass]); + + const handleCopy = useCallback(async () => { + if (!copyText) return; + if (await copyToClipboard(copyText)) setCopied(); + }, [copyText, setCopied]); + + return ( + + + + + {title} + {thirdParty && ( + + + Third-party theme. Only use themes from Providers you trust. + + + } + > + {(triggerRef) => ( + + )} + + )} + + {subtitle && ( + + {subtitle} + + )} + + + + {copyText && ( + { + handleCopy().catch(() => undefined); + }} + > + + + )} + + {onExport && ( + { + onExport(); + }} + > + + + )} + + {typeof isFavorited === 'boolean' && onToggleFavorite && ( + { + Promise.resolve(onToggleFavorite()).catch(() => undefined); + }} + > + + + )} + + + + {beforePreview} + + {styleBlock ? ( + <> + + + + Sample text + + + + Primary + + + Surface + + + + + ) : ( + + No preview tokens + + )} + + + {systemTheme ? ( + <> + {onApplyLight && ( + + )} + {onApplyDark && ( + + )} + + ) : ( + onApplyManual && ( + + ) + )} + + {onRevert && ( + + )} + + + ); +} diff --git a/src/app/components/upload-card/UploadCardRenderer.tsx b/src/app/components/upload-card/UploadCardRenderer.tsx index 24166507e..633babdaa 100644 --- a/src/app/components/upload-card/UploadCardRenderer.tsx +++ b/src/app/components/upload-card/UploadCardRenderer.tsx @@ -31,6 +31,8 @@ import { roomUploadAtomFamily } from '$state/room/roomInputDrafts'; import { useObjectURL } from '$hooks/useObjectURL'; import { useMediaConfig } from '$hooks/useMediaConfig'; import { useSettingsLinkBaseUrl } from '$features/settings/useSettingsLinkBaseUrl'; +import { useSetting } from '$state/hooks/settings'; +import { settingsAtom } from '$state/settings'; import { UploadCard, UploadCardError, UploadCardProgress } from './UploadCard'; import * as css from './UploadCard.css'; import { DescriptionEditor } from './UploadDescriptionEditor'; @@ -397,6 +399,11 @@ export function UploadCardRenderer({ const spoilerClickHandler = useSpoilerClickHandler(); const useAuthentication = useMediaAuthentication(); const settingsLinkBaseUrl = useSettingsLinkBaseUrl(); + const [incomingInlineImagesDefaultHeight] = useSetting( + settingsAtom, + 'incomingInlineImagesDefaultHeight' + ); + const [incomingInlineImagesMaxHeight] = useSetting(settingsAtom, 'incomingInlineImagesMaxHeight'); const htmlReactParserOptions = useMemo( () => getReactCustomHtmlParser(mx, roomId, { @@ -404,8 +411,19 @@ export function UploadCardRenderer({ linkifyOpts, useAuthentication, handleSpoilerClick: spoilerClickHandler, + incomingInlineImagesDefaultHeight, + incomingInlineImagesMaxHeight, }), - [linkifyOpts, mx, roomId, settingsLinkBaseUrl, spoilerClickHandler, useAuthentication] + [ + linkifyOpts, + mx, + roomId, + settingsLinkBaseUrl, + spoilerClickHandler, + useAuthentication, + incomingInlineImagesDefaultHeight, + incomingInlineImagesMaxHeight, + ] ); return ( ) { const editor = useEditor(); const [enterForNewline] = useSetting(settingsAtom, 'enterForNewline'); - const [isMarkdown] = useSetting(settingsAtom, 'isMarkdown'); - const [toolbar, setToolbar] = useState(false); const [autocompleteQuery, setAutocompleteQuery] = useState>(); @@ -56,18 +55,12 @@ export function DescriptionEditor({ const prevValue = useRef(value); const initialized = useRef(false); const handleSave = useCallback(() => { - const plainText = toPlainText(editor.children, isMarkdown).trim(); + const plainText = toPlainText(editor.children).trim(); - const customHtml = trimCustomHtml( - toMatrixCustomHTML(editor.children, { - allowTextFormatting: true, - allowBlockMarkdown: isMarkdown, - allowInlineMarkdown: isMarkdown, - }) - ); + const customHtml = trimCustomHtml(toMatrixCustomHTML(editor.children, {})); onSave(plainText, customHtml || plainText); - }, [editor, isMarkdown, onSave]); + }, [editor, onSave]); useEffect(() => { const valueChanged = prevValue.current !== value; @@ -88,17 +81,16 @@ export function DescriptionEditor({ const safeValue = typeof normalizedValue === 'string' ? normalizedValue : ''; const incomingPlainText = toPlainText( - htmlToEditorInput(safeValue, isMarkdown), - isMarkdown + plainToEditorInput(safeValue.includes('<') ? htmlToMarkdown(safeValue) : safeValue) ).trim(); - const currentPlainText = toPlainText(editor.children, isMarkdown).trim(); + const currentPlainText = toPlainText(editor.children).trim(); if (currentPlainText === incomingPlainText && initialized.current) return; const isLikelyHtml = safeValue.includes('<') || safeValue.includes('>'); const initialValue = isLikelyHtml - ? htmlToEditorInput(safeValue, isMarkdown) - : plainToEditorInput(safeValue, isMarkdown); + ? plainToEditorInput(htmlToMarkdown(safeValue)) + : plainToEditorInput(safeValue); editor.children = initialValue; Editor.normalize(editor, { force: true }); @@ -106,7 +98,7 @@ export function DescriptionEditor({ initialized.current = true; } - }, [value, editor, isMarkdown]); + }, [value, editor]); const handleKeyDown: KeyboardEventHandler = useCallback( (evt) => { @@ -168,6 +160,7 @@ export function DescriptionEditor({ variant="Background" bottom={ + - setToolbar(!toolbar)} - > - - + {(anchor: RectCords | undefined, setAnchor) => ( - {toolbar && ( - - - - - )} } /> diff --git a/src/app/components/url-preview/ClientPreview.tsx b/src/app/components/url-preview/ClientPreview.tsx index cea5b3c6f..61809f187 100644 --- a/src/app/components/url-preview/ClientPreview.tsx +++ b/src/app/components/url-preview/ClientPreview.tsx @@ -5,11 +5,11 @@ import { AsyncStatus, useAsyncCallback } from '$hooks/useAsyncCallback'; import { useSetting } from '$state/hooks/settings'; import { settingsAtom } from '$state/settings'; import { encodeBlurHash } from '$utils/blurHash'; -import { MATRIX_BLUR_HASH_PROPERTY_NAME } from '$types/matrix/common'; import { Attachment, AttachmentBox, AttachmentHeader } from '../message/attachment'; import { Image } from '../media'; import { UrlPreview } from './UrlPreview'; import { VideoContent } from '../message'; +import { MATRIX_UNSTABLE_BLUR_HASH_PROPERTY_NAME } from '../../../unstable/prefixes'; interface OEmbed { type: 'photo' | 'video' | 'link' | 'rich'; @@ -114,7 +114,7 @@ export const YoutubeElement = as<'div', YoutubeElementProps>(({ videoInfo, embed mimeType="fake" url={videoUrl} info={{ - thumbnail_info: { [MATRIX_BLUR_HASH_PROPERTY_NAME]: blurHash }, + thumbnail_info: { [MATRIX_UNSTABLE_BLUR_HASH_PROPERTY_NAME]: blurHash }, }} renderThumbnail={() => ( void; +}; + +export function SableChatPreviewPlaceholder({ + kind, + url, + hostLabel, + isApprovedHost, + onLoadPreview, +}: SableChatPreviewPlaceholderProps) { + const title = kind === 'theme' ? 'Theme preview' : 'Tweak preview'; + const bodyApproved = + kind === 'theme' + ? 'This message links to a catalog theme preview. Nothing is fetched until you load it.' + : 'This message links to a catalog tweak. Nothing is fetched until you load it.'; + const bodyThirdParty = + kind === 'theme' + ? 'This message links to third-party theme CSS. Nothing is fetched until you confirm. Only load previews you trust.' + : 'This message links to third-party tweak CSS. Nothing is fetched until you confirm. Only load previews you trust.'; + + return ( + + + {title} + {!isApprovedHost ? : null} + + {isApprovedHost ? bodyApproved : bodyThirdParty} + + + {isApprovedHost ? 'Official catalog' : hostLabel} + + + {url} + + + + + ); +} diff --git a/src/app/components/url-preview/ThemePreviewUrlCard.tsx b/src/app/components/url-preview/ThemePreviewUrlCard.tsx new file mode 100644 index 000000000..047f18333 --- /dev/null +++ b/src/app/components/url-preview/ThemePreviewUrlCard.tsx @@ -0,0 +1,485 @@ +import { useCallback, useEffect, useMemo, useRef, useState } from 'react'; +import { useQuery } from '@tanstack/react-query'; +import { Box, Text } from 'folds'; +import { useStore } from 'jotai/react'; + +import { useClientConfig } from '$hooks/useClientConfig'; +import { ThemeKind } from '$hooks/useTheme'; +import { usePatchSettings } from '$features/settings/cosmetics/themeSettingsPatch'; +import { useSetting } from '$state/hooks/settings'; +import { settingsAtom, type Settings, type ThemeRemoteFavorite } from '$state/settings'; +import { + extractFullThemeUrlFromPreview, + parseSableThemeMetadata, + type SableThemeContrast, +} from '../../theme/metadata'; +import { putCachedThemeCss } from '../../theme/cache'; +import { fullUrlFromPreviewUrl } from '../../theme/previewUrls'; +import { isApprovedCatalogHostUrl } from '../../theme/themeApproval'; +import { ThemePreviewCard } from '../theme/ThemePreviewCard'; +import { SableChatPreviewPlaceholder } from './SableChatPreviewPlaceholder'; +import { ThemeThirdPartyBanner } from './ThemeThirdPartyBanner'; + +function isHttps(url: string): boolean { + return /^https:\/\//i.test(url); +} + +function isPreviewThemeUrl(url: string): boolean { + return /\.preview\.sable\.css(\?|#|$)/i.test(url); +} + +function basenameFromUrl(url: string): string { + const tail = url.split('/').pop() ?? url; + return tail.replace(/\.preview\.sable\.css(\?|#|$)/i, '').replace(/\.sable\.css(\?|#|$)/i, ''); +} + +function baseLabel(url: string): string { + try { + const u = new URL(url); + return u.hostname; + } catch { + return 'Unofficial theme'; + } +} + +export function ThemePreviewUrlCard({ url }: { url: string }) { + const clientConfig = useClientConfig(); + const store = useStore(); + const patchSettings = usePatchSettings(); + const mountedRef = useRef(true); + + useEffect(() => { + mountedRef.current = true; + return () => { + mountedRef.current = false; + }; + }, []); + + const [autoPreviewApproved] = useSetting(settingsAtom, 'themeChatAutoPreviewApprovedUrls'); + const [autoPreviewAny] = useSetting(settingsAtom, 'themeChatAutoPreviewAnyUrl'); + const [favorites] = useSetting(settingsAtom, 'themeRemoteFavorites'); + const [systemTheme] = useSetting(settingsAtom, 'useSystemTheme'); + const [manualRemoteFullUrl] = useSetting(settingsAtom, 'themeRemoteManualFullUrl'); + const [lightRemoteFullUrl] = useSetting(settingsAtom, 'themeRemoteLightFullUrl'); + const [darkRemoteFullUrl] = useSetting(settingsAtom, 'themeRemoteDarkFullUrl'); + + const isEligibleUrl = useMemo(() => isHttps(url) && isPreviewThemeUrl(url), [url]); + + const prefixes = clientConfig.themeCatalogApprovedHostPrefixes; + + const isOfficial = useMemo(() => isApprovedCatalogHostUrl(url, prefixes), [prefixes, url]); + + const shouldAutoFetch = useMemo( + () => (isOfficial && autoPreviewApproved) || (!isOfficial && autoPreviewAny), + [isOfficial, autoPreviewApproved, autoPreviewAny] + ); + + const [userTriggeredLoad, setUserTriggeredLoad] = useState(false); + + useEffect(() => { + setUserTriggeredLoad(false); + }, [url]); + + const fetchEnabled = useMemo( + () => isEligibleUrl && (shouldAutoFetch || userTriggeredLoad), + [isEligibleUrl, shouldAutoFetch, userTriggeredLoad] + ); + + const showThirdPartyBanner = useMemo( + () => !isApprovedCatalogHostUrl(url, prefixes), + [prefixes, url] + ); + + const previewQuery = useQuery({ + queryKey: ['theme-preview-embed', url], + enabled: fetchEnabled, + staleTime: 10 * 60_000, + queryFn: async () => { + const res = await fetch(url, { mode: 'cors' }); + if (!res.ok) throw new Error(`theme preview fetch failed: ${res.status}`); + const previewText = await res.text(); + const meta = parseSableThemeMetadata(previewText); + const fullFromMeta = extractFullThemeUrlFromPreview(previewText); + const fullUrl = fullUrlFromPreviewUrl(url, fullFromMeta); + const kind = meta.kind ?? ThemeKind.Light; + const displayName = meta.name?.trim() || basenameFromUrl(url); + const author = meta.author?.trim() || undefined; + const contrast: SableThemeContrast = meta.contrast === 'high' ? 'high' : 'low'; + const tags = meta.tags ?? []; + return { previewText, fullUrl, kind, displayName, author, contrast, tags }; + }, + }); + + const revertRef = useRef | null>(null); + const lastAutoSavedUrlRef = useRef(null); + const [canRevert, setCanRevert] = useState(false); + const [favoriteTouched, setFavoriteTouched] = useState(false); + const [favoriteError, setFavoriteError] = useState(null); + + const appliedHere = useMemo(() => { + const u = previewQuery.data?.fullUrl; + if (!u) return false; + if (systemTheme) { + return lightRemoteFullUrl === u || darkRemoteFullUrl === u; + } + return manualRemoteFullUrl === u; + }, [ + previewQuery.data?.fullUrl, + systemTheme, + lightRemoteFullUrl, + darkRemoteFullUrl, + manualRemoteFullUrl, + ]); + + const canRevertUi = useMemo(() => canRevert || appliedHere, [canRevert, appliedHere]); + + const isFav = useMemo( + () => favorites.some((f) => f.fullUrl === previewQuery.data?.fullUrl), + [favorites, previewQuery.data?.fullUrl] + ); + + const pruneFavorites = useCallback( + (nextFavorites: ThemeRemoteFavorite[], nextActive: string[]) => { + const active = new Set(nextActive); + return nextFavorites.filter((f) => f.pinned === true || active.has(f.fullUrl)); + }, + [] + ); + + const toggleFavorite = useCallback(async () => { + const fullUrl = previewQuery.data?.fullUrl; + if (!fullUrl) return; + + setFavoriteError(null); + + const existing = favorites.find((f) => f.fullUrl === fullUrl); + if (existing) { + setFavoriteTouched(false); + const cleared: Partial = {}; + if (lightRemoteFullUrl === fullUrl) { + cleared.themeRemoteLightFullUrl = undefined; + cleared.themeRemoteLightKind = undefined; + } + if (darkRemoteFullUrl === fullUrl) { + cleared.themeRemoteDarkFullUrl = undefined; + cleared.themeRemoteDarkKind = undefined; + } + if (manualRemoteFullUrl === fullUrl) { + cleared.themeRemoteManualFullUrl = undefined; + cleared.themeRemoteManualKind = undefined; + } + + const nextFavs = favorites.filter((f) => f.fullUrl !== fullUrl); + const nextActive = [manualRemoteFullUrl, lightRemoteFullUrl, darkRemoteFullUrl] + .filter((u): u is string => Boolean(u && u.trim().length > 0)) + .filter((u) => u !== fullUrl); + patchSettings({ ...cleared, themeRemoteFavorites: pruneFavorites(nextFavs, nextActive) }); + return; + } + + setFavoriteTouched(true); + const res = await fetch(fullUrl, { mode: 'cors' }); + if (!mountedRef.current) return; + if (!res.ok) { + setFavoriteError(`Theme CSS not found (${res.status})`); + return; + } + const cssText = await res.text(); + if (!mountedRef.current) return; + await putCachedThemeCss(fullUrl, cssText); + if (!mountedRef.current) return; + + const next: ThemeRemoteFavorite = { + fullUrl, + displayName: previewQuery.data?.displayName ?? basenameFromUrl(fullUrl), + basename: basenameFromUrl(fullUrl), + kind: previewQuery.data?.kind === ThemeKind.Dark ? 'dark' : 'light', + pinned: true, + }; + + patchSettings({ themeRemoteFavorites: [...favorites, next] }); + }, [ + darkRemoteFullUrl, + favorites, + lightRemoteFullUrl, + manualRemoteFullUrl, + patchSettings, + previewQuery.data, + pruneFavorites, + ]); + + const applyManual = useCallback(() => { + const fullUrl = previewQuery.data?.fullUrl; + if (!fullUrl) return; + const kind = previewQuery.data?.kind === ThemeKind.Dark ? 'dark' : 'light'; + patchSettings({ themeRemoteManualFullUrl: fullUrl, themeRemoteManualKind: kind }); + }, [patchSettings, previewQuery.data]); + + const applyLightSlot = useCallback(() => { + const fullUrl = previewQuery.data?.fullUrl; + if (!fullUrl) return; + const kind = previewQuery.data?.kind === ThemeKind.Dark ? 'dark' : 'light'; + patchSettings({ themeRemoteLightFullUrl: fullUrl, themeRemoteLightKind: kind }); + }, [patchSettings, previewQuery.data]); + + const applyDarkSlot = useCallback(() => { + const fullUrl = previewQuery.data?.fullUrl; + if (!fullUrl) return; + const kind = previewQuery.data?.kind === ThemeKind.Dark ? 'dark' : 'light'; + patchSettings({ themeRemoteDarkFullUrl: fullUrl, themeRemoteDarkKind: kind }); + }, [patchSettings, previewQuery.data]); + + const ensureFavorited = useCallback(async (): Promise => { + const fullUrl = previewQuery.data?.fullUrl; + if (!fullUrl) return false; + if (favorites.some((f) => f.fullUrl === fullUrl)) return false; + + const res = await fetch(fullUrl, { mode: 'cors' }); + if (!mountedRef.current) return false; + if (!res.ok) return false; + const cssText = await res.text(); + if (!mountedRef.current) return false; + await putCachedThemeCss(fullUrl, cssText); + if (!mountedRef.current) return false; + + const next: ThemeRemoteFavorite = { + fullUrl, + displayName: previewQuery.data!.displayName, + basename: basenameFromUrl(fullUrl), + kind: previewQuery.data!.kind === ThemeKind.Dark ? 'dark' : 'light', + pinned: false, + }; + + patchSettings({ themeRemoteFavorites: [...favorites, next] }); + return true; + }, [favorites, patchSettings, previewQuery.data]); + + const snapshotAnd = useCallback( + async (fn: () => void, nextApplied: Partial) => { + const current = store.get(settingsAtom); + if ( + nextApplied.themeRemoteManualFullUrl && + current.themeRemoteManualFullUrl === nextApplied.themeRemoteManualFullUrl + ) { + return; + } + if ( + nextApplied.themeRemoteLightFullUrl && + current.themeRemoteLightFullUrl === nextApplied.themeRemoteLightFullUrl + ) { + return; + } + if ( + nextApplied.themeRemoteDarkFullUrl && + current.themeRemoteDarkFullUrl === nextApplied.themeRemoteDarkFullUrl + ) { + return; + } + revertRef.current = { + themeId: current.themeId, + themeRemoteManualFullUrl: current.themeRemoteManualFullUrl, + themeRemoteManualKind: current.themeRemoteManualKind, + themeRemoteLightFullUrl: current.themeRemoteLightFullUrl, + themeRemoteLightKind: current.themeRemoteLightKind, + themeRemoteDarkFullUrl: current.themeRemoteDarkFullUrl, + themeRemoteDarkKind: current.themeRemoteDarkKind, + } satisfies Partial; + setCanRevert(true); + + if (!favoriteTouched) { + const added = await ensureFavorited(); + if (!mountedRef.current) return; + lastAutoSavedUrlRef.current = added ? (previewQuery.data?.fullUrl ?? null) : null; + } else { + lastAutoSavedUrlRef.current = null; + } + + fn(); + if (!mountedRef.current) return; + + const nextActive = [ + nextApplied.themeRemoteManualFullUrl ?? manualRemoteFullUrl, + nextApplied.themeRemoteLightFullUrl ?? lightRemoteFullUrl, + nextApplied.themeRemoteDarkFullUrl ?? darkRemoteFullUrl, + ].filter((u): u is string => Boolean(u && u.trim().length > 0)); + + patchSettings({ + themeRemoteFavorites: pruneFavorites( + store.get(settingsAtom).themeRemoteFavorites, + nextActive + ), + }); + }, + [ + ensureFavorited, + favoriteTouched, + lightRemoteFullUrl, + darkRemoteFullUrl, + manualRemoteFullUrl, + patchSettings, + previewQuery.data?.fullUrl, + pruneFavorites, + store, + ] + ); + + const revert = useCallback(() => { + const syncFavoritesAfterRevert = (removeAutoSavedFullUrl: string | null) => { + const after = store.get(settingsAtom); + let favs = after.themeRemoteFavorites; + if (removeAutoSavedFullUrl) { + favs = favs.filter((f) => f.fullUrl !== removeAutoSavedFullUrl); + } + const nextActive = [ + after.themeRemoteManualFullUrl, + after.themeRemoteLightFullUrl, + after.themeRemoteDarkFullUrl, + ].filter((u): u is string => Boolean(u && u.trim().length > 0)); + patchSettings({ + themeRemoteFavorites: pruneFavorites(favs, nextActive), + }); + }; + + const snap = revertRef.current; + if (snap) { + patchSettings(snap); + syncFavoritesAfterRevert(lastAutoSavedUrlRef.current); + + revertRef.current = null; + lastAutoSavedUrlRef.current = null; + setCanRevert(false); + return; + } + + const u = previewQuery.data?.fullUrl; + if (!u) return; + const partial: Partial = {}; + if (lightRemoteFullUrl === u) { + partial.themeRemoteLightFullUrl = undefined; + partial.themeRemoteLightKind = undefined; + } + if (darkRemoteFullUrl === u) { + partial.themeRemoteDarkFullUrl = undefined; + partial.themeRemoteDarkKind = undefined; + } + if (manualRemoteFullUrl === u) { + partial.themeRemoteManualFullUrl = undefined; + partial.themeRemoteManualKind = undefined; + partial.themeId = previewQuery.data?.kind === ThemeKind.Dark ? 'dark-theme' : 'light-theme'; + } + if (Object.keys(partial).length === 0) return; + patchSettings(partial); + syncFavoritesAfterRevert(null); + }, [ + darkRemoteFullUrl, + lightRemoteFullUrl, + manualRemoteFullUrl, + patchSettings, + previewQuery.data?.fullUrl, + previewQuery.data?.kind, + pruneFavorites, + store, + ]); + + if (!isEligibleUrl) return null; + + if (!shouldAutoFetch && !userTriggeredLoad) { + return ( + { + setUserTriggeredLoad(true); + }} + /> + ); + } + + const title = previewQuery.data?.displayName ?? 'Theme preview'; + let kindLabel = 'Theme'; + if (previewQuery.data?.kind === ThemeKind.Dark) kindLabel = 'Dark'; + else if (previewQuery.data?.kind === ThemeKind.Light) kindLabel = 'Light'; + const contrastLabel = previewQuery.data?.contrast ? `${previewQuery.data.contrast} contrast` : ''; + const authorLabel = previewQuery.data?.author ? `by ${previewQuery.data.author}` : ''; + const tagsLabel = + previewQuery.data?.tags && previewQuery.data.tags.length > 0 + ? previewQuery.data.tags.join(', ') + : ''; + const sourceLabel = isOfficial ? 'Official theme' : baseLabel(url); + const subtitleLine1 = [kindLabel, contrastLabel].filter(Boolean).join(' · '); + const subtitleLine2 = [authorLabel, tagsLabel].filter(Boolean).join(' · '); + const subtitleLine3 = sourceLabel; + const subtitle = ( + <> + {subtitleLine1} + {subtitleLine2 ? ( + <> +
    + {subtitleLine2} + + ) : null} +
    + {subtitleLine3} + + ); + const fullUrl = previewQuery.data?.fullUrl; + + return ( + + : undefined + } + previewCssText={previewQuery.data?.previewText ?? ''} + scopeSlug={`chat-${basenameFromUrl(url)}`} + copyText={url} + isFavorited={fullUrl ? isFav : false} + onToggleFavorite={fullUrl ? () => toggleFavorite() : undefined} + systemTheme={systemTheme} + onApplyLight={ + systemTheme && fullUrl + ? () => snapshotAnd(() => applyLightSlot(), { themeRemoteLightFullUrl: fullUrl }) + : undefined + } + onApplyDark={ + systemTheme && fullUrl + ? () => snapshotAnd(() => applyDarkSlot(), { themeRemoteDarkFullUrl: fullUrl }) + : undefined + } + onApplyManual={ + !systemTheme && fullUrl + ? () => snapshotAnd(() => applyManual(), { themeRemoteManualFullUrl: fullUrl }) + : undefined + } + isAppliedLight={fullUrl ? lightRemoteFullUrl === fullUrl : false} + isAppliedDark={fullUrl ? darkRemoteFullUrl === fullUrl : false} + isAppliedManual={fullUrl ? manualRemoteFullUrl === fullUrl : false} + canRevert={canRevertUi} + onRevert={revert} + /> + {previewQuery.isPending && ( + + Loading preview… + + )} + {favoriteError && ( + + {favoriteError} + + )} + + ); +} diff --git a/src/app/components/url-preview/ThemeThirdPartyBanner.tsx b/src/app/components/url-preview/ThemeThirdPartyBanner.tsx new file mode 100644 index 000000000..ca31d8008 --- /dev/null +++ b/src/app/components/url-preview/ThemeThirdPartyBanner.tsx @@ -0,0 +1,41 @@ +import { Box, Icon, Icons, Text, toRem, config } from 'folds'; + +type ThemeThirdPartyBannerProps = { + hostLabel: string; + /** Default `theme` for backward compatibility. */ + kind?: 'theme' | 'tweak'; +}; + +export function ThemeThirdPartyBanner({ hostLabel, kind = 'theme' }: ThemeThirdPartyBannerProps) { + const title = kind === 'tweak' ? 'Third-party tweak' : 'Third-party theme'; + const body = + kind === 'tweak' + ? `This tweak is hosted on ${hostLabel}, outside the Sable catalog allowlist. Saving or enabling applies CSS from that host. Only use tweaks from providers you trust.` + : `This preview is hosted on ${hostLabel}, outside the Sable catalog allowlist. Saving or applying installs full theme CSS from that host. Only use themes from providers you trust.`; + + return ( + + + + + + {title} + + + {body} + + + + + ); +} diff --git a/src/app/components/url-preview/TweakPreviewUrlCard.tsx b/src/app/components/url-preview/TweakPreviewUrlCard.tsx new file mode 100644 index 000000000..c3c632745 --- /dev/null +++ b/src/app/components/url-preview/TweakPreviewUrlCard.tsx @@ -0,0 +1,403 @@ +import { useCallback, useEffect, useMemo, useRef, useState } from 'react'; +import { useQuery } from '@tanstack/react-query'; +import { + Box, + Icon, + IconButton, + Icons, + Spinner, + Switch, + Text, + Tooltip, + TooltipProvider, + config, + toRem, +} from 'folds'; + +import { useClientConfig } from '$hooks/useClientConfig'; +import { useTimeoutToggle } from '$hooks/useTimeoutToggle'; +import { usePatchSettings } from '$features/settings/cosmetics/themeSettingsPatch'; +import { useSetting } from '$state/hooks/settings'; +import { settingsAtom, type ThemeRemoteTweakFavorite } from '$state/settings'; +import { copyToClipboard } from '$utils/dom'; +import { putCachedThemeCss } from '../../theme/cache'; +import { getSableCssPackageKind, parseSableTweakMetadata } from '../../theme/metadata'; +import { isHttpsFullSableCssUrl } from '../../theme/previewUrls'; +import { buildPreviewStyleBlock, extractSafePreviewCustomProperties } from '../../theme/previewCss'; +import { isApprovedCatalogHostUrl, isThirdPartyThemeUrl } from '../../theme/themeApproval'; +import { SableChatPreviewPlaceholder } from './SableChatPreviewPlaceholder'; +import { ThemeThirdPartyBanner } from './ThemeThirdPartyBanner'; + +function baseLabel(url: string): string { + try { + return new URL(url).hostname; + } catch { + return 'Unofficial tweak'; + } +} + +function basenameFromFullSableUrl(url: string): string { + const tail = url.split('/').pop() ?? url; + return tail.replace(/\.sable\.css(\?.*)?$/i, '') || 'tweak'; +} + +function pruneTweakFavorites( + nextFavorites: ThemeRemoteTweakFavorite[], + nextEnabledUrls: string[] +): ThemeRemoteTweakFavorite[] { + const enabled = new Set(nextEnabledUrls); + return nextFavorites.filter((f) => f.pinned === true || enabled.has(f.fullUrl)); +} + +function safeSlug(input: string): string { + return (input || 'tweak').replace(/[^a-zA-Z0-9_-]/g, '-') || 'tweak'; +} + +type TweakPreviewData = { + cssText: string; + displayName: string; + description?: string; + author?: string; + tags: string[]; + basename: string; +}; + +export function TweakPreviewUrlCard({ url }: { url: string }) { + const clientConfig = useClientConfig(); + const patchSettings = usePatchSettings(); + const mountedRef = useRef(true); + + useEffect(() => { + mountedRef.current = true; + return () => { + mountedRef.current = false; + }; + }, []); + + const [autoPreviewApproved] = useSetting(settingsAtom, 'themeChatAutoPreviewApprovedUrls'); + const [autoPreviewAny] = useSetting(settingsAtom, 'themeChatAutoPreviewAnyUrl'); + const [tweakFavorites] = useSetting(settingsAtom, 'themeRemoteTweakFavorites'); + const [enabledTweakFullUrls] = useSetting(settingsAtom, 'themeRemoteEnabledTweakFullUrls'); + + const [copied, setCopied] = useTimeoutToggle(); + + const isEligibleUrl = useMemo(() => isHttpsFullSableCssUrl(url), [url]); + + const prefixes = clientConfig.themeCatalogApprovedHostPrefixes; + + const isOfficial = useMemo(() => isApprovedCatalogHostUrl(url, prefixes), [prefixes, url]); + + const shouldAutoFetch = useMemo( + () => (isOfficial && autoPreviewApproved) || (!isOfficial && autoPreviewAny), + [isOfficial, autoPreviewApproved, autoPreviewAny] + ); + + const [userTriggeredLoad, setUserTriggeredLoad] = useState(false); + + useEffect(() => { + setUserTriggeredLoad(false); + }, [url]); + + const fetchEnabled = useMemo( + () => isEligibleUrl && (shouldAutoFetch || userTriggeredLoad), + [isEligibleUrl, shouldAutoFetch, userTriggeredLoad] + ); + + const showThirdPartyBanner = useMemo( + () => !isApprovedCatalogHostUrl(url, prefixes), + [prefixes, url] + ); + + const tweakPreviewQuery = useQuery({ + queryKey: ['tweak-preview-embed', url], + enabled: fetchEnabled, + staleTime: 10 * 60_000, + queryFn: async (): Promise => { + const res = await fetch(url, { mode: 'cors' }); + if (!res.ok) throw new Error(`tweak fetch failed: ${res.status}`); + const cssText = await res.text(); + if (getSableCssPackageKind(cssText) !== 'tweak') return null; + const meta = parseSableTweakMetadata(cssText); + const basename = meta.id?.trim() || basenameFromFullSableUrl(url); + return { + cssText, + displayName: meta.name?.trim() || basenameFromFullSableUrl(url), + description: meta.description?.trim() || undefined, + author: meta.author?.trim() || undefined, + tags: meta.tags ?? [], + basename, + }; + }, + }); + + const { data } = tweakPreviewQuery; + + const scopeClass = useMemo(() => `sable-tweak-preview--${safeSlug(url)}`, [url]); + + const styleBlock = useMemo(() => { + if (!data?.cssText) return ''; + const vars = extractSafePreviewCustomProperties(data.cssText); + return buildPreviewStyleBlock(vars, scopeClass); + }, [data?.cssText, scopeClass]); + + const handleCopy = useCallback(async () => { + if (await copyToClipboard(url)) setCopied(); + }, [setCopied, url]); + + const toggleFavorite = useCallback(async () => { + if (!data) return; + const existing = tweakFavorites.find((f) => f.fullUrl === url); + if (existing) { + const nextFavs = tweakFavorites.filter((f) => f.fullUrl !== url); + const nextEnabled = enabledTweakFullUrls.filter((u) => u !== url); + patchSettings({ + themeRemoteTweakFavorites: pruneTweakFavorites(nextFavs, nextEnabled), + themeRemoteEnabledTweakFullUrls: nextEnabled, + }); + return; + } + await putCachedThemeCss(url, data.cssText); + if (!mountedRef.current) return; + const next: ThemeRemoteTweakFavorite = { + fullUrl: url, + displayName: data.displayName, + basename: data.basename, + pinned: true, + }; + patchSettings({ + themeRemoteTweakFavorites: pruneTweakFavorites( + [...tweakFavorites, next], + enabledTweakFullUrls + ), + }); + }, [data, enabledTweakFullUrls, patchSettings, tweakFavorites, url]); + + const setTweakEnabled = useCallback( + async (apply: boolean) => { + if (!data) return; + if (apply) { + await putCachedThemeCss(url, data.cssText); + if (!mountedRef.current) return; + const nextEnabled = enabledTweakFullUrls.includes(url) + ? [...enabledTweakFullUrls] + : [...enabledTweakFullUrls, url]; + const nextFavs = [...tweakFavorites]; + if (!nextFavs.some((f) => f.fullUrl === url)) { + nextFavs.push({ + fullUrl: url, + displayName: data.displayName, + basename: data.basename, + pinned: false, + }); + } + patchSettings({ + themeRemoteEnabledTweakFullUrls: nextEnabled, + themeRemoteTweakFavorites: pruneTweakFavorites(nextFavs, nextEnabled), + }); + } else { + const nextEnabled = enabledTweakFullUrls.filter((u) => u !== url); + patchSettings({ + themeRemoteEnabledTweakFullUrls: nextEnabled, + }); + } + }, + [data, enabledTweakFullUrls, patchSettings, tweakFavorites, url] + ); + + if (!isEligibleUrl) return null; + + if (!shouldAutoFetch && !userTriggeredLoad) { + return ( + { + setUserTriggeredLoad(true); + }} + /> + ); + } + + if (tweakPreviewQuery.isPending) { + return ( + + + + Loading tweak… + + + ); + } + + if (tweakPreviewQuery.isError || data === null || data === undefined) { + return null; + } + + const isFav = tweakFavorites.some((f) => f.fullUrl === url); + const isOn = enabledTweakFullUrls.includes(url); + const thirdPartyIcon = isThirdPartyThemeUrl(url, clientConfig.themeCatalogApprovedHostPrefixes); + + const descParts = [ + data.description, + data.author ? `by ${data.author}` : '', + data.tags.length > 0 ? data.tags.join(', ') : '', + ].filter(Boolean); + const descLine = descParts.join(' · '); + const sourceLabel = isOfficial ? 'Official catalog' : baseLabel(url); + + return ( + + + + + {data.displayName} + {thirdPartyIcon && ( + + Third-party tweak. Only enable CSS you trust. + + } + > + {(triggerRef) => ( + + )} + + )} + + {descLine ? ( + + {descLine} + + ) : null} + + {sourceLabel} + + + + + { + handleCopy().catch(() => undefined); + }} + > + + + { + toggleFavorite().catch(() => undefined); + }} + > + + + { + setTweakEnabled(v).catch(() => undefined); + }} + /> + + + + {showThirdPartyBanner ? ( + + ) : undefined} + + {styleBlock ? ( + <> + + + + Sample text + + + + Primary + + + Surface + + + + + ) : null} + + ); +} diff --git a/src/app/components/url-preview/UrlPreview.css.tsx b/src/app/components/url-preview/UrlPreview.css.tsx index 90adc127d..cae942dfa 100644 --- a/src/app/components/url-preview/UrlPreview.css.tsx +++ b/src/app/components/url-preview/UrlPreview.css.tsx @@ -25,6 +25,13 @@ export const UrlPreviewImg = style([ }, ]); +export const UrlPreviewMediaWell = style([ + DefaultReset, + { + backgroundColor: color.Surface.Container, + }, +]); + export const UrlPreviewContent = style([ DefaultReset, { diff --git a/src/app/components/url-preview/UrlPreviewCard.tsx b/src/app/components/url-preview/UrlPreviewCard.tsx index e927c0713..34383df76 100644 --- a/src/app/components/url-preview/UrlPreviewCard.tsx +++ b/src/app/components/url-preview/UrlPreviewCard.tsx @@ -1,17 +1,34 @@ import { useCallback, useEffect, useRef, useState } from 'react'; import type { MatrixClient } from '$types/matrix-sdk'; import type { IPreviewUrlResponse } from '$types/matrix-sdk'; -import { Box, Icon, IconButton, Icons, Scroll, Spinner, Text, as, color, config } from 'folds'; +import { + Box, + Icon, + IconButton, + Icons, + Scroll, + Spinner, + Text, + as, + color, + config, + toRem, +} from 'folds'; import { AsyncStatus, useAsyncCallback } from '$hooks/useAsyncCallback'; import { useMatrixClient } from '$hooks/useMatrixClient'; import { mxcUrlToHttp, downloadMedia } from '$utils/matrix'; import { useMediaAuthentication } from '$hooks/useMediaAuthentication'; import { safeDecodeUrl } from '$plugins/react-custom-html-parser'; import * as css from './UrlPreviewCard.css'; +import * as urlPreviewChrome from './UrlPreview.css'; import { UrlPreview, UrlPreviewContent, UrlPreviewDescription } from './UrlPreview'; import { AudioContent, ImageContent, VideoContent } from '../message'; import { Image, MediaControl, Video } from '../media'; import { ImageViewer } from '../image-viewer'; +import { useSetting } from '$state/hooks/settings'; +import { settingsAtom } from '$state/settings'; +import type { IImageInfo } from '$types/matrix/common'; +import { MATRIX_UNSTABLE_BLUR_HASH_PROPERTY_NAME } from '$unstable/prefixes'; const linkStyles = { color: color.Success.Main }; @@ -42,6 +59,32 @@ const openMediaInNewTab = async (url: string | undefined) => { window.open(blobUrl, '_blank'); }; +function ogPositiveDimension(value: unknown): number | undefined { + if (typeof value === 'number' && Number.isFinite(value) && value > 0) return value; + if (typeof value === 'string') { + const n = Number.parseFloat(value); + if (Number.isFinite(n) && n > 0) return n; + } + return undefined; +} + +function isLikelyPlayableOgVideo(prev: IPreviewUrlResponse): boolean { + const raw = prev['og:video']; + if (typeof raw !== 'string') return false; + const url = raw.trim(); + if (!url) return false; + const mime = + typeof prev['og:video:type'] === 'string' ? prev['og:video:type'].toLowerCase().trim() : ''; + if (mime.startsWith('video/')) return true; + if (/^mxc:\/\//i.test(url)) { + return mime.startsWith('video/') || /\.(mp4|webm|ogg|mov|m4v)(\?|$)/i.test(url); + } + if (/^https?:\/\//i.test(url)) { + return /\.(mp4|webm|ogg|mov|m4v)(\?|$)/i.test(url) || mime.startsWith('video/'); + } + return false; +} + export const UrlPreviewCard = as< 'div', { @@ -54,6 +97,7 @@ export const UrlPreviewCard = as< >(({ urlPreview, url, ts, mediaType, bundle, ...props }, ref) => { const mx = useMatrixClient(); const useAuthentication = useMediaAuthentication(); + const [linkPreviewImageMaxHeight] = useSetting(settingsAtom, 'linkPreviewImageMaxHeight'); const isDirect = !!mediaType; @@ -109,14 +153,49 @@ export const UrlPreviewCard = as< } }; - const ogW = ((prev['og:video'] && prev['og:video:width']) || - (prev['og:image'] && prev['og:image:width']) || - 1) as number; - const ogH = ((prev['og:video'] && prev['og:video:height']) || - (prev['og:image'] && prev['og:image:height']) || - 1) as number; + const videoW = prev['og:video'] ? ogPositiveDimension(prev['og:video:width']) : undefined; + const videoH = prev['og:video'] ? ogPositiveDimension(prev['og:video:height']) : undefined; + const ogImgW = ogPositiveDimension(prev['og:image:width']); + const ogImgH = ogPositiveDimension(prev['og:image:height']); - const aspectRatio = ogW && ogH ? `${ogW} / ${ogH}` : undefined; + const aspectRatio = + videoW && videoH + ? `${videoW} / ${videoH}` + : ogImgW && ogImgH + ? `${ogImgW} / ${ogImgH}` + : undefined; + + const previewBlurRaw = + typeof prev['matrix:image:blurhash'] === 'string' ? prev['matrix:image:blurhash'].trim() : ''; + + const ogImageInfo: IImageInfo | undefined = (() => { + const matrixSize = prev['matrix:image:size']; + const size = + typeof matrixSize === 'number' && Number.isFinite(matrixSize) ? matrixSize : undefined; + if (ogImgW && ogImgH) { + return { + w: ogImgW, + h: ogImgH, + ...(size !== undefined ? { size } : {}), + ...(previewBlurRaw ? { [MATRIX_UNSTABLE_BLUR_HASH_PROPERTY_NAME]: previewBlurRaw } : {}), + }; + } + if (previewBlurRaw || size !== undefined) { + return { + w: 16, + h: 9, + ...(size !== undefined ? { size } : {}), + ...(previewBlurRaw ? { [MATRIX_UNSTABLE_BLUR_HASH_PROPERTY_NAME]: previewBlurRaw } : {}), + }; + } + return undefined; + })(); + + const previewThumbMaxEdge = Math.min( + 2048, + Math.max(1, Math.round(Math.max(1, linkPreviewImageMaxHeight) * 2)) + ); + const showOgVideo = isLikelyPlayableOgVideo(prev); return ( )} - {prev['og:video'] && ( - + )} + {!showOgVideo && prev['og:image'] && ( + + } + renderImage={(p) => ( + + )} + /> + + )} + {!showOgVideo && !prev['og:image'] && prev['og:audio'] && ( -
    +
    { @@ -80,8 +103,8 @@ export function CreatorChip() { } > : undefined} onClick={open} aria-pressed={!!cords} + className={cardColor ? css.UserHeroChipThemed : css.UserHeroBrightnessHover} + style={heroMenuItemStyle( + cardColor && chipSurfaceStyle ? chipSurfaceStyle : {}, + chipHoverBrightness + )} > {tag.name} diff --git a/src/app/components/user-profile/PowerChip.tsx b/src/app/components/user-profile/PowerChip.tsx index 5b9669847..dbb6ae579 100644 --- a/src/app/components/user-profile/PowerChip.tsx +++ b/src/app/components/user-profile/PowerChip.tsx @@ -20,6 +20,7 @@ import { Text, toRem, } from 'folds'; +import type { CSSProperties } from 'react'; import type { MouseEventHandler } from 'react'; import { useCallback, useState } from 'react'; import FocusTrap from 'focus-trap-react'; @@ -45,6 +46,8 @@ import { useMemberPowerCompare } from '$hooks/useMemberPowerCompare'; import { CutoutCard } from '$components/cutout-card'; import { PowerColorBadge, PowerIcon } from '$components/power'; import { EventType } from '$types/matrix-sdk'; +import { heroMenuItemStyle } from './heroMenuItemStyle'; +import * as css from './styles.css'; type SelfDemoteAlertProps = { power: number; @@ -146,7 +149,24 @@ function SharedPowerAlert({ power, onCancel, onChange }: SharedPowerAlertProps) ); } -export function PowerChip({ userId }: { userId: string }) { +export function PowerChip({ + userId, + innerColor, + cardColor, + textColor, + chipSurfaceStyle, + chipFillColor, + chipHoverBrightness, +}: { + userId: string; + innerColor?: string; + cardColor?: string; + textColor?: string; + chipSurfaceStyle?: CSSProperties; + chipFillColor?: string; + chipHoverBrightness?: number; +}) { + const menuItemBg = chipFillColor ?? cardColor; const mx = useMatrixClient(); const room = useRoom(); const space = useSpaceOptionally(); @@ -241,7 +261,11 @@ export function PowerChip({ userId }: { userId: string }) { {error && ( @@ -270,6 +294,11 @@ export function PowerChip({ userId }: { userId: string }) { radii="300" aria-disabled={changing || !canChangePowers || !canAssignPower} aria-pressed={selected} + className={css.UserHeroMenuItem} + style={heroMenuItemStyle( + { backgroundColor: menuItemBg, color: textColor }, + chipHoverBrightness + )} before={} after={ powerTagIconSrc ? ( @@ -287,13 +316,18 @@ export function PowerChip({ userId }: { userId: string }) { ); })} - -
    + +
    { if (room.isSpaceRoom()) { openSpaceSettings( @@ -319,8 +353,19 @@ export function PowerChip({ userId }: { userId: string }) { } > diff --git a/src/app/components/user-profile/UserChips.tsx b/src/app/components/user-profile/UserChips.tsx index 07b5bbe62..168a973e5 100644 --- a/src/app/components/user-profile/UserChips.tsx +++ b/src/app/components/user-profile/UserChips.tsx @@ -1,4 +1,5 @@ import type { KeyboardEventHandler, MouseEventHandler } from 'react'; +import type { CSSProperties } from 'react'; import { useCallback, useEffect, useMemo, useRef, useState } from 'react'; import { useNavigate } from 'react-router-dom'; import FocusTrap from 'focus-trap-react'; @@ -22,7 +23,7 @@ import { Avatar, } from 'folds'; import { useMatrixClient } from '$hooks/useMatrixClient'; -import { getMxIdServer } from '$utils/matrix'; +import { getMxIdServer } from '$utils/mxIdHelper'; import { useCloseUserRoomProfile } from '$state/hooks/userRoomProfile'; import { stopPropagation } from '$utils/keyboard'; import { copyToClipboard } from '$utils/dom'; @@ -43,8 +44,27 @@ import { useNickname, useSetNickname } from '$hooks/useNickname'; import { CutoutCard } from '$components/cutout-card'; import { SettingTile } from '$components/setting-tile'; import { RoomAvatar, RoomIcon } from '$components/room-avatar'; +import { heroMenuItemStyle } from './heroMenuItemStyle'; +import * as css from './styles.css'; -export function ServerChip({ server }: { server: string }) { +export function ServerChip({ + server, + innerColor, + cardColor, + textColor, + chipSurfaceStyle, + chipFillColor, + chipHoverBrightness, +}: { + server: string; + innerColor?: string; + cardColor?: string; + textColor?: string; + chipSurfaceStyle?: CSSProperties; + chipFillColor?: string; + chipHoverBrightness?: number; +}) { + const menuItemBg = chipFillColor ?? cardColor; const mx = useMatrixClient(); const myServer = getMxIdServer(mx.getSafeUserId()); const navigate = useNavigate(); @@ -77,54 +97,91 @@ export function ServerChip({ server }: { server: string }) { }} > -
    - { - copyToClipboard(server); - setCopied(); - close(); - }} - > - Copy Server - - { - navigate(getExploreServerPath(server)); - closeProfile(); - }} - > - Explore Community - +
    + + { + copyToClipboard(server); + setCopied(); + close(); + }} + className={css.UserHeroMenuItem} + style={heroMenuItemStyle( + { + backgroundColor: menuItemBg, + color: textColor, + }, + chipHoverBrightness + )} + > + Copy Server + + { + navigate(getExploreServerPath(server)); + closeProfile(); + }} + className={css.UserHeroMenuItem} + style={heroMenuItemStyle( + { + backgroundColor: menuItemBg, + color: textColor, + }, + chipHoverBrightness + )} + > + Explore Community + +
    -
    - { - window.open(`https://${server}`, '_blank'); - close(); - }} - > - Open in Browser - +
    + + { + window.open(`https://${server}`, '_blank'); + close(); + }} + className={css.UserHeroMenuItem} + style={heroMenuItemStyle( + { + backgroundColor: menuItemBg, + color: textColor, + }, + chipHoverBrightness + )} + > + Open in Browser + +
    } > {server} @@ -144,7 +206,24 @@ export function ServerChip({ server }: { server: string }) { ); } -export function ShareChip({ userId }: { userId: string }) { +export function ShareChip({ + userId, + innerColor, + cardColor, + textColor, + chipSurfaceStyle, + chipFillColor, + chipHoverBrightness, +}: { + userId: string; + innerColor?: string; + cardColor?: string; + textColor?: string; + chipSurfaceStyle?: CSSProperties; + chipFillColor?: string; + chipHoverBrightness?: number; +}) { + const menuItemBg = chipFillColor ?? cardColor; const [cords, setCords] = useState(); const [copied, setCopied] = useTimeoutToggle(); @@ -173,40 +252,56 @@ export function ShareChip({ userId }: { userId: string }) { }} > -
    - { - copyToClipboard(userId); - setCopied(); - close(); - }} - > - Copy User ID - - { - copyToClipboard(getMatrixToUser(userId)); - setCopied(); - close(); - }} - > - Copy User Link - +
    + + { + copyToClipboard(userId); + setCopied(); + close(); + }} + > + Copy User ID + + { + copyToClipboard(getMatrixToUser(userId)); + setCopied(); + close(); + }} + > + Copy User Link + +
    } > Share @@ -232,7 +332,24 @@ type MutualRoomsData = { directs: Room[]; }; -export function MutualRoomsChip({ userId }: { userId: string }) { +export function MutualRoomsChip({ + userId, + innerColor, + cardColor, + textColor, + chipSurfaceStyle, + chipFillColor, + chipHoverBrightness, +}: { + userId: string; + innerColor?: string; + cardColor?: string; + textColor?: string; + chipSurfaceStyle?: CSSProperties; + chipFillColor?: string; + chipHoverBrightness?: number; +}) { + const menuItemBg = chipFillColor ?? cardColor; const mx = useMatrixClient(); const mutualRoomSupported = useMutualRoomsSupport(); const mutualRoomsState = useMutualRooms(userId); @@ -298,7 +415,15 @@ export function MutualRoomsChip({ userId }: { userId: string }) { fill="None" size="300" radii="300" - style={{ paddingLeft: config.space.S100 }} + className={css.UserHeroMenuItem} + style={heroMenuItemStyle( + { + paddingLeft: config.space.S100, + backgroundColor: menuItemBg, + color: textColor, + }, + chipHoverBrightness + )} onClick={() => { if (room.isSpaceRoom()) { navigateSpace(roomId); @@ -325,12 +450,17 @@ export function MutualRoomsChip({ userId }: { userId: string }) { )} /> ) : ( - + )} } > - + {room.name}
    @@ -360,6 +490,7 @@ export function MutualRoomsChip({ userId }: { userId: string }) { display: 'flex', maxWidth: toRem(200), maxHeight: '80vh', + backgroundColor: innerColor, }} > @@ -367,7 +498,7 @@ export function MutualRoomsChip({ userId }: { userId: string }) { {mutual.spaces.length > 0 && ( @@ -402,7 +533,7 @@ export function MutualRoomsChip({ userId }: { userId: string }) { } > } disabled={ @@ -410,8 +541,13 @@ export function MutualRoomsChip({ userId }: { userId: string }) { } onClick={open} aria-pressed={!!cords} + className={cardColor ? css.UserHeroChipThemed : css.UserHeroBrightnessHover} + style={heroMenuItemStyle( + cardColor && chipSurfaceStyle ? chipSurfaceStyle : {}, + chipHoverBrightness + )} > - + {mutualRoomsState.status === AsyncStatus.Success && `${mutualRoomsState.data.length} Mutual Rooms`} {mutualRoomsState.status === AsyncStatus.Loading && 'Mutual Rooms'} @@ -438,7 +574,24 @@ export function IgnoredUserAlert() { ); } -export function OptionsChip({ userId }: { userId: string }) { +export function OptionsChip({ + userId, + innerColor, + cardColor, + textColor, + chipSurfaceStyle, + chipFillColor, + chipHoverBrightness, +}: { + userId: string; + innerColor?: string; + cardColor?: string; + textColor?: string; + chipSurfaceStyle?: CSSProperties; + chipFillColor?: string; + chipHoverBrightness?: number; +}) { + const menuItemBg = chipFillColor ?? cardColor; const mx = useMatrixClient(); const [cords, setCords] = useState(); const [editingNick, setEditingNick] = useState(false); @@ -503,94 +656,130 @@ export function OptionsChip({ userId }: { userId: string }) { }} > -
    - {editingNick ? ( - - Nickname - - - - Save - - {currentNick && ( +
    + + {editingNick ? ( + + Nickname + + { - setNickname(userId, undefined); - close(); - }} + onClick={handleSaveNick} + className={css.UserHeroMenuItem} + style={heroMenuItemStyle( + { + backgroundColor: menuItemBg, + color: textColor, + }, + chipHoverBrightness + )} > - Clear + Save - )} + {currentNick && ( + { + setNickname(userId, undefined); + close(); + }} + style={heroMenuItemStyle( + { + backgroundColor: menuItemBg, + color: textColor, + }, + chipHoverBrightness + )} + > + Clear + + )} + - - ) : ( + ) : ( + } + onClick={() => setEditingNick(true)} + className={css.UserHeroMenuItem} + style={heroMenuItemStyle( + { + backgroundColor: menuItemBg, + color: textColor, + }, + chipHoverBrightness + )} + > + {currentNick ? 'Edit Nickname' : 'Set Nickname'} + + )} } - onClick={() => setEditingNick(true)} + onClick={() => { + toggleIgnore(); + close(); + }} + className={css.UserHeroMenuItem} + style={heroMenuItemStyle({ backgroundColor: menuItemBg }, chipHoverBrightness)} + before={ + ignoring ? ( + + ) : ( + + ) + } + disabled={ignoring} > - {currentNick ? 'Edit Nickname' : 'Set Nickname'} + + {ignored ? 'Unblock User' : 'Block User'} + - )} - { - toggleIgnore(); - close(); - }} - before={ - ignoring ? ( - - ) : ( - - ) - } - disabled={ignoring} - > - {ignored ? 'Unblock User' : 'Block User'} - +
    } > - + {ignoring ? ( ) : ( diff --git a/src/app/components/user-profile/UserHero.tsx b/src/app/components/user-profile/UserHero.tsx index 34cf7635a..746a5d1e3 100644 --- a/src/app/components/user-profile/UserHero.tsx +++ b/src/app/components/user-profile/UserHero.tsx @@ -1,7 +1,9 @@ import { useMemo, useState } from 'react'; +import type { CSSProperties } from 'react'; import { Avatar, Box, + color as standardColors, Icon, Icons, Modal, @@ -28,6 +30,8 @@ import { ImageViewer } from '$components/image-viewer'; import { AvatarPresence, PresenceBadge } from '$components/presence'; import { UserAvatar } from '$components/user-avatar'; import { ClientSideHoverFreeze } from '$components/ClientSideHoverFreeze'; +import { useUserProfile } from '$hooks/useUserProfile'; +import { shadeColor, areColorsTooSimilar } from '$utils/shadeColor'; import * as css from './styles.css'; type UserHeroProps = { @@ -69,8 +73,23 @@ export function UserHero({ userId, avatarUrl, bannerUrl, presence, autoplayGifs const status = presence?.status; const isExpandable = (status?.length ?? 0) > 70; + const fetchedProfile = useUserProfile(userId); + const backgroundColor = fetchedProfile.heroColor ?? standardColors.Surface.Container; + const fetchedBrightness = fetchedProfile?.heroBrightness; + const isBackgroundDark = fetchedBrightness ? fetchedBrightness === 'dark' : undefined; + const cardColor = + shadeColor(backgroundColor, isBackgroundDark ? -80 : 80) ?? standardColors.Background.Container; + const innerColor = shadeColor(backgroundColor, isBackgroundDark ? -50 : 50) ?? backgroundColor; + const statusSurfaceColor = + shadeColor(innerColor, fetchedBrightness === 'light' ? -14 : 32) ?? cardColor; + const textColor = + ((fetchedBrightness === 'dark' || areColorsTooSimilar('#000000', cardColor)) && '#FFFFFF') || + ((fetchedBrightness === 'light' || areColorsTooSimilar('#FFFFFF', cardColor)) && '#000000') || + undefined; + const statusHoverBrightness = fetchedBrightness === 'light' ? 0.94 : 1.08; + return ( - +
    0 && (
    setIsFullStatus(!isFullStatus) : undefined} - className={css.UserHeroStatusTooltip} + className={classNames( + css.UserHeroStatusTooltip, + isExpandable && css.UserHeroStatusTooltipInteractive + )} style={{ maxHeight: isFullStatus ? toRem(105) : toRem(48), cursor: isExpandable ? 'pointer' : 'default', transform: 'none', transition: 'none', display: 'flex', + padding: `${toRem(8)} ${toRem(12)}`, + backgroundColor: statusSurfaceColor, + color: textColor, + borderStyle: 'none', + borderWidth: 0, + outline: 'none', + boxShadow: 'inset 0 1px 1px rgba(0, 0, 0, 0.05)', + ...({ + '--user-hero-status-hover-brightness': String(statusHoverBrightness), + } as CSSProperties), }} > @@ -195,14 +229,14 @@ export function UserHero({ userId, avatarUrl, bannerUrl, presence, autoplayGifs type UserHeroNameProps = { displayName?: string; userId: string; + customHeroCards?: boolean; }; -export function UserHeroName({ displayName, userId }: UserHeroNameProps) { +export function UserHeroName({ displayName, userId, customHeroCards }: UserHeroNameProps) { const username = getMxIdLocalPart(userId); const nick = useNickname(userId); // Sable username color and fonts - const { color, font } = useSableCosmetics(userId, useRoom()); - + const { color, font } = useSableCosmetics(userId, useRoom(), customHeroCards); const shownName = nick ?? displayName ?? username ?? userId; return ( diff --git a/src/app/components/user-profile/UserRoomProfile.tsx b/src/app/components/user-profile/UserRoomProfile.tsx index 4f5c4a69a..2732649c1 100644 --- a/src/app/components/user-profile/UserRoomProfile.tsx +++ b/src/app/components/user-profile/UserRoomProfile.tsx @@ -1,11 +1,23 @@ -import { Box, Button, config, Icon, Icons, Menu, MenuItem, Scroll, Text, toRem } from 'folds'; -import type { SyntheticEvent } from 'react'; +import { + Box, + Button, + color, + config, + Icon, + Icons, + Menu, + MenuItem, + Scroll, + Text, + toRem, +} from 'folds'; +import type { CSSProperties, SyntheticEvent } from 'react'; import { useCallback, useMemo, useState } from 'react'; import { useNavigate } from 'react-router-dom'; import { useAtomValue } from 'jotai'; import type { Opts as LinkifyOpts } from 'linkifyjs'; import type { HTMLReactParserOptions } from 'html-react-parser'; -import { getMxIdServer, mxcUrlToHttp } from '$utils/matrix'; +import { mxcUrlToHttp } from '$utils/matrix'; import { getMemberAvatarMxc, getMemberDisplayName } from '$utils/room'; import { useMatrixClient } from '$hooks/useMatrixClient'; import { useMediaAuthentication } from '$hooks/useMediaAuthentication'; @@ -37,33 +49,42 @@ import { getSettings, settingsAtom } from '$state/settings'; import { filterPronounsByLanguage } from '$utils/pronouns'; import { useSetting } from '$state/hooks/settings'; import { useSettingsLinkBaseUrl } from '$features/settings/useSettingsLinkBaseUrl'; +import { getMxIdServer } from '$utils/mxIdHelper'; import { TextViewerContent } from '$components/text-viewer'; +import { areColorsTooSimilar, shadeColor } from '$utils/shadeColor'; +import { ThemeKind, useTheme } from '$hooks/useTheme'; +import { heroMenuItemStyle } from './heroMenuItemStyle'; import { CreatorChip } from './CreatorChip'; import { UserInviteAlert, UserBanAlert, UserModeration, UserKickAlert } from './UserModeration'; import { PowerChip } from './PowerChip'; import { IgnoredUserAlert, MutualRoomsChip, OptionsChip, ServerChip, ShareChip } from './UserChips'; import { UserHero, UserHeroName } from './UserHero'; import { KnownMembership } from '$types/matrix-sdk'; +import * as css from './styles.css'; +import * as prefix from '$unstable/prefixes'; const KNOWN_KEYS = new Set([ - 'moe.sable.app.bio', - 'chat.commet.profile_bio', - 'chat.commet.profile_banner', - 'chat.commet.profile_status', - 'io.fsky.nyx.pronouns', - 'us.cloke.msc4175.tz', - 'm.tz', - 'moe.sable.app.name_color', + prefix.MATRIX_SABLE_UNSTABLE_PROFILE_BIOGRAPHY_PROPERTY_NAME, + prefix.MATRIX_COMMET_UNSTABLE_PROFILE_BIO_PROPERTY_NAME, + prefix.MATRIX_UNSTABLE_PROFILE_BANNER_PROPERTY_NAME, + prefix.MATRIX_COMMET_UNSTABLE_PROFILE_STATUS_PROPERTY_NAME, + prefix.MATRIX_UNSTABLE_PROFILE_PRONOUNS_PROPERTY_NAME, + prefix.MATRIX_UNSTABLE_PROFILE_TIMEZONE_PROPERTY_NAME, + prefix.MATRIX_STABLE_PROFILE_TIMEZONE_PROPERTY_NAME, + prefix.MATRIX_SABLE_UNSTABLE_NAME_COLOR_PROPERTY_NAME, 'avatar_url', 'displayname', - 'kitty.meow.has_cats', - 'kitty.meow.is_cat', + prefix.MATRIX_SABLE_UNSTABLE_ANIMAL_IDENTITY_IS_CAT_PROPERTY_NAME, + prefix.MATRIX_SABLE_UNSTABLE_ANIMAL_IDENTITY_HAS_CAT_PROPERTY_NAME, ]); type UserExtendedSectionProps = { profile: UserProfile; htmlReactParserOptions: HTMLReactParserOptions; linkifyOpts: LinkifyOpts; + innerColor?: string; + cardColor?: string; + textColor?: string; }; const renderValue = (val: unknown) => { @@ -77,6 +98,9 @@ function UserExtendedSection({ profile, htmlReactParserOptions, linkifyOpts, + innerColor, + cardColor, + textColor, }: Readonly) { const [showMisc, setShowMisc] = useState(false); const [miscDataIndex, setMiscDataIndex] = useState(-1); @@ -119,8 +143,8 @@ function UserExtendedSection({ const bioContent = useMemo(() => { let rawBio = - profile.extended?.['moe.sable.app.bio'] || - profile.extended?.['chat.commet.profile_bio'] || + profile.extended?.[prefix.MATRIX_SABLE_UNSTABLE_PROFILE_BIOGRAPHY_PROPERTY_NAME] || + profile.extended?.[prefix.MATRIX_COMMET_UNSTABLE_PROFILE_BIO_PROPERTY_NAME] || profile.bio; if (!rawBio) return null; @@ -162,13 +186,24 @@ function UserExtendedSection({ return null; } return ( - + handleMiscSelector(-1)} > @@ -180,8 +215,7 @@ function UserExtendedSection({ size="300" radii="300" fill="None" - variant="Secondary" - style={{ justifyContent: 'Center' }} + style={{ justifyContent: 'Center', backgroundColor: cardColor, color: textColor }} onClick={() => handleMiscSelector(index)} > {key} @@ -189,21 +223,24 @@ function UserExtendedSection({ ))} ); - }, [miscDataIndex, showMisc, unknownFields]); + }, [cardColor, innerColor, miscDataIndex, showMisc, textColor, unknownFields]); const miscHeader = useMemo( () => ( @@ -314,21 +351,34 @@ function UserExtendedSection({ {miscHeader} {unknownFields.length > 1 && ( )} - + @@ -351,6 +401,7 @@ type UserRoomProfileProps = { initialProfile?: Partial; }; export function UserRoomProfile({ userId, initialProfile }: Readonly) { + const theme = useTheme(); const mx = useMatrixClient(); const useAuthentication = useMediaAuthentication(); const navigate = useNavigate(); @@ -451,8 +502,58 @@ export function UserRoomProfile({ userId, initialProfile }: Readonly + - - + + - + {userId !== myUserId && ( @@ -482,50 +608,57 @@ export function UserRoomProfile({ userId, initialProfile }: Readonly - {server && } - - {creator ? : } - {userId !== myUserId && } - {userId !== myUserId && } + {server && } + + {creator ? ( + + ) : ( + + )} + {userId !== myUserId && } + {userId !== myUserId && } - - {ignored && } - {member && membership === bannedMembership && ( - - )} - {member && - membership === leftMembership && - member.events.member && - member.events.member.getSender() !== userId && ( - } + {member && membership === bannedMembership && ( + )} - {member && membership === invitedMembership && ( - + )} + {member && membership === invitedMembership && ( + + )} + - )} - + ); diff --git a/src/app/components/user-profile/heroMenuItemStyle.ts b/src/app/components/user-profile/heroMenuItemStyle.ts new file mode 100644 index 000000000..0b66e36ce --- /dev/null +++ b/src/app/components/user-profile/heroMenuItemStyle.ts @@ -0,0 +1,19 @@ +import type { CSSProperties } from 'react'; + +export function heroMenuItemStyle( + base: CSSProperties, + chipHoverBrightness?: number +): CSSProperties { + const bg = base.backgroundColor; + const out: CSSProperties = { ...base }; + if (typeof bg === 'string' && bg !== '' && bg !== 'transparent') { + (out as CSSProperties & { '--user-hero-menu-item-bg': string })['--user-hero-menu-item-bg'] = + bg; + } + if (chipHoverBrightness != null) { + (out as CSSProperties & { '--user-hero-chip-hover-brightness': number })[ + '--user-hero-chip-hover-brightness' + ] = chipHoverBrightness; + } + return out; +} diff --git a/src/app/components/user-profile/styles.css.ts b/src/app/components/user-profile/styles.css.ts index 10b0c9e51..e7283d43b 100644 --- a/src/app/components/user-profile/styles.css.ts +++ b/src/app/components/user-profile/styles.css.ts @@ -57,9 +57,12 @@ export const UserHeroStatusContainer = style({ export const UserHeroStatusTooltip = style({ maxWidth: '98%', justifySelf: 'left', +}); + +export const UserHeroStatusTooltipInteractive = style({ cursor: 'pointer', ':hover': { - filter: 'brightness(0.8)', + filter: 'brightness(var(--user-hero-status-hover-brightness, 0.94))', transform: 'translateY(-1px)', }, }); @@ -78,3 +81,55 @@ export const UserHeroAvatarImg = style({ }, }, }); +export const UserHeroBrightnessHover = style({ + ':hover': { + filter: 'brightness(var(--user-hero-chip-hover-brightness, 0.94))', + transform: 'translateY(-1px)', + }, +}); + +export const UserHeroChip = style([ + UserHeroBrightnessHover, + { + borderStyle: 'solid', + borderWidth: '1px', + boxShadow: '0 1px 2px rgba(0, 0, 0, 0.1)', + }, +]); + +export const UserHeroChipThemed = style([ + UserHeroBrightnessHover, + { + borderStyle: 'solid', + borderWidth: '1px', + borderColor: 'transparent', + boxShadow: '0 1px 2px rgba(0, 0, 0, 0.1)', + }, +]); + +export const MiscDataToggleButton = style({ + backgroundColor: 'transparent', + opacity: 0.75, + selectors: { + '&:hover': { + opacity: 1, + backgroundColor: 'transparent', + transform: 'none !important', + }, + '&:active': { + transform: 'none !important', + }, + }, +}); +/** Same hover lift/filter as UserHeroBrightnessHover; pins bg so folds MenuItem hover can't mask brightness. */ +export const UserHeroMenuItem = style({ + borderStyle: 'hidden', + borderWidth: '1px', + selectors: { + '&:hover': { + filter: 'brightness(var(--user-hero-chip-hover-brightness, 0.94))', + transform: 'translateY(-1px)', + backgroundColor: 'var(--user-hero-menu-item-bg) !important', + }, + }, +}); diff --git a/src/app/cs-errorcode.ts b/src/app/cs-errorcode.ts index 6c21d670c..4e54d5ac0 100644 --- a/src/app/cs-errorcode.ts +++ b/src/app/cs-errorcode.ts @@ -34,4 +34,5 @@ export enum ErrorCode { M_EXCLUSIVE = 'M_EXCLUSIVE', M_RESOURCE_LIMIT_EXCEEDED = 'M_RESOURCE_LIMIT_EXCEEDED', M_CANNOT_LEAVE_SERVER_NOTICE_ROOM = 'M_CANNOT_LEAVE_SERVER_NOTICE_ROOM', + M_MAX_DELAY_EXCEEDED = 'M_MAX_DELAY_EXCEEDED', } diff --git a/src/app/features/common-settings/cosmetics/Cosmetics.tsx b/src/app/features/common-settings/cosmetics/Cosmetics.tsx index 8ce1f7512..e7d505f88 100644 --- a/src/app/features/common-settings/cosmetics/Cosmetics.tsx +++ b/src/app/features/common-settings/cosmetics/Cosmetics.tsx @@ -26,6 +26,7 @@ import { SettingTile } from '$components/setting-tile'; import { useRoom } from '$hooks/useRoom'; import { usePowerLevels } from '$hooks/usePowerLevels'; import { useMatrixClient } from '$hooks/useMatrixClient'; +import { useStateEvent } from '$hooks/useStateEvent'; import { useRoomCreators } from '$hooks/useRoomCreators'; import { useRoomPermissions } from '$hooks/useRoomPermissions'; @@ -70,8 +71,17 @@ export function CosmeticsAvatar({ profile, member, userId, room }: CosmeticsSett const capabilities = useCapabilities(); const [alertRemove, setAlertRemove] = useState(false); const disableSetAvatar = capabilities['m.set_avatar_url']?.enabled === false; - - const avatarMxc = member.getMxcAvatarUrl(); + const memberStateEvent = useStateEvent(room, EventType.RoomMember, userId); + const memberStateContent = memberStateEvent?.getContent<{ avatar_url?: string }>(); + const globalAvatarMxc = mx.getUser(userId)?.avatarUrl ?? profile.avatarUrl; + const roomAvatarMxc = memberStateEvent + ? memberStateContent?.avatar_url + : member.getMxcAvatarUrl(); + const avatarMxc = roomAvatarMxc ?? globalAvatarMxc; + const hasRoomAvatarOverride = + memberStateEvent !== undefined && + memberStateContent?.avatar_url !== undefined && + memberStateContent.avatar_url !== globalAvatarMxc; const avatarUrl = avatarMxc && (mxcUrlToHttp(mx, avatarMxc, useAuthentication, 96, 96, 'crop') ?? undefined); @@ -92,15 +102,17 @@ export function CosmeticsAvatar({ profile, member, userId, room }: CosmeticsSett const handleUploaded = useCallback( (upload: UploadSuccess) => { const { mxc } = upload; - myRoomAvatar.exe(mxc); - handleRemoveUpload(); + myRoomAvatar.exe(mxc).finally(() => { + handleRemoveUpload(); + }); }, [myRoomAvatar, handleRemoveUpload] ); const handleRemoveAvatar = () => { - myRoomAvatar.exe(''); - setAlertRemove(false); + myRoomAvatar.exe('').finally(() => { + setAlertRemove(false); + }); }; return ( @@ -139,20 +151,18 @@ export function CosmeticsAvatar({ profile, member, userId, room }: CosmeticsSett > Upload - {avatarUrl && - avatarUrl !== - mxcUrlToHttp(mx, profile.avatarUrl ?? '', useAuthentication, 96, 96, 'crop') && ( - - )} + {hasRoomAvatarOverride && ( + + )} )} diff --git a/src/app/features/common-settings/general/RoomAddress.tsx b/src/app/features/common-settings/general/RoomAddress.tsx index 269f2c1b4..d7b6a400c 100644 --- a/src/app/features/common-settings/general/RoomAddress.tsx +++ b/src/app/features/common-settings/general/RoomAddress.tsx @@ -31,9 +31,9 @@ import { AsyncStatus, useAsyncCallback } from '$hooks/useAsyncCallback'; import { CutoutCard } from '$components/cutout-card'; import { replaceSpaceWithDash } from '$utils/common'; import { useAlive } from '$hooks/useAlive'; +import { getMxIdServer } from '$utils/mxIdHelper'; import type { RoomPermissionsAPI } from '$hooks/useRoomPermissions'; -import { getMxIdServer } from '$utils/matrix'; import { EventType } from '$types/matrix-sdk'; type RoomPublishedAddressesProps = { diff --git a/src/app/features/common-settings/general/RoomJoinRules.tsx b/src/app/features/common-settings/general/RoomJoinRules.tsx index 4cdea0dfd..042fbd5af 100644 --- a/src/app/features/common-settings/general/RoomJoinRules.tsx +++ b/src/app/features/common-settings/general/RoomJoinRules.tsx @@ -22,7 +22,7 @@ import { getStateEvents } from '$utils/room'; import { useRecursiveChildSpaceScopeFactory, useSpaceChildren } from '$state/hooks/roomList'; import { allRoomsAtom } from '$state/room-list/roomList'; import { roomToParentsAtom } from '$state/room/roomToParents'; -import { knockRestrictedSupported, knockSupported, restrictedSupported } from '$utils/matrix'; +import { knockRestrictedSupported, restrictedSupported, knockSupported } from '$utils/roomSupport'; import type { RoomPermissionsAPI } from '$hooks/useRoomPermissions'; type RestrictedRoomAllowContent = { diff --git a/src/app/features/common-settings/general/RoomProfile.tsx b/src/app/features/common-settings/general/RoomProfile.tsx index e0db34b00..cb49900ff 100644 --- a/src/app/features/common-settings/general/RoomProfile.tsx +++ b/src/app/features/common-settings/general/RoomProfile.tsx @@ -4,15 +4,22 @@ import { Button, Chip, color, + config, + Dialog, + Header, Icon, + IconButton, Icons, Input, + Overlay, + OverlayBackdrop, + OverlayCenter, Spinner, Text, TextArea, } from 'folds'; import type { FormEventHandler } from 'react'; -import { useCallback, useMemo, useState } from 'react'; +import { useCallback, useEffect, useMemo, useState } from 'react'; import { useAtomValue } from 'jotai'; import Linkify from 'linkify-react'; import classNames from 'classnames'; @@ -40,6 +47,12 @@ import { useAlive } from '$hooks/useAlive'; import type { RoomPermissionsAPI } from '$hooks/useRoomPermissions'; import { useSetting } from '$state/hooks/settings'; import { settingsAtom } from '$state/settings'; +import { useStateEvent } from '$hooks/useStateEvent'; +import type { RoomBannerContent } from '$types/matrix-sdk-events'; +import { CustomStateEvent } from '$types/matrix/room'; +import { SettingTile } from '$components/setting-tile'; +import { stopPropagation } from '$utils/keyboard'; +import FocusTrap from 'focus-trap-react'; type RoomProfileEditProps = { canEditAvatar: boolean; @@ -296,6 +309,175 @@ export function RoomProfileEdit({ ); } +export type ProfileProps = { + bannerURI?: string; +}; +function RoomBannerEdit({ bannerURI }: Readonly) { + const mx = useMatrixClient(); + const [alertRemove, setAlertRemove] = useState(false); + + const space = useRoom(); + const [stagedUrl, setStagedUrl] = useState(); + const [isRemoving, setIsRemoving] = useState(false); + + const bannerUrl = bannerURI; + + useEffect(() => { + if (bannerUrl) { + setStagedUrl(undefined); + } + }, [bannerUrl]); + + const [imageFile, setImageFile] = useState(); + const imageFileURL = useObjectURL(imageFile); + + const uploadAtom = useMemo(() => { + if (imageFile) return createUploadAtom(imageFile); + return undefined; + }, [imageFile]); + + const pickFile = useFilePicker(setImageFile, false); + + const handlePick = useCallback(() => { + setIsRemoving(false); + setStagedUrl(undefined); + pickFile('image/*'); + }, [pickFile]); + + const handleRemoveUpload = useCallback(() => { + setImageFile(undefined); + }, []); + + const handleUploaded = useCallback( + (upload: UploadSuccess) => { + const { mxc } = upload; + + if (imageFileURL) setStagedUrl(imageFileURL); + mx.sendStateEvent(space.roomId, CustomStateEvent.RoomBanner, { url: mxc }, ''); + setImageFile(undefined); + }, + [mx, imageFileURL, space] + ); + + const handleRemoveBanner = async () => { + setIsRemoving(true); + setStagedUrl(undefined); + setImageFile(undefined); + + mx.sendStateEvent(space.roomId, CustomStateEvent.RoomBanner, { url: '' }, ''); + + setAlertRemove(false); + }; + + const previewUrl = isRemoving ? undefined : imageFileURL || stagedUrl || bannerUrl; + + return ( + + + + {previewUrl ? ( + Banner Preview + ) : ( + + + No Banner Set + + + )} + + + {uploadAtom ? ( + + + + ) : ( + + + {bannerUrl && ( + + )} + + )} + + + }> + + setAlertRemove(false), + clickOutsideDeactivates: true, + escapeDeactivates: stopPropagation, + }} + > + +
    + + Remove Banner + + setAlertRemove(false)} radii="300"> + + +
    + + Are you sure you want to remove profile banner? + + +
    +
    +
    +
    +
    + ); +} + type RoomProfileProps = { permissions: RoomPermissionsAPI; }; @@ -325,6 +507,10 @@ export function RoomProfile({ permissions }: RoomProfileProps) { const handleCloseEdit = useCallback(() => setEdit(false), []); + const bannerState = useStateEvent(room, CustomStateEvent.RoomBanner); + const bannerMXC = bannerState?.getContent()?.url; + const bannerURI = mxcUrlToHttp(mx, bannerMXC ?? '', true); + return ( Profile @@ -393,6 +579,16 @@ export function RoomProfile({ permissions }: RoomProfileProps) { )} + {room.isSpaceRoom() && ( + + + + )}
    ); } diff --git a/src/app/features/common-settings/general/RoomUpgrade.tsx b/src/app/features/common-settings/general/RoomUpgrade.tsx index 0c1534f4a..70131e7f0 100644 --- a/src/app/features/common-settings/general/RoomUpgrade.tsx +++ b/src/app/features/common-settings/general/RoomUpgrade.tsx @@ -37,9 +37,9 @@ import { useAdditionalCreators, } from '$components/create-room'; import { useAlive } from '$hooks/useAlive'; -import { creatorsSupported } from '$utils/matrix'; import { useRoomCreators } from '$hooks/useRoomCreators'; import { BreakWord } from '$styles/Text.css'; +import { creatorsSupported } from '$utils/roomSupport'; function RoomUpgradeDialog({ requestClose }: { requestClose: () => void }) { const mx = useMatrixClient(); diff --git a/src/app/features/common-settings/members/Members.tsx b/src/app/features/common-settings/members/Members.tsx index 71ef0a74d..cfdc7615e 100644 --- a/src/app/features/common-settings/members/Members.tsx +++ b/src/app/features/common-settings/members/Members.tsx @@ -25,7 +25,7 @@ import { useGetMemberPowerLevel, usePowerLevels } from '$hooks/usePowerLevels'; import { VirtualTile } from '$components/virtualizer'; import { MemberTile } from '$components/member-tile'; import { useMediaAuthentication } from '$hooks/useMediaAuthentication'; -import { getMxIdLocalPart, getMxIdServer } from '$utils/matrix'; +import { getMxIdLocalPart } from '$utils/matrix'; import { ServerBadge } from '$components/server-badge'; import { useDebounce } from '$hooks/useDebounce'; import type { SearchItemStrGetter, UseAsyncSearchOptions } from '$hooks/useAsyncSearch'; @@ -44,6 +44,7 @@ import { useSpaceOptionally } from '$hooks/useSpace'; import { useFlattenPowerTagMembers, useGetMemberPowerTag } from '$hooks/useMemberPowerTag'; import { useRoomCreators } from '$hooks/useRoomCreators'; import { getMouseEventCords } from '$utils/dom'; +import { getMxIdServer } from '$utils/mxIdHelper'; const SEARCH_OPTIONS: UseAsyncSearchOptions = { limit: 1000, diff --git a/src/app/features/common-settings/permissions/PowersEditor.tsx b/src/app/features/common-settings/permissions/PowersEditor.tsx index be1cb7da6..ba43bafa0 100644 --- a/src/app/features/common-settings/permissions/PowersEditor.tsx +++ b/src/app/features/common-settings/permissions/PowersEditor.tsx @@ -41,14 +41,13 @@ import { CompactUploadCardRenderer } from '$components/upload-card'; import type { UploadSuccess } from '$state/upload'; import { createUploadAtom } from '$state/upload'; import { AsyncStatus, useAsyncCallback } from '$hooks/useAsyncCallback'; -import type { MemberPowerTag, MemberPowerTagIcon } from '$types/matrix/room'; +import { CustomStateEvent, type MemberPowerTag, type MemberPowerTagIcon } from '$types/matrix/room'; import { useAlive } from '$hooks/useAlive'; import { BetaNoticeBadge } from '$components/BetaNoticeBadge'; import { getPowerTagIconSrc } from '$hooks/useMemberPowerTag'; -import { creatorsSupported } from '$utils/matrix'; import { SequenceCardStyle } from '$features/common-settings/styles.css'; -import { CustomStateEvent } from '$types/matrix/room'; +import { creatorsSupported } from '$utils/roomSupport'; type EditPowerProps = { maxPower: number; diff --git a/src/app/features/create-chat/CreateChat.tsx b/src/app/features/create-chat/CreateChat.tsx index 0a6df5602..492e9a1c4 100644 --- a/src/app/features/create-chat/CreateChat.tsx +++ b/src/app/features/create-chat/CreateChat.tsx @@ -39,6 +39,9 @@ export function CreateChat({ defaultUserId }: CreateChatProps) { visibility: Visibility.Private, preset: Preset.TrustedPrivateChat, initial_state: initialState, + creation_content: { + additional_creators: [userId], + }, }); addRoomIdToMDirect(mx, result.room_id, userId); diff --git a/src/app/features/create-room/CreateRoom.tsx b/src/app/features/create-room/CreateRoom.tsx index 911fb455b..59b2ec571 100644 --- a/src/app/features/create-room/CreateRoom.tsx +++ b/src/app/features/create-room/CreateRoom.tsx @@ -18,12 +18,6 @@ import { } from 'folds'; import { SettingTile } from '$components/setting-tile'; import { SequenceCard } from '$components/sequence-card'; -import { - creatorsSupported, - knockRestrictedSupported, - knockSupported, - restrictedSupported, -} from '$utils/matrix'; import { useMatrixClient } from '$hooks/useMatrixClient'; import { millisecondsToMinutes, replaceSpaceWithDash } from '$utils/common'; import { AsyncStatus, useAsyncCallback } from '$hooks/useAsyncCallback'; @@ -44,6 +38,12 @@ import { import { CreateRoomTypeSelector } from '$components/create-room/CreateRoomTypeSelector'; import { getRoomIconSrc } from '$utils/room'; import { createDebugLogger } from '$utils/debugLogger'; +import { + restrictedSupported, + creatorsSupported, + knockSupported, + knockRestrictedSupported, +} from '$utils/roomSupport'; import { ErrorCode } from '../../cs-errorcode'; const debugLog = createDebugLogger('CreateRoom'); diff --git a/src/app/features/create-space/CreateSpace.tsx b/src/app/features/create-space/CreateSpace.tsx index 5a7c0f7b1..8518110ad 100644 --- a/src/app/features/create-space/CreateSpace.tsx +++ b/src/app/features/create-space/CreateSpace.tsx @@ -18,12 +18,6 @@ import { } from 'folds'; import { SettingTile } from '$components/setting-tile'; import { SequenceCard } from '$components/sequence-card'; -import { - creatorsSupported, - knockRestrictedSupported, - knockSupported, - restrictedSupported, -} from '$utils/matrix'; import { useMatrixClient } from '$hooks/useMatrixClient'; import { millisecondsToMinutes, replaceSpaceWithDash } from '$utils/common'; import { AsyncStatus, useAsyncCallback } from '$hooks/useAsyncCallback'; @@ -39,6 +33,12 @@ import { RoomVersionSelector, useAdditionalCreators, } from '$components/create-room'; +import { + restrictedSupported, + creatorsSupported, + knockSupported, + knockRestrictedSupported, +} from '$utils/roomSupport'; import { ErrorCode } from '../../cs-errorcode'; diff --git a/src/app/features/message-search/SearchResultGroup.tsx b/src/app/features/message-search/SearchResultGroup.tsx index cd244af71..93e8db401 100644 --- a/src/app/features/message-search/SearchResultGroup.tsx +++ b/src/app/features/message-search/SearchResultGroup.tsx @@ -56,6 +56,8 @@ import { import { useRoomCreators } from '$hooks/useRoomCreators'; import { useRoomCreatorsTag } from '$hooks/useRoomCreatorsTag'; import { useSettingsLinkBaseUrl } from '$features/settings/useSettingsLinkBaseUrl'; +import { useSetting } from '$state/hooks/settings'; +import { settingsAtom } from '$state/settings'; import type { ResultItem } from './useMessageSearch'; type SearchResultGroupProps = { @@ -95,6 +97,11 @@ export function SearchResultGroup({ const accessibleTagColors = useAccessiblePowerTagColors(theme.kind, creatorsTag, powerLevelTags); const nicknames = useAtomValue(nicknamesAtom); const settingsLinkBaseUrl = useSettingsLinkBaseUrl(); + const [incomingInlineImagesDefaultHeight] = useSetting( + settingsAtom, + 'incomingInlineImagesDefaultHeight' + ); + const [incomingInlineImagesMaxHeight] = useSetting(settingsAtom, 'incomingInlineImagesMaxHeight'); const mentionClickHandler = useMentionClickHandler(room.roomId); const spoilerClickHandler = useSpoilerClickHandler(); @@ -127,6 +134,8 @@ export function SearchResultGroup({ handleSpoilerClick: spoilerClickHandler, handleMentionClick: mentionClickHandler, nicknames, + incomingInlineImagesDefaultHeight, + incomingInlineImagesMaxHeight, }), [ mx, @@ -138,6 +147,8 @@ export function SearchResultGroup({ useAuthentication, nicknames, settingsLinkBaseUrl, + incomingInlineImagesDefaultHeight, + incomingInlineImagesMaxHeight, ] ); diff --git a/src/app/features/room-nav/RoomNavCategoryButton.tsx b/src/app/features/room-nav/RoomNavCategoryButton.tsx index 3df48aa7d..97f78d543 100644 --- a/src/app/features/room-nav/RoomNavCategoryButton.tsx +++ b/src/app/features/room-nav/RoomNavCategoryButton.tsx @@ -1,26 +1,48 @@ -import { as, Chip, Icon, Icons, Text } from 'folds'; +import { as, Chip, Icon, IconButton, Icons, Text } from 'folds'; import classNames from 'classnames'; import * as css from './styles.css'; export const RoomNavCategoryButton = as<'button', { closed?: boolean }>( - ({ className, closed, children, ...props }, ref) => ( - { + if (children) + return ( + + } + {...props} + ref={ref} + > + {children && ( + + {children} + + )} + + ); + return ( + - } - {...props} - ref={ref} - > - - {children} - - - ) + + ); + } ); diff --git a/src/app/features/room-nav/RoomNavItem.tsx b/src/app/features/room-nav/RoomNavItem.tsx index a372b975a..7262e8fbe 100644 --- a/src/app/features/room-nav/RoomNavItem.tsx +++ b/src/app/features/room-nav/RoomNavItem.tsx @@ -73,6 +73,7 @@ import { livekitSupport } from '$hooks/useLivekitSupport'; import { Presence, useUserPresence } from '$hooks/useUserPresence'; import { AvatarPresence, PresenceBadge } from '$components/presence'; import { RoomNavUser } from './RoomNavUser'; +import { SidebarUnreadBadge } from '$components/sidebar'; /** * Reactively checks whether a room has unread messages. @@ -252,6 +253,9 @@ const RoomNavItemMenu = forwardRef( } ); +export const hideTextStyling = (isHidden: boolean | undefined) => + isHidden ? { width: '100%', height: '100%', padding: '0', paddingTop: '0px' } : {}; + type RoomNavItemProps = { room: Room; selected: boolean; @@ -260,6 +264,8 @@ type RoomNavItemProps = { showAvatar?: boolean; direct?: boolean; customDMCards?: boolean; + hideText?: boolean; + joinCallOnSingleClick?: boolean; }; export function RoomNavItem({ @@ -270,6 +276,8 @@ export function RoomNavItem({ customDMCards, notificationMode, linkPath, + hideText, + joinCallOnSingleClick, }: RoomNavItemProps) { const mx = useMatrixClient(); const useAuthentication = useMediaAuthentication(); @@ -326,8 +334,8 @@ export function RoomNavItem({ if (!livekitSupport(autoDiscoveryInfo) && callMembers.length === 0) return; if (callEmbed && !isActiveCall) return; - if (!isMobile) { - if (!isActiveCall && !callEmbed) { + if (!isMobile && !hideText) { + if (!isActiveCall && !callEmbed && joinCallOnSingleClick) { startCall( room, new CallControlState(callPref.microphone, callPref.video, callPref.sound) @@ -374,205 +382,263 @@ export function RoomNavItem({ .flat() .filter(Boolean) .join(', '); - return ( - - + - - - - - ) - } + + + {roomName} + + ) + } + > + {(triggerRef) => ( + - - {showAvatar ? ( - + + + ) } - uniformIcons - alt={roomName} - renderFallback={() => ( - - {nameInitials(roomName)} - - )} - /> - ) : ( - - )} - - - - + + {showAvatar ? ( + ( + + {nameInitials(roomName)} + + )} + /> + ) : ( + + )} + + + {unread && hideText && ( + 0} + count={unread.highlight > 0 ? unread.highlight : unread.total} + /> + )} + + {!hideText && ( + <> + + + {roomName} + + {roomTopic && ( + + {roomTopic} + + )} + + {!optionsVisible && !unread && !selected && typingMember.length > 0 && ( + + + + )} + {!optionsVisible && shouldShowUnreadIndicator && ( + + 0} + count={unreadCount} + dm={direct} + /> + + )} + {!optionsVisible && notificationMode !== RoomNotificationMode.Unset && ( + + )} + {(room.isCallRoom() || direct) && + callMembers.length > 0 && + !optionsVisible && ( + + + + + {direct ? 'Calling' : `${callMembers.length} Live`} + + + + )} + + )} + + + + )} + + {optionsVisible && !hideText && ( + + {(room.isCallRoom() || (direct && callMembers.length > 0)) && ( + + {isChatOpen ? 'Hide Chat' : 'Show Chat'} + + } > - {roomName} - - {roomTopic && ( - ( + + + + )} + + )} + setMenuAnchor(undefined), + clickOutsideDeactivates: true, + isKeyForward: (evt: KeyboardEvent) => evt.key === 'ArrowDown', + isKeyBackward: (evt: KeyboardEvent) => evt.key === 'ArrowUp', + escapeDeactivates: stopPropagation, }} > - {roomTopic} - - )} - - {!optionsVisible && !unread && !selected && typingMember.length > 0 && ( - - - - )} - {!optionsVisible && shouldShowUnreadIndicator && ( - - 0} - count={unreadCount} - dm={direct} - /> - - )} - {!optionsVisible && notificationMode !== RoomNotificationMode.Unset && ( - - )} - {(room.isCallRoom() || direct) && callMembers.length > 0 && !optionsVisible && ( - - - - - {direct ? 'Calling' : `${callMembers.length} Live`} - - - - )} - - - - {optionsVisible && ( - - {(room.isCallRoom() || (direct && callMembers.length > 0)) && ( - - {isChatOpen ? 'Hide Chat' : 'Show Chat'} - + setMenuAnchor(undefined)} + notificationMode={notificationMode} + /> + } > - {(triggerRef) => ( + {!hideText && ( - + )} - - )} - setMenuAnchor(undefined), - clickOutsideDeactivates: true, - isKeyForward: (evt: KeyboardEvent) => evt.key === 'ArrowDown', - isKeyBackward: (evt: KeyboardEvent) => evt.key === 'ArrowUp', - escapeDeactivates: stopPropagation, - }} - > - setMenuAnchor(undefined)} - notificationMode={notificationMode} - /> - - } - > - - - - - - )} - - + + + )} + +
    {room.isCallRoom() && ( - + {callMembers.map((callMembership) => ( ))} )} - + ); } diff --git a/src/app/features/room-nav/RoomNavUser.tsx b/src/app/features/room-nav/RoomNavUser.tsx index c574b1b3d..488545b32 100644 --- a/src/app/features/room-nav/RoomNavUser.tsx +++ b/src/app/features/room-nav/RoomNavUser.tsx @@ -16,9 +16,10 @@ import { useCallEmbed } from '$hooks/useCallEmbed'; type RoomNavUserProps = { room: Room; callMembership: CallMembership; + hideText?: boolean; }; -export function RoomNavUser({ room, callMembership }: RoomNavUserProps) { +export function RoomNavUser({ room, callMembership, hideText }: RoomNavUserProps) { const mx = useMatrixClient(); const useAuthentication = useMediaAuthentication(); const openProfile = useOpenUserRoomProfile(); @@ -45,9 +46,9 @@ export function RoomNavUser({ room, callMembership }: RoomNavUserProps) { return ( - + - + } /> - - {name} - + {!hideText && ( + + {name} + + )} diff --git a/src/app/features/room/CallChatView.tsx b/src/app/features/room/CallChatView.tsx index 3acc8c562..e73842f94 100644 --- a/src/app/features/room/CallChatView.tsx +++ b/src/app/features/room/CallChatView.tsx @@ -5,6 +5,11 @@ import { Page, PageHeader } from '../../components/page'; import { callChatAtom } from '../../state/callEmbed'; import { RoomView } from './RoomView'; import { ScreenSize, useScreenSizeContext } from '../../hooks/useScreenSize'; +import { SidebarResizer } from '$pages/client/sidebar/SidebarResizer'; +import { useSetting } from '$state/hooks/settings'; +import { settingsAtom } from '$state/settings'; +import { mobileOrTablet } from '$utils/user-agent'; +import { useState, useEffect } from 'react'; export function CallChatView() { const { eventId } = useParams(); @@ -13,44 +18,69 @@ export function CallChatView() { const handleClose = () => setChat(false); + const [vcmsgSidebarWidth, setVcmsgSidebarWidth] = useSetting(settingsAtom, 'vcmsgSidebarWidth'); + const [curWidth, setCurWidth] = useState(vcmsgSidebarWidth); + useEffect(() => { + setCurWidth(vcmsgSidebarWidth); + }, [vcmsgSidebarWidth]); return ( - - - - - - Chat - - - - - Close - - } - > - {(triggerRef) => ( - - - - )} - + {!mobileOrTablet() && ( + + )} + + + + + + Chat + + + + + Close + + } + > + {(triggerRef) => ( + + + + )} + + + + + - - - - - + + ); } diff --git a/src/app/features/room/MembersDrawer.css.ts b/src/app/features/room/MembersDrawer.css.ts index 860ceda01..56ba79641 100644 --- a/src/app/features/room/MembersDrawer.css.ts +++ b/src/app/features/room/MembersDrawer.css.ts @@ -7,7 +7,7 @@ export const MembersDrawer = style({ export const MembersDrawerHeader = style({ flexShrink: 0, - padding: `0 ${config.space.S200} 0 ${config.space.S300}`, + padding: `0 ${config.space.S200} 0 ${config.space.S200}`, borderBottomWidth: config.borderWidth.B300, }); diff --git a/src/app/features/room/MembersDrawer.tsx b/src/app/features/room/MembersDrawer.tsx index f751bcf31..2641899d4 100644 --- a/src/app/features/room/MembersDrawer.tsx +++ b/src/app/features/room/MembersDrawer.tsx @@ -1,5 +1,5 @@ import type { ChangeEventHandler, MouseEventHandler } from 'react'; -import { useCallback, useMemo, useRef, useState } from 'react'; +import { useCallback, useEffect, useMemo, useRef, useState } from 'react'; import type { RectCords } from 'folds'; import { Avatar, @@ -56,21 +56,27 @@ import { useRoomCreators } from '$hooks/useRoomCreators'; import { useSableCosmetics } from '$hooks/useSableCosmetics'; import { formatCompactNumber } from '$utils/formatCompactNumber'; import * as css from './MembersDrawer.css'; +import { SidebarResizer } from '$pages/client/sidebar/SidebarResizer'; +import { mobileOrTablet } from '$utils/user-agent'; +import { useScreenSizeContext, ScreenSize } from '$hooks/useScreenSize'; type MemberDrawerHeaderProps = { room: Room; + hideText?: boolean; }; -function MemberDrawerHeader({ room }: MemberDrawerHeaderProps) { +function MemberDrawerHeader({ room, hideText }: MemberDrawerHeaderProps) { const setPeopleDrawer = useSetSetting(settingsAtom, 'isPeopleDrawer'); return (
    - - - {`${formatCompactNumber(room.getJoinedMemberCount())} Members`} - - + {!hideText && ( + + + {`${formatCompactNumber(room.getJoinedMemberCount())} Members`} + + + )} ; pressed?: boolean; typing?: boolean; + hideText?: boolean; }; function MemberItem({ mx, @@ -115,6 +122,7 @@ function MemberItem({ onClick, pressed, typing, + hideText, }: MemberItemProps) { const nicknames = useAtomValue(nicknamesAtom); const name = @@ -130,7 +138,47 @@ function MemberItem({ const presence = useUserPresence(member.userId); const { color, font } = useSableCosmetics(member.userId, room); + const MemberAvatar = ( +
    + + ) : undefined + } + > + + } + /> + + +
    + ); + if (hideText) + return ( + + {MemberAvatar} + + ); return ( - - ) : undefined - } - > - - } - /> - - -
    - } + before={MemberAvatar} after={ typing && ( @@ -275,6 +296,8 @@ export function MembersDrawer({ room, members }: MembersDrawerProps) { ); const handleMemberClick: MouseEventHandler = (evt) => { + // oxlint-disable-next-line no-console + console.log(evt); const btn = evt.currentTarget as HTMLButtonElement; const userId = btn.getAttribute('data-user-id'); if (!userId) return; @@ -286,138 +309,174 @@ export function MembersDrawer({ room, members }: MembersDrawerProps) { openUserRoomProfile(room.roomId, space?.roomId, userId, cords, 'Left'); }; + const [memberSidebarWidth, setMemberSidebarWidth] = useSetting( + settingsAtom, + 'memberSidebarWidth' + ); + const [curWidth, setCurWidth] = useState(memberSidebarWidth); + useEffect(() => { + setCurWidth(memberSidebarWidth); + }, [memberSidebarWidth]); + + const screenSize = useScreenSizeContext(); + const isMobile = mobileOrTablet() || screenSize === ScreenSize.Mobile; + const hideText = curWidth <= 80 && !isMobile; return ( - + + {!mobileOrTablet() && ( + + )} - - - - {(anchor: RectCords | undefined, setAnchor) => ( - setAnchor(undefined)} - /> - } - > - - setAnchor( - evt.currentTarget.getBoundingClientRect() - )) as MouseEventHandler - } - variant="Background" - size="400" - radii="300" - before={} - > - {membershipFilter.name} - - - )} - - - {(anchor: RectCords | undefined, setAnchor) => ( - setAnchor(undefined)} - /> - } - > - - setAnchor( - evt.currentTarget.getBoundingClientRect() - )) as MouseEventHandler - } - variant="Background" - size="400" - radii="300" - after={} - > - {memberSort.name} - - - )} - - - - } - after={ - result && ( - 0 ? 'Success' : 'Critical'} - size="400" - radii="Pill" - aria-pressed - onClick={() => { - if (searchInputRef.current) { - searchInputRef.current.value = ''; - searchInputRef.current.focus(); + {!hideText && ( + <> + + + + {(anchor: RectCords | undefined, setAnchor) => ( + setAnchor(undefined)} + /> } - resetSearch(); - }} - after={} - > - {`${result.items.length || 'No'} ${ - result.items.length === 1 ? 'Result' : 'Results' - }`} - - ) - } - /> - - + > + + setAnchor( + evt.currentTarget.getBoundingClientRect() + )) as MouseEventHandler + } + variant="Background" + size="400" + radii="300" + before={} + > + {membershipFilter.name} + + + )} + + + {(anchor: RectCords | undefined, setAnchor) => ( + setAnchor(undefined)} + /> + } + > + + setAnchor( + evt.currentTarget.getBoundingClientRect() + )) as MouseEventHandler + } + variant="Background" + size="400" + radii="300" + after={} + > + {memberSort.name} + + + )} + + + + } + after={ + result && ( + 0 ? 'Success' : 'Critical'} + size="400" + radii="Pill" + aria-pressed + onClick={() => { + if (searchInputRef.current) { + searchInputRef.current.value = ''; + searchInputRef.current.focus(); + } + resetSearch(); + }} + after={} + > + {`${result.items.length || 'No'} ${ + result.items.length === 1 ? 'Result' : 'Results' + }`} + + ) + } + /> + + - - virtualizer.scrollToOffset(0)} - variant="Surface" - radii="Pill" - outlined - size="300" - aria-label="Scroll to Top" - > - - - + + virtualizer.scrollToOffset(0)} + variant="Surface" + radii="Pill" + outlined + size="300" + aria-label="Scroll to Top" + > + + + - {!fetchingMembers && !result && processMembers.length === 0 && ( - - {`No "${membershipFilter.name}" Members`} - + {!fetchingMembers && !result && processMembers.length === 0 && ( + + {`No "${membershipFilter.name}" Members`} + + )} + )} -
    {tagOrMember.name} @@ -465,6 +525,7 @@ export function MembersDrawer({ room, members }: MembersDrawerProps) { typing={typingMembers.some( (receipt) => receipt.userId === tagOrMember.userId )} + hideText={hideText} />
    ); diff --git a/src/app/features/room/RoomInput.tsx b/src/app/features/room/RoomInput.tsx index ed2fdb695..69f67248b 100644 --- a/src/app/features/room/RoomInput.tsx +++ b/src/app/features/room/RoomInput.tsx @@ -1,6 +1,7 @@ import type { KeyboardEventHandler, MouseEvent, RefObject } from 'react'; import { forwardRef, useCallback, useEffect, useRef, useState, useMemo } from 'react'; -import { useAtom, useAtomValue } from 'jotai'; +import { useAtom, useAtomValue, useSetAtom } from 'jotai'; + import { isKeyHotkey } from 'is-hotkey'; import type { IContent, @@ -10,6 +11,7 @@ import type { RoomMessageEventContent, StickerEventContent, } from '$types/matrix-sdk'; +import { MatrixError } from '$types/matrix-sdk'; import { EventType, MsgType, RelationType } from '$types/matrix-sdk'; import { ReactEditor } from 'slate-react'; import { Editor, Point, Range, Transforms } from 'slate'; @@ -22,7 +24,6 @@ import { Icon, IconButton, Icons, - Line, Menu, MenuItem, Overlay, @@ -46,7 +47,6 @@ import { resetEditor, RoomMentionAutocomplete, toMatrixCustomHTML, - Toolbar, toPlainText, trimCustomHtml, UserMentionAutocomplete, @@ -59,7 +59,13 @@ import { getMentions, ANYWHERE_AUTOCOMPLETE_PREFIXES, BEGINNING_AUTOCOMPLETE_PREFIXES, + getLinks, + MarkdownFormattingToolbarBottom, + MarkdownFormattingToolbarToggle, + replaceWithElement, + BlockType, } from '$components/editor'; +import { plainToEditorInput } from '$components/editor/input'; import { EmojiBoard, EmojiBoardTab } from '$components/emoji-board'; import { UseStateProvider } from '$components/UseStateProvider'; import type { TUploadContent } from '$utils/matrix'; @@ -85,7 +91,7 @@ import { safeFile } from '$utils/mimeTypes'; import { fulfilledPromiseSettledResult } from '$utils/common'; import { useSetting } from '$state/hooks/settings'; import { settingsAtom } from '$state/settings'; -import { getMentionContent, reactionOrEditEvent } from '$utils/room'; +import { getMentionContent, isThreadRelationEvent, reactionOrEditEvent } from '$utils/room'; import { Command, SHRUG, TABLEFLIP, UNFLIP, useCommands } from '$hooks/useCommands'; import { mobileOrTablet } from '$utils/user-agent'; import { useElementSizeObserver } from '$hooks/useElementSizeObserver'; @@ -104,6 +110,7 @@ import { delayedEventsSupportedAtom, roomIdToScheduledTimeAtomFamily, roomIdToEditingScheduledDelayIdAtomFamily, + serverMaxDelayMsAtom, } from '$state/scheduledMessages'; import { sendDelayedMessage, @@ -111,7 +118,7 @@ import { computeDelayMs, cancelDelayedEvent, } from '$utils/delayedEvents'; -import { timeHourMinute, timeDayMonthYear } from '$utils/time'; +import { timeHourMinute, timeDayMonthYear, daysToMs } from '$utils/time'; import { stopPropagation } from '$utils/keyboard'; import { usePowerLevelsContext } from '$hooks/usePowerLevels'; @@ -124,9 +131,17 @@ import { } from '$hooks/usePerMessageProfile'; import { Microphone, Stop } from '@phosphor-icons/react'; import { getSupportedAudioExtension } from '$plugins/voice-recorder-kit/supportedCodec'; +import { ErrorCode } from '../../cs-errorcode'; import { sanitizeText } from '$utils/sanitize'; import { PKitCommandMessageHandler } from '$plugins/pluralkit-handler/PKitCommandMessageHandler'; import { PKitProxyMessageHandler } from '$plugins/pluralkit-handler/PKitProxyMessageHandler'; +import type { IGenericMSC4459, MSC4459ImagePackReference } from '$types/matrix/common'; +import { + getImagePackReferencesForMxc, + getImagePackReferencesForMxcWrappedInMap, +} from '$utils/msc4459helper'; +import { ImageUsage } from '$plugins/custom-emoji'; +import { SerializableMap } from '$types/wrapper/SerializableMap'; import { useSettingsLinkBaseUrl } from '$features/settings/useSettingsLinkBaseUrl'; import { SchedulePickerDialog } from './schedule-send'; import * as css from './schedule-send/SchedulePickerDialog.css'; @@ -143,6 +158,7 @@ import type { AudioRecordingCompletePayload, } from './AudioMessageRecorder'; import { AudioMessageRecorder } from './AudioMessageRecorder'; +import * as prefix from '$unstable/prefixes'; // Returns the event ID of the most recent non-reaction/non-edit event in a thread, // falling back to the thread root if no replies exist yet. @@ -150,7 +166,10 @@ const getLatestThreadEventId = (room: Room, threadRootId: string): string => { const thread = room.getThread(threadRootId); const threadEvents: MatrixEvent[] = thread?.events ?? []; const filtered = threadEvents.filter( - (ev) => ev.getId() !== threadRootId && !reactionOrEditEvent(ev) + (ev) => + ev.getId() !== threadRootId && + !reactionOrEditEvent(ev) && + isThreadRelationEvent(ev, threadRootId) ); if (filtered.length > 0) { return filtered[filtered.length - 1]!.getId() ?? threadRootId; @@ -162,10 +181,12 @@ const getLatestThreadEventId = (room: Room, threadRootId: string): string => { .getEvents() .filter( (ev) => - ev.threadRootId === threadRootId && ev.getId() !== threadRootId && !reactionOrEditEvent(ev) + ev.getId() !== threadRootId && + !reactionOrEditEvent(ev) && + isThreadRelationEvent(ev, threadRootId) ); if (liveEvents.length > 0) { - return liveEvents[liveEvents.length - 1]!.getId() ?? threadRootId; + return liveEvents.at(-1)!.getId() ?? threadRootId; } return threadRootId; }; @@ -180,10 +201,11 @@ const getReplyContent = (replyDraft: IReplyDraft | undefined, room?: Room): IEve relatesTo.event_id = replyDraft.relation.event_id; relatesTo.rel_type = RelationType.Thread; - // Check if this is a reply to a specific message in the thread + // If the user explicitly clicked "reply" on a message (including the thread root), + // we must set is_falling_back=false and target that message directly. // (replyDraft.body being empty means it's just a seeded thread draft) - if (replyDraft.body && replyDraft.eventId !== replyDraft.relation.event_id) { - // Explicit reply to a specific message — per spec, is_falling_back must be false + if (replyDraft.body) { + // Explicit reply — per spec, is_falling_back must be false relatesTo['m.in_reply_to'] = { event_id: replyDraft.eventId, }; @@ -233,11 +255,12 @@ export const RoomInput = forwardRef( const mx = useMatrixClient(); const useAuthentication = useMediaAuthentication(); const [enterForNewline] = useSetting(settingsAtom, 'enterForNewline'); - const [isMarkdown] = useSetting(settingsAtom, 'isMarkdown'); + const [hideActivity] = useSetting(settingsAtom, 'hideActivity'); const [mentionInReplies] = useSetting(settingsAtom, 'mentionInReplies'); const settingsLinkBaseUrl = useSettingsLinkBaseUrl(); const commands = useCommands(mx, room); + const imagePacksUsedRef = useRef(new SerializableMap()); /** * handle pluralkit-style messages */ @@ -284,7 +307,6 @@ export const RoomInput = forwardRef( const imagePackRooms: Room[] = useImagePackRooms(roomId, roomToParents); - const [toolbar, setToolbar] = useSetting(settingsAtom, 'editorToolbar'); const [showAudioRecorder, setShowAudioRecorder] = useState(false); const audioRecorderRef = useRef(null); const micHoldStartRef = useRef(0); @@ -293,7 +315,7 @@ export const RoomInput = forwardRef( useState>(); const [isQuickTextReact, setQuickTextReact] = useState(false); - const sendTypingStatus = useTypingStatusUpdater(mx, roomId); + const sendTypingStatus = useTypingStatusUpdater(mx, roomId, { disabled: !!threadRootId }); const [inputKey, setInputKey] = useState(0); const getUploadItemKey = useCallback((fileItem: TUploadItem): string => { @@ -363,6 +385,8 @@ export const RoomInput = forwardRef( const [showSchedulePicker, setShowSchedulePicker] = useState(false); const [silentReply, setSilentReply] = useState(!mentionInReplies); const [hour24Clock] = useSetting(settingsAtom, 'hour24Clock'); + const setServerMaxDelayMs = useSetAtom(serverMaxDelayMsAtom); + const [sendError, setSendError] = useState(); const isEncrypted = room.hasEncryptionStateEvent(); useElementSizeObserver( @@ -505,7 +529,7 @@ export const RoomInput = forwardRef( }; const handleSendUpload = async (uploads: UploadSuccess[]) => { - const plainText = toPlainText(editor.children, isMarkdown).trim(); + const plainText = toPlainText(editor.children).trim(); const contentsPromises = uploads.map(async (upload) => { const fileItem = selectedFiles.find((f) => f.file === upload.file); @@ -537,10 +561,8 @@ export const RoomInput = forwardRef( // We intentionally mutate the objects here to avoid unnecessary copying // mutating should be unproblematic here, since contents isn't a react component, // or used for rendering - c['com.beeper.per_message_profile'] = convertPerMessageProfileToBeeperFormat( - perMessageProfile, - false - ); + c[prefix.MATRIX_UNSTABLE_PER_MESSAGE_PROFILE_PROPERTY_NAME] = + convertPerMessageProfileToBeeperFormat(perMessageProfile, false); }); } @@ -718,8 +740,26 @@ export const RoomInput = forwardRef( * the plain text we will send */ let serializedChildren = editor.children; + if (commandName) { + // Strip the empty text node and command node from the beginning of the first paragraph + const firstPara = serializedChildren[0]; + if ( + firstPara && + 'type' in firstPara && + firstPara.type === BlockType.Paragraph && + firstPara.children.length >= 2 + ) { + serializedChildren = [ + { + ...firstPara, + children: firstPara.children.slice(2), + }, + ...serializedChildren.slice(1), + ]; + } + } const outgoingTransformContext = { - isMarkdown, + isMarkdown: true, settingsLinkBaseUrl, }; @@ -728,19 +768,19 @@ export const RoomInput = forwardRef( serializedChildren = transform.apply(serializedChildren, outgoingTransformContext); }); - let plainText = toPlainText(serializedChildren, isMarkdown, true, nicknameReplacement).trim(); + let plainText = toPlainText(serializedChildren, true, nicknameReplacement).trim(); + /** * the html we will send */ let customHtml = trimCustomHtml( toMatrixCustomHTML(serializedChildren, { - allowTextFormatting: true, - allowBlockMarkdown: isMarkdown, - allowInlineMarkdown: isMarkdown, stripNickname: true, nickNameReplacement: nicknameReplacement, + forEmote: commandName === Command.Me, }) ); + let msgType = MsgType.Text; // quick text react @@ -751,7 +791,7 @@ export const RoomInput = forwardRef( // check if its a pk command if (pkCompatEnable && PKitCommandMessageHandler.isPKCommand(plainText)) { - pluralkitCmdMessageHandler.handleMessage(plainText); + await pluralkitCmdMessageHandler.handleMessage(plainText); resetEditor(editor); // clear the editor return; // don't do anything besides handling the command } @@ -787,6 +827,38 @@ export const RoomInput = forwardRef( if (plainText === '') return; + // PluralKit-style proxy wrappers (per-message profile proxies) must be stripped + // *before* building `content`, otherwise we end up sending the wrapper verbatim. + let proxiedPerMessageProfile: + | Awaited> + | undefined; + if (pmpProxyingEnable) { + proxiedPerMessageProfile = + await pluralkitProxyMessageHandler.getPmpBasedOnMessage(plainText); + if (proxiedPerMessageProfile) { + const stripped = pluralkitProxyMessageHandler.stripProxyFromMessage(plainText); + if (stripped !== undefined) { + // Re-run the normal outgoing pipeline on the stripped content so the message + // goes through the same transforms/parsers as any other message. + serializedChildren = plainToEditorInput(stripped); + + outgoingMessageTransforms.forEach((transform) => { + if (!transform.shouldApply(serializedChildren, outgoingTransformContext)) return; + serializedChildren = transform.apply(serializedChildren, outgoingTransformContext); + }); + + plainText = toPlainText(serializedChildren, true, nicknameReplacement).trim(); + customHtml = trimCustomHtml( + toMatrixCustomHTML(serializedChildren, { + stripNickname: true, + nickNameReplacement: nicknameReplacement, + forEmote: commandName === Command.Me, + }) + ); + } + } + } + const body = plainText; const formattedBody = customHtml; const mentionData = getMentions(mx, roomId, editor); @@ -801,6 +873,16 @@ export const RoomInput = forwardRef( } content['m.mentions'] = getMentionContent(Array.from(mentionData.users), mentionData.room); + content[prefix.MATRIX_UNSTABLE_IMAGE_SOURCE_PACK_PROPERTY_NAME] = + imagePacksUsedRef.current.toJSON(); + + const links = getLinks(serializedChildren); + content[prefix.MATRIX_UNSTABLE_EMBEDDED_LINK_PREVIEW_PROPERTY_NAME] = []; + links?.forEach((link) => + content[prefix.MATRIX_UNSTABLE_EMBEDDED_LINK_PREVIEW_PROPERTY_NAME].push({ + matched_url: link, + }) + ); if (replyDraft || !customHtmlEqualsPlainText(formattedBody, body)) { content.format = 'org.matrix.custom.html'; @@ -812,26 +894,24 @@ export const RoomInput = forwardRef( * This allows the server to apply the correct profile-based transformations (e.g. font size adjustments) when processing the message, * and also allows clients to display an accurate preview of how the message will look with the profile applied while it's being composed. */ - const perMessageProfile = - pmpProxyingEnable && pluralkitProxyMessageHandler.isAProxiedMessage(plainText) - ? await pluralkitProxyMessageHandler.getPmpBasedOnMessage(plainText) - : await getCurrentlyUsedPerMessageProfileForRoom(mx, roomId); - - if (pmpProxyingEnable && pluralkitProxyMessageHandler.isAProxiedMessage(plainText)) - plainText = pluralkitProxyMessageHandler.stripProxyFromMessage(plainText) ?? plainText; + let perMessageProfile = await getCurrentlyUsedPerMessageProfileForRoom(mx, roomId); + if (pmpProxyingEnable) { + if (proxiedPerMessageProfile) perMessageProfile = proxiedPerMessageProfile; + } if (perMessageProfile) { - content['com.beeper.per_message_profile'] = convertPerMessageProfileToBeeperFormat( - perMessageProfile, - perMessageProfile.name.trim() !== '' - ); + content[prefix.MATRIX_UNSTABLE_PER_MESSAGE_PROFILE_PROPERTY_NAME] = + convertPerMessageProfileToBeeperFormat( + perMessageProfile, + perMessageProfile.name.trim() !== '' + ); if (perMessageProfile.name.trim() !== '') { // if a per-message profile is used, it must per spec include a fallback - const prefix = `${perMessageProfile.name}: `; + const pmpPrefix = `${perMessageProfile.name}: `; - if (!content.body.startsWith(prefix)) { + if (!content.body.startsWith(pmpPrefix)) { // to prevent double-prefixing when the fallback is already present - content.body = prefix + content.body; + content.body = pmpPrefix + content.body; } /** @@ -846,7 +926,8 @@ export const RoomInput = forwardRef( } else { // we don't have a formatted body, but we need one content.format = 'org.matrix.custom.html'; - content.formatted_body = `${htmlPrefix}${plainText}`; + const escapedBody = sanitizeText(plainText).replaceAll('\n', '
    '); + content.formatted_body = `${htmlPrefix}${escapedBody}`; } } } @@ -861,6 +942,7 @@ export const RoomInput = forwardRef( resetEditor(editor); resetEditorHistory(editor); setInputKey((prev) => prev + 1); + imagePacksUsedRef.current.clear(); if (threadRootId) { // Re-seed the thread reply draft so the next message also goes to the thread. setReplyDraft({ @@ -885,12 +967,28 @@ export const RoomInput = forwardRef( } else { await sendDelayedMessage(mx, roomId, content as RoomMessageEventContent, delayMs); } + setSendError(undefined); invalidate(); setEditingScheduledDelayId(null); setScheduledTime(null); resetInput(); - } catch { - // Network/server error — leave editor and scheduled state intact for retry + } catch (e: unknown) { + if ( + e instanceof MatrixError && + (e.errcode === ErrorCode.M_MAX_DELAY_EXCEEDED || + e.data?.['org.matrix.msc4140.errcode'] === 'M_MAX_DELAY_EXCEEDED') + ) { + const maxDelay = + (e.data as { max_delay?: number })?.max_delay ?? + e.data?.['org.matrix.msc4140.max_delay']; + if (typeof maxDelay === 'number') setServerMaxDelayMs(maxDelay); + const maxDelayDays = maxDelay / daysToMs(1); + setSendError( + `Scheduled time exceeds the maximum delay allowed by this server. Please choose an earlier time. The Maximum Delay is of ${maxDelayDays} day${maxDelayDays > 1 ? 's' : ''}.` + ); + } else { + setSendError('Failed to schedule message. Please try again.'); + } } } else if (editingScheduledDelayId) { try { @@ -960,7 +1058,6 @@ export const RoomInput = forwardRef( replyEvent, mx, roomId, - isMarkdown, canSendReaction, pkCompatEnable, replyDraft, @@ -982,6 +1079,7 @@ export const RoomInput = forwardRef( isEncrypted, setEditingScheduledDelayId, setScheduledTime, + setServerMaxDelayMs, ]); const handleKeyDown: KeyboardEventHandler = useCallback( @@ -1109,8 +1207,18 @@ export const RoomInput = forwardRef( ); const handleEmoticonSelect = (key: string, shortcode: string) => { - editor.insertNode(createEmoticonElement(key, shortcode)); + const emoticonEl = createEmoticonElement(key, shortcode); + if (autocompleteQuery) { + replaceWithElement(editor, autocompleteQuery.range, emoticonEl); + } else { + editor.insertNode(emoticonEl); + } + if (!imagePacksUsedRef.current.has(key)) { + const imgPkRef = getImagePackReferencesForMxc(key, mx, ImageUsage.Emoticon, room); + if (imgPkRef?.room_id && imgPkRef?.shortcode) imagePacksUsedRef.current.set(key, imgPkRef); + } moveCursor(editor); + handleCloseAutocomplete(); }; const handleStickerSelect = async (mxc: string, shortcode: string, label: string) => { @@ -1122,12 +1230,16 @@ export const RoomInput = forwardRef( await getImageUrlBlob(stickerUrl) ); - const content: StickerEventContent & ReplyEventContent & IContent = { + const content: StickerEventContent & ReplyEventContent & IContent & IGenericMSC4459 = { body: label, url: mxc, info, }; + // add the image pack reference + content[prefix.MATRIX_UNSTABLE_IMAGE_SOURCE_PACK_PROPERTY_NAME] = + getImagePackReferencesForMxcWrappedInMap(mxc, mx, ImageUsage.Sticker, room); + /** * the currently with the room associated per-message profile, if any, so that it can be included in the message content when sending. * This allows the server to apply the correct profile-based transformations (e.g. font size adjustments) when processing the message, @@ -1136,11 +1248,11 @@ export const RoomInput = forwardRef( const perMessageProfile = await getCurrentlyUsedPerMessageProfileForRoom(mx, roomId); if (perMessageProfile) { - content['com.beeper.per_message_profile'] = convertPerMessageProfileToBeeperFormat( - perMessageProfile, - false - ); + content[prefix.MATRIX_UNSTABLE_PER_MESSAGE_PROFILE_PROPERTY_NAME] = + convertPerMessageProfileToBeeperFormat(perMessageProfile, false); } + content[prefix.MATRIX_UNSTABLE_IMAGE_SOURCE_PACK_PROPERTY_NAME] = + getImagePackReferencesForMxcWrappedInMap(mxc, mx, ImageUsage.Sticker, room); if (replyDraft) { content['m.relates_to'] = getReplyContent(replyDraft, room); @@ -1239,6 +1351,7 @@ export const RoomInput = forwardRef( editor={editor} query={autocompleteQuery} requestClose={handleCloseAutocomplete} + onEmoticonSelected={handleEmoticonSelect} /> )} {autocompleteQuery?.prefix === AutocompletePrefix.Reaction && @@ -1297,6 +1410,7 @@ export const RoomInput = forwardRef( onClick={() => { setScheduledTime(null); setEditingScheduledDelayId(null); + setSendError(undefined); }} variant="SurfaceVariant" size="300" @@ -1315,6 +1429,19 @@ export const RoomInput = forwardRef(
    )} + {sendError && ( +
    + + + {sendError} + + +
    + )} {replyDraft && (!threadRootId || replyDraft.body) && (
    ( )} - setToolbar(!toolbar)} - > - - + + {(emojiBoardTab: EmojiBoardTab | undefined, setEmojiBoardTab) => ( ( } - bottom={ - toolbar && ( -
    - - -
    - ) - } + bottom={} /> {showSchedulePicker && ( ( onSubmit={(date) => { setScheduledTime(date); setShowSchedulePicker(false); + setSendError(undefined); }} /> )} diff --git a/src/app/features/room/RoomTimeline.tsx b/src/app/features/room/RoomTimeline.tsx index 6eca94eaf..92f82061b 100644 --- a/src/app/features/room/RoomTimeline.tsx +++ b/src/app/features/room/RoomTimeline.tsx @@ -45,6 +45,7 @@ import { factoryRenderLinkifyWithMention, } from '$plugins/react-custom-html-parser'; import { today, yesterday, timeDayMonthYear } from '$utils/time'; +import { unwrapRelationJumpTarget } from '$utils/room'; import { useMemberEventParser } from '$hooks/useMemberEventParser'; import { usePowerLevelsContext } from '$hooks/usePowerLevels'; import { useRoomCreators } from '$hooks/useRoomCreators'; @@ -77,8 +78,11 @@ import { } from '$utils/timeline'; import { useTimelineSync } from '$hooks/timeline/useTimelineSync'; import { useTimelineActions } from '$hooks/timeline/useTimelineActions'; -import type { ProcessedEvent } from '$hooks/timeline/useProcessedTimeline'; -import { useProcessedTimeline } from '$hooks/timeline/useProcessedTimeline'; +import { + useProcessedTimeline, + getProcessedRowIndexForRawTimelineIndex, + type ProcessedEvent, +} from '$hooks/timeline/useProcessedTimeline'; import { useTimelineEventRenderer } from '$hooks/timeline/useTimelineEventRenderer'; import * as css from './RoomTimeline.css'; @@ -151,6 +155,11 @@ export function RoomTimeline({ const [dateFormatString] = useSetting(settingsAtom, 'dateFormatString'); const [autoplayStickers] = useSetting(settingsAtom, 'autoplayStickers'); const [autoplayEmojis] = useSetting(settingsAtom, 'autoplayEmojis'); + const [incomingInlineImagesDefaultHeight] = useSetting( + settingsAtom, + 'incomingInlineImagesDefaultHeight' + ); + const [incomingInlineImagesMaxHeight] = useSetting(settingsAtom, 'incomingInlineImagesMaxHeight'); const [hideMemberInReadOnly] = useSetting(settingsAtom, 'hideMembershipInReadOnly'); const showUrlPreview = room.hasEncryptionStateEvent() ? encUrlPreview : urlPreview; @@ -494,19 +503,40 @@ export function RoomTimeline({ setOpenThread: setOpenThread as unknown as (threadId: string | undefined) => void, handleEdit, handleOpenEvent: (id) => { - const evtTimeline = getEventTimeline(room, id); + const anchorId = unwrapRelationJumpTarget(room, id); + let evtTimeline = getEventTimeline(room, anchorId); + let resolvedForIndex = anchorId; + if (!evtTimeline && anchorId !== id) { + evtTimeline = getEventTimeline(room, id); + resolvedForIndex = id; + } const absoluteIndex = evtTimeline - ? getEventIdAbsoluteIndex(timelineSync.timeline.linkedTimelines, evtTimeline, id) + ? getEventIdAbsoluteIndex( + timelineSync.timeline.linkedTimelines, + evtTimeline, + resolvedForIndex + ) : undefined; if (typeof absoluteIndex === 'number') { - const processedIndex = getRawIndexToProcessedIndex(absoluteIndex); + let processedIndex = getRawIndexToProcessedIndex(absoluteIndex); + let focusRawIndex = absoluteIndex; + if (processedIndex === undefined) { + const nearest = getProcessedRowIndexForRawTimelineIndex( + processedEventsRef.current, + absoluteIndex + ); + if (nearest) { + processedIndex = nearest.rowIndex; + focusRawIndex = nearest.focusRawIndex; + } + } if (vListRef.current && processedIndex !== undefined) { vListRef.current.scrollToIndex(processedIndex, { align: 'center' }); } - timelineSync.setFocusItem({ index: absoluteIndex, scrollTo: false, highlight: true }); + timelineSync.setFocusItem({ index: focusRawIndex, scrollTo: false, highlight: true }); } else { - void timelineSync.loadEventTimeline(id); + void timelineSync.loadEventTimeline(anchorId); } }, }); @@ -542,6 +572,8 @@ export function RoomTimeline({ handleMentionClick: mentionClickHandler, nicknames, autoplayEmojis, + incomingInlineImagesDefaultHeight, + incomingInlineImagesMaxHeight, replaceTextNode: buildAbbrReplaceTextNode(abbrMap, linkifyOpts), }), [ @@ -549,6 +581,8 @@ export function RoomTimeline({ room.roomId, linkifyOpts, autoplayEmojis, + incomingInlineImagesDefaultHeight, + incomingInlineImagesMaxHeight, mentionClickHandler, nicknames, mediaAuthentication, diff --git a/src/app/features/room/RoomView.tsx b/src/app/features/room/RoomView.tsx index 90afe3498..a5329bed4 100644 --- a/src/app/features/room/RoomView.tsx +++ b/src/app/features/room/RoomView.tsx @@ -1,7 +1,7 @@ import { useCallback, useRef, useState } from 'react'; import { useAtomValue } from 'jotai'; import { Transforms } from 'slate'; -import { Box, Text, config, toRem } from 'folds'; +import { Box, Text, config } from 'folds'; import { EventType } from '$types/matrix-sdk'; import { ReactEditor } from 'slate-react'; import { isKeyHotkey } from 'is-hotkey'; @@ -141,14 +141,7 @@ export function RoomView({ eventId }: { eventId?: string }) { return ( {(onBack) => ( - + {showCallView && ( diff --git a/src/app/features/room/RoomViewFollowing.tsx b/src/app/features/room/RoomViewFollowing.tsx index e33101b19..979ee6507 100644 --- a/src/app/features/room/RoomViewFollowing.tsx +++ b/src/app/features/room/RoomViewFollowing.tsx @@ -1,28 +1,15 @@ -import { useState } from 'react'; -import { - Box, - Icon, - Icons, - Modal, - Overlay, - OverlayBackdrop, - OverlayCenter, - Text, - as, - config, -} from 'folds'; +import { useAtomValue } from 'jotai'; +import { Box, Icon, Icons, Text, as, config } from 'folds'; import type { Room } from '$types/matrix-sdk'; import classNames from 'classnames'; -import FocusTrap from 'focus-trap-react'; -import { useAtomValue } from 'jotai'; +import { useAtom } from 'jotai'; import { getMemberDisplayName } from '$utils/room'; import { getMxIdLocalPart } from '$utils/matrix'; import { useMatrixClient } from '$hooks/useMatrixClient'; import { useRoomLatestRenderedEvent } from '$hooks/useRoomLatestRenderedEvent'; import { useRoomEventReaders } from '$hooks/useRoomEventReaders'; -import { EventReaders } from '$components/event-readers'; -import { stopPropagation } from '$utils/keyboard'; +import { modalAtom, ModalType } from '$state/modal'; import { nicknamesAtom } from '$state/nicknames'; import * as css from './RoomViewFollowing.css'; @@ -38,7 +25,7 @@ export type RoomViewFollowingProps = { export const RoomViewFollowing = as<'div', RoomViewFollowingProps>( ({ className, room, threadEventId, participantIds, ...props }, ref) => { const mx = useMatrixClient(); - const [open, setOpen] = useState(false); + const [, setModal] = useAtom(modalAtom); const latestEvent = useRoomLatestRenderedEvent(room); const resolvedEventId = threadEventId ?? latestEvent?.getId(); const latestEventReaders = useRoomEventReaders(room, resolvedEventId); @@ -54,150 +41,138 @@ export const RoomViewFollowing = as<'div', RoomViewFollowingProps>( const eventId = resolvedEventId; return ( - <> - {eventId && ( - }> - - setOpen(false), - clickOutsideDeactivates: true, - escapeDeactivates: stopPropagation, - }} - > - - setOpen(false)} /> - - - - + 0 ? 'button' : 'div'} + onClick={ + names.length > 0 + ? () => { + if (eventId) { + setModal({ type: ModalType.ReadReceipts, room, eventId }); + } + } + : undefined + } + className={classNames(css.RoomViewFollowing({ clickable: names.length > 0 }), className)} + alignItems="Center" + justifyContent="End" + gap="200" + {...props} + ref={ref} + > + {names.length > 0 && ( + <> + + + {names.length === 1 && ( + <> + {names[0]} + + {' is following the conversation.'} + + + )} + {names.length === 2 && ( + <> + {names[0]} + + {' and '} + + {names[1]} + + {' are following the conversation.'} + + + )} + {names.length === 3 && ( + <> + {names[0]} + + {', '} + + {names[1]} + + {' and '} + + {names[2]} + + {' are following the conversation.'} + + + )} + {names.length > 3 && ( + <> + {names[0]} + + {', '} + + {names[1]} + + {', '} + + {names[2]} + + {' and '} + + {names.length - 3} others + + {' are following the conversation.'} + + + )} + + )} - 0 ? 'button' : 'div'} - onClick={names.length > 0 ? () => setOpen(true) : undefined} - className={classNames(css.RoomViewFollowing({ clickable: names.length > 0 }), className)} - alignItems="Center" - justifyContent="End" - gap="200" - {...props} - ref={ref} - > - {names.length > 0 && ( - <> - - - {names.length === 1 && ( - <> - {names[0]} - - {' is following the conversation.'} - - - )} - {names.length === 2 && ( - <> - {names[0]} - - {' and '} - - {names[1]} - - {' are following the conversation.'} - - - )} - {names.length === 3 && ( - <> - {names[0]} - - {', '} - - {names[1]} - - {' and '} - - {names[2]} - - {' are following the conversation.'} - - - )} - {names.length > 3 && ( - <> - {names[0]} - - {', '} - - {names[1]} - - {', '} - - {names[2]} - - {' and '} - - {names.length - 3} others - - {' are following the conversation.'} - - - )} - - - )} - - + ); } ); diff --git a/src/app/features/room/RoomViewHeader.tsx b/src/app/features/room/RoomViewHeader.tsx index c804f54ab..f45e6172f 100644 --- a/src/app/features/room/RoomViewHeader.tsx +++ b/src/app/features/room/RoomViewHeader.tsx @@ -82,6 +82,7 @@ import { useRoomPermissions } from '$hooks/useRoomPermissions'; import { InviteUserPrompt } from '$components/invite-user-prompt'; import { ContainerColor } from '$styles/ContainerColor.css'; import { useRoomWidgets } from '$hooks/useRoomWidgets'; +import { hasThreadRootAggregation, isThreadRelationEvent } from '$utils/room'; import { DirectInvitePrompt } from '$components/direct-invite-prompt'; import { AsyncStatus, useAsyncCallback } from '$hooks/useAsyncCallback'; @@ -439,8 +440,9 @@ export function RoomViewHeader({ callView }: Readonly<{ callView?: boolean }>) { // 1. Events that ARE thread roots (have isThreadRoot = true or have replies) // 2. Events that are IN threads (have threadRootId) events.forEach((event: MatrixEvent) => { - // Check if this event is a thread root - if (event.isThreadRoot) { + // Check if this event is an actual thread root. `isThreadRoot` can be + // polluted by locally-created Thread shells, so require the server bundle. + if (hasThreadRootAggregation(event)) { const rootId = event.getId(); if (rootId && !room.getThread(rootId)) { threadRoots.add(rootId); @@ -449,7 +451,11 @@ export function RoomViewHeader({ callView }: Readonly<{ callView?: boolean }>) { // Check if this event is a reply in a thread const { threadRootId } = event; - if (threadRootId && !room.getThread(threadRootId)) { + if ( + threadRootId && + isThreadRelationEvent(event, threadRootId) && + !room.getThread(threadRootId) + ) { threadRoots.add(threadRootId); } }); @@ -476,8 +482,9 @@ export function RoomViewHeader({ callView }: Readonly<{ callView?: boolean }>) { // Listen for new timeline events (including pagination) const handleTimelineEvent = (mEvent: MatrixEvent) => { - // Check if this event is a thread root - if (mEvent.isThreadRoot) { + // Check if this event is an actual thread root. `isThreadRoot` can be + // polluted by locally-created Thread shells, so require the server bundle. + if (hasThreadRootAggregation(mEvent)) { const rootId = mEvent.getId(); if (rootId && !room.getThread(rootId)) { const rootEvent = room.findEventById(rootId); @@ -489,7 +496,11 @@ export function RoomViewHeader({ callView }: Readonly<{ callView?: boolean }>) { // Check if this is a reply in a thread const { threadRootId } = mEvent; - if (threadRootId && !room.getThread(threadRootId)) { + if ( + threadRootId && + isThreadRelationEvent(mEvent, threadRootId) && + !room.getThread(threadRootId) + ) { const rootEvent = room.findEventById(threadRootId); if (rootEvent) { room.createThread(threadRootId, rootEvent, [], false); diff --git a/src/app/features/room/ThreadBrowser.tsx b/src/app/features/room/ThreadBrowser.tsx index f9891eeda..766889032 100644 --- a/src/app/features/room/ThreadBrowser.tsx +++ b/src/app/features/room/ThreadBrowser.tsx @@ -13,6 +13,7 @@ import { Avatar, config, Chip, + toRem, } from 'folds'; import type { EventTimelineSet, MatrixEvent, Room, Thread } from '$types/matrix-sdk'; import { NotificationCountType, RoomEvent, ThreadEvent } from '$types/matrix-sdk'; @@ -52,6 +53,8 @@ import { import { UnreadBadge, UnreadBadgeCenter } from '$components/unread-badge'; import { EncryptedContent } from './message'; import * as css from './ThreadDrawer.css'; +import { SidebarResizer } from '$pages/client/sidebar/SidebarResizer'; +import { mobileOrTablet } from '$utils/user-agent'; type ThreadPreviewProps = { room: Room; @@ -436,12 +439,34 @@ export function ThreadBrowser({ room, onOpenThread, onClose, overlay }: ThreadBr setQuery(e.target.value); }; + const [threadSidebarWidth, setThreadSidebarWidth] = useSetting( + settingsAtom, + 'threadSidebarWidth' + ); + const [curWidth, setCurWidth] = useState(threadSidebarWidth); + useEffect(() => { + setCurWidth(threadSidebarWidth); + }, [threadSidebarWidth]); return ( + {!mobileOrTablet() && ( + + )}
    diff --git a/src/app/features/room/ThreadDrawer.css.ts b/src/app/features/room/ThreadDrawer.css.ts index 4b2d9c1a1..607f2ac06 100644 --- a/src/app/features/room/ThreadDrawer.css.ts +++ b/src/app/features/room/ThreadDrawer.css.ts @@ -1,8 +1,7 @@ import { style, globalStyle } from '@vanilla-extract/css'; -import { config, color, toRem } from 'folds'; +import { config, color } from 'folds'; export const ThreadDrawer = style({ - width: toRem(440), height: '100%', display: 'flex', flexDirection: 'column', @@ -29,6 +28,23 @@ export const ThreadDrawerHeader = style({ borderBottomWidth: config.borderWidth.B300, }); +export const threadRootShell = style({ + position: 'relative', + display: 'flex', + flexDirection: 'column', + flexShrink: 0, +}); + +export const threadRootScrollShadow = style({ + position: 'relative', + flexShrink: 0, + zIndex: 1, + boxShadow: config.shadow.E100, + borderBottomWidth: config.borderWidth.B300, + borderBottomStyle: 'solid', + borderBottomColor: color.Surface.ContainerLine, +}); + export const ThreadDrawerContent = style({ position: 'relative', overflow: 'hidden', diff --git a/src/app/features/room/ThreadDrawer.test.ts b/src/app/features/room/ThreadDrawer.test.ts index 51eebd904..fc4263a04 100644 --- a/src/app/features/room/ThreadDrawer.test.ts +++ b/src/app/features/room/ThreadDrawer.test.ts @@ -23,13 +23,16 @@ type EventInit = { threadRootId?: string; /** When set, the event is treated as a reaction/annotation */ relType?: string; + /** Relation target event id */ + relEventId?: string; }; -function makeEvent({ id, threadRootId, relType }: EventInit) { +function makeEvent({ id, threadRootId, relType, relEventId }: EventInit) { return { getId: () => id, threadRootId, - getRelation: () => (relType ? { rel_type: relType } : null), + getRelation: () => (relType ? { rel_type: relType, event_id: relEventId } : null), + getWireContent: () => ({}), getContent: () => ({}), }; } @@ -61,7 +64,12 @@ const REACTION_ID = '$reaction-event-id'; describe('getThreadReplyEvents', () => { it('returns thread events minus the root when the Thread object has replies', () => { const rootEvent = makeEvent({ id: ROOT_ID, threadRootId: ROOT_ID }); - const replyEvent = makeEvent({ id: REPLY_ID, threadRootId: ROOT_ID }); + const replyEvent = makeEvent({ + id: REPLY_ID, + threadRootId: ROOT_ID, + relType: RelationType.Thread, + relEventId: ROOT_ID, + }); const room = makeRoom({ thread: { events: [rootEvent, replyEvent] as any }, @@ -76,11 +84,17 @@ describe('getThreadReplyEvents', () => { it('excludes reactions from thread events', () => { const rootEvent = makeEvent({ id: ROOT_ID, threadRootId: ROOT_ID }); - const replyEvent = makeEvent({ id: REPLY_ID, threadRootId: ROOT_ID }); + const replyEvent = makeEvent({ + id: REPLY_ID, + threadRootId: ROOT_ID, + relType: RelationType.Thread, + relEventId: ROOT_ID, + }); const reactionEvent = makeEvent({ id: REACTION_ID, threadRootId: ROOT_ID, relType: RelationType.Annotation, + relEventId: REPLY_ID, }); const room = makeRoom({ @@ -99,7 +113,12 @@ describe('getThreadReplyEvents', () => { it('falls back to the live timeline when thread.events contains only the root (classic-sync case)', () => { // classic sync: thread created with no initialEvents → events = [rootEvent] const rootEvent = makeEvent({ id: ROOT_ID, threadRootId: ROOT_ID }); - const liveReply = makeEvent({ id: REPLY_ID, threadRootId: ROOT_ID }); + const liveReply = makeEvent({ + id: REPLY_ID, + threadRootId: ROOT_ID, + relType: RelationType.Thread, + relEventId: ROOT_ID, + }); const room = makeRoom({ thread: { events: [rootEvent] as any }, @@ -115,7 +134,12 @@ describe('getThreadReplyEvents', () => { }); it('falls back to the live timeline when there is no Thread object at all', () => { - const liveReply = makeEvent({ id: REPLY_ID, threadRootId: ROOT_ID }); + const liveReply = makeEvent({ + id: REPLY_ID, + threadRootId: ROOT_ID, + relType: RelationType.Thread, + relEventId: ROOT_ID, + }); const room = makeRoom({ thread: null, @@ -129,8 +153,18 @@ describe('getThreadReplyEvents', () => { }); it('excludes events from the live timeline that belong to a different thread', () => { - const otherReply = makeEvent({ id: '$other-reply', threadRootId: '$other-root' }); - const ourReply = makeEvent({ id: REPLY_ID, threadRootId: ROOT_ID }); + const otherReply = makeEvent({ + id: '$other-reply', + threadRootId: '$other-root', + relType: RelationType.Thread, + relEventId: '$other-root', + }); + const ourReply = makeEvent({ + id: REPLY_ID, + threadRootId: ROOT_ID, + relType: RelationType.Thread, + relEventId: ROOT_ID, + }); const room = makeRoom({ thread: null, @@ -155,4 +189,25 @@ describe('getThreadReplyEvents', () => { expect(result).toHaveLength(0); }); + + it('excludes non-thread replies even if the SDK has assigned the same threadRootId', () => { + const rootEvent = makeEvent({ id: ROOT_ID, threadRootId: ROOT_ID }); + const plainReply = makeEvent({ id: '$plain-reply', threadRootId: ROOT_ID }); + const threadReply = makeEvent({ + id: REPLY_ID, + threadRootId: ROOT_ID, + relType: RelationType.Thread, + relEventId: ROOT_ID, + }); + + const room = makeRoom({ + thread: { events: [rootEvent] as any }, + liveEvents: [plainReply as any, threadReply as any], + }); + + const result = getThreadReplyEvents(room as any, ROOT_ID); + + expect(result).toHaveLength(1); + expect(result[0]?.getId()).toBe(REPLY_ID); + }); }); diff --git a/src/app/features/room/ThreadDrawer.tsx b/src/app/features/room/ThreadDrawer.tsx index 3171e3ba4..070cdaf58 100644 --- a/src/app/features/room/ThreadDrawer.tsx +++ b/src/app/features/room/ThreadDrawer.tsx @@ -1,6 +1,6 @@ import type { MouseEventHandler } from 'react'; import { useCallback, useEffect, useMemo, useRef, useState } from 'react'; -import { Box, Header, Icon, IconButton, Icons, Scroll, Spinner, Text, config } from 'folds'; +import { Box, Header, Icon, IconButton, Icons, Scroll, Spinner, Text, config, toRem } from 'folds'; import type { IEvent, Room } from '$types/matrix-sdk'; import { Direction, @@ -23,7 +23,13 @@ import { makeMentionCustomProps, renderMatrixMention, } from '$plugins/react-custom-html-parser'; -import { getEditedEvent, getMemberDisplayName, reactionOrEditEvent } from '$utils/room'; +import { + getEditedEvent, + getMemberDisplayName, + isThreadRelationEvent, + reactionOrEditEvent, + unwrapRelationJumpTarget, +} from '$utils/room'; import { getMxIdLocalPart, toggleReaction } from '$utils/matrix'; import { useMatrixClient } from '$hooks/useMatrixClient'; import { useMediaAuthentication } from '$hooks/useMediaAuthentication'; @@ -49,12 +55,17 @@ import { useIgnoredUsers } from '$hooks/useIgnoredUsers'; import { useGetMemberPowerTag } from '$hooks/useMemberPowerTag'; import { useMemberEventParser } from '$hooks/useMemberEventParser'; import { useMessageEdit } from '$hooks/useMessageEdit'; -import type { ProcessedEvent } from '$hooks/timeline/useProcessedTimeline'; -import { useProcessedTimeline } from '$hooks/timeline/useProcessedTimeline'; +import { + useProcessedTimeline, + getProcessedRowIndexForRawTimelineIndex, + type ProcessedEvent, +} from '$hooks/timeline/useProcessedTimeline'; import { useTimelineEventRenderer } from '$hooks/timeline/useTimelineEventRenderer'; import { RoomInput } from './RoomInput'; import { RoomViewFollowing, RoomViewFollowingPlaceholder } from './RoomViewFollowing'; import * as css from './ThreadDrawer.css'; +import { SidebarResizer } from '$pages/client/sidebar/SidebarResizer'; +import { mobileOrTablet } from '$utils/user-agent'; /** * Resolve the list of reply events to show in the thread drawer. @@ -71,7 +82,10 @@ export function getThreadReplyEvents(room: Room, threadRootId: string): MatrixEv const thread = room.getThread(threadRootId); const fromThread = thread?.events ?? []; const filteredFromThread = fromThread.filter( - (ev) => ev.getId() !== threadRootId && !reactionOrEditEvent(ev) + (ev) => + ev.getId() !== threadRootId && + !reactionOrEditEvent(ev) && + isThreadRelationEvent(ev, threadRootId) ); if (filteredFromThread.length > 0) { return filteredFromThread; @@ -82,7 +96,9 @@ export function getThreadReplyEvents(room: Room, threadRootId: string): MatrixEv .getEvents() .filter( (ev) => - ev.threadRootId === threadRootId && ev.getId() !== threadRootId && !reactionOrEditEvent(ev) + ev.getId() !== threadRootId && + !reactionOrEditEvent(ev) && + isThreadRelationEvent(ev, threadRootId) ); } @@ -301,7 +317,10 @@ export function ThreadDrawer({ room, threadRootId, onClose, overlay }: ThreadDra // thread.events is still empty (classic sync path; server-side was already // populated by paginateEventTimeline inside updateThreadMetadata). const hasRepliesInThread = currThread.events.some( - (ev) => ev.getId() !== threadRootId && !reactionOrEditEvent(ev) + (ev) => + ev.getId() !== threadRootId && + !reactionOrEditEvent(ev) && + isThreadRelationEvent(ev, threadRootId) ); if (hasRepliesInThread) return; @@ -311,9 +330,9 @@ export function ThreadDrawer({ room, threadRootId, onClose, overlay }: ThreadDra .getEvents() .filter( (ev) => - ev.threadRootId === threadRootId && ev.getId() !== threadRootId && - !reactionOrEditEvent(ev) + !reactionOrEditEvent(ev) && + isThreadRelationEvent(ev, threadRootId) ); if (liveEvents.length > 0) { // thread.addEvents() is typed as void but is internally async; schedule @@ -338,7 +357,7 @@ export function ThreadDrawer({ room, threadRootId, onClose, overlay }: ThreadDra useEffect(() => { const isEventInThread = (mEvent: MatrixEvent): boolean => { // Direct thread message or the root itself - if (mEvent.threadRootId === threadRootId || mEvent.getId() === threadRootId) { + if (mEvent.getId() === threadRootId || isThreadRelationEvent(mEvent, threadRootId)) { return true; } @@ -350,7 +369,8 @@ export function ThreadDrawer({ room, threadRootId, onClose, overlay }: ThreadDra const targetEvent = room.findEventById(targetEventId); if ( targetEvent && - (targetEvent.threadRootId === threadRootId || targetEvent.getId() === threadRootId) + (targetEvent.getId() === threadRootId || + isThreadRelationEvent(targetEvent, threadRootId)) ) { return true; } @@ -627,18 +647,32 @@ export function ThreadDrawer({ room, threadRootId, onClose, overlay }: ThreadDra (evt) => { const targetId = evt.currentTarget.getAttribute('data-event-id'); if (!targetId) return; - const isRoot = targetId === threadRootId; - const isInReplies = processedEventsRef.current.some((e) => e.id === targetId); + let anchorId = unwrapRelationJumpTarget(room, targetId); + const threadLive = thread?.timelineSet.getLiveTimeline(); + const threadEvents = threadLive?.getEvents(); + const rawIndex = threadEvents?.findIndex((e) => e.getId() === anchorId) ?? -1; + if (rawIndex >= 0) { + const nearest = getProcessedRowIndexForRawTimelineIndex( + processedEventsRef.current, + rawIndex + ); + if (nearest) { + const rowEv = processedEventsRef.current[nearest.rowIndex]; + if (rowEv) anchorId = rowEv.id; + } + } + const isRoot = anchorId === threadRootId; + const isInReplies = processedEventsRef.current.some((e) => e.id === anchorId); if (!isRoot && !isInReplies) return; - setJumpToEventId(targetId); + setJumpToEventId(anchorId); setTimeout(() => setJumpToEventId(undefined), 2500); const el = drawerRef.current; if (el) { - const target = el.querySelector(`[data-message-id="${targetId}"]`); + const target = el.querySelector(`[data-message-id="${anchorId}"]`); target?.scrollIntoView({ block: 'nearest', behavior: 'smooth' }); } }, - [threadRootId] + [threadRootId, room, thread] ); // Map jumpToEventId to a focusItem index for useTimelineEventRenderer highlighting @@ -704,13 +738,40 @@ export function ThreadDrawer({ room, threadRootId, onClose, overlay }: ThreadDra ); const latestThreadEventId = processedEvents.at(-1)?.id ?? rootEvent?.getId(); + const [threadSidebarWidth, setThreadSidebarWidth] = useSetting( + settingsAtom, + 'threadSidebarWidth' + ); + const [curWidth, setCurWidth] = useState(threadSidebarWidth); + useEffect(() => { + setCurWidth(threadSidebarWidth); + }, [threadSidebarWidth]); + + const [threadRootHeight, setThreadRootHeight] = useSetting(settingsAtom, 'threadRootHeight'); + const [curHeight, setCurHeight] = useState(threadRootHeight); + useEffect(() => { + setCurHeight(threadRootHeight); + }, [threadRootHeight]); return ( + {!mobileOrTablet() && ( + + )} {/* Header */}
    @@ -734,38 +795,48 @@ export function ThreadDrawer({ room, threadRootId, onClose, overlay }: ThreadDra {/* Thread root message */} {rootEvent && ( - - - {renderMatrixEvent( - rootEvent.getType(), - typeof rootEvent.getStateKey() === 'string', - rootEvent.getId()!, - rootEvent, - processedEvents.find((e) => e.id === threadRootId)?.itemIndex ?? 0, - thread?.timelineSet ?? room.getUnfilteredTimelineSet(), - false - )} + + + + + {renderMatrixEvent( + rootEvent.getType(), + typeof rootEvent.getStateKey() === 'string', + rootEvent.getId()!, + rootEvent, + processedEvents.find((e) => e.id === threadRootId)?.itemIndex ?? 0, + thread?.timelineSet ?? room.getUnfilteredTimelineSet(), + false + )} + + - + + )} - {/* Replies */} lang.trim().toLowerCase()) + .map((lang: string) => lang.trim().toLowerCase()) .filter(Boolean); /** @@ -447,11 +453,12 @@ function MessageInternal( // Avatars // Prefer the room-scoped member avatar (m.room.member) over the global profile // avatar so per-room avatar overrides are respected in the timeline. + const memberAvatarMxc = getMemberAvatarMxc(room, senderId); const avatarUrl = useMemo(() => { if (collapse) return undefined; - const mxc = pmp?.avatar_url || getMemberAvatarMxc(room, senderId) || profile.avatarUrl; + const mxc = pmp?.avatar_url || memberAvatarMxc || profile.avatarUrl; return mxc ? mxcUrlToHttp(mx, mxc, useAuthentication, 48, 48, 'crop') : undefined; - }, [pmp, collapse, profile.avatarUrl, senderId, mx, room, useAuthentication]); + }, [pmp, collapse, memberAvatarMxc, profile.avatarUrl, mx, useAuthentication]); const cachedAvatar = useBlobCache(avatarUrl ?? undefined); @@ -626,12 +633,18 @@ function MessageInternal( const mentionClickHandler = useMentionClickHandler(room.roomId); const forwardedNotice = useMemo(() => { + const isSameRoomForward = (originalRoomId: string | undefined) => + originalRoomId !== undefined && originalRoomId === room.roomId; + if (messageForwardedProps?.isForwarded) { + const originalRoomId = messageForwardedProps.originalRoomId; return { label: messageForwardedProps.originalEventPrivate ? 'Forwarded private message' - : 'Forwarded from another room', - roomId: messageForwardedProps.originalRoomId, + : isSameRoomForward(originalRoomId) + ? 'Forwarded from earlier in this room' + : 'Forwarded from another room', + roomId: originalRoomId, eventId: messageForwardedProps.originalEventId, ts: messageForwardedProps.originalTimestamp ?? 0, showLink: !messageForwardedProps.originalEventPrivate, @@ -639,9 +652,12 @@ function MessageInternal( } if (msc2723ForwardedMessageProps) { + const originalRoomId = msc2723ForwardedMessageProps.room_id; return { - label: 'Forwarded from another room', - roomId: msc2723ForwardedMessageProps.room_id, + label: isSameRoomForward(originalRoomId) + ? 'Forwarded from earlier in this room' + : 'Forwarded from another room', + roomId: originalRoomId, eventId: msc2723ForwardedMessageProps.event_id, ts: msc2723ForwardedMessageProps.origin_server_ts ?? 0, showLink: true, @@ -649,7 +665,7 @@ function MessageInternal( } return null; - }, [messageForwardedProps, msc2723ForwardedMessageProps]); + }, [messageForwardedProps, msc2723ForwardedMessageProps, room.roomId]); const handleResendClick: MouseEventHandler = useCallback( (evt) => { @@ -839,7 +855,7 @@ function MessageInternal( setMobileOptionsOpen(true); }); - const isThreadedMessage = mEvent.threadRootId !== undefined; + const isThreadedMessage = isThreadRelationEvent(mEvent, mEvent.threadRootId); const isStickerMessage = mEvent.getType() === 'm.sticker'; const evtId = mEvent.getId()!; diff --git a/src/app/features/room/message/MessageEditor.tsx b/src/app/features/room/message/MessageEditor.tsx index edcb4c4c3..307d17998 100644 --- a/src/app/features/room/message/MessageEditor.tsx +++ b/src/app/features/room/message/MessageEditor.tsx @@ -1,7 +1,7 @@ import type { KeyboardEventHandler, MouseEventHandler } from 'react'; import { useCallback, useEffect, useMemo, useState } from 'react'; import type { RectCords } from 'folds'; -import { Box, Chip, Icon, IconButton, Icons, Line, PopOut, Spinner, Text, as, config } from 'folds'; +import { Box, Chip, Icon, IconButton, Icons, PopOut, Spinner, Text, as, config } from 'folds'; import { Editor, Transforms } from 'slate'; import { ReactEditor } from 'slate-react'; import type { @@ -20,14 +20,14 @@ import { AutocompletePrefix, CustomEditor, EmoticonAutocomplete, + MarkdownFormattingToolbarBottom, + MarkdownFormattingToolbarToggle, RoomMentionAutocomplete, - Toolbar, UserMentionAutocomplete, createEmoticonElement, customHtmlEqualsPlainText, getAutocompleteQuery, getPrevWorldRange, - htmlToEditorInput, moveCursor, plainToEditorInput, toMatrixCustomHTML, @@ -36,7 +36,10 @@ import { useEditor, getMentions, ANYWHERE_AUTOCOMPLETE_PREFIXES, + getLinks, + LINKINPUTREGEX, } from '$components/editor'; +import { htmlToMarkdown } from '$plugins/markdown'; import { useSetting } from '$state/hooks/settings'; import { CaptionPosition, settingsAtom } from '$state/settings'; import { UseStateProvider } from '$components/UseStateProvider'; @@ -56,6 +59,11 @@ import { useMediaAuthentication } from '$hooks/useMediaAuthentication'; import type { Opts as LinkifyOpts } from 'linkifyjs'; import type { GetContentCallback } from '$types/matrix/room'; import { sanitizeText } from '$utils/sanitize'; +import type { BundleContent } from '$components/message'; +import { + readdAngleBracketsForHiddenPreviews, + stripMarkdownEscapesForHiddenPreviews, +} from './hiddenLinkPreviews'; type MessageEditorProps = { roomId: string; @@ -69,9 +77,6 @@ export const MessageEditor = as<'div', MessageEditorProps>( const mx = useMatrixClient(); const editor = useEditor(); const [enterForNewline] = useSetting(settingsAtom, 'enterForNewline'); - const [globalToolbar] = useSetting(settingsAtom, 'editorToolbar'); - const [isMarkdown] = useSetting(settingsAtom, 'isMarkdown'); - const [toolbar, setToolbar] = useState(globalToolbar); const isComposing = useComposingCheck(); const [autocompleteQuery, setAutocompleteQuery] = @@ -116,9 +121,48 @@ export const MessageEditor = as<'div', MessageEditorProps>( ); } + const bundleContent = content['com.beeper.linkpreviews'] as BundleContent[]; + const markHiddenLinks = (original: string, isHTML?: boolean) => { + if (!bundleContent) return original; + if (!isHTML) { + return readdAngleBracketsForHiddenPreviews(original, bundleContent); + } + /* Split according to the following fule: + - if its not HTML just break it by spaces, newLines, and parans + - if it is HTML + - break it before before any potential opening tag + - break it whenever a tag starts + - break it after a closing tag + - then for every non portion find regular links as though it is plaintext + * this is not recursive but needs flattening + */ + const splitBody = original.split(/(?=^.+<)|(?=)|(?=)/gi); + let newBody = ''; + splitBody + .map((item) => (item.startsWith(' acc.concat(current), []) + .map((s) => { + // the length is from the fact that a link is necessarily longer than 6 + if (s.length < 6 || s.startsWith('')) { + newBody += s; + return; + } + // since the way that the match works the key is at the start of the string, + // it needs to be separated such that it can be reintroduced before the < in case of regular text + // or after it in case that it is matching a tag + const strippedS = s.substring(1); + const isHidden = + (bundleContent?.length === 0 || + bundleContent.filter((b) => s.includes(b.matched_url)).length === 0) && + strippedS.match(LINKINPUTREGEX) !== null; + newBody += `${isHidden ? (isHTML && ((s.startsWith('' : ''}`; + }); + return newBody; + }; + return [ - typeof body === 'string' ? body : undefined, - typeof customHtml === 'string' ? customHtml : undefined, + typeof body === 'string' ? markHiddenLinks(body) : undefined, + typeof customHtml === 'string' ? markHiddenLinks(customHtml, true) : undefined, mMentions, ]; }, [room, mEvent]); @@ -126,13 +170,10 @@ export const MessageEditor = as<'div', MessageEditorProps>( const [saveState, save] = useAsyncCallback( useCallback(async () => { const oldContent = mEvent.getContent(); - let plainText = toPlainText(editor.children, isMarkdown).trim(); + const msgtype = mEvent.getContent().msgtype as RoomMessageTextEventContent['msgtype']; + let plainText = toPlainText(editor.children).trim(); let customHtml = trimCustomHtml( - toMatrixCustomHTML(editor.children, { - allowTextFormatting: true, - allowBlockMarkdown: isMarkdown, - allowInlineMarkdown: isMarkdown, - }) + toMatrixCustomHTML(editor.children, { forEmote: msgtype === MsgType.Emote }) ); const [prevBody, prevCustomHtml, prevMentions] = getPrevBodyAndFormattedBody(); @@ -154,8 +195,6 @@ export const MessageEditor = as<'div', MessageEditorProps>( } } - const msgtype = mEvent.getContent().msgtype as RoomMessageTextEventContent['msgtype']; - const newContent: IContent = { msgtype, body: plainText, @@ -212,7 +251,9 @@ export const MessageEditor = as<'div', MessageEditorProps>( newContent['m.mentions'] = mMentions; contentBody['m.mentions'] = mMentions; - if (!customHtmlEqualsPlainText(customHtml, plainText)) { + const links = getLinks(editor.children); + + if (pmpDisplayname || !customHtmlEqualsPlainText(customHtml, plainText)) { newContent.format = 'org.matrix.custom.html'; newContent.formatted_body = customHtml; contentBody.format = 'org.matrix.custom.html'; @@ -246,9 +287,12 @@ export const MessageEditor = as<'div', MessageEditorProps>( oldContent['page.codeberg.everypizza.msc4193.spoiler']; } } + content['com.beeper.linkpreviews'] = []; + links?.forEach((link) => content['com.beeper.linkpreviews'].push({ matched_url: link })); + content['m.new_content']['com.beeper.linkpreviews'] = content['com.beeper.linkpreviews']; return mx.sendMessage(roomId, content as RoomMessageEventContent); - }, [mx, editor, roomId, mEvent, isMarkdown, getPrevBodyAndFormattedBody, room]) + }, [mx, editor, roomId, mEvent, getPrevBodyAndFormattedBody, room]) ); const handleSave = useCallback(() => { @@ -310,10 +354,13 @@ export const MessageEditor = as<'div', MessageEditorProps>( useEffect(() => { const [body, customHtml] = getPrevBodyAndFormattedBody(); - const initialValue = - typeof customHtml === 'string' - ? htmlToEditorInput(customHtml, isMarkdown) - : plainToEditorInput(typeof body === 'string' ? body : '', isMarkdown); + const initialValue = plainToEditorInput( + customHtml + ? stripMarkdownEscapesForHiddenPreviews(htmlToMarkdown(customHtml)) + : typeof body === 'string' + ? body + : '' + ); Transforms.select(editor, { anchor: Editor.start(editor, []), @@ -322,7 +369,7 @@ export const MessageEditor = as<'div', MessageEditorProps>( editor.insertFragment(initialValue); if (!mobileOrTablet()) ReactEditor.focus(editor); - }, [editor, getPrevBodyAndFormattedBody, isMarkdown]); + }, [editor, getPrevBodyAndFormattedBody]); useEffect(() => { if (saveState.status === AsyncStatus.Success) { @@ -334,6 +381,14 @@ export const MessageEditor = as<'div', MessageEditorProps>( const settingsLinkBaseUrl = useSettingsLinkBaseUrl(); const linkifyOpts = useMemo(() => ({ ...LINKIFY_OPTS }), []); const spoilerClickHandler = useSpoilerClickHandler(); + const [incomingInlineImagesDefaultHeight] = useSetting( + settingsAtom, + 'incomingInlineImagesDefaultHeight' + ); + const [incomingInlineImagesMaxHeight] = useSetting( + settingsAtom, + 'incomingInlineImagesMaxHeight' + ); const htmlReactParserOptions = useMemo( () => getReactCustomHtmlParser(mx, mEvent.getRoomId(), { @@ -341,8 +396,19 @@ export const MessageEditor = as<'div', MessageEditorProps>( linkifyOpts, useAuthentication, handleSpoilerClick: spoilerClickHandler, + incomingInlineImagesDefaultHeight, + incomingInlineImagesMaxHeight, }), - [linkifyOpts, mEvent, mx, settingsLinkBaseUrl, spoilerClickHandler, useAuthentication] + [ + linkifyOpts, + mEvent, + mx, + settingsLinkBaseUrl, + spoilerClickHandler, + useAuthentication, + incomingInlineImagesDefaultHeight, + incomingInlineImagesMaxHeight, + ] ); const getContent = (() => mEvent.getContent()) as GetContentCallback; const msgType = mEvent.getContent().msgtype; @@ -431,6 +497,7 @@ export const MessageEditor = as<'div', MessageEditorProps>( onKeyUp={handleKeyUp} bottom={ <> + ( - setToolbar(!toolbar)} - > - - + {(anchor: RectCords | undefined, setAnchor) => ( ( - {toolbar && ( -
    - - -
    - )} } /> diff --git a/src/app/features/room/message/hiddenLinkPreviews.test.ts b/src/app/features/room/message/hiddenLinkPreviews.test.ts new file mode 100644 index 000000000..60ff23d0d --- /dev/null +++ b/src/app/features/room/message/hiddenLinkPreviews.test.ts @@ -0,0 +1,50 @@ +import { describe, expect, it } from 'vitest'; +import { + readdAngleBracketsForHiddenPreviews, + stripMarkdownEscapesForHiddenPreviews, +} from './hiddenLinkPreviews'; + +describe('stripMarkdownEscapesForHiddenPreviews', () => { + it('removes backslashes around suppressor wrappers', () => { + expect( + stripMarkdownEscapesForHiddenPreviews(String.raw`hello \ world`) + ).toBe('hello world'); + }); + + it('handles paren-adjacent variants produced by link matching', () => { + expect(stripMarkdownEscapesForHiddenPreviews(String.raw`(\)`)).toBe( + '()' + ); + expect(stripMarkdownEscapesForHiddenPreviews(String.raw`(\) and more`)).toBe( + '() and more' + ); + }); + + it('does not touch unrelated markdown escapes', () => { + expect(stripMarkdownEscapesForHiddenPreviews(String.raw`keep \*this\* and \`)).toBe( + String.raw`keep \*this\* and \` + ); + }); +}); + +describe('readdAngleBracketsForHiddenPreviews', () => { + it('wraps URLs in angle brackets when they are not previewed', () => { + expect(readdAngleBracketsForHiddenPreviews('see https://example.org/ thanks', [])).toBe( + 'see thanks' + ); + }); + + it('does not wrap URLs that are present in link previews', () => { + expect( + readdAngleBracketsForHiddenPreviews('see https://example.org/ thanks', [ + { matched_url: 'https://example.org/' } as never, + ]) + ).toBe('see https://example.org/ thanks'); + }); + + it('does not double-wrap already bracketed URLs', () => { + expect(readdAngleBracketsForHiddenPreviews('see ', [])).toBe( + 'see ' + ); + }); +}); diff --git a/src/app/features/room/message/hiddenLinkPreviews.ts b/src/app/features/room/message/hiddenLinkPreviews.ts new file mode 100644 index 000000000..7ca3111dc --- /dev/null +++ b/src/app/features/room/message/hiddenLinkPreviews.ts @@ -0,0 +1,49 @@ +import type { BundleContent } from '$components/message'; + +const LINK_URL = `(https?:\\/\\/.[A-Za-z0-9-._~:/?#[\\]()@!$&'*+,;%=]+)`; +const LINKINPUTREGEX = new RegExp(`\\(?(${LINK_URL})\\)?`, 'g'); + +/** + * `htmlToMarkdown()` escapes `<` and `>` into `\<` and `\>` in text nodes. + * + * We deliberately inject angle brackets around URLs to suppress link previews. Those backslashes + * are correct internally for markdown escaping, but should not be shown to the user when editing. + * + * This helper removes *only* the backslashes that wrap our `` suppressor pattern. + */ +export function stripMarkdownEscapesForHiddenPreviews(markdown: string): string { + // Handle: \ + // Also handle common surrounding parens: (\), (\) + const WRAPPED = new RegExp(String.raw`\\<(${LINK_URL})\\>`, 'g'); + const OPEN_ONLY = new RegExp(String.raw`\\<(${LINK_URL})`, 'g'); + const CLOSE_ONLY = new RegExp(String.raw`(${LINK_URL})\\>`, 'g'); + + return markdown.replace(WRAPPED, '<$1>').replace(OPEN_ONLY, '<$1').replace(CLOSE_ONLY, '$1>'); +} + +export function readdAngleBracketsForHiddenPreviews( + body: string, + linkPreviews: BundleContent[] | undefined +): string { + if (!linkPreviews) return body; + + const previewed = new Set(linkPreviews.map((b) => b.matched_url)); + + LINKINPUTREGEX.lastIndex = 0; + return body.replace(LINKINPUTREGEX, (full, url: string, offset: number) => { + if (!url || previewed.has(url)) return full; + + // If the URL is already wrapped as , leave it alone. + const urlIndex = body.indexOf(url, offset); + if (urlIndex !== -1 && body.slice(urlIndex - 1, urlIndex + url.length + 1) === `<${url}>`) { + return full; + } + + // Keep any surrounding parens emitted by LINKINPUTREGEX. + if (full.startsWith('(') && full.endsWith(')')) return `(<${url}>)`; + if (full.startsWith('(')) return `(<${url}`; + if (full.endsWith(')')) return `<${url}>)`; + + return `<${url}>`; + }); +} diff --git a/src/app/features/room/msgContent.ts b/src/app/features/room/msgContent.ts index 85e7200b8..8d51eb213 100644 --- a/src/app/features/room/msgContent.ts +++ b/src/app/features/room/msgContent.ts @@ -2,7 +2,6 @@ import type { IContent, MatrixClient } from '$types/matrix-sdk'; import { MsgType } from '$types/matrix-sdk'; import to from 'await-to-js'; import type { IThumbnailContent } from '$types/matrix/common'; -import { MATRIX_BLUR_HASH_PROPERTY_NAME, MATRIX_SPOILER_PROPERTY_NAME } from '$types/matrix/common'; import { getImageFileUrl, getThumbnail, @@ -16,6 +15,10 @@ import type { TUploadItem } from '$state/room/roomInputDrafts'; import { encodeBlurHash } from '$utils/blurHash'; import { scaleYDimension } from '$utils/common'; import { createLogger } from '$utils/debug'; +import { + MATRIX_UNSTABLE_BLUR_HASH_PROPERTY_NAME, + MATRIX_UNSTABLE_SPOILER_PROPERTY_NAME, +} from '../../../unstable/prefixes'; const log = createLogger('msgContent'); @@ -57,14 +60,14 @@ export const getImageMsgContent = async ( msgtype: MsgType.Image, filename: file.name, body: file.name, - [MATRIX_SPOILER_PROPERTY_NAME]: metadata.markedAsSpoiler, + [MATRIX_UNSTABLE_SPOILER_PROPERTY_NAME]: metadata.markedAsSpoiler, }; if (imgEl) { const blurHash = encodeBlurHash(imgEl, 512, scaleYDimension(imgEl.width, 512, imgEl.height)); content.info = { ...getImageInfo(imgEl, file), - [MATRIX_BLUR_HASH_PROPERTY_NAME]: blurHash, + [MATRIX_UNSTABLE_BLUR_HASH_PROPERTY_NAME]: blurHash, }; } if (encInfo) { @@ -97,7 +100,7 @@ export const getVideoMsgContent = async ( msgtype: MsgType.Video, filename: file.name, body: file.name, - [MATRIX_SPOILER_PROPERTY_NAME]: metadata.markedAsSpoiler, + [MATRIX_UNSTABLE_SPOILER_PROPERTY_NAME]: metadata.markedAsSpoiler, }; if (videoEl) { const [thumbError, thumbContent] = await to( @@ -109,7 +112,7 @@ export const getVideoMsgContent = async ( ) ); if (thumbContent && thumbContent.thumbnail_info) { - thumbContent.thumbnail_info[MATRIX_BLUR_HASH_PROPERTY_NAME] = encodeBlurHash( + thumbContent.thumbnail_info[MATRIX_UNSTABLE_BLUR_HASH_PROPERTY_NAME] = encodeBlurHash( videoEl, 512, scaleYDimension(videoEl.videoWidth, 512, videoEl.videoHeight) diff --git a/src/app/features/room/outgoingMessageTransforms.ts b/src/app/features/room/outgoingMessageTransforms.ts index 497c5f62d..a1b41f061 100644 --- a/src/app/features/room/outgoingMessageTransforms.ts +++ b/src/app/features/room/outgoingMessageTransforms.ts @@ -1,11 +1,7 @@ import type { Descendant } from 'slate'; -import { - hasSettingsLinksToRewriteInDescendants, - rewriteSettingsLinksInDescendants, -} from './settingsLinkMessage'; +import { hasSettingsLinksToRewrite, rewriteSettingsLinks } from './settingsLinkMessage'; export type OutgoingMessageTransformContext = { - isMarkdown: boolean; settingsLinkBaseUrl: string; }; @@ -16,13 +12,8 @@ export type OutgoingMessageTransform = { export const outgoingMessageTransforms: OutgoingMessageTransform[] = [ { - apply: (children, context) => - rewriteSettingsLinksInDescendants(children, context.settingsLinkBaseUrl, context.isMarkdown), + apply: (children, context) => rewriteSettingsLinks(children, context.settingsLinkBaseUrl), shouldApply: (children, context) => - hasSettingsLinksToRewriteInDescendants( - children, - context.settingsLinkBaseUrl, - context.isMarkdown - ), + hasSettingsLinksToRewrite(children, context.settingsLinkBaseUrl), }, ]; diff --git a/src/app/features/room/pmpProxyOutgoingPipeline.test.ts b/src/app/features/room/pmpProxyOutgoingPipeline.test.ts new file mode 100644 index 000000000..f5815891c --- /dev/null +++ b/src/app/features/room/pmpProxyOutgoingPipeline.test.ts @@ -0,0 +1,85 @@ +import { describe, expect, it } from 'vitest'; + +import { + plainToEditorInput, + toMatrixCustomHTML, + toPlainText, + trimCustomHtml, +} from '$components/editor'; +import { outgoingMessageTransforms } from './outgoingMessageTransforms'; +import { buildSettingsLink, getSettingsLinkLabel } from '$features/settings/settingsLink'; + +function runOutgoingPipeline(input: string, settingsLinkBaseUrl = 'https://app.example') { + let children = plainToEditorInput(input); + const context = { settingsLinkBaseUrl }; + + outgoingMessageTransforms.forEach((t) => { + if (!t.shouldApply(children, context)) return; + children = t.apply(children, context); + }); + + const plain = toPlainText(children, true).trim(); + const html = trimCustomHtml( + toMatrixCustomHTML(children, { + stripNickname: true, + nickNameReplacement: new Map(), + }) + ); + + return { children, plain, html }; +} + +describe('PMP proxy outgoing pipeline parity', () => { + it('renders markdown like normal messages (bold)', () => { + const { plain, html } = runOutgoingPipeline('**bold**'); + expect(plain).toBe('**bold**'); + // Our markdown pipeline injects `data-md` markers for round-tripping. + expect(html).toMatch(/]*>bold<\/strong>/); + }); + + it('preserves markdown links in plaintext and renders anchors in html', () => { + const { plain, html } = runOutgoingPipeline('[Sable](https://example.com)'); + expect(plain).toBe('[Sable](https://example.com)'); + expect(html).toContain('
    Sable'); + }); + + it('escapes raw html so it is not treated as markup', () => { + const { plain, html } = runOutgoingPipeline('nope'); + expect(plain).toBe('nope'); + // markdownToHtml sanitizes/strips raw tags; ensure it does not render as actual . + expect(html).toContain('nope'); + expect(html).not.toContain('nope'); + }); + + it('applies outgoing transforms (settings link rewrite) like normal messages', () => { + const base = 'https://app.example'; + const url = buildSettingsLink(base, 'appearance', 'message-link-preview'); + const label = getSettingsLinkLabel('appearance', 'message-link-preview'); + + const { plain, html } = runOutgoingPipeline(`see ${url}`, base); + + expect(plain).toContain(`[${label}](${url})`); + // HTML encodes & as & in attributes + const encodedUrl = url.replaceAll('&', '&'); + expect(html).toContain(`', '>'); + expect(html).toContain(`>${encodedLabel}`); + }); + + it('supports multi-paragraph messages (keeps line breaks)', () => { + const { plain, html } = runOutgoingPipeline('first line\n\nsecond line'); + // Plaintext keeps the blank line separation + expect(plain).toBe('first line\n\nsecond line'); + // HTML should contain two paragraphs + expect(html).toMatch(/

    first line<\/p>[\s\S]*

    second line<\/p>/); + }); + + it('supports fenced code blocks and renders them as code', () => { + const md = ['```ts', 'const x = 1', '```'].join('\n'); + const { plain, html } = runOutgoingPipeline(md); + expect(plain).toBe(md); + // Allow flexibility in the exact HTML produced by the markdown pipeline + expect(html).toMatch(/[\s\S]*const x = 1[\s\S]*<\/code><\/pre>/); + }); +}); diff --git a/src/app/features/room/schedule-send/SchedulePickerDialog.tsx b/src/app/features/room/schedule-send/SchedulePickerDialog.tsx index bf0e2689a..f699e2567 100644 --- a/src/app/features/room/schedule-send/SchedulePickerDialog.tsx +++ b/src/app/features/room/schedule-send/SchedulePickerDialog.tsx @@ -1,5 +1,7 @@ import type { MouseEventHandler } from 'react'; import { useState } from 'react'; +import { useAtomValue } from 'jotai'; +import { serverMaxDelayMsAtom } from '$state/scheduledMessages'; import FocusTrap from 'focus-trap-react'; import type { RectCords } from 'folds'; import { @@ -39,7 +41,9 @@ export function SchedulePickerDialog({ onSubmit, }: SchedulePickerDialogProps) { const now = Date.now(); - const maxDelay = daysToMs(30); + const serverMaxDelayMs = useAtomValue(serverMaxDelayMsAtom); + const maxDelay = serverMaxDelayMs ?? daysToMs(30); + const maxDays = Math.round(maxDelay / daysToMs(1)); const defaultTs = initialTime ?? now + hoursToMs(1); const [ts, setTs] = useState(() => Math.max(defaultTs, now + 60000)); const [error, setError] = useState(); @@ -67,7 +71,7 @@ export function SchedulePickerDialog({ return; } if (delay > maxDelay) { - setError('Cannot schedule more than 30 days in advance'); + setError(`Cannot schedule more than ${maxDays} day${maxDays !== 1 ? 's' : ''} in advance`); return; } setError(undefined); diff --git a/src/app/features/room/settingsLinkMessage.test.ts b/src/app/features/room/settingsLinkMessage.test.ts index c769357f7..ca96f717e 100644 --- a/src/app/features/room/settingsLinkMessage.test.ts +++ b/src/app/features/room/settingsLinkMessage.test.ts @@ -1,10 +1,7 @@ import { describe, expect, it } from 'vitest'; import { toMatrixCustomHTML, toPlainText, trimCustomHtml } from '$components/editor/output'; import { BlockType } from '$components/editor/types'; -import { - hasSettingsLinksToRewriteInDescendants, - rewriteSettingsLinksInDescendants, -} from './settingsLinkMessage'; +import { hasSettingsLinksToRewrite, rewriteSettingsLinks } from './settingsLinkMessage'; const settingsUrl = 'https://app.example/settings/account?focus=display-name&moe.sable.client.action=settings'; @@ -16,7 +13,7 @@ const invalidSettingsUrl = describe('settingsLinkMessage', () => { it('detects bare settings links that need outgoing rewriting', () => { expect( - hasSettingsLinksToRewriteInDescendants( + hasSettingsLinksToRewrite( [ { type: BlockType.Paragraph, @@ -29,7 +26,7 @@ describe('settingsLinkMessage', () => { }); it('rewrites bare settings links into message-friendly labels before serialization', () => { - const rewritten = rewriteSettingsLinksInDescendants( + const rewritten = rewriteSettingsLinks( [ { type: BlockType.Paragraph, @@ -39,22 +36,16 @@ describe('settingsLinkMessage', () => { 'https://app.example' ); - expect(toPlainText(rewritten, false).trim()).toBe( + expect(toPlainText(rewritten).trim()).toBe( `[Settings > Account > Display Name](${settingsUrl})` ); - expect( - trimCustomHtml( - toMatrixCustomHTML(rewritten, { - allowTextFormatting: true, - allowBlockMarkdown: false, - allowInlineMarkdown: false, - }) - ) - ).toBe(`Settings > Account > Display Name`); + expect(trimCustomHtml(toMatrixCustomHTML(rewritten, {}))).toContain( + `Settings > Account > Display Name` + ); }); it('rewrites same-base settings links with extra query params', () => { - const rewritten = rewriteSettingsLinksInDescendants( + const rewritten = rewriteSettingsLinks( [ { type: BlockType.Paragraph, @@ -64,13 +55,13 @@ describe('settingsLinkMessage', () => { 'https://app.example' ); - expect(toPlainText(rewritten, false).trim()).toBe( + expect(toPlainText(rewritten).trim()).toBe( `[Settings > Account > Display Name](${settingsUrlWithExtraParam})` ); }); it('does not rewrite settings links that are already in markdown link syntax', () => { - const rewritten = rewriteSettingsLinksInDescendants( + const rewritten = rewriteSettingsLinks( [ { type: BlockType.Paragraph, @@ -80,107 +71,69 @@ describe('settingsLinkMessage', () => { 'https://app.example' ); - expect(toPlainText(rewritten, true).trim()).toBe(`[Display Name](${settingsUrl})`); - }); - - it('does not rewrite settings links inside code blocks', () => { - const rewritten = rewriteSettingsLinksInDescendants( - [ - { - type: BlockType.CodeBlock, - children: [ - { - type: BlockType.CodeLine, - children: [{ text: settingsUrl }], - }, - ], - }, - ], - 'https://app.example' - ); - - expect(toPlainText(rewritten, false).trim()).toBe(settingsUrl); - expect( - trimCustomHtml( - toMatrixCustomHTML(rewritten, { - allowTextFormatting: true, - allowBlockMarkdown: false, - allowInlineMarkdown: false, - }) - ) - ).not.toContain(' { expect( - hasSettingsLinksToRewriteInDescendants( + hasSettingsLinksToRewrite( [ { type: BlockType.Paragraph, children: [{ text: `\`${settingsUrl}\`` }], }, ], - 'https://app.example', - true + 'https://app.example' ) ).toBe(false); - const rewritten = rewriteSettingsLinksInDescendants( + const rewritten = rewriteSettingsLinks( [ { type: BlockType.Paragraph, children: [{ text: `\`${settingsUrl}\`` }], }, ], - 'https://app.example', - true + 'https://app.example' ); - expect(toPlainText(rewritten, true).trim()).toBe(`\`${settingsUrl}\``); - expect( - trimCustomHtml( - toMatrixCustomHTML(rewritten, { - allowTextFormatting: true, - allowBlockMarkdown: false, - allowInlineMarkdown: true, - }) - ) - ).not.toContain('Settings > Account > Display Name'); + expect(toPlainText(rewritten).trim()).toBe(`\`${settingsUrl}\``); + expect(trimCustomHtml(toMatrixCustomHTML(rewritten, {}))).not.toContain( + 'Settings > Account > Display Name' + ); }); it('does not rewrite settings links inside markdown autolinks', () => { - const rewritten = rewriteSettingsLinksInDescendants( + const rewritten = rewriteSettingsLinks( [ { type: BlockType.Paragraph, children: [{ text: `<${settingsUrl}>` }], }, ], - 'https://app.example', - true + 'https://app.example' ); - expect(toPlainText(rewritten, true).trim()).toBe(`<${settingsUrl}>`); + expect(toPlainText(rewritten).trim()).toBe(settingsUrl); }); it('does not rewrite settings links inside literal html text', () => { - const rewritten = rewriteSettingsLinksInDescendants( + const rewritten = rewriteSettingsLinks( [ { type: BlockType.Paragraph, children: [{ text: `Settings` }], }, ], - 'https://app.example', - true + 'https://app.example' ); - expect(toPlainText(rewritten, true).trim()).toBe(`Settings`); + expect(toPlainText(rewritten).trim()).toBe(`Settings`); }); it('does not rewrite settings links with unknown focus ids', () => { expect( - hasSettingsLinksToRewriteInDescendants( + hasSettingsLinksToRewrite( [ { type: BlockType.Paragraph, @@ -191,7 +144,7 @@ describe('settingsLinkMessage', () => { ) ).toBe(false); - const rewritten = rewriteSettingsLinksInDescendants( + const rewritten = rewriteSettingsLinks( [ { type: BlockType.Paragraph, @@ -201,12 +154,12 @@ describe('settingsLinkMessage', () => { 'https://app.example' ); - expect(toPlainText(rewritten, false).trim()).toBe(invalidSettingsUrl); + expect(toPlainText(rewritten).trim()).toBe(invalidSettingsUrl); }); it('rewrites plain same-base hash-router settings links when given the runtime app base', () => { const hashRouterSettingsUrl = 'https://app.example/#/app/settings/account?focus=display-name'; - const rewritten = rewriteSettingsLinksInDescendants( + const rewritten = rewriteSettingsLinks( [ { type: BlockType.Paragraph, @@ -216,7 +169,7 @@ describe('settingsLinkMessage', () => { 'https://app.example/#/app' ); - expect(toPlainText(rewritten, false).trim()).toBe( + expect(toPlainText(rewritten).trim()).toBe( `[Settings > Account > Display Name](${hashRouterSettingsUrl})` ); }); diff --git a/src/app/features/room/settingsLinkMessage.ts b/src/app/features/room/settingsLinkMessage.ts index 84621c474..e3f25523e 100644 --- a/src/app/features/room/settingsLinkMessage.ts +++ b/src/app/features/room/settingsLinkMessage.ts @@ -1,20 +1,13 @@ import { find as findLinks } from 'linkifyjs'; import type { Descendant } from 'slate'; import { Text } from 'slate'; -import type { - BlockQuoteElement, - FormattedText, - HeadingElement, - InlineElement, - ListItemElement, - OrderedListElement, - ParagraphElement, - QuoteLineElement, - SmallElement, - UnorderedListElement, -} from '$components/editor/slate'; +import type { FormattedText, InlineElement, ParagraphElement } from '$components/editor/slate'; import { BlockType } from '$components/editor/types'; -import { createLinkElement } from '$components/editor/utils'; +import { + createLinkElement, + getMarkdownCodeSpanRanges, + isInsideMarkdownCodeSpan, +} from '$components/editor/utils'; import { getSettingsLinkLabel, parseSettingsLink } from '$features/settings/settingsLink'; type RewritableSettingsLinkMatch = { @@ -27,38 +20,6 @@ type RewritableSettingsLinkMatch = { const isMarkdownSettingsLink = (text: string, start: number, end: number): boolean => text.slice(0, start).endsWith('](') && text.slice(end).startsWith(')'); -const getMarkdownCodeSpanRanges = (text: string): [number, number][] => { - const ranges: [number, number][] = []; - let openRun: { start: number; length: number } | undefined; - - for (let index = 0; index < text.length; index += 1) { - if (text[index] === '`') { - let runEnd = index; - while (runEnd < text.length && text[runEnd] === '`') { - runEnd += 1; - } - - const runLength = runEnd - index; - if (!openRun) { - openRun = { start: index, length: runLength }; - } else if (openRun.length === runLength) { - ranges.push([openRun.start, runEnd]); - openRun = undefined; - } - - index = runEnd - 1; - } - } - - return ranges; -}; - -const isInsideMarkdownCodeSpan = ( - start: number, - end: number, - codeSpanRanges: [number, number][] -): boolean => codeSpanRanges.some(([rangeStart, rangeEnd]) => start > rangeStart && end < rangeEnd); - const isMarkdownAutolink = (text: string, start: number, end: number): boolean => text[start - 1] === '<' && text[end] === '>'; @@ -76,33 +37,26 @@ const isProtectedMarkdownContext = ( text: string, start: number, end: number, - isMarkdown: boolean, codeSpanRanges: [number, number][] ): boolean => isMarkdownSettingsLink(text, start, end) || - (isMarkdown && - (isInsideMarkdownCodeSpan(start, end, codeSpanRanges) || - isMarkdownAutolink(text, start, end) || - isInsideHtmlTag(text, start))); + isInsideMarkdownCodeSpan(start, end, codeSpanRanges) || + isMarkdownAutolink(text, start, end) || + isInsideHtmlTag(text, start); const getRewritableSettingsLinkMatches = ( text: string, - baseUrl: string, - isMarkdown: boolean + baseUrl: string ): RewritableSettingsLinkMatch[] => { const matches = findLinks(text, 'url'); if (matches.length === 0) return []; - const codeSpanRanges = isMarkdown ? getMarkdownCodeSpanRanges(text) : []; - + const codeSpanRanges = getMarkdownCodeSpanRanges(text); return matches.flatMap((match) => { const href = match.value; const settingsLink = parseSettingsLink(baseUrl, href); - if ( - !settingsLink || - isProtectedMarkdownContext(text, match.start, match.end, isMarkdown, codeSpanRanges) - ) { + if (!settingsLink || isProtectedMarkdownContext(text, match.start, match.end, codeSpanRanges)) { return []; } @@ -119,13 +73,11 @@ const getRewritableSettingsLinkMatches = ( const hasRewritableSettingsLinksInInlineChildren = ( children: InlineElement[], - baseUrl: string, - isMarkdown: boolean + baseUrl: string ): boolean => children.some( (child) => - Text.isText(child) && - getRewritableSettingsLinkMatches(child.text, baseUrl, isMarkdown).length > 0 + Text.isText(child) && getRewritableSettingsLinkMatches(child.text, baseUrl).length > 0 ); const createTextSegment = (node: FormattedText, text: string): FormattedText => ({ @@ -133,12 +85,8 @@ const createTextSegment = (node: FormattedText, text: string): FormattedText => text, }); -const rewriteInlineText = ( - node: FormattedText, - baseUrl: string, - isMarkdown: boolean -): InlineElement[] => { - const matches = getRewritableSettingsLinkMatches(node.text, baseUrl, isMarkdown); +const rewriteInlineText = (node: FormattedText, baseUrl: string): InlineElement[] => { + const matches = getRewritableSettingsLinkMatches(node.text, baseUrl); if (matches.length === 0) return [node]; const rewritten: InlineElement[] = []; @@ -162,125 +110,40 @@ const rewriteInlineText = ( return rewritten.filter((child) => !Text.isText(child) || child.text.length > 0); }; -const rewriteInlineChildren = ( - children: InlineElement[], - baseUrl: string, - isMarkdown: boolean -): InlineElement[] => - children.flatMap((child) => - Text.isText(child) ? rewriteInlineText(child, baseUrl, isMarkdown) : [child] - ); +const rewriteInlineChildren = (children: InlineElement[], baseUrl: string): InlineElement[] => + children.flatMap((child) => (Text.isText(child) ? rewriteInlineText(child, baseUrl) : [child])); -const rewriteInlineContainer = < - T extends ParagraphElement | HeadingElement | QuoteLineElement | ListItemElement | SmallElement, ->( - node: T, - baseUrl: string, - isMarkdown: boolean -): T => ({ +const rewriteInlineContainer = (node: ParagraphElement, baseUrl: string): ParagraphElement => ({ ...node, - children: rewriteInlineChildren(node.children, baseUrl, isMarkdown), + children: rewriteInlineChildren(node.children, baseUrl), }); -const rewriteBlockQuote = ( - node: BlockQuoteElement, - baseUrl: string, - isMarkdown: boolean -): BlockQuoteElement => ({ - ...node, - children: node.children.map((child) => rewriteInlineContainer(child, baseUrl, isMarkdown)), -}); - -const rewriteOrderedList = ( - node: OrderedListElement, - baseUrl: string, - isMarkdown: boolean -): OrderedListElement => ({ - ...node, - children: node.children.map((child) => rewriteInlineContainer(child, baseUrl, isMarkdown)), -}); - -const rewriteUnorderedList = ( - node: UnorderedListElement, - baseUrl: string, - isMarkdown: boolean -): UnorderedListElement => ({ - ...node, - children: node.children.map((child) => rewriteInlineContainer(child, baseUrl, isMarkdown)), -}); - -const hasSettingsLinksToRewriteInNode = ( - node: Descendant, - baseUrl: string, - isMarkdown: boolean -): boolean => { +const hasSettingsLinksToRewriteInNode = (node: Descendant, baseUrl: string): boolean => { if (Text.isText(node)) { - return getRewritableSettingsLinkMatches(node.text, baseUrl, isMarkdown).length > 0; + return getRewritableSettingsLinkMatches(node.text, baseUrl).length > 0; } switch (node.type) { case BlockType.Paragraph: - case BlockType.Heading: - case BlockType.QuoteLine: - case BlockType.ListItem: - case BlockType.Small: - return hasRewritableSettingsLinksInInlineChildren(node.children, baseUrl, isMarkdown); - case BlockType.BlockQuote: - case BlockType.OrderedList: - case BlockType.UnorderedList: - return node.children.some((child) => - hasSettingsLinksToRewriteInNode(child, baseUrl, isMarkdown) - ); - case BlockType.CodeBlock: - case BlockType.CodeLine: - case BlockType.HorizontalRule: - case BlockType.Link: - case BlockType.Mention: - case BlockType.Emoticon: - case BlockType.Command: - return false; + return hasRewritableSettingsLinksInInlineChildren(node.children, baseUrl); default: return false; } }; -const rewriteNode = (node: Descendant, baseUrl: string, isMarkdown: boolean): Descendant => { +const rewriteNode = (node: Descendant, baseUrl: string): Descendant => { if (Text.isText(node)) return node; switch (node.type) { case BlockType.Paragraph: - case BlockType.Heading: - case BlockType.QuoteLine: - case BlockType.ListItem: - case BlockType.Small: - return rewriteInlineContainer(node, baseUrl, isMarkdown); - case BlockType.BlockQuote: - return rewriteBlockQuote(node, baseUrl, isMarkdown); - case BlockType.OrderedList: - return rewriteOrderedList(node, baseUrl, isMarkdown); - case BlockType.UnorderedList: - return rewriteUnorderedList(node, baseUrl, isMarkdown); - case BlockType.CodeBlock: - case BlockType.CodeLine: - case BlockType.HorizontalRule: - case BlockType.Link: - case BlockType.Mention: - case BlockType.Emoticon: - case BlockType.Command: - return node; + return rewriteInlineContainer(node, baseUrl); default: return node; } }; -export const rewriteSettingsLinksInDescendants = ( - children: Descendant[], - baseUrl: string, - isMarkdown = false -): Descendant[] => children.map((child) => rewriteNode(child, baseUrl, isMarkdown)); +export const hasSettingsLinksToRewrite = (nodes: Descendant[], baseUrl: string): boolean => + nodes.some((node) => hasSettingsLinksToRewriteInNode(node, baseUrl)); -export const hasSettingsLinksToRewriteInDescendants = ( - children: Descendant[], - baseUrl: string, - isMarkdown = false -): boolean => children.some((child) => hasSettingsLinksToRewriteInNode(child, baseUrl, isMarkdown)); +export const rewriteSettingsLinks = (nodes: Descendant[], baseUrl: string): Descendant[] => + nodes.map((node) => rewriteNode(node, baseUrl)); diff --git a/src/app/features/search/Search.tsx b/src/app/features/search/Search.tsx index 1a80070d5..0c928aa38 100644 --- a/src/app/features/search/Search.tsx +++ b/src/app/features/search/Search.tsx @@ -4,6 +4,7 @@ import { Box, config, Icon, + IconButton, Icons, Input, Line, @@ -39,7 +40,7 @@ import { factoryRoomIdByActivity } from '$utils/sort'; import { nameInitials } from '$utils/common'; import { useRoomNavigate } from '$hooks/useRoomNavigate'; import { useListFocusIndex } from '$hooks/useListFocusIndex'; -import { getMxIdLocalPart, getMxIdServer, guessDmRoomUserId } from '$utils/matrix'; +import { getMxIdLocalPart, guessDmRoomUserId } from '$utils/matrix'; import { roomToParentsAtom } from '$state/room/roomToParents'; import { roomToUnreadAtom } from '$state/room/roomToUnread'; import { UnreadBadge, UnreadBadgeCenter } from '$components/unread-badge'; @@ -49,6 +50,7 @@ import { useMediaAuthentication } from '$hooks/useMediaAuthentication'; import { KeySymbol } from '$utils/key-symbol'; import { isMacOS } from '$utils/user-agent'; import { useSelectedSpace } from '$hooks/router/useSelectedSpace'; +import { getMxIdServer } from '$utils/mxIdHelper'; enum SearchRoomType { Rooms = '#', @@ -121,10 +123,20 @@ const SEARCH_OPTIONS: UseAsyncSearchOptions = { }, }; -type SearchProps = { - requestClose: () => void; +export type RoomSearchPickRoomConfig = { + title: string; + eligibleRoomIds: readonly string[]; + onPickRoom: (roomId: string) => void; + errorMessage?: string | null; + busy?: boolean; }; -export function Search({ requestClose }: SearchProps) { + +export type RoomSearchModalProps = { + requestClose: () => void; + pickRoom?: RoomSearchPickRoomConfig; +}; + +export function RoomSearchModal({ requestClose, pickRoom }: RoomSearchModalProps) { const mx = useMatrixClient(); const useAuthentication = useMediaAuthentication(); const scrollRef = useRef(null); @@ -144,8 +156,23 @@ export function Search({ requestClose }: SearchProps) { const spaces = useSpaces(mx, allRoomsAtom); const directs = useDirects(mx, allRoomsAtom, mDirects); - const topActiveRooms = useTopActiveRooms(searchRoomType, rooms, directs, spaces); - const targetRooms = useSearchTargetRooms(searchRoomType, rooms, directs, spaces); + const eligibleSet = useMemo( + () => (pickRoom ? new Set(pickRoom.eligibleRoomIds) : null), + [pickRoom] + ); + + const rawTopActiveRooms = useTopActiveRooms(searchRoomType, rooms, directs, spaces); + const rawTargetRooms = useSearchTargetRooms(searchRoomType, rooms, directs, spaces); + + const topActiveRooms = useMemo(() => { + if (!eligibleSet) return rawTopActiveRooms; + return rawTopActiveRooms.filter((id) => eligibleSet.has(id)); + }, [eligibleSet, rawTopActiveRooms]); + + const targetRooms = useMemo(() => { + if (!eligibleSet) return rawTargetRooms; + return rawTargetRooms.filter((id) => eligibleSet.has(id)); + }, [eligibleSet, rawTargetRooms]); const getTargetStr: SearchItemStrGetter = useCallback( (roomId: string) => { @@ -180,7 +207,12 @@ export function Search({ requestClose }: SearchProps) { ? makeHighlightRegex(result.query.split(' ')) : undefined; - const openRoomId = (roomId: string, isSpace: boolean) => { + const handleActivateRoom = (roomId: string, isSpace: boolean) => { + if (pickRoom) { + if (pickRoom.busy) return; + pickRoom.onPickRoom(roomId); + return; + } if (isSpace) navigateSpace(roomId); else navigateRoom(roomId); requestClose(); @@ -210,7 +242,7 @@ export function Search({ requestClose }: SearchProps) { const handleInputKeyDown: KeyboardEventHandler = (evt) => { const roomId = roomsToRender[listFocus.index]; if (isKeyHotkey('enter', evt) && roomId) { - openRoomId(roomId, spaces.includes(roomId)); + handleActivateRoom(roomId, spaces.includes(roomId)); return; } if (isKeyHotkey('arrowdown', evt)) { @@ -229,7 +261,7 @@ export function Search({ requestClose }: SearchProps) { const roomId = target.getAttribute('data-room-id'); const isSpace = target.getAttribute('data-space') === 'true'; if (!roomId) return; - openRoomId(roomId, isSpace); + handleActivateRoom(roomId, isSpace); }; useEffect(() => { @@ -260,6 +292,35 @@ export function Search({ requestClose }: SearchProps) { }} > + {pickRoom && ( + + {pickRoom.title} + + + + + )} + {pickRoom?.errorMessage ? ( + + + {pickRoom.errorMessage} + + + ) : null} } onChange={handleInputChange} onKeyDown={handleInputKeyDown} + disabled={pickRoom?.busy} /> @@ -288,12 +350,26 @@ export function Search({ requestClose }: SearchProps) { gap="100" > - {result ? 'No Match Found' : `No Rooms'}`} + {pickRoom + ? result + ? 'No Match Found' + : pickRoom.eligibleRoomIds.length === 0 + ? 'No rooms to forward to' + : 'No rooms match this filter' + : result + ? 'No Match Found' + : 'No Rooms'} - {result - ? `No match found for "${result.query}".` - : `You do not have any Rooms to display yet.`} + {pickRoom + ? result + ? `No match found for "${result.query}".` + : pickRoom.eligibleRoomIds.length === 0 + ? 'You cannot send messages in any joined room yet.' + : 'Try another search, or use # for group rooms and @ for direct messages.' + : result + ? `No match found for "${result.query}".` + : 'You do not have any Rooms to display yet.'} )} @@ -334,6 +410,7 @@ export function Search({ requestClose }: SearchProps) { data-room-id={roomId} data-space={room.isSpaceRoom()} onClick={handleRoomClick} + disabled={pickRoom?.busy} variant={listFocus.index === index ? 'Primary' : 'Surface'} aria-pressed={listFocus.index === index} radii="400" @@ -416,10 +493,19 @@ export function Search({ requestClose }: SearchProps) { - Type # for rooms, @ for DMs and * for spaces. Hotkey:{' '} - {isMacOS() ? KeySymbol.Command : 'Ctrl'} + k - {' / '} - {isMacOS() ? KeySymbol.Command : 'Ctrl'} + f + {pickRoom ? ( + <> + Type # for rooms and @ for direct messages. Choose a room to + forward this message. + + ) : ( + <> + Type # for rooms, @ for DMs and * for spaces. Hotkey:{' '} + {isMacOS() ? KeySymbol.Command : 'Ctrl'} + k + {' / '} + {isMacOS() ? KeySymbol.Command : 'Ctrl'} + f + + )} @@ -454,5 +540,9 @@ export function SearchModalRenderer() { ) ); - return opened && setOpen(false)} />; + return opened && setOpen(false)} />; +} + +export function Search(props: { requestClose: () => void }) { + return ; } diff --git a/src/app/features/settings/Settings.tsx b/src/app/features/settings/Settings.tsx index e480d53b9..65be2eaf5 100644 --- a/src/app/features/settings/Settings.tsx +++ b/src/app/features/settings/Settings.tsx @@ -249,29 +249,31 @@ export function Settings({ nav={ screenSize === ScreenSize.Mobile && visibleSection !== null ? undefined : ( - + - - {nameInitials(displayName)}} - /> - - - Settings - - - - {visibleSection === null && ( - - - - )} + + + {nameInitials(displayName)}} + /> + + + Settings + + + + {visibleSection === null && ( + + + + )} + diff --git a/src/app/features/settings/about/About.tsx b/src/app/features/settings/about/About.tsx index 44639f719..a9b2b63f0 100644 --- a/src/app/features/settings/about/About.tsx +++ b/src/app/features/settings/about/About.tsx @@ -3,7 +3,7 @@ import { Box, Text, Icon, Icons, Scroll, Button, config, toRem, Spinner } from ' import { PageContent } from '$components/page'; import { SequenceCard } from '$components/sequence-card'; import { SettingTile } from '$components/setting-tile'; -import CinnySVG from '$public/res/svg/cinny-logo.svg'; +import LogoSVG from '$public/res/svg/logo.svg'; import { clearCacheAndReload } from '$client/initMatrix'; import { useMatrixClient } from '$hooks/useMatrixClient'; import { SequenceCardStyle } from '$features/settings/styles.css'; @@ -190,8 +190,8 @@ export function About({ requestBack, requestClose }: Readonly) { Cinny logo @@ -304,7 +304,6 @@ export function About({ requestBack, requestClose }: Readonly) { >

  • - {' '} ) { > Cinny - is ©{' '} + {', © '} Ajay Bura - {' '} - used under the terms of{' '} + + {', is used under the terms of '} ) {
  • - The{' '} + {'The '} matrix-js-sdk - {' '} - is ©{' '} + + {', © '} The Matrix.org Foundation C.I.C - {' '} - used under the terms of{' '} + + {', is used under the terms of '} ) {
  • - The{' '} + {'The '} twemoji-colr - {' '} - font is ©{' '} + + {' font, © '} Mozilla Foundation - {' '} - used under the terms of{' '} + + {', is used under the terms of '} ) {
  • - The{' '} + {'The '} Twemoji - {' '} - emoji art is ©{' '} + + {' emoji art, © '} Twitter, Inc and other contributors - {' '} - used under the terms of{' '} + + {', is used under the terms of '} ) {
  • - The{' '} + {'The '} ) { > Material sound resources {' '} - are ©{' '} + {', © '} Google - {' '} - used under the terms of{' '} + + {', are used under the terms of '} { @@ -54,7 +59,12 @@ export function AnimalCosmetics({ profile, userId }: Readonly handleSaveField('kitty.meow.is_cat', !isCat)} + onChange={() => + handleSaveField( + prefix.MATRIX_SABLE_UNSTABLE_ANIMAL_IDENTITY_IS_CAT_PROPERTY_NAME, + !isCat + ) + } /> } /> @@ -68,7 +78,12 @@ export function AnimalCosmetics({ profile, userId }: Readonly handleSaveField('kitty.meow.has_cats', !hasCats)} + onChange={() => + handleSaveField( + prefix.MATRIX_SABLE_UNSTABLE_ANIMAL_IDENTITY_HAS_CAT_PROPERTY_NAME, + !hasCats + ) + } /> } /> diff --git a/src/app/features/settings/account/BioEditor.tsx b/src/app/features/settings/account/BioEditor.tsx index 05f8c2f76..70556fbf9 100644 --- a/src/app/features/settings/account/BioEditor.tsx +++ b/src/app/features/settings/account/BioEditor.tsx @@ -2,7 +2,7 @@ import type { KeyboardEventHandler } from 'react'; import { useCallback, useEffect, useState, useRef } from 'react'; import type { Room } from '$types/matrix-sdk'; import type { RectCords } from 'folds'; -import { Box, Chip, Icon, IconButton, Icons, Line, PopOut, Spinner, Text, config } from 'folds'; +import { Box, Chip, Icon, IconButton, Icons, PopOut, Spinner, Text, config } from 'folds'; import { Editor, Transforms } from 'slate'; import { ReactEditor } from 'slate-react'; import { isKeyHotkey } from 'is-hotkey'; @@ -11,11 +11,11 @@ import { AutocompletePrefix, CustomEditor, EmoticonAutocomplete, - Toolbar, + MarkdownFormattingToolbarBottom, + MarkdownFormattingToolbarToggle, createEmoticonElement, getAutocompleteQuery, getPrevWorldRange, - htmlToEditorInput, plainToEditorInput, moveCursor, toMatrixCustomHTML, @@ -23,6 +23,7 @@ import { trimCustomHtml, useEditor, } from '$components/editor'; +import { htmlToMarkdown } from '$plugins/markdown'; import { useSetting } from '$state/hooks/settings'; import { settingsAtom } from '$state/settings'; import { UseStateProvider } from '$components/UseStateProvider'; @@ -43,9 +44,6 @@ const BIO_LIMIT = 1024; export function BioEditor({ value, isSaving, imagePackRooms, onSave }: BioEditorProps) { const editor = useEditor(); const [enterForNewline] = useSetting(settingsAtom, 'enterForNewline'); - const [globalToolbar] = useSetting(settingsAtom, 'editorToolbar'); - const [isMarkdown] = useSetting(settingsAtom, 'isMarkdown'); - const [toolbar, setToolbar] = useState(globalToolbar); const [autocompleteQuery, setAutocompleteQuery] = useState>(); @@ -56,25 +54,19 @@ export function BioEditor({ value, isSaving, imagePackRooms, onSave }: BioEditor const initialized = useRef(false); const updateStats = useCallback(() => { - const plainText = toPlainText(editor.children, isMarkdown).trim(); + const plainText = toPlainText(editor.children).trim(); setCharCount(plainText.length); - }, [editor, isMarkdown]); + }, [editor]); const handleSave = useCallback(() => { - const plainText = toPlainText(editor.children, isMarkdown).trim(); + const plainText = toPlainText(editor.children).trim(); if (plainText.length > BIO_LIMIT) return; - const customHtml = trimCustomHtml( - toMatrixCustomHTML(editor.children, { - allowTextFormatting: true, - allowBlockMarkdown: isMarkdown, - allowInlineMarkdown: isMarkdown, - }) - ); + const customHtml = trimCustomHtml(toMatrixCustomHTML(editor.children, {})); onSave(customHtml || plainText, plainText); setHasChanged(false); - }, [editor, isMarkdown, onSave]); + }, [editor, onSave]); useEffect(() => { const valueChanged = prevValue.current !== value; @@ -95,17 +87,16 @@ export function BioEditor({ value, isSaving, imagePackRooms, onSave }: BioEditor const safeValue = typeof normalizedValue === 'string' ? normalizedValue : ''; const incomingPlainText = toPlainText( - htmlToEditorInput(safeValue, isMarkdown), - isMarkdown + plainToEditorInput(safeValue.includes('<') ? htmlToMarkdown(safeValue) : safeValue) ).trim(); - const currentPlainText = toPlainText(editor.children, isMarkdown).trim(); + const currentPlainText = toPlainText(editor.children).trim(); if (currentPlainText === incomingPlainText && initialized.current) return; const isLikelyHtml = safeValue.includes('<') || safeValue.includes('>'); const initialValue = isLikelyHtml - ? htmlToEditorInput(safeValue, isMarkdown) - : plainToEditorInput(safeValue, isMarkdown); + ? plainToEditorInput(htmlToMarkdown(safeValue)) + : plainToEditorInput(safeValue); editor.children = initialValue; Editor.normalize(editor, { force: true }); @@ -115,7 +106,7 @@ export function BioEditor({ value, isSaving, imagePackRooms, onSave }: BioEditor setHasChanged(false); updateStats(); } - }, [value, editor, isMarkdown, updateStats]); + }, [value, editor, updateStats]); const handleKeyDown: KeyboardEventHandler = useCallback( (evt) => { @@ -181,6 +172,7 @@ export function BioEditor({ value, isSaving, imagePackRooms, onSave }: BioEditor variant="Background" bottom={ + - setToolbar(!toolbar)} - > - - + {(anchor: RectCords | undefined, setAnchor) => ( - {toolbar && ( - - - - - )} } /> diff --git a/src/app/features/settings/account/Profile.tsx b/src/app/features/settings/account/Profile.tsx index fcc2b18ec..19dc11609 100644 --- a/src/app/features/settings/account/Profile.tsx +++ b/src/app/features/settings/account/Profile.tsx @@ -50,6 +50,7 @@ import { BioEditor } from './BioEditor'; import { NameColorEditor } from './NameColorEditor'; import { StatusEditor } from './StatusEditor'; import { AnimalCosmetics } from './AnimalCosmetics'; +import * as prefix from '$unstable/prefixes'; type PronounSet = { summary: string; @@ -258,7 +259,7 @@ function ProfileBanner({ profile }: Readonly>) { if (imageFileURL) setStagedUrl(imageFileURL); - mx.setExtendedProfileProperty?.('chat.commet.profile_banner', mxc); + mx.setExtendedProfileProperty?.(prefix.MATRIX_UNSTABLE_PROFILE_BANNER_PROPERTY_NAME, mxc); setImageFile(undefined); }, [mx, imageFileURL] @@ -269,7 +270,10 @@ function ProfileBanner({ profile }: Readonly>) { setStagedUrl(undefined); setImageFile(undefined); - await mx.setExtendedProfileProperty?.('chat.commet.profile_banner', null); + await mx.setExtendedProfileProperty?.( + prefix.MATRIX_UNSTABLE_PROFILE_BANNER_PROPERTY_NAME, + null + ); setAlertRemove(false); }; @@ -484,7 +488,10 @@ function ProfileExtended({ profile, userId }: Readonly) { const currentStatus = presence?.status || ''; // Keys we don't render here nor handle seperately but still need to exclude - const EXCLUDED_KEYS = new Set(['kitty.meow.is_cat', 'kitty.meow.has_cats']); + const EXCLUDED_KEYS = new Set([ + prefix.MATRIX_SABLE_UNSTABLE_ANIMAL_IDENTITY_IS_CAT_PROPERTY_NAME, + prefix.MATRIX_SABLE_UNSTABLE_ANIMAL_IDENTITY_HAS_CAT_PROPERTY_NAME, + ]); // Unknown fields / unimplemented non-matrix-spec fields // Only renders them, can't edit or set @@ -539,9 +546,13 @@ function ProfileExtended({ profile, userId }: Readonly) { focusId="name-color" current={ profile.nameColor || - (profile.extended?.['moe.sable.app.name_color'] as string | undefined) + (profile.extended?.[prefix.MATRIX_SABLE_UNSTABLE_NAME_COLOR_PROPERTY_NAME] as + | string + | undefined) + } + onSave={(color) => + handleSaveField(prefix.MATRIX_SABLE_UNSTABLE_NAME_COLOR_PROPERTY_NAME, color) } - onSave={(color) => handleSaveField('moe.sable.app.name_color', color)} /> ) { focusId="name-color-dark-theme" current={ profile.nameColorDark || - (profile.extended?.['moe.sable.app.name_color_dark_theme'] as string | undefined) + (profile.extended?.[prefix.MATRIX_SABLE_UNSTABLE_NAME_COLOR_DARK_PROPERTY_NAME] as + | string + | undefined) + } + onSave={(color) => + handleSaveField(prefix.MATRIX_SABLE_UNSTABLE_NAME_COLOR_DARK_PROPERTY_NAME, color) } - onSave={(color) => handleSaveField('moe.sable.app.name_color_dark_theme', color)} /> ) { focusId="name-color-light-theme" current={ profile.nameColorLight || - (profile.extended?.['moe.sable.app.name_color_light_theme'] as string | undefined) + (profile.extended?.[prefix.MATRIX_SABLE_UNSTABLE_NAME_COLOR_LIGHT_PROPERTY_NAME] as + | string + | undefined) + } + onSave={(color) => + handleSaveField(prefix.MATRIX_SABLE_UNSTABLE_NAME_COLOR_LIGHT_PROPERTY_NAME, color) } - onSave={(color) => handleSaveField('moe.sable.app.name_color_light_theme', color)} /> ) { handleSaveField('io.fsky.nyx.pronouns', p)} + onSave={(p) => handleSaveField(prefix.MATRIX_UNSTABLE_PROFILE_PRONOUNS_PROPERTY_NAME, p)} /> ) { { - handleSaveField('us.cloke.msc4175.tz', tz); - handleSaveField('m.tz', tz); + handleSaveField(prefix.MATRIX_UNSTABLE_PROFILE_TIMEZONE_PROPERTY_NAME, tz); + handleSaveField(prefix.MATRIX_STABLE_PROFILE_TIMEZONE_PROPERTY_NAME, tz); }} /> @@ -598,17 +617,24 @@ function ProfileExtended({ profile, userId }: Readonly) { > { - handleSaveField('moe.sable.app.bio', htmlBio); + handleSaveField(prefix.MATRIX_SABLE_UNSTABLE_PROFILE_BIOGRAPHY_PROPERTY_NAME, htmlBio); // MSC4440 - handleSaveField('gay.fomx.biography', { + handleSaveField(prefix.MATRIX_UNSTABLE_PROFILE_BIOGRAPHY_PROPERTY_NAME, { 'm.text': [ { body: htmlBio, @@ -621,13 +647,51 @@ function ProfileExtended({ profile, userId }: Readonly) { } satisfies MSC4440Bio); const cleanedHtml = htmlBio.replaceAll('
    ', ''); - handleSaveField('chat.commet.profile_bio', { + handleSaveField(prefix.MATRIX_COMMET_UNSTABLE_PROFILE_BIO_PROPERTY_NAME, { format: 'org.matrix.custom.html', formatted_body: cleanedHtml, }); }} /> + + + handleSaveField(prefix.MATRIX_COMMET_UNSTABLE_PROFILE_COLOR_SCHEME_PROPERTY_NAME, { + color, + brightness: color ? profile?.heroColorScheme?.brightness : null, + }) + } + /> + + handleSaveField(prefix.MATRIX_COMMET_UNSTABLE_PROFILE_COLOR_SCHEME_PROPERTY_NAME, { + color: profile?.heroColorScheme?.color, + brightness: profile?.heroColorScheme?.brightness === 'dark' ? 'light' : 'dark', + }) + } + > + + + {profile?.heroColorScheme?.brightness === 'dark' ? 'Dark Mode' : 'Light Mode'} + + + + + {extendedFields.length > 0 && extendedFields.map(([key, value]) => { diff --git a/src/app/features/settings/cosmetics/Cosmetics.tsx b/src/app/features/settings/cosmetics/Cosmetics.tsx index 1681774a2..49ab59374 100644 --- a/src/app/features/settings/cosmetics/Cosmetics.tsx +++ b/src/app/features/settings/cosmetics/Cosmetics.tsx @@ -1,5 +1,5 @@ +import { useEffect, useRef, useState } from 'react'; import type { MouseEventHandler } from 'react'; -import { useState } from 'react'; import type { RectCords } from 'folds'; import { Box, @@ -18,7 +18,7 @@ import FocusTrap from 'focus-trap-react'; import { PageContent } from '$components/page'; import { SequenceCard } from '$components/sequence-card'; import { useSetting } from '$state/hooks/settings'; -import type { JumboEmojiSize } from '$state/settings'; +import type { JumboEmojiSize, RenderUserCardsMode } from '$state/settings'; import { settingsAtom } from '$state/settings'; import { SettingTile } from '$components/setting-tile'; import { stopPropagation } from '$utils/keyboard'; @@ -104,6 +104,82 @@ function SelectJumboEmojiSize() { ); } +const profileCardRenderItems: { id: RenderUserCardsMode; name: string }[] = [ + { id: 'both', name: 'Light & dark' }, + { id: 'light', name: 'Light only' }, + { id: 'dark', name: 'Dark only' }, + { id: 'none', name: 'Off' }, +]; + +function SelectRenderCustomProfileCards() { + const [menuCords, setMenuCords] = useState(); + const [renderUserCardsMode, setRenderUserCardsMode] = useSetting(settingsAtom, 'renderUserCards'); + + const handleMenu: MouseEventHandler = (evt) => { + setMenuCords(evt.currentTarget.getBoundingClientRect()); + }; + + const handleSelect = (mode: RenderUserCardsMode) => { + setRenderUserCardsMode(mode); + setMenuCords(undefined); + }; + + const currentLabel = + profileCardRenderItems.find((i) => i.id === renderUserCardsMode)?.name ?? 'Light & dark'; + + return ( + <> + + setMenuCords(undefined), + clickOutsideDeactivates: true, + isKeyForward: (evt: KeyboardEvent) => + evt.key === 'ArrowDown' || evt.key === 'ArrowRight', + isKeyBackward: (evt: KeyboardEvent) => + evt.key === 'ArrowUp' || evt.key === 'ArrowLeft', + escapeDeactivates: stopPropagation, + }} + > + + + {profileCardRenderItems.map((item) => ( + handleSelect(item.id)} + > + {item.name} + + ))} + + + + } + /> + + ); +} + function JumboEmoji() { return ( @@ -214,6 +290,14 @@ function IdentityCosmetics() { after={} /> + + } + /> + (null); + + useEffect(() => { + let timeoutId: number | undefined; + const el = appearanceScrollRef.current; + + if (themeBrowserOpen && el) { + const scrollToTop = () => { + el.scrollTop = 0; + }; + + scrollToTop(); + requestAnimationFrame(scrollToTop); + timeoutId = window.setTimeout(scrollToTop, 0); + } + + return () => { + if (timeoutId !== undefined) { + window.clearTimeout(timeoutId); + } + }; + }, [themeBrowserOpen]); + return ( - + - - - - - + + {!themeBrowserOpen && ( + <> + + + + + + )} diff --git a/src/app/features/settings/cosmetics/ThemeAppearanceSection.tsx b/src/app/features/settings/cosmetics/ThemeAppearanceSection.tsx new file mode 100644 index 000000000..774940c51 --- /dev/null +++ b/src/app/features/settings/cosmetics/ThemeAppearanceSection.tsx @@ -0,0 +1,185 @@ +import { useCallback, useEffect } from 'react'; +import { Box, Button, Switch, Text } from 'folds'; + +import { SettingMenuSelector } from '$components/setting-menu-selector'; +import { SequenceCard } from '$components/sequence-card'; +import { SettingTile } from '$components/setting-tile'; +import type { Theme } from '$hooks/useTheme'; +import { DarkTheme, LightTheme, ThemeKind, useThemeNames, useThemes } from '$hooks/useTheme'; +import { useSetting } from '$state/hooks/settings'; +import { settingsAtom } from '$state/settings'; +import { SequenceCardStyle } from '$features/settings/styles.css'; +import { useStore } from 'jotai/react'; + +import { useThemeCatalogOnboardingGate } from './ThemeCatalogOnboarding'; +import { ThemeCatalogSettings } from './ThemeCatalogSettings'; + +function makeThemeOptions(themes: Theme[], themeNames: Record) { + return themes.map((theme) => ({ + value: theme.id, + label: themeNames[theme.id] ?? theme.id, + })); +} + +function SelectTheme({ disabled }: Readonly<{ disabled?: boolean }>) { + const themes = useThemes(); + const themeNames = useThemeNames(); + const [themeId, setThemeId] = useSetting(settingsAtom, 'themeId'); + + const themeOptions = makeThemeOptions(themes, themeNames); + const selectedThemeId = + themeOptions.find((theme) => theme.value === themeId)?.value ?? LightTheme.id; + + return ( + + ); +} + +function SystemThemePreferences() { + const themeNames = useThemeNames(); + const themes = useThemes(); + const [lightThemeId, setLightThemeId] = useSetting(settingsAtom, 'lightThemeId'); + const [darkThemeId, setDarkThemeId] = useSetting(settingsAtom, 'darkThemeId'); + + const lightThemes = themes.filter((theme) => theme.kind === ThemeKind.Light); + const darkThemes = themes.filter((theme) => theme.kind === ThemeKind.Dark); + const lightThemeOptions = makeThemeOptions(lightThemes, themeNames); + const darkThemeOptions = makeThemeOptions(darkThemes, themeNames); + + const selectedLightThemeId = + lightThemeOptions.find((theme) => theme.value === lightThemeId)?.value ?? LightTheme.id; + const selectedDarkThemeId = + darkThemeOptions.find((theme) => theme.value === darkThemeId)?.value ?? DarkTheme.id; + + return ( + + + } + /> + + } + /> + + ); +} + +function ClassicThemeSection({ onRequestCatalogEnable }: { onRequestCatalogEnable: () => void }) { + const [systemTheme, setSystemTheme] = useSetting(settingsAtom, 'useSystemTheme'); + + return ( + + + } + /> + {systemTheme && } + + + + } + /> + + + + + Enable catalog + + } + /> + + + ); +} + +function RemoteCatalogThemeSection({ + onBrowseOpenChange, +}: { + onBrowseOpenChange?: (open: boolean) => void; +}) { + return ; +} + +export function ThemeAppearanceSection({ + onBrowseOpenChange, +}: { + onBrowseOpenChange?: (open: boolean) => void; +} = {}) { + const store = useStore(); + const [onboardingDone] = useSetting(settingsAtom, 'themeCatalogOnboardingDone'); + const [catalogEnabled] = useSetting(settingsAtom, 'themeRemoteCatalogEnabled'); + + useEffect(() => { + if (!catalogEnabled) onBrowseOpenChange?.(false); + }, [catalogEnabled, onBrowseOpenChange]); + + const completeOnboarding = useCallback( + (enabled: boolean) => { + const next = { ...store.get(settingsAtom), themeCatalogOnboardingDone: true }; + next.themeRemoteCatalogEnabled = enabled; + store.set(settingsAtom, next); + }, + [store] + ); + + const { dialog, openOnboarding } = useThemeCatalogOnboardingGate( + onboardingDone, + completeOnboarding + ); + + return ( + + Theme + {dialog} + {catalogEnabled ? ( + + ) : ( + + )} + + ); +} diff --git a/src/app/features/settings/cosmetics/ThemeCatalogOnboarding.tsx b/src/app/features/settings/cosmetics/ThemeCatalogOnboarding.tsx new file mode 100644 index 000000000..e5fccee75 --- /dev/null +++ b/src/app/features/settings/cosmetics/ThemeCatalogOnboarding.tsx @@ -0,0 +1,151 @@ +import { useCallback, useEffect, useRef, useState } from 'react'; +import FocusTrap from 'focus-trap-react'; +import { + Box, + Button, + config, + Dialog, + Header, + Icon, + IconButton, + Icons, + Overlay, + OverlayBackdrop, + OverlayCenter, + Text, +} from 'folds'; + +import { stopPropagation } from '$utils/keyboard'; + +type ThemeCatalogOnboardingProps = { + open: boolean; + onEnable: () => void; + onDecline: () => void; +}; + +export function ThemeCatalogOnboarding({ open, onEnable, onDecline }: ThemeCatalogOnboardingProps) { + const suppressDeactivateDecline = useRef(false); + + const handleEnableClick = useCallback(() => { + suppressDeactivateDecline.current = true; + onEnable(); + }, [onEnable]); + + const handleDeclineClick = useCallback(() => { + suppressDeactivateDecline.current = true; + onDecline(); + }, [onDecline]); + + const handleTrapDeactivate = useCallback(() => { + if (suppressDeactivateDecline.current) { + suppressDeactivateDecline.current = false; + return; + } + onDecline(); + }, [onDecline]); + + return ( + }> + + + +
    + + Remote themes + + + + +
    + + + Load themes from the official Sable theme catalog on GitHub? You can browse + previews, save favorites locally, and sync them with light and dark mode. If you + choose not to, you can keep using the built-in Light and Dark themes only. + + + + + + +
    +
    +
    +
    + ); +} + +export function useThemeCatalogOnboardingGate( + onboardingDone: boolean, + onComplete: (enabled: boolean) => void +) { + const [open, setOpen] = useState(false); + + useEffect(() => { + if (!onboardingDone) { + setOpen(true); + } + }, [onboardingDone]); + + const handleEnable = useCallback(() => { + setOpen(false); + onComplete(true); + }, [onComplete]); + + const handleDecline = useCallback(() => { + setOpen(false); + onComplete(false); + }, [onComplete]); + + const openOnboarding = useCallback(() => { + setOpen(true); + }, []); + + return { + open, + openOnboarding, + dialog: ( + + ), + }; +} diff --git a/src/app/features/settings/cosmetics/ThemeCatalogSettings.tsx b/src/app/features/settings/cosmetics/ThemeCatalogSettings.tsx new file mode 100644 index 000000000..e602c7dfc --- /dev/null +++ b/src/app/features/settings/cosmetics/ThemeCatalogSettings.tsx @@ -0,0 +1,1584 @@ +import { type ChangeEventHandler, useCallback, useEffect, useMemo, useRef, useState } from 'react'; +import { useTimeoutToggle } from '$hooks/useTimeoutToggle'; +import { copyToClipboard, downloadTextFile } from '$utils/dom'; +import { useQuery, useQueryClient } from '@tanstack/react-query'; +import { + Box, + Button, + Chip, + Icon, + IconButton, + Icons, + Input, + Scroll, + Spinner, + Switch, + Text, + config, + toRem, +} from 'folds'; +import { useClientConfig } from '$hooks/useClientConfig'; +import { ThemeKind } from '$hooks/useTheme'; +import { useSetting } from '$state/hooks/settings'; +import { + settingsAtom, + type Settings, + type ThemeRemoteFavorite, + type ThemeRemoteTweakFavorite, +} from '$state/settings'; +import { SequenceCardStyle } from '$features/settings/styles.css'; +import { SequenceCard } from '$components/sequence-card'; +import { SettingTile } from '$components/setting-tile'; +import { ThemePreviewCard } from '$components/theme/ThemePreviewCard'; +import { usePatchSettings } from './themeSettingsPatch'; +import { ThemeImportModal } from './ThemeImportModal'; +import { getCachedThemeCss, putCachedThemeCss } from '../../../theme/cache'; +import { + fetchThemeCatalogBundle, + type ThemePair, + type TweakCatalogEntry, +} from '../../../theme/catalog'; +import { isLocalImportBundledUrl, isLocalImportThemeUrl } from '../../../theme/localImportUrls'; +import { isThirdPartyThemeUrl } from '../../../theme/themeApproval'; +import { themeCatalogListingBaseUrl } from '../../../theme/catalogDefaults'; +import { + extractFullThemeUrlFromPreview, + parseSableThemeMetadata, + parseSableTweakMetadata, + type SableThemeContrast, +} from '../../../theme/metadata'; +import { previewUrlFromFullThemeUrl } from '../../../theme/previewUrls'; + +export type CatalogPreviewRow = ThemePair & { + previewText: string; + displayName: string; + author?: string; + kind: ThemeKind; + contrast: SableThemeContrast; + tags: string[]; + fullInstallUrl: string; +}; + +export type LocalPreviewRow = ThemeRemoteFavorite & { + previewUrl: string; + previewText: string; + fullCssText: string; + displayName: string; + author?: string; + contrast: SableThemeContrast; + tags: string[]; + importedLocal?: boolean; +}; + +export type CatalogTweakRow = TweakCatalogEntry & { + fullCssText: string; + displayName: string; + description?: string; + author?: string; + tags: string[]; +}; + +export type LocalTweakRow = ThemeRemoteTweakFavorite & { + fullCssText: string; + description?: string; + author?: string; + tags: string[]; +}; + +export type ThemeCatalogSettingsMode = 'full' | 'local' | 'chat' | 'remote' | 'appearance'; + +export { usePatchSettings } from './themeSettingsPatch'; + +type ThemeCatalogSettingsProps = { + mode?: ThemeCatalogSettingsMode; + onBrowseOpenChange?: (open: boolean) => void; +}; + +type CatalogTweakCardProps = { + displayName: string; + description: string; + copyUrl?: string; + thirdPartyChip: boolean; + isFavorited: boolean; + onToggleFavorite: () => void | Promise; + isOn: boolean; + onSetApplied: (v: boolean) => void; + onExport?: () => void; +}; + +function CatalogTweakCard({ + displayName, + description, + copyUrl, + thirdPartyChip, + isFavorited, + onToggleFavorite, + isOn, + onSetApplied, + onExport, +}: CatalogTweakCardProps) { + const [copied, setCopied] = useTimeoutToggle(); + const handleCopy = useCallback(async () => { + if (!copyUrl) return; + if (await copyToClipboard(copyUrl)) setCopied(); + }, [copyUrl, setCopied]); + + return ( + + + + {displayName} + + {description} + + + + {thirdPartyChip && ( + + Third-party URL + + )} + + {copyUrl && ( + { + handleCopy().catch(() => undefined); + }} + > + + + )} + {onExport && ( + { + onExport(); + }} + > + + + )} + { + Promise.resolve(onToggleFavorite()).catch(() => undefined); + }} + > + + + + + + + + ); +} + +export function ThemeCatalogSettings({ + mode = 'full', + onBrowseOpenChange, +}: ThemeCatalogSettingsProps) { + const clientConfig = useClientConfig(); + const patchSettings = usePatchSettings(); + const queryClient = useQueryClient(); + const configBase = clientConfig.themeCatalogBaseUrl?.trim(); + const catalogBase = themeCatalogListingBaseUrl(configBase); + const catalogManifestUrl = clientConfig.themeCatalogManifestUrl?.trim() || undefined; + + const isAppearanceMode = mode === 'appearance'; + const [browseOpen, setBrowseOpen] = useState(false); + const [importModalOpen, setImportModalOpen] = useState(false); + + const appearanceCatalogBrowseWasOpenRef = useRef(false); + const tweakFavoritesSnapshotAtAppearanceCatalogOpenRef = useRef>(new Set()); + + useEffect(() => { + if (isAppearanceMode) { + onBrowseOpenChange?.(browseOpen); + } + }, [browseOpen, isAppearanceMode, onBrowseOpenChange]); + + const isRemoteMode = mode === 'remote' || mode === 'full' || (isAppearanceMode && browseOpen); + const isChatMode = mode === 'chat' || mode === 'full' || (isAppearanceMode && !browseOpen); + const showAssignmentChrome = + mode === 'full' || mode === 'local' || (isAppearanceMode && !browseOpen); + const showSavedLibrary = + (mode === 'full' || mode === 'local' || isAppearanceMode) && !(isAppearanceMode && browseOpen); + + const [getFavorites] = useSetting(settingsAtom, 'themeRemoteFavorites'); + const [favorites, setFavorites] = useState(getFavorites ? getFavorites : []); + const [tweakFavorites] = useSetting(settingsAtom, 'themeRemoteTweakFavorites'); + const [enabledTweakFullUrls] = useSetting(settingsAtom, 'themeRemoteEnabledTweakFullUrls'); + const [systemTheme, setSystemTheme] = useSetting(settingsAtom, 'useSystemTheme'); + const [manualRemoteFullUrl] = useSetting(settingsAtom, 'themeRemoteManualFullUrl'); + const [lightRemoteFullUrl] = useSetting(settingsAtom, 'themeRemoteLightFullUrl'); + const [darkRemoteFullUrl] = useSetting(settingsAtom, 'themeRemoteDarkFullUrl'); + const [sableChatWidgets, setSableChatWidgets] = useSetting( + settingsAtom, + 'themeChatSableWidgetsEnabled' + ); + const [autoPreviewApprovedUrls, setAutoPreviewApprovedUrls] = useSetting( + settingsAtom, + 'themeChatAutoPreviewApprovedUrls' + ); + const [autoPreviewAnyUrl, setAutoPreviewAnyUrl] = useSetting( + settingsAtom, + 'themeChatAutoPreviewAnyUrl' + ); + + useEffect(() => { + if (!isAppearanceMode) { + appearanceCatalogBrowseWasOpenRef.current = false; + return; + } + if (browseOpen && !appearanceCatalogBrowseWasOpenRef.current) { + tweakFavoritesSnapshotAtAppearanceCatalogOpenRef.current = new Set( + tweakFavorites.map((f) => f.fullUrl.trim()).filter(Boolean) + ); + } + appearanceCatalogBrowseWasOpenRef.current = browseOpen; + }, [browseOpen, isAppearanceMode, tweakFavorites]); + + const [themeSearch, setThemeSearch] = useState(''); + const [tweakSearch, setTweakSearch] = useState(''); + const [kindFilter, setKindFilter] = useState<'all' | 'light' | 'dark'>('all'); + const [contrastFilter, setContrastFilter] = useState<'all' | SableThemeContrast>('all'); + const [tweakApplyFilter, setTweakApplyFilter] = useState<'all' | 'enabled' | 'disabled'>('all'); + + useEffect(() => setFavorites(getFavorites ? getFavorites : []), [getFavorites]); + + const onThemeSearchChange: ChangeEventHandler = (e) => + setThemeSearch(e.target.value); + const onTweakSearchChange: ChangeEventHandler = (e) => + setTweakSearch(e.target.value); + + const activeUrls = useMemo( + () => + [manualRemoteFullUrl, lightRemoteFullUrl, darkRemoteFullUrl].filter((u): u is string => + Boolean(u && u.trim().length > 0) + ), + [darkRemoteFullUrl, lightRemoteFullUrl, manualRemoteFullUrl] + ); + + const pruneFavorites = useCallback( + (nextFavorites: ThemeRemoteFavorite[], nextActiveUrls: string[]) => { + const active = new Set(nextActiveUrls); + return nextFavorites.filter((f) => f.pinned === true || active.has(f.fullUrl)); + }, + [] + ); + + const pruneTweakFavorites = useCallback( + (nextFavorites: ThemeRemoteTweakFavorite[], nextEnabledUrls: string[]) => { + const enabled = new Set(nextEnabledUrls); + return nextFavorites.filter((f) => f.pinned === true || enabled.has(f.fullUrl)); + }, + [] + ); + + const clearAssignmentsIfMatch = useCallback( + (fullUrl: string) => { + const partial: Partial = {}; + if (lightRemoteFullUrl === fullUrl) { + partial.themeRemoteLightFullUrl = undefined; + partial.themeRemoteLightKind = undefined; + } + if (darkRemoteFullUrl === fullUrl) { + partial.themeRemoteDarkFullUrl = undefined; + partial.themeRemoteDarkKind = undefined; + } + if (manualRemoteFullUrl === fullUrl) { + partial.themeRemoteManualFullUrl = undefined; + partial.themeRemoteManualKind = undefined; + } + return partial; + }, + [darkRemoteFullUrl, lightRemoteFullUrl, manualRemoteFullUrl] + ); + + const catalogQuery = useQuery({ + queryKey: ['theme-catalog-bundle', catalogBase, catalogManifestUrl ?? ''], + queryFn: () => fetchThemeCatalogBundle(catalogBase, { manifestUrl: catalogManifestUrl }), + enabled: isRemoteMode, + staleTime: 5 * 60_000, + }); + + const previewsQuery = useQuery({ + queryKey: [ + 'theme-catalog-previews', + catalogBase, + catalogQuery.data?.themes?.map((p) => p.previewUrl).join('|') ?? '', + ], + queryFn: async (): Promise => { + const pairs = catalogQuery.data?.themes ?? []; + const rows = await Promise.all( + pairs.map(async (pair) => { + const res = await fetch(pair.previewUrl, { mode: 'cors' }); + const previewText = res.ok ? await res.text() : ''; + const meta = parseSableThemeMetadata(previewText); + const fullFromMeta = extractFullThemeUrlFromPreview(previewText); + const fullInstallUrl = + fullFromMeta && /^https:\/\//i.test(fullFromMeta) ? fullFromMeta : pair.fullUrl; + const kind = meta.kind ?? ThemeKind.Light; + const contrast: SableThemeContrast = meta.contrast === 'high' ? 'high' : 'low'; + return { + ...pair, + previewText, + displayName: meta.name?.trim() || pair.basename, + author: meta.author?.trim() || undefined, + kind, + contrast, + tags: meta.tags ?? [], + fullInstallUrl, + }; + }) + ); + return rows; + }, + enabled: isRemoteMode && Boolean(catalogQuery.data?.themes?.length), + staleTime: 10 * 60_000, + }); + + const tweakDetailsQuery = useQuery({ + queryKey: [ + 'theme-catalog-tweak-details', + catalogBase, + catalogQuery.data?.tweaks?.map((t) => t.fullUrl).join('|') ?? '', + ], + queryFn: async (): Promise => { + const tweaks = catalogQuery.data?.tweaks ?? []; + const rows = await Promise.all( + tweaks.map(async (entry) => { + try { + let text: string; + if (isLocalImportBundledUrl(entry.fullUrl)) { + text = (await getCachedThemeCss(entry.fullUrl)) ?? ''; + } else { + const res = await fetch(entry.fullUrl, { mode: 'cors' }); + text = res.ok ? await res.text() : ''; + } + const meta = parseSableTweakMetadata(text); + return { + ...entry, + fullCssText: text, + displayName: meta.name?.trim() || entry.basename, + description: meta.description?.trim() || undefined, + author: meta.author?.trim() || undefined, + tags: meta.tags ?? [], + }; + } catch { + return { + ...entry, + fullCssText: '', + displayName: entry.basename, + tags: [], + }; + } + }) + ); + return rows; + }, + enabled: isRemoteMode && Boolean(catalogQuery.data?.tweaks?.length), + staleTime: 10 * 60_000, + }); + + const filteredTweakRows = useMemo(() => { + const rows = tweakDetailsQuery.data ?? []; + const q = tweakSearch.trim().toLowerCase(); + if (!q) return rows; + return rows.filter((row) => { + const hay = + `${row.displayName} ${row.basename} ${row.description ?? ''} ${row.tags.join(' ')}`.toLowerCase(); + return hay.includes(q); + }); + }, [tweakDetailsQuery.data, tweakSearch]); + + const catalogTweaksAfterApplyFilter = useMemo(() => { + if (tweakApplyFilter === 'all') return filteredTweakRows; + if (tweakApplyFilter === 'enabled') { + return filteredTweakRows.filter((r) => enabledTweakFullUrls.includes(r.fullUrl)); + } + return filteredTweakRows.filter((r) => !enabledTweakFullUrls.includes(r.fullUrl)); + }, [filteredTweakRows, enabledTweakFullUrls, tweakApplyFilter]); + + const filteredRows = useMemo(() => { + const rows = previewsQuery.data ?? []; + const q = themeSearch.trim().toLowerCase(); + return rows.filter((row) => { + if (kindFilter !== 'all') { + const want = kindFilter === 'dark' ? ThemeKind.Dark : ThemeKind.Light; + if (row.kind !== want) return false; + } + if (contrastFilter !== 'all' && row.contrast !== contrastFilter) return false; + if (q) { + const hay = `${row.displayName} ${row.basename} ${row.tags.join(' ')}`.toLowerCase(); + if (!hay.includes(q)) return false; + } + return true; + }); + }, [previewsQuery.data, themeSearch, kindFilter, contrastFilter]); + + const localPreviewsQuery = useQuery({ + queryKey: ['theme-local-previews', favorites.map((f) => f.fullUrl).join('|')], + enabled: showSavedLibrary && favorites.length > 0, + staleTime: 10 * 60_000, + queryFn: async (): Promise => { + const rows = await Promise.all( + favorites.map(async (fav) => { + const previewUrl = previewUrlFromFullThemeUrl(fav.fullUrl); + if (!previewUrl) return undefined; + + try { + let previewText: string; + let fullCssText = ''; + if (isLocalImportThemeUrl(previewUrl)) { + previewText = (await getCachedThemeCss(previewUrl)) ?? ''; + } else { + const res = await fetch(previewUrl, { mode: 'cors' }); + if (!res.ok) return undefined; + previewText = await res.text(); + } + if (isLocalImportBundledUrl(fav.fullUrl)) { + fullCssText = (await getCachedThemeCss(fav.fullUrl)) ?? ''; + } else { + const fullRes = await fetch(fav.fullUrl, { mode: 'cors' }); + if (fullRes.ok) { + fullCssText = await fullRes.text(); + } + } + const meta = parseSableThemeMetadata(previewText); + const displayName = meta.name?.trim() || fav.displayName || fav.basename; + const contrast: SableThemeContrast = meta.contrast === 'high' ? 'high' : 'low'; + const authorTrim = meta.author?.trim(); + const row: LocalPreviewRow = { + ...fav, + previewUrl, + previewText, + fullCssText, + displayName, + contrast, + tags: meta.tags ?? [], + importedLocal: fav.importedLocal, + ...(authorTrim ? { author: authorTrim } : {}), + }; + return row; + } catch { + return undefined; + } + }) + ); + + return rows.filter((r): r is LocalPreviewRow => Boolean(r)); + }, + }); + + const localTweaksQuery = useQuery({ + queryKey: ['theme-local-tweaks', tweakFavorites.map((f) => f.fullUrl).join('|')], + enabled: showSavedLibrary && tweakFavorites.length > 0, + staleTime: 10 * 60_000, + queryFn: async (): Promise => { + const rows = await Promise.all( + tweakFavorites.map(async (fav) => { + try { + let text: string; + if (isLocalImportBundledUrl(fav.fullUrl)) { + text = (await getCachedThemeCss(fav.fullUrl)) ?? ''; + } else { + const res = await fetch(fav.fullUrl, { mode: 'cors' }); + if (!res.ok) return undefined; + text = await res.text(); + } + const meta = parseSableTweakMetadata(text); + const authorTrim = meta.author?.trim(); + const row: LocalTweakRow = { + ...fav, + fullCssText: text, + displayName: meta.name?.trim() || fav.displayName || fav.basename, + description: meta.description?.trim() || undefined, + tags: meta.tags ?? [], + importedLocal: fav.importedLocal, + ...(authorTrim ? { author: authorTrim } : {}), + }; + return row; + } catch { + return undefined; + } + }) + ); + return rows.filter((r): r is LocalTweakRow => Boolean(r)); + }, + }); + + const removeFavorite = useCallback( + (fullUrl: string) => { + const nextFavorites = favorites.filter((f) => f.fullUrl !== fullUrl); + const cleared = clearAssignmentsIfMatch(fullUrl); + const nextActive = [manualRemoteFullUrl, lightRemoteFullUrl, darkRemoteFullUrl] + .filter((u): u is string => Boolean(u && u.trim().length > 0)) + .filter((u) => u !== fullUrl); + patchSettings({ + ...cleared, + themeRemoteFavorites: pruneFavorites(nextFavorites, nextActive), + }); + }, + [ + clearAssignmentsIfMatch, + darkRemoteFullUrl, + favorites, + lightRemoteFullUrl, + manualRemoteFullUrl, + patchSettings, + pruneFavorites, + ] + ); + + const applyFavoriteToLight = useCallback( + (row: LocalPreviewRow) => { + patchSettings({ + themeRemoteLightFullUrl: row.fullUrl, + themeRemoteLightKind: row.kind, + }); + }, + [patchSettings] + ); + + const applyFavoriteToDark = useCallback( + (row: LocalPreviewRow) => { + patchSettings({ + themeRemoteDarkFullUrl: row.fullUrl, + themeRemoteDarkKind: row.kind, + }); + }, + [patchSettings] + ); + + const applyFavoriteToManual = useCallback( + (row: LocalPreviewRow) => { + patchSettings({ + themeRemoteManualFullUrl: row.fullUrl, + themeRemoteManualKind: row.kind, + }); + }, + [patchSettings] + ); + + const useBuiltinForLightSlot = useCallback( + () => + patchSettings({ + themeRemoteLightFullUrl: undefined, + themeRemoteLightKind: undefined, + }), + [patchSettings] + ); + + const useBuiltinForDarkSlot = useCallback( + () => + patchSettings({ + themeRemoteDarkFullUrl: undefined, + themeRemoteDarkKind: undefined, + }), + [patchSettings] + ); + + const useBuiltinForManualLight = useCallback( + () => + patchSettings({ + themeRemoteManualFullUrl: undefined, + themeRemoteManualKind: undefined, + themeId: 'light-theme', + }), + [patchSettings] + ); + + const useBuiltinForManualDark = useCallback( + () => + patchSettings({ + themeRemoteManualFullUrl: undefined, + themeRemoteManualKind: undefined, + themeId: 'dark-theme', + }), + [patchSettings] + ); + + const prefetchFull = useCallback(async (url: string): Promise => { + try { + if (isLocalImportBundledUrl(url)) { + const cached = await getCachedThemeCss(url); + return Boolean(cached); + } + const res = await fetch(url, { mode: 'cors' }); + if (!res.ok) return false; + const text = await res.text(); + await putCachedThemeCss(url, text); + return true; + } catch { + return false; + } + }, []); + + const toggleFavorite = useCallback( + async (row: CatalogPreviewRow) => { + const existing = favorites.find((f: ThemeRemoteFavorite) => f.fullUrl === row.fullInstallUrl); + if (existing) { + const nextFavorites = favorites.filter((f) => f.fullUrl !== row.fullInstallUrl); + const cleared = clearAssignmentsIfMatch(row.fullInstallUrl); + const nextActive = activeUrls.filter((u) => u !== row.fullInstallUrl); + patchSettings({ + ...cleared, + themeRemoteFavorites: pruneFavorites(nextFavorites, nextActive), + }); + return; + } + const ok = await prefetchFull(row.fullInstallUrl); + if (!ok) return; + const kind: 'light' | 'dark' = row.kind === ThemeKind.Dark ? 'dark' : 'light'; + const next: ThemeRemoteFavorite = { + fullUrl: row.fullInstallUrl, + displayName: row.displayName, + basename: row.basename, + kind, + pinned: true, + }; + patchSettings({ + themeRemoteFavorites: [...favorites, next], + }); + }, + [activeUrls, clearAssignmentsIfMatch, favorites, patchSettings, prefetchFull, pruneFavorites] + ); + + const installFromCatalogLight = useCallback( + async (row: CatalogPreviewRow) => { + const kind: 'light' | 'dark' = row.kind === ThemeKind.Dark ? 'dark' : 'light'; + const nextActive = Array.from( + new Set( + [manualRemoteFullUrl, darkRemoteFullUrl, row.fullInstallUrl].filter(Boolean) as string[] + ) + ); + + let nextFavorites = favorites; + const existing = favorites.find((f) => f.fullUrl === row.fullInstallUrl); + if (!existing) { + const ok = await prefetchFull(row.fullInstallUrl); + if (!ok) return; + nextFavorites = [ + ...favorites, + { + fullUrl: row.fullInstallUrl, + displayName: row.displayName, + basename: row.basename, + kind, + pinned: false, + }, + ]; + } + + patchSettings({ + themeRemoteLightFullUrl: row.fullInstallUrl, + themeRemoteLightKind: kind, + themeRemoteFavorites: pruneFavorites(nextFavorites, nextActive), + }); + }, + [darkRemoteFullUrl, favorites, manualRemoteFullUrl, patchSettings, prefetchFull, pruneFavorites] + ); + + const installFromCatalogDark = useCallback( + async (row: CatalogPreviewRow) => { + const kind: 'light' | 'dark' = row.kind === ThemeKind.Dark ? 'dark' : 'light'; + const nextActive = Array.from( + new Set( + [manualRemoteFullUrl, lightRemoteFullUrl, row.fullInstallUrl].filter(Boolean) as string[] + ) + ); + + let nextFavorites = favorites; + const existing = favorites.find((f) => f.fullUrl === row.fullInstallUrl); + if (!existing) { + const ok = await prefetchFull(row.fullInstallUrl); + if (!ok) return; + nextFavorites = [ + ...favorites, + { + fullUrl: row.fullInstallUrl, + displayName: row.displayName, + basename: row.basename, + kind, + pinned: false, + }, + ]; + } + + patchSettings({ + themeRemoteDarkFullUrl: row.fullInstallUrl, + themeRemoteDarkKind: kind, + themeRemoteFavorites: pruneFavorites(nextFavorites, nextActive), + }); + }, + [ + favorites, + lightRemoteFullUrl, + manualRemoteFullUrl, + patchSettings, + prefetchFull, + pruneFavorites, + ] + ); + + const installFromCatalogManual = useCallback( + async (row: CatalogPreviewRow) => { + const kind: 'light' | 'dark' = row.kind === ThemeKind.Dark ? 'dark' : 'light'; + const nextActive = Array.from( + new Set( + [lightRemoteFullUrl, darkRemoteFullUrl, row.fullInstallUrl].filter(Boolean) as string[] + ) + ); + + let nextFavorites = favorites; + const existing = favorites.find((f) => f.fullUrl === row.fullInstallUrl); + if (!existing) { + const ok = await prefetchFull(row.fullInstallUrl); + if (!ok) return; + nextFavorites = [ + ...favorites, + { + fullUrl: row.fullInstallUrl, + displayName: row.displayName, + basename: row.basename, + kind, + pinned: false, + }, + ]; + } + + patchSettings({ + themeRemoteManualFullUrl: row.fullInstallUrl, + themeRemoteManualKind: kind, + themeRemoteFavorites: pruneFavorites(nextFavorites, nextActive), + }); + }, + [darkRemoteFullUrl, favorites, lightRemoteFullUrl, patchSettings, prefetchFull, pruneFavorites] + ); + + const clearRemote = useCallback(() => { + patchSettings({ + themeRemoteManualFullUrl: undefined, + themeRemoteManualKind: undefined, + themeRemoteLightFullUrl: undefined, + themeRemoteLightKind: undefined, + themeRemoteDarkFullUrl: undefined, + themeRemoteDarkKind: undefined, + }); + }, [patchSettings]); + + const setTweakApplied = useCallback( + async ( + fullUrl: string, + apply: boolean, + hint?: { + displayName?: string; + basename?: string; + pruneUnpinnedFavoriteOnDisable?: boolean; + } + ) => { + const trimmed = fullUrl.trim(); + if (!trimmed) return; + + if (apply) { + const ok = await prefetchFull(trimmed); + if (!ok) return; + const nextEnabled = enabledTweakFullUrls.includes(trimmed) + ? [...enabledTweakFullUrls] + : [...enabledTweakFullUrls, trimmed]; + const nextFavs = [...tweakFavorites]; + if (!nextFavs.some((f) => f.fullUrl === trimmed)) { + const cached = (await getCachedThemeCss(trimmed)) ?? ''; + const meta = parseSableTweakMetadata(cached); + const base = + trimmed + .replace(/\.sable\.css(\?.*)?$/i, '') + .split('/') + .pop() ?? 'tweak'; + nextFavs.push({ + fullUrl: trimmed, + displayName: hint?.displayName ?? meta.name?.trim() ?? base, + basename: hint?.basename ?? meta.id?.trim() ?? base, + pinned: false, + }); + } + patchSettings({ + themeRemoteEnabledTweakFullUrls: nextEnabled, + themeRemoteTweakFavorites: pruneTweakFavorites(nextFavs, nextEnabled), + }); + } else { + const nextEnabled = enabledTweakFullUrls.filter((u) => u !== trimmed); + if (hint?.pruneUnpinnedFavoriteOnDisable) { + const enabledSet = new Set(nextEnabled); + const inLibraryBeforeThisCatalogVisit = + tweakFavoritesSnapshotAtAppearanceCatalogOpenRef.current; + const nextTweakFavs = tweakFavorites.filter( + (f) => + f.pinned === true || + enabledSet.has(f.fullUrl) || + inLibraryBeforeThisCatalogVisit.has(f.fullUrl.trim()) + ); + patchSettings({ + themeRemoteEnabledTweakFullUrls: nextEnabled, + themeRemoteTweakFavorites: nextTweakFavs, + }); + } else { + patchSettings({ + themeRemoteEnabledTweakFullUrls: nextEnabled, + }); + } + } + }, + [enabledTweakFullUrls, patchSettings, prefetchFull, pruneTweakFavorites, tweakFavorites] + ); + + const toggleCatalogTweakFavorite = useCallback( + async (row: CatalogTweakRow) => { + const existing = tweakFavorites.find((f) => f.fullUrl === row.fullUrl); + if (existing) { + const nextFavs = tweakFavorites.filter((f) => f.fullUrl !== row.fullUrl); + const nextEnabled = enabledTweakFullUrls.filter((u) => u !== row.fullUrl); + patchSettings({ + themeRemoteTweakFavorites: pruneTweakFavorites(nextFavs, nextEnabled), + themeRemoteEnabledTweakFullUrls: nextEnabled, + }); + return; + } + const ok = await prefetchFull(row.fullUrl); + if (!ok) return; + const next: ThemeRemoteTweakFavorite = { + fullUrl: row.fullUrl, + displayName: row.displayName, + basename: row.basename, + pinned: true, + }; + patchSettings({ + themeRemoteTweakFavorites: pruneTweakFavorites( + [...tweakFavorites, next], + enabledTweakFullUrls + ), + }); + }, + [enabledTweakFullUrls, patchSettings, prefetchFull, pruneTweakFavorites, tweakFavorites] + ); + + const removeTweakFavorite = useCallback( + (fullUrl: string) => { + const nextFavs = tweakFavorites.filter((f) => f.fullUrl !== fullUrl); + const nextEnabled = enabledTweakFullUrls.filter((u) => u !== fullUrl); + patchSettings({ + themeRemoteTweakFavorites: pruneTweakFavorites(nextFavs, nextEnabled), + themeRemoteEnabledTweakFullUrls: nextEnabled, + }); + }, + [enabledTweakFullUrls, patchSettings, pruneTweakFavorites, tweakFavorites] + ); + + const downloadThemeFile = useCallback((row: LocalPreviewRow) => { + const filename = `${row.basename || 'theme'}.sable.css`; + downloadTextFile(row.fullCssText, filename); + }, []); + + const downloadTweakFile = useCallback((row: LocalTweakRow) => { + const filename = `${row.basename || 'tweak'}.sable.css`; + downloadTextFile(row.fullCssText, filename); + }, []); + + const catalogBundle = catalogQuery.data; + const catalogThemeCount = catalogBundle?.themes.length ?? 0; + const catalogTweakCount = catalogBundle?.tweaks.length ?? 0; + const catalogHasEntries = catalogThemeCount + catalogTweakCount > 0; + + return ( + + {showAssignmentChrome && ( + <> + + } + /> + + {systemTheme ? ( + + + + + ) : ( + + + + + )} + + + + + Clear + + } + /> + + + )} + + {showSavedLibrary && ( + <> + + Saved themes + {localPreviewsQuery.isPending && favorites.length > 0 && ( + + + Loading local previews… + + )} + + {favorites.length === 0 && ( + + No saved themes yet. Star themes in the catalog to download them locally. + + )} + + {localPreviewsQuery.isSuccess && favorites.length > 0 && ( + <> + {localPreviewsQuery.data.length === 0 ? ( + + Could not load local previews. If this happens, the theme preview file may be + missing or not paired as `*.preview.sable.css`. + + ) : ( + + {localPreviewsQuery.data.map((row) => { + const slug = row.basename.replace(/[^a-zA-Z0-9_-]/g, '-') || 'theme'; + const kindLabel = row.kind === 'dark' ? 'Dark' : 'Light'; + const line1 = `${kindLabel} · ${row.contrast} contrast`; + const line2 = `${row.author ? `by ${row.author}` : ''}${ + row.tags.length > 0 + ? `${row.author ? ' · ' : ''}${row.tags.join(', ')}` + : '' + }`.trim(); + const subtitle = ( + <> + {line1} + {line2 ? ( + <> +
    + {line2} + + ) : null} + + ); + return ( + removeFavorite(row.fullUrl)} + onExport={() => downloadThemeFile(row)} + systemTheme={systemTheme} + onApplyLight={systemTheme ? () => applyFavoriteToLight(row) : undefined} + onApplyDark={systemTheme ? () => applyFavoriteToDark(row) : undefined} + onApplyManual={ + !systemTheme ? () => applyFavoriteToManual(row) : undefined + } + isAppliedLight={lightRemoteFullUrl === row.fullUrl} + isAppliedDark={darkRemoteFullUrl === row.fullUrl} + isAppliedManual={manualRemoteFullUrl === row.fullUrl} + /> + ); + })} +
    + )} + + )} +
    + + + Saved tweaks + {localTweaksQuery.isPending && tweakFavorites.length > 0 && ( + + + Loading tweaks… + + )} + {tweakFavorites.length === 0 && ( + + No saved tweaks. Favorite tweaks in the catalog to keep them here, or enable a tweak + to cache it automatically. + + )} + {localTweaksQuery.isSuccess && tweakFavorites.length > 0 && ( + + {localTweaksQuery.data.length === 0 ? ( + + Could not load tweak CSS. Check the URL or your connection. + + ) : ( + localTweaksQuery.data.map((row) => { + const isOn = enabledTweakFullUrls.includes(row.fullUrl); + const descParts = [ + row.description, + row.author ? `by ${row.author}` : '', + row.tags.length > 0 ? row.tags.join(', ') : '', + ].filter(Boolean); + const desc = + descParts.join(' · ') || + 'Applies on top of your current theme after it loads.'; + return ( + removeTweakFavorite(row.fullUrl)} + onExport={() => downloadTweakFile(row)} + isOn={isOn} + onSetApplied={(v) => + setTweakApplied(row.fullUrl, v, { + displayName: row.displayName, + basename: row.basename, + }) + } + /> + ); + }) + )} + + )} + + + )} + + {isAppearanceMode && !browseOpen && ( + <> + + setBrowseOpen(true)} + > + Browse catalog… + + } + /> + + + + setImportModalOpen(true)} + > + Import… + + } + /> + + + setImportModalOpen(false)} /> + + )} + + {isRemoteMode && ( + <> + {!isAppearanceMode && Browse catalog} + + {(isAppearanceMode && browseOpen) || + catalogQuery.isPending || + catalogQuery.isError || + (catalogQuery.isSuccess && + ((catalogThemeCount > 0 && previewsQuery.isPending) || + (catalogTweakCount > 0 && tweakDetailsQuery.isPending))) ? ( + + {isAppearanceMode && browseOpen && ( + + + Browse catalog + + Download themes and tweaks from the catalog. + + + + + + + + )} + + {(catalogQuery.isPending || catalogQuery.isError) && ( + + {catalogQuery.isPending && ( + + + Loading catalog… + + )} + {catalogQuery.isError && ( + + {catalogQuery.error?.message ?? 'Failed to load catalog'} + + )} + + )} + + {catalogQuery.isSuccess && catalogThemeCount > 0 && previewsQuery.isPending && ( + + + Loading previews… + + )} + + {catalogQuery.isSuccess && catalogTweakCount > 0 && tweakDetailsQuery.isPending && ( + + + Loading tweaks… + + )} + + ) : null} + + {catalogQuery.isSuccess && + catalogHasEntries && + catalogThemeCount > 0 && + previewsQuery.isSuccess && ( + + + + + Kind: + {(['all', 'light', 'dark'] as const).map((k) => ( + setKindFilter(k)} + > + {k === 'all' ? 'All' : k} + + ))} + Contrast: + {(['all', 'low', 'high'] as const).map((c) => ( + setContrastFilter(c)} + > + {c === 'all' ? 'All' : c} + + ))} + + + + + {filteredRows.map((row) => { + const slug = row.basename.replace(/[^a-zA-Z0-9_-]/g, '-') || 'theme'; + const kindLabel = row.kind === ThemeKind.Dark ? 'Dark' : 'Light'; + const isFav = favorites.some((f) => f.fullUrl === row.fullInstallUrl); + const line1 = `${kindLabel} · ${row.contrast} contrast`; + const line2 = `${row.author ? `by ${row.author}` : ''}${ + row.tags.length > 0 + ? `${row.author ? ' · ' : ''}${row.tags.join(', ')}` + : '' + }`.trim(); + const subtitle = ( + <> + {line1} + {line2 ? ( + <> +
    + {line2} + + ) : null} + + ); + return ( + toggleFavorite(row)} + systemTheme={systemTheme} + onApplyLight={ + systemTheme ? () => installFromCatalogLight(row) : undefined + } + onApplyDark={ + systemTheme ? () => installFromCatalogDark(row) : undefined + } + onApplyManual={ + !systemTheme ? () => installFromCatalogManual(row) : undefined + } + isAppliedLight={lightRemoteFullUrl === row.fullInstallUrl} + isAppliedDark={darkRemoteFullUrl === row.fullInstallUrl} + isAppliedManual={manualRemoteFullUrl === row.fullInstallUrl} + /> + ); + })} +
    + + {filteredRows.length === 0 && ( + + No themes match filters. + + )} +
    +
    +
    + )} + + {catalogQuery.isSuccess && + catalogHasEntries && + catalogTweakCount > 0 && + tweakDetailsQuery.isSuccess && ( + + + + + Status: + {(['all', 'enabled', 'disabled'] as const).map((f) => ( + setTweakApplyFilter(f)} + > + + { + { + all: 'All', + enabled: 'Enabled', + disabled: 'Disabled', + }[f] + } + + + ))} + + + + {catalogTweaksAfterApplyFilter.map((row) => { + const isFav = tweakFavorites.some((f) => f.fullUrl === row.fullUrl); + const isOn = enabledTweakFullUrls.includes(row.fullUrl); + const descParts = [ + row.description, + row.author ? `by ${row.author}` : '', + row.tags.length > 0 ? row.tags.join(', ') : '', + ].filter(Boolean); + const desc = + descParts.join(' · ') || + 'Applies on top of your current theme after it loads.'; + return ( + toggleCatalogTweakFavorite(row)} + isOn={isOn} + onSetApplied={(v) => + setTweakApplied(row.fullUrl, v, { + displayName: row.displayName, + basename: row.basename, + pruneUnpinnedFavoriteOnDisable: true, + }) + } + /> + ); + })} + {filteredTweakRows.length === 0 && ( + + No tweaks match your search. + + )} + {filteredTweakRows.length > 0 && catalogTweaksAfterApplyFilter.length === 0 && ( + + No tweaks match this status filter. + + )} + + + + )} + + )} + + {isChatMode && ( + <> + + + } + /> + + + + } + /> + + + + } + /> + + + )} +
    + ); +} diff --git a/src/app/features/settings/cosmetics/ThemeImportModal.tsx b/src/app/features/settings/cosmetics/ThemeImportModal.tsx new file mode 100644 index 000000000..10c50e951 --- /dev/null +++ b/src/app/features/settings/cosmetics/ThemeImportModal.tsx @@ -0,0 +1,364 @@ +import { type ChangeEventHandler, useCallback, useEffect, useMemo, useRef, useState } from 'react'; +import FocusTrap from 'focus-trap-react'; +import { + Box, + Button, + config, + Dialog, + Header, + Icon, + IconButton, + Icons, + Input, + Overlay, + OverlayBackdrop, + OverlayCenter, + Text, + toRem, +} from 'folds'; + +import { useSetting } from '$state/hooks/settings'; +import { + settingsAtom, + type ThemeRemoteFavorite, + type ThemeRemoteTweakFavorite, +} from '$state/settings'; +import { stopPropagation } from '$utils/keyboard'; + +import { SequenceCardStyle } from '$features/settings/styles.css'; +import { SequenceCard } from '$components/sequence-card'; +import { + processImportedHttpsUrl, + processPastedOrUploadedCss, + type ProcessedThemeImport, +} from '../../../theme/processThemeImport'; + +import { usePatchSettings } from './themeSettingsPatch'; + +type ThemeImportModalProps = { + open: boolean; + onClose: () => void; +}; + +export function ThemeImportModal({ open, onClose }: ThemeImportModalProps) { + const patchSettings = usePatchSettings(); + const [favorites] = useSetting(settingsAtom, 'themeRemoteFavorites'); + const [tweakFavorites] = useSetting(settingsAtom, 'themeRemoteTweakFavorites'); + const [enabledTweakFullUrls] = useSetting(settingsAtom, 'themeRemoteEnabledTweakFullUrls'); + const [manualRemoteFullUrl] = useSetting(settingsAtom, 'themeRemoteManualFullUrl'); + const [lightRemoteFullUrl] = useSetting(settingsAtom, 'themeRemoteLightFullUrl'); + const [darkRemoteFullUrl] = useSetting(settingsAtom, 'themeRemoteDarkFullUrl'); + + const [importUrl, setImportUrl] = useState(''); + const [importPaste, setImportPaste] = useState(''); + const [uploadedFileCss, setUploadedFileCss] = useState(null); + const [importError, setImportError] = useState(null); + const [importBusy, setImportBusy] = useState(false); + const [importFileName, setImportFileName] = useState(undefined); + const importFileRef = useRef(null); + + const activeUrls = useMemo( + () => + [manualRemoteFullUrl, lightRemoteFullUrl, darkRemoteFullUrl].filter((u): u is string => + Boolean(u && u.trim().length > 0) + ), + [darkRemoteFullUrl, lightRemoteFullUrl, manualRemoteFullUrl] + ); + + const pruneFavorites = useCallback( + (nextFavorites: ThemeRemoteFavorite[], nextActiveUrls: string[]) => { + const active = new Set(nextActiveUrls); + return nextFavorites.filter((f) => f.pinned === true || active.has(f.fullUrl)); + }, + [] + ); + + const pruneTweakFavorites = useCallback( + (nextFavorites: ThemeRemoteTweakFavorite[], nextEnabledUrls: string[]) => { + const enabled = new Set(nextEnabledUrls); + return nextFavorites.filter((f) => f.pinned === true || enabled.has(f.fullUrl)); + }, + [] + ); + + useEffect(() => { + if (!open) { + setImportUrl(''); + setImportPaste(''); + setUploadedFileCss(null); + setImportError(null); + setImportFileName(undefined); + if (importFileRef.current) importFileRef.current.value = ''; + } + }, [open]); + + const onImportUrlChange: ChangeEventHandler = (e) => + setImportUrl(e.target.value); + + const onImportPasteChange: ChangeEventHandler = (e) => + setImportPaste(e.target.value); + + const addImportedResult = useCallback( + (r: Extract) => { + if (r.role === 'tweak') { + const existing = tweakFavorites.find((f) => f.fullUrl === r.fullUrl); + if (existing) { + setImportError('That tweak is already saved.'); + return; + } + const next: ThemeRemoteTweakFavorite = { + fullUrl: r.fullUrl, + displayName: r.displayName, + basename: r.basename, + pinned: true, + importedLocal: r.importedLocal, + }; + const nextEnabled = enabledTweakFullUrls.includes(r.fullUrl) + ? [...enabledTweakFullUrls] + : [...enabledTweakFullUrls, r.fullUrl]; + patchSettings({ + themeRemoteTweakFavorites: pruneTweakFavorites([...tweakFavorites, next], nextEnabled), + themeRemoteEnabledTweakFullUrls: nextEnabled, + }); + onClose(); + return; + } + + const existing = favorites.find((f) => f.fullUrl === r.fullUrl); + if (existing) { + setImportError('That theme is already saved.'); + return; + } + const next: ThemeRemoteFavorite = { + fullUrl: r.fullUrl, + displayName: r.displayName, + basename: r.basename, + kind: r.kind, + pinned: true, + importedLocal: r.importedLocal, + }; + const nextActive = Array.from( + new Set( + [...activeUrls, r.fullUrl].filter((u): u is string => Boolean(u && u.trim().length > 0)) + ) + ); + patchSettings({ + themeRemoteFavorites: pruneFavorites([...favorites, next], nextActive), + }); + onClose(); + }, + [ + activeUrls, + enabledTweakFullUrls, + favorites, + onClose, + patchSettings, + pruneFavorites, + pruneTweakFavorites, + tweakFavorites, + ] + ); + + const onImportFileChange: ChangeEventHandler = (e) => { + const file = e.target.files?.[0]; + if (!file) return; + setImportFileName(file.name); + setImportPaste(''); + const reader = new FileReader(); + reader.addEventListener('load', () => { + setUploadedFileCss(typeof reader.result === 'string' ? reader.result : ''); + }); + reader.readAsText(file); + }; + + const handleImportTheme = useCallback(async () => { + setImportError(null); + const urlTrim = importUrl.trim(); + if (/^https:\/\//i.test(urlTrim)) { + setImportBusy(true); + try { + const result = await processImportedHttpsUrl(urlTrim); + if (!result.ok) { + setImportError(result.error); + return; + } + addImportedResult(result); + } finally { + setImportBusy(false); + } + return; + } + const pasted = importPaste.trim(); + const fromFile = uploadedFileCss?.trim(); + const cssToImport = fromFile || pasted; + if (!cssToImport) { + setImportError('Enter an URL, paste CSS, or choose a file.'); + return; + } + setImportBusy(true); + try { + const result = await processPastedOrUploadedCss( + cssToImport, + fromFile ? importFileName : undefined + ); + if (!result.ok) { + setImportError(result.error); + return; + } + addImportedResult(result); + } finally { + setImportBusy(false); + } + }, [addImportedResult, importFileName, importPaste, importUrl, uploadedFileCss]); + + const dismissSafe = useCallback(() => { + if (importBusy) return; + onClose(); + }, [importBusy, onClose]); + + if (!open) return null; + + return ( + }> + + + +
    + + + Import a theme or tweak + + + + + +
    + + + Paste a link to a .sable.css file, or paste CSS / upload a file. + Files whose first metadata block uses @sable-tweak are saved as + tweaks (applied on top of your current theme and turned on immediately). Themes use{' '} + @sable-theme. If theme CSS includes fullThemeUrl{' '} + and that URL loads, it is used; otherwise the theme is stored only on this device. + + + + {importFileName && uploadedFileCss !== null && ( + + + Loaded file: {importFileName}. + + + + )} +