Use cases
Dashboard
A section list of reports with global filters.
The stack you choose picks the code on this page. Options marked coming soon can't be chosen yet.
Copies the Quill CLI's install command: curl -fsSL https://quill.co/install.sh | shView as MarkdownThe whole page, with the code for the chosen stack.
Metric detail dashboard
import { useEffect, useState } from 'react';
import { Chart, format, useDashboard, useDashboardReport, useReport, type QuillReport } from '@quillsql/react';
import styles from '../components/blocks/metrics-dashboard/metrics-dashboard.module.css';
import { MorphBlock, SkeletonMorph } from '../components/skeleton-morph/skeleton-morph';
import { BlockStatus } from './BlockStatus';
function MetricDetail({ reportId, metric }: { reportId?: string; metric?: QuillReport }) {
const { chart, chartLoading, chartError, groupColumnsBy = '', groupColumnsByOptions, filterUniqueValuesLoading, setReport } = useReport(reportId, { showTableNames: false });
const breakdowns = [...groupColumnsByOptions, { value: '', label: 'Total' }];
// A skeleton until the chart and its columns' values have first loaded, so the options arrive together rather than
// one by one (a refetch shows the last answer's); never again after, so picking one doesn't flash it.
const [breakdownsReady, setBreakdownsReady] = useState(false);
useEffect(() => {
if (chart && !chartLoading && !filterUniqueValuesLoading) setBreakdownsReady(true);
}, [chart, chartLoading, filterUniqueValuesLoading]);
const breakdown = breakdowns.find((b) => b.value === groupColumnsBy);
useEffect(() => {
if (metric) setReport({
aggregations: metric.pivot?.aggregations,
yAxis: { fields: metric.yAxisFields },
groupRowsBy: metric.dateField && `${metric.dateField.table}::${metric.dateField.field.replace(/"/g, '')}`,
});
}, [metric?.id]);
return (
<>
<div className={styles.chartBar}>
<h3>{metric?.name}{breakdown?.value && ` by ${breakdown.label}`}</h3>
<SkeletonMorph loading={!breakdownsReady} loadingLabel="Loading breakdowns">
<MorphBlock width={240} height={32} radius={10}>
<div className={styles.segmented}>
{breakdowns.map((b) => (
<button key={b.value} aria-pressed={b.value === groupColumnsBy} onClick={() => setReport({ groupColumnsBy: b.value, showLegend: !!b.value })}>
{b.value === groupColumnsBy && <span className={styles.segmentThumb} />}
<span className={styles.segmentLabel}>{b.label}</span>
</button>
))}
</div>
</MorphBlock>
</SkeletonMorph>
</div>
<Chart chart={chart} chartLoading={chartLoading} chartError={chartError} containerStyle={{ width: '100%', height: 224, marginTop: 12 }} />
</>
);
}
/** A metric's tab: its name, and its value, a skeleton the size of a number until the report's row arrives. */
function Kpi({ metric, selected, onSelect }: { metric: QuillReport; selected: boolean; onSelect: () => void }) {
// The report is there, not loading, before its fetch starts: pending until it has its row. The value is read from
// the same report as `loading`, so it is never shown before it has arrived.
const { report, loading } = useDashboardReport(metric.id);
const row = report?.pivotRows?.[0];
return (
<button className={styles.kpi} role="tab" aria-selected={selected} onClick={onSelect}>
{selected && <span className={styles.kpiIndicator} />}
<span className={styles.kpiLabel}>{metric.name}</span>
<SkeletonMorph as="span" loading={loading || !row} loadingLabel={`Loading ${metric.name}`}>
<MorphBlock width={96} height={26}>
<span className={styles.kpiValue}>{format({ value: row?.[metric.xAxisField], format: metric.xAxisFormat })}</span>
</MorphBlock>
</SkeletonMorph>
</button>
);
}
export function MetricsDashboardBlock() {
const { isLoading, error, sections } = useDashboard('Metrics dashboard');
const [selected, setSelected] = useState<QuillReport>();
if (isLoading) return <BlockStatus />;
if (error) return <BlockStatus error={error.message} />;
const metrics = sections.Metrics ?? [];
const charts = sections.Charts ?? [];
const metric = selected ?? metrics[0];
return (
<section className={styles.dashboard}>
<header className={styles.header}>
<div className={styles.title}>
<h2>Analytics</h2>
<p>example.com · Last 30 days</p>
</div>
</header>
<div className={styles.kpis} role="tablist">
{metrics.map((m) => (
<Kpi key={m.id} metric={m} selected={m.id === metric?.id} onSelect={() => setSelected(m)} />
))}
</div>
<div className={styles.chartSection}>
<MetricDetail reportId={sections.Detail?.[0]?.id} metric={metric} />
</div>
<div className={styles.breakdowns}>
{charts.map((chart) => (
<section key={chart.id} className={styles.breakdown}>
<div className={styles.breakdownHead}>
<h3>{chart.name}</h3>
<span>Visitors</span>
</div>
<Chart reportId={chart.id} containerStyle={{ width: '100%', height: 220 }} />
</section>
))}
</div>
</section>
);
}import { useEffect, useState, type ReactNode } from 'react';
import { QuillProvider, type QuillTheme } from '@quillsql/react';
import { AdaptiveUiBlock } from './blocks/AdaptiveUiBlock';
import { AlertBuilder } from './blocks/AlertBuilder';
import { BlockStatus } from './blocks/BlockStatus';
import { DateComparisonDashboardBlock } from './blocks/DateComparisonDashboardBlock';
import { DrillDownBlock } from './blocks/DrillDownBlock';
import { FilteredDashboardBlock } from './blocks/FilteredDashboardBlock';
import { InsightBlock } from './blocks/InsightBlock';
import { MetricsDashboardBlock } from './blocks/MetricsDashboardBlock';
import { ReportBuilder } from './blocks/ReportBuilder';
import { ReportBuilderAdvanced } from './blocks/ReportBuilderAdvanced';
import { ReportBuilderSidebar } from './blocks/ReportBuilderSidebar';
import { ReportBuilderSidebarAdvanced } from './blocks/ReportBuilderSidebarAdvanced';
import { SearchBarBlock } from './blocks/SearchBarBlock';
import { TabbedDashboardBlock } from './blocks/TabbedDashboardBlock';
/**
* Quill's charts in the app's look: its body font, muted labels and hairlines, and its accent colors for the series,
* for whichever color scheme the page is in.
*/
function quillTheme(dark: boolean): QuillTheme {
return {
fontFamily: '"Inter Variable", "Inter", sans-serif',
chartLabelFontFamily: '"Inter Variable", "Inter", sans-serif',
fontSize: 13,
backgroundColor: dark ? '#262626' : '#ffffff',
primaryTextColor: dark ? '#f2f2f2' : '#1c1c1c',
secondaryTextColor: dark ? '#9b9b9b' : '#767676',
chartLabelColor: dark ? '#9b9b9b' : '#767676',
chartTickColor: dark ? '#353535' : '#e6e6e6',
borderColor: dark ? '#353535' : '#e6e6e6',
// Quill's loading skeleton is the app's placeholder block, in its --surface-muted.
loadingStateBackgroundColor: dark ? 'oklch(26% 0 0)' : 'oklch(97.8% 0 0)',
// The app's violet first: single-series charts, such as the bar lists, take the first color.
chartColors: dark ? ['#a78bff', '#6ba3ff', '#53dca6', '#ffcb62'] : ['#7747ff', '#0562ef', '#0db879', '#f3ad20'],
barChartCornerRadius: 2,
};
}
const root = document.documentElement;
/**
* The components read dark mode from data-theme on <html>: index.html sets it from the system, the docs from their toggle. Inline
* in a docs page (docs.tsx), <html> is the docs' own, dark by its .dark.
*/
export function useDark() {
const read = () => root.dataset.theme === 'dark' || root.classList.contains('dark');
const [dark, setDark] = useState(read);
useEffect(() => {
const observer = new MutationObserver(() => setDark(read()));
observer.observe(root, { attributeFilter: ['data-theme', 'class'] });
return () => observer.disconnect();
}, []);
return dark;
}
/** The app's Quill endpoint (server/index.ts), under the path the app is served at. */
const QUERY_ENDPOINT = `${window.location.origin}${import.meta.env.BASE_URL}quill`;
/** The environment's public key, from the server, whose environment holds both of its keys. */
function usePublicKey(endpoint: string) {
const [config, setConfig] = useState<{ publicKey?: string; error?: string }>({});
useEffect(() => {
fetch(`${endpoint}/config`)
.then((res) => (res.ok ? res.json() : Promise.reject(new Error(`The Quill endpoint answered ${res.status}`))))
.then(({ publicKey }) => setConfig(publicKey ? { publicKey } : { error: 'The server has no QUILL_PUBLIC_KEY' }))
.catch((err: Error) => setConfig({ error: err.message }));
}, [endpoint]);
return config;
}
/**
* A block shown alone opens on its skeleton, if it has one, in place of "Loading from Quill" while the key loads. A block
* gets the app's Quill endpoint, under which the server also answers other routes (Jev at /jev).
*/
const BLOCKS: { route: string; title: string; block: (endpoint: string) => ReactNode; skeleton?: () => ReactNode }[] = [
{ route: 'metrics-dashboard', title: 'Metrics dashboard', block: () => <MetricsDashboardBlock /> },
{ route: 'tabbed-dashboard', title: 'Tabbed dashboard', block: () => <TabbedDashboardBlock /> },
{ route: 'filtered-dashboard', title: 'Filtered dashboard', block: () => <FilteredDashboardBlock /> },
{ route: 'date-comparison-dashboard', title: 'Date comparison dashboard', block: () => <DateComparisonDashboardBlock /> },
{ route: 'drill-down', title: 'Drill down', block: () => <DrillDownBlock /> },
{ route: 'insight', title: 'Insight', block: () => <InsightBlock /> },
{ route: 'report-builder', title: 'Report builder', block: (endpoint) => <ReportBuilder endpoint={endpoint} /> },
{ route: 'report-builder-advanced', title: 'Report builder, advanced filters', block: (endpoint) => <ReportBuilderAdvanced endpoint={endpoint} /> },
{ route: 'report-builder-sidebar', title: 'Report builder, sidebar', block: (endpoint) => <ReportBuilderSidebar endpoint={endpoint} /> },
{ route: 'report-builder-sidebar-advanced', title: 'Report builder, sidebar, advanced filters', block: (endpoint) => <ReportBuilderSidebarAdvanced endpoint={endpoint} /> },
{ route: 'alert-builder-2', title: 'Alert builder 2', block: () => <AlertBuilder /> },
{ route: 'adaptive-ui', title: 'Generative UI', block: (endpoint) => <AdaptiveUiBlock jevEndpoint={`${endpoint}/jev`} /> },
{ route: 'search-bar', title: 'Search bar', block: (endpoint) => <SearchBarBlock jevEndpoint={`${endpoint}/jev`} /> },
];
/** `#/drill-down` shows that block alone, as each frame of the docs does; no route shows them all. */
function useRoute() {
const read = () => window.location.hash.replace(/^#\/?/, '');
const [route, setRoute] = useState(read);
useEffect(() => {
const onChange = () => setRoute(read());
window.addEventListener('hashchange', onChange);
return () => window.removeEventListener('hashchange', onChange);
}, []);
return route;
}
/** The block of the route in the URL, or of `route` with Quill at `endpoint`, as a docs page shows one inline (docs.tsx). */
export function App({ route: inline, endpoint = QUERY_ENDPOINT }: { route?: string; endpoint?: string }) {
const dark = useDark();
const { publicKey, error } = usePublicKey(endpoint);
const hash = useRoute();
const route = inline ?? hash;
const blocks = BLOCKS.filter((b) => b.route === route);
const shown = blocks.length ? blocks : BLOCKS;
return (
<div className="page" data-single={blocks.length ? '' : undefined}>
{!publicKey ? (
!error && blocks[0]?.skeleton ? blocks[0].skeleton() : <BlockStatus error={error} />
) : (
<QuillProvider theme={quillTheme(dark)} publicKey={publicKey} queryEndpoint={endpoint}>
<main className="blocks">
{shown.map(({ route, title, block }) => (
<section key={route} className="block" aria-label={title}>
{shown.length > 1 && <h2>{title}</h2>}
{block(endpoint)}
</section>
))}
</main>
</QuillProvider>
)}
</div>
);
}import { Quill } from '@quillsql/node';
const quill = new Quill({
privateKey: process.env.QUILL_PRIVATE_KEY,
databaseType: 'postgresql',
databaseConnectionString: process.env.DATABASE_URL,
});
// "authenticate" is your existing auth middleware.
app.post('/quill', authenticate, async (req, res) => {
const result = await quill.query({
tenants: [{ tenantField: 'organization_id', tenantIds: [req.user.organizationId] }],
metadata: req.body.metadata,
});
res.send(result);
});Dashboard with tabbed sections
import { useState } from 'react';
import { Chart, format, useDashboard } from '@quillsql/react';
import segmented from '../components/segmented-control/segmented-control.module.css';
import { BlockStatus } from './BlockStatus';
import styles from './TabbedDashboardBlock.module.css';
export function TabbedDashboardBlock() {
const { isLoading, error, sections, sectionOrder } = useDashboard('Tabbed dashboard');
const tabs = sectionOrder.map(({ section }) => section).filter(Boolean);
const [picked, setPicked] = useState<string>();
const active = picked ?? tabs[0];
if (error) return <BlockStatus error={error.message} />;
if (isLoading || !active) return <BlockStatus />;
return (
<section className={styles.root}>
<header className={styles.header}>
<div className={`${segmented.root} ${styles.sections}`} role="group" aria-label="Dashboard sections">
<div className={segmented.track}>
{tabs.map((section) => (
<button key={section} className={segmented.button} aria-pressed={section === active} onClick={() => setPicked(section)}>
{section === active && <span className={segmented.selection} />}
<span className={segmented.label}>{section}</span>
</button>
))}
</div>
</div>
</header>
<div className={styles.grid}>
{sections[active].map((report) =>
report.chartType === 'metric' ? (
<div key={report.id} className={styles.metric}>
<h3>{report.name}</h3>
<span className={styles.value}>{format({ value: report.pivotRows?.[0]?.[report.xAxisField], format: report.xAxisFormat })}</span>
</div>
) : (
<div key={report.id} className={styles.chart}>
<h3>{report.name}</h3>
<Chart reportId={report.id} containerStyle={{ width: '100%', height: 220 }} />
</div>
),
)}
</div>
</section>
);
}import { Quill } from '@quillsql/node';
const quill = new Quill({
privateKey: process.env.QUILL_PRIVATE_KEY,
databaseType: 'postgresql',
databaseConnectionString: process.env.DATABASE_URL,
});
// "authenticate" is your existing auth middleware.
app.post('/quill', authenticate, async (req, res) => {
const result = await quill.query({
tenants: [{ tenantField: 'organization_id', tenantIds: [req.user.organizationId] }],
metadata: req.body.metadata,
});
res.send(result);
});Dashboard with filters
import { Chart, DashboardFilterType, format, useDashboard, useDashboardReport, type QuillReport } from '@quillsql/react';
import { DateRangePicker } from '../components/date-range-picker/date-range-picker';
import { MultiSelect, Select } from '../components/filter-builder/filter-builder';
import { MorphBlock, SkeletonMorph } from '../components/skeleton-morph/skeleton-morph';
import { BlockStatus } from './BlockStatus';
import styles from './FilteredDashboardBlock.module.css';
/** A metric's figure, a skeleton until its report's row arrives, so a filter change never shows the last one's value. */
function MetricValue({ metric }: { metric: QuillReport }) {
const { report, loading } = useDashboardReport(metric.id);
const row = report?.pivotRows?.[0];
return (
<SkeletonMorph loading={loading || !row} loadingLabel={`Loading ${metric.name}`}>
<MorphBlock width={96} height={29}>
<span className={styles.value}>{format({ value: row?.[metric.xAxisField], format: metric.xAxisFormat })}</span>
</MorphBlock>
</SkeletonMorph>
);
}
export function FilteredDashboardBlock() {
const { isLoading, error, sections, filters, applyFilters } = useDashboard('Filtered dashboard');
if (isLoading) return <BlockStatus />;
if (error) return <BlockStatus error={error.message} />;
const reports = Object.values(sections).flat();
return (
<section className={styles.root}>
<header className={styles.filters}>
{filters.map((filter) => {
const { label } = filter;
const options = filter.options.map((option) => ({ label: option.label, value: String(option.value) }));
switch (filter.type) {
case DashboardFilterType.Date: {
// The filter's presets with dates (all but All time) fill the picker's rail; a range one of them gives stays that preset.
const presets = filter.options.filter((option) => option.startDate && option.endDate);
const { startDate, endDate, presetValue } = filter.value;
return (
<div key={label} className={styles.field}>
<span>{label}</span>
<DateRangePicker label={label} size="sm" weekStartsOn={1} maxDate={new Date()}
presets={presets.map((option) => ({ label: option.label, range: () => ({ start: new Date(option.startDate!), end: new Date(option.endDate!) }) }))}
preset={presetValue ? presets.find((option) => option.value === presetValue)?.label : startDate ? null : undefined}
value={startDate && endDate ? { start: new Date(startDate), end: new Date(endDate) } : null}
onChange={({ start, end }, presetLabel) => {
const preset = presets.find((option) => option.label === presetLabel);
applyFilters([{ label, value: preset ? { preset: preset.value } : { startDate: start, endDate: new Date(new Date(end).setHours(23, 59, 59, 999)) } }]);
}} />
</div>
);
}
case DashboardFilterType.MultiSelect:
return <MultiSelect key={label} className={styles.group} label={label} placeholder="All" options={options}
value={filter.value ?? []} onChange={(value) => applyFilters([{ label, value }])} />;
case DashboardFilterType.Select:
return <Select key={label} className={styles.group} label={label} options={[{ value: '', label: 'All' }, ...options]}
value={filter.value} onChange={(value) => applyFilters([{ label, value }])} />;
default:
return null;
}
})}
</header>
<div className={styles.grid}>
{reports.map((report) =>
report.chartType === 'metric' ? (
<div key={report.id} className={styles.metric}>
<h3>{report.name}</h3>
<MetricValue metric={report} />
</div>
) : (
<div key={report.id} className={styles.chart}>
<h3>{report.name}</h3>
<Chart reportId={report.id} containerStyle={{ width: '100%', height: 220 }} />
</div>
),
)}
</div>
</section>
);
}import { Quill } from '@quillsql/node';
const quill = new Quill({
privateKey: process.env.QUILL_PRIVATE_KEY,
databaseType: 'postgresql',
databaseConnectionString: process.env.DATABASE_URL,
});
// "authenticate" is your existing auth middleware.
app.post('/quill', authenticate, async (req, res) => {
const result = await quill.query({
tenants: [{ tenantField: 'organization_id', tenantIds: [req.user.organizationId] }],
metadata: req.body.metadata,
});
res.send(result);
});Dashboard with date comparison
import { useState } from 'react';
import { Chart, DashboardFilterType, format, useDashboard, useDashboardReport, type QuillReport } from '@quillsql/react';
import { Select } from '../components/filter-builder/filter-builder';
import { MorphBlock, SkeletonMorph } from '../components/skeleton-morph/skeleton-morph';
import { Switch } from '../components/switch/switch';
import { BlockStatus } from './BlockStatus';
import styles from './FilteredDashboardBlock.module.css';
import comparison from './DateComparisonDashboardBlock.module.css';
/** A chart's value in the hovered bucket, else the last one, and its change from the same bucket a period earlier. */
function Total({ metric, compare, hovered }: { metric: QuillReport; compare: boolean; hovered?: Record<string, unknown> }) {
const { report, loading } = useDashboardReport(metric.id);
const axis = report?.yAxisFields?.[0];
const row = hovered ?? report?.pivotRows?.at(-1);
const sum = (field: string) => Number(row?.[field] ?? 0);
const current = axis ? sum(axis.field) : 0;
const previous = axis ? sum(`comparison_${axis.field}`) : 0;
return (
<SkeletonMorph className={comparison.total} loading={loading || !report?.pivotRows?.length} loadingLabel={`Loading ${metric.name}`}>
<MorphBlock width={120} height={29}>
<div className={comparison.figure}>
<span className={styles.value}>{format({ value: current, format: axis?.format ?? 'whole_number' })}</span>
{compare && previous > 0 && (
<span className={comparison.change} data-down={current < previous || undefined}>
{current >= previous && '+'}
{format({ value: current / previous - 1, format: 'percent' })}
</span>
)}
</div>
</MorphBlock>
</SkeletonMorph>
);
}
/** Auto keeps each chart's own bucket; the others bucket every date chart on the dashboard. */
const BUCKETS = ['auto', 'day', 'week', 'month'].map((b) => ({ value: b, label: b[0].toUpperCase() + b.slice(1) }));
export function DateComparisonDashboardBlock() {
const { isLoading, error, sections, filters, applyFilters } = useDashboard('Date comparison');
const date = filters.find((filter) => filter.type === DashboardFilterType.Date);
// The rows carry the previous period either way, so this only changes what's drawn.
const [compare, setCompare] = useState(true);
if (isLoading) return <BlockStatus />;
if (error) return <BlockStatus error={error.message} />;
const reports = Object.values(sections).flat();
return (
<section className={styles.root}>
<header className={styles.filters}>
{date && (
<>
{/* The presets with dates: All time has no period before it. */}
<Select className={styles.group} label={date.label} value={date.value.presetValue}
options={date.options.filter((option) => option.startDate)}
onChange={(preset) => applyFilters([{ label: date.label, value: { preset } }])} />
<Select className={styles.group} label="Date bucket" value={date.value.dateBucket ?? 'auto'} options={BUCKETS}
onChange={(bucket) => applyFilters([{ label: date.label,
value: { preset: date.value.presetValue, dateBucket: bucket === 'auto' ? '' : (bucket as 'day' | 'week' | 'month') } }])} />
</>
)}
<Switch className={comparison.compare} label="Compare to previous period" checked={compare} onCheckedChange={setCompare} />
</header>
<div className={styles.grid}>
{reports.map((report) => (
<ChartCard key={report.id} report={report} compare={compare} />
))}
</div>
</section>
);
}
/** Module scope, so a hover re-render leaves Chart's props alone and skips it. */
const CHART_STYLE = { width: '100%', height: 220 };
/** A chart under its figure, which follows the hovered bucket. */
function ChartCard({ report, compare }: { report: QuillReport; compare: boolean }) {
const [hovered, setHovered] = useState<Record<string, unknown>>();
return (
<div className={styles.chart}>
<h3>{report.name}</h3>
<Total metric={report} compare={compare} hovered={hovered} />
<Chart reportId={report.id} compareToPreviousPeriod={compare} onHoverChartElement={setHovered}
containerStyle={CHART_STYLE} />
</div>
);
}import { Quill } from '@quillsql/node';
const quill = new Quill({
privateKey: process.env.QUILL_PRIVATE_KEY,
databaseType: 'postgresql',
databaseConnectionString: process.env.DATABASE_URL,
});
// "authenticate" is your existing auth middleware.
app.post('/quill', authenticate, async (req, res) => {
const result = await quill.query({
tenants: [{ tenantField: 'organization_id', tenantIds: [req.user.organizationId] }],
metadata: req.body.metadata,
});
res.send(result);
});