Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
50 changes: 38 additions & 12 deletions packages/core/src/core/mirror.ts
Original file line number Diff line number Diff line change
Expand Up @@ -460,20 +460,46 @@ export class Mirror<S extends SchemaType> {
string,
unknown
>;
const rootSchema =
this.schema && this.schema.type === "schema"
? (this.schema as RootSchemaType<
Record<string, ContainerSchemaType>
>)
: undefined;
for (const [key, value] of Object.entries(init)) {
let container: Container | null = null;
if (Array.isArray(value)) {
container = this.doc.getList(key);
} else if (typeof value === "string") {
container = this.doc.getText(key);
} else if (isObject(value)) {
container = this.doc.getMap(key);
}
if (container) {
this.rootPathById.set(container.id, [key]);
this.registerContainerWithRegistry(container.id, undefined);
}
const fieldSchema = rootSchema?.definition[key];
const containerType =
(fieldSchema
? schemaToContainerType(fieldSchema)
: undefined) ??
this.inferRootContainerTypeFromInitialValue(value);
if (!containerType) continue;

const container = getRootContainerByType(
this.doc,
key,
containerType,
);
this.rootPathById.set(container.id, [key]);
this.registerContainerWithRegistry(container.id, undefined);
}
}

private inferRootContainerTypeFromInitialValue(
value: unknown,
): ContainerType | undefined {
if (Array.isArray(value)) {
return this.options.inferOptions?.defaultMovableList
? "MovableList"
: "List";
}
if (typeof value === "string") {
return "Text";
}
if (isObject(value)) {
return "Map";
}
return undefined;
}

/**
Expand Down
34 changes: 34 additions & 0 deletions packages/core/tests/mirror-movable-list.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -753,6 +753,40 @@ describe("MovableList (inferred)", () => {
);
});

it("keeps initialState root arrays snapshot-safe with defaultMovableList", async () => {
const doc = new LoroDoc();
const mirror = new Mirror({
doc,
initialState: {
payload: {},
items: [],
},
inferOptions: { defaultMovableList: true },
validateUpdates: false,
});
const state = {
payload: { title: "hello", count: 42 },
items: [
{ id: "a", value: 1 },
{ id: "b", value: 2 },
],
};

mirror.setState(state);
await waitForSync();

const serialized = doc.getDeepValueWithID() as Record<string, unknown>;
expect(
valueIsContainerOfType(serialized["items"], ":MovableList"),
).toBe(true);

const restored = new LoroDoc();
restored.import(doc.export({ mode: "snapshot" }));

expect(restored.toJSON()).toStrictEqual(state);
expect(restored.toJSON()).toStrictEqual(doc.toJSON());
});

it("preserves nested map container identity for object items", async () => {
const doc = new LoroDoc();
const mirror = new Mirror({
Expand Down
Loading