forge
Explore
Log in

Don't you dare go Hollow

hezarfen_frontend

Clone
★ 0

0 watching0 forksTypeScript5.5 MiB5fcd955Burak Boduroğlu2 months ago730 commits

chart-line.tsx245 lines, 11.5 KiBHistoryRawDownload
1import { For, Show, createMemo, createSignal, onCleanup, type Component } from "solid-js";
2import { cn } from "@/lib/cn";
3import { usePreferences } from "@/stores/preferences-context";
4import { formatDecimal } from "@/lib/format";
5import { EmptyInline } from "@/components/ui/empty-inline";
6
7export type ChartLineItem = {
8 id: string;
9 label: string;
10 value: number;
11 formattedValue?: string;
12 caption?: string;
13};
14
15export type ChartLineProps = {
16 title?: string;
17 subtitle?: string;
18 items: ChartLineItem[];
19 maxScale?: number;
20 class?: string;
21};
22
23// The drawing is laid out in real pixels: the viewBox follows the measured
24// width, so a wide card is filled edge to edge (a fixed 720-wide viewBox in a
25// 240px-tall box letterboxed it) and axis text keeps its 11px size.
26const DEFAULT_VIEW_WIDTH = 720;
27const MIN_VIEW_WIDTH = 260;
28// Room one x-axis caption needs, so a phone gets fewer ticks, not overlaps.
29const TICK_SLOT = 96;
30const VIEW_HEIGHT = 240;
31const PADDING = { top: 18, right: 18, bottom: 34, left: 38 };
32const Y_TICKS = [0, 25, 50, 75, 100];
33const TOOLTIP_WIDTH = 190;
34const TOOLTIP_HEIGHT = 62;
35const TICK_MAX_CHARS = 14;
36
37export const ChartLine: Component<ChartLineProps> = (props) => {
38 const { t, locale } = usePreferences();
39 const decimal = (value: number) => formatDecimal(value, locale());
40 const maxValue = () => props.maxScale != null && props.maxScale > 0
41 ? props.maxScale
42 : Math.max(...props.items.map((item) => item.value), 1);
43 const [viewWidth, setViewWidth] = createSignal(DEFAULT_VIEW_WIDTH);
44 const observeWidth = (el: HTMLDivElement) => {
45 if (typeof ResizeObserver === "undefined") return;
46 const observer = new ResizeObserver((entries) => {
47 const width = Math.round(entries[0]?.contentRect.width ?? 0);
48 if (width > 0) setViewWidth(Math.max(MIN_VIEW_WIDTH, width));
49 });
50 observer.observe(el);
51 onCleanup(() => observer.disconnect());
52 };
53 const plotWidth = () => viewWidth() - PADDING.left - PADDING.right;
54 const plotHeight = VIEW_HEIGHT - PADDING.top - PADDING.bottom;
55 const pointFor = (item: ChartLineItem, index: number) => {
56 const x = props.items.length === 1
57 ? PADDING.left + plotWidth() / 2
58 : PADDING.left + (index / (props.items.length - 1)) * plotWidth();
59 const y = PADDING.top + (1 - Math.min(1, Math.max(0, item.value / maxValue()))) * plotHeight;
60 return { x, y };
61 };
62 const points = createMemo(() => props.items.map((item, index) => {
63 const point = pointFor(item, index);
64 return `${point.x},${point.y}`;
65 }).join(" "));
66 const areaPoints = createMemo(() => {
67 if (props.items.length < 2) return "";
68 const baseline = PADDING.top + plotHeight;
69 return `${PADDING.left},${baseline} ${points()} ${PADDING.left + plotWidth()},${baseline}`;
70 });
71 const summary = createMemo(() => {
72 if (props.items.length === 0) return null;
73 const values = props.items.map((item) => item.value);
74 return {
75 latest: props.items[props.items.length - 1],
76 minimum: Math.min(...values),
77 maximum: Math.max(...values),
78 average: values.reduce((sum, value) => sum + value, 0) / values.length,
79 };
80 });
81 const xTickIndexes = createMemo(() => {
82 if (props.items.length <= 1) return [0];
83 const slots = Math.max(1, Math.min(5, Math.floor(plotWidth() / TICK_SLOT)));
84 const step = Math.max(1, Math.ceil((props.items.length - 1) / slots));
85 const indexes = Array.from({ length: props.items.length }, (_, index) => index)
86 .filter((index) => index % step === 0);
87 if (indexes[indexes.length - 1] !== props.items.length - 1) indexes.push(props.items.length - 1);
88 return indexes;
89 });
90 // An axis tick has ~1/6 of the width, so it carries the item's caption (a
91 // short date) or, when there is none, its position. Full labels overlap
92 // each other and are already in the tooltip and the "latest" line.
93 const tickLabel = (index: number) => {
94 const caption = props.items[index].caption;
95 if (!caption) return String(index + 1);
96 return caption.length > TICK_MAX_CHARS ? `${caption.slice(0, TICK_MAX_CHARS - 1)}…` : caption;
97 };
98 const averageY = () => PADDING.top + (1 - Math.min(1, summary()!.average / maxValue())) * plotHeight;
99
100 return (
101 <div class={cn("flex flex-col gap-4 rounded-xl border border-border-line bg-surface-base p-4", props.class)}>
102 <Show when={props.title}>
103 <div class="border-b border-border-hairline pb-3">
104 <h3 class="text-sm font-semibold tracking-tight text-foreground">{props.title}</h3>
105 <Show when={props.subtitle}>
106 <p class="mt-0.5 text-xs text-muted-foreground">{props.subtitle}</p>
107 </Show>
108 </div>
109 </Show>
110
111 <Show
112 when={summary()}
113 fallback={
114 <EmptyInline illustration="charts" title={t("dashboard.chartEmpty")} hint={t("dashboard.chartEmptyHint")} />
115 }
116 >
117 {(stats) => (
118 <div class="space-y-3">
119 <dl class="grid grid-cols-2 gap-2 sm:grid-cols-4">
120 <div class="rounded-lg bg-surface-overlay px-2.5 py-2">
121 <dt class="text-[11px] text-muted-foreground">{t("dashboard.chartExamCount")}</dt>
122 <dd class="mt-0.5 font-mono text-sm font-semibold tabular-nums">{props.items.length}</dd>
123 </div>
124 <div class="rounded-lg bg-surface-overlay px-2.5 py-2">
125 <dt class="text-[11px] text-muted-foreground">{t("dashboard.chartLatest")}</dt>
126 <dd class="mt-0.5 font-mono text-sm font-semibold tabular-nums">{stats().latest.formattedValue ?? stats().latest.value}</dd>
127 </div>
128 <div class="rounded-lg bg-surface-overlay px-2.5 py-2">
129 <dt class="text-[11px] text-muted-foreground">{t("dashboard.chartAverage")}</dt>
130 <dd class="mt-0.5 font-mono text-sm font-semibold tabular-nums">{decimal(stats().average)}</dd>
131 </div>
132 <div class="rounded-lg bg-surface-overlay px-2.5 py-2">
133 <dt class="text-[11px] text-muted-foreground">{t("dashboard.chartRange")}</dt>
134 <dd class="mt-0.5 font-mono text-sm font-semibold tabular-nums">{decimal(stats().minimum)}–{decimal(stats().maximum)}</dd>
135 </div>
136 </dl>
137
138 {/* Fits any width: the viewBox follows the box and a narrow
139 screen gets fewer x ticks, so a phone needs no sideways
140 scroller (a 480px floor cut the line with no scroll cue). */}
141 <div ref={observeWidth} class="pb-1">
142 <svg
143 class="h-60 w-full"
144 viewBox={`0 0 ${viewWidth()} ${VIEW_HEIGHT}`}
145 role="img"
146 aria-label={props.items.map((item) => `${item.label}${item.caption ? ` (${item.caption})` : ""}: ${item.formattedValue ?? item.value}`).join(", ")}
147 >
148 <For each={Y_TICKS}>
149 {(tick) => {
150 const y = () => PADDING.top + (1 - tick / 100) * plotHeight;
151 return (
152 <g>
153 <line x1={PADDING.left} x2={PADDING.left + plotWidth()} y1={y()} y2={y()} class="stroke-border/70" stroke-width="1" />
154 <text x={PADDING.left - 8} y={y() + 3} text-anchor="end" class="fill-muted-foreground text-[11px]">{tick}</text>
155 </g>
156 );
157 }}
158 </For>
159
160 <Show when={props.items.length > 1}>
161 <polygon points={areaPoints()} class="fill-primary opacity-10" />
162 <line
163 x1={PADDING.left}
164 x2={PADDING.left + plotWidth()}
165 y1={averageY()}
166 y2={averageY()}
167 class="stroke-muted-foreground"
168 stroke-width="1"
169 stroke-dasharray="4 4"
170 />
171 <polyline points={points()} fill="none" class="stroke-primary" stroke-width="3" stroke-linecap="round" stroke-linejoin="round" />
172 </Show>
173
174 <For each={props.items}>
175 {(item, index) => {
176 const point = () => pointFor(item, index());
177 const tooltipX = () => Math.min(
178 viewWidth() - PADDING.right - TOOLTIP_WIDTH,
179 Math.max(PADDING.left, point().x - TOOLTIP_WIDTH / 2),
180 );
181 const tooltipY = () => {
182 const preferred = point().y - TOOLTIP_HEIGHT - 12;
183 return preferred >= PADDING.top
184 ? preferred
185 : Math.min(point().y + 12, VIEW_HEIGHT - PADDING.bottom - TOOLTIP_HEIGHT);
186 };
187 const detail = () => `${item.label}${item.caption ? `, ${item.caption}` : ""}: ${item.formattedValue ?? item.value}`;
188 return (
189 <g class="group outline-none" tabindex="0" aria-label={detail()}>
190 <circle cx={point().x} cy={point().y} r="9" class="fill-transparent" />
191 <circle
192 cx={point().x}
193 cy={point().y}
194 r="4"
195 class="fill-primary stroke-card transition-[r] group-hover:r-[6px] group-focus:r-[6px]"
196 stroke-width="2"
197 />
198 <foreignObject
199 x={tooltipX()}
200 y={tooltipY()}
201 width={TOOLTIP_WIDTH}
202 height={TOOLTIP_HEIGHT}
203 class="pointer-events-none opacity-0 transition-opacity duration-150 group-hover:opacity-100 group-focus:opacity-100"
204 data-chart-tooltip
205 >
206 <div class="h-full rounded-md border border-border bg-popover px-3 py-2 text-popover-foreground shadow-lg">
207 <p class="truncate text-[11px] font-semibold" title={item.label}>{item.label}</p>
208 <div class="mt-1 flex items-end justify-between gap-3">
209 <span class="truncate text-[11px] text-muted-foreground">{item.caption}</span>
210 <span class="font-mono text-base font-bold leading-none tabular-nums">{item.formattedValue ?? item.value}</span>
211 </div>
212 </div>
213 </foreignObject>
214 </g>
215 );
216 }}
217 </For>
218
219 <For each={xTickIndexes()}>
220 {(index) => {
221 const point = () => pointFor(props.items[index], index);
222 return (
223 <text
224 x={point().x}
225 y={VIEW_HEIGHT - 10}
226 text-anchor={index === 0 ? "start" : index === props.items.length - 1 ? "end" : "middle"}
227 class="fill-muted-foreground text-[11px]"
228 >
229 {tickLabel(index)}
230 </text>
231 );
232 }}
233 </For>
234 </svg>
235 </div>
236 <p class="truncate text-[11px] text-muted-foreground" title={stats().latest.label}>
237 {t("dashboard.chartLatestExam")}: <span class="font-medium text-foreground/80">{stats().latest.label}</span>
238 <Show when={stats().latest.caption}> · {stats().latest.caption}</Show>
239 </p>
240 </div>
241 )}
242 </Show>
243 </div>
244 );
245};