import type { CSSProperties } from 'react'; import { memo, useMemo, useCallback } from 'react'; import type { IPreviewUrlResponse, MatrixClient, MatrixEvent, Room } from '$types/matrix-sdk'; import { MsgType } from '$types/matrix-sdk'; import { parseSettingsLink } from '$features/settings/settingsLink'; import { useSettingsLinkBaseUrl } from '$features/settings/useSettingsLinkBaseUrl'; import { testMatrixTo } from '$plugins/matrix-to'; import { testMatrixUri } from '$plugins/matrix-uri'; import { useSetting } from '$state/hooks/settings'; import { settingsAtom, CaptionPosition } from '$state/settings'; import type { HTMLReactParserOptions } from 'html-react-parser'; import type { Opts } from 'linkifyjs'; import { Box, config } from 'folds'; import { AudioContent, DownloadFile, FileContent, ImageContent, MAudio, MBadEncrypted, MEmote, MFile, MImage, MLocation, MNotice, MText, MVideo, MGallery, ReadPdfFile, ReadTextFile, RenderBody, ThumbnailContent, UnsupportedContent, UploadedSableCssContent, VideoContent, } from './message'; import { UrlPreviewCard, UrlPreviewHolder, ClientPreview, ThemePreviewUrlCard, TweakPreviewUrlCard, youtubeUrl, } from './url-preview'; import { isHttpsFullSableCssUrl } from '../theme/previewUrls'; import { isSableCssAttachmentFileName } from '../theme/processThemeImport'; import { Image, MediaControl, PersistedVolumeVideo } from './media'; import { ImageViewer } from './image-viewer'; import { PdfViewer } from './Pdf-viewer'; import { TextViewer } from './text-viewer'; 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, IGalleryContent } from '$types/matrix/common'; import { GALLERY_MSGTYPE } from '$types/matrix/common'; type RenderMessageContentProps = { displayName: string; msgType: string; ts: number; edited?: boolean; getContent: () => unknown; mediaAutoLoad?: boolean; bundledPreview?: boolean; urlPreview?: boolean; clientUrlPreview?: boolean; isGallery?: boolean; showMaps?: boolean; highlightRegex?: RegExp; htmlReactParserOptions: HTMLReactParserOptions; linkifyOpts: Opts; outlineAttachment?: boolean; hideCaption?: boolean; mEvent?: MatrixEvent; mx?: MatrixClient; room?: Room; }; const getMediaType = (url: string) => { const cleanUrl = url.toLowerCase(); if (cleanUrl.match(/\.(mp4|webm|ogg)$/i)) return 'video'; if (cleanUrl.match(/\.(png|jpg|jpeg|gif|webp)$/i) || cleanUrl.match(/@(jpeg|webp|png|jpg)$/i)) return 'image'; return null; }; const isSableChatEmbedCandidate = (url: string): boolean => /^https:\/\//i.test(url) && (/\.preview\.sable\.css(\?|#|$)/i.test(url) || isHttpsFullSableCssUrl(url)); const CAPTION_STYLE: CSSProperties = { marginTop: config.space.S200, maxWidth: '100%' }; const TEXT_STYLE: CSSProperties = { maxWidth: '100%' }; function RenderMessageContentInternal({ displayName, msgType, ts, edited, getContent, mediaAutoLoad, isGallery, bundledPreview, urlPreview, clientUrlPreview, showMaps, highlightRegex, htmlReactParserOptions, linkifyOpts, outlineAttachment, hideCaption, mEvent, mx, room, }: RenderMessageContentProps) { const content = useMemo(() => getContent() as Record, [getContent]); const [autoplayGifs] = useSetting(settingsAtom, 'autoplayGifs'); const [captionPosition] = useSetting(settingsAtom, 'captionPosition'); const [themeChatSableWidgets] = useSetting(settingsAtom, 'themeChatSableWidgetsEnabled'); const [multiplePreviews] = useSetting(settingsAtom, 'multiplePreviews'); const settingsLinkBaseUrl = useSettingsLinkBaseUrl(); const captionPositionMap = { [CaptionPosition.Above]: 'column-reverse', [CaptionPosition.Below]: 'column', [CaptionPosition.Inline]: 'row', [CaptionPosition.Hidden]: 'row', } satisfies Record; const attachmentDirection = captionPositionMap[captionPosition]; const renderBody = useCallback( (props: Record) => ( ), [highlightRegex, htmlReactParserOptions, linkifyOpts] ); const renderUrlsPreview = useCallback( (urls: string[]) => { const filteredUrls = urls.filter( (url) => !testMatrixTo(url) && !testMatrixUri(url) && !parseSettingsLink(settingsLinkBaseUrl, url) ); if (filteredUrls.length === 0) return undefined; const themePreviewUrls = themeChatSableWidgets ? filteredUrls.filter( (u) => /^https:\/\//i.test(u) && /\.preview\.sable\.css(\?|#|$)/i.test(u) ) : []; const themeToRender = themePreviewUrls.filter((u) => /^https:\/\//i.test(u)); const tweakCandidateUrls = themeChatSableWidgets ? filteredUrls.filter((u) => isHttpsFullSableCssUrl(u)) : []; const analyzed = filteredUrls.map((url) => ({ url, type: getMediaType(url), })); const mediaLinks = analyzed.filter((item) => item.type !== null); const previewCandidates = mediaLinks.length > 0 ? mediaLinks : analyzed; const toRender = multiplePreviews ? previewCandidates : [previewCandidates[0]!]; return ( {themeToRender.map((url) => ( ))} {tweakCandidateUrls.map((url) => ( ))} {toRender.map((item) => { const { url } = item; if (themeToRender.includes(url)) return null; if (tweakCandidateUrls.includes(url)) return null; if (!themeChatSableWidgets && isSableChatEmbedCandidate(url)) return null; if (clientUrlPreview && youtubeUrl(url)) { return ; } if (urlPreview) { return ; } return null; })} ); }, [multiplePreviews, themeChatSableWidgets, settingsLinkBaseUrl, clientUrlPreview, urlPreview, ts] ); const renderBundledPreviews = useCallback( (bundles: IPreviewUrlResponse[]) => ( {bundles.map((bundle) => ( ))} ), [urlPreview] ); const messageUrlsPreview = urlPreview || themeChatSableWidgets ? renderUrlsPreview : undefined; const messageBundlePreview = bundledPreview ? renderBundledPreviews : undefined; const renderCaption = () => { const hasCaption = content.body && (content.body as string).trim().length > 0; if (captionPosition === CaptionPosition.Hidden || hideCaption) return null; if ( hasCaption && (((content as { filename?: string }).filename && (content as { filename?: string }).filename !== content.body) || msgType === GALLERY_MSGTYPE) ) { if (captionPosition !== CaptionPosition.Inline) return ( ); return ( ); } return null; }; function renderCaptionedAttachment(attachment: JSX.Element, isInGallery?: boolean): JSX.Element { return (
{attachment} {!isInGallery && renderCaption()}
); } const renderFile = () => renderCaptionedAttachment( & { msgtype: MsgType.File }} renderFileContent={({ fileName, mimeType, info, encInfo, url }) => ( ( } /> )} renderAsTextFile={() => ( } /> )} > {themeChatSableWidgets && isSableCssAttachmentFileName(fileName) && ( )} )} outlined={outlineAttachment} /> ); if (msgType === (MsgType.Text as string)) { return ( ); } if (msgType === (MsgType.Emote as string)) { if ((content as { 'fyi.cisnt.headpat'?: boolean })['fyi.cisnt.headpat']) { return ( ); } return ( ); } if (msgType === (MsgType.Notice as string)) { return ( ); } if (msgType === (MsgType.Image as string)) { const { info } = content as { info?: IImageInfo }; const isGif = info?.mimetype === 'image/gif' || info?.mimetype === 'image/apng' || info?.mimetype === 'image/webp' || (content.body as string)?.toLowerCase().endsWith('.gif') || (content.body as string)?.toLowerCase().endsWith('.apng') || (content.body as string)?.toLowerCase().endsWith('.webp') || (typeof (content as { url?: string }).url === 'string' && ((content as { url?: string }).url?.toLowerCase().endsWith('.gif') || (content as { url?: string }).url?.toLowerCase().endsWith('.apng') || (content as { url?: string }).url?.toLowerCase().endsWith('.webp'))); return renderCaptionedAttachment( & { msgtype: MsgType.Image }} fitParent={isGallery} renderImageContent={(imageProps) => ( { if (isGif && !autoplayGifs && p.src) { return ( ); } return ; }} renderViewer={(p) => } /> )} outlined={outlineAttachment} />, isGallery ); } if (msgType === (MsgType.Video as string)) { return renderCaptionedAttachment( & { msgtype: MsgType.Video }} renderAsFile={renderFile} renderVideoContent={({ body, info, ...videoProps }) => ( ( ( {body} )} /> ) : undefined } renderVideo={(p) => } /> )} outlined={outlineAttachment} />, isGallery ); } if (msgType === (MsgType.Audio as string)) { return renderCaptionedAttachment( & { msgtype: MsgType.Audio }} renderAsFile={renderFile} renderAudioContent={(audioProps) => ( } /> )} outlined={outlineAttachment} fitParent={isGallery} /> ); } if (msgType === (MsgType.File as string)) return renderFile(); if (msgType === (MsgType.Location as string)) return ; if (msgType === GALLERY_MSGTYPE) { return renderCaptionedAttachment( ( itemContent} mediaAutoLoad={mediaAutoLoad} urlPreview={urlPreview} highlightRegex={highlightRegex} htmlReactParserOptions={htmlReactParserOptions} linkifyOpts={linkifyOpts} outlineAttachment={outlineAttachment} isGallery={true} /> )} /> ); } if (msgType === 'm.bad.encrypted') return ; // cute events if (msgType === 'im.fluffychat.cute_event') return ( ); // as fallback to render older events where msgtype was set instead of m.emote with a custom property if (msgType === 'fyi.cisnt.headpat') return ( ); if (content['org.matrix.msc3381.poll.start']) { if (mEvent && mx && room) return ; else return ; } return ( ); } export const RenderMessageContent = memo(RenderMessageContentInternal);