Step 5 of 7. Show the top pages, referrers, browsers, devices and countries, filter on a click and track each change as a custom event.
This step turns the page into a dashboard you can explore. The view becomes state: a period, a traffic filter and any number of dimension filters. Clicking a row in a top list adds a filter, and every panel reads again with it.
7 files, 4 new
123456789101112131414151617181920212223242526272829303132333435import { createClient } from "@spoar/client";import type { ProjectScope } from "@spoar/client";
import type { Settings } from "./settings";import { trimEndpoint } from "./settings";import type { ViewState } from "./state";
/** * @name createProject * @description One `@spoar/client` scope over the configured project. A public project needs no * token, so `token` is left out when empty. * * @example * const project = createProject(settings); * const stats = await project.period("7d").stats(); * const stats = await scoped(project, state).stats(); */export function createProject(settings: Settings): ProjectScope { const api = createClient({ endpoint: trimEndpoint(settings.endpoint), ...(settings.token ? { token: settings.token } : {}), }); return api.project(settings.project);}
/** * @name scoped * @description Applies the page's period, traffic and filters to a project scope. Every view * reads from the result, so one state change refreshes them all together. * * @example * scoped(project, { period: "7d", traffic: "human", filters: { country: "NL" } }).stats(); */export function scoped(project: ProjectScope, state: ViewState) { return project.period(state.period).traffic(state.traffic).where(state.filters); }where() takes the filters as an object with one value per dimension. Each panel reads from this scope.
1123445678910111213141516171819202122232425121326272829303132333435363738394041424344454647484950515253542 unmodified lines57585960616263646566676869707172737475767778798081828384852 unmodified linesimport type { Filters, Period, TrafficFilter } from "@spoar/client";import { useEffect, useMemo } from "react";import { useEffect, useMemo, useState } from "react";
import { createTracking } from "./analytics";import { createProject } from "./api";import { createProject, scoped } from "./api";import { BreakdownTable } from "./components/breakdown-table";import { Controls } from "./components/controls";import { CountryTable } from "./components/country-table";import { StatsTiles } from "./components/stats-tiles";import { TimeseriesChart } from "./components/timeseries-chart";import { settings } from "./settings";import { defaultState, withFilter, withoutFilter } from "./state";import type { ViewState } from "./state";
const breakdowns: { dimension: keyof Filters; title: string }[] = [ { dimension: "page", title: "Pages" }, { dimension: "referrer_domain", title: "Referrers" }, { dimension: "browser", title: "Browsers" }, { dimension: "device", title: "Devices" },];
export function App() { const [state, setState] = useState<ViewState>(defaultState); const project = useMemo(() => createProject(settings), []); const analytics = useMemo(() => createTracking(settings), []); const scope = useMemo(() => project.period("7d").traffic("human"), [project]); const scopeKey = "7d|human"; const scope = useMemo(() => scoped(project, state), [project, state]); const scopeKey = JSON.stringify(state);
useEffect(() => () => void analytics.shutdown(), [analytics]);
function onPeriod(period: Period) { analytics.track("period_changed", { period }); setState((current) => ({ ...current, period })); }
function onTraffic(traffic: TrafficFilter) { analytics.track("traffic_changed", { traffic }); setState((current) => ({ ...current, traffic })); }
function onPick(dimension: keyof Filters, value: string) { analytics.track("filter_added", { dimension }); setState((current) => withFilter(current, dimension, value)); }
function onRemoveFilter(dimension: keyof Filters) { analytics.track("filter_removed", { dimension }); setState((current) => withoutFilter(current, dimension)); }
return ( <div className="shell"> <main className="main"> {settings.project === "" ? (2 unmodified lines id. </p> ) : ( <> <Controls state={state} onPeriod={onPeriod} onTraffic={onTraffic} onRemoveFilter={onRemoveFilter} /> <StatsTiles scope={scope} scopeKey={scopeKey} /> <TimeseriesChart scope={scope} scopeKey={scopeKey} /> <div className="grid"> {breakdowns.map((item) => ( <BreakdownTable key={item.dimension} scope={scope} scopeKey={scopeKey} dimension={item.dimension} title={item.title} onPick={onPick} /> ))} </div> <CountryTable scope={scope} scopeKey={scopeKey} onPick={onPick} /> </> )} </main> </div>2 unmodified linesTyped by the Events map from step 2. The page tracks how it is used.
The read hook runs again when the key changes. Step 6 replaces it with the URL hash.
12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273import type { Dimension, Filters, ProjectScope, BreakdownRow } from "@spoar/client";
import { countryName, formatCount, formatPercent } from "../format";import { useRead } from "../use-read";import { ReadFrame } from "./read-frame";
type Props = { scope: ProjectScope; scopeKey: string; dimension: Dimension; title: string; onPick: (dimension: keyof Filters, value: string) => void;};
function label(dimension: Dimension, row: BreakdownRow) { if (row.value === "") return "(none)"; return dimension === "country" ? countryName(row.value) : row.value;}
function Skeleton() { return ( <ol className="breakdown"> {Array.from({ length: 5 }, (_, index) => ( <li key={index} className="skeleton-row"> <span className="skeleton">loading</span> <strong className="skeleton">0</strong> </li> ))} </ol> );}
export function BreakdownTable({ scope, scopeKey, dimension, title, onPick }: Props) { const rows = useRead( () => scope.breakdown(dimension, { metrics: ["visitors", "pageviews"], limit: 10 }), [scopeKey, dimension], ); return ( <ReadFrame title={title} read={rows} isEmpty={(value) => value.data.length === 0} empty="Nothing in this range." skeleton={<Skeleton />} > {(value) => ( <ol className="breakdown"> {value.data.map((row) => ( <li key={row.value}> <button type="button" className="breakdown-row" data-spoar-click="breakdown" data-spoar-prop-dimension={dimension} onClick={() => onPick(dimension, row.value)} title={`Filter on ${dimension} = ${row.value}`} > <span className="bar" style={{ width: formatPercent(row.share ?? 0) }} aria-hidden="true" /> <span className="label">{label(dimension, row)}</span> <span className="share">{formatPercent(row.share ?? 0)}</span> <strong>{formatCount(row.visitors ?? 0)}</strong> </button> </li> ))} </ol> )} </ReadFrame> );}The top values of one dimension, with visitors, pageviews and each row's share.
12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788import type { Filters, Period, TrafficFilter } from "@spoar/client";
import { periods } from "../state";import type { ViewState } from "../state";
type Props = { state: ViewState; onPeriod: (period: Period) => void; onTraffic: (traffic: TrafficFilter) => void; onRemoveFilter: (dimension: keyof Filters) => void;};
const periodLabels: { [Key in Period]: string } = { "24h": "Last 24 hours", "7d": "Last 7 days", "30d": "Last 30 days", "90d": "Last 90 days", "12mo": "Last 12 months", all: "All time",};
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="Traffic"> <button type="button" className={state.traffic === "human" ? "active" : ""} data-spoar-click="traffic" data-spoar-prop-traffic="human" onClick={() => onTraffic("human")} > Human </button> <button type="button" className={state.traffic === "all" ? "active" : ""} data-spoar-click="traffic" data-spoar-prop-traffic="all" onClick={() => onTraffic("all")} > All traffic </button> </div> </div> {filters.length > 0 ? ( <ul className="chips" aria-label="Filters"> {filters.map(([dimension, value]) => ( <li key={dimension}> <button type="button" className="chip" onClick={() => onRemoveFilter(dimension)} aria-label={`Remove filter ${dimension} is ${value}`} > <span>{dimension}</span> <strong>{value}</strong> <span aria-hidden="true">×</span> </button> </li> ))} </ul> ) : null} </div> );}1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556import type { Filters, ProjectScope } from "@spoar/client";
import { countryName, formatCount, formatPercent } from "../format";import { useRead } from "../use-read";import { ReadFrame } from "./read-frame";
type Props = { scope: ProjectScope; scopeKey: string; onPick: (dimension: keyof Filters, value: string) => void;};
export function CountryTable({ scope, scopeKey, onPick }: Props) { const places = useRead(() => scope.map({ level: "country", limit: 25 }), [scopeKey]); return ( <ReadFrame title="Countries" read={places} isEmpty={(value) => value.data.length === 0} empty="No located visitors in this range." skeleton={<div className="table-wrap skeleton" style={{ height: 240 }} />} > {(value) => ( <div className="table-wrap"> <table className="rows"> <thead> <tr> <th>Country</th> <th>Code</th> <th>Visitors</th> <th>Share</th> </tr> </thead> <tbody> {value.data.map((place) => ( <tr key={place.country} onClick={() => onPick("country", place.country)} className="clickable" > <td>{countryName(place.country)}</td> <td className="mono">{place.country}</td> <td>{formatCount(place.visitors)}</td> <td>{formatPercent(place.share)}</td> </tr> ))} </tbody> </table> <p className="table-foot"> {value.total} {value.total === 1 ? "country" : "countries"} in total </p> </div> )} </ReadFrame> );}map() groups by place and returns the total number of countries next to the first 25.
63 unmodified lines646566676869707172737475767778798081828363 unmodified lines return date.toLocaleTimeString("en", { hour: "2-digit", minute: "2-digit", hour12: false }); } return date.toLocaleDateString("en", { month: "short", day: "numeric" });}
/** * @name countryName * @description Turns an ISO 3166-1 alpha-2 code into the English country name, or returns the * code when the browser does not know it. * * @example * countryName("NL"); // "Netherlands" */export function countryName(code: string) { try { return new Intl.DisplayNames(["en"], { type: "region" }).of(code) ?? code; } catch { return code; }}1234567891011121314151617181920212223242526272829303132333435import type { Filters, Period, TrafficFilter } from "@spoar/client";
export type ViewState = { period: Period; traffic: TrafficFilter; filters: Filters;};
export const periods: readonly Period[] = ["24h", "7d", "30d", "90d", "12mo", "all"];
export const defaultState: ViewState = { period: "7d", traffic: "human", filters: {} };
/** * @name withFilter * @description Returns the state with one filter added or replaced. * * @example * withFilter(state, "country", "NL"); */export function withFilter(state: ViewState, dimension: keyof Filters, value: string): ViewState { return { ...state, filters: { ...state.filters, [dimension]: value } };}
/** * @name withoutFilter * @description Returns the state with one filter removed. * * @example * withoutFilter(state, "country"); */export function withoutFilter(state: ViewState, dimension: keyof Filters): ViewState { const filters = { ...state.filters }; delete filters[dimension]; return { ...state, filters };}Everything a read depends on, in one value.
The top pages of this site:
Click a page in the dashboard: a chip appears under the controls, and every panel shows only visits to that page. Click the chip to remove the filter.
Next, keep the view in the URL.