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

middle-truncate.tsx

147 lines5.3 KB

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 raw = splitForMiddleTruncate(value, tail);
20 const split = raw && collapseSegments(raw);
21 const headRef = useRef<HTMLSpanElement>(null);
22 const head = split?.head;
23 // oxlint-disable-next-line t3code/no-unreasoned-state-sync -- fits the head span's DOM text and refits it through a ResizeObserver
24 useLayoutEffect(() => {
25 const element = headRef.current;
26 // A new head can keep the same box size, so refit here, not only on resize.
27 if (!element || head === undefined) return;
28 fitHead(element);
29 return observeResize(element, () => fitHead(element));
30 }, [head]);
31 return (
32 <span
33 {...(showTitle ? { title: value } : {})}
34 className={cn(
35 "inline-flex min-w-0 max-w-full overflow-hidden whitespace-nowrap",
36 variant === "cap-aligned" &&
37 // Padding keeps descenders inside the box, so the cut does not clip them.
38 "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",
39 className,
40 )}
41 {...props}
42 >
43 {split ? (
44 <>
45 {/* The tail carries the ellipsis so it sits flush; a CSS ellipsis leaves a ragged gap. */}
46 <span ref={headRef} className="peer min-w-0 overflow-hidden whitespace-pre">
47 {split.head}
48 </span>
49 <span className="shrink-0 whitespace-pre peer-data-overflow:before:content-['…']">
50 {split.tail}
51 </span>
52 </>
53 ) : (
54 // Keyed so React does not reuse the head node and its imperative clip.
55 <span key="whole" className="min-w-0 truncate">
56 {value}
57 </span>
58 )}
59 </span>
60 );
62​
63// An overflowing head is cut after its last whole character: clip the partial glyph
64// and slide the tail left over the slack. Neither changes layout, so the observed
65// size stays the true available width.
66​
67function fitHead(head: HTMLElement) {
68 const text = head.firstChild;
69 const overflowing = head.scrollWidth > head.clientWidth && text instanceof Text;
70 head.toggleAttribute("data-overflow", overflowing);
71 let slack = 0;
72 if (overflowing) {
73 const range = document.createRange();
74 const left = head.getBoundingClientRect().left;
75 const widthTo = (end: number) => {
76 range.setStart(text, 0);
77 range.setEnd(text, end);
78 return range.getBoundingClientRect().right - left;
79 };
80 let fits = 0;
81 let over = text.length;
82 while (over - fits > 1) {
83 const mid = (fits + over) >> 1;
84 if (widthTo(mid) <= head.clientWidth) fits = mid;
85 else over = mid;
86 }
87 if (/[\uD800-\uDBFF]/.test(text.data[fits - 1] ?? "")) fits -= 1;
88 slack = Math.max(0, head.clientWidth - widthTo(fits));
89 }
90 head.style.clipPath = slack > 0 ? `inset(-0.25em ${slack}px -0.25em 0)` : "";
91 const tail = head.nextElementSibling;
92 if (tail instanceof HTMLElement) tail.style.translate = slack > 0 ? `-${slack}px 0` : "";
94​
95// The segments render pre so the space at the cut survives, so collapse here what CSS
96// would have (not \s: em and no-break spaces are kept). Split first, so the tail length
97// still counts the raw value.
98function collapseSegments(split: { head: string; tail: string }) {
99 const collapse = (text: string) => text.replace(/[ \t\n\r\f]+/g, " ");
100 const head = collapse(split.head).replace(/^ /, "");
101 const tail = collapse(split.tail).replace(/ $/, "");
102 return { head, tail: head.endsWith(" ") ? tail.replace(/^ /, "") : tail };
104​
105const DEFAULT_TAIL = 10;
106const MAX_SEGMENT_TAIL = 16;
107const MIN_WORD_TAIL = 4;
108const WORD_BREAK = /[-_./]/;
109​
110export function splitForMiddleTruncate(
111 value: string,
112 tail?: number,
113): { head: string; tail: string } | null {
114 // Split by code point to avoid cutting surrogate pairs into broken glyphs.
115 const chars = Array.from(value);
116 let keep = tail ?? DEFAULT_TAIL;
117 if (tail === undefined) {
118 const slash = chars.lastIndexOf("/");
119 if (slash > 0 && slash < chars.length - 1) {
120 const segment = chars.length - slash - 1;
121 keep = segment <= MAX_SEGMENT_TAIL ? segment : DEFAULT_TAIL;
122 }
123 }
124 if (keep <= 0 || chars.length <= keep + 4) return null;
125 let cut = chars.length - keep;
126 // Start an automatic tail on a word ("machine", not "er-machine"). A shorter tail is
127 // preferred so the head stays readable; a longer one is the fallback.
128 if (tail === undefined && !WORD_BREAK.test(chars[cut - 1]!)) {
129 const startsWord = (index: number) => WORD_BREAK.test(chars[index - 1]!);
130 let snapped = -1;
131 for (let index = cut + 1; index <= chars.length - MIN_WORD_TAIL; index++) {
132 if (startsWord(index)) {
133 snapped = index;
134 break;
135 }
136 }
137 for (
138 let index = cut - 1;
139 snapped < 0 && index >= chars.length - MAX_SEGMENT_TAIL && index > 4;
140 index--
141 ) {
142 if (startsWord(index)) snapped = index;
143 }
144 if (snapped > 0) cut = snapped;
145 }
146 return { head: chars.slice(0, cut).join(""), tail: chars.slice(cut).join("") };