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

middle-truncate.tsx

62 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 // Split by code point to avoid cutting surrogate pairs into broken glyphs.
50 const chars = Array.from(value);
51 let keep = tail ?? DEFAULT_TAIL;
52 if (tail === undefined) {
53 const slash = chars.lastIndexOf("/");
54 if (slash > 0 && slash < chars.length - 1) {
55 const segment = chars.length - slash - 1;
56 keep = segment <= MAX_SEGMENT_TAIL ? segment : DEFAULT_TAIL;
57 }
58 }
59 if (keep <= 0 || chars.length <= keep + 4) return null;
60 const cut = chars.length - keep;
61 return { head: chars.slice(0, cut).join(""), tail: chars.slice(cut).join("") };