Step 7 of 7. Move the connection settings from build-time variables into a settings bar kept in localStorage.
The settings come from .env.local, so another project means another build. This last step adds a settings bar for the API, the project, a read token and a public key, and keeps them in localStorage. The result is the example dashboard as it is in the repository.
9 files, 3 new
5 unmodified lines67891011121011121314151619 unmodified lines36373839404142414243444544464748495017 unmodified lines6869707172737475737476777879808182838485868485878889909118 unmodified lines5 unmodified linesimport { BreakdownTable } from "./components/breakdown-table";import { Controls } from "./components/controls";import { CountryTable } from "./components/country-table";import { Realtime } from "./components/realtime";import { StatsTiles } from "./components/stats-tiles";import { TimeseriesChart } from "./components/timeseries-chart";import { settings } from "./settings";import { SettingsBar } from "./components/settings-bar";import { Overview } from "./components/overview";import { useSettings } from "./settings";import { fromHash, toHash, withFilter, withoutFilter } from "./state";import type { ViewState } from "./state";
const breakdowns: { dimension: keyof Filters; title: string }[] = [19 unmodified lines return [state, setState] as const;}
export function App() { const [settings, setSettings] = useSettings(); const [state, setState] = useViewState(); const connection = `${settings.endpoint}|${settings.project}|${settings.token}`; const project = useMemo(() => createProject(settings), []); const analytics = useMemo(() => createTracking(settings), []); const project = useMemo(() => createProject(settings), [connection]); const analytics = useMemo(() => createTracking(settings), [connection, settings.publicKey]); const scope = useMemo(() => scoped(project, state), [project, state]); const scopeKey = toHash(state); const scopeKey = `${connection}|${toHash(state)}`;
useEffect(() => () => void analytics.shutdown(), [analytics]);
function onPeriod(period: Period) {17 unmodified lines }
return ( <div className="shell"> <SettingsBar settings={settings} onChange={setSettings} /> <main className="main"> {settings.project === "" ? ( <p className="note warn"> Set <code>BUN_PUBLIC_DASHBOARD_PROJECT</code> in <code>.env.local</code> to your project id. Fill in the project id above. A public project needs no token; a private one needs an{" "} <code>at_live_</code> read token. </p> ) : ( <> <Controls state={state} onPeriod={onPeriod} onTraffic={onTraffic} onRemoveFilter={onRemoveFilter} /> <StatsTiles scope={scope} scopeKey={scopeKey} /> <TimeseriesChart scope={scope} scopeKey={scopeKey} /> <Overview scope={scope} scopeKey={scopeKey} /> <div className="grid"> {breakdowns.map((item) => ( <BreakdownTable key={item.dimension}18 unmodified linesA new connection builds a new client and scope, and every panel reads again.
17 unmodified lines181920212223242526272829303132333435363729303132333435363738394041424344454638394041424344454647484950515253545556575838 unmodified lines17 unmodified lines "12mo": "Last 12 months", all: "All time",};
const periodShort: { [Key in Period]: string } = { "24h": "24h", "7d": "7d", "30d": "30d", "90d": "90d", "12mo": "12mo", all: "All",};
export function Controls({ state, onPeriod, onTraffic, onRemoveFilter }: Props) { const filters = Object.entries(state.filters).filter( (entry): entry is [keyof Filters, string] => entry[1] !== undefined, ); return ( <div className="controls"> <div className="control-row"> <label className="select" htmlFor="period"> <span>Period</span> <select id="period" value={state.period} data-spoar-click="period" onChange={(event) => { const next = periods.find((period) => period === event.target.value); if (next) onPeriod(next); }} > {periods.map((period) => ( <option key={period} value={period}> {periodLabels[period]} </option> ))} </select> </label> <div className="segmented" role="group" aria-label="Period"> {periods.map((period) => ( <button key={period} type="button" className={state.period === period ? "active" : ""} aria-pressed={state.period === period} aria-label={periodLabels[period]} title={periodLabels[period]} data-spoar-click="period" data-spoar-prop-period={period} onClick={() => onPeriod(period)} > {periodShort[period]} </button> ))} </div> <div className="segmented" role="group" aria-label="Traffic"> <button type="button" className={state.traffic === "human" ? "active" : ""}38 unmodified lines123456789101112131415161718import type { ProjectScope } from "@spoar/client";import { useState } from "react";
import type { MetricKey } from "../metrics";import { StatsTiles } from "./stats-tiles";import { TimeseriesChart } from "./timeseries-chart";
type Props = { scope: ProjectScope; scopeKey: string };
export function Overview({ scope, scopeKey }: Props) { const [metric, setMetric] = useState<MetricKey>("visitors"); return ( <section className="card overview"> <StatsTiles scope={scope} scopeKey={scopeKey} selected={metric} onSelect={setMetric} /> <TimeseriesChart scope={scope} scopeKey={scopeKey} metric={metric} /> </section> );}10 unmodified lines1112131415151617181940 unmodified lines10 unmodified lines skeleton: ReactNode; children: (value: Value) => ReactNode;};
function Failure({ error, onRetry }: { error: ClientError; onRetry: () => void }) {export function Failure({ error, onRetry }: { error: ClientError; onRetry: () => void }) { return ( <div className="failure" role="alert"> <code>{error.code}</code> <p>{error.message}</p>40 unmodified lines123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111import { useState } from "react";
import type { Settings } from "../settings";
type Props = { settings: Settings; onChange: (settings: Settings) => void;};
const fields: { key: keyof Settings; label: string; placeholder: string; hint: string; secret: boolean;}[] = [ { key: "endpoint", label: "API", placeholder: "https://api.analytics.remcostoeten.nl", hint: "Where the Spoar API runs.", secret: false, }, { key: "project", label: "Project", placeholder: "remcostoeten.nl", hint: "The project id to read.", secret: false, }, { key: "token", label: "Read token", placeholder: "at_live_...", hint: "Only for private projects.", secret: true, }, { key: "publicKey", label: "Public key", placeholder: "pk_live_...", hint: "Lets this page track itself.", secret: true, },];
function host(endpoint: string) { try { return new URL(endpoint).host; } catch { return endpoint; }}
export function SettingsBar({ settings, onChange }: Props) { const [open, setOpen] = useState(settings.project === ""); return ( <header className="topbar"> <div className="topbar-row"> <div className="brand"> <strong>Example dashboard</strong> <span>@spoar/client</span> </div> <button type="button" className="connection" aria-expanded={open} aria-controls="connection-panel" onClick={() => setOpen((value) => !value)} onKeyDown={(event) => { if (event.key === "Escape") setOpen(false); }} > <span className="connection-project">{settings.project || "No project"}</span> <span className="connection-host">{host(settings.endpoint)}</span> <span className={`chevron${open ? " open" : ""}`} aria-hidden="true"> ▾ </span> </button> </div> {open ? ( <form id="connection-panel" className="settings" onSubmit={(event) => event.preventDefault()} onKeyDown={(event) => { if (event.key === "Escape") setOpen(false); }} > {fields.map((field) => ( <label key={field.key} className="field" htmlFor={`setting-${field.key}`}> <span className="field-label">{field.label}</span> <input id={`setting-${field.key}`} type={field.secret ? "password" : "text"} autoComplete="off" spellCheck={false} placeholder={field.placeholder} value={settings[field.key]} onChange={(event) => onChange({ ...settings, [field.key]: event.target.value.trim() }) } /> <span className="field-hint">{field.hint}</span> </label> ))} </form> ) : null} </header> );}Tokens are hidden on screen, but they are still in this browser's storage. Use a read-only token and only on your own machine.
11233456578789101112139101112131415161718192021222316171819202122232425302627282930313334353637383940414243444546474849505152535455565758596061626364653233343536373839404142434445464748495051525354555657585960import type { ProjectScope, StatsResponse } from "@spoar/client";import type { ProjectScope } from "@spoar/client";
import { formatChange, formatCount, formatDuration, formatPercent } from "../format";import { formatChange } from "../format";import { metrics } from "../metrics";import type { Metric, MetricKey } from "../metrics";import { useRead } from "../use-read";import { ReadFrame } from "./read-frame";import { Failure } from "./read-frame";
type Props = { scope: ProjectScope; scopeKey: string };
type Tile = { label: string; metric: keyof StatsResponse["data"]; format: (value: number) => string; invert?: boolean;type Props = { scope: ProjectScope; scopeKey: string; selected: MetricKey; onSelect: (metric: MetricKey) => void;};
const tiles: Tile[] = [ { label: "Visitors", metric: "visitors", format: formatCount }, { label: "Sessions", metric: "sessions", format: formatCount }, { label: "Pageviews", metric: "pageviews", format: formatCount }, { label: "Bounce rate", metric: "bounceRate", format: formatPercent, invert: true }, { label: "Session duration", metric: "sessionDurationMs", format: formatDuration },];
function direction(change: number | null, invert: boolean | undefined) { if (change === null || change === 0) return "flat"; const up = change > 0; return up !== Boolean(invert) ? "good" : "bad";}
function tileLabel(metric: Metric) { return `Chart ${metric.label.toLowerCase()}`;}
export function StatsTiles({ scope, scopeKey }: Props) {export function StatsTiles({ scope, scopeKey, selected, onSelect }: Props) { const stats = useRead(() => scope.stats(), [scopeKey]); if (stats.status === "error" && stats.value === null) { return <Failure error={stats.error} onRetry={stats.retry} />; } return ( <ReadFrame title="Overview" read={stats} isEmpty={(value) => value.data.visitors.value === 0 && value.data.pageviews.value === 0} empty="No traffic in this range." skeleton={ <dl className="tiles"> {tiles.map((tile) => ( <div key={tile.metric} className="tile"> <dt>{tile.label}</dt> <dd className="skeleton">0</dd> </div> ))} </dl> } > {(value) => ( <dl className="tiles"> {tiles.map((tile) => { const compared = value.data[tile.metric]; return ( <div key={tile.metric} className="tile"> <dt>{tile.label}</dt> <dd>{tile.format(compared.value)}</dd> <span className={`change ${direction(compared.change, tile.invert)}`}> {formatChange(compared.change)} </span> </div> ); })} </dl> )} </ReadFrame> <div className="tiles" role="group" aria-label="Metrics"> {metrics.map((metric) => { const compared = stats.value?.data[metric.stat]; return ( <button key={metric.key} type="button" className={`tile${selected === metric.key ? " active" : ""}`} aria-pressed={selected === metric.key} aria-label={tileLabel(metric)} data-spoar-click="metric" data-spoar-prop-metric={metric.key} onClick={() => onSelect(metric.key)} > <span className="tile-label">{metric.label}</span> <span className={`tile-value${compared ? "" : " skeleton"}`}> {compared ? metric.format(compared.value) : "0"} </span> <span className={`change ${compared ? direction(compared.change, metric.invert) : "skeleton"}`} > {compared ? formatChange(compared.change) : "+0%"} </span> </button> ); })} </div> );}123435678591071112910111314151316171819202122232425262728293031323316343536181920373839402526274142434445463334354748495051525354383940414243444546474849505152555657585960616263646566545567686970717273747576777879808182838485868788899057585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186import type { ProjectScope, TimeseriesPoint } from "@spoar/client";import { useEffect, useRef, useState } from "react";import type { PointerEvent } from "react";
import { formatBucket, formatCount } from "../format";import { formatBucket } from "../format";import { metrics } from "../metrics";import type { MetricKey } from "../metrics";import { useRead } from "../use-read";import { ReadFrame } from "./read-frame";import { Failure } from "./read-frame";
type Props = { scope: ProjectScope; scopeKey: string };type Props = { scope: ProjectScope; scopeKey: string; metric: MetricKey };
const width = 800;const height = 220;const padding = { top: 12, right: 12, bottom: 28, left: 40 };const height = 260;const padding = { top: 16, right: 8, bottom: 28, left: 44 };
function path(function useWidth() { const ref = useRef<HTMLDivElement>(null); const [width, setWidth] = useState(0); useEffect(() => { const node = ref.current; if (!node) return; const observer = new ResizeObserver((entries) => { setWidth(Math.round(entries[0]?.contentRect.width ?? 0)); }); observer.observe(node); return () => observer.disconnect(); }, []); return [ref, width] as const;}
function line( points: TimeseriesPoint[], pick: (point: TimeseriesPoint) => number | undefined, max: number, x: (index: number) => number, y: (value: number) => number,) { const innerWidth = width - padding.left - padding.right; const innerHeight = height - padding.top - padding.bottom; const step = points.length > 1 ? innerWidth / (points.length - 1) : 0; return points .map((point, index) => { const value = pick(point); if (value === undefined) return null; const x = padding.left + index * step; const y = padding.top + innerHeight - (max === 0 ? 0 : (value / max) * innerHeight); return `${index === 0 ? "M" : "L"}${x.toFixed(1)},${y.toFixed(1)}`; return `${index === 0 ? "M" : "L"}${x(index).toFixed(1)},${y(value).toFixed(1)}`; }) .filter((segment): segment is string => segment !== null) .join(" ");}
function anchorFor(index: number, length: number): "start" | "middle" | "end" { if (index === 0) return "start"; return index === length - 1 ? "end" : "middle";function tickIndexes(length: number, width: number) { const target = Math.max(2, Math.floor(width / 110)); const every = Math.max(1, Math.ceil(length / target)); return Array.from({ length }, (_, index) => index).filter( (index) => index % every === 0 && length - 1 - index >= every / 2, );}
function ticks(points: TimeseriesPoint[], interval: string) { const every = Math.max(1, Math.ceil(points.length / 6)); return points .map((point, index) => ({ point, index })) .filter(({ index }) => index % every === 0 || index === points.length - 1) .filter( ({ index }, position, all) => position === 0 || index - (all[position - 1]?.index ?? 0) > every / 2, ) .map(({ point, index }) => ({ index, label: formatBucket(point.bucket, interval), anchor: anchorFor(index, points.length), }));}export function TimeseriesChart({ scope, scopeKey, metric }: Props) { const series = useRead( () => scope.timeseries(metric, { compare: "previous" }), [scopeKey, metric], ); const [ref, width] = useWidth(); const [hover, setHover] = useState<number | null>(null); const config = metrics.find((item) => item.key === metric) ?? metrics[0]; const data = series.value?.data ?? []; const interval = series.value?.interval ?? "day"; const failed = series.status === "error" && series.value === null;
export function TimeseriesChart({ scope, scopeKey }: Props) { const series = useRead(() => scope.timeseries("visitors", { compare: "previous" }), [scopeKey]); const innerWidth = Math.max(0, width - padding.left - padding.right); const innerHeight = height - padding.top - padding.bottom; const max = Math.max(1e-9, ...data.flatMap((point) => [point.value, point.previous ?? 0])); const step = data.length > 1 ? innerWidth / (data.length - 1) : 0; function x(index: number) { return padding.left + index * step; } function y(value: number) { return padding.top + innerHeight - (value / max) * innerHeight; } const baseline = padding.top + innerHeight; const current = line(data, (point) => point.value, x, y); const area = current === "" ? "" : `${current} L${x(data.length - 1)},${baseline} L${x(0)},${baseline} Z`; const point = hover === null ? undefined : data[hover];
function onMove(event: PointerEvent<HTMLDivElement>) { if (data.length === 0 || step === 0) return; const bounds = event.currentTarget.getBoundingClientRect(); const index = Math.round((event.clientX - bounds.left - padding.left) / step); setHover(Math.min(data.length - 1, Math.max(0, index))); }
return ( <ReadFrame title="Visitors over time" read={series} isEmpty={(value) => value.data.every((point) => point.value === 0 && !point.previous)} empty="No visitors in this range." skeleton={<div className="chart skeleton" style={{ height }} />} > {(value) => { const max = Math.max( 1, ...value.data.flatMap((point) => [point.value, point.previous ?? 0]), ); const innerWidth = width - padding.left - padding.right; const step = value.data.length > 1 ? innerWidth / (value.data.length - 1) : 0; return ( <figure className="chart"> <svg viewBox={`0 0 ${width} ${height}`} role="img" aria-label="Visitors per bucket, with the previous range dashed" > {[0, 0.5, 1].map((fraction) => { const y = padding.top + (height - padding.top - padding.bottom) * (1 - fraction); return ( <g key={fraction}> <line x1={padding.left} x2={width - padding.right} y1={y} y2={y} className="grid" /> <text x={padding.left - 8} y={y + 4} textAnchor="end" className="axis"> {formatCount(Math.round(max * fraction))} </text> </g> ); })} <path d={path(value.data, (point) => point.previous, max)} className="line previous" /> <path d={path(value.data, (point) => point.value, max)} className="line current" /> {ticks(value.data, value.interval).map((tick) => ( <text key={tick.index} x={padding.left + tick.index * step} y={height - 8} textAnchor={tick.anchor} className="axis" > {tick.label} </text> ))} </svg> <figcaption> <span className="legend current">This range</span> <span className="legend previous">Previous range</span> </figcaption> </figure> ); }} </ReadFrame> <div className="chart-wrap"> {failed ? <Failure error={series.error} onRetry={series.retry} /> : null} <div ref={ref} className={`chart${series.status === "loading" ? " is-loading" : ""}`} style={{ height }} onPointerMove={onMove} onPointerLeave={() => setHover(null)} > {width > 0 && data.length > 0 ? ( <svg width={width} height={height} role="img" aria-label={`${config.label} per ${interval}, with the previous range dashed`} > <defs> <linearGradient id="area-fill" x1="0" x2="0" y1="0" y2="1"> <stop offset="0" className="area-top" /> <stop offset="1" className="area-bottom" /> </linearGradient> </defs> {[0, 0.5, 1].map((fraction) => { const gridY = y(max * fraction); return ( <g key={fraction}> <line x1={padding.left} x2={width - padding.right} y1={gridY} y2={gridY} className="grid-line" /> <text x={padding.left - 8} y={gridY + 4} textAnchor="end" className="axis"> {config.format(max * fraction)} </text> </g> ); })} <path d={line(data, (item) => item.previous, x, y)} className="line previous" /> <path d={area} fill="url(#area-fill)" /> <path d={current} className="line current" /> {tickIndexes(data.length, width).map((index) => ( <text key={index} x={x(index)} y={height - 8} textAnchor={index === 0 ? "start" : "middle"} className="axis" > {formatBucket(data[index]?.bucket ?? "", interval)} </text> ))} {point && hover !== null ? ( <g> <line x1={x(hover)} x2={x(hover)} y1={padding.top} y2={baseline} className="cursor" /> <circle cx={x(hover)} cy={y(point.value)} r={4} className="dot" /> </g> ) : null} </svg> ) : null} {point && hover !== null ? ( <div className="tooltip" style={{ left: Math.min(Math.max(x(hover), 80), Math.max(80, width - 80)), top: padding.top, }} > <span className="tooltip-date">{formatBucket(point.bucket, interval)}</span> <span className="tooltip-row current"> <span>This range</span> <strong>{config.format(point.value)}</strong> </span> {point.previous === undefined ? null : ( <span className="tooltip-row previous"> <span>Previous</span> <strong>{config.format(point.previous)}</strong> </span> )} </div> ) : null} </div> <div className="legend-row"> <span className="legend current">This range</span> <span className="legend previous">Previous range</span> </div> </div> );}1234567891011121314151617181920212223242526272829303132import type { StatsResponse } from "@spoar/client";
import { formatCount, formatDuration, formatPercent } from "./format";
export type MetricKey = "visitors" | "sessions" | "pageviews" | "bounce_rate" | "session_duration";
export type Metric = { key: MetricKey; label: string; stat: keyof StatsResponse["data"]; format: (value: number) => string; invert?: boolean;};
export const metrics: Metric[] = [ { key: "visitors", label: "Visitors", stat: "visitors", format: formatCount }, { key: "sessions", label: "Sessions", stat: "sessions", format: formatCount }, { key: "pageviews", label: "Pageviews", stat: "pageviews", format: formatCount }, { key: "bounce_rate", label: "Bounce rate", stat: "bounceRate", format: formatPercent, invert: true, }, { key: "session_duration", label: "Session duration", stat: "sessionDurationMs", format: formatDuration, },];1234567898101112131415161718192021222324252627282930313233343536373839404142432 unmodified lines464748495051525354555657585960616263646566676869import { useEffect, useState } from "react";
export type Settings = { endpoint: string; project: string; token: string; publicKey: string;};
export const settings: Settings = {const storageKey = "spoar-example-dashboard-settings";
const defaults: Settings = { endpoint: process.env.BUN_PUBLIC_DASHBOARD_API || "https://api.analytics.remcostoeten.nl", project: process.env.BUN_PUBLIC_DASHBOARD_PROJECT ?? "", token: process.env.BUN_PUBLIC_DASHBOARD_TOKEN ?? "", publicKey: process.env.BUN_PUBLIC_DASHBOARD_PUBLIC_KEY ?? "",};
function field(saved: { [key: string]: unknown }, key: keyof Settings) { const value = saved[key]; return typeof value === "string" && value !== "" ? value : defaults[key];}
function stored(): Settings { try { const raw = localStorage.getItem(storageKey); if (!raw) return defaults; const saved: { [key: string]: unknown } = JSON.parse(raw); return { endpoint: field(saved, "endpoint"), project: field(saved, "project"), token: field(saved, "token"), publicKey: field(saved, "publicKey"), }; } catch { return defaults; }}
/** * @name trimEndpoint * @description Strips trailing slashes so paths can be appended without doubling them. *2 unmodified lines */export function trimEndpoint(endpoint: string) { return endpoint.replace(/\/+$/, "");}
/** * @name useSettings * @description The connection settings, kept in this browser's localStorage and seeded from the * `BUN_PUBLIC_DASHBOARD_*` variables at build time. * * @example * const [settings, setSettings] = useSettings(); */export function useSettings() { const [settings, setSettings] = useState(stored); useEffect(() => { try { localStorage.setItem(storageKey, JSON.stringify(settings)); } catch (error) { console.warn("Settings were not saved", error); } }, [settings]); return [settings, setSettings] as const;}The variables from .env.local are now only the defaults. Whatever someone types in the bar wins and is saved in this browser.
The finished app is in the repository, with tests for the URL state and the read hook:
git clone https://github.com/remcostoeten/analytics
cd analytics && bun install
bun run --cwd examples/dashboard devIt opens on http://localhost:3301. Read client lists every read this dashboard did not use, such as paths, retention and lifecycle, and Build a minimal dashboard shows the same reads from a Next.js server component.