phanpy/src/components/emoji-text.jsx
Lim Chee Aun 65bd6fb1ef It's micro-optimization week
Includes experimental replacing dangerouslySetInnerHTML with setting actual DOM
2024-09-25 17:18:30 +08:00

40 lines
1 KiB
JavaScript

import { memo } from 'preact/compat';
import mem from '../utils/mem';
import CustomEmoji from './custom-emoji';
const shortcodesRegexp = mem((shortcodes) => {
return new RegExp(`:(${shortcodes.join('|')}):`, 'g');
});
function EmojiText({ text, emojis }) {
if (!text) return '';
if (!emojis?.length) return text;
if (text.indexOf(':') === -1) return text;
// const regex = new RegExp(
// `:(${emojis.map((e) => e.shortcode).join('|')}):`,
// 'g',
// );
const regex = shortcodesRegexp(emojis.map((e) => e.shortcode));
const elements = text.split(regex).map((word) => {
const emoji = emojis.find((e) => e.shortcode === word);
if (emoji) {
const { url, staticUrl } = emoji;
return (
<CustomEmoji staticUrl={staticUrl} alt={word} url={url} key={word} />
);
}
return word;
});
return elements;
}
export default mem(EmojiText);
// export default memo(
// EmojiText,
// (oldProps, newProps) =>
// oldProps.text === newProps.text &&
// oldProps.emojis?.length === newProps.emojis?.length,
// );