<!--# if expr="$arg_server = /^(node|python|go|php|ruby|dotnet)$/" --><!--# set var="stack_server" value="$arg_server" --><!--# else --><!--# set var="stack_server" value="node" --><!--# endif --><!--# if expr="$arg_database = /^(postgresql|redshift|mysql|mssql|clickhouse|snowflake|bigquery|databricks)$/" --><!--# set var="stack_database" value="$arg_database" --><!--# else --><!--# set var="stack_database" value="postgresql" --><!--# endif --><!--# if expr="$arg_cache = /^(none|duckdb|redis)$/" --><!--# set var="stack_cache" value="$arg_cache" --><!--# else --><!--# set var="stack_cache" value="none" --><!--# endif -->
# Dashboard

A section list of reports with global filters.

> The code on this page is for the stack in its URL's query, by default `?server=node&database=postgresql&cache=none`. Server: `node`, `python`, `go`, `php`, `ruby`, `dotnet`. Database: `postgresql`, `redshift`, `mysql`, `mssql`, `clickhouse`, `snowflake`, `bigquery`, `databricks`. Cache: `none`, `duckdb` (`node` only), `redis`. A missing or unknown value is the default, the first listed.

## Metric detail dashboard

[Open the demo](https://quill.co/docs-demo/blocks/#/metrics-dashboard)

`MetricsDashboardBlock.tsx`

Source is included with Quill Enterprise. [Get Quill Enterprise](https://cal.com/quillsql/30min)

`App.tsx`

Source is included with Quill Enterprise. [Get Quill Enterprise](https://cal.com/quillsql/30min)

<!--# include virtual="/docs-md/code/server-file/$stack_server/$stack_database/$stack_cache.md" -->

## Dashboard with tabbed sections

[Open the demo](https://quill.co/docs-demo/blocks/#/tabbed-dashboard)

`TabbedDashboardBlock.tsx`

```tsx
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>
  );
}
```

<!--# include virtual="/docs-md/code/server-file/$stack_server/$stack_database/$stack_cache.md" -->

## Dashboard with filters

[Open the demo](https://quill.co/docs-demo/blocks/#/filtered-dashboard)

`FilteredDashboardBlock.tsx`

```tsx
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>
  );
}
```

<!--# include virtual="/docs-md/code/server-file/$stack_server/$stack_database/$stack_cache.md" -->

## Dashboard with date comparison

[Open the demo](https://quill.co/docs-demo/blocks/#/date-comparison-dashboard)

`DateComparisonDashboardBlock.tsx`

```tsx
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>
  );
}
```

<!--# include virtual="/docs-md/code/server-file/$stack_server/$stack_database/$stack_cache.md" -->
