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

DraftProjectName.tsx

58 lines2.0 KB

1import { useLayoutEffect, useRef, useState } from "react";
2​
3import { observeResize } from "~/lib/observeResize";
4​
5import { truncateProjectName } from "./DraftProjectName.logic";
6​
7export function DraftProjectName({ value }: { value: string }) {
8 const containerRef = useRef<HTMLSpanElement>(null);
9 const measurementRef = useRef<HTMLSpanElement>(null);
10 const [displayName, setDisplayName] = useState(value);
11​
12 useLayoutEffect(() => {
13 const container = containerRef.current;
14 const measurement = measurementRef.current;
15 if (!container || !measurement) return;
16​
17 const update = () => {
18 // Canvas text metrics can differ from layout for the same font, weight, and zoom.
19 // Measure in the DOM so a name that fits never loses characters to that mismatch.
20 setDisplayName(
21 truncateProjectName(value, container.getBoundingClientRect().width, (text) => {
22 measurement.textContent = text;
23 return measurement.getBoundingClientRect().width;
24 }),
25 );
26 };
27 update();
28 const stopObserving = observeResize(container, update);
29 document.fonts.addEventListener("loadingdone", update);
30 return () => {
31 stopObserving();
32 document.fonts.removeEventListener("loadingdone", update);
33 };
34 }, [value]);
35​
36 return (
37 <span
38 ref={containerRef}
39 className="relative inline-grid min-w-0 max-w-full overflow-hidden align-baseline whitespace-nowrap"
40 >
41 {/* Keep the full name's intrinsic width so fitting the visible text cannot shrink its budget. */}
42 <span
43 aria-hidden="true"
44 className="invisible col-start-1 row-start-1 min-w-0 overflow-hidden select-none"
45 >
46 {value}
47 </span>
48 <span aria-label={value} className="col-start-1 row-start-1 min-w-0 overflow-hidden">
49 {displayName}
50 </span>
51 <span
52 ref={measurementRef}
53 aria-hidden="true"
54 className="invisible absolute top-0 left-0 w-max select-none"
55 />
56 </span>
57 );