Birch UI v0.1
Pricing

Save and load pivot layoutsPivot Studio

Let users save named Pivot Studio layouts as PivotReport JSON, keep them in localStorage or on your server, and open them again.

Open .md

Analysts build the same few views over and over: revenue by depot, hours by technician, first-time fix rate by job type. This recipe adds a layout picker to a Pivot Studio report so each view is built once, saved under a name, and opened again with one click. Layouts are stored as PivotReport JSON, first in localStorage and then on a server.

Saved pivot layouts

Loading demo…

View source

Sample data and small UI helpers are imported from the docs' demos/_shared.ts and demos/_scheduler-data.ts files.

demos/recipe-pivot-saved-layouts.ts
import { createPivotStudio, type PivotReport } from '@birchui/pivot-studio';
import { button, docsTheme, field, layout, onDocsThemeChange, seededRandom } from './_shared';

export const meta = { title: 'Saved pivot layouts', height: 600 };

const STORAGE_KEY = 'birchui-docs:work-order-layouts';

interface WorkOrder {
  region: string;
  depot: string;
  technician: string;
  jobType: string;
  month: string;
  hours: number;
  revenue: number;
  firstTimeFix: number;
}

const DEPOTS: [string, string, string[]][] = [
  ['North', 'Leeds', ['Ana Ruiz', 'Omar Haddad']],
  ['North', 'Manchester', ['Li Wei', 'Sam Patel']],
  ['South', 'Bristol', ['Nora Lindqvist', 'Ben Mensah']],
  ['South', 'Southampton', ['Priya Natarajan', 'Diego Alvarez']],
  ['London', 'Croydon', ['Hana Sato', 'Jonas Becker']],
];
const JOB_TYPES: [string, number, number][] = [
  ['Boiler service', 1.5, 95],
  ['Heat pump install', 14, 1850],
  ['EV charger fit', 5, 640],
  ['Fault finding', 2.5, 180],
  ['Annual inspection', 1, 75],
];

function makeWorkOrders(): WorkOrder[] {
  const random = seededRandom(47);
  const orders: WorkOrder[] = [];
  for (let m = 0; m < 6; m++) {
    const month = `2026-${String(m + 7).padStart(2, '0')}`;
    for (const [region, depot, crew] of DEPOTS) {
      for (const technician of crew) {
        for (const [jobType, hours, price] of JOB_TYPES) {
          const count = 1 + Math.floor(random() * 6);
          orders.push({
            region,
            depot,
            technician,
            jobType,
            month,
            hours: Math.round(count * hours * (0.8 + random() * 0.4) * 10) / 10,
            revenue: Math.round(count * price * (0.9 + random() * 0.2)),
            firstTimeFix: random() < 0.82 ? 1 : 0,
          });
        }
      }
    }
  }
  return orders;
}

const BUILT_IN: Record<string, PivotReport> = {
  'Revenue by depot': {
    version: 1,
    slice: {
      rows: [{ field: 'region' }, { field: 'depot' }],
      columns: [{ field: 'month' }],
      values: [{ field: 'revenue', aggregation: 'sum', caption: 'Revenue' }],
    },
    formats: { revenue: { style: 'currency', currency: 'GBP', decimals: 0 } },
  },
  'Hours by technician': {
    version: 1,
    slice: {
      rows: [{ field: 'technician', sortBy: { measure: 'sum(hours)', dir: 'desc' } }],
      columns: [{ field: 'jobType' }],
      values: [{ field: 'hours', aggregation: 'sum', caption: 'Hours' }],
    },
    options: { columnSubtotals: false },
  },
  'First-time fix rate': {
    version: 1,
    slice: {
      rows: [{ field: 'jobType' }],
      columns: [{ field: 'region' }],
      values: [{ field: 'firstTimeFix', aggregation: 'avg', caption: 'First-time fix' }],
    },
    formats: { firstTimeFix: { style: 'percent', decimals: 0 } },
  },
};

function readSaved(): Record<string, PivotReport> {
  try {
    const text = window.localStorage.getItem(STORAGE_KEY);
    const parsed: unknown = text ? JSON.parse(text) : {};
    return parsed && typeof parsed === 'object' ? (parsed as Record<string, PivotReport>) : {};
  } catch {
    return {};
  }
}

function writeSaved(layouts: Record<string, PivotReport>): boolean {
  try {
    window.localStorage.setItem(STORAGE_KEY, JSON.stringify(layouts));
    return true;
  } catch {
    return false;
  }
}

export default function mount(el: HTMLElement): () => void {
  const { toolbar, body, status } = layout(el);
  let saved = readSaved();

  const picker = document.createElement('select');
  const nameInput = document.createElement('input');
  nameInput.type = 'text';
  nameInput.placeholder = 'Layout name';
  nameInput.value = 'My layout';

  const allLayouts = () => ({ ...BUILT_IN, ...saved });
  const renderPicker = (selected: string) => {
    picker.replaceChildren(
      ...Object.keys(allLayouts()).map((name) => new Option(name, name, false, name === selected)),
    );
  };

  const studio = createPivotStudio<WorkOrder>(body, {
    data: makeWorkOrders(),
    report: BUILT_IN['Revenue by depot'],
    theme: docsTheme(),
    height: '100%',
    fileName: 'work-orders-h2-2026',
    ariaLabel: 'Work order pivot report',
  });

  const saveButton = button('Save layout', () => {
    const name = nameInput.value.trim();
    if (!name) {
      status.textContent = 'Enter a name for the layout first.';
      return;
    }
    saved = { ...saved, [name]: studio.getReport() };
    const stored = writeSaved(saved);
    renderPicker(name);
    status.textContent = stored
      ? `Saved "${name}". It is still here after a reload.`
      : `Saved "${name}" for this visit only; browser storage is unavailable.`;
  });
  const deleteButton = button('Delete', () => {
    const name = picker.value;
    if (!(name in saved)) {
      status.textContent = `"${name}" is a built-in layout and cannot be deleted.`;
      return;
    }
    saved = Object.fromEntries(Object.entries(saved).filter(([key]) => key !== name));
    writeSaved(saved);
    renderPicker('Revenue by depot');
    studio.setReport(BUILT_IN['Revenue by depot']);
    status.textContent = `Deleted "${name}".`;
  });
  const onPick = () => {
    const report = allLayouts()[picker.value];
    if (report) studio.setReport(report);
    status.textContent = `Opened "${picker.value}".`;
  };
  picker.addEventListener('change', onPick);

  renderPicker('Revenue by depot');
  toolbar.append(field('Layout', picker), field('Save as', nameInput), saveButton, deleteButton);

  const offs = [
    studio.on('error', ({ message }) => {
      status.textContent = message;
    }),
  ];
  status.textContent = 'Rearrange the fields, then save the layout under a name.';
  const stopTheme = onDocsThemeChange((theme) => studio.update({ theme }));
  return () => {
    picker.removeEventListener('change', onPick);
    for (const off of offs) off();
    stopTheme();
    studio.destroy();
  };
}

Steps#

  1. Define the built-in layouts your team ships as PivotReport objects.
  2. Read the user's saved layouts on start-up and merge them with the built-in ones.
  3. On Save layout, store studio.getReport() under the chosen name.
  4. On selection, call studio.setReport(report). The data stays loaded; only the layout changes.

Built-in layouts#

A report needs only the slice; every other key falls back to its default.

work-order-layouts.ts
import type { PivotReport } from '@birchui/pivot-studio';

export const BUILT_IN_LAYOUTS: Record<string, PivotReport> = {
  'Revenue by depot': {
    version: 1,
    slice: {
      rows: [{ field: 'region' }, { field: 'depot' }],
      columns: [{ field: 'month' }],
      values: [{ field: 'revenue', aggregation: 'sum', caption: 'Revenue' }],
    },
    formats: { revenue: { style: 'currency', currency: 'GBP', decimals: 0 } },
  },
  'Hours by technician': {
    version: 1,
    slice: {
      rows: [{ field: 'technician', sortBy: { measure: 'sum(hours)', dir: 'desc' } }],
      columns: [{ field: 'jobType' }],
      values: [{ field: 'hours', aggregation: 'sum', caption: 'Hours' }],
    },
    options: { columnSubtotals: false },
  },
  'First-time fix rate': {
    version: 1,
    slice: {
      rows: [{ field: 'jobType' }],
      columns: [{ field: 'region' }],
      values: [{ field: 'firstTimeFix', aggregation: 'avg', caption: 'First-time fix' }],
    },
    formats: { firstTimeFix: { style: 'percent', decimals: 0 } },
  },
};

Save to localStorage#

localStorage can throw: in private windows, when storage is full, or when the user has blocked site data. Wrap every access so the report keeps working without it.

layout-store.ts
import type { PivotReport } from '@birchui/pivot-studio';

const STORAGE_KEY = 'work-orders:pivot-layouts';

export function readLayouts(): Record<string, PivotReport> {
  try {
    const text = window.localStorage.getItem(STORAGE_KEY);
    const parsed: unknown = text ? JSON.parse(text) : {};
    return parsed && typeof parsed === 'object' ? (parsed as Record<string, PivotReport>) : {};
  } catch {
    return {};
  }
}

export function writeLayouts(layouts: Record<string, PivotReport>): boolean {
  try {
    window.localStorage.setItem(STORAGE_KEY, JSON.stringify(layouts));
    return true;
  } catch {
    return false;
  }
}

Wire up the picker#

work-order-report.ts
import { createPivotStudio } from '@birchui/pivot-studio';
import { BUILT_IN_LAYOUTS } from './work-order-layouts';
import { readLayouts, writeLayouts } from './layout-store';

const picker = document.querySelector<HTMLSelectElement>('#layout-picker')!;
const nameInput = document.querySelector<HTMLInputElement>('#layout-name')!;
let saved = readLayouts();

const allLayouts = () => ({ ...BUILT_IN_LAYOUTS, ...saved });

function renderPicker(selected: string) {
  picker.replaceChildren(...Object.keys(allLayouts()).map((name) => new Option(name, name, false, name === selected)));
}

const studio = createPivotStudio<WorkOrder>(document.querySelector<HTMLElement>('#work-orders')!, {
  data: workOrders,
  report: BUILT_IN_LAYOUTS['Revenue by depot'],
  fileName: 'work-orders-h2-2026',
});

picker.addEventListener('change', () => studio.setReport(allLayouts()[picker.value]));

document.querySelector('#save-layout')!.addEventListener('click', () => {
  const name = nameInput.value.trim();
  if (!name) return;
  saved = { ...saved, [name]: studio.getReport() };
  writeLayouts(saved);
  renderPicker(name);
});

renderPicker('Revenue by depot');

Save to a server#

For layouts that follow the user across devices, or that a team shares, store them on your server. Clean reports with normalizeReport() before you store them, so a hand-edited or outdated report never reaches the database:

server/layouts.ts
import { normalizeReport, type PivotReport } from '@birchui/pivot-studio';

export async function saveLayout(userId: string, name: string, body: unknown): Promise<PivotReport> {
  const report = normalizeReport(body, (message) => logger.warn({ userId, name }, message));
  await db.pivotLayouts.upsert({ userId, name, report: JSON.stringify(report), updatedAt: new Date() });
  return report;
}

In the browser, replace writeLayouts with a request:

layout-api.ts
import type { PivotReport } from '@birchui/pivot-studio';

export async function saveLayoutToServer(name: string, report: PivotReport): Promise<void> {
  const response = await fetch(`/api/pivot-layouts/${encodeURIComponent(name)}`, {
    method: 'PUT',
    headers: { 'Content-Type': 'application/json' },
    body: JSON.stringify(report),
  });
  if (!response.ok) throw new Error(`Layout "${name}" could not be saved (${response.status})`);
}

export async function loadLayoutsFromServer(): Promise<Record<string, PivotReport>> {
  const response = await fetch('/api/pivot-layouts');
  return response.ok ? ((await response.json()) as Record<string, PivotReport>) : {};
}

To remember the layout a user was last looking at, save on reportChange with a debounce, as in Saving and loading reports.

How it works#

  • getReport() returns the whole layout: fields in each zone, filters, sorts, number formats, conditional formats, layout options and which members are expanded.
  • setReport(report) replaces the layout and recomputes the table without reloading the data.
  • Reports are validated on load. Fields that no longer exist are ignored with a console warning, so an old layout never breaks the widget.

Pitfalls#

  • Renamed fields. Layouts refer to field names. When you rename a column in your data, migrate stored layouts or keep the old name as an alias column. See the tip in Saving and loading reports.
  • Several datasets. If one page can show different datasets, store the dataset id in dataSource.ref and load the matching data before calling setReport(). See The data source reference.
  • Saving on every change. reportChange fires several times while a chip is dragged. Save named layouts on an explicit action, and debounce automatic saves.

↑ ↓ to move, Enter to open, Esc to close