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.

fix(sheets): keep cross-sheet formula references working from any row (#8129)

teo196be87ed975
diff --git a/apps/web/src/features/block-spreadsheet/README.md b/apps/web/src/features/block-spreadsheet/README.md
index b43ff31599..7ea013d894 100644
--- a/apps/web/src/features/block-spreadsheet/README.md
+++ b/apps/web/src/features/block-spreadsheet/README.md
@@ -256,7 +256,10 @@ Formula point selection keeps the original cell and textarea focused while a
pointer drag inserts or replaces an A1 reference at the caret. Only the local
draft and a single dashed reference overlay update during dragging; the shared
document and calculation worker receive the formula on commit. Quoted text and
-completed expressions retain normal click-away behavior.
+completed expressions retain normal click-away behavior. Changing tabs while a
+formula awaits a reference keeps its draft, even when the formula's row is past
+the other sheet's last row, and every tab change scrolls to that sheet's own
+selection.
Selection does not recalculate the workbook. A bounded row window mounts visible
rows and a small buffer, keeping the active editor mounted while scrolling. Shared
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 0926801efb..9a69578d6b 100644
--- a/apps/web/src/features/block-spreadsheet/browser-test/README.md
+++ b/apps/web/src/features/block-spreadsheet/browser-test/README.md
@@ -112,4 +112,4 @@ explicit test document/socket query parameters are supplied.
## Editor interaction regressions
-`editor-interactions.browser.e2e.ts` mounts the real global hotkey listener to verify that selected-cell typing and arrows beat app navigation shortcuts. It also exercises multi-header drag/Shift selection, persistent row resizing and auto-fit, cross-sheet formula reference picking, and numeric/month-end date fill with undo. `formatting.browser.e2e.ts` checks mixed whole-column formatting, style persistence, viewport stability, a styled cell's pixels staying the same when selected, in a range and edited, and percentage entry through both editors against the real calculation worker.
+`editor-interactions.browser.e2e.ts` mounts the real global hotkey listener to verify that selected-cell typing and arrows beat app navigation shortcuts. It also exercises multi-header drag/Shift selection, persistent row resizing and auto-fit, cross-sheet formula reference picking (including after comparison operators, from a row past the other sheet's end), and numeric/month-end date fill with undo. `formatting.browser.e2e.ts` checks mixed whole-column formatting, style persistence, viewport stability, a styled cell's pixels staying the same when selected, in a range and edited, and percentage entry through both editors against the real calculation worker.
diff --git a/apps/web/src/features/block-spreadsheet/browser-test/editor-interactions.browser.e2e.ts b/apps/web/src/features/block-spreadsheet/browser-test/editor-interactions.browser.e2e.ts
index e1adab7b43..015fc99f99 100644
--- a/apps/web/src/features/block-spreadsheet/browser-test/editor-interactions.browser.e2e.ts
+++ b/apps/web/src/features/block-spreadsheet/browser-test/editor-interactions.browser.e2e.ts
@@ -168,6 +168,52 @@ test('picks a range on a second sheet and commits the formula back to its origin
expect(sheets[1].cells.A1.value).toBe('12');
});
+test('picks a reference after a comparison operator on a shorter sheet and returns on Enter', async ({
+ page,
+}) => {
+ await page.getByRole('button', { name: 'Add sheet', exact: true }).click();
+ await edit(page, 'B4', '25');
+ await page.getByRole('tab', { name: 'Sheet2', exact: true }).dblclick();
+ await page.getByRole('textbox', { name: 'Sheet name' }).fill('Other Sheet');
+ await page.getByRole('button', { name: 'Save name' }).click();
+ await page.getByRole('tab', { name: 'Sheet1', exact: true }).click();
+ // The formulas sit below the other sheet's last row.
+ await page.getByRole('button', { name: 'Add 100 rows', exact: true }).click();
+ const goTo = page.getByRole('textbox', { name: 'Go to cell' });
+ const formula = page.getByRole('textbox', {
+ name: 'Formula bar',
+ exact: true,
+ });
+ for (const [address, operator] of [
+ ['C250', '<'],
+ ['C251', '>='],
+ ['C252', '<>'],
+ ]) {
+ await goTo.fill(address);
+ await goTo.press('Enter');
+ await page.keyboard.type(`=IF(B2 ${operator}`);
+ await page.getByRole('tab', { name: 'Other Sheet', exact: true }).click();
+ await expect(formula).toHaveValue(`=IF(B2 ${operator}`);
+ await page.locator('[data-address="B4"]').click();
+ await expect(formula).toHaveValue(`=IF(B2 ${operator}'Other Sheet'!B4`);
+ await expect(formula).toBeFocused();
+ await page.keyboard.type(',1,0)');
+ await page.keyboard.press('Enter');
+ await expect(
+ page.getByRole('tab', { name: 'Sheet1', exact: true })
+ ).toHaveAttribute('aria-selected', 'true');
+ }
+ await expect(page.locator('[data-address="C252"]')).toHaveText('1');
+ await expect(page.locator('[data-address="C251"]')).toHaveText('0');
+ await expect(page.locator('[data-address="C250"]')).toHaveText('1');
+ const cells = await page.evaluate(
+ () => window.spreadsheetFixture.snapshot()[0].cells
+ );
+ expect(cells.C250.value).toBe("=IF(B2 <'Other Sheet'!B4,1,0)");
+ expect(cells.C251.value).toBe("=IF(B2 >='Other Sheet'!B4,1,0)");
+ expect(cells.C252.value).toBe("=IF(B2 <>'Other Sheet'!B4,1,0)");
+});
+
test('drag fill continues numbers and month-end dates and undo restores the empty destination', async ({
page,
}) => {
diff --git a/apps/web/src/features/block-spreadsheet/core/formula-reference.test.ts b/apps/web/src/features/block-spreadsheet/core/formula-reference.test.ts
index bc29bb38aa..047c3f18e9 100644
--- a/apps/web/src/features/block-spreadsheet/core/formula-reference.test.ts
+++ b/apps/web/src/features/block-spreadsheet/core/formula-reference.test.ts
@@ -8,14 +8,22 @@ import {
import { SPREADSHEET_MAX_ROWS } from './spreadsheet-document';
describe('formula reference slots', () => {
- it.each(['=', '=SUM(', '=A1+', '=IF(A1>0, ', '=SUM(B1:B4,'])(
- 'inserts an operand at the end of %s',
- (text) => {
- expect(
- formulaReferenceSlot(text, { start: text.length, end: text.length })
- ).toEqual({ start: text.length, end: text.length });
- }
- );
+ it.each([
+ '=',
+ '=SUM(',
+ '=A1+',
+ '=IF(A1>0, ',
+ '=SUM(B1:B4,',
+ '=IF(D2 <',
+ '=IF(D2<=',
+ '=IF(D2 >= ',
+ '=IF(D2<>',
+ '=D2=',
+ ])('inserts an operand at the end of %s', (text) => {
+ expect(
+ formulaReferenceSlot(text, { start: text.length, end: text.length })
+ ).toEqual({ start: text.length, end: text.length });
+ });
it('replaces an existing mixed reference/range, preserving surrounding formula text', () => {
expect(
diff --git a/apps/web/src/features/block-spreadsheet/primitives/create-grid-controller.test.ts b/apps/web/src/features/block-spreadsheet/primitives/create-grid-controller.test.ts
index f9a24bdb97..31f2442029 100644
--- a/apps/web/src/features/block-spreadsheet/primitives/create-grid-controller.test.ts
+++ b/apps/web/src/features/block-spreadsheet/primitives/create-grid-controller.test.ts
@@ -1,5 +1,5 @@
// @vitest-environment jsdom
-import { createRoot, createSignal } from 'solid-js';
+import { createMemo, createRoot, createSignal } from 'solid-js';
import { afterEach, describe, expect, it, vi } from 'vitest';
import type { CellCopy } from '../core/calculation';
import {
@@ -649,6 +649,9 @@ function crossSheetSetup() {
},
});
const [canEdit, setCanEdit] = createSignal(true);
+ // Subscribing before the controller makes row-count reactions run before
+ // its tab-change handling, an order the store's subscriptions can produce.
+ const rowCount = createMemo(() => (sheetId() === 'summary' ? 300 : 200));
const setSheetCells = vi.fn((id: string, edits: SpreadsheetCellEdits) => {
if (!sheets().some((sheet) => sheet.id === id)) return;
const cells = { ...books()[id] };
@@ -665,6 +668,7 @@ function crossSheetSetup() {
setSheetCells,
setCells: (edits) => setSheetCells(sheetId(), edits),
canEdit,
+ rowCount,
undo: () => {},
redo: () => {},
});
@@ -704,6 +708,25 @@ describe('cross-sheet formula editing', () => {
expect(view.grid.activeAddress()).toBe('B4');
});
+ it('keeps a draft from a row the picked sheet does not have and returns to it on commit', () => {
+ const view = crossSheetSetup();
+ view.grid.select({ row: 249, column: 2 });
+ view.grid.beginEdit('cell', '=IF(D2 <');
+ view.grid.switchSheet('inputs');
+ expect(view.sheetId()).toBe('inputs');
+ expect(view.grid.editing()).toBe('formula');
+ expect(view.grid.editingAddress()).toBe('C250');
+ expect(view.grid.beginReference({ row: 3, column: 1 })).toBe(true);
+ view.grid.endReference();
+ expect(view.grid.draft()).toBe("=IF(D2 <'Owner''s budget'!B4");
+ view.grid.commit();
+ expect(view.books().summary.C250.value).toBe(
+ "=IF(D2 <'Owner''s budget'!B4"
+ );
+ expect(view.sheetId()).toBe('summary');
+ expect(view.grid.activeAddress()).toBe('C250');
+ });
+
it('replaces a prior reference when choosing another sheet and omits the qualifier on the origin', () => {
const view = crossSheetSetup();
view.grid.beginEdit('formula', '=');
diff --git a/apps/web/src/features/block-spreadsheet/primitives/create-grid-controller.ts b/apps/web/src/features/block-spreadsheet/primitives/create-grid-controller.ts
index c8537559cd..ed0c6cc685 100644
--- a/apps/web/src/features/block-spreadsheet/primitives/create-grid-controller.ts
+++ b/apps/web/src/features/block-spreadsheet/primitives/create-grid-controller.ts
@@ -239,16 +239,22 @@ export function createGridController(source: GridSource) {
// A local undo or remote layout operation can remove the selected empty row.
// End its draft before moving focus so it cannot commit into a different cell.
+ // A tab change bounds the new sheet's selection itself, and may keep a
+ // cross-sheet formula draft that this would otherwise cancel.
createEffect(
- on(rowCount, (count, previous) => {
- // A fill preview can extend past the current selection. Shrinking the
- // sheet invalidates that pending copy even when selection stays in bounds.
- if (previous !== undefined && count < previous) cancelPendingCopy();
- const current = selection();
- if (current.anchor.row < count && current.focus.row < count) return;
- cancel();
- selectRange(current.anchor, current.focus);
- })
+ on(
+ () => [source.sheetId?.(), rowCount()] as const,
+ ([sheetId, count], previous) => {
+ if (previous && previous[0] !== sheetId) return;
+ // A fill preview can extend past the current selection. Shrinking the
+ // sheet invalidates that pending copy even when selection stays in bounds.
+ if (previous && count < previous[1]) cancelPendingCopy();
+ const current = selection();
+ if (current.anchor.row < count && current.focus.row < count) return;
+ cancel();
+ selectRange(current.anchor, current.focus);
+ }
+ )
);
function cancelPendingCopy() {
diff --git a/apps/web/src/features/block-spreadsheet/views/SpreadsheetEditor.tsx b/apps/web/src/features/block-spreadsheet/views/SpreadsheetEditor.tsx
index 83c7bd92b1..e18dd40964 100644
--- a/apps/web/src/features/block-spreadsheet/views/SpreadsheetEditor.tsx
+++ b/apps/web/src/features/block-spreadsheet/views/SpreadsheetEditor.tsx
@@ -350,6 +350,13 @@ export function SpreadsheetEditor(props: {
gridElement
?.querySelector(`[data-address="${cellAddress(grid.selection().focus)}"]`)
?.scrollIntoView({ block: 'nearest', inline: 'nearest' });
+ // One grid shows every sheet, so each opens scrolled to its own selection,
+ // including while a formula draft picks a reference there or returns home.
+ createEffect(
+ on(props.store.activeSheetId, () => queueMicrotask(revealSelection), {
+ defer: true,
+ })
+ );
const goalSeek = createGoalSeek({
sheets: () =>
props.store.workbook().map((sheet) => ({
@@ -1132,25 +1139,16 @@ export function SpreadsheetEditor(props: {
actions.clearNotice();
workbookActions.clearNotice();
if (grid.editing()) queueMicrotask(restoreEditorFocus);
- else {
- focusGrid();
- queueMicrotask(revealSelection);
- }
+ else focusGrid();
}}
onAdd={() => {
workbookActions.addSheet();
- queueMicrotask(() => {
- focusGrid();
- revealSelection();
- });
+ queueMicrotask(focusGrid);
}}
onRename={(id) => workbookActions.openSheetDialog('rename', id)}
onDuplicate={(id) => {
workbookActions.duplicateSheet(id);
- queueMicrotask(() => {
- focusGrid();
- revealSelection();
- });
+ queueMicrotask(focusGrid);
}}
onDelete={(id) => workbookActions.openSheetDialog('delete', id)}
onMove={workbookActions.moveSheet}
diff --git a/docs/agent-guide/documents.md b/docs/agent-guide/documents.md
index c94e2deeee..6a0ec9dbc6 100644
--- a/docs/agent-guide/documents.md
+++ b/docs/agent-guide/documents.md
@@ -262,10 +262,12 @@ to `=SUM(B4:B7` without committing or moving the active cell. A dashed outline s
the referenced range. Release, type `)`, and press Enter to calculate. This works
in both the cell editor and formula bar, including reverse drags, replacement of
an existing reference, and subsequent arguments after a comma or operator. To reference another sheet,
-click its tab while the formula is awaiting a reference, then click or drag the
-source cells. The draft stays in the formula bar; Enter commits it to the original
-sheet and cell. Names with spaces are quoted automatically. Escape cancels and
-returns to the original sheet.
+click its tab while the formula is awaiting a reference (for example after
+`=IF(D2 <`), then click or drag the source cells. The other sheet opens at its
+own selection, even when the formula's row is past that sheet's last row. The
+draft stays in the formula bar; Enter commits it to the original sheet and cell.
+Names with spaces are quoted automatically. Escape cancels and returns to the
+original sheet.
While a formula is being edited, each cell or range it refers to, including whole
columns or rows such as `D:D`, is outlined in its own color on the grid, and the
reference text in both editors uses the same color. A repeated reference keeps