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

lazy-charts.tsx

125 lines4.3 KB

1import { RotateCw } from "lucide-react";
2import { Component, Suspense, lazy, useMemo } from "react";
3import type { ComponentProps, ComponentType, ErrorInfo, ReactNode } from "react";
4​
5import { createStore, useStore } from "@/lib/store";
6​
7import { DAY_CHART_HEIGHT, folderChartHeight } from "./analytics-data";
8import { chartChunkUrlFrom, createChartsLoader } from "./charts-loader";
9import type { DayBarChart, FolderBarChart } from "./charts";
10​
11/*
12 * The charts, loaded on demand: the first one to render fetches the chart
13 * library, and a placeholder of the same height holds its place meanwhile,
14 * so nothing jumps when it arrives.
15 *
16 * If the library can't be fetched (a flaky network, a deploy that removed
17 * the old chunk), each chart says so in its own place, with a button to try
18 * again; the rest of the page, the guide and the "Show as table" numbers
19 * stay. Retrying fetches the module again for every chart at once.
20 */
21​
22type ChartsModule = typeof import("./charts");
23​
24/** The chart module, imported once, and again on "Try again" (see `charts-loader.ts`). */
25const loadCharts = createChartsLoader<ChartsModule>({
26 importModule: () => import("./charts"),
27 importUrl: (url) => import(/* @vite-ignore */ url) as Promise<ChartsModule>,
28 chunkUrlFrom: (error) => chartChunkUrlFrom(error, import.meta.url, window.location.origin),
29});
30​
31/** Bumped by "Try again": every chart makes a fresh lazy component and clears its error. */
32const attemptStore = createStore(0);
33​
34function retryCharts() {
35 attemptStore.set((attempt) => attempt + 1);
37​
38/** `lazy()` remembers a failure for good, so each attempt gets its own lazy component. */
39function useLazyChart<TName extends "FolderBarChart" | "DayBarChart">(name: TName) {
40 const attempt = useStore(attemptStore);
41 const Chart = useMemo(
42 () =>
43 lazy(() =>
44 loadCharts().then((module) => ({
45 default: module[name] as ComponentType<ComponentProps<ChartsModule[TName]>>,
46 })),
47 ),
48 // A new attempt needs a new lazy component.
49 [name, attempt],
50 );
51 return { Chart, attempt };
53​
54export function LazyFolderBarChart(props: ComponentProps<typeof FolderBarChart>) {
55 const { Chart, attempt } = useLazyChart("FolderBarChart");
56 const height = folderChartHeight(props.rows.length);
57 return (
58 <ChartErrorBoundary key={attempt} height={height}>
59 <Suspense fallback={<ChartPlaceholder height={height} />}>
60 <Chart {...props} />
61 </Suspense>
62 </ChartErrorBoundary>
63 );
65​
66export function LazyDayBarChart(props: ComponentProps<typeof DayBarChart>) {
67 const { Chart, attempt } = useLazyChart("DayBarChart");
68 return (
69 <ChartErrorBoundary key={attempt} height={DAY_CHART_HEIGHT}>
70 <Suspense fallback={<ChartPlaceholder height={DAY_CHART_HEIGHT} />}>
71 <Chart {...props} />
72 </Suspense>
73 </ChartErrorBoundary>
74 );
76​
77export function ChartPlaceholder({ height }: { height: number }) {
78 return (
79 <div
80 aria-hidden
81 style={{ height }}
82 className="rounded-lg bg-current/5 motion-safe:animate-pulse"
83 />
84 );
86​
87/** Keeps a chart that failed to load (or render) from taking the page down with it. */
88class ChartErrorBoundary extends Component<
89 { height: number; children: ReactNode },
90 { failed: boolean }
91> {
92 state = { failed: false };
93​
94 static getDerivedStateFromError() {
95 return { failed: true };
96 }
97​
98 componentDidCatch(error: unknown, info: ErrorInfo) {
99 console.error("A chart failed to load", error, info.componentStack);
100 }
101​
102 render() {
103 if (!this.state.failed) return this.props.children;
104 return <ChartUnavailable height={this.props.height} />;
105 }
107​
108function ChartUnavailable({ height }: { height: number }) {
109 return (
110 <div
111 style={{ minHeight: Math.min(height, 140) }}
112 className="flex flex-col items-center justify-center gap-2 rounded-lg bg-current/5 px-4 py-3 text-center"
113 >
114 <p className="text-[0.9em] opacity-75">Couldn't load the chart.</p>
115 <button
116 type="button"
117 onClick={retryCharts}
118 className="inline-flex h-7 items-center gap-1.5 rounded-full border border-current/20 px-3 text-[0.85em] font-medium transition-colors outline-none hover:bg-current/10 focus-visible:ring-2 focus-visible:ring-notes-accent/60"
119 >
120 <RotateCw className="size-3.5" aria-hidden />
121 Try again
122 </button>
123 </div>
124 );