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

ThreadGitControls.logic.ts

48 lines1.9 KB

1import { splitsSurrogatePair } from "@t3tools/shared/assistantCitations";
2​
3const REGIONAL_INDICATOR = /^\p{RI}$/u;
4const EMOJI_SEQUENCE =
5 /\p{Extended_Pictographic}[\p{Grapheme_Extend}\p{Emoji_Modifier}]*(?:\u200d\p{Extended_Pictographic}[\p{Grapheme_Extend}\p{Emoji_Modifier}]*)*/gu;
6​
7// Regional indicators pair into flags from the start of their run, so an odd
8// count before the offset means it falls inside a flag.
9function splitsFlag(value: string, offset: number): boolean {
10 let before = 0;
11 while (REGIONAL_INDICATOR.test(value.slice(offset - 2 * before - 2, offset - 2 * before))) {
12 before += 1;
13 }
14 return before % 2 === 1 && REGIONAL_INDICATOR.test(value.slice(offset, offset + 2));
16​
17function truncateMiddle(value: string, maxLength: number): string {
18 if (value.length <= maxLength) {
19 return value;
20 }
21​
22 const headLength = Math.ceil((maxLength - 1) / 2);
23 const tailStart = value.length - Math.floor((maxLength - 1) / 2);
24 let headEnd = splitsSurrogatePair(value, headLength) ? headLength - 1 : headLength;
25 let tailFrom = splitsSurrogatePair(value, tailStart) ? tailStart + 1 : tailStart;
26 for (const match of value.matchAll(EMOJI_SEQUENCE)) {
27 const start = match.index;
28 if (start >= tailStart) break;
29 const end = start + match[0].length;
30 if (start < headLength && headLength < end) headEnd = start;
31 if (tailStart < end) tailFrom = end;
32 }
33 // Drop a letter whose marks cross the head cut, so the head never grows.
34 if (/^\p{M}/u.test(value.slice(headEnd))) {
35 headEnd = value.slice(0, headEnd).search(/\P{M}?\p{M}*$/u);
36 }
37 if (splitsFlag(value, headEnd)) headEnd -= 2;
38 if (splitsFlag(value, tailFrom)) tailFrom += 2;
39 const marks = /\p{M}*/uy;
40 marks.lastIndex = tailFrom;
41 marks.test(value);
42 tailFrom = marks.lastIndex;
43 return `${value.slice(0, headEnd)}…${value.slice(tailFrom)}`;
45​
46export function compactMenuBranchLabel(branch: string): string {
47 return truncateMiddle(branch, 24);