Patches now also succeed for ES5. Patches generated are more optimal
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 11a2d24 · Browse files · 4 files·+385 added−102 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+385 added−102 removed
- tests:+241 added−79 removed
- other:+144 added−23 removed
Provenance
- Commit
fd9ed2d- Tree
0635239- Author
Michel Weststrate <mweststrate@gmail.com>- Committer
Michel Weststrate <mweststrate@gmail.com>- Parent
11a2d24
4 files changed+385 added−102 removed
modified:__tests__/base.js+36 added
917 unmodified lines918 })919 expect(nextState).toBe(baseState)920 })921 922+ it("should not detect noop assignments - 0", () => {923+ const baseState = {x: {y: 3}}924+ const nextState = produce(baseState, d => {925+ const a = d.x926+ d.x = a927+ })928+ expect(nextState).toBe(baseState)929+ })930+931+ it("should not detect noop assignments - 1", () => {932+ const baseState = {x: {y: 3}}933+ const nextState = produce(baseState, d => {934+ const a = d.x935+ d.x = 4936+ d.x = a937+ })938+ // Ideally, this should actually be the same instances939+ // but this would be pretty expensive to detect,940+ // so we don't atm941+ expect(nextState).not.toBe(baseState)942+ })943+944+ it("should not detect noop assignments - 2", () => {945+ const baseState = {x: {y: 3}}946+ const nextState = produce(baseState, d => {947+ const a = d.x948+ const stuff = a.y + 3949+ d.x = 4950+ d.x = a951+ })952+ // Ideally, this should actually be the same instances953+ // but this would be pretty expensive to detect,954+ // so we don't atm955+ expect(nextState).not.toBe(baseState)956+ })957+958 it("immer should have no dependencies", () => {959 expect(require("../package.json").dependencies).toEqual(undefined)960 })961 25 unmodified linesmodified:__tests__/patch.js+205 added-79 removed
123456678991011121213141516171819202122232425242627282928303132333433353637383940394041424344454641424344454647484950484950515253545551525354555657585960575859606162636461626364656667686970666768697071727371727374757677787980757677787980818283848182838485868788899091928687888990919293949596979893949596979899100101102103104105106107100101102103104105106107108109110111112113114108109110111112113114115116117118119120121122116117118123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244"use strict"import produce, {setUseProxies, applyPatches} from "../src/immer"
jest.setTimeout(1000)
function runPatchTest(name, base, producer, patches) {function runPatchTest(base, producer, patches, inversePathes) { function runPatchTestHelper() { let recordedPatches let inversePatches let recordedInversePatches const res = produce(base, producer, (p, i) => { recordedPatches = p inversePatches = i recordedInversePatches = i })
test("produces the correct patches", () => { expect(recordedPatches).toEqual(patches) if (inversePathes) expect(recordedInversePatches).toEqual(inversePathes) })
test("patches are replayable", () => { expect(applyPatches(base, recordedPatches)).toEqual(res) })
test("patches can be revered", () => { expect(applyPatches(res, inversePatches)).toEqual(base) expect(applyPatches(res, recordedInversePatches)).toEqual(base) }) }
describe(`patches - ${name} - proxy`, () => { describe(`proxy`, () => { setUseProxies(true) runPatchTestHelper() })
describe(`patches - ${name} - es5`, () => { describe(`es5`, () => { setUseProxies(false) runPatchTestHelper() })}
runPatchTest( "simple assignment", {x: 3}, d => { d.x++ }, [{op: "replace", path: ["x"], value: 4}])describe("simple assignment", () => { runPatchTest( {x: 3}, d => { d.x++ }, [{op: "replace", path: ["x"], value: 4}] )})
runPatchTest( "simple assignment - 2", {x: {y: 4}}, d => { d.x.y++ }, [{op: "replace", path: ["x", "y"], value: 5}])describe("simple assignment - 2", () => { runPatchTest( {x: {y: 4}}, d => { d.x.y++ }, [{op: "replace", path: ["x", "y"], value: 5}] )})
runPatchTest( "simple assignment - 2", {x: {y: 4}}, d => { d.x.y++ }, [{op: "replace", path: ["x", "y"], value: 5}])describe("simple assignment - 2", () => { runPatchTest( {x: {y: 4}}, d => { d.x.y++ }, [{op: "replace", path: ["x", "y"], value: 5}] )})
runPatchTest( "delete 1", {x: {y: 4}}, d => { delete d.x }, [{op: "remove", path: ["x"]}])describe("delete 1", () => { runPatchTest( {x: {y: 4}}, d => { delete d.x }, [{op: "remove", path: ["x"]}] )})
runPatchTest( "moving stuff", {x: {y: 4}}, d => { d.z = d.x d.z.y++ delete d.x }, [{op: "replace", path: ["z"], value: {y: 5}}, {op: "remove", path: ["x"]}])describe("moving stuff", () => { runPatchTest( {x: {y: 4}}, d => { d.z = d.x d.z.y++ delete d.x }, [{op: "add", path: ["z"], value: {y: 5}}, {op: "remove", path: ["x"]}] )})
runPatchTest( "minimum amount of changes", {x: 3, y: {a: 4}, z: 3}, d => { d.y.a = 4 d.y.b = 5 Object.assign(d, {x: 4, y: {a: 2}}) }, [ {op: "replace", path: ["x"], value: 4}, {op: "replace", path: ["y"], value: {a: 2}} ])describe("minimum amount of changes", () => { runPatchTest( {x: 3, y: {a: 4}, z: 3}, d => { d.y.a = 4 d.y.b = 5 Object.assign(d, {x: 4, y: {a: 2}}) }, [ {op: "replace", path: ["x"], value: 4}, {op: "replace", path: ["y"], value: {a: 2}} ] )})
runPatchTest( "arrays", {x: [1, 2, 3]}, d => { d.x.unshift(4) d.x.splice(2, 1) }, [ {op: "replace", path: ["x", "0"], value: 4}, {op: "replace", path: ["x", "1"], value: 1}, {op: "replace", path: ["x", "2"], value: 3}, {op: "remove", path: ["x", "3"]}, {op: "replace", path: ["x", "length"], value: 3} ])describe("arrays - 1", () => { runPatchTest( {x: [1, 2, 3]}, d => { d.x.unshift(4) }, [ {op: "replace", path: ["x", 0], value: 4}, {op: "replace", path: ["x", 1], value: 1}, {op: "replace", path: ["x", 2], value: 2}, {op: "add", path: ["x", 3], value: 3} ] )})
runPatchTest("simple replacement", {x: 3}, _d => 4, [ {op: "replace", path: [], value: 4}])describe("arrays - 2", () => { runPatchTest( {x: [1, 2, 3]}, d => { d.x.splice(1, 1) }, [ {op: "replace", path: ["x", 1], value: 3}, {op: "replace", path: ["x", "length"], value: 2} ] )})
describe("arrays - 3", () => { runPatchTest( {x: [1, 2, 3]}, d => { d.x.unshift(4) d.x.splice(2, 1) }, [ {op: "replace", path: ["x", 0], value: 4}, {op: "replace", path: ["x", 1], value: 1} ] )})
describe("arrays - 4", () => { runPatchTest( {x: [1, 2, 3]}, d => { d.x.splice(1, 1) d.x.unshift(4) }, [ {op: "replace", path: ["x", 0], value: 4}, {op: "replace", path: ["x", 1], value: 1} ] )})
describe("arrays - 5a", () => { runPatchTest( {x: [1, 2, 3]}, d => { d.x.length -= 2 }, [{op: "replace", path: ["x", "length"], value: 1}], [ {op: "add", path: ["x", 1], value: 2}, {op: "add", path: ["x", 2], value: 3} ] )})
describe("arrays - 5b", () => { runPatchTest( {x: [1, 2, 3]}, d => { d.x.pop() d.x.pop() }, [{op: "replace", path: ["x", "length"], value: 1}] )})
describe("arrays - 6", () => { runPatchTest( {x: [1, 2, 3]}, d => { d.x.push(4, 5) }, [ {op: "add", path: ["x", 3], value: 4}, {op: "add", path: ["x", 4], value: 5} ], [{op: "replace", path: ["x", "length"], value: 3}] )})
describe("simple replacement", () => { runPatchTest({x: 3}, _d => 4, [{op: "replace", path: [], value: 4}])})
describe("same value replacement - 1", () => { runPatchTest( {x: {y: 3}}, d => { const a = d.x d.x = a }, [] )})
describe("same value replacement - 2", () => { runPatchTest( {x: {y: 3}}, d => { const a = d.x d.x = 4 d.x = a }, // immer does not detect this is not an actual change [{op: "replace", path: ["x"], value: {y: 3}}] )})
describe("simple delete", () => { runPatchTest( {x: 2}, d => { delete d.x }, [ { op: "remove", path: ["x"] } ] )})modified:src/es5.js+50 added-5 removed
107 unmodified lines108 109 // this sounds very expensive, but actually it is not that expensive in practice110 // as it will only visit proxies, and only do key-based change detection for objects for111 // which it is not already know that they are changed (that is, only object for which no known key was changed)112-function markChanges() {112+function markChangesSweep() {113 // intentionally we process the proxies in reverse order;114 // ideally we start by processing leafs in the tree, because if a child has changed, we don't have to check the parent anymore115 // reverse order of proxy creation approximates this116 for (let i = states.length - 1; i >= 0; i--) {5 unmodified lines122 }123 }124 }125 126+function markChangesRecursively(object) {127+ if (!object || typeof object !== "object") return128+ const state = object[PROXY_STATE]129+ if (!state) return130+ const {proxy, base} = state131+ if (Array.isArray(object)) {132+ if (hasArrayChanges(state)) {133+ markChanged(state)134+ state.assigned.length = true135+ if (proxy.length < base.length)136+ for (let i = proxy.length; i < base.length; i++)137+ state.assigned[i] = false138+ else139+ for (let i = base.length; i < proxy.length; i++)140+ state.assigned[i] = true141+ each(proxy, (index, child) => {142+ if (!state.assigned[index]) markChangesRecursively(child)143+ })144+ }145+ } else {146+ const {added, removed} = diffKeys(base, proxy)147+ if (added.length > 0 || removed.length > 0) markChanged(state)148+ each(added, (_, key) => {149+ state.assigned[key] = true150+ })151+ each(removed, (_, key) => {152+ state.assigned[key] = false153+ })154+ each(proxy, (key, child) => {155+ if (!state.assigned[key]) markChangesRecursively(child)156+ })157+ }158+}159+160+function diffKeys(from, to) {161+ // TODO: optimize162+ const a = Object.keys(from)163+ const b = Object.keys(to)164+ return {165+ added: b.filter(key => a.indexOf(key) === -1),166+ removed: a.filter(key => b.indexOf(key) === -1)167+ }168+}169+170 function hasObjectChanges(state) {171 const baseKeys = Object.keys(state.base)172 const keys = Object.keys(state.proxy)173 return !shallowEqual(baseKeys, keys)34 unmodified lines208 // and finalize the modified proxy209 each(states, (_, state) => {210 state.finalizing = true211 })168- // find and mark all changes (for parts not done yet)169- // TODO: store states by depth, to be able guarantee processing leaves first170- markChanges()212 let result213 // check whether the draft was modified and/or a value was returned214 if (returnValue !== undefined && returnValue !== rootProxy) {215 // something was returned, and it wasn't the proxy itself3 unmodified lines219 if (patches) {220 patches.push({op: "replace", path: [], value: result})221 inversePatches.push({op: "replace", path: [], value: baseState})222 }223+ } else {224+ if (patchListener) markChangesRecursively(rootProxy)225+ else markChangesSweep() // this one is more efficient if we don't need to know which attributes have changed182- } else result = finalize(rootProxy, [], patches, inversePatches)226+ result = finalize(rootProxy, [], patches, inversePatches)227+ }228 // make sure all proxies become unusable229 each(states, (_, state) => {230 state.finished = true231 })39 unmodified linesmodified:src/patches.js+94 added-18 removed
7 unmodified lines8 baseValue,9 resultValue10 ) {11 if (patches)12- each(state.assigned, (key, added) => {13- const path = basepath.concat(key)14- patches.push(15- added16- ? {17- op: "replace",18- path,19- value: resultValue[key]20- }21- : {22- op: "remove",23- path24- }12+ if (Array.isArray(baseValue))13+ generateArrayPatches(14+ state,15+ basepath,16+ patches,17+ inversePatches,18+ baseValue,19+ resultValue20 )26- inversePatches.push(27- added && !key in baseValue28- ? {op: "remove", path}29- : {op: "replace", path, value: baseValue[key]}21+ else22+ generateObjectPatches(23+ state,24+ basepath,25+ patches,26+ inversePatches,27+ baseValue,28+ resultValue29 )30+}31+32+export function generateArrayPatches(33+ state,34+ basepath,35+ patches,36+ inversePatches,37+ baseValue,38+ resultValue39+) {40+ const shared = Math.min(baseValue.length, resultValue.length)41+ for (let i = 0; i < shared; i++) {42+ if (state.assigned[i] && baseValue[i] !== resultValue[i]) {43+ const path = basepath.concat(i)44+ patches.push({op: "replace", path, value: resultValue[i]})45+ inversePatches.push({op: "replace", path, value: baseValue[i]})46+ }47+ }48+ if (shared < resultValue.length) {49+ // stuff was added50+ for (let i = shared; i < resultValue.length; i++) {51+ const path = basepath.concat(i)52+ patches.push({op: "add", path, value: resultValue[i]})53+ }54+ inversePatches.push({55+ op: "replace",56+ path: basepath.concat("length"),57+ value: baseValue.length58 })59+ } else if (shared < baseValue.length) {60+ // stuff was removed61+ patches.push({62+ op: "replace",63+ path: basepath.concat("length"),64+ value: resultValue.length65+ })66+ for (let i = shared; i < baseValue.length; i++) {67+ const path = basepath.concat(i)68+ inversePatches.push({op: "add", path, value: baseValue[i]})69+ }70+ }71 }72 73+function generateObjectPatches(74+ state,75+ basepath,76+ patches,77+ inversePatches,78+ baseValue,79+ resultValue80+) {81+ each(state.assigned, (key, assignedValue) => {82+ const origValue = baseValue[key]83+ const value = resultValue[key]84+ const op = !assignedValue85+ ? "remove"86+ : key in baseValue ? "replace" : "add"87+ if (origValue === baseValue && op === "replace") return88+ const path = basepath.concat(key)89+ patches.push(op === "remove" ? {op, path} : {op, path, value})90+ inversePatches.push(91+ op === "add"92+ ? {op: "remove", path}93+ : op === "remove"94+ ? {op: "add", path, value: origValue}95+ : {op: "replace", path, value: origValue}96+ )97+ })98+}99+100 export function applyPatches(draft, patches) {101 for (let i = 0; i < patches.length; i++) {102 const patch = patches[i]103 if (patch.path.length === 0 && patch.op === "replace") {15 unmodified lines119 patch.path.join("/")120 )121 switch (patch.op) {122 case "replace":123+ case "add":124+ // TODO: add support is not extensive, it does not support insertion or `-` atm!125 base[key] = patch.value126 break127 case "remove":128+ if (Array.isArray(base)) {129+ if (key === base.length - 1) base.length -= 1130+ else131+ throw new Error(132+ `Remove can only remove the last key of an array, index: ${key}, length: ${133+ base.length134+ }`135+ )60- delete base[key]136+ } else delete base[key]137 break138 default:139 throw new Error("Unsupported patch operation: " + patch.op)140 }4 unmodified lines