Skip to content
Open
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
4 changes: 4 additions & 0 deletions packages/core/src/core/mirror.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2515,6 +2515,10 @@ function mergeInitialIntoBaseWithSchema(
if (!(k in base)) base[k] = "";
continue;
}
if (t === "loro-tree") {
if (!(k in base)) base[k] = [];
continue;
}
if (t === "string" || t === "number" || t === "boolean") {
if (!(k in base)) base[k] = initVal;
continue;
Expand Down
6 changes: 5 additions & 1 deletion packages/core/src/schema/validators.ts
Original file line number Diff line number Diff line change
Expand Up @@ -438,7 +438,11 @@ export function getDefaultValue<S extends SchemaType>(
case "loro-list":
return [] as InferType<S>;
case "loro-tree": {
const value = schema.options.required ? [] : undefined;
const required =
schema.options.required !== undefined
? schema.options.required
: true;
const value = required ? [] : undefined;
if (value === undefined) return undefined;
Comment on lines +441 to 446

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 Badge Avoid defaulting empty tree when snapshot omits it

This change makes getDefaultValue return [] for loro-tree when required is unset, which means Mirror's in-memory state will always include an empty tree even if the doc has no tree nodes. However, buildRootStateSnapshot only includes trees when they are non‑empty, so when checkStateConsistency is enabled, any setState call that doesn’t add tree nodes will now throw State diverged because the state has tree: [] but the snapshot omits it. Consider either keeping the default undefined for empty trees or updating the snapshot logic to include empty trees so the invariants still hold.

Useful? React with 👍 / 👎.

return value as InferType<S>;
}
Expand Down
16 changes: 16 additions & 0 deletions packages/core/tests/mirror-tree.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -1117,4 +1117,20 @@ describe("LoroTree integration", () => {

expect(m.getState().root.tree[0].data.desc).toBe("world");
});

it("Schema - LoroTree example from README docs works (#65)", async () => {
/*
The example of using schema.LoroMap() from the README docs
failed with `Cannot read properties of undefined (reading 'push')`
https://github.com/loro-dev/loro-mirror/issues/65
*/
const node = schema.LoroMap({
name: schema.String({ required: true }),
});
const s = schema({ tree: schema.LoroTree(node) });
const mirror = new Mirror({ doc: new LoroDoc(), schema: s });
mirror.setState((st) => {
st.tree.push({ data: { name: "root" }, children: [] });
});
});
});