mirror of
https://github.com/SableClient/Sable.git
synced 2026-11-21 09:31:17 -08:00
Merge branch 'dev' into resize-side-panels
This commit is contained in:
74 files changed
+3046
-892
No files matched your search
@@ -0,0 +1,30 @@
|
||||
import { describe, expect, it } from 'vitest';
|
||||
import { toMatrixCustomHTML, trimCustomHtml } from '$components/editor/output';
|
||||
import { BlockType } from '$components/editor/types';
|
||||
|
||||
describe('toMatrixCustomHTML emoticons', () => {
|
||||
it('always serializes custom emoji images with height=32', () => {
|
||||
const html = trimCustomHtml(
|
||||
toMatrixCustomHTML(
|
||||
[
|
||||
{
|
||||
type: BlockType.Paragraph,
|
||||
children: [
|
||||
{
|
||||
type: BlockType.Emoticon,
|
||||
key: 'mxc://example.org/emote',
|
||||
shortcode: 'blobcat',
|
||||
children: [{ text: '' }],
|
||||
} as never,
|
||||
],
|
||||
} as never,
|
||||
],
|
||||
{}
|
||||
)
|
||||
);
|
||||
|
||||
expect(html).toContain('data-mx-emoticon');
|
||||
expect(html).toContain('mxc://example.org/emote');
|
||||
expect(html).toContain('height="32"');
|
||||
});
|
||||
});
|
||||
@@ -5,6 +5,7 @@ export const EventReaders = style([
|
||||
DefaultReset,
|
||||
{
|
||||
height: '100%',
|
||||
width: '280px',
|
||||
},
|
||||
]);
|
||||
|
||||
@@ -18,4 +19,6 @@ export const Header = style({
|
||||
export const Content = style({
|
||||
paddingLeft: config.space.S200,
|
||||
paddingBottom: config.space.S400,
|
||||
width: '100%',
|
||||
minWidth: 0,
|
||||
});
|
||||
@@ -58,9 +58,14 @@ export const EventReaders = as<'div', EventReadersProps>(
|
||||
<Icon src={Icons.Cross} />
|
||||
</IconButton>
|
||||
</Header>
|
||||
<Box grow="Yes">
|
||||
<Box className={css.Content} direction="Column">
|
||||
<Scroll visibility="Hover" hideTrack size="300">
|
||||
<Box grow="Yes" style={{ width: '100%', minWidth: 0 }}>
|
||||
<Box
|
||||
grow="Yes"
|
||||
className={css.Content}
|
||||
direction="Column"
|
||||
style={{ width: '100%', minWidth: 0 }}
|
||||
>
|
||||
<Scroll visibility="Hover" hideTrack size="300" style={{ width: '100%' }}>
|
||||
{latestEventReaders.map((readerId) => {
|
||||
const name = getName(readerId);
|
||||
const avatarMxcUrl = room.getMember(readerId)?.getMxcAvatarUrl();
|
||||
@@ -79,7 +84,7 @@ export const EventReaders = as<'div', EventReadersProps>(
|
||||
return (
|
||||
<MenuItem
|
||||
key={readerId}
|
||||
style={{ padding: `0 ${config.space.S200}` }}
|
||||
style={{ padding: `0 ${config.space.S200}`, width: '100%' }}
|
||||
radii="400"
|
||||
onClick={(event) => {
|
||||
openProfile(
|
||||
|
||||
@@ -29,7 +29,7 @@ export const MemberTile = as<'button', MemberTileProps>(
|
||||
const name = getName(room, member, nicknames);
|
||||
const presence = useUserPresence(member.userId ?? '');
|
||||
|
||||
const avatarMxcUrl = member.getMxcAvatarUrl();
|
||||
const avatarMxcUrl = member.getMxcAvatarUrl() ?? mx.getUser(member.userId)?.avatarUrl;
|
||||
const avatarUrl = avatarMxcUrl
|
||||
? mx.mxcUrlToHttp(avatarMxcUrl, 100, 100, 'crop', undefined, false, useAuthentication)
|
||||
: undefined;
|
||||
|
||||
@@ -26,6 +26,8 @@ import { useIgnoredUsers } from '$hooks/useIgnoredUsers';
|
||||
import { nicknamesAtom } from '$state/nicknames';
|
||||
import { useMatrixClient } from '$hooks/useMatrixClient';
|
||||
import { useMemberEventParser } from '$hooks/useMemberEventParser';
|
||||
import { useSetting } from '$state/hooks/settings';
|
||||
import { settingsAtom } from '$state/settings';
|
||||
|
||||
import { useMentionClickHandler } from '$hooks/useMentionClickHandler';
|
||||
import { useTranslation } from 'react-i18next';
|
||||
@@ -139,6 +141,14 @@ export const Reply = as<'div', ReplyProps>(
|
||||
const nicknames = useAtomValue(nicknamesAtom);
|
||||
const useAuthentication = useMediaAuthentication();
|
||||
const settingsLinkBaseUrl = useSettingsLinkBaseUrl();
|
||||
const [incomingInlineImagesDefaultHeight] = useSetting(
|
||||
settingsAtom,
|
||||
'incomingInlineImagesDefaultHeight'
|
||||
);
|
||||
const [incomingInlineImagesMaxHeight] = useSetting(
|
||||
settingsAtom,
|
||||
'incomingInlineImagesMaxHeight'
|
||||
);
|
||||
|
||||
const fallbackBody = isRedacted ? <MessageDeletedContent /> : <MessageFailedContent />;
|
||||
|
||||
@@ -190,6 +200,8 @@ export const Reply = as<'div', ReplyProps>(
|
||||
useAuthentication,
|
||||
nicknames,
|
||||
handleMentionClick: mentionClickHandler,
|
||||
incomingInlineImagesDefaultHeight,
|
||||
incomingInlineImagesMaxHeight,
|
||||
});
|
||||
bodyJSX = parse(sanitizedHtml, parserOpts) as JSX.Element;
|
||||
} else if (hasPlainTextReply) {
|
||||
@@ -280,7 +292,7 @@ export const Reply = as<'div', ReplyProps>(
|
||||
onClick={replyEvent !== null && !isBlockedSender ? onClick : undefined}
|
||||
>
|
||||
{replyEvent !== undefined && !isPendingDecrypt ? (
|
||||
<Text size="T300" truncate>
|
||||
<Text size="T300" truncate style={{ unicodeBidi: 'plaintext' }}>
|
||||
{replyContent}
|
||||
</Text>
|
||||
) : (
|
||||
|
||||
@@ -19,6 +19,7 @@ import {
|
||||
TooltipProvider,
|
||||
as,
|
||||
config,
|
||||
toRem,
|
||||
} from 'folds';
|
||||
import classNames from 'classnames';
|
||||
import { BlurhashCanvas } from 'react-blurhash';
|
||||
@@ -37,6 +38,23 @@ import { validBlurHash } from '$utils/blurHash';
|
||||
import * as css from './style.css';
|
||||
import { MATRIX_UNSTABLE_BLUR_HASH_PROPERTY_NAME } from '../../../../unstable/prefixes';
|
||||
|
||||
function thumbnailDimsForMaxEdge(
|
||||
maxEdge: number,
|
||||
w?: number,
|
||||
h?: number
|
||||
): { tw: number; th: number } {
|
||||
const safeEdge = Math.max(1, Math.round(maxEdge));
|
||||
const iw = typeof w === 'number' && Number.isFinite(w) && w > 0 ? w : safeEdge;
|
||||
const ih = typeof h === 'number' && Number.isFinite(h) && h > 0 ? h : safeEdge;
|
||||
const longest = Math.max(iw, ih);
|
||||
if (longest <= safeEdge) return { tw: Math.round(iw), th: Math.round(ih) };
|
||||
const scale = safeEdge / longest;
|
||||
return {
|
||||
tw: Math.max(1, Math.round(iw * scale)),
|
||||
th: Math.max(1, Math.round(ih * scale)),
|
||||
};
|
||||
}
|
||||
|
||||
type RenderViewerProps = {
|
||||
src: string;
|
||||
alt: string;
|
||||
@@ -62,6 +80,10 @@ export type ImageContentProps = {
|
||||
spoilerReason?: string;
|
||||
renderViewer: (props: RenderViewerProps) => ReactNode;
|
||||
renderImage: (props: RenderImageProps) => ReactNode;
|
||||
matrixThumbnailMaxEdge?: number;
|
||||
mediaLayout?: 'default' | 'contained';
|
||||
containedStripMinPx?: number;
|
||||
fillsPreviewSlot?: boolean;
|
||||
};
|
||||
export const ImageContent = as<'div', ImageContentProps>(
|
||||
(
|
||||
@@ -78,6 +100,10 @@ export const ImageContent = as<'div', ImageContentProps>(
|
||||
spoilerReason,
|
||||
renderViewer,
|
||||
renderImage,
|
||||
matrixThumbnailMaxEdge,
|
||||
mediaLayout = 'default',
|
||||
containedStripMinPx,
|
||||
fillsPreviewSlot,
|
||||
...props
|
||||
},
|
||||
ref
|
||||
@@ -89,6 +115,7 @@ export const ImageContent = as<'div', ImageContentProps>(
|
||||
const [load, setLoad] = useState(false);
|
||||
const [error, setError] = useState(false);
|
||||
const [viewer, setViewer] = useState(false);
|
||||
const [viewerFullSrc, setViewerFullSrc] = useState<string | null>(null);
|
||||
const [blurred, setBlurred] = useState(markedAsSpoiler ?? false);
|
||||
const [isHovered, setIsHovered] = useState(false);
|
||||
|
||||
@@ -96,6 +123,12 @@ export const ImageContent = as<'div', ImageContentProps>(
|
||||
useCallback(async () => {
|
||||
if (url.startsWith('http')) return url;
|
||||
|
||||
if (typeof matrixThumbnailMaxEdge === 'number' && matrixThumbnailMaxEdge > 0 && !encInfo) {
|
||||
const { tw, th } = thumbnailDimsForMaxEdge(matrixThumbnailMaxEdge, info?.w, info?.h);
|
||||
const thumbUrl = mxcUrlToHttp(mx, url, useAuthentication, tw, th, 'scale', false);
|
||||
if (thumbUrl) return thumbUrl;
|
||||
}
|
||||
|
||||
const mediaUrl = mxcUrlToHttp(mx, url, useAuthentication);
|
||||
if (!mediaUrl) throw new Error('Invalid media URL');
|
||||
if (encInfo) {
|
||||
@@ -105,9 +138,33 @@ export const ImageContent = as<'div', ImageContentProps>(
|
||||
return URL.createObjectURL(fileContent);
|
||||
}
|
||||
return mediaUrl;
|
||||
}, [mx, url, useAuthentication, mimeType, encInfo])
|
||||
}, [mx, url, useAuthentication, mimeType, encInfo, matrixThumbnailMaxEdge, info?.w, info?.h])
|
||||
);
|
||||
|
||||
useEffect(() => {
|
||||
if (!viewer) {
|
||||
setViewerFullSrc(null);
|
||||
return;
|
||||
}
|
||||
if (
|
||||
typeof matrixThumbnailMaxEdge !== 'number' ||
|
||||
matrixThumbnailMaxEdge <= 0 ||
|
||||
encInfo ||
|
||||
url.startsWith('http')
|
||||
) {
|
||||
return;
|
||||
}
|
||||
let cancelled = false;
|
||||
void (async () => {
|
||||
const mediaUrl = mxcUrlToHttp(mx, url, useAuthentication);
|
||||
if (!mediaUrl || cancelled) return;
|
||||
setViewerFullSrc(mediaUrl);
|
||||
})();
|
||||
return () => {
|
||||
cancelled = true;
|
||||
};
|
||||
}, [viewer, matrixThumbnailMaxEdge, encInfo, url, mx, useAuthentication]);
|
||||
|
||||
const handleLoad = () => {
|
||||
setLoad(true);
|
||||
};
|
||||
@@ -126,12 +183,36 @@ export const ImageContent = as<'div', ImageContentProps>(
|
||||
}, [autoPlay, loadSrc]);
|
||||
|
||||
const hasDimensions = typeof info?.w === 'number' && typeof info?.h === 'number';
|
||||
const isContained = mediaLayout === 'contained';
|
||||
const fillsSlot = Boolean(fillsPreviewSlot && isContained);
|
||||
const containedReserveStrip =
|
||||
!fillsSlot &&
|
||||
isContained &&
|
||||
(srcState.status === AsyncStatus.Loading ||
|
||||
srcState.status === AsyncStatus.Error ||
|
||||
error ||
|
||||
(srcState.status === AsyncStatus.Success && !load));
|
||||
|
||||
const rootClass = isContained ? css.ContainedMediaRoot : css.RelativeBase;
|
||||
const stripMin = containedStripMinPx ?? 56;
|
||||
const intrinsicSizingStyle = fillsSlot
|
||||
? {}
|
||||
: isContained
|
||||
? { minHeight: containedReserveStrip ? toRem(stripMin) : undefined }
|
||||
: hasDimensions
|
||||
? { aspectRatio: `${info!.w} / ${info!.h}` }
|
||||
: { minHeight: '150px' };
|
||||
|
||||
const fillPreviewSlotStyle = fillsSlot
|
||||
? ({ width: '100%', height: '100%' } as const)
|
||||
: undefined;
|
||||
|
||||
return (
|
||||
<Box
|
||||
className={classNames(css.RelativeBase, className)}
|
||||
className={classNames(rootClass, className)}
|
||||
style={{
|
||||
...(hasDimensions ? { aspectRatio: `${info.w} / ${info.h}` } : { minHeight: '150px' }),
|
||||
...fillPreviewSlotStyle,
|
||||
...intrinsicSizingStyle,
|
||||
...style,
|
||||
}}
|
||||
{...props}
|
||||
@@ -156,7 +237,7 @@ export const ImageContent = as<'div', ImageContentProps>(
|
||||
onContextMenu={(evt: React.MouseEvent) => evt.stopPropagation()}
|
||||
>
|
||||
{renderViewer({
|
||||
src: srcState.data,
|
||||
src: viewerFullSrc ?? srcState.data,
|
||||
alt: body,
|
||||
requestClose: () => setViewer(false),
|
||||
})}
|
||||
@@ -196,7 +277,7 @@ export const ImageContent = as<'div', ImageContentProps>(
|
||||
{srcState.status === AsyncStatus.Success && (
|
||||
<Box
|
||||
className={classNames(
|
||||
hasDimensions ? css.AbsoluteContainer : undefined,
|
||||
hasDimensions && !isContained ? css.AbsoluteContainer : undefined,
|
||||
blurred && css.Blur
|
||||
)}
|
||||
style={{ width: '100%' }}
|
||||
|
||||
@@ -10,6 +10,15 @@ export const RelativeBase = style([
|
||||
},
|
||||
]);
|
||||
|
||||
export const ContainedMediaRoot = style([
|
||||
DefaultReset,
|
||||
{
|
||||
position: 'relative',
|
||||
width: '100%',
|
||||
minHeight: 0,
|
||||
},
|
||||
]);
|
||||
|
||||
export const AbsoluteContainer = style([
|
||||
DefaultReset,
|
||||
{
|
||||
|
||||
@@ -48,6 +48,7 @@ export const MessageTextBody = as<'div', css.MessageTextBodyVariants & { notice?
|
||||
className={classNames(css.MessageTextBody({ preWrap, jumboEmoji, emote }), className)}
|
||||
{...props}
|
||||
ref={ref}
|
||||
dir="auto"
|
||||
>
|
||||
{children}
|
||||
</Text>
|
||||
|
||||
@@ -229,6 +229,8 @@ export const PronounPill = style({
|
||||
|
||||
export const MessageTextBody = recipe({
|
||||
base: {
|
||||
unicodeBidi: 'plaintext',
|
||||
alignSelf: 'start',
|
||||
wordBreak: 'break-word',
|
||||
fontSize: '1rem !important', // Override folds Text component to enable page zoom scaling
|
||||
},
|
||||
|
||||
@@ -31,6 +31,8 @@ import { roomUploadAtomFamily } from '$state/room/roomInputDrafts';
|
||||
import { useObjectURL } from '$hooks/useObjectURL';
|
||||
import { useMediaConfig } from '$hooks/useMediaConfig';
|
||||
import { useSettingsLinkBaseUrl } from '$features/settings/useSettingsLinkBaseUrl';
|
||||
import { useSetting } from '$state/hooks/settings';
|
||||
import { settingsAtom } from '$state/settings';
|
||||
import { UploadCard, UploadCardError, UploadCardProgress } from './UploadCard';
|
||||
import * as css from './UploadCard.css';
|
||||
import { DescriptionEditor } from './UploadDescriptionEditor';
|
||||
@@ -397,6 +399,11 @@ export function UploadCardRenderer({
|
||||
const spoilerClickHandler = useSpoilerClickHandler();
|
||||
const useAuthentication = useMediaAuthentication();
|
||||
const settingsLinkBaseUrl = useSettingsLinkBaseUrl();
|
||||
const [incomingInlineImagesDefaultHeight] = useSetting(
|
||||
settingsAtom,
|
||||
'incomingInlineImagesDefaultHeight'
|
||||
);
|
||||
const [incomingInlineImagesMaxHeight] = useSetting(settingsAtom, 'incomingInlineImagesMaxHeight');
|
||||
const htmlReactParserOptions = useMemo<HTMLReactParserOptions>(
|
||||
() =>
|
||||
getReactCustomHtmlParser(mx, roomId, {
|
||||
@@ -404,8 +411,19 @@ export function UploadCardRenderer({
|
||||
linkifyOpts,
|
||||
useAuthentication,
|
||||
handleSpoilerClick: spoilerClickHandler,
|
||||
incomingInlineImagesDefaultHeight,
|
||||
incomingInlineImagesMaxHeight,
|
||||
}),
|
||||
[linkifyOpts, mx, roomId, settingsLinkBaseUrl, spoilerClickHandler, useAuthentication]
|
||||
[
|
||||
linkifyOpts,
|
||||
mx,
|
||||
roomId,
|
||||
settingsLinkBaseUrl,
|
||||
spoilerClickHandler,
|
||||
useAuthentication,
|
||||
incomingInlineImagesDefaultHeight,
|
||||
incomingInlineImagesMaxHeight,
|
||||
]
|
||||
);
|
||||
return (
|
||||
<UploadCard
|
||||
|
||||
@@ -25,6 +25,13 @@ export const UrlPreviewImg = style([
|
||||
},
|
||||
]);
|
||||
|
||||
export const UrlPreviewMediaWell = style([
|
||||
DefaultReset,
|
||||
{
|
||||
backgroundColor: color.Surface.Container,
|
||||
},
|
||||
]);
|
||||
|
||||
export const UrlPreviewContent = style([
|
||||
DefaultReset,
|
||||
{
|
||||
|
||||
@@ -1,17 +1,34 @@
|
||||
import { useCallback, useEffect, useRef, useState } from 'react';
|
||||
import type { MatrixClient } from '$types/matrix-sdk';
|
||||
import type { IPreviewUrlResponse } from '$types/matrix-sdk';
|
||||
import { Box, Icon, IconButton, Icons, Scroll, Spinner, Text, as, color, config } from 'folds';
|
||||
import {
|
||||
Box,
|
||||
Icon,
|
||||
IconButton,
|
||||
Icons,
|
||||
Scroll,
|
||||
Spinner,
|
||||
Text,
|
||||
as,
|
||||
color,
|
||||
config,
|
||||
toRem,
|
||||
} from 'folds';
|
||||
import { AsyncStatus, useAsyncCallback } from '$hooks/useAsyncCallback';
|
||||
import { useMatrixClient } from '$hooks/useMatrixClient';
|
||||
import { mxcUrlToHttp, downloadMedia } from '$utils/matrix';
|
||||
import { useMediaAuthentication } from '$hooks/useMediaAuthentication';
|
||||
import { safeDecodeUrl } from '$plugins/react-custom-html-parser';
|
||||
import * as css from './UrlPreviewCard.css';
|
||||
import * as urlPreviewChrome from './UrlPreview.css';
|
||||
import { UrlPreview, UrlPreviewContent, UrlPreviewDescription } from './UrlPreview';
|
||||
import { AudioContent, ImageContent, VideoContent } from '../message';
|
||||
import { Image, MediaControl, Video } from '../media';
|
||||
import { ImageViewer } from '../image-viewer';
|
||||
import { useSetting } from '$state/hooks/settings';
|
||||
import { settingsAtom } from '$state/settings';
|
||||
import type { IImageInfo } from '$types/matrix/common';
|
||||
import { MATRIX_UNSTABLE_BLUR_HASH_PROPERTY_NAME } from '$unstable/prefixes';
|
||||
|
||||
const linkStyles = { color: color.Success.Main };
|
||||
|
||||
@@ -42,6 +59,32 @@ const openMediaInNewTab = async (url: string | undefined) => {
|
||||
window.open(blobUrl, '_blank');
|
||||
};
|
||||
|
||||
function ogPositiveDimension(value: unknown): number | undefined {
|
||||
if (typeof value === 'number' && Number.isFinite(value) && value > 0) return value;
|
||||
if (typeof value === 'string') {
|
||||
const n = Number.parseFloat(value);
|
||||
if (Number.isFinite(n) && n > 0) return n;
|
||||
}
|
||||
return undefined;
|
||||
}
|
||||
|
||||
function isLikelyPlayableOgVideo(prev: IPreviewUrlResponse): boolean {
|
||||
const raw = prev['og:video'];
|
||||
if (typeof raw !== 'string') return false;
|
||||
const url = raw.trim();
|
||||
if (!url) return false;
|
||||
const mime =
|
||||
typeof prev['og:video:type'] === 'string' ? prev['og:video:type'].toLowerCase().trim() : '';
|
||||
if (mime.startsWith('video/')) return true;
|
||||
if (/^mxc:\/\//i.test(url)) {
|
||||
return mime.startsWith('video/') || /\.(mp4|webm|ogg|mov|m4v)(\?|$)/i.test(url);
|
||||
}
|
||||
if (/^https?:\/\//i.test(url)) {
|
||||
return /\.(mp4|webm|ogg|mov|m4v)(\?|$)/i.test(url) || mime.startsWith('video/');
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
export const UrlPreviewCard = as<
|
||||
'div',
|
||||
{
|
||||
@@ -54,6 +97,7 @@ export const UrlPreviewCard = as<
|
||||
>(({ urlPreview, url, ts, mediaType, bundle, ...props }, ref) => {
|
||||
const mx = useMatrixClient();
|
||||
const useAuthentication = useMediaAuthentication();
|
||||
const [linkPreviewImageMaxHeight] = useSetting(settingsAtom, 'linkPreviewImageMaxHeight');
|
||||
|
||||
const isDirect = !!mediaType;
|
||||
|
||||
@@ -109,14 +153,49 @@ export const UrlPreviewCard = as<
|
||||
}
|
||||
};
|
||||
|
||||
const ogW = ((prev['og:video'] && prev['og:video:width']) ||
|
||||
(prev['og:image'] && prev['og:image:width']) ||
|
||||
1) as number;
|
||||
const ogH = ((prev['og:video'] && prev['og:video:height']) ||
|
||||
(prev['og:image'] && prev['og:image:height']) ||
|
||||
1) as number;
|
||||
const videoW = prev['og:video'] ? ogPositiveDimension(prev['og:video:width']) : undefined;
|
||||
const videoH = prev['og:video'] ? ogPositiveDimension(prev['og:video:height']) : undefined;
|
||||
const ogImgW = ogPositiveDimension(prev['og:image:width']);
|
||||
const ogImgH = ogPositiveDimension(prev['og:image:height']);
|
||||
|
||||
const aspectRatio = ogW && ogH ? `${ogW} / ${ogH}` : undefined;
|
||||
const aspectRatio =
|
||||
videoW && videoH
|
||||
? `${videoW} / ${videoH}`
|
||||
: ogImgW && ogImgH
|
||||
? `${ogImgW} / ${ogImgH}`
|
||||
: undefined;
|
||||
|
||||
const previewBlurRaw =
|
||||
typeof prev['matrix:image:blurhash'] === 'string' ? prev['matrix:image:blurhash'].trim() : '';
|
||||
|
||||
const ogImageInfo: IImageInfo | undefined = (() => {
|
||||
const matrixSize = prev['matrix:image:size'];
|
||||
const size =
|
||||
typeof matrixSize === 'number' && Number.isFinite(matrixSize) ? matrixSize : undefined;
|
||||
if (ogImgW && ogImgH) {
|
||||
return {
|
||||
w: ogImgW,
|
||||
h: ogImgH,
|
||||
...(size !== undefined ? { size } : {}),
|
||||
...(previewBlurRaw ? { [MATRIX_UNSTABLE_BLUR_HASH_PROPERTY_NAME]: previewBlurRaw } : {}),
|
||||
};
|
||||
}
|
||||
if (previewBlurRaw || size !== undefined) {
|
||||
return {
|
||||
w: 16,
|
||||
h: 9,
|
||||
...(size !== undefined ? { size } : {}),
|
||||
...(previewBlurRaw ? { [MATRIX_UNSTABLE_BLUR_HASH_PROPERTY_NAME]: previewBlurRaw } : {}),
|
||||
};
|
||||
}
|
||||
return undefined;
|
||||
})();
|
||||
|
||||
const previewThumbMaxEdge = Math.min(
|
||||
2048,
|
||||
Math.max(1, Math.round(Math.max(1, linkPreviewImageMaxHeight) * 2))
|
||||
);
|
||||
const showOgVideo = isLikelyPlayableOgVideo(prev);
|
||||
|
||||
return (
|
||||
<Box
|
||||
@@ -159,61 +238,89 @@ export const UrlPreviewCard = as<
|
||||
</Text>
|
||||
)}
|
||||
</UrlPreviewContent>
|
||||
{prev['og:video'] && (
|
||||
<VideoContent
|
||||
{showOgVideo && (
|
||||
<Box
|
||||
shrink="No"
|
||||
className={urlPreviewChrome.UrlPreviewMediaWell}
|
||||
style={{
|
||||
width: '100%',
|
||||
aspectRatio: aspectRatio ?? '10 / 9',
|
||||
maxHeight: toRem(linkPreviewImageMaxHeight),
|
||||
aspectRatio: aspectRatio ?? '16 / 9',
|
||||
flexShrink: 1,
|
||||
minHeight: 0,
|
||||
overflow: 'hidden',
|
||||
position: 'relative',
|
||||
}}
|
||||
body={prev['og:title']}
|
||||
info={{}}
|
||||
url={prev['og:video'] as string}
|
||||
mimeType={(prev['og:video:type'] as string) ?? ''}
|
||||
renderVideo={(vidProps) => <Video style={{ objectFit: 'contain' }} {...vidProps} />}
|
||||
renderThumbnail={() => <Image src={imgUrl ?? undefined} />}
|
||||
/>
|
||||
)}
|
||||
{!prev['og:video'] &&
|
||||
prev['og:image'] &&
|
||||
(() => (
|
||||
<Box
|
||||
>
|
||||
<VideoContent
|
||||
style={{
|
||||
position: 'absolute',
|
||||
inset: 0,
|
||||
width: '100%',
|
||||
maxHeight: '320px',
|
||||
aspectRatio: aspectRatio ?? '16 / 9',
|
||||
flexShrink: 1,
|
||||
overflow: 'hidden',
|
||||
position: 'relative',
|
||||
height: '100%',
|
||||
}}
|
||||
>
|
||||
<ImageContent
|
||||
style={{
|
||||
width: '100%',
|
||||
height: '100%',
|
||||
position: 'absolute',
|
||||
inset: 0,
|
||||
minHeight: 0,
|
||||
}}
|
||||
autoPlay
|
||||
onAuxClick={handleAuxClick}
|
||||
body={prev['og:title']}
|
||||
url={prev['og:image']}
|
||||
renderViewer={(p) => <ImageViewer {...p} />}
|
||||
renderImage={(p) => (
|
||||
<Image
|
||||
{...p}
|
||||
style={{
|
||||
width: '100%',
|
||||
height: '100%',
|
||||
objectFit: 'contain',
|
||||
objectPosition: 'center',
|
||||
}}
|
||||
/>
|
||||
)}
|
||||
/>
|
||||
</Box>
|
||||
))()}
|
||||
{!prev['og:video'] && !prev['og:image'] && prev['og:audio'] && (
|
||||
body={prev['og:title']}
|
||||
info={{}}
|
||||
url={(prev['og:video'] as string).trim()}
|
||||
mimeType={(prev['og:video:type'] as string) ?? ''}
|
||||
renderVideo={(vidProps) => (
|
||||
<Video
|
||||
style={{ width: '100%', height: '100%', objectFit: 'contain' }}
|
||||
{...vidProps}
|
||||
/>
|
||||
)}
|
||||
renderThumbnail={() => <Image src={imgUrl ?? undefined} />}
|
||||
/>
|
||||
</Box>
|
||||
)}
|
||||
{!showOgVideo && prev['og:image'] && (
|
||||
<Box
|
||||
shrink="No"
|
||||
className={urlPreviewChrome.UrlPreviewMediaWell}
|
||||
style={{
|
||||
width: '100%',
|
||||
maxHeight: toRem(linkPreviewImageMaxHeight),
|
||||
aspectRatio: aspectRatio ?? '16 / 9',
|
||||
flexShrink: 1,
|
||||
minHeight: 0,
|
||||
overflow: 'hidden',
|
||||
position: 'relative',
|
||||
}}
|
||||
>
|
||||
<ImageContent
|
||||
style={{
|
||||
position: 'absolute',
|
||||
inset: 0,
|
||||
width: '100%',
|
||||
height: '100%',
|
||||
}}
|
||||
mediaLayout="contained"
|
||||
fillsPreviewSlot
|
||||
autoPlay
|
||||
onAuxClick={handleAuxClick}
|
||||
body={prev['og:title']}
|
||||
url={prev['og:image']}
|
||||
info={ogImageInfo}
|
||||
matrixThumbnailMaxEdge={previewThumbMaxEdge}
|
||||
renderViewer={(p) => <ImageViewer {...p} />}
|
||||
renderImage={(p) => (
|
||||
<Image
|
||||
{...p}
|
||||
style={{
|
||||
display: 'block',
|
||||
maxWidth: '100%',
|
||||
maxHeight: '100%',
|
||||
width: 'auto',
|
||||
height: 'auto',
|
||||
objectFit: 'contain',
|
||||
objectPosition: 'center',
|
||||
}}
|
||||
/>
|
||||
)}
|
||||
/>
|
||||
</Box>
|
||||
)}
|
||||
{!showOgVideo && !prev['og:image'] && prev['og:audio'] && (
|
||||
<Box className={css.UrlPreviewAudio} style={{ flexShrink: 0 }}>
|
||||
<AudioContent
|
||||
url={(prev['og:audio'] as string) ?? ''}
|
||||
|
||||
@@ -1,5 +1,6 @@
|
||||
import type { RectCords } from 'folds';
|
||||
import { Chip, config, Icon, Icons, Menu, MenuItem, PopOut, Text } from 'folds';
|
||||
import type { CSSProperties } from 'react';
|
||||
import type { MouseEventHandler } from 'react';
|
||||
import { useState } from 'react';
|
||||
import FocusTrap from 'focus-trap-react';
|
||||
@@ -16,19 +17,25 @@ import { useOpenSpaceSettings } from '$state/hooks/spaceSettings';
|
||||
import { SpaceSettingsPage } from '$state/spaceSettings';
|
||||
import { RoomSettingsPage } from '$state/roomSettings';
|
||||
import { PowerColorBadge, PowerIcon } from '$components/power';
|
||||
import { heroMenuItemStyle } from './heroMenuItemStyle';
|
||||
import * as css from './styles.css';
|
||||
|
||||
export function CreatorChip({
|
||||
backgroundColor,
|
||||
innerColor,
|
||||
cardColor,
|
||||
textColor,
|
||||
chipSurfaceStyle,
|
||||
chipFillColor,
|
||||
chipHoverBrightness,
|
||||
}: {
|
||||
backgroundColor?: string;
|
||||
innerColor?: string;
|
||||
cardColor?: string;
|
||||
textColor?: string;
|
||||
chipSurfaceStyle?: CSSProperties;
|
||||
chipFillColor?: string;
|
||||
chipHoverBrightness?: number;
|
||||
}) {
|
||||
const menuItemBg = chipFillColor ?? cardColor;
|
||||
const mx = useMatrixClient();
|
||||
const useAuthentication = useMediaAuthentication();
|
||||
const room = useRoom();
|
||||
@@ -69,7 +76,10 @@ export function CreatorChip({
|
||||
variant="Surface"
|
||||
fill="None"
|
||||
className={css.UserHeroMenuItem}
|
||||
style={{ backgroundColor: cardColor, color: textColor }}
|
||||
style={heroMenuItemStyle(
|
||||
{ backgroundColor: menuItemBg, color: textColor },
|
||||
chipHoverBrightness
|
||||
)}
|
||||
size="300"
|
||||
radii="300"
|
||||
onClick={() => {
|
||||
@@ -93,6 +103,8 @@ export function CreatorChip({
|
||||
}
|
||||
>
|
||||
<Chip
|
||||
variant={cardColor ? undefined : 'Success'}
|
||||
outlined={!cardColor}
|
||||
radii="Pill"
|
||||
before={
|
||||
cords ? (
|
||||
@@ -104,12 +116,11 @@ export function CreatorChip({
|
||||
after={tagIconSrc ? <PowerIcon size="50" iconSrc={tagIconSrc} /> : undefined}
|
||||
onClick={open}
|
||||
aria-pressed={!!cords}
|
||||
className={css.UserHeroChip}
|
||||
style={{
|
||||
backgroundColor: cardColor,
|
||||
borderColor: backgroundColor,
|
||||
color: textColor,
|
||||
}}
|
||||
className={cardColor ? css.UserHeroChipThemed : css.UserHeroBrightnessHover}
|
||||
style={heroMenuItemStyle(
|
||||
cardColor && chipSurfaceStyle ? chipSurfaceStyle : {},
|
||||
chipHoverBrightness
|
||||
)}
|
||||
>
|
||||
<Text size="B300" truncate>
|
||||
{tag.name}
|
||||
|
||||
@@ -20,6 +20,7 @@ import {
|
||||
Text,
|
||||
toRem,
|
||||
} from 'folds';
|
||||
import type { CSSProperties } from 'react';
|
||||
import type { MouseEventHandler } from 'react';
|
||||
import { useCallback, useState } from 'react';
|
||||
import FocusTrap from 'focus-trap-react';
|
||||
@@ -45,6 +46,7 @@ import { useMemberPowerCompare } from '$hooks/useMemberPowerCompare';
|
||||
import { CutoutCard } from '$components/cutout-card';
|
||||
import { PowerColorBadge, PowerIcon } from '$components/power';
|
||||
import { EventType } from '$types/matrix-sdk';
|
||||
import { heroMenuItemStyle } from './heroMenuItemStyle';
|
||||
import * as css from './styles.css';
|
||||
|
||||
type SelfDemoteAlertProps = {
|
||||
@@ -149,17 +151,22 @@ function SharedPowerAlert({ power, onCancel, onChange }: SharedPowerAlertProps)
|
||||
|
||||
export function PowerChip({
|
||||
userId,
|
||||
backgroundColor,
|
||||
innerColor,
|
||||
cardColor,
|
||||
textColor,
|
||||
chipSurfaceStyle,
|
||||
chipFillColor,
|
||||
chipHoverBrightness,
|
||||
}: {
|
||||
userId: string;
|
||||
backgroundColor?: string;
|
||||
innerColor?: string;
|
||||
cardColor?: string;
|
||||
textColor?: string;
|
||||
chipSurfaceStyle?: CSSProperties;
|
||||
chipFillColor?: string;
|
||||
chipHoverBrightness?: number;
|
||||
}) {
|
||||
const menuItemBg = chipFillColor ?? cardColor;
|
||||
const mx = useMatrixClient();
|
||||
const room = useRoom();
|
||||
const space = useSpaceOptionally();
|
||||
@@ -288,7 +295,10 @@ export function PowerChip({
|
||||
aria-disabled={changing || !canChangePowers || !canAssignPower}
|
||||
aria-pressed={selected}
|
||||
className={css.UserHeroMenuItem}
|
||||
style={{ backgroundColor: cardColor, color: textColor }}
|
||||
style={heroMenuItemStyle(
|
||||
{ backgroundColor: menuItemBg, color: textColor },
|
||||
chipHoverBrightness
|
||||
)}
|
||||
before={<PowerColorBadge color={powerTag.color} />}
|
||||
after={
|
||||
powerTagIconSrc ? (
|
||||
@@ -314,7 +324,10 @@ export function PowerChip({
|
||||
size="300"
|
||||
radii="300"
|
||||
className={css.UserHeroMenuItem}
|
||||
style={{ backgroundColor: cardColor, color: textColor }}
|
||||
style={heroMenuItemStyle(
|
||||
{ backgroundColor: menuItemBg, color: textColor },
|
||||
chipHoverBrightness
|
||||
)}
|
||||
onClick={() => {
|
||||
if (room.isSpaceRoom()) {
|
||||
openSpaceSettings(
|
||||
@@ -340,14 +353,19 @@ export function PowerChip({
|
||||
}
|
||||
>
|
||||
<Chip
|
||||
variant={error ? 'Critical' : undefined}
|
||||
variant={error ? 'Critical' : cardColor ? undefined : 'SurfaceVariant'}
|
||||
radii="Pill"
|
||||
className={css.UserHeroChip}
|
||||
style={{
|
||||
backgroundColor: (!error && cardColor) || undefined,
|
||||
borderColor: backgroundColor,
|
||||
color: textColor,
|
||||
}}
|
||||
className={
|
||||
error ? undefined : cardColor ? css.UserHeroChipThemed : css.UserHeroBrightnessHover
|
||||
}
|
||||
style={
|
||||
error
|
||||
? undefined
|
||||
: heroMenuItemStyle(
|
||||
cardColor && chipSurfaceStyle ? chipSurfaceStyle : {},
|
||||
chipHoverBrightness
|
||||
)
|
||||
}
|
||||
before={
|
||||
cords ? (
|
||||
<Icon size="50" src={Icons.ChevronBottom} />
|
||||
|
||||
@@ -1,4 +1,5 @@
|
||||
import type { KeyboardEventHandler, MouseEventHandler } from 'react';
|
||||
import type { CSSProperties } from 'react';
|
||||
import { useCallback, useEffect, useMemo, useRef, useState } from 'react';
|
||||
import { useNavigate } from 'react-router-dom';
|
||||
import FocusTrap from 'focus-trap-react';
|
||||
@@ -22,6 +23,7 @@ import {
|
||||
Avatar,
|
||||
} from 'folds';
|
||||
import { useMatrixClient } from '$hooks/useMatrixClient';
|
||||
import { getMxIdServer } from '$utils/mxIdHelper';
|
||||
import { useCloseUserRoomProfile } from '$state/hooks/userRoomProfile';
|
||||
import { stopPropagation } from '$utils/keyboard';
|
||||
import { copyToClipboard } from '$utils/dom';
|
||||
@@ -42,6 +44,7 @@ import { useNickname, useSetNickname } from '$hooks/useNickname';
|
||||
import { CutoutCard } from '$components/cutout-card';
|
||||
import { SettingTile } from '$components/setting-tile';
|
||||
import { RoomAvatar, RoomIcon } from '$components/room-avatar';
|
||||
import { heroMenuItemStyle } from './heroMenuItemStyle';
|
||||
import * as css from './styles.css';
|
||||
|
||||
export function ServerChip({
|
||||
@@ -49,14 +52,21 @@ export function ServerChip({
|
||||
innerColor,
|
||||
cardColor,
|
||||
textColor,
|
||||
backgroundColor,
|
||||
chipSurfaceStyle,
|
||||
chipFillColor,
|
||||
chipHoverBrightness,
|
||||
}: {
|
||||
server: string;
|
||||
innerColor?: string;
|
||||
cardColor?: string;
|
||||
textColor?: string;
|
||||
backgroundColor?: string;
|
||||
chipSurfaceStyle?: CSSProperties;
|
||||
chipFillColor?: string;
|
||||
chipHoverBrightness?: number;
|
||||
}) {
|
||||
const menuItemBg = chipFillColor ?? cardColor;
|
||||
const mx = useMatrixClient();
|
||||
const myServer = getMxIdServer(mx.getSafeUserId());
|
||||
const navigate = useNavigate();
|
||||
const closeProfile = useCloseUserRoomProfile();
|
||||
const [copied, setCopied] = useTimeoutToggle();
|
||||
@@ -89,71 +99,89 @@ export function ServerChip({
|
||||
<Menu>
|
||||
<div
|
||||
style={{
|
||||
padding: config.space.S100,
|
||||
padding: config.space.S200,
|
||||
maxWidth: toRem(200),
|
||||
backgroundColor: innerColor,
|
||||
}}
|
||||
>
|
||||
<MenuItem
|
||||
fill="None"
|
||||
size="300"
|
||||
radii="300"
|
||||
onClick={() => {
|
||||
copyToClipboard(server);
|
||||
setCopied();
|
||||
close();
|
||||
}}
|
||||
className={css.UserHeroMenuItem}
|
||||
style={{
|
||||
backgroundColor: cardColor,
|
||||
color: textColor,
|
||||
}}
|
||||
>
|
||||
<Text size="B300">Copy Server</Text>
|
||||
</MenuItem>
|
||||
<MenuItem
|
||||
fill="None"
|
||||
size="300"
|
||||
radii="300"
|
||||
onClick={() => {
|
||||
navigate(getExploreServerPath(server));
|
||||
closeProfile();
|
||||
}}
|
||||
className={css.UserHeroMenuItem}
|
||||
style={{
|
||||
backgroundColor: cardColor,
|
||||
color: textColor,
|
||||
}}
|
||||
>
|
||||
<Text size="B300">Explore Community</Text>
|
||||
</MenuItem>
|
||||
<Box direction="Column" gap="100">
|
||||
<MenuItem
|
||||
fill="None"
|
||||
size="300"
|
||||
radii="300"
|
||||
onClick={() => {
|
||||
copyToClipboard(server);
|
||||
setCopied();
|
||||
close();
|
||||
}}
|
||||
className={css.UserHeroMenuItem}
|
||||
style={heroMenuItemStyle(
|
||||
{
|
||||
backgroundColor: menuItemBg,
|
||||
color: textColor,
|
||||
},
|
||||
chipHoverBrightness
|
||||
)}
|
||||
>
|
||||
<Text size="B300">Copy Server</Text>
|
||||
</MenuItem>
|
||||
<MenuItem
|
||||
fill="None"
|
||||
size="300"
|
||||
radii="300"
|
||||
onClick={() => {
|
||||
navigate(getExploreServerPath(server));
|
||||
closeProfile();
|
||||
}}
|
||||
className={css.UserHeroMenuItem}
|
||||
style={heroMenuItemStyle(
|
||||
{
|
||||
backgroundColor: menuItemBg,
|
||||
color: textColor,
|
||||
},
|
||||
chipHoverBrightness
|
||||
)}
|
||||
>
|
||||
<Text size="B300">Explore Community</Text>
|
||||
</MenuItem>
|
||||
</Box>
|
||||
</div>
|
||||
<Line size="300" />
|
||||
<div
|
||||
style={{ padding: config.space.S100, backgroundColor: cardColor, color: textColor }}
|
||||
style={{
|
||||
padding: config.space.S200,
|
||||
backgroundColor: innerColor,
|
||||
color: textColor,
|
||||
}}
|
||||
>
|
||||
<MenuItem
|
||||
fill="None"
|
||||
size="300"
|
||||
radii="300"
|
||||
onClick={() => {
|
||||
window.open(`https://${server}`, '_blank');
|
||||
close();
|
||||
}}
|
||||
className={css.UserHeroMenuItem}
|
||||
style={{
|
||||
backgroundColor: cardColor,
|
||||
color: textColor,
|
||||
}}
|
||||
>
|
||||
<Text size="B300">Open in Browser</Text>
|
||||
</MenuItem>
|
||||
<Box direction="Column" gap="100">
|
||||
<MenuItem
|
||||
fill="None"
|
||||
size="300"
|
||||
radii="300"
|
||||
onClick={() => {
|
||||
window.open(`https://${server}`, '_blank');
|
||||
close();
|
||||
}}
|
||||
className={css.UserHeroMenuItem}
|
||||
style={heroMenuItemStyle(
|
||||
{
|
||||
backgroundColor: menuItemBg,
|
||||
color: textColor,
|
||||
},
|
||||
chipHoverBrightness
|
||||
)}
|
||||
>
|
||||
<Text size="B300">Open in Browser</Text>
|
||||
</MenuItem>
|
||||
</Box>
|
||||
</div>
|
||||
</Menu>
|
||||
</FocusTrap>
|
||||
}
|
||||
>
|
||||
<Chip
|
||||
variant={cardColor ? undefined : myServer === server ? 'SurfaceVariant' : 'Warning'}
|
||||
radii="Pill"
|
||||
before={
|
||||
cords ? (
|
||||
@@ -164,12 +192,11 @@ export function ServerChip({
|
||||
}
|
||||
onClick={open}
|
||||
aria-pressed={!!cords}
|
||||
className={css.UserHeroChip}
|
||||
style={{
|
||||
backgroundColor: cardColor,
|
||||
borderColor: backgroundColor,
|
||||
color: textColor,
|
||||
}}
|
||||
className={cardColor ? css.UserHeroChipThemed : css.UserHeroBrightnessHover}
|
||||
style={heroMenuItemStyle(
|
||||
cardColor && chipSurfaceStyle ? chipSurfaceStyle : {},
|
||||
chipHoverBrightness
|
||||
)}
|
||||
>
|
||||
<Text size="B300" truncate>
|
||||
{server}
|
||||
@@ -184,14 +211,19 @@ export function ShareChip({
|
||||
innerColor,
|
||||
cardColor,
|
||||
textColor,
|
||||
backgroundColor,
|
||||
chipSurfaceStyle,
|
||||
chipFillColor,
|
||||
chipHoverBrightness,
|
||||
}: {
|
||||
userId: string;
|
||||
innerColor?: string;
|
||||
cardColor?: string;
|
||||
textColor?: string;
|
||||
backgroundColor?: string;
|
||||
chipSurfaceStyle?: CSSProperties;
|
||||
chipFillColor?: string;
|
||||
chipHoverBrightness?: number;
|
||||
}) {
|
||||
const menuItemBg = chipFillColor ?? cardColor;
|
||||
const [cords, setCords] = useState<RectCords>();
|
||||
|
||||
const [copied, setCopied] = useTimeoutToggle();
|
||||
@@ -220,48 +252,56 @@ export function ShareChip({
|
||||
}}
|
||||
>
|
||||
<Menu>
|
||||
<div style={{ padding: config.space.S100, backgroundColor: innerColor }}>
|
||||
<MenuItem
|
||||
fill="None"
|
||||
size="300"
|
||||
radii="300"
|
||||
className={css.UserHeroMenuItem}
|
||||
style={{
|
||||
backgroundColor: cardColor,
|
||||
color: textColor,
|
||||
}}
|
||||
onClick={() => {
|
||||
copyToClipboard(userId);
|
||||
setCopied();
|
||||
close();
|
||||
}}
|
||||
>
|
||||
<Text size="B300">Copy User ID</Text>
|
||||
</MenuItem>
|
||||
<MenuItem
|
||||
fill="None"
|
||||
size="300"
|
||||
radii="300"
|
||||
className={css.UserHeroMenuItem}
|
||||
style={{
|
||||
backgroundColor: cardColor,
|
||||
color: textColor,
|
||||
}}
|
||||
onClick={() => {
|
||||
copyToClipboard(getMatrixToUser(userId));
|
||||
setCopied();
|
||||
close();
|
||||
}}
|
||||
>
|
||||
<Text size="B300">Copy User Link</Text>
|
||||
</MenuItem>
|
||||
<div style={{ padding: config.space.S200, backgroundColor: innerColor }}>
|
||||
<Box direction="Column" gap="100">
|
||||
<MenuItem
|
||||
fill="None"
|
||||
size="300"
|
||||
radii="300"
|
||||
className={css.UserHeroMenuItem}
|
||||
style={heroMenuItemStyle(
|
||||
{
|
||||
backgroundColor: menuItemBg,
|
||||
color: textColor,
|
||||
},
|
||||
chipHoverBrightness
|
||||
)}
|
||||
onClick={() => {
|
||||
copyToClipboard(userId);
|
||||
setCopied();
|
||||
close();
|
||||
}}
|
||||
>
|
||||
<Text size="B300">Copy User ID</Text>
|
||||
</MenuItem>
|
||||
<MenuItem
|
||||
fill="None"
|
||||
size="300"
|
||||
radii="300"
|
||||
className={css.UserHeroMenuItem}
|
||||
style={heroMenuItemStyle(
|
||||
{
|
||||
backgroundColor: menuItemBg,
|
||||
color: textColor,
|
||||
},
|
||||
chipHoverBrightness
|
||||
)}
|
||||
onClick={() => {
|
||||
copyToClipboard(getMatrixToUser(userId));
|
||||
setCopied();
|
||||
close();
|
||||
}}
|
||||
>
|
||||
<Text size="B300">Copy User Link</Text>
|
||||
</MenuItem>
|
||||
</Box>
|
||||
</div>
|
||||
</Menu>
|
||||
</FocusTrap>
|
||||
}
|
||||
>
|
||||
<Chip
|
||||
variant={copied ? 'Success' : undefined}
|
||||
variant={copied ? 'Success' : cardColor ? undefined : 'SurfaceVariant'}
|
||||
radii="Pill"
|
||||
before={
|
||||
cords ? (
|
||||
@@ -272,12 +312,11 @@ export function ShareChip({
|
||||
}
|
||||
onClick={open}
|
||||
aria-pressed={!!cords}
|
||||
className={css.UserHeroChip}
|
||||
style={{
|
||||
backgroundColor: (!copied && cardColor) || undefined,
|
||||
borderColor: backgroundColor,
|
||||
color: textColor,
|
||||
}}
|
||||
className={!copied && cardColor ? css.UserHeroChipThemed : css.UserHeroBrightnessHover}
|
||||
style={heroMenuItemStyle(
|
||||
cardColor && !copied && chipSurfaceStyle ? chipSurfaceStyle : {},
|
||||
chipHoverBrightness
|
||||
)}
|
||||
>
|
||||
<Text size="B300" truncate>
|
||||
Share
|
||||
@@ -295,17 +334,22 @@ type MutualRoomsData = {
|
||||
|
||||
export function MutualRoomsChip({
|
||||
userId,
|
||||
backgroundColor,
|
||||
innerColor,
|
||||
cardColor,
|
||||
textColor,
|
||||
chipSurfaceStyle,
|
||||
chipFillColor,
|
||||
chipHoverBrightness,
|
||||
}: {
|
||||
userId: string;
|
||||
backgroundColor?: string;
|
||||
innerColor?: string;
|
||||
cardColor?: string;
|
||||
textColor?: string;
|
||||
chipSurfaceStyle?: CSSProperties;
|
||||
chipFillColor?: string;
|
||||
chipHoverBrightness?: number;
|
||||
}) {
|
||||
const menuItemBg = chipFillColor ?? cardColor;
|
||||
const mx = useMatrixClient();
|
||||
const mutualRoomSupported = useMutualRoomsSupport();
|
||||
const mutualRoomsState = useMutualRooms(userId);
|
||||
@@ -372,11 +416,14 @@ export function MutualRoomsChip({
|
||||
size="300"
|
||||
radii="300"
|
||||
className={css.UserHeroMenuItem}
|
||||
style={{
|
||||
paddingLeft: config.space.S100,
|
||||
backgroundColor: cardColor,
|
||||
color: textColor,
|
||||
}}
|
||||
style={heroMenuItemStyle(
|
||||
{
|
||||
paddingLeft: config.space.S100,
|
||||
backgroundColor: menuItemBg,
|
||||
color: textColor,
|
||||
},
|
||||
chipHoverBrightness
|
||||
)}
|
||||
onClick={() => {
|
||||
if (room.isSpaceRoom()) {
|
||||
navigateSpace(roomId);
|
||||
@@ -486,6 +533,7 @@ export function MutualRoomsChip({
|
||||
}
|
||||
>
|
||||
<Chip
|
||||
variant={cardColor ? undefined : 'SurfaceVariant'}
|
||||
radii="Pill"
|
||||
before={mutualRoomsState.status === AsyncStatus.Loading && <Spinner size="50" />}
|
||||
disabled={
|
||||
@@ -493,12 +541,11 @@ export function MutualRoomsChip({
|
||||
}
|
||||
onClick={open}
|
||||
aria-pressed={!!cords}
|
||||
className={css.UserHeroChip}
|
||||
style={{
|
||||
backgroundColor: cardColor,
|
||||
borderColor: backgroundColor,
|
||||
color: textColor,
|
||||
}}
|
||||
className={cardColor ? css.UserHeroChipThemed : css.UserHeroBrightnessHover}
|
||||
style={heroMenuItemStyle(
|
||||
cardColor && chipSurfaceStyle ? chipSurfaceStyle : {},
|
||||
chipHoverBrightness
|
||||
)}
|
||||
>
|
||||
<Text size="B300" style={{ color: textColor }}>
|
||||
{mutualRoomsState.status === AsyncStatus.Success &&
|
||||
@@ -529,17 +576,22 @@ export function IgnoredUserAlert() {
|
||||
|
||||
export function OptionsChip({
|
||||
userId,
|
||||
backgroundColor,
|
||||
innerColor,
|
||||
cardColor,
|
||||
textColor,
|
||||
chipSurfaceStyle,
|
||||
chipFillColor,
|
||||
chipHoverBrightness,
|
||||
}: {
|
||||
userId: string;
|
||||
backgroundColor?: string;
|
||||
innerColor?: string;
|
||||
cardColor?: string;
|
||||
textColor?: string;
|
||||
chipSurfaceStyle?: CSSProperties;
|
||||
chipFillColor?: string;
|
||||
chipHoverBrightness?: number;
|
||||
}) {
|
||||
const menuItemBg = chipFillColor ?? cardColor;
|
||||
const mx = useMatrixClient();
|
||||
const [cords, setCords] = useState<RectCords>();
|
||||
const [editingNick, setEditingNick] = useState(false);
|
||||
@@ -604,122 +656,129 @@ export function OptionsChip({
|
||||
}}
|
||||
>
|
||||
<Menu>
|
||||
<div style={{ padding: config.space.S100, backgroundColor: innerColor }}>
|
||||
{editingNick ? (
|
||||
<Box
|
||||
direction="Column"
|
||||
gap="100"
|
||||
style={{ padding: `${config.space.S100} ${config.space.S200}`, color: textColor }}
|
||||
>
|
||||
<Text size="L400">Nickname</Text>
|
||||
<input
|
||||
ref={nickInputRef}
|
||||
defaultValue={currentNick ?? ''}
|
||||
placeholder="Enter a nickname…"
|
||||
onKeyDown={handleNickKeyDown}
|
||||
style={{
|
||||
background: 'var(--mx-c-surface)',
|
||||
color: 'var(--mx-c-on-surface)',
|
||||
border: '1px solid var(--mx-c-outline)',
|
||||
borderRadius: '6px',
|
||||
padding: '4px 8px',
|
||||
fontSize: '14px',
|
||||
width: '100%',
|
||||
outline: 'none',
|
||||
}}
|
||||
/>
|
||||
<Box gap="200">
|
||||
<MenuItem
|
||||
size="300"
|
||||
radii="300"
|
||||
variant="Success"
|
||||
fill="None"
|
||||
onClick={handleSaveNick}
|
||||
className={css.UserHeroMenuItem}
|
||||
<div style={{ padding: config.space.S200, backgroundColor: innerColor }}>
|
||||
<Box direction="Column" gap="100">
|
||||
{editingNick ? (
|
||||
<Box direction="Column" gap="100" style={{ color: textColor }}>
|
||||
<Text size="L400">Nickname</Text>
|
||||
<input
|
||||
ref={nickInputRef}
|
||||
defaultValue={currentNick ?? ''}
|
||||
placeholder="Enter a nickname…"
|
||||
onKeyDown={handleNickKeyDown}
|
||||
style={{
|
||||
backgroundColor: cardColor,
|
||||
color: textColor,
|
||||
background: 'var(--mx-c-surface)',
|
||||
color: 'var(--mx-c-on-surface)',
|
||||
border: '1px solid var(--mx-c-outline)',
|
||||
borderRadius: '6px',
|
||||
padding: '4px 8px',
|
||||
fontSize: '14px',
|
||||
width: '100%',
|
||||
outline: 'none',
|
||||
}}
|
||||
>
|
||||
<Text size="B300">Save</Text>
|
||||
</MenuItem>
|
||||
{currentNick && (
|
||||
/>
|
||||
<Box gap="200">
|
||||
<MenuItem
|
||||
size="300"
|
||||
radii="300"
|
||||
variant="Critical"
|
||||
variant="Success"
|
||||
fill="None"
|
||||
onClick={handleSaveNick}
|
||||
className={css.UserHeroMenuItem}
|
||||
onClick={() => {
|
||||
setNickname(userId, undefined);
|
||||
close();
|
||||
}}
|
||||
style={{
|
||||
backgroundColor: cardColor,
|
||||
color: textColor,
|
||||
}}
|
||||
style={heroMenuItemStyle(
|
||||
{
|
||||
backgroundColor: menuItemBg,
|
||||
color: textColor,
|
||||
},
|
||||
chipHoverBrightness
|
||||
)}
|
||||
>
|
||||
<Text size="B300">Clear</Text>
|
||||
<Text size="B300">Save</Text>
|
||||
</MenuItem>
|
||||
)}
|
||||
{currentNick && (
|
||||
<MenuItem
|
||||
size="300"
|
||||
radii="300"
|
||||
variant="Critical"
|
||||
fill="None"
|
||||
className={css.UserHeroMenuItem}
|
||||
onClick={() => {
|
||||
setNickname(userId, undefined);
|
||||
close();
|
||||
}}
|
||||
style={heroMenuItemStyle(
|
||||
{
|
||||
backgroundColor: menuItemBg,
|
||||
color: textColor,
|
||||
},
|
||||
chipHoverBrightness
|
||||
)}
|
||||
>
|
||||
<Text size="B300">Clear</Text>
|
||||
</MenuItem>
|
||||
)}
|
||||
</Box>
|
||||
</Box>
|
||||
</Box>
|
||||
) : (
|
||||
) : (
|
||||
<MenuItem
|
||||
variant="Surface"
|
||||
fill="None"
|
||||
size="300"
|
||||
radii="300"
|
||||
before={<Icon size="50" src={Icons.Pencil} />}
|
||||
onClick={() => setEditingNick(true)}
|
||||
className={css.UserHeroMenuItem}
|
||||
style={heroMenuItemStyle(
|
||||
{
|
||||
backgroundColor: menuItemBg,
|
||||
color: textColor,
|
||||
},
|
||||
chipHoverBrightness
|
||||
)}
|
||||
>
|
||||
<Text size="B300">{currentNick ? 'Edit Nickname' : 'Set Nickname'}</Text>
|
||||
</MenuItem>
|
||||
)}
|
||||
<MenuItem
|
||||
variant="Surface"
|
||||
variant="Critical"
|
||||
fill="None"
|
||||
size="300"
|
||||
radii="300"
|
||||
before={<Icon size="50" src={Icons.Pencil} />}
|
||||
onClick={() => setEditingNick(true)}
|
||||
className={css.UserHeroMenuItem}
|
||||
style={{
|
||||
backgroundColor: cardColor,
|
||||
color: textColor,
|
||||
onClick={() => {
|
||||
toggleIgnore();
|
||||
close();
|
||||
}}
|
||||
className={css.UserHeroMenuItem}
|
||||
style={heroMenuItemStyle({ backgroundColor: menuItemBg }, chipHoverBrightness)}
|
||||
before={
|
||||
ignoring ? (
|
||||
<Spinner variant="Critical" size="50" />
|
||||
) : (
|
||||
<Icon size="50" src={Icons.Prohibited} />
|
||||
)
|
||||
}
|
||||
disabled={ignoring}
|
||||
>
|
||||
<Text size="B300">{currentNick ? 'Edit Nickname' : 'Set Nickname'}</Text>
|
||||
<Text size="B300" style={{ color: textColor }}>
|
||||
{ignored ? 'Unblock User' : 'Block User'}
|
||||
</Text>
|
||||
</MenuItem>
|
||||
)}
|
||||
<MenuItem
|
||||
variant="Critical"
|
||||
fill="None"
|
||||
size="300"
|
||||
radii="300"
|
||||
onClick={() => {
|
||||
toggleIgnore();
|
||||
close();
|
||||
}}
|
||||
className={css.UserHeroMenuItem}
|
||||
style={{ backgroundColor: cardColor }}
|
||||
before={
|
||||
ignoring ? (
|
||||
<Spinner variant="Critical" size="50" />
|
||||
) : (
|
||||
<Icon size="50" src={Icons.Prohibited} />
|
||||
)
|
||||
}
|
||||
disabled={ignoring}
|
||||
>
|
||||
<Text size="B300" style={{ color: textColor }}>
|
||||
{ignored ? 'Unblock User' : 'Block User'}
|
||||
</Text>
|
||||
</MenuItem>
|
||||
</Box>
|
||||
</div>
|
||||
</Menu>
|
||||
</FocusTrap>
|
||||
}
|
||||
>
|
||||
<Chip
|
||||
variant={cardColor ? undefined : 'SurfaceVariant'}
|
||||
radii="Pill"
|
||||
onClick={open}
|
||||
aria-pressed={!!cords}
|
||||
className={css.UserHeroChip}
|
||||
style={{
|
||||
backgroundColor: cardColor,
|
||||
borderColor: backgroundColor,
|
||||
color: textColor,
|
||||
}}
|
||||
className={cardColor ? css.UserHeroChipThemed : css.UserHeroBrightnessHover}
|
||||
style={heroMenuItemStyle(
|
||||
cardColor && chipSurfaceStyle ? chipSurfaceStyle : {},
|
||||
chipHoverBrightness
|
||||
)}
|
||||
>
|
||||
{ignoring ? (
|
||||
<Spinner variant="Secondary" size="50" />
|
||||
|
||||
@@ -1,4 +1,5 @@
|
||||
import { useMemo, useState } from 'react';
|
||||
import type { CSSProperties } from 'react';
|
||||
import {
|
||||
Avatar,
|
||||
Box,
|
||||
@@ -78,10 +79,14 @@ export function UserHero({ userId, avatarUrl, bannerUrl, presence, autoplayGifs
|
||||
const isBackgroundDark = fetchedBrightness ? fetchedBrightness === 'dark' : undefined;
|
||||
const cardColor =
|
||||
shadeColor(backgroundColor, isBackgroundDark ? -80 : 80) ?? standardColors.Background.Container;
|
||||
const innerColor = shadeColor(backgroundColor, isBackgroundDark ? -50 : 50) ?? backgroundColor;
|
||||
const statusSurfaceColor =
|
||||
shadeColor(innerColor, fetchedBrightness === 'light' ? -14 : 32) ?? cardColor;
|
||||
const textColor =
|
||||
((fetchedBrightness === 'dark' || areColorsTooSimilar('#000000', cardColor)) && '#FFFFFF') ||
|
||||
((fetchedBrightness === 'light' || areColorsTooSimilar('#FFFFFF', cardColor)) && '#000000') ||
|
||||
undefined;
|
||||
const statusHoverBrightness = fetchedBrightness === 'light' ? 0.94 : 1.08;
|
||||
|
||||
return (
|
||||
<Box direction="Column" className={css.UserHero} style={{ backgroundColor: backgroundColor }}>
|
||||
@@ -153,16 +158,29 @@ export function UserHero({ userId, avatarUrl, bannerUrl, presence, autoplayGifs
|
||||
{status && status.length > 0 && (
|
||||
<div className={css.UserHeroStatusContainer}>
|
||||
<Tooltip
|
||||
radii="400"
|
||||
variant="Surface"
|
||||
onClick={isExpandable ? () => setIsFullStatus(!isFullStatus) : undefined}
|
||||
className={css.UserHeroStatusTooltip}
|
||||
className={classNames(
|
||||
css.UserHeroStatusTooltip,
|
||||
isExpandable && css.UserHeroStatusTooltipInteractive
|
||||
)}
|
||||
style={{
|
||||
maxHeight: isFullStatus ? toRem(105) : toRem(48),
|
||||
cursor: isExpandable ? 'pointer' : 'default',
|
||||
transform: 'none',
|
||||
transition: 'none',
|
||||
display: 'flex',
|
||||
backgroundColor: cardColor,
|
||||
padding: `${toRem(8)} ${toRem(12)}`,
|
||||
backgroundColor: statusSurfaceColor,
|
||||
color: textColor,
|
||||
borderStyle: 'none',
|
||||
borderWidth: 0,
|
||||
outline: 'none',
|
||||
boxShadow: 'inset 0 1px 1px rgba(0, 0, 0, 0.05)',
|
||||
...({
|
||||
'--user-hero-status-hover-brightness': String(statusHoverBrightness),
|
||||
} as CSSProperties),
|
||||
}}
|
||||
>
|
||||
<Box direction="Row" gap="100" style={{ height: '100%', width: '100%' }}>
|
||||
|
||||
@@ -11,7 +11,7 @@ import {
|
||||
Text,
|
||||
toRem,
|
||||
} from 'folds';
|
||||
import type { SyntheticEvent } from 'react';
|
||||
import type { CSSProperties, SyntheticEvent } from 'react';
|
||||
import { useCallback, useMemo, useState } from 'react';
|
||||
import { useNavigate } from 'react-router-dom';
|
||||
import { useAtomValue } from 'jotai';
|
||||
@@ -52,6 +52,8 @@ import { useSettingsLinkBaseUrl } from '$features/settings/useSettingsLinkBaseUr
|
||||
import { getMxIdServer } from '$utils/mxIdHelper';
|
||||
import { TextViewerContent } from '$components/text-viewer';
|
||||
import { areColorsTooSimilar, shadeColor } from '$utils/shadeColor';
|
||||
import { ThemeKind, useTheme } from '$hooks/useTheme';
|
||||
import { heroMenuItemStyle } from './heroMenuItemStyle';
|
||||
import { CreatorChip } from './CreatorChip';
|
||||
import { UserInviteAlert, UserBanAlert, UserModeration, UserKickAlert } from './UserModeration';
|
||||
import { PowerChip } from './PowerChip';
|
||||
@@ -80,7 +82,6 @@ type UserExtendedSectionProps = {
|
||||
profile: UserProfile;
|
||||
htmlReactParserOptions: HTMLReactParserOptions;
|
||||
linkifyOpts: LinkifyOpts;
|
||||
backgroundColor?: string;
|
||||
innerColor?: string;
|
||||
cardColor?: string;
|
||||
textColor?: string;
|
||||
@@ -97,7 +98,6 @@ function UserExtendedSection({
|
||||
profile,
|
||||
htmlReactParserOptions,
|
||||
linkifyOpts,
|
||||
backgroundColor,
|
||||
innerColor,
|
||||
cardColor,
|
||||
textColor,
|
||||
@@ -228,11 +228,13 @@ function UserExtendedSection({
|
||||
() => (
|
||||
<Box justifyContent="Center" grow="Yes">
|
||||
<Button
|
||||
variant="Secondary"
|
||||
size="300"
|
||||
fill="None"
|
||||
size="300"
|
||||
className={css.MiscDataToggleButton}
|
||||
onClick={() => setShowMisc(!showMisc)}
|
||||
after={miscDataIndex === -1 && <Icon size="50" src={Icons.ChevronBottom} />}
|
||||
after={
|
||||
<Icon size="50" src={miscDataIndex === -1 ? Icons.ChevronBottom : Icons.ChevronTop} />
|
||||
}
|
||||
style={{
|
||||
padding: '1rem',
|
||||
justifyContent: 'flex-start',
|
||||
@@ -293,9 +295,7 @@ function UserExtendedSection({
|
||||
style={{
|
||||
backgroundColor: cardColor,
|
||||
borderRadius: config.radii.R400,
|
||||
borderColor: backgroundColor,
|
||||
borderStyle: 'solid',
|
||||
borderWidth: '1px',
|
||||
boxShadow: 'inset 0 1px 2px rgba(0, 0, 0, 0.1)',
|
||||
maxHeight: '200px',
|
||||
marginTop: config.space.S0,
|
||||
overflowY: 'auto',
|
||||
@@ -326,25 +326,18 @@ function UserExtendedSection({
|
||||
{miscDataIndex > -1 && (
|
||||
<div
|
||||
style={{
|
||||
border: '2px solid',
|
||||
backgroundColor: cardColor,
|
||||
borderColor: 'var(--sable-surface-container-line)',
|
||||
borderRadius: config.radii.R400,
|
||||
borderWidth: '1px',
|
||||
boxShadow: 'inset 0 1px 2px rgba(0, 0, 0, 0.1)',
|
||||
overflow: 'hidden',
|
||||
}}
|
||||
>
|
||||
<Box
|
||||
direction="Row"
|
||||
justifyContent="Center"
|
||||
alignContent="Center"
|
||||
style={{
|
||||
borderRadius: config.radii.R400,
|
||||
}}
|
||||
>
|
||||
<Box direction="Row" justifyContent="Center" alignContent="Center">
|
||||
{unknownFields.length > 1 && (
|
||||
<Button
|
||||
size="300"
|
||||
fill="None"
|
||||
className={css.MiscDataToggleButton}
|
||||
onClick={() =>
|
||||
setMiscDataIndex(
|
||||
miscDataIndex === 0 ? unknownFields.length - 1 : miscDataIndex - 1
|
||||
@@ -360,6 +353,7 @@ function UserExtendedSection({
|
||||
<Button
|
||||
size="300"
|
||||
fill="None"
|
||||
className={css.MiscDataToggleButton}
|
||||
onClick={() => setMiscDataIndex((miscDataIndex + 1) % unknownFields.length)}
|
||||
style={{ color: textColor }}
|
||||
>
|
||||
@@ -370,16 +364,21 @@ function UserExtendedSection({
|
||||
<Scroll
|
||||
size="300"
|
||||
direction="Both"
|
||||
visibility="Hover"
|
||||
hideTrack
|
||||
variant="SurfaceVariant"
|
||||
style={{
|
||||
backgroundColor: color.Background.Container,
|
||||
color: color.Background.OnContainer,
|
||||
backgroundColor: color.SurfaceVariant.Container,
|
||||
color: color.SurfaceVariant.OnContainer,
|
||||
fontFamily: 'monospace',
|
||||
boxShadow:
|
||||
'inset 0 2px 0 rgba(0, 0, 0, 0.65), inset 0 4px 6px -2px rgba(0, 0, 0, 0.35)',
|
||||
}}
|
||||
>
|
||||
<Box
|
||||
direction="Column"
|
||||
style={{
|
||||
padding: config.space.S200,
|
||||
borderRadius: config.radii.R400,
|
||||
maxHeight: toRem(100),
|
||||
}}
|
||||
>
|
||||
@@ -402,6 +401,7 @@ type UserRoomProfileProps = {
|
||||
initialProfile?: Partial<UserProfile>;
|
||||
};
|
||||
export function UserRoomProfile({ userId, initialProfile }: Readonly<UserRoomProfileProps>) {
|
||||
const theme = useTheme();
|
||||
const mx = useMatrixClient();
|
||||
const useAuthentication = useMediaAuthentication();
|
||||
const navigate = useNavigate();
|
||||
@@ -515,6 +515,43 @@ export function UserRoomProfile({ userId, initialProfile }: Readonly<UserRoomPro
|
||||
|
||||
const showCustomHeroCard = !!fetchedProfile.heroColor;
|
||||
|
||||
const chipFillColor =
|
||||
shadeColor(innerColor, fetchedBrightness === 'light' ? -14 : 32) ?? cardColor;
|
||||
const chipHoverBrightness =
|
||||
fetchedBrightness === 'light'
|
||||
? 0.94
|
||||
: fetchedBrightness === 'dark'
|
||||
? 1.12
|
||||
: theme.kind === ThemeKind.Dark
|
||||
? 1.12
|
||||
: 0.94;
|
||||
const chipSurfaceStyle: CSSProperties | undefined =
|
||||
showCustomHeroCard && chipFillColor
|
||||
? ({
|
||||
backgroundColor: chipFillColor,
|
||||
borderColor: 'transparent',
|
||||
color: textColor,
|
||||
'--user-hero-chip-hover-brightness': chipHoverBrightness,
|
||||
} as CSSProperties)
|
||||
: undefined;
|
||||
|
||||
const chipMenuTextColor = textColor ?? color.Surface.OnContainer;
|
||||
const chipColors = showCustomHeroCard
|
||||
? {
|
||||
innerColor,
|
||||
cardColor,
|
||||
textColor: chipMenuTextColor,
|
||||
chipSurfaceStyle,
|
||||
chipFillColor,
|
||||
chipHoverBrightness,
|
||||
}
|
||||
: {
|
||||
innerColor: color.Surface.Container,
|
||||
chipFillColor: color.SurfaceVariant.Container,
|
||||
textColor: color.SurfaceVariant.OnContainer,
|
||||
chipHoverBrightness,
|
||||
};
|
||||
|
||||
return (
|
||||
<Box direction="Column" style={{ color: textColor }}>
|
||||
<UserHero
|
||||
@@ -538,9 +575,7 @@ export function UserRoomProfile({ userId, initialProfile }: Readonly<UserRoomPro
|
||||
style={{
|
||||
backgroundColor: innerColor,
|
||||
borderRadius: toRem(5),
|
||||
borderWidth: toRem(5),
|
||||
borderColor: '#00000000',
|
||||
borderStyle: 'solid',
|
||||
boxShadow: 'inset 0 1px 2px rgba(0, 0, 0, 0.1)',
|
||||
padding: showCustomHeroCard && innerColor ? config.space.S200 : config.space.S300,
|
||||
}}
|
||||
>
|
||||
@@ -558,13 +593,11 @@ export function UserRoomProfile({ userId, initialProfile }: Readonly<UserRoomPro
|
||||
radii="300"
|
||||
before={<Icon size="50" src={Icons.Message} filled />}
|
||||
onClick={handleMessage}
|
||||
className={css.UserHeroChip}
|
||||
className={showCustomHeroCard ? css.UserHeroChipThemed : css.UserHeroChip}
|
||||
style={{
|
||||
marginLeft: 'auto',
|
||||
backgroundColor:
|
||||
backgroundColor !== color.Surface.Container ? cardColor : undefined,
|
||||
borderColor: backgroundColor,
|
||||
color: backgroundColor !== color.Surface.Container ? textColor : undefined,
|
||||
...(showCustomHeroCard && chipSurfaceStyle ? chipSurfaceStyle : {}),
|
||||
...heroMenuItemStyle({}, chipHoverBrightness),
|
||||
}}
|
||||
>
|
||||
<Text size="B300">Message</Text>
|
||||
@@ -575,62 +608,20 @@ export function UserRoomProfile({ userId, initialProfile }: Readonly<UserRoomPro
|
||||
profile={extendedProfile}
|
||||
htmlReactParserOptions={htmlReactParserOptions}
|
||||
linkifyOpts={linkifyOpts}
|
||||
backgroundColor={backgroundColor}
|
||||
innerColor={innerColor}
|
||||
cardColor={cardColor}
|
||||
textColor={textColor}
|
||||
/>
|
||||
<Box alignItems="Center" gap="100" wrap="Wrap" justifyContent="Center">
|
||||
{server && (
|
||||
<ServerChip
|
||||
server={server}
|
||||
backgroundColor={backgroundColor}
|
||||
innerColor={innerColor}
|
||||
cardColor={cardColor}
|
||||
textColor={textColor}
|
||||
/>
|
||||
)}
|
||||
<ShareChip
|
||||
userId={userId}
|
||||
backgroundColor={backgroundColor}
|
||||
innerColor={innerColor}
|
||||
cardColor={cardColor}
|
||||
textColor={textColor}
|
||||
/>
|
||||
{server && <ServerChip server={server} {...chipColors} />}
|
||||
<ShareChip userId={userId} {...chipColors} />
|
||||
{creator ? (
|
||||
<CreatorChip
|
||||
backgroundColor={backgroundColor}
|
||||
innerColor={innerColor}
|
||||
cardColor={cardColor}
|
||||
textColor={textColor}
|
||||
/>
|
||||
<CreatorChip {...chipColors} />
|
||||
) : (
|
||||
<PowerChip
|
||||
userId={userId}
|
||||
backgroundColor={backgroundColor}
|
||||
innerColor={innerColor}
|
||||
cardColor={cardColor}
|
||||
textColor={textColor}
|
||||
/>
|
||||
)}
|
||||
{userId !== myUserId && (
|
||||
<MutualRoomsChip
|
||||
userId={userId}
|
||||
backgroundColor={backgroundColor}
|
||||
innerColor={innerColor}
|
||||
cardColor={cardColor}
|
||||
textColor={textColor}
|
||||
/>
|
||||
)}
|
||||
{userId !== myUserId && (
|
||||
<OptionsChip
|
||||
userId={userId}
|
||||
backgroundColor={backgroundColor}
|
||||
innerColor={innerColor}
|
||||
cardColor={cardColor}
|
||||
textColor={textColor}
|
||||
/>
|
||||
<PowerChip userId={userId} {...chipColors} />
|
||||
)}
|
||||
{userId !== myUserId && <MutualRoomsChip userId={userId} {...chipColors} />}
|
||||
{userId !== myUserId && <OptionsChip userId={userId} {...chipColors} />}
|
||||
</Box>
|
||||
{ignored && <IgnoredUserAlert />}
|
||||
{member && membership === bannedMembership && (
|
||||
|
||||
@@ -0,0 +1,19 @@
|
||||
import type { CSSProperties } from 'react';
|
||||
|
||||
export function heroMenuItemStyle(
|
||||
base: CSSProperties,
|
||||
chipHoverBrightness?: number
|
||||
): CSSProperties {
|
||||
const bg = base.backgroundColor;
|
||||
const out: CSSProperties = { ...base };
|
||||
if (typeof bg === 'string' && bg !== '' && bg !== 'transparent') {
|
||||
(out as CSSProperties & { '--user-hero-menu-item-bg': string })['--user-hero-menu-item-bg'] =
|
||||
bg;
|
||||
}
|
||||
if (chipHoverBrightness != null) {
|
||||
(out as CSSProperties & { '--user-hero-chip-hover-brightness': number })[
|
||||
'--user-hero-chip-hover-brightness'
|
||||
] = chipHoverBrightness;
|
||||
}
|
||||
return out;
|
||||
}
|
||||
@@ -57,9 +57,12 @@ export const UserHeroStatusContainer = style({
|
||||
export const UserHeroStatusTooltip = style({
|
||||
maxWidth: '98%',
|
||||
justifySelf: 'left',
|
||||
});
|
||||
|
||||
export const UserHeroStatusTooltipInteractive = style({
|
||||
cursor: 'pointer',
|
||||
':hover': {
|
||||
filter: 'brightness(0.8)',
|
||||
filter: 'brightness(var(--user-hero-status-hover-brightness, 0.94))',
|
||||
transform: 'translateY(-1px)',
|
||||
},
|
||||
});
|
||||
@@ -78,19 +81,55 @@ export const UserHeroAvatarImg = style({
|
||||
},
|
||||
},
|
||||
});
|
||||
export const UserHeroChip = style({
|
||||
borderStyle: 'solid',
|
||||
borderWidth: '1px',
|
||||
export const UserHeroBrightnessHover = style({
|
||||
':hover': {
|
||||
filter: 'brightness(0.8)',
|
||||
filter: 'brightness(var(--user-hero-chip-hover-brightness, 0.94))',
|
||||
transform: 'translateY(-1px)',
|
||||
},
|
||||
});
|
||||
|
||||
export const UserHeroChip = style([
|
||||
UserHeroBrightnessHover,
|
||||
{
|
||||
borderStyle: 'solid',
|
||||
borderWidth: '1px',
|
||||
boxShadow: '0 1px 2px rgba(0, 0, 0, 0.1)',
|
||||
},
|
||||
]);
|
||||
|
||||
export const UserHeroChipThemed = style([
|
||||
UserHeroBrightnessHover,
|
||||
{
|
||||
borderStyle: 'solid',
|
||||
borderWidth: '1px',
|
||||
borderColor: 'transparent',
|
||||
boxShadow: '0 1px 2px rgba(0, 0, 0, 0.1)',
|
||||
},
|
||||
]);
|
||||
|
||||
export const MiscDataToggleButton = style({
|
||||
backgroundColor: 'transparent',
|
||||
opacity: 0.75,
|
||||
selectors: {
|
||||
'&:hover': {
|
||||
opacity: 1,
|
||||
backgroundColor: 'transparent',
|
||||
transform: 'none !important',
|
||||
},
|
||||
'&:active': {
|
||||
transform: 'none !important',
|
||||
},
|
||||
},
|
||||
});
|
||||
/** Same hover lift/filter as UserHeroBrightnessHover; pins bg so folds MenuItem hover can't mask brightness. */
|
||||
export const UserHeroMenuItem = style({
|
||||
borderStyle: 'hidden',
|
||||
borderWidth: '1px',
|
||||
':hover': {
|
||||
filter: 'brightness(0.8)',
|
||||
transform: 'translateY(-1px)',
|
||||
selectors: {
|
||||
'&:hover': {
|
||||
filter: 'brightness(var(--user-hero-chip-hover-brightness, 0.94))',
|
||||
transform: 'translateY(-1px)',
|
||||
backgroundColor: 'var(--user-hero-menu-item-bg) !important',
|
||||
},
|
||||
},
|
||||
});
|
||||
@@ -34,4 +34,5 @@ export enum ErrorCode {
|
||||
M_EXCLUSIVE = 'M_EXCLUSIVE',
|
||||
M_RESOURCE_LIMIT_EXCEEDED = 'M_RESOURCE_LIMIT_EXCEEDED',
|
||||
M_CANNOT_LEAVE_SERVER_NOTICE_ROOM = 'M_CANNOT_LEAVE_SERVER_NOTICE_ROOM',
|
||||
M_MAX_DELAY_EXCEEDED = 'M_MAX_DELAY_EXCEEDED',
|
||||
}
|
||||
@@ -26,6 +26,7 @@ import { SettingTile } from '$components/setting-tile';
|
||||
import { useRoom } from '$hooks/useRoom';
|
||||
import { usePowerLevels } from '$hooks/usePowerLevels';
|
||||
import { useMatrixClient } from '$hooks/useMatrixClient';
|
||||
import { useStateEvent } from '$hooks/useStateEvent';
|
||||
|
||||
import { useRoomCreators } from '$hooks/useRoomCreators';
|
||||
import { useRoomPermissions } from '$hooks/useRoomPermissions';
|
||||
@@ -70,8 +71,17 @@ export function CosmeticsAvatar({ profile, member, userId, room }: CosmeticsSett
|
||||
const capabilities = useCapabilities();
|
||||
const [alertRemove, setAlertRemove] = useState(false);
|
||||
const disableSetAvatar = capabilities['m.set_avatar_url']?.enabled === false;
|
||||
|
||||
const avatarMxc = member.getMxcAvatarUrl();
|
||||
const memberStateEvent = useStateEvent(room, EventType.RoomMember, userId);
|
||||
const memberStateContent = memberStateEvent?.getContent<{ avatar_url?: string }>();
|
||||
const globalAvatarMxc = mx.getUser(userId)?.avatarUrl ?? profile.avatarUrl;
|
||||
const roomAvatarMxc = memberStateEvent
|
||||
? memberStateContent?.avatar_url
|
||||
: member.getMxcAvatarUrl();
|
||||
const avatarMxc = roomAvatarMxc ?? globalAvatarMxc;
|
||||
const hasRoomAvatarOverride =
|
||||
memberStateEvent !== undefined &&
|
||||
memberStateContent?.avatar_url !== undefined &&
|
||||
memberStateContent.avatar_url !== globalAvatarMxc;
|
||||
const avatarUrl =
|
||||
avatarMxc && (mxcUrlToHttp(mx, avatarMxc, useAuthentication, 96, 96, 'crop') ?? undefined);
|
||||
|
||||
@@ -92,15 +102,17 @@ export function CosmeticsAvatar({ profile, member, userId, room }: CosmeticsSett
|
||||
const handleUploaded = useCallback(
|
||||
(upload: UploadSuccess) => {
|
||||
const { mxc } = upload;
|
||||
myRoomAvatar.exe(mxc);
|
||||
handleRemoveUpload();
|
||||
myRoomAvatar.exe(mxc).finally(() => {
|
||||
handleRemoveUpload();
|
||||
});
|
||||
},
|
||||
[myRoomAvatar, handleRemoveUpload]
|
||||
);
|
||||
|
||||
const handleRemoveAvatar = () => {
|
||||
myRoomAvatar.exe('');
|
||||
setAlertRemove(false);
|
||||
myRoomAvatar.exe('').finally(() => {
|
||||
setAlertRemove(false);
|
||||
});
|
||||
};
|
||||
|
||||
return (
|
||||
@@ -139,20 +151,18 @@ export function CosmeticsAvatar({ profile, member, userId, room }: CosmeticsSett
|
||||
>
|
||||
<Text size="B300">Upload</Text>
|
||||
</Button>
|
||||
{avatarUrl &&
|
||||
avatarUrl !==
|
||||
mxcUrlToHttp(mx, profile.avatarUrl ?? '', useAuthentication, 96, 96, 'crop') && (
|
||||
<Button
|
||||
size="300"
|
||||
variant="Critical"
|
||||
fill="None"
|
||||
radii="300"
|
||||
disabled={disableSetAvatar}
|
||||
onClick={() => setAlertRemove(true)}
|
||||
>
|
||||
<Text size="B300">Remove</Text>
|
||||
</Button>
|
||||
)}
|
||||
{hasRoomAvatarOverride && (
|
||||
<Button
|
||||
size="300"
|
||||
variant="Critical"
|
||||
fill="None"
|
||||
radii="300"
|
||||
disabled={disableSetAvatar}
|
||||
onClick={() => setAlertRemove(true)}
|
||||
>
|
||||
<Text size="B300">Remove</Text>
|
||||
</Button>
|
||||
)}
|
||||
</Box>
|
||||
)}
|
||||
|
||||
|
||||
@@ -56,6 +56,8 @@ import {
|
||||
import { useRoomCreators } from '$hooks/useRoomCreators';
|
||||
import { useRoomCreatorsTag } from '$hooks/useRoomCreatorsTag';
|
||||
import { useSettingsLinkBaseUrl } from '$features/settings/useSettingsLinkBaseUrl';
|
||||
import { useSetting } from '$state/hooks/settings';
|
||||
import { settingsAtom } from '$state/settings';
|
||||
import type { ResultItem } from './useMessageSearch';
|
||||
|
||||
type SearchResultGroupProps = {
|
||||
@@ -95,6 +97,11 @@ export function SearchResultGroup({
|
||||
const accessibleTagColors = useAccessiblePowerTagColors(theme.kind, creatorsTag, powerLevelTags);
|
||||
const nicknames = useAtomValue(nicknamesAtom);
|
||||
const settingsLinkBaseUrl = useSettingsLinkBaseUrl();
|
||||
const [incomingInlineImagesDefaultHeight] = useSetting(
|
||||
settingsAtom,
|
||||
'incomingInlineImagesDefaultHeight'
|
||||
);
|
||||
const [incomingInlineImagesMaxHeight] = useSetting(settingsAtom, 'incomingInlineImagesMaxHeight');
|
||||
|
||||
const mentionClickHandler = useMentionClickHandler(room.roomId);
|
||||
const spoilerClickHandler = useSpoilerClickHandler();
|
||||
@@ -127,6 +134,8 @@ export function SearchResultGroup({
|
||||
handleSpoilerClick: spoilerClickHandler,
|
||||
handleMentionClick: mentionClickHandler,
|
||||
nicknames,
|
||||
incomingInlineImagesDefaultHeight,
|
||||
incomingInlineImagesMaxHeight,
|
||||
}),
|
||||
[
|
||||
mx,
|
||||
@@ -138,6 +147,8 @@ export function SearchResultGroup({
|
||||
useAuthentication,
|
||||
nicknames,
|
||||
settingsLinkBaseUrl,
|
||||
incomingInlineImagesDefaultHeight,
|
||||
incomingInlineImagesMaxHeight,
|
||||
]
|
||||
);
|
||||
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
import type { KeyboardEventHandler, MouseEvent, RefObject } from 'react';
|
||||
import { forwardRef, useCallback, useEffect, useRef, useState, useMemo } from 'react';
|
||||
import { useAtom, useAtomValue } from 'jotai';
|
||||
import { useAtom, useAtomValue, useSetAtom } from 'jotai';
|
||||
|
||||
import { isKeyHotkey } from 'is-hotkey';
|
||||
import type {
|
||||
IContent,
|
||||
@@ -10,6 +11,7 @@ import type {
|
||||
RoomMessageEventContent,
|
||||
StickerEventContent,
|
||||
} from '$types/matrix-sdk';
|
||||
import { MatrixError } from '$types/matrix-sdk';
|
||||
import { EventType, MsgType, RelationType } from '$types/matrix-sdk';
|
||||
import { ReactEditor } from 'slate-react';
|
||||
import { Editor, Point, Range, Transforms } from 'slate';
|
||||
@@ -89,7 +91,7 @@ import { safeFile } from '$utils/mimeTypes';
|
||||
import { fulfilledPromiseSettledResult } from '$utils/common';
|
||||
import { useSetting } from '$state/hooks/settings';
|
||||
import { settingsAtom } from '$state/settings';
|
||||
import { getMentionContent, reactionOrEditEvent } from '$utils/room';
|
||||
import { getMentionContent, isThreadRelationEvent, reactionOrEditEvent } from '$utils/room';
|
||||
import { Command, SHRUG, TABLEFLIP, UNFLIP, useCommands } from '$hooks/useCommands';
|
||||
import { mobileOrTablet } from '$utils/user-agent';
|
||||
import { useElementSizeObserver } from '$hooks/useElementSizeObserver';
|
||||
@@ -108,6 +110,7 @@ import {
|
||||
delayedEventsSupportedAtom,
|
||||
roomIdToScheduledTimeAtomFamily,
|
||||
roomIdToEditingScheduledDelayIdAtomFamily,
|
||||
serverMaxDelayMsAtom,
|
||||
} from '$state/scheduledMessages';
|
||||
import {
|
||||
sendDelayedMessage,
|
||||
@@ -115,7 +118,7 @@ import {
|
||||
computeDelayMs,
|
||||
cancelDelayedEvent,
|
||||
} from '$utils/delayedEvents';
|
||||
import { timeHourMinute, timeDayMonthYear } from '$utils/time';
|
||||
import { timeHourMinute, timeDayMonthYear, daysToMs } from '$utils/time';
|
||||
import { stopPropagation } from '$utils/keyboard';
|
||||
|
||||
import { usePowerLevelsContext } from '$hooks/usePowerLevels';
|
||||
@@ -128,6 +131,7 @@ import {
|
||||
} from '$hooks/usePerMessageProfile';
|
||||
import { Microphone, Stop } from '@phosphor-icons/react';
|
||||
import { getSupportedAudioExtension } from '$plugins/voice-recorder-kit/supportedCodec';
|
||||
import { ErrorCode } from '../../cs-errorcode';
|
||||
import { sanitizeText } from '$utils/sanitize';
|
||||
import { PKitCommandMessageHandler } from '$plugins/pluralkit-handler/PKitCommandMessageHandler';
|
||||
import { PKitProxyMessageHandler } from '$plugins/pluralkit-handler/PKitProxyMessageHandler';
|
||||
@@ -162,7 +166,10 @@ const getLatestThreadEventId = (room: Room, threadRootId: string): string => {
|
||||
const thread = room.getThread(threadRootId);
|
||||
const threadEvents: MatrixEvent[] = thread?.events ?? [];
|
||||
const filtered = threadEvents.filter(
|
||||
(ev) => ev.getId() !== threadRootId && !reactionOrEditEvent(ev)
|
||||
(ev) =>
|
||||
ev.getId() !== threadRootId &&
|
||||
!reactionOrEditEvent(ev) &&
|
||||
isThreadRelationEvent(ev, threadRootId)
|
||||
);
|
||||
if (filtered.length > 0) {
|
||||
return filtered[filtered.length - 1]!.getId() ?? threadRootId;
|
||||
@@ -174,7 +181,9 @@ const getLatestThreadEventId = (room: Room, threadRootId: string): string => {
|
||||
.getEvents()
|
||||
.filter(
|
||||
(ev) =>
|
||||
ev.threadRootId === threadRootId && ev.getId() !== threadRootId && !reactionOrEditEvent(ev)
|
||||
ev.getId() !== threadRootId &&
|
||||
!reactionOrEditEvent(ev) &&
|
||||
isThreadRelationEvent(ev, threadRootId)
|
||||
);
|
||||
if (liveEvents.length > 0) {
|
||||
return liveEvents.at(-1)!.getId() ?? threadRootId;
|
||||
@@ -192,10 +201,11 @@ const getReplyContent = (replyDraft: IReplyDraft | undefined, room?: Room): IEve
|
||||
relatesTo.event_id = replyDraft.relation.event_id;
|
||||
relatesTo.rel_type = RelationType.Thread;
|
||||
|
||||
// Check if this is a reply to a specific message in the thread
|
||||
// If the user explicitly clicked "reply" on a message (including the thread root),
|
||||
// we must set is_falling_back=false and target that message directly.
|
||||
// (replyDraft.body being empty means it's just a seeded thread draft)
|
||||
if (replyDraft.body && replyDraft.eventId !== replyDraft.relation.event_id) {
|
||||
// Explicit reply to a specific message — per spec, is_falling_back must be false
|
||||
if (replyDraft.body) {
|
||||
// Explicit reply — per spec, is_falling_back must be false
|
||||
relatesTo['m.in_reply_to'] = {
|
||||
event_id: replyDraft.eventId,
|
||||
};
|
||||
@@ -305,7 +315,7 @@ export const RoomInput = forwardRef<HTMLDivElement, RoomInputProps>(
|
||||
useState<AutocompleteQuery<AutocompletePrefix>>();
|
||||
const [isQuickTextReact, setQuickTextReact] = useState(false);
|
||||
|
||||
const sendTypingStatus = useTypingStatusUpdater(mx, roomId);
|
||||
const sendTypingStatus = useTypingStatusUpdater(mx, roomId, { disabled: !!threadRootId });
|
||||
|
||||
const [inputKey, setInputKey] = useState(0);
|
||||
const getUploadItemKey = useCallback((fileItem: TUploadItem): string => {
|
||||
@@ -375,6 +385,8 @@ export const RoomInput = forwardRef<HTMLDivElement, RoomInputProps>(
|
||||
const [showSchedulePicker, setShowSchedulePicker] = useState(false);
|
||||
const [silentReply, setSilentReply] = useState(!mentionInReplies);
|
||||
const [hour24Clock] = useSetting(settingsAtom, 'hour24Clock');
|
||||
const setServerMaxDelayMs = useSetAtom(serverMaxDelayMsAtom);
|
||||
const [sendError, setSendError] = useState<string | undefined>();
|
||||
const isEncrypted = room.hasEncryptionStateEvent();
|
||||
|
||||
useElementSizeObserver(
|
||||
@@ -953,12 +965,28 @@ export const RoomInput = forwardRef<HTMLDivElement, RoomInputProps>(
|
||||
} else {
|
||||
await sendDelayedMessage(mx, roomId, content as RoomMessageEventContent, delayMs);
|
||||
}
|
||||
setSendError(undefined);
|
||||
invalidate();
|
||||
setEditingScheduledDelayId(null);
|
||||
setScheduledTime(null);
|
||||
resetInput();
|
||||
} catch {
|
||||
// Network/server error — leave editor and scheduled state intact for retry
|
||||
} catch (e: unknown) {
|
||||
if (
|
||||
e instanceof MatrixError &&
|
||||
(e.errcode === ErrorCode.M_MAX_DELAY_EXCEEDED ||
|
||||
e.data?.['org.matrix.msc4140.errcode'] === 'M_MAX_DELAY_EXCEEDED')
|
||||
) {
|
||||
const maxDelay =
|
||||
(e.data as { max_delay?: number })?.max_delay ??
|
||||
e.data?.['org.matrix.msc4140.max_delay'];
|
||||
if (typeof maxDelay === 'number') setServerMaxDelayMs(maxDelay);
|
||||
const maxDelayDays = maxDelay / daysToMs(1);
|
||||
setSendError(
|
||||
`Scheduled time exceeds the maximum delay allowed by this server. Please choose an earlier time. The Maximum Delay is of ${maxDelayDays} day${maxDelayDays > 1 ? 's' : ''}.`
|
||||
);
|
||||
} else {
|
||||
setSendError('Failed to schedule message. Please try again.');
|
||||
}
|
||||
}
|
||||
} else if (editingScheduledDelayId) {
|
||||
try {
|
||||
@@ -1049,6 +1077,7 @@ export const RoomInput = forwardRef<HTMLDivElement, RoomInputProps>(
|
||||
isEncrypted,
|
||||
setEditingScheduledDelayId,
|
||||
setScheduledTime,
|
||||
setServerMaxDelayMs,
|
||||
]);
|
||||
|
||||
const handleKeyDown: KeyboardEventHandler = useCallback(
|
||||
@@ -1379,6 +1408,7 @@ export const RoomInput = forwardRef<HTMLDivElement, RoomInputProps>(
|
||||
onClick={() => {
|
||||
setScheduledTime(null);
|
||||
setEditingScheduledDelayId(null);
|
||||
setSendError(undefined);
|
||||
}}
|
||||
variant="SurfaceVariant"
|
||||
size="300"
|
||||
@@ -1397,6 +1427,19 @@ export const RoomInput = forwardRef<HTMLDivElement, RoomInputProps>(
|
||||
</Box>
|
||||
</div>
|
||||
)}
|
||||
{sendError && (
|
||||
<div>
|
||||
<Box
|
||||
alignItems="Center"
|
||||
gap="300"
|
||||
style={{ padding: `${config.space.S200} ${config.space.S300} 0` }}
|
||||
>
|
||||
<Text style={{ color: color.Critical.Main }} size="T300">
|
||||
{sendError}
|
||||
</Text>
|
||||
</Box>
|
||||
</div>
|
||||
)}
|
||||
{replyDraft && (!threadRootId || replyDraft.body) && (
|
||||
<div>
|
||||
<Box
|
||||
@@ -1720,6 +1763,7 @@ export const RoomInput = forwardRef<HTMLDivElement, RoomInputProps>(
|
||||
onSubmit={(date) => {
|
||||
setScheduledTime(date);
|
||||
setShowSchedulePicker(false);
|
||||
setSendError(undefined);
|
||||
}}
|
||||
/>
|
||||
)}
|
||||
|
||||
@@ -155,6 +155,11 @@ export function RoomTimeline({
|
||||
const [dateFormatString] = useSetting(settingsAtom, 'dateFormatString');
|
||||
const [autoplayStickers] = useSetting(settingsAtom, 'autoplayStickers');
|
||||
const [autoplayEmojis] = useSetting(settingsAtom, 'autoplayEmojis');
|
||||
const [incomingInlineImagesDefaultHeight] = useSetting(
|
||||
settingsAtom,
|
||||
'incomingInlineImagesDefaultHeight'
|
||||
);
|
||||
const [incomingInlineImagesMaxHeight] = useSetting(settingsAtom, 'incomingInlineImagesMaxHeight');
|
||||
const [hideMemberInReadOnly] = useSetting(settingsAtom, 'hideMembershipInReadOnly');
|
||||
|
||||
const showUrlPreview = room.hasEncryptionStateEvent() ? encUrlPreview : urlPreview;
|
||||
@@ -567,6 +572,8 @@ export function RoomTimeline({
|
||||
handleMentionClick: mentionClickHandler,
|
||||
nicknames,
|
||||
autoplayEmojis,
|
||||
incomingInlineImagesDefaultHeight,
|
||||
incomingInlineImagesMaxHeight,
|
||||
replaceTextNode: buildAbbrReplaceTextNode(abbrMap, linkifyOpts),
|
||||
}),
|
||||
[
|
||||
@@ -574,6 +581,8 @@ export function RoomTimeline({
|
||||
room.roomId,
|
||||
linkifyOpts,
|
||||
autoplayEmojis,
|
||||
incomingInlineImagesDefaultHeight,
|
||||
incomingInlineImagesMaxHeight,
|
||||
mentionClickHandler,
|
||||
nicknames,
|
||||
mediaAuthentication,
|
||||
|
||||
@@ -1,28 +1,15 @@
|
||||
import { useState } from 'react';
|
||||
import {
|
||||
Box,
|
||||
Icon,
|
||||
Icons,
|
||||
Modal,
|
||||
Overlay,
|
||||
OverlayBackdrop,
|
||||
OverlayCenter,
|
||||
Text,
|
||||
as,
|
||||
config,
|
||||
} from 'folds';
|
||||
import { useAtomValue } from 'jotai';
|
||||
import { Box, Icon, Icons, Text, as, config } from 'folds';
|
||||
import type { Room } from '$types/matrix-sdk';
|
||||
import classNames from 'classnames';
|
||||
import FocusTrap from 'focus-trap-react';
|
||||
import { useAtomValue } from 'jotai';
|
||||
import { useAtom } from 'jotai';
|
||||
|
||||
import { getMemberDisplayName } from '$utils/room';
|
||||
import { getMxIdLocalPart } from '$utils/matrix';
|
||||
import { useMatrixClient } from '$hooks/useMatrixClient';
|
||||
import { useRoomLatestRenderedEvent } from '$hooks/useRoomLatestRenderedEvent';
|
||||
import { useRoomEventReaders } from '$hooks/useRoomEventReaders';
|
||||
import { EventReaders } from '$components/event-readers';
|
||||
import { stopPropagation } from '$utils/keyboard';
|
||||
import { modalAtom, ModalType } from '$state/modal';
|
||||
import { nicknamesAtom } from '$state/nicknames';
|
||||
import * as css from './RoomViewFollowing.css';
|
||||
|
||||
@@ -38,7 +25,7 @@ export type RoomViewFollowingProps = {
|
||||
export const RoomViewFollowing = as<'div', RoomViewFollowingProps>(
|
||||
({ className, room, threadEventId, participantIds, ...props }, ref) => {
|
||||
const mx = useMatrixClient();
|
||||
const [open, setOpen] = useState(false);
|
||||
const [, setModal] = useAtom(modalAtom);
|
||||
const latestEvent = useRoomLatestRenderedEvent(room);
|
||||
const resolvedEventId = threadEventId ?? latestEvent?.getId();
|
||||
const latestEventReaders = useRoomEventReaders(room, resolvedEventId);
|
||||
@@ -54,150 +41,138 @@ export const RoomViewFollowing = as<'div', RoomViewFollowingProps>(
|
||||
const eventId = resolvedEventId;
|
||||
|
||||
return (
|
||||
<>
|
||||
{eventId && (
|
||||
<Overlay open={open} backdrop={<OverlayBackdrop />}>
|
||||
<OverlayCenter>
|
||||
<FocusTrap
|
||||
focusTrapOptions={{
|
||||
initialFocus: false,
|
||||
onDeactivate: () => setOpen(false),
|
||||
clickOutsideDeactivates: true,
|
||||
escapeDeactivates: stopPropagation,
|
||||
}}
|
||||
>
|
||||
<Modal variant="Surface" size="300">
|
||||
<EventReaders room={room} eventId={eventId} requestClose={() => setOpen(false)} />
|
||||
</Modal>
|
||||
</FocusTrap>
|
||||
</OverlayCenter>
|
||||
</Overlay>
|
||||
<Box
|
||||
as={names.length > 0 ? 'button' : 'div'}
|
||||
onClick={
|
||||
names.length > 0
|
||||
? () => {
|
||||
if (eventId) {
|
||||
setModal({ type: ModalType.ReadReceipts, room, eventId });
|
||||
}
|
||||
}
|
||||
: undefined
|
||||
}
|
||||
className={classNames(css.RoomViewFollowing({ clickable: names.length > 0 }), className)}
|
||||
alignItems="Center"
|
||||
justifyContent="End"
|
||||
gap="200"
|
||||
{...props}
|
||||
ref={ref}
|
||||
>
|
||||
{names.length > 0 && (
|
||||
<>
|
||||
<Icon style={{ opacity: config.opacity.P300 }} size="100" src={Icons.CheckTwice} />
|
||||
<Text size="T300" truncate>
|
||||
{names.length === 1 && (
|
||||
<>
|
||||
<b style={{ WebkitTextFillColor: 'inherit' }}>{names[0]}</b>
|
||||
<Text
|
||||
as="span"
|
||||
size="Inherit"
|
||||
priority="300"
|
||||
style={{ WebkitTextFillColor: 'currentColor' }}
|
||||
>
|
||||
{' is following the conversation.'}
|
||||
</Text>
|
||||
</>
|
||||
)}
|
||||
{names.length === 2 && (
|
||||
<>
|
||||
<b style={{ WebkitTextFillColor: 'inherit' }}>{names[0]}</b>
|
||||
<Text
|
||||
as="span"
|
||||
size="Inherit"
|
||||
priority="300"
|
||||
style={{ WebkitTextFillColor: 'currentColor' }}
|
||||
>
|
||||
{' and '}
|
||||
</Text>
|
||||
<b style={{ WebkitTextFillColor: 'inherit' }}>{names[1]}</b>
|
||||
<Text
|
||||
as="span"
|
||||
size="Inherit"
|
||||
priority="300"
|
||||
style={{ WebkitTextFillColor: 'currentColor' }}
|
||||
>
|
||||
{' are following the conversation.'}
|
||||
</Text>
|
||||
</>
|
||||
)}
|
||||
{names.length === 3 && (
|
||||
<>
|
||||
<b style={{ WebkitTextFillColor: 'inherit' }}>{names[0]}</b>
|
||||
<Text
|
||||
as="span"
|
||||
size="Inherit"
|
||||
priority="300"
|
||||
style={{ WebkitTextFillColor: 'currentColor' }}
|
||||
>
|
||||
{', '}
|
||||
</Text>
|
||||
<b style={{ WebkitTextFillColor: 'inherit' }}>{names[1]}</b>
|
||||
<Text
|
||||
as="span"
|
||||
size="Inherit"
|
||||
priority="300"
|
||||
style={{ WebkitTextFillColor: 'currentColor' }}
|
||||
>
|
||||
{' and '}
|
||||
</Text>
|
||||
<b style={{ WebkitTextFillColor: 'inherit' }}>{names[2]}</b>
|
||||
<Text
|
||||
as="span"
|
||||
size="Inherit"
|
||||
priority="300"
|
||||
style={{ WebkitTextFillColor: 'currentColor' }}
|
||||
>
|
||||
{' are following the conversation.'}
|
||||
</Text>
|
||||
</>
|
||||
)}
|
||||
{names.length > 3 && (
|
||||
<>
|
||||
<b style={{ WebkitTextFillColor: 'inherit' }}>{names[0]}</b>
|
||||
<Text
|
||||
as="span"
|
||||
size="Inherit"
|
||||
priority="300"
|
||||
style={{ WebkitTextFillColor: 'currentColor' }}
|
||||
>
|
||||
{', '}
|
||||
</Text>
|
||||
<b style={{ WebkitTextFillColor: 'inherit' }}>{names[1]}</b>
|
||||
<Text
|
||||
as="span"
|
||||
size="Inherit"
|
||||
priority="300"
|
||||
style={{ WebkitTextFillColor: 'currentColor' }}
|
||||
>
|
||||
{', '}
|
||||
</Text>
|
||||
<b style={{ WebkitTextFillColor: 'inherit' }}>{names[2]}</b>
|
||||
<Text
|
||||
as="span"
|
||||
size="Inherit"
|
||||
priority="300"
|
||||
style={{ WebkitTextFillColor: 'currentColor' }}
|
||||
>
|
||||
{' and '}
|
||||
</Text>
|
||||
<b style={{ WebkitTextFillColor: 'inherit' }}>{names.length - 3} others</b>
|
||||
<Text
|
||||
as="span"
|
||||
size="Inherit"
|
||||
priority="300"
|
||||
style={{ WebkitTextFillColor: 'currentColor' }}
|
||||
>
|
||||
{' are following the conversation.'}
|
||||
</Text>
|
||||
</>
|
||||
)}
|
||||
</Text>
|
||||
</>
|
||||
)}
|
||||
<Box
|
||||
as={names.length > 0 ? 'button' : 'div'}
|
||||
onClick={names.length > 0 ? () => setOpen(true) : undefined}
|
||||
className={classNames(css.RoomViewFollowing({ clickable: names.length > 0 }), className)}
|
||||
alignItems="Center"
|
||||
justifyContent="End"
|
||||
gap="200"
|
||||
{...props}
|
||||
ref={ref}
|
||||
>
|
||||
{names.length > 0 && (
|
||||
<>
|
||||
<Icon style={{ opacity: config.opacity.P300 }} size="100" src={Icons.CheckTwice} />
|
||||
<Text size="T300" truncate>
|
||||
{names.length === 1 && (
|
||||
<>
|
||||
<b style={{ WebkitTextFillColor: 'inherit' }}>{names[0]}</b>
|
||||
<Text
|
||||
as="span"
|
||||
size="Inherit"
|
||||
priority="300"
|
||||
style={{ WebkitTextFillColor: 'currentColor' }}
|
||||
>
|
||||
{' is following the conversation.'}
|
||||
</Text>
|
||||
</>
|
||||
)}
|
||||
{names.length === 2 && (
|
||||
<>
|
||||
<b style={{ WebkitTextFillColor: 'inherit' }}>{names[0]}</b>
|
||||
<Text
|
||||
as="span"
|
||||
size="Inherit"
|
||||
priority="300"
|
||||
style={{ WebkitTextFillColor: 'currentColor' }}
|
||||
>
|
||||
{' and '}
|
||||
</Text>
|
||||
<b style={{ WebkitTextFillColor: 'inherit' }}>{names[1]}</b>
|
||||
<Text
|
||||
as="span"
|
||||
size="Inherit"
|
||||
priority="300"
|
||||
style={{ WebkitTextFillColor: 'currentColor' }}
|
||||
>
|
||||
{' are following the conversation.'}
|
||||
</Text>
|
||||
</>
|
||||
)}
|
||||
{names.length === 3 && (
|
||||
<>
|
||||
<b style={{ WebkitTextFillColor: 'inherit' }}>{names[0]}</b>
|
||||
<Text
|
||||
as="span"
|
||||
size="Inherit"
|
||||
priority="300"
|
||||
style={{ WebkitTextFillColor: 'currentColor' }}
|
||||
>
|
||||
{', '}
|
||||
</Text>
|
||||
<b style={{ WebkitTextFillColor: 'inherit' }}>{names[1]}</b>
|
||||
<Text
|
||||
as="span"
|
||||
size="Inherit"
|
||||
priority="300"
|
||||
style={{ WebkitTextFillColor: 'currentColor' }}
|
||||
>
|
||||
{' and '}
|
||||
</Text>
|
||||
<b style={{ WebkitTextFillColor: 'inherit' }}>{names[2]}</b>
|
||||
<Text
|
||||
as="span"
|
||||
size="Inherit"
|
||||
priority="300"
|
||||
style={{ WebkitTextFillColor: 'currentColor' }}
|
||||
>
|
||||
{' are following the conversation.'}
|
||||
</Text>
|
||||
</>
|
||||
)}
|
||||
{names.length > 3 && (
|
||||
<>
|
||||
<b style={{ WebkitTextFillColor: 'inherit' }}>{names[0]}</b>
|
||||
<Text
|
||||
as="span"
|
||||
size="Inherit"
|
||||
priority="300"
|
||||
style={{ WebkitTextFillColor: 'currentColor' }}
|
||||
>
|
||||
{', '}
|
||||
</Text>
|
||||
<b style={{ WebkitTextFillColor: 'inherit' }}>{names[1]}</b>
|
||||
<Text
|
||||
as="span"
|
||||
size="Inherit"
|
||||
priority="300"
|
||||
style={{ WebkitTextFillColor: 'currentColor' }}
|
||||
>
|
||||
{', '}
|
||||
</Text>
|
||||
<b style={{ WebkitTextFillColor: 'inherit' }}>{names[2]}</b>
|
||||
<Text
|
||||
as="span"
|
||||
size="Inherit"
|
||||
priority="300"
|
||||
style={{ WebkitTextFillColor: 'currentColor' }}
|
||||
>
|
||||
{' and '}
|
||||
</Text>
|
||||
<b style={{ WebkitTextFillColor: 'inherit' }}>{names.length - 3} others</b>
|
||||
<Text
|
||||
as="span"
|
||||
size="Inherit"
|
||||
priority="300"
|
||||
style={{ WebkitTextFillColor: 'currentColor' }}
|
||||
>
|
||||
{' are following the conversation.'}
|
||||
</Text>
|
||||
</>
|
||||
)}
|
||||
</Text>
|
||||
</>
|
||||
)}
|
||||
</Box>
|
||||
</>
|
||||
</Box>
|
||||
);
|
||||
}
|
||||
);
|
||||
@@ -82,6 +82,7 @@ import { useRoomPermissions } from '$hooks/useRoomPermissions';
|
||||
import { InviteUserPrompt } from '$components/invite-user-prompt';
|
||||
import { ContainerColor } from '$styles/ContainerColor.css';
|
||||
import { useRoomWidgets } from '$hooks/useRoomWidgets';
|
||||
import { hasThreadRootAggregation, isThreadRelationEvent } from '$utils/room';
|
||||
|
||||
import { DirectInvitePrompt } from '$components/direct-invite-prompt';
|
||||
import { AsyncStatus, useAsyncCallback } from '$hooks/useAsyncCallback';
|
||||
@@ -439,8 +440,9 @@ export function RoomViewHeader({ callView }: Readonly<{ callView?: boolean }>) {
|
||||
// 1. Events that ARE thread roots (have isThreadRoot = true or have replies)
|
||||
// 2. Events that are IN threads (have threadRootId)
|
||||
events.forEach((event: MatrixEvent) => {
|
||||
// Check if this event is a thread root
|
||||
if (event.isThreadRoot) {
|
||||
// Check if this event is an actual thread root. `isThreadRoot` can be
|
||||
// polluted by locally-created Thread shells, so require the server bundle.
|
||||
if (hasThreadRootAggregation(event)) {
|
||||
const rootId = event.getId();
|
||||
if (rootId && !room.getThread(rootId)) {
|
||||
threadRoots.add(rootId);
|
||||
@@ -449,7 +451,11 @@ export function RoomViewHeader({ callView }: Readonly<{ callView?: boolean }>) {
|
||||
|
||||
// Check if this event is a reply in a thread
|
||||
const { threadRootId } = event;
|
||||
if (threadRootId && !room.getThread(threadRootId)) {
|
||||
if (
|
||||
threadRootId &&
|
||||
isThreadRelationEvent(event, threadRootId) &&
|
||||
!room.getThread(threadRootId)
|
||||
) {
|
||||
threadRoots.add(threadRootId);
|
||||
}
|
||||
});
|
||||
@@ -476,8 +482,9 @@ export function RoomViewHeader({ callView }: Readonly<{ callView?: boolean }>) {
|
||||
|
||||
// Listen for new timeline events (including pagination)
|
||||
const handleTimelineEvent = (mEvent: MatrixEvent) => {
|
||||
// Check if this event is a thread root
|
||||
if (mEvent.isThreadRoot) {
|
||||
// Check if this event is an actual thread root. `isThreadRoot` can be
|
||||
// polluted by locally-created Thread shells, so require the server bundle.
|
||||
if (hasThreadRootAggregation(mEvent)) {
|
||||
const rootId = mEvent.getId();
|
||||
if (rootId && !room.getThread(rootId)) {
|
||||
const rootEvent = room.findEventById(rootId);
|
||||
@@ -489,7 +496,11 @@ export function RoomViewHeader({ callView }: Readonly<{ callView?: boolean }>) {
|
||||
|
||||
// Check if this is a reply in a thread
|
||||
const { threadRootId } = mEvent;
|
||||
if (threadRootId && !room.getThread(threadRootId)) {
|
||||
if (
|
||||
threadRootId &&
|
||||
isThreadRelationEvent(mEvent, threadRootId) &&
|
||||
!room.getThread(threadRootId)
|
||||
) {
|
||||
const rootEvent = room.findEventById(threadRootId);
|
||||
if (rootEvent) {
|
||||
room.createThread(threadRootId, rootEvent, [], false);
|
||||
|
||||
@@ -23,13 +23,16 @@ type EventInit = {
|
||||
threadRootId?: string;
|
||||
/** When set, the event is treated as a reaction/annotation */
|
||||
relType?: string;
|
||||
/** Relation target event id */
|
||||
relEventId?: string;
|
||||
};
|
||||
|
||||
function makeEvent({ id, threadRootId, relType }: EventInit) {
|
||||
function makeEvent({ id, threadRootId, relType, relEventId }: EventInit) {
|
||||
return {
|
||||
getId: () => id,
|
||||
threadRootId,
|
||||
getRelation: () => (relType ? { rel_type: relType } : null),
|
||||
getRelation: () => (relType ? { rel_type: relType, event_id: relEventId } : null),
|
||||
getWireContent: () => ({}),
|
||||
getContent: () => ({}),
|
||||
};
|
||||
}
|
||||
@@ -61,7 +64,12 @@ const REACTION_ID = '$reaction-event-id';
|
||||
describe('getThreadReplyEvents', () => {
|
||||
it('returns thread events minus the root when the Thread object has replies', () => {
|
||||
const rootEvent = makeEvent({ id: ROOT_ID, threadRootId: ROOT_ID });
|
||||
const replyEvent = makeEvent({ id: REPLY_ID, threadRootId: ROOT_ID });
|
||||
const replyEvent = makeEvent({
|
||||
id: REPLY_ID,
|
||||
threadRootId: ROOT_ID,
|
||||
relType: RelationType.Thread,
|
||||
relEventId: ROOT_ID,
|
||||
});
|
||||
|
||||
const room = makeRoom({
|
||||
thread: { events: [rootEvent, replyEvent] as any },
|
||||
@@ -76,11 +84,17 @@ describe('getThreadReplyEvents', () => {
|
||||
|
||||
it('excludes reactions from thread events', () => {
|
||||
const rootEvent = makeEvent({ id: ROOT_ID, threadRootId: ROOT_ID });
|
||||
const replyEvent = makeEvent({ id: REPLY_ID, threadRootId: ROOT_ID });
|
||||
const replyEvent = makeEvent({
|
||||
id: REPLY_ID,
|
||||
threadRootId: ROOT_ID,
|
||||
relType: RelationType.Thread,
|
||||
relEventId: ROOT_ID,
|
||||
});
|
||||
const reactionEvent = makeEvent({
|
||||
id: REACTION_ID,
|
||||
threadRootId: ROOT_ID,
|
||||
relType: RelationType.Annotation,
|
||||
relEventId: REPLY_ID,
|
||||
});
|
||||
|
||||
const room = makeRoom({
|
||||
@@ -99,7 +113,12 @@ describe('getThreadReplyEvents', () => {
|
||||
it('falls back to the live timeline when thread.events contains only the root (classic-sync case)', () => {
|
||||
// classic sync: thread created with no initialEvents → events = [rootEvent]
|
||||
const rootEvent = makeEvent({ id: ROOT_ID, threadRootId: ROOT_ID });
|
||||
const liveReply = makeEvent({ id: REPLY_ID, threadRootId: ROOT_ID });
|
||||
const liveReply = makeEvent({
|
||||
id: REPLY_ID,
|
||||
threadRootId: ROOT_ID,
|
||||
relType: RelationType.Thread,
|
||||
relEventId: ROOT_ID,
|
||||
});
|
||||
|
||||
const room = makeRoom({
|
||||
thread: { events: [rootEvent] as any },
|
||||
@@ -115,7 +134,12 @@ describe('getThreadReplyEvents', () => {
|
||||
});
|
||||
|
||||
it('falls back to the live timeline when there is no Thread object at all', () => {
|
||||
const liveReply = makeEvent({ id: REPLY_ID, threadRootId: ROOT_ID });
|
||||
const liveReply = makeEvent({
|
||||
id: REPLY_ID,
|
||||
threadRootId: ROOT_ID,
|
||||
relType: RelationType.Thread,
|
||||
relEventId: ROOT_ID,
|
||||
});
|
||||
|
||||
const room = makeRoom({
|
||||
thread: null,
|
||||
@@ -129,8 +153,18 @@ describe('getThreadReplyEvents', () => {
|
||||
});
|
||||
|
||||
it('excludes events from the live timeline that belong to a different thread', () => {
|
||||
const otherReply = makeEvent({ id: '$other-reply', threadRootId: '$other-root' });
|
||||
const ourReply = makeEvent({ id: REPLY_ID, threadRootId: ROOT_ID });
|
||||
const otherReply = makeEvent({
|
||||
id: '$other-reply',
|
||||
threadRootId: '$other-root',
|
||||
relType: RelationType.Thread,
|
||||
relEventId: '$other-root',
|
||||
});
|
||||
const ourReply = makeEvent({
|
||||
id: REPLY_ID,
|
||||
threadRootId: ROOT_ID,
|
||||
relType: RelationType.Thread,
|
||||
relEventId: ROOT_ID,
|
||||
});
|
||||
|
||||
const room = makeRoom({
|
||||
thread: null,
|
||||
@@ -155,4 +189,25 @@ describe('getThreadReplyEvents', () => {
|
||||
|
||||
expect(result).toHaveLength(0);
|
||||
});
|
||||
|
||||
it('excludes non-thread replies even if the SDK has assigned the same threadRootId', () => {
|
||||
const rootEvent = makeEvent({ id: ROOT_ID, threadRootId: ROOT_ID });
|
||||
const plainReply = makeEvent({ id: '$plain-reply', threadRootId: ROOT_ID });
|
||||
const threadReply = makeEvent({
|
||||
id: REPLY_ID,
|
||||
threadRootId: ROOT_ID,
|
||||
relType: RelationType.Thread,
|
||||
relEventId: ROOT_ID,
|
||||
});
|
||||
|
||||
const room = makeRoom({
|
||||
thread: { events: [rootEvent] as any },
|
||||
liveEvents: [plainReply as any, threadReply as any],
|
||||
});
|
||||
|
||||
const result = getThreadReplyEvents(room as any, ROOT_ID);
|
||||
|
||||
expect(result).toHaveLength(1);
|
||||
expect(result[0]?.getId()).toBe(REPLY_ID);
|
||||
});
|
||||
});
|
||||
@@ -38,6 +38,7 @@ import {
|
||||
import {
|
||||
getEditedEvent,
|
||||
getMemberDisplayName,
|
||||
isThreadRelationEvent,
|
||||
reactionOrEditEvent,
|
||||
unwrapRelationJumpTarget,
|
||||
} from '$utils/room';
|
||||
@@ -93,7 +94,10 @@ export function getThreadReplyEvents(room: Room, threadRootId: string): MatrixEv
|
||||
const thread = room.getThread(threadRootId);
|
||||
const fromThread = thread?.events ?? [];
|
||||
const filteredFromThread = fromThread.filter(
|
||||
(ev) => ev.getId() !== threadRootId && !reactionOrEditEvent(ev)
|
||||
(ev) =>
|
||||
ev.getId() !== threadRootId &&
|
||||
!reactionOrEditEvent(ev) &&
|
||||
isThreadRelationEvent(ev, threadRootId)
|
||||
);
|
||||
if (filteredFromThread.length > 0) {
|
||||
return filteredFromThread;
|
||||
@@ -104,7 +108,9 @@ export function getThreadReplyEvents(room: Room, threadRootId: string): MatrixEv
|
||||
.getEvents()
|
||||
.filter(
|
||||
(ev) =>
|
||||
ev.threadRootId === threadRootId && ev.getId() !== threadRootId && !reactionOrEditEvent(ev)
|
||||
ev.getId() !== threadRootId &&
|
||||
!reactionOrEditEvent(ev) &&
|
||||
isThreadRelationEvent(ev, threadRootId)
|
||||
);
|
||||
}
|
||||
|
||||
@@ -323,7 +329,10 @@ export function ThreadDrawer({ room, threadRootId, onClose, overlay }: ThreadDra
|
||||
// thread.events is still empty (classic sync path; server-side was already
|
||||
// populated by paginateEventTimeline inside updateThreadMetadata).
|
||||
const hasRepliesInThread = currThread.events.some(
|
||||
(ev) => ev.getId() !== threadRootId && !reactionOrEditEvent(ev)
|
||||
(ev) =>
|
||||
ev.getId() !== threadRootId &&
|
||||
!reactionOrEditEvent(ev) &&
|
||||
isThreadRelationEvent(ev, threadRootId)
|
||||
);
|
||||
if (hasRepliesInThread) return;
|
||||
|
||||
@@ -333,9 +342,9 @@ export function ThreadDrawer({ room, threadRootId, onClose, overlay }: ThreadDra
|
||||
.getEvents()
|
||||
.filter(
|
||||
(ev) =>
|
||||
ev.threadRootId === threadRootId &&
|
||||
ev.getId() !== threadRootId &&
|
||||
!reactionOrEditEvent(ev)
|
||||
!reactionOrEditEvent(ev) &&
|
||||
isThreadRelationEvent(ev, threadRootId)
|
||||
);
|
||||
if (liveEvents.length > 0) {
|
||||
// thread.addEvents() is typed as void but is internally async; schedule
|
||||
@@ -360,7 +369,7 @@ export function ThreadDrawer({ room, threadRootId, onClose, overlay }: ThreadDra
|
||||
useEffect(() => {
|
||||
const isEventInThread = (mEvent: MatrixEvent): boolean => {
|
||||
// Direct thread message or the root itself
|
||||
if (mEvent.threadRootId === threadRootId || mEvent.getId() === threadRootId) {
|
||||
if (mEvent.getId() === threadRootId || isThreadRelationEvent(mEvent, threadRootId)) {
|
||||
return true;
|
||||
}
|
||||
|
||||
@@ -372,7 +381,8 @@ export function ThreadDrawer({ room, threadRootId, onClose, overlay }: ThreadDra
|
||||
const targetEvent = room.findEventById(targetEventId);
|
||||
if (
|
||||
targetEvent &&
|
||||
(targetEvent.threadRootId === threadRootId || targetEvent.getId() === threadRootId)
|
||||
(targetEvent.getId() === threadRootId ||
|
||||
isThreadRelationEvent(targetEvent, threadRootId))
|
||||
) {
|
||||
return true;
|
||||
}
|
||||
|
||||
@@ -33,7 +33,13 @@ import {
|
||||
Username,
|
||||
UsernameBold,
|
||||
} from '$components/message';
|
||||
import { canEditEvent, getEditedEvent, getEventEdits, getMemberAvatarMxc } from '$utils/room';
|
||||
import {
|
||||
canEditEvent,
|
||||
getEditedEvent,
|
||||
getEventEdits,
|
||||
getMemberAvatarMxc,
|
||||
isThreadRelationEvent,
|
||||
} from '$utils/room';
|
||||
import { mxcUrlToHttp } from '$utils/matrix';
|
||||
import type { MessageSpacing } from '$state/settings';
|
||||
import { getSettings, MessageLayout, settingsAtom } from '$state/settings';
|
||||
@@ -447,11 +453,12 @@ function MessageInternal(
|
||||
// Avatars
|
||||
// Prefer the room-scoped member avatar (m.room.member) over the global profile
|
||||
// avatar so per-room avatar overrides are respected in the timeline.
|
||||
const memberAvatarMxc = getMemberAvatarMxc(room, senderId);
|
||||
const avatarUrl = useMemo(() => {
|
||||
if (collapse) return undefined;
|
||||
const mxc = pmp?.avatar_url || getMemberAvatarMxc(room, senderId) || profile.avatarUrl;
|
||||
const mxc = pmp?.avatar_url || memberAvatarMxc || profile.avatarUrl;
|
||||
return mxc ? mxcUrlToHttp(mx, mxc, useAuthentication, 48, 48, 'crop') : undefined;
|
||||
}, [pmp, collapse, profile.avatarUrl, senderId, mx, room, useAuthentication]);
|
||||
}, [pmp, collapse, memberAvatarMxc, profile.avatarUrl, mx, useAuthentication]);
|
||||
|
||||
const cachedAvatar = useBlobCache(avatarUrl ?? undefined);
|
||||
|
||||
@@ -839,7 +846,7 @@ function MessageInternal(
|
||||
setMobileOptionsOpen(true);
|
||||
});
|
||||
|
||||
const isThreadedMessage = mEvent.threadRootId !== undefined;
|
||||
const isThreadedMessage = isThreadRelationEvent(mEvent, mEvent.threadRootId);
|
||||
const isStickerMessage = mEvent.getType() === 'm.sticker';
|
||||
|
||||
const evtId = mEvent.getId()!;
|
||||
|
||||
@@ -60,6 +60,10 @@ import type { Opts as LinkifyOpts } from 'linkifyjs';
|
||||
import type { GetContentCallback } from '$types/matrix/room';
|
||||
import { sanitizeText } from '$utils/sanitize';
|
||||
import type { BundleContent } from '$components/message';
|
||||
import {
|
||||
readdAngleBracketsForHiddenPreviews,
|
||||
stripMarkdownEscapesForHiddenPreviews,
|
||||
} from './hiddenLinkPreviews';
|
||||
|
||||
type MessageEditorProps = {
|
||||
roomId: string;
|
||||
@@ -120,6 +124,9 @@ export const MessageEditor = as<'div', MessageEditorProps>(
|
||||
const bundleContent = content['com.beeper.linkpreviews'] as BundleContent[];
|
||||
const markHiddenLinks = (original: string, isHTML?: boolean) => {
|
||||
if (!bundleContent) return original;
|
||||
if (!isHTML) {
|
||||
return readdAngleBracketsForHiddenPreviews(original, bundleContent);
|
||||
}
|
||||
/* Split according to the following fule:
|
||||
- if its not HTML just break it by spaces, newLines, and parans
|
||||
- if it is HTML
|
||||
@@ -129,31 +136,27 @@ export const MessageEditor = as<'div', MessageEditorProps>(
|
||||
- then for every non <a> portion find regular links as though it is plaintext
|
||||
* this is not recursive but needs flattening
|
||||
*/
|
||||
let splitBody = original.split(
|
||||
isHTML ? /(?=^.+<)|(?=<a.+)|(?<=\/a>)|(?=<code.+)|(?<=\/code>)/gi : /(?=[ \n()])/gi
|
||||
);
|
||||
if (isHTML)
|
||||
splitBody = splitBody
|
||||
.map((item) => (item.startsWith('<a') ? [item] : item.split(/(?=[ \n()])/g)))
|
||||
.reduce((acc, current) => acc.concat(current), []);
|
||||
const splitBody = original.split(/(?=^.+<)|(?=<a.+)|(?<=\/a>)|(?=<code.+)|(?<=\/code>)/gi);
|
||||
let newBody = '';
|
||||
splitBody.map((s) => {
|
||||
// the length is from the fact that a link is necessarily longer than 6
|
||||
if (s.length < 6 || s.startsWith('<code') || s.endsWith('code>')) {
|
||||
newBody += s;
|
||||
return;
|
||||
}
|
||||
// since the way that the match works the key is at the start of the string,
|
||||
// it needs to be separated such that it can be reintroduced before the < in case of regular text
|
||||
// or after it in case that it is matching a <a> tag
|
||||
const strippedS = s.substring(1);
|
||||
const isHidden =
|
||||
(bundleContent?.length === 0 ||
|
||||
bundleContent.filter((b) => s.includes(b.matched_url)).length === 0) &&
|
||||
strippedS.match(LINKINPUTREGEX) !== null &&
|
||||
strippedS.startsWith('https://matrix.to/');
|
||||
newBody += `${isHidden ? (isHTML && ((s.startsWith('<a') && `<${s[0]}`) || `${s[0]}<`)) || `${s[0]}<` : s[0]}${strippedS}${isHidden ? (isHTML && '>') || '>' : ''}`;
|
||||
});
|
||||
splitBody
|
||||
.map((item) => (item.startsWith('<a') ? [item] : item.split(/(?=[ \n()])/g)))
|
||||
.reduce((acc, current) => acc.concat(current), [])
|
||||
.map((s) => {
|
||||
// the length is from the fact that a link is necessarily longer than 6
|
||||
if (s.length < 6 || s.startsWith('<code') || s.endsWith('code>')) {
|
||||
newBody += s;
|
||||
return;
|
||||
}
|
||||
// since the way that the match works the key is at the start of the string,
|
||||
// it needs to be separated such that it can be reintroduced before the < in case of regular text
|
||||
// or after it in case that it is matching a <a> tag
|
||||
const strippedS = s.substring(1);
|
||||
const isHidden =
|
||||
(bundleContent?.length === 0 ||
|
||||
bundleContent.filter((b) => s.includes(b.matched_url)).length === 0) &&
|
||||
strippedS.match(LINKINPUTREGEX) !== null;
|
||||
newBody += `${isHidden ? (isHTML && ((s.startsWith('<a') && `<${s[0]}`) || `${s[0]}<`)) || `${s[0]}<` : s[0]}${strippedS}${isHidden ? (isHTML && '>') || '>' : ''}`;
|
||||
});
|
||||
return newBody;
|
||||
};
|
||||
|
||||
@@ -351,7 +354,11 @@ export const MessageEditor = as<'div', MessageEditorProps>(
|
||||
const [body, customHtml] = getPrevBodyAndFormattedBody();
|
||||
|
||||
const initialValue = plainToEditorInput(
|
||||
customHtml ? htmlToMarkdown(customHtml) : typeof body === 'string' ? body : ''
|
||||
customHtml
|
||||
? stripMarkdownEscapesForHiddenPreviews(htmlToMarkdown(customHtml))
|
||||
: typeof body === 'string'
|
||||
? body
|
||||
: ''
|
||||
);
|
||||
|
||||
Transforms.select(editor, {
|
||||
@@ -373,6 +380,14 @@ export const MessageEditor = as<'div', MessageEditorProps>(
|
||||
const settingsLinkBaseUrl = useSettingsLinkBaseUrl();
|
||||
const linkifyOpts = useMemo<LinkifyOpts>(() => ({ ...LINKIFY_OPTS }), []);
|
||||
const spoilerClickHandler = useSpoilerClickHandler();
|
||||
const [incomingInlineImagesDefaultHeight] = useSetting(
|
||||
settingsAtom,
|
||||
'incomingInlineImagesDefaultHeight'
|
||||
);
|
||||
const [incomingInlineImagesMaxHeight] = useSetting(
|
||||
settingsAtom,
|
||||
'incomingInlineImagesMaxHeight'
|
||||
);
|
||||
const htmlReactParserOptions = useMemo<HTMLReactParserOptions>(
|
||||
() =>
|
||||
getReactCustomHtmlParser(mx, mEvent.getRoomId(), {
|
||||
@@ -380,8 +395,19 @@ export const MessageEditor = as<'div', MessageEditorProps>(
|
||||
linkifyOpts,
|
||||
useAuthentication,
|
||||
handleSpoilerClick: spoilerClickHandler,
|
||||
incomingInlineImagesDefaultHeight,
|
||||
incomingInlineImagesMaxHeight,
|
||||
}),
|
||||
[linkifyOpts, mEvent, mx, settingsLinkBaseUrl, spoilerClickHandler, useAuthentication]
|
||||
[
|
||||
linkifyOpts,
|
||||
mEvent,
|
||||
mx,
|
||||
settingsLinkBaseUrl,
|
||||
spoilerClickHandler,
|
||||
useAuthentication,
|
||||
incomingInlineImagesDefaultHeight,
|
||||
incomingInlineImagesMaxHeight,
|
||||
]
|
||||
);
|
||||
const getContent = (() => mEvent.getContent()) as GetContentCallback;
|
||||
const msgType = mEvent.getContent().msgtype;
|
||||
|
||||
@@ -0,0 +1,50 @@
|
||||
import { describe, expect, it } from 'vitest';
|
||||
import {
|
||||
readdAngleBracketsForHiddenPreviews,
|
||||
stripMarkdownEscapesForHiddenPreviews,
|
||||
} from './hiddenLinkPreviews';
|
||||
|
||||
describe('stripMarkdownEscapesForHiddenPreviews', () => {
|
||||
it('removes backslashes around <url> suppressor wrappers', () => {
|
||||
expect(
|
||||
stripMarkdownEscapesForHiddenPreviews(String.raw`hello \<https://example.com\> world`)
|
||||
).toBe('hello <https://example.com> world');
|
||||
});
|
||||
|
||||
it('handles paren-adjacent variants produced by link matching', () => {
|
||||
expect(stripMarkdownEscapesForHiddenPreviews(String.raw`(\<https://a.b\>)`)).toBe(
|
||||
'(<https://a.b>)'
|
||||
);
|
||||
expect(stripMarkdownEscapesForHiddenPreviews(String.raw`(\<https://a.b\>) and more`)).toBe(
|
||||
'(<https://a.b>) and more'
|
||||
);
|
||||
});
|
||||
|
||||
it('does not touch unrelated markdown escapes', () => {
|
||||
expect(stripMarkdownEscapesForHiddenPreviews(String.raw`keep \*this\* and \<not-a-url\>`)).toBe(
|
||||
String.raw`keep \*this\* and \<not-a-url\>`
|
||||
);
|
||||
});
|
||||
});
|
||||
|
||||
describe('readdAngleBracketsForHiddenPreviews', () => {
|
||||
it('wraps URLs in angle brackets when they are not previewed', () => {
|
||||
expect(readdAngleBracketsForHiddenPreviews('see https://example.org/ thanks', [])).toBe(
|
||||
'see <https://example.org/> thanks'
|
||||
);
|
||||
});
|
||||
|
||||
it('does not wrap URLs that are present in link previews', () => {
|
||||
expect(
|
||||
readdAngleBracketsForHiddenPreviews('see https://example.org/ thanks', [
|
||||
{ matched_url: 'https://example.org/' } as never,
|
||||
])
|
||||
).toBe('see https://example.org/ thanks');
|
||||
});
|
||||
|
||||
it('does not double-wrap already bracketed URLs', () => {
|
||||
expect(readdAngleBracketsForHiddenPreviews('see <https://example.org/>', [])).toBe(
|
||||
'see <https://example.org/>'
|
||||
);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,49 @@
|
||||
import type { BundleContent } from '$components/message';
|
||||
|
||||
const LINK_URL = `(https?:\\/\\/.[A-Za-z0-9-._~:/?#[\\]()@!$&'*+,;%=]+)`;
|
||||
const LINKINPUTREGEX = new RegExp(`\\(?(${LINK_URL})\\)?`, 'g');
|
||||
|
||||
/**
|
||||
* `htmlToMarkdown()` escapes `<` and `>` into `\<` and `\>` in text nodes.
|
||||
*
|
||||
* We deliberately inject angle brackets around URLs to suppress link previews. Those backslashes
|
||||
* are correct internally for markdown escaping, but should not be shown to the user when editing.
|
||||
*
|
||||
* This helper removes *only* the backslashes that wrap our `<url>` suppressor pattern.
|
||||
*/
|
||||
export function stripMarkdownEscapesForHiddenPreviews(markdown: string): string {
|
||||
// Handle: \<https://example.com\>
|
||||
// Also handle common surrounding parens: (\<url\>), (\<url), \<url\>)
|
||||
const WRAPPED = new RegExp(String.raw`\\<(${LINK_URL})\\>`, 'g');
|
||||
const OPEN_ONLY = new RegExp(String.raw`\\<(${LINK_URL})`, 'g');
|
||||
const CLOSE_ONLY = new RegExp(String.raw`(${LINK_URL})\\>`, 'g');
|
||||
|
||||
return markdown.replace(WRAPPED, '<$1>').replace(OPEN_ONLY, '<$1').replace(CLOSE_ONLY, '$1>');
|
||||
}
|
||||
|
||||
export function readdAngleBracketsForHiddenPreviews(
|
||||
body: string,
|
||||
linkPreviews: BundleContent[] | undefined
|
||||
): string {
|
||||
if (!linkPreviews) return body;
|
||||
|
||||
const previewed = new Set(linkPreviews.map((b) => b.matched_url));
|
||||
|
||||
LINKINPUTREGEX.lastIndex = 0;
|
||||
return body.replace(LINKINPUTREGEX, (full, url: string, offset: number) => {
|
||||
if (!url || previewed.has(url)) return full;
|
||||
|
||||
// If the URL is already wrapped as <url>, leave it alone.
|
||||
const urlIndex = body.indexOf(url, offset);
|
||||
if (urlIndex !== -1 && body.slice(urlIndex - 1, urlIndex + url.length + 1) === `<${url}>`) {
|
||||
return full;
|
||||
}
|
||||
|
||||
// Keep any surrounding parens emitted by LINKINPUTREGEX.
|
||||
if (full.startsWith('(') && full.endsWith(')')) return `(<${url}>)`;
|
||||
if (full.startsWith('(')) return `(<${url}`;
|
||||
if (full.endsWith(')')) return `<${url}>)`;
|
||||
|
||||
return `<${url}>`;
|
||||
});
|
||||
}
|
||||
@@ -1,5 +1,7 @@
|
||||
import type { MouseEventHandler } from 'react';
|
||||
import { useState } from 'react';
|
||||
import { useAtomValue } from 'jotai';
|
||||
import { serverMaxDelayMsAtom } from '$state/scheduledMessages';
|
||||
import FocusTrap from 'focus-trap-react';
|
||||
import type { RectCords } from 'folds';
|
||||
import {
|
||||
@@ -39,7 +41,9 @@ export function SchedulePickerDialog({
|
||||
onSubmit,
|
||||
}: SchedulePickerDialogProps) {
|
||||
const now = Date.now();
|
||||
const maxDelay = daysToMs(30);
|
||||
const serverMaxDelayMs = useAtomValue(serverMaxDelayMsAtom);
|
||||
const maxDelay = serverMaxDelayMs ?? daysToMs(30);
|
||||
const maxDays = Math.round(maxDelay / daysToMs(1));
|
||||
const defaultTs = initialTime ?? now + hoursToMs(1);
|
||||
const [ts, setTs] = useState(() => Math.max(defaultTs, now + 60000));
|
||||
const [error, setError] = useState<string>();
|
||||
@@ -67,7 +71,7 @@ export function SchedulePickerDialog({
|
||||
return;
|
||||
}
|
||||
if (delay > maxDelay) {
|
||||
setError('Cannot schedule more than 30 days in advance');
|
||||
setError(`Cannot schedule more than ${maxDays} day${maxDays !== 1 ? 's' : ''} in advance`);
|
||||
return;
|
||||
}
|
||||
setError(undefined);
|
||||
|
||||
@@ -25,6 +25,9 @@ type SettingsShape = {
|
||||
autoplayGifs: boolean;
|
||||
autoplayStickers: boolean;
|
||||
autoplayEmojis: boolean;
|
||||
incomingInlineImagesDefaultHeight: number;
|
||||
incomingInlineImagesMaxHeight: number;
|
||||
linkPreviewImageMaxHeight: number;
|
||||
twitterEmoji: boolean;
|
||||
showEasterEggs: boolean;
|
||||
subspaceHierarchyLimit: number;
|
||||
@@ -90,6 +93,9 @@ beforeEach(() => {
|
||||
autoplayGifs: true,
|
||||
autoplayStickers: true,
|
||||
autoplayEmojis: true,
|
||||
incomingInlineImagesDefaultHeight: 32,
|
||||
incomingInlineImagesMaxHeight: 64,
|
||||
linkPreviewImageMaxHeight: 320,
|
||||
twitterEmoji: true,
|
||||
showEasterEggs: true,
|
||||
subspaceHierarchyLimit: 3,
|
||||
|
||||
@@ -39,6 +39,8 @@ import { useShowRoomIcon } from '$hooks/useShowRoomIcon';
|
||||
import type { PanelSizetItem } from '$hooks/usePanelSizes';
|
||||
import { usePanelSizeItems } from '$hooks/usePanelSizes';
|
||||
|
||||
const clampIncomingInlineImageHeight = (n: number) => Math.max(1, Math.min(4096, n));
|
||||
|
||||
function makeArboriumThemeOptions(kind?: 'light' | 'dark') {
|
||||
const themes = kind
|
||||
? getArboriumThemeOptions(kind)
|
||||
@@ -214,6 +216,61 @@ function ThemeVisualPreferences() {
|
||||
const [autoplayGifs, setAutoplayGifs] = useSetting(settingsAtom, 'autoplayGifs');
|
||||
const [autoplayStickers, setAutoplayStickers] = useSetting(settingsAtom, 'autoplayStickers');
|
||||
const [autoplayEmojis, setAutoplayEmojis] = useSetting(settingsAtom, 'autoplayEmojis');
|
||||
const [incomingInlineImagesDefaultHeight, setIncomingInlineImagesDefaultHeight] = useSetting(
|
||||
settingsAtom,
|
||||
'incomingInlineImagesDefaultHeight'
|
||||
);
|
||||
const [incomingInlineImagesMaxHeight, setIncomingInlineImagesMaxHeight] = useSetting(
|
||||
settingsAtom,
|
||||
'incomingInlineImagesMaxHeight'
|
||||
);
|
||||
const [linkPreviewImageMaxHeight, setLinkPreviewImageMaxHeight] = useSetting(
|
||||
settingsAtom,
|
||||
'linkPreviewImageMaxHeight'
|
||||
);
|
||||
const [incomingDefaultHeightInput, setIncomingDefaultHeightInput] = useState(
|
||||
incomingInlineImagesDefaultHeight.toString()
|
||||
);
|
||||
const [incomingMaxHeightInput, setIncomingMaxHeightInput] = useState(
|
||||
incomingInlineImagesMaxHeight.toString()
|
||||
);
|
||||
const [linkPreviewMaxHeightInput, setLinkPreviewMaxHeightInput] = useState(
|
||||
linkPreviewImageMaxHeight.toString()
|
||||
);
|
||||
|
||||
const handleIncomingDefaultHeightChange: ChangeEventHandler<HTMLInputElement> = (evt) => {
|
||||
const val = evt.target.value;
|
||||
setIncomingDefaultHeightInput(val);
|
||||
const parsed = Number.parseInt(val, 10);
|
||||
if (!Number.isNaN(parsed))
|
||||
setIncomingInlineImagesDefaultHeight(clampIncomingInlineImageHeight(parsed));
|
||||
};
|
||||
const handleIncomingMaxHeightChange: ChangeEventHandler<HTMLInputElement> = (evt) => {
|
||||
const val = evt.target.value;
|
||||
setIncomingMaxHeightInput(val);
|
||||
const parsed = Number.parseInt(val, 10);
|
||||
if (!Number.isNaN(parsed))
|
||||
setIncomingInlineImagesMaxHeight(clampIncomingInlineImageHeight(parsed));
|
||||
};
|
||||
const handleLinkPreviewMaxHeightChange: ChangeEventHandler<HTMLInputElement> = (evt) => {
|
||||
const val = evt.target.value;
|
||||
setLinkPreviewMaxHeightInput(val);
|
||||
const parsed = Number.parseInt(val, 10);
|
||||
if (!Number.isNaN(parsed)) setLinkPreviewImageMaxHeight(clampIncomingInlineImageHeight(parsed));
|
||||
};
|
||||
|
||||
const onNumberInputKeyDown =
|
||||
(reset: () => void): KeyboardEventHandler<HTMLInputElement> =>
|
||||
(evt) => {
|
||||
if (isKeyHotkey('escape', evt)) {
|
||||
evt.stopPropagation();
|
||||
reset();
|
||||
(evt.target as HTMLInputElement).blur();
|
||||
}
|
||||
if (isKeyHotkey('enter', evt)) {
|
||||
(evt.target as HTMLInputElement).blur();
|
||||
}
|
||||
};
|
||||
|
||||
return (
|
||||
<Box direction="Column" gap="100">
|
||||
@@ -287,6 +344,97 @@ function ThemeVisualPreferences() {
|
||||
after={<Switch variant="Primary" value={autoplayEmojis} onChange={setAutoplayEmojis} />}
|
||||
/>
|
||||
</SequenceCard>
|
||||
|
||||
<SequenceCard className={SequenceCardStyle} variant="SurfaceVariant" direction="Column">
|
||||
<SettingTile
|
||||
title="Incoming inline images default height"
|
||||
focusId="incoming-inline-images-default-height"
|
||||
description={`Default height for incoming inline images that don't specify a height.`}
|
||||
after={
|
||||
<Input
|
||||
style={{ width: toRem(100) }}
|
||||
variant={
|
||||
Number.parseInt(incomingDefaultHeightInput, 10) ===
|
||||
incomingInlineImagesDefaultHeight
|
||||
? 'Secondary'
|
||||
: 'Success'
|
||||
}
|
||||
size="300"
|
||||
radii="300"
|
||||
type="number"
|
||||
min="1"
|
||||
max="4096"
|
||||
value={incomingDefaultHeightInput}
|
||||
onChange={handleIncomingDefaultHeightChange}
|
||||
onKeyDown={onNumberInputKeyDown(() =>
|
||||
setIncomingDefaultHeightInput(incomingInlineImagesDefaultHeight.toString())
|
||||
)}
|
||||
after={<Text size="T300">px</Text>}
|
||||
outlined
|
||||
/>
|
||||
}
|
||||
/>
|
||||
</SequenceCard>
|
||||
|
||||
<SequenceCard className={SequenceCardStyle} variant="SurfaceVariant" direction="Column">
|
||||
<SettingTile
|
||||
title="Incoming inline images max height"
|
||||
focusId="incoming-inline-images-max-height"
|
||||
description={`Maximum height for incoming inline images. Any incoming height above this is clamped down.`}
|
||||
after={
|
||||
<Input
|
||||
style={{ width: toRem(100) }}
|
||||
variant={
|
||||
Number.parseInt(incomingMaxHeightInput, 10) === incomingInlineImagesMaxHeight
|
||||
? 'Secondary'
|
||||
: 'Success'
|
||||
}
|
||||
size="300"
|
||||
radii="300"
|
||||
type="number"
|
||||
min="1"
|
||||
max="4096"
|
||||
value={incomingMaxHeightInput}
|
||||
onChange={handleIncomingMaxHeightChange}
|
||||
onKeyDown={onNumberInputKeyDown(() =>
|
||||
setIncomingMaxHeightInput(incomingInlineImagesMaxHeight.toString())
|
||||
)}
|
||||
after={<Text size="T300">px</Text>}
|
||||
outlined
|
||||
/>
|
||||
}
|
||||
/>
|
||||
</SequenceCard>
|
||||
|
||||
<SequenceCard className={SequenceCardStyle} variant="SurfaceVariant" direction="Column">
|
||||
<SettingTile
|
||||
title="Link preview image max height"
|
||||
focusId="link-preview-image-max-height"
|
||||
description="Maximum height for URL / Open Graph preview media (image or playable og:video), including bundled previews."
|
||||
after={
|
||||
<Input
|
||||
style={{ width: toRem(100) }}
|
||||
variant={
|
||||
Number.parseInt(linkPreviewMaxHeightInput, 10) === linkPreviewImageMaxHeight
|
||||
? 'Secondary'
|
||||
: 'Success'
|
||||
}
|
||||
size="300"
|
||||
radii="300"
|
||||
type="number"
|
||||
min="1"
|
||||
max="4096"
|
||||
value={linkPreviewMaxHeightInput}
|
||||
onChange={handleLinkPreviewMaxHeightChange}
|
||||
onKeyDown={onNumberInputKeyDown(() =>
|
||||
setLinkPreviewMaxHeightInput(linkPreviewImageMaxHeight.toString())
|
||||
)}
|
||||
after={<Text size="T300">px</Text>}
|
||||
outlined
|
||||
/>
|
||||
}
|
||||
/>
|
||||
</SequenceCard>
|
||||
</Box>
|
||||
);
|
||||
}
|
||||
|
||||
@@ -34,6 +34,12 @@ describe('settingsLink', () => {
|
||||
'https://app.example/settings/appearance/?focus=message-link-preview'
|
||||
)
|
||||
).toEqual({ section: 'appearance', focus: 'message-link-preview' });
|
||||
expect(
|
||||
parseSettingsLink(
|
||||
'https://app.example',
|
||||
`https://app.example/settings/general?focus=composer-formatting-toolbar&${SETTINGS_LINK_ACTION_PARAM}=${SETTINGS_LINK_ACTION_SETTINGS}`
|
||||
)
|
||||
).toEqual({ section: 'general', focus: 'composer-formatting-toolbar' });
|
||||
expect(
|
||||
parseSettingsLink(
|
||||
'https://app.example',
|
||||
@@ -44,6 +50,36 @@ describe('settingsLink', () => {
|
||||
expect(parseSettingsLink('https://app.example', 'https://app.example/home/')).toBeUndefined();
|
||||
});
|
||||
|
||||
it('accepts the incoming inline image height focus ids', () => {
|
||||
expect(
|
||||
parseSettingsLink(
|
||||
'https://app.example',
|
||||
'https://app.example/settings/appearance?focus=incoming-inline-images-default-height'
|
||||
)
|
||||
).toEqual({
|
||||
section: 'appearance',
|
||||
focus: 'incoming-inline-images-default-height',
|
||||
});
|
||||
expect(
|
||||
parseSettingsLink(
|
||||
'https://app.example',
|
||||
'https://app.example/settings/appearance?focus=incoming-inline-images-max-height'
|
||||
)
|
||||
).toEqual({
|
||||
section: 'appearance',
|
||||
focus: 'incoming-inline-images-max-height',
|
||||
});
|
||||
expect(
|
||||
parseSettingsLink(
|
||||
'https://app.example',
|
||||
'https://app.example/settings/appearance?focus=link-preview-image-max-height'
|
||||
)
|
||||
).toEqual({
|
||||
section: 'appearance',
|
||||
focus: 'link-preview-image-max-height',
|
||||
});
|
||||
});
|
||||
|
||||
it('parses cross-base settings links only when the explicit action marker is present', () => {
|
||||
expect(
|
||||
parseSettingsLink(
|
||||
|
||||
@@ -18,10 +18,12 @@ const settingsSectionLabel = Object.fromEntries(
|
||||
const settingsLinkFocusIdsBySection: Record<SettingsSectionId, readonly string[]> = {
|
||||
general: [
|
||||
'client-side-embeds',
|
||||
'composer-formatting-toolbar',
|
||||
'custom-date-format',
|
||||
'date-format',
|
||||
'disable-media-auto-load',
|
||||
'display-bundled-embeds',
|
||||
'display-multiple-embeds',
|
||||
'embed-youtube-links',
|
||||
'emoji-selector-threshold',
|
||||
'enable-swiping',
|
||||
@@ -62,6 +64,7 @@ const settingsLinkFocusIdsBySection: Record<SettingsSectionId, readonly string[]
|
||||
'email-address',
|
||||
'has-cats',
|
||||
'is-cat',
|
||||
'user-hero-color',
|
||||
'matrix-id',
|
||||
'name-color',
|
||||
'name-color-dark-theme',
|
||||
@@ -86,13 +89,24 @@ const settingsLinkFocusIdsBySection: Record<SettingsSectionId, readonly string[]
|
||||
'collapse-folders-by-default',
|
||||
'colorful-names',
|
||||
'consistent-icon-style',
|
||||
'browse-remote-catalog',
|
||||
'customize-dm-cards',
|
||||
'custom-profile-cards',
|
||||
'dark-theme',
|
||||
'jumbo-emoji-size',
|
||||
'light-theme',
|
||||
'manual-theme',
|
||||
'message-link-preview',
|
||||
'page-zoom',
|
||||
'catalog-themes',
|
||||
'catalog-tweaks',
|
||||
'theme-browse-remote',
|
||||
'theme-catalog-clear-remote',
|
||||
'theme-chat-sable-widgets',
|
||||
'theme-chat-auto-approved',
|
||||
'theme-chat-auto-any',
|
||||
'theme-import-open',
|
||||
'theme-local-sync-system',
|
||||
'pronoun-pills-for-all',
|
||||
'reduced-motion',
|
||||
'render-global-username-colors',
|
||||
@@ -109,6 +123,9 @@ const settingsLinkFocusIdsBySection: Record<SettingsSectionId, readonly string[]
|
||||
'underline-links',
|
||||
'show-room-icons',
|
||||
'sidebar-size',
|
||||
'incoming-inline-images-default-height',
|
||||
'incoming-inline-images-max-height',
|
||||
'link-preview-image-max-height',
|
||||
],
|
||||
notifications: [
|
||||
'background-push-notifications',
|
||||
|
||||
@@ -5,7 +5,7 @@ import {
|
||||
getTimelineRelativeIndex,
|
||||
getTimelineEvent,
|
||||
} from '$utils/timeline';
|
||||
import { reactionOrEditEvent, isMembershipChanged } from '$utils/room';
|
||||
import { isMembershipChanged, isThreadRelationEvent, reactionOrEditEvent } from '$utils/room';
|
||||
import { inSameDay, minuteDifference } from '$utils/time';
|
||||
|
||||
export interface UseProcessedTimelineOptions {
|
||||
@@ -132,7 +132,13 @@ export function useProcessedTimeline({
|
||||
}
|
||||
}
|
||||
|
||||
if (!skipThreadFilter && threadRootId !== undefined && threadRootId !== mEventId) return acc;
|
||||
if (
|
||||
!skipThreadFilter &&
|
||||
threadRootId !== undefined &&
|
||||
threadRootId !== mEventId &&
|
||||
isThreadRelationEvent(mEvent, threadRootId)
|
||||
)
|
||||
return acc;
|
||||
|
||||
const isReactionOrEdit = reactionOrEditEvent(mEvent);
|
||||
if (isReactionOrEdit) return acc;
|
||||
|
||||
@@ -47,6 +47,7 @@ import {
|
||||
getEventReactions,
|
||||
getMemberDisplayName,
|
||||
isMembershipChanged,
|
||||
isThreadRelationEvent,
|
||||
reactionOrEditEvent,
|
||||
getMemberAvatarMxc,
|
||||
} from '$utils/room';
|
||||
@@ -130,7 +131,8 @@ function ThreadReplyChip({
|
||||
// Prefer thread.events when available so avatars and preview text are populated.
|
||||
if (thread) {
|
||||
const fromThread = thread.events.filter(
|
||||
(ev) => ev.getId() !== mEventId && !reactionOrEditEvent(ev)
|
||||
(ev) =>
|
||||
ev.getId() !== mEventId && !reactionOrEditEvent(ev) && isThreadRelationEvent(ev, mEventId)
|
||||
);
|
||||
if (fromThread.length > 0) return fromThread;
|
||||
}
|
||||
@@ -138,7 +140,8 @@ function ThreadReplyChip({
|
||||
return linkedTimelines
|
||||
.flatMap((tl) => tl.getEvents())
|
||||
.filter(
|
||||
(ev) => ev.threadRootId === mEventId && ev.getId() !== mEventId && !reactionOrEditEvent(ev)
|
||||
(ev) =>
|
||||
ev.getId() !== mEventId && !reactionOrEditEvent(ev) && isThreadRelationEvent(ev, mEventId)
|
||||
);
|
||||
}, [room, mEventId, thread, counter]);
|
||||
|
||||
@@ -354,12 +357,18 @@ export function useTimelineEventRenderer({
|
||||
{
|
||||
[EventType.RoomMessage]: (mEventId, mEvent, item, timelineSet, collapse) => {
|
||||
const { replyEventId: rawReplyEventId, threadRootId } = mEvent;
|
||||
const isThreadRel = isThreadRelationEvent(mEvent, threadRootId);
|
||||
const actualThreadRootId = isThreadRel ? threadRootId : undefined;
|
||||
const explicitInReplyTo = mEvent.getWireContent()?.['m.relates_to']?.['m.in_reply_to']
|
||||
?.event_id as unknown;
|
||||
const threadReplyTargetId =
|
||||
isThreadRel && typeof explicitInReplyTo === 'string' ? explicitInReplyTo : undefined;
|
||||
// In the thread drawer (hideThreadChip=true), suppress reply headers for events
|
||||
// that only have m.in_reply_to as a non-thread-client fallback (is_falling_back: true).
|
||||
const replyEventId =
|
||||
hideThreadChip && mEvent.getWireContent()?.['m.relates_to']?.is_falling_back
|
||||
? undefined
|
||||
: rawReplyEventId;
|
||||
: (threadReplyTargetId ?? rawReplyEventId);
|
||||
|
||||
const reactionRelations = getEventReactions(timelineSet, mEventId);
|
||||
const reactions = reactionRelations?.getSortedAnnotationsByKey();
|
||||
@@ -446,7 +455,7 @@ export function useTimelineEventRenderer({
|
||||
room={room}
|
||||
timelineSet={timelineSet}
|
||||
replyEventId={replyEventId}
|
||||
threadRootId={hideThreadChip ? undefined : threadRootId}
|
||||
threadRootId={hideThreadChip ? undefined : actualThreadRootId}
|
||||
mentions={baseContent['m.mentions']}
|
||||
onClick={handleOpenReply}
|
||||
/>
|
||||
@@ -509,10 +518,16 @@ export function useTimelineEventRenderer({
|
||||
},
|
||||
[EventType.RoomMessageEncrypted]: (mEventId, mEvent, item, timelineSet, collapse) => {
|
||||
const { replyEventId: rawReplyEventId, threadRootId } = mEvent;
|
||||
const isThreadRel = isThreadRelationEvent(mEvent, threadRootId);
|
||||
const actualThreadRootId = isThreadRel ? threadRootId : undefined;
|
||||
const explicitInReplyTo = mEvent.getWireContent()?.['m.relates_to']?.['m.in_reply_to']
|
||||
?.event_id as unknown;
|
||||
const threadReplyTargetId =
|
||||
isThreadRel && typeof explicitInReplyTo === 'string' ? explicitInReplyTo : undefined;
|
||||
const replyEventId =
|
||||
hideThreadChip && mEvent.getWireContent()?.['m.relates_to']?.is_falling_back
|
||||
? undefined
|
||||
: rawReplyEventId;
|
||||
: (threadReplyTargetId ?? rawReplyEventId);
|
||||
|
||||
const reactionRelations = getEventReactions(timelineSet, mEventId);
|
||||
const reactions = reactionRelations?.getSortedAnnotationsByKey();
|
||||
@@ -563,7 +578,7 @@ export function useTimelineEventRenderer({
|
||||
room={room}
|
||||
timelineSet={timelineSet}
|
||||
replyEventId={replyEventId}
|
||||
threadRootId={hideThreadChip ? undefined : threadRootId}
|
||||
threadRootId={hideThreadChip ? undefined : actualThreadRootId}
|
||||
onClick={handleOpenReply}
|
||||
/>
|
||||
)
|
||||
@@ -673,10 +688,16 @@ export function useTimelineEventRenderer({
|
||||
},
|
||||
[EventType.Sticker]: (mEventId, mEvent, item, timelineSet, collapse) => {
|
||||
const { replyEventId: rawReplyEventId, threadRootId } = mEvent;
|
||||
const isThreadRel = isThreadRelationEvent(mEvent, threadRootId);
|
||||
const actualThreadRootId = isThreadRel ? threadRootId : undefined;
|
||||
const explicitInReplyTo = mEvent.getWireContent()?.['m.relates_to']?.['m.in_reply_to']
|
||||
?.event_id as unknown;
|
||||
const threadReplyTargetId =
|
||||
isThreadRel && typeof explicitInReplyTo === 'string' ? explicitInReplyTo : undefined;
|
||||
const replyEventId =
|
||||
hideThreadChip && mEvent.getWireContent()?.['m.relates_to']?.is_falling_back
|
||||
? undefined
|
||||
: rawReplyEventId;
|
||||
: (threadReplyTargetId ?? rawReplyEventId);
|
||||
|
||||
const reactionRelations = getEventReactions(timelineSet, mEventId);
|
||||
const reactions = reactionRelations?.getSortedAnnotationsByKey();
|
||||
@@ -719,7 +740,7 @@ export function useTimelineEventRenderer({
|
||||
room={room}
|
||||
timelineSet={timelineSet}
|
||||
replyEventId={replyEventId}
|
||||
threadRootId={hideThreadChip ? undefined : threadRootId}
|
||||
threadRootId={hideThreadChip ? undefined : actualThreadRootId}
|
||||
mentions={content['m.mentions']}
|
||||
onClick={handleOpenReply}
|
||||
/>
|
||||
|
||||
@@ -1,5 +1,7 @@
|
||||
import { createContext, useContext } from 'react';
|
||||
|
||||
import type { Settings } from '$state/settings';
|
||||
|
||||
export type HashRouterConfig = {
|
||||
enabled?: boolean;
|
||||
basename?: string;
|
||||
@@ -46,6 +48,8 @@ export type ClientConfig = {
|
||||
themeCatalogBaseUrl?: string;
|
||||
themeCatalogManifestUrl?: string;
|
||||
themeCatalogApprovedHostPrefixes?: string[];
|
||||
|
||||
settingsDefaults?: Partial<Settings>;
|
||||
};
|
||||
|
||||
const ClientConfigContext = createContext<ClientConfig | null>(null);
|
||||
|
||||
@@ -639,21 +639,34 @@ export const useCommands = (mx: MatrixClient, room: Room): CommandRecord => {
|
||||
name: Command.MyRoomAvatar,
|
||||
description: 'Change profile picture in current room. Example /myroomavatar mxc://xyzabc',
|
||||
exe: async (payload) => {
|
||||
let newAvatar: string | undefined = payload.trim();
|
||||
if (newAvatar.length === 0) {
|
||||
// no avatar, reset to global
|
||||
newAvatar = profile.avatarUrl;
|
||||
} else if (!newAvatar.match(/^mxc:\/\/\S+$/)) {
|
||||
// bad mxc
|
||||
return;
|
||||
}
|
||||
const trimmed = payload.trim();
|
||||
const isRemove = trimmed.length === 0;
|
||||
const mEvent = room
|
||||
.getLiveTimeline()
|
||||
.getState(EventTimeline.FORWARDS)
|
||||
?.getStateEvents(EventType.RoomMember, mx.getSafeUserId());
|
||||
const content = mEvent?.getContent<RoomMemberEventContent>();
|
||||
if (!content) return;
|
||||
await mx.sendStateEvent(room.roomId, EventType.RoomMember, content, mx.getSafeUserId());
|
||||
const updatedContent: RoomMemberEventContent = { ...content };
|
||||
if (isRemove) {
|
||||
// Reset to global avatar
|
||||
const globalAvatar = mx.getUser(mx.getSafeUserId())?.avatarUrl ?? undefined;
|
||||
(updatedContent as RoomMemberEventContent & { avatar_url?: string }).avatar_url =
|
||||
globalAvatar;
|
||||
} else {
|
||||
if (!trimmed.match(/^mxc:\/\/\S+$/)) {
|
||||
// bad mxc
|
||||
return;
|
||||
}
|
||||
(updatedContent as RoomMemberEventContent & { avatar_url?: string }).avatar_url =
|
||||
trimmed;
|
||||
}
|
||||
await mx.sendStateEvent(
|
||||
room.roomId,
|
||||
EventType.RoomMember,
|
||||
updatedContent,
|
||||
mx.getSafeUserId()
|
||||
);
|
||||
},
|
||||
},
|
||||
[Command.ConvertToDm]: {
|
||||
@@ -1595,7 +1608,6 @@ export const useCommands = (mx: MatrixClient, room: Room): CommandRecord => {
|
||||
navigateRoom,
|
||||
room,
|
||||
profile.displayName,
|
||||
profile.avatarUrl,
|
||||
pkitcmdHandler,
|
||||
developerTools,
|
||||
enableMSC4268CMD,
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
import type { MatrixClient, MatrixEvent, RoomMember } from '$types/matrix-sdk';
|
||||
import { RoomMemberEvent } from '$types/matrix-sdk';
|
||||
import { EventType, RoomMemberEvent, RoomStateEvent } from '$types/matrix-sdk';
|
||||
import { useEffect, useState } from 'react';
|
||||
|
||||
export const useRoomMembers = (mx: MatrixClient, roomId: string): RoomMember[] => {
|
||||
@@ -25,12 +25,20 @@ export const useRoomMembers = (mx: MatrixClient, roomId: string): RoomMember[] =
|
||||
});
|
||||
}
|
||||
|
||||
const handleStateEvent = (event: MatrixEvent) => {
|
||||
if (event.getRoomId() !== roomId) return;
|
||||
if (event.getType() !== (EventType.RoomMember as string)) return;
|
||||
updateMemberList(event);
|
||||
};
|
||||
|
||||
mx.on(RoomMemberEvent.Membership, updateMemberList);
|
||||
mx.on(RoomMemberEvent.PowerLevel, updateMemberList);
|
||||
mx.on(RoomStateEvent.Events, handleStateEvent);
|
||||
return () => {
|
||||
disposed = true;
|
||||
mx.removeListener(RoomMemberEvent.Membership, updateMemberList);
|
||||
mx.removeListener(RoomMemberEvent.PowerLevel, updateMemberList);
|
||||
mx.removeListener(RoomStateEvent.Events, handleStateEvent);
|
||||
};
|
||||
}, [mx, roomId]);
|
||||
|
||||
|
||||
@@ -1,7 +1,9 @@
|
||||
import { useAtomValue } from 'jotai';
|
||||
import { useEffect, useState } from 'react';
|
||||
import type { RoomJoinRulesEventContent, Room } from '$types/matrix-sdk';
|
||||
import { RoomEvent, RoomStateEvent, EventType } from '$types/matrix-sdk';
|
||||
|
||||
import { mDirectAtom } from '$state/mDirectList';
|
||||
import { useStateEvent } from './useStateEvent';
|
||||
import { useNickname } from './useNickname';
|
||||
|
||||
@@ -20,6 +22,8 @@ export const useRoomAvatar = (room: Room, dm?: boolean): string | undefined => {
|
||||
export const useRoomName = (room: Room): string => {
|
||||
const dmUserId = room.guessDMUserId();
|
||||
const dmNickname = useNickname(dmUserId || '');
|
||||
const mDirects = useAtomValue(mDirectAtom);
|
||||
const isDmTagged = mDirects.has(room.roomId);
|
||||
const [name, setName] = useState(room.name);
|
||||
|
||||
useEffect(() => {
|
||||
@@ -28,11 +32,7 @@ export const useRoomName = (room: Room): string => {
|
||||
room.recalculate();
|
||||
}
|
||||
|
||||
// small room = dm i promise trust
|
||||
const memberCount = room.getJoinedMemberCount();
|
||||
const isSmallRoom = memberCount <= 2;
|
||||
|
||||
const nextName = isSmallRoom && dmNickname ? dmNickname : room.name;
|
||||
const nextName = isDmTagged && dmNickname ? dmNickname : room.name;
|
||||
setName((prev) => (prev !== nextName ? nextName : prev));
|
||||
};
|
||||
|
||||
@@ -45,7 +45,7 @@ export const useRoomName = (room: Room): string => {
|
||||
room.removeListener(RoomEvent.Name, updateName);
|
||||
room.removeListener(RoomStateEvent.Members, updateName);
|
||||
};
|
||||
}, [room, dmNickname]);
|
||||
}, [room, dmNickname, isDmTagged]);
|
||||
|
||||
return name;
|
||||
};
|
||||
|
||||
@@ -4,12 +4,22 @@ import { TYPING_TIMEOUT_MS } from '$state/typingMembers';
|
||||
|
||||
type TypingStatusUpdater = (typing: boolean) => void;
|
||||
|
||||
export const useTypingStatusUpdater = (mx: MatrixClient, roomId: string): TypingStatusUpdater => {
|
||||
type TypingStatusUpdaterOptions = {
|
||||
disabled?: boolean;
|
||||
};
|
||||
|
||||
export const useTypingStatusUpdater = (
|
||||
mx: MatrixClient,
|
||||
roomId: string,
|
||||
options?: TypingStatusUpdaterOptions
|
||||
): TypingStatusUpdater => {
|
||||
const statusSentTsRef = useRef(0);
|
||||
const disabled = options?.disabled ?? false;
|
||||
|
||||
const sendTypingStatus: TypingStatusUpdater = useMemo(() => {
|
||||
statusSentTsRef.current = 0;
|
||||
return (typing) => {
|
||||
if (disabled) return;
|
||||
if (typing) {
|
||||
if (Date.now() - statusSentTsRef.current < TYPING_TIMEOUT_MS) {
|
||||
return;
|
||||
@@ -35,7 +45,7 @@ export const useTypingStatusUpdater = (mx: MatrixClient, roomId: string): Typing
|
||||
}
|
||||
statusSentTsRef.current = 0;
|
||||
};
|
||||
}, [mx, roomId]);
|
||||
}, [mx, roomId, disabled]);
|
||||
|
||||
return sendTypingStatus;
|
||||
};
|
||||
+35
-15
@@ -1,13 +1,16 @@
|
||||
import { lazy, Suspense } from 'react';
|
||||
import { lazy, Suspense, useRef } from 'react';
|
||||
import { Provider as JotaiProvider } from 'jotai';
|
||||
import { createStore } from 'jotai/vanilla';
|
||||
import { OverlayContainerProvider, PopOutContainerProvider, TooltipContainerProvider } from 'folds';
|
||||
import { RouterProvider } from 'react-router-dom';
|
||||
import { QueryClient, QueryClientProvider } from '@tanstack/react-query';
|
||||
import * as Sentry from '@sentry/react';
|
||||
|
||||
import { ClientConfigLoader } from '$components/ClientConfigLoader';
|
||||
import type { ClientConfig } from '$hooks/useClientConfig';
|
||||
import { ClientConfigProvider } from '$hooks/useClientConfig';
|
||||
import { setMatrixToBase } from '$plugins/matrix-to';
|
||||
import type { ScreenSize } from '$hooks/useScreenSize';
|
||||
import { ScreenSizeProvider, useScreenSize } from '$hooks/useScreenSize';
|
||||
import { useCompositionEndTracking } from '$hooks/useComposingCheck';
|
||||
import { ErrorPage } from '$components/DefaultErrorPage';
|
||||
@@ -15,6 +18,7 @@ import { ConfigConfigError, ConfigConfigLoading } from './ConfigConfig';
|
||||
import { FeatureCheck } from './FeatureCheck';
|
||||
import { createRouter } from './Router';
|
||||
import { isReactQueryDevtoolsEnabled } from './reactQueryDevtoolsGate';
|
||||
import { bootstrapSettingsStore } from '$state/settings';
|
||||
|
||||
const queryClient = new QueryClient();
|
||||
const ReactQueryDevtools = lazy(async () => {
|
||||
@@ -23,11 +27,38 @@ const ReactQueryDevtools = lazy(async () => {
|
||||
return { default: Devtools };
|
||||
});
|
||||
|
||||
type BootstrappedAppShellProps = {
|
||||
clientConfig: ClientConfig;
|
||||
screenSize: ScreenSize;
|
||||
};
|
||||
|
||||
function BootstrappedAppShell({ clientConfig, screenSize }: BootstrappedAppShellProps) {
|
||||
const jotaiStoreRef = useRef<ReturnType<typeof createStore>>();
|
||||
if (!jotaiStoreRef.current) {
|
||||
jotaiStoreRef.current = createStore();
|
||||
}
|
||||
bootstrapSettingsStore(jotaiStoreRef.current, clientConfig.settingsDefaults);
|
||||
const reactQueryDevtoolsEnabled = isReactQueryDevtoolsEnabled();
|
||||
|
||||
return (
|
||||
<ClientConfigProvider value={clientConfig}>
|
||||
<QueryClientProvider client={queryClient}>
|
||||
<JotaiProvider store={jotaiStoreRef.current}>
|
||||
<RouterProvider router={createRouter(clientConfig, screenSize)} />
|
||||
</JotaiProvider>
|
||||
{reactQueryDevtoolsEnabled && (
|
||||
<Suspense fallback={null}>
|
||||
<ReactQueryDevtools initialIsOpen={false} />
|
||||
</Suspense>
|
||||
)}
|
||||
</QueryClientProvider>
|
||||
</ClientConfigProvider>
|
||||
);
|
||||
}
|
||||
|
||||
function App() {
|
||||
const screenSize = useScreenSize();
|
||||
useCompositionEndTracking();
|
||||
const reactQueryDevtoolsEnabled = isReactQueryDevtoolsEnabled();
|
||||
|
||||
const portalContainer = document.getElementById('portalContainer') ?? undefined;
|
||||
|
||||
return (
|
||||
@@ -53,18 +84,7 @@ function App() {
|
||||
{(clientConfig) => {
|
||||
setMatrixToBase(clientConfig.matrixToBaseUrl);
|
||||
return (
|
||||
<ClientConfigProvider value={clientConfig}>
|
||||
<QueryClientProvider client={queryClient}>
|
||||
<JotaiProvider>
|
||||
<RouterProvider router={createRouter(clientConfig, screenSize)} />
|
||||
</JotaiProvider>
|
||||
{reactQueryDevtoolsEnabled && (
|
||||
<Suspense fallback={null}>
|
||||
<ReactQueryDevtools initialIsOpen={false} />
|
||||
</Suspense>
|
||||
)}
|
||||
</QueryClientProvider>
|
||||
</ClientConfigProvider>
|
||||
<BootstrappedAppShell clientConfig={clientConfig} screenSize={screenSize} />
|
||||
);
|
||||
}}
|
||||
</ClientConfigLoader>
|
||||
|
||||
@@ -107,6 +107,16 @@ describe('bidirectional round-trip', () => {
|
||||
expect(result).toContain('||hidden message||');
|
||||
});
|
||||
|
||||
it('round-trips literal line-start -# (escaped) in a paragraph', () => {
|
||||
const markdown = '\\-# not small text';
|
||||
const html = markdownToHtml(markdown);
|
||||
expect(html).not.toContain('<sub');
|
||||
const injected = injectDataMd(html);
|
||||
const result = htmlToMarkdown(injected);
|
||||
expect(result).toContain('\\-#');
|
||||
expect(result).toContain('not small text');
|
||||
});
|
||||
|
||||
it('round-trips inline math', () => {
|
||||
const markdown = '$E = mc^2$';
|
||||
const html = markdownToHtml(markdown);
|
||||
|
||||
@@ -1,8 +1,24 @@
|
||||
import type { TokenizerExtension, RendererExtension } from 'marked';
|
||||
|
||||
/** Private-use char so math extensions do not match `$` / `$$` inside code spans. Not U+E000–U+E002 (emoticon placeholders). */
|
||||
/** Private-use char so math extensions do not match `$` / `$$` inside code spans. Not U+E000–U+E002 (emoticon placeholders). {@link shieldDollarRunsForMarked} uses U+E021–U+E022. */
|
||||
export const MATH_CODE_DOLLAR_MASK = '\uE020';
|
||||
|
||||
/**
|
||||
* Replaces the `-` of line-start `-# …` inside markdown code so the Matrix subscript block
|
||||
* extension does not match before marked's `fences` rule (custom block extensions run first).
|
||||
* {@link unmaskSubscriptCodeLinePlaceholders} restores output HTML.
|
||||
*/
|
||||
export const SUBSCRIPT_CODE_LINE_MASK = '\uE023';
|
||||
|
||||
function maskSubscriptLineStartsInCodeInner(inner: string): string {
|
||||
return inner.replace(/(^|\n)-#( +)/g, `$1${SUBSCRIPT_CODE_LINE_MASK}#$2`);
|
||||
}
|
||||
|
||||
/** Applies {@link MATH_CODE_DOLLAR_MASK} and subscript masking inside a fence or inline-code region. */
|
||||
function maskMathAndSubscriptInCodeInner(inner: string): string {
|
||||
return maskSubscriptLineStartsInCodeInner(inner.replace(/\$/g, MATH_CODE_DOLLAR_MASK));
|
||||
}
|
||||
|
||||
function findSameLineFenceClose(md: string, from: number, tick: string, minLen: number): number {
|
||||
let j = from;
|
||||
while (j < md.length && md[j] !== '\n') {
|
||||
@@ -62,11 +78,11 @@ function tryConsumeFence(md: string, i: number): { text: string; end: number } |
|
||||
const close = findMultilineFenceEnd(md, contentStart, tick, openLen);
|
||||
if (!close) {
|
||||
const inner = md.slice(contentStart, md.length);
|
||||
const masked = inner.replace(/\$/g, MATH_CODE_DOLLAR_MASK);
|
||||
const masked = maskMathAndSubscriptInCodeInner(inner);
|
||||
return { text: md.slice(i, contentStart) + masked, end: md.length };
|
||||
}
|
||||
const inner = md.slice(contentStart, close.contentEnd);
|
||||
const maskedInner = inner.replace(/\$/g, MATH_CODE_DOLLAR_MASK);
|
||||
const maskedInner = maskMathAndSubscriptInCodeInner(inner);
|
||||
return {
|
||||
text: md.slice(i, contentStart) + maskedInner + md.slice(close.contentEnd, close.blockEnd),
|
||||
end: close.blockEnd,
|
||||
@@ -80,7 +96,7 @@ function tryConsumeFence(md: string, i: number): { text: string; end: number } |
|
||||
while (closeIdx + closeRun < md.length && md[closeIdx + closeRun] === tick) closeRun++;
|
||||
|
||||
const inner = md.slice(afterOpen, closeIdx);
|
||||
const maskedInner = inner.replace(/\$/g, MATH_CODE_DOLLAR_MASK);
|
||||
const maskedInner = maskMathAndSubscriptInCodeInner(inner);
|
||||
return {
|
||||
text: md.slice(i, afterOpen) + maskedInner + md.slice(closeIdx, closeIdx + closeRun),
|
||||
end: closeIdx + closeRun,
|
||||
@@ -99,7 +115,7 @@ function tryConsumeInlineCode(md: string, i: number): { text: string; end: numbe
|
||||
while (j + cr < md.length && md[j + cr] === '`') cr++;
|
||||
if (cr === run) {
|
||||
const inner = md.slice(contentStart, j);
|
||||
const maskedInner = inner.replace(/\$/g, MATH_CODE_DOLLAR_MASK);
|
||||
const maskedInner = maskMathAndSubscriptInCodeInner(inner);
|
||||
return {
|
||||
text: md.slice(i, contentStart) + maskedInner + md.slice(j, j + run),
|
||||
end: j + run,
|
||||
@@ -155,6 +171,35 @@ export function unmaskMathCodeDollarPlaceholders(html: string): string {
|
||||
return html.replaceAll(MATH_CODE_DOLLAR_MASK, '$');
|
||||
}
|
||||
|
||||
export function unmaskSubscriptCodeLinePlaceholders(html: string): string {
|
||||
return html.replaceAll(`${SUBSCRIPT_CODE_LINE_MASK}#`, '-#');
|
||||
}
|
||||
|
||||
const MARKED_MATH_BLOCK_SHIELD = '\uE021';
|
||||
const MARKED_MATH_BLOCK_SHIELD_END = '\uE022';
|
||||
|
||||
export function shieldDollarRunsForMarked(markdown: string): string {
|
||||
const blocks: string[] = [];
|
||||
const blockRe = /\$\$([^$]+)\$\$\n?/g;
|
||||
let m: RegExpExecArray | null;
|
||||
let shielded = '';
|
||||
let last = 0;
|
||||
while ((m = blockRe.exec(markdown)) !== null) {
|
||||
shielded += markdown.slice(last, m.index);
|
||||
blocks.push(m[0]);
|
||||
shielded += `${MARKED_MATH_BLOCK_SHIELD}${blocks.length - 1}${MARKED_MATH_BLOCK_SHIELD_END}`;
|
||||
last = m.index + m[0].length;
|
||||
}
|
||||
shielded += markdown.slice(last);
|
||||
|
||||
shielded = shielded.replace(/\${2,}/g, (run) => run.replace(/\$/g, () => '\\$'));
|
||||
|
||||
return shielded.replace(
|
||||
new RegExp(`${MARKED_MATH_BLOCK_SHIELD}(\\d+)${MARKED_MATH_BLOCK_SHIELD_END}`, 'g'),
|
||||
(_, i) => blocks[parseInt(i, 10)] ?? ''
|
||||
);
|
||||
}
|
||||
|
||||
function escapeHtml(text: string): string {
|
||||
return text
|
||||
.replace(/&/g, '&')
|
||||
@@ -163,6 +208,49 @@ function escapeHtml(text: string): string {
|
||||
.replace(/"/g, '"');
|
||||
}
|
||||
|
||||
function isIgnorableMathContent(latex: string): boolean {
|
||||
const t = latex.replace(/[\u200B-\u200D\uFEFF]/g, '').trim();
|
||||
if (t === '') return true;
|
||||
return /^\$+$/.test(t);
|
||||
}
|
||||
|
||||
/**
|
||||
* Inline math delimiters use `$...$` but must not greedily pair across dollar amounts
|
||||
* (e.g. "$10 ... $20"). We only treat a pair as math when:
|
||||
* - the opening `$` is not followed by whitespace, and
|
||||
* - the closing `$` is not preceded by whitespace, and
|
||||
* - the closing `$` is not immediately followed by an ASCII digit.
|
||||
*/
|
||||
function tryTokenizeInlineMath(
|
||||
src: string
|
||||
): { type: 'math'; raw: string; latex: string } | undefined {
|
||||
if (!src.startsWith('$')) {
|
||||
return undefined;
|
||||
}
|
||||
if (src.startsWith('$$') && (src.length < 3 || src.charAt(2) !== '$')) {
|
||||
return undefined;
|
||||
}
|
||||
if (src.length < 3 || /\s/.test(src.charAt(1))) {
|
||||
return undefined;
|
||||
}
|
||||
for (let j = 1; j < src.length; j++) {
|
||||
if (src.charAt(j) !== '$') continue;
|
||||
const before = src.charAt(j - 1);
|
||||
if (/\s/.test(before)) continue;
|
||||
const after = j + 1 < src.length ? src.charAt(j + 1) : '';
|
||||
if (after !== '' && /[0-9]/.test(after)) continue;
|
||||
const latex = src.slice(1, j);
|
||||
if (isIgnorableMathContent(latex)) continue;
|
||||
if (latex.trimStart().startsWith('$$')) continue;
|
||||
return {
|
||||
type: 'math',
|
||||
raw: src.slice(0, j + 1),
|
||||
latex,
|
||||
};
|
||||
}
|
||||
return undefined;
|
||||
}
|
||||
|
||||
// Inline math: $...$
|
||||
export const matrixMathExtension = {
|
||||
name: 'math',
|
||||
@@ -171,15 +259,7 @@ export const matrixMathExtension = {
|
||||
return src.indexOf('$');
|
||||
},
|
||||
tokenizer(src: string) {
|
||||
const match = /^\$([^$]+)\$/.exec(src);
|
||||
if (match) {
|
||||
return {
|
||||
type: 'math',
|
||||
raw: match[0],
|
||||
latex: match[1],
|
||||
};
|
||||
}
|
||||
return undefined;
|
||||
return tryTokenizeInlineMath(src);
|
||||
},
|
||||
renderer(token) {
|
||||
return `<span data-mx-maths="${escapeHtml(token.latex)}">${token.latex}</span>`;
|
||||
@@ -196,10 +276,12 @@ export const matrixMathBlockExtension = {
|
||||
tokenizer(src: string) {
|
||||
const match = /^\$\$([^$]+)\$\$\n?/.exec(src);
|
||||
if (match) {
|
||||
const latex = match[1]?.trim() ?? '';
|
||||
if (isIgnorableMathContent(latex)) return undefined;
|
||||
return {
|
||||
type: 'mathBlock',
|
||||
raw: match[0],
|
||||
latex: match[1]?.trim() ?? '',
|
||||
latex,
|
||||
};
|
||||
}
|
||||
return undefined;
|
||||
|
||||
@@ -4,25 +4,24 @@ import type { TokenizerExtension, RendererExtension, Tokens } from 'marked';
|
||||
export const matrixSubscriptExtension = {
|
||||
name: 'subscript',
|
||||
level: 'block',
|
||||
start(src: string) {
|
||||
return src.indexOf('-#');
|
||||
},
|
||||
tokenizer(
|
||||
this: { lexer: { inlineTokens: (t: string, tokens: Tokens.Generic[]) => void } },
|
||||
this: {
|
||||
lexer: { inlineTokens: (t: string, tokens: Tokens.Generic[]) => void };
|
||||
},
|
||||
src: string
|
||||
) {
|
||||
const match = /^-# +(.+)/.exec(src);
|
||||
if (match) {
|
||||
const token = {
|
||||
type: 'subscript',
|
||||
raw: match[0],
|
||||
text: match[1],
|
||||
tokens: [] as Tokens.Generic[],
|
||||
};
|
||||
this.lexer.inlineTokens(token.text!, token.tokens);
|
||||
return token;
|
||||
const match = /^-# +([^\n]+)/.exec(src);
|
||||
if (!match) {
|
||||
return undefined;
|
||||
}
|
||||
return undefined;
|
||||
const token = {
|
||||
type: 'subscript',
|
||||
raw: match[0],
|
||||
text: match[1],
|
||||
tokens: [] as Tokens.Generic[],
|
||||
};
|
||||
this.lexer.inlineTokens(token.text!, token.tokens);
|
||||
return token;
|
||||
},
|
||||
renderer(
|
||||
this: { parser: { parseInline: (tokens: Tokens.Generic[]) => string } },
|
||||
|
||||
@@ -1,7 +1,11 @@
|
||||
import { describe, expect, it } from 'vitest';
|
||||
import { marked } from 'marked';
|
||||
import { matrixSpoilerExtension } from './matrix-spoiler';
|
||||
import { matrixMathExtension, matrixMathBlockExtension } from './matrix-math';
|
||||
import {
|
||||
matrixMathBlockExtension,
|
||||
matrixMathExtension,
|
||||
shieldDollarRunsForMarked,
|
||||
} from './matrix-math';
|
||||
import { matrixSubscriptExtension } from './matrix-subscript';
|
||||
|
||||
function parse(input: string): string {
|
||||
@@ -13,7 +17,7 @@ function parse(input: string): string {
|
||||
matrixSubscriptExtension,
|
||||
],
|
||||
});
|
||||
return processor.parse(input) as string;
|
||||
return processor.parse(shieldDollarRunsForMarked(input)) as string;
|
||||
}
|
||||
|
||||
describe('matrixSpoilerExtension', () => {
|
||||
@@ -48,6 +52,36 @@ describe('matrixMathExtension (inline)', () => {
|
||||
it('does not parse unmatched $', () => {
|
||||
expect(parse('No $ math here')).not.toContain('data-mx-maths');
|
||||
});
|
||||
|
||||
it('does not parse dollar amounts in a sentence as inline math', () => {
|
||||
const input = 'I just bought something for $10 on sale, it was originally $20!';
|
||||
const result = parse(input);
|
||||
expect(result).not.toContain('data-mx-maths');
|
||||
expect(result).toContain('$10');
|
||||
expect(result).toContain('$20');
|
||||
});
|
||||
|
||||
it('does not treat $ as math when the opening is followed by whitespace', () => {
|
||||
expect(parse('$ E = mc^2$')).not.toContain('data-mx-maths');
|
||||
});
|
||||
|
||||
it('still parses valid inline math', () => {
|
||||
expect(parse('$E = mc^2$')).toContain('data-mx-maths');
|
||||
expect(parse('$2+2$')).toContain('data-mx-maths');
|
||||
});
|
||||
|
||||
it('does not parse inline math when inner trims to empty (e.g. zero-width only)', () => {
|
||||
expect(parse(`empty $\u200B$ here`)).not.toContain('data-mx-maths');
|
||||
});
|
||||
|
||||
it('does not parse long runs of dollar signs as inline math', () => {
|
||||
expect(parse('hey $$$$$$$ there')).not.toContain('data-mx-maths');
|
||||
});
|
||||
|
||||
it('does not parse block math when inner is only whitespace or dollars', () => {
|
||||
expect(parse('$$ $$')).not.toContain('data-mx-maths');
|
||||
expect(parse('$$ $ $$')).not.toContain('data-mx-maths');
|
||||
});
|
||||
});
|
||||
|
||||
describe('matrixMathBlockExtension (block)', () => {
|
||||
|
||||
@@ -62,6 +62,11 @@ describe('htmlToMarkdown', () => {
|
||||
);
|
||||
});
|
||||
|
||||
it('converts hidden-preview wrapped links to markdown with <href>', () => {
|
||||
const html = '<p><<a href="https://example.org/">https://example.org/</a>></p>';
|
||||
expect(htmlToMarkdown(html)).toBe('[https://example.org/](<https://example.org/>)');
|
||||
});
|
||||
|
||||
it('converts spoiler spans', () => {
|
||||
expect(htmlToMarkdown('<span data-mx-spoiler>hidden</span>')).toContain('||hidden||');
|
||||
});
|
||||
|
||||
@@ -176,7 +176,45 @@ function processInlineElements(
|
||||
listDepth: number = 0,
|
||||
insideCode: boolean = false
|
||||
): string {
|
||||
return node.children.map((c) => processNode(c, listDepth, insideCode)).join('');
|
||||
return processChildren(node.children, listDepth, insideCode);
|
||||
}
|
||||
|
||||
function processChildren(
|
||||
children: ChildNode[],
|
||||
listDepth: number = 0,
|
||||
insideCode: boolean = false
|
||||
): string {
|
||||
const out: string[] = [];
|
||||
|
||||
for (let i = 0; i < children.length; i += 1) {
|
||||
const cur = children[i];
|
||||
const next = children[i + 1];
|
||||
const next2 = children[i + 2];
|
||||
|
||||
if (
|
||||
cur &&
|
||||
next &&
|
||||
next2 &&
|
||||
isText(cur) &&
|
||||
cur.data === '<' &&
|
||||
isTag(next) &&
|
||||
next.name.toLowerCase() === 'a' &&
|
||||
isText(next2) &&
|
||||
next2.data === '>'
|
||||
) {
|
||||
const href = next.attribs.href ?? '';
|
||||
const content = next.children.map((c) => processNode(c, listDepth, insideCode)).join('');
|
||||
out.push(`[${content}](<${href}>)`);
|
||||
i += 2;
|
||||
continue;
|
||||
}
|
||||
|
||||
if (cur) {
|
||||
out.push(processNode(cur, listDepth, insideCode));
|
||||
}
|
||||
}
|
||||
|
||||
return out.join('');
|
||||
}
|
||||
|
||||
function processInlineWrapper(
|
||||
@@ -185,7 +223,7 @@ function processInlineWrapper(
|
||||
listDepth: number = 0,
|
||||
insideCode: boolean = false
|
||||
): string {
|
||||
const content = node.children.map((c) => processNode(c, listDepth, insideCode)).join('');
|
||||
const content = processChildren(node.children, listDepth, insideCode);
|
||||
return `${marker}${content}${marker}`;
|
||||
}
|
||||
|
||||
@@ -222,7 +260,7 @@ function processHeading(
|
||||
insideCode: boolean = false
|
||||
): string {
|
||||
const level = tag.charAt(1);
|
||||
const content = node.children.map((c) => processNode(c, listDepth, insideCode)).join('');
|
||||
const content = processChildren(node.children, listDepth, insideCode);
|
||||
return `${'#'.repeat(parseInt(level, 10))} ${content}\n`;
|
||||
}
|
||||
|
||||
@@ -231,7 +269,7 @@ function processParagraph(
|
||||
listDepth: number = 0,
|
||||
insideCode: boolean = false
|
||||
): string {
|
||||
const content = node.children.map((c) => processNode(c, listDepth, insideCode)).join('');
|
||||
const content = processChildren(node.children, listDepth, insideCode);
|
||||
return `${content}\n`;
|
||||
}
|
||||
|
||||
|
||||
@@ -1,4 +1,5 @@
|
||||
import { describe, expect, it } from 'vitest';
|
||||
import { htmlToMarkdown } from './htmlToMarkdown';
|
||||
import { markdownToHtml } from './markdownToHtml';
|
||||
|
||||
describe('markdownToHtml', () => {
|
||||
@@ -48,6 +49,26 @@ describe('markdownToHtml', () => {
|
||||
expect(result).toContain('E = mc^2');
|
||||
});
|
||||
|
||||
it('does not mangle messages with dollar amounts', () => {
|
||||
const result = markdownToHtml(
|
||||
'I just bought something for $10 on sale, it was originally $20!'
|
||||
);
|
||||
expect(result).not.toContain('data-mx-maths');
|
||||
expect(result).toContain('$10');
|
||||
expect(result).toContain('$20');
|
||||
});
|
||||
|
||||
it('does not treat empty or dollar-only block math as KaTeX', () => {
|
||||
expect(markdownToHtml('$$ $$')).not.toContain('data-mx-maths');
|
||||
expect(markdownToHtml('$$ $ $$')).not.toContain('data-mx-maths');
|
||||
});
|
||||
|
||||
it('does not parse five consecutive dollar signs in a sentence as math', () => {
|
||||
const result = markdownToHtml('hey $$$$$ there');
|
||||
expect(result).not.toContain('data-mx-maths');
|
||||
expect(result).toContain('$$$$$');
|
||||
});
|
||||
|
||||
it('does not parse dollars inside fenced code as math', () => {
|
||||
expect(markdownToHtml('```\n$$test$$\n```')).not.toContain('data-mx-maths');
|
||||
expect(markdownToHtml('```\n$$test$$\n```')).toContain('$$test$$');
|
||||
@@ -69,6 +90,41 @@ describe('markdownToHtml', () => {
|
||||
expect(result).toContain('$$test$$');
|
||||
});
|
||||
|
||||
it('converts -# small/sub syntax outside code', () => {
|
||||
const result = markdownToHtml('-# caption');
|
||||
expect(result).toContain('<sub');
|
||||
expect(result).toContain('data-md="-#"');
|
||||
expect(result).toContain('caption');
|
||||
});
|
||||
|
||||
it('does not parse -# inside fenced code as subscript', () => {
|
||||
expect(markdownToHtml('```\n-# not sub\n```')).not.toContain('<sub');
|
||||
expect(markdownToHtml('```\n-# not sub\n```')).toContain('-# not sub');
|
||||
});
|
||||
|
||||
it('does not parse -# inside inline code as subscript', () => {
|
||||
expect(markdownToHtml('`-# lit`')).not.toContain('<sub');
|
||||
expect(markdownToHtml('`-# lit`')).toContain('-# lit');
|
||||
});
|
||||
|
||||
it('parses -# as single-line only so fenced code below stays code', () => {
|
||||
const html = markdownToHtml('-# caption\n```\nfenced\n```');
|
||||
expect(html).toContain('caption');
|
||||
expect(html).toContain('<pre>');
|
||||
expect(html).toContain('fenced');
|
||||
});
|
||||
|
||||
it('does not parse escaped \\-# as small/sub', () => {
|
||||
const result = markdownToHtml('\\-# literal caption');
|
||||
expect(result).not.toContain('<sub');
|
||||
expect(result).not.toContain('data-md="-#"');
|
||||
expect(result).toContain('literal caption');
|
||||
});
|
||||
|
||||
it('escapes literal -# when converting paragraph HTML to markdown', () => {
|
||||
expect(htmlToMarkdown('<p>-# plain words</p>')).toContain('\\-#');
|
||||
});
|
||||
|
||||
it('converts block math syntax', () => {
|
||||
const result = markdownToHtml('$$\\frac{a}{b}$$');
|
||||
expect(result).toContain('data-mx-maths');
|
||||
@@ -134,6 +190,7 @@ describe('markdownToHtml', () => {
|
||||
const result = markdownToHtml(html);
|
||||
expect(result).toContain('mxc://example.org/emote');
|
||||
expect(result).toContain('data-mx-emoticon');
|
||||
expect(result).toContain('height="32"');
|
||||
});
|
||||
|
||||
it('rejects img tags with non-mxc protocols', () => {
|
||||
|
||||
@@ -5,7 +5,9 @@ import {
|
||||
matrixMathExtension,
|
||||
matrixMathBlockExtension,
|
||||
maskDollarSignsInsideMarkdownCode,
|
||||
shieldDollarRunsForMarked,
|
||||
unmaskMathCodeDollarPlaceholders,
|
||||
unmaskSubscriptCodeLinePlaceholders,
|
||||
} from './extensions/matrix-math';
|
||||
import { matrixSubscriptExtension } from './extensions/matrix-subscript';
|
||||
import { matrixEmoticonExtension, preprocessEmoticon } from './extensions/matrix-emoticon';
|
||||
@@ -48,6 +50,39 @@ const decodeHtmlEntities = (text: string): string => {
|
||||
return result;
|
||||
};
|
||||
|
||||
const MATRIX_TO_PLACEHOLDER_PREFIX = 'MATRIXTORAWLINKTOKEN';
|
||||
|
||||
const escapeHtml = (text: string): string =>
|
||||
text
|
||||
.replace(/&/g, '&')
|
||||
.replace(/</g, '<')
|
||||
.replace(/>/g, '>')
|
||||
.replace(/"/g, '"')
|
||||
.replace(/'/g, ''');
|
||||
|
||||
const shieldBareMatrixToLinks = (
|
||||
input: string
|
||||
): { shielded: string; placeholders: Map<string, string> } => {
|
||||
const placeholders = new Map<string, string>();
|
||||
let index = 0;
|
||||
|
||||
const shielded = input.replace(/(?<!\]\()https?:\/\/matrix\.to\/[^\s<)]+/gi, (url) => {
|
||||
const key = `${MATRIX_TO_PLACEHOLDER_PREFIX}${index++}X`;
|
||||
placeholders.set(key, url);
|
||||
return key;
|
||||
});
|
||||
|
||||
return { shielded, placeholders };
|
||||
};
|
||||
|
||||
const unshieldBareMatrixToLinks = (html: string, placeholders: Map<string, string>): string => {
|
||||
let result = html;
|
||||
for (const [key, url] of placeholders.entries()) {
|
||||
result = result.split(key).join(escapeHtml(url));
|
||||
}
|
||||
return result;
|
||||
};
|
||||
|
||||
/**
|
||||
* Converts markdown string to sanitized Matrix-compatible HTML.
|
||||
* Uses marked for parsing and DOMPurify for sanitization per Matrix spec.
|
||||
@@ -65,7 +100,10 @@ export function markdownToHtml(markdown: string): string {
|
||||
|
||||
const preprocessed = preprocessEmoticon(blockquotePrefixed);
|
||||
|
||||
const mathInput = maskDollarSignsInsideMarkdownCode(preprocessed);
|
||||
const { shielded: matrixToShielded, placeholders: matrixToPlaceholders } =
|
||||
shieldBareMatrixToLinks(preprocessed);
|
||||
|
||||
const mathInput = shieldDollarRunsForMarked(maskDollarSignsInsideMarkdownCode(matrixToShielded));
|
||||
|
||||
// Parse markdown to HTML using marked with our Matrix extensions
|
||||
const html = processor.parse(mathInput) as string;
|
||||
@@ -139,8 +177,9 @@ export function markdownToHtml(markdown: string): string {
|
||||
'type',
|
||||
'open',
|
||||
],
|
||||
// Allow safe rel attributes for links
|
||||
ADD_ATTR: ['target', 'rel'],
|
||||
// Ensure these safe attrs survive sanitization even when the input HTML
|
||||
// originates from markdown-embedded tags (e.g. custom emoji <img>).
|
||||
ADD_ATTR: ['target', 'rel', 'height', 'width'],
|
||||
// Force all links to have safe rel attribute
|
||||
FORCE_BODY: false,
|
||||
ALLOWED_URI_REGEXP: /^(?:https?|ftp|mailto|magnet|mxc):/i,
|
||||
@@ -148,8 +187,23 @@ export function markdownToHtml(markdown: string): string {
|
||||
|
||||
DOMPurify.removeHook('afterSanitizeAttributes');
|
||||
|
||||
return unmaskMathCodeDollarPlaceholders(sanitized).replace(
|
||||
/<li>(<p><\/p>)?<\/li>/gi,
|
||||
'<li><br></li>'
|
||||
const unmasked = unmaskSubscriptCodeLinePlaceholders(unmaskMathCodeDollarPlaceholders(sanitized));
|
||||
|
||||
// DOMPurify's Node/JSdom build can drop <img> size attributes even when allowlisted.
|
||||
// For Matrix custom emojis, always emit a stable height so outgoing messages have
|
||||
// consistent layout across clients.
|
||||
const restoredMxEmoticonHeight = unmasked.replace(
|
||||
/<img\b([^>]*\bdata-mx-emoticon\b[^>]*)>/gi,
|
||||
(full, attrs: string) => {
|
||||
if (/\bheight\s*=/i.test(attrs)) return full;
|
||||
return `<img${attrs} height="32">`;
|
||||
}
|
||||
);
|
||||
|
||||
const unshieldedMatrixTo = unshieldBareMatrixToLinks(
|
||||
restoredMxEmoticonHeight,
|
||||
matrixToPlaceholders
|
||||
);
|
||||
|
||||
return unshieldedMatrixTo.replace(/<li>(<p><\/p>)?<\/li>/gi, '<li><br></li>');
|
||||
}
|
||||
@@ -78,7 +78,12 @@ export const escapeMarkdownInlineSequences = (text: string): string => {
|
||||
(t) => t
|
||||
);
|
||||
|
||||
return parts.join('');
|
||||
let out = parts.join('');
|
||||
out = out.replace(
|
||||
/(^|\n)-(# +)/gm,
|
||||
(_, lineStart: string, hashSp: string) => `${lineStart}\\-${hashSp}`
|
||||
);
|
||||
return out;
|
||||
};
|
||||
|
||||
/**
|
||||
|
||||
@@ -128,6 +128,39 @@ describe('getReactCustomHtmlParser code blocks', () => {
|
||||
});
|
||||
|
||||
describe('react custom html parser', () => {
|
||||
it('defaults custom emoji img height to 32 when missing', () => {
|
||||
const { container } = renderParsedHtml(
|
||||
'<img data-mx-emoticon src="mxc://example.org/emote" alt="blobcat" title="blobcat" />',
|
||||
{
|
||||
sanitize: false,
|
||||
mx: createMatrixClient({
|
||||
mxcUrlToHttp: () => 'https://cdn.example/emote.png',
|
||||
}),
|
||||
}
|
||||
);
|
||||
|
||||
const img = container.querySelector('img');
|
||||
expect(img).toBeInTheDocument();
|
||||
expect(img).toHaveAttribute('height', '32');
|
||||
});
|
||||
|
||||
it('clamps incoming inline image height to the configured max', () => {
|
||||
const { container } = renderParsedHtml(
|
||||
'<img data-mx-emoticon src="mxc://example.org/emote" alt="blobcat" title="blobcat" height="128" />',
|
||||
{
|
||||
sanitize: false,
|
||||
mx: createMatrixClient({
|
||||
mxcUrlToHttp: () => 'https://cdn.example/emote.png',
|
||||
}),
|
||||
}
|
||||
);
|
||||
|
||||
const img = container.querySelector('img');
|
||||
expect(img).toBeInTheDocument();
|
||||
// Default max is 64 unless overridden by settings.
|
||||
expect(img).toHaveAttribute('height', '64');
|
||||
});
|
||||
|
||||
it('renders same-origin raw settings links as mention-style chips through the factory link render path', () => {
|
||||
const renderLink = factoryRenderLinkifyWithMention(
|
||||
settingsLinkBaseUrl,
|
||||
|
||||
@@ -516,6 +516,8 @@ export const getReactCustomHtmlParser = (
|
||||
useAuthentication?: boolean;
|
||||
nicknames?: Nicknames;
|
||||
autoplayEmojis?: boolean;
|
||||
incomingInlineImagesDefaultHeight?: number;
|
||||
incomingInlineImagesMaxHeight?: number;
|
||||
replaceTextNode?: (
|
||||
text: string,
|
||||
renderText: (text: string, key?: string) => JSX.Element
|
||||
@@ -524,6 +526,20 @@ export const getReactCustomHtmlParser = (
|
||||
): HTMLReactParserOptions => {
|
||||
const { replaceTextNode } = params;
|
||||
|
||||
const defaultIncomingImgHeight = params.incomingInlineImagesDefaultHeight ?? 32;
|
||||
const maxIncomingImgHeight = params.incomingInlineImagesMaxHeight ?? 64;
|
||||
|
||||
const normalizeIncomingImgHeight = (raw: unknown): number => {
|
||||
const parsed =
|
||||
typeof raw === 'number' ? raw : typeof raw === 'string' ? Number.parseInt(raw, 10) : NaN;
|
||||
const fallback = defaultIncomingImgHeight;
|
||||
const safe = Number.isFinite(parsed) ? parsed : fallback;
|
||||
// Clamp to sane bounds first, then apply the user max.
|
||||
const bounded = Math.max(1, Math.min(4096, Math.round(safe)));
|
||||
const max = Math.max(1, Math.min(4096, Math.round(maxIncomingImgHeight)));
|
||||
return Math.min(bounded, max);
|
||||
};
|
||||
|
||||
const decorateText = (text: string) => {
|
||||
let jsx = scaleSystemEmoji(text);
|
||||
|
||||
@@ -807,6 +823,8 @@ export const getReactCustomHtmlParser = (
|
||||
);
|
||||
}
|
||||
|
||||
const height = normalizeIncomingImgHeight(props.height);
|
||||
|
||||
const siblingCount = domNode.parent?.children.length ?? 0;
|
||||
|
||||
// seperate style for bundled emojis
|
||||
@@ -821,6 +839,7 @@ export const getReactCustomHtmlParser = (
|
||||
{...props}
|
||||
src={htmlSrc}
|
||||
className={css.EmoticonImg}
|
||||
height={height}
|
||||
style={{ verticalAlign: 'middle' }}
|
||||
fallback={
|
||||
<span className={css.EmoticonBase}>
|
||||
@@ -834,6 +853,7 @@ export const getReactCustomHtmlParser = (
|
||||
{...props}
|
||||
src={htmlSrc}
|
||||
className={css.EmoticonImg}
|
||||
height={height}
|
||||
style={{ verticalAlign: 'middle' }}
|
||||
fallback={
|
||||
<span className={css.EmoticonBase}>
|
||||
@@ -857,6 +877,7 @@ export const getReactCustomHtmlParser = (
|
||||
{...props}
|
||||
src={htmlSrc}
|
||||
className={css.EmoticonImg}
|
||||
height={height}
|
||||
fallback={
|
||||
<span className={css.EmoticonBase}>
|
||||
{props.alt || props.title || '?'}
|
||||
@@ -869,6 +890,7 @@ export const getReactCustomHtmlParser = (
|
||||
{...props}
|
||||
src={htmlSrc}
|
||||
className={css.EmoticonImg}
|
||||
height={height}
|
||||
fallback={
|
||||
<span className={css.EmoticonBase}>{props.alt || props.title || '?'}</span>
|
||||
}
|
||||
@@ -893,6 +915,7 @@ export const getReactCustomHtmlParser = (
|
||||
{...props}
|
||||
className={css.Img}
|
||||
src={htmlSrc}
|
||||
height={normalizeIncomingImgHeight(props.height)}
|
||||
fallback={
|
||||
<span title={`Failed to load media${props.alt ? `: ${props.alt}` : ''}`}>
|
||||
{props.alt || '[media]'}
|
||||
|
||||
@@ -14,3 +14,5 @@ export const roomIdToEditingScheduledDelayIdAtomFamily = atomFamily<
|
||||
string,
|
||||
ReturnType<typeof atom<string | null>>
|
||||
>(() => atom<string | null>(null));
|
||||
|
||||
export const serverMaxDelayMsAtom = atom<number | null>(null);
|
||||
@@ -0,0 +1,67 @@
|
||||
import { describe, it, expect, beforeEach } from 'vitest';
|
||||
import {
|
||||
defaultSettings,
|
||||
mergePersistedSettings,
|
||||
sanitizeSettingsDefaults,
|
||||
resetRuntimeSettingsDefaults,
|
||||
} from '$state/settings';
|
||||
|
||||
beforeEach(() => {
|
||||
localStorage.clear();
|
||||
resetRuntimeSettingsDefaults();
|
||||
});
|
||||
|
||||
describe('mergePersistedSettings', () => {
|
||||
it('layers deployer defaults over code defaults when localStorage is empty', () => {
|
||||
const merged = mergePersistedSettings(null, { twitterEmoji: false });
|
||||
expect(merged.twitterEmoji).toBe(false);
|
||||
expect(merged.pageZoom).toBe(defaultSettings.pageZoom);
|
||||
});
|
||||
|
||||
it('lets localStorage override deployer defaults', () => {
|
||||
localStorage.setItem('settings', JSON.stringify({ twitterEmoji: true }));
|
||||
const merged = mergePersistedSettings(localStorage.getItem('settings'), {
|
||||
twitterEmoji: false,
|
||||
});
|
||||
expect(merged.twitterEmoji).toBe(true);
|
||||
});
|
||||
|
||||
it('still applies monochrome migration when layering defaults', () => {
|
||||
localStorage.setItem('settings', JSON.stringify({ monochromeMode: true }));
|
||||
const merged = mergePersistedSettings(localStorage.getItem('settings'), {});
|
||||
expect(merged.saturationLevel).toBe(0);
|
||||
});
|
||||
});
|
||||
|
||||
describe('sanitizeSettingsDefaults', () => {
|
||||
it('keeps known keys with valid types', () => {
|
||||
expect(sanitizeSettingsDefaults({ twitterEmoji: false })).toEqual({
|
||||
twitterEmoji: false,
|
||||
});
|
||||
});
|
||||
|
||||
it('drops unknown keys', () => {
|
||||
expect(sanitizeSettingsDefaults({ notARealSetting: true, hour24Clock: true })).toEqual({
|
||||
hour24Clock: true,
|
||||
});
|
||||
});
|
||||
|
||||
it('drops invalid types', () => {
|
||||
expect(sanitizeSettingsDefaults({ twitterEmoji: 'yes' })).toEqual({});
|
||||
});
|
||||
|
||||
it('accepts messageLayout 0–2 only', () => {
|
||||
expect(sanitizeSettingsDefaults({ messageLayout: 2 })).toEqual({
|
||||
messageLayout: 2,
|
||||
});
|
||||
expect(sanitizeSettingsDefaults({ messageLayout: 9 })).toEqual({});
|
||||
expect(sanitizeSettingsDefaults({ messageLayout: 1.5 })).toEqual({});
|
||||
});
|
||||
|
||||
it('accepts rightSwipeAction enum strings', () => {
|
||||
expect(sanitizeSettingsDefaults({ rightSwipeAction: 'members' })).toEqual({
|
||||
rightSwipeAction: 'members',
|
||||
});
|
||||
expect(sanitizeSettingsDefaults({ rightSwipeAction: 'nope' })).toEqual({});
|
||||
});
|
||||
});
|
||||
+216
-16
@@ -1,4 +1,5 @@
|
||||
import { atom, type WritableAtom } from 'jotai';
|
||||
import type { Store } from 'jotai/vanilla/store';
|
||||
import { mobileOrTablet } from '$utils/user-agent';
|
||||
|
||||
const STORAGE_KEY = 'settings';
|
||||
@@ -145,6 +146,9 @@ export interface Settings {
|
||||
autoplayGifs: boolean;
|
||||
autoplayStickers: boolean;
|
||||
autoplayEmojis: boolean;
|
||||
incomingInlineImagesDefaultHeight: number;
|
||||
incomingInlineImagesMaxHeight: number;
|
||||
linkPreviewImageMaxHeight: number;
|
||||
saveStickerEmojiBandwidth: boolean;
|
||||
subspaceHierarchyLimit: number;
|
||||
alwaysShowCallButton: boolean;
|
||||
@@ -272,6 +276,9 @@ export const defaultSettings: Settings = {
|
||||
autoplayGifs: true,
|
||||
autoplayStickers: true,
|
||||
autoplayEmojis: true,
|
||||
incomingInlineImagesDefaultHeight: 32,
|
||||
incomingInlineImagesMaxHeight: 64,
|
||||
linkPreviewImageMaxHeight: 640,
|
||||
saveStickerEmojiBandwidth: false,
|
||||
subspaceHierarchyLimit: 3,
|
||||
alwaysShowCallButton: false,
|
||||
@@ -311,13 +318,18 @@ export const defaultSettings: Settings = {
|
||||
themeRemoteEnabledTweakFullUrls: [],
|
||||
};
|
||||
|
||||
export const getSettings = () => {
|
||||
const settings = localStorage.getItem(STORAGE_KEY);
|
||||
if (settings === null) return defaultSettings;
|
||||
function cloneDefaultSettings(): Settings {
|
||||
return {
|
||||
...defaultSettings,
|
||||
themeRemoteFavorites: defaultSettings.themeRemoteFavorites.map((x) => ({
|
||||
...x,
|
||||
})),
|
||||
themeRemoteTweakFavorites: defaultSettings.themeRemoteTweakFavorites.map((x) => ({ ...x })),
|
||||
themeRemoteEnabledTweakFullUrls: [...defaultSettings.themeRemoteEnabledTweakFullUrls],
|
||||
};
|
||||
}
|
||||
|
||||
// migration for old keys
|
||||
// monochrome -> saturation
|
||||
const parsed = JSON.parse(settings);
|
||||
function migrateParsedLocalStorage(parsed: Record<string, unknown>): void {
|
||||
if (parsed.monochromeMode === true && parsed.saturationLevel === undefined) {
|
||||
parsed.saturationLevel = 0;
|
||||
} else if (parsed.monochromeMode === false && parsed.saturationLevel === undefined) {
|
||||
@@ -336,27 +348,215 @@ export const getSettings = () => {
|
||||
parsed.renderUserCards = 'both';
|
||||
}
|
||||
|
||||
const parsedRecord = parsed as Record<string, unknown>;
|
||||
if (
|
||||
typeof parsedRecord.themeChatAutoPreviewAnyUrl !== 'boolean' &&
|
||||
typeof parsedRecord.themeChatPreviewAnyUrl === 'boolean'
|
||||
typeof parsed.themeChatAutoPreviewAnyUrl !== 'boolean' &&
|
||||
typeof parsed.themeChatPreviewAnyUrl === 'boolean'
|
||||
) {
|
||||
parsedRecord.themeChatAutoPreviewAnyUrl = parsedRecord.themeChatPreviewAnyUrl;
|
||||
parsed.themeChatAutoPreviewAnyUrl = parsed.themeChatPreviewAnyUrl;
|
||||
}
|
||||
delete parsedRecord.themeChatPreviewAnyUrl;
|
||||
delete parsedRecord.themeChatPreviewApprovedCatalogOnly;
|
||||
delete parsed.themeChatPreviewAnyUrl;
|
||||
delete parsed.themeChatPreviewApprovedCatalogOnly;
|
||||
}
|
||||
|
||||
export function mergePersistedSettings(
|
||||
rawLocalStorage: string | null,
|
||||
fileDefaults: Partial<Settings>
|
||||
): Settings {
|
||||
const base = { ...defaultSettings, ...fileDefaults };
|
||||
if (rawLocalStorage === null) return base;
|
||||
|
||||
const parsed = JSON.parse(rawLocalStorage) as Record<string, unknown>;
|
||||
migrateParsedLocalStorage(parsed);
|
||||
|
||||
return {
|
||||
...defaultSettings,
|
||||
...(parsed as Settings),
|
||||
...base,
|
||||
...(parsed as unknown as Settings),
|
||||
};
|
||||
};
|
||||
}
|
||||
|
||||
const MESSAGE_SPACING_VALUES = new Set<MessageSpacing>(['0', '100', '200', '300', '400', '500']);
|
||||
const JUMBO_EMOJI_VALUES = new Set<JumboEmojiSize>([
|
||||
'none',
|
||||
'extraSmall',
|
||||
'small',
|
||||
'normal',
|
||||
'large',
|
||||
'extraLarge',
|
||||
]);
|
||||
|
||||
function sanitizeStringArray(val: unknown): string[] | undefined {
|
||||
if (!Array.isArray(val)) return undefined;
|
||||
const out = val.filter((x): x is string => typeof x === 'string');
|
||||
return out;
|
||||
}
|
||||
|
||||
function sanitizeThemeRemoteFavorites(val: unknown): ThemeRemoteFavorite[] | undefined {
|
||||
if (!Array.isArray(val)) return undefined;
|
||||
const out: ThemeRemoteFavorite[] = [];
|
||||
for (const item of val) {
|
||||
if (!item || typeof item !== 'object') continue;
|
||||
const o = item as Record<string, unknown>;
|
||||
if (
|
||||
typeof o.fullUrl === 'string' &&
|
||||
typeof o.displayName === 'string' &&
|
||||
typeof o.basename === 'string' &&
|
||||
(o.kind === 'light' || o.kind === 'dark')
|
||||
) {
|
||||
out.push({
|
||||
fullUrl: o.fullUrl,
|
||||
displayName: o.displayName,
|
||||
basename: o.basename,
|
||||
kind: o.kind,
|
||||
pinned: typeof o.pinned === 'boolean' ? o.pinned : undefined,
|
||||
importedLocal: typeof o.importedLocal === 'boolean' ? o.importedLocal : undefined,
|
||||
});
|
||||
}
|
||||
}
|
||||
return out;
|
||||
}
|
||||
|
||||
function sanitizeThemeRemoteTweakFavorites(val: unknown): ThemeRemoteTweakFavorite[] | undefined {
|
||||
if (!Array.isArray(val)) return undefined;
|
||||
const out: ThemeRemoteTweakFavorite[] = [];
|
||||
for (const item of val) {
|
||||
if (!item || typeof item !== 'object') continue;
|
||||
const o = item as Record<string, unknown>;
|
||||
if (
|
||||
typeof o.fullUrl === 'string' &&
|
||||
typeof o.displayName === 'string' &&
|
||||
typeof o.basename === 'string'
|
||||
) {
|
||||
out.push({
|
||||
fullUrl: o.fullUrl,
|
||||
displayName: o.displayName,
|
||||
basename: o.basename,
|
||||
pinned: typeof o.pinned === 'boolean' ? o.pinned : undefined,
|
||||
importedLocal: typeof o.importedLocal === 'boolean' ? o.importedLocal : undefined,
|
||||
});
|
||||
}
|
||||
}
|
||||
return out;
|
||||
}
|
||||
|
||||
function isSanitizableSettingsKey(k: string): k is keyof Settings {
|
||||
return (
|
||||
k in defaultSettings || k === 'filterPronounsBasedOnLanguage' || k === 'filterPronounsLanguages'
|
||||
);
|
||||
}
|
||||
|
||||
function sanitizeSettingsKey(key: keyof Settings, val: unknown): unknown {
|
||||
switch (key) {
|
||||
case 'filterPronounsBasedOnLanguage':
|
||||
return typeof val === 'boolean' ? val : undefined;
|
||||
case 'filterPronounsLanguages':
|
||||
return sanitizeStringArray(val);
|
||||
case 'messageLayout':
|
||||
return typeof val === 'number' && Number.isInteger(val) && val >= 0 && val <= 2
|
||||
? val
|
||||
: undefined;
|
||||
case 'messageSpacing':
|
||||
return typeof val === 'string' && MESSAGE_SPACING_VALUES.has(val as MessageSpacing)
|
||||
? val
|
||||
: undefined;
|
||||
case 'captionPosition':
|
||||
return val === CaptionPosition.Above ||
|
||||
val === CaptionPosition.Inline ||
|
||||
val === CaptionPosition.Hidden ||
|
||||
val === CaptionPosition.Below
|
||||
? val
|
||||
: undefined;
|
||||
case 'rightSwipeAction':
|
||||
return val === RightSwipeAction.Members || val === RightSwipeAction.Reply ? val : undefined;
|
||||
case 'renderUserCards':
|
||||
return val === 'both' || val === 'light' || val === 'dark' || val === 'none'
|
||||
? val
|
||||
: undefined;
|
||||
case 'jumboEmojiSize':
|
||||
return typeof val === 'string' && JUMBO_EMOJI_VALUES.has(val as JumboEmojiSize)
|
||||
? val
|
||||
: undefined;
|
||||
case 'themeRemoteManualKind':
|
||||
case 'themeRemoteLightKind':
|
||||
case 'themeRemoteDarkKind':
|
||||
return val === 'light' || val === 'dark' ? val : undefined;
|
||||
case 'themeRemoteFavorites':
|
||||
return sanitizeThemeRemoteFavorites(val);
|
||||
case 'themeRemoteTweakFavorites':
|
||||
return sanitizeThemeRemoteTweakFavorites(val);
|
||||
case 'themeRemoteEnabledTweakFullUrls':
|
||||
return sanitizeStringArray(val);
|
||||
default: {
|
||||
if (!(key in defaultSettings)) return undefined;
|
||||
const sample = defaultSettings[key];
|
||||
if (typeof sample === 'boolean') {
|
||||
return typeof val === 'boolean' ? val : undefined;
|
||||
}
|
||||
if (typeof sample === 'number') {
|
||||
return typeof val === 'number' && Number.isFinite(val) ? val : undefined;
|
||||
}
|
||||
if (typeof sample === 'string') {
|
||||
return typeof val === 'string' ? val : undefined;
|
||||
}
|
||||
if (sample === undefined) {
|
||||
return typeof val === 'string' ? val : undefined;
|
||||
}
|
||||
return undefined;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
export function sanitizeSettingsDefaults(raw: unknown): Partial<Settings> {
|
||||
if (!raw || typeof raw !== 'object' || Array.isArray(raw)) return {};
|
||||
const src = raw as Record<string, unknown>;
|
||||
const out: Partial<Settings> = {};
|
||||
const warnings: string[] = [];
|
||||
|
||||
for (const k of Object.keys(src)) {
|
||||
if (!isSanitizableSettingsKey(k)) {
|
||||
warnings.push(k);
|
||||
continue;
|
||||
}
|
||||
const sanitized = sanitizeSettingsKey(k, src[k]);
|
||||
if (sanitized !== undefined) {
|
||||
(out as Record<string, unknown>)[k] = sanitized;
|
||||
} else if (src[k] !== undefined) {
|
||||
warnings.push(k);
|
||||
}
|
||||
}
|
||||
|
||||
if (import.meta.env.DEV && warnings.length > 0) {
|
||||
console.warn(
|
||||
'[config.settingsDefaults] ignored unknown or invalid keys:',
|
||||
[...new Set(warnings)].slice(0, 25).join(', ')
|
||||
);
|
||||
}
|
||||
|
||||
return out;
|
||||
}
|
||||
|
||||
let runtimeSettingsDefaults: Partial<Settings> = {};
|
||||
|
||||
/** @internal Resets deploy-time defaults, only used in tests. */
|
||||
export function resetRuntimeSettingsDefaults(): void {
|
||||
runtimeSettingsDefaults = {};
|
||||
}
|
||||
|
||||
export const baseSettings = atom<Settings>(cloneDefaultSettings());
|
||||
|
||||
export function bootstrapSettingsStore(store: Store, rawSettingsDefaults: unknown): void {
|
||||
const sanitized = sanitizeSettingsDefaults(rawSettingsDefaults);
|
||||
runtimeSettingsDefaults = sanitized;
|
||||
const merged = mergePersistedSettings(localStorage.getItem(STORAGE_KEY), sanitized);
|
||||
store.set(baseSettings, merged);
|
||||
}
|
||||
|
||||
export const getSettings = (): Settings =>
|
||||
mergePersistedSettings(localStorage.getItem(STORAGE_KEY), runtimeSettingsDefaults);
|
||||
|
||||
export const setSettings = (settings: Settings) => {
|
||||
localStorage.setItem(STORAGE_KEY, JSON.stringify(settings));
|
||||
};
|
||||
|
||||
const baseSettings = atom(getSettings());
|
||||
export const settingsAtom = atom<Settings, [Settings], undefined>(
|
||||
(get) => get(baseSettings),
|
||||
(_get, set, update) => {
|
||||
|
||||
@@ -7,6 +7,7 @@ import type {
|
||||
IPowerLevelsContent,
|
||||
IPushRule,
|
||||
IPushRules,
|
||||
IThreadBundledRelationship,
|
||||
MatrixClient,
|
||||
MatrixEvent,
|
||||
Room,
|
||||
@@ -679,6 +680,30 @@ export const reactionOrEditEvent = (mEvent: MatrixEvent): boolean => {
|
||||
return false;
|
||||
};
|
||||
|
||||
export const isThreadRelationEvent = (mEvent: MatrixEvent, threadRootId?: string): boolean => {
|
||||
const relation =
|
||||
mEvent.getRelation?.() ??
|
||||
(
|
||||
mEvent.getWireContent?.() as {
|
||||
'm.relates_to'?: { rel_type?: unknown; event_id?: unknown };
|
||||
}
|
||||
)?.['m.relates_to'] ??
|
||||
(
|
||||
mEvent.getContent?.() as {
|
||||
'm.relates_to'?: { rel_type?: unknown; event_id?: unknown };
|
||||
}
|
||||
)?.['m.relates_to'];
|
||||
|
||||
return (
|
||||
relation?.rel_type === (RelationType.Thread as string) &&
|
||||
(threadRootId === undefined || relation.event_id === threadRootId)
|
||||
);
|
||||
};
|
||||
|
||||
export const hasThreadRootAggregation = (mEvent: MatrixEvent): boolean =>
|
||||
(mEvent.getServerAggregatedRelation?.<IThreadBundledRelationship>(RelationType.Thread as string)
|
||||
?.count ?? 0) > 0;
|
||||
|
||||
/**
|
||||
* Timeline rows skip reactions, edits, and other relation-only events. When jumping
|
||||
* to a reply target, unwrap to the event that is actually rendered (root of an
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest';
|
||||
import { getSettings } from '$state/settings';
|
||||
import { getSettings, resetRuntimeSettingsDefaults } from '$state/settings';
|
||||
import {
|
||||
NON_SYNCABLE_KEYS,
|
||||
SETTINGS_SYNC_VERSION,
|
||||
@@ -15,6 +15,7 @@ let base: ReturnType<typeof getSettings>;
|
||||
|
||||
beforeEach(() => {
|
||||
localStorage.clear();
|
||||
resetRuntimeSettingsDefaults();
|
||||
base = getSettings();
|
||||
});
|
||||
|
||||
@@ -141,7 +142,12 @@ describe('deserializeFromSync', () => {
|
||||
developerTools: true,
|
||||
},
|
||||
};
|
||||
const local = { ...base, pageZoom: 100, isPeopleDrawer: true, settingsSyncEnabled: false };
|
||||
const local = {
|
||||
...base,
|
||||
pageZoom: 100,
|
||||
isPeopleDrawer: true,
|
||||
settingsSyncEnabled: false,
|
||||
};
|
||||
const result = deserializeFromSync(remote, local);
|
||||
expect(result).not.toBeNull();
|
||||
expect(result!.pageZoom).toBe(100);
|
||||
@@ -280,12 +286,21 @@ describe('importSettingsFromJson', () => {
|
||||
});
|
||||
|
||||
it('resolves merged settings when a valid JSON file is provided', async () => {
|
||||
const payload = { v: SETTINGS_SYNC_VERSION, settings: { twitterEmoji: false } };
|
||||
const payload = {
|
||||
v: SETTINGS_SYNC_VERSION,
|
||||
settings: { twitterEmoji: false },
|
||||
};
|
||||
const fileContent = JSON.stringify(payload);
|
||||
const file = new File([fileContent], 'settings.json', { type: 'application/json' });
|
||||
const file = new File([fileContent], 'settings.json', {
|
||||
type: 'application/json',
|
||||
});
|
||||
|
||||
// Build a minimal FileList-like object.
|
||||
const fakeFileList = { 0: file, length: 1, item: () => file } as unknown as FileList;
|
||||
const fakeFileList = {
|
||||
0: file,
|
||||
length: 1,
|
||||
item: () => file,
|
||||
} as unknown as FileList;
|
||||
mockInput.files = fakeFileList;
|
||||
|
||||
const promise = importSettingsFromJson({ ...base, twitterEmoji: true });
|
||||
@@ -299,8 +314,14 @@ describe('importSettingsFromJson', () => {
|
||||
});
|
||||
|
||||
it('resolves null when the file contains invalid JSON', async () => {
|
||||
const file = new File(['not json {{'], 'bad.json', { type: 'application/json' });
|
||||
const fakeFileList = { 0: file, length: 1, item: () => file } as unknown as FileList;
|
||||
const file = new File(['not json {{'], 'bad.json', {
|
||||
type: 'application/json',
|
||||
});
|
||||
const fakeFileList = {
|
||||
0: file,
|
||||
length: 1,
|
||||
item: () => file,
|
||||
} as unknown as FileList;
|
||||
mockInput.files = fakeFileList;
|
||||
|
||||
const promise = importSettingsFromJson(base);
|
||||
@@ -314,7 +335,11 @@ describe('importSettingsFromJson', () => {
|
||||
const file = new File([JSON.stringify(payload)], 'settings.json', {
|
||||
type: 'application/json',
|
||||
});
|
||||
const fakeFileList = { 0: file, length: 1, item: () => file } as unknown as FileList;
|
||||
const fakeFileList = {
|
||||
0: file,
|
||||
length: 1,
|
||||
item: () => file,
|
||||
} as unknown as FileList;
|
||||
mockInput.files = fakeFileList;
|
||||
|
||||
const promise = importSettingsFromJson(base);
|
||||
|
||||
@@ -1,6 +1,11 @@
|
||||
import type { EventTimeline, MatrixEvent, Room } from '$types/matrix-sdk';
|
||||
import { Direction } from '$types/matrix-sdk';
|
||||
import { roomHaveNotification, roomHaveUnread, reactionOrEditEvent } from '$utils/room';
|
||||
import {
|
||||
isThreadRelationEvent,
|
||||
reactionOrEditEvent,
|
||||
roomHaveNotification,
|
||||
roomHaveUnread,
|
||||
} from '$utils/room';
|
||||
|
||||
export const PAGINATION_LIMIT = 60;
|
||||
|
||||
@@ -161,7 +166,8 @@ export const getThreadReplyCount = (room: Room, mEventId: string): number => {
|
||||
const threadEvents = tl
|
||||
.getEvents()
|
||||
.filter(
|
||||
(ev) => ev.threadRootId === mEventId && ev.getId() !== mEventId && !reactionOrEditEvent(ev)
|
||||
(ev) =>
|
||||
ev.getId() !== mEventId && !reactionOrEditEvent(ev) && isThreadRelationEvent(ev, mEventId)
|
||||
);
|
||||
return acc + threadEvents.length;
|
||||
}, 0);
|
||||
|
||||
Reference in new issue
Block a user