The best way to control Claude Code, Codex and more from any computer or phone
| 1 | import { type ComponentProps, useLayoutEffect, useRef } from "react"; |
| 2 | |
| 3 | import { observeResize } from "~/lib/observeResize"; |
| 4 | import { cn } from "~/lib/utils"; |
| 5 | |
| 6 | export 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 | scheduleFit(element); |
| 29 | return observeResize(element, () => scheduleFit(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 | ); |
| 61 | } |
| 62 | |
| 63 | // Fitting heads one by one forces a layout per row, since each read follows the previous |
| 64 | // head's write. Heads queued in one commit or resize delivery fit together in a microtask, |
| 65 | // still before paint: all reads, then all writes. |
| 66 | const pendingFits = new Set<HTMLElement>(); |
| 67 | |
| 68 | function scheduleFit(head: HTMLElement) { |
| 69 | if (pendingFits.size === 0) queueMicrotask(fitPendingHeads); |
| 70 | pendingFits.add(head); |
| 71 | } |
| 72 | |
| 73 | // An overflowing head is cut after its last whole character: clip the partial glyph |
| 74 | // and slide the tail left over the slack. Neither changes layout, so the observed |
| 75 | // size stays the true available width. |
| 76 | function fitPendingHeads() { |
| 77 | const heads = [...pendingFits].filter((head) => head.isConnected); |
| 78 | pendingFits.clear(); |
| 79 | const overflowing = heads.map( |
| 80 | (head) => head.scrollWidth > head.clientWidth && head.firstChild instanceof Text, |
| 81 | ); |
| 82 | heads.forEach((head, index) => head.toggleAttribute("data-overflow", overflowing[index])); |
| 83 | const slacks = heads.map((head, index) => (overflowing[index] ? measureSlack(head) : 0)); |
| 84 | heads.forEach((head, index) => { |
| 85 | const slack = slacks[index]!; |
| 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 | } |
| 91 | |
| 92 | function measureSlack(head: HTMLElement) { |
| 93 | const text = head.firstChild as Text; |
| 94 | const range = document.createRange(); |
| 95 | const left = head.getBoundingClientRect().left; |
| 96 | const width = head.clientWidth; |
| 97 | const widthTo = (end: number) => { |
| 98 | range.setStart(text, 0); |
| 99 | range.setEnd(text, end); |
| 100 | return range.getBoundingClientRect().right - left; |
| 101 | }; |
| 102 | let fits = 0; |
| 103 | let over = text.length; |
| 104 | while (over - fits > 1) { |
| 105 | const mid = (fits + over) >> 1; |
| 106 | if (widthTo(mid) <= width) fits = mid; |
| 107 | else over = mid; |
| 108 | } |
| 109 | if (/[\uD800-\uDBFF]/.test(text.data[fits - 1] ?? "")) fits -= 1; |
| 110 | return Math.max(0, width - widthTo(fits)); |
| 111 | } |
| 112 | |
| 113 | // The segments render pre so the space at the cut survives, so collapse here what CSS |
| 114 | // would have (not \s: em and no-break spaces are kept). Split first, so the tail length |
| 115 | // still counts the raw value. |
| 116 | function collapseSegments(split: { head: string; tail: string }) { |
| 117 | const collapse = (text: string) => text.replace(/[ \t\n\r\f]+/g, " "); |
| 118 | const head = collapse(split.head).replace(/^ /, ""); |
| 119 | const tail = collapse(split.tail).replace(/ $/, ""); |
| 120 | return { head, tail: head.endsWith(" ") ? tail.replace(/^ /, "") : tail }; |
| 121 | } |
| 122 | |
| 123 | const DEFAULT_TAIL = 10; |
| 124 | const MAX_SEGMENT_TAIL = 16; |
| 125 | const MIN_WORD_TAIL = 4; |
| 126 | const WORD_BREAK = /[-_./]/; |
| 127 | |
| 128 | export function splitForMiddleTruncate( |
| 129 | value: string, |
| 130 | tail?: number, |
| 131 | ): { head: string; tail: string } | null { |
| 132 | // Split by code point to avoid cutting surrogate pairs into broken glyphs. |
| 133 | const chars = Array.from(value); |
| 134 | let keep = tail ?? DEFAULT_TAIL; |
| 135 | if (tail === undefined) { |
| 136 | const slash = chars.lastIndexOf("/"); |
| 137 | if (slash > 0 && slash < chars.length - 1) { |
| 138 | const segment = chars.length - slash - 1; |
| 139 | keep = segment <= MAX_SEGMENT_TAIL ? segment : DEFAULT_TAIL; |
| 140 | } |
| 141 | } |
| 142 | if (keep <= 0 || chars.length <= keep + 4) return null; |
| 143 | let cut = chars.length - keep; |
| 144 | // Start an automatic tail on a word ("machine", not "er-machine"). A shorter tail is |
| 145 | // preferred so the head stays readable; a longer one is the fallback. |
| 146 | if (tail === undefined && !WORD_BREAK.test(chars[cut - 1]!)) { |
| 147 | const startsWord = (index: number) => WORD_BREAK.test(chars[index - 1]!); |
| 148 | let snapped = -1; |
| 149 | for (let index = cut + 1; index <= chars.length - MIN_WORD_TAIL; index++) { |
| 150 | if (startsWord(index)) { |
| 151 | snapped = index; |
| 152 | break; |
| 153 | } |
| 154 | } |
| 155 | for ( |
| 156 | let index = cut - 1; |
| 157 | snapped < 0 && index >= chars.length - MAX_SEGMENT_TAIL && index > 4; |
| 158 | index-- |
| 159 | ) { |
| 160 | if (startsWord(index)) snapped = index; |
| 161 | } |
| 162 | if (snapped > 0) cut = snapped; |
| 163 | } |
| 164 | return { head: chars.slice(0, cut).join(""), tail: chars.slice(cut).join("") }; |
| 165 | } |