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): allow inserting and deleting rows and columns in connected workbooks (#7684)

teoe5be74abd585
diff --git a/apps/web/src/features/block-spreadsheet/README.md b/apps/web/src/features/block-spreadsheet/README.md
index 74cb39a72c..d33622f340 100644
--- a/apps/web/src/features/block-spreadsheet/README.md
+++ b/apps/web/src/features/block-spreadsheet/README.md
@@ -119,8 +119,12 @@ Rows and columns currently have fixed positions. Range sorting copies whole rows
within a selected rectangle and translates their relative formulas through IronCalc.
It validates that the sheet, selection, permission, and editing state have not changed
before committing. Other formulas keep their A1 references; they do not follow moved
-records. Structural insertion/deletion still needs stable identities and formula
-reference transformation across concurrent operations.
+records. Inserting or deleting rows and columns rewrites the moved cells, references
+and layout in one commit, under the same revision check. Saved workbooks allow it
+only while connected, so an offline coordinate shift cannot merge later over
+collaborators' edits. Rows and columns have no stable identities: an edit that a
+collaborator commits to old coordinates after the shift arrives still lands at
+those coordinates.
### Workbook sheets
diff --git a/apps/web/src/features/block-spreadsheet/browser-test/collaboration.browser.e2e.ts b/apps/web/src/features/block-spreadsheet/browser-test/collaboration.browser.e2e.ts
index 1e70020594..48ef1f913a 100644
--- a/apps/web/src/features/block-spreadsheet/browser-test/collaboration.browser.e2e.ts
+++ b/apps/web/src/features/block-spreadsheet/browser-test/collaboration.browser.e2e.ts
@@ -75,9 +75,7 @@ test.afterAll(async () => {
await server?.dispose();
});
-test('live edits, named colored ranges, offline recovery and departing cursors', async ({
- browser,
-}) => {
+async function seedDocument() {
const id = crypto.randomUUID();
const seeded = await server.dispatchFetch(
`${serverUrl}document/${id}/initialize`,
@@ -94,6 +92,68 @@ test('live edits, named colored ranges, offline recovery and departing cursors',
}
);
expect(seeded.status).toBe(200);
+ return id;
+}
+
+async function openConnected(page: Page, id: string, user: string) {
+ const socket = `${serverUrl.replace('http:', 'ws:')}document/${id}/connect?token=${token(id, user)}`;
+ await page.goto(
+ `http://localhost:3017/?${new URLSearchParams({ document: id, socket, user: `macro|${user}@example.com` })}`
+ );
+ await expect(page.locator('[data-address="A1"]')).toBeVisible();
+ await expect
+ .poll(() =>
+ page.evaluate(() => window.spreadsheetFixture.connectionStatus())
+ )
+ .toBe('connected');
+}
+
+test('connected workbooks insert rows and columns for every collaborator', async ({
+ browser,
+}) => {
+ const id = await seedDocument();
+ const contexts = await Promise.all(
+ ['alice', 'bob'].map(() => browser.newContext())
+ );
+ const [alice, bob] = await Promise.all(
+ contexts.map((context) => context.newPage())
+ );
+ try {
+ await openConnected(alice, id, 'alice');
+ await openConnected(bob, id, 'bob');
+ await alice.locator('[data-address="A1"]').dblclick();
+ await alice
+ .getByRole('textbox', { name: 'Edit A1', exact: true })
+ .fill('Founder');
+ await alice.keyboard.press('Enter');
+ await expect(bob.locator('[data-address="A1"]')).toHaveText('Founder');
+
+ await alice
+ .getByRole('button', { name: 'Select row 1', exact: true })
+ .click({ button: 'right' });
+ await alice
+ .getByRole('menuitem', { name: 'Insert 1 row above', exact: true })
+ .click();
+ await expect(bob.locator('[data-address="A2"]')).toHaveText('Founder');
+ await expect(bob.locator('[data-address="A1"]')).toHaveText('');
+
+ await bob
+ .getByRole('button', { name: 'Select column A', exact: true })
+ .click({ button: 'right' });
+ await bob
+ .getByRole('menuitem', { name: 'Insert 1 column left', exact: true })
+ .click();
+ await expect(alice.locator('[data-address="B2"]')).toHaveText('Founder');
+ await expect(alice.locator('[data-address="A2"]')).toHaveText('');
+ } finally {
+ await Promise.all(contexts.map((context) => context.close()));
+ }
+});
+
+test('live edits, named colored ranges, offline recovery and departing cursors', async ({
+ browser,
+}) => {
+ const id = await seedDocument();
const contexts = await Promise.all(
['alice', 'bob', 'carol'].map(() => browser.newContext())
);
diff --git a/apps/web/src/features/block-spreadsheet/components/SpreadsheetHeaderMenu.tsx b/apps/web/src/features/block-spreadsheet/components/SpreadsheetHeaderMenu.tsx
index 0e5efcdc51..b847d44f0e 100644
--- a/apps/web/src/features/block-spreadsheet/components/SpreadsheetHeaderMenu.tsx
+++ b/apps/web/src/features/block-spreadsheet/components/SpreadsheetHeaderMenu.tsx
@@ -92,7 +92,7 @@ export function SpreadsheetHeaderMenu(props: {
)}
<Show when={!props.canChangeStructure && !props.readonly}>
<div class="max-w-64 px-3 py-1 text-xs text-ink-muted">
- Insert and delete are available in local workbooks.
+ Reconnect to insert or delete rows or columns.
</div>
</Show>
{item(`Delete ${label()}`, 'delete')}
diff --git a/apps/web/src/features/block-spreadsheet/primitives/create-spreadsheet-store.test.ts b/apps/web/src/features/block-spreadsheet/primitives/create-spreadsheet-store.test.ts
index 22e515ca91..7d5744aba7 100644
--- a/apps/web/src/features/block-spreadsheet/primitives/create-spreadsheet-store.test.ts
+++ b/apps/web/src/features/block-spreadsheet/primitives/create-spreadsheet-store.test.ts
@@ -65,7 +65,46 @@ describe('spreadsheet store', () => {
doc.free();
});
- it.each(['connected', 'connecting', 'offline'] as const)(
+ it('shifts coordinates in a connected workbook and keeps inserted columns', async () => {
+ const doc = new LoroDoc();
+ writeSpreadsheetCells(doc, { A1: { value: 'Name' }, B1: { value: '=A1' } });
+ let dispose = () => {};
+ const store = createRoot((cleanup) => {
+ dispose = cleanup;
+ return createSpreadsheetStore({
+ canEdit: () => true,
+ source: {
+ doc: () => doc,
+ ready: () => true,
+ error: () => undefined,
+ status: () => 'connected',
+ peers: () => [],
+ setSelection: () => {},
+ },
+ });
+ });
+ await Promise.resolve();
+ expect(store.canChangeStructure()).toBe(true);
+ const before = structuredClone(store.workbook());
+ const columns = before[0].layout.columnCount;
+ const next = before.map((sheet) => ({
+ ...sheet,
+ cells: { B1: sheet.cells.A1, C1: { ...sheet.cells.B1, value: '=B1' } },
+ layout: { ...sheet.layout, columnCount: columns + 1 },
+ }));
+ store.applyStructure(before, next, store.revision());
+ expect(store.cells().A1).toBeUndefined();
+ expect(store.cells().B1.value).toBe('Name');
+ expect(store.cells().C1.value).toBe('=B1');
+ expect(readSpreadsheetLayout(doc).columnCount).toBe(columns + 1);
+ store.undo();
+ expect(store.cells().A1.value).toBe('Name');
+ expect(readSpreadsheetLayout(doc).columnCount).toBe(columns);
+ dispose();
+ doc.free();
+ });
+
+ it.each(['connecting', 'offline'] as const)(
'rejects coordinate shifts for a %s collaborative source',
async (status) => {
const doc = new LoroDoc();
@@ -91,7 +130,7 @@ describe('spreadsheet store', () => {
expect(store.canChangeStructure()).toBe(false);
expect(() =>
store.applyStructure(before, before, store.revision())
- ).toThrow('shared workbooks');
+ ).toThrow('Reconnect');
expect(doc.version().toJSON()).toEqual(version);
dispose();
doc.free();
diff --git a/apps/web/src/features/block-spreadsheet/primitives/create-spreadsheet-store.ts b/apps/web/src/features/block-spreadsheet/primitives/create-spreadsheet-store.ts
index 70edaf09e4..91038c166e 100644
--- a/apps/web/src/features/block-spreadsheet/primitives/create-spreadsheet-store.ts
+++ b/apps/web/src/features/block-spreadsheet/primitives/create-spreadsheet-store.ts
@@ -459,6 +459,11 @@ export function createSpreadsheetStore(options: {
);
const editable = () => options.source.ready() && options.canEdit();
+ // A structural edit rewrites cells at new coordinates. Offline, it could
+ // merge long after collaborators kept editing the old ones.
+ const canShiftCoordinates = () =>
+ options.source.status() === 'local' ||
+ options.source.status() === 'connected';
function setActiveSheet(id: string) {
if (!workbook().some((sheet) => sheet.id === id)) return;
@@ -631,7 +636,7 @@ export function createSpreadsheetStore(options: {
doc.commit({ origin: 'spreadsheet-layout' });
refresh();
},
- canChangeStructure: () => editable() && options.source.status() === 'local',
+ canChangeStructure: () => editable() && canShiftCoordinates(),
applyStructure(
expected: SpreadsheetWorkbookSheet[],
next: SpreadsheetWorkbookSheet[],
@@ -640,10 +645,8 @@ export function createSpreadsheetStore(options: {
const doc = options.source.doc();
if (!doc || !editable())
throw new Error('This spreadsheet is view only.');
- if (options.source.status() !== 'local')
- throw new Error(
- 'Inserting and deleting rows or columns is not yet available in shared workbooks.'
- );
+ if (!canShiftCoordinates())
+ throw new Error('Reconnect to insert or delete rows or columns.');
if (revision() !== expectedRevision)
throw new Error(
'The workbook changed while moving cells. No changes were applied; try again.'
@@ -696,11 +699,23 @@ export function createSpreadsheetStore(options: {
false
);
}
- const addition = sheet.layout.rowCount - previous.layout.rowCount;
- if (addition > 0)
- doc
- .getMap('spreadsheetRowAdditions')
- .set(spreadsheetSheetKey(crypto.randomUUID(), sheet.id), addition);
+ for (const [map, addition] of [
+ [
+ 'spreadsheetRowAdditions',
+ sheet.layout.rowCount - previous.layout.rowCount,
+ ],
+ [
+ 'spreadsheetColumnAdditions',
+ sheet.layout.columnCount - previous.layout.columnCount,
+ ],
+ ] as const)
+ if (addition > 0)
+ doc
+ .getMap(map)
+ .set(
+ spreadsheetSheetKey(crypto.randomUUID(), sheet.id),
+ addition
+ );
}
doc.commit({ origin: 'spreadsheet-axis-change' });
refresh();
diff --git a/docs/AGENT_GUIDE/documents.md b/docs/AGENT_GUIDE/documents.md
index 2f6d66730c..78b4c09ca3 100644
--- a/docs/AGENT_GUIDE/documents.md
+++ b/docs/AGENT_GUIDE/documents.md
@@ -252,10 +252,11 @@ The footer's bottom-right **Import and export → Import…** accepts `.csv` and
Right-click a row number or column letter for Macro's contextual menu: clipboard actions,
clear, hide/unhide, resize and fit-to-data; columns also offer whole-sheet sorting.
The menu keeps an existing whole-row/column selection when opened within it.
-Insert/delete shifts references and named ranges in local workbooks only; these
-commands are disabled on shared workbooks (including offline sessions) until
-collaborative rows and columns have stable identities. Adding blank rows at the
-bottom remains available. Hidden cells are skipped by keyboard navigation.
+Insert/delete shifts cells, references and named ranges in local workbooks and in
+saved workbooks while connected; the commands are disabled while a saved workbook
+is offline or reconnecting. A collaborator's change that arrives while the cells
+are being moved cancels the insert/delete. Adding blank rows at the bottom
+remains available. Hidden cells are skipped by keyboard navigation.
Cells support Macro mentions without Markdown formatting. Type `@` in a cell or
the formula bar to search people, documents, channels, email and dates, then choose an