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

middle-truncate.tsx

73 lines2.6 KB

1import type { ComponentProps } from "react";
2​
3import { cn } from "~/lib/utils";
4​
5/**
6 * Truncates in the middle, the way Finder does, for strings that carry meaning at both ends:
7 * branch names, paths, worktree names, shas. A tail-cut `fix/cache-main-20260918-180825` loses
8 * the date that tells two branches apart; a path loses its file name.
9 *
10 * CSS has no middle ellipsis, so the string is split into a head that truncates and a tail
11 * that does not. No measuring and no observers, so it costs the same as `truncate` in a long
12 * list and works inside `content-visibility` skipping. Both halves are real text: selection
13 * and copy give the whole string, and a screen reader reads it through.
14 */
15export function MiddleTruncate({
16 value,
17 tail,
18 showTitle = true,
19 className,
20 ...props
21}: Omit<ComponentProps<"span">, "children"> & {
22 value: string;
23 /** Characters kept at the end. Defaults to the last path segment, capped, or 10. */
24 tail?: number;
25 /** The full value on hover. Off where a tooltip already carries it. */
26 showTitle?: boolean;
27}) {
28 const split = splitForMiddleTruncate(value, tail);
29 return (
30 <span
31 {...(showTitle ? { title: value } : {})}
32 className={cn("inline-flex min-w-0 max-w-full overflow-hidden whitespace-nowrap", className)}
33 {...props}
34 >
35 {split ? (
36 <>
37 <span className="min-w-0 truncate">{split.head}</span>
38 <span className="shrink-0">{split.tail}</span>
39 </>
40 ) : (
41 <span className="min-w-0 truncate">{value}</span>
42 )}
43 </span>
44 );
46​
47const DEFAULT_TAIL = 10;
48const MAX_SEGMENT_TAIL = 16;
49​
50/**
51 * Where to cut. A path keeps its last segment when that is short enough to be the useful
52 * part; anything else keeps a fixed count. Nothing is split when the tail would be most of
53 * the string, since then the head could never show enough to be worth an ellipsis.
54 */
55export function splitForMiddleTruncate(
56 value: string,
57 tail?: number,
58): { head: string; tail: string } | null {
59 // Code points, not UTF-16 units: a cut inside a surrogate pair would render two broken
60 // glyphs where an emoji or a CJK extension character used to be.
61 const chars = Array.from(value);
62 let keep = tail ?? DEFAULT_TAIL;
63 if (tail === undefined) {
64 const slash = chars.lastIndexOf("/");
65 if (slash > 0 && slash < chars.length - 1) {
66 const segment = chars.length - slash - 1;
67 keep = segment <= MAX_SEGMENT_TAIL ? segment : DEFAULT_TAIL;
68 }
69 }
70 if (keep <= 0 || chars.length <= keep + 4) return null;
71 const cut = chars.length - keep;
72 return { head: chars.slice(0, cut).join(""), tail: chars.slice(cut).join("") };