immerClass.ts
This file
Path
src/core/immerClass.ts
213 lines · 6.1 KiB · TypeScript
Last changed by
Merge pull request #1028 from immerjs/immer-10Michel Weststratebefore adoption2ef9a42
History of this fileTake it
The walk stopped after 200 commits: lines older than f97d037 point at it.
docs: updated sponsor linksMichel Weststratebefore adoptionf97d037
lines 1–34why, 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}3334export class Immer implements ProducersFns {feature: Always freeze by default (#702)Michel Weststratebefore adoptiona406c8f
line 35why, one step back35 autoFreeze_: boolean = trueMerge pull request #1028 from immerjs/immer-10Michel Weststratebefore adoption2ef9a42
line 36why, one step back36 useStrictShallowCopy_: boolean = falsedocs: updated sponsor linksMichel Weststratebefore adoptionf97d037
line 37why, one step back37Merge pull request #1028 from immerjs/immer-10Michel Weststratebefore adoption2ef9a42
line 38why, one step back38 constructor(config?: {autoFreeze?: boolean; useStrictShallowCopy?: boolean}) {docs: updated sponsor linksMichel Weststratebefore adoptionf97d037
lines 39–40why, one step back39 if (typeof config?.autoFreeze === "boolean")40 this.setAutoFreeze(config!.autoFreeze)Merge pull request #1028 from immerjs/immer-10Michel Weststratebefore adoption2ef9a42
lines 41–42why, one step back41 if (typeof config?.useStrictShallowCopy === "boolean")42 this.setUseStrictShallowCopy(config!.useStrictShallowCopy)docs: updated sponsor linksMichel Weststratebefore adoptionf97d037
lines 43–59why, one step back43 }4445 /**46 * The `produce` function takes a value and a "recipe function" (whose47 * return value often depends on the base state). The recipe function is48 * free to mutate its first argument however it wants. All mutations are49 * only ever applied to a __copy__ of the base state.50 *51 * Pass only a function to create a "curried producer" which relieves you52 * from passing the recipe function every time.53 *54 * Only plain objects and arrays are made mutable. All other objects are55 * considered uncopyable.56 *57 * Note: This function is __bound__ to its `Immer` instance.58 *59 * @param {any} base - the initial statechore: fixed jsdoc parameter name (#994)Christopher Tranbefore adoption8a02d81
line 60why, one step back60 * @param {Function} recipe - function that receives a proxy of the base state as first argument and which can be freely modifieddocs: updated sponsor linksMichel Weststratebefore adoptionf97d037
lines 61–63why, one step back61 * @param {Function} patchListener - optional function that will be called with all the patches produced here62 * @returns {any} a new state, or the initial state if nothing was modified63 */fix: new Immer().produce now has the same type as produce. Fixes #749Michel Weststratebefore adoptionf8b77d1
line 64why, one step back64 produce: IProduce = (base: any, recipe?: any, patchListener?: any) => {docs: updated sponsor linksMichel Weststratebefore adoptionf97d037
lines 65–88why, one step back65 // curried invocation66 if (typeof base === "function" && typeof recipe !== "function") {67 const defaultBase = recipe68 recipe = base6970 const self = this71 return function curriedProduce(72 this: any,73 base = defaultBase,74 ...args: any[]75 ) {76 return self.produce(base, (draft: Drafted) => recipe.call(this, draft, ...args)) // prettier-ignore77 }78 }7980 if (typeof recipe !== "function") die(6)81 if (patchListener !== undefined && typeof patchListener !== "function")82 die(7)8384 let result8586 // Only plain objects, arrays, and "immerable classes" are drafted.87 if (isDraftable(base)) {88 const scope = enterScope(this)Merge pull request #1028 from immerjs/immer-10Michel Weststratebefore adoption2ef9a42
line 89why, one step back89 const proxy = createProxy(base, undefined)docs: updated sponsor linksMichel Weststratebefore adoptionf97d037
lines 90–103why, one step back90 let hasError = true91 try {92 result = recipe(proxy)93 hasError = false94 } finally {95 // finally instead of catch + rethrow better preserves original stack96 if (hasError) revokeScope(scope)97 else leaveScope(scope)98 }99 usePatchesInScope(scope, patchListener)100 return processResult(result, scope)101 } else if (!base || typeof base !== "object") {102 result = recipe(base)103 if (result === undefined) result = basefix: No patches being generated for root primitive replacements. Fixes #888Michel Weststratebefore adoption0f96270
line 104why, one step back104 if (result === NOTHING) result = undefineddocs: updated sponsor linksMichel Weststratebefore adoptionf97d037
line 105why, one step back105 if (this.autoFreeze_) freeze(result, true)fix: No patches being generated for root primitive replacements. Fixes #888Michel Weststratebefore adoption0f96270
lines 106–111why, one step back106 if (patchListener) {107 const p: Patch[] = []108 const ip: Patch[] = []109 getPlugin("Patches").generateReplacementPatches_(base, result, p, ip)110 patchListener(p, ip)111 }docs: updated sponsor linksMichel Weststratebefore adoptionf97d037
line 112why, one step back112 return resultMerge pull request #1028 from immerjs/immer-10Michel Weststratebefore adoption2ef9a42
line 113why, one step back113 } else die(1, base)docs: updated sponsor linksMichel Weststratebefore adoptionf97d037
lines 114–115why, one step back114 }115chore: fixed jsdoc parameter name (#994)Christopher Tranbefore adoption8a02d81
line 116why, one step back116 produceWithPatches: IProduceWithPatches = (base: any, recipe?: any): any => {chore: remove unused arg3 in produceWithPatches (#975)Brian Hungbefore adoption078e523
lines 117–118why, one step back117 // curried invocation118 if (typeof base === "function") {docs: updated sponsor linksMichel Weststratebefore adoptionf97d037
line 119why, one step back119 return (state: any, ...args: any[]) =>chore: remove unused arg3 in produceWithPatches (#975)Brian Hungbefore adoption078e523
line 120why, one step back120 this.produceWithPatches(state, (draft: any) => base(draft, ...args))docs: updated sponsor linksMichel Weststratebefore adoptionf97d037
lines 121–123why, one step back121 }122123 let patches: Patch[], inversePatches: Patch[]chore: remove unused arg3 in produceWithPatches (#975)Brian Hungbefore adoption078e523
line 124why, one step back124 const result = this.produce(base, recipe, (p: Patch[], ip: Patch[]) => {docs: updated sponsor linksMichel Weststratebefore adoptionf97d037
lines 125–127why, one step back125 patches = p126 inversePatches = ip127 })fix: make sure produceWithPatches accepts promisescviejobefore adoptiond80e823
line 128why, one step back128 return [result, patches!, inversePatches!]docs: updated sponsor linksMichel Weststratebefore adoptionf97d037
lines 129–134why, one step back129 }130131 createDraft<T extends Objectish>(base: T): Draft<T> {132 if (!isDraftable(base)) die(8)133 if (isDraft(base)) base = current(base)134 const scope = enterScope(this)Merge pull request #1028 from immerjs/immer-10Michel Weststratebefore adoption2ef9a42
line 135why, one step back135 const proxy = createProxy(base, undefined)docs: updated sponsor linksMichel Weststratebefore adoptionf97d037
lines 136–145why, one step back136 proxy[DRAFT_STATE].isManual_ = true137 leaveScope(scope)138 return proxy as any139 }140141 finishDraft<D extends Draft<any>>(142 draft: D,143 patchListener?: PatchListener144 ): D extends Draft<infer T> ? T : never {145 const state: ImmerState = draft && (draft as any)[DRAFT_STATE]Merge pull request #1028 from immerjs/immer-10Michel Weststratebefore adoption2ef9a42
line 146why, one step back146 if (!state || !state.isManual_) die(9)docs: updated sponsor linksMichel Weststratebefore adoptionf97d037
lines 147–154why, one step back147 const {scope_: scope} = state148 usePatchesInScope(scope, patchListener)149 return processResult(undefined, scope)150 }151152 /**153 * Pass true to automatically freeze all copies created by Immer.154 *docs: some refinements on freezingMichel Weststratebefore adoption7faa7b4
line 155why, one step back155 * By default, auto-freezing is enabled.docs: updated sponsor linksMichel Weststratebefore adoptionf97d037
lines 156–161why, one step back156 */157 setAutoFreeze(value: boolean) {158 this.autoFreeze_ = value159 }160161 /**Merge pull request #1028 from immerjs/immer-10Michel Weststratebefore adoption2ef9a42
line 162why, one step back162 * Pass true to enable strict shallow copy.docs: updated sponsor linksMichel Weststratebefore adoptionf97d037
line 163why, one step back163 *Merge pull request #1028 from immerjs/immer-10Michel Weststratebefore adoption2ef9a42
line 164why, one step back164 * By default, immer does not copy the object descriptors such as getter, setter and non-enumrable properties.docs: updated sponsor linksMichel Weststratebefore adoptionf97d037
line 165why, one step back165 */Merge pull request #1028 from immerjs/immer-10Michel Weststratebefore adoption2ef9a42
lines 166–167why, one step back166 setUseStrictShallowCopy(value: boolean) {167 this.useStrictShallowCopy_ = valuedocs: updated sponsor linksMichel Weststratebefore adoptionf97d037
lines 168–169why, one step back168 }169fix: Better applyPatches type (#810)Josh Kelleybefore adoption09ac097
line 170why, one step back170 applyPatches<T extends Objectish>(base: T, patches: Patch[]): T {docs: updated sponsor linksMichel Weststratebefore adoptionf97d037
lines 171–180why, one step back171 // If a patch replaces the entire state, take that replacement as base172 // before applying patches173 let i: number174 for (i = patches.length - 1; i >= 0; i--) {175 const patch = patches[i]176 if (patch.path.length === 0 && patch.op === "replace") {177 base = patch.value178 break179 }180 }fix: Append to array when key is "-" (#872)Louis DeSciolibefore adoption2afdb1b
lines 181–185why, one step back181 // If there was a patch that replaced the entire state, start from the182 // patch after that.183 if (i > -1) {184 patches = patches.slice(i + 1)185 }docs: updated sponsor linksMichel Weststratebefore adoptionf97d037
lines 186–189why, one step back186187 const applyPatchesImpl = getPlugin("Patches").applyPatches_188 if (isDraft(base)) {189 // N.B: never hits if some patch a replacement, patches are never draftsfix: Append to array when key is "-" (#872)Louis DeSciolibefore adoption2afdb1b
line 190why, one step back190 return applyPatchesImpl(base, patches)docs: updated sponsor linksMichel Weststratebefore adoptionf97d037
lines 191–193why, one step back191 }192 // Otherwise, produce a copy of the base state.193 return this.produce(base, (draft: Drafted) =>fix: Append to array when key is "-" (#872)Louis DeSciolibefore adoption2afdb1b
lines 194–195why, one step back194 applyPatchesImpl(draft, patches)195 )docs: updated sponsor linksMichel Weststratebefore adoptionf97d037
lines 196–207why, one step back196 }197}198199export function createProxy<T extends Objectish>(200 value: T,201 parent?: ImmerState202): Drafted<T, ImmerState> {203 // precondition: createProxy should be guarded by isDraftable, so we know we can safely draft204 const draft: Drafted = isMap(value)205 ? getPlugin("MapSet").proxyMap_(value, parent)206 : isSet(value)207 ? getPlugin("MapSet").proxySet_(value, parent)Merge pull request #1028 from immerjs/immer-10Michel Weststratebefore adoption2ef9a42
line 208why, one step back208 : createProxyProxy(value, parent)docs: updated sponsor linksMichel Weststratebefore adoptionf97d037
lines 209–213why, one step back209210 const scope = parent ? parent.scope_ : getCurrentScope()211 scope.drafts_.push(draft)212 return draft213}