This commit is contained in:
7w1 committed 2026-03-17 23:18:55 -05:00
1 parent fc303e2d3c
commit 74ece9e6ac
209 files changed
+15445 -1749

No files matched your search

@@ -1,5 +0,0 @@
---
sable: patch
---
added settings toggle in (General>Messages) to enable showing a tombstone for deleted messages without having to set all hidden events to visible
@@ -1,5 +0,0 @@
---
sable: patch
---
disabling quick add for encrypted sticker, this mitigates the issue of being unable to use quick to add encrypted sticker
-5
View File
@@ -1,5 +0,0 @@
---
sable: minor
---
added error page making it easier to report errors when they occur in the field
@@ -1,5 +0,0 @@
---
default: minor
---
Show group DM participants with triangle avatar layout. Group DMs now display up to 3 member avatars in a triangle formation (most recent sender on top), with bot filtering and DM count badge support.
-5
View File
@@ -1,5 +0,0 @@
---
'default': patch
---
Fix badge positioning and alignment across all sidebar components
-5
View File
@@ -1,5 +0,0 @@
---
default: patch
---
Fix bubble layout messages overflowing off the screen with embeds/images.
-5
View File
@@ -1,5 +0,0 @@
---
'default': patch
---
Fix notification handling with null safety and improved logic
@@ -0,0 +1,5 @@
---
default: patch
---
Hide presence badge in members list for users without homeserver support, mimicking room profile apperance.
-5
View File
@@ -1,5 +0,0 @@
---
default: patch
---
Fix cosmetics tab crashing if global/room/space pronouns weren't already set.
-5
View File
@@ -1,5 +0,0 @@
---
'default': patch
---
Fix reaction clicks, zoom persistence, and empty message rendering
+5
View File
@@ -0,0 +1,5 @@
---
default: patch
---
Added a toggle to notifications to disable full message mention highlighting.
-5
View File
@@ -1,5 +0,0 @@
---
'default': minor
---
Optimize sliding sync with progressive loading and improved timeline management
+5
View File
@@ -0,0 +1,5 @@
---
default: minor
---
Added a setting to Appearance that attempts to convert text in names like (it/its) into a pronoun pill, enlabed by default.
+1
View File
@@ -0,0 +1 @@
* @7w1 @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
+1 -1
View File
@@ -36,7 +36,7 @@ updates:
- package-ecosystem: npm
cooldown:
default-days: 1
default-days: 7
directory: /
schedule:
interval: daily
+26 -2
View File
@@ -9,8 +9,13 @@ on:
- '.github/actions/setup/**'
push:
tags:
- 'sable/v*'
- '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
+17 -1
View File
@@ -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:
@@ -66,7 +82,7 @@ jobs:
if [ "${{ github.event_name }}" = "pull_request" ]; then
echo "alias=pr-${{ github.event.pull_request.number }}" >> "$GITHUB_OUTPUT"
else
branch="${{ github.ref_name }}"
branch="${GITHUB_REF_NAME}"
alias="$(echo "$branch" | tr '[:upper:]' '[:lower:]' | sed 's/[^a-z0-9]/-/g' | sed 's/-\+/-/g' | sed 's/^-\|-$//g')"
echo "alias=${alias}" >> "$GITHUB_OUTPUT"
fi
+19 -7
View File
@@ -4,11 +4,17 @@ on:
push:
branches: [dev]
tags:
- 'sable/v*'
- 'v*'
pull_request:
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.') }}
+10 -2
View File
@@ -14,10 +14,18 @@ jobs:
contents: write
pull-requests: write
steps:
- name: Generate bot token
id: generate-token
uses: actions/create-github-app-token@f8d387b68d61c58ab83c6c016672934102569859
with:
app-id: ${{ secrets.APP_ID }}
private-key: ${{ secrets.APP_PRIVATE_KEY }}
- uses: actions/checkout@de0fac2e4500dabe0009e67214ff5f5447ce83dd # v6.0.2
with:
fetch-depth: 0
persist-credentials: true
token: ${{ steps.generate-token.outputs.token }}
- uses: fregante/setup-git-user@024bc0b8e177d7e77203b48dab6fb45666854b35 # v2.0.2
@@ -28,12 +36,12 @@ jobs:
- name: Prepare Release
run: knope prepare-release --verbose
env:
GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
GITHUB_TOKEN: ${{ steps.generate-token.outputs.token }}
- name: Enrich changelog and update release PR
uses: actions/github-script@ed597411d8f924073f98dfc5c65a23a2325f34cd # v8.0.0
with:
github-token: ${{ secrets.GITHUB_TOKEN }}
github-token: ${{ steps.generate-token.outputs.token }}
script: |
const fs = require("fs");
const { owner, repo } = context.repo;
+40
View File
@@ -4,11 +4,13 @@ on:
pull_request:
push:
branches: [dev]
merge_group:
jobs:
format:
name: Format check
runs-on: ubuntu-latest
if: github.head_ref != 'release'
permissions:
contents: read
steps:
@@ -26,6 +28,7 @@ jobs:
lint:
name: Lint
runs-on: ubuntu-latest
if: github.head_ref != 'release'
permissions:
contents: read
steps:
@@ -43,6 +46,7 @@ jobs:
typecheck:
name: Typecheck
runs-on: ubuntu-latest
if: github.head_ref != 'release'
permissions:
contents: read
steps:
@@ -60,6 +64,7 @@ jobs:
knip:
name: Knip
runs-on: ubuntu-latest
if: github.head_ref != 'release'
permissions:
contents: read
steps:
@@ -73,3 +78,38 @@ 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
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 and build
uses: ./.github/actions/setup
with:
build: 'true'
+2
View File
@@ -3,6 +3,7 @@ name: Require Changeset
on:
pull_request:
types: [opened, synchronize, reopened, labeled, unlabeled]
merge_group:
branches: [dev]
permissions: {}
@@ -10,6 +11,7 @@ permissions: {}
jobs:
require-changeset:
runs-on: ubuntu-latest
if: github.head_ref != 'release' && github.event_name != 'merge_group'
permissions:
contents: read
pull-requests: write
+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
+422 -329
View File
@@ -1,329 +1,422 @@
# Sable Client Changelog
## 1.7.0 (2026-03-12)
### Features
* Added ability to start calls in DMs and rooms. DM calls will trigger a notification popup & ringtone (for other sable users/compatible clients, probably). <!-- commit:0110522 -->
* Merge in upstream call things and remove the duplicate new voice room button. <!-- commit:49af037 -->
* Add button to save a sticker you see in the message timeline to your personal account sticker pack. <!-- commit:e4fb834 -->
* Added config option `hideUsernamePasswordFields` for hosts to hide username and password fields from login page. <!-- commit:7a700ab -->
* Add silent replies when clicking the bell icon during composing a reply. <!-- commit:1647586 -->
* Device names are now dynamic, showing your browser and OS (e.g., "Sable on Firefox for Windows") instead of just "Sable Web". <!-- commit:b71320e -->
* Implement an interface to allow room/space profile customization without needing to call the relating commands directly. <!-- commit:4839466 -->
* Added hover menu inside Message Version Pop-out. <!-- commit:9562aa8 -->
### Fixes
* Added a few accessibility tags to the elements involved in message composing. <!-- commit:485834b -->
* Clarify notification settings and functionality once and for all. <!-- commit:8053c45 -->
* Fix DM notifications, encrypted event notifications, and enable reaction notifications <!-- commit:976d2e8 -->
* Fix images without an empty body display as "Broken Message" <!-- commit:b66f53a -->
* Prevent overly wide emotes from taking up the entire screen width. <!-- commit:bee0356 -->
* Change to more standard compliant msgtype `m.emote` for `/headpat` event. <!-- commit:399915d -->
* fix message forwarding metadata leak when forwarding from private rooms [see issue 190](https://github.com/SableClient/Sable/issues/190) <!-- commit:6ec4f99 -->
* "Underline Links" setting no longer affects the entire app, only links in chat, bios, and room descriptions. <!-- commit:c51e895 -->
## 1.6.0 (2026-03-10)
### Features
* GitHub repo moved to [SableClient/Sable](https://github.com/SableClient/Sable) go star it!
* Added a pop-up for showing a message's edit history
* In-app bug report and feature request modal.
* Mentions now receive a full-width background highlight in the room timeline.
* Adds a **Presence Status** toggle under Settings → General.
* Rewrites the sliding sync implementation to match the Element Web approach (MSC4186).
### Fixes
* Enhance UnsupportedContent and BrokenContent to display message body.
* Notification settings page improvements.
* In-app notification banner placement fixes.
* Notification delivery bug fixes.
* Prevent multiple forwards of a message if sending is slow.
## 1.5.3 (2026-03-08)
### Fixes
* Fix scroll clamping to bottom while scrolling up.
* Fix message links sometimes scrolling to bottom of timeline instead of message + maybe other scroll bugs.
* Merge upstream call fixes
* Fix crash when invalid location events are sent.
* Add rendering of per-message-profiles.
* custom emojis are now also visible in forwards, instead of being reduced to it's shortcode
* fix: default badge unread counts to off
## 1.5.2 (2026-03-08)
### Fixes
* Add `/hug`, `/cuddle`, `/wave`, `/headpat`, and `/poke` slash commands.
* Swap Caddy port to 8080 + fixes for MDAD setups.
* Adjust media sizing and URL preview layout
* Fix picture in picture setting not effecting element-call
* Fixed an issue where the app would fail to load after completing SSO login (e.g., logging in with matrix.org). Users are now correctly redirected to the app after SSO authentication completes.
## 1.5.1 (2026-03-08)
### Fixes
* Fix recent emojis ignoring letter threshold.
* Disable in-app banners on desktop.
## 1.5.0 (2026-03-08)
### Features
* Merge Voice Call updates from upstream.
* Allow for replying to state events.
* Add message forwarding with metadata
* Add setting to enable picture-in-picture in element-call
* Add support for audio and video in URL previews if homeserver provides it.
* Added a new setting "Emoji Selector Character Threshold" to set the number of characters to type before the suggestions pop up.
* Add keyboard navigation shortcuts for unread rooms (Alt+N, Alt+Shift+Up/Down), ARIA form label associations for screen reader accessibility, and a keyboard shortcuts settings page.
* Added setting to always underline links.
* Added settings for disabling autoplay of gifs (& banners), stickers, and emojis.
* Added reduced motion setting. Let us know if any elements were missed!
* Replaced the monochrome mode with a saturation slider for more control.
* Added settings to Account that let you set if you are a cat or have cats, or not display other peoples cat status.
### Fixes
* change indexdb warning phrasing to include low disk space as possible reason
* Fix Element Call video/audio calls in DM and non-voice rooms: after joining through the lobby, the in-call grid now displays correctly instead of showing only the control bar.
* Disable autocorrect and spellcheck on the login page.
* Fix Tuwunel quotes often breaking timezones
* Improved the UI of file descriptions
* Timeline message avatars now use the room-specific avatar and display name instead of the user's global profile, when set via `/myroomavatar` or `/myroomnick`.
* In-app notification banners now appear for DMs by default; desktop banner setting defaults to off; fixed space room navigation from banner tap.
* Executing /myroomnick or /myroomavatar without a new nickname/avatar now removes the nickname/avatar.
* Split typing and read status settings, allowing toggling off one and not the other.
## 1.4.0 (2026-03-06)
### Features
* Add option to filter user pronouns based on the pronouns language
* Added a "Badge Counts for DMs Only" setting: when enabled, unread count numbers only appear on Direct Message room badges; non-DM rooms and spaces show a plain dot instead of a number, even when Show Unread Counts is on.
* Added the ability to add descriptions to uploaded files
* Fixed in-app notification banners in encrypted rooms showing "Encrypted Message" instead of the actual content. Banners now also render rich text (mentions, inline images) using the same pipeline as the timeline renderer.
* You can now remove your own reactions even if you don't have the permission to add new ones, as long as you are able to delete your own events (messages).
* Add a method of quickly adding a new text reaction to the latest message, just like emote quick react, using the prefix `+#`
* Added two toggles in Settings > Appearance > Identity for disabling rendering room/space fonts and colors.
* Added an additional toggle, Show Unread Ping Counts, to override the Show Unread Counts allowing for only pings to have counts.
### Fixes
* Rename gcolor, gfont, and gpronoun commands to scolor, sfont, and spronoun respectively.
* Improved emoji board performance by deferring image pack cache reads so the board opens instantly rather than blocking on the initial render.
* Fix dm room nicknames applying to non-dm private rooms.
* Hide delete modal after successfully deleting a message.
* Fixed media authentication handling: removed unnecessary redirect following, added error fallback UI for failed media loads, and ensured authentication headers are applied consistently when rendering inline media in HTML message bodies.
* Failed message retry and delete actions now use Chip buttons for visual consistency with the rest of the interface.
* Adds a new message pill and background app highlighted unread count.
* Mobile: changed scheduled send chevron to tap + hold
* Reply quotes now automatically retry decryption for E2EE messages, display a distinct placeholder for replies from blocked users, and fix edge cases where reply event loading could silently fail.
* Service worker push notifications now correctly deep-link to the right account and room on cold PWA launch. Notifications are automatically suppressed when the app window is already visible. The In-App (pill banner) and System (OS) notification settings are now independent: desktop shows both controls, mobile shows Push and In-App only. Tapping an in-app notification pill on mobile now opens the room timeline directly instead of routing through the space navigation panel.
* Fixed several room timeline issues with sliding sync: corrected event rendering order, more accurate scroll-to-bottom detection, phantom unread count clearing when the timeline is already at the bottom, and fixed pagination spinner state.
* In-app notification banners now appear for DMs by default, even without a mention or keyword match.
* Notification banner on desktop now defaults to off, consistent with push notification defaults.
* Fixed space room navigation when tapping an in-app notification banner for a room inside a space.
## 1.3.3 - 3/4/2026
- Fix unread counts and dot badges for muted rooms ([#118](https://github.com/7w1/sable/pull/118)) - [Evie Gauthier](https://github.com/Just-Insane)
- /raw, /rawmsg, /rawacc, /delacc, /setext, /delext for modifying arbitrary data in various places. Do not use them if you don't know what they mean. It can break things. Locked behind developer tools settings. ([#120](https://github.com/7w1/sable/pull/120))
- Quick reactions by typing +:emoji and hitting tab ([#132](https://github.com/7w1/sable/pull/132)) - [mini-bomba](https://github.com/mini-bomba)
- Add support for [MSC4140](https://github.com/matrix-org/matrix-spec-proposals/pull/4140) scheduled messages on homeservers that support it ([#113](https://github.com/7w1/sable/pull/113))
- Add /discardsession command to force discard e2ee session in current room ([#119](https://github.com/7w1/sable/issues/119), [#123](https://github.com/7w1/sable/pull/123))
- Fix consistency of nicknames in dm rooms ([#122](https://github.com/7w1/sable/pull/122)) - [Rose](https://github.com/dozro)
- Message sending improvements, color change instead of "Sending..." message. ([#128](https://github.com/7w1/sable/pull/128)) - [Evie Gauthier](https://github.com/Just-Insane)
- Fix view source scroll bar. ([#125](https://github.com/7w1/sable/pull/125))
- Added back Cinny Light theme as an option ([#80](https://github.com/7w1/sable/issues/80), [#126](https://github.com/7w1/sable/pull/126))
- Fix auto capitalization in login screen ([#131](https://github.com/7w1/sable/pull/131)) - [Rose](https://github.com/dozro)
- Automated deployments with Cloudflare Workers IaC ([#116](https://github.com/7w1/sable/pull/116)) - [haz](https://github.com/hazre)
- Notification delivery, account switching, and unread count toggle fixes ([#127](https://github.com/7w1/sable/pull/127)) - [Evie Gauthier](https://github.com/Just-Insane)
- More sliding sync fixes: cache emoji packs and fix edit message rendering ([#134](https://github.com/7w1/sable/pull/134)) - [Evie Gauthier](https://github.com/Just-Insane)
## 1.3.2 - 3/3/2026
- Content toggles in push notifications ([#88](https://github.com/7w1/sable/pull/88)) - [Evie Gauthier](https://github.com/Just-Insane)
- /rainbow command, supports markdown ([#105](https://github.com/7w1/sable/pull/105))
- Settings interface consistency updates ([#89](https://github.com/7w1/sable/pull/89), [#97](https://github.com/7w1/sable/pull/97)) - [Rosy-iso](https://github.com/Rosy-iso)
- Display statuses ([#98](https://github.com/7w1/sable/pull/98)) - [Shea](https://github.com/nushea)
- Set statuses and improve member list status apperance ([#110](https://github.com/7w1/sable/pull/110))
- More sliding sync bug fixes and improvements ([#87](https://github.com/7w1/sable/pull/87)) - [Evie Gauthier](https://github.com/Just-Insane)
- Replace `-#` small html tag with sub html tag to comply with spec. ([#90](https://github.com/7w1/sable/pull/90))
- Update reset all notifications button styles to conform better. ([#100](https://github.com/7w1/sable/pull/100))
- Fix user registration flow ([#101](https://github.com/7w1/sable/pull/101)) - [Evie Gauthier](https://github.com/Just-Insane)
- Add homeserver info to About page ([#84](https://github.com/7w1/sable/pull/84)) - [Rosy-iso](https://github.com/Rosy-iso)
- Add Accord theme, similar to another -cord ([#102](https://github.com/7w1/sable/pull/102)) - [kr0nst](https://github.com/kr0nst)
- Add Cinny Silver theme ([#80](https://github.com/7w1/sable/issues/80), [#108](https://github.com/7w1/sable/pull/108))
- Potentially fix bio scroll appearing when it shouldn't ([#104](https://github.com/7w1/sable/pull/104))
- Add /raw command to send raw message events ([#96](https://github.com/7w1/sable/issues/96), [#106](https://github.com/7w1/sable/pull/106))
- Adds a reset button and changes the system sync button to text for clarity ([#103](https://github.com/7w1/sable/issues/103), [#107](https://github.com/7w1/sable/pull/107))
- Fix logout flow to improve UX ([#111](https://github.com/7w1/sable/pull/111))
## 1.3.1 - 3/3/2026
- Important sliding sync config patches, notifications fixes, and client side toggle ([#85](https://github.com/7w1/sable/pull/85))
## 1.3.0 - 3/2/2026
- Mobile push notifications! ([#44](https://github.com/7w1/sable/issues/44), [#49](https://github.com/7w1/sable/pull/49)) - [Evie Gauthier](https://github.com/Just-Insane)
- Beta Simplified Sliding Sync support ([#67](https://github.com/7w1/sable/pull/67), [#75](https://github.com/7w1/sable/pull/75)) - [Evie Gauthier](https://github.com/Just-Insane)
- Codebase cleanups, CI improvements, and docker builds ([#26](https://github.com/7w1/sable/pull/26), [#35](https://github.com/7w1/sable/pull/35), [#62](https://github.com/7w1/sable/pull/62), [#64](https://github.com/7w1/sable/pull/64), [#65](https://github.com/7w1/sable/pull/65)) - [haz](https://github.com/hazre)
- Add room/space specific pronouns, when enabled by room/space admin. ([#30](https://github.com/7w1/sable/issues/30))
- Add validation to timezones before rendering.
- Fix invalid matrix.to event link generation ([cinnyapp#2717](https://github.com/cinnyapp/cinny/pull/2717)) - [tulir](https://github.com/tulir)
- Fix Call Rooms' chat button ([#58](https://github.com/7w1/sable/pull/58)) - [Rosy-iso](https://github.com/Rosy-iso)
- Strip quotes for mxc urls converted to http for tuwunel ([#56](https://github.com/7w1/sable/pull/56)) - [Rosy-iso](https://github.com/Rosy-iso)
- Add Sable space and announcements room to featured communities.
- Unobfusticate css in production builds.
## 1.2.3 - 3/2/2026
- Actually fix quotes around colors for tuwunel homeservers ([#46](https://github.com/7w1/sable/issues/46))
- Option to have your own message bubbles in bubble layout right aligned ([#38](https://github.com/7w1/sable/issues/38))
- Allow responding to and rendering replies with files ([#54](https://github.com/7w1/sable/pull/54)) - [nushea](https://github.com/nushea)
- Added Gruvbox theme ([#51](https://github.com/7w1/sable/pull/51)) - [dollth.ing](https://github.com/dollth-ing)
## 1.2.2 v2
- hotfix for stupid firefox cors crash
## 1.2.2 - 3/1/2026
- Fixed/updated unknown extended profile keys rendering.
- Added support for `---`, `-#`, and fixed `-` to be unordered.
- Fix quotes around colors for tuwunel homeservers ([#46](https://github.com/7w1/sable/issues/46))
- Added Rosé Pine theme ([#41](https://github.com/7w1/sable/pull/41)) - [wrigglebug](https://github.com/wrigglebug)
- Add back default Cinny Dark theme.
- Merge time formatting improvements from ([cinnyapp#2710](https://github.com/cinnyapp/cinny/pull/2710)) - [nushea](https://github.com/nushea)
- Merge Uniform avatar appearance in space/room navigation from ([cinnyapp#2713](https://github.com/cinnyapp/cinny/pull/2713)) - [wolterkam](https://github.com/wolterkam)
- Merge Streamline the confusing DM invite user experience from ([cinnyapp#2709](https://github.com/cinnyapp/cinny/pull/2709)) - [wolterkam](https://github.com/wolterkam)
## 1.2.1
- Update pronouns to match [MSC4247](https://github.com/matrix-org/matrix-spec-proposals/pull/4247) format better and support up to 3 pronoun pills on desktop, 1 on mobile ([#23](https://github.com/7w1/sable/issues/23), [#33](https://github.com/7w1/sable/pull/33)) - [ranidspace](https://github.com/ranidspace)
- Unfortunately, **everyone who set pronouns in Sable will need to reset them.**
- Fix jumbo-ified non-emojis with colons. ([#32](https://github.com/7w1/sable/issues/32))
- Show full timestamps on hover. ([cinnyapp#2699](https://github.com/cinnyapp/cinny/issues/2699))
- Enable Twitter-style emojis by default.
- Make inline editor buttons buttons.
- Name colors in pinned messages.
- Rename "Heating up" to "Petting cats"
- Concurrency guard for profile lookups.
- Hex color input for power level editor.
- Editing previous messages with keybinds no longer breaks message bar ([#36](https://github.com/7w1/sable/issues/36))
## 1.2.0
- Codebase cleanup ([#22](https://github.com/7w1/sable/pull/22)) - [haz](https://github.com/hazre)
- Fix mono font ([#18](https://github.com/7w1/sable/pull/18)) - [Alexia](https://github.com/cyrneko)
- Merge final commits from ([cinnyapp#2599](https://github.com/cinnyapp/cinny/pull/2599))
- Unread pin counter & highlighting ([#25](https://github.com/7w1/sable/pull/25), [#31](https://github.com/7w1/sable/pull/31))
## 1.1.7
- Fix delete and report button colors.
- Fix modal backgrounds missing in some menus.
- Reply is now a toggle. When you click/swipe to reply to the message you're already replying to, it's reset.
- Option to hide member events in read-only rooms, like announcement channels, so you can actually read them. Enabled by default.
- Improvements to image and pdf viewers. Touch pan/zoom, scroll wheel zoom, and better reponsiveness.
- Fixed gestures occasionally triggering inside image and pdf viewer.
## 1.1.6
- Fix crash if too many emojis present [cinnyapp#2570](https://github.com/cinnyapp/cinny/issues/2570)
## Version 1.1.5
- Various performance improvements. See commits for details.
- Fix typing indicator z index on mobile.
- Fix room nicknames not displaying.
- Fix rare crash with colorMXID [(#15)](https://github.com/7w1/sable/pull/15)
- Fix crash from long pronoun pills [(#16)](https://github.com/7w1/sable/pull/16)
## Version 1.1.4
- Various performance improvements
- Fix bio editor crashing when faced with commet bio format.
## Version 1.1.3
_skipped a number since lots of updates :3_
- Profile banners. Support's Commet's format.
- Global name colors. Can be disabled in settings.
- Even more refractoring to improve timeline & user profile speeds and caches and fix that stupid bug.
- probably introduced more bugs tbh, but things should be faster and less intense on resources?
- Pinned messages actually jump to the damn pins instead of somewhere vaguely nearby half the time.
- that is... if they've been seen before. otherwise it just gives up sadly.
- Mobile context menu is opened by double tapping on a message instead of holding.
- ~~Fixed bio editor formatting.~~ This was a lie.
- Properly clear user data when account settings are updated.
## Version 1.1.1
- More cache fixes and improvements.
- Fix flash of extra info when click on profiles sometimes.
- Added minimum width for widgit drawer.
## Version 1.1.0
- Global profile cache & automatic cache clearing on member update events along with other improvements.
- Fix unexpected bio field formats.
- Widgets support.
- (potentially) fixed rare crash when ~~changing rooms~~ existing. please...
## Version 1.0.1
- (potentially) fixed rare crash when changing rooms
- Support Commet bios.
- Raise bio limit to 1024 characters.
- Account switcher toggle in config.json.
## Version 1.0.0
- Releases provided in releases tab. Versions for Windows & Linux built via electron.
- Account switcher made by TastelessVoid. PR #1
- Gestures for mobile.
- Notifications jump to location instead of inbox.
- Merged voice & video calls from Cinny PR #2599.
- Client-side previews for some image and video formats.
- Will attempt to preview all image/video links in a message, if there are none, it generates a standard preview, forwarding the request to the homeserver.
- Bug fix for images/links/anything that loads after room is opened, properly shifting the scroll to the bottom.
- Client-side nicknames for other users. PR #3
- Inline editor for editing messages.
- Pronouns, bios, and timezones.
- Pressing send on mobile no longer closes keyboard.
- Pressing enter on mobile will always provide a newline, ignores the setting for desktop.
- More reactive UI (literally just buttons shifting up and shrinking on click)
- Added name colors and fonts to the member list sidebar.
- Added a reset button to the room name input box for dms.
- Reset's the dm room name to the name of the other user (on both ends).
- Same as saving a blank room name.
- New UI colors & fonts.
- Pronoun pills.
- Updated legacy colors (aka random name colors) to no longer be legacy and now be pretty.
- Fixed background & header for PWA on iOS devices.
- Lighten on currently hovered message.
- Privacy blur options in Appearance tab in user settings.
- Jumbo emoji size selector in Appearance tab in user settings.
- Added Cosmetics tab to room and space settings.
- New cosmetic commands, requires power level 50. Permission located in Cosmetics tab.
- /color #ffffff -> change your name color for a room
- /gcolor #111111 -> change your name color for a space
- /font monospace -> change your name font for a room
- /font Courier New -> change your name font for a space
- Hierarchies
- Room Color > Space Color > Role Color > Default
- Room Font > Space Font > Default
- _Note, if the room font is invaild it will fallback directly to default, not the space font._
- Includes all features in Cinny v4.10.5
# Sable Client Changelog
## 1.9.3 (2026-03-17)
### Fixes
* Fix autocomplete Enter & Tab key always selecting the first item and the first item not being highlighted on open. ([#310](https://github.com/SableClient/Sable/pull/310) by @Just-Insane)
* Fix messages with body empty but formatted body filled rendering as empty. ([#337](https://github.com/SableClient/Sable/pull/337) by @7w1)
* Fix emoticon autocomplete not respecting character threshold setting. ([#337](https://github.com/SableClient/Sable/pull/337) by @7w1)
* Fix images without explicit dimensions not appearing. ([#338](https://github.com/SableClient/Sable/pull/338) by @7w1)
* Fix Mac OS to macOS in the the devices tab ([#328](https://github.com/SableClient/Sable/pull/328) by @DidiDidi129)
* Improved voice message recording UI, it should now feel a lot more integrated. ([#311](https://github.com/SableClient/Sable/pull/311) by @hazre)
* Add opt-in Sentry crash reporting with a consent banner. ([#333](https://github.com/SableClient/Sable/pull/333) by @Just-Insane)
## 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
* add voice message composing ([#176](https://github.com/SableClient/Sable/pull/176) 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)
* Show group DM participants with triangle avatar layout. Group DMs now display up to 3 member avatars in a triangle formation (most recent sender on top), with bot filtering and DM count badge support. ([#212](https://github.com/SableClient/Sable/pull/212) by @Just-Insane)
* Add internal debug logging system with viewer UI, realtime updates, and instrumentation across sync, timeline, and messaging ([#245](https://github.com/SableClient/Sable/pull/245) by @Just-Insane)
* Add thread support with side panel, browser, unread badges, and cross-device sync ([#123](https://github.com/SableClient/Sable/pull/123) by @Just-Insane)
* Optimize sliding sync with progressive loading and improved timeline management ([#232](https://github.com/SableClient/Sable/pull/232) by @Just-Insane)
### Fixes
* added settings toggle in (General>Messages) to enable showing a tombstone for deleted messages without having to set all hidden events to visible ([#238](https://github.com/SableClient/Sable/pull/238) by @dozro)
* added for compatibility sake the forward meta data as defined in MSC2723 ([#257](https://github.com/SableClient/Sable/pull/257) by @dozro)
* disabling quick add for encrypted sticker, this mitigates the issue of being unable to use quick to add encrypted sticker ([#236](https://github.com/SableClient/Sable/pull/236) by @dozro)
* Fix badge positioning and alignment across all sidebar components ([#231](https://github.com/SableClient/Sable/pull/231) by @Just-Insane)
* Fix bubble layout messages overflowing off the screen with embeds/images. ([#237](https://github.com/SableClient/Sable/pull/237) by @7w1)
* Fixed unhandled promise rejections in media blob cache and added automatic retry for chunk loading failures after deployments. ([#255](https://github.com/SableClient/Sable/pull/255) by @Just-Insane)
* Fix notification handling with null safety and improved logic ([#233](https://github.com/SableClient/Sable/pull/233) by @Just-Insane)
* Fix cosmetics tab crashing if global/room/space pronouns weren't already set. ([#229](https://github.com/SableClient/Sable/pull/229) by @7w1)
* Fix reaction clicks, zoom persistence, and empty message rendering ([#234](https://github.com/SableClient/Sable/pull/234) by @Just-Insane)
* Fix call preferences not persisting. ([#273](https://github.com/SableClient/Sable/pull/273) by @7w1)
* Add width limit to notification banners ([#253](https://github.com/SableClient/Sable/pull/253) by @Vespe-r)
* removed forwarding of beeper's per message profile, as this might confuse clients ([#256](https://github.com/SableClient/Sable/pull/256) by @dozro)
* tweak emoji board for speed optimization (opt-in because of computational load increase on homeserver for thubmnail generation) ([#262](https://github.com/SableClient/Sable/pull/262) by @dozro)
* Handles a middle-click on the url preview card thumbnail image by downloading the full image from the homeserver proxy through a fetch request and opening received blob in the new tab ([#264](https://github.com/SableClient/Sable/pull/264) by @piko-piko)
## 1.7.0 (2026-03-12)
### Features
* Added ability to start calls in DMs and rooms. DM calls will trigger a notification popup & ringtone (for other sable users/compatible clients, probably). ([#165](https://github.com/SableClient/Sable/pull/165) by @7w1)
* Merge in upstream call things and remove the duplicate new voice room button. ([#184](https://github.com/SableClient/Sable/pull/184) by @7w1)
* Add button to save a sticker you see in the message timeline to your personal account sticker pack. ([#107](https://github.com/SableClient/Sable/pull/107) by @dozro)
* Added config option `hideUsernamePasswordFields` for hosts to hide username and password fields from login page. ([#146](https://github.com/SableClient/Sable/pull/146) by @7w1)
* Add silent replies when clicking the bell icon during composing a reply. ([#153](https://github.com/SableClient/Sable/pull/153) by @dozro)
* Device names are now dynamic, showing your browser and OS (e.g., "Sable on Firefox for Windows") instead of just "Sable Web". ([#187](https://github.com/SableClient/Sable/pull/187) by @hazre)
* Implement an interface to allow room/space profile customization without needing to call the relating commands directly. ([#129](https://github.com/SableClient/Sable/pull/129) by @Rosy-iso)
* Added hover menu inside Message Version Pop-out. ([#170](https://github.com/SableClient/Sable/pull/170) by @nushea)
### Fixes
* Added a few accessibility tags to the elements involved in message composing. ([#163](https://github.com/SableClient/Sable/pull/163) by @dozro)
* Clarify notification settings and functionality once and for all. ([#148](https://github.com/SableClient/Sable/pull/148) by @7w1)
* Fix DM notifications, encrypted event notifications, and enable reaction notifications ([#178](https://github.com/SableClient/Sable/pull/178) by @Just-Insane)
* Fix images without an empty body display as "Broken Message" ([#143](https://github.com/SableClient/Sable/pull/143) by @7w1)
* Prevent overly wide emotes from taking up the entire screen width. ([#164](https://github.com/SableClient/Sable/pull/164) by @Sugaryyyy)
* Change to more standard compliant msgtype `m.emote` for `/headpat` event. ([#145](https://github.com/SableClient/Sable/pull/145) by @dozro)
* fix message forwarding metadata leak when forwarding from private rooms [see issue 190](https://github.com/SableClient/Sable/issues/190) ([#191](https://github.com/SableClient/Sable/pull/191) by @dozro)
* "Underline Links" setting no longer affects the entire app, only links in chat, bios, and room descriptions. ([#157](https://github.com/SableClient/Sable/pull/157) by @hazre)
## 1.6.0 (2026-03-10)
### Features
* GitHub repo moved to [SableClient/Sable](https://github.com/SableClient/Sable) go star it!
* Added a pop-up for showing a message's edit history
* In-app bug report and feature request modal.
* Mentions now receive a full-width background highlight in the room timeline.
* Adds a **Presence Status** toggle under Settings → General.
* Rewrites the sliding sync implementation to match the Element Web approach (MSC4186).
### Fixes
* Enhance UnsupportedContent and BrokenContent to display message body.
* Notification settings page improvements.
* In-app notification banner placement fixes.
* Notification delivery bug fixes.
* Prevent multiple forwards of a message if sending is slow.
## 1.5.3 (2026-03-08)
### Fixes
* Fix scroll clamping to bottom while scrolling up.
* Fix message links sometimes scrolling to bottom of timeline instead of message + maybe other scroll bugs.
* Merge upstream call fixes
* Fix crash when invalid location events are sent.
* Add rendering of per-message-profiles.
* custom emojis are now also visible in forwards, instead of being reduced to it's shortcode
* fix: default badge unread counts to off
## 1.5.2 (2026-03-08)
### Fixes
* Add `/hug`, `/cuddle`, `/wave`, `/headpat`, and `/poke` slash commands.
* Swap Caddy port to 8080 + fixes for MDAD setups.
* Adjust media sizing and URL preview layout
* Fix picture in picture setting not effecting element-call
* Fixed an issue where the app would fail to load after completing SSO login (e.g., logging in with matrix.org). Users are now correctly redirected to the app after SSO authentication completes.
## 1.5.1 (2026-03-08)
### Fixes
* Fix recent emojis ignoring letter threshold.
* Disable in-app banners on desktop.
## 1.5.0 (2026-03-08)
### Features
* Merge Voice Call updates from upstream.
* Allow for replying to state events.
* Add message forwarding with metadata
* Add setting to enable picture-in-picture in element-call
* Add support for audio and video in URL previews if homeserver provides it.
* Added a new setting "Emoji Selector Character Threshold" to set the number of characters to type before the suggestions pop up.
* Add keyboard navigation shortcuts for unread rooms (Alt+N, Alt+Shift+Up/Down), ARIA form label associations for screen reader accessibility, and a keyboard shortcuts settings page.
* Added setting to always underline links.
* Added settings for disabling autoplay of gifs (& banners), stickers, and emojis.
* Added reduced motion setting. Let us know if any elements were missed!
* Replaced the monochrome mode with a saturation slider for more control.
* Added settings to Account that let you set if you are a cat or have cats, or not display other peoples cat status.
### Fixes
* change indexdb warning phrasing to include low disk space as possible reason
* Fix Element Call video/audio calls in DM and non-voice rooms: after joining through the lobby, the in-call grid now displays correctly instead of showing only the control bar.
* Disable autocorrect and spellcheck on the login page.
* Fix Tuwunel quotes often breaking timezones
* Improved the UI of file descriptions
* Timeline message avatars now use the room-specific avatar and display name instead of the user's global profile, when set via `/myroomavatar` or `/myroomnick`.
* In-app notification banners now appear for DMs by default; desktop banner setting defaults to off; fixed space room navigation from banner tap.
* Executing /myroomnick or /myroomavatar without a new nickname/avatar now removes the nickname/avatar.
* Split typing and read status settings, allowing toggling off one and not the other.
## 1.4.0 (2026-03-06)
### Features
* Add option to filter user pronouns based on the pronouns language
* Added a "Badge Counts for DMs Only" setting: when enabled, unread count numbers only appear on Direct Message room badges; non-DM rooms and spaces show a plain dot instead of a number, even when Show Unread Counts is on.
* Added the ability to add descriptions to uploaded files
* Fixed in-app notification banners in encrypted rooms showing "Encrypted Message" instead of the actual content. Banners now also render rich text (mentions, inline images) using the same pipeline as the timeline renderer.
* You can now remove your own reactions even if you don't have the permission to add new ones, as long as you are able to delete your own events (messages).
* Add a method of quickly adding a new text reaction to the latest message, just like emote quick react, using the prefix `+#`
* Added two toggles in Settings > Appearance > Identity for disabling rendering room/space fonts and colors.
* Added an additional toggle, Show Unread Ping Counts, to override the Show Unread Counts allowing for only pings to have counts.
### Fixes
* Rename gcolor, gfont, and gpronoun commands to scolor, sfont, and spronoun respectively.
* Improved emoji board performance by deferring image pack cache reads so the board opens instantly rather than blocking on the initial render.
* Fix dm room nicknames applying to non-dm private rooms.
* Hide delete modal after successfully deleting a message.
* Fixed media authentication handling: removed unnecessary redirect following, added error fallback UI for failed media loads, and ensured authentication headers are applied consistently when rendering inline media in HTML message bodies.
* Failed message retry and delete actions now use Chip buttons for visual consistency with the rest of the interface.
* Adds a new message pill and background app highlighted unread count.
* Mobile: changed scheduled send chevron to tap + hold
* Reply quotes now automatically retry decryption for E2EE messages, display a distinct placeholder for replies from blocked users, and fix edge cases where reply event loading could silently fail.
* Service worker push notifications now correctly deep-link to the right account and room on cold PWA launch. Notifications are automatically suppressed when the app window is already visible. The In-App (pill banner) and System (OS) notification settings are now independent: desktop shows both controls, mobile shows Push and In-App only. Tapping an in-app notification pill on mobile now opens the room timeline directly instead of routing through the space navigation panel.
* Fixed several room timeline issues with sliding sync: corrected event rendering order, more accurate scroll-to-bottom detection, phantom unread count clearing when the timeline is already at the bottom, and fixed pagination spinner state.
* In-app notification banners now appear for DMs by default, even without a mention or keyword match.
* Notification banner on desktop now defaults to off, consistent with push notification defaults.
* Fixed space room navigation when tapping an in-app notification banner for a room inside a space.
## 1.3.3 - 3/4/2026
- Fix unread counts and dot badges for muted rooms ([#118](https://github.com/7w1/sable/pull/118)) - [Evie Gauthier](https://github.com/Just-Insane)
- /raw, /rawmsg, /rawacc, /delacc, /setext, /delext for modifying arbitrary data in various places. Do not use them if you don't know what they mean. It can break things. Locked behind developer tools settings. ([#120](https://github.com/7w1/sable/pull/120))
- Quick reactions by typing +:emoji and hitting tab ([#132](https://github.com/7w1/sable/pull/132)) - [mini-bomba](https://github.com/mini-bomba)
- Add support for [MSC4140](https://github.com/matrix-org/matrix-spec-proposals/pull/4140) scheduled messages on homeservers that support it ([#113](https://github.com/7w1/sable/pull/113))
- Add /discardsession command to force discard e2ee session in current room ([#119](https://github.com/7w1/sable/issues/119), [#123](https://github.com/7w1/sable/pull/123))
- Fix consistency of nicknames in dm rooms ([#122](https://github.com/7w1/sable/pull/122)) - [Rose](https://github.com/dozro)
- Message sending improvements, color change instead of "Sending..." message. ([#128](https://github.com/7w1/sable/pull/128)) - [Evie Gauthier](https://github.com/Just-Insane)
- Fix view source scroll bar. ([#125](https://github.com/7w1/sable/pull/125))
- Added back Cinny Light theme as an option ([#80](https://github.com/7w1/sable/issues/80), [#126](https://github.com/7w1/sable/pull/126))
- Fix auto capitalization in login screen ([#131](https://github.com/7w1/sable/pull/131)) - [Rose](https://github.com/dozro)
- Automated deployments with Cloudflare Workers IaC ([#116](https://github.com/7w1/sable/pull/116)) - [haz](https://github.com/hazre)
- Notification delivery, account switching, and unread count toggle fixes ([#127](https://github.com/7w1/sable/pull/127)) - [Evie Gauthier](https://github.com/Just-Insane)
- More sliding sync fixes: cache emoji packs and fix edit message rendering ([#134](https://github.com/7w1/sable/pull/134)) - [Evie Gauthier](https://github.com/Just-Insane)
## 1.3.2 - 3/3/2026
- Content toggles in push notifications ([#88](https://github.com/7w1/sable/pull/88)) - [Evie Gauthier](https://github.com/Just-Insane)
- /rainbow command, supports markdown ([#105](https://github.com/7w1/sable/pull/105))
- Settings interface consistency updates ([#89](https://github.com/7w1/sable/pull/89), [#97](https://github.com/7w1/sable/pull/97)) - [Rosy-iso](https://github.com/Rosy-iso)
- Display statuses ([#98](https://github.com/7w1/sable/pull/98)) - [Shea](https://github.com/nushea)
- Set statuses and improve member list status apperance ([#110](https://github.com/7w1/sable/pull/110))
- More sliding sync bug fixes and improvements ([#87](https://github.com/7w1/sable/pull/87)) - [Evie Gauthier](https://github.com/Just-Insane)
- Replace `-#` small html tag with sub html tag to comply with spec. ([#90](https://github.com/7w1/sable/pull/90))
- Update reset all notifications button styles to conform better. ([#100](https://github.com/7w1/sable/pull/100))
- Fix user registration flow ([#101](https://github.com/7w1/sable/pull/101)) - [Evie Gauthier](https://github.com/Just-Insane)
- Add homeserver info to About page ([#84](https://github.com/7w1/sable/pull/84)) - [Rosy-iso](https://github.com/Rosy-iso)
- Add Accord theme, similar to another -cord ([#102](https://github.com/7w1/sable/pull/102)) - [kr0nst](https://github.com/kr0nst)
- Add Cinny Silver theme ([#80](https://github.com/7w1/sable/issues/80), [#108](https://github.com/7w1/sable/pull/108))
- Potentially fix bio scroll appearing when it shouldn't ([#104](https://github.com/7w1/sable/pull/104))
- Add /raw command to send raw message events ([#96](https://github.com/7w1/sable/issues/96), [#106](https://github.com/7w1/sable/pull/106))
- Adds a reset button and changes the system sync button to text for clarity ([#103](https://github.com/7w1/sable/issues/103), [#107](https://github.com/7w1/sable/pull/107))
- Fix logout flow to improve UX ([#111](https://github.com/7w1/sable/pull/111))
## 1.3.1 - 3/3/2026
- Important sliding sync config patches, notifications fixes, and client side toggle ([#85](https://github.com/7w1/sable/pull/85))
## 1.3.0 - 3/2/2026
- Mobile push notifications! ([#44](https://github.com/7w1/sable/issues/44), [#49](https://github.com/7w1/sable/pull/49)) - [Evie Gauthier](https://github.com/Just-Insane)
- Beta Simplified Sliding Sync support ([#67](https://github.com/7w1/sable/pull/67), [#75](https://github.com/7w1/sable/pull/75)) - [Evie Gauthier](https://github.com/Just-Insane)
- Codebase cleanups, CI improvements, and docker builds ([#26](https://github.com/7w1/sable/pull/26), [#35](https://github.com/7w1/sable/pull/35), [#62](https://github.com/7w1/sable/pull/62), [#64](https://github.com/7w1/sable/pull/64), [#65](https://github.com/7w1/sable/pull/65)) - [haz](https://github.com/hazre)
- Add room/space specific pronouns, when enabled by room/space admin. ([#30](https://github.com/7w1/sable/issues/30))
- Add validation to timezones before rendering.
- Fix invalid matrix.to event link generation ([cinnyapp#2717](https://github.com/cinnyapp/cinny/pull/2717)) - [tulir](https://github.com/tulir)
- Fix Call Rooms' chat button ([#58](https://github.com/7w1/sable/pull/58)) - [Rosy-iso](https://github.com/Rosy-iso)
- Strip quotes for mxc urls converted to http for tuwunel ([#56](https://github.com/7w1/sable/pull/56)) - [Rosy-iso](https://github.com/Rosy-iso)
- Add Sable space and announcements room to featured communities.
- Unobfusticate css in production builds.
## 1.2.3 - 3/2/2026
- Actually fix quotes around colors for tuwunel homeservers ([#46](https://github.com/7w1/sable/issues/46))
- Option to have your own message bubbles in bubble layout right aligned ([#38](https://github.com/7w1/sable/issues/38))
- Allow responding to and rendering replies with files ([#54](https://github.com/7w1/sable/pull/54)) - [nushea](https://github.com/nushea)
- Added Gruvbox theme ([#51](https://github.com/7w1/sable/pull/51)) - [dollth.ing](https://github.com/dollth-ing)
## 1.2.2 v2
- hotfix for stupid firefox cors crash
## 1.2.2 - 3/1/2026
- Fixed/updated unknown extended profile keys rendering.
- Added support for `---`, `-#`, and fixed `-` to be unordered.
- Fix quotes around colors for tuwunel homeservers ([#46](https://github.com/7w1/sable/issues/46))
- Added Rosé Pine theme ([#41](https://github.com/7w1/sable/pull/41)) - [wrigglebug](https://github.com/wrigglebug)
- Add back default Cinny Dark theme.
- Merge time formatting improvements from ([cinnyapp#2710](https://github.com/cinnyapp/cinny/pull/2710)) - [nushea](https://github.com/nushea)
- Merge Uniform avatar appearance in space/room navigation from ([cinnyapp#2713](https://github.com/cinnyapp/cinny/pull/2713)) - [wolterkam](https://github.com/wolterkam)
- Merge Streamline the confusing DM invite user experience from ([cinnyapp#2709](https://github.com/cinnyapp/cinny/pull/2709)) - [wolterkam](https://github.com/wolterkam)
## 1.2.1
- Update pronouns to match [MSC4247](https://github.com/matrix-org/matrix-spec-proposals/pull/4247) format better and support up to 3 pronoun pills on desktop, 1 on mobile ([#23](https://github.com/7w1/sable/issues/23), [#33](https://github.com/7w1/sable/pull/33)) - [ranidspace](https://github.com/ranidspace)
- Unfortunately, **everyone who set pronouns in Sable will need to reset them.**
- Fix jumbo-ified non-emojis with colons. ([#32](https://github.com/7w1/sable/issues/32))
- Show full timestamps on hover. ([cinnyapp#2699](https://github.com/cinnyapp/cinny/issues/2699))
- Enable Twitter-style emojis by default.
- Make inline editor buttons buttons.
- Name colors in pinned messages.
- Rename "Heating up" to "Petting cats"
- Concurrency guard for profile lookups.
- Hex color input for power level editor.
- Editing previous messages with keybinds no longer breaks message bar ([#36](https://github.com/7w1/sable/issues/36))
## 1.2.0
- Codebase cleanup ([#22](https://github.com/7w1/sable/pull/22)) - [haz](https://github.com/hazre)
- Fix mono font ([#18](https://github.com/7w1/sable/pull/18)) - [Alexia](https://github.com/cyrneko)
- Merge final commits from ([cinnyapp#2599](https://github.com/cinnyapp/cinny/pull/2599))
- Unread pin counter & highlighting ([#25](https://github.com/7w1/sable/pull/25), [#31](https://github.com/7w1/sable/pull/31))
## 1.1.7
- Fix delete and report button colors.
- Fix modal backgrounds missing in some menus.
- Reply is now a toggle. When you click/swipe to reply to the message you're already replying to, it's reset.
- Option to hide member events in read-only rooms, like announcement channels, so you can actually read them. Enabled by default.
- Improvements to image and pdf viewers. Touch pan/zoom, scroll wheel zoom, and better reponsiveness.
- Fixed gestures occasionally triggering inside image and pdf viewer.
## 1.1.6
- Fix crash if too many emojis present [cinnyapp#2570](https://github.com/cinnyapp/cinny/issues/2570)
## Version 1.1.5
- Various performance improvements. See commits for details.
- Fix typing indicator z index on mobile.
- Fix room nicknames not displaying.
- Fix rare crash with colorMXID [(#15)](https://github.com/7w1/sable/pull/15)
- Fix crash from long pronoun pills [(#16)](https://github.com/7w1/sable/pull/16)
## Version 1.1.4
- Various performance improvements
- Fix bio editor crashing when faced with commet bio format.
## Version 1.1.3
_skipped a number since lots of updates :3_
- Profile banners. Support's Commet's format.
- Global name colors. Can be disabled in settings.
- Even more refractoring to improve timeline & user profile speeds and caches and fix that stupid bug.
- probably introduced more bugs tbh, but things should be faster and less intense on resources?
- Pinned messages actually jump to the damn pins instead of somewhere vaguely nearby half the time.
- that is... if they've been seen before. otherwise it just gives up sadly.
- Mobile context menu is opened by double tapping on a message instead of holding.
- ~~Fixed bio editor formatting.~~ This was a lie.
- Properly clear user data when account settings are updated.
## Version 1.1.1
- More cache fixes and improvements.
- Fix flash of extra info when click on profiles sometimes.
- Added minimum width for widgit drawer.
## Version 1.1.0
- Global profile cache & automatic cache clearing on member update events along with other improvements.
- Fix unexpected bio field formats.
- Widgets support.
- (potentially) fixed rare crash when ~~changing rooms~~ existing. please...
## Version 1.0.1
- (potentially) fixed rare crash when changing rooms
- Support Commet bios.
- Raise bio limit to 1024 characters.
- Account switcher toggle in config.json.
## Version 1.0.0
- Releases provided in releases tab. Versions for Windows & Linux built via electron.
- Account switcher made by TastelessVoid. PR #1
- Gestures for mobile.
- Notifications jump to location instead of inbox.
- Merged voice & video calls from Cinny PR #2599.
- Client-side previews for some image and video formats.
- Will attempt to preview all image/video links in a message, if there are none, it generates a standard preview, forwarding the request to the homeserver.
- Bug fix for images/links/anything that loads after room is opened, properly shifting the scroll to the bottom.
- Client-side nicknames for other users. PR #3
- Inline editor for editing messages.
- Pronouns, bios, and timezones.
- Pressing send on mobile no longer closes keyboard.
- Pressing enter on mobile will always provide a newline, ignores the setting for desktop.
- More reactive UI (literally just buttons shifting up and shrinking on click)
- Added name colors and fonts to the member list sidebar.
- Added a reset button to the room name input box for dms.
- Reset's the dm room name to the name of the other user (on both ends).
- Same as saving a blank room name.
- New UI colors & fonts.
- Pronoun pills.
- Updated legacy colors (aka random name colors) to no longer be legacy and now be pretty.
- Fixed background & header for PWA on iOS devices.
- Lighten on currently hovered message.
- Privacy blur options in Appearance tab in user settings.
- Jumbo emoji size selector in Appearance tab in user settings.
- Added Cosmetics tab to room and space settings.
- New cosmetic commands, requires power level 50. Permission located in Cosmetics tab.
- /color #ffffff -> change your name color for a room
- /gcolor #111111 -> change your name color for a space
- /font monospace -> change your name font for a room
- /font Courier New -> change your name font for a space
- Hierarchies
- Room Color > Space Color > Role Color > Default
- Room Font > Space Font > Default
- _Note, if the room font is invaild it will fallback directly to default, not the space font._
- Includes all features in Cinny v4.10.5
+1 -1
View File
@@ -60,7 +60,7 @@ representative at an online or offline event.
Instances of abusive, harassing, or otherwise unacceptable behavior may be
reported to the community leaders responsible for enforcement at
cinnyapp@gmail.com.
executioner@sable.moe.
All complaints will be reviewed and investigated promptly and fairly.
All community leaders are obligated to respect the privacy and security of the
+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.7.0",
"version": "1.9.3",
"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"
}
}
+1147 -17
View File
File diff suppressed because it is too large. Load diff
+10 -8
View File
@@ -1,20 +1,22 @@
engineStrict: true
minimumReleaseAge: 1440
allowBuilds:
'@sentry/cli': true
'@swc/core': true
esbuild: true
sharp: true
unrs-resolver: true
workerd: true
engineStrict: true
minimumReleaseAge: 1440
minimumReleaseAgeExclude:
- '@sableclient/sable-call-embedded'
overrides:
serialize-javascript: '>=7.0.3'
rollup: '>=4.59.0'
minimatch: '>=10.2.3'
lodash: '>=4.17.23'
esbuild: '>=0.25.0'
brace-expansion: '>=1.1.12'
esbuild: '>=0.25.0'
lodash: '>=4.17.23'
minimatch: '>=10.2.3'
rollup: '>=4.59.0'
serialize-javascript: '>=7.0.3'
peerDependencyRules:
allowedVersions:
+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%',
},
]);
+12 -8
View File
@@ -26,13 +26,6 @@ import { CustomElement } from './slate';
import * as css from './Editor.css';
import { toggleKeyboardShortcut } from './keyboard';
const initialValue: CustomElement[] = [
{
type: BlockType.Paragraph,
children: [{ text: '' }],
},
];
const withInline = (editor: Editor): Editor => {
const { isInline } = editor;
@@ -96,6 +89,15 @@ export const CustomEditor = forwardRef<HTMLDivElement, CustomEditorProps>(
},
ref
) => {
// Each <Slate> instance must receive its own fresh node objects.
// Sharing a module-level constant causes Slate's global NODE_TO_ELEMENT
// WeakMap to be overwritten when multiple editors are mounted at the same
// time (e.g. RoomInput + MessageEditor in the thread drawer), leading to
// "Unable to find the path for Slate node" crashes.
const [slateInitialValue] = useState<CustomElement[]>(() => [
{ type: BlockType.Paragraph, children: [{ text: '' }] },
]);
const renderElement = useCallback(
(props: RenderElementProps) => <RenderElement {...props} />,
[]
@@ -132,7 +134,7 @@ export const CustomEditor = forwardRef<HTMLDivElement, CustomEditorProps>(
return (
<div className={`${css.Editor} ${className || ''}`} ref={ref}>
<Slate editor={editor} initialValue={initialValue} onChange={onChange}>
<Slate editor={editor} initialValue={slateInitialValue} onChange={onChange}>
{top}
<Box alignItems="Start">
{before && (
@@ -158,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,
});
@@ -0,0 +1,193 @@
import { type ReactNode } from 'react';
import { describe, it, expect, vi } from 'vitest';
import { render, act } from '@testing-library/react';
import {
AutocompleteMenu,
AUTOCOMPLETE_NAVIGATE_EVENT,
type AutocompleteNavigateDetail,
} from './AutocompleteMenu';
// ── Mocks ─────────────────────────────────────────────────────────────────────
vi.mock('focus-trap-react', () => ({
default: ({ children }: { children: ReactNode }) => <>{children}</>,
}));
vi.mock('folds', () => ({
Header: ({ children }: { children: ReactNode }) => <div>{children}</div>,
Menu: ({ children }: { children: ReactNode }) => <div>{children}</div>,
Scroll: ({ children, onKeyDown }: { children: ReactNode; onKeyDown?: unknown }) => (
// eslint-disable-next-line jsx-a11y/no-static-element-interactions
<div onKeyDown={onKeyDown as React.KeyboardEventHandler}>{children}</div>
),
config: { space: { S200: '8px' } },
Icons: {},
}));
vi.mock('$utils/keyboard', () => ({
preventScrollWithArrowKey: vi.fn(),
stopPropagation: vi.fn(() => true),
}));
vi.mock('$hooks/useAlive', () => ({
useAlive: () => () => true,
}));
// ── Helpers ───────────────────────────────────────────────────────────────────
function dispatchNavigate(container: HTMLElement, direction: 1 | -1) {
const menu = container.querySelector('[data-autocomplete-menu]');
if (!menu) throw new Error('data-autocomplete-menu element not found');
menu.dispatchEvent(
new CustomEvent<AutocompleteNavigateDetail>(AUTOCOMPLETE_NAVIGATE_EVENT, {
bubbles: true,
detail: { direction },
})
);
}
function renderMenu(children: ReactNode) {
return render(
<AutocompleteMenu headerContent={<span>header</span>} requestClose={() => {}}>
{children}
</AutocompleteMenu>
);
}
// ── Tests ─────────────────────────────────────────────────────────────────────
describe('AutocompleteMenu — data-selected stamping', () => {
it('stamps the first button with data-selected="true" on initial render', () => {
const { container } = renderMenu(
<>
<button type="button">Item 0</button>
<button type="button">Item 1</button>
<button type="button">Item 2</button>
</>
);
const buttons = container.querySelectorAll<HTMLButtonElement>('button');
expect(buttons[0].getAttribute('data-selected')).toBe('true');
expect(buttons[1].getAttribute('data-selected')).toBe('false');
expect(buttons[2].getAttribute('data-selected')).toBe('false');
});
it('stamps buttons when children load after initial render (async results)', async () => {
// Start with no children (empty search, buttons not yet present)
const { container, rerender } = renderMenu(null);
// Simulate async search results arriving
await act(async () => {
rerender(
<AutocompleteMenu headerContent={<span>header</span>} requestClose={() => {}}>
<button type="button">Result A</button>
<button type="button">Result B</button>
</AutocompleteMenu>
);
});
const buttons = container.querySelectorAll<HTMLButtonElement>('button');
expect(buttons).toHaveLength(2);
// First button must be marked selected — this was the bug: with the old
// [selectedIndex] dep array the effect didn't re-run when buttons appeared.
expect(buttons[0].getAttribute('data-selected')).toBe('true');
expect(buttons[1].getAttribute('data-selected')).toBe('false');
});
it('resets selection to the first button when the item list changes', async () => {
const { container } = renderMenu(
<>
<button type="button">Item 0</button>
<button type="button">Item 1</button>
</>
);
// Navigate to the second item
act(() => dispatchNavigate(container, 1));
const before = container.querySelectorAll<HTMLButtonElement>('button');
expect(before[1].getAttribute('data-selected')).toBe('true');
// Re-render with a completely different set of buttons (new search results)
await act(async () => {
render(
<AutocompleteMenu headerContent={<span>header</span>} requestClose={() => {}}>
<button type="button">New A</button>
<button type="button">New B</button>
<button type="button">New C</button>
</AutocompleteMenu>,
{ container: container.firstElementChild?.parentElement ?? document.body }
);
});
});
});
describe('AutocompleteMenu — keyboard navigation', () => {
it('moves selection forward with direction +1', () => {
const { container } = renderMenu(
<>
<button type="button">Item 0</button>
<button type="button">Item 1</button>
<button type="button">Item 2</button>
</>
);
act(() => dispatchNavigate(container, 1));
const buttons = container.querySelectorAll<HTMLButtonElement>('button');
expect(buttons[0].getAttribute('data-selected')).toBe('false');
expect(buttons[1].getAttribute('data-selected')).toBe('true');
expect(buttons[2].getAttribute('data-selected')).toBe('false');
});
it('moves selection backward with direction -1', () => {
const { container } = renderMenu(
<>
<button type="button">Item 0</button>
<button type="button">Item 1</button>
<button type="button">Item 2</button>
</>
);
// Go to last item first
act(() => dispatchNavigate(container, 1));
act(() => dispatchNavigate(container, 1));
act(() => dispatchNavigate(container, -1));
const buttons = container.querySelectorAll<HTMLButtonElement>('button');
expect(buttons[0].getAttribute('data-selected')).toBe('false');
expect(buttons[1].getAttribute('data-selected')).toBe('true');
expect(buttons[2].getAttribute('data-selected')).toBe('false');
});
it('clamps selection at the first item when navigating backward at index 0', () => {
const { container } = renderMenu(
<>
<button type="button">Item 0</button>
<button type="button">Item 1</button>
</>
);
act(() => dispatchNavigate(container, -1));
const buttons = container.querySelectorAll<HTMLButtonElement>('button');
expect(buttons[0].getAttribute('data-selected')).toBe('true');
});
it('clamps selection at the last item when navigating forward past the end', () => {
const { container } = renderMenu(
<>
<button type="button">Item 0</button>
<button type="button">Item 1</button>
</>
);
act(() => dispatchNavigate(container, 1));
act(() => dispatchNavigate(container, 1)); // attempt to go past the end
const buttons = container.querySelectorAll<HTMLButtonElement>('button');
expect(buttons[0].getAttribute('data-selected')).toBe('false');
expect(buttons[1].getAttribute('data-selected')).toBe('true');
});
});
@@ -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,46 @@ export function AutocompleteMenu({ headerContent, requestClose, children }: Auto
}
};
// Sync data-selected to DOM; reset to index 0 when the item list changes.
// No dep array — runs after every render so newly-loaded buttons are stamped
// immediately (buttons arrive async when search results load).
// setSelectedIndex is a stable React setter; the conditional call never
// triggers an infinite update chain (it only fires when button count changes).
// eslint-disable-next-line react-hooks/exhaustive-deps
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));
});
});
// 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 +77,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 +85,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);
};
+60 -14
View File
@@ -30,6 +30,8 @@ import { useMediaAuthentication } from '$hooks/useMediaAuthentication';
import { ImagePack, ImageUsage, PackImageReader } from '$plugins/custom-emoji';
import { getEmoticonSearchStr } from '$plugins/utils';
import { VirtualTile } from '$components/virtualizer';
import { useSetting } from '$state/hooks/settings';
import { settingsAtom } from '$state/settings';
import { useEmojiGroupIcons } from './useEmojiGroupIcons';
import { useEmojiGroupLabels } from './useEmojiGroupLabels';
import {
@@ -133,7 +135,7 @@ const useGroups = (
return [emojiGroupItems, stickerGroupItems];
};
const useItemRenderer = (tab: EmojiBoardTab) => {
const useItemRenderer = (tab: EmojiBoardTab, saveStickerEmojiBandwidth: boolean) => {
const mx = useMatrixClient();
const useAuthentication = useMediaAuthentication();
@@ -148,6 +150,7 @@ const useItemRenderer = (tab: EmojiBoardTab) => {
mx={mx}
useAuthentication={useAuthentication}
image={emoji}
saveStickerEmojiBandwidth={saveStickerEmojiBandwidth}
/>
);
}
@@ -157,6 +160,7 @@ const useItemRenderer = (tab: EmojiBoardTab) => {
mx={mx}
useAuthentication={useAuthentication}
image={emoji}
saveStickerEmojiBandwidth={saveStickerEmojiBandwidth}
/>
);
};
@@ -167,9 +171,15 @@ const useItemRenderer = (tab: EmojiBoardTab) => {
type EmojiSidebarProps = {
activeGroupAtom: PrimitiveAtom<string | undefined>;
packs: ImagePack[];
saveStickerEmojiBandwidth: boolean;
onScrollToGroup: (groupId: string) => void;
};
function EmojiSidebar({ activeGroupAtom, packs, onScrollToGroup }: EmojiSidebarProps) {
function EmojiSidebar({
activeGroupAtom,
packs,
saveStickerEmojiBandwidth,
onScrollToGroup,
}: Readonly<EmojiSidebarProps>) {
const mx = useMatrixClient();
const useAuthentication = useMediaAuthentication();
@@ -201,8 +211,11 @@ function EmojiSidebar({ activeGroupAtom, packs, onScrollToGroup }: EmojiSidebarP
let label = pack.meta.name;
if (!label) label = isUserId(pack.id) ? 'Personal Pack' : mx.getRoom(pack.id)?.name;
const url =
mxcUrlToHttp(mx, pack.getAvatarUrl(usage) ?? '', useAuthentication) ?? undefined;
// limit width and height to 36 to prevent very large icons from breaking the layout, since custom emoji pack icons can be of any size
// trying to get close to the render target size of the icons in the sidebar, which is around 24px
const url = saveStickerEmojiBandwidth
? mxcUrlToHttp(mx, pack.getAvatarUrl(usage) ?? '', useAuthentication, 36, 36)
: mxcUrlToHttp(mx, pack.getAvatarUrl(usage) ?? '', useAuthentication);
return (
<ImageGroupIcon
@@ -210,7 +223,7 @@ function EmojiSidebar({ activeGroupAtom, packs, onScrollToGroup }: EmojiSidebarP
active={activeGroupId === pack.id}
id={pack.id}
label={label ?? 'Unknown Pack'}
url={url}
url={url ?? undefined}
onClick={handleScrollToGroup}
/>
);
@@ -243,9 +256,15 @@ function EmojiSidebar({ activeGroupAtom, packs, onScrollToGroup }: EmojiSidebarP
type StickerSidebarProps = {
activeGroupAtom: PrimitiveAtom<string | undefined>;
packs: ImagePack[];
saveStickerEmojiBandwidth: boolean;
onScrollToGroup: (groupId: string) => void;
};
function StickerSidebar({ activeGroupAtom, packs, onScrollToGroup }: StickerSidebarProps) {
function StickerSidebar({
activeGroupAtom,
packs,
saveStickerEmojiBandwidth,
onScrollToGroup,
}: Readonly<StickerSidebarProps>) {
const mx = useMatrixClient();
const useAuthentication = useMediaAuthentication();
@@ -264,8 +283,11 @@ function StickerSidebar({ activeGroupAtom, packs, onScrollToGroup }: StickerSide
let label = pack.meta.name;
if (!label) label = isUserId(pack.id) ? 'Personal Pack' : mx.getRoom(pack.id)?.name;
const url =
mxcUrlToHttp(mx, pack.getAvatarUrl(usage) ?? '', useAuthentication) ?? undefined;
// limit width and height to 36 to prevent very large icons from breaking the layout, since custom emoji pack icons can be of any size
// trying to get close to the render target size of the icons in the sidebar, which is around 24px
const url = saveStickerEmojiBandwidth
? mxcUrlToHttp(mx, pack.getAvatarUrl(usage) ?? '', useAuthentication, 36, 36)
: mxcUrlToHttp(mx, pack.getAvatarUrl(usage) ?? '', useAuthentication);
return (
<ImageGroupIcon
@@ -273,7 +295,7 @@ function StickerSidebar({ activeGroupAtom, packs, onScrollToGroup }: StickerSide
active={activeGroupId === pack.id}
id={pack.id}
label={label ?? 'Unknown Pack'}
url={url}
url={url ?? undefined}
onClick={handleScrollToGroup}
/>
);
@@ -294,7 +316,7 @@ function EmojiGroupHolder({
previewAtom,
onGroupItemClick,
children,
}: EmojiGroupHolderProps) {
}: Readonly<EmojiGroupHolderProps>) {
const setPreviewData = useSetAtom(previewAtom);
const handleEmojiPreview = useCallback(
@@ -375,8 +397,9 @@ export function EmojiBoard({
onStickerSelect,
allowTextCustomEmoji,
addToRecentEmoji = true,
}: EmojiBoardProps) {
}: Readonly<EmojiBoardProps>) {
const mx = useMatrixClient();
const [saveStickerEmojiBandwidth] = useSetting(settingsAtom, 'saveStickerEmojiBandwidth');
const emojiTab = tab === EmojiBoardTab.Emoji;
const usage = emojiTab ? ImageUsage.Emoticon : ImageUsage.Sticker;
@@ -390,7 +413,7 @@ export function EmojiBoard({
const imagePacks = useRelevantImagePacks(usage, imagePackRooms);
const [emojiGroupItems, stickerGroupItems] = useGroups(tab, imagePacks);
const groups = emojiTab ? emojiGroupItems : stickerGroupItems;
const renderItem = useItemRenderer(tab);
const renderItem = useItemRenderer(tab, saveStickerEmojiBandwidth);
const searchList = useMemo(() => {
let list: Array<PackImageReader | IEmoji> = [];
@@ -424,7 +447,28 @@ export function EmojiBoard({
const virtualizer = useVirtualizer({
count: groups.length,
getScrollElement: () => contentScrollRef.current,
estimateSize: () => 40,
estimateSize: (index: number) => {
const group = groups[index];
if (!group) return emojiTab ? 320 : 420;
/**
* estimate tile size: stickers are generally larger than emojis, and custom emojis can vary in size but are often larger than standard emojis, so we use a larger estimate for them.
* This is a rough estimate to help the virtualizer calculate the total height and which items are in view.
* The actual rendered size may vary, but this should provide a reasonable approximation for most cases.
*/
const tile = emojiTab ? 48 : 112;
/**
* estimate number of columns that can fit in the view, with a min of 1 to avoid division by zero
*/
const cols = Math.max(1, Math.floor(280 / tile));
/**
* estimate number of rows based on the number of items and columns
*/
const rows = Math.ceil(group.items.length / cols);
// calculate total height based on rows, with some padding and a safety margin
return Math.ceil((28 + 24 + rows * tile) * 1.05); // small safety margin
},
overscan: VIRTUAL_OVER_SCAN,
});
const vItems = virtualizer.getVirtualItems();
@@ -520,12 +564,14 @@ export function EmojiBoard({
<EmojiSidebar
activeGroupAtom={activeGroupIdAtom}
packs={imagePacks}
saveStickerEmojiBandwidth={saveStickerEmojiBandwidth}
onScrollToGroup={handleScrollToGroup}
/>
) : (
<StickerSidebar
activeGroupAtom={activeGroupIdAtom}
packs={imagePacks}
saveStickerEmojiBandwidth={saveStickerEmojiBandwidth}
onScrollToGroup={handleScrollToGroup}
/>
)
@@ -543,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
@@ -6,6 +6,31 @@ import { mxcUrlToHttp } from '$utils/matrix';
import { EmojiItemInfo, EmojiType } from '$components/emoji-board/types';
import * as css from './styles.css';
const ANIMATED_MIME_TYPES = new Set(['image/gif', 'image/apng']);
const isAnimatedPackImage = (image: PackImageReader): boolean => {
const mimetype = image.info?.mimetype?.toLowerCase();
if (mimetype && ANIMATED_MIME_TYPES.has(mimetype)) return true;
const body = image.body?.toLowerCase();
return !!body && (body.endsWith('.gif') || body.endsWith('.webp') || body.endsWith('.apng'));
};
const getPackImageSrc = (
mx: MatrixClient,
image: PackImageReader,
useAuthentication: boolean | undefined,
saveStickerEmojiBandwidth: boolean,
width: number,
height: number
): string => {
const preserveAnimation = isAnimatedPackImage(image);
return preserveAnimation || !saveStickerEmojiBandwidth
? (mxcUrlToHttp(mx, image.url, useAuthentication) ?? '')
: (mxcUrlToHttp(mx, image.url, useAuthentication, width, height) ?? '');
};
export const getEmojiItemInfo = (element: Element): EmojiItemInfo | undefined => {
const label = element.getAttribute('title');
const type = element.getAttribute('data-emoji-type') as EmojiType | undefined;
@@ -48,8 +73,14 @@ type CustomEmojiItemProps = {
mx: MatrixClient;
useAuthentication?: boolean;
image: PackImageReader;
saveStickerEmojiBandwidth: boolean;
};
export function CustomEmojiItem({ mx, useAuthentication, image }: CustomEmojiItemProps) {
export function CustomEmojiItem({
mx,
useAuthentication,
image,
saveStickerEmojiBandwidth,
}: CustomEmojiItemProps) {
return (
<Box
as="button"
@@ -67,7 +98,7 @@ export function CustomEmojiItem({ mx, useAuthentication, image }: CustomEmojiIte
loading="lazy"
className={css.CustomEmojiImg}
alt={image.body || image.shortcode}
src={mxcUrlToHttp(mx, image.url, useAuthentication) ?? ''}
src={getPackImageSrc(mx, image, useAuthentication, saveStickerEmojiBandwidth, 32, 32)}
/>
</Box>
);
@@ -77,9 +108,15 @@ type StickerItemProps = {
mx: MatrixClient;
useAuthentication?: boolean;
image: PackImageReader;
saveStickerEmojiBandwidth: boolean;
};
export function StickerItem({ mx, useAuthentication, image }: StickerItemProps) {
export function StickerItem({
mx,
useAuthentication,
image,
saveStickerEmojiBandwidth,
}: StickerItemProps) {
return (
<Box
as="button"
@@ -97,7 +134,7 @@ export function StickerItem({ mx, useAuthentication, image }: StickerItemProps)
loading="lazy"
className={css.StickerImg}
alt={image.body || image.shortcode}
src={mxcUrlToHttp(mx, image.url, useAuthentication) ?? ''}
src={getPackImageSrc(mx, image, useAuthentication, saveStickerEmojiBandwidth, 125, 125)}
/>
</Box>
);
@@ -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
@@ -20,6 +20,9 @@ import { MatrixError } from '$types/matrix-sdk';
import { useMatrixClient } from '$hooks/useMatrixClient';
import { AsyncStatus, useAsyncCallback } from '$hooks/useAsyncCallback';
import { stopPropagation } from '$utils/keyboard';
import { createDebugLogger } from '$utils/debugLogger';
const debugLog = createDebugLogger('LeaveRoomPrompt');
type LeaveRoomPromptProps = {
roomId: string;
@@ -31,6 +34,7 @@ export function LeaveRoomPrompt({ roomId, onDone, onCancel }: LeaveRoomPromptPro
const [leaveState, leaveRoom] = useAsyncCallback<undefined, MatrixError, []>(
useCallback(async () => {
debugLog.info('ui', 'Leave room button clicked', { roomId });
mx.leave(roomId);
}, [mx, roomId])
);
@@ -41,9 +45,10 @@ export function LeaveRoomPrompt({ roomId, onDone, onCancel }: LeaveRoomPromptPro
useEffect(() => {
if (leaveState.status === AsyncStatus.Success) {
debugLog.info('ui', 'Successfully left room', { roomId });
onDone();
}
}, [leaveState, onDone]);
}, [leaveState, onDone, roomId]);
return (
<Overlay open backdrop={<OverlayBackdrop />}>
+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>(
@@ -87,6 +91,14 @@ type ForwardMeta = {
original_event_private: boolean;
};
// see https://github.com/hummlbach/matrix-doc/blob/acea0854a1c9489599295a858b068ce02a6b2b20/proposals/2723-add-forward-info.md
type MSC2723ForwardMeta = {
event_id: string;
room_id: string;
sender: string | null; // we won't set this field
origin_server_ts: number;
};
export function MessageForwardInternal({
room,
mEvent,
@@ -211,13 +223,15 @@ export function MessageForwardInternal({
formatted_body: newBodyHtml,
}
: {};
const baseContent = { ...mEvent.getContent() };
delete baseContent['com.beeper.per_message_profile']; // remove per-message profile as that could confuse clients in the target room
let content;
// handle privacy stuff
if (isPrivate) {
// if the message is from a private room, we should strip any media or mentions to avoid leaking information to the target room
// we can still include the original message content in the body of the message, so we'll just use a fallback text/plain content with the original message body
content = {
...mEvent.getContent(),
...baseContent,
'm.relates_to': null, // remove any relations to avoid confusion in the target room
'm.mentions': null, // remove mentions to avoid leaking information about users in the original room
...forwardedTextContent,
@@ -230,7 +244,7 @@ export function MessageForwardInternal({
};
} else {
content = {
...mEvent.getContent(),
...baseContent,
...forwardedTextContent,
'm.relates_to': {
rel_type: 'm.reference',
@@ -244,12 +258,39 @@ export function MessageForwardInternal({
original_event_id: eventId,
original_event_private: false,
} satisfies ForwardMeta,
'com.famedly.app.forwarded': {
event_id: eventId,
room_id: room.roomId,
sender: null, // we won't set this field, as a design decision to avoid potential privacy issues and since the sender can be inferred from the event_id and room_id if needed
origin_server_ts: mEvent.getTs(),
} satisfies MSC2723ForwardMeta,
};
}
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');
};
@@ -39,7 +39,7 @@ export const BannerContainer = style({
gap: config.space.S200,
padding: config.space.S400,
pointerEvents: 'none',
alignItems: 'stretch',
alignItems: 'flex-end',
// On iOS, when keyboard opens, ensure banner stays visible at top of visual viewport
'@supports': {
@@ -67,6 +67,7 @@ export const Banner = style({
boxShadow: `0 ${toRem(8)} ${toRem(32)} rgba(0, 0, 0, 0.45), 0 ${toRem(2)} ${toRem(8)} rgba(0, 0, 0, 0.3)`,
cursor: 'pointer',
width: '100%',
maxWidth: '50em',
animationName: slideIn,
animationDuration: '260ms',
animationTimingFunction: 'cubic-bezier(0.22, 0.8, 0.6, 1)',
+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,11 +3,7 @@ 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 } from '$utils/matrix';
import { mxcUrlToHttp, downloadMedia } from '$utils/matrix';
import { useMediaAuthentication } from '$hooks/useMediaAuthentication';
import * as css from './UrlPreviewCard.css';
import { UrlPreview, UrlPreviewContent, UrlPreviewDescription } from './UrlPreview';
@@ -17,6 +13,16 @@ import { ImageViewer } from '../image-viewer';
const linkStyles = { color: color.Success.Main };
const openMediaInNewTab = async (url: string | undefined) => {
if (!url) {
console.warn('Attempted to open an empty url');
return;
}
const blob = await downloadMedia(url);
const blobUrl = URL.createObjectURL(blob);
window.open(blobUrl, '_blank');
};
export const UrlPreviewCard = as<'div', { url: string; ts: number; mediaType?: string | null }>(
({ url, ts, mediaType, ...props }, ref) => {
const mx = useMatrixClient();
@@ -50,6 +56,21 @@ export const UrlPreviewCard = as<'div', { url: string; ts: number; mediaType?: s
'scale',
false
);
const handleAuxClick = (ev: React.MouseEvent) => {
if (!prev['og:image']) {
console.warn('No image');
return;
}
if (ev.button === 1) {
ev.preventDefault();
const mxcUrl = mxcUrlToHttp(mx, prev['og:image'], /* useAuthentication */ true);
if (!mxcUrl) {
console.error('Error converting mxc:// url.');
return;
}
openMediaInNewTab(mxcUrl);
}
};
return (
<Box
@@ -128,6 +149,7 @@ export const UrlPreviewCard = as<'div', { url: string; ts: number; mediaType?: s
<ImageContent
style={{ width: '100%', height: '100%', position: 'absolute', inset: 0 }}
autoPlay
onAuxClick={handleAuxClick}
body={prev['og:title']}
url={prev['og:image']}
renderViewer={(p) => <ImageViewer {...p} />}
@@ -187,7 +209,6 @@ export const UrlPreviewCard = as<'div', { url: string; ts: number; mediaType?: s
</Box>
);
}
return (
<UrlPreview
{...props}
@@ -217,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;
@@ -283,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
@@ -299,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
@@ -317,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>
+14 -7
View File
@@ -1,4 +1,4 @@
import { MouseEventHandler, useCallback, useRef, useState } from 'react';
import { MouseEventHandler, useCallback, useEffect, useRef, useState } from 'react';
import {
Box,
Button,
@@ -15,7 +15,13 @@ import {
toRem,
} from 'folds';
import FocusTrap from 'focus-trap-react';
import { SequenceCard } from '../../components/sequence-card';
import { SequenceCard } from '$components/sequence-card';
import { CallEmbed, useCallControlState } from '$plugins/call';
import { stopPropagation } from '$utils/keyboard';
import { AsyncStatus, useAsyncCallback } from '$hooks/useAsyncCallback';
import { useRoom } from '$hooks/useRoom';
import { ScreenSize, useScreenSizeContext } from '$hooks/useScreenSize';
import { useCallPreferences } from '$state/hooks/callPreferences';
import * as css from './styles.css';
import {
ChatButton,
@@ -25,11 +31,6 @@ import {
SoundButton,
VideoButton,
} from './Controls';
import { CallEmbed, useCallControlState } from '../../plugins/call';
import { stopPropagation } from '../../utils/keyboard';
import { AsyncStatus, useAsyncCallback } from '../../hooks/useAsyncCallback';
import { useRoom } from '../../hooks/useRoom';
import { ScreenSize, useScreenSizeContext } from '../../hooks/useScreenSize';
type CallControlsProps = {
callEmbed: CallEmbed;
@@ -45,6 +46,12 @@ export function CallControls({ callEmbed }: CallControlsProps) {
callEmbed.control
);
const { setPreferences } = useCallPreferences();
useEffect(() => {
setPreferences({ microphone, video, sound });
}, [microphone, video, sound, setPreferences]);
const [cords, setCords] = useState<RectCords>();
const handleOpenMenu: MouseEventHandler<HTMLButtonElement> = (evt) => {
@@ -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();
@@ -41,8 +41,11 @@ import {
import { RoomType } from '$types/matrix/room';
import { CreateRoomTypeSelector } from '$components/create-room/CreateRoomTypeSelector';
import { getRoomIconSrc } from '$utils/room';
import { createDebugLogger } from '$utils/debugLogger';
import { ErrorCode } from '../../cs-errorcode';
const debugLog = createDebugLogger('CreateRoom');
const getCreateRoomAccessToIcon = (access: CreateRoomAccess, type?: CreateRoomType) => {
const isVoiceRoom = type === CreateRoomType.VoiceRoom;
@@ -139,6 +142,16 @@ export function CreateRoomForm({
let roomType: RoomType | undefined;
if (type === CreateRoomType.VoiceRoom) roomType = RoomType.Call;
debugLog.info('ui', 'Create room button clicked', {
roomName,
access,
type,
publicRoom,
encryption,
hasParent: !!space,
parentRoomId: space?.roomId,
});
create({
version: selectedRoomVersion,
type: roomType,
@@ -152,6 +165,12 @@ export function CreateRoomForm({
allowFederation: federation,
additionalCreators: allowAdditionalCreators ? additionalCreators : undefined,
}).then((roomId) => {
debugLog.info('ui', 'Room created successfully', {
roomId,
roomName,
access,
type,
});
if (alive()) {
onCreate?.(roomId);
}
+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
@@ -179,7 +179,7 @@ export function Lobby() {
return new Set(sideSpaces);
}, [sidebarItems]);
const [spacesItems, setSpacesItem] = useState<Map<string, IHierarchyRoom>>(() => new Map());
const [spacesItems, setSpacesItems] = useState<Map<string, IHierarchyRoom>>(() => new Map());
useElementSizeObserver(
useCallback(() => heroSectionRef.current, []),
@@ -302,8 +302,7 @@ export function Lobby() {
}
if (
itemRoom &&
itemRoom.getJoinRule() === JoinRule.Restricted &&
itemRoom?.getJoinRule() === JoinRule.Restricted &&
item.parentId !== containerParentId
) {
// change join rule allow parameter when dragging
@@ -394,7 +393,7 @@ export function Lobby() {
const handleSpacesFound = useCallback(
(sItems: IHierarchyRoom[]) => {
setSpaceRooms({ type: 'PUT', roomIds: sItems.map((i) => i.room_id) });
setSpacesItem((current) => {
setSpacesItems((current) => {
const newItems = produce(current, (draft) => {
sItems.forEach((item) => draft.set(item.room_id, item));
});
@@ -49,7 +49,7 @@ export function MessageSearch({
rooms,
senders,
scrollRef,
}: MessageSearchProps) {
}: Readonly<MessageSearchProps>) {
const mx = useMatrixClient();
const mDirects = useAtomValue(mDirectAtom);
const allRooms = useRooms(mx, allRoomsAtom, mDirects);
@@ -175,7 +175,7 @@ export function MessageSearch({
});
};
const lastVItem = vItems[vItems.length - 1];
const lastVItem = vItems.at(-1);
const lastVItemIndex: number | undefined = lastVItem?.index;
const lastGroupIndex = groups.length - 1;
useEffect(() => {
@@ -253,7 +253,7 @@ export function MessageSearch({
{((msgSearchParams.term && status === 'pending') ||
(groups.length > 0 && vItems.length === 0)) && (
<Box direction="Column" gap="100">
{[...Array(8).keys()].map((key) => (
{[...new Array(8).keys()].map((key) => (
<SequenceCard variant="SurfaceVariant" key={key} style={{ minHeight: toRem(80) }} />
))}
</Box>
@@ -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,
},
]);
@@ -0,0 +1,168 @@
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: (payload: AudioRecordingCompletePayload) => void;
onRequestClose: () => void;
onWaveformUpdate: (waveform: number[]) => void;
onAudioLengthUpdate: (length: number) => void;
};
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>
</>
);
});
+5 -1
View File
@@ -155,7 +155,11 @@ function MemberItem({
}}
>
<AvatarPresence
badge={presence && <PresenceBadge presence={presence.presence} size="200" />}
badge={
presence && presence.lastActiveTs !== 0 ? (
<PresenceBadge presence={presence.presence} size="200" />
) : undefined
}
>
<Avatar size="300" radii="400">
<UserAvatar
+105 -3
View File
@@ -1,8 +1,8 @@
import { useCallback } from 'react';
import { useCallback, useEffect } from 'react';
import { Box, Line } from 'folds';
import { useParams } from 'react-router-dom';
import { isKeyHotkey } from 'is-hotkey';
import { useAtomValue } from 'jotai';
import { useAtom, useAtomValue } from 'jotai';
import { ScreenSize, useScreenSizeContext } from '$hooks/useScreenSize';
import { useSetting } from '$state/hooks/settings';
import { settingsAtom } from '$state/settings';
@@ -15,23 +15,74 @@ import { useRoomMembers } from '$hooks/useRoomMembers';
import { CallView } from '$features/call/CallView';
import { WidgetsDrawer } from '$features/widgets/WidgetsDrawer';
import { callChatAtom } from '$state/callEmbed';
import { roomIdToOpenThreadAtomFamily } from '$state/room/roomToOpenThread';
import { roomIdToThreadBrowserAtomFamily } from '$state/room/roomToThreadBrowser';
import { createDebugLogger } from '$utils/debugLogger';
import { RoomViewHeader } from './RoomViewHeader';
import { MembersDrawer } from './MembersDrawer';
import { RoomView } from './RoomView';
import { CallChatView } from './CallChatView';
import { ThreadDrawer } from './ThreadDrawer';
import { ThreadBrowser } from './ThreadBrowser';
const debugLog = createDebugLogger('Room');
export function Room() {
const { eventId } = useParams();
const room = useRoom();
const mx = useMatrixClient();
// Log room mount
useEffect(() => {
debugLog.info('ui', 'Room component mounted', { roomId: room.roomId, eventId });
return () => {
debugLog.info('ui', 'Room component unmounted', { roomId: room.roomId });
};
}, [room.roomId, eventId]);
const [isDrawer] = useSetting(settingsAtom, 'isPeopleDrawer');
const [isWidgetDrawerOpen] = useSetting(settingsAtom, 'isWidgetDrawer');
const [hideReads] = useSetting(settingsAtom, 'hideReads');
const screenSize = useScreenSizeContext();
// Log drawer state changes
useEffect(() => {
debugLog.debug('ui', 'Members drawer state changed', { roomId: room.roomId, isOpen: isDrawer });
}, [isDrawer, room.roomId]);
useEffect(() => {
debugLog.debug('ui', 'Widgets drawer state changed', {
roomId: room.roomId,
isOpen: isWidgetDrawerOpen,
});
}, [isWidgetDrawerOpen, room.roomId]);
const powerLevels = usePowerLevels(room);
const members = useRoomMembers(mx, room.roomId);
const chat = useAtomValue(callChatAtom);
const [openThreadId, setOpenThread] = useAtom(roomIdToOpenThreadAtomFamily(room.roomId));
const [threadBrowserOpen, setThreadBrowserOpen] = useAtom(
roomIdToThreadBrowserAtomFamily(room.roomId)
);
// If navigating to an event in a thread, open the thread drawer
useEffect(() => {
if (!eventId) return;
const event = room.findEventById(eventId);
if (!event) return;
const { threadRootId } = event;
if (threadRootId) {
// Ensure Thread object exists
if (!room.getThread(threadRootId)) {
const rootEvent = room.findEventById(threadRootId);
if (rootEvent) {
room.createThread(threadRootId, rootEvent, [], false);
}
}
setOpenThread(threadRootId);
}
}, [eventId, room, setOpenThread]);
useKeyDown(
window,
@@ -47,9 +98,14 @@ export function Room() {
const callView = room.isCallRoom();
// Log call view state
useEffect(() => {
debugLog.debug('ui', 'Room view mode', { roomId: room.roomId, callView, chatOpen: chat });
}, [callView, chat, room.roomId]);
return (
<PowerLevelsContextProvider value={powerLevels}>
<Box grow="Yes">
<Box grow="Yes" style={{ position: 'relative' }}>
{callView && (screenSize === ScreenSize.Desktop || !chat) && (
<Box grow="Yes" direction="Column">
<RoomViewHeader callView />
@@ -87,6 +143,52 @@ export function Room() {
<WidgetsDrawer key={`widgets-${room.roomId}`} room={room} />
</>
)}
{screenSize === ScreenSize.Desktop && openThreadId && (
<>
<Line variant="Background" direction="Vertical" size="300" />
<ThreadDrawer
key={`thread-${room.roomId}-${openThreadId}`}
room={room}
threadRootId={openThreadId}
onClose={() => setOpenThread(undefined)}
/>
</>
)}
{screenSize === ScreenSize.Desktop && threadBrowserOpen && !openThreadId && (
<>
<Line variant="Background" direction="Vertical" size="300" />
<ThreadBrowser
key={`thread-browser-${room.roomId}`}
room={room}
onOpenThread={(id) => {
setOpenThread(id);
setThreadBrowserOpen(false);
}}
onClose={() => setThreadBrowserOpen(false)}
/>
</>
)}
{screenSize !== ScreenSize.Desktop && openThreadId && (
<ThreadDrawer
key={`thread-${room.roomId}-${openThreadId}`}
room={room}
threadRootId={openThreadId}
onClose={() => setOpenThread(undefined)}
overlay
/>
)}
{screenSize !== ScreenSize.Desktop && threadBrowserOpen && !openThreadId && (
<ThreadBrowser
key={`thread-browser-${room.roomId}`}
room={room}
onOpenThread={(id) => {
setOpenThread(id);
setThreadBrowserOpen(false);
}}
onClose={() => setThreadBrowserOpen(false)}
overlay
/>
)}
</Box>
</PowerLevelsContextProvider>
);
+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
Loaded 100 of 209 files, more files were not shown because too many files have changed in this diff. Show more