Open History to see the last commit
1import { type ComponentProps, useLayoutEffect, useRef } from "react";
2
3import { observeResize } from "~/lib/observeResize";
4import { cn } from "~/lib/utils";
5
6export function MiddleTruncate({
7 value,
8 tail,
9 showTitle = true,
10 variant = "default",
11 className,
12 ...props
13}: Omit<ComponentProps<"span">, "children"> & {
14 value: string;
15 tail?: number;
16 showTitle?: boolean;
17 variant?: "default" | "cap-aligned";
18}) {
19 const split = splitForMiddleTruncate(value, tail);
20 const headRef = useRef<HTMLSpanElement>(null);
21 const head = split?.head;
22 useLayoutEffect(() => {
23 const element = headRef.current;
24 // A new head can keep the same box size, so refit here, not only on resize.
25 if (!element || head === undefined) return;
26 fitHead(element);
27 return observeResize(element, () => fitHead(element));
28 }, [head]);
29 return (
30 <span
31 {...(showTitle ? { title: value } : {})}
32 className={cn(
33 "inline-flex min-w-0 max-w-full overflow-hidden whitespace-nowrap",
34 variant === "cap-aligned" &&
35 // Padding keeps descenders inside the box, so the cut does not clip them.
36 "overflow-x-clip overflow-y-visible [&>span]:[text-box:trim-both_cap_alphabetic] [&>span]:-mb-1 [&>span]:pb-1 [&>span]:overflow-x-clip [&>span]:overflow-y-visible",
37 className,
38 )}
39 {...props}
40 >
41 {split ? (
42 <>
43 {/* The tail carries the ellipsis so it sits flush; a CSS ellipsis leaves a ragged gap. */}
44 <span ref={headRef} className="peer min-w-0 overflow-hidden">
45 {split.head}
46 </span>
47 <span className="shrink-0 peer-data-overflow:before:content-['…']">{split.tail}</span>
48 </>
49 ) : (
50 // Keyed so React does not reuse the head node and its imperative clip.
51 <span key="whole" className="min-w-0 truncate">
52 {value}
53 </span>
54 )}
55 </span>
56 );
57}
58
59// An overflowing head is cut after its last whole character: clip the partial glyph
60// and slide the tail left over the slack. Neither changes layout, so the observed
61// size stays the true available width.
62
63function fitHead(head: HTMLElement) {
64 const text = head.firstChild;
65 const overflowing = head.scrollWidth > head.clientWidth && text instanceof Text;
66 head.toggleAttribute("data-overflow", overflowing);
67 let slack = 0;
68 if (overflowing) {
69 const range = document.createRange();
70 const left = head.getBoundingClientRect().left;
71 const widthTo = (end: number) => {
72 range.setStart(text, 0);
73 range.setEnd(text, end);
74 return range.getBoundingClientRect().right - left;
75 };
76 let fits = 0;
77 let over = text.length;
78 while (over - fits > 1) {
79 const mid = (fits + over) >> 1;
80 if (widthTo(mid) <= head.clientWidth) fits = mid;
81 else over = mid;
82 }
83 if (/[\uD800-\uDBFF]/.test(text.data[fits - 1] ?? "")) fits -= 1;
84 slack = Math.max(0, head.clientWidth - widthTo(fits));
85 }
86 head.style.clipPath = slack > 0 ? `inset(-0.25em ${slack}px -0.25em 0)` : "";
87 const tail = head.nextElementSibling;
88 if (tail instanceof HTMLElement) tail.style.translate = slack > 0 ? `-${slack}px 0` : "";
89}
90
91const DEFAULT_TAIL = 10;
92const MAX_SEGMENT_TAIL = 16;
93const MIN_WORD_TAIL = 4;
94const WORD_BREAK = /[-_./]/;
95
96export function splitForMiddleTruncate(
97 value: string,
98 tail?: number,
99): { head: string; tail: string } | null {
100 // Split by code point to avoid cutting surrogate pairs into broken glyphs.
101 const chars = Array.from(value);
102 let keep = tail ?? DEFAULT_TAIL;
103 if (tail === undefined) {
104 const slash = chars.lastIndexOf("/");
105 if (slash > 0 && slash < chars.length - 1) {
106 const segment = chars.length - slash - 1;
107 keep = segment <= MAX_SEGMENT_TAIL ? segment : DEFAULT_TAIL;
108 }
109 }
110 if (keep <= 0 || chars.length <= keep + 4) return null;
111 let cut = chars.length - keep;
112 // Start an automatic tail on a word ("machine", not "er-machine"). A shorter tail is
113 // preferred so the head stays readable; a longer one is the fallback.
114 if (tail === undefined && !WORD_BREAK.test(chars[cut - 1]!)) {
115 const startsWord = (index: number) => WORD_BREAK.test(chars[index - 1]!);
116 let snapped = -1;
117 for (let index = cut + 1; index <= chars.length - MIN_WORD_TAIL; index++) {
118 if (startsWord(index)) {
119 snapped = index;
120 break;
121 }
122 }
123 for (
124 let index = cut - 1;
125 snapped < 0 && index >= chars.length - MAX_SEGMENT_TAIL && index > 4;
126 index--
127 ) {
128 if (startsWord(index)) snapped = index;
129 }
130 if (snapped > 0) cut = snapped;
131 }
132 return { head: chars.slice(0, cut).join(""), tail: chars.slice(cut).join("") };
133}