Files
cinny/src/app/plugins/react-custom-html-parser.tsx
T

302 lines
9.5 KiB
TypeScript
Raw Normal View History

2023-10-06 13:44:06 +11:00
/* eslint-disable jsx-a11y/alt-text */
import React, { ReactEventHandler, Suspense, lazy } from 'react';
import {
2023-10-06 13:44:06 +11:00
Element,
Text as DOMText,
HTMLReactParserOptions,
attributesToProps,
domToReact,
} from 'html-react-parser';
import { MatrixClient, Room } from 'matrix-js-sdk';
import classNames from 'classnames';
import { Scroll, Text } from 'folds';
import { Opts as LinkifyOpts } from 'linkifyjs';
import Linkify from 'linkify-react';
import { ErrorBoundary } from 'react-error-boundary';
import * as css from '../styles/CustomHtml.css';
import { getMxIdLocalPart, getRoomWithCanonicalAlias } from '../utils/matrix';
import { getMemberDisplayName } from '../utils/room';
2023-10-26 09:09:27 +11:00
import { EMOJI_PATTERN, URL_NEG_LB } from '../utils/regex';
import { getHexcodeForEmoji, getShortcodeFor } from './emoji';
2023-10-30 16:58:47 +11:00
import { findAndReplace } from '../utils/findAndReplace';
2023-10-06 13:44:06 +11:00
const ReactPrism = lazy(() => import('./react-prism/ReactPrism'));
2023-10-30 16:58:47 +11:00
const EMOJI_REG_G = new RegExp(`${URL_NEG_LB}(${EMOJI_PATTERN})`, 'g');
2023-10-26 09:09:27 +11:00
2023-10-06 13:44:06 +11:00
export const LINKIFY_OPTS: LinkifyOpts = {
attributes: {
target: '_blank',
rel: 'noreferrer noopener',
},
validate: {
url: (value) => /^(https|http|ftp|mailto|magnet)?:/.test(value),
},
2023-10-26 09:09:27 +11:00
ignoreTags: ['span'],
};
2023-10-30 16:58:47 +11:00
const textToEmojifyJSX = (text: string): (string | JSX.Element)[] =>
findAndReplace(
text,
2023-10-30 16:58:47 +11:00
EMOJI_REG_G,
(match, pushIndex) => (
<span key={pushIndex} className={css.EmoticonBase}>
<span className={css.Emoticon()} title={getShortcodeFor(getHexcodeForEmoji(match[0]))}>
{match[0]}
</span>
</span>
2023-10-30 16:58:47 +11:00
),
(txt) => txt
);
2023-10-26 09:09:27 +11:00
export const emojifyAndLinkify = (text: string, linkify?: boolean) => {
2023-10-30 16:58:47 +11:00
const emojifyJSX = textToEmojifyJSX(text);
2023-10-26 09:09:27 +11:00
if (linkify) {
return <Linkify options={LINKIFY_OPTS}>{emojifyJSX}</Linkify>;
}
return emojifyJSX;
2023-10-06 13:44:06 +11:00
};
export const getReactCustomHtmlParser = (
mx: MatrixClient,
room: Room,
params: {
handleSpoilerClick?: ReactEventHandler<HTMLElement>;
handleMentionClick?: ReactEventHandler<HTMLElement>;
}
): HTMLReactParserOptions => {
const opts: HTMLReactParserOptions = {
replace: (domNode) => {
if (domNode instanceof Element && 'name' in domNode) {
const { name, attribs, children, parent } = domNode;
const props = attributesToProps(attribs);
if (name === 'h1') {
return (
2023-10-26 09:09:27 +11:00
<Text {...props} className={css.Heading} size="H2">
2023-10-06 13:44:06 +11:00
{domToReact(children, opts)}
</Text>
);
}
if (name === 'h2') {
return (
2023-10-26 09:09:27 +11:00
<Text {...props} className={css.Heading} size="H3">
2023-10-06 13:44:06 +11:00
{domToReact(children, opts)}
</Text>
);
}
if (name === 'h3') {
return (
2023-10-26 09:09:27 +11:00
<Text {...props} className={css.Heading} size="H4">
2023-10-06 13:44:06 +11:00
{domToReact(children, opts)}
</Text>
);
}
if (name === 'h4') {
return (
2023-10-26 09:09:27 +11:00
<Text {...props} className={css.Heading} size="H4">
2023-10-06 13:44:06 +11:00
{domToReact(children, opts)}
</Text>
);
}
if (name === 'h5') {
return (
2023-10-26 09:09:27 +11:00
<Text {...props} className={css.Heading} size="H5">
2023-10-06 13:44:06 +11:00
{domToReact(children, opts)}
</Text>
);
}
if (name === 'h6') {
return (
2023-10-26 09:09:27 +11:00
<Text {...props} className={css.Heading} size="H6">
2023-10-06 13:44:06 +11:00
{domToReact(children, opts)}
</Text>
);
}
if (name === 'p') {
return (
2023-10-26 09:09:27 +11:00
<Text {...props} className={classNames(css.Paragraph, css.MarginSpaced)} size="Inherit">
2023-10-06 13:44:06 +11:00
{domToReact(children, opts)}
</Text>
);
}
if (name === 'pre') {
return (
2023-10-26 09:09:27 +11:00
<Text {...props} as="pre" className={css.CodeBlock}>
2023-10-06 13:44:06 +11:00
<Scroll
direction="Horizontal"
variant="Secondary"
size="300"
visibility="Hover"
hideTrack
>
<div className={css.CodeBlockInternal}>{domToReact(children, opts)}</div>
</Scroll>
</Text>
);
}
if (name === 'blockquote') {
return (
2023-10-26 09:09:27 +11:00
<Text {...props} size="Inherit" as="blockquote" className={css.BlockQuote}>
2023-10-06 13:44:06 +11:00
{domToReact(children, opts)}
</Text>
);
}
if (name === 'ul') {
return (
2023-10-26 09:09:27 +11:00
<ul {...props} className={css.List}>
2023-10-06 13:44:06 +11:00
{domToReact(children, opts)}
</ul>
);
}
if (name === 'ol') {
return (
2023-10-26 09:09:27 +11:00
<ol {...props} className={css.List}>
2023-10-06 13:44:06 +11:00
{domToReact(children, opts)}
</ol>
);
}
if (name === 'code') {
if (parent && 'name' in parent && parent.name === 'pre') {
const codeReact = domToReact(children, opts);
if (typeof codeReact === 'string') {
let lang = props.className;
if (lang === 'language-rs') lang = 'language-rust';
else if (lang === 'language-js') lang = 'language-javascript';
else if (lang === 'language-ts') lang = 'language-typescript';
2023-10-06 13:44:06 +11:00
return (
<ErrorBoundary fallback={<code {...props}>{codeReact}</code>}>
<Suspense fallback={<code {...props}>{codeReact}</code>}>
<ReactPrism>
{(ref) => (
<code ref={ref} {...props} className={lang}>
{codeReact}
</code>
)}
</ReactPrism>
</Suspense>
</ErrorBoundary>
);
}
} else {
return (
<code className={css.Code} {...props}>
{domToReact(children, opts)}
</code>
);
}
}
if (name === 'a') {
const mention = decodeURIComponent(props.href).match(
/^https?:\/\/matrix.to\/#\/((@|#|!).+:[^?/]+)/
);
if (mention) {
// convert mention link to pill
const mentionId = mention[1];
const mentionPrefix = mention[2];
if (mentionPrefix === '#' || mentionPrefix === '!') {
const mentionRoom =
mentionPrefix === '#'
? getRoomWithCanonicalAlias(mx, mentionId)
: mx.getRoom(mentionId);
return (
<span
{...props}
className={css.Mention({
highlight: room.roomId === (mentionRoom?.roomId ?? mentionId),
})}
data-mention-id={mentionRoom?.roomId ?? mentionId}
data-mention-href={props.href}
role="button"
tabIndex={params.handleMentionClick ? 0 : -1}
onKeyDown={params.handleMentionClick}
onClick={params.handleMentionClick}
style={{ cursor: 'pointer' }}
>
2023-10-19 17:43:54 +11:00
{domToReact(children, opts)}
2023-10-06 13:44:06 +11:00
</span>
);
}
if (mentionPrefix === '@')
return (
<span
{...props}
className={css.Mention({ highlight: mx.getUserId() === mentionId })}
data-mention-id={mentionId}
data-mention-href={props.href}
role="button"
tabIndex={params.handleMentionClick ? 0 : -1}
onKeyDown={params.handleMentionClick}
onClick={params.handleMentionClick}
style={{ cursor: 'pointer' }}
>
{`@${getMemberDisplayName(room, mentionId) ?? getMxIdLocalPart(mentionId)}`}
</span>
);
}
}
if (name === 'span' && 'data-mx-spoiler' in props) {
return (
<span
{...props}
role="button"
tabIndex={params.handleSpoilerClick ? 0 : -1}
onKeyDown={params.handleSpoilerClick}
onClick={params.handleSpoilerClick}
className={css.Spoiler()}
aria-pressed
style={{ cursor: 'pointer' }}
>
{domToReact(children, opts)}
</span>
);
}
if (name === 'img') {
const htmlSrc = mx.mxcUrlToHttp(props.src);
if (htmlSrc && props.src.startsWith('mxc://') === false) {
return (
<a href={htmlSrc} target="_blank" rel="noreferrer noopener">
2023-10-26 09:09:27 +11:00
{props.alt || props.title || htmlSrc}
2023-10-06 13:44:06 +11:00
</a>
);
}
if (htmlSrc && 'data-mx-emoticon' in props) {
return (
<span className={css.EmoticonBase}>
2023-10-26 09:09:27 +11:00
<span className={css.Emoticon()}>
<img {...props} className={css.EmoticonImg} src={htmlSrc} />
2023-10-06 13:44:06 +11:00
</span>
</span>
);
}
2023-10-26 09:09:27 +11:00
if (htmlSrc) return <img {...props} className={css.Img} src={htmlSrc} />;
2023-10-06 13:44:06 +11:00
}
}
2023-10-26 09:09:27 +11:00
if (domNode instanceof DOMText) {
const linkify =
!(domNode.parent && 'name' in domNode.parent && domNode.parent.name === 'code') &&
!(domNode.parent && 'name' in domNode.parent && domNode.parent.name === 'a');
return emojifyAndLinkify(domNode.data, linkify);
2023-10-06 13:44:06 +11:00
}
return undefined;
},
};
return opts;
};