atagen

malice

public
Star0
Watch0
e822c659890f1425e3506816b11a3f37e9cccbcd
2
ssh://brewery@pls.lobotomise.me:33/atagen/malice.git
web/src/lib/twemoji.tsTypescript48 lines1.6 KB
1
const ZWJ = 0x200d;
2
const VS16 = 0xfe0f;
3
4
export function twemojiUrl(emoji: string): string {
5
  const points = Array.from(emoji, (c) => c.codePointAt(0) ?? 0);
6
  const kept = points.includes(ZWJ) ? points : points.filter((p) => p !== VS16);
7
  return `/twemoji/${kept.map((p) => p.toString(16)).join('-')}.svg`;
8
}
9
10
export interface TextSegment {
11
  text: string;
12
  emoji: boolean;
13
}
14
15
const MAYBE_EMOJI = /\p{Extended_Pictographic}|\p{Regional_Indicator}|\u20E3/u;
16
const PICTOGRAPHIC = /\p{Extended_Pictographic}/u;
17
const EMOJI_PRESENTATION = /\p{Emoji_Presentation}/u;
18
const KEYCAP = /^[0-9#*]\uFE0F\u20E3$/;
19
const FLAG = /^\p{Regional_Indicator}{2}$/u;
20
21
let segmenter: Intl.Segmenter | null = null;
22
23
function isEmojiGrapheme(g: string): boolean {
24
  if (KEYCAP.test(g) || FLAG.test(g)) return true;
25
  return PICTOGRAPHIC.test(g) && (EMOJI_PRESENTATION.test(g) || g.includes(String.fromCodePoint(VS16)) || g.includes(String.fromCodePoint(ZWJ)));
26
}
27
28
export function segmentEmoji(text: string): TextSegment[] {
29
  if (!MAYBE_EMOJI.test(text)) return [{ text, emoji: false }];
30
  segmenter ??= new Intl.Segmenter(undefined, { granularity: 'grapheme' });
31
  const out: TextSegment[] = [];
32
  for (const { segment } of segmenter.segment(text)) {
33
    const emoji = isEmojiGrapheme(segment);
34
    const last = out[out.length - 1];
35
    if (last && !emoji && !last.emoji) last.text += segment;
36
    else out.push({ text: segment, emoji });
37
  }
38
  return out;
39
}
40
41
export function isJumbo(segments: TextSegment[]): boolean {
42
  let count = 0;
43
  for (const s of segments) {
44
    if (s.emoji) count += 1;
45
    else if (s.text.trim() !== '') return false;
46
  }
47
  return count >= 1 && count <= 3;
48
}