Skip to content

armgit / macro

Public Imported from GitHub
0

Macro is a unified workspace for teams: email, chat, docs, tasks, agents, calls, and CRM — @-linked together with shared AI memory.

feat(spreadsheet): Excel 2016 charts, pie of pie and bar of pie (#9326)

Wolf Mermelstein8ac0481ab83e
diff --git a/apps/web/src/features/block-spreadsheet/README.md b/apps/web/src/features/block-spreadsheet/README.md
index 2be280ed78..d12cf447eb 100644
--- a/apps/web/src/features/block-spreadsheet/README.md
+++ b/apps/web/src/features/block-spreadsheet/README.md
@@ -509,7 +509,9 @@ compare formula, error, and formatting behavior before replacing it.
`core/chart-builder.ts`), an image file, or checkboxes, as one undoable change. Its More
charts submenu holds radar, filled radar, bubble (x values, then pairs of
values and sizes), stock (three or four series: high, low and close, with
- open first for up-down bars) and contour charts. Drawings
+ open first for up-down bars), contour, histogram, waterfall, funnel, box and
+ whisker, treemap and sunburst charts; Edit chart also offers pareto, pie of
+ pie and bar of pie. Drawings
move by dragging and keyboard arrows and size by their handles;
`primitives/create-drawing-actions.ts` writes them, and the Edit chart
dialog changes a chart's type, title, legend and data. Edited charts are
@@ -610,6 +612,19 @@ Import keeps what Excel calculates and shows:
back with its current ranges and fresh caches; charts without it, or too large
to keep, are written from what Macro knows, with axes formatted like their
cells.
+- Excel 2016 charts. Histogram, pareto, waterfall, funnel, box and whisker,
+ treemap and sunburst charts are `cx:` chartEx parts behind
+ `mc:AlternateContent`. `core/xlsx-chartex.ts` reads them (series layout
+ options, bins, totals, quartile method, parent labels and axis gaps), keeps
+ the part for export with fresh caches, and writes parts for charts Macro
+ describes, which drawing parts wrap with Excel's fallback note. Maps and
+ other chartEx kinds import as that fallback. `core/chart-statistics.ts` holds
+ the math (Scott's-rule bins, QUARTILE.INC/EXC and 1.5 IQR whiskers, running
+ waterfall totals, label hierarchies, squarified tiles, sunburst arcs, of-pie
+ splits); `core/chart-axis-scenes.ts` and `core/chart-area-scenes.ts` draw
+ them. Pie of pie and bar of pie are `c:ofPieChart` pies with a split.
+ Automatic colors past the sixth are Office's shades of the accents
+ (`paletteColor` in `core/drawingml-colors.ts`).
- Shapes, text boxes, lines and groups. `core/xlsx-shapes.ts` reads each
`xdr:sp`, `xdr:cxnSp` and `xdr:grpSp` into parts placed as fractions of the
drawing (a group's members in its own coordinates): a preset or custom
diff --git a/apps/web/src/features/block-spreadsheet/browser-test/README.md b/apps/web/src/features/block-spreadsheet/browser-test/README.md
index a12d7bb174..ba1877b697 100644
--- a/apps/web/src/features/block-spreadsheet/browser-test/README.md
+++ b/apps/web/src/features/block-spreadsheet/browser-test/README.md
@@ -52,7 +52,10 @@ and images (drawn over their cells, following edits, deleted and restored with
undo, and kept in the download), radar, bubble, stock and contour charts
(imported, redrawn after edits, inserted from More charts and downloaded),
100% stacked columns from the insert menu and combo charts chosen in
-Edit chart,
+Edit chart, Excel 2016 histogram, pareto, waterfall, funnel, box and whisker,
+treemap and sunburst charts and pie of pie and bar of pie (imported from
+chartEx parts, redrawn after edits, inserted, retyped and downloaded as
+chartEx),
shapes, text boxes, groups, SmartArt and an EMF logo (drawn, a linked text box
following its cell, moved and downloaded), GETPIVOTDATA formulas of an imported
pivot table (calculated, following an edit to the table and downloaded), pivot
diff --git a/apps/web/src/features/block-spreadsheet/browser-test/chart-types.browser.e2e.ts b/apps/web/src/features/block-spreadsheet/browser-test/chart-types.browser.e2e.ts
index 11426993ab..097d50f1a3 100644
--- a/apps/web/src/features/block-spreadsheet/browser-test/chart-types.browser.e2e.ts
+++ b/apps/web/src/features/block-spreadsheet/browser-test/chart-types.browser.e2e.ts
@@ -15,7 +15,7 @@ test.beforeEach(async ({ page }) => {
await page.goto('/');
await expect(page.locator('[data-address="B4"]')).toHaveText('30');
const chooser = page.waitForEvent('filechooser');
- await menu(page, 'Import and export', 'Import…');
+ await page.getByRole('button', { name: 'Import', exact: true }).click();
await (await chooser).setFiles(
fileURLToPath(
new URL('../core/xlsx-fixtures/chart-types.xlsx', import.meta.url)
@@ -132,7 +132,7 @@ test('more chart types are inserted from the Insert menu and downloaded', async
await dialog.getByRole('button', { name: 'Cancel' }).click();
const downloaded = page.waitForEvent('download');
- await menu(page, 'Import and export', 'Download as Excel (.xlsx)');
+ await menu(page, 'Download', 'Download as Excel (.xlsx)');
const path = await (await downloaded).path();
if (!path) throw new Error('Workbook download missing');
const files = unzipSync(new Uint8Array(readFileSync(path)));
diff --git a/apps/web/src/features/block-spreadsheet/browser-test/office-2016-charts.browser.e2e.ts b/apps/web/src/features/block-spreadsheet/browser-test/office-2016-charts.browser.e2e.ts
new file mode 100644
index 0000000000..f2e71bc73e
--- /dev/null
+++ b/apps/web/src/features/block-spreadsheet/browser-test/office-2016-charts.browser.e2e.ts
@@ -0,0 +1,177 @@
+import { readFileSync } from 'node:fs';
+import { fileURLToPath } from 'node:url';
+import { expect, type Page, test } from '@playwright/test';
+import { strFromU8, unzipSync } from 'fflate';
+
+async function menu(page: Page, name: string, item: string) {
+ await page.getByRole('button', { name, exact: true }).click();
+ await page.getByRole('menuitem', { name: item, exact: true }).click();
+}
+
+const sheet = (page: Page, name: string) =>
+ page.getByRole('tab', { name, exact: true }).click();
+
+test.beforeEach(async ({ page }) => {
+ await page.goto('/');
+ await expect(page.locator('[data-address="B4"]')).toHaveText('30');
+ const chooser = page.waitForEvent('filechooser');
+ await page.getByRole('button', { name: 'Import', exact: true }).click();
+ await (await chooser).setFiles(
+ fileURLToPath(
+ new URL('../core/xlsx-fixtures/office-2016-charts.xlsx', import.meta.url)
+ )
+ );
+ await page.getByRole('button', { name: 'Import workbook' }).click();
+ await expect(
+ page.getByRole('tab', { name: 'Share', exact: true })
+ ).toBeVisible();
+});
+
+test("Excel 2016's charts and pie of pie draw from their cells", async ({
+ page,
+}) => {
+ await sheet(page, 'Scores');
+ const histogram = page.getByRole('figure', { name: 'Chart: Scores' });
+ await expect(histogram.locator('rect title')).toHaveText([
+ '[52, 62]: 3',
+ '(62, 72]: 5',
+ '(72, 82]: 3',
+ '(82, 92]: 3',
+ '(92, 102]: 1',
+ ]);
+
+ await sheet(page, 'Defects');
+ const pareto = page.getByRole('figure', { name: 'Chart: Defects' });
+ await expect(pareto.locator('rect title')).toHaveText([
+ 'Scratches: 40',
+ 'Chips: 30',
+ 'Cracks: 20',
+ 'Dents: 10',
+ 'Stains: 5',
+ ]);
+ await expect(pareto.locator('svg text', { hasText: /^100%$/ })).toHaveCount(
+ 1
+ );
+
+ await sheet(page, 'Cash');
+ const waterfall = page.getByRole('figure', { name: 'Chart: Cash flow' });
+ await expect(waterfall.locator('rect title')).toHaveText([
+ 'Start: 100',
+ 'Sales: 60',
+ 'Services: 20',
+ 'Costs: -50',
+ 'Tax: -15',
+ 'End: 115',
+ ]);
+ // A change in a cell moves every later bar and the total.
+ await page.locator('[data-address="B5"]').dblclick();
+ const input = page.getByRole('textbox', { name: 'Edit B5', exact: true });
+ await input.fill('-70');
+ await input.press('Enter');
+ await expect(
+ waterfall.locator('rect title', { hasText: 'Costs: -70' })
+ ).toHaveCount(1);
+
+ await sheet(page, 'Pipeline');
+ const funnel = page.getByRole('figure', { name: 'Chart: Pipeline' });
+ await expect(funnel.locator('rect title')).toHaveText([
+ 'Visits: 1,000',
+ 'Leads: 400',
+ 'Trials: 150',
+ 'Sales: 60',
+ ]);
+
+ await sheet(page, 'Times');
+ const box = page.getByRole('figure', { name: 'Chart: Delivery times' });
+ await expect(box.locator('rect title')).toHaveText([
+ 'Minutes · East: Q1 14.25, median 15.5, Q3 18.75',
+ 'Minutes · West: Q1 21.5, median 24, Q3 27',
+ ]);
+ await expect(
+ box.locator('circle title', { hasText: 'Minutes · East: 41' })
+ ).toHaveCount(1);
+
+ await sheet(page, 'Stores');
+ const treemap = page.getByRole('figure', { name: 'Chart: Store sales' });
+ await expect(
+ treemap.locator('rect title', { hasText: 'North › Airport: 20' })
+ ).toHaveCount(1);
+ const sunburst = page.getByRole('figure', {
+ name: 'Chart: Store sales by region',
+ });
+ await expect(sunburst.locator('path title')).toHaveText([
+ 'North: 50',
+ 'North › Downtown: 30',
+ 'North › Airport: 20',
+ 'South: 40',
+ 'South › Harbor: 25',
+ 'South › Mall: 15',
+ 'West: 10',
+ ]);
+
+ await sheet(page, 'Share');
+ const pieOfPie = page.getByRole('figure', { name: 'Chart: Pie of pie' });
+ await expect(pieOfPie.locator('path title')).toHaveText([
+ 'Desktop: 40%',
+ 'Phone: 30%',
+ 'Tablet: 12%',
+ 'Other: 18%',
+ 'Watch: 8%',
+ 'TV: 6%',
+ 'Other: 4%',
+ ]);
+ const barOfPie = page.getByRole('figure', { name: 'Chart: Bar of pie' });
+ await expect(barOfPie.locator('rect title')).toHaveText([
+ 'Watch: 8%',
+ 'TV: 6%',
+ 'Other: 4%',
+ ]);
+});
+
+test('a chart inserted as a waterfall becomes a funnel and downloads as chartEx', async ({
+ page,
+}) => {
+ await sheet(page, 'Cash');
+ await page.locator('[data-address="A3"]').click();
+ await page
+ .getByRole('button', {
+ name: 'Insert chart, image or checkbox',
+ exact: true,
+ })
+ .click();
+ await page.getByRole('menuitem', { name: 'More charts' }).click();
+ await page.getByRole('menuitem', { name: 'Waterfall', exact: true }).click();
+ const chart = page.getByRole('figure', { name: 'Chart: Amount' });
+ await expect(chart).toBeFocused();
+ await expect(chart.locator('rect title')).toHaveCount(6);
+ // The legend names the colors.
+ await expect(
+ chart.locator('svg text', { hasText: /^Decrease$/ })
+ ).toHaveCount(1);
+
+ await chart.press('Enter');
+ const dialog = page.getByRole('dialog', { name: 'Edit chart' });
+ await dialog.getByLabel('Type').selectOption('funnel');
+ await dialog.getByRole('button', { name: 'Apply' }).click();
+ await expect(
+ chart.locator('rect title', { hasText: 'Start: 100' })
+ ).toHaveCount(1);
+
+ const downloaded = page.waitForEvent('download');
+ await menu(page, 'Download', 'Download as Excel (.xlsx)');
+ const path = await (await downloaded).path();
+ if (!path) throw new Error('Workbook download missing');
+ const files = unzipSync(new Uint8Array(readFileSync(path)));
+ const parts = Object.keys(files).filter((name) =>
+ name.startsWith('xl/charts/chartEx')
+ );
+ // The seven imported, and the funnel Macro wrote.
+ expect(parts).toHaveLength(8);
+ const written = parts
+ .map((name) => strFromU8(files[name]))
+ .filter((part) => part.includes('layoutId="funnel"'));
+ expect(written).toHaveLength(2);
+ expect(strFromU8(files['xl/drawings/drawing3.xml'])).toContain(
+ 'Requires="cx2"'
+ );
+});
diff --git a/apps/web/src/features/block-spreadsheet/components/SpreadsheetChart.tsx b/apps/web/src/features/block-spreadsheet/components/SpreadsheetChart.tsx
index 783daa35cd..89a10888ff 100644
--- a/apps/web/src/features/block-spreadsheet/components/SpreadsheetChart.tsx
+++ b/apps/web/src/features/block-spreadsheet/components/SpreadsheetChart.tsx
@@ -1,6 +1,6 @@
import { For, Show } from 'solid-js';
import { match } from 'ts-pattern';
-import type { ChartScene, ChartShape } from '../core/chart-scene';
+import type { ChartScene, ChartShape } from '../core/chart-shapes';
function Shape(props: { shape: ChartShape }) {
return match(props.shape)
@@ -11,6 +11,8 @@ function Shape(props: { shape: ChartShape }) {
width={shape.width}
height={shape.height}
fill={shape.fill}
+ stroke={shape.stroke}
+ stroke-width={shape.stroke ? 1 : undefined}
>
<Show when={shape.tip}>{(tip) => <title>{tip()}</title>}</Show>
</rect>
@@ -28,6 +30,7 @@ function Shape(props: { shape: ChartShape }) {
stroke-width={shape.strokeWidth}
stroke-linejoin="round"
stroke-linecap="round"
+ stroke-dasharray={shape.dash}
opacity={shape.opacity}
>
<Show when={shape.tip}>{(tip) => <title>{tip()}</title>}</Show>
@@ -67,10 +70,13 @@ function Shape(props: { shape: ChartShape }) {
text-anchor={shape.anchor}
dominant-baseline={shape.baseline}
font-size={`${shape.size}px`}
- font-weight={shape.role === 'title' ? 600 : undefined}
- fill={
- shape.role === 'title' ? 'var(--color-ink)' : 'var(--color-ink-muted)'
- }
+ font-weight={shape.role === 'title' || shape.bold ? 600 : undefined}
+ fill={match(shape.role)
+ .with('title', () => 'var(--color-ink)')
+ .with('label', () => 'var(--color-ink-muted)')
+ // Over a series color, as Excel writes labels inside bars.
+ .with('inside', () => '#FFFFFF')
+ .exhaustive()}
>
{shape.text}
</text>
diff --git a/apps/web/src/features/block-spreadsheet/core/chart-area-scenes.ts b/apps/web/src/features/block-spreadsheet/core/chart-area-scenes.ts
new file mode 100644
index 0000000000..22215dc896
--- /dev/null
+++ b/apps/web/src/features/block-spreadsheet/core/chart-area-scenes.ts
@@ -0,0 +1,460 @@
+import { arc, pie } from 'd3-shape';
+import { valueText } from './chart-axis-scenes';
+import type { ChartData, ChartPlotData } from './chart-data';
+import {
+ type Box,
+ CHARACTER_WIDTH,
+ type ChartShape,
+ DEFAULT_GAP_WIDTHS,
+ truncate,
+} from './chart-shapes';
+import {
+ type HierarchyNode,
+ hierarchy,
+ ofPieSecond,
+ type Rect,
+ squarify,
+ sunburst,
+} from './chart-statistics';
+import { paletteColor } from './drawingml-colors';
+
+const fits = (text: string, width: number, size: number) =>
+ text.length * size * CHARACTER_WIDTH + 4 <= width;
+
+/**
+ * A funnel: a bar per category from the top down, centered, as wide as its
+ * value against the largest, its value written inside.
+ */
+export function funnelChart(
+ shapes: ChartShape[],
+ plot: ChartPlotData,
+ data: ChartData,
+ outer: Box,
+ font: number,
+ zoom: number
+) {
+ const count = Math.max(
+ data.categories.length,
+ ...plot.series.map((series) => series.values.length)
+ );
+ if (!count) return;
+ const categories = Array.from(
+ { length: count },
+ (_, index) => data.categories[index] ?? `${index + 1}`
+ );
+ const labelWidth = Math.min(
+ (outer.right - outer.left) * 0.3,
+ Math.max(1, ...categories.map((label) => label.length)) *
+ font *
+ CHARACTER_WIDTH +
+ 6 * zoom
+ );
+ const left = outer.left + labelWidth;
+ const width = outer.right - left;
+ const totals = categories.map((_, index) =>
+ plot.series.reduce(
+ (sum, series) => sum + Math.max(0, series.values[index] ?? 0),
+ 0
+ )
+ );
+ const largest = Math.max(0, ...totals);
+ if (width < 20 || !largest) return;
+ const band = (outer.bottom - outer.top) / count;
+ const height =
+ band / (1 + (plot.gapWidth ?? DEFAULT_GAP_WIDTHS.funnel ?? 0) / 100);
+ const middle = left + width / 2;
+ categories.forEach((category, index) => {
+ const y = outer.top + band * index + (band - height) / 2;
+ shapes.push({
+ type: 'text',
+ x: left - 4 * zoom,
+ y: y + height / 2,
+ text: truncate(category, labelWidth - 6 * zoom, font),
+ anchor: 'end',
+ size: font,
+ role: 'label',
+ baseline: 'middle',
+ });
+ let x = middle - ((totals[index] / largest) * width) / 2;
+ for (const series of plot.series) {
+ const value = series.values[index];
+ if (value === null || value === undefined || value <= 0) continue;
+ const piece = (value / largest) * width;
+ const text = valueText(series.sample)(value);
+ shapes.push({
+ type: 'rect',
+ x,
+ y,
+ width: piece,
+ height,
+ fill: series.color,
+ tip: `${plot.series.length > 1 ? `${series.name} · ` : ''}${category}: ${text}`,
+ });
+ if (plot.labels && fits(text, piece, font))
+ shapes.push({
+ type: 'text',
+ x: x + piece / 2,
+ y: y + height / 2,
+ text,
+ anchor: 'middle',
+ size: font,
+ role: 'inside',
+ baseline: 'middle',
+ });
+ x += piece;
+ }
+ });
+}
+
+/** A treemap's or sunburst's tree, from its first series. */
+export function chartTree(plot: ChartPlotData, data: ChartData) {
+ const series = plot.series[0];
+ return series
+ ? hierarchy(
+ data.paths ?? data.categories.map((category) => [category]),
+ series.values
+ )
+ : [];
+}
+
+/** The color of each top-level branch, from the palette in order. */
+const branchColor = (roots: HierarchyNode[], palette: string[]) => {
+ const colors = new Map(
+ roots.map((root, index) => [root, paletteColor(palette, index)])
+ );
+ return (root: HierarchyNode) => colors.get(root) ?? palette[0];
+};
+
+/**
+ * A treemap: rectangles in proportion to sizes, nested by level and colored
+ * by top-level branch. Parents are named over their children's top-left
+ * corner, in a banner above them, or not at all.
+ */
+export function treemapChart(
+ shapes: ChartShape[],
+ plot: ChartPlotData,
+ data: ChartData,
+ outer: Box,
+ font: number,
+ zoom: number
+) {
+ const roots = chartTree(plot, data);
+ const color = branchColor(roots, data.palette);
+ const format = valueText(plot.series[0]?.sample);
+ const banner = font * 1.6;
+ const leafLabels: ChartShape[] = [];
+ const parentLabels: ChartShape[] = [];
+ const place = (
+ nodes: HierarchyNode[],
+ rect: Rect,
+ path: string[],
+ root: HierarchyNode | undefined,
+ /** The corner a parent's name is written in, under `overlapping`. */
+ corner?: { x: number; y: number }
+ ) => {
+ const rects = squarify(
+ nodes.map((node) => node.value),
+ rect
+ );
+ nodes.forEach((node, index) => {
+ const at = rects[index];
+ const branch = root ?? node;
+ const names = [...path, node.name];
+ const tip = `${names.join(' › ')}: ${format(node.value)}`;
+ if (node.children.length) {
+ if (plot.parentLabels === 'banner' && at.height > banner * 2) {
+ shapes.push({
+ type: 'rect',
+ ...at,
+ height: banner,
+ fill: color(branch),
+ stroke: 'var(--color-surface)',
+ tip,
+ });
+ parentLabels.push({
+ type: 'text',
+ x: at.x + 4 * zoom,
+ y: at.y + banner / 2,
+ text: truncate(node.name, at.width - 8 * zoom, font),
+ anchor: 'start',
+ size: font,
+ role: 'inside',
+ baseline: 'middle',
+ bold: true,
+ });
+ place(
+ node.children,
+ { ...at, y: at.y + banner, height: at.height - banner },
+ names,
+ branch
+ );
+ return;
+ }
+ const named =
+ plot.parentLabels !== 'none' && fits(node.name, at.width, font);
+ place(
+ node.children,
+ at,
+ names,
+ branch,
+ named ? { x: at.x, y: at.y } : corner
+ );
+ if (named)
+ parentLabels.push({
+ type: 'text',
+ x: at.x + 4 * zoom,
+ y: at.y + 4 * zoom,
+ text: node.name,
+ anchor: 'start',
+ size: font * 1.15,
+ role: 'inside',
+ baseline: 'hanging',
+ bold: true,
+ });
+ return;
+ }
+ shapes.push({
+ type: 'rect',
+ ...at,
+ fill: color(branch),
+ stroke: 'var(--color-surface)',
+ tip,
+ });
+ // A leaf in the corner a parent is named in writes its name below.
+ const shifted =
+ !!corner &&
+ Math.abs(at.x - corner.x) < 0.5 &&
+ Math.abs(at.y - corner.y) < 0.5;
+ const top = at.y + 4 * zoom + (shifted ? font * 1.5 : 0);
+ if (top + font <= at.y + at.height && fits(node.name, at.width, font))
+ leafLabels.push({
+ type: 'text',
+ x: at.x + 4 * zoom,
+ y: top,
+ text: node.name,
+ anchor: 'start',
+ size: font,
+ role: 'inside',
+ baseline: 'hanging',
+ });
+ });
+ };
+ place(
+ roots,
+ {
+ x: outer.left,
+ y: outer.top,
+ width: outer.right - outer.left,
+ height: outer.bottom - outer.top,
+ },
+ [],
+ undefined
+ );
+ shapes.push(...leafLabels, ...parentLabels);
+}
+
+/**
+ * A sunburst: a ring per level from the center out, each arc as wide as its
+ * share of its parent, starting at twelve o'clock and colored by branch.
+ */
+export function sunburstChart(
+ shapes: ChartShape[],
+ plot: ChartPlotData,
+ data: ChartData,
+ outer: Box,
+ font: number
+) {
+ const roots = chartTree(plot, data);
+ const arcs = sunburst(roots);
+ if (!arcs.length) return;
+ const color = branchColor(roots, data.palette);
+ const format = valueText(plot.series[0]?.sample);
+ const levels = Math.max(...arcs.map((value) => value.depth)) + 1;
+ const radius =
+ Math.min(outer.right - outer.left, outer.bottom - outer.top) / 2;
+ // An empty center half a ring wide, as Excel leaves one.
+ const ring = radius / (levels + 0.5);
+ const center: [number, number] = [
+ (outer.left + outer.right) / 2,
+ (outer.top + outer.bottom) / 2,
+ ];
+ // Each arc's names from its root, parents coming before their children.
+ const names = new Map<HierarchyNode, string[]>();
+ for (const root of roots) names.set(root, [root.name]);
+ const shape = arc();
+ const labels: ChartShape[] = [];
+ for (const value of arcs) {
+ const path = names.get(value.node) ?? [value.node.name];
+ for (const child of value.node.children)
+ names.set(child, [...path, child.name]);
+ const inner = ring / 2 + value.depth * ring;
+ const geometry = {
+ innerRadius: inner,
+ outerRadius: inner + ring,
+ startAngle: value.start,
+ endAngle: value.end,
+ };
+ const d = shape(geometry);
+ if (!d) continue;
+ shapes.push({
+ type: 'path',
+ d,
+ translate: center,
+ fill: color(value.root),
+ stroke: 'var(--color-surface)',
+ strokeWidth: 1,
+ tip: `${path.join(' › ')}: ${format(value.node.value)}`,
+ });
+ const length = (value.end - value.start) * (inner + ring / 2);
+ const text = value.node.name;
+ if (ring >= font * 1.4 && fits(text, length, font * 0.9)) {
+ const [x, y] = shape.centroid(geometry);
+ labels.push({
+ type: 'text',
+ x: center[0] + x,
+ y: center[1] + y,
+ text,
+ anchor: 'middle',
+ size: font * 0.9,
+ role: 'inside',
+ baseline: 'middle',
+ });
+ }
+ }
+ shapes.push(...labels);
+}
+
+/**
+ * A pie of pie or bar of pie: the split points gathered into one slice of
+ * the first pie, facing a smaller pie or a stacked bar that shows them, with
+ * lines joining the two.
+ */
+export function ofPieChart(
+ shapes: ChartShape[],
+ plot: ChartPlotData,
+ data: ChartData,
+ outer: Box
+) {
+ const series = plot.series[0];
+ const ofPie = plot.ofPie;
+ if (!series || !ofPie) return;
+ const values = series.values.map((value) => Math.max(0, value ?? 0));
+ const second = new Set(ofPieSecond(series.values, ofPie));
+ const total = values.reduce((sum, value) => sum + value, 0);
+ const share = (value: number) =>
+ `${Math.round((value / (total || 1)) * 1000) / 10}%`;
+ const color = (index: number) => paletteColor(data.palette, index);
+ const label = (index: number) => data.categories[index] ?? `${index + 1}`;
+ const main = values.flatMap((value, index) =>
+ second.has(index) ? [] : [{ value, index }]
+ );
+ const moved = values.flatMap((value, index) =>
+ second.has(index) ? [{ value, index }] : []
+ );
+ const other = moved.reduce((sum, entry) => sum + entry.value, 0);
+ const ratio = (ofPie.size ?? 75) / 100;
+ // The gap between the plots is 40% of the first pie's radius.
+ const width = outer.right - outer.left;
+ const height = outer.bottom - outer.top;
+ const radius = Math.max(0, Math.min(height / 2, width / (2.4 + 2 * ratio)));
+ const smaller = radius * ratio;
+ const span = 2.4 * radius + 2 * smaller;
+ const cy = (outer.top + outer.bottom) / 2;
+ const cx = outer.left + (width - span) / 2 + radius;
+ const cx2 = cx + 1.4 * radius + smaller;
+ const slices = [...main, { value: other, index: -1 }];
+ // The gathered slice faces the second plot, centered at three o'clock.
+ const sweep = total ? (2 * Math.PI * other) / total : 0;
+ const start = Math.PI / 2 + sweep / 2 - 2 * Math.PI;
+ const angles = pie<{ value: number; index: number }>()
+ .sort(null)
+ .value((entry) => entry.value)
+ .startAngle(start)
+ .endAngle(start + 2 * Math.PI)(slices);
+ const shape = arc<(typeof angles)[number]>()
+ .innerRadius(0)
+ .outerRadius(radius);
+ angles.forEach((slice) => {
+ const d = shape(slice);
+ if (!d || !slice.value) return;
+ const gathered = slice.data.index < 0;
+ shapes.push({
+ type: 'path',
+ d,
+ translate: [cx, cy],
+ fill: color(gathered ? values.length : slice.data.index),
+ stroke: 'var(--color-surface)',
+ strokeWidth: 1,
+ tip: `${gathered ? 'Other' : label(slice.data.index)}: ${share(slice.value)}`,
+ });
+ });
+ if (!other) return;
+ const edge = (angle: number): [number, number] => [
+ cx + radius * Math.sin(angle),
+ cy - radius * Math.cos(angle),
+ ];
+ const [upper, lower] = [Math.PI / 2 - sweep / 2, Math.PI / 2 + sweep / 2].map(
+ edge
+ );
+ let joins: [[number, number], [number, number]];
+ if (ofPie.type === 'bar') {
+ const barWidth = smaller * 0.8;
+ const x = cx2 - barWidth / 2;
+ let y = cy - smaller;
+ for (const entry of moved) {
+ const piece = (entry.value / other) * 2 * smaller;
+ shapes.push({
+ type: 'rect',
+ x,
+ y,
+ width: barWidth,
+ height: piece,
+ fill: color(entry.index),
+ stroke: 'var(--color-surface)',
+ tip: `${label(entry.index)}: ${share(entry.value)}`,
+ });
+ y += piece;
+ }
+ joins = [
+ [x, cy - smaller],
+ [x, cy + smaller],
+ ];
+ } else {
+ // The second pie's slices are centered at nine o'clock, facing the first.
+ const secondAngles = pie<{ value: number; index: number }>()
+ .sort(null)
+ .value((entry) => entry.value)
+ .startAngle(Math.PI / 2)
+ .endAngle(Math.PI / 2 + 2 * Math.PI)(moved);
+ const secondShape = arc<(typeof secondAngles)[number]>()
+ .innerRadius(0)
+ .outerRadius(smaller);
+ for (const slice of secondAngles) {
+ const d = secondShape(slice);
+ if (!d || !slice.value) continue;
+ shapes.push({
+ type: 'path',
+ d,
+ translate: [cx2, cy],
+ fill: color(slice.data.index),
+ stroke: 'var(--color-surface)',
+ strokeWidth: 1,
+ tip: `${label(slice.data.index)}: ${share(slice.value)}`,
+ });
+ }
+ joins = [
+ [cx2, cy - smaller],
+ [cx2, cy + smaller],
+ ];
+ }
+ for (const [from, to] of [
+ [upper, joins[0]],
+ [lower, joins[1]],
+ ])
+ shapes.push({
+ type: 'path',
+ d: `M${from[0]},${from[1]}L${to[0]},${to[1]}`,
+ stroke: 'var(--color-ink-muted)',
+ strokeWidth: 1,
+ });
+}
diff --git a/apps/web/src/features/block-spreadsheet/core/chart-axis-scenes.ts b/apps/web/src/features/block-spreadsheet/core/chart-axis-scenes.ts
new file mode 100644
index 0000000000..3d56c71d28
--- /dev/null
+++ b/apps/web/src/features/block-spreadsheet/core/chart-axis-scenes.ts
@@ -0,0 +1,449 @@
+import { scaleLinear } from 'd3-scale';
+import type { ChartData, ChartPlotData, ChartSeriesData } from './chart-data';
+import {
+ axisDomain,
+ type Box,
+ CHARACTER_WIDTH,
+ type ChartShape,
+ DEFAULT_GAP_WIDTHS,
+ type Scale,
+ tickFormat,
+ truncate,
+} from './chart-shapes';
+import {
+ binLabels,
+ boxStatistics,
+ histogramBins,
+ paretoOrder,
+ sumByCategory,
+ waterfallSteps,
+} from './chart-statistics';
+import { paletteColor } from './drawingml-colors';
+
+/** A value as its cells show it, to four decimals at most. */
+export const valueText = (sample: string | undefined) =>
+ tickFormat(sample, 1e-4);
+
+type Frame = {
+ scale: Scale;
+ /** Percent from 0 to 100% on the right, for a pareto line. */
+ percent: Scale;
+ center: (index: number) => number;
+ band: number;
+ box: Box;
+ /** Draws the line along zero, over the bars. */
+ axis: () => void;
+};
+
+/**
+ * A value axis with gridlines on the left, categories along the bottom and,
+ * if asked, percentages on the right. Undefined when no plot area is left.
+ */
+function frame(
+ shapes: ChartShape[],
+ outer: Box,
+ categories: string[],
+ values: number[],
+ options: {
+ font: number;
+ zoom: number;
+ sample?: string;
+ zero?: boolean;
+ percent?: boolean;
+ }
+): Frame | undefined {
+ const { font, zoom } = options;
+ const all = options.zero ? [...values, 0] : values;
+ const scale = scaleLinear()
+ .domain(
+ all.length ? axisDomain(Math.min(...all), Math.max(...all)) : [0, 1]
+ )
+ .nice(5);
+ const ticks = scale.ticks(5);
+ const format = tickFormat(
+ options.sample,
+ ticks.length > 1 ? ticks[1] - ticks[0] : 1
+ );
+ const percent = scaleLinear().domain([0, 1]);
+ const percentTicks = percent.ticks(5);
+ const percentFormat = tickFormat('0%', 0.2);
+ const widest = (texts: string[]) =>
+ Math.max(0, ...texts.map((text) => text.length)) * font * CHARACTER_WIDTH +
+ 6 * zoom;
+ const box = {
+ top: outer.top,
+ bottom: outer.bottom - font * 1.6,
+ left: outer.left + widest(ticks.map(format)),
+ right:
+ outer.right -
+ (options.percent ? widest(percentTicks.map(percentFormat)) : 0),
+ };
+ if (box.right - box.left < 20 || box.bottom - box.top < 20) return;
+ scale.range([box.bottom, box.top]);
+ percent.range([box.bottom, box.top]);
+ for (const tick of ticks) {
+ const y = scale(tick);
+ shapes.push({
+ type: 'line',
+ x1: box.left,
+ y1: y,
+ x2: box.right,
+ y2: y,
+ role: 'grid',
+ });
+ shapes.push({
+ type: 'text',
+ x: box.left - 4 * zoom,
+ y,
+ text: format(tick),
+ anchor: 'end',
+ size: font,
+ role: 'label',
+ baseline: 'middle',
+ });
+ }
+ if (options.percent)
+ for (const tick of percentTicks)
+ shapes.push({
+ type: 'text',
+ x: box.right + 4 * zoom,
+ y: percent(tick),
+ text: percentFormat(tick),
+ anchor: 'start',
+ size: font,
+ role: 'label',
+ baseline: 'middle',
+ });
+ const count = Math.max(1, categories.length);
+ const band = (box.right - box.left) / count;
+ const center = (index: number) => box.left + band * (index + 0.5);
+ const every = Math.max(
+ 1,
+ Math.ceil(
+ (Math.max(1, ...categories.map((label) => label.length)) *
+ font *
+ CHARACTER_WIDTH +
+ 4 * zoom) /
+ band
+ )
+ );
+ categories.forEach((label, index) => {
+ if (index % every) return;
+ shapes.push({
+ type: 'text',
+ x: center(index),
+ y: box.bottom + font * 1.2,
+ text: truncate(label, band * every - 2 * zoom, font),
+ anchor: 'middle',
+ size: font,
+ role: 'label',
+ });
+ });
+ const [low, high] = scale.domain();
+ const zero = scale(Math.max(low, Math.min(0, high)));
+ return {
+ scale,
+ percent,
+ center,
+ band,
+ box,
+ axis: () =>
+ shapes.push({
+ type: 'line',
+ x1: box.left,
+ y1: zero,
+ x2: box.right,
+ y2: zero,
+ role: 'axis',
+ }),
+ };
+}
+
+/** A bar from `from` to `to` in a category's band, `gap` percent apart. */
+function bar(
+ frame: Frame,
+ index: number,
+ from: number,
+ to: number,
+ gap: number
+) {
+ const width = frame.band / (1 + gap / 100);
+ const a = frame.scale(from);
+ const b = frame.scale(to);
+ return {
+ x: frame.center(index) - width / 2,
+ y: Math.min(a, b),
+ width,
+ height: Math.max(Math.abs(b - a), 0.5),
+ };
+}
+
+/** What a histogram or pareto chart counts: its bins, or its categories. */
+function histogramGroups(
+ plot: ChartPlotData,
+ series: ChartSeriesData,
+ categories: string[]
+): { labels: string[]; values: number[] } {
+ if (plot.aggregate) {
+ const sums = sumByCategory(
+ series.values.map((_, index) => categories[index] ?? ''),
+ series.values
+ );
+ return {
+ labels: sums.map((sum) => sum.name),
+ values: sums.map((sum) => sum.value),
+ };
+ }
+ const bins = histogramBins(
+ series.values.filter((value): value is number => value !== null),
+ plot.binning ?? {}
+ );
+ const width = bins.find((bin) => !bin.edge && bin.high > bin.low);
+ // Edges one digit finer than the bins are wide, as Excel labels them.
+ const format = tickFormat(
+ series.sample,
+ width ? (width.high - width.low) / 10 : 1
+ );
+ return {
+ labels: binLabels(bins, !!plot.binning?.closedLeft, format),
+ values: bins.map((bin) => bin.count),
+ };
+}
+
+/**
+ * A histogram: a bar per bin, touching, as tall as the values in it. A
+ * pareto chart sorts the bars largest first under a line of their running
+ * share of the total, on a percent axis.
+ */
+export function histogramChart(
+ shapes: ChartShape[],
+ plot: ChartPlotData,
+ data: ChartData,
+ box: Box,
+ font: number,
+ zoom: number
+) {
+ const series = plot.series[0];
+ if (!series) return;
+ const groups = histogramGroups(plot, series, data.categories);
+ const pareto = plot.kind === 'pareto';
+ const { order, cumulative } = paretoOrder(groups.values);
+ const shown = pareto ? order : order.map((_, index) => index);
+ const labels = shown.map((index) => groups.labels[index]);
+ // Sums read like their cells; bins count values.
+ const sample = plot.aggregate ? series.sample : undefined;
+ const area = frame(shapes, box, labels, groups.values, {
+ font,
+ zoom,
+ sample,
+ zero: true,
+ percent: pareto,
+ });
+ if (!area) return;
+ const gap = plot.gapWidth ?? DEFAULT_GAP_WIDTHS[plot.kind] ?? 0;
+ const format = valueText(sample);
+ shown.forEach((index, position) => {
+ const value = groups.values[index];
+ if (!value) return;
+ shapes.push({
+ type: 'rect',
+ ...bar(area, position, 0, value, gap),
+ fill: series.color,
+ // Touching bins stay apart, as Excel outlines them.
+ ...(gap === 0 && { stroke: 'var(--color-surface)' }),
+ tip: `${groups.labels[index]}: ${format(value)}`,
+ });
+ });
+ area.axis();
+ if (!pareto || !cumulative.length) return;
+ shapes.push({
+ type: 'path',
+ d: `M${cumulative
+ .map(
+ (share, position) => `${area.center(position)},${area.percent(share)}`
+ )
+ .join('L')}`,
+ stroke: paletteColor(data.palette, 1),
+ strokeWidth: 2 * zoom,
+ tip: 'Cumulative %',
+ });
+}
+
+/**
+ * A waterfall: each change floats from the running total, in the increase or
+ * decrease color, and totals stand on zero, joined by connector lines.
+ */
+export function waterfallChart(
+ shapes: ChartShape[],
+ plot: ChartPlotData,
+ data: ChartData,
+ box: Box,
+ font: number,
+ zoom: number
+) {
+ const series = plot.series[0];
+ if (!series) return;
+ const steps = waterfallSteps(series.values, plot.totals);
+ const count = Math.max(data.categories.length, steps.length);
+ const categories = Array.from(
+ { length: count },
+ (_, index) => data.categories[index] ?? `${index + 1}`
+ );
+ const area = frame(
+ shapes,
+ box,
+ categories,
+ steps.flatMap((step) => (step ? [step.from, step.to] : [])),
+ { font, zoom, sample: series.sample, zero: true }
+ );
+ if (!area) return;
+ const gap = plot.gapWidth ?? DEFAULT_GAP_WIDTHS.waterfall ?? 0;
+ const format = valueText(series.sample);
+ const colors = {
+ increase: data.palette[0],
+ decrease: paletteColor(data.palette, 1),
+ total: paletteColor(data.palette, 2),
+ };
+ let previous: { index: number; level: number } | undefined;
+ steps.forEach((step, index) => {
+ const raw = series.values[index];
+ if (!step || raw === null) return;
+ const rect = bar(area, index, step.from, step.to, gap);
+ if (previous && !plot.noConnectors) {
+ const before = bar(area, previous.index, 0, 0, gap);
+ const y = area.scale(previous.level);
+ shapes.push({
+ type: 'path',
+ d: `M${before.x + before.width},${y}H${rect.x}`,
+ stroke: 'var(--color-ink-muted)',
+ strokeWidth: zoom,
+ dash: `${3 * zoom} ${2 * zoom}`,
+ });
+ }
+ previous = { index, level: step.to };
+ shapes.push({
+ type: 'rect',
+ ...rect,
+ fill: colors[step.kind],
+ tip: `${categories[index]}: ${format(raw)}`,
+ });
+ if (!plot.labels) return;
+ // Outside the bar's end: above a rise, below a fall.
+ const below = step.kind === 'decrease' || step.to < 0;
+ shapes.push({
+ type: 'text',
+ x: rect.x + rect.width / 2,
+ y: below ? rect.y + rect.height + 2 * zoom : rect.y - 2 * zoom,
+ text: format(raw),
+ anchor: 'middle',
+ size: font * 0.9,
+ role: 'label',
+ baseline: below ? 'hanging' : 'auto',
+ });
+ });
+ area.axis();
+}
+
+/**
+ * A box and whisker chart: for each category, a box per series from its
+ * first to third quartile with the median across it, whiskers to the last
+ * values within 1.5 boxes, the mean marked, and outliers as markers.
+ */
+export function boxWhiskerChart(
+ shapes: ChartShape[],
+ plot: ChartPlotData,
+ data: ChartData,
+ box: Box,
+ font: number,
+ zoom: number
+) {
+ const groups = data.numbered ? [''] : [...new Set(data.categories)];
+ const values = plot.series.flatMap((series) =>
+ series.values.filter((value): value is number => value !== null)
+ );
+ const area = frame(shapes, box, groups, values, {
+ font,
+ zoom,
+ sample: plot.series.find((series) => series.sample)?.sample,
+ });
+ if (!area) return;
+ const method = plot.quartiles ?? 'exclusive';
+ const slot =
+ area.band /
+ (plot.series.length +
+ (plot.gapWidth ?? DEFAULT_GAP_WIDTHS.boxWhisker ?? 0) / 100);
+ plot.series.forEach((series, position) => {
+ const format = valueText(series.sample);
+ const means: [number, number][] = [];
+ groups.forEach((group, index) => {
+ const points = series.values.filter(
+ (value, point): value is number =>
+ value !== null &&
+ (data.numbered || (data.categories[point] ?? '') === group)
+ );
+ if (!points.length) return;
+ const stats = boxStatistics(points, method);
+ const left =
+ area.center(index) - (plot.series.length * slot) / 2 + position * slot;
+ const middle = left + slot / 2;
+ const y = area.scale;
+ const name = group ? `${series.name} · ${group}` : series.name;
+ const cap = slot / 4;
+ shapes.push({
+ type: 'path',
+ d: `M${middle},${y(stats.high)}V${y(stats.q3)}M${middle},${y(stats.q1)}V${y(stats.low)}M${middle - cap},${y(stats.high)}H${middle + cap}M${middle - cap},${y(stats.low)}H${middle + cap}`,
+ stroke: 'var(--color-ink-muted)',
+ strokeWidth: zoom,
+ });
+ shapes.push({
+ type: 'rect',
+ x: left,
+ y: y(stats.q3),
+ width: slot,
+ height: Math.max(y(stats.q1) - y(stats.q3), 0.5),
+ fill: series.color,
+ tip: `${name}: Q1 ${format(stats.q1)}, median ${format(stats.median)}, Q3 ${format(stats.q3)}`,
+ });
+ shapes.push({
+ type: 'path',
+ d: `M${left},${y(stats.median)}H${left + slot}`,
+ stroke: 'var(--color-surface)',
+ strokeWidth: 1.5 * zoom,
+ });
+ means.push([middle, y(stats.mean)]);
+ if (!plot.noMeanMarkers) {
+ const size = 3 * zoom;
+ const [x, at] = [middle, y(stats.mean)];
+ shapes.push({
+ type: 'path',
+ d: `M${x - size},${at - size}L${x + size},${at + size}M${x - size},${at + size}L${x + size},${at - size}`,
+ stroke: 'var(--color-surface)',
+ strokeWidth: 1.5 * zoom,
+ tip: `${name}: mean ${format(stats.mean)}`,
+ });
+ }
+ const markers = [
+ ...(plot.noOutliers ? [] : stats.outliers),
+ ...(plot.innerPoints ? stats.inner : []),
+ ];
+ for (const value of markers)
+ shapes.push({
+ type: 'circle',
+ x: middle,
+ y: y(value),
+ r: 2.5 * zoom,
+ fill: 'var(--color-surface)',
+ stroke: series.color,
+ tip: `${name}: ${format(value)}`,
+ });
+ });
+ if (plot.meanLine && means.length > 1)
+ shapes.push({
+ type: 'path',
+ d: `M${means.map(([x, at]) => `${x},${at}`).join('L')}`,
+ stroke: series.color,
+ strokeWidth: 1.5 * zoom,
+ tip: `${series.name} mean`,
+ });
+ });
+}
diff --git a/apps/web/src/features/block-spreadsheet/core/chart-builder.test.ts b/apps/web/src/features/block-spreadsheet/core/chart-builder.test.ts
index fe4f316884..374e59a726 100644
--- a/apps/web/src/features/block-spreadsheet/core/chart-builder.test.ts
+++ b/apps/web/src/features/block-spreadsheet/core/chart-builder.test.ts
@@ -311,3 +311,138 @@ describe('charts of cells', () => {
]);
});
});
+
+describe("Excel 2016's charts and pie of pie", () => {
+ const scores = sheet([['Score'], [52], [58], [61], [63], [67]]);
+ const defects = sheet([
+ ['Cause', 'Count'],
+ ['Scratches', 40],
+ ['Dents', 10],
+ ['Chips', 30],
+ ]);
+ const stores = sheet([
+ ['Region', 'Store', 'Sales'],
+ ['North', 'Downtown', 30],
+ [undefined, 'Airport', 20],
+ ['South', 'Harbor', 25],
+ ['West', undefined, 10],
+ ]);
+
+ it('bins a column of numbers, and sums labeled values by category', () => {
+ const range = { top: 0, left: 0, bottom: 5, right: 0 };
+ expect(
+ chartFromLayout(
+ 'histogram',
+ 'Data',
+ guessLayout(range, scores.value, 'histogram')
+ )
+ ).toEqual({
+ plots: [{ kind: 'histogram', series: [{ nameRef: 0, values: 1 }] }],
+ references: ["'Data'!$A$1", "'Data'!$A$2:$A$6"],
+ });
+ const labeled = { top: 0, left: 0, bottom: 3, right: 1 };
+ expect(
+ chartFromLayout(
+ 'pareto',
+ 'Data',
+ guessLayout(labeled, defects.value, 'pareto')
+ )?.plots
+ ).toEqual([
+ {
+ kind: 'pareto',
+ aggregate: true,
+ series: [{ nameRef: 0, categories: 1, values: 2 }],
+ },
+ ]);
+ });
+
+ it('labels waterfall and funnel bars, and legends the waterfall', () => {
+ const layout = guessLayout(
+ { top: 0, left: 0, bottom: 3, right: 1 },
+ defects.value,
+ 'waterfall'
+ );
+ expect(chartFromLayout('waterfall', 'Data', layout)).toMatchObject({
+ legend: 'top',
+ plots: [{ kind: 'waterfall', labels: true }],
+ });
+ expect(chartFromLayout('funnel', 'Data', layout)?.plots).toEqual([
+ {
+ kind: 'funnel',
+ labels: true,
+ series: [{ nameRef: 0, categories: 1, values: 2 }],
+ },
+ ]);
+ });
+
+ it('reads every column before the values as a level of a treemap or sunburst', () => {
+ const range = { top: 0, left: 0, bottom: 4, right: 2 };
+ const layout = guessLayout(range, stores.value, 'treemap');
+ expect(layout).toEqual({
+ range,
+ orientation: 'columns',
+ firstRow: true,
+ firstColumn: true,
+ });
+ const treemap = chartFromLayout('treemap', 'Data', layout);
+ expect(treemap).toEqual({
+ legend: 'right',
+ plots: [
+ {
+ kind: 'treemap',
+ series: [{ nameRef: 0, categories: 1, values: 2 }],
+ },
+ ],
+ references: ["'Data'!$C$1", "'Data'!$A$2:$B$5", "'Data'!$C$2:$C$5"],
+ });
+ // The chart's cells read back as the same block.
+ expect(treemap && chartLayout(treemap, 'Data')).toEqual({
+ sheet: 'Data',
+ layout,
+ });
+ expect(
+ chartFromLayout('sunburst', 'Data', layout)?.plots[0].series
+ ).toEqual([{ nameRef: 0, categories: 1, values: 2 }]);
+ });
+
+ it('switches among pie of pie, bar of pie and other types', () => {
+ const layout = guessLayout(
+ { top: 0, left: 0, bottom: 3, right: 1 },
+ defects.value
+ );
+ const ofPie = chartFromLayout('pie-of-pie', 'Data', layout);
+ expect(ofPie?.plots).toEqual([
+ {
+ kind: 'pie',
+ ofPie: { type: 'pie' },
+ series: [{ nameRef: 0, categories: 1, values: 2 }],
+ },
+ ]);
+ if (!ofPie) throw new Error('Expected a chart.');
+ expect(chartType(ofPie)).toBe('pie-of-pie');
+ const bar = withChartType(ofPie, 'bar-of-pie');
+ expect(bar && chartType(bar)).toBe('bar-of-pie');
+ const pie = withChartType(ofPie, 'pie');
+ expect(pie?.plots[0]).toEqual({
+ kind: 'pie',
+ series: [{ nameRef: 0, categories: 1, values: 2 }],
+ });
+ // A labeled column chart becomes a histogram of its categories.
+ const columns = chartFromLayout('column', 'Data', layout);
+ const histogram = columns && withChartType(columns, 'histogram');
+ expect(histogram?.plots).toEqual([
+ {
+ kind: 'histogram',
+ aggregate: true,
+ series: [{ nameRef: 0, categories: 1, values: 2 }],
+ },
+ ]);
+ expect(histogram && chartType(histogram)).toBe('histogram');
+ expect(
+ chartType({
+ plots: [{ kind: 'boxWhisker', quartiles: 'inclusive', series: [] }],
+ references: [],
+ })
+ ).toBe('box-whisker');
+ });
+});
diff --git a/apps/web/src/features/block-spreadsheet/core/chart-builder.ts b/apps/web/src/features/block-spreadsheet/core/chart-builder.ts
index 6bf0e27d9d..5256dc0df5 100644
--- a/apps/web/src/features/block-spreadsheet/core/chart-builder.ts
+++ b/apps/web/src/features/block-spreadsheet/core/chart-builder.ts
@@ -82,12 +82,40 @@ export const CHART_TYPES = [
{ id: 'bubble', label: 'Bubble', kind: 'bubble', more: true },
{ id: 'stock', label: 'Stock', kind: 'stock', more: true },
{ id: 'contour', label: 'Contour', kind: 'surface', more: true },
+ { id: 'histogram', label: 'Histogram', kind: 'histogram', more: true },
+ { id: 'pareto', label: 'Pareto', kind: 'pareto', catalog: true },
+ { id: 'waterfall', label: 'Waterfall', kind: 'waterfall', more: true },
+ { id: 'funnel', label: 'Funnel', kind: 'funnel', more: true },
+ {
+ id: 'box-whisker',
+ label: 'Box and whisker',
+ kind: 'boxWhisker',
+ more: true,
+ },
+ { id: 'treemap', label: 'Treemap', kind: 'treemap', more: true },
+ { id: 'sunburst', label: 'Sunburst', kind: 'sunburst', more: true },
+ {
+ id: 'pie-of-pie',
+ label: 'Pie of pie',
+ kind: 'pie',
+ ofPie: 'pie',
+ catalog: true,
+ },
+ {
+ id: 'bar-of-pie',
+ label: 'Bar of pie',
+ kind: 'pie',
+ ofPie: 'bar',
+ catalog: true,
+ },
] as const satisfies readonly {
id: string;
label: string;
kind: ChartKind;
grouping?: ChartGrouping;
filled?: true;
+ /** A pie with some points in a second pie or a bar. */
+ ofPie?: 'pie' | 'bar';
/** Columns plus a line on the secondary axis. */
combo?: true;
/**
@@ -106,14 +134,29 @@ const groupingOf = (type: ChartType) =>
'grouping' in type ? type.grouping : undefined;
const filledOf = (type: ChartType) => 'filled' in type && type.filled;
const comboOf = (type: ChartType) => 'combo' in type && type.combo;
+const ofPieOf = (type: ChartType) => ('ofPie' in type ? type.ofPie : undefined);
/** Kinds whose series all belong in one plot. */
const SINGLE_PLOT: readonly ChartKind[] = [
'radar',
'bubble',
'stock',
'surface',
+ 'funnel',
+ 'boxWhisker',
];
const isRound = (kind: ChartKind) => kind === 'pie' || kind === 'doughnut';
+/** Kinds that show one series, as Excel's do. */
+const ONE_SERIES: readonly ChartKind[] = [
+ 'pie',
+ 'doughnut',
+ 'histogram',
+ 'pareto',
+ 'waterfall',
+ 'treemap',
+ 'sunburst',
+];
+/** Kinds whose labels are levels, in every column before the values. */
+const isNested = (kind: ChartKind) => kind === 'treemap' || kind === 'sunburst';
/** Kinds that plot numbers on both axes. */
const isXy = (kind: ChartKind) => kind === 'scatter' || kind === 'bubble';
@@ -139,7 +182,8 @@ export function chartType(chart: SheetChart): ChartTypeId | undefined {
type.kind === plot?.kind &&
groupingOf(type) ===
(plot.grouping === 'clustered' ? undefined : plot.grouping) &&
- filledOf(type) === !!plot.filled
+ filledOf(type) === !!plot.filled &&
+ ofPieOf(type) === plot.ofPie?.type
)?.id;
}
@@ -283,10 +327,10 @@ export function guessLayout(
const dataRows = rows - (firstRow ? 1 : 0);
const dataColumns = columns - (firstColumn ? 1 : 0);
const orientation = dataRows >= dataColumns ? 'columns' : 'rows';
- // Scatter and bubble charts read x values from the first column (or
- // row) even when they are numbers, as Excel does.
const kind = type && definitionOf(type)?.kind;
- if (kind && isXy(kind)) {
+ // Scatter and bubble charts' x values, and a treemap's or sunburst's
+ // levels, come before the values even when they are numbers.
+ if (kind && (isXy(kind) || isNested(kind))) {
if (orientation === 'columns' && columns > 1) firstColumn = true;
if (orientation === 'rows' && rows > 1) firstRow = true;
}
@@ -307,6 +351,26 @@ function reference(sheet: string, area: CellBounds) {
return `${quote(sheet)}!${start === end ? start : `${start}:${end}`}`;
}
+/**
+ * Options a type sets as Excel's do: labeled values make a histogram of
+ * categories, waterfalls and funnels write their values, and a pie of pie
+ * or bar of pie names its second plot.
+ */
+function kindOptions(
+ type: ChartType,
+ series: ChartSeries[]
+): Partial<ChartPlot> {
+ const ofPie = ofPieOf(type);
+ if (ofPie) return { ofPie: { type: ofPie } };
+ if (type.kind === 'histogram' || type.kind === 'pareto')
+ return series.some((value) => value.categories !== undefined)
+ ? { aggregate: true }
+ : {};
+ if (type.kind === 'waterfall' || type.kind === 'funnel')
+ return { labels: true };
+ return {};
+}
+
/**
* A chart of a block of cells, or undefined when the block has no values
* beside its names and labels.
@@ -337,8 +401,7 @@ export function chartFromLayout(
const bubble = definition.kind === 'bubble';
const step = bubble && lines > 1 ? 2 : 1;
const count = Math.ceil(lines / step);
- // Pie and doughnut charts show one series.
- const shown = isRound(definition.kind) ? 1 : Math.min(count, 255);
+ const shown = ONE_SERIES.includes(definition.kind) ? 1 : Math.min(count, 255);
const colors = previous?.plots.flatMap((plot) =>
plot.series.map((value) => value.color)
);
@@ -357,7 +420,55 @@ export function chartFromLayout(
left: dataLeft,
right: range.right,
};
- for (let index = 0; index < shown; index++) {
+ // A treemap's or sunburst's levels are every line before its values.
+ const nested =
+ isNested(definition.kind) &&
+ (orientation === 'columns'
+ ? firstColumn && range.right > range.left
+ : firstRow && range.bottom > range.top);
+ if (nested) {
+ const columns = orientation === 'columns';
+ const last = columns ? range.right : range.bottom;
+ const name = columns
+ ? firstRow && {
+ top: range.top,
+ bottom: range.top,
+ left: last,
+ right: last,
+ }
+ : firstColumn && {
+ top: last,
+ bottom: last,
+ left: range.left,
+ right: range.left,
+ };
+ const color = colors?.[0];
+ series.push({
+ ...(name && { nameRef: add(name) }),
+ categories: add(
+ columns
+ ? {
+ top: dataTop,
+ bottom: range.bottom,
+ left: range.left,
+ right: last - 1,
+ }
+ : {
+ top: range.top,
+ bottom: last - 1,
+ left: dataLeft,
+ right: range.right,
+ }
+ ),
+ values: add(
+ columns
+ ? { top: dataTop, bottom: range.bottom, left: last, right: last }
+ : { top: last, bottom: last, left: dataLeft, right: range.right }
+ ),
+ ...(color && { color }),
+ });
+ }
+ for (let index = 0; !nested && index < shown; index++) {
const at = index * step;
const name =
orientation === 'columns'
@@ -405,10 +516,15 @@ export function chartFromLayout(
...(previous?.title && { title: previous.title }),
...(previous
? previous.legend && { legend: previous.legend }
- : (series.length > 1 ||
- isRound(definition.kind) ||
- definition.kind === 'surface' ||
- comboOf(definition)) && { legend: 'bottom' as const }),
+ : // A waterfall's legend names its colors; a treemap's, its branches.
+ definition.kind === 'waterfall'
+ ? { legend: 'top' as const }
+ : definition.kind === 'treemap'
+ ? { legend: 'right' as const }
+ : (series.length > 1 ||
+ isRound(definition.kind) ||
+ definition.kind === 'surface' ||
+ comboOf(definition)) && { legend: 'bottom' as const }),
references,
...(previous?.colors && { colors: previous.colors }),
};
@@ -432,6 +548,7 @@ export function chartFromLayout(
hiLow: true,
...(series.length === 4 && { upDown: true }),
}),
+ ...kindOptions(definition, series),
series,
};
return { ...shell, plots: [plot] };
@@ -530,29 +647,29 @@ export function withChartType(
],
};
}
- const flags = (count: number) => ({
+ const flags = (series: ChartSeries[]) => ({
...('grouping' in definition && { grouping: definition.grouping }),
...(filledOf(definition) && { filled: true as const }),
...(kind === 'stock' && {
hiLow: true as const,
- ...(count === 4 && { upDown: true as const }),
+ ...(series.length === 4 && { upDown: true as const }),
}),
+ ...kindOptions(definition, series),
});
- if (isRound(kind))
- return {
- ...chart,
- plots: [{ kind, ...flags(1), series: all.slice(0, 1) }],
- };
+ if (ONE_SERIES.includes(kind)) {
+ const first = all.slice(0, 1);
+ return { ...chart, plots: [{ kind, ...flags(first), series: first }] };
+ }
if (SINGLE_PLOT.includes(kind))
return {
...chart,
- plots: [{ kind, ...flags(all.length), series: all }],
+ plots: [{ kind, ...flags(all), series: all }],
};
return {
...chart,
plots: chart.plots.map((plot) => ({
kind,
- ...flags(plot.series.length),
+ ...flags(plot.series),
...(plot.secondary && { secondary: true }),
series: plot.series.map((series) => shown(series, plot.kind)),
})),
diff --git a/apps/web/src/features/block-spreadsheet/core/chart-data.ts b/apps/web/src/features/block-spreadsheet/core/chart-data.ts
index 3ededb83e8..a101a54c0f 100644
--- a/apps/web/src/features/block-spreadsheet/core/chart-data.ts
+++ b/apps/web/src/features/block-spreadsheet/core/chart-data.ts
@@ -1,7 +1,6 @@
import { cellPlainText } from '@macro-inc/spreadsheet/cell-mentions';
import {
- type ChartGrouping,
- type ChartKind,
+ type ChartPlot,
type ChartRange,
type ChartValue,
parseChartLiteral,
@@ -9,6 +8,7 @@ import {
type SheetChart,
} from '@macro-inc/spreadsheet/sheet-drawings';
import type { WorkbookCalculation } from './calculation';
+import { paletteColor } from './drawingml-colors';
import { formatCellAddress } from './spreadsheet-document';
import type { SpreadsheetWorkbookSheet } from './workbook-document';
@@ -33,13 +33,7 @@ export type ChartSeriesData = {
sample?: string;
};
-export type ChartPlotData = {
- kind: ChartKind;
- grouping?: ChartGrouping;
- secondary?: boolean;
- filled?: boolean;
- hiLow?: boolean;
- upDown?: boolean;
+export type ChartPlotData = Omit<ChartPlot, 'series'> & {
series: ChartSeriesData[];
};
@@ -47,6 +41,13 @@ export type ChartData = {
title?: string;
legend?: SheetChart['legend'];
categories: string[];
+ /**
+ * Each point's labels from the outermost level in, for treemaps and
+ * sunbursts whose labels span several columns.
+ */
+ paths?: string[][];
+ /** No cells label the points, so they are numbered 1, 2, 3. */
+ numbered?: true;
plots: ChartPlotData[];
/** Colors of pie and doughnut slices. */
palette: string[];
@@ -135,23 +136,47 @@ export function chartData(
const target = range(reference, names);
return target ? read(target)?.slice(0, MAX_CHART_POINTS) : undefined;
};
+ /**
+ * A block of labels as one list per point: its rows when it is at least as
+ * tall as it is wide, else its columns.
+ */
+ const levels = (index: number): string[][] => {
+ const cells = values(index) ?? [];
+ const reference = chart.references[index] ?? '';
+ const target = !parseChartLiteral(reference) && range(reference, names);
+ if (!target) return cells.map((value) => [value.text]);
+ const width = target.right - target.left + 1;
+ const height = target.bottom - target.top + 1;
+ const across = height >= width;
+ return Array.from({ length: across ? height : width }, (_, point) =>
+ Array.from(
+ { length: across ? width : height },
+ (_, level) =>
+ cells[across ? point * width + level : level * width + point]?.text ??
+ ''
+ )
+ );
+ };
const palette = chart.colors?.length ? chart.colors : DEFAULT_PALETTE;
let categories: string[] | undefined;
+ let paths: string[][] | undefined;
let count = 0;
- const plots = chart.plots.map((plot) => ({
- kind: plot.kind,
- ...(plot.grouping && { grouping: plot.grouping }),
- ...(plot.secondary && { secondary: true }),
- ...(plot.filled && { filled: true }),
- ...(plot.hiLow && { hiLow: true }),
- ...(plot.upDown && { upDown: true }),
- series: plot.series.map((series) => {
+ const plots = chart.plots.map(({ series: plotSeries, ...plot }) => ({
+ ...plot,
+ series: plotSeries.map((series) => {
const index = count++;
const points = values(series.values) ?? [];
const labels = values(series.categories);
// Scatter and bubble charts plot numbers on both axes.
const xy = plot.kind === 'scatter' || plot.kind === 'bubble';
- if (!xy && labels && !categories)
+ const nested = plot.kind === 'treemap' || plot.kind === 'sunburst';
+ if (nested && series.categories !== undefined && !paths) {
+ paths = levels(series.categories);
+ // A point is named by its innermost label.
+ categories = paths.map(
+ (path) => path.findLast((label) => label.trim()) ?? ''
+ );
+ } else if (!xy && labels && !categories)
categories = labels.map((value) => value.text);
// A pivot chart's series are named as its pivot table names them.
const name =
@@ -164,7 +189,7 @@ export function chartData(
`Series ${index + 1}`;
return {
name,
- color: series.color ?? palette[index % palette.length],
+ color: series.color ?? paletteColor(palette, index),
values: points.map((value) => value.number ?? null),
// Text among the x values numbers the points 1, 2, 3, as in Excel.
...(xy && {
@@ -201,6 +226,8 @@ export function chartData(
categories:
categories ??
Array.from({ length: longest }, (_, index) => `${index + 1}`),
+ ...(!categories && { numbered: true as const }),
+ ...(paths && { paths }),
plots,
palette,
};
diff --git a/apps/web/src/features/block-spreadsheet/core/chart-kinds-scene.test.ts b/apps/web/src/features/block-spreadsheet/core/chart-kinds-scene.test.ts
new file mode 100644
index 0000000000..7f5e734c32
--- /dev/null
+++ b/apps/web/src/features/block-spreadsheet/core/chart-kinds-scene.test.ts
@@ -0,0 +1,402 @@
+import { describe, expect, it } from 'vitest';
+import type { ChartData } from './chart-data';
+import { chartScene } from './chart-scene';
+import type { ChartShape } from './chart-shapes';
+
+const PALETTE = [
+ '#4472C4',
+ '#ED7D31',
+ '#A5A5A5',
+ '#FFC000',
+ '#5B9BD5',
+ '#70AD47',
+];
+
+const of = <Type extends ChartShape['type']>(
+ shapes: ChartShape[],
+ type: Type
+) =>
+ shapes.filter(
+ (shape): shape is Extract<ChartShape, { type: Type }> => shape.type === type
+ );
+const texts = (shapes: ChartShape[]) =>
+ of(shapes, 'text').map((shape) => shape.text);
+const tipped = (shapes: ChartShape[], tip: string) =>
+ shapes.find((shape) => 'tip' in shape && shape.tip === tip);
+/** The corners of a rectangle drawn as a rect or as a closed path. */
+function bounds(shape: ChartShape | undefined) {
+ if (shape?.type === 'rect')
+ return {
+ left: shape.x,
+ right: shape.x + shape.width,
+ top: shape.y,
+ bottom: shape.y + shape.height,
+ };
+ if (shape?.type !== 'path') throw new Error('not a rectangle');
+ const numbers = [...shape.d.matchAll(/-?\d+(?:\.\d+)?(?:e-?\d+)?/g)].map(
+ (found) => Number(found[0])
+ );
+ const xs = numbers.filter((_, index) => index % 2 === 0);
+ const ys = numbers.filter((_, index) => index % 2 === 1);
+ return {
+ left: Math.min(...xs),
+ right: Math.max(...xs),
+ top: Math.min(...ys),
+ bottom: Math.max(...ys),
+ };
+}
+
+const data = (
+ plot: ChartData['plots'][number],
+ categories: string[],
+ extra: Partial<ChartData> = {}
+): ChartData => ({ categories, plots: [plot], palette: PALETTE, ...extra });
+
+describe('histograms and pareto charts', () => {
+ it('draws touching bins labeled with their ranges', () => {
+ const { shapes } = chartScene(
+ data(
+ {
+ kind: 'histogram',
+ binning: { size: 5 },
+ series: [
+ {
+ name: 'Scores',
+ color: '#4472C4',
+ values: [1, 2, 5, 6, 10, 11, 20],
+ },
+ ],
+ },
+ []
+ ),
+ 480,
+ 288
+ );
+ expect(texts(shapes)).toEqual(
+ expect.arrayContaining(['[1, 6]', '(6, 11]', '(11, 16]', '(16, 21]'])
+ );
+ const first = bounds(tipped(shapes, '[1, 6]: 4'));
+ const second = bounds(tipped(shapes, '(6, 11]: 2'));
+ const last = bounds(tipped(shapes, '(16, 21]: 1'));
+ // No gap between bins; heights in proportion to counts.
+ expect(second.left).toBeCloseTo(first.right);
+ expect(first.bottom - first.top).toBeCloseTo(4 * (last.bottom - last.top));
+ expect(tipped(shapes, '(11, 16]: 0')).toBeUndefined();
+ });
+
+ it('sums by category when the histogram aggregates', () => {
+ const { shapes } = chartScene(
+ data(
+ {
+ kind: 'histogram',
+ aggregate: true,
+ series: [{ name: 'Sales', color: '#4472C4', values: [1, 2, 3] }],
+ },
+ ['North', 'South', 'North']
+ ),
+ 480,
+ 288
+ );
+ expect(tipped(shapes, 'North: 4')).toBeDefined();
+ expect(tipped(shapes, 'South: 2')).toBeDefined();
+ });
+
+ it('sorts pareto bars largest first under a cumulative percentage line', () => {
+ const { shapes } = chartScene(
+ data(
+ {
+ kind: 'pareto',
+ aggregate: true,
+ series: [
+ { name: 'Defects', color: '#4472C4', values: [10, 40, 30, 20] },
+ ],
+ },
+ ['Dents', 'Scratches', 'Chips', 'Cracks']
+ ),
+ 480,
+ 288
+ );
+ const bars = ['Scratches: 40', 'Chips: 30', 'Cracks: 20', 'Dents: 10'].map(
+ (tip) => bounds(tipped(shapes, tip))
+ );
+ for (let index = 1; index < bars.length; index++)
+ expect(bars[index].left).toBeGreaterThan(bars[index - 1].left);
+ // The secondary axis runs to 100%, and the line ends there.
+ expect(texts(shapes)).toEqual(expect.arrayContaining(['0%', '100%']));
+ const line = of(shapes, 'path').find(
+ (shape) => shape.tip === 'Cumulative %'
+ );
+ const points = [...(line?.d ?? '').matchAll(/(-?[\d.]+),(-?[\d.]+)/g)].map(
+ (found) => Number(found[2])
+ );
+ expect(points).toHaveLength(4);
+ const top = Math.min(
+ ...bars.map((bar) => bar.top),
+ ...of(shapes, 'line').map((shape) => Math.min(shape.y1, shape.y2))
+ );
+ expect(points[3]).toBeCloseTo(top);
+ // 40% of the total is 40% of the way up.
+ const bottom = bars[0].bottom;
+ expect((bottom - points[0]) / (bottom - points[3])).toBeCloseTo(0.4);
+ });
+});
+
+describe('waterfall charts', () => {
+ const plot: ChartData['plots'][number] = {
+ kind: 'waterfall',
+ totals: [3],
+ labels: true,
+ series: [{ name: 'Cash', color: '#4472C4', values: [100, 30, -50, 80] }],
+ };
+
+ it('floats changes from the running total and stands totals on zero', () => {
+ const { shapes } = chartScene(
+ data(plot, ['Start', 'Sales', 'Costs', 'End'], { legend: 'bottom' }),
+ 480,
+ 288
+ );
+ const start = bounds(tipped(shapes, 'Start: 100'));
+ const sales = bounds(tipped(shapes, 'Sales: 30'));
+ const costs = bounds(tipped(shapes, 'Costs: -50'));
+ const end = bounds(tipped(shapes, 'End: 80'));
+ const unit = (start.bottom - start.top) / 100;
+ expect(sales.bottom).toBeCloseTo(start.top);
+ expect(sales.bottom - sales.top).toBeCloseTo(30 * unit);
+ expect(costs.top).toBeCloseTo(sales.top);
+ expect(costs.bottom - costs.top).toBeCloseTo(50 * unit);
+ expect(end.bottom).toBeCloseTo(start.bottom);
+ expect(end.top).toBeCloseTo(costs.bottom);
+ // Colors by direction, a legend of them, labels and connectors.
+ const fill = (tip: string) => {
+ const shape = tipped(shapes, tip);
+ return shape?.type === 'rect' ? shape.fill : undefined;
+ };
+ expect([fill('Sales: 30'), fill('Costs: -50'), fill('End: 80')]).toEqual(
+ PALETTE.slice(0, 3)
+ );
+ expect(texts(shapes)).toEqual(
+ expect.arrayContaining(['Increase', 'Decrease', 'Total', '-50', '80'])
+ );
+ expect(of(shapes, 'path').filter((shape) => shape.dash)).toHaveLength(3);
+ });
+
+ it('leaves out connectors when asked', () => {
+ const { shapes } = chartScene(
+ data({ ...plot, noConnectors: true }, ['A', 'B', 'C', 'D']),
+ 480,
+ 288
+ );
+ expect(of(shapes, 'path').filter((shape) => shape.dash)).toHaveLength(0);
+ });
+});
+
+describe('box and whisker charts', () => {
+ it('draws a box from quartile to quartile per category, with outliers', () => {
+ const values = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 40, 5, 6, 7];
+ const categories = [
+ ...Array.from({ length: 12 }, () => 'East'),
+ 'West',
+ 'West',
+ 'West',
+ ];
+ const { shapes } = chartScene(
+ data(
+ {
+ kind: 'boxWhisker',
+ series: [{ name: 'Times', color: '#4472C4', values }],
+ },
+ categories
+ ),
+ 480,
+ 288
+ );
+ const east = bounds(
+ tipped(shapes, 'Times · East: Q1 3.25, median 6.5, Q3 9.75')
+ );
+ const west = bounds(tipped(shapes, 'Times · West: Q1 5, median 6, Q3 7'));
+ expect(west.left).toBeGreaterThan(east.right);
+ // One outlier, 40, as a marker; the mean as a marker per box.
+ expect(
+ of(shapes, 'circle').filter((shape) => shape.tip === 'Times · East: 40')
+ ).toHaveLength(1);
+ expect(
+ of(shapes, 'path').filter((shape) => shape.tip?.includes('mean'))
+ ).toHaveLength(2);
+ expect(texts(shapes)).toEqual(expect.arrayContaining(['East', 'West']));
+ });
+});
+
+describe('funnel charts', () => {
+ it('centers bars as wide as their values, largest at the top', () => {
+ const { shapes } = chartScene(
+ data(
+ {
+ kind: 'funnel',
+ labels: true,
+ series: [{ name: 'Leads', color: '#4472C4', values: [400, 200, 50] }],
+ },
+ ['Visits', 'Trials', 'Sales']
+ ),
+ 480,
+ 288
+ );
+ const [visits, trials, sales] = [
+ 'Visits: 400',
+ 'Trials: 200',
+ 'Sales: 50',
+ ].map((tip) => bounds(tipped(shapes, tip)));
+ expect(trials.right - trials.left).toBeCloseTo(
+ (visits.right - visits.left) / 2
+ );
+ expect(sales.right - sales.left).toBeCloseTo(
+ (visits.right - visits.left) / 8
+ );
+ expect((trials.left + trials.right) / 2).toBeCloseTo(
+ (visits.left + visits.right) / 2
+ );
+ expect(visits.top).toBeLessThan(trials.top);
+ expect(texts(shapes)).toEqual(
+ expect.arrayContaining(['Visits', '400', '200', '50'])
+ );
+ });
+});
+
+describe('treemaps and sunbursts', () => {
+ const paths = [
+ ['Fruit', 'Apple'],
+ ['', 'Pear'],
+ ['Veg', 'Leek'],
+ ['Nuts', ''],
+ ];
+ const series = [{ name: 'Sales', color: '#4472C4', values: [3, 5, 2, 4] }];
+
+ it('tiles the plot area by size, colored by branch', () => {
+ const { shapes } = chartScene(
+ data({ kind: 'treemap', series }, ['Apple', 'Pear', 'Leek', 'Nuts'], {
+ paths,
+ legend: 'right',
+ }),
+ 480,
+ 288
+ );
+ const area = (tip: string) => {
+ const box = bounds(tipped(shapes, tip));
+ return (box.right - box.left) * (box.bottom - box.top);
+ };
+ expect(area('Fruit › Pear: 5') / area('Veg › Leek: 2')).toBeCloseTo(2.5);
+ expect(area('Nuts: 4') / area('Fruit › Apple: 3')).toBeCloseTo(4 / 3);
+ const fill = (tip: string) => {
+ const shape = tipped(shapes, tip);
+ return shape?.type === 'rect' ? shape.fill : undefined;
+ };
+ expect(fill('Fruit › Pear: 5')).toBe(fill('Fruit › Apple: 3'));
+ expect(fill('Fruit › Pear: 5')).not.toBe(fill('Veg › Leek: 2'));
+ // The legend lists branches; parents are written over their tiles.
+ expect(texts(shapes)).toEqual(
+ expect.arrayContaining(['Fruit', 'Nuts', 'Veg', 'Pear'])
+ );
+ });
+
+ it('gives banner labels a strip of their own', () => {
+ const banner = chartScene(
+ data(
+ { kind: 'treemap', parentLabels: 'banner', series },
+ ['Apple', 'Pear', 'Leek', 'Nuts'],
+ { paths }
+ ),
+ 480,
+ 288
+ ).shapes;
+ const strip = bounds(tipped(banner, 'Fruit: 8'));
+ const pear = bounds(tipped(banner, 'Fruit › Pear: 5'));
+ expect(pear.top).toBeGreaterThan(strip.top + 5);
+ });
+
+ it('rings each level around the one it belongs to', () => {
+ const { shapes } = chartScene(
+ data({ kind: 'sunburst', series }, ['Apple', 'Pear', 'Leek', 'Nuts'], {
+ paths,
+ }),
+ 480,
+ 288
+ );
+ const arcs = of(shapes, 'path');
+ expect(arcs.map((shape) => shape.tip)).toEqual([
+ 'Fruit: 8',
+ 'Fruit › Pear: 5',
+ 'Fruit › Apple: 3',
+ 'Nuts: 4',
+ 'Veg: 2',
+ 'Veg › Leek: 2',
+ ]);
+ // Arcs share the chart's center.
+ const centers = new Set(arcs.map((shape) => shape.translate?.join()));
+ expect(centers.size).toBe(1);
+ });
+});
+
+describe('pie of pie and bar of pie', () => {
+ const values = [40, 30, 12, 8, 6, 4];
+ const categories = ['A', 'B', 'C', 'D', 'E', 'F'];
+
+ it('gathers the split points into one slice and shows them beside it', () => {
+ const { shapes } = chartScene(
+ data(
+ {
+ kind: 'pie',
+ ofPie: { type: 'pie', split: 'position', splitAt: 3 },
+ series: [{ name: 'Share', color: '#4472C4', values }],
+ },
+ categories
+ ),
+ 480,
+ 288
+ );
+ const slices = of(shapes, 'path').filter((shape) => shape.translate);
+ expect(slices.map((shape) => shape.tip)).toEqual([
+ 'A: 40%',
+ 'B: 30%',
+ 'C: 12%',
+ 'Other: 18%',
+ 'D: 8%',
+ 'E: 6%',
+ 'F: 4%',
+ ]);
+ const [main, second] = [
+ ...new Set(slices.map((shape) => shape.translate?.join())),
+ ].map((center) => center?.split(',').map(Number) ?? []);
+ expect(second[0]).toBeGreaterThan(main[0]);
+ expect(second[1]).toBeCloseTo(main[1]);
+ // Past the six accents, Excel shades them: the gathered slice is the
+ // seventh color, a darker first accent, not the first again.
+ const fill = (tip: string) =>
+ slices.find((shape) => shape.tip === tip)?.fill;
+ expect(fill('Other: 18%')).toBe('#264478');
+ expect(fill('A: 40%')).toBe('#4472C4');
+ // Two lines join the gathered slice to the second pie.
+ expect(
+ of(shapes, 'path').filter((shape) => !shape.translate && shape.stroke)
+ ).toHaveLength(2);
+ });
+
+ it('stacks the split points in a bar', () => {
+ const { shapes } = chartScene(
+ data(
+ {
+ kind: 'pie',
+ ofPie: { type: 'bar', split: 'value', splitAt: 10 },
+ series: [{ name: 'Share', color: '#4472C4', values }],
+ },
+ categories
+ ),
+ 480,
+ 288
+ );
+ const [d, e, f] = ['D: 8%', 'E: 6%', 'F: 4%'].map((tip) =>
+ bounds(tipped(shapes, tip))
+ );
+ expect(e.top).toBeCloseTo(d.bottom);
+ expect(f.top).toBeCloseTo(e.bottom);
+ expect((d.bottom - d.top) / (f.bottom - f.top)).toBeCloseTo(2);
+ });
+});
diff --git a/apps/web/src/features/block-spreadsheet/core/chart-scene.test.ts b/apps/web/src/features/block-spreadsheet/core/chart-scene.test.ts
index 294acbb2b6..ffb99f7dbe 100644
--- a/apps/web/src/features/block-spreadsheet/core/chart-scene.test.ts
+++ b/apps/web/src/features/block-spreadsheet/core/chart-scene.test.ts
@@ -1,7 +1,8 @@
import type { SheetChart } from '@macro-inc/spreadsheet/sheet-drawings';
import { describe, expect, it } from 'vitest';
import { type ChartData, type ChartReader, chartData } from './chart-data';
-import { type ChartShape, chartScene } from './chart-scene';
+import { chartScene } from './chart-scene';
+import type { ChartShape } from './chart-shapes';
const months = ['Jan', 'Feb', 'Mar'];
const data = (plots: ChartData['plots'], extra: Partial<ChartData> = {}) => ({
diff --git a/apps/web/src/features/block-spreadsheet/core/chart-scene.ts b/apps/web/src/features/block-spreadsheet/core/chart-scene.ts
index 2a5c39d57c..66c821b099 100644
--- a/apps/web/src/features/block-spreadsheet/core/chart-scene.ts
+++ b/apps/web/src/features/block-spreadsheet/core/chart-scene.ts
@@ -1,83 +1,29 @@
import { scaleLinear } from 'd3-scale';
import { arc, pie } from 'd3-shape';
+import {
+ chartTree,
+ funnelChart,
+ ofPieChart,
+ sunburstChart,
+ treemapChart,
+} from './chart-area-scenes';
+import {
+ boxWhiskerChart,
+ histogramChart,
+ waterfallChart,
+} from './chart-axis-scenes';
import type { ChartData, ChartPlotData, ChartSeriesData } from './chart-data';
-
-/** Shapes a chart draws, in pixels within its box; the view only paints. */
-export type ChartShape =
- | {
- type: 'rect';
- x: number;
- y: number;
- width: number;
- height: number;
- fill: string;
- tip?: string;
- }
- | {
- type: 'path';
- d: string;
- /** Where the path's origin is drawn. */
- translate?: [number, number];
- fill?: string;
- stroke?: string;
- strokeWidth?: number;
- opacity?: number;
- tip?: string;
- }
- | {
- type: 'circle';
- x: number;
- y: number;
- r: number;
- fill: string;
- opacity?: number;
- stroke?: string;
- tip?: string;
- }
- | {
- type: 'line';
- x1: number;
- y1: number;
- x2: number;
- y2: number;
- /** Gridlines and axes use theme colors. */
- role: 'grid' | 'axis';
- }
- | {
- type: 'text';
- x: number;
- y: number;
- text: string;
- anchor: 'start' | 'middle' | 'end';
- size: number;
- role: 'title' | 'label';
- baseline?: 'middle' | 'hanging' | 'auto';
- };
-
-export type ChartScene = { shapes: ChartShape[] };
-
-const CHARACTER_WIDTH = 0.6;
-
-function truncate(text: string, width: number, size: number): string {
- const fits = Math.max(1, Math.floor(width / (size * CHARACTER_WIDTH)));
- return text.length > fits ? `${text.slice(0, Math.max(1, fits - 1))}…` : text;
-}
-
-/** Tick labels formatted like the series' cells: percentages, currency. */
-function tickFormat(sample: string | undefined, step: number) {
- const digits = step >= 1 ? 0 : Math.min(4, Math.ceil(-Math.log10(step)));
- const percent = !!sample?.trim().endsWith('%');
- const currency = /^-?\(?([$€£¥])/.exec(sample?.trim() ?? '')?.[1];
- const format = new Intl.NumberFormat('en-US', {
- maximumFractionDigits: percent ? Math.max(0, digits - 2) : digits,
- ...(percent && { style: 'percent' }),
- });
- return (value: number) => {
- const text = format.format(value);
- if (!currency) return text;
- return value < 0 ? `-${currency}${text.slice(1)}` : `${currency}${text}`;
- };
-}
+import {
+ axisDomain,
+ type Box,
+ CHARACTER_WIDTH,
+ type ChartScene,
+ type ChartShape,
+ type Scale,
+ tickFormat,
+ truncate,
+} from './chart-shapes';
+import { paletteColor } from './drawingml-colors';
/** The extent a value axis spans for the plots drawn on it. */
function extent(plots: ChartPlotData[], categories: number): [number, number] {
@@ -118,13 +64,7 @@ function extent(plots: ChartPlotData[], categories: number): [number, number] {
if (plot.kind === 'column' || plot.kind === 'bar' || plot.kind === 'area')
see(0);
}
- if (!Number.isFinite(low)) return [0, 1];
- // Like Excel, an axis starts at zero unless the values sit far from it.
- if (low > 0 && (high - low) / high >= 1 / 6) low = 0;
- if (high < 0 && (low - high) / low >= 1 / 6) high = 0;
- if (low === high)
- return low === 0 ? [0, 1] : [Math.min(0, low), Math.max(0, high)];
- return [low, high];
+ return axisDomain(low, high);
}
const sample = (plots: ChartPlotData[]) =>
@@ -165,32 +105,56 @@ export function chartScene(
);
const surface = data.plots.find((plot) => plot.kind === 'surface');
const bands = surface && surfaceBands(surface, data.palette);
- // Legend entries: slices of a pie, bands of a surface, otherwise series.
+ // Legend entries: slices of a pie, bands of a surface, branches of a
+ // tree, a waterfall's directions, otherwise series.
+ const first = data.plots[0];
+ const color = (index: number) => paletteColor(data.palette, index);
const entries = round
? data.categories.map((name, index) => ({
name,
- color: data.palette[index % data.palette.length],
+ color: color(index),
line: false,
}))
: bands
? bands.entries
- : data.plots.flatMap((plot) =>
- plot.series
- // Prices draw as high-low lines and bars, not as their series.
- .filter(
- (series) =>
- plot.kind !== 'stock' &&
- (!series.noFill || plot.kind === 'line')
- )
- .map((series) => ({
- name: series.name,
- color: series.color,
- line:
- plot.kind === 'line' ||
- plot.kind === 'scatter' ||
- (plot.kind === 'radar' && !plot.filled),
+ : first?.kind === 'treemap' || first?.kind === 'sunburst'
+ ? chartTree(first, data).map((root, index) => ({
+ name: root.name,
+ color: color(index),
+ line: false,
+ }))
+ : first?.kind === 'waterfall'
+ ? ['Increase', 'Decrease', 'Total'].map((name, index) => ({
+ name,
+ color: color(index),
+ line: false,
}))
- );
+ : first?.kind === 'pareto'
+ ? [
+ ...first.series.slice(0, 1).map((series) => ({
+ name: series.name,
+ color: series.color,
+ line: false,
+ })),
+ { name: 'Cumulative %', color: color(1), line: true },
+ ]
+ : data.plots.flatMap((plot) =>
+ plot.series
+ // Prices draw as high-low lines and bars, not as their series.
+ .filter(
+ (series) =>
+ plot.kind !== 'stock' &&
+ (!series.noFill || plot.kind === 'line')
+ )
+ .map((series) => ({
+ name: series.name,
+ color: series.color,
+ line:
+ plot.kind === 'line' ||
+ plot.kind === 'scatter' ||
+ (plot.kind === 'radar' && !plot.filled),
+ }))
+ );
if (data.legend && entries.length) {
const swatch = 8 * scale;
const row = font * 1.6;
@@ -265,8 +229,38 @@ export function chartScene(
}
}
if (right - left < 20 || bottom - top < 20) return { shapes };
+ const area = { top, bottom, left, right };
+ if (round?.ofPie) {
+ ofPieChart(shapes, round, data, area);
+ return { shapes };
+ }
if (round) {
- roundChart(shapes, round, data, { top, bottom, left, right });
+ roundChart(shapes, round, data, area);
+ return { shapes };
+ }
+ // Excel 2016's charts each fill the chart on their own.
+ if (first?.kind === 'histogram' || first?.kind === 'pareto') {
+ histogramChart(shapes, first, data, area, font, scale);
+ return { shapes };
+ }
+ if (first?.kind === 'waterfall') {
+ waterfallChart(shapes, first, data, area, font, scale);
+ return { shapes };
+ }
+ if (first?.kind === 'boxWhisker') {
+ boxWhiskerChart(shapes, first, data, area, font, scale);
+ return { shapes };
+ }
+ if (first?.kind === 'funnel') {
+ funnelChart(shapes, first, data, area, font, scale);
+ return { shapes };
+ }
+ if (first?.kind === 'treemap') {
+ treemapChart(shapes, first, data, area, font, scale);
+ return { shapes };
+ }
+ if (first?.kind === 'sunburst') {
+ sunburstChart(shapes, first, data, area, font);
return { shapes };
}
const radar = data.plots.filter((plot) => plot.kind === 'radar');
@@ -512,9 +506,6 @@ function legendSwatch(
);
}
-type Box = { top: number; bottom: number; left: number; right: number };
-type Scale = ReturnType<typeof scaleLinear<number, number>>;
-
/**
* How much of its category a value is in a 100% stack. Positive values share
* the positive total and negative values share the negative total, so each
@@ -904,7 +895,7 @@ function roundChart(
// Arcs are centered at the origin.
d,
translate: [cx, cy],
- fill: data.palette[index % data.palette.length],
+ fill: paletteColor(data.palette, index),
stroke: 'var(--color-surface)',
strokeWidth: 1,
tip: `${data.categories[index] ?? ''}: ${Math.round((slice.value / (total || 1)) * 1000) / 10}%`,
@@ -1102,7 +1093,7 @@ function surfaceBands(plot: ChartPlotData, palette: string[]) {
return {
entries: Array.from({ length: count }, (_, index) => ({
name: `${format(ticks[index])}–${format(ticks[index + 1] ?? ticks[index])}`,
- color: palette[index % palette.length],
+ color: paletteColor(palette, index),
line: false,
})),
band: (value: number) => {
diff --git a/apps/web/src/features/block-spreadsheet/core/chart-shapes.ts b/apps/web/src/features/block-spreadsheet/core/chart-shapes.ts
new file mode 100644
index 0000000000..65311f3f55
--- /dev/null
+++ b/apps/web/src/features/block-spreadsheet/core/chart-shapes.ts
@@ -0,0 +1,113 @@
+import type { ChartKind } from '@macro-inc/spreadsheet/sheet-drawings';
+import type { scaleLinear } from 'd3-scale';
+
+/** Shapes a chart draws, in pixels within its box; the view only paints. */
+export type ChartShape =
+ | {
+ type: 'rect';
+ x: number;
+ y: number;
+ width: number;
+ height: number;
+ fill: string;
+ /** An outline, such as the line between touching histogram bins. */
+ stroke?: string;
+ tip?: string;
+ }
+ | {
+ type: 'path';
+ d: string;
+ /** Where the path's origin is drawn. */
+ translate?: [number, number];
+ fill?: string;
+ stroke?: string;
+ strokeWidth?: number;
+ opacity?: number;
+ /** A dash pattern, in pixels. */
+ dash?: string;
+ tip?: string;
+ }
+ | {
+ type: 'circle';
+ x: number;
+ y: number;
+ r: number;
+ fill: string;
+ opacity?: number;
+ stroke?: string;
+ tip?: string;
+ }
+ | {
+ type: 'line';
+ x1: number;
+ y1: number;
+ x2: number;
+ y2: number;
+ /** Gridlines and axes use theme colors. */
+ role: 'grid' | 'axis';
+ }
+ | {
+ type: 'text';
+ x: number;
+ y: number;
+ text: string;
+ anchor: 'start' | 'middle' | 'end';
+ size: number;
+ /** `inside` text is written over a filled shape. */
+ role: 'title' | 'label' | 'inside';
+ baseline?: 'middle' | 'hanging' | 'auto';
+ bold?: boolean;
+ };
+
+export type ChartScene = { shapes: ChartShape[] };
+
+export const CHARACTER_WIDTH = 0.6;
+
+export function truncate(text: string, width: number, size: number): string {
+ const fits = Math.max(1, Math.floor(width / (size * CHARACTER_WIDTH)));
+ return text.length > fits ? `${text.slice(0, Math.max(1, fits - 1))}…` : text;
+}
+
+/** Tick labels formatted like the series' cells: percentages, currency. */
+export function tickFormat(sample: string | undefined, step: number) {
+ const digits = step >= 1 ? 0 : Math.min(4, Math.ceil(-Math.log10(step)));
+ const percent = !!sample?.trim().endsWith('%');
+ const currency = /^-?\(?([$€£¥])/.exec(sample?.trim() ?? '')?.[1];
+ const format = new Intl.NumberFormat('en-US', {
+ maximumFractionDigits: percent ? Math.max(0, digits - 2) : digits,
+ ...(percent && { style: 'percent' }),
+ });
+ return (value: number) => {
+ const text = format.format(value);
+ if (!currency) return text;
+ return value < 0 ? `-${currency}${text.slice(1)}` : `${currency}${text}`;
+ };
+}
+
+export type Box = { top: number; bottom: number; left: number; right: number };
+export type Scale = ReturnType<typeof scaleLinear<number, number>>;
+
+/**
+ * A value axis over values from `low` to `high`: from zero, as Excel starts
+ * one, unless the values sit far from it.
+ */
+export function axisDomain(low: number, high: number): [number, number] {
+ if (!Number.isFinite(low) || !Number.isFinite(high)) return [0, 1];
+ if (low > 0 && (high - low) / high >= 1 / 6) low = 0;
+ if (high < 0 && (low - high) / low >= 1 / 6) high = 0;
+ if (low === high)
+ return low === 0 ? [0, 1] : [Math.min(0, low), Math.max(0, high)];
+ return [low, high];
+}
+
+/**
+ * Excel's default gaps between the bars of its 2016 charts, in percent of a
+ * bar's width (a funnel's, of a bar's height).
+ */
+export const DEFAULT_GAP_WIDTHS: Partial<Record<ChartKind, number>> = {
+ histogram: 0,
+ pareto: 0,
+ waterfall: 50,
+ boxWhisker: 100,
+ funnel: 6,
+};
diff --git a/apps/web/src/features/block-spreadsheet/core/chart-statistics.test.ts b/apps/web/src/features/block-spreadsheet/core/chart-statistics.test.ts
new file mode 100644
index 0000000000..16eaccca57
--- /dev/null
+++ b/apps/web/src/features/block-spreadsheet/core/chart-statistics.test.ts
@@ -0,0 +1,266 @@
+import { describe, expect, it } from 'vitest';
+import {
+ binLabels,
+ boxStatistics,
+ hierarchy,
+ histogramBins,
+ ofPieSecond,
+ paretoOrder,
+ quartile,
+ squarify,
+ sumByCategory,
+ sunburst,
+ waterfallSteps,
+} from './chart-statistics';
+
+const plain = (value: number) => String(value);
+
+describe('histogram bins', () => {
+ it('uses bins of a width from the smallest value, each holding its upper edge', () => {
+ const bins = histogramBins([1, 2, 5, 6, 10, 11, 20], { size: 5 });
+ expect(bins).toEqual([
+ { low: 1, high: 6, count: 4 },
+ { low: 6, high: 11, count: 2 },
+ { low: 11, high: 16, count: 0 },
+ { low: 16, high: 21, count: 1 },
+ ]);
+ expect(binLabels(bins, false, plain)).toEqual([
+ '[1, 6]',
+ '(6, 11]',
+ '(11, 16]',
+ '(16, 21]',
+ ]);
+ });
+
+ it('holds lower edges when bins are closed on the left', () => {
+ const bins = histogramBins([1, 2, 5, 6, 10, 11, 20], {
+ size: 5,
+ closedLeft: true,
+ });
+ expect(bins.map((bin) => bin.count)).toEqual([3, 2, 1, 1]);
+ expect(binLabels(bins, true, plain)).toEqual([
+ '[1, 6)',
+ '[6, 11)',
+ '[11, 16)',
+ '[16, 21]',
+ ]);
+ });
+
+ it('splits the range into a number of bins, the last ending at the largest value', () => {
+ const bins = histogramBins([0, 0.1, 0.2, 0.3, 0.6, 0.9], { count: 3 });
+ // 0.3 is an edge: it belongs to the first bin, (0, 0.3].
+ expect(bins.map((bin) => bin.count)).toEqual([4, 1, 1]);
+ expect(bins[2].high).toBeCloseTo(0.9);
+ });
+
+ it('gathers values past the underflow and overflow edges', () => {
+ const bins = histogramBins([1, 3, 4, 5, 7, 9, 12, 30], {
+ size: 2,
+ underflow: 3,
+ overflow: 9,
+ });
+ expect(bins).toEqual([
+ { low: 3, high: 3, count: 2, edge: 'under' },
+ { low: 3, high: 5, count: 2 },
+ { low: 5, high: 7, count: 1 },
+ { low: 7, high: 9, count: 1 },
+ { low: 9, high: 9, count: 2, edge: 'over' },
+ ]);
+ expect(binLabels(bins, false, plain)).toEqual([
+ '≤3',
+ '(3, 5]',
+ '(5, 7]',
+ '(7, 9]',
+ '>9',
+ ]);
+ expect(
+ binLabels(
+ histogramBins([1, 3, 9, 12], {
+ size: 3,
+ underflow: 3,
+ overflow: 9,
+ closedLeft: true,
+ }),
+ true,
+ plain
+ )
+ ).toEqual(['<3', '[3, 6)', '[6, 9)', '≥9']);
+ });
+
+ it("sizes automatic bins by Scott's rule", () => {
+ // Sample standard deviation 2.138, so 3.5 × 2.138 / ∛8 = 3.742.
+ const values = [2, 4, 4, 4, 5, 5, 7, 9];
+ const bins = histogramBins(values, {});
+ expect(bins[0].low).toBe(2);
+ expect(bins[0].high - bins[0].low).toBeCloseTo(3.7417, 3);
+ expect(bins).toHaveLength(2);
+ expect(bins.map((bin) => bin.count)).toEqual([6, 2]);
+ });
+
+ it('widens bins to cover every value when there would be too many', () => {
+ const bins = histogramBins([0, 500_000, 1_000_000], { size: 1 });
+ expect(bins).toHaveLength(1_000);
+ expect(bins.at(-1)?.high).toBeCloseTo(1_000_000);
+ expect(bins.map((bin) => bin.count).filter(Boolean)).toEqual([1, 1, 1]);
+ });
+
+ it('puts equal values in one bin and draws nothing for no values', () => {
+ expect(histogramBins([4, 4, 4], {})).toEqual([
+ { low: 4, high: 4, count: 3 },
+ ]);
+ expect(histogramBins([], {})).toEqual([]);
+ });
+});
+
+describe('categories and pareto order', () => {
+ it('sums values by category in the order categories first appear', () => {
+ expect(
+ sumByCategory(['B', 'A', 'B', 'C', 'A'], [1, 2, 3, null, 4])
+ ).toEqual([
+ { name: 'B', value: 4 },
+ { name: 'A', value: 6 },
+ { name: 'C', value: 0 },
+ ]);
+ });
+
+ it('sorts largest first and accumulates percentages to 100%', () => {
+ expect(paretoOrder([10, 40, 30, 20])).toEqual({
+ order: [1, 2, 3, 0],
+ cumulative: [0.4, 0.7, 0.9, 1],
+ });
+ });
+});
+
+describe('quartiles and boxes', () => {
+ const values = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11];
+
+ it('computes exclusive and inclusive quartiles as QUARTILE.EXC and QUARTILE.INC', () => {
+ const sorted = [6, 7, 15, 36, 39, 40, 41, 42, 43, 47, 49];
+ expect(quartile(sorted, 0.25, 'exclusive')).toBe(15);
+ expect(quartile(sorted, 0.75, 'exclusive')).toBe(43);
+ expect(quartile(sorted, 0.25, 'inclusive')).toBe(25.5);
+ expect(quartile(sorted, 0.75, 'inclusive')).toBe(42.5);
+ expect(quartile([1, 2, 3, 4], 0.25, 'exclusive')).toBe(1.25);
+ expect(quartile([1, 2, 3, 4], 0.5, 'exclusive')).toBe(2.5);
+ });
+
+ it('ends whiskers at the last values within 1.5 boxes, past which are outliers', () => {
+ const box = boxStatistics([...values, 40, -30], 'exclusive');
+ expect(box.median).toBe(6);
+ expect(box.q1).toBe(2.5);
+ expect(box.q3).toBe(9.5);
+ expect(box.low).toBe(1);
+ expect(box.high).toBe(11);
+ expect(box.outliers).toEqual([-30, 40]);
+ expect(box.inner).toEqual(values);
+ expect(box.mean).toBeCloseTo((66 + 10) / 13);
+ });
+});
+
+describe('waterfall', () => {
+ it('floats changes from the running total and measures totals from zero', () => {
+ expect(waterfallSteps([100, 30, -50, 80, null, 20], [3])).toEqual([
+ { from: 0, to: 100, kind: 'increase' },
+ { from: 100, to: 130, kind: 'increase' },
+ { from: 130, to: 80, kind: 'decrease' },
+ { from: 0, to: 80, kind: 'total' },
+ undefined,
+ { from: 80, to: 100, kind: 'increase' },
+ ]);
+ });
+});
+
+describe('hierarchies', () => {
+ it('nests paths, continuing blank parents and ending at blank leaves', () => {
+ const tree = hierarchy(
+ [
+ ['Fruit', 'Apple'],
+ ['', 'Pear'],
+ ['Veg', 'Leek'],
+ ['Nuts', ''],
+ ],
+ [3, 5, 2, 4]
+ );
+ expect(tree).toEqual([
+ {
+ name: 'Fruit',
+ value: 8,
+ children: [
+ { name: 'Pear', value: 5, children: [], point: 1 },
+ { name: 'Apple', value: 3, children: [], point: 0 },
+ ],
+ },
+ { name: 'Nuts', value: 4, children: [], point: 3 },
+ {
+ name: 'Veg',
+ value: 2,
+ children: [{ name: 'Leek', value: 2, children: [], point: 2 }],
+ },
+ ]);
+ });
+
+ it('leaves out points without a positive size', () => {
+ expect(hierarchy([['A'], ['B'], ['C']], [0, -1, null])).toEqual([]);
+ });
+
+ it('squarifies areas in proportion to values', () => {
+ const rects = squarify([6, 6, 4, 3, 2, 2, 1], {
+ x: 0,
+ y: 0,
+ width: 6,
+ height: 4,
+ });
+ for (const [index, value] of [6, 6, 4, 3, 2, 2, 1].entries())
+ expect(rects[index].width * rects[index].height).toBeCloseTo(value);
+ // Every rectangle stays inside, and none is a sliver.
+ for (const rect of rects) {
+ expect(rect.x).toBeGreaterThanOrEqual(0);
+ expect(rect.y).toBeGreaterThanOrEqual(0);
+ expect(rect.x + rect.width).toBeLessThanOrEqual(6 + 1e-9);
+ expect(rect.y + rect.height).toBeLessThanOrEqual(4 + 1e-9);
+ expect(
+ Math.max(rect.width / rect.height, rect.height / rect.width)
+ ).toBeLessThan(3);
+ }
+ });
+
+ it('divides rings by value from twelve o’clock, clockwise', () => {
+ const tree = hierarchy(
+ [
+ ['A', 'x'],
+ ['A', 'y'],
+ ['B', ''],
+ ],
+ [1, 1, 2]
+ );
+ const arcs = sunburst(tree);
+ expect(
+ arcs.map(({ node, depth, start, end }) => [node.name, depth, start, end])
+ ).toEqual([
+ ['A', 0, 0, Math.PI],
+ ['x', 1, 0, Math.PI / 2],
+ ['y', 1, Math.PI / 2, Math.PI],
+ ['B', 0, Math.PI, 2 * Math.PI],
+ ]);
+ });
+});
+
+describe('pie of pie', () => {
+ const values = [40, 30, 12, 8, 6, 4];
+
+ it('moves points by position, value, percent or choice', () => {
+ expect(ofPieSecond(values, { type: 'pie' })).toEqual([4, 5]);
+ expect(
+ ofPieSecond(values, { type: 'pie', split: 'position', splitAt: 3 })
+ ).toEqual([3, 4, 5]);
+ expect(
+ ofPieSecond(values, { type: 'bar', split: 'value', splitAt: 10 })
+ ).toEqual([3, 4, 5]);
+ expect(
+ ofPieSecond(values, { type: 'bar', split: 'percent', splitAt: 7 })
+ ).toEqual([4, 5]);
+ expect(
+ ofPieSecond(values, { type: 'pie', split: 'custom', custom: [0, 9] })
+ ).toEqual([0]);
+ });
+});
diff --git a/apps/web/src/features/block-spreadsheet/core/chart-statistics.ts b/apps/web/src/features/block-spreadsheet/core/chart-statistics.ts
new file mode 100644
index 0000000000..8fb5f0a16f
--- /dev/null
+++ b/apps/web/src/features/block-spreadsheet/core/chart-statistics.ts
@@ -0,0 +1,429 @@
+import type {
+ ChartBinning,
+ ChartOfPie,
+} from '@macro-inc/spreadsheet/sheet-drawings';
+
+/**
+ * A histogram bin: values above `low` up to `high`, or the reverse when bins
+ * are closed on the left. Underflow and overflow bins gather the values past
+ * an edge.
+ */
+export type HistogramBin = {
+ low: number;
+ high: number;
+ count: number;
+ edge?: 'under' | 'over';
+};
+
+/** Bins at most, so a tiny width cannot make millions. */
+const MAX_BINS = 1_000;
+
+/** A quotient, snapped to a whole number when rounding put it just off one. */
+function steps(distance: number, width: number) {
+ const quotient = distance / width;
+ const whole = Math.round(quotient);
+ return Math.abs(quotient - whole) < 1e-9 * Math.max(1, Math.abs(quotient))
+ ? whole
+ : quotient;
+}
+
+function sampleDeviation(values: number[]) {
+ if (values.length < 2) return 0;
+ const mean = values.reduce((sum, value) => sum + value, 0) / values.length;
+ const squares = values.reduce((sum, value) => sum + (value - mean) ** 2, 0);
+ return Math.sqrt(squares / (values.length - 1));
+}
+
+/**
+ * Excel's histogram bins: from the smallest value (or the underflow edge),
+ * of the set width, into the set number, or as wide as Scott's normal
+ * reference rule, 3.5 standard deviations over the cube root of the count.
+ */
+export function histogramBins(
+ values: number[],
+ binning: ChartBinning
+): HistogramBin[] {
+ if (!values.length) return [];
+ const low = Math.min(...values);
+ const high = Math.max(...values);
+ const start = binning.underflow ?? low;
+ const end = Math.max(start, binning.overflow ?? high);
+ const chosen =
+ binning.size ??
+ (binning.count
+ ? (end - start) / binning.count
+ : (3.5 * sampleDeviation(values)) / Math.cbrt(values.length));
+ const needed =
+ !(chosen > 0) || end === start
+ ? 1
+ : (binning.count ?? Math.max(1, Math.ceil(steps(end - start, chosen))));
+ // Past the cap, wider bins still cover every value.
+ const count = Math.min(MAX_BINS, needed);
+ const width = needed > MAX_BINS ? (end - start) / MAX_BINS : chosen;
+ const bins: HistogramBin[] = Array.from({ length: count }, (_, index) => ({
+ low: start + index * (width > 0 ? width : 0),
+ high:
+ (binning.count || needed > MAX_BINS) && index === count - 1
+ ? end
+ : width > 0
+ ? start + (index + 1) * width
+ : end,
+ count: 0,
+ }));
+ const under: HistogramBin | undefined =
+ binning.underflow === undefined
+ ? undefined
+ : { low: start, high: start, count: 0, edge: 'under' };
+ const over: HistogramBin | undefined =
+ binning.overflow === undefined
+ ? undefined
+ : { low: end, high: end, count: 0, edge: 'over' };
+ const left = !!binning.closedLeft;
+ for (const value of values) {
+ if (under && (left ? value < start : value <= start)) {
+ under.count++;
+ continue;
+ }
+ if (over && (left ? value >= end : value > end)) {
+ over.count++;
+ continue;
+ }
+ const at = width > 0 ? steps(value - start, width) : 0;
+ const index = left ? Math.floor(at) : Math.ceil(at) - 1;
+ bins[Math.max(0, Math.min(count - 1, index))].count++;
+ }
+ return [...(under ? [under] : []), ...bins, ...(over ? [over] : [])];
+}
+
+/** Bins labeled as Excel labels them: `[1, 6]`, `(6, 11]`, `≤3`, `>9`. */
+export function binLabels(
+ bins: HistogramBin[],
+ closedLeft: boolean,
+ format: (value: number) => string
+): string[] {
+ const regular = bins.filter((bin) => !bin.edge);
+ const first = regular[0];
+ const last = regular.at(-1);
+ const underflow = bins.some((bin) => bin.edge === 'under');
+ const overflow = bins.some((bin) => bin.edge === 'over');
+ return bins.map((bin) => {
+ if (bin.edge === 'under')
+ return `${closedLeft ? '<' : '≤'}${format(bin.high)}`;
+ if (bin.edge === 'over')
+ return `${closedLeft ? '≥' : '>'}${format(bin.low)}`;
+ const range = `${format(bin.low)}, ${format(bin.high)}`;
+ if (closedLeft)
+ return bin === last && !overflow ? `[${range}]` : `[${range})`;
+ return bin === first && !underflow ? `[${range}]` : `(${range}]`;
+ });
+}
+
+/** Values summed by category, in the order categories first appear. */
+export function sumByCategory(
+ categories: string[],
+ values: (number | null)[]
+): { name: string; value: number }[] {
+ const sums = new Map<string, number>();
+ categories.forEach((name, index) =>
+ sums.set(name, (sums.get(name) ?? 0) + (values[index] ?? 0))
+ );
+ return [...sums].map(([name, value]) => ({ name, value }));
+}
+
+/** A pareto chart's order, largest first, and its running share of the total. */
+export function paretoOrder(values: number[]): {
+ order: number[];
+ cumulative: number[];
+} {
+ const order = values
+ .map((_, index) => index)
+ .sort((a, b) => values[b] - values[a]);
+ const total = values.reduce((sum, value) => sum + Math.max(0, value), 0);
+ let running = 0;
+ const cumulative = order.map((index) => {
+ running += Math.max(0, values[index]);
+ return total ? running / total : 0;
+ });
+ return { order, cumulative };
+}
+
+/**
+ * A quartile of sorted values, interpolated as QUARTILE.INC, or as
+ * QUARTILE.EXC with ranks past either end held at that end.
+ */
+export function quartile(
+ sorted: number[],
+ share: number,
+ method: 'inclusive' | 'exclusive'
+): number {
+ const count = sorted.length;
+ if (!count) return Number.NaN;
+ const rank =
+ method === 'inclusive' ? (count - 1) * share : (count + 1) * share - 1;
+ if (rank <= 0) return sorted[0];
+ if (rank >= count - 1) return sorted[count - 1];
+ const below = Math.floor(rank);
+ return sorted[below] + (rank - below) * (sorted[below + 1] - sorted[below]);
+}
+
+export type BoxStatistics = {
+ q1: number;
+ median: number;
+ q3: number;
+ mean: number;
+ /** Whisker ends: the outermost values within 1.5 boxes of the box. */
+ low: number;
+ high: number;
+ outliers: number[];
+ /** Values within the whiskers. */
+ inner: number[];
+};
+
+/** A box and its whiskers, as Excel's box and whisker charts draw them. */
+export function boxStatistics(
+ values: number[],
+ method: 'inclusive' | 'exclusive'
+): BoxStatistics {
+ const sorted = [...values].sort((a, b) => a - b);
+ const q1 = quartile(sorted, 0.25, method);
+ const q3 = quartile(sorted, 0.75, method);
+ const reach = 1.5 * (q3 - q1);
+ const inner = sorted.filter(
+ (value) => value >= q1 - reach && value <= q3 + reach
+ );
+ return {
+ q1,
+ median: quartile(sorted, 0.5, method),
+ q3,
+ mean: sorted.reduce((sum, value) => sum + value, 0) / sorted.length,
+ low: inner[0] ?? q1,
+ high: inner.at(-1) ?? q3,
+ outliers: sorted.filter(
+ (value) => value < q1 - reach || value > q3 + reach
+ ),
+ inner,
+ };
+}
+
+export type WaterfallStep = {
+ from: number;
+ to: number;
+ kind: 'increase' | 'decrease' | 'total';
+};
+
+/**
+ * Each waterfall bar: a change floats from the running total; a total stands
+ * on zero at its own value, which the running total then continues from.
+ */
+export function waterfallSteps(
+ values: (number | null)[],
+ totals: number[] = []
+): (WaterfallStep | undefined)[] {
+ let running = 0;
+ return values.map((value, index) => {
+ if (value === null) return undefined;
+ if (totals.includes(index)) {
+ running = value;
+ return { from: 0, to: value, kind: 'total' };
+ }
+ const from = running;
+ running += value;
+ return { from, to: running, kind: value >= 0 ? 'increase' : 'decrease' };
+ });
+}
+
+export type HierarchyNode = {
+ name: string;
+ value: number;
+ children: HierarchyNode[];
+ /** The point a leaf draws. */
+ point?: number;
+};
+
+/**
+ * A tree of each point's path from its root, as treemaps and sunbursts read
+ * columns of labels: a blank label continues the row above when a deeper
+ * label follows, and otherwise ends the path there. Points without a
+ * positive size are left out. Siblings are largest first.
+ */
+export function hierarchy(
+ paths: string[][],
+ sizes: (number | null)[]
+): HierarchyNode[] {
+ const roots: HierarchyNode[] = [];
+ let previous: string[] = [];
+ paths.forEach((row, point) => {
+ const path: string[] = [];
+ for (let level = 0; level < row.length; level++) {
+ const label = row[level].trim();
+ if (label) path.push(label);
+ else if (row.slice(level + 1).some((deeper) => deeper.trim()))
+ path.push(previous[level] ?? '');
+ else break;
+ }
+ previous = path;
+ const size = sizes[point];
+ if (!path.length || size === null || size === undefined || !(size > 0))
+ return;
+ let siblings = roots;
+ path.forEach((name, depth) => {
+ let node = siblings.find((entry) => entry.name === name);
+ if (!node) {
+ node = { name, value: 0, children: [] };
+ siblings.push(node);
+ }
+ node.value += size;
+ if (depth === path.length - 1) node.point = point;
+ siblings = node.children;
+ });
+ });
+ const order = (nodes: HierarchyNode[]) => {
+ nodes.sort((a, b) => b.value - a.value);
+ for (const node of nodes) order(node.children);
+ };
+ order(roots);
+ return roots;
+}
+
+export type Rect = { x: number; y: number; width: number; height: number };
+
+/** The golden ratio d3 squarifies to. */
+const RATIO = (1 + Math.sqrt(5)) / 2;
+
+/**
+ * Rectangles of `rect` with areas in proportion to `values`, largest first,
+ * by the squarified treemap algorithm of Bruls, Huizing and van Wijk.
+ */
+export function squarify(values: number[], rect: Rect): Rect[] {
+ const placed: Rect[] = [];
+ let { x, y, width, height } = rect;
+ let remaining = values.reduce((sum, value) => sum + value, 0);
+ let start = 0;
+ while (start < values.length) {
+ let end = start;
+ let sum = values[end++];
+ let smallest = sum;
+ let largest = sum;
+ const alpha =
+ Math.max(height / width, width / height) / (remaining * RATIO);
+ let beta = sum * sum * alpha;
+ let worst = Math.max(largest / beta, beta / smallest);
+ for (; end < values.length; end++) {
+ const value = values[end];
+ const next = sum + value;
+ beta = next * next * alpha;
+ const ratio = Math.max(
+ Math.max(largest, value) / beta,
+ beta / Math.min(smallest, value)
+ );
+ if (ratio > worst) break;
+ sum = next;
+ smallest = Math.min(smallest, value);
+ largest = Math.max(largest, value);
+ worst = ratio;
+ }
+ const share = remaining ? sum / remaining : 1;
+ // A row along the shorter side, filling the rest of the rectangle's length.
+ if (width < height) {
+ const rowHeight = height * share;
+ let left = x;
+ for (let index = start; index < end; index++) {
+ const piece = sum ? (width * values[index]) / sum : 0;
+ placed.push({ x: left, y, width: piece, height: rowHeight });
+ left += piece;
+ }
+ y += rowHeight;
+ height -= rowHeight;
+ } else {
+ const rowWidth = width * share;
+ let top = y;
+ for (let index = start; index < end; index++) {
+ const piece = sum ? (height * values[index]) / sum : 0;
+ placed.push({ x, y: top, width: rowWidth, height: piece });
+ top += piece;
+ }
+ x += rowWidth;
+ width -= rowWidth;
+ }
+ remaining -= sum;
+ start = end;
+ }
+ return placed;
+}
+
+export type SunburstArc = {
+ node: HierarchyNode;
+ /** The top-level node the arc descends from. */
+ root: HierarchyNode;
+ depth: number;
+ /** Radians clockwise from twelve o'clock. */
+ start: number;
+ end: number;
+};
+
+/** A sunburst's arcs, parents before their children. */
+export function sunburst(roots: HierarchyNode[]): SunburstArc[] {
+ const arcs: SunburstArc[] = [];
+ const total = roots.reduce((sum, node) => sum + node.value, 0);
+ if (!total) return arcs;
+ const visit = (
+ nodes: HierarchyNode[],
+ depth: number,
+ start: number,
+ span: number,
+ sum: number,
+ root?: HierarchyNode
+ ) => {
+ let at = start;
+ for (const node of nodes) {
+ const sweep = (span * node.value) / sum;
+ arcs.push({
+ node,
+ root: root ?? node,
+ depth,
+ start: at,
+ end: at + sweep,
+ });
+ visit(node.children, depth + 1, at, sweep, node.value, root ?? node);
+ at += sweep;
+ }
+ };
+ visit(roots, 0, 0, 2 * Math.PI, total);
+ return arcs;
+}
+
+/**
+ * The points a pie of pie or bar of pie moves to its second plot. Without a
+ * split, Excel's automatic one moves the last third.
+ */
+export function ofPieSecond(
+ values: (number | null)[],
+ ofPie: ChartOfPie
+): number[] {
+ const count = values.length;
+ const indexes = values.map((_, index) => index);
+ if (ofPie.split === 'custom')
+ return indexes.filter((index) => ofPie.custom?.includes(index));
+ if (ofPie.split === 'value')
+ return indexes.filter(
+ (index) => (values[index] ?? 0) < (ofPie.splitAt ?? 0)
+ );
+ if (ofPie.split === 'percent') {
+ const total = values.reduce<number>(
+ (sum, value) => sum + Math.max(0, value ?? 0),
+ 0
+ );
+ return indexes.filter(
+ (index) =>
+ total > 0 &&
+ (Math.max(0, values[index] ?? 0) / total) * 100 < (ofPie.splitAt ?? 0)
+ );
+ }
+ const moved = Math.min(
+ Math.max(0, count - 1),
+ ofPie.split === 'position'
+ ? (ofPie.splitAt ?? 0)
+ : Math.max(1, Math.round(count / 3))
+ );
+ return indexes.slice(count - moved);
+}
diff --git a/apps/web/src/features/block-spreadsheet/core/drawingml-colors.ts b/apps/web/src/features/block-spreadsheet/core/drawingml-colors.ts
index 51787d64cd..d6d7b861b7 100644
--- a/apps/web/src/features/block-spreadsheet/core/drawingml-colors.ts
+++ b/apps/web/src/features/block-spreadsheet/core/drawingml-colors.ts
@@ -65,6 +65,36 @@ export function finishColor(color: PendingColor): string | undefined {
return `#${hex.toUpperCase()}`;
}
+/**
+ * Office's shades of the accents for the seventh color on, six at a time:
+ * darker, lighter, a little darker, lighter still, darkest.
+ */
+const PALETTE_SHADES: [string, number][][] = [
+ [],
+ [['lumMod', 60_000]],
+ [
+ ['lumMod', 80_000],
+ ['lumOff', 20_000],
+ ],
+ [['lumMod', 80_000]],
+ [
+ ['lumMod', 60_000],
+ ['lumOff', 40_000],
+ ],
+ [['lumMod', 50_000]],
+];
+
+/**
+ * The `index`th automatic color of a chart: the palette's colors in turn,
+ * then shades of them, as Excel colors series and points past the sixth.
+ */
+export function paletteColor(palette: string[], index: number): string {
+ const base = palette[index % palette.length];
+ const shade = PALETTE_SHADES[Math.floor(index / palette.length) % 6];
+ if (!shade.length || !/^#[0-9a-f]{6}$/i.test(base)) return base;
+ return finishColor({ hex: base.slice(1), modifiers: shade }) ?? base;
+}
+
/** Office's default theme colors, by `SCHEME_COLORS` index. */
export const DEFAULT_THEME = [
'FFFFFF',
diff --git a/apps/web/src/features/block-spreadsheet/core/xlsx-chart-values.ts b/apps/web/src/features/block-spreadsheet/core/xlsx-chart-values.ts
new file mode 100644
index 0000000000..e9720eb417
--- /dev/null
+++ b/apps/web/src/features/block-spreadsheet/core/xlsx-chart-values.ts
@@ -0,0 +1,22 @@
+import type { ChartValue } from '@macro-inc/spreadsheet/sheet-drawings';
+
+/** A cell a chart reads, with the Excel number format it displays with. */
+export type CellChartValue = ChartValue & { format?: string };
+export type ChartValues = (reference: string) => CellChartValue[] | undefined;
+
+export function xml(value: string) {
+ return value
+ .replace(/&/g, '&amp;')
+ .replace(/</g, '&lt;')
+ .replace(/>/g, '&gt;')
+ .replace(/"/g, '&quot;');
+}
+
+export const numberText = (value: number) =>
+ Number.isInteger(value)
+ ? String(value)
+ : String(Number(value.toPrecision(15)));
+
+/** The number format of the first number among values, as Excel caches it. */
+export const numberFormat = (values: CellChartValue[] | undefined) =>
+ values?.find((value) => value.number !== undefined)?.format || 'General';
diff --git a/apps/web/src/features/block-spreadsheet/core/xlsx-chartex.ts b/apps/web/src/features/block-spreadsheet/core/xlsx-chartex.ts
new file mode 100644
index 0000000000..1b013315fa
--- /dev/null
+++ b/apps/web/src/features/block-spreadsheet/core/xlsx-chartex.ts
@@ -0,0 +1,765 @@
+import {
+ type ChartBinning,
+ type ChartKind,
+ type ChartPlot,
+ type ChartSeries,
+ chartLiteral,
+ MAX_CHART_SOURCE_LENGTH,
+ parseChartLiteral,
+ parseChartReference,
+ type SheetChart,
+} from '@macro-inc/spreadsheet/sheet-drawings';
+import { match } from 'ts-pattern';
+import { DEFAULT_GAP_WIDTHS } from './chart-shapes';
+import {
+ finishColor,
+ type PendingColor,
+ resolveSchemeColors,
+ schemeColor,
+ themeAccents,
+} from './drawingml-colors';
+import {
+ type CellChartValue,
+ type ChartValues,
+ numberFormat,
+ numberText,
+ xml,
+} from './xlsx-chart-values';
+import { attributes, parse } from './xlsx-parts';
+
+/** Excel 2016's chart namespace, for histograms, waterfalls, treemaps... */
+export const CHARTEX =
+ 'http://schemas.microsoft.com/office/drawing/2014/chartex';
+export const CHARTEX_RELATIONSHIP =
+ 'http://schemas.microsoft.com/office/2014/relationships/chartEx';
+export const CHARTEX_CONTENT_TYPE = 'application/vnd.ms-office.chartex+xml';
+const DRAWING = 'http://schemas.openxmlformats.org/drawingml/2006/main';
+const RELATIONSHIPS =
+ 'http://schemas.openxmlformats.org/officeDocument/2006/relationships';
+
+/** Each kind's series layout, as chartEx parts name it. */
+const LAYOUTS = {
+ histogram: 'clusteredColumn',
+ pareto: 'clusteredColumn',
+ waterfall: 'waterfall',
+ funnel: 'funnel',
+ boxWhisker: 'boxWhisker',
+ treemap: 'treemap',
+ sunburst: 'sunburst',
+} as const satisfies Partial<Record<ChartKind, string>>;
+type ChartExKind = keyof typeof LAYOUTS;
+
+const isChartExKind = (kind: ChartKind): kind is ChartExKind => kind in LAYOUTS;
+
+/** Whether Excel saves a chart as a chartEx part. */
+export const isChartEx = (chart: SheetChart) =>
+ chart.plots.some((plot) => isChartExKind(plot.kind));
+
+/**
+ * The compatibility namespace a chartEx frame requires, as Excel writes it:
+ * funnels came in a later revision than the others.
+ */
+export function chartExRequirement(chart: SheetChart): {
+ prefix: string;
+ namespace: string;
+} {
+ return chart.plots.some((plot) => plot.kind === 'funnel')
+ ? {
+ prefix: 'cx2',
+ namespace:
+ 'http://schemas.microsoft.com/office/drawing/2015/10/21/chartex',
+ }
+ : {
+ prefix: 'cx1',
+ namespace:
+ 'http://schemas.microsoft.com/office/drawing/2015/9/8/chartex',
+ };
+}
+
+/** Whether chart part bytes are a chartEx part. */
+export const isChartExPart = (bytes: Uint8Array) =>
+ new TextDecoder().decode(bytes.subarray(0, 4_096)).includes(CHARTEX);
+
+/** The prefix a part gives a namespace, `''` when it is the default. */
+function namespacePrefix(source: string, uri: string): string | undefined {
+ const escaped = uri.replace(/[.]/g, '\\.');
+ const named = new RegExp(`xmlns:([A-Za-z_][\\w.-]*)="${escaped}"`).exec(
+ source
+ );
+ if (named) return `${named[1]}:`;
+ if (new RegExp(`xmlns="${escaped}"`).test(source)) return '';
+}
+
+const pattern = (prefix: string) => prefix.replace(/[.]/g, '\\.');
+
+/**
+ * The chartEx part as Macro keeps it for export: without cached values,
+ * which export writes again. Undefined when it refers to other parts or is
+ * too large.
+ */
+function chartExSource(
+ xml: string,
+ theme: (string | undefined)[]
+): string | undefined {
+ const prefix = namespacePrefix(xml, CHARTEX);
+ if (prefix === undefined) return;
+ const name = (local: string) => `${pattern(prefix)}${local}`;
+ let source = xml
+ .replace(/^<\?xml[^>]*>\s*/, '')
+ .replace(new RegExp(`<${name('lvl')}\\b[^>]*/>`, 'g'), '')
+ .replace(
+ new RegExp(`<${name('lvl')}\\b[^>]*>[\\s\\S]*?</${name('lvl')}>`, 'g'),
+ ''
+ )
+ .replace(new RegExp(`<${name('externalData')}\\b[^>]*/>`, 'g'), '')
+ .replace(
+ new RegExp(
+ `<${name('externalData')}\\b[^>]*>[\\s\\S]*?</${name('externalData')}>`,
+ 'g'
+ ),
+ ''
+ );
+ if (/\br:(?:id|embed|link)=/.test(source)) return;
+ const drawing = namespacePrefix(source, DRAWING);
+ if (drawing)
+ source = resolveSchemeColors(source, drawing.slice(0, -1), theme);
+ return source.length <= MAX_CHART_SOURCE_LENGTH ? source : undefined;
+}
+
+type PendingDimension = {
+ type: string;
+ numeric: boolean;
+ reference?: number;
+ /** Values cached in the first level, for data without a formula. */
+ cached: Map<number, string>;
+ count: number;
+ levels: number;
+};
+
+type PendingSeries = {
+ layout: string;
+ hidden: boolean;
+ dataId?: string;
+ nameRef?: number;
+ name?: string;
+ color?: string;
+ labels: boolean;
+ aggregate: boolean;
+ binning?: ChartBinning;
+ totals: number[];
+ visibility: Record<string, string>;
+ quartiles?: string;
+ parentLabels?: string;
+};
+
+const LEGENDS = {
+ r: 'right',
+ l: 'left',
+ t: 'top',
+ b: 'bottom',
+} as const;
+
+const finite = (text: string | undefined) => {
+ const value = Number(text);
+ return text !== undefined && text.trim() !== '' && Number.isFinite(value)
+ ? value
+ : undefined;
+};
+
+/**
+ * Read a chartEx part into what Macro draws, keeping the part for export.
+ * Undefined for kinds Macro does not draw, such as region maps, so the
+ * drawing's fallback is read instead.
+ */
+export function readChartEx(
+ bytes: Uint8Array,
+ path: string,
+ theme: (string | undefined)[],
+ warnings: Set<string>
+): SheetChart | undefined {
+ const references: string[] = [];
+ const data = new Map<string, PendingDimension[]>();
+ const series: PendingSeries[] = [];
+ const stack: string[] = [];
+ let dimensions: PendingDimension[] | undefined;
+ let dimension: PendingDimension | undefined;
+ let current: PendingSeries | undefined;
+ let text: string | undefined;
+ let point = 0;
+ let title: string | undefined;
+ let titleSeen = false;
+ // The chart's own title's depth in `stack`, not an axis title's.
+ let titleDepth: number | undefined;
+ let legend: SheetChart['legend'];
+ let gapWidth: number | undefined;
+ let literalData = false;
+ let color: PendingColor | undefined;
+ let colorDepth: number | undefined;
+ const inside = (local: string) => stack.includes(local);
+ const inTitle = () => titleDepth !== undefined;
+ parse(bytes, path, (parser) => {
+ parser.on('opentag', (node) => {
+ const value = attributes(node);
+ const parent = stack.at(-1);
+ stack.push(node.local);
+ if (node.uri === DRAWING) {
+ if (node.local === 't' && inTitle()) text = '';
+ else if (
+ current &&
+ colorDepth !== undefined &&
+ parent === 'solidFill'
+ ) {
+ if (node.local === 'srgbClr')
+ color = { hex: value.val, modifiers: [] };
+ else if (node.local === 'schemeClr')
+ color = { hex: schemeColor(theme, value.val ?? ''), modifiers: [] };
+ } else if (color && value.val !== undefined)
+ color.modifiers.push([node.local, Number(value.val)]);
+ return;
+ }
+ if (node.uri !== CHARTEX) return;
+ match(node.local)
+ .with('data', () => {
+ dimensions = [];
+ data.set(value.id ?? '', dimensions);
+ })
+ .with('numDim', 'strDim', (local) => {
+ dimension = {
+ type: value.type ?? '',
+ numeric: local === 'numDim',
+ cached: new Map(),
+ count: 0,
+ levels: 0,
+ };
+ dimensions?.push(dimension);
+ })
+ .with('lvl', () => {
+ if (dimension && !dimension.levels++)
+ dimension.count = Number(value.ptCount) || 0;
+ })
+ .with('pt', () => {
+ point = Number(value.idx) || 0;
+ if (dimension?.levels === 1) text = '';
+ })
+ .with('f', 'v', () => {
+ text = '';
+ })
+ .with('title', () => {
+ if (parent !== 'chart') return;
+ titleSeen = true;
+ titleDepth = stack.length;
+ })
+ .with('legend', () => {
+ legend = LEGENDS[value.pos as keyof typeof LEGENDS] ?? 'right';
+ })
+ .with('catScaling', () => {
+ const gap = finite(value.gapWidth);
+ if (gap !== undefined) gapWidth = Math.round(gap * 100);
+ })
+ .with('series', () => {
+ current = {
+ layout: value.layoutId ?? '',
+ hidden: value.hidden === '1' || value.hidden === 'true',
+ labels: false,
+ aggregate: false,
+ totals: [],
+ visibility: {},
+ };
+ })
+ .with('dataId', () => {
+ if (current) current.dataId = value.val;
+ })
+ .with('spPr', () => {
+ if (current && parent === 'series') colorDepth = stack.length;
+ })
+ .with('dataLabels', () => {
+ if (current) current.labels = true;
+ })
+ .with('visibility', () => {
+ if (!current) return;
+ if (parent === 'dataLabels') current.labels = value.value !== '0';
+ else current.visibility = value;
+ })
+ .with('aggregation', () => {
+ if (current) current.aggregate = true;
+ })
+ .with('binning', () => {
+ if (!current) return;
+ const underflow = finite(value.underflow);
+ const overflow = finite(value.overflow);
+ current.binning = {
+ ...(underflow !== undefined && { underflow }),
+ ...(overflow !== undefined && { overflow }),
+ ...(value.intervalClosed === 'l' && { closedLeft: true as const }),
+ };
+ })
+ .with('binSize', () => {
+ const size = finite(value.val);
+ if (current?.binning && size !== undefined && size > 0)
+ current.binning.size = size;
+ })
+ .with('binCount', () => {
+ const count = Number(value.val);
+ if (current?.binning && Number.isInteger(count) && count >= 1)
+ current.binning.count = Math.min(1_000, count);
+ })
+ .with('statistics', () => {
+ if (current) current.quartiles = value.quartileMethod;
+ })
+ .with('idx', () => {
+ const index = Number(value.val);
+ // Points a sheet can hold, as plots validate them.
+ if (
+ current &&
+ parent === 'subtotals' &&
+ Number.isInteger(index) &&
+ index >= 0 &&
+ index < 100_000 &&
+ current.totals.length < 100_000
+ )
+ current.totals.push(index);
+ })
+ .with('parentLabelLayout', () => {
+ if (current) current.parentLabels = value.val;
+ })
+ .otherwise(() => undefined);
+ });
+ parser.on('text', (chunk) => {
+ if (text !== undefined) text += chunk;
+ });
+ parser.on('closetag', (node) => {
+ stack.pop();
+ if (node.uri === DRAWING) {
+ if (node.local === 't' && text !== undefined) {
+ title = (title ?? '') + text;
+ text = undefined;
+ } else if (
+ color &&
+ (node.local === 'srgbClr' || node.local === 'schemeClr')
+ ) {
+ if (current && /^[0-9a-f]{6}$/i.test(color.hex ?? ''))
+ current.color ??= finishColor(color);
+ color = undefined;
+ }
+ return;
+ }
+ if (node.uri !== CHARTEX) return;
+ match(node.local)
+ .with('f', () => {
+ if (text === undefined) return;
+ references.push(text.trim());
+ const index = references.length - 1;
+ if (dimension) dimension.reference = index;
+ else if (current && inside('tx')) current.nameRef = index;
+ text = undefined;
+ })
+ .with('pt', () => {
+ if (dimension && text !== undefined)
+ dimension.cached.set(point, text);
+ text = undefined;
+ })
+ .with('v', () => {
+ if (text === undefined) return;
+ if (current && inside('tx')) current.name = text.trim();
+ else if (inTitle()) title ??= text;
+ text = undefined;
+ })
+ .with('numDim', 'strDim', () => {
+ // Data without a formula is kept as fixed values.
+ if (dimension && dimension.reference === undefined) {
+ literalData = true;
+ const length = Math.min(
+ 100_000,
+ Math.max(
+ dimension.count,
+ ...[...dimension.cached.keys()].map((index) => index + 1)
+ )
+ );
+ const values = Array.from({ length }, (_, index) => {
+ const cell = dimension?.cached.get(index) ?? '';
+ const number = finite(cell);
+ return number === undefined
+ ? { text: cell }
+ : { text: cell, number };
+ });
+ references.push(
+ chartLiteral(values, dimension.numeric ? 'number' : 'text')
+ );
+ dimension.reference = references.length - 1;
+ }
+ dimension = undefined;
+ })
+ .with('title', () => {
+ if (titleDepth !== undefined && stack.length < titleDepth)
+ titleDepth = undefined;
+ })
+ .with('spPr', () => {
+ if (colorDepth !== undefined && stack.length < colorDepth)
+ colorDepth = undefined;
+ })
+ .with('series', () => {
+ if (current) series.push(current);
+ current = undefined;
+ colorDepth = undefined;
+ })
+ .otherwise(() => undefined);
+ });
+ });
+ const shown = series.filter(
+ (value) => !value.hidden && value.layout !== 'paretoLine'
+ );
+ const first = shown[0];
+ const kind = first && kindOf(first.layout, series);
+ if (!first || !kind) {
+ warnings.add(
+ 'Some Excel 2016 charts, such as maps, are imported as the picture Excel saved for older versions.'
+ );
+ return;
+ }
+ const plotSeries: ChartSeries[] = shown.flatMap((value) => {
+ if (LAYOUTS[kind] !== value.layout) return [];
+ const dims = data.get(value.dataId ?? '0') ?? [];
+ const values = dims.find(
+ (dim) => dim.type === 'val' || dim.type === 'size'
+ )?.reference;
+ if (values === undefined) return [];
+ const categories = dims.find((dim) => dim.type === 'cat')?.reference;
+ return [
+ {
+ ...(value.name && { name: value.name }),
+ ...(value.nameRef !== undefined && { nameRef: value.nameRef }),
+ ...(categories !== undefined && { categories }),
+ values,
+ ...(value.color && { color: value.color }),
+ },
+ ];
+ });
+ const plot: ChartPlot = {
+ kind,
+ ...plotOptions(kind, first, gapWidth),
+ series: plotSeries,
+ };
+ if (titleSeen && title === undefined && plotSeries.length === 1)
+ title = plotSeries[0].name;
+ const kept = literalData
+ ? undefined
+ : chartExSource(new TextDecoder().decode(bytes), theme);
+ if (!kept)
+ warnings.add(
+ 'Some charts keep only their data and type; their formatting is not exported.'
+ );
+ const shownTitle = titleSeen ? title?.trim() : undefined;
+ return {
+ ...(shownTitle && { title: shownTitle }),
+ ...(legend && { legend }),
+ plots: [plot],
+ references,
+ colors: themeAccents(theme),
+ ...(kept && { source: kept }),
+ };
+}
+
+function kindOf(
+ layout: string,
+ series: PendingSeries[]
+): ChartExKind | undefined {
+ if (layout === 'clusteredColumn')
+ return series.some((value) => value.layout === 'paretoLine')
+ ? 'pareto'
+ : 'histogram';
+ return (Object.keys(LAYOUTS) as ChartExKind[]).find(
+ (kind) =>
+ kind !== 'histogram' && kind !== 'pareto' && LAYOUTS[kind] === layout
+ );
+}
+
+/** A chartEx series' layout options, as a plot keeps those its kind takes. */
+function plotOptions(
+ kind: ChartExKind,
+ series: PendingSeries,
+ gapWidth: number | undefined
+): Omit<ChartPlot, 'kind' | 'series'> {
+ const gap =
+ gapWidth !== undefined && gapWidth >= 0 && gapWidth <= 500
+ ? { gapWidth }
+ : {};
+ const visible = (key: string, fallback: boolean) =>
+ series.visibility[key] === undefined
+ ? fallback
+ : series.visibility[key] === '1' || series.visibility[key] === 'true';
+ return match(kind)
+ .with('histogram', 'pareto', () => ({
+ ...(series.aggregate
+ ? { aggregate: true as const }
+ : series.binning &&
+ Object.keys(series.binning).length && { binning: series.binning }),
+ ...gap,
+ }))
+ .with('waterfall', () => ({
+ ...(series.totals.length && { totals: series.totals }),
+ ...(!visible('connectorLines', true) && { noConnectors: true as const }),
+ ...(series.labels && { labels: true as const }),
+ ...gap,
+ }))
+ .with('funnel', () => ({
+ ...(series.labels && { labels: true as const }),
+ ...gap,
+ }))
+ .with('boxWhisker', () => ({
+ ...(series.quartiles === 'inclusive' && {
+ quartiles: 'inclusive' as const,
+ }),
+ ...(visible('meanLine', false) && { meanLine: true as const }),
+ ...(!visible('meanMarker', true) && { noMeanMarkers: true as const }),
+ ...(visible('nonoutliers', false) && { innerPoints: true as const }),
+ ...(!visible('outliers', true) && { noOutliers: true as const }),
+ ...gap,
+ }))
+ .with('treemap', () =>
+ match(series.parentLabels)
+ .with('banner', 'none', (parentLabels) => ({ parentLabels }))
+ .otherwise(() => ({}))
+ )
+ .with('sunburst', () => ({}))
+ .exhaustive();
+}
+
+// Export -------------------------------------------------------------------
+
+/**
+ * Cached levels of a data dimension: numbers in one level, or labels in a
+ * level per column (per row, for a wide block), innermost first.
+ */
+function levels(
+ reference: string,
+ numeric: boolean,
+ values: CellChartValue[] | undefined
+): string {
+ const cells = values ?? [];
+ const point = (value: CellChartValue, index: number) =>
+ numeric
+ ? value.number === undefined
+ ? ''
+ : `<cx:pt idx="${index}">${numberText(value.number)}</cx:pt>`
+ : value.text === ''
+ ? ''
+ : `<cx:pt idx="${index}">${xml(value.text)}</cx:pt>`;
+ if (numeric)
+ return `<cx:lvl ptCount="${cells.length}" formatCode="${xml(numberFormat(cells))}">${cells.map(point).join('')}</cx:lvl>`;
+ const range = parseChartReference(reference);
+ const width = range ? range.right - range.left + 1 : 1;
+ const height = range ? range.bottom - range.top + 1 : cells.length;
+ const across = height >= width;
+ const count = across ? height : width;
+ const depth = across ? width : height;
+ return Array.from({ length: depth }, (_, level) => depth - 1 - level)
+ .map((level) => {
+ const column = Array.from(
+ { length: count },
+ (_, index) =>
+ cells[across ? index * width + level : level * width + index] ?? {
+ text: '',
+ }
+ );
+ return `<cx:lvl ptCount="${count}">${column.map(point).join('')}</cx:lvl>`;
+ })
+ .join('');
+}
+
+/**
+ * The chartEx part Macro kept, with its references as they are now and
+ * caches of their current values. Undefined if it no longer matches them.
+ */
+function keptChartEx(
+ chart: SheetChart,
+ values: ChartValues
+): string | undefined {
+ const source = chart.source;
+ const prefix = source && namespacePrefix(source, CHARTEX);
+ if (!source || prefix === undefined) return;
+ const name = (local: string) => `${pattern(prefix)}${local}`;
+ const formulas = new RegExp(
+ `(<${name('f')}\\b[^>]*>)[\\s\\S]*?</${name('f')}>(\\s*<${name('v')}>[\\s\\S]*?</${name('v')}>)?`,
+ 'g'
+ );
+ if ((source.match(formulas) ?? []).length !== chart.references.length) return;
+ let index = 0;
+ let broken = false;
+ const written = source.replace(
+ formulas,
+ (
+ _,
+ open: string,
+ cachedName: string | undefined,
+ offset: number,
+ whole: string
+ ) => {
+ const reference = chart.references[index++];
+ if (parseChartLiteral(reference)) broken = true;
+ const read = values(reference);
+ const before = whole.slice(Math.max(0, offset - 200), offset);
+ const dimension = new RegExp(
+ `<${pattern(prefix)}(numDim|strDim)\\b[^>]*>\\s*$`
+ ).exec(before);
+ const formula = `${open}${xml(reference)}</${prefix}f>`;
+ if (dimension)
+ return `${formula}${levels(reference, dimension[1] === 'numDim', read).replaceAll('cx:', prefix)}`;
+ // A series name caches the text its cells show now.
+ if (cachedName === undefined) return formula;
+ const text = (read ?? [])
+ .map((value) => value.text.trim())
+ .filter(Boolean)
+ .join(' ');
+ return `${formula}<${prefix}v>${xml(text)}</${prefix}v>`;
+ }
+ );
+ if (broken) return;
+ return `<?xml version="1.0" encoding="UTF-8" standalone="yes"?>\n${written}`;
+}
+
+/** A data dimension's formula and cache, or fixed values without one. */
+function dimensionXml(
+ element: 'numDim' | 'strDim',
+ type: string,
+ reference: string,
+ values: ChartValues
+): string {
+ const literal = parseChartLiteral(reference);
+ if (literal)
+ return `<cx:${element} type="${type}">${levels('', element === 'numDim', literal)}</cx:${element}>`;
+ return `<cx:${element} type="${type}"><cx:f>${xml(reference)}</cx:f>${levels(reference, element === 'numDim', values(reference))}</cx:${element}>`;
+}
+
+/** A series' layout options, in the order the chartEx schema lists them. */
+function layoutXml(plot: ChartPlot): string {
+ const flag = (on: boolean | undefined) => (on ? '1' : '0');
+ const body = match(plot.kind)
+ .with('histogram', 'pareto', () => {
+ if (plot.aggregate) return '<cx:aggregation/>';
+ const binning = plot.binning ?? {};
+ const edges = `${binning.underflow === undefined ? '' : ` underflow="${numberText(binning.underflow)}"`}${binning.overflow === undefined ? '' : ` overflow="${numberText(binning.overflow)}"`}`;
+ const width =
+ binning.size !== undefined
+ ? `<cx:binSize val="${numberText(binning.size)}"/>`
+ : binning.count !== undefined
+ ? `<cx:binCount val="${binning.count}"/>`
+ : '';
+ return `<cx:binning intervalClosed="${binning.closedLeft ? 'l' : 'r'}"${edges}>${width}</cx:binning>`;
+ })
+ .with(
+ 'waterfall',
+ () =>
+ `<cx:visibility connectorLines="${flag(!plot.noConnectors)}"/>${
+ plot.totals?.length
+ ? `<cx:subtotals>${plot.totals.map((index) => `<cx:idx val="${index}"/>`).join('')}</cx:subtotals>`
+ : ''
+ }`
+ )
+ .with(
+ 'boxWhisker',
+ () =>
+ `<cx:visibility meanLine="${flag(plot.meanLine)}" meanMarker="${flag(!plot.noMeanMarkers)}" nonoutliers="${flag(plot.innerPoints)}" outliers="${flag(!plot.noOutliers)}"/><cx:statistics quartileMethod="${plot.quartiles ?? 'exclusive'}"/>`
+ )
+ .with(
+ 'treemap',
+ () =>
+ `<cx:parentLabelLayout val="${plot.parentLabels ?? 'overlapping'}"/>`
+ )
+ .otherwise(() => '');
+ return body ? `<cx:layoutPr>${body}</cx:layoutPr>` : '';
+}
+
+/** A chartEx part made from what Macro knows of the chart. */
+function generatedChartEx(chart: SheetChart, values: ChartValues): string {
+ const plot = chart.plots.find((value) => isChartExKind(value.kind));
+ if (!plot || !isChartExKind(plot.kind)) return '';
+ const kind = plot.kind;
+ // Histograms, pareto charts, waterfalls, treemaps and sunbursts show one
+ // series, as Excel's do.
+ const shown =
+ kind === 'funnel' || kind === 'boxWhisker'
+ ? plot.series
+ : plot.series.slice(0, 1);
+ const data = shown
+ .map((series, index) => {
+ const categories =
+ series.categories === undefined
+ ? ''
+ : dimensionXml(
+ 'strDim',
+ 'cat',
+ chart.references[series.categories],
+ values
+ );
+ const sized = kind === 'treemap' || kind === 'sunburst';
+ return `<cx:data id="${index}">${categories}${dimensionXml('numDim', sized ? 'size' : 'val', chart.references[series.values], values)}</cx:data>`;
+ })
+ .join('');
+ const pareto = kind === 'pareto';
+ const series = shown
+ .map((value, index) => {
+ const reference =
+ value.nameRef === undefined
+ ? undefined
+ : chart.references[value.nameRef];
+ const fixed =
+ reference === undefined
+ ? undefined
+ : parseChartLiteral(reference)
+ ?.map((item) => item.text.trim())
+ .filter(Boolean)
+ .join(' ');
+ const read =
+ reference === undefined || fixed !== undefined
+ ? undefined
+ : (values(reference) ?? [])
+ .map((item) => item.text.trim())
+ .filter(Boolean)
+ .join(' ');
+ const text = fixed ?? (read || value.name);
+ const name =
+ reference !== undefined && fixed === undefined
+ ? `<cx:tx><cx:txData><cx:f>${xml(reference)}</cx:f>${text ? `<cx:v>${xml(text)}</cx:v>` : ''}</cx:txData></cx:tx>`
+ : text
+ ? `<cx:tx><cx:txData><cx:v>${xml(text)}</cx:v></cx:txData></cx:tx>`
+ : '';
+ const fill = value.color
+ ? `<cx:spPr><a:solidFill><a:srgbClr val="${value.color.slice(1)}"/></a:solidFill></cx:spPr>`
+ : '';
+ const labels =
+ plot.labels && (kind === 'waterfall' || kind === 'funnel')
+ ? `<cx:dataLabels pos="${kind === 'funnel' ? 'ctr' : 'outEnd'}"><cx:visibility seriesName="0" categoryName="0" value="1"/></cx:dataLabels>`
+ : '';
+ return `<cx:series layoutId="${LAYOUTS[kind]}" uniqueId="{00000000-0000-4000-8000-${String(index + 1).padStart(12, '0')}}">${name}${fill}${labels}<cx:dataId val="${index}"/>${layoutXml(plot)}${pareto ? '<cx:axisId val="1"/>' : ''}</cx:series>`;
+ })
+ .join('');
+ const line = pareto
+ ? `<cx:series layoutId="paretoLine" ownerIdx="0" uniqueId="{00000000-0000-4000-8000-100000000001}"><cx:axisId val="2"/></cx:series>`
+ : '';
+ const gap = (plot.gapWidth ?? DEFAULT_GAP_WIDTHS[kind] ?? 0) / 100;
+ const categoryAxis = `<cx:axis id="0"><cx:catScaling gapWidth="${numberText(gap)}"/><cx:tickLabels/></cx:axis>`;
+ const axes = match(kind)
+ .with('treemap', 'sunburst', () => '')
+ .with('funnel', () => categoryAxis)
+ .otherwise(
+ () =>
+ `${categoryAxis}<cx:axis id="1"><cx:valScaling/><cx:majorGridlines/><cx:tickLabels/></cx:axis>${
+ pareto
+ ? '<cx:axis id="2"><cx:valScaling max="1" min="0"/><cx:units unit="percentage"/><cx:tickLabels/></cx:axis>'
+ : ''
+ }`
+ );
+ const title = chart.title
+ ? `<cx:title pos="t" align="ctr" overlay="0"><cx:tx><cx:txData><cx:v>${xml(chart.title)}</cx:v></cx:txData></cx:tx></cx:title>`
+ : '';
+ const legend = chart.legend
+ ? `<cx:legend pos="${chart.legend[0]}" align="ctr" overlay="0"/>`
+ : '';
+ return `<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
+<cx:chartSpace xmlns:a="${DRAWING}" xmlns:r="${RELATIONSHIPS}" xmlns:cx="${CHARTEX}"><cx:chartData>${data}</cx:chartData><cx:chart>${title}<cx:plotArea><cx:plotAreaRegion>${series}${line}</cx:plotAreaRegion>${axes}</cx:plotArea>${legend}</cx:chart></cx:chartSpace>`;
+}
+
+/** A chartEx part for export: the one imported when it still fits. */
+export function chartExPart(chart: SheetChart, values: ChartValues): string {
+ return keptChartEx(chart, values) ?? generatedChartEx(chart, values);
+}
diff --git a/apps/web/src/features/block-spreadsheet/core/xlsx-drawings.ts b/apps/web/src/features/block-spreadsheet/core/xlsx-drawings.ts
index b7b63b7ea7..418fd6f4a8 100644
--- a/apps/web/src/features/block-spreadsheet/core/xlsx-drawings.ts
+++ b/apps/web/src/features/block-spreadsheet/core/xlsx-drawings.ts
@@ -3,7 +3,6 @@ import {
type ChartKind,
type ChartPlot,
type ChartSeries,
- type ChartValue,
chartLiteral,
type DrawingPoint,
MAX_CHART_SOURCE_LENGTH,
@@ -16,6 +15,7 @@ import { match } from 'ts-pattern';
import {
finishColor,
type PendingColor,
+ paletteColor,
resolveSchemeColors,
schemeColor,
themeAccents,
@@ -27,6 +27,22 @@ import {
SPREADSHEET_MAX_ROWS,
} from './spreadsheet-document';
import type { XlsxArchive } from './xlsx-archive';
+import {
+ type CellChartValue,
+ type ChartValues,
+ numberFormat,
+ numberText,
+ xml,
+} from './xlsx-chart-values';
+import {
+ CHARTEX,
+ CHARTEX_RELATIONSHIP,
+ chartExPart,
+ chartExRequirement,
+ isChartEx,
+ isChartExPart,
+ readChartEx,
+} from './xlsx-chartex';
import { attributes, parse, relationships } from './xlsx-parts';
import {
diagramShape,
@@ -211,6 +227,33 @@ type PendingPlot = {
direction?: string;
};
+const SPLITS = {
+ pos: 'position',
+ val: 'value',
+ percent: 'percent',
+ cust: 'custom',
+} as const;
+
+/** An option of a pie of pie or bar of pie, onto its plot. */
+function readOfPie(plot: ChartPlot, local: string, value: string | undefined) {
+ if (local === 'ofPieType')
+ plot.ofPie = { ...plot.ofPie, type: value === 'bar' ? 'bar' : 'pie' };
+ const ofPie = plot.ofPie;
+ if (!ofPie) return;
+ const number = Number(value);
+ if (local === 'splitType') {
+ const split = SPLITS[value as keyof typeof SPLITS];
+ if (split) ofPie.split = split;
+ } else if (
+ local === 'splitPos' &&
+ value !== undefined &&
+ Number.isFinite(number)
+ )
+ ofPie.splitAt = number;
+ else if (local === 'secondPieSize' && number >= 5 && number <= 200)
+ ofPie.size = number;
+}
+
/** Read a chart part into what Macro draws, keeping the part for export. */
export function readChart(
archive: XlsxArchive,
@@ -220,6 +263,7 @@ export function readChart(
): SheetChart | undefined {
const bytes = archive.read(path);
if (!bytes) return;
+ if (isChartExPart(bytes)) return readChartEx(bytes, path, theme, warnings);
const references: string[] = [];
const plots: PendingPlot[] = [];
const rightAxes = new Set<string>();
@@ -314,6 +358,16 @@ export function readChart(
: undefined;
else if (node.local === 'axId') plot.axes.push(value.val ?? '');
else if (node.local === 'ser') series = { values: -1 };
+ else if (plot.local === 'ofPieChart')
+ readOfPie(plot.plot, node.local, value.val);
+ } else if (
+ plot?.local === 'ofPieChart' &&
+ node.local === 'secondPiePt' &&
+ parent === 'custSplit'
+ ) {
+ const index = Number(value.val);
+ if (plot.plot.ofPie && Number.isInteger(index) && index >= 0)
+ plot.plot.ofPie.custom = [...(plot.plot.ofPie.custom ?? []), index];
} else if (
parent === 'plotArea' &&
(node.local === 'valAx' ||
@@ -422,6 +476,15 @@ export function readChart(
seriesColorDepth = undefined;
} else if (plot && node.local === plot.local) {
if (plot.direction === 'bar') plot.plot.kind = 'bar';
+ // A position counts whole points.
+ const ofPie = plot.plot.ofPie;
+ if (ofPie?.split === 'position' && ofPie.splitAt !== undefined)
+ ofPie.splitAt = Math.min(
+ 99_999,
+ Math.max(0, Math.round(ofPie.splitAt))
+ );
+ if (ofPie?.custom)
+ ofPie.custom = ofPie.custom.filter((index) => index < 100_000);
plots.push(plot);
plot = undefined;
} else if (axis && parent === 'plotArea' && node.local.endsWith('Ax')) {
@@ -481,6 +544,8 @@ type PendingAnchor = {
field?: keyof Marker;
position?: { x: number; y: number };
extent?: { cx: number; cy: number };
+ /** An Excel 2016 chart's frame, read from the choice before its fallback. */
+ chartEx?: { id?: string; name?: string };
content?:
| {
type: 'pic';
@@ -489,7 +554,7 @@ type PendingAnchor = {
description?: string;
extent?: { cx: number; cy: number };
}
- | { type: 'chart'; id?: string; name?: string }
+ | { type: 'chart'; id?: string; name?: string; chart?: SheetChart }
| {
type: 'shape';
builder: ReturnType<typeof elementBuilder>;
@@ -579,8 +644,20 @@ export function readSheetDrawings(options: {
let choiceDepth = 0;
// A graphic frame's size, read before it is known to hold SmartArt.
let frameExtent: { cx: number; cy: number } | undefined;
+ // The name of the frame in a choice, for an Excel 2016 chart there.
+ let choiceName: string | undefined;
const stack: string[] = [];
const finish = (value: PendingAnchor) => {
+ // Excel 2016's chart stands in for its fallback when Macro can draw it.
+ if (value.chartEx) {
+ const target = relations.get(value.chartEx.id ?? '');
+ const chart =
+ target && !target.external
+ ? readChart(archive, target.target, options.theme, warnings)
+ : undefined;
+ if (chart)
+ value.content = { type: 'chart', name: value.chartEx.name, chart };
+ }
const content = value.content;
if (!content || content.type === 'other') {
unsupported = true;
@@ -677,6 +754,10 @@ export function readSheetDrawings(options: {
else unsupported = true;
return;
}
+ if (content.type === 'chart' && content.chart) {
+ drawings.push({ ...placement, type: 'chart', chart: content.chart });
+ return;
+ }
const target = relations.get(
(content.type === 'pic' ? content.embed : content.id) ?? ''
);
@@ -716,7 +797,13 @@ export function readSheetDrawings(options: {
choiceDepth++;
return;
}
- if (choiceDepth) return;
+ if (choiceDepth) {
+ if (anchor && node.uri === XDR && node.local === 'cNvPr')
+ choiceName = value.name;
+ else if (anchor && node.uri === CHARTEX && node.local === 'chart')
+ anchor.chartEx = { id: value.id, name: choiceName };
+ return;
+ }
// A shape is kept whole, to read and to export.
if (anchor?.content?.type === 'shape' && anchor.content.builder.open) {
anchor.content.builder.start(node);
@@ -788,7 +875,8 @@ export function readSheetDrawings(options: {
node.uri === DRAWING &&
node.local === 'graphicData' &&
anchor.content?.type === 'chart' &&
- value.uri !== CHART_NAMESPACE
+ value.uri !== CHART_NAMESPACE &&
+ value.uri !== CHARTEX
)
anchor.content =
value.uri === DIAGRAM
@@ -818,7 +906,7 @@ export function readSheetDrawings(options: {
anchor.content.data = value.dm;
anchor.content.extent ??= frameExtent;
} else if (
- node.uri === CHART_NAMESPACE &&
+ (node.uri === CHART_NAMESPACE || node.uri === CHARTEX) &&
node.local === 'chart' &&
anchor.content?.type === 'chart'
)
@@ -873,30 +961,9 @@ export function readSheetDrawings(options: {
// Export -------------------------------------------------------------------
-/** A cell a chart reads, with the Excel number format it displays with. */
-export type CellChartValue = ChartValue & { format?: string };
-export type ChartValues = (reference: string) => CellChartValue[] | undefined;
-
const RELATIONSHIPS =
'http://schemas.openxmlformats.org/officeDocument/2006/relationships';
-function xml(value: string) {
- return value
- .replace(/&/g, '&amp;')
- .replace(/</g, '&lt;')
- .replace(/>/g, '&gt;')
- .replace(/"/g, '&quot;');
-}
-
-const numberText = (value: number) =>
- Number.isInteger(value)
- ? String(value)
- : String(Number(value.toPrecision(15)));
-
-/** The number format of the first number among values, as Excel caches it. */
-const numberFormat = (values: CellChartValue[] | undefined) =>
- values?.find((value) => value.number !== undefined)?.format || 'General';
-
/** Points of a cache or of fixed values, as Excel writes them. */
function points(
prefix: string,
@@ -1080,7 +1147,7 @@ function generatedChart(chart: SheetChart, values: ChartValues): string {
const series = plot.series
.map((value) => {
const index = seriesIndex++;
- const color = (value.color ?? palette[index % palette.length]).slice(1);
+ const color = (value.color ?? paletteColor(palette, index)).slice(1);
const solid = `<a:solidFill><a:srgbClr val="${color}"/></a:solidFill>`;
const lined =
plot.kind === 'line' ||
@@ -1148,59 +1215,88 @@ function generatedChart(chart: SheetChart, values: ChartValues): string {
const grouping = plot.grouping ?? 'clustered';
const axisIds = axes.map((id) => `<c:axId val="${id}"/>`).join('');
const stacking = grouping === 'clustered' ? 'standard' : grouping;
- return match(plot.kind)
- .with(
- 'column',
- 'bar',
- (kind) =>
- `<c:barChart><c:barDir val="${kind === 'bar' ? 'bar' : 'col'}"/><c:grouping val="${grouping}"/><c:varyColors val="0"/>${series}<c:gapWidth val="150"/>${grouping === 'clustered' ? '' : '<c:overlap val="100"/>'}${axisIds}</c:barChart>`
- )
- .with(
- 'line',
- () =>
- `<c:lineChart><c:grouping val="${stacking}"/><c:varyColors val="0"/>${series}<c:marker val="1"/>${axisIds}</c:lineChart>`
- )
- .with(
- 'area',
- () =>
- `<c:areaChart><c:grouping val="${stacking}"/><c:varyColors val="0"/>${series}${axisIds}</c:areaChart>`
- )
- .with(
- 'pie',
- () =>
- `<c:pieChart><c:varyColors val="1"/>${series}<c:firstSliceAng val="0"/></c:pieChart>`
- )
- .with(
- 'doughnut',
- () =>
- `<c:doughnutChart><c:varyColors val="1"/>${series}<c:firstSliceAng val="0"/><c:holeSize val="50"/></c:doughnutChart>`
- )
- .with(
- 'scatter',
- () =>
- `<c:scatterChart><c:scatterStyle val="${plot.series.every((value) => value.noLine) ? 'marker' : 'lineMarker'}"/><c:varyColors val="0"/>${series}${axisIds}</c:scatterChart>`
- )
- .with(
- 'radar',
- () =>
- `<c:radarChart><c:radarStyle val="${plot.filled ? 'filled' : 'marker'}"/><c:varyColors val="0"/>${series}${axisIds}</c:radarChart>`
- )
- .with(
- 'bubble',
- () =>
- `<c:bubbleChart><c:varyColors val="0"/>${series}<c:bubbleScale val="100"/><c:showNegBubbles val="0"/>${axisIds}</c:bubbleChart>`
- )
- .with(
- 'stock',
- () =>
- `<c:stockChart>${series}${plot.hiLow ? '<c:hiLowLines/>' : ''}${plot.upDown ? '<c:upDownBars><c:gapWidth val="150"/><c:upBars/><c:downBars/></c:upDownBars>' : ''}${axisIds}</c:stockChart>`
- )
- .with(
- 'surface',
- () =>
- `<c:surfaceChart><c:wireframe val="0"/>${series}${axisIds}<c:axId val="${SERIES_AXIS}"/></c:surfaceChart>`
- )
- .exhaustive();
+ return (
+ match(plot.kind)
+ .with(
+ 'column',
+ 'bar',
+ (kind) =>
+ `<c:barChart><c:barDir val="${kind === 'bar' ? 'bar' : 'col'}"/><c:grouping val="${grouping}"/><c:varyColors val="0"/>${series}<c:gapWidth val="150"/>${grouping === 'clustered' ? '' : '<c:overlap val="100"/>'}${axisIds}</c:barChart>`
+ )
+ .with(
+ 'line',
+ () =>
+ `<c:lineChart><c:grouping val="${stacking}"/><c:varyColors val="0"/>${series}<c:marker val="1"/>${axisIds}</c:lineChart>`
+ )
+ .with(
+ 'area',
+ () =>
+ `<c:areaChart><c:grouping val="${stacking}"/><c:varyColors val="0"/>${series}${axisIds}</c:areaChart>`
+ )
+ .with('pie', () => {
+ const ofPie = plot.ofPie;
+ if (!ofPie)
+ return `<c:pieChart><c:varyColors val="1"/>${series}<c:firstSliceAng val="0"/></c:pieChart>`;
+ const split = match(ofPie.split)
+ .with('position', () => 'pos')
+ .with('value', () => 'val')
+ .with('percent', () => 'percent')
+ .with('custom', () => 'cust')
+ .with(undefined, () => 'auto')
+ .exhaustive();
+ return `<c:ofPieChart><c:ofPieType val="${ofPie.type}"/><c:varyColors val="1"/>${series}<c:gapWidth val="100"/><c:splitType val="${split}"/>${
+ ofPie.splitAt === undefined
+ ? ''
+ : `<c:splitPos val="${numberText(ofPie.splitAt)}"/>`
+ }${
+ ofPie.custom
+ ? `<c:custSplit>${ofPie.custom.map((index) => `<c:secondPiePt val="${index}"/>`).join('')}</c:custSplit>`
+ : ''
+ }${ofPie.size === undefined ? '' : `<c:secondPieSize val="${ofPie.size}"/>`}<c:serLines/></c:ofPieChart>`;
+ })
+ .with(
+ 'doughnut',
+ () =>
+ `<c:doughnutChart><c:varyColors val="1"/>${series}<c:firstSliceAng val="0"/><c:holeSize val="50"/></c:doughnutChart>`
+ )
+ .with(
+ 'scatter',
+ () =>
+ `<c:scatterChart><c:scatterStyle val="${plot.series.every((value) => value.noLine) ? 'marker' : 'lineMarker'}"/><c:varyColors val="0"/>${series}${axisIds}</c:scatterChart>`
+ )
+ .with(
+ 'radar',
+ () =>
+ `<c:radarChart><c:radarStyle val="${plot.filled ? 'filled' : 'marker'}"/><c:varyColors val="0"/>${series}${axisIds}</c:radarChart>`
+ )
+ .with(
+ 'bubble',
+ () =>
+ `<c:bubbleChart><c:varyColors val="0"/>${series}<c:bubbleScale val="100"/><c:showNegBubbles val="0"/>${axisIds}</c:bubbleChart>`
+ )
+ .with(
+ 'stock',
+ () =>
+ `<c:stockChart>${series}${plot.hiLow ? '<c:hiLowLines/>' : ''}${plot.upDown ? '<c:upDownBars><c:gapWidth val="150"/><c:upBars/><c:downBars/></c:upDownBars>' : ''}${axisIds}</c:stockChart>`
+ )
+ .with(
+ 'surface',
+ () =>
+ `<c:surfaceChart><c:wireframe val="0"/>${series}${axisIds}<c:axId val="${SERIES_AXIS}"/></c:surfaceChart>`
+ )
+ // Excel 2016's charts are chartEx parts, written by `chartExPart`.
+ .with(
+ 'histogram',
+ 'pareto',
+ 'waterfall',
+ 'funnel',
+ 'boxWhisker',
+ 'treemap',
+ 'sunburst',
+ () => ''
+ )
+ .exhaustive()
+ );
});
const axisPairs = [false, true].flatMap((secondary) => {
const plot = plots.find(
@@ -1269,6 +1365,7 @@ export function chartPart(
values: ChartValues,
pivotExists: (sheet: string, name: string) => boolean = () => false
): string {
+ if (isChartEx(chart)) return chartExPart(chart, values);
return keptChart(chart, values, pivotExists) ?? generatedChart(chart, values);
}
@@ -1349,10 +1446,25 @@ export function drawingPart(options: {
} else {
const id = takeId();
const path = options.chart(drawing.chart);
+ const ex = isChartEx(drawing.chart);
relations.push(
- `<Relationship Id="rId${relations.length + 1}" Type="${RELATIONSHIPS}/chart" Target="../${path.replace(/^xl\//, '')}"/>`
+ `<Relationship Id="rId${relations.length + 1}" Type="${ex ? CHARTEX_RELATIONSHIP : `${RELATIONSHIPS}/chart`}" Target="../${path.replace(/^xl\//, '')}"/>`
);
- content = `<xdr:graphicFrame macro=""><xdr:nvGraphicFramePr><xdr:cNvPr id="${id}" name="${xml(drawing.name ?? `Chart ${index + 1}`)}"/><xdr:cNvGraphicFramePr/></xdr:nvGraphicFramePr><xdr:xfrm><a:off x="0" y="0"/><a:ext cx="0" cy="0"/></xdr:xfrm><a:graphic><a:graphicData uri="${CHART_NAMESPACE}"><c:chart xmlns:c="${CHART_NAMESPACE}" r:id="rId${relations.length}"/></a:graphicData></a:graphic></xdr:graphicFrame>`;
+ const name = xml(drawing.name ?? `Chart ${index + 1}`);
+ const frame = (uri: string, element: string) =>
+ `<xdr:graphicFrame macro=""><xdr:nvGraphicFramePr><xdr:cNvPr id="${id}" name="${name}"/><xdr:cNvGraphicFramePr/></xdr:nvGraphicFramePr><xdr:xfrm><a:off x="0" y="0"/><a:ext cx="0" cy="0"/></xdr:xfrm><a:graphic><a:graphicData uri="${uri}">${element}</a:graphicData></a:graphic></xdr:graphicFrame>`;
+ if (ex) {
+ // Older Excel shows the fallback: a note where the chart would be.
+ const requirement = chartExRequirement(drawing.chart);
+ const corner = options.origin(drawing.from);
+ const { width, height } = options.size(drawing);
+ const note = `<xdr:sp macro="" textlink=""><xdr:nvSpPr><xdr:cNvPr id="${id}" name="${name}"/><xdr:cNvSpPr><a:spLocks noTextEdit="1"/></xdr:cNvSpPr></xdr:nvSpPr><xdr:spPr><a:xfrm><a:off x="${Math.round(corner.x * EMU_PER_PIXEL)}" y="${Math.round(corner.y * EMU_PER_PIXEL)}"/><a:ext cx="${Math.round(width * EMU_PER_PIXEL)}" cy="${Math.round(height * EMU_PER_PIXEL)}"/></a:xfrm><a:prstGeom prst="rect"><a:avLst/></a:prstGeom><a:solidFill><a:prstClr val="white"/></a:solidFill><a:ln w="1"><a:solidFill><a:prstClr val="green"/></a:solidFill></a:ln></xdr:spPr><xdr:txBody><a:bodyPr vertOverflow="clip" horzOverflow="clip"/><a:lstStyle/><a:p><a:r><a:rPr lang="en-US" sz="1100"/><a:t>This chart isn't available in your version of Excel.</a:t></a:r></a:p></xdr:txBody></xdr:sp>`;
+ content = `<mc:AlternateContent xmlns:mc="${COMPATIBILITY}"><mc:Choice xmlns:${requirement.prefix}="${requirement.namespace}" Requires="${requirement.prefix}">${frame(CHARTEX, `<cx:chart xmlns:cx="${CHARTEX}" r:id="rId${relations.length}"/>`)}</mc:Choice><mc:Fallback>${note}</mc:Fallback></mc:AlternateContent>`;
+ } else
+ content = frame(
+ CHART_NAMESPACE,
+ `<c:chart xmlns:c="${CHART_NAMESPACE}" r:id="rId${relations.length}"/>`
+ );
}
anchors.push(
drawing.to
diff --git a/apps/web/src/features/block-spreadsheet/core/xlsx-fixtures/README.md b/apps/web/src/features/block-spreadsheet/core/xlsx-fixtures/README.md
index 9a09ad93b4..a940015c37 100644
--- a/apps/web/src/features/block-spreadsheet/core/xlsx-fixtures/README.md
+++ b/apps/web/src/features/block-spreadsheet/core/xlsx-fixtures/README.md
@@ -6,6 +6,8 @@
`chart-types.xlsx` holds radar (marker and filled), bubble, stock (open-high-low-close with up-down bars, and high-low-close) and contour charts written by openpyxl. Regenerate it with `python3 generate-chart-types.py`.
+`office-2016-charts.xlsx` holds histogram, pareto, waterfall, funnel, box and whisker, treemap and sunburst charts as Excel 2016 saves them (`cx:` chartEx parts inside `mc:AlternateContent`, with Excel's fallback note), and pie of pie and bar of pie charts. No library writes chartEx parts, so `generate-office-2016-charts.py` writes every part with the Python standard library. Regenerate it with `python3 generate-office-2016-charts.py`.
+
`shapes.xlsx` holds a text box with rich text, a shape styled by the theme, a shape whose text is linked to a cell, an arrow, a group, an EMF logo and SmartArt with its saved drawing. openpyxl writes the cells; `generate-shapes.py` writes the drawing, the EMF records and the SmartArt parts as Excel does, since openpyxl drops shapes. Regenerate it with `python3 generate-shapes.py` (needs openpyxl and Pillow).
The financial fixture covers cross-sheet and absolute/mixed references, global and local names, NPV/IRR/XIRR/PMT, SUMIFS, INDEX/MATCH, IFERROR, precision, accounting negative/zero sections, scaling, multiples, percentages, elapsed time, Excel's 1900 leap-day compatibility, fonts/colors, double borders, merges, hidden rows/columns/sheets, row heights, filters, and frozen panes. Tests check independently specified results, native Loro save/reopen, value and style edits, and Excel import/export round trips.
diff --git a/apps/web/src/features/block-spreadsheet/core/xlsx-fixtures/generate-office-2016-charts.py b/apps/web/src/features/block-spreadsheet/core/xlsx-fixtures/generate-office-2016-charts.py
new file mode 100644
index 0000000000..696b8c1562
--- /dev/null
+++ b/apps/web/src/features/block-spreadsheet/core/xlsx-fixtures/generate-office-2016-charts.py
@@ -0,0 +1,445 @@
+"""Generate office-2016-charts.xlsx: histogram, pareto, waterfall, funnel, box
+and whisker, treemap and sunburst charts as Excel 2016 writes them (`cx:`
+chartEx parts behind a compatibility fallback), and pie of pie and bar of pie
+charts (`c:ofPieChart`).
+
+No spreadsheet library writes chartEx parts, so every part is written here
+with the standard library, laid out as Excel lays them out.
+
+Run from this directory: python3 generate-office-2016-charts.py
+"""
+
+import zipfile
+from xml.sax.saxutils import escape
+
+MAIN = "http://schemas.openxmlformats.org/spreadsheetml/2006/main"
+REL = "http://schemas.openxmlformats.org/officeDocument/2006/relationships"
+PKG = "http://schemas.openxmlformats.org/package/2006/relationships"
+XDR = "http://schemas.openxmlformats.org/drawingml/2006/spreadsheetDrawing"
+A = "http://schemas.openxmlformats.org/drawingml/2006/main"
+C = "http://schemas.openxmlformats.org/drawingml/2006/chart"
+CX = "http://schemas.microsoft.com/office/drawing/2014/chartex"
+MC = "http://schemas.openxmlformats.org/markup-compatibility/2006"
+CX1 = "http://schemas.microsoft.com/office/drawing/2015/9/8/chartex"
+CX2 = "http://schemas.microsoft.com/office/drawing/2015/10/21/chartex"
+CHARTEX_REL = "http://schemas.microsoft.com/office/2014/relationships/chartEx"
+
+# Each sheet: its rows, then its charts, each anchored over columns E to L.
+SHEETS = [
+ {
+ "name": "Scores",
+ "rows": [["Score"]] + [[value] for value in [52, 58, 61, 63, 67, 68, 71, 72, 74, 75, 79, 83, 86, 91, 98]],
+ "charts": [
+ {
+ "kind": "histogram",
+ "title": "Scores",
+ "data": [("numDim", "val", "Scores!$A$2:$A$16", 0)],
+ "name": "Scores!$A$1",
+ "layout": '<cx:binning intervalClosed="r"><cx:binSize val="10"/></cx:binning>',
+ "axes": "category",
+ }
+ ],
+ },
+ {
+ "name": "Defects",
+ "rows": [["Cause", "Count"], ["Scratches", 40], ["Dents", 10], ["Chips", 30], ["Cracks", 20], ["Stains", 5]],
+ "charts": [
+ {
+ "kind": "pareto",
+ "title": "Defects",
+ "data": [
+ ("strDim", "cat", "Defects!$A$2:$A$6", 0),
+ ("numDim", "val", "Defects!$B$2:$B$6", 1),
+ ],
+ "name": "Defects!$B$1",
+ "layout": "<cx:aggregation/>",
+ "axes": "pareto",
+ }
+ ],
+ },
+ {
+ "name": "Cash",
+ "rows": [
+ ["Step", "Amount"],
+ ["Start", 100],
+ ["Sales", 60],
+ ["Services", 20],
+ ["Costs", -50],
+ ["Tax", -15],
+ ["End", 115],
+ ],
+ "charts": [
+ {
+ "kind": "waterfall",
+ "title": "Cash flow",
+ "data": [
+ ("strDim", "cat", "Cash!$A$2:$A$7", 0),
+ ("numDim", "val", "Cash!$B$2:$B$7", 1),
+ ],
+ "name": "Cash!$B$1",
+ "labels": True,
+ "layout": '<cx:visibility connectorLines="1"/><cx:subtotals><cx:idx val="5"/></cx:subtotals>',
+ "axes": "category",
+ "legend": "t",
+ }
+ ],
+ },
+ {
+ "name": "Pipeline",
+ "rows": [["Stage", "People"], ["Visits", 1000], ["Leads", 400], ["Trials", 150], ["Sales", 60]],
+ "charts": [
+ {
+ "kind": "funnel",
+ "title": "Pipeline",
+ "data": [
+ ("strDim", "cat", "Pipeline!$A$2:$A$5", 0),
+ ("numDim", "val", "Pipeline!$B$2:$B$5", 1),
+ ],
+ "name": "Pipeline!$B$1",
+ "labels": True,
+ "layout": "",
+ "axes": "funnel",
+ }
+ ],
+ },
+ {
+ "name": "Times",
+ "rows": [["Region", "Minutes"]]
+ + [["East", value] for value in [12, 14, 15, 15, 16, 18, 19, 41]]
+ + [["West", value] for value in [20, 22, 23, 25, 26, 30]],
+ "charts": [
+ {
+ "kind": "boxWhisker",
+ "title": "Delivery times",
+ "data": [
+ ("strDim", "cat", "Times!$A$2:$A$15", 0),
+ ("numDim", "val", "Times!$B$2:$B$15", 1),
+ ],
+ "name": "Times!$B$1",
+ "layout": '<cx:visibility meanLine="0" meanMarker="1" nonoutliers="0" outliers="1"/><cx:statistics quartileMethod="exclusive"/>',
+ "axes": "category",
+ }
+ ],
+ },
+ {
+ "name": "Stores",
+ "rows": [
+ ["Region", "Store", "Sales"],
+ ["North", "Downtown", 30],
+ [None, "Airport", 20],
+ ["South", "Harbor", 25],
+ [None, "Mall", 15],
+ ["West", None, 10],
+ ],
+ "charts": [
+ {
+ "kind": "treemap",
+ "title": "Store sales",
+ "data": [
+ ("strDim", "cat", "Stores!$A$2:$B$6", 0, 2),
+ ("numDim", "size", "Stores!$C$2:$C$6", 2),
+ ],
+ "name": "Stores!$C$1",
+ "layout": '<cx:parentLabelLayout val="banner"/>',
+ "axes": None,
+ "legend": "r",
+ },
+ {
+ "kind": "sunburst",
+ "title": "Store sales by region",
+ "data": [
+ ("strDim", "cat", "Stores!$A$2:$B$6", 0, 2),
+ ("numDim", "size", "Stores!$C$2:$C$6", 2),
+ ],
+ "name": "Stores!$C$1",
+ "layout": "",
+ "axes": None,
+ },
+ ],
+ },
+ {
+ "name": "Share",
+ "rows": [
+ ["Product", "Share"],
+ ["Desktop", 40],
+ ["Phone", 30],
+ ["Tablet", 12],
+ ["Watch", 8],
+ ["TV", 6],
+ ["Other", 4],
+ ],
+ "charts": [
+ {"kind": "ofPie", "type": "pie", "split": ("pos", 3), "title": "Pie of pie"},
+ {"kind": "ofPie", "type": "bar", "split": ("val", 10), "title": "Bar of pie"},
+ ],
+ },
+]
+
+
+def column_name(index):
+ name = ""
+ index += 1
+ while index:
+ index, remainder = divmod(index - 1, 26)
+ name = chr(65 + remainder) + name
+ return name
+
+
+def cell_values(rows, column, first, last):
+ return [rows[row][column] if column < len(rows[row]) else None for row in range(first, last + 1)]
+
+
+def lvl(values, numeric):
+ points = "".join(
+ f'<cx:pt idx="{index}">{escape(str(value))}</cx:pt>'
+ for index, value in enumerate(values)
+ if value is not None
+ )
+ format_code = ' formatCode="General"' if numeric else ""
+ return f'<cx:lvl ptCount="{len(values)}"{format_code}>{points}</cx:lvl>'
+
+
+def dimension(sheet, element, kind, reference, column, width=1):
+ """A data dimension and its cached values; labels in `width` columns are a
+ level each, innermost first."""
+ rows = sheet["rows"]
+ count = len(rows) - 1
+ if element == "numDim":
+ cache = lvl(cell_values(rows, column, 1, count), True)
+ else:
+ cache = "".join(
+ lvl(cell_values(rows, level, 1, count), False)
+ for level in reversed(range(column, column + width))
+ )
+ return f"<cx:{element} type=\"{kind}\"><cx:f>{reference}</cx:f>{cache}</cx:{element}>"
+
+
+def chartex_part(sheet, chart):
+ data = "".join(dimension(sheet, *entry) for entry in chart["data"])
+ name_text = sheet["rows"][0][chart["data"][-1][3]]
+ labels = (
+ '<cx:dataLabels pos="outEnd"><cx:visibility seriesName="0" categoryName="0" value="1"/></cx:dataLabels>'
+ if chart.get("labels")
+ else ""
+ )
+ layout = f"<cx:layoutPr>{chart['layout']}</cx:layoutPr>" if chart["layout"] else ""
+ axis_id = '<cx:axisId val="1"/>' if chart["kind"] == "pareto" else ""
+ series = (
+ f'<cx:series layoutId="{"clusteredColumn" if chart["kind"] in ("histogram", "pareto") else chart["kind"]}" uniqueId="{{6C4B4D2E-0000-4000-8000-000000000001}}">'
+ f'<cx:tx><cx:txData><cx:f>{chart["name"]}</cx:f><cx:v>{escape(name_text)}</cx:v></cx:txData></cx:tx>'
+ f"{labels}<cx:dataId val=\"0\"/>{layout}{axis_id}</cx:series>"
+ )
+ if chart["kind"] == "pareto":
+ series += '<cx:series layoutId="paretoLine" ownerIdx="0" uniqueId="{6C4B4D2E-0000-4000-8000-000000000002}"><cx:axisId val="2"/></cx:series>'
+ axes = {
+ "category": '<cx:axis id="0"><cx:catScaling gapWidth="0.5"/><cx:tickLabels/></cx:axis><cx:axis id="1"><cx:valScaling/><cx:majorGridlines/><cx:tickLabels/></cx:axis>',
+ "pareto": '<cx:axis id="0"><cx:catScaling gapWidth="0"/><cx:tickLabels/></cx:axis><cx:axis id="1"><cx:valScaling/><cx:majorGridlines/><cx:tickLabels/></cx:axis><cx:axis id="2"><cx:valScaling max="1" min="0"/><cx:units unit="percentage"/><cx:tickLabels/></cx:axis>',
+ "funnel": '<cx:axis id="0"><cx:catScaling gapWidth="0.06"/><cx:tickLabels/></cx:axis>',
+ None: "",
+ }[chart["axes"]]
+ if chart["kind"] == "histogram":
+ axes = axes.replace('gapWidth="0.5"', 'gapWidth="0"')
+ legend = f'<cx:legend pos="{chart["legend"]}" align="ctr" overlay="0"/>' if chart.get("legend") else ""
+ title = (
+ '<cx:title pos="t" align="ctr" overlay="0"><cx:tx><cx:txData><cx:v>'
+ f'{escape(chart["title"])}</cx:v></cx:txData></cx:tx></cx:title>'
+ )
+ return (
+ '<?xml version="1.0" encoding="UTF-8" standalone="yes"?>\n'
+ f'<cx:chartSpace xmlns:a="{A}" xmlns:r="{REL}" xmlns:cx="{CX}">'
+ f'<cx:chartData><cx:data id="0">{data}</cx:data></cx:chartData>'
+ f"<cx:chart>{title}<cx:plotArea><cx:plotAreaRegion>{series}</cx:plotAreaRegion>{axes}</cx:plotArea>{legend}</cx:chart>"
+ "</cx:chartSpace>"
+ )
+
+
+def of_pie_part(sheet, chart):
+ rows = sheet["rows"]
+ count = len(rows) - 1
+ labels = "".join(
+ f'<c:pt idx="{index}"><c:v>{escape(row[0])}</c:v></c:pt>' for index, row in enumerate(rows[1:])
+ )
+ values = "".join(f'<c:pt idx="{index}"><c:v>{row[1]}</c:v></c:pt>' for index, row in enumerate(rows[1:]))
+ split, position = chart["split"]
+ return (
+ '<?xml version="1.0" encoding="UTF-8" standalone="yes"?>\n'
+ f'<c:chartSpace xmlns:c="{C}" xmlns:a="{A}" xmlns:r="{REL}"><c:roundedCorners val="0"/><c:chart>'
+ f'<c:title><c:tx><c:rich><a:bodyPr/><a:p><a:r><a:t>{chart["title"]}</a:t></a:r></a:p></c:rich></c:tx><c:overlay val="0"/></c:title>'
+ '<c:autoTitleDeleted val="0"/><c:plotArea><c:layout/><c:ofPieChart>'
+ f'<c:ofPieType val="{chart["type"]}"/><c:varyColors val="1"/>'
+ '<c:ser><c:idx val="0"/><c:order val="0"/>'
+ f'<c:tx><c:strRef><c:f>Share!$B$1</c:f><c:strCache><c:ptCount val="1"/><c:pt idx="0"><c:v>Share</c:v></c:pt></c:strCache></c:strRef></c:tx>'
+ f'<c:cat><c:strRef><c:f>Share!$A$2:$A${count + 1}</c:f><c:strCache><c:ptCount val="{count}"/>{labels}</c:strCache></c:strRef></c:cat>'
+ f'<c:val><c:numRef><c:f>Share!$B$2:$B${count + 1}</c:f><c:numCache><c:formatCode>General</c:formatCode><c:ptCount val="{count}"/>{values}</c:numCache></c:numRef></c:val>'
+ "</c:ser>"
+ f'<c:gapWidth val="100"/><c:splitType val="{split}"/><c:splitPos val="{position}"/><c:secondPieSize val="75"/>'
+ "<c:serLines/></c:ofPieChart></c:plotArea>"
+ '<c:legend><c:legendPos val="r"/><c:overlay val="0"/></c:legend><c:plotVisOnly val="1"/><c:dispBlanksAs val="gap"/>'
+ "</c:chart></c:chartSpace>"
+ )
+
+
+def anchor(index, chart, rel_id, shape_id):
+ top = index * 18
+ frame_name = f"Chart {shape_id - 1}"
+ position = (
+ f"<xdr:from><xdr:col>4</xdr:col><xdr:colOff>0</xdr:colOff><xdr:row>{top}</xdr:row><xdr:rowOff>0</xdr:rowOff></xdr:from>"
+ f"<xdr:to><xdr:col>12</xdr:col><xdr:colOff>0</xdr:colOff><xdr:row>{top + 16}</xdr:row><xdr:rowOff>0</xdr:rowOff></xdr:to>"
+ )
+ if chart["kind"] == "ofPie":
+ frame = (
+ f'<xdr:graphicFrame macro=""><xdr:nvGraphicFramePr><xdr:cNvPr id="{shape_id}" name="{frame_name}"/><xdr:cNvGraphicFramePr/></xdr:nvGraphicFramePr>'
+ '<xdr:xfrm><a:off x="0" y="0"/><a:ext cx="0" cy="0"/></xdr:xfrm>'
+ f'<a:graphic><a:graphicData uri="{C}"><c:chart xmlns:c="{C}" r:id="{rel_id}"/></a:graphicData></a:graphic></xdr:graphicFrame>'
+ )
+ return f'<xdr:twoCellAnchor editAs="oneCell">{position}{frame}<xdr:clientData/></xdr:twoCellAnchor>'
+ requires, namespace = ("cx2", CX2) if chart["kind"] == "funnel" else ("cx1", CX1)
+ choice = (
+ f'<mc:Choice xmlns:{requires}="{namespace}" Requires="{requires}">'
+ f'<xdr:graphicFrame macro=""><xdr:nvGraphicFramePr><xdr:cNvPr id="{shape_id}" name="{frame_name}"/><xdr:cNvGraphicFramePr/></xdr:nvGraphicFramePr>'
+ '<xdr:xfrm><a:off x="0" y="0"/><a:ext cx="0" cy="0"/></xdr:xfrm>'
+ f'<a:graphic><a:graphicData uri="{CX}"><cx:chart xmlns:cx="{CX}" r:id="{rel_id}"/></a:graphicData></a:graphic>'
+ "</xdr:graphicFrame></mc:Choice>"
+ )
+ fallback = (
+ f'<mc:Fallback><xdr:sp macro="" textlink=""><xdr:nvSpPr><xdr:cNvPr id="{shape_id}" name="{frame_name}"/><xdr:cNvSpPr><a:spLocks noTextEdit="1"/></xdr:cNvSpPr></xdr:nvSpPr>'
+ '<xdr:spPr><a:xfrm><a:off x="2438400" y="0"/><a:ext cx="4876800" cy="3048000"/></a:xfrm><a:prstGeom prst="rect"><a:avLst/></a:prstGeom>'
+ '<a:solidFill><a:prstClr val="white"/></a:solidFill><a:ln w="1"><a:solidFill><a:prstClr val="green"/></a:solidFill></a:ln></xdr:spPr>'
+ '<xdr:txBody><a:bodyPr vertOverflow="clip" horzOverflow="clip"/><a:lstStyle/><a:p><a:r><a:rPr lang="en-US" sz="1100"/>'
+ "<a:t>This chart isn't available in your version of Excel.</a:t></a:r></a:p></xdr:txBody></xdr:sp></mc:Fallback>"
+ )
+ return (
+ f'<xdr:twoCellAnchor editAs="oneCell">{position}'
+ f'<mc:AlternateContent xmlns:mc="{MC}">{choice}{fallback}</mc:AlternateContent>'
+ "<xdr:clientData/></xdr:twoCellAnchor>"
+ )
+
+
+def main():
+ strings = []
+
+ def shared(text):
+ if text not in strings:
+ strings.append(text)
+ return strings.index(text)
+
+ files = {}
+ chart_number = 0
+ chartex_number = 0
+ overrides = []
+ for sheet_index, sheet in enumerate(SHEETS, start=1):
+ rows_xml = []
+ for row_index, row in enumerate(sheet["rows"], start=1):
+ cells = []
+ for column_index, value in enumerate(row):
+ if value is None:
+ continue
+ reference = f"{column_name(column_index)}{row_index}"
+ if isinstance(value, str):
+ cells.append(f'<c r="{reference}" t="s"><v>{shared(value)}</v></c>')
+ else:
+ cells.append(f'<c r="{reference}"><v>{value}</v></c>')
+ rows_xml.append(f'<row r="{row_index}">{"".join(cells)}</row>')
+ files[f"xl/worksheets/sheet{sheet_index}.xml"] = (
+ '<?xml version="1.0" encoding="UTF-8" standalone="yes"?>\n'
+ f'<worksheet xmlns="{MAIN}" xmlns:r="{REL}"><sheetData>{"".join(rows_xml)}</sheetData><drawing r:id="rId1"/></worksheet>'
+ )
+ files[f"xl/worksheets/_rels/sheet{sheet_index}.xml.rels"] = (
+ '<?xml version="1.0" encoding="UTF-8" standalone="yes"?>\n'
+ f'<Relationships xmlns="{PKG}"><Relationship Id="rId1" Type="{REL}/drawing" Target="../drawings/drawing{sheet_index}.xml"/></Relationships>'
+ )
+ anchors = []
+ relations = []
+ for chart_index, chart in enumerate(sheet["charts"]):
+ rel_id = f"rId{chart_index + 1}"
+ if chart["kind"] == "ofPie":
+ chart_number += 1
+ path = f"charts/chart{chart_number}.xml"
+ files[f"xl/{path}"] = of_pie_part(sheet, chart)
+ relations.append(f'<Relationship Id="{rel_id}" Type="{REL}/chart" Target="../{path}"/>')
+ overrides.append(
+ f'<Override PartName="/xl/{path}" ContentType="application/vnd.openxmlformats-officedocument.drawingml.chart+xml"/>'
+ )
+ else:
+ chartex_number += 1
+ path = f"charts/chartEx{chartex_number}.xml"
+ files[f"xl/{path}"] = chartex_part(sheet, chart)
+ relations.append(f'<Relationship Id="{rel_id}" Type="{CHARTEX_REL}" Target="../{path}"/>')
+ overrides.append(
+ f'<Override PartName="/xl/{path}" ContentType="application/vnd.ms-office.chartex+xml"/>'
+ )
+ anchors.append(anchor(chart_index, chart, rel_id, chart_index + 2))
+ files[f"xl/drawings/drawing{sheet_index}.xml"] = (
+ '<?xml version="1.0" encoding="UTF-8" standalone="yes"?>\n'
+ f'<xdr:wsDr xmlns:xdr="{XDR}" xmlns:a="{A}" xmlns:r="{REL}">{"".join(anchors)}</xdr:wsDr>'
+ )
+ files[f"xl/drawings/_rels/drawing{sheet_index}.xml.rels"] = (
+ '<?xml version="1.0" encoding="UTF-8" standalone="yes"?>\n'
+ f'<Relationships xmlns="{PKG}">{"".join(relations)}</Relationships>'
+ )
+ overrides.append(
+ f'<Override PartName="/xl/worksheets/sheet{sheet_index}.xml" ContentType="application/vnd.openxmlformats-officedocument.spreadsheetml.worksheet+xml"/>'
+ )
+ overrides.append(
+ f'<Override PartName="/xl/drawings/drawing{sheet_index}.xml" ContentType="application/vnd.openxmlformats-officedocument.drawing+xml"/>'
+ )
+ files["xl/workbook.xml"] = (
+ '<?xml version="1.0" encoding="UTF-8" standalone="yes"?>\n'
+ f'<workbook xmlns="{MAIN}" xmlns:r="{REL}"><sheets>'
+ + "".join(
+ f'<sheet name="{sheet["name"]}" sheetId="{index}" r:id="rId{index}"/>'
+ for index, sheet in enumerate(SHEETS, start=1)
+ )
+ + "</sheets></workbook>"
+ )
+ count = len(SHEETS)
+ files["xl/_rels/workbook.xml.rels"] = (
+ '<?xml version="1.0" encoding="UTF-8" standalone="yes"?>\n'
+ f'<Relationships xmlns="{PKG}">'
+ + "".join(
+ f'<Relationship Id="rId{index}" Type="{REL}/worksheet" Target="worksheets/sheet{index}.xml"/>'
+ for index in range(1, count + 1)
+ )
+ + f'<Relationship Id="rId{count + 1}" Type="{REL}/styles" Target="styles.xml"/>'
+ + f'<Relationship Id="rId{count + 2}" Type="{REL}/sharedStrings" Target="sharedStrings.xml"/>'
+ + "</Relationships>"
+ )
+ files["xl/styles.xml"] = (
+ '<?xml version="1.0" encoding="UTF-8" standalone="yes"?>\n'
+ f'<styleSheet xmlns="{MAIN}"><fonts count="1"><font><sz val="11"/><name val="Calibri"/></font></fonts>'
+ '<fills count="2"><fill><patternFill patternType="none"/></fill><fill><patternFill patternType="gray125"/></fill></fills>'
+ '<borders count="1"><border><left/><right/><top/><bottom/><diagonal/></border></borders>'
+ '<cellStyleXfs count="1"><xf numFmtId="0" fontId="0" fillId="0" borderId="0"/></cellStyleXfs>'
+ '<cellXfs count="1"><xf numFmtId="0" fontId="0" fillId="0" borderId="0" xfId="0"/></cellXfs></styleSheet>'
+ )
+ files["xl/sharedStrings.xml"] = (
+ '<?xml version="1.0" encoding="UTF-8" standalone="yes"?>\n'
+ f'<sst xmlns="{MAIN}" count="{len(strings)}" uniqueCount="{len(strings)}">'
+ + "".join(f"<si><t>{escape(text)}</t></si>" for text in strings)
+ + "</sst>"
+ )
+ files["_rels/.rels"] = (
+ '<?xml version="1.0" encoding="UTF-8" standalone="yes"?>\n'
+ f'<Relationships xmlns="{PKG}"><Relationship Id="rId1" Type="{REL}/officeDocument" Target="xl/workbook.xml"/></Relationships>'
+ )
+ files["[Content_Types].xml"] = (
+ '<?xml version="1.0" encoding="UTF-8" standalone="yes"?>\n'
+ '<Types xmlns="http://schemas.openxmlformats.org/package/2006/content-types">'
+ '<Default Extension="rels" ContentType="application/vnd.openxmlformats-package.relationships+xml"/>'
+ '<Default Extension="xml" ContentType="application/xml"/>'
+ '<Override PartName="/xl/workbook.xml" ContentType="application/vnd.openxmlformats-officedocument.spreadsheetml.sheet.main+xml"/>'
+ '<Override PartName="/xl/styles.xml" ContentType="application/vnd.openxmlformats-officedocument.spreadsheetml.styles+xml"/>'
+ '<Override PartName="/xl/sharedStrings.xml" ContentType="application/vnd.openxmlformats-officedocument.spreadsheetml.sharedStrings+xml"/>'
+ + "".join(overrides)
+ + "</Types>"
+ )
+ with zipfile.ZipFile("office-2016-charts.xlsx", "w", zipfile.ZIP_DEFLATED) as archive:
+ # The content types first, as Excel writes them.
+ for name in ["[Content_Types].xml"] + sorted(name for name in files if name != "[Content_Types].xml"):
+ info = zipfile.ZipInfo(name, date_time=(2026, 1, 1, 0, 0, 0))
+ info.compress_type = zipfile.ZIP_DEFLATED
+ archive.writestr(info, files[name])
+
+
+if __name__ == "__main__":
+ main()
diff --git a/apps/web/src/features/block-spreadsheet/core/xlsx-fixtures/office-2016-charts.xlsx b/apps/web/src/features/block-spreadsheet/core/xlsx-fixtures/office-2016-charts.xlsx
new file mode 100644
index 0000000000..aa9e1b9c15
Binary files /dev/null and b/apps/web/src/features/block-spreadsheet/core/xlsx-fixtures/office-2016-charts.xlsx differ
diff --git a/apps/web/src/features/block-spreadsheet/core/xlsx-office-2016-charts.test.ts b/apps/web/src/features/block-spreadsheet/core/xlsx-office-2016-charts.test.ts
new file mode 100644
index 0000000000..f2738810d8
--- /dev/null
+++ b/apps/web/src/features/block-spreadsheet/core/xlsx-office-2016-charts.test.ts
@@ -0,0 +1,354 @@
+import { readFileSync } from 'node:fs';
+import { createRequire } from 'node:module';
+import type {
+ SheetChart,
+ SheetDrawing,
+} from '@macro-inc/spreadsheet/sheet-drawings';
+import { strFromU8, strToU8, unzipSync } from 'fflate';
+import { describe, expect, it } from 'vitest';
+import { type ChartReader, chartData } from './chart-data';
+import { chartScene } from './chart-scene';
+import { formatCellAddress } from './spreadsheet-document';
+import type { WorkbookFileData } from './workbook-file-types';
+import { decodeXlsx, encodeXlsx } from './xlsx-codec';
+import { chartPart, drawingPart, readChart } from './xlsx-drawings';
+
+const fixture = () =>
+ new Uint8Array(
+ readFileSync(
+ createRequire(import.meta.url).resolve(
+ './xlsx-fixtures/office-2016-charts.xlsx'
+ )
+ )
+ );
+
+function reader(workbook: WorkbookFileData, home: string): ChartReader {
+ return (range) => {
+ const sheet = workbook.sheets.find(
+ (entry) => entry.name === (range.sheet ?? home)
+ );
+ if (!sheet) return;
+ const values = [];
+ for (let row = range.top; row <= range.bottom; row++)
+ for (let column = range.left; column <= range.right; column++) {
+ const text = sheet.cells[formatCellAddress(row, column)]?.value ?? '';
+ const number = text === '' ? Number.NaN : Number(text);
+ values.push({ text, ...(Number.isFinite(number) && { number }) });
+ }
+ return values;
+ };
+}
+
+const charts = (workbook: WorkbookFileData, name: string) =>
+ (
+ workbook.sheets.find((sheet) => sheet.name === name)?.metadata?.drawings ??
+ []
+ ).flatMap((drawing) => (drawing.type === 'chart' ? [drawing.chart] : []));
+
+/** What a chart is, without the part kept for export or theme colors. */
+const described = ({
+ source: _source,
+ colors: _colors,
+ ...chart
+}: SheetChart) => chart;
+
+describe('Excel 2016 charts', () => {
+ it('imports each kind from its chartEx part instead of the fallback', async () => {
+ const workbook = await decodeXlsx(fixture());
+ expect(workbook.warnings).toEqual([]);
+ expect(charts(workbook, 'Scores').map(described)).toEqual([
+ {
+ title: 'Scores',
+ plots: [
+ {
+ kind: 'histogram',
+ binning: { size: 10 },
+ gapWidth: 0,
+ series: [{ name: 'Score', nameRef: 1, values: 0 }],
+ },
+ ],
+ references: ['Scores!$A$2:$A$16', 'Scores!$A$1'],
+ },
+ ]);
+ expect(charts(workbook, 'Defects').map(described)).toEqual([
+ {
+ title: 'Defects',
+ plots: [
+ {
+ kind: 'pareto',
+ aggregate: true,
+ gapWidth: 0,
+ series: [{ name: 'Count', nameRef: 2, categories: 0, values: 1 }],
+ },
+ ],
+ references: ['Defects!$A$2:$A$6', 'Defects!$B$2:$B$6', 'Defects!$B$1'],
+ },
+ ]);
+ const [waterfall] = charts(workbook, 'Cash');
+ expect(waterfall.legend).toBe('top');
+ expect(waterfall.plots).toEqual([
+ {
+ kind: 'waterfall',
+ totals: [5],
+ labels: true,
+ gapWidth: 50,
+ series: [{ name: 'Amount', nameRef: 2, categories: 0, values: 1 }],
+ },
+ ]);
+ expect(charts(workbook, 'Pipeline')[0].plots[0]).toMatchObject({
+ kind: 'funnel',
+ labels: true,
+ gapWidth: 6,
+ });
+ expect(charts(workbook, 'Times')[0].plots[0]).toEqual({
+ kind: 'boxWhisker',
+ gapWidth: 50,
+ series: [{ name: 'Minutes', nameRef: 2, categories: 0, values: 1 }],
+ });
+ const [treemap, sunburst] = charts(workbook, 'Stores');
+ expect(treemap.legend).toBe('right');
+ expect(treemap.plots[0]).toMatchObject({
+ kind: 'treemap',
+ parentLabels: 'banner',
+ });
+ expect(sunburst.plots[0].kind).toBe('sunburst');
+ expect(treemap.references[0]).toBe('Stores!$A$2:$B$6');
+ const [pieOfPie, barOfPie] = charts(workbook, 'Share');
+ expect(pieOfPie.plots[0]).toMatchObject({
+ kind: 'pie',
+ ofPie: { type: 'pie', split: 'position', splitAt: 3, size: 75 },
+ });
+ expect(barOfPie.plots[0]).toMatchObject({
+ kind: 'pie',
+ ofPie: { type: 'bar', split: 'value', splitAt: 10, size: 75 },
+ });
+ });
+
+ it('draws imported charts from their cells', async () => {
+ const workbook = await decodeXlsx(fixture());
+ const data = (sheet: string, index: number) =>
+ chartData(charts(workbook, sheet)[index], reader(workbook, sheet));
+ const stores = data('Stores', 0);
+ expect(stores.paths).toEqual([
+ ['North', 'Downtown'],
+ ['', 'Airport'],
+ ['South', 'Harbor'],
+ ['', 'Mall'],
+ ['West', ''],
+ ]);
+ const tips = (shapes: ReturnType<typeof chartScene>['shapes']) =>
+ shapes.flatMap((shape) =>
+ 'tip' in shape && shape.tip ? [shape.tip] : []
+ );
+ expect(tips(chartScene(stores, 480, 288).shapes)).toEqual(
+ expect.arrayContaining([
+ 'North: 50',
+ 'North › Airport: 20',
+ 'South › Mall: 15',
+ 'West: 10',
+ ])
+ );
+ expect(tips(chartScene(data('Cash', 0), 480, 288).shapes)).toEqual(
+ expect.arrayContaining(['Start: 100', 'Costs: -50', 'End: 115'])
+ );
+ expect(tips(chartScene(data('Times', 0), 480, 288).shapes)).toEqual(
+ expect.arrayContaining(['Minutes · East: 41'])
+ );
+ expect(tips(chartScene(data('Scores', 0), 480, 288).shapes)).toEqual(
+ expect.arrayContaining(['[52, 62]: 3', '(62, 72]: 5', '(92, 102]: 1'])
+ );
+ });
+
+ it('exports chartEx parts behind a fallback, which import again unchanged', async () => {
+ const workbook = await decodeXlsx(fixture());
+ const exported = await encodeXlsx(workbook);
+ expect(exported.warnings).toEqual([]);
+ const files = unzipSync(exported.bytes);
+ const names = Object.keys(files).filter((name) =>
+ name.startsWith('xl/charts/')
+ );
+ expect(names.filter((name) => name.includes('chartEx'))).toHaveLength(7);
+ const types = strFromU8(files['[Content_Types].xml']);
+ expect(types).toContain(
+ '<Override PartName="/xl/charts/chartEx7.xml" ContentType="application/vnd.ms-office.chartex+xml"/>'
+ );
+ const drawing = strFromU8(files['xl/drawings/drawing1.xml']);
+ expect(drawing).toContain('<mc:Choice xmlns:cx1=');
+ expect(drawing).toContain('<mc:Fallback>');
+ expect(strFromU8(files['xl/drawings/_rels/drawing1.xml.rels'])).toContain(
+ 'Type="http://schemas.microsoft.com/office/2014/relationships/chartEx" Target="../charts/chartEx1.xml"'
+ );
+ // The kept part carries caches of the cells' current values.
+ const histogram = strFromU8(files['xl/charts/chartEx1.xml']);
+ expect(histogram).toContain(
+ '<cx:f>Scores!$A$2:$A$16</cx:f><cx:lvl ptCount="15" formatCode="General"><cx:pt idx="0">52</cx:pt>'
+ );
+ const again = await decodeXlsx(exported.bytes);
+ expect(again.warnings).toEqual([]);
+ for (const sheet of workbook.sheets)
+ expect(charts(again, sheet.name).map(described)).toEqual(
+ charts(workbook, sheet.name).map(described)
+ );
+ });
+
+ it('writes each kind it describes as Excel does and reads it back unchanged', () => {
+ const cells = (range: string) => `'Data'!${range}`;
+ const series = [{ nameRef: 2, categories: 0, values: 1 }];
+ const references = [cells('$A$2:$A$9'), cells('$B$2:$B$9'), cells('$B$1')];
+ // A `c:` series names itself before its data.
+ const pieSeries = [{ nameRef: 0, categories: 1, values: 2 }];
+ const pieReferences = [references[2], references[0], references[1]];
+ const kinds: SheetChart[] = [
+ {
+ plots: [
+ {
+ kind: 'histogram',
+ binning: { count: 4, underflow: 2, overflow: 9, closedLeft: true },
+ series: [{ nameRef: 1, values: 0 }],
+ },
+ ],
+ references: references.slice(1),
+ },
+ {
+ plots: [
+ {
+ kind: 'pareto',
+ binning: { size: 5 },
+ series: [{ nameRef: 1, values: 0 }],
+ },
+ ],
+ references: references.slice(1),
+ },
+ {
+ title: 'Cash',
+ legend: 'bottom',
+ plots: [
+ {
+ kind: 'waterfall',
+ totals: [0, 7],
+ labels: true,
+ noConnectors: true,
+ series,
+ },
+ ],
+ references,
+ },
+ { plots: [{ kind: 'funnel', labels: true, series }], references },
+ {
+ plots: [
+ {
+ kind: 'boxWhisker',
+ quartiles: 'inclusive',
+ meanLine: true,
+ noMeanMarkers: true,
+ innerPoints: true,
+ noOutliers: true,
+ series,
+ },
+ ],
+ references,
+ },
+ {
+ plots: [{ kind: 'treemap', parentLabels: 'none', series }],
+ references: [cells('$A$2:$B$9'), cells('$C$2:$C$9'), cells('$C$1')],
+ },
+ { plots: [{ kind: 'sunburst', series }], references },
+ {
+ plots: [
+ {
+ kind: 'pie',
+ ofPie: { type: 'bar', split: 'custom', custom: [1, 3], size: 50 },
+ series: pieSeries,
+ },
+ ],
+ references: pieReferences,
+ },
+ {
+ plots: [{ kind: 'pie', ofPie: { type: 'pie' }, series: pieSeries }],
+ references: pieReferences,
+ },
+ ];
+ for (const chart of kinds) {
+ const part = chartPart(chart, () => undefined);
+ const path = part.includes('<cx:chartSpace')
+ ? 'xl/charts/chartEx1.xml'
+ : 'xl/charts/chart1.xml';
+ const warnings = new Set<string>();
+ const again = readChart(
+ {
+ names: [path],
+ read: (name) => (name === path ? strToU8(part) : undefined),
+ },
+ path,
+ [],
+ warnings
+ );
+ expect([...warnings]).toEqual([]);
+ expect(again && described(again)).toEqual({
+ ...chart,
+ plots: chart.plots.map((plot) => ({
+ ...plot,
+ // Excel saves its default gaps.
+ ...(plot.kind === 'histogram' || plot.kind === 'pareto'
+ ? { gapWidth: 0 }
+ : plot.kind === 'waterfall'
+ ? { gapWidth: 50 }
+ : plot.kind === 'boxWhisker'
+ ? { gapWidth: 100 }
+ : plot.kind === 'funnel'
+ ? { gapWidth: 6 }
+ : {}),
+ })),
+ });
+ }
+ });
+
+ it('reads only the chart title, and only totals a sheet can hold', () => {
+ const path = 'xl/charts/chartEx1.xml';
+ const part = `<cx:chartSpace xmlns:a="http://schemas.openxmlformats.org/drawingml/2006/main" xmlns:cx="http://schemas.microsoft.com/office/drawing/2014/chartex"><cx:chartData><cx:data id="0"><cx:numDim type="val"><cx:f>Data!$B$2:$B$5</cx:f></cx:numDim></cx:data></cx:chartData><cx:chart><cx:title pos="t"/><cx:plotArea><cx:plotAreaRegion><cx:series layoutId="waterfall"><cx:tx><cx:txData><cx:v>Cash</cx:v></cx:txData></cx:tx><cx:dataId val="0"/><cx:layoutPr><cx:subtotals><cx:idx val="-1"/><cx:idx val="3"/><cx:idx val="100000"/></cx:subtotals></cx:layoutPr></cx:series></cx:plotAreaRegion><cx:axis id="0"><cx:catScaling/><cx:title><cx:tx><cx:rich><a:p><a:r><a:t>Months</a:t></a:r></a:p></cx:rich></cx:tx></cx:title></cx:axis><cx:axis id="1"><cx:valScaling/><cx:title><cx:tx><cx:txData><cx:v>Dollars</cx:v></cx:txData></cx:tx></cx:title></cx:axis></cx:plotArea></cx:chart></cx:chartSpace>`;
+ const chart = readChart(
+ {
+ names: [path],
+ read: (name) => (name === path ? strToU8(part) : undefined),
+ },
+ path,
+ [],
+ new Set()
+ );
+ // A chart title without text shows the series name, not an axis title.
+ expect(chart?.title).toBe('Cash');
+ expect(chart?.plots[0].totals).toEqual([3]);
+ });
+
+ it('wraps a chartEx frame in compatibility content', () => {
+ const drawing: SheetDrawing = {
+ id: 'chart',
+ type: 'chart',
+ name: 'Pipeline',
+ from: { row: 0, column: 4, x: 0, y: 0 },
+ width: 480,
+ height: 288,
+ chart: {
+ plots: [{ kind: 'funnel', series: [{ values: 0 }] }],
+ references: ["'Data'!$B$2:$B$5"],
+ },
+ };
+ const part = drawingPart({
+ drawings: [drawing],
+ image: () => undefined,
+ chart: () => 'xl/charts/chartEx1.xml',
+ size: () => ({ width: 480, height: 288 }),
+ origin: () => ({ x: 0, y: 0 }),
+ });
+ // Funnels need Excel's 2016 chartEx revision two.
+ expect(part?.xml).toContain(
+ '<mc:Choice xmlns:cx2="http://schemas.microsoft.com/office/drawing/2015/10/21/chartex" Requires="cx2">'
+ );
+ expect(part?.xml).toContain(
+ '<a:graphicData uri="http://schemas.microsoft.com/office/drawing/2014/chartex"><cx:chart xmlns:cx="http://schemas.microsoft.com/office/drawing/2014/chartex" r:id="rId1"/>'
+ );
+ expect(part?.rels).toContain(
+ 'Type="http://schemas.microsoft.com/office/2014/relationships/chartEx" Target="../charts/chartEx1.xml"'
+ );
+ });
+});
diff --git a/apps/web/src/features/block-spreadsheet/core/xlsx-writer.ts b/apps/web/src/features/block-spreadsheet/core/xlsx-writer.ts
index 41e4e3f7bb..c65f964ff1 100644
--- a/apps/web/src/features/block-spreadsheet/core/xlsx-writer.ts
+++ b/apps/web/src/features/block-spreadsheet/core/xlsx-writer.ts
@@ -27,20 +27,15 @@ import {
XLSX_MAX_EXPANDED_BYTES,
XLSX_MAX_SHEETS,
} from './workbook-file-types';
+import type { CellChartValue, ChartValues } from './xlsx-chart-values';
+import { CHARTEX_CONTENT_TYPE, isChartEx } from './xlsx-chartex';
import {
CHECKBOX_BAGS,
CHECKBOX_CONTENT_TYPE,
CHECKBOX_PART,
CHECKBOX_RELATIONSHIP,
} from './xlsx-checkboxes';
-import {
- type CellChartValue,
- type ChartValues,
- chartPart,
- drawingPart,
- imageFile,
- themePart,
-} from './xlsx-drawings';
+import { chartPart, drawingPart, imageFile, themePart } from './xlsx-drawings';
import {
addFunctionPrefixes,
exportImplicitIntersections,
@@ -268,6 +263,7 @@ export function writeXlsxWorkbook(
// Drawing parts by number, chart parts, and images written once each.
let drawingCount = 0;
let chartCount = 0;
+ let chartExCount = 0;
const media = new Map<string, string | undefined>();
const imageExtensions = new Set<string>();
// Pivot tables, each with its own cache, numbered from 1, the caches that
@@ -530,7 +526,10 @@ export function writeXlsxWorkbook(
drawings: metadata.drawings,
image: writeImage,
chart: (chart) => {
- const path = `xl/charts/chart${++chartCount}.xml`;
+ // Excel 2016's charts are chartEx parts, numbered on their own.
+ const path = isChartEx(chart)
+ ? `xl/charts/chartEx${++chartExCount}.xml`
+ : `xl/charts/chart${++chartCount}.xml`;
files[path] = strToU8(chartPart(chart, readValues, pivotExists));
return path;
},
@@ -713,6 +712,10 @@ export function writeXlsxWorkbook(
{ length: chartCount },
(_, index) =>
`<Override PartName="/xl/charts/chart${index + 1}.xml" ContentType="application/vnd.openxmlformats-officedocument.drawingml.chart+xml"/>`
+ ).join('')}${Array.from(
+ { length: chartExCount },
+ (_, index) =>
+ `<Override PartName="/xl/charts/chartEx${index + 1}.xml" ContentType="${CHARTEX_CONTENT_TYPE}"/>`
).join('')}${Array.from(
{ length: pivotCount },
(_, index) =>
diff --git a/docs/agent-guide/documents.md b/docs/agent-guide/documents.md
index 6d487fa55b..33abad28ac 100644
--- a/docs/agent-guide/documents.md
+++ b/docs/agent-guide/documents.md
@@ -516,8 +516,10 @@ its days are `gridcell` buttons marked `data-active` (the keyboard's day),
`data-selected` (the cell's date) and `data-today`.
Images and charts (column, bar, line and area, each clustered, stacked or
-100% stacked, plus pie, doughnut, scatter, combo, radar, bubble, stock and
-surface, drawn as a contour) are drawn over their cells and move with them;
+100% stacked, plus pie, pie of pie, bar of pie, doughnut, scatter, combo,
+radar, bubble, stock, surface drawn as a contour, and Excel 2016's histogram,
+pareto, waterfall, funnel, box and whisker, treemap and sunburst) are drawn
+over their cells and move with them;
charts redraw as the cells they read change. A 100% stacked chart fills each
category to 100% of its positive values and to 100% of its negative values.
Scatter charts plot markers without connecting lines. A combo chart draws
@@ -527,8 +529,15 @@ image description. The toolbar's **Insert chart, image or checkbox** menu (chart
adds a chart of the selected cells — or, from one cell, of the table around
it, placed beside it — or an image file (PNG, JPEG, GIF, WebP or BMP up to
2 MB) at the active cell. Its **More charts** submenu holds Radar, Filled
-radar, Bubble, Stock and Contour. Edit chart's type list also offers 100%
-stacked bar, stacked line, 100% stacked line, 100% stacked area and Combo. A
+radar, Bubble, Stock, Contour, Histogram, Waterfall, Funnel, Box and whisker,
+Treemap and Sunburst. Edit chart's type list also offers 100% stacked bar,
+stacked line, 100% stacked line, 100% stacked area, Combo, Pareto, Pie of pie
+and Bar of pie. A histogram bins one column of numbers (Scott's rule, as
+Excel's automatic bins) or, with labels, sums values by label; a treemap or
+sunburst reads every column before its values as a level, a blank label
+continuing the one above. Excel 2016 charts download as chartEx parts with
+Excel's fallback note for older versions; Excel 2016 maps import as that
+fallback. A
stock chart needs three or four series (high, low, close, with open first for
up-down bars), a bubble chart reads x values from the first column, then
values and sizes in pairs, and a combo chart needs at least two series. Imported shapes, text boxes, lines,
diff --git a/packages/spreadsheet/src/sheet-drawings.test.ts b/packages/spreadsheet/src/sheet-drawings.test.ts
index ed7ec44ede..2cb1c3be79 100644
--- a/packages/spreadsheet/src/sheet-drawings.test.ts
+++ b/packages/spreadsheet/src/sheet-drawings.test.ts
@@ -53,6 +53,71 @@ describe('sheet drawings', () => {
expect(validDrawings([chart, image])).toBe(true);
});
+ it("accepts Excel 2016's statistical, flow and hierarchy charts with their options", () => {
+ const options: SheetDrawing = {
+ ...chart,
+ chart: {
+ ...chart.chart,
+ plots: [
+ {
+ kind: 'histogram',
+ binning: {
+ size: 10,
+ underflow: 20,
+ overflow: 90,
+ closedLeft: true,
+ },
+ gapWidth: 0,
+ series: [{ values: 2 }],
+ },
+ {
+ kind: 'pareto',
+ aggregate: true,
+ series: [{ categories: 1, values: 2 }],
+ },
+ {
+ kind: 'waterfall',
+ totals: [0, 5],
+ labels: true,
+ noConnectors: true,
+ series: [{ categories: 1, values: 2 }],
+ },
+ {
+ kind: 'funnel',
+ labels: true,
+ series: [{ categories: 1, values: 2 }],
+ },
+ {
+ kind: 'boxWhisker',
+ quartiles: 'inclusive',
+ meanLine: true,
+ noMeanMarkers: true,
+ innerPoints: true,
+ noOutliers: true,
+ series: [{ categories: 1, values: 2 }],
+ },
+ {
+ kind: 'treemap',
+ parentLabels: 'banner',
+ series: [{ categories: 1, values: 2 }],
+ },
+ { kind: 'sunburst', series: [{ categories: 1, values: 2 }] },
+ {
+ kind: 'pie',
+ ofPie: { type: 'bar', split: 'value', splitAt: 10, size: 60 },
+ series: [{ categories: 1, values: 2 }],
+ },
+ {
+ kind: 'pie',
+ ofPie: { type: 'pie', split: 'custom', custom: [3, 4] },
+ series: [{ categories: 1, values: 2 }],
+ },
+ ],
+ },
+ };
+ expect(validDrawings([options])).toBe(true);
+ });
+
it.each([
[
'a series reading a missing reference',
@@ -62,7 +127,53 @@ describe('sheet drawings', () => {
'an unknown chart kind',
{
...chart,
- chart: { ...chart.chart, plots: [{ kind: 'funnel', series: [] }] },
+ chart: { ...chart.chart, plots: [{ kind: 'gauge', series: [] }] },
+ },
+ ],
+ [
+ 'a kind named after an object method',
+ {
+ ...chart,
+ chart: {
+ ...chart.chart,
+ plots: [{ kind: 'constructor', ofPie: { type: 'pie' }, series: [] }],
+ },
+ },
+ ],
+ [
+ 'bins of no width',
+ {
+ ...chart,
+ chart: {
+ ...chart.chart,
+ plots: [{ kind: 'histogram', binning: { size: 0 }, series: [] }],
+ },
+ },
+ ],
+ [
+ 'an option of another kind',
+ {
+ ...chart,
+ chart: {
+ ...chart.chart,
+ plots: [{ kind: 'column', totals: [1], series: [] }],
+ },
+ },
+ ],
+ [
+ 'a second plot split at a fraction of a point',
+ {
+ ...chart,
+ chart: {
+ ...chart.chart,
+ plots: [
+ {
+ kind: 'pie',
+ ofPie: { type: 'pie', split: 'position', splitAt: 1.5 },
+ series: [],
+ },
+ ],
+ },
},
],
[
diff --git a/packages/spreadsheet/src/sheet-drawings.ts b/packages/spreadsheet/src/sheet-drawings.ts
index 1e5c6d9773..46682ac38e 100644
--- a/packages/spreadsheet/src/sheet-drawings.ts
+++ b/packages/spreadsheet/src/sheet-drawings.ts
@@ -40,6 +40,14 @@ export const CHART_KINDS = [
'bubble',
'stock',
'surface',
+ // Excel 2016's charts, saved as `cx:` chart parts.
+ 'histogram',
+ 'pareto',
+ 'waterfall',
+ 'funnel',
+ 'boxWhisker',
+ 'treemap',
+ 'sunburst',
] as const;
export type ChartKind = (typeof CHART_KINDS)[number];
export const CHART_GROUPINGS = [
@@ -69,6 +77,39 @@ export type ChartSeries = {
sizes?: number;
};
+/**
+ * How a histogram groups its values: bins of a width, or a number of bins,
+ * else as wide as Scott's rule makes them, as Excel's automatic bins.
+ */
+export type ChartBinning = {
+ size?: number;
+ count?: number;
+ /** Values at or below this share the first bin. */
+ underflow?: number;
+ /** Values above this share the last bin. */
+ overflow?: number;
+ /** Bins hold their lower edge rather than their upper edge. */
+ closedLeft?: true;
+};
+
+/**
+ * A pie with some of its points moved to a second, smaller pie or a bar,
+ * as Excel's pie of pie and bar of pie.
+ */
+export type ChartOfPie = {
+ type: 'pie' | 'bar';
+ /**
+ * Which points move: the last `splitAt` points, those below `splitAt`, or
+ * below `splitAt` percent of the total; `custom` lists them. Excel's
+ * automatic split moves the last third.
+ */
+ split?: 'position' | 'value' | 'percent' | 'custom';
+ splitAt?: number;
+ custom?: number[];
+ /** The second plot's size, in percent of the first's. */
+ size?: number;
+};
+
/** Series drawn the same way, on the primary or the secondary value axis. */
export type ChartPlot = {
kind: ChartKind;
@@ -79,6 +120,28 @@ export type ChartPlot = {
/** A stock chart's lines from high to low, and bars from open to close. */
hiLow?: boolean;
upDown?: boolean;
+ /** A histogram's or pareto chart's bins. */
+ binning?: ChartBinning;
+ /** A histogram or pareto chart sums values by category instead of binning. */
+ aggregate?: true;
+ /** The gap between bars, in percent of a bar's width. */
+ gapWidth?: number;
+ /** A waterfall's points that are totals, measured from zero. */
+ totals?: number[];
+ /** A waterfall without lines from each bar to the next. */
+ noConnectors?: true;
+ /** Values written on a waterfall's or funnel's bars. */
+ labels?: true;
+ /** A box and whisker chart's quartiles: exclusive unless inclusive. */
+ quartiles?: 'inclusive';
+ meanLine?: true;
+ noMeanMarkers?: true;
+ /** Points inside the whiskers, drawn as markers. */
+ innerPoints?: true;
+ noOutliers?: true;
+ /** Where a treemap writes its parents' names; overlapping by default. */
+ parentLabels?: 'banner' | 'none';
+ ofPie?: ChartOfPie;
series: ChartSeries[];
};
@@ -386,24 +449,126 @@ function validSeries(value: unknown, references: number): boolean {
);
}
+const finite = (value: unknown) =>
+ typeof value === 'number' && Number.isFinite(value);
+const pointIndex = (value: unknown) =>
+ Number.isInteger(value) &&
+ (value as number) >= 0 &&
+ (value as number) < 100_000;
+
+function validBinning(value: unknown): boolean {
+ if (!value || typeof value !== 'object') return false;
+ const binning = value as Record<string, unknown>;
+ return (
+ Object.keys(binning).every((key) =>
+ ['size', 'count', 'underflow', 'overflow', 'closedLeft'].includes(key)
+ ) &&
+ (binning.size === undefined ||
+ (finite(binning.size) && (binning.size as number) > 0)) &&
+ (binning.count === undefined ||
+ (Number.isInteger(binning.count) &&
+ (binning.count as number) >= 1 &&
+ (binning.count as number) <= 1_000)) &&
+ (binning.underflow === undefined || finite(binning.underflow)) &&
+ (binning.overflow === undefined || finite(binning.overflow)) &&
+ (binning.closedLeft === undefined || binning.closedLeft === true)
+ );
+}
+
+function validOfPie(value: unknown): boolean {
+ if (!value || typeof value !== 'object') return false;
+ const ofPie = value as Record<string, unknown>;
+ return (
+ Object.keys(ofPie).every((key) =>
+ ['type', 'split', 'splitAt', 'custom', 'size'].includes(key)
+ ) &&
+ (ofPie.type === 'pie' || ofPie.type === 'bar') &&
+ (ofPie.split === undefined ||
+ ['position', 'value', 'percent', 'custom'].includes(
+ ofPie.split as string
+ )) &&
+ (ofPie.splitAt === undefined ||
+ (ofPie.split === 'position'
+ ? pointIndex(ofPie.splitAt)
+ : finite(ofPie.splitAt))) &&
+ (ofPie.custom === undefined ||
+ (Array.isArray(ofPie.custom) &&
+ ofPie.custom.length <= 1_000 &&
+ ofPie.custom.every(pointIndex))) &&
+ (ofPie.size === undefined ||
+ (finite(ofPie.size) &&
+ (ofPie.size as number) >= 5 &&
+ (ofPie.size as number) <= 200))
+ );
+}
+
+/** Options every kind may carry, as charts were first stored. */
+const SHARED_PLOT_OPTIONS = [
+ 'grouping',
+ 'secondary',
+ 'filled',
+ 'hiLow',
+ 'upDown',
+];
+/** Options only some kinds take. */
+const KIND_OPTIONS: Partial<Record<ChartKind, string[]>> = {
+ pie: ['ofPie'],
+ histogram: ['binning', 'aggregate', 'gapWidth'],
+ pareto: ['binning', 'aggregate', 'gapWidth'],
+ waterfall: ['totals', 'noConnectors', 'labels', 'gapWidth'],
+ funnel: ['labels', 'gapWidth'],
+ boxWhisker: [
+ 'quartiles',
+ 'meanLine',
+ 'noMeanMarkers',
+ 'innerPoints',
+ 'noOutliers',
+ 'gapWidth',
+ ],
+ treemap: ['parentLabels'],
+};
+
function validPlot(value: unknown, references: number): boolean {
if (!value || typeof value !== 'object') return false;
const plot = value as Record<string, unknown>;
+ const options =
+ (typeof plot.kind === 'string' && Object.hasOwn(KIND_OPTIONS, plot.kind)
+ ? KIND_OPTIONS[plot.kind as ChartKind]
+ : undefined) ?? [];
return (
- Object.keys(plot).every((key) =>
- [
- 'kind',
- 'grouping',
- 'secondary',
- 'filled',
- 'hiLow',
- 'upDown',
- 'series',
- ].includes(key)
- ) &&
- ['filled', 'hiLow', 'upDown'].every(
- (key) => plot[key] === undefined || plot[key] === true
+ Object.keys(plot).every(
+ (key) =>
+ key === 'kind' ||
+ key === 'series' ||
+ SHARED_PLOT_OPTIONS.includes(key) ||
+ options.includes(key)
) &&
+ [
+ 'filled',
+ 'hiLow',
+ 'upDown',
+ 'aggregate',
+ 'noConnectors',
+ 'labels',
+ 'meanLine',
+ 'noMeanMarkers',
+ 'innerPoints',
+ 'noOutliers',
+ ].every((key) => plot[key] === undefined || plot[key] === true) &&
+ (plot.binning === undefined || validBinning(plot.binning)) &&
+ (plot.gapWidth === undefined ||
+ (finite(plot.gapWidth) &&
+ (plot.gapWidth as number) >= 0 &&
+ (plot.gapWidth as number) <= 500)) &&
+ (plot.totals === undefined ||
+ (Array.isArray(plot.totals) &&
+ plot.totals.length <= 100_000 &&
+ plot.totals.every(pointIndex))) &&
+ (plot.quartiles === undefined || plot.quartiles === 'inclusive') &&
+ (plot.parentLabels === undefined ||
+ plot.parentLabels === 'banner' ||
+ plot.parentLabels === 'none') &&
+ (plot.ofPie === undefined || validOfPie(plot.ofPie)) &&
(CHART_KINDS as readonly unknown[]).includes(plot.kind) &&
(plot.grouping === undefined ||
(CHART_GROUPINGS as readonly unknown[]).includes(plot.grouping)) &&