Skip to content
Source
Sign inSign up
fuko/trytanstackdb.com
Open History to see the last commit

live-words-chart.tsx

64 lines2.3 KB

1import { useEffect, useRef, useState } from "react";
2​
3import { folderChartHeight, useAnalyticsRows } from "@/components/notes/analytics-data";
4import { ChartPlaceholder, LazyFolderBarChart } from "@/components/notes/lazy-charts";
5​
6/**
7 * Words per folder, drawn in the guide from the same live query as the
8 * Analytics page. With the app beside the guide, it moves as you type.
9 *
10 * The guide is on screen from the first paint, but this chart sits far down
11 * it: the chart library only loads once the chart comes near the viewport.
12 */
13export function LiveWordsChart() {
14 const { folderRows } = useAnalyticsRows();
15 const ref = useRef<HTMLElement>(null);
16 const nearViewport = useNearViewport(ref);
17​
18 return (
19 <figure
20 ref={ref}
21 className="analytics-chart not-prose my-5 rounded-xl border bg-background/60 px-4 pt-3 pb-2 text-[13px]"
22 >
23 <figcaption className="mb-1 flex items-center gap-2 text-[12px] font-medium text-muted-foreground">
24 <span
25 className="size-1.5 rounded-full bg-emerald-500 motion-safe:animate-pulse"
26 aria-hidden
27 />
28 Live: words per folder
29 </figcaption>
30 {nearViewport ? (
31 <LazyFolderBarChart rows={folderRows} measure="words" />
32 ) : (
33 <ChartPlaceholder height={folderChartHeight(folderRows.length)} />
34 )}
35 </figure>
36 );
38​
39/** Becomes `true` (and stays) once the element is within a screen of the viewport. */
40function useNearViewport(ref: React.RefObject<HTMLElement | null>): boolean {
41 const [near, setNear] = useState(false);
42 useEffect(() => {
43 const element = ref.current;
44 if (!element || near) return;
45 // The guide scrolls inside its own container; the margin only reaches
46 // past the edge of the observer's root, so observe from there.
47 const observer = new IntersectionObserver(
48 (entries) => {
49 if (entries.some((entry) => entry.isIntersecting)) setNear(true);
50 },
51 { root: scrollParent(element), rootMargin: "100% 0px" },
52 );
53 observer.observe(element);
54 return () => observer.disconnect();
55 }, [ref, near]);
56 return near;
58​
59function scrollParent(element: HTMLElement): HTMLElement | null {
60 for (let parent = element.parentElement; parent; parent = parent.parentElement) {
61 if (/(auto|scroll)/.test(getComputedStyle(parent).overflowY)) return parent;
62 }
63 return null;