Open History to see the last commit
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 [displayName, setDisplayName] = useState(value);
10
11 useLayoutEffect(() => {
12 const container = containerRef.current;
13 const context = document.createElement("canvas").getContext("2d");
14 if (!container || !context) return;
15
16 const update = () => {
17 const style = getComputedStyle(container);
18 context.font = style.font;
19 context.letterSpacing = style.letterSpacing === "normal" ? "0px" : style.letterSpacing;
20 setDisplayName(
21 truncateProjectName(
22 value,
23 container.getBoundingClientRect().width,
24 (text) => context.measureText(text).width,
25 ),
26 );
27 };
28 update();
29 const stopObserving = observeResize(container, update);
30 document.fonts.addEventListener("loadingdone", update);
31 return () => {
32 stopObserving();
33 document.fonts.removeEventListener("loadingdone", update);
34 };
35 }, [value]);
36
37 return (
38 <span
39 ref={containerRef}
40 className="inline-grid min-w-0 max-w-full overflow-hidden align-baseline whitespace-nowrap"
41 >
42 {/* Keep the full name's intrinsic width so fitting the visible text cannot shrink its budget. */}
43 <span
44 aria-hidden="true"
45 className="invisible col-start-1 row-start-1 min-w-0 overflow-hidden select-none"
46 >
47 {value}
48 </span>
49 <span aria-label={value} className="col-start-1 row-start-1 min-w-0 overflow-hidden">
50 {displayName}
51 </span>
52 </span>
53 );
54}