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(editor): avoid duplicate document rebuilds on undo (#7205)

Wolf Mermelstein3894f3f4801f
diff --git a/docs/AGENT_GUIDE/documents.md b/docs/AGENT_GUIDE/documents.md
index 56aa5ad8a9..c258eb28bf 100644
--- a/docs/AGENT_GUIDE/documents.md
+++ b/docs/AGENT_GUIDE/documents.md
@@ -1933,3 +1933,9 @@ An edit uses the revision from a fresh read and atomically applies a CRDT delta
that is broadcast to connected collaborators. A stale revision is rejected:
reread and reconsider the change instead of blindly retrying. Unsynced edits
still follow normal CRDT collaboration semantics when they reconnect.
+
+## Large-document undo checks
+
+In a disposable Markdown document, change several paragraphs in one edit, then
+undo and redo. Verify the text, paragraph count, and a second peer agree after
+each operation; wait for saving to finish and reload to check persistence.
diff --git a/packages/loro-mirror/src/core/mirror.ts b/packages/loro-mirror/src/core/mirror.ts
index e490fe68a1..1e87bb48f6 100644
--- a/packages/loro-mirror/src/core/mirror.ts
+++ b/packages/loro-mirror/src/core/mirror.ts
@@ -6,27 +6,27 @@ import {
type Container,
type ContainerID,
type ContainerType,
+ isContainer,
type LoroDoc,
type LoroEventBatch,
LoroList,
LoroMap,
LoroMovableList,
LoroText,
- isContainer,
} from 'loro-crdt';
import {
type ContainerSchemaType,
- type InferType,
- type LoroListSchema,
- type LoroMapSchema,
- type RootSchemaType,
- type SchemaType,
getDefaultValue,
+ type InferType,
isContainerSchema,
isListLikeSchema,
isLoroListSchema,
isLoroMapSchema,
isLoroMovableListSchema,
+ type LoroListSchema,
+ type LoroMapSchema,
+ type RootSchemaType,
+ type SchemaType,
validateSchema,
} from '../schema';
import { diffContainer } from './diff';
@@ -178,8 +178,6 @@ export class Mirror<S extends SchemaType> {
private syncing: boolean = false;
private options: MirrorOptions<S>;
- // Unsubscribe functions for container subscriptions
- private containerSubscriptions: Map<ContainerID, () => void> = new Map();
/** Root `doc.subscribe` listener. Must be dropped before `doc.free()`. */
private docUnsubscribe?: () => void;
private disposed = false;
@@ -214,10 +212,12 @@ export class Mirror<S extends SchemaType> {
...this.options.initialState,
} as InferType<S>;
- // Initialize Loro containers and setup subscriptions
+ // Initialize Loro containers
this.initializeContainers();
- // Subscribe to the root doc for global updates
+ // The root subscription covers nested containers too. Subscribing to each
+ // container would rebuild the full document and notify once per changed
+ // container during undo/redo instead of once per batch.
this.docUnsubscribe = this.doc.subscribe(this.handleLoroEvent);
}
@@ -241,7 +241,9 @@ export class Mirror<S extends SchemaType> {
// Register root containers
if (this.schema && this.schema.type === 'schema') {
- const rootSchema = this.schema as RootSchemaType<Record<string, ContainerSchemaType>>;
+ const rootSchema = this.schema as RootSchemaType<
+ Record<string, ContainerSchemaType>
+ >;
for (const key in rootSchema.definition) {
if (Object.prototype.hasOwnProperty.call(rootSchema.definition, key)) {
const fieldSchema = rootSchema.definition[key];
@@ -282,10 +284,6 @@ export class Mirror<S extends SchemaType> {
this.registerContainerWithRegistry(containerId, schemaType);
- // Subscribe to container events
- const unsubscribe = container.subscribe(this.handleContainerEvent);
- this.containerSubscriptions.set(containerId, unsubscribe);
-
// Register nested containers
this.registerNestedContainers(container);
} catch (error) {
@@ -455,37 +453,6 @@ export class Mirror<S extends SchemaType> {
}
}
- /**
- * Handle events from individual containers
- */
- private handleContainerEvent = (event: LoroEventBatch) => {
- if (this.disposed || this.syncing) return;
- if (event.origin === 'to-loro') return;
-
- this.syncing = true;
- try {
- // Build a complete new state from the document
- let start = performance.now();
- const currentDocState = this.doc.toJSON();
-
- // Update the app state to match
- const newState = produce<InferType<S>>((draft) => {
- Object.assign(draft, currentDocState);
- })(this.state);
-
- this.state = newState;
-
- // If the event was from an import, [handleLoroEvent]
- // will handle notifying subscribers
- if (event.by !== 'import') {
- // Notify subscribers
- this.notifySubscribers(SyncDirection.FROM_LORO);
- }
- } finally {
- this.syncing = false;
- }
- };
-
/**
* Update Loro based on state changes
*/
@@ -770,7 +737,11 @@ export class Mirror<S extends SchemaType> {
}
// Get the idSelector function from the schema
- const listSchema = (schema != null && (isLoroListSchema(schema) || isLoroMovableListSchema(schema))) ? schema : undefined;
+ const listSchema =
+ schema != null &&
+ (isLoroListSchema(schema) || isLoroMovableListSchema(schema))
+ ? schema
+ : undefined;
const idSelector = listSchema?.idSelector;
const itemSchema = listSchema?.itemSchema;
@@ -1087,12 +1058,6 @@ export class Mirror<S extends SchemaType> {
this.docUnsubscribe?.();
this.docUnsubscribe = undefined;
- // Unsubscribe from all container subscriptions
- for (const [_, unsubscribe] of this.containerSubscriptions) {
- unsubscribe();
- }
-
- this.containerSubscriptions.clear();
this.subscribers.clear();
}
diff --git a/packages/loro-mirror/tests/core/mirror-notifications.test.ts b/packages/loro-mirror/tests/core/mirror-notifications.test.ts
new file mode 100644
index 0000000000..62c18802e5
--- /dev/null
+++ b/packages/loro-mirror/tests/core/mirror-notifications.test.ts
@@ -0,0 +1,61 @@
+import { LoroDoc, LoroMap, LoroText, UndoManager } from 'loro-crdt';
+import { describe, expect, it, vi } from 'vitest';
+import { Mirror } from '../../src/core/mirror';
+import { schema } from '../../src/schema';
+
+const documentSchema = schema({
+ nodes: schema.LoroList(schema.LoroMap({ text: schema.LoroText() })),
+});
+const flush = () => new Promise<void>((resolve) => queueMicrotask(resolve));
+
+describe('batched document notifications', () => {
+ it('rebuilds once for bulk local changes, undo, redo and remote imports', async () => {
+ const doc = new LoroDoc();
+ const list = doc.getList('nodes');
+ const texts = Array.from({ length: 100 }, (_, i) => {
+ const text = list
+ .insertContainer(i, new LoroMap())
+ .setContainer('text', new LoroText());
+ text.insert(0, `paragraph ${i}`);
+ return text;
+ });
+ doc.commit();
+ const mirror = new Mirror({ doc, schema: documentSchema });
+ const undo = new UndoManager(doc, { mergeInterval: 0 });
+ const notify = vi.fn();
+ mirror.subscribe(notify);
+ const serialize = vi.spyOn(doc, 'toJSON');
+ const check = async () => {
+ await flush();
+ expect(notify).toHaveBeenCalledTimes(1);
+ expect(serialize).toHaveBeenCalledTimes(1);
+ expect(mirror.getState()).toEqual(doc.toJSON());
+ notify.mockClear();
+ serialize.mockClear();
+ };
+ try {
+ for (const text of texts) text.insert(0, 'edit ');
+ doc.commit();
+ await check();
+ undo.undo();
+ await check();
+ undo.redo();
+ await check();
+ const remote = doc.fork();
+ const version = remote.version();
+ for (let i = 0; i < 100; i++) {
+ const node = remote.getList('nodes').get(i) as LoroMap;
+ (node.get('text') as LoroText).insert(0, 'remote ');
+ }
+ remote.commit();
+ doc.import(remote.export({ mode: 'update', from: version }));
+ await check();
+ remote.free();
+ } finally {
+ serialize.mockRestore();
+ mirror.dispose();
+ undo.free();
+ doc.free();
+ }
+ });
+});