Merge branch 'dev' of https://github.com/SableClient/Sable into improve-space

This commit is contained in:
Kace Cottam committed 2026-03-17 12:50:02 -07:00
commit 689aee5ac3
180 files changed
+10255 -2628

No files matched your search

+5
View File
@@ -0,0 +1,5 @@
---
default: patch
---
Fix messages with body empty but formatted body filled rendering as empty.
+5
View File
@@ -0,0 +1,5 @@
---
default: patch
---
Fix emoticon autocomplete not respecting character threshold setting.
+5
View File
@@ -0,0 +1,5 @@
---
default: patch
---
Fix images without explicit dimensions not appearing.
+5
View File
@@ -0,0 +1,5 @@
---
default: patch
---
Fix Mac OS to macOS in the the devices tab
@@ -0,0 +1,5 @@
---
default: patch
---
# Improved voice message recording UI, it should now feel a lot more integrated.
@@ -0,0 +1,5 @@
---
default: patch
---
Add opt-in Sentry crash reporting with a consent banner.
+1
View File
@@ -0,0 +1 @@
* @7w1 @Just-Insane @hazre
+12
View File
@@ -6,6 +6,10 @@ inputs:
description: The OpenTofu version to install.
required: false
default: '1.11.5'
is_release_tag:
description: Whether the build is for a release tag. Passed through to VITE_IS_RELEASE_TAG.
required: false
default: 'false'
runs:
using: composite
@@ -14,6 +18,14 @@ runs:
uses: ./.github/actions/setup
with:
build: 'true'
env:
VITE_IS_RELEASE_TAG: ${{ inputs.is_release_tag }}
VITE_SENTRY_DSN: ${{ env.VITE_SENTRY_DSN }}
VITE_SENTRY_ENVIRONMENT: ${{ env.VITE_SENTRY_ENVIRONMENT }}
VITE_APP_VERSION: ${{ env.VITE_APP_VERSION }}
SENTRY_AUTH_TOKEN: ${{ env.SENTRY_AUTH_TOKEN }}
SENTRY_ORG: ${{ env.SENTRY_ORG }}
SENTRY_PROJECT: ${{ env.SENTRY_PROJECT }}
- name: Setup OpenTofu
uses: opentofu/setup-opentofu@9d84900f3238fab8cd84ce47d658d25dd008be2f # v1.0.8
+25 -1
View File
@@ -11,6 +11,11 @@ on:
tags:
- 'v*'
workflow_dispatch:
inputs:
git_tag:
description: 'Git tag to deploy (e.g. v1.2.3). Leave empty to deploy current HEAD.'
required: false
type: string
env:
CLOUDFLARE_API_TOKEN: ${{ secrets.TF_CLOUDFLARE_API_TOKEN }}
@@ -49,6 +54,15 @@ jobs:
- name: Prepare OpenTofu deployment
uses: ./.github/actions/prepare-tofu
with:
is_release_tag: ${{ startsWith(github.ref, 'refs/tags/v') || (github.event_name == 'workflow_dispatch' && inputs.git_tag != '') }}
env:
VITE_SENTRY_DSN: ${{ secrets.VITE_SENTRY_DSN }}
VITE_SENTRY_ENVIRONMENT: production
VITE_APP_VERSION: ${{ github.ref_name }}
SENTRY_AUTH_TOKEN: ${{ secrets.SENTRY_AUTH_TOKEN }}
SENTRY_ORG: ${{ secrets.SENTRY_ORG }}
SENTRY_PROJECT: ${{ secrets.SENTRY_PROJECT }}
- name: Comment PR plan
uses: dflook/tofu-plan@3f5dc358343fb58cd60f83b019e810315aa8258f # v2.2.3
@@ -57,7 +71,7 @@ jobs:
label: production
apply:
if: (github.event_name == 'push' && startsWith(github.ref, 'refs/tags/sable/v')) || github.event_name == 'workflow_dispatch'
if: (github.event_name == 'push' && startsWith(github.ref, 'refs/tags/v')) || github.event_name == 'workflow_dispatch'
runs-on: ubuntu-latest
permissions:
contents: read
@@ -69,9 +83,19 @@ jobs:
uses: actions/checkout@de0fac2e4500dabe0009e67214ff5f5447ce83dd # v6.0.2
with:
persist-credentials: false
ref: ${{ github.event_name == 'workflow_dispatch' && inputs.git_tag || '' }}
- name: Prepare OpenTofu deployment
uses: ./.github/actions/prepare-tofu
with:
is_release_tag: ${{ startsWith(github.ref, 'refs/tags/v') || (github.event_name == 'workflow_dispatch' && inputs.git_tag != '') }}
env:
VITE_SENTRY_DSN: ${{ secrets.VITE_SENTRY_DSN }}
VITE_SENTRY_ENVIRONMENT: production
VITE_APP_VERSION: ${{ github.ref_name }}
SENTRY_AUTH_TOKEN: ${{ secrets.SENTRY_AUTH_TOKEN }}
SENTRY_ORG: ${{ secrets.SENTRY_ORG }}
SENTRY_PROJECT: ${{ secrets.SENTRY_PROJECT }}
- name: Plan infrastructure
run: tofu plan -input=false -no-color
@@ -54,6 +54,22 @@ jobs:
echo EOF
} >> "$GITHUB_OUTPUT"
- name: Set Sentry build environment for PR preview
if: github.event_name == 'pull_request'
env:
VITE_SENTRY_DSN: ${{ secrets.VITE_SENTRY_DSN }}
SENTRY_AUTH_TOKEN: ${{ secrets.SENTRY_AUTH_TOKEN }}
SENTRY_ORG: ${{ secrets.SENTRY_ORG }}
SENTRY_PROJECT: ${{ secrets.SENTRY_PROJECT }}
shell: bash
run: |
echo "VITE_SENTRY_DSN=$VITE_SENTRY_DSN" >> "$GITHUB_ENV"
echo "VITE_SENTRY_ENVIRONMENT=preview" >> "$GITHUB_ENV"
echo "VITE_SENTRY_PR=${{ github.event.pull_request.number }}" >> "$GITHUB_ENV"
echo "SENTRY_AUTH_TOKEN=$SENTRY_AUTH_TOKEN" >> "$GITHUB_ENV"
echo "SENTRY_ORG=$SENTRY_ORG" >> "$GITHUB_ENV"
echo "SENTRY_PROJECT=$SENTRY_PROJECT" >> "$GITHUB_ENV"
- name: Setup app and build
uses: ./.github/actions/setup
with:
+18 -6
View File
@@ -9,6 +9,12 @@ on:
paths:
- 'Dockerfile'
- '.github/workflows/docker-publish.yml'
workflow_dispatch:
inputs:
git_tag:
description: 'Git tag to build and publish (e.g. v1.2.3). Leave empty to build current HEAD as a dev image.'
required: false
type: string
env:
REGISTRY: ghcr.io
@@ -29,6 +35,7 @@ jobs:
uses: actions/checkout@de0fac2e4500dabe0009e67214ff5f5447ce83dd # v6.0.2
with:
persist-credentials: false
ref: ${{ github.event_name == 'workflow_dispatch' && inputs.git_tag || '' }}
- name: Log in to GitHub Container Registry
if: github.event_name != 'pull_request'
@@ -42,8 +49,13 @@ jobs:
id: release_tag
shell: bash
run: |
if [[ "${GITHUB_REF}" == refs/tags/sable/v* ]]; then
echo "value=${GITHUB_REF#refs/tags/sable/}" >> "$GITHUB_OUTPUT"
if [[ "${{ github.event_name }}" == "workflow_dispatch" ]]; then
TAG="${{ inputs.git_tag }}"
else
TAG="${GITHUB_REF#refs/tags/}"
fi
if [[ "${TAG}" == v* ]]; then
echo "value=${TAG}" >> "$GITHUB_OUTPUT"
echo "is_release=true" >> "$GITHUB_OUTPUT"
else
echo "value=" >> "$GITHUB_OUTPUT"
@@ -58,11 +70,11 @@ jobs:
flavor: |
latest=false
tags: |
# dev branch: short commit SHA + latest
type=sha,prefix=,format=short,enable=${{ github.ref == 'refs/heads/dev' }}
type=raw,value=latest,enable=${{ github.ref == 'refs/heads/dev' }}
# dev branch or manual dispatch without a tag: short commit SHA + latest
type=sha,prefix=,format=short,enable=${{ github.ref == 'refs/heads/dev' || (github.event_name == 'workflow_dispatch' && inputs.git_tag == '') }}
type=raw,value=latest,enable=${{ github.ref == 'refs/heads/dev' || (github.event_name == 'workflow_dispatch' && inputs.git_tag == '') }}
# git tags: semver breakdown
# git tags (push or manual dispatch with a tag): semver breakdown
type=semver,pattern={{version}},value=${{ steps.release_tag.outputs.value }},enable=${{ steps.release_tag.outputs.is_release == 'true' }}
type=semver,pattern={{major}}.{{minor}},value=${{ steps.release_tag.outputs.value }},enable=${{ steps.release_tag.outputs.is_release == 'true' }}
type=semver,pattern={{major}},value=${{ steps.release_tag.outputs.value }},enable=${{ steps.release_tag.outputs.is_release == 'true' && !startsWith(steps.release_tag.outputs.value, 'v0.') }}
+18
View File
@@ -79,6 +79,24 @@ jobs:
- name: Run Knip
run: pnpm run knip
tests:
name: Tests
runs-on: ubuntu-latest
if: github.head_ref != 'release'
permissions:
contents: read
steps:
- name: Checkout repository
uses: actions/checkout@de0fac2e4500dabe0009e67214ff5f5447ce83dd # v6.0.2
with:
persist-credentials: false
- name: Setup app
uses: ./.github/actions/setup
- name: Run tests
run: pnpm run test:run
build:
name: Build
runs-on: ubuntu-latest
+231
View File
@@ -0,0 +1,231 @@
name: Sentry Preview Error Triage
on:
pull_request:
types: [opened, synchronize, reopened]
paths:
- 'src/**'
- 'index.html'
- 'package.json'
- 'vite.config.ts'
- 'tsconfig.json'
workflow_dispatch:
inputs:
pr_number:
description: 'PR number to triage'
required: true
type: number
jobs:
triage:
# Only run for PRs from the same repo (not forks) or manual dispatch
if: >
(github.event_name == 'pull_request' &&
github.event.pull_request.head.repo.full_name == github.repository) ||
github.event_name == 'workflow_dispatch'
runs-on: ubuntu-latest
permissions:
issues: write
pull-requests: write
steps:
- name: Triage Sentry preview errors
uses: actions/github-script@ed597411d8f924073f98dfc5c65a23a2325f34cd # v8.0.0
env:
SENTRY_AUTH_TOKEN: ${{ secrets.SENTRY_AUTH_TOKEN }}
SENTRY_ORG: ${{ secrets.SENTRY_ORG }}
SENTRY_PROJECT: ${{ secrets.SENTRY_PROJECT }}
PR_NUMBER: ${{ github.event.pull_request.number || github.event.inputs.pr_number }}
with:
github-token: ${{ secrets.GITHUB_TOKEN }}
script: |
const sentryToken = process.env.SENTRY_AUTH_TOKEN;
const sentryOrg = process.env.SENTRY_ORG;
const sentryProject = process.env.SENTRY_PROJECT;
const prNumber = Number(process.env.PR_NUMBER);
if (!prNumber) {
core.info('No PR number available — skipping triage.');
return;
}
if (!sentryToken || !sentryOrg || !sentryProject) {
core.warning('Sentry credentials not configured — skipping triage.');
return;
}
const COMMENT_MARKER = '<!-- sentry-preview-triage -->';
const { owner, repo } = context.repo;
// Create a label if it doesn't already exist
async function ensureLabel(name, description, color) {
try {
await github.rest.issues.getLabel({ owner, repo, name });
} catch {
try {
await github.rest.issues.createLabel({ owner, repo, name, description, color });
} catch (err) {
core.warning(`Could not create label "${name}": ${err.message}`);
}
}
}
// Find an existing GitHub issue that tracks a given Sentry issue ID
async function findExistingGhIssue(sentryIssueId) {
const marker = `sentry-id:${sentryIssueId}`;
const result = await github.rest.search.issuesAndPullRequests({
q: `repo:${owner}/${repo} is:issue label:sentry-preview "${marker}" in:body`,
});
return result.data.total_count > 0 ? result.data.items[0] : null;
}
// Create or update the sticky PR comment with the triage summary table
async function upsertPrComment(rows) {
const now = new Date().toUTCString().replace(':00 GMT', ' UTC');
let body;
if (rows.length === 0) {
body = [
COMMENT_MARKER,
'## Sentry Preview Error Triage',
'',
`No Sentry errors found for this PR's preview deployment as of ${now}.`,
'',
'_This comment updates automatically after each push._',
].join('\n');
} else {
const tableRows = rows.map(
(r) =>
`| [${r.title.slice(0, 70)}](${r.permalink}) | ${r.count} | ${new Date(r.firstSeen).toLocaleDateString()} | #${r.ghIssueNumber} |`
);
body = [
COMMENT_MARKER,
'## Sentry Preview Error Triage',
'',
`**${rows.length} error type(s)** detected in this PR's preview deployment:`,
'',
'| Error | Events | First seen | Issue |',
'| ----- | ------ | ---------- | ----- |',
...tableRows,
'',
`_Last checked: ${now}. Exclude these from your issues view with \`-label:sentry-preview\`._`,
].join('\n');
}
const comments = await github.paginate(github.rest.issues.listComments, {
owner,
repo,
issue_number: prNumber,
});
const existing = comments.find(
(c) => c.user.type === 'Bot' && c.body.includes(COMMENT_MARKER)
);
if (existing) {
await github.rest.issues.updateComment({
owner,
repo,
comment_id: existing.id,
body,
});
} else {
await github.rest.issues.createComment({
owner,
repo,
issue_number: prNumber,
body,
});
}
}
// Query Sentry for unresolved issues tagged with this PR number in the preview env
const query = encodeURIComponent(`is:unresolved pr:${prNumber}`);
const sentryUrl =
`https://sentry.io/api/0/projects/${sentryOrg}/${sentryProject}/issues/` +
`?query=${query}&environment=preview&limit=100`;
let sentryIssues;
try {
const resp = await fetch(sentryUrl, {
headers: { Authorization: `Bearer ${sentryToken}` },
});
if (!resp.ok) {
const msg = await resp.text();
core.warning(`Sentry API returned ${resp.status}: ${msg.slice(0, 200)}`);
return;
}
sentryIssues = await resp.json();
} catch (err) {
core.warning(`Sentry API unreachable: ${err.message}`);
return;
}
if (!Array.isArray(sentryIssues) || sentryIssues.length === 0) {
await upsertPrComment([]);
return;
}
// Ensure the shared and PR-specific labels exist
await ensureLabel('sentry-preview', 'Automated Sentry preview error', 'e4e669');
await ensureLabel(`pr-${prNumber}`, `Preview errors from PR #${prNumber}`, 'fbca04');
const rows = [];
for (const issue of sentryIssues) {
const {
id: sentryId,
title,
culprit,
permalink,
count,
userCount,
firstSeen,
lastSeen,
} = issue;
const displayTitle = (title || culprit || 'Unknown error').trim();
const sentryMarker = `sentry-id:${sentryId}`;
const existing = await findExistingGhIssue(sentryId);
let ghIssueNumber;
if (existing) {
ghIssueNumber = existing.number;
// Reopen if it was closed (e.g. after a previous fix that regressed)
if (existing.state === 'closed') {
await github.rest.issues.update({
owner,
repo,
issue_number: ghIssueNumber,
state: 'open',
});
core.info(`Reopened GH issue #${ghIssueNumber} for Sentry issue ${sentryId}`);
}
} else {
const issueBody = [
`<!-- ${sentryMarker} -->`,
`## Sentry Error — PR #${prNumber} Preview`,
'',
`**Error:** [${displayTitle}](${permalink})`,
`**First seen:** ${new Date(firstSeen).toUTCString()}`,
`**Last seen:** ${new Date(lastSeen).toUTCString()}`,
`**Events:** ${count} | **Affected users:** ${userCount}`,
'',
`This issue was automatically created from a Sentry error detected in the preview deployment for PR #${prNumber}.`,
'',
'> [!NOTE]',
'> To exclude automated preview issues from your issues view, filter with: `-label:sentry-preview`',
].join('\n');
const created = await github.rest.issues.create({
owner,
repo,
title: `[Sentry] ${displayTitle.slice(0, 120)}`,
body: issueBody,
labels: ['sentry-preview', `pr-${prNumber}`],
});
ghIssueNumber = created.data.number;
core.info(`Created GH issue #${ghIssueNumber} for Sentry issue ${sentryId}`);
}
rows.push({ title: displayTitle, permalink, count, firstSeen, ghIssueNumber });
}
await upsertPrComment(rows);
core.info(`Triage complete: ${rows.length} Sentry issue(s) processed for PR #${prNumber}.`);
+2
View File
@@ -1,5 +1,6 @@
experiment
dist
coverage
node_modules
devAssets
@@ -18,6 +19,7 @@ devAssets
*.tfbackend
!*.tfbackend.example
crash.log
build.sh
# the following line was added with the "git ignore" tool by itsrye.dev, version 0.1.0
.lh
+53
View File
@@ -1,5 +1,58 @@
# Sable Client Changelog
## 1.9.2 (2026-03-17)
### Fixes
* Fix opacity rendering in name colors. ([#325](https://github.com/SableClient/Sable/pull/325) by @7w1)
* Fix sending scheduled file attachments. ([#325](https://github.com/SableClient/Sable/pull/325) by @7w1)
* Fix replies rendering new lines when messages have lists. ([#325](https://github.com/SableClient/Sable/pull/325) by @7w1)
* Fix threads rendering fallback replies. ([#325](https://github.com/SableClient/Sable/pull/325) by @7w1)
* Remove pip video setting now that we have sable call ([#324](https://github.com/SableClient/Sable/pull/324) by @beef331)
## 1.9.1 (2026-03-17)
### Fixes
* Fix docker builds. ([#322](https://github.com/SableClient/Sable/pull/322) by @7w1)
## 1.9.0 (2026-03-17)
### Features
* Bring in Sable Call, our fork of element call, which introduces camera settings, screenshare settings, echo cancellation, noise suppression, automatic gain control, and avatars in calls. ([#127](https://github.com/SableClient/Sable/pull/127) by @melogale)
* added a `/sharehistory` command to [share encrypted history with a user](https://github.com/matrix-org/matrix-spec-proposals/blob/rav/proposal/encrypted_history_sharing/proposals/4268-encrypted-history-sharing.md) ([#296](https://github.com/SableClient/Sable/pull/296) by @dozro)
* added error page making it easier to report errors when they occur in the field ([#240](https://github.com/SableClient/Sable/pull/240) by @dozro)
* Push notifications now use `event_id_only` format — Sygnal never sees message content or sender metadata, and encrypted messages are decrypted client-side when the app tab is open ([#295](https://github.com/SableClient/Sable/pull/295) by @Just-Insane)
* Added a toggle to enable/disable showing the call button for large (> 10 member) rooms. ([#308](https://github.com/SableClient/Sable/pull/308) by @7w1)
* Add Sentry integration for error tracking and bug reporting ([#280](https://github.com/SableClient/Sable/pull/280) by @Just-Insane)
* Added the ability to edit the description of a file and streamlined the image and video ui ([#282](https://github.com/SableClient/Sable/pull/282) by @nushea)
### Fixes
* Add Ctrl+F / Cmd+F keyboard shortcut to open Sable search instead of browser find-in-page ([#304](https://github.com/SableClient/Sable/pull/304) by @Just-Insane)
* Add Vitest testing infrastructure with example tests and contributor documentation ([#297](https://github.com/SableClient/Sable/pull/297) by @Just-Insane)
* Account switcher: show a confirmation dialog before signing out of an account. ([#310](https://github.com/SableClient/Sable/pull/310) by @Just-Insane)
* Fix animated avatars not looping. ([#307](https://github.com/SableClient/Sable/pull/307) by @7w1)
* Autocomplete: pressing Enter now selects the highlighted item instead of sending the message. The first item is highlighted on open and ArrowUp/Down navigate the list while keeping typing focus in the editor. Focus returns to the message editor after completing a mention or emoji. ([#310](https://github.com/SableClient/Sable/pull/310) by @Just-Insane)
* Fix camera turning on by default when starting a call from the room header button ([#305](https://github.com/SableClient/Sable/pull/305) by @Just-Insane)
* Adding account: show a "Cancel" button next to the "Adding account" label so users can abort the flow. ([#310](https://github.com/SableClient/Sable/pull/310) by @Just-Insane)
* Fix duplicate unread badges on the /direct/ icon for DM rooms already shown as individual sidebar avatars ([#289](https://github.com/SableClient/Sable/pull/289) by @Just-Insane)
* Message editor: add `autoCapitalize="sentences"` to respect the OS/keyboard capitalisation setting on mobile. ([#310](https://github.com/SableClient/Sable/pull/310) by @Just-Insane)
* Fix emoji color bleeding into adjacent text in read receipt display names on Safari/WebKit ([#303](https://github.com/SableClient/Sable/pull/303) by @Just-Insane)
* Notifications: add "Favicon Dot: Mentions Only" setting — when enabled, the favicon badge only changes for mentions/keywords, not plain unreads. ([#310](https://github.com/SableClient/Sable/pull/310) by @Just-Insane)
* Support `matrixToBaseUrl` in `config.json` to override the default `matrix.to` link base URL. ([#314](https://github.com/SableClient/Sable/pull/314) by @Just-Insane)
* Video and audio messages: volume level is now persisted across page loads via `localStorage` and shared between all media players. ([#310](https://github.com/SableClient/Sable/pull/310) by @Just-Insane)
* Fix notification dot badge appearing off-center on sidebar avatars ([#306](https://github.com/SableClient/Sable/pull/306) by @Just-Insane)
* Reduced-motion: add `animation-iteration-count: 1` so spinners stop after one cycle instead of running indefinitely at near-zero speed. ([#310](https://github.com/SableClient/Sable/pull/310) by @Just-Insane)
* Server picker: prevent iOS from restoring the old server name while the user is actively editing the input. ([#310](https://github.com/SableClient/Sable/pull/310) by @Just-Insane)
* Browser tab/PWA: use the correct light (`#ffffff`) and dark (`#1b1a21`) theme-color values via `media` attribute on the meta tags. ([#310](https://github.com/SableClient/Sable/pull/310) by @Just-Insane)
* Fix excessive whitespace between the thread root message and replies in the thread drawer ([#302](https://github.com/SableClient/Sable/pull/302) by @Just-Insane)
* Fix thread messages to include the required `m.in_reply_to` fallback pointing to the latest thread event, so unthreaded clients can display the reply chain correctly per the Matrix spec. ([#288](https://github.com/SableClient/Sable/pull/288) by @Just-Insane)
* Fix spurious scroll-to-bottom and MaxListeners warnings on sync gap: stable callback refs and prevEventsLength guard in RoomTimeline, correct CallEmbed .bind(this) listener leak, stable refs in useCallSignaling, and unreadInfoRef to stop per-message listener churn ([#279](https://github.com/SableClient/Sable/pull/279) by @Just-Insane)
* Fix URL preview scroll arrows appearing when there is no content to scroll ([#301](https://github.com/SableClient/Sable/pull/301) by @Just-Insane)
* fix of compatibility of voice messages with element clients and style misshaps ([#286](https://github.com/SableClient/Sable/pull/286) by @dozro)
## 1.8.0 (2026-03-14)
### Features
+4 -1
View File
@@ -37,12 +37,15 @@ It is not always possible to phrase every change in such a manner, but it is des
Also, we use [ESLint](https://eslint.org/) for clean and stylistically consistent code syntax, so make sure your pull request follow it.
**Pull requests are not merged unless all quality checks are passing.** At minimum, `format`, `lint`, `typecheck`, and `knip` must all be green before a pull request can be merged. Run these locally before opening or updating a pull request:
**Pull requests are not merged unless all quality checks are passing.** At minimum, `format`, `lint`, `typecheck`, `knip`, and `tests` must all be green before a pull request can be merged. Run these locally before opening or updating a pull request:
- `pnpm run fmt:check`
- `pnpm run lint`
- `pnpm run typecheck`
- `pnpm run knip`
- `pnpm run test:run`
If your change touches logic with testable behaviour, please include tests. See [docs/TESTING.md](./docs/TESTING.md) for a guide on how to write them.
## Restrictions on Generative AI Usage
+3
View File
@@ -15,4 +15,7 @@
}
try_files {path} /index.html
# Required for Sentry browser profiling (JS Self-Profiling API)
header Document-Policy "js-profiling"
}
+3
View File
@@ -20,6 +20,9 @@ server {
location / {
root /opt/cinny/dist/;
# Required for Sentry browser profiling (JS Self-Profiling API)
add_header Document-Policy "js-profiling" always;
rewrite ^/config.json$ /config.json break;
rewrite ^/manifest.json$ /manifest.json break;
+122
View File
@@ -0,0 +1,122 @@
# Privacy Policy
**Effective date:** 2026-03-15
Sable is an open-source Matrix client developed by 7w1.
It is designed to keep data collection to a minimum. Most of the app works on your device and communicates directly with the Matrix homeserver you choose.
## Who is responsible
For official Sable builds distributed by the project, the data controller is **7w1**.
Contact: **[email protected]**
Project website: [**https://sable.moe**](https://sable.moe)
If you use a self-hosted, modified, or third-party build of Sable, that operator may use different diagnostics settings and may be responsible for their own privacy practices.
## What we collect
We only collect limited diagnostic data to help find bugs and improve the stability and security of the app.
Diagnostic data is sent only when error reporting is enabled.
This data may include:
- Crash and error details, such as exception type, stack trace, and error message
- Device, browser, or operating system name and version
- Application version and environment
- Anonymous performance information, such as page load, sync, or message-send timing
Before any diagnostic data is sent, sensitive values are scrubbed in the browser on your device.
## What we do not collect
Sable is designed not to collect or transmit:
- Matrix message content
- Room names or aliases
- User display names or avatars
- Contact lists or room member lists
- Authentication tokens or passwords
- Encryption keys or cryptographic session data
- IP addresses
- Precise or approximate location data
## Optional features
### Session replay
Session replay may be available for debugging, but it is **disabled by default** and must be turned on by the user.
When session replay is enabled, all text is masked, media is blocked, and form inputs are masked before any data leaves the device.
This is intended to ensure that Matrix messages, room names, user names, and other personal content are not visible in replays.
### Bug reports
You may choose to submit a bug report from within the app.
A bug report may include the description you write, platform and app version details, and optional diagnostic logs that you choose to attach.
Submitting a bug report is voluntary, and the app shows what will be sent before submission.
## Third-party services
Sable uses **Sentry** for crash reporting and performance diagnostics.
Sentry receives only the diagnostic data described in this policy.
Sentry handles that data under its own privacy policy:
[**https://sentry.io/privacy/**](https://sentry.io/privacy/)
Technical details about Sable's Sentry integration are documented here:
[**https://github.com/SableClient/Sable/dev/docs/SENTRY_PRIVACY.md**](https://github.com/SableClient/Sable/dev/docs/SENTRY_PRIVACY.md)
If a Sentry DSN is not configured, Sentry is inactive and no Sentry data is sent.
Self-hosted deployments may use a different Sentry instance or disable diagnostics entirely.
## Your controls
You can manage diagnostic features in: **Settings → General → Diagnostics & Privacy**
Depending on the build, you can disable error reporting, enable or disable session replay, and adjust breadcrumb categories.
### First-time consent notice
When a build has crash reporting configured, a notice appears the first time you open Sable. It explains that Sable can send anonymous crash reports to help fix bugs, and gives you the option to enable it. Dismissing the notice without enabling keeps crash reporting off.
This notice only appears once. Your choice is saved and can be changed at any time in **Settings → General → Diagnostics & Privacy**.
You can also stop all app-based data transmission by uninstalling the app.
## Legal basis
For users in the European Economic Area, diagnostic data is processed on the basis of legitimate interest for app reliability and security, and on the basis of consent where optional features such as session replay are explicitly enabled.
## Retention and transfers
Diagnostic data is stored by Sentry according to the retention settings of the Sentry project.
The Sable project does not keep a separate copy of that diagnostic data.
Because Sentry is a cloud service, diagnostic data may be processed outside your country of residence. Sentry states that it provides safeguards such as Standard Contractual Clauses where required.
## Children
Sable is not directed to children under 13.
We do not knowingly collect personal information from children through the app.
If you believe a child has submitted information through Sable, contact **[email protected]** so it can be removed.
## Changes to this policy
We may update this Privacy Policy from time to time.
When we do, we will publish the updated version at [**https://github.com/SableClient/Sable/blob/dev/docs/PRIVACY.md**](https://github.com/SableClient/Sable/blob/dev/docs/PRIVACY.md) and/or [**https://sable.moe**](https://sable.moe).
## Contact
If you have questions about this Privacy Policy or want to request deletion of data connected to a bug report, contact **[email protected]**.
+492
View File
@@ -0,0 +1,492 @@
# Sentry Integration for Sable
This document describes the Sentry error tracking and monitoring integration added to Sable.
For a detailed breakdown of what data is collected and how it is protected, see [SENTRY_PRIVACY.md](./SENTRY_PRIVACY.md).
## Overview
Sentry is integrated with Sable to provide:
- **Error tracking**: Automatic capture and reporting of errors and exceptions
- **Performance monitoring**: Track application performance and identify bottlenecks
- **User feedback**: Collect bug reports with context from users
- **Session replay**: Record user sessions (with privacy controls) for debugging
- **Breadcrumbs**: Track user actions leading up to errors
- **Debug log integration**: Attach internal debug logs to error reports
## Bug Fixes (found via Sentry Replay)
Two non-Sentry bugs were found and fixed in the course of building this integration:
### Scroll-to-bottom after list→subscription timeline expansion
**Problem**: When a room with a single cached event (list subscription, `timeline_limit=1`) becomes
fully subscribed and the SDK delivers N new events, the `TimelineReset` fires before any events land
on the fresh timeline. The "stay at bottom" effect queues a `scrollToBottom` while the DOM is still
empty (range `end=0`). By the time real events load, the scroll has already fired against an empty
container and is a no-op — the user's view stalls mid-list.
**Fix**: The stay-at-bottom `useEffect` now increments `scrollToBottomRef.current.count` after
calling `setTimeline(getInitialTimeline(room))`, re-queuing the scroll for after the first batch of
events arrives and the DOM has content.
**File**: `src/app/features/room/RoomTimeline.tsx`
### TS2367 redundant phase guard in `useCallSignaling`
**Problem**: A `phase !== undefined` guard was always evaluating to `true` because the TypeScript
type for `phase` had no `undefined` branch at that point in the control flow.
**Fix**: Removed the dead branch. TypeScript no longer emits a TS2367 comparison error here.
**File**: `src/app/hooks/useCallSignaling.ts`
---
## Features
### 1. Automatic Error Tracking
All errors are automatically captured and sent to Sentry with:
- Stack traces
- User context (anonymized)
- Device and browser information
- Recent breadcrumbs (user actions)
- Debug logs (when enabled)
### 2. Debug Logger Integration
The internal debug logger now integrates with Sentry:
- **Breadcrumbs**: All debug logs are added as breadcrumbs for context
- **Error capture**: Errors logged to the debug logger are automatically sent to Sentry
- **Warning sampling**: 10% of warnings are sent to Sentry to avoid overwhelming the system
- **Log attachment**: Recent logs can be attached to bug reports for additional context
Key integration points:
- `src/app/utils/debugLogger.ts` - Enhanced with Sentry breadcrumb and error capture
- Automatic breadcrumb creation for all log entries
- Error objects in log data are captured as exceptions
- 10% sampling rate for warnings to control volume
### 3. Bug Report Modal Integration
The bug report modal (`/bugreport` command or "Bug Report" button) now includes:
- **Optional Sentry reporting**: Checkbox to send anonymous reports to Sentry
- **Debug log attachment**: Option to include recent debug logs (last 100 entries)
- **User feedback API**: Bug reports are sent as Sentry user feedback for better visibility
- **Privacy controls**: Users can opt-in to Sentry reporting
Integration points:
- `src/app/features/bug-report/BugReportModal.tsx` - Added Sentry options and submission logic
- Automatically attaches platform info, version, and user agent
- Links bug reports to Sentry events for tracking
### 4. Privacy & Security
Comprehensive data scrubbing (full details in [SENTRY_PRIVACY.md](./SENTRY_PRIVACY.md)):
- **Token masking**: All access tokens, passwords, and authentication data are redacted
- **Matrix ID anonymization**: User IDs, room IDs, and event IDs are masked
- **Session replay privacy**: All text, media, and form inputs are masked when replay is enabled
- **request header sanitization**: Authorization headers are removed
- **User opt-in**: Users can enable Sentry via settings
Sensitive patterns automatically redacted:
- `access_token`, `password`, `token`, `refresh_token`
- `session_id`, `sync_token`, `next_batch`
- Matrix user IDs (`@user:server`)
- Matrix room IDs (`!room:server`)
- Matrix event IDs (`$event_id`)
### 5. Settings UI
Sentry controls are split across two settings locations:
**Settings → General → Diagnostics & Privacy** (user-facing):
- **Enable/disable error reporting**: Toggle Sentry error tracking on/off
- **Session replay control**: Enable/disable session recording (opt-in)
- Link to the privacy policy
**Settings → Developer Tools → Error Tracking (Sentry)** (power-user):
- **Breadcrumb categories**: Granular control over which log categories are sent as breadcrumbs
- **Session stats**: Live error/warning counts for the current page load
- **Export debug logs**: Download the in-memory log buffer as JSON for offline analysis
- **Attach debug logs**: Manually attach recent logs to next error report
- **Test buttons**: Force an error, test feedback, test message capture
### 6. First-Login Consent Banner
When `VITE_SENTRY_DSN` is set and a user has never seen the crash-reporting notice (i.e. `sable_sentry_enabled` is absent from `localStorage`), a dismissible banner slides in from the bottom of the screen on first load. It explains that anonymous crash reporting is available and asks if the user wants to enable it.
**Actions available in the banner:**
| Button | Effect |
| ------------------------- | -------------------------------------------------------------------------------------------------------------------------------- |
| **Enable** | Sets `sable_sentry_enabled = true` in `localStorage` and reloads the page so Sentry initialises. Reporting begins after reload. |
| **No thanks** / × (close) | Sets `sable_sentry_enabled = false` in `localStorage` and dismisses the banner with a fade-out animation. Sentry stays disabled. |
Once the user has interacted with the banner (either action), it never appears again. The same preference can be changed later in **Settings → General → Diagnostics & Privacy**.
**Implementation:** `src/app/components/telemetry-consent/TelemetryConsentBanner.tsx` — rendered inside the logged-in client layout so it only appears after a session is established.
> **Self-hosters**: If you do not set `VITE_SENTRY_DSN`, the banner is never shown and Sentry is entirely disabled at build time. No network requests are made to Sentry.
## Configuration
### Environment Variables
Configure Sentry via environment variables:
```env
# Required: Your Sentry DSN (if not set, Sentry is disabled)
VITE_SENTRY_DSN=https://[email protected]/project-id
# Required: Environment name - controls sampling rates
# - "production" = 10% trace/replay sampling (cost-effective for production)
# - "preview" = 100% trace/replay sampling (full debugging for PR previews)
# - "development" = 100% trace/replay sampling (full debugging for local dev)
VITE_SENTRY_ENVIRONMENT=production
# Optional: Release version for tracking (defaults to VITE_APP_VERSION)
VITE_SENTRY_RELEASE=1.7.0
# Optional: For uploading source maps to Sentry (CI/CD only)
SENTRY_AUTH_TOKEN=your-sentry-auth-token
SENTRY_ORG=your-org-slug
SENTRY_PROJECT=your-project-slug
```
### Self-Hosting with Docker
Sable is compiled at build time, so `VITE_*` variables must be passed as Docker
**build arguments** — they cannot be injected at container runtime via a plain
`docker run -e` flag. The easiest way for self-hosters to supply them is with
a `.env` file and `docker-compose`.
#### 1. Create a `.env` file
```env
# .env — never commit this file
VITE_SENTRY_DSN=https://[email protected]/XXXXXXX
VITE_SENTRY_ENVIRONMENT=production
```
The `VITE_SENTRY_ENVIRONMENT` value controls sampling rates (see table below).
Leave it as `production` for a live deployment.
#### 2. Reference it in `docker-compose.yml`
The `args` block forwards the variables from `.env` into the Docker build
stage so Vite can embed them in the bundle:
```yaml
services:
sable:
build:
context: .
args:
- VITE_SENTRY_DSN=${VITE_SENTRY_DSN}
- VITE_SENTRY_ENVIRONMENT=${VITE_SENTRY_ENVIRONMENT}
ports:
- '8080:8080'
```
Then build and start with:
```bash
docker compose --env-file .env up --build
```
#### 3. Verify it worked
Open the browser console after loading your instance — you should see:
```
[Sentry] Initialized for production environment
[Sentry] DSN configured: https://your-key@o...
```
If you see `[Sentry] Disabled - no DSN provided`, the build arg was not
picked up — double-check the `args` block and that your `.env` file is in the
same directory as `docker-compose.yml`.
#### Building without Compose
If you use plain `docker build`, pass build args directly:
```bash
docker build \
--build-arg VITE_SENTRY_DSN="https://[email protected]/XXXXXXX" \
--build-arg VITE_SENTRY_ENVIRONMENT="production" \
-t sable .
```
> **Security note:** DSN values embedded in the JavaScript bundle are visible
> to any user who opens DevTools. This is normal and expected for Sentry DSNs —
> they are designed to be public-facing ingest keys. Rate-limiting and origin
> restrictions on the Sentry project side are the correct controls.
### Deployment Configuration
**Production deployment (from `dev` branch):**
- Set `VITE_SENTRY_ENVIRONMENT=production`
- Gets 10% sampling for traces and session replay
- Cost-effective for production usage
- Configured in `.github/workflows/cloudflare-web-deploy.yml`
**Preview deployments (PR previews, Cloudflare Pages):**
- Set `VITE_SENTRY_ENVIRONMENT=preview`
- Gets 100% sampling for traces and session replay
- Full debugging capabilities for testing
- Configured in `.github/workflows/cloudflare-web-preview.yml`
**Local development:**
- `VITE_SENTRY_ENVIRONMENT` not set (defaults to `development` via Vite MODE)
- Gets 100% sampling for traces and session replay
- Full debugging capabilities
**Sampling rates by environment:**
```
Environment | Traces | Profiles | Session Replay | Error Replay
---------------|--------|----------|----------------|-------------
production | 10% | 10% | 10% | 100%
preview | 100% | 100% | 100% | 100%
development | 100% | 100% | 100% | 100%
```
> **Browser profiling requires a `Document-Policy: js-profiling` response header** on your HTML document.
> This is already included in the provided `Caddyfile` and nginx config. For other servers, add the header to
> the response serving `index.html`.
### User Preferences
Users can control Sentry via localStorage:
```javascript
// Disable Sentry entirely (requires page refresh)
localStorage.setItem('sable_sentry_enabled', 'false');
// Disable session replay only (requires page refresh)
localStorage.setItem('sable_sentry_replay_enabled', 'false');
```
Or use the UI in Settings → General → Diagnostics & Privacy.
## Custom Instrumentation
Beyond automatic error capture, Sable has hand-crafted monitoring at key
lifecycle points. See [SENTRY_PRIVACY.md](./SENTRY_PRIVACY.md) for the full
metrics reference. Key areas:
| Area | What's tracked |
| ---------------------- | ---------------------------------------------------------------------------------------------------------------------------------- |
| **Auth** | Login failures (by `errcode`), forced server logouts |
| **Sync** | Transport type, degraded states, cycle stats, initial sync latency, time-to-ready, total rooms loaded, active subscriptions |
| **Cryptography** | Decryption failures (by failure reason), key backup errors, store wipes, E2E verification outcomes, bulk decryption latency |
| **Messaging** | Send latency, send errors, local-echo `NOT_SENT` events |
| **Timeline** | Opens, virtual window size, jump-load latency, re-initialisations, `limited` sync resets, scroll offset at load, pagination errors |
| **Pagination** | Pagination latency (`sable.pagination.latency_ms`) and errors per direction |
| **Sliding sync** | Room subscription latency (`sable.sync.room_sub_latency_ms`), events per subscription batch (`sable.sync.room_sub_event_count`) |
| **Scroll / UX** | `atBottom` transitions with rapid-flip anomaly detection, scroll-to-bottom trigger warnings when user is scrolled up |
| **Calls** | `sable.call.start.attempt/error`, `sable.call.answered`, `sable.call.declined`, active/ended/timeout counters |
| **Message actions** | `sable.message.delete.*`, `sable.message.forward.*`, `sable.message.report.*`, `sable.message.reaction.toggle` |
| **Media** | Upload latency, upload size, cache stats |
| **Background clients** | Per-account notification client count, startup failures |
Fatal errors that are caught by `useAsyncCallback` state (and therefore never
reach React's ErrorBoundary) are explicitly forwarded with `captureException`:
- Client load failure (`phase: load`)
- Client start failure (`phase: start`)
- Background notification client startup failure
### Breadcrumb categories
All hand-crafted breadcrumbs use structured Sentry categories that appear in
the Sentry issue timeline and can be filtered in the developer settings panel.
| Category | Where emitted | What it records |
| ----------------- | ---------------------------------------------- | ------------------------------------------------------------------------------ |
| `auth` | `ClientRoot.tsx` | Login session start, forced logout |
| `sync` | `initMatrix.ts`, `SyncStatus.tsx` | Sync state transitions, degraded states, client ready |
| `sync.sliding` | `slidingSync.ts` | First room subscription data: latency, event count |
| `timeline.sync` | `RoomTimeline.tsx` | SDK-initiated `TimelineReset` (limited sync gap) — fires before events arrive |
| `timeline.events` | `RoomTimeline.tsx` | Every `eventsLength` batch: delta, batch size label, range gap, `atBottom` |
| `ui.scroll` | `RoomTimeline.tsx` | `atBottom` true→false transitions, rapid-flip warnings, scroll-to-bottom fires |
| `ui.timeline` | `RoomTimeline.tsx` | Virtual paginator window shifts (range start/end changes) |
| `call.signal` | `useCallSignaling.ts`, `IncomingCallModal.tsx` | Call signal state changes, answer/decline |
| `crypto` | `useKeyBackup.ts` | Key backup errors |
| `media` | `ClientNonUIFeatures.tsx` | Blob cache stats on blob URL creation |
## Implementation Details
### Files Modified
1. **`src/instrument.ts`**
- Enhanced Sentry initialization with privacy controls
- Added user preference checks
- Improved data scrubbing for Matrix-specific data
- Conditional session replay based on user settings
2. **`src/app/utils/debugLogger.ts`**
- Added Sentry import
- New `sendToSentry()` method for breadcrumbs and error capture
- New `exportLogsForSentry()` method
- New `attachLogsToSentry()` method
- Integrated into main `log()` method
3. **`src/app/features/bug-report/BugReportModal.tsx`**
- Added Sentry and debug logger imports
- New state for Sentry options (`sendToSentry`, `includeDebugLogs`)
- Enhanced `handleSubmit()` with Sentry user feedback
- New UI checkboxes for Sentry options
4. **`src/app/features/settings/developer-tools/SentrySettings.tsx`** _(new file)_
- New settings panel component
- Controls for Sentry and session replay
- Manual log attachment
5. **`src/app/features/settings/developer-tools/DevelopTools.tsx`**
- Added SentrySettings import and component
### Sentry Configuration
- **Tracing sample rate**: 100% in development, 10% in production
- **Session replay sample rate**: 10% of all sessions, 100% of error sessions
- **Warning capture rate**: 10% to avoid overwhelming Sentry
- **Breadcrumb retention**: All breadcrumbs retained for context
- **Log attachment limit**: Last 100 debug log entries
### Performance Considerations
- Breadcrumbs are added synchronously but are low-overhead
- Error capture is asynchronous and non-blocking
- Warning sampling (10%) prevents excessive Sentry usage
- Session replay only captures when enabled by user
- Debug log attachment limited to most recent entries
## Usage Examples
### For Developers
```typescript
import { getDebugLogger } from '$utils/debugLogger';
// Errors are automatically sent to Sentry
const logger = createDebugLogger('myNamespace');
logger.error('sync', 'Sync failed', error); // Sent to Sentry
// Manually attach logs before capturing an error
const debugLogger = getDebugLogger();
debugLogger.attachLogsToSentry(100);
Sentry.captureException(error);
```
### For Users
1. **Report a bug with Sentry**:
- Type `/bugreport` or click "Bug Report" button
- Fill in the form
- Check "Send anonymous report to Sentry"
- Check "Include recent debug logs" for more context
- Submit
2. **Disable Sentry**:
- Go to Settings → Developer Tools
- Enable Developer Tools
- Scroll to "Error Tracking (Sentry)"
- Toggle off "Enable Sentry Error Tracking"
- Refresh the page
## Benefits
### For Users
- Better bug tracking and faster fixes
- Optional participation with privacy controls
- Transparent data usage
### For Developers
- Real-time error notifications
- Rich context with breadcrumbs and logs
- Performance monitoring
- User feedback integrated with errors
- Replay sessions to reproduce bugs
## Privacy Commitment
See [SENTRY_PRIVACY.md](./SENTRY_PRIVACY.md) for a complete, code-linked breakdown of what is collected, what is masked, and how user controls work.
In summary, all data sent to Sentry is:
- **Off by default**: Sentry is disabled until the user explicitly opts in
- **Anonymized**: No personal data or message content
- **Filtered**: Tokens, passwords, and IDs are redacted
- **Minimal**: Only error context and debug info
- **Transparent**: Users can see what's being sent
No message content, room conversations, or personal information is ever sent to Sentry.
## Testing
To test the integration:
1. **Test error reporting**:
- Go to Settings → General → Diagnostics & Privacy
- Check that Sentry is enabled and `VITE_SENTRY_DSN` is set
- Open the browser console and run: `window.Sentry?.captureMessage('Test message')`
- Check the Sentry dashboard for the event
2. **Test bug report integration**:
- Type `/bugreport`
- Fill in form with test data
- Enable "Send anonymous report to Sentry"
- Submit and check Sentry
3. **Test privacy controls**:
- Disable Sentry in settings
- Refresh page
- Trigger an error (should not appear in Sentry)
- Re-enable and verify errors are captured again
## Troubleshooting
### Sentry not capturing errors
1. Check that `VITE_SENTRY_DSN` is set
2. Check that Sentry is enabled in settings
3. Check browser console for Sentry initialization message
4. Verify network requests to Sentry are not blocked
### Sensitive data in reports
1. Check `beforeSend` hook in `instrument.ts`
2. Add new patterns to the scrubbing regex
3. Test with actual data to verify masking
### Performance impact
1. Reduce tracing sample rate in production
2. Disable session replay if not needed
3. Monitor Sentry quota usage
4. Adjust warning sampling rate
## Resources
- [Sentry React Documentation](https://docs.sentry.io/platforms/javascript/guides/react/)
- [Sentry Error Monitoring Best Practices](https://docs.sentry.io/product/error-monitoring/)
- [Sentry Session Replay](https://docs.sentry.io/product/session-replay/)
- [Sentry User Feedback](https://docs.sentry.io/product/user-feedback/)
+340
View File
@@ -0,0 +1,340 @@
# Sentry Privacy Policy
This document describes exactly what data the Sentry integration collects, what
is masked or blocked, and where the relevant code lives. For setup and
configuration details see [SENTRY_INTEGRATION.md](./SENTRY_INTEGRATION.md).
---
## What Is Collected
Sentry is **disabled by default when no DSN is configured** and can be **opted
in to by users** at any time via Settings → General → Diagnostics & Privacy.
### First-Login Consent Notice
When Sentry is configured, the app shows a dismissible notice the first time a
user loads Sable. The notice explains that crash reporting is available and
provides a one-click opt-in before any data is sent.
| Action | Effect |
| -------------------------------- | --------------------------------------------------------------------------------------------------------------------------- |
| **"Enable"** | Sentry enabled (`sable_sentry_enabled = 'true'`), page reloads so Sentry initialises — data collection begins after reload |
| **"No thanks"** or **✕ dismiss** | Preference saved as opted-out (`sable_sentry_enabled = 'false'`); notice does not appear again; no Sentry data is ever sent |
The preference persists in `localStorage` and can be changed at any time in
**Settings → General → Diagnostics & Privacy**.
**Code:** `src/app/components/telemetry-consent/TelemetryConsentBanner.tsx`
When enabled, the following categories of data are sent:
### Error Reports
- Exception type and stack trace (function names, file names, line numbers)
- Error message text — scrubbed of tokens and Matrix IDs before sending (see
[What Is Scrubbed](#what-is-scrubbed))
- Browser and OS name/version
- JavaScript engine version
- Application release version (`VITE_APP_VERSION`)
- Sentry environment tag (`VITE_SENTRY_ENVIRONMENT`)
- Current URL path — tokens in query strings are redacted before sending
**Code:** `src/instrument.ts` — `beforeSend` callback
### Breadcrumbs (Action Trail)
Leading up to an error, Sentry records a trail of recent user actions:
- Navigation events (route changes)
- `console.error` and `console.warn` calls — filtered for sensitive patterns
before sending
- Internal debug log entries (category, level, summary message) — filtered
before sending
Breadcrumbs containing any of the patterns listed in
[What Is Scrubbed](#what-is-scrubbed) are sanitised in-place before leaving the
browser.
**Code:** `src/instrument.ts` — `beforeBreadcrumb` callback
**Code:** `src/app/utils/debugLogger.ts` — Sentry breadcrumb integration
### Application Breadcrumbs
In addition to automatic navigation/console breadcrumbs, the following named
events are explicitly recorded as breadcrumbs:
| Event | Category | Level | Source |
| ------------------------------------------- | -------- | ------------- | ------------------------- |
| Session forcibly logged out by server | `auth` | warning | `ClientRoot.tsx` |
| Sync state changed to Reconnecting/Error | `sync` | warning/error | `SyncStatus.tsx` |
| Sliding sync first run completed | `sync` | info | `initMatrix.ts` |
| Crypto store mismatch — wiping local stores | `crypto` | warning | `initMatrix.ts` |
| Key backup failed | `crypto` | error | `useKeyBackup.ts` |
| High media inflight request count | `media` | warning | `ClientNonUIFeatures.tsx` |
**Code:** `src/app/pages/client/ClientRoot.tsx`, `src/app/pages/client/SyncStatus.tsx`,
`src/client/initMatrix.ts`, `src/app/hooks/useKeyBackup.ts`,
`src/app/pages/client/ClientNonUIFeatures.tsx`
### Component Error Capture
The following failure paths use explicit `captureException` because they are
caught by state management hooks and never propagate to React's ErrorBoundary:
| Failure | Tag | Source |
| ---------------------------------------------- | ------------------------------------ | ----------------------------- |
| Client failed to load (fetch/init) | `phase: load` | `ClientRoot.tsx` |
| Client failed to start (sync start) | `phase: start` | `ClientRoot.tsx` |
| Background notification client failed to start | `component: BackgroundNotifications` | `BackgroundNotifications.tsx` |
**Code:** `src/app/pages/client/ClientRoot.tsx`,
`src/app/pages/client/BackgroundNotifications.tsx`
### Performance Traces
- Timing of React Router navigations (page-load and route-change latency)
- Custom spans for Matrix sync cycles, message send, and room data loading
- JavaScript CPU profiles during traced transactions (call-stack samples)
Performance data contains **no message content, no room names, and no user
identifiers**. Spans are labelled with operation names only.
| Span name | Operation | Source |
| ----------------------- | ----------------- | ---------------------- |
| `auth.login` | `auth` | `loginUtil.ts` |
| `decrypt.event` | `matrix.crypto` | `EncryptedContent.tsx` |
| `decrypt.bulk` | `matrix.crypto` | `room.ts` |
| `timeline.jump_load` | `matrix.timeline` | `RoomTimeline.tsx` |
| `message.send` | `matrix.message` | `RoomInput.tsx` |
| Sliding sync processing | `matrix.sync` | `slidingSync.ts` |
**Sample rates:**
| Environment | Traces | Profiles |
| ------------------------- | ------ | -------- |
| `production` | 10% | 10% |
| `preview` / `development` | 100% | 100% |
**Code:** `src/instrument.ts` — `tracesSampleRate`, `profilesSampleRate`
**Code:** `src/app/features/room/RoomInput.tsx` — message send span
**Code:** `src/app/utils/room.ts`, `src/client/slidingSync.ts` — room/sync spans
### Custom Metrics
All metrics contain no message content, room names, or user identifiers.
Attribute values are limited to short enumerated strings (error codes, states)
or numeric measurements.
#### Authentication
| Metric | Type | Attributes | What it tracks |
| ------------------------- | ----- | ---------- | ------------------------------------ |
| `sable.auth.login_failed` | count | `errcode` | Login attempt failures by error code |
**Code:** `src/app/pages/auth/login/loginUtil.ts`
#### Cryptography
| Metric | Type | Attributes | What it tracks |
| ----------------------------------- | ------------ | ----------------------------------- | ------------------------------------------------ |
| `sable.decryption.failure` | count | `reason` | Unable-to-decrypt events by failure reason |
| `sable.decryption.event_ms` | distribution | — | Per-event decryption latency |
| `sable.decryption.bulk_latency_ms` | distribution | `event_count` | Bulk re-decryption time on room open |
| `sable.crypto.key_backup_failures` | count | `errcode` | Key backup errors by code |
| `sable.crypto.store_wipe` | count | — | Crypto store mismatch wipe-and-retry occurrences |
| `sable.crypto.verification_outcome` | count | `outcome` (`completed`/`cancelled`) | E2E device verification outcomes |
**Code:** `src/app/features/room/message/EncryptedContent.tsx`,
`src/app/utils/room.ts`, `src/app/hooks/useKeyBackup.ts`,
`src/client/initMatrix.ts`, `src/app/components/DeviceVerification.tsx`
#### Messaging
| Metric | Type | Attributes | What it tracks |
| ------------------------------- | ------------ | ----------- | ----------------------------------- |
| `sable.message.send_latency_ms` | distribution | `encrypted` | Message send round-trip time |
| `sable.message.send_error` | count | — | Send errors from message composer |
| `sable.message.send_failed` | count | — | Local-echo `NOT_SENT` status events |
**Code:** `src/app/features/room/RoomInput.tsx`,
`src/app/features/room/RoomTimeline.tsx`
#### Timeline
| Metric | Type | Attributes | What it tracks |
| ------------------------------ | ------------ | ----------- | -------------------------------- |
| `sable.timeline.open` | count | `mode` | Timeline render initiations |
| `sable.timeline.render_window` | distribution | `mode` | Initial virtual window size |
| `sable.timeline.jump_load_ms` | distribution | — | Event-jump timeline load latency |
| `sable.timeline.reinit` | count | — | Full timeline re-initialisations |
| `sable.pagination.error` | count | `direction` | Pagination errors by direction |
**Code:** `src/app/features/room/RoomTimeline.tsx`
#### Sync
| Metric | Type | Attributes | What it tracks |
| --------------------------------- | ------------ | ---------------------------- | -------------------------------------- |
| `sable.sync.transport` | count | `type` (`sliding`/`classic`) | Sync transport type used |
| `sable.sync.cycle` | count | (various) | Completed sliding sync cycles |
| `sable.sync.error` | count | `errcode` | Sliding sync errors |
| `sable.sync.initial_ms` | distribution | — | Initial sync completion time |
| `sable.sync.processing_ms` | distribution | — | Per-cycle sync processing time |
| `sable.sync.lists_loaded_ms` | distribution | — | Time for room lists to fully load |
| `sable.sync.total_rooms` | gauge | `sync_type` | Total rooms known at list load |
| `sable.sync.active_subscriptions` | gauge | — | Active room subscription count |
| `sable.sync.client_ready_ms` | distribution | `type` | Time from init to client ready |
| `sable.sync.time_to_ready_ms` | distribution | — | Wall-clock time to first sync ready |
| `sable.sync.degraded` | count | `state` | Sync reconnect/error state transitions |
**Code:** `src/client/initMatrix.ts`, `src/client/slidingSync.ts`,
`src/app/pages/client/ClientRoot.tsx`, `src/app/pages/client/SyncStatus.tsx`
#### Media
| Metric | Type | Attributes | What it tracks |
| ------------------------------- | ------------ | ---------- | ---------------------------- |
| `sable.media.upload_latency_ms` | distribution | `mimetype` | Media upload round-trip time |
| `sable.media.upload_bytes` | distribution | `mimetype` | Upload size distribution |
| `sable.media.upload_error` | count | `reason` | Upload failures by reason |
| `sable.media.blob_cache_size` | gauge | — | Blob URL cache entry count |
| `sable.media.inflight_requests` | gauge | — | Concurrent media requests |
**Code:** `src/app/utils/matrix.ts`, `src/app/pages/client/ClientNonUIFeatures.tsx`
#### Background clients & debug telemetry
| Metric | Type | Attributes | What it tracks |
| ------------------------------- | ----- | ---------- | -------------------------------------- |
| `sable.background.client_count` | gauge | — | Active background notification clients |
| `sable.errors` | count | `category` | Error-level debug log entries |
| `sable.warnings` | count | `category` | Warning-level debug log entries |
**Code:** `src/app/pages/client/BackgroundNotifications.tsx`,
`src/app/utils/debugLogger.ts`
### Session Replay _(opt-in, disabled by default)_
When session replay is explicitly enabled by the user, Sentry records UI
interactions to help reproduce bugs. **All content is masked at the browser
level before any data leaves the device:**
- All text on screen → replaced with `█` characters
- All images, video, and audio → blocked entirely (replaced with a grey box)
- All form inputs, including the message composer → replaced with `*` characters
This means **no Matrix messages, no room names, no user display names, and no
media are ever visible in a replay**.
Sample rates for replay:
| Trigger | Production | Preview / Dev |
| -------------------- | ---------- | ------------- |
| Regular sessions | 10% | 100% |
| Sessions with errors | 100% | 100% |
**Code:** `src/instrument.ts` — `replayIntegration` call with `maskAllText`,
`blockAllMedia`, `maskAllInputs`
### Bug Reports _(manual, opt-in per report)_
When a user submits a bug report via `/bugreport` or the "Bug Report" button:
- Free-text description written by the user
- Optional: recent debug log entries (last 100) attached as a file
- Platform info, browser version, application version
- Checkbox to send or not send to Sentry is **shown before submission**
**Code:** `src/app/features/bug-report/BugReportModal.tsx`
---
## What Is Never Collected
- Matrix message content
- Room names or aliases
- User display names or avatars
- Contact lists or room member lists
- Encryption keys or session data
- IP addresses (`sendDefaultPii: false`)
- Authentication tokens (scrubbed — see below)
---
## What Is Scrubbed
All scrubbing happens **in the browser before data is transmitted**. Nothing
leaves the device in unredacted form.
### Tokens and Credentials
The following patterns are replaced with `[REDACTED]` in error messages,
exception values, breadcrumb messages, and request URLs:
- `access_token`
- `password`
- `token`
- `refresh_token`
- `session_id`
- `sync_token`
- `next_batch`
- HTTP `Authorization` headers
**Code:** `src/instrument.ts` — `beforeSend` and `beforeBreadcrumb` callbacks
Regex: `/(access_token|password|token|refresh_token|session_id|sync_token|next_batch)([=:]\s*)([^\s&]+)/gi`
### Matrix Identifiers
Matrix IDs are replaced with placeholder tokens before sending:
| Original form | Replaced with |
| -------------- | ------------- |
| `@user:server` | `@[USER_ID]` |
| `!room:server` | `![ROOM_ID]` |
| `$event_id` | `$[EVENT_ID]` |
**Code:** `src/instrument.ts` — `beforeSend` callback (applied to `event.message`
and all `event.exception.values`)
---
## User Controls
Users can adjust Sentry behaviour without restarting the app:
| Setting | Location | `localStorage` key | Default |
| ----------------------------- | ---------------------------------------------------------------------------- | ---------------------------------- | ----------------- |
| Disable Sentry entirely | Settings → General → Diagnostics & Privacy | `sable_sentry_enabled` | Enabled |
| Enable session replay | Settings → General → Diagnostics & Privacy | `sable_sentry_replay_enabled` | Disabled (opt-in) |
| Disable breadcrumb categories | Settings → Developer Tools → Error Tracking (Sentry) → Breadcrumb Categories | `sable_sentry_breadcrumb_disabled` | All enabled |
**Rate limiting:** A maximum of 50 error events are forwarded to Sentry per page load (session).
Subsequent errors are silently dropped, protecting against quota exhaustion without affecting
in-app behaviour. Performance traces are not subject to this cap.
Changes to Sentry enable/disable and session replay take effect after the next page refresh
(the SDK is initialised once at startup). Breadcrumb category changes take effect immediately.
**Code:** `src/instrument.ts` — reads `localStorage` before `Sentry.init()`, enforces rate limit in `beforeSend`
**Code:** `src/app/features/settings/developer-tools/SentrySettings.tsx` — settings UI
**Code:** `src/app/utils/debugLogger.ts` — per-category breadcrumb filtering and session stats
---
## Data Residency
Sentry data is sent to the Sentry.io cloud service. The destination project is
configured by the operator via `VITE_SENTRY_DSN`. Self-hosted Sentry instances
are supported by changing the DSN.
When `VITE_SENTRY_DSN` is not set, the integration is entirely inactive — no
code path in the Sentry SDK is reached and no data is transmitted.
---
## Further Reading
- [SENTRY_INTEGRATION.md](./SENTRY_INTEGRATION.md) — setup, configuration, environment variables, and deployment instructions
- [Sentry Privacy Policy](https://sentry.io/privacy/) — Sentry's own data handling commitments
- [Sentry Session Replay privacy documentation](https://docs.sentry.io/product/explore/session-replay/privacy/) — details on masking and blocking behaviour
+137
View File
@@ -0,0 +1,137 @@
# Testing Guide
Sable uses [Vitest](https://vitest.dev/) as its test runner and [React Testing Library](https://testing-library.com/docs/react-testing-library/intro/) for component tests. Tests run in a [jsdom](https://github.com/jsdom/jsdom) environment and coverage is collected via V8.
---
## Running tests
```sh
# Watch mode — reruns affected tests on file save (recommended during development)
pnpm test
# Single run — equivalent to what CI runs
pnpm test:run
# With browser UI (interactive results viewer)
pnpm test:ui
# With coverage report
pnpm test:coverage
```
Coverage reports are written to `coverage/`. Open `coverage/index.html` in your browser for the full HTML report.
---
## Writing tests
### Where to put test files
Place test files next to the source file they cover, with a `.test.ts` or `.test.tsx` suffix:
```
src/app/utils/colorMXID.ts
src/app/utils/colorMXID.test.ts
src/app/features/room/RoomTimeline.tsx
src/app/features/room/RoomTimeline.test.tsx
```
### Testing plain utility functions
For pure functions in `src/app/utils/`, no special setup is needed — just import and assert:
```ts
import { describe, it, expect } from 'vitest';
import { bytesToSize } from './common';
describe('bytesToSize', () => {
it('converts bytes to KB', () => {
expect(bytesToSize(1500)).toBe('1.5 KB');
});
});
```
### Testing React components
Use `@testing-library/react` to render components inside the jsdom environment. Query by accessible role/text rather than CSS classes or implementation details:
```tsx
import { describe, it, expect } from 'vitest';
import { render, screen } from '@testing-library/react';
import userEvent from '@testing-library/user-event';
import { MyButton } from './MyButton';
describe('MyButton', () => {
it('calls onClick when pressed', async () => {
const user = userEvent.setup();
const onClick = vi.fn();
render(<MyButton onClick={onClick}>Click me</MyButton>);
await user.click(screen.getByRole('button', { name: 'Click me' }));
expect(onClick).toHaveBeenCalledOnce();
});
});
```
### Testing hooks
Use `renderHook` from `@testing-library/react`:
```ts
import { describe, it, expect } from 'vitest';
import { renderHook, act } from '@testing-library/react';
import { useMyHook } from './useMyHook';
describe('useMyHook', () => {
it('returns the expected initial value', () => {
const { result } = renderHook(() => useMyHook());
expect(result.current.value).toBe(0);
});
});
```
### Mocking
Vitest has Jest-compatible mocking APIs:
```ts
import { vi } from 'vitest';
// Mock a module
vi.mock('./someModule', () => ({ doThing: vi.fn(() => 'mocked') }));
// Spy on a method
const spy = vi.spyOn(console, 'error').mockImplementation(() => {});
// Restore after test
afterEach(() => vi.restoreAllMocks());
```
### Path aliases
All the project's path aliases work inside tests — you can import using `$utils/`, `$components/`, `$features/`, etc., just like in application code.
---
## What to test
Not every file needs tests. Focus on logic that would be painful to debug when broken:
| Worth testing | Less valuable |
| ----------------------------------------------- | ---------------------------------------------- |
| Pure utility functions (`src/app/utils/`) | Purely presentational components with no logic |
| Custom hooks with non-trivial state transitions | Thin wrappers around third-party APIs |
| State atoms and reducers | Generated or declarative config |
| Data transformation / formatting functions | |
When you fix a bug, consider adding a regression test that would have caught it — the description in the test is useful documentation.
---
## CI
`pnpm test:run` is part of the required quality checks and runs on every pull request alongside `lint`, `typecheck`, and `knip`. A PR with failing tests cannot be merged.
+2 -1
View File
@@ -23,7 +23,8 @@
property="og:description"
content="A Matrix client where you can enjoy the conversation using (not) simple, elegant and secure interface protected by e2ee with the power of open source. And colorful cosmetics. Because yes."
/>
<meta name="theme-color" content="#000000" />
<meta name="theme-color" media="(prefers-color-scheme: light)" content="#ffffff" />
<meta name="theme-color" media="(prefers-color-scheme: dark)" content="#1b1a21" />
<link id="favicon" rel="shortcut icon" href="./public/favicon.png" />
+3 -2
View File
@@ -7,8 +7,9 @@
},
"ignoreDependencies": [
"buffer",
"@element-hq/element-call-embedded",
"@matrix-org/matrix-sdk-crypto-wasm"
"@sableclient/sable-call-embedded",
"@matrix-org/matrix-sdk-crypto-wasm",
"@testing-library/user-event"
],
"ignoreBinaries": ["knope"],
"rules": {
+2 -2
View File
@@ -64,6 +64,6 @@ repo = "Sable"
[release_notes]
# The <!-- commit:$commit_hash --> marker is used by prepare-release.yml
change_templates = [
"### $summary <!-- commit:$commit_hash -->\n\n$details",
# "### $summary <!-- commit:$commit_hash -->\n\n$details",
"* $summary <!-- commit:$commit_hash -->",
]
]
+17 -3
View File
@@ -1,6 +1,6 @@
{
"name": "sable",
"version": "1.8.0",
"version": "1.9.2",
"description": "An almost stable Matrix client",
"type": "module",
"packageManager": "[email protected]+sha512.a706938f0e89ac1456b6563eab4edf1d1faf3368d1191fc5c59790e96dc918e4456ab2e67d613de1043d2e8c81f87303e6b40d4ffeca9df15ef1ad567348f2be",
@@ -17,6 +17,10 @@
"fmt": "prettier --write .",
"fmt:check": "prettier --check .",
"typecheck": "tsc",
"test": "vitest",
"test:ui": "vitest --ui",
"test:run": "vitest run",
"test:coverage": "vitest run --coverage",
"knip": "knip",
"knope": "knope",
"document-change": "knope document-change",
@@ -30,7 +34,9 @@
"@atlaskit/pragmatic-drag-and-drop-auto-scroll": "^1.4.0",
"@atlaskit/pragmatic-drag-and-drop-hitbox": "^1.1.0",
"@fontsource-variable/nunito": "5.2.7",
"@sentry/react": "^10.43.0",
"@fontsource/space-mono": "5.2.9",
"@phosphor-icons/react": "^2.1.10",
"@tanstack/react-query": "^5.90.21",
"@tanstack/react-query-devtools": "^5.91.3",
"@tanstack/react-virtual": "^3.13.19",
@@ -65,7 +71,7 @@
"linkify-react": "^4.3.2",
"linkifyjs": "^4.3.2",
"matrix-js-sdk": "^38.4.0",
"matrix-widget-api": "1.13.0",
"matrix-widget-api": "^1.16.1",
"millify": "^6.1.0",
"pdfjs-dist": "^5.4.624",
"prismjs": "^1.30.0",
@@ -89,12 +95,16 @@
},
"devDependencies": {
"@cloudflare/vite-plugin": "^1.26.0",
"@element-hq/element-call-embedded": "0.16.3",
"@sableclient/sable-call-embedded": "v1.1.3",
"@esbuild-plugins/node-globals-polyfill": "^0.2.3",
"@eslint/compat": "2.0.2",
"@eslint/js": "9.39.3",
"@rollup/plugin-inject": "^5.0.5",
"@rollup/plugin-wasm": "^6.2.2",
"@sentry/vite-plugin": "^5.1.1",
"@testing-library/jest-dom": "^6.9.1",
"@testing-library/react": "^16.3.2",
"@testing-library/user-event": "^14.6.1",
"@types/chroma-js": "^3.1.2",
"@types/file-saver": "^2.0.7",
"@types/is-hotkey": "^0.1.10",
@@ -106,12 +116,15 @@
"@types/sanitize-html": "^2.16.0",
"@types/ua-parser-js": "^0.7.39",
"@vitejs/plugin-react": "^5.1.4",
"@vitest/coverage-v8": "^4.1.0",
"@vitest/ui": "^4.1.0",
"buffer": "^6.0.3",
"eslint": "9.39.3",
"eslint-config-airbnb-extended": "3.0.1",
"eslint-config-prettier": "10.1.8",
"eslint-plugin-prettier": "5.5.5",
"globals": "17.3.0",
"jsdom": "^29.0.0",
"knip": "5.85.0",
"prettier": "3.8.1",
"typescript": "^5.9.3",
@@ -121,6 +134,7 @@
"vite-plugin-static-copy": "^3.2.0",
"vite-plugin-svgr": "4.5.0",
"vite-plugin-top-level-await": "^1.6.0",
"vitest": "^4.1.0",
"wrangler": "^4.70.0"
}
}
+1142 -12
View File
File diff suppressed because it is too large. Load diff
+3
View File
@@ -1,4 +1,5 @@
allowBuilds:
'@sentry/cli': true
'@swc/core': true
esbuild: true
sharp: true
@@ -6,6 +7,8 @@ allowBuilds:
workerd: true
engineStrict: true
minimumReleaseAge: 1440
minimumReleaseAgeExclude:
- '@sableclient/sable-call-embedded'
overrides:
brace-expansion: '>=1.1.12'
+2 -2
View File
@@ -7,8 +7,8 @@
"display": "standalone",
"orientation": "portrait",
"start_url": "./",
"background_color": "#fff",
"theme_color": "#fff",
"background_color": "#1b1a21",
"theme_color": "#1b1a21",
"icons": [
{
"src": "./public/android/android-chrome-36x36.png",
+8 -7
View File
@@ -9,8 +9,8 @@ import {
useCallThemeSync,
useCallMemberSoundSync,
} from '$hooks/useCallEmbed';
import { CallEmbed, useClientWidgetApiEvent, ElementWidgetActions } from '$plugins/call';
import { callChatAtom, callEmbedAtom } from '$state/callEmbed';
import { CallEmbed } from '$plugins/call';
import { useSelectedRoom } from '$hooks/router/useSelectedRoom';
import { ScreenSize, useScreenSizeContext } from '$hooks/useScreenSize';
import { IncomingCallModal } from './IncomingCallModal';
@@ -20,12 +20,13 @@ function CallUtils({ embed }: { embed: CallEmbed }) {
useCallMemberSoundSync(embed);
useCallThemeSync(embed);
useCallHangupEvent(
embed,
useCallback(() => {
setCallEmbed(undefined);
}, [setCallEmbed])
);
const handleCallEnd = useCallback(() => {
setCallEmbed(undefined);
}, [setCallEmbed]);
useCallHangupEvent(embed, handleCallEnd);
useClientWidgetApiEvent(embed.call, ElementWidgetActions.Close, handleCallEnd);
return null;
}
@@ -0,0 +1,99 @@
/**
* Integration tests: exercises the full config-load → setMatrixToBase → URL
* generation pipeline that App.tsx runs on startup.
*
* The pattern under test mirrors App.tsx:
* <ClientConfigLoader>
* {(config) => { setMatrixToBase(config.matrixToBaseUrl); ... }}
* </ClientConfigLoader>
*
* We mock fetch so we don't need a real config.json or a live matrix.to instance.
*/
import { describe, it, expect, vi, afterEach } from 'vitest';
import { render, screen, waitFor } from '@testing-library/react';
import { setMatrixToBase, getMatrixToRoom, getMatrixToUser } from '$plugins/matrix-to';
import { ClientConfigLoader } from './ClientConfigLoader';
afterEach(() => {
setMatrixToBase(); // reset module state to 'https://matrix.to'
vi.unstubAllGlobals();
});
const mockFetch = (config: object) =>
vi.stubGlobal('fetch', vi.fn().mockResolvedValue({ json: () => Promise.resolve(config) }));
describe('ClientConfigLoader + matrix-to wiring', () => {
it('generates a standard matrix.to URL when no custom base is configured', async () => {
mockFetch({});
render(
<ClientConfigLoader>
{(config) => {
setMatrixToBase(config.matrixToBaseUrl);
return <span data-testid="link">{getMatrixToRoom('!room:example.com')}</span>;
}}
</ClientConfigLoader>
);
await waitFor(() =>
expect(screen.getByTestId('link')).toHaveTextContent('https://matrix.to/#/!room:example.com')
);
});
it('generates a custom-base URL for rooms when matrixToBaseUrl is set', async () => {
mockFetch({ matrixToBaseUrl: 'https://custom.example.org' });
render(
<ClientConfigLoader>
{(config) => {
setMatrixToBase(config.matrixToBaseUrl);
return <span data-testid="link">{getMatrixToRoom('!room:example.com')}</span>;
}}
</ClientConfigLoader>
);
await waitFor(() =>
expect(screen.getByTestId('link')).toHaveTextContent(
'https://custom.example.org/#/!room:example.com'
)
);
});
it('generates a custom-base URL for users when matrixToBaseUrl is set', async () => {
mockFetch({ matrixToBaseUrl: 'https://custom.example.org' });
render(
<ClientConfigLoader>
{(config) => {
setMatrixToBase(config.matrixToBaseUrl);
return <span data-testid="user">{getMatrixToUser('@alice:example.com')}</span>;
}}
</ClientConfigLoader>
);
await waitFor(() =>
expect(screen.getByTestId('user')).toHaveTextContent(
'https://custom.example.org/#/@alice:example.com'
)
);
});
it('strips a trailing slash from matrixToBaseUrl', async () => {
mockFetch({ matrixToBaseUrl: 'https://custom.example.org/' });
render(
<ClientConfigLoader>
{(config) => {
setMatrixToBase(config.matrixToBaseUrl);
return <span data-testid="link">{getMatrixToRoom('!room:example.com')}</span>;
}}
</ClientConfigLoader>
);
await waitFor(() =>
expect(screen.getByTestId('link')).toHaveTextContent(
'https://custom.example.org/#/!room:example.com'
)
);
});
});
+48 -14
View File
@@ -1,9 +1,12 @@
import { Box, Button, Dialog, Icon, Icons, Text, color, config } from 'folds';
import * as Sentry from '@sentry/react';
import { SplashScreen } from '$components/splash-screen';
import { buildGitHubUrl } from '$features/bug-report/BugReportModal';
type ErrorPageProps = {
error: Error;
/** Sentry event ID — present when Sentry.ErrorBoundary captured the crash */
eventId?: string;
};
function createIssueUrl(error: Error): string {
@@ -29,7 +32,9 @@ ${stacktrace}
// It provides a user-friendly error message and options to report the issue or reload the page.
// Motivation of the design is to encourage users to report issues while also providing them with the necessary information to do so, and to give them an easy way to recover by reloading the page.
// Note: Since this component is rendered in response to an error, it should be as resilient as possible and avoid any complex logic or dependencies that could potentially throw additional errors.
export function ErrorPage({ error }: ErrorPageProps) {
export function ErrorPage({ error, eventId }: ErrorPageProps) {
const sentryEnabled = Sentry.isInitialized();
const reportedToSentry = sentryEnabled && !!eventId;
return (
<SplashScreen>
<Box grow="Yes" direction="Column" gap="400" alignItems="Center" justifyContent="Center">
@@ -52,20 +57,49 @@ export function ErrorPage({ error }: ErrorPageProps) {
<Text size="H2">Oops! Something went wrong</Text>
</Box>
<Text size="T300">
An unexpected error occurred. Please try again. If it continues, report the issue on
our GitHub using the button below, it will include error details to help us
investigate. Thank you for helping improve the app.
{reportedToSentry
? 'An unexpected error occurred. This crash has been automatically reported to our team. You can add more details to help us investigate.'
: 'An unexpected error occurred. Please try again. If it continues, report the issue on our GitHub using the button below, it will include error details to help us investigate. Thank you for helping improve the app.'}
</Text>
<Button
variant="Secondary"
onClick={() => window.open(createIssueUrl(error), '_blank', 'noopener noreferrer')}
fill="Solid"
title="Clicking this button will open a new issue on our GitHub repository with the error details pre-filled. Please review the information before submitting."
>
<Text as="span" size="B400">
Report Issue
</Text>
</Button>
{reportedToSentry ? (
<Box direction="Column" gap="200">
<Button
variant="Primary"
onClick={() => Sentry.showReportDialog({ eventId })}
fill="Solid"
title="Opens a short form so you can describe what you were doing before the crash. This helps our team fix the issue faster."
>
<Text as="span" size="B400">
Add Details to Report
</Text>
</Button>
<Button
variant="Secondary"
onClick={() =>
window.open(createIssueUrl(error), '_blank', 'noopener noreferrer')
}
fill="None"
title="Opens a pre-filled GitHub issue as an alternative reporting method."
>
<Text as="span" size="B400">
Also Report on GitHub
</Text>
</Button>
</Box>
) : (
<Button
variant="Secondary"
onClick={() =>
window.open(createIssueUrl(error), '_blank', 'noopener noreferrer')
}
fill="Solid"
title="Clicking this button will open a new issue on our GitHub repository with the error details pre-filled. Please review the information before submitting."
>
<Text as="span" size="B400">
Report Issue
</Text>
</Button>
)}
<Box
direction="Column"
gap="300"
+13
View File
@@ -22,6 +22,7 @@ import {
Text,
} from 'folds';
import FocusTrap from 'focus-trap-react';
import * as Sentry from '@sentry/react';
import {
useVerificationRequestPhase,
useVerificationRequestReceived,
@@ -246,6 +247,18 @@ export function DeviceVerification({ request, onExit }: DeviceVerificationProps)
await request.startVerification(VerificationMethod.Sas);
}, [request]);
useEffect(() => {
if (phase === VerificationPhase.Done) {
Sentry.metrics.count('sable.crypto.verification_outcome', 1, {
attributes: { outcome: 'completed' },
});
} else if (phase === VerificationPhase.Cancelled) {
Sentry.metrics.count('sable.crypto.verification_outcome', 1, {
attributes: { outcome: 'cancelled' },
});
}
}, [phase]);
return (
<Overlay open backdrop={<OverlayBackdrop />}>
<OverlayCenter>
@@ -70,7 +70,7 @@ function makeUIAAction<T>(
type SetupVerificationProps = {
onComplete: (recoveryKey: string) => void;
};
function SetupVerification({ onComplete }: SetupVerificationProps) {
function SetupVerification({ onComplete }: Readonly<SetupVerificationProps>) {
const mx = useMatrixClient();
const alive = useAlive();
@@ -227,7 +227,7 @@ function SetupVerification({ onComplete }: SetupVerificationProps) {
type RecoveryKeyDisplayProps = {
recoveryKey: string;
};
function RecoveryKeyDisplay({ recoveryKey }: RecoveryKeyDisplayProps) {
function RecoveryKeyDisplay({ recoveryKey }: Readonly<RecoveryKeyDisplayProps>) {
const [show, setShow] = useState(false);
const handleCopy = () => {
@@ -241,7 +241,7 @@ function RecoveryKeyDisplay({ recoveryKey }: RecoveryKeyDisplayProps) {
FileSaver.saveAs(blob, 'recovery-key.txt');
};
const safeToDisplayKey = show ? recoveryKey : recoveryKey.replace(/[^\s]/g, '*');
const safeToDisplayKey = show ? recoveryKey : recoveryKey.replaceAll(/[^\s]/g, '*');
return (
<Box direction="Column" gap="400">
+18
View File
@@ -19,14 +19,18 @@ import { getRoomAvatarUrl } from '$utils/room';
import { useRoomNavigate } from '$hooks/useRoomNavigate';
import FocusTrap from 'focus-trap-react';
import { stopPropagation } from '$utils/keyboard';
import * as Sentry from '@sentry/react';
import { useAtom, useSetAtom } from 'jotai';
import {
autoJoinCallIntentAtom,
incomingCallRoomIdAtom,
mutedCallRoomIdAtom,
} from '$state/callEmbed';
import { createDebugLogger } from '$utils/debugLogger';
import { RoomAvatar } from './room-avatar';
const debugLog = createDebugLogger('IncomingCall');
type IncomingCallInternalProps = {
room: any;
onClose: () => void;
@@ -41,6 +45,13 @@ export function IncomingCallInternal({ room, onClose }: IncomingCallInternalProp
const setMutedRoomId = useSetAtom(mutedCallRoomIdAtom);
const handleAnswer = () => {
debugLog.info('call', 'Incoming call answered', { roomId: room.roomId });
Sentry.addBreadcrumb({
category: 'call.signal',
message: 'Incoming call answered',
data: { roomId: room.roomId },
});
Sentry.metrics.count('sable.call.answered', 1);
setMutedRoomId(room.roomId);
setAutoJoinIntent(room.roomId);
onClose();
@@ -48,6 +59,13 @@ export function IncomingCallInternal({ room, onClose }: IncomingCallInternalProp
};
const handleDecline = async () => {
debugLog.info('call', 'Incoming call declined', { roomId: room.roomId });
Sentry.addBreadcrumb({
category: 'call.signal',
message: 'Incoming call declined',
data: { roomId: room.roomId },
});
Sentry.metrics.count('sable.call.declined', 1);
setMutedRoomId(room.roomId);
onClose();
};
+1 -1
View File
@@ -85,7 +85,7 @@ export const PdfViewer = as<'div', PdfViewerProps>(
if (docState.status !== AsyncStatus.Success) return;
const jumpInput = evt.currentTarget.jumpInput as HTMLInputElement;
if (!jumpInput) return;
const jumpTo = parseInt(jumpInput.value, 10);
const jumpTo = Number.parseInt(jumpInput.value, 10);
setPageNo(Math.max(1, Math.min(docState.data.numPages, jumpTo)));
setJumpAnchor(undefined);
};
+5 -3
View File
@@ -28,7 +28,7 @@ import {
VideoContent,
} from './message';
import { UrlPreviewCard, UrlPreviewHolder } from './url-preview';
import { Image, MediaControl, Video } from './media';
import { Image, MediaControl, PersistedVolumeVideo } from './media';
import { ImageViewer } from './image-viewer';
import { PdfViewer } from './Pdf-viewer';
import { TextViewer } from './text-viewer';
@@ -47,6 +47,7 @@ type RenderMessageContentProps = {
htmlReactParserOptions: HTMLReactParserOptions;
linkifyOpts: Opts;
outlineAttachment?: boolean;
hideCaption?: boolean;
};
const getMediaType = (url: string) => {
@@ -71,6 +72,7 @@ function RenderMessageContentInternal({
htmlReactParserOptions,
linkifyOpts,
outlineAttachment,
hideCaption,
}: RenderMessageContentProps) {
const content = useMemo(() => getContent<any>(), [getContent]);
@@ -121,7 +123,7 @@ function RenderMessageContentInternal({
const renderCaption = () => {
const hasCaption = content.body && content.body.trim().length > 0;
if (captionPosition === CaptionPosition.Hidden) return null;
if (captionPosition === CaptionPosition.Hidden || hideCaption) return null;
if (hasCaption && content.filename && content.filename !== content.body) {
if (captionPosition !== CaptionPosition.Inline)
return (
@@ -321,7 +323,7 @@ function RenderMessageContentInternal({
)
: undefined
}
renderVideo={(p) => <Video {...p} />}
renderVideo={(p) => <PersistedVolumeVideo {...p} />}
/>
)}
outlined={outlineAttachment}
+1
View File
@@ -9,6 +9,7 @@ export const Editor = style([
boxShadow: `inset 0 0 0 ${config.borderWidth.B300} ${color.SurfaceVariant.ContainerLine}`,
borderRadius: config.radii.R400,
overflow: 'hidden',
width: '100%',
},
]);
+2
View File
@@ -160,6 +160,8 @@ export const CustomEditor = forwardRef<HTMLDivElement, CustomEditorProps>(
onKeyDown={handleKeydown}
onKeyUp={onKeyUp}
onPaste={onPaste}
// Defer to OS capitalization setting (respects iOS sentence-case toggle).
autoCapitalize="sentences"
// keeps focus after pressing send.
onBlur={() => {
if (mobileOrTablet()) ReactEditor.focus(editor);
@@ -1,4 +1,4 @@
import { style } from '@vanilla-extract/css';
import { globalStyle, style } from '@vanilla-extract/css';
import { DefaultReset, color, config } from 'folds';
export const AutocompleteMenuBase = style([
@@ -38,3 +38,11 @@ export const AutocompleteNotice = style([
AutocompleteMenuHeader,
{ color: color.SurfaceVariant.OnContainer },
]);
export const AutocompleteMenuItems = style({});
globalStyle(`${AutocompleteMenuItems} button[data-selected='true']`, {
backgroundColor: color.SurfaceVariant.ContainerHover,
outline: `2px solid ${color.Primary.Main}`,
outlineOffset: -2,
});
@@ -1,6 +1,5 @@
import { ReactNode } from 'react';
import { ReactNode, useEffect, useLayoutEffect, useRef, useState } from 'react';
import FocusTrap from 'focus-trap-react';
import { isKeyHotkey } from 'is-hotkey';
import { Header, Menu, Scroll, config } from 'folds';
import { preventScrollWithArrowKey, stopPropagation } from '$utils/keyboard';
@@ -8,6 +7,9 @@ import { useAlive } from '$hooks/useAlive';
import * as css from './AutocompleteMenu.css';
import { BaseAutocompleteMenu } from './BaseAutocompleteMenu';
export const AUTOCOMPLETE_NAVIGATE_EVENT = 'autocomplete-navigate';
export type AutocompleteNavigateDetail = { direction: 1 | -1 };
type AutocompleteMenuProps = {
requestClose: () => void;
headerContent: ReactNode;
@@ -15,6 +17,9 @@ type AutocompleteMenuProps = {
};
export function AutocompleteMenu({ headerContent, requestClose, children }: AutocompleteMenuProps) {
const alive = useAlive();
const itemsRef = useRef<HTMLDivElement>(null);
const [selectedIndex, setSelectedIndex] = useState(0);
const prevButtonCountRef = useRef(-1);
const handleDeactivate = () => {
if (alive()) {
@@ -23,6 +28,41 @@ export function AutocompleteMenu({ headerContent, requestClose, children }: Auto
}
};
// Sync data-selected to DOM; reset to index 0 when the item list changes
useLayoutEffect(() => {
const buttons = Array.from(
itemsRef.current?.querySelectorAll<HTMLButtonElement>('button') ?? []
);
const count = buttons.length;
let idx = selectedIndex;
if (count !== prevButtonCountRef.current) {
prevButtonCountRef.current = count;
idx = 0;
if (selectedIndex !== 0) setSelectedIndex(0);
}
const safeIdx = Math.max(0, Math.min(idx, count - 1));
buttons.forEach((btn, i) => {
btn.setAttribute('data-selected', String(i === safeIdx));
});
}, [selectedIndex]);
// Listen for navigation events dispatched by the editor key handler
useEffect(() => {
const container = itemsRef.current?.closest('[data-autocomplete-menu]');
if (!container) return undefined;
const handler = (e: Event) => {
const { direction } = (e as CustomEvent<AutocompleteNavigateDetail>).detail;
setSelectedIndex((prev) => {
const buttons = itemsRef.current?.querySelectorAll('button') ?? [];
return Math.max(0, Math.min(prev + direction, buttons.length - 1));
});
};
container.addEventListener(AUTOCOMPLETE_NAVIGATE_EVENT, handler);
return () => container.removeEventListener(AUTOCOMPLETE_NAVIGATE_EVENT, handler);
}, []);
return (
<BaseAutocompleteMenu>
<FocusTrap
@@ -32,8 +72,6 @@ export function AutocompleteMenu({ headerContent, requestClose, children }: Auto
returnFocusOnDeactivate: false,
clickOutsideDeactivates: true,
allowOutsideClick: true,
isKeyForward: (evt: KeyboardEvent) => isKeyHotkey('arrowdown', evt),
isKeyBackward: (evt: KeyboardEvent) => isKeyHotkey('arrowup', evt),
escapeDeactivates: stopPropagation,
}}
>
@@ -42,7 +80,13 @@ export function AutocompleteMenu({ headerContent, requestClose, children }: Auto
{headerContent}
</Header>
<Scroll style={{ flexGrow: 1 }} onKeyDown={preventScrollWithArrowKey}>
<div style={{ padding: config.space.S200 }}>{children}</div>
<div
ref={itemsRef}
className={css.AutocompleteMenuItems}
style={{ padding: config.space.S200 }}
>
{children}
</div>
</Scroll>
</Menu>
</FocusTrap>
@@ -7,7 +7,9 @@ type BaseAutocompleteMenuProps = {
export function BaseAutocompleteMenu({ children }: BaseAutocompleteMenuProps) {
return (
<div className={css.AutocompleteMenuBase}>
<div className={css.AutocompleteMenuContainer}>{children}</div>
<div className={css.AutocompleteMenuContainer} data-autocomplete-menu="true">
{children}
</div>
</div>
);
}
@@ -1,5 +1,6 @@
import { KeyboardEvent as ReactKeyboardEvent, useEffect, useMemo } from 'react';
import { Editor } from 'slate';
import { ReactEditor } from 'slate-react';
import { Box, MenuItem, Text, toRem } from 'folds';
import { Room } from '$types/matrix-sdk';
@@ -57,13 +58,10 @@ export function EmoticonAutocomplete({
const [emojiThreshold] = useSetting(settingsAtom, 'emojiSuggestThreshold');
const searchList = useMemo(() => {
const list: Array<EmoticonSearchItem> = [];
return list.concat(
imagePacks.flatMap((pack) => pack.getImages(ImageUsage.Emoticon)),
emojis
);
}, [imagePacks]);
const searchList = useMemo<Array<EmoticonSearchItem>>(
() => [...imagePacks.flatMap((pack) => pack.getImages(ImageUsage.Emoticon)), ...emojis],
[imagePacks]
);
const [result, search, resetSearch] = useAsyncSearch(
searchList,
@@ -91,6 +89,7 @@ export function EmoticonAutocomplete({
const emoticonEl = createEmoticonElement(key, shortcode);
replaceWithElement(editor, query.range, emoticonEl);
moveCursor(editor, true);
ReactEditor.focus(editor);
requestClose();
});
@@ -1,5 +1,6 @@
import { KeyboardEvent as ReactKeyboardEvent, useCallback, useEffect } from 'react';
import { Editor } from 'slate';
import { ReactEditor } from 'slate-react';
import { Avatar, Icon, Icons, MenuItem, Text } from 'folds';
import { JoinRule, MatrixClient } from '$types/matrix-sdk';
import { useAtomValue } from 'jotai';
@@ -115,6 +116,7 @@ export function RoomMentionAutocomplete({
);
replaceWithElement(editor, query.range, mentionEl);
moveCursor(editor, true);
ReactEditor.focus(editor);
requestClose();
};
@@ -1,5 +1,6 @@
import { useEffect, KeyboardEvent as ReactKeyboardEvent } from 'react';
import { Editor } from 'slate';
import { ReactEditor } from 'slate-react';
import { Avatar, Icon, Icons, MenuItem, Text } from 'folds';
import { MatrixClient, Room, RoomMember } from '$types/matrix-sdk';
@@ -113,6 +114,7 @@ export function UserMentionAutocomplete({
);
replaceWithElement(editor, query.range, mentionEl);
moveCursor(editor, true);
ReactEditor.focus(editor);
requestClose();
};
+2 -2
View File
@@ -322,7 +322,7 @@ const parseHeadingNode = (
const headingMatch = node.name.match(/^h([123456])$/);
const [, g1AsLevel] = headingMatch ?? ['h3', '3'];
const level = parseInt(g1AsLevel, 10);
const level = Number.parseInt(g1AsLevel, 10);
const mdSequence = node.attribs['data-md'];
if (mdSequence !== undefined) {
@@ -334,7 +334,7 @@ const parseHeadingNode = (
return {
type: BlockType.Heading,
level: (level <= 3 ? level : 3) as HeadingLevel,
level: Math.min(level, 3) as HeadingLevel,
children,
};
};
+8 -5
View File
@@ -128,10 +128,13 @@ export const toMatrixCustomHTML = (
return `${parsedMarkdown}${toMatrixCustomHTML(n, { ...opts, allowBlockMarkdown: false })}`;
};
if (Array.isArray(node)) return node.map(parseNode).join('');
if (Array.isArray(node))
return node.map((element, index, array) => parseNode(element, index, array)).join('');
if (Text.isText(node)) return textToCustomHtml(node, opts);
const children = node.children.map(parseNode).join('');
const children = node.children
.map((element, index, array) => parseNode(element, index, array))
.join('');
return elementToCustomHtml(node, children);
};
@@ -193,14 +196,14 @@ export const toPlainText = (node: Descendant | Descendant[], isMarkdown: boolean
* @returns boolean
*/
export const customHtmlEqualsPlainText = (customHtml: string, plain: string): boolean =>
customHtml.replace(/<br\/>/g, '\n') === sanitizeText(plain);
customHtml.replaceAll('<br/>', '\n') === sanitizeText(plain);
export const trimCustomHtml = (customHtml: string) => customHtml.replace(/<br\/>$/g, '').trim();
export const trimCustomHtml = (customHtml: string) => customHtml.replaceAll(/<br\/>$/g, '').trim();
export const trimCommand = (cmdName: string, str: string) => {
const cmdRegX = new RegExp(`^(\\s+)?(\\/${sanitizeForRegex(cmdName)})([^\\S\n]+)?`);
const match = str.match(cmdRegX);
const match = new RegExp(cmdRegX).exec(str);
if (!match) return str;
return str.slice(match[0].length);
};
@@ -179,7 +179,7 @@ function EmojiSidebar({
packs,
saveStickerEmojiBandwidth,
onScrollToGroup,
}: EmojiSidebarProps) {
}: Readonly<EmojiSidebarProps>) {
const mx = useMatrixClient();
const useAuthentication = useMediaAuthentication();
@@ -264,7 +264,7 @@ function StickerSidebar({
packs,
saveStickerEmojiBandwidth,
onScrollToGroup,
}: StickerSidebarProps) {
}: Readonly<StickerSidebarProps>) {
const mx = useMatrixClient();
const useAuthentication = useMediaAuthentication();
@@ -316,7 +316,7 @@ function EmojiGroupHolder({
previewAtom,
onGroupItemClick,
children,
}: EmojiGroupHolderProps) {
}: Readonly<EmojiGroupHolderProps>) {
const setPreviewData = useSetAtom(previewAtom);
const handleEmojiPreview = useCallback(
@@ -397,7 +397,7 @@ export function EmojiBoard({
onStickerSelect,
allowTextCustomEmoji,
addToRecentEmoji = true,
}: EmojiBoardProps) {
}: Readonly<EmojiBoardProps>) {
const mx = useMatrixClient();
const [saveStickerEmojiBandwidth] = useSetting(settingsAtom, 'saveStickerEmojiBandwidth');
@@ -589,7 +589,7 @@ export function EmojiBoard({
id={SEARCH_GROUP_ID}
label={searchedItems.length ? 'Search Results' : 'No Results found'}
>
{searchedItems.map(renderItem)}
{searchedItems.map((element, index) => renderItem(element, index))}
</EmojiGroup>
)}
<div
@@ -121,7 +121,7 @@ export const EventHistory = as<'div', EventHistoryProps>(
[room, setReplyDraft]
);
function MenuOptions({ mEvent }: { mEvent: MatrixEvent }) {
function MenuOptions({ mEvent }: Readonly<{ mEvent: MatrixEvent }>) {
const setModal = useSetAtom(modalAtom);
return (
<Menu className={css.MenuOptions}>
@@ -177,7 +177,10 @@ export const EventHistory = as<'div', EventHistoryProps>(
);
}
function EventItem({ mEvent, EventContent }: { mEvent: MatrixEvent; EventContent: IContent }) {
function EventItem({
mEvent,
EventContent,
}: Readonly<{ mEvent: MatrixEvent; EventContent: IContent }>) {
const [isHovered, setIsHovered] = useState(false);
return (
<Box
+29 -1
View File
@@ -1,4 +1,4 @@
import { VideoHTMLAttributes, forwardRef } from 'react';
import { VideoHTMLAttributes, forwardRef, useEffect, useRef } from 'react';
import classNames from 'classnames';
import * as css from './media.css';
@@ -8,3 +8,31 @@ export const Video = forwardRef<HTMLVideoElement, VideoHTMLAttributes<HTMLVideoE
<video className={classNames(css.Video, className)} {...props} ref={ref} />
)
);
export const MEDIA_VOLUME_KEY = 'mediaVolume';
export function PersistedVolumeVideo({
onVolumeChange,
...props
}: VideoHTMLAttributes<HTMLVideoElement>) {
const innerRef = useRef<HTMLVideoElement>(null);
useEffect(() => {
const stored = localStorage.getItem(MEDIA_VOLUME_KEY);
if (innerRef.current && stored !== null) {
const parsed = parseFloat(stored);
if (!Number.isNaN(parsed)) innerRef.current.volume = parsed;
}
}, []);
return (
<Video
{...props}
ref={innerRef}
onVolumeChange={(e) => {
localStorage.setItem(MEDIA_VOLUME_KEY, String((e.target as HTMLVideoElement).volume));
onVolumeChange?.(e);
}}
/>
);
}
@@ -121,7 +121,7 @@ export function MText({ edited, content, renderBody, renderUrlsPreview, style }:
return true;
}, [trimmedBody, safeCustomBody]);
if (!body) return <BrokenContent body={customBody ?? body} />;
if (!body && !customBody) return <BrokenContent body={customBody ?? body} />;
const urlsMatch = renderUrlsPreview && trimmedBody.match(URL_REG);
const urls = urlsMatch ? [...new Set(urlsMatch)] : undefined;
+3 -2
View File
@@ -19,12 +19,13 @@ export function RenderBody({
highlightRegex,
htmlReactParserOptions,
linkifyOpts,
}: RenderBodyProps) {
if (body === '') return <MessageEmptyContent />;
}: Readonly<RenderBodyProps>) {
if (customBody) {
if (customBody === '') return <MessageEmptyContent />;
return parse(sanitizeCustomHtml(customBody), htmlReactParserOptions);
}
if (body === '') return <MessageEmptyContent />;
return (
<Linkify options={linkifyOpts}>
{highlightRegex
+10 -8
View File
@@ -68,10 +68,10 @@ export const ThreadIndicator = as<'div'>(({ ...props }, ref) => (
type ReplyProps = {
room: Room;
timelineSet?: EventTimelineSet | undefined;
timelineSet?: EventTimelineSet;
replyEventId: string;
threadRootId?: string | undefined;
onClick?: MouseEventHandler | undefined;
threadRootId?: string;
onClick?: MouseEventHandler;
};
export const Reply = as<'div', ReplyProps>(
@@ -119,10 +119,12 @@ export const Reply = as<'div', ReplyProps>(
if (format === 'org.matrix.custom.html' && formattedBody) {
const strippedHtml = trimReplyFromFormattedBody(formattedBody)
.replace(/<br\s*\/?>/gi, ' ')
.replace(/<\/p>\s*<p[^>]*>/gi, ' ')
.replace(/<\/?p[^>]*>/gi, '')
.replace(/(?:\r\n|\r|\n)/g, ' ');
.replaceAll(/<br\s*\/?>/gi, ' ')
.replaceAll(/<\/p>\s*<p[^>]*>/gi, ' ')
.replaceAll(/<\/?p[^>]*>/gi, '')
.replaceAll(/<\/li>\s*<li[^>]*>/gi, ' ')
.replaceAll(/<\/?(ul|ol|li|blockquote|h[1-6]|pre|div)[^>]*>/gi, '')
.replaceAll(/(?:\r\n|\r|\n)/g, ' ');
const parserOpts = getReactCustomHtmlParser(mx, room.roomId, {
linkifyOpts: LINKIFY_OPTS,
useAuthentication,
@@ -130,7 +132,7 @@ export const Reply = as<'div', ReplyProps>(
});
bodyJSX = parse(strippedHtml, parserOpts) as JSX.Element;
} else if (body) {
const strippedBody = trimReplyFromBody(body).replace(/(?:\r\n|\r|\n)/g, ' ');
const strippedBody = trimReplyFromBody(body).replaceAll(/(?:\r\n|\r|\n)/g, ' ');
bodyJSX = scaleSystemEmoji(strippedBody);
}
@@ -1,5 +1,5 @@
/* eslint-disable jsx-a11y/media-has-caption */
import { ReactNode, useCallback, useRef, useState } from 'react';
import { ReactNode, useCallback, useEffect, useRef, useState } from 'react';
import { Badge, Chip, Icon, IconButton, Icons, ProgressBar, Spinner, Text, toRem } from 'folds';
import { EncryptedAttachmentInfo } from 'browser-encrypt-attachment';
import { Range } from 'react-range';
@@ -18,6 +18,7 @@ import { useThrottle } from '$hooks/useThrottle';
import { secondsToMinutesAndSeconds } from '$utils/common';
import { decryptFile, downloadEncryptedMedia, downloadMedia, mxcUrlToHttp } from '$utils/matrix';
import { useMediaAuthentication } from '$hooks/useMediaAuthentication';
import { MEDIA_VOLUME_KEY } from '$components/media';
const PLAY_TIME_THROTTLE_OPS = {
wait: 500,
@@ -60,6 +61,14 @@ export function AudioContent({
const audioRef = useRef<HTMLAudioElement | null>(null);
useEffect(() => {
const stored = localStorage.getItem(MEDIA_VOLUME_KEY);
if (audioRef.current && stored !== null) {
const parsed = parseFloat(stored);
if (!Number.isNaN(parsed)) audioRef.current.volume = parsed;
}
}, []);
const [currentTime, setCurrentTime] = useState(0);
// duration in seconds. (NOTE: info.duration is in milliseconds)
const infoDuration = info.duration ?? 0;
@@ -95,34 +104,41 @@ export function AudioContent({
max={duration || 1}
values={[currentTime]}
onChange={(values) => seek(values[0])}
renderTrack={(params) => (
<div {...params.props}>
{params.children}
<ProgressBar
as="div"
variant="Secondary"
renderTrack={(params) => {
const { key, ...restProps } = params.props as any;
return (
<div key={key} {...restProps}>
{params.children}
<ProgressBar
as="div"
variant="Secondary"
size="300"
min={0}
max={duration}
value={currentTime}
radii="300"
/>
</div>
);
}}
renderThumb={(params) => {
const { key, style, ...restProps } = params.props as any;
return (
<Badge
key={key}
size="300"
min={0}
max={duration}
value={currentTime}
radii="300"
variant="Secondary"
fill="Solid"
radii="Pill"
outlined
{...restProps}
style={{
...style,
zIndex: 0,
}}
/>
</div>
)}
renderThumb={(params) => (
<Badge
size="300"
variant="Secondary"
fill="Solid"
radii="Pill"
outlined
{...params.props}
style={{
...params.props.style,
zIndex: 0,
}}
/>
)}
);
}}
/>
),
leftControl: (
@@ -165,39 +181,53 @@ export function AudioContent({
max={1}
values={[volume]}
onChange={(values) => setVolume(values[0])}
renderTrack={(params) => (
<div {...params.props}>
{params.children}
<ProgressBar
style={{ width: toRem(48) }}
variant="Secondary"
renderTrack={(params) => {
const { key, ...restProps } = params.props as any;
return (
<div key={key} {...restProps}>
{params.children}
<ProgressBar
style={{ width: toRem(48) }}
variant="Secondary"
size="300"
min={0}
max={1}
value={volume}
radii="300"
/>
</div>
);
}}
renderThumb={(params) => {
const { key, style, ...restProps } = params.props as any;
return (
<Badge
key={key}
size="300"
min={0}
max={1}
value={volume}
radii="300"
variant="Secondary"
fill="Solid"
radii="Pill"
outlined
{...restProps}
style={{
...style,
zIndex: 0,
}}
/>
</div>
)}
renderThumb={(params) => (
<Badge
size="300"
variant="Secondary"
fill="Solid"
radii="Pill"
outlined
{...params.props}
style={{
...params.props.style,
zIndex: 0,
}}
/>
)}
);
}}
/>
</>
),
children: (
<audio controls={false} autoPlay ref={audioRef}>
<audio
controls={false}
autoPlay
ref={audioRef}
onVolumeChange={(e) => {
localStorage.setItem(MEDIA_VOLUME_KEY, String((e.target as HTMLAudioElement).volume));
}}
>
{srcState.status === AsyncStatus.Success && <source src={srcState.data} type={mimeType} />}
</audio>
),
@@ -6,6 +6,8 @@ import {
Chip,
Icon,
Icons,
Menu,
MenuItem,
Modal,
Overlay,
OverlayBackdrop,
@@ -15,6 +17,7 @@ import {
Tooltip,
TooltipProvider,
as,
config,
} from 'folds';
import classNames from 'classnames';
import { BlurhashCanvas } from 'react-blurhash';
@@ -62,6 +65,7 @@ export const ImageContent = as<'div', ImageContentProps>(
(
{
className,
style,
body,
mimeType,
url,
@@ -84,6 +88,7 @@ export const ImageContent = as<'div', ImageContentProps>(
const [error, setError] = useState(false);
const [viewer, setViewer] = useState(false);
const [blurred, setBlurred] = useState(markedAsSpoiler ?? false);
const [isHovered, setIsHovered] = useState(false);
const [srcState, loadSrc] = useAsyncCallback(
useCallback(async () => {
@@ -118,8 +123,20 @@ export const ImageContent = as<'div', ImageContentProps>(
if (autoPlay) loadSrc();
}, [autoPlay, loadSrc]);
const hasDimensions = typeof info?.w === 'number' && typeof info?.h === 'number';
return (
<Box className={classNames(css.RelativeBase, className)} {...props} ref={ref}>
<Box
className={classNames(css.RelativeBase, className)}
style={{
...(hasDimensions ? { aspectRatio: `${info.w} / ${info.h}` } : { minHeight: '150px' }),
...style,
}}
{...props}
ref={ref}
onPointerEnter={() => setIsHovered(true)}
onPointerLeave={() => setIsHovered(false)}
>
{srcState.status === AsyncStatus.Success && (
<Overlay open={viewer} backdrop={<OverlayBackdrop />}>
<OverlayCenter>
@@ -156,7 +173,12 @@ export const ImageContent = as<'div', ImageContentProps>(
/>
)}
{!autoPlay && !markedAsSpoiler && srcState.status === AsyncStatus.Idle && (
<Box className={css.AbsoluteContainer} alignItems="Center" justifyContent="Center">
<Box
className={css.AbsoluteContainer}
alignItems="Center"
justifyContent="Center"
onClick={loadSrc}
>
<Button
variant="Secondary"
fill="Solid"
@@ -170,7 +192,12 @@ export const ImageContent = as<'div', ImageContentProps>(
</Box>
)}
{srcState.status === AsyncStatus.Success && (
<Box className={classNames(css.AbsoluteContainer, blurred && css.Blur)}>
<Box
className={classNames(
hasDimensions ? css.AbsoluteContainer : undefined,
blurred && css.Blur
)}
>
{renderImage({
alt: body,
title: body,
@@ -183,36 +210,35 @@ export const ImageContent = as<'div', ImageContentProps>(
</Box>
)}
{blurred && !error && srcState.status !== AsyncStatus.Error && (
<Box className={css.AbsoluteContainer} alignItems="Center" justifyContent="Center">
<TooltipProvider
tooltip={
typeof spoilerReason === 'string' && (
<Tooltip variant="Secondary">
<Text>{spoilerReason}</Text>
</Tooltip>
)
<Box
className={css.AbsoluteContainer}
alignItems="Center"
justifyContent="Center"
onClick={() => {
setBlurred(false);
if (srcState.status === AsyncStatus.Idle) {
loadSrc();
}
position="Top"
align="Center"
}}
>
<Chip
variant="Secondary"
radii="Pill"
size="500"
outlined
onClick={() => {
setBlurred(false);
if (srcState.status === AsyncStatus.Idle) {
loadSrc();
}
}}
>
{(triggerRef) => (
<Chip
ref={triggerRef}
variant="Secondary"
radii="Pill"
size="500"
outlined
onClick={() => {
setBlurred(false);
if (srcState.status === AsyncStatus.Idle) {
loadSrc();
}
}}
>
<Text size="B300">Spoiler</Text>
</Chip>
)}
</TooltipProvider>
<Text size="B300">
{typeof spoilerReason === 'string' && spoilerReason.length > 0
? `Spoiler reason: ${spoilerReason}`
: `Spoilered`}
</Text>
</Chip>
</Box>
)}
{(srcState.status === AsyncStatus.Loading || srcState.status === AsyncStatus.Success) &&
@@ -223,7 +249,12 @@ export const ImageContent = as<'div', ImageContentProps>(
</Box>
)}
{(error || srcState.status === AsyncStatus.Error) && (
<Box className={css.AbsoluteContainer} alignItems="Center" justifyContent="Center">
<Box
className={css.AbsoluteContainer}
alignItems="Center"
justifyContent="Center"
onClick={handleRetry}
>
<TooltipProvider
tooltip={
<Tooltip variant="Critical">
@@ -250,6 +281,27 @@ export const ImageContent = as<'div', ImageContentProps>(
</TooltipProvider>
</Box>
)}
{isHovered && (
<Box style={{ padding: config.space.S200, right: 0, position: 'absolute' }}>
<Menu style={{ padding: config.space.S0 }}>
<MenuItem
size="300"
after={<Icon size="200" src={blurred ? Icons.Eye : Icons.EyeBlind} />}
radii="300"
fill="Soft"
variant="Secondary"
title={blurred ? 'Reveal Image' : 'Hide Image'}
onClick={(e) => {
e.preventDefault();
if (srcState.status === AsyncStatus.Idle) {
loadSrc();
setBlurred(false);
} else setBlurred(!blurred);
}}
/>
</Menu>
</Box>
)}
{!load && typeof info?.size === 'number' && (
<Box className={css.AbsoluteFooter} justifyContent="End" alignContent="Center" gap="200">
<Badge variant="Secondary" fill="Soft">
@@ -6,11 +6,14 @@ import {
Chip,
Icon,
Icons,
Menu,
MenuItem,
Spinner,
Text,
Tooltip,
TooltipProvider,
as,
config,
} from 'folds';
import classNames from 'classnames';
import { BlurhashCanvas } from 'react-blurhash';
@@ -73,6 +76,7 @@ export const VideoContent = as<'div', VideoContentProps>(
const [load, setLoad] = useState(false);
const [error, setError] = useState(false);
const [blurred, setBlurred] = useState(markedAsSpoiler ?? false);
const [isHovered, setIsHovered] = useState(false);
const [srcState, loadSrc] = useAsyncCallback(
useCallback(async () => {
@@ -107,7 +111,13 @@ export const VideoContent = as<'div', VideoContentProps>(
}, [autoPlay, loadSrc]);
return (
<Box className={classNames(css.RelativeBase, className)} {...props} ref={ref}>
<Box
className={classNames(css.RelativeBase, className)}
{...props}
ref={ref}
onPointerEnter={() => setIsHovered(true)}
onPointerLeave={() => setIsHovered(false)}
>
{typeof blurHash === 'string' && !load && (
<BlurhashCanvas
style={{ width: '100%', height: '100%' }}
@@ -127,7 +137,12 @@ export const VideoContent = as<'div', VideoContentProps>(
</Box>
)}
{!autoPlay && !blurred && srcState.status === AsyncStatus.Idle && (
<Box className={css.AbsoluteContainer} alignItems="Center" justifyContent="Center">
<Box
className={css.AbsoluteContainer}
alignItems="Center"
justifyContent="Center"
onClick={loadSrc}
>
<Button
variant="Secondary"
fill="Solid"
@@ -147,39 +162,41 @@ export const VideoContent = as<'div', VideoContentProps>(
src: srcState.data,
onLoadedMetadata: handleLoad,
onError: handleError,
autoPlay: true,
autoPlay: false,
controls: true,
})}
</Box>
)}
{blurred && !error && srcState.status !== AsyncStatus.Error && (
<Box className={css.AbsoluteContainer} alignItems="Center" justifyContent="Center">
<TooltipProvider
tooltip={
typeof spoilerReason === 'string' && (
<Tooltip variant="Secondary">
<Text>{spoilerReason}</Text>
</Tooltip>
)
<Box
className={css.AbsoluteContainer}
alignItems="Center"
justifyContent="Center"
onClick={() => {
setBlurred(false);
if (srcState.status === AsyncStatus.Idle) {
loadSrc();
}
position="Top"
align="Center"
}}
>
<Chip
variant="Secondary"
radii="Pill"
size="500"
outlined
onClick={() => {
setBlurred(false);
if (srcState.status === AsyncStatus.Idle) {
loadSrc();
}
}}
>
{(triggerRef) => (
<Chip
ref={triggerRef}
variant="Secondary"
radii="Pill"
size="500"
outlined
onClick={() => {
setBlurred(false);
}}
>
<Text size="B300">Spoiler</Text>
</Chip>
)}
</TooltipProvider>
<Text size="B300">
{typeof spoilerReason === 'string' && spoilerReason.length > 0
? `Spoiler reason: ${spoilerReason}`
: `Spoilered`}
</Text>
</Chip>
</Box>
)}
{(srcState.status === AsyncStatus.Loading || srcState.status === AsyncStatus.Success) &&
@@ -190,7 +207,12 @@ export const VideoContent = as<'div', VideoContentProps>(
</Box>
)}
{(error || srcState.status === AsyncStatus.Error) && (
<Box className={css.AbsoluteContainer} alignItems="Center" justifyContent="Center">
<Box
className={css.AbsoluteContainer}
alignItems="Center"
justifyContent="Center"
onClick={handleRetry}
>
<TooltipProvider
tooltip={
<Tooltip variant="Critical">
@@ -217,6 +239,27 @@ export const VideoContent = as<'div', VideoContentProps>(
</TooltipProvider>
</Box>
)}
{isHovered && (
<Box style={{ padding: config.space.S200, right: 0, position: 'absolute' }}>
<Menu style={{ padding: config.space.S0 }}>
<MenuItem
size="300"
after={<Icon size="200" src={blurred ? Icons.Eye : Icons.EyeBlind} />}
radii="300"
fill="Soft"
variant="Secondary"
title={blurred ? 'Reveal Video' : 'Hide Video'}
onClick={(e) => {
e.preventDefault();
if (srcState.status === AsyncStatus.Idle) {
loadSrc();
setBlurred(false);
} else setBlurred(!blurred);
}}
/>
</Menu>
</Box>
)}
{!load && typeof info.size === 'number' && (
<Box
className={css.AbsoluteFooter}
@@ -20,6 +20,10 @@ import { useMatrixClient } from '$hooks/useMatrixClient';
import { AsyncStatus, useAsyncCallback } from '$hooks/useAsyncCallback';
import { modalAtom, ModalType } from '$state/modal';
import * as css from '$features/room/message/styles.css';
import { createDebugLogger } from '$utils/debugLogger';
import * as Sentry from '@sentry/react';
const debugLog = createDebugLogger('MessageDelete');
export function MessageDeleteItem({ room, mEvent }: { room: Room; mEvent: MatrixEvent }) {
const setModal = useSetAtom(modalAtom);
@@ -67,9 +71,15 @@ export function MessageDeleteInternal({ room, mEvent, onClose }: MessageDeleteIn
useEffect(() => {
if (deleteState.status === AsyncStatus.Success) {
debugLog.info('ui', 'Message deleted successfully', { roomId: room.roomId });
Sentry.metrics.count('sable.message.delete.success', 1);
onClose();
}
}, [deleteState.status, onClose]);
if (deleteState.status === AsyncStatus.Error) {
debugLog.error('ui', 'Message delete failed', { roomId: room.roomId });
Sentry.metrics.count('sable.message.delete.error', 1);
}
}, [deleteState.status, room.roomId, onClose]);
const handleSubmit: FormEventHandler<HTMLFormElement> = (evt) => {
evt.preventDefault();
@@ -85,6 +95,8 @@ export function MessageDeleteInternal({ room, mEvent, onClose }: MessageDeleteIn
const reasonInput = target?.reasonInput as HTMLInputElement | undefined;
const reason = reasonInput && reasonInput.value.trim();
debugLog.info('ui', 'Deleting message', { eventId, hasReason: !!reason });
Sentry.metrics.count('sable.message.delete.attempt', 1);
deleteMessage(eventId, reason);
};
@@ -26,6 +26,10 @@ import * as css from '$features/room/message/styles.css';
import { sanitizeCustomHtml } from '$utils/sanitize';
import { getStateEvents } from '$utils/room';
import { StateEvent } from '$types/matrix/room';
import { createDebugLogger } from '$utils/debugLogger';
import * as Sentry from '@sentry/react';
const debugLog = createDebugLogger('MessageForward');
// Message forwarding component
export const MessageForwardItem = as<'button', MessageForwardItemProps>(
@@ -263,9 +267,30 @@ export function MessageForwardInternal({
};
}
const msgtype = String(originalContent.msgtype ?? 'unknown');
debugLog.info('ui', 'Forwarding message', {
sourceRoomId: room.roomId,
targetRoomId: targetRoom.roomId,
msgtype,
isPrivate,
});
Sentry.metrics.count('sable.message.forward.attempt', 1, { attributes: { msgtype } });
mx.sendEvent(targetRoom.roomId, null, eventType, content as unknown as SendEventContent)
.then(() => setIsForwardSuccess(true))
.catch(() => {
.then(() => {
debugLog.info('ui', 'Message forwarded successfully', {
sourceRoomId: room.roomId,
targetRoomId: targetRoom.roomId,
});
Sentry.metrics.count('sable.message.forward.success', 1);
setIsForwardSuccess(true);
})
.catch((err: unknown) => {
debugLog.error('ui', 'Message forward failed', {
sourceRoomId: room.roomId,
targetRoomId: targetRoom.roomId,
error: err instanceof Error ? err.message : String(err),
});
Sentry.metrics.count('sable.message.forward.error', 1);
setIsForwarding(false);
setIsForwardSuccess(false);
setIsForwardError(true);
@@ -1,4 +1,4 @@
import { FormEventHandler, MouseEvent, useCallback } from 'react';
import { FormEventHandler, MouseEvent, useCallback, useEffect } from 'react';
import { Room, MatrixEvent } from '$types/matrix-sdk';
import { useSetAtom } from 'jotai';
import {
@@ -20,6 +20,10 @@ import { useMatrixClient } from '$hooks/useMatrixClient';
import { AsyncStatus, useAsyncCallback } from '$hooks/useAsyncCallback';
import * as css from '$features/room/message/styles.css';
import { modalAtom, ModalType } from '$state/modal';
import { createDebugLogger } from '$utils/debugLogger';
import * as Sentry from '@sentry/react';
const debugLog = createDebugLogger('MessageReport');
export function MessageReportItem({ room, mEvent }: { room: Room; mEvent: MatrixEvent }) {
const setModal = useSetAtom(modalAtom);
@@ -65,6 +69,17 @@ export function MessageReportInternal({ room, mEvent, onClose }: MessageReportIn
)
);
useEffect(() => {
if (reportState.status === AsyncStatus.Success) {
debugLog.info('ui', 'Message reported successfully', { roomId: room.roomId });
Sentry.metrics.count('sable.message.report.success', 1);
}
if (reportState.status === AsyncStatus.Error) {
debugLog.error('ui', 'Message report failed', { roomId: room.roomId });
Sentry.metrics.count('sable.message.report.error', 1);
}
}, [reportState.status, room.roomId]);
const handleSubmit: FormEventHandler<HTMLFormElement> = (evt) => {
evt.preventDefault();
const eventId = mEvent.getId();
@@ -79,6 +94,8 @@ export function MessageReportInternal({ room, mEvent, onClose }: MessageReportIn
const reasonInput = target?.reasonInput as HTMLInputElement | undefined;
const reason = reasonInput && reasonInput.value.trim();
debugLog.info('ui', 'Reporting message', { eventId, hasReason: !!reason });
Sentry.metrics.count('sable.message.report.attempt', 1);
reportMessage(eventId, reason ? -100 : -50, reason || 'No reason provided');
};
+51 -4
View File
@@ -1,5 +1,5 @@
import { AvatarImage as FoldsAvatarImage } from 'folds';
import { ReactEventHandler, useState } from 'react';
import { ReactEventHandler, useState, useEffect } from 'react';
import bgColorImg from '$utils/bgColorImg';
import { settingsAtom } from '$state/settings';
import { useSetting } from '$state/hooks/settings';
@@ -15,20 +15,67 @@ type AvatarImageProps = {
export function AvatarImage({ src, alt, uniformIcons, onError }: AvatarImageProps) {
const [uniformIconsSetting] = useSetting(settingsAtom, 'uniformIcons');
const [image, setImage] = useState<HTMLImageElement | undefined>(undefined);
const normalizedBg = image ? bgColorImg(image) : undefined;
const [processedSrc, setProcessedSrc] = useState<string>(src);
const useUniformIcons = uniformIconsSetting && uniformIcons === true;
const normalizedBg = useUniformIcons && image ? bgColorImg(image) : undefined;
useEffect(() => {
let isMounted = true;
let objectUrl: string | null = null;
const processImage = async () => {
try {
const res = await fetch(src, { mode: 'cors' });
const contentType = res.headers.get('content-type');
if (contentType && contentType.includes('image/svg+xml')) {
const text = await res.text();
const parser = new DOMParser();
const doc = parser.parseFromString(text, 'image/svg+xml');
const animations = doc.querySelectorAll('animate, animateTransform, animateMotion');
animations.forEach((anim) => anim.setAttribute('repeatCount', 'indefinite'));
const style = doc.createElementNS('http://www.w3.org/2000/svg', 'style');
style.textContent = '* { animation-iteration-count: infinite !important; }';
doc.documentElement.appendChild(style);
const serializer = new XMLSerializer();
const newSvgString = serializer.serializeToString(doc);
const blob = new Blob([newSvgString], { type: 'image/svg+xml' });
objectUrl = URL.createObjectURL(blob);
if (isMounted) setProcessedSrc(objectUrl);
} else if (isMounted) setProcessedSrc(src);
} catch {
if (isMounted) setProcessedSrc(src);
}
};
processImage();
return () => {
isMounted = false;
if (objectUrl) {
URL.revokeObjectURL(objectUrl);
}
};
}, [src]);
const handleLoad: ReactEventHandler<HTMLImageElement> = (evt) => {
evt.currentTarget.setAttribute('data-image-loaded', 'true');
setImage(evt.currentTarget);
};
const isBlobUrl = processedSrc.startsWith('blob:');
return (
<FoldsAvatarImage
className={css.RoomAvatar}
style={{ backgroundColor: useUniformIcons ? normalizedBg : undefined }}
src={src}
crossOrigin="anonymous"
src={processedSrc}
crossOrigin={isBlobUrl ? undefined : 'anonymous'}
alt={alt}
onError={() => {
setImage(undefined);
+4 -4
View File
@@ -134,8 +134,8 @@ export const SidebarItemBadge = recipe({
left: toRem(-6),
},
false: {
top: toRem(-2),
left: toRem(-2),
top: toRem(-4),
left: toRem(-4),
},
},
},
@@ -167,9 +167,9 @@ export const SidebarItemBadge = recipe({
style: {
selectors: {
'div:has(> button[data-id]) &': {
top: toRem(2),
top: toRem(0),
left: 'auto',
right: toRem(2),
right: toRem(0),
},
},
},
@@ -0,0 +1,82 @@
import { keyframes, style } from '@vanilla-extract/css';
import { color, config, toRem } from 'folds';
const slideUp = keyframes({
from: {
opacity: 0,
transform: 'translateY(100%)',
},
to: {
opacity: 1,
transform: 'translateY(0)',
},
});
const slideDown = keyframes({
from: {
opacity: 1,
transform: 'translateY(0)',
},
to: {
opacity: 0,
transform: 'translateY(100%)',
},
});
export const Container = style({
position: 'fixed',
bottom: 'env(safe-area-inset-bottom, 0)',
left: '50%',
transform: 'translateX(-50%)',
zIndex: 9998,
width: `min(100%, ${toRem(520)})`,
padding: config.space.S400,
pointerEvents: 'none',
});
export const Banner = style({
pointerEvents: 'all',
display: 'flex',
flexDirection: 'column',
gap: config.space.S300,
backgroundColor: color.Surface.Container,
color: color.Surface.OnContainer,
border: `${config.borderWidth.B300} solid ${color.Surface.ContainerLine}`,
borderRadius: toRem(16),
padding: config.space.S400,
boxShadow: `0 ${toRem(8)} ${toRem(32)} rgba(0, 0, 0, 0.45), 0 ${toRem(2)} ${toRem(8)} rgba(0, 0, 0, 0.3)`,
animationName: slideUp,
animationDuration: '300ms',
animationTimingFunction: 'cubic-bezier(0.22, 0.8, 0.6, 1)',
animationFillMode: 'both',
selectors: {
'&[data-dismissing=true]': {
animationName: slideDown,
animationDuration: '220ms',
animationTimingFunction: 'cubic-bezier(0.4, 0, 1, 1)',
animationFillMode: 'both',
},
},
});
export const Header = style({
display: 'flex',
alignItems: 'flex-start',
gap: config.space.S300,
});
export const HeaderText = style({
flex: 1,
minWidth: 0,
display: 'flex',
flexDirection: 'column',
gap: toRem(4),
});
export const Actions = style({
display: 'flex',
gap: config.space.S200,
justifyContent: 'flex-end',
flexWrap: 'wrap',
});
@@ -0,0 +1,95 @@
import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest';
import { render, screen, fireEvent } from '@testing-library/react';
import { TelemetryConsentBanner } from './TelemetryConsentBanner';
const SENTRY_KEY = 'sable_sentry_enabled';
const TEST_DSN = 'https://[email protected]/0';
describe('TelemetryConsentBanner', () => {
beforeEach(() => {
localStorage.clear();
vi.stubGlobal('location', { reload: vi.fn() });
});
afterEach(() => {
vi.unstubAllEnvs();
vi.unstubAllGlobals();
});
// ── visibility ────────────────────────────────────────────────────────────
it('renders nothing when VITE_SENTRY_DSN is not configured', () => {
vi.stubEnv('VITE_SENTRY_DSN', '');
const { container } = render(<TelemetryConsentBanner />);
expect(container).toBeEmptyDOMElement();
});
it('renders nothing when the user has already opted in', () => {
vi.stubEnv('VITE_SENTRY_DSN', TEST_DSN);
localStorage.setItem(SENTRY_KEY, 'true');
const { container } = render(<TelemetryConsentBanner />);
expect(container).toBeEmptyDOMElement();
});
it('renders nothing when the user has already opted out', () => {
vi.stubEnv('VITE_SENTRY_DSN', TEST_DSN);
localStorage.setItem(SENTRY_KEY, 'false');
const { container } = render(<TelemetryConsentBanner />);
expect(container).toBeEmptyDOMElement();
});
it('renders the banner when DSN is configured and no preference is saved', () => {
vi.stubEnv('VITE_SENTRY_DSN', TEST_DSN);
render(<TelemetryConsentBanner />);
expect(screen.getByRole('region', { name: /crash reporting prompt/i })).toBeInTheDocument();
expect(screen.getByText(/help improve sable/i)).toBeInTheDocument();
});
// ── accessibility ─────────────────────────────────────────────────────────
it('has both action buttons visible', () => {
vi.stubEnv('VITE_SENTRY_DSN', TEST_DSN);
render(<TelemetryConsentBanner />);
expect(screen.getByRole('button', { name: /enable/i })).toBeInTheDocument();
expect(screen.getByRole('button', { name: /no thanks/i })).toBeInTheDocument();
expect(screen.queryByRole('button', { name: /dismiss/i })).not.toBeInTheDocument();
});
it('includes a link to the privacy policy', () => {
vi.stubEnv('VITE_SENTRY_DSN', TEST_DSN);
render(<TelemetryConsentBanner />);
expect(screen.getByRole('link', { name: /learn more/i })).toBeInTheDocument();
});
// ── "Enable" action ───────────────────────────────────────────────────────
it('"Enable" saves opted-in preference to localStorage', () => {
vi.stubEnv('VITE_SENTRY_DSN', TEST_DSN);
render(<TelemetryConsentBanner />);
fireEvent.click(screen.getByRole('button', { name: /enable/i }));
expect(localStorage.getItem(SENTRY_KEY)).toBe('true');
});
it('"Enable" reloads the page so Sentry initialises', () => {
vi.stubEnv('VITE_SENTRY_DSN', TEST_DSN);
render(<TelemetryConsentBanner />);
fireEvent.click(screen.getByRole('button', { name: /enable/i }));
expect(window.location.reload).toHaveBeenCalledOnce();
});
// ── "No thanks" action ────────────────────────────────────────────────────
it('"No thanks" saves opted-out preference to localStorage', () => {
vi.stubEnv('VITE_SENTRY_DSN', TEST_DSN);
render(<TelemetryConsentBanner />);
fireEvent.click(screen.getByRole('button', { name: /no thanks/i }));
expect(localStorage.getItem(SENTRY_KEY)).toBe('false');
});
it('"No thanks" does not reload the page', () => {
vi.stubEnv('VITE_SENTRY_DSN', TEST_DSN);
render(<TelemetryConsentBanner />);
fireEvent.click(screen.getByRole('button', { name: /no thanks/i }));
expect(window.location.reload).not.toHaveBeenCalled();
});
});
@@ -0,0 +1,71 @@
import { useEffect, useRef, useState } from 'react';
import { Box, Button, Icon, Icons, Text } from 'folds';
import * as css from './TelemetryConsentBanner.css';
const SENTRY_KEY = 'sable_sentry_enabled';
export function TelemetryConsentBanner() {
const isSentryConfigured = Boolean(import.meta.env.VITE_SENTRY_DSN);
const [visible, setVisible] = useState(
isSentryConfigured && localStorage.getItem(SENTRY_KEY) === null
);
const [dismissing, setDismissing] = useState(false);
const dismissTimerRef = useRef<ReturnType<typeof setTimeout> | null>(null);
useEffect(
() => () => {
if (dismissTimerRef.current) clearTimeout(dismissTimerRef.current);
},
[]
);
if (!visible) return null;
const handleEnable = () => {
localStorage.setItem(SENTRY_KEY, 'true');
window.location.reload();
};
const handleDecline = () => {
localStorage.setItem(SENTRY_KEY, 'false');
setDismissing(true);
dismissTimerRef.current = setTimeout(() => setVisible(false), 220);
};
return (
<div className={css.Container}>
<div
className={css.Banner}
data-dismissing={dismissing}
role="region"
aria-label="Crash reporting prompt"
>
<div className={css.Header}>
<Icon src={Icons.Shield} size="400" />
<div className={css.HeaderText}>
<Text size="H4">Help improve Sable</Text>
<Text size="T300" priority="300">
Optionally send anonymous crash reports to help us fix bugs faster. No messages, room
names, or personal data are included.{' '}
<a
href="https://github.com/SableClient/Sable/blob/dev/docs/PRIVACY.md"
target="_blank"
rel="noreferrer noopener"
>
Learn more
</a>
</Text>
</div>
</div>
<Box className={css.Actions}>
<Button variant="Secondary" fill="Soft" size="300" radii="300" onClick={handleDecline}>
<Text size="B300">No thanks</Text>
</Button>
<Button variant="Primary" fill="Solid" size="300" radii="300" onClick={handleEnable}>
<Text size="B300">Enable</Text>
</Button>
</Box>
</div>
</div>
);
}
@@ -0,0 +1 @@
export * from './TelemetryConsentBanner';
+4 -4
View File
@@ -33,7 +33,7 @@ export const DatePicker = forwardRef<HTMLDivElement, DatePickerProps>(
const currentDate = dateFor(selectedYear, selectedMonth, selectedDay);
const time = value - currentDate;
const newDate = dateFor(year, month, mDays < selectedDay ? mDays : selectedDay);
const newDate = dateFor(year, month, Math.min(mDays, selectedDay));
const newValue = newDate + time;
handleSubmit(newValue);
@@ -60,7 +60,7 @@ export const DatePicker = forwardRef<HTMLDivElement, DatePickerProps>(
<Menu className={css.PickerMenu} ref={ref}>
<Box direction="Row" gap="200" className={css.PickerContainer}>
<PickerColumn title="Day">
{Array.from(Array(daysInMonth(selectedMonth, selectedYear)).keys())
{Array.from(new Array(daysInMonth(selectedMonth, selectedYear)).keys())
.map((i) => i + 1)
.map((day) => (
<Chip
@@ -81,7 +81,7 @@ export const DatePicker = forwardRef<HTMLDivElement, DatePickerProps>(
))}
</PickerColumn>
<PickerColumn title="Month">
{Array.from(Array(12).keys())
{Array.from(new Array(12).keys())
.map((i) => i + 1)
.map((month) => (
<Chip
@@ -106,7 +106,7 @@ export const DatePicker = forwardRef<HTMLDivElement, DatePickerProps>(
))}
</PickerColumn>
<PickerColumn title="Year">
{Array.from(Array(yearsRange).keys())
{Array.from(new Array(yearsRange).keys())
.map((i) => minYear + i)
.map((year) => (
<Chip
+4 -4
View File
@@ -64,7 +64,7 @@ export const TimePicker = forwardRef<HTMLDivElement, TimePickerProps>(
<Box direction="Row" gap="200" className={css.PickerContainer}>
<PickerColumn title="Hour">
{hour24Clock
? Array.from(Array(24).keys()).map((hour) => (
? Array.from(new Array(24).keys()).map((hour) => (
<Chip
key={hour}
size="500"
@@ -78,7 +78,7 @@ export const TimePicker = forwardRef<HTMLDivElement, TimePickerProps>(
<Text size="T300">{hour < 10 ? `0${hour}` : hour}</Text>
</Chip>
))
: Array.from(Array(12).keys())
: Array.from(new Array(12).keys())
.map((i) => {
if (i === 0) return 12;
return i;
@@ -102,7 +102,7 @@ export const TimePicker = forwardRef<HTMLDivElement, TimePickerProps>(
))}
</PickerColumn>
<PickerColumn title="Minutes">
{Array.from(Array(60).keys()).map((minute) => (
{Array.from(new Array(60).keys()).map((minute) => (
<Chip
key={minute}
size="500"
@@ -124,7 +124,7 @@ export const TimePicker = forwardRef<HTMLDivElement, TimePickerProps>(
<PickerColumn title="Period">
<Chip
size="500"
variant={!selectedPM ? 'Primary' : 'SurfaceVariant'}
variant={selectedPM ? 'SurfaceVariant' : 'Primary'}
fill="None"
radii="300"
aria-selected={!selectedPM}
@@ -1,6 +1,6 @@
import { style } from '@vanilla-extract/css';
import { RecipeVariants, recipe } from '@vanilla-extract/recipes';
import { RadiiVariant, color, config } from 'folds';
import { DefaultReset, RadiiVariant, color, config, toRem } from 'folds';
export const UploadCard = recipe({
base: {
@@ -34,3 +34,65 @@ export const UploadCardError = style({
padding: `0 ${config.space.S100}`,
color: color.Critical.Main,
});
export const AudioPreviewContainer = style([
DefaultReset,
{
backgroundColor: color.SurfaceVariant.Container,
border: `${config.borderWidth.B300} solid ${color.SurfaceVariant.ContainerLine}`,
borderRadius: config.radii.R400,
padding: config.space.S300,
width: '100%',
maxWidth: toRem(400),
boxSizing: 'border-box',
},
]);
export const AudioWaveformContainer = style([
DefaultReset,
{
minHeight: 44,
cursor: 'pointer',
userSelect: 'none',
overflow: 'hidden',
},
]);
export const AudioWaveformBar = style([
DefaultReset,
{
width: 2,
height: 3,
borderRadius: 1,
flexShrink: 0,
transition: 'background-color 40ms, opacity 40ms',
pointerEvents: 'none',
},
]);
export const AudioWaveformBarPlayed = style([
DefaultReset,
{
backgroundColor: color.Secondary.Main,
opacity: 1,
},
]);
export const AudioWaveformBarUnplayed = style([
DefaultReset,
{
backgroundColor: color.SurfaceVariant.OnContainer,
opacity: 0.5,
},
]);
export const AudioTimeDisplay = style([
DefaultReset,
{
fontVariantNumeric: 'tabular-nums',
color: color.SurfaceVariant.OnContainer,
minWidth: toRem(30),
textAlign: 'right',
flexShrink: 0,
},
]);
@@ -1,4 +1,4 @@
import { ReactNode, useEffect, useMemo, useState } from 'react';
import { ReactNode, useEffect, useMemo, useRef, useState } from 'react';
import {
Box,
Chip,
@@ -14,6 +14,7 @@ import {
toRem,
} from 'folds';
import { HTMLReactParserOptions } from 'html-react-parser';
import { Play, Pause } from '@phosphor-icons/react';
import { useMediaAuthentication } from '$hooks/useMediaAuthentication';
import { Opts as LinkifyOpts } from 'linkifyjs';
import { getReactCustomHtmlParser, LINKIFY_OPTS } from '$plugins/react-custom-html-parser';
@@ -27,12 +28,13 @@ import { roomUploadAtomFamily, TUploadItem, TUploadMetadata } from '$state/room/
import { useObjectURL } from '$hooks/useObjectURL';
import { useMediaConfig } from '$hooks/useMediaConfig';
import { UploadCard, UploadCardError, UploadCardProgress } from './UploadCard';
import * as css from './UploadCard.css';
import { DescriptionEditor } from './UploadDescriptionEditor';
type PreviewImageProps = {
fileItem: TUploadItem;
};
function PreviewImage({ fileItem }: PreviewImageProps) {
function PreviewImage({ fileItem }: Readonly<PreviewImageProps>) {
const { originalFile, metadata } = fileItem;
const fileUrl = useObjectURL(originalFile);
@@ -53,7 +55,7 @@ function PreviewImage({ fileItem }: PreviewImageProps) {
type PreviewVideoProps = {
fileItem: TUploadItem;
};
function PreviewVideo({ fileItem }: PreviewVideoProps) {
function PreviewVideo({ fileItem }: Readonly<PreviewVideoProps>) {
const { originalFile, metadata } = fileItem;
const fileUrl = useObjectURL(originalFile);
@@ -71,6 +73,196 @@ function PreviewVideo({ fileItem }: PreviewVideoProps) {
);
}
const BAR_COUNT = 44;
function formatAudioTime(s: number): string {
const m = Math.floor(s / 60);
const sec = Math.floor(s % 60);
return `${m}:${sec.toString().padStart(2, '0')}`;
}
type PreviewAudioProps = {
fileItem: TUploadItem;
};
function PreviewAudio({ fileItem }: PreviewAudioProps) {
const { originalFile, metadata } = fileItem;
const audioUrl = useObjectURL(originalFile);
const { waveform, audioDuration } = metadata;
const duration = audioDuration ?? 0;
const [isPlaying, setIsPlaying] = useState(false);
const [currentTime, setCurrentTime] = useState(0);
const audioRef = useRef<HTMLAudioElement | null>(null);
const rafRef = useRef<number | null>(null);
const bars = useMemo(() => {
if (!waveform || waveform.length === 0) {
return Array(BAR_COUNT).fill(0.3);
}
if (waveform.length <= BAR_COUNT) {
const step = (waveform.length - 1) / (BAR_COUNT - 1);
return Array.from({ length: BAR_COUNT }, (_, i) => {
const position = i * step;
const lower = Math.floor(position);
const upper = Math.min(Math.ceil(position), waveform.length - 1);
const fraction = position - lower;
if (lower === upper) {
return waveform[lower] ?? 0.3;
}
return (waveform[lower] ?? 0.3) * (1 - fraction) + (waveform[upper] ?? 0.3) * fraction;
});
}
const step = waveform.length / BAR_COUNT;
return Array.from({ length: BAR_COUNT }, (_, i) => {
const start = Math.floor(i * step);
const end = Math.floor((i + 1) * step);
const slice = waveform.slice(start, end);
return slice.length > 0 ? Math.max(...slice) : 0.3;
});
}, [waveform]);
const progress = duration > 0 ? Math.min(currentTime / duration, 1) : 0;
useEffect(() => {
if (!audioUrl) {
return undefined;
}
const audio = new Audio(audioUrl);
audioRef.current = audio;
audio.onended = () => {
setIsPlaying(false);
setCurrentTime(0);
if (rafRef.current !== null) {
cancelAnimationFrame(rafRef.current);
rafRef.current = null;
}
};
return () => {
audio.pause();
if (rafRef.current !== null) {
cancelAnimationFrame(rafRef.current);
}
};
}, [audioUrl]);
const startRaf = (audio: HTMLAudioElement) => {
const tick = () => {
setCurrentTime(audio.currentTime);
rafRef.current = requestAnimationFrame(tick);
};
rafRef.current = requestAnimationFrame(tick);
};
const stopRaf = () => {
if (rafRef.current !== null) {
cancelAnimationFrame(rafRef.current);
rafRef.current = null;
}
};
const handlePlayPause = () => {
const audio = audioRef.current;
if (!audio) return;
if (isPlaying) {
audio.pause();
setIsPlaying(false);
stopRaf();
} else {
audio.play().catch(() => {});
setIsPlaying(true);
startRaf(audio);
}
};
const handleScrubClick = (e: React.MouseEvent<HTMLDivElement>) => {
const audio = audioRef.current;
if (!audio || !duration) return;
const rect = e.currentTarget.getBoundingClientRect();
const ratio = Math.max(0, Math.min(1, (e.clientX - rect.left) / rect.width));
audio.currentTime = ratio * duration;
setCurrentTime(audio.currentTime);
};
const handleKeyDown = (e: React.KeyboardEvent) => {
const audio = audioRef.current;
if (!audio || !duration) return;
const SEEK_STEP = 5;
let newTime = currentTime;
if (e.key === 'ArrowLeft' || e.key === 'ArrowDown') {
e.preventDefault();
newTime = Math.max(0, currentTime - SEEK_STEP);
} else if (e.key === 'ArrowRight' || e.key === 'ArrowUp') {
e.preventDefault();
newTime = Math.min(duration, currentTime + SEEK_STEP);
} else if (e.key === 'Home') {
e.preventDefault();
newTime = 0;
} else if (e.key === 'End') {
e.preventDefault();
newTime = duration;
} else {
return;
}
audio.currentTime = newTime;
setCurrentTime(newTime);
};
return (
<Box alignItems="Center" gap="200" className={css.AudioPreviewContainer}>
<IconButton
variant="Secondary"
size="400"
radii="300"
onClick={handlePlayPause}
title={isPlaying ? 'Pause' : 'Play voice message'}
aria-label={isPlaying ? 'Pause' : 'Play voice message'}
aria-pressed={isPlaying}
>
{isPlaying ? <Pause size={20} weight="fill" /> : <Play size={20} weight="fill" />}
</IconButton>
<Box
grow="Yes"
alignItems="Center"
gap="100"
onClick={handleScrubClick}
onKeyDown={handleKeyDown}
className={css.AudioWaveformContainer}
tabIndex={0}
role="slider"
aria-label="Audio position"
aria-valuemin={0}
aria-valuemax={duration}
aria-valuenow={Math.floor(currentTime)}
title="Seek"
>
{bars.map((level, i) => {
const barRatio = i / BAR_COUNT;
const played = progress > 0 && barRatio <= progress;
return (
<div
// eslint-disable-next-line react/no-array-index-key
key={i}
className={`${css.AudioWaveformBar} ${played ? css.AudioWaveformBarPlayed : css.AudioWaveformBarUnplayed}`}
style={{ height: Math.max(3, Math.round(level * 24)) }}
/>
);
})}
</Box>
<Text size="T200" className={css.AudioTimeDisplay}>
{formatAudioTime(isPlaying ? currentTime : duration)}
</Text>
</Box>
);
}
type MediaPreviewProps = {
fileItem: TUploadItem;
onSpoiler: (marked: boolean) => void;
@@ -131,7 +323,7 @@ export function UploadCardRenderer({
onRemove,
onComplete,
roomId,
}: UploadCardRendererProps) {
}: Readonly<UploadCardRendererProps>) {
const mx = useMatrixClient();
const mediaConfig = useMediaConfig();
const allowSize = mediaConfig['m.upload.size'] || Infinity;
@@ -247,6 +439,7 @@ export function UploadCardRenderer({
<PreviewVideo fileItem={fileItem} />
</MediaPreview>
)}
{fileItem.metadata.waveform && <PreviewAudio fileItem={fileItem} />}
{upload.status === UploadStatus.Idle && !fileSizeExceeded && (
<UploadCardProgress sentBytes={0} totalBytes={file.size} />
)}
@@ -53,7 +53,7 @@ export function DescriptionEditor({
imagePackRooms,
onSave,
onCancel,
}: DescriptionEditorProps) {
}: Readonly<DescriptionEditorProps>) {
const editor = useEditor();
const [enterForNewline] = useSetting(settingsAtom, 'enterForNewline');
const [isMarkdown] = useSetting(settingsAtom, 'isMarkdown');
@@ -3,10 +3,6 @@ import { IPreviewUrlResponse } from '$types/matrix-sdk';
import { Box, Icon, IconButton, Icons, Scroll, Spinner, Text, as, color, config } from 'folds';
import { AsyncStatus, useAsyncCallback } from '$hooks/useAsyncCallback';
import { useMatrixClient } from '$hooks/useMatrixClient';
import {
getIntersectionObserverEntry,
useIntersectionObserver,
} from '$hooks/useIntersectionObserver';
import { mxcUrlToHttp, downloadMedia } from '$utils/matrix';
import { useMediaAuthentication } from '$hooks/useMediaAuthentication';
import * as css from './UrlPreviewCard.css';
@@ -242,43 +238,34 @@ export const UrlPreviewCard = as<'div', { url: string; ts: number; mediaType?: s
export const UrlPreviewHolder = as<'div'>(({ children, ...props }, ref) => {
const scrollRef = useRef<HTMLDivElement>(null);
const backAnchorRef = useRef<HTMLDivElement>(null);
const frontAnchorRef = useRef<HTMLDivElement>(null);
const [backVisible, setBackVisible] = useState(true);
const [frontVisible, setFrontVisible] = useState(true);
const innerBoxRef = useRef<HTMLDivElement>(null);
const [canScrollLeft, setCanScrollLeft] = useState(false);
const [canScrollRight, setCanScrollRight] = useState(false);
const intersectionObserver = useIntersectionObserver(
useCallback((entries) => {
const backAnchor = backAnchorRef.current;
const frontAnchor = frontAnchorRef.current;
const backEntry = backAnchor && getIntersectionObserverEntry(backAnchor, entries);
const frontEntry = frontAnchor && getIntersectionObserverEntry(frontAnchor, entries);
if (backEntry) {
setBackVisible(backEntry.isIntersecting);
}
if (frontEntry) {
setFrontVisible(frontEntry.isIntersecting);
}
}, []),
useCallback(
() => ({
root: scrollRef.current,
rootMargin: '10px',
}),
[]
)
);
const updateArrows = useCallback(() => {
const scroll = scrollRef.current;
if (!scroll) return;
const { scrollLeft, scrollWidth, clientWidth } = scroll;
setCanScrollLeft(scrollLeft > 1);
setCanScrollRight(scrollLeft + clientWidth < scrollWidth - 1);
}, []);
useEffect(() => {
const backAnchor = backAnchorRef.current;
const frontAnchor = frontAnchorRef.current;
if (backAnchor) intersectionObserver?.observe(backAnchor);
if (frontAnchor) intersectionObserver?.observe(frontAnchor);
const scroll = scrollRef.current;
if (!scroll) return undefined;
updateArrows();
scroll.addEventListener('scroll', updateArrows, { passive: true });
const resizeObserver = new ResizeObserver(updateArrows);
resizeObserver.observe(scroll);
if (innerBoxRef.current) resizeObserver.observe(innerBoxRef.current);
return () => {
if (backAnchor) intersectionObserver?.unobserve(backAnchor);
if (frontAnchor) intersectionObserver?.unobserve(frontAnchor);
scroll.removeEventListener('scroll', updateArrows);
resizeObserver.disconnect();
};
}, [intersectionObserver]);
}, [updateArrows]);
const handleScrollBack = () => {
const scroll = scrollRef.current;
@@ -308,8 +295,7 @@ export const UrlPreviewHolder = as<'div'>(({ children, ...props }, ref) => {
>
<Scroll ref={scrollRef} direction="Horizontal" size="0" visibility="Hover" hideTrack>
<Box shrink="No" alignItems="Center">
<div ref={backAnchorRef} />
{!backVisible && (
{canScrollLeft && (
<>
<div className={css.UrlPreviewHolderGradient({ position: 'Left' })} />
<IconButton
@@ -324,10 +310,9 @@ export const UrlPreviewHolder = as<'div'>(({ children, ...props }, ref) => {
</IconButton>
</>
)}
<Box alignItems="Inherit" gap="200">
<Box ref={innerBoxRef} alignItems="Inherit" gap="200">
{children}
{!frontVisible && (
{canScrollRight && (
<>
<div className={css.UrlPreviewHolderGradient({ position: 'Right' })} />
<IconButton
@@ -342,7 +327,6 @@ export const UrlPreviewHolder = as<'div'>(({ children, ...props }, ref) => {
</IconButton>
</>
)}
<div ref={frontAnchorRef} />
</Box>
</Box>
</Scroll>
@@ -65,7 +65,7 @@ function UserExtendedSection({
profile,
htmlReactParserOptions,
linkifyOpts,
}: UserExtendedSectionProps) {
}: Readonly<UserExtendedSectionProps>) {
const clamp = (str: any, len: number) => {
const stringified = String(str ?? '');
return stringified.length > len ? `${stringified.slice(0, len)}...` : stringified;
@@ -108,7 +108,7 @@ function UserExtendedSection({
return new Intl.DateTimeFormat([], {
hour: 'numeric',
minute: '2-digit',
timeZone: profile.timezone.replace(/^["']|["']$/g, ''),
timeZone: profile.timezone.replaceAll(/^["']|["']$/g, ''),
}).format(new Date());
} catch {
return null;
@@ -133,7 +133,7 @@ function UserExtendedSection({
const safetyTrim = rawBio.length > 2048 ? rawBio.slice(0, 2048) : rawBio;
const visibleText = safetyTrim.replace(/<[^>]*>?/gm, '');
const visibleText = safetyTrim.replaceAll(/<[^>]*>?/gm, '');
const VISIBLE_LIMIT = 1024;
if (visibleText.length <= VISIBLE_LIMIT) {
@@ -163,7 +163,7 @@ function UserExtendedSection({
<Box alignItems="Center" gap="100">
<Icon size="50" src={Icons.Clock} style={{ opacity: 0.5 }} />
<Text size="T200" priority="400">
{localTime} ({profile.timezone.replace(/^["']|["']$/g, '')})
{localTime} ({profile.timezone.replaceAll(/^["']|["']$/g, '')})
</Text>
</Box>
)}
@@ -252,7 +252,7 @@ type UserRoomProfileProps = {
userId: string;
initialProfile?: Partial<UserProfile>;
};
export function UserRoomProfile({ userId, initialProfile }: UserRoomProfileProps) {
export function UserRoomProfile({ userId, initialProfile }: Readonly<UserRoomProfileProps>) {
const mx = useMatrixClient();
const useAuthentication = useMediaAuthentication();
const navigate = useNavigate();
@@ -296,7 +296,7 @@ export function UserRoomProfile({ userId, initialProfile }: UserRoomProfileProps
const parsedBanner =
typeof extendedProfile.bannerUrl === 'string'
? extendedProfile.bannerUrl.replace(/^"|"$/g, '')
? extendedProfile.bannerUrl.replaceAll(/^"|"$/g, '')
: undefined;
const bannerHttpUrl = parsedBanner
+134 -3
View File
@@ -18,9 +18,12 @@ import {
Spinner,
Text,
TextArea,
Checkbox,
} from 'folds';
import * as Sentry from '@sentry/react';
import { useCloseBugReportModal, useBugReportModalOpen } from '$state/hooks/bugReportModal';
import { stopPropagation } from '$utils/keyboard';
import { getDebugLogger } from '$utils/debugLogger';
type ReportType = 'bug' | 'feature';
@@ -84,6 +87,7 @@ export function buildGitHubUrl(
function BugReportModal() {
const close = useCloseBugReportModal();
const sentryEnabled = Sentry.isInitialized();
const [type, setType] = useState<ReportType>('bug');
const [title, setTitle] = useState('');
@@ -100,6 +104,12 @@ function BugReportModal() {
// Shared optional field
const [context, setContext] = useState('');
// Sentry integration options
const [sendToSentry, setSendToSentry] = useState(true);
const [includeDebugLogs, setIncludeDebugLogs] = useState(true);
// When Sentry is enabled, GitHub is opt-in; when disabled, GitHub is always used
const [openOnGitHub, setOpenOnGitHub] = useState(!sentryEnabled);
const [similarIssues, setSimilarIssues] = useState<SimilarIssue[]>([]);
const [searching, setSearching] = useState(false);
@@ -141,12 +151,74 @@ function BugReportModal() {
const handleSubmit = () => {
if (!canSubmit) return;
const fields: Record<string, string> =
type === 'bug'
? { description, reproduction, 'expected-behavior': expectedBehavior, context }
: { problem, solution, alternatives, context };
const url = buildGitHubUrl(type, title.trim(), fields);
window.open(url, '_blank', 'noopener,noreferrer');
// Send to Sentry if bug report and option is enabled
if (sendToSentry && type === 'bug') {
const debugLogger = getDebugLogger();
// Attach recent logs if user opted in
if (includeDebugLogs) {
debugLogger.attachLogsToSentry(100);
}
const version = `v${APP_VERSION}${IS_RELEASE_TAG ? '' : '-dev'}${BUILD_HASH ? ` (${BUILD_HASH})` : ''}`;
// Build a fully self-contained message so all fields are visible
// directly in the Sentry issue detail without digging into sub-sections.
const sentryMessage = [
`[Bug Report] ${title.trim()}`,
'',
`Description:\n${description}`,
reproduction ? `\nSteps to Reproduce:\n${reproduction}` : '',
expectedBehavior ? `\nExpected Behavior:\n${expectedBehavior}` : '',
context ? `\nAdditional Context:\n${context}` : '',
`\nEnvironment: ${version} · ${navigator.platform}`,
]
.filter(Boolean)
.join('\n');
const eventId = Sentry.captureMessage(sentryMessage, {
level: 'info',
// Group all user bug reports together in Sentry Issues
fingerprint: ['bug-report-modal'],
tags: {
source: 'bug-report-modal',
reportType: type,
},
extra: {
title: title.trim(),
description,
reproduction: reproduction || '(not provided)',
expectedBehavior: expectedBehavior || '(not provided)',
context: context || '(not provided)',
userAgent: navigator.userAgent,
platform: navigator.platform,
version,
},
});
// Also send as User Feedback so it appears in the Sentry Feedback section
if (eventId) {
Sentry.captureFeedback({
message: sentryMessage,
name: 'User Bug Report',
associatedEventId: eventId,
});
}
}
// Feature requests always go to GitHub; bugs go to GitHub only when Sentry
// is unavailable or the user explicitly opts in.
const shouldOpenGitHub = type === 'feature' || !sentryEnabled || openOnGitHub;
if (shouldOpenGitHub) {
const url = buildGitHubUrl(type, title.trim(), fields);
window.open(url, '_blank', 'noopener,noreferrer');
}
close();
};
@@ -352,6 +424,63 @@ function BugReportModal() {
/>
</Box>
{/* Sentry integration options (only for bug reports when Sentry is configured) */}
{type === 'bug' && sentryEnabled && (
<Box direction="Column" gap="200">
<Text size="L400">Error Tracking</Text>
<Box as="label" gap="200" alignItems="Center" style={{ cursor: 'pointer' }}>
<Checkbox
variant="Primary"
checked={sendToSentry}
onClick={() => setSendToSentry((v) => !v)}
/>
<Box direction="Column" gap="100" grow="Yes">
<Text size="T300">
Send anonymous report to Sentry for error tracking
</Text>
<Text size="T200" style={{ opacity: 0.7 }}>
Helps developers identify and fix issues faster. No personal data is
sent.
</Text>
</Box>
</Box>
{sendToSentry && (
<Box
as="label"
gap="200"
alignItems="Center"
style={{ cursor: 'pointer', paddingLeft: config.space.S400 }}
>
<Checkbox
variant="Primary"
checked={includeDebugLogs}
onClick={() => setIncludeDebugLogs((v) => !v)}
/>
<Box direction="Column" gap="100" grow="Yes">
<Text size="T300">Include recent debug logs (last 100 entries)</Text>
<Text size="T200" style={{ opacity: 0.7 }}>
Provides additional context to help diagnose the issue. Logs are
filtered for sensitive data.
</Text>
</Box>
</Box>
)}
<Box as="label" gap="200" alignItems="Center" style={{ cursor: 'pointer' }}>
<Checkbox
variant="Primary"
checked={openOnGitHub}
onClick={() => setOpenOnGitHub((v) => !v)}
/>
<Box direction="Column" gap="100" grow="Yes">
<Text size="T300">Also create a GitHub issue</Text>
<Text size="T200" style={{ opacity: 0.7 }}>
Opens a pre-filled GitHub issue in addition to the Sentry report.
</Text>
</Box>
</Box>
</Box>
)}
{/* Actions */}
<Box gap="300" justifyContent="End">
<Button size="400" variant="Secondary" fill="None" radii="400" onClick={close}>
@@ -365,7 +494,9 @@ function BugReportModal() {
onClick={handleSubmit}
after={<Icon src={Icons.ArrowRight} size="100" />}
>
<Text size="B400">Open on GitHub</Text>
<Text size="B400">
{sentryEnabled && type === 'bug' ? 'Submit Report' : 'Open on GitHub'}
</Text>
</Button>
</Box>
</Box>
@@ -45,7 +45,7 @@ type CreatePackTileProps = {
packs: ImagePack[];
roomId: string;
};
function CreatePackTile({ packs, roomId }: CreatePackTileProps) {
function CreatePackTile({ packs, roomId }: Readonly<CreatePackTileProps>) {
const mx = useMatrixClient();
const alive = useAlive();
@@ -75,9 +75,9 @@ function CreatePackTile({ packs, roomId }: CreatePackTileProps) {
const name = nameInput?.value.trim();
if (!name) return;
let packKey = name.replace(/\s/g, '-');
let packKey = name.replaceAll(/\s/g, '-');
const hasPack = (k: string): boolean => !!packs.find((pack) => pack.address?.stateKey === k);
const hasPack = (k: string): boolean => packs.some((pack) => pack.address?.stateKey === k);
if (hasPack(packKey)) {
packKey = suffixRename(packKey, hasPack);
}
@@ -141,7 +141,7 @@ function CreatePackTile({ packs, roomId }: CreatePackTileProps) {
type RoomPacksProps = {
onViewPack: (imagePack: ImagePack) => void;
};
export function RoomPacks({ onViewPack }: RoomPacksProps) {
export function RoomPacks({ onViewPack }: Readonly<RoomPacksProps>) {
const mx = useMatrixClient();
const useAuthentication = useMediaAuthentication();
const room = useRoom();
@@ -193,7 +193,7 @@ export function RoomPacks({ onViewPack }: RoomPacksProps) {
const avatarUrl = avatarMxc ? mxcUrlToHttp(mx, avatarMxc, useAuthentication) : undefined;
const { address } = pack;
if (!address) return null;
const removed = !!removedPacks.find((addr) => packAddressEqual(addr, address));
const removed = removedPacks.some((addr) => packAddressEqual(addr, address));
return (
<SequenceCard
@@ -57,7 +57,7 @@ type EditPowerProps = {
onSave: (power: number, tag: MemberPowerTag) => void;
onClose: () => void;
};
function EditPower({ maxPower, power, tag, onSave, onClose }: EditPowerProps) {
function EditPower({ maxPower, power, tag, onSave, onClose }: Readonly<EditPowerProps>) {
const mx = useMatrixClient();
const room = useRoom();
const roomToParents = useAtomValue(roomToParentsAtom);
@@ -103,7 +103,7 @@ function EditPower({ maxPower, power, tag, onSave, onClose }: EditPowerProps) {
const nameInput = target?.nameInput as HTMLInputElement | undefined;
if (!powerInput || !nameInput) return;
const tagPower = parseInt(powerInput.value, 10);
const tagPower = Number.parseInt(powerInput.value, 10);
if (Number.isNaN(tagPower)) return;
const tagName = nameInput.value.trim();
@@ -307,7 +307,7 @@ type PowersEditorProps = {
powerLevels: IPowerLevels;
requestClose: () => void;
};
export function PowersEditor({ powerLevels, requestClose }: PowersEditorProps) {
export function PowersEditor({ powerLevels, requestClose }: Readonly<PowersEditorProps>) {
const mx = useMatrixClient();
const useAuthentication = useMediaAuthentication();
const room = useRoom();
+7 -7
View File
@@ -29,9 +29,8 @@ export const useDraggableItem = (
const target = targetRef.current;
const dragHandle = dragHandleRef?.current ?? undefined;
return !target
? undefined
: draggable({
return target
? draggable({
element: target,
dragHandle,
getInitialData: () => item,
@@ -43,7 +42,8 @@ export const useDraggableItem = (
setDragging(false);
onDragging(undefined);
},
});
})
: undefined;
}, [targetRef, dragHandleRef, item, onDragging]);
return dragging;
@@ -72,14 +72,14 @@ export function AfterItemDropTarget({
afterSpace,
nextRoomId,
canDrop,
}: AfterItemDropTargetProps) {
}: Readonly<AfterItemDropTargetProps>) {
const targetRef = useRef<HTMLDivElement>(null);
const [dropState, setDropState] = useState<'idle' | 'allow' | 'not-allow'>('idle');
useEffect(() => {
const target = targetRef.current;
if (!target) {
throw Error('drop target ref is not set properly');
throw new Error('drop target ref is not set properly');
}
return dropTargetForElements({
@@ -126,7 +126,7 @@ export const useDnDMonitor = (
useEffect(() => {
const scrollElement = scrollRef.current;
if (!scrollElement) {
throw Error('Scroll element ref not configured');
throw new Error('Scroll element ref not configured');
}
return combine(
+3 -4
View File
@@ -185,7 +185,7 @@ export function Lobby() {
return new Set(sideSpaces);
}, [sidebarItems]);
const [spacesItems, setSpacesItem] = useState<Map<string, IHierarchyRoom>>(() => new Map());
const [spacesItems, setSpacesItems] = useState<Map<string, IHierarchyRoom>>(() => new Map());
useElementSizeObserver(
useCallback(() => heroSectionRef.current, []),
@@ -387,8 +387,7 @@ export function Lobby() {
}
if (
itemRoom &&
itemRoom.getJoinRule() === JoinRule.Restricted &&
itemRoom?.getJoinRule() === JoinRule.Restricted &&
item.parentId !== containerParentId
) {
// change join rule allow parameter when dragging
@@ -479,7 +478,7 @@ export function Lobby() {
const handleSpacesFound = useCallback(
(sItems: IHierarchyRoom[]) => {
setSpaceRooms({ type: 'PUT', roomIds: sItems.map((i) => i.room_id) });
setSpacesItem((current) => {
setSpacesItems((current) => {
const newItems = produce(current, (draft) => {
sItems.forEach((item) => draft.set(item.room_id, item));
});
@@ -49,7 +49,7 @@ export function MessageSearch({
rooms,
senders,
scrollRef,
}: MessageSearchProps) {
}: Readonly<MessageSearchProps>) {
const mx = useMatrixClient();
const mDirects = useAtomValue(mDirectAtom);
const allRooms = useRooms(mx, allRoomsAtom, mDirects);
@@ -175,7 +175,7 @@ export function MessageSearch({
});
};
const lastVItem = vItems[vItems.length - 1];
const lastVItem = vItems.at(-1);
const lastVItemIndex: number | undefined = lastVItem?.index;
const lastGroupIndex = groups.length - 1;
useEffect(() => {
@@ -253,7 +253,7 @@ export function MessageSearch({
{((msgSearchParams.term && status === 'pending') ||
(groups.length > 0 && vItems.length === 0)) && (
<Box direction="Column" gap="100">
{[...Array(8).keys()].map((key) => (
{[...new Array(8).keys()].map((key) => (
<SequenceCard variant="SurfaceVariant" key={key} style={{ minHeight: toRem(80) }} />
))}
</Box>
@@ -0,0 +1,120 @@
import { keyframes, style } from '@vanilla-extract/css';
import { DefaultReset, color, config, toRem } from 'folds';
const RecDotPulse = keyframes({
'0%, 100%': { opacity: 1 },
'50%': { opacity: 0.25 },
});
const SlideOutLeft = keyframes({
'0%': { transform: 'translateX(0)', opacity: 1 },
'100%': { transform: 'translateX(-100%)', opacity: 0 },
});
const Shake = keyframes({
'0%, 100%': { transform: 'translateX(0)' },
'20%': { transform: 'translateX(-4px)' },
'40%': { transform: 'translateX(4px)' },
'60%': { transform: 'translateX(-4px)' },
'80%': { transform: 'translateX(4px)' },
});
export const Container = style([
DefaultReset,
{
flexGrow: 1,
minWidth: 0,
overflow: 'hidden',
touchAction: 'pan-y',
userSelect: 'none',
},
]);
export const ContainerCanceling = style({
animation: `${SlideOutLeft} 200ms ease-out forwards`,
});
export const ContainerShake = style({
animation: `${Shake} 300ms ease-out`,
});
export const RecDot = style([
DefaultReset,
{
width: 7,
height: 7,
borderRadius: '50%',
backgroundColor: color.Critical.Main,
flexShrink: 0,
animation: `${RecDotPulse} 1.4s ease-in-out infinite`,
},
]);
export const WaveformContainer = style([
DefaultReset,
{
height: 22,
overflow: 'hidden',
minWidth: 0,
},
]);
export const WaveformBar = style([
DefaultReset,
{
width: 2,
height: 3,
borderRadius: 1,
backgroundColor: color.Primary.Main,
transition: 'height 70ms ease-out',
flexShrink: 0,
},
]);
export const Timer = style([
DefaultReset,
{
fontVariantNumeric: 'tabular-nums',
color: color.Critical.Main,
minWidth: config.space.S300,
flexShrink: 0,
fontWeight: 600,
},
]);
export const CancelHint = style([
DefaultReset,
{
position: 'absolute',
left: config.space.S200,
top: 0,
bottom: 0,
display: 'flex',
alignItems: 'center',
color: color.Critical.Main,
fontSize: toRem(12),
fontWeight: 600,
opacity: 0,
transition: 'opacity 100ms ease-out',
pointerEvents: 'none',
},
]);
export const CancelHintVisible = style({
opacity: 1,
});
export const SrOnly = style([
DefaultReset,
{
position: 'absolute',
width: 1,
height: 1,
padding: 0,
margin: -1,
overflow: 'hidden',
clip: 'rect(0, 0, 0, 0)',
whiteSpace: 'nowrap',
borderWidth: 0,
},
]);
+160 -84
View File
@@ -1,92 +1,168 @@
import { VoiceRecorder } from '$plugins/voice-recorder-kit';
import FocusTrap from 'focus-trap-react';
import { Box, Icon, Icons, Text, color, config } from 'folds';
import { useRef } from 'react';
import {
forwardRef,
useCallback,
useEffect,
useImperativeHandle,
useMemo,
useRef,
useState,
} from 'react';
import { useVoiceRecorder } from '$plugins/voice-recorder-kit';
import type { VoiceRecorderStopPayload } from '$plugins/voice-recorder-kit';
import { Box, Text } from 'folds';
import * as css from './AudioMessageRecorder.css';
export type AudioRecordingCompletePayload = {
audioBlob: Blob;
waveform: number[];
audioLength: number;
audioCodec: string;
};
export type AudioMessageRecorderHandle = {
stop: () => void;
cancel: () => void;
};
type AudioMessageRecorderProps = {
onRecordingComplete: (audioBlob: Blob) => void;
onRecordingComplete: (payload: AudioRecordingCompletePayload) => void;
onRequestClose: () => void;
onWaveformUpdate: (waveform: number[]) => void;
onAudioLengthUpdate: (length: number) => void;
};
// We use a react voice recorder library to handle the recording of audio messages, as it provides a simple API and handles the complexities of recording audio in the browser.
// The component is wrapped in a focus trap to ensure that keyboard users can easily navigate and interact with the recorder without accidentally losing focus or interacting with other parts of the UI.
// The styling is kept simple and consistent with the rest of the app, using Folds' design tokens for colors, spacing, and typography.
// we use a modified version of https://www.npmjs.com/package/react-voice-recorder-kit for the recording
export function AudioMessageRecorder({
onRecordingComplete,
onRequestClose,
onWaveformUpdate,
onAudioLengthUpdate,
}: AudioMessageRecorderProps) {
const containerRef = useRef<HTMLDivElement>(null);
const isDismissedRef = useRef(false);
// uses default styling, we use at other places
return (
<FocusTrap
focusTrapOptions={{
returnFocusOnDeactivate: false,
initialFocus: false,
onDeactivate: () => {
isDismissedRef.current = true;
onRequestClose();
},
clickOutsideDeactivates: true,
allowOutsideClick: true,
fallbackFocus: () => containerRef.current!,
}}
>
<div ref={containerRef} tabIndex={-1} style={{ outline: 'none' }}>
<Box
direction="Column"
gap="200"
alignItems="Center"
style={{
backgroundColor: color.Surface.Container,
color: color.Surface.OnContainer,
border: `${config.borderWidth.B300} solid ${color.Surface.ContainerLine}`,
borderRadius: config.radii.R400,
boxShadow: config.shadow.E200,
padding: config.space.S400,
minWidth: 300,
}}
>
<Text size="H4">Audio Message Recorder</Text>
<VoiceRecorder
autoStart
onStop={({
audioFile,
waveform,
audioLength,
}: {
audioFile: Blob;
waveform: number[];
audioLength: number;
}) => {
if (isDismissedRef.current) return;
// closes the recorder and sends the audio file back to the parent component to be uploaded and sent as a message
onRecordingComplete(audioFile);
onWaveformUpdate(waveform);
onAudioLengthUpdate(audioLength);
}}
buttonBackgroundColor={color.SurfaceVariant.Container}
buttonHoverBackgroundColor={color.SurfaceVariant.ContainerHover}
iconColor={color.Primary.Main}
// icons for the recorder, we use Folds' icon library to keep the styling consistent with the rest of the app
customPauseIcon={<Icon src={Icons.Pause} size="200" color={color.Primary.Main} />}
customPlayIcon={<Icon src={Icons.Play} size="200" color={color.Primary.Main} />}
customDeleteIcon={<Icon src={Icons.Delete} size="200" color={color.Primary.Main} />}
customStopIcon={<Icon src={Icons.Send} size="200" color={color.Primary.Main} />}
customRepeatIcon={<Icon src={Icons.Reload} size="200" color={color.Primary.Main} />}
customResumeIcon={<Icon src={Icons.Mic} size="200" color={color.Primary.Main} />}
style={{
backgroundColor: color.Surface.ContainerActive,
}}
/>
</Box>
</div>
</FocusTrap>
);
function formatTime(seconds: number): string {
const m = Math.floor(seconds / 60);
const s = seconds % 60;
return `${m}:${s.toString().padStart(2, '0')}`;
}
export const AudioMessageRecorder = forwardRef<
AudioMessageRecorderHandle,
AudioMessageRecorderProps
>(({ onRecordingComplete, onRequestClose, onWaveformUpdate, onAudioLengthUpdate }, ref) => {
const isDismissedRef = useRef(false);
const userRequestedStopRef = useRef(false);
const [isCanceling, setIsCanceling] = useState(false);
const [announcedTime, setAnnouncedTime] = useState(0);
const onRecordingCompleteRef = useRef(onRecordingComplete);
onRecordingCompleteRef.current = onRecordingComplete;
const onRequestCloseRef = useRef(onRequestClose);
onRequestCloseRef.current = onRequestClose;
const onWaveformUpdateRef = useRef(onWaveformUpdate);
onWaveformUpdateRef.current = onWaveformUpdate;
const onAudioLengthUpdateRef = useRef(onAudioLengthUpdate);
onAudioLengthUpdateRef.current = onAudioLengthUpdate;
const stableOnStop = useCallback((payload: VoiceRecorderStopPayload) => {
if (!userRequestedStopRef.current) return;
if (isDismissedRef.current) return;
onRecordingCompleteRef.current({
audioBlob: payload.audioFile,
waveform: payload.waveform,
audioLength: payload.audioLength,
audioCodec: payload.audioCodec,
});
onWaveformUpdateRef.current(payload.waveform);
onAudioLengthUpdateRef.current(payload.audioLength);
}, []);
const stableOnDelete = useCallback(() => {
isDismissedRef.current = true;
onRequestCloseRef.current();
}, []);
const { levels, seconds, error, handleStop, handleDelete } = useVoiceRecorder({
autoStart: true,
onStop: stableOnStop,
onDelete: stableOnDelete,
});
const doStop = useCallback(() => {
if (isDismissedRef.current) return;
userRequestedStopRef.current = true;
handleStop();
}, [handleStop]);
const doCancel = useCallback(() => {
if (isDismissedRef.current) return;
setIsCanceling(true);
setTimeout(() => {
isDismissedRef.current = true;
handleDelete();
}, 180);
}, [handleDelete]);
useImperativeHandle(ref, () => ({ stop: doStop, cancel: doCancel }), [doStop, doCancel]);
useEffect(() => {
if (seconds > 0 && seconds % 30 === 0 && seconds !== announcedTime) {
setAnnouncedTime(seconds);
}
}, [seconds, announcedTime]);
const BAR_COUNT = 28;
const bars = useMemo(() => {
if (levels.length === 0) {
return Array(BAR_COUNT).fill(0.15);
}
if (levels.length <= BAR_COUNT) {
const step = (levels.length - 1) / (BAR_COUNT - 1);
return Array.from({ length: BAR_COUNT }, (_, i) => {
const position = i * step;
const lower = Math.floor(position);
const upper = Math.min(Math.ceil(position), levels.length - 1);
const fraction = position - lower;
if (lower === upper) {
return levels[lower] ?? 0.15;
}
return (levels[lower] ?? 0.15) * (1 - fraction) + (levels[upper] ?? 0.15) * fraction;
});
}
const step = levels.length / BAR_COUNT;
return Array.from({ length: BAR_COUNT }, (_, i) => {
const start = Math.floor(i * step);
const end = Math.floor((i + 1) * step);
const slice = levels.slice(start, end);
return slice.length > 0 ? Math.max(...slice) : 0.15;
});
}, [levels]);
const containerClassName = [css.Container, isCanceling ? css.ContainerCanceling : null]
.filter(Boolean)
.join(' ');
return (
<>
{error && (
<Text size="T200" style={{ color: 'var(--color-critical-main)' }}>
{error}
</Text>
)}
<Box grow="Yes" alignItems="Center" gap="200" className={containerClassName}>
<div aria-hidden className={css.RecDot} />
<Box grow="Yes" alignItems="Center" gap="100" className={css.WaveformContainer}>
{bars.map((level, i) => (
<div
// eslint-disable-next-line react/no-array-index-key
key={i}
className={css.WaveformBar}
style={{ height: Math.max(3, Math.round(level * 20)) }}
/>
))}
</Box>
<Text size="T200" className={css.Timer} aria-live="polite" aria-atomic="true">
{formatTime(seconds)}
</Text>
{announcedTime > 0 && announcedTime === seconds && (
<span className={css.SrOnly} aria-live="polite">
Recording duration: {formatTime(announcedTime)}
</span>
)}
</Box>
</>
);
});
+3 -1
View File
@@ -4,6 +4,7 @@ import { Room } from '$types/matrix-sdk';
import { useCallStart, useCallJoined } from '$hooks/useCallEmbed';
import { callEmbedAtom } from '$state/callEmbed';
import { useMatrixClient } from '$hooks/useMatrixClient';
import { useCallPreferences } from '$state/hooks/callPreferences';
interface RoomCallButtonProps {
room: Room;
@@ -14,13 +15,14 @@ export function RoomCallButton({ room }: RoomCallButtonProps) {
const callEmbed = useAtomValue(callEmbedAtom);
const joined = useCallJoined(callEmbed);
const mx = useMatrixClient();
const { microphone, video, sound } = useCallPreferences();
const isJoinedInThisRoom = joined && callEmbed?.roomId === room.roomId;
if (isJoinedInThisRoom) return null;
const handleStartCall = async () => {
startCall(room);
startCall(room, { microphone, video, sound });
try {
const now = Date.now();
// TODO not use as any one day someday i swear
+275 -87
View File
@@ -14,6 +14,7 @@ import { isKeyHotkey } from 'is-hotkey';
import {
EventType,
IContent,
MatrixEvent,
MsgType,
RelationType,
Room,
@@ -24,6 +25,7 @@ import { ReactEditor } from 'slate-react';
import { Editor, Point, Range, Transforms } from 'slate';
import {
Box,
color,
config,
Dialog,
Icon,
@@ -114,6 +116,7 @@ import { settingsAtom } from '$state/settings';
import {
getMemberDisplayName,
getMentionContent,
reactionOrEditEvent,
trimReplyFromBody,
trimReplyFromFormattedBody,
} from '$utils/room';
@@ -131,6 +134,7 @@ import { createLogger } from '$utils/debug';
import { createDebugLogger } from '$utils/debugLogger';
import FocusTrap from 'focus-trap-react';
import { useQueryClient } from '@tanstack/react-query';
import * as Sentry from '@sentry/react';
import {
delayedEventsSupportedAtom,
roomIdToScheduledTimeAtomFamily,
@@ -149,6 +153,8 @@ import { usePowerLevelsContext } from '$hooks/usePowerLevels';
import { useRoomCreators } from '$hooks/useRoomCreators';
import { useRoomPermissions } from '$hooks/useRoomPermissions';
import { AutocompleteNotice } from '$components/editor/autocomplete/AutocompleteNotice';
import { Microphone, Stop } from '@phosphor-icons/react';
import { getSupportedAudioExtension } from '$plugins/voice-recorder-kit/supportedCodec';
import { SchedulePickerDialog } from './schedule-send';
import * as css from './schedule-send/SchedulePickerDialog.css';
import {
@@ -158,9 +164,35 @@ import {
getVideoMsgContent,
} from './msgContent';
import { CommandAutocomplete } from './CommandAutocomplete';
import { AudioMessageRecorder } from './AudioMessageRecorder';
import { AudioMessageRecorder, AudioMessageRecorderHandle } from './AudioMessageRecorder';
const getReplyContent = (replyDraft: IReplyDraft | undefined): IEventRelation => {
// Returns the event ID of the most recent non-reaction/non-edit event in a thread,
// falling back to the thread root if no replies exist yet.
const getLatestThreadEventId = (room: Room, threadRootId: string): string => {
const thread = room.getThread(threadRootId);
const threadEvents: MatrixEvent[] = thread?.events ?? [];
const filtered = threadEvents.filter(
(ev) => ev.getId() !== threadRootId && !reactionOrEditEvent(ev)
);
if (filtered.length > 0) {
return filtered[filtered.length - 1].getId() ?? threadRootId;
}
// Fall back to the live timeline if the Thread object hasn't been registered yet
const liveEvents = room
.getUnfilteredTimelineSet()
.getLiveTimeline()
.getEvents()
.filter(
(ev) =>
ev.threadRootId === threadRootId && ev.getId() !== threadRootId && !reactionOrEditEvent(ev)
);
if (liveEvents.length > 0) {
return liveEvents[liveEvents.length - 1].getId() ?? threadRootId;
}
return threadRootId;
};
const getReplyContent = (replyDraft: IReplyDraft | undefined, room?: Room): IEventRelation => {
if (!replyDraft) return {};
const relatesTo: IEventRelation = {};
@@ -173,13 +205,19 @@ const getReplyContent = (replyDraft: IReplyDraft | undefined): IEventRelation =>
// Check if this is a reply to a specific message in the thread
// (replyDraft.body being empty means it's just a seeded thread draft)
if (replyDraft.body && replyDraft.eventId !== replyDraft.relation.event_id) {
// This is a reply to a message within the thread
// Explicit reply to a specific message — per spec, is_falling_back must be false
relatesTo['m.in_reply_to'] = {
event_id: replyDraft.eventId,
};
relatesTo.is_falling_back = false;
} else {
// This is just a regular thread message
// Regular thread message — per spec, include fallback m.in_reply_to pointing to the
// most recent thread message so unthreaded clients can display it as a reply chain
const threadRootId = replyDraft.relation.event_id ?? replyDraft.eventId;
const latestEventId = room ? getLatestThreadEventId(room, threadRootId) : threadRootId;
relatesTo['m.in_reply_to'] = {
event_id: latestEventId,
};
relatesTo.is_falling_back = true;
}
} else {
@@ -249,8 +287,9 @@ export const RoomInput = forwardRef<HTMLDivElement, RoomInputProps>(
const [toolbar, setToolbar] = useSetting(settingsAtom, 'editorToolbar');
const [showAudioRecorder, setShowAudioRecorder] = useState(false);
const [audioMsgWaveform, setAudioMsgWaveform] = useState<number[] | undefined>(undefined);
const [audioMsgLength, setAudioMsgLength] = useState<number | undefined>(undefined);
const audioRecorderRef = useRef<AudioMessageRecorderHandle>(null);
const micHoldStartRef = useRef<number>(0);
const HOLD_THRESHOLD_MS = 400;
const [autocompleteQuery, setAutocompleteQuery] =
useState<AutocompleteQuery<AutocompletePrefix>>();
const [isQuickTextReact, setQuickTextReact] = useState(false);
@@ -260,7 +299,7 @@ export const RoomInput = forwardRef<HTMLDivElement, RoomInputProps>(
const [inputKey, setInputKey] = useState(0);
const handleFiles = useCallback(
async (files: File[]) => {
async (files: File[], audioMeta?: { waveform: number[]; audioDuration: number }) => {
setUploadBoard(true);
const safeFiles = files.map(safeFile);
const fileItems: TUploadItem[] = [];
@@ -274,6 +313,8 @@ export const RoomInput = forwardRef<HTMLDivElement, RoomInputProps>(
...ef,
metadata: {
markedAsSpoiler: false,
waveform: audioMeta?.waveform,
audioDuration: audioMeta?.audioDuration,
},
})
);
@@ -285,6 +326,8 @@ export const RoomInput = forwardRef<HTMLDivElement, RoomInputProps>(
encInfo: undefined,
metadata: {
markedAsSpoiler: false,
waveform: audioMeta?.waveform,
audioDuration: audioMeta?.audioDuration,
},
})
);
@@ -453,7 +496,7 @@ export const RoomInput = forwardRef<HTMLDivElement, RoomInputProps>(
return getVideoMsgContent(mx, fileItem, upload.mxc);
}
if (fileItem.file.type.startsWith('audio')) {
return getAudioMsgContent(fileItem, upload.mxc, audioMsgWaveform, audioMsgLength);
return getAudioMsgContent(fileItem, upload.mxc);
}
return getFileMsgContent(fileItem, upload.mxc);
});
@@ -461,7 +504,8 @@ export const RoomInput = forwardRef<HTMLDivElement, RoomInputProps>(
const contents = fulfilledPromiseSettledResult(await Promise.allSettled(contentsPromises));
if (contents.length > 0) {
const replyContent = plainText?.length === 0 ? getReplyContent(replyDraft) : undefined;
const replyContent =
plainText?.length === 0 ? getReplyContent(replyDraft, room) : undefined;
if (replyContent) contents[0]['m.relates_to'] = replyContent;
if (threadRootId) {
setReplyDraft({
@@ -475,28 +519,74 @@ export const RoomInput = forwardRef<HTMLDivElement, RoomInputProps>(
}
}
await Promise.all(
contents.map((content) =>
mx
.sendMessage(roomId, threadRootId ?? null, content as any)
.then((res) => {
debugLog.info('message', 'Uploaded file message sent', {
roomId,
eventId: res.event_id,
msgtype: content.msgtype,
});
return res;
const invalidate = () =>
queryClient.invalidateQueries({ queryKey: ['delayedEvents', roomId] });
if (scheduledTime) {
try {
const delayMs = computeDelayMs(scheduledTime);
if (editingScheduledDelayId) {
await cancelDelayedEvent(mx, editingScheduledDelayId);
}
await Promise.all(
contents.map((content) => {
if (isEncrypted) {
return sendDelayedMessageE2EE(mx, roomId, room, content, delayMs);
}
return sendDelayedMessage(mx, roomId, content, delayMs);
})
.catch((error: unknown) => {
debugLog.error('message', 'Failed to send uploaded file message', {
roomId,
error: error instanceof Error ? error.message : String(error),
});
log.error('failed to send uploaded message', { roomId }, error);
throw error;
})
)
);
);
invalidate();
setEditingScheduledDelayId(null);
setScheduledTime(null);
} catch (error) {
debugLog.error('message', 'Failed to schedule uploaded file message', {
roomId,
error: error instanceof Error ? error.message : String(error),
});
log.error('failed to schedule uploaded message', { roomId }, error);
throw error;
}
} else {
if (editingScheduledDelayId) {
try {
await cancelDelayedEvent(mx, editingScheduledDelayId);
invalidate();
setEditingScheduledDelayId(null);
} catch {
debugLog.error(
'message',
'Failed to cancel scheduled event before immediate file send',
{ roomId }
);
}
}
await Promise.all(
contents.map((content) =>
mx
.sendMessage(roomId, threadRootId ?? null, content as any)
.then((res: { event_id: string }) => {
debugLog.info('message', 'Uploaded file message sent', {
roomId,
eventId: res.event_id,
msgtype: content.msgtype,
});
return res;
})
.catch((error: unknown) => {
debugLog.error('message', 'Failed to send uploaded file message', {
roomId,
error: error instanceof Error ? error.message : String(error),
});
log.error('failed to send uploaded message', { roomId }, error);
throw error;
})
)
);
}
};
const handleCloseAutocomplete = useCallback(() => {
@@ -605,7 +695,7 @@ export const RoomInput = forwardRef<HTMLDivElement, RoomInputProps>(
content.formatted_body = formattedBody;
}
if (replyDraft) {
content['m.relates_to'] = getReplyContent(replyDraft);
content['m.relates_to'] = getReplyContent(replyDraft, room);
}
const invalidate = () =>
queryClient.invalidateQueries({ queryKey: ['delayedEvents', roomId] });
@@ -665,20 +755,36 @@ export const RoomInput = forwardRef<HTMLDivElement, RoomInputProps>(
// Cancel failed — leave state intact for retry
}
} else {
const msgSendStart = performance.now();
resetInput();
debugLog.info('message', 'Sending message', { roomId, msgtype: (content as any).msgtype });
mx.sendMessage(roomId, threadRootId ?? null, content as any)
.then((res) => {
Sentry.startSpan(
{
name: 'message.send',
op: 'matrix.message',
attributes: { encrypted: String(isEncrypted) },
},
() => mx.sendMessage(roomId, threadRootId ?? null, content as any)
)
.then((res: { event_id: string }) => {
debugLog.info('message', 'Message sent successfully', {
roomId,
eventId: res.event_id,
});
Sentry.metrics.distribution(
'sable.message.send_latency_ms',
performance.now() - msgSendStart,
{ attributes: { encrypted: String(isEncrypted) } }
);
})
.catch((error: unknown) => {
debugLog.error('message', 'Failed to send message', {
roomId,
error: error instanceof Error ? error.message : String(error),
});
Sentry.metrics.count('sable.message.send_error', 1, {
attributes: { encrypted: String(isEncrypted) },
});
log.error('failed to send message', { roomId }, error);
});
}
@@ -706,6 +812,38 @@ export const RoomInput = forwardRef<HTMLDivElement, RoomInputProps>(
const handleKeyDown: KeyboardEventHandler = useCallback(
(evt) => {
const autocompleteMenu = document.querySelector('[data-autocomplete-menu]');
const isMenuVisible = !!(autocompleteQuery && autocompleteMenu);
if (isMenuVisible) {
if (isKeyHotkey('arrowdown', evt)) {
evt.preventDefault();
autocompleteMenu.dispatchEvent(
new CustomEvent('autocomplete-navigate', { detail: { direction: 1 } })
);
return;
}
if (isKeyHotkey('arrowup', evt)) {
evt.preventDefault();
autocompleteMenu.dispatchEvent(
new CustomEvent('autocomplete-navigate', { detail: { direction: -1 } })
);
return;
}
if (isKeyHotkey('enter', evt) && !isComposing(evt)) {
const selectedItem =
autocompleteMenu.querySelector<HTMLButtonElement>('button[data-selected]') ??
autocompleteMenu.querySelector<HTMLButtonElement>('button');
if (selectedItem) {
evt.preventDefault();
selectedItem.click();
return;
}
}
}
if (
(isKeyHotkey('mod+enter', evt) || (!enterForNewline && isKeyHotkey('enter', evt))) &&
!isComposing(evt)
@@ -714,9 +852,14 @@ export const RoomInput = forwardRef<HTMLDivElement, RoomInputProps>(
submit().catch((error) => {
log.error('submit failed', { roomId }, error);
});
return;
}
if (isKeyHotkey('escape', evt)) {
evt.preventDefault();
if (showAudioRecorder) {
audioRecorderRef.current?.cancel();
return;
}
if (autocompleteQuery) {
setAutocompleteQuery(undefined);
return;
@@ -724,7 +867,15 @@ export const RoomInput = forwardRef<HTMLDivElement, RoomInputProps>(
setReplyDraft(undefined);
}
},
[submit, roomId, setReplyDraft, enterForNewline, autocompleteQuery, isComposing]
[
submit,
roomId,
setReplyDraft,
enterForNewline,
autocompleteQuery,
isComposing,
showAudioRecorder,
]
);
const handleKeyUp: KeyboardEventHandler = useCallback(
@@ -792,7 +943,7 @@ export const RoomInput = forwardRef<HTMLDivElement, RoomInputProps>(
info,
};
if (replyDraft) {
content['m.relates_to'] = getReplyContent(replyDraft);
content['m.relates_to'] = getReplyContent(replyDraft, room);
if (threadRootId) {
setReplyDraft({
userId: mx.getUserId() ?? '',
@@ -926,7 +1077,7 @@ export const RoomInput = forwardRef<HTMLDivElement, RoomInputProps>(
editableName="RoomInput"
editor={editor}
key={inputKey}
placeholder="Send a message..."
placeholder={showAudioRecorder && mobileOrTablet() ? '' : 'Send a message...'}
onKeyDown={handleKeyDown}
onKeyUp={handleKeyUp}
onPaste={handlePaste}
@@ -1046,19 +1197,97 @@ export const RoomInput = forwardRef<HTMLDivElement, RoomInputProps>(
</>
}
before={
<IconButton
onClick={() => pickFile('*')}
variant="SurfaceVariant"
size="300"
radii="300"
title="Upload File"
aria-label="Upload and attach a File"
>
<Icon src={Icons.PlusCircle} />
</IconButton>
!(showAudioRecorder && mobileOrTablet()) && (
<IconButton
onClick={() => pickFile('*')}
variant="SurfaceVariant"
size="300"
radii="300"
title="Upload File"
aria-label="Upload and attach a File"
>
<Icon src={Icons.PlusCircle} />
</IconButton>
)
}
after={
<>
{showAudioRecorder && (
<AudioMessageRecorder
ref={audioRecorderRef}
onRequestClose={() => setShowAudioRecorder(false)}
onRecordingComplete={(payload) => {
const extension = getSupportedAudioExtension(payload.audioCodec);
const file = new File(
[payload.audioBlob],
`sable-audio-message-${Date.now()}.${extension}`,
{
type: payload.audioCodec,
}
);
handleFiles([file], {
waveform: payload.waveform,
audioDuration: payload.audioLength,
});
setShowAudioRecorder(false);
}}
onAudioLengthUpdate={() => {}}
onWaveformUpdate={() => {}}
/>
)}
{/* ── Mic button — always present; icon swaps to Stop while recording ── */}
<IconButton
ref={micBtnRef}
variant={showAudioRecorder ? 'Critical' : 'SurfaceVariant'}
size="300"
radii="300"
title={showAudioRecorder ? 'Stop recording' : 'Record audio message'}
aria-label={showAudioRecorder ? 'Stop recording' : 'Record audio message'}
aria-pressed={showAudioRecorder}
onClick={() => {
if (mobileOrTablet()) return;
if (showAudioRecorder) {
audioRecorderRef.current?.stop();
} else {
setShowAudioRecorder(true);
}
}}
onPointerDown={() => {
if (!mobileOrTablet()) return;
if (showAudioRecorder) return;
micHoldStartRef.current = Date.now();
setShowAudioRecorder(true);
let cleanup: () => void;
const onUp = () => {
cleanup();
const held = Date.now() - micHoldStartRef.current;
if (held >= HOLD_THRESHOLD_MS) {
setTimeout(() => {
audioRecorderRef.current?.stop();
}, 50);
} else {
setTimeout(() => {
audioRecorderRef.current?.cancel();
}, 50);
}
};
cleanup = () => {
window.removeEventListener('pointerup', onUp);
window.removeEventListener('pointercancel', cleanup);
};
window.addEventListener('pointerup', onUp);
window.addEventListener('pointercancel', cleanup);
}}
>
{showAudioRecorder ? (
<Stop size={20} weight="fill" style={{ color: color.Critical.Main }} />
) : (
<Microphone size={20} />
)}
</IconButton>
<IconButton
variant="SurfaceVariant"
size="300"
@@ -1070,47 +1299,6 @@ export const RoomInput = forwardRef<HTMLDivElement, RoomInputProps>(
>
<Icon src={toolbar ? Icons.AlphabetUnderline : Icons.Alphabet} />
</IconButton>
<IconButton
ref={micBtnRef}
variant="SurfaceVariant"
size="300"
radii="300"
title="record audio message"
aria-pressed={showAudioRecorder}
onClick={() => setShowAudioRecorder(!showAudioRecorder)}
>
<Icon src={Icons.Mic} />
</IconButton>
{showAudioRecorder && (
<PopOut
anchor={micBtnRef.current?.getBoundingClientRect() ?? undefined}
offset={8}
position="Top"
align="End"
alignOffset={-44}
content={
<AudioMessageRecorder
onRequestClose={() => {
setShowAudioRecorder(false);
}}
onRecordingComplete={(audioBlob) => {
const file = new File(
[audioBlob],
`sable-audio-message-${Date.now()}.ogg`,
{
type: audioBlob.type,
}
);
handleFiles([file]);
// Close the recorder after handling the file, to give some feedback that the recording was successful
setShowAudioRecorder(false);
}}
onAudioLengthUpdate={(len) => setAudioMsgLength(len)}
onWaveformUpdate={(w) => setAudioMsgWaveform(w)}
/>
}
/>
)}
<UseStateProvider initial={undefined}>
{(emojiBoardTab: EmojiBoardTab | undefined, setEmojiBoardTab) => (
<PopOut
+393 -93
View File
@@ -36,6 +36,7 @@ import { ReactEditor } from 'slate-react';
import { Editor } from 'slate';
import { SessionMembershipData } from 'matrix-js-sdk/lib/matrixrtc/CallMembership';
import to from 'await-to-js';
import * as Sentry from '@sentry/react';
import { useAtomValue, useSetAtom } from 'jotai';
import {
as,
@@ -205,7 +206,9 @@ export const timelineToEventsCount = (t: EventTimeline) => {
export const getTimelinesEventsCount = (timelines: EventTimeline[]): number => {
const timelineEventCountReducer = (count: number, tm: EventTimeline) =>
count + timelineToEventsCount(tm);
return (timelines || []).filter(Boolean).reduce(timelineEventCountReducer, 0);
return (timelines || [])
.filter(Boolean)
.reduce((accumulator, element) => timelineEventCountReducer(accumulator, element), 0);
};
export const getTimelineAndBaseIndex = (
@@ -290,54 +293,60 @@ const useEventTimelineLoader = (
onError: (err: Error | null) => void
) =>
useCallback(
async (eventId: string) => {
const withTimeout = async <T,>(promise: Promise<T>, timeoutMs: number): Promise<T> =>
new Promise<T>((resolve, reject) => {
const timeoutId = globalThis.setTimeout(() => {
reject(new Error('Timed out loading event timeline'));
}, timeoutMs);
async (eventId: string) =>
Sentry.startSpan({ name: 'timeline.jump_load', op: 'matrix.timeline' }, async () => {
const jumpLoadStart = performance.now();
const withTimeout = async <T,>(promise: Promise<T>, timeoutMs: number): Promise<T> =>
new Promise<T>((resolve, reject) => {
const timeoutId = globalThis.setTimeout(() => {
reject(new Error('Timed out loading event timeline'));
}, timeoutMs);
promise
.then((value) => {
globalThis.clearTimeout(timeoutId);
resolve(value);
})
.catch((error) => {
globalThis.clearTimeout(timeoutId);
reject(error);
});
});
promise
.then((value) => {
globalThis.clearTimeout(timeoutId);
resolve(value);
})
.catch((error) => {
globalThis.clearTimeout(timeoutId);
reject(error);
});
});
if (!room.getUnfilteredTimelineSet().getTimelineForEvent(eventId)) {
await withTimeout(
mx.roomInitialSync(room.roomId, PAGINATION_LIMIT),
EVENT_TIMELINE_LOAD_TIMEOUT_MS
if (!room.getUnfilteredTimelineSet().getTimelineForEvent(eventId)) {
await withTimeout(
mx.roomInitialSync(room.roomId, PAGINATION_LIMIT),
EVENT_TIMELINE_LOAD_TIMEOUT_MS
);
await withTimeout(
mx.getLatestTimeline(room.getUnfilteredTimelineSet()),
EVENT_TIMELINE_LOAD_TIMEOUT_MS
);
}
const [err, replyEvtTimeline] = await to(
withTimeout(
mx.getEventTimeline(room.getUnfilteredTimelineSet(), eventId),
EVENT_TIMELINE_LOAD_TIMEOUT_MS
)
);
await withTimeout(
mx.getLatestTimeline(room.getUnfilteredTimelineSet()),
EVENT_TIMELINE_LOAD_TIMEOUT_MS
if (!replyEvtTimeline) {
onError(err ?? null);
return;
}
const linkedTimelines = getLinkedTimelines(replyEvtTimeline);
const absIndex = getEventIdAbsoluteIndex(linkedTimelines, replyEvtTimeline, eventId);
if (absIndex === undefined) {
onError(err ?? null);
return;
}
Sentry.metrics.distribution(
'sable.timeline.jump_load_ms',
performance.now() - jumpLoadStart
);
}
const [err, replyEvtTimeline] = await to(
withTimeout(
mx.getEventTimeline(room.getUnfilteredTimelineSet(), eventId),
EVENT_TIMELINE_LOAD_TIMEOUT_MS
)
);
if (!replyEvtTimeline) {
onError(err ?? null);
return;
}
const linkedTimelines = getLinkedTimelines(replyEvtTimeline);
const absIndex = getEventIdAbsoluteIndex(linkedTimelines, replyEvtTimeline, eventId);
if (absIndex === undefined) {
onError(err ?? null);
return;
}
onLoad(eventId, linkedTimelines, absIndex);
},
onLoad(eventId, linkedTimelines, absIndex);
}), // end startSpan
[mx, room, onLoad, onError]
);
@@ -414,6 +423,7 @@ const useTimelinePagination = (
});
}
try {
const paginateStart = performance.now();
const [err] = await to(
mx.paginateEventTimeline(timelineToPaginate, {
backwards,
@@ -423,6 +433,9 @@ const useTimelinePagination = (
if (err) {
if (alive()) {
(backwards ? setBackwardStatus : setForwardStatus)('error');
Sentry.metrics.count('sable.pagination.error', 1, {
attributes: { direction: backwards ? 'backward' : 'forward' },
});
debugLog.error('timeline', 'Timeline pagination failed', {
direction: backwards ? 'backward' : 'forward',
error: err instanceof Error ? err.message : String(err),
@@ -445,6 +458,16 @@ const useTimelinePagination = (
if (alive()) {
recalibratePagination(lTimelines, timelinesEventsCount, backwards);
(backwards ? setBackwardStatus : setForwardStatus)('idle');
Sentry.metrics.distribution(
'sable.pagination.latency_ms',
performance.now() - paginateStart,
{
attributes: {
direction: backwards ? 'backward' : 'forward',
encrypted: String(!!room?.hasEncryptionStateEvent()),
},
}
);
debugLog.info('timeline', 'Timeline pagination completed', {
direction: backwards ? 'backward' : 'forward',
totalEventsNow: getTimelinesEventsCount(lTimelines),
@@ -460,6 +483,12 @@ const useTimelinePagination = (
};
const useLiveEventArrive = (room: Room, onArrive: (mEvent: MatrixEvent) => void) => {
// Stable ref so the effect dep array only contains `room`. The listener is
// registered once per room mount; onArrive can change freely without causing
// listener churn during rapid re-renders (e.g. sync error/retry cycles).
const onArriveRef = useRef(onArrive);
onArriveRef.current = onArrive;
useEffect(() => {
// Capture the live timeline and registration time. Events appended to the
// live timeline AFTER this point can be genuinely new even when
@@ -486,14 +515,14 @@ const useLiveEventArrive = (room: Room, onArrive: (mEvent: MatrixEvent) => void)
data.timeline === liveTimeline &&
mEvent.getTs() >= registeredAt - 60_000);
if (!isLive) return;
onArrive(mEvent);
onArriveRef.current(mEvent);
};
const handleRedaction: RoomEventHandlerMap[RoomEvent.Redaction] = (
mEvent: MatrixEvent,
eventRoom: Room | undefined
) => {
if (eventRoom?.roomId !== room.roomId) return;
onArrive(mEvent);
onArriveRef.current(mEvent);
};
room.on(RoomEvent.Timeline, handleTimelineEvent);
@@ -502,10 +531,13 @@ const useLiveEventArrive = (room: Room, onArrive: (mEvent: MatrixEvent) => void)
room.removeListener(RoomEvent.Timeline, handleTimelineEvent);
room.removeListener(RoomEvent.Redaction, handleRedaction);
};
}, [room, onArrive]);
}, [room]); // stable: re-register only when room changes, not on callback identity changes
};
const useRelationUpdate = (room: Room, onRelation: () => void) => {
const onRelationRef = useRef(onRelation);
onRelationRef.current = onRelation;
useEffect(() => {
const handleTimelineEvent: EventTimelineSetHandlerMap[RoomEvent.Timeline] = (
mEvent: MatrixEvent,
@@ -519,42 +551,78 @@ const useRelationUpdate = (room: Room, onRelation: () => void) => {
// also need to trigger a re-render so makeReplaced state is reflected.
if (eventRoom?.roomId !== room.roomId || data.liveEvent) return;
if (mEvent.getRelation()?.rel_type === RelationType.Replace) {
onRelation();
onRelationRef.current();
}
};
room.on(RoomEvent.Timeline, handleTimelineEvent);
return () => {
room.removeListener(RoomEvent.Timeline, handleTimelineEvent);
};
}, [room, onRelation]);
}, [room]);
};
const useLiveTimelineRefresh = (room: Room, onRefresh: () => void) => {
const onRefreshRef = useRef(onRefresh);
onRefreshRef.current = onRefresh;
useEffect(() => {
const handleTimelineRefresh: RoomEventHandlerMap[RoomEvent.TimelineRefresh] = (r: Room) => {
if (r.roomId !== room.roomId) return;
onRefresh();
// App-initiated full reinit (e.g. from refreshLiveTimeline()). Rare in normal usage.
debugLog.debug('timeline', 'TimelineRefresh: app-initiated live timeline reinit', {
roomId: room.roomId,
trigger: 'TimelineRefresh',
});
onRefreshRef.current();
};
// The SDK fires RoomEvent.TimelineReset on the EventTimelineSet (not the Room)
// when a limited sync response replaces the live EventTimeline with a fresh one.
// This happens in classic /sync on limited=true (gap after idle/reconnect) AND in
// sliding sync when the proxy sends a limited room update.
const handleTimelineReset: EventTimelineSetHandlerMap[RoomEvent.TimelineReset] = () => {
debugLog.info('timeline', 'TimelineReset: SDK-initiated (limited sync / sync gap)', {
roomId: room.roomId,
trigger: 'TimelineReset',
liveTimelineEvents: room.getUnfilteredTimelineSet().getLiveTimeline().getEvents().length,
});
Sentry.metrics.count('sable.timeline.limited_reset', 1);
Sentry.addBreadcrumb({
category: 'timeline.sync',
message: 'TimelineReset: limited sync gap',
level: 'info',
data: { roomId: room.roomId },
});
onRefreshRef.current();
};
const unfilteredTimelineSet = room.getUnfilteredTimelineSet();
room.on(RoomEvent.TimelineRefresh, handleTimelineRefresh);
unfilteredTimelineSet.on(RoomEvent.TimelineReset, handleTimelineReset);
return () => {
room.removeListener(RoomEvent.TimelineRefresh, handleTimelineRefresh);
unfilteredTimelineSet.removeListener(RoomEvent.TimelineReset, handleTimelineReset);
};
}, [room, onRefresh]);
}, [room]);
};
// Trigger re-render when thread reply counts change so the thread chip updates.
const useThreadUpdate = (room: Room, onUpdate: () => void) => {
const onUpdateRef = useRef(onUpdate);
onUpdateRef.current = onUpdate;
useEffect(() => {
room.on(ThreadEvent.New, onUpdate);
room.on(ThreadEvent.Update, onUpdate);
room.on(ThreadEvent.NewReply, onUpdate);
// Stable wrapper: the same function identity is kept for the lifetime of
// the room so add/removeListener calls always match.
const handler = () => onUpdateRef.current();
room.on(ThreadEvent.New, handler);
room.on(ThreadEvent.Update, handler);
room.on(ThreadEvent.NewReply, handler);
return () => {
room.removeListener(ThreadEvent.New, onUpdate);
room.removeListener(ThreadEvent.Update, onUpdate);
room.removeListener(ThreadEvent.NewReply, onUpdate);
room.removeListener(ThreadEvent.New, handler);
room.removeListener(ThreadEvent.Update, handler);
room.removeListener(ThreadEvent.NewReply, handler);
};
}, [room, onUpdate]);
}, [room]);
};
// Returns the number of replies in a thread, counting actual reply events
@@ -576,7 +644,12 @@ type ThreadReplyChipProps = {
onToggle: () => void;
};
function ThreadReplyChip({ room, mEventId, openThreadId, onToggle }: ThreadReplyChipProps) {
function ThreadReplyChip({
room,
mEventId,
openThreadId,
onToggle,
}: Readonly<ThreadReplyChipProps>) {
const mx = useMatrixClient();
const useAuthentication = useMediaAuthentication();
const nicknames = useAtomValue(nicknamesAtom);
@@ -602,7 +675,7 @@ function ThreadReplyChip({ room, mEventId, openThreadId, onToggle }: ThreadReply
}
});
const latestReply = replyEvents[replyEvents.length - 1];
const latestReply = replyEvents.at(-1);
const latestSenderId = latestReply?.getSender() ?? '';
const latestSenderName =
getMemberDisplayName(room, latestSenderId, nicknames) ??
@@ -706,7 +779,7 @@ export function RoomTimeline({
roomInputRef,
editor,
onEditorReset,
}: RoomTimelineProps) {
}: Readonly<RoomTimelineProps>) {
const mx = useMatrixClient();
const useAuthentication = useMediaAuthentication();
const pushProcessor = useMemo(() => new PushProcessor(mx), [mx]);
@@ -765,6 +838,10 @@ export function RoomTimeline({
const imagePackRooms: Room[] = useImagePackRooms(room.roomId, roomToParents);
const [unreadInfo, setUnreadInfo] = useState(() => getRoomUnreadInfo(room, true));
// Stable ref so listeners that only need to *read* unreadInfo don't force
// effect re-registration (and listener churn) every time a new message arrives.
const unreadInfoRef = useRef(unreadInfo);
unreadInfoRef.current = unreadInfo;
const readUptoEventIdRef = useRef<string>();
if (unreadInfo) {
readUptoEventIdRef.current = unreadInfo.readUptoEventId;
@@ -772,12 +849,44 @@ export function RoomTimeline({
const atBottomAnchorRef = useRef<HTMLElement>(null);
// TODO: The return value of "useState" should be destructured and named symmetrically (typescript:S6754)
const [atBottom, setAtBottomState] = useState<boolean>(true);
const atBottomRef = useRef(atBottom);
const setAtBottom = useCallback((val: boolean) => {
setAtBottomState(val);
atBottomRef.current = val;
}, []);
// Tracks when atBottom last changed so we can detect rapid true→false flips
// (characteristic of the IO false-positive on bulk event loads).
const atBottomLastChangedRef = useRef<number>(0);
const setAtBottom = useCallback(
(val: boolean) => {
setAtBottomState(val);
const now = Date.now();
const msSincePrevious = now - atBottomLastChangedRef.current;
atBottomLastChangedRef.current = now;
Sentry.addBreadcrumb({
category: 'ui.scroll',
message: val ? 'Timeline: scrolled to bottom' : 'Timeline: scrolled away from bottom',
level: 'info',
data: { roomId: room.roomId, msSincePrevious },
});
// Rapid flip: bottom→away within 200 ms is characteristic of the known
// IntersectionObserver false-positive triggered by bulk event loads causing
// a DOM layout shift (see memory: "RoomTimeline Stay at Bottom False-Positive").
if (!val && msSincePrevious < 200) {
Sentry.captureMessage('Timeline: rapid atBottom flip (possible spurious scroll reset)', {
level: 'warning',
extra: { roomId: room.roomId, msSincePrevious },
tags: { feature: 'timeline' },
});
}
atBottomRef.current = val;
},
[room.roomId]
);
// Set to true by the useLiveTimelineRefresh callback when the timeline is
// re-initialised (TimelineRefresh or TimelineReset). Allows the range self-heal
// effect below to run even when atBottom=false, so the virtual paginator window
// is restored to the live end without forcing a viewport scroll.
const timelineJustResetRef = useRef(false);
const scrollRef = useRef<HTMLDivElement>(null);
const scrollToBottomRef = useRef({
@@ -839,8 +948,67 @@ export function RoomTimeline({
const eventsLength = getTimelinesEventsCount(timeline.linkedTimelines);
const liveTimelineLinked = timeline.linkedTimelines.at(-1) === getLiveTimeline(room);
// Track previous eventsLength so we can calculate batch sizes.
const prevEventsLengthRef = useRef(eventsLength);
// Breadcrumb every time the timeline gains events so we can correlate message
// batches (sliding sync chunks) with scroll state changes in Sentry Replay.
useEffect(() => {
const prev = prevEventsLengthRef.current;
const delta = eventsLength - prev;
prevEventsLengthRef.current = eventsLength;
if (delta === 0) return;
const isBatch = delta > 1;
// Classify by size: single new message vs small batch vs large catch-up load
let batchSize: string;
if (delta === 1) batchSize = 'single';
else if (delta <= 20) batchSize = 'small';
else if (delta <= 100) batchSize = 'medium';
else batchSize = 'large';
Sentry.addBreadcrumb({
category: 'timeline.events',
message: `Timeline: ${delta} event${delta === 1 ? '' : 's'} added (${batchSize})`,
level: isBatch ? 'info' : 'debug',
data: {
delta,
batchSize,
eventsLength,
prevEventsLength: prev,
liveTimelineLinked,
rangeEnd: timeline.range.end,
atBottom: atBottomRef.current,
// Gap between live end and visible window — non-zero while user is scrolled back
rangeGap: eventsLength - timeline.range.end,
},
});
// A large batch (> 50) while liveTimelineLinked is the sliding-sync
// adaptive load pattern that can trigger the IO false-positive scroll reset.
// Capture a warning so it's searchable in Sentry even when no reset fires.
if (delta > 50 && liveTimelineLinked) {
Sentry.captureMessage('Timeline: large event batch from sliding sync', {
level: 'warning',
extra: { delta, eventsLength, rangeEnd: timeline.range.end, atBottom: atBottomRef.current },
tags: { feature: 'timeline', batchSize },
});
}
// atBottomRef and timeline.range.end are intentionally read at effect time, not as deps
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [eventsLength, liveTimelineLinked]);
// Log timeline component mount/unmount
useEffect(() => {
const mode = eventId ? 'jump' : 'live';
Sentry.metrics.count('sable.timeline.open', 1, { attributes: { mode } });
const initialWindowSize = timeline.range.end - timeline.range.start;
if (initialWindowSize > 0) {
Sentry.metrics.distribution('sable.timeline.render_window', initialWindowSize, {
attributes: { encrypted: String(room.hasEncryptionStateEvent()), mode },
});
}
debugLog.info('timeline', 'Timeline mounted', {
roomId: room.roomId,
eventId,
@@ -890,6 +1058,34 @@ export function RoomTimeline({
return currentTimeline;
}
// Log range changes with scroll state so we can correlate visible-content
// jumps with paginator window shifts. scrollRef is a stable ref — safe here.
const scrollEl = scrollRef.current;
const ds = newRange.start - currentTimeline.range.start;
const de = newRange.end - currentTimeline.range.end;
debugLog.debug('timeline', 'Virtual paginator range changed', {
prevRange: { start: currentTimeline.range.start, end: currentTimeline.range.end },
newRange,
deltaStart: ds,
deltaEnd: de,
scrollTop: scrollEl?.scrollTop,
scrollHeight: scrollEl?.scrollHeight,
clientHeight: scrollEl?.clientHeight,
});
Sentry.addBreadcrumb({
category: 'ui.timeline',
message: 'Timeline window shifted',
level: 'debug',
data: {
prevStart: currentTimeline.range.start,
prevEnd: currentTimeline.range.end,
newStart: newRange.start,
newEnd: newRange.end,
deltaStart: ds,
deltaEnd: de,
},
});
return { ...currentTimeline, range: newRange };
});
}, []),
@@ -957,14 +1153,17 @@ export function RoomTimeline({
// otherwise we update timeline without paginating
// so timeline can be updated with evt like: edits, reactions etc
if (atBottomRef.current && atLiveEndRef.current) {
if (document.hasFocus() && (!unreadInfo || mEvt.getSender() === mx.getUserId())) {
if (
document.hasFocus() &&
(!unreadInfoRef.current || mEvt.getSender() === mx.getUserId())
) {
// Check if the document is in focus (user is actively viewing the app),
// and either there are no unread messages or the latest message is from the current user.
// If either condition is met, trigger the markAsRead function to send a read receipt.
requestAnimationFrame(() => markAsRead(mx, mEvt.getRoomId()!, hideReads));
}
if (!document.hasFocus() && !unreadInfo) {
if (!document.hasFocus() && !unreadInfoRef.current) {
setUnreadInfo(getRoomUnreadInfo(room));
}
@@ -983,11 +1182,11 @@ export function RoomTimeline({
return;
}
setTimeline((ct) => ({ ...ct }));
if (!unreadInfo) {
if (!unreadInfoRef.current) {
setUnreadInfo(getRoomUnreadInfo(room));
}
},
[mx, room, unreadInfo, hideReads]
[mx, room, hideReads]
)
);
@@ -997,8 +1196,11 @@ export function RoomTimeline({
eventRoom: Room | undefined
) => {
if (eventRoom?.roomId !== room.roomId) return;
if (_mEvent.getAssociatedStatus() === EventStatus.NOT_SENT) {
Sentry.metrics.count('sable.message.send_failed', 1);
}
setTimeline((ct) => ({ ...ct }));
if (!unreadInfo) {
if (!unreadInfoRef.current) {
setUnreadInfo(getRoomUnreadInfo(room));
}
};
@@ -1007,7 +1209,7 @@ export function RoomTimeline({
return () => {
room.removeListener(RoomEvent.LocalEchoUpdated, handleLocalEchoUpdated);
};
}, [room, unreadInfo, setTimeline, setUnreadInfo]);
}, [room, setTimeline, setUnreadInfo]);
const handleOpenEvent = useCallback(
async (
@@ -1058,18 +1260,20 @@ export function RoomTimeline({
useLiveTimelineRefresh(
room,
useCallback(() => {
// Always reinitialize on TimelineRefresh. With sliding sync, a limited
// response replaces the room's live EventTimeline with a brand-new object,
// firing TimelineRefresh. At that moment liveTimelineLinked is stale-false
// (the stored linkedTimelines still reference the old detached object),
// so the previous guard `if (liveTimelineLinked || ...)` would silently
// skip reinit. Back-pagination then calls paginateEventTimeline against
// the dead old timeline, which no-ops, and the IntersectionObserver never
// re-fires because intersection state didn't change — causing a permanent
// hang at the top of the timeline with no spinner and no history loaded.
// Unconditionally reinitializing is correct: TimelineRefresh signals that
// the SDK has replaced the timeline chain, so any stored range/indices
// against the old chain are invalid anyway.
// Always reinitialize on TimelineRefresh/TimelineReset. With sliding sync,
// a limited response replaces the room's live EventTimeline with a brand-new
// object. At that moment liveTimelineLinked is stale-false (stored
// linkedTimelines reference the old detached chain), so any guard on that
// flag would skip reinit, causing back-pagination to no-op silently and the
// room to appear frozen. Unconditional reinit is correct: both events signal
// that stored range/indices against the old chain are invalid.
//
// Only force the viewport to the bottom if the user was already there.
// When the user has scrolled up to read history and a sync gap fires, we
// must still reinit (the old timeline is gone), but scrolling them back to
// the bottom is jarring. Instead we set timelineJustResetRef=true so the
// self-heal effect below can advance the range as events arrive on the fresh
// timeline, without atBottom=true being required.
//
// Also force atBottom=true and queue a scroll-to-bottom. The SDK fires
// TimelineRefresh before adding new events to the fresh live timeline, so
@@ -1080,11 +1284,20 @@ export function RoomTimeline({
// "Jump to Latest" button to stick permanently. Forcing atBottom here is
// correct: TimelineRefresh always reinits to the live end, so the user
// should be repositioned to the bottom regardless.
Sentry.metrics.count('sable.timeline.reinit', 1);
// When the user WAS at the bottom we still call setAtBottom(true) so a
// transient isIntersecting=false from the IntersectionObserver during the
// DOM transition cannot stick the "Jump to Latest" button on-screen.
debugLog.info('timeline', 'Live timeline refresh triggered', { roomId: room.roomId });
const wasAtBottom = atBottomRef.current;
timelineJustResetRef.current = true;
setTimeline(getInitialTimeline(room));
setAtBottom(true);
scrollToBottomRef.current.count += 1;
scrollToBottomRef.current.smooth = false;
if (wasAtBottom) {
setAtBottom(true);
scrollToBottomRef.current.count += 1;
scrollToBottomRef.current.smooth = false;
}
}, [room, setAtBottom])
);
@@ -1111,9 +1324,39 @@ export function RoomTimeline({
// position we want to display. Without this, loading more history makes it look
// like we've scrolled up because the range (0, 10) is now showing the old events
// instead of the latest ones.
//
// Also runs after a timeline reset (timelineJustResetRef=true) even when
// atBottom=false. After TimelineReset the SDK fires the event before populating
// the fresh timeline, so getInitialTimeline sees range.end=0. When events
// arrive eventsLength grows and we need to heal the range back to the live end
// regardless of the user's scroll position.
useEffect(() => {
if (atBottom && liveTimelineLinked && eventsLength > timeline.range.end) {
// More events exist than our current range shows. Adjust to stay at bottom.
const resetPending = timelineJustResetRef.current;
if ((atBottom || resetPending) && liveTimelineLinked && eventsLength > timeline.range.end) {
if (resetPending) timelineJustResetRef.current = false;
// More events exist than our current range shows. Adjust to the live end.
//
// IMPORTANT: also queue a scroll-to-bottom here. The scroll that was queued
// during TimelineReset / initial mount fires when range.end is still 0
// (the SDK fires Reset *before* populating the fresh timeline), so the DOM
// has no items yet and the scroll is a no-op. This second increment fires
// after setTimeline renders the full range, guaranteeing we actually land
// at the bottom once the events are visible.
const rangeGap = eventsLength - timeline.range.end;
scrollToBottomRef.current.count += 1;
scrollToBottomRef.current.smooth = false;
Sentry.addBreadcrumb({
category: 'ui.scroll',
message: 'Timeline: stay-at-bottom range expansion + scroll',
level: 'info',
data: {
eventsLength,
prevRangeEnd: timeline.range.end,
rangeGap,
wasReset: resetPending,
atBottom,
},
});
setTimeline((ct) => ({
...ct,
range: {
@@ -1254,7 +1497,24 @@ export function RoomTimeline({
useLayoutEffect(() => {
const scrollEl = scrollRef.current;
if (scrollEl) {
const preScrollTop = scrollEl.scrollTop;
const preScrollHeight = scrollEl.scrollHeight;
const { clientHeight } = scrollEl;
scrollToBottom(scrollEl);
// Log whether we were actually away from bottom at mount — useful for diagnosing
// rooms that open with the wrong scroll position.
const distanceFromBottom = preScrollHeight - preScrollTop - clientHeight;
debugLog.debug('timeline', 'Initial scroll to bottom (mount)', {
preScrollTop,
preScrollHeight,
clientHeight,
postScrollTop: scrollEl.scrollTop,
distanceFromBottom,
alreadyAtBottom: distanceFromBottom <= 2,
});
if (distanceFromBottom > 0) {
Sentry.metrics.distribution('sable.timeline.initial_scroll_offset_px', distanceFromBottom);
}
}
}, []);
@@ -1266,7 +1526,19 @@ export function RoomTimeline({
const forceScroll = () => {
// if the user isn't scrolling jump down to latest content
if (!atBottomRef.current) return;
const wasAtBottom = atBottomRef.current;
const preScrollTop = scrollEl?.scrollTop ?? 0;
const preScrollHeight = scrollEl?.scrollHeight ?? 0;
// Log every resize so we can see when media loads move the timeline and whether
// we corrected it (atBottom=true) or left it (atBottom=false, user is scrolled up).
debugLog.debug('timeline', 'Content resized (image/media load)', {
atBottom: wasAtBottom,
preScrollTop,
preScrollHeight,
clientHeight: scrollEl?.clientHeight,
distanceFromBottom: preScrollHeight - preScrollTop - (scrollEl?.clientHeight ?? 0),
});
if (!wasAtBottom) return;
scrollToBottom(scrollEl, 'instant');
};
@@ -1326,11 +1598,36 @@ export function RoomTimeline({
const scrollEl = scrollRef.current;
if (scrollEl) {
const behavior = scrollToBottomRef.current.smooth && !reducedMotion ? 'smooth' : 'instant';
const wasAtBottom = atBottomRef.current;
Sentry.addBreadcrumb({
category: 'ui.scroll',
message: 'Timeline: scroll-to-bottom triggered',
level: 'info',
data: { roomId: room.roomId, behavior, wasAtBottom },
});
// A scroll-to-bottom while the user was NOT at the bottom and no timeline
// reset is expected is a sign of an unexpected scroll jump.
if (!wasAtBottom && !timelineJustResetRef.current) {
Sentry.captureMessage('Timeline: scroll-to-bottom fired while user was scrolled up', {
level: 'warning',
extra: { roomId: room.roomId, behavior },
tags: { feature: 'timeline' },
});
}
// Use requestAnimationFrame to ensure the virtual paginator has finished
// updating the DOM before we scroll. This prevents scroll position from
// being stale when new messages arrive while at the bottom.
requestAnimationFrame(() => {
const preScrollTop = scrollEl.scrollTop;
const { scrollHeight } = scrollEl;
scrollToBottom(scrollEl, behavior);
debugLog.debug('timeline', 'scrollToBottom fired', {
behavior,
preScrollTop,
scrollHeight,
postScrollTop: scrollEl.scrollTop,
remainingOffset: scrollEl.scrollHeight - scrollEl.scrollTop - scrollEl.clientHeight,
});
// On Android WebView, layout may still settle after the initial scroll.
// Fire a second instant scroll after a short delay to guarantee we
// reach the true bottom (e.g. after images finish loading or the
@@ -1343,7 +1640,7 @@ export function RoomTimeline({
});
}
}
}, [scrollToBottomCount, reducedMotion]);
}, [scrollToBottomCount, reducedMotion, room.roomId]);
// Remove unreadInfo on mark as read
useEffect(() => {
@@ -1522,8 +1819,11 @@ export function RoomTimeline({
);
const handleReactionToggle = useCallback(
(targetEventId: string, key: string, shortcode?: string) =>
toggleReaction(mx, room, targetEventId, key, shortcode),
(targetEventId: string, key: string, shortcode?: string) => {
debugLog.info('ui', 'Reaction toggled', { roomId: room.roomId, targetEventId, key });
Sentry.metrics.count('sable.message.reaction.toggle', 1);
toggleReaction(mx, room, targetEventId, key, shortcode);
},
[mx, room]
);
+70 -20
View File
@@ -89,56 +89,106 @@ export const RoomViewFollowing = as<'div', RoomViewFollowingProps>(
<Text size="T300" truncate>
{names.length === 1 && (
<>
<b>{names[0]}</b>
<Text as="span" size="Inherit" priority="300">
<b style={{ WebkitTextFillColor: 'inherit' }}>{names[0]}</b>
<Text
as="span"
size="Inherit"
priority="300"
style={{ WebkitTextFillColor: 'currentColor' }}
>
{' is following the conversation.'}
</Text>
</>
)}
{names.length === 2 && (
<>
<b>{names[0]}</b>
<Text as="span" size="Inherit" priority="300">
<b style={{ WebkitTextFillColor: 'inherit' }}>{names[0]}</b>
<Text
as="span"
size="Inherit"
priority="300"
style={{ WebkitTextFillColor: 'currentColor' }}
>
{' and '}
</Text>
<b>{names[1]}</b>
<Text as="span" size="Inherit" priority="300">
<b style={{ WebkitTextFillColor: 'inherit' }}>{names[1]}</b>
<Text
as="span"
size="Inherit"
priority="300"
style={{ WebkitTextFillColor: 'currentColor' }}
>
{' are following the conversation.'}
</Text>
</>
)}
{names.length === 3 && (
<>
<b>{names[0]}</b>
<Text as="span" size="Inherit" priority="300">
<b style={{ WebkitTextFillColor: 'inherit' }}>{names[0]}</b>
<Text
as="span"
size="Inherit"
priority="300"
style={{ WebkitTextFillColor: 'currentColor' }}
>
{', '}
</Text>
<b>{names[1]}</b>
<Text as="span" size="Inherit" priority="300">
<b style={{ WebkitTextFillColor: 'inherit' }}>{names[1]}</b>
<Text
as="span"
size="Inherit"
priority="300"
style={{ WebkitTextFillColor: 'currentColor' }}
>
{' and '}
</Text>
<b>{names[2]}</b>
<Text as="span" size="Inherit" priority="300">
<b style={{ WebkitTextFillColor: 'inherit' }}>{names[2]}</b>
<Text
as="span"
size="Inherit"
priority="300"
style={{ WebkitTextFillColor: 'currentColor' }}
>
{' are following the conversation.'}
</Text>
</>
)}
{names.length > 3 && (
<>
<b>{names[0]}</b>
<Text as="span" size="Inherit" priority="300">
<b style={{ WebkitTextFillColor: 'inherit' }}>{names[0]}</b>
<Text
as="span"
size="Inherit"
priority="300"
style={{ WebkitTextFillColor: 'currentColor' }}
>
{', '}
</Text>
<b>{names[1]}</b>
<Text as="span" size="Inherit" priority="300">
<b style={{ WebkitTextFillColor: 'inherit' }}>{names[1]}</b>
<Text
as="span"
size="Inherit"
priority="300"
style={{ WebkitTextFillColor: 'currentColor' }}
>
{', '}
</Text>
<b>{names[2]}</b>
<Text as="span" size="Inherit" priority="300">
<b style={{ WebkitTextFillColor: 'inherit' }}>{names[2]}</b>
<Text
as="span"
size="Inherit"
priority="300"
style={{ WebkitTextFillColor: 'currentColor' }}
>
{' and '}
</Text>
<b>{names.length - 3} others</b>
<Text as="span" size="Inherit" priority="300">
<b style={{ WebkitTextFillColor: 'inherit' }}>{names.length - 3} others</b>
<Text
as="span"
size="Inherit"
priority="300"
style={{ WebkitTextFillColor: 'currentColor' }}
>
{' are following the conversation.'}
</Text>
</>
+9 -7
View File
@@ -340,7 +340,7 @@ const RoomMenu = forwardRef<HTMLDivElement, RoomMenuProps>(({ room, requestClose
});
RoomMenu.displayName = 'RoomMenu';
export function RoomViewHeader({ callView }: { callView?: boolean }) {
export function RoomViewHeader({ callView }: Readonly<{ callView?: boolean }>) {
const navigate = useNavigate();
const mx = useMatrixClient();
const useAuthentication = useMediaAuthentication();
@@ -361,6 +361,8 @@ export function RoomViewHeader({ callView }: { callView?: boolean }) {
.getLiveTimeline()
.getState(EventTimeline.FORWARDS)
?.maySendStateEvent('org.matrix.msc3401.call.member', mx.getUserId()!);
const [alwaysShowCallButton] = useSetting(settingsAtom, 'alwaysShowCallButton');
const shouldShowCallButton = alwaysShowCallButton || room.getJoinedMemberCount() <= 10;
const encryptionEvent = useStateEvent(room, StateEvent.RoomEncryption);
const encryptedRoom = !!encryptionEvent;
@@ -408,14 +410,14 @@ export function RoomViewHeader({ callView }: { callView?: boolean }) {
}
const lastSeenIndex = pinnedIds.indexOf(pinMarker?.last_seen_id);
if (lastSeenIndex !== -1) {
const newPins = pinnedIds.slice(lastSeenIndex + 1);
setUnreadPinsCount(newPins.length);
} else {
if (lastSeenIndex === -1) {
const oldCount = pinMarker?.count ?? 0;
const startIndex = Math.max(0, oldCount - 1);
const newCount = pinnedIds.length > 0 ? pinnedIds.length - startIndex : 0;
setUnreadPinsCount(Math.max(0, newCount));
} else {
const newPins = pinnedIds.slice(lastSeenIndex + 1);
setUnreadPinsCount(newPins.length);
}
};
checkUnreads().catch((err) => {
@@ -557,7 +559,7 @@ export function RoomViewHeader({ callView }: { callView?: boolean }) {
await mx.setRoomAccountData(room.roomId, AccountDataEvent.SablePinStatus, {
hash,
count: pinnedIds.length,
last_seen_id: pinnedIds[pinnedIds.length - 1],
last_seen_id: pinnedIds.at(-1),
});
};
@@ -708,7 +710,7 @@ export function RoomViewHeader({ callView }: { callView?: boolean }) {
</IconButton>
)}
</TooltipProvider>
{canUseCalls && <RoomCallButton room={room} />}
{canUseCalls && shouldShowCallButton && <RoomCallButton room={room} />}
<PopOut
anchor={pinMenuAnchor}
position="Bottom"
+10 -3
View File
@@ -180,6 +180,11 @@ function ThreadMessage({
const { replyEventId } = mEvent;
const relation = mEvent.getRelation();
const contentRelatesTo = mEvent.getContent()?.['m.relates_to'];
const isFallback =
relation?.is_falling_back === true || contentRelatesTo?.is_falling_back === true;
return (
<Message
key={mEvent.getId()}
@@ -214,7 +219,8 @@ function ThreadMessage({
hideReadReceipts={showHideReads}
showDeveloperTools={showDeveloperTools}
reply={
replyEventId && (
replyEventId &&
!isFallback && (
<Reply
room={room}
timelineSet={timelineSet}
@@ -719,6 +725,7 @@ export function ThreadDrawer({ room, threadRootId, onClose, overlay }: ThreadDra
hideTrack={false}
style={{
maxHeight: '200px',
height: 'fit-content',
flexShrink: 0,
}}
>
@@ -726,7 +733,7 @@ export function ThreadDrawer({ room, threadRootId, onClose, overlay }: ThreadDra
className={css.messageList}
direction="Column"
style={{
padding: `${config.space.S600} 0`,
padding: `${config.space.S400} 0 ${config.space.S200} 0`,
}}
>
<ThreadMessage {...sharedMessageProps} mEvent={rootEvent} />
@@ -772,7 +779,7 @@ export function ThreadDrawer({ room, threadRootId, onClose, overlay }: ThreadDra
<Box
className={css.messageList}
direction="Column"
style={{ padding: `${config.space.S600} 0` }}
style={{ padding: `0 0 ${config.space.S600} 0` }}
>
{replyEvents.map((mEvent, i) => {
const prevEvent = i > 0 ? replyEvents[i - 1] : undefined;
@@ -2,6 +2,7 @@ import { MatrixEvent, MatrixEventEvent, MatrixEventHandlerMap } from '$types/mat
import { ReactNode, useEffect, useState } from 'react';
import { MessageEvent } from '$types/matrix/room';
import { useMatrixClient } from '$hooks/useMatrixClient';
import * as Sentry from '@sentry/react';
type EncryptedContentProps = {
mEvent: MatrixEvent;
@@ -14,12 +15,27 @@ export function EncryptedContent({ mEvent, children }: EncryptedContentProps) {
useEffect(() => {
if (mEvent.getType() !== MessageEvent.RoomMessageEncrypted) return;
mx.decryptEventIfNeeded(mEvent).catch(() => undefined);
// Sample 5% of events for per-event decryption latency profiling
if (Math.random() < 0.05) {
const start = performance.now();
Sentry.startSpan({ name: 'decrypt.event', op: 'matrix.crypto' }, () =>
mx.decryptEventIfNeeded(mEvent).then(() => {
Sentry.metrics.distribution('sable.decryption.event_ms', performance.now() - start);
})
).catch(() => undefined);
} else {
mx.decryptEventIfNeeded(mEvent).catch(() => undefined);
}
}, [mx, mEvent]);
useEffect(() => {
toggleEncrypted(mEvent.getType() === MessageEvent.RoomMessageEncrypted);
const handleDecrypted: MatrixEventHandlerMap[MatrixEventEvent.Decrypted] = (event) => {
if (event.isDecryptionFailure()) {
Sentry.metrics.count('sable.decryption.failure', 1, {
attributes: { reason: event.decryptionFailureReason ?? 'UNKNOWN_ERROR' },
});
}
toggleEncrypted(event.getType() === MessageEvent.RoomMessageEncrypted);
};
mEvent.on(MatrixEventEvent.Decrypted, handleDecrypted);
+193 -100
View File
@@ -1,4 +1,11 @@
import { KeyboardEventHandler, MouseEventHandler, useCallback, useEffect, useState } from 'react';
import {
KeyboardEventHandler,
MouseEventHandler,
useCallback,
useEffect,
useMemo,
useState,
} from 'react';
import {
Box,
Chip,
@@ -22,8 +29,8 @@ import {
ReplacementEvent,
RelationType,
Room,
RoomMessageEventContent,
RoomMessageTextEventContent,
MsgType,
} from '$types/matrix-sdk';
import { isKeyHotkey } from 'is-hotkey';
import {
@@ -49,7 +56,7 @@ import {
ANYWHERE_AUTOCOMPLETE_PREFIXES,
} from '$components/editor';
import { useSetting } from '$state/hooks/settings';
import { settingsAtom } from '$state/settings';
import { CaptionPosition, settingsAtom } from '$state/settings';
import { UseStateProvider } from '$components/UseStateProvider';
import { EmojiBoard } from '$components/emoji-board';
import { AsyncStatus, useAsyncCallback } from '$hooks/useAsyncCallback';
@@ -58,6 +65,13 @@ import { getEditedEvent, getMentionContent, trimReplyFromFormattedBody } from '$
import { mobileOrTablet } from '$utils/user-agent';
import { useComposingCheck } from '$hooks/useComposingCheck';
import { floatingEditor } from '$styles/overrides/Composer.css';
import { RenderMessageContent } from '$components/RenderMessageContent';
import { getReactCustomHtmlParser, LINKIFY_OPTS } from '$plugins/react-custom-html-parser';
import { useSpoilerClickHandler } from '$hooks/useSpoilerClickHandler';
import { HTMLReactParserOptions } from 'html-react-parser';
import { useMediaAuthentication } from '$hooks/useMediaAuthentication';
import { Opts as LinkifyOpts } from 'linkifyjs';
import { GetContentCallback } from '$types/matrix/room';
type MessageEditorProps = {
roomId: string;
@@ -104,6 +118,7 @@ export const MessageEditor = as<'div', MessageEditorProps>(
const [saveState, save] = useAsyncCallback(
useCallback(async () => {
const oldContent = mEvent.getContent();
const plainText = toPlainText(editor.children, isMarkdown).trim();
const customHtml = trimCustomHtml(
toMatrixCustomHTML(editor.children, {
@@ -134,13 +149,12 @@ export const MessageEditor = as<'div', MessageEditorProps>(
const msgtype = mEvent.getContent().msgtype as RoomMessageTextEventContent['msgtype'];
const newContent: RoomMessageTextEventContent = {
const newContent: IContent = {
msgtype,
body: plainText,
};
const contentBody: RoomMessageTextEventContent &
Omit<ReplacementEvent<RoomMessageEventContent>, 'm.relates_to'> = {
const contentBody: IContent & Omit<ReplacementEvent<IContent>, 'm.relates_to'> = {
msgtype,
body: `* ${plainText}`,
'm.new_content': newContent,
@@ -163,15 +177,35 @@ export const MessageEditor = as<'div', MessageEditorProps>(
contentBody.formatted_body = `* ${customHtml}`;
}
const content: RoomMessageEventContent = {
...contentBody,
const content: IContent = {
...oldContent,
'm.relates_to': {
event_id: eventId,
rel_type: RelationType.Replace,
},
};
content.body = contentBody.body;
content.format = contentBody.format;
content.formatted_body = contentBody.formatted_body;
content['m.new_content'] = newContent;
if (oldContent.info !== undefined && oldContent.filename?.length > 0) {
content.filename = oldContent.filename;
content['m.new_content'].filename = oldContent.filename;
content.info = oldContent.info;
content['m.new_content'].info = oldContent.info;
return mx.sendMessage(roomId, content);
if (oldContent.file !== undefined) content['m.new_content'].file = oldContent.file;
if (oldContent.url !== undefined) content['m.new_content'].url = oldContent.url;
if (oldContent['page.codeberg.everypizza.msc4193.spoiler'] !== undefined) {
content['page.codeberg.everypizza.msc4193.spoiler'] =
oldContent['page.codeberg.everypizza.msc4193.spoiler'];
content['m.new_content']['page.codeberg.everypizza.msc4193.spoiler'] =
oldContent['page.codeberg.everypizza.msc4193.spoiler'];
}
}
return mx.sendMessage(roomId, content as any);
}, [mx, editor, roomId, mEvent, isMarkdown, getPrevBodyAndFormattedBody])
);
@@ -247,6 +281,27 @@ export const MessageEditor = as<'div', MessageEditorProps>(
}
}, [saveState, onCancel]);
const useAuthentication = useMediaAuthentication();
const linkifyOpts = useMemo<LinkifyOpts>(() => ({ ...LINKIFY_OPTS }), []);
const spoilerClickHandler = useSpoilerClickHandler();
const htmlReactParserOptions = useMemo<HTMLReactParserOptions>(
() =>
getReactCustomHtmlParser(mx, mEvent.getRoomId(), {
linkifyOpts,
useAuthentication,
handleSpoilerClick: spoilerClickHandler,
}),
[linkifyOpts, mEvent, mx, spoilerClickHandler, useAuthentication]
);
const getContent = (() => mEvent.getContent()) as GetContentCallback;
const msgType = mEvent.getContent().msgtype;
const [captionPosition] = useSetting(settingsAtom, 'captionPosition');
const captionPositionMap = {
[CaptionPosition.Above]: 'column-reverse',
[CaptionPosition.Below]: 'column',
[CaptionPosition.Inline]: 'row',
[CaptionPosition.Hidden]: 'row',
} satisfies Record<CaptionPosition, React.CSSProperties['flexDirection']>;
return (
<div {...props} ref={ref} className={`${props.className || ''} ${floatingEditor}`.trim()}>
{autocompleteQuery?.prefix === AutocompletePrefix.RoomMention && (
@@ -273,100 +328,138 @@ export const MessageEditor = as<'div', MessageEditorProps>(
requestClose={handleCloseAutocomplete}
/>
)}
<CustomEditor
editor={editor}
placeholder="Edit message..."
onKeyDown={handleKeyDown}
onKeyUp={handleKeyUp}
bottom={
<>
<Box
style={{ padding: config.space.S200, paddingTop: 0 }}
alignItems="End"
justifyContent="SpaceBetween"
gap="100"
>
<Box gap="Inherit">
<Chip
onClick={handleSave}
variant="Primary"
radii="Pill"
disabled={saveState.status === AsyncStatus.Loading}
outlined
before={
saveState.status === AsyncStatus.Loading ? (
<Spinner variant="Primary" fill="Soft" size="100" />
) : undefined
}
<Box
style={{
display: 'flex',
flexDirection: captionPositionMap[captionPosition],
}}
>
{(msgType === MsgType.Image ||
msgType === MsgType.Video ||
msgType === MsgType.Audio ||
msgType === MsgType.File) && (
<RenderMessageContent
displayName={mEvent.sender?.name ?? ''}
msgType={mEvent.getContent().msgtype ?? ''}
ts={mEvent.getTs()}
getContent={getContent}
htmlReactParserOptions={htmlReactParserOptions}
hideCaption
linkifyOpts={linkifyOpts}
/>
)}
<Box
style={
captionPosition !== CaptionPosition.Inline
? { marginTop: config.space.S400, width: '100%' }
: {
padding: config.space.S200,
wordBreak: 'break-word',
maxWidth: '100%',
width: '100%',
display: 'flex',
flexDirection: 'column',
justifyContent: 'center',
flexShrink: 1,
}
}
>
<CustomEditor
editor={editor}
placeholder="Edit message..."
onKeyDown={handleKeyDown}
onKeyUp={handleKeyUp}
bottom={
<>
<Box
style={{ padding: config.space.S200, paddingTop: 0 }}
alignItems="End"
justifyContent="SpaceBetween"
gap="100"
>
<Text size="B300">Save</Text>
</Chip>
<Chip onClick={onCancel} variant="SurfaceVariant" radii="Pill">
<Text size="B300">Cancel</Text>
</Chip>
</Box>
<Box gap="Inherit">
<IconButton
variant="SurfaceVariant"
size="300"
radii="300"
onClick={() => setToolbar(!toolbar)}
>
<Icon size="400" src={toolbar ? Icons.AlphabetUnderline : Icons.Alphabet} />
</IconButton>
<UseStateProvider initial={undefined}>
{(anchor: RectCords | undefined, setAnchor) => (
<PopOut
anchor={anchor}
alignOffset={-8}
position="Top"
align="End"
content={
<EmojiBoard
imagePackRooms={imagePackRooms ?? []}
returnFocusOnDeactivate={false}
onEmojiSelect={handleEmoticonSelect}
onCustomEmojiSelect={handleEmoticonSelect}
requestClose={() => {
setAnchor((v) => {
if (v) {
if (!mobileOrTablet()) ReactEditor.focus(editor);
return undefined;
}
return v;
});
}}
/>
<Box gap="Inherit">
<Chip
onClick={handleSave}
variant="Primary"
radii="Pill"
disabled={saveState.status === AsyncStatus.Loading}
outlined
before={
saveState.status === AsyncStatus.Loading ? (
<Spinner variant="Primary" fill="Soft" size="100" />
) : undefined
}
>
<IconButton
aria-pressed={anchor !== undefined}
onClick={
((evt) =>
setAnchor(
evt.currentTarget.getBoundingClientRect()
)) as MouseEventHandler<HTMLButtonElement>
}
variant="SurfaceVariant"
size="300"
radii="300"
>
<Icon size="400" src={Icons.Smile} filled={anchor !== undefined} />
</IconButton>
</PopOut>
)}
</UseStateProvider>
</Box>
</Box>
{toolbar && (
<div>
<Line variant="SurfaceVariant" size="300" />
<Toolbar />
</div>
)}
</>
}
/>
<Text size="B300">Save</Text>
</Chip>
<Chip onClick={onCancel} variant="SurfaceVariant" radii="Pill">
<Text size="B300">Cancel</Text>
</Chip>
</Box>
<Box gap="Inherit">
<IconButton
variant="SurfaceVariant"
size="300"
radii="300"
onClick={() => setToolbar(!toolbar)}
>
<Icon size="400" src={toolbar ? Icons.AlphabetUnderline : Icons.Alphabet} />
</IconButton>
<UseStateProvider initial={undefined}>
{(anchor: RectCords | undefined, setAnchor) => (
<PopOut
anchor={anchor}
alignOffset={-8}
position="Top"
align="End"
content={
<EmojiBoard
imagePackRooms={imagePackRooms ?? []}
returnFocusOnDeactivate={false}
onEmojiSelect={handleEmoticonSelect}
onCustomEmojiSelect={handleEmoticonSelect}
requestClose={() => {
setAnchor((v) => {
if (v) {
if (!mobileOrTablet()) ReactEditor.focus(editor);
return undefined;
}
return v;
});
}}
/>
}
>
<IconButton
aria-pressed={anchor !== undefined}
onClick={
((evt) =>
setAnchor(
evt.currentTarget.getBoundingClientRect()
)) as MouseEventHandler<HTMLButtonElement>
}
variant="SurfaceVariant"
size="300"
radii="300"
>
<Icon size="400" src={Icons.Smile} filled={anchor !== undefined} />
</IconButton>
</PopOut>
)}
</UseStateProvider>
</Box>
</Box>
{toolbar && (
<div>
<Line variant="SurfaceVariant" size="300" />
<Toolbar />
</div>
)}
</>
}
/>
</Box>
</Box>
</div>
);
}
+40 -12
View File
@@ -148,35 +148,63 @@ export type AudioMsgContent = IContent & {
audioLength?: number;
};
export const getAudioMsgContent = (
item: TUploadItem,
mxc: string,
waveform?: number[],
audioLength?: number
): AudioMsgContent => {
const { file, encInfo } = item;
const content: IContent = {
export const getAudioMsgContent = (item: TUploadItem, mxc: string): AudioMsgContent => {
const { file, encInfo, metadata } = item;
const { waveform, audioDuration, markedAsSpoiler } = metadata;
let content: IContent = {
msgtype: MsgType.Audio,
filename: file.name,
body: file.name,
body: item.body && item.body.length > 0 ? item.body : 'a voice message',
format: 'org.matrix.custom.html',
formatted_body: file.name,
formatted_body: item.body && item.body.length > 0 ? item.body : '<em>a voice message</em>',
info: {
mimetype: file.type,
size: file.size,
duration: markedAsSpoiler || !audioDuration ? 0 : audioDuration * 1000,
},
// Element-compatible unstable extensible-event keys
'org.matrix.msc1767.audio': {
waveform: waveform?.map((v) => Math.round(v * 1024)), // scale waveform values to fit in 10 bits (0-1024) for more efficient storage, as per MSC1767 spec
duration: item.metadata.markedAsSpoiler || !audioLength ? 0 : audioLength * 1000, // if marked as spoiler, set duration to 0 to hide it in clients that support msc1767
waveform: waveform?.map((v) => Math.round(v * 1024)),
duration: markedAsSpoiler || !audioDuration ? 0 : audioDuration * 1000,
},
'org.matrix.msc1767.text': item.body && item.body.length > 0 ? item.body : 'a voice message',
'org.matrix.msc3245.voice.v2': {
duration: markedAsSpoiler || !audioDuration ? 0 : audioDuration,
waveform: waveform?.map((v) => Math.round(v * 1024)),
},
// for element compat
'org.matrix.msc3245.voice': {},
};
if (encInfo) {
content.file = {
...encInfo,
url: mxc,
};
content = {
...content,
// Element-compatible unstable extensible-event keys
'org.matrix.msc1767.file': {
name: file.name,
mimetype: file.type,
size: file.size,
file: content.file,
},
};
} else {
content.url = mxc;
content = {
...content,
// Element-compatible unstable extensible-event keys
'org.matrix.msc1767.file': {
name: file.name,
mimetype: file.type,
size: file.size,
url: content.url,
},
};
}
if (item.body && item.body.length > 0) content.body = item.body;
if (item.formatted_body && item.formatted_body.length > 0) {
+3 -1
View File
@@ -407,6 +407,8 @@ export function Search({ requestClose }: SearchProps) {
<Text size="T200" priority="300">
Type <b>#</b> for rooms, <b>@</b> for DMs and <b>*</b> for spaces. Hotkey:{' '}
<b>{isMacOS() ? KeySymbol.Command : 'Ctrl'} + k</b>
{' / '}
<b>{isMacOS() ? KeySymbol.Command : 'Ctrl'} + f</b>
</Text>
</Box>
</Modal>
@@ -423,7 +425,7 @@ export function SearchModalRenderer() {
window,
useCallback(
(event) => {
if (isKeyHotkey('mod+k', event)) {
if (isKeyHotkey('mod+k', event) || isKeyHotkey('mod+f', event)) {
event.preventDefault();
if (opened) {
setOpen(false);
+3 -3
View File
@@ -35,7 +35,7 @@ export function HomeserverInfo() {
setFederationUrl(newUrl);
}
})
.catch((error2) => setVersion({ error: error2 }));
.catch((error_) => setVersion({ error: error_ }));
} else {
setVersion({ error });
}
@@ -144,7 +144,7 @@ export function HomeserverInfo() {
type AboutProps = {
requestClose: () => void;
};
export function About({ requestClose }: AboutProps) {
export function About({ requestClose }: Readonly<AboutProps>) {
const mx = useMatrixClient();
const devLabel = IS_RELEASE_TAG ? '' : '-dev';
const buildLabel = BUILD_HASH ? ` (${BUILD_HASH})` : '';
@@ -293,7 +293,7 @@ export function About({ requestClose }: AboutProps) {
target="_blank"
>
Cinny
</a>{' '}
</a>
is ©{' '}
<a
href="https://github.com/ajbura"
@@ -18,11 +18,11 @@ export function NameColorEditor({
current,
onSave,
disabled,
}: NameColorEditorProps) {
}: Readonly<NameColorEditorProps>) {
const stripQuotes = (str?: string) => {
if (!str) return '';
// to solve the silly tuwunel
return str.replace(/^["']|["']$/g, '');
return str.replaceAll(/^["']|["']$/g, '');
};
const [tempColor, setTempColor] = useState(stripQuotes(current) || '#FFFFFF');
@@ -64,7 +64,7 @@ type ProfileProps = {
profile: UserProfile;
userId: string;
};
function ProfileAvatar({ profile, userId }: ProfileProps) {
function ProfileAvatar({ profile, userId }: Readonly<ProfileProps>) {
const mx = useMatrixClient();
const useAuthentication = useMediaAuthentication();
const capabilities = useCapabilities();
@@ -218,7 +218,7 @@ function ProfileAvatar({ profile, userId }: ProfileProps) {
}
// eslint-disable-next-line @typescript-eslint/no-unused-vars
function ProfileBanner({ profile, userId }: ProfileProps) {
function ProfileBanner({ profile, userId }: Readonly<ProfileProps>) {
const mx = useMatrixClient();
const useAuthentication = useMediaAuthentication();
const [alertRemove, setAlertRemove] = useState(false);
@@ -387,7 +387,7 @@ function ProfileBanner({ profile, userId }: ProfileProps) {
);
}
function ProfileDisplayName({ profile, userId }: ProfileProps) {
function ProfileDisplayName({ profile, userId }: Readonly<ProfileProps>) {
const mx = useMatrixClient();
const capabilities = useCapabilities();
const disableSetDisplayname = capabilities['m.set_displayname']?.enabled === false;
@@ -479,7 +479,7 @@ function ProfileDisplayName({ profile, userId }: ProfileProps) {
);
}
function ProfileExtended({ profile, userId }: ProfileProps) {
function ProfileExtended({ profile, userId }: Readonly<ProfileProps>) {
const mx = useMatrixClient();
const setGlobalProfiles = useSetAtom(profilesCacheAtom);
@@ -488,12 +488,12 @@ function ProfileExtended({ profile, userId }: ProfileProps) {
const currentStatus = presence?.status || '';
// Keys we don't render here nor handle seperately but still need to exclude
const EXCLUDED_KEYS = ['kitty.meow.is_cat', 'kitty.meow.has_cats'];
const EXCLUDED_KEYS = new Set(['kitty.meow.is_cat', 'kitty.meow.has_cats']);
// Unknown fields / unimplemented non-matrix-spec fields
// Only renders them, can't edit or set
const extendedFields = Object.entries(profile.extended || {}).filter(
([key]) => !EXCLUDED_KEYS.includes(key)
([key]) => !EXCLUDED_KEYS.has(key)
);
const handleSaveField = useCallback(
@@ -585,7 +585,7 @@ function ProfileExtended({ profile, userId }: ProfileProps) {
onSave={(htmlBio) => {
handleSaveField('moe.sable.app.bio', htmlBio);
const cleanedHtml = htmlBio.replace(/<br\/><\/blockquote>/g, '</blockquote>');
const cleanedHtml = htmlBio.replaceAll('<br/></blockquote>', '</blockquote>');
handleSaveField('chat.commet.profile_bio', {
format: 'org.matrix.custom.html',
formatted_body: cleanedHtml,
@@ -642,7 +642,7 @@ type AnimalCosmeticsProps = {
profile: UserProfile;
userId: string;
};
function AnimalCosmetics({ profile, userId }: AnimalCosmeticsProps) {
function AnimalCosmetics({ profile, userId }: Readonly<AnimalCosmeticsProps>) {
const mx = useMatrixClient();
const setGlobalProfiles = useSetAtom(profilesCacheAtom);
const [renderAnimals, setRenderAnimals] = useSetting(settingsAtom, 'renderAnimals');
@@ -232,23 +232,6 @@ function IdentityCosmetics() {
);
}
function VideoCosmetics() {
const [allowPipVideos, setPipVideos] = useSetting(settingsAtom, 'allowPipVideos');
return (
<Box direction="Column" gap="100">
<Text size="L400">Video</Text>
<SequenceCard className={SequenceCardStyle} variant="SurfaceVariant" direction="Column">
<SettingTile
title="Picture in Picture Videos"
description="If your browser has it enabled, allows you to pop out the videos in the video call interface. Does not apply retroactively to current joined voice rooms."
after={<Switch variant="Primary" value={allowPipVideos} onChange={setPipVideos} />}
/>
</SequenceCard>
</Box>
);
}
type CosmeticsProps = {
requestClose: () => void;
};
@@ -278,7 +261,6 @@ export function Cosmetics({ requestClose }: CosmeticsProps) {
<IdentityCosmetics />
<JumboEmoji />
<Privacy />
<VideoCosmetics />
</Box>
</PageContent>
</Scroll>
@@ -60,7 +60,7 @@ export const ThemeSelector = as<'div', ThemeSelectorProps>(
)
);
function SelectTheme({ disabled }: { disabled?: boolean }) {
function SelectTheme({ disabled }: Readonly<{ disabled?: boolean }>) {
const themes = useThemes();
const themeNames = useThemeNames();
const [themeId, setThemeId] = useSetting(settingsAtom, 'themeId');
@@ -288,7 +288,7 @@ function ThemeSettings() {
max="100"
step="1"
value={saturation}
onChange={(e) => setSaturation(parseInt(e.target.value, 10))}
onChange={(e) => setSaturation(Number.parseInt(e.target.value, 10))}
style={{
width: toRem(160),
cursor: 'pointer',
@@ -407,7 +407,7 @@ function PageZoomInput() {
'value' in evt.target &&
typeof evt.target.value === 'string'
) {
const newZoom = parseInt(evt.target.value, 10);
const newZoom = Number.parseInt(evt.target.value, 10);
if (Number.isNaN(newZoom)) return;
const safeZoom = Math.max(Math.min(newZoom, 150), 75);
setPageZoom(safeZoom);
@@ -418,7 +418,7 @@ function PageZoomInput() {
return (
<Input
style={{ width: toRem(100) }}
variant={pageZoom === parseInt(currentZoom, 10) ? 'Secondary' : 'Success'}
variant={pageZoom === Number.parseInt(currentZoom, 10) ? 'Secondary' : 'Success'}
size="300"
radii="300"
type="number"
@@ -12,6 +12,7 @@ import { SequenceCardStyle } from '$features/settings/styles.css';
import { AccountData } from './AccountData';
import { SyncDiagnostics } from './SyncDiagnostics';
import { DebugLogViewer } from './DebugLogViewer';
import { SentrySettings } from './SentrySettings';
type DeveloperToolsProps = {
requestClose: () => void;
@@ -126,6 +127,11 @@ export function DeveloperTools({ requestClose }: DeveloperToolsProps) {
<DebugLogViewer />
</Box>
)}
{developerTools && (
<Box direction="Column" gap="100">
<SentrySettings />
</Box>
)}
</Box>
</PageContent>
</Scroll>
@@ -0,0 +1,153 @@
import { useState, useEffect } from 'react';
import { Box, Text, Switch, Button } from 'folds';
import { SequenceCard } from '$components/sequence-card';
import { SettingTile } from '$components/setting-tile';
import { SequenceCardStyle } from '$features/settings/styles.css';
import { getDebugLogger, LogCategory } from '$utils/debugLogger';
const ALL_CATEGORIES: LogCategory[] = [
'sync',
'network',
'notification',
'message',
'call',
'ui',
'timeline',
'error',
'general',
];
export function SentrySettings() {
const [categoryEnabled, setCategoryEnabled] = useState<Record<LogCategory, boolean>>(() => {
const logger = getDebugLogger();
return Object.fromEntries(
ALL_CATEGORIES.map((c) => [c, logger.getBreadcrumbCategoryEnabled(c)])
) as Record<LogCategory, boolean>;
});
const [sentryStats, setSentryStats] = useState(() => getDebugLogger().getSentryStats());
useEffect(() => {
const interval = setInterval(() => {
setSentryStats(getDebugLogger().getSentryStats());
}, 5000);
return () => clearInterval(interval);
}, []);
const handleCategoryToggle = (category: LogCategory, enabled: boolean) => {
getDebugLogger().setBreadcrumbCategoryEnabled(category, enabled);
setCategoryEnabled((prev) => ({ ...prev, [category]: enabled }));
};
const handleExportLogs = () => {
const data = getDebugLogger().exportLogs();
const blob = new Blob([data], { type: 'application/json' });
const url = URL.createObjectURL(blob);
const a = document.createElement('a');
a.href = url;
a.download = `sable-debug-logs-${Date.now()}.json`;
a.click();
URL.revokeObjectURL(url);
};
const isSentryConfigured = Boolean(import.meta.env.VITE_SENTRY_DSN);
const sentryEnabled = localStorage.getItem('sable_sentry_enabled') === 'true';
const environment = import.meta.env.VITE_SENTRY_ENVIRONMENT || import.meta.env.MODE;
const isProd = environment === 'production';
const traceSampleRate = isProd ? '10%' : '100%';
const replaySampleRate = isProd ? '10%' : '100%';
return (
<Box direction="Column" gap="100">
<Text size="L400">Error Tracking (Sentry)</Text>
<Text size="T200" style={{ opacity: 0.7 }}>
Error reporting toggles are in <strong>Settings → General → Diagnostics & Privacy</strong>.
</Text>
{!isSentryConfigured && (
<Box
style={{
padding: '12px',
backgroundColor: 'rgba(255, 193, 7, 0.1)',
borderRadius: '8px',
}}
>
<Text size="T300" style={{ color: 'orange' }}>
Sentry is not configured. Set VITE_SENTRY_DSN to enable error tracking.
</Text>
</Box>
)}
{isSentryConfigured && sentryEnabled && (
<>
<Text size="L400">Performance Metrics</Text>
<SequenceCard
className={SequenceCardStyle}
variant="SurfaceVariant"
direction="Column"
gap="400"
>
<SettingTile
title="Traces &amp; Profiles"
description={`Current environment: ${environment}. Sample rate: ${traceSampleRate}`}
/>
<SettingTile
title="Session Replay"
description={`Session sample rate: ${replaySampleRate} · On-error rate: 100%`}
/>
<SettingTile
title="Session Error Budget"
description="At most 50 error events are forwarded to Sentry per page load to prevent quota exhaustion."
/>
</SequenceCard>
<Text size="L400">Breadcrumb Categories</Text>
<Text size="T200" style={{ opacity: 0.7 }}>
Control which log categories are included as breadcrumbs in Sentry error reports.
Disabling a category reduces noise without affecting error capture.
</Text>
<SequenceCard
className={SequenceCardStyle}
variant="SurfaceVariant"
direction="Column"
gap="400"
>
{ALL_CATEGORIES.map((cat) => (
<SettingTile
key={cat}
title={cat.charAt(0).toUpperCase() + cat.slice(1)}
after={
<Switch
variant="Primary"
value={categoryEnabled[cat]}
onChange={(v) => handleCategoryToggle(cat, v)}
/>
}
/>
))}
</SequenceCard>
<Text size="L400">Debug Logs</Text>
<SequenceCard
className={SequenceCardStyle}
variant="SurfaceVariant"
direction="Column"
gap="400"
>
<SettingTile
title="Session Activity"
description={`Errors captured: ${sentryStats.errors} · Warnings captured: ${sentryStats.warnings} (updates every 5 s)`}
/>
<SettingTile
title="Export Debug Logs"
description="Download the current in-memory debug log buffer as a JSON file for offline analysis."
after={
<Button variant="Secondary" size="300" onClick={handleExportLogs}>
Export JSON
</Button>
}
/>
</SequenceCard>
</>
)}
</Box>
);
}
@@ -4,11 +4,12 @@ import { InfoCard } from '$components/info-card';
import { LanguageSpecificPronouns } from '../cosmetics/LanguageSpecificPronouns';
import { Sync } from '../general';
import { BandwidthSavingEmojis } from './BandwithSavingEmojis';
import { MSC4268HistoryShare } from './MSC4268HistoryShare';
type ExperimentalProps = {
requestClose: () => void;
};
export function Experimental({ requestClose }: ExperimentalProps) {
export function Experimental({ requestClose }: Readonly<ExperimentalProps>) {
return (
<Page>
<PageHeader outlined={false}>
@@ -33,8 +34,8 @@ export function Experimental({ requestClose }: ExperimentalProps) {
variant="Warning"
description={
<>
The features listed below may be unstable or incomplete,
<strong> use at your own risk</strong>.
The features listed below may be unstable or incomplete,{' '}
<strong>use at your own risk</strong>.
<br />
Please report any new issues potentially caused by these features!
</>
@@ -43,6 +44,7 @@ export function Experimental({ requestClose }: ExperimentalProps) {
<br />
<Box direction="Column" gap="700">
<Sync />
<MSC4268HistoryShare />
<LanguageSpecificPronouns />
<BandwidthSavingEmojis />
</Box>
@@ -0,0 +1,42 @@
import { SequenceCard } from '$components/sequence-card';
import { SettingTile } from '$components/setting-tile';
import { useSetting } from '$state/hooks/settings';
import { settingsAtom } from '$state/settings';
import { Box, Switch, Text } from 'folds';
import { SequenceCardStyle } from '../styles.css';
export function MSC4268HistoryShare() {
const [enabledMSC4268Command, setEnabledMSC4268Command] = useSetting(
settingsAtom,
'enableMSC4268CMD'
);
return (
<Box direction="Column" gap="100">
<Text size="L400">Enable Sharing of Encrypted History</Text>
<SequenceCard
className={SequenceCardStyle}
variant="SurfaceVariant"
direction="Column"
gap="100"
>
<SettingTile
title="Enable the /sharehistory command"
description="If enabled, this command will allow users to share encrypted history with other newly joined users, as per MSC4268."
after={
<Switch
variant="Primary"
value={enabledMSC4268Command}
onChange={setEnabledMSC4268Command}
title={
enabledMSC4268Command
? 'Disable /sharehistory command'
: 'Enable /sharehistory command'
}
/>
}
/>
</SequenceCard>
</Box>
);
}
+140 -10
View File
@@ -56,7 +56,7 @@ type DateHintProps = {
hasChanges: boolean;
handleReset: () => void;
};
function DateHint({ hasChanges, handleReset }: DateHintProps) {
function DateHint({ hasChanges, handleReset }: Readonly<DateHintProps>) {
const [anchor, setAnchor] = useState<RectCords>();
const categoryPadding = { padding: config.space.S200, paddingTop: 0 };
@@ -223,7 +223,7 @@ type CustomDateFormatProps = {
value: string;
onChange: (format: string) => void;
};
function CustomDateFormat({ value, onChange }: CustomDateFormatProps) {
function CustomDateFormat({ value, onChange }: Readonly<CustomDateFormatProps>) {
const [dateFormatCustom, setDateFormatCustom] = useState(value);
useEffect(() => {
@@ -288,12 +288,12 @@ type PresetDateFormatProps = {
value: string;
onChange: (format: string) => void;
};
function PresetDateFormat({ value, onChange }: PresetDateFormatProps) {
function PresetDateFormat({ value, onChange }: Readonly<PresetDateFormatProps>) {
const [menuCords, setMenuCords] = useState<RectCords>();
const dateFormatItems = useDateFormatItems();
const getDisplayDate = (format: string): string =>
format !== '' ? dayjs().format(format) : 'Custom';
format === '' ? 'Custom' : dayjs().format(format);
const handleMenu: MouseEventHandler<HTMLButtonElement> = (evt) => {
setMenuCords(evt.currentTarget.getBoundingClientRect());
@@ -415,7 +415,7 @@ function DateAndTime() {
);
}
function Editor({ isMobile }: { isMobile: boolean }) {
function Editor({ isMobile }: Readonly<{ isMobile: boolean }>) {
const [enterForNewline, setEnterForNewline] = useSetting(settingsAtom, 'enterForNewline');
const [isMarkdown, setIsMarkdown] = useSetting(settingsAtom, 'isMarkdown');
const [hideActivity, setHideActivity] = useSetting(settingsAtom, 'hideActivity');
@@ -681,7 +681,7 @@ function SelectMessageSpacing() {
);
}
function SelectRightSwipeAction({ disabled }: { disabled?: boolean }) {
function SelectRightSwipeAction({ disabled }: Readonly<{ disabled?: boolean }>) {
const [menuCords, setMenuCords] = useState<RectCords>();
const [action, setAction] = useSetting(settingsAtom, 'rightSwipeAction');
@@ -749,7 +749,7 @@ function SelectRightSwipeAction({ disabled }: { disabled?: boolean }) {
);
}
function Gestures({ isMobile }: { isMobile: boolean }) {
function Gestures({ isMobile }: Readonly<{ isMobile: boolean }>) {
const [mobileGestures, setMobileGestures] = useSetting(settingsAtom, 'mobileGestures');
return (
@@ -788,7 +788,7 @@ function EmojiSelectorThresholdInput() {
const val = evt.target.value;
setInputValue(val);
const parsed = parseInt(val, 10);
const parsed = Number.parseInt(val, 10);
if (!Number.isNaN(parsed) && parsed >= 1 && parsed <= 10) {
setEmojiThreshold(parsed);
}
@@ -809,7 +809,7 @@ function EmojiSelectorThresholdInput() {
return (
<Input
style={{ width: toRem(80) }}
variant={parseInt(inputValue, 10) === emojiThreshold ? 'Secondary' : 'Success'}
variant={Number.parseInt(inputValue, 10) === emojiThreshold ? 'Secondary' : 'Success'}
size="300"
radii="300"
type="number"
@@ -823,6 +823,31 @@ function EmojiSelectorThresholdInput() {
);
}
function Calls() {
const [alwaysShowCallButton, setAlwaysShowCallButton] = useSetting(
settingsAtom,
'alwaysShowCallButton'
);
return (
<Box direction="Column" gap="100">
<Text size="L400">Calls</Text>
<SequenceCard className={SequenceCardStyle} variant="SurfaceVariant" direction="Column">
<SettingTile
title="Show Call Button for Large Rooms"
after={
<Switch
variant="Primary"
value={alwaysShowCallButton}
onChange={setAlwaysShowCallButton}
/>
}
/>
</SequenceCard>
</Box>
);
}
function Messages() {
const [hideMembershipEvents, setHideMembershipEvents] = useSetting(
settingsAtom,
@@ -1053,7 +1078,110 @@ export function Sync() {
type GeneralProps = {
requestClose: () => void;
};
export function General({ requestClose }: GeneralProps) {
function DiagnosticsAndPrivacy() {
const [sentryEnabled, setSentryEnabled] = useState(
localStorage.getItem('sable_sentry_enabled') === 'true'
);
const [sessionReplayEnabled, setSessionReplayEnabled] = useState(
localStorage.getItem('sable_sentry_replay_enabled') === 'true'
);
const [needsRefresh, setNeedsRefresh] = useState(false);
const isSentryConfigured = Boolean(import.meta.env.VITE_SENTRY_DSN);
const handleSentryToggle = (enabled: boolean) => {
setSentryEnabled(enabled);
if (enabled) {
localStorage.setItem('sable_sentry_enabled', 'true');
} else {
localStorage.setItem('sable_sentry_enabled', 'false');
}
setNeedsRefresh(true);
};
const handleReplayToggle = (enabled: boolean) => {
setSessionReplayEnabled(enabled);
if (enabled) {
localStorage.setItem('sable_sentry_replay_enabled', 'true');
} else {
localStorage.removeItem('sable_sentry_replay_enabled');
}
setNeedsRefresh(true);
};
return (
<Box direction="Column" gap="100">
<Text size="L400">Diagnostics & Privacy</Text>
{needsRefresh && (
<Box
style={{
padding: '12px',
backgroundColor: 'rgba(33, 150, 243, 0.1)',
borderRadius: '8px',
}}
>
<Text size="T300" style={{ color: 'rgb(33, 150, 243)' }}>
Please refresh the page for these settings to take effect.
</Text>
</Box>
)}
<SequenceCard
className={SequenceCardStyle}
variant="SurfaceVariant"
direction="Column"
gap="400"
>
<SettingTile
title="Error Reporting"
description={
isSentryConfigured
? 'Send anonymous crash reports to help improve Sable. No messages, room names, or personal data are included.'
: 'Error reporting is not configured for this build.'
}
after={
<Switch
variant="Primary"
value={sentryEnabled}
onChange={handleSentryToggle}
disabled={!isSentryConfigured}
/>
}
/>
{sentryEnabled && isSentryConfigured && (
<SettingTile
title="Session Replay"
description="Allow recording of UI interactions to help debug errors. All text, media, and inputs are fully masked before sending."
after={
<Switch
variant="Primary"
value={sessionReplayEnabled}
onChange={handleReplayToggle}
/>
}
/>
)}
</SequenceCard>
<Box gap="200" wrap="Wrap" style={{ paddingTop: '4px' }}>
<Button
as="a"
href="https://github.com/SableClient/Sable/blob/dev/docs/PRIVACY.md"
rel="noreferrer noopener"
target="_blank"
variant="Secondary"
fill="Soft"
size="300"
radii="300"
before={<Icon src={Icons.Shield} size="100" filled />}
>
<Text size="B300">Privacy Policy</Text>
</Button>
</Box>
</Box>
);
}
export function General({ requestClose }: Readonly<GeneralProps>) {
return (
<Page>
<PageHeader outlined={false}>
@@ -1078,6 +1206,8 @@ export function General({ requestClose }: GeneralProps) {
<Gestures isMobile={mobileOrTablet()} />
<Editor isMobile={mobileOrTablet()} />
<Messages />
<Calls />
<DiagnosticsAndPrivacy />
</Box>
</PageContent>
</Scroll>
Loaded 100 of 180 files, more files were not shown because too many files have changed in this diff. Show more