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
+16 -4
View File
@@ -1,7 +1,19 @@
import React, { FormEventHandler, useCallback, useEffect, useMemo, useRef, useState } from 'react';
import { Box, Text, IconButton, Input, Button, TextArea, color, Spinner, Chip, Scroll, config } from 'folds';
import { Icon, Icons } from './icons';
import {
Box,
Text,
IconButton,
Input,
Button,
TextArea,
color,
Spinner,
Chip,
Scroll,
config,
} from 'folds';
import { MatrixError } from 'matrix-js-sdk';
import { Icon, Icons } from './icons';
import { Cursor } from '../plugins/text-area';
import { syntaxErrorPosition } from '../utils/dom';
import { AsyncStatus, useAsyncCallback } from '../hooks/useAsyncCallback';
@@ -41,7 +53,7 @@ function AccountDataEdit({
const { handleKeyDown, operations, getTarget } = useTextAreaCodeEditor(
textAreaRef,
EDITOR_INTENT_SPACE_COUNT
EDITOR_INTENT_SPACE_COUNT,
);
const [submitState, submit] = useAsyncCallback<void, MatrixError, [string, object]>(submitChange);
@@ -263,7 +275,7 @@ export function AccountDataEditor({
const contentJSONStr = useMemo(
() => JSON.stringify(data.content, null, EDITOR_INTENT_SPACE_COUNT),
[data.content]
[data.content],
);
return (
+5 -5
View File
@@ -52,7 +52,7 @@ export function AngleSelector({
return Math.round(angle);
},
[value]
[value],
);
/**
@@ -67,7 +67,7 @@ export function AngleSelector({
const newAngle = calculateAngle(e.clientX, e.clientY);
onChange(newAngle);
},
[disabled, calculateAngle, onChange]
[disabled, calculateAngle, onChange],
);
/**
@@ -79,7 +79,7 @@ export function AngleSelector({
const newAngle = calculateAngle(e.clientX, e.clientY);
onChange(newAngle);
},
[isDragging, disabled, calculateAngle, onChange]
[isDragging, disabled, calculateAngle, onChange],
);
/**
@@ -90,7 +90,7 @@ export function AngleSelector({
}, []);
// Calculate line endpoint position
const lineLength = (size / 2) - 8;
const lineLength = size / 2 - 8;
const radians = ((value - 90) * Math.PI) / 180;
const lineX = Math.cos(radians) * lineLength;
const lineY = Math.sin(radians) * lineLength;
@@ -160,7 +160,7 @@ export function AngleSelector({
{/* Cardinal direction markers */}
{[0, 90, 180, 270].map((deg) => {
const markerRadians = ((deg - 90) * Math.PI) / 180;
const markerDist = (size / 2) - 3;
const markerDist = size / 2 - 3;
const markerX = Math.cos(markerRadians) * markerDist;
const markerY = Math.sin(markerRadians) * markerDist;
return (
+1 -1
View File
@@ -42,7 +42,7 @@ export function AnimatedOutlet() {
const location = useLocation();
const transitionKey = useMemo(
() => getOutletTransitionKey(location.pathname),
[location.pathname]
[location.pathname],
);
return (
+1 -1
View File
@@ -45,7 +45,7 @@ export function AuthFlowsLoader({ fallback, error, children }: AuthFlowsLoaderPr
};
return authFlows;
}, [mx])
}, [mx]),
);
useEffect(() => {
+17 -3
View File
@@ -1,9 +1,23 @@
import React, { MouseEventHandler, useCallback, useState } from 'react';
import { useAtom } from 'jotai';
import { CryptoApi, KeyBackupInfo } from 'matrix-js-sdk/lib/crypto-api';
import { Badge, Box, Button, color, config, IconButton, Menu, percent, PopOut, ProgressBar, RectCords, Spinner, Text } from 'folds';
import { Icon, Icons } from './icons';
import {
Badge,
Box,
Button,
color,
config,
IconButton,
Menu,
percent,
PopOut,
ProgressBar,
RectCords,
Spinner,
Text,
} from 'folds';
import FocusTrap from 'focus-trap-react';
import { Icon, Icons } from './icons';
import { BackupProgressStatus, backupRestoreProgressAtom } from '../state/backupRestore';
import { InfoCard } from './info-card';
import { AsyncStatus, useAsyncCallback } from '../hooks/useAsyncCallback';
@@ -142,7 +156,7 @@ export function BackupRestoreTile({ crypto }: BackupRestoreTileProps) {
setRestoreProgress(progress);
},
});
}, [crypto, setRestoreProgress])
}, [crypto, setRestoreProgress]),
);
const handleRestore = () => {
+2 -2
View File
@@ -7,7 +7,7 @@ type ConfirmPasswordMatchProps = {
match: boolean,
doMatch: () => void,
passRef: RefObject<HTMLInputElement>,
confPassRef: RefObject<HTMLInputElement>
confPassRef: RefObject<HTMLInputElement>,
) => ReactNode;
};
export function ConfirmPasswordMatch({ initialValue, children }: ConfirmPasswordMatchProps) {
@@ -28,7 +28,7 @@ export function ConfirmPasswordMatch({ initialValue, children }: ConfirmPassword
{
wait: 500,
immediate: false,
}
},
);
return children(match, doMatch, passRef, confPassRef);
+14 -2
View File
@@ -6,9 +6,21 @@ import {
} from 'matrix-js-sdk/lib/crypto-api';
import React, { CSSProperties, useCallback, useEffect, useState } from 'react';
import { VerificationMethod } from 'matrix-js-sdk/lib/types';
import { Box, Button, config, Dialog, Header, IconButton, Overlay, OverlayBackdrop, OverlayCenter, Spinner, Text } from 'folds';
import { Icon, Icons } from './icons';
import {
Box,
Button,
config,
Dialog,
Header,
IconButton,
Overlay,
OverlayBackdrop,
OverlayCenter,
Spinner,
Text,
} from 'folds';
import FocusTrap from 'focus-trap-react';
import { Icon, Icons } from './icons';
import {
useVerificationRequestPhase,
useVerificationRequestReceived,
+10 -10
View File
@@ -1,9 +1,9 @@
import React, { FormEventHandler, forwardRef, useCallback, useState } from 'react';
import { Dialog, Header, Box, Text, IconButton, config, Button, Chip, color, Spinner } from 'folds';
import { Icon, Icons } from './icons';
import FileSaver from 'file-saver';
import to from 'await-to-js';
import { AuthDict, IAuthData, MatrixError, UIAuthCallback } from 'matrix-js-sdk';
import { Icon, Icons } from './icons';
import { PasswordInput } from './password-input';
import { ContainerColor } from '../styles/ContainerColor.css';
import { copyToClipboard } from '../utils/dom';
@@ -15,7 +15,7 @@ import { useAlive } from '../hooks/useAlive';
import { UseStateProvider } from './UseStateProvider';
type UIACallback<T> = (
authDict: AuthDict | null
authDict: AuthDict | null,
) => Promise<[IAuthData, undefined] | [undefined, T]>;
type PerformAction<T> = (authDict: AuthDict | null) => Promise<T>;
@@ -30,7 +30,7 @@ function makeUIAAction<T>(
authData: IAuthData,
performAction: PerformAction<T>,
resolve: (data: T) => void,
reject: (error?: any) => void
reject: (error?: any) => void,
): UIAAction<T> {
const action: UIAAction<T> = {
authData,
@@ -79,7 +79,7 @@ function SetupVerification({ onComplete }: SetupVerificationProps) {
setNextAuthData(authData);
}
},
[uiaAction, alive]
[uiaAction, alive],
);
const resetUIA = useCallback(() => {
@@ -106,7 +106,7 @@ function SetupVerification({ onComplete }: SetupVerificationProps) {
(err) => {
resetUIA();
reject(err);
}
},
);
if (alive()) {
setUIAAction(action);
@@ -118,7 +118,7 @@ function SetupVerification({ onComplete }: SetupVerificationProps) {
reject(error);
});
}),
[alive, resetUIA]
[alive, resetUIA],
);
const [setupState, setup] = useAsyncCallback<void, Error, [string | undefined]>(
@@ -147,8 +147,8 @@ function SetupVerification({ onComplete }: SetupVerificationProps) {
onComplete(recoveryKeyData.encodedPrivateKey);
},
[mx, onComplete, authUploadDeviceSigningKeys]
)
[mx, onComplete, authUploadDeviceSigningKeys],
),
);
const loading = setupState.status === AsyncStatus.Loading;
@@ -302,7 +302,7 @@ export const DeviceVerificationSetup = forwardRef<HTMLDivElement, DeviceVerifica
</Box>
</Dialog>
);
}
},
);
type DeviceVerificationResetProps = {
onCancel: () => void;
@@ -359,5 +359,5 @@ export const DeviceVerificationReset = forwardRef<HTMLDivElement, DeviceVerifica
)}
</Dialog>
);
}
},
);
+5 -5
View File
@@ -1,8 +1,8 @@
import React, { MouseEventHandler, useCallback, useMemo, useState } from 'react';
import { config, Box, MenuItem, Text, RectCords, PopOut, Menu, Button, Spinner } from 'folds';
import { Icon, Icons, IconSrc } from './icons';
import { JoinRule } from 'matrix-js-sdk';
import FocusTrap from 'focus-trap-react';
import { Icon, Icons, IconSrc } from './icons';
import { stopPropagation } from '../utils/keyboard';
export type ExtraJoinRules = 'knock_restricted';
@@ -19,7 +19,7 @@ export const useRoomJoinRuleIcon = (): JoinRuleIcons =>
[JoinRule.Public]: Icons.HashGlobe,
[JoinRule.Private]: Icons.HashLock,
}),
[]
[],
);
export const useSpaceJoinRuleIcon = (): JoinRuleIcons =>
useMemo(
@@ -31,7 +31,7 @@ export const useSpaceJoinRuleIcon = (): JoinRuleIcons =>
[JoinRule.Public]: Icons.SpaceGlobe,
[JoinRule.Private]: Icons.SpaceLock,
}),
[]
[],
);
type JoinRuleLabels = Record<ExtendedJoinRules, string>;
@@ -45,7 +45,7 @@ export const useRoomJoinRuleLabel = (): JoinRuleLabels =>
[JoinRule.Public]: 'Public',
[JoinRule.Private]: 'Invite Only',
}),
[]
[],
);
type JoinRulesSwitcherProps<T extends ExtendedJoinRules[]> = {
@@ -77,7 +77,7 @@ export function JoinRulesSwitcher<T extends ExtendedJoinRules[]>({
setCords(undefined);
onChange(selectedRule);
},
[onChange]
[onChange],
);
return (
+3 -3
View File
@@ -21,13 +21,13 @@ export const LogoutDialog = forwardRef<HTMLDivElement, LogoutDialogProps>(
const verificationStatus = useDeviceVerificationStatus(
mx.getCrypto(),
mx.getSafeUserId(),
mx.getDeviceId() ?? undefined
mx.getDeviceId() ?? undefined,
);
const [logoutState, logout] = useAsyncCallback<void, Error, []>(
useCallback(async () => {
await logoutClient(mx);
}, [mx])
}, [mx]),
);
const ongoingLogout = logoutState.status === AsyncStatus.Loading;
@@ -85,5 +85,5 @@ export const LogoutDialog = forwardRef<HTMLDivElement, LogoutDialogProps>(
</Box>
</Dialog>
);
}
},
);
+4 -4
View File
@@ -1,7 +1,7 @@
import React, { MouseEventHandler, ReactNode, useCallback, useState } from 'react';
import { Box, Text, Chip, RectCords, PopOut, Menu, config, MenuItem, color } from 'folds';
import { Icon, Icons } from './icons';
import FocusTrap from 'focus-trap-react';
import { Icon, Icons } from './icons';
import { stopPropagation } from '../utils/keyboard';
import { SettingTile } from './setting-tile';
import { SecretStorageKeyContent } from '../../types/matrix/accountData';
@@ -115,7 +115,7 @@ export function ManualVerificationTile({
const [method, setMethod] = useState(
hasPassphrase
? ManualVerificationMethod.RecoveryPassphrase
: ManualVerificationMethod.RecoveryKey
: ManualVerificationMethod.RecoveryKey,
);
const verifyAndRestoreBackup = useCallback(
@@ -132,11 +132,11 @@ export function ManualVerificationTile({
await crypto.loadSessionBackupPrivateKeyFromSecretStorage();
},
[mx, secretStorageKeyId]
[mx, secretStorageKeyId],
);
const [verifyState, handleDecodedRecoveryKey] = useAsyncCallback<void, Error, [Uint8Array]>(
verifyAndRestoreBackup
verifyAndRestoreBackup,
);
const verifying = verifyState.status === AsyncStatus.Loading;
+19 -6
View File
@@ -1,10 +1,23 @@
/* eslint-disable no-param-reassign */
/* eslint-disable jsx-a11y/no-noninteractive-element-interactions */
import React, { FormEventHandler, MouseEventHandler, useEffect, useRef, useState } from 'react';
import classNames from 'classnames';
import { Box, Button, Chip, Header, IconButton, Input, Menu, PopOut, RectCords, Scroll, Spinner, Text, as, config } from 'folds';
import { Icon, Icons } from '../icons';
import {
Box,
Button,
Chip,
Header,
IconButton,
Input,
Menu,
PopOut,
RectCords,
Scroll,
Spinner,
Text,
as,
config,
} from 'folds';
import FocusTrap from 'focus-trap-react';
import { Icon, Icons } from '../icons';
import { saveMediaBlob } from '../../utils/saveMedia';
import * as css from './PdfViewer.css';
import { AsyncStatus } from '../../hooks/useAsyncCallback';
@@ -27,7 +40,7 @@ export const PdfViewer = as<'div', PdfViewerProps>(
const [pdfJSState, loadPdfJS] = usePdfJSLoader();
const [docState, loadPdfDocument] = usePdfDocumentLoader(
pdfJSState.status === AsyncStatus.Success ? pdfJSState.data : undefined,
src
src,
);
const isLoading =
pdfJSState.status === AsyncStatus.Loading || docState.status === AsyncStatus.Loading;
@@ -247,5 +260,5 @@ export const PdfViewer = as<'div', PdfViewerProps>(
)}
</Box>
);
}
},
);
+39 -29
View File
@@ -25,7 +25,16 @@ import {
VideoContent,
VideoFrameThumbnail,
} from './message';
import { UrlPreviewCard, UrlPreviewHolder, YouTubeEmbed, isYouTubeUrl, TikTokEmbed, isTikTokUrl, GiphyEmbed, isGiphyUrl } from './url-preview';
import {
UrlPreviewCard,
UrlPreviewHolder,
YouTubeEmbed,
isYouTubeUrl,
TikTokEmbed,
isTikTokUrl,
GiphyEmbed,
isGiphyUrl,
} from './url-preview';
import { Image, MediaControl, Video } from './media';
import { ImageViewer } from './image-viewer';
import { VideoViewer } from './video-viewer';
@@ -53,7 +62,7 @@ type RenderMessageContentProps = {
onJumboEmojiClick?: (
targetEventId: string,
body: string,
event: MouseEvent<HTMLElement> | KeyboardEvent<HTMLElement>
event: MouseEvent<HTMLElement> | KeyboardEvent<HTMLElement>,
) => void;
};
export function RenderMessageContent({
@@ -81,7 +90,9 @@ export function RenderMessageContent({
const youtubeUrls = filteredUrls.filter(isYouTubeUrl);
const tiktokUrls = filteredUrls.filter(isTikTokUrl);
const giphyUrls = filteredUrls.filter(isGiphyUrl);
const otherUrls = filteredUrls.filter((url) => !isYouTubeUrl(url) && !isTikTokUrl(url) && !isGiphyUrl(url));
const otherUrls = filteredUrls.filter(
(url) => !isYouTubeUrl(url) && !isTikTokUrl(url) && !isGiphyUrl(url),
);
return (
<>
@@ -275,8 +286,9 @@ export function RenderMessageContent({
content={getContent()}
renderAsFile={renderFile}
renderVideoContent={({ body, info, mimeType, url, encInfo, ...props }) => {
const hasValidThumbnail =
(typeof info.thumbnail_file?.url === 'string' || typeof info.thumbnail_url === 'string') &&
const hasValidThumbnail =
(typeof info.thumbnail_file?.url === 'string' ||
typeof info.thumbnail_url === 'string') &&
typeof info.thumbnail_info?.mimetype === 'string';
return (
@@ -290,23 +302,24 @@ export function RenderMessageContent({
{...props}
renderThumbnail={
mediaAutoLoad
? () => hasValidThumbnail ? (
<ThumbnailContent
info={info}
renderImage={(src) => (
<Image alt={body} title={body} src={src} loading="lazy" />
)}
/>
) : (
<VideoFrameThumbnail
mimeType={mimeType}
url={url}
encInfo={encInfo}
renderImage={(src) => (
<Image alt={body} title={body} src={src} loading="lazy" />
)}
/>
)
? () =>
hasValidThumbnail ? (
<ThumbnailContent
info={info}
renderImage={(src) => (
<Image alt={body} title={body} src={src} loading="lazy" />
)}
/>
) : (
<VideoFrameThumbnail
mimeType={mimeType}
url={url}
encInfo={encInfo}
renderImage={(src) => (
<Image alt={body} title={body} src={src} loading="lazy" />
)}
/>
)
: undefined
}
renderViewer={(p) => <VideoViewer {...p} />}
@@ -360,13 +373,10 @@ export function RenderMessageContent({
};
console.log('[RenderMessageContent] Calling customRenderer with msgtype:', msgType);
console.log('[RenderMessageContent] messageData:', messageData);
const customContent = customRenderer(
messageData,
() => {
console.log('[RenderMessageContent] defaultRenderer called');
return null;
}
);
const customContent = customRenderer(messageData, () => {
console.log('[RenderMessageContent] defaultRenderer called');
return null;
});
console.log('[RenderMessageContent] customRenderer returned:', customContent);
console.log('[RenderMessageContent] customContent type:', typeof customContent);
if (customContent) {
@@ -1,7 +1,7 @@
import { Box, config, Menu, MenuItem, PopOut, RectCords, Text } from 'folds';
import { Icon } from './icons';
import React, { MouseEventHandler, ReactNode, useMemo, useState } from 'react';
import FocusTrap from 'focus-trap-react';
import { Icon } from './icons';
import { stopPropagation } from '../utils/keyboard';
import {
getRoomNotificationModeIcon,
@@ -18,7 +18,7 @@ const useRoomNotificationModes = (): RoomNotificationMode[] =>
RoomNotificationMode.SpecialMessages,
RoomNotificationMode.Mute,
],
[]
[],
);
const useRoomNotificationModeStr = (): Record<RoomNotificationMode, string> =>
@@ -29,7 +29,7 @@ const useRoomNotificationModeStr = (): Record<RoomNotificationMode, string> =>
[RoomNotificationMode.SpecialMessages]: 'Mention & Keywords',
[RoomNotificationMode.Mute]: 'Mute',
}),
[]
[],
);
type NotificationModeSwitcherProps = {
@@ -38,7 +38,7 @@ type NotificationModeSwitcherProps = {
children: (
handleOpen: MouseEventHandler<HTMLButtonElement>,
opened: boolean,
changing: boolean
changing: boolean,
) => ReactNode;
};
export function RoomNotificationModeSwitcher({
+6 -5
View File
@@ -88,11 +88,12 @@ export function RouteTransition({ children }: RouteTransitionProps) {
};
}, [location, displayLocation]);
const className = transitionStage === 'entering'
? `${transitionContent} ${animateIn}`
: transitionStage === 'exiting'
? `${transitionContent} ${animateOut}`
: transitionContent;
const className =
transitionStage === 'entering'
? `${transitionContent} ${animateIn}`
: transitionStage === 'exiting'
? `${transitionContent} ${animateOut}`
: transitionContent;
return (
<div className={transitionContainer}>
+5 -5
View File
@@ -36,7 +36,7 @@ export function SecretStorageRecoveryPassphrase({
passphrase,
salt,
iterations,
bits
bits,
);
const match = await mx.secretStorage.checkKey(decodedRecoveryKey, keyContent as any);
@@ -47,8 +47,8 @@ export function SecretStorageRecoveryPassphrase({
return decodedRecoveryKey;
},
[mx, keyContent]
)
[mx, keyContent],
),
);
const drivingKey = driveKeyState.status === AsyncStatus.Loading;
@@ -139,8 +139,8 @@ export function SecretStorageRecoveryKey({
return decodedRecoveryKey;
},
[mx, keyContent]
)
[mx, keyContent],
),
);
const drivingKey = driveKeyState.status === AsyncStatus.Loading;
+1 -1
View File
@@ -44,7 +44,7 @@ export function ServerConfigsLoader({ children }: ServerConfigsLoaderProps) {
mediaConfig,
authMetadata: validatedAuthMetadata,
};
}, [mx])
}, [mx]),
);
const configs: ServerConfigs =
@@ -21,7 +21,7 @@ export function SpaceChildDirectsProvider({
const childDirects = useSpaceChildren(
allRoomsAtom,
spaceId,
useChildDirectScopeFactory(mx, mDirects, roomToParents)
useChildDirectScopeFactory(mx, mDirects, roomToParents),
);
return children(childDirects);
@@ -21,7 +21,7 @@ export function SpaceChildRoomsProvider({
const childRooms = useSpaceChildren(
allRoomsAtom,
spaceId,
useChildRoomScopeFactory(mx, mDirects, roomToParents)
useChildRoomScopeFactory(mx, mDirects, roomToParents),
);
return children(childRooms);
+2 -2
View File
@@ -15,7 +15,7 @@ export function SpecVersionsLoader({
children,
}: SpecVersionsLoaderProps) {
const [state, load] = useAsyncCallback(
useCallback(() => specVersions(fetch, baseUrl), [baseUrl])
useCallback(() => specVersions(fetch, baseUrl), [baseUrl]),
);
const [ignoreError, setIgnoreError] = useState(false);
@@ -38,6 +38,6 @@ export function SpecVersionsLoader({
? state.data
: {
versions: [],
}
},
);
}
+12 -2
View File
@@ -1,7 +1,17 @@
import React, { ReactNode } from 'react';
import { Overlay, OverlayBackdrop, Box, config, Text, TooltipProvider, Tooltip, Chip, IconButton } from 'folds';
import { Icons, Icon } from './icons';
import {
Overlay,
OverlayBackdrop,
Box,
config,
Text,
TooltipProvider,
Tooltip,
Chip,
IconButton,
} from 'folds';
import FocusTrap from 'focus-trap-react';
import { Icons, Icon } from './icons';
export type UIAFlowOverlayProps = {
currentStep: number;
@@ -1,7 +1,7 @@
import React, { useEffect, useState } from 'react';
import { Avatar, Box, MenuItem, Text, config } from 'folds';
import { Icon, Icons } from '../icons';
import { useAtomValue } from 'jotai';
import { Icon, Icons } from '../icons';
import { sessionsAtom, Session } from '../../state/sessions';
import { setLocalStorageItem } from '../../state/utils/atomWithLocalStorage';
import { getMxIdServer, mxcUrlToHttp } from '../../utils/matrix';
@@ -26,7 +26,7 @@ function OtherSessionAvatar({ session }: { session: Session }) {
try {
const res = await fetch(
`${session.baseUrl}/_matrix/client/v3/profile/${encodeURIComponent(session.userId)}`,
{ headers: { Authorization: `Bearer ${session.accessToken}` } }
{ headers: { Authorization: `Bearer ${session.accessToken}` } },
);
if (!res.ok) return;
const data = await res.json();
@@ -34,7 +34,7 @@ function OtherSessionAvatar({ session }: { session: Session }) {
const match = (data.avatar_url as string).match(/^mxc:\/\/([^/]+)\/(.+)$/);
if (match) {
setSrc(
`${session.baseUrl}/_matrix/media/v3/thumbnail/${match[1]}/${match[2]}?width=32&height=32&method=crop`
`${session.baseUrl}/_matrix/media/v3/thumbnail/${match[1]}/${match[2]}?width=32&height=32&method=crop`,
);
}
}
@@ -59,25 +59,25 @@ function OtherSessionAvatar({ session }: { session: Session }) {
const deleteAllMatrixDatabases = async (): Promise<void> => {
console.log('[AccountSwitcher] Deleting all Matrix IndexedDB databases...');
// List of known Matrix database names/patterns to delete
const dbsToDelete = [
'matrix-js-sdk::matrix-sdk-crypto', // Shared crypto store (causes conflicts)
'matrix-js-sdk::matrix-sdk-crypto', // Shared crypto store (causes conflicts)
];
// Try to get all databases if the API is available
try {
if ('databases' in indexedDB) {
const allDbs = await (indexedDB as any).databases();
const matrixDbs = allDbs
.map((db: any) => db.name)
.filter((name: string) =>
name && (
name.startsWith('matrix-js-sdk') ||
name.includes('@@') ||
name.startsWith('sync@@') ||
name.startsWith('crypto@@')
)
.filter(
(name: string) =>
name &&
(name.startsWith('matrix-js-sdk') ||
name.includes('@@') ||
name.startsWith('sync@@') ||
name.startsWith('crypto@@')),
);
dbsToDelete.push(...matrixDbs);
console.log('[AccountSwitcher] Found Matrix databases:', matrixDbs);
@@ -85,7 +85,7 @@ const deleteAllMatrixDatabases = async (): Promise<void> => {
} catch (e) {
console.warn('[AccountSwitcher] Could not enumerate databases:', e);
}
// Delete each database with timeout
const deletePromises = dbsToDelete.map(async (dbName) => {
try {
@@ -104,7 +104,7 @@ const deleteAllMatrixDatabases = async (): Promise<void> => {
resolve(); // Don't reject, reload will handle it
};
});
// Add 1-second timeout per database
const timeoutPromise = new Promise<void>((resolve) => {
setTimeout(() => {
@@ -112,13 +112,13 @@ const deleteAllMatrixDatabases = async (): Promise<void> => {
resolve();
}, 1000);
});
await Promise.race([deletePromise, timeoutPromise]);
} catch (error) {
console.warn(`[AccountSwitcher] Error deleting ${dbName}:`, error);
}
});
await Promise.all(deletePromises);
console.log('[AccountSwitcher] ✅ Database cleanup complete');
};
@@ -129,14 +129,14 @@ export function AccountSwitcher({ currentUserId }: AccountSwitcherProps) {
const useAuthentication = useMediaAuthentication();
const currentProfile = useUserProfile(currentUserId ?? '');
const currentAvatarUrl = currentProfile.avatarUrl
? mxcUrlToHttp(mx, currentProfile.avatarUrl, useAuthentication, 32, 32, 'crop') ?? undefined
? (mxcUrlToHttp(mx, currentProfile.avatarUrl, useAuthentication, 32, 32, 'crop') ?? undefined)
: undefined;
const handleSwitchAccount = async (session: Session) => {
if (session.userId === currentUserId) return;
console.log('[AccountSwitcher] Switching account from', currentUserId, 'to', session.userId);
// Stop the current client before switching
if (mx) {
console.log('[AccountSwitcher] Stopping current Matrix client...');
@@ -147,16 +147,16 @@ export function AccountSwitcher({ currentUserId }: AccountSwitcherProps) {
console.error('[AccountSwitcher] Error stopping client:', error);
}
}
// Set the new current session
setLocalStorageItem('currentSessionUserId', session.userId);
// Delete all Matrix databases to prevent conflicts
await deleteAllMatrixDatabases();
// Small delay to ensure cleanup is complete
await new Promise(resolve => setTimeout(resolve, 100));
await new Promise((resolve) => setTimeout(resolve, 100));
// Reload the page to initialize the new session
console.log('[AccountSwitcher] Reloading page...');
window.location.reload();
@@ -168,15 +168,18 @@ export function AccountSwitcher({ currentUserId }: AccountSwitcherProps) {
}
// Filter out other sessions (not current)
const otherSessions = sessions.filter(s => s.userId !== currentUserId);
const otherSessions = sessions.filter((s) => s.userId !== currentUserId);
const hasMultipleAccounts = sessions.length > 1;
return (
<Box direction="Column" gap="200">
<Text size="L400" style={{ paddingInline: config.space.S200, paddingBlock: config.space.S100 }}>
<Text
size="L400"
style={{ paddingInline: config.space.S200, paddingBlock: config.space.S100 }}
>
{hasMultipleAccounts ? 'Switch Account' : 'Accounts'}
</Text>
{/* Show current account */}
{currentUserId && (
<MenuItem
@@ -210,11 +213,11 @@ export function AccountSwitcher({ currentUserId }: AccountSwitcherProps) {
</Box>
</MenuItem>
)}
{/* Show other accounts if any */}
{otherSessions.map((session) => {
const server = getMxIdServer(session.userId);
return (
<MenuItem
key={session.userId}
@@ -16,7 +16,7 @@ export const AuthenticatedAvatarImage = forwardRef<HTMLImageElement, Authenticat
const authenticatedSrc = useAuthenticatedMediaUrl(src, useAuthentication);
return <AvatarImage ref={ref} {...props} src={authenticatedSrc} />;
}
},
);
AuthenticatedAvatarImage.displayName = 'AuthenticatedAvatarImage';
@@ -2,8 +2,7 @@ import React, { ImgHTMLAttributes, forwardRef, useEffect, useState } from 'react
import { useAuthenticatedMediaUrl } from '../../hooks/useAuthenticatedMediaUrl';
import { useMediaAuthentication } from '../../hooks/useMediaAuthentication';
export interface AuthenticatedMediaProps
extends Omit<ImgHTMLAttributes<HTMLImageElement>, 'src'> {
export interface AuthenticatedMediaProps extends Omit<ImgHTMLAttributes<HTMLImageElement>, 'src'> {
/** The source URL of the media (may be an authenticated media URL) */
src?: string;
/** Override for authentication - if not provided, uses useMediaAuthentication hook */
@@ -22,7 +21,7 @@ export const AuthenticatedMedia = forwardRef<HTMLImageElement, AuthenticatedMedi
const authenticatedSrc = useAuthenticatedMediaUrl(src, useAuthentication);
return <img ref={ref} {...props} src={authenticatedSrc} />;
}
},
);
AuthenticatedMedia.displayName = 'AuthenticatedMedia';
@@ -39,7 +38,7 @@ export const AuthenticatedImg = forwardRef<HTMLImageElement, AuthenticatedImgPro
const authenticatedSrc = useAuthenticatedMediaUrl(src, useAuthentication);
return <img ref={ref} {...props} src={authenticatedSrc} />;
}
},
);
AuthenticatedImg.displayName = 'AuthenticatedImg';
@@ -1,5 +1,18 @@
import { Box, Button, Chip, config, Input, Line, Menu, MenuItem, PopOut, RectCords, Scroll, Text, toRem } from 'folds';
import { Icon, Icons } from '../icons';
import {
Box,
Button,
Chip,
config,
Input,
Line,
Menu,
MenuItem,
PopOut,
RectCords,
Scroll,
Text,
toRem,
} from 'folds';
import { isKeyHotkey } from 'is-hotkey';
import FocusTrap from 'focus-trap-react';
import React, {
@@ -9,6 +22,7 @@ import React, {
useMemo,
useState,
} from 'react';
import { Icon, Icons } from '../icons';
import { getMxIdLocalPart, getMxIdServer, isUserId } from '../../utils/matrix';
import { useDirectUsers } from '../../hooks/useDirectUsers';
import { SettingTile } from '../setting-tile';
@@ -20,7 +34,7 @@ import { highlightText, makeHighlightRegex } from '../../plugins/react-custom-ht
export const useAdditionalCreators = (defaultCreators?: string[]) => {
const mx = useMatrixClient();
const [additionalCreators, setAdditionalCreators] = useState<string[]>(
() => defaultCreators?.filter((id) => id !== mx.getSafeUserId()) ?? []
() => defaultCreators?.filter((id) => id !== mx.getSafeUserId()) ?? [],
);
const addAdditionalCreator = (userId: string) => {
@@ -75,12 +89,12 @@ export function AdditionalCreatorInput({
const [validUserId, setValidUserId] = useState<string>();
const filteredUsers = useMemo(
() => directUsers.filter((userId) => !additionalCreators.includes(userId)),
[directUsers, additionalCreators]
[directUsers, additionalCreators],
);
const [result, search, resetSearch] = useAsyncSearch(
filteredUsers,
getUserIdString,
SEARCH_OPTIONS
SEARCH_OPTIONS,
);
const queryHighlighRegex = result?.query ? makeHighlightRegex([result.query]) : undefined;
@@ -8,8 +8,8 @@ import React, {
} from 'react';
import { MatrixError } from 'matrix-js-sdk';
import { Box, color, Input, Spinner, Text, toRem } from 'folds';
import { Icon, Icons } from '../icons';
import { isKeyHotkey } from 'is-hotkey';
import { Icon, Icons } from '../icons';
import { getMxIdServer } from '../../utils/matrix';
import { useMatrixClient } from '../../hooks/useMatrixClient';
import { replaceSpaceWithDash } from '../../utils/common';
@@ -43,9 +43,9 @@ export function CreateRoomAliasInput({ disabled }: { disabled?: boolean }) {
throw e;
}
},
[mx]
[mx],
),
setAliasAvail
setAliasAvail,
);
const aliasAvailable: boolean | undefined =
aliasAvail.status === AsyncStatus.Success ? aliasAvail.data : undefined;
@@ -1,7 +1,7 @@
import React, { MouseEventHandler, useState } from 'react';
import { Box, Button, Chip, config, Menu, PopOut, RectCords, Text, toRem } from 'folds';
import { Icon, Icons } from '../icons';
import FocusTrap from 'focus-trap-react';
import { Icon, Icons } from '../icons';
import { SettingTile } from '../setting-tile';
import { SequenceCard } from '../sequence-card';
import { stopPropagation } from '../../utils/keyboard';
+4 -4
View File
@@ -15,7 +15,7 @@ import { getMxIdServer } from '../../utils/matrix';
export const createRoomCreationContent = (
type: RoomType | undefined,
allowFederation: boolean,
additionalCreators: string[] | undefined
additionalCreators: string[] | undefined,
): object => {
const content: Record<string, any> = {};
if (typeof type === 'string') {
@@ -34,7 +34,7 @@ export const createRoomCreationContent = (
export const createRoomJoinRulesState = (
kind: CreateRoomKind,
parent: Room | undefined,
knock: boolean
knock: boolean,
) => {
let content: RoomJoinRulesEventContent = {
join_rule: knock ? JoinRule.Knock : JoinRule.Invite,
@@ -134,7 +134,7 @@ export const createRoom = async (mx: MatrixClient, data: CreateRoomData): Promis
creation_content: createRoomCreationContent(
data.type,
data.allowFederation,
data.additionalCreators
data.additionalCreators,
),
initial_state: initialState,
};
@@ -150,7 +150,7 @@ export const createRoom = async (mx: MatrixClient, data: CreateRoomData): Promis
suggested: false,
via: [getMxIdServer(mx.getUserId() ?? '') ?? ''],
},
result.room_id
result.room_id,
);
}
@@ -27,10 +27,10 @@ export interface CustomStatusDialogProps {
/**
* CustomStatusDialog Component
*
*
* Provides a dialog interface for users to set or clear their custom status message.
* The status is stored in Matrix presence and will be visible to other users.
*
*
* @param props - Component props
* @returns The custom status dialog component
*/
@@ -38,9 +38,9 @@ export function CustomStatusDialog({ open, onClose }: CustomStatusDialogProps) {
const mx = useMatrixClient();
const userId = mx.getUserId();
const presence = useUserPresence(userId ?? '');
const [statusText, setStatusText] = useState(presence?.status || '');
/**
* Handles input changes for the status text field
* @param evt - The change event from the input
@@ -48,7 +48,7 @@ export function CustomStatusDialog({ open, onClose }: CustomStatusDialogProps) {
const handleChange: ChangeEventHandler<HTMLInputElement> = (evt) => {
setStatusText(evt.currentTarget.value);
};
/**
* Async callback to save the status to Matrix presence
*/
@@ -59,9 +59,9 @@ export function CustomStatusDialog({ open, onClose }: CustomStatusDialogProps) {
status_msg: statusText,
});
onClose();
}, [mx, presence?.presence, statusText, onClose])
}, [mx, presence?.presence, statusText, onClose]),
);
/**
* Async callback to clear the status from Matrix presence
*/
@@ -73,9 +73,9 @@ export function CustomStatusDialog({ open, onClose }: CustomStatusDialogProps) {
});
setStatusText('');
onClose();
}, [mx, presence?.presence, onClose])
}, [mx, presence?.presence, onClose]),
);
/**
* Handles form submission to save the custom status
* @param evt - The form submit event
@@ -84,7 +84,7 @@ export function CustomStatusDialog({ open, onClose }: CustomStatusDialogProps) {
evt.preventDefault();
saveStatus();
};
/**
* Handles the clear status button click
*/
@@ -118,7 +118,7 @@ export function CustomStatusDialog({ open, onClose }: CustomStatusDialogProps) {
Your custom status will be visible to other users
</Text>
</Box>
<Box direction="Column" gap="200">
<Input
value={statusText}
@@ -126,7 +126,10 @@ export function CustomStatusDialog({ open, onClose }: CustomStatusDialogProps) {
placeholder="What's on your mind?"
maxLength={100}
autoFocus
disabled={saveState.status === AsyncStatus.Loading || clearState.status === AsyncStatus.Loading}
disabled={
saveState.status === AsyncStatus.Loading ||
clearState.status === AsyncStatus.Loading
}
/>
{statusText.length > 0 && (
<Text size="T200" priority="300">
@@ -135,7 +138,8 @@ export function CustomStatusDialog({ open, onClose }: CustomStatusDialogProps) {
)}
</Box>
{(saveState.status === AsyncStatus.Error || clearState.status === AsyncStatus.Error) && (
{(saveState.status === AsyncStatus.Error ||
clearState.status === AsyncStatus.Error) && (
<Text size="T300" priority="400" style={{ color: 'var(--color-critical-main)' }}>
Failed to update status. Please try again.
</Text>
@@ -146,7 +150,10 @@ export function CustomStatusDialog({ open, onClose }: CustomStatusDialogProps) {
type="button"
variant="Secondary"
onClick={onClose}
disabled={saveState.status === AsyncStatus.Loading || clearState.status === AsyncStatus.Loading}
disabled={
saveState.status === AsyncStatus.Loading ||
clearState.status === AsyncStatus.Loading
}
>
<Text size="B400">Cancel</Text>
</Button>
@@ -156,7 +163,10 @@ export function CustomStatusDialog({ open, onClose }: CustomStatusDialogProps) {
variant="Critical"
fill="None"
onClick={handleClear}
disabled={saveState.status === AsyncStatus.Loading || clearState.status === AsyncStatus.Loading}
disabled={
saveState.status === AsyncStatus.Loading ||
clearState.status === AsyncStatus.Loading
}
>
<Text size="B400">Clear Status</Text>
</Button>
@@ -164,7 +174,10 @@ export function CustomStatusDialog({ open, onClose }: CustomStatusDialogProps) {
<Button
type="submit"
variant="Primary"
disabled={saveState.status === AsyncStatus.Loading || clearState.status === AsyncStatus.Loading}
disabled={
saveState.status === AsyncStatus.Loading ||
clearState.status === AsyncStatus.Loading
}
>
<Text size="B400">
{saveState.status === AsyncStatus.Loading ? 'Saving...' : 'Save'}
@@ -11,5 +11,5 @@ export const CutoutCard = as<'div', { variant?: TContainerColor }>(
{...props}
ref={ref}
/>
)
),
);
+19 -7
View File
@@ -1,10 +1,22 @@
import React, { MouseEventHandler, forwardRef, useMemo, useState } from 'react';
import { useAtom, useAtomValue } from 'jotai';
import { Avatar, Box, Button, IconButton, Menu, MenuItem, PopOut, RectCords, Text, config, toRem } from 'folds';
import { Icon, Icons } from '../icons';
import {
Avatar,
Box,
Button,
IconButton,
Menu,
MenuItem,
PopOut,
RectCords,
Text,
config,
toRem,
} from 'folds';
import { useVirtualizer } from '@tanstack/react-virtual';
import FocusTrap from 'focus-trap-react';
import { useNavigate } from 'react-router-dom';
import { Icon, Icons } from '../icons';
import { useMatrixClient } from '../../hooks/useMatrixClient';
import { factoryRoomIdByActivity } from '../../utils/sort';
import {
@@ -202,7 +214,7 @@ export function DirectList({
const createDirectSelected = useDirectCreateSelected();
const selectedRoomId = useSelectedRoom();
const [closedCategories, setClosedCategories] = useAtom(useClosedNavCategoriesAtom());
const reorderTrigger = useRoomListReorder(mx, directs);
const sortedDirects = useMemo(() => {
@@ -223,7 +235,7 @@ export function DirectList({
});
const handleCategoryClick = useCategoryHandler(setClosedCategories, (categoryId) =>
closedCategories.has(categoryId)
closedCategories.has(categoryId),
);
const noRoomToDisplay = directs.length === 0;
@@ -280,9 +292,9 @@ export function DirectList({
const selected = selectedRoomId === roomId;
return (
<VirtualTile
virtualItem={vItem}
key={roomId}
<VirtualTile
virtualItem={vItem}
key={roomId}
ref={virtualizer.measureElement}
data-room-id={roomId}
>
+54 -51
View File
@@ -8,7 +8,13 @@ import React, {
useState,
} from 'react';
import { Box, Scroll, Text } from 'folds';
import { Descendant, Editor, createEditor, Element as SlateElement, Text as SlateText } from 'slate';
import {
Descendant,
Editor,
createEditor,
Element as SlateElement,
Text as SlateText,
} from 'slate';
import {
Slate,
Editable,
@@ -37,7 +43,7 @@ const withInline = (editor: Editor): Editor => {
editor.isInline = (element) =>
[BlockType.Mention, BlockType.Emoticon, BlockType.Link, BlockType.Command].includes(
element.type
element.type,
) || isInline(element);
return editor;
@@ -61,16 +67,15 @@ export const setCommandValidator = (validator: CommandValidatorFn) => {
commandValidator = validator;
};
const withCommandAutoConvert = (editor: Editor): Editor => {
const withCommandAutoConvert = (editor: Editor): Editor =>
// Removed auto-conversion on space to prevent focus issues
// Commands are now highlighted visually via decorations
// and executed when Enter is pressed
return editor;
};
editor;
export const useEditor = (): Editor => {
const [editor] = useState(() =>
withCommandAutoConvert(withInline(withVoid(withReact(withHistory(createEditor())))))
const [editor] = useState(() =>
withCommandAutoConvert(withInline(withVoid(withReact(withHistory(createEditor()))))),
);
return editor;
};
@@ -109,57 +114,55 @@ export const CustomEditor = forwardRef<HTMLDivElement, CustomEditorProps>(
onChange,
onPaste,
},
ref
ref,
) => {
const renderElement = useCallback(
(props: RenderElementProps) => <RenderElement {...props} />,
[]
[],
);
const renderLeaf = useCallback((props: RenderLeafProps) => <RenderLeaf {...props} />, []);
const decorate = useCallback(([node, path]: [any, number[]]) => {
const ranges: any[] = [];
// Only decorate text nodes in the first paragraph
if (
path.length === 2 &&
path[0] === 0 &&
path[1] === 0 &&
SlateText.isText(node)
) {
const firstChild = editor.children[0];
if (SlateElement.isElement(firstChild) && firstChild.type === BlockType.Paragraph) {
const [firstInline, secondInline] = firstChild.children;
// Don't decorate if we already have a CommandElement
if (SlateElement.isElement(secondInline) && secondInline.type === BlockType.Command) {
return ranges;
}
// Check if the text matches /command pattern
const text = node.text;
const match = text.match(/^(\s*\/\w+)/);
if (match && commandValidator) {
const commandText = match[1].trim();
const commandName = commandText.substring(1);
if (commandValidator(commandName)) {
// Create decoration for the command text
ranges.push({
anchor: { path, offset: 0 },
focus: { path, offset: match[1].length },
pendingCommand: true,
});
const decorate = useCallback(
([node, path]: [any, number[]]) => {
const ranges: any[] = [];
// Only decorate text nodes in the first paragraph
if (path.length === 2 && path[0] === 0 && path[1] === 0 && SlateText.isText(node)) {
const firstChild = editor.children[0];
if (SlateElement.isElement(firstChild) && firstChild.type === BlockType.Paragraph) {
const [firstInline, secondInline] = firstChild.children;
// Don't decorate if we already have a CommandElement
if (SlateElement.isElement(secondInline) && secondInline.type === BlockType.Command) {
return ranges;
}
// Check if the text matches /command pattern
const { text } = node;
const match = text.match(/^(\s*\/\w+)/);
if (match && commandValidator) {
const commandText = match[1].trim();
const commandName = commandText.substring(1);
if (commandValidator(commandName)) {
// Create decoration for the command text
ranges.push({
anchor: { path, offset: 0 },
focus: { path, offset: match[1].length },
pendingCommand: true,
});
}
}
}
}
}
return ranges;
}, [editor]);
return ranges;
},
[editor],
);
const handleKeydown: KeyboardEventHandler = useCallback(
(evt) => {
@@ -167,7 +170,7 @@ export const CustomEditor = forwardRef<HTMLDivElement, CustomEditorProps>(
const shortcutToggled = toggleKeyboardShortcut(editor, evt);
if (shortcutToggled) evt.preventDefault();
},
[editor, onKeyDown]
[editor, onKeyDown],
);
const renderPlaceholder = useCallback(
@@ -179,7 +182,7 @@ export const CustomEditor = forwardRef<HTMLDivElement, CustomEditorProps>(
</Text>
</span>
),
[]
[],
);
const scrollStyle = fillHeight
@@ -239,5 +242,5 @@ export const CustomEditor = forwardRef<HTMLDivElement, CustomEditorProps>(
</Slate>
</div>
);
}
},
);
+16 -2
View File
@@ -1,8 +1,22 @@
import FocusTrap from 'focus-trap-react';
import { Badge, Box, config, IconButton, Line, Menu, PopOut, RectCords, Scroll, Text, Tooltip, TooltipProvider, toRem } from 'folds';
import { Icon, Icons, IconSrc } from '../icons';
import {
Badge,
Box,
config,
IconButton,
Line,
Menu,
PopOut,
RectCords,
Scroll,
Text,
Tooltip,
TooltipProvider,
toRem,
} from 'folds';
import React, { MouseEventHandler, ReactNode, useState } from 'react';
import { ReactEditor, useSlate } from 'slate-react';
import { Icon, Icons, IconSrc } from '../icons';
import {
headingLevel,
isAnyMarkActive,
@@ -51,14 +51,14 @@ export function EmoticonAutocomplete({
const list: Array<EmoticonSearchItem> = [];
return list.concat(
imagePacks.flatMap((pack) => pack.getImages(ImageUsage.Emoticon)),
emojis
emojis,
);
}, [imagePacks]);
const [result, search, resetSearch] = useAsyncSearch(
searchList,
getEmoticonSearchStr,
SEARCH_OPTIONS
SEARCH_OPTIONS,
);
const autoCompleteEmoticon = result ? result.items.slice(0, 20) : recentEmoji;
@@ -1,9 +1,9 @@
import React, { KeyboardEvent as ReactKeyboardEvent, useCallback, useEffect } from 'react';
import { Editor } from 'slate';
import { Avatar, MenuItem, Text } from 'folds';
import { Icon, Icons } from '../../icons';
import { JoinRule, MatrixClient } from 'matrix-js-sdk';
import { useAtomValue } from 'jotai';
import { Icon, Icons } from '../../icons';
import { createMentionElement, moveCursor, replaceWithElement } from '../utils';
import { getDirectRoomAvatarUrl, guessPerfectParent } from '../../../utils/room';
@@ -94,9 +94,9 @@ export function RoomMentionAutocomplete({
if (alias) return [r.name, alias];
return r.name;
},
[mx]
[mx],
),
SEARCH_OPTIONS
SEARCH_OPTIONS,
);
const autoCompleteRoomIds = result ? result.items.slice(0, 20) : allRooms.slice(0, 20);
@@ -107,40 +107,43 @@ export function RoomMentionAutocomplete({
}, [query.text, search, resetSearch]);
// Build space hierarchy path for a room
const getSpacePath = useCallback((rId: string): string | null => {
// Skip DMs
if (mDirects.has(rId)) return null;
const buildParentChain = (currentRoomId: string): string[] => {
const parents = roomToParents.get(currentRoomId);
if (!parents || parents.size === 0) {
return [];
}
const parentsList = Array.from(parents);
let chosenParent: string;
if (parentsList.length === 1) {
chosenParent = parentsList[0];
} else {
const orphanParents = parentsList.filter(p => !roomToParents.has(p));
if (orphanParents.length > 0) {
chosenParent = guessPerfectParent(mx, currentRoomId, orphanParents) ?? orphanParents[0];
} else {
chosenParent = parentsList[0];
const getSpacePath = useCallback(
(rId: string): string | null => {
// Skip DMs
if (mDirects.has(rId)) return null;
const buildParentChain = (currentRoomId: string): string[] => {
const parents = roomToParents.get(currentRoomId);
if (!parents || parents.size === 0) {
return [];
}
}
const parentRoom = mx.getRoom(chosenParent);
if (!parentRoom?.name) return [];
const upperChain = buildParentChain(chosenParent);
return [...upperChain, parentRoom.name];
};
const parentChain = buildParentChain(rId);
return parentChain.length > 0 ? parentChain.join(' > ') : null;
}, [mx, mDirects, roomToParents]);
const parentsList = Array.from(parents);
let chosenParent: string;
if (parentsList.length === 1) {
chosenParent = parentsList[0];
} else {
const orphanParents = parentsList.filter((p) => !roomToParents.has(p));
if (orphanParents.length > 0) {
chosenParent = guessPerfectParent(mx, currentRoomId, orphanParents) ?? orphanParents[0];
} else {
chosenParent = parentsList[0];
}
}
const parentRoom = mx.getRoom(chosenParent);
if (!parentRoom?.name) return [];
const upperChain = buildParentChain(chosenParent);
return [...upperChain, parentRoom.name];
};
const parentChain = buildParentChain(rId);
return parentChain.length > 0 ? parentChain.join(' > ') : null;
},
[mx, mDirects, roomToParents],
);
const handleAutocomplete: MentionAutoCompleteHandler = (roomAliasOrId, name) => {
const mentionRoom = mx.getRoom(roomAliasOrId);
@@ -150,7 +153,7 @@ export function RoomMentionAutocomplete({
name.startsWith('#') ? name : `#${name}`,
roomId === roomAliasOrId || mx.getRoom(roomId)?.getCanonicalAlias() === roomAliasOrId,
undefined,
viaServers
viaServers,
);
replaceWithElement(editor, query.range, mentionEl);
moveCursor(editor, true);
@@ -1,8 +1,8 @@
import React, { useEffect, KeyboardEvent as ReactKeyboardEvent } from 'react';
import { Editor } from 'slate';
import { Avatar, MenuItem, Text } from 'folds';
import { Icon, Icons } from '../../icons';
import { MatrixClient, Room, RoomMember } from 'matrix-js-sdk';
import { Icon, Icons } from '../../icons';
import { AutocompleteQuery } from './autocompleteQuery';
import { AutocompleteMenu } from './AutocompleteMenu';
@@ -99,7 +99,7 @@ export function UserMentionAutocomplete({
const [result, search, resetSearch] = useAsyncSearch(members, getRoomMemberStr, SEARCH_OPTIONS);
const autoCompleteMembers = (result ? result.items.slice(0, 20) : members.slice(0, 20)).filter(
withAllowedMembership
withAllowedMembership,
);
useEffect(() => {
@@ -111,7 +111,7 @@ export function UserMentionAutocomplete({
const mentionEl = createMentionElement(
uId,
name.startsWith('@') ? name : `@${name}`,
mx.getUserId() === uId || roomAliasOrId === uId
mx.getUserId() === uId || roomAliasOrId === uId,
);
replaceWithElement(editor, query.range, mentionEl);
moveCursor(editor, true);
@@ -22,7 +22,7 @@ export type AutocompleteQuery<TPrefix extends string> = {
export const getAutocompletePrefix = <TPrefix extends string>(
editor: Editor,
queryRange: BaseRange,
validPrefixes: readonly TPrefix[]
validPrefixes: readonly TPrefix[],
): TPrefix | undefined => {
const world = Editor.string(editor, queryRange);
return validPrefixes.find((p) => world.startsWith(p));
@@ -31,13 +31,13 @@ export const getAutocompletePrefix = <TPrefix extends string>(
export const getAutocompleteQueryText = (
editor: Editor,
queryRange: BaseRange,
prefix: string
prefix: string,
): string => Editor.string(editor, queryRange).slice(prefix.length);
export const getAutocompleteQuery = <TPrefix extends string>(
editor: Editor,
queryRange: BaseRange,
validPrefixes: readonly TPrefix[]
validPrefixes: readonly TPrefix[],
): AutocompleteQuery<TPrefix> | undefined => {
const prefix = getAutocompletePrefix(editor, queryRange, validPrefixes);
if (!prefix) return undefined;
+8 -8
View File
@@ -77,7 +77,7 @@ const getInlineNodeMarkType = (node: Element): MarkType | undefined => {
const getInlineMarkElement = (
markType: MarkType,
node: Element,
getChild: (child: ChildNode) => InlineElement[]
getChild: (child: ChildNode) => InlineElement[],
): InlineElement[] => {
const children = node.children.flatMap(getChild);
const mdSequence = node.attribs['data-md'];
@@ -115,7 +115,7 @@ const getInlineNonMarkElement = (node: Element): MentionElement | EmoticonElemen
getText(node) || roomMention.roomIdOrAlias,
false,
undefined,
roomMention.viaServers
roomMention.viaServers,
);
}
const eventMention = parseMatrixToRoomEvent(href);
@@ -125,7 +125,7 @@ const getInlineNonMarkElement = (node: Element): MentionElement | EmoticonElemen
getText(node) || eventMention.roomIdOrAlias,
false,
eventMention.eventId,
eventMention.viaServers
eventMention.viaServers,
);
}
}
@@ -165,7 +165,7 @@ const getInlineElement = (node: ChildNode, processText: ProcessTextCallback): In
const parseBlockquoteNode = (
node: Element,
processText: ProcessTextCallback
processText: ProcessTextCallback,
): BlockQuoteElement[] | ParagraphElement[] => {
const quoteLines: Array<InlineElement[]> = [];
let lineHolder: InlineElement[] = [];
@@ -229,7 +229,7 @@ const parseCodeBlockNode = (node: Element): CodeBlockElement[] | ParagraphElemen
}));
const childCode = node.children[0];
const className =
isTag(childCode) && childCode.tagName === 'code' ? childCode.attribs.class ?? '' : '';
isTag(childCode) && childCode.tagName === 'code' ? (childCode.attribs.class ?? '') : '';
const prefix = { text: `${mdSequence}${className.replace('language-', '')}` };
const suffix = { text: mdSequence };
return [
@@ -251,7 +251,7 @@ const parseCodeBlockNode = (node: Element): CodeBlockElement[] | ParagraphElemen
};
const parseListNode = (
node: Element,
processText: ProcessTextCallback
processText: ProcessTextCallback,
): OrderedListElement[] | UnorderedListElement[] | ParagraphElement[] => {
const listLines: Array<InlineElement[]> = [];
let lineHolder: InlineElement[] = [];
@@ -323,7 +323,7 @@ const parseListNode = (
};
const parseHeadingNode = (
node: Element,
processText: ProcessTextCallback
processText: ProcessTextCallback,
): HeadingElement | ParagraphElement => {
const children = node.children.flatMap((child) => getInlineElement(child, processText));
@@ -349,7 +349,7 @@ const parseHeadingNode = (
export const domToEditorInput = (
domNodes: ChildNode[],
processText: ProcessTextCallback,
processLineStartText: ProcessTextCallback
processLineStartText: ProcessTextCallback,
): Descendant[] => {
const children: Descendant[] = [];
+3 -3
View File
@@ -74,7 +74,7 @@ const elementToCustomHtml = (node: CustomElement, children: string): string => {
case BlockType.Emoticon:
return node.key.startsWith('mxc://')
? `<img data-mx-emoticon src="${node.key}" alt="${sanitizeText(
node.shortcode
node.shortcode,
)}" title="${sanitizeText(node.shortcode)}" height="32" />`
: sanitizeText(node.key);
case BlockType.Link:
@@ -92,12 +92,12 @@ const ignoreHTMLParseInlineMD = (text: string): string =>
text,
HTML_TAG_REG_G,
(match) => match[0],
(txt) => parseInlineMD(txt)
(txt) => parseInlineMD(txt),
).join('');
export const toMatrixCustomHTML = (
node: Descendant | Descendant[],
opts: OutputOptions
opts: OutputOptions,
): string => {
let markdownLines = '';
const parseNode = (n: Descendant, index: number, targetNodes: Descendant[]) => {
+3 -3
View File
@@ -161,7 +161,7 @@ export const createMentionElement = (
name: string,
highlight: boolean,
eventId?: string,
viaServers?: string[]
viaServers?: string[],
): MentionElement => ({
type: BlockType.Mention,
id,
@@ -181,7 +181,7 @@ export const createEmoticonElement = (key: string, shortcode: string): EmoticonE
export const createLinkElement = (
href: string,
children: string | FormattedText[]
children: string | FormattedText[],
): LinkElement => ({
type: BlockType.Link,
href,
@@ -237,7 +237,7 @@ interface PointUntilCharOptions {
export const getPointUntilChar = (
editor: Editor,
cursorPoint: BasePoint,
options: PointUntilCharOptions
options: PointUntilCharOptions,
): BasePoint | undefined => {
let targetPoint: BasePoint | undefined;
let prevPoint: BasePoint | undefined;
+9 -12
View File
@@ -10,12 +10,12 @@ import React, {
useRef,
} from 'react';
import { Box, config, Scroll } from 'folds';
import { Icons } from '../icons';
import FocusTrap from 'focus-trap-react';
import { isKeyHotkey } from 'is-hotkey';
import { Room } from 'matrix-js-sdk';
import { atom, PrimitiveAtom, useAtom, useSetAtom } from 'jotai';
import { useVirtualizer } from '@tanstack/react-virtual';
import { Icons } from '../icons';
import { IEmoji, emojiGroups, emojis } from '../../plugins/emoji';
import { useEmojiGroupLabels } from './useEmojiGroupLabels';
import { useEmojiGroupIcons } from './useEmojiGroupIcons';
@@ -71,7 +71,7 @@ type StickerGroupItem = {
const useGroups = (
tab: EmojiBoardTab,
imagePacks: ImagePack[]
imagePacks: ImagePack[],
): [EmojiGroupItem[], StickerGroupItem[]] => {
const mx = useMatrixClient();
const { getTopEmojis } = useEmojiUsage();
@@ -88,7 +88,7 @@ const useGroups = (
const mostUsedEmojis = topShortcodes
.map((shortcode) => emojis.find((e) => e.shortcode === shortcode))
.filter((e): e is IEmoji => e !== undefined);
if (mostUsedEmojis.length > 0) {
g.push({
id: MOST_USED_GROUP_ID,
@@ -320,7 +320,7 @@ function EmojiGroupHolder({
shortcode: emojiInfo.shortcode,
});
},
[setPreviewData]
[setPreviewData],
);
const throttleEmojiHover = useThrottle(handleEmojiPreview, {
@@ -398,7 +398,7 @@ export function EmojiBoard({
// Get default emoji - use most used or fallback to slight_smile
const defaultPreview = useMemo((): PreviewData => {
if (!emojiTab) return undefined;
const mostUsedShortcode = getMostUsedEmoji();
if (mostUsedShortcode) {
// Find emoji by shortcode
@@ -411,10 +411,7 @@ export function EmojiBoard({
return DefaultEmojiPreview;
}, [emojiTab, getMostUsedEmoji]);
const previewAtom = useMemo(
() => createPreviewDataAtom(defaultPreview),
[defaultPreview]
);
const previewAtom = useMemo(() => createPreviewDataAtom(defaultPreview), [defaultPreview]);
const activeGroupIdAtom = useMemo(() => atom<string | undefined>(undefined), []);
const setActiveGroupId = useSetAtom(activeGroupIdAtom);
const imagePacks = useRelevantImagePacks(usage, imagePackRooms);
@@ -432,7 +429,7 @@ export function EmojiBoard({
const [result, search, resetSearch] = useAsyncSearch(
searchList,
getEmoticonSearchStr,
SEARCH_OPTIONS
SEARCH_OPTIONS,
);
const searchedItems = result?.items.slice(0, 100);
@@ -444,9 +441,9 @@ export function EmojiBoard({
if (term) search(term);
else resetSearch();
},
[search, resetSearch]
[search, resetSearch],
),
{ wait: 200 }
{ wait: 200 },
);
const contentScrollRef = useRef<HTMLDivElement>(null);
@@ -2,6 +2,7 @@ import React from 'react';
import { Box, toRem, config, Text } from 'folds';
import { Icons, Icon } from '../../icons';
export function NoStickerPacks() {
return (
<Box
@@ -1,7 +1,7 @@
import React, { ReactNode } from 'react';
import { Box, Scroll, Line, as, TooltipProvider, Tooltip, Text, IconButton } from 'folds';
import { Icon, IconSrc, Icons } from '../../icons';
import classNames from 'classnames';
import { Icon, IconSrc, Icons } from '../../icons';
import * as css from './styles.css';
export function Sidebar({ children }: { children: ReactNode }) {
@@ -1,6 +1,5 @@
import { IconSrc, Icons } from '../icons';
import { useMemo } from 'react';
import { IconSrc, Icons } from '../icons';
import { EmojiGroupId } from '../../plugins/emoji';
@@ -18,5 +17,5 @@ export const useEmojiGroupIcons = (): IEmojiGroupIcons =>
[EmojiGroupId.Symbol]: Icons.Peace,
[EmojiGroupId.Flag]: Icons.Flag,
}),
[]
[],
);
@@ -15,5 +15,5 @@ export const useEmojiGroupLabels = (): IEmojiGroupLabels =>
[EmojiGroupId.Symbol]: 'Symbols',
[EmojiGroupId.Flag]: 'Flags',
}),
[]
[],
);
@@ -1,8 +1,8 @@
import React from 'react';
import classNames from 'classnames';
import { Avatar, Box, Header, IconButton, MenuItem, Scroll, Text, as, config } from 'folds';
import { Icon, Icons } from '../icons';
import { Room } from 'matrix-js-sdk';
import { Icon, Icons } from '../icons';
import { useRoomEventReaders } from '../../hooks/useRoomEventReaders';
import { getMemberDisplayName } from '../../utils/room';
import { getMxIdLocalPart } from '../../utils/matrix';
@@ -59,7 +59,7 @@ export const EventReaders = as<'div', EventReadersProps>(
'crop',
undefined,
false,
useAuthentication
useAuthentication,
)
: undefined;
@@ -74,7 +74,7 @@ export const EventReaders = as<'div', EventReadersProps>(
space?.roomId,
readerId,
getMouseEventCords(event.nativeEvent),
'Bottom'
'Bottom',
);
}}
before={
@@ -99,5 +99,5 @@ export const EventReaders = as<'div', EventReadersProps>(
</Box>
</Box>
);
}
},
);
+6 -3
View File
@@ -15,7 +15,10 @@ export type IconProps = {
} & Omit<React.SVGAttributes<SVGSVGElement>, 'fill'>;
export const Icon = forwardRef<SVGSVGElement, IconProps>(
({ className, size = '400', filled = false, src: LucideIconComponent, style, fill, ...props }, ref) => {
(
{ className, size = '400', filled = false, src: LucideIconComponent, style, fill, ...props },
ref,
) => {
const pixelSize = ICON_PIXEL_SIZES[size];
return (
@@ -33,11 +36,11 @@ export const Icon = forwardRef<SVGSVGElement, IconProps>(
// Emphasize selection with a heavier stroke instead.
strokeWidth={filled ? 2.75 : 2}
fill={fill ?? 'none'}
aria-hidden={props['aria-hidden'] ?? props['aria-label'] ? undefined : true}
aria-hidden={(props['aria-hidden'] ?? props['aria-label']) ? undefined : true}
{...props}
/>
);
}
},
);
Icon.displayName = 'Icon';
@@ -48,5 +48,5 @@ export const ImageEditor = as<'div', ImageEditorProps>(
</Box>
</Box>
);
}
},
);
@@ -57,7 +57,7 @@ export const ImagePackContent = as<'div', ImagePackContentProps>(
Array.from(savedImages).find(([, img]) => img.shortcode === shortcode) !== undefined;
return hasInSaved;
},
[imagePack, savedImages, uploadedImages]
[imagePack, savedImages, uploadedImages],
);
const pickFiles = useFilePicker(
@@ -74,9 +74,9 @@ export const ImagePackContent = as<'div', ImagePackContentProps>(
setFiles((f) => [...f, ...uniqueFiles]);
},
[hasImageWithShortcode]
[hasImageWithShortcode],
),
true
true,
);
const handleMetaSave = useCallback(
@@ -88,10 +88,10 @@ export const ImagePackContent = as<'div', ImagePackContentProps>(
...imagePack.meta.content,
...m?.content,
...editedMeta.content,
})
}),
);
},
[imagePack.meta]
[imagePack.meta],
);
const handleMetaCancel = () => setMetaEditing(false);
@@ -104,10 +104,10 @@ export const ImagePackContent = as<'div', ImagePackContentProps>(
...imagePack.meta.content,
...m?.content,
usage: usg,
})
}),
);
},
[imagePack.meta]
[imagePack.meta],
);
const handleUploadRemove = useCallback((file: TUploadContent) => {
@@ -123,13 +123,13 @@ export const ImagePackContent = as<'div', ImagePackContentProps>(
};
const image = PackImageReader.fromPackImage(
getFileNameWithoutExt(data.file.name),
packImage
packImage,
);
if (!image) return;
handleUploadRemove(data.file);
setUploadedImages((imgs) => [image, ...imgs]);
},
[handleUploadRemove]
[handleUploadRemove],
);
const handleImageEdit = (shortcode: string) => {
@@ -164,7 +164,7 @@ export const ImagePackContent = as<'div', ImagePackContentProps>(
? new PackImageReader(
suffixRename(image.shortcode, hasImageWithShortcode),
image.url,
image.content
image.content,
)
: image;
@@ -199,7 +199,7 @@ export const ImagePackContent = as<'div', ImagePackContentProps>(
images.forEach((img) => pushImage(img));
return onUpdate?.(pack);
}, [imagePack, images, savedMeta, uploadedImages, savedImages, deleteImages, onUpdate])
}, [imagePack, images, savedMeta, uploadedImages, savedImages, deleteImages, onUpdate]),
);
useEffect(() => {
@@ -384,5 +384,5 @@ export const ImagePackContent = as<'div', ImagePackContentProps>(
)}
</Box>
);
}
},
);
@@ -1,7 +1,7 @@
import React, { FormEventHandler, useCallback, useMemo, useState } from 'react';
import { Box, Text, Avatar, AvatarFallback, Button, Input, TextArea, Chip } from 'folds';
import { Icon, Icons } from '../icons';
import Linkify from 'linkify-react';
import { Icon, Icons } from '../icons';
import { mxcUrlToHttp } from '../../utils/matrix';
import { useMatrixClient } from '../../hooks/useMatrixClient';
import { nameInitials } from '../../utils/common';
@@ -43,7 +43,7 @@ export function ImagePackProfile({ meta, canEdit, onEdit }: ImagePackProfileProp
const mx = useMatrixClient();
const useAuthentication = useMediaAuthentication();
const avatarUrl = meta.avatar
? mxcUrlToHttp(mx, meta.avatar, useAuthentication) ?? undefined
? (mxcUrlToHttp(mx, meta.avatar, useAuthentication) ?? undefined)
: undefined;
return (
@@ -91,7 +91,7 @@ export function ImagePackProfileEdit({ meta, onCancel, onSave }: ImagePackProfil
const useAuthentication = useMediaAuthentication();
const [avatar, setAvatar] = useState(meta.avatar);
const avatarUrl = avatar ? mxcUrlToHttp(mx, avatar, useAuthentication) ?? undefined : undefined;
const avatarUrl = avatar ? (mxcUrlToHttp(mx, avatar, useAuthentication) ?? undefined) : undefined;
const [imageFile, setImageFile] = useState<File>();
const avatarFileUrl = useObjectURL(imageFile);
@@ -32,7 +32,7 @@ export function RoomImagePack({ room, stateKey }: RoomImagePackProps) {
{
roomId: room.roomId,
stateKey,
}
},
);
}, [room.roomId, stateKey]);
const imagePack = useRoomImagePack(room, stateKey) ?? fallbackPack;
@@ -46,10 +46,10 @@ export function RoomImagePack({ room, stateKey }: RoomImagePackProps) {
address.roomId,
StateEvent.PoniesRoomEmotes,
packContent,
address.stateKey
address.stateKey,
);
},
[mx, imagePack]
[mx, imagePack],
);
return (
@@ -1,7 +1,7 @@
import React, { MouseEventHandler, useMemo, useState } from 'react';
import { Box, Button, config, Menu, MenuItem, PopOut, RectCords, Text } from 'folds';
import { Icon, Icons } from '../icons';
import FocusTrap from 'focus-trap-react';
import { Icon, Icons } from '../icons';
import { ImageUsage } from '../../plugins/custom-emoji';
import { stopPropagation } from '../../utils/keyboard';
@@ -30,7 +30,7 @@ export function UsageSelector({ selected, onChange }: UsageSelectorProps) {
const allUsages: ImageUsage[][] = useMemo(
() => [[ImageUsage.Emoticon], [ImageUsage.Sticker], [ImageUsage.Sticker, ImageUsage.Emoticon]],
[]
[],
);
return (
@@ -15,7 +15,7 @@ export function UserImagePack() {
async (packContent: PackContent) => {
await mx.setAccountData(AccountDataEvent.PoniesUserEmotes, packContent);
},
[mx]
[mx],
);
return <ImagePackContent imagePack={imagePack ?? defaultPack} canEdit onUpdate={handleUpdate} />;
@@ -1,11 +1,4 @@
/* eslint-disable jsx-a11y/no-noninteractive-element-interactions */
import React, {
useCallback,
useEffect,
useLayoutEffect,
useRef,
useState,
} from 'react';
import React, { useCallback, useEffect, useLayoutEffect, useRef, useState } from 'react';
import classNames from 'classnames';
import { as } from 'folds';
import { Icon, Icons } from '../icons';
@@ -42,16 +35,13 @@ function imageViewportMax() {
};
}
function pointerDistance(
a: { x: number; y: number },
b: { x: number; y: number }
): number {
function pointerDistance(a: { x: number; y: number }, b: { x: number; y: number }): number {
return Math.hypot(a.x - b.x, a.y - b.y);
}
function pointerMidpoint(
a: { x: number; y: number },
b: { x: number; y: number }
b: { x: number; y: number },
): { x: number; y: number } {
return { x: (a.x + b.x) / 2, y: (a.y + b.y) / 2 };
}
@@ -123,7 +113,7 @@ export const ImageViewer = as<'div', ImageViewerProps>(
applyZoomCss(clamped);
setZoom(clamped);
},
[applyZoomCss, clampPan]
[applyZoomCss, clampPan],
);
const resetZoom = useCallback(() => {
@@ -162,7 +152,7 @@ export const ImageViewer = as<'div', ImageViewerProps>(
ty: py - iy * scale,
});
},
[commitZoom]
[commitZoom],
);
const framePoint = (clientX: number, clientY: number) => {
@@ -202,7 +192,7 @@ export const ImageViewer = as<'div', ImageViewerProps>(
const local = framePoint(mid.x, mid.y);
const scale = Math.min(
ZOOM_MAX,
Math.max(ZOOM_MIN, pinch.startScale * (dist / pinch.startDist))
Math.max(ZOOM_MIN, pinch.startScale * (dist / pinch.startDist)),
);
// Keep the original content under the pinch midpoint while scaling + panning.
@@ -441,5 +431,5 @@ export const ImageViewer = as<'div', ImageViewerProps>(
</div>
</div>
);
}
},
);
@@ -7,11 +7,30 @@ import React, {
useRef,
useState,
} from 'react';
import { Overlay, OverlayBackdrop, OverlayCenter, Box, Header, config, Text, IconButton, Input, Button, Spinner, color, TextArea, Dialog, Menu, toRem, Scroll, MenuItem } from 'folds';
import { Icon, Icons } from '../icons';
import {
Overlay,
OverlayBackdrop,
OverlayCenter,
Box,
Header,
config,
Text,
IconButton,
Input,
Button,
Spinner,
color,
TextArea,
Dialog,
Menu,
toRem,
Scroll,
MenuItem,
} from 'folds';
import { Room } from 'matrix-js-sdk';
import { isKeyHotkey } from 'is-hotkey';
import FocusTrap from 'focus-trap-react';
import { Icon, Icons } from '../icons';
import { stopPropagation } from '../../utils/keyboard';
import { useDirectUsers } from '../../hooks/useDirectUsers';
import { getMxIdLocalPart, getMxIdServer, isUserId } from '../../utils/matrix';
@@ -49,12 +68,12 @@ export function InviteUserPrompt({ room, requestClose }: InviteUserProps) {
const membership = room.getMember(userId)?.membership;
return membership !== Membership.Join;
}),
[directUsers, room]
[directUsers, room],
);
const [result, search, resetSearch] = useAsyncSearch(
filteredUsers,
getUserIdString,
SEARCH_OPTIONS
SEARCH_OPTIONS,
);
const queryHighlighRegex = result?.query
? makeHighlightRegex(result.query.split(' '))
@@ -65,8 +84,8 @@ export function InviteUserPrompt({ room, requestClose }: InviteUserProps) {
async (userId, reason) => {
await mx.invite(room.roomId, userId, reason);
},
[mx, room]
)
[mx, room],
),
);
const inviting = inviteState.status === AsyncStatus.Loading;
@@ -1,6 +1,19 @@
import React, { FormEventHandler, useState } from 'react';
import FocusTrap from 'focus-trap-react';
import { Dialog, Overlay, OverlayCenter, OverlayBackdrop, Header, config, Box, Text, IconButton, Button, Input, color } from 'folds';
import {
Dialog,
Overlay,
OverlayCenter,
OverlayBackdrop,
Header,
config,
Box,
Text,
IconButton,
Button,
Input,
color,
} from 'folds';
import { Icon, Icons } from '../icons';
import { stopPropagation } from '../../utils/keyboard';
import { isRoomAlias, isRoomId } from '../../utils/matrix';
@@ -1,8 +1,25 @@
import React, { useMemo, useState } from 'react';
import FocusTrap from 'focus-trap-react';
import { Dialog, Overlay, OverlayCenter, OverlayBackdrop, Header, config, Box, Text, IconButton, color, Button, Spinner, Scroll, Checkbox, Avatar, Badge } from 'folds';
import { Icon, Icons } from '../icons';
import {
Dialog,
Overlay,
OverlayCenter,
OverlayBackdrop,
Header,
config,
Box,
Text,
IconButton,
color,
Button,
Spinner,
Scroll,
Checkbox,
Avatar,
Badge,
} from 'folds';
import { IHierarchyRoom } from 'matrix-js-sdk/lib/@types/spaces';
import { Icon, Icons } from '../icons';
import { useMatrixClient } from '../../hooks/useMatrixClient';
import { stopPropagation } from '../../utils/keyboard';
import { RoomType, Membership } from '../../../types/matrix/room';
@@ -274,7 +291,7 @@ export function JoinSpacePrompt({
mx,
item.room_id,
RoomNotificationMode.SpecialMessages,
RoomNotificationMode.Unset
RoomNotificationMode.Unset,
);
}
@@ -290,12 +307,12 @@ export function JoinSpacePrompt({
// Join spaces first, then rooms
await spacesToJoin.reduce(
(promise, space) => promise.then(() => joinItem(space, true)),
Promise.resolve()
Promise.resolve(),
);
await regularRoomsToJoin.reduce(
(promise, room) => promise.then(() => joinItem(room, false)),
Promise.resolve()
Promise.resolve(),
);
setProgress(null);
@@ -334,11 +351,11 @@ export function JoinSpacePrompt({
const isJoining = phase === 'joining-space' || phase === 'joining-rooms';
const spaces = useMemo(
() => hierarchyRooms.filter((r) => r.room_type === RoomType.Space),
[hierarchyRooms]
[hierarchyRooms],
);
const rooms = useMemo(
() => hierarchyRooms.filter((r) => r.room_type !== RoomType.Space),
[hierarchyRooms]
[hierarchyRooms],
);
const getButtonText = () => {
@@ -451,11 +468,7 @@ export function JoinSpacePrompt({
</Box>
</Box>
<Scroll
hideTrack
visibility="Hover"
style={{ maxHeight: '300px', flexGrow: 1 }}
>
<Scroll hideTrack visibility="Hover" style={{ maxHeight: '300px', flexGrow: 1 }}>
<Box direction="Column" gap="200">
{spaces.length > 0 && (
<Box direction="Column" gap="100">
@@ -525,7 +538,9 @@ export function JoinSpacePrompt({
variant="Primary"
onClick={handlePrimaryAction}
disabled={isJoining}
before={isJoining ? <Spinner fill="Solid" variant="Primary" size="200" /> : undefined}
before={
isJoining ? <Spinner fill="Solid" variant="Primary" size="200" /> : undefined
}
aria-disabled={isJoining}
>
<Text size="B400">{getButtonText()}</Text>
@@ -1,8 +1,21 @@
import React, { useCallback, useEffect } from 'react';
import FocusTrap from 'focus-trap-react';
import { Dialog, Overlay, OverlayCenter, OverlayBackdrop, Header, config, Box, Text, IconButton, color, Button, Spinner } from 'folds';
import { Icon, Icons } from '../icons';
import {
Dialog,
Overlay,
OverlayCenter,
OverlayBackdrop,
Header,
config,
Box,
Text,
IconButton,
color,
Button,
Spinner,
} from 'folds';
import { MatrixError } from 'matrix-js-sdk';
import { Icon, Icons } from '../icons';
import { useMatrixClient } from '../../hooks/useMatrixClient';
import { AsyncStatus, useAsyncCallback } from '../../hooks/useAsyncCallback';
import { stopPropagation } from '../../utils/keyboard';
@@ -18,7 +31,7 @@ export function LeaveRoomPrompt({ roomId, onDone, onCancel }: LeaveRoomPromptPro
const [leaveState, leaveRoom] = useAsyncCallback<undefined, MatrixError, []>(
useCallback(async () => {
mx.leave(roomId);
}, [mx, roomId])
}, [mx, roomId]),
);
const handleLeave = () => {
@@ -1,9 +1,22 @@
import React, { useCallback, useEffect, useState } from 'react';
import FocusTrap from 'focus-trap-react';
import { Dialog, Overlay, OverlayCenter, OverlayBackdrop, Header, config, Box, Text, IconButton, color, Button, Spinner } from 'folds';
import { Icon, Icons } from '../icons';
import {
Dialog,
Overlay,
OverlayCenter,
OverlayBackdrop,
Header,
config,
Box,
Text,
IconButton,
color,
Button,
Spinner,
} from 'folds';
import { MatrixError, Room } from 'matrix-js-sdk';
import { useAtomValue } from 'jotai';
import { Icon, Icons } from '../icons';
import { useMatrixClient } from '../../hooks/useMatrixClient';
import { AsyncStatus, useAsyncCallback } from '../../hooks/useAsyncCallback';
import { stopPropagation } from '../../utils/keyboard';
@@ -28,7 +41,7 @@ function delay(ms: number): Promise<void> {
async function leaveRoomsSequentially(
mx: ReturnType<typeof useMatrixClient>,
roomIds: string[],
onProgress?: (current: number, total: number) => void
onProgress?: (current: number, total: number) => void,
): Promise<void> {
const total = roomIds.length;
@@ -53,7 +66,7 @@ async function leaveRoomsSequentially(
function getDirectChildRoomsToLeave(
mx: ReturnType<typeof useMatrixClient>,
spaceRoom: Room,
mDirects: Set<string>
mDirects: Set<string>,
): string[] {
const childIds = getSpaceChildren(spaceRoom);
@@ -111,7 +124,7 @@ export function LeaveSpacePrompt({ roomId, onDone, onCancel }: LeaveSpacePromptP
// Clear progress and leave the space itself
setProgress(null);
await mx.leave(roomId);
}, [mx, roomId, mDirects])
}, [mx, roomId, mDirects]),
);
const handleLeave = () => {
@@ -1,8 +1,26 @@
import React, { useMemo, useState, useCallback, useRef, useEffect, MouseEvent } from 'react';
import FocusTrap from 'focus-trap-react';
import { Dialog, Overlay, OverlayCenter, OverlayBackdrop, Header, config, Box, Text, IconButton, color, Button, Spinner, Scroll, Checkbox, Badge, Line, Avatar } from 'folds';
import { Icon, Icons } from '../icons';
import {
Dialog,
Overlay,
OverlayCenter,
OverlayBackdrop,
Header,
config,
Box,
Text,
IconButton,
color,
Button,
Spinner,
Scroll,
Checkbox,
Badge,
Line,
Avatar,
} from 'folds';
import { Room } from 'matrix-js-sdk';
import { Icon, Icons } from '../icons';
import { useMatrixClient } from '../../hooks/useMatrixClient';
import { stopPropagation } from '../../utils/keyboard';
import { RoomAvatar } from '../room-avatar';
@@ -95,9 +113,7 @@ function RoomItem({ room, selected, onToggle, onShiftClick, disabled }: RoomItem
roomId={room.roomId}
src={avatarUrl}
alt={roomName}
renderFallback={() => (
<Text size="H6">{nameInitials(roomName, 2)}</Text>
)}
renderFallback={() => <Text size="H6">{nameInitials(roomName, 2)}</Text>}
/>
</Avatar>
<Box direction="Column" grow="Yes" style={{ minWidth: 0 }}>
@@ -128,7 +144,7 @@ export function ManageRoomsPrompt({ rooms, onDone, onCancel }: ManageRoomsPrompt
const [selectedRoomIds, setSelectedRoomIds] = useState<Set<string>>(new Set());
const [phase, setPhase] = useState<LeavePhase>('selecting');
const [leaveProgress, setLeaveProgress] = useState<{ current: number; total: number } | null>(
null
null,
);
const [errorMessage, setErrorMessage] = useState<string | null>(null);
const lastSelectedIndex = useRef<number | null>(null);
@@ -140,7 +156,7 @@ export function ManageRoomsPrompt({ rooms, onDone, onCancel }: ManageRoomsPrompt
const nameB = b.name?.toLowerCase() || '';
return nameA.localeCompare(nameB);
}),
[rooms]
[rooms],
);
/**
@@ -179,7 +195,7 @@ export function ManageRoomsPrompt({ rooms, onDone, onCancel }: ManageRoomsPrompt
});
lastSelectedIndex.current = index;
},
[handleToggle, sortedRooms]
[handleToggle, sortedRooms],
);
/**
@@ -208,10 +224,7 @@ export function ManageRoomsPrompt({ rooms, onDone, onCancel }: ManageRoomsPrompt
} catch (error) {
// Check if it's a rate limit error (429)
const isRateLimited =
error &&
typeof error === 'object' &&
'httpStatus' in error &&
error.httpStatus === 429;
error && typeof error === 'object' && 'httpStatus' in error && error.httpStatus === 429;
if (isRateLimited && attempt < MAX_RETRIES) {
const retryDelay = getRetryDelay(error, attempt);
@@ -221,7 +234,7 @@ export function ManageRoomsPrompt({ rooms, onDone, onCancel }: ManageRoomsPrompt
return false;
}
},
[mx]
[mx],
);
/**
@@ -312,7 +325,9 @@ export function ManageRoomsPrompt({ rooms, onDone, onCancel }: ManageRoomsPrompt
) : (
<>
<Icon src={Icons.Check} size="600" style={{ color: color.Success.Main }} />
<Text style={{ color: color.Success.Main }}>Successfully left all selected rooms!</Text>
<Text style={{ color: color.Success.Main }}>
Successfully left all selected rooms!
</Text>
</>
)}
</Box>
+1 -1
View File
@@ -11,5 +11,5 @@ export const Image = forwardRef<HTMLImageElement, ImgHTMLAttributes<HTMLImageEle
{...props}
ref={ref}
/>
)
),
);
+1 -1
View File
@@ -23,5 +23,5 @@ export const MediaControl = as<'div', MediaControlProps>(
{after && <Box direction="Column">{after}</Box>}
{children}
</Box>
)
),
);
+30 -17
View File
@@ -44,13 +44,13 @@ export const Video = forwardRef<HTMLVideoElement, VideoProps>(
if (disableControls) {
return (
// eslint-disable-next-line jsx-a11y/media-has-caption
<video
className={classNames(css.Video, className)}
{...props}
ref={videoRef}
loop={props.autoPlay}
muted={props.autoPlay}
playsInline
<video
className={classNames(css.Video, className)}
{...props}
ref={videoRef}
loop={props.autoPlay}
muted={props.autoPlay}
playsInline
/>
);
}
@@ -62,19 +62,32 @@ export const Video = forwardRef<HTMLVideoElement, VideoProps>(
onMouseLeave={() => setShowControls(false)}
>
{/* eslint-disable-next-line jsx-a11y/media-has-caption */}
<video
className={classNames(css.Video, className)}
{...props}
ref={videoRef}
loop={props.autoPlay}
muted={props.autoPlay}
<video
className={classNames(css.Video, className)}
{...props}
ref={videoRef}
loop={props.autoPlay}
muted={props.autoPlay}
playsInline
controlsList={onExpand ? 'nofullscreen' : undefined}
onDoubleClick={onExpand ? (e) => { e.stopPropagation(); onExpand(); } : undefined}
onDoubleClick={
onExpand
? (e) => {
e.stopPropagation();
onExpand();
}
: undefined
}
/>
{onExpand && (
<Box className={classNames(videoCss.VideoControlsOverlay, !showControls && videoCss.VideoControlsOverlayHidden)} gap="200">
<Box
className={classNames(
videoCss.VideoControlsOverlay,
!showControls && videoCss.VideoControlsOverlayHidden,
)}
gap="200"
>
<TooltipProvider
tooltip={
<Tooltip variant="Secondary">
@@ -101,5 +114,5 @@ export const Video = forwardRef<HTMLVideoElement, VideoProps>(
)}
</Box>
);
}
},
);
@@ -1,7 +1,7 @@
import React, { ReactNode } from 'react';
import { as, Avatar, Box, Text } from 'folds';
import { Icon, Icons } from '../icons';
import { MatrixClient, Room, RoomMember } from 'matrix-js-sdk';
import { Icon, Icons } from '../icons';
import { getMemberDisplayName } from '../../utils/room';
import { getMxIdLocalPart } from '../../utils/matrix';
import { UserAvatar } from '../user-avatar';
@@ -50,5 +50,5 @@ export const MemberTile = as<'button', MemberTileProps>(
{after}
</AsMemberTile>
);
}
},
);
+7 -3
View File
@@ -1,7 +1,7 @@
import { Badge, Box, IconButton, Spinner, Text, as, toRem } from 'folds';
import { Icon, Icons } from '../icons';
import React, { ReactNode, useCallback } from 'react';
import { EncryptedAttachmentInfo } from 'browser-encrypt-attachment';
import { Icon, Icons } from '../icons';
import { mimeTypeToExt } from '../../utils/mimeTypes';
import { useMatrixClient } from '../../hooks/useMatrixClient';
import { useMediaAuthentication } from '../../hooks/useMediaAuthentication';
@@ -33,12 +33,16 @@ export function FileDownloadButton({ filename, url, mimeType, encInfo }: FileDow
// Always use current session's token to avoid stale tokens during account switches
const accessToken = getCurrentAccessToken();
const fileContent = encInfo
? await downloadEncryptedMedia(mediaUrl, (encBuf) => decryptFile(encBuf, mimeType, encInfo), accessToken)
? await downloadEncryptedMedia(
mediaUrl,
(encBuf) => decryptFile(encBuf, mimeType, encInfo),
accessToken,
)
: await downloadMedia(mediaUrl, accessToken);
await saveMediaBlob(fileContent, filename);
return true;
}, [mx, url, useAuthentication, mimeType, encInfo, filename])
}, [mx, url, useAuthentication, mimeType, encInfo, filename]),
);
const downloading = downloadState.status === AsyncStatus.Loading;
+37 -32
View File
@@ -1,7 +1,7 @@
import React, { CSSProperties, ReactNode } from 'react';
import { Box, Chip, Text, toRem } from 'folds';
import { Icon, Icons } from '../icons';
import { IContent } from 'matrix-js-sdk';
import { Icon, Icons } from '../icons';
import { JUMBO_EMOJI_REG, URL_REG } from '../../utils/regex';
import { trimReplyFromBody } from '../../utils/room';
import { MessageTextBody } from './layout';
@@ -27,7 +27,10 @@ import {
MATRIX_SPOILER_REASON_PROPERTY_NAME,
} from '../../../types/matrix/common';
import { StationeryMedia, hashStationerySeed, stationeryMediaRot } from './StationeryMedia';
import { getJumboEmojiInteractionProps, JumboEmojiClickHandler } from '../../features/room/emoji-confetti/jumboEmojiInteraction';
import {
getJumboEmojiInteractionProps,
JumboEmojiClickHandler,
} from '../../features/room/emoji-confetti/jumboEmojiInteraction';
import { FALLBACK_MIMETYPE, getBlobSafeMimeType } from '../../utils/mimeTypes';
import { parseGeoUri, scaleYDimension } from '../../utils/common';
import { resolveAttachmentBoxSize } from '../../state/mediaDimensionCache';
@@ -81,14 +84,22 @@ type MTextProps = {
style?: CSSProperties;
onJumboEmojiClick?: JumboEmojiClickHandler;
};
export function MText({ edited, content, renderBody, renderUrlsPreview, style, onJumboEmojiClick }: MTextProps) {
export function MText({
edited,
content,
renderBody,
renderUrlsPreview,
style,
onJumboEmojiClick,
}: MTextProps) {
const { body, formatted_body: customBody } = content;
if (typeof body !== 'string') return <BrokenContent />;
const trimmedBody = trimReplyFromBody(body).trim();
const trimmedCustomBody = typeof customBody === 'string'
? customBody.trim().replace(/(<br\s*\/?>\s*)+$/gi, '')
: undefined;
const trimmedCustomBody =
typeof customBody === 'string'
? customBody.trim().replace(/(<br\s*\/?>\s*)+$/gi, '')
: undefined;
const urlsMatch = renderUrlsPreview && trimmedBody.match(URL_REG);
const urls = urlsMatch ? [...new Set(urlsMatch)] : undefined;
const isJumboEmoji = JUMBO_EMOJI_REG.test(trimmedBody);
@@ -137,9 +148,10 @@ export function MEmote({
if (typeof body !== 'string') return <BrokenContent />;
const trimmedBody = trimReplyFromBody(body).trim();
const trimmedCustomBody = typeof customBody === 'string'
? customBody.trim().replace(/(<br\s*\/?>\s*)+$/gi, '')
: undefined;
const trimmedCustomBody =
typeof customBody === 'string'
? customBody.trim().replace(/(<br\s*\/?>\s*)+$/gi, '')
: undefined;
const urlsMatch = renderUrlsPreview && trimmedBody.match(URL_REG);
const urls = urlsMatch ? [...new Set(urlsMatch)] : undefined;
const isJumboEmoji = JUMBO_EMOJI_REG.test(trimmedBody);
@@ -151,11 +163,7 @@ export function MEmote({
return (
<>
<MessageTextBody
emote
preWrap={typeof customBody !== 'string'}
jumboEmoji={isJumboEmoji}
>
<MessageTextBody emote preWrap={typeof customBody !== 'string'} jumboEmoji={isJumboEmoji}>
<b>{`${displayName} `}</b>
<span {...jumboEmojiInteraction}>
{renderBody({
@@ -177,14 +185,21 @@ type MNoticeProps = {
renderUrlsPreview?: (urls: string[]) => ReactNode;
onJumboEmojiClick?: JumboEmojiClickHandler;
};
export function MNotice({ edited, content, renderBody, renderUrlsPreview, onJumboEmojiClick }: MNoticeProps) {
export function MNotice({
edited,
content,
renderBody,
renderUrlsPreview,
onJumboEmojiClick,
}: MNoticeProps) {
const { body, formatted_body: customBody } = content;
if (typeof body !== 'string') return <BrokenContent />;
const trimmedBody = trimReplyFromBody(body).trim();
const trimmedCustomBody = typeof customBody === 'string'
? customBody.trim().replace(/(<br\s*\/?>\s*)+$/gi, '')
: undefined;
const trimmedCustomBody =
typeof customBody === 'string'
? customBody.trim().replace(/(<br\s*\/?>\s*)+$/gi, '')
: undefined;
const urlsMatch = renderUrlsPreview && trimmedBody.match(URL_REG);
const urls = urlsMatch ? [...new Set(urlsMatch)] : undefined;
const isJumboEmoji = JUMBO_EMOJI_REG.test(trimmedBody);
@@ -232,7 +247,7 @@ type MImageProps = {
const resolveMediaBoxSize = (
mxcUrl: string,
w?: number,
h?: number
h?: number,
): { width: number; height: number } => resolveAttachmentBoxSize(mxcUrl, w, h);
/** Extra space after media so following text stays on the 24px ruled grid — applied outside the photo chrome */
@@ -253,12 +268,7 @@ export function MImage({ content, renderImageContent, outlined }: MImageProps) {
const gridPad = snapStationeryGridPad(height);
return (
<StationeryMedia
outlined={outlined}
transparent
tiltSeed={mxcUrl}
gridPad={gridPad}
>
<StationeryMedia outlined={outlined} transparent tiltSeed={mxcUrl} gridPad={gridPad}>
<AttachmentBox
style={{
width: toRem(width),
@@ -312,17 +322,12 @@ export function MVideo({ content, renderAsFile, renderVideoContent, outlined }:
const { width, height } = resolveMediaBoxSize(
mxcUrl,
videoInfo.w ?? videoInfo.thumbnail_info?.w,
videoInfo.h ?? videoInfo.thumbnail_info?.h
videoInfo.h ?? videoInfo.thumbnail_info?.h,
);
const gridPad = snapStationeryGridPad(height);
return (
<StationeryMedia
outlined={outlined}
transparent
tiltSeed={mxcUrl}
gridPad={gridPad}
>
<StationeryMedia outlined={outlined} transparent tiltSeed={mxcUrl} gridPad={gridPad}>
<AttachmentHeader>
<FileHeader
body={filename}
+2 -2
View File
@@ -23,7 +23,7 @@ export const Reaction = as<
const stationery = isStationeryTheme(theme);
const isCustomEmoji = reaction.startsWith('mxc://');
const customSrc = isCustomEmoji
? mxcUrlToHttp(mx, reaction, useAuthentication) ?? reaction
? (mxcUrlToHttp(mx, reaction, useAuthentication) ?? reaction)
: undefined;
const emoji = isCustomEmoji ? (
@@ -130,7 +130,7 @@ export function ReactionTooltipMsg({ room, reaction, events }: ReactionTooltipMs
(ev: MatrixEvent) =>
getMemberDisplayName(room, ev.getSender() ?? 'Unknown') ??
getMxIdLocalPart(ev.getSender() ?? 'Unknown') ??
'Unknown'
'Unknown',
);
return (
+9 -8
View File
@@ -1,8 +1,8 @@
import { Box, Text, as, color, toRem } from 'folds';
import { Icon, Icons } from '../icons';
import { EventTimelineSet, Room } from 'matrix-js-sdk';
import React, { MouseEventHandler, ReactNode, useCallback, useMemo } from 'react';
import classNames from 'classnames';
import { Icon, Icons } from '../icons';
import { getMemberAvatarMxc, getMemberDisplayName, trimReplyFromBody } from '../../utils/room';
import { getMxIdLocalPart } from '../../utils/matrix';
import { LinePlaceholder } from './placeholder';
@@ -23,8 +23,8 @@ type ReplyLayoutProps = {
};
export const ReplyLayout = as<'div', ReplyLayoutProps>(
({ username, userColor, className, children, ...props }, ref) => {
const theme = useTheme();
const isStationery = isStationeryTheme(theme);
const theme = useTheme();
const isStationery = isStationeryTheme(theme);
return (
<Box
@@ -61,7 +61,7 @@ export const ReplyLayout = as<'div', ReplyLayoutProps>(
</Box>
</Box>
);
}
},
);
export const ThreadIndicator = as<'div'>(({ ...props }, ref) => (
@@ -105,12 +105,12 @@ export const Reply = as<'div', ReplyProps>(
legacyUsernameColor,
...props
},
ref
ref,
) => {
const placeholderWidth = useMemo(() => randomNumberBetween(40, 400), []);
const getFromLocalTimeline = useCallback(
() => timelineSet?.findEventById(replyEventId),
[timelineSet, replyEventId]
[timelineSet, replyEventId],
);
const replyEvent = useRoomEvent(room, replyEventId, getFromLocalTimeline);
@@ -122,7 +122,8 @@ export const Reply = as<'div', ReplyProps>(
const tagColor = powerTag?.color ? accessibleTagColors?.get(powerTag.color) : undefined;
// Priority: custom user color > tag color (non-legacy) > colorMXID (legacy)
const usernameColor = customUserColor ?? (legacyUsernameColor ? colorMXID(sender ?? replyEventId) : tagColor);
const usernameColor =
customUserColor ?? (legacyUsernameColor ? colorMXID(sender ?? replyEventId) : tagColor);
const fallbackBody = replyEvent?.isRedacted() ? (
<MessageDeletedContent />
@@ -171,5 +172,5 @@ export const Reply = as<'div', ReplyProps>(
</ReplyLayout>
</Box>
);
}
},
);
@@ -56,7 +56,7 @@ function cornerPeelPaths(
cy: number,
ux: number,
uy: number,
size: number
size: number,
): {
keep: string;
flap: string;
@@ -147,20 +147,21 @@ export function StationeryMedia({
const isStationery = isStationeryTheme(theme);
const peelRef = useRef<HTMLSpanElement>(null);
const tiltStyle = useMemo((): CSSProperties => {
return {
const tiltStyle = useMemo(
(): CSSProperties => ({
...(style as CSSProperties | undefined),
// Margin sits outside the paper chrome — snaps the grid without a white bar
...(isStationery && gridPad > 0 ? { marginBottom: `${gridPad}px` } : null),
['--media-rot' as string]: stationeryMediaRot(tiltSeed),
};
}, [tiltSeed, style, isStationery, gridPad]);
}),
[tiltSeed, style, isStationery, gridPad],
);
const tapeAlt = useMemo(() => hashStationerySeed(tiltSeed) % 2 === 1, [tiltSeed]);
// Default tape covers TL; alt covers TR — peel only the free top corner
const peelCorner = useMemo(
() => (tapeAlt ? CORNERS.find((c) => c.id === 'tl')! : CORNERS.find((c) => c.id === 'tr')!),
[tapeAlt]
[tapeAlt],
);
const clearPeel = useCallback((host: HTMLElement) => {
@@ -237,7 +238,7 @@ export function StationeryMedia({
cy,
ux,
uy,
size
size,
);
target.style.clipPath = keep;
peel.style.clipPath = flap;
@@ -253,7 +254,7 @@ export function StationeryMedia({
clearPeel(host);
}
},
[peelCorner, clearPeel]
[peelCorner, clearPeel],
);
const handleMove: MouseEventHandler<HTMLElement> = (evt) => {
+1 -1
View File
@@ -41,5 +41,5 @@ export const Time = as<'span', TimeProps & ComponentProps<typeof Text>>(
{time}
</Text>
);
}
},
);
@@ -12,7 +12,7 @@ export const Attachment = as<'div', css.AttachmentVariants>(
{...props}
ref={ref}
/>
)
),
);
export const AttachmentHeader = as<'div'>(({ className, ...props }, ref) => (
@@ -1,9 +1,9 @@
/* eslint-disable jsx-a11y/media-has-caption */
import React, { ReactNode, useCallback, useRef, useState } from 'react';
import { Badge, Chip, IconButton, ProgressBar, Spinner, Text, toRem } from 'folds';
import { Icon, Icons } from '../../icons';
import { EncryptedAttachmentInfo } from 'browser-encrypt-attachment';
import { Range } from 'react-range';
import { Icon, Icons } from '../../icons';
import { useMatrixClient } from '../../../hooks/useMatrixClient';
import { AsyncStatus, useAsyncCallback } from '../../../hooks/useAsyncCallback';
import { IAudioInfo } from '../../../../types/matrix/common';
@@ -60,10 +60,14 @@ export function AudioContent({
// Always use current session's token to avoid stale tokens during account switches
const accessToken = getCurrentAccessToken();
const fileContent = encInfo
? await downloadEncryptedMedia(mediaUrl, (encBuf) => decryptFile(encBuf, mimeType, encInfo), accessToken)
? await downloadEncryptedMedia(
mediaUrl,
(encBuf) => decryptFile(encBuf, mimeType, encInfo),
accessToken,
)
: await downloadMedia(mediaUrl, accessToken);
return URL.createObjectURL(fileContent);
}, [mx, url, useAuthentication, mimeType, encInfo])
}, [mx, url, useAuthentication, mimeType, encInfo]),
);
const audioRef = useRef<HTMLAudioElement | null>(null);
@@ -84,7 +88,7 @@ export function AudioContent({
}, []);
useMediaPlayTimeCallback(
getAudioRef,
useThrottle(handlePlayTimeCallback, PLAY_TIME_THROTTLE_OPS)
useThrottle(handlePlayTimeCallback, PLAY_TIME_THROTTLE_OPS),
);
const handlePlay = () => {
@@ -152,7 +156,7 @@ export function AudioContent({
</Chip>
<Text size="T200">{`${secondsToMinutesAndSeconds(
currentTime
currentTime,
)} / ${secondsToMinutesAndSeconds(duration)}`}</Text>
</>
),
@@ -1,6 +1,6 @@
import { Box } from 'folds';
import { Icon, IconSrc } from '../../icons';
import React, { ReactNode } from 'react';
import { Icon, IconSrc } from '../../icons';
import { BubbleLayout, CompactLayout, ModernLayout } from '..';
import { MessageLayout } from '../../../state/settings';
@@ -1,6 +1,6 @@
import { Box, Text, as, color, config } from 'folds';
import { Icon, Icons } from '../../icons';
import React from 'react';
import { Icon, Icons } from '../../icons';
const warningStyle = { color: color.Warning.Main, opacity: config.opacity.P300 };
const criticalStyle = { color: color.Critical.Main, opacity: config.opacity.P300 };
@@ -15,7 +15,7 @@ export const MessageDeletedContent = as<'div', { children?: never; reason?: stri
<i>This message has been deleted</i>
)}
</Box>
)
),
);
export const MessageUnsupportedContent = as<'div', { children?: never }>(({ ...props }, ref) => (
@@ -1,9 +1,21 @@
import React, { ReactNode, useCallback, useState } from 'react';
import { Box, Button, Modal, Overlay, OverlayBackdrop, OverlayCenter, Spinner, Text, Tooltip, TooltipProvider, as } from 'folds';
import { Icon, Icons } from '../../icons';
import {
Box,
Button,
Modal,
Overlay,
OverlayBackdrop,
OverlayCenter,
Spinner,
Text,
Tooltip,
TooltipProvider,
as,
} from 'folds';
import { EncryptedAttachmentInfo } from 'browser-encrypt-attachment';
import { saveMediaBlob } from '../../../utils/saveMedia';
import FocusTrap from 'focus-trap-react';
import { Icon, Icons } from '../../icons';
import { saveMediaBlob } from '../../../utils/saveMedia';
import { IFileInfo } from '../../../../types/matrix/common';
import { AsyncStatus, useAsyncCallback } from '../../../hooks/useAsyncCallback';
import { useMatrixClient } from '../../../hooks/useMatrixClient';
@@ -78,13 +90,17 @@ export function ReadTextFile({ body, mimeType, url, encInfo, renderViewer }: Rea
// Always use current session's token to avoid stale tokens during account switches
const accessToken = getCurrentAccessToken();
const fileContent = encInfo
? await downloadEncryptedMedia(mediaUrl, (encBuf) => decryptFile(encBuf, mimeType, encInfo), accessToken)
? await downloadEncryptedMedia(
mediaUrl,
(encBuf) => decryptFile(encBuf, mimeType, encInfo),
accessToken,
)
: await downloadMedia(mediaUrl, accessToken);
const text = fileContent.text();
setTextViewer(true);
return text;
}, [mx, useAuthentication, mimeType, encInfo, url])
}, [mx, useAuthentication, mimeType, encInfo, url]),
);
return (
@@ -170,11 +186,15 @@ export function ReadPdfFile({ body, mimeType, url, encInfo, renderViewer }: Read
// Always use current session's token to avoid stale tokens during account switches
const accessToken = getCurrentAccessToken();
const fileContent = encInfo
? await downloadEncryptedMedia(mediaUrl, (encBuf) => decryptFile(encBuf, mimeType, encInfo), accessToken)
? await downloadEncryptedMedia(
mediaUrl,
(encBuf) => decryptFile(encBuf, mimeType, encInfo),
accessToken,
)
: await downloadMedia(mediaUrl, accessToken);
setPdfViewer(true);
return URL.createObjectURL(fileContent);
}, [mx, url, useAuthentication, mimeType, encInfo])
}, [mx, url, useAuthentication, mimeType, encInfo]),
);
return (
@@ -249,12 +269,16 @@ export function DownloadFile({ body, mimeType, url, info, encInfo }: DownloadFil
// Always use current session's token to avoid stale tokens during account switches
const accessToken = getCurrentAccessToken();
const fileContent = encInfo
? await downloadEncryptedMedia(mediaUrl, (encBuf) => decryptFile(encBuf, mimeType, encInfo), accessToken)
? await downloadEncryptedMedia(
mediaUrl,
(encBuf) => decryptFile(encBuf, mimeType, encInfo),
accessToken,
)
: await downloadMedia(mediaUrl, accessToken);
await saveMediaBlob(fileContent, body);
return fileContent;
}, [mx, url, useAuthentication, mimeType, encInfo, body])
}, [mx, url, useAuthentication, mimeType, encInfo, body]),
);
return downloadState.status === AsyncStatus.Error ? (
@@ -299,5 +323,5 @@ export const FileContent = as<'div', FileContentProps>(
{mimeType === 'application/pdf' && renderAsPdfFile()}
{children}
</Box>
)
),
);
@@ -1,10 +1,21 @@
import React, { ReactNode, useCallback, useEffect, useState } from 'react';
import { Badge, Box, Button, Chip, Overlay, Spinner, Text, Tooltip, TooltipProvider, as } from 'folds';
import { Icon, Icons } from '../../icons';
import {
Badge,
Box,
Button,
Chip,
Overlay,
Spinner,
Text,
Tooltip,
TooltipProvider,
as,
} from 'folds';
import classNames from 'classnames';
import { Blurhash } from 'react-blurhash';
import FocusTrap from 'focus-trap-react';
import { EncryptedAttachmentInfo } from 'browser-encrypt-attachment';
import { Icon, Icons } from '../../icons';
import { IImageInfo, MATRIX_BLUR_HASH_PROPERTY_NAME } from '../../../../types/matrix/common';
import { AsyncStatus, useAsyncCallback } from '../../../hooks/useAsyncCallback';
import { useMatrixClient } from '../../../hooks/useMatrixClient';
@@ -16,7 +27,12 @@ import { decryptFile, downloadEncryptedMedia, mxcUrlToHttp } from '../../../util
import { useMediaAuthentication } from '../../../hooks/useMediaAuthentication';
import { validBlurHash } from '../../../utils/blurHash';
import { getCurrentAccessToken } from '../../../utils/auth';
import { setMediaDimensions, getMediaBlurHash, getMediaDimensions, rememberMediaBlurHash } from '../../../state/mediaDimensionCache';
import {
setMediaDimensions,
getMediaBlurHash,
getMediaDimensions,
rememberMediaBlurHash,
} from '../../../state/mediaDimensionCache';
/**
* Fetches media with authentication headers and returns a blob URL.
@@ -26,28 +42,36 @@ import { setMediaDimensions, getMediaBlurHash, getMediaDimensions, rememberMedia
*/
const fetchAuthenticatedMedia = async (
url: string,
accessToken: string | null
accessToken: string | null,
): Promise<string> => {
try {
let response = await fetch(url, {
method: 'GET',
headers: accessToken ? { Authorization: `Bearer ${accessToken}` } : undefined,
});
// If we got a 401 and we tried with auth, fallback to unauthenticated request
if (!response.ok && response.status === 401 && accessToken) {
console.warn('[ImageContent] Auth failed (401), attempting unauthenticated fallback for:', url);
console.warn(
'[ImageContent] Auth failed (401), attempting unauthenticated fallback for:',
url,
);
response = await fetch(url, { method: 'GET' });
}
if (!response.ok) {
console.warn(`[ImageContent] Failed to fetch authenticated media (${response.status}), falling back to original URL`);
console.warn(
`[ImageContent] Failed to fetch authenticated media (${response.status}), falling back to original URL`,
);
return url;
}
const blob = await response.blob();
return URL.createObjectURL(blob);
} catch (error) {
console.warn('[ImageContent] Error fetching authenticated media, falling back to original URL:', error);
console.warn(
'[ImageContent] Error fetching authenticated media, falling back to original URL:',
error,
);
return url;
}
};
@@ -101,7 +125,7 @@ export const ImageContent = as<'div', ImageContentProps>(
renderImage,
...props
},
ref
ref,
) => {
const mx = useMatrixClient();
const useAuthentication = useMediaAuthentication();
@@ -132,7 +156,7 @@ export const ImageContent = as<'div', ImageContentProps>(
const fileContent = await downloadEncryptedMedia(
mediaUrl,
(encBuf) => decryptFile(encBuf, mimeType ?? FALLBACK_MIMETYPE, encInfo),
accessToken
accessToken,
);
return URL.createObjectURL(fileContent);
}
@@ -141,7 +165,7 @@ export const ImageContent = as<'div', ImageContentProps>(
return fetchAuthenticatedMedia(mediaUrl, accessToken);
}
return mediaUrl;
}, [mx, url, useAuthentication, mimeType, encInfo])
}, [mx, url, useAuthentication, mimeType, encInfo]),
);
const handleLoad = () => {
@@ -228,7 +252,7 @@ export const ImageContent = as<'div', ImageContentProps>(
css.AbsoluteContainer,
css.MediaFadeIn,
load && css.MediaFadeInLoaded,
blurred && css.Blur
blurred && css.Blur,
)}
>
{renderImage({
@@ -327,5 +351,5 @@ export const ImageContent = as<'div', ImageContentProps>(
)}
</Box>
);
}
},
);
@@ -2,7 +2,12 @@ import { ReactNode, useCallback, useEffect } from 'react';
import { IThumbnailContent } from '../../../../types/matrix/common';
import { useMatrixClient } from '../../../hooks/useMatrixClient';
import { AsyncStatus, useAsyncCallback } from '../../../hooks/useAsyncCallback';
import { decryptFile, downloadEncryptedMedia, isAuthenticatedMediaUrl, mxcUrlToHttp } from '../../../utils/matrix';
import {
decryptFile,
downloadEncryptedMedia,
isAuthenticatedMediaUrl,
mxcUrlToHttp,
} from '../../../utils/matrix';
import { useMediaAuthentication } from '../../../hooks/useMediaAuthentication';
import { FALLBACK_MIMETYPE } from '../../../utils/mimeTypes';
import { getCurrentAccessToken } from '../../../utils/auth';
@@ -14,28 +19,36 @@ import { getCurrentAccessToken } from '../../../utils/auth';
*/
const fetchAuthenticatedMedia = async (
url: string,
accessToken: string | null
accessToken: string | null,
): Promise<string> => {
try {
let response = await fetch(url, {
method: 'GET',
headers: accessToken ? { Authorization: `Bearer ${accessToken}` } : undefined,
});
// If we got a 401 and we tried with auth, fallback to unauthenticated request
if (!response.ok && response.status === 401 && accessToken) {
console.warn('[ThumbnailContent] Auth failed (401), attempting unauthenticated fallback for:', url);
console.warn(
'[ThumbnailContent] Auth failed (401), attempting unauthenticated fallback for:',
url,
);
response = await fetch(url, { method: 'GET' });
}
if (!response.ok) {
console.warn(`[ThumbnailContent] Failed to fetch authenticated media (${response.status}), falling back to original URL`);
console.warn(
`[ThumbnailContent] Failed to fetch authenticated media (${response.status}), falling back to original URL`,
);
return url;
}
const blob = await response.blob();
return URL.createObjectURL(blob);
} catch (error) {
console.warn('[ThumbnailContent] Error fetching authenticated media, falling back to original URL:', error);
console.warn(
'[ThumbnailContent] Error fetching authenticated media, falling back to original URL:',
error,
);
return url;
}
};
@@ -51,7 +64,8 @@ export function ThumbnailContent({ info, renderImage }: ThumbnailContentProps) {
// Check if we have valid thumbnail data
const thumbInfo = info.thumbnail_info;
const thumbMxcUrl = info.thumbnail_file?.url ?? info.thumbnail_url;
const hasValidThumbnail = typeof thumbMxcUrl === 'string' && typeof thumbInfo?.mimetype === 'string';
const hasValidThumbnail =
typeof thumbMxcUrl === 'string' && typeof thumbInfo?.mimetype === 'string';
const [thumbSrcState, loadThumbSrc] = useAsyncCallback(
useCallback(async () => {
@@ -64,7 +78,7 @@ export function ThumbnailContent({ info, renderImage }: ThumbnailContentProps) {
const fileContent = await downloadEncryptedMedia(
mediaUrl,
(encBuf) => decryptFile(encBuf, thumbInfo.mimetype ?? FALLBACK_MIMETYPE, encInfo),
accessToken
accessToken,
);
return URL.createObjectURL(fileContent);
}
@@ -75,7 +89,7 @@ export function ThumbnailContent({ info, renderImage }: ThumbnailContentProps) {
}
return mediaUrl;
}, [mx, thumbMxcUrl, thumbInfo, info.thumbnail_file, useAuthentication])
}, [mx, thumbMxcUrl, thumbInfo, info.thumbnail_file, useAuthentication]),
);
useEffect(() => {
@@ -1,10 +1,24 @@
import React, { ReactNode, useCallback, useEffect, useState } from 'react';
import { Badge, Box, Button, Chip, Modal, Overlay, OverlayBackdrop, OverlayCenter, Spinner, Text, Tooltip, TooltipProvider, as } from 'folds';
import { Icon, Icons } from '../../icons';
import {
Badge,
Box,
Button,
Chip,
Modal,
Overlay,
OverlayBackdrop,
OverlayCenter,
Spinner,
Text,
Tooltip,
TooltipProvider,
as,
} from 'folds';
import classNames from 'classnames';
import { Blurhash } from 'react-blurhash';
import FocusTrap from 'focus-trap-react';
import { EncryptedAttachmentInfo } from 'browser-encrypt-attachment';
import { Icon, Icons } from '../../icons';
import {
IThumbnailContent,
IVideoInfo,
@@ -25,7 +39,12 @@ import { useMediaAuthentication } from '../../../hooks/useMediaAuthentication';
import { validBlurHash } from '../../../utils/blurHash';
import { ModalWide } from '../../../styles/Modal.css';
import { stopPropagation } from '../../../utils/keyboard';
import { setMediaDimensions, getMediaBlurHash, getMediaDimensions, rememberMediaBlurHash } from '../../../state/mediaDimensionCache';
import {
setMediaDimensions,
getMediaBlurHash,
getMediaDimensions,
rememberMediaBlurHash,
} from '../../../state/mediaDimensionCache';
type RenderViewerProps = {
src: string;
@@ -71,7 +90,7 @@ export const VideoContent = as<'div', VideoContentProps>(
renderVideo,
...props
},
ref
ref,
) => {
const mx = useMatrixClient();
const useAuthentication = useMediaAuthentication();
@@ -83,9 +102,7 @@ export const VideoContent = as<'div', VideoContentProps>(
const blurW = info.w ?? info.thumbnail_info?.w ?? cachedDims?.w;
const blurH = info.h ?? info.thumbnail_info?.h ?? cachedDims?.h;
const blurResolutionY =
blurW && blurH && blurW > 0
? Math.max(1, Math.round(blurResolutionX * (blurH / blurW)))
: 32;
blurW && blurH && blurW > 0 ? Math.max(1, Math.round(blurResolutionX * (blurH / blurW))) : 32;
const [load, setLoad] = useState(false);
const [error, setError] = useState(false);
@@ -99,12 +116,14 @@ export const VideoContent = as<'div', VideoContentProps>(
// Always use current session's token to avoid stale tokens during account switches
const accessToken = getCurrentAccessToken();
const fileContent = encInfo
? await downloadEncryptedMedia(mediaUrl, (encBuf) =>
decryptFile(encBuf, mimeType, encInfo), accessToken
? await downloadEncryptedMedia(
mediaUrl,
(encBuf) => decryptFile(encBuf, mimeType, encInfo),
accessToken,
)
: await downloadMedia(mediaUrl, accessToken);
return URL.createObjectURL(fileContent);
}, [mx, url, useAuthentication, mimeType, encInfo])
}, [mx, url, useAuthentication, mimeType, encInfo]),
);
const handleLoad = (video?: HTMLVideoElement) => {
@@ -207,7 +226,7 @@ export const VideoContent = as<'div', VideoContentProps>(
css.AbsoluteContainer,
css.MediaFadeIn,
load && css.MediaFadeInLoaded,
blurred && css.Blur
blurred && css.Blur,
)}
>
{renderVideo({
@@ -306,5 +325,5 @@ export const VideoContent = as<'div', VideoContentProps>(
)}
</Box>
);
}
},
);
@@ -2,13 +2,18 @@ import { ReactNode, useCallback, useEffect, useState } from 'react';
import { EncryptedAttachmentInfo } from 'browser-encrypt-attachment';
import { useMatrixClient } from '../../../hooks/useMatrixClient';
import { AsyncStatus, useAsyncCallback } from '../../../hooks/useAsyncCallback';
import { decryptFile, downloadEncryptedMedia, downloadMedia, mxcUrlToHttp } from '../../../utils/matrix';
import {
decryptFile,
downloadEncryptedMedia,
downloadMedia,
mxcUrlToHttp,
} from '../../../utils/matrix';
import { useMediaAuthentication } from '../../../hooks/useMediaAuthentication';
import { getCurrentAccessToken } from '../../../utils/auth';
/**
* Extracts the first frame from a video file and renders it as a thumbnail.
* This is used as a fallback when no thumbnail metadata is provided.
* This is used as a fallback when no thumbnail metadata is provided.
*/
export type VideoFrameThumbnailProps = {
mimeType: string;
@@ -31,15 +36,17 @@ export function VideoFrameThumbnail({
useCallback(async () => {
const mediaUrl = mxcUrlToHttp(mx, url, useAuthentication) ?? url;
const accessToken = getCurrentAccessToken();
const fileContent = encInfo
? await downloadEncryptedMedia(mediaUrl, (encBuf) =>
decryptFile(encBuf, mimeType, encInfo), accessToken
? await downloadEncryptedMedia(
mediaUrl,
(encBuf) => decryptFile(encBuf, mimeType, encInfo),
accessToken,
)
: await downloadMedia(mediaUrl, accessToken);
return URL.createObjectURL(fileContent);
}, [mx, url, useAuthentication, mimeType, encInfo])
}, [mx, url, useAuthentication, mimeType, encInfo]),
);
useEffect(() => {
@@ -69,7 +76,7 @@ export function VideoFrameThumbnail({
const cleanup = () => {
if (isCleanedUp) return;
isCleanedUp = true;
if (handlers.loadedData) video.removeEventListener('loadeddata', handlers.loadedData);
if (handlers.seeked) video.removeEventListener('seeked', handlers.seeked);
if (handlers.error) video.removeEventListener('error', handlers.error);
@@ -90,7 +97,7 @@ export function VideoFrameThumbnail({
const canvas = document.createElement('canvas');
canvas.width = video.videoWidth;
canvas.height = video.videoHeight;
const ctx = canvas.getContext('2d');
if (!ctx) {
cleanup();
@@ -98,14 +105,18 @@ export function VideoFrameThumbnail({
}
ctx.drawImage(video, 0, 0, canvas.width, canvas.height);
canvas.toBlob((blob) => {
if (blob) {
const thumbnailUrl = URL.createObjectURL(blob);
setThumbnailSrc(thumbnailUrl);
}
cleanup();
}, 'image/jpeg', 0.85);
canvas.toBlob(
(blob) => {
if (blob) {
const thumbnailUrl = URL.createObjectURL(blob);
setThumbnailSrc(thumbnailUrl);
}
cleanup();
},
'image/jpeg',
0.85,
);
} catch {
cleanup();
}
+38 -33
View File
@@ -6,17 +6,20 @@ import { isStationeryTheme, useTheme } from '../../../hooks/useTheme';
import { STATIONERY_NAME_INK } from '../../../utils/paperSafeInk';
export const MessageBase = as<'div', css.MessageBaseVariants>(
({ className, highlight, selected, collapse, autoCollapse, space, newMessage, ...props }, ref) => (
(
{ className, highlight, selected, collapse, autoCollapse, space, newMessage, ...props },
ref,
) => (
<div
className={classNames(
css.MessageBase({ highlight, selected, collapse, autoCollapse, space, newMessage }),
className
className,
)}
data-message-collapsed={collapse ? '' : undefined}
{...props}
ref={ref}
/>
)
),
);
export const AvatarBase = as<'span'>(({ className, ...props }, ref) => (
@@ -28,37 +31,39 @@ export const AvatarBase = as<'span'>(({ className, ...props }, ref) => (
/>
));
export const Username = as<'span'>(({ as: AsUsername = 'span', className, style, ...props }, ref) => {
const theme = useTheme();
const isStationery = isStationeryTheme(theme);
const userColor =
typeof (style as CSSProperties | undefined)?.color === 'string'
? ((style as CSSProperties).color as string)
: undefined;
export const Username = as<'span'>(
({ as: AsUsername = 'span', className, style, ...props }, ref) => {
const theme = useTheme();
const isStationery = isStationeryTheme(theme);
const userColor =
typeof (style as CSSProperties | undefined)?.color === 'string'
? ((style as CSSProperties).color as string)
: undefined;
const safeStyle = useMemo((): CSSProperties | undefined => {
if (!isStationery) return style as CSSProperties | undefined;
return {
...(style as CSSProperties | undefined),
// Name in ink; keep their color as an accent underline
color: STATIONERY_NAME_INK,
...(userColor
? { ['--username-accent' as string]: userColor, textDecorationColor: userColor }
: null),
};
}, [style, isStationery, userColor]);
const safeStyle = useMemo((): CSSProperties | undefined => {
if (!isStationery) return style as CSSProperties | undefined;
return {
...(style as CSSProperties | undefined),
// Name in ink; keep their color as an accent underline
color: STATIONERY_NAME_INK,
...(userColor
? { ['--username-accent' as string]: userColor, textDecorationColor: userColor }
: null),
};
}, [style, isStationery, userColor]);
return (
<AsUsername
className={classNames(css.Username, className)}
data-message-username=""
data-username-accent={isStationery && userColor ? '' : undefined}
style={safeStyle}
{...props}
ref={ref}
/>
);
});
return (
<AsUsername
className={classNames(css.Username, className)}
data-message-username=""
data-username-accent={isStationery && userColor ? '' : undefined}
style={safeStyle}
{...props}
ref={ref}
/>
);
},
);
export const UsernameBold = as<'b'>(({ as: AsUsernameBold = 'b', className, ...props }, ref) => (
<AsUsernameBold className={classNames(css.UsernameBold, className)} {...props} ref={ref} />
@@ -77,5 +82,5 @@ export const MessageTextBody = as<'div', css.MessageTextBodyVariants & { notice?
{...props}
ref={ref}
/>
)
),
);
+1 -1
View File
@@ -59,5 +59,5 @@ export const BubbleLayout = as<'div', BubbleLayoutProps>(
)}
</Box>
</Box>
)
),
);
@@ -14,5 +14,5 @@ export const CompactLayout = as<'div', CompactLayoutProps>(
</Box>
{children}
</Box>
)
),
);
@@ -1,7 +1,7 @@
import { createVar, globalStyle, keyframes, style, styleVariants } from '@vanilla-extract/css';
import * as htmlCss from '../../../styles/CustomHtml.css';
import { recipe, RecipeVariants } from '@vanilla-extract/recipes';
import { DefaultReset, color, config, toRem } from 'folds';
import * as htmlCss from '../../../styles/CustomHtml.css';
export const StickySection = style({
position: 'sticky',
@@ -23,5 +23,5 @@ export const CompactPlaceholder = as<'div', { variant?: ContainerColor }>(
<LinePlaceholder variant={variant} style={{ maxWidth: toRem(msgSize) }} />
</CompactLayout>
);
}
},
);
@@ -35,5 +35,5 @@ export const DefaultPlaceholder = as<'div', { variant?: ContainerColor }>(
</Box>
</ModernLayout>
);
}
},
);
@@ -11,5 +11,5 @@ export const LinePlaceholder = as<'div', css.LinePlaceholderVariants>(
{...props}
ref={ref}
/>
)
),
);
+1 -1
View File
@@ -15,5 +15,5 @@ export const NavCategoryHeader = as<'div', NavCategoryHeaderProps>(
{...props}
ref={ref}
/>
)
),
);
+2 -2
View File
@@ -24,11 +24,11 @@ export const NavItem = as<
export const NavLink = forwardRef<HTMLAnchorElement, ComponentProps<typeof Link>>(
({ className, ...props }, ref) => (
<Link className={classNames(css.NavLink, className)} {...props} ref={ref} />
)
),
);
export const NavButton = as<'button'>(
({ as: AsNavButton = 'button', className, ...props }, ref) => (
<AsNavButton className={classNames(css.NavLink, className)} {...props} ref={ref} />
)
),
);
+1 -1
View File
@@ -6,5 +6,5 @@ import * as css from './styles.css';
export const NavItemContent = as<'span', ComponentProps<typeof Text>>(
({ className, ...props }, ref) => (
<Text className={classNames(css.NavItemContent, className)} size="T300" {...props} ref={ref} />
)
),
);
+1 -1
View File
@@ -13,5 +13,5 @@ export const NavItemOptions = as<'div', ComponentProps<typeof Box>>(
{...props}
ref={ref}
/>
)
),
);
+3 -3
View File
@@ -65,7 +65,7 @@ export const PageNavHeader = as<'header', css.PageNavHeaderVariants>(
{...props}
ref={ref}
/>
)
),
);
export function PageNavContent({
@@ -118,7 +118,7 @@ export const PageHeader = as<'div', css.PageHeaderVariants>(
{...props}
ref={ref}
/>
)
),
);
export const PageContent = as<'div'>(({ className, ...props }, ref) => (
@@ -147,7 +147,7 @@ export const PageHeroSection = as<'div', ComponentProps<typeof Box>>(
{...props}
ref={ref}
/>
)
),
);
export function PageHero({
@@ -42,5 +42,5 @@ export const PasswordInput = forwardRef<HTMLInputElement, PasswordInputProps>(
)}
</UseStateProvider>
);
}
},
);
+1 -1
View File
@@ -17,5 +17,5 @@ export const PowerColorBadge = as<'span', PowerColorBadgeProps>(
{...props}
ref={ref}
/>
)
),
);
+1 -1
View File
@@ -46,7 +46,7 @@ export const PowerSelector = forwardRef<HTMLDivElement, PowerSelectorProps>(
</Scroll>
</Box>
</Menu>
)
),
);
type PowerSwitcherProps = PowerSelectorProps & {
+5 -2
View File
@@ -65,7 +65,10 @@ type AvatarPresenceProps = {
badgeBackgroundColor?: string;
};
export const AvatarPresence = as<'div', AvatarPresenceProps>(
({ as: AsAvatarPresence, badge, variant = 'Surface', badgeBackgroundColor, children, ...props }, ref) => (
(
{ as: AsAvatarPresence, badge, variant = 'Surface', badgeBackgroundColor, children, ...props },
ref,
) => (
<Box as={AsAvatarPresence} className={css.AvatarPresence} {...props} ref={ref}>
{children}
{badge && (
@@ -77,5 +80,5 @@ export const AvatarPresence = as<'div', AvatarPresenceProps>(
</div>
)}
</Box>
)
),
);
@@ -66,7 +66,7 @@ export type InaccessibleScanResult = {
*/
export async function collectInaccessibleSpaceChildren(
mx: MatrixClient,
rootSpaceId: string
rootSpaceId: string,
): Promise<InaccessibleScanResult> {
let hierarchySummaries = new Map<string, { room_id: string }>();
try {
@@ -125,7 +125,7 @@ export async function collectInaccessibleSpaceChildren(
async function removeSpaceChildrenSequentially(
mx: MatrixClient,
children: InaccessibleSpaceChild[],
onProgress?: (current: number, total: number) => void
onProgress?: (current: number, total: number) => void,
): Promise<void> {
const total = children.length;
@@ -160,7 +160,7 @@ export function RemoveInaccessiblePrompt({
const [scanResult, setScanResult] = useState<InaccessibleScanResult | null>(null);
const [scanState, scan] = useAsyncCallback<InaccessibleScanResult, MatrixError | Error, []>(
useCallback(async () => collectInaccessibleSpaceChildren(mx, roomId), [mx, roomId])
useCallback(async () => collectInaccessibleSpaceChildren(mx, roomId), [mx, roomId]),
);
const children = scanResult?.inaccessible ?? null;
@@ -172,7 +172,7 @@ export function RemoveInaccessiblePrompt({
setProgress({ current, total });
});
setProgress(null);
}, [mx, children])
}, [mx, children]),
);
useEffect(() => {
@@ -191,8 +191,12 @@ export function RemoveInaccessiblePrompt({
}
}, [removeState, onDone]);
const previewIds = useMemo(() => (children ?? []).slice(0, PREVIEW_LIMIT).map((c) => c.roomId), [children]);
const isScanning = scanState.status === AsyncStatus.Loading || scanState.status === AsyncStatus.Idle;
const previewIds = useMemo(
() => (children ?? []).slice(0, PREVIEW_LIMIT).map((c) => c.roomId),
[children],
);
const isScanning =
scanState.status === AsyncStatus.Loading || scanState.status === AsyncStatus.Idle;
const isRemoving = removeState.status === AsyncStatus.Loading;
const count = children?.length ?? 0;
+14 -6
View File
@@ -1,8 +1,15 @@
import { JoinRule } from 'matrix-js-sdk';
import { AvatarFallback, AvatarImage, color } from 'folds';
import { Icon, Icons } from '../icons';
import React, { ComponentProps, ReactEventHandler, ReactNode, forwardRef, useEffect, useState } from 'react';
import React, {
ComponentProps,
ReactEventHandler,
ReactNode,
forwardRef,
useEffect,
useState,
} from 'react';
import { Blurhash } from 'react-blurhash';
import { Icon, Icons } from '../icons';
import * as css from './RoomAvatar.css';
import { joinRuleToIconSrc } from '../../utils/room';
import colorMXID from '../../../util/colorMXID';
@@ -33,16 +40,17 @@ export function RoomAvatar({ roomId, src, alt, renderFallback }: RoomAvatarProps
const dims = getMediaDimensions(src ?? '');
const blobCached =
!!src &&
(!useAuthentication ||
!isAuthenticatedMediaUrl(src) ||
!!getCachedAuthenticatedMediaUrl(src));
(!useAuthentication || !isAuthenticatedMediaUrl(src) || !!getCachedAuthenticatedMediaUrl(src));
const [loaded, setLoaded] = useState(() => isAvatarCached(src) || blobCached);
useEffect(() => {
if (
authenticatedSrc &&
(isAvatarCached(src) ||
(src && (!useAuthentication || !isAuthenticatedMediaUrl(src) || getCachedAuthenticatedMediaUrl(src))))
(src &&
(!useAuthentication ||
!isAuthenticatedMediaUrl(src) ||
getCachedAuthenticatedMediaUrl(src))))
) {
setLoaded(true);
}
+28 -10
View File
@@ -1,9 +1,23 @@
import React, { ReactNode, useCallback, useRef, useState } from 'react';
import { MatrixError, Room } from 'matrix-js-sdk';
import { Avatar, Badge, Box, Button, Dialog, Overlay, OverlayBackdrop, OverlayCenter, Spinner, Text, as, color, config } from 'folds';
import { Icon, Icons } from '../icons';
import {
Avatar,
Badge,
Box,
Button,
Dialog,
Overlay,
OverlayBackdrop,
OverlayCenter,
Spinner,
Text,
as,
color,
config,
} from 'folds';
import classNames from 'classnames';
import FocusTrap from 'focus-trap-react';
import { Icon, Icons } from '../icons';
import * as css from './style.css';
import { RoomAvatar } from '../room-avatar';
import { getMxIdLocalPart, mxcUrlToHttp } from '../../utils/matrix';
@@ -36,7 +50,7 @@ export function RoomCardGrid({ children }: { children: ReactNode }) {
useElementSizeObserver(
useCallback(() => gridRef.current, []),
useCallback((width, _, target) => setGridColumnCount(target, getGridColumnCount(width)), [])
useCallback((width, _, target) => setGridColumnCount(target, getGridColumnCount(width)), []),
);
return (
@@ -145,7 +159,7 @@ export const RoomCard = as<'div', RoomCardProps>(
renderTopicViewer,
...props
},
ref
ref,
) => {
const mx = useMatrixClient();
const useAuthentication = useMediaAuthentication();
@@ -153,7 +167,7 @@ export const RoomCard = as<'div', RoomCardProps>(
const joinedRoom = mx.getRoom(joinedRoomId);
const createEvent = joinedRoom ? getStateEvent(joinedRoom, StateEvent.RoomCreate) : undefined;
const [topicEvent, setTopicEvent] = useState(() =>
joinedRoom ? getStateEvent(joinedRoom, StateEvent.RoomTopic) : undefined
joinedRoom ? getStateEvent(joinedRoom, StateEvent.RoomTopic) : undefined,
);
const fallbackName = getMxIdLocalPart(roomIdOrAlias) ?? roomIdOrAlias;
@@ -180,12 +194,15 @@ export const RoomCard = as<'div', RoomCardProps>(
setTopicEvent(getStateEvent(joinedRoom, StateEvent.RoomTopic));
}
},
[joinedRoom]
)
[joinedRoom],
),
);
const [joinState, join] = useAsyncCallback<Room, MatrixError, []>(
useCallback(() => mx.joinRoom(roomIdOrAlias, { viaServers }), [mx, roomIdOrAlias, viaServers])
useCallback(
() => mx.joinRoom(roomIdOrAlias, { viaServers }),
[mx, roomIdOrAlias, viaServers],
),
);
const joining =
joinState.status === AsyncStatus.Loading || joinState.status === AsyncStatus.Success;
@@ -197,7 +214,8 @@ export const RoomCard = as<'div', RoomCardProps>(
const [showSpaceJoinPrompt, setShowSpaceJoinPrompt] = useState(false);
const isSpace = roomType === RoomType.Space || joinedRoom?.isSpaceRoom();
const isForum =
roomType === RoomType.Forum || createEvent?.getContent<{ type?: string }>().type === RoomType.Forum;
roomType === RoomType.Forum ||
createEvent?.getContent<{ type?: string }>().type === RoomType.Forum;
const handleJoinClick = () => {
if (isSpace) {
@@ -334,5 +352,5 @@ export const RoomCard = as<'div', RoomCardProps>(
)}
</RoomCardBase>
);
}
},
);
+1 -1
View File
@@ -43,7 +43,7 @@ export const RoomIntro = as<'div', RoomIntroProps>(({ room, ...props }, ref) =>
const prevRoomId = createContent?.predecessor?.room_id;
const [prevRoomState, joinPrevRoom] = useAsyncCallback(
useCallback(async (roomId: string) => mx.joinRoom(roomId), [mx])
useCallback(async (roomId: string) => mx.joinRoom(roomId), [mx]),
);
const [hour24Clock] = useSetting(settingsAtom, 'hour24Clock');
@@ -1,8 +1,8 @@
import React from 'react';
import { as, Box, Header, IconButton, Modal, Scroll, Text } from 'folds';
import { Icon, Icons } from '../icons';
import classNames from 'classnames';
import Linkify from 'linkify-react';
import { Icon, Icons } from '../icons';
import * as css from './style.css';
import { LINKIFY_OPTS, scaleSystemEmoji } from '../../plugins/react-custom-html-parser';

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