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(docx): undo typing, keep the app layout, center the page, open from Home (#7448)

Jacob Beckermandf42ec2f1b22
diff --git a/apps/web/src/features/block-write/browser-test/collaboration.browser.e2e.ts b/apps/web/src/features/block-write/browser-test/collaboration.browser.e2e.ts
index 5918a03909..64fc159ed3 100644
--- a/apps/web/src/features/block-write/browser-test/collaboration.browser.e2e.ts
+++ b/apps/web/src/features/block-write/browser-test/collaboration.browser.e2e.ts
@@ -37,6 +37,11 @@ async function open(page: Page, documentId: string, user: string, extra = {}) {
await expect
.poll(() => page.evaluate(() => window.docxFixture?.status()))
.toBe('connected');
+ // The document's own stylesheet ("body { margin: 20px }") must stay inside
+ // the editor; leaking it shifts the whole app.
+ expect(
+ await page.evaluate(() => getComputedStyle(document.body).margin)
+ ).toBe('0px');
}
const paragraphs = (page: Page) =>
@@ -252,6 +257,52 @@ test('two people edit the same DOCX live through the sync service', async ({
}
});
+test('undo and redo cover typing the editor has not committed yet', async ({
+ browser,
+}) => {
+ const documentId = crypto.randomUUID();
+ const contexts = await Promise.all([
+ browser.newContext(),
+ browser.newContext(),
+ ]);
+ const [alice, bob] = await Promise.all(
+ contexts.map((context) => context.newPage())
+ );
+ const shared = async () => (await paragraphs(bob)).join('\n');
+ try {
+ await open(alice, documentId, ALICE);
+ await open(bob, documentId, BOB);
+
+ // Undo straight after typing, before the idle commit, and keep going.
+ const clause = paragraph(alice, 'This Agreement shall remain');
+ await caretAtEnd(alice, 'This Agreement shall remain');
+ await alice.keyboard.type(' [first]');
+ await alice.keyboard.press('ControlOrMeta+z');
+ await expect(clause).not.toContainText('[first]');
+ await alice.keyboard.press('ControlOrMeta+Shift+z');
+ await expect(clause).toContainText('[first]');
+ await expect.poll(shared).toContain('[first]');
+ // The caret lands after the redone text, so typing continues there.
+ await alice.keyboard.type(' [second]');
+ await expect(clause).toContainText('[first] [second]');
+ await alice.keyboard.press('ControlOrMeta+z');
+ await alice.keyboard.press('ControlOrMeta+z');
+ await expect(clause).not.toContainText('[first]');
+ await expect.poll(shared).not.toContain('[first]');
+ expect(await shared()).not.toContain('[second]');
+
+ // The toolbar commits pending typing the same way.
+ await alice.keyboard.type(' [third]');
+ await alice.getByRole('button', { name: 'Undo' }).click();
+ await expect(clause).not.toContainText('[third]');
+ await alice.getByRole('button', { name: 'Redo' }).click();
+ await expect(clause).toContainText('[third]');
+ await expect.poll(shared).toContain('[third]');
+ } finally {
+ await Promise.all(contexts.map((context) => context.close()));
+ }
+});
+
test('viewers follow along read-only, and header edits reach them', async ({
browser,
}) => {
diff --git a/apps/web/src/features/block-write/core/editor-bridge.ts b/apps/web/src/features/block-write/core/editor-bridge.ts
index 742b01304d..e35b1eccfd 100644
--- a/apps/web/src/features/block-write/core/editor-bridge.ts
+++ b/apps/web/src/features/block-write/core/editor-bridge.ts
@@ -48,8 +48,14 @@ const DOCUMENT_RENDERS = [
'RenderHtml',
'RenderHtmlForReview',
'RenderEditorHtml',
+ // The windowed mount injects this document's <style> into the page.
+ 'RenderEditorChromeHtml',
] as const;
+/** A whole HTML document, as opposed to JSON or a fragment. */
+const isHtmlDocument = (value: unknown): value is string =>
+ typeof value === 'string' && /^\s*<(?:!doctype|html)/i.test(value);
+
export type EditorBridgeOptions = {
/** Selector of the editor's mount; document CSS is confined to it. */
rootSelector: string;
@@ -95,7 +101,13 @@ export function editorBridge(
bridge[name] = (...args: never[]) =>
scopeDocumentStyles(call(...args) as string, options.rootSelector);
} else if (isRead(name)) {
- bridge[name] = call;
+ // A render added in a later release must not leak its stylesheet either.
+ bridge[name] = (...args: never[]) => {
+ const result = call(...args);
+ return isHtmlDocument(result)
+ ? scopeDocumentStyles(result, options.rootSelector)
+ : result;
+ };
} else {
bridge[name] = (...args: never[]) => {
const result = call(...args);
diff --git a/apps/web/src/features/block-write/core/text-offsets.test.ts b/apps/web/src/features/block-write/core/text-offsets.test.ts
index 5cd5fc82ca..bd30f5fdf5 100644
--- a/apps/web/src/features/block-write/core/text-offsets.test.ts
+++ b/apps/web/src/features/block-write/core/text-offsets.test.ts
@@ -2,6 +2,7 @@ import { beforeEach, describe, expect, it } from 'vitest';
import {
blockOf,
blockSpanOfRange,
+ changedTextEnd,
contentOffset,
contentRange,
contentText,
@@ -67,3 +68,16 @@ describe('content offsets', () => {
expect(blockOf(root, root)).toBeNull();
});
});
+
+describe('changed text end', () => {
+ it('lands after reinserted text and where removed text was', () => {
+ expect(changedTextEnd('notice.', 'notice. More.')).toBe(13);
+ expect(changedTextEnd('notice. More.', 'notice.')).toBe(7);
+ });
+
+ it('handles a change in the middle and repeated characters', () => {
+ expect(changedTextEnd('abcdef', 'abcXYZdef')).toBe(6);
+ expect(changedTextEnd('aaa', 'aaaa')).toBe(4);
+ expect(changedTextEnd('same', 'same')).toBe(4);
+ });
+});
diff --git a/apps/web/src/features/block-write/core/text-offsets.ts b/apps/web/src/features/block-write/core/text-offsets.ts
index 02f4c746b0..aec8015c6c 100644
--- a/apps/web/src/features/block-write/core/text-offsets.ts
+++ b/apps/web/src/features/block-write/core/text-offsets.ts
@@ -203,3 +203,20 @@ export function blockSpanOfRange(
if (end <= start) return null;
return { block, start, length: end - start };
}
+
+/**
+ * Where the caret belongs after `before` became `after`, as undo and redo
+ * place it: the end of the text that changed, in `after`'s offsets.
+ */
+export function changedTextEnd(before: string, after: string): number {
+ const limit = Math.min(before.length, after.length);
+ let start = 0;
+ while (start < limit && before[start] === after[start]) start++;
+ let end = 0;
+ while (
+ end < limit - start &&
+ before[before.length - 1 - end] === after[after.length - 1 - end]
+ )
+ end++;
+ return after.length - end;
+}
diff --git a/apps/web/src/features/block-write/primitives/create-docx-editor.ts b/apps/web/src/features/block-write/primitives/create-docx-editor.ts
index fcd3a9320c..6f497ee8ce 100644
--- a/apps/web/src/features/block-write/primitives/create-docx-editor.ts
+++ b/apps/web/src/features/block-write/primitives/create-docx-editor.ts
@@ -7,13 +7,20 @@ import { assemblePackage } from '../core/docx-package';
import { DOCX_SYNC_SESSION_SETTINGS } from '../core/docx-seed';
import { DocxSyncController } from '../core/docx-sync';
import { editorBridge } from '../core/editor-bridge';
-import { caretRange, contentOffset, contentText } from '../core/text-offsets';
+import {
+ caretRange,
+ changedTextEnd,
+ contentOffset,
+ contentText,
+} from '../core/text-offsets';
import type { DocxodusRuntime } from '../queries/docxodus-runtime';
/** Commit typing this long after the last keystroke so peers see it live. */
const IDLE_COMMIT_MS = 1_200;
/** Coalesce bursts of engine mutations into one publish. */
const PUBLISH_DELAY_MS = 80;
+/** A rendered block the user can type in. */
+const EDITABLE_BLOCK = '[data-anchor][contenteditable="true"]';
export type DocxEditorOptions = {
runtime: DocxodusRuntime;
@@ -37,6 +44,10 @@ export type DocxEditorHandle = {
mount: (element: HTMLElement) => Promise<void>;
/** Publish committed local edits now (e.g. before leaving). */
flush: () => void;
+ /** Undo the last edit, including typing not yet committed. */
+ undo: () => void;
+ /** Redo the last undone edit. */
+ redo: () => void;
/** The editor's live document bytes, without engine bookkeeping. */
save: () => Uint8Array | undefined;
};
@@ -120,7 +131,7 @@ export function createDocxEditor(options: DocxEditorOptions): DocxEditorHandle {
const active = document.activeElement;
if (!(active instanceof HTMLElement) || !container?.contains(active))
return null;
- return active.closest<HTMLElement>('[data-anchor][contenteditable="true"]');
+ return active.closest<HTMLElement>(EDITABLE_BLOCK);
};
const isDirty = (block: HTMLElement) =>
block.dataset.committedText !== undefined &&
@@ -137,47 +148,115 @@ export function createDocxEditor(options: DocxEditorOptions): DocxEditorHandle {
return !!owner?.contains(block);
};
+ const editableBlocks = () =>
+ Array.from(container?.querySelectorAll<HTMLElement>(EDITABLE_BLOCK) ?? []);
+
+ const scrollTop = () => options.scroller?.()?.scrollTop;
+
+ /** Focus `block` with the caret at a content offset and the scroll at `top`. */
+ const placeCaret = (block: HTMLElement, offset: number, top?: number) => {
+ block.focus({ preventScroll: true });
+ const caret = caretRange(block, offset);
+ const selection = window.getSelection();
+ if (caret && selection) {
+ selection.removeAllRanges();
+ selection.addRange(caret);
+ }
+ const scrollParent = options.scroller?.();
+ if (scrollParent && top !== undefined) scrollParent.scrollTop = top;
+ };
+
+ /** The focused block and the content offset of the selection's focus end. */
+ const caretPosition = () => {
+ const block = activeBlock();
+ if (!block) return null;
+ const selection = window.getSelection();
+ const node = selection?.focusNode;
+ const inside = !!node && block.contains(node);
+ return {
+ block,
+ collapsed: inside && selection!.isCollapsed,
+ offset: inside ? contentOffset(block, node, selection!.focusOffset) : 0,
+ };
+ };
+
/**
* Commit the block the user is typing in without moving their caret: the
- * editor commits on blur, so blur and restore focus at the same offset.
+ * editor commits on blur, so blur and restore focus at the same offset. The
+ * idle commit leaves a selection in progress alone; `force` commits anyway.
*/
- const commitTyping = () => {
+ const commitTyping = (force = false) => {
+ clearTimeout(idleTimer);
idleTimer = undefined;
- const block = activeBlock();
- if (!block || !isDirty(block)) return;
- const selection = window.getSelection();
- if (!selection?.isCollapsed || !selection.anchorNode) return;
- if (!block.contains(selection.anchorNode)) return;
- const offset = contentOffset(
- block,
- selection.anchorNode,
- selection.anchorOffset
- );
- const id = block.getAttribute('data-anchor');
- const scrollParent = options.scroller?.();
- const scrollTop = scrollParent?.scrollTop;
- block.blur();
+ const position = caretPosition();
+ if (!position || !isDirty(position.block)) return;
+ if (!force && !position.collapsed) return;
+ const id = position.block.getAttribute('data-anchor');
+ const top = scrollTop();
+ position.block.blur();
const fresh =
(id &&
container?.querySelector<HTMLElement>(
`[data-anchor="${CSS.escape(id)}"][contenteditable="true"]`
)) ||
null;
- if (!fresh) return;
- fresh.focus({ preventScroll: true });
- const caret = caretRange(fresh, offset);
- if (caret) {
- selection.removeAllRanges();
- selection.addRange(caret);
+ if (fresh) placeCaret(fresh, position.offset, top);
+ };
+
+ /**
+ * Step through the session's history. Typing reaches the session only when
+ * committed, so commit it first; otherwise undo skips past it.
+ */
+ const step = (direction: 'undo' | 'redo') => {
+ const current = editor();
+ if (!current || !options.editable) return;
+ commitTyping(true);
+ const position = caretPosition();
+ const index = position ? editableBlocks().indexOf(position.block) : -1;
+ const before = editableBlocks().map(contentText);
+ const top = scrollTop();
+ current[direction]();
+ // Repainting drops the caret. Put it at the end of the change, as word
+ // processors do, so typing continues there and the next shortcut lands.
+ const blocks = editableBlocks();
+ const changed = blocks.findIndex(
+ (block, i) => contentText(block) !== before[i]
+ );
+ if (changed >= 0) {
+ const block = blocks[changed];
+ placeCaret(
+ block,
+ changedTextEnd(before[changed] ?? '', contentText(block)),
+ top
+ );
+ block.scrollIntoView({ block: 'nearest' });
+ return;
}
- if (scrollParent && scrollTop !== undefined)
- scrollParent.scrollTop = scrollTop;
+ if (!position || container?.contains(document.activeElement)) return;
+ const block = blocks[Math.min(index, blocks.length - 1)];
+ if (block) placeCaret(block, position.offset, top);
+ };
+
+ /** Own the history shortcuts so they commit pending typing first. */
+ const onKeyDown = (event: KeyboardEvent) => {
+ if (!options.editable || event.isComposing || event.altKey) return;
+ if (!(event.metaKey || event.ctrlKey)) return;
+ const key = event.key.toLowerCase();
+ if (key !== 'z' && key !== 'y') return;
+ if (
+ !(event.target instanceof Element) ||
+ !event.target.closest(EDITABLE_BLOCK)
+ )
+ return;
+ event.preventDefault();
+ event.stopPropagation();
+ step(key === 'z' && !event.shiftKey ? 'undo' : 'redo');
};
const onInput = (event: Event) => {
if ((event as InputEvent).isComposing) return;
clearTimeout(idleTimer);
- idleTimer = setTimeout(commitTyping, IDLE_COMMIT_MS);
+ idleTimer = setTimeout(() => commitTyping(), IDLE_COMMIT_MS);
};
const rebuild = (bytes: Uint8Array) => {
@@ -212,6 +291,8 @@ export function createDocxEditor(options: DocxEditorOptions): DocxEditorHandle {
container = element;
container.setAttribute('data-docx-editor', rootId);
container.addEventListener('input', onInput);
+ // Capture, so this runs before the block's own shortcut handling.
+ container.addEventListener('keydown', onKeyDown, true);
const bytes = options.doc
? assemblePackage(readDocxState(options.doc))
: options.original;
@@ -253,6 +334,7 @@ export function createDocxEditor(options: DocxEditorOptions): DocxEditorHandle {
clearTimeout(idleTimer);
document.removeEventListener('visibilitychange', onHide);
container?.removeEventListener('input', onInput);
+ container?.removeEventListener('keydown', onKeyDown, true);
editor()?.close();
});
@@ -261,6 +343,8 @@ export function createDocxEditor(options: DocxEditorOptions): DocxEditorHandle {
revision,
mount,
flush: publish,
+ undo: () => step('undo'),
+ redo: () => step('redo'),
save: () => editor()?.save(),
};
}
diff --git a/apps/web/src/features/block-write/views/DocxEditorView.tsx b/apps/web/src/features/block-write/views/DocxEditorView.tsx
index f4a7bd2d17..039cce1e0f 100644
--- a/apps/web/src/features/block-write/views/DocxEditorView.tsx
+++ b/apps/web/src/features/block-write/views/DocxEditorView.tsx
@@ -27,6 +27,11 @@ import type { DocxPeer, DocxSelection } from '../queries/docx-session';
import type { DocxodusRuntime } from '../queries/docxodus-runtime';
import { DocxCollaboratorCarets } from './DocxCollaborators';
+/** A US Letter sheet at 96 dpi. */
+const PAGE_WIDTH = 816;
+/** Room for a comment card (280px) and its inset beside the page. */
+const MARGIN_WIDTH = 296;
+
/** Paragraph styles offered in the toolbar, when the document defines them. */
const PREFERRED_STYLES = [
'Normal',
@@ -102,6 +107,17 @@ export function DocxEditorView(props: DocxEditorViewProps) {
revision: handle.revision,
canEdit: () => props.canEdit,
});
+ // The right gutter holds the comment margin. With cards or a draft showing
+ // it keeps their width and the page gives way; otherwise it only needs room
+ // for the comment button beside a selection, so the page stays centered.
+ const pageColumns = () => {
+ const gutter = !props.margin
+ ? 0
+ : comments.located().length > 0 || comments.draft()
+ ? MARGIN_WIDTH
+ : 48;
+ return `minmax(0, 1fr) minmax(0, ${PAGE_WIDTH}px) minmax(${gutter}px, 1fr)`;
+ };
const highlightStyles = createCommentHighlights(
comments,
@@ -241,8 +257,8 @@ ${highlightStyles}`}</style>
onAlign={(alignment: DocxAlignment) =>
run((instance) => instance.setAlignment(alignment))
}
- onUndo={() => run((instance) => instance.undo())}
- onRedo={() => run((instance) => instance.redo())}
+ onUndo={() => run(() => handle.undo())}
+ onRedo={() => run(() => handle.redo())}
onInsertTable={() => run((instance) => instance.insertTable(3, 3))}
onToggleTrackChanges={() =>
run((instance) => {
@@ -267,14 +283,14 @@ ${highlightStyles}`}</style>
class="relative min-h-0 flex-1 overflow-auto bg-panel"
data-docx-scroller
>
- {/* The page column shrinks so Docxodus zooms the sheet to fit a
- narrow split instead of scrolling it sideways. */}
- <div class="relative mx-auto flex max-w-[1160px] justify-center gap-2 px-4 pt-6 pb-24">
- <div
- ref={page}
- class="relative min-w-0 max-w-[816px] flex-1"
- data-docx-page
- >
+ {/* The page sits centered between equal gutters. The page column
+ shrinks so Docxodus zooms the sheet to fit a narrow split instead
+ of scrolling it sideways. */}
+ <div
+ class="relative grid gap-x-2 px-4 pt-6 pb-24"
+ style={{ 'grid-template-columns': pageColumns() }}
+ >
+ <div ref={page} class="relative col-start-2 min-w-0" data-docx-page>
<div ref={setEditorRoot} class="docx-paper rounded-sm shadow-md" />
<DocxCollaboratorCarets
peers={props.peers()}
@@ -293,7 +309,7 @@ ${highlightStyles}`}</style>
{(renderMargin) => (
<div
ref={setMargin}
- class="relative w-[296px] shrink-0"
+ class="relative col-start-3 min-w-0"
data-docx-margin
>
{renderMargin()({
diff --git a/apps/web/src/features/home/home-route-schema.test.ts b/apps/web/src/features/home/home-route-schema.test.ts
new file mode 100644
index 0000000000..9ef190fc4d
--- /dev/null
+++ b/apps/web/src/features/home/home-route-schema.test.ts
@@ -0,0 +1,20 @@
+import { describe, expect, it } from 'vitest';
+import { homePreviewRouteParams } from './home-route-schema';
+
+describe('home preview route params', () => {
+ it('opens a DOCX item in the write block', () => {
+ expect(
+ homePreviewRouteParams.safeParse({ blockType: 'write', previewId: 'doc' })
+ .success
+ ).toBe(true);
+ });
+
+ it('leaves calendar to the calendar route', () => {
+ expect(
+ homePreviewRouteParams.safeParse({
+ blockType: 'calendar',
+ previewId: 'id',
+ }).success
+ ).toBe(false);
+ });
+});
diff --git a/apps/web/src/features/home/home-route-schema.ts b/apps/web/src/features/home/home-route-schema.ts
index 4577edaf77..abd457611e 100644
--- a/apps/web/src/features/home/home-route-schema.ts
+++ b/apps/web/src/features/home/home-route-schema.ts
@@ -16,13 +16,14 @@ import { z } from 'zod';
* The block an inline Home item opens. Aliases such as `task` name markdown
* subtypes, as Drive's document routes do. `calendar` is not a block here:
* the `home-calendar` route renders the Calendar view at `calendar/:period`.
+ * `write` is the DOCX editor; items only name it while that editor is on.
*/
export const homePreviewRouteParams = z
.object({
blockType: z.enum([...BlockRegistry, ...BlockAliasRegistry] as const),
previewId: z.string().min(1),
})
- .refine(({ blockType }) => blockType !== 'write' && blockType !== 'calendar');
+ .refine(({ blockType }) => blockType !== 'calendar');
export type HomePreviewRouteParams = z.infer<typeof homePreviewRouteParams>;
export function isHomeDocumentType(value: string): value is DriveDocumentType {
diff --git a/docs/AGENT_GUIDE/documents.md b/docs/AGENT_GUIDE/documents.md
index f72b4b9d8a..cb10520899 100644
--- a/docs/AGENT_GUIDE/documents.md
+++ b/docs/AGENT_GUIDE/documents.md
@@ -816,6 +816,10 @@ updates live and shows each collaborator's caret with their name.
buttons, `Insert table` and `Track changes`.
- Typing is committed after about a second of idle time, or on blur. Wait
roughly 1.5 s before checking another tab for the text.
+- Mod+Z, Mod+Shift+Z and Ctrl+Y (or the toolbar buttons) undo and redo. They
+ commit pending typing first, so an undo straight after typing removes it,
+ and leave the caret at the end of the change.
+- Clicking a DOCX in the Home list opens the editor in the Home preview pane.
- Editors see editable `Header` and `Footer` bands. Viewers and commenters get
a read-only paginated rendering instead.
- To comment on any text, including table cells: select it, then click the
@@ -833,6 +837,7 @@ updates live and shows each collaborator's caret with their name.
Comments stay in Macro threads and are not written into the file.
- The stored upload is not rewritten yet. Search, the PDF export and AI
`ReadContent` still see the original file.
+- AI `EditDocument` edits Markdown documents only and rejects DOCX files.
## Document history