Skip to content
Source
Sign inSign up
pingdotgg/t3code
Open History to see the last commit

String.ts

45 lines1.5 KB

1const EXTENDER = /[\p{M}\p{Grapheme_Extend}\p{Emoji_Modifier}]/u;
2const EMOJI_EXTENDER = /[\p{Grapheme_Extend}\p{Emoji_Modifier}]/u;
3const PICTOGRAPH = /\p{Extended_Pictographic}/u;
4const ZWJ = "\u200d";
5​
6export function truncate(text: string, maxLength = 50): string {
7 const trimmed = text.trim();
8 let end = Math.trunc(maxLength);
9 const characters: string[] = [];
10 for (const character of trimmed) {
11 characters.push(character);
12 // A joiner exactly at the cutoff may join the next pictograph.
13 if (maxLength >= 0 && characters.length === end + 2) break;
14 }
15 if (characters.length <= maxLength) {
16 return trimmed;
17 }
18​
19 while (end > 0 && EXTENDER.test(characters[end] ?? "")) {
20 end -= 1;
21 }
22 while (end > 0) {
23 const joiner = characters[end] === ZWJ ? end : end - 1;
24 if (characters[joiner] !== ZWJ || !PICTOGRAPH.test(characters[joiner + 1] ?? "")) break;
25​
26 let start = joiner - 1;
27 while (EMOJI_EXTENDER.test(characters[start] ?? "")) {
28 start -= 1;
29 }
30 if (!PICTOGRAPH.test(characters[start] ?? "")) break;
31 end = start;
32 }
33​
34 // Regional indicators pair up from the start of their run, so an odd count
35 // before the cut means it would split a flag.
36 if (/\p{RI}/u.test(characters[end] ?? "")) {
37 let pairedIndicators = 0;
38 while (/\p{RI}/u.test(characters[end - 1 - pairedIndicators] ?? "")) {
39 pairedIndicators += 1;
40 }
41 end -= pairedIndicators % 2;
42 }
43​
44 return `${characters.slice(0, end).join("").trimEnd()}...`;