diff --git a/src/current.ts b/src/current.ts index 2679cfd4..eaa45a85 100644 --- a/src/current.ts +++ b/src/current.ts @@ -130,11 +130,15 @@ function getCurrent(target: any, rootOptions?: Options) { 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 diff --git a/src/utils/finalize.ts b/src/utils/finalize.ts index b72246da..e68e55e4 100644 --- a/src/utils/finalize.ts +++ b/src/utils/finalize.ts @@ -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. @@ -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); @@ -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 diff --git a/test/current.test.ts b/test/current.test.ts index d86016a7..7efe182c 100644 --- a/test/current.test.ts +++ b/test/current.test.ts @@ -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', () => { @@ -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; + }); +}); diff --git a/test/moved-child-patches.test.ts b/test/moved-child-patches.test.ts index 25ac9346..7abc79fb 100644 --- a/test/moved-child-patches.test.ts +++ b/test/moved-child-patches.test.ts @@ -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, + 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([]); + }); +}); diff --git a/test/nested-create.test.ts b/test/nested-create.test.ts index 375fb70c..f4cf1f0a 100644 --- a/test/nested-create.test.ts +++ b/test/nested-create.test.ts @@ -1,4 +1,4 @@ -import { create } from '../src'; +import { apply, create, type Patches } from '../src'; describe('drafts whose original is a draft of an outer create() call', () => { test('a Set draft is copied through the outer draft', () => { @@ -42,3 +42,100 @@ describe('drafts whose original is a draft of an outer create() call', () => { expect(state).toBe(base); }); }); + +// The inner call finalizes the value it drafted at the key it read, where it +// finds the outer draft instead; that draft is left to the outer call. +describe('a draft of an outer create() call placed where an inner one read', () => { + const makeBase = () => ({ item: { value: 0, nested: { value: 0 } } }); + const placements: [string, (innerDraft: any, item: any) => void][] = [ + [ + 'at a key', + (innerDraft, item) => { + expect(innerDraft.slot).toEqual({}); + innerDraft.slot = item; + }, + ], + [ + 'at a key and at a new key', + (innerDraft, item) => { + expect(innerDraft.slot).toEqual({}); + innerDraft.slot = item; + innerDraft.extra = item; + }, + ], + [ + 'at an index and at a new key', + (innerDraft, item) => { + expect(innerDraft.list[0]).toEqual({}); + innerDraft.list[0] = item; + innerDraft.extra = item; + }, + ], + ]; + + test.each(placements)('%s', (_, place) => { + const base = makeBase(); + let innerPatches: Patches = []; + const [state, patches, inversePatches] = create( + base, + (draft) => { + draft.item.value = 1; + [, innerPatches] = create( + { slot: {}, list: [{}] }, + (innerDraft) => place(innerDraft, draft.item), + { enablePatches: true } + ); + // The outer recipe still changes the draft after the inner call. + draft.item.nested.value = 2; + }, + { enablePatches: true } + ); + expect(base).toStrictEqual(makeBase()); + expect(state).toStrictEqual({ item: { value: 1, nested: { value: 2 } } }); + expect(apply(makeBase(), patches)).toStrictEqual(state); + expect(apply(state, inversePatches)).toStrictEqual(makeBase()); + // The inner patches address the inner state only. + expect(innerPatches.some((patch) => patch.path[0] === 'item')).toBe(false); + expect(() => apply({ slot: {}, list: [{}] }, innerPatches)).not.toThrow(); + }); + + // An inner call that finalized the outer draft would mark it done whether + // or not either call makes patches, and the outer recipe would then change + // the base through it. + const patchOptions: [boolean, boolean][] = [ + [false, false], + [true, false], + [false, true], + ]; + test.each( + placements.flatMap(([name, place]) => + patchOptions.map( + ([outer, inner]): [string, boolean, boolean, typeof place] => [ + name, + outer, + inner, + place, + ] + ) + ) + )( + '%s, with outer patches %s and inner patches %s', + (_, outer, inner, place) => { + const base = makeBase(); + const recipe = (draft: ReturnType) => { + draft.item.value = 1; + create( + { slot: {}, list: [{}] }, + (innerDraft) => place(innerDraft, draft.item), + { enablePatches: inner } + ); + draft.item.nested.value = 2; + }; + const state = outer + ? create(base, recipe, { enablePatches: true })[0] + : create(base, recipe); + expect(base).toStrictEqual(makeBase()); + expect(state).toStrictEqual({ item: { value: 1, nested: { value: 2 } } }); + } + ); +}); diff --git a/test/shared-draft-patches.test.ts b/test/shared-draft-patches.test.ts new file mode 100644 index 00000000..f0a6ffe8 --- /dev/null +++ b/test/shared-draft-patches.test.ts @@ -0,0 +1,246 @@ +/* eslint-disable no-void -- Pre-reads intentionally discard values to control draft creation order. */ +import { apply, create, type Patches } from '../src'; + +type SharedValue = number[] | { inner: SharedValue }; +type SharedParent = { q: SharedValue; extra?: SharedValue }; +type State = { + a: SharedParent; + b: Partial; + c: { x: SharedValue }; +}; + +function sharedValue(depth: number, values: number[]): SharedValue { + return depth === 0 ? values : { inner: sharedValue(depth - 1, values) }; +} + +function changedArray(value: SharedValue): number[] { + return Array.isArray(value) ? value : changedArray(value.inner); +} + +function makeBase(depth: number): State { + return { a: { q: sharedValue(depth, [0]) }, b: {}, c: { x: [] } }; +} + +const readOrders: { + name: string; + before: ('b' | 'c.x')[]; + readB: boolean; + readX: boolean; +}[] = [ + { + name: 'both reads before assignment', + before: [], + readB: true, + readX: true, + }, + { name: 'only b read', before: [], readB: true, readX: false }, + { name: 'only c.x read', before: [], readB: false, readX: true }, + { name: 'no pre-reads', before: [], readB: false, readX: false }, + { name: 'b read first', before: ['b'], readB: false, readX: true }, + { name: 'c.x read first', before: ['c.x'], readB: true, readX: false }, + { + name: 'b then c.x read first', + before: ['b', 'c.x'], + readB: false, + readX: false, + }, + { + name: 'c.x then b read first', + before: ['c.x', 'b'], + readB: false, + readX: false, + }, +]; + +const configurations = [false, true].flatMap((enableAutoFreeze) => + [false, true].flatMap((pathAsArray) => + [false, true].map((arrayLengthAssignment) => ({ + enableAutoFreeze, + enablePatches: { pathAsArray, arrayLengthAssignment }, + })) + ) +); + +describe.each(configurations)( + 'shared draft patches with options %j', + (options) => { + describe.each([0, 1, 2])('shared draft depth %i', (depth) => { + test.each(readOrders)('$name', ({ before, readB, readX }) => { + const base = makeBase(depth); + const [state, patches, inversePatches] = create( + base, + (draft) => { + // Reads create drafts whose finalization order must not affect replay. + for (const key of before) { + if (key === 'b') void draft.b; + else void draft.c.x; + } + const q = draft.a.q; + const values = changedArray(q); + if (readB) void draft.b; + draft.b = draft.a; + if (readX) void draft.c.x; + // The changed array itself is shared, also when q nests it: with + // c.x read after it, c.x finds it before its own node, the order + // in which #217 generated its patches twice. + draft.c.x = values; + draft.a.extra = q; + values.push(1); + }, + options + ); + + const expectedValue = sharedValue(depth, [0, 1]); + const expectedParent = { q: expectedValue, extra: expectedValue }; + expect(state).toStrictEqual({ + a: expectedParent, + b: expectedParent, + c: { x: [0, 1] }, + }); + expect(state.b).toBe(state.a); + expect(state.c.x).toBe(changedArray(state.a.q as SharedValue)); + expect(state.a.extra).toBe(state.a.q); + expect(Object.isFrozen(state)).toBe(options.enableAutoFreeze); + expect(apply(base, patches)).toStrictEqual(state); + expect(apply(state, inversePatches)).toStrictEqual(base); + + // Serialized patches must also support persistence and undo/redo. + const serializedPatches = JSON.parse(JSON.stringify(patches)); + const serializedInverse = JSON.parse(JSON.stringify(inversePatches)); + const replayed = apply(makeBase(depth), serializedPatches); + expect(replayed).toStrictEqual(state); + const restored = apply(replayed, serializedInverse); + expect(restored).toStrictEqual(base); + expect(apply(restored, serializedPatches)).toStrictEqual(state); + expect(base).toStrictEqual(makeBase(depth)); + + const arrayPath = ['a', 'q', ...Array(depth).fill('inner'), 1]; + const path = options.enablePatches.pathAsArray + ? arrayPath + : `/${arrayPath.join('/')}`; + expect( + patches.filter( + (patch) => JSON.stringify(patch.path) === JSON.stringify(path) + ) + ).toStrictEqual([{ op: 'add', path, value: 1 }]); + }); + }); + } +); + +type ListState = { + a: { q: number[]; extra?: number[] }; + b: { q?: number[]; extra?: number[] }; + c: { x: number[] }; +}; + +const makeListBase = (): ListState => ({ + a: { q: [0, 1, 2] }, + b: {}, + c: { x: [] }, +}); + +const removals: [string, (values: number[]) => void][] = [ + [ + 'pop', + (values) => { + values.pop(); + }, + ], + [ + 'splice', + (values) => { + values.splice(1, 1); + }, + ], + [ + 'shift', + (values) => { + values.shift(); + }, + ], +]; + +// A repeated inverse patch restores a removed item twice, which breaks undo. +describe.each( + [false, true].flatMap((strict) => + [false, true].map((arrayLengthAssignment) => ({ + strict, + enablePatches: { arrayLengthAssignment }, + })) + ) +)('shared draft removals with options %j', (options) => { + test.each(removals)('%s', (_, remove) => { + const base = makeListBase(); + const [state, patches, inversePatches] = create( + base, + (draft) => { + const q = draft.a.q; + void draft.b; + draft.b = draft.a; + void draft.c.x; + draft.c.x = q; + draft.a.extra = q; + remove(q); + }, + options + ); + expect(apply(base, patches)).toStrictEqual(state); + expect(apply(state, inversePatches)).toStrictEqual(base); + expect(base).toStrictEqual(makeListBase()); + }); +}); + +const sharedDrafts: [string, () => object, (value: any) => void][] = [ + [ + 'object', + () => ({ k: 0 }), + (value) => { + value.n = 1; + }, + ], + [ + 'Map', + () => new Map([['k', 0]]), + (value) => { + value.set('n', 1); + }, + ], + [ + 'Set', + () => new Set([0]), + (value) => { + value.add(1); + }, + ], +]; + +describe.each([false, true])('shared drafts with strict %s', (strict) => { + test.each(sharedDrafts)( + 'a shared %s draft generates its patches once', + (_, make, change) => { + const base: any = { a: { q: make() }, b: {}, c: { x: {} } }; + const [state, patches, inversePatches] = create( + base, + (draft: any) => { + const q = draft.a.q; + void draft.b; + draft.b = draft.a; + void draft.c.x; + draft.c.x = q; + draft.a.extra = q; + change(q); + }, + { enablePatches: true, strict } + ); + const inQ = (list: Patches) => + list.filter( + (patch) => patch.path.length === 3 && patch.path[1] === 'q' + ); + expect(inQ(patches)).toHaveLength(1); + expect(inQ(inversePatches)).toHaveLength(1); + expect(apply(base, patches)).toStrictEqual(state); + expect(apply(state, inversePatches)).toStrictEqual(base); + } + ); +});