immerClass.ts
This file
Path
src/core/immerClass.ts
229 lines · 6.3 KiB · TypeScript
Last changed by
fix: #768 `immerable` field being lost during patch value cloning (#771)Michel Weststratebefore adoptione0b7c01
History of this fileTake it
Merge pull request #536 from immerjs/multi-bundleMichel Weststratebefore adoption0d87fc8
lines 1–23why, one step back1import {2 IProduceWithPatches,3 IProduce,4 ImmerState,5 Drafted,6 isDraftable,7 processResult,8 Patch,9 Objectish,10 DRAFT_STATE,11 Draft,12 PatchListener,13 isDraft,14 isMap,15 isSet,16 createProxyProxy,17 getPlugin,18 die,19 hasProxies,20 enterScope,21 revokeScope,22 leaveScope,23 usePatchesInScope,Immer 7Michel Weststratebefore adoption467ea5d
lines 24–27why, one step back24 getCurrentScope,25 NOTHING,26 freeze,27 currentMerge pull request #536 from immerjs/multi-bundleMichel Weststratebefore adoption0d87fc8
lines 28–37why, one step back28} from "../internal"2930interface ProducersFns {31 produce: IProduce32 produceWithPatches: IProduceWithPatches33}3435export class Immer implements ProducersFns {36 useProxies_: boolean = hasProxies37feature: Always freeze by default (#702)Michel Weststratebefore adoptiona406c8f
line 38why, one step back38 autoFreeze_: boolean = trueMerge pull request #536 from immerjs/multi-bundleMichel Weststratebefore adoption0d87fc8
lines 39–65why, one step back3940 constructor(config?: {useProxies?: boolean; autoFreeze?: boolean}) {41 if (typeof config?.useProxies === "boolean")42 this.setUseProxies(config!.useProxies)43 if (typeof config?.autoFreeze === "boolean")44 this.setAutoFreeze(config!.autoFreeze)45 }4647 /**48 * The `produce` function takes a value and a "recipe function" (whose49 * return value often depends on the base state). The recipe function is50 * free to mutate its first argument however it wants. All mutations are51 * only ever applied to a __copy__ of the base state.52 *53 * Pass only a function to create a "curried producer" which relieves you54 * from passing the recipe function every time.55 *56 * Only plain objects and arrays are made mutable. All other objects are57 * considered uncopyable.58 *59 * Note: This function is __bound__ to its `Immer` instance.60 *61 * @param {any} base - the initial state62 * @param {Function} producer - function that receives a proxy of the base state as first argument and which can be freely modified63 * @param {Function} patchListener - optional function that will be called with all the patches produced here64 * @returns {any} a new state, or the initial state if nothing was modified65 */fix: new Immer().produce now has the same type as produce. Fixes #749Michel Weststratebefore adoptionf8b77d1
line 66why, one step back66 produce: IProduce = (base: any, recipe?: any, patchListener?: any) => {Merge pull request #536 from immerjs/multi-bundleMichel Weststratebefore adoption0d87fc8
lines 67–114why, one step back67 // curried invocation68 if (typeof base === "function" && typeof recipe !== "function") {69 const defaultBase = recipe70 recipe = base7172 const self = this73 return function curriedProduce(74 this: any,75 base = defaultBase,76 ...args: any[]77 ) {78 return self.produce(base, (draft: Drafted) => recipe.call(this, draft, ...args)) // prettier-ignore79 }80 }8182 if (typeof recipe !== "function") die(6)83 if (patchListener !== undefined && typeof patchListener !== "function")84 die(7)8586 let result8788 // Only plain objects, arrays, and "immerable classes" are drafted.89 if (isDraftable(base)) {90 const scope = enterScope(this)91 const proxy = createProxy(this, base, undefined)92 let hasError = true93 try {94 result = recipe(proxy)95 hasError = false96 } finally {97 // finally instead of catch + rethrow better preserves original stack98 if (hasError) revokeScope(scope)99 else leaveScope(scope)100 }101 if (typeof Promise !== "undefined" && result instanceof Promise) {102 return result.then(103 result => {104 usePatchesInScope(scope, patchListener)105 return processResult(result, scope)106 },107 error => {108 revokeScope(scope)109 throw error110 }111 )112 }113 usePatchesInScope(scope, patchListener)114 return processResult(result, scope)Immer 7Michel Weststratebefore adoption467ea5d
line 115why, one step back115 } else if (!base || typeof base !== "object") {Merge pull request #536 from immerjs/multi-bundleMichel Weststratebefore adoption0d87fc8
lines 116–120why, one step back116 result = recipe(base)117 if (result === NOTHING) return undefined118 if (result === undefined) result = base119 if (this.autoFreeze_) freeze(result, true)120 return resultImmer 7Michel Weststratebefore adoption467ea5d
line 121why, one step back121 } else die(21, base)Merge pull request #536 from immerjs/multi-bundleMichel Weststratebefore adoption0d87fc8
lines 122–123why, one step back122 }123fix: new Immer().produce now has the same type as produce. Fixes #749Michel Weststratebefore adoptionf8b77d1
lines 124–128why, one step back124 produceWithPatches: IProduceWithPatches = (125 arg1: any,126 arg2?: any,127 arg3?: any128 ): any => {Merge pull request #536 from immerjs/multi-bundleMichel Weststratebefore adoption0d87fc8
lines 129–143why, one step back129 if (typeof arg1 === "function") {130 return (state: any, ...args: any[]) =>131 this.produceWithPatches(state, (draft: any) => arg1(draft, ...args))132 }133134 let patches: Patch[], inversePatches: Patch[]135 const nextState = this.produce(arg1, arg2, (p: Patch[], ip: Patch[]) => {136 patches = p137 inversePatches = ip138 })139 return [nextState, patches!, inversePatches!]140 }141142 createDraft<T extends Objectish>(base: T): Draft<T> {143 if (!isDraftable(base)) die(8)Immer 7Michel Weststratebefore adoption467ea5d
line 144why, one step back144 if (isDraft(base)) base = current(base)Merge pull request #536 from immerjs/multi-bundleMichel Weststratebefore adoption0d87fc8
lines 145–155why, one step back145 const scope = enterScope(this)146 const proxy = createProxy(this, base, undefined)147 proxy[DRAFT_STATE].isManual_ = true148 leaveScope(scope)149 return proxy as any150 }151152 finishDraft<D extends Draft<any>>(153 draft: D,154 patchListener?: PatchListener155 ): D extends Draft<infer T> ? T : never {Immer 7Michel Weststratebefore adoption467ea5d
line 156why, one step back156 const state: ImmerState = draft && (draft as any)[DRAFT_STATE]Merge pull request #536 from immerjs/multi-bundleMichel Weststratebefore adoption0d87fc8
lines 157–168why, one step back157 if (__DEV__) {158 if (!state || !state.isManual_) die(9)159 if (state.finalized_) die(10)160 }161 const {scope_: scope} = state162 usePatchesInScope(scope, patchListener)163 return processResult(undefined, scope)164 }165166 /**167 * Pass true to automatically freeze all copies created by Immer.168 *docs: some refinements on freezingMichel Weststratebefore adoption7faa7b4
line 169why, one step back169 * By default, auto-freezing is enabled.Merge pull request #536 from immerjs/multi-bundleMichel Weststratebefore adoption0d87fc8
lines 170–181why, one step back170 */171 setAutoFreeze(value: boolean) {172 this.autoFreeze_ = value173 }174175 /**176 * Pass true to use the ES2015 `Proxy` class when creating drafts, which is177 * always faster than using ES5 proxies.178 *179 * By default, feature detection is used, so calling this is rarely necessary.180 */181 setUseProxies(value: boolean) {Immer 7Michel Weststratebefore adoption467ea5d
line 182why, one step back182 if (value && !hasProxies) {Merge pull request #536 from immerjs/multi-bundleMichel Weststratebefore adoption0d87fc8
lines 183–187why, one step back183 die(20)184 }185 this.useProxies_ = value186 }187fix: #768 `immerable` field being lost during patch value cloning (#771)Michel Weststratebefore adoptione0b7c01
line 188why, one step back188 applyPatches<T extends Objectish>(base: Objectish, patches: Patch[]): T {Merge pull request #536 from immerjs/multi-bundleMichel Weststratebefore adoption0d87fc8
lines 189–202why, one step back189 // If a patch replaces the entire state, take that replacement as base190 // before applying patches191 let i: number192 for (i = patches.length - 1; i >= 0; i--) {193 const patch = patches[i]194 if (patch.path.length === 0 && patch.op === "replace") {195 base = patch.value196 break197 }198 }199200 const applyPatchesImpl = getPlugin("Patches").applyPatches_201 if (isDraft(base)) {202 // N.B: never hits if some patch a replacement, patches are never draftsfix: #768 `immerable` field being lost during patch value cloning (#771)Michel Weststratebefore adoptione0b7c01
line 203why, one step back203 return applyPatchesImpl(base, patches) as anyMerge pull request #536 from immerjs/multi-bundleMichel Weststratebefore adoption0d87fc8
lines 204–207why, one step back204 }205 // Otherwise, produce a copy of the base state.206 return this.produce(base, (draft: Drafted) =>207 applyPatchesImpl(draft, patches.slice(i + 1))fix: #768 `immerable` field being lost during patch value cloning (#771)Michel Weststratebefore adoptione0b7c01
line 208why, one step back208 ) as anyMerge pull request #536 from immerjs/multi-bundleMichel Weststratebefore adoption0d87fc8
lines 209–229why, one step back209 }210}211212export function createProxy<T extends Objectish>(213 immer: Immer,214 value: T,215 parent?: ImmerState216): Drafted<T, ImmerState> {217 // precondition: createProxy should be guarded by isDraftable, so we know we can safely draft218 const draft: Drafted = isMap(value)219 ? getPlugin("MapSet").proxyMap_(value, parent)220 : isSet(value)221 ? getPlugin("MapSet").proxySet_(value, parent)222 : immer.useProxies_223 ? createProxyProxy(value, parent)224 : getPlugin("ES5").createES5Proxy_(value, parent)225226 const scope = parent ? parent.scope_ : getCurrentScope()227 scope.drafts_.push(draft)228 return draft229}