Skip to content
Myr

immerClass.ts

This file

Path

src/core/immerClass.ts

235 lines · 6.4 KiB · TypeScript

Last changed by

unclassed scopeMichel Weststratebefore adoption7a38af9

History of this file

Take it

Moving files into foldersMichel Weststratebefore adoptionab49edc

lines 1–20why, one step back
1import {
2 IProduceWithPatches,3 IProduce,4 ImmerState,5 Drafted,6 isDraftable,7 processResult,8 NOTHING,9 Patch,10 Objectish,11 DRAFT_STATE,12 Draft,13 PatchListener,14 isDraft,15 isMap,16 isSet,17 markChangedProxy,18 createProxyProxy,19 freeze,20 getPlugin,

Tests for pluginsMichel Weststratebefore adoptiondb16520

lines 21–22why, one step back
21 die,
22 hasProxies,

unclassed scopeMichel Weststratebefore adoption7a38af9

lines 23–28why, one step back
23 isMinified,
24 enterScope,25 revokeScope,26 leaveScope,27 usePatchesInScope,28 getCurrentScope

Moving files into foldersMichel Weststratebefore adoptionab49edc

lines 29–36why, one step back
29} from "../internal"
3031interface ProducersFns {32 produce: IProduce33 produceWithPatches: IProduceWithPatches34}3536export class Immer implements ProducersFns {

Tests for pluginsMichel Weststratebefore adoptiondb16520

line 37why, one step back
37 useProxies_: boolean = hasProxies

Moving files into foldersMichel Weststratebefore adoptionab49edc

line 38why, one step back
38

Tests for pluginsMichel Weststratebefore adoptiondb16520

lines 39–40why, one step back
39 autoFreeze_: boolean = __DEV__ ? true /* istanbul ignore next */ : !isMinified
40

Moving files into foldersMichel Weststratebefore adoptionab49edc

lines 41–92why, one step back
41 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)) {

unclassed scopeMichel Weststratebefore adoption7a38af9

line 93why, one step back
93 const scope = enterScope(this)

Moving files into foldersMichel Weststratebefore adoptionab49edc

lines 94–100why, one step back
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 stack

unclassed scopeMichel Weststratebefore adoption7a38af9

lines 101–102why, one step back
101 if (hasError) revokeScope(scope)
102 else leaveScope(scope)

Moving files into foldersMichel Weststratebefore adoptionab49edc

lines 103–106why, one step back
103 }
104 if (typeof Promise !== "undefined" && result instanceof Promise) {105 return result.then(106 result => {

unclassed scopeMichel Weststratebefore adoption7a38af9

line 107why, one step back
107 usePatchesInScope(scope, patchListener)

Moving files into foldersMichel Weststratebefore adoptionab49edc

lines 108–110why, one step back
108 return processResult(result, scope)
109 },110 error => {

unclassed scopeMichel Weststratebefore adoption7a38af9

line 111why, one step back
111 revokeScope(scope)

Moving files into foldersMichel Weststratebefore adoptionab49edc

lines 112–115why, one step back
112 throw error
113 }114 )115 }

unclassed scopeMichel Weststratebefore adoption7a38af9

line 116why, one step back
116 usePatchesInScope(scope, patchListener)

Moving files into foldersMichel Weststratebefore adoptionab49edc

lines 117–142why, one step back
117 return processResult(result, scope)
118 } else {119 result = recipe(base)120 if (result === NOTHING) return undefined121 if (result === undefined) result = base122 if (this.autoFreeze_) freeze(result, true)123 return result124 }125 }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)

unclassed scopeMichel Weststratebefore adoption7a38af9

line 143why, one step back
143 const scope = enterScope(this)

Moving files into foldersMichel Weststratebefore adoptionab49edc

lines 144–145why, one step back
144 const proxy = createProxy(this, base, undefined)
145 proxy[DRAFT_STATE].isManual_ = true

unclassed scopeMichel Weststratebefore adoption7a38af9

line 146why, one step back
146 leaveScope(scope)

Moving files into foldersMichel Weststratebefore adoptionab49edc

lines 147–159why, one step back
147 return proxy as any
148 }149150 finishDraft<D extends Draft<any>>(151 draft: D,152 patchListener?: PatchListener153 ): D extends Draft<infer T> ? T : never {154 const state: ImmerState = draft && draft[DRAFT_STATE]155 if (__DEV__) {156 if (!state || !state.isManual_) die(9)157 if (state.finalized_) die(10)158 }159 const {scope_: scope} = state

unclassed scopeMichel Weststratebefore adoption7a38af9

line 160why, one step back
160 usePatchesInScope(scope, patchListener)

Moving files into foldersMichel Weststratebefore adoptionab49edc

lines 161–179why, one step back
161 return processResult(undefined, scope)
162 }163164 /**165 * Pass true to automatically freeze all copies created by Immer.166 *167 * By default, auto-freezing is disabled in production.168 */169 setAutoFreeze(value: boolean) {170 this.autoFreeze_ = value171 }172173 /**174 * Pass true to use the ES2015 `Proxy` class when creating drafts, which is175 * always faster than using ES5 proxies.176 *177 * By default, feature detection is used, so calling this is rarely necessary.178 */179 setUseProxies(value: boolean) {

Tests for pluginsMichel Weststratebefore adoptiondb16520

lines 180–182why, one step back
180 if (!hasProxies) {
181 die(20)182 }

Moving files into foldersMichel Weststratebefore adoptionab49edc

lines 183–197why, one step back
183 this.useProxies_ = value
184 }185186 applyPatches(base: Objectish, patches: Patch[]) {187 // If a patch replaces the entire state, take that replacement as base188 // before applying patches189 let i: number190 for (i = patches.length - 1; i >= 0; i--) {191 const patch = patches[i]192 if (patch.path.length === 0 && patch.op === "replace") {193 base = patch.value194 break195 }196 }197

Tests for pluginsMichel Weststratebefore adoptiondb16520

line 198why, one step back
198 const applyPatchesImpl = getPlugin("Patches").applyPatches_

Moving files into foldersMichel Weststratebefore adoptionab49edc

lines 199–216why, one step back
199 if (isDraft(base)) {
200 // N.B: never hits if some patch a replacement, patches are never drafts201 return applyPatchesImpl(base, patches)202 }203 // Otherwise, produce a copy of the base state.204 return this.produce(base, (draft: Drafted) =>205 applyPatchesImpl(draft, patches.slice(i + 1))206 )207 }208}209210export function createProxy<T extends Objectish>(211 immer: Immer,212 value: T,213 parent?: ImmerState214): Drafted<T, ImmerState> {215 // precondition: createProxy should be guarded by isDraftable, so we know we can safely draft216 const draft: Drafted = isMap(value)

Tests for pluginsMichel Weststratebefore adoptiondb16520

line 217why, one step back
217 ? getPlugin("MapSet").proxyMap_(value, parent)

Moving files into foldersMichel Weststratebefore adoptionab49edc

line 218why, one step back
218 : isSet(value)

Tests for pluginsMichel Weststratebefore adoptiondb16520

line 219why, one step back
219 ? getPlugin("MapSet").proxySet_(value, parent)

Moving files into foldersMichel Weststratebefore adoptionab49edc

lines 220–221why, one step back
220 : immer.useProxies_
221 ? createProxyProxy(value, parent)

Tests for pluginsMichel Weststratebefore adoptiondb16520

line 222why, one step back
222 : getPlugin("ES5").createES5Proxy_(value, parent)

Moving files into foldersMichel Weststratebefore adoptionab49edc

line 223why, one step back
223

unclassed scopeMichel Weststratebefore adoption7a38af9

line 224why, one step back
224 const scope = parent ? parent.scope_ : getCurrentScope()

Moving files into foldersMichel Weststratebefore adoptionab49edc

lines 225–232why, one step back
225 scope.drafts_.push(draft)
226 return draft227}228229export function markChanged(immer: Immer, state: ImmerState) {230 if (immer.useProxies_) {231 markChangedProxy(state)232 } else {

Tests for pluginsMichel Weststratebefore adoptiondb16520

line 233why, one step back
233 getPlugin("ES5").markChangedES5_(state)

Moving files into foldersMichel Weststratebefore adoptionab49edc

lines 234–235why, one step back
234 }
235}