Merge remote-tracking branch 'origin/dev' into fix/sliding-sync-room-state-and-unread
# Conflicts: # src/client/initMatrix.test.ts
No files matched your search
@@ -0,0 +1,5 @@
|
||||
---
|
||||
sable: minor
|
||||
---
|
||||
|
||||
Add a `/gif` composer command that opens the GIF picker.
|
||||
@@ -0,0 +1,5 @@
|
||||
---
|
||||
default: patch
|
||||
---
|
||||
|
||||
Publish an `obtainium.json` app config with every release so Android builds can be installed and auto-updated through Obtainium.
|
||||
@@ -0,0 +1,5 @@
|
||||
---
|
||||
default: minor
|
||||
---
|
||||
|
||||
# Add accessibility tab and accessible color correction
|
||||
@@ -0,0 +1,5 @@
|
||||
---
|
||||
default: minor
|
||||
---
|
||||
|
||||
# Add the option to remove the fallback from PMPs
|
||||
@@ -0,0 +1,5 @@
|
||||
---
|
||||
default: patch
|
||||
---
|
||||
|
||||
# Escape blockquote data-md=">" because that's good practice
|
||||
@@ -0,0 +1,5 @@
|
||||
---
|
||||
default: patch
|
||||
---
|
||||
|
||||
Refill the room member list from the server when sliding sync only delivered lazy-loaded members, so mention autocomplete and the members panel are complete.
|
||||
@@ -0,0 +1,5 @@
|
||||
---
|
||||
default: patch
|
||||
---
|
||||
|
||||
# Fix for the call room name positioning
|
||||
@@ -0,0 +1,5 @@
|
||||
---
|
||||
default: minor
|
||||
---
|
||||
|
||||
# Impl MSC4461: Storing per-message profiles for users
|
||||
@@ -7,11 +7,12 @@
|
||||
import { readFileSync, writeFileSync } from 'node:fs';
|
||||
import process from 'node:process';
|
||||
|
||||
const version = process.argv[2];
|
||||
const updaterEndpoint = process.argv[3];
|
||||
const args = process.argv.slice(2);
|
||||
const foldNightlyIntoPatch = args.includes('--apple-short-version');
|
||||
const [version, updaterEndpoint] = args.filter((arg) => !arg.startsWith('--'));
|
||||
if (!version || !/^\d+\.\d+\.\d+/.test(version)) {
|
||||
console.error(
|
||||
`Usage: set-tauri-version.mjs <version> [updater-endpoint] (got: ${version ?? '<none>'})`
|
||||
`Usage: set-tauri-version.mjs <version> [updater-endpoint] [--apple-short-version] (got: ${version ?? '<none>'})`
|
||||
);
|
||||
process.exit(1);
|
||||
}
|
||||
@@ -33,10 +34,30 @@ const sanitizedVersion = version.replace(/^(\d+\.\d+\.\d+-nightly)\.(.+)$/, (_,
|
||||
return `${prefix}.${sanitizedBuild}`;
|
||||
});
|
||||
|
||||
config.version = sanitizedVersion;
|
||||
// The nightly stamp goes into patch as a Unix timestamp, since the YYMMDDHHMMSS form
|
||||
// overflows the u32 Tauri parses each version part into.
|
||||
let stampedVersion = sanitizedVersion;
|
||||
if (foldNightlyIntoPatch) {
|
||||
const nightly = /^(\d+\.\d+)\.\d+-nightly\.(\d{2})(\d{2})(\d{2})(\d{2})(\d{2})(\d{2})$/.exec(
|
||||
sanitizedVersion
|
||||
);
|
||||
if (!nightly) {
|
||||
console.error(`--apple-short-version needs a nightly version (got: ${sanitizedVersion})`);
|
||||
process.exit(1);
|
||||
}
|
||||
const [, base, yy, mm, dd, hh, min, sec] = nightly;
|
||||
const patch = Date.UTC(2000 + +yy, mm - 1, +dd, +hh, +min, +sec) / 1000;
|
||||
if (!Number.isInteger(patch) || patch <= 0 || patch > 0xffffffff) {
|
||||
console.error(`Nightly stamp does not map to a u32 patch version: ${sanitizedVersion}`);
|
||||
process.exit(1);
|
||||
}
|
||||
stampedVersion = `${base}.${patch}`;
|
||||
}
|
||||
|
||||
config.version = stampedVersion;
|
||||
if (updaterEndpoint) {
|
||||
config.plugins.updater.endpoints = [updaterEndpoint];
|
||||
}
|
||||
writeFileSync(file, `${JSON.stringify(config, null, 2)}\n`);
|
||||
console.log(`Set ${file} version to ${version}`);
|
||||
console.log(`Set ${file} version to ${stampedVersion}`);
|
||||
if (updaterEndpoint) console.log(`Set ${file} updater endpoint to ${updaterEndpoint}`);
|
||||
@@ -5,7 +5,7 @@
|
||||
// IPA asset, then prints the updated file. Used by .github/workflows/tauri-build.yml.
|
||||
//
|
||||
// Usage: update-altstore-source.mjs <source.json> <version> <build> <ipa-size> <downloadURL> <date> [description]
|
||||
// Env: none
|
||||
// Env: ALTSTORE_MAX_VERSIONS - how many version entries to keep (default 20)
|
||||
|
||||
import { readFileSync, writeFileSync } from 'node:fs';
|
||||
import process from 'node:process';
|
||||
@@ -60,8 +60,15 @@ const idx = versions.findIndex((v) => v.version === normalizedVersion);
|
||||
if (idx >= 0) versions[idx] = entry;
|
||||
else versions.unshift(entry);
|
||||
|
||||
// Keep only the most recent 20 versions in the manifest.
|
||||
app.versions = versions.slice(0, 20);
|
||||
// Keep only the most recent versions in the manifest.
|
||||
const maxVersions = Number(process.env.ALTSTORE_MAX_VERSIONS ?? 20);
|
||||
if (!Number.isInteger(maxVersions) || maxVersions <= 0) {
|
||||
console.error(
|
||||
`ALTSTORE_MAX_VERSIONS must be a positive integer (got: ${process.env.ALTSTORE_MAX_VERSIONS})`
|
||||
);
|
||||
process.exit(1);
|
||||
}
|
||||
app.versions = versions.slice(0, maxVersions);
|
||||
|
||||
writeFileSync(sourcePath, `${JSON.stringify(source, null, 2)}\n`);
|
||||
console.log(
|
||||
|
||||
@@ -69,7 +69,7 @@ jobs:
|
||||
|
||||
# Initializes the CodeQL tools for scanning.
|
||||
- name: Initialize CodeQL
|
||||
uses: github/codeql-action/init@e4fba868fa4b1b91e1fdab776edc8cfbe6e9fb81 # v4.37.3
|
||||
uses: github/codeql-action/init@f205ea1c3313d32999d8d6a48b4f6530d4437b38 # v4.37.4
|
||||
with:
|
||||
languages: ${{ matrix.language }}
|
||||
build-mode: ${{ matrix.build-mode }}
|
||||
@@ -98,6 +98,6 @@ jobs:
|
||||
exit 1
|
||||
|
||||
- name: Perform CodeQL Analysis
|
||||
uses: github/codeql-action/analyze@e4fba868fa4b1b91e1fdab776edc8cfbe6e9fb81 # v4.37.3
|
||||
uses: github/codeql-action/analyze@f205ea1c3313d32999d8d6a48b4f6530d4437b38 # v4.37.4
|
||||
with:
|
||||
category: '/language:${{matrix.language}}'
|
||||
@@ -38,7 +38,7 @@ jobs:
|
||||
|
||||
- name: Log in to GitHub Container Registry
|
||||
if: github.event_name != 'pull_request'
|
||||
uses: docker/login-action@abd2ef45e78c5afb21d64d4ca52ee8550d9572c7 # v4.5.1
|
||||
uses: docker/login-action@dbcb813823bdd20940b903addbd779551569679f # v4.6.0
|
||||
with:
|
||||
registry: ${{ env.REGISTRY }}
|
||||
username: ${{ github.actor }}
|
||||
|
||||
@@ -30,7 +30,7 @@ jobs:
|
||||
token: ${{ steps.app-token.outputs.token }}
|
||||
|
||||
- name: Install Determinate Nix
|
||||
uses: DeterminateSystems/determinate-nix-action@d96678350ffd6a456235832eb11e1c491589b7bb # v3.21.8
|
||||
uses: DeterminateSystems/determinate-nix-action@61cbfe2efc2d4e7a8a6d56967c3c1058e846c858 # v3.21.9
|
||||
|
||||
- id: check
|
||||
run: nix flake check -L
|
||||
|
||||
@@ -408,6 +408,33 @@ jobs:
|
||||
gh release upload "$TAG" "$f" --clobber
|
||||
done
|
||||
|
||||
obtainium:
|
||||
name: Publish Obtainium config
|
||||
needs: [setup-release, android]
|
||||
runs-on: ubuntu-latest
|
||||
timeout-minutes: 5
|
||||
permissions:
|
||||
contents: write
|
||||
env:
|
||||
TAG: ${{ needs.setup-release.outputs.tag }}
|
||||
VERSION: ${{ needs.setup-release.outputs.version }}
|
||||
steps:
|
||||
- name: Checkout repository
|
||||
uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1
|
||||
with:
|
||||
ref: ${{ needs.setup-release.outputs.ref }}
|
||||
persist-credentials: false
|
||||
|
||||
- name: Generate obtainium.json
|
||||
shell: bash
|
||||
run: node scripts/obtainium-generate.js "$VERSION" "$TAG" obtainium.json
|
||||
|
||||
- name: Attach Obtainium config to release
|
||||
shell: bash
|
||||
env:
|
||||
GH_TOKEN: ${{ github.token }}
|
||||
run: gh release upload "$TAG" obtainium.json --clobber
|
||||
|
||||
ios:
|
||||
name: Build iOS (AltStore/SideStore)
|
||||
needs: setup-release
|
||||
@@ -455,7 +482,14 @@ jobs:
|
||||
|
||||
- name: Stamp release version into tauri.conf.json
|
||||
shell: bash
|
||||
run: node .github/scripts/set-tauri-version.mjs "$VERSION"
|
||||
env:
|
||||
IS_NIGHTLY: ${{ needs.setup-release.outputs.nightly }}
|
||||
run: |
|
||||
if [ "$IS_NIGHTLY" = "true" ]; then
|
||||
node .github/scripts/set-tauri-version.mjs "$VERSION" --apple-short-version
|
||||
else
|
||||
node .github/scripts/set-tauri-version.mjs "$VERSION"
|
||||
fi
|
||||
|
||||
- name: Set up iOS
|
||||
shell: bash
|
||||
@@ -541,6 +575,8 @@ jobs:
|
||||
set -euo pipefail
|
||||
if [ "$NIGHTLY" = "true" ]; then
|
||||
SOURCE_FILE="altstore-source-nightly.json"
|
||||
# Superseded nightly IPAs get deleted, so older entries would be dead links.
|
||||
export ALTSTORE_MAX_VERSIONS=1
|
||||
else
|
||||
SOURCE_FILE="altstore-source.json"
|
||||
fi
|
||||
|
||||
@@ -1,128 +1,78 @@
|
||||
# Contributor Covenant Code of Conduct
|
||||
# Sable Community Code of Conduct
|
||||
|
||||
## Our Pledge
|
||||
## Welcome!
|
||||
|
||||
We as members, contributors, and leaders pledge to make participation in our
|
||||
community a harassment-free experience for everyone, regardless of age, body
|
||||
size, visible or invisible disability, ethnicity, sex characteristics, gender
|
||||
identity and expression, level of experience, education, socio-economic status,
|
||||
nationality, personal appearance, race, religion, or sexual identity
|
||||
and orientation.
|
||||
We're excited to have you here. Sable is a Matrix client meant for everyone.
|
||||
Because of that we're committed to keeping this community open and welcoming to all.
|
||||
|
||||
We pledge to act and interact in ways that contribute to an open, welcoming,
|
||||
diverse, inclusive, and healthy community.
|
||||
We ask all of our community—the people who build it, use it, break it, suggest things for it, help each other with it, and
|
||||
occasionally meow—to abide by some general rules when in official Sable spaces.
|
||||
|
||||
## Our Standards
|
||||
## The rules
|
||||
|
||||
Examples of behavior that contributes to a positive environment for our
|
||||
community include:
|
||||
Conversation here is casual. You can disagree, joke around, swear, be weird,
|
||||
and criticize Sable or its decisions. Just remember that other people share the room with you.
|
||||
|
||||
- Demonstrating empathy and kindness toward other people
|
||||
- Being respectful of differing opinions, viewpoints, and experiences
|
||||
- Giving and gracefully accepting constructive feedback
|
||||
- Accepting responsibility and apologizing to those affected by our mistakes,
|
||||
and learning from the experience
|
||||
- Focusing on what is best not just for us as individuals, but for the
|
||||
overall community
|
||||
The following are not allowed:
|
||||
|
||||
Examples of unacceptable behavior include:
|
||||
- **Do not harass people.** This includes targeted insults, dogpiling, repeatedly
|
||||
provoking someone, unwelcome sexual advances or attention, or continuing to contact someone after they ask you to
|
||||
stop.
|
||||
- **Do not use hate speech or attack someone based on their identity**, including but not
|
||||
limited to race, ethnicity, nationality, religion, disability, age, body size or
|
||||
appearance, sex, sex characteristics, sexuality, gender identity, gender
|
||||
expression, and socioeconomic status.
|
||||
- **Do not make threats, encourage violence or self-harm, or doxx anyone.** Doxxing includes
|
||||
sharing or threatening to share someone's private information.
|
||||
- **Do not post explicit sexual content.** This includes graphic NSFW media, pornography,
|
||||
and explicit sexual comments or jokes.
|
||||
- **Do not abuse the shared spaces.** This includes impersonation, scams, malicious links or
|
||||
files, spam, flooding, ban evasion, or retaliation against someone for making
|
||||
a report or setting a boundary.
|
||||
|
||||
- The use of sexualized language or imagery, and sexual attention or
|
||||
advances of any kind
|
||||
- Trolling, insulting or derogatory comments, and personal or political attacks
|
||||
- Public or private harassment
|
||||
- Publishing others' private information, such as a physical or email
|
||||
address, without their explicit permission
|
||||
- Other conduct which could reasonably be considered inappropriate in a
|
||||
professional setting
|
||||
Context and patterns matter. Being blunt, disagreeing about politics or project
|
||||
direction, or criticizing a maintainer is not automatically a violation. These
|
||||
rules cannot cover every situation, so moderators have final say on how they
|
||||
apply.
|
||||
|
||||
## Enforcement Responsibilities
|
||||
## Where this applies
|
||||
|
||||
Community leaders are responsible for clarifying and enforcing our standards of
|
||||
acceptable behavior and will take appropriate and fair corrective action in
|
||||
response to any behavior that they deem inappropriate, threatening, offensive,
|
||||
or harmful.
|
||||
These rules apply to Sable's official GitHub repositories and Matrix space and
|
||||
rooms.
|
||||
|
||||
Community leaders have the right and responsibility to remove, edit, or reject
|
||||
comments, commits, code, wiki edits, issues, and other contributions that are
|
||||
not aligned to this Code of Conduct, and will communicate reasons for moderation
|
||||
decisions when appropriate.
|
||||
We do not police people's unrelated private lives. We may act on credible
|
||||
threats, doxxing, or targeted harassment outside these spaces when it is
|
||||
connected to Sable.
|
||||
|
||||
## Scope
|
||||
## Moderation
|
||||
|
||||
This Code of Conduct applies within all community spaces, and also applies when
|
||||
an individual is officially representing the community in public spaces.
|
||||
Examples of representing our community include using an official e-mail address,
|
||||
posting via an official social media account, or acting as an appointed
|
||||
representative at an online or offline event.
|
||||
If a moderator asks you to stop, stop.
|
||||
|
||||
## Enforcement
|
||||
When this code of conduct is not followed,
|
||||
moderators may remove content, issue a warning, kick, or ban someone from Sable's Matrix
|
||||
rooms or block them from its GitHub repositories.
|
||||
|
||||
Instances of abusive, harassing, or otherwise unacceptable behavior may be
|
||||
reported to the community leaders responsible for enforcement at
|
||||
executioner@sable.moe.
|
||||
All complaints will be reviewed and investigated promptly and fairly.
|
||||
When practical, moderators will explain the problem and what needs to happen next.
|
||||
Moderators will step back from handling reports that involve them directly, provided another moderator is available. You may request a review by emailing the address listed in the Reporting section below if you believe a decision was mistaken.
|
||||
|
||||
All community leaders are obligated to respect the privacy and security of the
|
||||
reporter of any incident.
|
||||
## Reporting
|
||||
|
||||
## Enforcement Guidelines
|
||||
Message a moderator (anyone with an Admin or Moderator power level) in the relevant Matrix room or email
|
||||
[[email protected]](mailto:[email protected]). Reports
|
||||
will be handled thoughtfully and as privately as we reasonably can.
|
||||
|
||||
Community leaders will follow these Community Impact Guidelines in determining
|
||||
the consequences for any action they deem in violation of this Code of Conduct:
|
||||
If your report is about a moderator, email
|
||||
[[email protected]](mailto:[email protected]) or contact 7w1 directly at
|
||||
[`@seven:sable.moe`](https://matrix.to/#/@seven:sable.moe).
|
||||
|
||||
### 1. Correction
|
||||
Send whatever context you have. You do not need to build a case first.
|
||||
We will limit access to people who need it to handle the report. We will not
|
||||
identify you to the reported person without your permission, though details of
|
||||
the report may need to be discussed to investigate or act on it.
|
||||
Knowingly false reports or using reports to harass someone are not allowed.
|
||||
|
||||
**Community Impact**: Use of inappropriate language or other behavior deemed
|
||||
unprofessional or unwelcome in the community.
|
||||
## Other stuff
|
||||
|
||||
**Consequence**: A private, written warning from community leaders, providing
|
||||
clarity around the nature of the violation and an explanation of why the
|
||||
behavior was inappropriate. A public apology may be requested.
|
||||
|
||||
### 2. Warning
|
||||
|
||||
**Community Impact**: A violation through a single incident or series
|
||||
of actions.
|
||||
|
||||
**Consequence**: A warning with consequences for continued behavior. No
|
||||
interaction with the people involved, including unsolicited interaction with
|
||||
those enforcing the Code of Conduct, for a specified period of time. This
|
||||
includes avoiding interactions in community spaces as well as external channels
|
||||
like social media. Violating these terms may lead to a temporary or
|
||||
permanent ban.
|
||||
|
||||
### 3. Temporary Ban
|
||||
|
||||
**Community Impact**: A serious violation of community standards, including
|
||||
sustained inappropriate behavior.
|
||||
|
||||
**Consequence**: A temporary ban from any sort of interaction or public
|
||||
communication with the community for a specified period of time. No public or
|
||||
private interaction with the people involved, including unsolicited interaction
|
||||
with those enforcing the Code of Conduct, is allowed during this period.
|
||||
Violating these terms may lead to a permanent ban.
|
||||
|
||||
### 4. Permanent Ban
|
||||
|
||||
**Community Impact**: Demonstrating a pattern of violation of community
|
||||
standards, including sustained inappropriate behavior, harassment of an
|
||||
individual, or aggression toward or disparagement of classes of individuals.
|
||||
|
||||
**Consequence**: A permanent ban from any sort of public interaction within
|
||||
the community.
|
||||
|
||||
## Attribution
|
||||
|
||||
This Code of Conduct is adapted from the [Contributor Covenant][homepage],
|
||||
version 2.0, available at
|
||||
https://www.contributor-covenant.org/version/2/0/code_of_conduct.html.
|
||||
|
||||
Community Impact Guidelines were inspired by [Mozilla's code of conduct
|
||||
enforcement ladder](https://github.com/mozilla/diversity).
|
||||
|
||||
[homepage]: https://www.contributor-covenant.org
|
||||
|
||||
For answers to common questions about this code of conduct, see the FAQ at
|
||||
https://www.contributor-covenant.org/faq. Translations are available at
|
||||
https://www.contributor-covenant.org/translations.
|
||||
These rules may change as Sable and its community change.
|
||||
By continuing to participate in official Sable spaces, you agree to continue abiding by these rules.
|
||||
If something is unclear, missing, or badly written, please tell us and we will update this document.
|
||||
@@ -13,6 +13,42 @@ The stable web app is available at [app.sable.moe](https://app.sable.moe/) and t
|
||||
|
||||
You can also download our desktop app for Windows and Linux from [releases](https://github.com/SableClient/Sable/releases/latest). Release artifacts include build attestations, and desktop installations update automatically.
|
||||
|
||||
## Android (Obtainium)
|
||||
|
||||
Android APKs are published to every release, and [Obtainium](https://obtainium.imranr.dev) keeps them updated straight from GitHub. Each release also ships an `obtainium.json` app config. Use it for the nightly channel, where prereleases and date-based version tracking have to be enabled to follow the rolling `nightly` tag.
|
||||
|
||||
### Stable
|
||||
|
||||
<a href="https://apps.obtainium.imranr.dev/redirect?r=obtainium://add/https://github.com/SableClient/Sable"><img alt="Add to Obtainium" src="https://img.shields.io/badge/Add_to_Obtainium-6750A3?style=for-the-badge"></a>
|
||||
|
||||
<a href="https://github.com/SableClient/Sable/releases/latest/download/obtainium.json"><img alt="App config" src="https://img.shields.io/badge/App_config-6B7280?style=for-the-badge"></a>
|
||||
|
||||
<a href="https://github.com/SableClient/Sable/releases/latest"><img alt="Download APK" src="https://img.shields.io/badge/Download_APK-3DDC84?style=for-the-badge&logo=android"></a>
|
||||
|
||||
### Nightly
|
||||
|
||||
<a href="https://apps.obtainium.imranr.dev/redirect?r=obtainium://app/%7B%22id%22%3A%22moe.sable.client%22%2C%22url%22%3A%22https%3A%2F%2Fgithub.com%2FSableClient%2FSable%22%2C%22author%22%3A%22SableClient%22%2C%22name%22%3A%22Sable%22%2C%22preferredApkIndex%22%3A0%2C%22additionalSettings%22%3A%22%7B%5C%22about%5C%22%3A%5C%22An%20almost%20stable%20Matrix%20client%5C%22%2C%5C%22includePrereleases%5C%22%3Atrue%2C%5C%22useLatestAssetDateAsReleaseDate%5C%22%3Atrue%2C%5C%22releaseDateAsVersion%5C%22%3Atrue%2C%5C%22versionDetection%5C%22%3Afalse%7D%22%2C%22overrideSource%22%3A%22GitHub%22%7D"><img alt="Add to Obtainium" src="https://img.shields.io/badge/Add_to_Obtainium-6750A3?style=for-the-badge"></a>
|
||||
|
||||
<a href="https://github.com/SableClient/Sable/releases/download/nightly/obtainium.json"><img alt="App config" src="https://img.shields.io/badge/App_config-6B7280?style=for-the-badge"></a>
|
||||
|
||||
<a href="https://github.com/SableClient/Sable/releases/tag/nightly"><img alt="Download APK" src="https://img.shields.io/badge/Download_APK-3DDC84?style=for-the-badge&logo=android"></a>
|
||||
|
||||
### Setup & install
|
||||
|
||||
1. Install [Obtainium](https://github.com/ImranR98/Obtainium/releases/latest).
|
||||
2. Tap **Add to Obtainium** above. Stable opens the **Add App** page prefilled with `https://github.com/SableClient/Sable`; nightly opens an import prompt, since it carries the prerelease and version-tracking settings the rolling `nightly` tag needs.
|
||||
3. Or download the `obtainium.json` for either channel and import it with **Import/Export → Import from file**.
|
||||
|
||||
Android builds are produced by the `android` job in [`tauri-build.yml`](.github/workflows/tauri-build.yml), and the config by the `obtainium` job in the same workflow.
|
||||
|
||||
### Relevant variables and switching between Nightly and Stable
|
||||
|
||||
Relevant variable differences between Nightly and Stable:
|
||||
- *Include prereleases* - `true` for Nightly, `false` for Stable
|
||||
- *Fallback to older releases* - `false` for Nightly, `true` for Stable
|
||||
- *Use latest asset upload as release date* - `true` for Nightly, `false` for Stable (this is due to Nightly builds being uploaded to one release instead of creating new ones)
|
||||
- *Use release date as version string (pseudo-version)* - `true` for Nightly, `false` for Stable (this is due to Nightly builds being uploaded to one release instead of creating new ones)
|
||||
|
||||
## iOS (AltStore / SideStore)
|
||||
|
||||
Sable iOS builds are distributed as unsigned IPAs through [AltStore](https://altstore.io) and [SideStore](https://sidestore.io). Each release publishes both the IPA and an `altstore-source.json` manifest — stable builds to the [latest GitHub release](https://github.com/SableClient/Sable/releases/latest), nightly builds to the [`nightly` GitHub release](https://github.com/SableClient/Sable/releases/tag/nightly).
|
||||
@@ -55,7 +91,8 @@ You have a few options for self hosting, you can:
|
||||
|
||||
Prebuilt images are published to `ghcr.io/sableclient/sable`.
|
||||
|
||||
- `latest` tracks the current `dev` branch image.
|
||||
- `latest` tracks the current latest version release.
|
||||
- `dev` tracks the current `dev` branch image.
|
||||
- `X.Y.Z` tags are versioned releases.
|
||||
- `X.Y` tags float within a release line.
|
||||
- Pushes to `dev` also publish a short commit SHA tag.
|
||||
|
||||
@@ -20,12 +20,12 @@
|
||||
"screenshots": [],
|
||||
"versions": [
|
||||
{
|
||||
"version": "1.20.1",
|
||||
"buildVersion": "1.20.1.260803112751",
|
||||
"date": "2026-08-03T11:40:25Z",
|
||||
"size": 18914950,
|
||||
"downloadURL": "https://github.com/SableClient/Sable/releases/download/nightly/Sable-1.20.1-nightly.260803112751-ios-arm64.ipa",
|
||||
"localizedDescription": "Sable 1.20.1-nightly.260803112751"
|
||||
"version": "1.20.1786133496",
|
||||
"buildVersion": "1.20.1786133496",
|
||||
"date": "2026-08-07T20:22:21Z",
|
||||
"size": 18940363,
|
||||
"downloadURL": "https://github.com/SableClient/Sable/releases/download/nightly/Sable-1.20.1-nightly.260807201136-ios-arm64.ipa",
|
||||
"localizedDescription": "Sable 1.20.1-nightly.260807201136"
|
||||
}
|
||||
],
|
||||
"appPermissions": {
|
||||
|
||||
@@ -13,8 +13,9 @@
|
||||
};
|
||||
};
|
||||
|
||||
outputs = inputs @ {flake-parts, ...}:
|
||||
flake-parts.lib.mkFlake {inherit inputs;} {
|
||||
outputs =
|
||||
inputs@{ flake-parts, ... }:
|
||||
flake-parts.lib.mkFlake { inherit inputs; } {
|
||||
imports = [
|
||||
inputs.git-hooks.flakeModule
|
||||
inputs.treefmt-nix.flakeModule
|
||||
@@ -27,24 +28,26 @@
|
||||
"aarch64-darwin"
|
||||
];
|
||||
|
||||
perSystem = {
|
||||
inputs',
|
||||
config,
|
||||
system,
|
||||
lib,
|
||||
...
|
||||
}: let
|
||||
pkgs = import inputs.nixpkgs {
|
||||
inherit system;
|
||||
perSystem =
|
||||
{
|
||||
inputs',
|
||||
config,
|
||||
system,
|
||||
lib,
|
||||
...
|
||||
}:
|
||||
let
|
||||
pkgs = import inputs.nixpkgs {
|
||||
inherit system;
|
||||
|
||||
config = {
|
||||
allowUnfree = true;
|
||||
android_sdk.accept_license = true;
|
||||
config = {
|
||||
allowUnfree = true;
|
||||
android_sdk.accept_license = true;
|
||||
};
|
||||
};
|
||||
};
|
||||
|
||||
rust = (
|
||||
with inputs'.fenix.packages;
|
||||
rust = (
|
||||
with inputs'.fenix.packages;
|
||||
combine [
|
||||
stable.toolchain
|
||||
targets.aarch64-linux-android.stable.rust-std
|
||||
@@ -52,140 +55,140 @@
|
||||
targets.armv7-linux-androideabi.stable.rust-std
|
||||
targets.i686-linux-android.stable.rust-std
|
||||
]
|
||||
);
|
||||
);
|
||||
|
||||
platformVersion = "36";
|
||||
systemImageType = "default";
|
||||
currentPath = builtins.getEnv "PWD";
|
||||
androidEnv = pkgs.androidenv.override {licenseAccepted = true;};
|
||||
androidComp = (
|
||||
androidEnv.composeAndroidPackages {
|
||||
cmdLineToolsVersion = "8.0";
|
||||
includeNDK = true;
|
||||
buildToolsVersions = ["35.0.0"];
|
||||
platformVersion = "36";
|
||||
systemImageType = "default";
|
||||
currentPath = builtins.getEnv "PWD";
|
||||
androidEnv = pkgs.androidenv.override { licenseAccepted = true; };
|
||||
androidComp = (
|
||||
androidEnv.composeAndroidPackages {
|
||||
cmdLineToolsVersion = "8.0";
|
||||
includeNDK = true;
|
||||
buildToolsVersions = [ "35.0.0" ];
|
||||
|
||||
platformVersions = [
|
||||
"30"
|
||||
platformVersion
|
||||
];
|
||||
includeEmulator = true;
|
||||
includeSystemImages = true;
|
||||
systemImageTypes = [
|
||||
systemImageType
|
||||
];
|
||||
abiVersions = [
|
||||
"x86"
|
||||
"x86_64"
|
||||
"armeabi-v7a"
|
||||
"arm64-v8a"
|
||||
];
|
||||
cmakeVersions = ["3.10.2"];
|
||||
}
|
||||
);
|
||||
android-sdk = pkgs.android-studio.withSdk androidComp.androidsdk;
|
||||
platformVersions = [
|
||||
"30"
|
||||
platformVersion
|
||||
];
|
||||
includeEmulator = true;
|
||||
includeSystemImages = true;
|
||||
systemImageTypes = [
|
||||
systemImageType
|
||||
];
|
||||
abiVersions = [
|
||||
"x86"
|
||||
"x86_64"
|
||||
"armeabi-v7a"
|
||||
"arm64-v8a"
|
||||
];
|
||||
cmakeVersions = [ "3.10.2" ];
|
||||
}
|
||||
);
|
||||
android-sdk = pkgs.android-studio.withSdk androidComp.androidsdk;
|
||||
|
||||
self = inputs.self;
|
||||
self = inputs.self;
|
||||
|
||||
packageJson = builtins.fromJSON (builtins.readFile ./package.json);
|
||||
packageJson = builtins.fromJSON (builtins.readFile ./package.json);
|
||||
|
||||
nodejs = pkgs.nodejs_24;
|
||||
pnpm = pkgs.pnpm_10;
|
||||
pnpmConfigHook = pkgs.pnpmConfigHook.override {inherit pnpm;};
|
||||
nodejs = pkgs.nodejs_24;
|
||||
pnpm = pkgs.pnpm_10;
|
||||
pnpmConfigHook = pkgs.pnpmConfigHook.override { inherit pnpm; };
|
||||
|
||||
pnpmNativeBuildInputs = [
|
||||
pkgs.pkg-config
|
||||
nodejs
|
||||
pnpm
|
||||
pnpmConfigHook
|
||||
];
|
||||
pnpmNativeBuildInputs = [
|
||||
pkgs.pkg-config
|
||||
nodejs
|
||||
pnpm
|
||||
pnpmConfigHook
|
||||
];
|
||||
|
||||
mkPnpmDeps = {
|
||||
src,
|
||||
version,
|
||||
pnpmInstallFlags,
|
||||
}:
|
||||
pkgs.fetchPnpmDeps {
|
||||
inherit
|
||||
pnpm
|
||||
src
|
||||
version
|
||||
pnpmInstallFlags
|
||||
;
|
||||
pname = "sable";
|
||||
fetcherVersion = 3;
|
||||
hash = "sha256-9lHy7/+hVET5c9Mt3F9DvrkW97DMxTISJsrklK/Ls2c=";
|
||||
};
|
||||
|
||||
mkPnpmCheck = name: script:
|
||||
pkgs.stdenv.mkDerivation (finalAttrs: {
|
||||
pname = "sable-${name}";
|
||||
inherit (packageJson) version;
|
||||
src = lib.cleanSource ./.;
|
||||
|
||||
pnpmInstallFlags = ["--ignore-scripts"];
|
||||
|
||||
pnpmDeps = mkPnpmDeps {
|
||||
inherit (finalAttrs) src version pnpmInstallFlags;
|
||||
mkPnpmDeps =
|
||||
{
|
||||
src,
|
||||
version,
|
||||
pnpmInstallFlags,
|
||||
}:
|
||||
pkgs.fetchPnpmDeps {
|
||||
inherit
|
||||
pnpm
|
||||
src
|
||||
version
|
||||
pnpmInstallFlags
|
||||
;
|
||||
pname = "sable";
|
||||
fetcherVersion = 3;
|
||||
hash = "sha256-1siT4fB6ty2azmWXe5L40EFUdk0th59qIdARUB0cVOc=";
|
||||
};
|
||||
|
||||
nativeBuildInputs = pnpmNativeBuildInputs;
|
||||
mkPnpmCheck =
|
||||
name: script:
|
||||
pkgs.stdenv.mkDerivation (finalAttrs: {
|
||||
pname = "sable-${name}";
|
||||
inherit (packageJson) version;
|
||||
src = lib.cleanSource ./.;
|
||||
|
||||
buildPhase = ''
|
||||
runHook preBuild
|
||||
pnpm run ${script}
|
||||
runHook postBuild
|
||||
'';
|
||||
pnpmInstallFlags = [ "--ignore-scripts" ];
|
||||
|
||||
installPhase = ''
|
||||
runHook preInstall
|
||||
touch $out
|
||||
runHook postInstall
|
||||
'';
|
||||
pnpmDeps = mkPnpmDeps {
|
||||
inherit (finalAttrs) src version pnpmInstallFlags;
|
||||
};
|
||||
|
||||
doCheck = false;
|
||||
});
|
||||
nativeBuildInputs = pnpmNativeBuildInputs;
|
||||
|
||||
nativeBuildInputs = with pkgs; [
|
||||
pkg-config
|
||||
gobject-introspection
|
||||
cargo
|
||||
cargo-tauri
|
||||
nodejs
|
||||
xdg-utils
|
||||
desktop-file-utils
|
||||
wrapGAppsHook3
|
||||
];
|
||||
buildPhase = ''
|
||||
runHook preBuild
|
||||
pnpm run ${script}
|
||||
runHook postBuild
|
||||
'';
|
||||
|
||||
buildInputs = with pkgs; [
|
||||
at-spi2-atk
|
||||
atkmm
|
||||
cairo
|
||||
gdk-pixbuf
|
||||
glib
|
||||
glib-networking
|
||||
gtk3
|
||||
gsettings-desktop-schemas
|
||||
harfbuzz
|
||||
librsvg
|
||||
libsoup_3
|
||||
pango
|
||||
webkitgtk_4_1
|
||||
openssl
|
||||
dbus
|
||||
dbus.dev
|
||||
libpulseaudio
|
||||
alsa-lib
|
||||
libayatana-appindicator
|
||||
gst_all_1.gstreamer
|
||||
gst_all_1.gst-plugins-base
|
||||
gst_all_1.gst-plugins-good
|
||||
gst_all_1.gst-plugins-bad
|
||||
gst_all_1.gst-plugins-ugly
|
||||
gst_all_1.gst-libav
|
||||
android-sdk
|
||||
];
|
||||
installPhase = ''
|
||||
runHook preInstall
|
||||
touch $out
|
||||
runHook postInstall
|
||||
'';
|
||||
|
||||
defaultPackages = [
|
||||
doCheck = false;
|
||||
});
|
||||
|
||||
nativeBuildInputs = with pkgs; [
|
||||
pkg-config
|
||||
gobject-introspection
|
||||
cargo
|
||||
cargo-tauri
|
||||
nodejs
|
||||
xdg-utils
|
||||
desktop-file-utils
|
||||
wrapGAppsHook3
|
||||
];
|
||||
|
||||
buildInputs = with pkgs; [
|
||||
at-spi2-atk
|
||||
atkmm
|
||||
cairo
|
||||
gdk-pixbuf
|
||||
glib
|
||||
glib-networking
|
||||
gtk3
|
||||
gsettings-desktop-schemas
|
||||
harfbuzz
|
||||
librsvg
|
||||
libsoup_3
|
||||
pango
|
||||
webkitgtk_4_1
|
||||
openssl
|
||||
dbus
|
||||
dbus.dev
|
||||
libayatana-appindicator
|
||||
gst_all_1.gstreamer
|
||||
gst_all_1.gst-plugins-base
|
||||
gst_all_1.gst-plugins-good
|
||||
gst_all_1.gst-plugins-bad
|
||||
gst_all_1.gst-plugins-ugly
|
||||
gst_all_1.gst-libav
|
||||
android-sdk
|
||||
];
|
||||
|
||||
defaultPackages = [
|
||||
nodejs
|
||||
pnpm
|
||||
rust
|
||||
@@ -202,112 +205,113 @@
|
||||
pkgs.nixd
|
||||
pkgs.jdk
|
||||
];
|
||||
in {
|
||||
treefmt = {
|
||||
projectRootFile = "flake.nix";
|
||||
programs = {
|
||||
nixfmt.enable = true;
|
||||
oxfmt.enable = true;
|
||||
};
|
||||
settings.global.excludes = [
|
||||
"dist"
|
||||
"node_modules"
|
||||
"pnpm-lock.yaml"
|
||||
"pnpm-workspace.yaml"
|
||||
"package.json"
|
||||
"LICENSE"
|
||||
"CHANGELOG.md"
|
||||
"./changeset"
|
||||
];
|
||||
};
|
||||
pre-commit.settings.hooks = {
|
||||
in
|
||||
{
|
||||
treefmt = {
|
||||
enable = true;
|
||||
package = config.treefmt.build.wrapper;
|
||||
};
|
||||
};
|
||||
|
||||
packages.sable = pkgs.stdenv.mkDerivation (finalAttrs: {
|
||||
pname = "sable";
|
||||
inherit (packageJson) version;
|
||||
src = lib.cleanSource ./.;
|
||||
|
||||
# ignoring knope for building
|
||||
pnpmInstallFlags = ["--ignore-scripts"];
|
||||
|
||||
pnpmDeps = mkPnpmDeps {
|
||||
inherit (finalAttrs) src version pnpmInstallFlags;
|
||||
};
|
||||
|
||||
nativeBuildInputs = pnpmNativeBuildInputs;
|
||||
|
||||
env.VITE_BUILD_HASH = self.shortRev or self.dirtyShortRev or "";
|
||||
env.SABLE_BUILD_FLAVOR = "stable";
|
||||
|
||||
buildPhase = ''
|
||||
runHook preBuild
|
||||
pnpm run build
|
||||
runHook postBuild
|
||||
'';
|
||||
|
||||
installPhase = ''
|
||||
runHook preInstall
|
||||
cp -r dist $out
|
||||
runHook postInstall
|
||||
'';
|
||||
});
|
||||
|
||||
packages.android-emulator = androidEnv.emulateApp {
|
||||
name = "emulate-sable";
|
||||
platformVersion = platformVersion;
|
||||
abiVersion = "x86_64"; # arm64-v8a
|
||||
systemImageType = systemImageType;
|
||||
};
|
||||
|
||||
packages.default = config.packages.sable;
|
||||
|
||||
checks = {
|
||||
build = config.packages.sable;
|
||||
lint = mkPnpmCheck "lint" "lint";
|
||||
fmt = mkPnpmCheck "fmt" "fmt:check";
|
||||
test = mkPnpmCheck "test" "test:run";
|
||||
typecheck = mkPnpmCheck "typecheck" "typecheck";
|
||||
knip = mkPnpmCheck "knip" "knip";
|
||||
};
|
||||
|
||||
devShells = {
|
||||
default = pkgs.mkShell {
|
||||
inherit buildInputs nativeBuildInputs;
|
||||
|
||||
packages = defaultPackages;
|
||||
|
||||
LD_LIBRARY_PATH = pkgs.lib.makeLibraryPath (nativeBuildInputs ++ buildInputs);
|
||||
|
||||
GIO_EXTRA_MODULES = "${pkgs.glib-networking}/lib/gio/modules";
|
||||
GST_PLUGIN_SYSTEM_PATH = "${pkgs.gst_all_1.gst-plugins-base}/lib/gstreamer-1.0:${pkgs.gst_all_1.gst-plugins-good}/lib/gstreamer-1.0:${pkgs.gst_all_1.gst-plugins-bad}/lib/gstreamer-1.0";
|
||||
|
||||
RUST_SRC_PATH = "${pkgs.rust.packages.stable.rustPlatform.rustLibSrc}";
|
||||
};
|
||||
|
||||
android = pkgs.mkShell {
|
||||
inherit buildInputs nativeBuildInputs;
|
||||
|
||||
packages = defaultPackages ++ [
|
||||
android-sdk
|
||||
projectRootFile = "flake.nix";
|
||||
programs = {
|
||||
nixfmt.enable = true;
|
||||
oxfmt.enable = true;
|
||||
};
|
||||
settings.global.excludes = [
|
||||
"dist"
|
||||
"node_modules"
|
||||
"pnpm-lock.yaml"
|
||||
"pnpm-workspace.yaml"
|
||||
"package.json"
|
||||
"LICENSE"
|
||||
"CHANGELOG.md"
|
||||
"./changeset"
|
||||
];
|
||||
};
|
||||
pre-commit.settings.hooks = {
|
||||
treefmt = {
|
||||
enable = true;
|
||||
package = config.treefmt.build.wrapper;
|
||||
};
|
||||
};
|
||||
|
||||
LD_LIBRARY_PATH = pkgs.lib.makeLibraryPath (nativeBuildInputs ++ buildInputs);
|
||||
packages.sable = pkgs.stdenv.mkDerivation (finalAttrs: {
|
||||
pname = "sable";
|
||||
inherit (packageJson) version;
|
||||
src = lib.cleanSource ./.;
|
||||
|
||||
ANDROID_HOME = "${androidComp.androidsdk}/libexec/android-sdk";
|
||||
ANDROID_SDK_ROOT = "${androidComp.androidsdk}/libexec/android-sdk";
|
||||
ANDROID_NDK_ROOT = "${androidComp.androidsdk}/libexec/android-sdk/ndk-bundle";
|
||||
# ignoring knope for building
|
||||
pnpmInstallFlags = [ "--ignore-scripts" ];
|
||||
|
||||
GIO_EXTRA_MODULES = "${pkgs.glib-networking}/lib/gio/modules";
|
||||
GST_PLUGIN_SYSTEM_PATH = "${pkgs.gst_all_1.gst-plugins-base}/lib/gstreamer-1.0:${pkgs.gst_all_1.gst-plugins-good}/lib/gstreamer-1.0:${pkgs.gst_all_1.gst-plugins-bad}/lib/gstreamer-1.0";
|
||||
|
||||
RUST_SRC_PATH = "${pkgs.rust.packages.stable.rustPlatform.rustLibSrc}";
|
||||
pnpmDeps = mkPnpmDeps {
|
||||
inherit (finalAttrs) src version pnpmInstallFlags;
|
||||
};
|
||||
|
||||
nativeBuildInputs = pnpmNativeBuildInputs;
|
||||
|
||||
env.VITE_BUILD_HASH = self.shortRev or self.dirtyShortRev or "";
|
||||
env.SABLE_BUILD_FLAVOR = "stable";
|
||||
|
||||
buildPhase = ''
|
||||
runHook preBuild
|
||||
pnpm run build
|
||||
runHook postBuild
|
||||
'';
|
||||
|
||||
installPhase = ''
|
||||
runHook preInstall
|
||||
cp -r dist $out
|
||||
runHook postInstall
|
||||
'';
|
||||
});
|
||||
|
||||
packages.android-emulator = androidEnv.emulateApp {
|
||||
name = "emulate-sable";
|
||||
platformVersion = platformVersion;
|
||||
abiVersion = "x86_64"; # arm64-v8a
|
||||
systemImageType = systemImageType;
|
||||
};
|
||||
|
||||
packages.default = config.packages.sable;
|
||||
|
||||
checks = {
|
||||
build = config.packages.sable;
|
||||
lint = mkPnpmCheck "lint" "lint";
|
||||
fmt = mkPnpmCheck "fmt" "fmt:check";
|
||||
test = mkPnpmCheck "test" "test:run";
|
||||
typecheck = mkPnpmCheck "typecheck" "typecheck";
|
||||
knip = mkPnpmCheck "knip" "knip";
|
||||
};
|
||||
|
||||
devShells = {
|
||||
default = pkgs.mkShell {
|
||||
inherit buildInputs nativeBuildInputs;
|
||||
|
||||
packages = defaultPackages;
|
||||
|
||||
LD_LIBRARY_PATH = pkgs.lib.makeLibraryPath (nativeBuildInputs ++ buildInputs);
|
||||
|
||||
GIO_EXTRA_MODULES = "${pkgs.glib-networking}/lib/gio/modules";
|
||||
GST_PLUGIN_SYSTEM_PATH = "${pkgs.gst_all_1.gst-plugins-base}/lib/gstreamer-1.0:${pkgs.gst_all_1.gst-plugins-good}/lib/gstreamer-1.0:${pkgs.gst_all_1.gst-plugins-bad}/lib/gstreamer-1.0";
|
||||
|
||||
RUST_SRC_PATH = "${pkgs.rust.packages.stable.rustPlatform.rustLibSrc}";
|
||||
};
|
||||
|
||||
android = pkgs.mkShell {
|
||||
inherit buildInputs nativeBuildInputs;
|
||||
|
||||
packages = defaultPackages ++ [
|
||||
android-sdk
|
||||
];
|
||||
|
||||
LD_LIBRARY_PATH = pkgs.lib.makeLibraryPath (nativeBuildInputs ++ buildInputs);
|
||||
|
||||
ANDROID_HOME = "${androidComp.androidsdk}/libexec/android-sdk";
|
||||
ANDROID_SDK_ROOT = "${androidComp.androidsdk}/libexec/android-sdk";
|
||||
ANDROID_NDK_ROOT = "${androidComp.androidsdk}/libexec/android-sdk/ndk-bundle";
|
||||
|
||||
GIO_EXTRA_MODULES = "${pkgs.glib-networking}/lib/gio/modules";
|
||||
GST_PLUGIN_SYSTEM_PATH = "${pkgs.gst_all_1.gst-plugins-base}/lib/gstreamer-1.0:${pkgs.gst_all_1.gst-plugins-good}/lib/gstreamer-1.0:${pkgs.gst_all_1.gst-plugins-bad}/lib/gstreamer-1.0";
|
||||
|
||||
RUST_SRC_PATH = "${pkgs.rust.packages.stable.rustPlatform.rustLibSrc}";
|
||||
};
|
||||
};
|
||||
};
|
||||
};
|
||||
};
|
||||
}
|
||||
@@ -18,7 +18,6 @@ android-sdk = "22.0"
|
||||
"apt:build-essential" = "latest"
|
||||
"apt:file" = "latest"
|
||||
"apt:libayatana-appindicator3-dev" = "latest"
|
||||
"apt:libpulse0" = "latest"
|
||||
"apt:libgtk-3-dev" = "latest"
|
||||
"apt:librsvg2-dev" = "latest"
|
||||
"apt:libsoup-3.0-dev" = "latest"
|
||||
|
||||
@@ -31,7 +31,6 @@ overrides:
|
||||
- libdrm2
|
||||
- libxkbcommon0
|
||||
- libasound2
|
||||
- libpulse0
|
||||
- libcups2
|
||||
- xdg-utils
|
||||
- xwayland
|
||||
@@ -45,7 +44,6 @@ overrides:
|
||||
- libdrm
|
||||
- libxkbcommon
|
||||
- alsa-lib
|
||||
- pulseaudio-libs
|
||||
- cups-libs
|
||||
- xdg-utils
|
||||
- xorg-x11-server-Xwayland
|
||||
|
||||
@@ -99,6 +99,7 @@
|
||||
"marked": "^18.0.5",
|
||||
"matrix-js-sdk": "42.0.0",
|
||||
"matrix-widget-api": "^1.17.0",
|
||||
"nanoid": "^6.0.0",
|
||||
"pdfjs-dist": "^6.1.200",
|
||||
"react": "^18.3.1",
|
||||
"react-aria": "^3.50.0",
|
||||
|
||||
@@ -202,6 +202,9 @@ importers:
|
||||
matrix-widget-api:
|
||||
specifier: ^1.17.0
|
||||
version: 1.17.0
|
||||
nanoid:
|
||||
specifier: ^6.0.0
|
||||
version: 6.0.0
|
||||
pdfjs-dist:
|
||||
specifier: ^6.1.200
|
||||
version: 6.1.200
|
||||
@@ -4634,6 +4637,11 @@ packages:
|
||||
engines: {node: ^10 || ^12 || ^13.7 || ^14 || >=15.0.1}
|
||||
hasBin: true
|
||||
|
||||
[email protected]:
|
||||
resolution: {integrity: sha512-mkUH+rPkwU2qPadJ0oJZOjeZ5Mxn8Q1UhevwkTRWNuUZzyia3h4rhzK39hxaHTk0o2OxB8W2SQ6A8k23ZDi1pQ==}
|
||||
engines: {node: ^22 || ^24 || >=26}
|
||||
hasBin: true
|
||||
|
||||
no-[email protected]:
|
||||
resolution: {integrity: sha512-fgAN3jGAh+RoxUGZHTSOLJIqUc2wmoBwGR4tbpNAKmmovFoWq0OdRkb0VkldReO2a2iBT/OEulG9XSUc10r3zg==}
|
||||
|
||||
@@ -9824,6 +9832,8 @@ snapshots:
|
||||
|
||||
[email protected]: {}
|
||||
|
||||
[email protected]: {}
|
||||
|
||||
no-[email protected]:
|
||||
dependencies:
|
||||
lower-case: 2.0.2
|
||||
|
||||
@@ -12,15 +12,6 @@ PROFILE="${1:-debug}"
|
||||
ROOT="$(cd "$(dirname "${BASH_SOURCE[0]}")/../.." && pwd)"
|
||||
DEST="${2:-$ROOT/src-tauri/target/$PROFILE}"
|
||||
|
||||
CEF_DIR="$(
|
||||
find "$ROOT/src-tauri/target/$PROFILE/build" \
|
||||
-type d -name cef_linux_x86_64 -print -quit 2>/dev/null || true
|
||||
)"
|
||||
if [ -z "$CEF_DIR" ]; then
|
||||
echo "❌ CEF dist not found under target/$PROFILE/build — build with --features cef first." >&2
|
||||
exit 1
|
||||
fi
|
||||
|
||||
CEF_VERSION="$(awk '
|
||||
/^\[\[package\]\]$/ { in_cef=0 }
|
||||
/^name = "cef"$/ { in_cef=1 }
|
||||
@@ -36,6 +27,18 @@ if [ -z "$CEF_VERSION" ]; then
|
||||
fi
|
||||
CEF_MAJOR="${CEF_VERSION%%.*}"
|
||||
|
||||
CEF_DIR=""
|
||||
while IFS= read -r candidate; do
|
||||
if grep -q "^#define CEF_VERSION_MAJOR $CEF_MAJOR$" "$candidate/include/cef_version.h" 2>/dev/null; then
|
||||
CEF_DIR="$candidate"
|
||||
break
|
||||
fi
|
||||
done < <(find "$ROOT/src-tauri/target/$PROFILE/build" -type d -name cef_linux_x86_64 2>/dev/null)
|
||||
if [ -z "$CEF_DIR" ]; then
|
||||
echo "❌ CEF $CEF_MAJOR dist not found under target/$PROFILE/build — build with --features cef first." >&2
|
||||
exit 1
|
||||
fi
|
||||
|
||||
CEF_LIB="$CEF_DIR/libcef.so"
|
||||
if [ ! -f "$CEF_LIB" ]; then
|
||||
echo "❌ libcef.so not found in $CEF_DIR." >&2
|
||||
|
||||
@@ -74,35 +74,6 @@ stage_appindicator() {
|
||||
done
|
||||
}
|
||||
|
||||
# Bundle the PulseAudio client and its audio dependencies for CEF.
|
||||
stage_pulseaudio() {
|
||||
local dest="$1" main
|
||||
mkdir -p "$dest"
|
||||
main="$(ldconfig -p 2>/dev/null | awk '$1=="libpulse.so.0"{v=$NF} END{print v}')"
|
||||
[ -n "$main" ] || main="$(find /usr/lib /usr/lib64 /lib -name libpulse.so.0 2>/dev/null | sort | tail -n1)"
|
||||
if [ -z "$main" ] || [ ! -e "$main" ]; then
|
||||
echo "warning: libpulse.so.0 not found; PulseAudio disabled in the AppImage" >&2
|
||||
return 0
|
||||
fi
|
||||
local -A seen=()
|
||||
local -a queue=("$main")
|
||||
local lib dep
|
||||
while [ "${#queue[@]}" -gt 0 ]; do
|
||||
lib="${queue[-1]}"
|
||||
queue=("${queue[@]:0:${#queue[@]}-1}")
|
||||
[ -n "$lib" ] && [ -e "$lib" ] || continue
|
||||
seen["$lib"]=1
|
||||
while read -r dep; do
|
||||
[ -n "$dep" ] && [ -z "${seen[$dep]:-}" ] || continue
|
||||
seen["$dep"]=1
|
||||
queue+=("$dep")
|
||||
done < <(ldd "$lib" 2>/dev/null | awk '/=>/ {print $3}' | grep -iE 'pulse|sndfile|asyncns|FLAC|ogg|vorbis|opus|mpg123|mp3lame|lame|speexdsp' || true)
|
||||
done
|
||||
for lib in "${!seen[@]}"; do
|
||||
cp -Lf "$lib" "$dest/$(basename "$lib")"
|
||||
done
|
||||
}
|
||||
|
||||
write_desktop() {
|
||||
cat > "$1" <<EOF
|
||||
[Desktop Entry]
|
||||
@@ -159,7 +130,6 @@ if [ -n "$APPIMAGETOOL_CMD" ]; then
|
||||
APPDIR="$WORK/Sable.AppDir"
|
||||
stage_runtime "$APPDIR/usr/bin"
|
||||
stage_appindicator "$APPDIR/usr/bin"
|
||||
stage_pulseaudio "$APPDIR/usr/bin"
|
||||
# nosuid AppImage mount: drop setuid chrome-sandbox, use the namespace sandbox.
|
||||
rm -f "$APPDIR/usr/bin/chrome-sandbox"
|
||||
write_desktop "$APPDIR/sable.desktop"
|
||||
|
||||
@@ -0,0 +1,62 @@
|
||||
#!/usr/bin/env node
|
||||
//MISE hide=true
|
||||
//MISE description="Generate obtainium.json for one-click app import"
|
||||
/* oxlint-disable no-console */
|
||||
|
||||
import { writeFileSync } from 'node:fs';
|
||||
import { resolve } from 'node:path';
|
||||
import process from 'node:process';
|
||||
|
||||
const version = process.argv[2];
|
||||
const tag = process.argv[3] || `v${version}`;
|
||||
const outputPath = process.argv[4] || 'obtainium.json';
|
||||
|
||||
if (!version) {
|
||||
console.error('Usage: node scripts/obtainium-generate.js <version> [tag] [output-path]');
|
||||
process.exit(1);
|
||||
}
|
||||
|
||||
const GITHUB_REPO = 'SableClient/Sable';
|
||||
const APK_NAME = `Sable-${version}-android-universal.apk`;
|
||||
const APK_URL = `https://github.com/${GITHUB_REPO}/releases/download/${tag}/${APK_NAME}`;
|
||||
const isNightly = tag === 'nightly';
|
||||
|
||||
// Obtainium fills in every other setting from its own defaults on import.
|
||||
const additionalSettings = {
|
||||
about: 'An almost stable Matrix client',
|
||||
// The nightly tag name never changes, so the version has to come from the date instead.
|
||||
...(isNightly && {
|
||||
includePrereleases: true,
|
||||
useLatestAssetDateAsReleaseDate: true,
|
||||
releaseDateAsVersion: true,
|
||||
versionDetection: false,
|
||||
}),
|
||||
};
|
||||
|
||||
const config = {
|
||||
apps: [
|
||||
{
|
||||
id: 'moe.sable.client',
|
||||
url: `https://github.com/${GITHUB_REPO}`,
|
||||
author: 'SableClient',
|
||||
name: 'Sable',
|
||||
installedVersion: null,
|
||||
latestVersion: version,
|
||||
apkUrls: JSON.stringify([[APK_NAME, APK_URL]]),
|
||||
otherAssetUrls: '[]',
|
||||
preferredApkIndex: 0,
|
||||
additionalSettings: JSON.stringify(additionalSettings),
|
||||
lastUpdateCheck: null,
|
||||
pinned: false,
|
||||
categories: ['Communication'],
|
||||
releaseDate: null,
|
||||
changeLog: null,
|
||||
overrideSource: 'GitHub',
|
||||
allowIdChange: false,
|
||||
pendingRepoRenameUrl: null,
|
||||
},
|
||||
],
|
||||
};
|
||||
|
||||
writeFileSync(resolve(outputPath), JSON.stringify(config, null, 2) + '\n');
|
||||
console.log(`Generated ${outputPath}`);
|
||||
@@ -35,13 +35,13 @@ checksum = "320119579fcad9c21884f5c4861d16174d0e06250625266f50fe6898340abefa"
|
||||
|
||||
[[package]]
|
||||
name = "aes"
|
||||
version = "0.8.4"
|
||||
version = "0.9.2"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "b169f7a6d4742236a0a00c541b845991d0ac43e546831af1249753ab4c3aa3a0"
|
||||
checksum = "f8eb277bec05f56a0e0591f155a484cbd0f4f07ff2905051a48c72f004f7ed58"
|
||||
dependencies = [
|
||||
"cfg-if",
|
||||
"cipher",
|
||||
"cpufeatures 0.2.17",
|
||||
"cpubits",
|
||||
"cpufeatures 0.3.0",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
@@ -168,7 +168,7 @@ version = "1.1.5"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "40c48f72fd53cd289104fc64099abca73db4166ad86ea0b4341abe65af83dadc"
|
||||
dependencies = [
|
||||
"windows-sys 0.61.2",
|
||||
"windows-sys 0.60.2",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
@@ -179,7 +179,7 @@ checksum = "291e6a250ff86cd4a820112fb8898808a366d8f9f58ce16d1f538353ad55747d"
|
||||
dependencies = [
|
||||
"anstyle",
|
||||
"once_cell_polyfill",
|
||||
"windows-sys 0.61.2",
|
||||
"windows-sys 0.60.2",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
@@ -496,6 +496,12 @@ version = "0.22.1"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "72b3254f16251a8381aa12e40e3c4d2f0199f8c6508fbecb9d91f575e0fbb8c6"
|
||||
|
||||
[[package]]
|
||||
name = "base64"
|
||||
version = "0.23.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "b25655df2c3cdd83c5e5b293b88acd880332b2ddadd7c30ac43144fdc0033da9"
|
||||
|
||||
[[package]]
|
||||
name = "bit-set"
|
||||
version = "0.8.0"
|
||||
@@ -541,6 +547,15 @@ dependencies = [
|
||||
"generic-array",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "block-buffer"
|
||||
version = "0.12.1"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "d2f6c7dbe95a6ed67ad9f18e57daf93a2f034c524b99fd2b76d18fdfeb6660aa"
|
||||
dependencies = [
|
||||
"hybrid-array",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "block2"
|
||||
version = "0.6.2"
|
||||
@@ -903,11 +918,12 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "cipher"
|
||||
version = "0.4.4"
|
||||
version = "0.5.2"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "773f3b9af64447d2ce9850330c473515014aa235e6a783b02db81ff39e4a3dad"
|
||||
checksum = "e8cf2a2c93cd704877c0858356ed03480ff301ee950b43f1cbe4573b088bfa6c"
|
||||
dependencies = [
|
||||
"crypto-common",
|
||||
"block-buffer 0.12.1",
|
||||
"crypto-common 0.2.2",
|
||||
"inout",
|
||||
]
|
||||
|
||||
@@ -1058,6 +1074,12 @@ dependencies = [
|
||||
"windows-sys 0.61.2",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "const-oid"
|
||||
version = "0.10.2"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "a6ef517f0926dd24a1582492c791b6a4818a4d94e789a334894aa15b0d12f55c"
|
||||
|
||||
[[package]]
|
||||
name = "const-random"
|
||||
version = "0.1.18"
|
||||
@@ -1177,6 +1199,12 @@ dependencies = [
|
||||
"libc",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "cpubits"
|
||||
version = "0.1.1"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "15b85f9c39137c3a891689859392b1bd49812121d0d61c9caf00d46ed5ce06ae"
|
||||
|
||||
[[package]]
|
||||
name = "cpufeatures"
|
||||
version = "0.2.17"
|
||||
@@ -1254,6 +1282,15 @@ dependencies = [
|
||||
"typenum",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "crypto-common"
|
||||
version = "0.2.2"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "ce6e4c961d6cd6c9a86db418387425e8bdeaf05b3c8bc1411e6dca4c252f1453"
|
||||
dependencies = [
|
||||
"hybrid-array",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "cssparser"
|
||||
version = "0.29.6"
|
||||
@@ -1312,9 +1349,9 @@ checksum = "52560adf09603e58c9a7ee1fe1dcb95a16927b17c127f0ac02d6e768a0e25bc1"
|
||||
|
||||
[[package]]
|
||||
name = "ctr"
|
||||
version = "0.9.2"
|
||||
version = "0.10.1"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "0369ee1ad671834580515889b80f2ea915f23b8be8d0daa4bbaf2ac5c7590835"
|
||||
checksum = "baaca1c4b237092596f64d571e9db6ce4109c4ef9742e27590f1709594461f21"
|
||||
dependencies = [
|
||||
"cipher",
|
||||
]
|
||||
@@ -1525,8 +1562,19 @@ version = "0.10.7"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "9ed9a281f7bc9b7576e61468ba615a66a5c8cfdff42420a70aa82701a3b1e292"
|
||||
dependencies = [
|
||||
"block-buffer",
|
||||
"crypto-common",
|
||||
"block-buffer 0.10.4",
|
||||
"crypto-common 0.1.7",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "digest"
|
||||
version = "0.11.3"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "f1dd6dbb5841937940781866fa1281a1ff7bd3bf827091440879f9994983d5c2"
|
||||
dependencies = [
|
||||
"block-buffer 0.12.1",
|
||||
"const-oid",
|
||||
"crypto-common 0.2.2",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
@@ -1553,7 +1601,7 @@ dependencies = [
|
||||
"libc",
|
||||
"option-ext",
|
||||
"redox_users",
|
||||
"windows-sys 0.61.2",
|
||||
"windows-sys 0.59.0",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
@@ -1781,9 +1829,9 @@ checksum = "66b7e2430c6dff6a955451e2cfc438f09cea1965a9d6f87f7e3b90decc014099"
|
||||
|
||||
[[package]]
|
||||
name = "enigo"
|
||||
version = "0.5.0"
|
||||
version = "0.6.1"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "71744ff36f35a4276e8827add8102d0e792378c574fd93cb4e1c8e0505f96b7c"
|
||||
checksum = "71c6c56e50f7acae2906a0dcbb34529ca647e40421119ad5d12e7f8ba6e50010"
|
||||
dependencies = [
|
||||
"core-foundation 0.10.1",
|
||||
"core-graphics 0.25.0",
|
||||
@@ -1794,7 +1842,7 @@ dependencies = [
|
||||
"objc2",
|
||||
"objc2-app-kit",
|
||||
"objc2-foundation",
|
||||
"windows",
|
||||
"windows 0.61.3",
|
||||
"x11rb",
|
||||
"xkbcommon",
|
||||
"xkeysym",
|
||||
@@ -1855,7 +1903,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "39cab71617ae0d63f51a36d69f866391735b51691dbda63cf6f96d042b63efeb"
|
||||
dependencies = [
|
||||
"libc",
|
||||
"windows-sys 0.61.2",
|
||||
"windows-sys 0.52.0",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
@@ -2733,6 +2781,15 @@ dependencies = [
|
||||
"libm",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "hybrid-array"
|
||||
version = "0.4.14"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "707114b52a152fa7bdb290cd7cd5912d9467273b6d74e21b8d81aca1f8533f6b"
|
||||
dependencies = [
|
||||
"typenum",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "hyper"
|
||||
version = "0.14.32"
|
||||
@@ -3070,11 +3127,11 @@ checksum = "f4200d433cbd5178df7797c9c2e75b348b728e39631cf14520d1e2fc424201f4"
|
||||
|
||||
[[package]]
|
||||
name = "inout"
|
||||
version = "0.1.4"
|
||||
version = "0.2.2"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "879f10e63c20629ecabbb64a8010319738c66a5cd0c29b02d63d272b03751d01"
|
||||
checksum = "4250ce6452e92010fdf7268ccc5d14faa80bb12fc741938534c58f16804e03c7"
|
||||
dependencies = [
|
||||
"generic-array",
|
||||
"hybrid-array",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
@@ -3653,7 +3710,7 @@ dependencies = [
|
||||
"png 0.18.1",
|
||||
"serde",
|
||||
"thiserror 2.0.19",
|
||||
"windows-sys 0.61.2",
|
||||
"windows-sys 0.60.2",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
@@ -3777,7 +3834,7 @@ version = "0.50.3"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "7957b9740744892f114936ab4a57b3f487491bbeafaf8083688b16841a4240e5"
|
||||
dependencies = [
|
||||
"windows-sys 0.61.2",
|
||||
"windows-sys 0.59.0",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
@@ -4217,7 +4274,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "7d8fae84b431384b68627d0f9b3b1245fcf9f46f6c0e3dc902e9dce64edd1967"
|
||||
dependencies = [
|
||||
"libc",
|
||||
"windows-sys 0.61.2",
|
||||
"windows-sys 0.48.0",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
@@ -4875,7 +4932,7 @@ dependencies = [
|
||||
"once_cell",
|
||||
"socket2 0.6.5",
|
||||
"tracing",
|
||||
"windows-sys 0.61.2",
|
||||
"windows-sys 0.52.0",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
@@ -5294,7 +5351,7 @@ dependencies = [
|
||||
"errno",
|
||||
"libc",
|
||||
"linux-raw-sys",
|
||||
"windows-sys 0.61.2",
|
||||
"windows-sys 0.52.0",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
@@ -5352,7 +5409,7 @@ dependencies = [
|
||||
"security-framework",
|
||||
"security-framework-sys",
|
||||
"webpki-root-certs",
|
||||
"windows-sys 0.61.2",
|
||||
"windows-sys 0.52.0",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
@@ -5390,7 +5447,7 @@ version = "1.20.0"
|
||||
dependencies = [
|
||||
"aes",
|
||||
"async-stream",
|
||||
"base64 0.22.1",
|
||||
"base64 0.23.0",
|
||||
"block2",
|
||||
"cef",
|
||||
"ctr",
|
||||
@@ -5398,8 +5455,8 @@ dependencies = [
|
||||
"futures-util",
|
||||
"gtk",
|
||||
"infer 0.22.0",
|
||||
"jni 0.21.1",
|
||||
"libloading 0.8.9",
|
||||
"jni 0.22.4",
|
||||
"libloading 0.9.0",
|
||||
"log",
|
||||
"objc2",
|
||||
"objc2-avf-audio",
|
||||
@@ -5412,7 +5469,7 @@ dependencies = [
|
||||
"sentry",
|
||||
"serde",
|
||||
"serde_json",
|
||||
"sha2",
|
||||
"sha2 0.11.0",
|
||||
"tauri",
|
||||
"tauri-build",
|
||||
"tauri-plugin-android-fs",
|
||||
@@ -5440,8 +5497,8 @@ dependencies = [
|
||||
"tokio-util",
|
||||
"ts-rs",
|
||||
"webkit2gtk",
|
||||
"windows",
|
||||
"zip",
|
||||
"windows 0.62.2",
|
||||
"zip 8.6.0",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
@@ -5610,9 +5667,9 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "sentry"
|
||||
version = "0.48.5"
|
||||
version = "0.49.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "d631477761f57c76148456e55e80e9a479ff3fa4c65b2b4a0c3acf1167fd4638"
|
||||
checksum = "d91e4790d8c2f43a6645ee2cb12aac2db79221fddd035b94c8166b88ea094408"
|
||||
dependencies = [
|
||||
"cfg_aliases",
|
||||
"httpdate",
|
||||
@@ -5627,9 +5684,9 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "sentry-backtrace"
|
||||
version = "0.48.5"
|
||||
version = "0.49.1"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "448b0981fbde6cdc9eb087ba3dc01035a253fef9a0d9e79aaf198fc26acb2e64"
|
||||
checksum = "e3bcc2497c2327998146207b7600599ef7592233920f4d4e1d41ddeeba0e4210"
|
||||
dependencies = [
|
||||
"backtrace",
|
||||
"regex",
|
||||
@@ -5638,9 +5695,9 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "sentry-contexts"
|
||||
version = "0.48.5"
|
||||
version = "0.49.1"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "9e5e909d02170ba6d1dc5ebd05bef7999280f5d960e3eaee5d1a18d88d41b334"
|
||||
checksum = "1cb04cba225b38f59d08f9e3c29ab7259d9cc94fbb2c46d613a51cb0a4a7ee05"
|
||||
dependencies = [
|
||||
"hostname",
|
||||
"libc",
|
||||
@@ -5652,9 +5709,9 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "sentry-core"
|
||||
version = "0.48.5"
|
||||
version = "0.49.1"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "ecf0b1a4a4e9ec88395b52e6fa4868b95564c1fa96b26a0606f5f6288a0f7149"
|
||||
checksum = "48759bc392fb5e3b36b4efcb485f51074c0ba8479711cd5c8cf79e86f9f75d41"
|
||||
dependencies = [
|
||||
"rand 0.9.5",
|
||||
"sentry-types",
|
||||
@@ -5665,9 +5722,9 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "sentry-debug-images"
|
||||
version = "0.48.5"
|
||||
version = "0.49.1"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "f81d7749c57fc78ed52134889e8121da874065bc40da788d5798cce0f8c19f15"
|
||||
checksum = "0a5bd325059b70b21ca6e42b0f2409821272dddc1cf37923de37269af55389b5"
|
||||
dependencies = [
|
||||
"findshlibs",
|
||||
"sentry-core",
|
||||
@@ -5675,9 +5732,9 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "sentry-panic"
|
||||
version = "0.48.5"
|
||||
version = "0.49.1"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "0b7d93d6ecb55d2251c5fc084c55c03a2bc68904918d76117e602c999e92f00f"
|
||||
checksum = "a685d22f672b1562ebeff3f2affceb5960595648cc936dae73da3e1d6a55fbd1"
|
||||
dependencies = [
|
||||
"sentry-backtrace",
|
||||
"sentry-core",
|
||||
@@ -5685,9 +5742,9 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "sentry-tracing"
|
||||
version = "0.48.5"
|
||||
version = "0.49.1"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "58d26379236c4ef97eaf081bca3c7bf0ef6f06b3aa881eca2ee8e8dbc923e5b8"
|
||||
checksum = "8aa7d8e0db4cccddbac01ddabd5344ad03b7c2f954b3ff850cecb1d9cf5d4758"
|
||||
dependencies = [
|
||||
"bitflags 2.13.1",
|
||||
"sentry-backtrace",
|
||||
@@ -5698,9 +5755,9 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "sentry-types"
|
||||
version = "0.48.5"
|
||||
version = "0.49.1"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "2239099d47e76857b0825a182ecdb90159add7aa1097b60247c6e7ca6bf49c6a"
|
||||
checksum = "fab146d15a30ab4897a95fd15d6a038b8d7fbf2661c5f8b13738ce8df7a095b7"
|
||||
dependencies = [
|
||||
"debugid",
|
||||
"hex",
|
||||
@@ -5913,7 +5970,18 @@ checksum = "a7507d819769d01a365ab707794a4084392c824f54a7a6a7862f8c3d0892b283"
|
||||
dependencies = [
|
||||
"cfg-if",
|
||||
"cpufeatures 0.2.17",
|
||||
"digest",
|
||||
"digest 0.10.7",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "sha2"
|
||||
version = "0.11.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "446ba717509524cb3f22f17ecc096f10f4822d76ab5c0b9822c5f9c284e825f4"
|
||||
dependencies = [
|
||||
"cfg-if",
|
||||
"cpufeatures 0.3.0",
|
||||
"digest 0.11.3",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
@@ -6051,7 +6119,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "c3d1e2c7f27f8d4cb10542a02c49005dbd6e93095799d6f3be745fae9f8fedd4"
|
||||
dependencies = [
|
||||
"libc",
|
||||
"windows-sys 0.61.2",
|
||||
"windows-sys 0.60.2",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
@@ -6391,7 +6459,7 @@ dependencies = [
|
||||
"tao-macros",
|
||||
"unicode-segmentation",
|
||||
"url",
|
||||
"windows",
|
||||
"windows 0.61.3",
|
||||
"windows-core 0.61.2",
|
||||
"windows-version",
|
||||
"x11-dl",
|
||||
@@ -6475,7 +6543,7 @@ dependencies = [
|
||||
"webkit2gtk",
|
||||
"webview2-com",
|
||||
"window-vibrancy",
|
||||
"windows",
|
||||
"windows 0.61.3",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
@@ -6516,7 +6584,7 @@ dependencies = [
|
||||
"semver",
|
||||
"serde",
|
||||
"serde_json",
|
||||
"sha2",
|
||||
"sha2 0.10.9",
|
||||
"syn 2.0.119",
|
||||
"tauri-utils",
|
||||
"thiserror 2.0.19",
|
||||
@@ -6558,9 +6626,9 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "tauri-plugin-android-fs"
|
||||
version = "28.4.0"
|
||||
version = "29.0.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "999e39313646a1f48f65270e75df20664a692bf28fa21f44a16bf8706c154f31"
|
||||
checksum = "8ca3a802951458c58c32e4605d43143ca92c205ba3eb7c989b03183cd88e9e6e"
|
||||
dependencies = [
|
||||
"base64 0.22.1",
|
||||
"glob",
|
||||
@@ -6613,9 +6681,9 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "tauri-plugin-devtools"
|
||||
version = "2.0.0"
|
||||
version = "2.1.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "8e5cd17faa36a826e5686bd0fda5bc3f4c903682263f00cd50f2f778fc4bb866"
|
||||
checksum = "6a8fa7b8275c5f3efed02591d5c080540bec4c3e5b3180586fcd824953328e8e"
|
||||
dependencies = [
|
||||
"async-stream",
|
||||
"bytes",
|
||||
@@ -6754,7 +6822,7 @@ dependencies = [
|
||||
[[package]]
|
||||
name = "tauri-plugin-notifications"
|
||||
version = "0.5.0-rc.11"
|
||||
source = "git+https://github.com/SableClient/tauri-plugin-notifications.git?rev=0175b5ec58a31ab15397e981a67f47fa32254620#0175b5ec58a31ab15397e981a67f47fa32254620"
|
||||
source = "git+https://github.com/SableClient/tauri-plugin-notifications.git?rev=057d323862d815a0c7459a1f1acd5a3c08750a51#057d323862d815a0c7459a1f1acd5a3c08750a51"
|
||||
dependencies = [
|
||||
"log",
|
||||
"notify-rust",
|
||||
@@ -6772,7 +6840,7 @@ dependencies = [
|
||||
"tokio",
|
||||
"url",
|
||||
"uuid",
|
||||
"windows",
|
||||
"windows 0.61.3",
|
||||
"windows-core 0.61.2",
|
||||
"zbus",
|
||||
]
|
||||
@@ -6795,7 +6863,7 @@ dependencies = [
|
||||
"tauri-plugin",
|
||||
"thiserror 2.0.19",
|
||||
"url",
|
||||
"windows",
|
||||
"windows 0.61.3",
|
||||
"zbus",
|
||||
]
|
||||
|
||||
@@ -6844,8 +6912,8 @@ dependencies = [
|
||||
"tauri-plugin",
|
||||
"thiserror 2.0.19",
|
||||
"tokio",
|
||||
"windows",
|
||||
"windows-collections",
|
||||
"windows 0.61.3",
|
||||
"windows-collections 0.2.0",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
@@ -6911,7 +6979,7 @@ dependencies = [
|
||||
"tokio",
|
||||
"url",
|
||||
"windows-sys 0.60.2",
|
||||
"zip",
|
||||
"zip 4.6.1",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
@@ -6951,13 +7019,13 @@ dependencies = [
|
||||
"url",
|
||||
"webkit2gtk",
|
||||
"webview2-com",
|
||||
"windows",
|
||||
"windows 0.61.3",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "tauri-runtime-cef"
|
||||
version = "0.1.0"
|
||||
source = "git+https://github.com/SableClient/tauri-runtime-cef?branch=main#23464067ddcfe61239e41faeb26e1ce200ff3242"
|
||||
source = "git+https://github.com/SableClient/tauri-runtime-cef?branch=main#6aee1cdbe137b53cb28201417ec302b75a93330a"
|
||||
dependencies = [
|
||||
"base64 0.22.1",
|
||||
"cef",
|
||||
@@ -6980,12 +7048,12 @@ dependencies = [
|
||||
"raw-window-handle",
|
||||
"serde",
|
||||
"serde_json",
|
||||
"sha2",
|
||||
"sha2 0.10.9",
|
||||
"softbuffer",
|
||||
"tauri-runtime",
|
||||
"tauri-utils",
|
||||
"url",
|
||||
"windows",
|
||||
"windows 0.61.3",
|
||||
"winit",
|
||||
"x11-dl",
|
||||
]
|
||||
@@ -7013,7 +7081,7 @@ dependencies = [
|
||||
"url",
|
||||
"webkit2gtk",
|
||||
"webview2-com",
|
||||
"windows",
|
||||
"windows 0.61.3",
|
||||
"wry",
|
||||
]
|
||||
|
||||
@@ -7095,7 +7163,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "9ed071c670382e85fc2f48ae706492d8c338f4f89bf72520d32f8abfe880aade"
|
||||
dependencies = [
|
||||
"thiserror 2.0.19",
|
||||
"windows",
|
||||
"windows 0.61.3",
|
||||
"windows-version",
|
||||
]
|
||||
|
||||
@@ -7109,7 +7177,7 @@ dependencies = [
|
||||
"getrandom 0.4.3",
|
||||
"once_cell",
|
||||
"rustix",
|
||||
"windows-sys 0.61.2",
|
||||
"windows-sys 0.52.0",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
@@ -7734,7 +7802,7 @@ dependencies = [
|
||||
"png 0.18.1",
|
||||
"serde",
|
||||
"thiserror 2.0.19",
|
||||
"windows-sys 0.61.2",
|
||||
"windows-sys 0.60.2",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
@@ -7782,6 +7850,12 @@ version = "0.25.1"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "d2df906b07856748fa3f6e0ad0cbaa047052d4a7dd609e231c4f72cee8c36f31"
|
||||
|
||||
[[package]]
|
||||
name = "typed-path"
|
||||
version = "0.12.3"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "8e28f89b80c87b8fb0cf04ab448d5dd0dd0ade2f8891bae878de66a75a28600e"
|
||||
|
||||
[[package]]
|
||||
name = "typeid"
|
||||
version = "1.0.3"
|
||||
@@ -7808,7 +7882,7 @@ checksum = "f2f6fb2847f6742cd76af783a2a2c49e9375d0a111c7bef6f71cd9e738c72d6e"
|
||||
dependencies = [
|
||||
"memoffset",
|
||||
"tempfile",
|
||||
"windows-sys 0.61.2",
|
||||
"windows-sys 0.60.2",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
@@ -8382,7 +8456,7 @@ checksum = "7130243a7a5b33c54a444e54842e6a9e133de08b5ad7b5861cd8ed9a6a5bc96a"
|
||||
dependencies = [
|
||||
"webview2-com-macros",
|
||||
"webview2-com-sys",
|
||||
"windows",
|
||||
"windows 0.61.3",
|
||||
"windows-core 0.61.2",
|
||||
"windows-implement",
|
||||
"windows-interface",
|
||||
@@ -8406,7 +8480,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "381336cfffd772377d291702245447a5251a2ffa5bad679c99e61bc48bacbf9c"
|
||||
dependencies = [
|
||||
"thiserror 2.0.19",
|
||||
"windows",
|
||||
"windows 0.61.3",
|
||||
"windows-core 0.61.2",
|
||||
]
|
||||
|
||||
@@ -8438,7 +8512,7 @@ version = "0.1.11"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "c2a7b1c03c876122aa43f3020e6c3c3ee5c05081c9a00739faf7503aeba10d22"
|
||||
dependencies = [
|
||||
"windows-sys 0.61.2",
|
||||
"windows-sys 0.48.0",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
@@ -8468,11 +8542,23 @@ version = "0.61.3"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "9babd3a767a4c1aef6900409f85f5d53ce2544ccdfaa86dad48c91782c6d6893"
|
||||
dependencies = [
|
||||
"windows-collections",
|
||||
"windows-collections 0.2.0",
|
||||
"windows-core 0.61.2",
|
||||
"windows-future",
|
||||
"windows-future 0.2.1",
|
||||
"windows-link 0.1.3",
|
||||
"windows-numerics",
|
||||
"windows-numerics 0.2.0",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "windows"
|
||||
version = "0.62.2"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "527fadee13e0c05939a6a05d5bd6eec6cd2e3dbd648b9f8e447c6518133d8580"
|
||||
dependencies = [
|
||||
"windows-collections 0.3.2",
|
||||
"windows-core 0.62.2",
|
||||
"windows-future 0.3.2",
|
||||
"windows-numerics 0.3.1",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
@@ -8484,6 +8570,15 @@ dependencies = [
|
||||
"windows-core 0.61.2",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "windows-collections"
|
||||
version = "0.3.2"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "23b2d95af1a8a14a3c7367e1ed4fc9c20e0a26e79551b1454d72583c97cc6610"
|
||||
dependencies = [
|
||||
"windows-core 0.62.2",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "windows-core"
|
||||
version = "0.61.2"
|
||||
@@ -8518,7 +8613,18 @@ checksum = "fc6a41e98427b19fe4b73c550f060b59fa592d7d686537eebf9385621bfbad8e"
|
||||
dependencies = [
|
||||
"windows-core 0.61.2",
|
||||
"windows-link 0.1.3",
|
||||
"windows-threading",
|
||||
"windows-threading 0.1.0",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "windows-future"
|
||||
version = "0.3.2"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "e1d6f90251fe18a279739e78025bd6ddc52a7e22f921070ccdc67dde84c605cb"
|
||||
dependencies = [
|
||||
"windows-core 0.62.2",
|
||||
"windows-link 0.2.1",
|
||||
"windows-threading 0.2.1",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
@@ -8565,6 +8671,16 @@ dependencies = [
|
||||
"windows-link 0.1.3",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "windows-numerics"
|
||||
version = "0.3.1"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "6e2e40844ac143cdb44aead537bbf727de9b044e107a0f1220392177d15b0f26"
|
||||
dependencies = [
|
||||
"windows-core 0.62.2",
|
||||
"windows-link 0.2.1",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "windows-registry"
|
||||
version = "0.5.3"
|
||||
@@ -8738,6 +8854,15 @@ dependencies = [
|
||||
"windows-link 0.1.3",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "windows-threading"
|
||||
version = "0.2.1"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "3949bd5b99cafdf1c7ca86b43ca564028dfe27d66958f2470940f73d86d75b37"
|
||||
dependencies = [
|
||||
"windows-link 0.2.1",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "windows-version"
|
||||
version = "0.1.7"
|
||||
@@ -9246,7 +9371,7 @@ dependencies = [
|
||||
"once_cell",
|
||||
"percent-encoding",
|
||||
"raw-window-handle",
|
||||
"sha2",
|
||||
"sha2 0.10.9",
|
||||
"soup3",
|
||||
"tao-macros",
|
||||
"thiserror 2.0.19",
|
||||
@@ -9255,7 +9380,7 @@ dependencies = [
|
||||
"webkit2gtk",
|
||||
"webkit2gtk-sys",
|
||||
"webview2-com",
|
||||
"windows",
|
||||
"windows 0.61.3",
|
||||
"windows-core 0.61.2",
|
||||
"windows-version",
|
||||
"x11-dl",
|
||||
@@ -9322,9 +9447,9 @@ checksum = "bec9e4a500ca8864c5b47b8b482a73d62e4237670e5b5f1d6b9e3cae50f28f2b"
|
||||
|
||||
[[package]]
|
||||
name = "xkbcommon"
|
||||
version = "0.8.0"
|
||||
version = "0.9.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "8d66ca9352cbd4eecbbc40871d8a11b4ac8107cfc528a6e14d7c19c69d0e1ac9"
|
||||
checksum = "a7a974f48060a14e95705c01f24ad9c3345022f4d97441b8a36beb7ed5c4a02d"
|
||||
dependencies = [
|
||||
"libc",
|
||||
"memmap2",
|
||||
@@ -9522,10 +9647,22 @@ source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "caa8cd6af31c3b31c6631b8f483848b91589021b28fffe50adada48d4f4d2ed1"
|
||||
dependencies = [
|
||||
"arbitrary",
|
||||
"crc32fast",
|
||||
"indexmap 2.14.0",
|
||||
"memchr",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "zip"
|
||||
version = "8.6.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "2d04a6b5381502aa6087c94c669499eb1602eb9c5e8198e534de571f7154809b"
|
||||
dependencies = [
|
||||
"crc32fast",
|
||||
"flate2",
|
||||
"indexmap 2.14.0",
|
||||
"memchr",
|
||||
"typed-path",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
|
||||
@@ -24,7 +24,7 @@ serde = { version = "1.0", features = ["derive"] }
|
||||
log = "0.4"
|
||||
# default-features = false drops reqwest + native-tls (openssl); ureq is a sync
|
||||
# rustls transport with no async-runtime dependency.
|
||||
sentry = { version = "0.48.5", default-features = false, features = [
|
||||
sentry = { version = "0.49.0", default-features = false, features = [
|
||||
"backtrace",
|
||||
"contexts",
|
||||
"panic",
|
||||
@@ -33,9 +33,9 @@ sentry = { version = "0.48.5", default-features = false, features = [
|
||||
] }
|
||||
tokio = { version = "1", features = ["time", "sync", "fs", "io-util"] }
|
||||
ts-rs = "12.0.0"
|
||||
sha2 = "0.10"
|
||||
aes = "0.8"
|
||||
ctr = "0.9"
|
||||
sha2 = "0.11"
|
||||
aes = "0.9"
|
||||
ctr = "0.10"
|
||||
infer = { version = "0.22", default-features = false }
|
||||
percent-encoding = "2"
|
||||
# Enables `stream` (for native_upload's `Body::wrap_stream`) on the reqwest that
|
||||
@@ -43,11 +43,11 @@ percent-encoding = "2"
|
||||
# openssl-sys out of the Android cross-compile.
|
||||
reqwest = { version = "0.12", default-features = false, features = ["stream"] }
|
||||
async-stream = "0.3"
|
||||
base64 = "0.22"
|
||||
base64 = "0.23"
|
||||
tokio-util = { version = "0.7", features = ["codec"] }
|
||||
futures-util = "0.3"
|
||||
regex = "1"
|
||||
zip = { version = "=4.6.1", default-features = false, features = ["deflate-flate2-zlib-rs"] }
|
||||
zip = { version = "=8.6.0", default-features = false, features = ["deflate-flate2-zlib-rs"] }
|
||||
|
||||
tauri = { version = "2.11.5", default-features = false, features = [
|
||||
"tray-icon",
|
||||
@@ -76,11 +76,11 @@ tauri-plugin-dialog = "2"
|
||||
# wry/tauri-runtime-wry/webkit2gtk.
|
||||
# Pinned to =2.0.0 because 2.1.0+ introduced an unconditional call to
|
||||
# tauri::webview_version() which is gated behind tauri's `wry` feature.
|
||||
tauri-plugin-devtools = { version = "=2.0.0", default-features = false, optional = true }
|
||||
tauri-plugin-devtools = { version = "=2.1.0", default-features = false, optional = true }
|
||||
|
||||
[target.'cfg(target_os = "windows")'.dependencies]
|
||||
enigo = "0.5.0"
|
||||
windows = { version = "0.61", features = [
|
||||
enigo = "0.6.1"
|
||||
windows = { version = "0.62", features = [
|
||||
"Win32_Foundation",
|
||||
"Win32_UI_WindowsAndMessaging",
|
||||
"Win32_System_Threading",
|
||||
@@ -91,12 +91,12 @@ windows = { version = "0.61", features = [
|
||||
tauri-plugin-single-instance = { version = "2.4.3", features = ["deep-link"] }
|
||||
|
||||
[target.'cfg(any(windows, target_os = "linux"))'.dependencies]
|
||||
tauri-plugin-notifications = { git = "https://github.com/SableClient/tauri-plugin-notifications.git", rev = "0175b5ec58a31ab15397e981a67f47fa32254620" }
|
||||
tauri-plugin-notifications = { git = "https://github.com/SableClient/tauri-plugin-notifications.git", rev = "057d323862d815a0c7459a1f1acd5a3c08750a51" }
|
||||
|
||||
# default-features = false drops notify-rust so macOS uses the native
|
||||
# UNUserNotificationCenter backend (needs a signed .app to deliver).
|
||||
[target.'cfg(target_os = "macos")'.dependencies]
|
||||
tauri-plugin-notifications = { git = "https://github.com/SableClient/tauri-plugin-notifications.git", rev = "0175b5ec58a31ab15397e981a67f47fa32254620", default-features = false }
|
||||
tauri-plugin-notifications = { git = "https://github.com/SableClient/tauri-plugin-notifications.git", rev = "057d323862d815a0c7459a1f1acd5a3c08750a51", default-features = false }
|
||||
|
||||
[target.'cfg(not(any(target_os = "android", target_os = "ios")))'.dependencies]
|
||||
tauri-plugin-updater = { version = "2", optional = true }
|
||||
@@ -116,10 +116,10 @@ webkit2gtk = { version = "2.0", optional = true }
|
||||
[target.'cfg(target_os = "linux")'.dependencies]
|
||||
tauri-runtime-cef = { git = "https://github.com/SableClient/tauri-runtime-cef", branch = "main", optional = true }
|
||||
cef = { version = "=150.2.1", optional = true }
|
||||
libloading = "0.8"
|
||||
libloading = "0.9"
|
||||
|
||||
[target.'cfg(any(target_os = "android", target_os = "ios"))'.dependencies]
|
||||
tauri-plugin-notifications = { git = "https://github.com/SableClient/tauri-plugin-notifications.git", rev = "0175b5ec58a31ab15397e981a67f47fa32254620", features = [
|
||||
tauri-plugin-notifications = { git = "https://github.com/SableClient/tauri-plugin-notifications.git", rev = "057d323862d815a0c7459a1f1acd5a3c08750a51", features = [
|
||||
"push-notifications",
|
||||
] }
|
||||
tauri-plugin-edge-to-edge = { git = "https://github.com/SableClient/tauri-plugin-edge-to-edge.git", rev = "33c6116c27be28c06df5a9d02231ecc5fdeb93c5" }
|
||||
@@ -171,8 +171,8 @@ objc2-call-kit = { version = "0.3", default-features = false, features = [
|
||||
] }
|
||||
|
||||
[target.'cfg(target_os = "android")'.dependencies]
|
||||
tauri-plugin-android-fs = { version = "=28.4.0", features = ["legacy-storage-permission"] }
|
||||
jni = "0.21"
|
||||
tauri-plugin-android-fs = { version = "=29.0.0", features = ["legacy-storage-permission"] }
|
||||
jni = "0.22"
|
||||
|
||||
[features]
|
||||
default = ["wry", "updater"]
|
||||
|
||||
|
Before Width: | Height: | Size: 745 B After Width: | Height: | Size: 1.0 KiB |
|
Before Width: | Height: | Size: 516 B After Width: | Height: | Size: 773 B |
|
Before Width: | Height: | Size: 1.0 KiB After Width: | Height: | Size: 1.3 KiB |
|
Before Width: | Height: | Size: 1.5 KiB After Width: | Height: | Size: 1.9 KiB |
|
Before Width: | Height: | Size: 2.2 KiB After Width: | Height: | Size: 2.5 KiB |
@@ -1,7 +1,6 @@
|
||||
<?xml version="1.0" encoding="utf-8"?>
|
||||
<!-- Notification small icon: monochrome (white-on-transparent) silhouette of
|
||||
the Sable bird. Android's status bar tints this with the notification
|
||||
the Sable logo. Android's status bar tints this with the notification
|
||||
accent colour, so only the bird shape should be opaque. -->
|
||||
<bitmap xmlns:android="http://schemas.android.com/apk/res/android"
|
||||
android:src="@mipmap/ic_notification" />
|
||||
|
||||
@@ -1,7 +1,6 @@
|
||||
<?xml version="1.0" encoding="utf-8"?>
|
||||
<!-- Alias so sendNotification({ icon: 'notification_icon' }) resolves correctly.
|
||||
Points to a monochrome (white-on-transparent) silhouette of the Sable bird so
|
||||
Points to a monochrome (white-on-transparent) silhouette of the Sable logo so
|
||||
the status-bar icon renders the bird shape instead of just a filled circle. -->
|
||||
<bitmap xmlns:android="http://schemas.android.com/apk/res/android"
|
||||
android:src="@mipmap/ic_notification" />
|
||||
|
||||
|
Before Width: | Height: | Size: 508 B After Width: | Height: | Size: 1.0 KiB |
|
Before Width: | Height: | Size: 442 B After Width: | Height: | Size: 773 B |
|
Before Width: | Height: | Size: 601 B After Width: | Height: | Size: 1.3 KiB |
|
Before Width: | Height: | Size: 785 B After Width: | Height: | Size: 1.9 KiB |
|
Before Width: | Height: | Size: 969 B After Width: | Height: | Size: 2.5 KiB |
@@ -7,16 +7,22 @@ use tauri_plugin_dialog::DialogExt;
|
||||
const DEFAULT_ARCHIVE_NAME: &str = "sable-diagnostics.zip";
|
||||
|
||||
#[tauri::command]
|
||||
pub fn export_diagnostics(
|
||||
pub async fn export_diagnostics(
|
||||
app: AppHandle<crate::BrowserEngine>,
|
||||
frontend_logs: Option<String>,
|
||||
) -> Result<Option<String>, String> {
|
||||
let Some(path) = app
|
||||
.dialog()
|
||||
let (sender, receiver) = tokio::sync::oneshot::channel();
|
||||
app.dialog()
|
||||
.file()
|
||||
.set_file_name(DEFAULT_ARCHIVE_NAME)
|
||||
.add_filter("ZIP archive", &["zip"])
|
||||
.blocking_save_file()
|
||||
.save_file(move |path| {
|
||||
let _ = sender.send(path);
|
||||
});
|
||||
|
||||
let Some(path) = receiver
|
||||
.await
|
||||
.map_err(|error| format!("Save dialog did not return a result: {error}"))?
|
||||
else {
|
||||
return Ok(None);
|
||||
};
|
||||
|
||||
@@ -2,16 +2,22 @@ use tauri::AppHandle;
|
||||
use tauri_plugin_dialog::DialogExt;
|
||||
|
||||
#[tauri::command]
|
||||
pub fn save_download(
|
||||
pub async fn save_download(
|
||||
app: AppHandle<crate::BrowserEngine>,
|
||||
filename: String,
|
||||
bytes: Vec<u8>,
|
||||
) -> Result<bool, String> {
|
||||
let Some(path) = app
|
||||
.dialog()
|
||||
let (sender, receiver) = tokio::sync::oneshot::channel();
|
||||
app.dialog()
|
||||
.file()
|
||||
.set_file_name(&filename)
|
||||
.blocking_save_file()
|
||||
.save_file(move |path| {
|
||||
let _ = sender.send(path);
|
||||
});
|
||||
|
||||
let Some(path) = receiver
|
||||
.await
|
||||
.map_err(|error| format!("Save dialog did not return a result: {error}"))?
|
||||
else {
|
||||
return Ok(false);
|
||||
};
|
||||
|
||||
@@ -280,7 +280,7 @@ fn appindicator_available() -> bool {
|
||||
];
|
||||
CANDIDATES
|
||||
.iter()
|
||||
.any(|name| unsafe { libloading::Library::new(name) }.is_ok())
|
||||
.any(|name| unsafe { libloading::Library::new(*name) }.is_ok())
|
||||
}
|
||||
|
||||
pub fn create_system_tray(app: &AppHandle<crate::BrowserEngine>) -> tauri::Result<()> {
|
||||
|
||||
@@ -98,29 +98,6 @@ fn resolve_webview_permission(
|
||||
allowed
|
||||
}
|
||||
|
||||
#[cfg(all(feature = "cef", target_os = "linux"))]
|
||||
fn setup_cef_resize_workaround(
|
||||
webview_window: &tauri::WebviewWindow<BrowserEngine>,
|
||||
) -> tauri::Result<()> {
|
||||
let webview = webview_window.as_ref().clone();
|
||||
webview.set_auto_resize(false)?;
|
||||
webview_window.on_window_event(move |event| {
|
||||
let size = match event {
|
||||
tauri::WindowEvent::Resized(size) => *size,
|
||||
tauri::WindowEvent::ScaleFactorChanged { new_inner_size, .. } => *new_inner_size,
|
||||
_ => return,
|
||||
};
|
||||
|
||||
if let Err(error) = webview.set_bounds(tauri::Rect {
|
||||
position: tauri::Position::Physical(tauri::PhysicalPosition::new(0, 0)),
|
||||
size: tauri::Size::Physical(size),
|
||||
}) {
|
||||
log::warn!("failed to resize CEF webview: {error}");
|
||||
}
|
||||
});
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Routes in-app notification sounds to the native volume stream on mobile.
|
||||
/// `kind` is "notification" or "invite".
|
||||
#[cfg(any(target_os = "android", target_os = "ios"))]
|
||||
@@ -212,9 +189,6 @@ pub fn show_or_create_main_window(app: &AppHandle<crate::BrowserEngine>) -> taur
|
||||
#[cfg(not(desktop))]
|
||||
builder.build()?;
|
||||
|
||||
#[cfg(all(feature = "cef", target_os = "linux"))]
|
||||
setup_cef_resize_workaround(&webview_window)?;
|
||||
|
||||
#[cfg(desktop)]
|
||||
desktop::tray::setup_close_to_background(&webview_window);
|
||||
|
||||
@@ -304,6 +278,18 @@ pub fn run() {
|
||||
|
||||
let builder = tauri::Builder::<BrowserEngine>::new();
|
||||
|
||||
// this should always be the first
|
||||
#[cfg(desktop)]
|
||||
let builder = builder.plugin(tauri_plugin_single_instance::init(|app, _argv, _cwd| {
|
||||
let handle = app.clone();
|
||||
std::thread::spawn(move || {
|
||||
let app_handle = handle.clone();
|
||||
let _ = handle.run_on_main_thread(move || {
|
||||
let _ = show_or_create_main_window(&app_handle);
|
||||
});
|
||||
});
|
||||
}));
|
||||
|
||||
// macOS needs a standard menu (with the Edit submenu) for keyboard
|
||||
// copy/paste/select-all to work in the webview. It lives in the system menu
|
||||
// bar, so it is macOS-only to avoid an in-window menu bar elsewhere.
|
||||
@@ -332,11 +318,6 @@ pub fn run() {
|
||||
desktop::windows::window_tracking::TrackingState::new(),
|
||||
));
|
||||
|
||||
#[cfg(desktop)]
|
||||
let builder = builder.plugin(tauri_plugin_single_instance::init(|app, _argv, _cwd| {
|
||||
let _ = show_or_create_main_window(app);
|
||||
}));
|
||||
|
||||
let builder = builder.plugin(tauri_plugin_notifications::init());
|
||||
|
||||
#[cfg(all(desktop, feature = "updater"))]
|
||||
|
||||
@@ -5,7 +5,7 @@
|
||||
fn prompt_cef_permission(message: String, tx: std::sync::mpsc::Sender<bool>) {
|
||||
use gtk::glib;
|
||||
use gtk::prelude::*;
|
||||
use gtk::{ButtonsType, DialogFlags, MessageDialog, MessageType, ResponseType};
|
||||
use gtk::{ButtonsType, DialogFlags, MessageDialog, MessageType, ResponseType, WindowPosition};
|
||||
|
||||
// Non-blocking: show() + response signal instead of run().
|
||||
// dialog.run() blocks the GLib main loop, which CEF's message pump
|
||||
@@ -19,6 +19,7 @@ fn prompt_cef_permission(message: String, tx: std::sync::mpsc::Sender<bool>) {
|
||||
&message,
|
||||
);
|
||||
dialog.set_title("Permission request");
|
||||
dialog.set_position(WindowPosition::CenterAlways);
|
||||
|
||||
let tx = std::cell::RefCell::new(Some(tx));
|
||||
dialog.connect_response(move |dlg, response| {
|
||||
@@ -130,7 +131,7 @@ fn main() {
|
||||
.cloned()
|
||||
.collect();
|
||||
|
||||
if permission_kinds.is_empty() {
|
||||
if permission_kinds.is_empty() || permission_kinds.len() != request.kinds.len() {
|
||||
return responder.deny(DenyReason::NoPolicy);
|
||||
}
|
||||
|
||||
|
||||
@@ -7,19 +7,22 @@
|
||||
use std::sync::OnceLock;
|
||||
|
||||
use jni::objects::{JObject, JValue};
|
||||
use jni::{JNIEnv, JavaVM};
|
||||
use jni::strings::JNIString;
|
||||
use jni::{jni_sig, jni_str, EnvUnowned, JavaVM};
|
||||
|
||||
static JAVA_VM: OnceLock<JavaVM> = OnceLock::new();
|
||||
|
||||
// Called by MainActivity.onCreate to cache the JavaVM for later callbacks.
|
||||
#[no_mangle]
|
||||
pub extern "system" fn Java_moe_sable_client_MainActivity_nativeInitStatusBar(
|
||||
env: JNIEnv,
|
||||
mut env: EnvUnowned,
|
||||
_this: JObject,
|
||||
) {
|
||||
if let Ok(vm) = env.get_java_vm() {
|
||||
let _ = env.with_env(|env| {
|
||||
let vm = env.get_java_vm()?;
|
||||
let _ = JAVA_VM.set(vm);
|
||||
}
|
||||
Ok::<_, jni::errors::Error>(())
|
||||
});
|
||||
}
|
||||
|
||||
/// `color` is a packed ARGB int (as produced by Android's `Color`).
|
||||
@@ -52,49 +55,51 @@ pub(crate) fn play_notification_sound(kind: String) -> Result<(), String> {
|
||||
_ => 0,
|
||||
};
|
||||
let vm = JAVA_VM.get().ok_or("java vm not initialized")?;
|
||||
let mut env = vm.attach_current_thread().map_err(|e| e.to_string())?;
|
||||
|
||||
let result = env.call_static_method(
|
||||
"moe/sable/client/MainActivity",
|
||||
"playNotificationSoundNative",
|
||||
"(I)V",
|
||||
&[JValue::Int(code)],
|
||||
);
|
||||
if result.is_err() {
|
||||
let _ = env.exception_clear();
|
||||
}
|
||||
result.map_err(|e| e.to_string())?;
|
||||
|
||||
Ok(())
|
||||
vm.attach_current_thread(|env| {
|
||||
let result = env.call_static_method(
|
||||
jni_str!("moe/sable/client/MainActivity"),
|
||||
jni_str!("playNotificationSoundNative"),
|
||||
jni_sig!("(I)V"),
|
||||
&[JValue::Int(code)],
|
||||
);
|
||||
if result.is_err() {
|
||||
let _ = env.exception_clear();
|
||||
}
|
||||
result.map(|_| ())
|
||||
})
|
||||
.map_err(|e| e.to_string())
|
||||
}
|
||||
|
||||
fn call_bar_color(method: &str, color: u32) -> Result<(), String> {
|
||||
let vm = JAVA_VM.get().ok_or("java vm not initialized")?;
|
||||
let mut env = vm.attach_current_thread().map_err(|e| e.to_string())?;
|
||||
|
||||
let result = env.call_static_method(
|
||||
"moe/sable/client/MainActivity",
|
||||
method,
|
||||
"(I)V",
|
||||
&[JValue::Int(color as i32)],
|
||||
);
|
||||
if result.is_err() {
|
||||
let _ = env.exception_clear();
|
||||
}
|
||||
result.map_err(|e| e.to_string())?;
|
||||
|
||||
Ok(())
|
||||
vm.attach_current_thread(|env| {
|
||||
let result = env.call_static_method(
|
||||
jni_str!("moe/sable/client/MainActivity"),
|
||||
JNIString::new(method),
|
||||
jni_sig!("(I)V"),
|
||||
&[JValue::Int(color as i32)],
|
||||
);
|
||||
if result.is_err() {
|
||||
let _ = env.exception_clear();
|
||||
}
|
||||
result.map(|_| ())
|
||||
})
|
||||
.map_err(|e| e.to_string())
|
||||
}
|
||||
|
||||
fn call_static_method(method: &str) -> Result<(), String> {
|
||||
let vm = JAVA_VM.get().ok_or("java vm not initialized")?;
|
||||
let mut env = vm.attach_current_thread().map_err(|e| e.to_string())?;
|
||||
|
||||
let result = env.call_static_method("moe/sable/client/MainActivity", method, "()V", &[]);
|
||||
if result.is_err() {
|
||||
let _ = env.exception_clear();
|
||||
}
|
||||
result.map_err(|e| e.to_string())?;
|
||||
|
||||
Ok(())
|
||||
vm.attach_current_thread(|env| {
|
||||
let result = env.call_static_method(
|
||||
jni_str!("moe/sable/client/MainActivity"),
|
||||
JNIString::new(method),
|
||||
jni_sig!("()V"),
|
||||
&[],
|
||||
);
|
||||
if result.is_err() {
|
||||
let _ = env.exception_clear();
|
||||
}
|
||||
result.map(|_| ())
|
||||
})
|
||||
.map_err(|e| e.to_string())
|
||||
}
|
||||
@@ -1,7 +1,7 @@
|
||||
use std::{
|
||||
collections::HashMap,
|
||||
fs,
|
||||
io::Read,
|
||||
io::{Read, Seek, SeekFrom},
|
||||
path::{Path, PathBuf},
|
||||
sync::{
|
||||
atomic::{AtomicBool, AtomicU64, Ordering},
|
||||
@@ -50,6 +50,9 @@ const MAX_CONCURRENT_DOWNLOAD_REQUESTS: usize = 6;
|
||||
const SESSION_WAIT: Duration = Duration::from_secs(5);
|
||||
const SESSION_REFRESH_WAIT: Duration = Duration::from_millis(2500);
|
||||
const MAX_CACHE_BYTES: u64 = 512 * 1024 * 1024;
|
||||
// WRY's Android adapter copies custom-protocol bodies into a JNI byte array, so range
|
||||
// responses must stay bounded even when WebView asks for the rest of a large video.
|
||||
const MAX_RANGE_CHUNK: u64 = 2 * 1024 * 1024;
|
||||
// Short: a 4xx stops being true once an unreachable remote server comes back.
|
||||
const NEGATIVE_CACHE_TTL: Duration = Duration::from_secs(600);
|
||||
const MAX_NEGATIVE_CACHE_ENTRIES: usize = 512;
|
||||
@@ -475,9 +478,10 @@ pub fn respond<R: Runtime>(
|
||||
.and_then(|value| value.to_str().ok())
|
||||
.map(str::to_owned)
|
||||
};
|
||||
let range = header_value(header::RANGE);
|
||||
let origin = header_value(header::ORIGIN);
|
||||
tauri::async_runtime::spawn(async move {
|
||||
let mut response = handle_request(&app, uri)
|
||||
let mut response = handle_request(&app, uri, range)
|
||||
.await
|
||||
.unwrap_or_else(error_response);
|
||||
apply_cors_headers(&mut response, origin.as_deref());
|
||||
@@ -488,6 +492,7 @@ pub fn respond<R: Runtime>(
|
||||
async fn handle_request<R: Runtime>(
|
||||
app: &AppHandle<R>,
|
||||
uri: Uri,
|
||||
range: Option<String>,
|
||||
) -> Result<Response<Vec<u8>>, StatusCode> {
|
||||
let target = percent_encoding::percent_decode_str(uri.path().trim_start_matches('/'))
|
||||
.decode_utf8()
|
||||
@@ -529,12 +534,16 @@ async fn handle_request<R: Runtime>(
|
||||
let (content_type, in_memory_body, disk_path) =
|
||||
ensure_cached(&state, &session, &key, media_url, dir, temp_dir).await?;
|
||||
|
||||
match in_memory_body {
|
||||
Some(body) => {
|
||||
match (range, in_memory_body) {
|
||||
(Some(range_header), Some(body)) => {
|
||||
Ok(serve_range_memory(&body, &content_type, &range_header))
|
||||
}
|
||||
(Some(range_header), None) => serve_range(disk_path, content_type, range_header).await,
|
||||
(None, Some(body)) => {
|
||||
let vec_body = Arc::try_unwrap(body).unwrap_or_else(|b| (*b).clone());
|
||||
Ok(ok_response(vec_body, &content_type))
|
||||
}
|
||||
None => Ok(ok_response(read_full(disk_path).await?, &content_type)),
|
||||
(None, None) => Ok(ok_response(read_full(disk_path).await?, &content_type)),
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1087,6 +1096,105 @@ async fn read_full(body_path: PathBuf) -> Result<Vec<u8>, StatusCode> {
|
||||
.map_err(|_| StatusCode::INTERNAL_SERVER_ERROR)
|
||||
}
|
||||
|
||||
async fn serve_range(
|
||||
body_path: PathBuf,
|
||||
content_type: String,
|
||||
range_header: String,
|
||||
) -> Result<Response<Vec<u8>>, StatusCode> {
|
||||
tokio::task::spawn_blocking(move || {
|
||||
let mut file = fs::File::open(&body_path).map_err(|_| StatusCode::INTERNAL_SERVER_ERROR)?;
|
||||
let total = file
|
||||
.metadata()
|
||||
.map_err(|_| StatusCode::INTERNAL_SERVER_ERROR)?
|
||||
.len();
|
||||
let (start, end) = match select_range(&range_header, total) {
|
||||
RangeSelection::Partial { start, end } => (start, end),
|
||||
RangeSelection::Ignore => {
|
||||
let mut body = Vec::new();
|
||||
file.read_to_end(&mut body)
|
||||
.map_err(|_| StatusCode::INTERNAL_SERVER_ERROR)?;
|
||||
return Ok(ok_response(body, &content_type));
|
||||
}
|
||||
RangeSelection::Unsatisfiable => return Ok(range_not_satisfiable(total)),
|
||||
};
|
||||
let length = end - start + 1;
|
||||
let mut body = vec![0; length as usize];
|
||||
file.seek(SeekFrom::Start(start))
|
||||
.map_err(|_| StatusCode::INTERNAL_SERVER_ERROR)?;
|
||||
file.read_exact(&mut body)
|
||||
.map_err(|_| StatusCode::INTERNAL_SERVER_ERROR)?;
|
||||
Ok(partial_response(body, &content_type, start, end, total))
|
||||
})
|
||||
.await
|
||||
.map_err(|_| StatusCode::INTERNAL_SERVER_ERROR)?
|
||||
}
|
||||
|
||||
fn serve_range_memory(body: &[u8], content_type: &str, range_header: &str) -> Response<Vec<u8>> {
|
||||
let total = body.len() as u64;
|
||||
let (start, end) = match select_range(range_header, total) {
|
||||
RangeSelection::Partial { start, end } => (start, end),
|
||||
RangeSelection::Ignore => return ok_response(body.to_vec(), content_type),
|
||||
RangeSelection::Unsatisfiable => return range_not_satisfiable(total),
|
||||
};
|
||||
partial_response(
|
||||
body[start as usize..=end as usize].to_vec(),
|
||||
content_type,
|
||||
start,
|
||||
end,
|
||||
total,
|
||||
)
|
||||
}
|
||||
|
||||
enum RangeSelection {
|
||||
Partial { start: u64, end: u64 },
|
||||
Ignore,
|
||||
Unsatisfiable,
|
||||
}
|
||||
|
||||
fn select_range(range_header: &str, total: u64) -> RangeSelection {
|
||||
if total == 0 {
|
||||
return RangeSelection::Unsatisfiable;
|
||||
}
|
||||
let Some(spec) = range_header.strip_prefix("bytes=") else {
|
||||
return RangeSelection::Unsatisfiable;
|
||||
};
|
||||
if spec.contains(',') {
|
||||
return RangeSelection::Ignore;
|
||||
}
|
||||
let Some((start, end)) = spec.trim().split_once('-') else {
|
||||
return RangeSelection::Unsatisfiable;
|
||||
};
|
||||
let (start, end) = if start.is_empty() {
|
||||
let Ok(suffix) = end.parse::<u64>() else {
|
||||
return RangeSelection::Unsatisfiable;
|
||||
};
|
||||
if suffix == 0 {
|
||||
return RangeSelection::Unsatisfiable;
|
||||
}
|
||||
let length = suffix.min(total).min(MAX_RANGE_CHUNK);
|
||||
(total - length, total - 1)
|
||||
} else {
|
||||
let Ok(start) = start.parse::<u64>() else {
|
||||
return RangeSelection::Unsatisfiable;
|
||||
};
|
||||
let requested_end = if end.is_empty() {
|
||||
total - 1
|
||||
} else {
|
||||
let Ok(end) = end.parse::<u64>() else {
|
||||
return RangeSelection::Unsatisfiable;
|
||||
};
|
||||
end.min(total - 1)
|
||||
};
|
||||
let end = requested_end.min(start.saturating_add(MAX_RANGE_CHUNK - 1));
|
||||
(start, end)
|
||||
};
|
||||
if start <= end && start < total {
|
||||
RangeSelection::Partial { start, end }
|
||||
} else {
|
||||
RangeSelection::Unsatisfiable
|
||||
}
|
||||
}
|
||||
|
||||
// Trim oldest-first when the cache exceeds its byte budget.
|
||||
fn evict_directory_if_needed(dir: &Path, max_bytes: u64) {
|
||||
let Ok(entries) = fs::read_dir(dir) else {
|
||||
@@ -1123,7 +1231,7 @@ fn evict_directory_if_needed(dir: &Path, max_bytes: u64) {
|
||||
}
|
||||
|
||||
// Shared response headers. Media is content-addressed and the URL is session-scoped, so
|
||||
// it is safe to let the webview cache it as immutable.
|
||||
// it is safe to let the webview cache it as immutable and advertise byte-range support.
|
||||
fn media_response_builder(status: StatusCode, content_type: &str) -> ResponseBuilder {
|
||||
let cache_control = if content_type == "application/octet-stream" {
|
||||
"no-store"
|
||||
@@ -1133,6 +1241,7 @@ fn media_response_builder(status: StatusCode, content_type: &str) -> ResponseBui
|
||||
Response::builder()
|
||||
.status(status)
|
||||
.header(header::CONTENT_TYPE, content_type)
|
||||
.header(header::ACCEPT_RANGES, "bytes")
|
||||
.header(header::CACHE_CONTROL, cache_control)
|
||||
.header(header::X_CONTENT_TYPE_OPTIONS, "nosniff")
|
||||
.header(
|
||||
@@ -1149,6 +1258,43 @@ fn ok_response(body: Vec<u8>, content_type: &str) -> Response<Vec<u8>> {
|
||||
.expect("failed to build media response")
|
||||
}
|
||||
|
||||
fn partial_response(
|
||||
body: Vec<u8>,
|
||||
content_type: &str,
|
||||
start: u64,
|
||||
end: u64,
|
||||
total: u64,
|
||||
) -> Response<Vec<u8>> {
|
||||
let content_length = body.len();
|
||||
media_response_builder(StatusCode::PARTIAL_CONTENT, content_type)
|
||||
.header(header::CONTENT_LENGTH, content_length)
|
||||
.header(
|
||||
header::CONTENT_RANGE,
|
||||
format!("bytes {start}-{end}/{total}"),
|
||||
)
|
||||
.body(body)
|
||||
.expect("failed to build partial media response")
|
||||
}
|
||||
|
||||
fn range_not_satisfiable(total: u64) -> Response<Vec<u8>> {
|
||||
let mut response = error_response(StatusCode::RANGE_NOT_SATISFIABLE);
|
||||
let headers = response.headers_mut();
|
||||
headers.insert(
|
||||
header::CONTENT_RANGE,
|
||||
header::HeaderValue::from_str(&format!("bytes */{total}"))
|
||||
.expect("valid 416 content range"),
|
||||
);
|
||||
headers.insert(
|
||||
header::CONTENT_LENGTH,
|
||||
header::HeaderValue::from_static("0"),
|
||||
);
|
||||
headers.insert(
|
||||
header::ACCEPT_RANGES,
|
||||
header::HeaderValue::from_static("bytes"),
|
||||
);
|
||||
response
|
||||
}
|
||||
|
||||
fn session_unavailable_response() -> Response<Vec<u8>> {
|
||||
Response::builder()
|
||||
.status(StatusCode::SERVICE_UNAVAILABLE)
|
||||
@@ -1209,6 +1355,13 @@ mod tests {
|
||||
|
||||
static TEST_CACHE_ID: AtomicU64 = AtomicU64::new(0);
|
||||
|
||||
fn selected_range(header: &str, total: u64) -> Option<(u64, u64)> {
|
||||
match super::select_range(header, total) {
|
||||
super::RangeSelection::Partial { start, end } => Some((start, end)),
|
||||
_ => None,
|
||||
}
|
||||
}
|
||||
|
||||
fn test_session(origin: &str, token: &str, scope: &str, generation: u64) -> MediaSession {
|
||||
MediaSession {
|
||||
origin: origin.to_owned(),
|
||||
@@ -1725,6 +1878,168 @@ mod tests {
|
||||
response.headers().get(header::CACHE_CONTROL).unwrap(),
|
||||
"private, max-age=31536000, immutable"
|
||||
);
|
||||
assert_eq!(
|
||||
response.headers().get(header::ACCEPT_RANGES).unwrap(),
|
||||
"bytes"
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn select_range_supports_video_metadata_and_seek_requests() {
|
||||
assert_eq!(selected_range("bytes=0-499", 1000), Some((0, 499)));
|
||||
assert_eq!(selected_range("bytes=500-", 1000), Some((500, 999)));
|
||||
assert_eq!(selected_range("bytes=-200", 1000), Some((800, 999)));
|
||||
assert_eq!(selected_range("bytes=990-5000", 1000), Some((990, 999)));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn open_ended_ranges_are_capped_from_the_requested_offset() {
|
||||
let total = super::MAX_RANGE_CHUNK * 2 + 100;
|
||||
assert_eq!(
|
||||
selected_range("bytes=0-", total),
|
||||
Some((0, super::MAX_RANGE_CHUNK - 1))
|
||||
);
|
||||
assert_eq!(
|
||||
selected_range(&format!("bytes={}-", super::MAX_RANGE_CHUNK), total),
|
||||
Some((super::MAX_RANGE_CHUNK, super::MAX_RANGE_CHUNK * 2 - 1))
|
||||
);
|
||||
assert_eq!(
|
||||
selected_range(&format!("bytes={}-", super::MAX_RANGE_CHUNK * 2), total),
|
||||
Some((super::MAX_RANGE_CHUNK * 2, total - 1))
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn malformed_or_unsatisfiable_range_is_rejected() {
|
||||
for range in [
|
||||
"bytes=1000-1001",
|
||||
"bytes=500-400",
|
||||
"bytes=abc-def",
|
||||
"items=0-1",
|
||||
] {
|
||||
assert!(
|
||||
matches!(
|
||||
super::select_range(range, 1000),
|
||||
super::RangeSelection::Unsatisfiable
|
||||
),
|
||||
"{range}"
|
||||
);
|
||||
}
|
||||
assert!(matches!(
|
||||
super::select_range("bytes=0-0", 0),
|
||||
super::RangeSelection::Unsatisfiable
|
||||
));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn multi_range_requests_fall_back_to_the_full_response() {
|
||||
let body = [1_u8, 2, 3];
|
||||
let response = super::serve_range_memory(&body, "video/mp4", "bytes=0-0,2-2");
|
||||
|
||||
assert_eq!(response.status(), StatusCode::OK);
|
||||
assert_eq!(response.body(), &body);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn in_memory_ranges_are_partial_and_capped() {
|
||||
let body: Vec<u8> = (0..200u8).collect();
|
||||
let response = super::serve_range_memory(&body, "video/mp4", "bytes=10-19");
|
||||
assert_eq!(response.status(), StatusCode::PARTIAL_CONTENT);
|
||||
assert_eq!(response.body(), &body[10..=19]);
|
||||
assert_eq!(
|
||||
response.headers().get(header::CONTENT_RANGE).unwrap(),
|
||||
"bytes 10-19/200"
|
||||
);
|
||||
|
||||
let body = vec![7_u8; (super::MAX_RANGE_CHUNK * 2) as usize];
|
||||
let response = super::serve_range_memory(&body, "video/mp4", "bytes=0-");
|
||||
assert_eq!(response.body().len() as u64, super::MAX_RANGE_CHUNK);
|
||||
assert_eq!(
|
||||
response
|
||||
.headers()
|
||||
.get(header::CONTENT_RANGE)
|
||||
.unwrap()
|
||||
.to_str()
|
||||
.unwrap(),
|
||||
format!("bytes 0-{}/{}", super::MAX_RANGE_CHUNK - 1, body.len())
|
||||
);
|
||||
|
||||
let requested_suffix = super::MAX_RANGE_CHUNK + 100;
|
||||
let response =
|
||||
super::serve_range_memory(&body, "video/mp4", &format!("bytes=-{requested_suffix}"));
|
||||
assert_eq!(response.body().len() as u64, super::MAX_RANGE_CHUNK);
|
||||
let expected = format!(
|
||||
"bytes {}-{}/{}",
|
||||
body.len() as u64 - super::MAX_RANGE_CHUNK,
|
||||
body.len() - 1,
|
||||
body.len()
|
||||
);
|
||||
assert_eq!(
|
||||
response
|
||||
.headers()
|
||||
.get(header::CONTENT_RANGE)
|
||||
.unwrap()
|
||||
.to_str()
|
||||
.unwrap(),
|
||||
expected
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn unsatisfiable_ranges_are_not_cacheable() {
|
||||
let response = super::range_not_satisfiable(1000);
|
||||
assert_eq!(response.status(), StatusCode::RANGE_NOT_SATISFIABLE);
|
||||
assert_eq!(
|
||||
response.headers().get(header::CONTENT_RANGE).unwrap(),
|
||||
"bytes */1000"
|
||||
);
|
||||
assert_eq!(
|
||||
response.headers().get(header::CACHE_CONTROL).unwrap(),
|
||||
"no-store"
|
||||
);
|
||||
assert_eq!(response.headers().get(header::CONTENT_LENGTH).unwrap(), "0");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn partial_responses_include_webview_range_metadata() {
|
||||
let response = super::serve_range_memory(&[0_u8; 100], "video/mp4", "bytes=10-19");
|
||||
|
||||
assert_eq!(response.status(), StatusCode::PARTIAL_CONTENT);
|
||||
assert_eq!(
|
||||
response.headers().get(header::CONTENT_TYPE).unwrap(),
|
||||
"video/mp4"
|
||||
);
|
||||
assert_eq!(
|
||||
response.headers().get(header::CONTENT_LENGTH).unwrap(),
|
||||
"10"
|
||||
);
|
||||
assert_eq!(
|
||||
response.headers().get(header::CONTENT_RANGE).unwrap(),
|
||||
"bytes 10-19/100"
|
||||
);
|
||||
assert_eq!(
|
||||
response.headers().get(header::ACCEPT_RANGES).unwrap(),
|
||||
"bytes"
|
||||
);
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn disk_range_reads_only_the_requested_cached_bytes() {
|
||||
let path = std::env::temp_dir().join(format!(
|
||||
"sable-media-range-test-{}-{}",
|
||||
std::process::id(),
|
||||
TEST_CACHE_ID.fetch_add(1, std::sync::atomic::Ordering::Relaxed)
|
||||
));
|
||||
let body: Vec<u8> = (0..200u8).collect();
|
||||
fs::write(&path, &body).unwrap();
|
||||
|
||||
let response = super::serve_range(path.clone(), "video/mp4".into(), "bytes=10-19".into())
|
||||
.await
|
||||
.unwrap();
|
||||
fs::remove_file(path).ok();
|
||||
|
||||
assert_eq!(response.status(), StatusCode::PARTIAL_CONTENT);
|
||||
assert_eq!(response.body(), &body[10..=19]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
|
||||
@@ -11,20 +11,20 @@ pub fn init() -> Option<sentry::ClientInitGuard> {
|
||||
let environment = option_env!("SENTRY_ENVIRONMENT");
|
||||
let release = option_env!("SENTRY_APP_VERSION").map(|v| format!("sable@{v}"));
|
||||
|
||||
let guard = sentry::init(sentry::ClientOptions {
|
||||
dsn: dsn.parse().ok(),
|
||||
release: release.map(Into::into),
|
||||
environment: environment.map(Into::into),
|
||||
send_default_pii: false,
|
||||
before_send: Some(std::sync::Arc::new(|event: Event<'static>| {
|
||||
if CONSENT.load(Ordering::Relaxed) {
|
||||
Some(event)
|
||||
} else {
|
||||
None
|
||||
}
|
||||
})),
|
||||
..Default::default()
|
||||
});
|
||||
// ClientOptions is #[non_exhaustive]; mutate a default instance instead.
|
||||
let mut options = sentry::ClientOptions::default();
|
||||
options.dsn = dsn.parse().ok();
|
||||
options.release = release.map(Into::into);
|
||||
options.environment = environment.map(Into::into);
|
||||
options.send_default_pii = false;
|
||||
options.before_send = Some(std::sync::Arc::new(|event: Event<'static>| {
|
||||
if CONSENT.load(Ordering::Relaxed) {
|
||||
Some(event)
|
||||
} else {
|
||||
None
|
||||
}
|
||||
}));
|
||||
let guard = sentry::init(options);
|
||||
|
||||
Some(guard)
|
||||
}
|
||||
|
||||
@@ -6,16 +6,18 @@ import { resolveSection } from '$pages/pathUtils';
|
||||
import { HOME_ROOM_PATH, DIRECT_ROOM_PATH, SPACE_ROOM_PATH } from '$pages/paths';
|
||||
import { lastVisitedRoomAtom } from '$state/room/lastRoom';
|
||||
import { isRoomAlias, isRoomId } from '$utils/matrix';
|
||||
import { useAndroidBackHandler } from '$utils/androidBack';
|
||||
|
||||
type BackRouteHandlerProps = {
|
||||
children: (onBack: () => void) => ReactNode;
|
||||
};
|
||||
export function BackRouteHandler({ children }: BackRouteHandlerProps) {
|
||||
|
||||
export function useBackRoute(): () => void {
|
||||
const navigate = useNavigate();
|
||||
const location = useLocation();
|
||||
const setLastRoom = useSetAtom(lastVisitedRoomAtom);
|
||||
|
||||
const goBack = useCallback(() => {
|
||||
return useCallback(() => {
|
||||
const section = resolveSection(location.pathname);
|
||||
if (!section) return;
|
||||
|
||||
@@ -32,6 +34,14 @@ export function BackRouteHandler({ children }: BackRouteHandlerProps) {
|
||||
|
||||
navigate(section.listPath);
|
||||
}, [navigate, location, setLastRoom]);
|
||||
}
|
||||
|
||||
export function BackRouteHandler({ children }: BackRouteHandlerProps) {
|
||||
const goBack = useBackRoute();
|
||||
useAndroidBackHandler(() => {
|
||||
goBack();
|
||||
return true;
|
||||
});
|
||||
|
||||
return children(goBack);
|
||||
}
|
||||
@@ -0,0 +1,66 @@
|
||||
import { fireEvent, render, screen, waitFor } from '@testing-library/react';
|
||||
import { beforeEach, describe, expect, it, vi } from 'vitest';
|
||||
import type { CryptoApi } from '$types/matrix-sdk';
|
||||
import type { SecretStorageKeyContent } from '$types/matrix/accountData';
|
||||
import { ManualVerificationTile } from './ManualVerification';
|
||||
|
||||
const decodeRecoveryKey = vi.hoisted(() => vi.fn<(key: string) => Uint8Array>());
|
||||
const checkKey = vi.hoisted(() => vi.fn<() => Promise<boolean>>());
|
||||
const storePrivateKey = vi.hoisted(() => vi.fn<() => void>());
|
||||
const processDeviceLists = vi.hoisted(() => vi.fn<() => Promise<void>>());
|
||||
const bootstrapCrossSigning = vi.hoisted(() => vi.fn<() => Promise<void>>());
|
||||
const bootstrapSecretStorage = vi.hoisted(() => vi.fn<() => Promise<void>>());
|
||||
const loadSessionBackupPrivateKeyFromSecretStorage = vi.hoisted(() => vi.fn<() => Promise<void>>());
|
||||
|
||||
vi.mock('$types/matrix-sdk', () => ({ decodeRecoveryKey }));
|
||||
vi.mock('$client/secretStorageKeys', () => ({ storePrivateKey }));
|
||||
vi.mock('$hooks/useMatrixClient', () => ({
|
||||
useMatrixClient: () => ({
|
||||
getSafeUserId: () => '@me:example.org',
|
||||
secretStorage: { checkKey },
|
||||
getCrypto: () =>
|
||||
({
|
||||
processDeviceLists,
|
||||
bootstrapCrossSigning,
|
||||
bootstrapSecretStorage,
|
||||
loadSessionBackupPrivateKeyFromSecretStorage,
|
||||
}) as unknown as CryptoApi,
|
||||
}),
|
||||
}));
|
||||
|
||||
const KEY_ID = 'key-id';
|
||||
const KEY_CONTENT = { algorithm: 'm.secret_storage.v1.aes-hmac-sha2' } as SecretStorageKeyContent;
|
||||
const recoveryKey = new Uint8Array([1, 2, 3]);
|
||||
|
||||
const submitRecoveryKey = (value: string) => {
|
||||
const input = document.querySelector('form input') as HTMLInputElement;
|
||||
fireEvent.change(input, { target: { value } });
|
||||
const form = input.closest('form') as HTMLFormElement;
|
||||
Object.defineProperty(form, input.name, { value: input, configurable: true });
|
||||
fireEvent.submit(form);
|
||||
};
|
||||
|
||||
describe('ManualVerificationTile', () => {
|
||||
beforeEach(() => {
|
||||
vi.clearAllMocks();
|
||||
decodeRecoveryKey.mockReturnValue(recoveryKey);
|
||||
checkKey.mockResolvedValue(true);
|
||||
processDeviceLists.mockResolvedValue(undefined);
|
||||
bootstrapCrossSigning.mockResolvedValue(undefined);
|
||||
bootstrapSecretStorage.mockResolvedValue(undefined);
|
||||
loadSessionBackupPrivateKeyFromSecretStorage.mockResolvedValue(undefined);
|
||||
});
|
||||
|
||||
it('refreshes cross-signing public keys before importing the recovery key', async () => {
|
||||
render(
|
||||
<ManualVerificationTile secretStorageKeyId={KEY_ID} secretStorageKeyContent={KEY_CONTENT} />
|
||||
);
|
||||
|
||||
submitRecoveryKey('valid-key');
|
||||
|
||||
await waitFor(() => expect(screen.getByText('Device verified!')).toBeInTheDocument());
|
||||
expect(storePrivateKey).toHaveBeenCalledWith(KEY_ID, recoveryKey);
|
||||
expect(processDeviceLists).toHaveBeenCalledWith({ changed: ['@me:example.org'] });
|
||||
expect(bootstrapCrossSigning).toHaveBeenCalledAfter(processDeviceLists);
|
||||
});
|
||||
});
|
||||
@@ -5,6 +5,7 @@ import { Box, Text, Chip, PopOut, Menu, config, MenuItem, color } from 'folds';
|
||||
import { CaretDown, sizedIcon } from '$components/icons/phosphor';
|
||||
import FocusTrap from 'focus-trap-react';
|
||||
import type { SecretStorageKeyContent } from '$types/matrix/accountData';
|
||||
import type { CryptoBackend } from '$types/matrix-sdk';
|
||||
import { storePrivateKey } from '$client/secretStorageKeys';
|
||||
import { stopPropagation } from '$utils/keyboard';
|
||||
import { useMatrixClient } from '$hooks/useMatrixClient';
|
||||
@@ -117,13 +118,14 @@ export function ManualVerificationTile({
|
||||
|
||||
const verifyAndRestoreBackup = useCallback(
|
||||
async (recoveryKey: Uint8Array) => {
|
||||
const crypto = mx.getCrypto();
|
||||
const crypto = mx.getCrypto() as CryptoBackend | undefined;
|
||||
if (!crypto) {
|
||||
throw new Error('Unexpected Error! Crypto object not found.');
|
||||
}
|
||||
|
||||
storePrivateKey(secretStorageKeyId, recoveryKey);
|
||||
|
||||
await crypto.processDeviceLists({ changed: [mx.getSafeUserId()] });
|
||||
await crypto.bootstrapCrossSigning({});
|
||||
await crypto.bootstrapSecretStorage({});
|
||||
|
||||
|
||||
@@ -54,6 +54,12 @@ import { PollEvent } from './message/PollEvent';
|
||||
import { M_POLL_START, M_TEXT } from 'matrix-js-sdk';
|
||||
import type { IImageInfo, IGalleryContent } from '$types/matrix/common';
|
||||
import { GALLERY_MSGTYPE } from '$types/matrix/common';
|
||||
import {
|
||||
convertBeeperFormatToOurPerMessageProfile,
|
||||
type PerMessageProfileBeeperFormat,
|
||||
stripPerMessageProfileFormattedBody,
|
||||
stripPerMessageProfilePlainBody,
|
||||
} from '$hooks/usePerMessageProfile';
|
||||
|
||||
type RenderMessageContentProps = {
|
||||
displayName: string;
|
||||
@@ -339,6 +345,21 @@ function RenderMessageContentInternal({
|
||||
}
|
||||
|
||||
if (msgType === (MsgType.Emote as string)) {
|
||||
const beeperProfile = content['com.beeper.per_message_profile'] as
|
||||
| PerMessageProfileBeeperFormat
|
||||
| undefined;
|
||||
const pmp = beeperProfile
|
||||
? convertBeeperFormatToOurPerMessageProfile(beeperProfile)
|
||||
: undefined;
|
||||
|
||||
const strippedContent = pmp
|
||||
? {
|
||||
...content,
|
||||
formatted_body: stripPerMessageProfileFormattedBody(content['formatted_body'] as string),
|
||||
body: stripPerMessageProfilePlainBody(content['body'] as string),
|
||||
}
|
||||
: content;
|
||||
|
||||
if ((content as { 'fyi.cisnt.headpat'?: boolean })['fyi.cisnt.headpat']) {
|
||||
return (
|
||||
<MCuteEvent
|
||||
@@ -352,9 +373,9 @@ function RenderMessageContentInternal({
|
||||
}
|
||||
return (
|
||||
<MEmote
|
||||
displayName={displayName}
|
||||
displayName={pmp?.displayname ?? displayName}
|
||||
edited={edited}
|
||||
content={content}
|
||||
content={strippedContent}
|
||||
renderBody={renderBody}
|
||||
renderUrlsPreview={messageUrlsPreview}
|
||||
renderBundledPreviews={messageBundlePreview}
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
import type {
|
||||
ChangeEventHandler,
|
||||
ChangeEvent,
|
||||
FocusEventHandler,
|
||||
MouseEventHandler,
|
||||
ReactNode,
|
||||
@@ -455,6 +455,7 @@ type EmojiBoardProps = {
|
||||
onCustomEmojiSelect?: (mxc: string, shortcode: string) => void;
|
||||
onStickerSelect?: (mxc: string, shortcode: string, label: string) => void;
|
||||
onGifSelect?: (gif: GifData, spoiler?: boolean) => void;
|
||||
initialGifSearch?: string;
|
||||
allowTextCustomEmoji?: boolean;
|
||||
addToRecentEmoji?: boolean;
|
||||
isFullWidth?: boolean;
|
||||
@@ -474,6 +475,7 @@ export function EmojiBoard({
|
||||
onCustomEmojiSelect,
|
||||
onStickerSelect,
|
||||
onGifSelect,
|
||||
initialGifSearch,
|
||||
allowTextCustomEmoji,
|
||||
addToRecentEmoji = true,
|
||||
isFullWidth,
|
||||
@@ -525,7 +527,8 @@ export function EmojiBoard({
|
||||
loading: gifsLoading,
|
||||
error: gifsError,
|
||||
searchGifs,
|
||||
} = useGifSearch(favoriteGifs, showGifPicker, gifSearch);
|
||||
cancelSearch: cancelGifSearch,
|
||||
} = useGifSearch(favoriteGifs, showGifPicker && gifTab, gifSearch);
|
||||
const [emojiGroupItems, stickerGroupItems, gifGroupItems] = useGroups(tab, imagePacks, gifs);
|
||||
const [showFavoritesOnly, setShowFavoritesOnly] = useState(true);
|
||||
const groupsByTab = {
|
||||
@@ -553,9 +556,9 @@ export function EmojiBoard({
|
||||
const groups = groupsByTab[tab];
|
||||
const renderItem = useItemRenderer(tab, saveStickerEmojiBandwidth);
|
||||
|
||||
const handleOnChange: ChangeEventHandler<HTMLInputElement> = useDebounce(
|
||||
const handleOnChange = useDebounce(
|
||||
useCallback(
|
||||
(evt) => {
|
||||
(evt: ChangeEvent<HTMLInputElement>) => {
|
||||
const term = evt.target.value;
|
||||
if (tab === EmojiBoardTab.Gif) {
|
||||
if (term) {
|
||||
@@ -563,6 +566,7 @@ export function EmojiBoard({
|
||||
searchGifs(term);
|
||||
} else {
|
||||
setShowFavoritesOnly(true);
|
||||
cancelGifSearch();
|
||||
resetGifSearch();
|
||||
}
|
||||
} else if (term) {
|
||||
@@ -571,11 +575,25 @@ export function EmojiBoard({
|
||||
resetEmojiSearch();
|
||||
}
|
||||
},
|
||||
[emojiSearch, resetEmojiSearch, searchGifs, resetGifSearch, tab]
|
||||
[cancelGifSearch, emojiSearch, resetEmojiSearch, searchGifs, resetGifSearch, tab]
|
||||
),
|
||||
{ wait: 200 }
|
||||
);
|
||||
|
||||
useEffect(() => {
|
||||
if (!gifTab || initialGifSearch === undefined) return;
|
||||
setShowFavoritesOnly(initialGifSearch.length === 0);
|
||||
if (initialGifSearch) searchGifs(initialGifSearch);
|
||||
else resetGifSearch();
|
||||
}, [gifTab, initialGifSearch, searchGifs, resetGifSearch]);
|
||||
|
||||
useEffect(() => {
|
||||
if (!showGifPicker || !gifTab) {
|
||||
handleOnChange.cancel();
|
||||
cancelGifSearch();
|
||||
}
|
||||
}, [cancelGifSearch, gifTab, handleOnChange, showGifPicker]);
|
||||
|
||||
const contentScrollRef = useRef<HTMLDivElement>(null);
|
||||
const virtualBaseRef = useRef<HTMLDivElement>(null);
|
||||
const virtualizer = useVirtualizer({
|
||||
@@ -677,10 +695,11 @@ export function EmojiBoard({
|
||||
<Box direction="Column" gap="200">
|
||||
{onTabChange && <EmojiBoardTabs tab={tab} onTabChange={onTabChange} />}
|
||||
<SearchInput
|
||||
key={tab}
|
||||
key={gifTab ? `${tab}-${initialGifSearch ?? ''}` : tab}
|
||||
query={emojiResult?.query}
|
||||
onChange={handleOnChange}
|
||||
tab={tab}
|
||||
defaultValue={gifTab ? initialGifSearch : undefined}
|
||||
allowTextCustomEmoji={allowTextCustomEmoji}
|
||||
onTextCustomEmojiSelect={handleTextCustomEmojiSelect}
|
||||
/>
|
||||
|
||||
@@ -7,6 +7,7 @@ import { EmojiBoardTab } from '../types';
|
||||
|
||||
type SearchInputProps = {
|
||||
query?: string;
|
||||
defaultValue?: string;
|
||||
onChange: ChangeEventHandler<HTMLInputElement>;
|
||||
allowTextCustomEmoji?: boolean;
|
||||
onTextCustomEmojiSelect?: (text: string) => void;
|
||||
@@ -14,6 +15,7 @@ type SearchInputProps = {
|
||||
};
|
||||
export function SearchInput({
|
||||
query,
|
||||
defaultValue,
|
||||
onChange,
|
||||
allowTextCustomEmoji,
|
||||
onTextCustomEmojiSelect,
|
||||
@@ -40,6 +42,7 @@ export function SearchInput({
|
||||
: 'Search'
|
||||
}
|
||||
maxLength={50}
|
||||
defaultValue={defaultValue}
|
||||
after={
|
||||
allowTextCustomEmoji && query && tab !== EmojiBoardTab.Gif ? (
|
||||
<Chip
|
||||
|
||||
@@ -0,0 +1,134 @@
|
||||
import { act, renderHook } from '@testing-library/react';
|
||||
import { afterEach, describe, expect, it, vi } from 'vitest';
|
||||
import { useGifSearch } from './useGifSearch';
|
||||
|
||||
const { fetchMock } = vi.hoisted(() => ({
|
||||
fetchMock: vi.fn<(input: string, init?: RequestInit) => Promise<Response>>(),
|
||||
}));
|
||||
|
||||
vi.mock('$utils/fetch', () => ({ fetch: fetchMock }));
|
||||
vi.mock('$hooks/useClientConfig', () => ({
|
||||
useClientConfig: () => ({ gifs: { klipyApiKey: 'test-key' } }),
|
||||
}));
|
||||
|
||||
type Deferred<T> = {
|
||||
promise: Promise<T>;
|
||||
resolve: (value: T) => void;
|
||||
reject: (reason?: unknown) => void;
|
||||
};
|
||||
|
||||
const deferred = <T,>(): Deferred<T> => {
|
||||
let resolve!: (value: T) => void;
|
||||
let reject!: (reason?: unknown) => void;
|
||||
const promise = new Promise<T>((promiseResolve, promiseReject) => {
|
||||
resolve = promiseResolve;
|
||||
reject = promiseReject;
|
||||
});
|
||||
return { promise, resolve, reject };
|
||||
};
|
||||
|
||||
const responseFor = (id: string): Response =>
|
||||
new Response(
|
||||
JSON.stringify({
|
||||
data: {
|
||||
data: [
|
||||
{
|
||||
id,
|
||||
title: id,
|
||||
file: { xs: { gif: { url: `https://${id}.preview` } } },
|
||||
},
|
||||
],
|
||||
},
|
||||
}),
|
||||
{ status: 200 }
|
||||
);
|
||||
|
||||
const flushPromises = async () => {
|
||||
await Promise.resolve();
|
||||
await Promise.resolve();
|
||||
};
|
||||
|
||||
afterEach(() => {
|
||||
fetchMock.mockReset();
|
||||
});
|
||||
|
||||
describe('useGifSearch', () => {
|
||||
it('keeps stale success, error, and finally handlers from changing the latest request', async () => {
|
||||
const first = deferred<Response>();
|
||||
const second = deferred<Response>();
|
||||
fetchMock.mockImplementation((url: string) =>
|
||||
url.includes('q=first') ? first.promise : second.promise
|
||||
);
|
||||
|
||||
const { result } = renderHook(() => useGifSearch([], true, vi.fn<() => void>()));
|
||||
|
||||
act(() => {
|
||||
void result.current.searchGifs('first');
|
||||
void result.current.searchGifs('second');
|
||||
});
|
||||
|
||||
const firstSignal = fetchMock.mock.calls[0]?.[1]?.signal as AbortSignal;
|
||||
expect(firstSignal.aborted).toBe(true);
|
||||
|
||||
first.reject(new Error('stale failure'));
|
||||
await act(async () => {
|
||||
await flushPromises();
|
||||
});
|
||||
expect(result.current.loading).toBe(true);
|
||||
expect(result.current.error).toBeNull();
|
||||
|
||||
second.resolve(responseFor('second'));
|
||||
await act(async () => {
|
||||
await flushPromises();
|
||||
});
|
||||
expect(result.current.gifs.gifs[0]?.id).toBe('second');
|
||||
expect(result.current.loading).toBe(false);
|
||||
|
||||
first.resolve(responseFor('first'));
|
||||
await act(async () => {
|
||||
await flushPromises();
|
||||
});
|
||||
expect(result.current.gifs.gifs[0]?.id).toBe('second');
|
||||
});
|
||||
|
||||
it('aborts and invalidates a request when cancelled or closed', async () => {
|
||||
const request = deferred<Response>();
|
||||
fetchMock.mockReturnValue(request.promise);
|
||||
|
||||
const { result, rerender } = renderHook(
|
||||
({ open }) => useGifSearch([], open, vi.fn<() => void>()),
|
||||
{ initialProps: { open: true } }
|
||||
);
|
||||
|
||||
act(() => {
|
||||
void result.current.searchGifs('query');
|
||||
});
|
||||
const signal = fetchMock.mock.calls[0]?.[1]?.signal as AbortSignal;
|
||||
|
||||
rerender({ open: false });
|
||||
|
||||
expect(signal.aborted).toBe(true);
|
||||
expect(result.current.loading).toBe(false);
|
||||
|
||||
request.resolve(responseFor('stale'));
|
||||
await act(async () => {
|
||||
await flushPromises();
|
||||
});
|
||||
expect(result.current.gifs.gifs).toEqual([]);
|
||||
});
|
||||
|
||||
it('aborts the active request on unmount', () => {
|
||||
const request = deferred<Response>();
|
||||
fetchMock.mockReturnValue(request.promise);
|
||||
const { result, unmount } = renderHook(() => useGifSearch([], true, vi.fn<() => void>()));
|
||||
|
||||
act(() => {
|
||||
void result.current.searchGifs('query');
|
||||
});
|
||||
const signal = fetchMock.mock.calls[0]?.[1]?.signal as AbortSignal;
|
||||
|
||||
unmount();
|
||||
|
||||
expect(signal.aborted).toBe(true);
|
||||
});
|
||||
});
|
||||
@@ -1,4 +1,4 @@
|
||||
import { useCallback, useMemo, useState } from 'react';
|
||||
import { useCallback, useEffect, useMemo, useRef, useState } from 'react';
|
||||
import type { AsyncSearchHandler } from '$utils/AsyncSearch';
|
||||
import { fetch } from '$utils/fetch';
|
||||
import { useClientConfig } from '$hooks/useClientConfig';
|
||||
@@ -57,14 +57,34 @@ export function useGifSearch(
|
||||
const [error, setError] = useState<string | null>(null);
|
||||
const clientConfig = useClientConfig();
|
||||
const klipyApiKey = clientConfig.gifs?.klipyApiKey ?? '';
|
||||
const requestGenerationRef = useRef(0);
|
||||
const abortControllerRef = useRef<AbortController>();
|
||||
const mountedRef = useRef(true);
|
||||
const showGifPickerRef = useRef(showGifPicker);
|
||||
showGifPickerRef.current = showGifPicker;
|
||||
|
||||
const cancelRequest = useCallback(() => {
|
||||
requestGenerationRef.current += 1;
|
||||
abortControllerRef.current?.abort();
|
||||
abortControllerRef.current = undefined;
|
||||
}, []);
|
||||
|
||||
const cancelSearch = useCallback(() => {
|
||||
cancelRequest();
|
||||
if (mountedRef.current) setLoading(false);
|
||||
}, [cancelRequest]);
|
||||
|
||||
const searchGifs = useCallback(
|
||||
async (query: string) => {
|
||||
if (!showGifPicker) {
|
||||
if (!mountedRef.current || !showGifPickerRef.current) {
|
||||
return;
|
||||
}
|
||||
|
||||
const trimmedQuery = query.trim();
|
||||
cancelRequest();
|
||||
const generation = requestGenerationRef.current;
|
||||
const controller = new AbortController();
|
||||
abortControllerRef.current = controller;
|
||||
|
||||
setLoading(true);
|
||||
setError(null);
|
||||
@@ -77,30 +97,50 @@ export function useGifSearch(
|
||||
url.searchParams.set('q', trimmedQuery);
|
||||
url.searchParams.set('per_page', '50'); // TODO: infinite scroll?
|
||||
|
||||
const response = await fetch(url.toString());
|
||||
const response = await fetch(url.toString(), { signal: controller.signal });
|
||||
|
||||
if (response.status === 200) {
|
||||
const data = (await response.json()) as KlipySearchResponse;
|
||||
const results = data.data?.data;
|
||||
|
||||
setSearchResults(results ? results.map(parseKlipyResult) : []);
|
||||
if (generation === requestGenerationRef.current && mountedRef.current) {
|
||||
setSearchResults(results ? results.map(parseKlipyResult) : []);
|
||||
}
|
||||
} else {
|
||||
throw new Error(`HTTP ${response.status}`);
|
||||
}
|
||||
} catch {
|
||||
setError('Failed to search GIFs');
|
||||
setSearchResults([]);
|
||||
if (generation === requestGenerationRef.current && mountedRef.current) {
|
||||
setError('Failed to search GIFs');
|
||||
setSearchResults([]);
|
||||
}
|
||||
} finally {
|
||||
setLoading(false);
|
||||
if (generation === requestGenerationRef.current && mountedRef.current) {
|
||||
abortControllerRef.current = undefined;
|
||||
setLoading(false);
|
||||
}
|
||||
}
|
||||
},
|
||||
[klipyApiKey, showGifPicker, gifSearch]
|
||||
[cancelRequest, klipyApiKey, gifSearch]
|
||||
);
|
||||
|
||||
useEffect(() => {
|
||||
mountedRef.current = true;
|
||||
|
||||
return () => {
|
||||
mountedRef.current = false;
|
||||
cancelRequest();
|
||||
};
|
||||
}, [cancelRequest]);
|
||||
|
||||
useEffect(() => {
|
||||
if (!showGifPicker) cancelSearch();
|
||||
}, [cancelSearch, showGifPicker]);
|
||||
|
||||
const gifs = useMemo(
|
||||
() => ({ gifs: searchResults, favorites: favoriteGifs }),
|
||||
[searchResults, favoriteGifs]
|
||||
);
|
||||
|
||||
return { gifs, loading, error, searchGifs };
|
||||
return { gifs, loading, error, searchGifs, cancelSearch };
|
||||
}
|
||||
@@ -415,11 +415,13 @@ export function MessagePreview({
|
||||
const [showPronouns] = useSetting(settingsAtom, 'showPronouns');
|
||||
const [parsePronouns] = useSetting(settingsAtom, 'parsePronouns');
|
||||
const { cleanedDisplayName: displayName, inlinePronoun } = useMemo(
|
||||
() => getParsedPronouns(perMessageProfile?.name || fallbackDisplayName, parsePronouns),
|
||||
[perMessageProfile?.name, fallbackDisplayName, parsePronouns]
|
||||
() => getParsedPronouns(perMessageProfile?.displayname || fallbackDisplayName, parsePronouns),
|
||||
[perMessageProfile?.displayname, fallbackDisplayName, parsePronouns]
|
||||
);
|
||||
const pronouns = useMemo(() => {
|
||||
const resolved = [...(perMessageProfile?.pronouns ?? userProfile.pronouns ?? [])];
|
||||
const resolved = [
|
||||
...(perMessageProfile?.['io.fsky.nyx.pronouns'] ?? userProfile.pronouns ?? []),
|
||||
];
|
||||
if (
|
||||
inlinePronoun &&
|
||||
!resolved.some((item) => item.summary?.toLowerCase() === inlinePronoun.toLowerCase())
|
||||
@@ -427,9 +429,9 @@ export function MessagePreview({
|
||||
resolved.push({ summary: inlinePronoun, language: 'en' });
|
||||
}
|
||||
return resolved;
|
||||
}, [perMessageProfile?.pronouns, userProfile.pronouns, inlinePronoun]);
|
||||
}, [perMessageProfile, userProfile.pronouns, inlinePronoun]);
|
||||
const avatarMxc =
|
||||
perMessageProfile?.avatarUrl ??
|
||||
perMessageProfile?.avatar_url ??
|
||||
getMemberAvatarMxc(room, sender) ??
|
||||
userProfile.avatarUrl ??
|
||||
profile?.avatarUrl;
|
||||
|
||||
@@ -21,7 +21,11 @@ import { FALLBACK_MIMETYPE, getBlobSafeMimeType } from '$utils/mimeTypes';
|
||||
import { parseGeoUri, scaleYDimension } from '$utils/common';
|
||||
import { useSetting } from '$state/hooks/settings';
|
||||
import { settingsAtom } from '$state/settings';
|
||||
import type { PerMessageProfileBeeperFormat } from '$hooks/usePerMessageProfile';
|
||||
import {
|
||||
stripPerMessageProfileFormattedBody,
|
||||
stripPerMessageProfilePlainBody,
|
||||
type PerMessageProfileBeeperFormat,
|
||||
} from '$hooks/usePerMessageProfile';
|
||||
import { Attachment, AttachmentBox, AttachmentContent, AttachmentHeader } from './attachment';
|
||||
import { FileHeader, FileDownloadButton } from './FileHeader';
|
||||
import {
|
||||
@@ -217,29 +221,51 @@ export function MText({
|
||||
/**
|
||||
* For the unwrapping of per-message profile fallbacks, we look for <strong> tags with the data-mx-profile-fallback attribute
|
||||
*/
|
||||
const unwrappedPerMessageProfileMessage = useMemo(
|
||||
() =>
|
||||
cleanedMessage?.replace(/<strong[^>]*data-mx-profile-fallback[^>]*>(.*?):\s*<\/strong>/i, ''),
|
||||
const hadPerMessageProfileFallback = useMemo(
|
||||
() => cleanedMessage?.match(/<strong[^>]*data-mx-profile-fallback[^>]*>(.*?):\s*<\/strong>/i),
|
||||
[cleanedMessage]
|
||||
);
|
||||
// the html body, with PMP fallback removed
|
||||
const unwrappedPmpCustomBody = useMemo(
|
||||
() => (cleanedMessage ? stripPerMessageProfileFormattedBody(cleanedMessage) : undefined),
|
||||
[cleanedMessage]
|
||||
);
|
||||
// the plain body, with PMP fallback removed
|
||||
const unwrappedPmpBody = useMemo(
|
||||
() =>
|
||||
hadPerMessageProfileFallback
|
||||
? stripPerMessageProfilePlainBody(trimmedBody ?? '')
|
||||
: trimmedBody,
|
||||
[trimmedBody, hadPerMessageProfileFallback]
|
||||
);
|
||||
|
||||
const isJumbo = useMemo(() => {
|
||||
if (!trimmedBody || trimmedBody.length >= 500) return false;
|
||||
if (
|
||||
(unwrappedPerMessageProfileMessage ?? cleanedMessage ?? customBody)?.match(
|
||||
(unwrappedPmpCustomBody ?? cleanedMessage ?? customBody)?.match(
|
||||
/^(<img[^>]*data-mx-emoticon[^>]*\/>){1,20}$/i
|
||||
)
|
||||
)
|
||||
return true;
|
||||
if (!isJumboEmojiText(trimmedBody)) return false;
|
||||
if (!isJumboEmojiText(unwrappedPmpBody)) return false;
|
||||
|
||||
if (trimmedBody.includes(':')) {
|
||||
const hasImage = customBody && /<img[^>]*>/i.test(customBody);
|
||||
// we need to strip the plainbody fallback because it contains a colon
|
||||
if (unwrappedPmpBody.includes(':')) {
|
||||
const newCustomBody = hadPerMessageProfileFallback ? unwrappedPmpCustomBody : customBody;
|
||||
|
||||
const hasImage = newCustomBody && /<img[^>]*>/i.test(newCustomBody);
|
||||
if (!hasImage) return false;
|
||||
}
|
||||
|
||||
return true;
|
||||
}, [unwrappedPerMessageProfileMessage, cleanedMessage, trimmedBody, customBody]);
|
||||
}, [
|
||||
unwrappedPmpCustomBody,
|
||||
cleanedMessage,
|
||||
trimmedBody,
|
||||
customBody,
|
||||
unwrappedPmpBody,
|
||||
hadPerMessageProfileFallback,
|
||||
]);
|
||||
|
||||
const { urls, bundleContent } = getUrlsFromContent(content, renderUrlsPreview);
|
||||
|
||||
@@ -260,7 +286,7 @@ export function MText({
|
||||
>
|
||||
{renderBody({
|
||||
body: trimmedBody,
|
||||
customBody: unwrappedPerMessageProfileMessage,
|
||||
customBody: unwrappedPmpCustomBody,
|
||||
})}
|
||||
{edited && <MessageEditedContent />}
|
||||
</MessageTextBody>
|
||||
|
||||
@@ -44,6 +44,11 @@ vi.mock('$hooks/useSableCosmetics', () => ({
|
||||
useSableCosmetics: () => ({ color: undefined, font: undefined }),
|
||||
}));
|
||||
|
||||
vi.mock('$hooks/useTheme', () => ({
|
||||
ThemeKind: { Light: 'light', Dark: 'dark' },
|
||||
useActiveTheme: () => ({ kind: 'light' }),
|
||||
}));
|
||||
|
||||
vi.mock('$hooks/useMediaAuthentication', () => ({
|
||||
useMediaAuthentication: () => false,
|
||||
}));
|
||||
|
||||
@@ -63,7 +63,12 @@ import { LinePlaceholder } from './placeholder';
|
||||
import { ReactionKeyInline } from './ReactionKeyInline';
|
||||
import { M_POLL_START, M_TEXT } from 'matrix-js-sdk';
|
||||
import type { PerMessageProfileBeeperFormat } from '$hooks/usePerMessageProfile';
|
||||
import { convertBeeperFormatToOurPerMessageProfile } from '$hooks/usePerMessageProfile';
|
||||
import { ThemeKind, useActiveTheme } from '$hooks/useTheme';
|
||||
import {
|
||||
convertBeeperFormatToOurPerMessageProfile,
|
||||
stripPerMessageProfileFormattedBody,
|
||||
} from '$hooks/usePerMessageProfile';
|
||||
import { useAccessibleNameColor } from '$hooks/useAccessibleNameColor';
|
||||
|
||||
const ROOM_REPLY_TIMELINE_EVENT_TYPES = new Set<string>([
|
||||
EventType.RoomMessage as string,
|
||||
@@ -272,7 +277,7 @@ export const Reply = as<'div', ReplyProps>(
|
||||
|
||||
// strip the PMP fallback if it's there, to avoid displaying the PMP name twice
|
||||
const formattedBodyStripped: string = pmp
|
||||
? formattedBody?.replace(/^<strong\s+data-mx-profile-fallback[^>]*>.*?<\/strong>/, '')
|
||||
? stripPerMessageProfileFormattedBody(formattedBody ?? '')
|
||||
: formattedBody;
|
||||
|
||||
const extensibleContent = contentForPreview[M_TEXT.name] as
|
||||
@@ -291,6 +296,15 @@ export const Reply = as<'div', ReplyProps>(
|
||||
const parseMemberEvent = useMemberEventParser();
|
||||
|
||||
const { color: usernameColor, font: usernameFont } = useSableCosmetics(sender ?? '', room);
|
||||
const activeTheme = useActiveTheme();
|
||||
|
||||
const accessibleNameColor = useAccessibleNameColor(activeTheme.kind);
|
||||
const pmpNameColor = useMemo(() => {
|
||||
return activeTheme.kind === ThemeKind.Dark
|
||||
? pmp?.['eu.she-a.color']?.on_dark
|
||||
: pmp?.['eu.she-a.color']?.on_light;
|
||||
}, [activeTheme, pmp]);
|
||||
|
||||
const nicknames = useAtomValue(nicknamesAtom);
|
||||
const cachedProfiles = useAtomValue(profilesCacheAtom);
|
||||
useRoomMemberHydration(room, sender ?? '');
|
||||
@@ -503,7 +517,7 @@ export const Reply = as<'div', ReplyProps>(
|
||||
)}
|
||||
<ReplyLayout
|
||||
as="button"
|
||||
userColor={usernameColor}
|
||||
userColor={accessibleNameColor(pmpNameColor) ?? usernameColor}
|
||||
icon={image}
|
||||
replyIcon={replyIcon}
|
||||
mentioned={mentioned}
|
||||
@@ -512,7 +526,7 @@ export const Reply = as<'div', ReplyProps>(
|
||||
eventType !== EventType.RoomMember && (
|
||||
<Text size="T300" truncate style={{ fontFamily: usernameFont }}>
|
||||
<b>
|
||||
{pmp?.name ??
|
||||
{pmp?.displayname ??
|
||||
getMemberDisplayName(room, sender, nicknames) ??
|
||||
cachedProfiles[sender]?.displayName ??
|
||||
getMxIdLocalPart(sender)}
|
||||
|
||||
@@ -62,12 +62,15 @@ import {
|
||||
} from '$features/bookmarks';
|
||||
import { CopyIcon } from '@phosphor-icons/react';
|
||||
import * as OptionsCss from './Options.css';
|
||||
import { MATRIX_SABLE_UNSTABLE_FAVORITE_GIFS } from '$unstable/prefixes';
|
||||
import {
|
||||
MATRIX_SABLE_UNSTABLE_FAVORITE_GIFS,
|
||||
MATRIX_UNSTABLE_PER_MESSAGE_PROFILE_PROPERTY_NAME,
|
||||
} from '$unstable/prefixes';
|
||||
import { useFavoriteGifs } from '$hooks/useFavoriteGifs';
|
||||
import type { IImageInfo } from '$types/matrix/common';
|
||||
import { getIncomingMediaMxcUrl } from '../MsgTypeRenderers';
|
||||
import { TemporaryPersonaPicker } from '$features/room/persona-picker/PersonaPicker';
|
||||
import { type PerMessageProfile } from '$hooks/usePerMessageProfile';
|
||||
import { type PerMessageProfileMsc4461 } from '$hooks/usePerMessageProfile';
|
||||
import { buildReplacementPmpContent } from '$features/room/buildReplacementContent';
|
||||
import { settingsAtom } from '$state/settings';
|
||||
import { useSetting } from '$state/hooks/settings';
|
||||
@@ -172,7 +175,8 @@ const MessageCopyTextItem = as<
|
||||
>(({ room, mEvent, onClose, ...props }, ref) => {
|
||||
const handleCopy = () => {
|
||||
const content = mEvent.getContent();
|
||||
const body = content?.body;
|
||||
const pmp = content[MATRIX_UNSTABLE_PER_MESSAGE_PROFILE_PROPERTY_NAME];
|
||||
const body = pmp ? content?.body?.replace(`${pmp.displayname}: `, '') : content?.body;
|
||||
|
||||
if (body) copyToClipboard(body);
|
||||
onClose();
|
||||
@@ -414,7 +418,7 @@ function OptionsReproxyPersonaPicker({
|
||||
closeMenu,
|
||||
anchor,
|
||||
}: OptionsReproxyPersonaPickerProps) {
|
||||
const reproxyMessage = async (profile: PerMessageProfile | undefined) => {
|
||||
const reproxyMessage = async (profile: PerMessageProfileMsc4461 | undefined) => {
|
||||
const content = buildReplacementPmpContent(mEvent.getContent(), mEvent.getId()!, profile);
|
||||
await mx.sendMessage(roomId, content as RoomMessageEventContent);
|
||||
|
||||
|
||||
@@ -1,7 +1,9 @@
|
||||
import { render, screen } from '@testing-library/react';
|
||||
import { useLayoutEffect, useRef } from 'react';
|
||||
import { fireEvent, render, screen } from '@testing-library/react';
|
||||
import { beforeAll, describe, expect, it, vi } from 'vitest';
|
||||
import { MemoryRouter } from 'react-router-dom';
|
||||
import { MobileNavDrawer } from './MobileNavDrawer';
|
||||
import { useMobileNavDrawer } from './MobileNavDrawerContext';
|
||||
|
||||
vi.mock('$state/hooks/settings', () => ({
|
||||
useSetting: () => [true, vi.fn<() => void>()],
|
||||
@@ -36,6 +38,11 @@ const renderDrawer = () =>
|
||||
</MemoryRouter>
|
||||
);
|
||||
|
||||
const touchList = (target: HTMLElement, clientX: number, clientY: number) => {
|
||||
const point = { identifier: 0, target, clientX, clientY, pageX: clientX, pageY: clientY };
|
||||
return { touches: [point], targetTouches: [point], changedTouches: [point] };
|
||||
};
|
||||
|
||||
describe('MobileNavDrawer', () => {
|
||||
// The panels sit side by side in a track twice the viewport wide, moved by transform.
|
||||
// `hidden` leaves a scrollport that focus or scrollIntoView scrolls a full panel width,
|
||||
@@ -48,4 +55,43 @@ describe('MobileNavDrawer', () => {
|
||||
expect(viewport.style.overflow).toBe('clip');
|
||||
expect(viewport.style.overflow).not.toBe('hidden');
|
||||
});
|
||||
|
||||
it('still drives message swipe when the gesture starts on a nested ignored element (e.g. an image)', () => {
|
||||
const move = vi.fn<(distanceX: number) => void>();
|
||||
|
||||
function MessageProbe() {
|
||||
const drawer = useMobileNavDrawer();
|
||||
const containerRef = useRef<HTMLDivElement | null>(null);
|
||||
useLayoutEffect(() => {
|
||||
const el = containerRef.current;
|
||||
if (!el || !drawer) return undefined;
|
||||
return drawer.registerMessageSwipe(el, {
|
||||
move,
|
||||
end: vi.fn<(gesture: { distanceX: number; velocityX: number }) => void>(),
|
||||
cancel: vi.fn<() => void>(),
|
||||
});
|
||||
}, [drawer]);
|
||||
return (
|
||||
<div ref={containerRef} data-message-swipe data-gestures="ignore">
|
||||
<div data-gestures="ignore" data-testid="image">
|
||||
image
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
render(
|
||||
<MemoryRouter initialEntries={['/home']}>
|
||||
<MobileNavDrawer nav={<MessageProbe />}>
|
||||
<div>content</div>
|
||||
</MobileNavDrawer>
|
||||
</MemoryRouter>
|
||||
);
|
||||
|
||||
const image = screen.getByTestId('image');
|
||||
fireEvent.touchStart(image, touchList(image, 260, 100));
|
||||
fireEvent.touchMove(image, touchList(image, 200, 100));
|
||||
|
||||
expect(move).toHaveBeenCalled();
|
||||
});
|
||||
});
|
||||
@@ -353,7 +353,12 @@ export function MobileNavDrawer({ nav, rail, bottomNav, children }: MobileNavDra
|
||||
const ignoredElement = target.closest<HTMLElement>('[data-gestures="ignore"]');
|
||||
const message = messageElement ? messageTargetsRef.current.get(messageElement) : undefined;
|
||||
const chat = chatElement ? chatTargetsRef.current.get(chatElement) : undefined;
|
||||
const blocked = ignoredElement !== null && ignoredElement !== messageElement;
|
||||
// Nested ignore markers (e.g. inline media) don't block swipe if they're part of
|
||||
// this message/chat's own surface, only if they sit outside it.
|
||||
const blocked =
|
||||
ignoredElement !== null &&
|
||||
!(messageElement && messageElement.contains(ignoredElement)) &&
|
||||
!(chatElement && chatElement.contains(ignoredElement));
|
||||
|
||||
gestureRef.current = {
|
||||
startX: touch.clientX,
|
||||
|
||||
@@ -2,6 +2,7 @@ import type { ReactNode } from 'react';
|
||||
import { Box, IconButton, Text } from 'folds';
|
||||
import { ScreenSize, useScreenSizeContext } from '$hooks/useScreenSize';
|
||||
import { ArrowLeft, composerIcon, X } from '$components/icons/phosphor';
|
||||
import { useAndroidBackHandler } from '$utils/androidBack';
|
||||
import { Page, PageHeader } from './Page';
|
||||
import { SettingsSectionBody, SettingsSectionHeader } from './style.css';
|
||||
|
||||
@@ -27,6 +28,10 @@ export function SettingsSectionPage({
|
||||
const screenSize = useScreenSizeContext();
|
||||
const closeLabel = actionLabel ?? 'Close';
|
||||
const showBack = screenSize === ScreenSize.Mobile && requestBack;
|
||||
useAndroidBackHandler(() => {
|
||||
requestBack?.();
|
||||
return true;
|
||||
}, !!showBack);
|
||||
|
||||
return (
|
||||
<Page>
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
import type { MutableRefObject, ReactNode } from 'react';
|
||||
import { useEffect, useImperativeHandle, useRef } from 'react';
|
||||
import { useEffect, useImperativeHandle } from 'react';
|
||||
import { Badge, Box, Chip, Header, Spinner, Text, as, percent } from 'folds';
|
||||
import { CaretRight, CaretUp, X, sizedIcon } from '$components/icons/phosphor';
|
||||
import classNames from 'classnames';
|
||||
@@ -27,14 +27,15 @@ export const UploadBoard = as<'div', UploadBoardProps>(({ header, children, ...p
|
||||
</Box>
|
||||
));
|
||||
|
||||
export type UploadBoardImperativeHandlers = { handleSend: () => Promise<void> };
|
||||
// Progress ticks re-render this header, so the caller reads uploads on demand here
|
||||
// instead of subscribing to them itself.
|
||||
export type UploadBoardImperativeHandlers = { getSendableUploads: () => Upload[] };
|
||||
|
||||
type UploadBoardHeaderProps = {
|
||||
open: boolean;
|
||||
onToggle: () => void;
|
||||
uploadFamilyObserverAtom: TUploadFamilyObserverAtom;
|
||||
onCancel: (uploads: Upload[]) => void;
|
||||
onSend: (uploads: Upload[]) => Promise<void>;
|
||||
onBusyChange?: (busy: boolean) => void;
|
||||
imperativeHandlerRef: MutableRefObject<UploadBoardImperativeHandlers | undefined>;
|
||||
};
|
||||
@@ -44,11 +45,9 @@ export function UploadBoardHeader({
|
||||
onToggle,
|
||||
uploadFamilyObserverAtom,
|
||||
onCancel,
|
||||
onSend,
|
||||
onBusyChange,
|
||||
imperativeHandlerRef,
|
||||
}: UploadBoardHeaderProps) {
|
||||
const sendingRef = useRef(false);
|
||||
const uploads = useAtomValue(uploadFamilyObserverAtom);
|
||||
|
||||
const isSuccess = uploads.every((upload) => upload.status === UploadStatus.Success);
|
||||
@@ -72,23 +71,11 @@ export function UploadBoardHeader({
|
||||
{ loaded: 0, total: 0 }
|
||||
);
|
||||
|
||||
const handleSend = async () => {
|
||||
if (sendingRef.current) return;
|
||||
sendingRef.current = true;
|
||||
try {
|
||||
await onSend(
|
||||
uploads.filter(
|
||||
(upload) =>
|
||||
upload.status === UploadStatus.Success || upload.status === UploadStatus.Loading
|
||||
)
|
||||
);
|
||||
} finally {
|
||||
sendingRef.current = false;
|
||||
}
|
||||
};
|
||||
|
||||
useImperativeHandle(imperativeHandlerRef, () => ({
|
||||
handleSend,
|
||||
getSendableUploads: () =>
|
||||
uploads.filter(
|
||||
(upload) => upload.status === UploadStatus.Success || upload.status === UploadStatus.Loading
|
||||
),
|
||||
}));
|
||||
const handleCancel = () => onCancel(uploads);
|
||||
|
||||
|
||||
@@ -19,6 +19,8 @@ import { BreakWord, LineClamp3 } from '$styles/Text.css';
|
||||
import type { UserPresence } from '$hooks/useUserPresence';
|
||||
import { useRoom } from '$hooks/useRoom';
|
||||
import { useSableCosmetics } from '$hooks/useSableCosmetics';
|
||||
import { useActiveTheme } from '$hooks/useTheme';
|
||||
import { useAccessibleNameColor } from '$hooks/useAccessibleNameColor';
|
||||
import { useNickname } from '$hooks/useNickname';
|
||||
import { useRenderableMediaUrl } from '$hooks/useRenderableMediaUrl';
|
||||
import { ImageViewer } from '$components/image-viewer';
|
||||
@@ -358,6 +360,8 @@ export function GlobalUserHeroName({ displayName, userId, server }: UserHeroName
|
||||
const username = getMxIdLocalPart(userId);
|
||||
const nick = useNickname(userId);
|
||||
const profile = useUserProfile(userId);
|
||||
const activeTheme = useActiveTheme();
|
||||
const accessibleNameColor = useAccessibleNameColor(activeTheme.kind);
|
||||
|
||||
const shownName = nick ?? displayName ?? username ?? userId;
|
||||
|
||||
@@ -367,7 +371,7 @@ export function GlobalUserHeroName({ displayName, userId, server }: UserHeroName
|
||||
server={server}
|
||||
shownName={shownName}
|
||||
font={profile.resolvedFont}
|
||||
color={profile.resolvedColor}
|
||||
color={accessibleNameColor(profile.resolvedColor)}
|
||||
/>
|
||||
);
|
||||
}
|
||||
@@ -37,7 +37,13 @@ export function CallRoomName({ room }: CallRoomNameProps) {
|
||||
variant="Background"
|
||||
radii="Pill"
|
||||
before={
|
||||
<RoomIcon size="200" joinRule={room.getJoinRule()} roomType={room.getType()} filled />
|
||||
<RoomIcon
|
||||
size="200"
|
||||
joinRule={room.getJoinRule()}
|
||||
roomType={room.getType()}
|
||||
filled
|
||||
style={{ width: 'auto' }}
|
||||
/>
|
||||
}
|
||||
onClick={() => navigateRoom(room.roomId)}
|
||||
>
|
||||
|
||||
@@ -17,7 +17,7 @@ import { produce } from 'immer';
|
||||
import { useSpace } from '$hooks/useSpace';
|
||||
import { Page, PageContent, PageContentCenter, PageHeroSection } from '$components/page';
|
||||
import type { HierarchyItem, HierarchyItemSpace } from '$hooks/useSpaceHierarchy';
|
||||
import { useSpaceHierarchy } from '$hooks/useSpaceHierarchy';
|
||||
import { getSpaceHierarchyItemKey, useSpaceHierarchy } from '$hooks/useSpaceHierarchy';
|
||||
import { VirtualTile } from '$components/virtualizer';
|
||||
import { spaceRoomsAtom } from '$state/spaceRooms';
|
||||
import { useSetting } from '$state/hooks/settings';
|
||||
@@ -301,7 +301,7 @@ export function Lobby() {
|
||||
(index: number) => {
|
||||
const item = hierarchy[index];
|
||||
if (!item) return index;
|
||||
return `${space.roomId}:${item.space.roomId}:${item.space.depth}`;
|
||||
return getSpaceHierarchyItemKey(space.roomId, item.space);
|
||||
},
|
||||
[hierarchy, space.roomId]
|
||||
);
|
||||
|
||||
@@ -22,7 +22,7 @@ import { useNavigate } from 'react-router-dom';
|
||||
import { NavButton, NavItem, NavItemContent, NavItemOptions } from '$components/nav';
|
||||
import { UnreadBadge, UnreadBadgeCenter } from '$components/unread-badge';
|
||||
import { RoomAvatar, RoomIcon } from '$components/room-avatar';
|
||||
import { getDirectRoomAvatarUrl, getRoomAvatarUrl } from '$utils/room/display';
|
||||
import { getDirectRoomAvatarUrl, getDmOtherMember, getRoomAvatarUrl } from '$utils/room/display';
|
||||
import { roomHaveUnread } from '$utils/room/unread';
|
||||
import { nameInitials } from '$utils/common';
|
||||
import { useMatrixClient } from '$hooks/useMatrixClient';
|
||||
@@ -335,7 +335,7 @@ export function RoomNavItem({
|
||||
|
||||
const [roomIconOverlay] = useSetting(settingsAtom, 'roomIconOverlay');
|
||||
const nicknames = useAtomValue(nicknamesAtom);
|
||||
const dmUserId = direct ? room.getAvatarFallbackMember()?.userId : undefined;
|
||||
const dmUserId = direct ? getDmOtherMember(mx, room)?.userId : undefined;
|
||||
const matrixRoomName = useRoomName(room);
|
||||
const roomName = (dmUserId && nicknames[dmUserId]) || matrixRoomName;
|
||||
const presence = useUserPresence(dmUserId ?? '');
|
||||
|
||||
@@ -0,0 +1,107 @@
|
||||
/* oxlint-disable typescript/no-explicit-any, vitest/require-mock-type-parameters */
|
||||
|
||||
import { act, render } from '@testing-library/react';
|
||||
import { createRef } from 'react';
|
||||
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
|
||||
import { AudioMessageRecorder, type AudioMessageRecorderHandle } from './AudioMessageRecorder';
|
||||
|
||||
const recorderState = vi.hoisted(() => ({
|
||||
handleStop: vi.fn(),
|
||||
handleDelete: vi.fn(),
|
||||
onStop: undefined as ((payload: any) => void) | undefined,
|
||||
onDelete: undefined as (() => void) | undefined,
|
||||
}));
|
||||
|
||||
vi.mock('$plugins/voice-recorder-kit', () => ({
|
||||
useVoiceRecorder: ({ onStop, onDelete }: any) => {
|
||||
recorderState.onStop = onStop;
|
||||
recorderState.onDelete = onDelete;
|
||||
return {
|
||||
levels: [],
|
||||
seconds: 0,
|
||||
error: undefined,
|
||||
handleStop: recorderState.handleStop,
|
||||
handleDelete: recorderState.handleDelete,
|
||||
};
|
||||
},
|
||||
}));
|
||||
vi.mock('$hooks/useElementSizeObserver', () => ({ useElementSizeObserver: () => {} }));
|
||||
vi.mock('folds', () => ({
|
||||
Box: ({ children }: any) => <div>{children}</div>,
|
||||
Text: ({ children }: any) => <span>{children}</span>,
|
||||
}));
|
||||
|
||||
const payload = {
|
||||
audioFile: new Blob(['audio'], { type: 'audio/ogg' }),
|
||||
waveform: [0.5],
|
||||
audioLength: 1,
|
||||
audioCodec: 'audio/ogg',
|
||||
};
|
||||
|
||||
function renderRecorder() {
|
||||
const ref = createRef<AudioMessageRecorderHandle>();
|
||||
const onRecordingComplete = vi.fn();
|
||||
const result = render(
|
||||
<AudioMessageRecorder
|
||||
ref={ref}
|
||||
onRecordingComplete={onRecordingComplete}
|
||||
onRequestClose={vi.fn()}
|
||||
onWaveformUpdate={vi.fn()}
|
||||
onAudioLengthUpdate={vi.fn()}
|
||||
/>
|
||||
);
|
||||
return { ref, onRecordingComplete, result };
|
||||
}
|
||||
|
||||
beforeEach(() => {
|
||||
vi.useFakeTimers();
|
||||
recorderState.handleStop.mockReset();
|
||||
recorderState.handleDelete.mockReset();
|
||||
recorderState.onStop = undefined;
|
||||
recorderState.onDelete = undefined;
|
||||
});
|
||||
|
||||
afterEach(() => {
|
||||
vi.useRealTimers();
|
||||
});
|
||||
|
||||
describe('AudioMessageRecorder lifecycle', () => {
|
||||
it('makes stop idempotent and surfaces one completion', () => {
|
||||
const { ref, onRecordingComplete } = renderRecorder();
|
||||
|
||||
act(() => {
|
||||
ref.current?.stop();
|
||||
ref.current?.stop();
|
||||
recorderState.onStop?.(payload);
|
||||
recorderState.onStop?.(payload);
|
||||
});
|
||||
|
||||
expect(recorderState.handleStop).toHaveBeenCalledOnce();
|
||||
expect(onRecordingComplete).toHaveBeenCalledOnce();
|
||||
});
|
||||
|
||||
it('makes delayed cancel idempotent and cancels its timer on unmount', () => {
|
||||
const { ref, result } = renderRecorder();
|
||||
|
||||
act(() => {
|
||||
ref.current?.cancel();
|
||||
ref.current?.cancel();
|
||||
vi.advanceTimersByTime(180);
|
||||
});
|
||||
expect(recorderState.handleDelete).toHaveBeenCalledOnce();
|
||||
|
||||
result.unmount();
|
||||
act(() => vi.runOnlyPendingTimers());
|
||||
expect(recorderState.handleDelete).toHaveBeenCalledOnce();
|
||||
});
|
||||
|
||||
it('does not delete after cancel is followed by unmount before the delay', () => {
|
||||
const { ref, result } = renderRecorder();
|
||||
|
||||
act(() => ref.current?.cancel());
|
||||
result.unmount();
|
||||
act(() => vi.advanceTimersByTime(180));
|
||||
|
||||
expect(recorderState.handleDelete).not.toHaveBeenCalled();
|
||||
});
|
||||
});
|
||||
@@ -48,8 +48,9 @@ export const AudioMessageRecorder = forwardRef<
|
||||
AudioMessageRecorderHandle,
|
||||
AudioMessageRecorderProps
|
||||
>(({ onRecordingComplete, onRequestClose, onWaveformUpdate, onAudioLengthUpdate }, ref) => {
|
||||
const isDismissedRef = useRef(false);
|
||||
const userRequestedStopRef = useRef(false);
|
||||
const actionRef = useRef<'active' | 'stopping' | 'canceling' | 'dismissed'>('active');
|
||||
const cancelTimerRef = useRef<ReturnType<typeof setTimeout> | null>(null);
|
||||
const containerRef = useRef<HTMLDivElement>(null);
|
||||
const [isCanceling, setIsCanceling] = useState(false);
|
||||
const [announcedTime, setAnnouncedTime] = useState(0);
|
||||
@@ -67,8 +68,8 @@ export const AudioMessageRecorder = forwardRef<
|
||||
const stableOnStop = useCallback((payload: VoiceRecorderStopPayload) => {
|
||||
// useVoiceRecorder also stops during cancel/teardown paths, so only surface a completed
|
||||
// recording after an explicit user stop.
|
||||
if (!userRequestedStopRef.current) return;
|
||||
if (isDismissedRef.current) return;
|
||||
if (!userRequestedStopRef.current || actionRef.current !== 'stopping') return;
|
||||
actionRef.current = 'dismissed';
|
||||
onRecordingCompleteRef.current({
|
||||
audioBlob: payload.audioFile,
|
||||
waveform: payload.waveform,
|
||||
@@ -80,7 +81,11 @@ export const AudioMessageRecorder = forwardRef<
|
||||
}, []);
|
||||
|
||||
const stableOnDelete = useCallback(() => {
|
||||
isDismissedRef.current = true;
|
||||
if (cancelTimerRef.current !== null) {
|
||||
clearTimeout(cancelTimerRef.current);
|
||||
cancelTimerRef.current = null;
|
||||
}
|
||||
actionRef.current = 'dismissed';
|
||||
onRequestCloseRef.current();
|
||||
}, []);
|
||||
|
||||
@@ -91,22 +96,35 @@ export const AudioMessageRecorder = forwardRef<
|
||||
});
|
||||
|
||||
const doStop = useCallback(() => {
|
||||
if (isDismissedRef.current) return;
|
||||
if (actionRef.current !== 'active') return;
|
||||
actionRef.current = 'stopping';
|
||||
userRequestedStopRef.current = true;
|
||||
handleStop();
|
||||
}, [handleStop]);
|
||||
|
||||
const doCancel = useCallback(() => {
|
||||
if (isDismissedRef.current) return;
|
||||
if (actionRef.current !== 'active') return;
|
||||
actionRef.current = 'canceling';
|
||||
setIsCanceling(true);
|
||||
setTimeout(() => {
|
||||
isDismissedRef.current = true;
|
||||
cancelTimerRef.current = setTimeout(() => {
|
||||
cancelTimerRef.current = null;
|
||||
if (actionRef.current !== 'canceling') return;
|
||||
actionRef.current = 'dismissed';
|
||||
handleDelete();
|
||||
}, 180);
|
||||
}, [handleDelete]);
|
||||
|
||||
useImperativeHandle(ref, () => ({ stop: doStop, cancel: doCancel }), [doStop, doCancel]);
|
||||
|
||||
useEffect(
|
||||
() => () => {
|
||||
if (cancelTimerRef.current !== null) clearTimeout(cancelTimerRef.current);
|
||||
cancelTimerRef.current = null;
|
||||
actionRef.current = 'dismissed';
|
||||
},
|
||||
[]
|
||||
);
|
||||
|
||||
useEffect(() => {
|
||||
if (seconds > 0 && seconds % 30 === 0 && seconds !== announcedTime) {
|
||||
setAnnouncedTime(seconds);
|
||||
|
||||
@@ -19,6 +19,7 @@ import { useKeyDown } from '$hooks/useKeyDown';
|
||||
import { onTabPress } from '$utils/keyboard';
|
||||
|
||||
type CommandAutoCompleteHandler = (commandName: string) => void;
|
||||
const GIF_COMMAND = 'gif';
|
||||
|
||||
type CommandAutocompleteProps = {
|
||||
room: Room;
|
||||
@@ -41,7 +42,10 @@ export function CommandAutocomplete({
|
||||
}: CommandAutocompleteProps) {
|
||||
const mx = useMatrixClient();
|
||||
const commands = useCommands(mx, room);
|
||||
const commandNames = useMemo(() => Object.keys(commands) as Command[], [commands]);
|
||||
const commandNames = useMemo(
|
||||
() => [GIF_COMMAND, ...(Object.keys(commands) as Command[])],
|
||||
[commands]
|
||||
);
|
||||
|
||||
const [result, search, resetSearch] = useAsyncSearch(
|
||||
commandNames,
|
||||
@@ -106,7 +110,9 @@ export function CommandAutocomplete({
|
||||
{`/${commandName}`}
|
||||
</Text>
|
||||
<Text truncate priority="300" size="T200">
|
||||
{commands[commandName].description}
|
||||
{commandName === GIF_COMMAND
|
||||
? 'Search and send a GIF: /gif <search>'
|
||||
: commands[commandName as Command].description}
|
||||
</Text>
|
||||
</Box>
|
||||
</MenuItem>
|
||||
|
||||
@@ -20,6 +20,7 @@ const {
|
||||
windowFocused,
|
||||
rowItemIndex,
|
||||
rowRenders,
|
||||
eventRedacted,
|
||||
} = vi.hoisted(() => ({
|
||||
vListHandle: {
|
||||
scrollSize: 1000,
|
||||
@@ -55,6 +56,7 @@ const {
|
||||
windowFocused: { current: false },
|
||||
rowItemIndex: { current: 0 },
|
||||
rowRenders: { count: 0 },
|
||||
eventRedacted: { current: false },
|
||||
}));
|
||||
|
||||
let lastOnScroll: ((offset: number) => void) | undefined;
|
||||
@@ -152,10 +154,11 @@ vi.mock('$hooks/timeline/useProcessedTimeline', async (importOriginal) => {
|
||||
getTs: () => Date.now(),
|
||||
getSender: () => '@me:example.org',
|
||||
getId: () => '$evt1',
|
||||
isRedacted: () => false,
|
||||
isRedacted: () => eventRedacted.current,
|
||||
},
|
||||
timelineSet: undefined,
|
||||
eventSender: '@me:example.org',
|
||||
isRedacted: eventRedacted.current,
|
||||
editId: undefined,
|
||||
reactionsKey: '',
|
||||
content: undefined,
|
||||
@@ -166,6 +169,7 @@ vi.mock('$hooks/timeline/useProcessedTimeline', async (importOriginal) => {
|
||||
processedTimelineOptions.current = options;
|
||||
// Same object every call so the row memo can compare eventData by identity.
|
||||
fakeEvent.itemIndex = rowItemIndex.current;
|
||||
fakeEvent.isRedacted = eventRedacted.current;
|
||||
return (options.items as number[]).length === 0 ? [] : [fakeEvent];
|
||||
},
|
||||
};
|
||||
@@ -292,6 +296,7 @@ beforeEach(() => {
|
||||
windowFocused.current = false;
|
||||
rowItemIndex.current = 0;
|
||||
rowRenders.count = 0;
|
||||
eventRedacted.current = false;
|
||||
timelineSync.eventsLength = 1;
|
||||
timelineSync.focusItem = undefined;
|
||||
timelineSync.canPaginateBack = false;
|
||||
@@ -504,6 +509,16 @@ describe('MemoizedTimelineItem', () => {
|
||||
|
||||
expect(rowRenders.count).toBe(before);
|
||||
});
|
||||
|
||||
it('re-renders a row when its event is redacted in place', () => {
|
||||
const { rerender } = renderTimeline();
|
||||
const before = rowRenders.count;
|
||||
|
||||
eventRedacted.current = true;
|
||||
rerender(<RoomTimeline room={room} editor={{} as Editor} />);
|
||||
|
||||
expect(rowRenders.count).toBeGreaterThan(before);
|
||||
});
|
||||
});
|
||||
|
||||
describe('unread read marker (normal sync)', () => {
|
||||
|
||||
@@ -291,6 +291,7 @@ const MemoizedTimelineItem = memo(
|
||||
prev.eventData.id === next.eventData.id &&
|
||||
// A filtered mid-timeline insert shifts this without changing `index`.
|
||||
prev.eventData.itemIndex === next.eventData.itemIndex &&
|
||||
prev.eventData.isRedacted === next.eventData.isRedacted &&
|
||||
prev.eventData.collapsed === next.eventData.collapsed &&
|
||||
prev.eventData.willRenderNewDivider === next.eventData.willRenderNewDivider &&
|
||||
prev.eventData.willRenderDayDivider === next.eventData.willRenderDayDivider &&
|
||||
@@ -1281,7 +1282,11 @@ export function RoomTimeline({
|
||||
>
|
||||
{(eventData, index) => (
|
||||
<MemoizedTimelineItem
|
||||
key={eventData ? eventData.id : `placeholder-${index}`}
|
||||
key={
|
||||
eventData
|
||||
? `${eventData.id}:${eventData.isRedacted ? 'redacted' : 'message'}`
|
||||
: `placeholder-${index}`
|
||||
}
|
||||
eventData={eventData}
|
||||
index={index}
|
||||
showLoadingPlaceholders={showLoadingPlaceholders}
|
||||
|
||||
@@ -101,6 +101,8 @@ export function RoomView({ eventId }: { eventId?: string }) {
|
||||
alive,
|
||||
focusOnCancel: !isMobileOrTablet(),
|
||||
});
|
||||
const onCancelEdit = useCallback(() => handleEdit(undefined), [handleEdit]);
|
||||
const onEditLastMessage = useCallback(() => editLastMessageRef.current?.(), []);
|
||||
|
||||
useDelayedEventsSupport();
|
||||
const delayedEventsSupported = useAtomValue(delayedEventsSupportedAtom);
|
||||
@@ -194,9 +196,9 @@ export function RoomView({ eventId }: { eventId?: string }) {
|
||||
roomId={roomId}
|
||||
fileDropContainerRef={roomViewRef}
|
||||
ref={roomInputRef}
|
||||
onEditLastMessage={() => editLastMessageRef.current?.()}
|
||||
onEditLastMessage={onEditLastMessage}
|
||||
editId={editId}
|
||||
onCancelEdit={() => handleEdit(undefined)}
|
||||
onCancelEdit={onCancelEdit}
|
||||
/>
|
||||
)}
|
||||
{!canMessage && (
|
||||
|
||||
@@ -231,6 +231,7 @@ export function ThreadDrawer({ room, threadRootId, onClose, overlay }: ThreadDra
|
||||
id: ev.getId() ?? `thread-reply-${idx}`,
|
||||
itemIndex: idx,
|
||||
mEvent: ev,
|
||||
isRedacted: ev.isRedacted(),
|
||||
timelineSet,
|
||||
eventSender: ev.getSender() ?? null,
|
||||
collapsed: false,
|
||||
|
||||
@@ -2,8 +2,11 @@ import type { IContent, IMentions } from '$types/matrix-sdk';
|
||||
import { MsgType, RelationType } from '$types/matrix-sdk';
|
||||
import { customHtmlEqualsPlainText } from '$components/editor';
|
||||
import { sanitizeText } from '$utils/sanitize';
|
||||
import type { PerMessageProfile } from '$hooks/usePerMessageProfile';
|
||||
import { convertPerMessageProfileToBeeperFormat } from '$hooks/usePerMessageProfile';
|
||||
import type { PerMessageProfileMsc4461 } from '$hooks/usePerMessageProfile';
|
||||
import {
|
||||
convertPerMessageProfileToBeeperFormat,
|
||||
stripPerMessageProfileFormattedBody,
|
||||
} from '$hooks/usePerMessageProfile';
|
||||
import { MATRIX_UNSTABLE_PER_MESSAGE_PROFILE_PROPERTY_NAME } from '$unstable/prefixes';
|
||||
|
||||
/**
|
||||
@@ -17,7 +20,8 @@ export function buildReplacementContent(
|
||||
eventId: string,
|
||||
mMentions: IMentions,
|
||||
linkPreviews: { matched_url: string }[],
|
||||
perMessageProfile: unknown
|
||||
perMessageProfile: unknown,
|
||||
pmpNoFallback: boolean
|
||||
): IContent {
|
||||
const pmpDisplayname =
|
||||
perMessageProfile !== null &&
|
||||
@@ -31,7 +35,7 @@ export function buildReplacementContent(
|
||||
let adjustedPlainText = plainText;
|
||||
let adjustedCustomHtml = customHtml;
|
||||
|
||||
if (pmpDisplayname) {
|
||||
if (!pmpNoFallback && pmpDisplayname) {
|
||||
const bodyPrefix = `${pmpDisplayname}: `;
|
||||
if (!adjustedPlainText.startsWith(bodyPrefix))
|
||||
adjustedPlainText = bodyPrefix + adjustedPlainText;
|
||||
@@ -100,7 +104,7 @@ export function buildReplacementContent(
|
||||
export function buildReplacementPmpContent(
|
||||
oldContent: IContent,
|
||||
eventId: string,
|
||||
newProfile: PerMessageProfile | undefined
|
||||
newProfile: PerMessageProfileMsc4461 | undefined
|
||||
) {
|
||||
const profileBeeperFormat =
|
||||
newProfile && convertPerMessageProfileToBeeperFormat(newProfile, true);
|
||||
@@ -111,17 +115,16 @@ export function buildReplacementPmpContent(
|
||||
let newPlainBody = plainBody?.replace(/^.*?: /, '');
|
||||
|
||||
const formattedBody = oldContent.formatted_body;
|
||||
let newFormattedBody = formattedBody?.replace(
|
||||
/^<strong\s+data-mx-profile-fallback[^>]*>.*?<\/strong>/,
|
||||
''
|
||||
);
|
||||
let newFormattedBody = formattedBody
|
||||
? stripPerMessageProfileFormattedBody(formattedBody)
|
||||
: undefined;
|
||||
|
||||
oldContent.formatted_body = newFormattedBody;
|
||||
oldContent.body = newPlainBody;
|
||||
}
|
||||
|
||||
if (newProfile) {
|
||||
const escapedName = sanitizeText(newProfile.name);
|
||||
const escapedName = sanitizeText(newProfile.displayname);
|
||||
const htmlPrefix = `<strong data-mx-profile-fallback>${escapedName}: </strong>`;
|
||||
|
||||
if (oldContent.formatted_body) {
|
||||
@@ -133,7 +136,7 @@ export function buildReplacementPmpContent(
|
||||
oldContent.formatted_body = `${htmlPrefix}${escapedBody}`;
|
||||
}
|
||||
|
||||
const pmpPrefix = `${newProfile.name}: `;
|
||||
const pmpPrefix = `${newProfile.displayname}: `;
|
||||
oldContent.body = pmpPrefix + oldContent.body;
|
||||
}
|
||||
|
||||
|
||||
@@ -0,0 +1,72 @@
|
||||
import { describe, expect, it } from 'vitest';
|
||||
import { createComposerController } from './composerController';
|
||||
|
||||
function deferred<T>() {
|
||||
let resolve!: (value: T) => void;
|
||||
const promise = new Promise<T>((res) => {
|
||||
resolve = res;
|
||||
});
|
||||
return { promise, resolve };
|
||||
}
|
||||
|
||||
describe('composer controller', () => {
|
||||
it('runs a later send only after a slow one finishes', async () => {
|
||||
const controller = createComposerController();
|
||||
const slow = deferred<void>();
|
||||
const order: string[] = [];
|
||||
|
||||
const slowSend = controller.enqueue(async () => {
|
||||
order.push('slow:start');
|
||||
await slow.promise;
|
||||
order.push('slow:end');
|
||||
});
|
||||
const nextSend = controller.enqueue(() => {
|
||||
order.push('next');
|
||||
});
|
||||
|
||||
await Promise.resolve();
|
||||
expect(order).toEqual(['slow:start']);
|
||||
slow.resolve();
|
||||
await Promise.all([slowSend, nextSend]);
|
||||
expect(order).toEqual(['slow:start', 'slow:end', 'next']);
|
||||
});
|
||||
|
||||
it('reports the composer as gone after disposal', async () => {
|
||||
const controller = createComposerController();
|
||||
const completion = deferred<void>();
|
||||
let cleanupCount = 0;
|
||||
|
||||
const send = controller.enqueue(async (isLive) => {
|
||||
await completion.promise;
|
||||
if (isLive()) cleanupCount += 1;
|
||||
});
|
||||
|
||||
await Promise.resolve();
|
||||
controller.dispose();
|
||||
completion.resolve();
|
||||
await send;
|
||||
|
||||
expect(cleanupCount).toBe(0);
|
||||
});
|
||||
|
||||
it('skips operations enqueued after disposal', async () => {
|
||||
const controller = createComposerController();
|
||||
let ran = false;
|
||||
|
||||
controller.dispose();
|
||||
|
||||
await expect(controller.enqueue(() => (ran = true))).resolves.toBeUndefined();
|
||||
expect(ran).toBe(false);
|
||||
});
|
||||
|
||||
it('advances the tail after a rejected operation', async () => {
|
||||
const controller = createComposerController();
|
||||
|
||||
await expect(
|
||||
controller.enqueue(() => {
|
||||
throw new Error('send failed');
|
||||
})
|
||||
).rejects.toThrow('send failed');
|
||||
await expect(controller.enqueue(() => 'completed')).resolves.toBe('completed');
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,40 @@
|
||||
export type ComposerOperation<T> = (isLive: () => boolean) => T | Promise<T>;
|
||||
|
||||
export interface ComposerController {
|
||||
enqueue<T>(operation: ComposerOperation<T>): Promise<T | undefined>;
|
||||
dispose(): void;
|
||||
}
|
||||
|
||||
/** Serializes composer sends so a slow send cannot interleave with the next one. */
|
||||
export const createComposerController = (): ComposerController => {
|
||||
let queueTail: Promise<void> = Promise.resolve();
|
||||
let disposed = false;
|
||||
const isLive = () => !disposed;
|
||||
|
||||
const enqueue = <T>(operation: ComposerOperation<T>): Promise<T | undefined> =>
|
||||
new Promise<T | undefined>((resolve, reject) => {
|
||||
const run = async () => {
|
||||
if (disposed) {
|
||||
resolve(undefined);
|
||||
return;
|
||||
}
|
||||
try {
|
||||
resolve(await operation(isLive));
|
||||
} catch (error) {
|
||||
reject(error);
|
||||
}
|
||||
};
|
||||
|
||||
queueTail = queueTail.then(run, run).then(
|
||||
() => undefined,
|
||||
() => undefined
|
||||
);
|
||||
});
|
||||
|
||||
return {
|
||||
enqueue,
|
||||
dispose: () => {
|
||||
disposed = true;
|
||||
},
|
||||
};
|
||||
};
|
||||
@@ -0,0 +1,211 @@
|
||||
import { beforeEach, describe, expect, it, vi } from 'vitest';
|
||||
import { BlockType, plainToEditorInput } from '$components/editor';
|
||||
import { Command, SHRUG } from '$hooks/useCommands';
|
||||
import type { MatrixClient, Room } from '$types/matrix-sdk';
|
||||
import { SerializableMap } from '$types/wrapper/SerializableMap';
|
||||
import type { MSC4459ImagePackReference } from '$types/matrix/common';
|
||||
import type { PKitProxyMessageHandler } from '$plugins/pluralkit-handler/PKitProxyMessageHandler';
|
||||
import type * as PerMessageProfileModule from '$hooks/usePerMessageProfile';
|
||||
import type { PerMessageProfileMsc4461 } from '$hooks/usePerMessageProfile';
|
||||
|
||||
const { profiles } = vi.hoisted(() => ({
|
||||
profiles: {
|
||||
account: undefined as PerMessageProfileMsc4461 | undefined,
|
||||
room: undefined as PerMessageProfileMsc4461 | undefined,
|
||||
},
|
||||
}));
|
||||
|
||||
vi.mock('$hooks/usePerMessageProfile', async (importOriginal) => ({
|
||||
...(await importOriginal<typeof PerMessageProfileModule>()),
|
||||
getCurrentlyUsedPerMessageProfileForAccount: () => Promise.resolve(profiles.account),
|
||||
getCurrentlyUsedPerMessageProfileForRoom: () => Promise.resolve(profiles.room),
|
||||
}));
|
||||
|
||||
const { buildOutgoingMessage } = await import('./composerMessage');
|
||||
|
||||
const ROOM_ID = '!room:example.org';
|
||||
|
||||
const room = {
|
||||
roomId: ROOM_ID,
|
||||
getMember: (userId: string) => ({ rawDisplayName: `Display ${userId}` }),
|
||||
} as unknown as Room;
|
||||
|
||||
const mx = {
|
||||
getUserId: () => '@me:example.org',
|
||||
getSafeUserId: () => '@me:example.org',
|
||||
getRoom: () => room,
|
||||
} as unknown as MatrixClient;
|
||||
|
||||
const noProxyHandler = {
|
||||
getPmpBasedOnMessage: () => Promise.resolve(undefined),
|
||||
stripProxyFromMessage: () => undefined,
|
||||
} as unknown as PKitProxyMessageHandler;
|
||||
|
||||
const profile = (id: string, displayname: string): PerMessageProfileMsc4461 => ({
|
||||
id,
|
||||
displayname,
|
||||
trigger: { prefix: [] },
|
||||
});
|
||||
|
||||
/** Mirrors how the editor represents a typed command: empty text node, then a command node. */
|
||||
const commandInput = (command: Command, rest = '') => [
|
||||
{
|
||||
type: BlockType.Paragraph as const,
|
||||
children: [
|
||||
{ text: '' },
|
||||
{ type: BlockType.Command as const, command, children: [{ text: '' }] },
|
||||
{ text: rest },
|
||||
],
|
||||
},
|
||||
];
|
||||
|
||||
const build = (
|
||||
input: string | ReturnType<typeof commandInput>,
|
||||
overrides: Partial<Parameters<typeof buildOutgoingMessage>[1]> = {}
|
||||
) =>
|
||||
buildOutgoingMessage(typeof input === 'string' ? plainToEditorInput(input) : input, {
|
||||
mx,
|
||||
room,
|
||||
roomId: ROOM_ID,
|
||||
nicknames: {},
|
||||
replyEvent: undefined,
|
||||
replyDraft: undefined,
|
||||
silentReply: false,
|
||||
settingsLinkBaseUrl: 'https://app.example',
|
||||
canSendReaction: true,
|
||||
pkCompatEnable: false,
|
||||
pmpProxyingEnable: false,
|
||||
pmpLatchingEnable: false,
|
||||
pmpNoFallback: false,
|
||||
latchedPersona: undefined,
|
||||
isPKCommand: () => false,
|
||||
pluralkitProxyMessageHandler: noProxyHandler,
|
||||
imagePacksUsed: new SerializableMap<string, MSC4459ImagePackReference>(),
|
||||
...overrides,
|
||||
});
|
||||
|
||||
beforeEach(() => {
|
||||
profiles.account = undefined;
|
||||
profiles.room = undefined;
|
||||
});
|
||||
|
||||
describe('buildOutgoingMessage', () => {
|
||||
it('builds a plain text message', async () => {
|
||||
const result = await build('hello world');
|
||||
expect(result).toMatchObject({ kind: 'message' });
|
||||
if (result.kind !== 'message') throw new Error('expected a message');
|
||||
expect(result.content.body).toBe('hello world');
|
||||
expect(result.content.msgtype).toBe('m.text');
|
||||
});
|
||||
|
||||
it('reports empty input instead of sending a blank message', async () => {
|
||||
await expect(build(' ')).resolves.toEqual({ kind: 'empty' });
|
||||
});
|
||||
|
||||
it('returns a quick-react descriptor rather than reacting itself', async () => {
|
||||
await expect(build('+#tada')).resolves.toEqual({ kind: 'quickReact', key: 'tada' });
|
||||
});
|
||||
|
||||
it('ignores quick-react syntax without permission to react', async () => {
|
||||
const result = await build('+#tada', { canSendReaction: false });
|
||||
expect(result.kind).toBe('message');
|
||||
});
|
||||
|
||||
it('returns a pk-command descriptor only when pk compat is on', async () => {
|
||||
await expect(
|
||||
build('pk;switch', { pkCompatEnable: false, isPKCommand: () => true })
|
||||
).resolves.toMatchObject({ kind: 'message' });
|
||||
await expect(
|
||||
build('pk;switch', { pkCompatEnable: true, isPKCommand: () => true })
|
||||
).resolves.toEqual({ kind: 'pkCommand', plainText: 'pk;switch' });
|
||||
});
|
||||
|
||||
it('prefixes shrug and emits an emote for /me', async () => {
|
||||
const shrug = await build(commandInput(Command.Shrug, ' take it'));
|
||||
if (shrug.kind !== 'message') throw new Error('expected a message');
|
||||
expect(shrug.content.body.startsWith(SHRUG)).toBe(true);
|
||||
|
||||
const emote = await build(commandInput(Command.Me, ' waves'));
|
||||
if (emote.kind !== 'message') throw new Error('expected a message');
|
||||
expect(emote.content.msgtype).toBe('m.emote');
|
||||
expect(emote.content.body).toBe('waves');
|
||||
});
|
||||
|
||||
it('hands unhandled commands back to the caller to execute', async () => {
|
||||
const result = await build(commandInput(Command.Poll));
|
||||
expect(result).toMatchObject({ kind: 'command', command: Command.Poll });
|
||||
});
|
||||
|
||||
it('mentions the replied-to user unless the reply is silent', async () => {
|
||||
const replyDraft = { userId: '@other:example.org', eventId: '$reply', body: 'hi' };
|
||||
|
||||
const loud = await build('answer', { replyDraft });
|
||||
if (loud.kind !== 'message') throw new Error('expected a message');
|
||||
expect(loud.content['m.mentions']?.user_ids).toContain('@other:example.org');
|
||||
|
||||
const silent = await build('answer', { replyDraft, silentReply: true });
|
||||
if (silent.kind !== 'message') throw new Error('expected a message');
|
||||
expect(silent.content['m.mentions']?.user_ids ?? []).not.toContain('@other:example.org');
|
||||
});
|
||||
|
||||
it('adds the spec-required fallback prefix for a named per-message profile', async () => {
|
||||
profiles.room = profile('p1', 'Alter');
|
||||
const result = await build('hello');
|
||||
if (result.kind !== 'message') throw new Error('expected a message');
|
||||
expect(result.content.body).toBe('Alter: hello');
|
||||
expect(result.content.formatted_body).toBe(
|
||||
'<strong data-mx-profile-fallback>Alter: </strong>hello'
|
||||
);
|
||||
});
|
||||
|
||||
it('does not double-prefix a body that already carries the fallback', async () => {
|
||||
profiles.room = profile('p1', 'Alter');
|
||||
const result = await build('Alter: hello');
|
||||
if (result.kind !== 'message') throw new Error('expected a message');
|
||||
expect(result.content.body).toBe('Alter: hello');
|
||||
expect(result.content.formatted_body).toBe(
|
||||
'<strong data-mx-profile-fallback>Alter: </strong>hello'
|
||||
);
|
||||
});
|
||||
|
||||
it('prefers the room profile over the account profile', async () => {
|
||||
profiles.account = profile('global', 'Global');
|
||||
profiles.room = profile('scoped', 'Scoped');
|
||||
const result = await build('hello');
|
||||
if (result.kind !== 'message') throw new Error('expected a message');
|
||||
expect(result.content.body).toBe('Scoped: hello');
|
||||
});
|
||||
|
||||
it('omits an unnamed profile fallback but still tags the profile', async () => {
|
||||
profiles.account = profile('p1', '');
|
||||
const result = await build('hello');
|
||||
if (result.kind !== 'message') throw new Error('expected a message');
|
||||
expect(result.content.body).toBe('hello');
|
||||
});
|
||||
|
||||
it('strips a pluralkit proxy wrapper and lets its profile win', async () => {
|
||||
const proxied = profile('proxy', 'Proxied');
|
||||
const handler = {
|
||||
getPmpBasedOnMessage: () => Promise.resolve(proxied),
|
||||
stripProxyFromMessage: (text: string) => text.replace(/^A:\s*/, ''),
|
||||
} as unknown as PKitProxyMessageHandler;
|
||||
profiles.account = profile('global', 'Global');
|
||||
|
||||
const result = await build('A: hello there', {
|
||||
pmpProxyingEnable: true,
|
||||
pluralkitProxyMessageHandler: handler,
|
||||
});
|
||||
if (result.kind !== 'message') throw new Error('expected a message');
|
||||
// The wrapper must never reach the wire, and the proxy's profile wins.
|
||||
expect(result.content.body).toBe('Proxied: hello there');
|
||||
});
|
||||
|
||||
it('records embedded link previews for urls in the body', async () => {
|
||||
const result = await build('see https://example.com/page');
|
||||
if (result.kind !== 'message') throw new Error('expected a message');
|
||||
const previews = result.content['com.beeper.linkpreviews'] as
|
||||
| { matched_url: string }[]
|
||||
| undefined;
|
||||
expect(previews?.map((preview) => preview.matched_url)).toContain('https://example.com/page');
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,336 @@
|
||||
import type { Editor } from 'slate';
|
||||
import type { IContent, MatrixEvent, Room } from '$types/matrix-sdk';
|
||||
import { MsgType } from '$types/matrix-sdk';
|
||||
import type { MatrixClient, RoomMessageEventContent } from '$types/matrix-sdk';
|
||||
import {
|
||||
BlockType,
|
||||
customHtmlEqualsPlainText,
|
||||
getBeginCommand,
|
||||
getLinks,
|
||||
getMentions,
|
||||
plainToEditorInput,
|
||||
toMatrixCustomHTML,
|
||||
toPlainText,
|
||||
trimCommand,
|
||||
trimCustomHtml,
|
||||
} from '$components/editor';
|
||||
import { sanitizeText } from '$utils/sanitize';
|
||||
import { getMentionContent } from '$utils/room/relations';
|
||||
import type { IReplyDraft } from '$state/room/roomInputDrafts';
|
||||
import {
|
||||
convertPerMessageProfileToBeeperFormat,
|
||||
getCurrentlyUsedPerMessageProfileForAccount,
|
||||
getCurrentlyUsedPerMessageProfileForRoom,
|
||||
type PerMessageProfileMsc4461,
|
||||
} from '$hooks/usePerMessageProfile';
|
||||
import * as prefix from '$unstable/prefixes';
|
||||
import { outgoingMessageTransforms } from './outgoingMessageTransforms';
|
||||
import { buildReplacementContent } from './buildReplacementContent';
|
||||
import { Command, SHRUG, TABLEFLIP, UNFLIP } from '$hooks/useCommands';
|
||||
import type { PKitProxyMessageHandler } from '$plugins/pluralkit-handler/PKitProxyMessageHandler';
|
||||
import type { MSC4459ImagePackReference } from '$types/matrix/common';
|
||||
import type { SerializableMap } from '$types/wrapper/SerializableMap';
|
||||
|
||||
export type MessageContent = IContent & Pick<RoomMessageEventContent, 'msgtype' | 'body'>;
|
||||
|
||||
/**
|
||||
* Branches needing React state (opening a picker, running a command, reacting) are
|
||||
* returned as descriptors rather than executed, keeping this module pure.
|
||||
*/
|
||||
export type OutgoingMessage =
|
||||
| { kind: 'message'; content: MessageContent; latchPersona?: PerMessageProfileMsc4461 }
|
||||
| { kind: 'quickReact'; key: string }
|
||||
| { kind: 'pkCommand'; plainText: string }
|
||||
| { kind: 'command'; command: Command; plainText: string; customHtml: string }
|
||||
| { kind: 'gifSearch'; query: string }
|
||||
| { kind: 'empty' };
|
||||
|
||||
export interface BuildOutgoingMessageDeps {
|
||||
mx: MatrixClient;
|
||||
room: Room;
|
||||
roomId: string;
|
||||
/** userId -> nickname, stripped from the body and replaced with the real display name. */
|
||||
nicknames: Record<string, unknown>;
|
||||
replyEvent: MatrixEvent | undefined;
|
||||
replyDraft: IReplyDraft | undefined;
|
||||
silentReply: boolean;
|
||||
settingsLinkBaseUrl: string;
|
||||
canSendReaction: boolean;
|
||||
pkCompatEnable: boolean;
|
||||
pmpProxyingEnable: boolean;
|
||||
pmpLatchingEnable: boolean;
|
||||
pmpNoFallback: boolean;
|
||||
/** Persona latched by an earlier proxied message in this room. */
|
||||
latchedPersona: PerMessageProfileMsc4461 | undefined;
|
||||
isPKCommand: (plainText: string) => boolean;
|
||||
pluralkitProxyMessageHandler: PKitProxyMessageHandler;
|
||||
imagePacksUsed: SerializableMap<string, MSC4459ImagePackReference>;
|
||||
}
|
||||
|
||||
const resolveNickname = (
|
||||
room: Room,
|
||||
nicknames: Record<string, unknown>,
|
||||
userId: string
|
||||
): string | undefined => {
|
||||
const nick = nicknames[userId];
|
||||
if (typeof nick !== 'string' || nick.length === 0) return undefined;
|
||||
return room.getMember(userId)?.rawDisplayName ?? userId;
|
||||
};
|
||||
|
||||
// Nicknames are local-only, so they are swapped back to real display names before the
|
||||
// body goes out, keeping server-side mention processing correct.
|
||||
const buildNicknameReplacement = (
|
||||
children: Editor['children'],
|
||||
{ mx, room, roomId, nicknames, replyEvent }: BuildOutgoingMessageDeps
|
||||
): Map<RegExp, string> => {
|
||||
const replacement = new Map<RegExp, string>();
|
||||
const add = (userId: string) => {
|
||||
const displayName = resolveNickname(room, nicknames, userId);
|
||||
if (displayName)
|
||||
replacement.set(new RegExp(`@?${nicknames[userId] as string}`, 'g'), displayName);
|
||||
};
|
||||
|
||||
const senderId = replyEvent?.getSender();
|
||||
if (senderId) add(senderId);
|
||||
getMentions(mx, roomId, { children } as Editor)?.users?.forEach(add);
|
||||
|
||||
return replacement;
|
||||
};
|
||||
|
||||
const stripCommandNode = (children: Editor['children']): Editor['children'] => {
|
||||
const firstPara = children[0];
|
||||
if (
|
||||
firstPara &&
|
||||
'type' in firstPara &&
|
||||
firstPara.type === BlockType.Paragraph &&
|
||||
firstPara.children.length >= 2
|
||||
) {
|
||||
return [{ ...firstPara, children: firstPara.children.slice(2) }, ...children.slice(1)];
|
||||
}
|
||||
return children;
|
||||
};
|
||||
|
||||
const applyPerMessageProfileFallback = (
|
||||
content: MessageContent,
|
||||
profile: PerMessageProfileMsc4461,
|
||||
noFallback: boolean
|
||||
) => {
|
||||
content[prefix.MATRIX_UNSTABLE_PER_MESSAGE_PROFILE_PROPERTY_NAME] =
|
||||
convertPerMessageProfileToBeeperFormat(profile, !noFallback);
|
||||
if (noFallback || profile.displayname.trim() === '') return;
|
||||
|
||||
// Per spec a per-message profile must ship a fallback prefix for clients that ignore it.
|
||||
const pmpPrefix = `${profile.displayname}: `;
|
||||
const bodyWithoutFallback = content.body.startsWith(pmpPrefix)
|
||||
? content.body.slice(pmpPrefix.length)
|
||||
: content.body;
|
||||
// guard against double-prefixing when the fallback is already present
|
||||
if (!content.body.startsWith(pmpPrefix)) content.body = pmpPrefix + content.body;
|
||||
|
||||
const htmlPrefix = `<strong data-mx-profile-fallback>${sanitizeText(profile.displayname)}: </strong>`;
|
||||
if (content.formatted_body && !content.formatted_body.startsWith(htmlPrefix)) {
|
||||
content.formatted_body = htmlPrefix + content.formatted_body;
|
||||
} else {
|
||||
// we don't have a formatted body, but the fallback needs one
|
||||
content.format = 'org.matrix.custom.html';
|
||||
const escapedBody = sanitizeText(bodyWithoutFallback).replaceAll('\n', '<br/>');
|
||||
content.formatted_body = `${htmlPrefix}${escapedBody}`;
|
||||
}
|
||||
};
|
||||
|
||||
export async function buildOutgoingMessage(
|
||||
children: Editor['children'],
|
||||
deps: BuildOutgoingMessageDeps
|
||||
): Promise<OutgoingMessage> {
|
||||
const {
|
||||
mx,
|
||||
room,
|
||||
roomId,
|
||||
replyDraft,
|
||||
silentReply,
|
||||
settingsLinkBaseUrl,
|
||||
canSendReaction,
|
||||
pkCompatEnable,
|
||||
pmpProxyingEnable,
|
||||
pmpLatchingEnable,
|
||||
pmpNoFallback,
|
||||
latchedPersona,
|
||||
isPKCommand,
|
||||
pluralkitProxyMessageHandler,
|
||||
imagePacksUsed,
|
||||
} = deps;
|
||||
|
||||
const commandName = getBeginCommand({ children } as Editor);
|
||||
const nicknameReplacement = buildNicknameReplacement(children, deps);
|
||||
const transformContext = { isMarkdown: true, settingsLinkBaseUrl };
|
||||
|
||||
const runTransforms = (input: Editor['children']): Editor['children'] => {
|
||||
let output = input;
|
||||
outgoingMessageTransforms.forEach((transform) => {
|
||||
if (!transform.shouldApply(output, transformContext)) return;
|
||||
output = transform.apply(output, transformContext);
|
||||
});
|
||||
return output;
|
||||
};
|
||||
const forEmote = commandName === Command.Me || commandName === Command.RainbowMe;
|
||||
const serializeHtml = (input: Editor['children']) =>
|
||||
trimCustomHtml(
|
||||
toMatrixCustomHTML(input, {
|
||||
stripNickname: true,
|
||||
nickNameReplacement: nicknameReplacement,
|
||||
forEmote,
|
||||
room,
|
||||
})
|
||||
);
|
||||
|
||||
let serializedChildren = runTransforms(commandName ? stripCommandNode(children) : children);
|
||||
let plainText = toPlainText(serializedChildren, true, true, nicknameReplacement).trim();
|
||||
let customHtml = serializeHtml(serializedChildren);
|
||||
let msgType = MsgType.Text;
|
||||
|
||||
if (canSendReaction && plainText.startsWith('+#')) {
|
||||
return { kind: 'quickReact', key: plainText.substring(2) };
|
||||
}
|
||||
if (pkCompatEnable && isPKCommand(plainText)) {
|
||||
return { kind: 'pkCommand', plainText };
|
||||
}
|
||||
const rawGifCommand =
|
||||
commandName === undefined ? plainText.match(/^\/gif(?:\s+(.*))?$/i) : undefined;
|
||||
if (rawGifCommand) return { kind: 'gifSearch', query: rawGifCommand[1] ?? '' };
|
||||
|
||||
if (commandName) {
|
||||
plainText = trimCommand(commandName, plainText);
|
||||
customHtml = trimCommand(commandName, customHtml);
|
||||
}
|
||||
if (commandName === Command.Me) {
|
||||
msgType = MsgType.Emote;
|
||||
} else if (commandName === Command.Notice) {
|
||||
msgType = MsgType.Notice;
|
||||
} else if (commandName === Command.Shrug) {
|
||||
plainText = `${SHRUG} ${plainText}`;
|
||||
customHtml = `${SHRUG} ${customHtml}`;
|
||||
} else if (commandName === Command.TableFlip) {
|
||||
plainText = `${TABLEFLIP} ${plainText}`;
|
||||
customHtml = `${TABLEFLIP} ${customHtml}`;
|
||||
} else if (commandName === Command.UnFlip) {
|
||||
plainText = `${UNFLIP} ${plainText}`;
|
||||
customHtml = `${UNFLIP} ${customHtml}`;
|
||||
} else if (commandName) {
|
||||
if (commandName === 'gif') return { kind: 'gifSearch', query: plainText };
|
||||
return { kind: 'command', command: commandName as Command, plainText, customHtml };
|
||||
}
|
||||
|
||||
if (plainText === '') return { kind: 'empty' };
|
||||
|
||||
// PluralKit-style proxy wrappers must be stripped before building `content`, otherwise
|
||||
// the wrapper itself gets sent verbatim.
|
||||
let proxiedPerMessageProfile: PerMessageProfileMsc4461 | undefined;
|
||||
let proxyStripped = false;
|
||||
if (pmpProxyingEnable) {
|
||||
proxiedPerMessageProfile = await pluralkitProxyMessageHandler.getPmpBasedOnMessage(plainText);
|
||||
if (proxiedPerMessageProfile) {
|
||||
// plainText has spoilers stripped, which breaks spoilers carrying a proxy tag, so
|
||||
// match the proxy against an unsanitized copy instead.
|
||||
const unsanitizedPlainText = toPlainText(
|
||||
serializedChildren,
|
||||
true,
|
||||
false,
|
||||
nicknameReplacement
|
||||
).trim();
|
||||
const stripped = pluralkitProxyMessageHandler.stripProxyFromMessage(unsanitizedPlainText);
|
||||
if (stripped !== undefined) {
|
||||
proxyStripped = true;
|
||||
// Re-run the normal pipeline so a proxied message is parsed like any other.
|
||||
serializedChildren = runTransforms(plainToEditorInput(stripped));
|
||||
plainText = toPlainText(serializedChildren, true, true, nicknameReplacement).trim();
|
||||
customHtml = serializeHtml(serializedChildren);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
const mentionData = getMentions(mx, roomId, { children } as Editor);
|
||||
if (replyDraft && !silentReply) mentionData.users.add(replyDraft.userId);
|
||||
|
||||
const content: MessageContent = { msgtype: msgType, body: plainText };
|
||||
content['m.mentions'] = getMentionContent(Array.from(mentionData.users), mentionData.room);
|
||||
content[prefix.MATRIX_UNSTABLE_IMAGE_SOURCE_PACK_PROPERTY_NAME] = imagePacksUsed.toJSON();
|
||||
content[prefix.MATRIX_UNSTABLE_EMBEDDED_LINK_PREVIEW_PROPERTY_NAME] = (
|
||||
getLinks(serializedChildren) ?? []
|
||||
).map((matched_url) => ({ matched_url }));
|
||||
|
||||
if (replyDraft || !customHtmlEqualsPlainText(customHtml, plainText)) {
|
||||
content.format = 'org.matrix.custom.html';
|
||||
content.formatted_body = customHtml;
|
||||
}
|
||||
|
||||
const [globalProfile, roomProfile] = await Promise.all([
|
||||
getCurrentlyUsedPerMessageProfileForAccount(mx),
|
||||
getCurrentlyUsedPerMessageProfileForRoom(mx, roomId),
|
||||
]);
|
||||
const perMessageProfile =
|
||||
proxiedPerMessageProfile ?? latchedPersona ?? roomProfile ?? globalProfile;
|
||||
if (perMessageProfile) applyPerMessageProfileFallback(content, perMessageProfile, pmpNoFallback);
|
||||
|
||||
return {
|
||||
kind: 'message',
|
||||
content,
|
||||
// Only a proxy we actually stripped counts as used, so a wrapper we failed to
|
||||
// strip does not latch the persona for the rest of the room.
|
||||
latchPersona: pmpLatchingEnable && proxyStripped ? proxiedPerMessageProfile : undefined,
|
||||
};
|
||||
}
|
||||
|
||||
export interface BuildEditReplacementDeps {
|
||||
mx: MatrixClient;
|
||||
room: Room;
|
||||
roomId: string;
|
||||
editingEvent: MatrixEvent;
|
||||
/** Content of the latest edit, so a re-edit builds on the current body. */
|
||||
currentContent: IContent;
|
||||
pmpNoFallback: boolean;
|
||||
}
|
||||
|
||||
/** Returns undefined when there is nothing to send, which cancels the edit. */
|
||||
export function buildEditReplacement(
|
||||
children: Editor['children'],
|
||||
{ mx, room, roomId, editingEvent, currentContent, pmpNoFallback }: BuildEditReplacementDeps
|
||||
): IContent | undefined {
|
||||
const plainText = toPlainText(children).trim();
|
||||
if (!plainText) return undefined;
|
||||
|
||||
const eventId = editingEvent.getId();
|
||||
if (!eventId) return undefined;
|
||||
|
||||
const oldContent = editingEvent.getContent();
|
||||
const customHtml = trimCustomHtml(
|
||||
toMatrixCustomHTML(children, {
|
||||
forEmote: oldContent.msgtype === MsgType.Emote,
|
||||
room,
|
||||
})
|
||||
);
|
||||
|
||||
const mentionData = getMentions(mx, roomId, { children } as Editor);
|
||||
const previousMentions = currentContent['m.mentions'];
|
||||
if (
|
||||
previousMentions &&
|
||||
typeof previousMentions === 'object' &&
|
||||
'user_ids' in previousMentions &&
|
||||
Array.isArray(previousMentions.user_ids)
|
||||
) {
|
||||
previousMentions.user_ids.forEach((userId) => {
|
||||
if (typeof userId === 'string') mentionData.users.add(userId);
|
||||
});
|
||||
}
|
||||
|
||||
return buildReplacementContent(
|
||||
oldContent,
|
||||
plainText,
|
||||
customHtml,
|
||||
eventId,
|
||||
getMentionContent(Array.from(mentionData.users), mentionData.room),
|
||||
(getLinks(children) ?? []).map((matched_url) => ({ matched_url })),
|
||||
currentContent['com.beeper.per_message_profile'] ??
|
||||
oldContent['com.beeper.per_message_profile'],
|
||||
pmpNoFallback
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,101 @@
|
||||
/* oxlint-disable typescript/no-explicit-any, react/void-dom-elements-no-children, vitest/require-mock-type-parameters, unicorn/consistent-function-scoping, typescript/no-extraneous-class */
|
||||
|
||||
import { fireEvent, render, screen, waitFor } from '@testing-library/react';
|
||||
import { describe, expect, it, vi } from 'vitest';
|
||||
import { LocationDialog } from './LocationDialog';
|
||||
|
||||
vi.mock('folds', () => {
|
||||
const div = ({ children, ...props }: any) => <div {...props}>{children}</div>;
|
||||
const button = ({ children, ...props }: any) => <button {...props}>{children}</button>;
|
||||
return {
|
||||
Dialog: div,
|
||||
Header: div,
|
||||
Box: div,
|
||||
Text: div,
|
||||
IconButton: button,
|
||||
Button: button,
|
||||
Input: (props: any) => <input {...props} />,
|
||||
Chip: button,
|
||||
color: { Critical: { OnContainer: 'red' } },
|
||||
};
|
||||
});
|
||||
|
||||
vi.mock('@phosphor-icons/react', () => ({
|
||||
ClipboardIcon: () => null,
|
||||
MapPinAreaIcon: () => null,
|
||||
MapPinLineIcon: () => null,
|
||||
}));
|
||||
|
||||
vi.mock('$components/icons/phosphor', () => ({
|
||||
chipIcon: () => null,
|
||||
composerIcon: () => null,
|
||||
Warning: 'Warning',
|
||||
X: 'X',
|
||||
}));
|
||||
|
||||
vi.mock('$components/modal-overlay/ModalOverlay', () => ({
|
||||
ModalOverlay: ({ children }: any) => <div>{children}</div>,
|
||||
}));
|
||||
|
||||
vi.mock('$state/settings', () => ({ settingsAtom: {} }));
|
||||
vi.mock('$state/hooks/settings', () => ({
|
||||
useSetting: (_atom: unknown, key: string) => [key === 'showInteractiveMap', vi.fn()],
|
||||
}));
|
||||
vi.mock('$utils/dom', () => ({ readClipboardText: vi.fn() }));
|
||||
vi.mock('react-leaflet', () => ({
|
||||
MapContainer: ({ children }: any) => <div>{children}</div>,
|
||||
Marker: () => null,
|
||||
TileLayer: () => null,
|
||||
useMapEvents: () => null,
|
||||
}));
|
||||
|
||||
vi.mock('leaflet', () => {
|
||||
class Icon {}
|
||||
return {
|
||||
default: { Icon, Marker: class Marker {}, marker: () => ({ addTo: () => ({}) }) },
|
||||
Icon,
|
||||
};
|
||||
});
|
||||
|
||||
describe('LocationDialog', () => {
|
||||
it('awaits the content callback and only closes after success', async () => {
|
||||
let resolveSubmit!: () => void;
|
||||
const onSubmit = vi.fn(
|
||||
() =>
|
||||
new Promise<void>((resolve) => {
|
||||
resolveSubmit = resolve;
|
||||
})
|
||||
);
|
||||
const onCancel = vi.fn();
|
||||
const room = { hasEncryptionStateEvent: () => false } as any;
|
||||
|
||||
render(<LocationDialog room={room} onCancel={onCancel} onSubmit={onSubmit} />);
|
||||
const submit = screen.getByRole('button', { name: 'Share Location' });
|
||||
fireEvent.click(submit);
|
||||
fireEvent.click(submit);
|
||||
|
||||
expect(onSubmit).toHaveBeenCalledTimes(1);
|
||||
expect(onCancel).not.toHaveBeenCalled();
|
||||
expect(submit).toBeDisabled();
|
||||
expect((onSubmit as any).mock.calls[0]?.[0]).toMatchObject({
|
||||
msgtype: 'm.location',
|
||||
geo_uri: expect.stringMatching(/^geo:/),
|
||||
});
|
||||
|
||||
resolveSubmit();
|
||||
await waitFor(() => expect(onCancel).toHaveBeenCalledTimes(1));
|
||||
});
|
||||
|
||||
it('shows a retryable error when submission fails', async () => {
|
||||
const onSubmit = vi.fn().mockRejectedValueOnce(new Error('Send failed'));
|
||||
const onCancel = vi.fn();
|
||||
const room = { hasEncryptionStateEvent: () => false } as any;
|
||||
|
||||
render(<LocationDialog room={room} onCancel={onCancel} onSubmit={onSubmit} />);
|
||||
fireEvent.click(screen.getByRole('button', { name: 'Share Location' }));
|
||||
|
||||
await waitFor(() => expect(screen.getByText('Send failed')).toBeInTheDocument());
|
||||
expect(onCancel).not.toHaveBeenCalled();
|
||||
expect(screen.getByRole('button', { name: 'Share Location' })).not.toBeDisabled();
|
||||
});
|
||||
});
|
||||
@@ -1,17 +1,14 @@
|
||||
import { Dialog, Header, Box, Text, IconButton, Button, Input, Chip } from 'folds';
|
||||
import { Dialog, Header, Box, Text, IconButton, Button, Input, Chip, color } from 'folds';
|
||||
import { ClipboardIcon, MapPinAreaIcon, MapPinLineIcon } from '@phosphor-icons/react';
|
||||
import { chipIcon, composerIcon, Warning, X } from '$components/icons/phosphor';
|
||||
import { readClipboardText } from '$utils/dom';
|
||||
import type { IContent, MatrixClient, Room } from 'matrix-js-sdk';
|
||||
import type { IContent, Room } from 'matrix-js-sdk';
|
||||
import * as css from './LocationDialog.css';
|
||||
import type { IReplyDraft } from '$state/room/roomInputDrafts';
|
||||
import { MapContainer, Marker, TileLayer, useMapEvents } from 'react-leaflet';
|
||||
import 'leaflet/dist/leaflet.css';
|
||||
import { useCallback, useEffect, useRef, useState, type ChangeEventHandler } from 'react';
|
||||
import type { LatLngLiteral } from 'leaflet';
|
||||
import L from 'leaflet';
|
||||
import { getReplyContent } from '../RoomInput';
|
||||
import type { RoomMessageEventContent } from '$types/matrix-sdk';
|
||||
import { MsgType } from '$types/matrix-sdk';
|
||||
import { settingsAtom } from '$state/settings';
|
||||
import { useSetting } from '$state/hooks/settings';
|
||||
@@ -85,10 +82,8 @@ export function filterLocationString(result: string) {
|
||||
|
||||
type LocationDialogProps = {
|
||||
onCancel: () => void;
|
||||
mx: MatrixClient;
|
||||
onSubmit: (content: IContent) => Promise<void>;
|
||||
room: Room;
|
||||
replyDraft?: IReplyDraft;
|
||||
clearReplyDraft?: () => void;
|
||||
};
|
||||
|
||||
export enum LocationErrors {
|
||||
@@ -106,13 +101,7 @@ export type LocationPoint = {
|
||||
lon?: number;
|
||||
};
|
||||
|
||||
export function LocationDialog({
|
||||
onCancel,
|
||||
mx,
|
||||
room,
|
||||
replyDraft,
|
||||
clearReplyDraft,
|
||||
}: LocationDialogProps) {
|
||||
export function LocationDialog({ onCancel, onSubmit, room }: LocationDialogProps) {
|
||||
const [showInteractiveMap] = useSetting(settingsAtom, 'showInteractiveMap');
|
||||
const [showEncInteractiveMap] = useSetting(settingsAtom, 'showEncInteractiveMap');
|
||||
const showMaps = room.hasEncryptionStateEvent() ? showEncInteractiveMap : showInteractiveMap;
|
||||
@@ -125,6 +114,8 @@ export function LocationDialog({
|
||||
const [pinPosition, setPinPosition] = useState<L.LatLngLiteral>(initCoords);
|
||||
const zoom = useRef<number>(2);
|
||||
const [locationError, setLocationError] = useState<LocationErrors>(LocationErrors.none);
|
||||
const [submitError, setSubmitError] = useState<string | undefined>(undefined);
|
||||
const [isSubmitting, setIsSubmitting] = useState(false);
|
||||
|
||||
const [map, setMap] = useState<L.Map | null>(null);
|
||||
|
||||
@@ -235,7 +226,8 @@ export function LocationDialog({
|
||||
}
|
||||
};
|
||||
|
||||
const handleSubmit = () => {
|
||||
const handleSubmit = async () => {
|
||||
if (isSubmitting) return;
|
||||
const mlat = pinPosition.lat.toFixed(6);
|
||||
const mlon = pinPosition.lng.toFixed(6);
|
||||
const content: IContent = {
|
||||
@@ -243,13 +235,18 @@ export function LocationDialog({
|
||||
geo_uri: `geo:${mlat},${mlon};u=0`,
|
||||
body: `https://www.openstreetmap.org/?mlat=${mlat}&mlon=${mlon}#map=16/${mlat}/${mlon}"`,
|
||||
};
|
||||
if (replyDraft && clearReplyDraft) {
|
||||
content['m.relates_to'] = getReplyContent(replyDraft, room);
|
||||
clearReplyDraft();
|
||||
}
|
||||
mx.sendMessage(room.roomId, content as RoomMessageEventContent).then(() => {
|
||||
setSubmitError(undefined);
|
||||
setIsSubmitting(true);
|
||||
try {
|
||||
await onSubmit(content);
|
||||
onCancel();
|
||||
});
|
||||
} catch (err) {
|
||||
setSubmitError(
|
||||
err instanceof Error ? err.message : 'Failed to share location. Please try again.'
|
||||
);
|
||||
} finally {
|
||||
setIsSubmitting(false);
|
||||
}
|
||||
};
|
||||
|
||||
return (
|
||||
@@ -258,7 +255,7 @@ export function LocationDialog({
|
||||
<Header className={css.LocationDialogHeader} variant="Surface" size="500">
|
||||
<Box grow="Yes" gap="200">
|
||||
<MapPinLineIcon size="20" />
|
||||
<Text size="H4">{`Share Location ${replyDraft ? '(reply / thread)' : ''}`} </Text>
|
||||
<Text size="H4">Share Location</Text>
|
||||
</Box>
|
||||
<IconButton
|
||||
size="300"
|
||||
@@ -372,9 +369,15 @@ export function LocationDialog({
|
||||
title="Share Location"
|
||||
aria-label="Share Location"
|
||||
onClick={handleSubmit}
|
||||
disabled={isSubmitting}
|
||||
>
|
||||
<Text size="B400">Share Location</Text>
|
||||
</Button>
|
||||
{!!submitError && (
|
||||
<Text align="Center" size="B500" style={{ color: color.Critical.OnContainer }}>
|
||||
{submitError}
|
||||
</Text>
|
||||
)}
|
||||
</Box>
|
||||
</Dialog>
|
||||
</ModalOverlay>
|
||||
|
||||
@@ -5,8 +5,11 @@ import { useEffect, useState } from 'react';
|
||||
|
||||
import { useMatrixClient } from '$hooks/useMatrixClient';
|
||||
import { scheduleDecrypt } from '$utils/decryptScheduler';
|
||||
import { createDebugLogger } from '$utils/debugLogger';
|
||||
import * as Sentry from '@sentry/react';
|
||||
|
||||
const debugLog = createDebugLogger('EncryptedContent');
|
||||
|
||||
type EncryptedContentProps = {
|
||||
mEvent: MatrixEvent;
|
||||
children: () => ReactNode;
|
||||
@@ -39,6 +42,12 @@ export function EncryptedContent({ mEvent, children }: EncryptedContentProps) {
|
||||
toggleEncrypted(mEvent.getType() === (EventType.RoomMessageEncrypted as string));
|
||||
const handleDecrypted: MatrixEventHandlerMap[MatrixEventEvent.Decrypted] = (event) => {
|
||||
if (event.isDecryptionFailure()) {
|
||||
debugLog.error('error', 'Failed to decrypt room event', {
|
||||
eventId: event.getId(),
|
||||
roomId: event.getRoomId(),
|
||||
sender: event.getSender(),
|
||||
reason: event.decryptionFailureReason ?? 'UNKNOWN_ERROR',
|
||||
});
|
||||
Sentry.metrics.count('sable.decryption.failure', 1, {
|
||||
attributes: { reason: event.decryptionFailureReason ?? 'UNKNOWN_ERROR' },
|
||||
});
|
||||
|
||||
@@ -133,6 +133,7 @@ export type MessageProps = {
|
||||
|
||||
import { useMenuAnchor } from '$hooks/useMenuAnchor';
|
||||
import { ThemeKind, useActiveTheme } from '$hooks/useTheme';
|
||||
import { useAccessibleNameColor } from '$hooks/useAccessibleNameColor';
|
||||
import { shouldIgnoreMessageLongPress } from './messageTouch';
|
||||
|
||||
const clamp = (str: string, len: number) => (str.length > len ? `${str.slice(0, len)}...` : str);
|
||||
@@ -458,8 +459,8 @@ function MessageInternal(
|
||||
|
||||
const pmpNameColor = useMemo(() => {
|
||||
if (!renderPersonaColors) return undefined;
|
||||
const pmpNameColorLight = parsedPMPContent?.colors?.on_light;
|
||||
const pmpNameColorDark = parsedPMPContent?.colors?.on_dark;
|
||||
const pmpNameColorLight = parsedPMPContent?.['eu.she-a.color']?.on_light;
|
||||
const pmpNameColorDark = parsedPMPContent?.['eu.she-a.color']?.on_dark;
|
||||
|
||||
return activeTheme.kind === ThemeKind.Dark ? pmpNameColorDark : pmpNameColorLight;
|
||||
}, [parsedPMPContent, activeTheme, renderPersonaColors]);
|
||||
@@ -468,7 +469,7 @@ function MessageInternal(
|
||||
* boolean to indicate wheather we should indicate to the user that it is a pmp
|
||||
* We want to not show it, when the name is unset, or whitespace only
|
||||
*/
|
||||
const showPmPInfo = parsedPMPContent?.name && parsedPMPContent.name?.trim() !== '';
|
||||
const showPmPInfo = parsedPMPContent?.displayname && parsedPMPContent.displayname?.trim() !== '';
|
||||
// Profiles and Colors
|
||||
const profile = useUserProfile(senderId, room, undefined, true, isVisible);
|
||||
const { color: usernameColor, font: usernameFont } = useSableCosmetics(
|
||||
@@ -477,6 +478,9 @@ function MessageInternal(
|
||||
false,
|
||||
isVisible
|
||||
);
|
||||
|
||||
const accessibleNameColor = useAccessibleNameColor(activeTheme.kind);
|
||||
|
||||
const senderFallbackName = getMxIdLocalPart(senderId) ?? senderId;
|
||||
const resolvedSenderDisplayName =
|
||||
senderDisplayName === senderFallbackName || senderDisplayName === senderId
|
||||
@@ -488,7 +492,7 @@ function MessageInternal(
|
||||
* otherwise we fall back to the profile pronouns.
|
||||
* This allows users to set pronouns on a per-message basis, while still falling back to their profile pronouns if they don't set any for a specific message.
|
||||
*/
|
||||
const pronouns = parsedPMPContent?.pronouns ?? profile.pronouns;
|
||||
const pronouns = parsedPMPContent?.['io.fsky.nyx.pronouns'] ?? profile.pronouns;
|
||||
|
||||
const [highlightMentions] = useSetting(settingsAtom, 'highlightMentions');
|
||||
|
||||
@@ -588,7 +592,7 @@ function MessageInternal(
|
||||
<Username
|
||||
as="button"
|
||||
style={{
|
||||
color: pmpNameColor ?? usernameColor,
|
||||
color: accessibleNameColor(pmpNameColor) ?? usernameColor,
|
||||
fontFamily: usernameFont,
|
||||
}}
|
||||
data-user-id={senderId}
|
||||
@@ -606,7 +610,7 @@ function MessageInternal(
|
||||
{showPronouns && (
|
||||
<Pronouns
|
||||
pronouns={mergedPronouns}
|
||||
tagColor={pmpNameColor ?? usernameColor ?? 'currentColor'}
|
||||
tagColor={accessibleNameColor(pmpNameColor) ?? usernameColor ?? 'currentColor'}
|
||||
/>
|
||||
)}
|
||||
{showPmPInfo && (
|
||||
|
||||
@@ -81,6 +81,7 @@ import {
|
||||
readdAngleBracketsForHiddenPreviews,
|
||||
stripMarkdownEscapesForHiddenPreviews,
|
||||
} from './hiddenLinkPreviews';
|
||||
import { stripPerMessageProfileFormattedBody } from '$hooks/usePerMessageProfile';
|
||||
|
||||
// Wraps the mobile emoji-board overlay so the Android back action closes it
|
||||
// instead of navigating away. Hooks can't run inside the UseStateProvider
|
||||
@@ -126,6 +127,7 @@ export const MessageEditor = as<'div', MessageEditorProps>(
|
||||
const nicknames = useAtomValue(nicknamesAtom);
|
||||
const editor = useEditor();
|
||||
const [enterForNewline] = useSetting(settingsAtom, 'enterForNewline');
|
||||
const [pmpNoFallback] = useSetting(settingsAtom, 'pmpNoFallback');
|
||||
const isComposing = useComposingCheck();
|
||||
|
||||
const [autocompleteQuery, setAutocompleteQuery] =
|
||||
@@ -164,10 +166,7 @@ export const MessageEditor = as<'div', MessageEditorProps>(
|
||||
}
|
||||
|
||||
if (pmpDisplayname && typeof customHtml === 'string') {
|
||||
customHtml = customHtml.replace(
|
||||
/^<strong\s+data-mx-profile-fallback[^>]*>.*?<\/strong>/,
|
||||
''
|
||||
);
|
||||
customHtml = stripPerMessageProfileFormattedBody(customHtml);
|
||||
}
|
||||
|
||||
const bundleContent =
|
||||
@@ -292,11 +291,12 @@ export const MessageEditor = as<'div', MessageEditorProps>(
|
||||
eventId,
|
||||
mMentions,
|
||||
linkPreviews,
|
||||
rawPmp
|
||||
rawPmp,
|
||||
pmpNoFallback
|
||||
);
|
||||
|
||||
return mx.sendMessage(roomId, content as RoomMessageEventContent);
|
||||
}, [mx, editor, roomId, mEvent, getPrevBodyAndFormattedBody, room])
|
||||
}, [mx, editor, roomId, mEvent, getPrevBodyAndFormattedBody, room, pmpNoFallback])
|
||||
);
|
||||
|
||||
const handleSave = useCallback(() => {
|
||||
@@ -337,6 +337,14 @@ export const MessageEditor = as<'div', MessageEditorProps>(
|
||||
[enterForNewline, isComposing, editor, handleSave, onCancel]
|
||||
);
|
||||
|
||||
const detectAutocomplete = useCallback(() => {
|
||||
const prevWordRange = getPrevWorldRange(editor);
|
||||
const query = prevWordRange
|
||||
? getAutocompleteQuery(editor, prevWordRange, ANYWHERE_AUTOCOMPLETE_PREFIXES)
|
||||
: undefined;
|
||||
setAutocompleteQuery(query);
|
||||
}, [editor]);
|
||||
|
||||
const handleKeyUp: KeyboardEventHandler = useCallback(
|
||||
(evt) => {
|
||||
if (isKeyHotkey('escape', evt)) {
|
||||
@@ -344,13 +352,9 @@ export const MessageEditor = as<'div', MessageEditorProps>(
|
||||
return;
|
||||
}
|
||||
|
||||
const prevWordRange = getPrevWorldRange(editor);
|
||||
const query = prevWordRange
|
||||
? getAutocompleteQuery(editor, prevWordRange, ANYWHERE_AUTOCOMPLETE_PREFIXES)
|
||||
: undefined;
|
||||
setAutocompleteQuery(query);
|
||||
detectAutocomplete();
|
||||
},
|
||||
[editor]
|
||||
[detectAutocomplete]
|
||||
);
|
||||
|
||||
const handleCloseAutocomplete = useCallback(() => {
|
||||
|
||||
@@ -1,6 +1,9 @@
|
||||
import { style } from '@vanilla-extract/css';
|
||||
import { DefaultReset, FocusOutline, color, config, toRem } from 'folds';
|
||||
|
||||
// Sheets can be opened from an existing Folds overlay, whose maximum layer is Z9999.
|
||||
const mobileSheetZIndex = `calc(${config.zIndex.Max} + 1)`;
|
||||
|
||||
export const MessageBase = style({
|
||||
position: 'relative',
|
||||
maxWidth: '100%',
|
||||
@@ -102,7 +105,7 @@ export const MessageMobileOptionsWrapped = style({
|
||||
left: 0,
|
||||
right: 0,
|
||||
bottom: 0,
|
||||
zIndex: 1004,
|
||||
zIndex: mobileSheetZIndex,
|
||||
width: '100vw',
|
||||
height: '100%',
|
||||
backgroundColor: color.Other.Overlay,
|
||||
@@ -118,7 +121,7 @@ export const MessageMobileOptionsContainer = style({
|
||||
bottom: 0,
|
||||
left: 0,
|
||||
right: 0,
|
||||
zIndex: 1005,
|
||||
zIndex: mobileSheetZIndex,
|
||||
width: '100%',
|
||||
maxHeight: '85vh',
|
||||
display: 'flex',
|
||||
|
||||
@@ -0,0 +1,262 @@
|
||||
import { fireEvent, render, screen, waitFor } from '@testing-library/react';
|
||||
import type { ReactNode } from 'react';
|
||||
import { beforeEach, describe, expect, it, vi } from 'vitest';
|
||||
import type { MatrixClient } from 'matrix-js-sdk';
|
||||
import type { PerMessageProfileMsc4461 } from '$hooks/usePerMessageProfile';
|
||||
import { TemporaryPersonaPicker, PersonaPickerTab } from './PersonaPicker';
|
||||
|
||||
const mocked = vi.hoisted(() => ({
|
||||
getAll: vi.fn<(mx: MatrixClient) => Promise<PerMessageProfileMsc4461[]>>(),
|
||||
getRoom:
|
||||
vi.fn<(mx: MatrixClient, roomId: string) => Promise<PerMessageProfileMsc4461 | undefined>>(),
|
||||
getAccount: vi.fn<(mx: MatrixClient) => Promise<PerMessageProfileMsc4461 | undefined>>(),
|
||||
setRoom: vi.fn<(...args: unknown[]) => Promise<void>>(),
|
||||
setAccount: vi.fn<(...args: unknown[]) => Promise<void>>(),
|
||||
}));
|
||||
|
||||
vi.mock('$hooks/usePerMessageProfile', () => ({
|
||||
getAllPerMessageProfiles: mocked.getAll,
|
||||
getCurrentlyUsedPerMessageProfileForRoom: mocked.getRoom,
|
||||
getCurrentlyUsedPerMessageProfileForAccount: mocked.getAccount,
|
||||
setCurrentlyUsedPerMessageProfileIdForRoom: mocked.setRoom,
|
||||
setCurrentlyUsedPerMessageProfileIdForAccount: mocked.setAccount,
|
||||
}));
|
||||
vi.mock('$hooks/useMediaAuthentication.ts', () => ({ useMediaAuthentication: () => false }));
|
||||
// useActiveTheme reaches for window.matchMedia, which jsdom does not provide.
|
||||
vi.mock('$hooks/useTheme.ts', () => ({
|
||||
ThemeKind: { Light: 'light', Dark: 'dark' },
|
||||
useActiveTheme: () => ({ kind: 'light' }),
|
||||
}));
|
||||
vi.mock('$components/icons/phosphor', () => ({
|
||||
MagnifyingGlass: {},
|
||||
User: {},
|
||||
composerIcon: () => null,
|
||||
menuIcon: () => null,
|
||||
}));
|
||||
vi.mock('$components/ResponsiveMenu', () => ({
|
||||
ResponsiveMenu: ({ children, menu }: { children: ReactNode; menu: ReactNode }) => (
|
||||
<div>
|
||||
{children}
|
||||
{menu}
|
||||
</div>
|
||||
),
|
||||
}));
|
||||
vi.mock('$components/user-avatar/UserAvatar.tsx', () => ({
|
||||
UserAvatar: ({ renderFallback }: { renderFallback: () => ReactNode }) => <>{renderFallback()}</>,
|
||||
}));
|
||||
vi.mock('$components/info-card/InfoCard.tsx', () => ({
|
||||
InfoCard: ({ description }: { description: ReactNode }) => <div>{description}</div>,
|
||||
}));
|
||||
vi.mock('@phosphor-icons/react', () => ({ InfoIcon: {} }));
|
||||
vi.mock('$utils/matrix.ts', () => ({ mxcUrlToHttp: () => undefined }));
|
||||
vi.mock('$utils/platform', () => ({ isMobileOrTablet: () => false }));
|
||||
vi.mock('$utils/common', () => ({ nameInitials: (name: string) => name.slice(0, 1) }));
|
||||
vi.mock('./PersonaPicker.css.ts', () => ({
|
||||
PersonaPickerMenuItem: '',
|
||||
PersonaPickerButtonAvatar: '',
|
||||
SelectedPersonaPickerButtonAvatar: '',
|
||||
PersonaPickerButtonAvatarImage: '',
|
||||
}));
|
||||
|
||||
vi.mock('folds', async () => {
|
||||
const React = await import('react');
|
||||
const Input = React.forwardRef<HTMLInputElement, React.ComponentProps<'input'>>((props, ref) => (
|
||||
<input ref={ref} {...props} />
|
||||
));
|
||||
const TestButton = ({ children, ...props }: React.ComponentProps<'button'>) =>
|
||||
React.createElement('button', props, children);
|
||||
const TestContainer = ({ children }: { children?: ReactNode }) =>
|
||||
React.createElement('div', null, children);
|
||||
|
||||
return {
|
||||
Avatar: TestContainer,
|
||||
Badge: TestButton,
|
||||
Box: TestContainer,
|
||||
IconButton: TestButton,
|
||||
Input,
|
||||
Menu: TestContainer,
|
||||
MenuItem: TestButton,
|
||||
Scroll: TestContainer,
|
||||
Text: TestContainer,
|
||||
config: { space: { S200: 0 } },
|
||||
toRem: (value: number) => `${value}rem`,
|
||||
};
|
||||
});
|
||||
|
||||
function deferred<T>() {
|
||||
let resolve!: (value: T) => void;
|
||||
let reject!: (reason?: unknown) => void;
|
||||
const promise = new Promise<T>((resolvePromise, rejectPromise) => {
|
||||
resolve = resolvePromise;
|
||||
reject = rejectPromise;
|
||||
});
|
||||
return { promise, resolve, reject };
|
||||
}
|
||||
|
||||
const profiles: PerMessageProfileMsc4461[] = [
|
||||
{ id: 'first', displayname: 'First', trigger: { prefix: [] } },
|
||||
{ id: 'second', displayname: 'Second', trigger: { prefix: [] } },
|
||||
];
|
||||
|
||||
function renderPicker(mx = {} as MatrixClient, tab = PersonaPickerTab.Global) {
|
||||
return render(
|
||||
<TemporaryPersonaPicker
|
||||
tab={tab}
|
||||
mx={mx}
|
||||
roomId="!room:example.org"
|
||||
suppressEditorRefocus={vi.fn<() => void>()}
|
||||
onTabChange={vi.fn<(tab: PersonaPickerTab) => void>()}
|
||||
latchedPersona={undefined}
|
||||
/>
|
||||
);
|
||||
}
|
||||
|
||||
describe('PersonaPicker async flows', () => {
|
||||
beforeEach(() => {
|
||||
vi.clearAllMocks();
|
||||
mocked.getAll.mockResolvedValue(profiles);
|
||||
mocked.getRoom.mockResolvedValue(undefined);
|
||||
mocked.getAccount.mockResolvedValue(undefined);
|
||||
mocked.setRoom.mockResolvedValue(undefined);
|
||||
mocked.setAccount.mockResolvedValue(undefined);
|
||||
});
|
||||
|
||||
it('ignores a stale profile fetch after the client changes', async () => {
|
||||
const firstClient = {} as MatrixClient;
|
||||
const secondClient = {} as MatrixClient;
|
||||
const firstFetch = deferred<PerMessageProfileMsc4461[]>();
|
||||
const secondFetch = deferred<PerMessageProfileMsc4461[]>();
|
||||
mocked.getAll.mockImplementation((client: MatrixClient) =>
|
||||
client === firstClient ? firstFetch.promise : secondFetch.promise
|
||||
);
|
||||
|
||||
const view = renderPicker(firstClient);
|
||||
view.rerender(
|
||||
<TemporaryPersonaPicker
|
||||
mx={secondClient}
|
||||
roomId="!room:example.org"
|
||||
suppressEditorRefocus={vi.fn<() => void>()}
|
||||
onTabChange={vi.fn<(tab: PersonaPickerTab) => void>()}
|
||||
latchedPersona={undefined}
|
||||
/>
|
||||
);
|
||||
|
||||
secondFetch.resolve([{ id: 'new', displayname: 'New', trigger: { prefix: [] } }]);
|
||||
expect(await screen.findByText('New')).toBeInTheDocument();
|
||||
firstFetch.resolve([{ id: 'old', displayname: 'Old', trigger: { prefix: [] } }]);
|
||||
|
||||
await waitFor(() => expect(screen.queryByText('Old')).not.toBeInTheDocument());
|
||||
});
|
||||
|
||||
it('does not update state when an in-flight profile fetch resolves after unmount', async () => {
|
||||
const fetch = deferred<PerMessageProfileMsc4461[]>();
|
||||
mocked.getAll.mockReturnValue(fetch.promise);
|
||||
const view = renderPicker();
|
||||
view.unmount();
|
||||
|
||||
fetch.resolve(profiles);
|
||||
await Promise.resolve();
|
||||
expect(screen.queryByText('First')).not.toBeInTheDocument();
|
||||
});
|
||||
|
||||
it('commits an independent global sync when the room sync is still pending', async () => {
|
||||
const roomSync = deferred<PerMessageProfileMsc4461 | undefined>();
|
||||
mocked.getRoom.mockReturnValue(roomSync.promise);
|
||||
mocked.getAccount.mockResolvedValue(profiles[0]);
|
||||
renderPicker();
|
||||
|
||||
await waitFor(() => {
|
||||
expect(screen.getByRole('button', { name: 'First' })).toHaveAttribute(
|
||||
'aria-selected',
|
||||
'true'
|
||||
);
|
||||
});
|
||||
|
||||
roomSync.reject(new Error('room sync failed'));
|
||||
});
|
||||
|
||||
it('keeps the latest optimistic selection when an earlier write fails', async () => {
|
||||
const firstWrite = deferred<void>();
|
||||
const secondWrite = deferred<void>();
|
||||
mocked.setAccount.mockImplementationOnce(() => firstWrite.promise);
|
||||
mocked.setAccount.mockImplementationOnce(() => secondWrite.promise);
|
||||
renderPicker();
|
||||
await screen.findByText('First');
|
||||
|
||||
fireEvent.click(screen.getByRole('button', { name: 'First' }));
|
||||
fireEvent.click(screen.getByRole('button', { name: 'Second' }));
|
||||
|
||||
firstWrite.reject(new Error('first write failed'));
|
||||
secondWrite.resolve();
|
||||
|
||||
await waitFor(() => {
|
||||
expect(screen.getByRole('button', { name: 'Second' })).toHaveAttribute(
|
||||
'aria-selected',
|
||||
'true'
|
||||
);
|
||||
});
|
||||
});
|
||||
|
||||
it('rolls back a failed global selection without suppressing a room selection', async () => {
|
||||
const mx = {} as MatrixClient;
|
||||
const globalWrite = deferred<void>();
|
||||
const roomWrite = deferred<void>();
|
||||
mocked.setAccount.mockImplementationOnce(() => globalWrite.promise);
|
||||
mocked.setRoom.mockImplementationOnce(() => roomWrite.promise);
|
||||
const view = renderPicker(mx);
|
||||
await screen.findByText('First');
|
||||
|
||||
fireEvent.click(screen.getByRole('button', { name: 'First' }));
|
||||
view.rerender(
|
||||
<TemporaryPersonaPicker
|
||||
tab={PersonaPickerTab.PerRoom}
|
||||
mx={mx}
|
||||
roomId="!room:example.org"
|
||||
suppressEditorRefocus={vi.fn<() => void>()}
|
||||
onTabChange={vi.fn<(tab: PersonaPickerTab) => void>()}
|
||||
latchedPersona={undefined}
|
||||
/>
|
||||
);
|
||||
fireEvent.click(screen.getByRole('button', { name: 'Second' }));
|
||||
|
||||
globalWrite.reject(new Error('global write failed'));
|
||||
roomWrite.resolve();
|
||||
|
||||
await waitFor(() => {
|
||||
expect(screen.getByRole('button', { name: 'Second' })).toHaveAttribute(
|
||||
'aria-selected',
|
||||
'true'
|
||||
);
|
||||
});
|
||||
|
||||
view.rerender(
|
||||
<TemporaryPersonaPicker
|
||||
tab={PersonaPickerTab.Global}
|
||||
mx={mx}
|
||||
roomId="!room:example.org"
|
||||
suppressEditorRefocus={vi.fn<() => void>()}
|
||||
onTabChange={vi.fn<(tab: PersonaPickerTab) => void>()}
|
||||
latchedPersona={undefined}
|
||||
/>
|
||||
);
|
||||
expect(screen.getByRole('button', { name: 'First' })).not.toHaveAttribute(
|
||||
'aria-selected',
|
||||
'true'
|
||||
);
|
||||
});
|
||||
|
||||
it('reconciles an optimistic selection when its write is rejected', async () => {
|
||||
mocked.setAccount.mockRejectedValueOnce(new Error('write failed'));
|
||||
renderPicker();
|
||||
await screen.findByText('First');
|
||||
|
||||
fireEvent.click(screen.getByRole('button', { name: 'First' }));
|
||||
|
||||
await waitFor(() => {
|
||||
expect(screen.getByRole('button', { name: 'First' })).not.toHaveAttribute(
|
||||
'aria-selected',
|
||||
'true'
|
||||
);
|
||||
});
|
||||
});
|
||||
});
|
||||
@@ -10,7 +10,7 @@ import { useMediaAuthentication } from '$hooks/useMediaAuthentication.ts';
|
||||
import {
|
||||
getCurrentlyUsedPerMessageProfileForRoom,
|
||||
getAllPerMessageProfiles,
|
||||
type PerMessageProfile,
|
||||
type PerMessageProfileMsc4461,
|
||||
setCurrentlyUsedPerMessageProfileIdForRoom,
|
||||
getCurrentlyUsedPerMessageProfileForAccount,
|
||||
setCurrentlyUsedPerMessageProfileIdForAccount,
|
||||
@@ -33,137 +33,180 @@ import {
|
||||
Badge,
|
||||
} from 'folds';
|
||||
import type { MatrixClient } from 'matrix-js-sdk';
|
||||
import { useCallback, useEffect, useRef, useState, type FormEvent } from 'react';
|
||||
import {
|
||||
useCallback,
|
||||
useEffect,
|
||||
useRef,
|
||||
useState,
|
||||
type FormEvent,
|
||||
type MutableRefObject,
|
||||
} from 'react';
|
||||
import * as css from './PersonaPicker.css.ts';
|
||||
import { InfoCard } from '$components/info-card/InfoCard.tsx';
|
||||
import { InfoIcon, XIcon } from '@phosphor-icons/react';
|
||||
import { InfoIcon } from '@phosphor-icons/react';
|
||||
import { ThemeKind, useActiveTheme } from '$hooks/useTheme.ts';
|
||||
|
||||
const pillStyles = {
|
||||
cursor: 'pointer',
|
||||
} as const;
|
||||
|
||||
export enum PersonaPickerPresentation {
|
||||
TemporarySelectorMenu = 'TemporarySelectorMenu',
|
||||
PersistentPicker = 'PersistentPicker',
|
||||
}
|
||||
export enum PersonaPickerTab {
|
||||
Global = 'Global',
|
||||
PerRoom = 'PerRoom',
|
||||
}
|
||||
|
||||
export enum PersonaPickerPresentation {
|
||||
TemporarySelectorMenu = 'TemporarySelectorMenu',
|
||||
PersistentPicker = 'PersistentPicker',
|
||||
}
|
||||
|
||||
type PersonaPickerProps = {
|
||||
tab?: PersonaPickerTab;
|
||||
mx: MatrixClient;
|
||||
roomId?: string;
|
||||
suppressEditorRefocus?: () => void;
|
||||
onTabChange?: (tab: PersonaPickerTab) => void;
|
||||
latchedPersona?: PerMessageProfile;
|
||||
hideTabs?: boolean;
|
||||
onPersonaSelect?: (persona: PerMessageProfile | undefined) => void;
|
||||
latchedPersona?: PerMessageProfileMsc4461;
|
||||
onPersonaSelect?: (persona: PerMessageProfileMsc4461 | undefined) => void | Promise<void>;
|
||||
requestClose?: () => void;
|
||||
showNoneOption?: boolean;
|
||||
hideButton?: boolean;
|
||||
hideTabs?: boolean;
|
||||
anchor?: RectCords;
|
||||
};
|
||||
|
||||
function PersonaSelectMenuTabs({
|
||||
tab,
|
||||
setTab,
|
||||
}: {
|
||||
tab: PersonaPickerTab;
|
||||
setTab: (tab: PersonaPickerTab) => void;
|
||||
}) {
|
||||
return (
|
||||
<Box gap="100" style={{ marginBlock: '0.25rem' }}>
|
||||
<Badge
|
||||
style={pillStyles}
|
||||
as="button"
|
||||
variant="Secondary"
|
||||
fill={tab == PersonaPickerTab.Global ? 'Solid' : 'None'}
|
||||
size="500"
|
||||
onClick={() => setTab(PersonaPickerTab.Global)}
|
||||
>
|
||||
<Text as="span" size="L400">
|
||||
Global
|
||||
</Text>
|
||||
</Badge>
|
||||
<Badge
|
||||
style={pillStyles}
|
||||
as="button"
|
||||
variant="Secondary"
|
||||
fill={tab == PersonaPickerTab.PerRoom ? 'Solid' : 'None'}
|
||||
size="500"
|
||||
onClick={() => setTab(PersonaPickerTab.PerRoom)}
|
||||
>
|
||||
<Text as="span" size="L400">
|
||||
Per-room
|
||||
</Text>
|
||||
</Badge>
|
||||
</Box>
|
||||
);
|
||||
}
|
||||
|
||||
export function TemporaryPersonaPicker(props: PersonaPickerProps) {
|
||||
return (
|
||||
<PersonaPicker {...props} presentation={PersonaPickerPresentation.TemporarySelectorMenu} />
|
||||
<PersonaPickerMenu {...props} presentation={PersonaPickerPresentation.TemporarySelectorMenu} />
|
||||
);
|
||||
}
|
||||
|
||||
export function PersistentPersonaPicker(props: PersonaPickerProps) {
|
||||
return <PersonaPicker {...props} presentation={PersonaPickerPresentation.PersistentPicker} />;
|
||||
return <PersonaPickerMenu {...props} presentation={PersonaPickerPresentation.PersistentPicker} />;
|
||||
}
|
||||
|
||||
function PersonaPicker({
|
||||
function PersonaPickerMenu({
|
||||
tab: tabProp = PersonaPickerTab.Global,
|
||||
mx,
|
||||
roomId,
|
||||
suppressEditorRefocus,
|
||||
onTabChange,
|
||||
latchedPersona,
|
||||
onPersonaSelect,
|
||||
anchor,
|
||||
requestClose,
|
||||
presentation,
|
||||
onTabChange,
|
||||
}: PersonaPickerProps & { presentation: PersonaPickerPresentation }) {
|
||||
const useAuthentication = useMediaAuthentication();
|
||||
|
||||
const persistent = presentation === PersonaPickerPresentation.PersistentPicker;
|
||||
|
||||
const [tab, setTab] = useState(tabProp);
|
||||
const activeTheme = useActiveTheme();
|
||||
const [AddPersonaMenuAnchor, setAddPersonaMenuAnchor] = useState<RectCords | undefined>(anchor);
|
||||
const [profiles, setProfiles] = useState<PerMessageProfile[] | undefined>(undefined);
|
||||
const [selectedGlobalPersona, setSelectedGlobalPersona] = useState<PerMessageProfile | null>(
|
||||
null
|
||||
);
|
||||
const [selectedRoomPersona, setSelectedRoomPersona] = useState<PerMessageProfile | null>(
|
||||
const [profiles, setProfiles] = useState<PerMessageProfileMsc4461[] | undefined>(undefined);
|
||||
const [selectedGlobalPersona, setSelectedGlobalPersona] =
|
||||
useState<PerMessageProfileMsc4461 | null>(null);
|
||||
const [selectedRoomPersona, setSelectedRoomPersona] = useState<PerMessageProfileMsc4461 | null>(
|
||||
latchedPersona ?? null
|
||||
);
|
||||
const mountedRef = useRef(false);
|
||||
const profileFetchGenerationRef = useRef(0);
|
||||
// Bumped on each click so an in-flight sync cannot undo a fresher choice. Global and
|
||||
// per-room selections are independent, so one must not invalidate the other's rollback.
|
||||
const globalSelectionRef = useRef(0);
|
||||
const roomSelectionRef = useRef(0);
|
||||
const isPickerMenuItemSelected = (persona: PerMessageProfileMsc4461) => {
|
||||
const selectedPersona =
|
||||
tab === PersonaPickerTab.Global ? selectedGlobalPersona : selectedRoomPersona;
|
||||
return persona.id === selectedPersona?.id ? true : undefined;
|
||||
};
|
||||
|
||||
const nameColor = useCallback(
|
||||
(persona: PerMessageProfileMsc4461) =>
|
||||
activeTheme.kind === ThemeKind.Dark
|
||||
? persona['eu.she-a.color']?.on_dark
|
||||
: persona['eu.she-a.color']?.on_light,
|
||||
[activeTheme]
|
||||
);
|
||||
|
||||
const defactoPersona = () => selectedRoomPersona ?? selectedGlobalPersona;
|
||||
|
||||
const activeTheme = useActiveTheme();
|
||||
|
||||
useEffect(() => {
|
||||
const syncProfile = async () => {
|
||||
if (roomId) {
|
||||
const syncedRoomProfile = await getCurrentlyUsedPerMessageProfileForRoom(mx, roomId);
|
||||
if (!selectedRoomPersona) setSelectedRoomPersona(syncedRoomProfile ?? null);
|
||||
|
||||
const syncedGlobalProfile = await getCurrentlyUsedPerMessageProfileForAccount(mx);
|
||||
setSelectedGlobalPersona(syncedGlobalProfile ?? null);
|
||||
}
|
||||
};
|
||||
syncProfile();
|
||||
}, [mx, roomId, profiles, latchedPersona, selectedRoomPersona]);
|
||||
|
||||
const fetchProfiles = async (mx_: MatrixClient) => {
|
||||
const fetchedProfiles = await getAllPerMessageProfiles(mx_);
|
||||
setProfiles(fetchedProfiles);
|
||||
setFilteredProfiles(fetchedProfiles);
|
||||
};
|
||||
const searchInputRef = useRef<HTMLInputElement>(null);
|
||||
|
||||
const scrollRef = useRef<HTMLDivElement>(null);
|
||||
const searchInputRef = useRef<HTMLInputElement>(null);
|
||||
const [filteredProfiles, setFilteredProfiles] = useState<PerMessageProfileMsc4461[] | undefined>(
|
||||
undefined
|
||||
);
|
||||
|
||||
useEffect(() => {
|
||||
mountedRef.current = true;
|
||||
return () => {
|
||||
mountedRef.current = false;
|
||||
profileFetchGenerationRef.current += 1;
|
||||
};
|
||||
}, []);
|
||||
|
||||
const clearFilterInput = () => {
|
||||
if (searchInputRef.current) {
|
||||
searchInputRef.current.value = '';
|
||||
}
|
||||
setFilteredProfiles(profiles);
|
||||
};
|
||||
|
||||
useEffect(() => {
|
||||
let cancelled = false;
|
||||
|
||||
const syncProfile = async (
|
||||
generationRef: MutableRefObject<number>,
|
||||
load: () => Promise<PerMessageProfileMsc4461 | undefined>,
|
||||
apply: (profile: PerMessageProfileMsc4461 | null) => void
|
||||
) => {
|
||||
const generation = generationRef.current;
|
||||
try {
|
||||
const synced = await load();
|
||||
if (!cancelled && generation === generationRef.current) apply(synced ?? null);
|
||||
} catch {
|
||||
// Profile synchronization is best effort; retain the current selection on failure.
|
||||
}
|
||||
};
|
||||
|
||||
void syncProfile(
|
||||
roomSelectionRef,
|
||||
() =>
|
||||
roomId ? getCurrentlyUsedPerMessageProfileForRoom(mx, roomId) : Promise.resolve(undefined),
|
||||
// A latched persona already reflects the user's intent, so don't overwrite it.
|
||||
(profile) => {
|
||||
if (!selectedRoomPersona) setSelectedRoomPersona(profile);
|
||||
}
|
||||
);
|
||||
void syncProfile(
|
||||
globalSelectionRef,
|
||||
() => getCurrentlyUsedPerMessageProfileForAccount(mx),
|
||||
setSelectedGlobalPersona
|
||||
);
|
||||
|
||||
return () => {
|
||||
cancelled = true;
|
||||
};
|
||||
}, [mx, roomId, latchedPersona, selectedRoomPersona]);
|
||||
|
||||
const fetchProfiles = useCallback(async (mx_: MatrixClient) => {
|
||||
const fetchGeneration = ++profileFetchGenerationRef.current;
|
||||
try {
|
||||
const fetchedProfiles = await getAllPerMessageProfiles(mx_);
|
||||
if (!mountedRef.current || fetchGeneration !== profileFetchGenerationRef.current) {
|
||||
return;
|
||||
}
|
||||
setProfiles(fetchedProfiles);
|
||||
setFilteredProfiles(fetchedProfiles);
|
||||
} catch {
|
||||
// Profile loading is best effort; keep the existing list when it fails.
|
||||
}
|
||||
}, []);
|
||||
|
||||
useEffect(() => {
|
||||
void fetchProfiles(mx);
|
||||
return () => {
|
||||
profileFetchGenerationRef.current += 1;
|
||||
};
|
||||
}, [fetchProfiles, mx]);
|
||||
|
||||
const filter = useCallback(
|
||||
(e: FormEvent) => {
|
||||
@@ -172,7 +215,7 @@ function PersonaPicker({
|
||||
const filtered = term
|
||||
? profiles?.filter((profile) =>
|
||||
searchInputRef.current
|
||||
? profile.name.toLocaleLowerCase().includes(searchInputRef.current?.value) ||
|
||||
? profile.displayname.toLocaleLowerCase().includes(searchInputRef.current?.value) ||
|
||||
profile.id.toLocaleLowerCase().includes(searchInputRef.current?.value)
|
||||
: true
|
||||
)
|
||||
@@ -182,28 +225,11 @@ function PersonaPicker({
|
||||
},
|
||||
[profiles]
|
||||
);
|
||||
const nameColor = useCallback(
|
||||
(persona: PerMessageProfile) =>
|
||||
activeTheme.kind === ThemeKind.Dark ? persona.colors?.on_dark : persona.colors?.on_light,
|
||||
[activeTheme]
|
||||
);
|
||||
|
||||
const isSelected = (persona: PerMessageProfile | undefined) => {
|
||||
if (!persona) return undefined;
|
||||
const selected = tab === PersonaPickerTab.Global ? selectedGlobalPersona : selectedRoomPersona;
|
||||
return persona.id === selected?.id ? true : undefined;
|
||||
};
|
||||
|
||||
const [filteredProfiles, setFilteredProfiles] = useState(profiles);
|
||||
|
||||
useEffect(() => {
|
||||
fetchProfiles(mx);
|
||||
}, [mx]);
|
||||
|
||||
const avatarUrl = useCallback(
|
||||
(profile: PerMessageProfile) => {
|
||||
if (profile.avatarUrl !== undefined) {
|
||||
return mxcUrlToHttp(mx, profile.avatarUrl, useAuthentication, 96, 96, 'crop') ?? undefined;
|
||||
(profile: PerMessageProfileMsc4461) => {
|
||||
if (profile.avatar_url !== undefined) {
|
||||
return mxcUrlToHttp(mx, profile.avatar_url, useAuthentication, 96, 96, 'crop') ?? undefined;
|
||||
} else {
|
||||
return undefined;
|
||||
}
|
||||
@@ -211,58 +237,16 @@ function PersonaPicker({
|
||||
[mx, useAuthentication]
|
||||
);
|
||||
|
||||
const handleSelect = useCallback(
|
||||
async (profile: PerMessageProfile | undefined) => {
|
||||
if (onPersonaSelect) {
|
||||
onPersonaSelect(profile);
|
||||
return;
|
||||
}
|
||||
if (!roomId) return;
|
||||
|
||||
const isGlobal = tab === PersonaPickerTab.Global;
|
||||
const selectedPersona = isGlobal ? selectedGlobalPersona : selectedRoomPersona;
|
||||
const disabling = !profile || profile.id === selectedPersona?.id;
|
||||
|
||||
if (!disabling) {
|
||||
if (isGlobal) {
|
||||
setSelectedGlobalPersona(profile);
|
||||
await setCurrentlyUsedPerMessageProfileIdForAccount(mx, profile.id);
|
||||
} else {
|
||||
setSelectedRoomPersona(profile);
|
||||
await setCurrentlyUsedPerMessageProfileIdForRoom(mx, roomId, profile.id);
|
||||
}
|
||||
} else {
|
||||
if (isGlobal) {
|
||||
setSelectedGlobalPersona(null);
|
||||
await setCurrentlyUsedPerMessageProfileIdForAccount(mx, undefined, undefined, true);
|
||||
} else {
|
||||
setSelectedRoomPersona(null);
|
||||
await setCurrentlyUsedPerMessageProfileIdForRoom(mx, roomId, undefined, undefined, true);
|
||||
}
|
||||
}
|
||||
},
|
||||
[
|
||||
mx,
|
||||
roomId,
|
||||
tab,
|
||||
selectedRoomPersona,
|
||||
selectedGlobalPersona,
|
||||
setSelectedGlobalPersona,
|
||||
setSelectedRoomPersona,
|
||||
onPersonaSelect,
|
||||
]
|
||||
);
|
||||
|
||||
return (
|
||||
<ResponsiveMenu
|
||||
anchor={AddPersonaMenuAnchor}
|
||||
position={!persistent ? 'Left' : 'Top'}
|
||||
position="Top"
|
||||
align="Start"
|
||||
offset={!persistent ? 10 : 16}
|
||||
alignOffset={!persistent ? 0 : -44}
|
||||
offset={16}
|
||||
alignOffset={-44}
|
||||
requestClose={() => {
|
||||
setAddPersonaMenuAnchor(undefined);
|
||||
requestClose?.();
|
||||
clearFilterInput();
|
||||
}}
|
||||
menu={
|
||||
<Menu>
|
||||
@@ -271,15 +255,39 @@ function PersonaPicker({
|
||||
gap="100"
|
||||
style={{ padding: config.space.S200, minWidth: '18rem' }}
|
||||
>
|
||||
{persistent && (
|
||||
<PersonaSelectMenuTabs
|
||||
tab={tab}
|
||||
setTab={(newTab) => {
|
||||
onTabChange?.(newTab);
|
||||
setTab(newTab);
|
||||
<Box gap="100">
|
||||
<Badge
|
||||
style={pillStyles}
|
||||
as="button"
|
||||
variant="Secondary"
|
||||
fill={tab == PersonaPickerTab.Global ? 'Solid' : 'None'}
|
||||
size="500"
|
||||
onClick={() => {
|
||||
setTab(PersonaPickerTab.Global);
|
||||
onTabChange?.(PersonaPickerTab.Global);
|
||||
}}
|
||||
/>
|
||||
)}
|
||||
>
|
||||
<Text as="span" size="L400">
|
||||
Global
|
||||
</Text>
|
||||
</Badge>
|
||||
<Badge
|
||||
style={pillStyles}
|
||||
as="button"
|
||||
variant="Secondary"
|
||||
fill={tab == PersonaPickerTab.PerRoom ? 'Solid' : 'None'}
|
||||
size="500"
|
||||
onClick={() => {
|
||||
setTab(PersonaPickerTab.PerRoom);
|
||||
onTabChange?.(PersonaPickerTab.PerRoom);
|
||||
}}
|
||||
>
|
||||
<Text as="span" size="L400">
|
||||
Per-room
|
||||
</Text>
|
||||
</Badge>
|
||||
</Box>
|
||||
|
||||
<>
|
||||
<Input
|
||||
ref={searchInputRef}
|
||||
@@ -292,20 +300,56 @@ function PersonaPicker({
|
||||
before={menuIcon(MagnifyingGlass)}
|
||||
/>
|
||||
|
||||
<Scroll
|
||||
hideTrack
|
||||
ref={scrollRef}
|
||||
size="400"
|
||||
style={{ maxHeight: isMobileOrTablet() ? '55dvh' : '10rem' }}
|
||||
>
|
||||
<Scroll hideTrack ref={scrollRef} size="400" style={{ maxHeight: '10rem' }}>
|
||||
{filteredProfiles?.map((profile) => (
|
||||
<MenuItem
|
||||
key={profile.id}
|
||||
size="400"
|
||||
radii="300"
|
||||
className={css.PersonaPickerMenuItem}
|
||||
aria-selected={isSelected(profile)}
|
||||
onClick={() => handleSelect(profile)}
|
||||
aria-selected={isPickerMenuItemSelected(profile)}
|
||||
onClick={async () => {
|
||||
if (onPersonaSelect) {
|
||||
await onPersonaSelect(profile);
|
||||
requestClose?.();
|
||||
return;
|
||||
}
|
||||
const isGlobal = tab === PersonaPickerTab.Global;
|
||||
const previousPersona = isGlobal
|
||||
? selectedGlobalPersona
|
||||
: selectedRoomPersona;
|
||||
const disabling = profile.id === previousPersona?.id;
|
||||
const setPersona = isGlobal
|
||||
? setSelectedGlobalPersona
|
||||
: setSelectedRoomPersona;
|
||||
const generationRef = isGlobal ? globalSelectionRef : roomSelectionRef;
|
||||
const selectionGeneration = ++generationRef.current;
|
||||
|
||||
setPersona(disabling ? null : profile);
|
||||
|
||||
try {
|
||||
if (isGlobal) {
|
||||
await setCurrentlyUsedPerMessageProfileIdForAccount(
|
||||
mx,
|
||||
disabling ? undefined : profile.id,
|
||||
undefined,
|
||||
disabling
|
||||
);
|
||||
} else {
|
||||
await setCurrentlyUsedPerMessageProfileIdForRoom(
|
||||
mx,
|
||||
roomId!,
|
||||
disabling ? undefined : profile.id,
|
||||
undefined,
|
||||
disabling
|
||||
);
|
||||
}
|
||||
} catch {
|
||||
if (mountedRef.current && selectionGeneration === generationRef.current) {
|
||||
setPersona(previousPersona);
|
||||
}
|
||||
}
|
||||
}}
|
||||
before={
|
||||
<Avatar
|
||||
size="300"
|
||||
@@ -320,10 +364,10 @@ function PersonaPicker({
|
||||
<UserAvatar
|
||||
userId={profile.id}
|
||||
src={avatarUrl(profile)}
|
||||
fallbackColor={profile.colors?.on_light ?? undefined}
|
||||
fallbackColor={profile['eu.she-a.color']?.on_light ?? undefined}
|
||||
renderFallback={() => (
|
||||
<Text as="span" size="H4" aria-label="Avatar fallback">
|
||||
{nameInitials(profile.name)}
|
||||
{nameInitials(profile.displayname)}
|
||||
</Text>
|
||||
)}
|
||||
alt={`Avatar for profile ${profile.id}`}
|
||||
@@ -335,104 +379,76 @@ function PersonaPicker({
|
||||
truncate
|
||||
style={{ color: nameColor(profile) ?? undefined, maxWidth: toRem(150) }}
|
||||
>
|
||||
{profile.name}
|
||||
{profile.displayname}
|
||||
</Text>
|
||||
</MenuItem>
|
||||
))}
|
||||
{presentation !== PersonaPickerPresentation.PersistentPicker && (
|
||||
<MenuItem
|
||||
key={'none'}
|
||||
size="400"
|
||||
radii="300"
|
||||
className={css.PersonaPickerMenuItem}
|
||||
onClick={() => handleSelect(undefined)}
|
||||
before={
|
||||
<div
|
||||
style={{
|
||||
width: 28,
|
||||
height: 28,
|
||||
marginLeft: -6,
|
||||
}}
|
||||
>
|
||||
{menuIcon(XIcon, { weight: 'regular', size: 28 })}{' '}
|
||||
</div>
|
||||
}
|
||||
>
|
||||
<Text truncate style={{ maxWidth: toRem(150) }}>
|
||||
No persona
|
||||
</Text>
|
||||
</MenuItem>
|
||||
)}
|
||||
</Scroll>
|
||||
{presentation === PersonaPickerPresentation.PersistentPicker && (
|
||||
<InfoCard
|
||||
before={menuIcon(InfoIcon, { weight: 'fill' })}
|
||||
variant="Primary"
|
||||
description={
|
||||
selectedRoomPersona ? (
|
||||
<>
|
||||
Message will use your <em>per-room</em> persona.
|
||||
</>
|
||||
) : selectedGlobalPersona ? (
|
||||
<>
|
||||
Message will use your <em>global</em> persona.
|
||||
</>
|
||||
) : (
|
||||
<>No persona chosen.</>
|
||||
)
|
||||
}
|
||||
/>
|
||||
)}
|
||||
<InfoCard
|
||||
before={menuIcon(InfoIcon, { weight: 'fill' })}
|
||||
variant="Primary"
|
||||
description={
|
||||
selectedRoomPersona ? (
|
||||
<>
|
||||
Message will use your <em>per-room</em> persona.
|
||||
</>
|
||||
) : selectedGlobalPersona ? (
|
||||
<>
|
||||
Message will use your <em>global</em> persona.
|
||||
</>
|
||||
) : (
|
||||
<>No persona chosen.</>
|
||||
)
|
||||
}
|
||||
/>
|
||||
</>
|
||||
</Box>
|
||||
</Menu>
|
||||
}
|
||||
>
|
||||
{persistent && (
|
||||
<IconButton
|
||||
aria-pressed={!!AddPersonaMenuAnchor}
|
||||
onClick={(evt) => {
|
||||
// getAllPerMessageProfiles can return an empty list during initial startup.
|
||||
if (profiles?.length === 0) {
|
||||
fetchProfiles(mx);
|
||||
<IconButton
|
||||
aria-pressed={!!AddPersonaMenuAnchor}
|
||||
onClick={(evt) => {
|
||||
// getAllPerMessageProfiles can return an empty list during initial startup.
|
||||
if (profiles?.length === 0) {
|
||||
void fetchProfiles(mx);
|
||||
}
|
||||
setAddPersonaMenuAnchor(evt.currentTarget.getBoundingClientRect());
|
||||
}}
|
||||
onPointerDown={suppressEditorRefocus}
|
||||
variant="SurfaceVariant"
|
||||
size="300"
|
||||
style={{ backgroundColor: 'transparent' }}
|
||||
title="Switch persona"
|
||||
aria-label="Switch persona"
|
||||
>
|
||||
{(selectedRoomPersona ?? selectedGlobalPersona) ? (
|
||||
<Avatar
|
||||
size="200"
|
||||
radii="300"
|
||||
className={
|
||||
AddPersonaMenuAnchor
|
||||
? css.SelectedPersonaPickerButtonAvatar
|
||||
: css.PersonaPickerButtonAvatar
|
||||
}
|
||||
setAddPersonaMenuAnchor(evt.currentTarget.getBoundingClientRect());
|
||||
}}
|
||||
onPointerDown={suppressEditorRefocus}
|
||||
variant="SurfaceVariant"
|
||||
size="300"
|
||||
style={{ backgroundColor: 'transparent' }}
|
||||
title="Switch persona"
|
||||
aria-label="Switch persona"
|
||||
>
|
||||
{(selectedRoomPersona ?? selectedGlobalPersona) ? (
|
||||
<Avatar
|
||||
size="200"
|
||||
radii="300"
|
||||
className={
|
||||
AddPersonaMenuAnchor
|
||||
? css.SelectedPersonaPickerButtonAvatar
|
||||
: css.PersonaPickerButtonAvatar
|
||||
}
|
||||
aria-label="Profile avatar"
|
||||
>
|
||||
<UserAvatar
|
||||
className={css.PersonaPickerButtonAvatarImage}
|
||||
userId={defactoPersona()!.id}
|
||||
src={avatarUrl(defactoPersona()!)}
|
||||
renderFallback={() => (
|
||||
<Text as="span" size="H6" aria-label="Avatar fallback">
|
||||
{nameInitials(defactoPersona()!.name)}
|
||||
</Text>
|
||||
)}
|
||||
alt={`Avatar for profile ${defactoPersona()!.id}`}
|
||||
/>
|
||||
</Avatar>
|
||||
) : (
|
||||
composerIcon(UserIcon, { weight: AddPersonaMenuAnchor ? 'fill' : 'regular' })
|
||||
)}
|
||||
</IconButton>
|
||||
)}
|
||||
aria-label="Profile avatar"
|
||||
>
|
||||
<UserAvatar
|
||||
className={css.PersonaPickerButtonAvatarImage}
|
||||
userId={defactoPersona()!.id}
|
||||
src={avatarUrl(defactoPersona()!)}
|
||||
renderFallback={() => (
|
||||
<Text as="span" size="H6" aria-label="Avatar fallback">
|
||||
{nameInitials(defactoPersona()!.displayname)}
|
||||
</Text>
|
||||
)}
|
||||
alt={`Avatar for profile ${defactoPersona()!.id}`}
|
||||
/>
|
||||
</Avatar>
|
||||
) : (
|
||||
composerIcon(UserIcon, { weight: AddPersonaMenuAnchor ? 'fill' : 'regular' })
|
||||
)}
|
||||
</IconButton>
|
||||
</ResponsiveMenu>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,116 @@
|
||||
/* oxlint-disable typescript/no-explicit-any, react/void-dom-elements-no-children, vitest/require-mock-type-parameters, unicorn/consistent-function-scoping */
|
||||
|
||||
import { fireEvent, render, screen, waitFor } from '@testing-library/react';
|
||||
import { beforeEach, describe, expect, it, vi } from 'vitest';
|
||||
import { PollDialog } from './PollDialog';
|
||||
|
||||
vi.mock('folds', () => {
|
||||
const div = ({ children, ...props }: any) => <div {...props}>{children}</div>;
|
||||
const button = ({ children, ...props }: any) => <button {...props}>{children}</button>;
|
||||
const input = (props: any) => <input {...props} />;
|
||||
return {
|
||||
Dialog: div,
|
||||
Header: div,
|
||||
Box: div,
|
||||
Text: div,
|
||||
IconButton: button,
|
||||
Button: button,
|
||||
Input: input,
|
||||
Chip: button,
|
||||
Switch: ({ value, onChange }: any) => (
|
||||
<input type="checkbox" checked={value} onChange={(event) => onChange(event.target.checked)} />
|
||||
),
|
||||
Scroll: div,
|
||||
color: { Critical: { OnContainer: 'red' } },
|
||||
};
|
||||
});
|
||||
|
||||
vi.mock('$components/icons/phosphor', () => ({
|
||||
chipIcon: () => null,
|
||||
composerIcon: () => null,
|
||||
ListBullets: 'ListBullets',
|
||||
Minus: 'Minus',
|
||||
X: 'X',
|
||||
}));
|
||||
|
||||
vi.mock('$components/setting-tile', () => ({
|
||||
SettingTile: ({ children, after }: any) => (
|
||||
<div>
|
||||
{children}
|
||||
{after}
|
||||
</div>
|
||||
),
|
||||
}));
|
||||
|
||||
vi.mock('$components/sequence-card', () => ({
|
||||
SequenceCard: ({ children }: any) => <div>{children}</div>,
|
||||
SequenceCardStyle: '',
|
||||
}));
|
||||
|
||||
vi.mock('$components/modal-overlay/ModalOverlay', () => ({
|
||||
ModalOverlay: ({ children }: any) => <div>{children}</div>,
|
||||
}));
|
||||
|
||||
describe('PollDialog', () => {
|
||||
beforeEach(() => vi.clearAllMocks());
|
||||
|
||||
it('awaits submission, prevents duplicates, and closes after success', async () => {
|
||||
let resolveSubmit!: () => void;
|
||||
const onSubmit = vi.fn(
|
||||
() =>
|
||||
new Promise<void>((resolve) => {
|
||||
resolveSubmit = resolve;
|
||||
})
|
||||
);
|
||||
const onCancel = vi.fn();
|
||||
|
||||
render(<PollDialog onCancel={onCancel} onSubmit={onSubmit} />);
|
||||
fireEvent.change(screen.getByLabelText('Insert Title'), {
|
||||
target: { value: 'Dinner' },
|
||||
});
|
||||
fireEvent.change(screen.getByLabelText('Type Option 1'), {
|
||||
target: { value: 'Pizza' },
|
||||
});
|
||||
fireEvent.change(screen.getByLabelText('Type Option 2'), {
|
||||
target: { value: 'Pasta' },
|
||||
});
|
||||
|
||||
const submit = screen.getByRole('button', { name: 'Create Poll' });
|
||||
fireEvent.click(submit);
|
||||
fireEvent.click(submit);
|
||||
|
||||
expect(onSubmit).toHaveBeenCalledTimes(1);
|
||||
expect(onCancel).not.toHaveBeenCalled();
|
||||
expect(submit).toBeDisabled();
|
||||
expect((onSubmit as any).mock.calls[0]?.[0]).toMatchObject({
|
||||
'org.matrix.msc3381.poll.start': expect.objectContaining({
|
||||
question: expect.objectContaining({ body: 'Dinner' }),
|
||||
}),
|
||||
});
|
||||
|
||||
resolveSubmit();
|
||||
await waitFor(() => expect(onCancel).toHaveBeenCalledTimes(1));
|
||||
});
|
||||
|
||||
it('keeps the dialog open and shows a retryable error when submission fails', async () => {
|
||||
const onSubmit = vi.fn().mockRejectedValueOnce(new Error('Send failed'));
|
||||
const onCancel = vi.fn();
|
||||
|
||||
render(<PollDialog onCancel={onCancel} onSubmit={onSubmit} />);
|
||||
fireEvent.change(screen.getByLabelText('Insert Title'), {
|
||||
target: { value: 'Dinner' },
|
||||
});
|
||||
fireEvent.change(screen.getByLabelText('Type Option 1'), {
|
||||
target: { value: 'Pizza' },
|
||||
});
|
||||
fireEvent.change(screen.getByLabelText('Type Option 2'), {
|
||||
target: { value: 'Pasta' },
|
||||
});
|
||||
|
||||
fireEvent.click(screen.getByRole('button', { name: 'Create Poll' }));
|
||||
|
||||
await waitFor(() => expect(screen.getByText('Send failed')).toBeInTheDocument());
|
||||
expect(onCancel).not.toHaveBeenCalled();
|
||||
expect(screen.getByRole('button', { name: 'Create Poll' })).not.toBeDisabled();
|
||||
});
|
||||
});
|
||||
@@ -18,7 +18,7 @@ import type { PollAnswerItem } from '$components/message/PollEvent';
|
||||
import { randomStr } from '$utils/common';
|
||||
import { SettingTile } from '$components/setting-tile';
|
||||
import { SequenceCard, SequenceCardStyle } from '$components/sequence-card';
|
||||
import type { IContent, MatrixClient, Room, TimelineEvents } from 'matrix-js-sdk';
|
||||
import type { IContent } from 'matrix-js-sdk';
|
||||
import {
|
||||
M_POLL_KIND_DISCLOSED,
|
||||
M_POLL_KIND_UNDISCLOSED,
|
||||
@@ -28,16 +28,11 @@ import {
|
||||
import { MsgType } from '$types/matrix-sdk';
|
||||
import { isKeyHotkey } from 'is-hotkey';
|
||||
import * as css from './PollDialog.css';
|
||||
import type { IReplyDraft } from '$state/room/roomInputDrafts';
|
||||
import { getReplyContent } from '../RoomInput';
|
||||
import { ModalOverlay } from '$components/modal-overlay/ModalOverlay';
|
||||
|
||||
type PollDialogProps = {
|
||||
onCancel: () => void;
|
||||
mx: MatrixClient;
|
||||
room: Room;
|
||||
replyDraft?: IReplyDraft;
|
||||
clearReplyDraft?: () => void;
|
||||
onSubmit: (content: IContent) => Promise<void>;
|
||||
};
|
||||
|
||||
type ErrorProps = {
|
||||
@@ -45,13 +40,14 @@ type ErrorProps = {
|
||||
errorString: string;
|
||||
};
|
||||
|
||||
export function PollDialog({ onCancel, mx, room, replyDraft, clearReplyDraft }: PollDialogProps) {
|
||||
const roomId = room.roomId;
|
||||
export function PollDialog({ onCancel, onSubmit }: PollDialogProps) {
|
||||
const [isDisclosed, setIsDisclosed] = useState(true);
|
||||
const [maxSelections, setMaxSelections] = useState(1);
|
||||
const [inputValue, setInputValue] = useState(1);
|
||||
const title = useRef<string>('');
|
||||
const [error, setError] = useState<ErrorProps | undefined>(undefined);
|
||||
const [submitError, setSubmitError] = useState<string | undefined>(undefined);
|
||||
const [isSubmitting, setIsSubmitting] = useState(false);
|
||||
const [answers, setAnswers] = useState<PollAnswerItem[]>([
|
||||
{
|
||||
id: randomStr(),
|
||||
@@ -88,7 +84,8 @@ export function PollDialog({ onCancel, mx, room, replyDraft, clearReplyDraft }:
|
||||
[answers, setAnswers, maxSelections, setMaxSelections]
|
||||
);
|
||||
|
||||
const handleSubmit = () => {
|
||||
const handleSubmit = async () => {
|
||||
if (isSubmitting) return;
|
||||
if (title.current.length === 0) {
|
||||
setError({ errorcode: 'title', errorString: 'Missing Title' });
|
||||
return;
|
||||
@@ -122,18 +119,18 @@ export function PollDialog({ onCancel, mx, room, replyDraft, clearReplyDraft }:
|
||||
},
|
||||
[M_TEXT.name]: `New poll\n Question: ${title.current}\nAnswers:\n ${answers.map((item) => item[M_TEXT.name]).join('\n')}`,
|
||||
};
|
||||
if (replyDraft && clearReplyDraft) {
|
||||
pollContent['m.relates_to'] = getReplyContent(replyDraft, room);
|
||||
clearReplyDraft();
|
||||
setSubmitError(undefined);
|
||||
setIsSubmitting(true);
|
||||
try {
|
||||
await onSubmit(pollContent);
|
||||
onCancel();
|
||||
} catch (err) {
|
||||
setSubmitError(
|
||||
err instanceof Error ? err.message : 'Failed to create poll. Please try again.'
|
||||
);
|
||||
} finally {
|
||||
setIsSubmitting(false);
|
||||
}
|
||||
|
||||
mx.sendEvent(
|
||||
roomId,
|
||||
M_POLL_START.name as keyof TimelineEvents,
|
||||
pollContent as TimelineEvents[keyof TimelineEvents]
|
||||
);
|
||||
|
||||
onCancel();
|
||||
};
|
||||
|
||||
const handleMaxOptions: ChangeEventHandler<HTMLInputElement> = (evt) => {
|
||||
@@ -155,7 +152,7 @@ export function PollDialog({ onCancel, mx, room, replyDraft, clearReplyDraft }:
|
||||
<Header className={css.PollDialogHeader} variant="Surface" size="500">
|
||||
<Box grow="Yes" gap="200">
|
||||
{composerIcon(ListBullets)}
|
||||
<Text size="H4">{`New Poll ${replyDraft ? '(reply / thread)' : ''}`} </Text>
|
||||
<Text size="H4">New Poll</Text>
|
||||
</Box>
|
||||
<IconButton
|
||||
size="300"
|
||||
@@ -288,6 +285,7 @@ export function PollDialog({ onCancel, mx, room, replyDraft, clearReplyDraft }:
|
||||
type="submit"
|
||||
variant="Primary"
|
||||
onClick={handleSubmit}
|
||||
disabled={isSubmitting}
|
||||
fill="Soft"
|
||||
title="Create Poll"
|
||||
aria-label="Create Poll"
|
||||
@@ -299,6 +297,11 @@ export function PollDialog({ onCancel, mx, room, replyDraft, clearReplyDraft }:
|
||||
{error.errorString}
|
||||
</Text>
|
||||
)}
|
||||
{!!submitError && (
|
||||
<Text align="Center" size="B500" style={{ color: color.Critical.OnContainer }}>
|
||||
{submitError}
|
||||
</Text>
|
||||
)}
|
||||
</Box>
|
||||
</Dialog>
|
||||
</ModalOverlay>
|
||||
|
||||
@@ -0,0 +1,202 @@
|
||||
/* oxlint-disable typescript/no-explicit-any, typescript/no-extraneous-class, unicorn/consistent-function-scoping, vitest/require-mock-type-parameters */
|
||||
|
||||
import { fireEvent, render, screen, waitFor } from '@testing-library/react';
|
||||
import { beforeEach, describe, expect, it, vi } from 'vitest';
|
||||
import { ScheduledMessagesList } from './ScheduledMessagesList';
|
||||
import type * as MatrixSdkModule from '$types/matrix-sdk';
|
||||
|
||||
const testState = vi.hoisted(() => ({
|
||||
cancelDelayedEvent: vi.fn(),
|
||||
coordinatorRun: vi.fn(),
|
||||
invalidateQueries: vi.fn(),
|
||||
matrix: {
|
||||
getSafeUserId: vi.fn(() => '@me:example.org'),
|
||||
},
|
||||
}));
|
||||
|
||||
vi.mock('$hooks/useMatrixClient', () => ({
|
||||
useMatrixClient: () => testState.matrix,
|
||||
}));
|
||||
|
||||
vi.mock('$utils/delayedEvents', () => ({
|
||||
cancelDelayedEvent: testState.cancelDelayedEvent,
|
||||
getDelayedEvents: vi.fn(),
|
||||
}));
|
||||
|
||||
vi.mock('$state/room/roomScheduleCoordinator', () => ({
|
||||
roomScheduleCoordinator: {
|
||||
run: testState.coordinatorRun,
|
||||
},
|
||||
}));
|
||||
|
||||
vi.mock('@tanstack/react-query', () => ({
|
||||
useQuery: () => ({
|
||||
data: {
|
||||
delayed_events: [
|
||||
{
|
||||
delay_id: 'delay-1',
|
||||
room_id: '!room:example.org',
|
||||
type: 'm.room.message',
|
||||
content: { body: 'Scheduled message' },
|
||||
running_since: 1_000,
|
||||
delay: 60_000,
|
||||
},
|
||||
],
|
||||
},
|
||||
}),
|
||||
useQueryClient: () => ({ invalidateQueries: testState.invalidateQueries }),
|
||||
}));
|
||||
|
||||
vi.mock('$state/scheduledMessages', async () => {
|
||||
const { atom } = await import('jotai');
|
||||
const scheduledTimeAtom = atom<Date | null>(null);
|
||||
const editingScheduledDelayIdAtom = atom<string | null>(null);
|
||||
|
||||
return {
|
||||
delayedEventsSupportedAtom: atom(true),
|
||||
getScheduledMessageStateKey: (userId: string, roomId: string) => `${userId}\0${roomId}`,
|
||||
roomIdToScheduledTimeAtomFamily: () => scheduledTimeAtom,
|
||||
roomIdToEditingScheduledDelayIdAtomFamily: () => editingScheduledDelayIdAtom,
|
||||
};
|
||||
});
|
||||
|
||||
vi.mock('$state/hooks/settings', () => ({
|
||||
useSetting: (_atom: unknown, key: string) => [
|
||||
key === 'hour24Clock' ? false : 'YYYY-MM-DD',
|
||||
vi.fn(),
|
||||
],
|
||||
}));
|
||||
|
||||
vi.mock('$state/settings', () => ({ settingsAtom: {} }));
|
||||
|
||||
vi.mock('$types/matrix-sdk', async (importOriginal) => ({
|
||||
...(await importOriginal<typeof MatrixSdkModule>()),
|
||||
MatrixEvent: class MatrixEvent {},
|
||||
}));
|
||||
|
||||
vi.mock('$utils/time', () => ({
|
||||
timeDayMonthYear: () => '2026-07-28',
|
||||
timeHourMinute: () => '00:01',
|
||||
}));
|
||||
|
||||
vi.mock('$components/message-preview', () => ({
|
||||
MessagePreview: ({ actions, event }: any) => (
|
||||
<div>
|
||||
<span>{event.getContent?.().body ?? 'Scheduled message'}</span>
|
||||
{actions}
|
||||
</div>
|
||||
),
|
||||
useRoomMessagePreviewRenderer: () => vi.fn(),
|
||||
}));
|
||||
|
||||
vi.mock('$components/icons/phosphor', () => ({
|
||||
CaretDown: 'CaretDown',
|
||||
CaretUp: 'CaretUp',
|
||||
Clock: 'Clock',
|
||||
Lock: 'Lock',
|
||||
PencilSimple: 'PencilSimple',
|
||||
X: 'X',
|
||||
chipIcon: () => null,
|
||||
}));
|
||||
|
||||
vi.mock('folds', () => {
|
||||
const Box = ({ children, ...props }: any) => <div {...props}>{children}</div>;
|
||||
const Text = ({ children, ...props }: any) => <span {...props}>{children}</span>;
|
||||
const Button = ({ children, ...props }: any) => <button {...props}>{children}</button>;
|
||||
|
||||
return {
|
||||
Box,
|
||||
Chip: Button,
|
||||
IconButton: Button,
|
||||
Spinner: () => <span role="progressbar">Cancelling</span>,
|
||||
Text,
|
||||
config: {
|
||||
borderWidth: { B300: '1px' },
|
||||
space: { S100: '1px', S200: '2px', S400: '4px' },
|
||||
},
|
||||
toRem: (value: number) => `${value / 16}rem`,
|
||||
};
|
||||
});
|
||||
|
||||
vi.mock('./SchedulePickerDialog', () => ({
|
||||
SchedulePickerDialog: () => null,
|
||||
}));
|
||||
|
||||
const room = { roomId: '!room:example.org' } as any;
|
||||
|
||||
function deferred<T>() {
|
||||
let resolve!: (value: T) => void;
|
||||
let reject!: (reason?: unknown) => void;
|
||||
const promise = new Promise<T>((promiseResolve, promiseReject) => {
|
||||
resolve = promiseResolve;
|
||||
reject = promiseReject;
|
||||
});
|
||||
return { promise, resolve, reject };
|
||||
}
|
||||
|
||||
function renderExpandedList() {
|
||||
render(<ScheduledMessagesList room={room} />);
|
||||
fireEvent.click(screen.getByRole('button', { name: /1 scheduled message/i }));
|
||||
return screen.getByRole('button', { name: 'Cancel scheduled message' });
|
||||
}
|
||||
|
||||
describe('ScheduledMessagesList cancellation', () => {
|
||||
beforeEach(() => {
|
||||
testState.cancelDelayedEvent.mockReset();
|
||||
testState.coordinatorRun.mockReset();
|
||||
testState.invalidateQueries.mockReset();
|
||||
testState.coordinatorRun.mockImplementation(
|
||||
(_mx: unknown, _roomId: string, operation: () => unknown) => operation()
|
||||
);
|
||||
});
|
||||
|
||||
it('blocks duplicate cancellation clicks and shows pending state', () => {
|
||||
const pending = deferred<void>();
|
||||
testState.cancelDelayedEvent.mockReturnValue(pending.promise);
|
||||
|
||||
const cancel = renderExpandedList();
|
||||
fireEvent.click(cancel);
|
||||
fireEvent.click(cancel);
|
||||
|
||||
expect(testState.coordinatorRun).toHaveBeenCalledWith(
|
||||
testState.matrix,
|
||||
room.roomId,
|
||||
expect.any(Function)
|
||||
);
|
||||
expect(testState.cancelDelayedEvent).toHaveBeenCalledOnce();
|
||||
expect(cancel).toBeDisabled();
|
||||
expect(cancel).toHaveAttribute('aria-busy', 'true');
|
||||
expect(screen.getByRole('progressbar')).toBeInTheDocument();
|
||||
});
|
||||
|
||||
it('shows a retryable alert when cancellation fails', async () => {
|
||||
testState.cancelDelayedEvent.mockRejectedValueOnce(new Error('Cancel failed'));
|
||||
const cancel = renderExpandedList();
|
||||
|
||||
fireEvent.click(cancel);
|
||||
|
||||
await waitFor(() =>
|
||||
expect(screen.getByRole('alert')).toHaveTextContent(
|
||||
'Failed to cancel scheduled message. Try again.'
|
||||
)
|
||||
);
|
||||
expect(cancel).not.toBeDisabled();
|
||||
expect(cancel).not.toHaveAttribute('aria-busy', 'true');
|
||||
});
|
||||
|
||||
it('successfully retries cancellation after a failure', async () => {
|
||||
testState.cancelDelayedEvent
|
||||
.mockRejectedValueOnce(new Error('Cancel failed'))
|
||||
.mockResolvedValueOnce(undefined);
|
||||
const cancel = renderExpandedList();
|
||||
|
||||
fireEvent.click(cancel);
|
||||
await waitFor(() => expect(screen.getByRole('alert')).toBeInTheDocument());
|
||||
|
||||
fireEvent.click(cancel);
|
||||
|
||||
await waitFor(() => expect(testState.cancelDelayedEvent).toHaveBeenCalledTimes(2));
|
||||
await waitFor(() => expect(testState.invalidateQueries).toHaveBeenCalledOnce());
|
||||
expect(screen.queryByRole('alert')).not.toBeInTheDocument();
|
||||
});
|
||||
});
|
||||
@@ -1,6 +1,6 @@
|
||||
import { useCallback, useMemo, useState } from 'react';
|
||||
import { useCallback, useMemo, useRef, useState } from 'react';
|
||||
import { useQuery, useQueryClient } from '@tanstack/react-query';
|
||||
import { Box, Text, Chip, IconButton } from 'folds';
|
||||
import { Box, Text, Chip, IconButton, Spinner } from 'folds';
|
||||
import {
|
||||
CaretDown,
|
||||
CaretUp,
|
||||
@@ -21,12 +21,14 @@ import {
|
||||
} from '$utils/delayedEvents';
|
||||
import {
|
||||
delayedEventsSupportedAtom,
|
||||
getScheduledMessageStateKey,
|
||||
roomIdToScheduledTimeAtomFamily,
|
||||
roomIdToEditingScheduledDelayIdAtomFamily,
|
||||
} from '$state/scheduledMessages';
|
||||
import { timeHourMinute, timeDayMonthYear } from '$utils/time';
|
||||
import { useSetting } from '$state/hooks/settings';
|
||||
import { settingsAtom } from '$state/settings';
|
||||
import { roomScheduleCoordinator } from '$state/room/roomScheduleCoordinator';
|
||||
import { MessagePreview, useRoomMessagePreviewRenderer } from '$components/message-preview';
|
||||
import { SchedulePickerDialog } from './SchedulePickerDialog';
|
||||
import * as css from './ScheduledMessagesList.css';
|
||||
@@ -44,6 +46,12 @@ type ScheduledMessageRowProps = {
|
||||
hour24Clock: boolean;
|
||||
onEdit: (delayId: string, body: string, formattedBody?: string, scheduledTs?: number) => void;
|
||||
onCancel: (delayId: string) => void;
|
||||
cancellationState: CancellationState;
|
||||
};
|
||||
|
||||
type CancellationState = {
|
||||
status: 'idle' | 'pending' | 'error';
|
||||
error?: string;
|
||||
};
|
||||
|
||||
function ScheduledMessageRow({
|
||||
@@ -52,6 +60,7 @@ function ScheduledMessageRow({
|
||||
hour24Clock,
|
||||
onEdit,
|
||||
onCancel,
|
||||
cancellationState,
|
||||
}: ScheduledMessageRowProps) {
|
||||
const mx = useMatrixClient();
|
||||
const [dateFormatString] = useSetting(settingsAtom, 'dateFormatString');
|
||||
@@ -63,6 +72,8 @@ function ScheduledMessageRow({
|
||||
!isEncrypted && typeof event.content.formatted_body === 'string'
|
||||
? event.content.formatted_body
|
||||
: undefined;
|
||||
const isCancelling = cancellationState.status === 'pending';
|
||||
const cancelIcon = isCancelling ? <Spinner size="100" /> : chipIcon(X);
|
||||
const matrixEvent = useMemo(
|
||||
() =>
|
||||
new MatrixEvent({
|
||||
@@ -106,9 +117,11 @@ function ScheduledMessageRow({
|
||||
variant="Critical"
|
||||
radii="300"
|
||||
onClick={() => onCancel(event.delay_id)}
|
||||
disabled={isCancelling}
|
||||
aria-busy={isCancelling}
|
||||
aria-label="Cancel scheduled message"
|
||||
>
|
||||
{chipIcon(X)}
|
||||
{cancelIcon}
|
||||
</IconButton>
|
||||
</Box>
|
||||
}
|
||||
@@ -126,12 +139,19 @@ function ScheduledMessageRow({
|
||||
variant="Critical"
|
||||
radii="300"
|
||||
onClick={() => onCancel(event.delay_id)}
|
||||
disabled={isCancelling}
|
||||
aria-busy={isCancelling}
|
||||
aria-label="Cancel scheduled message"
|
||||
>
|
||||
{chipIcon(X)}
|
||||
{cancelIcon}
|
||||
</IconButton>
|
||||
)}
|
||||
</Box>
|
||||
{cancellationState.status === 'error' && (
|
||||
<Text size="T200" priority="300" role="alert" aria-live="polite">
|
||||
{cancellationState.error}
|
||||
</Text>
|
||||
)}
|
||||
</Box>
|
||||
);
|
||||
}
|
||||
@@ -140,12 +160,17 @@ export function ScheduledMessagesList({ room, onEditMessage }: ScheduledMessages
|
||||
const mx = useMatrixClient();
|
||||
const queryClient = useQueryClient();
|
||||
const supported = useAtomValue(delayedEventsSupportedAtom);
|
||||
const setScheduledTime = useSetAtom(roomIdToScheduledTimeAtomFamily(room.roomId));
|
||||
const scheduledStateKey = getScheduledMessageStateKey(mx.getSafeUserId(), room.roomId);
|
||||
const setScheduledTime = useSetAtom(roomIdToScheduledTimeAtomFamily(scheduledStateKey));
|
||||
const [hour24Clock] = useSetting(settingsAtom, 'hour24Clock');
|
||||
const [expanded, setExpanded] = useState(false);
|
||||
const [editingDelayId, setEditingDelayId] = useAtom(
|
||||
roomIdToEditingScheduledDelayIdAtomFamily(room.roomId)
|
||||
roomIdToEditingScheduledDelayIdAtomFamily(scheduledStateKey)
|
||||
);
|
||||
const [cancellationStates, setCancellationStates] = useState<Record<string, CancellationState>>(
|
||||
{}
|
||||
);
|
||||
const pendingCancellations = useRef(new Set<string>());
|
||||
|
||||
const { data } = useQuery({
|
||||
queryKey: ['delayedEvents', room.roomId],
|
||||
@@ -167,10 +192,35 @@ export function ScheduledMessagesList({ room, onEditMessage }: ScheduledMessages
|
||||
|
||||
const handleCancel = useCallback(
|
||||
async (delayId: string) => {
|
||||
await cancelDelayedEvent(mx, delayId);
|
||||
invalidateEvents();
|
||||
if (pendingCancellations.current.has(delayId)) return;
|
||||
|
||||
pendingCancellations.current.add(delayId);
|
||||
setCancellationStates((states) => ({
|
||||
...states,
|
||||
[delayId]: { status: 'pending' },
|
||||
}));
|
||||
|
||||
try {
|
||||
await roomScheduleCoordinator.run(mx, room.roomId, () => cancelDelayedEvent(mx, delayId));
|
||||
invalidateEvents();
|
||||
setCancellationStates((states) => {
|
||||
const next = { ...states };
|
||||
delete next[delayId];
|
||||
return next;
|
||||
});
|
||||
} catch {
|
||||
setCancellationStates((states) => ({
|
||||
...states,
|
||||
[delayId]: {
|
||||
status: 'error',
|
||||
error: 'Failed to cancel scheduled message. Try again.',
|
||||
},
|
||||
}));
|
||||
} finally {
|
||||
pendingCancellations.current.delete(delayId);
|
||||
}
|
||||
},
|
||||
[mx, invalidateEvents]
|
||||
[mx, room.roomId, invalidateEvents]
|
||||
);
|
||||
|
||||
const handleEdit = useCallback(
|
||||
@@ -218,6 +268,7 @@ export function ScheduledMessagesList({ room, onEditMessage }: ScheduledMessages
|
||||
hour24Clock={hour24Clock}
|
||||
onEdit={handleEdit}
|
||||
onCancel={handleCancel}
|
||||
cancellationState={cancellationStates[event.delay_id] ?? { status: 'idle' }}
|
||||
/>
|
||||
))}
|
||||
</Box>
|
||||
|
||||
@@ -8,78 +8,108 @@ export function PKCompatSettings() {
|
||||
const [usePKCompat, setUsePKCompat] = useSetting(settingsAtom, 'pkCompat');
|
||||
const [usePmpProxying, setUsePmpProxying] = useSetting(settingsAtom, 'pmpProxying');
|
||||
const [usePmpLatching, setUsePmpLatching] = useSetting(settingsAtom, 'pmpLatching');
|
||||
const [usePmpNoFallback, setUsePmpNoFallback] = useSetting(settingsAtom, 'pmpNoFallback');
|
||||
|
||||
return (
|
||||
<Box direction="Column" gap="100">
|
||||
<Text size="L400">Limited Compatibility with PluralKit-like functions</Text>
|
||||
<SequenceCard
|
||||
className={SequenceCardStyle}
|
||||
variant="SurfaceVariant"
|
||||
direction="Column"
|
||||
gap="100"
|
||||
>
|
||||
<SettingTile
|
||||
focusId="enable-pk-commands"
|
||||
title="Enable PK commands"
|
||||
description="If enabled, it will enable a few pk style commands, currently verry limited"
|
||||
after={
|
||||
<Switch
|
||||
variant="Primary"
|
||||
value={usePKCompat}
|
||||
onChange={setUsePKCompat}
|
||||
title={usePKCompat ? 'disable pk; commands' : 'enable pk; commands'}
|
||||
/>
|
||||
}
|
||||
/>
|
||||
</SequenceCard>
|
||||
<SequenceCard
|
||||
className={SequenceCardStyle}
|
||||
variant="SurfaceVariant"
|
||||
direction="Column"
|
||||
gap="100"
|
||||
>
|
||||
<SettingTile
|
||||
focusId="enable-pk-shorthands"
|
||||
title="Enable Shorthands"
|
||||
description="If enabled, you can use shorthands to use a Persona for one message only (eg. '✨:test')"
|
||||
after={
|
||||
<Switch
|
||||
variant="Primary"
|
||||
value={usePmpProxying}
|
||||
onChange={setUsePmpProxying}
|
||||
title={
|
||||
usePmpProxying
|
||||
? 'disable checking typed messages for shorthands'
|
||||
: 'enable checking typed messages for shorthands'
|
||||
}
|
||||
/>
|
||||
}
|
||||
/>
|
||||
</SequenceCard>
|
||||
<SequenceCard
|
||||
className={SequenceCardStyle}
|
||||
variant="SurfaceVariant"
|
||||
direction="Column"
|
||||
gap="100"
|
||||
>
|
||||
<SettingTile
|
||||
focusId="enable-pk-latching"
|
||||
title="Enable Shorthand Latching"
|
||||
description="If enabled, you change a room's persona when you use a shorthand."
|
||||
after={
|
||||
<Switch
|
||||
variant="Primary"
|
||||
value={usePmpLatching}
|
||||
onChange={setUsePmpLatching}
|
||||
title={
|
||||
usePmpLatching
|
||||
? 'disable latching when using a shorthand'
|
||||
: 'enable latching when using a shorthand'
|
||||
}
|
||||
/>
|
||||
}
|
||||
/>
|
||||
</SequenceCard>
|
||||
</Box>
|
||||
<>
|
||||
<Box direction="Column" gap="100">
|
||||
<Text size="L400">Limited Compatibility with PluralKit-like functions</Text>
|
||||
<SequenceCard
|
||||
className={SequenceCardStyle}
|
||||
variant="SurfaceVariant"
|
||||
direction="Column"
|
||||
gap="100"
|
||||
>
|
||||
<SettingTile
|
||||
focusId="enable-pk-commands"
|
||||
title="Enable PK commands"
|
||||
description="If enabled, it will enable a few pk style commands, currently verry limited"
|
||||
after={
|
||||
<Switch
|
||||
variant="Primary"
|
||||
value={usePKCompat}
|
||||
onChange={setUsePKCompat}
|
||||
title={usePKCompat ? 'disable pk; commands' : 'enable pk; commands'}
|
||||
/>
|
||||
}
|
||||
/>
|
||||
</SequenceCard>
|
||||
<SequenceCard
|
||||
className={SequenceCardStyle}
|
||||
variant="SurfaceVariant"
|
||||
direction="Column"
|
||||
gap="100"
|
||||
>
|
||||
<SettingTile
|
||||
focusId="enable-pk-shorthands"
|
||||
title="Enable Shorthands"
|
||||
description="If enabled, you can use shorthands to use a Persona for one message only (eg. '✨:test')"
|
||||
after={
|
||||
<Switch
|
||||
variant="Primary"
|
||||
value={usePmpProxying}
|
||||
onChange={setUsePmpProxying}
|
||||
title={
|
||||
usePmpProxying
|
||||
? 'disable checking typed messages for shorthands'
|
||||
: 'enable checking typed messages for shorthands'
|
||||
}
|
||||
/>
|
||||
}
|
||||
/>
|
||||
</SequenceCard>
|
||||
<SequenceCard
|
||||
className={SequenceCardStyle}
|
||||
variant="SurfaceVariant"
|
||||
direction="Column"
|
||||
gap="100"
|
||||
>
|
||||
<SettingTile
|
||||
focusId="enable-pk-latching"
|
||||
title="Enable Shorthand Latching"
|
||||
description="If enabled, you change a room's persona when you use a shorthand."
|
||||
after={
|
||||
<Switch
|
||||
variant="Primary"
|
||||
value={usePmpLatching}
|
||||
onChange={setUsePmpLatching}
|
||||
title={
|
||||
usePmpLatching
|
||||
? 'disable latching when using a shorthand'
|
||||
: 'enable latching when using a shorthand'
|
||||
}
|
||||
/>
|
||||
}
|
||||
/>
|
||||
</SequenceCard>
|
||||
</Box>
|
||||
<Box direction="Column" gap="100">
|
||||
<Text size="L400">General Behavior</Text>
|
||||
<SequenceCard
|
||||
className={SequenceCardStyle}
|
||||
variant="SurfaceVariant"
|
||||
direction="Column"
|
||||
gap="100"
|
||||
>
|
||||
<SettingTile
|
||||
focusId="prevent-sending-pmp-fallback"
|
||||
title="Prevent sending Persona fallback"
|
||||
description="If enabled, your messages will not include a prefix with your name to show clients that do not support Personas."
|
||||
after={
|
||||
<Switch
|
||||
variant="Primary"
|
||||
value={usePmpNoFallback}
|
||||
onChange={setUsePmpNoFallback}
|
||||
title={
|
||||
usePmpNoFallback
|
||||
? 'do not prevent fallbacks when sending a persona attached message'
|
||||
: 'prevent fallbacks when sending a persona attached message'
|
||||
}
|
||||
/>
|
||||
}
|
||||
/>
|
||||
</SequenceCard>
|
||||
</Box>
|
||||
</>
|
||||
);
|
||||
}
|
||||
@@ -1,4 +1,5 @@
|
||||
import { SequenceCard, SequenceCardStyle } from '$components/sequence-card';
|
||||
import { nanoid } from 'nanoid';
|
||||
import { Box, Button, Text, Avatar, config, IconButton, Input, toRem, Spinner, color } from 'folds';
|
||||
import { menuIcon, Trash, X } from '$components/icons/phosphor';
|
||||
import type { MatrixClient } from '$types/matrix-sdk';
|
||||
@@ -11,67 +12,62 @@ import { useObjectURL } from '$hooks/useObjectURL';
|
||||
import { createUploadAtom } from '$state/upload';
|
||||
import { UserAvatar } from '$components/user-avatar';
|
||||
import { CompactUploadCardRenderer } from '$components/upload-card';
|
||||
import type { ProfileTrigger } from '$hooks/usePerMessageProfile';
|
||||
import {
|
||||
addOrUpdatePerMessageProfile,
|
||||
associateProxyWithProfile,
|
||||
createProxyKey,
|
||||
deletePerMessageProfile,
|
||||
dropProxyAssociationForPMP,
|
||||
getAllPerMessageProfileProxies,
|
||||
getAllProxiesForPMP,
|
||||
getPerMessageProfileById,
|
||||
type PerMessageProfileProxyAssociationV2,
|
||||
renamePerMessageProfile,
|
||||
} from '$hooks/usePerMessageProfile';
|
||||
import type { PronounSet } from '$utils/pronouns';
|
||||
import { parsePronounsStringToPronounsSetArray } from '$utils/pronouns';
|
||||
import { generateShortId } from '$utils/shortIdGen';
|
||||
import { SettingTile } from '$components/setting-tile';
|
||||
import { type AsyncState, AsyncStatus, useAsyncCallback } from '$hooks/useAsyncCallback';
|
||||
import { AsyncStatus, useAsyncCallback } from '$hooks/useAsyncCallback';
|
||||
import { NameColorEditor } from '../account/NameColorEditor';
|
||||
import {
|
||||
MATRIX_SABLE_UNSTABLE_MSC4461_TRIGGER_CIRCUMFIX_PROPERTY_NAME,
|
||||
MATRIX_SABLE_UNSTABLE_MSC4461_TRIGGER_SUFFIX_PROPERTY_NAME,
|
||||
MATRIX_UNSTABLE_COLORS,
|
||||
MATRIX_UNSTABLE_PROFILE_PRONOUNS_PROPERTY_NAME,
|
||||
} from '$unstable/prefixes';
|
||||
import { accessibleColor } from '$plugins/color';
|
||||
import { ThemeKind } from '$hooks/useTheme';
|
||||
|
||||
const constructProxyString = (s: Shorthand) => {
|
||||
return `${s.prefix ?? ''}text${s.suffix ?? ''}`;
|
||||
};
|
||||
type Shorthand = { prefix?: string; suffix?: string };
|
||||
type ShorthandRow = Shorthand & { id: string };
|
||||
|
||||
type Shorthand = { id: string; prefix?: string; suffix?: string };
|
||||
type ShorthandRow = Shorthand & { rowId: string };
|
||||
|
||||
type ShorthandListItemProps = Shorthand & {
|
||||
type ShorthandListItemProps = ShorthandRow & {
|
||||
onDelete: (shorthandId: string) => void;
|
||||
onSave: (shorthandId: string, shorthand: Shorthand) => void;
|
||||
deleteState: AsyncState<void>;
|
||||
saveState: AsyncState<void>;
|
||||
onChange: (shorthandId: string, shorthand: Shorthand) => void;
|
||||
};
|
||||
function ShorthandListItem({
|
||||
id,
|
||||
prefix,
|
||||
suffix,
|
||||
onDelete,
|
||||
onSave,
|
||||
deleteState,
|
||||
saveState,
|
||||
}: ShorthandListItemProps) {
|
||||
const [currentPrefix] = useState(prefix);
|
||||
const [currentSuffix] = useState(suffix);
|
||||
function ShorthandListItem({ id, prefix, suffix, onDelete, onChange }: ShorthandListItemProps) {
|
||||
const [newPrefix, setNewPrefix] = useState(prefix);
|
||||
const [newSuffix, setNewSuffix] = useState(suffix);
|
||||
|
||||
const [prefixWarn, setPrefixWarn] = useState(false);
|
||||
const [suffixWarn, setSuffixWarn] = useState(false);
|
||||
|
||||
const handlePrefixChange = useCallback((e: React.ChangeEvent<HTMLInputElement>) => {
|
||||
setNewPrefix(e.target.value);
|
||||
}, []);
|
||||
const handleSuffixChange = useCallback((e: React.ChangeEvent<HTMLInputElement>) => {
|
||||
setNewSuffix(e.target.value);
|
||||
}, []);
|
||||
|
||||
const hasChanges = useMemo(
|
||||
() =>
|
||||
(newPrefix ?? '') !== (currentPrefix ?? '') || (newSuffix ?? '') !== (currentSuffix ?? ''),
|
||||
[newPrefix, newSuffix, currentPrefix, currentSuffix]
|
||||
const handlePrefixChange = useCallback(
|
||||
(e: React.ChangeEvent<HTMLInputElement>) => {
|
||||
onChange(id, {
|
||||
prefix: e.target.value.trimStart(),
|
||||
suffix: newSuffix?.trimEnd(),
|
||||
});
|
||||
setNewPrefix(e.target.value);
|
||||
},
|
||||
[newSuffix, id, onChange]
|
||||
);
|
||||
const handleSuffixChange = useCallback(
|
||||
(e: React.ChangeEvent<HTMLInputElement>) => {
|
||||
// if you call setNewSuffix then use newSuffix you get race conditioned lol
|
||||
onChange(id, {
|
||||
prefix: newPrefix?.trimStart(),
|
||||
suffix: e.target.value.trimEnd(),
|
||||
});
|
||||
setNewSuffix(e.target.value);
|
||||
},
|
||||
[newPrefix, id, onChange]
|
||||
);
|
||||
|
||||
const isBlank = useMemo(() => !newPrefix && !newSuffix, [newPrefix, newSuffix]);
|
||||
|
||||
useEffect(() => {
|
||||
@@ -79,13 +75,6 @@ function ShorthandListItem({
|
||||
setSuffixWarn((newSuffix ?? '').startsWith(' '));
|
||||
}, [newPrefix, newSuffix]);
|
||||
|
||||
const handleSave = () =>
|
||||
onSave(id, {
|
||||
id: createProxyKey(newPrefix, newSuffix),
|
||||
prefix: newPrefix?.trimStart(),
|
||||
suffix: newSuffix?.trimEnd(),
|
||||
});
|
||||
|
||||
return (
|
||||
<SequenceCard
|
||||
className={SequenceCardStyle}
|
||||
@@ -138,27 +127,7 @@ function ShorthandListItem({
|
||||
radii="300"
|
||||
aria-label="Delete shorthand"
|
||||
>
|
||||
{deleteState.status === AsyncStatus.Loading ? (
|
||||
<Spinner size="100" variant="Primary" fill="Solid" />
|
||||
) : (
|
||||
menuIcon(Trash)
|
||||
)}
|
||||
</Button>
|
||||
<Button
|
||||
onClick={handleSave}
|
||||
size="300"
|
||||
variant="Primary"
|
||||
disabled={!hasChanges}
|
||||
fill="Soft"
|
||||
outlined
|
||||
radii="300"
|
||||
aria-label="Update shorthand"
|
||||
>
|
||||
{saveState.status === AsyncStatus.Loading ? (
|
||||
<Spinner size="100" variant="Primary" fill="Solid" />
|
||||
) : (
|
||||
<Text size="B300">Save</Text>
|
||||
)}
|
||||
{menuIcon(Trash)}
|
||||
</Button>
|
||||
</Box>
|
||||
</Box>
|
||||
@@ -167,154 +136,51 @@ function ShorthandListItem({
|
||||
);
|
||||
}
|
||||
|
||||
type ShorthandEditorProps = {
|
||||
mx: MatrixClient;
|
||||
profileId: string;
|
||||
};
|
||||
function ShorthandEditor({ mx, profileId }: ShorthandEditorProps) {
|
||||
const [shorthands, setShorthands] = useState<ShorthandRow[]>();
|
||||
|
||||
const containsBlankShorthand = useMemo(
|
||||
() => shorthands && shorthands.some((shorthand) => !shorthand.prefix && !shorthand.suffix),
|
||||
[shorthands]
|
||||
);
|
||||
|
||||
const handleAddShorthand = () => {
|
||||
if (shorthands !== undefined) {
|
||||
setShorthands([...shorthands, { id: 'blank', rowId: generateShortId(16) }]);
|
||||
function triggersToShorthandRows(trigger: ProfileTrigger): ShorthandRow[] {
|
||||
const prefixes: ShorthandRow[] = trigger.prefix.map((str) => {
|
||||
return { prefix: str, id: nanoid() };
|
||||
});
|
||||
const suffixes: ShorthandRow[] | undefined = trigger['net.f0rest.suffix']?.map((str) => {
|
||||
return { suffix: str, id: nanoid() };
|
||||
});
|
||||
const circumfixes: ShorthandRow[] | undefined = trigger['net.f0rest.circumfix']?.map(
|
||||
({ prefix, suffix }) => {
|
||||
return { prefix: prefix, suffix: suffix, id: nanoid() };
|
||||
}
|
||||
};
|
||||
|
||||
const [deleteShorthandState, handleDeleteShorthand] = useAsyncCallback(
|
||||
useCallback(
|
||||
async (id: string) => {
|
||||
if (shorthands === undefined) return;
|
||||
|
||||
const shorthandToDelete = shorthands.find((shorthand) => shorthand.id === id);
|
||||
if (!shorthandToDelete) return;
|
||||
|
||||
const proxy = constructProxyString(shorthandToDelete);
|
||||
|
||||
await dropProxyAssociationForPMP(mx, proxy);
|
||||
|
||||
setShorthands((s) => s?.filter((shorthand) => shorthand.id !== id));
|
||||
},
|
||||
[mx, shorthands]
|
||||
)
|
||||
);
|
||||
|
||||
const [saveShorthandState, handleSaveShorthand] = useAsyncCallback<
|
||||
void,
|
||||
Error,
|
||||
[string, Shorthand]
|
||||
>(
|
||||
useCallback(
|
||||
async (oldId: string, shorthand: Shorthand) => {
|
||||
if (shorthands === undefined) return;
|
||||
|
||||
const shorthandAssociation = (await getAllPerMessageProfileProxies(mx)).find(
|
||||
(association) => createProxyKey(association.prefix, association.suffix) === shorthand.id
|
||||
);
|
||||
const shorthandAssociatedProfile = shorthandAssociation
|
||||
? await getPerMessageProfileById(mx, shorthandAssociation.profileId)
|
||||
: undefined;
|
||||
if (shorthandAssociatedProfile) {
|
||||
throw new Error(
|
||||
`Shorthand is already associated with profile ${shorthandAssociatedProfile.name} (${shorthandAssociatedProfile.id})`
|
||||
);
|
||||
}
|
||||
|
||||
if (oldId !== 'blank') {
|
||||
await dropProxyAssociationForPMP(mx, oldId);
|
||||
}
|
||||
await associateProxyWithProfile(mx, profileId, shorthand.prefix, shorthand.suffix, false);
|
||||
|
||||
setShorthands((currentShorthands) => {
|
||||
if (currentShorthands === undefined) return currentShorthands;
|
||||
|
||||
const oldShorthandIdx = currentShorthands.findIndex((s) => s.id === oldId);
|
||||
if (oldShorthandIdx < 0) return currentShorthands;
|
||||
const oldShorthand = currentShorthands[oldShorthandIdx];
|
||||
if (oldShorthand === undefined) return currentShorthands;
|
||||
|
||||
return currentShorthands.with(oldShorthandIdx, {
|
||||
...shorthand,
|
||||
rowId: oldShorthand.rowId,
|
||||
});
|
||||
});
|
||||
},
|
||||
[mx, shorthands, profileId]
|
||||
)
|
||||
);
|
||||
|
||||
useEffect(() => {
|
||||
const fetchShorthands = async () => {
|
||||
const fetchedShorthands: PerMessageProfileProxyAssociationV2[] = await getAllProxiesForPMP(
|
||||
mx,
|
||||
profileId
|
||||
);
|
||||
const enumeratedShorthands: ShorthandRow[] = fetchedShorthands.map((v) => {
|
||||
return { id: createProxyKey(v.prefix, v.suffix), rowId: generateShortId(16), ...v };
|
||||
});
|
||||
setShorthands(enumeratedShorthands);
|
||||
};
|
||||
fetchShorthands();
|
||||
}, [mx, profileId]);
|
||||
|
||||
return (
|
||||
<>
|
||||
<SequenceCard
|
||||
className={SequenceCardStyle}
|
||||
variant="SurfaceVariant"
|
||||
direction="Column"
|
||||
gap="400"
|
||||
>
|
||||
<SettingTile
|
||||
title="Shorthands"
|
||||
description="Use this persona for a single message using a prefix or suffix."
|
||||
focusId={`shorthandsInput-${profileId}`}
|
||||
>
|
||||
{saveShorthandState.status === AsyncStatus.Error && (
|
||||
<Text size="T200" style={{ color: color.Critical.Main }}>
|
||||
{saveShorthandState.error.toString()}
|
||||
</Text>
|
||||
)}
|
||||
{shorthands === undefined ? (
|
||||
<Spinner size="400" />
|
||||
) : (
|
||||
shorthands.map((shorthand: ShorthandRow) => (
|
||||
<ShorthandListItem
|
||||
key={shorthand.rowId}
|
||||
id={shorthand.id}
|
||||
prefix={shorthand.prefix}
|
||||
suffix={shorthand.suffix}
|
||||
onDelete={handleDeleteShorthand}
|
||||
onSave={handleSaveShorthand}
|
||||
deleteState={deleteShorthandState}
|
||||
saveState={saveShorthandState}
|
||||
/>
|
||||
))
|
||||
)}
|
||||
<Button
|
||||
onClick={handleAddShorthand}
|
||||
size="400"
|
||||
radii="300"
|
||||
variant="Primary"
|
||||
disabled={containsBlankShorthand}
|
||||
/* add aria label and title pls */
|
||||
>
|
||||
<Text size="B300">Add new shorthand</Text>
|
||||
</Button>
|
||||
</SettingTile>
|
||||
</SequenceCard>
|
||||
</>
|
||||
);
|
||||
return prefixes.concat(suffixes ?? [], circumfixes ?? []);
|
||||
}
|
||||
|
||||
function shorthandRowsToTriggers(rows: ShorthandRow[]): ProfileTrigger {
|
||||
const prefix: string[] = [];
|
||||
const suffix: string[] = [];
|
||||
const circumfix: { prefix: string; suffix: string }[] = [];
|
||||
|
||||
rows.forEach((row) => {
|
||||
if (row.prefix && row.suffix) {
|
||||
circumfix.push({ prefix: row.prefix, suffix: row.suffix });
|
||||
} else if (row.prefix) {
|
||||
prefix.push(row.prefix);
|
||||
} else if (row.suffix) {
|
||||
suffix.push(row.suffix);
|
||||
}
|
||||
});
|
||||
|
||||
return {
|
||||
prefix,
|
||||
...(suffix.length > 0
|
||||
? { [MATRIX_SABLE_UNSTABLE_MSC4461_TRIGGER_SUFFIX_PROPERTY_NAME]: suffix }
|
||||
: {}),
|
||||
...(circumfix.length > 0
|
||||
? { [MATRIX_SABLE_UNSTABLE_MSC4461_TRIGGER_CIRCUMFIX_PROPERTY_NAME]: circumfix }
|
||||
: {}),
|
||||
};
|
||||
}
|
||||
/**
|
||||
* the props we use for the per-message profile editor, which is used to edit a per-message profile. This is used in the settings page when the user wants to edit a profile.
|
||||
*/
|
||||
type PerMessageProfileEditorProps = {
|
||||
export type PerMessageProfileEditorProps = {
|
||||
mx: MatrixClient;
|
||||
profileId: string;
|
||||
avatarMxcUrl?: string;
|
||||
@@ -322,7 +188,7 @@ type PerMessageProfileEditorProps = {
|
||||
pronouns?: PronounSet[];
|
||||
nameColorLightTheme?: string;
|
||||
nameColorDarkTheme?: string;
|
||||
shorthands?: Shorthand[];
|
||||
shorthands?: ProfileTrigger;
|
||||
onDelete?: (profileId: string) => void;
|
||||
};
|
||||
|
||||
@@ -334,6 +200,7 @@ export function PerMessageProfileEditor({
|
||||
pronouns = Array<PronounSet>(),
|
||||
nameColorLightTheme,
|
||||
nameColorDarkTheme,
|
||||
shorthands,
|
||||
onDelete,
|
||||
}: Readonly<PerMessageProfileEditorProps>) {
|
||||
const useAuthentication = useMediaAuthentication();
|
||||
@@ -364,6 +231,44 @@ export function PerMessageProfileEditor({
|
||||
const [currentNameColorDark, setCurrentNameColorDark] = useState(nameColorDarkTheme ?? null);
|
||||
const [newNameColorDark, setNewNameColorDark] = useState(nameColorDarkTheme ?? null);
|
||||
|
||||
// shorthands
|
||||
const shorthandProp = shorthands ? triggersToShorthandRows(shorthands) : undefined;
|
||||
const [currentShorthands, setCurrentShorthands] = useState<ShorthandRow[] | undefined>(
|
||||
shorthandProp
|
||||
);
|
||||
const [newShorthands, setNewShorthands] = useState<ShorthandRow[] | undefined>(shorthandProp);
|
||||
|
||||
const containsBlankShorthand = useMemo(
|
||||
() =>
|
||||
newShorthands && newShorthands.some((shorthand) => !shorthand.prefix && !shorthand.suffix),
|
||||
[newShorthands]
|
||||
);
|
||||
|
||||
const handleAddShorthand = () => {
|
||||
if (newShorthands !== undefined) {
|
||||
setNewShorthands([...newShorthands, { id: nanoid() }]);
|
||||
}
|
||||
};
|
||||
|
||||
const handleDeleteShorthand = (id: string) => {
|
||||
if (newShorthands === undefined) return;
|
||||
setNewShorthands((s) => s?.filter((shorthand) => shorthand.id !== id));
|
||||
};
|
||||
|
||||
const handleSaveShorthand = (oldId: string, shorthand: Shorthand) => {
|
||||
setNewShorthands((rows = []) => {
|
||||
const index = rows.findIndex((row) => row.id === oldId);
|
||||
if (index === -1) return rows;
|
||||
const oldShorthand = rows[index];
|
||||
if (oldShorthand === undefined) return rows;
|
||||
|
||||
return rows.with(index, {
|
||||
...shorthand,
|
||||
id: oldShorthand.id,
|
||||
});
|
||||
});
|
||||
};
|
||||
|
||||
const [newDisplayName, setNewDisplayName] = useState(currentDisplayName);
|
||||
const [imageFile, setImageFile] = useState<File | undefined>();
|
||||
const [imageHasChanges, setImageHasChanges] = useState(false);
|
||||
@@ -409,6 +314,7 @@ export function PerMessageProfileEditor({
|
||||
newPronounsString !== currentPronounsString ||
|
||||
newNameColorLight !== currentNameColorLight ||
|
||||
newNameColorDark !== currentNameColorDark ||
|
||||
newShorthands !== currentShorthands ||
|
||||
hasIdChange ||
|
||||
imageHasChanges,
|
||||
[
|
||||
@@ -420,6 +326,8 @@ export function PerMessageProfileEditor({
|
||||
currentNameColorLight,
|
||||
newNameColorDark,
|
||||
currentNameColorDark,
|
||||
newShorthands,
|
||||
currentShorthands,
|
||||
hasIdChange,
|
||||
imageHasChanges,
|
||||
]
|
||||
@@ -447,10 +355,11 @@ export function PerMessageProfileEditor({
|
||||
useCallback(async () => {
|
||||
await addOrUpdatePerMessageProfile(mx, {
|
||||
id: profileId,
|
||||
name: newDisplayName,
|
||||
avatarUrl: avatarMxc,
|
||||
pronouns: newPronouns,
|
||||
colors: {
|
||||
displayname: newDisplayName,
|
||||
avatar_url: avatarMxc,
|
||||
[MATRIX_UNSTABLE_PROFILE_PRONOUNS_PROPERTY_NAME]: newPronouns,
|
||||
trigger: shorthandRowsToTriggers(newShorthands ?? []),
|
||||
[MATRIX_UNSTABLE_COLORS]: {
|
||||
on_light: newNameColorLight ?? undefined,
|
||||
on_dark: newNameColorDark ?? undefined,
|
||||
},
|
||||
@@ -460,6 +369,7 @@ export function PerMessageProfileEditor({
|
||||
setCurrentPronouns(newPronouns);
|
||||
setCurrentNameColorLight(newNameColorLight);
|
||||
setCurrentNameColorDark(newNameColorDark);
|
||||
setCurrentShorthands(newShorthands);
|
||||
setImageHasChanges(false);
|
||||
setChangingDisplayName(false);
|
||||
setDisableSetDisplayname(false);
|
||||
@@ -476,6 +386,7 @@ export function PerMessageProfileEditor({
|
||||
newPronouns,
|
||||
newNameColorLight,
|
||||
newNameColorDark,
|
||||
newShorthands,
|
||||
hasIdChange,
|
||||
newId,
|
||||
])
|
||||
@@ -694,8 +605,22 @@ export function PerMessageProfileEditor({
|
||||
description="This persona's name color for a dark theme user."
|
||||
focusId={`nameColorDarkTheme-${profileId}`}
|
||||
current={currentNameColorDark ?? undefined}
|
||||
newNameColor={newNameColorDark ?? undefined}
|
||||
onChange={setNewNameColorDark}
|
||||
/>
|
||||
{!newNameColorLight && newNameColorDark && (
|
||||
<Box direction="Column" alignItems="End">
|
||||
<Button
|
||||
size="300"
|
||||
fill="Soft"
|
||||
onClick={() => {
|
||||
setNewNameColorLight(accessibleColor(ThemeKind.Light, newNameColorDark));
|
||||
}}
|
||||
>
|
||||
<Text size="T200">Create new color from dark theme</Text>
|
||||
</Button>
|
||||
</Box>
|
||||
)}
|
||||
</SequenceCard>
|
||||
<SequenceCard
|
||||
className={SequenceCardStyle}
|
||||
@@ -708,8 +633,22 @@ export function PerMessageProfileEditor({
|
||||
description="This persona's name color for a light theme user."
|
||||
focusId={`nameColorLightTheme-${profileId}`}
|
||||
current={currentNameColorLight ?? undefined}
|
||||
newNameColor={newNameColorLight ?? undefined}
|
||||
onChange={setNewNameColorLight}
|
||||
/>
|
||||
{!newNameColorDark && newNameColorLight && (
|
||||
<Box direction="Column" alignItems="End">
|
||||
<Button
|
||||
size="300"
|
||||
fill="Soft"
|
||||
onClick={() => {
|
||||
setNewNameColorDark(accessibleColor(ThemeKind.Dark, newNameColorLight));
|
||||
}}
|
||||
>
|
||||
<Text size="T200">Create new color from light theme</Text>
|
||||
</Button>
|
||||
</Box>
|
||||
)}
|
||||
</SequenceCard>
|
||||
<Box
|
||||
direction="Row"
|
||||
@@ -753,7 +692,43 @@ export function PerMessageProfileEditor({
|
||||
</Box>
|
||||
|
||||
<Text size="L400">Shorthands</Text>
|
||||
<ShorthandEditor mx={mx} profileId={profileId} />
|
||||
<SequenceCard
|
||||
className={SequenceCardStyle}
|
||||
variant="SurfaceVariant"
|
||||
direction="Column"
|
||||
gap="400"
|
||||
>
|
||||
<SettingTile
|
||||
title="Shorthands"
|
||||
description="Use this persona for a single message using a prefix or suffix."
|
||||
focusId={`shorthandsInput-${profileId}`}
|
||||
>
|
||||
{newShorthands === undefined ? (
|
||||
<Spinner size="400" />
|
||||
) : (
|
||||
newShorthands.map((shorthand: ShorthandRow) => (
|
||||
<ShorthandListItem
|
||||
key={shorthand.id}
|
||||
id={shorthand.id}
|
||||
prefix={shorthand.prefix}
|
||||
suffix={shorthand.suffix}
|
||||
onDelete={handleDeleteShorthand}
|
||||
onChange={handleSaveShorthand}
|
||||
/>
|
||||
))
|
||||
)}
|
||||
<Button
|
||||
onClick={handleAddShorthand}
|
||||
size="400"
|
||||
radii="300"
|
||||
variant="Primary"
|
||||
disabled={containsBlankShorthand}
|
||||
/* add aria label and title pls */
|
||||
>
|
||||
<Text size="B300">Add new shorthand</Text>
|
||||
</Button>
|
||||
</SettingTile>
|
||||
</SequenceCard>
|
||||
</Box>
|
||||
);
|
||||
}
|
||||
@@ -1,32 +1,13 @@
|
||||
import { Box, IconButton, Text, Scroll, Chip } from 'folds';
|
||||
import { ArrowLeft, composerIcon, sizedIcon, X } from '$components/icons/phosphor';
|
||||
import { Page, PageHeader, PageContent } from '$components/page';
|
||||
import type { MatrixClient } from 'matrix-js-sdk';
|
||||
import type { PronounSet } from '$utils/pronouns';
|
||||
import type { PerMessageProfileEditorProps } from './PerMessageProfileEditor';
|
||||
import { PerMessageProfileEditor } from './PerMessageProfileEditor';
|
||||
|
||||
type PerMessageProfileEditorViewProps = {
|
||||
mx: MatrixClient;
|
||||
profileId: string;
|
||||
avatarMxcUrl?: string;
|
||||
displayName?: string;
|
||||
pronouns?: PronounSet[];
|
||||
nameColorLightTheme?: string;
|
||||
nameColorDarkTheme?: string;
|
||||
onChange?: (profile: { id: string; name: string; avatarUrl?: string }) => void;
|
||||
onDelete?: (profileId: string) => void;
|
||||
requestClose: () => void;
|
||||
};
|
||||
export function PerMessageProfileEditorView({
|
||||
mx,
|
||||
profileId,
|
||||
avatarMxcUrl,
|
||||
displayName,
|
||||
pronouns = Array<PronounSet>(),
|
||||
nameColorLightTheme,
|
||||
nameColorDarkTheme,
|
||||
requestClose,
|
||||
}: Readonly<PerMessageProfileEditorViewProps>) {
|
||||
...editorProps
|
||||
}: Readonly<PerMessageProfileEditorProps & { requestClose: () => void }>) {
|
||||
return (
|
||||
<Page>
|
||||
<PageHeader outlined={false} balance>
|
||||
@@ -51,16 +32,7 @@ export function PerMessageProfileEditorView({
|
||||
<Box grow="Yes">
|
||||
<Scroll hideTrack visibility="Hover">
|
||||
<PageContent>
|
||||
<PerMessageProfileEditor
|
||||
mx={mx}
|
||||
profileId={profileId}
|
||||
avatarMxcUrl={avatarMxcUrl}
|
||||
displayName={displayName}
|
||||
pronouns={pronouns}
|
||||
nameColorLightTheme={nameColorLightTheme}
|
||||
nameColorDarkTheme={nameColorDarkTheme}
|
||||
onDelete={requestClose}
|
||||
/>
|
||||
<PerMessageProfileEditor {...editorProps} onDelete={requestClose} />
|
||||
</PageContent>
|
||||
</Scroll>
|
||||
</Box>
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
import { useMatrixClient } from '$hooks/useMatrixClient';
|
||||
import type { PerMessageProfile } from '$hooks/usePerMessageProfile';
|
||||
import type { PerMessageProfileMsc4461 } from '$hooks/usePerMessageProfile';
|
||||
import {
|
||||
addOrUpdatePerMessageProfile,
|
||||
getAllPerMessageProfiles,
|
||||
@@ -12,10 +12,14 @@ import { SequenceCard, SequenceCardStyle } from '$components/sequence-card';
|
||||
import { PerMessageProfileListItem } from './PerMessageProfileListItem';
|
||||
import { SettingTile } from '$components/setting-tile';
|
||||
import { AsyncStatus, useAsyncCallback } from '$hooks/useAsyncCallback';
|
||||
import {
|
||||
MATRIX_UNSTABLE_COLORS,
|
||||
MATRIX_UNSTABLE_PROFILE_PRONOUNS_PROPERTY_NAME,
|
||||
} from '$unstable/prefixes';
|
||||
|
||||
type PerMessageProfileOverviewProps = {
|
||||
onCreateProfile: (profile: PerMessageProfile) => void;
|
||||
onEditProfile: (profile: PerMessageProfile) => void;
|
||||
onCreateProfile: (profile: PerMessageProfileMsc4461) => void;
|
||||
onEditProfile: (profile: PerMessageProfileMsc4461) => void;
|
||||
};
|
||||
/**
|
||||
* Renders a list of per-message profiles along with an editor.
|
||||
@@ -26,7 +30,7 @@ export function PerMessageProfileOverview({
|
||||
onEditProfile,
|
||||
}: PerMessageProfileOverviewProps) {
|
||||
const mx = useMatrixClient();
|
||||
const [profiles, setProfiles] = useState<PerMessageProfile[]>([]);
|
||||
const [profiles, setProfiles] = useState<PerMessageProfileMsc4461[]>([]);
|
||||
|
||||
useEffect(() => {
|
||||
const fetchProfiles = async () => {
|
||||
@@ -43,9 +47,10 @@ export function PerMessageProfileOverview({
|
||||
|
||||
const [addState, handleAdd] = useAsyncCallback(
|
||||
useCallback(async () => {
|
||||
const newProfile: PerMessageProfile = {
|
||||
const newProfile: PerMessageProfileMsc4461 = {
|
||||
id: generateShortId(5),
|
||||
name: 'New Profile',
|
||||
displayname: 'New Profile',
|
||||
trigger: { prefix: [] },
|
||||
};
|
||||
await addOrUpdatePerMessageProfile(mx, newProfile);
|
||||
onCreateProfile(newProfile);
|
||||
@@ -92,12 +97,12 @@ export function PerMessageProfileOverview({
|
||||
>
|
||||
<PerMessageProfileListItem
|
||||
mx={mx}
|
||||
avatarMxcUrl={profile.avatar_url}
|
||||
displayName={profile.displayname}
|
||||
pronouns={profile[MATRIX_UNSTABLE_PROFILE_PRONOUNS_PROPERTY_NAME]}
|
||||
profileId={profile.id}
|
||||
avatarMxcUrl={profile.avatarUrl}
|
||||
displayName={profile.name}
|
||||
pronouns={profile.pronouns}
|
||||
nameColorLight={profile.colors?.on_light}
|
||||
nameColorDark={profile.colors?.on_dark}
|
||||
nameColorLight={profile[MATRIX_UNSTABLE_COLORS]?.on_light}
|
||||
nameColorDark={profile[MATRIX_UNSTABLE_COLORS]?.on_dark}
|
||||
onOpenEditor={handleEdit}
|
||||
/>
|
||||
</SequenceCard>
|
||||
|
||||
@@ -3,7 +3,7 @@ import { Box, Scroll } from 'folds';
|
||||
import { PerMessageProfileOverview } from './PerMessageProfileOverview';
|
||||
import { PKCompatSettings } from './PKCompat';
|
||||
import { PickerPageSettings } from './PickerPage';
|
||||
import type { PerMessageProfile } from '$hooks/usePerMessageProfile';
|
||||
import type { PerMessageProfileMsc4461 } from '$hooks/usePerMessageProfile';
|
||||
import { useState } from 'react';
|
||||
import { useMatrixClient } from '$hooks/useMatrixClient';
|
||||
import { PerMessageProfileEditorView } from './PerMessageProfileEditorView';
|
||||
@@ -15,7 +15,7 @@ type PerMessageProfilePageProps = {
|
||||
|
||||
export function PerMessageProfilePage({ requestBack, requestClose }: PerMessageProfilePageProps) {
|
||||
const mx = useMatrixClient();
|
||||
const [editingProfile, setEditingProfile] = useState<PerMessageProfile>();
|
||||
const [editingProfile, setEditingProfile] = useState<PerMessageProfileMsc4461>();
|
||||
|
||||
const handleEditorClose = () => {
|
||||
setEditingProfile(undefined);
|
||||
@@ -26,11 +26,12 @@ export function PerMessageProfilePage({ requestBack, requestClose }: PerMessageP
|
||||
<PerMessageProfileEditorView
|
||||
mx={mx}
|
||||
profileId={editingProfile.id}
|
||||
avatarMxcUrl={editingProfile.avatarUrl}
|
||||
displayName={editingProfile.name}
|
||||
pronouns={editingProfile.pronouns}
|
||||
nameColorLightTheme={editingProfile.colors?.on_light}
|
||||
nameColorDarkTheme={editingProfile.colors?.on_dark}
|
||||
avatarMxcUrl={editingProfile.avatar_url}
|
||||
displayName={editingProfile.displayname}
|
||||
pronouns={editingProfile['io.fsky.nyx.pronouns']}
|
||||
nameColorLightTheme={editingProfile['eu.she-a.color']?.on_light}
|
||||
nameColorDarkTheme={editingProfile['eu.she-a.color']?.on_dark}
|
||||
shorthands={editingProfile.trigger}
|
||||
requestClose={handleEditorClose}
|
||||
/>
|
||||
);
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
import { useMemo, useState } from 'react';
|
||||
import type { ComponentType, ReactNode } from 'react';
|
||||
import { DesktopIcon, type IconProps } from '@phosphor-icons/react';
|
||||
import { DesktopIcon, PersonSimpleCircleIcon, type IconProps } from '@phosphor-icons/react';
|
||||
import { Avatar, Box, Button, config, Text } from 'folds';
|
||||
import { ScreenSize, useScreenSizeContext } from '$hooks/useScreenSize';
|
||||
import { useUserProfile } from '$hooks/useUserProfile';
|
||||
@@ -46,10 +46,12 @@ import { SettingsLinkProvider } from './SettingsLinkContext';
|
||||
import { useSettingsLinkBaseUrl } from './useSettingsLinkBaseUrl';
|
||||
import { Desktop } from './desktop';
|
||||
import { isDesktopTauri } from '$utils/platform';
|
||||
import { Accessibility } from './accessibility/Accessibility';
|
||||
|
||||
enum SettingsPages {
|
||||
GeneralPage,
|
||||
AccountPage,
|
||||
AccessibilityPage,
|
||||
PerMessageProfilesPage,
|
||||
NotificationPage,
|
||||
DevicesPage,
|
||||
@@ -79,6 +81,7 @@ const settingsMenuIcons: Record<
|
||||
account: { icon: User },
|
||||
persona: { icon: UsersThree },
|
||||
appearance: { icon: Palette },
|
||||
accessibility: { icon: PersonSimpleCircleIcon },
|
||||
notifications: { icon: Bell },
|
||||
devices: { icon: DevicesIcon },
|
||||
desktop: { icon: DesktopIcon },
|
||||
@@ -92,6 +95,7 @@ const settingsMenuIcons: Record<
|
||||
const settingsPageToSectionId: Record<SettingsPages, SettingsSectionId> = {
|
||||
[SettingsPages.GeneralPage]: 'general',
|
||||
[SettingsPages.AccountPage]: 'account',
|
||||
[SettingsPages.AccessibilityPage]: 'accessibility',
|
||||
[SettingsPages.PerMessageProfilesPage]: 'persona',
|
||||
[SettingsPages.NotificationPage]: 'notifications',
|
||||
[SettingsPages.DevicesPage]: 'devices',
|
||||
@@ -109,6 +113,7 @@ const settingsSectionIdToPage: Record<SettingsSectionId, SettingsPages> = {
|
||||
account: SettingsPages.AccountPage,
|
||||
persona: SettingsPages.PerMessageProfilesPage,
|
||||
appearance: SettingsPages.CosmeticsPage,
|
||||
accessibility: SettingsPages.AccessibilityPage,
|
||||
notifications: SettingsPages.NotificationPage,
|
||||
devices: SettingsPages.DevicesPage,
|
||||
desktop: SettingsPages.DesktopPage,
|
||||
@@ -124,6 +129,7 @@ const settingsSectionComponents = {
|
||||
account: Account,
|
||||
persona: PerMessageProfilePage,
|
||||
appearance: Cosmetics,
|
||||
accessibility: Accessibility,
|
||||
notifications: Notifications,
|
||||
devices: Devices,
|
||||
desktop: Desktop,
|
||||
|
||||