@protoyard/analytics-ui
v1.9.4
Published
Svelte 5 analytics kit for Protoyard prototypes: KPI tiles, date ranges, filters and segments, cohort and funnel views and a dashboard grid, one lazy subpath per view.
Maintainers
Readme
@protoyard/analytics-ui
Svelte 5 analytics kit for Protoyard prototypes
(ADR-021), built on
@protoyard/analytics, Texuli 0.5.0 (texuli/stat,
texuli/date, texuli/select, texuli/toggle,
@texuli/data/filter-builder, @texuli/charts/compact and
@texuli/charts/matrix),
@protoyard/charts-ui and @protoyard/ui. Each
view has its own subpath, so a prototype pays only for the views its screens
import. Nothing here is re-exported from the @protoyard/ui barrel.
The platform guide is docs/ANALYTICS.md. Working examples:
templates/analytics: every view on lazy routes, as a starter;prototypes/pebblestat-analytics-demo: the flagship.
Install in a workspace prototype
Add "@protoyard/analytics-ui": "workspace:*" to the prototype dependencies
and import the styles after Tailwind and the theme, UI and charts styles:
@import 'tailwindcss';
@import '@protoyard/themes/base.css';
@import '@protoyard/ui/styles.css';
@import '@protoyard/charts-ui/styles.css';
@import '@protoyard/analytics-ui/styles.css';Entry points
| Import | View |
| --- | --- |
| @protoyard/analytics-ui | KpiTile, KpiRow, LiveCounter, formatKpi, kpiDelta; ANALYTICS_VIEWS and the data contract types (imports no view) |
| @protoyard/analytics-ui/date-range | DateRangePicker, DateRangePanel, MonthGrid; toDateRangeQuery / fromDateRangeQuery, allowedGranularities, fitGranularity, describeDateRange |
| @protoyard/analytics-ui/filters | FilterBuilder, FilterGroupEditor, SegmentPicker, BreakdownSelect; describeFilter, validateFilter, saveErrorOf |
| @protoyard/analytics-ui/cohort | CohortTable; formatRate, cohortLabel, periodLabel, readSequentialRamp |
| @protoyard/analytics-ui/funnel | FunnelAnalysis; funnelSeries, formatConversion, formatDuration |
| @protoyard/analytics-ui/grid | DashboardGrid, WidgetCard (and the layout helpers from @protoyard/analytics) |
| @protoyard/analytics-ui/drill | DrillDown; drillStep, pushDrill, truncateDrill, drillFilter, toDrillQuery / fromDrillQuery |
Every mutation (save a segment, move a widget) is a callback that returns the
prototype's service promise, so a Button shows pending feedback; the kit
never writes to the database itself.
KPI tiles and live counters (root entry)
KPI tiles are small enough for a first screen, so they live on the root entry; every view stays on its subpath.
<KpiRow label="Key metrics">
<KpiTile label="Signups" value={now.signups} previous={before.signups} trend={series} trendPeriod="30 days" href="#/insights/signups" />
<KpiTile label="Churn" value={0.031} previous={0.04} unit="percent" positive="down" />
<KpiTile label="MRR" value={1_245_000} previous={1_180_000} unit="cents" />
</KpiRow>
<LiveCounter label="Active users" query={activeUsers} />KpiTileadaptstexuli/statKpiand@texuli/charts/compactSparkline, formatting the value by unit (number,compact,percentratios,cents= integer cents).- The delta comes from
previous: a signed percentage, or the signed absolute change when the previous value is 0. - Tone and wording come from the same helpers as
@protoyard/uiStatCard(resolveTrend,trendTone,trendWord): success when the change goes thepositiveway, destructive otherwise, with "Increased / Decreased / No change:" read first. - An optional Sparkline speaks its trend sentence.
hrefmakes the whole tile a drill-down link named by the label and described by the value. loadingshows a skeleton witharia-busy;emptyshows "—" and a message.
- The delta comes from
KpiRowadaptstexuli/statKpiRow;minmaps tominItemWidth(default12rem) so the library owns responsive wrapping.LiveCounterfollows a liveQuery result (query.current) and never writes data; new values arrive from timeline events.- It renders through Texuli
Kpi, counts up visually overduration, or shows the value at once under reduced motion (data-tx-motion="reduce"). - Its polite live region speaks at most once per
announceEvery(5 s), always with the latest value.
- It renders through Texuli
KPI number formatting and trend calculation re-export texuli/stat directly.
Lucide glyphs are rendered only through texuli/icons/lucide's LucideIcon
bridge; raw Lucide components are never placed in markup.
Filters and segments (./filters)
Filters are data: FilterBuilder edits and emits a FilterGroup (the
FilterSchema of @protoyard/analytics). The prototype stores it and runs
compileFilter(filter) over its rows. Properties come from a catalog that
the prototype declares:
const properties: FilterProperty[] = [
{ path: 'properties.plan', label: 'Plan', type: 'string', options: [{ value: 'pro', label: 'Pro' }] },
{ path: 'properties.seats', label: 'Seats', type: 'number' },
];FilterBuilder: Texuli's@texuli/data/filter-builderwith the property catalog: match all/any, rows of field / operator / value as native controls, and nested groups up to three levels deep. Operators follow the property type, inOPERATORS_BY_TYPEorder; the ones Texuli does not ship (greater/less than, at least/most, does not contain, starts with, is none of, on or after/before) are catalog operators (BUILDER_OPERATORS). Values include number, date, Yes/No, a choice or a multi-select for known options (shown by label), comma-separated text for lists, two inputs for "between".- "Apply filters" validates against the catalog: unknown properties,
operators that do not fit the type and missing values show on the
condition's control: the builder shows the message under it and
sets
aria-invalidandaria-describedby(Texuli's hostissues, G101). Errors on a whole group are listed under the builder. Only valid data reachesonchange. Option-backed properties pass{ value, label }options, so menus show labels and the model stores values. - A one-line summary reads "Plan is Pro and Seats at least 5".
- "Apply filters" validates against the catalog: unknown properties,
operators that do not fit the type and missing values show on the
condition's control: the builder shows the message under it and
sets
SegmentPicker: saved segments asaria-pressedchips ("Everyone" clears) and a "Save current filter as a segment" form.onsave({ name, filter })must return the service promise, for examplerunService(() => saveSegment(runtime, input)). TheButtonshows pending feedback until it settles.- A resolved
{ ok: false, error }or a rejection shows inline: field issues next to the name, a permission error as "Your role can't save segments".runServicestill shows its toast.
BreakdownSelect: "Break down by" over string and boolean properties, or None.
Why not @protoyard/ui FilterBar? FilterBar filters list rows by flat
per-field values (FilterValues) for CRUD screens. Analytics filters are
nested AND/OR trees that are saved as segments and validated against a
property catalog, so they need this data-first builder. FilterGroupEditor
renders Texuli's @texuli/data/filter-builder with that catalog (fields,
per-type operator lists and catalog operators, G49) and converts its model
to and from @protoyard/analytics FilterGroup (toBuilderFilter,
fromBuilderFilter); validation and the compiled predicate stay
@protoyard/analytics. Use FilterBar for entity lists and FilterBuilder for
analytics queries.
Pre-migration size estimates (esbuild minify + gzip -9; svelte, @protoyard/ui, @protoyard/analytics and zod external), each imported from the subpath: FilterBuilder 4.6 KB (5.5 KB with the analytics filter code it validates with), SegmentPicker 2.0 KB, BreakdownSelect 0.7 KB. Like charts-ui, analytics-ui marks only CSS as side-effectful, so a screen pays only for the components it imports.
Date range (./date-range)
DateRangePicker edits a DateRangeValue ({ range, comparison,
granularity }, where range is a preset or custom days from
@protoyard/analytics). It always works from a caller-supplied now, so it
follows the simulated clock:
<script lang="ts">
const clock = useClock();
let value = $state(fromDateRangeQuery(location.hash.split('?')[1] ?? ''));
</script>
<DateRangePicker {value} now={clock.now} onchange={(next) => { value = next; navigate(`#/insights?${toDateRangeQuery(next)}`); }} />- Trigger: an outline
Buttonreading "Last 30 days vs previous period", opening aPopover. - Presets: today through last month, as
aria-pressedbuttons. Picking one emits at once and closes the popover. - Custom range: the month view is rendered by
texuli/dateCalendar. The adapter supplies the simulated maximum and today, week start, selected range highlighting, and the 3,660-day limit. Presets, comparison and Apply behavior remain Protoyard-owned. - Compare to none, previous period or previous year, and Group by
hour/day/week/month: segmented
aria-pressedbuttons. Granularities that do not fit the span (hourly over a year, monthly over a week) are disabled, and a range change refits the granularity. - Query:
toDateRangeQuerywritesrange=last-30-days&compare=previous-period&by=day(custom:range=2026-03-01..2026-03-07);fromDateRangeQueryreads it back, ignoring invalid parts. It fitsby=to the range (fitGranularity; passnowto fit presets too), and custom ranges span at mostMAX_CUSTOM_RANGE_DAYS(3,660 days), so a shared link cannot request more thanMAX_BUCKETSbuckets.
The date adapter consumes Texuli's keyboard-accessible range Calendar and keeps only Protoyard's analytics-specific preset, comparison and granularity controls around it.
Dashboard grid (./grid)
DashboardGrid lays out widgets from a layout stored as data
(DashboardLayoutSchema in @protoyard/analytics). It is page content
inside whatever app shell the prototype uses, not a shell itself.
<DashboardGrid {layout} label="Growth" editing={editing} onchange={(next) => runService(() => saveLayout(next))}>
{#snippet widget(item)}
<WidgetCard title={item.title ?? item.widget} menu={menuFor(item)}>
{#snippet children({ expanded })}<RevenueChart {expanded} />{/snippet}
</WidgetCard>
{/snippet}
</DashboardGrid>It renders Texuli's dashboard (@texuli/data/dashboard); this package keeps
the saved layout format and its persistence.
- Layout: 12 columns,
rowHeightper row unit (default 80 px),gap(pixels, mapped to Texuli's gap steps). BelowcollapseBelowcontainer width (default 640 px) the grid stacks into one column in reading order (row, then column). The DOM is always in reading order, and each widget's title is its heading. - Editing: Texuli's handles on every widget. A pointer drags the move handle or the resize handle, snapping to cells. On the keyboard, Space or Enter picks a handle up, arrow keys move or resize one step, Space or Enter drops, Escape cancels. A click (or Enter) on a handle shows an arrange toolbar (Move left/right/up/down or Narrower/Wider/Shorter/Taller, Done, Cancel), so no drag is needed (WCAG 2.5.7). Neighbours make room and everything compacts upward; focus stays on the handle and a polite live region announces each step. The keyboard step can move a widget down past a wider widget below it (G122, Texuli 0.10.0).
- Saving: an edit on the 12-column grid calls
onchange(layout)with the layout inDashboardLayoutSchemaform (widget keys and titles kept). Return the service promise: the grid isaria-busyuntil it settles and restores the previous layout if it rejects (announced politely). An arrangement on the stacked phone grid lasts for the session only. When the savedlayoutprop changes (liveQuery, scenario load), the grid follows it. - WidgetCard: a titled
sectionwith an optional actions menu (DropdownMenu), loading/empty/error states (retry with pending feedback), and an Expand button that opens the same content in a large dialog (childrenreceives{ expanded }). InsideDashboardGridit draws no card chrome or heading of its own (the dashboard widget does) and is named by its title.
Measured on pebblestat-analytics-demo (protoyard budget, gzip): moving the
grid onto Texuli's dashboard costs about 0.13 KB of initial JS and 0.66 KB of
CSS. Widgets load their chart chunks themselves.
Explore: drill-down, cohorts, funnels (./drill, ./cohort, ./funnel)
<DrillDown title="Tickets" {rows} {columns} getRowId={(r) => r.id} {path} onchange={(p) => go(`#/tickets?${toDrillQuery(p)}`)}>
{#snippet chart({ drill })}
<BarChart title="Tickets by priority" {series} onselect={(s) => drill(drillStep('priority', s.datum.priority))} />
{/snippet}
</DrillDown>
<CohortTable title="Weekly retention" result={computeRetention(events, { interval: 'week', periods: 8, now })} />
<FunnelAnalysis title="Activation" result={computeFunnel(events, steps, { breakdown: 'properties.plan' })} breakdownLabel="Plan" />DrillDown: the chart snippet callsdrill(step)from itsonselect; the rows matching the path (ANDed with an optionalbasefilter, viacompileFilter) fill aDataTable, and a breadcrumbnavwalks back (aria-currenton the last step, a polite row count).- The path is data (
{ steps: [{ label, filter }] }).toDrillQuery/fromDrillQueryround-trip it through the hash query, so a reload or a shared link restores it. The parser validates every filter withFilterConditionSchemaand drops anything else (the query is untrusted). - A step on a property already in the path replaces it and drops the steps after it.
- The path is data (
CohortTable: a real<table>with a caption,scope="col"period headers,scope="row"cohort headers and an average row. Its fills and text colors come from@texuli/data/cohortresolveHeatScaleandheatLevel(G51); the semantic row/period layout, the %/count toggle and the incomplete marks stay Protoyard-owned.- Cells use the theme's sequential ramp (
--tx-chart-sequential-*, or apaletteprop). Texuli checks each hex step and pairs it with the text color that reaches 4.5:1 on it, so every number sits on its fill. Without a hex ramp (or one Texuli refuses) cells keep the token fill and the value sits on a surface chip, so contrast never depends on a guess. - The % / Count toggle uses
aria-pressedbuttons and is bindable (display). Incomplete periods are outlined and marked with an asterisk and "(incomplete)" for screen readers. Period 0 is unfilled because it is always 100%.
- Cells use the theme's sequential ramp (
FunnelAnalysis: aFunnelChartplus a step table (users, overall conversion, conversion from the previous step, drop-off, median time to convert).- With a breakdown,
aria-pressedbuttons (each with its overall conversion) switch the chart and the table to that series.selectedis bindable, andonstepselectpasses the clicked step on (for example, to aDrillDown).
- With a breakdown,
Pre-migration size estimates (esbuild minify + gzip -9; svelte, @protoyard/ui, charts and analytics
external): DrillDown 1.3 KB (2.7 KB with its filter code, zod external),
CohortTable 2.7 KB, FunnelAnalysis 2.0 KB. All are under the 6 KB budget
beyond the charts they use.
Tests
pnpm vitest run packages/analytics-ui
pnpm --filter @protoyard/analytics-ui typecheckPackage output
The repository keeps source exports for workspace development. pnpm build:packages --filter svelte creates the compiled ESM, declarations and Svelte components under dist/ that the packed manifest exposes.
