add ability to cap preview size and minor adjustment to restore codeblock background of misc data

This commit is contained in:
7w1 committed 2026-05-09 16:42:07 -05:00
1 parent 9d264ee5d3
commit f9ade5b986
10 files changed
+331 -75

No files matched your search

@@ -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,
{
@@ -25,6 +25,13 @@ export const UrlPreviewImg = style([
},
]);
export const UrlPreviewMediaWell = style([
DefaultReset,
{
backgroundColor: color.Surface.Container,
},
]);
export const UrlPreviewContent = style([
DefaultReset,
{
+164 -57
View File
@@ -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) ?? ''}
@@ -232,7 +232,9 @@ function UserExtendedSection({
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',
@@ -330,14 +332,7 @@ function UserExtendedSection({
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"
@@ -371,12 +366,13 @@ function UserExtendedSection({
direction="Both"
visibility="Hover"
hideTrack
variant="SurfaceVariant"
style={{
backgroundColor: 'rgba(0, 0, 0, 0.4)',
color: textColor,
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)',
fontFamily: 'monospace',
}}
>
<Box
@@ -384,7 +380,6 @@ function UserExtendedSection({
style={{
padding: config.space.S200,
maxHeight: toRem(100),
opacity: 0.85,
}}
>
<TextViewerContent
@@ -27,6 +27,7 @@ type SettingsShape = {
autoplayEmojis: boolean;
incomingInlineImagesDefaultHeight: number;
incomingInlineImagesMaxHeight: number;
linkPreviewImageMaxHeight: number;
twitterEmoji: boolean;
showEasterEggs: boolean;
subspaceHierarchyLimit: number;
@@ -94,6 +95,7 @@ beforeEach(() => {
autoplayEmojis: true,
incomingInlineImagesDefaultHeight: 32,
incomingInlineImagesMaxHeight: 64,
linkPreviewImageMaxHeight: 320,
twitterEmoji: true,
showEasterEggs: true,
subspaceHierarchyLimit: 3,
@@ -203,12 +203,19 @@ function ThemeVisualPreferences() {
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;
@@ -224,6 +231,12 @@ function ThemeVisualPreferences() {
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> =>
@@ -371,6 +384,36 @@ function ThemeVisualPreferences() {
}
/>
</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>
);
}
@@ -69,6 +69,15 @@ describe('settingsLink', () => {
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', () => {
@@ -122,6 +122,7 @@ const settingsLinkFocusIdsBySection: Record<SettingsSectionId, readonly string[]
'underline-links',
'incoming-inline-images-default-height',
'incoming-inline-images-max-height',
'link-preview-image-max-height',
],
notifications: [
'background-push-notifications',
+2
View File
@@ -141,6 +141,7 @@ export interface Settings {
autoplayEmojis: boolean;
incomingInlineImagesDefaultHeight: number;
incomingInlineImagesMaxHeight: number;
linkPreviewImageMaxHeight: number;
saveStickerEmojiBandwidth: boolean;
subspaceHierarchyLimit: number;
alwaysShowCallButton: boolean;
@@ -262,6 +263,7 @@ export const defaultSettings: Settings = {
autoplayEmojis: true,
incomingInlineImagesDefaultHeight: 32,
incomingInlineImagesMaxHeight: 64,
linkPreviewImageMaxHeight: 320,
saveStickerEmojiBandwidth: false,
subspaceHierarchyLimit: 3,
alwaysShowCallButton: false,