Skip to content
6 changes: 5 additions & 1 deletion src/current.ts
Original file line number Diff line number Diff line change
Expand Up @@ -130,11 +130,15 @@ function getCurrent(target: any, rootOptions?: Options<any, any>) {

if (proxyDraft) {
// It's a proxy draft, let's create a shallow copy eagerly
// Restore the flag instead of clearing it: current() must not unfinalize
// a draft, which would let reads through it create drafts again and let
// it generate its patches twice.
const finalized = proxyDraft.finalized;
proxyDraft.finalized = true;
try {
ensureShallowCopy();
} finally {
proxyDraft.finalized = false;
proxyDraft.finalized = finalized;
}
} else if (type === DraftType.Set) {
// A plain Set is walked as an indexed snapshot so nested drafts can be
Expand Down
23 changes: 15 additions & 8 deletions src/utils/finalize.ts
Original file line number Diff line number Diff line change
Expand Up @@ -146,6 +146,10 @@ export function finalizeNode(
inversePatches?: Patches
) {
const parent = node.parent;
// A Set draft gives its items their final values before it generates its
// patches, and also when it left its key: it then reaches its new place as
// a value, through a callback or a value assigned there.
finalizeSetValue(node);
if (parent) {
const parentType = parent.type;
// if the parent is a Set draft, `setMap` is the real Set copies proxy mapping.
Expand All @@ -155,21 +159,25 @@ export function finalizeNode(
parentType === DraftType.Set || parentType === DraftType.Map;
const draft = isMapLike ? copy.get(key) : copy[key];
// Fast path: the node is still at its own key. Otherwise another draft
// may have been moved here, e.g. by `reverse()`, and is finalized instead.
// may have been moved here, e.g. by `reverse()`, and its value is written
// here instead.
const proxyDraft = draft === node.proxy ? node : getProxyDraft(draft);
// A draft that left its key reaches its new place as a value, through a
// callback or a value assigned there, so a Set finalizes its items here.
if (proxyDraft !== node) finalizeSetValue(node);
if (proxyDraft) {
// assign the updated value to the copy object
const updatedValue = proxyDraft.operated
? proxyDraft.copy
: proxyDraft.original;
// A draft generates its patches at its own node, after the nodes of its
// child drafts, whose patches assume its original layout and so come
// before its own. A draft found at another node's key generates them at
// its own node, in its own producer, if it is still at its own key;
// otherwise its value is part of the patches of the draft holding it.
if (proxyDraft === node)
finalizePatches(node, generatePatches, patches, inversePatches);
// A draft of another producer, which a recipe placed here, is
// finalized by that producer.
if (proxyDraft.finalities === node.finalities)
// finalized by that producer: its recipe may still change the draft.
else if (proxyDraft.finalities === node.finalities)
finalizeSetValue(proxyDraft);
finalizePatches(proxyDraft, generatePatches, patches, inversePatches);
// final update value
if (isMapLike) {
copy.set(key, updatedValue);
Expand All @@ -179,7 +187,6 @@ export function finalizeNode(
}
} else {
// !case: handle the root draft
finalizeSetValue(node);
finalizePatches(node, generatePatches, patches, inversePatches);
}
// !case: handle the deleted key
Expand Down
17 changes: 17 additions & 0 deletions test/current.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@
/* eslint-disable consistent-return */
/* eslint-disable no-param-reassign */
import { create, current, isDraft } from '../src';
import { PROXY_DRAFT } from '../src/constant';

describe('current', () => {
test('base', () => {
Expand Down Expand Up @@ -371,3 +372,19 @@ test('current() snapshots an assigned object that a mark makes draftable', () =>
expect(state.child.count).toBe(2);
expect(state.box!.value.count).toBe(2);
});

// A finalized draft no longer drafts the values read through it and generates
// its patches only once, so a snapshot must not clear the flag.
test('current() leaves the finalized flag of a draft as it was', () => {
create({ a: { b: 1 } }, (draft) => {
draft.a.b = 2;
const proxyDraft = (draft.a as any)[PROXY_DRAFT];
expect(current(draft.a)).toEqual({ b: 2 });
expect(proxyDraft.finalized).toBe(false);
proxyDraft.finalized = true;
expect(current(draft.a)).toEqual({ b: 2 });
expect(proxyDraft.finalized).toBe(true);
// The producer finalizes the draft itself.
proxyDraft.finalized = false;
});
});
254 changes: 254 additions & 0 deletions test/moved-child-patches.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -192,3 +192,257 @@ describe('patches of drafts that left their key', () => {
expect(failures).toStrictEqual([]);
});
});

// A parent that a recipe placed at a key read after the drafts it holds is
// found at that key before they are finalized. Their patches assume its
// original layout, so they still come before its own.
describe('patches of a parent placed at a key read after the drafts it holds', () => {
const optionSets = [
{ enablePatches: { arrayLengthAssignment: true }, strict: false },
{ enablePatches: { arrayLengthAssignment: false }, strict: false },
// Strict mode moves the elements of these arrays through the proxy.
{ enablePatches: { arrayLengthAssignment: true }, strict: true },
];
const recipes: [string, (list: any[]) => void][] = [
[
'unshift() of a changed element',
(list) => {
list[0].push(9);
list.unshift(list[0]);
},
],
[
'splice() that inserts a changed element at its index',
(list) => {
list[0].push(9);
list.splice(0, 0, list[0]);
},
],
[
'unshift() then shift()',
(list) => {
list[0].push(9);
list.unshift([1]);
list.shift();
},
],
[
'shift() then unshift() of the shifted element',
(list) => {
list[0].push(9);
list.unshift(list.shift());
},
],
[
'reverse() twice',
(list) => {
list[0].push(9);
list.reverse();
list.reverse();
},
],
[
'an element assigned back to its index',
(list) => {
const item = list[0];
item.push(9);
list[0] = [1];
list[0] = item;
},
],
];

// `recipe` reads the parent and the drafts it holds, then calls `place`,
// which reads record.key only then and places the parent there.
function replayEarly(
makeBase: () => any,
recipe: (draft: any, place: (parent: any) => void) => void,
options: (typeof optionSets)[number]
) {
const base = makeBase();
const [state, patches, inversePatches] = create(
base,
(draft: any) =>
recipe(draft, (parent) => {
expect(draft.record.key).toEqual({});
draft.record.key = parent;
}),
options
);
expect(apply(makeBase(), patches)).toStrictEqual(state);
expect(apply(state, inversePatches)).toStrictEqual(makeBase());
expect(base).toStrictEqual(makeBase());
return patches;
}

describe.each(optionSets)('with options %j', (options) => {
test.each(recipes)('%s', (_, recipe) => {
replayEarly(
() => ({ record: { key: {} }, list: [[7, 4], [5]] }),
(draft, place) => {
const list = draft.list;
expect(list[0]).toEqual([7, 4]);
place(list);
recipe(list);
},
options
);
});

test('an object key assigned its draft again', () => {
replayEarly(
() => ({ record: { key: {} }, item: { list: [7, 4] } }),
(draft, place) => {
const item = draft.item;
const list = item.list;
place(item);
list.push(9);
item.list = [1];
item.list = list;
},
options
);
});

test('a Map key set to its draft again', () => {
replayEarly(
() => ({ record: { key: {} }, map: new Map([['list', [7, 4]]]) }),
(draft, place) => {
const map = draft.map;
const list = map.get('list');
place(map);
list.push(9);
map.set('list', [1]);
map.set('list', list);
},
options
);
});

test('an element whose own draft changed, moved and moved back', () => {
replayEarly(
() => ({
record: { key: {} },
list: [{ inner: [7, 4] }, { inner: [5] }],
}),
(draft, place) => {
const list = draft.list;
const inner = list[0].inner;
place(list);
inner.push(9);
list.unshift({ inner: [] });
list.shift();
},
options
);
});
});

test("an element's patches precede its list's", () => {
const patches = replayEarly(
() => ({ record: { key: {} }, list: [[7, 4]] }),
(draft, place) => {
const list = draft.list;
const item = list[0];
place(list);
item.push(9);
list.unshift(item);
},
optionSets[0]
);
const element = patches.findIndex((patch) => patch.path.length === 3);
const list = patches.findIndex(
(patch) => patch.path.length === 2 && patch.path[0] === 'list'
);
expect(element).toBeGreaterThan(-1);
expect(element).toBeLessThan(list);
});

test('random edits and moves of a placed list replay in both directions', () => {
// Park-Miller generator: the same recipes on every run.
let seed = 7;
const random = () => (seed = (seed * 16807) % 2147483647) / 2147483647;
const int = (n: number) => Math.floor(random() * n);
// Reads only create drafts, so that later keys' nodes come after theirs.
const read = (value: unknown) => value;
const keys = ['a', 'b', 'c'];
const failures: unknown[] = [];
for (let run = 0; run < 1000; run += 1) {
const list: any[] = [];
for (let index = 2 + int(4); index > 0; index -= 1) {
const kind = random();
list.push(
kind < 0.15
? index
: kind < 0.55
? [index, index + 1]
: { v: index, deep: [index] }
);
}
const base = {
record: { a: {}, b: {}, c: {} } as Record<string, any>,
list,
};
const steps = Array.from({ length: 2 + int(7) }, () => [
int(11),
int(8),
int(8),
int(100),
]);
const options = optionSets[int(3)];
try {
const [state, patches, inversePatches] = create(
base,
(draft) => {
for (const [op, i, j, k] of steps) {
const items = draft.list;
const n = items.length;
const x = n ? i % n : 0;
const y = n ? j % n : 0;
const record = draft.record;
const key = keys[i % 3];
if (op === 0 && n) read(items[x]);
else if (op === 1 && n) {
const item = items[x];
if (Array.isArray(item)) item.push(k);
else if (item && typeof item === 'object') {
if (k % 2) item.v = k;
else item.deep.push(k);
}
} else if (op === 2) {
// The list is placed at a key read after its drafts.
read(record[key]);
record[key] = items;
} else if (op === 3) items.unshift(n && k % 2 ? items[y] : [k]);
else if (op === 4) items.shift();
else if (op === 5) {
if (k % 3 === 0) items.splice(x, 1);
else if (k % 3 === 1 && n) items.splice(x, 0, items[y]);
else items.splice(x, 1, [k]);
} else if (op === 6) items.reverse();
else if (op === 7 && n) items[x] = items[y];
else if (op === 8 && n) {
const item = items[x];
items[x] = [k];
items[x] = item;
} else if (op === 9 && n) {
const item = items[x];
if (item && typeof item === 'object') record[key] = item;
} else if (op === 10 && n) items[x] = k;
}
},
options
);
if (
!isDeepStrictEqual(apply(base, patches), state) ||
!isDeepStrictEqual(apply(state, inversePatches), base)
) {
failures.push(steps);
}
} catch {
failures.push(steps);
}
}
expect(failures).toStrictEqual([]);
});
});
Loading
Loading