Merge branch '7w1:dev' into fix/timezone-quotes
This commit is contained in:
173 files changed
+6298
-2879
No files matched your search
@@ -0,0 +1,5 @@
|
||||
---
|
||||
sable: minor
|
||||
---
|
||||
|
||||
Merge Voice Call updates from upstream.
|
||||
@@ -0,0 +1,5 @@
|
||||
---
|
||||
sable: minor
|
||||
---
|
||||
|
||||
Allow for replying to state events.
|
||||
@@ -0,0 +1,5 @@
|
||||
---
|
||||
sable: minor
|
||||
---
|
||||
|
||||
Add message forwarding with metadata
|
||||
@@ -1,5 +0,0 @@
|
||||
---
|
||||
sable: patch
|
||||
---
|
||||
|
||||
Add option to filter user pronouns based on the pronouns language
|
||||
@@ -0,0 +1,5 @@
|
||||
---
|
||||
sable: minor
|
||||
---
|
||||
|
||||
Add setting to enable picture-in-picture in element-call
|
||||
+5
@@ -0,0 +1,5 @@
|
||||
---
|
||||
sable: minor
|
||||
---
|
||||
|
||||
Add support for audio and video in URL previews if homeserver provides it.
|
||||
@@ -1,5 +0,0 @@
|
||||
---
|
||||
sable: patch
|
||||
---
|
||||
|
||||
Rename gcolor, gfont, and gpronoun commands to scolor, sfont, and spronoun respectively.
|
||||
@@ -0,0 +1,5 @@
|
||||
---
|
||||
sable: patch
|
||||
---
|
||||
|
||||
change indexdb warning phrasing to include low disk space as possible reason
|
||||
@@ -0,0 +1,5 @@
|
||||
---
|
||||
sable: patch
|
||||
---
|
||||
|
||||
Fix Element Call video/audio calls in DM and non-voice rooms: after joining through the lobby, the in-call grid now displays correctly instead of showing only the control bar.
|
||||
@@ -0,0 +1,5 @@
|
||||
---
|
||||
sable: minor
|
||||
---
|
||||
|
||||
Added a new setting "Emoji Selector Character Threshold" to set the number of characters to type before the suggestions pop up.
|
||||
@@ -0,0 +1,5 @@
|
||||
---
|
||||
sable: patch
|
||||
---
|
||||
|
||||
Disable autocorrect and spellcheck on the login page.
|
||||
@@ -1,5 +0,0 @@
|
||||
---
|
||||
sable: patch
|
||||
---
|
||||
|
||||
Hide delete modal after successfully deleting a message.
|
||||
@@ -0,0 +1,5 @@
|
||||
---
|
||||
sable: patch
|
||||
---
|
||||
|
||||
Improved the UI of file descriptions
|
||||
@@ -0,0 +1,5 @@
|
||||
---
|
||||
sable: minor
|
||||
---
|
||||
|
||||
Add keyboard navigation shortcuts for unread rooms (Alt+N, Alt+Shift+Up/Down), ARIA form label associations for screen reader accessibility, and a keyboard shortcuts settings page.
|
||||
@@ -0,0 +1,5 @@
|
||||
---
|
||||
sable: patch
|
||||
---
|
||||
|
||||
Timeline message avatars now use the room-specific avatar and display name instead of the user's global profile, when set via `/myroomavatar` or `/myroomnick`.
|
||||
@@ -0,0 +1,5 @@
|
||||
---
|
||||
sable: patch
|
||||
---
|
||||
|
||||
In-app notification banners now appear for DMs by default; desktop banner setting defaults to off; fixed space room navigation from banner tap.
|
||||
@@ -1,5 +0,0 @@
|
||||
---
|
||||
sable: patch
|
||||
---
|
||||
|
||||
Adds a new message pill and background app highlighted unread count.
|
||||
@@ -1,5 +0,0 @@
|
||||
---
|
||||
sable: patch
|
||||
---
|
||||
|
||||
You can now remove your own reactions even if you don't have the permission to add new ones, as long as you are able to delete your own events (messages).
|
||||
@@ -1,5 +0,0 @@
|
||||
---
|
||||
sable: minor
|
||||
---
|
||||
|
||||
Add a method of quickly adding a new text reaction to the latest message, just like emote quick react, using the prefix `+#`
|
||||
@@ -0,0 +1,5 @@
|
||||
---
|
||||
sable: patch
|
||||
---
|
||||
|
||||
Executing /myroomnick or /myroomavatar without a new nickname/avatar now removes the nickname/avatar.
|
||||
@@ -1,5 +0,0 @@
|
||||
---
|
||||
sable: patch
|
||||
---
|
||||
|
||||
Added two toggles in Settings > Appearance > Identity for disabling rendering room/space fonts and colors.
|
||||
@@ -0,0 +1,5 @@
|
||||
---
|
||||
sable: patch
|
||||
---
|
||||
|
||||
Split typing and read status settings, allowing toggling off one and not the other.
|
||||
@@ -1,5 +0,0 @@
|
||||
---
|
||||
sable: patch
|
||||
---
|
||||
|
||||
Added an additional toggle, Show Unread Ping Counts, to override the Show Unread Counts allowing for only pings to have counts.
|
||||
@@ -0,0 +1,5 @@
|
||||
---
|
||||
sable: minor
|
||||
---
|
||||
|
||||
Added setting to always underline links.
|
||||
@@ -0,0 +1,5 @@
|
||||
---
|
||||
sable: minor
|
||||
---
|
||||
|
||||
Added settings for disabling autoplay of gifs (& banners), stickers, and emojis.
|
||||
@@ -0,0 +1,5 @@
|
||||
---
|
||||
sable: minor
|
||||
---
|
||||
|
||||
Added reduced motion setting. Let us know if any elements were missed!
|
||||
@@ -0,0 +1,5 @@
|
||||
---
|
||||
sable: minor
|
||||
---
|
||||
|
||||
Replaced the monochrome mode with a saturation slider for more control.
|
||||
@@ -0,0 +1,5 @@
|
||||
---
|
||||
sable: minor
|
||||
---
|
||||
|
||||
Added settings to Account that let you set if you are a cat or have cats, or not display other peoples cat status.
|
||||
@@ -1,2 +1,3 @@
|
||||
node_modules/
|
||||
dist/
|
||||
.git/
|
||||
@@ -0,0 +1 @@
|
||||
* text=auto eol=lf
|
||||
@@ -0,0 +1 @@
|
||||
* @7w1
|
||||
@@ -62,16 +62,30 @@ jobs:
|
||||
type=semver,pattern={{major}}.{{minor}},value=${{ steps.release_tag.outputs.value }},enable=${{ steps.release_tag.outputs.is_release == 'true' }}
|
||||
type=semver,pattern={{major}},value=${{ steps.release_tag.outputs.value }},enable=${{ steps.release_tag.outputs.is_release == 'true' && !startsWith(steps.release_tag.outputs.value, 'v0.') }}
|
||||
|
||||
- name: Compute short SHA
|
||||
id: vars
|
||||
run: echo "short_sha=$(git rev-parse --short HEAD)" >> $GITHUB_OUTPUT
|
||||
|
||||
- name: Set up Node.js
|
||||
uses: actions/setup-node@53b83947a5a98c8d113130e565377fae1a50d02f # v6.3.0
|
||||
with:
|
||||
node-version: '24'
|
||||
cache: 'npm'
|
||||
|
||||
- name: Build site
|
||||
env:
|
||||
VITE_BUILD_HASH: ${{ steps.vars.outputs.short_sha }}
|
||||
VITE_IS_RELEASE_TAG: ${{ steps.release_tag.outputs.is_release }}
|
||||
run: |
|
||||
npm ci --ignore-scripts
|
||||
NODE_OPTIONS=--max_old_space_size=4096 npm run build
|
||||
|
||||
- name: Set up QEMU
|
||||
uses: docker/setup-qemu-action@c7c53464625b32c7a7e944ae62b3e17d2b600130 # v3.7.0
|
||||
|
||||
- name: Set up Docker Buildx
|
||||
uses: docker/setup-buildx-action@8d2750c68a42422c14e847fe6c8ac0403b4cbd6f # v3.12.0
|
||||
|
||||
- name: Compute short SHA
|
||||
id: vars
|
||||
run: echo "short_sha=$(git rev-parse --short HEAD)" >> $GITHUB_OUTPUT
|
||||
|
||||
- name: Build and push Docker image
|
||||
id: push
|
||||
uses: docker/build-push-action@10e90e3645eae34f1e60eeb005ba3a3d33f178e8 # v6.19.2
|
||||
@@ -83,8 +97,8 @@ jobs:
|
||||
labels: ${{ steps.meta.outputs.labels }}
|
||||
cache-from: type=gha
|
||||
cache-to: type=gha,mode=max
|
||||
build-args: |
|
||||
VITE_BUILD_HASH=${{ steps.vars.outputs.short_sha }}
|
||||
build-contexts: |
|
||||
site-dist=./dist
|
||||
|
||||
- name: Generate artifact attestation
|
||||
uses: actions/attest-build-provenance@a2bbfa25375fe432b6a289bc6b6cd05ecd0c4c32 # v4.1.0
|
||||
|
||||
+3
-1
@@ -3,4 +3,6 @@ node_modules
|
||||
package.json
|
||||
package-lock.json
|
||||
LICENSE
|
||||
README.md
|
||||
README.md
|
||||
CHANGELOG.md
|
||||
./changeset
|
||||
@@ -1,5 +1,35 @@
|
||||
# Sable Client Changelog
|
||||
|
||||
## 1.4.0 (2026-03-06)
|
||||
|
||||
### Features
|
||||
|
||||
* Add option to filter user pronouns based on the pronouns language
|
||||
* Added a "Badge Counts for DMs Only" setting: when enabled, unread count numbers only appear on Direct Message room badges; non-DM rooms and spaces show a plain dot instead of a number, even when Show Unread Counts is on.
|
||||
* Added the ability to add descriptions to uploaded files
|
||||
* Fixed in-app notification banners in encrypted rooms showing "Encrypted Message" instead of the actual content. Banners now also render rich text (mentions, inline images) using the same pipeline as the timeline renderer.
|
||||
* You can now remove your own reactions even if you don't have the permission to add new ones, as long as you are able to delete your own events (messages).
|
||||
* Add a method of quickly adding a new text reaction to the latest message, just like emote quick react, using the prefix `+#`
|
||||
* Added two toggles in Settings > Appearance > Identity for disabling rendering room/space fonts and colors.
|
||||
* Added an additional toggle, Show Unread Ping Counts, to override the Show Unread Counts allowing for only pings to have counts.
|
||||
|
||||
### Fixes
|
||||
|
||||
* Rename gcolor, gfont, and gpronoun commands to scolor, sfont, and spronoun respectively.
|
||||
* Improved emoji board performance by deferring image pack cache reads so the board opens instantly rather than blocking on the initial render.
|
||||
* Fix dm room nicknames applying to non-dm private rooms.
|
||||
* Hide delete modal after successfully deleting a message.
|
||||
* Fixed media authentication handling: removed unnecessary redirect following, added error fallback UI for failed media loads, and ensured authentication headers are applied consistently when rendering inline media in HTML message bodies.
|
||||
* Failed message retry and delete actions now use Chip buttons for visual consistency with the rest of the interface.
|
||||
* Adds a new message pill and background app highlighted unread count.
|
||||
* Mobile: changed scheduled send chevron to tap + hold
|
||||
* Reply quotes now automatically retry decryption for E2EE messages, display a distinct placeholder for replies from blocked users, and fix edge cases where reply event loading could silently fail.
|
||||
* Service worker push notifications now correctly deep-link to the right account and room on cold PWA launch. Notifications are automatically suppressed when the app window is already visible. The In-App (pill banner) and System (OS) notification settings are now independent: desktop shows both controls, mobile shows Push and In-App only. Tapping an in-app notification pill on mobile now opens the room timeline directly instead of routing through the space navigation panel.
|
||||
* Fixed several room timeline issues with sliding sync: corrected event rendering order, more accurate scroll-to-bottom detection, phantom unread count clearing when the timeline is already at the bottom, and fixed pagination spinner state.
|
||||
* In-app notification banners now appear for DMs by default, even without a mention or keyword match.
|
||||
* Notification banner on desktop now defaults to off, consistent with push notification defaults.
|
||||
* Fixed space room navigation when tapping an in-app notification banner for a room inside a space.
|
||||
|
||||
## 1.3.3 - 3/4/2026
|
||||
|
||||
- Fix unread counts and dot badges for muted rooms ([#118](https://github.com/7w1/sable/pull/118)) - [Evie Gauthier](https://github.com/Just-Insane)
|
||||
|
||||
@@ -0,0 +1,18 @@
|
||||
{
|
||||
servers {
|
||||
protocols h1 h2c
|
||||
}
|
||||
}
|
||||
|
||||
:80 {
|
||||
root * /app
|
||||
|
||||
# Enable on-the-fly compression for things not pre-compressed
|
||||
encode zstd gzip
|
||||
|
||||
file_server {
|
||||
precompressed br
|
||||
}
|
||||
|
||||
try_files {path} /index.html
|
||||
}
|
||||
+8
-6
@@ -4,7 +4,9 @@ FROM --platform=$BUILDPLATFORM node:24.13.1-alpine AS builder
|
||||
WORKDIR /src
|
||||
|
||||
ARG VITE_BUILD_HASH
|
||||
ARG VITE_IS_RELEASE_TAG=false
|
||||
ENV VITE_BUILD_HASH=$VITE_BUILD_HASH
|
||||
ENV VITE_IS_RELEASE_TAG=$VITE_IS_RELEASE_TAG
|
||||
|
||||
COPY .npmrc package.json package-lock.json /src/
|
||||
RUN npm ci --ignore-scripts
|
||||
@@ -12,12 +14,12 @@ COPY . /src/
|
||||
ENV NODE_OPTIONS=--max_old_space_size=4096
|
||||
RUN npm run build
|
||||
|
||||
## Dist
|
||||
FROM scratch AS site-dist
|
||||
COPY --from=builder /src/dist /
|
||||
|
||||
## App
|
||||
FROM nginx:1.29.5-alpine
|
||||
FROM caddy:2-alpine
|
||||
|
||||
COPY --from=builder /src/dist /app
|
||||
COPY --from=builder /src/docker-nginx.conf /etc/nginx/conf.d/default.conf
|
||||
|
||||
RUN rm -rf /usr/share/nginx/html \
|
||||
&& ln -s /app /usr/share/nginx/html
|
||||
COPY --from=site-dist / /app
|
||||
COPY Caddyfile /etc/caddy/Caddyfile
|
||||
@@ -1,21 +0,0 @@
|
||||
server {
|
||||
listen 80;
|
||||
listen [::]:80;
|
||||
|
||||
location / {
|
||||
root /usr/share/nginx/html;
|
||||
|
||||
rewrite ^/config.json$ /config.json break;
|
||||
rewrite ^/manifest.json$ /manifest.json break;
|
||||
|
||||
rewrite ^/sw.js$ /sw.js break;
|
||||
rewrite ^/pdf.worker.min.js$ /pdf.worker.min.js break;
|
||||
|
||||
rewrite ^/public/(.*)$ /public/$1 break;
|
||||
rewrite ^/assets/(.*)$ /assets/$1 break;
|
||||
|
||||
rewrite ^/element-call/dist/(.*)$ /element-call/dist/$1 break;
|
||||
|
||||
rewrite ^(.+)$ /index.html break;
|
||||
}
|
||||
}
|
||||
+7
-1
@@ -4,7 +4,7 @@ versioned_files = ["package.json", "package-lock.json"]
|
||||
changelog = "CHANGELOG.md"
|
||||
extra_changelog_sections = [
|
||||
{ name = "Documentation", types = ["docs"] },
|
||||
{ name = "Notes", types = ["note"] }
|
||||
{ name = "Notes", types = ["note"] },
|
||||
]
|
||||
# assets = "marker for GitHub bot" // TODO: add this later once we have assets
|
||||
|
||||
@@ -42,6 +42,12 @@ repo = "sable"
|
||||
|
||||
[bot.releases]
|
||||
enabled = true
|
||||
pull_request.title = "$version changelog"
|
||||
|
||||
[bot.checks]
|
||||
skip_labels = ["internal"]
|
||||
|
||||
[release_notes]
|
||||
change_templates = [
|
||||
"* $summary",
|
||||
]
|
||||
Generated
+39
-4
@@ -1,12 +1,12 @@
|
||||
{
|
||||
"name": "sable",
|
||||
"version": "1.3.3",
|
||||
"version": "1.4.0",
|
||||
"lockfileVersion": 2,
|
||||
"requires": true,
|
||||
"packages": {
|
||||
"": {
|
||||
"name": "sable",
|
||||
"version": "1.3.3",
|
||||
"version": "1.4.0",
|
||||
"hasInstallScript": true,
|
||||
"license": "AGPL-3.0-only",
|
||||
"dependencies": {
|
||||
@@ -98,6 +98,7 @@
|
||||
"prettier": "3.8.1",
|
||||
"typescript": "^5.9.3",
|
||||
"vite": "^7.3.1",
|
||||
"vite-plugin-compression2": "2.5.0",
|
||||
"vite-plugin-pwa": "^1.2.0",
|
||||
"vite-plugin-static-copy": "^3.2.0",
|
||||
"vite-plugin-svgr": "4.5.0",
|
||||
@@ -12778,7 +12779,7 @@
|
||||
"jwt-decode": "^4.0.0",
|
||||
"loglevel": "^1.9.2",
|
||||
"matrix-events-sdk": "0.0.1",
|
||||
"matrix-widget-api": "^1.10.0",
|
||||
"matrix-widget-api": "1.13.0",
|
||||
"oidc-client-ts": "^3.0.1",
|
||||
"p-retry": "7",
|
||||
"sdp-transform": "^2.14.1",
|
||||
@@ -14920,6 +14921,13 @@
|
||||
"url": "https://opencollective.com/webpack"
|
||||
}
|
||||
},
|
||||
"node_modules/tar-mini": {
|
||||
"version": "0.2.0",
|
||||
"resolved": "https://registry.npmjs.org/tar-mini/-/tar-mini-0.2.0.tgz",
|
||||
"integrity": "sha512-+qfUHz700DWnRutdUsxRRVZ38G1Qr27OetwaMYTdg8hcPxf46U0S1Zf76dQMWRBmusOt2ZCK5kbIaiLkoGO7WQ==",
|
||||
"dev": true,
|
||||
"license": "MIT"
|
||||
},
|
||||
"node_modules/temp-dir": {
|
||||
"version": "2.0.0",
|
||||
"resolved": "https://registry.npmjs.org/temp-dir/-/temp-dir-2.0.0.tgz",
|
||||
@@ -16032,6 +16040,17 @@
|
||||
}
|
||||
}
|
||||
},
|
||||
"node_modules/vite-plugin-compression2": {
|
||||
"version": "2.5.0",
|
||||
"resolved": "https://registry.npmjs.org/vite-plugin-compression2/-/vite-plugin-compression2-2.5.0.tgz",
|
||||
"integrity": "sha512-bHxtBibPxxSn5eZSe0IAzvYucP/hg8Bz8ppjbH7lndU5kIHT+92qTkB4z9xWYfnyV0YHuir1SjOuyO0fzU4Vgg==",
|
||||
"dev": true,
|
||||
"license": "MIT",
|
||||
"dependencies": {
|
||||
"@rollup/pluginutils": "^5.1.0",
|
||||
"tar-mini": "^0.2.0"
|
||||
}
|
||||
},
|
||||
"node_modules/vite-plugin-pwa": {
|
||||
"version": "1.2.0",
|
||||
"resolved": "https://registry.npmjs.org/vite-plugin-pwa/-/vite-plugin-pwa-1.2.0.tgz",
|
||||
@@ -25820,6 +25839,12 @@
|
||||
"integrity": "sha512-g9ljZiwki/LfxmQADO3dEY1CbpmXT5Hm2fJ+QaGKwSXUylMybePR7/67YW7jOrrvjEgL1Fmz5kzyAjWVWLlucg==",
|
||||
"dev": true
|
||||
},
|
||||
"tar-mini": {
|
||||
"version": "0.2.0",
|
||||
"resolved": "https://registry.npmjs.org/tar-mini/-/tar-mini-0.2.0.tgz",
|
||||
"integrity": "sha512-+qfUHz700DWnRutdUsxRRVZ38G1Qr27OetwaMYTdg8hcPxf46U0S1Zf76dQMWRBmusOt2ZCK5kbIaiLkoGO7WQ==",
|
||||
"dev": true
|
||||
},
|
||||
"temp-dir": {
|
||||
"version": "2.0.0",
|
||||
"resolved": "https://registry.npmjs.org/temp-dir/-/temp-dir-2.0.0.tgz",
|
||||
@@ -26369,6 +26394,16 @@
|
||||
}
|
||||
}
|
||||
},
|
||||
"vite-plugin-compression2": {
|
||||
"version": "2.5.0",
|
||||
"resolved": "https://registry.npmjs.org/vite-plugin-compression2/-/vite-plugin-compression2-2.5.0.tgz",
|
||||
"integrity": "sha512-bHxtBibPxxSn5eZSe0IAzvYucP/hg8Bz8ppjbH7lndU5kIHT+92qTkB4z9xWYfnyV0YHuir1SjOuyO0fzU4Vgg==",
|
||||
"dev": true,
|
||||
"requires": {
|
||||
"@rollup/pluginutils": "^5.1.0",
|
||||
"tar-mini": "^0.2.0"
|
||||
}
|
||||
},
|
||||
"vite-plugin-pwa": {
|
||||
"version": "1.2.0",
|
||||
"resolved": "https://registry.npmjs.org/vite-plugin-pwa/-/vite-plugin-pwa-1.2.0.tgz",
|
||||
@@ -26870,4 +26905,4 @@
|
||||
"dev": true
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
+3
-2
@@ -1,6 +1,6 @@
|
||||
{
|
||||
"name": "sable",
|
||||
"version": "1.3.3",
|
||||
"version": "1.4.0",
|
||||
"description": "Yet another matrix client fork",
|
||||
"type": "module",
|
||||
"packageManager": "[email protected]",
|
||||
@@ -114,10 +114,11 @@
|
||||
"prettier": "3.8.1",
|
||||
"typescript": "^5.9.3",
|
||||
"vite": "^7.3.1",
|
||||
"vite-plugin-compression2": "2.5.0",
|
||||
"vite-plugin-pwa": "^1.2.0",
|
||||
"vite-plugin-static-copy": "^3.2.0",
|
||||
"vite-plugin-svgr": "4.5.0",
|
||||
"vite-plugin-top-level-await": "^1.6.0",
|
||||
"wrangler": "^4.70.0"
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,63 @@
|
||||
import { ReactNode, useCallback, useRef } from 'react';
|
||||
import { useAtomValue, useSetAtom } from 'jotai';
|
||||
import {
|
||||
CallEmbedContextProvider,
|
||||
CallEmbedRefContextProvider,
|
||||
useCallHangupEvent,
|
||||
useCallJoined,
|
||||
useCallThemeSync,
|
||||
} from '../hooks/useCallEmbed';
|
||||
import { callChatAtom, callEmbedAtom } from '../state/callEmbed';
|
||||
import { CallEmbed } from '../plugins/call';
|
||||
import { useSelectedRoom } from '../hooks/router/useSelectedRoom';
|
||||
import { ScreenSize, useScreenSizeContext } from '../hooks/useScreenSize';
|
||||
|
||||
function CallUtils({ embed }: { embed: CallEmbed }) {
|
||||
const setCallEmbed = useSetAtom(callEmbedAtom);
|
||||
|
||||
useCallThemeSync(embed);
|
||||
useCallHangupEvent(
|
||||
embed,
|
||||
useCallback(() => {
|
||||
setCallEmbed(undefined);
|
||||
}, [setCallEmbed])
|
||||
);
|
||||
|
||||
return null;
|
||||
}
|
||||
|
||||
type CallEmbedProviderProps = {
|
||||
children?: ReactNode;
|
||||
};
|
||||
export function CallEmbedProvider({ children }: CallEmbedProviderProps) {
|
||||
const callEmbed = useAtomValue(callEmbedAtom);
|
||||
const callEmbedRef = useRef<HTMLDivElement>(null);
|
||||
const joined = useCallJoined(callEmbed);
|
||||
|
||||
const selectedRoom = useSelectedRoom();
|
||||
const chat = useAtomValue(callChatAtom);
|
||||
const screenSize = useScreenSizeContext();
|
||||
|
||||
const chatOnlyView = chat && screenSize !== ScreenSize.Desktop;
|
||||
|
||||
const callVisible = callEmbed && selectedRoom === callEmbed.roomId && joined && !chatOnlyView;
|
||||
|
||||
return (
|
||||
<CallEmbedContextProvider value={callEmbed}>
|
||||
{callEmbed && <CallUtils embed={callEmbed} />}
|
||||
<CallEmbedRefContextProvider value={callEmbedRef}>{children}</CallEmbedRefContextProvider>
|
||||
<div
|
||||
data-call-embed-container
|
||||
style={{
|
||||
visibility: callVisible ? undefined : 'hidden',
|
||||
position: 'fixed',
|
||||
top: 0,
|
||||
left: 0,
|
||||
width: '100%',
|
||||
height: '50%',
|
||||
}}
|
||||
ref={callEmbedRef}
|
||||
/>
|
||||
</CallEmbedContextProvider>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,76 @@
|
||||
import { useEffect, useRef, useState } from 'react';
|
||||
|
||||
export function ClientSideHoverFreeze({
|
||||
children,
|
||||
src,
|
||||
className,
|
||||
}: {
|
||||
children: React.ReactNode;
|
||||
src: string;
|
||||
className?: string;
|
||||
}) {
|
||||
const [isHovered, setIsHovered] = useState(false);
|
||||
const canvasRef = useRef<HTMLCanvasElement>(null);
|
||||
const [isCanvasReady, setIsCanvasReady] = useState(false);
|
||||
useEffect(() => {
|
||||
let isMounted = true;
|
||||
const img = new window.Image();
|
||||
img.crossOrigin = 'anonymous';
|
||||
img.src = src;
|
||||
|
||||
img.onload = () => {
|
||||
if (isMounted && canvasRef.current) {
|
||||
canvasRef.current.width = img.naturalWidth || img.width;
|
||||
canvasRef.current.height = img.naturalHeight || img.height;
|
||||
const ctx = canvasRef.current.getContext('2d');
|
||||
ctx?.drawImage(img, 0, 0);
|
||||
setIsCanvasReady(true);
|
||||
}
|
||||
};
|
||||
return () => {
|
||||
isMounted = false;
|
||||
};
|
||||
}, [src]);
|
||||
|
||||
return (
|
||||
<div
|
||||
onMouseEnter={() => setIsHovered(true)}
|
||||
onMouseLeave={() => setIsHovered(false)}
|
||||
onFocus={() => setIsHovered(true)}
|
||||
onBlur={() => setIsHovered(false)}
|
||||
className={className}
|
||||
style={{
|
||||
position: 'relative',
|
||||
display: 'inline-flex',
|
||||
cursor: 'pointer',
|
||||
verticalAlign: 'middle',
|
||||
overflow: 'hidden',
|
||||
borderRadius: 'inherit',
|
||||
}}
|
||||
>
|
||||
<div
|
||||
style={{
|
||||
opacity: isHovered || !isCanvasReady ? 1 : 0,
|
||||
display: 'flex',
|
||||
width: '100%',
|
||||
}}
|
||||
>
|
||||
{children}
|
||||
</div>
|
||||
<canvas
|
||||
ref={canvasRef}
|
||||
style={{
|
||||
position: 'absolute',
|
||||
top: 0,
|
||||
left: 0,
|
||||
width: '100%',
|
||||
height: '100%',
|
||||
objectFit: 'inherit',
|
||||
opacity: !isHovered && isCanvasReady ? 1 : 0,
|
||||
pointerEvents: 'none',
|
||||
display: 'block',
|
||||
}}
|
||||
/>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,117 @@
|
||||
/**
|
||||
* Global keyboard shortcuts for navigation and accessibility.
|
||||
*
|
||||
* Shortcuts provided:
|
||||
* Alt+N — jump to the highest-priority unread room
|
||||
* Alt+Shift+Down — cycle forward through unread rooms
|
||||
* Alt+Shift+Up — cycle backward through unread rooms
|
||||
*/
|
||||
import { useCallback, useRef } from 'react';
|
||||
import { useNavigate, useLocation, matchPath } from 'react-router-dom';
|
||||
import { useAtomValue } from 'jotai';
|
||||
import { isKeyHotkey } from 'is-hotkey';
|
||||
import { useMatrixClient } from '$hooks/useMatrixClient';
|
||||
import { roomToParentsAtom } from '$state/room/roomToParents';
|
||||
import { mDirectAtom } from '$state/mDirectList';
|
||||
import { roomToUnreadAtom } from '$state/room/roomToUnread';
|
||||
import { useKeyDown } from '$hooks/useKeyDown';
|
||||
import { getDirectRoomPath, getHomeRoomPath, getSpaceRoomPath } from '$pages/pathUtils';
|
||||
import { HOME_ROOM_PATH, DIRECT_ROOM_PATH, SPACE_ROOM_PATH } from '$pages/paths';
|
||||
import { getCanonicalAliasOrRoomId } from '$utils/matrix';
|
||||
import { announce } from '$utils/announce';
|
||||
|
||||
export function GlobalKeyboardShortcuts() {
|
||||
const navigate = useNavigate();
|
||||
const location = useLocation();
|
||||
const mx = useMatrixClient();
|
||||
const roomToParents = useAtomValue(roomToParentsAtom);
|
||||
const mDirects = useAtomValue(mDirectAtom);
|
||||
const roomToUnread = useAtomValue(roomToUnreadAtom);
|
||||
const unreadIndexRef = useRef(0);
|
||||
|
||||
// Derive the current room ID from the URL so we know which room is active.
|
||||
const roomMatch =
|
||||
matchPath(HOME_ROOM_PATH, location.pathname) ??
|
||||
matchPath(DIRECT_ROOM_PATH, location.pathname) ??
|
||||
matchPath(SPACE_ROOM_PATH, location.pathname);
|
||||
const roomIdOrAlias = roomMatch?.params.roomIdOrAlias
|
||||
? decodeURIComponent(roomMatch.params.roomIdOrAlias)
|
||||
: undefined;
|
||||
let currentRoomId: string | null = null;
|
||||
if (roomIdOrAlias) {
|
||||
if (roomIdOrAlias.startsWith('!')) {
|
||||
currentRoomId = roomIdOrAlias;
|
||||
} else {
|
||||
currentRoomId =
|
||||
mx.getRooms().find((r) => r.getCanonicalAlias() === roomIdOrAlias)?.roomId ?? null;
|
||||
}
|
||||
}
|
||||
|
||||
/** Navigate to a room by ID and announce it to screen readers. */
|
||||
const navigateToRoom = useCallback(
|
||||
(roomId: string, remaining: number) => {
|
||||
const roomIdOrAliasToNav = getCanonicalAliasOrRoomId(mx, roomId);
|
||||
const isDirect = mDirects.has(roomId);
|
||||
if (isDirect) {
|
||||
navigate(getDirectRoomPath(roomIdOrAliasToNav));
|
||||
} else {
|
||||
const parents = roomToParents.get(roomId);
|
||||
if (parents && parents.size > 0) {
|
||||
const spaceId = Array.from(parents)[0];
|
||||
const spaceIdOrAlias = getCanonicalAliasOrRoomId(mx, spaceId);
|
||||
navigate(getSpaceRoomPath(spaceIdOrAlias, roomIdOrAliasToNav));
|
||||
} else {
|
||||
navigate(getHomeRoomPath(roomIdOrAliasToNav));
|
||||
}
|
||||
}
|
||||
const roomName = mx.getRoom(roomId)?.name ?? 'Room';
|
||||
const roomType = isDirect ? 'Direct Message' : 'Group Room';
|
||||
announce(`${roomName}, ${roomType}. ${remaining} room${remaining === 1 ? '' : 's'} unread.`);
|
||||
},
|
||||
[mx, mDirects, roomToParents, navigate]
|
||||
);
|
||||
|
||||
/** Alt+N: jump to the top-priority unread room and reset the cycle index. */
|
||||
const handleNextUnreadKeyDown = useCallback(
|
||||
(evt: KeyboardEvent) => {
|
||||
if (!isKeyHotkey('alt+n', evt)) return;
|
||||
const unreadEntries = Array.from(roomToUnread.entries())
|
||||
.filter(([id, u]) => u.total > 0 && id !== currentRoomId)
|
||||
.sort((a, b) => b[1].highlight - a[1].highlight || b[1].total - a[1].total);
|
||||
if (unreadEntries.length === 0) return;
|
||||
evt.preventDefault();
|
||||
unreadIndexRef.current = 0;
|
||||
const [roomId] = unreadEntries[0];
|
||||
navigateToRoom(roomId, unreadEntries.length - 1);
|
||||
},
|
||||
[roomToUnread, currentRoomId, navigateToRoom]
|
||||
);
|
||||
|
||||
/** Alt+Shift+Down / Alt+Shift+Up: cycle through unread rooms. */
|
||||
const handleUnreadNavKeyDown = useCallback(
|
||||
(evt: KeyboardEvent) => {
|
||||
const isDown = isKeyHotkey('alt+shift+down', evt);
|
||||
const isUp = isKeyHotkey('alt+shift+up', evt);
|
||||
if (!isDown && !isUp) return;
|
||||
const unreadEntries = Array.from(roomToUnread.entries())
|
||||
.filter(([, u]) => u.total > 0)
|
||||
.sort((a, b) => b[1].highlight - a[1].highlight || b[1].total - a[1].total);
|
||||
if (unreadEntries.length === 0) return;
|
||||
evt.preventDefault();
|
||||
if (isDown) {
|
||||
unreadIndexRef.current = (unreadIndexRef.current + 1) % unreadEntries.length;
|
||||
} else {
|
||||
unreadIndexRef.current =
|
||||
(unreadIndexRef.current - 1 + unreadEntries.length) % unreadEntries.length;
|
||||
}
|
||||
const [roomId] = unreadEntries[unreadIndexRef.current];
|
||||
navigateToRoom(roomId, unreadEntries.length - 1);
|
||||
},
|
||||
[roomToUnread, navigateToRoom]
|
||||
);
|
||||
|
||||
useKeyDown(window, handleNextUnreadKeyDown);
|
||||
useKeyDown(window, handleUnreadNavKeyDown);
|
||||
|
||||
return null;
|
||||
}
|
||||
@@ -1,9 +1,11 @@
|
||||
import { memo, useMemo, useCallback } from 'react';
|
||||
import { MsgType } from '$types/matrix-sdk';
|
||||
import { testMatrixTo } from '$plugins/matrix-to';
|
||||
import { useSetting } from '$state/hooks/settings';
|
||||
import { settingsAtom, CaptionPosition } from '$state/settings';
|
||||
import { HTMLReactParserOptions } from 'html-react-parser';
|
||||
import { Opts } from 'linkifyjs';
|
||||
import { config } from 'folds';
|
||||
import { Box, config } from 'folds';
|
||||
import {
|
||||
AudioContent,
|
||||
DownloadFile,
|
||||
@@ -30,6 +32,7 @@ import { Image, MediaControl, Video } from './media';
|
||||
import { ImageViewer } from './image-viewer';
|
||||
import { PdfViewer } from './Pdf-viewer';
|
||||
import { TextViewer } from './text-viewer';
|
||||
import { ClientSideHoverFreeze } from './ClientSideHoverFreeze';
|
||||
|
||||
type RenderMessageContentProps = {
|
||||
displayName: string;
|
||||
@@ -70,6 +73,15 @@ function RenderMessageContentInternal({
|
||||
}: RenderMessageContentProps) {
|
||||
const content = useMemo(() => getContent<any>(), [getContent]);
|
||||
|
||||
const [autoplayGifs] = useSetting(settingsAtom, 'autoplayGifs');
|
||||
const [captionPosition] = useSetting(settingsAtom, 'captionPosition');
|
||||
const captionPositionMap = {
|
||||
[CaptionPosition.Above]: 'column-reverse',
|
||||
[CaptionPosition.Below]: 'column',
|
||||
[CaptionPosition.Inline]: 'row',
|
||||
[CaptionPosition.Hidden]: 'row',
|
||||
} satisfies Record<CaptionPosition, React.CSSProperties['flexDirection']>;
|
||||
|
||||
const renderBody = useCallback(
|
||||
(props: any) => (
|
||||
<RenderBody
|
||||
@@ -107,54 +119,89 @@ function RenderMessageContentInternal({
|
||||
);
|
||||
|
||||
const renderCaption = () => {
|
||||
if (captionPosition === CaptionPosition.Hidden) return null;
|
||||
if (content.filename && content.filename !== content.body) {
|
||||
if (captionPosition !== CaptionPosition.Inline)
|
||||
return (
|
||||
<MText
|
||||
style={CAPTION_STYLE}
|
||||
edited={edited}
|
||||
content={content}
|
||||
renderBody={renderBody}
|
||||
renderUrlsPreview={urlPreview ? renderUrlsPreview : undefined}
|
||||
/>
|
||||
);
|
||||
return (
|
||||
<MText
|
||||
style={CAPTION_STYLE}
|
||||
edited={edited}
|
||||
content={content}
|
||||
renderBody={renderBody}
|
||||
renderUrlsPreview={urlPreview ? renderUrlsPreview : undefined}
|
||||
/>
|
||||
<Box
|
||||
style={{
|
||||
padding: config.space.S200,
|
||||
wordBreak: 'break-word',
|
||||
maxWidth: '100%',
|
||||
display: 'flex',
|
||||
flexDirection: 'column',
|
||||
justifyContent: 'center',
|
||||
flexShrink: 1,
|
||||
}}
|
||||
>
|
||||
<MText
|
||||
edited={edited}
|
||||
content={content}
|
||||
renderBody={renderBody}
|
||||
renderUrlsPreview={urlPreview ? renderUrlsPreview : undefined}
|
||||
/>
|
||||
</Box>
|
||||
);
|
||||
}
|
||||
return null;
|
||||
};
|
||||
|
||||
const renderFile = () => (
|
||||
<>
|
||||
<MFile
|
||||
content={content}
|
||||
renderFileContent={({ body, mimeType, info, encInfo, url }) => (
|
||||
<FileContent
|
||||
body={body}
|
||||
mimeType={mimeType}
|
||||
renderAsPdfFile={() => (
|
||||
<ReadPdfFile
|
||||
<div
|
||||
style={{
|
||||
display: 'flex',
|
||||
flexDirection: captionPositionMap[captionPosition],
|
||||
}}
|
||||
>
|
||||
<div>
|
||||
<MFile
|
||||
content={content}
|
||||
renderFileContent={({ body, mimeType, info, encInfo, url }) => (
|
||||
<FileContent
|
||||
body={body}
|
||||
mimeType={mimeType}
|
||||
renderAsPdfFile={() => (
|
||||
<ReadPdfFile
|
||||
body={body}
|
||||
mimeType={mimeType}
|
||||
url={url}
|
||||
encInfo={encInfo}
|
||||
renderViewer={(p) => <PdfViewer {...p} />}
|
||||
/>
|
||||
)}
|
||||
renderAsTextFile={() => (
|
||||
<ReadTextFile
|
||||
body={body}
|
||||
mimeType={mimeType}
|
||||
url={url}
|
||||
encInfo={encInfo}
|
||||
renderViewer={(p) => <TextViewer {...p} />}
|
||||
/>
|
||||
)}
|
||||
>
|
||||
<DownloadFile
|
||||
body={body}
|
||||
mimeType={mimeType}
|
||||
url={url}
|
||||
encInfo={encInfo}
|
||||
renderViewer={(p) => <PdfViewer {...p} />}
|
||||
info={info}
|
||||
/>
|
||||
)}
|
||||
renderAsTextFile={() => (
|
||||
<ReadTextFile
|
||||
body={body}
|
||||
mimeType={mimeType}
|
||||
url={url}
|
||||
encInfo={encInfo}
|
||||
renderViewer={(p) => <TextViewer {...p} />}
|
||||
/>
|
||||
)}
|
||||
>
|
||||
<DownloadFile body={body} mimeType={mimeType} url={url} encInfo={encInfo} info={info} />
|
||||
</FileContent>
|
||||
)}
|
||||
outlined={outlineAttachment}
|
||||
/>
|
||||
</FileContent>
|
||||
)}
|
||||
outlined={outlineAttachment}
|
||||
/>
|
||||
</div>
|
||||
{renderCaption()}
|
||||
</>
|
||||
</div>
|
||||
);
|
||||
|
||||
if (msgType === MsgType.Text) {
|
||||
@@ -192,71 +239,108 @@ function RenderMessageContentInternal({
|
||||
}
|
||||
|
||||
if (msgType === MsgType.Image) {
|
||||
const isGif =
|
||||
content.info?.mimetype === 'image/gif' ||
|
||||
content.info?.mimetype === 'image/webp' ||
|
||||
content.body?.toLowerCase().endsWith('.gif') ||
|
||||
content.body?.toLowerCase().endsWith('.webp') ||
|
||||
(typeof content.url === 'string' && content.url.toLowerCase().includes('gif'));
|
||||
|
||||
return (
|
||||
<>
|
||||
<MImage
|
||||
content={content}
|
||||
renderImageContent={(imageProps) => (
|
||||
<ImageContent
|
||||
{...imageProps}
|
||||
autoPlay={mediaAutoLoad}
|
||||
renderImage={(p) => <Image {...p} loading="lazy" />}
|
||||
renderViewer={(p) => <ImageViewer {...p} />}
|
||||
/>
|
||||
)}
|
||||
outlined={outlineAttachment}
|
||||
/>
|
||||
<div
|
||||
style={{
|
||||
display: 'flex',
|
||||
flexDirection: captionPositionMap[captionPosition],
|
||||
}}
|
||||
>
|
||||
<div>
|
||||
<MImage
|
||||
content={content}
|
||||
renderImageContent={(imageProps) => (
|
||||
<ImageContent
|
||||
{...imageProps}
|
||||
autoPlay={mediaAutoLoad}
|
||||
renderImage={(p) => {
|
||||
if (isGif && !autoplayGifs && p.src) {
|
||||
return (
|
||||
<ClientSideHoverFreeze src={p.src}>
|
||||
<Image {...p} loading="lazy" />
|
||||
</ClientSideHoverFreeze>
|
||||
);
|
||||
}
|
||||
return <Image {...p} loading="lazy" />;
|
||||
}}
|
||||
renderViewer={(p) => <ImageViewer {...p} />}
|
||||
/>
|
||||
)}
|
||||
outlined={outlineAttachment}
|
||||
/>
|
||||
</div>
|
||||
{renderCaption()}
|
||||
</>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
if (msgType === MsgType.Video) {
|
||||
return (
|
||||
<>
|
||||
<MVideo
|
||||
content={content}
|
||||
renderAsFile={renderFile}
|
||||
renderVideoContent={({ body, info, ...videoProps }) => (
|
||||
<VideoContent
|
||||
body={body}
|
||||
info={info}
|
||||
{...videoProps}
|
||||
renderThumbnail={
|
||||
mediaAutoLoad
|
||||
? () => (
|
||||
<ThumbnailContent
|
||||
info={info}
|
||||
renderImage={(src) => (
|
||||
<Image alt={body} title={body} src={src} loading="lazy" />
|
||||
)}
|
||||
/>
|
||||
)
|
||||
: undefined
|
||||
}
|
||||
renderVideo={(p) => <Video {...p} />}
|
||||
/>
|
||||
)}
|
||||
outlined={outlineAttachment}
|
||||
/>
|
||||
<div
|
||||
style={{
|
||||
display: 'flex',
|
||||
flexDirection: captionPositionMap[captionPosition],
|
||||
}}
|
||||
>
|
||||
<div>
|
||||
<MVideo
|
||||
content={content}
|
||||
renderAsFile={renderFile}
|
||||
renderVideoContent={({ body, info, ...videoProps }) => (
|
||||
<VideoContent
|
||||
body={body}
|
||||
info={info}
|
||||
{...videoProps}
|
||||
renderThumbnail={
|
||||
mediaAutoLoad
|
||||
? () => (
|
||||
<ThumbnailContent
|
||||
info={info}
|
||||
renderImage={(src) => (
|
||||
<Image alt={body} title={body} src={src} loading="lazy" />
|
||||
)}
|
||||
/>
|
||||
)
|
||||
: undefined
|
||||
}
|
||||
renderVideo={(p) => <Video {...p} />}
|
||||
/>
|
||||
)}
|
||||
outlined={outlineAttachment}
|
||||
/>
|
||||
</div>
|
||||
{renderCaption()}
|
||||
</>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
if (msgType === MsgType.Audio) {
|
||||
return (
|
||||
<>
|
||||
<MAudio
|
||||
content={content}
|
||||
renderAsFile={renderFile}
|
||||
renderAudioContent={(audioProps) => (
|
||||
<AudioContent {...audioProps} renderMediaControl={(p) => <MediaControl {...p} />} />
|
||||
)}
|
||||
outlined={outlineAttachment}
|
||||
/>
|
||||
<div
|
||||
style={{
|
||||
display: 'flex',
|
||||
flexDirection: captionPositionMap[captionPosition],
|
||||
}}
|
||||
>
|
||||
<div>
|
||||
<MAudio
|
||||
content={content}
|
||||
renderAsFile={renderFile}
|
||||
renderAudioContent={(audioProps) => (
|
||||
<AudioContent {...audioProps} renderMediaControl={(p) => <MediaControl {...p} />} />
|
||||
)}
|
||||
outlined={outlineAttachment}
|
||||
/>
|
||||
</div>
|
||||
{renderCaption()}
|
||||
</>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
import { Box, Text, Icon, Icons, config, IconSrc } from 'folds';
|
||||
import { SequenceCard } from '$components/sequence-card';
|
||||
import { SettingTile } from '$components/setting-tile';
|
||||
import { BetaNoticeBadge } from '$components/BetaNoticeBadge';
|
||||
import { CreateRoomType } from './types';
|
||||
|
||||
type CreateRoomTypeSelectorProps = {
|
||||
@@ -32,10 +33,14 @@ export function CreateRoomTypeSelector({
|
||||
before={<Icon size="400" src={getIcon(CreateRoomType.TextRoom)} />}
|
||||
after={value === CreateRoomType.TextRoom && <Icon src={Icons.Check} />}
|
||||
>
|
||||
<Text size="H6">Text</Text>
|
||||
<Text size="T300" priority="300">
|
||||
Send text messages, videos and GIFs.
|
||||
</Text>
|
||||
<Box gap="200" alignItems="Baseline">
|
||||
<Text size="H6" style={{ flexShrink: 0 }}>
|
||||
Chat Room
|
||||
</Text>
|
||||
<Text size="T300" priority="300" truncate>
|
||||
- Messages, photos, and videos.
|
||||
</Text>
|
||||
</Box>
|
||||
</SettingTile>
|
||||
</SequenceCard>
|
||||
<SequenceCard
|
||||
@@ -53,10 +58,15 @@ export function CreateRoomTypeSelector({
|
||||
before={<Icon size="400" src={getIcon(CreateRoomType.VoiceRoom)} />}
|
||||
after={value === CreateRoomType.VoiceRoom && <Icon src={Icons.Check} />}
|
||||
>
|
||||
<Text size="H6">Voice</Text>
|
||||
<Text size="T300" priority="300">
|
||||
A room optimized for voice calls.
|
||||
</Text>
|
||||
<Box gap="200" alignItems="Baseline">
|
||||
<Text size="H6" style={{ flexShrink: 0 }}>
|
||||
Voice Room
|
||||
</Text>
|
||||
<Text size="T300" priority="300" truncate>
|
||||
- Live audio and video conversations.
|
||||
</Text>
|
||||
<BetaNoticeBadge />
|
||||
</Box>
|
||||
</SettingTile>
|
||||
</SequenceCard>
|
||||
</Box>
|
||||
|
||||
@@ -14,6 +14,8 @@ import { mxcUrlToHttp } from '$utils/matrix';
|
||||
import { useMediaAuthentication } from '$hooks/useMediaAuthentication';
|
||||
import { ImageUsage, PackImageReader } from '$plugins/custom-emoji';
|
||||
import { getEmoticonSearchStr } from '$plugins/utils';
|
||||
import { useSetting } from '$state/hooks/settings';
|
||||
import { settingsAtom } from '$state/settings';
|
||||
import { createEmoticonElement, moveCursor, replaceWithElement } from '$components/editor/utils';
|
||||
import { AutocompleteMenu } from './AutocompleteMenu';
|
||||
import { AutocompleteQuery } from './autocompleteQuery';
|
||||
@@ -53,6 +55,8 @@ export function EmoticonAutocomplete({
|
||||
const imagePacks = useRelevantImagePacks(ImageUsage.Emoticon, imagePackRooms);
|
||||
const recentEmoji = useRecentEmoji(mx, 20);
|
||||
|
||||
const [emojiThreshold] = useSetting(settingsAtom, 'emojiSuggestThreshold');
|
||||
|
||||
const searchList = useMemo(() => {
|
||||
const list: Array<EmoticonSearchItem> = [];
|
||||
return list.concat(
|
||||
@@ -69,9 +73,12 @@ export function EmoticonAutocomplete({
|
||||
const autoCompleteEmoticon = result ? result.items.slice(0, 20) : recentEmoji;
|
||||
|
||||
useEffect(() => {
|
||||
if (query.text) search(query.text);
|
||||
else resetSearch();
|
||||
}, [query.text, search, resetSearch]);
|
||||
if (query.text && query.text.length >= emojiThreshold) {
|
||||
search(query.text);
|
||||
} else {
|
||||
resetSearch();
|
||||
}
|
||||
}, [query.text, search, resetSearch, emojiThreshold]);
|
||||
|
||||
const handleAutocomplete: EmoticonCompleteHandler =
|
||||
onEmoticonSelected ??
|
||||
|
||||
@@ -169,6 +169,7 @@ export function RoomMentionAutocomplete({
|
||||
<RoomIcon
|
||||
size="50"
|
||||
joinRule={room.getJoinRule() ?? JoinRule.Restricted}
|
||||
roomType={room.getType()}
|
||||
filled
|
||||
/>
|
||||
)}
|
||||
|
||||
@@ -31,6 +31,7 @@ import {
|
||||
MessageUnsupportedContent,
|
||||
} from './content';
|
||||
import { MessageTextBody } from './layout';
|
||||
import { unwrapForwardedContent } from './modals/MessageForward';
|
||||
|
||||
export function MBadEncrypted() {
|
||||
return (
|
||||
@@ -86,6 +87,10 @@ export function MText({ edited, content, renderBody, renderUrlsPreview, style }:
|
||||
typeof content.formatted_body === 'string' ? content.formatted_body : undefined;
|
||||
|
||||
const trimmedBody = useMemo(() => trimReplyFromBody(body), [body]);
|
||||
const unwrappedForwardedContent = useMemo(
|
||||
() => unwrapForwardedContent(customBody ?? body),
|
||||
[customBody, body]
|
||||
);
|
||||
|
||||
const safeCustomBody = useMemo(() => {
|
||||
if (!customBody) return undefined;
|
||||
@@ -96,6 +101,10 @@ export function MText({ edited, content, renderBody, renderUrlsPreview, style }:
|
||||
return customBody;
|
||||
}, [customBody]);
|
||||
|
||||
const isForwarded = useMemo(() => {
|
||||
const forwardMeta = content['moe.sable.message.forward'];
|
||||
return typeof forwardMeta === 'object';
|
||||
}, [content]);
|
||||
const isJumbo = useMemo(() => {
|
||||
if (!trimmedBody || trimmedBody.length >= 500) return false;
|
||||
if (!JUMBO_EMOJI_REG.test(trimmedBody)) return false;
|
||||
@@ -113,6 +122,19 @@ export function MText({ edited, content, renderBody, renderUrlsPreview, style }:
|
||||
const urlsMatch = renderUrlsPreview && trimmedBody.match(URL_REG);
|
||||
const urls = urlsMatch ? [...new Set(urlsMatch)] : undefined;
|
||||
|
||||
if (isForwarded && unwrappedForwardedContent) {
|
||||
return (
|
||||
<MessageTextBody preWrap={typeof unwrappedForwardedContent !== 'string'} style={style}>
|
||||
{renderBody({
|
||||
body: trimmedBody,
|
||||
customBody: unwrappedForwardedContent,
|
||||
})}
|
||||
{edited && <MessageEditedContent />}
|
||||
{renderUrlsPreview && urls && urls.length > 0 && renderUrlsPreview(urls)}
|
||||
</MessageTextBody>
|
||||
);
|
||||
}
|
||||
|
||||
return (
|
||||
<>
|
||||
<MessageTextBody
|
||||
@@ -231,14 +253,20 @@ export function MImage({ content, renderImageContent, outlined }: MImageProps) {
|
||||
const height = scaleYDimension(imgInfo?.w || 400, 400, imgInfo?.h || 400);
|
||||
|
||||
return (
|
||||
<Attachment outlined={outlined}>
|
||||
<Attachment
|
||||
style={{
|
||||
flexGrow: 1,
|
||||
flexShrink: 0,
|
||||
}}
|
||||
outlined={outlined}
|
||||
>
|
||||
<AttachmentBox
|
||||
style={{
|
||||
height: toRem(height < 48 ? 48 : height),
|
||||
}}
|
||||
>
|
||||
{renderImageContent({
|
||||
body: content.body || 'Image',
|
||||
body: content.filename || 'Image',
|
||||
info: imgInfo,
|
||||
mimeType: imgInfo?.mimetype,
|
||||
url: mxcUrl,
|
||||
@@ -283,7 +311,13 @@ export function MVideo({ content, renderAsFile, renderVideoContent, outlined }:
|
||||
const filename = content.filename ?? content.body ?? 'Video';
|
||||
|
||||
return (
|
||||
<Attachment outlined={outlined}>
|
||||
<Attachment
|
||||
style={{
|
||||
flexGrow: 1,
|
||||
flexShrink: 0,
|
||||
}}
|
||||
outlined={outlined}
|
||||
>
|
||||
<AttachmentHeader>
|
||||
<FileHeader
|
||||
body={filename}
|
||||
|
||||
@@ -1,4 +1,5 @@
|
||||
import { Box, Text, as } from 'folds';
|
||||
import { useState } from 'react';
|
||||
import { Box, Icon, Icons, Text, as } from 'folds';
|
||||
import classNames from 'classnames';
|
||||
import { MatrixClient, MatrixEvent, Room } from '$types/matrix-sdk';
|
||||
import { getHexcodeForEmoji, getShortcodeFor } from '$plugins/emoji';
|
||||
@@ -16,34 +17,52 @@ export const Reaction = as<
|
||||
reaction: string;
|
||||
useAuthentication?: boolean;
|
||||
}
|
||||
>(({ className, mx, count, reaction, useAuthentication, ...props }, ref) => (
|
||||
<Box
|
||||
as="button"
|
||||
className={classNames(css.Reaction, className)}
|
||||
alignItems="Center"
|
||||
shrink="No"
|
||||
gap="200"
|
||||
{...props}
|
||||
ref={ref}
|
||||
>
|
||||
<Text className={css.ReactionText} as="span" size="T400">
|
||||
{reaction.startsWith('mxc://') ? (
|
||||
<img
|
||||
className={css.ReactionImg}
|
||||
src={mxcUrlToHttp(mx, reaction, useAuthentication) ?? reaction}
|
||||
alt={reaction}
|
||||
/>
|
||||
) : (
|
||||
<Text as="span" size="Inherit" truncate>
|
||||
{reaction}
|
||||
</Text>
|
||||
)}
|
||||
</Text>
|
||||
<Text as="span" size="T300">
|
||||
{count}
|
||||
</Text>
|
||||
</Box>
|
||||
));
|
||||
>(({ className, mx, count, reaction, useAuthentication, ...props }, ref) => {
|
||||
const [imgError, setImgError] = useState(false);
|
||||
|
||||
return (
|
||||
<Box
|
||||
as="button"
|
||||
className={classNames(css.Reaction, className)}
|
||||
alignItems="Center"
|
||||
shrink="No"
|
||||
gap="200"
|
||||
{...props}
|
||||
ref={ref}
|
||||
>
|
||||
<Text className={css.ReactionText} as="span" size="T400">
|
||||
{reaction.startsWith('mxc://') ? (
|
||||
(() => {
|
||||
if (imgError)
|
||||
return (
|
||||
// Image loaded but fetch failed — show a small warning icon so the
|
||||
// reaction button still renders correctly and the user can see
|
||||
// something went wrong rather than a browser broken-image icon.
|
||||
<span title="Failed to load emoji image" aria-label="Failed to load emoji image">
|
||||
<Icon size="100" src={Icons.Warning} style={{ opacity: 0.5 }} />
|
||||
</span>
|
||||
);
|
||||
return (
|
||||
<img
|
||||
className={css.ReactionImg}
|
||||
src={mxcUrlToHttp(mx, reaction, useAuthentication) ?? reaction}
|
||||
alt={reaction}
|
||||
onError={() => setImgError(true)}
|
||||
/>
|
||||
);
|
||||
})()
|
||||
) : (
|
||||
<Text as="span" size="Inherit" truncate>
|
||||
{reaction}
|
||||
</Text>
|
||||
)}
|
||||
</Text>
|
||||
<Text as="span" size="T300">
|
||||
{count}
|
||||
</Text>
|
||||
</Box>
|
||||
);
|
||||
});
|
||||
|
||||
type ReactionTooltipMsgProps = {
|
||||
room: Room;
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
import { Box, Icon, Icons, Text, as, color, toRem } from 'folds';
|
||||
import { Box, Chip, Icon, Icons, Text, as, color, toRem } from 'folds';
|
||||
import { EventTimelineSet, Room } from '$types/matrix-sdk';
|
||||
import { MouseEventHandler, ReactNode, useCallback, useMemo } from 'react';
|
||||
import { useQueryClient } from '@tanstack/react-query';
|
||||
import classNames from 'classnames';
|
||||
import parse from 'html-react-parser';
|
||||
import { useAtomValue } from 'jotai';
|
||||
@@ -14,9 +15,16 @@ import {
|
||||
} from '$plugins/react-custom-html-parser';
|
||||
import { useRoomEvent } from '$hooks/useRoomEvent';
|
||||
import { useSableCosmetics } from '$hooks/useSableCosmetics';
|
||||
import { useMediaAuthentication } from '$hooks/useMediaAuthentication';
|
||||
import { useIgnoredUsers } from '$hooks/useIgnoredUsers';
|
||||
import { nicknamesAtom } from '$state/nicknames';
|
||||
import { useMatrixClient } from '$hooks/useMatrixClient';
|
||||
import { MessageBadEncryptedContent, MessageDeletedContent, MessageFailedContent } from './content';
|
||||
import {
|
||||
MessageBadEncryptedContent,
|
||||
MessageBlockedContent,
|
||||
MessageDeletedContent,
|
||||
MessageFailedContent,
|
||||
} from './content';
|
||||
import * as css from './Reply.css';
|
||||
import { LinePlaceholder } from './placeholder';
|
||||
|
||||
@@ -74,14 +82,19 @@ export const Reply = as<'div', ReplyProps>(
|
||||
[timelineSet, replyEventId]
|
||||
);
|
||||
const replyEvent = useRoomEvent(room, replyEventId, getFromLocalTimeline);
|
||||
const queryClient = useQueryClient();
|
||||
|
||||
const mx = useMatrixClient();
|
||||
|
||||
const { body, formatted_body: formattedBody, format } = replyEvent?.getContent() ?? {};
|
||||
const sender = replyEvent?.getSender();
|
||||
|
||||
const ignoredUsers = useIgnoredUsers();
|
||||
const isBlockedSender = !!sender && ignoredUsers.includes(sender);
|
||||
|
||||
const { color: usernameColor, font: usernameFont } = useSableCosmetics(sender ?? '', room);
|
||||
const nicknames = useAtomValue(nicknamesAtom);
|
||||
const useAuthentication = useMediaAuthentication();
|
||||
|
||||
const fallbackBody = replyEvent?.isRedacted() ? (
|
||||
<MessageDeletedContent />
|
||||
@@ -90,6 +103,18 @@ export const Reply = as<'div', ReplyProps>(
|
||||
);
|
||||
|
||||
const badEncryption = replyEvent?.getContent().msgtype === 'm.bad.encrypted';
|
||||
|
||||
// An encrypted event that hasn't been decrypted yet (keys pending) has an
|
||||
// empty result from getClearContent(). Treat it as still-loading rather
|
||||
// than a failure so the UI shows a placeholder instead of MessageFailedContent
|
||||
// until the MatrixEventEvent.Decrypted callback fires.
|
||||
const isPendingDecrypt =
|
||||
replyEvent !== undefined &&
|
||||
replyEvent !== null &&
|
||||
replyEvent.isEncrypted() &&
|
||||
!replyEvent.isDecryptionFailure() &&
|
||||
!replyEvent.getClearContent();
|
||||
|
||||
let bodyJSX: ReactNode = fallbackBody;
|
||||
|
||||
if (format === 'org.matrix.custom.html' && formattedBody) {
|
||||
@@ -100,6 +125,7 @@ export const Reply = as<'div', ReplyProps>(
|
||||
.replace(/(?:\r\n|\r|\n)/g, ' ');
|
||||
const parserOpts = getReactCustomHtmlParser(mx, room.roomId, {
|
||||
linkifyOpts: LINKIFY_OPTS,
|
||||
useAuthentication,
|
||||
nicknames,
|
||||
});
|
||||
bodyJSX = parse(strippedHtml, parserOpts) as JSX.Element;
|
||||
@@ -124,11 +150,15 @@ export const Reply = as<'div', ReplyProps>(
|
||||
)
|
||||
}
|
||||
data-event-id={replyEventId}
|
||||
onClick={onClick}
|
||||
onClick={replyEvent !== null && !isBlockedSender ? onClick : undefined}
|
||||
>
|
||||
{replyEvent !== undefined ? (
|
||||
{replyEvent !== undefined && !isPendingDecrypt ? (
|
||||
<Text size="T300" truncate>
|
||||
{badEncryption ? <MessageBadEncryptedContent /> : bodyJSX}
|
||||
{(() => {
|
||||
if (isBlockedSender) return <MessageBlockedContent />;
|
||||
if (badEncryption) return <MessageBadEncryptedContent />;
|
||||
return bodyJSX;
|
||||
})()}
|
||||
</Text>
|
||||
) : (
|
||||
<LinePlaceholder
|
||||
@@ -140,6 +170,17 @@ export const Reply = as<'div', ReplyProps>(
|
||||
/>
|
||||
)}
|
||||
</ReplyLayout>
|
||||
{replyEvent === null && (
|
||||
<Chip
|
||||
variant="Critical"
|
||||
radii="Pill"
|
||||
before={<Icon size="50" src={Icons.Reload} />}
|
||||
onClick={(evt) => {
|
||||
evt.stopPropagation();
|
||||
queryClient.invalidateQueries({ queryKey: [room.roomId, replyEventId] });
|
||||
}}
|
||||
/>
|
||||
)}
|
||||
</Box>
|
||||
);
|
||||
}
|
||||
|
||||
@@ -58,6 +58,13 @@ export const MessageEmptyContent = as<'div', { children?: never }>(({ ...props }
|
||||
</Box>
|
||||
));
|
||||
|
||||
export const MessageBlockedContent = as<'div', { children?: never }>(({ ...props }, ref) => (
|
||||
<Box as="span" alignItems="Center" gap="100" style={warningStyle} {...props} ref={ref}>
|
||||
<Icon size="50" src={Icons.Cross} />
|
||||
<i>Message from a blocked user</i>
|
||||
</Box>
|
||||
));
|
||||
|
||||
export const MessageEditedContent = as<'span', { children?: never }>(({ ...props }, ref) => (
|
||||
<Text as="span" size="T200" priority="300" {...props} ref={ref}>
|
||||
{' (edited)'}
|
||||
|
||||
@@ -6,6 +6,7 @@ import { modalAtom, ModalType } from '$state/modal';
|
||||
import { MessageReportInternal } from './MessageReport';
|
||||
import { MessageDeleteInternal } from './MessageDelete';
|
||||
import { MessageSourceInternal } from './MessageSource';
|
||||
import { MessageForwardInternal } from './MessageForward';
|
||||
import { MessageAllReactionInternal } from './MessageReactions';
|
||||
import { MessageReadReceiptInternal } from './MessageReadRecipts';
|
||||
|
||||
@@ -40,6 +41,12 @@ export function GlobalModalManager() {
|
||||
</Box>
|
||||
)}
|
||||
|
||||
{modal.type === ModalType.Forward && (
|
||||
<Box>
|
||||
<MessageForwardInternal room={modal.room} mEvent={modal.mEvent} onClose={close} />
|
||||
</Box>
|
||||
)}
|
||||
|
||||
{modal.type === ModalType.Source && (
|
||||
<Modal variant="Surface" size="300">
|
||||
<MessageSourceInternal room={modal.room} mEvent={modal.mEvent} onClose={close} />
|
||||
|
||||
@@ -0,0 +1,285 @@
|
||||
// Modal for message forwarding, which allows users to select a room to forward the message to
|
||||
|
||||
import { useMatrixClient } from '$hooks/useMatrixClient';
|
||||
import { modalAtom, ModalType } from '$state/modal';
|
||||
import {
|
||||
Box,
|
||||
Button,
|
||||
Dialog,
|
||||
Header,
|
||||
Icon,
|
||||
Icons,
|
||||
IconButton,
|
||||
MenuItem,
|
||||
Text,
|
||||
config,
|
||||
Scroll,
|
||||
as,
|
||||
} from 'folds';
|
||||
import { useAtomValue, useSetAtom } from 'jotai';
|
||||
import { JoinRule, MatrixEvent, Room } from '$types/matrix-sdk';
|
||||
import { useEffect, useMemo, useState } from 'react';
|
||||
import { allRoomsAtom } from '$state/room-list/roomList';
|
||||
import { useAllJoinedRoomsSet, useGetRoom } from '$hooks/useGetRoom';
|
||||
import { factoryRoomIdByActivity } from '$utils/sort';
|
||||
import * as css from '$features/room/message/styles.css';
|
||||
import { sanitizeCustomHtml } from '$utils/sanitize';
|
||||
import { getStateEvents } from '$utils/room';
|
||||
import { StateEvent } from '$types/matrix/room';
|
||||
|
||||
// Message forwarding component
|
||||
export const MessageForwardItem = as<'button', MessageForwardItemProps>(
|
||||
({ room, mEvent, onClose, ...props }: MessageForwardItemProps) => {
|
||||
const setModal = useSetAtom(modalAtom);
|
||||
|
||||
const handleClick = () => {
|
||||
setModal({
|
||||
type: ModalType.Forward,
|
||||
room,
|
||||
mEvent,
|
||||
});
|
||||
onClose?.();
|
||||
};
|
||||
|
||||
return (
|
||||
<MenuItem
|
||||
size="300"
|
||||
after={<Icon size="100" src={Icons.ArrowRight} />}
|
||||
radii="300"
|
||||
{...props}
|
||||
onClick={handleClick}
|
||||
>
|
||||
<Text className={css.MessageMenuItemText} as="span" size="T300" truncate>
|
||||
Forward
|
||||
</Text>
|
||||
</MenuItem>
|
||||
);
|
||||
}
|
||||
);
|
||||
|
||||
export const unwrapForwardedContent = (content: string) => {
|
||||
// unwrap the content of a forwarded message if it was wrapped in a blockquote with the data-forward-marker attribute
|
||||
const parser = new DOMParser();
|
||||
const doc = parser.parseFromString(content, 'text/html');
|
||||
const forwardMarker = doc.querySelector('[data-forward-marker]');
|
||||
if (forwardMarker) {
|
||||
const blockquote = forwardMarker.querySelector('blockquote');
|
||||
if (blockquote) {
|
||||
return blockquote.innerHTML;
|
||||
}
|
||||
}
|
||||
return content;
|
||||
};
|
||||
|
||||
type MessageForwardInternalProps = {
|
||||
room: Room;
|
||||
mEvent: MatrixEvent;
|
||||
onClose: () => void;
|
||||
};
|
||||
|
||||
type ForwardMeta = {
|
||||
v: 1;
|
||||
is_forwarded: true;
|
||||
original_timestamp: number;
|
||||
original_room_id?: string;
|
||||
original_event_id?: string;
|
||||
// to mark that event_id and room_id are not present
|
||||
original_event_private: boolean;
|
||||
};
|
||||
|
||||
export function MessageForwardInternal({ room, mEvent, onClose }: MessageForwardInternalProps) {
|
||||
const mx = useMatrixClient();
|
||||
|
||||
const [isTargetSelected, setIsTargetSelected] = useState(false);
|
||||
const [isForwardSuccess, setIsForwardSuccess] = useState(false);
|
||||
const [isForwardError, setIsForwardError] = useState(false);
|
||||
const [targetRoomId, setTargetRoomId] = useState<string | null>(null);
|
||||
|
||||
// detect if it's a public room or not
|
||||
const joinRule = room.getJoinRule() ?? JoinRule.Invite;
|
||||
|
||||
const parentSpaceIds = getStateEvents(room, StateEvent.SpaceParent)
|
||||
.map((e) => e.getStateKey())
|
||||
.filter((id): id is string => Boolean(id));
|
||||
|
||||
const isInPublicSpace = parentSpaceIds.some((spaceId) => {
|
||||
const space = mx.getRoom(spaceId);
|
||||
return Boolean(space?.isSpaceRoom()) && space?.getJoinRule() === JoinRule.Public;
|
||||
});
|
||||
|
||||
// A room is private if its join rule is Invite (or other non-public/non-knock/non-restricted),
|
||||
// or it's Restricted but NOT inside a public space.
|
||||
const isPrivate =
|
||||
joinRule === JoinRule.Invite ||
|
||||
(joinRule === JoinRule.Restricted && !isInPublicSpace) ||
|
||||
(joinRule !== JoinRule.Public &&
|
||||
joinRule !== JoinRule.Knock &&
|
||||
joinRule !== JoinRule.Restricted);
|
||||
|
||||
const allRooms = useAtomValue(allRoomsAtom);
|
||||
const allJoinedRooms = useAllJoinedRoomsSet();
|
||||
const getRoom = useGetRoom(allJoinedRooms);
|
||||
// possible targets to forward the message to
|
||||
const forwardTargets = useMemo(
|
||||
() =>
|
||||
allRooms
|
||||
.filter((id) => id !== room.roomId)
|
||||
.filter((id) => {
|
||||
const target = getRoom(id);
|
||||
return !!target && !target.isSpaceRoom() && target.maySendMessage();
|
||||
})
|
||||
.sort(factoryRoomIdByActivity(mx)),
|
||||
[allRooms, room.roomId, getRoom, mx]
|
||||
);
|
||||
|
||||
useEffect(() => {
|
||||
if (isForwardSuccess) {
|
||||
setTimeout(() => {
|
||||
// close the modal if the message was forwarded successfully
|
||||
onClose();
|
||||
}, 2000);
|
||||
}
|
||||
}, [isForwardSuccess, onClose]);
|
||||
|
||||
// actually forward the message to the selected room
|
||||
const handleForwardClick = () => {
|
||||
if (!targetRoomId) return;
|
||||
|
||||
const targetRoom = getRoom(targetRoomId);
|
||||
const eventId = mEvent.getId();
|
||||
if (!targetRoom || !eventId) return;
|
||||
|
||||
type SendEventType = Parameters<typeof mx.sendEvent>[2];
|
||||
type SendEventContent = Parameters<typeof mx.sendEvent>[3];
|
||||
|
||||
const eventType = mEvent.getType() as SendEventType;
|
||||
// using reference relation to indicate that this is a forwarded message,
|
||||
// which allows clients to display it as such
|
||||
|
||||
const bodyModifText = `(Forwarded message from ${isPrivate ? 'a private room' : (getRoom(room.roomId)?.name ?? 'a room')})`;
|
||||
let newBodyPlain = '';
|
||||
let newBodyHtml = '';
|
||||
// transform if msgtype is m.text
|
||||
if (mEvent.getContent().msgtype === 'm.text') {
|
||||
const original = mEvent.getContent().body;
|
||||
newBodyPlain = `${bodyModifText}\n\n${original
|
||||
.split('\n')
|
||||
.map((l: string) => `> ${l}`)
|
||||
.join('\n')}`;
|
||||
const safeHtml = sanitizeCustomHtml(original).replace(/\n/g, '<br>');
|
||||
newBodyHtml =
|
||||
`<div class="forwarded" data-forward-marker>` +
|
||||
`<p>${sanitizeCustomHtml(bodyModifText)}</p>` +
|
||||
`<blockquote>${safeHtml}</blockquote>` +
|
||||
`</div>`;
|
||||
}
|
||||
let content;
|
||||
// handle privacy stuff
|
||||
if (isPrivate) {
|
||||
// if the message is from a private room, we should strip any media or mentions to avoid leaking information to the target room
|
||||
// we can still include the original message content in the body of the message, so we'll just use a fallback text/plain content with the original message body
|
||||
content = {
|
||||
...mEvent.getContent(),
|
||||
body: newBodyPlain,
|
||||
format: 'org.matrix.custom.html',
|
||||
formatted_body: newBodyHtml,
|
||||
'moe.sable.message.forward': {
|
||||
v: 1,
|
||||
is_forwarded: true,
|
||||
original_timestamp: mEvent.getTs(),
|
||||
original_event_private: true,
|
||||
} satisfies ForwardMeta,
|
||||
};
|
||||
} else {
|
||||
content = {
|
||||
...mEvent.getContent(),
|
||||
body: newBodyPlain,
|
||||
format: 'org.matrix.custom.html',
|
||||
formatted_body: newBodyHtml,
|
||||
'm.relates_to': {
|
||||
rel_type: 'm.reference',
|
||||
event_id: eventId,
|
||||
},
|
||||
'moe.sable.message.forward': {
|
||||
v: 1,
|
||||
is_forwarded: true,
|
||||
original_timestamp: mEvent.getTs(),
|
||||
original_room_id: room.roomId,
|
||||
original_event_id: eventId,
|
||||
original_event_private: false,
|
||||
} satisfies ForwardMeta,
|
||||
};
|
||||
}
|
||||
|
||||
try {
|
||||
mx.sendEvent(targetRoom.roomId, null, eventType, content as unknown as SendEventContent).then(
|
||||
() => setIsForwardSuccess(true)
|
||||
);
|
||||
} catch {
|
||||
setIsForwardSuccess(false);
|
||||
setIsForwardError(true);
|
||||
}
|
||||
};
|
||||
|
||||
return (
|
||||
<Dialog variant="Surface">
|
||||
<Header
|
||||
style={{
|
||||
padding: `0 ${config.space.S200} 0 ${config.space.S400}`,
|
||||
borderBottomWidth: config.borderWidth.B300,
|
||||
}}
|
||||
variant="Surface"
|
||||
size="500"
|
||||
>
|
||||
<Box grow="Yes">
|
||||
<Text size="H4">Forward Message</Text>
|
||||
</Box>
|
||||
<IconButton size="300" onClick={onClose} radii="300">
|
||||
<Icon src={Icons.Cross} />
|
||||
</IconButton>
|
||||
</Header>
|
||||
<Box direction="Column" style={{ height: '300px' }}>
|
||||
<Scroll hideTrack>
|
||||
<Box direction="Column" style={{ padding: config.space.S300 }}>
|
||||
{forwardTargets.map((roomId) => {
|
||||
const target = getRoom(roomId);
|
||||
if (!target) return null;
|
||||
return (
|
||||
<MenuItem
|
||||
key={roomId}
|
||||
data-room-id={roomId}
|
||||
onClick={() => {
|
||||
setIsTargetSelected(true);
|
||||
setTargetRoomId(roomId);
|
||||
}}
|
||||
variant={targetRoomId === roomId ? 'Success' : 'Surface'}
|
||||
aria-pressed={targetRoomId === roomId}
|
||||
size="400"
|
||||
radii="400"
|
||||
>
|
||||
<Text truncate>{target.name}</Text>
|
||||
</MenuItem>
|
||||
);
|
||||
})}
|
||||
</Box>
|
||||
</Scroll>
|
||||
{isTargetSelected && targetRoomId && (
|
||||
<Button style={{ margin: config.space.S300 }} onClick={handleForwardClick}>
|
||||
<Text>Forward to {getRoom(targetRoomId)?.name}</Text>
|
||||
</Button>
|
||||
)}
|
||||
{isForwardError && (
|
||||
<Text size="T300" color="Critical600" style={{ margin: config.space.S300 }}>
|
||||
Failed to forward message. Please try again.
|
||||
</Text>
|
||||
)}
|
||||
</Box>
|
||||
</Dialog>
|
||||
);
|
||||
}
|
||||
|
||||
type MessageForwardItemProps = {
|
||||
room: Room;
|
||||
mEvent: MatrixEvent;
|
||||
onClose?: () => void;
|
||||
};
|
||||
@@ -110,11 +110,18 @@ export const BannerRoomName = style({
|
||||
});
|
||||
|
||||
// Caps tall previews and fades the bottom edge when content overflows.
|
||||
// Desktop: 25vh, mobile (≤768px): 35vh.
|
||||
export const BannerBody = style({
|
||||
position: 'relative',
|
||||
maxHeight: toRem(56),
|
||||
maxHeight: '25vh',
|
||||
overflow: 'hidden',
|
||||
|
||||
'@media': {
|
||||
'(max-width: 768px)': {
|
||||
maxHeight: '35vh',
|
||||
},
|
||||
},
|
||||
|
||||
selectors: {
|
||||
'&[data-overflow=true]::after': {
|
||||
content: '""',
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
import { useAtom } from 'jotai';
|
||||
import { useCallback, useEffect, useRef, useState } from 'react';
|
||||
import { ReactNode, useCallback, useEffect, useRef, useState } from 'react';
|
||||
import { Box, Icon, IconButton, Icons, Text } from 'folds';
|
||||
import { inAppBannerAtom, InAppBannerNotification } from '$state/sessions';
|
||||
import * as css from './NotificationBanner.css';
|
||||
@@ -26,6 +26,26 @@ function BodyText({ text, hovered }: { text: string; hovered: boolean }) {
|
||||
);
|
||||
}
|
||||
|
||||
// Same as BodyText but renders a pre-built ReactNode (rich HTML with mxc/mention transforms).
|
||||
function BodyNode({ node, hovered }: { node: ReactNode; hovered: boolean }) {
|
||||
const ref = useRef<HTMLDivElement>(null);
|
||||
const [overflow, setOverflow] = useState(false);
|
||||
|
||||
useEffect(() => {
|
||||
const el = ref.current;
|
||||
if (!el) return;
|
||||
setOverflow(el.scrollHeight > el.clientHeight);
|
||||
}, [node]);
|
||||
|
||||
return (
|
||||
<div ref={ref} className={css.BannerBody} data-overflow={overflow} data-hovered={hovered}>
|
||||
<Text size="T200" priority="300">
|
||||
{node}
|
||||
</Text>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
type BannerItemProps = {
|
||||
notification: InAppBannerNotification;
|
||||
onDismiss: (id: string) => void;
|
||||
@@ -115,7 +135,11 @@ function BannerItem({ notification, onDismiss }: BannerItemProps) {
|
||||
</span>
|
||||
)}
|
||||
</Text>
|
||||
{notification.body && <BodyText text={notification.body} hovered={paused} />}
|
||||
{notification.bodyNode ? (
|
||||
<BodyNode node={notification.bodyNode} hovered={paused} />
|
||||
) : (
|
||||
notification.body && <BodyText text={notification.body} hovered={paused} />
|
||||
)}
|
||||
</div>
|
||||
<Box shrink="No">
|
||||
<IconButton
|
||||
|
||||
@@ -17,6 +17,7 @@ export const SequenceCard = as<
|
||||
firstChild,
|
||||
lastChild,
|
||||
outlined,
|
||||
mergeBorder,
|
||||
...props
|
||||
},
|
||||
ref
|
||||
@@ -24,7 +25,7 @@ export const SequenceCard = as<
|
||||
<Box
|
||||
as={AsSequenceCard}
|
||||
className={classNames(
|
||||
css.SequenceCard({ radii, outlined }),
|
||||
css.SequenceCard({ radii, outlined, mergeBorder }),
|
||||
ContainerColor({ variant }),
|
||||
className
|
||||
)}
|
||||
|
||||
@@ -11,7 +11,7 @@ export const SequenceCard = recipe({
|
||||
},
|
||||
borderStyle: 'solid',
|
||||
borderWidth: outlinedWidth,
|
||||
borderBottomWidth: 0,
|
||||
|
||||
selectors: {
|
||||
'&:first-child, :not(&) + &': {
|
||||
borderTopLeftRadius: [radii],
|
||||
@@ -20,7 +20,6 @@ export const SequenceCard = recipe({
|
||||
'&:last-child, &:not(:has(+&))': {
|
||||
borderBottomLeftRadius: [radii],
|
||||
borderBottomRightRadius: [radii],
|
||||
borderBottomWidth: outlinedWidth,
|
||||
},
|
||||
[`&[data-first-child="true"]`]: {
|
||||
borderTopLeftRadius: [radii],
|
||||
@@ -74,6 +73,16 @@ export const SequenceCard = recipe({
|
||||
},
|
||||
},
|
||||
},
|
||||
mergeBorder: {
|
||||
true: {
|
||||
borderBottomWidth: 0,
|
||||
selectors: {
|
||||
'&:last-child, &:not(:has(+&))': {
|
||||
borderBottomWidth: outlinedWidth,
|
||||
},
|
||||
},
|
||||
},
|
||||
},
|
||||
},
|
||||
defaultVariants: {
|
||||
radii: '400',
|
||||
|
||||
@@ -0,0 +1,17 @@
|
||||
import { as, Avatar } from 'folds';
|
||||
import classNames from 'classnames';
|
||||
import * as css from './styles.css';
|
||||
|
||||
type StackedAvatarProps = {
|
||||
radii?: '0' | '300' | '400' | '500' | 'Pill' | 'Inherit' | undefined;
|
||||
};
|
||||
export const StackedAvatar = as<'span', css.StackedAvatarVariants & StackedAvatarProps>(
|
||||
({ size, variant, className, ...props }, ref) => (
|
||||
<Avatar
|
||||
size={size}
|
||||
className={classNames(css.StackedAvatar({ size, variant }), className)}
|
||||
{...props}
|
||||
ref={ref}
|
||||
/>
|
||||
)
|
||||
);
|
||||
@@ -0,0 +1 @@
|
||||
export * from './StackedAvatar';
|
||||
@@ -0,0 +1,59 @@
|
||||
import { ComplexStyleRule } from '@vanilla-extract/css';
|
||||
import { recipe, RecipeVariants } from '@vanilla-extract/recipes';
|
||||
import { color, config, ContainerColor, toRem } from 'folds';
|
||||
|
||||
const getVariant = (variant: ContainerColor): ComplexStyleRule => ({
|
||||
outlineColor: color[variant].Container,
|
||||
});
|
||||
|
||||
export const StackedAvatar = recipe({
|
||||
base: {
|
||||
backgroundColor: color.Surface.Container,
|
||||
outlineStyle: 'solid',
|
||||
selectors: {
|
||||
'&:first-child': {
|
||||
marginLeft: 0,
|
||||
},
|
||||
'button&': {
|
||||
cursor: 'pointer',
|
||||
},
|
||||
},
|
||||
},
|
||||
|
||||
variants: {
|
||||
size: {
|
||||
'200': {
|
||||
marginLeft: toRem(-6),
|
||||
outlineWidth: config.borderWidth.B300,
|
||||
},
|
||||
'300': {
|
||||
marginLeft: toRem(-9),
|
||||
outlineWidth: config.borderWidth.B400,
|
||||
},
|
||||
'400': {
|
||||
marginLeft: toRem(-10.5),
|
||||
outlineWidth: config.borderWidth.B500,
|
||||
},
|
||||
'500': {
|
||||
marginLeft: toRem(-13),
|
||||
outlineWidth: config.borderWidth.B600,
|
||||
},
|
||||
},
|
||||
variant: {
|
||||
Background: getVariant('Background'),
|
||||
Surface: getVariant('Surface'),
|
||||
SurfaceVariant: getVariant('SurfaceVariant'),
|
||||
Primary: getVariant('Primary'),
|
||||
Secondary: getVariant('Secondary'),
|
||||
Success: getVariant('Success'),
|
||||
Warning: getVariant('Warning'),
|
||||
Critical: getVariant('Critical'),
|
||||
},
|
||||
},
|
||||
defaultVariants: {
|
||||
size: '400',
|
||||
variant: 'Surface',
|
||||
},
|
||||
});
|
||||
|
||||
export type StackedAvatarVariants = RecipeVariants<typeof StackedAvatar>;
|
||||
@@ -7,6 +7,8 @@ import { settingsAtom } from '$state/settings';
|
||||
type UnreadBadgeProps = {
|
||||
highlight?: boolean;
|
||||
count: number;
|
||||
/** Whether this badge belongs to a DM room. Used with the badgeCountDMsOnly setting. */
|
||||
dm?: boolean;
|
||||
};
|
||||
const styles: CSSProperties = {
|
||||
minWidth: toRem(16),
|
||||
@@ -19,11 +21,14 @@ export function UnreadBadgeCenter({ children }: { children: ReactNode }) {
|
||||
);
|
||||
}
|
||||
|
||||
export function UnreadBadge({ highlight, count }: UnreadBadgeProps) {
|
||||
export function UnreadBadge({ highlight, count, dm }: UnreadBadgeProps) {
|
||||
const [showUnreadCounts] = useSetting(settingsAtom, 'showUnreadCounts');
|
||||
const [badgeCountDMsOnly] = useSetting(settingsAtom, 'badgeCountDMsOnly');
|
||||
const [showPingCounts] = useSetting(settingsAtom, 'showPingCounts');
|
||||
|
||||
const showNumber = count > 0 && (showUnreadCounts || (highlight && showPingCounts));
|
||||
// Show count when: (showUnreadCounts OR highlight+showPingCounts) AND (not DM-only mode OR this is a DM)
|
||||
const showNumber =
|
||||
count > 0 && (showUnreadCounts || (highlight && showPingCounts)) && (!badgeCountDMsOnly || dm);
|
||||
|
||||
return (
|
||||
<Badge
|
||||
|
||||
@@ -1,5 +1,24 @@
|
||||
import { ReactNode, useEffect } from 'react';
|
||||
import { Box, Chip, Icon, IconButton, Icons, Text, color, config, toRem } from 'folds';
|
||||
import { ReactNode, useEffect, useMemo, useState } from 'react';
|
||||
import {
|
||||
Box,
|
||||
Chip,
|
||||
Icon,
|
||||
IconButton,
|
||||
Icons,
|
||||
Scroll,
|
||||
Text,
|
||||
Tooltip,
|
||||
TooltipProvider,
|
||||
color,
|
||||
config,
|
||||
toRem,
|
||||
} from 'folds';
|
||||
import { HTMLReactParserOptions } from 'html-react-parser';
|
||||
import { useMediaAuthentication } from '$hooks/useMediaAuthentication';
|
||||
import { Opts as LinkifyOpts } from 'linkifyjs';
|
||||
import { getReactCustomHtmlParser, LINKIFY_OPTS } from '$plugins/react-custom-html-parser';
|
||||
import { useSpoilerClickHandler } from '$hooks/useSpoilerClickHandler';
|
||||
import { RenderBody } from '$components/message';
|
||||
import { UploadStatus, UploadSuccess, useBindUploadAtom } from '$state/upload';
|
||||
import { useMatrixClient } from '$hooks/useMatrixClient';
|
||||
import { TUploadContent } from '$utils/matrix';
|
||||
@@ -8,6 +27,7 @@ import { roomUploadAtomFamily, TUploadItem, TUploadMetadata } from '$state/room/
|
||||
import { useObjectURL } from '$hooks/useObjectURL';
|
||||
import { useMediaConfig } from '$hooks/useMediaConfig';
|
||||
import { UploadCard, UploadCardError, UploadCardProgress } from './UploadCard';
|
||||
import { DescriptionEditor } from './UploadDescriptionEditor';
|
||||
|
||||
type PreviewImageProps = {
|
||||
fileItem: TUploadItem;
|
||||
@@ -98,15 +118,19 @@ type UploadCardRendererProps = {
|
||||
isEncrypted?: boolean;
|
||||
fileItem: TUploadItem;
|
||||
setMetadata: (fileItem: TUploadItem, metadata: TUploadMetadata) => void;
|
||||
setDesc: (fileItem: TUploadItem, body: string, formatted_body: string) => void;
|
||||
onRemove: (file: TUploadContent) => void;
|
||||
onComplete?: (upload: UploadSuccess) => void;
|
||||
roomId: string;
|
||||
};
|
||||
export function UploadCardRenderer({
|
||||
isEncrypted,
|
||||
fileItem,
|
||||
setMetadata,
|
||||
setDesc,
|
||||
onRemove,
|
||||
onComplete,
|
||||
roomId,
|
||||
}: UploadCardRendererProps) {
|
||||
const mx = useMatrixClient();
|
||||
const mediaConfig = useMediaConfig();
|
||||
@@ -118,6 +142,8 @@ export function UploadCardRenderer({
|
||||
const { file } = upload;
|
||||
const fileSizeExceeded = file.size >= allowSize;
|
||||
|
||||
const [isDescribed, setIsDescribed] = useState(false);
|
||||
|
||||
if (upload.status === UploadStatus.Idle && !fileSizeExceeded) {
|
||||
startUpload();
|
||||
}
|
||||
@@ -137,6 +163,19 @@ export function UploadCardRenderer({
|
||||
}
|
||||
}, [upload, onComplete]);
|
||||
|
||||
const linkifyOpts = useMemo<LinkifyOpts>(() => ({ ...LINKIFY_OPTS }), []);
|
||||
|
||||
const spoilerClickHandler = useSpoilerClickHandler();
|
||||
const useAuthentication = useMediaAuthentication();
|
||||
const htmlReactParserOptions = useMemo<HTMLReactParserOptions>(
|
||||
() =>
|
||||
getReactCustomHtmlParser(mx, roomId, {
|
||||
linkifyOpts,
|
||||
useAuthentication,
|
||||
handleSpoilerClick: spoilerClickHandler,
|
||||
}),
|
||||
[linkifyOpts, mx, roomId, spoilerClickHandler, useAuthentication]
|
||||
);
|
||||
return (
|
||||
<UploadCard
|
||||
radii="300"
|
||||
@@ -155,6 +194,36 @@ export function UploadCardRenderer({
|
||||
<Text size="B300">Retry</Text>
|
||||
</Chip>
|
||||
)}
|
||||
{!isDescribed && (
|
||||
<IconButton
|
||||
onClick={() => {
|
||||
setIsDescribed(true);
|
||||
}}
|
||||
aria-label="Add Upload Description"
|
||||
variant="SurfaceVariant"
|
||||
radii="Pill"
|
||||
size="300"
|
||||
>
|
||||
<Icon src={Icons.Pencil} size="50" />
|
||||
</IconButton>
|
||||
)}
|
||||
{isDescribed && (
|
||||
<TooltipProvider
|
||||
delay={400}
|
||||
position="Top"
|
||||
style={{ textAlign: 'center' }}
|
||||
tooltip={
|
||||
<Tooltip>
|
||||
<Text size="H5">
|
||||
Don't forget to save your description before sending the message!
|
||||
</Text>
|
||||
</Tooltip>
|
||||
}
|
||||
>
|
||||
{(triggerRef) => <Icon ref={triggerRef} src={Icons.Info} size="50" />}
|
||||
</TooltipProvider>
|
||||
)}
|
||||
|
||||
<IconButton
|
||||
onClick={removeUpload}
|
||||
aria-label="Cancel Upload"
|
||||
@@ -198,6 +267,43 @@ export function UploadCardRenderer({
|
||||
</Text>
|
||||
</UploadCardError>
|
||||
)}
|
||||
|
||||
{isDescribed && (
|
||||
<DescriptionEditor
|
||||
value={fileItem.formatted_body || fileItem.body}
|
||||
onSave={(plainText, htmlContent) => {
|
||||
setDesc(fileItem, plainText, htmlContent);
|
||||
setIsDescribed(false);
|
||||
}}
|
||||
onCancel={() => setIsDescribed(false)}
|
||||
/>
|
||||
)}
|
||||
{!isDescribed && fileItem.body && fileItem.body.length > 0 && (
|
||||
<Scroll
|
||||
direction="Vertical"
|
||||
variant="SurfaceVariant"
|
||||
visibility="Always"
|
||||
size="300"
|
||||
style={{
|
||||
backgroundColor: 'var(--sable-bg-container)',
|
||||
borderRadius: config.radii.R400,
|
||||
maxHeight: '180px',
|
||||
marginTop: config.space.S0,
|
||||
overflowY: 'auto',
|
||||
}}
|
||||
>
|
||||
<Box style={{ padding: config.space.S200, wordBreak: 'break-word' }}>
|
||||
<Text size="T200" priority="400" as="div">
|
||||
<RenderBody
|
||||
body={fileItem.body}
|
||||
customBody={fileItem.formatted_body}
|
||||
htmlReactParserOptions={htmlReactParserOptions}
|
||||
linkifyOpts={linkifyOpts}
|
||||
/>
|
||||
</Text>
|
||||
</Box>
|
||||
</Scroll>
|
||||
)}
|
||||
</>
|
||||
}
|
||||
>
|
||||
|
||||
@@ -0,0 +1,28 @@
|
||||
import { style, globalStyle } from '@vanilla-extract/css';
|
||||
import { config } from 'folds';
|
||||
|
||||
export const DescriptionEditorContainer = style({
|
||||
backgroundColor: 'var(--sable-bg-container)',
|
||||
borderRadius: config.radii.R400,
|
||||
overflow: 'hidden',
|
||||
});
|
||||
|
||||
globalStyle(`${DescriptionEditorContainer} div[class*="EditorTextarea"]`, {
|
||||
backgroundColor: 'var(--sable-bg-container) !important',
|
||||
border: 'none !important',
|
||||
});
|
||||
|
||||
globalStyle(`${DescriptionEditorContainer} [class*="Toolbar"]`, {
|
||||
backgroundColor: 'var(--sable-bg-container) !important',
|
||||
padding: 'var(--space-S100) !important',
|
||||
borderTop: '1px solid var(--sable-outline-variant) !important',
|
||||
});
|
||||
|
||||
globalStyle(`${DescriptionEditorContainer} [class*="Toolbar"] button`, {
|
||||
backgroundColor: 'transparent !important',
|
||||
boxShadow: 'none !important',
|
||||
});
|
||||
|
||||
globalStyle(`${DescriptionEditorContainer} [class*="Toolbar"] button:hover`, {
|
||||
backgroundColor: 'var(--sable-surface-variant) !important',
|
||||
});
|
||||
@@ -0,0 +1,274 @@
|
||||
import { KeyboardEventHandler, useCallback, useEffect, useState, useRef } from 'react';
|
||||
import {
|
||||
Box,
|
||||
Chip,
|
||||
Icon,
|
||||
IconButton,
|
||||
Icons,
|
||||
Line,
|
||||
PopOut,
|
||||
RectCords,
|
||||
Spinner,
|
||||
Text,
|
||||
config,
|
||||
} from 'folds';
|
||||
import { Editor, Transforms } from 'slate';
|
||||
import { ReactEditor } from 'slate-react';
|
||||
import { isKeyHotkey } from 'is-hotkey';
|
||||
import {
|
||||
AutocompletePrefix,
|
||||
AutocompleteQuery,
|
||||
CustomEditor,
|
||||
EmoticonAutocomplete,
|
||||
Toolbar,
|
||||
createEmoticonElement,
|
||||
getAutocompleteQuery,
|
||||
getPrevWorldRange,
|
||||
htmlToEditorInput,
|
||||
plainToEditorInput,
|
||||
moveCursor,
|
||||
toMatrixCustomHTML,
|
||||
toPlainText,
|
||||
trimCustomHtml,
|
||||
useEditor,
|
||||
} from '$components/editor';
|
||||
import { useSetting } from '$state/hooks/settings';
|
||||
import { settingsAtom } from '$state/settings';
|
||||
import { UseStateProvider } from '$components/UseStateProvider';
|
||||
import { EmojiBoard } from '$components/emoji-board';
|
||||
import { mobileOrTablet } from '$utils/user-agent';
|
||||
import * as css from './UploadDescriptionEditor.css';
|
||||
|
||||
type DescriptionEditorProps = {
|
||||
value?: string | any;
|
||||
isSaving?: boolean;
|
||||
imagePackRooms?: any[];
|
||||
onSave: (plaintext: string, htmlContent: string) => void;
|
||||
onCancel: () => void;
|
||||
};
|
||||
|
||||
export function DescriptionEditor({
|
||||
value,
|
||||
isSaving,
|
||||
imagePackRooms,
|
||||
onSave,
|
||||
onCancel,
|
||||
}: DescriptionEditorProps) {
|
||||
const editor = useEditor();
|
||||
const [enterForNewline] = useSetting(settingsAtom, 'enterForNewline');
|
||||
const [isMarkdown] = useSetting(settingsAtom, 'isMarkdown');
|
||||
const [toolbar, setToolbar] = useState(false);
|
||||
|
||||
const [autocompleteQuery, setAutocompleteQuery] =
|
||||
useState<AutocompleteQuery<AutocompletePrefix>>();
|
||||
|
||||
const prevValue = useRef(value);
|
||||
const initialized = useRef(false);
|
||||
const handleSave = useCallback(() => {
|
||||
const plainText = toPlainText(editor.children, isMarkdown).trim();
|
||||
|
||||
const customHtml = trimCustomHtml(
|
||||
toMatrixCustomHTML(editor.children, {
|
||||
allowTextFormatting: true,
|
||||
allowBlockMarkdown: isMarkdown,
|
||||
allowInlineMarkdown: isMarkdown,
|
||||
})
|
||||
);
|
||||
|
||||
onSave(plainText, customHtml || plainText);
|
||||
}, [editor, isMarkdown, onSave]);
|
||||
|
||||
useEffect(() => {
|
||||
const valueChanged = prevValue.current !== value;
|
||||
const isFirstValidLoad = !initialized.current && value !== undefined;
|
||||
|
||||
if (valueChanged || isFirstValidLoad) {
|
||||
prevValue.current = value;
|
||||
|
||||
let normalizedValue = value;
|
||||
if (
|
||||
typeof normalizedValue === 'object' &&
|
||||
normalizedValue !== null &&
|
||||
'formatted_body' in normalizedValue
|
||||
) {
|
||||
normalizedValue = normalizedValue.formatted_body;
|
||||
}
|
||||
|
||||
const safeValue = typeof normalizedValue === 'string' ? normalizedValue : '';
|
||||
|
||||
const incomingPlainText = toPlainText(
|
||||
htmlToEditorInput(safeValue, isMarkdown),
|
||||
isMarkdown
|
||||
).trim();
|
||||
const currentPlainText = toPlainText(editor.children, isMarkdown).trim();
|
||||
|
||||
if (currentPlainText === incomingPlainText && initialized.current) return;
|
||||
|
||||
const isLikelyHtml = safeValue.includes('<') || safeValue.includes('>');
|
||||
const initialValue = isLikelyHtml
|
||||
? htmlToEditorInput(safeValue, isMarkdown)
|
||||
: plainToEditorInput(safeValue, isMarkdown);
|
||||
|
||||
editor.children = initialValue;
|
||||
Editor.normalize(editor, { force: true });
|
||||
Transforms.select(editor, Editor.start(editor, []));
|
||||
|
||||
initialized.current = true;
|
||||
}
|
||||
}, [value, editor, isMarkdown]);
|
||||
|
||||
const handleKeyDown: KeyboardEventHandler = useCallback(
|
||||
(evt) => {
|
||||
if (isKeyHotkey('mod+enter', evt) || (!enterForNewline && isKeyHotkey('enter', evt))) {
|
||||
evt.preventDefault();
|
||||
handleSave();
|
||||
}
|
||||
},
|
||||
[handleSave, enterForNewline]
|
||||
);
|
||||
|
||||
const handleKeyUp: KeyboardEventHandler = useCallback(
|
||||
(evt) => {
|
||||
if (isKeyHotkey('escape', evt)) {
|
||||
evt.preventDefault();
|
||||
onCancel();
|
||||
return;
|
||||
}
|
||||
const prevWordRange = getPrevWorldRange(editor);
|
||||
const query = prevWordRange
|
||||
? getAutocompleteQuery(editor, prevWordRange, [AutocompletePrefix.Emoticon])
|
||||
: undefined;
|
||||
setAutocompleteQuery(query);
|
||||
},
|
||||
[editor, onCancel]
|
||||
);
|
||||
|
||||
const handleCloseAutocomplete = useCallback(() => {
|
||||
ReactEditor.focus(editor);
|
||||
setAutocompleteQuery(undefined);
|
||||
}, [editor]);
|
||||
|
||||
const handleEmoticonSelect = (key: string, shortcode: string) => {
|
||||
editor.insertNode(createEmoticonElement(key, shortcode));
|
||||
moveCursor(editor);
|
||||
};
|
||||
|
||||
return (
|
||||
<Box direction="Column" gap="100">
|
||||
<Box
|
||||
className={css.DescriptionEditorContainer}
|
||||
direction="Column"
|
||||
style={{ position: 'relative' }}
|
||||
>
|
||||
{autocompleteQuery?.prefix === AutocompletePrefix.Emoticon && (
|
||||
<EmoticonAutocomplete
|
||||
imagePackRooms={imagePackRooms || []}
|
||||
editor={editor}
|
||||
query={autocompleteQuery}
|
||||
requestClose={handleCloseAutocomplete}
|
||||
/>
|
||||
)}
|
||||
<CustomEditor
|
||||
editor={editor}
|
||||
placeholder="File Description..."
|
||||
onKeyDown={handleKeyDown}
|
||||
onKeyUp={handleKeyUp}
|
||||
maxHeight="200px"
|
||||
variant="Background"
|
||||
bottom={
|
||||
<Box direction="Column" style={{ backgroundColor: 'var(--sable-bg-container)' }}>
|
||||
<Box
|
||||
style={{ padding: config.space.S200, paddingTop: 0 }}
|
||||
alignItems="End"
|
||||
justifyContent="SpaceBetween"
|
||||
gap="100"
|
||||
>
|
||||
<Box gap="200">
|
||||
<Box gap="200" alignItems="Center">
|
||||
<Chip
|
||||
onClick={handleSave}
|
||||
variant="Primary"
|
||||
radii="Pill"
|
||||
outlined
|
||||
before={
|
||||
isSaving ? <Spinner variant="Primary" fill="Soft" size="100" /> : undefined
|
||||
}
|
||||
>
|
||||
<Text size="B300">{isSaving ? 'Saving' : 'Save'}</Text>
|
||||
</Chip>
|
||||
</Box>
|
||||
<Box gap="200" alignItems="Center">
|
||||
<Chip
|
||||
onClick={onCancel}
|
||||
variant="Warning"
|
||||
radii="Pill"
|
||||
outlined
|
||||
before={
|
||||
isSaving ? <Spinner variant="Primary" fill="Soft" size="100" /> : undefined
|
||||
}
|
||||
>
|
||||
<Text size="B300">Cancel</Text>
|
||||
</Chip>
|
||||
</Box>
|
||||
</Box>
|
||||
<Box gap="Inherit">
|
||||
<IconButton
|
||||
variant="Background"
|
||||
size="300"
|
||||
radii="300"
|
||||
onClick={() => setToolbar(!toolbar)}
|
||||
>
|
||||
<Icon size="400" src={toolbar ? Icons.AlphabetUnderline : Icons.Alphabet} />
|
||||
</IconButton>
|
||||
<UseStateProvider initial={undefined}>
|
||||
{(anchor: RectCords | undefined, setAnchor) => (
|
||||
<PopOut
|
||||
anchor={anchor}
|
||||
alignOffset={-8}
|
||||
position="Top"
|
||||
align="End"
|
||||
content={
|
||||
<EmojiBoard
|
||||
imagePackRooms={imagePackRooms ?? []}
|
||||
returnFocusOnDeactivate={false}
|
||||
onEmojiSelect={handleEmoticonSelect}
|
||||
onCustomEmojiSelect={handleEmoticonSelect}
|
||||
requestClose={() =>
|
||||
setAnchor((v) => {
|
||||
if (v) {
|
||||
if (!mobileOrTablet()) ReactEditor.focus(editor);
|
||||
return undefined;
|
||||
}
|
||||
return v;
|
||||
})
|
||||
}
|
||||
/>
|
||||
}
|
||||
>
|
||||
<IconButton
|
||||
aria-pressed={anchor !== undefined}
|
||||
variant="Background"
|
||||
size="300"
|
||||
radii="300"
|
||||
onClick={(evt) => setAnchor(evt.currentTarget.getBoundingClientRect())}
|
||||
>
|
||||
<Icon size="400" src={Icons.Smile} filled={anchor !== undefined} />
|
||||
</IconButton>
|
||||
</PopOut>
|
||||
)}
|
||||
</UseStateProvider>
|
||||
</Box>
|
||||
</Box>
|
||||
{toolbar && (
|
||||
<Box direction="Column">
|
||||
<Line variant="Surface" size="300" />
|
||||
<Toolbar />
|
||||
</Box>
|
||||
)}
|
||||
</Box>
|
||||
}
|
||||
/>
|
||||
</Box>
|
||||
</Box>
|
||||
);
|
||||
}
|
||||
@@ -6,13 +6,10 @@ export const UrlPreview = as<'div'>(({ className, ...props }, ref) => (
|
||||
<Box shrink="No" className={classNames(css.UrlPreview, className)} {...props} ref={ref} />
|
||||
));
|
||||
|
||||
export const UrlPreviewImg = as<'img'>(({ className, alt, ...props }, ref) => (
|
||||
<img className={classNames(css.UrlPreviewImg, className)} alt={alt} {...props} ref={ref} />
|
||||
));
|
||||
|
||||
export const UrlPreviewContent = as<'div'>(({ className, ...props }, ref) => (
|
||||
<Box
|
||||
grow="Yes"
|
||||
shrink="No"
|
||||
direction="Column"
|
||||
gap="100"
|
||||
className={classNames(css.UrlPreviewContent, className)}
|
||||
|
||||
@@ -1,5 +1,14 @@
|
||||
import { style } from '@vanilla-extract/css';
|
||||
import { recipe } from '@vanilla-extract/recipes';
|
||||
import { DefaultReset, color, toRem } from 'folds';
|
||||
import { DefaultReset, color, config, toRem } from 'folds';
|
||||
|
||||
export const UrlPreviewAudio = style([
|
||||
DefaultReset,
|
||||
{
|
||||
padding: config.space.S300,
|
||||
paddingTop: 0,
|
||||
},
|
||||
]);
|
||||
|
||||
export const UrlPreviewHolderGradient = recipe({
|
||||
base: [
|
||||
|
||||
@@ -10,7 +10,10 @@ import {
|
||||
import { mxcUrlToHttp } from '$utils/matrix';
|
||||
import { useMediaAuthentication } from '$hooks/useMediaAuthentication';
|
||||
import * as css from './UrlPreviewCard.css';
|
||||
import { UrlPreview, UrlPreviewContent, UrlPreviewDescription, UrlPreviewImg } from './UrlPreview';
|
||||
import { UrlPreview, UrlPreviewContent, UrlPreviewDescription } from './UrlPreview';
|
||||
import { AudioContent, ImageContent, VideoContent } from '../message';
|
||||
import { Image, MediaControl, Video } from '../media';
|
||||
import { ImageViewer } from '../image-viewer';
|
||||
|
||||
const linkStyles = { color: color.Success.Main };
|
||||
|
||||
@@ -49,23 +52,77 @@ export const UrlPreviewCard = as<'div', { url: string; ts: number; mediaType?: s
|
||||
);
|
||||
|
||||
return (
|
||||
<>
|
||||
{imgUrl && (
|
||||
<UrlPreviewImg
|
||||
src={imgUrl}
|
||||
alt="Media"
|
||||
<Box
|
||||
grow="Yes"
|
||||
direction={prev['og:video'] ? 'ColumnReverse' : 'Row'}
|
||||
style={{
|
||||
display: 'flex',
|
||||
alignItems: 'center',
|
||||
overflow: 'hidden',
|
||||
width: '100%',
|
||||
}}
|
||||
>
|
||||
{(prev['og:video'] && (
|
||||
<VideoContent
|
||||
style={{
|
||||
width: 'auto',
|
||||
height: 'auto',
|
||||
maxWidth: '100%',
|
||||
maxHeight: '100px',
|
||||
borderRadius: '8px',
|
||||
objectFit: 'contain',
|
||||
display: 'block',
|
||||
aspectRatio:
|
||||
((prev['og:video:width'] as number) ?? 1) /
|
||||
((prev['og:video:height'] as number) ?? 1),
|
||||
}}
|
||||
body={prev['og:title']}
|
||||
info={{}}
|
||||
url={prev['og:video'] as string}
|
||||
mimeType={(prev['og:video:type'] as string) ?? ''}
|
||||
renderVideo={(vidProps) => <Video style={{ objectFit: 'contain' }} {...vidProps} />}
|
||||
renderThumbnail={() => <Image src={imgUrl ?? undefined} />}
|
||||
/>
|
||||
)}
|
||||
<UrlPreviewContent>
|
||||
)) ||
|
||||
(prev['og:image'] && (
|
||||
<Box style={{ flexShrink: 0, height: '100px' }}>
|
||||
{' '}
|
||||
<ImageContent
|
||||
style={{
|
||||
height: '100%',
|
||||
aspectRatio: (prev['og:image:width'] ?? 1) / (prev['og:image:height'] ?? 1),
|
||||
position: 'relative',
|
||||
width: 'auto',
|
||||
}}
|
||||
autoPlay
|
||||
body={prev['og:title']}
|
||||
url={prev['og:image']}
|
||||
renderViewer={(p) => <ImageViewer {...p} />}
|
||||
renderImage={(p) => (
|
||||
<Image
|
||||
{...p}
|
||||
style={{
|
||||
height: '100%',
|
||||
width: 'auto',
|
||||
objectFit: 'contain',
|
||||
}}
|
||||
/>
|
||||
)}
|
||||
/>
|
||||
</Box>
|
||||
)) ||
|
||||
(prev['og:audio'] && (
|
||||
<Box className={css.UrlPreviewAudio} style={{ flexShrink: 0 }}>
|
||||
<AudioContent
|
||||
url={(prev['og:audio'] as string) ?? ''}
|
||||
mimeType={(prev['og:audio:type'] as string) ?? ''}
|
||||
info={{}}
|
||||
renderMediaControl={(p) => <MediaControl {...p} />}
|
||||
/>
|
||||
</Box>
|
||||
))}
|
||||
<UrlPreviewContent
|
||||
style={{
|
||||
flex: 1,
|
||||
minWidth: 0,
|
||||
display: 'flex',
|
||||
flexDirection: 'column',
|
||||
justifyContent: 'center',
|
||||
}}
|
||||
>
|
||||
<Text
|
||||
style={linkStyles}
|
||||
truncate
|
||||
@@ -90,7 +147,7 @@ export const UrlPreviewCard = as<'div', { url: string; ts: number; mediaType?: s
|
||||
</Text>
|
||||
)}
|
||||
</UrlPreviewContent>
|
||||
</>
|
||||
</Box>
|
||||
);
|
||||
};
|
||||
|
||||
|
||||
@@ -332,7 +332,7 @@ export function MutualRoomsChip({ userId }: { userId: string }) {
|
||||
)}
|
||||
/>
|
||||
) : (
|
||||
<RoomIcon size="100" joinRule={room.getJoinRule()} />
|
||||
<RoomIcon size="100" joinRule={room.getJoinRule()} roomType={room.getType()} />
|
||||
)}
|
||||
</Avatar>
|
||||
}
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
import { useState } from 'react';
|
||||
import { useMemo, useState } from 'react';
|
||||
import {
|
||||
Avatar,
|
||||
Box,
|
||||
@@ -27,6 +27,7 @@ import { useBlobCache } from '$hooks/useBlobCache';
|
||||
import { ImageViewer } from '$components/image-viewer';
|
||||
import { AvatarPresence, PresenceBadge } from '$components/presence';
|
||||
import { UserAvatar } from '$components/user-avatar';
|
||||
import { ClientSideHoverFreeze } from '$components/ClientSideHoverFreeze';
|
||||
import * as css from './styles.css';
|
||||
|
||||
type UserHeroProps = {
|
||||
@@ -34,8 +35,9 @@ type UserHeroProps = {
|
||||
avatarUrl?: string;
|
||||
bannerUrl?: string;
|
||||
presence?: UserPresence;
|
||||
autoplayGifs?: boolean;
|
||||
};
|
||||
export function UserHero({ userId, avatarUrl, bannerUrl, presence }: UserHeroProps) {
|
||||
export function UserHero({ userId, avatarUrl, bannerUrl, presence, autoplayGifs }: UserHeroProps) {
|
||||
const [viewAvatar, setViewAvatar] = useState<string>();
|
||||
const [isFullStatus, setIsFullStatus] = useState(false);
|
||||
|
||||
@@ -45,6 +47,25 @@ export function UserHero({ userId, avatarUrl, bannerUrl, presence }: UserHeroPro
|
||||
const coverUrl = cachedBannerUrl || cachedAvatarUrl;
|
||||
const isFallbackCover = !cachedBannerUrl && !!cachedAvatarUrl;
|
||||
|
||||
const isAnimated = useMemo(() => {
|
||||
if (!coverUrl) return false;
|
||||
const url = coverUrl.toLowerCase();
|
||||
const isStatic = url.endsWith('.jpg') || url.endsWith('.jpeg') || url.endsWith('.png');
|
||||
|
||||
return !isStatic || url.includes('gif') || url.includes('webp');
|
||||
}, [coverUrl]);
|
||||
|
||||
const bannerClasses = classNames(css.UserHeroCover, isFallbackCover && css.UserHeroCoverFallback);
|
||||
|
||||
const renderCoverImage = () => (
|
||||
<img
|
||||
className={classNames(css.UserHeroCover, isFallbackCover && css.UserHeroCoverFallback)}
|
||||
src={coverUrl}
|
||||
alt={`${userId} cover`}
|
||||
draggable="false"
|
||||
/>
|
||||
);
|
||||
|
||||
const status = presence?.status;
|
||||
const isExpandable = (status?.length ?? 0) > 70;
|
||||
|
||||
@@ -57,12 +78,15 @@ export function UserHero({ userId, avatarUrl, bannerUrl, presence }: UserHeroPro
|
||||
}}
|
||||
>
|
||||
{coverUrl && (
|
||||
<img
|
||||
className={classNames(css.UserHeroCover, isFallbackCover && css.UserHeroCoverFallback)}
|
||||
src={coverUrl}
|
||||
alt={`${userId} cover`}
|
||||
draggable="false"
|
||||
/>
|
||||
<>
|
||||
{isAnimated && !autoplayGifs ? (
|
||||
<ClientSideHoverFreeze src={coverUrl} className={bannerClasses}>
|
||||
{renderCoverImage()}
|
||||
</ClientSideHoverFreeze>
|
||||
) : (
|
||||
renderCoverImage()
|
||||
)}
|
||||
</>
|
||||
)}
|
||||
</div>
|
||||
<Box direction="Row" className={css.UserHeroAvatarStatusContainer}>
|
||||
|
||||
@@ -31,8 +31,9 @@ import {
|
||||
} from '$plugins/react-custom-html-parser';
|
||||
import { useSpoilerClickHandler } from '$hooks/useSpoilerClickHandler';
|
||||
import { RenderBody } from '$components/message';
|
||||
import { getSettings } from '$state/settings';
|
||||
import { getSettings, settingsAtom } from '$state/settings';
|
||||
import { filterPronounsByLanguage } from '$utils/pronouns';
|
||||
import { useSetting } from '$state/hooks/settings';
|
||||
import { CreatorChip } from './CreatorChip';
|
||||
import { UserInviteAlert, UserBanAlert, UserModeration, UserKickAlert } from './UserModeration';
|
||||
import { PowerChip } from './PowerChip';
|
||||
@@ -50,6 +51,8 @@ const KNOWN_KEYS = [
|
||||
'moe.sable.app.name_color',
|
||||
'avatar_url',
|
||||
'displayname',
|
||||
'kitty.meow.has_cats',
|
||||
'kitty.meow.is_cat',
|
||||
];
|
||||
|
||||
type UserExtendedSectionProps = {
|
||||
@@ -69,6 +72,18 @@ function UserExtendedSection({
|
||||
};
|
||||
const [showMore, setShowMore] = useState(false);
|
||||
|
||||
const [renderAnimals] = useSetting(settingsAtom, 'renderAnimals');
|
||||
const isCat = profile.isCat === true;
|
||||
const hasCats = profile.hasCats === true;
|
||||
|
||||
const catStatusText = useMemo(() => {
|
||||
if (!renderAnimals) return null;
|
||||
if (isCat && hasCats) return 'Cat with cats—needs pets & love!';
|
||||
if (isCat) return 'Is a cat—give pets & love!';
|
||||
if (hasCats) return 'Has cats—send love!';
|
||||
return null;
|
||||
}, [renderAnimals, isCat, hasCats]);
|
||||
|
||||
const renderValue = (val: any) => {
|
||||
if (val === null || val === undefined) return 'n/a';
|
||||
if (typeof val === 'boolean') return val ? 'Yes' : 'No';
|
||||
@@ -152,6 +167,14 @@ function UserExtendedSection({
|
||||
</Text>
|
||||
</Box>
|
||||
)}
|
||||
{catStatusText && (
|
||||
<Box alignItems="Center" gap="100">
|
||||
<Icon size="50" src={Icons.Heart} style={{ opacity: 0.5 }} />
|
||||
<Text size="T200" priority="400">
|
||||
{catStatusText}
|
||||
</Text>
|
||||
</Box>
|
||||
)}
|
||||
</Box>
|
||||
)}
|
||||
|
||||
@@ -236,6 +259,8 @@ export function UserRoomProfile({ userId, initialProfile }: UserRoomProfileProps
|
||||
const ignoredUsers = useIgnoredUsers();
|
||||
const ignored = ignoredUsers.includes(userId);
|
||||
|
||||
const [autoplayGifs] = useSetting(settingsAtom, 'autoplayGifs');
|
||||
|
||||
const room = useRoom();
|
||||
const powerLevels = usePowerLevels(room);
|
||||
const creators = useRoomCreators(room);
|
||||
@@ -325,6 +350,7 @@ export function UserRoomProfile({ userId, initialProfile }: UserRoomProfileProps
|
||||
avatarUrl={avatarUrl}
|
||||
bannerUrl={bannerHttpUrl ?? undefined}
|
||||
presence={presence && presence.lastActiveTs !== 0 ? presence : undefined}
|
||||
autoplayGifs={autoplayGifs}
|
||||
/>
|
||||
<Box direction="Column" gap="300" style={{ padding: config.space.S400 }}>
|
||||
<Box direction="Column" gap="200">
|
||||
|
||||
@@ -287,7 +287,11 @@ export function AddExistingModal({ parentId, space, requestClose }: AddExistingM
|
||||
)}
|
||||
/>
|
||||
) : (
|
||||
<RoomIcon size="200" joinRule={room.getJoinRule()} />
|
||||
<RoomIcon
|
||||
size="200"
|
||||
joinRule={room.getJoinRule()}
|
||||
roomType={room.getType()}
|
||||
/>
|
||||
)}
|
||||
</Avatar>
|
||||
}
|
||||
|
||||
@@ -0,0 +1,168 @@
|
||||
import { Box, Chip, Icon, IconButton, Icons, Text, Tooltip, TooltipProvider } from 'folds';
|
||||
import { useState } from 'react';
|
||||
import { StatusDivider } from './components';
|
||||
import { CallEmbed, useCallControlState } from '../../plugins/call';
|
||||
|
||||
type MicrophoneButtonProps = {
|
||||
enabled: boolean;
|
||||
onToggle: () => Promise<unknown>;
|
||||
};
|
||||
function MicrophoneButton({ enabled, onToggle }: MicrophoneButtonProps) {
|
||||
return (
|
||||
<TooltipProvider
|
||||
position="Top"
|
||||
tooltip={
|
||||
<Tooltip>
|
||||
<Text size="T200">{enabled ? 'Turn Off Microphone' : 'Turn On Microphone'}</Text>
|
||||
</Tooltip>
|
||||
}
|
||||
>
|
||||
{(anchorRef) => (
|
||||
<IconButton
|
||||
ref={anchorRef}
|
||||
variant={enabled ? 'Background' : 'Warning'}
|
||||
fill="Soft"
|
||||
radii="300"
|
||||
size="300"
|
||||
onClick={() => onToggle()}
|
||||
outlined={!enabled}
|
||||
>
|
||||
<Icon size="100" src={enabled ? Icons.Mic : Icons.MicMute} filled={!enabled} />
|
||||
</IconButton>
|
||||
)}
|
||||
</TooltipProvider>
|
||||
);
|
||||
}
|
||||
|
||||
type SoundButtonProps = {
|
||||
enabled: boolean;
|
||||
onToggle: () => void;
|
||||
};
|
||||
function SoundButton({ enabled, onToggle }: SoundButtonProps) {
|
||||
return (
|
||||
<TooltipProvider
|
||||
position="Top"
|
||||
tooltip={
|
||||
<Tooltip>
|
||||
<Text size="T200">{enabled ? 'Turn Off Sound' : 'Turn On Sound'}</Text>
|
||||
</Tooltip>
|
||||
}
|
||||
>
|
||||
{(anchorRef) => (
|
||||
<IconButton
|
||||
ref={anchorRef}
|
||||
variant={enabled ? 'Background' : 'Warning'}
|
||||
fill="Soft"
|
||||
radii="300"
|
||||
size="300"
|
||||
onClick={() => onToggle()}
|
||||
outlined={!enabled}
|
||||
>
|
||||
<Icon
|
||||
size="100"
|
||||
src={enabled ? Icons.Headphone : Icons.HeadphoneMute}
|
||||
filled={!enabled}
|
||||
/>
|
||||
</IconButton>
|
||||
)}
|
||||
</TooltipProvider>
|
||||
);
|
||||
}
|
||||
|
||||
type VideoButtonProps = {
|
||||
enabled: boolean;
|
||||
onToggle: () => Promise<unknown>;
|
||||
};
|
||||
function VideoButton({ enabled, onToggle }: VideoButtonProps) {
|
||||
return (
|
||||
<TooltipProvider
|
||||
position="Top"
|
||||
tooltip={
|
||||
<Tooltip>
|
||||
<Text size="T200">{enabled ? 'Stop Camera' : 'Start Camera'}</Text>
|
||||
</Tooltip>
|
||||
}
|
||||
>
|
||||
{(anchorRef) => (
|
||||
<IconButton
|
||||
ref={anchorRef}
|
||||
variant={enabled ? 'Success' : 'Background'}
|
||||
fill="Soft"
|
||||
radii="300"
|
||||
size="300"
|
||||
onClick={() => onToggle()}
|
||||
outlined={enabled}
|
||||
>
|
||||
<Icon
|
||||
size="100"
|
||||
src={enabled ? Icons.VideoCamera : Icons.VideoCameraMute}
|
||||
filled={enabled}
|
||||
/>
|
||||
</IconButton>
|
||||
)}
|
||||
</TooltipProvider>
|
||||
);
|
||||
}
|
||||
|
||||
function ScreenShareButton() {
|
||||
const [enabled, setEnabled] = useState(false);
|
||||
|
||||
return (
|
||||
<TooltipProvider
|
||||
position="Top"
|
||||
tooltip={
|
||||
<Tooltip>
|
||||
<Text size="T200">{enabled ? 'Stop Screenshare' : 'Start Screenshare'}</Text>
|
||||
</Tooltip>
|
||||
}
|
||||
>
|
||||
{(anchorRef) => (
|
||||
<IconButton
|
||||
ref={anchorRef}
|
||||
variant={enabled ? 'Success' : 'Background'}
|
||||
fill="Soft"
|
||||
radii="300"
|
||||
size="300"
|
||||
onClick={() => setEnabled(!enabled)}
|
||||
outlined={enabled}
|
||||
>
|
||||
<Icon size="100" src={Icons.ScreenShare} filled={enabled} />
|
||||
</IconButton>
|
||||
)}
|
||||
</TooltipProvider>
|
||||
);
|
||||
}
|
||||
|
||||
export function CallControl({ callEmbed }: { callEmbed: CallEmbed }) {
|
||||
const { microphone, video, sound } = useCallControlState(callEmbed.control);
|
||||
|
||||
return (
|
||||
<Box shrink="No" alignItems="Center" gap="300">
|
||||
<Box alignItems="Inherit" gap="200">
|
||||
<MicrophoneButton
|
||||
enabled={microphone}
|
||||
onToggle={() => callEmbed.control.toggleMicrophone()}
|
||||
/>
|
||||
<SoundButton enabled={sound} onToggle={() => callEmbed.control.toggleSound()} />
|
||||
</Box>
|
||||
<StatusDivider />
|
||||
<Box alignItems="Inherit" gap="200">
|
||||
<VideoButton enabled={video} onToggle={() => callEmbed.control.toggleVideo()} />
|
||||
{false && <ScreenShareButton />}
|
||||
</Box>
|
||||
<StatusDivider />
|
||||
<Chip
|
||||
variant="Critical"
|
||||
radii="300"
|
||||
fill="Soft"
|
||||
before={<Icon size="50" src={Icons.PhoneDown} filled />}
|
||||
outlined
|
||||
onClick={() => callEmbed.hangup()}
|
||||
>
|
||||
<Text as="span" size="L400">
|
||||
End
|
||||
</Text>
|
||||
</Chip>
|
||||
</Box>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,54 @@
|
||||
import { Room } from 'matrix-js-sdk';
|
||||
import { Chip, Text } from 'folds';
|
||||
import { useAtomValue } from 'jotai';
|
||||
import { useRoomName } from '../../hooks/useRoomMeta';
|
||||
import { RoomIcon } from '../../components/room-avatar';
|
||||
import { roomToParentsAtom } from '../../state/room/roomToParents';
|
||||
import { getAllParents, guessPerfectParent } from '../../utils/room';
|
||||
import { useOrphanSpaces } from '../../state/hooks/roomList';
|
||||
import { useMatrixClient } from '../../hooks/useMatrixClient';
|
||||
import { allRoomsAtom } from '../../state/room-list/roomList';
|
||||
import { mDirectAtom } from '../../state/mDirectList';
|
||||
import { useAllJoinedRoomsSet, useGetRoom } from '../../hooks/useGetRoom';
|
||||
import { useRoomNavigate } from '../../hooks/useRoomNavigate';
|
||||
|
||||
type CallRoomNameProps = {
|
||||
room: Room;
|
||||
};
|
||||
export function CallRoomName({ room }: CallRoomNameProps) {
|
||||
const mx = useMatrixClient();
|
||||
const name = useRoomName(room);
|
||||
const roomToParents = useAtomValue(roomToParentsAtom);
|
||||
const orphanSpaces = useOrphanSpaces(mx, allRoomsAtom, roomToParents);
|
||||
const mDirects = useAtomValue(mDirectAtom);
|
||||
const dm = mDirects.has(room.roomId);
|
||||
|
||||
const allRoomsSet = useAllJoinedRoomsSet();
|
||||
const getRoom = useGetRoom(allRoomsSet);
|
||||
|
||||
const allParents = getAllParents(roomToParents, room.roomId);
|
||||
const orphanParents = allParents && orphanSpaces.filter((o) => allParents.has(o));
|
||||
const perfectOrphanParent = orphanParents && guessPerfectParent(mx, room.roomId, orphanParents);
|
||||
|
||||
const { navigateRoom } = useRoomNavigate();
|
||||
|
||||
return (
|
||||
<Chip
|
||||
variant="Background"
|
||||
radii="Pill"
|
||||
before={
|
||||
<RoomIcon size="200" joinRule={room.getJoinRule()} roomType={room.getType()} filled />
|
||||
}
|
||||
onClick={() => navigateRoom(room.roomId)}
|
||||
>
|
||||
<Text size="L400" truncate>
|
||||
{name}
|
||||
{!dm && perfectOrphanParent && (
|
||||
<Text as="span" size="T200" priority="300">
|
||||
{' •'} <b>{getRoom(perfectOrphanParent)?.name ?? perfectOrphanParent}</b>
|
||||
</Text>
|
||||
)}
|
||||
</Text>
|
||||
</Chip>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,51 @@
|
||||
import { Box, Spinner } from 'folds';
|
||||
import classNames from 'classnames';
|
||||
import { LiveChip } from './LiveChip';
|
||||
import * as css from './styles.css';
|
||||
import { CallRoomName } from './CallRoomName';
|
||||
import { CallControl } from './CallControl';
|
||||
import { ContainerColor } from '../../styles/ContainerColor.css';
|
||||
import { useCallMembers, useCallSession } from '../../hooks/useCall';
|
||||
import { ScreenSize, useScreenSize } from '../../hooks/useScreenSize';
|
||||
import { MemberGlance } from './MemberGlance';
|
||||
import { StatusDivider } from './components';
|
||||
import { CallEmbed } from '../../plugins/call/CallEmbed';
|
||||
import { useCallJoined } from '../../hooks/useCallEmbed';
|
||||
|
||||
type CallStatusProps = {
|
||||
callEmbed: CallEmbed;
|
||||
};
|
||||
export function CallStatus({ callEmbed }: CallStatusProps) {
|
||||
const { room } = callEmbed;
|
||||
|
||||
const callSession = useCallSession(room);
|
||||
const callMembers = useCallMembers(room, callSession);
|
||||
const screenSize = useScreenSize();
|
||||
const callJoined = useCallJoined(callEmbed);
|
||||
|
||||
return (
|
||||
<Box
|
||||
className={classNames(css.CallStatus, ContainerColor({ variant: 'Background' }))}
|
||||
shrink="No"
|
||||
gap="400"
|
||||
alignItems="Center"
|
||||
direction={screenSize === ScreenSize.Mobile ? 'Column' : 'Row'}
|
||||
>
|
||||
<Box grow="Yes" alignItems="Inherit" gap="200">
|
||||
{callJoined && callMembers.length > 0 ? (
|
||||
<Box shrink="No" gap="Inherit" alignItems="Inherit">
|
||||
<MemberGlance room={room} members={callMembers} />
|
||||
<LiveChip count={callMembers.length} room={room} members={callMembers} />
|
||||
</Box>
|
||||
) : (
|
||||
<Spinner variant="Secondary" size="200" />
|
||||
)}
|
||||
<StatusDivider />
|
||||
<CallRoomName room={room} />
|
||||
</Box>
|
||||
<Box shrink="No" alignItems="Inherit" gap="Inherit">
|
||||
<CallControl callEmbed={callEmbed} />
|
||||
</Box>
|
||||
</Box>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,137 @@
|
||||
import { MouseEventHandler, useState } from 'react';
|
||||
import {
|
||||
Avatar,
|
||||
Badge,
|
||||
Box,
|
||||
Chip,
|
||||
config,
|
||||
Icon,
|
||||
Icons,
|
||||
Menu,
|
||||
MenuItem,
|
||||
PopOut,
|
||||
RectCords,
|
||||
Scroll,
|
||||
Text,
|
||||
toRem,
|
||||
} from 'folds';
|
||||
import { CallMembership } from 'matrix-js-sdk/lib/matrixrtc/CallMembership';
|
||||
import FocusTrap from 'focus-trap-react';
|
||||
import { Room } from 'matrix-js-sdk';
|
||||
import * as css from './styles.css';
|
||||
import { stopPropagation } from '../../utils/keyboard';
|
||||
import { getMemberAvatarMxc, getMemberDisplayName } from '../../utils/room';
|
||||
import { getMxIdLocalPart, mxcUrlToHttp } from '../../utils/matrix';
|
||||
import { useMatrixClient } from '../../hooks/useMatrixClient';
|
||||
import { useMediaAuthentication } from '../../hooks/useMediaAuthentication';
|
||||
import { UserAvatar } from '../../components/user-avatar';
|
||||
import { useOpenUserRoomProfile } from '../../state/hooks/userRoomProfile';
|
||||
import { getMouseEventCords } from '../../utils/dom';
|
||||
|
||||
type LiveChipProps = {
|
||||
room: Room;
|
||||
members: CallMembership[];
|
||||
count: number;
|
||||
};
|
||||
export function LiveChip({ count, room, members }: LiveChipProps) {
|
||||
const mx = useMatrixClient();
|
||||
const useAuthentication = useMediaAuthentication();
|
||||
const openUserProfile = useOpenUserRoomProfile();
|
||||
|
||||
const [cords, setCords] = useState<RectCords>();
|
||||
|
||||
const handleOpenMenu: MouseEventHandler<HTMLButtonElement> = (evt) => {
|
||||
setCords(evt.currentTarget.getBoundingClientRect());
|
||||
};
|
||||
|
||||
return (
|
||||
<PopOut
|
||||
anchor={cords}
|
||||
position="Top"
|
||||
align="Start"
|
||||
content={
|
||||
<FocusTrap
|
||||
focusTrapOptions={{
|
||||
initialFocus: false,
|
||||
onDeactivate: () => setCords(undefined),
|
||||
clickOutsideDeactivates: true,
|
||||
isKeyForward: (evt: KeyboardEvent) => evt.key === 'ArrowDown',
|
||||
isKeyBackward: (evt: KeyboardEvent) => evt.key === 'ArrowUp',
|
||||
escapeDeactivates: stopPropagation,
|
||||
}}
|
||||
>
|
||||
<Menu
|
||||
style={{
|
||||
maxHeight: '75vh',
|
||||
maxWidth: toRem(300),
|
||||
display: 'flex',
|
||||
}}
|
||||
>
|
||||
<Box grow="Yes">
|
||||
<Scroll size="0" hideTrack visibility="Hover">
|
||||
<Box direction="Column" style={{ padding: config.space.S100 }}>
|
||||
{members.map((callMember) => {
|
||||
const userId = callMember.sender;
|
||||
if (!userId) return null;
|
||||
const name =
|
||||
getMemberDisplayName(room, userId) ?? getMxIdLocalPart(userId) ?? userId;
|
||||
const avatarMxc = getMemberAvatarMxc(room, userId);
|
||||
const avatarUrl = avatarMxc
|
||||
? (mxcUrlToHttp(mx, avatarMxc, useAuthentication, 96, 96) ?? undefined)
|
||||
: undefined;
|
||||
|
||||
return (
|
||||
<MenuItem
|
||||
key={callMember.membershipID}
|
||||
size="400"
|
||||
variant="Surface"
|
||||
radii="300"
|
||||
style={{ paddingLeft: config.space.S200 }}
|
||||
onClick={(evt) =>
|
||||
openUserProfile(
|
||||
room.roomId,
|
||||
undefined,
|
||||
userId,
|
||||
getMouseEventCords(evt.nativeEvent),
|
||||
'Right'
|
||||
)
|
||||
}
|
||||
before={
|
||||
<Avatar size="200" radii="400">
|
||||
<UserAvatar
|
||||
userId={userId}
|
||||
src={avatarUrl}
|
||||
alt={name}
|
||||
renderFallback={() => <Icon size="50" src={Icons.User} filled />}
|
||||
/>
|
||||
</Avatar>
|
||||
}
|
||||
>
|
||||
<Text size="T300" truncate>
|
||||
{name}
|
||||
</Text>
|
||||
</MenuItem>
|
||||
);
|
||||
})}
|
||||
</Box>
|
||||
</Scroll>
|
||||
</Box>
|
||||
</Menu>
|
||||
</FocusTrap>
|
||||
}
|
||||
>
|
||||
<Chip
|
||||
variant="Surface"
|
||||
fill="Soft"
|
||||
before={<Badge variant="Critical" fill="Solid" size="200" />}
|
||||
after={<Icon size="50" src={cords ? Icons.ChevronBottom : Icons.ChevronTop} />}
|
||||
radii="Pill"
|
||||
onClick={handleOpenMenu}
|
||||
>
|
||||
<Text className={css.LiveChipText} as="span" size="L400">
|
||||
{count} Live
|
||||
</Text>
|
||||
</Chip>
|
||||
</PopOut>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,71 @@
|
||||
import { Box, config, Icon, Icons, Text } from 'folds';
|
||||
import { CallMembership } from 'matrix-js-sdk/lib/matrixrtc/CallMembership';
|
||||
import { Room } from 'matrix-js-sdk';
|
||||
import { UserAvatar } from '../../components/user-avatar';
|
||||
import { getMemberAvatarMxc, getMemberDisplayName } from '../../utils/room';
|
||||
import { getMxIdLocalPart, mxcUrlToHttp } from '../../utils/matrix';
|
||||
import { useMatrixClient } from '../../hooks/useMatrixClient';
|
||||
import { useMediaAuthentication } from '../../hooks/useMediaAuthentication';
|
||||
import { StackedAvatar } from '../../components/stacked-avatar';
|
||||
import { useOpenUserRoomProfile } from '../../state/hooks/userRoomProfile';
|
||||
import { getMouseEventCords } from '../../utils/dom';
|
||||
|
||||
type MemberGlanceProps = {
|
||||
room: Room;
|
||||
members: CallMembership[];
|
||||
max?: number;
|
||||
};
|
||||
export function MemberGlance({ room, members, max = 6 }: MemberGlanceProps) {
|
||||
const mx = useMatrixClient();
|
||||
const useAuthentication = useMediaAuthentication();
|
||||
const openUserProfile = useOpenUserRoomProfile();
|
||||
|
||||
const visibleMembers = members.slice(0, max);
|
||||
const remainingCount = max && members.length > max ? members.length - max : 0;
|
||||
|
||||
return (
|
||||
<Box alignItems="Center">
|
||||
{visibleMembers.map((callMember) => {
|
||||
const userId = callMember.sender;
|
||||
if (!userId) return null;
|
||||
const name = getMemberDisplayName(room, userId) ?? getMxIdLocalPart(userId) ?? userId;
|
||||
const avatarMxc = getMemberAvatarMxc(room, userId);
|
||||
const avatarUrl = avatarMxc
|
||||
? (mxcUrlToHttp(mx, avatarMxc, useAuthentication, 96, 96) ?? undefined)
|
||||
: undefined;
|
||||
|
||||
return (
|
||||
<StackedAvatar
|
||||
key={callMember.membershipID}
|
||||
title={name}
|
||||
as="button"
|
||||
variant="Background"
|
||||
size="200"
|
||||
radii="Pill"
|
||||
onClick={(evt) =>
|
||||
openUserProfile(
|
||||
room.roomId,
|
||||
undefined,
|
||||
userId,
|
||||
getMouseEventCords(evt.nativeEvent),
|
||||
'Top'
|
||||
)
|
||||
}
|
||||
>
|
||||
<UserAvatar
|
||||
userId={userId}
|
||||
src={avatarUrl}
|
||||
alt={name}
|
||||
renderFallback={() => <Icon size="50" src={Icons.User} filled />}
|
||||
/>
|
||||
</StackedAvatar>
|
||||
);
|
||||
})}
|
||||
{remainingCount > 0 && (
|
||||
<Text size="L400" style={{ paddingLeft: config.space.S100 }}>
|
||||
+{remainingCount}
|
||||
</Text>
|
||||
)}
|
||||
</Box>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,8 @@
|
||||
import { Line } from 'folds';
|
||||
import * as css from './styles.css';
|
||||
|
||||
export function StatusDivider() {
|
||||
return (
|
||||
<Line variant="Background" size="300" direction="Vertical" className={css.ControlDivider} />
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1 @@
|
||||
export * from './CallStatus';
|
||||
@@ -0,0 +1,17 @@
|
||||
import { style } from '@vanilla-extract/css';
|
||||
import { color, config, toRem } from 'folds';
|
||||
|
||||
export const LiveChipText = style({
|
||||
color: color.Critical.Main,
|
||||
});
|
||||
|
||||
export const CallStatus = style([
|
||||
{
|
||||
padding: `${toRem(6)} ${config.space.S200}`,
|
||||
borderTop: `${config.borderWidth.B300} solid ${color.Background.ContainerLine}`,
|
||||
},
|
||||
]);
|
||||
|
||||
export const ControlDivider = style({
|
||||
height: toRem(16),
|
||||
});
|
||||
@@ -0,0 +1,121 @@
|
||||
import { CallMembership, SessionMembershipData } from 'matrix-js-sdk/lib/matrixrtc/CallMembership';
|
||||
import { useState } from 'react';
|
||||
import { Avatar, Box, Icon, Icons, Text } from 'folds';
|
||||
import { useMatrixClient } from '../../hooks/useMatrixClient';
|
||||
import { useMediaAuthentication } from '../../hooks/useMediaAuthentication';
|
||||
import { useOpenUserRoomProfile } from '../../state/hooks/userRoomProfile';
|
||||
import { SequenceCard } from '../../components/sequence-card';
|
||||
import { getMemberAvatarMxc, getMemberDisplayName } from '../../utils/room';
|
||||
import { useRoom } from '../../hooks/useRoom';
|
||||
import { getMxIdLocalPart, mxcUrlToHttp } from '../../utils/matrix';
|
||||
import { UserAvatar } from '../../components/user-avatar';
|
||||
import { getMouseEventCords } from '../../utils/dom';
|
||||
import * as css from './styles.css';
|
||||
|
||||
interface MemberWithMembershipData {
|
||||
membershipData?: SessionMembershipData & {
|
||||
'm.call.intent': 'video' | 'audio';
|
||||
};
|
||||
}
|
||||
|
||||
type CallMemberCardProps = {
|
||||
member: CallMembership;
|
||||
};
|
||||
export function CallMemberCard({ member }: CallMemberCardProps) {
|
||||
const mx = useMatrixClient();
|
||||
const useAuthentication = useMediaAuthentication();
|
||||
const room = useRoom();
|
||||
|
||||
const openUserProfile = useOpenUserRoomProfile();
|
||||
|
||||
const userId = member.sender;
|
||||
if (!userId) return null;
|
||||
|
||||
const name = getMemberDisplayName(room, userId) ?? getMxIdLocalPart(userId) ?? userId;
|
||||
const avatarMxc = getMemberAvatarMxc(room, userId);
|
||||
const avatarUrl = avatarMxc
|
||||
? (mxcUrlToHttp(mx, avatarMxc, useAuthentication, 96, 96) ?? undefined)
|
||||
: undefined;
|
||||
|
||||
const audioOnly =
|
||||
(member as unknown as MemberWithMembershipData).membershipData?.['m.call.intent'] === 'audio';
|
||||
|
||||
return (
|
||||
<SequenceCard
|
||||
as="button"
|
||||
key={member.membershipID}
|
||||
className={css.CallMemberCard}
|
||||
variant="SurfaceVariant"
|
||||
radii="500"
|
||||
onClick={(evt: any) =>
|
||||
openUserProfile(
|
||||
room.roomId,
|
||||
undefined,
|
||||
userId,
|
||||
getMouseEventCords(evt.nativeEvent),
|
||||
'Right'
|
||||
)
|
||||
}
|
||||
>
|
||||
<Box grow="Yes" gap="300" alignItems="Center">
|
||||
<Avatar size="200" radii="400">
|
||||
<UserAvatar
|
||||
userId={userId}
|
||||
src={avatarUrl}
|
||||
alt={name}
|
||||
renderFallback={() => <Icon size="50" src={Icons.User} filled />}
|
||||
/>
|
||||
</Avatar>
|
||||
<Box grow="Yes">
|
||||
<Text size="L400" truncate>
|
||||
{name}
|
||||
</Text>
|
||||
</Box>
|
||||
{audioOnly && <Icon src={Icons.VideoCameraMute} size="100" />}
|
||||
</Box>
|
||||
</SequenceCard>
|
||||
);
|
||||
}
|
||||
|
||||
export function CallMemberRenderer({
|
||||
members,
|
||||
max = 4,
|
||||
}: {
|
||||
members: CallMembership[];
|
||||
max?: number;
|
||||
}) {
|
||||
const [viewMore, setViewMore] = useState(false);
|
||||
|
||||
const truncatedMembers = viewMore ? members : members.slice(0, 4);
|
||||
const remaining = members.length - truncatedMembers.length;
|
||||
|
||||
return (
|
||||
<>
|
||||
{truncatedMembers.map((member) => (
|
||||
<CallMemberCard key={member.membershipID} member={member} />
|
||||
))}
|
||||
{members.length > max && (
|
||||
<SequenceCard
|
||||
as="button"
|
||||
className={css.CallMemberCard}
|
||||
variant="SurfaceVariant"
|
||||
radii="500"
|
||||
onClick={() => setViewMore(!viewMore)}
|
||||
>
|
||||
<Box grow="Yes" gap="300" alignItems="Center">
|
||||
{viewMore ? (
|
||||
<Text size="L400" truncate>
|
||||
Collapse
|
||||
</Text>
|
||||
) : (
|
||||
<Text size="L400" truncate>
|
||||
{remaining === 0 ? `+${remaining} Other` : `+${remaining} Others`}
|
||||
</Text>
|
||||
)}
|
||||
</Box>
|
||||
<Icon src={viewMore ? Icons.ChevronTop : Icons.ChevronBottom} size="100" />
|
||||
</SequenceCard>
|
||||
)}
|
||||
</>
|
||||
);
|
||||
}
|
||||
@@ -1,37 +0,0 @@
|
||||
import { style } from '@vanilla-extract/css';
|
||||
import { DefaultReset, config } from 'folds';
|
||||
import { ContainerColor } from '$styles/ContainerColor.css';
|
||||
|
||||
export const CallViewUserGrid = style({
|
||||
display: 'flex',
|
||||
flexWrap: 'wrap',
|
||||
justifyContent: 'center',
|
||||
alignItems: 'center',
|
||||
marginInline: '20px',
|
||||
gap: config.space.S400,
|
||||
});
|
||||
|
||||
export const CallViewUser = style([
|
||||
DefaultReset,
|
||||
ContainerColor({ variant: 'SurfaceVariant' }),
|
||||
{
|
||||
height: '90px',
|
||||
width: '150px',
|
||||
borderRadius: config.radii.R500,
|
||||
},
|
||||
]);
|
||||
|
||||
export const UserLink = style({
|
||||
color: 'inherit',
|
||||
minWidth: 0,
|
||||
cursor: 'pointer',
|
||||
flexGrow: 0,
|
||||
transition: 'all ease-out 200ms',
|
||||
':hover': {
|
||||
transform: 'translateY(-3px)',
|
||||
textDecoration: 'unset',
|
||||
},
|
||||
':focus': {
|
||||
outline: 'none',
|
||||
},
|
||||
});
|
||||
@@ -1,271 +1,105 @@
|
||||
import { EventType, Room } from '$types/matrix-sdk';
|
||||
import {
|
||||
Children,
|
||||
useContext,
|
||||
useCallback,
|
||||
useEffect,
|
||||
useRef,
|
||||
MouseEventHandler,
|
||||
useState,
|
||||
ReactNode,
|
||||
} from 'react';
|
||||
import { Box, Button, config, Spinner, Text } from 'folds';
|
||||
import { useCallState } from '$pages/client/call/CallProvider';
|
||||
import { useCallMembers } from '$hooks/useCallMemberships';
|
||||
|
||||
import { CallRefContext } from '$pages/client/call/PersistentCallContainer';
|
||||
import { ScreenSize, useScreenSizeContext } from '$hooks/useScreenSize';
|
||||
import { useDebounce } from '$hooks/useDebounce';
|
||||
import { useMatrixClient } from '$hooks/useMatrixClient';
|
||||
import { useRoomNavigate } from '$hooks/useRoomNavigate';
|
||||
import { getMemberDisplayName } from '$utils/room';
|
||||
import { getMxIdLocalPart } from '$utils/matrix';
|
||||
import { useRoomPermissions } from '$hooks/useRoomPermissions';
|
||||
import { useRoomCreators } from '$hooks/useRoomCreators';
|
||||
import { useRef } from 'react';
|
||||
import { Badge, Box, color, Header, Scroll, Text, toRem } from 'folds';
|
||||
import { EventType } from '$types/matrix-sdk';
|
||||
import { useCallEmbed, useCallJoined, useSyncCallEmbedPlacement } from '$hooks/useCallEmbed';
|
||||
import { ContainerColor } from '$styles/ContainerColor.css';
|
||||
import { usePowerLevelsContext } from '$hooks/usePowerLevels';
|
||||
import { useRoomName } from '$hooks/useRoomMeta';
|
||||
import { useAtomValue } from 'jotai';
|
||||
import { nicknamesAtom } from '$state/nicknames';
|
||||
import * as css from './CallView.css';
|
||||
import { CallViewUser } from './CallViewUser';
|
||||
import { useRoom } from '$hooks/useRoom';
|
||||
import { useRoomCreators } from '$hooks/useRoomCreators';
|
||||
import { useRoomPermissions } from '$hooks/useRoomPermissions';
|
||||
import { useMatrixClient } from '$hooks/useMatrixClient';
|
||||
import { useCallMembers, useCallSession } from '$hooks/useCall';
|
||||
import { PrescreenControls } from './PrescreenControls';
|
||||
import { CallMemberRenderer } from './CallMemberCard';
|
||||
import * as css from './styles.css';
|
||||
|
||||
type OriginalStyles = {
|
||||
position?: string;
|
||||
top?: string;
|
||||
left?: string;
|
||||
width?: string;
|
||||
height?: string;
|
||||
zIndex?: string;
|
||||
display?: string;
|
||||
visibility?: string;
|
||||
pointerEvents?: string;
|
||||
border?: string;
|
||||
};
|
||||
function JoinMessage({ hasParticipant }: { hasParticipant?: boolean }) {
|
||||
if (hasParticipant) return null;
|
||||
|
||||
export function CallViewUserGrid({ children }: { children: ReactNode }) {
|
||||
return (
|
||||
<Box
|
||||
className={css.CallViewUserGrid}
|
||||
style={{
|
||||
maxWidth: Children.count(children) === 4 ? '336px' : '503px',
|
||||
}}
|
||||
>
|
||||
{children}
|
||||
</Box>
|
||||
<Text style={{ margin: 'auto' }} size="L400" align="Center">
|
||||
Voice chat's empty — Be the first to hop in!
|
||||
</Text>
|
||||
);
|
||||
}
|
||||
|
||||
export function CallView({ room }: { room: Room }) {
|
||||
const callIframeRef = useContext(CallRefContext);
|
||||
const iframeHostRef = useRef<HTMLDivElement>(null);
|
||||
function NoPermissionMessage() {
|
||||
return (
|
||||
<Text style={{ margin: 'auto' }} size="L400" align="Center">
|
||||
You don't have permission to join!
|
||||
</Text>
|
||||
);
|
||||
}
|
||||
|
||||
const originalIframeStylesRef = useRef<OriginalStyles | null>(null);
|
||||
function AlreadyInCallMessage() {
|
||||
return (
|
||||
<Text style={{ margin: 'auto', color: color.Warning.Main }} size="L400" align="Center">
|
||||
Already in another call — End the current call to join!
|
||||
</Text>
|
||||
);
|
||||
}
|
||||
|
||||
export function CallView() {
|
||||
const mx = useMatrixClient();
|
||||
const room = useRoom();
|
||||
|
||||
const [visibleCallNames, setVisibleCallNames] = useState('');
|
||||
const callViewRef = useRef<HTMLDivElement>(null);
|
||||
useSyncCallEmbedPlacement(callViewRef);
|
||||
|
||||
const powerLevels = usePowerLevelsContext();
|
||||
const creators = useRoomCreators(room);
|
||||
|
||||
const roomName = useRoomName(room);
|
||||
const permissions = useRoomPermissions(creators, powerLevels);
|
||||
const canJoin = permissions.event(EventType.GroupCallMemberPrefix, mx.getSafeUserId());
|
||||
|
||||
const {
|
||||
isActiveCallReady,
|
||||
activeCallRoomId,
|
||||
isChatOpen,
|
||||
setActiveCallRoomId,
|
||||
hangUp,
|
||||
setViewedCallRoomId,
|
||||
} = useCallState();
|
||||
const callSession = useCallSession(room);
|
||||
const callMembers = useCallMembers(room, callSession);
|
||||
const hasParticipant = callMembers.length > 0;
|
||||
|
||||
const isActiveCallRoom = activeCallRoomId === room.roomId;
|
||||
const callIsCurrentAndReady = isActiveCallRoom && isActiveCallReady;
|
||||
const callMembers = useCallMembers(mx, room.roomId);
|
||||
const callEmbed = useCallEmbed();
|
||||
const callJoined = useCallJoined(callEmbed);
|
||||
const inOtherCall = callEmbed && callEmbed.roomId !== room.roomId;
|
||||
|
||||
const nicknames = useAtomValue(nicknamesAtom);
|
||||
const getName = (userId: string) =>
|
||||
getMemberDisplayName(room, userId, nicknames) ?? getMxIdLocalPart(userId);
|
||||
|
||||
const memberDisplayNames = callMembers.map((callMembership) =>
|
||||
getName(callMembership.sender ?? '')
|
||||
);
|
||||
|
||||
const { navigateRoom } = useRoomNavigate();
|
||||
const screenSize = useScreenSizeContext();
|
||||
const isMobile = screenSize === ScreenSize.Mobile;
|
||||
|
||||
const activeIframeDisplayRef = callIframeRef;
|
||||
|
||||
const applyFixedPositioningToIframe = useCallback(() => {
|
||||
const iframeElement = activeIframeDisplayRef?.current;
|
||||
const hostElement = iframeHostRef?.current;
|
||||
|
||||
if (iframeElement && hostElement) {
|
||||
if (!originalIframeStylesRef.current) {
|
||||
const computed = window.getComputedStyle(iframeElement);
|
||||
originalIframeStylesRef.current = {
|
||||
position: iframeElement.style.position || computed.position,
|
||||
top: iframeElement.style.top || computed.top,
|
||||
left: iframeElement.style.left || computed.left,
|
||||
width: iframeElement.style.width || computed.width,
|
||||
height: iframeElement.style.height || computed.height,
|
||||
zIndex: iframeElement.style.zIndex || computed.zIndex,
|
||||
display: iframeElement.style.display || computed.display,
|
||||
visibility: iframeElement.style.visibility || computed.visibility,
|
||||
pointerEvents: iframeElement.style.pointerEvents || computed.pointerEvents,
|
||||
border: iframeElement.style.border || computed.border,
|
||||
};
|
||||
}
|
||||
|
||||
const hostRect = hostElement.getBoundingClientRect();
|
||||
|
||||
iframeElement.style.position = 'fixed';
|
||||
iframeElement.style.top = `${hostRect.top}px`;
|
||||
iframeElement.style.left = `${hostRect.left}px`;
|
||||
iframeElement.style.width = `${hostRect.width}px`;
|
||||
iframeElement.style.height = `${hostRect.height}px`;
|
||||
iframeElement.style.border = 'none';
|
||||
iframeElement.style.zIndex = '1000';
|
||||
iframeElement.style.display = room.isCallRoom() ? 'block' : 'none';
|
||||
iframeElement.style.visibility = 'visible';
|
||||
iframeElement.style.pointerEvents = 'auto';
|
||||
}
|
||||
}, [activeIframeDisplayRef, room]);
|
||||
|
||||
const debouncedApplyFixedPositioning = useDebounce(applyFixedPositioningToIframe, {
|
||||
wait: 50,
|
||||
immediate: false,
|
||||
});
|
||||
useEffect(() => {
|
||||
const iframeElement = activeIframeDisplayRef?.current;
|
||||
const hostElement = iframeHostRef?.current;
|
||||
|
||||
if (room.isCallRoom() || (callIsCurrentAndReady && iframeElement && hostElement)) {
|
||||
applyFixedPositioningToIframe();
|
||||
|
||||
const resizeObserver = new ResizeObserver(debouncedApplyFixedPositioning);
|
||||
if (hostElement) resizeObserver.observe(hostElement);
|
||||
window.addEventListener('scroll', debouncedApplyFixedPositioning, true);
|
||||
|
||||
return () => {
|
||||
resizeObserver.disconnect();
|
||||
window.removeEventListener('scroll', debouncedApplyFixedPositioning, true);
|
||||
|
||||
if (iframeElement && originalIframeStylesRef.current) {
|
||||
const originalStyles = originalIframeStylesRef.current;
|
||||
(Object.keys(originalStyles) as Array<keyof OriginalStyles>).forEach((key) => {
|
||||
if (key in iframeElement.style) {
|
||||
iframeElement.style[key as any] = originalStyles[key] || '';
|
||||
}
|
||||
});
|
||||
}
|
||||
originalIframeStylesRef.current = null;
|
||||
};
|
||||
}
|
||||
|
||||
return undefined;
|
||||
}, [
|
||||
activeIframeDisplayRef,
|
||||
applyFixedPositioningToIframe,
|
||||
debouncedApplyFixedPositioning,
|
||||
callIsCurrentAndReady,
|
||||
room,
|
||||
]);
|
||||
|
||||
const handleJoinVCClick: MouseEventHandler<HTMLElement> = (evt) => {
|
||||
if (!canJoin) return;
|
||||
|
||||
if (isMobile) {
|
||||
evt.stopPropagation();
|
||||
setViewedCallRoomId(room.roomId);
|
||||
navigateRoom(room.roomId);
|
||||
}
|
||||
if (!callIsCurrentAndReady) {
|
||||
hangUp();
|
||||
setActiveCallRoomId(room.roomId);
|
||||
}
|
||||
};
|
||||
|
||||
const isCallViewVisible = room.isCallRoom() && (screenSize === ScreenSize.Desktop || !isChatOpen);
|
||||
|
||||
useEffect(() => {
|
||||
if (memberDisplayNames.length <= 2) {
|
||||
setVisibleCallNames(memberDisplayNames.join(' and '));
|
||||
} else {
|
||||
const visible = memberDisplayNames.slice(0, 2);
|
||||
const remaining = memberDisplayNames.length - 2;
|
||||
|
||||
setVisibleCallNames(
|
||||
`${visible.join(', ')}, and ${remaining} other${remaining > 1 ? 's' : ''}`
|
||||
);
|
||||
}
|
||||
}, [memberDisplayNames]);
|
||||
const currentJoined = callEmbed?.roomId === room.roomId && callJoined;
|
||||
|
||||
return (
|
||||
<Box grow="Yes" direction="Column" style={{ display: isCallViewVisible ? 'flex' : 'none' }}>
|
||||
<div
|
||||
ref={iframeHostRef}
|
||||
style={{
|
||||
width: '100%',
|
||||
height: '100%',
|
||||
position: 'relative',
|
||||
pointerEvents: 'none',
|
||||
display: callIsCurrentAndReady ? 'flex' : 'none',
|
||||
}}
|
||||
/>
|
||||
<Box
|
||||
grow="Yes"
|
||||
justifyContent="Center"
|
||||
alignItems="Center"
|
||||
direction="Column"
|
||||
gap="300"
|
||||
style={{
|
||||
display: callIsCurrentAndReady ? 'none' : 'flex',
|
||||
}}
|
||||
>
|
||||
<CallViewUserGrid>
|
||||
{callMembers.slice(0, 6).map((callMember) => (
|
||||
<CallViewUser key={callMember.membershipID} room={room} callMembership={callMember} />
|
||||
))}
|
||||
</CallViewUserGrid>
|
||||
|
||||
<Box
|
||||
direction="Column"
|
||||
alignItems="Center"
|
||||
style={{
|
||||
paddingBlock: config.space.S200,
|
||||
}}
|
||||
>
|
||||
<Text
|
||||
size="H1"
|
||||
style={{
|
||||
paddingBottom: config.space.S300,
|
||||
}}
|
||||
>
|
||||
{roomName}
|
||||
</Text>
|
||||
<Text size="T200">
|
||||
{visibleCallNames !== '' ? visibleCallNames : 'No one'}{' '}
|
||||
{memberDisplayNames.length > 1 ? 'are' : 'is'} currently in voice
|
||||
</Text>
|
||||
</Box>
|
||||
<Button
|
||||
variant="Secondary"
|
||||
disabled={!canJoin || isActiveCallRoom}
|
||||
onClick={handleJoinVCClick}
|
||||
>
|
||||
{isActiveCallRoom ? (
|
||||
<Box justifyContent="Center" alignItems="Center" gap="200">
|
||||
<Spinner />
|
||||
<Text size="B500">{activeCallRoomId === room.roomId ? `Joining` : 'Join Voice'}</Text>
|
||||
<Box
|
||||
ref={callViewRef}
|
||||
className={ContainerColor({ variant: 'Surface' })}
|
||||
style={{ minWidth: toRem(280) }}
|
||||
grow="Yes"
|
||||
>
|
||||
{!currentJoined && (
|
||||
<Scroll variant="Surface" hideTrack>
|
||||
<Box className={css.CallViewContent} alignItems="Center" justifyContent="Center">
|
||||
<Box style={{ maxWidth: toRem(382), width: '100%' }} direction="Column" gap="100">
|
||||
{hasParticipant && (
|
||||
<Header size="300">
|
||||
<Box grow="Yes" alignItems="Center">
|
||||
<Text size="L400">Participant</Text>
|
||||
</Box>
|
||||
<Badge variant="Critical" fill="Solid" size="400">
|
||||
<Text as="span" size="L400" truncate>
|
||||
{callMembers.length} Live
|
||||
</Text>
|
||||
</Badge>
|
||||
</Header>
|
||||
)}
|
||||
<CallMemberRenderer members={callMembers} />
|
||||
<PrescreenControls canJoin={canJoin} />
|
||||
<Header size="300">
|
||||
{!inOtherCall &&
|
||||
(canJoin ? (
|
||||
<JoinMessage hasParticipant={hasParticipant} />
|
||||
) : (
|
||||
<NoPermissionMessage />
|
||||
))}
|
||||
{inOtherCall && <AlreadyInCallMessage />}
|
||||
</Header>
|
||||
</Box>
|
||||
) : (
|
||||
<Text size="B500">{canJoin ? 'Join Voice' : 'Channel Locked'}</Text>
|
||||
)}
|
||||
</Button>
|
||||
</Box>
|
||||
</Box>
|
||||
</Scroll>
|
||||
)}
|
||||
</Box>
|
||||
);
|
||||
}
|
||||
@@ -1,73 +0,0 @@
|
||||
import { as, Avatar, Box, Icon, Icons, Text } from 'folds';
|
||||
import { MouseEventHandler } from 'react';
|
||||
import classNames from 'classnames';
|
||||
import { Room, CallMembership } from '$types/matrix-sdk';
|
||||
import { UserAvatar } from '$components/user-avatar';
|
||||
import { useMatrixClient } from '$hooks/useMatrixClient';
|
||||
import { getMxIdLocalPart } from '$utils/matrix';
|
||||
import { getMemberAvatarMxc, getMemberDisplayName } from '$utils/room';
|
||||
import { useAtomValue } from 'jotai';
|
||||
import { nicknamesAtom } from '$state/nicknames';
|
||||
import { useMediaAuthentication } from '$hooks/useMediaAuthentication';
|
||||
import { useOpenUserRoomProfile } from '$state/hooks/userRoomProfile';
|
||||
import { useSpaceOptionally } from '$hooks/useSpace';
|
||||
import * as css from './CallView.css';
|
||||
|
||||
type CallViewUserProps = {
|
||||
room: Room;
|
||||
callMembership: CallMembership;
|
||||
};
|
||||
|
||||
export const UserProfileButton = as<'button'>(
|
||||
({ as: AsUserProfileButton = 'button', className, ...props }, ref) => (
|
||||
<AsUserProfileButton className={classNames(css.UserLink, className)} {...props} ref={ref} />
|
||||
)
|
||||
);
|
||||
|
||||
export const CallViewUserBase = as<'div'>(({ className, ...props }, ref) => (
|
||||
<Box
|
||||
direction="Column"
|
||||
gap="300"
|
||||
className={classNames(css.CallViewUser, className)}
|
||||
{...props}
|
||||
ref={ref}
|
||||
/>
|
||||
));
|
||||
|
||||
export function CallViewUser({ room, callMembership }: CallViewUserProps) {
|
||||
const mx = useMatrixClient();
|
||||
const useAuthentication = useMediaAuthentication();
|
||||
const openProfile = useOpenUserRoomProfile();
|
||||
const space = useSpaceOptionally();
|
||||
const userId = callMembership.sender ?? '';
|
||||
const avatarMxcUrl = getMemberAvatarMxc(room, userId);
|
||||
const avatarUrl = avatarMxcUrl
|
||||
? mx.mxcUrlToHttp(avatarMxcUrl, 32, 32, 'crop', undefined, false, useAuthentication)
|
||||
: undefined;
|
||||
const nicknames = useAtomValue(nicknamesAtom);
|
||||
const getName = getMemberDisplayName(room, userId, nicknames) ?? getMxIdLocalPart(userId);
|
||||
|
||||
const handleUserClick: MouseEventHandler<HTMLButtonElement> = (evt) => {
|
||||
openProfile(room.roomId, space?.roomId, userId, evt.currentTarget.getBoundingClientRect());
|
||||
};
|
||||
|
||||
return (
|
||||
<UserProfileButton onClick={handleUserClick} aria-label={getName}>
|
||||
<CallViewUserBase>
|
||||
<Box direction="Column" grow="Yes" alignItems="Center" gap="200" justifyContent="Center">
|
||||
<Avatar size="200">
|
||||
<UserAvatar
|
||||
userId={userId}
|
||||
src={avatarUrl ?? undefined}
|
||||
alt={getName}
|
||||
renderFallback={() => <Icon size="50" src={Icons.User} filled />}
|
||||
/>
|
||||
</Avatar>
|
||||
<Text size="B400" priority="300" truncate>
|
||||
{getName}
|
||||
</Text>
|
||||
</Box>
|
||||
</CallViewUserBase>
|
||||
</UserProfileButton>
|
||||
);
|
||||
}
|
||||
@@ -1,9 +0,0 @@
|
||||
import { Widget } from 'matrix-widget-api';
|
||||
import type { IApp } from './SmallWidget';
|
||||
|
||||
// Wrapper class for the widget definition
|
||||
export class CinnyWidget extends Widget {
|
||||
public constructor(private rawDefinition: IApp) {
|
||||
super(rawDefinition);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,144 @@
|
||||
import { Icon, IconButton, Icons, Line, Text, Tooltip, TooltipProvider } from 'folds';
|
||||
import { useAtom } from 'jotai';
|
||||
import * as css from './styles.css';
|
||||
import { callChatAtom } from '../../state/callEmbed';
|
||||
|
||||
export function ControlDivider() {
|
||||
return (
|
||||
<Line variant="SurfaceVariant" size="300" direction="Vertical" className={css.ControlDivider} />
|
||||
);
|
||||
}
|
||||
|
||||
type MicrophoneButtonProps = {
|
||||
enabled: boolean;
|
||||
onToggle: () => void;
|
||||
};
|
||||
export function MicrophoneButton({ enabled, onToggle }: MicrophoneButtonProps) {
|
||||
return (
|
||||
<TooltipProvider
|
||||
position="Top"
|
||||
delay={500}
|
||||
tooltip={
|
||||
<Tooltip>
|
||||
<Text size="T200">{enabled ? 'Turn Off Microphone' : 'Turn On Microphone'}</Text>
|
||||
</Tooltip>
|
||||
}
|
||||
>
|
||||
{(anchorRef) => (
|
||||
<IconButton
|
||||
ref={anchorRef}
|
||||
variant={enabled ? 'Surface' : 'Warning'}
|
||||
fill="Soft"
|
||||
radii="400"
|
||||
size="400"
|
||||
onClick={() => onToggle()}
|
||||
outlined
|
||||
>
|
||||
<Icon size="400" src={enabled ? Icons.Mic : Icons.MicMute} filled={!enabled} />
|
||||
</IconButton>
|
||||
)}
|
||||
</TooltipProvider>
|
||||
);
|
||||
}
|
||||
|
||||
type SoundButtonProps = {
|
||||
enabled: boolean;
|
||||
onToggle: () => void;
|
||||
};
|
||||
export function SoundButton({ enabled, onToggle }: SoundButtonProps) {
|
||||
return (
|
||||
<TooltipProvider
|
||||
position="Top"
|
||||
delay={500}
|
||||
tooltip={
|
||||
<Tooltip>
|
||||
<Text size="T200">{enabled ? 'Turn Off Sound' : 'Turn On Sound'}</Text>
|
||||
</Tooltip>
|
||||
}
|
||||
>
|
||||
{(anchorRef) => (
|
||||
<IconButton
|
||||
ref={anchorRef}
|
||||
variant={enabled ? 'Surface' : 'Warning'}
|
||||
fill="Soft"
|
||||
radii="400"
|
||||
size="400"
|
||||
onClick={() => onToggle()}
|
||||
outlined
|
||||
>
|
||||
<Icon
|
||||
size="400"
|
||||
src={enabled ? Icons.Headphone : Icons.HeadphoneMute}
|
||||
filled={!enabled}
|
||||
/>
|
||||
</IconButton>
|
||||
)}
|
||||
</TooltipProvider>
|
||||
);
|
||||
}
|
||||
|
||||
type VideoButtonProps = {
|
||||
enabled: boolean;
|
||||
onToggle: () => void;
|
||||
};
|
||||
export function VideoButton({ enabled, onToggle }: VideoButtonProps) {
|
||||
return (
|
||||
<TooltipProvider
|
||||
position="Top"
|
||||
delay={500}
|
||||
tooltip={
|
||||
<Tooltip>
|
||||
<Text size="T200">{enabled ? 'Stop Camera' : 'Start Camera'}</Text>
|
||||
</Tooltip>
|
||||
}
|
||||
>
|
||||
{(anchorRef) => (
|
||||
<IconButton
|
||||
ref={anchorRef}
|
||||
variant={enabled ? 'Success' : 'Surface'}
|
||||
fill="Soft"
|
||||
radii="400"
|
||||
size="400"
|
||||
onClick={() => onToggle()}
|
||||
outlined
|
||||
>
|
||||
<Icon
|
||||
size="400"
|
||||
src={enabled ? Icons.VideoCamera : Icons.VideoCameraMute}
|
||||
filled={enabled}
|
||||
/>
|
||||
</IconButton>
|
||||
)}
|
||||
</TooltipProvider>
|
||||
);
|
||||
}
|
||||
|
||||
export function ChatButton() {
|
||||
const [chat, setChat] = useAtom(callChatAtom);
|
||||
|
||||
return (
|
||||
<TooltipProvider
|
||||
position="Top"
|
||||
delay={500}
|
||||
tooltip={
|
||||
<Tooltip>
|
||||
<Text size="T200">{chat ? 'Close Chat' : 'Open Chat'}</Text>
|
||||
</Tooltip>
|
||||
}
|
||||
>
|
||||
{(anchorRef) => (
|
||||
<IconButton
|
||||
ref={anchorRef}
|
||||
variant={chat ? 'Success' : 'Surface'}
|
||||
fill="Soft"
|
||||
radii="400"
|
||||
size="400"
|
||||
onClick={() => setChat(!chat)}
|
||||
outlined
|
||||
>
|
||||
<Icon size="400" src={Icons.Message} filled={chat} />
|
||||
</IconButton>
|
||||
)}
|
||||
</TooltipProvider>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,67 @@
|
||||
import { Box, Button, Icon, Icons, Spinner, Text } from 'folds';
|
||||
import { SequenceCard } from '../../components/sequence-card';
|
||||
import * as css from './styles.css';
|
||||
import { ChatButton, ControlDivider, MicrophoneButton, SoundButton, VideoButton } from './Controls';
|
||||
import { useIsDirectRoom, useRoom } from '../../hooks/useRoom';
|
||||
import { useCallEmbed, useCallJoined, useCallStart } from '../../hooks/useCallEmbed';
|
||||
import { useCallPreferences } from '../../state/hooks/callPreferences';
|
||||
import { CallControlState } from '../../plugins/call/CallControlState';
|
||||
|
||||
type PrescreenControlsProps = {
|
||||
canJoin?: boolean;
|
||||
};
|
||||
export function PrescreenControls({ canJoin }: PrescreenControlsProps) {
|
||||
const room = useRoom();
|
||||
const callEmbed = useCallEmbed();
|
||||
const callJoined = useCallJoined(callEmbed);
|
||||
const direct = useIsDirectRoom();
|
||||
|
||||
const inOtherCall = callEmbed && callEmbed.roomId !== room.roomId;
|
||||
|
||||
const startCall = useCallStart(direct);
|
||||
const joining = callEmbed?.roomId === room.roomId && !callJoined;
|
||||
|
||||
const disabled = inOtherCall || !canJoin;
|
||||
|
||||
const { microphone, video, sound, toggleMicrophone, toggleVideo, toggleSound } =
|
||||
useCallPreferences();
|
||||
|
||||
return (
|
||||
<SequenceCard
|
||||
className={css.ControlCard}
|
||||
variant="SurfaceVariant"
|
||||
gap="400"
|
||||
radii="500"
|
||||
alignItems="Center"
|
||||
justifyContent="SpaceBetween"
|
||||
wrap="Wrap"
|
||||
>
|
||||
<Box shrink="No" alignItems="Inherit" justifyContent="SpaceBetween" gap="200">
|
||||
<MicrophoneButton enabled={microphone} onToggle={toggleMicrophone} />
|
||||
<SoundButton enabled={sound} onToggle={toggleSound} />
|
||||
</Box>
|
||||
<ControlDivider />
|
||||
<Box shrink="No" alignItems="Inherit" justifyContent="SpaceBetween" gap="200">
|
||||
<VideoButton enabled={video} onToggle={toggleVideo} />
|
||||
<ChatButton />
|
||||
</Box>
|
||||
<Box grow="Yes" direction="Column">
|
||||
<Button
|
||||
variant={disabled ? 'Secondary' : 'Success'}
|
||||
fill={disabled ? 'Soft' : 'Solid'}
|
||||
onClick={() => startCall(room, new CallControlState(microphone, video, sound))}
|
||||
disabled={disabled || joining}
|
||||
before={
|
||||
joining ? (
|
||||
<Spinner variant="Success" fill="Solid" size="200" />
|
||||
) : (
|
||||
<Icon src={Icons.Phone} size="200" filled />
|
||||
)
|
||||
}
|
||||
>
|
||||
<Text size="B400">Join</Text>
|
||||
</Button>
|
||||
</Box>
|
||||
</SequenceCard>
|
||||
);
|
||||
}
|
||||
@@ -1,419 +0,0 @@
|
||||
/*
|
||||
* Copyright 2024 New Vector Ltd.
|
||||
* Copyright 2020-2023 The Matrix.org Foundation C.I.C.
|
||||
*
|
||||
* SPDX-License-Identifier: AGPL-3.0-only OR GPL-3.0-only OR LicenseRef-Element-Commercial
|
||||
* Please see LICENSE files in the repository root for full details.
|
||||
*/
|
||||
|
||||
import EventEmitter from 'events';
|
||||
import {
|
||||
ClientEvent,
|
||||
Direction,
|
||||
IEvent,
|
||||
KnownMembership,
|
||||
MatrixClient,
|
||||
MatrixEvent,
|
||||
MatrixEventEvent,
|
||||
RoomStateEvent,
|
||||
} from '$types/matrix-sdk';
|
||||
import {
|
||||
ClientWidgetApi,
|
||||
IRoomEvent,
|
||||
IStickyActionRequest,
|
||||
IWidget,
|
||||
IWidgetData,
|
||||
MatrixCapabilities,
|
||||
WidgetApiFromWidgetAction,
|
||||
WidgetKind,
|
||||
} from 'matrix-widget-api';
|
||||
import { createLogger } from '$utils/debug';
|
||||
import { CinnyWidget } from './CinnyWidget';
|
||||
import { SmallWidgetDriver } from './SmallWidgetDriver';
|
||||
|
||||
const log = createLogger('SmallWidget');
|
||||
|
||||
/**
|
||||
* Generates the URL for the Element Call widget.
|
||||
* @param mx - The MatrixClient instance.
|
||||
* @param roomId - The ID of the room.
|
||||
* @returns The generated URL object.
|
||||
*/
|
||||
export const getWidgetUrl = (
|
||||
mx: MatrixClient,
|
||||
roomId: string,
|
||||
elementCallUrl: string,
|
||||
widgetId: string,
|
||||
setParams: any
|
||||
): URL => {
|
||||
const baseUrl = window.location.origin;
|
||||
const url = elementCallUrl
|
||||
? new URL(`${elementCallUrl}/room`)
|
||||
: new URL('/public/element-call/index.html#', baseUrl);
|
||||
|
||||
const params = new URLSearchParams({
|
||||
embed: 'true',
|
||||
widgetId,
|
||||
appPrompt: 'false',
|
||||
skipLobby: setParams.skipLobby ?? 'true', // TODO: skipLobby is deprecated, use intent instead (intent doesn't produce the same effect?)
|
||||
returnToLobby: setParams.returnToLobby ?? 'true',
|
||||
perParticipantE2EE: setParams.perParticipantE2EE ?? 'true',
|
||||
callIntent: setParams.callIntent ?? 'video',
|
||||
header: 'none',
|
||||
confineToRoom: 'true',
|
||||
theme: setParams.theme ?? 'dark',
|
||||
userId: mx.getUserId()!,
|
||||
deviceId: mx.getDeviceId()!,
|
||||
roomId,
|
||||
baseUrl: mx.baseUrl,
|
||||
parentUrl: window.location.origin,
|
||||
});
|
||||
|
||||
const replacedParams = params.toString().replace(/%24/g, '$');
|
||||
url.search = `?${replacedParams}`;
|
||||
|
||||
return url;
|
||||
};
|
||||
|
||||
export interface IApp extends IWidget {
|
||||
client: MatrixClient;
|
||||
roomId: string;
|
||||
eventId?: string;
|
||||
avatar_url?: string;
|
||||
sender: string;
|
||||
'io.element.managed_hybrid'?: boolean;
|
||||
}
|
||||
|
||||
export class SmallWidget extends EventEmitter {
|
||||
private client: MatrixClient;
|
||||
|
||||
private messaging: ClientWidgetApi | null = null;
|
||||
|
||||
private mockWidget: CinnyWidget;
|
||||
|
||||
public roomId?: string;
|
||||
|
||||
public url?: string;
|
||||
|
||||
public iframe: HTMLIFrameElement | null = null;
|
||||
|
||||
private type: string; // Type of the widget (e.g., 'm.call')
|
||||
|
||||
private readUpToMap: Record<string, string> = {}; // room ID to event ID
|
||||
|
||||
private readonly eventsToFeed = new WeakSet<MatrixEvent>();
|
||||
|
||||
private stickyPromise?: () => Promise<void>;
|
||||
|
||||
constructor(private iapp: IApp) {
|
||||
super();
|
||||
this.client = iapp.client;
|
||||
this.roomId = iapp.roomId;
|
||||
this.url = iapp.url;
|
||||
this.type = iapp.type;
|
||||
this.mockWidget = new CinnyWidget(iapp);
|
||||
}
|
||||
|
||||
/**
|
||||
* Initializes the widget messaging API.
|
||||
* @param iframe - The HTMLIFrameElement to bind to.
|
||||
* @returns The initialized ClientWidgetApi instance.
|
||||
*/
|
||||
startMessaging(iframe: HTMLIFrameElement): ClientWidgetApi {
|
||||
// Ensure the driver is correctly instantiated
|
||||
// The capabilities array might need adjustment based on required permissions
|
||||
const driver = new SmallWidgetDriver(
|
||||
this.client,
|
||||
[],
|
||||
this.mockWidget,
|
||||
WidgetKind.Room,
|
||||
true,
|
||||
this.roomId
|
||||
);
|
||||
this.iframe = iframe;
|
||||
this.messaging = new ClientWidgetApi(this.mockWidget, iframe, driver);
|
||||
this.messaging.setViewedRoomId(this.roomId ?? null);
|
||||
|
||||
// Emit events during the widget lifecycle
|
||||
this.messaging.on('preparing', () => this.emit('preparing'));
|
||||
this.messaging.on('error:preparing', (err: unknown) => this.emit('error:preparing', err));
|
||||
this.messaging.once('ready', () => this.emit('ready'));
|
||||
// this.messaging.on("capabilitiesNotified", () => this.emit("capabilitiesNotified")); // Uncomment if needed
|
||||
|
||||
// Populate the map of "read up to" events for this widget with the current event in every room.
|
||||
// This is a bit inefficient, but should be okay. We do this for all rooms in case the widget
|
||||
// requests timeline capabilities in other rooms down the road. It's just easier to manage here.
|
||||
// eslint-disable-next-line no-restricted-syntax
|
||||
for (const room of this.client.getRooms()) {
|
||||
// Timelines are most recent last
|
||||
const events = room.getLiveTimeline()?.getEvents() || [];
|
||||
const roomEvent = events[events.length - 1];
|
||||
// force later code to think the room is fresh
|
||||
if (roomEvent) {
|
||||
const eventId = roomEvent.getId();
|
||||
if (eventId) this.readUpToMap[room.roomId] = eventId;
|
||||
}
|
||||
}
|
||||
|
||||
this.messaging.on('action:org.matrix.msc2876.read_events', (ev: CustomEvent) => {
|
||||
const room = this.client.getRoom(this.roomId);
|
||||
const events: Partial<IEvent>[] = [];
|
||||
const { type } = ev.detail.data;
|
||||
|
||||
ev.preventDefault();
|
||||
if (room === null) {
|
||||
return this.messaging?.transport.reply(ev.detail, { events });
|
||||
}
|
||||
const state = room.getLiveTimeline().getState(Direction.Forward);
|
||||
if (state === undefined) {
|
||||
return this.messaging?.transport.reply(ev.detail, { events });
|
||||
}
|
||||
|
||||
const stateEvents = state.events?.get(type);
|
||||
|
||||
Array.from(stateEvents?.values() ?? []).forEach((eventObject) => {
|
||||
events.push(eventObject.event);
|
||||
});
|
||||
|
||||
return this.messaging?.transport.reply(ev.detail, { events });
|
||||
});
|
||||
|
||||
this.client.on(ClientEvent.Event, this.onEvent);
|
||||
this.client.on(MatrixEventEvent.Decrypted, this.onEventDecrypted);
|
||||
this.client.on(RoomStateEvent.Events, this.onStateUpdate);
|
||||
this.client.on(ClientEvent.ToDeviceEvent, this.onToDeviceEvent);
|
||||
this.messaging.on(
|
||||
`action:${WidgetApiFromWidgetAction.UpdateAlwaysOnScreen}`,
|
||||
async (ev: CustomEvent<IStickyActionRequest>) => {
|
||||
if (this.messaging?.hasCapability(MatrixCapabilities.AlwaysOnScreen)) {
|
||||
ev.preventDefault();
|
||||
if (ev.detail.data.value) {
|
||||
// If the widget wants to become sticky we wait for the stickyPromise to resolve
|
||||
if (this.stickyPromise) await this.stickyPromise();
|
||||
this.messaging.transport.reply(ev.detail, {});
|
||||
}
|
||||
// Stop being persistent can be done instantly
|
||||
// MAKE PERSISTENT HERE
|
||||
// Send the ack after the widget actually has become sticky.
|
||||
}
|
||||
}
|
||||
);
|
||||
|
||||
return this.messaging;
|
||||
}
|
||||
|
||||
private onEvent = (ev: MatrixEvent): void => {
|
||||
this.client.decryptEventIfNeeded(ev);
|
||||
if (!ev.isState()) this.feedEvent(ev);
|
||||
};
|
||||
|
||||
private onEventDecrypted = (ev: MatrixEvent): void => {
|
||||
if (!ev.isState()) this.feedEvent(ev);
|
||||
};
|
||||
|
||||
private onReadEvent = (ev: MatrixEvent): void => {
|
||||
this.feedEvent(ev);
|
||||
};
|
||||
|
||||
private onStateUpdate = (ev: MatrixEvent): void => {
|
||||
if (this.messaging === null || !ev.isState()) return;
|
||||
const raw = ev.getEffectiveEvent();
|
||||
this.messaging.feedStateUpdate(raw as IRoomEvent).catch((err) => {
|
||||
log.warn('Failed to feed widget state update:', err);
|
||||
});
|
||||
};
|
||||
|
||||
private onToDeviceEvent = async (ev: MatrixEvent): Promise<void> => {
|
||||
await this.client.decryptEventIfNeeded(ev);
|
||||
if (ev.isDecryptionFailure()) return;
|
||||
await this.messaging?.feedToDevice(ev.getEffectiveEvent() as IRoomEvent, ev.isEncrypted());
|
||||
};
|
||||
|
||||
/**
|
||||
* Determines whether the event comes from a room that we've been invited to
|
||||
* (in which case we likely don't have the full timeline).
|
||||
*/
|
||||
private isFromInvite(ev: MatrixEvent): boolean {
|
||||
const room = this.client.getRoom(ev.getRoomId());
|
||||
return room?.getMyMembership() === KnownMembership.Invite;
|
||||
}
|
||||
|
||||
/**
|
||||
* Determines whether the event has a relation to an unknown parent.
|
||||
*/
|
||||
private relatesToUnknown(ev: MatrixEvent): boolean {
|
||||
// Replies to unknown events don't count
|
||||
if (!ev.relationEventId || ev.replyEventId) return false;
|
||||
const room = this.client.getRoom(ev.getRoomId());
|
||||
return room === null || !room.findEventById(ev.relationEventId);
|
||||
}
|
||||
|
||||
// eslint-disable-next-line class-methods-use-this
|
||||
private arrayFastClone<T>(a: T[]): T[] {
|
||||
return a.slice(0, a.length);
|
||||
}
|
||||
|
||||
private advanceReadUpToMarker(ev: MatrixEvent): boolean {
|
||||
const evId = ev.getId();
|
||||
if (evId === undefined) return false;
|
||||
const roomId = ev.getRoomId();
|
||||
if (roomId === undefined) return false;
|
||||
const room = this.client.getRoom(roomId);
|
||||
if (room === null) return false;
|
||||
|
||||
const upToEventId = this.readUpToMap[ev.getRoomId()!];
|
||||
if (!upToEventId) {
|
||||
// There's no marker yet; start it at this event
|
||||
this.readUpToMap[roomId] = evId;
|
||||
return true;
|
||||
}
|
||||
|
||||
// Small optimization for exact match (skip the search)
|
||||
if (upToEventId === evId) return false;
|
||||
|
||||
// Timelines are most recent last, so reverse the order and limit ourselves to 100 events
|
||||
// to avoid overusing the CPU.
|
||||
const timeline = room.getLiveTimeline();
|
||||
const events = this.arrayFastClone(timeline.getEvents()).reverse().slice(0, 100);
|
||||
|
||||
let advanced = false;
|
||||
|
||||
events.some((timelineEvent) => {
|
||||
const id = timelineEvent.getId();
|
||||
|
||||
if (id === upToEventId) {
|
||||
// The event must be somewhere before the "read up to" marker
|
||||
return true;
|
||||
}
|
||||
|
||||
if (id === evId) {
|
||||
// The event is after the marker; advance it
|
||||
this.readUpToMap[roomId] = evId;
|
||||
advanced = true;
|
||||
return true;
|
||||
}
|
||||
// We can't say for sure whether the widget has seen the event; let's
|
||||
// just assume that it has
|
||||
return false;
|
||||
});
|
||||
|
||||
return advanced;
|
||||
}
|
||||
|
||||
private feedEvent(ev: MatrixEvent): void {
|
||||
if (this.messaging === null) return;
|
||||
|
||||
if (
|
||||
// If we had decided earlier to feed this event to the widget, but
|
||||
// it just wasn't ready, give it another try
|
||||
this.eventsToFeed.delete(ev) ||
|
||||
// Skip marker timeline check for events with relations to unknown parent because these
|
||||
// events are not added to the timeline here and will be ignored otherwise:
|
||||
// https://github.com/matrix-org/matrix-js-sdk/blob/d3dfcd924201d71b434af3d77343b5229b6ed75e/src/models/room.ts#L2207-L2213
|
||||
this.relatesToUnknown(ev) ||
|
||||
// Skip marker timeline check for rooms where membership is
|
||||
// 'invite', otherwise the membership event from the invitation room
|
||||
// will advance the marker and new state events will not be
|
||||
// forwarded to the widget.
|
||||
this.isFromInvite(ev) ||
|
||||
// Check whether this event would be before or after our "read up to" marker. If it's
|
||||
// before, or we can't decide, then we assume the widget will have already seen the event.
|
||||
// If the event is after, or we don't have a marker for the room, then the marker will advance and we'll
|
||||
// send it through.
|
||||
// This approach of "read up to" prevents widgets receiving decryption spam from startup or
|
||||
// receiving ancient events from backfill and such.
|
||||
this.advanceReadUpToMarker(ev)
|
||||
) {
|
||||
// If the event is still being decrypted, remember that we want to
|
||||
// feed it to the widget (even if not strictly in the order given by
|
||||
// the timeline) and get back to it later
|
||||
if (ev.isBeingDecrypted() || ev.isDecryptionFailure()) {
|
||||
this.eventsToFeed.add(ev);
|
||||
} else {
|
||||
const raw = ev.getEffectiveEvent();
|
||||
this.messaging.feedEvent(raw as IRoomEvent).catch((err) => {
|
||||
log.warn('Failed to feed widget event:', err);
|
||||
});
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Stops the widget messaging and cleans up resources.
|
||||
*/
|
||||
stopMessaging() {
|
||||
if (this.messaging) {
|
||||
this.messaging.stop(); // Example if a stop method exists
|
||||
this.messaging.removeAllListeners(); // Remove listeners attached by SmallWidget
|
||||
this.messaging = null;
|
||||
}
|
||||
|
||||
this.client.off(ClientEvent.Event, this.onEvent);
|
||||
this.client.off(MatrixEventEvent.Decrypted, this.onEventDecrypted);
|
||||
this.client.off(RoomStateEvent.Events, this.onStateUpdate);
|
||||
this.client.off(ClientEvent.ToDeviceEvent, this.onToDeviceEvent);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Creates the data object for the widget.
|
||||
* @param client - The MatrixClient instance.
|
||||
* @param roomId - The ID of the room.
|
||||
* @param currentData - Existing widget data.
|
||||
* @param overwriteData - Data to merge or overwrite.
|
||||
* @returns The final widget data object.
|
||||
*/
|
||||
export const getWidgetData = (
|
||||
client: MatrixClient,
|
||||
roomId: string,
|
||||
currentData: object,
|
||||
overwriteData: object
|
||||
): IWidgetData => {
|
||||
// Example: Determine E2EE based on room state if needed
|
||||
const perParticipantE2EE = true; // Default or based on logic
|
||||
// const roomEncryption = client.getRoom(roomId)?.currentState.getStateEvents(EventType.RoomEncryption, "");
|
||||
// if (roomEncryption) perParticipantE2EE = true; // Simplified example
|
||||
|
||||
return {
|
||||
...currentData,
|
||||
...overwriteData,
|
||||
perParticipantE2EE,
|
||||
};
|
||||
};
|
||||
|
||||
/**
|
||||
* Creates a virtual widget definition (IApp).
|
||||
* @param client - MatrixClient instance.
|
||||
* @param id - Widget ID.
|
||||
* @param creatorUserId - User ID of the creator.
|
||||
* @param name - Widget display name.
|
||||
* @param type - Widget type (e.g., 'm.call').
|
||||
* @param url - Widget URL.
|
||||
* @param waitForIframeLoad - Whether to wait for iframe load signal.
|
||||
* @param data - Widget data.
|
||||
* @param roomId - Room ID.
|
||||
* @returns The IApp widget definition.
|
||||
*/
|
||||
export const createVirtualWidget = (
|
||||
client: MatrixClient,
|
||||
id: string,
|
||||
creatorUserId: string,
|
||||
name: string,
|
||||
type: string,
|
||||
url: URL,
|
||||
waitForIframeLoad: boolean,
|
||||
data: IWidgetData,
|
||||
roomId: string
|
||||
): IApp => ({
|
||||
client,
|
||||
id,
|
||||
creatorUserId,
|
||||
name,
|
||||
type,
|
||||
url: url.toString(), // Store URL as string in the definition
|
||||
waitForIframeLoad,
|
||||
data,
|
||||
roomId,
|
||||
// Add other required fields from IWidget if necessary
|
||||
sender: creatorUserId, // Example: Assuming sender is the creator
|
||||
});
|
||||
@@ -1,550 +0,0 @@
|
||||
/* eslint-disable no-param-reassign */
|
||||
/* eslint-disable no-continue */
|
||||
/* eslint-disable class-methods-use-this */
|
||||
|
||||
/*
|
||||
* Copyright 2024 New Vector Ltd.
|
||||
* Copyright 2020-2023 The Matrix.org Foundation C.I.C.
|
||||
*
|
||||
* SPDX-License-Identifier: AGPL-3.0-only OR GPL-3.0-only OR LicenseRef-Element-Commercial
|
||||
* Please see LICENSE files in the repository root for full details.
|
||||
*/
|
||||
import {
|
||||
type Capability,
|
||||
EventDirection,
|
||||
type ISendDelayedEventDetails,
|
||||
type ISendEventDetails,
|
||||
type IReadEventRelationsResult,
|
||||
type IRoomEvent,
|
||||
MatrixCapabilities,
|
||||
type Widget,
|
||||
WidgetDriver,
|
||||
WidgetEventCapability,
|
||||
WidgetKind,
|
||||
type IWidgetApiErrorResponseDataDetails,
|
||||
type ISearchUserDirectoryResult,
|
||||
type IGetMediaConfigResult,
|
||||
UpdateDelayedEventAction,
|
||||
OpenIDRequestState,
|
||||
SimpleObservable,
|
||||
IOpenIDUpdate,
|
||||
} from 'matrix-widget-api';
|
||||
import {
|
||||
EventType,
|
||||
type IContent,
|
||||
MatrixError,
|
||||
type MatrixEvent,
|
||||
Direction,
|
||||
type SendDelayedEventResponse,
|
||||
type StateEvents,
|
||||
type TimelineEvents,
|
||||
MatrixClient,
|
||||
} from '$types/matrix-sdk';
|
||||
|
||||
export class SmallWidgetDriver extends WidgetDriver {
|
||||
private allowedCapabilities: Set<Capability>;
|
||||
|
||||
private readonly mxClient: MatrixClient; // Store the client instance
|
||||
|
||||
public constructor(
|
||||
mx: MatrixClient,
|
||||
allowedCapabilities: Capability[],
|
||||
private forWidget: Widget,
|
||||
private forWidgetKind: WidgetKind,
|
||||
virtual: boolean, // Assuming 'virtual' might be needed later, kept for consistency
|
||||
private inRoomId?: string
|
||||
) {
|
||||
super();
|
||||
this.mxClient = mx; // Store the passed instance
|
||||
|
||||
this.allowedCapabilities = new Set([
|
||||
...allowedCapabilities,
|
||||
MatrixCapabilities.Screenshots,
|
||||
// Add other base capabilities as needed, e.g., ElementWidgetCapabilities.RequiresClient
|
||||
]);
|
||||
|
||||
// --- Capabilities specific to Element Call (or similar trusted widgets) ---
|
||||
// This is a trusted Element Call widget that we control (adjust if not Element Call)
|
||||
this.allowedCapabilities.add(MatrixCapabilities.AlwaysOnScreen);
|
||||
this.allowedCapabilities.add(MatrixCapabilities.MSC3846TurnServers);
|
||||
this.allowedCapabilities.add(MatrixCapabilities.MSC4157SendDelayedEvent);
|
||||
this.allowedCapabilities.add(MatrixCapabilities.MSC4157UpdateDelayedEvent);
|
||||
// Capability to access the room timeline (MSC2762)
|
||||
this.allowedCapabilities.add(`org.matrix.msc2762.timeline:${inRoomId}`);
|
||||
// Capability to read room state (MSC2762)
|
||||
this.allowedCapabilities.add(`org.matrix.msc2762.state:${inRoomId}`);
|
||||
this.allowedCapabilities.add(
|
||||
WidgetEventCapability.forStateEvent(EventDirection.Receive, EventType.RoomMember).raw
|
||||
);
|
||||
this.allowedCapabilities.add(
|
||||
WidgetEventCapability.forStateEvent(EventDirection.Receive, 'org.matrix.msc3401.call').raw
|
||||
);
|
||||
this.allowedCapabilities.add(
|
||||
WidgetEventCapability.forStateEvent(EventDirection.Receive, EventType.RoomEncryption).raw
|
||||
);
|
||||
const clientUserId = this.mxClient.getSafeUserId();
|
||||
// For the legacy membership type
|
||||
this.allowedCapabilities.add(
|
||||
WidgetEventCapability.forStateEvent(
|
||||
EventDirection.Send,
|
||||
'org.matrix.msc3401.call.member',
|
||||
clientUserId
|
||||
).raw
|
||||
);
|
||||
const clientDeviceId = this.mxClient.getDeviceId();
|
||||
if (clientDeviceId !== null) {
|
||||
// For the session membership type compliant with MSC4143
|
||||
this.allowedCapabilities.add(
|
||||
WidgetEventCapability.forStateEvent(
|
||||
EventDirection.Send,
|
||||
'org.matrix.msc3401.call.member',
|
||||
`_${clientUserId}_${clientDeviceId}`
|
||||
).raw
|
||||
);
|
||||
// Version with no leading underscore, for room versions whose auth rules allow it
|
||||
this.allowedCapabilities.add(
|
||||
WidgetEventCapability.forStateEvent(
|
||||
EventDirection.Send,
|
||||
'org.matrix.msc3401.call.member',
|
||||
`${clientUserId}_${clientDeviceId}`
|
||||
).raw
|
||||
);
|
||||
}
|
||||
this.allowedCapabilities.add(
|
||||
WidgetEventCapability.forStateEvent(EventDirection.Receive, 'org.matrix.msc3401.call.member')
|
||||
.raw
|
||||
);
|
||||
// for determining auth rules specific to the room version
|
||||
this.allowedCapabilities.add(
|
||||
WidgetEventCapability.forStateEvent(EventDirection.Receive, EventType.RoomCreate).raw
|
||||
);
|
||||
|
||||
const sendRecvRoomEvents = [
|
||||
'io.element.call.encryption_keys',
|
||||
'org.matrix.rageshake_request',
|
||||
EventType.Reaction,
|
||||
EventType.RoomRedaction,
|
||||
'io.element.call.reaction',
|
||||
];
|
||||
// eslint-disable-next-line no-restricted-syntax
|
||||
for (const eventType of sendRecvRoomEvents) {
|
||||
this.allowedCapabilities.add(
|
||||
WidgetEventCapability.forRoomEvent(EventDirection.Send, eventType).raw
|
||||
);
|
||||
this.allowedCapabilities.add(
|
||||
WidgetEventCapability.forRoomEvent(EventDirection.Receive, eventType).raw
|
||||
);
|
||||
}
|
||||
|
||||
const sendRecvToDevice = [
|
||||
EventType.CallInvite,
|
||||
EventType.CallCandidates,
|
||||
EventType.CallAnswer,
|
||||
EventType.CallHangup,
|
||||
EventType.CallReject,
|
||||
EventType.CallSelectAnswer,
|
||||
EventType.CallNegotiate,
|
||||
EventType.CallSDPStreamMetadataChanged,
|
||||
EventType.CallSDPStreamMetadataChangedPrefix,
|
||||
EventType.CallReplaces,
|
||||
EventType.CallEncryptionKeysPrefix,
|
||||
];
|
||||
// eslint-disable-next-line no-restricted-syntax
|
||||
for (const eventType of sendRecvToDevice) {
|
||||
this.allowedCapabilities.add(
|
||||
WidgetEventCapability.forToDeviceEvent(EventDirection.Send, eventType).raw
|
||||
);
|
||||
this.allowedCapabilities.add(
|
||||
WidgetEventCapability.forToDeviceEvent(EventDirection.Receive, eventType).raw
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
public async validateCapabilities(requested: Set<Capability>): Promise<Set<Capability>> {
|
||||
// Stubbed under the assumption voice calls will be valid thru element-call
|
||||
return requested;
|
||||
}
|
||||
|
||||
public async sendEvent<K extends keyof StateEvents>(
|
||||
eventType: K,
|
||||
content: StateEvents[K],
|
||||
stateKey: string | null,
|
||||
targetRoomId: string | null
|
||||
): Promise<ISendEventDetails>;
|
||||
|
||||
public async sendEvent<K extends keyof TimelineEvents>(
|
||||
eventType: K,
|
||||
content: TimelineEvents[K],
|
||||
stateKey: null,
|
||||
targetRoomId: string | null
|
||||
): Promise<ISendEventDetails>;
|
||||
|
||||
public async sendEvent(
|
||||
eventType: string,
|
||||
content: IContent,
|
||||
stateKey: string | null = null,
|
||||
targetRoomId: string | null = null
|
||||
): Promise<ISendEventDetails> {
|
||||
const client = this.mxClient;
|
||||
const roomId = targetRoomId || this.inRoomId;
|
||||
|
||||
if (!client || !roomId) throw new Error('Not in a room or not attached to a client');
|
||||
|
||||
let r: { event_id: string } | null;
|
||||
if (stateKey !== null) {
|
||||
// state event
|
||||
r = await client.sendStateEvent(
|
||||
roomId,
|
||||
eventType as keyof StateEvents,
|
||||
content as StateEvents[keyof StateEvents],
|
||||
stateKey
|
||||
);
|
||||
} else if (eventType === EventType.RoomRedaction) {
|
||||
// special case: extract the `redacts` property and call redact
|
||||
r = await client.redactEvent(roomId, content.redacts);
|
||||
} else {
|
||||
// message event
|
||||
r = await client.sendEvent(
|
||||
roomId,
|
||||
eventType as keyof TimelineEvents,
|
||||
content as TimelineEvents[keyof TimelineEvents]
|
||||
);
|
||||
}
|
||||
|
||||
return { roomId, eventId: r.event_id };
|
||||
}
|
||||
|
||||
/**
|
||||
* @experimental Part of MSC4140 & MSC4157
|
||||
* @see {@link WidgetDriver#sendDelayedEvent}
|
||||
*/
|
||||
public async sendDelayedEvent<K extends keyof StateEvents>(
|
||||
delay: number | null,
|
||||
parentDelayId: string | null,
|
||||
eventType: K,
|
||||
content: StateEvents[K],
|
||||
stateKey: string | null,
|
||||
targetRoomId: string | null
|
||||
): Promise<ISendDelayedEventDetails>;
|
||||
|
||||
/**
|
||||
* @experimental Part of MSC4140 & MSC4157
|
||||
*/
|
||||
public async sendDelayedEvent<K extends keyof TimelineEvents>(
|
||||
delay: number | null,
|
||||
parentDelayId: string | null,
|
||||
eventType: K,
|
||||
content: TimelineEvents[K],
|
||||
stateKey: null,
|
||||
targetRoomId: string | null
|
||||
): Promise<ISendDelayedEventDetails>;
|
||||
|
||||
public async sendDelayedEvent(
|
||||
delay: number | null,
|
||||
parentDelayId: string | null,
|
||||
eventType: string,
|
||||
content: IContent,
|
||||
stateKey: string | null = null,
|
||||
targetRoomId: string | null = null
|
||||
): Promise<ISendDelayedEventDetails> {
|
||||
const client = this.mxClient;
|
||||
const roomId = targetRoomId || this.inRoomId;
|
||||
|
||||
if (!client || !roomId) throw new Error('Not in a room or not attached to a client');
|
||||
|
||||
let delayOpts;
|
||||
if (delay !== null) {
|
||||
delayOpts = {
|
||||
delay,
|
||||
...(parentDelayId !== null && { parent_delay_id: parentDelayId }),
|
||||
};
|
||||
} else if (parentDelayId !== null) {
|
||||
delayOpts = {
|
||||
parent_delay_id: parentDelayId,
|
||||
};
|
||||
} else {
|
||||
throw new Error('Must provide at least one of delay or parentDelayId');
|
||||
}
|
||||
|
||||
let r: SendDelayedEventResponse | null;
|
||||
if (stateKey !== null) {
|
||||
// state event
|
||||
r = await client._unstable_sendDelayedStateEvent(
|
||||
roomId,
|
||||
delayOpts,
|
||||
eventType as keyof StateEvents,
|
||||
content as StateEvents[keyof StateEvents],
|
||||
stateKey
|
||||
);
|
||||
} else {
|
||||
// message event
|
||||
r = await client._unstable_sendDelayedEvent(
|
||||
roomId,
|
||||
delayOpts,
|
||||
null,
|
||||
eventType as keyof TimelineEvents,
|
||||
content as TimelineEvents[keyof TimelineEvents]
|
||||
);
|
||||
}
|
||||
|
||||
return {
|
||||
roomId,
|
||||
delayId: r.delay_id,
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* @experimental Part of MSC4140 & MSC4157
|
||||
*/
|
||||
public async updateDelayedEvent(
|
||||
delayId: string,
|
||||
action: UpdateDelayedEventAction
|
||||
): Promise<void> {
|
||||
const client = this.mxClient;
|
||||
|
||||
if (!client) throw new Error('Not in a room or not attached to a client');
|
||||
|
||||
await client._unstable_updateDelayedEvent(delayId, action);
|
||||
}
|
||||
|
||||
/**
|
||||
* Implements {@link WidgetDriver#sendToDevice}
|
||||
*/
|
||||
public async sendToDevice(
|
||||
eventType: string,
|
||||
encrypted: boolean,
|
||||
contentMap: Record<string, Record<string, object>>
|
||||
): Promise<void> {
|
||||
const client = this.mxClient;
|
||||
|
||||
if (encrypted) {
|
||||
const crypto = client.getCrypto();
|
||||
if (!crypto) throw new Error('E2EE not enabled');
|
||||
|
||||
// attempt to re-batch these up into a single request
|
||||
const invertedContentMap: Record<string, { userId: string; deviceId: string }[]> = {};
|
||||
|
||||
// eslint-disable-next-line no-restricted-syntax
|
||||
for (const userId of Object.keys(contentMap)) {
|
||||
const userContentMap = contentMap[userId];
|
||||
// eslint-disable-next-line no-restricted-syntax
|
||||
for (const deviceId of Object.keys(userContentMap)) {
|
||||
const content = userContentMap[deviceId];
|
||||
const stringifiedContent = JSON.stringify(content);
|
||||
invertedContentMap[stringifiedContent] = invertedContentMap[stringifiedContent] || [];
|
||||
invertedContentMap[stringifiedContent].push({ userId, deviceId });
|
||||
}
|
||||
}
|
||||
|
||||
await Promise.all(
|
||||
Object.entries(invertedContentMap).map(async ([stringifiedContent, recipients]) => {
|
||||
const batch = await crypto.encryptToDeviceMessages(
|
||||
eventType,
|
||||
recipients,
|
||||
JSON.parse(stringifiedContent)
|
||||
);
|
||||
|
||||
await client.queueToDevice(batch);
|
||||
})
|
||||
);
|
||||
} else {
|
||||
await client.queueToDevice({
|
||||
eventType,
|
||||
batch: Object.entries(contentMap).flatMap(([userId, userContentMap]) =>
|
||||
Object.entries(userContentMap).map(([deviceId, content]) => ({
|
||||
userId,
|
||||
deviceId,
|
||||
payload: content,
|
||||
}))
|
||||
),
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Reads all events of the given type, and optionally `msgtype` (if applicable/defined),
|
||||
* the user has access to. The widget API will have already verified that the widget is
|
||||
* capable of receiving the events. Less events than the limit are allowed to be returned,
|
||||
* but not more.
|
||||
* @param roomId The ID of the room to look within.
|
||||
* @param eventType The event type to be read.
|
||||
* @param msgtype The msgtype of the events to be read, if applicable/defined.
|
||||
* @param stateKey The state key of the events to be read, if applicable/defined.
|
||||
* @param limit The maximum number of events to retrieve. Will be zero to denote "as many as
|
||||
* possible".
|
||||
* @param since When null, retrieves the number of events specified by the "limit" parameter.
|
||||
* Otherwise, the event ID at which only subsequent events will be returned, as many as specified
|
||||
* in "limit".
|
||||
* @returns {Promise<IRoomEvent[]>} Resolves to the room events, or an empty array.
|
||||
*/
|
||||
public async readRoomTimeline(
|
||||
roomId: string,
|
||||
eventType: string,
|
||||
msgtype: string | undefined,
|
||||
stateKey: string | undefined,
|
||||
limit: number,
|
||||
since: string | undefined
|
||||
): Promise<IRoomEvent[]> {
|
||||
limit = limit > 0 ? Math.min(limit, Number.MAX_SAFE_INTEGER) : Number.MAX_SAFE_INTEGER; // relatively arbitrary
|
||||
|
||||
const room = this.mxClient.getRoom(roomId);
|
||||
if (room === null) return [];
|
||||
const results: MatrixEvent[] = [];
|
||||
const events = room.getLiveTimeline().getEvents(); // timelines are most recent last
|
||||
for (let i = events.length - 1; i >= 0; i -= 1) {
|
||||
const ev = events[i];
|
||||
if (results.length >= limit) break;
|
||||
if (since !== undefined && ev.getId() === since) break;
|
||||
|
||||
if (ev.getType() !== eventType || ev.isState()) continue;
|
||||
if (eventType === EventType.RoomMessage && msgtype && msgtype !== ev.getContent().msgtype)
|
||||
continue;
|
||||
if (ev.getStateKey() !== undefined && stateKey !== undefined && ev.getStateKey() !== stateKey)
|
||||
continue;
|
||||
results.push(ev);
|
||||
}
|
||||
|
||||
return results.map((e) => e.getEffectiveEvent() as IRoomEvent);
|
||||
}
|
||||
|
||||
public async askOpenID(observer: SimpleObservable<IOpenIDUpdate>): Promise<void> {
|
||||
return observer.update({
|
||||
state: OpenIDRequestState.Allowed,
|
||||
token: await this.mxClient.getOpenIdToken(),
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* Reads the current values of all matching room state entries.
|
||||
* @param roomId The ID of the room.
|
||||
* @param eventType The event type of the entries to be read.
|
||||
* @param stateKey The state key of the entry to be read. If undefined,
|
||||
* all room state entries with a matching event type should be returned.
|
||||
* @returns {Promise<IRoomEvent[]>} Resolves to the events representing the
|
||||
* current values of the room state entries.
|
||||
*/
|
||||
public async readRoomState(
|
||||
roomId: string,
|
||||
eventType: string,
|
||||
stateKey: string | undefined
|
||||
): Promise<IRoomEvent[]> {
|
||||
const room = this.mxClient.getRoom(roomId);
|
||||
if (room === null) return [];
|
||||
const state = room.getLiveTimeline().getState(Direction.Forward);
|
||||
if (state === undefined) return [];
|
||||
|
||||
if (stateKey === undefined)
|
||||
return state.getStateEvents(eventType).map((e) => e.getEffectiveEvent() as IRoomEvent);
|
||||
const event = state.getStateEvents(eventType, stateKey);
|
||||
return event === null ? [] : [event.getEffectiveEvent() as IRoomEvent];
|
||||
}
|
||||
|
||||
/*
|
||||
public async navigate(uri: string): Promise<void> {
|
||||
navigateToPermalink(uri);
|
||||
}
|
||||
*/
|
||||
|
||||
public async readEventRelations(
|
||||
eventId: string,
|
||||
roomId?: string,
|
||||
relationType?: string,
|
||||
eventType?: string,
|
||||
from?: string,
|
||||
to?: string,
|
||||
limit?: number,
|
||||
direction?: 'f' | 'b'
|
||||
): Promise<IReadEventRelationsResult> {
|
||||
const client = this.mxClient;
|
||||
const dir = direction as Direction;
|
||||
roomId = roomId ?? this.inRoomId ?? undefined;
|
||||
|
||||
if (typeof roomId !== 'string') {
|
||||
throw new Error('Error while reading the current room');
|
||||
}
|
||||
|
||||
const { events, nextBatch, prevBatch } = await client.relations(
|
||||
roomId,
|
||||
eventId,
|
||||
relationType ?? null,
|
||||
eventType ?? null,
|
||||
{ from, to, limit, dir }
|
||||
);
|
||||
|
||||
return {
|
||||
chunk: events.map((e) => e.getEffectiveEvent() as IRoomEvent),
|
||||
nextBatch: nextBatch ?? undefined,
|
||||
prevBatch: prevBatch ?? undefined,
|
||||
};
|
||||
}
|
||||
|
||||
public async searchUserDirectory(
|
||||
searchTerm: string,
|
||||
limit?: number
|
||||
): Promise<ISearchUserDirectoryResult> {
|
||||
const client = this.mxClient;
|
||||
|
||||
const { limited, results } = await client.searchUserDirectory({ term: searchTerm, limit });
|
||||
|
||||
return {
|
||||
limited,
|
||||
results: results.map((r) => ({
|
||||
userId: r.user_id,
|
||||
displayName: r.display_name,
|
||||
avatarUrl: r.avatar_url,
|
||||
})),
|
||||
};
|
||||
}
|
||||
|
||||
public async getMediaConfig(): Promise<IGetMediaConfigResult> {
|
||||
const client = this.mxClient;
|
||||
|
||||
return client.getMediaConfig();
|
||||
}
|
||||
|
||||
public async uploadFile(file: XMLHttpRequestBodyInit): Promise<{ contentUri: string }> {
|
||||
const client = this.mxClient;
|
||||
|
||||
const uploadResult = await client.uploadContent(file);
|
||||
|
||||
return { contentUri: uploadResult.content_uri };
|
||||
}
|
||||
|
||||
/**
|
||||
* Download a file from the media repository on the homeserver.
|
||||
*
|
||||
* @param contentUri - the MXC URI of the file to download
|
||||
* @returns an object with: file - response contents as Blob
|
||||
*/
|
||||
/*
|
||||
public async downloadFile(contentUri: string): Promise<{ file: XMLHttpRequestBodyInit }> {
|
||||
const client = this.mxClient;
|
||||
const media = mediaFromMxc(contentUri, client);
|
||||
const response = await media.downloadSource();
|
||||
const blob = await response.blob();
|
||||
return { file: blob };
|
||||
}
|
||||
*/
|
||||
|
||||
/**
|
||||
* Gets the IDs of all joined or invited rooms currently known to the
|
||||
* client.
|
||||
* @returns The room IDs.
|
||||
*/
|
||||
public getKnownRooms(): string[] {
|
||||
return this.mxClient.getVisibleRooms().map((r) => r.roomId);
|
||||
}
|
||||
|
||||
/**
|
||||
* Expresses a {@link MatrixError} as a JSON payload
|
||||
* for use by Widget API error responses.
|
||||
* @param error The error to handle.
|
||||
* @returns The error expressed as a JSON payload,
|
||||
* or undefined if it is not a {@link MatrixError}.
|
||||
*/
|
||||
public processError(error: unknown): IWidgetApiErrorResponseDataDetails | undefined {
|
||||
return error instanceof MatrixError
|
||||
? { matrix_api_error: error.asWidgetApiErrorData() }
|
||||
: undefined;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,20 @@
|
||||
import { style } from '@vanilla-extract/css';
|
||||
import { config, toRem } from 'folds';
|
||||
|
||||
export const CallViewContent = style({
|
||||
padding: config.space.S400,
|
||||
paddingRight: 0,
|
||||
minHeight: '100%',
|
||||
});
|
||||
|
||||
export const ControlCard = style({
|
||||
padding: config.space.S300,
|
||||
});
|
||||
|
||||
export const ControlDivider = style({
|
||||
height: toRem(24),
|
||||
});
|
||||
|
||||
export const CallMemberCard = style({
|
||||
padding: config.space.S300,
|
||||
});
|
||||
@@ -54,7 +54,9 @@ function CreateRoomModal({ state }: CreateRoomModalProps) {
|
||||
}}
|
||||
>
|
||||
<Box grow="Yes">
|
||||
<Text size="H4">New {type === CreateRoomType.VoiceRoom && 'Voice '}Room</Text>
|
||||
<Text size="H4">
|
||||
{type === CreateRoomType.VoiceRoom ? 'New Voice Room' : 'New Chat Room'}
|
||||
</Text>
|
||||
</Box>
|
||||
<Box shrink="No">
|
||||
<IconButton size="300" radii="300" onClick={closeDialog}>
|
||||
|
||||
@@ -33,6 +33,7 @@ import { useOpenCreateRoomModal } from '$state/hooks/createRoomModal';
|
||||
import { useOpenCreateSpaceModal } from '$state/hooks/createSpaceModal';
|
||||
import { CreateRoomType } from '$components/create-room/types';
|
||||
import { AddExistingModal } from '$features/add-existing';
|
||||
import { BetaNoticeBadge } from '$components/BetaNoticeBadge';
|
||||
import { useDraggableItem } from './DnD';
|
||||
import * as styleCss from './style.css';
|
||||
import * as css from './SpaceItem.css';
|
||||
@@ -283,7 +284,17 @@ function AddRoomButton({ item }: { item: HierarchyItem }) {
|
||||
fill="None"
|
||||
onClick={() => handleCreateRoom(CreateRoomType.TextRoom)}
|
||||
>
|
||||
<Text size="T300">New Room</Text>
|
||||
<Text size="T300">Chat Room</Text>
|
||||
</MenuItem>
|
||||
<MenuItem
|
||||
size="300"
|
||||
radii="300"
|
||||
variant="Primary"
|
||||
fill="None"
|
||||
onClick={() => handleCreateRoom(CreateRoomType.VoiceRoom)}
|
||||
after={<BetaNoticeBadge />}
|
||||
>
|
||||
<Text size="T300">Voice Room</Text>
|
||||
</MenuItem>
|
||||
<MenuItem
|
||||
size="300"
|
||||
|
||||
@@ -214,7 +214,12 @@ export function SearchResultGroup({
|
||||
src={getRoomAvatarUrl(mx, room, 96, useAuthentication)}
|
||||
alt={room.name}
|
||||
renderFallback={() => (
|
||||
<RoomIcon size="50" joinRule={room.getJoinRule() ?? JoinRule.Restricted} filled />
|
||||
<RoomIcon
|
||||
size="50"
|
||||
roomType={room.getType()}
|
||||
joinRule={room.getJoinRule() ?? JoinRule.Restricted}
|
||||
filled
|
||||
/>
|
||||
)}
|
||||
/>
|
||||
</Avatar>
|
||||
|
||||
@@ -1,21 +0,0 @@
|
||||
import { style } from '@vanilla-extract/css';
|
||||
import { config } from 'folds';
|
||||
|
||||
export const Actions = style({
|
||||
padding: config.space.S200,
|
||||
});
|
||||
|
||||
export const RoomButtonWrap = style({
|
||||
minWidth: 0,
|
||||
});
|
||||
|
||||
export const RoomButton = style({
|
||||
width: '100%',
|
||||
minWidth: 0,
|
||||
padding: `0 ${config.space.S200}`,
|
||||
});
|
||||
|
||||
export const RoomName = style({
|
||||
flexGrow: 1,
|
||||
minWidth: 0,
|
||||
});
|
||||
@@ -1,128 +0,0 @@
|
||||
import {
|
||||
Box,
|
||||
Chip,
|
||||
Icon,
|
||||
IconButton,
|
||||
Icons,
|
||||
Line,
|
||||
Spinner,
|
||||
Text,
|
||||
Tooltip,
|
||||
TooltipProvider,
|
||||
color,
|
||||
} from 'folds';
|
||||
import { useCallState } from '$pages/client/call/CallProvider';
|
||||
import { useRoomNavigate } from '$hooks/useRoomNavigate';
|
||||
import * as css from './RoomCallNavStatus.css';
|
||||
|
||||
export function CallNavStatus() {
|
||||
const {
|
||||
activeCallRoomId,
|
||||
isActiveCallReady,
|
||||
isAudioEnabled,
|
||||
isVideoEnabled,
|
||||
toggleAudio,
|
||||
toggleVideo,
|
||||
hangUp,
|
||||
} = useCallState();
|
||||
const { navigateRoom } = useRoomNavigate();
|
||||
const hasActiveCall = Boolean(activeCallRoomId);
|
||||
const isConnected = hasActiveCall && isActiveCallReady;
|
||||
const handleGoToCallRoom = () => {
|
||||
if (activeCallRoomId) {
|
||||
navigateRoom(activeCallRoomId);
|
||||
}
|
||||
};
|
||||
|
||||
return (
|
||||
<Box direction="Column" shrink="No">
|
||||
<Line variant="Surface" size="300" />
|
||||
<Box className={css.Actions} direction="Row" alignItems="Center" gap="100">
|
||||
<Box className={css.RoomButtonWrap} grow="Yes">
|
||||
{hasActiveCall && (
|
||||
<TooltipProvider
|
||||
position="Top"
|
||||
offset={4}
|
||||
tooltip={
|
||||
<Tooltip>
|
||||
<Text>Go to Room</Text>
|
||||
</Tooltip>
|
||||
}
|
||||
>
|
||||
{(triggerRef) => (
|
||||
<Chip
|
||||
size="500"
|
||||
fill="Soft"
|
||||
as="button"
|
||||
onClick={handleGoToCallRoom}
|
||||
ref={triggerRef}
|
||||
className={css.RoomButton}
|
||||
>
|
||||
{isConnected ? (
|
||||
<Icon size="300" src={Icons.VolumeHigh} style={{ color: color.Success.Main }} />
|
||||
) : (
|
||||
<Spinner size="300" variant="Secondary" />
|
||||
)}
|
||||
<Text
|
||||
as="span"
|
||||
size="L400"
|
||||
style={{ color: isConnected ? color.Success.Main : color.Warning.Main }}
|
||||
>
|
||||
{isConnected ? 'Connected' : 'Connecting'}
|
||||
</Text>
|
||||
</Chip>
|
||||
)}
|
||||
</TooltipProvider>
|
||||
)}
|
||||
</Box>
|
||||
{hasActiveCall && (
|
||||
<TooltipProvider
|
||||
position="Top"
|
||||
offset={4}
|
||||
tooltip={
|
||||
<Tooltip>
|
||||
<Text>Hang Up</Text>
|
||||
</Tooltip>
|
||||
}
|
||||
>
|
||||
{(triggerRef) => (
|
||||
<IconButton fill="None" size="300" ref={triggerRef} onClick={hangUp}>
|
||||
<Icon src={Icons.PhoneDown} />
|
||||
</IconButton>
|
||||
)}
|
||||
</TooltipProvider>
|
||||
)}
|
||||
<TooltipProvider
|
||||
position="Top"
|
||||
offset={4}
|
||||
tooltip={
|
||||
<Tooltip>
|
||||
<Text>{!isAudioEnabled ? 'Unmute' : 'Mute'}</Text>
|
||||
</Tooltip>
|
||||
}
|
||||
>
|
||||
{(triggerRef) => (
|
||||
<IconButton fill="None" size="300" ref={triggerRef} onClick={toggleAudio}>
|
||||
<Icon src={!isAudioEnabled ? Icons.MicMute : Icons.Mic} />
|
||||
</IconButton>
|
||||
)}
|
||||
</TooltipProvider>
|
||||
<TooltipProvider
|
||||
position="Top"
|
||||
offset={4}
|
||||
tooltip={
|
||||
<Tooltip>
|
||||
<Text>{!isVideoEnabled ? 'Video On' : 'Video Off'}</Text>
|
||||
</Tooltip>
|
||||
}
|
||||
>
|
||||
{(triggerRef) => (
|
||||
<IconButton fill="None" size="300" ref={triggerRef} onClick={toggleVideo}>
|
||||
<Icon src={!isVideoEnabled ? Icons.VideoCameraMute : Icons.VideoCamera} />
|
||||
</IconButton>
|
||||
)}
|
||||
</TooltipProvider>
|
||||
</Box>
|
||||
</Box>
|
||||
);
|
||||
}
|
||||
@@ -1,5 +1,5 @@
|
||||
import { MouseEventHandler, forwardRef, useState, MouseEvent, useEffect } from 'react';
|
||||
import { EventType, Room, RoomEvent as RoomEventEnum } from '$types/matrix-sdk';
|
||||
import { Room, RoomEvent as RoomEventEnum } from '$types/matrix-sdk';
|
||||
import {
|
||||
Avatar,
|
||||
Box,
|
||||
@@ -21,6 +21,7 @@ import {
|
||||
} from 'folds';
|
||||
import { useFocusWithin, useHover } from 'react-aria';
|
||||
import FocusTrap from 'focus-trap-react';
|
||||
import { useAtom, useAtomValue } from 'jotai';
|
||||
import { useNavigate } from 'react-router-dom';
|
||||
import { NavButton, NavItem, NavItemContent, NavItemOptions } from '$components/nav';
|
||||
import { UnreadBadge, UnreadBadgeCenter } from '$components/unread-badge';
|
||||
@@ -54,13 +55,17 @@ import { RoomNotificationModeSwitcher } from '$components/RoomNotificationSwitch
|
||||
import { useRoomCreators } from '$hooks/useRoomCreators';
|
||||
import { useRoomPermissions } from '$hooks/useRoomPermissions';
|
||||
import { InviteUserPrompt } from '$components/invite-user-prompt';
|
||||
import { useCallState } from '$pages/client/call/CallProvider';
|
||||
import { useCallMembers } from '$hooks/useCallMemberships';
|
||||
import { useRoomNavigate } from '$hooks/useRoomNavigate';
|
||||
import { ScreenSize, useScreenSizeContext } from '$hooks/useScreenSize';
|
||||
import { useRoomName } from '$hooks/useRoomMeta';
|
||||
import { useAtomValue } from 'jotai';
|
||||
import { nicknamesAtom } from '$state/nicknames';
|
||||
import { useRoomNavigate } from '$hooks/useRoomNavigate';
|
||||
|
||||
// Upstream Call Hooks
|
||||
import { useCallMembers, useCallSession } from '$hooks/useCall';
|
||||
import { useCallEmbed, useCallStart } from '$hooks/useCallEmbed';
|
||||
import { callChatAtom } from '$state/callEmbed';
|
||||
import { useCallPreferencesAtom } from '$state/hooks/callPreferences';
|
||||
import { CallControlState } from '$plugins/call/CallControlState';
|
||||
import { RoomNavUser } from './RoomNavUser';
|
||||
|
||||
/**
|
||||
@@ -90,10 +95,11 @@ type RoomNavItemMenuProps = {
|
||||
requestClose: () => void;
|
||||
notificationMode?: RoomNotificationMode;
|
||||
};
|
||||
|
||||
const RoomNavItemMenu = forwardRef<HTMLDivElement, RoomNavItemMenuProps>(
|
||||
({ room, requestClose, notificationMode }, ref) => {
|
||||
const mx = useMatrixClient();
|
||||
const [hideActivity] = useSetting(settingsAtom, 'hideActivity');
|
||||
const [hideReads] = useSetting(settingsAtom, 'hideReads');
|
||||
const unread = useRoomUnread(room.roomId, roomToUnreadAtom);
|
||||
const powerLevels = usePowerLevels(room);
|
||||
const creators = useRoomCreators(room);
|
||||
@@ -106,7 +112,7 @@ const RoomNavItemMenu = forwardRef<HTMLDivElement, RoomNavItemMenuProps>(
|
||||
const [invitePrompt, setInvitePrompt] = useState(false);
|
||||
|
||||
const handleMarkAsRead = () => {
|
||||
markAsRead(mx, room.roomId, hideActivity);
|
||||
markAsRead(mx, room.roomId, hideReads);
|
||||
requestClose();
|
||||
};
|
||||
|
||||
@@ -250,6 +256,7 @@ type RoomNavItemProps = {
|
||||
showAvatar?: boolean;
|
||||
direct?: boolean;
|
||||
};
|
||||
|
||||
export function RoomNavItem({
|
||||
room,
|
||||
selected,
|
||||
@@ -264,41 +271,35 @@ export function RoomNavItem({
|
||||
const { hoverProps } = useHover({ onHoverChange: setHover });
|
||||
const { focusWithinProps } = useFocusWithin({ onFocusWithinChange: setHover });
|
||||
const [menuAnchor, setMenuAnchor] = useState<RectCords>();
|
||||
|
||||
const unread = useRoomUnread(room.roomId, roomToUnreadAtom);
|
||||
const hasRoomUnread = useRoomHasUnread(room);
|
||||
const typingMember = useRoomTypingMember(room.roomId).filter(
|
||||
(receipt) => receipt.userId !== mx.getUserId()
|
||||
);
|
||||
|
||||
const {
|
||||
isActiveCallReady,
|
||||
activeCallRoomId,
|
||||
setActiveCallRoomId,
|
||||
setViewedCallRoomId,
|
||||
isChatOpen,
|
||||
toggleChat,
|
||||
hangUp,
|
||||
} = useCallState();
|
||||
|
||||
const isActiveCall = isActiveCallReady && activeCallRoomId === room.roomId;
|
||||
const callMemberships = useCallMembers(mx, room.roomId);
|
||||
|
||||
const powerLevels = usePowerLevels(room);
|
||||
const creators = useRoomCreators(room);
|
||||
// Name Resolution
|
||||
const nicknames = useAtomValue(nicknamesAtom);
|
||||
const dmUserId = direct ? room.getAvatarFallbackMember()?.userId : undefined;
|
||||
const matrixRoomName = useRoomName(room);
|
||||
const roomName = (dmUserId && nicknames[dmUserId]) || matrixRoomName;
|
||||
|
||||
const permissions = useRoomPermissions(creators, powerLevels);
|
||||
const canJoinCall = permissions.event(EventType.GroupCallMemberPrefix, mx.getSafeUserId());
|
||||
|
||||
// Navigation & Context
|
||||
const { navigateRoom } = useRoomNavigate();
|
||||
const navigate = useNavigate();
|
||||
|
||||
const screenSize = useScreenSizeContext();
|
||||
const isMobile = screenSize === ScreenSize.Mobile;
|
||||
|
||||
// Call Hooks (Merged from upstream)
|
||||
const callSession = useCallSession(room);
|
||||
const callMembers = useCallMembers(room, callSession);
|
||||
const startCall = useCallStart(direct);
|
||||
const callEmbed = useCallEmbed();
|
||||
const callPref = useAtomValue(useCallPreferencesAtom());
|
||||
const [isChatOpen, setChatOpen] = useAtom(callChatAtom);
|
||||
|
||||
const isActiveCall = callEmbed?.roomId === room.roomId;
|
||||
|
||||
const handleContextMenu: MouseEventHandler<HTMLElement> = (evt) => {
|
||||
evt.preventDefault();
|
||||
setMenuAnchor({
|
||||
@@ -316,16 +317,17 @@ export function RoomNavItem({
|
||||
const handleNavItemClick: MouseEventHandler<HTMLElement> = (evt) => {
|
||||
if (room.isCallRoom()) {
|
||||
if (!isMobile) {
|
||||
if (!isActiveCall && canJoinCall) {
|
||||
hangUp();
|
||||
setActiveCallRoomId(room.roomId);
|
||||
if (!isActiveCall && !callEmbed) {
|
||||
startCall(
|
||||
room,
|
||||
new CallControlState(callPref.microphone, callPref.video, callPref.sound)
|
||||
);
|
||||
} else {
|
||||
navigateRoom(room.roomId);
|
||||
}
|
||||
} else {
|
||||
evt.stopPropagation();
|
||||
if (isChatOpen) toggleChat();
|
||||
setViewedCallRoomId(room.roomId);
|
||||
if (isChatOpen) setChatOpen(false);
|
||||
navigateRoom(room.roomId);
|
||||
}
|
||||
} else {
|
||||
@@ -335,8 +337,7 @@ export function RoomNavItem({
|
||||
|
||||
const handleChatButtonClick = (evt: MouseEvent<HTMLButtonElement>) => {
|
||||
evt.stopPropagation();
|
||||
toggleChat();
|
||||
setViewedCallRoomId(room.roomId);
|
||||
setChatOpen(!isChatOpen);
|
||||
navigate(linkPath);
|
||||
};
|
||||
|
||||
@@ -345,13 +346,14 @@ export function RoomNavItem({
|
||||
if (unread) {
|
||||
unreadCount = unread.highlight > 0 ? unread.highlight : unread.total;
|
||||
}
|
||||
|
||||
const ariaLabel = [
|
||||
roomName,
|
||||
room.isCallRoom()
|
||||
? [
|
||||
'Call Room',
|
||||
isActiveCall && 'Currently in Call',
|
||||
callMemberships.length && `${callMemberships.length} in Call`,
|
||||
callMembers.length && `${callMembers.length} in Call`,
|
||||
]
|
||||
: 'Text Room',
|
||||
unread?.total && `${unread.total} Messages`,
|
||||
@@ -424,7 +426,11 @@ export function RoomNavItem({
|
||||
)}
|
||||
{!optionsVisible && (unread || hasRoomUnread) && (
|
||||
<UnreadBadgeCenter>
|
||||
<UnreadBadge highlight={!!unread && unread.highlight > 0} count={unreadCount} />
|
||||
<UnreadBadge
|
||||
highlight={!!unread && unread.highlight > 0}
|
||||
count={unreadCount}
|
||||
dm={direct}
|
||||
/>
|
||||
</UnreadBadgeCenter>
|
||||
)}
|
||||
{!optionsVisible && notificationMode !== RoomNotificationMode.Unset && (
|
||||
@@ -434,11 +440,45 @@ export function RoomNavItem({
|
||||
aria-label={notificationMode}
|
||||
/>
|
||||
)}
|
||||
{room.isCallRoom() && callMembers.length > 0 && !optionsVisible && (
|
||||
<Badge variant="Critical" fill="Solid" size="400">
|
||||
<Text as="span" size="L400" truncate>
|
||||
{callMembers.length} Live
|
||||
</Text>
|
||||
</Badge>
|
||||
)}
|
||||
</Box>
|
||||
</NavItemContent>
|
||||
</NavButton>
|
||||
{optionsVisible && (
|
||||
<NavItemOptions>
|
||||
{room.isCallRoom() && (
|
||||
<TooltipProvider
|
||||
position="Bottom"
|
||||
offset={4}
|
||||
tooltip={
|
||||
<Tooltip>
|
||||
<Text>{isChatOpen ? 'Hide Chat' : 'Show Chat'}</Text>
|
||||
</Tooltip>
|
||||
}
|
||||
>
|
||||
{(triggerRef) => (
|
||||
<IconButton
|
||||
ref={triggerRef}
|
||||
data-testid="chat-button"
|
||||
onClick={handleChatButtonClick}
|
||||
aria-pressed={isChatOpen && selected}
|
||||
aria-label="Open Chat"
|
||||
variant="Background"
|
||||
fill="None"
|
||||
size="300"
|
||||
radii="300"
|
||||
>
|
||||
<Icon size="50" src={Icons.Message} filled={isChatOpen} />
|
||||
</IconButton>
|
||||
)}
|
||||
</TooltipProvider>
|
||||
)}
|
||||
<PopOut
|
||||
id={`menu-${room.roomId}`}
|
||||
aria-expanded={!!menuAnchor}
|
||||
@@ -467,33 +507,6 @@ export function RoomNavItem({
|
||||
</FocusTrap>
|
||||
}
|
||||
>
|
||||
{room.isCallRoom() && (
|
||||
<TooltipProvider
|
||||
position="Bottom"
|
||||
offset={4}
|
||||
tooltip={
|
||||
<Tooltip>
|
||||
<Text>{isChatOpen ? 'Hide Chat' : 'Show Chat'}</Text>
|
||||
</Tooltip>
|
||||
}
|
||||
>
|
||||
{(triggerRef) => (
|
||||
<IconButton
|
||||
ref={triggerRef}
|
||||
data-testid="chat-button"
|
||||
onClick={handleChatButtonClick}
|
||||
aria-pressed={isChatOpen && selected}
|
||||
aria-label="Open Chat"
|
||||
variant="Background"
|
||||
fill="None"
|
||||
size="300"
|
||||
radii="300"
|
||||
>
|
||||
<Icon size="50" src={Icons.Message} />
|
||||
</IconButton>
|
||||
)}
|
||||
</TooltipProvider>
|
||||
)}
|
||||
<IconButton
|
||||
onClick={handleOpenMenu}
|
||||
aria-pressed={!!menuAnchor}
|
||||
@@ -510,9 +523,10 @@ export function RoomNavItem({
|
||||
</NavItemOptions>
|
||||
)}
|
||||
</NavItem>
|
||||
|
||||
{room.isCallRoom() && (
|
||||
<Box direction="Column" style={{ paddingLeft: config.space.S200 }}>
|
||||
{callMemberships.map((callMembership) => (
|
||||
{callMembers.map((callMembership) => (
|
||||
<RoomNavUser
|
||||
key={callMembership.membershipID}
|
||||
room={room}
|
||||
|
||||
@@ -1,29 +1,32 @@
|
||||
import { Avatar, Box, Icon, Icons, Text } from 'folds';
|
||||
import { MouseEventHandler } from 'react';
|
||||
import { useAtomValue } from 'jotai';
|
||||
import { Room, CallMembership } from '$types/matrix-sdk';
|
||||
import { NavButton, NavItem, NavItemContent } from '$components/nav';
|
||||
import { UserAvatar } from '$components/user-avatar';
|
||||
import { useMatrixClient } from '$hooks/useMatrixClient';
|
||||
import { useCallState } from '$pages/client/call/CallProvider';
|
||||
import { getMxIdLocalPart } from '$utils/matrix';
|
||||
import { getMemberAvatarMxc, getMemberDisplayName } from '$utils/room';
|
||||
import { useMediaAuthentication } from '$hooks/useMediaAuthentication';
|
||||
import { useOpenUserRoomProfile } from '$state/hooks/userRoomProfile';
|
||||
import { useSpaceOptionally } from '$hooks/useSpace';
|
||||
import { useAtomValue } from 'jotai';
|
||||
import { nicknamesAtom } from '$state/nicknames';
|
||||
import { useCallEmbed } from '$hooks/useCallEmbed';
|
||||
|
||||
type RoomNavUserProps = {
|
||||
room: Room;
|
||||
callMembership: CallMembership;
|
||||
};
|
||||
|
||||
export function RoomNavUser({ room, callMembership }: RoomNavUserProps) {
|
||||
const mx = useMatrixClient();
|
||||
const useAuthentication = useMediaAuthentication();
|
||||
const openProfile = useOpenUserRoomProfile();
|
||||
const space = useSpaceOptionally();
|
||||
const { isActiveCallReady, activeCallRoomId } = useCallState();
|
||||
const isActiveCall = isActiveCallReady && activeCallRoomId === room.roomId;
|
||||
|
||||
const callEmbed = useCallEmbed();
|
||||
const isActiveCall = callEmbed?.roomId === room.roomId;
|
||||
|
||||
const userId = callMembership.sender ?? '';
|
||||
const avatarMxcUrl = getMemberAvatarMxc(room, userId);
|
||||
const avatarUrl = avatarMxcUrl
|
||||
|
||||
@@ -67,6 +67,7 @@ type RoomSettingsProps = {
|
||||
initialPage?: RoomSettingsPage;
|
||||
requestClose: () => void;
|
||||
};
|
||||
|
||||
export function RoomSettings({ initialPage, requestClose }: RoomSettingsProps) {
|
||||
const room = useRoom();
|
||||
const mx = useMatrixClient();
|
||||
@@ -118,6 +119,7 @@ export function RoomSettings({ initialPage, requestClose }: RoomSettingsProps) {
|
||||
renderFallback={() => (
|
||||
<RoomIcon
|
||||
size="50"
|
||||
roomType={room.getType()}
|
||||
joinRule={joinRuleContent?.join_rule ?? JoinRule.Invite}
|
||||
filled
|
||||
/>
|
||||
|
||||
@@ -0,0 +1,56 @@
|
||||
import { useSetAtom } from 'jotai';
|
||||
import { useParams } from 'react-router-dom';
|
||||
import { Box, Text, TooltipProvider, Tooltip, Icon, Icons, IconButton, toRem } from 'folds';
|
||||
import { Page, PageHeader } from '../../components/page';
|
||||
import { callChatAtom } from '../../state/callEmbed';
|
||||
import { RoomView } from './RoomView';
|
||||
import { ScreenSize, useScreenSizeContext } from '../../hooks/useScreenSize';
|
||||
|
||||
export function CallChatView() {
|
||||
const { eventId } = useParams();
|
||||
const setChat = useSetAtom(callChatAtom);
|
||||
const screenSize = useScreenSizeContext();
|
||||
|
||||
const handleClose = () => setChat(false);
|
||||
|
||||
return (
|
||||
<Page
|
||||
style={{
|
||||
width: screenSize === ScreenSize.Desktop ? toRem(456) : '100%',
|
||||
flexShrink: 0,
|
||||
flexGrow: 0,
|
||||
}}
|
||||
>
|
||||
<PageHeader>
|
||||
<Box grow="Yes" alignItems="Center" gap="200">
|
||||
<Box grow="Yes">
|
||||
<Text size="H5" truncate>
|
||||
Chat
|
||||
</Text>
|
||||
</Box>
|
||||
<Box shrink="No" alignItems="Center">
|
||||
<TooltipProvider
|
||||
position="Bottom"
|
||||
align="End"
|
||||
offset={4}
|
||||
tooltip={
|
||||
<Tooltip>
|
||||
<Text>Close</Text>
|
||||
</Tooltip>
|
||||
}
|
||||
>
|
||||
{(triggerRef) => (
|
||||
<IconButton ref={triggerRef} variant="Surface" onClick={handleClose}>
|
||||
<Icon src={Icons.Cross} />
|
||||
</IconButton>
|
||||
)}
|
||||
</TooltipProvider>
|
||||
</Box>
|
||||
</Box>
|
||||
</PageHeader>
|
||||
<Box grow="Yes" direction="Column">
|
||||
<RoomView eventId={eventId} />
|
||||
</Box>
|
||||
</Page>
|
||||
);
|
||||
}
|
||||
@@ -12,11 +12,13 @@ import { markAsRead } from '$utils/notifications';
|
||||
import { useMatrixClient } from '$hooks/useMatrixClient';
|
||||
import { useRoomMembers } from '$hooks/useRoomMembers';
|
||||
import { CallView } from '$features/call/CallView';
|
||||
import { useCallState } from '$pages/client/call/CallProvider';
|
||||
import { WidgetsDrawer } from '$features/widgets/WidgetsDrawer';
|
||||
import { useAtomValue } from 'jotai';
|
||||
import { callChatAtom } from '$state/callEmbed';
|
||||
import { RoomViewHeader } from './RoomViewHeader';
|
||||
import { MembersDrawer } from './MembersDrawer';
|
||||
import { RoomView } from './RoomView';
|
||||
import { CallChatView } from './CallChatView';
|
||||
|
||||
export function Room() {
|
||||
const { eventId } = useParams();
|
||||
@@ -25,38 +27,55 @@ export function Room() {
|
||||
|
||||
const [isDrawer] = useSetting(settingsAtom, 'isPeopleDrawer');
|
||||
const [isWidgetDrawerOpen] = useSetting(settingsAtom, 'isWidgetDrawer');
|
||||
const [hideActivity] = useSetting(settingsAtom, 'hideActivity');
|
||||
const [hideReads] = useSetting(settingsAtom, 'hideReads');
|
||||
const screenSize = useScreenSizeContext();
|
||||
const powerLevels = usePowerLevels(room);
|
||||
const members = useRoomMembers(mx, room.roomId);
|
||||
const { isChatOpen } = useCallState();
|
||||
const chat = useAtomValue(callChatAtom);
|
||||
|
||||
useKeyDown(
|
||||
window,
|
||||
useCallback(
|
||||
(evt) => {
|
||||
if (isKeyHotkey('escape', evt)) {
|
||||
markAsRead(mx, room.roomId, hideActivity);
|
||||
markAsRead(mx, room.roomId, hideReads);
|
||||
}
|
||||
},
|
||||
[mx, room.roomId, hideActivity]
|
||||
[mx, room.roomId, hideReads]
|
||||
)
|
||||
);
|
||||
|
||||
const callView = room.isCallRoom();
|
||||
|
||||
return (
|
||||
<PowerLevelsContextProvider value={powerLevels}>
|
||||
<Box grow="Yes">
|
||||
<Box grow="Yes" direction="Column">
|
||||
<RoomViewHeader />
|
||||
<Box grow="Yes">
|
||||
<CallView room={room} />
|
||||
{room.isCallRoom() && screenSize === ScreenSize.Desktop && isChatOpen && (
|
||||
{callView && (screenSize === ScreenSize.Desktop || !chat) && (
|
||||
<Box grow="Yes" direction="Column">
|
||||
<RoomViewHeader callView />
|
||||
<Box grow="Yes">
|
||||
<CallView />
|
||||
</Box>
|
||||
</Box>
|
||||
)}
|
||||
{!callView && (
|
||||
<Box grow="Yes" direction="Column">
|
||||
<RoomViewHeader />
|
||||
<Box grow="Yes">
|
||||
<RoomView eventId={eventId} />
|
||||
</Box>
|
||||
</Box>
|
||||
)}
|
||||
|
||||
{callView && chat && (
|
||||
<>
|
||||
{screenSize === ScreenSize.Desktop && (
|
||||
<Line variant="Background" direction="Vertical" size="300" />
|
||||
)}
|
||||
{(!room.isCallRoom() || isChatOpen) && <RoomView room={room} eventId={eventId} />}
|
||||
</Box>
|
||||
</Box>
|
||||
{screenSize === ScreenSize.Desktop && isDrawer && (
|
||||
<CallChatView />
|
||||
</>
|
||||
)}
|
||||
{!callView && screenSize === ScreenSize.Desktop && isDrawer && (
|
||||
<>
|
||||
<Line variant="Background" direction="Vertical" size="300" />
|
||||
<MembersDrawer key={room.roomId} room={room} members={members} />
|
||||
|
||||
@@ -219,6 +219,8 @@ export const RoomInput = forwardRef<HTMLDivElement, RoomInputProps>(
|
||||
selectedFiles.map((f) => f.file)
|
||||
);
|
||||
const uploadBoardHandlers = useRef<UploadBoardImperativeHandlers>();
|
||||
const longPressTimer = useRef<ReturnType<typeof setTimeout> | null>(null);
|
||||
const isLongPress = useRef(false);
|
||||
|
||||
const imagePackRooms: Room[] = useImagePackRooms(roomId, roomToParents);
|
||||
|
||||
@@ -298,25 +300,30 @@ export const RoomInput = forwardRef<HTMLDivElement, RoomInputProps>(
|
||||
format: replyFormat,
|
||||
} = replyEvent?.getContent() ?? {};
|
||||
|
||||
// Prefer the live event content; fall back to what was snapshotted in the
|
||||
// draft when the user hit Reply (the event may not be in SDK state if it
|
||||
// was redacted or evicted, but the draft always carries the original body).
|
||||
const htmlBody =
|
||||
replyFormat === 'org.matrix.custom.html' ? replyFormattedBody : replyDraft?.formattedBody;
|
||||
const plainBody = replyBody ?? replyDraft?.body;
|
||||
|
||||
let replyBodyJSX: ReactNode = replyDraft ? trimReplyFromBody(replyDraft.body) : null;
|
||||
|
||||
if (replyFormat === 'org.matrix.custom.html' && replyFormattedBody) {
|
||||
const strippedHtml = trimReplyFromFormattedBody(replyFormattedBody)
|
||||
if (htmlBody) {
|
||||
const strippedHtml = trimReplyFromFormattedBody(htmlBody)
|
||||
.replace(/<br\s*\/?>/gi, ' ')
|
||||
.replace(/<\/p>\s*<p[^>]*>/gi, ' ')
|
||||
.replace(/<\/?p[^>]*>/gi, '')
|
||||
.replace(/(?:\r\n|\r|\n)/g, ' ');
|
||||
const parserOpts = getReactCustomHtmlParser(mx, roomId, {
|
||||
linkifyOpts: LINKIFY_OPTS,
|
||||
useAuthentication,
|
||||
nicknames,
|
||||
});
|
||||
replyBodyJSX = parse(strippedHtml, parserOpts);
|
||||
} else if (replyBody) {
|
||||
const strippedBody = trimReplyFromBody(replyBody).replace(/(?:\r\n|\r|\n)/g, ' ');
|
||||
replyBodyJSX = scaleSystemEmoji(trimReplyFromBody(strippedBody));
|
||||
} else if (replyDraft) {
|
||||
const strippedBody = trimReplyFromBody(replyDraft.body).replace(/(?:\r\n|\r|\n)/g, ' ');
|
||||
replyBodyJSX = scaleSystemEmoji(trimReplyFromBody(strippedBody));
|
||||
} else if (plainBody) {
|
||||
const strippedBody = trimReplyFromBody(plainBody).replace(/(?:\r\n|\r|\n)/g, ' ');
|
||||
replyBodyJSX = scaleSystemEmoji(strippedBody);
|
||||
}
|
||||
|
||||
useEffect(() => {
|
||||
@@ -347,7 +354,16 @@ export const RoomInput = forwardRef<HTMLDivElement, RoomInputProps>(
|
||||
},
|
||||
[setSelectedFiles]
|
||||
);
|
||||
|
||||
const setDesc = useCallback(
|
||||
(fileItem: TUploadItem, body: string, formatted_body: string) => {
|
||||
setSelectedFiles({
|
||||
type: 'REPLACE',
|
||||
item: fileItem,
|
||||
replacement: { ...fileItem, body, formatted_body },
|
||||
});
|
||||
},
|
||||
[setSelectedFiles]
|
||||
);
|
||||
const handleRemoveUpload = useCallback(
|
||||
(upload: TUploadContent | TUploadContent[]) => {
|
||||
const uploads = Array.isArray(upload) ? upload : [upload];
|
||||
@@ -370,7 +386,8 @@ export const RoomInput = forwardRef<HTMLDivElement, RoomInputProps>(
|
||||
};
|
||||
|
||||
const handleSendUpload = async (uploads: UploadSuccess[]) => {
|
||||
const plaintext = toPlainText(editor.children, isMarkdown).trim();
|
||||
const plainText = toPlainText(editor.children, isMarkdown).trim();
|
||||
|
||||
const contentsPromises = uploads.map(async (upload) => {
|
||||
const fileItem = selectedFiles.find((f) => f.file === upload.file);
|
||||
if (!fileItem) throw new Error('Broken upload');
|
||||
@@ -390,7 +407,7 @@ export const RoomInput = forwardRef<HTMLDivElement, RoomInputProps>(
|
||||
const contents = fulfilledPromiseSettledResult(await Promise.allSettled(contentsPromises));
|
||||
|
||||
if (contents.length > 0) {
|
||||
const replyContent = plaintext.length === 0 ? getReplyContent(replyDraft) : undefined;
|
||||
const replyContent = plainText?.length === 0 ? getReplyContent(replyDraft) : undefined;
|
||||
if (replyContent) contents[0]['m.relates_to'] = replyContent;
|
||||
setReplyDraft(undefined);
|
||||
}
|
||||
@@ -523,7 +540,6 @@ export const RoomInput = forwardRef<HTMLDivElement, RoomInputProps>(
|
||||
setReplyDraft(undefined);
|
||||
sendTypingStatus(false);
|
||||
};
|
||||
|
||||
if (scheduledTime) {
|
||||
try {
|
||||
const delayMs = computeDelayMs(scheduledTime);
|
||||
@@ -700,6 +716,8 @@ export const RoomInput = forwardRef<HTMLDivElement, RoomInputProps>(
|
||||
fileItem={fileItem}
|
||||
setMetadata={handleFileMetadata}
|
||||
onRemove={handleRemoveUpload}
|
||||
setDesc={setDesc}
|
||||
roomId={roomId}
|
||||
/>
|
||||
))}
|
||||
</UploadBoardContent>
|
||||
@@ -994,8 +1012,35 @@ export const RoomInput = forwardRef<HTMLDivElement, RoomInputProps>(
|
||||
/>
|
||||
<Box display="Flex" alignItems="Center">
|
||||
<IconButton
|
||||
onClick={submit}
|
||||
onClick={() => {
|
||||
if (isLongPress.current) {
|
||||
isLongPress.current = false;
|
||||
return;
|
||||
}
|
||||
submit();
|
||||
}}
|
||||
onMouseDown={(e: MouseEvent) => e.preventDefault()}
|
||||
onPointerDown={() => {
|
||||
isLongPress.current = false;
|
||||
if (mobileOrTablet() && delayedEventsSupported) {
|
||||
longPressTimer.current = setTimeout(() => {
|
||||
isLongPress.current = true;
|
||||
setShowSchedulePicker(true);
|
||||
}, 1000);
|
||||
}
|
||||
}}
|
||||
onPointerUp={() => {
|
||||
if (longPressTimer.current !== null) {
|
||||
clearTimeout(longPressTimer.current);
|
||||
longPressTimer.current = null;
|
||||
}
|
||||
}}
|
||||
onPointerCancel={() => {
|
||||
if (longPressTimer.current !== null) {
|
||||
clearTimeout(longPressTimer.current);
|
||||
longPressTimer.current = null;
|
||||
}
|
||||
}}
|
||||
variant={scheduledTime ? 'Primary' : 'SurfaceVariant'}
|
||||
size="300"
|
||||
radii="0"
|
||||
@@ -1003,7 +1048,7 @@ export const RoomInput = forwardRef<HTMLDivElement, RoomInputProps>(
|
||||
>
|
||||
<Icon src={scheduledTime ? Icons.Clock : Icons.Send} />
|
||||
</IconButton>
|
||||
{delayedEventsSupported && (
|
||||
{delayedEventsSupported && !mobileOrTablet() && (
|
||||
<IconButton
|
||||
onClick={(evt: MouseEvent<HTMLButtonElement>) => {
|
||||
setScheduleMenuAnchor(evt.currentTarget.getBoundingClientRect());
|
||||
|
||||
Loaded 100 of 173 files, more files were not shown because too many files have changed in this diff.
Show more
Reference in new issue
Block a user