Add jsdelivr cdn for twemoji

This commit is contained in:
Ajay Bura 2023-01-14 18:51:42 +05:30
parent 899a89cb3b
commit e5e3f5f0a3
3 changed files with 137 additions and 120 deletions

View file

@ -13,6 +13,7 @@ import cons from '../../../client/state/cons';
import navigation from '../../../client/state/navigation'; import navigation from '../../../client/state/navigation';
import AsyncSearch from '../../../util/AsyncSearch'; import AsyncSearch from '../../../util/AsyncSearch';
import { addRecentEmoji, getRecentEmojis } from './recent'; import { addRecentEmoji, getRecentEmojis } from './recent';
import { TWEMOJI_BASE_URL } from '../../../util/twemojify';
import Text from '../../atoms/text/Text'; import Text from '../../atoms/text/Text';
import RawIcon from '../../atoms/system-icons/RawIcon'; import RawIcon from '../../atoms/system-icons/RawIcon';
@ -46,45 +47,49 @@ const EmojiGroup = React.memo(({ name, groupEmojis }) => {
const emoji = groupEmojis[emojiIndex]; const emoji = groupEmojis[emojiIndex];
emojiRow.push( emojiRow.push(
<span key={emojiIndex}> <span key={emojiIndex}>
{ {emoji.hexcode ? (
emoji.hexcode // This is a unicode emoji, and should be rendered with twemoji
// This is a unicode emoji, and should be rendered with twemoji parse(
? parse(twemoji.parse( twemoji.parse(emoji.unicode, {
emoji.unicode, attributes: () => ({
{ unicode: emoji.unicode,
attributes: () => ({ shortcodes: emoji.shortcodes?.toString(),
unicode: emoji.unicode, hexcode: emoji.hexcode,
shortcodes: emoji.shortcodes?.toString(), loading: 'lazy',
hexcode: emoji.hexcode, }),
loading: 'lazy', base: TWEMOJI_BASE_URL,
}), })
}, )
)) ) : (
// This is a custom emoji, and should be render as an mxc // This is a custom emoji, and should be render as an mxc
: ( <img
<img className="emoji"
className="emoji" draggable="false"
draggable="false" loading="lazy"
loading="lazy" alt={emoji.shortcode}
alt={emoji.shortcode} unicode={`:${emoji.shortcode}:`}
unicode={`:${emoji.shortcode}:`} shortcodes={emoji.shortcode}
shortcodes={emoji.shortcode} src={initMatrix.matrixClient.mxcUrlToHttp(emoji.mxc)}
src={initMatrix.matrixClient.mxcUrlToHttp(emoji.mxc)} data-mx-emoticon={emoji.mxc}
data-mx-emoticon={emoji.mxc} />
/> )}
) </span>
}
</span>,
); );
} }
emojiBoard.push(<div key={r} className="emoji-row">{emojiRow}</div>); emojiBoard.push(
<div key={r} className="emoji-row">
{emojiRow}
</div>
);
} }
return emojiBoard; return emojiBoard;
} }
return ( return (
<div className="emoji-group"> <div className="emoji-group">
<Text className="emoji-group__header" variant="b2" weight="bold">{name}</Text> <Text className="emoji-group__header" variant="b2" weight="bold">
{name}
</Text>
{groupEmojis.length !== 0 && <div className="emoji-set noselect">{getEmojiBoard()}</div>} {groupEmojis.length !== 0 && <div className="emoji-set noselect">{getEmojiBoard()}</div>}
</div> </div>
); );
@ -92,17 +97,16 @@ const EmojiGroup = React.memo(({ name, groupEmojis }) => {
EmojiGroup.propTypes = { EmojiGroup.propTypes = {
name: PropTypes.string.isRequired, name: PropTypes.string.isRequired,
groupEmojis: PropTypes.arrayOf(PropTypes.shape({ groupEmojis: PropTypes.arrayOf(
length: PropTypes.number, PropTypes.shape({
unicode: PropTypes.string, length: PropTypes.number,
hexcode: PropTypes.string, unicode: PropTypes.string,
mxc: PropTypes.string, hexcode: PropTypes.string,
shortcode: PropTypes.string, mxc: PropTypes.string,
shortcodes: PropTypes.oneOfType([ shortcode: PropTypes.string,
PropTypes.string, shortcodes: PropTypes.oneOfType([PropTypes.string, PropTypes.arrayOf(PropTypes.string)]),
PropTypes.arrayOf(PropTypes.string), })
]), ).isRequired,
})).isRequired,
}; };
const asyncSearch = new AsyncSearch(); const asyncSearch = new AsyncSearch();
@ -128,7 +132,13 @@ function SearchedEmoji() {
if (searchedEmojis === null) return false; if (searchedEmojis === null) return false;
return <EmojiGroup key="-1" name={searchedEmojis.emojis.length === 0 ? 'No search result found' : 'Search results'} groupEmojis={searchedEmojis.emojis} />; return (
<EmojiGroup
key="-1"
name={searchedEmojis.emojis.length === 0 ? 'No search result found' : 'Search results'}
groupEmojis={searchedEmojis.emojis}
/>
);
} }
function EmojiBoard({ onSelect, searchRef }) { function EmojiBoard({ onSelect, searchRef }) {
@ -146,7 +156,10 @@ function EmojiBoard({ onSelect, searchRef }) {
if (typeof shortcodes === 'undefined') shortcodes = undefined; if (typeof shortcodes === 'undefined') shortcodes = undefined;
else shortcodes = shortcodes.split(','); else shortcodes = shortcodes.split(',');
return { return {
unicode, hexcode, shortcodes, mxc, unicode,
hexcode,
shortcodes,
mxc,
}; };
} }
@ -211,10 +224,9 @@ function EmojiBoard({ onSelect, searchRef }) {
const parentIds = initMatrix.roomList.getAllParentSpaces(room.roomId); const parentIds = initMatrix.roomList.getAllParentSpaces(room.roomId);
const parentRooms = [...parentIds].map((id) => mx.getRoom(id)); const parentRooms = [...parentIds].map((id) => mx.getRoom(id));
if (room) { if (room) {
const packs = getRelevantPacks( const packs = getRelevantPacks(room.client, [room, ...parentRooms]).filter(
room.client, (pack) => pack.getEmojis().length !== 0
[room, ...parentRooms], );
).filter((pack) => pack.getEmojis().length !== 0);
// Set an index for each pack so that we know where to jump when the user uses the nav // Set an index for each pack so that we know where to jump when the user uses the nav
for (let i = 0; i < packs.length; i += 1) { for (let i = 0; i < packs.length; i += 1) {
@ -263,44 +275,41 @@ function EmojiBoard({ onSelect, searchRef }) {
/> />
)} )}
<div className="emoji-board__nav-custom"> <div className="emoji-board__nav-custom">
{ {availableEmojis.map((pack) => {
availableEmojis.map((pack) => { const src = initMatrix.matrixClient.mxcUrlToHttp(
const src = initMatrix.matrixClient pack.avatarUrl ?? pack.getEmojis()[0].mxc
.mxcUrlToHttp(pack.avatarUrl ?? pack.getEmojis()[0].mxc); );
return ( return (
<IconButton <IconButton
onClick={() => openGroup(recentOffset + pack.packIndex)} onClick={() => openGroup(recentOffset + pack.packIndex)}
src={src} src={src}
key={pack.packIndex} key={pack.packIndex}
tooltip={pack.displayName ?? 'Unknown'} tooltip={pack.displayName ?? 'Unknown'}
tooltipPlacement="left" tooltipPlacement="left"
isImage isImage
/> />
); );
}) })}
}
</div> </div>
<div className="emoji-board__nav-twemoji"> <div className="emoji-board__nav-twemoji">
{ {[
[ [0, EmojiIC, 'Smilies'],
[0, EmojiIC, 'Smilies'], [1, DogIC, 'Animals'],
[1, DogIC, 'Animals'], [2, CupIC, 'Food'],
[2, CupIC, 'Food'], [3, BallIC, 'Activities'],
[3, BallIC, 'Activities'], [4, PhotoIC, 'Travel'],
[4, PhotoIC, 'Travel'], [5, BulbIC, 'Objects'],
[5, BulbIC, 'Objects'], [6, PeaceIC, 'Symbols'],
[6, PeaceIC, 'Symbols'], [7, FlagIC, 'Flags'],
[7, FlagIC, 'Flags'], ].map(([indx, ico, name]) => (
].map(([indx, ico, name]) => ( <IconButton
<IconButton onClick={() => openGroup(recentOffset + availableEmojis.length + indx)}
onClick={() => openGroup(recentOffset + availableEmojis.length + indx)} key={indx}
key={indx} src={ico}
src={ico} tooltip={name}
tooltip={name} tooltipPlacement="left"
tooltipPlacement="left" />
/> ))}
))
}
</div> </div>
</div> </div>
</ScrollView> </ScrollView>
@ -313,27 +322,25 @@ function EmojiBoard({ onSelect, searchRef }) {
<ScrollView ref={scrollEmojisRef} autoHide> <ScrollView ref={scrollEmojisRef} autoHide>
<div onMouseMove={hoverEmoji} onClick={selectEmoji}> <div onMouseMove={hoverEmoji} onClick={selectEmoji}>
<SearchedEmoji /> <SearchedEmoji />
{recentEmojis.length > 0 && <EmojiGroup name="Recently used" groupEmojis={recentEmojis} />} {recentEmojis.length > 0 && (
{ <EmojiGroup name="Recently used" groupEmojis={recentEmojis} />
availableEmojis.map((pack) => ( )}
<EmojiGroup {availableEmojis.map((pack) => (
name={pack.displayName ?? 'Unknown'} <EmojiGroup
key={pack.packIndex} name={pack.displayName ?? 'Unknown'}
groupEmojis={pack.getEmojis()} key={pack.packIndex}
className="custom-emoji-group" groupEmojis={pack.getEmojis()}
/> className="custom-emoji-group"
)) />
} ))}
{ {emojiGroups.map((group) => (
emojiGroups.map((group) => ( <EmojiGroup key={group.name} name={group.name} groupEmojis={group.emojis} />
<EmojiGroup key={group.name} name={group.name} groupEmojis={group.emojis} /> ))}
))
}
</div> </div>
</ScrollView> </ScrollView>
</div> </div>
<div ref={emojiInfo} className="emoji-board__content__info"> <div ref={emojiInfo} className="emoji-board__content__info">
<div>{ parse(twemoji.parse('🙂')) }</div> <div>{parse(twemoji.parse('🙂', { base: TWEMOJI_BASE_URL }))}</div>
<Text>:slight_smile:</Text> <Text>:slight_smile:</Text>
</div> </div>
</div> </div>

View file

@ -5,7 +5,7 @@ import './RoomViewCmdBar.scss';
import parse from 'html-react-parser'; import parse from 'html-react-parser';
import twemoji from 'twemoji'; import twemoji from 'twemoji';
import { twemojify } from '../../../util/twemojify'; import { twemojify, TWEMOJI_BASE_URL } from '../../../util/twemojify';
import initMatrix from '../../../client/initMatrix'; import initMatrix from '../../../client/initMatrix';
import { getEmojiForCompletion } from '../emoji-board/custom-emoji'; import { getEmojiForCompletion } from '../emoji-board/custom-emoji';
@ -31,7 +31,7 @@ CmdItem.propTypes = {
function renderSuggestions({ prefix, option, suggestions }, fireCmd) { function renderSuggestions({ prefix, option, suggestions }, fireCmd) {
function renderCmdSuggestions(cmdPrefix, cmds) { function renderCmdSuggestions(cmdPrefix, cmds) {
const cmdOptString = (typeof option === 'string') ? `/${option}` : '/?'; const cmdOptString = typeof option === 'string' ? `/${option}` : '/?';
return cmds.map((cmd) => ( return cmds.map((cmd) => (
<CmdItem <CmdItem
key={cmd} key={cmd}
@ -53,15 +53,15 @@ function renderSuggestions({ prefix, option, suggestions }, fireCmd) {
// Renders a small Twemoji // Renders a small Twemoji
function renderTwemoji(emoji) { function renderTwemoji(emoji) {
return parse(twemoji.parse( return parse(
emoji.unicode, twemoji.parse(emoji.unicode, {
{
attributes: () => ({ attributes: () => ({
unicode: emoji.unicode, unicode: emoji.unicode,
shortcodes: emoji.shortcodes?.toString(), shortcodes: emoji.shortcodes?.toString(),
}), }),
}, base: TWEMOJI_BASE_URL,
)); })
);
} }
// Render a custom emoji // Render a custom emoji
@ -87,10 +87,12 @@ function renderSuggestions({ prefix, option, suggestions }, fireCmd) {
return emos.map((emoji) => ( return emos.map((emoji) => (
<CmdItem <CmdItem
key={emoji.shortcode} key={emoji.shortcode}
onClick={() => fireCmd({ onClick={() =>
prefix: emPrefix, fireCmd({
result: emoji, prefix: emPrefix,
})} result: emoji,
})
}
> >
<Text variant="b1">{renderEmoji(emoji)}</Text> <Text variant="b1">{renderEmoji(emoji)}</Text>
<Text variant="b2">{`:${emoji.shortcode}:`}</Text> <Text variant="b2">{`:${emoji.shortcode}:`}</Text>
@ -187,10 +189,13 @@ function RoomViewCmdBar({ roomId, roomTimeline, viewEvent }) {
}); });
}, },
'@': () => { '@': () => {
const members = mx.getRoom(roomId).getJoinedMembers().map((member) => ({ const members = mx
name: member.name, .getRoom(roomId)
userId: member.userId.slice(1), .getJoinedMembers()
})); .map((member) => ({
name: member.name,
userId: member.userId.slice(1),
}));
asyncSearch.setup(members, { keys: ['name', 'userId'], limit: 20 }); asyncSearch.setup(members, { keys: ['name', 'userId'], limit: 20 });
const endIndex = members.length > 20 ? 20 : members.length; const endIndex = members.length > 20 ? 20 : members.length;
setCmd({ prefix, suggestions: members.slice(0, endIndex) }); setCmd({ prefix, suggestions: members.slice(0, endIndex) });
@ -277,9 +282,7 @@ function RoomViewCmdBar({ roomId, roomTimeline, viewEvent }) {
</div> </div>
<div className="cmd-bar__content"> <div className="cmd-bar__content">
<ScrollView horizontal vertical={false} invisible> <ScrollView horizontal vertical={false} invisible>
<div className="cmd-bar__content-suggestions"> <div className="cmd-bar__content-suggestions">{renderSuggestions(cmd, fireCmd)}</div>
{ renderSuggestions(cmd, fireCmd) }
</div>
</ScrollView> </ScrollView>
</div> </div>
</div> </div>

View file

@ -6,6 +6,8 @@ import parse from 'html-react-parser';
import twemoji from 'twemoji'; import twemoji from 'twemoji';
import { sanitizeText } from './sanitize'; import { sanitizeText } from './sanitize';
export const TWEMOJI_BASE_URL = 'https://cdn.jsdelivr.net/gh/twitter/twemoji@14.0.2/assets/';
const Math = lazy(() => import('../app/atoms/math/Math')); const Math = lazy(() => import('../app/atoms/math/Math'));
const mathOptions = { const mathOptions = {
@ -38,11 +40,16 @@ const mathOptions = {
export function twemojify(text, opts, linkify = false, sanitize = true, maths = false) { export function twemojify(text, opts, linkify = false, sanitize = true, maths = false) {
if (typeof text !== 'string') return text; if (typeof text !== 'string') return text;
let content = text; let content = text;
const options = opts ?? { base: TWEMOJI_BASE_URL };
if (!options.base) {
options.base = TWEMOJI_BASE_URL;
}
if (sanitize) { if (sanitize) {
content = sanitizeText(content); content = sanitizeText(content);
} }
content = twemoji.parse(content, opts);
content = twemoji.parse(content, options);
if (linkify) { if (linkify) {
content = linkifyHtml(content, { content = linkifyHtml(content, {
target: '_blank', target: '_blank',