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
Provenance
- Commit
d821dda- Tree
ac40ce1- Author
Michel Weststrate <mweststrate@gmail.com>- Committer
Michel Weststrate <mweststrate@gmail.com>- Parent
79bd6fb
5 files changed+151 added−15 removed
added:__tests__/patch.js+86 added
1+"use strict"2+import produce, {setUseProxies} from "../src/immer"3+4+jest.setTimeout(1000)5+6+function 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+ })14+15+ test("produces the correct patches", () => {16+ expect(recordedPatches).toEqual(patches)17+ })18+19+ test.skip("patches are replayable", () => {20+ expect(applyPatches(base, recordedPatches)).toBe(res)21+ })22+23+ test.skip("patches can be revered", () => {24+ expect(applyPatches(res, inversePatches)).toBe(base)25+ })26+ }27+28+ describe(`patches - ${name} - proxy`, () => {29+ setUseProxies(true)30+ runPatchTest()31+ })32+33+ describe.skip(`patches - ${name} - es5`, () => {34+ setUseProxies(false)35+ runPatchTest()36+ })37+}38+39+runPatchTest(40+ "simple assignment",41+ {x: 3},42+ d => {43+ d.x++44+ },45+ [{op: "replace", path: ["x"], value: 4}]46+)47+48+runPatchTest(49+ "simple assignment - 2",50+ {x: {y: 4}},51+ d => {52+ d.x.y++53+ },54+ [{op: "replace", path: ["x", "y"], value: 5}]55+)56+57+runPatchTest(58+ "simple assignment - 2",59+ {x: {y: 4}},60+ d => {61+ d.x.y++62+ },63+ [{op: "replace", path: ["x", "y"], value: 5}]64+)65+66+runPatchTest(67+ "delete 1",68+ {x: {y: 4}},69+ d => {70+ delete d.x71+ },72+ [{op: "remove", path: ["x"]}]73+)74+75+runPatchTest(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+)85+86+// runPatchTest("simple replacement", { x: 3 }, _d => 4, [{ op: "replace", path: [], value: 4 }])modified:src/common.js+37 added-5 removed
82 unmodified lines838485868787888990919293939495959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612710512812913010813113213313413513613713813914014114214314432 unmodified lines82 unmodified lines return Object.prototype.hasOwnProperty.call(thing, prop)}
// given a base object, returns it if unmodified, or return the changed cloned if modifiedexport function finalize(base) {export function finalize(base, path, patches) { if (isProxy(base)) { const state = base[PROXY_STATE] if (state.modified === true) { if (state.finalized === true) return state.copy state.finalized = true return finalizeObject( const result = finalizeObject( useProxies ? state.copy : (state.copy = shallowCopy(base)), state state, path, patches ) generatePatches(state, path, patches, result) return result } else { return state.base } } finalizeNonProxiedObject(base) return base}
function generatePatches(state, path, patches, result) { if (patches) each(state.assigned, (key, value) => { patches.push( value ? { op: "replace", path: path.concat(key), value: result[key] } : { op: "remove", path: path.concat(key) } ) // TODO: also inverse patches })}
function finalizeObject(copy, state) {function finalizeObject(copy, state, path, patches) { const base = state.base each(copy, (prop, value) => { if (value !== base[prop]) copy[prop] = finalize(value) if (value !== base[prop]) { // if there was an assignment on this property, we don't need to generate // patches for the subtree const generatePatches = patches && !has(state.assigned, prop) copy[prop] = finalize( value, generatePatches && path.concat(prop), generatePatches && patches ) } }) return freeze(copy)}
32 unmodified linesmodified:src/immer.d.ts+12 added-1 removed
8 unmodified lines9 T extends ReadonlyArray<any> ? DraftArray<T[number]> :10 T extends object ? DraftObject<T> :11 T;12 13+export interface Patch {14+ op: "replace" | "remove",15+ path: (string|number)[]16+ value?: any17+}18+19+export type PatchListener = (patches: Patch[], inversePatches: Patch[]) => void20+21 /**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 */36 export 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 ): S41 42 // curried invocations with default initial state43 // 0 additional arguments63 unmodified linesmodified:src/immer.js+4 added-4 removed
12 unmodified lines13 * @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 */17-export default function produce(baseState, producer) {17+export 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)20 21 // curried invocation22 if (typeof baseState === "function") {23 // prettier-ignore32 unmodified lines56 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 lines41 })42 43 function 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 lines74 }75 }76 77 function 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 lines89 return true90 }91 92 function deleteProperty(state, prop) {93+ state.assigned[prop] = false94 markChanged(state)95 delete state.copy[prop]96 return true97 }24 unmodified lines122 }123 }124 125 // creates a proxy for plain objects / arrays122-function createProxy(parentState, base) {126+function 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 }135 132-export function produceProxy(baseState, producer) {136+export 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 thunk9 unmodified lines158 // 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