mirror of
https://github.com/SableClient/Sable.git
synced 2026-11-20 00:51:17 -08:00
Merge branch 'dev' of github.com:SableClient/Sable into hazre/feat/arborium-migration
# Conflicts: # src/app/plugins/react-custom-html-parser.test.tsx # src/app/plugins/react-custom-html-parser.tsx # src/app/utils/sanitize.test.ts # src/app/utils/sanitize.ts
This commit is contained in:
65 files changed
+2328
-743
No files matched your search
@@ -1,5 +0,0 @@
|
||||
---
|
||||
default: patch
|
||||
---
|
||||
|
||||
Add detailed error messages to forwarding failures.
|
||||
@@ -1,5 +0,0 @@
|
||||
---
|
||||
default: minor
|
||||
---
|
||||
|
||||
# Add black theme
|
||||
@@ -1,5 +0,0 @@
|
||||
---
|
||||
default: minor
|
||||
---
|
||||
|
||||
Add /location sharing command, and a /sharemylocation command.
|
||||
@@ -1,5 +0,0 @@
|
||||
---
|
||||
default: minor
|
||||
---
|
||||
|
||||
Add quick reply keybinds by using <kbd>ctrl</kbd>+<kbd>up</kbd> / <kbd>ctrl</kbd>+<kbd>down</kbd> you can now cycle through the message you are replying to with keybinds
|
||||
@@ -1,5 +0,0 @@
|
||||
---
|
||||
default: patch
|
||||
---
|
||||
|
||||
Cap unread badge numbers at `1k+`, and something extra :)
|
||||
@@ -1,5 +0,0 @@
|
||||
---
|
||||
default: minor
|
||||
---
|
||||
|
||||
Add room abbreviations with hover tooltips: moderators define term/definition pairs in room settings; matching terms are highlighted in messages.
|
||||
@@ -1,5 +0,0 @@
|
||||
---
|
||||
default: patch
|
||||
---
|
||||
|
||||
Fixes the most recent pmp message in encrypted rooms not consistently rendering the pmp and not grouping with previous pmps.
|
||||
@@ -1,5 +0,0 @@
|
||||
---
|
||||
default: patch
|
||||
---
|
||||
|
||||
fixed sending sticker and attachments while having a persona selected
|
||||
@@ -1,5 +0,0 @@
|
||||
---
|
||||
default: patch
|
||||
---
|
||||
|
||||
Fix broken link to Sliding Sync known issues — now points to SableClient/Sable#39 instead of the old repository.
|
||||
@@ -1,5 +0,0 @@
|
||||
---
|
||||
default: patch
|
||||
---
|
||||
|
||||
Fix service worker authenticated media requests returning 401 errors after SW restart or when session data is missing/stale.
|
||||
@@ -1,5 +0,0 @@
|
||||
---
|
||||
default: patch
|
||||
---
|
||||
|
||||
# Fix confusing ui with `Client Side Embeds in Encrypted Rooms` setting
|
||||
@@ -1,5 +0,0 @@
|
||||
---
|
||||
default: patch
|
||||
---
|
||||
|
||||
fix forwarding metadata by removing the `null` value
|
||||
@@ -1,5 +0,0 @@
|
||||
---
|
||||
default: patch
|
||||
---
|
||||
|
||||
fix the display of jumbo emojis on messages sent with a persona
|
||||
@@ -1,5 +0,0 @@
|
||||
---
|
||||
default: patch
|
||||
---
|
||||
|
||||
Fix sidebar notification badge positioning so unread and unverified counts align consistently.
|
||||
@@ -1,5 +0,0 @@
|
||||
---
|
||||
default: minor
|
||||
---
|
||||
|
||||
# Add support for timestamps, playlists and youtube music links for the youtube embeds
|
||||
@@ -1,5 +0,0 @@
|
||||
---
|
||||
default: note
|
||||
---
|
||||
|
||||
moved the setting for filtering pronouns by language from experimental to the appearance setting
|
||||
@@ -1,5 +0,0 @@
|
||||
---
|
||||
default: patch
|
||||
---
|
||||
|
||||
Use the browser's native compact number formatting for room and member counts.
|
||||
@@ -1,5 +0,0 @@
|
||||
---
|
||||
default: patch
|
||||
---
|
||||
|
||||
fix(sentry): scrub percent-encoded Matrix IDs and opaque base64url tokens from Sentry URLs
|
||||
@@ -1,5 +0,0 @@
|
||||
---
|
||||
default: minor
|
||||
---
|
||||
|
||||
Add settings sync across devices via Matrix account data, with JSON export/import
|
||||
@@ -0,0 +1,101 @@
|
||||
# For most projects, this workflow file will not need changing; you simply need
|
||||
# to commit it to your repository.
|
||||
#
|
||||
# You may wish to alter this file to override the set of languages analyzed,
|
||||
# or to provide custom queries or build logic.
|
||||
#
|
||||
# ******** NOTE ********
|
||||
# We have attempted to detect the languages in your repository. Please check
|
||||
# the `language` matrix defined below to confirm you have the correct set of
|
||||
# supported CodeQL languages.
|
||||
#
|
||||
name: 'CodeQL Advanced'
|
||||
|
||||
on:
|
||||
push:
|
||||
branches: ['dev']
|
||||
pull_request:
|
||||
branches: ['dev']
|
||||
schedule:
|
||||
- cron: '29 1 * * 2'
|
||||
|
||||
jobs:
|
||||
analyze:
|
||||
name: Analyze (${{ matrix.language }})
|
||||
# Runner size impacts CodeQL analysis time. To learn more, please see:
|
||||
# - https://gh.io/recommended-hardware-resources-for-running-codeql
|
||||
# - https://gh.io/supported-runners-and-hardware-resources
|
||||
# - https://gh.io/using-larger-runners (GitHub.com only)
|
||||
# Consider using larger runners or machines with greater resources for possible analysis time improvements.
|
||||
runs-on: ${{ (matrix.language == 'swift' && 'macos-latest') || 'ubuntu-latest' }}
|
||||
permissions:
|
||||
# required for all workflows
|
||||
security-events: write
|
||||
|
||||
# required to fetch internal or private CodeQL packs
|
||||
packages: read
|
||||
|
||||
# only required for workflows in private repositories
|
||||
actions: read
|
||||
contents: read
|
||||
|
||||
strategy:
|
||||
fail-fast: false
|
||||
matrix:
|
||||
include:
|
||||
- language: actions
|
||||
build-mode: none
|
||||
- language: javascript-typescript
|
||||
build-mode: none
|
||||
# CodeQL supports the following values keywords for 'language': 'actions', 'c-cpp', 'csharp', 'go', 'java-kotlin', 'javascript-typescript', 'python', 'ruby', 'rust', 'swift'
|
||||
# Use `c-cpp` to analyze code written in C, C++ or both
|
||||
# Use 'java-kotlin' to analyze code written in Java, Kotlin or both
|
||||
# Use 'javascript-typescript' to analyze code written in JavaScript, TypeScript or both
|
||||
# To learn more about changing the languages that are analyzed or customizing the build mode for your analysis,
|
||||
# see https://docs.github.com/en/code-security/code-scanning/creating-an-advanced-setup-for-code-scanning/customizing-your-advanced-setup-for-code-scanning.
|
||||
# If you are analyzing a compiled language, you can modify the 'build-mode' for that language to customize how
|
||||
# your codebase is analyzed, see https://docs.github.com/en/code-security/code-scanning/creating-an-advanced-setup-for-code-scanning/codeql-code-scanning-for-compiled-languages
|
||||
steps:
|
||||
- name: Checkout repository
|
||||
uses: actions/checkout@de0fac2e4500dabe0009e67214ff5f5447ce83dd # v6.0.2
|
||||
|
||||
# Add any setup steps before running the `github/codeql-action/init` action.
|
||||
# This includes steps like installing compilers or runtimes (`actions/setup-node`
|
||||
# or others). This is typically only required for manual builds.
|
||||
# - name: Setup runtime (example)
|
||||
# uses: actions/setup-example@v1
|
||||
|
||||
# Initializes the CodeQL tools for scanning.
|
||||
- name: Initialize CodeQL
|
||||
uses: github/codeql-action/init@c10b8064de6f491fea524254123dbe5e09572f13
|
||||
with:
|
||||
languages: ${{ matrix.language }}
|
||||
build-mode: ${{ matrix.build-mode }}
|
||||
# If you wish to specify custom queries, you can do so here or in a config file.
|
||||
# By default, queries listed here will override any specified in a config file.
|
||||
# Prefix the list here with "+" to use these queries and those in the config file.
|
||||
|
||||
# For more details on CodeQL's query packs, refer to: https://docs.github.com/en/code-security/code-scanning/automatically-scanning-your-code-for-vulnerabilities-and-errors/configuring-code-scanning#using-queries-in-ql-packs
|
||||
# queries: security-extended,security-and-quality
|
||||
|
||||
# If the analyze step fails for one of the languages you are analyzing with
|
||||
# "We were unable to automatically build your code", modify the matrix above
|
||||
# to set the build mode to "manual" for that language. Then modify this step
|
||||
# to build your code.
|
||||
# ℹ️ Command-line programs to run using the OS shell.
|
||||
# 📚 See https://docs.github.com/en/actions/using-workflows/workflow-syntax-for-github-actions#jobsjob_idstepsrun
|
||||
- name: Run manual build steps
|
||||
if: matrix.build-mode == 'manual'
|
||||
shell: bash
|
||||
run: |
|
||||
echo 'If you are using a "manual" build mode for one or more of the' \
|
||||
'languages you are analyzing, replace this with the commands to build' \
|
||||
'your code, for example:'
|
||||
echo ' make bootstrap'
|
||||
echo ' make release'
|
||||
exit 1
|
||||
|
||||
- name: Perform CodeQL Analysis
|
||||
uses: github/codeql-action/analyze@c10b8064de6f491fea524254123dbe5e09572f13
|
||||
with:
|
||||
category: '/language:${{matrix.language}}'
|
||||
@@ -1,5 +1,55 @@
|
||||
# Sable Client Changelog
|
||||
|
||||
## 1.13.1 (2026-03-30)
|
||||
|
||||
### Fixes
|
||||
|
||||
* Add youtube shorts support to stop it from crashing sable. ([#578](https://github.com/SableClient/Sable/pull/578) by @nushea)
|
||||
* Fix rich-text reply previews and custom-formatted messages so unsafe HTML is filtered more strictly and Matrix colors render correctly. ([#571](https://github.com/SableClient/Sable/pull/571) by @hazre)
|
||||
* Fix crash when previewing non-video YouTube URLs (channels, @handles, etc.) that lack query parameters. ([#584](https://github.com/SableClient/Sable/pull/584) by @Just-Insane)
|
||||
* fix id handling and id generation for Personas ([#583](https://github.com/SableClient/Sable/pull/583) by @dozro)
|
||||
|
||||
## 1.13.0 (2026-03-28)
|
||||
|
||||
### Features
|
||||
|
||||
* Add ability to click on usernames in member and state events to view user info ([#536](https://github.com/SableClient/Sable/pull/536) by @thundertheidiot)
|
||||
* Add black theme ([#437](https://github.com/SableClient/Sable/pull/437) by @Elec3137)
|
||||
* added a limited compatibility with `pk;member` commands ([#550](https://github.com/SableClient/Sable/pull/550) by @dozro)
|
||||
* Add /location sharing command, and a /sharemylocation command. ([#509](https://github.com/SableClient/Sable/pull/509) by @nushea)
|
||||
* added option to use shorthands to send a message with a Persona, for example `✨:test` ([#550](https://github.com/SableClient/Sable/pull/550) by @dozro)
|
||||
* Add quick reply keybinds by using <kbd>ctrl</kbd>+<kbd>up</kbd> / <kbd>ctrl</kbd>+<kbd>down</kbd> you can now cycle through the message you are replying to with keybinds ([#524](https://github.com/SableClient/Sable/pull/524) by @CodeF53)
|
||||
* Adds a `/html` command to send HTML messages ([#560](https://github.com/SableClient/Sable/pull/560) by @Vespe-r)
|
||||
* Add room abbreviations with hover tooltips: moderators define term/definition pairs in room settings; matching terms are highlighted in messages. ([#514](https://github.com/SableClient/Sable/pull/514) by @Just-Insane)
|
||||
* Add support for timestamps, playlists and youtube music links for the youtube embeds ([#534](https://github.com/SableClient/Sable/pull/534) by @thundertheidiot)
|
||||
* Add settings sync across devices via Matrix account data, with JSON export/import ([#515](https://github.com/SableClient/Sable/pull/515) by @Just-Insane)
|
||||
|
||||
### Fixes
|
||||
|
||||
* Add detailed error messages to forwarding failures. ([#532](https://github.com/SableClient/Sable/pull/532) by @7w1)
|
||||
* Cap unread badge numbers at `1k+`, and something extra :) ([#484](https://github.com/SableClient/Sable/pull/484) by @hazre)
|
||||
* Fix scroll-to-bottom after room navigation, timeline pagination reliability, and URL preview deduplication. ([#529](https://github.com/SableClient/Sable/pull/529) by @Just-Insane)
|
||||
* Fixes the most recent pmp message in encrypted rooms not consistently rendering the pmp and not grouping with previous pmps. ([#526](https://github.com/SableClient/Sable/pull/526) by @7w1)
|
||||
* fixed sending sticker and attachments while having a persona selected ([#525](https://github.com/SableClient/Sable/pull/525) by @dozro)
|
||||
* Fix push notifications missing sender/room avatar and showing stale display names when using event_id_only push format. ([#551](https://github.com/SableClient/Sable/pull/551) by @Just-Insane)
|
||||
* Sanitize formatted reply previews before rendering to prevent unsafe HTML from being parsed in reply snippets. ([#569](https://github.com/SableClient/Sable/pull/569) by @Just-Insane)
|
||||
* Fix broken link to Sliding Sync known issues — now points to SableClient/Sable#39 instead of the old repository. ([#519](https://github.com/SableClient/Sable/pull/519) by @Just-Insane)
|
||||
* Fix service worker authenticated media requests returning 401 errors after SW restart or when session data is missing/stale. ([#516](https://github.com/SableClient/Sable/pull/516) by @Just-Insane)
|
||||
* rephrased the command describtion for `/usepmp` and made `/usepmp reset` actually reset the room association of the pmp ([#550](https://github.com/SableClient/Sable/pull/550) by @dozro)
|
||||
* Fix confusing ui with `Client Side Embeds in Encrypted Rooms` setting ([#535](https://github.com/SableClient/Sable/pull/535) by @thundertheidiot)
|
||||
* fix forwarding metadata by removing the `null` value ([#540](https://github.com/SableClient/Sable/pull/540) by @dozro)
|
||||
* fix forwarding issue for users on synapse homeservers, by removing the relation ([#558](https://github.com/SableClient/Sable/pull/558) by @dozro)
|
||||
* fixed the syntax issues regarding `/addpmp` and `usepmp` (note that the syntax for `/usepmp` has changed) ([#550](https://github.com/SableClient/Sable/pull/550) by @dozro)
|
||||
* fix the display of jumbo emojis on messages sent with a persona ([#530](https://github.com/SableClient/Sable/pull/530) by @dozro)
|
||||
* Fix sidebar notification badge positioning so unread and unverified counts align consistently. ([#484](https://github.com/SableClient/Sable/pull/484) by @hazre)
|
||||
* Use the browser's native compact number formatting for room and member counts. ([#484](https://github.com/SableClient/Sable/pull/484) by @hazre)
|
||||
* fix(sentry): scrub percent-encoded Matrix IDs and opaque base64url tokens from Sentry URLs ([#531](https://github.com/SableClient/Sable/pull/531) by @Just-Insane)
|
||||
|
||||
### Notes
|
||||
|
||||
* new/changed bios will now also be saved in the format MSC4440 expects ([#559](https://github.com/SableClient/Sable/pull/559) by @dozro)
|
||||
* moved the setting for filtering pronouns by language from experimental to the appearance setting ([#521](https://github.com/SableClient/Sable/pull/521) by @dozro)
|
||||
|
||||
## 1.12.3 (2026-03-24)
|
||||
|
||||
### Fixes
|
||||
|
||||
+2
-3
@@ -1,6 +1,6 @@
|
||||
{
|
||||
"name": "sable",
|
||||
"version": "1.12.3",
|
||||
"version": "1.13.1",
|
||||
"description": "An almost stable Matrix client",
|
||||
"type": "module",
|
||||
"packageManager": "[email protected]+sha512.a706938f0e89ac1456b6563eab4edf1d1faf3368d1191fc5c59790e96dc918e4456ab2e67d613de1043d2e8c81f87303e6b40d4ffeca9df15ef1ad567348f2be",
|
||||
@@ -54,6 +54,7 @@
|
||||
"classnames": "^2.5.1",
|
||||
"dayjs": "^1.11.19",
|
||||
"domhandler": "^5.0.3",
|
||||
"dompurify": "^3.3.3",
|
||||
"emojibase": "^15.3.1",
|
||||
"emojibase-data": "^15.3.2",
|
||||
"eslint-plugin-react": "7.37.5",
|
||||
@@ -84,7 +85,6 @@
|
||||
"react-i18next": "^16.5.4",
|
||||
"react-range": "^1.10.0",
|
||||
"react-router-dom": "^6.30.3",
|
||||
"sanitize-html": "^2.17.1",
|
||||
"slate": "^0.123.0",
|
||||
"slate-dom": "^0.123.0",
|
||||
"slate-history": "^0.113.1",
|
||||
@@ -112,7 +112,6 @@
|
||||
"@types/react": "^18.3.28",
|
||||
"@types/react-dom": "^18.3.7",
|
||||
"@types/react-google-recaptcha": "^2.1.9",
|
||||
"@types/sanitize-html": "^2.16.0",
|
||||
"@types/ua-parser-js": "^0.7.39",
|
||||
"@vitejs/plugin-react": "^5.1.4",
|
||||
"@vitest/coverage-v8": "^4.1.0",
|
||||
|
||||
Generated
+98
-116
@@ -62,7 +62,7 @@ importers:
|
||||
version: 0.5.7(@vanilla-extract/[email protected])
|
||||
'@vanilla-extract/vite-plugin':
|
||||
specifier: ^5.1.4
|
||||
version: 5.1.4(@types/[email protected])([email protected])([email protected].0)([email protected](@types/[email protected])([email protected])([email protected].0)([email protected]))([email protected])
|
||||
version: 5.1.4(@types/[email protected])([email protected])([email protected].1)([email protected](@types/[email protected])([email protected])([email protected].1)([email protected]))([email protected])
|
||||
await-to-js:
|
||||
specifier: ^3.0.0
|
||||
version: 3.0.0
|
||||
@@ -87,6 +87,9 @@ importers:
|
||||
domhandler:
|
||||
specifier: ^5.0.3
|
||||
version: 5.0.3
|
||||
dompurify:
|
||||
specifier: ^3.3.3
|
||||
version: 3.3.3
|
||||
emojibase:
|
||||
specifier: ^15.3.1
|
||||
version: 15.3.1
|
||||
@@ -177,9 +180,6 @@ importers:
|
||||
react-router-dom:
|
||||
specifier: ^6.30.3
|
||||
version: 6.30.3([email protected]([email protected]))([email protected])
|
||||
sanitize-html:
|
||||
specifier: ^2.17.1
|
||||
version: 2.17.1
|
||||
slate:
|
||||
specifier: ^0.123.0
|
||||
version: 0.123.0
|
||||
@@ -204,7 +204,7 @@ importers:
|
||||
devDependencies:
|
||||
'@cloudflare/vite-plugin':
|
||||
specifier: ^1.26.0
|
||||
version: 1.27.0([email protected](@types/[email protected])([email protected])([email protected].0)([email protected]))([email protected])([email protected])
|
||||
version: 1.27.0([email protected](@types/[email protected])([email protected])([email protected].1)([email protected]))([email protected])([email protected])
|
||||
'@esbuild-plugins/node-globals-polyfill':
|
||||
specifier: ^0.2.3
|
||||
version: 0.2.3([email protected])
|
||||
@@ -256,15 +256,12 @@ importers:
|
||||
'@types/react-google-recaptcha':
|
||||
specifier: ^2.1.9
|
||||
version: 2.1.9
|
||||
'@types/sanitize-html':
|
||||
specifier: ^2.16.0
|
||||
version: 2.16.1
|
||||
'@types/ua-parser-js':
|
||||
specifier: ^0.7.39
|
||||
version: 0.7.39
|
||||
'@vitejs/plugin-react':
|
||||
specifier: ^5.1.4
|
||||
version: 5.1.4([email protected](@types/[email protected])([email protected])([email protected].0)([email protected]))
|
||||
version: 5.1.4([email protected](@types/[email protected])([email protected])([email protected].1)([email protected]))
|
||||
'@vitest/coverage-v8':
|
||||
specifier: ^4.1.0
|
||||
version: 4.1.0([email protected])
|
||||
@@ -306,25 +303,25 @@ importers:
|
||||
version: 5.9.3
|
||||
vite:
|
||||
specifier: ^7.3.1
|
||||
version: 7.3.1(@types/[email protected])([email protected])([email protected].0)([email protected])
|
||||
version: 7.3.1(@types/[email protected])([email protected])([email protected].1)([email protected])
|
||||
vite-plugin-compression2:
|
||||
specifier: 2.5.0
|
||||
version: 2.5.0([email protected])
|
||||
vite-plugin-pwa:
|
||||
specifier: ^1.2.0
|
||||
version: 1.2.0([email protected](@types/[email protected])([email protected])([email protected].0)([email protected]))([email protected](@types/[email protected]))([email protected])
|
||||
version: 1.2.0([email protected](@types/[email protected])([email protected])([email protected].1)([email protected]))([email protected](@types/[email protected]))([email protected])
|
||||
vite-plugin-static-copy:
|
||||
specifier: ^3.2.0
|
||||
version: 3.2.0([email protected](@types/[email protected])([email protected])([email protected].0)([email protected]))
|
||||
version: 3.2.0([email protected](@types/[email protected])([email protected])([email protected].1)([email protected]))
|
||||
vite-plugin-svgr:
|
||||
specifier: 4.5.0
|
||||
version: 4.5.0([email protected])([email protected])([email protected](@types/[email protected])([email protected])([email protected].0)([email protected]))
|
||||
version: 4.5.0([email protected])([email protected])([email protected](@types/[email protected])([email protected])([email protected].1)([email protected]))
|
||||
vite-plugin-top-level-await:
|
||||
specifier: ^1.6.0
|
||||
version: 1.6.0(@swc/[email protected])([email protected])([email protected](@types/[email protected])([email protected])([email protected].0)([email protected]))
|
||||
version: 1.6.0(@swc/[email protected])([email protected])([email protected](@types/[email protected])([email protected])([email protected].1)([email protected]))
|
||||
vitest:
|
||||
specifier: ^4.1.0
|
||||
version: 4.1.0(@types/[email protected])(@vitest/[email protected])([email protected])([email protected](@types/[email protected])([email protected])([email protected].0)([email protected]))
|
||||
version: 4.1.0(@types/[email protected])(@vitest/[email protected])([email protected])([email protected](@types/[email protected])([email protected])([email protected].1)([email protected]))
|
||||
wrangler:
|
||||
specifier: ^4.70.0
|
||||
version: 4.72.0
|
||||
@@ -399,8 +396,8 @@ packages:
|
||||
peerDependencies:
|
||||
'@babel/core': ^7.0.0
|
||||
|
||||
'@babel/[email protected].7':
|
||||
resolution: {integrity: sha512-6Fqi8MtQ/PweQ9xvux65emkLQ83uB+qAVtfHkC9UodyHMIZdxNI01HjLCLUtybElp2KY2XNE0nOgyP1E1vXw9w==}
|
||||
'@babel/[email protected].8':
|
||||
resolution: {integrity: sha512-47UwBLPpQi1NoWzLuHNjRoHlYXMwIJoBf7MFou6viC/sIHWYygpvr0B6IAyh5sBdA2nr2LPIRww8lfaUVQINBA==}
|
||||
peerDependencies:
|
||||
'@babel/core': ^7.4.0 || ^8.0.0-0 <8.0.0
|
||||
|
||||
@@ -849,8 +846,8 @@ packages:
|
||||
peerDependencies:
|
||||
'@babel/core': ^7.0.0
|
||||
|
||||
'@babel/[email protected].0':
|
||||
resolution: {integrity: sha512-fNEdfc0yi16lt6IZo2Qxk3knHVdfMYX33czNb4v8yWhemoBhibCpQK/uYHtSKIiO+p/zd3+8fYVXhQdOVV608w==}
|
||||
'@babel/[email protected].2':
|
||||
resolution: {integrity: sha512-DYD23veRYGvBFhcTY1iUvJnDNpuqNd/BzBwCvzOTKUnJjKg5kpUBh3/u9585Agdkgj+QuygG7jLfOPWMa2KVNw==}
|
||||
engines: {node: '>=6.9.0'}
|
||||
peerDependencies:
|
||||
'@babel/core': ^7.0.0-0
|
||||
@@ -864,6 +861,10 @@ packages:
|
||||
resolution: {integrity: sha512-05WQkdpL9COIMz4LjTxGpPNCdlpyimKppYNoJ5Di5EUObifl8t4tuLuUBBZEpoLYOmfvIWrsp9fCl0HoPRVTdA==}
|
||||
engines: {node: '>=6.9.0'}
|
||||
|
||||
'@babel/[email protected]':
|
||||
resolution: {integrity: sha512-JiDShH45zKHWyGe4ZNVRrCjBz8Nh9TMmZG1kh4QTK8hCBTWBi8Da+i7s1fJw7/lYpM4ccepSNfqzZ/QvABBi5g==}
|
||||
engines: {node: '>=6.9.0'}
|
||||
|
||||
'@babel/[email protected]':
|
||||
resolution: {integrity: sha512-YA6Ma2KsCdGb+WC6UpBVFJGXL58MDA6oyONbjyF/+5sBgxY/dwkhLogbMT2GXXyU84/IhRw/2D1Os1B/giz+BQ==}
|
||||
engines: {node: '>=6.9.0'}
|
||||
@@ -2826,9 +2827,6 @@ packages:
|
||||
'@types/[email protected]':
|
||||
resolution: {integrity: sha512-60BCwRFOZCQhDncwQdxxeOEEkbc5dIMccYLwbxsS4TUNeVECQ/pBJ0j09mrHOl/JJvpRPGwO9SvE4nR2Nb/a4Q==}
|
||||
|
||||
'@types/[email protected]':
|
||||
resolution: {integrity: sha512-n9wjs8bCOTyN/ynwD8s/nTcTreIHB1vf31vhLMGqUPNHaweKC4/fAl4Dj+hUlCTKYgm4P3k83fmiFfzkZ6sgMA==}
|
||||
|
||||
'@types/[email protected]':
|
||||
resolution: {integrity: sha512-ScaPdn1dQczgbl0QFTeTOmVHFULt394XJgOQNoyVhZ6r2vLnMLJfBPd53SB52T/3G36VI1/g2MZaX0cwDuXsfw==}
|
||||
|
||||
@@ -3197,18 +3195,18 @@ packages:
|
||||
resolution: {integrity: sha512-qIj0G9wZbMGNLjLmg1PT6v2mE9AH2zlnADJD/2tC6E00hgmhUOfEB6greHPAfLRSufHqROIUTkw6E+M3lH0PTQ==}
|
||||
engines: {node: '>= 0.4'}
|
||||
|
||||
[email protected]6:
|
||||
resolution: {integrity: sha512-xaVwwSfebXf0ooE11BJovZYKhFjIvQo7TsyVpETuIeH2JHv0k/T6Y5j22pPTvqYqmpkxdlPAJlyJ0tfOJAoMxw==}
|
||||
[email protected]7:
|
||||
resolution: {integrity: sha512-aTyf30K/rqAsNwN76zYrdtx8obu0E4KoUME29B1xj+B3WxgvWkp943vYQ+z8Mv3lw9xHXMHpvSPOBxzAkIa94w==}
|
||||
peerDependencies:
|
||||
'@babel/core': ^7.4.0 || ^8.0.0-0 <8.0.0
|
||||
|
||||
[email protected].1:
|
||||
resolution: {integrity: sha512-ENp89vM9Pw4kv/koBb5N2f9bDZsR0hpf3BdPMOg/pkS3pwO4dzNnQZVXtBbeyAadgm865DmQG2jMMLqmZXvuCw==}
|
||||
[email protected].2:
|
||||
resolution: {integrity: sha512-coWpDLJ410R781Npmn/SIBZEsAetR4xVi0SxLMXPaMO4lSf1MwnkGYMtkFxew0Dn8B3/CpbpYxN0JCgg8mn67g==}
|
||||
peerDependencies:
|
||||
'@babel/core': ^7.4.0 || ^8.0.0-0 <8.0.0
|
||||
|
||||
[email protected].7:
|
||||
resolution: {integrity: sha512-OTYbUlSwXhNgr4g6efMZgsO8//jA61P7ZbRX3iTT53VON8l+WQS8IAUEVo4a4cWknrg2W8Cj4gQhRYNCJ8GkAA==}
|
||||
[email protected].8:
|
||||
resolution: {integrity: sha512-M762rNHfSF1EV3SLtnCJXFoQbbIIz0OyRwnCmV0KPC7qosSfCO0QLTSuJX3ayAebubhE6oYBAYPrBA5ljowaZg==}
|
||||
peerDependencies:
|
||||
'@babel/core': ^7.4.0 || ^8.0.0-0 <8.0.0
|
||||
|
||||
@@ -3362,8 +3360,8 @@ packages:
|
||||
resolution: {integrity: sha512-ei8Aos7ja0weRpFzJnEA9UHJ/7XQmqglbRwnf2ATjcB9Wq874VKH9kfjjirM6UhU2/E5fFYadylyhFldcqSidQ==}
|
||||
engines: {node: '>=18'}
|
||||
|
||||
[email protected]8.0:
|
||||
resolution: {integrity: sha512-OM4cAF3D6VtH/WkLtWvyNC56EZVXsZdU3iqaMG2B4WvYrlqU831pc4UtG5yp0sE9z8Y02wVN7PjW5Zf9Gt0f1Q==}
|
||||
[email protected]9.0:
|
||||
resolution: {integrity: sha512-VQXt1jr9cBz03b331DFDCCP90b3fanciLkgiOoy8SBHy06gNf+vQ1A3WFLqG7I8TipYIKeYK9wxd0tUrvHcOZA==}
|
||||
|
||||
[email protected]:
|
||||
resolution: {integrity: sha512-kcZ6+W5QzcJ3P1Mt+83OUv/oHFqZHIx8DuxG6eZ5RGMERoLqp4BuGjhHLYGK+Kf5XVkQvqBSmAy/nGWN3qDgEA==}
|
||||
@@ -3504,6 +3502,9 @@ packages:
|
||||
resolution: {integrity: sha512-cgwlv/1iFQiFnU96XXgROh8xTeetsnJiDsTc7TYCLFd9+/WNkIqPTxiM/8pSd8VIrhXGTf1Ny1q1hquVqDJB5w==}
|
||||
engines: {node: '>= 4'}
|
||||
|
||||
[email protected]:
|
||||
resolution: {integrity: sha512-Oj6pzI2+RqBfFG+qOaOLbFXLQ90ARpcGG6UePL82bJLtdsa6CYJD7nmiU8MW9nQNOtCHV3lZ/Bzq1X0QYbBZCA==}
|
||||
|
||||
[email protected]:
|
||||
resolution: {integrity: sha512-6kZKyUajlDuqlHKVX1w7gyslj9MPIXzIFiz/rGu35uC1wMi+kMhQwGhl4lt9unC9Vb9INnY9Z3/ZA3+FhASLaw==}
|
||||
|
||||
@@ -4072,9 +4073,6 @@ packages:
|
||||
[email protected]:
|
||||
resolution: {integrity: sha512-VTZkM9GWRAtEpveh7MSF6SjjrpNVNNVJfFup7xTY3UpFtm67foy9HDVXneLtFVt4pMz5kZtgNcvCniNFb1hlEQ==}
|
||||
|
||||
[email protected]:
|
||||
resolution: {integrity: sha512-GYdjWKDkbRLkZ5geuHs5NY1puJ+PXwP7+fHPRz06Eirsb9ugf6d8kkXav6ADhcODhFFPMIXyxkxSuMf3D6NCFA==}
|
||||
|
||||
[email protected]:
|
||||
resolution: {integrity: sha512-uxbSI98wmFT/G4P2zXx4OVx04qWUmyFPrD2/CNepa2Zo3GPNaCaaxElDgwUrwYWkK1nr9fft0Ya8dws8coDLLQ==}
|
||||
|
||||
@@ -4679,9 +4677,6 @@ packages:
|
||||
resolution: {integrity: sha512-ayCKvm/phCGxOkYRSCM82iDwct8/EonSEgCSxWxD7ve6jHggsFl4fZVQBPRNgQoKiuV/odhFrGzQXZwbifC8Rg==}
|
||||
engines: {node: '>=8'}
|
||||
|
||||
[email protected]:
|
||||
resolution: {integrity: sha512-/2qh0lav6CmI15FzA3i/2Bzk2zCgQhGMkvhOhKNcBVQ1ldgpbfiNTVslmooUmWJcADi1f1kIeynbDRVzNlfR6Q==}
|
||||
|
||||
[email protected]:
|
||||
resolution: {integrity: sha512-9m4m5GSgXjL4AjumKzq1Fgfp3Z8rsvjRNbnkVwfu2ImRqE5D0LnY2QfDen18FSY9C573YU5XxSapdHZTZ2WolA==}
|
||||
|
||||
@@ -4721,6 +4716,10 @@ packages:
|
||||
resolution: {integrity: sha512-JU3teHTNjmE2VCGFzuY8EXzCDVwEqB2a8fsIvwaStHhAWJEeVd1o1QD80CU6+ZdEXXSLbSsuLwJjkCBWqRQUVA==}
|
||||
engines: {node: '>=8.6'}
|
||||
|
||||
[email protected]:
|
||||
resolution: {integrity: sha512-V7+vQEJ06Z+c5tSye8S+nHUfI51xoXIXjHQ99cQtKUkQqqO1kO/KCJUfZXuB47h/YBlDhah2H3hdUGXn8ie0oA==}
|
||||
engines: {node: '>=8.6'}
|
||||
|
||||
[email protected]:
|
||||
resolution: {integrity: sha512-5gTmgEY/sqK6gFXLIsQNH19lWb4ebPDLA4SdLP7dsWkIXHWlG66oPuVvXSGFPppYZz8ZDZq0dYYrbHfBCVUb1Q==}
|
||||
engines: {node: '>=12'}
|
||||
@@ -4948,9 +4947,6 @@ packages:
|
||||
resolution: {integrity: sha512-x/+Cz4YrimQxQccJf5mKEbIa1NzeCRNI5Ecl/ekmlYaampdNLPalVyIcCZNNH3MvmqBugV5TMYZXv0ljslUlaw==}
|
||||
engines: {node: '>= 0.4'}
|
||||
|
||||
[email protected]:
|
||||
resolution: {integrity: sha512-ehFCW+q1a4CSOWRAdX97BX/6/PDEkCqw7/0JXZAGQV57FQB3YOkTa/rrzHPeJ+Aghy4vZAFfWMYyfxIiB7F/gw==}
|
||||
|
||||
[email protected]:
|
||||
resolution: {integrity: sha512-xAg7SOnEhrm5zI3puOOKyy1OMcMlIJZYNJY7xLBwSze0UjhPLnWfj2GF2EpT0jmzaJKIWKHLsaSSajf35bcYnA==}
|
||||
engines: {node: '>=v12.22.7'}
|
||||
@@ -4974,8 +4970,8 @@ packages:
|
||||
engines: {node: '>=10'}
|
||||
hasBin: true
|
||||
|
||||
[email protected].4:
|
||||
resolution: {integrity: sha512-DuGdB+Po43Q5Jxwpzt1lhyFSYKryqoNjQSA9M92tyw0lyHIOur+XCalOUe0KTJpyqzT8+fQ5A0Jf7vCx/NKmIg==}
|
||||
[email protected].5:
|
||||
resolution: {integrity: sha512-F4LcB0UqUl1zErq+1nYEEzSHJnIwb3AF2XWB94b+afhrekOUijwooAYqFyRbjYkm2PAKBabx6oYv/xDxNi8IBw==}
|
||||
engines: {node: '>=20.0.0'}
|
||||
|
||||
[email protected]:
|
||||
@@ -5188,8 +5184,8 @@ packages:
|
||||
resolution: {integrity: sha512-G13vtMYPT/J8A4X2SjdtBTphZlrp1gKv6hZiOjw14RCWg6GbHuQBGtjlx75xLbYV/wEc0D7G5K4rxKP/cXk8Bw==}
|
||||
engines: {node: '>=10'}
|
||||
|
||||
[email protected].0:
|
||||
resolution: {integrity: sha512-jTwoImyr/QbOWFFso3YoU3ik0jBBDJ6JTOQiy/J2YxVJdZCc+5u7skhNwiOR3FQIygFqVUPHl7qbbxtjW2K3Qg==}
|
||||
[email protected].1:
|
||||
resolution: {integrity: sha512-vzCjQO/rgUuK9sf8VJZvjqiqiHFaZLnOiimmUuOKODxWL8mm/xua7viT7aqX7dgPY60otQjUotzFMmCB4VdmqQ==}
|
||||
engines: {node: '>=10'}
|
||||
hasBin: true
|
||||
|
||||
@@ -5792,7 +5788,7 @@ snapshots:
|
||||
regexpu-core: 6.4.0
|
||||
semver: 6.3.1
|
||||
|
||||
'@babel/[email protected].7(@babel/[email protected])':
|
||||
'@babel/[email protected].8(@babel/[email protected])':
|
||||
dependencies:
|
||||
'@babel/core': 7.29.0
|
||||
'@babel/helper-compilation-targets': 7.28.6
|
||||
@@ -6285,7 +6281,7 @@ snapshots:
|
||||
'@babel/helper-create-regexp-features-plugin': 7.28.5(@babel/[email protected])
|
||||
'@babel/helper-plugin-utils': 7.28.6
|
||||
|
||||
'@babel/[email protected].0(@babel/[email protected])':
|
||||
'@babel/[email protected].2(@babel/[email protected])':
|
||||
dependencies:
|
||||
'@babel/compat-data': 7.29.0
|
||||
'@babel/core': 7.29.0
|
||||
@@ -6353,10 +6349,10 @@ snapshots:
|
||||
'@babel/plugin-transform-unicode-regex': 7.27.1(@babel/[email protected])
|
||||
'@babel/plugin-transform-unicode-sets-regex': 7.28.6(@babel/[email protected])
|
||||
'@babel/preset-modules': 0.1.6-no-external-plugins(@babel/[email protected])
|
||||
babel-plugin-polyfill-corejs2: 0.4.16(@babel/[email protected])
|
||||
babel-plugin-polyfill-corejs3: 0.14.1(@babel/[email protected])
|
||||
babel-plugin-polyfill-regenerator: 0.6.7(@babel/[email protected])
|
||||
core-js-compat: 3.48.0
|
||||
babel-plugin-polyfill-corejs2: 0.4.17(@babel/[email protected])
|
||||
babel-plugin-polyfill-corejs3: 0.14.2(@babel/[email protected])
|
||||
babel-plugin-polyfill-regenerator: 0.6.8(@babel/[email protected])
|
||||
core-js-compat: 3.49.0
|
||||
semver: 6.3.1
|
||||
transitivePeerDependencies:
|
||||
- supports-color
|
||||
@@ -6370,6 +6366,8 @@ snapshots:
|
||||
|
||||
'@babel/[email protected]': {}
|
||||
|
||||
'@babel/[email protected]': {}
|
||||
|
||||
'@babel/[email protected]':
|
||||
dependencies:
|
||||
'@babel/code-frame': 7.29.0
|
||||
@@ -6407,12 +6405,12 @@ snapshots:
|
||||
optionalDependencies:
|
||||
workerd: 1.20260310.1
|
||||
|
||||
'@cloudflare/[email protected]([email protected](@types/[email protected])([email protected])([email protected].0)([email protected]))([email protected])([email protected])':
|
||||
'@cloudflare/[email protected]([email protected](@types/[email protected])([email protected])([email protected].1)([email protected]))([email protected])([email protected])':
|
||||
dependencies:
|
||||
'@cloudflare/unenv-preset': 2.15.0([email protected])([email protected])
|
||||
miniflare: 4.20260310.0
|
||||
unenv: 2.0.0-rc.24
|
||||
vite: 7.3.1(@types/[email protected])([email protected])([email protected].0)([email protected])
|
||||
vite: 7.3.1(@types/[email protected])([email protected])([email protected].1)([email protected])
|
||||
wrangler: 4.72.0
|
||||
ws: 8.18.0
|
||||
transitivePeerDependencies:
|
||||
@@ -7973,9 +7971,9 @@ snapshots:
|
||||
|
||||
'@rollup/[email protected]([email protected])':
|
||||
dependencies:
|
||||
serialize-javascript: 7.0.4
|
||||
serialize-javascript: 7.0.5
|
||||
smob: 1.6.1
|
||||
terser: 5.46.0
|
||||
terser: 5.46.1
|
||||
optionalDependencies:
|
||||
rollup: 4.59.0
|
||||
|
||||
@@ -7993,7 +7991,7 @@ snapshots:
|
||||
dependencies:
|
||||
'@types/estree': 0.0.39
|
||||
estree-walker: 1.0.1
|
||||
picomatch: 2.3.1
|
||||
picomatch: 2.3.2
|
||||
rollup: 4.59.0
|
||||
|
||||
'@rollup/[email protected]([email protected])':
|
||||
@@ -8372,7 +8370,7 @@ snapshots:
|
||||
'@testing-library/[email protected]':
|
||||
dependencies:
|
||||
'@babel/code-frame': 7.29.0
|
||||
'@babel/runtime': 7.28.6
|
||||
'@babel/runtime': 7.29.2
|
||||
'@types/aria-query': 5.0.4
|
||||
aria-query: 5.3.0
|
||||
dom-accessibility-api: 0.5.16
|
||||
@@ -8475,10 +8473,6 @@ snapshots:
|
||||
|
||||
'@types/[email protected]': {}
|
||||
|
||||
'@types/[email protected]':
|
||||
dependencies:
|
||||
htmlparser2: 10.1.0
|
||||
|
||||
'@types/[email protected]': {}
|
||||
|
||||
'@types/[email protected]': {}
|
||||
@@ -8646,12 +8640,12 @@ snapshots:
|
||||
transitivePeerDependencies:
|
||||
- supports-color
|
||||
|
||||
'@vanilla-extract/[email protected](@types/[email protected])([email protected])([email protected].0)([email protected])':
|
||||
'@vanilla-extract/[email protected](@types/[email protected])([email protected])([email protected].1)([email protected])':
|
||||
dependencies:
|
||||
'@vanilla-extract/css': 1.18.0
|
||||
'@vanilla-extract/integration': 8.0.7
|
||||
vite: 7.3.1(@types/[email protected])([email protected])([email protected].0)([email protected])
|
||||
vite-node: 3.2.4(@types/[email protected])([email protected])([email protected].0)([email protected])
|
||||
vite: 7.3.1(@types/[email protected])([email protected])([email protected].1)([email protected])
|
||||
vite-node: 3.2.4(@types/[email protected])([email protected])([email protected].1)([email protected])
|
||||
transitivePeerDependencies:
|
||||
- '@types/node'
|
||||
- babel-plugin-macros
|
||||
@@ -8706,11 +8700,11 @@ snapshots:
|
||||
dependencies:
|
||||
'@vanilla-extract/css': 1.18.0
|
||||
|
||||
'@vanilla-extract/[email protected](@types/[email protected])([email protected])([email protected].0)([email protected](@types/[email protected])([email protected])([email protected].0)([email protected]))([email protected])':
|
||||
'@vanilla-extract/[email protected](@types/[email protected])([email protected])([email protected].1)([email protected](@types/[email protected])([email protected])([email protected].1)([email protected]))([email protected])':
|
||||
dependencies:
|
||||
'@vanilla-extract/compiler': 0.3.4(@types/[email protected])([email protected])([email protected].0)([email protected])
|
||||
'@vanilla-extract/compiler': 0.3.4(@types/[email protected])([email protected])([email protected].1)([email protected])
|
||||
'@vanilla-extract/integration': 8.0.7
|
||||
vite: 7.3.1(@types/[email protected])([email protected])([email protected].0)([email protected])
|
||||
vite: 7.3.1(@types/[email protected])([email protected])([email protected].1)([email protected])
|
||||
transitivePeerDependencies:
|
||||
- '@types/node'
|
||||
- babel-plugin-macros
|
||||
@@ -8726,7 +8720,7 @@ snapshots:
|
||||
- tsx
|
||||
- yaml
|
||||
|
||||
'@vitejs/[email protected]([email protected](@types/[email protected])([email protected])([email protected].0)([email protected]))':
|
||||
'@vitejs/[email protected]([email protected](@types/[email protected])([email protected])([email protected].1)([email protected]))':
|
||||
dependencies:
|
||||
'@babel/core': 7.29.0
|
||||
'@babel/plugin-transform-react-jsx-self': 7.27.1(@babel/[email protected])
|
||||
@@ -8734,7 +8728,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/[email protected])([email protected])([email protected].0)([email protected])
|
||||
vite: 7.3.1(@types/[email protected])([email protected])([email protected].1)([email protected])
|
||||
transitivePeerDependencies:
|
||||
- supports-color
|
||||
|
||||
@@ -8750,7 +8744,7 @@ snapshots:
|
||||
obug: 2.1.1
|
||||
std-env: 4.0.0
|
||||
tinyrainbow: 3.1.0
|
||||
vitest: 4.1.0(@types/[email protected])(@vitest/[email protected])([email protected])([email protected](@types/[email protected])([email protected])([email protected].0)([email protected]))
|
||||
vitest: 4.1.0(@types/[email protected])(@vitest/[email protected])([email protected])([email protected](@types/[email protected])([email protected])([email protected].1)([email protected]))
|
||||
|
||||
'@vitest/[email protected]':
|
||||
dependencies:
|
||||
@@ -8761,13 +8755,13 @@ snapshots:
|
||||
chai: 6.2.2
|
||||
tinyrainbow: 3.1.0
|
||||
|
||||
'@vitest/[email protected]([email protected](@types/[email protected])([email protected])([email protected].0)([email protected]))':
|
||||
'@vitest/[email protected]([email protected](@types/[email protected])([email protected])([email protected].1)([email protected]))':
|
||||
dependencies:
|
||||
'@vitest/spy': 4.1.0
|
||||
estree-walker: 3.0.3
|
||||
magic-string: 0.30.21
|
||||
optionalDependencies:
|
||||
vite: 7.3.1(@types/[email protected])([email protected])([email protected].0)([email protected])
|
||||
vite: 7.3.1(@types/[email protected])([email protected])([email protected].1)([email protected])
|
||||
|
||||
'@vitest/[email protected]':
|
||||
dependencies:
|
||||
@@ -8796,7 +8790,7 @@ snapshots:
|
||||
sirv: 3.0.2
|
||||
tinyglobby: 0.2.15
|
||||
tinyrainbow: 3.1.0
|
||||
vitest: 4.1.0(@types/[email protected])(@vitest/[email protected])([email protected])([email protected](@types/[email protected])([email protected])([email protected].0)([email protected]))
|
||||
vitest: 4.1.0(@types/[email protected])(@vitest/[email protected])([email protected])([email protected](@types/[email protected])([email protected])([email protected].1)([email protected]))
|
||||
|
||||
'@vitest/[email protected]':
|
||||
dependencies:
|
||||
@@ -8946,27 +8940,27 @@ snapshots:
|
||||
|
||||
[email protected]: {}
|
||||
|
||||
[email protected]6(@babel/[email protected]):
|
||||
[email protected]7(@babel/[email protected]):
|
||||
dependencies:
|
||||
'@babel/compat-data': 7.29.0
|
||||
'@babel/core': 7.29.0
|
||||
'@babel/helper-define-polyfill-provider': 0.6.7(@babel/[email protected])
|
||||
'@babel/helper-define-polyfill-provider': 0.6.8(@babel/[email protected])
|
||||
semver: 6.3.1
|
||||
transitivePeerDependencies:
|
||||
- supports-color
|
||||
|
||||
[email protected].1(@babel/[email protected]):
|
||||
[email protected].2(@babel/[email protected]):
|
||||
dependencies:
|
||||
'@babel/core': 7.29.0
|
||||
'@babel/helper-define-polyfill-provider': 0.6.7(@babel/[email protected])
|
||||
core-js-compat: 3.48.0
|
||||
'@babel/helper-define-polyfill-provider': 0.6.8(@babel/[email protected])
|
||||
core-js-compat: 3.49.0
|
||||
transitivePeerDependencies:
|
||||
- supports-color
|
||||
|
||||
[email protected].7(@babel/[email protected]):
|
||||
[email protected].8(@babel/[email protected]):
|
||||
dependencies:
|
||||
'@babel/core': 7.29.0
|
||||
'@babel/helper-define-polyfill-provider': 0.6.7(@babel/[email protected])
|
||||
'@babel/helper-define-polyfill-provider': 0.6.8(@babel/[email protected])
|
||||
transitivePeerDependencies:
|
||||
- supports-color
|
||||
|
||||
@@ -9097,7 +9091,7 @@ snapshots:
|
||||
|
||||
[email protected]: {}
|
||||
|
||||
[email protected]8.0:
|
||||
[email protected]9.0:
|
||||
dependencies:
|
||||
browserslist: 4.28.1
|
||||
|
||||
@@ -9222,6 +9216,10 @@ snapshots:
|
||||
dependencies:
|
||||
domelementtype: 2.3.0
|
||||
|
||||
[email protected]:
|
||||
optionalDependencies:
|
||||
'@types/trusted-types': 2.0.7
|
||||
|
||||
[email protected]:
|
||||
dependencies:
|
||||
dom-serializer: 2.0.0
|
||||
@@ -9977,13 +9975,6 @@ snapshots:
|
||||
domutils: 3.2.2
|
||||
entities: 7.0.1
|
||||
|
||||
[email protected]:
|
||||
dependencies:
|
||||
domelementtype: 2.3.0
|
||||
domhandler: 5.0.3
|
||||
domutils: 3.2.2
|
||||
entities: 4.5.0
|
||||
|
||||
[email protected]:
|
||||
dependencies:
|
||||
domelementtype: 2.3.0
|
||||
@@ -10619,8 +10610,6 @@ snapshots:
|
||||
json-parse-even-better-errors: 2.3.1
|
||||
lines-and-columns: 1.2.4
|
||||
|
||||
[email protected]: {}
|
||||
|
||||
[email protected]:
|
||||
dependencies:
|
||||
entities: 6.0.1
|
||||
@@ -10651,6 +10640,8 @@ snapshots:
|
||||
|
||||
[email protected]: {}
|
||||
|
||||
[email protected]: {}
|
||||
|
||||
[email protected]: {}
|
||||
|
||||
[email protected]:
|
||||
@@ -10945,15 +10936,6 @@ snapshots:
|
||||
es-errors: 1.3.0
|
||||
is-regex: 1.2.1
|
||||
|
||||
[email protected]:
|
||||
dependencies:
|
||||
deepmerge: 4.3.1
|
||||
escape-string-regexp: 4.0.0
|
||||
htmlparser2: 8.0.2
|
||||
is-plain-object: 5.0.0
|
||||
parse-srcset: 1.0.2
|
||||
postcss: 8.5.8
|
||||
|
||||
[email protected]:
|
||||
dependencies:
|
||||
xmlchars: 2.2.0
|
||||
@@ -10972,7 +10954,7 @@ snapshots:
|
||||
|
||||
[email protected]: {}
|
||||
|
||||
[email protected].4: {}
|
||||
[email protected].5: {}
|
||||
|
||||
[email protected]:
|
||||
dependencies:
|
||||
@@ -11244,7 +11226,7 @@ snapshots:
|
||||
type-fest: 0.16.0
|
||||
unique-string: 2.0.0
|
||||
|
||||
[email protected].0:
|
||||
[email protected].1:
|
||||
dependencies:
|
||||
'@jridgewell/source-map': 0.3.11
|
||||
acorn: 8.16.0
|
||||
@@ -11447,13 +11429,13 @@ snapshots:
|
||||
react: 18.3.1
|
||||
react-dom: 18.3.1([email protected])
|
||||
|
||||
[email protected](@types/[email protected])([email protected])([email protected].0)([email protected]):
|
||||
[email protected](@types/[email protected])([email protected])([email protected].1)([email protected]):
|
||||
dependencies:
|
||||
cac: 6.7.14
|
||||
debug: 4.4.3
|
||||
es-module-lexer: 1.7.0
|
||||
pathe: 2.0.3
|
||||
vite: 7.3.1(@types/[email protected])([email protected])([email protected].0)([email protected])
|
||||
vite: 7.3.1(@types/[email protected])([email protected])([email protected].1)([email protected])
|
||||
transitivePeerDependencies:
|
||||
- '@types/node'
|
||||
- jiti
|
||||
@@ -11475,48 +11457,48 @@ snapshots:
|
||||
transitivePeerDependencies:
|
||||
- rollup
|
||||
|
||||
[email protected]([email protected](@types/[email protected])([email protected])([email protected].0)([email protected]))([email protected](@types/[email protected]))([email protected]):
|
||||
[email protected]([email protected](@types/[email protected])([email protected])([email protected].1)([email protected]))([email protected](@types/[email protected]))([email protected]):
|
||||
dependencies:
|
||||
debug: 4.4.3
|
||||
pretty-bytes: 6.1.1
|
||||
tinyglobby: 0.2.15
|
||||
vite: 7.3.1(@types/[email protected])([email protected])([email protected].0)([email protected])
|
||||
vite: 7.3.1(@types/[email protected])([email protected])([email protected].1)([email protected])
|
||||
workbox-build: 7.4.0(@types/[email protected])
|
||||
workbox-window: 7.4.0
|
||||
transitivePeerDependencies:
|
||||
- supports-color
|
||||
|
||||
[email protected]([email protected](@types/[email protected])([email protected])([email protected].0)([email protected])):
|
||||
[email protected]([email protected](@types/[email protected])([email protected])([email protected].1)([email protected])):
|
||||
dependencies:
|
||||
chokidar: 3.6.0
|
||||
p-map: 7.0.4
|
||||
picocolors: 1.1.1
|
||||
tinyglobby: 0.2.15
|
||||
vite: 7.3.1(@types/[email protected])([email protected])([email protected].0)([email protected])
|
||||
vite: 7.3.1(@types/[email protected])([email protected])([email protected].1)([email protected])
|
||||
|
||||
[email protected]([email protected])([email protected])([email protected](@types/[email protected])([email protected])([email protected].0)([email protected])):
|
||||
[email protected]([email protected])([email protected])([email protected](@types/[email protected])([email protected])([email protected].1)([email protected])):
|
||||
dependencies:
|
||||
'@rollup/pluginutils': 5.3.0([email protected])
|
||||
'@svgr/core': 8.1.0([email protected])
|
||||
'@svgr/plugin-jsx': 8.1.0(@svgr/[email protected]([email protected]))
|
||||
vite: 7.3.1(@types/[email protected])([email protected])([email protected].0)([email protected])
|
||||
vite: 7.3.1(@types/[email protected])([email protected])([email protected].1)([email protected])
|
||||
transitivePeerDependencies:
|
||||
- rollup
|
||||
- supports-color
|
||||
- typescript
|
||||
|
||||
[email protected](@swc/[email protected])([email protected])([email protected](@types/[email protected])([email protected])([email protected].0)([email protected])):
|
||||
[email protected](@swc/[email protected])([email protected])([email protected](@types/[email protected])([email protected])([email protected].1)([email protected])):
|
||||
dependencies:
|
||||
'@rollup/plugin-virtual': 3.0.2([email protected])
|
||||
'@swc/core': 1.15.18(@swc/[email protected])
|
||||
'@swc/wasm': 1.15.18
|
||||
uuid: 10.0.0
|
||||
vite: 7.3.1(@types/[email protected])([email protected])([email protected].0)([email protected])
|
||||
vite: 7.3.1(@types/[email protected])([email protected])([email protected].1)([email protected])
|
||||
transitivePeerDependencies:
|
||||
- '@swc/helpers'
|
||||
- rollup
|
||||
|
||||
[email protected](@types/[email protected])([email protected])([email protected].0)([email protected]):
|
||||
[email protected](@types/[email protected])([email protected])([email protected].1)([email protected]):
|
||||
dependencies:
|
||||
esbuild: 0.27.3
|
||||
fdir: 6.5.0([email protected])
|
||||
@@ -11528,13 +11510,13 @@ snapshots:
|
||||
'@types/node': 24.10.13
|
||||
fsevents: 2.3.3
|
||||
jiti: 2.6.1
|
||||
terser: 5.46.0
|
||||
terser: 5.46.1
|
||||
yaml: 2.8.2
|
||||
|
||||
[email protected](@types/[email protected])(@vitest/[email protected])([email protected])([email protected](@types/[email protected])([email protected])([email protected].0)([email protected])):
|
||||
[email protected](@types/[email protected])(@vitest/[email protected])([email protected])([email protected](@types/[email protected])([email protected])([email protected].1)([email protected])):
|
||||
dependencies:
|
||||
'@vitest/expect': 4.1.0
|
||||
'@vitest/mocker': 4.1.0([email protected](@types/[email protected])([email protected])([email protected].0)([email protected]))
|
||||
'@vitest/mocker': 4.1.0([email protected](@types/[email protected])([email protected])([email protected].1)([email protected]))
|
||||
'@vitest/pretty-format': 4.1.0
|
||||
'@vitest/runner': 4.1.0
|
||||
'@vitest/snapshot': 4.1.0
|
||||
@@ -11551,7 +11533,7 @@ snapshots:
|
||||
tinyexec: 1.0.4
|
||||
tinyglobby: 0.2.15
|
||||
tinyrainbow: 3.1.0
|
||||
vite: 7.3.1(@types/[email protected])([email protected])([email protected].0)([email protected])
|
||||
vite: 7.3.1(@types/[email protected])([email protected])([email protected].1)([email protected])
|
||||
why-is-node-running: 2.3.0
|
||||
optionalDependencies:
|
||||
'@types/node': 24.10.13
|
||||
@@ -11660,8 +11642,8 @@ snapshots:
|
||||
dependencies:
|
||||
'@apideck/better-ajv-errors': 0.3.6([email protected])
|
||||
'@babel/core': 7.29.0
|
||||
'@babel/preset-env': 7.29.0(@babel/[email protected])
|
||||
'@babel/runtime': 7.28.6
|
||||
'@babel/preset-env': 7.29.2(@babel/[email protected])
|
||||
'@babel/runtime': 7.29.2
|
||||
'@rollup/plugin-babel': 5.3.1(@babel/[email protected])(@types/[email protected])([email protected])
|
||||
'@rollup/plugin-node-resolve': 15.3.1([email protected])
|
||||
'@rollup/plugin-replace': 2.4.2([email protected])
|
||||
|
||||
@@ -86,6 +86,7 @@ function RenderMessageContentInternal({
|
||||
[CaptionPosition.Inline]: 'row',
|
||||
[CaptionPosition.Hidden]: 'row',
|
||||
} satisfies Record<CaptionPosition, React.CSSProperties['flexDirection']>;
|
||||
const attachmentDirection = captionPositionMap[captionPosition];
|
||||
|
||||
const renderBody = useCallback(
|
||||
(props: any) => (
|
||||
@@ -131,6 +132,7 @@ function RenderMessageContentInternal({
|
||||
},
|
||||
[ts, clientUrlPreview, urlPreview]
|
||||
);
|
||||
const messageUrlsPreview = urlPreview ? renderUrlsPreview : undefined;
|
||||
|
||||
const renderCaption = () => {
|
||||
const hasCaption = content.body && content.body.trim().length > 0;
|
||||
@@ -143,7 +145,7 @@ function RenderMessageContentInternal({
|
||||
edited={edited}
|
||||
content={content}
|
||||
renderBody={renderBody}
|
||||
renderUrlsPreview={urlPreview ? renderUrlsPreview : undefined}
|
||||
renderUrlsPreview={messageUrlsPreview}
|
||||
/>
|
||||
);
|
||||
return (
|
||||
@@ -162,7 +164,7 @@ function RenderMessageContentInternal({
|
||||
edited={edited}
|
||||
content={content}
|
||||
renderBody={renderBody}
|
||||
renderUrlsPreview={urlPreview ? renderUrlsPreview : undefined}
|
||||
renderUrlsPreview={messageUrlsPreview}
|
||||
/>
|
||||
</Box>
|
||||
);
|
||||
@@ -170,54 +172,53 @@ function RenderMessageContentInternal({
|
||||
return null;
|
||||
};
|
||||
|
||||
const renderFile = () => (
|
||||
<div
|
||||
style={{
|
||||
display: 'flex',
|
||||
flexDirection: captionPositionMap[captionPosition],
|
||||
}}
|
||||
>
|
||||
<div>
|
||||
<MFile
|
||||
content={content}
|
||||
renderFileContent={({ body, mimeType, info, encInfo, url }) => (
|
||||
<FileContent
|
||||
body={body}
|
||||
mimeType={mimeType}
|
||||
renderAsPdfFile={() => (
|
||||
<ReadPdfFile
|
||||
body={body}
|
||||
mimeType={mimeType}
|
||||
url={url}
|
||||
encInfo={encInfo}
|
||||
renderViewer={(p) => <PdfViewer {...p} />}
|
||||
/>
|
||||
)}
|
||||
renderAsTextFile={() => (
|
||||
<ReadTextFile
|
||||
body={body}
|
||||
mimeType={mimeType}
|
||||
url={url}
|
||||
encInfo={encInfo}
|
||||
renderViewer={(p) => <TextViewer {...p} />}
|
||||
/>
|
||||
)}
|
||||
>
|
||||
<DownloadFile
|
||||
function renderCaptionedAttachment(attachment: JSX.Element): JSX.Element {
|
||||
return (
|
||||
<div
|
||||
style={{
|
||||
display: 'flex',
|
||||
flexDirection: attachmentDirection,
|
||||
}}
|
||||
>
|
||||
<div>{attachment}</div>
|
||||
{renderCaption()}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
const renderFile = () =>
|
||||
renderCaptionedAttachment(
|
||||
<MFile
|
||||
content={content}
|
||||
renderFileContent={({ body, mimeType, info, encInfo, url }) => (
|
||||
<FileContent
|
||||
body={body}
|
||||
mimeType={mimeType}
|
||||
renderAsPdfFile={() => (
|
||||
<ReadPdfFile
|
||||
body={body}
|
||||
mimeType={mimeType}
|
||||
url={url}
|
||||
encInfo={encInfo}
|
||||
info={info}
|
||||
renderViewer={(p) => <PdfViewer {...p} />}
|
||||
/>
|
||||
</FileContent>
|
||||
)}
|
||||
outlined={outlineAttachment}
|
||||
/>
|
||||
</div>
|
||||
{renderCaption()}
|
||||
</div>
|
||||
);
|
||||
)}
|
||||
renderAsTextFile={() => (
|
||||
<ReadTextFile
|
||||
body={body}
|
||||
mimeType={mimeType}
|
||||
url={url}
|
||||
encInfo={encInfo}
|
||||
renderViewer={(p) => <TextViewer {...p} />}
|
||||
/>
|
||||
)}
|
||||
>
|
||||
<DownloadFile body={body} mimeType={mimeType} url={url} encInfo={encInfo} info={info} />
|
||||
</FileContent>
|
||||
)}
|
||||
outlined={outlineAttachment}
|
||||
/>
|
||||
);
|
||||
|
||||
if (msgType === MsgType.Text) {
|
||||
return (
|
||||
@@ -225,7 +226,7 @@ function RenderMessageContentInternal({
|
||||
edited={edited}
|
||||
content={content}
|
||||
renderBody={renderBody}
|
||||
renderUrlsPreview={urlPreview ? renderUrlsPreview : undefined}
|
||||
renderUrlsPreview={messageUrlsPreview}
|
||||
/>
|
||||
);
|
||||
}
|
||||
@@ -246,7 +247,7 @@ function RenderMessageContentInternal({
|
||||
edited={edited}
|
||||
content={content}
|
||||
renderBody={renderBody}
|
||||
renderUrlsPreview={urlPreview ? renderUrlsPreview : undefined}
|
||||
renderUrlsPreview={messageUrlsPreview}
|
||||
/>
|
||||
);
|
||||
}
|
||||
@@ -257,7 +258,7 @@ function RenderMessageContentInternal({
|
||||
edited={edited}
|
||||
content={content}
|
||||
renderBody={renderBody}
|
||||
renderUrlsPreview={urlPreview ? renderUrlsPreview : undefined}
|
||||
renderUrlsPreview={messageUrlsPreview}
|
||||
/>
|
||||
);
|
||||
}
|
||||
@@ -270,101 +271,71 @@ function RenderMessageContentInternal({
|
||||
content.body?.toLowerCase().endsWith('.webp') ||
|
||||
(typeof content.url === 'string' && content.url.toLowerCase().includes('gif'));
|
||||
|
||||
return (
|
||||
<div
|
||||
style={{
|
||||
display: 'flex',
|
||||
flexDirection: captionPositionMap[captionPosition],
|
||||
}}
|
||||
>
|
||||
<div>
|
||||
<MImage
|
||||
content={content}
|
||||
renderImageContent={(imageProps) => (
|
||||
<ImageContent
|
||||
{...imageProps}
|
||||
autoPlay={mediaAutoLoad}
|
||||
renderImage={(p) => {
|
||||
if (isGif && !autoplayGifs && p.src) {
|
||||
return (
|
||||
<ClientSideHoverFreeze src={p.src}>
|
||||
<Image {...p} loading="lazy" />
|
||||
</ClientSideHoverFreeze>
|
||||
);
|
||||
}
|
||||
return <Image {...p} loading="lazy" />;
|
||||
}}
|
||||
renderViewer={(p) => <ImageViewer {...p} />}
|
||||
/>
|
||||
)}
|
||||
outlined={outlineAttachment}
|
||||
return renderCaptionedAttachment(
|
||||
<MImage
|
||||
content={content}
|
||||
renderImageContent={(imageProps) => (
|
||||
<ImageContent
|
||||
{...imageProps}
|
||||
autoPlay={mediaAutoLoad}
|
||||
renderImage={(p) => {
|
||||
if (isGif && !autoplayGifs && p.src) {
|
||||
return (
|
||||
<ClientSideHoverFreeze src={p.src}>
|
||||
<Image {...p} loading="lazy" />
|
||||
</ClientSideHoverFreeze>
|
||||
);
|
||||
}
|
||||
return <Image {...p} loading="lazy" />;
|
||||
}}
|
||||
renderViewer={(p) => <ImageViewer {...p} />}
|
||||
/>
|
||||
</div>
|
||||
{renderCaption()}
|
||||
</div>
|
||||
)}
|
||||
outlined={outlineAttachment}
|
||||
/>
|
||||
);
|
||||
}
|
||||
|
||||
if (msgType === MsgType.Video) {
|
||||
return (
|
||||
<div
|
||||
style={{
|
||||
display: 'flex',
|
||||
flexDirection: captionPositionMap[captionPosition],
|
||||
}}
|
||||
>
|
||||
<div>
|
||||
<MVideo
|
||||
content={content}
|
||||
renderAsFile={renderFile}
|
||||
renderVideoContent={({ body, info, ...videoProps }) => (
|
||||
<VideoContent
|
||||
body={body}
|
||||
info={info}
|
||||
{...videoProps}
|
||||
renderThumbnail={
|
||||
mediaAutoLoad
|
||||
? () => (
|
||||
<ThumbnailContent
|
||||
info={info}
|
||||
renderImage={(src) => (
|
||||
<Image alt={body} title={body} src={src} loading="lazy" />
|
||||
)}
|
||||
/>
|
||||
)
|
||||
: undefined
|
||||
}
|
||||
renderVideo={(p) => <PersistedVolumeVideo {...p} />}
|
||||
/>
|
||||
)}
|
||||
outlined={outlineAttachment}
|
||||
return renderCaptionedAttachment(
|
||||
<MVideo
|
||||
content={content}
|
||||
renderAsFile={renderFile}
|
||||
renderVideoContent={({ body, info, ...videoProps }) => (
|
||||
<VideoContent
|
||||
body={body}
|
||||
info={info}
|
||||
{...videoProps}
|
||||
renderThumbnail={
|
||||
mediaAutoLoad
|
||||
? () => (
|
||||
<ThumbnailContent
|
||||
info={info}
|
||||
renderImage={(src) => (
|
||||
<Image alt={body} title={body} src={src} loading="lazy" />
|
||||
)}
|
||||
/>
|
||||
)
|
||||
: undefined
|
||||
}
|
||||
renderVideo={(p) => <PersistedVolumeVideo {...p} />}
|
||||
/>
|
||||
</div>
|
||||
{renderCaption()}
|
||||
</div>
|
||||
)}
|
||||
outlined={outlineAttachment}
|
||||
/>
|
||||
);
|
||||
}
|
||||
|
||||
if (msgType === MsgType.Audio) {
|
||||
return (
|
||||
<div
|
||||
style={{
|
||||
display: 'flex',
|
||||
flexDirection: captionPositionMap[captionPosition],
|
||||
}}
|
||||
>
|
||||
<div>
|
||||
<MAudio
|
||||
content={content}
|
||||
renderAsFile={renderFile}
|
||||
renderAudioContent={(audioProps) => (
|
||||
<AudioContent {...audioProps} renderMediaControl={(p) => <MediaControl {...p} />} />
|
||||
)}
|
||||
outlined={outlineAttachment}
|
||||
/>
|
||||
</div>
|
||||
{renderCaption()}
|
||||
</div>
|
||||
return renderCaptionedAttachment(
|
||||
<MAudio
|
||||
content={content}
|
||||
renderAsFile={renderFile}
|
||||
renderAudioContent={(audioProps) => (
|
||||
<AudioContent {...audioProps} renderMediaControl={(p) => <MediaControl {...p} />} />
|
||||
)}
|
||||
outlined={outlineAttachment}
|
||||
/>
|
||||
);
|
||||
}
|
||||
|
||||
|
||||
@@ -9,6 +9,25 @@ import { useRoomAbbreviationsContext } from '$hooks/useRoomAbbreviations';
|
||||
import { splitByAbbreviations } from '$utils/abbreviations';
|
||||
import { MessageEmptyContent } from './content';
|
||||
|
||||
function getRenderedBodyText(text: string, highlightRegex?: RegExp): (string | JSX.Element)[] {
|
||||
const emojiScaledText = scaleSystemEmoji(text);
|
||||
|
||||
return highlightRegex ? highlightText(highlightRegex, emojiScaledText) : emojiScaledText;
|
||||
}
|
||||
|
||||
function renderLinkifiedBodyText(
|
||||
text: string,
|
||||
linkifyOpts: Opts,
|
||||
highlightRegex: RegExp | undefined,
|
||||
key?: string
|
||||
): JSX.Element {
|
||||
return (
|
||||
<Linkify key={key} options={linkifyOpts}>
|
||||
{getRenderedBodyText(text, highlightRegex)}
|
||||
</Linkify>
|
||||
);
|
||||
}
|
||||
|
||||
type AbbreviationTermProps = {
|
||||
text: string;
|
||||
definition: string;
|
||||
@@ -92,7 +111,6 @@ export function buildAbbrReplaceTextNode(
|
||||
type RenderBodyProps = {
|
||||
body: string;
|
||||
customBody?: string;
|
||||
|
||||
highlightRegex?: RegExp;
|
||||
htmlReactParserOptions: HTMLReactParserOptions;
|
||||
linkifyOpts: Opts;
|
||||
@@ -107,7 +125,6 @@ export function RenderBody({
|
||||
const abbrMap = useRoomAbbreviationsContext();
|
||||
|
||||
if (customBody) {
|
||||
if (customBody === '') return <MessageEmptyContent />;
|
||||
return parse(sanitizeCustomHtml(customBody), htmlReactParserOptions);
|
||||
}
|
||||
if (body === '') return <MessageEmptyContent />;
|
||||
@@ -122,24 +139,12 @@ export function RenderBody({
|
||||
const definition = abbrMap.get(seg.termKey) ?? '';
|
||||
return <AbbreviationTerm key={seg.id} text={seg.text} definition={definition} />;
|
||||
}
|
||||
return (
|
||||
<Linkify key={seg.id} options={linkifyOpts}>
|
||||
{highlightRegex
|
||||
? highlightText(highlightRegex, scaleSystemEmoji(seg.text))
|
||||
: scaleSystemEmoji(seg.text)}
|
||||
</Linkify>
|
||||
);
|
||||
return renderLinkifiedBodyText(seg.text, linkifyOpts, highlightRegex, seg.id);
|
||||
})}
|
||||
</>
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
return (
|
||||
<Linkify options={linkifyOpts}>
|
||||
{highlightRegex
|
||||
? highlightText(highlightRegex, scaleSystemEmoji(body))
|
||||
: scaleSystemEmoji(body)}
|
||||
</Linkify>
|
||||
);
|
||||
return renderLinkifiedBodyText(body, linkifyOpts, highlightRegex);
|
||||
}
|
||||
@@ -0,0 +1,129 @@
|
||||
import { render, screen } from '@testing-library/react';
|
||||
import { describe, expect, it, vi } from 'vitest';
|
||||
import { Reply } from './Reply';
|
||||
|
||||
const { mockUseRoomEvent, mockInvalidateQueries } = vi.hoisted(() => ({
|
||||
mockUseRoomEvent: vi.fn(),
|
||||
mockInvalidateQueries: vi.fn(),
|
||||
}));
|
||||
|
||||
vi.mock('@tanstack/react-query', () => ({
|
||||
useQueryClient: () => ({
|
||||
invalidateQueries: mockInvalidateQueries,
|
||||
}),
|
||||
}));
|
||||
|
||||
vi.mock('jotai', async (importActual) => {
|
||||
const actual = await importActual<typeof import('jotai')>();
|
||||
return {
|
||||
...actual,
|
||||
useAtomValue: () => ({}),
|
||||
};
|
||||
});
|
||||
|
||||
vi.mock('react-i18next', () => ({
|
||||
useTranslation: () => ({
|
||||
t: (key: string) => key,
|
||||
}),
|
||||
}));
|
||||
|
||||
vi.mock('$hooks/useRoomEvent', () => ({
|
||||
useRoomEvent: (...args: unknown[]) => mockUseRoomEvent(...args),
|
||||
}));
|
||||
|
||||
vi.mock('$hooks/useSableCosmetics', () => ({
|
||||
useSableCosmetics: () => ({ color: undefined, font: undefined }),
|
||||
}));
|
||||
|
||||
vi.mock('$hooks/useMediaAuthentication', () => ({
|
||||
useMediaAuthentication: () => false,
|
||||
}));
|
||||
|
||||
vi.mock('$hooks/useIgnoredUsers', () => ({
|
||||
useIgnoredUsers: () => [],
|
||||
}));
|
||||
|
||||
vi.mock('$hooks/useMatrixClient', () => ({
|
||||
useMatrixClient: () =>
|
||||
({
|
||||
getRoom: () => undefined,
|
||||
getUserId: () => '@me:example.com',
|
||||
mxcUrlToHttp: () => null,
|
||||
}) as any,
|
||||
}));
|
||||
|
||||
vi.mock('$hooks/useMemberEventParser', () => ({
|
||||
useMemberEventParser: () => vi.fn(),
|
||||
}));
|
||||
|
||||
vi.mock('$hooks/useMentionClickHandler', () => ({
|
||||
useMentionClickHandler: () => undefined,
|
||||
}));
|
||||
|
||||
vi.mock('$utils/room', async (importActual) => {
|
||||
const actual = await importActual<typeof import('$utils/room')>();
|
||||
return {
|
||||
...actual,
|
||||
getMemberDisplayName: () => 'Alice',
|
||||
};
|
||||
});
|
||||
|
||||
const createReplyEvent = (formattedBody: string) =>
|
||||
({
|
||||
getContent: () => ({
|
||||
body: 'fallback body',
|
||||
format: 'org.matrix.custom.html',
|
||||
formatted_body: formattedBody,
|
||||
msgtype: 'm.text',
|
||||
}),
|
||||
getSender: () => '@alice:example.com',
|
||||
getType: () => 'm.room.message',
|
||||
isRedacted: () => false,
|
||||
isEncrypted: () => false,
|
||||
isDecryptionFailure: () => false,
|
||||
getClearContent: () => ({}),
|
||||
}) as any;
|
||||
|
||||
describe('Reply', () => {
|
||||
it('sanitizes formatted_body before trimming and parsing the reply preview', () => {
|
||||
mockUseRoomEvent.mockReturnValue(
|
||||
createReplyEvent(
|
||||
'<mx-reply><blockquote>quoted<script>alert(1)</script></blockquote></mx-reply>' +
|
||||
'<span data-mx-color="#ff0000" style="color:#00ff00">visible</span>' +
|
||||
'<img src="https://example.com/not-allowed.png" alt="blocked image" />'
|
||||
)
|
||||
);
|
||||
|
||||
render(
|
||||
<Reply
|
||||
room={{ roomId: '!room:example.com', getMember: () => undefined } as any}
|
||||
replyEventId="$reply:example.com"
|
||||
/>
|
||||
);
|
||||
|
||||
expect(screen.getByText('visible')).toBeInTheDocument();
|
||||
expect(screen.queryByText('quoted')).not.toBeInTheDocument();
|
||||
expect(screen.queryByText('alert(1)')).not.toBeInTheDocument();
|
||||
expect(screen.queryByAltText('blocked image')).not.toBeInTheDocument();
|
||||
});
|
||||
|
||||
it('does not render unresolved mxc images as raw browser img tags in reply previews', () => {
|
||||
const warnSpy = vi.spyOn(console, 'warn').mockImplementation(() => undefined);
|
||||
|
||||
mockUseRoomEvent.mockReturnValue(
|
||||
createReplyEvent(
|
||||
'<img data-mx-emoticon src="mxc://mozilla.org/ca2ed58example" alt="blobcat" title="blobcat" height="32" />'
|
||||
)
|
||||
);
|
||||
|
||||
const { container } = render(
|
||||
<Reply
|
||||
room={{ roomId: '!room:example.com', getMember: () => undefined } as any}
|
||||
replyEventId="$reply:example.com"
|
||||
/>
|
||||
);
|
||||
|
||||
expect(container.querySelector('img[src^="mxc://"]')).toBeNull();
|
||||
expect(warnSpy).not.toHaveBeenCalled();
|
||||
});
|
||||
});
|
||||
@@ -8,6 +8,7 @@ import { useAtomValue } from 'jotai';
|
||||
import { getMemberDisplayName, trimReplyFromBody, trimReplyFromFormattedBody } from '$utils/room';
|
||||
import { getMxIdLocalPart } from '$utils/matrix';
|
||||
import { randomNumberBetween } from '$utils/common';
|
||||
import { sanitizeCustomHtml } from '$utils/sanitize';
|
||||
import {
|
||||
getReactCustomHtmlParser,
|
||||
scaleSystemEmoji,
|
||||
@@ -91,6 +92,19 @@ type ReplyProps = {
|
||||
replyIcon?: JSX.Element;
|
||||
};
|
||||
|
||||
export const sanitizeReplyFormattedPreview = (formattedBody: string): string => {
|
||||
const safeFormattedBody = sanitizeCustomHtml(formattedBody);
|
||||
const strippedHtml = trimReplyFromFormattedBody(safeFormattedBody)
|
||||
.replaceAll(/<br\s*\/?>/gi, ' ')
|
||||
.replaceAll(/<\/p>\s*<p[^>]*>/gi, ' ')
|
||||
.replaceAll(/<\/?p[^>]*>/gi, '')
|
||||
.replaceAll(/<\/li>\s*<li[^>]*>/gi, ' ')
|
||||
.replaceAll(/<\/?(ul|ol|li|blockquote|h[1-6]|pre|div)[^>]*>/gi, '')
|
||||
.replaceAll(/(?:\r\n|\r|\n)/g, ' ');
|
||||
|
||||
return strippedHtml;
|
||||
};
|
||||
|
||||
export const Reply = as<'div', ReplyProps>(
|
||||
(
|
||||
{ room, timelineSet, replyEventId, threadRootId, mentions, onClick, replyIcon, ...props },
|
||||
@@ -125,6 +139,9 @@ export const Reply = as<'div', ReplyProps>(
|
||||
|
||||
const badEncryption = replyEvent?.getContent().msgtype === 'm.bad.encrypted';
|
||||
const mentionClickHandler = useMentionClickHandler(room.roomId);
|
||||
const isFormattedReply =
|
||||
format === 'org.matrix.custom.html' && typeof formattedBody === 'string';
|
||||
const hasPlainTextReply = typeof body === 'string' && body !== '';
|
||||
|
||||
// An encrypted event that hasn't been decrypted yet (keys pending) has an
|
||||
// empty result from getClearContent(). Treat it as still-loading rather
|
||||
@@ -157,22 +174,16 @@ export const Reply = as<'div', ReplyProps>(
|
||||
[mx, room.roomId, mentionClickHandler, nicknames]
|
||||
);
|
||||
|
||||
if (format === 'org.matrix.custom.html' && formattedBody) {
|
||||
const strippedHtml = trimReplyFromFormattedBody(formattedBody)
|
||||
.replaceAll(/<br\s*\/?>/gi, ' ')
|
||||
.replaceAll(/<\/p>\s*<p[^>]*>/gi, ' ')
|
||||
.replaceAll(/<\/?p[^>]*>/gi, '')
|
||||
.replaceAll(/<\/li>\s*<li[^>]*>/gi, ' ')
|
||||
.replaceAll(/<\/?(ul|ol|li|blockquote|h[1-6]|pre|div)[^>]*>/gi, '')
|
||||
.replaceAll(/(?:\r\n|\r|\n)/g, ' ');
|
||||
if (isFormattedReply && formattedBody !== '') {
|
||||
const sanitizedHtml = sanitizeReplyFormattedPreview(formattedBody);
|
||||
const parserOpts = getReactCustomHtmlParser(mx, room.roomId, {
|
||||
linkifyOpts: replyLinkifyOpts,
|
||||
useAuthentication,
|
||||
nicknames,
|
||||
handleMentionClick: mentionClickHandler,
|
||||
});
|
||||
bodyJSX = parse(strippedHtml, parserOpts) as JSX.Element;
|
||||
} else if (body) {
|
||||
bodyJSX = parse(sanitizedHtml, parserOpts) as JSX.Element;
|
||||
} else if (hasPlainTextReply) {
|
||||
const strippedBody = trimReplyFromBody(body).replaceAll(/(?:\r\n|\r|\n)/g, ' ');
|
||||
bodyJSX = scaleSystemEmoji(strippedBody);
|
||||
} else if (eventType === StateEvent.RoomMember && !!replyEvent) {
|
||||
@@ -230,6 +241,13 @@ export const Reply = as<'div', ReplyProps>(
|
||||
</>
|
||||
);
|
||||
}
|
||||
let replyContent = bodyJSX;
|
||||
if (isBlockedSender) {
|
||||
replyContent = <MessageBlockedContent />;
|
||||
} else if (badEncryption) {
|
||||
replyContent = <MessageBadEncryptedContent />;
|
||||
}
|
||||
|
||||
return (
|
||||
<Box direction="Row" gap="200" alignItems="Center" {...props} ref={ref}>
|
||||
{threadRootId && (
|
||||
@@ -254,11 +272,7 @@ export const Reply = as<'div', ReplyProps>(
|
||||
>
|
||||
{replyEvent !== undefined && !isPendingDecrypt ? (
|
||||
<Text size="T300" truncate>
|
||||
{(() => {
|
||||
if (isBlockedSender) return <MessageBlockedContent />;
|
||||
if (badEncryption) return <MessageBadEncryptedContent />;
|
||||
return bodyJSX;
|
||||
})()}
|
||||
{replyContent}
|
||||
</Text>
|
||||
) : (
|
||||
(isRedacted && <MessageDeletedContent />) || (
|
||||
|
||||
@@ -14,7 +14,7 @@
|
||||
import { describe, it, expect } from 'vitest';
|
||||
import { render, screen } from '@testing-library/react';
|
||||
import { RelationType } from '$types/matrix-sdk';
|
||||
import { ThreadIndicator } from './Reply';
|
||||
import { sanitizeReplyFormattedPreview, ThreadIndicator } from './Reply';
|
||||
|
||||
function Subject({ relType, threadRootId }: { relType?: string; threadRootId?: string }) {
|
||||
return <>{relType === RelationType.Thread && !threadRootId && <ThreadIndicator />}</>;
|
||||
@@ -41,3 +41,26 @@ describe('ThreadIndicator visibility in compose strip', () => {
|
||||
expect(screen.queryByText('Thread')).not.toBeInTheDocument();
|
||||
});
|
||||
});
|
||||
|
||||
describe('sanitizeReplyFormattedPreview', () => {
|
||||
it('removes mx-reply quote block content and keeps message text', () => {
|
||||
const html = '<mx-reply><blockquote>quoted</blockquote></mx-reply><p>Visible message</p>';
|
||||
|
||||
const result = sanitizeReplyFormattedPreview(html);
|
||||
|
||||
expect(result).not.toContain('quoted');
|
||||
expect(result).toContain('Visible message');
|
||||
});
|
||||
|
||||
it('sanitizes dangerous HTML before parse', () => {
|
||||
const html =
|
||||
'<mx-reply><blockquote>old</blockquote></mx-reply><p>safe<script>alert(1)</script></p><a href="https://example.org" onclick="alert(1)">x</a>';
|
||||
|
||||
const result = sanitizeReplyFormattedPreview(html);
|
||||
|
||||
expect(result).not.toContain('<script');
|
||||
expect(result).not.toContain('alert(1)');
|
||||
expect(result).not.toContain('onclick=');
|
||||
expect(result).toContain('safe');
|
||||
});
|
||||
});
|
||||
@@ -23,7 +23,7 @@ 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 } from '$utils/sanitize';
|
||||
import { sanitizeCustomHtml, sanitizeText } from '$utils/sanitize';
|
||||
import { getStateEvents } from '$utils/room';
|
||||
import { StateEvent } from '$types/matrix/room';
|
||||
import { createDebugLogger } from '$utils/debugLogger';
|
||||
@@ -206,12 +206,12 @@ export function MessageForwardInternal({
|
||||
|
||||
const safeHtml =
|
||||
originalFormattedBody === undefined
|
||||
? sanitizeCustomHtml(originalBody).replaceAll('\n', '<br>')
|
||||
? sanitizeText(originalBody).replaceAll('\n', '<br>')
|
||||
: sanitizeCustomHtml(originalFormattedBody);
|
||||
|
||||
newBodyHtml =
|
||||
`<div data-forward-marker>` +
|
||||
`<p>${sanitizeCustomHtml(bodyModifText)}</p>` +
|
||||
`<p>${sanitizeText(bodyModifText)}</p>` +
|
||||
`<blockquote>${safeHtml}</blockquote>` +
|
||||
`</div>`;
|
||||
}
|
||||
@@ -224,6 +224,8 @@ export function MessageForwardInternal({
|
||||
}
|
||||
: {};
|
||||
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
|
||||
@@ -232,8 +234,6 @@ export function MessageForwardInternal({
|
||||
// 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,
|
||||
'm.relates_to': null, // remove any relations to avoid confusion in the target room
|
||||
'm.mentions': null, // remove mentions to avoid leaking information about users in the original room
|
||||
...forwardedTextContent,
|
||||
'moe.sable.message.forward': {
|
||||
v: 1,
|
||||
@@ -249,10 +249,6 @@ export function MessageForwardInternal({
|
||||
content = {
|
||||
...baseContent,
|
||||
...forwardedTextContent,
|
||||
'm.relates_to': {
|
||||
rel_type: 'm.reference',
|
||||
event_id: eventId,
|
||||
},
|
||||
'moe.sable.message.forward': {
|
||||
v: 1,
|
||||
is_forwarded: true,
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
import { JoinRule } from '$types/matrix-sdk';
|
||||
import { AvatarFallback, Icon, Icons, color } from 'folds';
|
||||
import { ComponentProps, ReactNode, forwardRef, useState } from 'react';
|
||||
import { ComponentProps, ReactNode, forwardRef, useEffect, useState } from 'react';
|
||||
import { getRoomIconSrc } from '$utils/room';
|
||||
import colorMXID from '$utils/colorMXID';
|
||||
import * as css from './RoomAvatar.css';
|
||||
@@ -17,6 +17,10 @@ type RoomAvatarProps = {
|
||||
export function RoomAvatar({ roomId, src, alt, renderFallback, uniformIcons }: RoomAvatarProps) {
|
||||
const [error, setError] = useState(false);
|
||||
|
||||
useEffect(() => {
|
||||
setError(false);
|
||||
}, [src]);
|
||||
|
||||
if (!src || error) {
|
||||
return (
|
||||
<AvatarFallback
|
||||
|
||||
@@ -166,17 +166,21 @@ function parseYoutubeLink(url: string): YoutubeLink | null {
|
||||
if (url.includes('youtu.be')) {
|
||||
const split = path.split('?');
|
||||
[videoId] = split;
|
||||
params = split[1].split('&');
|
||||
} else {
|
||||
params = path.split('?')[1].split('&');
|
||||
videoId = params.find((s) => s.startsWith('v='), params)?.split('v=')[1];
|
||||
}
|
||||
params = split[1]?.split('&');
|
||||
} else if (url.includes('/shorts/')) {
|
||||
const split = path.split('?');
|
||||
[videoId] = split;
|
||||
params = split[1]?.split('&') ?? [];
|
||||
} else if (url.includes('youtube.com')) {
|
||||
params = path.split('?')[1]?.split('&') ?? [];
|
||||
videoId = params.find((s) => s.startsWith('v='))?.split('v=')[1];
|
||||
} else return null;
|
||||
|
||||
if (!videoId) return null;
|
||||
|
||||
// playlist is not used for the embed, it can be appended as is
|
||||
const playlist = params.find((s) => s.startsWith('list='), params);
|
||||
const timestamp = params.find((s) => s.startsWith('t='), params)?.split('t=')[1];
|
||||
const playlist = params ? params.find((s) => s.startsWith('list=')) : undefined;
|
||||
const timestamp = params ? params.find((s) => s.startsWith('t='))?.split('t=')[1] : undefined;
|
||||
|
||||
return {
|
||||
videoId,
|
||||
|
||||
@@ -14,6 +14,23 @@ import { ImageViewer } from '../image-viewer';
|
||||
|
||||
const linkStyles = { color: color.Success.Main };
|
||||
|
||||
// Module-level in-flight deduplication: prevents N+1 concurrent requests when a
|
||||
// large event batch renders many UrlPreviewCard instances for the same URL.
|
||||
// Scoped by MatrixClient to avoid cross-account dedup if multiple clients exist.
|
||||
// Inner cache keyed by URL only (not ts) — the same URL shows the same preview
|
||||
// regardless of which message referenced it. Promises are evicted after settling
|
||||
// so a later render can retry after network recovery.
|
||||
const previewRequestCache = new WeakMap<any, Map<string, Promise<IPreviewUrlResponse>>>();
|
||||
|
||||
const getClientCache = (mx: any): Map<string, Promise<IPreviewUrlResponse>> => {
|
||||
let clientCache = previewRequestCache.get(mx);
|
||||
if (!clientCache) {
|
||||
clientCache = new Map();
|
||||
previewRequestCache.set(mx, clientCache);
|
||||
}
|
||||
return clientCache;
|
||||
};
|
||||
|
||||
const openMediaInNewTab = async (url: string | undefined) => {
|
||||
if (!url) {
|
||||
console.warn('Attempted to open an empty url');
|
||||
@@ -34,7 +51,13 @@ export const UrlPreviewCard = as<'div', { url: string; ts: number; mediaType?: s
|
||||
const [previewStatus, loadPreview] = useAsyncCallback(
|
||||
useCallback(() => {
|
||||
if (isDirect) return Promise.resolve(null);
|
||||
return mx.getUrlPreview(url, ts);
|
||||
const clientCache = getClientCache(mx);
|
||||
const cached = clientCache.get(url);
|
||||
if (cached !== undefined) return cached;
|
||||
const urlPreview = mx.getUrlPreview(url, ts);
|
||||
clientCache.set(url, urlPreview);
|
||||
urlPreview.finally(() => clientCache.delete(url));
|
||||
return urlPreview;
|
||||
}, [url, ts, mx, isDirect])
|
||||
);
|
||||
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
import { AvatarFallback, AvatarImage, color } from 'folds';
|
||||
import { ReactEventHandler, ReactNode, useState } from 'react';
|
||||
import { ReactEventHandler, ReactNode, useEffect, useState } from 'react';
|
||||
import classNames from 'classnames';
|
||||
import colorMXID from '$utils/colorMXID';
|
||||
import * as css from './UserAvatar.css';
|
||||
@@ -14,6 +14,10 @@ type UserAvatarProps = {
|
||||
export function UserAvatar({ className, userId, src, alt, renderFallback }: UserAvatarProps) {
|
||||
const [error, setError] = useState(false);
|
||||
|
||||
useEffect(() => {
|
||||
setError(false);
|
||||
}, [src]);
|
||||
|
||||
const handleLoad: ReactEventHandler<HTMLImageElement> = (evt) => {
|
||||
evt.currentTarget.setAttribute('data-image-loaded', 'true');
|
||||
};
|
||||
|
||||
@@ -7,6 +7,7 @@ import {
|
||||
useEffect,
|
||||
useRef,
|
||||
useState,
|
||||
useMemo,
|
||||
} from 'react';
|
||||
import { useAtom, useAtomValue } from 'jotai';
|
||||
import { isKeyHotkey } from 'is-hotkey';
|
||||
@@ -143,7 +144,9 @@ import {
|
||||
} from '$hooks/usePerMessageProfile';
|
||||
import { Microphone, Stop } from '@phosphor-icons/react';
|
||||
import { getSupportedAudioExtension } from '$plugins/voice-recorder-kit/supportedCodec';
|
||||
import { sanitizeCustomHtml } from '$utils/sanitize';
|
||||
import { sanitizeText } from '$utils/sanitize';
|
||||
import { PKitCommandMessageHandler } from '$plugins/pluralkit-handler/PKitCommandMessageHandler';
|
||||
import { PKitProxyMessageHandler } from '$plugins/pluralkit-handler/PKitProxyMessageHandler';
|
||||
import { SchedulePickerDialog } from './schedule-send';
|
||||
import * as css from './schedule-send/SchedulePickerDialog.css';
|
||||
import {
|
||||
@@ -249,6 +252,20 @@ export const RoomInput = forwardRef<HTMLDivElement, RoomInputProps>(
|
||||
const [hideActivity] = useSetting(settingsAtom, 'hideActivity');
|
||||
const [mentionInReplies] = useSetting(settingsAtom, 'mentionInReplies');
|
||||
const commands = useCommands(mx, room);
|
||||
/**
|
||||
* handle pluralkit-style messages
|
||||
*/
|
||||
const pluralkitCmdMessageHandler = useMemo(
|
||||
() => new PKitCommandMessageHandler(mx, room),
|
||||
[mx, room]
|
||||
);
|
||||
const pluralkitProxyMessageHandler = useMemo(() => new PKitProxyMessageHandler(mx), [mx]);
|
||||
useEffect(() => {
|
||||
pluralkitProxyMessageHandler.init();
|
||||
}, [pluralkitProxyMessageHandler]);
|
||||
|
||||
const [pkCompatEnable] = useSetting(settingsAtom, 'pkCompat');
|
||||
const [pmpProxyingEnable] = useSetting(settingsAtom, 'pmpProxying');
|
||||
const emojiBtnRef = useRef<HTMLButtonElement>(null);
|
||||
const micBtnRef = useRef<HTMLButtonElement>(null);
|
||||
const roomToParents = useAtomValue(roomToParentsAtom);
|
||||
@@ -707,6 +724,13 @@ export const RoomInput = forwardRef<HTMLDivElement, RoomInputProps>(
|
||||
return;
|
||||
}
|
||||
|
||||
// check if its a pk command
|
||||
if (pkCompatEnable && PKitCommandMessageHandler.isPKCommand(plainText)) {
|
||||
pluralkitCmdMessageHandler.handleMessage(plainText);
|
||||
resetEditor(editor); // clear the editor
|
||||
return; // don't do anything besides handling the command
|
||||
}
|
||||
|
||||
if (commandName) {
|
||||
plainText = trimCommand(commandName, plainText);
|
||||
customHtml = trimCommand(commandName, customHtml);
|
||||
@@ -763,8 +787,13 @@ export const RoomInput = forwardRef<HTMLDivElement, RoomInputProps>(
|
||||
* 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 = await getCurrentlyUsedPerMessageProfileForRoom(mx, roomId);
|
||||
const perMessageProfile =
|
||||
pmpProxyingEnable && pluralkitProxyMessageHandler.isAProxiedMessage(plainText)
|
||||
? await pluralkitProxyMessageHandler.getPmpBasedOnMessage(plainText)
|
||||
: await getCurrentlyUsedPerMessageProfileForRoom(mx, roomId);
|
||||
|
||||
if (pmpProxyingEnable && pluralkitProxyMessageHandler.isAProxiedMessage(plainText))
|
||||
plainText = pluralkitProxyMessageHandler.stripProxyFromMessage(plainText) ?? plainText;
|
||||
if (perMessageProfile) {
|
||||
content['com.beeper.per_message_profile'] = convertPerMessageProfileToBeeperFormat(
|
||||
perMessageProfile,
|
||||
@@ -783,7 +812,7 @@ export const RoomInput = forwardRef<HTMLDivElement, RoomInputProps>(
|
||||
/**
|
||||
* html escaped version of the display name
|
||||
*/
|
||||
const escapedName = sanitizeCustomHtml(perMessageProfile.name);
|
||||
const escapedName = sanitizeText(perMessageProfile.name);
|
||||
|
||||
const htmlPrefix = `<strong data-mx-profile-fallback>${escapedName}: </strong>`;
|
||||
|
||||
@@ -894,19 +923,23 @@ export const RoomInput = forwardRef<HTMLDivElement, RoomInputProps>(
|
||||
}, [
|
||||
editor,
|
||||
replyEvent,
|
||||
isMarkdown,
|
||||
canSendReaction,
|
||||
mx,
|
||||
roomId,
|
||||
isMarkdown,
|
||||
canSendReaction,
|
||||
pkCompatEnable,
|
||||
replyDraft,
|
||||
silentReply,
|
||||
pmpProxyingEnable,
|
||||
pluralkitProxyMessageHandler,
|
||||
scheduledTime,
|
||||
editingScheduledDelayId,
|
||||
nicknames,
|
||||
room,
|
||||
handleQuickReact,
|
||||
pluralkitCmdMessageHandler,
|
||||
commands,
|
||||
sendTypingStatus,
|
||||
room,
|
||||
queryClient,
|
||||
threadRootId,
|
||||
setReplyDraft,
|
||||
|
||||
@@ -209,6 +209,14 @@ export function RoomTimeline({
|
||||
const topSpacerHeightRef = useRef(0);
|
||||
const mountScrollWindowRef = useRef<number>(Date.now() + 3000);
|
||||
const hasInitialScrolledRef = useRef(false);
|
||||
// Stored in a ref so eventsLength fluctuations (e.g. onLifecycle timeline reset
|
||||
// firing within the window) cannot cancel it via useLayoutEffect cleanup.
|
||||
const initialScrollTimerRef = useRef<ReturnType<typeof setTimeout> | undefined>(undefined);
|
||||
// Set to true when the 80 ms timer fires but processedEvents is still empty
|
||||
// (e.g. the onLifecycle reset cleared the timeline before events refilled it).
|
||||
// A recovery useLayoutEffect watches for processedEvents becoming non-empty
|
||||
// and performs the final scroll + setIsReady when this flag is set.
|
||||
const pendingReadyRef = useRef(false);
|
||||
const currentRoomIdRef = useRef(room.roomId);
|
||||
|
||||
const [isReady, setIsReady] = useState(false);
|
||||
@@ -217,6 +225,11 @@ export function RoomTimeline({
|
||||
hasInitialScrolledRef.current = false;
|
||||
mountScrollWindowRef.current = Date.now() + 3000;
|
||||
currentRoomIdRef.current = room.roomId;
|
||||
pendingReadyRef.current = false;
|
||||
if (initialScrollTimerRef.current !== undefined) {
|
||||
clearTimeout(initialScrollTimerRef.current);
|
||||
initialScrollTimerRef.current = undefined;
|
||||
}
|
||||
setIsReady(false);
|
||||
}
|
||||
|
||||
@@ -272,18 +285,45 @@ export function RoomTimeline({
|
||||
!eventId &&
|
||||
!hasInitialScrolledRef.current &&
|
||||
timelineSync.eventsLength > 0 &&
|
||||
// Guard: only scroll once the timeline reflects the current room's live
|
||||
// timeline. Without this, a render with stale data from the previous room
|
||||
// (before the room-change reset propagates) fires the scroll at the wrong
|
||||
// position and marks hasInitialScrolledRef = true, preventing the correct
|
||||
// scroll when the right data arrives.
|
||||
timelineSync.liveTimelineLinked &&
|
||||
vListRef.current
|
||||
) {
|
||||
vListRef.current.scrollToIndex(processedEventsRef.current.length - 1, { align: 'end' });
|
||||
const t = setTimeout(() => {
|
||||
vListRef.current?.scrollToIndex(processedEventsRef.current.length - 1, { align: 'end' });
|
||||
setIsReady(true);
|
||||
// Store in a ref rather than a local so subsequent eventsLength changes
|
||||
// (e.g. the onLifecycle timeline reset firing within 80 ms) do NOT
|
||||
// cancel this timer through the useLayoutEffect cleanup.
|
||||
initialScrollTimerRef.current = setTimeout(() => {
|
||||
initialScrollTimerRef.current = undefined;
|
||||
if (processedEventsRef.current.length > 0) {
|
||||
vListRef.current?.scrollToIndex(processedEventsRef.current.length - 1, { align: 'end' });
|
||||
// Only mark ready once we've successfully scrolled. If processedEvents
|
||||
// was empty when the timer fired (e.g. the onLifecycle reset cleared the
|
||||
// timeline within the 80 ms window), defer setIsReady until the recovery
|
||||
// effect below fires once events repopulate.
|
||||
setIsReady(true);
|
||||
} else {
|
||||
pendingReadyRef.current = true;
|
||||
}
|
||||
}, 80);
|
||||
hasInitialScrolledRef.current = true;
|
||||
return () => clearTimeout(t);
|
||||
}
|
||||
return () => {};
|
||||
}, [timelineSync.eventsLength, eventId, room.roomId]);
|
||||
// No cleanup return — the timer must survive eventsLength fluctuations.
|
||||
// It is cancelled on unmount by the dedicated effect below.
|
||||
}, [timelineSync.eventsLength, timelineSync.liveTimelineLinked, eventId, room.roomId]);
|
||||
|
||||
// Cancel the initial-scroll timer on unmount (the useLayoutEffect above
|
||||
// intentionally does not cancel it when deps change).
|
||||
useEffect(
|
||||
() => () => {
|
||||
if (initialScrollTimerRef.current !== undefined) clearTimeout(initialScrollTimerRef.current);
|
||||
},
|
||||
[]
|
||||
);
|
||||
|
||||
const recalcTopSpacer = useCallback(() => {
|
||||
const v = vListRef.current;
|
||||
@@ -357,6 +397,11 @@ export function RoomTimeline({
|
||||
|
||||
useEffect(() => {
|
||||
if (eventId) return;
|
||||
// Guard: once the timeline is visible to the user, do not override their
|
||||
// scroll position. Without this, a later timeline refresh (e.g. the
|
||||
// onLifecycle reset delivering a new linkedTimelines reference) can fire
|
||||
// this effect after isReady and snap the view back to the read marker.
|
||||
if (isReady) return;
|
||||
const { readUptoEventId, inLiveTimeline, scrollTo } = unreadInfo ?? {};
|
||||
if (readUptoEventId && inLiveTimeline && scrollTo) {
|
||||
const evtTimeline = getEventTimeline(room, readUptoEventId);
|
||||
@@ -368,12 +413,16 @@ export function RoomTimeline({
|
||||
)
|
||||
: undefined;
|
||||
|
||||
if (absoluteIndex !== undefined && vListRef.current) {
|
||||
if (absoluteIndex !== undefined) {
|
||||
const processedIndex = getRawIndexToProcessedIndex(absoluteIndex);
|
||||
if (processedIndex !== undefined) {
|
||||
if (processedIndex !== undefined && vListRef.current) {
|
||||
vListRef.current.scrollToIndex(processedIndex, { align: 'start' });
|
||||
setUnreadInfo((prev) => (prev ? { ...prev, scrollTo: false } : prev));
|
||||
}
|
||||
// Always consume the scroll intent once the event is located in the
|
||||
// linked timelines, even if its processedIndex is undefined (filtered
|
||||
// event). Without this, each linkedTimelines reference change retries
|
||||
// the scroll indefinitely.
|
||||
setUnreadInfo((prev) => (prev ? { ...prev, scrollTo: false } : prev));
|
||||
}
|
||||
}
|
||||
}, [
|
||||
@@ -381,6 +430,7 @@ export function RoomTimeline({
|
||||
unreadInfo,
|
||||
timelineSync.timeline.linkedTimelines,
|
||||
eventId,
|
||||
isReady,
|
||||
getRawIndexToProcessedIndex,
|
||||
]);
|
||||
|
||||
@@ -674,6 +724,18 @@ export function RoomTimeline({
|
||||
|
||||
processedEventsRef.current = processedEvents;
|
||||
|
||||
// Recovery: if the 80 ms initial-scroll timer fired while processedEvents was
|
||||
// empty (timeline was mid-reset), scroll to bottom and reveal the timeline once
|
||||
// events repopulate. Fires on every processedEvents.length change but is
|
||||
// guarded by pendingReadyRef so it only acts once per initial-scroll attempt.
|
||||
useLayoutEffect(() => {
|
||||
if (!pendingReadyRef.current) return;
|
||||
if (processedEvents.length === 0) return;
|
||||
pendingReadyRef.current = false;
|
||||
vListRef.current?.scrollToIndex(processedEvents.length - 1, { align: 'end' });
|
||||
setIsReady(true);
|
||||
}, [processedEvents.length]);
|
||||
|
||||
useEffect(() => {
|
||||
if (!onEditLastMessageRef) return;
|
||||
const ref = onEditLastMessageRef;
|
||||
|
||||
@@ -72,7 +72,7 @@ import { HTMLReactParserOptions } from 'html-react-parser';
|
||||
import { useMediaAuthentication } from '$hooks/useMediaAuthentication';
|
||||
import { Opts as LinkifyOpts } from 'linkifyjs';
|
||||
import { GetContentCallback } from '$types/matrix/room';
|
||||
import { sanitizeCustomHtml } from '$utils/sanitize';
|
||||
import { sanitizeText } from '$utils/sanitize';
|
||||
|
||||
type MessageEditorProps = {
|
||||
roomId: string;
|
||||
@@ -204,7 +204,7 @@ export const MessageEditor = as<'div', MessageEditorProps>(
|
||||
plainText = bodyPrefix + plainText;
|
||||
}
|
||||
|
||||
const escapedName = sanitizeCustomHtml(pmpDisplayname);
|
||||
const escapedName = sanitizeText(pmpDisplayname);
|
||||
const htmlPrefix = `<strong data-mx-profile-fallback>${escapedName}: </strong>`;
|
||||
if (!customHtml.startsWith(htmlPrefix)) {
|
||||
customHtml = htmlPrefix + customHtml;
|
||||
|
||||
@@ -0,0 +1,52 @@
|
||||
import { SequenceCard } from '$components/sequence-card';
|
||||
import { SettingTile } from '$components/setting-tile';
|
||||
import { useSetting } from '$state/hooks/settings';
|
||||
import { settingsAtom } from '$state/settings';
|
||||
import { Box, Switch, Text } from 'folds';
|
||||
import { SequenceCardStyle } from '../styles.css';
|
||||
|
||||
export function PKCompatSettings() {
|
||||
const [usePKCompat, setUsePKCompat] = useSetting(settingsAtom, 'pkCompat');
|
||||
const [usePmpProxying, setUsePmpProxying] = useSetting(settingsAtom, 'pmpProxying');
|
||||
|
||||
return (
|
||||
<Box direction="Column" gap="100">
|
||||
<Text size="L400">Limited Compatibility with PluralKit-like functions</Text>
|
||||
<SequenceCard
|
||||
className={SequenceCardStyle}
|
||||
variant="SurfaceVariant"
|
||||
direction="Column"
|
||||
gap="100"
|
||||
>
|
||||
<SettingTile
|
||||
title="Enable PK commands"
|
||||
description="If enabled, it will enable a few pk style commands, currently verry limited"
|
||||
after={
|
||||
<Switch
|
||||
variant="Primary"
|
||||
value={usePKCompat}
|
||||
onChange={setUsePKCompat}
|
||||
title={usePKCompat ? 'disable pk; commands' : 'enable pk; commands'}
|
||||
/>
|
||||
}
|
||||
/>
|
||||
<SettingTile
|
||||
title="Enable Shorthands"
|
||||
description="If enabled, you can use shorthands to use a Persona for one message only (eg. '✨:test')"
|
||||
after={
|
||||
<Switch
|
||||
variant="Primary"
|
||||
value={usePmpProxying}
|
||||
onChange={setUsePmpProxying}
|
||||
title={
|
||||
usePmpProxying
|
||||
? 'disable checking typed messages for shorthands'
|
||||
: 'enable checking typed messages for shorthands'
|
||||
}
|
||||
/>
|
||||
}
|
||||
/>
|
||||
</SequenceCard>
|
||||
</Box>
|
||||
);
|
||||
}
|
||||
@@ -6,6 +6,7 @@ import {
|
||||
} from '$hooks/usePerMessageProfile';
|
||||
import { useEffect, useState } from 'react';
|
||||
import { Box, Button, Text } from 'folds';
|
||||
import { generateShortId } from '$utils/shortIdGen';
|
||||
import { PerMessageProfileEditor } from './PerMessageProfileEditor';
|
||||
|
||||
/**
|
||||
@@ -36,7 +37,7 @@ export function PerMessageProfileOverview() {
|
||||
<Button
|
||||
onClick={() => {
|
||||
const newProfile: PerMessageProfile = {
|
||||
id: crypto.randomUUID(),
|
||||
id: generateShortId(5),
|
||||
name: 'New Profile',
|
||||
};
|
||||
addOrUpdatePerMessageProfile(mx, newProfile).then(() => {
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
import { Page, PageHeader, PageNavContent } from '$components/page';
|
||||
import { Box, IconButton, Icon, Icons, Text } from 'folds';
|
||||
import { PerMessageProfileOverview } from './PerMessageProfileOverview';
|
||||
import { PKCompatSettings } from './PKCompat';
|
||||
|
||||
type PerMessageProfilePageProps = {
|
||||
requestClose: () => void;
|
||||
@@ -37,6 +38,7 @@ export function PerMessageProfilePage({ requestClose }: PerMessageProfilePagePro
|
||||
direction="Column"
|
||||
shrink="No"
|
||||
>
|
||||
<PKCompatSettings />
|
||||
<PerMessageProfileOverview />
|
||||
</Box>
|
||||
</PageNavContent>
|
||||
|
||||
@@ -44,7 +44,7 @@ type BioEditorProps = {
|
||||
value?: string | any;
|
||||
isSaving?: boolean;
|
||||
imagePackRooms?: any[];
|
||||
onSave: (htmlContent: string) => void;
|
||||
onSave: (htmlContent: string, plainText: string) => void;
|
||||
};
|
||||
|
||||
const BIO_LIMIT = 1024;
|
||||
@@ -81,7 +81,7 @@ export function BioEditor({ value, isSaving, imagePackRooms, onSave }: BioEditor
|
||||
})
|
||||
);
|
||||
|
||||
onSave(customHtml || plainText);
|
||||
onSave(customHtml || plainText, plainText);
|
||||
setHasChanged(false);
|
||||
}, [editor, isMarkdown, onSave]);
|
||||
|
||||
|
||||
@@ -29,7 +29,7 @@ import { useSetAtom } from 'jotai';
|
||||
import { SequenceCard } from '$components/sequence-card';
|
||||
import { SettingTile } from '$components/setting-tile';
|
||||
import { useMatrixClient } from '$hooks/useMatrixClient';
|
||||
import { UserProfile, useUserProfile } from '$hooks/useUserProfile';
|
||||
import { UserProfile, useUserProfile, MSC4440Bio } from '$hooks/useUserProfile';
|
||||
import { getMxIdLocalPart, mxcUrlToHttp } from '$utils/matrix';
|
||||
import { UserAvatar } from '$components/user-avatar';
|
||||
import { useMediaAuthentication } from '$hooks/useMediaAuthentication';
|
||||
@@ -46,6 +46,7 @@ import { useCapabilities } from '$hooks/useCapabilities';
|
||||
import { profilesCacheAtom } from '$state/userRoomProfile';
|
||||
import { SequenceCardStyle } from '$features/settings/styles.css';
|
||||
import { useUserPresence } from '$hooks/useUserPresence';
|
||||
import { MSC1767Text } from '$types/matrix/common';
|
||||
import { TimezoneEditor } from './TimezoneEditor';
|
||||
import { PronounEditor } from './PronounEditor';
|
||||
import { BioEditor } from './BioEditor';
|
||||
@@ -576,13 +577,27 @@ function ProfileExtended({ profile, userId }: Readonly<ProfileProps>) {
|
||||
>
|
||||
<BioEditor
|
||||
value={
|
||||
(profile.extended?.['gay.fomx.biography'] satisfies MSC4440Bio)?.formatted_body ||
|
||||
profile.extended?.['moe.sable.app.bio'] ||
|
||||
profile.extended?.['chat.commet.profile_bio'] ||
|
||||
profile.bio
|
||||
}
|
||||
onSave={(htmlBio) => {
|
||||
onSave={(htmlBio, plainTextBio) => {
|
||||
handleSaveField('moe.sable.app.bio', htmlBio);
|
||||
|
||||
// MSC4440
|
||||
handleSaveField('gay.fomx.biography', {
|
||||
'm.text': [
|
||||
{
|
||||
body: htmlBio,
|
||||
mimetype: 'text/html',
|
||||
} satisfies MSC1767Text,
|
||||
{
|
||||
body: plainTextBio,
|
||||
} satisfies MSC1767Text,
|
||||
],
|
||||
} satisfies MSC4440Bio);
|
||||
|
||||
const cleanedHtml = htmlBio.replaceAll('<br/></blockquote>', '</blockquote>');
|
||||
handleSaveField('chat.commet.profile_bio', {
|
||||
format: 'org.matrix.custom.html',
|
||||
|
||||
@@ -23,8 +23,7 @@ function formatKey(key: string): string {
|
||||
return key
|
||||
.replace(/\bmod\b/g, isMac ? '⌘' : 'Ctrl')
|
||||
.replace(/\balt\b/gi, isMac ? '⌥' : 'Alt')
|
||||
.replace(/\bshift\b/gi, '⇧')
|
||||
.replace(/\+/g, '+');
|
||||
.replace(/\bshift\b/gi, '⇧');
|
||||
}
|
||||
|
||||
const SHORTCUT_CATEGORIES: ShortcutCategory[] = [
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
import { MouseEventHandler, useMemo } from 'react';
|
||||
import { MouseEventHandler, useCallback, useMemo } from 'react';
|
||||
import { useTranslation } from 'react-i18next';
|
||||
import { useAtomValue } from 'jotai';
|
||||
import {
|
||||
@@ -20,6 +20,7 @@ import { useMemberEventParser } from '$hooks/useMemberEventParser';
|
||||
import { useMatrixClient } from '$hooks/useMatrixClient';
|
||||
import { useMediaAuthentication } from '$hooks/useMediaAuthentication';
|
||||
import { useMatrixEventRenderer } from '$hooks/useMatrixEventRenderer';
|
||||
import { useOpenUserRoomProfile } from '$state/hooks/userRoomProfile';
|
||||
import {
|
||||
EventContent,
|
||||
ImageContent,
|
||||
@@ -58,9 +59,25 @@ import { useSableCosmetics } from '$hooks/useSableCosmetics';
|
||||
|
||||
function DecoratedUser({ room, userId, userName }: DecoratedUserProps) {
|
||||
const { color, font } = useSableCosmetics(userId, room ?? ({} as Room));
|
||||
|
||||
const openUserRoomProfile = useOpenUserRoomProfile();
|
||||
const handleUserClick: MouseEventHandler = useCallback(
|
||||
(evt) => {
|
||||
evt.preventDefault();
|
||||
evt.stopPropagation();
|
||||
openUserRoomProfile(
|
||||
room.roomId,
|
||||
undefined,
|
||||
userId,
|
||||
evt.currentTarget.getBoundingClientRect()
|
||||
);
|
||||
},
|
||||
[room, userId, openUserRoomProfile]
|
||||
);
|
||||
|
||||
return (
|
||||
<Text truncate>
|
||||
<b style={{ color, font }}> {userName ?? userId} </b>
|
||||
<Text as="a" onClick={handleUserClick} truncate>
|
||||
<b style={{ color, font }}>{userName ?? userId} </b>
|
||||
</Text>
|
||||
);
|
||||
}
|
||||
|
||||
@@ -40,12 +40,18 @@ function createTimeline(events: unknown[] = [{}]): FakeTimeline {
|
||||
};
|
||||
}
|
||||
|
||||
function createRoom(events: unknown[] = [{}]): {
|
||||
function createRoom(
|
||||
roomId = '!room:test',
|
||||
events: unknown[] = [{}]
|
||||
): {
|
||||
room: FakeRoom;
|
||||
timelineSet: FakeTimelineSet;
|
||||
events: unknown[];
|
||||
} {
|
||||
const timeline = createTimeline(events);
|
||||
const timeline = {
|
||||
...createTimeline(events),
|
||||
getRoomId: () => roomId,
|
||||
};
|
||||
const timelineSet = new EventEmitter() as FakeTimelineSet;
|
||||
timelineSet.getLiveTimeline = () => timeline;
|
||||
timelineSet.getTimelineForEvent = () => undefined;
|
||||
@@ -55,7 +61,7 @@ function createRoom(events: unknown[] = [{}]): {
|
||||
on: roomEmitter.on.bind(roomEmitter),
|
||||
removeListener: roomEmitter.removeListener.bind(roomEmitter),
|
||||
emit: roomEmitter.emit.bind(roomEmitter),
|
||||
roomId: '!room:test',
|
||||
roomId,
|
||||
getUnfilteredTimelineSet: () => timelineSet as never,
|
||||
getEventReadUpTo: () => null,
|
||||
getThread: () => null,
|
||||
@@ -125,4 +131,110 @@ describe('useTimelineSync', () => {
|
||||
|
||||
expect(scrollToBottom).toHaveBeenCalledWith('instant');
|
||||
});
|
||||
|
||||
it('resets timeline state when room.roomId changes and eventId is not set', async () => {
|
||||
const roomOne = createRoom('!room:one');
|
||||
const roomTwo = createRoom('!room:two');
|
||||
const scrollToBottom = vi.fn();
|
||||
|
||||
const { result, rerender } = renderHook(
|
||||
({ room, eventId }) =>
|
||||
useTimelineSync({
|
||||
room,
|
||||
mx: { getUserId: () => '@alice:test' } as never,
|
||||
eventId,
|
||||
isAtBottom: false,
|
||||
isAtBottomRef: { current: false },
|
||||
scrollToBottom,
|
||||
unreadInfo: undefined,
|
||||
setUnreadInfo: vi.fn(),
|
||||
hideReadsRef: { current: false },
|
||||
readUptoEventIdRef: { current: undefined },
|
||||
}),
|
||||
{
|
||||
initialProps: {
|
||||
room: roomOne.room as Room,
|
||||
eventId: undefined as string | undefined,
|
||||
},
|
||||
}
|
||||
);
|
||||
|
||||
expect(result.current.timeline.linkedTimelines[0]).toBe(roomOne.timelineSet.getLiveTimeline());
|
||||
|
||||
await act(async () => {
|
||||
rerender({ room: roomTwo.room as Room, eventId: undefined });
|
||||
await Promise.resolve();
|
||||
});
|
||||
|
||||
expect(result.current.timeline.linkedTimelines[0]).toBe(roomTwo.timelineSet.getLiveTimeline());
|
||||
});
|
||||
|
||||
it('does not reset timeline when eventId is set during a room change', async () => {
|
||||
const roomOne = createRoom('!room:one');
|
||||
const roomTwo = createRoom('!room:two');
|
||||
const scrollToBottom = vi.fn();
|
||||
|
||||
const { result, rerender } = renderHook(
|
||||
({ room, eventId }) =>
|
||||
useTimelineSync({
|
||||
room,
|
||||
mx: { getUserId: () => '@alice:test' } as never,
|
||||
eventId,
|
||||
isAtBottom: false,
|
||||
isAtBottomRef: { current: false },
|
||||
scrollToBottom,
|
||||
unreadInfo: undefined,
|
||||
setUnreadInfo: vi.fn(),
|
||||
hideReadsRef: { current: false },
|
||||
readUptoEventIdRef: { current: undefined },
|
||||
}),
|
||||
{
|
||||
initialProps: {
|
||||
room: roomOne.room as Room,
|
||||
eventId: undefined as string | undefined,
|
||||
},
|
||||
}
|
||||
);
|
||||
|
||||
await act(async () => {
|
||||
rerender({ room: roomTwo.room as Room, eventId: '$event:one' });
|
||||
await Promise.resolve();
|
||||
});
|
||||
|
||||
expect(result.current.timeline.linkedTimelines[0]).toBe(roomOne.timelineSet.getLiveTimeline());
|
||||
});
|
||||
|
||||
it('does not reset timeline when the roomId stays the same', async () => {
|
||||
const roomOne = createRoom('!room:one');
|
||||
const sameRoomId = createRoom('!room:one');
|
||||
const scrollToBottom = vi.fn();
|
||||
|
||||
const { result, rerender } = renderHook(
|
||||
({ room }) =>
|
||||
useTimelineSync({
|
||||
room,
|
||||
mx: { getUserId: () => '@alice:test' } as never,
|
||||
eventId: undefined,
|
||||
isAtBottom: false,
|
||||
isAtBottomRef: { current: false },
|
||||
scrollToBottom,
|
||||
unreadInfo: undefined,
|
||||
setUnreadInfo: vi.fn(),
|
||||
hideReadsRef: { current: false },
|
||||
readUptoEventIdRef: { current: undefined },
|
||||
}),
|
||||
{
|
||||
initialProps: {
|
||||
room: roomOne.room as Room,
|
||||
},
|
||||
}
|
||||
);
|
||||
|
||||
await act(async () => {
|
||||
rerender({ room: sameRoomId.room as Room });
|
||||
await Promise.resolve();
|
||||
});
|
||||
|
||||
expect(result.current.timeline.linkedTimelines[0]).toBe(roomOne.timelineSet.getLiveTimeline());
|
||||
});
|
||||
});
|
||||
@@ -147,6 +147,13 @@ const useTimelinePagination = (
|
||||
(backwards ? setBackwardStatus : setForwardStatus)('loading');
|
||||
}
|
||||
|
||||
// `continuing` tracks whether we hand the fetchingRef lock to a recursive
|
||||
// continuation call below. The finally block must NOT reset the lock if
|
||||
// the recursive call has already claimed it, otherwise there is a brief
|
||||
// window where fetchingRef is false while the recursive paginate is in
|
||||
// flight, allowing a third overlapping call to start on sparse pages.
|
||||
let continuing = false;
|
||||
|
||||
try {
|
||||
const countBefore = getTimelinesEventsCount(lTimelines);
|
||||
|
||||
@@ -172,25 +179,45 @@ const useTimelinePagination = (
|
||||
}
|
||||
|
||||
if (alive()) {
|
||||
recalibratePagination(lTimelines);
|
||||
// Re-read linkedTimelines after the await: a sliding sync reset may have
|
||||
// replaced lTimelines[0] (via resetLiveTimeline) while pagination was in
|
||||
// flight, making the captured lTimelines stale. Using the fresh ref
|
||||
// ensures recalibratePagination rebuilds from the current live chain and
|
||||
// that countAfter/stillHasToken comparisons are meaningful.
|
||||
const freshLTimelines = timelineRef.current.linkedTimelines;
|
||||
recalibratePagination(freshLTimelines);
|
||||
(backwards ? setBackwardStatus : setForwardStatus)('idle');
|
||||
|
||||
const countAfter = getTimelinesEventsCount(getLinkedTimelines(lTimelines[0]));
|
||||
const countAfter = getTimelinesEventsCount(getLinkedTimelines(freshLTimelines[0]));
|
||||
const fetched = countAfter - countBefore;
|
||||
|
||||
if (fetched > 0 && fetched < 5) {
|
||||
const checkTimeline = backwards
|
||||
? freshLTimelines[0]
|
||||
: freshLTimelines[freshLTimelines.length - 1];
|
||||
const checkDirection = backwards ? Direction.Backward : Direction.Forward;
|
||||
const stillHasToken =
|
||||
typeof getLinkedTimelines(lTimelines[0])[0]?.getPaginationToken(
|
||||
Direction.Backward
|
||||
) === 'string';
|
||||
typeof getLinkedTimelines(checkTimeline)[0]?.getPaginationToken(checkDirection) ===
|
||||
'string';
|
||||
if (stillHasToken) {
|
||||
// Release lock so inner paginate can claim it, then mark continuing
|
||||
// so the finally block below does NOT reset it after inner claims.
|
||||
fetchingRef.current[directionKey] = false;
|
||||
continuing = true;
|
||||
paginate(backwards);
|
||||
// At this point the inner paginate has synchronously set
|
||||
// fetchingRef.current[directionKey] = true before hitting its own
|
||||
// await. The finally below will skip the reset.
|
||||
}
|
||||
}
|
||||
}
|
||||
} finally {
|
||||
fetchingRef.current[directionKey] = false;
|
||||
// Only release the lock if we did NOT hand it to a recursive continuation.
|
||||
// If `continuing` is true the recursive call owns the lock and will release
|
||||
// it in its own finally block.
|
||||
if (!continuing) {
|
||||
fetchingRef.current[directionKey] = false;
|
||||
}
|
||||
}
|
||||
};
|
||||
}, [mx, alive, setTimeline, limit, setBackwardStatus, setForwardStatus]);
|
||||
@@ -548,6 +575,24 @@ export function useTimelineSync({
|
||||
setTimeline({ linkedTimelines: getInitialTimeline(room).linkedTimelines });
|
||||
}, [eventId, room, timeline.linkedTimelines.length]);
|
||||
|
||||
// When navigating between rooms, reset the timeline state to the new room's
|
||||
// initial linked timelines. Without this, the component's timeline state
|
||||
// retains stale data from the previous room, causing liveTimelineLinked to be
|
||||
// false until a TimelineReset event fires. For revisited rooms with up-to-date
|
||||
// data (no initial:true in the sliding sync response), that event may never
|
||||
// arrive — leaving the initial-scroll guard permanently blocked and the room
|
||||
// invisible.
|
||||
const prevRoomIdRef = useRef(room.roomId);
|
||||
useEffect(() => {
|
||||
if (prevRoomIdRef.current === room.roomId) return;
|
||||
prevRoomIdRef.current = room.roomId;
|
||||
if (eventId) return;
|
||||
setTimeline({ linkedTimelines: getInitialTimeline(room).linkedTimelines });
|
||||
// Intentionally only depends on room: we want this to fire when the room
|
||||
// identity changes, not on every eventId change.
|
||||
// eslint-disable-next-line react-hooks/exhaustive-deps
|
||||
}, [room]);
|
||||
|
||||
return {
|
||||
timeline,
|
||||
setTimeline,
|
||||
|
||||
@@ -32,6 +32,7 @@ import { useOpenBugReportModal } from '$state/hooks/bugReportModal';
|
||||
import { createRoomEncryptionState } from '$components/create-room';
|
||||
import { parsePronounsInput } from '$utils/pronouns';
|
||||
import { sendFeedback } from '$utils/sendFeedbackToUser';
|
||||
import { PKitCommandMessageHandler } from '$plugins/pluralkit-handler/PKitCommandMessageHandler';
|
||||
import { useRoomNavigate } from './useRoomNavigate';
|
||||
import { enrichWidgetUrl } from './useRoomWidgets';
|
||||
import { useUserProfile } from './useUserProfile';
|
||||
@@ -50,6 +51,9 @@ const FLAG_PAT = String.raw`(?:^|\s)-(\w+)\b`;
|
||||
const FLAG_REG = new RegExp(FLAG_PAT);
|
||||
const FLAG_REG_G = new RegExp(FLAG_PAT, 'g');
|
||||
|
||||
const ADDPMP_REGEX = /(\S+) (name=)?"?([\w\s]*)"? (avatar=)?([\w.:/]+)/;
|
||||
const USEPMP_REGEX = /^(\S+)\s*(-g)?(-o)?(-u)?\s*(\d+)?$/;
|
||||
|
||||
export const splitPayloadContentAndFlags = (payload: string): [string, string | undefined] => {
|
||||
const flagMatch = new RegExp(FLAG_REG).exec(payload);
|
||||
|
||||
@@ -242,6 +246,7 @@ export enum Command {
|
||||
AddPerMessageProfileToAccount = 'addpmp',
|
||||
DeletePerMessageProfileFromAccount = 'delpmp',
|
||||
UsePerMessageProfile = 'usepmp',
|
||||
AssociateProxyPerMessageProfile = 'pmpproxy',
|
||||
Pronoun = 'pronoun',
|
||||
SPronoun = 'spronoun',
|
||||
Rainbow = 'rainbow',
|
||||
@@ -252,6 +257,7 @@ export enum Command {
|
||||
SetExt = 'setext',
|
||||
DelExt = 'delext',
|
||||
DiscardSession = 'discardsession',
|
||||
Html = 'html',
|
||||
// Cute Events
|
||||
Hug = 'hug',
|
||||
Cuddle = 'cuddle',
|
||||
@@ -280,6 +286,8 @@ export const useCommands = (mx: MatrixClient, room: Room): CommandRecord => {
|
||||
const { navigateRoom } = useRoomNavigate();
|
||||
const [developerTools] = useSetting(settingsAtom, 'developerTools');
|
||||
const [enableMSC4268CMD] = useSetting(settingsAtom, 'enableMSC4268CMD');
|
||||
// helper for pkit commands
|
||||
const pkitcmdHandler = useMemo(() => new PKitCommandMessageHandler(mx, room), [mx, room]);
|
||||
const profile = useUserProfile(mx.getSafeUserId());
|
||||
const openBugReport = useOpenBugReportModal();
|
||||
|
||||
@@ -493,26 +501,19 @@ export const useCommands = (mx: MatrixClient, room: Room): CommandRecord => {
|
||||
'Add or update a per message profile to your account. Example: /addpmp profileId name=Profile Name avatar=mxc://xyzabc',
|
||||
exe: async (payload) => {
|
||||
// Parse key=value pairs
|
||||
const parts = payload.split(' ');
|
||||
let avatarUrl: string | undefined;
|
||||
let name: string | undefined;
|
||||
parts.forEach((part, index) => {
|
||||
const [key, value] = part.split('=');
|
||||
if (key && value) {
|
||||
if (key === 'name' || key === 'avatar') {
|
||||
if (key === 'name') {
|
||||
name = parts
|
||||
.slice(index)
|
||||
.map((p) => p.split('=')[1])
|
||||
.join(' ');
|
||||
return;
|
||||
}
|
||||
if (key === 'avatar') avatarUrl = value;
|
||||
}
|
||||
}
|
||||
});
|
||||
const args = ADDPMP_REGEX.exec(payload);
|
||||
if (!args) {
|
||||
sendFeedback(`invalid payload`, room, mx.getSafeUserId());
|
||||
return;
|
||||
}
|
||||
const avatarUrl: string | undefined = args[5];
|
||||
const name: string | undefined = args[3];
|
||||
const profileId = args[1];
|
||||
|
||||
const profileId = parts[0]; // profileId is positional (before any key=)
|
||||
if (!avatarUrl || !name || !profileId) {
|
||||
sendFeedback(`invalid payload`, room, mx.getSafeUserId());
|
||||
return;
|
||||
}
|
||||
|
||||
const pmp: PerMessageProfile = {
|
||||
id: profileId,
|
||||
@@ -566,13 +567,28 @@ export const useCommands = (mx: MatrixClient, room: Room): CommandRecord => {
|
||||
[Command.UsePerMessageProfile]: {
|
||||
name: Command.UsePerMessageProfile,
|
||||
description:
|
||||
'Use a per message profile for this room once, or until reset. Example: /usepmp profileId [once,reset,or duration like 1h30m]',
|
||||
'Use a per message profile for this room once, or until reset. Example: /usepmp (profileId,reset) [-o,-u,-g] [ts]',
|
||||
exe: async (payload) => {
|
||||
// this command doesn't need to do anything, the composer will pick it up and apply the profile to the message being composed
|
||||
const profileId: string = splitWithSpace(payload)[0];
|
||||
const durationStr: string | undefined = splitWithSpace(payload)[1];
|
||||
let validUntil: number | undefined;
|
||||
if (durationStr === 'reset') {
|
||||
const args = USEPMP_REGEX.exec(payload);
|
||||
if (!args) {
|
||||
sendFeedback(`invalid payload`, room, mx.getSafeUserId());
|
||||
return;
|
||||
}
|
||||
const profileId = args[1];
|
||||
const globalFlag = args[2] !== undefined;
|
||||
const onceFlag = args[3] !== undefined;
|
||||
// const untilFlag = args[4] !== undefined;
|
||||
const validUntil = Number.parseInt(args[5], 10);
|
||||
if (onceFlag || globalFlag) {
|
||||
sendFeedback(
|
||||
'Currently not implemented, consider using shorthands, with /pmpproxy id ✨:text',
|
||||
room,
|
||||
mx.getSafeUserId()
|
||||
);
|
||||
return;
|
||||
}
|
||||
|
||||
if (profileId.normalize() === 'reset') {
|
||||
setCurrentlyUsedPerMessageProfileIdForRoom(mx, room.roomId, undefined, undefined, true)
|
||||
.then(() => {
|
||||
sendFeedback('Per message profile reset for this room.', room, mx.getSafeUserId());
|
||||
@@ -590,7 +606,7 @@ export const useCommands = (mx: MatrixClient, room: Room): CommandRecord => {
|
||||
.then(() => {
|
||||
sendFeedback(
|
||||
`Per message profile "${profileId}" will be used for messages in this room for the until ${
|
||||
durationStr ?? 'reset'
|
||||
validUntil ?? 'reset'
|
||||
}. Use \`/usepmp reset\` to reset it at any time.`,
|
||||
room,
|
||||
mx.getSafeUserId()
|
||||
@@ -605,6 +621,15 @@ export const useCommands = (mx: MatrixClient, room: Room): CommandRecord => {
|
||||
});
|
||||
},
|
||||
},
|
||||
[Command.AssociateProxyPerMessageProfile]: {
|
||||
name: Command.AssociateProxyPerMessageProfile,
|
||||
description: 'Associate proxy with a profile. Example /pmpproxy id ✨:text',
|
||||
exe: async (payload) => {
|
||||
const pid: string = splitWithSpace(payload)[0];
|
||||
const proxy: string = splitWithSpace(payload)[1];
|
||||
pkitcmdHandler.handleMessage(`pk;member "${pid}" proxy ${proxy}`, true);
|
||||
},
|
||||
},
|
||||
[Command.MyRoomAvatar]: {
|
||||
name: Command.MyRoomAvatar,
|
||||
description: 'Change profile picture in current room. Example /myroomavatar mxc://xyzabc',
|
||||
@@ -1323,6 +1348,26 @@ export const useCommands = (mx: MatrixClient, room: Room): CommandRecord => {
|
||||
}
|
||||
},
|
||||
},
|
||||
[Command.Html]: {
|
||||
name: Command.Html,
|
||||
description:
|
||||
'Send a message with HTML content. Example: /html <span data-mx-color="#ff0000">Red</span>',
|
||||
exe: async (payload) => {
|
||||
await mx.sendMessage(room.roomId, {
|
||||
msgtype: MsgType.Text,
|
||||
body: payload
|
||||
.replaceAll('<br>', '\n')
|
||||
.replaceAll('<li>', '\n- ')
|
||||
.replaceAll(
|
||||
/<a(.*?)href="(?<link>(.*?))"(.*?)>(?<text>(.*?))<\/a>/g,
|
||||
'[$<text>]($<link>)'
|
||||
)
|
||||
.replaceAll(/<[^>]*>/g, ''),
|
||||
format: 'org.matrix.custom.html',
|
||||
formatted_body: payload,
|
||||
});
|
||||
},
|
||||
},
|
||||
// Sharing E2EE History of a room with a user
|
||||
[Command.ShareE2EEHistory]: {
|
||||
name: Command.ShareE2EEHistory,
|
||||
@@ -1531,6 +1576,7 @@ export const useCommands = (mx: MatrixClient, room: Room): CommandRecord => {
|
||||
room,
|
||||
profile.displayName,
|
||||
profile.avatarUrl,
|
||||
pkitcmdHandler,
|
||||
developerTools,
|
||||
enableMSC4268CMD,
|
||||
openBugReport,
|
||||
|
||||
@@ -1,9 +1,10 @@
|
||||
import { ReactNode } from 'react';
|
||||
import { MouseEventHandler, useCallback, ReactNode } from 'react';
|
||||
import { IconSrc, Icons, Text } from 'folds';
|
||||
import { MatrixEvent, Room } from '$types/matrix-sdk';
|
||||
import { IMemberContent, Membership } from '$types/matrix/room';
|
||||
import { getMxIdLocalPart } from '$utils/matrix';
|
||||
import { isMembershipChanged } from '$utils/room';
|
||||
import { useOpenUserRoomProfile } from '$state/hooks/userRoomProfile';
|
||||
import { useSableCosmetics } from './useSableCosmetics';
|
||||
import { useMatrixClient } from './useMatrixClient';
|
||||
|
||||
@@ -17,8 +18,19 @@ function DecoratedUser({ roomId, userId, userName }: DecoratedUserProps) {
|
||||
const mx = useMatrixClient();
|
||||
const room = mx.getRoom(roomId);
|
||||
const { color, font } = useSableCosmetics(userId, room ?? ({} as Room));
|
||||
|
||||
const openUserRoomProfile = useOpenUserRoomProfile();
|
||||
const handleUserClick: MouseEventHandler = useCallback(
|
||||
(evt) => {
|
||||
evt.preventDefault();
|
||||
evt.stopPropagation();
|
||||
openUserRoomProfile(roomId, undefined, userId, evt.currentTarget.getBoundingClientRect());
|
||||
},
|
||||
[roomId, userId, openUserRoomProfile]
|
||||
);
|
||||
|
||||
return (
|
||||
<Text truncate>
|
||||
<Text as="a" onClick={handleUserClick} truncate>
|
||||
<b style={{ color, font }}>{userName ?? userId} </b>
|
||||
</Text>
|
||||
);
|
||||
|
||||
@@ -1,7 +1,8 @@
|
||||
import { AccountDataCompatVersion, AccountDataEvent } from '$types/matrix/accountData';
|
||||
import { PronounSet } from '$utils/pronouns';
|
||||
import { MatrixClient } from 'matrix-js-sdk';
|
||||
|
||||
const ACCOUNT_DATA_PREFIX = 'fyi.cisnt.permessageprofile';
|
||||
const ACCOUNT_DATA_PREFIX = AccountDataEvent.SablePerProfileMessageProfiles;
|
||||
|
||||
/**
|
||||
* a per message profile
|
||||
@@ -26,6 +27,7 @@ export type PerMessageProfile = {
|
||||
* @see PronounSet for the format of the pronouns, and how to parse them from a string input
|
||||
*/
|
||||
pronouns?: PronounSet[];
|
||||
compat?: AccountDataCompatVersion;
|
||||
};
|
||||
|
||||
/**
|
||||
@@ -104,6 +106,7 @@ type PerMessageProfileIndex = {
|
||||
* a list of all profile ids, used to list all profiles when the user wants to manage them.
|
||||
*/
|
||||
profileIds: string[];
|
||||
compat: AccountDataCompatVersion;
|
||||
};
|
||||
|
||||
/**
|
||||
@@ -114,6 +117,64 @@ type PerMessageProfileRoomAssociation = {
|
||||
validUntil?: number;
|
||||
};
|
||||
|
||||
/**
|
||||
* associating a profile by proxy
|
||||
* @author Rye
|
||||
*/
|
||||
export type PerMessageProfileProxyAssociation = {
|
||||
/**
|
||||
* the profile associated with the proxy
|
||||
*/
|
||||
profileId: string;
|
||||
/**
|
||||
* regex (string representation of it) to handle the proxy
|
||||
*/
|
||||
regexString: string;
|
||||
/**
|
||||
* optional parameter to save when the proxy was added
|
||||
*/
|
||||
setAt?: number;
|
||||
};
|
||||
|
||||
export type InternalPerMessageProfileProxyAssociation = {
|
||||
/**
|
||||
* the profile associated with the proxy
|
||||
*/
|
||||
profileId: string;
|
||||
/**
|
||||
* regex to handle the proxy
|
||||
*/
|
||||
regex: RegExp;
|
||||
/**
|
||||
* optional parameter to save when the proxy was added
|
||||
*/
|
||||
setAt?: number;
|
||||
};
|
||||
|
||||
export function parsePerMessageProfileProxyAssociation(
|
||||
assoc: PerMessageProfileProxyAssociation
|
||||
): InternalPerMessageProfileProxyAssociation {
|
||||
return {
|
||||
profileId: assoc.profileId,
|
||||
// we need to remove artifacts from the toString conversion
|
||||
regex: new RegExp(assoc.regexString.slice(1, -1)),
|
||||
setAt: assoc.setAt,
|
||||
} satisfies InternalPerMessageProfileProxyAssociation;
|
||||
}
|
||||
|
||||
type PerMessageProfileProxyAssociationWrapper = {
|
||||
/**
|
||||
* the associations saved in the wrapper
|
||||
*/
|
||||
associations:
|
||||
| Map<string, PerMessageProfileProxyAssociation>
|
||||
| Record<string, PerMessageProfileProxyAssociation>;
|
||||
/**
|
||||
* optional parameter to save compatibility information
|
||||
*/
|
||||
compat?: AccountDataCompatVersion;
|
||||
};
|
||||
|
||||
/**
|
||||
* the shape of the account data for room associations, which is a wrapper around a list of associations.
|
||||
* This is used to store the associations in account data, and allows us to easily add additional fields in the future if needed without breaking the existing data structure.
|
||||
@@ -128,9 +189,14 @@ type PerMessageProfileRoomAssociationWrapper = {
|
||||
associations:
|
||||
| Map<string, PerMessageProfileRoomAssociation>
|
||||
| Record<string, PerMessageProfileRoomAssociation>;
|
||||
compat?: AccountDataCompatVersion;
|
||||
};
|
||||
|
||||
// Helper to always get a Map from wrapper
|
||||
/**
|
||||
* unwrap a profile-room-associations-wrapper
|
||||
* @param wrapper the wrapper to unwrap
|
||||
* @returns unwrapped map for profile-room-associations
|
||||
*/
|
||||
function getAssociationsMap(
|
||||
wrapper?: PerMessageProfileRoomAssociationWrapper
|
||||
): Map<string, PerMessageProfileRoomAssociation> {
|
||||
@@ -146,6 +212,33 @@ function associationsMapToObject(
|
||||
return Object.fromEntries(map);
|
||||
}
|
||||
|
||||
/**
|
||||
* helper function (similar to getAssociationsMap for Room associations)
|
||||
* @param wrapper the wrapper to unwrap
|
||||
* @returns unwrapped map of proxy associations
|
||||
*/
|
||||
function getProxyAssociationMap(
|
||||
wrapper?: PerMessageProfileProxyAssociationWrapper
|
||||
): Map<string, PerMessageProfileProxyAssociation> {
|
||||
if (!wrapper?.associations) return new Map();
|
||||
if (wrapper.associations instanceof Map) return wrapper.associations;
|
||||
return new Map(Object.entries(wrapper.associations));
|
||||
}
|
||||
|
||||
function proxyAssociationsMapToObject(
|
||||
map: Map<string, PerMessageProfileProxyAssociation>
|
||||
): Record<string, PerMessageProfileProxyAssociation> {
|
||||
return Object.fromEntries(map);
|
||||
}
|
||||
|
||||
/**
|
||||
* getting a profile from the account data where the profile matches a given id
|
||||
*
|
||||
* @export
|
||||
* @param {MatrixClient} mx the matrix client
|
||||
* @param {string} id the profile id
|
||||
* @return {*} {(Promise<PerMessageProfile | undefined>)} the profile, with the profile Id, if it exists
|
||||
*/
|
||||
export async function getPerMessageProfileById(
|
||||
mx: MatrixClient,
|
||||
id: string
|
||||
@@ -154,6 +247,13 @@ export async function getPerMessageProfileById(
|
||||
return profile ? (profile.getContent() as unknown as PerMessageProfile) : undefined;
|
||||
}
|
||||
|
||||
/**
|
||||
* getting an array of all PerMessageProfile's saved in the account data
|
||||
*
|
||||
* @export
|
||||
* @param {MatrixClient} mx the matrix client
|
||||
* @return {*} {Promise<PerMessageProfile[]>} a array containing all per-message-profiles saved
|
||||
*/
|
||||
export async function getAllPerMessageProfiles(mx: MatrixClient): Promise<PerMessageProfile[]> {
|
||||
const profileData = mx.getAccountData(`${ACCOUNT_DATA_PREFIX}.index` as any);
|
||||
const profileIds = (profileData?.getContent() as PerMessageProfileIndex)?.profileIds || [];
|
||||
@@ -161,17 +261,33 @@ export async function getAllPerMessageProfiles(mx: MatrixClient): Promise<PerMes
|
||||
return profiles.filter((profile): profile is PerMessageProfile => profile !== undefined);
|
||||
}
|
||||
|
||||
/**
|
||||
* add or update a pmp
|
||||
* @param mx the matrix client
|
||||
* @param profile the profile to add/update
|
||||
* @returns void
|
||||
*/
|
||||
export function addOrUpdatePerMessageProfile(mx: MatrixClient, profile: PerMessageProfile) {
|
||||
const profileListIndex = mx.getAccountData(`${ACCOUNT_DATA_PREFIX}.index` as any);
|
||||
const profileWithCompat = {
|
||||
...profile,
|
||||
compat: {
|
||||
version: 1,
|
||||
compatDate: '2026-03-26',
|
||||
} satisfies AccountDataCompatVersion,
|
||||
} satisfies PerMessageProfile;
|
||||
if (profileListIndex?.getContent()?.profileIds.includes(profile.id)) {
|
||||
// profile already exists, just update it
|
||||
return mx.setAccountData(`${ACCOUNT_DATA_PREFIX}.${profile.id}` as any, profile as any);
|
||||
return mx.setAccountData(
|
||||
`${ACCOUNT_DATA_PREFIX}.${profile.id}` as any,
|
||||
profileWithCompat as any
|
||||
);
|
||||
}
|
||||
// profile doesn't exist, add it to the index and then add the profile data
|
||||
const newProfileIds = [...(profileListIndex?.getContent()?.profileIds || []), profile.id];
|
||||
return Promise.all([
|
||||
mx.setAccountData(`${ACCOUNT_DATA_PREFIX}.index` as any, { profileIds: newProfileIds } as any),
|
||||
mx.setAccountData(`${ACCOUNT_DATA_PREFIX}.${profile.id}` as any, profile as any),
|
||||
mx.setAccountData(`${ACCOUNT_DATA_PREFIX}.${profile.id}` as any, profileWithCompat as any),
|
||||
]);
|
||||
}
|
||||
|
||||
@@ -243,6 +359,89 @@ export async function setCurrentlyUsedPerMessageProfileIdForRoom(
|
||||
}
|
||||
|
||||
/**
|
||||
*
|
||||
* @param mx the matrix client
|
||||
* @param profileId the profile id which the prefix should be attached to
|
||||
* @param proxy the prefix to use as index
|
||||
* @param proxyRegExp the regex we can use to match the prefix
|
||||
* @param reset wheather to delete the prefix
|
||||
*/
|
||||
export async function associateProxyWithProfile(
|
||||
mx: MatrixClient,
|
||||
profileId: string | undefined,
|
||||
proxy: string,
|
||||
proxyRegExp: RegExp,
|
||||
reset: boolean
|
||||
) {
|
||||
const associations = getProxyAssociationMap(
|
||||
mx.getAccountData(`${ACCOUNT_DATA_PREFIX}.proxyassociation` as any)?.getContent()
|
||||
);
|
||||
|
||||
if (reset) associations.delete(proxy);
|
||||
|
||||
if (!profileId) throw new Error('profileId might not be undefined');
|
||||
if (profileId)
|
||||
associations.set(proxy, {
|
||||
profileId,
|
||||
regexString: proxyRegExp.toString(),
|
||||
} satisfies PerMessageProfileProxyAssociation);
|
||||
mx.setAccountData(
|
||||
`${ACCOUNT_DATA_PREFIX}.proxyassociation` as any,
|
||||
{ associations: proxyAssociationsMapToObject(associations) } as any
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* get a profile based on a proxy
|
||||
* @param mx the matrix client
|
||||
* @param proxy the proxy to look for
|
||||
* @returns the profile, if any, associated with the prefix
|
||||
*/
|
||||
export async function getProfileAssociatedWithProxy(
|
||||
mx: MatrixClient,
|
||||
proxy: string
|
||||
): Promise<PerMessageProfile | undefined> {
|
||||
const profileId = getAssociationsMap(
|
||||
mx.getAccountData(`${ACCOUNT_DATA_PREFIX}.proxyassociation` as any)?.getContent()
|
||||
).get(proxy)?.profileId;
|
||||
if (!profileId) return undefined;
|
||||
return getPerMessageProfileById(mx, profileId);
|
||||
}
|
||||
|
||||
/**
|
||||
*
|
||||
*
|
||||
* @export
|
||||
* @param {MatrixClient} mx the matrix client
|
||||
* @return {*} {Promise<PerMessageProfileProxyAssociation[]>}
|
||||
*/
|
||||
export async function getAllPerMessageProfileProxies(
|
||||
mx: MatrixClient
|
||||
): Promise<PerMessageProfileProxyAssociation[]> {
|
||||
const cont: PerMessageProfileProxyAssociationWrapper | undefined = mx
|
||||
.getAccountData(`${ACCOUNT_DATA_PREFIX}.proxyassociation` as any)
|
||||
?.getContent();
|
||||
if (!cont) return [];
|
||||
const pmap = getProxyAssociationMap(cont);
|
||||
const parr = new Array<PerMessageProfileProxyAssociation>();
|
||||
pmap.values().forEach((v) => parr.push(v));
|
||||
return parr;
|
||||
}
|
||||
|
||||
export async function dropProxyAssociationForPMP(mx: MatrixClient, proxy: string) {
|
||||
const associations = getProxyAssociationMap(
|
||||
mx.getAccountData(`${ACCOUNT_DATA_PREFIX}.proxyassociation` as any)?.getContent()
|
||||
);
|
||||
if (!associations) return;
|
||||
associations.delete(proxy);
|
||||
mx.setAccountData(
|
||||
`${ACCOUNT_DATA_PREFIX}.proxyassociation` as any,
|
||||
{ associations: proxyAssociationsMapToObject(associations) } as any
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
*
|
||||
* drops all room associations for a profile, used when deleting a profile to make sure there are no dangling associations left that point to a non existing profile, which could cause issues when trying to apply the profile to a message in a room that still has an association for the deleted profile.
|
||||
*
|
||||
* @param {MatrixClient} mx the matrix client
|
||||
|
||||
@@ -24,16 +24,7 @@ export const useSlidingSyncActiveRoom = (): void => {
|
||||
const manager = getSlidingSyncManager(mx);
|
||||
if (!manager) return undefined;
|
||||
|
||||
// Wait for the room to be initialized from list sync before subscribing
|
||||
// with the full timeline limit. This prevents timeline ordering issues where
|
||||
// the room might be receiving events from list expansion while we're also
|
||||
// trying to load a large timeline, causing events to be added out of order.
|
||||
const timeoutId = setTimeout(() => {
|
||||
manager.subscribeToRoom(roomId);
|
||||
}, 100);
|
||||
|
||||
return () => {
|
||||
clearTimeout(timeoutId);
|
||||
};
|
||||
manager.subscribeToRoom(roomId);
|
||||
return undefined;
|
||||
}, [mx, roomId]);
|
||||
};
|
||||
@@ -7,10 +7,15 @@ import colorMXID from '$utils/colorMXID';
|
||||
import { profilesCacheAtom } from '$state/userRoomProfile';
|
||||
import { useSetting } from '$state/hooks/settings';
|
||||
import { settingsAtom } from '$state/settings';
|
||||
import { MSC1767Text } from '$types/matrix/common';
|
||||
import { useMatrixClient } from './useMatrixClient';
|
||||
|
||||
const inFlightProfiles = new Map<string, Promise<any>>();
|
||||
|
||||
export type MSC4440Bio = {
|
||||
'm.text': Array<MSC1767Text>;
|
||||
};
|
||||
|
||||
export type UserProfile = {
|
||||
avatarUrl?: string;
|
||||
displayName?: string;
|
||||
@@ -27,6 +32,7 @@ export type UserProfile = {
|
||||
};
|
||||
|
||||
const normalizeInfo = (info: any): UserProfile => {
|
||||
const msc4440Bio = info['gay.fomx.biography'] as MSC4440Bio | undefined;
|
||||
const knownKeys = new Set([
|
||||
'avatar_url',
|
||||
'displayname',
|
||||
@@ -35,6 +41,7 @@ const normalizeInfo = (info: any): UserProfile => {
|
||||
'm.tz',
|
||||
'moe.sable.app.bio',
|
||||
'chat.commet.profile_bio',
|
||||
'gay.fomx.biography',
|
||||
'chat.commet.profile_banner',
|
||||
'chat.commet.profile_status',
|
||||
'moe.sable.app.name_color',
|
||||
@@ -54,7 +61,10 @@ const normalizeInfo = (info: any): UserProfile => {
|
||||
displayName: info.displayname,
|
||||
pronouns: info['io.fsky.nyx.pronouns'],
|
||||
timezone: info['us.cloke.msc4175.tz'] || info['m.tz'],
|
||||
bio: info['moe.sable.app.bio'] || info['chat.commet.profile_bio'],
|
||||
bio:
|
||||
msc4440Bio?.['m.text']?.[0]?.body ||
|
||||
info['moe.sable.app.bio'] ||
|
||||
info['chat.commet.profile_bio'],
|
||||
status: info['chat.commet.profile_status'],
|
||||
bannerUrl: info['chat.commet.profile_banner'],
|
||||
nameColor: info['moe.sable.app.name_color'],
|
||||
@@ -94,7 +104,10 @@ export const useUserProfile = (
|
||||
const cached = useAtomValue(userSelector);
|
||||
const setGlobalProfiles = useSetAtom(profilesCacheAtom);
|
||||
|
||||
const needsFetch = !!userId && userId !== 'undefined' && !cached?._fetched;
|
||||
const hasOnlyFetchedMarker =
|
||||
cached?._fetched === true && Object.keys(cached ?? {}).every((key) => key === '_fetched');
|
||||
const needsFetch =
|
||||
!!userId && userId !== 'undefined' && (!cached?._fetched || hasOnlyFetchedMarker);
|
||||
|
||||
useEffect(() => {
|
||||
if (!needsFetch) return undefined;
|
||||
|
||||
@@ -0,0 +1,249 @@
|
||||
import {
|
||||
addOrUpdatePerMessageProfile,
|
||||
associateProxyWithProfile,
|
||||
dropProxyAssociationForPMP,
|
||||
getAllPerMessageProfiles,
|
||||
getPerMessageProfileById,
|
||||
PerMessageProfile,
|
||||
} from '$hooks/usePerMessageProfile';
|
||||
import { sendFeedback } from '$utils/sendFeedbackToUser';
|
||||
import { MatrixClient, Room } from 'matrix-js-sdk';
|
||||
import { generateShortId } from '$utils/shortIdGen';
|
||||
|
||||
const pkMemberRenameRegex = /^(pk;member)\s+"?([\w\s]+)"?\s*rename\s+"?([\w\s]+)"?$/;
|
||||
const pkMemberNewRegex = /^(pk;member)\s+new\s+"?([\w\s]+)"?$/;
|
||||
const pkMemberNewProxy = /^(pk;member)\s+"?([\w\s]+)"?\s+proxy(\s+add)?\s+(.*text.*)$/;
|
||||
const pkMemberRemoveProxy = /^(pk;member)\s+"?([\w\s]+)"?\s+proxy\s+remove\s+(.*text.*)$/;
|
||||
|
||||
const helpTextPkMemberNew = 'To create a new persona: pk;member new Yumi';
|
||||
const helpTextPkMemberRename = 'To rename a persona: pk;member "Rain Deer" rename "Micky Mouse"';
|
||||
const helpTextPkMemberNewProxy = 'To add a shorthand to a persona: pk;member Yumi proxy [text]';
|
||||
const helpTextPkMemberRemoveProxy =
|
||||
'To remove a shorthand from a persona: pk;member Yumi proxy remove [text]';
|
||||
const helpTextPkMember = `Available 'pk;member' commands:\n${helpTextPkMemberNew}\n${helpTextPkMemberRename}\n${helpTextPkMemberNewProxy}\n${helpTextPkMemberRemoveProxy}`;
|
||||
|
||||
function regexEscapeFallBackFunc(template: string): string {
|
||||
return template.replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
|
||||
}
|
||||
|
||||
/**
|
||||
* build a regex to recognize proxies
|
||||
* a template can be for example `[text]` or `f:text`
|
||||
*
|
||||
* @param {string} template
|
||||
* @return {*} {RegExp}
|
||||
*/
|
||||
function buildRegex(template: string): RegExp {
|
||||
const [before, after] = template.split('text');
|
||||
// RegExp.escape is baseline since May 2025
|
||||
// @ts-ignore TS2322
|
||||
const escape = RegExp.escape ?? regexEscapeFallBackFunc;
|
||||
const pattern = `${escape(before)}(.+)${escape(after)}`;
|
||||
return new RegExp(`^${pattern}$`);
|
||||
}
|
||||
|
||||
/**
|
||||
* a class to use as PluralKit command message handler
|
||||
*
|
||||
* @export
|
||||
* @class PluralKitCommandMessageHandler
|
||||
* @author Rye
|
||||
*/
|
||||
export class PKitCommandMessageHandler {
|
||||
/**
|
||||
* the matrix client we use, is set in the constructor
|
||||
*
|
||||
* @private
|
||||
* @type {MatrixClient}
|
||||
* @memberof PKitCommandMessageHandler
|
||||
*/
|
||||
private readonly mx: MatrixClient;
|
||||
|
||||
private message = '';
|
||||
|
||||
private readonly room: Room;
|
||||
|
||||
/**
|
||||
* flag to interpret the name given as id
|
||||
*
|
||||
* @private
|
||||
* @type {boolean}
|
||||
* @memberof PKitCommandMessageHandler
|
||||
*/
|
||||
private useIdInsteadOfNameWherePossible: boolean;
|
||||
|
||||
public constructor(mx: MatrixClient, room: Room) {
|
||||
this.mx = mx;
|
||||
this.room = room;
|
||||
this.useIdInsteadOfNameWherePossible = false;
|
||||
}
|
||||
|
||||
/**
|
||||
* Handler for `pk;member` commands
|
||||
* @async
|
||||
*/
|
||||
private async memberHandler() {
|
||||
if (this.message.match(pkMemberNewRegex)) {
|
||||
// adding a new member
|
||||
const cmdParts = pkMemberNewRegex.exec(this.message);
|
||||
if (!cmdParts) {
|
||||
sendFeedback(`malformed input, ${helpTextPkMemberNew}`, this.room, this.mx.getSafeUserId());
|
||||
return;
|
||||
}
|
||||
const memberName = cmdParts[2];
|
||||
const generatedID = generateShortId(5);
|
||||
sendFeedback(
|
||||
`adding new member has been created with id: ${generatedID} and name ${memberName}`,
|
||||
this.room,
|
||||
this.mx.getSafeUserId()
|
||||
);
|
||||
addOrUpdatePerMessageProfile(this.mx, { id: generatedID, name: memberName });
|
||||
sendFeedback(
|
||||
`added new member has been created with id: ${generatedID} and name ${memberName}`,
|
||||
this.room,
|
||||
this.mx.getSafeUserId()
|
||||
);
|
||||
} else if (this.message.match(pkMemberRenameRegex)) {
|
||||
// renaming a profile based on the name
|
||||
const cmdParts = pkMemberRenameRegex.exec(this.message);
|
||||
if (!cmdParts) {
|
||||
sendFeedback(
|
||||
`malformed input, ${helpTextPkMemberRename}`,
|
||||
this.room,
|
||||
this.mx.getSafeUserId()
|
||||
);
|
||||
return;
|
||||
}
|
||||
// extract from the cmd the old and the new name
|
||||
/**
|
||||
* The old name we want to search for in our records, is in capture group 2
|
||||
*/
|
||||
const oldName = cmdParts[2];
|
||||
/**
|
||||
* The new name we want to set is in capture group 3
|
||||
*/
|
||||
const newName = cmdParts[3];
|
||||
/**
|
||||
* The id of the per-message-profile
|
||||
*/
|
||||
const pmpId = (await getAllPerMessageProfiles(this.mx)).find(
|
||||
(pmp) => pmp.name === oldName
|
||||
)?.id;
|
||||
if (!pmpId) {
|
||||
sendFeedback(
|
||||
`Persona with name "${oldName}" doesn't exist in your records, ${helpTextPkMemberNew}`,
|
||||
this.room,
|
||||
this.mx.getSafeUserId()
|
||||
);
|
||||
return;
|
||||
}
|
||||
/**
|
||||
* get the persona record we already have for the id
|
||||
*/
|
||||
const pmp = await getPerMessageProfileById(this.mx, pmpId);
|
||||
if (!pmp) {
|
||||
sendFeedback(
|
||||
"Persona record can't be retrieved, data might be corrupted",
|
||||
this.room,
|
||||
this.mx.getSafeUserId()
|
||||
);
|
||||
return;
|
||||
}
|
||||
// actually change the name
|
||||
pmp.name = newName;
|
||||
sendFeedback(
|
||||
`renaming your profile ${pmpId} from ${oldName} to ${newName}`,
|
||||
this.room,
|
||||
this.mx.getSafeUserId()
|
||||
);
|
||||
addOrUpdatePerMessageProfile(this.mx, pmp);
|
||||
} else if (pkMemberRemoveProxy.test(this.message)) {
|
||||
const cmdParts = pkMemberRemoveProxy.exec(this.message);
|
||||
if (!cmdParts) return;
|
||||
const name = cmdParts[2];
|
||||
const matchAgainst = cmdParts[3];
|
||||
const pmpId = this.useIdInsteadOfNameWherePossible
|
||||
? name
|
||||
: (await getAllPerMessageProfiles(this.mx)).find((pmp) => pmp.name === name)?.id;
|
||||
if (!pmpId) {
|
||||
sendFeedback(
|
||||
`Persona with ${this.useIdInsteadOfNameWherePossible ? 'id' : 'name'} "${name}" doesn't exist in your records, ${helpTextPkMemberNew}`,
|
||||
this.room,
|
||||
this.mx.getSafeUserId()
|
||||
);
|
||||
return;
|
||||
}
|
||||
|
||||
dropProxyAssociationForPMP(this.mx, matchAgainst);
|
||||
|
||||
sendFeedback(
|
||||
`Persona with ${this.useIdInsteadOfNameWherePossible ? 'id' : 'name'} "${name}" (${pmpId}) is now no longer associated with ${matchAgainst}`,
|
||||
this.room,
|
||||
this.mx.getSafeUserId()
|
||||
);
|
||||
} else if (pkMemberNewProxy.test(this.message)) {
|
||||
const cmdParts = pkMemberNewProxy.exec(this.message);
|
||||
if (!cmdParts) return;
|
||||
const name = cmdParts[2];
|
||||
const matchAgainst = cmdParts[4];
|
||||
const pmpId = this.useIdInsteadOfNameWherePossible
|
||||
? name
|
||||
: (await getAllPerMessageProfiles(this.mx)).find((pmp) => pmp.name === name)?.id;
|
||||
if (!pmpId) {
|
||||
sendFeedback(
|
||||
`Persona with ${this.useIdInsteadOfNameWherePossible ? 'id' : 'name'} "${name}" doesn't exist in your records, ${helpTextPkMemberNew}`,
|
||||
this.room,
|
||||
this.mx.getSafeUserId()
|
||||
);
|
||||
return;
|
||||
}
|
||||
const matchAgainstRegExp = buildRegex(matchAgainst);
|
||||
associateProxyWithProfile(this.mx, pmpId, matchAgainst, matchAgainstRegExp, false);
|
||||
sendFeedback(
|
||||
`Persona with ${this.useIdInsteadOfNameWherePossible ? 'id' : 'name'} "${name}" (${pmpId}) is now associated with ${matchAgainst}`,
|
||||
this.room,
|
||||
this.mx.getSafeUserId()
|
||||
);
|
||||
} else {
|
||||
// default to looking up member info
|
||||
const listOfProfiles: PerMessageProfile[] = await getAllPerMessageProfiles(this.mx);
|
||||
const stringListOfProfiles: string = listOfProfiles
|
||||
.map((pmp: PerMessageProfile) => `${pmp.id}: ${pmp.name ? pmp.name : '(empty name)'}`)
|
||||
.join('\n');
|
||||
sendFeedback(
|
||||
`If you see this, you have messed up a command\n\nYou currently have the following persona set up:\n${stringListOfProfiles}\n\n${helpTextPkMember}`,
|
||||
this.room,
|
||||
this.mx.getSafeUserId()
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* check if a message is a pluralkit-style command
|
||||
* @param message the message to check
|
||||
* @returns true if it's a pluralkit style command
|
||||
*/
|
||||
public static isPKCommand(message: string): boolean {
|
||||
return message.startsWith('pk;');
|
||||
}
|
||||
|
||||
/**
|
||||
* handle a message, which might be a pk command
|
||||
* @param message the message we want to handle
|
||||
* @returns void
|
||||
*/
|
||||
public async handleMessage(message: string, useId?: boolean): Promise<void> {
|
||||
this.message = message;
|
||||
this.useIdInsteadOfNameWherePossible = useId ?? false;
|
||||
if (!this.message.startsWith('pk;')) return;
|
||||
if (this.message.startsWith('pk;member')) {
|
||||
await this.memberHandler();
|
||||
return;
|
||||
}
|
||||
sendFeedback(
|
||||
`Command currently not supported, right now compatibility is limited and only a subset of pk;member is supported\n\n${helpTextPkMember}`,
|
||||
this.room,
|
||||
this.mx.getSafeUserId()
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,98 @@
|
||||
import {
|
||||
getAllPerMessageProfileProxies,
|
||||
getPerMessageProfileById,
|
||||
InternalPerMessageProfileProxyAssociation,
|
||||
parsePerMessageProfileProxyAssociation,
|
||||
PerMessageProfile,
|
||||
} from '$hooks/usePerMessageProfile';
|
||||
import { MatrixClient } from 'matrix-js-sdk';
|
||||
|
||||
/**
|
||||
* proxy message handler
|
||||
* @author Rye
|
||||
*/
|
||||
export class PKitProxyMessageHandler {
|
||||
/**
|
||||
* the matrix client we use, we init that in the constructor
|
||||
*
|
||||
* @private
|
||||
* @type {MatrixClient}
|
||||
* @memberof PKitProxyMessageHandler
|
||||
*/
|
||||
private readonly mx: MatrixClient;
|
||||
|
||||
/**
|
||||
* a list of proxies; is not initialized in the constructor
|
||||
* @private
|
||||
* @type {PerMessageProfileProxyAssociation[]}
|
||||
* @memberof PKitProxyMessageHandler
|
||||
*/
|
||||
private proxiesAssocs: InternalPerMessageProfileProxyAssociation[];
|
||||
|
||||
private succInit: boolean;
|
||||
|
||||
/**
|
||||
* a pk proxy message handler
|
||||
* @param mx the matrix client
|
||||
*/
|
||||
public constructor(mx: MatrixClient) {
|
||||
this.mx = mx;
|
||||
this.proxiesAssocs = [];
|
||||
this.succInit = false;
|
||||
}
|
||||
|
||||
/**
|
||||
* initialize the handler, as this is not necessarily fast, it shouldn't happen in the constructor
|
||||
*/
|
||||
public async init(): Promise<void> {
|
||||
try {
|
||||
this.proxiesAssocs = (await getAllPerMessageProfileProxies(this.mx)).map((p) =>
|
||||
parsePerMessageProfileProxyAssociation(p)
|
||||
);
|
||||
this.succInit = true;
|
||||
} catch (err) {
|
||||
this.succInit = false;
|
||||
throw new Error(`failed to init pmp proxy handler: ${String(err)}`);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* you should probably check this before running `getPmpBasedOnMessage`, as this is faster
|
||||
* @param message the message to check
|
||||
*/
|
||||
public isAProxiedMessage(message: string): boolean {
|
||||
if (!this.succInit) throw new Error('PK proxy message handler is not initialized');
|
||||
return this.proxiesAssocs.some((assoc) => assoc.regex.test(message));
|
||||
}
|
||||
|
||||
/**
|
||||
* get PmP based on message
|
||||
* @param message the message to look at
|
||||
* @returns the matching Per-Message-Profile, if any
|
||||
*/
|
||||
public async getPmpBasedOnMessage(message: string): Promise<PerMessageProfile | undefined> {
|
||||
if (!this.succInit) await this.init();
|
||||
// check if the message matches our formats
|
||||
// maybe a bit unsafe, as we are evaluating regex that aren't necessarily by us, could be _maybe_ manipulated
|
||||
const profileId = this.proxiesAssocs.find((assoc) => assoc.regex.test(message))?.profileId;
|
||||
if (!profileId) return undefined;
|
||||
return getPerMessageProfileById(this.mx, profileId);
|
||||
}
|
||||
|
||||
/**
|
||||
* this runs synchronously, so it needs to be inited beforehand
|
||||
*
|
||||
* @param {string} message the message you want to extract from
|
||||
* @return {*} {(string | undefined)} the message without the proxy
|
||||
* @memberof PKitProxyMessageHandler
|
||||
*/
|
||||
public stripProxyFromMessage(message: string): string | undefined {
|
||||
if (!this.succInit) throw new Error('PK proxy message handler is not initialized');
|
||||
let m;
|
||||
this.proxiesAssocs.forEach((assoc) => {
|
||||
const match = assoc.regex.exec(message);
|
||||
if (match?.at(1)) m = match.at(1);
|
||||
});
|
||||
return m;
|
||||
}
|
||||
}
|
||||
@@ -2,7 +2,7 @@ import { render, screen } from '@testing-library/react';
|
||||
import parse from 'html-react-parser';
|
||||
import { afterEach, describe, expect, it, vi } from 'vitest';
|
||||
import * as css from '$styles/CustomHtml.css';
|
||||
|
||||
import { sanitizeCustomHtml } from '$utils/sanitize';
|
||||
import { getReactCustomHtmlParser, LINKIFY_OPTS } from './react-custom-html-parser';
|
||||
|
||||
const { CodeHighlightRenderer } = vi.hoisted(() => ({
|
||||
@@ -31,24 +31,36 @@ vi.mock('$components/code-highlight', () => ({
|
||||
CodeHighlightRenderer,
|
||||
}));
|
||||
|
||||
function createMatrixClient() {
|
||||
return {
|
||||
getRoom: () => undefined,
|
||||
getUserId: () => '@me:example.com',
|
||||
mxcUrlToHttp: () => null,
|
||||
} as any;
|
||||
}
|
||||
|
||||
function renderParsedHtml(
|
||||
html: string,
|
||||
options: {
|
||||
sanitize?: boolean;
|
||||
mx?: any;
|
||||
} = {}
|
||||
) {
|
||||
const { sanitize = true, mx = createMatrixClient() } = options;
|
||||
const parserOptions = getReactCustomHtmlParser(mx, '!room:example.com', {
|
||||
linkifyOpts: LINKIFY_OPTS,
|
||||
});
|
||||
|
||||
return render(<div>{parse(sanitize ? sanitizeCustomHtml(html) : html, parserOptions)}</div>);
|
||||
}
|
||||
|
||||
const renderMessage = (html: string) => renderParsedHtml(html, { sanitize: false });
|
||||
|
||||
afterEach(() => {
|
||||
vi.clearAllMocks();
|
||||
vi.restoreAllMocks();
|
||||
});
|
||||
|
||||
const mx = {} as never;
|
||||
|
||||
const renderMessage = (html: string) =>
|
||||
render(
|
||||
<>
|
||||
{parse(
|
||||
html,
|
||||
getReactCustomHtmlParser(mx, undefined, {
|
||||
linkifyOpts: LINKIFY_OPTS,
|
||||
})
|
||||
)}
|
||||
</>
|
||||
);
|
||||
|
||||
describe('getReactCustomHtmlParser code blocks', () => {
|
||||
it('renders the Arborium renderer inside the existing code block shell for explicit data-lang metadata', () => {
|
||||
const { container } = renderMessage(
|
||||
@@ -109,3 +121,56 @@ describe('getReactCustomHtmlParser code blocks', () => {
|
||||
expect(shell).toHaveAttribute('data-language', 'ts');
|
||||
});
|
||||
});
|
||||
|
||||
describe('getReactCustomHtmlParser', () => {
|
||||
it('translates Matrix color data attributes into rendered styles', () => {
|
||||
renderParsedHtml('<span data-mx-color="#ff0000" data-mx-bg-color="#00ff00">colored</span>');
|
||||
|
||||
expect(screen.getByText('colored')).toHaveStyle({
|
||||
color: 'rgb(255, 0, 0)',
|
||||
backgroundColor: 'rgb(0, 255, 0)',
|
||||
});
|
||||
});
|
||||
|
||||
it('drops incoming style attributes even if unsanitized html reaches the parser', () => {
|
||||
renderParsedHtml(
|
||||
'<span style="background-color:#00ff00" data-mx-color="#ff0000">styled</span>',
|
||||
{ sanitize: false }
|
||||
);
|
||||
|
||||
const styled = screen.getByText('styled');
|
||||
|
||||
expect(styled).toHaveStyle({
|
||||
color: 'rgb(255, 0, 0)',
|
||||
});
|
||||
expect(styled).not.toHaveStyle({
|
||||
backgroundColor: 'rgb(0, 255, 0)',
|
||||
});
|
||||
});
|
||||
|
||||
it('renders a readable fallback for unresolved legacy emote MXC images', () => {
|
||||
const { container } = renderParsedHtml(
|
||||
'<img data-mx-emoticon src="mxc://example.org/emote" alt="blobcat" title="blobcat" height="32" />'
|
||||
);
|
||||
|
||||
expect(screen.getByText(':blobcat:')).toBeInTheDocument();
|
||||
expect(container.querySelector('img[src^="mxc://"]')).toBeNull();
|
||||
});
|
||||
|
||||
it('renders a readable fallback for unresolved non-emote MXC images', () => {
|
||||
const { container } = renderParsedHtml(
|
||||
'<img src="mxc://example.org/image" alt="media" title="media" />'
|
||||
);
|
||||
|
||||
expect(screen.getByText('media')).toBeInTheDocument();
|
||||
expect(container.querySelector('img[src^="mxc://"]')).toBeNull();
|
||||
});
|
||||
|
||||
it('renders unresolved MXC fallbacks without emitting debug logs', () => {
|
||||
const logSpy = vi.spyOn(console, 'warn').mockImplementation(() => undefined);
|
||||
|
||||
renderParsedHtml('<img src="mxc://example.org/image" alt="media" title="media" />');
|
||||
|
||||
expect(logSpy).not.toHaveBeenCalled();
|
||||
});
|
||||
});
|
||||
@@ -1,5 +1,12 @@
|
||||
/* eslint-disable jsx-a11y/alt-text */
|
||||
import { ComponentPropsWithoutRef, ReactEventHandler, ReactNode, useMemo, useState } from 'react';
|
||||
import {
|
||||
CSSProperties,
|
||||
ComponentPropsWithoutRef,
|
||||
ReactEventHandler,
|
||||
ReactNode,
|
||||
useMemo,
|
||||
useState,
|
||||
} from 'react';
|
||||
import {
|
||||
attributesToProps,
|
||||
domToReact,
|
||||
@@ -26,6 +33,7 @@ import { EMOJI_PATTERN, sanitizeForRegex, URL_NEG_LB } from '$utils/regex';
|
||||
import { findAndReplace } from '$utils/findAndReplace';
|
||||
import { onEnterOrSpace } from '$utils/keyboard';
|
||||
import { copyToClipboard } from '$utils/dom';
|
||||
import { isMatrixHexColor } from '$utils/matrixHtml';
|
||||
import { useTimeoutToggle } from '$hooks/useTimeoutToggle';
|
||||
import { ClientSideHoverFreeze } from '$components/ClientSideHoverFreeze';
|
||||
import { CodeHighlightRenderer } from '$components/code-highlight';
|
||||
@@ -58,6 +66,42 @@ export const safeDecodeUrl = (url: string) => {
|
||||
}
|
||||
};
|
||||
|
||||
const getMatrixColorStyle = (attribs: Record<string, string>): CSSProperties | undefined => {
|
||||
const color = attribs['data-mx-color'];
|
||||
const backgroundColor = attribs['data-mx-bg-color'];
|
||||
|
||||
const style: CSSProperties = {};
|
||||
|
||||
if (typeof color === 'string' && isMatrixHexColor(color)) {
|
||||
style.color = color;
|
||||
}
|
||||
|
||||
if (typeof backgroundColor === 'string' && isMatrixHexColor(backgroundColor)) {
|
||||
style.backgroundColor = backgroundColor;
|
||||
}
|
||||
|
||||
return Object.keys(style).length > 0 ? style : undefined;
|
||||
};
|
||||
|
||||
const stripIncomingStyle = (
|
||||
attribs: Record<string, string>
|
||||
): Omit<ReturnType<typeof attributesToProps>, 'style'> => {
|
||||
const { style, ...props } = attributesToProps(attribs);
|
||||
|
||||
return props;
|
||||
};
|
||||
|
||||
const ensureNoopenerRel = (rel: unknown): string => {
|
||||
if (typeof rel !== 'string') return 'noopener';
|
||||
|
||||
const parts = rel.split(/\s+/).filter(Boolean);
|
||||
if (!parts.includes('noopener')) {
|
||||
parts.push('noopener');
|
||||
}
|
||||
|
||||
return parts.join(' ');
|
||||
};
|
||||
|
||||
export const makeMentionCustomProps = (
|
||||
handleMentionClick?: ReactEventHandler<HTMLElement>,
|
||||
content?: string
|
||||
@@ -373,7 +417,8 @@ export const getReactCustomHtmlParser = (
|
||||
if (domNode instanceof Element && 'name' in domNode) {
|
||||
const { name, attribs, children, parent } = domNode;
|
||||
const renderChildren = () => domToReact(children as any, opts);
|
||||
const props = attributesToProps(attribs);
|
||||
const props = stripIncomingStyle(attribs);
|
||||
const matrixColorStyle = getMatrixColorStyle(attribs);
|
||||
|
||||
if (name === 'h1') {
|
||||
return (
|
||||
@@ -505,8 +550,13 @@ export const getReactCustomHtmlParser = (
|
||||
if (name === 'a' && typeof props.href === 'string') {
|
||||
const encodedHref = props.href;
|
||||
const decodedHref = encodedHref && safeDecodeUrl(encodedHref);
|
||||
const anchorProps = {
|
||||
...props,
|
||||
rel: ensureNoopenerRel(props.rel),
|
||||
};
|
||||
|
||||
if (!decodedHref || !testMatrixTo(decodedHref)) {
|
||||
return undefined;
|
||||
return <a {...anchorProps}>{renderChildren()}</a>;
|
||||
}
|
||||
|
||||
const content = children.find((child) => !(child instanceof DOMText))
|
||||
@@ -534,13 +584,21 @@ export const getReactCustomHtmlParser = (
|
||||
onClick={params.handleSpoilerClick}
|
||||
className={css.Spoiler()}
|
||||
aria-pressed
|
||||
style={{ cursor: 'pointer' }}
|
||||
style={{ ...matrixColorStyle, cursor: 'pointer' }}
|
||||
>
|
||||
{renderChildren()}
|
||||
</span>
|
||||
);
|
||||
}
|
||||
|
||||
if (name === 'span' && matrixColorStyle) {
|
||||
return (
|
||||
<span {...props} style={matrixColorStyle}>
|
||||
{renderChildren()}
|
||||
</span>
|
||||
);
|
||||
}
|
||||
|
||||
if (name === 'img') {
|
||||
// Guard: img without a src survives sanitisation (fix for crash #1731)
|
||||
// but we can't convert it — skip rendering rather than passing
|
||||
@@ -548,6 +606,8 @@ export const getReactCustomHtmlParser = (
|
||||
if (!props.src) return null;
|
||||
|
||||
const htmlSrc = mxcUrlToHttp(mx, props.src, params.useAuthentication) ?? undefined;
|
||||
const fallbackLabel = props.alt || props.title || '[media]';
|
||||
const failedToResolveMxc = props.src.startsWith('mxc://') && !htmlSrc;
|
||||
|
||||
// Non-mxc images were already converted to <a> links by the sanitiser,
|
||||
// but handle the edge case defensively here too.
|
||||
@@ -643,6 +703,14 @@ export const getReactCustomHtmlParser = (
|
||||
);
|
||||
}
|
||||
|
||||
if (failedToResolveMxc) {
|
||||
return (
|
||||
<span title={`Failed to load media${props.alt ? `: ${props.alt}` : ''}`}>
|
||||
{fallbackLabel}
|
||||
</span>
|
||||
);
|
||||
}
|
||||
|
||||
if (htmlSrc)
|
||||
return (
|
||||
<FallbackImg
|
||||
|
||||
@@ -110,6 +110,11 @@ export interface Settings {
|
||||
alwaysShowCallButton: boolean;
|
||||
faviconForMentionsOnly: boolean;
|
||||
highlightMentions: boolean;
|
||||
/**
|
||||
* whether to enable pk compat
|
||||
*/
|
||||
pkCompat: boolean;
|
||||
pmpProxying: boolean;
|
||||
mentionInReplies: boolean;
|
||||
showPersonaSetting: boolean;
|
||||
|
||||
@@ -205,6 +210,8 @@ const defaultSettings: Settings = {
|
||||
alwaysShowCallButton: false,
|
||||
faviconForMentionsOnly: false,
|
||||
highlightMentions: true,
|
||||
pkCompat: false,
|
||||
pmpProxying: false,
|
||||
mentionInReplies: true,
|
||||
showPersonaSetting: false,
|
||||
|
||||
|
||||
@@ -0,0 +1,5 @@
|
||||
export const MATRIX_HEX_COLOR_REGEX = /^#[0-9a-fA-F]{6}$/;
|
||||
|
||||
export function isMatrixHexColor(value: string): boolean {
|
||||
return MATRIX_HEX_COLOR_REGEX.test(value);
|
||||
}
|
||||
+125
-119
@@ -1,134 +1,140 @@
|
||||
// Tests for sanitizeCustomHtml — security-critical: strips dangerous content from
|
||||
// user-supplied Matrix message HTML before rendering.
|
||||
import { describe, it, expect } from 'vitest';
|
||||
import { describe, expect, it } from 'vitest';
|
||||
import { sanitizeCustomHtml } from './sanitize';
|
||||
|
||||
describe('sanitizeCustomHtml – tag allowlist', () => {
|
||||
it('passes through permitted tags', () => {
|
||||
expect(sanitizeCustomHtml('<b>bold</b>')).toBe('<b>bold</b>');
|
||||
expect(sanitizeCustomHtml('<i>italic</i>')).toBe('<i>italic</i>');
|
||||
expect(sanitizeCustomHtml('<code>snippet</code>')).toBe('<code>snippet</code>');
|
||||
});
|
||||
|
||||
it('strips disallowed tags but keeps their text content', () => {
|
||||
const result = sanitizeCustomHtml('<marquee>text</marquee>');
|
||||
expect(result).not.toContain('<marquee');
|
||||
expect(result).toContain('text');
|
||||
});
|
||||
|
||||
it('strips <mx-reply> and its content entirely', () => {
|
||||
const result = sanitizeCustomHtml('<mx-reply>quoted message</mx-reply>remaining');
|
||||
expect(result).not.toContain('quoted message');
|
||||
expect(result).toContain('remaining');
|
||||
});
|
||||
});
|
||||
|
||||
describe('sanitizeCustomHtml – XSS prevention', () => {
|
||||
it('strips <script> tags and their content', () => {
|
||||
const result = sanitizeCustomHtml("<script>alert('xss')</script>");
|
||||
expect(result).not.toContain('<script');
|
||||
expect(result).not.toContain('alert');
|
||||
});
|
||||
|
||||
it('strips inline event handlers', () => {
|
||||
const result = sanitizeCustomHtml('<b onclick="alert(1)">click me</b>');
|
||||
expect(result).not.toContain('onclick');
|
||||
expect(result).toContain('click me');
|
||||
});
|
||||
|
||||
it('strips javascript: href on anchor tags', () => {
|
||||
const result = sanitizeCustomHtml('<a href="javascript:alert(\'xss\')">link</a>');
|
||||
expect(result).not.toMatch(/javascript:/);
|
||||
});
|
||||
|
||||
it('strips data: href on anchor tags', () => {
|
||||
describe('sanitizeCustomHtml', () => {
|
||||
it('keeps permitted Matrix v1.18 tags', () => {
|
||||
const result = sanitizeCustomHtml(
|
||||
'<a href="data:text/html,<script>alert(1)</script>">link</a>'
|
||||
'<details><summary>Summary</summary><table><tbody><tr><td><del>text</del></td></tr></tbody></table></details>'
|
||||
);
|
||||
expect(result).not.toContain('data:');
|
||||
|
||||
expect(result).toContain('<details>');
|
||||
expect(result).toContain('<summary>Summary</summary>');
|
||||
expect(result).toContain('<table>');
|
||||
expect(result).toContain('<del>text</del>');
|
||||
});
|
||||
|
||||
it('strips vbscript: href', () => {
|
||||
const result = sanitizeCustomHtml('<a href="vbscript:msgbox(1)">link</a>');
|
||||
expect(result).not.toContain('vbscript:');
|
||||
});
|
||||
});
|
||||
it('strips tags outside the Matrix v1.18 allowlist', () => {
|
||||
const result = sanitizeCustomHtml('<font color="#ff0000">font</font><strike>strike</strike>');
|
||||
|
||||
describe('sanitizeCustomHtml – link transformer', () => {
|
||||
it('adds rel and target to http links', () => {
|
||||
const result = sanitizeCustomHtml('<a href="https://example.com">link</a>');
|
||||
expect(result).toContain('rel="noreferrer noopener"');
|
||||
expect(result).toContain('target="_blank"');
|
||||
expect(result).not.toContain('<font');
|
||||
expect(result).not.toContain('<strike');
|
||||
expect(result).toContain('font');
|
||||
expect(result).toContain('strike');
|
||||
});
|
||||
|
||||
it('passes through existing href for http links', () => {
|
||||
const result = sanitizeCustomHtml('<a href="https://example.com">link</a>');
|
||||
it('strips mx-reply and its contents entirely', () => {
|
||||
const result = sanitizeCustomHtml('<mx-reply>quoted message</mx-reply><p>remaining</p>');
|
||||
|
||||
expect(result).not.toContain('quoted message');
|
||||
expect(result).toBe('<p>remaining</p>');
|
||||
});
|
||||
|
||||
it('does not accept style attributes anywhere', () => {
|
||||
const result = sanitizeCustomHtml(
|
||||
'<span style="color:#00ff00" data-mx-color="#ff0000">text</span><p style="color:#00ff00">para</p>'
|
||||
);
|
||||
|
||||
expect(result).not.toContain('style=');
|
||||
expect(result).toContain('data-mx-color="#ff0000"');
|
||||
});
|
||||
|
||||
it('keeps only the permitted attributes on each tag while preserving markdown metadata', () => {
|
||||
const result = sanitizeCustomHtml(
|
||||
'<span data-mx-color="#ff0000" data-mx-bg-color="#00ff00" data-mx-spoiler="spoiler" data-mx-maths="x" data-md="**">span</span>' +
|
||||
'<a href="https://example.com" target="_blank" rel="noreferrer" data-md="[]()">link</a>' +
|
||||
'<ol start="2" type="A" data-md="1."><li>item</li></ol>' +
|
||||
'<pre class="language-rust" data-md="```" data-lang="rust"><code class="language-rust" data-md="```" data-lang="rust">fn main() {}</code></pre>' +
|
||||
'<div data-mx-maths="x" data-md="nope">maths</div>'
|
||||
);
|
||||
|
||||
expect(result).toContain('data-mx-color="#ff0000"');
|
||||
expect(result).toContain('data-mx-bg-color="#00ff00"');
|
||||
expect(result).toContain('data-mx-spoiler="spoiler"');
|
||||
expect(result).toContain('data-mx-maths="x"');
|
||||
expect(result).toContain('data-md="**"');
|
||||
expect(result).toContain('href="https://example.com"');
|
||||
});
|
||||
});
|
||||
|
||||
describe('sanitizeCustomHtml – image transformer', () => {
|
||||
it('keeps <img> tags with mxc:// src', () => {
|
||||
const result = sanitizeCustomHtml('<img src="mxc://example.com/abc" alt="img" />');
|
||||
expect(result).toContain('<img');
|
||||
expect(result).toContain('src="mxc://example.com/abc"');
|
||||
});
|
||||
|
||||
it('converts <img> with https:// src to a safe <a> link', () => {
|
||||
const result = sanitizeCustomHtml('<img src="https://example.com/image.jpg" alt="photo" />');
|
||||
expect(result).not.toContain('<img');
|
||||
expect(result).toContain('<a');
|
||||
expect(result).toContain('https://example.com/image.jpg');
|
||||
expect(result).toContain('rel="noreferrer noopener"');
|
||||
});
|
||||
});
|
||||
|
||||
describe('sanitizeCustomHtml – style attribute restrictions', () => {
|
||||
// The span transformer unconditionally overwrites the style attribute with
|
||||
// values derived from data-mx-color / data-mx-bg-color. Inline CSS is always
|
||||
// discarded; colors must come from the data-mx-* attributes.
|
||||
it('converts data-mx-color to a CSS color style on span', () => {
|
||||
const result = sanitizeCustomHtml('<span data-mx-color="#ff0000">text</span>');
|
||||
// sanitize-html may normalise whitespace around the colon
|
||||
expect(result).toMatch(/color:\s*#ff0000/);
|
||||
});
|
||||
|
||||
it('discards plain inline style on span (use data-mx-color instead)', () => {
|
||||
const result = sanitizeCustomHtml('<span style="color: #ff0000">text</span>');
|
||||
// The transformer replaces style with data-mx-* values; no data-mx-color
|
||||
// present here, so style ends up stripped by the allowedStyles check.
|
||||
expect(result).not.toContain('color: #ff0000');
|
||||
});
|
||||
|
||||
it('strips non-hex values from data-mx-color', () => {
|
||||
const result = sanitizeCustomHtml('<span data-mx-color="red">text</span>');
|
||||
expect(result).not.toContain('color: red');
|
||||
});
|
||||
|
||||
it('strips disallowed CSS properties', () => {
|
||||
const result = sanitizeCustomHtml('<span style="position: fixed">text</span>');
|
||||
expect(result).not.toContain('position');
|
||||
});
|
||||
});
|
||||
|
||||
describe('sanitizeCustomHtml – code block class handling', () => {
|
||||
it('preserves language class on code blocks', () => {
|
||||
const result = sanitizeCustomHtml('<code class="language-typescript">const x = 1;</code>');
|
||||
expect(result).toContain('class="language-typescript"');
|
||||
});
|
||||
|
||||
it('preserves data-lang on code blocks', () => {
|
||||
const result = sanitizeCustomHtml('<code data-lang="typescript">const x = 1;</code>');
|
||||
expect(result).toContain('data-lang="typescript"');
|
||||
});
|
||||
|
||||
it('preserves data-lang on pre blocks', () => {
|
||||
const result = sanitizeCustomHtml('<pre data-lang="rust"><code>fn main() {}</code></pre>');
|
||||
expect(result).toContain('target="_blank"');
|
||||
expect(result).toContain('data-md="[]()"');
|
||||
expect(result).not.toContain('rel=');
|
||||
expect(result).toContain('<ol start="2" data-md="1.">');
|
||||
expect(result).not.toContain('type=');
|
||||
expect(result).toContain('class="language-rust"');
|
||||
expect(result).toContain('data-lang="rust"');
|
||||
expect(result).toContain('data-md="```"');
|
||||
expect(result).toContain('<div data-mx-maths="x">maths</div>');
|
||||
});
|
||||
|
||||
it('strips arbitrary classes not matching language-*', () => {
|
||||
const result = sanitizeCustomHtml('<code class="evil-class">code</code>');
|
||||
expect(result).not.toContain('evil-class');
|
||||
it('preserves a language class only when every class starts with language-', () => {
|
||||
expect(sanitizeCustomHtml('<code class="language-typescript">code</code>')).toContain(
|
||||
'class="language-typescript"'
|
||||
);
|
||||
expect(sanitizeCustomHtml('<pre class="language-rust"><code>code</code></pre>')).toContain(
|
||||
'class="language-rust"'
|
||||
);
|
||||
expect(
|
||||
sanitizeCustomHtml('<code class="language-typescript language-js">code</code>')
|
||||
).toContain('class="language-typescript language-js"');
|
||||
expect(sanitizeCustomHtml('<code class="language-typescript extra">code</code>')).not.toContain(
|
||||
'class='
|
||||
);
|
||||
});
|
||||
|
||||
it('keeps only valid absolute href schemes on links', () => {
|
||||
expect(sanitizeCustomHtml('<a href="https://example.com">https</a>')).toContain(
|
||||
'href="https://example.com"'
|
||||
);
|
||||
expect(sanitizeCustomHtml('<a href="mailto:[email protected]">mail</a>')).toContain(
|
||||
'href="mailto:[email protected]"'
|
||||
);
|
||||
expect(sanitizeCustomHtml('<a href="magnet:?xt=urn:btih:abcdef">magnet</a>')).toContain(
|
||||
'href="magnet:?xt=urn:btih:abcdef"'
|
||||
);
|
||||
|
||||
expect(sanitizeCustomHtml('<a href="/relative">relative</a>')).toBe('<a>relative</a>');
|
||||
expect(sanitizeCustomHtml('<a href="matrix:u/alice:example.com">matrix</a>')).toBe(
|
||||
'<a>matrix</a>'
|
||||
);
|
||||
expect(sanitizeCustomHtml('<a href="javascript:alert(1)">bad</a>')).toBe('<a>bad</a>');
|
||||
expect(sanitizeCustomHtml('<a href="vbscript:msgbox(1)">bad</a>')).toBe('<a>bad</a>');
|
||||
});
|
||||
|
||||
it('keeps only mxc image sources and preserves custom-emote markers', () => {
|
||||
const allowed = sanitizeCustomHtml(
|
||||
'<img data-mx-emoticon src="mxc://example.com/abc123" alt="blobcat" title="blobcat" height="32" />'
|
||||
);
|
||||
const blocked = sanitizeCustomHtml('<img src="https://example.com/image.jpg" alt="img" />');
|
||||
|
||||
expect(allowed).toContain('<img');
|
||||
expect(allowed).toContain('data-mx-emoticon');
|
||||
expect(allowed).toContain('src="mxc://example.com/abc123"');
|
||||
expect(allowed).toContain('alt="blobcat"');
|
||||
expect(blocked).not.toContain('<img');
|
||||
});
|
||||
|
||||
it('restores only one validated image src after masking duplicate image source attributes', () => {
|
||||
const result = sanitizeCustomHtml(
|
||||
'<img src="mxc://example.com/primary" src="mxc://example.com/secondary" srcset="mxc://example.com/secondary 1x" alt="img" />'
|
||||
);
|
||||
|
||||
expect(result).toContain('src="mxc://example.com/primary"');
|
||||
expect(result).not.toContain('mxc://example.com/secondary');
|
||||
expect(result).not.toContain('srcset=');
|
||||
expect(result.match(/\ssrc=/g)).toHaveLength(1);
|
||||
});
|
||||
|
||||
it('drops invalid Matrix color attributes instead of translating them to style', () => {
|
||||
const result = sanitizeCustomHtml(
|
||||
'<span data-mx-color="red" data-mx-bg-color="#123">text</span>'
|
||||
);
|
||||
|
||||
expect(result).toBe('<span>text</span>');
|
||||
});
|
||||
|
||||
it('enforces the 100-level nesting limit', () => {
|
||||
const deepHtml = `${'<div>'.repeat(101)}text${'</div>'.repeat(101)}`;
|
||||
const result = sanitizeCustomHtml(deepHtml);
|
||||
|
||||
expect(result).toContain('text');
|
||||
expect((result.match(/<div>/g) ?? []).length).toBeLessThanOrEqual(100);
|
||||
});
|
||||
});
|
||||
+273
-98
@@ -1,9 +1,10 @@
|
||||
import sanitizeHtml, { Transformer } from 'sanitize-html';
|
||||
import DOMPurify from 'dompurify';
|
||||
import { isMatrixHexColor } from './matrixHtml';
|
||||
|
||||
const MAX_TAG_NESTING = 100;
|
||||
const INTERNAL_IMG_SRC_ATTR = 'data-sable-img-src';
|
||||
|
||||
const permittedHtmlTags = [
|
||||
'font',
|
||||
'del',
|
||||
'h1',
|
||||
'h2',
|
||||
@@ -24,7 +25,6 @@ const permittedHtmlTags = [
|
||||
'u',
|
||||
'strong',
|
||||
'em',
|
||||
'strike',
|
||||
's',
|
||||
'code',
|
||||
'hr',
|
||||
@@ -42,22 +42,16 @@ const permittedHtmlTags = [
|
||||
'img',
|
||||
'details',
|
||||
'summary',
|
||||
];
|
||||
|
||||
const urlSchemes = ['https', 'http', 'ftp', 'mailto', 'magnet'];
|
||||
] as const;
|
||||
|
||||
const permittedTagToAttributes = {
|
||||
font: ['style', 'data-mx-bg-color', 'data-mx-color', 'color'],
|
||||
span: [
|
||||
'style',
|
||||
'data-mx-bg-color',
|
||||
'data-mx-color',
|
||||
'data-mx-spoiler',
|
||||
'data-mx-maths',
|
||||
'data-mx-pill',
|
||||
'data-mx-ping',
|
||||
'data-md',
|
||||
],
|
||||
span: ['data-mx-bg-color', 'data-mx-color', 'data-mx-spoiler', 'data-mx-maths', 'data-md'],
|
||||
a: ['target', 'href', 'data-md'],
|
||||
img: ['width', 'height', 'alt', 'title', 'src', 'data-mx-emoticon'], // data-mx-emoticon is for MSC2545
|
||||
ol: ['start', 'data-md'],
|
||||
ul: ['data-md'],
|
||||
code: ['class', 'data-md', 'data-lang'],
|
||||
pre: ['class', 'data-md', 'data-lang'],
|
||||
div: ['data-mx-maths'],
|
||||
blockquote: ['data-md'],
|
||||
h1: ['data-md'],
|
||||
@@ -66,12 +60,6 @@ const permittedTagToAttributes = {
|
||||
h4: ['data-md'],
|
||||
h5: ['data-md'],
|
||||
h6: ['data-md'],
|
||||
pre: ['data-md', 'class', 'data-lang'],
|
||||
ol: ['start', 'type', 'data-md'],
|
||||
ul: ['data-md'],
|
||||
a: ['name', 'target', 'href', 'rel', 'data-md'],
|
||||
img: ['width', 'height', 'alt', 'title', 'src', 'data-mx-emoticon'],
|
||||
code: ['class', 'data-md', 'data-lang'],
|
||||
strong: ['data-md'],
|
||||
i: ['data-md'],
|
||||
em: ['data-md'],
|
||||
@@ -80,85 +68,18 @@ const permittedTagToAttributes = {
|
||||
del: ['data-md'],
|
||||
sub: ['data-md'],
|
||||
hr: ['data-md'],
|
||||
};
|
||||
} as const satisfies Record<string, readonly string[]>;
|
||||
|
||||
const transformFontTag: Transformer = (tagName, attribs) => ({
|
||||
tagName,
|
||||
attribs: {
|
||||
...attribs,
|
||||
style: `background-color: ${attribs['data-mx-bg-color']}; color: ${attribs['data-mx-color']}`,
|
||||
},
|
||||
});
|
||||
const permittedHtmlAttributes = Array.from(new Set(Object.values(permittedTagToAttributes).flat()));
|
||||
|
||||
const transformSpanTag: Transformer = (tagName, attribs) => ({
|
||||
tagName,
|
||||
attribs: {
|
||||
...attribs,
|
||||
style: `background-color: ${attribs['data-mx-bg-color']}; color: ${attribs['data-mx-color']}`,
|
||||
},
|
||||
});
|
||||
const allowedLinkSchemes = new Set(['https', 'http', 'ftp', 'mailto', 'magnet']);
|
||||
const forbiddenContentTags = ['mx-reply', 'script', 'style', 'textarea', 'option', 'noscript'];
|
||||
|
||||
const transformATag: Transformer = (tagName, attribs) => ({
|
||||
tagName,
|
||||
attribs: {
|
||||
...attribs,
|
||||
rel: 'noreferrer noopener',
|
||||
target: '_blank',
|
||||
},
|
||||
});
|
||||
const codeLanguageClassRegex = /^language-[A-Za-z0-9_-]+$/;
|
||||
const orderedListStartRegex = /^-?\d+$/;
|
||||
const allowedUriRegex = /^(?:https?|ftp|mailto|magnet|mxc):/i;
|
||||
|
||||
const transformImgTag: Transformer = (tagName, attribs) => {
|
||||
const { src } = attribs;
|
||||
if (typeof src === 'string' && src.startsWith('mxc://') === false) {
|
||||
return {
|
||||
tagName: 'a',
|
||||
attribs: {
|
||||
href: src,
|
||||
rel: 'noreferrer noopener',
|
||||
target: '_blank',
|
||||
},
|
||||
text: attribs.alt || src,
|
||||
};
|
||||
}
|
||||
return {
|
||||
tagName,
|
||||
attribs: {
|
||||
...attribs,
|
||||
},
|
||||
};
|
||||
};
|
||||
|
||||
export const sanitizeCustomHtml = (customHtml: string): string =>
|
||||
sanitizeHtml(customHtml, {
|
||||
allowedTags: permittedHtmlTags,
|
||||
allowedAttributes: permittedTagToAttributes,
|
||||
disallowedTagsMode: 'discard',
|
||||
allowedSchemes: urlSchemes,
|
||||
allowedSchemesByTag: {
|
||||
a: urlSchemes,
|
||||
},
|
||||
allowedSchemesAppliedToAttributes: ['href'],
|
||||
allowProtocolRelative: false,
|
||||
allowedClasses: {
|
||||
code: ['language-*'],
|
||||
},
|
||||
allowedStyles: {
|
||||
'*': {
|
||||
color: [/^#(?:[0-9a-fA-F]{3}){1,2}$/],
|
||||
'background-color': [/^#(?:[0-9a-fA-F]{3}){1,2}$/],
|
||||
},
|
||||
},
|
||||
transformTags: {
|
||||
font: transformFontTag,
|
||||
span: transformSpanTag,
|
||||
a: transformATag,
|
||||
img: transformImgTag,
|
||||
},
|
||||
nonTextTags: ['style', 'script', 'textarea', 'option', 'noscript', 'mx-reply'],
|
||||
nestingLimit: MAX_TAG_NESTING,
|
||||
});
|
||||
|
||||
export const sanitizeText = (body: string) => {
|
||||
export function sanitizeText(body: string): string {
|
||||
const tagsToReplace: Record<string, string> = {
|
||||
'&': '&',
|
||||
'<': '<',
|
||||
@@ -166,5 +87,259 @@ export const sanitizeText = (body: string) => {
|
||||
'"': '"',
|
||||
"'": ''',
|
||||
};
|
||||
|
||||
return body.replace(/[&<>'"]/g, (tag) => tagsToReplace[tag] || tag);
|
||||
}
|
||||
|
||||
function tagAllowsAttribute(tagName: string, attrName: string): boolean {
|
||||
const allowedAttributes =
|
||||
permittedTagToAttributes[tagName as keyof typeof permittedTagToAttributes];
|
||||
|
||||
return allowedAttributes ? (allowedAttributes as readonly string[]).includes(attrName) : false;
|
||||
}
|
||||
|
||||
function isAllowedAbsoluteLink(value: string): boolean {
|
||||
try {
|
||||
const parsed = new URL(value);
|
||||
return allowedLinkSchemes.has(parsed.protocol.slice(0, -1));
|
||||
} catch {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
function isAllowedMxcUri(value: string): boolean {
|
||||
try {
|
||||
const parsed = new URL(value);
|
||||
return (
|
||||
parsed.protocol === 'mxc:' &&
|
||||
parsed.host.length > 0 &&
|
||||
parsed.pathname.length > 1 &&
|
||||
parsed.username === '' &&
|
||||
parsed.password === '' &&
|
||||
parsed.search === '' &&
|
||||
parsed.hash === ''
|
||||
);
|
||||
} catch {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
function normalizeCodeClasses(attrValue: string): string | undefined {
|
||||
const classes = attrValue.split(/\s+/).filter(Boolean);
|
||||
if (
|
||||
classes.length === 0 ||
|
||||
classes.some((className) => !codeLanguageClassRegex.test(className))
|
||||
) {
|
||||
return undefined;
|
||||
}
|
||||
|
||||
return classes.join(' ');
|
||||
}
|
||||
|
||||
function getValidatedAttributeValue(
|
||||
tagName: string,
|
||||
attrName: string,
|
||||
attrValue: string
|
||||
): string | undefined {
|
||||
if (attrName === 'style') {
|
||||
return undefined;
|
||||
}
|
||||
|
||||
if (
|
||||
(attrName === 'data-mx-color' || attrName === 'data-mx-bg-color') &&
|
||||
!isMatrixHexColor(attrValue)
|
||||
) {
|
||||
return undefined;
|
||||
}
|
||||
|
||||
if (tagName === 'a' && attrName === 'href' && !isAllowedAbsoluteLink(attrValue)) {
|
||||
return undefined;
|
||||
}
|
||||
|
||||
if (tagName === 'img' && attrName === 'src' && !isAllowedMxcUri(attrValue)) {
|
||||
return undefined;
|
||||
}
|
||||
|
||||
if (tagName === 'ol' && attrName === 'start' && !orderedListStartRegex.test(attrValue)) {
|
||||
return undefined;
|
||||
}
|
||||
|
||||
if ((tagName === 'code' || tagName === 'pre') && attrName === 'class') {
|
||||
return normalizeCodeClasses(attrValue);
|
||||
}
|
||||
|
||||
return attrValue;
|
||||
}
|
||||
|
||||
function getValidatedProtectedImageSource(
|
||||
sourceId: string | null,
|
||||
protectedSources?: Map<string, string>
|
||||
): string | undefined {
|
||||
const rawSrc = sourceId ? protectedSources?.get(sourceId) : undefined;
|
||||
|
||||
return typeof rawSrc === 'string' ? getValidatedAttributeValue('img', 'src', rawSrc) : undefined;
|
||||
}
|
||||
|
||||
function protectImageSources(customHtml: string): {
|
||||
protectedHtml: string;
|
||||
protectedSources: Map<string, string>;
|
||||
} {
|
||||
const protectedSources = new Map<string, string>();
|
||||
const protectedHtml = customHtml.replace(/<img\b[^>]*>/gi, (imgTag) => {
|
||||
let protectedSourceId: string | undefined;
|
||||
|
||||
const strippedTag = imgTag.replace(
|
||||
/\s(src|srcset)\s*=\s*("([^"]*)"|'([^']*)'|([^\s"'=<>`]+))/gi,
|
||||
(_match, attrName: string, _value, doubleQuoted, singleQuoted, bareValue) => {
|
||||
if (attrName.toLowerCase() !== 'src') {
|
||||
return '';
|
||||
}
|
||||
|
||||
if (protectedSourceId !== undefined) {
|
||||
return '';
|
||||
}
|
||||
|
||||
const rawSrc = doubleQuoted ?? singleQuoted ?? bareValue ?? '';
|
||||
protectedSourceId = `${protectedSources.size}`;
|
||||
protectedSources.set(protectedSourceId, rawSrc);
|
||||
|
||||
return ` ${INTERNAL_IMG_SRC_ATTR}="${protectedSourceId}"`;
|
||||
}
|
||||
);
|
||||
|
||||
return strippedTag;
|
||||
});
|
||||
|
||||
return {
|
||||
protectedHtml,
|
||||
protectedSources,
|
||||
};
|
||||
}
|
||||
|
||||
function restoreProtectedImageSources(
|
||||
sanitizedHtml: string,
|
||||
protectedSources: Map<string, string>
|
||||
): string {
|
||||
return sanitizedHtml.replace(
|
||||
new RegExp(`\\s${INTERNAL_IMG_SRC_ATTR}="([^"]+)"`, 'g'),
|
||||
(_match, sourceId: string) => {
|
||||
const validatedSrc = getValidatedProtectedImageSource(sourceId, protectedSources);
|
||||
if (!validatedSrc) return '';
|
||||
|
||||
return ` src="${sanitizeText(validatedSrc)}"`;
|
||||
}
|
||||
);
|
||||
}
|
||||
|
||||
const enforceNestingLimit = (fragment: DocumentFragment): void => {
|
||||
const overlyNestedElements: Array<{ depth: number; element: Element }> = [];
|
||||
|
||||
const collect = (node: ParentNode, depth: number) => {
|
||||
Array.from(node.childNodes).forEach((child) => {
|
||||
if (!(child instanceof Element)) return;
|
||||
|
||||
const childDepth = depth + 1;
|
||||
if (childDepth > MAX_TAG_NESTING) {
|
||||
overlyNestedElements.push({ depth: childDepth, element: child });
|
||||
}
|
||||
|
||||
collect(child, childDepth);
|
||||
});
|
||||
};
|
||||
|
||||
collect(fragment, 0);
|
||||
|
||||
overlyNestedElements
|
||||
.sort((a, b) => b.depth - a.depth)
|
||||
.forEach(({ element }) => {
|
||||
if (!element.parentNode) return;
|
||||
element.replaceWith(...Array.from(element.childNodes));
|
||||
});
|
||||
};
|
||||
|
||||
const pruneInvalidEmptyElements = (
|
||||
fragment: DocumentFragment,
|
||||
protectedSources?: Map<string, string>
|
||||
): void => {
|
||||
fragment.querySelectorAll('img').forEach((img) => {
|
||||
const validatedProtectedSource = getValidatedProtectedImageSource(
|
||||
img.getAttribute(INTERNAL_IMG_SRC_ATTR),
|
||||
protectedSources
|
||||
);
|
||||
|
||||
if (!img.getAttribute('src') && !validatedProtectedSource) {
|
||||
img.remove();
|
||||
}
|
||||
});
|
||||
};
|
||||
|
||||
export const sanitizeCustomHtml = (customHtml: string): string => {
|
||||
if (typeof window === 'undefined') {
|
||||
return sanitizeText(customHtml);
|
||||
}
|
||||
|
||||
const { protectedHtml, protectedSources } = protectImageSources(customHtml);
|
||||
const purify = DOMPurify(window);
|
||||
const allowedHtmlAttributes = [...permittedHtmlAttributes, INTERNAL_IMG_SRC_ATTR];
|
||||
|
||||
purify.addHook('uponSanitizeAttribute', (currentNode, hookEvent) => {
|
||||
const tagName = currentNode.tagName.toLowerCase();
|
||||
const attrName = hookEvent.attrName.toLowerCase();
|
||||
|
||||
if (tagName === 'img' && attrName === INTERNAL_IMG_SRC_ATTR) {
|
||||
if (!protectedSources.has(hookEvent.attrValue)) {
|
||||
// eslint-disable-next-line no-param-reassign
|
||||
hookEvent.keepAttr = false;
|
||||
return;
|
||||
}
|
||||
|
||||
// eslint-disable-next-line no-param-reassign
|
||||
hookEvent.forceKeepAttr = true;
|
||||
return;
|
||||
}
|
||||
|
||||
if (!tagAllowsAttribute(tagName, attrName)) {
|
||||
// DOMPurify exposes attribute decisions by mutating the hook event.
|
||||
// eslint-disable-next-line no-param-reassign
|
||||
hookEvent.keepAttr = false;
|
||||
return;
|
||||
}
|
||||
|
||||
const validatedAttrValue = getValidatedAttributeValue(tagName, attrName, hookEvent.attrValue);
|
||||
if (validatedAttrValue === undefined) {
|
||||
// eslint-disable-next-line no-param-reassign
|
||||
hookEvent.keepAttr = false;
|
||||
return;
|
||||
}
|
||||
|
||||
// eslint-disable-next-line no-param-reassign
|
||||
hookEvent.attrValue = validatedAttrValue;
|
||||
// eslint-disable-next-line no-param-reassign
|
||||
hookEvent.forceKeepAttr = true;
|
||||
});
|
||||
|
||||
const sanitizedNode = purify.sanitize(protectedHtml, {
|
||||
ALLOWED_TAGS: [...permittedHtmlTags],
|
||||
ALLOWED_ATTR: allowedHtmlAttributes,
|
||||
ALLOW_ARIA_ATTR: false,
|
||||
ALLOW_DATA_ATTR: true,
|
||||
FORBID_ATTR: ['style'],
|
||||
FORBID_TAGS: ['mx-reply'],
|
||||
FORBID_CONTENTS: forbiddenContentTags,
|
||||
KEEP_CONTENT: true,
|
||||
ALLOWED_URI_REGEXP: allowedUriRegex,
|
||||
RETURN_DOM_FRAGMENT: true,
|
||||
});
|
||||
|
||||
if (!(sanitizedNode instanceof window.DocumentFragment)) {
|
||||
return sanitizeText(customHtml);
|
||||
}
|
||||
|
||||
const fragment = sanitizedNode;
|
||||
enforceNestingLimit(fragment);
|
||||
pruneInvalidEmptyElements(fragment, protectedSources);
|
||||
|
||||
const container = document.createElement('div');
|
||||
container.append(fragment);
|
||||
return restoreProtectedImageSources(container.innerHTML, protectedSources);
|
||||
};
|
||||
@@ -0,0 +1,4 @@
|
||||
export function generateShortId(length: number): string {
|
||||
const uuid = crypto.randomUUID();
|
||||
return uuid.replaceAll('-', '').substring(0, length);
|
||||
}
|
||||
@@ -22,18 +22,14 @@ export const getFirstLinkedTimeline = (
|
||||
return current;
|
||||
};
|
||||
|
||||
const collectTimelines = (
|
||||
tl: EventTimeline | null,
|
||||
dir: Direction,
|
||||
acc: EventTimeline[] = []
|
||||
): EventTimeline[] => {
|
||||
if (!tl) return acc;
|
||||
return collectTimelines(tl.getNeighbouringTimeline(dir), dir, [...acc, tl]);
|
||||
};
|
||||
|
||||
export const getLinkedTimelines = (timeline: EventTimeline): EventTimeline[] => {
|
||||
const firstTimeline = getFirstLinkedTimeline(timeline, Direction.Backward);
|
||||
return collectTimelines(firstTimeline, Direction.Forward);
|
||||
const result: EventTimeline[] = [];
|
||||
let current: EventTimeline | null = getFirstLinkedTimeline(timeline, Direction.Backward);
|
||||
while (current) {
|
||||
result.push(current);
|
||||
current = current.getNeighbouringTimeline(Direction.Forward);
|
||||
}
|
||||
return result;
|
||||
};
|
||||
|
||||
export const timelineToEventsCount = (t: EventTimeline) => {
|
||||
|
||||
@@ -563,9 +563,6 @@ export const startClient = async (mx: MatrixClient, config?: StartClientConfig):
|
||||
pollTimeoutMs: slidingConfig?.pollTimeoutMs ?? SLIDING_SYNC_POLL_TIMEOUT_MS,
|
||||
});
|
||||
manager.attach();
|
||||
// Begin background spidering so all rooms are eventually indexed.
|
||||
// Not awaited — this runs incrementally in the background.
|
||||
manager.startSpidering(100, 50);
|
||||
slidingSyncByClient.set(mx, manager);
|
||||
syncTransportByClient.set(mx, {
|
||||
transport: 'sliding',
|
||||
|
||||
@@ -8,6 +8,7 @@ import {
|
||||
MSC3575List,
|
||||
MSC3575RoomData,
|
||||
MSC3575RoomSubscription,
|
||||
MSC3575SlidingSyncResponse,
|
||||
MSC3575_WILDCARD,
|
||||
RoomMemberEvent,
|
||||
SlidingSync,
|
||||
@@ -351,6 +352,27 @@ export class SlidingSyncManager {
|
||||
return;
|
||||
}
|
||||
|
||||
// Before room data is processed, reset live timelines for active rooms that
|
||||
// are receiving a full refresh (initial: true) or a post-gap update
|
||||
// (limited: true). The SDK deliberately does not call resetLiveTimeline() for
|
||||
// sliding sync, so events from previous visits accumulate in the live
|
||||
// timeline alongside new events. Resetting here — before the SDK's
|
||||
// onRoomData listener runs — ensures the fresh batch lands on a clean
|
||||
// timeline with a correct backward pagination token.
|
||||
if (state === SlidingSyncState.RequestFinished && resp && !err) {
|
||||
const rooms = (resp as MSC3575SlidingSyncResponse).rooms ?? {};
|
||||
Object.entries(rooms)
|
||||
.filter(([, roomData]) => roomData.initial || roomData.limited)
|
||||
.filter(([roomId]) => this.activeRoomSubscriptions.has(roomId))
|
||||
.forEach(([roomId]) => {
|
||||
const room = this.mx.getRoom(roomId);
|
||||
if (!room) return;
|
||||
const timelineSet = room.getUnfilteredTimelineSet();
|
||||
if (timelineSet.getLiveTimeline().getEvents().length === 0) return;
|
||||
timelineSet.resetLiveTimeline();
|
||||
});
|
||||
}
|
||||
|
||||
if (err || !resp || state !== SlidingSyncState.Complete) return;
|
||||
|
||||
// Track what changed in this sync cycle
|
||||
|
||||
@@ -277,28 +277,73 @@ async function fetchRoomName(
|
||||
}
|
||||
}
|
||||
|
||||
type MemberInfo = {
|
||||
displayname: string | undefined;
|
||||
avatarUrl: string | undefined;
|
||||
};
|
||||
|
||||
/**
|
||||
* Fetch a room member's displayname from homeserver member state.
|
||||
* Returns undefined if the member has no displayname or the request fails.
|
||||
* Fetch a room member's state from the homeserver.
|
||||
* Returns displayname and avatar_url (both may be undefined).
|
||||
*/
|
||||
async function fetchMemberDisplayName(
|
||||
async function fetchMemberInfo(
|
||||
baseUrl: string,
|
||||
accessToken: string,
|
||||
roomId: string,
|
||||
userId: string
|
||||
): Promise<string | undefined> {
|
||||
): Promise<MemberInfo> {
|
||||
try {
|
||||
const url = `${baseUrl}/_matrix/client/v3/rooms/${encodeURIComponent(roomId)}/state/m.room.member/${encodeURIComponent(userId)}`;
|
||||
const res = await fetch(url, { headers: { Authorization: `Bearer ${accessToken}` } });
|
||||
if (!res.ok) return { displayname: undefined, avatarUrl: undefined };
|
||||
const data = (await res.json()) as Record<string, unknown>;
|
||||
const displayname =
|
||||
typeof data.displayname === 'string' && data.displayname.trim()
|
||||
? data.displayname.trim()
|
||||
: undefined;
|
||||
const avatarUrl =
|
||||
typeof data.avatar_url === 'string' && data.avatar_url.trim()
|
||||
? data.avatar_url.trim()
|
||||
: undefined;
|
||||
return { displayname, avatarUrl };
|
||||
} catch {
|
||||
return { displayname: undefined, avatarUrl: undefined };
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Fetch the m.room.avatar state event URL from the homeserver.
|
||||
* Returns undefined when the room has no avatar or the request fails.
|
||||
*/
|
||||
async function fetchRoomAvatar(
|
||||
baseUrl: string,
|
||||
accessToken: string,
|
||||
roomId: string
|
||||
): Promise<string | undefined> {
|
||||
try {
|
||||
const url = `${baseUrl}/_matrix/client/v3/rooms/${encodeURIComponent(roomId)}/state/m.room.avatar`;
|
||||
const res = await fetch(url, { headers: { Authorization: `Bearer ${accessToken}` } });
|
||||
if (!res.ok) return undefined;
|
||||
const data = (await res.json()) as Record<string, unknown>;
|
||||
const name = data.displayname;
|
||||
return typeof name === 'string' && name.trim() ? name.trim() : undefined;
|
||||
const avatarUrl = data.url;
|
||||
return typeof avatarUrl === 'string' && avatarUrl.trim() ? avatarUrl.trim() : undefined;
|
||||
} catch {
|
||||
return undefined;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Convert an mxc:// URL to a legacy unauthenticated thumbnail URL.
|
||||
* Notification icons are fetched by the OS without auth headers, so we use
|
||||
* the pre-MSC3916 media endpoint which most homeservers still serve publicly.
|
||||
*/
|
||||
function mxcToNotificationUrl(mxcUrl: string, baseUrl: string): string | undefined {
|
||||
const match = mxcUrl.match(/^mxc:\/\/([^/]+)\/([^?#]+)/);
|
||||
if (!match) return undefined;
|
||||
const [, server, mediaId] = match;
|
||||
return `${baseUrl}/_matrix/media/v3/thumbnail/${encodeURIComponent(server)}/${encodeURIComponent(mediaId)}?width=96&height=96&method=crop`;
|
||||
}
|
||||
|
||||
/**
|
||||
* Return the first any-session we have stored (used for push fetches where we
|
||||
* don't have a client ID, e.g. when the app is backgrounded but still loaded).
|
||||
@@ -386,10 +431,11 @@ async function handleMinimalPushPayload(
|
||||
return;
|
||||
}
|
||||
|
||||
// Fetch the raw event and room name state in parallel — both need only roomId.
|
||||
const [rawEvent, roomNameFromState] = await Promise.all([
|
||||
// Fetch the raw event, room name, and room avatar in parallel — all need only roomId.
|
||||
const [rawEvent, roomNameFromState, roomAvatarMxc] = await Promise.all([
|
||||
fetchRawEvent(session.baseUrl, session.accessToken, roomId, eventId),
|
||||
fetchRoomName(session.baseUrl, session.accessToken, roomId),
|
||||
fetchRoomAvatar(session.baseUrl, session.accessToken, roomId),
|
||||
]);
|
||||
|
||||
if (!rawEvent) {
|
||||
@@ -406,13 +452,20 @@ async function handleMinimalPushPayload(
|
||||
|
||||
const eventType = rawEvent.type as string | undefined;
|
||||
const sender = rawEvent.sender as string | undefined;
|
||||
// Fetch sender's display name from room member state; fall back to MXID localpart.
|
||||
const senderDisplay =
|
||||
(sender
|
||||
? await fetchMemberDisplayName(session.baseUrl, session.accessToken, roomId, sender)
|
||||
: undefined) ?? (sender ? mxidLocalpart(sender) : 'Someone');
|
||||
// Fetch sender's member state — gives us both display name and avatar URL.
|
||||
const memberInfo = sender
|
||||
? await fetchMemberInfo(session.baseUrl, session.accessToken, roomId, sender)
|
||||
: { displayname: undefined, avatarUrl: undefined };
|
||||
// Fall back to MXID localpart when the server returns no displayname.
|
||||
const senderDisplay = memberInfo.displayname ?? (sender ? mxidLocalpart(sender) : 'Someone');
|
||||
// For DMs (no m.room.name state), use the sender's display name as the room name.
|
||||
const resolvedRoomName = roomNameFromState ?? senderDisplay;
|
||||
// Room avatar takes priority (group rooms); for DMs fall back to sender's member avatar.
|
||||
// Convert mxc:// to a legacy unauthenticated thumbnail URL so the OS can fetch it.
|
||||
const notificationAvatarUrl =
|
||||
(roomAvatarMxc ?? memberInfo.avatarUrl) !== undefined
|
||||
? mxcToNotificationUrl((roomAvatarMxc ?? memberInfo.avatarUrl)!, session.baseUrl)
|
||||
: undefined;
|
||||
const baseData = {
|
||||
room_id: roomId,
|
||||
event_id: eventId,
|
||||
@@ -432,13 +485,16 @@ async function handleMinimalPushPayload(
|
||||
|
||||
if (result?.success) {
|
||||
// App was backgrounded but not frozen — decryption succeeded.
|
||||
// Prefer the server-fetched display name (authoritative) over the relay's SDK cache
|
||||
// value, which may be stale or missing if the SDK hasn't fully synced yet.
|
||||
await handlePushNotificationPushData({
|
||||
...baseData,
|
||||
type: result.eventType,
|
||||
content: result.content,
|
||||
sender_display_name: result.sender_display_name ?? senderDisplay,
|
||||
sender_display_name: senderDisplay,
|
||||
// Prefer relay's room name (has m.direct / computed SDK name); fall back to state fetch.
|
||||
room_name: result.room_name || resolvedRoomName,
|
||||
room_avatar_url: notificationAvatarUrl,
|
||||
});
|
||||
} else {
|
||||
// App is frozen or fully closed — show "Encrypted message" fallback.
|
||||
@@ -448,6 +504,7 @@ async function handleMinimalPushPayload(
|
||||
content: {},
|
||||
sender_display_name: senderDisplay,
|
||||
room_name: resolvedRoomName,
|
||||
room_avatar_url: notificationAvatarUrl,
|
||||
});
|
||||
}
|
||||
} else {
|
||||
@@ -458,6 +515,7 @@ async function handleMinimalPushPayload(
|
||||
content: rawEvent.content,
|
||||
sender_display_name: senderDisplay,
|
||||
room_name: resolvedRoomName,
|
||||
room_avatar_url: notificationAvatarUrl,
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
@@ -21,6 +21,9 @@ export enum AccountDataEvent {
|
||||
// Sable account data
|
||||
SableNicknames = 'moe.sable.app.nicknames',
|
||||
SablePinStatus = 'moe.sable.app.pins_read_marker',
|
||||
|
||||
// because of a mistake hasn't been renamed in time
|
||||
SablePerProfileMessageProfiles = 'fyi.cisnt.permessageprofile',
|
||||
SableSettings = 'moe.sable.app.settings',
|
||||
}
|
||||
|
||||
@@ -51,6 +54,24 @@ export type SecretContent = {
|
||||
mac: string;
|
||||
};
|
||||
|
||||
/**
|
||||
* type to save compatibility information
|
||||
*/
|
||||
export type AccountDataCompatVersion = {
|
||||
/**
|
||||
* a simple version number, for example 1
|
||||
*/
|
||||
version: number;
|
||||
/**
|
||||
* the date where it was added
|
||||
*/
|
||||
compatDate: string;
|
||||
/**
|
||||
* version number which is the oldest compatible, this attribute is optional
|
||||
*/
|
||||
incompatBefore?: number;
|
||||
};
|
||||
|
||||
export type SecretAccountData = {
|
||||
encrypted: Record<string, SecretContent>;
|
||||
};
|
||||
@@ -14,6 +14,11 @@ export type IImageInfo = {
|
||||
[MATRIX_BLUR_HASH_PROPERTY_NAME]?: string;
|
||||
};
|
||||
|
||||
export type MSC1767Text = {
|
||||
body: string;
|
||||
mimetype?: string;
|
||||
};
|
||||
|
||||
export type IVideoInfo = {
|
||||
w?: number;
|
||||
h?: number;
|
||||
|
||||
Reference in new issue
Block a user