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

middle-truncate.tsx

63 lines1.8 KB

1import type { ComponentProps } from "react";
2​
3import { cn } from "~/lib/utils";
4​
5export function MiddleTruncate({
6 value,
7 tail,
8 showTitle = true,
9 variant = "default",
10 className,
11 ...props
12}: Omit<ComponentProps<"span">, "children"> & {
13 value: string;
14 tail?: number;
15 showTitle?: boolean;
16 variant?: "default" | "cap-aligned";
17}) {
18 const split = splitForMiddleTruncate(value, tail);
19 return (
20 <span
21 {...(showTitle ? { title: value } : {})}
22 className={cn(
23 "inline-flex min-w-0 max-w-full overflow-hidden whitespace-nowrap",
24 variant === "cap-aligned" &&
25 "overflow-x-clip overflow-y-visible [&>span]:[text-box:trim-both_cap_alphabetic] [&>span]:overflow-x-clip [&>span]:overflow-y-visible",
26 className,
27 )}
28 {...props}
29 >
30 {split ? (
31 <>
32 <span className="min-w-0 truncate">{split.head}</span>
33 <span className="shrink-0">{split.tail}</span>
34 </>
35 ) : (
36 <span className="min-w-0 truncate">{value}</span>
37 )}
38 </span>
39 );
41​
42const DEFAULT_TAIL = 10;
43const MAX_SEGMENT_TAIL = 16;
44​
45export function splitForMiddleTruncate(
46 value: string,
47 tail?: number,
48): { head: string; tail: string } | null {
49 // Code points, not UTF-16 units: a cut inside a surrogate pair would render two broken
50 // glyphs where an emoji or a CJK extension character used to be.
51 const chars = Array.from(value);
52 let keep = tail ?? DEFAULT_TAIL;
53 if (tail === undefined) {
54 const slash = chars.lastIndexOf("/");
55 if (slash > 0 && slash < chars.length - 1) {
56 const segment = chars.length - slash - 1;
57 keep = segment <= MAX_SEGMENT_TAIL ? segment : DEFAULT_TAIL;
58 }
59 }
60 if (keep <= 0 || chars.length <= keep + 4) return null;
61 const cut = chars.length - keep;
62 return { head: chars.slice(0, cut).join(""), tail: chars.slice(cut).join("") };