Add gallery support

Co-Authored-By: Tomasz Sterna <[email protected]>
This commit is contained in:
nikiandTomasz Sterna committed 2026-07-01 13:03:14 +03:00
1 parent 4d6137b0d2
commit 55a9032656
13 files changed
+469 -15

No files matched your search

+64 -2
View File
@@ -25,6 +25,7 @@ import {
MNotice,
MText,
MVideo,
MGallery,
ReadPdfFile,
ReadTextFile,
RenderBody,
@@ -49,7 +50,8 @@ import { ClientSideHoverFreeze } from './ClientSideHoverFreeze';
import { CuteEventType, MCuteEvent } from './message/MCuteEvent';
import { PollEvent } from './message/PollEvent';
import { M_TEXT } from 'matrix-js-sdk';
import type { IImageInfo } from '$types/matrix/common';
import type { IImageInfo, IGalleryContent } from '$types/matrix/common';
import { GALLERY_MSGTYPE } from '$types/matrix/common';
type RenderMessageContentProps = {
displayName: string;
@@ -61,6 +63,7 @@ type RenderMessageContentProps = {
bundledPreview?: boolean;
urlPreview?: boolean;
clientUrlPreview?: boolean;
isGallery?: boolean;
showMaps?: boolean;
highlightRegex?: RegExp;
htmlReactParserOptions: HTMLReactParserOptions;
@@ -94,6 +97,7 @@ function RenderMessageContentInternal({
edited,
getContent,
mediaAutoLoad,
isGallery,
bundledPreview,
urlPreview,
clientUrlPreview,
@@ -260,9 +264,18 @@ function RenderMessageContentInternal({
style={{
display: 'flex',
flexDirection: attachmentDirection,
width: '100%',
height: '100%',
}}
>
<div>{attachment}</div>
<div
style={{
width: '100%',
height: '100%',
}}
>
{attachment}
</div>
{renderCaption()}
</div>
);
@@ -272,6 +285,7 @@ function RenderMessageContentInternal({
renderCaptionedAttachment(
<MFile
content={content as Record<string, never> & { msgtype: MsgType.File }}
fitParent={isGallery}
renderFileContent={({ body, mimeType, info, encInfo, url }) => (
<FileContent
body={body}
@@ -368,6 +382,7 @@ function RenderMessageContentInternal({
return renderCaptionedAttachment(
<MImage
content={content as Record<string, never> & { msgtype: MsgType.Image }}
fitParent={isGallery}
renderImageContent={(imageProps) => (
<ImageContent
{...imageProps}
@@ -395,6 +410,7 @@ function RenderMessageContentInternal({
<MVideo
content={content as Record<string, never> & { msgtype: MsgType.Video }}
renderAsFile={renderFile}
fitParent={isGallery}
renderVideoContent={({ body, info, ...videoProps }) => (
<VideoContent
body={body}
@@ -429,6 +445,7 @@ function RenderMessageContentInternal({
<AudioContent {...audioProps} renderMediaControl={(p) => <MediaControl {...p} />} />
)}
outlined={outlineAttachment}
fitParent={isGallery}
/>
);
}
@@ -436,6 +453,51 @@ function RenderMessageContentInternal({
if (msgType === (MsgType.File as string)) return renderFile();
if (msgType === (MsgType.Location as string))
return <MLocation showMaps={showMaps} content={content} />;
if (msgType === GALLERY_MSGTYPE) {
const galleryContent = getContent() as IGalleryContent;
return (
<MGallery
content={galleryContent}
renderItem={(itemContent) => (
<RenderMessageContent
displayName={displayName}
msgType={itemContent.msgtype as string}
ts={ts}
getContent={() => itemContent}
mediaAutoLoad={mediaAutoLoad}
urlPreview={urlPreview}
highlightRegex={highlightRegex}
htmlReactParserOptions={htmlReactParserOptions}
linkifyOpts={linkifyOpts}
outlineAttachment={outlineAttachment}
isGallery={true}
/>
)}
renderCaption={
galleryContent.body
? () => (
<MText
style={{ marginTop: config.space.S200 }}
edited={edited}
content={galleryContent}
renderBody={(props) => (
<RenderBody
{...props}
highlightRegex={highlightRegex}
htmlReactParserOptions={htmlReactParserOptions}
linkifyOpts={linkifyOpts}
/>
)}
renderUrlsPreview={urlPreview ? renderUrlsPreview : undefined}
/>
)
: undefined
}
/>
);
}
if (msgType === 'm.bad.encrypted') return <MBadEncrypted />;
// cute events
+1 -1
View File
@@ -4,7 +4,7 @@ import { DefaultReset } from 'folds';
export const Image = style([
DefaultReset,
{
objectFit: 'contain',
objectFit: 'cover',
width: '100%',
height: '100%',
},
@@ -0,0 +1,62 @@
import { recipe } from '@vanilla-extract/recipes';
import { style } from '@vanilla-extract/css';
import { DefaultReset, color, config, toRem } from 'folds';
export const GalleryHolder = style({
position: 'relative',
marginTop: config.space.S200,
});
export const GalleryItem = style({
width: toRem(300),
height: toRem(200),
flexShrink: 0,
overflow: 'hidden',
borderRadius: config.radii.R300,
});
export const GalleryHolderGradient = recipe({
base: [
DefaultReset,
{
position: 'absolute',
height: '100%',
width: toRem(10),
zIndex: 1,
},
],
variants: {
position: {
Left: {
left: 0,
background: `linear-gradient(to right,${color.Surface.Container} , rgba(116,116,116,0))`,
},
Right: {
right: 0,
background: `linear-gradient(to left,${color.Surface.Container} , rgba(116,116,116,0))`,
},
},
},
});
export const GalleryHolderBtn = recipe({
base: [
DefaultReset,
{
position: 'absolute',
zIndex: 1,
},
],
variants: {
position: {
Left: {
left: 0,
transform: 'translateX(-25%)',
},
Right: {
right: 0,
transform: 'translateX(25%)',
},
},
},
});
+134
View File
@@ -0,0 +1,134 @@
import type { ReactNode } from 'react';
import React, { useCallback, useEffect, useRef, useState } from 'react';
import { Box, Icon, IconButton, Icons, Scroll } from 'folds';
import type { IContent } from 'matrix-js-sdk';
import type { IGalleryContent, IGalleryItem } from '$types/matrix/common';
import {
getIntersectionObserverEntry,
useIntersectionObserver,
} from '$hooks/useIntersectionObserver';
import * as css from './MGallery.css';
function galleryItemToContent(item: IGalleryItem): IContent {
const { itemtype, ...rest } = item;
return { ...rest, msgtype: itemtype } as IContent;
}
type MGalleryProps = {
content: IGalleryContent;
renderItem: (content: IContent, index: number) => ReactNode;
renderCaption?: () => ReactNode;
};
export function MGallery({ content, renderItem, renderCaption }: MGalleryProps) {
const scrollRef = useRef<HTMLDivElement>(null);
const backAnchorRef = useRef<HTMLDivElement>(null);
const frontAnchorRef = useRef<HTMLDivElement>(null);
const [backVisible, setBackVisible] = useState(true);
const [frontVisible, setFrontVisible] = useState(true);
const intersectionObserver = useIntersectionObserver(
useCallback((entries) => {
const backAnchor = backAnchorRef.current;
const frontAnchor = frontAnchorRef.current;
const backEntry = backAnchor && getIntersectionObserverEntry(backAnchor, entries);
const frontEntry = frontAnchor && getIntersectionObserverEntry(frontAnchor, entries);
if (backEntry) {
setBackVisible(backEntry.isIntersecting);
}
if (frontEntry) {
setFrontVisible(frontEntry.isIntersecting);
}
}, []),
useCallback(
() => ({
root: scrollRef.current,
rootMargin: '10px',
}),
[]
)
);
useEffect(() => {
const backAnchor = backAnchorRef.current;
const frontAnchor = frontAnchorRef.current;
if (backAnchor) intersectionObserver?.observe(backAnchor);
if (frontAnchor) intersectionObserver?.observe(frontAnchor);
return () => {
if (backAnchor) intersectionObserver?.unobserve(backAnchor);
if (frontAnchor) intersectionObserver?.unobserve(frontAnchor);
};
}, [intersectionObserver]);
const handleScrollBack = () => {
const scroll = scrollRef.current;
if (!scroll) return;
const { offsetWidth, scrollLeft } = scroll;
scroll.scrollTo({
left: scrollLeft - offsetWidth / 1.3,
behavior: 'smooth',
});
};
const handleScrollFront = () => {
const scroll = scrollRef.current;
if (!scroll) return;
const { offsetWidth, scrollLeft } = scroll;
scroll.scrollTo({
left: scrollLeft + offsetWidth / 1.3,
behavior: 'smooth',
});
};
const items = content.itemtypes;
return (
<Box direction="Column">
<Box className={css.GalleryHolder} direction="Column" style={{ position: 'relative' }}>
<Scroll ref={scrollRef} direction="Horizontal" size="0" visibility="Hover" hideTrack>
<Box shrink="No" alignItems="Center">
<div ref={backAnchorRef} />
{!backVisible && (
<>
<div className={css.GalleryHolderGradient({ position: 'Left' })} />
<IconButton
className={css.GalleryHolderBtn({ position: 'Left' })}
variant="Secondary"
radii="Pill"
size="300"
outlined
onClick={handleScrollBack}
>
<Icon size="300" src={Icons.ArrowLeft} />
</IconButton>
</>
)}
<Box alignItems="Inherit" gap="200">
{items.map((item, index) => (
<div key={item.url ?? item.file?.url ?? index} className={css.GalleryItem}>
{renderItem(galleryItemToContent(item), index)}
</div>
))}
{!frontVisible && (
<>
<div className={css.GalleryHolderGradient({ position: 'Right' })} />
<IconButton
className={css.GalleryHolderBtn({ position: 'Right' })}
variant="Primary"
radii="Pill"
size="300"
outlined
onClick={handleScrollFront}
>
<Icon size="300" src={Icons.ArrowRight} />
</IconButton>
</>
)}
<div ref={frontAnchorRef} />
</Box>
</Box>
</Scroll>
</Box>
{renderCaption?.()}
</Box>
);
}
+39 -10
View File
@@ -432,8 +432,9 @@ type MImageProps = {
content: IImageContent;
renderImageContent: (props: RenderImageContentProps) => ReactNode;
outlined?: boolean;
fitParent?: boolean;
};
export function MImage({ content, renderImageContent, outlined }: MImageProps) {
export function MImage({ content, renderImageContent, outlined, fitParent }: MImageProps) {
const imgInfo = content?.info;
const mxcUrl = content.file?.url ?? content.url;
if (typeof mxcUrl !== 'string') {
@@ -445,20 +446,23 @@ export function MImage({ content, renderImageContent, outlined }: MImageProps) {
const aspectRatio = imgInfo?.w && imgInfo?.h ? `${imgW} / ${imgH}` : undefined;
// this garbage is for portrait images, we cap the width so the card doesn't exceed the bounds of the image
const displayWidth = imgH > imgW ? Math.round(MAX_SIZE * (imgW / imgH)) : MAX_SIZE;
const height = scaleYDimension(imgInfo?.w || 400, displayWidth, imgInfo?.h || 400);
return (
<Attachment
style={{
flexGrow: 1,
flexShrink: 0,
width: toRem(displayWidth),
width: fitParent ? '100%' : toRem(displayWidth),
height: fitParent ? '100%' : 'auto',
}}
outlined={outlined}
>
<AttachmentBox
style={{
flexGrow: 1,
aspectRatio,
maxHeight: toRem(MAX_SIZE),
width: fitParent ? '100%' : toRem(displayWidth),
height: fitParent ? '100%' : toRem(height < 48 ? 48 : height),
}}
>
{renderImageContent({
@@ -489,8 +493,15 @@ type MVideoProps = {
renderAsFile: () => ReactNode;
renderVideoContent: (props: RenderVideoContentProps) => ReactNode;
outlined?: boolean;
fitParent?: boolean;
};
export function MVideo({ content, renderAsFile, renderVideoContent, outlined }: MVideoProps) {
export function MVideo({
content,
renderAsFile,
renderVideoContent,
outlined,
fitParent,
}: MVideoProps) {
const videoInfo = content?.info;
const mxcUrl = content.file?.url ?? content.url;
const safeMimeType = getBlobSafeMimeType(videoInfo?.mimetype ?? '');
@@ -502,6 +513,7 @@ export function MVideo({ content, renderAsFile, renderVideoContent, outlined }:
return <BrokenContent body={content.body ?? content.filename} />;
}
const displayWidth = Math.min(videoInfo.w || 400, 400);
const height = Math.min(scaleYDimension(videoInfo.w || 400, 400, videoInfo.h || 400), 400);
const filename = content.filename ?? content.body ?? 'Video';
@@ -511,6 +523,8 @@ export function MVideo({ content, renderAsFile, renderVideoContent, outlined }:
style={{
flexGrow: 1,
flexShrink: 0,
width: fitParent ? '100%' : toRem(displayWidth),
height: fitParent ? '100%' : 'auto',
}}
outlined={outlined}
>
@@ -530,7 +544,8 @@ export function MVideo({ content, renderAsFile, renderVideoContent, outlined }:
</AttachmentHeader>
<AttachmentBox
style={{
height: toRem(height < 48 ? 48 : height),
width: fitParent ? '100%' : toRem(displayWidth),
height: fitParent ? '100%' : toRem(height < 48 ? 48 : height),
}}
>
{renderVideoContent({
@@ -580,8 +595,15 @@ type MAudioProps = {
renderAsFile: () => ReactNode;
renderAudioContent: (props: RenderAudioContentProps) => ReactNode;
outlined?: boolean;
fitParent?: boolean;
};
export function MAudio({ content, renderAsFile, renderAudioContent, outlined }: MAudioProps) {
export function MAudio({
content,
renderAsFile,
renderAudioContent,
outlined,
fitParent,
}: MAudioProps) {
const audioInfo = content?.info;
const mxcUrl = content.file?.url ?? content.url;
const safeMimeType = getBlobSafeMimeType(audioInfo?.mimetype ?? '');
@@ -598,7 +620,10 @@ export function MAudio({ content, renderAsFile, renderAudioContent, outlined }:
const resolvedInfo =
durationMs !== undefined ? { ...audioInfo, duration: durationMs } : audioInfo;
return (
<Attachment outlined={outlined}>
<Attachment
outlined={outlined}
style={{ width: fitParent ? '100%' : toRem(400), height: fitParent ? '100%' : 'auto' }}
>
<AttachmentHeader>
<FileHeader
body={filename}
@@ -638,8 +663,9 @@ type MFileProps = {
content: IFileContent;
renderFileContent: (props: RenderFileContentProps) => ReactNode;
outlined?: boolean;
fitParent?: boolean;
};
export function MFile({ content, renderFileContent, outlined }: MFileProps) {
export function MFile({ content, renderFileContent, outlined, fitParent }: MFileProps) {
const fileInfo = content?.info;
const mxcUrl = content.file?.url ?? content.url;
@@ -648,7 +674,10 @@ export function MFile({ content, renderFileContent, outlined }: MFileProps) {
}
return (
<Attachment outlined={outlined}>
<Attachment
outlined={outlined}
style={{ width: fitParent ? '100%' : toRem(400), height: fitParent ? '100%' : 'auto' }}
>
<AttachmentHeader>
<FileHeader
body={content.filename ?? content.body ?? 'Unnamed File'}
+1
View File
@@ -10,3 +10,4 @@ export * from './Time';
export * from './MsgTypeRenderers';
export * from './FileHeader';
export * from './RenderBody';
export * from './MGallery';
+48
View File
@@ -170,6 +170,8 @@ import {
getImageMsgContent,
getVideoMsgContent,
getGifMsgContent,
buildGalleryContent,
getGalleryItemContent,
} from './msgContent';
import { outgoingMessageTransforms } from './outgoingMessageTransforms';
import { getKlipyMxcUrl } from '$utils/klipy';
@@ -437,6 +439,7 @@ export const RoomInput = forwardRef<HTMLDivElement, RoomInputProps>(
const [sendError, setSendError] = useState<string | undefined>();
const isEncrypted = room.hasEncryptionStateEvent();
const [emojiBoardTab, setEmojiBoardTab] = useState<EmojiBoardTab | undefined>(undefined);
const [enableMediaGalleries] = useSetting(settingsAtom, 'enableMediaGalleries');
useElementSizeObserver(
useCallback(() => fileDropContainerRef.current, [fileDropContainerRef]),
@@ -677,6 +680,44 @@ export const RoomInput = forwardRef<HTMLDivElement, RoomInputProps>(
};
const handleSendUpload = async (uploads: UploadSuccess[]) => {
if (uploads.length >= 2 && enableMediaGalleries) {
const plainText = toPlainText(editor.children).trim();
const caption = plainText.length > 0 ? plainText : undefined;
let customHtml = trimCustomHtml(
toMatrixCustomHTML(editor.children, {
stripNickname: true,
room,
})
);
const formattedCaption =
caption && !customHtmlEqualsPlainText(customHtml, plainText) ? customHtml : undefined;
const itemsPromises = uploads.map(async (upload) => {
const fileItem = selectedFiles.find((f) => f.file === upload.file);
if (!fileItem) throw new Error('Broken upload');
return getGalleryItemContent(mx, fileItem, upload.mxc);
});
handleCancelUpload(uploads);
const items = fulfilledPromiseSettledResult(await Promise.allSettled(itemsPromises));
if (items.length === 0) return;
const galleryContent = buildGalleryContent(items, caption, formattedCaption);
const mentionData = getMentions(mx, roomId, editor);
if (replyDraft && replyDraft.userId !== mx.getUserId()) {
mentionData.users.add(replyDraft.userId);
}
const mMentions = getMentionContent(Array.from(mentionData.users), mentionData.room);
galleryContent['m.mentions'] = mMentions;
if (replyDraft) {
galleryContent['m.relates_to'] = getReplyContent(replyDraft);
}
await handleSendContents([galleryContent]);
return;
}
const contentsPromises = uploads.map(async (upload) => {
const fileItem = selectedFiles.find((f) => f.file === upload.file);
if (!fileItem) throw new Error('Broken upload');
@@ -735,6 +776,12 @@ export const RoomInput = forwardRef<HTMLDivElement, RoomInputProps>(
const submit = useCallback(async () => {
uploadBoardHandlers.current?.handleSend();
if (selectedFiles.length >= 2) {
resetEditor(editor);
resetEditorHistory(editor);
sendTypingStatus(false);
return;
}
const commandName = getBeginCommand(editor);
/**
@@ -1124,6 +1171,7 @@ export const RoomInput = forwardRef<HTMLDivElement, RoomInputProps>(
setScheduledTime,
setServerMaxDelayMs,
replyDraftBase,
selectedFiles,
]);
const handleKeyDown: KeyboardEventHandler = useCallback(
+51 -1
View File
@@ -1,7 +1,8 @@
import type { IContent, MatrixClient } from '$types/matrix-sdk';
import { MsgType } from '$types/matrix-sdk';
import to from 'await-to-js';
import type { IThumbnailContent } from '$types/matrix/common';
import type { IGalleryItem } from '$types/matrix/common';
import { GALLERY_MSGTYPE, type IThumbnailContent } from '$types/matrix/common';
import {
getImageFileUrl,
getThumbnail,
@@ -288,3 +289,52 @@ export const getGifMsgContent = async (
return content;
};
const swapMsgTypeToItemType = (
content: IContent,
itemtype: IGalleryItem['itemtype']
): IGalleryItem => {
const result = { ...content, itemtype };
delete result.msgtype;
return result as IGalleryItem;
};
export const getGalleryItemContent = async (
mx: MatrixClient,
item: TUploadItem,
mxc: string
): Promise<IGalleryItem> => {
if (item.file.type.startsWith('image')) {
return swapMsgTypeToItemType(await getImageMsgContent(mx, item, mxc), MsgType.Image);
}
if (item.file.type.startsWith('video')) {
return swapMsgTypeToItemType(await getVideoMsgContent(mx, item, mxc), MsgType.Video);
}
if (item.file.type.startsWith('audio')) {
return swapMsgTypeToItemType(getAudioMsgContent(item, mxc), MsgType.Audio);
}
return swapMsgTypeToItemType(getFileMsgContent(item, mxc), MsgType.File);
};
export const buildGalleryContent = (
items: IGalleryItem[],
caption?: string,
formattedCaption?: string
): IContent => {
const body =
caption ||
items.map((item) => `[${item.filename ?? item.itemtype}: ${item.url ?? 'file'}]`).join('\n');
const content: IContent = {
msgtype: GALLERY_MSGTYPE,
body,
itemtypes: items,
};
if (formattedCaption) {
content.format = 'org.matrix.custom.html';
content.formatted_body = formattedCaption;
}
return content;
};
@@ -11,6 +11,7 @@ import { Sync } from '../general';
import { SettingsSectionPage } from '../SettingsSectionPage';
import { BandwidthSavingEmojis } from './BandwithSavingEmojis';
import { MSC4268HistoryShare } from './MSC4268HistoryShare';
import { MSC4274MediaGalleries } from './MSC4274MediaGalleries';
function PersonaToggle() {
const [showPersonaSetting, setShowPersonaSetting] = useSetting(
@@ -63,6 +64,7 @@ export function Experimental({ requestBack, requestClose }: Readonly<Experimenta
<MSC4268HistoryShare />
<BandwidthSavingEmojis />
<PersonaToggle />
<MSC4274MediaGalleries />
</Box>
</PageContent>
</Scroll>
@@ -0,0 +1,39 @@
import { SequenceCard } from '$components/sequence-card';
import { SettingTile } from '$components/setting-tile';
import { useSetting } from '$state/hooks/settings';
import { settingsAtom } from '$state/settings';
import { Box, Switch, Text } from 'folds';
import { SequenceCardStyle } from '../styles.css';
export function MSC4274MediaGalleries() {
const [enabledMediaGalleries, setEnabledMediaGalleries] = useSetting(
settingsAtom,
'enableMediaGalleries'
);
return (
<Box direction="Column" gap="100">
<Text size="L400">Enable Media Galleries Support</Text>
<SequenceCard
className={SequenceCardStyle}
variant="SurfaceVariant"
direction="Column"
gap="100"
>
<SettingTile
title="Enable Media Galleries"
focusId="media-galleries"
description="If enabled, multiple attachments will be sent in one message, as per MSC4274. Incompatible with clients that don't implement it."
after={
<Switch
variant="Primary"
value={enabledMediaGalleries}
onChange={setEnabledMediaGalleries}
title={enabledMediaGalleries ? 'Disable Media Galleries' : 'Enable Media Galleries'}
/>
}
/>
</SequenceCard>
</Box>
);
}
+6 -1
View File
@@ -201,7 +201,12 @@ const settingsLinkFocusIdsBySection: Record<SettingsSectionId, readonly string[]
'session-replay',
'traces-profiles',
],
experimental: ['bandwidth-saving-emojis', 'sharehistory-command', 'show-personas-tab'],
experimental: [
'bandwidth-saving-emojis',
'sharehistory-command',
'show-personas-tab',
'media-galleries',
],
about: [
'base-url',
'clear-cache-and-reload',
+2
View File
@@ -141,6 +141,7 @@ export interface Settings {
developerTools: boolean;
enableMSC4268CMD: boolean;
enableMediaGalleries: boolean;
settingsSyncEnabled: boolean;
// Cosmetics!
@@ -280,6 +281,7 @@ export const defaultSettings: Settings = {
legacyUsernameColor: false,
enableMSC4268CMD: false,
enableMediaGalleries: false,
// Push notifications (SW/Sygnal): default on for mobile, opt-in on desktop.
// In-app pill banner: default on for mobile (primary foreground alert), opt-in on desktop.
+20
View File
@@ -142,3 +142,23 @@ export type ILocationContent = {
geo_uri?: string;
info?: IThumbnailContent;
};
export type IGalleryImageItem = Omit<IImageContent, 'msgtype'> & { itemtype: MsgType.Image };
export type IGalleryVideoItem = Omit<IVideoContent, 'msgtype'> & { itemtype: MsgType.Video };
export type IGalleryAudioItem = Omit<IAudioContent, 'msgtype'> & { itemtype: MsgType.Audio };
export type IGalleryFileItem = Omit<IFileContent, 'msgtype'> & { itemtype: MsgType.File };
export type IGalleryItem =
| IGalleryImageItem
| IGalleryVideoItem
| IGalleryAudioItem
| IGalleryFileItem;
export const GALLERY_MSGTYPE = 'dm.filament.gallery';
export type IGalleryContent = {
msgtype: typeof GALLERY_MSGTYPE;
body: string;
format?: string;
formatted_body?: string;
itemtypes: IGalleryItem[];
};