Skip to content
Myr

immerClass.ts

This file

Path

src/core/immerClass.ts

219 lines · 6.0 KiB · TypeScript

Last changed by

Code cleanup, bug fixesMichel Weststratebefore adoption0592d3c

History of this file

Take it

Merge pull request #536 from immerjs/multi-bundleMichel Weststratebefore adoption0d87fc8

lines 1–115why, one step back
1import {
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,25 getCurrentScope26} from "../internal"2728interface ProducersFns {29 produce: IProduce30 produceWithPatches: IProduceWithPatches31}3233export class Immer implements ProducersFns {34 useProxies_: boolean = hasProxies3536 autoFreeze_: boolean = __DEV__ ? true /* istanbul ignore next */ : !isMinified3738 constructor(config?: {useProxies?: boolean; autoFreeze?: boolean}) {39 if (typeof config?.useProxies === "boolean")40 this.setUseProxies(config!.useProxies)41 if (typeof config?.autoFreeze === "boolean")42 this.setAutoFreeze(config!.autoFreeze)43 this.produce = this.produce.bind(this)44 this.produceWithPatches = this.produceWithPatches.bind(this)45 }4647 /**48 * The `produce` function takes a value and a "recipe function" (whose49 * return value often depends on the base state). The recipe function is50 * free to mutate its first argument however it wants. All mutations are51 * only ever applied to a __copy__ of the base state.52 *53 * Pass only a function to create a "curried producer" which relieves you54 * from passing the recipe function every time.55 *56 * Only plain objects and arrays are made mutable. All other objects are57 * considered uncopyable.58 *59 * Note: This function is __bound__ to its `Immer` instance.60 *61 * @param {any} base - the initial state62 * @param {Function} producer - function that receives a proxy of the base state as first argument and which can be freely modified63 * @param {Function} patchListener - optional function that will be called with all the patches produced here64 * @returns {any} a new state, or the initial state if nothing was modified65 */66 produce(base: any, recipe?: any, patchListener?: any) {67 // curried invocation68 if (typeof base === "function" && typeof recipe !== "function") {69 const defaultBase = recipe70 recipe = base7172 const self = this73 return function curriedProduce(74 this: any,75 base = defaultBase,76 ...args: any[]77 ) {78 return self.produce(base, (draft: Drafted) => recipe.call(this, draft, ...args)) // prettier-ignore79 }80 }8182 if (typeof recipe !== "function") die(6)83 if (patchListener !== undefined && typeof patchListener !== "function")84 die(7)8586 let result8788 // Only plain objects, arrays, and "immerable classes" are drafted.89 if (isDraftable(base)) {90 const scope = enterScope(this)91 const proxy = createProxy(this, base, undefined)92 let hasError = true93 try {94 result = recipe(proxy)95 hasError = false96 } finally {97 // finally instead of catch + rethrow better preserves original stack98 if (hasError) revokeScope(scope)99 else leaveScope(scope)100 }101 if (typeof Promise !== "undefined" && result instanceof Promise) {102 return result.then(103 result => {104 usePatchesInScope(scope, patchListener)105 return processResult(result, scope)106 },107 error => {108 revokeScope(scope)109 throw error110 }111 )112 }113 usePatchesInScope(scope, patchListener)114 return processResult(result, scope)115 }

fix: produce no longer accepts non draftable objects, fixes #596Michel Weststratebefore adoptiond9bf68b

line 116why, one step back
116 die(21, base)

Merge pull request #536 from immerjs/multi-bundleMichel Weststratebefore adoption0d87fc8

lines 117–145why, one step back
117 }
118119 produceWithPatches(arg1: any, arg2?: any, arg3?: any): any {120 if (typeof arg1 === "function") {121 return (state: any, ...args: any[]) =>122 this.produceWithPatches(state, (draft: any) => arg1(draft, ...args))123 }124125 let patches: Patch[], inversePatches: Patch[]126 const nextState = this.produce(arg1, arg2, (p: Patch[], ip: Patch[]) => {127 patches = p128 inversePatches = ip129 })130 return [nextState, patches!, inversePatches!]131 }132133 createDraft<T extends Objectish>(base: T): Draft<T> {134 if (!isDraftable(base)) die(8)135 const scope = enterScope(this)136 const proxy = createProxy(this, base, undefined)137 proxy[DRAFT_STATE].isManual_ = true138 leaveScope(scope)139 return proxy as any140 }141142 finishDraft<D extends Draft<any>>(143 draft: D,144 patchListener?: PatchListener145 ): D extends Draft<infer T> ? T : never {

fix: produce no longer accepts non draftable objects, fixes #596Michel Weststratebefore adoptiond9bf68b

line 146why, one step back
146 const state: ImmerState = draft && (draft as any)[DRAFT_STATE]

Merge pull request #536 from immerjs/multi-bundleMichel Weststratebefore adoption0d87fc8

lines 147–219why, one step back
147 if (__DEV__) {
148 if (!state || !state.isManual_) die(9)149 if (state.finalized_) die(10)150 }151 const {scope_: scope} = state152 usePatchesInScope(scope, patchListener)153 return processResult(undefined, scope)154 }155156 /**157 * Pass true to automatically freeze all copies created by Immer.158 *159 * By default, auto-freezing is disabled in production.160 */161 setAutoFreeze(value: boolean) {162 this.autoFreeze_ = value163 }164165 /**166 * Pass true to use the ES2015 `Proxy` class when creating drafts, which is167 * always faster than using ES5 proxies.168 *169 * By default, feature detection is used, so calling this is rarely necessary.170 */171 setUseProxies(value: boolean) {172 if (!hasProxies) {173 die(20)174 }175 this.useProxies_ = value176 }177178 applyPatches(base: Objectish, patches: Patch[]) {179 // If a patch replaces the entire state, take that replacement as base180 // before applying patches181 let i: number182 for (i = patches.length - 1; i >= 0; i--) {183 const patch = patches[i]184 if (patch.path.length === 0 && patch.op === "replace") {185 base = patch.value186 break187 }188 }189190 const applyPatchesImpl = getPlugin("Patches").applyPatches_191 if (isDraft(base)) {192 // N.B: never hits if some patch a replacement, patches are never drafts193 return applyPatchesImpl(base, patches)194 }195 // Otherwise, produce a copy of the base state.196 return this.produce(base, (draft: Drafted) =>197 applyPatchesImpl(draft, patches.slice(i + 1))198 )199 }200}201202export function createProxy<T extends Objectish>(203 immer: Immer,204 value: T,205 parent?: ImmerState206): Drafted<T, ImmerState> {207 // precondition: createProxy should be guarded by isDraftable, so we know we can safely draft208 const draft: Drafted = isMap(value)209 ? getPlugin("MapSet").proxyMap_(value, parent)210 : isSet(value)211 ? getPlugin("MapSet").proxySet_(value, parent)212 : immer.useProxies_213 ? createProxyProxy(value, parent)214 : getPlugin("ES5").createES5Proxy_(value, parent)215216 const scope = parent ? parent.scope_ : getCurrentScope()217 scope.drafts_.push(draft)218 return draft219}