Macro is a unified workspace for teams: email, chat, docs, tasks, agents, calls, and CRM — @-linked together with shared AI memory.
TypeScript agentaiai-agentsall-in-onecrmcrm-systememaillinearmcpmessagingnotesnotionofficerustslackslack-alternativestartupstartup-toolstypescriptworkspace
feat(spreadsheet): add percent stacks and combo charts (#7742)
Wolf Mermelsteinb2d12650f6cc
diff --git a/apps/web/src/features/block-spreadsheet/browser-test/README.md b/apps/web/src/features/block-spreadsheet/browser-test/README.mdindex 0f8dcfabe7..996efe0fa4 100644--- a/apps/web/src/features/block-spreadsheet/browser-test/README.md+++ b/apps/web/src/features/block-spreadsheet/browser-test/README.md@@ -38,6 +38,8 @@ Imported conditional formatting, validation lists and notes, imported chartsand images (drawn over their cells, following edits, deleted and restored withundo, 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,shapes, text boxes, groups, SmartArt and an EMF logo (drawn, a linked text boxfollowing its cell, moved and downloaded), GETPIVOTDATA formulas of an importedpivot table (calculated, following an edit to the table and downloaded), pivotdiff --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.tsindex b8dc8f0d08..46aabc9f71 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@@ -150,3 +150,52 @@ test('more chart types are inserted from the Insert menu and downloaded', asyncparts.filter((part) => part.includes('<radarStyle val="filled"'))).toHaveLength(1);});++test('100% stacked columns and combo charts are inserted from the menu', async ({+ page,+}) => {+ await sheet(page, 'Ratings');+ await page.locator('[data-address="B3"]').click();+ await page+ .getByRole('button', { name: 'Insert chart or image', exact: true })+ .click();+ await page+ .getByRole('menuitem', { name: '100% stacked column', exact: true })+ .click();+ const stacked = page.getByRole('figure', { name: 'Chart: Chart 3' });+ await expect(stacked).toBeFocused();+ // Every category fills the axis, so the value labels run to 100%.+ await expect(stacked.locator('svg text', { hasText: /^100%$/ })).toHaveCount(+ 1+ );+ await expect(+ stacked.locator('rect title', { hasText: 'Basic · Price:' })+ ).toHaveCount(1);++ await stacked.press('Escape');+ await page.locator('[data-address="B3"]').click();+ await page+ .getByRole('button', { name: 'Insert chart or image', exact: true })+ .click();+ await page.getByRole('menuitem', { name: 'Column', exact: true }).click();+ const combo = page.getByRole('figure', { name: 'Chart: Chart 4' });+ await expect(combo).toBeFocused();+ await combo.press('Enter');+ const edit = page.getByRole('dialog', { name: 'Edit chart' });+ await edit.getByLabel('Type').selectOption('combo');+ await edit.getByRole('button', { name: 'Apply' }).click();+ await expect(combo).toBeFocused();+ // The last series is the line; the earlier series stay columns.+ await expect(+ combo.locator('rect title', { hasText: /^Basic · / })+ ).toHaveCount(5);+ await expect(+ combo.locator('rect title', { hasText: /^Plus · / })+ ).toHaveCount(5);+ await expect(combo.locator('path title', { hasText: /^Pro$/ })).toHaveCount(+ 1+ );+ await expect(+ combo.locator('circle title', { hasText: /^Pro · / })+ ).toHaveCount(5);+});diff --git a/apps/web/src/features/block-spreadsheet/components/SpreadsheetActionMenus.tsx b/apps/web/src/features/block-spreadsheet/components/SpreadsheetActionMenus.tsxindex 8d43bdf5ea..dcb2829bb5 100644--- a/apps/web/src/features/block-spreadsheet/components/SpreadsheetActionMenus.tsx+++ b/apps/web/src/features/block-spreadsheet/components/SpreadsheetActionMenus.tsx@@ -103,7 +103,11 @@ export function InsertMenu(props: SpreadsheetToolbarProps) {><Dropdown.Group><Dropdown.GroupLabel>Chart of the selected cells</Dropdown.GroupLabel>- <For each={CHART_TYPES.filter((type) => !('more' in type))}>+ <For+ each={CHART_TYPES.filter(+ (type) => !('more' in type) && !('catalog' in type)+ )}+ >{(type) => (<Dropdown.ItemcloseOnSelect@@ -120,7 +124,11 @@ export function InsertMenu(props: SpreadsheetToolbarProps) {</Dropdown.SubTrigger><Dropdown.SubContent><Dropdown.Group>- <For each={CHART_TYPES.filter((type) => 'more' in type)}>+ <For+ each={CHART_TYPES.filter(+ (type) => 'more' in type && !('catalog' in type)+ )}+ >{(type) => (<Dropdown.ItemcloseOnSelectdiff --git a/apps/web/src/features/block-spreadsheet/core/chart-builder.test.ts b/apps/web/src/features/block-spreadsheet/core/chart-builder.test.tsindex 8ae8214b29..fe4f316884 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@@ -167,6 +167,16 @@ describe('charts of cells', () => {{ kind: 'pie', series: [chart.plots[0].series[0]] },]);expect(chartType(withChartType(chart, 'bar-stacked')!)).toBe('bar-stacked');+ expect(chartType(withChartType(chart, 'bar-percent')!)).toBe('bar-percent');+ expect(chartType(withChartType(chart, 'line-stacked')!)).toBe(+ 'line-stacked'+ );+ expect(chartType(withChartType(chart, 'line-percent')!)).toBe(+ 'line-percent'+ );+ expect(chartType(withChartType(chart, 'area-percent')!)).toBe(+ 'area-percent'+ );});it('plots against the first column for scatter and bubble charts', () => {@@ -188,9 +198,12 @@ describe('charts of cells', () => {firstRow: true,firstColumn: true,});- expect(- chartFromLayout('scatter', 'Sheet1', layout)?.plots[0].series- ).toHaveLength(2);+ const scatter = chartFromLayout('scatter', 'Sheet1', layout);+ expect(scatter?.plots[0].series).toHaveLength(2);+ // Points are not joined: a scatter has no order along a line.+ expect(scatter?.plots[0].series.every((series) => series.noLine)).toBe(+ true+ );// A bubble series reads its values, then its sizes.const bubble = chartFromLayout('bubble',@@ -220,6 +233,9 @@ describe('charts of cells', () => {'A stock chart needs three or four series: high, low and close, or open, high, low and close.');expect(chartTypeProblem('line', 2)).toBeUndefined();+ expect(chartTypeProblem('combo', 1)).toBe(+ 'A combo chart needs at least two series: columns, and a line on the secondary axis.'+ );// Open, high, low and close: bars from open to close.const prices = chartFromLayout('stock', 'Sheet1', layout(4));expect(prices?.plots[0]).toMatchObject({@@ -241,6 +257,7 @@ describe('charts of cells', () => {],references: ['A1:A3', 'B1:B3'],};+ expect(chartType(combo)).toBe('combo');const radar = withChartType(combo, 'radar-filled');expect(radar?.plots).toEqual([{ kind: 'radar', filled: true, series: [{ values: 0 }, { values: 1 }] },@@ -273,5 +290,24 @@ describe('charts of cells', () => {]);// As lines again, the series draw their lines.expect(withChartType(stock!, 'line')?.plots).toEqual(lines.plots);+ // A scatter's markers become a line again, and a combo splits the series.+ const marked = withChartType(lines, 'scatter');+ expect(marked?.plots[0].series.every((series) => series.noLine)).toBe(true);+ expect(withChartType(marked!, 'line')?.plots).toEqual(lines.plots);+ const built = chartFromLayout('combo', 'Sheet1', {+ range: { top: 0, left: 0, bottom: 3, right: 2 },+ orientation: 'columns',+ firstRow: true,+ firstColumn: true,+ });+ expect(chartType(built!)).toBe('combo');+ expect(built?.plots).toMatchObject([+ { kind: 'column', series: [{}] },+ { kind: 'line', secondary: true, series: [{}] },+ ]);+ expect(withChartType(lines, 'combo')?.plots).toEqual([+ { kind: 'column', series: [{ values: 0 }, { values: 1 }] },+ { kind: 'line', secondary: true, series: [{ values: 2 }] },+ ]);});});diff --git a/apps/web/src/features/block-spreadsheet/core/chart-builder.ts b/apps/web/src/features/block-spreadsheet/core/chart-builder.tsindex 3d998d04a3..6bf0e27d9d 100644--- a/apps/web/src/features/block-spreadsheet/core/chart-builder.ts+++ b/apps/web/src/features/block-spreadsheet/core/chart-builder.ts@@ -30,7 +30,28 @@ export const CHART_TYPES = [},{ id: 'bar', label: 'Bar', kind: 'bar' },{ id: 'bar-stacked', label: 'Stacked bar', kind: 'bar', grouping: 'stacked' },+ {+ id: 'bar-percent',+ label: '100% stacked bar',+ kind: 'bar',+ grouping: 'percentStacked',+ catalog: true,+ },{ id: 'line', label: 'Line', kind: 'line' },+ {+ id: 'line-stacked',+ label: 'Stacked line',+ kind: 'line',+ grouping: 'stacked',+ catalog: true,+ },+ {+ id: 'line-percent',+ label: '100% stacked line',+ kind: 'line',+ grouping: 'percentStacked',+ catalog: true,+ },{ id: 'area', label: 'Area', kind: 'area' },{id: 'area-stacked',@@ -38,9 +59,18 @@ export const CHART_TYPES = [kind: 'area',grouping: 'stacked',},+ {+ id: 'area-percent',+ label: '100% stacked area',+ kind: 'area',+ grouping: 'percentStacked',+ catalog: true,+ },{ id: 'pie', label: 'Pie', kind: 'pie' },{ id: 'doughnut', label: 'Doughnut', kind: 'doughnut' },{ id: 'scatter', label: 'Scatter', kind: 'scatter' },+ // Columns for every series but the last, which is a line on its own axis.+ { id: 'combo', label: 'Combo', kind: 'column', combo: true, catalog: true },{ id: 'radar', label: 'Radar', kind: 'radar', more: true },{id: 'radar-filled',@@ -58,6 +88,13 @@ export const CHART_TYPES = [kind: ChartKind;grouping?: ChartGrouping;filled?: true;+ /** Columns plus a line on the secondary axis. */+ combo?: true;+ /**+ * Listed in Edit chart. Kept out of the insert menu so that menu, and its+ * submenu, still fit on screen.+ */+ catalog?: true;more?: true;}[];export type ChartTypeId = (typeof CHART_TYPES)[number]['id'];@@ -68,6 +105,7 @@ const definitionOf = (type: ChartTypeId): ChartType | undefined =>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;/** Kinds whose series all belong in one plot. */const SINGLE_PLOT: readonly ChartKind[] = ['radar',@@ -79,11 +117,25 @@ const isRound = (kind: ChartKind) => kind === 'pie' || kind === 'doughnut';/** Kinds that plot numbers on both axes. */const isXy = (kind: ChartKind) => kind === 'scatter' || kind === 'bubble';+/** Columns together with a line, as a combination chart. */+function isCombo(chart: SheetChart): boolean {+ return (+ chart.plots.length > 1 &&+ chart.plots.every(+ (plot) => plot.kind === 'column' || plot.kind === 'line'+ ) &&+ chart.plots.some((plot) => plot.kind === 'column') &&+ chart.plots.some((plot) => plot.kind === 'line')+ );+}+/** The type a chart's first plot shows, as Macro offers it. */export function chartType(chart: SheetChart): ChartTypeId | undefined {+ if (isCombo(chart)) return 'combo';const plot = chart.plots[0];return CHART_TYPES.find((type) =>+ !comboOf(type) &&type.kind === plot?.kind &&groupingOf(type) ===(plot.grouping === 'clustered' ? undefined : plot.grouping) &&@@ -101,6 +153,8 @@ export function chartTypeProblem(): string | undefined {if (definitionOf(type)?.kind === 'stock' && (series < 3 || series > 4))return 'A stock chart needs three or four series: high, low and close, or open, high, low and close.';+ if (type === 'combo' && series < 2)+ return 'A combo chart needs at least two series: columns, and a line on the secondary axis.';}export type CellBounds = {@@ -341,9 +395,35 @@ export function chartFromLayout(...(bubble && at + 1 < lines && { sizes: add(line(at + 1)) }),...(color && { color }),// Prices are drawn by their high-low lines and bars, not series lines.- ...(definition.kind === 'stock' && { noLine: true }),+ // A scatter chart plots markers; connecting them would invent an order.+ ...((definition.kind === 'stock' || definition.kind === 'scatter') && {+ noLine: true as const,+ }),});}+ const shell = {+ ...(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 }),+ references,+ ...(previous?.colors && { colors: previous.colors }),+ };+ // The last series uses its own axis, as Excel's column-and-line chart does.+ if (comboOf(definition)) {+ const line = series.at(-1);+ if (!line || series.length < 2) return;+ return {+ ...shell,+ plots: [+ { kind: 'column', series: series.slice(0, -1) },+ { kind: 'line', secondary: true, series: [line] },+ ],+ };+ }const plot: ChartPlot = {kind: definition.kind,...('grouping' in definition && { grouping: definition.grouping }),@@ -354,17 +434,7 @@ export function chartFromLayout(}),series,};- return {- ...(previous?.title && { title: previous.title }),- ...(previous- ? previous.legend && { legend: previous.legend }- : (series.length > 1 ||- isRound(definition.kind) ||- definition.kind === 'surface') && { legend: 'bottom' as const }),- plots: [plot],- references,- ...(previous?.colors && { colors: previous.colors }),- };+ return { ...shell, plots: [plot] };}/** How many series a block of cells makes in a chart of a type. */@@ -437,10 +507,11 @@ export function withChartType(const definition = definitionOf(type);if (!definition) return chart;const kind = definition.kind;- // Stock series have no lines of their own; other kinds draw theirs.+ // Stock and scatter series have no lines of their own; other kinds draw theirs.const shown = (series: ChartSeries, from: ChartKind): ChartSeries => {- if (kind === 'stock') return { ...series, noLine: true };- if (from !== 'stock') return series;+ if (kind === 'stock' || kind === 'scatter')+ return { ...series, noLine: true };+ if (from !== 'stock' && from !== 'scatter') return series;const { noLine: _noLine, ...rest } = series;return rest;};@@ -448,6 +519,17 @@ export function withChartType(plot.series.map((series) => shown(series, plot.kind)));if (chartTypeProblem(type, all.length)) return;+ if (comboOf(definition)) {+ const line = all.at(-1);+ if (!line) return;+ return {+ ...chart,+ plots: [+ { kind: 'column', series: all.slice(0, -1) },+ { kind: 'line', secondary: true, series: [line] },+ ],+ };+ }const flags = (count: number) => ({...('grouping' in definition && { grouping: definition.grouping }),...(filledOf(definition) && { filled: true as const }),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.tsindex 11d97b4153..294acbb2b6 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@@ -104,6 +104,51 @@ describe('chart layout', () => {expect(heights[1]).toBeCloseTo(heights[2]);});+ it('fills a 100% stack to the axis, positives and negatives apart', () => {+ const at = (label: string) =>+ of(shapes, 'text').find((shape) => shape.text === label)?.y;+ const shapes = chartScene(+ data(+ [+ {+ kind: 'column',+ grouping: 'percentStacked',+ series: [series('A', [20, 30]), series('B', [30, -10])],+ },+ ],+ { categories: ['Jan', 'Feb'] }+ ),+ 400,+ 300+ ).shapes;+ const span = Math.abs((at('100%') ?? 0) - (at('0%') ?? 0));+ const bar = (tip: string) =>+ of(shapes, 'rect').find((shape) => shape.tip === tip);+ // Jan is 20 + 30, both positive, so the two bars together are the axis.+ expect(+ (bar('A · Jan: 20')?.height ?? 0) + (bar('B · Jan: 30')?.height ?? 0)+ ).toBeCloseTo(span);+ // Feb's positive series is the whole axis, and its negative series mirrors it.+ expect(bar('A · Feb: 30')?.height).toBeCloseTo(span);+ expect(bar('B · Feb: -10')?.height).toBeCloseTo(+ Math.abs((at('-100%') ?? 0) - (at('0%') ?? 0))+ );+ const line = chartScene(+ data([+ {+ kind: 'line',+ grouping: 'percentStacked',+ series: [series('A', [10, 10, 10]), series('B', [30, 30, 30])],+ },+ ]),+ 400,+ 300+ ).shapes;+ const hundred = of(line, 'text').find((shape) => shape.text === '100%');+ const top = of(line, 'circle').find((shape) => shape.tip === 'B · Jan: 30');+ expect(top?.y).toBeCloseTo(hundred?.y ?? Number.NaN);+ });+it('labels a secondary axis on the right and keeps series without fill out of the legend', () => {const shapes = chartScene(data(@@ -209,6 +254,18 @@ describe('radar, bubble, stock and contour charts', () => {const [small, large] = of(shapes, 'circle');expect(large.r / small.r).toBeCloseTo(2);expect(large.tip).toBe('A: (2, 20), 4');+ const marked = chartScene(+ data([+ {+ kind: 'scatter',+ series: [series('A', [10, 20], { x: [1, 2], noLine: true })],+ },+ ]),+ 400,+ 300+ ).shapes;+ expect(of(marked, 'circle')).toHaveLength(2);+ expect(of(marked, 'path').filter((path) => path.tip)).toHaveLength(0);expect(large.x).toBeGreaterThan(small.x);expect(large.y).toBeLessThan(small.y);});diff --git a/apps/web/src/features/block-spreadsheet/core/chart-scene.ts b/apps/web/src/features/block-spreadsheet/core/chart-scene.tsindex 6e7e069b06..2a5c39d57c 100644--- a/apps/web/src/features/block-spreadsheet/core/chart-scene.ts+++ b/apps/web/src/features/block-spreadsheet/core/chart-scene.ts@@ -89,14 +89,14 @@ function extent(plots: ChartPlotData[], categories: number): [number, number] {};for (const plot of plots) {if (plot.grouping === 'percentStacked') {+ // Each category fills to 100% of its positive values and -100% of its+ // negative values, so the axis always includes both ends that occur.see(0);- see(- plot.series.some((series) =>- series.values.some((value) => (value ?? 0) < 0)- )- ? -1- : 1- );+ const values = plot.series.flatMap((series) => series.values);+ const hasPositive = values.some((value) => (value ?? 0) > 0);+ const hasNegative = values.some((value) => (value ?? 0) < 0);+ if (hasPositive || !hasNegative) see(1);+ if (hasNegative) see(-1);continue;}if (plot.grouping === 'stacked')@@ -293,13 +293,22 @@ export function chartScene();const count = Math.max(1, data.categories.length);const valueScale = (plots: ChartPlotData[], range: [number, number]) => {- const scale = scaleLinear()- .domain(extent(plots, count))- .range(range)- .nice(5);+ // A 100% axis is already 0–100% (and -100% when negatives occur). Nice+ // rounding would draw ticks past the stack.+ const percent =+ plots.length > 0 &&+ plots.every((plot) => plot.grouping === 'percentStacked');+ const scale = scaleLinear().domain(extent(plots, count)).range(range);+ if (!percent) scale.nice(5);const ticks = scale.ticks(5);const step = ticks.length > 1 ? ticks[1] - ticks[0] : 1;- return { scale, ticks, format: tickFormat(sample(plots), step) };+ const format = tickFormat(sample(plots), step);+ return {+ scale,+ ticks,+ format,+ axisFormat: percent ? tickFormat('0%', step) : format,+ };};// Axis label space, measured with the widest tick label.const measure = (plots: ChartPlotData[]) => {@@ -351,7 +360,7 @@ export function chartScene(type: 'text',x: at,y: bottom + font * 1.2,- text: values.format(tick),+ text: values.axisFormat(tick),anchor: 'middle',size: font,role: 'label',@@ -360,7 +369,7 @@ export function chartScene(type: 'text',x: left - 4 * scale,y: at,- text: values.format(tick),+ text: values.axisFormat(tick),anchor: 'end',size: font,role: 'label',@@ -377,7 +386,7 @@ export function chartScene(type: 'text',x: right + 4 * scale,y: secondaryValues.scale(tick),- text: secondaryValues.format(tick),+ text: secondaryValues.axisFormat(tick),anchor: 'start',size: font,role: 'label',@@ -506,6 +515,33 @@ 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+ * direction fills the axis to 100%, as Excel, Google Sheets and LibreOffice+ * draw it.+ */+function percentShare(+ raw: number,+ mass: { positive: number; negative: number }+): number {+ if (raw > 0) return mass.positive ? raw / mass.positive : 0;+ if (raw < 0) return mass.negative ? raw / Math.abs(mass.negative) : 0;+ return 0;+}++function categoryMass(series: ChartSeriesData[], index: number) {+ let positive = 0;+ let negative = 0;+ for (const item of series) {+ const value = item.values[index];+ if (value === null || value === undefined) continue;+ if (value > 0) positive += value;+ else if (value < 0) negative += value;+ }+ return { positive, negative };+}+function bars(shapes: ChartShape[],plot: ChartPlotData,@@ -521,18 +557,19 @@ function bars(const groups = stacked ? 1 : plot.series.length;// Excel's default gap is 150% of a bar's width.const barWidth = band / (groups + 1.5);+ const masses = data.categories.map((_, index) =>+ categoryMass(plot.series, index)+ );data.categories.forEach((category, index) => {let positive = 0;let negative = 0;- const total = plot.series.reduce(- (sum, series) => sum + Math.abs(series.values[index] ?? 0),- 0- );plot.series.forEach((series, position) => {const raw = series.values[index];if (raw === null || raw === undefined) return;const value =- plot.grouping === 'percentStacked' ? (total ? raw / total : 0) : raw;+ plot.grouping === 'percentStacked'+ ? percentShare(raw, masses[index])+ : raw;let from = 0;let to = value;if (stacked) {@@ -585,35 +622,45 @@ function lines(format: (value: number) => string,zoom: number) {- const stacked =- plot.grouping === 'stacked' || plot.grouping === 'percentStacked';- const totals = data.categories.map((_, index) =>- plot.series.reduce(- (sum, series) => sum + Math.abs(series.values[index] ?? 0),- 0- )+ const percent = plot.grouping === 'percentStacked';+ const stacked = plot.grouping === 'stacked' || percent;+ // A stacked line or area is one running total. A 100% stack keeps+ // positives and negatives on separate piles, the same way bars do.+ const running = data.categories.map(() => 0);+ const positive = data.categories.map(() => 0);+ const negative = data.categories.map(() => 0);+ const masses = data.categories.map((_, index) =>+ categoryMass(plot.series, index));- const base = data.categories.map(() => 0);const markers = data.categories.length <= 40;for (const series of plot.series) {const points = series.values.map((raw, index) => {if (raw === null) return undefined;- let value =- plot.grouping === 'percentStacked'- ? totals[index]- ? raw / totals[index]- : 0+ const baseline = percent+ ? raw >= 0+ ? positive[index]+ : negative[index]+ : stacked+ ? running[index]+ : 0;+ const value = percent+ ? baseline + percentShare(raw, masses[index])+ : stacked+ ? baseline + raw: raw;- if (stacked) value += base[index];- return { x: center(index), y: scale(value), raw, index };+ return {+ x: center(index),+ y: scale(value),+ from: scale(baseline),+ raw,+ index,+ };});if (plot.kind === 'area' && !series.noFill) {const present = points.filter((point) => point !== undefined);if (present.length) {const floor = present- .map(- (point) => `L${point.x},${scale(stacked ? base[point.index] : 0)}`- )+ .map((point) => `L${point.x},${point.from}`).reverse().join('');shapes.push({@@ -627,12 +674,14 @@ function lines(}if (stacked)series.values.forEach((raw, index) => {- base[index] +=- plot.grouping === 'percentStacked'- ? totals[index]- ? (raw ?? 0) / totals[index]- : 0- : (raw ?? 0);+ if (raw === null || raw === undefined) return;+ if (!percent) {+ running[index] += raw;+ return;+ }+ const share = percentShare(raw, masses[index]);+ if (share >= 0) positive[index] += share;+ else negative[index] += share;});if (plot.kind !== 'line') continue;// Gaps in the data break the line, as Excel shows blanks.diff --git a/apps/web/src/features/block-spreadsheet/core/xlsx-drawings.test.ts b/apps/web/src/features/block-spreadsheet/core/xlsx-drawings.test.tsindex 8c23f9e7a8..beeae006cf 100644--- a/apps/web/src/features/block-spreadsheet/core/xlsx-drawings.test.ts+++ b/apps/web/src/features/block-spreadsheet/core/xlsx-drawings.test.ts@@ -612,6 +612,70 @@ describe('radar, bubble, stock and contour charts', () => {);});+ it('writes stacked, scatter, line and combo charts as Excel opens them', () => {+ const part = (chart: SheetChart) => chartPart(chart, () => undefined);+ const percent = part({+ plots: [+ {+ kind: 'bar',+ grouping: 'percentStacked',+ series: columns(['B', 'C']).series,+ },+ ],+ references: columns(['B', 'C']).references,+ });+ expect(percent).toContain(+ '<c:barDir val="bar"/><c:grouping val="percentStacked"/>'+ );+ expect(percent).toContain('formatCode="0%"');+ expect(reread(percent)?.plots[0].grouping).toBe('percentStacked');+ const stacked = part({+ plots: [+ {+ kind: 'line',+ grouping: 'stacked',+ series: columns(['B', 'C']).series,+ },+ ],+ references: columns(['B', 'C']).references,+ });+ expect(stacked).toContain('<c:grouping val="stacked"/>');+ expect(stacked).toContain('<c:marker><c:symbol val="circle"/>');+ expect(reread(stacked)?.plots[0]).toMatchObject({+ kind: 'line',+ grouping: 'stacked',+ });+ const points = part({+ plots: [+ {+ kind: 'scatter',+ series: [{ categories: 0, values: 1, noLine: true }],+ },+ ],+ references: [cells('A'), cells('B')],+ });+ expect(points).toContain('<c:scatterStyle val="marker"/>');+ expect(reread(points)?.plots[0].series[0].noLine).toBe(true);+ const combo = part({+ plots: [+ { kind: 'column', series: [columns(['B']).series[0]] },+ {+ kind: 'line',+ secondary: true,+ series: [columns(['C']).series[0]],+ },+ ],+ references: [...columns(['B']).references, ...columns(['C']).references],+ });+ expect(combo).toContain('<c:barChart>');+ expect(combo).toContain('<c:lineChart>');+ expect(combo).toContain('<c:crosses val="max"/>');+ expect(reread(combo)?.plots).toMatchObject([+ { kind: 'column' },+ { kind: 'line', secondary: true },+ ]);+ });+it('writes a stock chart Excel cannot open as lines', () => {const part = chartPart({diff --git a/apps/web/src/features/block-spreadsheet/core/xlsx-drawings.ts b/apps/web/src/features/block-spreadsheet/core/xlsx-drawings.tsindex 84e59bd30d..b7b63b7ea7 100644--- a/apps/web/src/features/block-spreadsheet/core/xlsx-drawings.ts+++ b/apps/web/src/features/block-spreadsheet/core/xlsx-drawings.ts@@ -1127,9 +1127,11 @@ function generatedChart(chart: SheetChart, values: ChartValues): string {}`: `<c:val>${reference(value.values, 'numRef')}</c:val>`;const marker =- plot.kind === 'line' || plot.kind === 'stock'+ plot.kind === 'stock'? '<c:marker><c:symbol val="none"/></c:marker>'- : plot.kind === 'scatter' || (plot.kind === 'radar' && !plot.filled)+ : plot.kind === 'line' ||+ plot.kind === 'scatter' ||+ (plot.kind === 'radar' && !plot.filled)? '<c:marker><c:symbol val="circle"/><c:size val="5"/></c:marker>': '';const inverted =@@ -1176,7 +1178,7 @@ function generatedChart(chart: SheetChart, values: ChartValues): string {.with('scatter',() =>- `<c:scatterChart><c:scatterStyle val="lineMarker"/><c:varyColors val="0"/>${series}${axisIds}</c:scatterChart>`+ `<c:scatterChart><c:scatterStyle val="${plot.series.every((value) => value.noLine) ? 'marker' : 'lineMarker'}"/><c:varyColors val="0"/>${series}${axisIds}</c:scatterChart>`).with('radar',diff --git a/docs/AGENT_GUIDE/documents.md b/docs/AGENT_GUIDE/documents.mdindex 10c0e94ef5..bbc7b3650e 100644--- a/docs/AGENT_GUIDE/documents.md+++ b/docs/AGENT_GUIDE/documents.md@@ -122,17 +122,23 @@ shows the rule's message in the footer, and a "stop" rule keeps the previous valA red corner marks a cell with a note; selecting the cell shows the note, and anyinput message, beside it.-Images and charts (column, bar, line, area, pie, doughnut, scatter, radar,-bubble, stock and surface, drawn as a contour) are drawn over their cells and-move with them; charts redraw as the cells they read change. Each is a `figure`-named after the chart title ("Chart: Revenue") or the image description. The-toolbar's **Insert chart or image** menu (chart icon) 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; a stock chart needs three or four series (high, low, close, with open-first for up-down bars), and a bubble chart reads x values from the first-column, then values and sizes in pairs. Imported shapes, text boxes, lines,+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;+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+every series but the last as columns and the last series as a line on a second+axis. Each is a `figure` named after the chart title ("Chart: Revenue") or the+image description. The toolbar's **Insert chart or image** menu (chart icon)+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+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,groups and SmartArt are drawn too, as `figure`s named after their text (ortheir name, such as "Straight Connector 2"); a shape linked to a cell shows thecell's value. They move, size and delete like images, and download as Excel