Skip to content

Commit

Permalink
fix: guard against undefined nested child (#41) (#42)
Browse files Browse the repository at this point in the history
Co-authored-by: Daishi Kato <[email protected]>
  • Loading branch information
raineorshine and dai-shi authored Dec 2, 2023
1 parent 0e316c0 commit eed5e93
Show file tree
Hide file tree
Showing 2 changed files with 76 additions and 0 deletions.
72 changes: 72 additions & 0 deletions __tests__/07_nested_map_spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -147,4 +147,76 @@ describe('issue #14', () => {
expect(listener1).toBeCalledTimes(2);
expect(listener2).toBeCalledTimes(2);
});

it('nested map delete', async () => {
type State = Record<
'items',
{
[key: string]: {
color: string;
};
}
>;
const doc = new Y.Doc();
const p = proxy<State>({
items: { item1: { color: 'blue' }, item2: { color: 'red' } },
});
const m = doc.getMap('map') as any;

bind(p, m);

delete p.items.item1;
await Promise.resolve();

expect(m.get('items').get('item1')).toBeUndefined();
expect(m.get('items').get('item2')).toBeDefined();
});

it('nested map delete child and parent', async () => {
type State = Record<
'parents',
{
[key: string]: Record<
'children',
{
[key: string]: {
color: string;
};
}
>;
}
>;
const doc = new Y.Doc();
const p = proxy<State>({
parents: {
parent1: {
children: {
child1: { color: 'blue' },
},
},
parent2: {
children: {
child2: { color: 'red' },
},
},
},
});
const m = doc.getMap('map') as any;

bind(p, m);

delete p.parents.parent1.children.child1;
delete p.parents.parent1;
await Promise.resolve();

expect(m.toJSON()).toStrictEqual({
parents: {
parent2: {
children: {
child2: { color: 'red' },
},
},
},
});
});
});
4 changes: 4 additions & 0 deletions src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -73,9 +73,13 @@ const getNestedValues = <T>(
for (let i = 0; i < path.length; i += 1) {
const k = path[i];
if (yv instanceof Y.Map) {
// child may already be deleted
if (!pv) break;
pv = pv[k];
yv = yv.get(k as string);
} else if (yv instanceof Y.Array) {
// child may already be deleted
if (!pv) break;
const index = Number(k);
pv = pv[k];
yv = yv.get(index);
Expand Down

0 comments on commit eed5e93

Please sign in to comment.