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

DraftProjectName.logic.ts

27 lines911 Bytes

1const graphemes = new Intl.Segmenter(undefined, { granularity: "grapheme" });
2​
3export function truncateProjectName(
4 value: string,
5 availableWidth: number,
6 measure: (text: string) => number,
7): string {
8 if (measure(value) <= availableWidth) return value;
9 if (measure("…") > availableWidth) return "";
10​
11 const characters = Array.from(graphemes.segment(value), (part) => part.segment);
12 const candidate = (count: number) => {
13 const head = characters.slice(0, Math.floor(count / 2)).join("");
14 const tailCount = Math.ceil(count / 2);
15 const tail = tailCount > 0 ? characters.slice(-tailCount).join("") : "";
16 return `${head}…${tail}`;
17 };
18​
19 let low = 0;
20 let high = characters.length - 1;
21 while (low < high) {
22 const count = Math.ceil((low + high) / 2);
23 if (measure(candidate(count)) <= availableWidth) low = count;
24 else high = count - 1;
25 }
26 return candidate(low);