Skip to content
Myr

immerClass.ts

This file

Path

src/core/immerClass.ts

233 lines · 6.5 KiB · TypeScript

Last changed by

Moving files into foldersMichel Weststratebefore adoptionab49edc

History of this file

Take it

Moving files into foldersMichel Weststratebefore adoptionab49edc

lines 1–233why, one step back
1import {
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,22 die23} from "../internal"2425/* istanbul ignore next */26function verifyMinified() {}2728interface ProducersFns {29 produce: IProduce30 produceWithPatches: IProduceWithPatches31}3233export class Immer implements ProducersFns {34 useProxies_: boolean =35 typeof Proxy !== "undefined" &&36 typeof Proxy.revocable !== "undefined" &&37 typeof Reflect !== "undefined"38 autoFreeze_: boolean = __DEV__39 ? false /* istanbul ignore next */40 : verifyMinified.name === "verifyMinified"4142 constructor(config?: {useProxies?: boolean; autoFreeze?: boolean}) {43 if (typeof config?.useProxies === "boolean")44 this.setUseProxies(config!.useProxies)45 if (typeof config?.autoFreeze === "boolean")46 this.setAutoFreeze(config!.autoFreeze)47 this.produce = this.produce.bind(this)48 this.produceWithPatches = this.produceWithPatches.bind(this)49 }5051 /**52 * The `produce` function takes a value and a "recipe function" (whose53 * return value often depends on the base state). The recipe function is54 * free to mutate its first argument however it wants. All mutations are55 * only ever applied to a __copy__ of the base state.56 *57 * Pass only a function to create a "curried producer" which relieves you58 * from passing the recipe function every time.59 *60 * Only plain objects and arrays are made mutable. All other objects are61 * considered uncopyable.62 *63 * Note: This function is __bound__ to its `Immer` instance.64 *65 * @param {any} base - the initial state66 * @param {Function} producer - function that receives a proxy of the base state as first argument and which can be freely modified67 * @param {Function} patchListener - optional function that will be called with all the patches produced here68 * @returns {any} a new state, or the initial state if nothing was modified69 */70 produce(base: any, recipe?: any, patchListener?: any) {71 // curried invocation72 if (typeof base === "function" && typeof recipe !== "function") {73 const defaultBase = recipe74 recipe = base7576 const self = this77 return function curriedProduce(78 this: any,79 base = defaultBase,80 ...args: any[]81 ) {82 return self.produce(base, (draft: Drafted) => recipe.call(this, draft, ...args)) // prettier-ignore83 }84 }8586 if (typeof recipe !== "function") die(6)87 if (patchListener !== undefined && typeof patchListener !== "function")88 die(7)8990 let result9192 // Only plain objects, arrays, and "immerable classes" are drafted.93 if (isDraftable(base)) {94 const scope = ImmerScope.enter_(this)95 const proxy = createProxy(this, base, undefined)96 let hasError = true97 try {98 result = recipe(proxy)99 hasError = false100 } finally {101 // finally instead of catch + rethrow better preserves original stack102 if (hasError) scope.revoke_()103 else scope.leave_()104 }105 if (typeof Promise !== "undefined" && result instanceof Promise) {106 return result.then(107 result => {108 scope.usePatches_(patchListener)109 return processResult(result, scope)110 },111 error => {112 scope.revoke_()113 throw error114 }115 )116 }117 scope.usePatches_(patchListener)118 return processResult(result, scope)119 } else {120 result = recipe(base)121 if (result === NOTHING) return undefined122 if (result === undefined) result = base123 if (this.autoFreeze_) freeze(result, true)124 return result125 }126 }127128 produceWithPatches(arg1: any, arg2?: any, arg3?: any): any {129 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)144 const scope = ImmerScope.enter_(this)145 const proxy = createProxy(this, base, undefined)146 proxy[DRAFT_STATE].isManual_ = true147 scope.leave_()148 return proxy as any149 }150151 finishDraft<D extends Draft<any>>(152 draft: D,153 patchListener?: PatchListener154 ): D extends Draft<infer T> ? T : never {155 const state: ImmerState = draft && draft[DRAFT_STATE]156 if (__DEV__) {157 if (!state || !state.isManual_) die(9)158 if (state.finalized_) die(10)159 }160 const {scope_: scope} = state161 scope.usePatches_(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) {181 this.useProxies_ = value182 }183184 applyPatches(base: Objectish, patches: Patch[]) {185 // If a patch replaces the entire state, take that replacement as base186 // before applying patches187 let i: number188 for (i = patches.length - 1; i >= 0; i--) {189 const patch = patches[i]190 if (patch.path.length === 0 && patch.op === "replace") {191 base = patch.value192 break193 }194 }195196 const applyPatchesImpl = getPlugin("patches").applyPatches_197 if (isDraft(base)) {198 // N.B: never hits if some patch a replacement, patches are never drafts199 return applyPatchesImpl(base, patches)200 }201 // Otherwise, produce a copy of the base state.202 return this.produce(base, (draft: Drafted) =>203 applyPatchesImpl(draft, patches.slice(i + 1))204 )205 }206}207208export function createProxy<T extends Objectish>(209 immer: Immer,210 value: T,211 parent?: ImmerState212): Drafted<T, ImmerState> {213 // precondition: createProxy should be guarded by isDraftable, so we know we can safely draft214 const draft: Drafted = isMap(value)215 ? getPlugin("mapset").proxyMap_(value, parent)216 : isSet(value)217 ? getPlugin("mapset").proxySet_(value, parent)218 : immer.useProxies_219 ? createProxyProxy(value, parent)220 : getPlugin("es5").createES5Proxy_(value, parent)221222 const scope = parent ? parent.scope_ : ImmerScope.current_!223 scope.drafts_.push(draft)224 return draft225}226227export function markChanged(immer: Immer, state: ImmerState) {228 if (immer.useProxies_) {229 markChangedProxy(state)230 } else {231 getPlugin("es5").markChangedES5_(state)232 }233}