immerClass.ts
This file
Path
src/core/immerClass.ts
227 lines · 6.3 KiB · TypeScript
Last changed by
feature: Always freeze by default (#702)Michel Weststratebefore adoptiona406c8f
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–116why, 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 this.produce = this.produce.bind(this)46 this.produceWithPatches = this.produceWithPatches.bind(this)47 }4849 /**50 * The `produce` function takes a value and a "recipe function" (whose51 * return value often depends on the base state). The recipe function is52 * free to mutate its first argument however it wants. All mutations are53 * only ever applied to a __copy__ of the base state.54 *55 * Pass only a function to create a "curried producer" which relieves you56 * from passing the recipe function every time.57 *58 * Only plain objects and arrays are made mutable. All other objects are59 * considered uncopyable.60 *61 * Note: This function is __bound__ to its `Immer` instance.62 *63 * @param {any} base - the initial state64 * @param {Function} producer - function that receives a proxy of the base state as first argument and which can be freely modified65 * @param {Function} patchListener - optional function that will be called with all the patches produced here66 * @returns {any} a new state, or the initial state if nothing was modified67 */68 produce(base: any, recipe?: any, patchListener?: any) {69 // curried invocation70 if (typeof base === "function" && typeof recipe !== "function") {71 const defaultBase = recipe72 recipe = base7374 const self = this75 return function curriedProduce(76 this: any,77 base = defaultBase,78 ...args: any[]79 ) {80 return self.produce(base, (draft: Drafted) => recipe.call(this, draft, ...args)) // prettier-ignore81 }82 }8384 if (typeof recipe !== "function") die(6)85 if (patchListener !== undefined && typeof patchListener !== "function")86 die(7)8788 let result8990 // Only plain objects, arrays, and "immerable classes" are drafted.91 if (isDraftable(base)) {92 const scope = enterScope(this)93 const proxy = createProxy(this, base, undefined)94 let hasError = true95 try {96 result = recipe(proxy)97 hasError = false98 } finally {99 // finally instead of catch + rethrow better preserves original stack100 if (hasError) revokeScope(scope)101 else leaveScope(scope)102 }103 if (typeof Promise !== "undefined" && result instanceof Promise) {104 return result.then(105 result => {106 usePatchesInScope(scope, patchListener)107 return processResult(result, scope)108 },109 error => {110 revokeScope(scope)111 throw error112 }113 )114 }115 usePatchesInScope(scope, patchListener)116 return processResult(result, scope)Immer 7Michel Weststratebefore adoption467ea5d
line 117why, one step back117 } else if (!base || typeof base !== "object") {Merge pull request #536 from immerjs/multi-bundleMichel Weststratebefore adoption0d87fc8
lines 118–122why, one step back118 result = recipe(base)119 if (result === NOTHING) return undefined120 if (result === undefined) result = base121 if (this.autoFreeze_) freeze(result, true)122 return resultImmer 7Michel Weststratebefore adoption467ea5d
line 123why, one step back123 } else die(21, base)Merge pull request #536 from immerjs/multi-bundleMichel Weststratebefore adoption0d87fc8
lines 124–141why, one step back124 }125126 produceWithPatches(arg1: any, arg2?: any, arg3?: any): any {127 if (typeof arg1 === "function") {128 return (state: any, ...args: any[]) =>129 this.produceWithPatches(state, (draft: any) => arg1(draft, ...args))130 }131132 let patches: Patch[], inversePatches: Patch[]133 const nextState = this.produce(arg1, arg2, (p: Patch[], ip: Patch[]) => {134 patches = p135 inversePatches = ip136 })137 return [nextState, patches!, inversePatches!]138 }139140 createDraft<T extends Objectish>(base: T): Draft<T> {141 if (!isDraftable(base)) die(8)Immer 7Michel Weststratebefore adoption467ea5d
line 142why, one step back142 if (isDraft(base)) base = current(base)Merge pull request #536 from immerjs/multi-bundleMichel Weststratebefore adoption0d87fc8
lines 143–153why, one step back143 const scope = enterScope(this)144 const proxy = createProxy(this, base, undefined)145 proxy[DRAFT_STATE].isManual_ = true146 leaveScope(scope)147 return proxy as any148 }149150 finishDraft<D extends Draft<any>>(151 draft: D,152 patchListener?: PatchListener153 ): D extends Draft<infer T> ? T : never {Immer 7Michel Weststratebefore adoption467ea5d
line 154why, one step back154 const state: ImmerState = draft && (draft as any)[DRAFT_STATE]Merge pull request #536 from immerjs/multi-bundleMichel Weststratebefore adoption0d87fc8
lines 155–179why, one step back155 if (__DEV__) {156 if (!state || !state.isManual_) die(9)157 if (state.finalized_) die(10)158 }159 const {scope_: scope} = state160 usePatchesInScope(scope, patchListener)161 return processResult(undefined, scope)162 }163164 /**165 * Pass true to automatically freeze all copies created by Immer.166 *167 * By default, auto-freezing is disabled in production.168 */169 setAutoFreeze(value: boolean) {170 this.autoFreeze_ = value171 }172173 /**174 * Pass true to use the ES2015 `Proxy` class when creating drafts, which is175 * always faster than using ES5 proxies.176 *177 * By default, feature detection is used, so calling this is rarely necessary.178 */179 setUseProxies(value: boolean) {Immer 7Michel Weststratebefore adoption467ea5d
line 180why, one step back180 if (value && !hasProxies) {Merge pull request #536 from immerjs/multi-bundleMichel Weststratebefore adoption0d87fc8
lines 181–227why, one step back181 die(20)182 }183 this.useProxies_ = value184 }185186 applyPatches(base: Objectish, patches: Patch[]) {187 // If a patch replaces the entire state, take that replacement as base188 // before applying patches189 let i: number190 for (i = patches.length - 1; i >= 0; i--) {191 const patch = patches[i]192 if (patch.path.length === 0 && patch.op === "replace") {193 base = patch.value194 break195 }196 }197198 const applyPatchesImpl = getPlugin("Patches").applyPatches_199 if (isDraft(base)) {200 // N.B: never hits if some patch a replacement, patches are never drafts201 return applyPatchesImpl(base, patches)202 }203 // Otherwise, produce a copy of the base state.204 return this.produce(base, (draft: Drafted) =>205 applyPatchesImpl(draft, patches.slice(i + 1))206 )207 }208}209210export function createProxy<T extends Objectish>(211 immer: Immer,212 value: T,213 parent?: ImmerState214): Drafted<T, ImmerState> {215 // precondition: createProxy should be guarded by isDraftable, so we know we can safely draft216 const draft: Drafted = isMap(value)217 ? getPlugin("MapSet").proxyMap_(value, parent)218 : isSet(value)219 ? getPlugin("MapSet").proxySet_(value, parent)220 : immer.useProxies_221 ? createProxyProxy(value, parent)222 : getPlugin("ES5").createES5Proxy_(value, parent)223224 const scope = parent ? parent.scope_ : getCurrentScope()225 scope.drafts_.push(draft)226 return draft227}