immerClass.ts
This file
Path
src/core/immerClass.ts
236 lines · 6.7 KiB · TypeScript
Last changed by
feat: Optimize Immer performance where possible, introduce `setUseStrictIteration` (#1164)Mark Eriksonbefore adoptione1996ce
History of this fileTake it
The walk stopped after 200 commits: lines older than bc35916 point at it.
chore: fix links, fixes #779Michel Weststratebefore adoptionbc35916
lines 1–33why, one step back1import {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 enterScope,20 revokeScope,21 leaveScope,22 usePatchesInScope,23 getCurrentScope,24 NOTHING,25 freeze,26 current27} from "../internal"2829interface ProducersFns {30 produce: IProduce31 produceWithPatches: IProduceWithPatches32}33feat: Optimize Immer performance where possible, introduce `setUseStrictIteration` (#1164)Mark Eriksonbefore adoptione1996ce
line 34why, one step back34export type StrictMode = boolean | "class_only"feat(performance): Make non-strict mode faster for classes. Addresses #1071Michel Weststratebefore adoption53e3203
line 35why, one step back35chore: fix links, fixes #779Michel Weststratebefore adoptionbc35916
lines 36–37why, one step back36export class Immer implements ProducersFns {37 autoFreeze_: boolean = truefeat(performance): Make non-strict mode faster for classes. Addresses #1071Michel Weststratebefore adoption53e3203
line 38why, one step back38 useStrictShallowCopy_: StrictMode = falsefeat: Optimize Immer performance where possible, introduce `setUseStrictIteration` (#1164)Mark Eriksonbefore adoptione1996ce
line 39why, one step back39 useStrictIteration_: boolean = truechore: fix links, fixes #779Michel Weststratebefore adoptionbc35916
line 40why, one step back40feat(performance): Make non-strict mode faster for classes. Addresses #1071Michel Weststratebefore adoption53e3203
lines 41–43why, one step back41 constructor(config?: {42 autoFreeze?: boolean43 useStrictShallowCopy?: StrictModefeat: Optimize Immer performance where possible, introduce `setUseStrictIteration` (#1164)Mark Eriksonbefore adoptione1996ce
line 44why, one step back44 useStrictIteration?: booleanfeat(performance): Make non-strict mode faster for classes. Addresses #1071Michel Weststratebefore adoption53e3203
line 45why, one step back45 }) {chore: fix links, fixes #779Michel Weststratebefore adoptionbc35916
lines 46–47why, one step back46 if (typeof config?.autoFreeze === "boolean")47 this.setAutoFreeze(config!.autoFreeze)Merge pull request #1028 from immerjs/immer-10Michel Weststratebefore adoption2ef9a42
lines 48–49why, one step back48 if (typeof config?.useStrictShallowCopy === "boolean")49 this.setUseStrictShallowCopy(config!.useStrictShallowCopy)feat: Optimize Immer performance where possible, introduce `setUseStrictIteration` (#1164)Mark Eriksonbefore adoptione1996ce
lines 50–51why, one step back50 if (typeof config?.useStrictIteration === "boolean")51 this.setUseStrictIteration(config!.useStrictIteration)chore: fix links, fixes #779Michel Weststratebefore adoptionbc35916
lines 52–68why, one step back52 }5354 /**55 * The `produce` function takes a value and a "recipe function" (whose56 * return value often depends on the base state). The recipe function is57 * free to mutate its first argument however it wants. All mutations are58 * only ever applied to a __copy__ of the base state.59 *60 * Pass only a function to create a "curried producer" which relieves you61 * from passing the recipe function every time.62 *63 * Only plain objects and arrays are made mutable. All other objects are64 * considered uncopyable.65 *66 * Note: This function is __bound__ to its `Immer` instance.67 *68 * @param {any} base - the initial statechore: fixed jsdoc parameter name (#994)Christopher Tranbefore adoption8a02d81
line 69why, one step back69 * @param {Function} recipe - function that receives a proxy of the base state as first argument and which can be freely modifiedchore: fix links, fixes #779Michel Weststratebefore adoptionbc35916
lines 70–97why, one step back70 * @param {Function} patchListener - optional function that will be called with all the patches produced here71 * @returns {any} a new state, or the initial state if nothing was modified72 */73 produce: IProduce = (base: any, recipe?: any, patchListener?: any) => {74 // curried invocation75 if (typeof base === "function" && typeof recipe !== "function") {76 const defaultBase = recipe77 recipe = base7879 const self = this80 return function curriedProduce(81 this: any,82 base = defaultBase,83 ...args: any[]84 ) {85 return self.produce(base, (draft: Drafted) => recipe.call(this, draft, ...args)) // prettier-ignore86 }87 }8889 if (typeof recipe !== "function") die(6)90 if (patchListener !== undefined && typeof patchListener !== "function")91 die(7)9293 let result9495 // Only plain objects, arrays, and "immerable classes" are drafted.96 if (isDraftable(base)) {97 const scope = enterScope(this)Merge pull request #1028 from immerjs/immer-10Michel Weststratebefore adoption2ef9a42
line 98why, one step back98 const proxy = createProxy(base, undefined)chore: fix links, fixes #779Michel Weststratebefore adoptionbc35916
lines 99–112why, one step back99 let hasError = true100 try {101 result = recipe(proxy)102 hasError = false103 } finally {104 // finally instead of catch + rethrow better preserves original stack105 if (hasError) revokeScope(scope)106 else leaveScope(scope)107 }108 usePatchesInScope(scope, patchListener)109 return processResult(result, scope)110 } else if (!base || typeof base !== "object") {111 result = recipe(base)112 if (result === undefined) result = basefix: No patches being generated for root primitive replacements. Fixes #888Michel Weststratebefore adoption0f96270
line 113why, one step back113 if (result === NOTHING) result = undefinedchore: fix links, fixes #779Michel Weststratebefore adoptionbc35916
line 114why, one step back114 if (this.autoFreeze_) freeze(result, true)fix: No patches being generated for root primitive replacements. Fixes #888Michel Weststratebefore adoption0f96270
lines 115–120why, one step back115 if (patchListener) {116 const p: Patch[] = []117 const ip: Patch[] = []118 getPlugin("Patches").generateReplacementPatches_(base, result, p, ip)119 patchListener(p, ip)120 }chore: fix links, fixes #779Michel Weststratebefore adoptionbc35916
line 121why, one step back121 return resultMerge pull request #1028 from immerjs/immer-10Michel Weststratebefore adoption2ef9a42
line 122why, one step back122 } else die(1, base)chore: fix links, fixes #779Michel Weststratebefore adoptionbc35916
lines 123–124why, one step back123 }124chore: fixed jsdoc parameter name (#994)Christopher Tranbefore adoption8a02d81
line 125why, one step back125 produceWithPatches: IProduceWithPatches = (base: any, recipe?: any): any => {chore: remove unused arg3 in produceWithPatches (#975)Brian Hungbefore adoption078e523
lines 126–127why, one step back126 // curried invocation127 if (typeof base === "function") {chore: fix links, fixes #779Michel Weststratebefore adoptionbc35916
line 128why, one step back128 return (state: any, ...args: any[]) =>chore: remove unused arg3 in produceWithPatches (#975)Brian Hungbefore adoption078e523
line 129why, one step back129 this.produceWithPatches(state, (draft: any) => base(draft, ...args))chore: fix links, fixes #779Michel Weststratebefore adoptionbc35916
lines 130–132why, one step back130 }131132 let patches: Patch[], inversePatches: Patch[]chore: remove unused arg3 in produceWithPatches (#975)Brian Hungbefore adoption078e523
line 133why, one step back133 const result = this.produce(base, recipe, (p: Patch[], ip: Patch[]) => {chore: fix links, fixes #779Michel Weststratebefore adoptionbc35916
lines 134–136why, one step back134 patches = p135 inversePatches = ip136 })fix: make sure produceWithPatches accepts promisescviejobefore adoptiond80e823
line 137why, one step back137 return [result, patches!, inversePatches!]chore: fix links, fixes #779Michel Weststratebefore adoptionbc35916
lines 138–143why, one step back138 }139140 createDraft<T extends Objectish>(base: T): Draft<T> {141 if (!isDraftable(base)) die(8)142 if (isDraft(base)) base = current(base)143 const scope = enterScope(this)Merge pull request #1028 from immerjs/immer-10Michel Weststratebefore adoption2ef9a42
line 144why, one step back144 const proxy = createProxy(base, undefined)chore: fix links, fixes #779Michel Weststratebefore adoptionbc35916
lines 145–154why, one step back145 proxy[DRAFT_STATE].isManual_ = true146 leaveScope(scope)147 return proxy as any148 }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 as any)[DRAFT_STATE]Merge pull request #1028 from immerjs/immer-10Michel Weststratebefore adoption2ef9a42
line 155why, one step back155 if (!state || !state.isManual_) die(9)chore: fix links, fixes #779Michel Weststratebefore adoptionbc35916
lines 156–170why, one step back156 const {scope_: scope} = state157 usePatchesInScope(scope, patchListener)158 return processResult(undefined, scope)159 }160161 /**162 * Pass true to automatically freeze all copies created by Immer.163 *164 * By default, auto-freezing is enabled.165 */166 setAutoFreeze(value: boolean) {167 this.autoFreeze_ = value168 }169170 /**Merge pull request #1028 from immerjs/immer-10Michel Weststratebefore adoption2ef9a42
line 171why, one step back171 * Pass true to enable strict shallow copy.chore: fix links, fixes #779Michel Weststratebefore adoptionbc35916
line 172why, one step back172 *Merge pull request #1028 from immerjs/immer-10Michel Weststratebefore adoption2ef9a42
line 173why, one step back173 * By default, immer does not copy the object descriptors such as getter, setter and non-enumrable properties.chore: fix links, fixes #779Michel Weststratebefore adoptionbc35916
line 174why, one step back174 */feat(performance): Make non-strict mode faster for classes. Addresses #1071Michel Weststratebefore adoption53e3203
line 175why, one step back175 setUseStrictShallowCopy(value: StrictMode) {Merge pull request #1028 from immerjs/immer-10Michel Weststratebefore adoption2ef9a42
line 176why, one step back176 this.useStrictShallowCopy_ = valuefeat: Optimize Immer performance where possible, introduce `setUseStrictIteration` (#1164)Mark Eriksonbefore adoptione1996ce
lines 177–190why, one step back177 }178179 /**180 * Pass false to use faster iteration that skips non-enumerable properties181 * but still handles symbols for compatibility.182 *183 * By default, strict iteration is enabled (includes all own properties).184 */185 setUseStrictIteration(value: boolean) {186 this.useStrictIteration_ = value187 }188189 shouldUseStrictIteration(): boolean {190 return this.useStrictIteration_chore: fix links, fixes #779Michel Weststratebefore adoptionbc35916
lines 191–192why, one step back191 }192fix: Make `applyPatches` to accept `readonly Patch[]` (#1094)Mateusz Burzyńskibefore adoption4da2e0d
line 193why, one step back193 applyPatches<T extends Objectish>(base: T, patches: readonly Patch[]): T {chore: fix links, fixes #779Michel Weststratebefore adoptionbc35916
lines 194–203why, one step back194 // If a patch replaces the entire state, take that replacement as base195 // before applying patches196 let i: number197 for (i = patches.length - 1; i >= 0; i--) {198 const patch = patches[i]199 if (patch.path.length === 0 && patch.op === "replace") {200 base = patch.value201 break202 }203 }fix: Append to array when key is "-" (#872)Louis DeSciolibefore adoption2afdb1b
lines 204–208why, one step back204 // If there was a patch that replaced the entire state, start from the205 // patch after that.206 if (i > -1) {207 patches = patches.slice(i + 1)208 }chore: fix links, fixes #779Michel Weststratebefore adoptionbc35916
lines 209–212why, one step back209210 const applyPatchesImpl = getPlugin("Patches").applyPatches_211 if (isDraft(base)) {212 // N.B: never hits if some patch a replacement, patches are never draftsfix: Append to array when key is "-" (#872)Louis DeSciolibefore adoption2afdb1b
line 213why, one step back213 return applyPatchesImpl(base, patches)chore: fix links, fixes #779Michel Weststratebefore adoptionbc35916
lines 214–216why, one step back214 }215 // Otherwise, produce a copy of the base state.216 return this.produce(base, (draft: Drafted) =>fix: Append to array when key is "-" (#872)Louis DeSciolibefore adoption2afdb1b
lines 217–218why, one step back217 applyPatchesImpl(draft, patches)218 )chore: fix links, fixes #779Michel Weststratebefore adoptionbc35916
lines 219–230why, one step back219 }220}221222export function createProxy<T extends Objectish>(223 value: T,224 parent?: ImmerState225): Drafted<T, ImmerState> {226 // precondition: createProxy should be guarded by isDraftable, so we know we can safely draft227 const draft: Drafted = isMap(value)228 ? getPlugin("MapSet").proxyMap_(value, parent)229 : isSet(value)230 ? getPlugin("MapSet").proxySet_(value, parent)Merge pull request #1028 from immerjs/immer-10Michel Weststratebefore adoption2ef9a42
line 231why, one step back231 : createProxyProxy(value, parent)chore: fix links, fixes #779Michel Weststratebefore adoptionbc35916
lines 232–236why, one step back232233 const scope = parent ? parent.scope_ : getCurrentScope()234 scope.drafts_.push(draft)235 return draft236}