immerClass.ts
This file
Path
src/core/immerClass.ts
228 lines · 6.3 KiB · TypeScript
Last changed by
createDraft can now handle draftsMichel Weststratebefore adoption7682990
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–26why, one step back25 getCurrentScope,26 NOTHING,createDraft can now handle draftsMichel Weststratebefore adoption7682990
lines 27–28why, one step back27 freeze,28 currentMerge pull request #536 from immerjs/multi-bundleMichel Weststratebefore adoption0d87fc8
lines 29–117why, one step back29} from "../internal"3031interface ProducersFns {32 produce: IProduce33 produceWithPatches: IProduceWithPatches34}3536export class Immer implements ProducersFns {37 useProxies_: boolean = hasProxies3839 autoFreeze_: boolean = __DEV__ ? true /* istanbul ignore next */ : !isMinified4041 constructor(config?: {useProxies?: boolean; autoFreeze?: boolean}) {42 if (typeof config?.useProxies === "boolean")43 this.setUseProxies(config!.useProxies)44 if (typeof config?.autoFreeze === "boolean")45 this.setAutoFreeze(config!.autoFreeze)46 this.produce = this.produce.bind(this)47 this.produceWithPatches = this.produceWithPatches.bind(this)48 }4950 /**51 * The `produce` function takes a value and a "recipe function" (whose52 * return value often depends on the base state). The recipe function is53 * free to mutate its first argument however it wants. All mutations are54 * only ever applied to a __copy__ of the base state.55 *56 * Pass only a function to create a "curried producer" which relieves you57 * from passing the recipe function every time.58 *59 * Only plain objects and arrays are made mutable. All other objects are60 * considered uncopyable.61 *62 * Note: This function is __bound__ to its `Immer` instance.63 *64 * @param {any} base - the initial state65 * @param {Function} producer - function that receives a proxy of the base state as first argument and which can be freely modified66 * @param {Function} patchListener - optional function that will be called with all the patches produced here67 * @returns {any} a new state, or the initial state if nothing was modified68 */69 produce(base: any, recipe?: any, patchListener?: any) {70 // curried invocation71 if (typeof base === "function" && typeof recipe !== "function") {72 const defaultBase = recipe73 recipe = base7475 const self = this76 return function curriedProduce(77 this: any,78 base = defaultBase,79 ...args: any[]80 ) {81 return self.produce(base, (draft: Drafted) => recipe.call(this, draft, ...args)) // prettier-ignore82 }83 }8485 if (typeof recipe !== "function") die(6)86 if (patchListener !== undefined && typeof patchListener !== "function")87 die(7)8889 let result9091 // Only plain objects, arrays, and "immerable classes" are drafted.92 if (isDraftable(base)) {93 const scope = enterScope(this)94 const proxy = createProxy(this, base, undefined)95 let hasError = true96 try {97 result = recipe(proxy)98 hasError = false99 } finally {100 // finally instead of catch + rethrow better preserves original stack101 if (hasError) revokeScope(scope)102 else leaveScope(scope)103 }104 if (typeof Promise !== "undefined" && result instanceof Promise) {105 return result.then(106 result => {107 usePatchesInScope(scope, patchListener)108 return processResult(result, scope)109 },110 error => {111 revokeScope(scope)112 throw error113 }114 )115 }116 usePatchesInScope(scope, patchListener)117 return processResult(result, scope)Restore: allow produce to be called with primitivesMichel Weststratebefore adoptione7983c4
lines 118–124why, one step back118 } else if (!base || typeof base !== "object") {119 result = recipe(base)120 if (result === NOTHING) return undefined121 if (result === undefined) result = base122 if (this.autoFreeze_) freeze(result, true)123 return result124 } else die(21, base)Merge pull request #536 from immerjs/multi-bundleMichel Weststratebefore adoption0d87fc8
lines 125–142why, one step back125 }126127 produceWithPatches(arg1: any, arg2?: any, arg3?: any): any {128 if (typeof arg1 === "function") {129 return (state: any, ...args: any[]) =>130 this.produceWithPatches(state, (draft: any) => arg1(draft, ...args))131 }132133 let patches: Patch[], inversePatches: Patch[]134 const nextState = this.produce(arg1, arg2, (p: Patch[], ip: Patch[]) => {135 patches = p136 inversePatches = ip137 })138 return [nextState, patches!, inversePatches!]139 }140141 createDraft<T extends Objectish>(base: T): Draft<T> {142 if (!isDraftable(base)) die(8)createDraft can now handle draftsMichel Weststratebefore adoption7682990
line 143why, one step back143 if (isDraft(base)) base = current(base)Merge pull request #536 from immerjs/multi-bundleMichel Weststratebefore adoption0d87fc8
lines 144–154why, one step back144 const scope = enterScope(this)145 const proxy = createProxy(this, base, undefined)146 proxy[DRAFT_STATE].isManual_ = true147 leaveScope(scope)148 return proxy as any149 }150151 finishDraft<D extends Draft<any>>(152 draft: D,153 patchListener?: PatchListener154 ): D extends Draft<infer T> ? T : never {fix: produce no longer accepts non draftable objects, fixes #596Michel Weststratebefore adoptiond9bf68b
line 155why, one step back155 const state: ImmerState = draft && (draft as any)[DRAFT_STATE]Merge pull request #536 from immerjs/multi-bundleMichel Weststratebefore adoption0d87fc8
lines 156–180why, one step back156 if (__DEV__) {157 if (!state || !state.isManual_) die(9)158 if (state.finalized_) die(10)159 }160 const {scope_: scope} = state161 usePatchesInScope(scope, patchListener)162 return processResult(undefined, scope)163 }164165 /**166 * Pass true to automatically freeze all copies created by Immer.167 *168 * By default, auto-freezing is disabled in production.169 */170 setAutoFreeze(value: boolean) {171 this.autoFreeze_ = value172 }173174 /**175 * Pass true to use the ES2015 `Proxy` class when creating drafts, which is176 * always faster than using ES5 proxies.177 *178 * By default, feature detection is used, so calling this is rarely necessary.179 */180 setUseProxies(value: boolean) {Some cleanupMichel Weststratebefore adoptionb3b43b9
line 181why, one step back181 if (value && !hasProxies) {Merge pull request #536 from immerjs/multi-bundleMichel Weststratebefore adoption0d87fc8
lines 182–228why, one step back182 die(20)183 }184 this.useProxies_ = value185 }186187 applyPatches(base: Objectish, patches: Patch[]) {188 // If a patch replaces the entire state, take that replacement as base189 // before applying patches190 let i: number191 for (i = patches.length - 1; i >= 0; i--) {192 const patch = patches[i]193 if (patch.path.length === 0 && patch.op === "replace") {194 base = patch.value195 break196 }197 }198199 const applyPatchesImpl = getPlugin("Patches").applyPatches_200 if (isDraft(base)) {201 // N.B: never hits if some patch a replacement, patches are never drafts202 return applyPatchesImpl(base, patches)203 }204 // Otherwise, produce a copy of the base state.205 return this.produce(base, (draft: Drafted) =>206 applyPatchesImpl(draft, patches.slice(i + 1))207 )208 }209}210211export function createProxy<T extends Objectish>(212 immer: Immer,213 value: T,214 parent?: ImmerState215): Drafted<T, ImmerState> {216 // precondition: createProxy should be guarded by isDraftable, so we know we can safely draft217 const draft: Drafted = isMap(value)218 ? getPlugin("MapSet").proxyMap_(value, parent)219 : isSet(value)220 ? getPlugin("MapSet").proxySet_(value, parent)221 : immer.useProxies_222 ? createProxyProxy(value, parent)223 : getPlugin("ES5").createES5Proxy_(value, parent)224225 const scope = parent ? parent.scope_ : getCurrentScope()226 scope.drafts_.push(draft)227 return draft228}