bigbuffet-rw/app/soapbox/utils/rich_content.ts

25 lines
916 B
TypeScript
Raw Normal View History

2022-04-24 12:28:07 -07:00
/** Returns `true` if the node contains only emojis, up to a limit */
export const onlyEmoji = (node: HTMLElement, limit = 1, ignoreMentions = true): boolean => {
2021-07-09 12:22:01 -07:00
if (!node) return false;
2021-07-09 16:39:05 -07:00
2021-07-10 10:41:57 -07:00
try {
// Remove mentions before checking content
if (ignoreMentions) {
2022-04-24 12:28:07 -07:00
node = node.cloneNode(true) as HTMLElement;
node.querySelectorAll('a.mention').forEach(m => m.parentNode?.removeChild(m));
2021-07-10 10:41:57 -07:00
}
2021-07-09 16:39:05 -07:00
2022-04-24 12:28:07 -07:00
if (node.textContent?.replace(new RegExp(' ', 'g'), '') !== '') return false;
2021-07-10 10:41:57 -07:00
const emojis = Array.from(node.querySelectorAll('img.emojione'));
if (emojis.length === 0) return false;
if (emojis.length > limit) return false;
const images = Array.from(node.querySelectorAll('img'));
if (images.length > emojis.length) return false;
return true;
} catch (e) {
// If anything in here crashes, skipping it is inconsequential.
console.error(e);
return false;
}
2021-07-09 12:22:01 -07:00
};