Skip to content

Every analytics tool wants a subscription. And your data. I built Twiligent instead. YouTube stats. Instagram stats. One dashboard. Runs locally on your machine.

feat(frontend): add a stacked bar card adapted from Bencho's Stacked bars

spacesdrivef0abe0e70f50
diff --git a/THIRD_PARTY_NOTICES.md b/THIRD_PARTY_NOTICES.md
index 35e3b49..c206ad6 100644
--- a/THIRD_PARTY_NOTICES.md
+++ b/THIRD_PARTY_NOTICES.md
@@ -18,7 +18,13 @@ Twiligent includes work by others under their own licences. This file gives the
- **Licence:** MIT. Copyright (c) 2024 Irsyad A. Panjaitan. The full MIT text is at the end of this file
- **Changes:** class names merge through the app's own `cn()` instead of the `cn` package; React Aria's `selected:` variant is written as `data-selected:` so no Tailwind plugin is needed; the tooltip's overlay colours map to the app's surface and ink tokens; legend buttons take their accessible name from their visible label
-## MIT licence text
+## Bencho blocks
+
+- **Used in:** the app (`frontend/`): `src/components/RollingNumber.tsx` with `src/lib/rollingNumber.ts`, adapted from the Rolling counter block, and `src/components/StackedBars.tsx` with `src/lib/stackedBars.ts`, adapted from the Stacked bars block; their styles are the `.roll-*` and `.stb-*` rules in `src/index.css`
+- **Author:** Lorenzo Cabra
+- **Source:** [bencho.dev](https://bencho.dev), the free blocks' Code pane, read on 2026-11-05 without an account (the licence calls these free blocks MIT)
+- **Licence:** MIT. Copyright (c) 2026 Lorenzo Cabra. The full MIT text is at the end of this file. "Bencho" is the author's trademark and is not used in the product
+- **Changes:** Rolling counter's odometer strips are kept and its number input with buttons, drag and sounds is left out, so it only displays a value. Stacked bars draws real data from props in the app's design tokens, sizes itself to its box, glides with CSS transitions instead of framer-motion, and adds the arrow keys, an announced status line and a legend
The works above marked MIT are given under this text, with their own copyright line:
diff --git a/frontend/src/components/StackedBars.tsx b/frontend/src/components/StackedBars.tsx
new file mode 100644
index 0000000..e69b7e2
--- /dev/null
+++ b/frontend/src/components/StackedBars.tsx
@@ -0,0 +1,218 @@
+import { useEffect, useMemo, useRef, useState } from 'react';
+import type { CSSProperties, KeyboardEvent, PointerEvent } from 'react';
+import SurfaceBox from '@/components/SurfaceBox';
+import SegmentedChoice from '@/components/SegmentedChoice';
+import RollingNumber from '@/components/RollingNumber';
+import LiveStatus from '@/components/LiveStatus';
+import { stackedColumns, tooltipLeft } from '@/lib/stackedBars';
+import type { StackedPoint } from '@/lib/stackedBars';
+import { fmtNumFull } from '@/utils/formatters';
+
+export interface StackedSeries {
+ label: string;
+ // a design token colour, such as SERIES.primary
+ color: string;
+}
+
+export interface StackedView {
+ id: string;
+ label: string;
+ points: StackedPoint[];
+}
+
+export interface StackedBarsProps {
+ title: string;
+ subtitle?: string;
+ // what one count is, in the plural ("posts", "comments")
+ unit: string;
+ series: StackedSeries[];
+ // one view, or several the person switches between (by day, by week)
+ views: StackedView[];
+ height?: number;
+ gap?: number;
+ className?: string;
+}
+
+const TIP_WIDTH = 152;
+
+// adapted from Bencho's Stacked bars (MIT, see THIRD_PARTY_NOTICES.md): run along the bars, or use the arrow keys, and
+// one column is ringed while a tooltip glides beside it with the period, the total and what made it up
+export default function StackedBars({ title, subtitle, unit, series, views, height = 120, gap = 6, className }: StackedBarsProps) {
+ const [viewId, setViewId] = useState(views[0]?.id ?? '');
+ const view = views.find(item => item.id === viewId) ?? views[0];
+ const points = useMemo(() => view?.points ?? [], [view]);
+ const [at, setAt] = useState<number | null>(null);
+ const [width, setWidth] = useState(0);
+ // without IntersectionObserver the bars draw at once
+ const [seen, setSeen] = useState(() => typeof IntersectionObserver === 'undefined');
+ const plot = useRef<HTMLDivElement>(null);
+
+ useEffect(() => {
+ const node = plot.current;
+ if (!node) return;
+ const measure = () => setWidth(node.clientWidth);
+ measure();
+ const resize = new ResizeObserver(measure);
+ resize.observe(node);
+ // the bars grow out of the baseline the first time the card is on screen
+ if (typeof IntersectionObserver === 'undefined') return () => resize.disconnect();
+ const visible = new IntersectionObserver(([entry]) => {
+ if (entry.isIntersecting) {
+ setSeen(true);
+ visible.disconnect();
+ }
+ }, { threshold: 0.3 });
+ visible.observe(node);
+ return () => {
+ resize.disconnect();
+ visible.disconnect();
+ };
+ }, []);
+
+ const columns = useMemo(() => stackedColumns(points, width, height, gap), [points, width, height, gap]);
+ const total = columns.reduce((sum, column) => sum + column.total, 0);
+ const active = at !== null && at < columns.length ? at : null;
+ const current = active === null ? null : points[active];
+ const column = active === null ? null : columns[active];
+
+ const pick = (event: PointerEvent<HTMLDivElement>) => {
+ const box = plot.current?.getBoundingClientRect();
+ if (!box || box.width === 0 || points.length === 0) return;
+ const index = Math.floor(((event.clientX - box.left) / box.width) * points.length);
+ setAt(Math.max(0, Math.min(points.length - 1, index)));
+ };
+
+ const handleKeyDown = (event: KeyboardEvent<HTMLDivElement>) => {
+ const last = points.length - 1;
+ const moves: Record<string, number> = {
+ ArrowLeft: Math.max(0, (active ?? last + 1) - 1),
+ ArrowRight: Math.min(last, (active ?? -1) + 1),
+ Home: 0,
+ End: last,
+ };
+ if (event.key in moves) {
+ event.preventDefault();
+ setAt(moves[event.key]);
+ } else if (event.key === 'Escape') {
+ setAt(null);
+ }
+ };
+
+ const status = current
+ ? `${current.label}: ${fmtNumFull(columns[active!].total)} ${unit}. ${series
+ .map((item, index) => `${item.label} ${fmtNumFull(current.values[index] ?? 0)}`)
+ .join(', ')}.`
+ : '';
+
+ return (
+ <SurfaceBox
+ title={title}
+ subheader={subtitle}
+ className={className}
+ secondary={views.length > 1 ? (
+ <SegmentedChoice
+ name={`${title}-range`}
+ options={views.map(item => ({ value: item.id, label: item.label }))}
+ value={view?.id ?? ''}
+ onChange={next => { setViewId(next); setAt(null); }}
+ />
+ ) : undefined}
+ >
+ <div className="stb flex flex-col gap-3" data-scrub={current ? '' : undefined}>
+ <p className="flex items-baseline gap-2">
+ <RollingNumber text={fmtNumFull(total)} className="text-metric font-semibold tracking-tight" />
+ <span className="text-sm text-ink-muted">{unit}</span>
+ </p>
+ <div
+ ref={plot}
+ role="group"
+ tabIndex={0}
+ aria-label={`${title}, ${view?.label ?? ''}. Use the left and right arrow keys to read each bar.`}
+ className="relative w-full cursor-crosshair touch-none rounded-row"
+ style={{ height: height + 1 }}
+ onPointerDown={event => {
+ try { event.currentTarget.setPointerCapture(event.pointerId); } catch { /* a scripted event has no pointer to capture */ }
+ pick(event);
+ }}
+ onPointerMove={pick}
+ onPointerUp={event => {
+ try { event.currentTarget.releasePointerCapture(event.pointerId); } catch { /* nothing was captured */ }
+ if (event.pointerType !== 'mouse') setAt(null);
+ }}
+ onPointerCancel={() => setAt(null)}
+ onPointerLeave={() => setAt(null)}
+ onKeyDown={handleKeyDown}
+ onBlur={() => setAt(null)}
+ >
+ <span className="absolute inset-x-0 h-px bg-divider" style={{ top: height }} />
+ {columns.map((item, index) => (
+ <div
+ key={`${view?.id}-${index}`}
+ className="stb-col absolute top-0 bottom-0"
+ data-on={active === index || undefined}
+ style={{ left: item.left, width: item.width, '--i': index } as CSSProperties}
+ >
+ {item.segments.map((segment, segmentIndex) => (
+ <span
+ key={segmentIndex}
+ className="stb-bar"
+ style={{
+ '--c': series[segmentIndex]?.color ?? 'var(--chart-1)',
+ bottom: 1 + (seen ? segment.bottom : 0),
+ height: seen ? segment.height : 0,
+ } as CSSProperties}
+ />
+ ))}
+ </div>
+ ))}
+ {column && (
+ <span
+ className="stb-ring"
+ aria-hidden="true"
+ style={{
+ transform: `translate(${column.left - 3}px, ${height - column.top - 3}px)`,
+ width: column.width + 6,
+ height: column.top + 6,
+ }}
+ />
+ )}
+ {current && column && (
+ <div
+ className="stb-tip"
+ aria-hidden="true"
+ style={{ transform: `translateX(${tooltipLeft(column, width, TIP_WIDTH)}px)`, width: TIP_WIDTH }}
+ >
+ <div className="flex justify-between gap-2 text-ink-muted">
+ <span>{current.label}</span>
+ <b className="font-medium text-ink tabular-nums">{fmtNumFull(column.total)}</b>
+ </div>
+ {series.map((item, index) => (
+ <div key={item.label} className="flex items-center gap-1.5">
+ <i className="size-2 shrink-0 rounded-xs" style={{ backgroundColor: item.color }} />
+ <span className="flex-1 text-ink-muted">{item.label}</span>
+ <b className="font-normal text-ink tabular-nums">{fmtNumFull(current.values[index] ?? 0)}</b>
+ </div>
+ ))}
+ </div>
+ )}
+ </div>
+ {points.length > 0 && (
+ <div className="flex justify-between text-caption text-ink-faint tabular-nums">
+ <span>{points[0].short}</span>
+ <span>{points[points.length - 1].short}</span>
+ </div>
+ )}
+ <ul className="flex flex-wrap gap-x-4 gap-y-1 text-caption text-ink-muted">
+ {series.map(item => (
+ <li key={item.label} className="flex items-center gap-1.5">
+ <i className="size-2 rounded-xs" style={{ backgroundColor: item.color }} aria-hidden="true" />
+ {item.label}
+ </li>
+ ))}
+ </ul>
+ <LiveStatus message={status} />
+ </div>
+ </SurfaceBox>
+ );
+}
+
diff --git a/frontend/src/index.css b/frontend/src/index.css
index 66e92d3..0736a24 100644
--- a/frontend/src/index.css
+++ b/frontend/src/index.css
@@ -377,6 +377,58 @@
.scrollbar-hide::-webkit-scrollbar {
display: none;
}
+ /* StackedBars (adapted from Bencho, MIT): segments grow with a stagger along the row, the others step back by mixing
+ toward the card instead of fading, and the ring and tooltip glide to the column under the pointer */
+ .stb-bar {
+ position: absolute;
+ inset-inline: 0;
+ border-radius: 2.5px;
+ background-color: var(--c);
+ transition:
+ height 600ms var(--ease-fold) calc(var(--i) * 14ms),
+ bottom 600ms var(--ease-fold) calc(var(--i) * 14ms),
+ background-color var(--duration-base) ease;
+ }
+ .stb[data-scrub] .stb-col:not([data-on]) .stb-bar {
+ background-color: color-mix(in srgb, var(--c) 38%, var(--surface-raised));
+ }
+ .stb-ring {
+ position: absolute;
+ top: 0;
+ left: 0;
+ border: 1.5px solid var(--ink-muted);
+ border-radius: 5.5px;
+ pointer-events: none;
+ transition: transform var(--duration-overlay) var(--ease-fold), height var(--duration-overlay) var(--ease-fold);
+ }
+ .stb-tip {
+ position: absolute;
+ top: 0;
+ left: 0;
+ display: flex;
+ flex-direction: column;
+ gap: 4px;
+ padding: 8px 10px;
+ border: 1px solid var(--line);
+ border-radius: var(--radius-control);
+ background: var(--surface-overlay);
+ box-shadow: var(--shadow-md);
+ font-size: var(--text-caption);
+ line-height: var(--text-caption--line-height);
+ pointer-events: none;
+ transition: transform var(--duration-overlay) var(--ease-fold);
+ }
+ /* RollingNumber: each digit is a 0 to 9 strip seen through a one-line window; the ones column moves first */
+ .roll { display: inline-block; }
+ .roll-row { display: inline-flex; }
+ .roll-window { display: inline-block; height: 1lh; overflow: hidden; }
+ .roll-strip {
+ display: flex;
+ flex-direction: column;
+ transform: translateY(calc(var(--roll-digit) * -1lh));
+ transition: transform 600ms var(--ease-fold) calc(var(--roll-order) * 40ms);
+ }
+ .roll-strip > span { height: 1lh; }
.delayed-appear {
animation: delayed-appear 1ms var(--spinner-delay, 300ms) both;
}
diff --git a/frontend/src/lib/stackedBars.ts b/frontend/src/lib/stackedBars.ts
new file mode 100644
index 0000000..4e87f78
--- /dev/null
+++ b/frontend/src/lib/stackedBars.ts
@@ -0,0 +1,62 @@
+// geometry for the stacked bar card: columns across the width, each a stack of segments rising from the baseline
+
+export interface StackedPoint {
+ // the full label read in the tooltip ("Oct 11", "Oct 5 to 11") and the short one under the axis
+ label: string;
+ short: string;
+ values: number[];
+}
+
+export interface StackedSegment {
+ bottom: number;
+ height: number;
+}
+
+export interface StackedColumn {
+ left: number;
+ width: number;
+ top: number;
+ total: number;
+ segments: StackedSegment[];
+}
+
+// segments keep a hairline of air between them, and a stack never draws thinner than a visible sliver
+const SEGMENT_GAP = 2;
+const MIN_SEGMENT = 2;
+const MIN_BAR_WIDTH = 3;
+
+export function stackedColumns(points: StackedPoint[], width: number, height: number, gap: number): StackedColumn[] {
+ const count = points.length;
+ if (count === 0 || width <= 0) return [];
+ // the gap gives way before a bar gets thinner than 3 px, so a long range still draws
+ const actualGap = count === 1 ? 0 : Math.max(1, Math.min(gap, (width - MIN_BAR_WIDTH * count) / (count - 1)));
+ const barWidth = (width - actualGap * (count - 1)) / count;
+ const totals = points.map(point => point.values.reduce((sum, value) => sum + value, 0));
+ const maxTotal = Math.max(1, ...totals);
+ const segmentCount = Math.max(1, ...points.map(point => point.values.length));
+ const scale = (height - SEGMENT_GAP * (segmentCount - 1)) / maxTotal;
+ return points.map((point, index) => {
+ let bottom = 0;
+ const segments = point.values.map(value => {
+ const segmentHeight = value > 0 ? Math.max(MIN_SEGMENT, value * scale) : 0;
+ const segment = { bottom, height: segmentHeight };
+ if (segmentHeight > 0) bottom += segmentHeight + SEGMENT_GAP;
+ return segment;
+ });
+ return {
+ left: index * (barWidth + actualGap),
+ width: barWidth,
+ top: Math.max(0, bottom - SEGMENT_GAP),
+ total: totals[index],
+ segments,
+ };
+ });
+}
+
+// the tooltip sits right of the column while it fits, otherwise left of it, and never past either edge
+export function tooltipLeft(column: StackedColumn, width: number, tipWidth: number, offset = 8): number {
+ const right = column.left + column.width + offset;
+ if (right + tipWidth <= width) return right;
+ const left = column.left - offset - tipWidth;
+ return left >= 0 ? left : Math.max(0, Math.min(width - tipWidth, right));
+}
diff --git a/frontend/tests/lib/stackedBars.test.ts b/frontend/tests/lib/stackedBars.test.ts
new file mode 100644
index 0000000..a9e5ff1
--- /dev/null
+++ b/frontend/tests/lib/stackedBars.test.ts
@@ -0,0 +1,47 @@
+import { test } from 'node:test';
+import assert from 'node:assert/strict';
+import { stackedColumns, tooltipLeft } from '../../src/lib/stackedBars.ts';
+
+const points = [
+ { label: 'Mon', short: 'Mon', values: [10, 5] },
+ { label: 'Tue', short: 'Tue', values: [20, 10] },
+];
+
+test('columns fill the width with the gap between them', () => {
+ const columns = stackedColumns(points, 106, 100, 6);
+ assert.equal(columns.length, 2);
+ assert.equal(columns[0].left, 0);
+ assert.equal(columns[0].width, 50);
+ assert.equal(columns[1].left, 56);
+});
+
+test('the tallest stack reaches the full height and its segments sit on top of each other', () => {
+ const [, tallest] = stackedColumns(points, 106, 100, 6);
+ assert.equal(tallest.total, 30);
+ assert.ok(Math.abs(tallest.top - 100) < 0.001);
+ assert.equal(tallest.segments[0].bottom, 0);
+ assert.ok(Math.abs(tallest.segments[1].bottom - (tallest.segments[0].height + 2)) < 0.001);
+});
+
+test('a zero value draws no segment and leaves no gap', () => {
+ const [column] = stackedColumns([{ label: 'a', short: 'a', values: [0, 4] }], 50, 100, 6);
+ assert.equal(column.segments[0].height, 0);
+ assert.equal(column.segments[1].bottom, 0);
+});
+
+test('the gap shrinks before bars get thinner than 3 px', () => {
+ const many = Array.from({ length: 30 }, (_, index) => ({ label: `${index}`, short: `${index}`, values: [1] }));
+ const columns = stackedColumns(many, 120, 100, 6);
+ assert.ok(columns[0].width >= 3);
+ assert.ok(columns[29].left + columns[29].width <= 120.001);
+});
+
+test('the tooltip sits right of a column while it fits and flips left near the edge', () => {
+ const [first, second] = stackedColumns(points, 300, 100, 6);
+ assert.equal(tooltipLeft(first, 300, 120), first.left + first.width + 8);
+ assert.equal(tooltipLeft(second, 300, 120), second.left - 8 - 120);
+});
+
+test('an empty range draws nothing', () => {
+ assert.deepEqual(stackedColumns([], 300, 100, 6), []);
+});