/* oxlint-disable jsx-a11y/alt-text */ import type { CSSProperties, ComponentPropsWithoutRef, ReactEventHandler, ReactNode } from 'react'; import { Fragment, useEffect, useMemo, useState } from 'react'; import type { HTMLReactParserOptions } from 'html-react-parser'; import { attributesToProps, domToReact, Element, Text as DOMText } from 'html-react-parser'; import type { MatrixClient } from '$types/matrix-sdk'; import classNames from 'classnames'; import { Box, Chip, config, Header, IconButton, Scroll, Text, toRem } from 'folds'; import { CaretDown, CaretUp, ChatCircle, Check, GearSix, sizedIcon, } from '$components/icons/phosphor'; import type { IntermediateRepresentation, OptFn, Opts as LinkifyOpts } from 'linkifyjs'; import Linkify from 'linkify-react'; import type { ChildNode } from 'domhandler'; import * as css from '$styles/CustomHtml.css'; import { getCanonicalAliasRoomId, getMxIdLocalPart, isRoomAlias, mxcUrlToHttp, } from '$utils/matrix'; import { getMemberDisplayName } from '$utils/room'; import { type Nicknames } from '$state/nicknames'; import { sanitizeForRegex, URL_REG } from '$utils/regex'; import { splitEmojiText } from '$utils/emojiDetection'; import { findAndReplace } from '$utils/findAndReplace'; import { onEnterOrSpace } from '$utils/keyboard'; import { copyToClipboard } from '$utils/dom'; import { isMatrixHexColor } from '$utils/matrixHtml'; import { useTimeoutToggle } from '$hooks/useTimeoutToggle'; import { getSettingsLinkChipLabel, parseSettingsLink } from '$features/settings/settingsLink'; import { ClientSideHoverFreeze } from '$components/ClientSideHoverFreeze'; import { CodeHighlightRenderer } from '$components/code-highlight'; import { isRedundantMatrixToAnchorText, parseMatrixToRoom, parseMatrixToRoomEvent, parseMatrixToUser, testMatrixTo, } from './matrix-to'; import { isRedundantMatrixUriAnchorText, parseMatrixUri, testMatrixUri } from './matrix-uri'; import { getHexcodeForEmoji, getShortcodeFor } from './emoji'; const shouldLinkifyDomText = (domNode: DOMText): boolean => !(domNode.parent && 'name' in domNode.parent && domNode.parent.name === 'code') && !(domNode.parent && 'name' in domNode.parent && domNode.parent.name === 'a'); export const LINKIFY_OPTS: LinkifyOpts = { attributes: { target: '_blank', rel: 'noreferrer noopener', }, validate: { url: (value) => { if (/^matrix:/i.test(value)) return testMatrixUri(value); return /^(https|http|ftp|mailto|magnet)?:/.test(value); }, }, ignoreTags: ['span'], }; export const safeDecodeUrl = (url: string) => { try { return decodeURIComponent(url); } catch { return url; } }; const getMatrixColorStyle = (attribs: Record): CSSProperties | undefined => { const color = attribs['data-mx-color']; const backgroundColor = attribs['data-mx-bg-color']; const style: CSSProperties = {}; if (typeof color === 'string' && isMatrixHexColor(color)) { style.color = color; } if (typeof backgroundColor === 'string' && isMatrixHexColor(backgroundColor)) { style.backgroundColor = backgroundColor; } return Object.keys(style).length > 0 ? style : undefined; }; const stripIncomingStyle = ( attribs: Record ): Omit, 'style'> => { const { style, ...props } = attributesToProps(attribs); return props; }; const ensureNoopenerRel = (rel: unknown): string => { if (typeof rel !== 'string') return 'noopener'; const parts = rel.split(/\s+/).filter(Boolean); if (!parts.includes('noopener')) { parts.push('noopener'); } return parts.join(' '); }; function KatexRenderer({ math, displayMode, style, }: { math: string; displayMode: boolean; style?: CSSProperties; }) { const [html, setHtml] = useState(null); useEffect(() => { let mounted = true; void Promise.all([import('katex'), import('katex/dist/katex.min.css')]).then(([katex]) => { if (mounted) { setHtml(katex.default.renderToString(math, { throwOnError: false, displayMode })); } }); return () => { mounted = false; }; }, [math, displayMode]); if (html === null) { return ( {displayMode ? '$$\n' : '$'} {math} {displayMode ? '\n$$' : '$'} ); } const Tag = displayMode ? 'div' : 'span'; return ; } export const makeMentionCustomProps = ( handleMentionClick?: ReactEventHandler, content?: string ): ComponentPropsWithoutRef<'a'> => ({ style: { cursor: 'pointer' }, target: '_blank', rel: 'noreferrer noopener', role: 'link', tabIndex: handleMentionClick ? 0 : -1, onKeyDown: handleMentionClick ? onEnterOrSpace(handleMentionClick) : undefined, onClick: handleMentionClick, children: content, }); const matrixPermalinkDisplayLabel = ( href: string, customChildren: ReactNode | undefined, fallback: ReactNode ): ReactNode => { if (customChildren === undefined || customChildren === null) return fallback; if (typeof customChildren === 'string') { const redundant = isRedundantMatrixToAnchorText(href, customChildren) || isRedundantMatrixUriAnchorText(href, customChildren); return redundant ? fallback : customChildren; } return customChildren; }; export const renderMatrixMention = ( mx: MatrixClient, currentRoomId: string | undefined, href: string, customProps: ComponentPropsWithoutRef<'a'>, nicknames?: Nicknames ) => { const matrixUri = parseMatrixUri(href); const userId = parseMatrixToUser(href) ?? (matrixUri?.kind === 'user' ? matrixUri.userId : undefined); if (userId) { const currentRoom = mx.getRoom(currentRoomId); return ( {`@${ (currentRoom && getMemberDisplayName(currentRoom, userId, nicknames)) ?? getMxIdLocalPart(userId) }`} ); } const matrixToRoom = parseMatrixToRoom(href) ?? (matrixUri?.kind === 'room' ? matrixUri.room : undefined); if (matrixToRoom) { const { roomIdOrAlias, viaServers } = matrixToRoom; const mentionRoom = mx.getRoom( isRoomAlias(roomIdOrAlias) ? getCanonicalAliasRoomId(mx, roomIdOrAlias) : roomIdOrAlias ); const fallbackContent = mentionRoom ? `#${mentionRoom.name}` : roomIdOrAlias; const label = matrixPermalinkDisplayLabel(href, customProps.children, fallbackContent); return ( {label} ); } const matrixToRoomEvent = parseMatrixToRoomEvent(href) ?? (matrixUri?.kind === 'event' ? matrixUri.event : undefined); if (matrixToRoomEvent) { const { roomIdOrAlias, eventId, viaServers } = matrixToRoomEvent; const mentionRoom = mx.getRoom( isRoomAlias(roomIdOrAlias) ? getCanonicalAliasRoomId(mx, roomIdOrAlias) : roomIdOrAlias ); let fallbackContent = mentionRoom ? `#${mentionRoom.name}` : roomIdOrAlias; if (mentionRoom) { const linkedEvent = mentionRoom.findEventById?.(eventId); if (linkedEvent) { const raw = linkedEvent.getContent() as { body?: unknown }; const body = typeof raw.body === 'string' ? raw.body.trim() : ''; if (body) { const singleLine = body.replace(/\s+/g, ' '); const short = singleLine.length > 72 ? `${singleLine.slice(0, 69)}…` : singleLine; fallbackContent = `#${mentionRoom.name}: ${short}`; } } } const label = matrixPermalinkDisplayLabel(href, customProps.children, fallbackContent); return ( {label} ); } return undefined; }; const renderSettingsLink = ({ href, section, focus, handleMentionClick, }: { href: string; section: Parameters[0]; focus?: string; handleMentionClick?: ReactEventHandler; }) => ( {getSettingsLinkChipLabel(section, focus)} ); export const factoryRenderLinkifyWithMention = ( settingsLinkBaseUrl: string, mentionRender: (href: string) => JSX.Element | undefined, handleMentionClick?: ReactEventHandler ): OptFn<(ir: IntermediateRepresentation) => unknown> => { const renderLink: OptFn<(ir: IntermediateRepresentation) => unknown> = ({ tagName, attributes, content, }) => { const encodedHref = attributes.href; const decodedHref = encodedHref && safeDecodeUrl(encodedHref); if ( tagName === 'a' && decodedHref && (testMatrixTo(decodedHref) || testMatrixUri(decodedHref)) ) { const mention = mentionRender(decodedHref); if (mention) return mention; } if (tagName === 'a' && decodedHref) { const settingsLink = parseSettingsLink(settingsLinkBaseUrl, decodedHref); if (settingsLink) { const { section, focus } = settingsLink; return renderSettingsLink({ href: decodedHref, section, focus, handleMentionClick, }); } } return ( {content} ); }; return renderLink; }; const scaleEmojiChunk = (text: string, output: (string | JSX.Element)[]) => { splitEmojiText(text).forEach((part) => { if (part.type === 'text') { output.push(part.value); return; } output.push( {part.value} ); }); }; export const scaleSystemEmoji = (text: string): (string | JSX.Element)[] => { const parts: (string | JSX.Element)[] = []; const urlReg = new RegExp(URL_REG); let lastIndex = 0; [...text.matchAll(urlReg)].forEach((match) => { const start = match.index ?? 0; scaleEmojiChunk(text.slice(lastIndex, start), parts); parts.push(match[0]); lastIndex = start + match[0].length; }); scaleEmojiChunk(text.slice(lastIndex), parts); const normalized: (string | JSX.Element)[] = []; parts.forEach((part) => { if (typeof part !== 'string') { normalized.push(part); return; } if (part === '') return; const previous = normalized.at(-1); if (typeof previous === 'string') { normalized[normalized.length - 1] = `${previous}${part}`; return; } normalized.push(part); }); return normalized.length > 0 ? normalized : ['']; }; export const makeHighlightRegex = (highlights: string[]): RegExp | undefined => { const pattern = highlights.map(sanitizeForRegex).join('|'); if (!pattern) return undefined; return new RegExp(pattern, 'gi'); }; export const highlightText = ( regex: RegExp, data: (string | JSX.Element)[] ): (string | JSX.Element)[] => data.flatMap((text) => { if (typeof text !== 'string') return text; return findAndReplace( text, regex, (match, pushIndex) => ( {match[0]} ), (txt) => txt ); }); const extractTextFromNodes = (n: ChildNode[]): string => { let text = ''; n.forEach((node) => { if ((node.type as unknown as string) === 'text') { text += (node as unknown as Text).data; } else if (node instanceof Element && node.children) { text += extractTextFromNodes(node.children); } }); return text; }; /** * Recursively extracts and concatenates all text content from an array of ChildNode objects. * * @param {ChildNode[]} nodes - An array of ChildNode objects to extract text from. * @returns {string} The concatenated plain text content of all descendant text nodes. */ const extractTextFromChildren = (nodes: ChildNode[]): string => extractTextFromNodes(nodes).replace(/\n$/, ''); const getLanguageFromClassName = (className?: string): string | undefined => { if (!className) return undefined; return className .split(/\s+/) .find((token) => token.startsWith('language-')) ?.replace('language-', ''); }; const getCodeBlockLanguage = ( children: ChildNode[], attribs?: Record ): string | undefined => { const code = children.find((child) => child instanceof Element && child.name === 'code'); const codeAttribs = code instanceof Element ? code.attribs : undefined; return ( codeAttribs?.['data-lang'] ?? attribs?.['data-lang'] ?? getLanguageFromClassName(codeAttribs?.class) ?? getLanguageFromClassName(attribs?.class) ); }; export function CodeBlock({ children, attribs, opts, }: { children: ChildNode[]; attribs?: Record; opts: HTMLReactParserOptions; }) { const language = getCodeBlockLanguage(children, attribs); const LINE_LIMIT = 14; const largeCodeBlock = useMemo( () => extractTextFromChildren(children).split('\n').length > LINE_LIMIT, [children] ); const [expanded, setExpand] = useState(false); const [copied, setCopied] = useTimeoutToggle(); const handleCopy = () => { void copyToClipboard(extractTextFromChildren(children)); setCopied(); }; const toggleExpand = () => { setExpand(!expanded); }; return (
{language ?? 'Code'} {copied ? 'Copied' : 'Copy'} {largeCodeBlock && ( {sizedIcon(expanded ? CaretUp : CaretDown, '50')} )}
{domToReact(children as unknown as Parameters[0], opts)}
{largeCodeBlock && !expanded && }
); } /** * Thin wrapper around that gracefully swaps in a fallback node when the * image fails to load (e.g. federation down, mxc URL unavailable). Avoids the * silent browser broken-image icon showing up in message bodies. */ function FallbackImg({ fallback, ...props }: ComponentPropsWithoutRef<'img'> & { fallback: ReactNode }) { const [failed, setFailed] = useState(false); if (failed) return <>{fallback}; return setFailed(true)} />; } export const getReactCustomHtmlParser = ( mx: MatrixClient, roomId: string | undefined, params: { settingsLinkBaseUrl: string; linkifyOpts: LinkifyOpts; highlightRegex?: RegExp; handleSpoilerClick?: ReactEventHandler; handleMentionClick?: ReactEventHandler; useAuthentication?: boolean; nicknames?: Nicknames; autoplayEmojis?: boolean; incomingInlineImagesDefaultHeight?: number; incomingInlineImagesMaxHeight?: number; replaceTextNode?: ( text: string, renderText: (text: string, key?: string) => JSX.Element ) => JSX.Element | undefined; } ): 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); if (params.highlightRegex) { jsx = highlightText(params.highlightRegex, jsx); } return jsx; }; const renderReplacementText = (text: string, linkify: boolean, key?: string): JSX.Element => { const decoratedText = decorateText(text); if (linkify) { return ( {decoratedText} ); } return {decoratedText}; }; const opts: HTMLReactParserOptions = { replace: (domNode) => { if (replaceTextNode && domNode instanceof DOMText) { const replacement = replaceTextNode(domNode.data, (text, key) => renderReplacementText(text, shouldLinkifyDomText(domNode), key) ); if (replacement !== undefined) { return replacement; } } if (domNode instanceof Element && 'name' in domNode) { const { name, attribs, children, parent } = domNode; const renderChildren = () => domToReact(children as unknown as Parameters[0], opts); const props = stripIncomingStyle(attribs); const matrixColorStyle = getMatrixColorStyle(attribs); if (name === 'h1') { return ( {renderChildren()} ); } if (name === 'h2') { return ( {renderChildren()} ); } if (name === 'h3') { return ( {renderChildren()} ); } if (name === 'h4') { return ( {renderChildren()} ); } if (name === 'h5') { return ( {renderChildren()} ); } if (name === 'h6') { return ( {renderChildren()} ); } if (name === 'p') { if (parent instanceof Element && parent.name === 'li') { return <>{renderChildren()}; } return ( {renderChildren()} ); } if (name === 'sub') { return ( {renderChildren()} ); } if (name === 'hr') { return
; } if (name === 'pre') { return ( {children} ); } if (name === 'blockquote') { return ( {renderChildren()} ); } if (name === 'ul') { return (
    {renderChildren()}
); } if (name === 'ol') { return (
    {renderChildren()}
); } if (name === 'code') { if (parent && 'name' in parent && parent.name === 'pre') { const codeContent = renderChildren(); if (typeof codeContent !== 'string') { return undefined; } const language = getCodeBlockLanguage( parent instanceof Element ? parent.children : [], parent instanceof Element ? parent.attribs : undefined ); const trimmedCode = codeContent.replace(/\n$/, ''); return ( ); } return ( {renderChildren()} ); } if (name === 'a' && typeof props.href === 'string') { const encodedHref = props.href; const decodedHref = encodedHref && safeDecodeUrl(encodedHref); const renderedChildren = renderChildren(); const anchorProps = { ...props, target: '_blank', rel: ensureNoopenerRel(props.rel), }; const content = children.find((child) => !(child instanceof DOMText)) ? undefined : children.map((c) => (c instanceof DOMText ? c.data : '')).join(); if (decodedHref && (testMatrixTo(decodedHref) || testMatrixUri(decodedHref))) { const mention = renderMatrixMention( mx, roomId, decodedHref, makeMentionCustomProps(params.handleMentionClick, content), params.nicknames ); if (mention) return mention; } if (decodedHref) { const settingsLink = parseSettingsLink(params.settingsLinkBaseUrl, decodedHref); if (settingsLink) { const { section, focus } = settingsLink; return renderSettingsLink({ href: decodedHref, section, focus, handleMentionClick: params.handleMentionClick, }); } } return {renderedChildren}; } if (name === 'span' && 'data-mx-spoiler' in props) { return ( {renderChildren()} ); } if (name === 'span' && 'data-mx-maths' in props) { const math = props['data-mx-maths']; if (typeof math === 'string') { return ; } } if (name === 'div' && 'data-mx-maths' in props) { const math = props['data-mx-maths']; if (typeof math === 'string') { return ; } } if (name === 'span' && matrixColorStyle) { return ( {renderChildren()} ); } if (name === 'img') { // Guard: img without a src survives sanitisation (fix for crash #1731) // but we can't convert it  Eskip rendering rather than passing // undefined into mxcUrlToHttp where it would throw. if (!props.src) return null; const htmlSrc = mxcUrlToHttp(mx, props.src, params.useAuthentication) ?? undefined; const fallbackLabel = props.alt || props.title || '[media]'; const failedToResolveMxc = props.src.startsWith('mxc://') && !htmlSrc; // Non-mxc images were already converted to links by the sanitiser, // but handle the edge case defensively here too. if (htmlSrc && !props.src.startsWith('mxc://')) { return ( {props.alt || props.title || htmlSrc} ); } if ('data-mx-emoticon' in props) { // When the mxc URL can't be resolved (e.g. federation unavailable), // fall back to rendering the shortcode text so the message stays readable. if (!htmlSrc) { const label = props.alt || props.title || ''; return ( {label ? `:${label}:` : ''} ); } const height = normalizeIncomingImgHeight(props.height); const siblingCount = domNode.parent?.children.length ?? 0; // seperate style for bundled emojis // seperate style for bundled emojis if (siblingCount > 5) { return ( {!params.autoplayEmojis ? ( {props.alt || props.title || '?'} } /> ) : ( {props.alt || props.title || '?'} } /> )} ); } // old style for just a few... what is this even for? React components or something? return ( {!params.autoplayEmojis ? ( {props.alt || props.title || '?'} } /> ) : ( {props.alt || props.title || '?'} } /> )} ); } if (failedToResolveMxc) { return ( {fallbackLabel} ); } if (htmlSrc) return ( {props.alt || '[media]'} } /> ); } } if (domNode instanceof DOMText) { const linkify = shouldLinkifyDomText(domNode); const decoratedText = decorateText(domNode.data); if (linkify) { return {decoratedText}; } return decoratedText; } return undefined; }, }; return opts; };