immerClass.ts
This file
Path
src/core/immerClass.ts
226 lines · 6.3 KiB · TypeScript
Last changed by
Some cleanupMichel Weststratebefore adoptionb3b43b9
History of this fileTake it
Merge pull request #536 from immerjs/multi-bundleMichel Weststratebefore adoption0d87fc8
lines 1–24why, 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 isMinified,21 enterScope,22 revokeScope,23 leaveScope,24 usePatchesInScope,Restore: allow produce to be called with primitivesMichel Weststratebefore adoptione7983c4
lines 25–27why, one step back25 getCurrentScope,26 NOTHING,27 freezeMerge pull request #536 from immerjs/multi-bundleMichel Weststratebefore adoption0d87fc8
lines 28–116why, one step back28} from "../internal"2930interface ProducersFns {31 produce: IProduce32 produceWithPatches: IProduceWithPatches33}3435export class Immer implements ProducersFns {36 useProxies_: boolean = hasProxies3738 autoFreeze_: boolean = __DEV__ ? true /* istanbul ignore next */ : !isMinified3940 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)Restore: allow produce to be called with primitivesMichel Weststratebefore adoptione7983c4
lines 117–123why, one step back117 } else if (!base || typeof base !== "object") {118 result = recipe(base)119 if (result === NOTHING) return undefined120 if (result === undefined) result = base121 if (this.autoFreeze_) freeze(result, true)122 return result123 } else die(21, base)Merge pull request #536 from immerjs/multi-bundleMichel Weststratebefore adoption0d87fc8
lines 124–152why, 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)142 const scope = enterScope(this)143 const proxy = createProxy(this, base, undefined)144 proxy[DRAFT_STATE].isManual_ = true145 leaveScope(scope)146 return proxy as any147 }148149 finishDraft<D extends Draft<any>>(150 draft: D,151 patchListener?: PatchListener152 ): D extends Draft<infer T> ? T : never {fix: produce no longer accepts non draftable objects, fixes #596Michel Weststratebefore adoptiond9bf68b
line 153why, one step back153 const state: ImmerState = draft && (draft as any)[DRAFT_STATE]Merge pull request #536 from immerjs/multi-bundleMichel Weststratebefore adoption0d87fc8
lines 154–178why, one step back154 if (__DEV__) {155 if (!state || !state.isManual_) die(9)156 if (state.finalized_) die(10)157 }158 const {scope_: scope} = state159 usePatchesInScope(scope, patchListener)160 return processResult(undefined, scope)161 }162163 /**164 * Pass true to automatically freeze all copies created by Immer.165 *166 * By default, auto-freezing is disabled in production.167 */168 setAutoFreeze(value: boolean) {169 this.autoFreeze_ = value170 }171172 /**173 * Pass true to use the ES2015 `Proxy` class when creating drafts, which is174 * always faster than using ES5 proxies.175 *176 * By default, feature detection is used, so calling this is rarely necessary.177 */178 setUseProxies(value: boolean) {Some cleanupMichel Weststratebefore adoptionb3b43b9
line 179why, one step back179 if (value && !hasProxies) {Merge pull request #536 from immerjs/multi-bundleMichel Weststratebefore adoption0d87fc8
lines 180–226why, one step back180 die(20)181 }182 this.useProxies_ = value183 }184185 applyPatches(base: Objectish, patches: Patch[]) {186 // If a patch replaces the entire state, take that replacement as base187 // before applying patches188 let i: number189 for (i = patches.length - 1; i >= 0; i--) {190 const patch = patches[i]191 if (patch.path.length === 0 && patch.op === "replace") {192 base = patch.value193 break194 }195 }196197 const applyPatchesImpl = getPlugin("Patches").applyPatches_198 if (isDraft(base)) {199 // N.B: never hits if some patch a replacement, patches are never drafts200 return applyPatchesImpl(base, patches)201 }202 // Otherwise, produce a copy of the base state.203 return this.produce(base, (draft: Drafted) =>204 applyPatchesImpl(draft, patches.slice(i + 1))205 )206 }207}208209export function createProxy<T extends Objectish>(210 immer: Immer,211 value: T,212 parent?: ImmerState213): Drafted<T, ImmerState> {214 // precondition: createProxy should be guarded by isDraftable, so we know we can safely draft215 const draft: Drafted = isMap(value)216 ? getPlugin("MapSet").proxyMap_(value, parent)217 : isSet(value)218 ? getPlugin("MapSet").proxySet_(value, parent)219 : immer.useProxies_220 ? createProxyProxy(value, parent)221 : getPlugin("ES5").createES5Proxy_(value, parent)222223 const scope = parent ? parent.scope_ : getCurrentScope()224 scope.drafts_.push(draft)225 return draft226}