Skip to content
Myr

Initial work on supporting patches

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 79bd6fb · Browse files · 5 files+151 added−15 removed
This commit

State

Before adoption: this commit came in with the history the project adopted, so no landing records it.

Diff stats

5 files+151 added−15 removed

  • tests:+86 added−0 removed
  • other:+65 added−15 removed

5 files+151 added−15 removed

added:__tests__/patch.js+86 added
1"use strict"2import produce, {setUseProxies} from "../src/immer"34jest.setTimeout(1000)56function runPatchTest(name, base, producer, patches) {7 function runPatchTest() {8 let recordedPatches9 let inversePatches10 const res = produce(base, producer, (p, i) => {11 recordedPatches = p12 inversePatches = i13 })1415 test("produces the correct patches", () => {16 expect(recordedPatches).toEqual(patches)17 })1819 test.skip("patches are replayable", () => {20 expect(applyPatches(base, recordedPatches)).toBe(res)21 })2223 test.skip("patches can be revered", () => {24 expect(applyPatches(res, inversePatches)).toBe(base)25 })26 }2728 describe(`patches - ${name} - proxy`, () => {29 setUseProxies(true)30 runPatchTest()31 })3233 describe.skip(`patches - ${name} - es5`, () => {34 setUseProxies(false)35 runPatchTest()36 })37}3839runPatchTest(40 "simple assignment",41 {x: 3},42 d => {43 d.x++44 },45 [{op: "replace", path: ["x"], value: 4}]46)4748runPatchTest(49 "simple assignment - 2",50 {x: {y: 4}},51 d => {52 d.x.y++53 },54 [{op: "replace", path: ["x", "y"], value: 5}]55)5657runPatchTest(58 "simple assignment - 2",59 {x: {y: 4}},60 d => {61 d.x.y++62 },63 [{op: "replace", path: ["x", "y"], value: 5}]64)6566runPatchTest(67 "delete 1",68 {x: {y: 4}},69 d => {70 delete d.x71 },72 [{op: "remove", path: ["x"]}]73)7475runPatchTest(76 "moving stuff",77 {x: {y: 4}},78 d => {79 d.z = d.x80 d.z.y++81 delete d.x82 },83 [{op: "replace", path: ["z"], value: {y: 5}}, {op: "remove", path: ["x"]}]84)8586// runPatchTest("simple replacement", { x: 3 }, _d => 4, [{ op: "replace", path: [], value: 4 }])
modified:src/common.js+37 added-5 removed
modified:src/immer.d.ts+12 added-1 removed
8 unmodified lines
9 T extends ReadonlyArray<any> ? DraftArray<T[number]> :10 T extends object ? DraftObject<T> :11 T;1213export interface Patch {14 op: "replace" | "remove",15 path: (string|number)[]16 value?: any17}1819export type PatchListener = (patches: Patch[], inversePatches: Patch[]) => void2021/**22 * Immer takes a state, and runs a function against it.23 * That function can freely mutate the state, as it will create copies-on-write.24 * This means that the original state will stay unchanged, and once the function finishes, the modified state is returned.25 *26 * If the first argument is a function, this is interpreted as the recipe, and will create a curried function that will execute the recipe27 * any time it is called with the current state.28 *29 * In it's base form immer can receive a patch handler30 *31 * @param currentState - the state to start with32 * @param recipe - function that receives a proxy of the current state as first argument and which can be freely modified33 * @param initialState - if a curried function is created and this argument was given, it will be used as fallback if the curried function is called with a state of undefined34 * @returns The next state: a new state, or the current state if nothing was modified35 */36export default function<S = any>(37 currentState: S,28 recipe: (this: Draft<S>, draftState: Draft<S>) => void | S38 recipe: (this: Draft<S>, draftState: Draft<S>) => void | S,39 patchListener?: PatchListener40): S4142// curried invocations with default initial state43// 0 additional arguments
63 unmodified lines
modified:src/immer.js+4 added-4 removed
12 unmodified lines
13 * @param {any} baseState - the state to start with14 * @param {Function} producer - function that receives a proxy of the base state as first argument and which can be freely modified15 * @returns {any} a new state, or the base state if nothing was modified16 */17export default function produce(baseState, producer) {17export default function produce(baseState, producer, patchListener) {18 // prettier-ignore19 if (arguments.length !== 1 && arguments.length !== 2) throw new Error("produce expects 1 or 2 arguments, got " + arguments.length)19 if (arguments.length < 1 && arguments.length > 3) throw new Error("produce expects 1 to 3 arguments, got " + arguments.length)2021 // curried invocation22 if (typeof baseState === "function") {23 // prettier-ignore
32 unmodified lines
56 throw new Error(57 `the first argument to an immer producer should be a primitive, plain object or array, got ${typeof baseState}: "${baseState}"`58 )59 return getUseProxies()60 ? produceProxy(baseState, producer)61 : produceEs5(baseState, producer)60 ? produceProxy(baseState, producer, patchListener)61 : produceEs5(baseState, producer, patchListener)62}
modified:src/proxy.js+12 added-5 removed
40 unmodified lines
41})4243function createState(parent, base) {44 return {45 modified: false,45 modified: false, // this tree is modified (either this object or one of it's children)46 assigned: {}, // true: value was assigned to these props, false: was removed // TODO: optimize if not recording47 finalized: false,48 parent,49 base,50 copy: undefined,
23 unmodified lines
74 }75}7677function set(state, prop, value) {78 // TODO: optimize79 state.assigned[prop] = true80 if (!state.modified) {81 if (82 (prop in state.base && is(state.base[prop], value)) ||83 (has(state.proxies, prop) && state.proxies[prop] === value)
5 unmodified lines
89 return true90}9192function deleteProperty(state, prop) {93 state.assigned[prop] = false94 markChanged(state)95 delete state.copy[prop]96 return true97}
24 unmodified lines
122 }123}124125// creates a proxy for plain objects / arrays122function createProxy(parentState, base) {126function createProxy(parentState, base, key) {127 if (isProxy(base)) throw new Error("Immer bug. Plz report.")124 const state = createState(parentState, base)128 const state = createState(parentState, base, key)129 const proxy = Array.isArray(base)130 ? Proxy.revocable([state], arrayTraps)131 : Proxy.revocable(state, objectTraps)132 proxies.push(proxy)133 return proxy.proxy134}135132export function produceProxy(baseState, producer) {136export function produceProxy(baseState, producer, patchListener) {137 if (isProxy(baseState)) {138 // See #100, don't nest producers139 const returnValue = producer.call(baseState, baseState)140 return returnValue === undefined ? baseState : returnValue141 }142 const previousProxies = proxies143 proxies = []144 const patches = [] // TODO: optimize, leave empty if no listener145 try {146 // create proxy for root147 const rootProxy = createProxy(undefined, baseState)148 // execute the thunk
9 unmodified lines
158 // See #117159 // Should we just throw when returning a proxy which is not the root, but a subset of the original state?160 // Looks like a wrongly modeled reducer161 result = finalize(returnValue)162 // TODO: emit patch163 } else {158 result = finalize(rootProxy)164 result = finalize(rootProxy, [], patches)165 }166 // revoke all proxies167 each(proxies, (_, p) => p.revoke())168 patchListener && patchListener(patches)169 return result170 } finally {171 proxies = previousProxies172 }
1 unmodified line