Skip to content

Commit

Permalink
fix: guard against undefined nested parent (valtiojs#41)
Browse files Browse the repository at this point in the history
  • Loading branch information
raineorshine committed Dec 1, 2023
1 parent cddabca commit 11ddbfb
Show file tree
Hide file tree
Showing 2 changed files with 67 additions and 0 deletions.
63 changes: 63 additions & 0 deletions __tests__/07_nested_map_spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -147,4 +147,67 @@ 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) {
// parent may already be deleted
if (!pv) break
pv = pv[k];
yv = yv.get(k as string);
} else if (yv instanceof Y.Array) {
// parent may already be deleted
if (!pv) break
const index = Number(k);
pv = pv[k];
yv = yv.get(index);
Expand Down

0 comments on commit 11ddbfb

Please sign in to comment.