Apply the auto-fixable lint rules and the formatter, and drop the Vite build artifacts.
Checks / checks (push) Successful in 2m11s
Trigger cinny-mobile / dispatch (push) Successful in 1s

This commit is contained in:
2026-11-01 04:23:53 +11:00
parent 3cd159a63e
commit a6ad8651b3
605 changed files with 11480 additions and 9125 deletions
+181 -172
View File
@@ -2,7 +2,22 @@ import { useAtomValue } from 'jotai';
import React, { ChangeEventHandler, useCallback, useMemo, useRef, useState } from 'react';
import { useVirtualizer } from '@tanstack/react-virtual';
import FocusTrap from 'focus-trap-react';
import { Avatar, Box, Button, Header, IconButton, Input, MenuItem, Modal, Overlay, OverlayBackdrop, OverlayCenter, Scroll, Text, config } from 'folds';
import {
Avatar,
Box,
Button,
Header,
IconButton,
Input,
MenuItem,
Modal,
Overlay,
OverlayBackdrop,
OverlayCenter,
Scroll,
Text,
config,
} from 'folds';
import { Icon, Icons } from '../components/icons';
import { useMatrixClient } from '../hooks/useMatrixClient';
import { useAllJoinedRoomsSet, useGetRoom } from '../hooks/useGetRoom';
@@ -57,18 +72,18 @@ export function ShareRoomPicker({ share, onPick, onDismiss }: ShareRoomPickerPro
const allItems = useMemo(
() => [...rooms, ...directs].sort(factoryRoomIdByActivity(mx)),
[mx, rooms, directs]
[mx, rooms, directs],
);
const getRoomNameStr: SearchItemStrGetter<string> = useCallback(
(rId) => getRoom(rId)?.name ?? rId,
[getRoom]
[getRoom],
);
const [searchResult, searchRoom, resetSearch] = useAsyncSearch(
allItems,
getRoomNameStr,
SEARCH_OPTS
SEARCH_OPTS,
);
const items = searchResult ? searchResult.items : allItems;
@@ -113,188 +128,182 @@ export function ShareRoomPicker({ share, onPick, onDismiss }: ShareRoomPickerPro
return (
<>
<Overlay open>
<FocusTrap
focusTrapOptions={{
initialFocus: false,
clickOutsideDeactivates: true,
onDeactivate: onDismiss,
escapeDeactivates: stopPropagation,
}}
>
<Box
grow="Yes"
direction="Column"
style={{
position: 'fixed',
inset: 0,
zIndex: 999,
backgroundColor: '#1a1d23',
paddingTop: '60px',
<FocusTrap
focusTrapOptions={{
initialFocus: false,
clickOutsideDeactivates: true,
onDeactivate: onDismiss,
escapeDeactivates: stopPropagation,
}}
>
<Header
size="500"
style={{ padding: config.space.S400 }}
>
<Box grow="Yes" direction="Column" gap="100" style={{ minWidth: 0, maxWidth: '80%' }}>
<Text size="H4">Share to Room</Text>
{(previewText || fileCount > 0) && (
<Text size="T200" priority="300" style={{ opacity: 0.7, wordBreak: 'break-word', whiteSpace: 'normal' }}>
{previewText
? `"${previewText}${(share.text?.length ?? 0) > 80 ? '…' : ''}"`
: `${fileCount} file${fileCount !== 1 ? 's' : ''}`}
</Text>
)}
</Box>
<Box shrink="No">
<IconButton size="300" radii="300" onClick={onDismiss}>
<Icon src={Icons.Cross} />
</IconButton>
</Box>
</Header>
<Box
grow="Yes"
direction="Column"
style={{
padding: config.space.S200,
paddingTop: config.space.S300,
position: 'fixed',
inset: 0,
zIndex: 999,
backgroundColor: '#1a1d23',
paddingTop: '60px',
}}
>
<Input
onChange={handleSearchChange}
before={<Icon size="200" src={Icons.Search} />}
placeholder="Search rooms…"
size="400"
variant="Background"
outlined
autoFocus
style={{ width: '100%' }}
/>
</Box>
<Scroll ref={scrollRef} size="300" hideTrack style={{ flex: 1, minHeight: 0 }}>
<Box style={{ padding: config.space.S300 }} direction="Column">
{vItems.length === 0 && (
<Box
style={{ padding: `${config.space.S700} 0` }}
alignItems="Center"
justifyContent="Center"
direction="Column"
gap="100"
>
<Text size="H6" align="Center">
{searchResult ? 'No Match Found' : 'No Rooms'}
<Header size="500" style={{ padding: config.space.S400 }}>
<Box grow="Yes" direction="Column" gap="100" style={{ minWidth: 0, maxWidth: '80%' }}>
<Text size="H4">Share to Room</Text>
{(previewText || fileCount > 0) && (
<Text
size="T200"
priority="300"
style={{ opacity: 0.7, wordBreak: 'break-word', whiteSpace: 'normal' }}
>
{previewText
? `"${previewText}${(share.text?.length ?? 0) > 80 ? '…' : ''}"`
: `${fileCount} file${fileCount !== 1 ? 's' : ''}`}
</Text>
<Text size="T200" align="Center" priority="300">
{searchResult
? `No rooms found for "${searchResult.query}".`
: 'You have no rooms to share into.'}
</Text>
</Box>
)}
<Box style={{ position: 'relative', height: virtualizer.getTotalSize() }}>
{vItems.map((vItem) => {
const roomId = items[vItem.index];
const room = getRoom(roomId);
if (!room) return null;
const isDm = mDirects.has(roomId);
const avatarSrc = isDm
? getDirectRoomAvatarUrl(mx, room, 96, useAuthentication)
: getRoomAvatarUrl(mx, room, 96, useAuthentication);
return (
<VirtualTile
virtualItem={vItem}
style={{ paddingBottom: config.space.S100 }}
ref={virtualizer.measureElement}
key={roomId}
>
<MenuItem
data-room-id={roomId}
onClick={handleRoomClick}
variant="Surface"
size="400"
radii="400"
before={
<Avatar size="300" radii={isDm ? '400' : '300'}>
{avatarSrc ? (
<RoomAvatar
roomId={roomId}
src={avatarSrc}
alt={room.name}
renderFallback={() => (
<Text as="span" size="H6">
{nameInitials(room.name)}
</Text>
)}
/>
) : (
<RoomIcon room={room} size="200" filled />
)}
</Avatar>
}
>
<Box grow="Yes" direction="Column">
<Text size="B400" truncate>
{room.name}
</Text>
</Box>
</MenuItem>
</VirtualTile>
);
})}
)}
</Box>
</Box>
</Scroll>
</Box>
</FocusTrap>
</Overlay>
<Box shrink="No">
<IconButton size="300" radii="300" onClick={onDismiss}>
<Icon src={Icons.Cross} />
</IconButton>
</Box>
</Header>
{confirmRoomId && (() => {
const room = getRoom(confirmRoomId);
const roomName = room?.name ?? confirmRoomId;
const isDm = mDirects.has(confirmRoomId);
return (
<Overlay open backdrop={<OverlayBackdrop />}>
<OverlayCenter>
<FocusTrap
focusTrapOptions={{
initialFocus: false,
onDeactivate: handleCancelConfirm,
escapeDeactivates: stopPropagation,
<Box
style={{
padding: config.space.S200,
paddingTop: config.space.S300,
}}
>
<Modal style={{ maxWidth: '280px' }}>
<Box direction="Column" gap="100" style={{ padding: config.space.S300 }}>
<Box direction="Column" gap="100">
<Text size="H4">Share to {isDm ? 'Person' : 'Room'}?</Text>
<Text size="T300" priority="300">
Send to <strong>{roomName}</strong>?
<Input
onChange={handleSearchChange}
before={<Icon size="200" src={Icons.Search} />}
placeholder="Search rooms…"
size="400"
variant="Background"
outlined
autoFocus
style={{ width: '100%' }}
/>
</Box>
<Scroll ref={scrollRef} size="300" hideTrack style={{ flex: 1, minHeight: 0 }}>
<Box style={{ padding: config.space.S300 }} direction="Column">
{vItems.length === 0 && (
<Box
style={{ padding: `${config.space.S700} 0` }}
alignItems="Center"
justifyContent="Center"
direction="Column"
gap="100"
>
<Text size="H6" align="Center">
{searchResult ? 'No Match Found' : 'No Rooms'}
</Text>
<Text size="T200" align="Center" priority="300">
{searchResult
? `No rooms found for "${searchResult.query}".`
: 'You have no rooms to share into.'}
</Text>
</Box>
<Box gap="200" justifyContent="End">
<Button
onClick={handleCancelConfirm}
variant="Secondary"
size="400"
>
<Text size="B400">Cancel</Text>
</Button>
<Button
onClick={handleConfirm}
variant="Primary"
size="400"
>
<Text size="B400">Share</Text>
</Button>
</Box>
)}
<Box style={{ position: 'relative', height: virtualizer.getTotalSize() }}>
{vItems.map((vItem) => {
const roomId = items[vItem.index];
const room = getRoom(roomId);
if (!room) return null;
const isDm = mDirects.has(roomId);
const avatarSrc = isDm
? getDirectRoomAvatarUrl(mx, room, 96, useAuthentication)
: getRoomAvatarUrl(mx, room, 96, useAuthentication);
return (
<VirtualTile
virtualItem={vItem}
style={{ paddingBottom: config.space.S100 }}
ref={virtualizer.measureElement}
key={roomId}
>
<MenuItem
data-room-id={roomId}
onClick={handleRoomClick}
variant="Surface"
size="400"
radii="400"
before={
<Avatar size="300" radii={isDm ? '400' : '300'}>
{avatarSrc ? (
<RoomAvatar
roomId={roomId}
src={avatarSrc}
alt={room.name}
renderFallback={() => (
<Text as="span" size="H6">
{nameInitials(room.name)}
</Text>
)}
/>
) : (
<RoomIcon room={room} size="200" filled />
)}
</Avatar>
}
>
<Box grow="Yes" direction="Column">
<Text size="B400" truncate>
{room.name}
</Text>
</Box>
</MenuItem>
</VirtualTile>
);
})}
</Box>
</Modal>
</FocusTrap>
</OverlayCenter>
</Overlay>
);
})()}
</Box>
</Scroll>
</Box>
</FocusTrap>
</Overlay>
{confirmRoomId &&
(() => {
const room = getRoom(confirmRoomId);
const roomName = room?.name ?? confirmRoomId;
const isDm = mDirects.has(confirmRoomId);
return (
<Overlay open backdrop={<OverlayBackdrop />}>
<OverlayCenter>
<FocusTrap
focusTrapOptions={{
initialFocus: false,
onDeactivate: handleCancelConfirm,
escapeDeactivates: stopPropagation,
}}
>
<Modal style={{ maxWidth: '280px' }}>
<Box direction="Column" gap="100" style={{ padding: config.space.S300 }}>
<Box direction="Column" gap="100">
<Text size="H4">Share to {isDm ? 'Person' : 'Room'}?</Text>
<Text size="T300" priority="300">
Send to <strong>{roomName}</strong>?
</Text>
</Box>
<Box gap="200" justifyContent="End">
<Button onClick={handleCancelConfirm} variant="Secondary" size="400">
<Text size="B400">Cancel</Text>
</Button>
<Button onClick={handleConfirm} variant="Primary" size="400">
<Text size="B400">Share</Text>
</Button>
</Box>
</Box>
</Modal>
</FocusTrap>
</OverlayCenter>
</Overlay>
);
})()}
</>
);
}
+24 -7
View File
@@ -1,6 +1,22 @@
import FocusTrap from 'focus-trap-react';
import { Avatar, Box, Button, config, Header, IconButton, Input, Menu, MenuItem, Modal, Overlay, OverlayBackdrop, OverlayCenter, Scroll, Spinner, Text } from 'folds';
import { Icon, Icons } from '../../components/icons';
import {
Avatar,
Box,
Button,
config,
Header,
IconButton,
Input,
Menu,
MenuItem,
Modal,
Overlay,
OverlayBackdrop,
OverlayCenter,
Scroll,
Spinner,
Text,
} from 'folds';
import React, {
ChangeEventHandler,
MouseEventHandler,
@@ -12,6 +28,7 @@ import React, {
import { useAtomValue } from 'jotai';
import { useVirtualizer } from '@tanstack/react-virtual';
import { Room } from 'matrix-js-sdk';
import { Icon, Icons } from '../../components/icons';
import { stopPropagation } from '../../utils/keyboard';
import { useDirects, useRooms, useSpaces } from '../../state/hooks/roomList';
import { useMatrixClient } from '../../hooks/useMatrixClient';
@@ -79,13 +96,13 @@ export function AddExistingModal({ parentId, space, requestClose }: AddExistingM
const getRoomNameStr: SearchItemStrGetter<string> = useCallback(
(rId) => getRoom(rId)?.name ?? rId,
[getRoom]
[getRoom],
);
const [searchResult, searchRoom, resetSearch] = useAsyncSearch(
allItems,
getRoomNameStr,
SEARCH_OPTS
SEARCH_OPTS,
);
const queryHighlighRegex = searchResult?.query
? makeHighlightRegex(searchResult.query.split(' '))
@@ -124,12 +141,12 @@ export function AddExistingModal({ parentId, space, requestClose }: AddExistingM
suggested: false,
via,
},
room.roomId
room.roomId,
);
});
},
[mx, parentId]
)
[mx, parentId],
),
);
const applyingChanges = applyState.status === AsyncStatus.Loading;
File diff suppressed because it is too large Load Diff
+187 -146
View File
@@ -1,5 +1,5 @@
/* eslint-disable no-console */
/* eslint-disable import/no-extraneous-dependencies */
import {
Room,
RoomEvent,
@@ -23,16 +23,22 @@ import {
LiveKitJWTResponse,
CallMemberEventContent,
} from './types';
import {
fetchLiveKitJWT,
fetchWellKnownWithRTC,
getLiveKitFocus,
import {
fetchLiveKitJWT,
fetchWellKnownWithRTC,
getLiveKitFocus,
requestOpenIdToken,
fetchLiveKitJWTFromServers,
getLiveKitHomeserverPriority,
} from './useRtcConfig';
import { getActiveCallMembers } from './useRoomCallMembers';
import { getAudioCaptureOptions, getAudioSettings, AUDIO_SETTINGS_CHANGED_EVENT, SCREEN_SHARE_RESOLUTIONS, SCREEN_SHARE_BITRATES } from '../settings/audio/Audio';
import {
getAudioCaptureOptions,
getAudioSettings,
AUDIO_SETTINGS_CHANGED_EVENT,
SCREEN_SHARE_RESOLUTIONS,
SCREEN_SHARE_BITRATES,
} from '../settings/audio/Audio';
import { getCallSounds, CallSoundType } from './CallSounds';
type CallEventListener = (event: CallEvent) => void;
@@ -61,19 +67,26 @@ function checkWebRTCSupport(): { supported: boolean; details: Record<string, unk
// Check for key WebRTC APIs
details.hasGetUserMedia = !!(navigator.mediaDevices && navigator.mediaDevices.getUserMedia);
details.hasRTCPeerConnection = !!(window.RTCPeerConnection);
details.hasRTCDataChannel = !!(window.RTCPeerConnection && window.RTCPeerConnection.prototype.createDataChannel);
details.hasRTCPeerConnection = !!window.RTCPeerConnection;
details.hasRTCDataChannel = !!(
window.RTCPeerConnection && window.RTCPeerConnection.prototype.createDataChannel
);
// Check WebKit-specific APIs
details.hasWebkitGetUserMedia = !!(navigator.getUserMedia || (navigator as any).webkitGetUserMedia);
details.hasWebkitRTCPeerConnection = !!((window as any).webkitRTCPeerConnection);
details.hasWebkitGetUserMedia = !!(
navigator.getUserMedia || (navigator as any).webkitGetUserMedia
);
details.hasWebkitRTCPeerConnection = !!(window as any).webkitRTCPeerConnection;
// Check if mediaDevices API exists
details.hasMediaDevices = !!navigator.mediaDevices;
details.hasEnumerateDevices = !!(navigator.mediaDevices && navigator.mediaDevices.enumerateDevices);
details.hasEnumerateDevices = !!(
navigator.mediaDevices && navigator.mediaDevices.enumerateDevices
);
const supported = !!(
(navigator.mediaDevices && navigator.mediaDevices.getUserMedia) &&
navigator.mediaDevices &&
navigator.mediaDevices.getUserMedia &&
(window.RTCPeerConnection || (window as any).webkitRTCPeerConnection)
);
@@ -184,7 +197,7 @@ export class CallService {
private async sendCallMemberEvent(
roomId: string,
callId: string,
active: boolean
active: boolean,
): Promise<void> {
const stateKey = this.config.userId;
@@ -193,15 +206,19 @@ export class CallService {
if (room) {
const powerLevelsEvent = room.currentState.getStateEvents('m.room.power_levels', '');
const powerLevelsContent = powerLevelsEvent?.getContent() || {};
const myPower = powerLevelsContent.users?.[this.config.userId] ?? powerLevelsContent.users_default ?? 0;
const requiredPower = powerLevelsContent.events?.[CALL_MEMBER_EVENT_TYPE] ?? powerLevelsContent.state_default ?? 50;
const myPower =
powerLevelsContent.users?.[this.config.userId] ?? powerLevelsContent.users_default ?? 0;
const requiredPower =
powerLevelsContent.events?.[CALL_MEMBER_EVENT_TYPE] ??
powerLevelsContent.state_default ??
50;
if (myPower < requiredPower) {
console.warn(
`Cannot send call member event: insufficient permissions. ` +
`User power level (${myPower}) < required power level (${requiredPower}). ` +
`Call will work locally but room members won't see your call status.`
`User power level (${myPower}) < required power level (${requiredPower}). ` +
`Call will work locally but room members won't see your call status.`,
);
return;
}
@@ -217,9 +234,7 @@ export class CallService {
device_id: this.config.deviceId,
session_id: callId,
expires_ts: Date.now() + MEMBERSHIP_EXPIRY_MS,
feeds: [
{ purpose: 'usermedia' },
],
feeds: [{ purpose: 'usermedia' }],
},
],
},
@@ -231,7 +246,7 @@ export class CallService {
roomId,
CALL_MEMBER_EVENT_TYPE,
content,
stateKey
stateKey,
);
} else {
// Clear the call membership by sending empty calls array
@@ -244,7 +259,7 @@ export class CallService {
roomId,
CALL_MEMBER_EVENT_TYPE,
content,
stateKey
stateKey,
);
}
}
@@ -335,7 +350,7 @@ export class CallService {
// Check if there's already an active call
const activeCallMembers = getActiveCallMembers(room);
const isJoiningExistingCall = activeCallMembers.length > 0;
if (isJoiningExistingCall) {
console.log(`Joining existing call with ${activeCallMembers.length} participant(s)`);
} else {
@@ -345,7 +360,7 @@ export class CallService {
const homeserverPriority = getLiveKitHomeserverPriority(
room,
this.config.homeserverBaseUrl,
this.config.userId
this.config.userId,
);
console.log('Trying homeservers in order:', homeserverPriority);
@@ -357,7 +372,7 @@ export class CallService {
roomId,
this.config.userId,
this.config.deviceId,
this.config.accessToken
this.config.accessToken,
);
if (!result) {
@@ -365,15 +380,13 @@ export class CallService {
}
this.livekitJwt = result.jwt;
// Track if using remote homeserver
const userHomeserverDomain = this.config.homeserverBaseUrl
.replace('https://', '')
.replace('http://', '');
const usedHomeserverDomain = result.homeserver
.replace('https://', '')
.replace('http://', '');
const usedHomeserverDomain = result.homeserver.replace('https://', '').replace('http://', '');
if (usedHomeserverDomain !== userHomeserverDomain) {
this.activeCall!.livekitHomeserver = result.homeserver;
console.log(`Using remote homeserver for LiveKit: ${result.homeserver}`);
@@ -385,7 +398,7 @@ export class CallService {
// Check WebRTC support before attempting connection
const webrtcCheck = checkWebRTCSupport();
console.log('WebRTC support check:', webrtcCheck);
if (!webrtcCheck.supported) {
console.warn('WebRTC may not be fully supported. Attempting connection anyway...');
console.warn('WebRTC details:', JSON.stringify(webrtcCheck.details, null, 2));
@@ -480,15 +493,24 @@ export class CallService {
(
track: RemoteTrackPublication['track'],
publication: RemoteTrackPublication,
participant: RemoteParticipant
participant: RemoteParticipant,
) => {
if (!track || !this.activeCall) return;
const isScreenShare = publication.source === Track.Source.ScreenShare ||
publication.source === Track.Source.ScreenShareAudio;
console.log('Track subscribed:', track.kind, 'source:', publication.source,
'isScreenShare:', isScreenShare, 'from', participant.identity);
const isScreenShare =
publication.source === Track.Source.ScreenShare ||
publication.source === Track.Source.ScreenShareAudio;
console.log(
'Track subscribed:',
track.kind,
'source:',
publication.source,
'isScreenShare:',
isScreenShare,
'from',
participant.identity,
);
console.log('Track mediaStreamTrack:', track.mediaStreamTrack);
console.log('Track mediaStreamTrack readyState:', track.mediaStreamTrack?.readyState);
console.log('Track mediaStreamTrack enabled:', track.mediaStreamTrack?.enabled);
@@ -497,7 +519,7 @@ export class CallService {
if (track.kind === 'audio') {
const audioElement = track.attach() as HTMLAudioElement;
audioElement.id = `audio-${participant.identity}-${publication.source}`;
// Set the preferred output device if supported and selected
const audioSettings = getAudioSettings();
if (audioSettings.speakerId && 'setSinkId' in audioElement) {
@@ -506,35 +528,39 @@ export class CallService {
.then(() => console.log('Speaker set to:', audioSettings.speakerId))
.catch((e) => console.warn('Could not set speaker device:', e));
}
document.body.appendChild(audioElement);
console.log('Audio element attached for', participant.identity);
// If we're currently deafened, mute this new track so we don't hear them
if (this.activeCall?.isDeafened) {
track.setMuted(true);
console.log('Auto-muted new audio track from', participant.identity, 'due to deafen state');
console.log(
'Auto-muted new audio track from',
participant.identity,
'due to deafen state',
);
}
}
// Handle screen share video tracks separately
if (isScreenShare && track.kind === 'video') {
const mediaStream = new MediaStream([track.mediaStreamTrack]);
console.log('📺 Screen share received from', participant.identity);
console.log('📺 Screen share track:', track);
console.log('📺 Screen share MediaStream:', mediaStream);
console.log('📺 Screen share MediaStream tracks:', mediaStream?.getTracks());
this.activeCall.remoteScreenStreams.set(participant.identity, mediaStream);
// Store the actual track for proper attachment later
this.activeCall.remoteScreenTracks.set(participant.identity, {
participantId: participant.identity,
track,
stream: mediaStream,
});
this.emit({
type: CallEventType.ScreenShareStarted,
roomId: this.activeCall.roomId,
@@ -547,7 +573,7 @@ export class CallService {
} else if (track.kind === 'video') {
const mediaStream = new MediaStream([track.mediaStreamTrack]);
this.activeCall.remoteStreams.set(participant.identity, mediaStream);
this.emit({
type: CallEventType.RemoteStreamAdded,
roomId: this.activeCall.roomId,
@@ -562,7 +588,7 @@ export class CallService {
if (!this.activeCall.participants.includes(participant.identity)) {
this.activeCall.participants.push(participant.identity);
}
}
},
);
this.livekitRoom.on(
@@ -570,19 +596,30 @@ export class CallService {
(
track: RemoteTrackPublication['track'],
publication: RemoteTrackPublication,
participant: RemoteParticipant
participant: RemoteParticipant,
) => {
if (!this.activeCall) return;
const isScreenShare = publication.source === Track.Source.ScreenShare ||
publication.source === Track.Source.ScreenShareAudio;
const isScreenShare =
publication.source === Track.Source.ScreenShare ||
publication.source === Track.Source.ScreenShareAudio;
console.log('Track unsubscribed:', track?.kind, 'source:', publication.source,
'isScreenShare:', isScreenShare, 'from', participant.identity);
console.log(
'Track unsubscribed:',
track?.kind,
'source:',
publication.source,
'isScreenShare:',
isScreenShare,
'from',
participant.identity,
);
// Remove audio element if it exists
if (track?.kind === 'audio') {
const audioElement = document.getElementById(`audio-${participant.identity}-${publication.source}`);
const audioElement = document.getElementById(
`audio-${participant.identity}-${publication.source}`,
);
if (audioElement) {
audioElement.remove();
console.log('Audio element removed for', participant.identity);
@@ -597,7 +634,7 @@ export class CallService {
this.activeCall.remoteScreenStreams.delete(participant.identity);
this.activeCall.remoteScreenTracks.delete(participant.identity);
console.log('📺 Screen share ended from', participant.identity);
this.emit({
type: CallEventType.ScreenShareStopped,
roomId: this.activeCall.roomId,
@@ -605,18 +642,23 @@ export class CallService {
});
} else if (track?.kind === 'video') {
this.activeCall.remoteStreams.delete(participant.identity);
this.emit({
type: CallEventType.RemoteStreamRemoved,
roomId: this.activeCall.roomId,
data: { participantId: participant.identity },
});
}
}
},
);
this.livekitRoom.on(RoomEvent.ParticipantConnected, (participant: RemoteParticipant) => {
console.log('Participant connected:', participant.identity, 'in Matrix room:', this.activeCall?.roomId);
console.log(
'Participant connected:',
participant.identity,
'in Matrix room:',
this.activeCall?.roomId,
);
console.log('Current LiveKit room name:', this.livekitRoom?.name);
// Listen for this participant's speaking state
@@ -630,10 +672,10 @@ export class CallService {
if (this.activeCall && !this.activeCall.participants.includes(participant.identity)) {
this.activeCall.participants.push(participant.identity);
// Play join sound for remote participant
getCallSounds().playSound(CallSoundType.CallJoined);
this.emit({
type: CallEventType.ParticipantJoined,
roomId: this.activeCall.roomId,
@@ -647,7 +689,7 @@ export class CallService {
if (this.activeCall) {
this.activeCall.participants = this.activeCall.participants.filter(
(p) => p !== participant.identity
(p) => p !== participant.identity,
);
this.activeCall.remoteStreams.delete(participant.identity);
@@ -677,15 +719,15 @@ export class CallService {
if (!this.activeCall) return;
if (participant.identity === this.livekitRoom?.localParticipant.identity) return;
if (publication.kind !== 'audio') return;
console.log(`🔇 ${participant.identity} muted their microphone`);
// Track muted state
this.activeCall.mutedParticipants.add(participant.identity);
// Play mute sound for remote participant
getCallSounds().playSound(CallSoundType.MicMute);
this.emit({
type: CallEventType.RemoteMuteChanged,
roomId: this.activeCall.roomId,
@@ -698,15 +740,15 @@ export class CallService {
if (!this.activeCall) return;
if (participant.identity === this.livekitRoom?.localParticipant.identity) return;
if (publication.kind !== 'audio') return;
console.log(`🔊 ${participant.identity} unmuted their microphone`);
// Track unmuted state
this.activeCall.mutedParticipants.delete(participant.identity);
// Play unmute sound for remote participant
getCallSounds().playSound(CallSoundType.MicUnmute);
this.emit({
type: CallEventType.RemoteMuteChanged,
roomId: this.activeCall.roomId,
@@ -719,30 +761,30 @@ export class CallService {
// We preserve the existing activeSpeakers that may include local user
this.livekitRoom.on(RoomEvent.ActiveSpeakersChanged, (speakers: Participant[]) => {
if (!this.activeCall) return;
// Get remote speaker identities
const remoteSpeakerIds = speakers
.filter((s) => s.identity !== this.livekitRoom?.localParticipant.identity)
.map((s) => s.identity);
// Check if local participant is speaking (from LiveKit's list)
const localSpeaking = speakers.some(
(s) => s.identity === this.livekitRoom?.localParticipant.identity
(s) => s.identity === this.livekitRoom?.localParticipant.identity,
);
// Build new activeSpeakers set - use Matrix user ID for local
const newSpeakers = new Set<string>(remoteSpeakerIds);
if (localSpeaking) {
newSpeakers.add(this.config.userId);
}
this.activeCall.activeSpeakers = newSpeakers;
if (speakers.length > 0) {
const speakerNames = speakers.map((s) => s.identity).join(', ');
console.log('🎤 Active speakers:', speakerNames);
}
this.emit({
type: CallEventType.SpeakersChanged,
roomId: this.activeCall.roomId,
@@ -751,46 +793,52 @@ export class CallService {
});
// Listen for participant metadata changes (for deafen state)
this.livekitRoom.on(RoomEvent.ParticipantMetadataChanged, (prevMetadata: string | undefined, participant: Participant) => {
if (!this.activeCall) return;
if (participant.identity === this.livekitRoom?.localParticipant.identity) return;
try {
const prevData = prevMetadata ? JSON.parse(prevMetadata) : {};
const newData = participant.metadata ? JSON.parse(participant.metadata) : {};
const wasDeafened = prevData.isDeafened === true;
const isDeafened = newData.isDeafened === true;
if (wasDeafened !== isDeafened) {
console.log(`🎧 ${participant.identity} ${isDeafened ? 'deafened' : 'undeafened'}`);
getCallSounds().playSound(isDeafened ? CallSoundType.Deafen : CallSoundType.Undeafen);
this.livekitRoom.on(
RoomEvent.ParticipantMetadataChanged,
(prevMetadata: string | undefined, participant: Participant) => {
if (!this.activeCall) return;
if (participant.identity === this.livekitRoom?.localParticipant.identity) return;
try {
const prevData = prevMetadata ? JSON.parse(prevMetadata) : {};
const newData = participant.metadata ? JSON.parse(participant.metadata) : {};
const wasDeafened = prevData.isDeafened === true;
const isDeafened = newData.isDeafened === true;
if (wasDeafened !== isDeafened) {
console.log(`🎧 ${participant.identity} ${isDeafened ? 'deafened' : 'undeafened'}`);
getCallSounds().playSound(isDeafened ? CallSoundType.Deafen : CallSoundType.Undeafen);
}
} catch {
// Ignore metadata parse errors
}
} catch {
// Ignore metadata parse errors
}
});
},
);
// Track local participant speaking state - use Matrix user ID for consistency
this.livekitRoom.localParticipant.on(ParticipantEvent.IsSpeakingChanged, (speaking: boolean) => {
if (!this.activeCall) return;
const myUserId = this.config.userId;
if (speaking) {
console.log('🎙️ You are speaking');
this.activeCall.activeSpeakers.add(myUserId);
} else {
console.log('🔇 You stopped speaking');
this.activeCall.activeSpeakers.delete(myUserId);
}
this.emit({
type: CallEventType.SpeakersChanged,
roomId: this.activeCall.roomId,
data: { speakers: this.activeCall.activeSpeakers },
});
});
this.livekitRoom.localParticipant.on(
ParticipantEvent.IsSpeakingChanged,
(speaking: boolean) => {
if (!this.activeCall) return;
const myUserId = this.config.userId;
if (speaking) {
console.log('🎙️ You are speaking');
this.activeCall.activeSpeakers.add(myUserId);
} else {
console.log('🔇 You stopped speaking');
this.activeCall.activeSpeakers.delete(myUserId);
}
this.emit({
type: CallEventType.SpeakersChanged,
roomId: this.activeCall.roomId,
data: { speakers: this.activeCall.activeSpeakers },
});
},
);
// Track audio level changes for local participant (more detailed)
this.livekitRoom.localParticipant.on(ParticipantEvent.AudioStreamAcquired, () => {
@@ -817,7 +865,7 @@ export class CallService {
getCallSounds().playSound(CallSoundType.CallDepart);
try {
// Clear Matrix call membership - this state event will be rendered
// Clear Matrix call membership - this state event will be rendered
// in the timeline as a "left the call" notification
await this.sendCallMemberEvent(roomId, '', false);
} catch (error) {
@@ -854,12 +902,12 @@ export class CallService {
}
const newMuteState = !this.activeCall.isMuted;
// If unmuting while deafened, undeafen first
if (!newMuteState && this.activeCall.isDeafened) {
this.activeCall.isDeafened = false;
getCallSounds().setDeafened(false);
// Unmute all remote audio tracks
this.livekitRoom.remoteParticipants.forEach((participant) => {
participant.audioTrackPublications.forEach((publication) => {
@@ -868,7 +916,7 @@ export class CallService {
}
});
});
// Broadcast undeafen state
const metadata = JSON.stringify({ isDeafened: false });
this.livekitRoom.localParticipant.setMetadata(metadata).catch((err) => {
@@ -878,17 +926,12 @@ export class CallService {
// Play undeafen sound
getCallSounds().playSound(CallSoundType.Undeafen);
}
this.livekitRoom.localParticipant.setMicrophoneEnabled(
!newMuteState,
getAudioCaptureOptions()
);
this.livekitRoom.localParticipant.setMicrophoneEnabled(!newMuteState, getAudioCaptureOptions());
this.activeCall.isMuted = newMuteState;
// Play mute/unmute sound
getCallSounds().playSound(
newMuteState ? CallSoundType.MicMute : CallSoundType.MicUnmute
);
getCallSounds().playSound(newMuteState ? CallSoundType.MicMute : CallSoundType.MicUnmute);
return newMuteState;
}
@@ -921,7 +964,7 @@ export class CallService {
if (newDeafenState) {
// Remember if user was muted before deafening
this.wasMutedBeforeDeafen = this.activeCall.isMuted;
// Deafening - always mute mic
if (!this.activeCall.isMuted) {
this.livekitRoom.localParticipant.setMicrophoneEnabled(false);
@@ -943,9 +986,7 @@ export class CallService {
});
// Play deafen/undeafen sound (these always play for user feedback)
getCallSounds().playSound(
newDeafenState ? CallSoundType.Deafen : CallSoundType.Undeafen
);
getCallSounds().playSound(newDeafenState ? CallSoundType.Deafen : CallSoundType.Undeafen);
return newDeafenState;
}
@@ -1031,13 +1072,14 @@ export class CallService {
// Note: audio here is for system/tab audio, not microphone
const screenShareOptions = {
audio: true, // Include system audio if available
resolution: audioSettings.screenShareResolution === 'source'
? undefined
: {
width: resolution.width,
height: resolution.height,
frameRate: audioSettings.screenShareFrameRate,
},
resolution:
audioSettings.screenShareResolution === 'source'
? undefined
: {
width: resolution.width,
height: resolution.height,
frameRate: audioSettings.screenShareFrameRate,
},
};
// Enable screen share with the configured options
@@ -1050,14 +1092,13 @@ export class CallService {
// Set bitrate on the screen share track publication
const screenSharePub = Array.from(
this.livekitRoom.localParticipant.trackPublications.values()
).find(
(pub): pub is LocalTrackPublication =>
pub.source === Track.Source.ScreenShare
);
this.livekitRoom.localParticipant.trackPublications.values(),
).find((pub): pub is LocalTrackPublication => pub.source === Track.Source.ScreenShare);
if (screenSharePub?.track) {
console.log(`Screen share started with bitrate: ${SCREEN_SHARE_BITRATES[audioSettings.screenShareBitrate].bitrate}kbps`);
console.log(
`Screen share started with bitrate: ${SCREEN_SHARE_BITRATES[audioSettings.screenShareBitrate].bitrate}kbps`,
);
// Capture local screen stream for preview
const mediaStream = new MediaStream([screenSharePub.track.mediaStreamTrack]);
this.activeCall.localScreenStream = mediaStream;
@@ -1145,7 +1186,7 @@ export class CallService {
};
const publication = this.livekitRoom.localParticipant.getTrackPublication(
Track.Source.Microphone
Track.Source.Microphone,
);
const track = publication?.track;
if (!(track instanceof LocalAudioTrack)) return;
+5 -3
View File
@@ -70,9 +70,11 @@ export class CallSounds {
*/
playSound(soundType: CallSoundType, loop = false): void {
// Don't play sounds if deafened (except deafen/undeafen sounds for feedback)
if (this.isDeafened &&
soundType !== CallSoundType.Deafen &&
soundType !== CallSoundType.Undeafen) {
if (
this.isDeafened &&
soundType !== CallSoundType.Deafen &&
soundType !== CallSoundType.Undeafen
) {
return;
}
+70 -48
View File
@@ -1,7 +1,7 @@
import React, { useEffect, useMemo, useState } from 'react';
import { Box, IconButton, Text, Tooltip, TooltipProvider, Scroll, color } from 'folds';
import { Icon, Icons } from '../../components/icons';
import { useSetAtom } from 'jotai';
import { Icon, Icons } from '../../components/icons';
import { useCall } from './useCall';
import { ScreenShareItem, ScreenShareEntry } from './CallOverlay';
import { useRoomCallMembers } from './useRoomCallMembers';
@@ -69,7 +69,7 @@ export function DockedCallContent() {
const { navigateRoom } = useRoomNavigate();
const [, setIsDocked] = useSetting(settingsAtom, 'isCallPanelDocked');
const setPendingDrag = useSetAtom(pendingUndockDragAtom);
const unread = useRoomUnread(activeCall?.roomId ?? '', roomToUnreadAtom);
const { callMembers } = useRoomCallMembers(activeCall?.roomId ?? '');
const myUserId = mx.getUserId() ?? '';
@@ -95,7 +95,8 @@ export function DockedCallContent() {
remoteScreenTracks.forEach((trackInfo) => {
const livekitId = trackInfo.participantId;
const underscoreIndex = livekitId.lastIndexOf('_');
const possibleDeviceId = underscoreIndex > 0 ? livekitId.substring(0, underscoreIndex) : livekitId;
const possibleDeviceId =
underscoreIndex > 0 ? livekitId.substring(0, underscoreIndex) : livekitId;
const matchingMember = callMembers.find((m) => m.deviceId === possibleDeviceId);
const matrixUserId = matchingMember?.userId ?? livekitId;
@@ -111,7 +112,14 @@ export function DockedCallContent() {
});
return shares;
}, [activeCall?.isScreenSharing, activeCall?.localScreenStream, activeCall?.remoteScreenTracks, activeCall?.roomId, callMembers, myUserId]);
}, [
activeCall?.isScreenSharing,
activeCall?.localScreenStream,
activeCall?.remoteScreenTracks,
activeCall?.roomId,
callMembers,
myUserId,
]);
useEffect(() => {
if (!activeCall || activeCall.state !== CallState.Connected) {
@@ -137,10 +145,10 @@ export function DockedCallContent() {
const isParticipantSpeaking = (userId: string): boolean => {
if (!activeCall) return false;
if (activeCall.activeSpeakers.has(userId)) return true;
const member = callMembers.find((m) => m.userId === userId);
if (!member) return false;
return Array.from(activeCall.activeSpeakers).some((speakerId) => {
const underscoreIndex = speakerId.lastIndexOf('_');
const deviceId = underscoreIndex > 0 ? speakerId.substring(0, underscoreIndex) : speakerId;
@@ -154,10 +162,10 @@ export function DockedCallContent() {
const isParticipantMuted = (userId: string): boolean => {
if (!activeCall) return false;
if (userId === myUserId) return activeCall.isMuted;
const member = callMembers.find((m) => m.userId === userId);
if (!member) return false;
return Array.from(activeCall.mutedParticipants).some((mutedId) => {
const underscoreIndex = mutedId.lastIndexOf('_');
const deviceId = underscoreIndex > 0 ? mutedId.substring(0, underscoreIndex) : mutedId;
@@ -194,7 +202,7 @@ export function DockedCallContent() {
const handleHeaderMouseDown = async (e: React.MouseEvent) => {
// Don't start drag if clicking a button
if ((e.target as HTMLElement).closest('button')) return;
// Exit browser fullscreen if active before undocking
if (document.fullscreenElement) {
try {
@@ -203,11 +211,11 @@ export function DockedCallContent() {
// Fullscreen exit may fail
}
}
// Get the header element to calculate offset
const header = e.currentTarget as HTMLElement;
const rect = header.getBoundingClientRect();
// Store the drag start position with mouse offset from panel edges
setPendingDrag({
startX: e.clientX,
@@ -216,7 +224,7 @@ export function DockedCallContent() {
offsetY: e.clientY - rect.top,
timestamp: Date.now(),
});
// Undock immediately - the floating overlay will pick up the drag
setIsDocked(false);
};
@@ -235,30 +243,31 @@ export function DockedCallContent() {
<div className={css.DockedCallPanelContent}>
{/* Header - drag to undock */}
{/* eslint-disable-next-line jsx-a11y/no-static-element-interactions */}
<div
<div
className={css.CallOverlayHeader}
onMouseDown={handleHeaderMouseDown}
style={{ cursor: 'grab' }}
>
<Box alignItems="Center" gap="200" style={{ minWidth: 0, flex: 1 }}>
<Icon
size="200"
src={isVideoCall ? Icons.VideoCamera : Icons.Phone}
/>
<Icon size="200" src={isVideoCall ? Icons.VideoCamera : Icons.Phone} />
<Text size="T300" truncate>
{isConnecting ? 'Connecting...' : room?.name ?? 'Unknown Room'}
{isConnecting ? 'Connecting...' : (room?.name ?? 'Unknown Room')}
{selectedRoomId === activeCall.roomId && (
<TooltipProvider
position="Top"
offset={4}
tooltip={<Tooltip><Text>Current Room</Text></Tooltip>}
tooltip={
<Tooltip>
<Text>Current Room</Text>
</Tooltip>
}
>
{(triggerRef) => (
<Icon
<Icon
ref={triggerRef}
size="100"
src={Icons.Check}
style={{ marginLeft: '4px', opacity: 0.7, verticalAlign: 'middle' }}
size="100"
src={Icons.Check}
style={{ marginLeft: '4px', opacity: 0.7, verticalAlign: 'middle' }}
/>
)}
</TooltipProvider>
@@ -276,13 +285,17 @@ export function DockedCallContent() {
<TooltipProvider
position="Top"
offset={4}
tooltip={<Tooltip><Text>Go to Room</Text></Tooltip>}
tooltip={
<Tooltip>
<Text>Go to Room</Text>
</Tooltip>
}
>
{(triggerRef) => (
<IconButton
ref={triggerRef}
onClick={() => navigateRoom(activeCall.roomId)}
variant="Secondary"
<IconButton
ref={triggerRef}
onClick={() => navigateRoom(activeCall.roomId)}
variant="Secondary"
size="300"
>
<Icon size="100" src={Icons.Link} />
@@ -316,18 +329,19 @@ export function DockedCallContent() {
{allParticipants.map((participantId) => {
const avatarMxc = getMemberAvatarMxc(room, participantId);
const avatarUrl = avatarMxc
? mxcUrlToHttp(mx, avatarMxc, useAuthentication, 32, 32, 'crop') ?? undefined
? (mxcUrlToHttp(mx, avatarMxc, useAuthentication, 32, 32, 'crop') ?? undefined)
: undefined;
const displayName = getMemberDisplayName(room, participantId)
?? getMxIdLocalPart(participantId)
?? participantId;
const displayName =
getMemberDisplayName(room, participantId) ??
getMxIdLocalPart(participantId) ??
participantId;
const isMe = participantId === myUserId;
const isMuted = isParticipantMuted(participantId);
const isSpeaking = isParticipantSpeaking(participantId);
return (
<div key={participantId} className={css.ParticipantItem}>
<div
<div
className={`${css.ParticipantAvatarWrapper} ${isSpeaking ? css.ParticipantSpeaking : ''}`}
>
<UserAvatar
@@ -349,11 +363,7 @@ export function DockedCallContent() {
</Text>
</Box>
{isMuted && (
<Icon
size="100"
src={Icons.MicMute}
className={css.ParticipantMutedIcon}
/>
<Icon size="100" src={Icons.MicMute} className={css.ParticipantMutedIcon} />
)}
</div>
);
@@ -378,7 +388,11 @@ export function DockedCallContent() {
<TooltipProvider
position="Top"
offset={4}
tooltip={<Tooltip><Text>{activeCall.isMuted ? 'Unmute' : 'Mute'}</Text></Tooltip>}
tooltip={
<Tooltip>
<Text>{activeCall.isMuted ? 'Unmute' : 'Mute'}</Text>
</Tooltip>
}
>
{(triggerRef) => (
<IconButton
@@ -394,7 +408,11 @@ export function DockedCallContent() {
<TooltipProvider
position="Top"
offset={4}
tooltip={<Tooltip><Text>{activeCall.isDeafened ? 'Undeafen' : 'Deafen'}</Text></Tooltip>}
tooltip={
<Tooltip>
<Text>{activeCall.isDeafened ? 'Undeafen' : 'Deafen'}</Text>
</Tooltip>
}
>
{(triggerRef) => (
<IconButton
@@ -410,7 +428,11 @@ export function DockedCallContent() {
<TooltipProvider
position="Top"
offset={4}
tooltip={<Tooltip><Text>{activeCall.isScreenSharing ? 'Stop Screen Share' : 'Share Screen'}</Text></Tooltip>}
tooltip={
<Tooltip>
<Text>{activeCall.isScreenSharing ? 'Stop Screen Share' : 'Share Screen'}</Text>
</Tooltip>
}
>
{(triggerRef) => (
<IconButton
@@ -438,14 +460,14 @@ export function DockedCallContent() {
<TooltipProvider
position="Top"
offset={4}
tooltip={<Tooltip><Text>End Call</Text></Tooltip>}
tooltip={
<Tooltip>
<Text>End Call</Text>
</Tooltip>
}
>
{(triggerRef) => (
<IconButton
ref={triggerRef}
onClick={handleEndCall}
variant="Critical"
>
<IconButton ref={triggerRef} onClick={handleEndCall} variant="Critical">
<Icon size="300" src={Icons.Phone} />
</IconButton>
)}
+2 -2
View File
@@ -10,11 +10,11 @@ import * as css from './CallOverlay.css';
*/
export function DockedCallPanel() {
const isCallDockedRight = useIsCallDockedRight();
if (!isCallDockedRight) {
return null;
}
return (
<>
<Line variant="Background" direction="Vertical" size="300" />
@@ -44,18 +44,21 @@ function isDirectOrSmallGroup(room: Room): boolean {
* @param myUserId - The current user's ID
* @returns Object with member IDs and earliest call start time
*/
function getOtherCallMembersWithTime(room: Room, myUserId: string): { members: string[]; earliestTime: number } {
function getOtherCallMembersWithTime(
room: Room,
myUserId: string,
): { members: string[]; earliestTime: number } {
const members: string[] = [];
const now = Date.now();
let earliestTime = now;
try {
const stateEvents = room.currentState.getStateEvents(CALL_MEMBER_EVENT_TYPE);
stateEvents.forEach((event) => {
const content = event.getContent();
const userId = event.getStateKey();
if (!userId || userId === myUserId || !content['m.calls']) return;
const calls = content['m.calls'];
@@ -67,7 +70,7 @@ function getOtherCallMembersWithTime(room: Room, myUserId: string): { members: s
devices.forEach((device) => {
const expiresTs = device.expires_ts || 0;
if (expiresTs > now && !members.includes(userId)) {
members.push(userId);
// Track event origin time to determine call age
@@ -122,7 +125,7 @@ export function IncomingCallNotification() {
const rooms = mx.getRooms();
const now = Date.now();
const MAX_CALL_AGE = 10000; // 10 seconds
// Find the first room with an incoming call
const incomingRoom = rooms.find((room) => {
// Only monitor 1-1 DMs (exactly 2 members)
@@ -131,11 +134,11 @@ export function IncomingCallNotification() {
if (declinedRooms.has(room.roomId)) return false;
const { members, earliestTime } = getOtherCallMembersWithTime(room, myUserId);
if (members.length === 0) return false;
// Skip if we've already seen this exact call session
const lastSeenTime = seenCalls.get(room.roomId);
if (lastSeenTime && lastSeenTime === earliestTime) return false;
// Only show if the call is fresh (less than 10 seconds old)
const callAge = now - earliestTime;
return callAge < MAX_CALL_AGE;
@@ -157,35 +160,38 @@ export function IncomingCallNotification() {
/**
* Handles state events for call member changes
*/
const handleStateEvent = useCallback((event: MatrixEvent) => {
if (event.getType() === CALL_MEMBER_EVENT_TYPE) {
// Clear declined status and seen calls if call ended in that room
const roomId = event.getRoomId();
if (roomId) {
const room = mx.getRoom(roomId);
if (room) {
const myUserId = mx.getUserId();
if (myUserId) {
const members = getOtherCallMembers(room, myUserId);
if (members.length === 0) {
// Call ended, clear tracking
setDeclinedRooms((prev) => {
const newSet = new Set(prev);
newSet.delete(roomId);
return newSet;
});
setSeenCalls((prev) => {
const newMap = new Map(prev);
newMap.delete(roomId);
return newMap;
});
const handleStateEvent = useCallback(
(event: MatrixEvent) => {
if (event.getType() === CALL_MEMBER_EVENT_TYPE) {
// Clear declined status and seen calls if call ended in that room
const roomId = event.getRoomId();
if (roomId) {
const room = mx.getRoom(roomId);
if (room) {
const myUserId = mx.getUserId();
if (myUserId) {
const members = getOtherCallMembers(room, myUserId);
if (members.length === 0) {
// Call ended, clear tracking
setDeclinedRooms((prev) => {
const newSet = new Set(prev);
newSet.delete(roomId);
return newSet;
});
setSeenCalls((prev) => {
const newMap = new Map(prev);
newMap.delete(roomId);
return newMap;
});
}
}
}
}
checkForIncomingCalls();
}
checkForIncomingCalls();
}
}, [checkForIncomingCalls, declinedRooms, mx]);
},
[checkForIncomingCalls, declinedRooms, mx],
);
// Set up event listeners
useEffect(() => {
@@ -205,15 +211,27 @@ export function IncomingCallNotification() {
if (incomingCall) {
// Mark this call as seen so we don't notify again
setSeenCalls((prev) => new Map(prev).set(incomingCall.roomId, incomingCall.startTime));
const callAge = Date.now() - incomingCall.startTime;
const MAX_CALL_AGE_FOR_SOUND = 15000; // 15 seconds
if (callAge < MAX_CALL_AGE_FOR_SOUND) {
getCallSounds().playSound(CallSoundType.CallDialing, true);
console.log('🔔 Incoming call from room:', incomingCall.roomName, '(age:', Math.round(callAge / 1000), 's)');
console.log(
'🔔 Incoming call from room:',
incomingCall.roomName,
'(age:',
Math.round(callAge / 1000),
's)',
);
} else {
console.log('📞 Incoming call too old for sound:', incomingCall.roomName, '(age:', Math.round(callAge / 1000), 's)');
console.log(
'📞 Incoming call too old for sound:',
incomingCall.roomName,
'(age:',
Math.round(callAge / 1000),
's)',
);
getCallSounds().stopDialingLoop();
}
} else {
@@ -230,7 +248,7 @@ export function IncomingCallNotification() {
*/
const handleAccept = useCallback(async () => {
if (!incomingCall) return;
getCallSounds().stopDialingLoop();
setSeenCalls((prev) => new Map(prev).set(incomingCall.roomId, incomingCall.startTime));
try {
@@ -245,7 +263,7 @@ export function IncomingCallNotification() {
*/
const handleDecline = useCallback(() => {
if (!incomingCall) return;
getCallSounds().stopDialingLoop();
setSeenCalls((prev) => new Map(prev).set(incomingCall.roomId, incomingCall.startTime));
setDeclinedRooms((prev) => new Set(prev).add(incomingCall.roomId));
@@ -260,7 +278,7 @@ export function IncomingCallNotification() {
const room = mx.getRoom(incomingCall.roomId);
const firstCaller = incomingCall.callerIds[0];
const isGroupCall = room ? room.getJoinedMemberCount() > 2 : false;
/**
* Gets the display name for a user
*/
@@ -320,18 +338,10 @@ export function IncomingCallNotification() {
</div>
<Box alignItems="Center" gap="200" className={css.CallActions}>
<IconButton
onClick={handleDecline}
variant="Critical"
className={css.DeclineButton}
>
<IconButton onClick={handleDecline} variant="Critical" className={css.DeclineButton}>
<Icon size="300" src={Icons.Cross} />
</IconButton>
<IconButton
onClick={handleAccept}
variant="Success"
className={css.AcceptButton}
>
<IconButton onClick={handleAccept} variant="Success" className={css.AcceptButton}>
<Icon size="300" src={Icons.Phone} />
</IconButton>
</Box>
@@ -22,7 +22,7 @@ interface RemoteCursorOverlayProps {
*/
function resolveParticipantUserId(
livekitIdentity: string,
callMembers: { userId: string; deviceId: string }[]
callMembers: { userId: string; deviceId: string }[],
): string {
const underscoreIndex = livekitIdentity.lastIndexOf('_');
const possibleDeviceId =
@@ -60,10 +60,7 @@ function CursorDot({
opacity: cursor.visible ? 1 : 0,
}}
/>
<div
className={css.RemoteCursorLabel}
style={{ left, top, color: 'white' }}
>
<div className={css.RemoteCursorLabel} style={{ left, top, color: 'white' }}>
{displayName}
</div>
</>
@@ -100,7 +97,7 @@ export function RemoteCursorOverlay({ shareId, roomId }: RemoteCursorOverlayProp
});
const remoteCursors = Array.from(cursors.entries()).filter(
([participantId]) => participantId !== myIdentity
([participantId]) => participantId !== myIdentity,
);
if (remoteCursors.length === 0) return null;
@@ -1,7 +1,7 @@
import React, { useEffect, useState } from 'react';
import { Box, IconButton, Scroll, Text, Tooltip, TooltipProvider, color } from 'folds';
import { Icon, Icons } from '../../components/icons';
import { useSetAtom } from 'jotai';
import { Icon, Icons } from '../../components/icons';
import { useCall } from './useCall';
import { useRoomCallMembers } from './useRoomCallMembers';
import { CallState } from './types';
@@ -69,10 +69,10 @@ export function SidebarDockedCallPanel() {
const isParticipantSpeaking = (userId: string): boolean => {
if (!activeCall) return false;
if (activeCall.activeSpeakers.has(userId)) return true;
const member = callMembers.find((m) => m.userId === userId);
if (!member) return false;
return Array.from(activeCall.activeSpeakers).some((speakerId) => {
const underscoreIndex = speakerId.lastIndexOf('_');
const deviceId = underscoreIndex > 0 ? speakerId.substring(0, underscoreIndex) : speakerId;
@@ -86,10 +86,10 @@ export function SidebarDockedCallPanel() {
const isParticipantMuted = (userId: string): boolean => {
if (!activeCall) return false;
if (userId === myUserId) return activeCall.isMuted;
const member = callMembers.find((m) => m.userId === userId);
if (!member) return false;
return Array.from(activeCall.mutedParticipants).some((mutedId) => {
const underscoreIndex = mutedId.lastIndexOf('_');
const deviceId = underscoreIndex > 0 ? mutedId.substring(0, underscoreIndex) : mutedId;
@@ -102,7 +102,7 @@ export function SidebarDockedCallPanel() {
*/
const handleHeaderMouseDown = async (e: React.MouseEvent) => {
if ((e.target as HTMLElement).closest('button')) return;
if (document.fullscreenElement) {
try {
await document.exitFullscreen();
@@ -110,10 +110,10 @@ export function SidebarDockedCallPanel() {
// Ignore
}
}
const header = e.currentTarget as HTMLElement;
const rect = header.getBoundingClientRect();
setPendingDrag({
startX: e.clientX,
startY: e.clientY,
@@ -121,11 +121,16 @@ export function SidebarDockedCallPanel() {
offsetY: e.clientY - rect.top,
timestamp: Date.now(),
});
setIsDocked(false);
};
if (!isCallDockedSidebar || !activeCall || activeCall.state === CallState.Idle || activeCall.state === CallState.Ended) {
if (
!isCallDockedSidebar ||
!activeCall ||
activeCall.state === CallState.Idle ||
activeCall.state === CallState.Ended
) {
return null;
}
@@ -138,14 +143,11 @@ export function SidebarDockedCallPanel() {
<div className={css.SidebarDockedCallContainer}>
{/* Header - drag to undock */}
{/* eslint-disable-next-line jsx-a11y/no-static-element-interactions */}
<div
className={css.SidebarDockedCallHeader}
onMouseDown={handleHeaderMouseDown}
>
<div className={css.SidebarDockedCallHeader} onMouseDown={handleHeaderMouseDown}>
<Box alignItems="Center" gap="200" style={{ minWidth: 0, flex: 1 }}>
<Icon size="100" src={Icons.Phone} />
<Text size="T300" truncate>
{isConnecting ? 'Connecting...' : room?.name ?? 'Call'}
{isConnecting ? 'Connecting...' : (room?.name ?? 'Call')}
</Text>
{selectedRoomId === activeCall.roomId && (
<Icon size="100" src={Icons.Check} style={{ opacity: 0.7 }} />
@@ -159,13 +161,17 @@ export function SidebarDockedCallPanel() {
<TooltipProvider
position="Top"
offset={4}
tooltip={<Tooltip><Text>Go to Room</Text></Tooltip>}
tooltip={
<Tooltip>
<Text>Go to Room</Text>
</Tooltip>
}
>
{(triggerRef) => (
<IconButton
ref={triggerRef}
onClick={() => navigateRoom(activeCall.roomId)}
variant="Secondary"
<IconButton
ref={triggerRef}
onClick={() => navigateRoom(activeCall.roomId)}
variant="Secondary"
size="300"
>
<Icon size="100" src={Icons.Link} />
@@ -199,18 +205,19 @@ export function SidebarDockedCallPanel() {
{allParticipants.map((participantId) => {
const avatarMxc = getMemberAvatarMxc(room, participantId);
const avatarUrl = avatarMxc
? mxcUrlToHttp(mx, avatarMxc, useAuthentication, 32, 32, 'crop') ?? undefined
? (mxcUrlToHttp(mx, avatarMxc, useAuthentication, 32, 32, 'crop') ?? undefined)
: undefined;
const displayName = getMemberDisplayName(room, participantId)
?? getMxIdLocalPart(participantId)
?? participantId;
const displayName =
getMemberDisplayName(room, participantId) ??
getMxIdLocalPart(participantId) ??
participantId;
const isMe = participantId === myUserId;
const isMuted = isParticipantMuted(participantId);
const isSpeaking = isParticipantSpeaking(participantId);
return (
<div key={participantId} className={css.ParticipantItem}>
<div
<div
className={`${css.ParticipantAvatarWrapper} ${isSpeaking ? css.ParticipantSpeaking : ''}`}
>
<UserAvatar
@@ -231,9 +238,7 @@ export function SidebarDockedCallPanel() {
{isMe && <span className={css.YouBadge}> (You)</span>}
</Text>
</Box>
{isMuted && (
<Icon size="100" src={Icons.MicMute} style={{ opacity: 0.5 }} />
)}
{isMuted && <Icon size="100" src={Icons.MicMute} style={{ opacity: 0.5 }} />}
</div>
);
})}
@@ -247,7 +252,11 @@ export function SidebarDockedCallPanel() {
<TooltipProvider
position="Top"
offset={4}
tooltip={<Tooltip><Text>{activeCall.isMuted ? 'Unmute' : 'Mute'}</Text></Tooltip>}
tooltip={
<Tooltip>
<Text>{activeCall.isMuted ? 'Unmute' : 'Mute'}</Text>
</Tooltip>
}
>
{(triggerRef) => (
<IconButton
@@ -264,7 +273,11 @@ export function SidebarDockedCallPanel() {
<TooltipProvider
position="Top"
offset={4}
tooltip={<Tooltip><Text>{activeCall.isDeafened ? 'Undeafen' : 'Deafen'}</Text></Tooltip>}
tooltip={
<Tooltip>
<Text>{activeCall.isDeafened ? 'Undeafen' : 'Deafen'}</Text>
</Tooltip>
}
>
{(triggerRef) => (
<IconButton
@@ -281,15 +294,14 @@ export function SidebarDockedCallPanel() {
<TooltipProvider
position="Top"
offset={4}
tooltip={<Tooltip><Text>End Call</Text></Tooltip>}
tooltip={
<Tooltip>
<Text>End Call</Text>
</Tooltip>
}
>
{(triggerRef) => (
<IconButton
ref={triggerRef}
onClick={endCall}
variant="Critical"
size="300"
>
<IconButton ref={triggerRef} onClick={endCall} variant="Critical" size="300">
<Icon size="200" src={Icons.Phone} />
</IconButton>
)}
+55 -25
View File
@@ -2,7 +2,11 @@ import { createContext, useContext, useState, useCallback, useEffect, useMemo }
import { useMatrixClient } from '../../hooks/useMatrixClient';
import { CallService } from './CallService';
import { ActiveCall, CallEvent, CallEventType, CallState, CallType } from './types';
import { fetchWellKnownWithRTC, getLiveKitFocus, getLiveKitHomeserverPriority } from './useRtcConfig';
import {
fetchWellKnownWithRTC,
getLiveKitFocus,
getLiveKitHomeserverPriority,
} from './useRtcConfig';
interface CallContextValue {
callService: CallService | null;
@@ -93,7 +97,7 @@ export function useCallService(): CallContextValue {
userId,
deviceId,
},
mx
mx,
);
setCallService(service);
@@ -105,14 +109,16 @@ export function useCallService(): CallContextValue {
unsubscribe = service.on((event: CallEvent) => {
// Update state for any event that might change the call state
if (event.type === CallEventType.StateChanged ||
event.type === CallEventType.ScreenShareStarted ||
event.type === CallEventType.ScreenShareStopped ||
event.type === CallEventType.RemoteStreamAdded ||
event.type === CallEventType.RemoteStreamRemoved ||
event.type === CallEventType.ParticipantJoined ||
event.type === CallEventType.ParticipantLeft ||
event.type === CallEventType.SpeakersChanged) {
if (
event.type === CallEventType.StateChanged ||
event.type === CallEventType.ScreenShareStarted ||
event.type === CallEventType.ScreenShareStopped ||
event.type === CallEventType.RemoteStreamAdded ||
event.type === CallEventType.RemoteStreamRemoved ||
event.type === CallEventType.ParticipantJoined ||
event.type === CallEventType.ParticipantLeft ||
event.type === CallEventType.SpeakersChanged
) {
const newCall = service?.getActiveCall();
if (newCall) {
// Deep copy Maps and Sets to ensure React detects changes
@@ -152,7 +158,7 @@ export function useCallService(): CallContextValue {
}
await callService.startCall(roomId, callType);
},
[callService]
[callService],
);
const endCall = useCallback(async () => {
@@ -223,7 +229,18 @@ export function useCallService(): CallContextValue {
toggleVideo,
toggleScreenShare,
}),
[callService, activeCall, callSupported, callSupportLoading, startCall, endCall, toggleMute, toggleDeafen, toggleVideo, toggleScreenShare]
[
callService,
activeCall,
callSupported,
callSupportLoading,
startCall,
endCall,
toggleMute,
toggleDeafen,
toggleVideo,
toggleScreenShare,
],
);
}
@@ -231,7 +248,14 @@ export function useCallService(): CallContextValue {
* Hook to check if a call is active in a specific room
*/
export function useRoomCall(roomId: string) {
const { activeCall, startCall, endCall, callSupported: globalCallSupported, callSupportLoading: globalCallSupportLoading, callService } = useCall();
const {
activeCall,
startCall,
endCall,
callSupported: globalCallSupported,
callSupportLoading: globalCallSupportLoading,
callService,
} = useCall();
const mx = useMatrixClient();
const [roomCallSupported, setRoomCallSupported] = useState(false);
const [roomCallSupportLoading, setRoomCallSupportLoading] = useState(true);
@@ -240,7 +264,7 @@ export function useRoomCall(roomId: string) {
useEffect(() => {
const checkRoomCallSupport = async () => {
setRoomCallSupportLoading(true);
const room = mx.getRoom(roomId);
if (!room) {
setRoomCallSupported(false);
@@ -252,10 +276,13 @@ export function useRoomCall(roomId: string) {
const homeserverPriority = getLiveKitHomeserverPriority(
room,
mx.getHomeserverUrl(),
mx.getSafeUserId()
mx.getSafeUserId(),
);
console.log(`Checking call support for room ${roomId}, homeserver priority:`, homeserverPriority);
console.log(
`Checking call support for room ${roomId}, homeserver priority:`,
homeserverPriority,
);
// Check each homeserver in priority order
for (const homeserver of homeserverPriority) {
@@ -263,10 +290,10 @@ export function useRoomCall(roomId: string) {
console.log(`Fetching well-known from ${homeserver}...`);
const wellKnown = await fetchWellKnownWithRTC(homeserver);
console.log(`Well-known response from ${homeserver}:`, wellKnown);
const livekitFocus = getLiveKitFocus(wellKnown);
console.log(`LiveKit focus from ${homeserver}:`, livekitFocus);
if (livekitFocus) {
console.log(`Call support found for room ${roomId} on homeserver: ${homeserver}`);
setRoomCallSupported(true);
@@ -290,29 +317,32 @@ export function useRoomCall(roomId: string) {
const isInCall = activeCall?.roomId === roomId;
const callState = isInCall ? activeCall.state : CallState.Idle;
const isUsingRemoteHomeserver = isInCall ? callService?.isUsingRemoteHomeserver() ?? false : false;
const isUsingRemoteHomeserver = isInCall
? (callService?.isUsingRemoteHomeserver() ?? false)
: false;
// Check if a remote homeserver WOULD be used (pre-call check)
const wouldUseRemoteHomeserver = useMemo(() => {
if (isInCall) return isUsingRemoteHomeserver;
const room = mx.getRoom(roomId);
if (!room) return false;
const homeserverPriority = getLiveKitHomeserverPriority(
room,
mx.getHomeserverUrl(),
mx.getSafeUserId()
mx.getSafeUserId(),
);
// Check if first priority is different from user's homeserver
const userHomeserverDomain = mx.getHomeserverUrl()
const userHomeserverDomain = mx
.getHomeserverUrl()
.replace('https://', '')
.replace('http://', '');
const firstPriorityDomain = homeserverPriority[0]
?.replace('https://', '')
.replace('http://', '');
return firstPriorityDomain !== userHomeserverDomain;
}, [isInCall, isUsingRemoteHomeserver, mx, roomId]);
+6 -5
View File
@@ -10,10 +10,11 @@ import { CallState } from './types';
export function useIsCallDocked(): boolean {
const { activeCall } = useCall();
const [isDocked] = useSetting(settingsAtom, 'isCallPanelDocked');
const hasActiveCall = activeCall &&
const hasActiveCall =
activeCall &&
(activeCall.state === CallState.Connecting || activeCall.state === CallState.Connected);
return Boolean(hasActiveCall && isDocked);
}
@@ -23,7 +24,7 @@ export function useIsCallDocked(): boolean {
export function useIsCallDockedRight(): boolean {
const isCallDocked = useIsCallDocked();
const [dockPosition] = useSetting(settingsAtom, 'callPanelDockPosition');
return isCallDocked && dockPosition === 'right';
}
@@ -33,7 +34,7 @@ export function useIsCallDockedRight(): boolean {
export function useIsCallDockedSidebar(): boolean {
const isCallDocked = useIsCallDocked();
const [dockPosition] = useSetting(settingsAtom, 'callPanelDockPosition');
return isCallDocked && dockPosition === 'sidebar';
}
+3 -3
View File
@@ -70,7 +70,7 @@ export function useSendCursor(shareId: string) {
});
}
},
[callService]
[callService],
);
/**
@@ -87,7 +87,7 @@ export function useSendCursor(shareId: string) {
sendCursorData({ x, y, visible: true, shareId });
},
[showRemoteCursor, sendCursorData, shareId]
[showRemoteCursor, sendCursorData, shareId],
);
/**
@@ -127,7 +127,7 @@ export function useReceiveCursors(shareId: string): Map<string, RemoteCursorStat
payload: Uint8Array,
participant?: { identity: string },
_kind?: unknown,
topic?: string
topic?: string,
) => {
if (!participant) return;
// Only process cursor messages by topic
+3 -3
View File
@@ -25,11 +25,11 @@ export function getActiveCallMembers(room: Room): CallMember[] {
try {
const stateEvents = room.currentState.getStateEvents(CALL_MEMBER_EVENT_TYPE);
stateEvents.forEach((event) => {
const content = event.getContent();
const userId = event.getStateKey();
if (!userId || !content['m.calls']) return;
const calls = content['m.calls'];
@@ -41,7 +41,7 @@ export function getActiveCallMembers(room: Room): CallMember[] {
devices.forEach((device) => {
const expiresTs = device.expires_ts || 0;
// Check if the call membership is still valid (not expired)
if (expiresTs > now) {
members.push({
+48 -33
View File
@@ -2,8 +2,7 @@ import { useCallback } from 'react';
import { Room } from 'matrix-js-sdk';
import { useMatrixClient } from '../../hooks/useMatrixClient';
import { LiveKitFocus, LiveKitJWTResponse, OpenIdToken, WellKnownWithRTC } from './types';
import { getMxIdServer } from '../../utils/matrix';
import { guessDmRoomUserId } from '../../utils/matrix';
import { getMxIdServer, guessDmRoomUserId } from '../../utils/matrix';
import { getActiveCallMembers } from './useRoomCallMembers';
/**
@@ -26,21 +25,23 @@ function getRoomServer(roomId: string): string | undefined {
export function getLiveKitHomeserverPriority(
room: Room,
userHomeserver: string,
myUserId: string
myUserId: string,
): string[] {
const servers: string[] = [];
const memberCount = room.getMembers().length;
const isDM = memberCount <= 2;
console.log(`[getLiveKitHomeserverPriority] Room: ${room.roomId}`);
console.log(`[getLiveKitHomeserverPriority] Member count: ${memberCount}, isDM: ${isDM}`);
console.log(`[getLiveKitHomeserverPriority] User homeserver: ${userHomeserver}`);
// Check for active call members
const activeCallMembers = getActiveCallMembers(room);
const hasActiveCall = activeCallMembers.length > 0;
console.log(`[getLiveKitHomeserverPriority] Active call members: ${activeCallMembers.length}, hasActiveCall: ${hasActiveCall}`);
console.log(
`[getLiveKitHomeserverPriority] Active call members: ${activeCallMembers.length}, hasActiveCall: ${hasActiveCall}`,
);
if (hasActiveCall) {
// Joining existing call - prioritize room's homeserver (where call is hosted)
@@ -49,13 +50,13 @@ export function getLiveKitHomeserverPriority(
if (roomServer) {
servers.push(`https://${roomServer}`);
}
// Add user's homeserver as fallback
const userDomain = userHomeserver.replace('https://', '').replace('http://', '');
if (!roomServer || roomServer !== userDomain) {
servers.push(userHomeserver);
}
// For DMs, also try other member's homeserver
if (isDM) {
const otherUserId = guessDmRoomUserId(room, myUserId);
@@ -72,7 +73,7 @@ export function getLiveKitHomeserverPriority(
console.log(`[getLiveKitHomeserverPriority] DM path - user homeserver first`);
// For DMs: user's homeserver first, then other member's homeserver
servers.push(userHomeserver);
const otherUserId = guessDmRoomUserId(room, myUserId);
console.log(`[getLiveKitHomeserverPriority] Other user ID: ${otherUserId}`);
if (otherUserId && otherUserId !== myUserId) {
@@ -91,10 +92,12 @@ export function getLiveKitHomeserverPriority(
if (roomServer) {
servers.push(`https://${roomServer}`);
}
// Fallback to user's homeserver if different
const userDomain = userHomeserver.replace('https://', '').replace('http://', '');
console.log(`[getLiveKitHomeserverPriority] User domain: ${userDomain}, room server: ${roomServer}`);
console.log(
`[getLiveKitHomeserverPriority] User domain: ${userDomain}, room server: ${roomServer}`,
);
if (!roomServer || roomServer !== userDomain) {
servers.push(userHomeserver);
}
@@ -113,7 +116,7 @@ export function getLiveKitHomeserverPriority(
export function getLiveKitFocus(wellKnown: WellKnownWithRTC): LiveKitFocus | undefined {
const rtcFoci = wellKnown['org.matrix.msc4143.rtc_foci'];
console.log(`[getLiveKitFocus] rtcFoci from well-known:`, rtcFoci);
if (!rtcFoci || !Array.isArray(rtcFoci)) {
console.log(`[getLiveKitFocus] No rtc_foci found or not an array`);
return undefined;
@@ -131,8 +134,9 @@ export function getLiveKitFocus(wellKnown: WellKnownWithRTC): LiveKitFocus | und
*/
export async function fetchWellKnownWithRTC(baseUrl: string): Promise<WellKnownWithRTC> {
// In development mode (localhost), use CORS proxy to avoid CORS issues
const isDev = window.location.hostname === 'localhost' || window.location.hostname === '127.0.0.1';
const isDev =
window.location.hostname === 'localhost' || window.location.hostname === '127.0.0.1';
let wellKnownUrl: string;
if (isDev) {
// Extract hostname from baseUrl for proxy
@@ -165,14 +169,18 @@ export async function fetchWellKnownWithRTC(baseUrl: string): Promise<WellKnownW
export async function requestOpenIdToken(
homeserverBaseUrl: string,
userId: string,
accessToken: string
accessToken: string,
): Promise<OpenIdToken> {
// In development mode (localhost), use CORS proxy to avoid CORS issues
const isDev = window.location.hostname === 'localhost' || window.location.hostname === '127.0.0.1';
const isDev =
window.location.hostname === 'localhost' || window.location.hostname === '127.0.0.1';
let url: string;
if (isDev) {
const hostname = homeserverBaseUrl.replace('https://', '').replace('http://', '').replace(/\/$/, '');
const hostname = homeserverBaseUrl
.replace('https://', '')
.replace('http://', '')
.replace(/\/$/, '');
url = `/_matrix-cors-proxy/${hostname}/_matrix/client/v3/user/${encodeURIComponent(userId)}/openid/request_token`;
} else {
url = `${homeserverBaseUrl}/_matrix/client/v3/user/${encodeURIComponent(userId)}/openid/request_token`;
@@ -209,7 +217,7 @@ export async function fetchLiveKitJWT(
roomId: string,
userId: string,
deviceId: string,
openIdToken: OpenIdToken
openIdToken: OpenIdToken,
): Promise<LiveKitJWTResponse> {
// Generate a unique member ID for this participant (used for identity, not room assignment)
const memberId = `${deviceId}_${Date.now()}`;
@@ -220,14 +228,15 @@ export async function fetchLiveKitJWT(
const slotId = 'm.call';
// In development mode (localhost), use CORS proxy to avoid CORS issues
const isDev = window.location.hostname === 'localhost' || window.location.hostname === '127.0.0.1';
const isDev =
window.location.hostname === 'localhost' || window.location.hostname === '127.0.0.1';
let url: string;
if (isDev) {
// Extract hostname and path from livekitServiceUrl
const urlObj = new URL(livekitServiceUrl);
const hostname = urlObj.hostname;
const pathname = urlObj.pathname;
const { hostname } = urlObj;
const { pathname } = urlObj;
url = `/_matrix-cors-proxy/${hostname}${pathname}`;
} else {
url = livekitServiceUrl;
@@ -274,34 +283,34 @@ export async function fetchLiveKitJWTFromServers(
roomId: string,
userId: string,
deviceId: string,
accessToken: string
accessToken: string,
): Promise<{ jwt: LiveKitJWTResponse; homeserver: string } | null> {
for (const homeserver of homeservers) {
try {
console.log(`Trying LiveKit JWT from homeserver: ${homeserver}`);
// Fetch well-known from this homeserver
const wellKnown = await fetchWellKnownWithRTC(homeserver);
const livekitFocus = getLiveKitFocus(wellKnown);
if (!livekitFocus) {
console.log(`No LiveKit config on ${homeserver}, trying next...`);
continue;
}
// Always get OpenID token from user's own homeserver
// (Can't use access token on remote homeserver)
const openIdToken = await requestOpenIdToken(userHomeserver, userId, accessToken);
// Exchange for LiveKit JWT
const jwt = await fetchLiveKitJWT(
livekitFocus.livekit_service_url,
roomId,
userId,
deviceId,
openIdToken
openIdToken,
);
console.log(`Successfully got LiveKit JWT from ${homeserver}`);
return { jwt, homeserver };
} catch (error) {
@@ -309,7 +318,7 @@ export async function fetchLiveKitJWTFromServers(
// Continue to next homeserver
}
}
console.error('Failed to get LiveKit JWT from any homeserver');
return null;
}
@@ -348,9 +357,15 @@ export function useRtcConfig() {
const openIdToken = await requestOpenIdToken(baseUrl, userId, accessToken);
// Exchange for LiveKit JWT
return fetchLiveKitJWT(livekitFocus.livekit_service_url, roomId, userId, deviceId, openIdToken);
return fetchLiveKitJWT(
livekitFocus.livekit_service_url,
roomId,
userId,
deviceId,
openIdToken,
);
},
[mx]
[mx],
);
const isCallSupported = useCallback(async (): Promise<boolean> => {
@@ -1,7 +1,23 @@
import React, { useCallback, useMemo, useState } from 'react';
import { Box, Text, IconButton, Scroll, Switch, Button, MenuItem, config, color, TextArea, Dialog, Overlay, OverlayBackdrop, OverlayCenter, Modal } from 'folds';
import { Icon, Icons } from '../../../components/icons';
import {
Box,
Text,
IconButton,
Scroll,
Switch,
Button,
MenuItem,
config,
color,
TextArea,
Dialog,
Overlay,
OverlayBackdrop,
OverlayCenter,
Modal,
} from 'folds';
import FocusTrap from 'focus-trap-react';
import { Icon, Icons } from '../../../components/icons';
import { Page, PageContent, PageHeader } from '../../../components/page';
import { SequenceCard } from '../../../components/sequence-card';
import { SequenceCardStyle } from '../styles.css';
@@ -54,7 +70,10 @@ export function DeveloperTools({ requestClose }: DeveloperToolsProps) {
const newestEvent = liveEvents.length > 0 ? liveEvents[liveEvents.length - 1] : null;
// Get power level tags
const powerLevelTagsEvent = room.currentState.getStateEvents('in.cinny.room.power_level_tags', '');
const powerLevelTagsEvent = room.currentState.getStateEvents(
'in.cinny.room.power_level_tags',
'',
);
const powerLevelTags = powerLevelTagsEvent?.getContent();
const info: any = {
@@ -122,7 +141,7 @@ export function DeveloperTools({ requestClose }: DeveloperToolsProps) {
async (type, content) => {
await mx.setRoomAccountData(room.roomId, type, content);
},
[mx, room.roomId]
[mx, room.roomId],
);
if (accountDataType !== undefined) {
@@ -1,6 +1,17 @@
import React, { useCallback, useRef, useState, FormEventHandler, useEffect } from 'react';
import { MatrixError } from 'matrix-js-sdk';
import { Box, Chip, IconButton, Text, config, Button, Spinner, color, TextArea, Input } from 'folds';
import {
Box,
Chip,
IconButton,
Text,
config,
Button,
Spinner,
color,
TextArea,
Input,
} from 'folds';
import { Icon, Icons } from '../../../components/icons';
import { Page, PageHeader } from '../../../components/page';
import { useMatrixClient } from '../../../hooks/useMatrixClient';
@@ -28,7 +39,7 @@ export function SendRoomEvent({ type, stateKey, requestClose }: SendRoomEventPro
const [jsonError, setJSONError] = useState<SyntaxError>();
const { handleKeyDown, operations, getTarget } = useTextAreaCodeEditor(
textAreaRef,
EDITOR_INTENT_SPACE_COUNT
EDITOR_INTENT_SPACE_COUNT,
);
const [submitState, submit] = useAsyncCallback<
@@ -43,8 +54,8 @@ export function SendRoomEvent({ type, stateKey, requestClose }: SendRoomEventPro
}
return mx.sendEvent(room.roomId, evtType as any, evtContent);
},
[mx, room]
)
[mx, room],
),
);
const submitting = submitState.status === AsyncStatus.Loading;
@@ -1,7 +1,18 @@
import React, { FormEventHandler, useCallback, useEffect, useMemo, useRef, useState } from 'react';
import { Box, Text, IconButton, Chip, Scroll, config, TextArea, color, Spinner, Button } from 'folds';
import { Icon, Icons } from '../../../components/icons';
import {
Box,
Text,
IconButton,
Chip,
Scroll,
config,
TextArea,
color,
Spinner,
Button,
} from 'folds';
import { MatrixError } from 'matrix-js-sdk';
import { Icon, Icons } from '../../../components/icons';
import { Page, PageHeader } from '../../../components/page';
import { SequenceCard } from '../../../components/sequence-card';
import { TextViewerContent } from '../../../components/text-viewer';
@@ -35,21 +46,21 @@ function StateEventEdit({ type, stateKey, content, requestClose }: StateEventEdi
const defaultContentStr = useMemo(
() => JSON.stringify(content, undefined, EDITOR_INTENT_SPACE_COUNT),
[content]
[content],
);
const textAreaRef = useRef<HTMLTextAreaElement>(null);
const [jsonError, setJSONError] = useState<SyntaxError>();
const { handleKeyDown, operations, getTarget } = useTextAreaCodeEditor(
textAreaRef,
EDITOR_INTENT_SPACE_COUNT
EDITOR_INTENT_SPACE_COUNT,
);
const [submitState, submit] = useAsyncCallback<object, MatrixError, [object]>(
useCallback(
(c) => mx.sendStateEvent(room.roomId, type as any, c, stateKey),
[mx, room, type, stateKey]
)
[mx, room, type, stateKey],
),
);
const submitting = submitState.status === AsyncStatus.Loading;
@@ -1,7 +1,20 @@
import React, { FormEventHandler, useCallback, useMemo, useState } from 'react';
import { Box, Text, Button, Avatar, AvatarFallback, toRem, config, Input, Spinner, color, IconButton, Menu } from 'folds';
import { Icon, Icons } from '../../../components/icons';
import {
Box,
Text,
Button,
Avatar,
AvatarFallback,
toRem,
config,
Input,
Spinner,
color,
IconButton,
Menu,
} from 'folds';
import { MatrixError } from 'matrix-js-sdk';
import { Icon, Icons } from '../../../components/icons';
import { SequenceCard } from '../../../components/sequence-card';
import {
ImagePack,
@@ -45,8 +58,8 @@ function CreatePackTile({ packs, roomId }: CreatePackTileProps) {
};
await mx.sendStateEvent(roomId, StateEvent.PoniesRoomEmotes as any, content, stateKey);
},
[mx, roomId]
)
[mx, roomId],
),
);
const creating = addState.status === AsyncStatus.Loading;
@@ -152,7 +165,7 @@ export function RoomPacks({ onViewPack }: RoomPacksProps) {
// eslint-disable-next-line no-await-in-loop
await mx.sendStateEvent(room.roomId, StateEvent.PoniesRoomEmotes as any, {}, addr.stateKey);
}
}, [mx, room, removedPacks])
}, [mx, room, removedPacks]),
);
const applyingChanges = applyState.status === AsyncStatus.Loading;
@@ -1,5 +1,16 @@
import React, { FormEventHandler, useCallback, useState } from 'react';
import { Box, Button, Chip, color, config, Input, Spinner, Text, Tooltip, TooltipProvider } from 'folds';
import {
Box,
Button,
Chip,
color,
config,
Input,
Spinner,
Text,
Tooltip,
TooltipProvider,
} from 'folds';
import { Icon, Icons } from '../../../components/icons';
import { SequenceCard } from '../../../components/sequence-card';
import { SequenceCardStyle } from '../../room-settings/styles.css';
@@ -181,8 +192,8 @@ export function PersonalEmbedFilters() {
async (newFilters: EmbedFiltersContent) => {
await setFilters(newFilters);
},
[setFilters]
)
[setFilters],
),
);
const saving = saveState.status === AsyncStatus.Loading;
@@ -243,8 +254,8 @@ export function RoomWideEmbedFilters() {
async (newFilters: EmbedFiltersContent) => {
await setRoomWideFilters(newFilters);
},
[setRoomWideFilters]
)
[setRoomWideFilters],
),
);
const saving = saveState.status === AsyncStatus.Loading;
@@ -1,7 +1,19 @@
import React, { FormEventHandler, useCallback, useState } from 'react';
import { Badge, Box, Button, Checkbox, Chip, color, config, Input, Spinner, Text, toRem } from 'folds';
import { Icon, Icons } from '../../../components/icons';
import {
Badge,
Box,
Button,
Checkbox,
Chip,
color,
config,
Input,
Spinner,
Text,
toRem,
} from 'folds';
import { MatrixError } from 'matrix-js-sdk';
import { Icon, Icons } from '../../../components/icons';
import { SettingTile } from '../../../components/setting-tile';
import { SequenceCard } from '../../../components/sequence-card';
import { SequenceCardStyle } from '../../room-settings/styles.css';
@@ -31,7 +43,7 @@ export function RoomPublishedAddresses({ permissions }: RoomPublishedAddressesPr
const canEditCanonical = permissions.stateEvent(
StateEvent.RoomCanonicalAlias,
mx.getSafeUserId()
mx.getSafeUserId(),
);
const [canonicalAlias, publishedAliases] = usePublishedAliases(room);
@@ -228,8 +240,8 @@ function LocalAddressesList({
await removeLocalAlias(alias);
}
},
[removeLocalAlias]
)
[removeLocalAlias],
),
);
const [publishState, publish] = useAsyncCallback(publishAliases);
const [unpublishState, unpublish] = useAsyncCallback(unpublishAliases);
@@ -352,7 +364,7 @@ export function RoomLocalAddresses({ permissions }: { permissions: RoomPermissio
const canEditCanonical = permissions.stateEvent(
StateEvent.RoomCanonicalAlias,
mx.getSafeUserId()
mx.getSafeUserId(),
);
const [expand, setExpand] = useState(false);
@@ -1,8 +1,22 @@
import { Badge, Box, Button, color, config, Dialog, Header, IconButton, Overlay, OverlayBackdrop, OverlayCenter, Spinner, Text } from 'folds';
import { Icon, Icons } from '../../../components/icons';
import {
Badge,
Box,
Button,
color,
config,
Dialog,
Header,
IconButton,
Overlay,
OverlayBackdrop,
OverlayCenter,
Spinner,
Text,
} from 'folds';
import React, { useCallback, useState } from 'react';
import { MatrixError } from 'matrix-js-sdk';
import FocusTrap from 'focus-trap-react';
import { Icon, Icons } from '../../../components/icons';
import { SequenceCard } from '../../../components/sequence-card';
import { SequenceCardStyle } from '../../room-settings/styles.css';
import { SettingTile } from '../../../components/setting-tile';
@@ -34,7 +48,7 @@ export function RoomEncryption({ permissions }: RoomEncryptionProps) {
await mx.sendStateEvent(room.roomId, StateEvent.RoomEncryption as any, {
algorithm: ROOM_ENC_ALGO,
});
}, [mx, room.roomId])
}, [mx, room.roomId]),
);
const enabling = enableState.status === AsyncStatus.Loading;
@@ -1,9 +1,9 @@
import React, { MouseEventHandler, useCallback, useMemo, useState } from 'react';
import { Button, color, config, Menu, MenuItem, PopOut, RectCords, Spinner, Text } from 'folds';
import { Icon, Icons } from '../../../components/icons';
import { HistoryVisibility, MatrixError } from 'matrix-js-sdk';
import { RoomHistoryVisibilityEventContent } from 'matrix-js-sdk/lib/types';
import FocusTrap from 'focus-trap-react';
import { Icon, Icons } from '../../../components/icons';
import { SequenceCard } from '../../../components/sequence-card';
import { SequenceCardStyle } from '../../room-settings/styles.css';
import { SettingTile } from '../../../components/setting-tile';
@@ -23,7 +23,7 @@ const useVisibilityStr = () =>
[HistoryVisibility.Shared]: 'All Messages',
[HistoryVisibility.WorldReadable]: 'All Messages (Guests)',
}),
[]
[],
);
const useVisibilityMenu = () =>
@@ -34,7 +34,7 @@ const useVisibilityMenu = () =>
HistoryVisibility.Joined,
HistoryVisibility.WorldReadable,
],
[]
[],
);
type RoomHistoryVisibilityProps = {
@@ -67,8 +67,8 @@ export function RoomHistoryVisibility({ permissions }: RoomHistoryVisibilityProp
};
await mx.sendStateEvent(room.roomId, StateEvent.RoomHistoryVisibility as any, content);
},
[mx, room.roomId]
)
[mx, room.roomId],
),
);
const submitting = submitState.status === AsyncStatus.Loading;
@@ -115,8 +115,8 @@ export function RoomJoinRules({ permissions }: RoomJoinRulesProps) {
if (allow.length > 0) c.allow = allow;
await mx.sendStateEvent(room.roomId, StateEvent.RoomJoinRules as any, c);
},
[mx, room, space, subspaces, roomIdToParents]
)
[mx, room, space, subspaces, roomIdToParents],
),
);
const submitting = submitState.status === AsyncStatus.Loading;
@@ -1,10 +1,10 @@
import { Avatar, Box, Button, Chip, color, Input, Spinner, Text, TextArea } from 'folds';
import { Icon, Icons } from '../../../components/icons';
import React, { FormEventHandler, useCallback, useMemo, useState } from 'react';
import { useAtomValue } from 'jotai';
import Linkify from 'linkify-react';
import classNames from 'classnames';
import { JoinRule, MatrixError } from 'matrix-js-sdk';
import { Icon, Icons } from '../../../components/icons';
import { SequenceCard } from '../../../components/sequence-card';
import { SequenceCardStyle } from '../../room-settings/styles.css';
import { useRoom } from '../../../hooks/useRoom';
@@ -56,7 +56,7 @@ export function RoomProfileEdit({
const [roomAvatar, setRoomAvatar] = useState(avatar);
const avatarUrl = roomAvatar
? mxcUrlToHttp(mx, roomAvatar, useAuthentication) ?? undefined
? (mxcUrlToHttp(mx, roomAvatar, useAuthentication) ?? undefined)
: undefined;
const [imageFile, setImageFile] = useState<File>();
@@ -93,8 +93,8 @@ export function RoomProfileEdit({
await mx.sendStateEvent(room.roomId, StateEvent.RoomTopic as any, { topic: roomTopic });
}
},
[mx, room.roomId]
)
[mx, room.roomId],
),
);
const submitting = submitState.status === AsyncStatus.Loading;
@@ -117,7 +117,7 @@ export function RoomProfileEdit({
submit(
roomAvatar === avatar ? undefined : roomAvatar || null,
roomName === name ? undefined : roomName,
roomTopic === topic ? undefined : roomTopic
roomTopic === topic ? undefined : roomTopic,
).then(() => {
if (alive()) {
onClose();
@@ -269,7 +269,7 @@ export function RoomProfile({ permissions }: RoomProfileProps) {
const canEdit = canEditAvatar || canEditName || canEditTopic;
const avatarUrl = avatar
? mxcUrlToHttp(mx, avatar, useAuthentication, 96, 96, 'crop') ?? undefined
? (mxcUrlToHttp(mx, avatar, useAuthentication, 96, 96, 'crop') ?? undefined)
: undefined;
const [edit, setEdit] = useState(false);
@@ -23,7 +23,7 @@ export function RoomPublish({ permissions }: RoomPublishProps) {
const canEditCanonical = permissions.stateEvent(
StateEvent.RoomCanonicalAlias,
mx.getSafeUserId()
mx.getSafeUserId(),
);
const joinRuleEvent = useStateEvent(room, StateEvent.RoomJoinRules);
const content = joinRuleEvent?.getContent<RoomJoinRulesEventContent>();
@@ -1,9 +1,22 @@
import React, { useCallback, useEffect, useState } from 'react';
import { Button, color, Spinner, Text, Overlay, OverlayBackdrop, OverlayCenter, Dialog, Header, config, Box, IconButton } from 'folds';
import { Icon, Icons } from '../../../components/icons';
import {
Button,
color,
Spinner,
Text,
Overlay,
OverlayBackdrop,
OverlayCenter,
Dialog,
Header,
config,
Box,
IconButton,
} from 'folds';
import FocusTrap from 'focus-trap-react';
import { MatrixError, Method } from 'matrix-js-sdk';
import { RoomTombstoneEventContent } from 'matrix-js-sdk/lib/types';
import { Icon, Icons } from '../../../components/icons';
import { SequenceCard } from '../../../components/sequence-card';
import { SequenceCardStyle } from '../../room-settings/styles.css';
import { SettingTile } from '../../../components/setting-tile';
@@ -52,8 +65,8 @@ function RoomUpgradeDialog({ requestClose }: { requestClose: () => void }) {
additional_creators: newAdditionalCreators,
});
},
[mx, room]
)
[mx, room],
),
);
const upgrading = upgradeState.status === AsyncStatus.Loading;
@@ -154,14 +167,14 @@ export function RoomUpgrade({ permissions, requestClose }: RoomUpgradeProps) {
const { navigateRoom, navigateSpace } = useRoomNavigate();
const createContent = useStateEvent(
room,
StateEvent.RoomCreate
StateEvent.RoomCreate,
)?.getContent<IRoomCreateContent>();
const roomVersion = createContent?.room_version ?? '1';
const predecessorRoomId = createContent?.predecessor?.room_id;
const tombstoneContent = useStateEvent(
room,
StateEvent.RoomTombstone
StateEvent.RoomTombstone,
)?.getContent<RoomTombstoneEventContent>();
const replacementRoom = tombstoneContent?.replacement_room;
@@ -6,10 +6,22 @@ import React, {
useRef,
useState,
} from 'react';
import { Box, Chip, config, IconButton, Input, PopOut, RectCords, Scroll, Spinner, Text, toRem } from 'folds';
import { Icon, Icons } from '../../../components/icons';
import {
Box,
Chip,
config,
IconButton,
Input,
PopOut,
RectCords,
Scroll,
Spinner,
Text,
toRem,
} from 'folds';
import { useVirtualizer } from '@tanstack/react-virtual';
import { RoomMember } from 'matrix-js-sdk';
import { Icon, Icons } from '../../../components/icons';
import { Page, PageContent, PageHeader } from '../../../components/page';
import { useRoom } from '../../../hooks/useRoom';
import { useRoomMembers } from '../../../hooks/useRoomMembers';
@@ -92,13 +104,13 @@ export function Members({ requestClose }: MembersProps) {
.filter(membershipFilter.filterFn)
.sort(memberSort.sortFn)
.sort(memberPowerSort),
[members, membershipFilter, memberSort, memberPowerSort]
[members, membershipFilter, memberSort, memberPowerSort],
);
const [result, search, resetSearch] = useAsyncSearch(
sortedMembers,
getRoomMemberStr,
SEARCH_OPTIONS
SEARCH_OPTIONS,
);
if (!result && searchInputRef.current?.value) search(searchInputRef.current.value);
@@ -117,9 +129,9 @@ export function Members({ requestClose }: MembersProps) {
if (evt.target.value) search(evt.target.value);
else resetSearch();
},
[search, resetSearch]
[search, resetSearch],
),
{ wait: 200 }
{ wait: 200 },
);
const handleSearchReset = () => {
@@ -212,7 +224,7 @@ export function Members({ requestClose }: MembersProps) {
onClick={
((evt) =>
setAnchor(
evt.currentTarget.getBoundingClientRect()
evt.currentTarget.getBoundingClientRect(),
)) as MouseEventHandler<HTMLButtonElement>
}
variant="SurfaceVariant"
@@ -244,7 +256,7 @@ export function Members({ requestClose }: MembersProps) {
onClick={
((evt) =>
setAnchor(
evt.currentTarget.getBoundingClientRect()
evt.currentTarget.getBoundingClientRect(),
)) as MouseEventHandler<HTMLButtonElement>
}
variant="SurfaceVariant"
@@ -1,8 +1,8 @@
/* eslint-disable react/no-array-index-key */
import React, { useCallback, useEffect, useMemo, useState } from 'react';
import { Badge, Box, Button, Chip, config, Menu, Spinner, Text } from 'folds';
import { Icon, Icons } from '../../../components/icons';
import { produce } from 'immer';
import { Icon, Icons } from '../../../components/icons';
import { SequenceCard } from '../../../components/sequence-card';
import { SequenceCardStyle } from '../styles.css';
import { SettingTile } from '../../../components/setting-tile';
@@ -43,7 +43,7 @@ export function PermissionGroups({
const maxPower = useMemo(() => Math.max(...getPowers(powerLevelTags)), [powerLevelTags]);
const [permissionUpdate, setPermissionUpdate] = useState<Map<PermissionLocation, number>>(
new Map()
new Map(),
);
useEffect(() => {
@@ -55,7 +55,7 @@ export function PermissionGroups({
const handleChangePermission = (
location: PermissionLocation,
newPower: number,
currentPower: number
currentPower: number,
) => {
setPermissionUpdate((p) => {
const up: typeof p = new Map();
@@ -78,16 +78,16 @@ export function PermissionGroups({
group.items.forEach((item) => {
const power = getPermissionPower(powerLevels, item.location);
applyPermissionPower(draftPowerLevels, item.location, power);
})
}),
);
permissionUpdate.forEach((power, location) =>
applyPermissionPower(draftPowerLevels, location, power)
applyPermissionPower(draftPowerLevels, location, power),
);
return draftPowerLevels;
});
await mx.sendStateEvent(room.roomId, StateEvent.RoomPowerLevels as any, editedPowerLevels);
}, [mx, room, powerLevels, permissionUpdate, permissionGroups])
}, [mx, room, powerLevels, permissionUpdate, permissionGroups]),
);
const resetChanges = useCallback(() => {
@@ -1,8 +1,24 @@
import React, { FormEventHandler, MouseEventHandler, useCallback, useMemo, useState } from 'react';
import { Box, Text, Chip, IconButton, Scroll, Button, Input, RectCords, PopOut, Menu, config, Spinner, toRem, TooltipProvider, Tooltip } from 'folds';
import { Icon, Icons } from '../../../components/icons';
import {
Box,
Text,
Chip,
IconButton,
Scroll,
Button,
Input,
RectCords,
PopOut,
Menu,
config,
Spinner,
toRem,
TooltipProvider,
Tooltip,
} from 'folds';
import { HexColorPicker } from 'react-colorful';
import { useAtomValue } from 'jotai';
import { Icon, Icons } from '../../../components/icons';
import { Page, PageContent, PageHeader } from '../../../components/page';
import { IPowerLevels } from '../../../hooks/usePowerLevels';
import { SequenceCard } from '../../../components/sequence-card';
@@ -211,7 +227,7 @@ function EditPower({ maxPower, power, tag, onSave, onClose }: EditPowerProps) {
onClick={
((evt) =>
setCords(
evt.currentTarget.getBoundingClientRect()
evt.currentTarget.getBoundingClientRect(),
)) as MouseEventHandler<HTMLButtonElement>
}
type="button"
@@ -307,7 +323,7 @@ export function PowersEditor({ powerLevels, requestClose }: PowersEditorProps) {
return editedTags;
});
},
[powerLevelTags]
[powerLevelTags],
);
const [applyState, applyChanges] = useAsyncCallback(
@@ -317,7 +333,7 @@ export function PowersEditor({ powerLevels, requestClose }: PowersEditorProps) {
delete content[power];
});
await mx.sendStateEvent(room.roomId, StateEvent.PowerLevelTags as any, content);
}, [mx, room, powerLevelTags, editedPowerTags, deleted])
}, [mx, room, powerLevelTags, editedPowerTags, deleted]),
);
const resetChanges = useCallback(() => {
+4 -4
View File
@@ -1,8 +1,8 @@
import { Box, Button, color, config, Input, Spinner, Switch, Text } from 'folds';
import { Icon, Icons } from '../../components/icons';
import React, { FormEventHandler, useCallback, useState } from 'react';
import { ICreateRoomStateEvent, MatrixError, Preset, Visibility } from 'matrix-js-sdk';
import { useNavigate } from 'react-router-dom';
import { Icon, Icons } from '../../components/icons';
import { SettingTile } from '../../components/setting-tile';
import { SequenceCard } from '../../components/sequence-card';
import { addRoomIdToMDirect, isUserId } from '../../utils/matrix';
@@ -46,8 +46,8 @@ export function CreateChat({ defaultUserId }: CreateChatProps) {
return result.room_id;
},
[mx]
)
[mx],
),
);
const loading = createState.status === AsyncStatus.Loading;
const error = createState.status === AsyncStatus.Error ? createState.error : undefined;
@@ -129,7 +129,7 @@ export function CreateChat({ defaultUserId }: CreateChatProps) {
<b>
{error instanceof MatrixError && error.name === ErrorCode.M_LIMIT_EXCEEDED
? `Server rate-limited your request for ${millisecondsToMinutes(
(error.data.retry_after_ms as number | undefined) ?? 0
(error.data.retry_after_ms as number | undefined) ?? 0,
)} minutes!`
: error.message}
</b>
+3 -3
View File
@@ -54,7 +54,7 @@ export function CreateRoomForm({ defaultKind, space, onCreate }: CreateRoomFormP
const allowRestricted = space && restrictedSupported(selectedRoomVersion);
const [kind, setKind] = useState(
defaultKind ?? allowRestricted ? CreateRoomKind.Restricted : CreateRoomKind.Private
(defaultKind ?? allowRestricted) ? CreateRoomKind.Restricted : CreateRoomKind.Private,
);
const allowAdditionalCreators = creatorsSupported(selectedRoomVersion);
const { additionalCreators, addAdditionalCreator, removeAdditionalCreator } =
@@ -77,7 +77,7 @@ export function CreateRoomForm({ defaultKind, space, onCreate }: CreateRoomFormP
};
const [createState, create] = useAsyncCallback<string, Error | MatrixError, [CreateRoomData]>(
useCallback((data) => createRoom(mx, data), [mx])
useCallback((data) => createRoom(mx, data), [mx]),
);
const loading = createState.status === AsyncStatus.Loading;
const error = createState.status === AsyncStatus.Error ? createState.error : undefined;
@@ -292,7 +292,7 @@ export function CreateRoomForm({ defaultKind, space, onCreate }: CreateRoomFormP
<b>
{error instanceof MatrixError && error.name === ErrorCode.M_LIMIT_EXCEEDED
? `Server rate-limited your request for ${millisecondsToMinutes(
(error.data.retry_after_ms as number | undefined) ?? 0
(error.data.retry_after_ms as number | undefined) ?? 0,
)} minutes!`
: error.message}
</b>
@@ -1,8 +1,19 @@
import React, { useCallback } from 'react';
import { Box, config, Header, IconButton, Modal, Overlay, OverlayBackdrop, OverlayCenter, Scroll, Text } from 'folds';
import { Icon, Icons } from '../../components/icons';
import {
Box,
config,
Header,
IconButton,
Modal,
Overlay,
OverlayBackdrop,
OverlayCenter,
Scroll,
Text,
} from 'folds';
import FocusTrap from 'focus-trap-react';
import { useAtomValue } from 'jotai';
import { Icon, Icons } from '../../components/icons';
import { useAllJoinedRoomsSet, useGetRoom } from '../../hooks/useGetRoom';
import { SpaceProvider } from '../../hooks/useSpace';
import { CreateRoomForm } from './CreateRoom';
@@ -49,7 +60,7 @@ function CreateRoomModal({ state }: CreateRoomModalProps) {
canonical: true,
via: viaServers,
},
parentSubRoomId
parentSubRoomId,
);
// Set m.space.child on the parent room pointing to this sub-room
@@ -57,19 +68,17 @@ function CreateRoomModal({ state }: CreateRoomModalProps) {
parentSubRoomId,
StateEvent.SpaceChild,
{ via: viaServers },
newRoomId
newRoomId,
);
// Copy parent's join_rules to the sub-room
const parentJoinRulesEvent = parentRoom.currentState.getStateEvents(StateEvent.RoomJoinRules, '');
const parentJoinRulesEvent = parentRoom.currentState.getStateEvents(
StateEvent.RoomJoinRules,
'',
);
if (parentJoinRulesEvent) {
const joinRulesContent = parentJoinRulesEvent.getContent();
await mx.sendStateEvent(
newRoomId,
StateEvent.RoomJoinRules,
joinRulesContent,
''
);
await mx.sendStateEvent(newRoomId, StateEvent.RoomJoinRules, joinRulesContent, '');
}
// Add new room to parent's sub-rooms list
@@ -80,7 +89,12 @@ function CreateRoomModal({ state }: CreateRoomModalProps) {
children: [...currentChildren, newRoomId],
};
// eslint-disable-next-line @typescript-eslint/no-explicit-any
await mx.sendStateEvent(parentSubRoomId, StateEvent.PaarrotSubRooms as any, newContent, '');
await mx.sendStateEvent(
parentSubRoomId,
StateEvent.PaarrotSubRooms as any,
newContent,
'',
);
// Also add sub-room to parent's space(s) for joining/permissions
// The UI will hide it from the top-level display and only show it nested
@@ -101,14 +115,14 @@ function CreateRoomModal({ state }: CreateRoomModalProps) {
// eslint-disable-next-line @typescript-eslint/no-explicit-any
StateEvent.SpaceChild as any,
{ via: spaceViaServers },
newRoomId
newRoomId,
);
} catch (spaceError) {
// eslint-disable-next-line no-console
console.warn(`Failed to add sub-room to space ${parentSpaceId}:`, spaceError);
}
}
})
}),
);
}
} catch (error) {
@@ -118,7 +132,7 @@ function CreateRoomModal({ state }: CreateRoomModalProps) {
}
closeDialog();
},
[mx, parentSubRoomId, parentRoom, roomToParents, closeDialog]
[mx, parentSubRoomId, parentRoom, roomToParents, closeDialog],
);
const modalTitle = parentSubRoomId ? 'New Sub-Room' : 'New Room';
+29 -13
View File
@@ -1,7 +1,28 @@
import React, { FormEventHandler, MouseEventHandler, useCallback, useEffect, useState } from 'react';
import React, {
FormEventHandler,
MouseEventHandler,
useCallback,
useEffect,
useState,
} from 'react';
import { MatrixError, Room } from 'matrix-js-sdk';
import FocusTrap from 'focus-trap-react';
import { Box, Button, Chip, color, config, Input, Menu, MenuItem, PopOut, RectCords, Spinner, Switch, Text, TextArea } from 'folds';
import {
Box,
Button,
Chip,
color,
config,
Input,
Menu,
MenuItem,
PopOut,
RectCords,
Spinner,
Switch,
Text,
TextArea,
} from 'folds';
import { Icon, Icons } from '../../components/icons';
import { SettingTile } from '../../components/setting-tile';
import { SequenceCard } from '../../components/sequence-card';
@@ -62,7 +83,7 @@ export function CreateSpaceForm({ defaultKind, space, onCreate }: CreateSpaceFor
const allowRestricted = space && restrictedSupported(selectedRoomVersion);
const [kind, setKind] = useState(
defaultKind ?? allowRestricted ? CreateRoomKind.Restricted : CreateRoomKind.Private
(defaultKind ?? allowRestricted) ? CreateRoomKind.Restricted : CreateRoomKind.Private,
);
const allowAdditionalCreators = creatorsSupported(selectedRoomVersion);
@@ -94,7 +115,7 @@ export function CreateSpaceForm({ defaultKind, space, onCreate }: CreateSpaceFor
};
const [createState, create] = useAsyncCallback<string, Error | MatrixError, [CreateRoomData]>(
useCallback((data) => createRoom(mx, data), [mx])
useCallback((data) => createRoom(mx, data), [mx]),
);
const loading = createState.status === AsyncStatus.Loading;
const error = createState.status === AsyncStatus.Error ? createState.error : undefined;
@@ -146,12 +167,7 @@ export function CreateSpaceForm({ defaultKind, space, onCreate }: CreateSpaceFor
}).then(async (roomId) => {
if (spaceType === RoomType.Forum) {
try {
await mx.sendStateEvent(
roomId,
StateEvent.PaarrotRoomKind,
{ kind: 'forum_space' },
''
);
await mx.sendStateEvent(roomId, StateEvent.PaarrotRoomKind, { kind: 'forum_space' }, '');
} catch (err) {
// eslint-disable-next-line no-console
console.warn('Failed to set forum space marker state event:', err);
@@ -250,8 +266,8 @@ export function CreateSpaceForm({ defaultKind, space, onCreate }: CreateSpaceFor
)}
{parentIsForum && (
<Text size="T200" priority="300">
Creates a forum category (subspace). Add topics inside it with Add Topic after selecting the
category in the filter bar.
Creates a forum category (subspace). Add topics inside it with Add Topic after selecting
the category in the filter bar.
</Text>
)}
<Box shrink="No" direction="Column" gap="100">
@@ -362,7 +378,7 @@ export function CreateSpaceForm({ defaultKind, space, onCreate }: CreateSpaceFor
<b>
{error instanceof MatrixError && error.name === ErrorCode.M_LIMIT_EXCEEDED
? `Server rate-limited your request for ${millisecondsToMinutes(
(error.data.retry_after_ms as number | undefined) ?? 0
(error.data.retry_after_ms as number | undefined) ?? 0,
)} minutes!`
: error.message}
</b>
@@ -1,7 +1,18 @@
import React from 'react';
import { Box, config, Header, IconButton, Modal, Overlay, OverlayBackdrop, OverlayCenter, Scroll, Text } from 'folds';
import { Icon, Icons } from '../../components/icons';
import {
Box,
config,
Header,
IconButton,
Modal,
Overlay,
OverlayBackdrop,
OverlayCenter,
Scroll,
Text,
} from 'folds';
import FocusTrap from 'focus-trap-react';
import { Icon, Icons } from '../../components/icons';
import { useAllJoinedRoomsSet, useGetRoom } from '../../hooks/useGetRoom';
import { SpaceProvider } from '../../hooks/useSpace';
import { CreateSpaceForm } from './CreateSpace';
@@ -37,11 +37,13 @@ export function ForumAuthorIdentity({
const useAuthentication = useMediaAuthentication();
const mxc = room ? getMemberAvatarMxc(room, sender) : undefined;
const avatarUrl = mxc
? mxcUrlToHttp(mx, mxc, useAuthentication, compact ? 36 : 48, compact ? 36 : 48, 'crop') ??
undefined
? (mxcUrlToHttp(mx, mxc, useAuthentication, compact ? 36 : 48, compact ? 36 : 48, 'crop') ??
undefined)
: undefined;
const name =
displayName || (room ? getMemberDisplayName(room, sender) : undefined) || matrixUserLocalpart(sender);
displayName ||
(room ? getMemberDisplayName(room, sender) : undefined) ||
matrixUserLocalpart(sender);
const server = matrixUserServer(sender);
const identityClass = compact
@@ -57,9 +59,7 @@ export function ForumAuthorIdentity({
userId={sender}
src={avatarUrl}
alt={name}
renderFallback={() => (
<Text size="L400">{name.slice(0, 1).toUpperCase()}</Text>
)}
renderFallback={() => <Text size="L400">{name.slice(0, 1).toUpperCase()}</Text>}
/>
</Avatar>
</span>
+5 -6
View File
@@ -1,8 +1,8 @@
import React, { useCallback, useEffect, useMemo, useRef, useState } from 'react';
import { Box, Scroll, Text, color } from 'folds';
import { Icon, Icons } from '../../components/icons';
import classNames from 'classnames';
import { useSetAtom } from 'jotai';
import { Icon, Icons } from '../../components/icons';
import { useMatrixClient } from '../../hooks/useMatrixClient';
import { Page, PageContent } from '../../components/page';
import { ContainerColor } from '../../styles/ContainerColor.css';
@@ -31,7 +31,7 @@ export function ForumBoardDetail() {
const topicSelected = Boolean(query.topic);
const setActiveThreadId = useSetAtom(
activeThreadIdAtomFamily(activeTopicRoomId ?? forumSpace.roomId)
activeThreadIdAtomFamily(activeTopicRoomId ?? forumSpace.roomId),
);
useEffect(() => {
@@ -51,7 +51,7 @@ export function ForumBoardDetail() {
const selectedThread = useMemo(
() => threads.find((t) => t.eventId === selectedPostId),
[threads, selectedPostId]
[threads, selectedPostId],
);
const handleReplySent = useCallback(
@@ -60,12 +60,11 @@ export function ForumBoardDetail() {
recordThreadReply(selectedPostId);
}
},
[recordThreadReply, selectedPostId]
[recordThreadReply, selectedPostId],
);
const showThread = Boolean(selectedPostId && activeTopicRoom);
const threadInitialPost =
optimisticPost?.eventId === selectedPostId ? optimisticPost : null;
const threadInitialPost = optimisticPost?.eventId === selectedPostId ? optimisticPost : null;
const detailDropRef = useRef<HTMLDivElement>(null);
return (
+15 -6
View File
@@ -1,8 +1,8 @@
import React, { useCallback, useEffect, useRef } from 'react';
import { Box, Text } from 'folds';
import { Icon, Icons } from '../../components/icons';
import { Room } from 'matrix-js-sdk';
import { useSetAtom } from 'jotai';
import { Icon, Icons } from '../../components/icons';
import { Page, PageContent } from '../../components/page';
import { useMatrixClient } from '../../hooks/useMatrixClient';
import { PowerLevelsContextProvider, usePowerLevels } from '../../hooks/usePowerLevels';
@@ -48,7 +48,7 @@ export function ForumBoardView({ forumSpace, scope }: ForumBoardViewProps) {
const activeTopicRoom = activeTopicRoomId ? mx.getRoom(activeTopicRoomId) : null;
const topicPowerLevels = usePowerLevels(activeTopicRoom ?? forumSpace);
const setActiveThreadId = useSetAtom(
activeThreadIdAtomFamily(activeTopicRoomId ?? forumSpace.roomId)
activeThreadIdAtomFamily(activeTopicRoomId ?? forumSpace.roomId),
);
const topicSelected = Boolean(query.topic || scope.topicRoomId);
@@ -64,7 +64,7 @@ export function ForumBoardView({ forumSpace, scope }: ForumBoardViewProps) {
const getTopicRoom = useCallback(
(roomId: string | undefined) => (roomId ? mx.getRoom(roomId) : null),
[mx]
[mx],
);
const handlePostPublished = useCallback(
@@ -73,7 +73,7 @@ export function ForumBoardView({ forumSpace, scope }: ForumBoardViewProps) {
selectPost(published.eventId, published.topicRoomId);
detailScrollRef.current?.scrollIntoView({ behavior: 'smooth' });
},
[insertThreadFromNewPost, selectPost]
[insertThreadFromNewPost, selectPost],
);
const showComposer = Boolean(activeTopicRoom && (!selectedPostId || topicSelected));
@@ -129,7 +129,13 @@ export function ForumBoardView({ forumSpace, scope }: ForumBoardViewProps) {
<ThreadView room={activeTopicRoom} threadRootId={selectedPostId} />
</PowerLevelsContextProvider>
) : (
<Box grow="Yes" alignItems="Center" justifyContent="Center" direction="Column" gap="200">
<Box
grow="Yes"
alignItems="Center"
justifyContent="Center"
direction="Column"
gap="200"
>
<Icon src={Icons.Thread} size="600" />
<Text priority="300">
{topicSelected
@@ -143,7 +149,10 @@ export function ForumBoardView({ forumSpace, scope }: ForumBoardViewProps) {
<Box
shrink="No"
direction="Column"
style={{ padding: '0.75rem', borderTop: '1px solid var(--fc-surface-container)' }}
style={{
padding: '0.75rem',
borderTop: '1px solid var(--fc-surface-container)',
}}
>
<PowerLevelsContextProvider value={topicPowerLevels}>
<RoomInput
+14 -14
View File
@@ -2,6 +2,8 @@ import React, { KeyboardEventHandler, useCallback, useRef, useState } from 'reac
import { isKeyHotkey } from 'is-hotkey';
import { Editor } from 'slate';
import { IconButton, Line, PopOut } from 'folds';
import { useAtomValue } from 'jotai';
import { Room } from 'matrix-js-sdk';
import { Icon, Icons } from '../../components/icons';
import {
CustomEditor,
@@ -19,9 +21,7 @@ import { UseStateProvider } from '../../components/UseStateProvider';
import { useSetting } from '../../state/hooks/settings';
import { settingsAtom } from '../../state/settings';
import { useImagePackRooms } from '../../hooks/useImagePackRooms';
import { useAtomValue } from 'jotai';
import { roomToParentsAtom } from '../../state/room/roomToParents';
import { Room } from 'matrix-js-sdk';
import { mobileOrTablet } from '../../utils/user-agent';
import { PluginButtonSlot } from '../settings/plugins/PluginButtonSlot';
@@ -62,7 +62,7 @@ export function ForumChatComposer({
onSend();
}
},
[enterForNewline, onSend]
[enterForNewline, onSend],
);
const handleKeyUp: KeyboardEventHandler = useCallback(
@@ -74,7 +74,7 @@ export function ForumChatComposer({
}
setAutocompleteQuery(undefined);
},
[editor]
[editor],
);
const handleEmoticonSelect = (key: string, shortcode: string) => {
@@ -126,7 +126,7 @@ export function ForumChatComposer({
anchor={
emojiBoardTab === undefined
? undefined
: emojiBtnRef.current?.getBoundingClientRect() ?? undefined
: (emojiBtnRef.current?.getBoundingClientRect() ?? undefined)
}
content={
<EmojiBoard
@@ -136,15 +136,15 @@ export function ForumChatComposer({
returnFocusOnDeactivate={false}
onEmojiSelect={handleEmoticonSelect}
onCustomEmojiSelect={handleEmoticonSelect}
requestClose={() => {
setEmojiBoardTab((t) => {
if (t) {
if (!mobileOrTablet()) safeFocusEditor(editor);
return undefined;
}
return t;
});
}}
requestClose={() => {
setEmojiBoardTab((t) => {
if (t) {
if (!mobileOrTablet()) safeFocusEditor(editor);
return undefined;
}
return t;
});
}}
/>
}
>
+4 -2
View File
@@ -33,8 +33,10 @@ export function ForumEventContent({
}, [event, eventId, timelineSet]);
const getContent = useCallback<GetContentCallback>(
() => editedEvent?.getContent()['m.new_content'] ?? event?.getContent() ?? { body, msgtype: 'm.text' },
[editedEvent, event, body]
() =>
editedEvent?.getContent()['m.new_content'] ??
event?.getContent() ?? { body, msgtype: 'm.text' },
[editedEvent, event, body],
);
if (!event || event.getType() !== EventType.RoomMessage) {
+3 -4
View File
@@ -1,8 +1,7 @@
import React, { useCallback } from 'react';
import { Text, color } from 'folds';
import { useMatrixClient } from '../../hooks/useMatrixClient';
import { usePowerLevels } from '../../hooks/usePowerLevels';
import { PowerLevelsContextProvider } from '../../hooks/usePowerLevels';
import { usePowerLevels, PowerLevelsContextProvider } from '../../hooks/usePowerLevels';
import { useForumBoardContext } from './ForumBoardContext';
import { ForumFilterBar } from './ForumFilterBar';
import { ForumPostList } from './ForumPostList';
@@ -36,7 +35,7 @@ export function ForumFeedSidebar() {
const getTopicRoom = useCallback(
(roomId: string | undefined) => (roomId ? mx.getRoom(roomId) : null),
[mx]
[mx],
);
const handlePostPublished = useCallback(
@@ -44,7 +43,7 @@ export function ForumFeedSidebar() {
insertThreadFromNewPost(published);
selectPost(published.eventId, published.topicRoomId);
},
[insertThreadFromNewPost, selectPost]
[insertThreadFromNewPost, selectPost],
);
return (
+2 -2
View File
@@ -36,7 +36,7 @@ export function ForumFilterBar({
onCategoryChange,
}: ForumFilterBarProps) {
const categoryTopics = query.category
? sections.find((s) => s.title === query.category)?.topics ?? []
? (sections.find((s) => s.title === query.category)?.topics ?? [])
: sections.flatMap((s) => s.topics);
const [searchDraft, setSearchDraft] = useState(query.q || '');
@@ -47,7 +47,7 @@ export function ForumFilterBar({
const applySearch = useCallback(() => {
const trimmed = searchDraft.trim();
onQueryChange('q', trimmed ? trimmed : null);
onQueryChange('q', trimmed || null);
}, [onQueryChange, searchDraft]);
const handleSearchSubmit: FormEventHandler<HTMLFormElement> = (evt) => {
+91 -91
View File
@@ -1,7 +1,7 @@
import React, { MouseEventHandler, useEffect, useRef, useState } from 'react';
import { Box, IconButton, Menu, PopOut } from 'folds';
import { Icon, Icons } from '../../components/icons';
import { Room } from 'matrix-js-sdk';
import { Icon, Icons } from '../../components/icons';
import { EmojiBoard } from '../../components/emoji-board';
import { copyToClipboard } from '../../utils/dom';
import { PluginButtonSlot } from '../settings/plugins/PluginButtonSlot';
@@ -72,103 +72,103 @@ export function ForumMessageActions({
return (
<Menu className={theme.ForumMessageOptionsBar} variant="SurfaceVariant">
<Box gap="100" direction="Row" alignItems="Center">
{canSendReaction && eventId && onReactionToggle && (
<PopOut
position="Bottom"
align="End"
anchor={emojiBoardAnchor}
content={
<EmojiBoard
imagePackRooms={imagePackRooms}
returnFocusOnDeactivate={false}
allowTextCustomEmoji
onEmojiSelect={(key) => {
onReactionToggle(eventId, key);
setEmojiBoardAnchor(undefined);
}}
onCustomEmojiSelect={(mxc, shortcode) => {
onReactionToggle(eventId, mxc, shortcode);
setEmojiBoardAnchor(undefined);
}}
requestClose={() => setEmojiBoardAnchor(undefined)}
/>
}
{canSendReaction && eventId && onReactionToggle && (
<PopOut
position="Bottom"
align="End"
anchor={emojiBoardAnchor}
content={
<EmojiBoard
imagePackRooms={imagePackRooms}
returnFocusOnDeactivate={false}
allowTextCustomEmoji
onEmojiSelect={(key) => {
onReactionToggle(eventId, key);
setEmojiBoardAnchor(undefined);
}}
onCustomEmojiSelect={(mxc, shortcode) => {
onReactionToggle(eventId, mxc, shortcode);
setEmojiBoardAnchor(undefined);
}}
requestClose={() => setEmojiBoardAnchor(undefined)}
/>
}
>
<IconButton
ref={emojiBtnRef}
onClick={handleOpenEmojiBoard}
variant="SurfaceVariant"
size="300"
radii="300"
aria-label="Add reaction"
title="Add reaction"
aria-pressed={!!emojiBoardAnchor}
>
<Icon src={Icons.SmilePlus} size="100" />
</IconButton>
</PopOut>
)}
<IconButton
onClick={handleReplyClick}
variant="SurfaceVariant"
size="300"
radii="300"
aria-label="Reply"
title="Reply"
aria-pressed={replyActive}
className={replyActive ? theme.ForumMessageActionBtnActive : undefined}
>
<Icon src={Icons.ReplyArrow} size="100" />
</IconButton>
{canEdit && onEdit && (
<IconButton
ref={emojiBtnRef}
onClick={handleOpenEmojiBoard}
onClick={onEdit}
variant="SurfaceVariant"
size="300"
radii="300"
aria-label="Add reaction"
title="Add reaction"
aria-pressed={!!emojiBoardAnchor}
aria-label="Edit"
title="Edit"
>
<Icon src={Icons.SmilePlus} size="100" />
<Icon src={Icons.Pencil} size="100" />
</IconButton>
</PopOut>
)}
<IconButton
onClick={handleReplyClick}
variant="SurfaceVariant"
size="300"
radii="300"
aria-label="Reply"
title="Reply"
aria-pressed={replyActive}
className={replyActive ? theme.ForumMessageActionBtnActive : undefined}
>
<Icon src={Icons.ReplyArrow} size="100" />
</IconButton>
{canEdit && onEdit && (
<IconButton
onClick={onEdit}
variant="SurfaceVariant"
size="300"
radii="300"
aria-label="Edit"
title="Edit"
>
<Icon src={Icons.Pencil} size="100" />
</IconButton>
)}
{body && (
<IconButton
onClick={() => copyToClipboard(body)}
variant="SurfaceVariant"
size="300"
radii="300"
aria-label="Copy raw text"
title="Copy raw text"
>
<Icon src={Icons.File} size="100" />
</IconButton>
)}
{shiftHeld && canDelete && onDelete && (
<IconButton
onClick={onDelete}
variant="Critical"
size="300"
radii="300"
aria-label="Delete"
title="Delete message (Shift held)"
>
<Icon src={Icons.Delete} size="100" />
</IconButton>
)}
<PluginButtonSlot location="message-actions" />
{menu && (
<IconButton
onClick={handleOpenMenu}
variant="SurfaceVariant"
size="300"
radii="300"
aria-label="Message menu"
title="More actions"
>
<Icon src={Icons.VerticalDots} size="100" />
</IconButton>
)}
)}
{body && (
<IconButton
onClick={() => copyToClipboard(body)}
variant="SurfaceVariant"
size="300"
radii="300"
aria-label="Copy raw text"
title="Copy raw text"
>
<Icon src={Icons.File} size="100" />
</IconButton>
)}
{shiftHeld && canDelete && onDelete && (
<IconButton
onClick={onDelete}
variant="Critical"
size="300"
radii="300"
aria-label="Delete"
title="Delete message (Shift held)"
>
<Icon src={Icons.Delete} size="100" />
</IconButton>
)}
<PluginButtonSlot location="message-actions" />
{menu && (
<IconButton
onClick={handleOpenMenu}
variant="SurfaceVariant"
size="300"
radii="300"
aria-label="Message menu"
title="More actions"
>
<Icon src={Icons.VerticalDots} size="100" />
</IconButton>
)}
</Box>
</Menu>
);
@@ -1,15 +1,7 @@
import React, { MouseEventHandler, ReactNode, useCallback, useState } from 'react';
import FocusTrap from 'focus-trap-react';
import { MatrixEvent, Room } from 'matrix-js-sdk';
import {
Box,
Line,
Menu,
MenuItem,
PopOut,
RectCords,
Text,
} from 'folds';
import { Box, Line, Menu, MenuItem, PopOut, RectCords, Text } from 'folds';
import { Icon, Icons } from '../../components/icons';
import { useMatrixClient } from '../../hooks/useMatrixClient';
import { useSetting } from '../../state/hooks/settings';
@@ -94,7 +86,7 @@ export function ForumMessageContextMenu({
height: 0,
});
},
[disabled, mEvent]
[disabled, mEvent],
);
const handleAddReactions: MouseEventHandler<HTMLButtonElement> = useCallback(() => {
+40 -7
View File
@@ -1,7 +1,30 @@
import React, { FormEventHandler, KeyboardEventHandler, useCallback, useEffect, useMemo, useRef, useState } from 'react';
import React, {
FormEventHandler,
KeyboardEventHandler,
useCallback,
useEffect,
useMemo,
useRef,
useState,
} from 'react';
import { isKeyHotkey } from 'is-hotkey';
import FocusTrap from 'focus-trap-react';
import { Box, Button, Header, IconButton, Modal, Overlay, OverlayBackdrop, OverlayCenter, Line, Scroll, Text, color, config, toRem } from 'folds';
import {
Box,
Button,
Header,
IconButton,
Modal,
Overlay,
OverlayBackdrop,
OverlayCenter,
Line,
Scroll,
Text,
color,
config,
toRem,
} from 'folds';
import { Icon, Icons } from '../../components/icons';
import {
CustomEditor,
@@ -85,7 +108,7 @@ export function ForumNewPostModal({
const trimmedTitle = title.trim();
const plainText = toPlainText(editor.children, false).trim();
const formattedHtml = trimCustomHtml(
toMatrixCustomHTML(editor.children, FORUM_EDITOR_OUTPUT_OPTS)
toMatrixCustomHTML(editor.children, FORUM_EDITOR_OUTPUT_OPTS),
);
const hasText = !isEmptyEditor(editor);
@@ -165,7 +188,7 @@ export function ForumNewPostModal({
sending,
title,
topicRoomId,
]
],
);
const handleEditorKeyDown: KeyboardEventHandler = useCallback(
@@ -175,7 +198,7 @@ export function ForumNewPostModal({
evt.currentTarget.closest('form')?.requestSubmit();
}
},
[sending]
[sending],
);
const handleCategoryChange = useCallback((next: string) => {
@@ -215,7 +238,13 @@ export function ForumNewPostModal({
<Box grow="Yes">
<Text size="H4">New post</Text>
</Box>
<IconButton size="300" radii="300" onClick={handleClose} disabled={sending} aria-label="Close">
<IconButton
size="300"
radii="300"
onClick={handleClose}
disabled={sending}
aria-label="Close"
>
<Icon src={Icons.Cross} />
</IconButton>
</Header>
@@ -264,7 +293,11 @@ export function ForumNewPostModal({
bottom={
<div>
<Line variant="SurfaceVariant" size="300" />
<Box alignItems="Center" gap="200" style={{ padding: `0 ${config.space.S200}` }}>
<Box
alignItems="Center"
gap="200"
style={{ padding: `0 ${config.space.S200}` }}
>
<ForumPostUploadField
roomId={uploadRoomKey}
disabled={sending || !topicRoomId}
+8 -2
View File
@@ -1,7 +1,7 @@
import React, { KeyboardEventHandler } from 'react';
import { Box, Button, Scroll, Spinner, Text } from 'folds';
import { Icon, Icons } from '../../components/icons';
import { Room } from 'matrix-js-sdk';
import { Icon, Icons } from '../../components/icons';
import type { ForumThreadSummary } from './types';
import { formatForumTimeAgo } from './forumTime';
import { ForumPostAuthor } from './ForumPostAuthor';
@@ -91,7 +91,13 @@ export function ForumPostList({
</span>
</div>
{thread.totalReplies > 0 && (
<Box as="span" className={t.ForumReplyMeta} alignItems="Center" gap="100" aria-hidden>
<Box
as="span"
className={t.ForumReplyMeta}
alignItems="Center"
gap="100"
aria-hidden
>
{thread.totalReplies > 1 && (
<Text as="span" className={t.ForumReplyCount} size="L400">
{thread.totalReplies}
@@ -37,7 +37,7 @@ import {
export async function buildContentsFromUploads(
mx: MatrixClient,
items: TUploadItem[],
uploads: UploadSuccess[]
uploads: UploadSuccess[],
): Promise<IContent[]> {
const contentsPromises = uploads.map(async (upload) => {
const fileItem = items.find((f) => f.file === upload.file);
@@ -75,7 +75,7 @@ export function ForumPostUploadField({
const [uploadBoard, setUploadBoard] = useState(true);
const uploadFamilyObserverAtom = createUploadFamilyObserverAtom(
roomUploadAtomFamily,
selectedFiles.map((f) => f.file)
selectedFiles.map((f) => f.file),
);
const handleFiles = useCallback(
@@ -93,7 +93,7 @@ export function ForumPostUploadField({
})),
});
},
[disabled, setSelectedFiles]
[disabled, setSelectedFiles],
);
const pickFiles = useFilePicker(handleFiles, true);
@@ -106,7 +106,7 @@ export function ForumPostUploadField({
replacement: { ...fileItem, metadata },
});
},
[setSelectedFiles]
[setSelectedFiles],
);
const handleRemoveUpload = useCallback(
@@ -118,7 +118,7 @@ export function ForumPostUploadField({
});
uploads.forEach((u) => roomUploadAtomFamily.remove(u));
},
[selectedFiles, setSelectedFiles]
[selectedFiles, setSelectedFiles],
);
const handleCancelUpload = (uploads: Upload[]) => {
@@ -227,7 +227,7 @@ export function useForumPostUploads(roomId: string) {
uploadResolverRef.current = null;
}
},
[mx, selectedFiles, setSelectedFiles]
[mx, selectedFiles, setSelectedFiles],
);
const collectUploadContents = useCallback(async (): Promise<IContent[]> => {
@@ -45,7 +45,7 @@ export function ForumRichReplyComposer({
const plainText = toPlainText(editor.children, false).trim();
const formattedHtml = trimCustomHtml(
toMatrixCustomHTML(editor.children, FORUM_EDITOR_OUTPUT_OPTS)
toMatrixCustomHTML(editor.children, FORUM_EDITOR_OUTPUT_OPTS),
);
if (!plainText) return;
@@ -62,7 +62,7 @@ export function ForumRichReplyComposer({
createForumReplyFromPayload(mx, roomId, eventId, replyToEventId, {
plainText,
formattedHtml,
})
}),
);
} catch (err) {
setError(err instanceof Error ? err.message : 'Failed to send reply');
@@ -70,7 +70,7 @@ export function ForumRichReplyComposer({
setSending(false);
}
},
[editor, mx, onSent, replyToEventId, roomId, sending, threadRootId]
[editor, mx, onSent, replyToEventId, roomId, sending, threadRootId],
);
const handleKeyDown: KeyboardEventHandler = useCallback(
@@ -80,7 +80,7 @@ export function ForumRichReplyComposer({
evt.currentTarget.closest('form')?.requestSubmit();
}
},
[sending]
[sending],
);
return (
@@ -106,11 +106,23 @@ export function ForumRichReplyComposer({
)}
<div className={t.ForumReplyFormActions}>
{onCancel && (
<Button type="button" variant="SurfaceVariant" size="300" onClick={onCancel} disabled={sending}>
<Button
type="button"
variant="SurfaceVariant"
size="300"
onClick={onCancel}
disabled={sending}
>
<Text size="B400">Cancel</Text>
</Button>
)}
<Button type="submit" className={t.ForumReplySubmitBtn} variant="Primary" size="300" disabled={sending}>
<Button
type="submit"
className={t.ForumReplySubmitBtn}
variant="Primary"
size="300"
disabled={sending}
>
<Text size="B400">{sending ? 'Sending…' : 'Send reply'}</Text>
</Button>
</div>
+13 -11
View File
@@ -1,11 +1,10 @@
import React, { useCallback, useEffect, useMemo, useRef, useState } from 'react';
import { Box, Text, color, Scroll } from 'folds';
import { Icon, Icons } from '../../components/icons';
import classNames from 'classnames';
import { useSetAtom } from 'jotai';
import { Icon, Icons } from '../../components/icons';
import { useMatrixClient } from '../../hooks/useMatrixClient';
import { usePowerLevels } from '../../hooks/usePowerLevels';
import { PowerLevelsContextProvider } from '../../hooks/usePowerLevels';
import { usePowerLevels, PowerLevelsContextProvider } from '../../hooks/usePowerLevels';
import { Page, PageContent } from '../../components/page';
import { ContainerColor } from '../../styles/ContainerColor.css';
import { LobbyHeader } from '../lobby/LobbyHeader';
@@ -48,7 +47,7 @@ export function ForumSpaceShell() {
const topicSelected = Boolean(query.topic);
const setActiveThreadId = useSetAtom(
activeThreadIdAtomFamily(activeTopicRoomId ?? forumSpace.roomId)
activeThreadIdAtomFamily(activeTopicRoomId ?? forumSpace.roomId),
);
useEffect(() => {
@@ -68,12 +67,12 @@ export function ForumSpaceShell() {
const selectedThread = useMemo(
() => threads.find((t) => t.eventId === selectedPostId),
[threads, selectedPostId]
[threads, selectedPostId],
);
const getTopicRoom = useCallback(
(roomId: string | undefined) => (roomId ? mx.getRoom(roomId) : null),
[mx]
[mx],
);
const handlePostPublished = useCallback(
@@ -84,7 +83,7 @@ export function ForumSpaceShell() {
}
selectPost(published.eventId, published.topicRoomId);
},
[insertThreadFromNewPost, selectPost]
[insertThreadFromNewPost, selectPost],
);
const handleReplySent = useCallback(
@@ -93,13 +92,12 @@ export function ForumSpaceShell() {
recordThreadReply(selectedPostId);
}
},
[recordThreadReply, selectedPostId]
[recordThreadReply, selectedPostId],
);
const showThread = Boolean(selectedPostId && activeTopicRoom);
const threadInitialPost =
optimisticPost?.eventId === selectedPostId ? optimisticPost : null;
const threadInitialPost = optimisticPost?.eventId === selectedPostId ? optimisticPost : null;
const detailDropRef = useRef<HTMLDivElement>(null);
return (
@@ -123,7 +121,11 @@ export function ForumSpaceShell() {
</section>
<section className={theme.ForumListCard}>
{error && (
<Text as="p" className={theme.ForumListLoading} style={{ color: color.Critical.Main }}>
<Text
as="p"
className={theme.ForumListLoading}
style={{ color: color.Critical.Main }}
>
{error}
</Text>
)}
+126 -101
View File
@@ -1,5 +1,14 @@
// @refresh reset
import { useCallback, useEffect, useMemo, useRef, useState, type MouseEvent, type ReactNode, type RefObject } from 'react';
import {
useCallback,
useEffect,
useMemo,
useRef,
useState,
type MouseEvent,
type ReactNode,
type RefObject,
} from 'react';
import { useAtom, useAtomValue } from 'jotai';
import { Box, Scroll, Spinner, Text, config } from 'folds';
import { RelationType, Room } from 'matrix-js-sdk';
@@ -36,7 +45,7 @@ function forumBranchKey(eventId: string): string {
function forumMessageSurfaceClass(
baseClass: string,
eventId: string,
replyTargetEventId?: string
replyTargetEventId?: string,
): string {
if (replyTargetEventId && replyTargetEventId === eventId) {
return `${baseClass} ${theme.ForumThreadReplyTarget}`;
@@ -159,7 +168,7 @@ function ForumThreadMessage({
: false;
const { canSendReaction, reactionRelations, handleReactionToggle } = useForumMessageReactions(
room,
mEvent
mEvent,
);
const handleDelete = useCallback(() => {
@@ -186,11 +195,19 @@ function ForumThreadMessage({
onReply={() => onReplyTo(post.eventId)}
onEdit={() => onEditEventId(post.eventId)}
onDeleted={onDeleted}
className={forumMessageSurfaceClass(theme.ForumThreadReplyInner, post.eventId, replyTargetEventId)}
className={forumMessageSurfaceClass(
theme.ForumThreadReplyInner,
post.eventId,
replyTargetEventId,
)}
>
<header className={theme.ForumPostHeader}>
<div className={theme.ForumPostHeaderMain}>
<ForumAuthorIdentity room={room} sender={post.sender} displayName={post.senderDisplayName} />
<ForumAuthorIdentity
room={room}
sender={post.sender}
displayName={post.senderDisplayName}
/>
<time className={theme.ForumPostTime} dateTime={new Date(post.timestamp).toISOString()}>
{formatForumTimeAgo(post.timestamp)}
</time>
@@ -318,7 +335,7 @@ function ForumThreadDetailBody({
resetEditor(editor);
resetEditorHistory(editor);
},
[editor]
[editor],
);
useEffect(() => {
@@ -382,7 +399,7 @@ function ForumThreadDetailBody({
setContentRevision((revision) => revision + 1);
void reloadThread();
},
{ threadRootId: rootEventId, wait: 150 }
{ threadRootId: rootEventId, wait: 150 },
);
const rootEvent = room.findEventById(rootEventId);
@@ -393,7 +410,7 @@ function ForumThreadDetailBody({
: false;
const { canSendReaction, reactionRelations, handleReactionToggle } = useForumMessageReactions(
room,
rootEvent
rootEvent,
);
const handleDeleteRoot = useCallback(() => {
@@ -447,7 +464,7 @@ function ForumThreadDetailBody({
if (!mobileOrTablet()) ReactEditor.focus(editor);
}, 0);
},
[editor, rootEventId, room, setReplyDraft, timelineSet]
[editor, rootEventId, room, setReplyDraft, timelineSet],
);
const rootBranchKey = forumBranchKey(rootEventId);
@@ -472,105 +489,113 @@ function ForumThreadDetailBody({
visibility="Hover"
>
<div className={theme.ForumTopicDetailBody}>
<header className={theme.ForumTopicDetailHead}>
<div className={theme.ForumTopicDetailHeadMain}>
<h1 className={theme.ForumDetailTitle}>{title}</h1>
<div className={theme.ForumTopicDetailAuthor}>
<ForumAuthorIdentity room={room} sender={post.sender} displayName={post.senderDisplayName} />
<span className={theme.ForumPostTime}>· {formatForumTimeAgo(post.timestamp)}</span>
</div>
</div>
</header>
<ForumMessageContextMenu
room={room}
mEvent={rootEvent}
imagePackRooms={imagePackRooms}
disabled={rootEditing}
canEdit={canEditRoot}
canDelete={canDeleteRoot}
onReply={() => handleReplyTo(post.eventId)}
onEdit={() => setEditEventId(rootEventId)}
onDeleted={handleDeleted}
className={forumMessageSurfaceClass(theme.ForumTopicDetailOp, post.eventId, replyTargetEventId)}
>
{rootEditing && rootEvent ? (
<MessageEditor
<header className={theme.ForumTopicDetailHead}>
<div className={theme.ForumTopicDetailHeadMain}>
<h1 className={theme.ForumDetailTitle}>{title}</h1>
<div className={theme.ForumTopicDetailAuthor}>
<ForumAuthorIdentity
room={room}
sender={post.sender}
displayName={post.senderDisplayName}
/>
<span className={theme.ForumPostTime}>· {formatForumTimeAgo(post.timestamp)}</span>
</div>
</div>
</header>
<ForumMessageContextMenu
room={room}
roomId={roomId}
mEvent={rootEvent}
imagePackRooms={imagePackRooms}
onCancel={handleEditRootClose}
/>
) : (
<>
<ForumEventContent
room={room}
eventId={post.eventId}
body={post.body}
bodyHtml={post.bodyHtml}
senderDisplayName={post.senderDisplayName}
/>
{reactionRelations && (
<Reactions
style={{ marginTop: config.space.S200 }}
room={room}
relations={reactionRelations}
mEventId={post.eventId}
canSendReaction={canSendReaction}
onReactionToggle={handleReactionToggle}
/>
disabled={rootEditing}
canEdit={canEditRoot}
canDelete={canDeleteRoot}
onReply={() => handleReplyTo(post.eventId)}
onEdit={() => setEditEventId(rootEventId)}
onDeleted={handleDeleted}
className={forumMessageSurfaceClass(
theme.ForumTopicDetailOp,
post.eventId,
replyTargetEventId,
)}
</>
)}
{!rootEditing && (
<div className={theme.ForumMessageOptionsBase}>
<ForumMessageActions
imagePackRooms={imagePackRooms}
eventId={post.eventId}
body={post.body}
canSendReaction={canSendReaction}
onReactionToggle={handleReactionToggle}
onReply={() => handleReplyTo(post.eventId)}
replyActive={replyTargetEventId === post.eventId}
onEdit={() => setEditEventId(rootEventId)}
canEdit={canEditRoot}
onDelete={handleDeleteRoot}
canDelete={canDeleteRoot}
/>
</div>
)}
</ForumMessageContextMenu>
{post.replies.length > 0 && (
<ForumThreadBranch
className={theme.ForumThread}
railClassName={theme.ForumThreadRailHitRoot}
collapsed={rootRepliesCollapsed}
hiddenCount={rootReplyCount}
onToggle={() => toggleBranch(rootBranchKey)}
>
{!rootRepliesCollapsed &&
post.replies.map((reply) => (
<ForumThreadMessage
key={reply.eventId}
post={reply}
>
{rootEditing && rootEvent ? (
<MessageEditor
room={room}
roomId={roomId}
threadRootId={rootEventId}
fileDropContainerRef={dropRef}
editEventId={editEventId}
onEditEventId={setEditEventId}
onComposerSent={() => {
void handleComposerSent();
}}
onDeleted={handleDeleted}
onReplyTo={handleReplyTo}
replyTargetEventId={replyTargetEventId}
collapsedBranches={collapsedBranches}
onToggleBranch={toggleBranch}
mEvent={rootEvent}
imagePackRooms={imagePackRooms}
onCancel={handleEditRootClose}
/>
))}
</ForumThreadBranch>
)}
) : (
<>
<ForumEventContent
room={room}
eventId={post.eventId}
body={post.body}
bodyHtml={post.bodyHtml}
senderDisplayName={post.senderDisplayName}
/>
{reactionRelations && (
<Reactions
style={{ marginTop: config.space.S200 }}
room={room}
relations={reactionRelations}
mEventId={post.eventId}
canSendReaction={canSendReaction}
onReactionToggle={handleReactionToggle}
/>
)}
</>
)}
{!rootEditing && (
<div className={theme.ForumMessageOptionsBase}>
<ForumMessageActions
imagePackRooms={imagePackRooms}
eventId={post.eventId}
body={post.body}
canSendReaction={canSendReaction}
onReactionToggle={handleReactionToggle}
onReply={() => handleReplyTo(post.eventId)}
replyActive={replyTargetEventId === post.eventId}
onEdit={() => setEditEventId(rootEventId)}
canEdit={canEditRoot}
onDelete={handleDeleteRoot}
canDelete={canDeleteRoot}
/>
</div>
)}
</ForumMessageContextMenu>
{post.replies.length > 0 && (
<ForumThreadBranch
className={theme.ForumThread}
railClassName={theme.ForumThreadRailHitRoot}
collapsed={rootRepliesCollapsed}
hiddenCount={rootReplyCount}
onToggle={() => toggleBranch(rootBranchKey)}
>
{!rootRepliesCollapsed &&
post.replies.map((reply) => (
<ForumThreadMessage
key={reply.eventId}
post={reply}
room={room}
roomId={roomId}
threadRootId={rootEventId}
fileDropContainerRef={dropRef}
editEventId={editEventId}
onEditEventId={setEditEventId}
onComposerSent={() => {
void handleComposerSent();
}}
onDeleted={handleDeleted}
onReplyTo={handleReplyTo}
replyTargetEventId={replyTargetEventId}
collapsedBranches={collapsedBranches}
onToggleBranch={toggleBranch}
/>
))}
</ForumThreadBranch>
)}
</div>
</Scroll>
<div className={theme.ForumThreadFooterComposer}>
@@ -1,4 +1,11 @@
import React, { KeyboardEventHandler, useCallback, useEffect, useMemo, useRef, useState } from 'react';
import React, {
KeyboardEventHandler,
useCallback,
useEffect,
useMemo,
useRef,
useState,
} from 'react';
import classNames from 'classnames';
import { IconButton } from 'folds';
import { Icon, Icons } from '../../components/icons';
@@ -28,7 +35,11 @@ type ForumTopicSearchInputProps = {
type SuggestionMode = 'qualifier' | 'author' | 'title';
export function ForumTopicSearchInput({ value, onChange, threads = [] }: ForumTopicSearchInputProps) {
export function ForumTopicSearchInput({
value,
onChange,
threads = [],
}: ForumTopicSearchInputProps) {
const inputRef = useRef<HTMLInputElement>(null);
const mirrorRef = useRef<HTMLSpanElement>(null);
const pillsRef = useRef<HTMLDivElement>(null);
@@ -48,15 +59,14 @@ export function ForumTopicSearchInput({ value, onChange, threads = [] }: ForumTo
: TOPIC_SEARCH_QUALIFIERS;
const authorMatches = useMemo(
() =>
valueContext?.key === 'from' ? matchAuthorHints(valueContext.partial, authorHints) : [],
[authorHints, valueContext]
() => (valueContext?.key === 'from' ? matchAuthorHints(valueContext.partial, authorHints) : []),
[authorHints, valueContext],
);
const titleMatches = useMemo(
() =>
valueContext?.key === 'intitle' ? matchTitleHints(valueContext.partial, titleHints) : [],
[titleHints, valueContext]
[titleHints, valueContext],
);
const suggestionMode: SuggestionMode | null = useMemo(() => {
@@ -144,7 +154,7 @@ export function ForumTopicSearchInput({ value, onChange, threads = [] }: ForumTo
positionFloatingPills();
});
},
[onChange, positionFloatingPills]
[onChange, positionFloatingPills],
);
const insertQualifier = useCallback(
@@ -155,7 +165,7 @@ export function ForumTopicSearchInput({ value, onChange, threads = [] }: ForumTo
const { value: nextValue, cursor } = insertTopicSearchQualifierAt(value, caretPos, qualifier);
applyInputUpdate(nextValue, cursor);
},
[applyInputUpdate, value]
[applyInputUpdate, value],
);
const insertValue = useCallback(
@@ -166,7 +176,7 @@ export function ForumTopicSearchInput({ value, onChange, threads = [] }: ForumTo
const { value: nextValue, cursor } = insertTopicSearchValueAt(value, caretPos, replacement);
applyInputUpdate(nextValue, cursor);
},
[applyInputUpdate, value]
[applyInputUpdate, value],
);
const selectAtIndex = useCallback(
@@ -192,7 +202,7 @@ export function ForumTopicSearchInput({ value, onChange, threads = [] }: ForumTo
}
}
},
[authorMatches, insertQualifier, insertValue, qualifierMatches, suggestionMode, titleMatches]
[authorMatches, insertQualifier, insertValue, qualifierMatches, suggestionMode, titleMatches],
);
const selectHighlighted = useCallback(() => {
@@ -204,7 +214,7 @@ export function ForumTopicSearchInput({ value, onChange, threads = [] }: ForumTo
if (!suggestionCount) return;
setHighlightIndex((idx) => (idx + delta + suggestionCount) % suggestionCount);
},
[suggestionCount]
[suggestionCount],
);
const handleKeyDown: KeyboardEventHandler<HTMLInputElement> = (event) => {
@@ -259,8 +269,7 @@ export function ForumTopicSearchInput({ value, onChange, threads = [] }: ForumTo
? `title:${valueContext?.partial ?? ''}`
: `qualifier:${qualifierPartial}`;
const nextIndex =
tabKey === tabPartial ? (highlightIndex + 1) % suggestionCount : 0;
const nextIndex = tabKey === tabPartial ? (highlightIndex + 1) % suggestionCount : 0;
setTabPartial(tabKey);
setHighlightIndex(nextIndex);
selectAtIndex(nextIndex);
+33 -32
View File
@@ -46,7 +46,7 @@ function isForumRootContent(content: Record<string, unknown>): boolean {
function syncForumRootContentAfterEdit(
merged: Record<string, unknown>,
baseContent: Record<string, unknown>
baseContent: Record<string, unknown>,
): Record<string, unknown> {
if (!isForumRootContent(baseContent)) return merged;
@@ -77,7 +77,7 @@ function syncForumRootContentAfterEdit(
function getLatestEditContent(
event: IRoomEvent,
timelineEvents: IRoomEvent[]
timelineEvents: IRoomEvent[],
): Record<string, unknown> {
const baseContent = event.content as Record<string, unknown>;
const targetId = event.event_id;
@@ -151,7 +151,7 @@ function sortRepliesRecursively(posts: ForumPost[]) {
function buildPosts(mx: MatrixClient, roomId: string, timelineEvents: IRoomEvent[]): ForumPost[] {
const redactedIds = new Set(
timelineEvents.filter((e) => e.unsigned?.redacted_because).map((e) => e.event_id)
timelineEvents.filter((e) => e.unsigned?.redacted_because).map((e) => e.event_id),
);
const normalized = timelineEvents
@@ -160,7 +160,7 @@ function buildPosts(mx: MatrixClient, roomId: string, timelineEvents: IRoomEvent
event.type === EventType.RoomMessage &&
event.event_id &&
event.content &&
!redactedIds.has(event.event_id)
!redactedIds.has(event.event_id),
)
.map((event) => {
const rawContent = event.content as Record<string, unknown>;
@@ -183,7 +183,7 @@ function buildPosts(mx: MatrixClient, roomId: string, timelineEvents: IRoomEvent
});
const room = mx.getRoom(roomId);
const displayName = room
? getMemberDisplayName(room, event.sender || '') ?? event.sender
? (getMemberDisplayName(room, event.sender || '') ?? event.sender)
: event.sender;
return {
@@ -223,7 +223,7 @@ function buildPosts(mx: MatrixClient, roomId: string, timelineEvents: IRoomEvent
const current = postsById.get(event.eventId);
if (!current) continue;
const relation = event.relation;
const { relation } = event;
let threadRootId: string | null = null;
let parentEventId: string | null = null;
@@ -271,7 +271,10 @@ function buildPosts(mx: MatrixClient, roomId: string, timelineEvents: IRoomEvent
return roots.sort((a, b) => b.timestamp - a.timestamp);
}
export async function listForumTopics(mx: MatrixClient, spaceRoomId: string): Promise<ForumTopic[]> {
export async function listForumTopics(
mx: MatrixClient,
spaceRoomId: string,
): Promise<ForumTopic[]> {
const rooms: IHierarchyRoom[] = [];
let nextBatch: string | undefined;
for (let page = 0; page < 5; page += 1) {
@@ -285,7 +288,8 @@ export async function listForumTopics(mx: MatrixClient, spaceRoomId: string): Pr
for (const room of rooms) {
if (!room?.room_id || !Array.isArray(room.children_state)) continue;
for (const childState of room.children_state) {
if (childState?.type !== 'm.space.child' || typeof childState.state_key !== 'string') continue;
if (childState?.type !== 'm.space.child' || typeof childState.state_key !== 'string')
continue;
parentByRoomId.set(childState.state_key, room.room_id);
}
}
@@ -339,7 +343,7 @@ export async function listForumTopics(mx: MatrixClient, spaceRoomId: string): Pr
export async function listTopicFeedPosts(
mx: MatrixClient,
roomId: string,
options: { from?: string; minRoots?: number } = {}
options: { from?: string; minRoots?: number } = {},
): Promise<{ posts: ForumPost[]; nextBatch: string | null }> {
const pageSize = 40;
const minRoots = options.minRoots ?? 8;
@@ -352,7 +356,7 @@ export async function listTopicFeedPosts(
roomId,
nextBatch ?? null,
pageSize,
Direction.Backward
Direction.Backward,
);
const chunk = [...(response.chunk || [])].reverse();
const pagePosts = buildPosts(mx, roomId, chunk);
@@ -437,7 +441,7 @@ function matrixEventToRoomEvent(mEvent: MatrixEvent): IRoomEvent {
export function collectLocalThreadEvents(
mx: MatrixClient,
roomId: string,
rootEventId: string
rootEventId: string,
): IRoomEvent[] {
const rootId = rootEventId.trim();
const room = mx.getRoom(roomId);
@@ -524,7 +528,7 @@ function collectLocalRootPosts(mx: MatrixClient, roomId: string): IRoomEvent[] {
export function loadPostThreadLocal(
mx: MatrixClient,
roomId: string,
rootEventId: string
rootEventId: string,
): ForumPost | null {
const rootId = rootEventId.trim();
const events = collectLocalThreadEvents(mx, roomId, rootId);
@@ -536,7 +540,7 @@ export function loadPostThreadLocal(
async function fetchRootEvent(
mx: MatrixClient,
roomId: string,
rootEventId: string
rootEventId: string,
): Promise<IRoomEvent | null> {
const rootId = rootEventId.trim();
if (!rootId) return null;
@@ -556,7 +560,7 @@ async function fetchRootEvent(
export async function loadPostThread(
mx: MatrixClient,
roomId: string,
rootEventId: string
rootEventId: string,
): Promise<ForumPost | null> {
const rootId = rootEventId.trim();
const localEvents = collectLocalThreadEvents(mx, roomId, rootId);
@@ -566,7 +570,7 @@ export async function loadPostThread(
const collectRelations = async (
relationType: RelationType | null,
eventType: EventType | null
eventType: EventType | null,
) => {
let from: string | undefined;
for (let page = 0; page < 20; page += 1) {
@@ -610,7 +614,7 @@ export async function loadPostThread(
export async function loadAggregatedTopicFeed(
mx: MatrixClient,
scopes: Array<{ roomId: string; sectionTitle?: string; topicName?: string }>
scopes: Array<{ roomId: string; sectionTitle?: string; topicName?: string }>,
): Promise<ForumPost[]> {
const allPosts: ForumPost[] = [];
for (const scope of scopes) {
@@ -639,7 +643,7 @@ export type ForumNewPostPayload = {
export async function sendForumPost(
mx: MatrixClient,
roomId: string,
post: ForumNewPostPayload
post: ForumNewPostPayload,
): Promise<string> {
const title = post.title.trim();
const plainText = post.plainText.trim();
@@ -674,7 +678,7 @@ export async function sendForumMediaRoot(
mx: MatrixClient,
roomId: string,
title: string,
content: IContent
content: IContent,
): Promise<string> {
const trimmedTitle = title.trim();
if (!trimmedTitle) {
@@ -697,7 +701,7 @@ export async function sendForumThreadAttachment(
roomId: string,
threadRootId: string,
content: IContent,
replyToEventId?: string
replyToEventId?: string,
): Promise<string> {
const rootId = threadRootId.trim();
const parentId = replyToEventId?.trim() || rootId;
@@ -728,7 +732,7 @@ export function sendForumReply(
roomId: string,
threadRootId: string,
replyToEventId: string,
message: string | ForumReplyPayload
message: string | ForumReplyPayload,
): Promise<string> {
const rootId = threadRootId.trim();
const parentId = replyToEventId.trim() || rootId;
@@ -741,8 +745,7 @@ export function sendForumReply(
throw new Error('Reply message is required.');
}
let formattedHtml =
typeof message === 'string' ? '' : String(message.formattedHtml || '').trim();
let formattedHtml = typeof message === 'string' ? '' : String(message.formattedHtml || '').trim();
formattedHtml = formattedHtml.replace(/(<br\s*\/?>\s*)+$/gi, '');
const content: Record<string, unknown> = {
@@ -769,13 +772,11 @@ export function createForumPostFromPayload(
roomId: string,
eventId: string,
payload: ForumNewPostPayload,
meta: { topicRoomId?: string; sectionTitle?: string; topicName?: string } = {}
meta: { topicRoomId?: string; sectionTitle?: string; topicName?: string } = {},
): ForumPost {
const userId = mx.getUserId() || 'unknown';
const room = mx.getRoom(roomId);
const displayName = room
? getMemberDisplayName(room, userId) ?? userId
: userId;
const displayName = room ? (getMemberDisplayName(room, userId) ?? userId) : userId;
const title = payload.title.trim();
const plainText = payload.plainText.trim();
let formattedHtml = payload.formattedHtml.trim().replace(/(<br\s*\/?>\s*)+$/gi, '');
@@ -792,7 +793,7 @@ export function createForumPostFromPayload(
format: 'org.matrix.custom.html',
formatted_body: `<h1>${escapeHtml(title)}</h1>${formattedHtml}`,
},
{ stripTitleHeading: true }
{ stripTitleHeading: true },
),
sender: userId,
senderDisplayName: displayName,
@@ -810,15 +811,15 @@ export function createForumReplyFromPayload(
roomId: string,
eventId: string,
replyToEventId: string,
payload: ForumReplyPayload
payload: ForumReplyPayload,
): ForumPost {
const userId = mx.getUserId() || 'unknown';
const room = mx.getRoom(roomId);
const displayName = room
? getMemberDisplayName(room, userId) ?? userId
: userId;
const displayName = room ? (getMemberDisplayName(room, userId) ?? userId) : userId;
const plainText = payload.plainText.trim();
let formattedHtml = String(payload.formattedHtml || '').trim().replace(/(<br\s*\/?>\s*)+$/gi, '');
const formattedHtml = String(payload.formattedHtml || '')
.trim()
.replace(/(<br\s*\/?>\s*)+$/gi, '');
const content: Record<string, unknown> = { body: plainText };
if (formattedHtml) {
+25 -18
View File
@@ -6,7 +6,12 @@ import type { IconSrc } from 'folds';
type SvgNode = [tag: string, attrs: Record<string, string>];
const FLAME: SvgNode[] = [
['path', { d: 'M12 3q1 4 4 6.5t3 5.5a1 1 0 0 1-14 0 5 5 0 0 1 1-3 1 1 0 0 0 5 0c0-2-1.5-3-1.5-5q0-2 2.5-4' }],
[
'path',
{
d: 'M12 3q1 4 4 6.5t3 5.5a1 1 0 0 1-14 0 5 5 0 0 1 1-3 1 1 0 0 0 5 0c0-2-1.5-3-1.5-5q0-2 2.5-4',
},
],
];
const SPARKLES: SvgNode[] = [
@@ -32,23 +37,25 @@ const CROWN: SvgNode[] = [
];
function lucideIcon(nodes: SvgNode): IconSrc {
return () => (
<svg
xmlns="http://www.w3.org/2000/svg"
viewBox="0 0 24 24"
fill="none"
stroke="currentColor"
strokeWidth={2}
strokeLinecap="round"
strokeLinejoin="round"
aria-hidden
focusable="false"
>
{nodes.map(([tag, attrs]) =>
React.createElement(tag, { key: `${tag}-${attrs.d ?? attrs.cx ?? ''}`, ...attrs })
)}
</svg>
);
return function () {
return (
<svg
xmlns="http://www.w3.org/2000/svg"
viewBox="0 0 24 24"
fill="none"
stroke="currentColor"
strokeWidth={2}
strokeLinecap="round"
strokeLinejoin="round"
aria-hidden
focusable="false"
>
{nodes.map(([tag, attrs]) =>
React.createElement(tag, { key: `${tag}-${attrs.d ?? attrs.cx ?? ''}`, ...attrs }),
)}
</svg>
);
};
}
/** hot → flame, new → sparkles, top → crown (matrixsso SORT_LUCIDE_ICONS) */
+1 -1
View File
@@ -21,7 +21,7 @@ export function stripLeadingTitleHeading(html: string): string {
export function bodyHtmlFromMessageContent(
content: Record<string, unknown>,
options: { stripTitleHeading?: boolean } = {}
options: { stripTitleHeading?: boolean } = {},
): string | undefined {
if (content.format !== 'org.matrix.custom.html') return undefined;
const raw = content.formatted_body;
+32 -23
View File
@@ -180,10 +180,7 @@ export const ForumTopicPostDetailInner = style({
});
/** @deprecated use ForumTopicPostDetailScroll + ForumTopicPostDetailInner */
export const ForumTopicPostDetail = style([
ForumTopicPostDetailScroll,
ForumTopicPostDetailInner,
]);
export const ForumTopicPostDetail = style([ForumTopicPostDetailScroll, ForumTopicPostDetailInner]);
export const ForumTopicPostDetailWithThread = style({});
@@ -1285,7 +1282,7 @@ globalStyle(
`${ForumThreadReplyInner}:hover ${ForumMessageOptionsBase}, ${ForumThreadReplyInner}:focus-within ${ForumMessageOptionsBase}`,
{
pointerEvents: 'auto',
}
},
);
globalStyle(
@@ -1293,12 +1290,15 @@ globalStyle(
{
opacity: 1,
pointerEvents: 'auto',
}
},
);
globalStyle(`${ForumThreadReplyInner}:has(${ForumMessageActionPanels}) ${ForumMessageOptionsBase}`, {
display: 'none',
});
globalStyle(
`${ForumThreadReplyInner}:has(${ForumMessageActionPanels}) ${ForumMessageOptionsBase}`,
{
display: 'none',
},
);
globalStyle(`${ForumTopicDetailOp}:has(${ForumMessageActionPanels}) ${ForumMessageOptionsBase}`, {
display: 'none',
@@ -1308,7 +1308,7 @@ globalStyle(
`${ForumTopicDetailOp}:hover ${ForumMessageOptionsBase}, ${ForumTopicDetailOp}:focus-within ${ForumMessageOptionsBase}`,
{
pointerEvents: 'auto',
}
},
);
globalStyle(
@@ -1316,21 +1316,21 @@ globalStyle(
{
opacity: 1,
pointerEvents: 'auto',
}
},
);
globalStyle(
`${ForumThread}:has(> ${ForumThreadReply} > ${ForumThreadReplyInner}:hover)::before, ${ForumThread}:has(> ${ForumThreadReply} > ${ForumThreadReplyInner}:focus-within)::before`,
{
background: threadLineActive,
}
},
);
globalStyle(
`${ForumThreadChildren}:has(> ${ForumThreadReply} > ${ForumThreadReplyInner}:hover)::before, ${ForumThreadChildren}:has(> ${ForumThreadReply} > ${ForumThreadReplyInner}:focus-within)::before`,
{
background: threadLineActive,
}
},
);
globalStyle(`${ForumThreadChildren} ${ForumThreadChildren}::before`, {
@@ -1342,18 +1342,27 @@ globalStyle(`${ForumAuthorAvatar} > *`, {
width: '100%',
});
globalStyle(`${ForumThreadReplyInner} ${ForumMessageBody}, ${ForumThreadReplyInner} ${ForumMessageBodyRich}`, {
marginLeft: 0,
marginRight: 0,
});
globalStyle(
`${ForumThreadReplyInner} ${ForumMessageBody}, ${ForumThreadReplyInner} ${ForumMessageBodyRich}`,
{
marginLeft: 0,
marginRight: 0,
},
);
globalStyle(`${ForumTopicDetailRoot} ${ForumMessageBody}, ${ForumTopicDetailRoot} ${ForumMessageBodyRich}`, {
marginTop: toRem(5.6),
});
globalStyle(
`${ForumTopicDetailRoot} ${ForumMessageBody}, ${ForumTopicDetailRoot} ${ForumMessageBodyRich}`,
{
marginTop: toRem(5.6),
},
);
globalStyle(`${ForumTopicDetailOp} ${ForumMessageBody}, ${ForumTopicDetailOp} ${ForumMessageBodyRich}`, {
marginTop: toRem(5.6),
});
globalStyle(
`${ForumTopicDetailOp} ${ForumMessageBody}, ${ForumTopicDetailOp} ${ForumMessageBodyRich}`,
{
marginTop: toRem(5.6),
},
);
// Legacy aliases
export const ForumApp = ForumTopicLiveApp;
+5 -9
View File
@@ -1,9 +1,5 @@
import type { ForumPost, ForumSection, ForumThreadSummary, ForumTopic } from './types';
import {
applyTopicStatusSort,
filterPostsBySearch,
parseTopicSearchQuery,
} from './topicSearch';
import { applyTopicStatusSort, filterPostsBySearch, parseTopicSearchQuery } from './topicSearch';
export function countAllReplies(replies: ForumPost[] | undefined): number {
let total = 0;
@@ -45,7 +41,7 @@ export function buildThreadSummaries(posts: ForumPost[]): ForumThreadSummary[] {
export function buildTopicThreads(
posts: ForumPost[],
query: { q?: string; status?: string; sort?: string } = {}
query: { q?: string; status?: string; sort?: string } = {},
): ForumThreadSummary[] {
const parsed = parseTopicSearchQuery(query.q || '');
const filtered = filterPostsBySearch(posts, parsed);
@@ -70,7 +66,7 @@ export function buildForumSections(topics: ForumTopic[]): ForumSection[] {
}
const coveredTopicIds = new Set(
sections.flatMap((section) => section.topics.map((topic) => topic.roomId))
sections.flatMap((section) => section.topics.map((topic) => topic.roomId)),
);
const uncategorizedTopics = postableTopics.filter((topic) => !coveredTopicIds.has(topic.roomId));
if (uncategorizedTopics.length > 0) {
@@ -88,7 +84,7 @@ export function buildForumSections(topics: ForumTopic[]): ForumSection[] {
export function appendReplyToThread(
root: ForumPost,
parentEventId: string,
reply: ForumPost
reply: ForumPost,
): ForumPost {
const walk = (node: ForumPost): ForumPost => {
if (node.eventId === parentEventId) {
@@ -112,7 +108,7 @@ export function appendReplyToThread(
export function annotatePostsWithRoomScope(
posts: ForumPost[],
roomId: string,
scope: { sectionTitle?: string; topicName?: string } | null = null
scope: { sectionTitle?: string; topicName?: string } | null = null,
): void {
const sectionTitle = scope?.sectionTitle ? String(scope.sectionTitle) : '';
const topicName = scope?.topicName ? String(scope.topicName) : '';
+29 -24
View File
@@ -87,10 +87,13 @@ export function formatSearchValue(value: string): string {
}
/** Partial value typed after a qualifier token (e.g. `from:ali` or `intitle:"rel`). */
export function readActiveQualifierValueAt(value: string, cursor: number): QualifierValueContext | null {
export function readActiveQualifierValueAt(
value: string,
cursor: number,
): QualifierValueContext | null {
const before = String(value || '').slice(0, Math.max(0, cursor));
const match = before.match(
/(?:^|\s)(intitle|inpost|inbody|inthread|inreply|from):\s*(?:"([^"]*)"?|(\S*))$/i
/(?:^|\s)(intitle|inpost|inbody|inthread|inreply|from):\s*(?:"([^"]*)"?|(\S*))$/i,
);
if (!match) {
return null;
@@ -117,7 +120,7 @@ export function readActiveQualifierValueAt(value: string, cursor: number): Quali
export function insertTopicSearchValueAt(
value: string,
cursor: number,
replacement: string
replacement: string,
): { value: string; cursor: number } {
const ctx = readActiveQualifierValueAt(value, cursor);
if (!ctx) {
@@ -135,7 +138,7 @@ export function insertTopicSearchValueAt(
}
export function collectAuthorHintsFromThreads(
threads: Array<{ sender: string; senderDisplayName?: string }>
threads: Array<{ sender: string; senderDisplayName?: string }>,
): TopicSearchAuthorHint[] {
const map = new Map<string, TopicSearchAuthorHint>();
@@ -150,7 +153,7 @@ export function collectAuthorHintsFromThreads(
}
return [...map.values()].sort(
(a, b) => a.displayName.localeCompare(b.displayName) || a.localpart.localeCompare(b.localpart)
(a, b) => a.displayName.localeCompare(b.displayName) || a.localpart.localeCompare(b.localpart),
);
}
@@ -167,9 +170,11 @@ export function collectTitleHintsFromThreads(threads: Array<{ title: string }>):
export function matchAuthorHints(
partial: string,
hints: TopicSearchAuthorHint[]
hints: TopicSearchAuthorHint[],
): TopicSearchAuthorHint[] {
const prefix = String(partial || '').trim().toLowerCase();
const prefix = String(partial || '')
.trim()
.toLowerCase();
return hints
.filter((hint) => {
if (!prefix) {
@@ -185,16 +190,16 @@ export function matchAuthorHints(
}
export function matchTitleHints(partial: string, titles: string[]): string[] {
const prefix = String(partial || '').trim().toLowerCase();
return titles
.filter((title) => !prefix || title.toLowerCase().includes(prefix))
.slice(0, 12);
const prefix = String(partial || '')
.trim()
.toLowerCase();
return titles.filter((title) => !prefix || title.toLowerCase().includes(prefix)).slice(0, 12);
}
export function insertTopicSearchQualifierAt(
value: string,
cursor: number,
qualifier: TopicSearchQualifier
qualifier: TopicSearchQualifier,
): { value: string; cursor: number } {
const input = String(value || '');
const caret = Math.max(0, Math.min(cursor, input.length));
@@ -285,10 +290,10 @@ export function parseTopicSearchQuery(raw: string): ParsedTopicSearch {
const terms = collectTerms(qualifiers, freeText);
const isActive = Boolean(
freeText ||
qualifiers.intitle.length ||
qualifiers.inpost.length ||
qualifiers.inthread.length ||
qualifiers.from.length
qualifiers.intitle.length ||
qualifiers.inpost.length ||
qualifiers.inthread.length ||
qualifiers.from.length,
);
return { isActive, qualifiers, freeText, terms };
@@ -377,11 +382,9 @@ export function filterPostsBySearch(posts: ForumPost[], parsed: ParsedTopicSearc
return (posts || []).filter((post) => threadMatchesSearch(post, parsed));
}
export function applyTopicStatusSort<T extends { lastActivityTs: number; timestamp: number; totalReplies: number; eventId: string }>(
threads: T[],
statusFilter: string,
sortBy: string
): T[] {
export function applyTopicStatusSort<
T extends { lastActivityTs: number; timestamp: number; totalReplies: number; eventId: string },
>(threads: T[], statusFilter: string, sortBy: string): T[] {
let filtered = threads || [];
if (statusFilter === 'open') {
@@ -396,7 +399,7 @@ export function applyTopicStatusSort<T extends { lastActivityTs: number; timesta
(a, b) =>
b.totalReplies - a.totalReplies ||
b.lastActivityTs - a.lastActivityTs ||
b.eventId.localeCompare(a.eventId)
b.eventId.localeCompare(a.eventId),
);
} else if (sortBy === 'new') {
sorted.sort((a, b) => b.timestamp - a.timestamp || b.eventId.localeCompare(a.eventId));
@@ -404,7 +407,9 @@ export function applyTopicStatusSort<T extends { lastActivityTs: number; timesta
sorted.sort((a, b) => {
const hotA = a.totalReplies * 4 + Math.floor((a.lastActivityTs - a.timestamp) / 3600000);
const hotB = b.totalReplies * 4 + Math.floor((b.lastActivityTs - b.timestamp) / 3600000);
return hotB - hotA || b.lastActivityTs - a.lastActivityTs || b.eventId.localeCompare(a.eventId);
return (
hotB - hotA || b.lastActivityTs - a.lastActivityTs || b.eventId.localeCompare(a.eventId)
);
});
}
@@ -417,7 +422,7 @@ export function highlightSearchTerms(text: string, terms: string[]): string {
}
const usable = [...new Set(terms.map((term) => String(term || '').trim()).filter(Boolean))].sort(
(a, b) => b.length - a.length
(a, b) => b.length - a.length,
);
let result = text;
+57 -61
View File
@@ -9,11 +9,7 @@ import { getSpaceLobbyPath } from '../../pages/pathUtils';
import { createRoomModalAtom } from '../../state/createRoomModal';
import { createSpaceModalAtom } from '../../state/createSpaceModal';
import { StateEvent } from '../../../types/matrix/room';
import {
buildForumSections,
buildTopicThreads,
buildThreadSummaries,
} from './forumTopicHelpers';
import { buildForumSections, buildTopicThreads, buildThreadSummaries } from './forumTopicHelpers';
import { applyTopicStatusSort } from './topicSearch';
import {
createForumPostFromPayload,
@@ -39,7 +35,7 @@ export type ForumBoardScope = {
function scopesFromSelection(
sections: ForumSection[],
category?: string,
topic?: string
topic?: string,
): Array<{ roomId: string; sectionTitle?: string; topicName?: string }> {
if (topic) {
for (const section of sections) {
@@ -66,7 +62,7 @@ function scopesFromSelection(
roomId: t.roomId,
sectionTitle: section.title,
topicName: t.name,
}))
})),
);
}
@@ -76,10 +72,7 @@ export function useForumBoard(scope: ForumBoardScope, forumSpace: Room) {
const navigate = useNavigate();
const selectedRoomId = useSelectedRoom();
const searchParams = useMemo(
() => new URLSearchParams(location.search),
[location.search]
);
const searchParams = useMemo(() => new URLSearchParams(location.search), [location.search]);
const filterQuery: ForumBoardQuery = useMemo(
() => ({
@@ -89,7 +82,7 @@ export function useForumBoard(scope: ForumBoardScope, forumSpace: Room) {
status: (searchParams.get('status') as ForumBoardQuery['status']) || 'all',
sort: (searchParams.get('sort') as ForumBoardQuery['sort']) || 'hot',
}),
[searchParams]
[searchParams],
);
const query: ForumBoardQuery = useMemo(
@@ -98,7 +91,7 @@ export function useForumBoard(scope: ForumBoardScope, forumSpace: Room) {
post: searchParams.get('post') || undefined,
postRoom: searchParams.get('postRoom') || undefined,
}),
[filterQuery, searchParams]
[filterQuery, searchParams],
);
const [sections, setSections] = useState<ForumSection[]>([]);
@@ -115,8 +108,7 @@ export function useForumBoard(scope: ForumBoardScope, forumSpace: Room) {
mutate(next);
const search = next.toString();
const onTopicRoomRoute =
Boolean(selectedRoomId) && selectedRoomId !== forumSpace.roomId;
const onTopicRoomRoute = Boolean(selectedRoomId) && selectedRoomId !== forumSpace.roomId;
navigate(
{
@@ -125,10 +117,10 @@ export function useForumBoard(scope: ForumBoardScope, forumSpace: Room) {
: location.pathname,
search: search ? `?${search}` : '',
},
{ replace: true }
{ replace: true },
);
},
[location.pathname, location.search, navigate, mx, forumSpace.roomId, selectedRoomId]
[location.pathname, location.search, navigate, mx, forumSpace.roomId, selectedRoomId],
);
const setQueryParam = useCallback(
@@ -142,7 +134,7 @@ export function useForumBoard(scope: ForumBoardScope, forumSpace: Room) {
}
});
},
[applyForumSearchParams]
[applyForumSearchParams],
);
const setCategory = useCallback(
@@ -155,7 +147,7 @@ export function useForumBoard(scope: ForumBoardScope, forumSpace: Room) {
next.delete('postRoom');
});
},
[applyForumSearchParams]
[applyForumSearchParams],
);
const loadSections = useCallback(async () => {
@@ -171,39 +163,42 @@ export function useForumBoard(scope: ForumBoardScope, forumSpace: Room) {
}
}, [mx, scope.forumSpaceId]);
const refreshThreads = useCallback(async (options?: { silent?: boolean }) => {
if (!options?.silent) setLoadingThreads(true);
setError(null);
try {
const roomScopes = scopesFromSelection(sections, filterQuery.category, filterQuery.topic);
if (roomScopes.length === 0) {
setThreads([]);
return;
}
const refreshThreads = useCallback(
async (options?: { silent?: boolean }) => {
if (!options?.silent) setLoadingThreads(true);
setError(null);
try {
const roomScopes = scopesFromSelection(sections, filterQuery.category, filterQuery.topic);
if (roomScopes.length === 0) {
setThreads([]);
return;
}
let posts;
if (roomScopes.length === 1) {
const result = await listTopicFeedPosts(mx, roomScopes[0].roomId);
posts = result.posts;
setPostsNextBatch(result.nextBatch);
const scopeMeta = roomScopes[0];
posts.forEach((post) => {
post.topicRoomId = scopeMeta.roomId;
if (scopeMeta.sectionTitle) post.sectionTitle = scopeMeta.sectionTitle;
if (scopeMeta.topicName) post.topicName = scopeMeta.topicName;
});
} else {
posts = await loadAggregatedTopicFeed(mx, roomScopes);
setPostsNextBatch(null);
}
let posts;
if (roomScopes.length === 1) {
const result = await listTopicFeedPosts(mx, roomScopes[0].roomId);
posts = result.posts;
setPostsNextBatch(result.nextBatch);
const scopeMeta = roomScopes[0];
posts.forEach((post) => {
post.topicRoomId = scopeMeta.roomId;
if (scopeMeta.sectionTitle) post.sectionTitle = scopeMeta.sectionTitle;
if (scopeMeta.topicName) post.topicName = scopeMeta.topicName;
});
} else {
posts = await loadAggregatedTopicFeed(mx, roomScopes);
setPostsNextBatch(null);
}
setThreads(buildTopicThreads(posts, filterQuery));
} catch (err) {
setError(err instanceof Error ? err.message : 'Failed to load forum posts');
} finally {
if (!options?.silent) setLoadingThreads(false);
}
}, [mx, sections, filterQuery]);
setThreads(buildTopicThreads(posts, filterQuery));
} catch (err) {
setError(err instanceof Error ? err.message : 'Failed to load forum posts');
} finally {
if (!options?.silent) setLoadingThreads(false);
}
},
[mx, sections, filterQuery],
);
useEffect(() => {
loadSections();
@@ -214,10 +209,7 @@ export function useForumBoard(scope: ForumBoardScope, forumSpace: Room) {
if (event.getType() !== StateEvent.SpaceChild) return;
const roomId = event.getRoomId();
if (!roomId) return;
if (
roomId === forumSpace.roomId ||
sections.some((section) => section.spaceId === roomId)
) {
if (roomId === forumSpace.roomId || sections.some((section) => section.spaceId === roomId)) {
loadSections();
}
};
@@ -285,7 +277,7 @@ export function useForumBoard(scope: ForumBoardScope, forumSpace: Room) {
}
});
},
[applyForumSearchParams]
[applyForumSearchParams],
);
const insertThreadFromNewPost = useCallback(
@@ -312,7 +304,7 @@ export function useForumBoard(scope: ForumBoardScope, forumSpace: Room) {
topicRoomId: published.topicRoomId,
sectionTitle: scopeMeta?.sectionTitle,
topicName: scopeMeta?.topicName,
}
},
);
if (inScope) {
@@ -321,14 +313,18 @@ export function useForumBoard(scope: ForumBoardScope, forumSpace: Room) {
setThreads((prev) => {
const without = prev.filter((t) => t.eventId !== summary.eventId);
const merged = [summary, ...without];
return applyTopicStatusSort(merged, filterQuery.status || 'all', filterQuery.sort || 'hot');
return applyTopicStatusSort(
merged,
filterQuery.status || 'all',
filterQuery.sort || 'hot',
);
});
}
}
return post;
},
[mx, sections, filterQuery]
[mx, sections, filterQuery],
);
const recordThreadReply = useCallback((rootEventId: string) => {
@@ -340,8 +336,8 @@ export function useForumBoard(scope: ForumBoardScope, forumSpace: Room) {
totalReplies: t.totalReplies + 1,
lastActivityTs: Date.now(),
}
: t
)
: t,
),
);
}, []);
@@ -367,7 +363,7 @@ export function useForumBoard(scope: ForumBoardScope, forumSpace: Room) {
setThreads((prev) => {
const existingIds = new Set(prev.map((t) => t.eventId));
const added = buildTopicThreads(result.posts, filterQuery).filter(
(t) => !existingIds.has(t.eventId)
(t) => !existingIds.has(t.eventId),
);
const merged = [...prev, ...added];
const sort = filterQuery.sort || 'hot';
@@ -1,11 +1,5 @@
import { useCallback, useEffect, useMemo, useState } from 'react';
import {
EventType,
MatrixEvent,
RelationType,
Room,
RoomEvent,
} from 'matrix-js-sdk';
import { EventType, MatrixEvent, RelationType, Room, RoomEvent } from 'matrix-js-sdk';
import { RelationsEvent } from 'matrix-js-sdk/lib/models/relations';
import { MessageEvent } from '../../../types/matrix/room';
import { useMatrixClient } from '../../hooks/useMatrixClient';
@@ -115,13 +109,13 @@ export function useForumMessageReactions(room: Room, mEvent: MatrixEvent | undef
mx.sendEvent(
room.roomId,
MessageEvent.Reaction as never,
getReactionContent(targetEventId, key, rShortcode)
getReactionContent(targetEventId, key, rShortcode),
).finally(() => {
bumpRelations();
window.setTimeout(bumpRelations, 250);
});
},
[bumpRelations, mx, room.roomId, roomTimelineSet]
[bumpRelations, mx, room.roomId, roomTimelineSet],
);
return {
@@ -32,7 +32,7 @@ export function useForumMessageRenderOptions(room: Room | null | undefined) {
const roomWideEmbedFilters = useRoomWideEmbedFilters(room ?? undefined);
const combinedEmbedFilters = useMemo(
() => combineEmbedFilters(personalEmbedFilters, roomWideEmbedFilters),
[personalEmbedFilters, roomWideEmbedFilters]
[personalEmbedFilters, roomWideEmbedFilters],
);
const mentionClickHandler = useMentionClickHandler(room?.roomId ?? '');
@@ -42,10 +42,15 @@ export function useForumMessageRenderOptions(room: Room | null | undefined) {
() => ({
...LINKIFY_OPTS,
render: factoryRenderLinkifyWithMention((href) =>
renderMatrixMention(mx, room?.roomId ?? '', href, makeMentionCustomProps(mentionClickHandler))
renderMatrixMention(
mx,
room?.roomId ?? '',
href,
makeMentionCustomProps(mentionClickHandler),
),
),
}),
[mx, room?.roomId, mentionClickHandler]
[mx, room?.roomId, mentionClickHandler],
);
const htmlReactParserOptions = useMemo<HTMLReactParserOptions>(
@@ -56,7 +61,7 @@ export function useForumMessageRenderOptions(room: Room | null | undefined) {
handleSpoilerClick: spoilerClickHandler,
handleMentionClick: mentionClickHandler,
}),
[mx, room?.roomId, linkifyOpts, spoilerClickHandler, mentionClickHandler, useAuthentication]
[mx, room?.roomId, linkifyOpts, spoilerClickHandler, mentionClickHandler, useAuthentication],
);
return {
@@ -1,11 +1,5 @@
import { useEffect, useMemo, useRef } from 'react';
import {
EventType,
MatrixEvent,
RelationType,
Room,
RoomEvent,
} from 'matrix-js-sdk';
import { EventType, MatrixEvent, RelationType, Room, RoomEvent } from 'matrix-js-sdk';
import { useMatrixClient } from '../../hooks/useMatrixClient';
type ForumRoomLiveOptions = {
@@ -42,8 +36,7 @@ function isForumThreadEvent(mEvent: MatrixEvent, threadRootId: string): boolean
function isSecondaryMatrixEvent(mEvent: MatrixEvent): boolean {
const relation = mEvent.getRelation();
return (
relation?.rel_type === RelationType.Replace ||
relation?.rel_type === RelationType.Annotation
relation?.rel_type === RelationType.Replace || relation?.rel_type === RelationType.Annotation
);
}
@@ -69,7 +62,7 @@ function isRelevantEvent(mEvent: MatrixEvent, threadRootId?: string): boolean {
export function useForumRoomLiveUpdates(
rooms: Room[],
onUpdate: () => void,
options: ForumRoomLiveOptions = {}
options: ForumRoomLiveOptions = {},
) {
const mx = useMatrixClient();
const { threadRootId, wait = 200 } = options;
@@ -1,7 +1,7 @@
import React from 'react';
import { Box, IconButton, Scroll, Text, toRem } from 'folds';
import { Icon, Icons } from '../../components/icons';
import { useAtomValue } from 'jotai';
import { Icon, Icons } from '../../components/icons';
import { RoomCard } from '../../components/room-card';
import { RoomTopicViewer } from '../../components/room-topic-viewer';
import { Page, PageHeader } from '../../components/page';
+3 -3
View File
@@ -22,7 +22,7 @@ export const useDraggableItem = (
item: HierarchyItem,
targetRef: RefObject<HTMLElement>,
onDragging: (item?: HierarchyItem) => void,
dragHandleRef?: RefObject<HTMLElement>
dragHandleRef?: RefObject<HTMLElement>,
): boolean => {
const [dragging, setDragging] = useState(false);
@@ -122,7 +122,7 @@ export function AfterItemDropTarget({
export const useDnDMonitor = (
scrollRef: RefObject<HTMLElement>,
onDragging: (item?: HierarchyItem) => void,
onReorder: (item: HierarchyItem, container: DropContainerData) => void
onReorder: (item: HierarchyItem, container: DropContainerData) => void,
) => {
useEffect(() => {
const scrollElement = scrollRef.current;
@@ -141,7 +141,7 @@ export const useDnDMonitor = (
}),
autoScrollForElements({
element: scrollElement,
})
}),
);
}, [scrollRef, onDragging, onReorder]);
};
+16 -4
View File
@@ -1,6 +1,18 @@
import React, { MouseEventHandler, useCallback, useEffect, useState } from 'react';
import FocusTrap from 'focus-trap-react';
import { Box, IconButton, PopOut, Menu, MenuItem, Text, RectCords, config, Line, Spinner, toRem } from 'folds';
import {
Box,
IconButton,
PopOut,
Menu,
MenuItem,
Text,
RectCords,
config,
Line,
Spinner,
toRem,
} from 'folds';
import { Icon, Icons } from '../../components/icons';
import { HierarchyItem } from '../../hooks/useSpaceHierarchy';
import { useMatrixClient } from '../../hooks/useMatrixClient';
@@ -36,7 +48,7 @@ function SuggestMenuItem({
useCallback(() => {
const newContent: MSpaceChildContent = { ...content, suggested: !content.suggested };
return mx.sendStateEvent(parentId, StateEvent.SpaceChild as any, newContent, roomId);
}, [mx, parentId, roomId, content])
}, [mx, parentId, roomId, content]),
);
useEffect(() => {
@@ -73,8 +85,8 @@ function RemoveMenuItem({
const [removeState, handleRemove] = useAsyncCallback(
useCallback(
() => mx.sendStateEvent(parentId, StateEvent.SpaceChild as any, {}, roomId),
[mx, parentId, roomId]
)
[mx, parentId, roomId],
),
);
useEffect(() => {
+27 -27
View File
@@ -1,6 +1,5 @@
import React, { MouseEventHandler, useCallback, useEffect, useMemo, useRef, useState } from 'react';
import { Box, Chip, IconButton, Line, Scroll, Spinner, Text, config } from 'folds';
import { Icon, Icons } from '../../components/icons';
import { useVirtualizer } from '@tanstack/react-virtual';
import { useAtom, useAtomValue } from 'jotai';
import { useNavigate } from 'react-router-dom';
@@ -8,6 +7,7 @@ import { JoinRule, RestrictedAllowType, Room } from 'matrix-js-sdk';
import { RoomJoinRulesEventContent } from 'matrix-js-sdk/lib/types';
import { IHierarchyRoom } from 'matrix-js-sdk/lib/@types/spaces';
import { produce } from 'immer';
import { Icon, Icons } from '../../components/icons';
import { useSpace } from '../../hooks/useSpace';
import { Page, PageContent, PageContentCenter, PageHeroSection } from '../../components/page';
import {
@@ -64,7 +64,7 @@ import { joiningProgressAtom } from '../../state/joiningProgress';
const useCanDropLobbyItem = (
space: Room,
roomsPowerLevels: Map<string, IPowerLevels>,
getRoom: (roomId: string) => Room | undefined
getRoom: (roomId: string) => Room | undefined,
): CanDropCallback => {
const mx = useMatrixClient();
@@ -91,7 +91,7 @@ const useCanDropLobbyItem = (
return true;
},
[space, roomsPowerLevels, getRoom, mx]
[space, roomsPowerLevels, getRoom, mx],
);
const canDropRoom: CanDropCallback = useCallback(
@@ -111,7 +111,7 @@ const useCanDropLobbyItem = (
const canChangeJoinRuleAllow = itemPermissions.stateEvent(
StateEvent.RoomJoinRules,
mx.getSafeUserId()
mx.getSafeUserId(),
);
if (!canChangeJoinRuleAllow) {
return false;
@@ -129,7 +129,7 @@ const useCanDropLobbyItem = (
}
return true;
},
[mx, getRoom, roomsPowerLevels]
[mx, getRoom, roomsPowerLevels],
);
const canDrop: CanDropCallback = useCallback(
@@ -146,7 +146,7 @@ const useCanDropLobbyItem = (
return canDropRoom(item, container);
},
[canDropSpace, canDropRoom]
[canDropSpace, canDropRoom],
);
return canDrop;
@@ -179,7 +179,7 @@ function SpaceCardLobby() {
const [onTop, setOnTop] = useState(true);
const [closedCategories, setClosedCategories] = useAtom(useClosedLobbyCategoriesAtom());
const [sidebarItems] = useSidebarItems(
useOrphanSpaces(mx, allRoomsAtom, useAtomValue(roomToParentsAtom))
useOrphanSpaces(mx, allRoomsAtom, useAtomValue(roomToParentsAtom)),
);
const sidebarSpaces = useMemo(() => {
const sideSpaces = sidebarItems.flatMap((item) => {
@@ -205,7 +205,7 @@ function SpaceCardLobby() {
setSpacesItem((current) =>
produce(current, (draft) => {
all.forEach((r) => draft.set(r.room_id, r));
})
}),
);
} catch {
// hierarchy may be unavailable for some memberships
@@ -218,7 +218,7 @@ function SpaceCardLobby() {
useElementSizeObserver(
useCallback(() => heroSectionRef.current, []),
useCallback((w, height) => setHeroSectionHeight(height), [])
useCallback((w, height) => setHeroSectionHeight(height), []),
);
const getRoom = useGetRoom(allJoinedRooms);
@@ -232,9 +232,9 @@ function SpaceCardLobby() {
(childId) =>
closedCategories.has(makeLobbyCategoryId(space.roomId, childId)) ||
(draggingItem ? 'space' in draggingItem : false),
[closedCategories, space.roomId, draggingItem]
[closedCategories, space.roomId, draggingItem],
),
spacesItems
spacesItems,
);
const virtualizer = useVirtualizer({
@@ -256,8 +256,8 @@ function SpaceCardLobby() {
return [getRoom(i.space.roomId), ...childRooms];
})
.filter((r) => !!r) as Room[],
[hierarchy, getRoom]
)
[hierarchy, getRoom],
),
);
const canDrop: CanDropCallback = useCanDropLobbyItem(space, roomsPowerLevels, getRoom);
@@ -311,13 +311,13 @@ function SpaceCardLobby() {
reorder.item.parentId,
StateEvent.SpaceChild as any,
{ ...reorder.item.content, order: reorder.orderKey },
reorder.item.roomId
reorder.item.roomId,
);
});
}
},
[mx, hierarchy, lex, roomsPowerLevels]
)
[mx, hierarchy, lex, roomsPowerLevels],
),
);
const reorderingSpace = reorderSpaceState.status === AsyncStatus.Loading;
@@ -346,7 +346,7 @@ function SpaceCardLobby() {
// restricted room from one space to another
const joinRuleContent = getStateEvent(
itemRoom,
StateEvent.RoomJoinRules
StateEvent.RoomJoinRules,
)?.getContent<RoomJoinRulesEventContent>();
if (joinRuleContent) {
@@ -362,7 +362,7 @@ function SpaceCardLobby() {
}
const itemSpaces = Array.from(
hierarchy?.find((i) => i.space.roomId === containerParentId)?.rooms ?? []
hierarchy?.find((i) => i.space.roomId === containerParentId)?.rooms ?? [],
);
const beforeItem: HierarchyItem | undefined =
@@ -398,13 +398,13 @@ function SpaceCardLobby() {
containerParentId,
StateEvent.SpaceChild as any,
{ ...reorder.item.content, order: reorder.orderKey },
reorder.item.roomId
reorder.item.roomId,
);
});
}
},
[mx, hierarchy, lex]
)
[mx, hierarchy, lex],
),
);
const reorderingRoom = reorderRoomState.status === AsyncStatus.Loading;
const reordering = reorderingRoom || reorderingSpace;
@@ -423,8 +423,8 @@ function SpaceCardLobby() {
reorderRoom(item, container.item);
}
},
[reorderRoom, reorderSpace, canDrop]
)
[reorderRoom, reorderSpace, canDrop],
),
);
const handleSpacesFound = useCallback(
@@ -436,14 +436,14 @@ function SpaceCardLobby() {
setSpacesItem((current) =>
produce(current, (draft) => {
items.forEach((item) => draft.set(item.room_id, item));
})
}),
);
},
[setSpaceRooms]
[setSpaceRooms],
);
const handleCategoryClick = useCategoryHandler(setClosedCategories, (categoryId) =>
closedCategories.has(categoryId)
closedCategories.has(categoryId),
);
const handleOpenRoom: MouseEventHandler<HTMLButtonElement> = (evt) => {
@@ -462,7 +462,7 @@ function SpaceCardLobby() {
const newSpacesContent = makeCinnySpacesContent(mx, newItems);
mx.setAccountData(AccountDataEvent.CinnySpaces as any, newSpacesContent as any);
},
[mx, sidebarItems, sidebarSpaces]
[mx, sidebarItems, sidebarSpaces],
);
return (
+114 -101
View File
@@ -1,7 +1,22 @@
import React, { MouseEventHandler, forwardRef, useEffect, useMemo, useRef, useState } from 'react';
import { Avatar, Box, IconButton, Line, Menu, MenuItem, PopOut, RectCords, Text, Tooltip, TooltipProvider, config, toRem } from 'folds';
import { Icon, Icons } from '../../components/icons';
import {
Avatar,
Box,
IconButton,
Line,
Menu,
MenuItem,
PopOut,
RectCords,
Text,
Tooltip,
TooltipProvider,
config,
toRem,
} from 'folds';
import FocusTrap from 'focus-trap-react';
import { useNavigate } from 'react-router-dom';
import { Icon, Icons } from '../../components/icons';
import { PageHeader } from '../../components/page';
import { useSetSetting } from '../../state/hooks/settings';
import { settingsAtom } from '../../state/settings';
@@ -18,7 +33,7 @@ import { RemoveInaccessiblePrompt } from '../../components/remove-inaccessible-p
import { stopPropagation } from '../../utils/keyboard';
import { ScreenSize, useScreenSizeContext } from '../../hooks/useScreenSize';
import { useBackRoute } from '../../hooks/useBackRoute';
import { mxcUrlToHttp } from '../../utils/matrix';
import { mxcUrlToHttp, getCanonicalAliasOrRoomId } from '../../utils/matrix';
import { useMediaAuthentication } from '../../hooks/useMediaAuthentication';
import { useOpenSpaceSettings } from '../../state/hooks/spaceSettings';
import { useRoomCreators } from '../../hooks/useRoomCreators';
@@ -28,8 +43,6 @@ import { AddExistingModal } from '../add-existing';
import { SpeechBubble } from '../../components/speech-bubble/SpeechBubble';
import { SpaceOptionsMenu, type OpenAddExistingOptions } from '../space/SpaceOptionsMenu';
import type { HierarchyItemSpace } from '../../hooks/useSpaceHierarchy';
import { useNavigate } from 'react-router-dom';
import { getCanonicalAliasOrRoomId } from '../../utils/matrix';
import { getSpaceFeedPath } from '../../pages/pathUtils';
import { shouldShowForumLobby } from '../../utils/room';
import { useForumBoardContextOptionally } from '../forum/ForumBoardContext';
@@ -176,7 +189,7 @@ const LobbyMenu = forwardRef<HTMLDivElement, LobbyMenuProps>(
</Box>
</Menu>
);
}
},
);
type LobbyHeaderProps = {
@@ -200,7 +213,7 @@ export function LobbyHeader({ showProfile, showSpaceToolbar, powerLevels }: Lobb
const name = useRoomName(space);
const avatarMxc = useRoomAvatar(space);
const avatarUrl = avatarMxc
? mxcUrlToHttp(mx, avatarMxc, useAuthentication, 96, 96, 'crop') ?? undefined
? (mxcUrlToHttp(mx, avatarMxc, useAuthentication, 96, 96, 'crop') ?? undefined)
: undefined;
const forumBoard = useForumBoardContextOptionally();
@@ -228,11 +241,11 @@ export function LobbyHeader({ showProfile, showSpaceToolbar, powerLevels }: Lobb
space: true,
parentId: addParent.roomId === space.roomId ? undefined : space.roomId,
}),
[addParent.roomId, space.roomId]
[addParent.roomId, space.roomId],
);
const canEditChildren = Boolean(
spacePermissions.stateEvent(StateEvent.SpaceChild, mx.getSafeUserId())
spacePermissions.stateEvent(StateEvent.SpaceChild, mx.getSafeUserId()),
);
const handleOpenMenu: MouseEventHandler<HTMLButtonElement> = (evt) => {
@@ -259,7 +272,7 @@ export function LobbyHeader({ showProfile, showSpaceToolbar, powerLevels }: Lobb
const isInside = (node: Node | null) => {
if (!node) return false;
return Boolean(
menuWrapperRef.current?.contains(node) || menuTriggerElRef.current?.contains(node)
menuWrapperRef.current?.contains(node) || menuTriggerElRef.current?.contains(node),
);
};
@@ -299,99 +312,99 @@ export function LobbyHeader({ showProfile, showSpaceToolbar, powerLevels }: Lobb
if (showSpaceToolbar) {
return (
<>
<PageHeader outlined>
<Box grow="Yes" alignItems="Center" gap="300">
{showInPageHeader && (
<Box shrink="No">
<IconButton onClick={goBack} aria-label="Back">
<Icon src={Icons.ArrowLeft} />
</IconButton>
</Box>
)}
<Avatar size="300" shrink="No">
<RoomAvatar
roomId={space.roomId}
src={avatarUrl}
alt={name}
renderFallback={() => <Text size="H4">{nameInitials(name)}</Text>}
/>
</Avatar>
<Text size="H3" truncate style={{ minWidth: 0 }}>
{name}
</Text>
<Box grow="Yes" />
<TooltipProvider
position="Bottom"
align="End"
offset={4}
tooltip={
<Tooltip>
<Text>More Options</Text>
</Tooltip>
}
>
{(triggerRef) => (
<IconButton
onClick={handleOpenMenu}
ref={triggerRef}
aria-pressed={!!menuAnchor}
variant="SurfaceVariant"
fill="None"
size="300"
radii="300"
>
<Icon size="400" src={Icons.VerticalDots} />
</IconButton>
<PageHeader outlined>
<Box grow="Yes" alignItems="Center" gap="300">
{showInPageHeader && (
<Box shrink="No">
<IconButton onClick={goBack} aria-label="Back">
<Icon src={Icons.ArrowLeft} />
</IconButton>
</Box>
)}
</TooltipProvider>
<PopOut
anchor={menuAnchor}
position="Bottom"
align="End"
content={
<FocusTrap
focusTrapOptions={{
initialFocus: false,
returnFocusOnDeactivate: false,
onDeactivate: () => setMenuAnchor(undefined),
clickOutsideDeactivates: true,
isKeyForward: (evt: KeyboardEvent) => evt.key === 'ArrowDown',
isKeyBackward: (evt: KeyboardEvent) => evt.key === 'ArrowUp',
escapeDeactivates: stopPropagation,
}}
>
<div ref={menuWrapperRef}>
<SpeechBubble variant="menu" tail="top" tailX="calc(100% - 22px)">
<SpaceOptionsMenu
room={space}
requestClose={() => setMenuAnchor(undefined)}
onOpenAddExisting={(options) => {
setAddExisting(options);
setMenuAnchor(undefined);
}}
forumAdd={
forumBoard && canEditChildren
? {
item: addParentItem,
showAddSpace: addParent.showAddSpace,
}
: undefined
}
/>
</SpeechBubble>
</div>
</FocusTrap>
}
<Avatar size="300" shrink="No">
<RoomAvatar
roomId={space.roomId}
src={avatarUrl}
alt={name}
renderFallback={() => <Text size="H4">{nameInitials(name)}</Text>}
/>
</Avatar>
<Text size="H3" truncate style={{ minWidth: 0 }}>
{name}
</Text>
<Box grow="Yes" />
<TooltipProvider
position="Bottom"
align="End"
offset={4}
tooltip={
<Tooltip>
<Text>More Options</Text>
</Tooltip>
}
>
{(triggerRef) => (
<IconButton
onClick={handleOpenMenu}
ref={triggerRef}
aria-pressed={!!menuAnchor}
variant="SurfaceVariant"
fill="None"
size="300"
radii="300"
>
<Icon size="400" src={Icons.VerticalDots} />
</IconButton>
)}
</TooltipProvider>
<PopOut
anchor={menuAnchor}
position="Bottom"
align="End"
content={
<FocusTrap
focusTrapOptions={{
initialFocus: false,
returnFocusOnDeactivate: false,
onDeactivate: () => setMenuAnchor(undefined),
clickOutsideDeactivates: true,
isKeyForward: (evt: KeyboardEvent) => evt.key === 'ArrowDown',
isKeyBackward: (evt: KeyboardEvent) => evt.key === 'ArrowUp',
escapeDeactivates: stopPropagation,
}}
>
<div ref={menuWrapperRef}>
<SpeechBubble variant="menu" tail="top" tailX="calc(100% - 22px)">
<SpaceOptionsMenu
room={space}
requestClose={() => setMenuAnchor(undefined)}
onOpenAddExisting={(options) => {
setAddExisting(options);
setMenuAnchor(undefined);
}}
forumAdd={
forumBoard && canEditChildren
? {
item: addParentItem,
showAddSpace: addParent.showAddSpace,
}
: undefined
}
/>
</SpeechBubble>
</div>
</FocusTrap>
}
/>
</Box>
</PageHeader>
{addExisting && (
<AddExistingModal
parentId={addExisting.parentId}
space={addExisting.space}
requestClose={() => setAddExisting(null)}
/>
</Box>
</PageHeader>
{addExisting && (
<AddExistingModal
parentId={addExisting.parentId}
space={addExisting.space}
requestClose={() => setAddExisting(null)}
/>
)}
)}
</>
);
}
+3 -1
View File
@@ -22,7 +22,9 @@ export function LobbyHero() {
const name = useRoomName(space);
const topic = useRoomTopic(space);
const avatarMxc = useRoomAvatar(space);
const avatarUrl = avatarMxc ? mxcUrlToHttp(mx, avatarMxc, useAuthentication, 96, 96, 'crop') ?? undefined : undefined;
const avatarUrl = avatarMxc
? (mxcUrlToHttp(mx, avatarMxc, useAuthentication, 96, 96, 'crop') ?? undefined)
: undefined;
return (
<PageHero
+23 -7
View File
@@ -1,9 +1,25 @@
import React, { MouseEventHandler, ReactNode, useCallback, useRef } from 'react';
import { Avatar, Badge, Box, Chip, Line, Overlay, OverlayBackdrop, OverlayCenter, Spinner, Text, Tooltip, TooltipProvider, as, color, toRem } from 'folds';
import { Icon, Icons } from '../../components/icons';
import {
Avatar,
Badge,
Box,
Chip,
Line,
Overlay,
OverlayBackdrop,
OverlayCenter,
Spinner,
Text,
Tooltip,
TooltipProvider,
as,
color,
toRem,
} from 'folds';
import FocusTrap from 'focus-trap-react';
import { JoinRule, MatrixError, Room } from 'matrix-js-sdk';
import { IHierarchyRoom } from 'matrix-js-sdk/lib/@types/spaces';
import { Icon, Icons } from '../../components/icons';
import { RoomAvatar, RoomIcon } from '../../components/room-avatar';
import { SequenceCard } from '../../components/sequence-card';
import { useMatrixClient } from '../../hooks/useMatrixClient';
@@ -30,7 +46,7 @@ function RoomJoinButton({ roomId, via }: RoomJoinButtonProps) {
const mx = useMatrixClient();
const [joinState, join] = useAsyncCallback<Room, MatrixError, []>(
useCallback(() => mx.joinRoom(roomId, { viaServers: via }), [mx, roomId, via])
useCallback(() => mx.joinRoom(roomId, { viaServers: via }), [mx, roomId, via]),
);
const canJoin = joinState.status === AsyncStatus.Idle || joinState.status === AsyncStatus.Error;
@@ -292,7 +308,7 @@ export const RoomItemCard = as<'div', RoomItemCardProps>(
getRoom,
...props
},
ref
ref,
) => {
const mx = useMatrixClient();
const useAuthentication = useMediaAuthentication();
@@ -383,8 +399,8 @@ export const RoomItemCard = as<'div', RoomItemCardProps>(
topic={summary.topic}
avatarUrl={
summary?.avatar_url
? mxcUrlToHttp(mx, summary.avatar_url, useAuthentication, 96, 96, 'crop') ??
undefined
? (mxcUrlToHttp(mx, summary.avatar_url, useAuthentication, 96, 96, 'crop') ??
undefined)
: undefined
}
memberCount={summary.num_joined_members}
@@ -400,5 +416,5 @@ export const RoomItemCard = as<'div', RoomItemCardProps>(
{after}
</SequenceCard>
);
}
},
);
+9 -5
View File
@@ -67,7 +67,7 @@ export const SpaceHierarchy = forwardRef<HTMLDivElement, SpaceHierarchyProps>(
onOpenRoom,
onSpacesFound,
},
ref
ref,
) => {
const mx = useMatrixClient();
@@ -132,7 +132,9 @@ export const SpaceHierarchy = forwardRef<HTMLDivElement, SpaceHierarchyProps>(
return parentToSubRooms;
}, [mx, roomItems]);
let childItems = roomItems?.filter((i) => !subspaces.has(i.roomId) && !globalSubRoomIds.has(i.roomId));
let childItems = roomItems?.filter(
(i) => !subspaces.has(i.roomId) && !globalSubRoomIds.has(i.roomId),
);
// Only hide when we know the user cannot edit children. If power levels are
// still loading (spacePermissions undefined), keep inaccessible rows visible
// so admins can clean them up.
@@ -196,7 +198,8 @@ export const SpaceHierarchy = forwardRef<HTMLDivElement, SpaceHierarchyProps>(
{childItems && childItems.length > 0 ? (
<Box direction="Column" gap="100">
{childItems.map((roomItem, index) => {
const roomSummary = rooms.get(roomItem.roomId) ?? hierarchySummaries.get(roomItem.roomId);
const roomSummary =
rooms.get(roomItem.roomId) ?? hierarchySummaries.get(roomItem.roomId);
const roomPowerLevels = roomsPowerLevels.get(roomItem.roomId) ?? {};
@@ -249,7 +252,8 @@ export const SpaceHierarchy = forwardRef<HTMLDivElement, SpaceHierarchyProps>(
<Box direction="Column" gap="100" style={{ marginLeft: config.space.S400 }}>
{subRoomIds.map((subRoomId) => {
const subRoom = mx.getRoom(subRoomId);
const subRoomSummary = rooms.get(subRoomId) ?? hierarchySummaries.get(subRoomId);
const subRoomSummary =
rooms.get(subRoomId) ?? hierarchySummaries.get(subRoomId);
const subRoomPowerLevels = roomsPowerLevels.get(subRoomId) ?? {};
const subRoomItem: HierarchyItemRoom = {
roomId: subRoomId,
@@ -318,5 +322,5 @@ export const SpaceHierarchy = forwardRef<HTMLDivElement, SpaceHierarchyProps>(
)}
</Box>
);
}
},
);
+27 -7
View File
@@ -1,10 +1,24 @@
import React, { MouseEventHandler, ReactNode, useCallback, useRef, useState } from 'react';
import { Box, Avatar, Text, Chip, as, Badge, toRem, Spinner, PopOut, Menu, MenuItem, RectCords, config } from 'folds';
import { Icon, Icons } from '../../components/icons';
import {
Box,
Avatar,
Text,
Chip,
as,
Badge,
toRem,
Spinner,
PopOut,
Menu,
MenuItem,
RectCords,
config,
} from 'folds';
import FocusTrap from 'focus-trap-react';
import classNames from 'classnames';
import { MatrixError, Room } from 'matrix-js-sdk';
import { IHierarchyRoom } from 'matrix-js-sdk/lib/@types/spaces';
import { Icon, Icons } from '../../components/icons';
import { HierarchyItem } from '../../hooks/useSpaceHierarchy';
import { useMatrixClient } from '../../hooks/useMatrixClient';
import { RoomAvatar } from '../../components/room-avatar';
@@ -94,7 +108,7 @@ function UnjoinedSpaceProfile({
const mx = useMatrixClient();
const [joinState, join] = useAsyncCallback<Room, MatrixError, []>(
useCallback(() => mx.joinRoom(roomId, { viaServers: via }), [mx, roomId, via])
useCallback(() => mx.joinRoom(roomId, { viaServers: via }), [mx, roomId, via]),
);
const canJoin = joinState.status === AsyncStatus.Idle || joinState.status === AsyncStatus.Error;
@@ -259,7 +273,7 @@ export const SpaceItemCard = as<'div', SpaceItemCardProps>(
getRoom,
...props
},
ref
ref,
) => {
const mx = useMatrixClient();
const useAuthentication = useMediaAuthentication();
@@ -320,8 +334,14 @@ export const SpaceItemCard = as<'div', SpaceItemCardProps>(
name={summary.name || summary.canonical_alias || roomId}
avatarUrl={
summary?.avatar_url
? mxcUrlToHttp(mx, summary.avatar_url, useAuthentication, 96, 96, 'crop') ??
undefined
? (mxcUrlToHttp(
mx,
summary.avatar_url,
useAuthentication,
96,
96,
'crop',
) ?? undefined)
: undefined
}
suggested={content.suggested}
@@ -340,5 +360,5 @@ export const SpaceItemCard = as<'div', SpaceItemCardProps>(
{after}
</Box>
);
}
},
);
@@ -1,11 +1,11 @@
import React, { RefObject, useEffect, useMemo, useRef } from 'react';
import { Text, Box, config, Spinner, IconButton, Line, toRem } from 'folds';
import { Icon, Icons } from '../../components/icons';
import { useAtomValue } from 'jotai';
import { useVirtualizer } from '@tanstack/react-virtual';
import { useInfiniteQuery } from '@tanstack/react-query';
import { useSearchParams } from 'react-router-dom';
import { SearchOrderBy } from 'matrix-js-sdk';
import { Icon, Icons } from '../../components/icons';
import { PageHero, PageHeroEmpty, PageHeroSection } from '../../components/page';
import { useMatrixClient } from '../../hooks/useMatrixClient';
import { _SearchPathSearchParams } from '../../pages/paths';
@@ -34,7 +34,7 @@ const useSearchPathSearchParams = (searchParams: URLSearchParams): _SearchPathSe
rooms: searchParams.get('rooms') ?? undefined,
senders: searchParams.get('senders') ?? undefined,
}),
[searchParams]
[searchParams],
);
type MessageSearchProps = {
@@ -58,7 +58,7 @@ export function MessageSearch({
// Include DMs — previously useRooms alone stripped them and broke DM search
const allRooms = useMemo(
() => [...nonDirectRooms, ...directRooms],
[nonDirectRooms, directRooms]
[nonDirectRooms, directRooms],
);
const [mediaAutoLoad] = useSetting(settingsAtom, 'mediaAutoLoad');
const [urlPreview] = useSetting(settingsAtom, 'urlPreview');
@@ -76,7 +76,7 @@ export function MessageSearch({
const searchParamRooms = useMemo(() => {
if (searchPathSearchParams.rooms) {
const joinedRoomIds = decodeSearchParamValueArray(searchPathSearchParams.rooms).filter(
(rId) => allRooms.includes(rId)
(rId) => allRooms.includes(rId),
);
return joinedRoomIds;
}
@@ -6,11 +6,27 @@ import React, {
useRef,
useState,
} from 'react';
import { Box, Chip, Text, Line, config, PopOut, Menu, MenuItem, Header, toRem, Scroll, Button, Input, Badge, RectCords } from 'folds';
import { Icon, Icons } from '../../components/icons';
import {
Box,
Chip,
Text,
Line,
config,
PopOut,
Menu,
MenuItem,
Header,
toRem,
Scroll,
Button,
Input,
Badge,
RectCords,
} from 'folds';
import { SearchOrderBy } from 'matrix-js-sdk';
import FocusTrap from 'focus-trap-react';
import { useVirtualizer } from '@tanstack/react-virtual';
import { Icon, Icons } from '../../components/icons';
import { useMatrixClient } from '../../hooks/useMatrixClient';
import { joinRuleToIconSrc } from '../../utils/room';
import { factoryRoomIdByAtoZ } from '../../utils/sort';
@@ -117,13 +133,13 @@ function SelectRoomButton({ roomList, selectedRooms, onChange }: SelectRoomButto
const getRoomNameStr: SearchItemStrGetter<string> = useCallback(
(rId) => mx.getRoom(rId)?.name ?? rId,
[mx]
[mx],
);
const [searchResult, _searchRoom, resetSearch] = useAsyncSearch(
roomList,
getRoomNameStr,
SEARCH_OPTS
SEARCH_OPTS,
);
const rooms = Array.from(searchResult?.items ?? roomList).sort(factoryRoomIdByAtoZ(mx));
@@ -2,6 +2,7 @@ import React, { FormEventHandler, RefObject } from 'react';
import { Box, Text, Input, Spinner, Chip, config } from 'folds';
import { Icon, Icons } from '../../components/icons';
type SearchProps = {
active?: boolean;
loading?: boolean;
@@ -3,8 +3,8 @@ import React, { MouseEventHandler, useMemo } from 'react';
import { IEventWithRoomId, JoinRule, RelationType, Room } from 'matrix-js-sdk';
import { HTMLReactParserOptions } from 'html-react-parser';
import { Avatar, Box, Chip, Header, Text, config } from 'folds';
import { Icon, Icons } from '../../components/icons';
import { Opts as LinkifyOpts } from 'linkifyjs';
import { Icon, Icons } from '../../components/icons';
import { useMatrixClient } from '../../hooks/useMatrixClient';
import {
factoryRenderLinkifyWithMention,
@@ -62,7 +62,9 @@ type SearchResultItemProps = {
item: ResultItem;
getMemberPowerTag: ReturnType<typeof useGetMemberPowerTag>;
accessibleTagColors: Map<string, string> | undefined;
renderMatrixEvent: ReturnType<typeof useMatrixEventRenderer<[IEventWithRoomId, string, GetContentCallback]>>;
renderMatrixEvent: ReturnType<
typeof useMatrixEventRenderer<[IEventWithRoomId, string, GetContentCallback]>
>;
handleOpenClick: MouseEventHandler;
legacyUsernameColor?: boolean;
hour24Clock: boolean;
@@ -88,21 +90,17 @@ function SearchResultItem({
const { event } = item;
const displayName =
getMemberDisplayName(room, event.sender) ??
getMxIdLocalPart(event.sender) ??
event.sender;
getMemberDisplayName(room, event.sender) ?? getMxIdLocalPart(event.sender) ?? event.sender;
const senderAvatarMxc = getMemberAvatarMxc(room, event.sender);
const relation = event.content['m.relates_to'];
const mainEventId =
relation?.rel_type === RelationType.Replace ? relation.event_id : event.event_id;
const getContent = (() =>
event.content['m.new_content'] ?? event.content) as GetContentCallback;
const getContent = (() => event.content['m.new_content'] ?? event.content) as GetContentCallback;
const replyEventId = relation?.['m.in_reply_to']?.event_id;
const threadRootId =
relation?.rel_type === RelationType.Thread ? relation.event_id : undefined;
const threadRootId = relation?.rel_type === RelationType.Thread ? relation.event_id : undefined;
// Get custom user color from avatar metadata
const customUserColor = useOtherUserColor(event.sender, room);
@@ -116,7 +114,8 @@ function SearchResultItem({
: undefined;
// Priority: custom user color > tag color (non-legacy) > colorMXID (legacy)
const usernameColor = customUserColor ?? (legacyUsernameColor ? colorMXID(event.sender) : tagColor);
const usernameColor =
customUserColor ?? (legacyUsernameColor ? colorMXID(event.sender) : tagColor);
return (
<SequenceCard
@@ -133,14 +132,8 @@ function SearchResultItem({
userId={event.sender}
src={
senderAvatarMxc
? mxcUrlToHttp(
mx,
senderAvatarMxc,
useAuthentication,
48,
48,
'crop'
) ?? undefined
? (mxcUrlToHttp(mx, senderAvatarMxc, useAuthentication, 48, 48, 'crop') ??
undefined)
: undefined
}
alt={displayName}
@@ -237,10 +230,10 @@ export function SearchResultGroup({
() => ({
...LINKIFY_OPTS,
render: factoryRenderLinkifyWithMention((href) =>
renderMatrixMention(mx, room.roomId, href, makeMentionCustomProps(mentionClickHandler))
renderMatrixMention(mx, room.roomId, href, makeMentionCustomProps(mentionClickHandler)),
),
}),
[mx, room, mentionClickHandler]
[mx, room, mentionClickHandler],
);
const htmlReactParserOptions = useMemo<HTMLReactParserOptions>(
() =>
@@ -259,7 +252,7 @@ export function SearchResultGroup({
mentionClickHandler,
spoilerClickHandler,
useAuthentication,
]
],
);
const renderMatrixEvent = useMatrixEventRenderer<[IEventWithRoomId, string, GetContentCallback]>(
@@ -326,7 +319,7 @@ export function SearchResultGroup({
</Text>
</Box>
);
}
},
);
const handleOpenClick: MouseEventHandler = (evt) => {
@@ -104,8 +104,7 @@ const getSearchableBody = (event: MatrixEvent): string | undefined => {
}
const body = typeof content.body === 'string' ? content.body : undefined;
const formatted =
typeof content.formatted_body === 'string' ? content.formatted_body : undefined;
const formatted = typeof content.formatted_body === 'string' ? content.formatted_body : undefined;
return [body, formatted].filter(Boolean).join('\n') || undefined;
};
@@ -233,7 +232,7 @@ export const useMessageSearch = (params: MessageSearchParams) => {
return searchLocalRooms(
mx,
scopedRooms.filter((id) => isEncryptedRoom(mx, id)),
term
term,
);
}
@@ -245,7 +244,7 @@ export const useMessageSearch = (params: MessageSearchParams) => {
throw new Error('Message search failed');
}
},
[mx, term, order, rooms, senders]
[mx, term, order, rooms, senders],
);
return searchMessages;
+3 -3
View File
@@ -43,7 +43,7 @@ export function RoomAppSchema({
const scopedCss = useMemo(
() => (content.css ? scopeRoomAppCss(content.css, SCOPE) : ''),
[content.css]
[content.css],
);
const setField = useCallback((name: string, value: string) => {
@@ -66,7 +66,7 @@ export function RoomAppSchema({
setSending(false);
}
},
[onAction, sending, uiEventId, values]
[onAction, sending, uiEventId, values],
);
const renderNode = (node: PaarrotUiNode): React.ReactNode => {
@@ -174,7 +174,7 @@ export function RoomAppSchema({
case 'image': {
if (!isAllowedRoomAppImageSrc(node.src)) return null;
const httpSrc = node.src.startsWith('mxc://')
? mxcUrlToHttp(mx, node.src, useAuthentication) ?? undefined
? (mxcUrlToHttp(mx, node.src, useAuthentication) ?? undefined)
: node.src;
if (!httpSrc) return null;
return (
+2 -6
View File
@@ -6,11 +6,7 @@ import { useMatrixClient } from '../../hooks/useMatrixClient';
import { useMediaAuthentication } from '../../hooks/useMediaAuthentication';
import { useStateEvent } from '../../hooks/useStateEvent';
import { useRoomName } from '../../hooks/useRoomMeta';
import {
MessageEvent,
PaarrotUiActionContent,
StateEvent,
} from '../../../types/matrix/room';
import { MessageEvent, PaarrotUiActionContent, StateEvent } from '../../../types/matrix/room';
import { parsePaarrotUiContent } from '../../utils/room';
import { RoomAppSchema } from './RoomAppSchema';
import * as css from './RoomAppView.css';
@@ -32,7 +28,7 @@ export function RoomAppView({ room, onShowChat }: RoomAppViewProps) {
async (payload: PaarrotUiActionContent) => {
await mx.sendEvent(room.roomId, MessageEvent.PaarrotUiAction as any, payload);
},
[mx, room.roomId]
[mx, room.roomId],
);
return (
@@ -84,8 +84,6 @@ export function scopeRoomAppCss(css: string, scopeSelector: string): string {
export function isAllowedRoomAppImageSrc(src: string): boolean {
const trimmed = src.trim();
return (
trimmed.startsWith('mxc://') ||
trimmed.startsWith('https://') ||
trimmed.startsWith('http://')
trimmed.startsWith('mxc://') || trimmed.startsWith('https://') || trimmed.startsWith('http://')
);
}
@@ -37,23 +37,22 @@ export function CallParticipantsIndicator({ roomId }: CallParticipantsIndicatorP
return mxcUrlToHttp(mx, mxcUrl, useAuthentication, 48, 48, 'crop') ?? undefined;
};
const getParticipantName = (userId: string): string => {
return getMemberDisplayName(room, userId) ?? getMxIdLocalPart(userId) ?? userId;
};
const getParticipantName = (userId: string): string =>
getMemberDisplayName(room, userId) ?? getMxIdLocalPart(userId) ?? userId;
/**
* Check if a participant is currently speaking
*/
const isParticipantSpeaking = (userId: string): boolean => {
if (!activeCall) return false;
// Direct check for Matrix user ID (works for local user)
if (activeCall.activeSpeakers.has(userId)) return true;
// For remote users, activeSpeakers contains LiveKit identities (deviceId_timestamp)
const member = callMembers.find((m) => m.userId === userId);
if (!member) return false;
// Check if any active speaker has this user's deviceId
return Array.from(activeCall.activeSpeakers).some((speakerId) => {
const underscoreIndex = speakerId.lastIndexOf('_');
@@ -67,14 +66,14 @@ export function CallParticipantsIndicator({ roomId }: CallParticipantsIndicatorP
*/
const isParticipantMuted = (userId: string): boolean => {
if (!activeCall) return false;
// For local user, check activeCall.isMuted
if (userId === myUserId) return activeCall.isMuted;
// For remote users, mutedParticipants contains LiveKit identities (deviceId_timestamp)
const member = callMembers.find((m) => m.userId === userId);
if (!member) return false;
// Check if any muted participant has this user's deviceId
return Array.from(activeCall.mutedParticipants).some((mutedId) => {
const underscoreIndex = mutedId.lastIndexOf('_');
@@ -115,7 +114,7 @@ export function CallParticipantsIndicator({ roomId }: CallParticipantsIndicatorP
const isSpeaking = isParticipantSpeaking(member.userId);
const isMuted = isParticipantMuted(member.userId);
const isDeafened = isLocalUserDeafened(member.userId);
return (
<Box
key={member.userId}
@@ -125,8 +124,8 @@ export function CallParticipantsIndicator({ roomId }: CallParticipantsIndicatorP
opacity: config.opacity.P300,
}}
>
<Avatar
size="200"
<Avatar
size="200"
radii="Pill"
className={isSpeaking ? css.ParticipantSpeaking : undefined}
>
@@ -148,13 +147,17 @@ export function CallParticipantsIndicator({ roomId }: CallParticipantsIndicatorP
)}
</Avatar>
<Box alignItems="Center" gap="100" grow="Yes">
<Icon
src={getAudioIcon(member.userId)}
size="50"
style={{
<Icon
src={getAudioIcon(member.userId)}
size="50"
style={{
opacity: config.opacity.P500,
color: isDeafened ? 'var(--color-Critical-Main)' : isMuted ? 'var(--color-Critical-Main)' : undefined
}}
color: isDeafened
? 'var(--color-Critical-Main)'
: isMuted
? 'var(--color-Critical-Main)'
: undefined,
}}
/>
<Text as="span" size="T200" truncate>
{getParticipantName(member.userId)}
@@ -1,7 +1,7 @@
import React from 'react';
import { as, Chip, Text } from 'folds';
import { Icon, Icons } from '../../components/icons';
import classNames from 'classnames';
import { Icon, Icons } from '../../components/icons';
import * as css from './styles.css';
export const RoomNavCategoryButton = as<'button', { closed?: boolean }>(
@@ -25,5 +25,5 @@ export const RoomNavCategoryButton = as<'button', { closed?: boolean }>(
{children}
</Text>
</Chip>
)
),
);
+128 -88
View File
@@ -2,15 +2,36 @@ import React, { MouseEventHandler, forwardRef, useState, useMemo } from 'react';
import { Room, EventTimeline } from 'matrix-js-sdk';
import { useAtomValue } from 'jotai';
import { useNavigate } from 'react-router-dom';
import { Avatar, Box, IconButton, Text, Menu, MenuItem, config, PopOut, toRem, Line, RectCords, Badge, Spinner, Tooltip, TooltipProvider } from 'folds';
import { Icon, Icons } from '../../components/icons';
import {
Avatar,
Box,
IconButton,
Text,
Menu,
MenuItem,
config,
PopOut,
toRem,
Line,
RectCords,
Badge,
Spinner,
Tooltip,
TooltipProvider,
} from 'folds';
import { useFocusWithin, useHover } from 'react-aria';
import FocusTrap from 'focus-trap-react';
import { Icon, Icons } from '../../components/icons';
import { NavItem, NavItemContent, NavItemOptions, NavLink } from '../../components/nav';
import * as css from '../../components/nav/styles.css';
import { UnreadBadge, UnreadBadgeCenter } from '../../components/unread-badge';
import { RoomAvatar, RoomIcon } from '../../components/room-avatar';
import { getDirectRoomAvatarUrl, getRoomAvatarUrl, guessPerfectParent, getOrphanParents } from '../../utils/room';
import {
getDirectRoomAvatarUrl,
getRoomAvatarUrl,
guessPerfectParent,
getOrphanParents,
} from '../../utils/room';
import { nameInitials } from '../../utils/common';
import { useMatrixClient } from '../../hooks/useMatrixClient';
import { useRoomUnread } from '../../state/hooks/unread';
@@ -24,7 +45,12 @@ import { useRoomTypingMember } from '../../hooks/useRoomTypingMembers';
import { TypingIndicator } from '../../components/typing-indicator';
import { stopPropagation } from '../../utils/keyboard';
import { getMatrixToRoom } from '../../plugins/matrix-to';
import { getCanonicalAliasOrRoomId, guessDmRoomUserId, isRoomAlias, mxcUrlToHttp } from '../../utils/matrix';
import {
getCanonicalAliasOrRoomId,
guessDmRoomUserId,
isRoomAlias,
mxcUrlToHttp,
} from '../../utils/matrix';
import { getViaServers } from '../../plugins/via-servers';
import { useMediaAuthentication } from '../../hooks/useMediaAuthentication';
import { useSetting } from '../../state/hooks/settings';
@@ -257,7 +283,7 @@ const RoomNavItemMenu = forwardRef<HTMLDivElement, RoomNavItemMenuProps>(
</Box>
</Menu>
);
}
},
);
type RoomNavItemProps = {
@@ -296,10 +322,10 @@ export function RoomNavItem({
const isDirect = Boolean(direct || mDirects.has(room.roomId));
const dmUserId = isDirect ? guessDmRoomUserId(room, mx.getSafeUserId()) : undefined;
const dmPresence = useUserPresence(dmUserId ?? '');
const shouldShowIcon = !hideIcon || (hideIcon && avatarUrl);
const typingMember = useRoomTypingMember(room.roomId).filter(
(receipt) => receipt.userId !== mx.getUserId()
(receipt) => receipt.userId !== mx.getUserId(),
);
const roomToParents = useAtomValue(roomToParentsAtom);
@@ -311,7 +337,7 @@ export function RoomNavItem({
if (participatedThreads.length === 0) return undefined;
const firstThread = participatedThreads[0];
const rootEvent = firstThread.rootEvent;
const { rootEvent } = firstThread;
if (!rootEvent) return undefined;
const rootBody = rootEvent.getContent()?.body ?? '';
@@ -324,18 +350,24 @@ export function RoomNavItem({
// Get parent space for DMs
const parentSpaceInfo = (() => {
if (!isDirect || !mDirects.has(room.roomId)) return undefined;
const orphanParents = getOrphanParents(roomToParents, room.roomId);
if (orphanParents.length === 0) return undefined;
const parentSpaceId = guessPerfectParent(mx, room.roomId, orphanParents) ?? orphanParents[0];
const parentSpace = mx.getRoom(parentSpaceId);
if (!parentSpace) return undefined;
const avatarEvent = parentSpace.getLiveTimeline().getState(EventTimeline.FORWARDS)?.getStateEvents(StateEvent.RoomAvatar, '');
const avatarEvent = parentSpace
.getLiveTimeline()
.getState(EventTimeline.FORWARDS)
?.getStateEvents(StateEvent.RoomAvatar, '');
const avatarContent = avatarEvent?.getContent();
const avatarMxc = avatarContent && typeof avatarContent.url === 'string' ? avatarContent.url : undefined;
const avatarUrl = avatarMxc ? mxcUrlToHttp(mx, avatarMxc, useAuthentication, 96, 96, 'crop') ?? undefined : undefined;
const avatarMxc =
avatarContent && typeof avatarContent.url === 'string' ? avatarContent.url : undefined;
const avatarUrl = avatarMxc
? (mxcUrlToHttp(mx, avatarMxc, useAuthentication, 96, 96, 'crop') ?? undefined)
: undefined;
return {
name: parentSpace.name,
@@ -360,11 +392,11 @@ export function RoomNavItem({
const handleRoomClick: MouseEventHandler<HTMLAnchorElement> = (evt) => {
if (selected) {
evt.preventDefault();
const shouldScroll =
const shouldScroll =
scrollToLatestBehavior === ScrollToLatestBehavior.Always ||
(scrollToLatestBehavior === ScrollToLatestBehavior.OnNewMessage && unread !== undefined);
if (shouldScroll) {
navigate(linkPath, { replace: true, state: { scrollToLatest: Date.now() } });
}
@@ -388,13 +420,13 @@ export function RoomNavItem({
>
<NavLink to={linkPath} onClick={handleRoomClick}>
<NavItemContent>
<Box as="span" grow="Yes" alignItems="Center" gap={shouldShowIcon ? "200" : "100"}>
<Box as="span" grow="Yes" alignItems="Center" gap={shouldShowIcon ? '200' : '100'}>
{shouldShowIcon &&
(isDirect ? (
<PresenceAvatar
presence={
dmUserId && dmUserId !== mx.getSafeUserId()
? dmPresence?.presence ?? Presence.Offline
? (dmPresence?.presence ?? Presence.Offline)
: Presence.Offline
}
>
@@ -443,7 +475,12 @@ export function RoomNavItem({
)}
</Avatar>
))}
<Box as="span" grow="Yes" direction="Column" style={{ overflow: 'hidden', minWidth: 0 }}>
<Box
as="span"
grow="Yes"
direction="Column"
style={{ overflow: 'hidden', minWidth: 0 }}
>
<Text priority={unread ? '500' : '300'} as="span" size="Inherit" truncate>
{room.name}
</Text>
@@ -469,76 +506,79 @@ export function RoomNavItem({
</Box>
</NavItemContent>
</NavLink>
{optionsVisible && (
<NavItemOptions>
<Box alignItems="Center" gap="100">
{parentSpaceInfo && (
<TooltipProvider
position="Top"
tooltip={
<Tooltip>
<Text size="T200">Space: {parentSpaceInfo.name}</Text>
</Tooltip>
}
>
{(triggerRef) => (
<Avatar ref={triggerRef} size="200" radii="Pill" style={{ flexShrink: 0, width: '16px', height: '16px' }}>
<RoomAvatar
roomId={parentSpaceInfo.roomId}
src={parentSpaceInfo.avatarUrl}
alt={parentSpaceInfo.name}
renderFallback={() => (
<Text size="Inherit">
{nameInitials(parentSpaceInfo.name, 1)}
</Text>
)}
/>
</Avatar>
)}
</TooltipProvider>
)}
{optionsVisible && (
<PopOut
anchor={menuAnchor}
offset={menuAnchor?.width === 0 ? 0 : undefined}
alignOffset={menuAnchor?.width === 0 ? 0 : -5}
position="Bottom"
align={menuAnchor?.width === 0 ? 'Start' : 'End'}
content={
<FocusTrap
focusTrapOptions={{
initialFocus: false,
returnFocusOnDeactivate: false,
onDeactivate: () => setMenuAnchor(undefined),
clickOutsideDeactivates: true,
isKeyForward: (evt: KeyboardEvent) => evt.key === 'ArrowDown',
isKeyBackward: (evt: KeyboardEvent) => evt.key === 'ArrowUp',
escapeDeactivates: stopPropagation,
}}
>
<RoomNavItemMenu
room={room}
requestClose={() => setMenuAnchor(undefined)}
notificationMode={notificationMode}
/>
</FocusTrap>
}
>
<IconButton
onClick={handleOpenMenu}
aria-pressed={!!menuAnchor}
variant="Background"
fill="None"
size="300"
radii="300"
{optionsVisible && (
<NavItemOptions>
<Box alignItems="Center" gap="100">
{parentSpaceInfo && (
<TooltipProvider
position="Top"
tooltip={
<Tooltip>
<Text size="T200">Space: {parentSpaceInfo.name}</Text>
</Tooltip>
}
>
<Icon size="50" src={Icons.VerticalDots} />
</IconButton>
</PopOut>
)}
</Box>
</NavItemOptions>
)}
{(triggerRef) => (
<Avatar
ref={triggerRef}
size="200"
radii="Pill"
style={{ flexShrink: 0, width: '16px', height: '16px' }}
>
<RoomAvatar
roomId={parentSpaceInfo.roomId}
src={parentSpaceInfo.avatarUrl}
alt={parentSpaceInfo.name}
renderFallback={() => (
<Text size="Inherit">{nameInitials(parentSpaceInfo.name, 1)}</Text>
)}
/>
</Avatar>
)}
</TooltipProvider>
)}
{optionsVisible && (
<PopOut
anchor={menuAnchor}
offset={menuAnchor?.width === 0 ? 0 : undefined}
alignOffset={menuAnchor?.width === 0 ? 0 : -5}
position="Bottom"
align={menuAnchor?.width === 0 ? 'Start' : 'End'}
content={
<FocusTrap
focusTrapOptions={{
initialFocus: false,
returnFocusOnDeactivate: false,
onDeactivate: () => setMenuAnchor(undefined),
clickOutsideDeactivates: true,
isKeyForward: (evt: KeyboardEvent) => evt.key === 'ArrowDown',
isKeyBackward: (evt: KeyboardEvent) => evt.key === 'ArrowUp',
escapeDeactivates: stopPropagation,
}}
>
<RoomNavItemMenu
room={room}
requestClose={() => setMenuAnchor(undefined)}
notificationMode={notificationMode}
/>
</FocusTrap>
}
>
<IconButton
onClick={handleOpenMenu}
aria-pressed={!!menuAnchor}
variant="Background"
fill="None"
size="300"
radii="300"
>
<Icon size="50" src={Icons.VerticalDots} />
</IconButton>
</PopOut>
)}
</Box>
</NavItemOptions>
)}
</NavItem>
<CallParticipantsIndicator roomId={room.roomId} />
</Box>
@@ -1,7 +1,7 @@
import React, { useCallback } from 'react';
import { Box, Chip, Spinner, Text, Tooltip, TooltipProvider, color, config, toRem } from 'folds';
import { Icon, Icons } from '../../components/icons';
import { MatrixError, Room } from 'matrix-js-sdk';
import { Icon, Icons } from '../../components/icons';
import { useMatrixClient } from '../../hooks/useMatrixClient';
import { AsyncStatus, useAsyncCallback } from '../../hooks/useAsyncCallback';
@@ -28,12 +28,12 @@ export function UnjoinedSubRoomItem({ roomId, depth, isLast = false }: UnjoinedS
const viaServers = [getServerFromRoomId(roomId)].filter(Boolean);
const [joinState, join] = useAsyncCallback<Room, MatrixError, []>(
useCallback(() => mx.joinRoom(roomId, { viaServers }), [mx, roomId, viaServers])
useCallback(() => mx.joinRoom(roomId, { viaServers }), [mx, roomId, viaServers]),
);
const canJoin = joinState.status === AsyncStatus.Idle || joinState.status === AsyncStatus.Error;
const paddingLeft = depth > 0 ? '30px' : undefined;
let treeIcon = '';
if (depth > 0) {
treeIcon = isLast ? '╰' : '├';
@@ -52,15 +52,17 @@ export function UnjoinedSubRoomItem({ roomId, depth, isLast = false }: UnjoinedS
gap="200"
>
{treeIcon && (
<span style={{
paddingRight: '2px',
opacity: 0.5,
fontFamily: 'monospace',
fontSize: '14px',
lineHeight: '1',
userSelect: 'none',
marginLeft: '-10px'
}}>
<span
style={{
paddingRight: '2px',
opacity: 0.5,
fontFamily: 'monospace',
fontSize: '14px',
lineHeight: '1',
userSelect: 'none',
marginLeft: '-10px',
}}
>
{treeIcon}
</span>
)}
@@ -96,7 +98,11 @@ export function UnjoinedSubRoomItem({ roomId, depth, isLast = false }: UnjoinedS
size="400"
radii="Pill"
before={
canJoin ? <Icon src={Icons.Plus} size="50" /> : <Spinner variant="Secondary" size="50" />
canJoin ? (
<Icon src={Icons.Plus} size="50" />
) : (
<Spinner variant="Secondary" size="50" />
)
}
onClick={join}
disabled={!canJoin}
@@ -1,8 +1,8 @@
import React, { useMemo, useState } from 'react';
import { useAtomValue } from 'jotai';
import { Avatar, Box, config, IconButton, MenuItem, Text } from 'folds';
import { Icon, Icons, IconSrc } from '../../components/icons';
import { JoinRule } from 'matrix-js-sdk';
import { Icon, Icons, IconSrc } from '../../components/icons';
import { PageNav, PageNavContent, PageNavHeader, PageRoot } from '../../components/page';
import { ScreenSize, useScreenSizeContext } from '../../hooks/useScreenSize';
import { useMatrixClient } from '../../hooks/useMatrixClient';
@@ -60,7 +60,7 @@ const useRoomSettingsMenuItems = (): RoomSettingsMenuItem[] =>
icon: Icons.Terminal,
},
],
[]
[],
);
type RoomSettingsProps = {
@@ -78,7 +78,7 @@ export function RoomSettings({ initialPage, requestClose }: RoomSettingsProps) {
const joinRuleContent = useRoomJoinRule(room);
const avatarUrl = roomAvatar
? mxcUrlToHttp(mx, roomAvatar, useAuthentication, 96, 96, 'crop') ?? undefined
? (mxcUrlToHttp(mx, roomAvatar, useAuthentication, 96, 96, 'crop') ?? undefined)
: undefined;
const screenSize = useScreenSizeContext();
@@ -168,9 +168,7 @@ export function RoomSettings({ initialPage, requestClose }: RoomSettingsProps) {
{activePage === RoomSettingsPage.PermissionsPage && (
<Permissions requestClose={handlePageRequestClose} />
)}
{activePage === RoomSettingsPage.SubRoomsPage && (
<SubRooms />
)}
{activePage === RoomSettingsPage.SubRoomsPage && <SubRooms />}
{activePage === RoomSettingsPage.EmojisStickersPage && (
<EmojisStickers requestClose={handlePageRequestClose} />
)}
@@ -1,7 +1,7 @@
import React, { useState, useCallback } from 'react';
import { Box, Button, Text, config, IconButton, Chip, Line } from 'folds';
import { Icon, Icons } from '../../../components/icons';
import { useAtomValue } from 'jotai';
import { Icon, Icons } from '../../../components/icons';
import { useMatrixClient } from '../../../hooks/useMatrixClient';
import { useRoom } from '../../../hooks/useRoom';
import { useRoomSubRooms, PaarrotSubRoomsContent } from '../../../hooks/useRoomSubRooms';
@@ -15,7 +15,15 @@ import { useRoomPermissions } from '../../../hooks/useRoomPermissions';
import { roomToParentsAtom } from '../../../state/room/roomToParents';
import { isSpace } from '../../../utils/room';
function SubRoomItem({ roomId, onRemove, canEdit }: { roomId: string; onRemove: (roomId: string) => void; canEdit: boolean }) {
function SubRoomItem({
roomId,
onRemove,
canEdit,
}: {
roomId: string;
onRemove: (roomId: string) => void;
canEdit: boolean;
}) {
const allJoinedRooms = useAllJoinedRoomsSet();
const getRoom = useGetRoom(allJoinedRooms);
const room = getRoom(roomId);
@@ -77,26 +85,26 @@ export function SubRooms() {
// eslint-disable-next-line @typescript-eslint/no-explicit-any
await mx.sendStateEvent(room.roomId, StateEvent.PaarrotSubRooms as any, content, '');
},
[mx, room]
)
[mx, room],
),
);
const handleRemoveSubRoom = useCallback(
(roomId: string) => {
const newSubRooms = subRooms.filter(id => id !== roomId);
const newSubRooms = subRooms.filter((id) => id !== roomId);
updateSubRooms(newSubRooms);
},
[subRooms, updateSubRooms]
[subRooms, updateSubRooms],
);
const handleAddRoom = useCallback(async () => {
const trimmedId = addRoomId.trim();
if (!trimmedId) return;
// Try to resolve room - if it's already joined, use the actual room ID
const targetRoom = mx.getRoom(trimmedId);
const roomIdToAdd = targetRoom ? targetRoom.roomId : trimmedId;
// Allow adding any room ID (even if not joined)
if (!subRooms.includes(roomIdToAdd)) {
const newSubRooms = [...subRooms, roomIdToAdd];
@@ -121,14 +129,14 @@ export function SubRooms() {
// eslint-disable-next-line @typescript-eslint/no-explicit-any
StateEvent.SpaceChild as any,
{ via: spaceViaServers },
roomIdToAdd
roomIdToAdd,
);
} catch (spaceError) {
// eslint-disable-next-line no-console
console.warn(`Failed to add sub-room to space ${parentSpaceId}:`, spaceError);
}
}
})
}),
);
}
@@ -144,8 +152,8 @@ export function SubRooms() {
Sub-Rooms
</Text>
<Text size="T300" priority="300">
Sub-rooms are nested rooms that appear indented under this room in the room list.
They work like sub-spaces but for regular rooms.
Sub-rooms are nested rooms that appear indented under this room in the room list. They
work like sub-spaces but for regular rooms.
</Text>
</Box>
</SettingTile>
@@ -217,14 +225,20 @@ export function SubRooms() {
) : (
<Box wrap="Wrap" gap="200">
{subRooms.map((roomId) => (
<SubRoomItem key={roomId} roomId={roomId} onRemove={handleRemoveSubRoom} canEdit={canEdit} />
<SubRoomItem
key={roomId}
roomId={roomId}
onRemove={handleRemoveSubRoom}
canEdit={canEdit}
/>
))}
</Box>
)}
{updateState.status === AsyncStatus.Error && (
<Text size="T300" priority="400" style={{ color: 'var(--color-critical)' }}>
Failed to update sub-rooms: {String((updateState.error as Error)?.message || updateState.error)}
Failed to update sub-rooms:{' '}
{String((updateState.error as Error)?.message || updateState.error)}
</Text>
)}
</Box>
@@ -39,18 +39,18 @@ export function CommandAutocomplete({
}: CommandAutocompleteProps) {
const mx = useMatrixClient();
const commands = useCommands(mx, room);
// Merge built-in commands with plugin commands
const commandNames = useMemo(() => {
const builtInCommands = Object.keys(commands) as Command[];
const pluginCommands = pluginRegistry.getCommands().map(cmd => cmd.name);
const pluginCommands = pluginRegistry.getCommands().map((cmd) => cmd.name);
return [...builtInCommands, ...pluginCommands];
}, [commands]);
const [result, search, resetSearch] = useAsyncSearch(
commandNames,
useCallback((commandName: string) => commandName, []),
SEARCH_OPTIONS
SEARCH_OPTIONS,
);
const autoCompleteNames = result ? result.items : commandNames;
@@ -89,9 +89,9 @@ export function CommandAutocomplete({
{autoCompleteNames.map((commandName) => {
// Get description from built-in commands or plugin commands
const builtInCmd = commands[commandName as Command];
const pluginCmd = pluginRegistry.getCommands().find(cmd => cmd.name === commandName);
const pluginCmd = pluginRegistry.getCommands().find((cmd) => cmd.name === commandName);
const description = builtInCmd?.description || pluginCmd?.command.description || '';
return (
<MenuItem
key={commandName}
+1 -1
View File
@@ -38,7 +38,7 @@ export function ForumRoomView({ room, eventId }: ForumRoomViewProps) {
}
return next;
},
{ replace: true }
{ replace: true },
);
}, [eventId, setSearchParams, room.roomId, forumSpaceId]);
+26 -9
View File
@@ -6,11 +6,28 @@ import React, {
useRef,
useState,
} from 'react';
import { Avatar, Badge, Box, Chip, Header, IconButton, Input, MenuItem, PopOut, RectCords, Scroll, Spinner, Text, Tooltip, TooltipProvider, config } from 'folds';
import { Icon, Icons } from '../../components/icons';
import {
Avatar,
Badge,
Box,
Chip,
Header,
IconButton,
Input,
MenuItem,
PopOut,
RectCords,
Scroll,
Spinner,
Text,
Tooltip,
TooltipProvider,
config,
} from 'folds';
import { MatrixClient, Room, RoomMember } from 'matrix-js-sdk';
import { useVirtualizer } from '@tanstack/react-virtual';
import classNames from 'classnames';
import { Icon, Icons } from '../../components/icons';
import * as css from './MembersDrawer.css';
import { useMatrixClient } from '../../hooks/useMatrixClient';
@@ -187,13 +204,13 @@ export function MembersDrawer({ room, members }: MembersDrawerProps) {
const filteredMembers = useMemo(
() => members.filter(membershipFilter.filterFn).sort(memberSort.sortFn).sort(memberPowerSort),
[members, membershipFilter, memberSort, memberPowerSort]
[members, membershipFilter, memberSort, memberPowerSort],
);
const [result, search, resetSearch] = useAsyncSearch(
filteredMembers,
getRoomMemberStr,
SEARCH_OPTIONS
SEARCH_OPTIONS,
);
if (!result && searchInputRef.current?.value) search(searchInputRef.current.value);
@@ -214,9 +231,9 @@ export function MembersDrawer({ room, members }: MembersDrawerProps) {
if (evt.target.value) search(evt.target.value);
else resetSearch();
},
[search, resetSearch]
[search, resetSearch],
),
{ wait: 200 }
{ wait: 200 },
);
const handleMemberClick: MouseEventHandler<HTMLButtonElement> = (evt) => {
@@ -257,7 +274,7 @@ export function MembersDrawer({ room, members }: MembersDrawerProps) {
onClick={
((evt) =>
setAnchor(
evt.currentTarget.getBoundingClientRect()
evt.currentTarget.getBoundingClientRect(),
)) as MouseEventHandler<HTMLButtonElement>
}
variant="Background"
@@ -289,7 +306,7 @@ export function MembersDrawer({ room, members }: MembersDrawerProps) {
onClick={
((evt) =>
setAnchor(
evt.currentTarget.getBoundingClientRect()
evt.currentTarget.getBoundingClientRect(),
)) as MouseEventHandler<HTMLButtonElement>
}
variant="Background"
@@ -402,7 +419,7 @@ export function MembersDrawer({ room, members }: MembersDrawerProps) {
onClick={handleMemberClick}
pressed={openProfileUserId === tagOrMember.userId}
typing={typingMembers.some(
(receipt) => receipt.userId === tagOrMember.userId
(receipt) => receipt.userId === tagOrMember.userId,
)}
/>
</div>
+4 -5
View File
@@ -1,9 +1,9 @@
import React, { useCallback, useEffect, useMemo, useState } from 'react';
import { Box, Button, Line, Text, config } from 'folds';
import { decodeRouteParam } from '../../pages/pathUtils';
import { useParams } from 'react-router-dom';
import { isKeyHotkey } from 'is-hotkey';
import { useAtom, useSetAtom } from 'jotai';
import { decodeRouteParam } from '../../pages/pathUtils';
import { RoomView } from './RoomView';
import { MembersDrawer } from './MembersDrawer';
import { MediaDrawer } from './room-media-menu';
@@ -41,8 +41,7 @@ export function Room() {
const forumRoom = isForum(room);
const skinny = screenSize !== ScreenSize.Desktop;
const showMediaSolo = skinny && isMediaDrawer;
const showRightDrawer =
!skinny && (isPeopleDrawer || isMediaDrawer);
const showRightDrawer = !skinny && (isPeopleDrawer || isMediaDrawer);
const uiEvent = useStateEvent(room, StateEvent.PaarrotUi);
const hasAppUi = useMemo(() => !!parsePaarrotUiContent(uiEvent?.getContent()), [uiEvent]);
@@ -68,8 +67,8 @@ export function Room() {
markAsRead(room.roomId, hideActivity);
}
},
[markAsRead, room.roomId, hideActivity]
)
[markAsRead, room.roomId, hideActivity],
),
);
return (
+73 -37
View File
@@ -11,7 +11,21 @@ import { useAtom, useAtomValue } from 'jotai';
import { isKeyHotkey } from 'is-hotkey';
import { EventType, IContent, MsgType, RelationType, Room } from 'matrix-js-sdk';
import { Transforms, Editor } from 'slate';
import { Box, Dialog, IconButton, Line, Overlay, OverlayBackdrop, OverlayCenter, PopOut, Scroll, Text, color, config, toRem } from 'folds';
import {
Box,
Dialog,
IconButton,
Line,
Overlay,
OverlayBackdrop,
OverlayCenter,
PopOut,
Scroll,
Text,
color,
config,
toRem,
} from 'folds';
import { Icon, Icons } from '../../components/icons';
import { useMatrixClient } from '../../hooks/useMatrixClient';
@@ -43,12 +57,7 @@ import {
} from '../../components/editor';
import { EmojiBoard, EmojiBoardTab } from '../../components/emoji-board';
import { UseStateProvider } from '../../components/UseStateProvider';
import {
TUploadContent,
getImageInfo,
getMxIdLocalPart,
mxcUrlToHttp,
} from '../../utils/matrix';
import { TUploadContent, getImageInfo, getMxIdLocalPart, mxcUrlToHttp } from '../../utils/matrix';
import { useTypingStatusUpdater } from '../../hooks/useTypingStatusUpdater';
import { useFilePicker } from '../../hooks/useFilePicker';
import { useFilePasteHandler } from '../../hooks/useFilePasteHandler';
@@ -85,7 +94,12 @@ import {
getImageMsgContent,
getVideoMsgContent,
} from './msgContent';
import { getMemberDisplayName, getMentionContent, trimReplyFromBody } from '../../utils/room';
import {
getMemberDisplayName,
getMentionContent,
trimReplyFromBody,
getMemberAvatarMxc,
} from '../../utils/room';
import { CommandAutocomplete } from './CommandAutocomplete';
import { Command, SHRUG, TABLEFLIP, UNFLIP, useCommands } from '../../hooks/useCommands';
import { pluginRegistry } from '../settings/plugins/PluginAPI';
@@ -105,7 +119,6 @@ import { useRoomCreatorsTag } from '../../hooks/useRoomCreatorsTag';
import { usePowerLevelTags } from '../../hooks/usePowerLevelTags';
import { useComposingCheck } from '../../hooks/useComposingCheck';
import { useOtherUserColor } from '../../hooks/useUserColor';
import { getMemberAvatarMxc } from '../../utils/room';
import { convertEmoticons, convertEmoticonsInHtml } from '../../utils/emoticonConverter';
import * as css from './RoomInput.css';
@@ -151,7 +164,7 @@ export const RoomInput = forwardRef<HTMLDivElement, RoomInputProps>(
replyPreviewHighlightClassName,
onMessageSent,
},
ref
ref,
) => {
const mx = useMatrixClient();
const useAuthentication = useMediaAuthentication();
@@ -179,7 +192,7 @@ export const RoomInput = forwardRef<HTMLDivElement, RoomInputProps>(
const accessibleTagColors = useAccessiblePowerTagColors(
theme.kind,
creatorsTag,
powerLevelTags
powerLevelTags,
);
// Get custom user color from avatar metadata
@@ -191,13 +204,14 @@ export const RoomInput = forwardRef<HTMLDivElement, RoomInputProps>(
: undefined;
// Priority: custom user color > legacy/direct colorMXID > tag color
const replyUsernameColor =
replyCustomColor ?? (legacyUsernameColor || direct ? colorMXID(replyUserID ?? '') : replyPowerColor);
replyCustomColor ??
(legacyUsernameColor || direct ? colorMXID(replyUserID ?? '') : replyPowerColor);
const [uploadBoard, setUploadBoard] = useState(true);
const [selectedFiles, setSelectedFiles] = useAtom(roomIdToUploadItemsAtomFamily(roomId));
const uploadFamilyObserverAtom = createUploadFamilyObserverAtom(
roomUploadAtomFamily,
selectedFiles.map((f) => f.file)
selectedFiles.map((f) => f.file),
);
const uploadBoardHandlers = useRef<UploadBoardImperativeHandlers>();
const editorRef = useRef<HTMLDivElement>(null);
@@ -218,7 +232,9 @@ export const RoomInput = forwardRef<HTMLDivElement, RoomInputProps>(
useEffect(() => {
setCommandValidator((commandName: string) => {
const isBuiltInCommand = commands[commandName as Command];
const isPluginCommand = pluginRegistry.getCommands().some(cmd => cmd.name === commandName);
const isPluginCommand = pluginRegistry
.getCommands()
.some((cmd) => cmd.name === commandName);
return !!(isBuiltInCommand || isPluginCommand);
});
}, [commands]);
@@ -229,7 +245,7 @@ export const RoomInput = forwardRef<HTMLDivElement, RoomInputProps>(
setUploadBoard(true);
await enqueueFiles(files);
},
[enqueueFiles]
[enqueueFiles],
);
const pickFile = useFilePicker(handleFiles, true);
const handlePaste = useFilePasteHandler(handleFiles);
@@ -252,7 +268,7 @@ export const RoomInput = forwardRef<HTMLDivElement, RoomInputProps>(
resetEditor(editor);
resetEditorHistory(editor);
},
[roomId, editor, setMsgDraft]
[roomId, editor, setMsgDraft],
);
const handleFileMetadata = useCallback(
@@ -263,7 +279,7 @@ export const RoomInput = forwardRef<HTMLDivElement, RoomInputProps>(
replacement: { ...fileItem, metadata },
});
},
[setSelectedFiles]
[setSelectedFiles],
);
const handleRemoveUpload = useCallback(
@@ -275,7 +291,7 @@ export const RoomInput = forwardRef<HTMLDivElement, RoomInputProps>(
});
uploads.forEach((u) => roomUploadAtomFamily.remove(u));
},
[setSelectedFiles, selectedFiles]
[setSelectedFiles, selectedFiles],
);
const handleCancelUpload = (uploads: Upload[]) => {
@@ -294,7 +310,7 @@ export const RoomInput = forwardRef<HTMLDivElement, RoomInputProps>(
});
const carouselUuid = imageUploads.length > 1 ? createCarouselUuid() : undefined;
const imageUploadIndexByFile = new Map(
imageUploads.map((upload, index) => [upload.file, index] as const)
imageUploads.map((upload, index) => [upload.file, index] as const),
);
const contentsPromises = uploads.map(async (upload) => {
@@ -314,7 +330,7 @@ export const RoomInput = forwardRef<HTMLDivElement, RoomInputProps>(
index: imageIndex,
total: imageUploads.length,
}
: undefined
: undefined,
);
}
if (fileItem.file.type.startsWith('video')) {
@@ -340,7 +356,7 @@ export const RoomInput = forwardRef<HTMLDivElement, RoomInputProps>(
allowTextFormatting: true,
allowBlockMarkdown: isMarkdown,
allowInlineMarkdown: isMarkdown,
})
}),
);
let msgType = MsgType.Text;
@@ -351,8 +367,10 @@ export const RoomInput = forwardRef<HTMLDivElement, RoomInputProps>(
const potentialCommand = match[1];
// Check if it's a valid command (built-in or plugin)
const isBuiltInCommand = commands[potentialCommand as Command];
const isPluginCommand = pluginRegistry.getCommands().some(cmd => cmd.name === potentialCommand);
const isPluginCommand = pluginRegistry
.getCommands()
.some((cmd) => cmd.name === potentialCommand);
if (isBuiltInCommand || isPluginCommand) {
commandName = potentialCommand;
}
@@ -459,7 +477,7 @@ export const RoomInput = forwardRef<HTMLDivElement, RoomInputProps>(
'm.in_reply_to': { event_id: inReplyToEventId },
};
}
// Process message through plugin interceptors
try {
const messageContext = {
@@ -470,7 +488,7 @@ export const RoomInput = forwardRef<HTMLDivElement, RoomInputProps>(
metadata: {},
};
const processedContext = await pluginRegistry.processBeforeSend(messageContext);
// Update content with intercepted values
content.body = processedContext.content;
if (processedContext.formatted) {
@@ -479,7 +497,7 @@ export const RoomInput = forwardRef<HTMLDivElement, RoomInputProps>(
} catch (err) {
console.error('[RoomInput] Plugin interceptor error:', err);
}
mx.sendMessage(roomId, content as any);
resetEditor(editor);
resetEditorHistory(editor);
@@ -487,7 +505,20 @@ export const RoomInput = forwardRef<HTMLDivElement, RoomInputProps>(
setCommandHint(undefined);
sendTypingStatus(false);
onMessageSent?.();
}, [mx, roomId, threadRootId, threadReplyToEventId, editor, replyDraft, sendTypingStatus, setReplyDraft, isMarkdown, commands, autoConvertEmoticons, onMessageSent]);
}, [
mx,
roomId,
threadRootId,
threadReplyToEventId,
editor,
replyDraft,
sendTypingStatus,
setReplyDraft,
isMarkdown,
commands,
autoConvertEmoticons,
onMessageSent,
]);
const handleKeyDown: KeyboardEventHandler = useCallback(
(evt) => {
@@ -511,7 +542,7 @@ export const RoomInput = forwardRef<HTMLDivElement, RoomInputProps>(
setReplyDraft(undefined);
}
},
[submit, setReplyDraft, enterForNewline, autocompleteQuery, isComposing, commandHint]
[submit, setReplyDraft, enterForNewline, autocompleteQuery, isComposing, commandHint],
);
const handleKeyUp: KeyboardEventHandler = useCallback(
@@ -534,12 +565,12 @@ export const RoomInput = forwardRef<HTMLDivElement, RoomInputProps>(
// Check if user is typing a command and show hint
const plainText = toPlainText(editor.children, false).trim();
const commandMatch = plainText.match(/^\/(\w+)(\s|$)/);
if (commandMatch) {
const commandName = commandMatch[1];
const builtInCmd = commands[commandName as Command];
const pluginCmd = pluginRegistry.getCommands().find(cmd => cmd.name === commandName);
const pluginCmd = pluginRegistry.getCommands().find((cmd) => cmd.name === commandName);
if (builtInCmd) {
setCommandHint({
command: commandName,
@@ -558,7 +589,7 @@ export const RoomInput = forwardRef<HTMLDivElement, RoomInputProps>(
setCommandHint(undefined);
}
},
[editor, sendTypingStatus, hideActivity, commands]
[editor, sendTypingStatus, hideActivity, commands],
);
const handleCloseAutocomplete = useCallback(() => {
@@ -577,7 +608,7 @@ export const RoomInput = forwardRef<HTMLDivElement, RoomInputProps>(
const info = await getImageInfo(
await loadImageElement(stickerUrl),
await getImageUrlBlob(stickerUrl)
await getImageUrlBlob(stickerUrl),
);
mx.sendEvent(roomId, EventType.Sticker, {
@@ -705,7 +736,10 @@ export const RoomInput = forwardRef<HTMLDivElement, RoomInputProps>(
<Text size="T200" priority="400">
<b>/{commandHint.command}</b>
{commandHint.args && commandHint.args.length > 0 && (
<span style={{ opacity: 0.6 }}> {commandHint.args.map(arg => `[${arg}]`).join(' ')}</span>
<span style={{ opacity: 0.6 }}>
{' '}
{commandHint.args.map((arg) => `[${arg}]`).join(' ')}
</span>
)}
</Text>
{commandHint.description && (
@@ -738,7 +772,9 @@ export const RoomInput = forwardRef<HTMLDivElement, RoomInputProps>(
className={replyPreviewHighlightClassName}
>
{!hideReplyThreadIndicator &&
replyDraft.relation?.rel_type === RelationType.Thread && <ThreadIndicator />}
replyDraft.relation?.rel_type === RelationType.Thread && (
<ThreadIndicator />
)}
<ReplyLayout
userColor={replyUsernameColor}
username={
@@ -794,7 +830,7 @@ export const RoomInput = forwardRef<HTMLDivElement, RoomInputProps>(
anchor={
emojiBoardTab === undefined
? undefined
: emojiBtnRef.current?.getBoundingClientRect() ?? undefined
: (emojiBtnRef.current?.getBoundingClientRect() ?? undefined)
}
content={
<EmojiBoard
@@ -851,5 +887,5 @@ export const RoomInput = forwardRef<HTMLDivElement, RoomInputProps>(
/>
</div>
);
}
},
);
@@ -7,5 +7,5 @@ import * as css from './RoomInputPlaceholder.css';
export const RoomInputPlaceholder = as<'div', ComponentProps<typeof Box>>(
({ className, ...props }, ref) => (
<Box className={classNames(css.RoomInputPlaceholder, className)} {...props} ref={ref} />
)
),
);
+198 -142
View File
@@ -30,12 +30,25 @@ import { ReactEditor } from 'slate-react';
import { Editor } from 'slate';
import to from 'await-to-js';
import { useAtomValue, useSetAtom } from 'jotai';
import { Badge, Box, Chip, ContainerColor, IconButton, Line, Scroll, Text, as, color, config, toRem } from 'folds';
import { Icon, Icons } from '../../components/icons';
import {
Badge,
Box,
Chip,
ContainerColor,
IconButton,
Line,
Scroll,
Text,
as,
color,
config,
toRem,
} from 'folds';
import { isKeyHotkey } from 'is-hotkey';
import { Opts as LinkifyOpts } from 'linkifyjs';
import { useTranslation } from 'react-i18next';
import { useLocation } from 'react-router-dom';
import { Icon, Icons } from '../../components/icons';
import { eventWithShortcode, factoryEventSentBy, getMxIdLocalPart } from '../../utils/matrix';
import { useMatrixClient } from '../../hooks/useMatrixClient';
import { useVirtualPaginator, ItemRange } from '../../hooks/useVirtualPaginator';
@@ -196,7 +209,7 @@ const TimelineFloat = as<'div', css.TimelineFloatVariants>(
{...props}
ref={ref}
/>
)
),
);
const TimelineDivider = as<'div', { variant?: ContainerColor | 'Inherit' }>(
@@ -206,7 +219,7 @@ const TimelineDivider = as<'div', { variant?: ContainerColor | 'Inherit' }>(
{children}
<Line style={{ flexGrow: 1 }} variant={variant} size="300" />
</Box>
)
),
);
type CarouselScrollerProps = {
@@ -294,7 +307,7 @@ export const getEventTimeline = (room: Room, eventId: string): EventTimeline | u
export const getFirstLinkedTimeline = (
timeline: EventTimeline,
direction: Direction
direction: Direction,
): EventTimeline => {
const linkedTm = timeline.getNeighbouringTimeline(direction);
if (!linkedTm) return timeline;
@@ -324,7 +337,7 @@ export const getTimelinesEventsCount = (timelines: EventTimeline[]): number => {
export const getTimelineAndBaseIndex = (
timelines: EventTimeline[],
index: number
index: number,
): [EventTimeline | undefined, number] => {
let uptoTimelineLen = 0;
const timeline = timelines.find((t) => {
@@ -345,7 +358,7 @@ export const getTimelineEvent = (timeline: EventTimeline, index: number): Matrix
export const getEventIdAbsoluteIndex = (
timelines: EventTimeline[],
eventTimeline: EventTimeline,
eventId: string
eventId: string,
): number | undefined => {
const timelineIndex = timelines.findIndex((t) => t === eventTimeline);
if (timelineIndex === -1) return undefined;
@@ -375,12 +388,12 @@ const useEventTimelineLoader = (
mx: MatrixClient,
room: Room,
onLoad: (eventId: string, linkedTimelines: EventTimeline[], evtAbsIndex: number) => void,
onError: (err: Error | null) => void
onError: (err: Error | null) => void,
) => {
const loadEventTimeline = useCallback(
async (eventId: string) => {
const [err, replyEvtTimeline] = await to(
mx.getEventTimeline(room.getUnfilteredTimelineSet(), eventId)
mx.getEventTimeline(room.getUnfilteredTimelineSet(), eventId),
);
if (!replyEvtTimeline) {
onError(err ?? null);
@@ -396,7 +409,7 @@ const useEventTimelineLoader = (
onLoad(eventId, linkedTimelines, absIndex);
},
[mx, room, onLoad, onError]
[mx, room, onLoad, onError],
);
return loadEventTimeline;
@@ -406,7 +419,7 @@ const useTimelinePagination = (
mx: MatrixClient,
timeline: Timeline,
setTimeline: Dispatch<SetStateAction<Timeline>>,
limit: number
limit: number,
) => {
const timelineRef = useRef(timeline);
timelineRef.current = timeline;
@@ -418,7 +431,7 @@ const useTimelinePagination = (
const recalibratePagination = (
linkedTimelines: EventTimeline[],
timelinesEventsCount: number[],
backwards: boolean
backwards: boolean,
) => {
const topTimeline = linkedTimelines[0];
const timelineMatch = (mt: EventTimeline) => (t: EventTimeline) => t === mt;
@@ -452,7 +465,7 @@ const useTimelinePagination = (
if (!timelineToPaginate) return;
const paginationToken = timelineToPaginate.getPaginationToken(
backwards ? Direction.Backward : Direction.Forward
backwards ? Direction.Backward : Direction.Forward,
);
if (
!paginationToken &&
@@ -468,7 +481,7 @@ const useTimelinePagination = (
mx.paginateEventTimeline(timelineToPaginate, {
backwards,
limit,
})
}),
);
if (err) {
// TODO: handle pagination error.
@@ -476,7 +489,7 @@ const useTimelinePagination = (
}
const fetchedTimeline =
timelineToPaginate.getNeighbouringTimeline(
backwards ? Direction.Backward : Direction.Forward
backwards ? Direction.Backward : Direction.Forward,
) ?? timelineToPaginate;
// Decrypt all event ahead of render cycle
const roomId = fetchedTimeline.getRoomId();
@@ -502,7 +515,7 @@ const useLiveEventArrive = (room: Room, onArrive: (mEvent: MatrixEvent) => void)
eventRoom,
toStartOfTimeline,
removed,
data
data,
) => {
if (eventRoom?.roomId !== room.roomId || !data.liveEvent) return;
onArrive(mEvent);
@@ -572,12 +585,12 @@ export function RoomTimeline({ room, eventId, roomInputRef, editor }: RoomTimeli
const [messageSpacing] = useSetting(settingsAtom, 'messageSpacing');
const [legacyUsernameColor] = useSetting(settingsAtom, 'legacyUsernameColor');
const direct = useIsDirectRoom();
const dmUserId = direct ? room.guessDMUserId() ?? undefined : undefined;
const dmUserId = direct ? (room.guessDMUserId() ?? undefined) : undefined;
const [timelineHovered, setTimelineHovered] = useState(false);
const { assetUrls: dmAssetUrls } = useOtherUserCollectibles(dmUserId ?? '');
const dmNameplateUrl = pickNameplateUrl(dmAssetUrls);
const dmNameplateIsVideo = Boolean(
dmAssetUrls['nameplate:animated'] || dmAssetUrls['nameplate:asset.webm']
dmAssetUrls['nameplate:animated'] || dmAssetUrls['nameplate:asset.webm'],
);
const [hideMembershipEvents] = useSetting(settingsAtom, 'hideMembershipEvents');
const [hideNickAvatarEvents] = useSetting(settingsAtom, 'hideNickAvatarEvents');
@@ -589,12 +602,15 @@ export function RoomTimeline({ room, eventId, roomInputRef, editor }: RoomTimeli
const roomWideEmbedFilters = useRoomWideEmbedFilters(room);
const combinedEmbedFilters = useMemo(
() => combineEmbedFilters(personalEmbedFilters, roomWideEmbedFilters),
[personalEmbedFilters, roomWideEmbedFilters]
[personalEmbedFilters, roomWideEmbedFilters],
);
const [showHiddenEvents] = useSetting(settingsAtom, 'showHiddenEvents');
const [showDeveloperTools] = useSetting(settingsAtom, 'developerTools');
const { bursts: emojiConfettiBursts, removeBurst: removeEmojiConfettiBurst, handleJumboEmojiClick } =
useJumboEmojiConfetti(room);
const {
bursts: emojiConfettiBursts,
removeBurst: removeEmojiConfettiBurst,
handleJumboEmojiClick,
} = useJumboEmojiConfetti(room);
const [hour24Clock] = useSetting(settingsAtom, 'hour24Clock');
const [dateFormatString] = useSetting(settingsAtom, 'dateFormatString');
@@ -619,7 +635,7 @@ export function RoomTimeline({ room, eventId, roomInputRef, editor }: RoomTimeli
const accessiblePowerTagColors = useAccessiblePowerTagColors(
theme.kind,
creatorsTag,
powerLevelTags
powerLevelTags,
);
const permissions = useRoomPermissions(creators, powerLevels);
@@ -641,13 +657,13 @@ export function RoomTimeline({ room, eventId, roomInputRef, editor }: RoomTimeli
const scrollToLatest = (location.state as { scrollToLatest?: boolean } | null)?.scrollToLatest;
const savedScrollRef = useRef(
eventId || scrollToLatest ? undefined : getRoomScrollState(room.roomId)
eventId || scrollToLatest ? undefined : getRoomScrollState(room.roomId),
);
const imagePackRooms: Room[] = useImagePackRooms(room.roomId, roomToParents);
const [unreadInfo, setUnreadInfo] = useState(() =>
getRoomUnreadInfo(room, scrollToLatestBehavior !== ScrollToLatestBehavior.Always)
getRoomUnreadInfo(room, scrollToLatestBehavior !== ScrollToLatestBehavior.Always),
);
const readUptoEventIdRef = useRef<string>();
if (unreadInfo) {
@@ -655,9 +671,7 @@ export function RoomTimeline({ room, eventId, roomInputRef, editor }: RoomTimeli
}
const atBottomAnchorRef = useRef<HTMLElement>(null);
const [atBottom, setAtBottom] = useState<boolean>(
() => savedScrollRef.current?.atBottom ?? true
);
const [atBottom, setAtBottom] = useState<boolean>(() => savedScrollRef.current?.atBottom ?? true);
const atBottomRef = useRef(atBottom);
atBottomRef.current = atBottom;
@@ -666,7 +680,7 @@ export function RoomTimeline({ room, eventId, roomInputRef, editor }: RoomTimeli
content: string;
} | null>(null);
const [returnToEventId, setReturnToEventIdState] = useState<string | null>(
() => getRoomReturnAnchor(room.roomId) ?? null
() => getRoomReturnAnchor(room.roomId) ?? null,
);
const setReturnToEventId = useCallback(
@@ -675,7 +689,7 @@ export function RoomTimeline({ room, eventId, roomInputRef, editor }: RoomTimeli
else clearRoomReturnAnchor(room.roomId);
setReturnToEventIdState(eventId);
},
[room.roomId]
[room.roomId],
);
const scrollRef = useRef<HTMLDivElement>(null);
@@ -727,10 +741,10 @@ export function RoomTimeline({ room, eventId, roomInputRef, editor }: RoomTimeli
() => ({
...LINKIFY_OPTS,
render: factoryRenderLinkifyWithMention((href) =>
renderMatrixMention(mx, room.roomId, href, makeMentionCustomProps(mentionClickHandler))
renderMatrixMention(mx, room.roomId, href, makeMentionCustomProps(mentionClickHandler)),
),
}),
[mx, room, mentionClickHandler]
[mx, room, mentionClickHandler],
);
const htmlReactParserOptions = useMemo<HTMLReactParserOptions>(
() =>
@@ -740,7 +754,7 @@ export function RoomTimeline({ room, eventId, roomInputRef, editor }: RoomTimeli
handleSpoilerClick: spoilerClickHandler,
handleMentionClick: mentionClickHandler,
}),
[mx, room, linkifyOpts, spoilerClickHandler, mentionClickHandler, useAuthentication]
[mx, room, linkifyOpts, spoilerClickHandler, mentionClickHandler, useAuthentication],
);
const parseMemberEvent = useMemberEventParser();
@@ -776,15 +790,14 @@ export function RoomTimeline({ room, eventId, roomInputRef, editor }: RoomTimeli
const scrollEl = scrollRef.current;
if (!scrollEl) return;
const distanceFromBottom =
scrollEl.scrollHeight - scrollEl.scrollTop - scrollEl.clientHeight;
const distanceFromBottom = scrollEl.scrollHeight - scrollEl.scrollTop - scrollEl.clientHeight;
saveRoomScrollState(roomId, {
top: scrollEl.scrollTop,
atBottom: distanceFromBottom <= 50,
range: timelineRef.current.range,
});
},
[eventId]
[eventId],
);
const eventsLength = getTimelinesEventsCount(timeline.linkedTimelines);
@@ -815,7 +828,7 @@ export function RoomTimeline({ room, eventId, roomInputRef, editor }: RoomTimeli
mx,
timeline,
setTimeline,
PAGINATION_LIMIT
PAGINATION_LIMIT,
);
const getScrollElement = useCallback(() => scrollRef.current, []);
@@ -831,7 +844,7 @@ export function RoomTimeline({ room, eventId, roomInputRef, editor }: RoomTimeli
(index: number) =>
(scrollRef.current?.querySelector(`[data-message-item="${index}"]`) as HTMLElement) ??
undefined,
[]
[],
),
onEnd: handleTimelinePagination,
});
@@ -857,7 +870,7 @@ export function RoomTimeline({ room, eventId, roomInputRef, editor }: RoomTimeli
},
});
},
[alive]
[alive],
),
useCallback(() => {
if (!alive()) return;
@@ -865,7 +878,7 @@ export function RoomTimeline({ room, eventId, roomInputRef, editor }: RoomTimeli
scrollToBottomRef.current.count += 1;
scrollToBottomRef.current.smooth = false;
scrollToBottomRef.current.force = true;
}, [alive, room])
}, [alive, room]),
);
useLiveEventArrive(
@@ -890,7 +903,7 @@ export function RoomTimeline({ room, eventId, roomInputRef, editor }: RoomTimeli
// Handle own messages and focus
if (isOwnMessage) {
setLatestUnreadMessage(null);
if (document.hasFocus() && (!unreadInfo)) {
if (document.hasFocus() && !unreadInfo) {
const roomId = mEvt.getRoomId();
if (roomId) {
requestAnimationFrame(() => markAsRead(roomId, hideActivity));
@@ -898,8 +911,7 @@ export function RoomTimeline({ room, eventId, roomInputRef, editor }: RoomTimeli
}
// Sending while scrolled up jumps to latest — offer return to previous spot
if (wasAwayFromBottom && isBottomPinnedEvent) {
const anchorEventId =
eventId ?? getViewportAnchorEventId() ?? getRangeCenterEventId();
const anchorEventId = eventId ?? getViewportAnchorEventId() ?? getRangeCenterEventId();
if (anchorEventId) {
setReturnToEventId(anchorEventId);
}
@@ -930,15 +942,25 @@ export function RoomTimeline({ room, eventId, roomInputRef, editor }: RoomTimeli
});
}
},
[mx, room, unreadInfo, hideActivity, markAsRead, eventId, getViewportAnchorEventId, getRangeCenterEventId, setReturnToEventId]
)
[
mx,
room,
unreadInfo,
hideActivity,
markAsRead,
eventId,
getViewportAnchorEventId,
getRangeCenterEventId,
setReturnToEventId,
],
),
);
const handleOpenEvent = useCallback(
async (
evtId: string,
highlight = true,
onScroll: ((scrolled: boolean) => void) | undefined = undefined
onScroll: ((scrolled: boolean) => void) | undefined = undefined,
) => {
const evtTimeline = getEventTimeline(room, evtId);
const absoluteIndex =
@@ -961,7 +983,7 @@ export function RoomTimeline({ room, eventId, roomInputRef, editor }: RoomTimeli
loadEventTimeline(evtId);
}
},
[room, timeline, scrollToItem, loadEventTimeline]
[room, timeline, scrollToItem, loadEventTimeline],
);
useLiveTimelineRefresh(
@@ -970,7 +992,7 @@ export function RoomTimeline({ room, eventId, roomInputRef, editor }: RoomTimeli
if (liveTimelineLinked) {
setTimeline(getInitialTimeline(room));
}
}, [room, liveTimelineLinked])
}, [room, liveTimelineLinked]),
);
// Stay at bottom when room editor resize
@@ -995,41 +1017,48 @@ export function RoomTimeline({ room, eventId, roomInputRef, editor }: RoomTimeli
}
};
}, [getScrollElement, roomInputRef]),
useCallback(() => roomInputRef.current, [roomInputRef])
useCallback(() => roomInputRef.current, [roomInputRef]),
);
useResizeObserver(
useCallback((entries) => {
const timelineContent = timelineContentRef.current;
const scrollElement = getScrollElement();
if (!timelineContent || !scrollElement) return;
useCallback(
(entries) => {
const timelineContent = timelineContentRef.current;
const scrollElement = getScrollElement();
if (!timelineContent || !scrollElement) return;
const timelineEntry = getResizeObserverEntry(timelineContent, entries);
if (!timelineEntry) return;
const timelineEntry = getResizeObserverEntry(timelineContent, entries);
if (!timelineEntry) return;
const nextHeight = timelineEntry.contentRect.height;
const previousHeight = timelineContentHeightRef.current;
timelineContentHeightRef.current = nextHeight;
const nextHeight = timelineEntry.contentRect.height;
const previousHeight = timelineContentHeightRef.current;
timelineContentHeightRef.current = nextHeight;
if (restoringScrollRef.current) {
const saved = savedScrollRef.current;
if (saved) {
if (saved.atBottom) {
scrollElement.scrollTop = scrollElement.scrollHeight;
} else {
scrollElement.scrollTop = saved.top;
if (restoringScrollRef.current) {
const saved = savedScrollRef.current;
if (saved) {
if (saved.atBottom) {
scrollElement.scrollTop = scrollElement.scrollHeight;
} else {
scrollElement.scrollTop = saved.top;
}
}
return;
}
return;
}
if (previousHeight === 0 || nextHeight <= previousHeight || !isScrolledToBottom(scrollElement)) {
return;
}
if (
previousHeight === 0 ||
nextHeight <= previousHeight ||
!isScrolledToBottom(scrollElement)
) {
return;
}
autoScrollToBottom(scrollElement, false, true);
}, [getScrollElement]),
useCallback(() => timelineContentRef.current, [])
autoScrollToBottom(scrollElement, false, true);
},
[getScrollElement],
),
useCallback(() => timelineContentRef.current, []),
);
const tryAutoMarkAsRead = useCallback(() => {
@@ -1070,16 +1099,16 @@ export function RoomTimeline({ room, eventId, roomInputRef, editor }: RoomTimeli
tryAutoMarkAsRead();
}
},
[tryAutoMarkAsRead]
[tryAutoMarkAsRead],
),
useCallback(
() => ({
root: getScrollElement(),
rootMargin: '100px',
}),
[getScrollElement]
[getScrollElement],
),
useCallback(() => atBottomAnchorRef.current, [])
useCallback(() => atBottomAnchorRef.current, []),
);
useDocumentFocusChange(
@@ -1099,8 +1128,8 @@ export function RoomTimeline({ room, eventId, roomInputRef, editor }: RoomTimeli
tryAutoMarkAsRead();
}
},
[tryAutoMarkAsRead, unreadInfo, handleOpenEvent]
)
[tryAutoMarkAsRead, unreadInfo, handleOpenEvent],
),
);
// Handle up arrow edit
@@ -1115,7 +1144,7 @@ export function RoomTimeline({ room, eventId, roomInputRef, editor }: RoomTimeli
isEmptyEditor(editor)
) {
const editableEvt = getLatestEditableEvt(room.getLiveTimeline(), (mEvt) =>
canEditEvent(mx, mEvt)
canEditEvent(mx, mEvt),
);
const editableEvtId = editableEvt?.getId();
if (!editableEvtId) return;
@@ -1123,8 +1152,8 @@ export function RoomTimeline({ room, eventId, roomInputRef, editor }: RoomTimeli
evt.preventDefault();
}
},
[mx, room, editor]
)
[mx, room, editor],
),
);
useEffect(() => {
@@ -1154,7 +1183,7 @@ export function RoomTimeline({ room, eventId, roomInputRef, editor }: RoomTimeli
// Remember scroll position when leaving a room (switch DM, nav away, etc.).
useLayoutEffect(() => {
const roomId = room.roomId;
const { roomId } = room;
return () => {
persistTimelineScroll(roomId);
};
@@ -1165,7 +1194,7 @@ export function RoomTimeline({ room, eventId, roomInputRef, editor }: RoomTimeli
const scrollEl = scrollRef.current;
if (!scrollEl || eventId) return undefined;
const roomId = room.roomId;
const { roomId } = room;
let raf = 0;
const onScroll = () => {
if (restoringScrollRef.current) return;
@@ -1282,7 +1311,7 @@ export function RoomTimeline({ room, eventId, roomInputRef, editor }: RoomTimeli
autoScrollToBottom(
scrollEl,
scrollToBottomRef.current.smooth,
scrollToBottomRef.current.force
scrollToBottomRef.current.force,
);
if (atLiveEndRef.current) {
setAtBottom(true);
@@ -1322,10 +1351,11 @@ export function RoomTimeline({ room, eventId, roomInputRef, editor }: RoomTimeli
if (!evtTimeline) return null;
const mEvent = evtTimeline.getEvents().find((e) => e.getId() === eventId);
if (!mEvent) return null;
const sender = getMemberDisplayName(room, mEvent.getSender() ?? '')
?? getMxIdLocalPart(mEvent.getSender() ?? '')
?? mEvent.getSender()
?? 'Unknown';
const sender =
getMemberDisplayName(room, mEvent.getSender() ?? '') ??
getMxIdLocalPart(mEvent.getSender() ?? '') ??
mEvent.getSender() ??
'Unknown';
const content = mEvent.getContent().body ?? '';
return {
sender,
@@ -1337,8 +1367,7 @@ export function RoomTimeline({ room, eventId, roomInputRef, editor }: RoomTimeli
}, [room, hour24Clock]);
const handleJumpToLatest = () => {
const anchorEventId =
eventId ?? getViewportAnchorEventId() ?? getRangeCenterEventId();
const anchorEventId = eventId ?? getViewportAnchorEventId() ?? getRangeCenterEventId();
if (anchorEventId) {
setReturnToEventId(anchorEventId);
}
@@ -1399,7 +1428,7 @@ export function RoomTimeline({ room, eventId, roomInputRef, editor }: RoomTimeli
if (!targetId) return;
handleOpenEvent(targetId);
},
[handleOpenEvent]
[handleOpenEvent],
);
const handleUserClick: MouseEventHandler<HTMLButtonElement> = useCallback(
@@ -1415,10 +1444,10 @@ export function RoomTimeline({ room, eventId, roomInputRef, editor }: RoomTimeli
room.roomId,
space?.roomId,
userId,
evt.currentTarget.getBoundingClientRect()
evt.currentTarget.getBoundingClientRect(),
);
},
[room, space, openUserRoomProfile]
[room, space, openUserRoomProfile],
);
const handleUsernameClick: MouseEventHandler<HTMLButtonElement> = useCallback(
(evt) => {
@@ -1433,13 +1462,13 @@ export function RoomTimeline({ room, eventId, roomInputRef, editor }: RoomTimeli
createMentionElement(
userId,
name.startsWith('@') ? name : `@${name}`,
userId === mx.getUserId()
)
userId === mx.getUserId(),
),
);
ReactEditor.focus(editor);
moveCursor(editor);
},
[mx, room, editor]
[mx, room, editor],
);
const handleReplyClick: MouseEventHandler<HTMLButtonElement> = useCallback(
@@ -1472,7 +1501,7 @@ export function RoomTimeline({ room, eventId, roomInputRef, editor }: RoomTimeli
setActiveThreadId(replyId);
}
},
[room, setReplyDraft, setActiveThreadId, editor]
[room, setReplyDraft, setActiveThreadId, editor],
);
/** Opens the thread view for the given thread root event ID. */
@@ -1480,7 +1509,7 @@ export function RoomTimeline({ room, eventId, roomInputRef, editor }: RoomTimeli
(threadRootId: string) => {
setActiveThreadId(threadRootId);
},
[setActiveThreadId]
[setActiveThreadId],
);
const handleReactionToggle = useCallback(
@@ -1501,10 +1530,10 @@ export function RoomTimeline({ room, eventId, roomInputRef, editor }: RoomTimeli
mx.sendEvent(
room.roomId,
MessageEvent.Reaction as any,
getReactionContent(targetEventId, key, rShortcode)
getReactionContent(targetEventId, key, rShortcode),
);
},
[mx, room]
[mx, room],
);
const handleEdit = useCallback(
(editEvtId?: string) => {
@@ -1515,7 +1544,7 @@ export function RoomTimeline({ room, eventId, roomInputRef, editor }: RoomTimeli
setEditId(undefined);
ReactEditor.focus(editor);
},
[editor]
[editor],
);
const { t } = useTranslation();
@@ -1984,23 +2013,29 @@ export function RoomTimeline({ room, eventId, roomInputRef, editor }: RoomTimeli
const senderName = getMemberDisplayName(room, senderId) || getMxIdLocalPart(senderId);
const content = mEvent.getContent();
const prevContent = mEvent.getPrevContent();
// Check current content for active devices
const calls = content['m.calls'];
const hasDevices = Array.isArray(calls) && calls.some((call: { 'm.devices'?: unknown[] }) =>
Array.isArray(call['m.devices']) && call['m.devices'].length > 0
);
const hasDevices =
Array.isArray(calls) &&
calls.some(
(call: { 'm.devices'?: unknown[] }) =>
Array.isArray(call['m.devices']) && call['m.devices'].length > 0,
);
// Check previous content for active devices
const prevCalls = prevContent['m.calls'];
const hadDevices = Array.isArray(prevCalls) && prevCalls.some((call: { 'm.devices'?: unknown[] }) =>
Array.isArray(call['m.devices']) && call['m.devices'].length > 0
);
const hadDevices =
Array.isArray(prevCalls) &&
prevCalls.some(
(call: { 'm.devices'?: unknown[] }) =>
Array.isArray(call['m.devices']) && call['m.devices'].length > 0,
);
// Determine if this is a join or leave
const isJoining = hasDevices && !hadDevices;
const isLeaving = !hasDevices && hadDevices;
// Skip if no change (refresh events or device updates within same call)
if (!isJoining && !isLeaving) return null;
@@ -2015,7 +2050,7 @@ export function RoomTimeline({ room, eventId, roomInputRef, editor }: RoomTimeli
mEventId,
mEvent,
});
// Return special marker for call event (will be handled by eventRenderer)
return 'CALL_EVENT_PENDING' as unknown as React.ReactNode;
},
@@ -2117,7 +2152,7 @@ export function RoomTimeline({ room, eventId, roomInputRef, editor }: RoomTimeli
/>
</Event>
);
}
},
);
let prevEvent: MatrixEvent | undefined;
@@ -2136,18 +2171,21 @@ export function RoomTimeline({ room, eventId, roomInputRef, editor }: RoomTimeli
if (callEvents.length === 0) return null;
// Group by user, tracking the sequence of actions to preserve order
const userActions = new Map<string, {
senderName: string;
firstAction: 'join' | 'leave';
lastAction: 'join' | 'leave';
joins: number;
leaves: number;
}>();
const userActions = new Map<
string,
{
senderName: string;
firstAction: 'join' | 'leave';
lastAction: 'join' | 'leave';
joins: number;
leaves: number;
}
>();
callEvents.forEach((evt) => {
const existing = userActions.get(evt.senderId);
const action = evt.isJoining ? 'join' : 'leave';
if (existing) {
existing.lastAction = action;
if (evt.isJoining) {
@@ -2171,7 +2209,7 @@ export function RoomTimeline({ room, eventId, roomInputRef, editor }: RoomTimeli
userActions.forEach((actions) => {
const { joins, leaves, senderName, firstAction, lastAction } = actions;
const total = joins + leaves;
if (total === 1) {
// Single action
summaryParts.push(`${senderName} ${firstAction === 'join' ? 'joined' : 'left'}`);
@@ -2180,14 +2218,18 @@ export function RoomTimeline({ room, eventId, roomInputRef, editor }: RoomTimeli
const startedWith = firstAction === 'join' ? 'joined' : 'left';
const opposite = firstAction === 'join' ? 'left' : 'joined';
const cycles = Math.min(joins, leaves);
if (firstAction === lastAction) {
// Ended on same action as started (odd number of same action)
// e.g., join-leave-join or leave-join-leave
if (cycles === 1) {
summaryParts.push(`${senderName} ${startedWith}, ${opposite}, then ${startedWith} again`);
summaryParts.push(
`${senderName} ${startedWith}, ${opposite}, then ${startedWith} again`,
);
} else {
summaryParts.push(`${senderName} ${startedWith} and ${opposite} ${cycles} times, then ${startedWith}`);
summaryParts.push(
`${senderName} ${startedWith} and ${opposite} ${cycles} times, then ${startedWith}`,
);
}
} else {
// Ended on opposite action (equal joins/leaves or started-opposite pattern)
@@ -2252,7 +2294,7 @@ export function RoomTimeline({ room, eventId, roomInputRef, editor }: RoomTimeli
mEvent: MatrixEvent,
item: number,
timelineSet: EventTimelineSet,
collapse: boolean
collapse: boolean,
): React.ReactNode => {
const reactionRelations = getEventReactions(timelineSet, mEventId);
const reactions = reactionRelations && reactionRelations.getSortedAnnotationsByKey();
@@ -2390,7 +2432,7 @@ export function RoomTimeline({ room, eventId, roomInputRef, editor }: RoomTimeli
minuteDifference(prevEvent.getTs(), mEvent.getTs()) < 2;
const getEventByItem = (
timelineItem: number
timelineItem: number,
): { event: MatrixEvent; eventId: string } | undefined => {
const [tm, bIndex] = getTimelineAndBaseIndex(timeline.linkedTimelines, timelineItem);
if (!tm) return undefined;
@@ -2443,7 +2485,14 @@ export function RoomTimeline({ room, eventId, roomInputRef, editor }: RoomTimeli
if (!reactionOrEditEvent(mEvent)) {
rawEventJSX =
carouselEvents.length > 1
? renderImageCarouselMessage(carouselEvents, mEventId, mEvent, item, timelineSet, collapsed)
? renderImageCarouselMessage(
carouselEvents,
mEventId,
mEvent,
item,
timelineSet,
collapsed,
)
: renderMatrixEvent(
mEvent.getType(),
typeof mEvent.getStateKey() === 'string',
@@ -2451,28 +2500,29 @@ export function RoomTimeline({ room, eventId, roomInputRef, editor }: RoomTimeli
mEvent,
item,
timelineSet,
collapsed
collapsed,
);
}
// Check if this is a call event that should be grouped
const isCallEventPending = rawEventJSX === ('CALL_EVENT_PENDING' as unknown as React.ReactNode);
// Determine if we need to flush pending call events
// Flush when: we hit a non-call event, or this is the last item
const isLastItem = index === allItems.length - 1;
const pendingCallEvents = pendingCallEventsRef.current;
const shouldFlushCallEvents = pendingCallEvents.length > 0 && (!isCallEventPending || isLastItem);
const shouldFlushCallEvents =
pendingCallEvents.length > 0 && (!isCallEventPending || isLastItem);
let callSummaryJSX: React.ReactNode = null;
if (shouldFlushCallEvents) {
callSummaryJSX = renderCallEventSummary([...pendingCallEvents]);
pendingCallEventsRef.current = []; // Clear array
}
// If this was a call event marker, don't render it directly
const eventJSX = isCallEventPending ? null : rawEventJSX;
prevEvent = mEvent;
isPrevRendered = !!eventJSX || !!callSummaryJSX;
@@ -2534,8 +2584,7 @@ export function RoomTimeline({ room, eventId, roomInputRef, editor }: RoomTimeli
return callSummaryJSX || eventJSX;
};
const showUnreadTop =
!!unreadInfo?.readUptoEventId && !unreadInfo?.inLiveTimeline;
const showUnreadTop = !!unreadInfo?.readUptoEventId && !unreadInfo?.inLiveTimeline;
const atLiveBottom = atBottom && liveTimelineLinked && rangeAtEnd;
return (
@@ -2728,11 +2777,15 @@ export function RoomTimeline({ room, eventId, roomInputRef, editor }: RoomTimeli
border: `1px solid ${color.Surface.ContainerLine}`,
}}
>
<Text size="T300" priority="300" style={{
whiteSpace: 'nowrap',
overflow: 'hidden',
textOverflow: 'ellipsis',
}}>
<Text
size="T300"
priority="300"
style={{
whiteSpace: 'nowrap',
overflow: 'hidden',
textOverflow: 'ellipsis',
}}
>
<b>{latestUnreadMessage.sender}:</b> {latestUnreadMessage.content}
</Text>
</Box>
@@ -2749,7 +2802,10 @@ export function RoomTimeline({ room, eventId, roomInputRef, editor }: RoomTimeli
</Box>
</TimelineFloat>
)}
<EmojiConfettiOverlay bursts={emojiConfettiBursts} onBurstComplete={removeEmojiConfettiBurst} />
<EmojiConfettiOverlay
bursts={emojiConfettiBursts}
onBurstComplete={removeEmojiConfettiBurst}
/>
</Box>
);
}
+1 -1
View File
@@ -21,7 +21,7 @@ export function RoomTombstone({ roomId, body, replacementRoomId }: RoomTombstone
return mx.joinRoom(replacementRoomId, {
viaServers: via,
});
}, [mx, roomId, replacementRoomId])
}, [mx, roomId, replacementRoomId]),
);
const replacementRoom = mx.getRoom(replacementRoomId);
+2 -2
View File
@@ -99,8 +99,8 @@ export function RoomView({ room, eventId }: { room: Room; eventId?: string }) {
ReactEditor.focus(editor);
}
},
[editor]
)
[editor],
),
);
return (
+4 -3
View File
@@ -1,9 +1,9 @@
import React, { useState } from 'react';
import { Box, Modal, Overlay, OverlayBackdrop, OverlayCenter, Text, as, config } from 'folds';
import { Icon, Icons } from '../../components/icons';
import { Room } from 'matrix-js-sdk';
import classNames from 'classnames';
import FocusTrap from 'focus-trap-react';
import { Icon, Icons } from '../../components/icons';
import { getMemberDisplayName } from '../../utils/room';
import { getMxIdLocalPart } from '../../utils/matrix';
@@ -33,7 +33,8 @@ export const RoomViewFollowing = as<'div', RoomViewFollowingProps>(
const names = latestEventReaders
.filter((readerId) => readerId !== myUserId)
.map(
(readerId) => getMemberDisplayName(room, readerId) ?? getMxIdLocalPart(readerId) ?? readerId
(readerId) =>
getMemberDisplayName(room, readerId) ?? getMxIdLocalPart(readerId) ?? readerId,
);
if (names.length === 0) {
@@ -116,5 +117,5 @@ export const RoomViewFollowing = as<'div', RoomViewFollowingProps>(
</Box>
</>
);
}
},
);
+61 -14
View File
@@ -1,10 +1,30 @@
import React, { MouseEventHandler, forwardRef, useState } from 'react';
import FocusTrap from 'focus-trap-react';
import { Box, Avatar, Text, Overlay, OverlayCenter, OverlayBackdrop, IconButton, Tooltip, TooltipProvider, Menu, MenuItem, toRem, config, Line, PopOut, RectCords, Badge, Spinner, color } from 'folds';
import { Icon, Icons } from '../../components/icons';
import {
Box,
Avatar,
Text,
Overlay,
OverlayCenter,
OverlayBackdrop,
IconButton,
Tooltip,
TooltipProvider,
Menu,
MenuItem,
toRem,
config,
Line,
PopOut,
RectCords,
Badge,
Spinner,
color,
} from 'folds';
import { useNavigate } from 'react-router-dom';
import { JoinRule, Room } from 'matrix-js-sdk';
import { useAtom, useAtomValue } from 'jotai';
import { Icon, Icons } from '../../components/icons';
import { activeThreadIdAtomFamily } from '../../state/activeThread';
import { PageHeader } from '../../components/page';
@@ -16,8 +36,18 @@ import { useRoom } from '../../hooks/useRoom';
import { useSetting } from '../../state/hooks/settings';
import { settingsAtom } from '../../state/settings';
import { useSpaceOptionally } from '../../hooks/useSpace';
import { getHomeSearchPath, getSpaceSearchPath, getDirectSearchPath, withSearchParam } from '../../pages/pathUtils';
import { getCanonicalAliasOrRoomId, guessDmRoomUserId, isRoomAlias, mxcUrlToHttp } from '../../utils/matrix';
import {
getHomeSearchPath,
getSpaceSearchPath,
getDirectSearchPath,
withSearchParam,
} from '../../pages/pathUtils';
import {
getCanonicalAliasOrRoomId,
guessDmRoomUserId,
isRoomAlias,
mxcUrlToHttp,
} from '../../utils/matrix';
import colorMXID from '../../../util/colorMXID';
import { useOtherUserColor } from '../../hooks/useUserColor';
import { _SearchPathSearchParams } from '../../pages/paths';
@@ -307,7 +337,10 @@ function CallIndicator({ roomId }: CallIndicatorProps) {
>
{displayName}
</Text>
<Text size="T200" style={{ opacity: 0.7, color: color.SurfaceVariant.OnContainer }}>
<Text
size="T200"
style={{ opacity: 0.7, color: color.SurfaceVariant.OnContainer }}
>
{member.userId}
</Text>
</Box>
@@ -321,9 +354,7 @@ function CallIndicator({ roomId }: CallIndicatorProps) {
src={avatarUrl}
alt={displayName}
renderFallback={() => (
<Text size="T200">
{displayName.charAt(0).toUpperCase()}
</Text>
<Text size="T200">{displayName.charAt(0).toUpperCase()}</Text>
)}
/>
</Avatar>
@@ -417,12 +448,18 @@ function RoomCallButtons({ roomId }: RoomCallButtonsProps) {
<IconButton
ref={triggerRef}
onClick={handleVoiceCall}
variant={isActive && activeCall?.callType === CallType.Voice ? 'Critical' : 'Background'}
variant={
isActive && activeCall?.callType === CallType.Voice ? 'Critical' : 'Background'
}
>
{isConnecting ? (
<Spinner size="100" variant="Secondary" />
) : (
<Icon size="300" src={Icons.Phone} filled={isActive && activeCall?.callType === CallType.Voice} />
<Icon
size="300"
src={Icons.Phone}
filled={isActive && activeCall?.callType === CallType.Voice}
/>
)}
</IconButton>
)}
@@ -443,12 +480,18 @@ function RoomCallButtons({ roomId }: RoomCallButtonsProps) {
<IconButton
ref={triggerRef}
onClick={handleVideoCall}
variant={isActive && activeCall?.callType === CallType.Video ? 'Critical' : 'Background'}
variant={
isActive && activeCall?.callType === CallType.Video ? 'Critical' : 'Background'
}
>
{isConnecting ? (
<Spinner size="100" variant="Secondary" />
) : (
<Icon size="300" src={Icons.VideoCamera} filled={isActive && activeCall?.callType === CallType.Video} />
<Icon
size="300"
src={Icons.VideoCamera}
filled={isActive && activeCall?.callType === CallType.Video}
/>
)}
</IconButton>
)}
@@ -482,7 +525,7 @@ export function RoomViewHeader({ forumLayout = false }: RoomViewHeaderProps) {
const name = useRoomName(room);
const topic = useRoomTopic(room);
const avatarUrl = avatarMxc
? mxcUrlToHttp(mx, avatarMxc, useAuthentication, 96, 96, 'crop') ?? undefined
? (mxcUrlToHttp(mx, avatarMxc, useAuthentication, 96, 96, 'crop') ?? undefined)
: undefined;
const dmUserId = isDirect ? guessDmRoomUserId(room, mx.getSafeUserId()) : undefined;
@@ -740,7 +783,11 @@ export function RoomViewHeader({ forumLayout = false }: RoomViewHeaderProps) {
onClick={() => setActiveThreadId(undefined)}
aria-pressed={!!activeThreadId}
>
<Icon size="300" src={activeThreadId ? Icons.ArrowLeft : Icons.Thread} filled={!!activeThreadId} />
<Icon
size="300"
src={activeThreadId ? Icons.ArrowLeft : Icons.Thread}
filled={!!activeThreadId}
/>
</IconButton>
)}
</TooltipProvider>
+4 -4
View File
@@ -1,9 +1,9 @@
import React from 'react';
import { Box, IconButton, Text, as } from 'folds';
import { Icon, Icons } from '../../components/icons';
import { Room } from 'matrix-js-sdk';
import classNames from 'classnames';
import { useSetAtom } from 'jotai';
import { Icon, Icons } from '../../components/icons';
import { roomIdToTypingMembersAtom } from '../../state/typingMembers';
import { TypingIndicator } from '../../components/typing-indicator';
import { getMemberDisplayName } from '../../utils/room';
@@ -66,7 +66,7 @@ export const RoomViewTyping = as<'div', RoomViewTypingProps>(
type: 'DELETE',
roomId: room.roomId,
userId: receipt.userId,
})
}),
);
};
@@ -88,12 +88,12 @@ export const RoomViewTyping = as<'div', RoomViewTypingProps>(
</React.Fragment>
))}
{sharedSuffix}
{'...'}
...
</Text>
<IconButton title="Drop Typing Status" size="300" radii="Pill" onClick={handleDropAll}>
<Icon size="50" src={Icons.Cross} />
</IconButton>
</Box>
);
}
},
);
+75 -90
View File
@@ -7,29 +7,29 @@ import React, {
useRef,
useState,
} from 'react';
import {
MatrixEvent,
RelationType,
Room,
RoomEvent,
ThreadEvent,
} from 'matrix-js-sdk';
import { MatrixEvent, RelationType, Room, RoomEvent, ThreadEvent } from 'matrix-js-sdk';
import { useAtomValue, useSetAtom } from 'jotai';
import { Badge, Box, IconButton, Line, Scroll, Text, Tooltip, TooltipProvider, config } from 'folds';
import { Icon, Icons } from '../../components/icons';
import {
Badge,
Box,
IconButton,
Line,
Scroll,
Text,
Tooltip,
TooltipProvider,
config,
} from 'folds';
import { HTMLReactParserOptions } from 'html-react-parser';
import { Opts as LinkifyOpts } from 'linkifyjs';
import { ReactEditor } from 'slate-react';
import { isKeyHotkey } from 'is-hotkey';
import { Icon, Icons } from '../../components/icons';
import { useMatrixClient } from '../../hooks/useMatrixClient';
import { useKeyDown } from '../../hooks/useKeyDown';
import { editableActiveElement } from '../../utils/dom';
import {
useEditor,
createMentionElement,
moveCursor,
} from '../../components/editor';
import { editableActiveElement, autoScrollToBottom, scrollElementIntoView } from '../../utils/dom';
import { useEditor, createMentionElement, moveCursor } from '../../components/editor';
import { useSetting } from '../../state/hooks/settings';
import { MessageLayout, settingsAtom } from '../../state/settings';
import { useMediaAuthentication } from '../../hooks/useMediaAuthentication';
@@ -44,10 +44,7 @@ import { useOpenUserRoomProfile } from '../../state/hooks/userRoomProfile';
import { useTheme } from '../../hooks/useTheme';
import { useRoomCreatorsTag } from '../../hooks/useRoomCreatorsTag';
import { usePowerLevelTags } from '../../hooks/usePowerLevelTags';
import {
useAccessiblePowerTagColors,
useGetMemberPowerTag,
} from '../../hooks/useMemberPowerTag';
import { useAccessiblePowerTagColors, useGetMemberPowerTag } from '../../hooks/useMemberPowerTag';
import {
combineEmbedFilters,
useRoomEmbedFilters,
@@ -81,14 +78,9 @@ import {
getReactionContent,
reactionOrEditEvent,
} from '../../utils/room';
import {
eventWithShortcode,
factoryEventSentBy,
getMxIdLocalPart,
} from '../../utils/matrix';
import { eventWithShortcode, factoryEventSentBy, getMxIdLocalPart } from '../../utils/matrix';
import { GetContentCallback, MessageEvent } from '../../../types/matrix/room';
import { inSameDay, minuteDifference, timeDayMonthYear, today, yesterday } from '../../utils/time';
import { autoScrollToBottom, scrollElementIntoView } from '../../utils/dom';
type ThreadViewProps = {
room: Room;
@@ -140,7 +132,7 @@ export function ThreadView({ room, threadRootId }: ThreadViewProps) {
console.log('[ThreadView] Component mount/render', {
roomId: room.roomId,
threadRootId,
allThreadsInRoom: room.getThreads().map(t => ({
allThreadsInRoom: room.getThreads().map((t) => ({
id: t.id,
rootEventId: t.rootEvent?.getId(),
length: t.length,
@@ -158,8 +150,11 @@ export function ThreadView({ room, threadRootId }: ThreadViewProps) {
const [hour24Clock] = useSetting(settingsAtom, 'hour24Clock');
const [dateFormatString] = useSetting(settingsAtom, 'dateFormatString');
const [hideActivity] = useSetting(settingsAtom, 'hideActivity');
const { bursts: emojiConfettiBursts, removeBurst: removeEmojiConfettiBurst, handleJumboEmojiClick } =
useJumboEmojiConfetti(room);
const {
bursts: emojiConfettiBursts,
removeBurst: removeEmojiConfettiBurst,
handleJumboEmojiClick,
} = useJumboEmojiConfetti(room);
const showUrlPreview = room.hasEncryptionStateEvent() ? encUrlPreview : urlPreview;
const direct = useIsDirectRoom();
@@ -173,7 +168,7 @@ export function ThreadView({ room, threadRootId }: ThreadViewProps) {
const accessiblePowerTagColors = useAccessiblePowerTagColors(
theme.kind,
creatorsTag,
powerLevelTags
powerLevelTags,
);
const permissions = useRoomPermissions(creators, powerLevels);
const canRedact = permissions.action('redact', mx.getSafeUserId());
@@ -191,7 +186,7 @@ export function ThreadView({ room, threadRootId }: ThreadViewProps) {
const roomWideEmbedFilters = useRoomWideEmbedFilters(room);
const combinedEmbedFilters = useMemo(
() => combineEmbedFilters(personalEmbedFilters, roomWideEmbedFilters),
[personalEmbedFilters, roomWideEmbedFilters]
[personalEmbedFilters, roomWideEmbedFilters],
);
const mentionClickHandler = useMentionClickHandler(room.roomId);
@@ -201,10 +196,10 @@ export function ThreadView({ room, threadRootId }: ThreadViewProps) {
() => ({
...LINKIFY_OPTS,
render: factoryRenderLinkifyWithMention((href) =>
renderMatrixMention(mx, room.roomId, href, makeMentionCustomProps(mentionClickHandler))
renderMatrixMention(mx, room.roomId, href, makeMentionCustomProps(mentionClickHandler)),
),
}),
[mx, room, mentionClickHandler]
[mx, room, mentionClickHandler],
);
const htmlReactParserOptions = useMemo<HTMLReactParserOptions>(
@@ -215,7 +210,7 @@ export function ThreadView({ room, threadRootId }: ThreadViewProps) {
handleSpoilerClick: spoilerClickHandler,
handleMentionClick: mentionClickHandler,
}),
[mx, room, linkifyOpts, spoilerClickHandler, mentionClickHandler, useAuthentication]
[mx, room, linkifyOpts, spoilerClickHandler, mentionClickHandler, useAuthentication],
);
const thread = room.getThread(threadRootId);
@@ -233,7 +228,11 @@ export function ThreadView({ room, threadRootId }: ThreadViewProps) {
rootEventFound: !!rootEvent,
rootEventType: rootEvent?.getType(),
rootEventThreadRootId: rootEvent?.threadRootId,
allEventIdsInTimeline: roomTimelineSet.getLiveTimeline().getEvents().slice(0, 20).map(e => e.getId()),
allEventIdsInTimeline: roomTimelineSet
.getLiveTimeline()
.getEvents()
.slice(0, 20)
.map((e) => e.getId()),
});
}
}, [thread, room, threadRootId, roomTimelineSet]);
@@ -245,33 +244,33 @@ export function ThreadView({ room, threadRootId }: ThreadViewProps) {
console.log('[ThreadView] No thread found for ID:', threadRootId);
// eslint-disable-next-line no-console
console.log('[ThreadView] Attempting to find replies manually from room timeline');
// Fallback: search the room timeline for events that are replies to this thread
const allEvents = roomTimelineSet.getLiveTimeline().getEvents();
const threadReplies = allEvents.filter(event => {
const threadReplies = allEvents.filter((event) => {
const relations = event.getRelation();
// Check if this event is a thread reply to our root event
return relations?.rel_type === 'm.thread' && relations?.event_id === threadRootId;
});
// eslint-disable-next-line no-console
console.log('[ThreadView] Manual search found', {
totalEventsInTimeline: allEvents.length,
repliesFound: threadReplies.length,
replies: threadReplies.map(e => ({
replies: threadReplies.map((e) => ({
id: e.getId(),
sender: e.getSender(),
body: e.getContent()?.body?.substring(0, 50),
})),
});
return threadReplies;
}
// thread.events contains only replies, not the root event
const replies = [...t.events];
const liveTimelineEvents = t.liveTimeline?.getEvents() || [];
// eslint-disable-next-line no-console
console.log('[ThreadView] getThreadEvents', {
threadId: threadRootId,
@@ -282,27 +281,27 @@ export function ThreadView({ room, threadRootId }: ThreadViewProps) {
initialEventsFetched: (t as any).initialEventsFetched,
liveTimelineEventsCount: liveTimelineEvents.length,
threadEventsMatch: replies.length === liveTimelineEvents.length,
allRepliesFromThreadEvents: replies.map(e => ({
id: e.getId(),
type: e.getType(),
allRepliesFromThreadEvents: replies.map((e) => ({
id: e.getId(),
type: e.getType(),
sender: e.getSender(),
content: e.getContent()?.body?.substring(0, 50),
})),
allEventsFromLiveTimeline: liveTimelineEvents.map(e => ({
allEventsFromLiveTimeline: liveTimelineEvents.map((e) => ({
id: e.getId(),
type: e.getType(),
sender: e.getSender(),
content: e.getContent()?.body?.substring(0, 50),
})),
});
// Try using liveTimeline events if thread.events is empty but liveTimeline has events
if (replies.length === 0 && liveTimelineEvents.length > 0) {
// eslint-disable-next-line no-console
console.log('[ThreadView] Using liveTimeline events instead of thread.events');
return [...liveTimelineEvents];
}
return replies;
}, [room, threadRootId, roomTimelineSet]);
@@ -332,8 +331,8 @@ export function ThreadView({ room, threadRootId }: ThreadViewProps) {
ReactEditor.focus(editor);
}
},
[editor]
)
[editor],
),
);
// Subscribe to thread and room timeline events.
@@ -364,7 +363,7 @@ export function ThreadView({ room, threadRootId }: ThreadViewProps) {
// Fires when initial events are loaded after the SDK paginates the thread.
// eslint-disable-next-line @typescript-eslint/no-explicit-any
(thread as any).on(RoomEvent.TimelineReset, handleUpdate);
// Also listen to Timeline events which fire when events are added
thread.on(RoomEvent.Timeline, handleUpdate);
}
@@ -373,9 +372,10 @@ export function ThreadView({ room, threadRootId }: ThreadViewProps) {
if (eventRoom?.roomId !== room.roomId) return;
// Check if this event is related to our thread (either it's a reply to it, or it IS the root event)
const relations = mEvent.getRelation();
const isThreadReply = relations?.rel_type === 'm.thread' && relations?.event_id === threadRootId;
const isThreadReply =
relations?.rel_type === 'm.thread' && relations?.event_id === threadRootId;
const isRootEvent = mEvent.getId() === threadRootId;
if (isThreadReply || isRootEvent) {
handleUpdate();
}
@@ -418,10 +418,10 @@ export function ThreadView({ room, threadRootId }: ThreadViewProps) {
room.roomId,
space?.roomId,
userId,
evt.currentTarget.getBoundingClientRect()
evt.currentTarget.getBoundingClientRect(),
);
},
[room, space, openUserRoomProfile]
[room, space, openUserRoomProfile],
);
const handleUsernameClick: MouseEventHandler<HTMLButtonElement> = useCallback(
@@ -434,25 +434,23 @@ export function ThreadView({ room, threadRootId }: ThreadViewProps) {
createMentionElement(
userId,
name.startsWith('@') ? name : `@${name}`,
userId === mx.getUserId()
)
userId === mx.getUserId(),
),
);
ReactEditor.focus(editor);
moveCursor(editor);
},
[mx, room, editor]
[mx, room, editor],
);
const handleReplyClick: MouseEventHandler<HTMLButtonElement> = useCallback(
(evt) => {
const replyId = evt.currentTarget.getAttribute('data-event-id');
if (!replyId) return;
const replyEvt =
thread?.findEventById(replyId) ?? room.findEventById(replyId);
const replyEvt = thread?.findEventById(replyId) ?? room.findEventById(replyId);
if (!replyEvt) return;
const editedReply = getEditedEvent(replyId, replyEvt, roomTimelineSet);
const content =
editedReply?.getContent()['m.new_content'] ?? replyEvt.getContent();
const content = editedReply?.getContent()['m.new_content'] ?? replyEvt.getContent();
const { body, formatted_body: formattedBody } = content;
const senderId = replyEvt.getSender();
if (senderId && typeof body === 'string') {
@@ -466,14 +464,14 @@ export function ThreadView({ room, threadRootId }: ThreadViewProps) {
setTimeout(() => ReactEditor.focus(editor), 100);
}
},
[room, thread, roomTimelineSet, threadRootId, setReplyDraft, editor]
[room, thread, roomTimelineSet, threadRootId, setReplyDraft, editor],
);
const handleOpenReply: MouseEventHandler = useCallback((evt) => {
const targetId = evt.currentTarget.getAttribute('data-event-id');
if (!targetId) return;
const el = scrollRef.current?.querySelector(
`[data-message-id="${targetId}"]`
`[data-message-id="${targetId}"]`,
) as HTMLElement | null;
if (el) scrollElementIntoView(el, { behavior: 'smooth', block: 'center' });
}, []);
@@ -498,10 +496,10 @@ export function ThreadView({ room, threadRootId }: ThreadViewProps) {
room.roomId,
// eslint-disable-next-line @typescript-eslint/no-explicit-any
MessageEvent.Reaction as any,
getReactionContent(targetEventId, key, rShortcode)
getReactionContent(targetEventId, key, rShortcode),
);
},
[mx, room, roomTimelineSet]
[mx, room, roomTimelineSet],
);
/** Renders a single thread event into JSX. Returns null for non-message events. */
@@ -514,17 +512,12 @@ export function ThreadView({ room, threadRootId }: ThreadViewProps) {
if (reactionOrEditEvent(mEvent)) return null;
const type = mEvent.getType();
if (
type !== MessageEvent.RoomMessage &&
type !== MessageEvent.RoomMessageEncrypted
) {
if (type !== MessageEvent.RoomMessage && type !== MessageEvent.RoomMessageEncrypted) {
return null;
}
const prevEvent = index > 0 ? all[index - 1] : undefined;
const dayDivider = prevEvent
? !inSameDay(prevEvent.getTs(), mEvent.getTs())
: false;
const dayDivider = prevEvent ? !inSameDay(prevEvent.getTs(), mEvent.getTs()) : false;
const collapse =
!dayDivider &&
@@ -534,21 +527,17 @@ export function ThreadView({ room, threadRootId }: ThreadViewProps) {
minuteDifference(prevEvent.getTs(), mEvent.getTs()) < 2;
const reactionRelations = getEventReactions(roomTimelineSet, mEventId);
const hasReactions =
!!reactionRelations?.getSortedAnnotationsByKey()?.length;
const hasReactions = !!reactionRelations?.getSortedAnnotationsByKey()?.length;
const { replyEventId, threadRootId: evtThreadRootId } = mEvent;
const editedEvent = getEditedEvent(mEventId, mEvent, roomTimelineSet);
const getContent = (() =>
editedEvent?.getContent()['m.new_content'] ??
mEvent.getContent()) as GetContentCallback;
editedEvent?.getContent()['m.new_content'] ?? mEvent.getContent()) as GetContentCallback;
const senderId = mEvent.getSender() ?? '';
const senderDisplayName =
getMemberDisplayName(room, senderId) ??
getMxIdLocalPart(senderId) ??
senderId;
getMemberDisplayName(room, senderId) ?? getMxIdLocalPart(senderId) ?? senderId;
const dayDividerJSX = dayDivider ? (
<Box
@@ -677,15 +666,14 @@ export function ThreadView({ room, threadRootId }: ThreadViewProps) {
const rootEvent = room.findEventById(threadRootId);
const rootBody =
getEditedEvent(threadRootId, rootEvent ?? new MatrixEvent(), roomTimelineSet)
?.getContent()['m.new_content']?.body ??
getEditedEvent(threadRootId, rootEvent ?? new MatrixEvent(), roomTimelineSet)?.getContent()[
'm.new_content'
]?.body ??
rootEvent?.getContent()?.body ??
'';
const rootSenderId = rootEvent?.getSender() ?? '';
const rootSenderName =
getMemberDisplayName(room, rootSenderId) ??
getMxIdLocalPart(rootSenderId) ??
rootSenderId;
getMemberDisplayName(room, rootSenderId) ?? getMxIdLocalPart(rootSenderId) ?? rootSenderId;
// Use actual events count if thread doesn't exist but we found replies manually
const replyCount = thread?.length ?? events.length;
@@ -750,19 +738,16 @@ export function ThreadView({ room, threadRootId }: ThreadViewProps) {
>
{/* Render the thread root event */}
{rootEvent && renderEvent(rootEvent, -1, [])}
{/* Show "no replies" message if no replies exist */}
{events.length === 0 && (
<Box
justifyContent="Center"
style={{ padding: config.space.S700 }}
>
<Box justifyContent="Center" style={{ padding: config.space.S700 }}>
<Text size="T300" priority="300">
No replies yet. Be the first!
</Text>
</Box>
)}
{/* Render all reply events */}
{events.map((evt, idx, arr) => renderEvent(evt, idx, arr))}
</Box>
@@ -1,7 +1,12 @@
import React, { useEffect, useMemo, useRef } from 'react';
import { createPortal } from 'react-dom';
import { EmojiConfettiBurst } from './types';
import { findJumboEmojiElement, getLocalBurstCanvasSize, measureJumboGlyph, setJumboEmojiHidden } from './findJumboMount';
import {
findJumboEmojiElement,
getLocalBurstCanvasSize,
measureJumboGlyph,
setJumboEmojiHidden,
} from './findJumboMount';
import {
BurstParticle,
drawBurstParticles,
@@ -30,7 +35,9 @@ export function EmojiConfettiBurstCanvas({ burst, onComplete }: EmojiConfettiBur
const fullscreen = isFullscreenBurstEmoji(primaryEmoji);
if (fullscreen) {
return <FireworkBurstCanvas burst={burst} primaryEmoji={primaryEmoji} onComplete={onComplete} />;
return (
<FireworkBurstCanvas burst={burst} primaryEmoji={primaryEmoji} onComplete={onComplete} />
);
}
return <LocalBurstCanvas burst={burst} primaryEmoji={primaryEmoji} onComplete={onComplete} />;
@@ -89,7 +96,7 @@ function FireworkBurstCanvas({ burst, primaryEmoji, onComplete }: BurstCanvasPro
const origin = {
x: glyph ? glyph.x : burst.origin.x,
y: glyph ? glyph.y : burst.origin.y,
maskRadius: glyph ? glyph.size * 0.5 : burst.origin.maskRadius ?? 36,
maskRadius: glyph ? glyph.size * 0.5 : (burst.origin.maskRadius ?? 36),
};
// Keep morph heroes glued to the message emoji; only clamp undirected fireworks.
@@ -105,7 +112,7 @@ function FireworkBurstCanvas({ burst, primaryEmoji, onComplete }: BurstCanvasPro
primaryEmoji,
profile,
performance.now(),
glyph?.size
glyph?.size,
);
const revealJumbo = () => {
@@ -188,7 +195,14 @@ function FireworkBurstCanvas({ burst, primaryEmoji, onComplete }: BurstCanvasPro
// Extra Things: allow Strict Mode remount to start a fresh burst.
spawnedRef.current = false;
};
}, [burst.id, burst.origin.maskRadius, burst.origin.x, burst.origin.y, burst.targetEventId, primaryEmoji]);
}, [
burst.id,
burst.origin.maskRadius,
burst.origin.x,
burst.origin.y,
burst.targetEventId,
primaryEmoji,
]);
return createPortal(
<div
@@ -213,7 +227,7 @@ function FireworkBurstCanvas({ burst, primaryEmoji, onComplete }: BurstCanvasPro
}}
/>
</div>,
document.body
document.body,
);
}
@@ -234,7 +248,7 @@ function LocalBurstCanvas({ burst, primaryEmoji, onComplete }: BurstCanvasProps)
y: canvasSize / 2,
maskRadius: burst.origin.maskRadius ?? 36,
}),
[burst.origin.maskRadius, canvasSize]
[burst.origin.maskRadius, canvasSize],
);
const updateLayerPosition = () => {
@@ -370,6 +384,6 @@ function LocalBurstCanvas({ burst, primaryEmoji, onComplete }: BurstCanvasProps)
}}
/>
</div>,
document.body
document.body,
);
}
@@ -13,11 +13,7 @@ export function EmojiConfettiOverlay({ bursts, onBurstComplete }: EmojiConfettiO
return (
<>
{bursts.map((burst) => (
<EmojiConfettiBurstCanvas
key={burst.id}
burst={burst}
onComplete={onBurstComplete}
/>
<EmojiConfettiBurstCanvas key={burst.id} burst={burst} onComplete={onBurstComplete} />
))}
</>
);
@@ -19,7 +19,7 @@ export function getElementCenter(element: Element): BurstPoint {
export function findEmojiOriginInMessage(
targetEventId: string,
emoji: string
emoji: string,
): BurstPoint | undefined {
const message = document.querySelector(`[data-message-id="${CSS.escape(targetEventId)}"]`);
if (!message) return undefined;
@@ -54,7 +54,7 @@ export function getMessageFallbackOrigin(targetEventId: string): BurstPoint | un
export function resolveBurstOrigin(
targetEventId: string | undefined,
emojis: string[],
explicitOrigin?: BurstPoint
explicitOrigin?: BurstPoint,
): BurstPoint {
if (explicitOrigin) return explicitOrigin;

Some files were not shown because too many files have changed in this diff Show More