immerClass.ts
This file
Path
src/core/immerClass.ts
231 lines · 6.3 KiB · TypeScript
Last changed by
Tests for pluginsMichel Weststratebefore adoptiondb16520
History of this fileTake it
Moving files into foldersMichel Weststratebefore adoptionab49edc
lines 1–21why, one step back1import {2 IProduceWithPatches,3 IProduce,4 ImmerState,5 Drafted,6 isDraftable,7 ImmerScope,8 processResult,9 NOTHING,10 Patch,11 Objectish,12 DRAFT_STATE,13 Draft,14 PatchListener,15 isDraft,16 isMap,17 isSet,18 markChangedProxy,19 createProxyProxy,20 freeze,21 getPlugin,Tests for pluginsMichel Weststratebefore adoptiondb16520
lines 22–24why, one step back22 die,23 hasProxies,24 isMinifiedMoving files into foldersMichel Weststratebefore adoptionab49edc
lines 25–32why, one step back25} from "../internal"2627interface ProducersFns {28 produce: IProduce29 produceWithPatches: IProduceWithPatches30}3132export class Immer implements ProducersFns {Tests for pluginsMichel Weststratebefore adoptiondb16520
line 33why, one step back33 useProxies_: boolean = hasProxiesMoving files into foldersMichel Weststratebefore adoptionab49edc
line 34why, one step back34Tests for pluginsMichel Weststratebefore adoptiondb16520
lines 35–36why, one step back35 autoFreeze_: boolean = __DEV__ ? true /* istanbul ignore next */ : !isMinified36Moving files into foldersMichel Weststratebefore adoptionab49edc
lines 37–175why, one step back37 constructor(config?: {useProxies?: boolean; autoFreeze?: boolean}) {38 if (typeof config?.useProxies === "boolean")39 this.setUseProxies(config!.useProxies)40 if (typeof config?.autoFreeze === "boolean")41 this.setAutoFreeze(config!.autoFreeze)42 this.produce = this.produce.bind(this)43 this.produceWithPatches = this.produceWithPatches.bind(this)44 }4546 /**47 * The `produce` function takes a value and a "recipe function" (whose48 * return value often depends on the base state). The recipe function is49 * free to mutate its first argument however it wants. All mutations are50 * only ever applied to a __copy__ of the base state.51 *52 * Pass only a function to create a "curried producer" which relieves you53 * from passing the recipe function every time.54 *55 * Only plain objects and arrays are made mutable. All other objects are56 * considered uncopyable.57 *58 * Note: This function is __bound__ to its `Immer` instance.59 *60 * @param {any} base - the initial state61 * @param {Function} producer - function that receives a proxy of the base state as first argument and which can be freely modified62 * @param {Function} patchListener - optional function that will be called with all the patches produced here63 * @returns {any} a new state, or the initial state if nothing was modified64 */65 produce(base: any, recipe?: any, patchListener?: any) {66 // curried invocation67 if (typeof base === "function" && typeof recipe !== "function") {68 const defaultBase = recipe69 recipe = base7071 const self = this72 return function curriedProduce(73 this: any,74 base = defaultBase,75 ...args: any[]76 ) {77 return self.produce(base, (draft: Drafted) => recipe.call(this, draft, ...args)) // prettier-ignore78 }79 }8081 if (typeof recipe !== "function") die(6)82 if (patchListener !== undefined && typeof patchListener !== "function")83 die(7)8485 let result8687 // Only plain objects, arrays, and "immerable classes" are drafted.88 if (isDraftable(base)) {89 const scope = ImmerScope.enter_(this)90 const proxy = createProxy(this, base, undefined)91 let hasError = true92 try {93 result = recipe(proxy)94 hasError = false95 } finally {96 // finally instead of catch + rethrow better preserves original stack97 if (hasError) scope.revoke_()98 else scope.leave_()99 }100 if (typeof Promise !== "undefined" && result instanceof Promise) {101 return result.then(102 result => {103 scope.usePatches_(patchListener)104 return processResult(result, scope)105 },106 error => {107 scope.revoke_()108 throw error109 }110 )111 }112 scope.usePatches_(patchListener)113 return processResult(result, scope)114 } else {115 result = recipe(base)116 if (result === NOTHING) return undefined117 if (result === undefined) result = base118 if (this.autoFreeze_) freeze(result, true)119 return result120 }121 }122123 produceWithPatches(arg1: any, arg2?: any, arg3?: any): any {124 if (typeof arg1 === "function") {125 return (state: any, ...args: any[]) =>126 this.produceWithPatches(state, (draft: any) => arg1(draft, ...args))127 }128129 let patches: Patch[], inversePatches: Patch[]130 const nextState = this.produce(arg1, arg2, (p: Patch[], ip: Patch[]) => {131 patches = p132 inversePatches = ip133 })134 return [nextState, patches!, inversePatches!]135 }136137 createDraft<T extends Objectish>(base: T): Draft<T> {138 if (!isDraftable(base)) die(8)139 const scope = ImmerScope.enter_(this)140 const proxy = createProxy(this, base, undefined)141 proxy[DRAFT_STATE].isManual_ = true142 scope.leave_()143 return proxy as any144 }145146 finishDraft<D extends Draft<any>>(147 draft: D,148 patchListener?: PatchListener149 ): D extends Draft<infer T> ? T : never {150 const state: ImmerState = draft && draft[DRAFT_STATE]151 if (__DEV__) {152 if (!state || !state.isManual_) die(9)153 if (state.finalized_) die(10)154 }155 const {scope_: scope} = state156 scope.usePatches_(patchListener)157 return processResult(undefined, scope)158 }159160 /**161 * Pass true to automatically freeze all copies created by Immer.162 *163 * By default, auto-freezing is disabled in production.164 */165 setAutoFreeze(value: boolean) {166 this.autoFreeze_ = value167 }168169 /**170 * Pass true to use the ES2015 `Proxy` class when creating drafts, which is171 * always faster than using ES5 proxies.172 *173 * By default, feature detection is used, so calling this is rarely necessary.174 */175 setUseProxies(value: boolean) {Tests for pluginsMichel Weststratebefore adoptiondb16520
lines 176–178why, one step back176 if (!hasProxies) {177 die(20)178 }Moving files into foldersMichel Weststratebefore adoptionab49edc
lines 179–193why, one step back179 this.useProxies_ = value180 }181182 applyPatches(base: Objectish, patches: Patch[]) {183 // If a patch replaces the entire state, take that replacement as base184 // before applying patches185 let i: number186 for (i = patches.length - 1; i >= 0; i--) {187 const patch = patches[i]188 if (patch.path.length === 0 && patch.op === "replace") {189 base = patch.value190 break191 }192 }193Tests for pluginsMichel Weststratebefore adoptiondb16520
line 194why, one step back194 const applyPatchesImpl = getPlugin("Patches").applyPatches_Moving files into foldersMichel Weststratebefore adoptionab49edc
lines 195–212why, one step back195 if (isDraft(base)) {196 // N.B: never hits if some patch a replacement, patches are never drafts197 return applyPatchesImpl(base, patches)198 }199 // Otherwise, produce a copy of the base state.200 return this.produce(base, (draft: Drafted) =>201 applyPatchesImpl(draft, patches.slice(i + 1))202 )203 }204}205206export function createProxy<T extends Objectish>(207 immer: Immer,208 value: T,209 parent?: ImmerState210): Drafted<T, ImmerState> {211 // precondition: createProxy should be guarded by isDraftable, so we know we can safely draft212 const draft: Drafted = isMap(value)Tests for pluginsMichel Weststratebefore adoptiondb16520
line 213why, one step back213 ? getPlugin("MapSet").proxyMap_(value, parent)Moving files into foldersMichel Weststratebefore adoptionab49edc
line 214why, one step back214 : isSet(value)Tests for pluginsMichel Weststratebefore adoptiondb16520
line 215why, one step back215 ? getPlugin("MapSet").proxySet_(value, parent)Moving files into foldersMichel Weststratebefore adoptionab49edc
lines 216–217why, one step back216 : immer.useProxies_217 ? createProxyProxy(value, parent)Tests for pluginsMichel Weststratebefore adoptiondb16520
line 218why, one step back218 : getPlugin("ES5").createES5Proxy_(value, parent)Moving files into foldersMichel Weststratebefore adoptionab49edc
lines 219–228why, one step back219220 const scope = parent ? parent.scope_ : ImmerScope.current_!221 scope.drafts_.push(draft)222 return draft223}224225export function markChanged(immer: Immer, state: ImmerState) {226 if (immer.useProxies_) {227 markChangedProxy(state)228 } else {Tests for pluginsMichel Weststratebefore adoptiondb16520
line 229why, one step back229 getPlugin("ES5").markChangedES5_(state)Moving files into foldersMichel Weststratebefore adoptionab49edc
lines 230–231why, one step back230 }231}