Skip to content
Myr

immerClass.ts

This file

Path

src/core/immerClass.ts

244 lines · 6.7 KiB · TypeScript

Last changed by

chore: remove unused arg3 in produceWithPatches (#975)Brian Hungbefore adoption078e523

History of this file

Take it

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

lines 1–23why, 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 enterScope,21 revokeScope,22 leaveScope,23 usePatchesInScope,

Immer 7Michel Weststratebefore adoption467ea5d

lines 24–27why, one step back
24 getCurrentScope,
25 NOTHING,26 freeze,27 current

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

lines 28–37why, one step back
28} from "../internal"
2930interface ProducersFns {31 produce: IProduce32 produceWithPatches: IProduceWithPatches33}3435export class Immer implements ProducersFns {36 useProxies_: boolean = hasProxies37

feature: Always freeze by default (#702)Michel Weststratebefore adoptiona406c8f

line 38why, one step back
38 autoFreeze_: boolean = true

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

lines 39–65why, one step back
39
40 constructor(config?: {useProxies?: boolean; autoFreeze?: boolean}) {41 if (typeof config?.useProxies === "boolean")42 this.setUseProxies(config!.useProxies)43 if (typeof config?.autoFreeze === "boolean")44 this.setAutoFreeze(config!.autoFreeze)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 */

fix: new Immer().produce now has the same type as produce. Fixes #749Michel Weststratebefore adoptionf8b77d1

line 66why, one step back
66 produce: IProduce = (base: any, recipe?: any, patchListener?: any) => {

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

lines 67–114why, one step back
67 // curried invocation
68 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)

Immer 7Michel Weststratebefore adoption467ea5d

line 115why, one step back
115 } else if (!base || typeof base !== "object") {

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

lines 116–117why, one step back
116 result = recipe(base)
117 if (result === undefined) result = base

fix: No patches being generated for root primitive replacements. Fixes #888Michel Weststratebefore adoption0f96270

line 118why, one step back
118 if (result === NOTHING) result = undefined

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

line 119why, one step back
119 if (this.autoFreeze_) freeze(result, true)

fix: No patches being generated for root primitive replacements. Fixes #888Michel Weststratebefore adoption0f96270

lines 120–125why, one step back
120 if (patchListener) {
121 const p: Patch[] = []122 const ip: Patch[] = []123 getPlugin("Patches").generateReplacementPatches_(base, result, p, ip)124 patchListener(p, ip)125 }

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

line 126why, one step back
126 return result

Immer 7Michel Weststratebefore adoption467ea5d

line 127why, one step back
127 } else die(21, base)

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

lines 128–129why, one step back
128 }
129

fix: new Immer().produce now has the same type as produce. Fixes #749Michel Weststratebefore adoptionf8b77d1

line 130why, one step back
130 produceWithPatches: IProduceWithPatches = (

chore: remove unused arg3 in produceWithPatches (#975)Brian Hungbefore adoption078e523

lines 131–132why, one step back
131 base: any,
132 recipe?: any,

fix: new Immer().produce now has the same type as produce. Fixes #749Michel Weststratebefore adoptionf8b77d1

line 133why, one step back
133 ): any => {

chore: remove unused arg3 in produceWithPatches (#975)Brian Hungbefore adoption078e523

lines 134–135why, one step back
134 // curried invocation
135 if (typeof base === "function") {

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

line 136why, one step back
136 return (state: any, ...args: any[]) =>

chore: remove unused arg3 in produceWithPatches (#975)Brian Hungbefore adoption078e523

line 137why, one step back
137 this.produceWithPatches(state, (draft: any) => base(draft, ...args))

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

lines 138–140why, one step back
138 }
139140 let patches: Patch[], inversePatches: Patch[]

chore: remove unused arg3 in produceWithPatches (#975)Brian Hungbefore adoption078e523

line 141why, one step back
141 const result = this.produce(base, recipe, (p: Patch[], ip: Patch[]) => {

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

lines 142–144why, one step back
142 patches = p
143 inversePatches = ip144 })

fix: make sure produceWithPatches accepts promisescviejobefore adoptiond80e823

lines 145–149why, one step back
145
146 if (typeof Promise !== "undefined" && result instanceof Promise) {147 return result.then(nextState => [nextState, patches!, inversePatches!])148 }149 return [result, patches!, inversePatches!]

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

lines 150–153why, one step back
150 }
151152 createDraft<T extends Objectish>(base: T): Draft<T> {153 if (!isDraftable(base)) die(8)

Immer 7Michel Weststratebefore adoption467ea5d

line 154why, one step back
154 if (isDraft(base)) base = current(base)

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

lines 155–165why, one step back
155 const scope = enterScope(this)
156 const proxy = createProxy(this, base, undefined)157 proxy[DRAFT_STATE].isManual_ = true158 leaveScope(scope)159 return proxy as any160 }161162 finishDraft<D extends Draft<any>>(163 draft: D,164 patchListener?: PatchListener165 ): D extends Draft<infer T> ? T : never {

Immer 7Michel Weststratebefore adoption467ea5d

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

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

lines 167–178why, one step back
167 if (__DEV__) {
168 if (!state || !state.isManual_) die(9)169 if (state.finalized_) die(10)170 }171 const {scope_: scope} = state172 usePatchesInScope(scope, patchListener)173 return processResult(undefined, scope)174 }175176 /**177 * Pass true to automatically freeze all copies created by Immer.178 *

docs: some refinements on freezingMichel Weststratebefore adoption7faa7b4

line 179why, one step back
179 * By default, auto-freezing is enabled.

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

lines 180–191why, one step back
180 */
181 setAutoFreeze(value: boolean) {182 this.autoFreeze_ = value183 }184185 /**186 * Pass true to use the ES2015 `Proxy` class when creating drafts, which is187 * always faster than using ES5 proxies.188 *189 * By default, feature detection is used, so calling this is rarely necessary.190 */191 setUseProxies(value: boolean) {

Immer 7Michel Weststratebefore adoption467ea5d

line 192why, one step back
192 if (value && !hasProxies) {

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

lines 193–197why, one step back
193 die(20)
194 }195 this.useProxies_ = value196 }197

fix: Better applyPatches type (#810)Josh Kelleybefore adoption09ac097

line 198why, one step back
198 applyPatches<T extends Objectish>(base: T, patches: Patch[]): T {

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

lines 199–208why, one step back
199 // If a patch replaces the entire state, take that replacement as base
200 // before applying patches201 let i: number202 for (i = patches.length - 1; i >= 0; i--) {203 const patch = patches[i]204 if (patch.path.length === 0 && patch.op === "replace") {205 base = patch.value206 break207 }208 }

fix: Append to array when key is "-" (#872)Louis DeSciolibefore adoption2afdb1b

lines 209–213why, one step back
209 // If there was a patch that replaced the entire state, start from the
210 // patch after that.211 if (i > -1) {212 patches = patches.slice(i + 1)213 }

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

lines 214–217why, one step back
214
215 const applyPatchesImpl = getPlugin("Patches").applyPatches_216 if (isDraft(base)) {217 // N.B: never hits if some patch a replacement, patches are never drafts

fix: Append to array when key is "-" (#872)Louis DeSciolibefore adoption2afdb1b

line 218why, one step back
218 return applyPatchesImpl(base, patches)

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

lines 219–221why, one step back
219 }
220 // Otherwise, produce a copy of the base state.221 return this.produce(base, (draft: Drafted) =>

fix: Append to array when key is "-" (#872)Louis DeSciolibefore adoption2afdb1b

lines 222–223why, one step back
222 applyPatchesImpl(draft, patches)
223 )

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

lines 224–244why, one step back
224 }
225}226227export function createProxy<T extends Objectish>(228 immer: Immer,229 value: T,230 parent?: ImmerState231): Drafted<T, ImmerState> {232 // precondition: createProxy should be guarded by isDraftable, so we know we can safely draft233 const draft: Drafted = isMap(value)234 ? getPlugin("MapSet").proxyMap_(value, parent)235 : isSet(value)236 ? getPlugin("MapSet").proxySet_(value, parent)237 : immer.useProxies_238 ? createProxyProxy(value, parent)239 : getPlugin("ES5").createES5Proxy_(value, parent)240241 const scope = parent ? parent.scope_ : getCurrentScope()242 scope.drafts_.push(draft)243 return draft244}