okami.mom/strata

git clone https://git.nkp.pet/okami.mom/strata

Niko1221Merge f-0213-guidata (4c4596746) into f-0213-int22a3d7068

main
1.7 KiB34 linesraw
1/**
2 * A chat title cut from the first prompt without cutting a character in half (#4533).
3 *
4 * `prompt.slice(0, 47)` counts UTF-16 units, so an emoji (two units), a flag (four), a family or a skin-tone sequence (up to eleven) that
5 * straddles the cut leaves half a character: a lone surrogate that draws as a replacement box, or a ZWJ with nothing after it. The title is
6 * stored and restored as it is, so the broken tail comes back on every start and goes through the font fallback that WebKitGTK crashes in.
7 * This cuts at a user-perceived character (grapheme) when the engine has Intl.Segmenter, and at a code point when it has not.
8 *
9 * The three `prompt.length > 48 ? prompt.slice(0, 47).trimEnd() + '…' : prompt` places in lib/store.ts should call `shortTitle(prompt)`.
10 */
11const WIDTH = 48;
12
13export function shortTitle(text: string, width = WIDTH): string {
14    if (text.length <= width)
15        return text;
16    const room = width - 1;                     // the ellipsis takes one unit
17    let end = 0;
18    const Segmenter = (Intl as unknown as { Segmenter?: new (locale?: string, options?: { granularity: string }) => { segment(input: string): Iterable<{ segment: string; index: number }> } }).Segmenter;
19    if (Segmenter) {
20        for (const part of new Segmenter(undefined, { granularity: 'grapheme' }).segment(text)) {
21            if (part.index + part.segment.length > room)
22                break;
23            end = part.index + part.segment.length;
24        }
25    }
26    else {
27        for (const ch of text) {                 // iterates by code point
28            if (end + ch.length > room)
29                break;
30            end += ch.length;
31        }
32    }
33    return text.slice(0, end).trimEnd() + '…';
34}