fix: Refactored patch array generation, fixes #468
Before adoption: this commit came in with the history the project adopted, so no landing records it.
authored by Michel Weststrate · committed by Michel Weststrate · parent 67afcdd · Browse files · 4 files·+200 added−96 removed
This commit
State
Before adoption: this commit came in with the history the project adopted, so no landing records it.
Diff stats
4 files+200 added−96 removed
- tests:+117 added−71 removed
- other:+83 added−25 removed
Provenance
- Commit
9f75bf5- Tree
171e2be- Author
Michel Weststrate <mweststrate@fb.com>- Committer
Michel Weststrate <mweststrate@fb.com>- Parent
67afcdd
4 files changed+200 added−96 removed
modified:__tests__/patch.js+117 added-71 removed
5 unmodified lines6 enableAllPlugins,7 isDraft,8 immerable9 } from "../src/immer"10+import {run} from "jest"11 12 enableAllPlugins()13 14 jest.setTimeout(1000)285 unmodified lines300 ]301 )302 })303 304+ describe("nested change in object", () => {305+ runPatchTest(306+ {307+ a: {b: 1}308+ },309+ d => {310+ d.a.b++311+ },312+ [{op: "replace", path: ["a", "b"], value: 2}],313+ [{op: "replace", path: ["a", "b"], value: 1}]314+ )315+ })316+317+ describe("nested change in map", () => {318+ runPatchTest(319+ new Map([["a", new Map([["b", 1]])]]),320+ d => {321+ d.get("a").set("b", 2)322+ },323+ [{op: "replace", path: ["a", "b"], value: 2}],324+ [{op: "replace", path: ["a", "b"], value: 1}]325+ )326+ })327+328+ describe("nested change in array", () => {329+ runPatchTest(330+ [[{b: 1}]],331+ d => {332+ d[0][0].b++333+ },334+ [{op: "replace", path: [0, 0, "b"], value: 2}],335+ [{op: "replace", path: [0, 0, "b"], value: 1}]336+ )337+ })338+339 describe("nested map (no changes)", () => {340 runPatchTest(341 new Map([["a", new Map([["b", 1]])]]),342 d => {169 unmodified lines512 {x: [1, 2, 3]},513 d => {514 d.x.unshift(4)515 },480- [{op: "add", path: ["x", 0], value: 4}]516+ [517+ {op: "replace", path: ["x", 0], value: 4},518+ {op: "replace", path: ["x", 1], value: 1},519+ {op: "replace", path: ["x", 2], value: 2},520+ {op: "add", path: ["x", 3], value: 3}521+ ]522 )523 })524 525 describe("arrays - multiple prepend", () => {1 unmodified line527 {x: [1, 2, 3]},528 d => {529 d.x.unshift(4)530 d.x.unshift(5)531+ // 4,5,1,2,3532 },533 [492- {op: "add", path: ["x", 0], value: 5},493- {op: "add", path: ["x", 1], value: 4}534+ {op: "replace", path: ["x", 0], value: 5},535+ {op: "replace", path: ["x", 1], value: 4},536+ {op: "replace", path: ["x", 2], value: 1},537+ {op: "add", path: ["x", 3], value: 2},538+ {op: "add", path: ["x", 4], value: 3}539 ]540 )541 })542 2 unmodified lines545 {x: [1, 2, 3]},546 d => {547 d.x.splice(1, 1)548 },504- [{op: "remove", path: ["x", 1]}]549+ [550+ {op: "replace", path: ["x", 1], value: 3},551+ {op: "replace", path: ["x", "length"], value: 2}552+ ]553 )554 })555 556 describe("arrays - multiple splice", () => {557 runPatchTest(558 [0, 1, 2, 3, 4, 5, 0],559 d => {560 d.splice(4, 2, 3)561+ // [0,1,2,3,3,0]562 d.splice(1, 2, 3)563+ // [0,3,3,3,0]564+ expect(d.slice()).toEqual([0, 3, 3, 3, 0])565 },566 [567 {op: "replace", path: [1], value: 3},568 {op: "replace", path: [2], value: 3},518- {op: "remove", path: [5]},519- {op: "remove", path: [4]}569+ {op: "replace", path: [4], value: 0},570+ {op: "replace", path: ["length"], value: 5}571 ]572 )573 })574 2 unmodified lines577 {x: [1, 2, 3]},578 d => {579 d.x[0] = 4580 d.x.length = 2581+ // [0, 2]582 },583 [584 {op: "replace", path: ["x", 0], value: 4},533- {op: "remove", path: ["x", 2]}585+ {op: "replace", path: ["x", "length"], value: 2}586 ],587 [588 {op: "replace", path: ["x", 0], value: 1},589 {op: "add", path: ["x", 2], value: 3}6 unmodified lines596 {x: [1, 2, 3]},597 d => {598 d.x.unshift(4)599 d.x.splice(2, 1)600+ // 4, 1, 3601 },602 [603 {op: "replace", path: ["x", 0], value: 4},604 {op: "replace", path: ["x", 1], value: 1}6 unmodified lines611 {x: [1, 2, 3]},612 d => {613 d.x.splice(1, 1)614 d.x.unshift(4)615+ // [4, 1, 3]616 },617 [618 {op: "replace", path: ["x", 0], value: 4},619 {op: "replace", path: ["x", 1], value: 1}6 unmodified lines626 {x: [1, 2, 3]},627 d => {628 d.x.length -= 2629 },630+ [{op: "replace", path: ["x", "length"], value: 1}],631 [577- {op: "remove", path: ["x", 2]},578- {op: "remove", path: ["x", 1]}579- ],580- [632 {op: "add", path: ["x", 1], value: 2},633 {op: "add", path: ["x", 2], value: 3}634 ]635 )5 unmodified lines641 d => {642 d.x.pop()643 d.x.pop()644 },594- [595- {op: "remove", path: ["x", 2]},596- {op: "remove", path: ["x", 1]}597- ]645+ [{op: "replace", path: ["x", "length"], value: 1}]646 )647 })648 649 describe("arrays - push multiple", () => {650+ // These patches were more optimal pre immer 7, but not always correct651 runPatchTest(652 {x: [1, 2, 3]},653 d => {654 d.x.push(4, 5)1 unmodified line656 [657 {op: "add", path: ["x", 3], value: 4},658 {op: "add", path: ["x", 4], value: 5}659 ],611- [612- {op: "remove", path: ["x", 4]},613- {op: "remove", path: ["x", 3]}614- ]660+ [{op: "replace", path: ["x", "length"], value: 3}]661 )662 })663 664 describe("arrays - splice (expand)", () => {665+ // These patches were more optimal pre immer 7, but not always correct666 runPatchTest(667 {x: [1, 2, 3]},668 d => {622- d.x.splice(1, 1, 4, 5, 6)669+ d.x.splice(1, 1, 4, 5, 6) // [1,4,5,6,3]670 },671 [672 {op: "replace", path: ["x", 1], value: 4},626- {op: "add", path: ["x", 2], value: 5},627- {op: "add", path: ["x", 3], value: 6}673+ {op: "replace", path: ["x", 2], value: 5},674+ {op: "add", path: ["x", 3], value: 6},675+ {op: "add", path: ["x", 4], value: 3}676 ],677 [678 {op: "replace", path: ["x", 1], value: 2},631- {op: "remove", path: ["x", 3]},632- {op: "remove", path: ["x", 2]}679+ {op: "replace", path: ["x", 2], value: 3},680+ {op: "replace", path: ["x", "length"], value: 3}681 ]682 )683 })684 685 describe("arrays - splice (shrink)", () => {686+ // These patches were more optimal pre immer 7, but not always correct687 runPatchTest(688 {x: [1, 2, 3, 4, 5]},689 d => {641- d.x.splice(1, 3, 6)690+ d.x.splice(1, 3, 6) // [1, 6, 5]691 },692 [693 {op: "replace", path: ["x", 1], value: 6},645- {op: "remove", path: ["x", 3]},646- {op: "remove", path: ["x", 2]}694+ {op: "replace", path: ["x", 2], value: 5},695+ {op: "replace", path: ["x", "length"], value: 3}696 ],697 [698 {op: "replace", path: ["x", 1], value: 2},650- {op: "add", path: ["x", 2], value: 3},651- {op: "add", path: ["x", 3], value: 4}699+ {op: "replace", path: ["x", 2], value: 3},700+ {op: "add", path: ["x", 3], value: 4},701+ {op: "add", path: ["x", 4], value: 5}702 ]703 )704 })705 81 unmodified lines787 )788 })789 790 describe("arrays - splice should should result in remove op.", () => {791+ // These patches were more optimal pre immer 7, but not always correct792 runPatchTest(793 [1, 2],794 d => {795 d.splice(1, 1)796 },746- [{op: "remove", path: [1]}],797+ [{op: "replace", path: ["length"], value: 1}],798 [{op: "add", path: [1], value: 2}]799 )800 })801 802 describe("arrays - NESTED splice should should result in remove op.", () => {803+ // These patches were more optimal pre immer 7, but not always correct804 runPatchTest(805 {a: {b: {c: [1, 2]}}},806 d => {807 d.a.b.c.splice(1, 1)808 },757- [{op: "remove", path: ["a", "b", "c", 1]}],809+ [{op: "replace", path: ["a", "b", "c", "length"], value: 1}],810 [{op: "add", path: ["a", "b", "c", 1], value: 2}]811 )812 })813 189 unmodified lines1003 })1004 ).toEqual({x: -1})1005 })1006 955-test.skip("#468", () => {956- const item = {id: 1}1007+describe("#468", () => {1008+ function run() {1009+ const item = {id: 1}1010+ const state = [item]1011+ const [nextState, patches] = produceWithPatches(state, draft => {1012+ draft[0].id = 21013+ draft[1] = item1014+ })1015 958- const state = [item]1016+ expect(nextState).toEqual([{id: 2}, {id: 1}])1017+ expect(patches).toEqual([1018+ {1019+ op: "replace",1020+ path: [0, "id"],1021+ value: 21022+ },1023+ {1024+ op: "add",1025+ path: [1],1026+ value: {1027+ id: 11028+ }1029+ }1030+ ])1031 960- const [nextState, patches] = produceWithPatches(state, draft => {961- draft[0].id = 2962- draft[1] = item1032+ const final = applyPatches(state, patches)1033+ expect(final).toEqual(nextState)1034+ }1035+1036+ test("es5", () => {1037+ setUseProxies(false)1038+ run()1039 })1040 965- expect(nextState).toMatchInlineSnapshot(`966- Array [967- Object {968- "id": 2,969- },970- Object {971- "id": 1,972- },973- ]974- `)975- expect(patches).toMatchInlineSnapshot(`976- Array [977- Object {978- "op": "replace",979- "path": Array [980- 0,981- "id",982- ],983- "value": 2,984- },985- Object {986- "op": "add",987- "path": Array [988- 0,989- ],990- "value": Object {991- "id": 2,992- },993- },994- ]995- `)996-997- const final = applyPatches(state, patches)998- expect(final).toEqual(nextState)1041+ test("proxy", () => {1042+ setUseProxies(true)1043+ run()1044+ })1045 })1046 1047 test("#521", () => {1048 const state = new Map()74 unmodified linesmodified:src/core/finalize.ts+7 added-1 removed
18 unmodified lines19202122232425262759 unmodified lines8788899091929394959697984 unmodified lines10310410510610210710810911011111250 unmodified lines18 unmodified lines revokeScope, isFrozen, shallowCopy} from "../internal"import {ProxyTypeProxyArray} from "../types/types-internal"
export function processResult(result: any, scope: ImmerScope) { scope.unfinalizedDrafts_ = scope.drafts_.length const baseDraft = scope.drafts_![0]59 unmodified lines // For ES5, create a good copy from the draft first, with added keys and without deleted keys. state.type_ === ProxyTypeES5Object || state.type_ === ProxyTypeES5Array ? (state.copy_ = shallowCopy(state.draft_)) : state.copy_ const originalCopy = state.type_ === ProxyTypeES5Array || state.type_ === ProxyTypeProxyArray ? result.slice() : undefined // finalize all children of the copy each(result as any, (key, childValue) => finalizeProperty(rootScope, state, result, key, childValue, path) )4 unmodified lines getPlugin("Patches").generatePatches_( state, path, rootScope.patches_, rootScope.inversePatches_! rootScope.inversePatches_!, originalCopy ) } } return state.copy_50 unmodified linesmodified:src/plugins/patches.ts+74 added-23 removed
25 unmodified lines26 ArchtypeArray,27 die28 } from "../internal"29 import {isDraft} from "../utils/common"30+import {DRAFT_STATE} from "../utils/env"31 32 export function enablePatches() {33 const REPLACE = "replace"34 const ADD = "add"2 unmodified lines37 function generatePatches_(38 state: ImmerState,39 basePath: PatchPath,40 patches: Patch[],40- inversePatches: Patch[]41+ inversePatches: Patch[],42+ originalCopy: any43 ): void {44 switch (state.type_) {45 case ProxyTypeProxyObject:46 case ProxyTypeES5Object:5 unmodified lines52 inversePatches53 )54 case ProxyTypeES5Array:55 case ProxyTypeProxyArray:54- return generateArrayPatches(state, basePath, patches, inversePatches)56+ return generateArrayPatches(57+ state,58+ basePath,59+ patches,60+ inversePatches,61+ originalCopy62+ )63 case ProxyTypeSet:64 return generateSetPatches(65 (state as any) as SetState,66 basePath,6 unmodified lines73 function generateArrayPatches(74 state: ES5ArrayState | ProxyArrayState,75 basePath: PatchPath,76 patches: Patch[],69- inversePatches: Patch[]77+ inversePatches: Patch[],78+ originalCopy: any[]79 ) {80+ // TODO: we need originalCopy to determine the indices that remained81 let {base_, assigned_} = state82 let copy_ = state.copy_!83 84 // Reduce complexity by ensuring `base` is never longer.2 unmodified lines87 ;[base_, copy_] = [copy_, base_]88 ;[patches, inversePatches] = [inversePatches, patches]89 }90 81- const delta = copy_.length - base_.length91+ // for (let i = 0; i < base_.length; i++) {92+ // const origValue = base_[i];93+ // const value = copy_[i];94+ // if (assigned_[i]) {95+ // const path = basePath.concat([i]);96+ // patches.push({97+ // op: REPLACE,98+ // path,99+ // value: clonePatchValueIfNeeded(value)100+ // })101+ // inversePatches.push({102+ // op: REPLACE,103+ // path,104+ // value: clonePatchValueIfNeeded(origValue)105+ // })106+ // }107+ // }108+ // if (base_.length !== copy_.length) {109+ // inversePatches.push({110+ // op: REPLACE,111+ // path: basePath.concat(["length"]),112+ // value: base_.length113+ // })114+ // for (let i = base_.length; i < copy_.length; i++) {115 83- // Find the first replaced index.84- let start = 085- while (base_[start] === copy_[start] && start < base_.length) {86- ++start87- }116+ // }117+ // }118+ // if (copy_.length < base_.length) {119+ // const path =120+ // patches.push({})121+ // }122 89- // Find the last replaced index. Search from the end to optimize splice patches.90- let end = base_.length91- while (end > start && base_[end - 1] === copy_[end + delta - 1]) {92- --end93- }123+ // const delta = copy_.length - base_.length124 125+ // // Find the first replaced index.126+ // let start = 0127+ // while (128+ // (base_[start] === copy_[start] ||129+ // base_[start] === copy_[start]?.[DRAFT_STATE]?.base) &&130+ // start < base_.length131+ // ) {132+ // ++start133+ // }134+135+ // // Find the last replaced index. Search from the end to optimize splice patches.136+ // let end = base_.length137+ // while (end > start && base_[end - 1] === copy_[end + delta - 1]) {138+ // --end139+ // }140+141 // Process replaced indices.96- for (let i = start; i < end; ++i) {97- if (assigned_[i] && copy_[i] !== base_[i]) {142+ for (let i = 0; i < base_.length; i++) {143+ const draft = originalCopy[i] && originalCopy[i][DRAFT_STATE]144+ if (145+ assigned_[i] &&146+ (draft ? draft.base_ !== base_[i] : copy_[i] !== base_[i])147+ ) {148 const path = basePath.concat([i])149 patches.push({150 op: REPLACE,151 path,8 unmodified lines160 })161 }162 }163 114- const replaceCount = patches.length115-164 // Process added indices.117- for (let i = end + delta - 1; i >= end; --i) {165+ for (let i = base_.length; i < copy_.length; i++) {166 const path = basePath.concat([i])119- patches[replaceCount + i - end] = {167+ patches.push({168 op: ADD,169 path,170 // Need to maybe clone it, as it can in fact be the original value171 // due to the base/copy inversion at the start of this function172 value: clonePatchValueIfNeeded(copy_[i])125- }173+ })174+ }175+ if (base_.length < copy_.length) {176 inversePatches.push({127- op: REMOVE,128- path177+ op: REPLACE,178+ path: basePath.concat(["length"]),179+ value: base_.length180 })181 }182 }183 174 unmodified linesmodified:src/utils/plugins.ts+2 added-1 removed
19 unmodified lines20 generatePatches_(21 state: ImmerState,22 basePath: PatchPath,23 patches: Patch[],24- inversePatches: Patch[]24+ inversePatches: Patch[],25+ originalCopy: any26 ): void27 generateReplacementPatches_(28 rootState: ImmerState,29 replacement: any,84 unmodified lines