Basic implementation for `current`
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 0321d34 · Browse files · 8 files·+110 added−59 removed
This commit
State
Before adoption: this commit came in with the history the project adopted, so no landing records it.
Diff stats
8 files+110 added−59 removed
- tests:+22 added−17 removed
- other:+88 added−42 removed
Provenance
- Commit
7322e82- Tree
23fb270- Author
Michel Weststrate <mweststrate@fb.com>- Committer
Michel Weststrate <mweststrate@fb.com>- Parent
0321d34
8 files changed+110 added−59 removed
modified:__tests__/current.js+22 added-17 removed
1123456678910111213141512161718192021222324212223242526272526272829303132333435363738394064 unmodified lines1051061071081071091101111121131145 unmodified lines1201211221231211241251261271281291301311321331341351311361371381341391401411421436 unmodified lines15015115215314915415515615715815916016116216315916416516616716813 unmodified lines18218318418518118618718818919011 unmodified linesimport produce, {import { setUseProxies, setAutoFreeze, enableAllPlugins, current, immerable immerable, isDraft, produce, original} from "../src/immer"
enableAllPlugins()
runTests("proxy", true)// TODO: enablerunTests("es5", false)// runTests("es5", false)
function runTests(name, useProxies) { describe("current - " + name, () => { beforeAll(() => { setAutoFreeze(true) setUseProxies(useProxies) })
it("returns undraftable values", () => { ;[null, undefined, 1, true, "test"].forEach(value => { // TODO: or throw? produce(value, draft => { expect(current(draft)).toBe(value) }) }) it("must be called on draft", () => { expect(() => { current({}) }).toThrowError("[Immer] 'current' expects a draft, got: [object Object]") })
it("can handle simple objects", () => { const base = {x: 1} let c const next = produce(base, draft => { draft.x++ debugger c = current(draft) draft.x++ }) expect(next).toEqual({x: 3})64 unmodified lines const base = { x: 1, y: { z: 2 } }, z: {} } produce(base, draft => { draft.y.z++ draft.y = {5 unmodified lines y: { nested: { z: 3 } } }, z: {} }) expect(isDraft(c.y.nested)).toBe(false) expect(c.z).toBe(base.z) expect(c.y.nested).not.toBe(draft.y.nested) }) })
it("handles map - 1", () => { const base = new Map([["a", {x: 1}]]) produce(base, draft => { expect(current(draft)).toBe(draft) expect(current(draft)).toBe(base) draft.delete("a") let c = current(draft) expect(current(draft)).not.toBe(draft) expect(current(draft)).not.toBe(base) expect(c).toEqual(new Map()) const obj = {} draft.set("b", obj) expect(c).toEqual(new Map())6 unmodified lines const base = new Map([["a", {x: 1}]]) produce(base, draft => { draft.get("a").x++ const c = current(draft) expect(c).not.toBe(draft) expect(c).not.toBe(base) expect(c).toEqual(new Map([["a", {x: 2}]])) draft.get("a").x++ expect(c).toEqual(new Map([["a", {x: 2}]])) }) })
it("handles set", () => { const base = new Set([1]) produce(base, draft => { expect(current(draft)).toBe(draft) expect(current(draft)).toBe(base) base.add(2) const c = current(draft) expect(c).toEqual(new Set([1, 2])) expect(c).not.toBe(draft)13 unmodified lines }
const c = new Counter() produce(c, draft => { expect(current(draft)).toBe(draft) expect(current(draft)).toBe(c) draft.inc() const c = current(draft) expect(c).not.toBe(draft) expect(c.current).toBe(1)11 unmodified linesadded:src/core/current.ts+38 added
1+import {2+ die,3+ isDraft,4+ shallowCopy,5+ each,6+ DRAFT_STATE,7+ get,8+ set,9+ ImmerState,10+ isDraftable11+} from "../internal"12+13+export function current<T>(value: T): T14+export function current(value: any): any {15+ if (!isDraft(value)) die(22, value)16+ return currentImpl(value)17+}18+19+function currentImpl(value: any): any {20+ if (!isDraftable(value)) return value21+ const state: ImmerState | undefined = value[DRAFT_STATE]22+ let copy: any23+ if (state) {24+ if (!state.modified_) return state.base_25+ // Optimization: avoid generating new drafts during copying26+ state.finalized_ = true27+ copy = shallowCopy(value)28+ state.finalized_ = false29+ } else {30+ copy = shallowCopy(value)31+ }32+33+ each(copy, (key, childValue) => {34+ if (state && get(state.base_, key) === childValue) return // no need to copy a current of something that didn't change35+ set(copy, key, currentImpl(childValue))36+ })37+ return copy38+}modified:src/core/finalize.ts+1 added-1 removed
131 unmodified lines132 rootScope.canAutoFreeze_ = false133 } else return134 }135 // Search new objects for unfinalized drafts. Frozen objects should never contain drafts.136- if (isDraftable(childValue) && !Object.isFrozen(childValue)) {136+ if (isDraftable(childValue)) {137 if (!rootScope.immer_.autoFreeze_ && rootScope.unfinalizedDrafts_ < 1) {138 // optimization: if an object is not a draft, and we don't have to139 // deepfreeze everything, and we are sure that no drafts are left in the remaining object140 // cause we saw and finalized all drafts already; we can stop visiting the rest of the tree.16 unmodified linesmodified:src/types/index.js.flow+36 added-34 removed
1 // @flow2 3 export interface Patch {4- op: "replace" | "remove" | "add",5- path: (string|number)[],6- value?: any4+ op: "replace" | "remove" | "add";5+ path: (string | number)[];6+ value?: any;7 }8 9 export type PatchListener = (patches: Patch[], inversePatches: Patch[]) => void10 11-type Base = {...} | Array<any> | Map<any> | Set<any>;11+type Base = {...} | Array<any> | Map<any> | Set<any>12 interface IProduce {13- /**14- * Immer takes a state, and runs a function against it.15- * That function can freely mutate the state, as it will create copies-on-write.16- * This means that the original state will stay unchanged, and once the function finishes, the modified state is returned.17- *18- * If the first argument is a function, this is interpreted as the recipe, and will create a curried function that will execute the recipe19- * any time it is called with the current state.20- *21- * @param currentState - the state to start with22- * @param recipe - function that receives a proxy of the current state as first argument and which can be freely modified23- * @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 undefined24- * @returns The next state: a new state, or the current state if nothing was modified25- */26- <S: Base>(27- currentState: S,28- recipe: (draftState: S) => S | void,29- patchListener?: PatchListener30- ): S;31- // curried invocations with inital state32- <S: Base, A = void, B = void, C = void>(33- recipe: (draftState: S, a: A, b: B, c: C, ...extraArgs: any[]) => S | void,34- initialState: S35- ): (currentState: S | void, a: A, b: B, c: C, ...extraArgs: any[]) => S;36- // curried invocations without inital state37- <S: Base, A = void, B = void, C = void>(38- recipe: (draftState: S, a: A, b: B, c: C, ...extraArgs: any[]) => S | void39- ): (currentState: S, a: A, b: B, c: C, ...extraArgs: any[]) => S;13+ /**14+ * Immer takes a state, and runs a function against it.15+ * That function can freely mutate the state, as it will create copies-on-write.16+ * This means that the original state will stay unchanged, and once the function finishes, the modified state is returned.17+ *18+ * If the first argument is a function, this is interpreted as the recipe, and will create a curried function that will execute the recipe19+ * any time it is called with the current state.20+ *21+ * @param currentState - the state to start with22+ * @param recipe - function that receives a proxy of the current state as first argument and which can be freely modified23+ * @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 undefined24+ * @returns The next state: a new state, or the current state if nothing was modified25+ */26+ <S: Base>(27+ currentState: S,28+ recipe: (draftState: S) => S | void,29+ patchListener?: PatchListener30+ ): S;31+ // curried invocations with inital state32+ <S: Base, A = void, B = void, C = void>(33+ recipe: (draftState: S, a: A, b: B, c: C, ...extraArgs: any[]) => S | void,34+ initialState: S35+ ): (currentState: S | void, a: A, b: B, c: C, ...extraArgs: any[]) => S;36+ // curried invocations without inital state37+ <S: Base, A = void, B = void, C = void>(38+ recipe: (draftState: S, a: A, b: B, c: C, ...extraArgs: any[]) => S | void39+ ): (currentState: S, a: A, b: B, c: C, ...extraArgs: any[]) => S;40 }41 42 declare export var produce: IProduce43 declare export default IProduce17 unmodified lines61 declare export function setUseProxies(useProxies: boolean): void62 63 declare export function applyPatches<S>(state: S, patches: Patch[]): S64 65-declare export function original<S>(value: S): ?S65+declare export function original<S>(value: S): S66 67+declare export function current<S>(value: S): S68+69 declare export function isDraft(value: any): boolean70 71 /**70- * Creates a mutable draft from an (immutable) object / array. 72+ * Creates a mutable draft from an (immutable) object / array.73 * The draft can be modified until `finishDraft` is called74 */75 declare export function createDraft<T>(base: T): T76 77 /**76- * Given a draft that was created using `createDraft`, 78+ * Given a draft that was created using `createDraft`,79 * finalizes the draft into a new immutable object.80 * Optionally a patch-listener can be provided to gather the patches that are needed to construct the object.81 */82 declare export function finishDraft<T>(base: T, listener?: PatchListener): T5 unmodified linesmodified:src/utils/common.ts+8 added-7 removed
25 unmodified lines26 /*#__PURE__*/27 export function isDraftable(value: any): boolean {28 if (!value) return false29 return (30- isPlainObject(value) ||31- Array.isArray(value) ||32- !!value[DRAFTABLE] ||33- !!value.constructor[DRAFTABLE] ||34- isMap(value) ||35- isSet(value)30+ (isPlainObject(value) ||31+ Array.isArray(value) ||32+ !!value[DRAFTABLE] ||33+ !!value.constructor[DRAFTABLE] ||34+ isMap(value) ||35+ isSet(value)) &&36+ !isFrozen(value)37 )38 }39 40 /*#__PURE__*/130 unmodified lines171 return Object.create(Object.getPrototypeOf(base), descriptors)172 }173 174 export function freeze(obj: any, deep: boolean): void {174- if (isDraft(obj) || isFrozen(obj) || !isDraftable(obj)) return175+ if (isDraft(obj) || !isDraftable(obj)) return176 if (getArchtype(obj) > 1 /* Map or Set */) {177 obj.set = obj.add = obj.clear = obj.delete = dontMutateFrozenCollections as any178 }179 Object.freeze(obj)12 unmodified linesmodified:src/utils/errors.ts+3 added
31 unmodified lines32 19: "plugin not loaded",33 20: "Cannot use proxies if Proxy, Proxy.revocable or Reflect are not available",34 21(thing: string) {35 return `produce can only be called on things that are draftable: plain objects, arrays, Map, Set or classes that are marked with '[immerable]: true'. Got '${thing}'`36+ },37+ 22(thing: string) {38+ return `'current' expects a draft, got: ${thing}`39 }40 } as const41 42 export function die(error: keyof typeof errors, ...args: any[]): never {15 unmodified linesmodified:src/immer.ts+1 added
10 unmodified lines11 Immutable,12 Patch,13 PatchListener,14 original,15+ current,16 isDraft,17 isDraftable,18 NOTHING as nothing,19 DRAFTABLE as immerable97 unmodified linesmodified:src/internal.ts+1 added
6 unmodified lines7 export * from "./core/scope"8 export * from "./core/finalize"9 export * from "./core/proxy"10 export * from "./core/immerClass"11+export * from "./core/current"