immerClass.ts
This file
Path
src/immerClass.ts
276 lines · 7.5 KiB · TypeScript
Last changed by
Mangle properties, -114 bytesMichel Weststratebefore adoptionbfa7ddd
History of this fileTake it
More WIPMichel Weststratebefore adoptionee1c977
lines 1–29why, one step back1import {2 createES5Proxy,3 willFinalizeES5,4 markChangedES5,5 IProduceWithPatches,6 IProduce,7 ImmerState,8 each,9 Drafted,10 isDraftable,11 ImmerScope,12 processResult,13 NOTHING,14 maybeFreeze,15 die,16 Patch,17 Objectish,18 DRAFT_STATE,19 Draft,20 PatchListener,21 isDraft,22 applyPatches,23 isMap,24 proxyMap,25 isSet,26 proxySet,27 markChangedProxy,28 createProxyProxy29} from "./internal"use invariant -321 bytesMichel Weststratebefore adoptionac57da5
line 30why, one step back30import invariant from "tiny-invariant"More WIPMichel Weststratebefore adoptionee1c977
line 31why, one step back31New build set. Current statsMichel Weststratebefore adoption9aec0fe
line 32why, one step back32declare const __DEV__: booleanMore WIPMichel Weststratebefore adoptionee1c977
lines 33–40why, one step back33/* istanbul ignore next */34function verifyMinified() {}3536const configDefaults = {37 useProxies:38 typeof Proxy !== "undefined" &&39 typeof Proxy.revocable !== "undefined" &&40 typeof Reflect !== "undefined",New build set. Current statsMichel Weststratebefore adoption9aec0fe
lines 41–43why, one step back41 autoFreeze: __DEV__42 ? false /* istanbul ignore next */43 : verifyMinified.name === "verifyMinified",More WIPMichel Weststratebefore adoptionee1c977
lines 44–115why, one step back44 onAssign: null,45 onDelete: null,46 onCopy: null47} as const4849interface ProducersFns {50 produce: IProduce51 produceWithPatches: IProduceWithPatches52}5354export class Immer implements ProducersFns {55 useProxies: boolean = false56 autoFreeze: boolean = false57 onAssign?: (state: ImmerState, prop: string | number, value: unknown) => void58 onDelete?: (state: ImmerState, prop: string | number) => void59 onCopy?: (state: ImmerState) => void6061 constructor(config?: {62 useProxies?: boolean63 autoFreeze?: boolean64 onAssign?: (65 state: ImmerState,66 prop: string | number,67 value: unknown68 ) => void69 onDelete?: (state: ImmerState, prop: string | number) => void70 onCopy?: (state: ImmerState) => void71 }) {72 each(configDefaults, (key, value) => {73 // @ts-ignore74 this[key] = config?.[key] ?? value75 })76 this.setUseProxies(this.useProxies)77 this.produce = this.produce.bind(this)78 this.produceWithPatches = this.produceWithPatches.bind(this)79 }8081 /**82 * The `produce` function takes a value and a "recipe function" (whose83 * return value often depends on the base state). The recipe function is84 * free to mutate its first argument however it wants. All mutations are85 * only ever applied to a __copy__ of the base state.86 *87 * Pass only a function to create a "curried producer" which relieves you88 * from passing the recipe function every time.89 *90 * Only plain objects and arrays are made mutable. All other objects are91 * considered uncopyable.92 *93 * Note: This function is __bound__ to its `Immer` instance.94 *95 * @param {any} base - the initial state96 * @param {Function} producer - function that receives a proxy of the base state as first argument and which can be freely modified97 * @param {Function} patchListener - optional function that will be called with all the patches produced here98 * @returns {any} a new state, or the initial state if nothing was modified99 */100 produce(base: any, recipe?: any, patchListener?: any) {101 // curried invocation102 if (typeof base === "function" && typeof recipe !== "function") {103 const defaultBase = recipe104 recipe = base105106 const self = this107 return function curriedProduce(108 this: any,109 base = defaultBase,110 ...args: any[]111 ) {112 return self.produce(base, (draft: Drafted) => recipe.call(this, draft, ...args)) // prettier-ignore113 }114 }115use invariant -321 bytesMichel Weststratebefore adoptionac57da5
lines 116–123why, one step back116 invariant(117 typeof recipe === "function",118 "The first or second argument to `produce` must be a function"119 )120 invariant(121 patchListener === undefined || typeof patchListener === "function",122 "The third argument to `produce` must be a function or undefined"123 )More WIPMichel Weststratebefore adoptionee1c977
lines 124–128why, one step back124125 let result126127 // Only plain objects, arrays, and "immerable classes" are drafted.128 if (isDraftable(base)) {Mangle properties, -114 bytesMichel Weststratebefore adoptionbfa7ddd
line 129why, one step back129 const scope = ImmerScope.enter_(this)More WIPMichel Weststratebefore adoptionee1c977
lines 130–136why, one step back130 const proxy = createProxy(this, base, undefined)131 let hasError = true132 try {133 result = recipe(proxy)134 hasError = false135 } finally {136 // finally instead of catch + rethrow better preserves original stackMangle properties, -114 bytesMichel Weststratebefore adoptionbfa7ddd
lines 137–138why, one step back137 if (hasError) scope.revoke_()138 else scope.leave_()More WIPMichel Weststratebefore adoptionee1c977
lines 139–142why, one step back139 }140 if (typeof Promise !== "undefined" && result instanceof Promise) {141 return result.then(142 result => {Mangle properties, -114 bytesMichel Weststratebefore adoptionbfa7ddd
line 143why, one step back143 scope.usePatches_(patchListener)More WIPMichel Weststratebefore adoptionee1c977
lines 144–146why, one step back144 return processResult(this, result, scope)145 },146 error => {Mangle properties, -114 bytesMichel Weststratebefore adoptionbfa7ddd
line 147why, one step back147 scope.revoke_()More WIPMichel Weststratebefore adoptionee1c977
lines 148–151why, one step back148 throw error149 }150 )151 }Mangle properties, -114 bytesMichel Weststratebefore adoptionbfa7ddd
line 152why, one step back152 scope.usePatches_(patchListener)More WIPMichel Weststratebefore adoptionee1c977
lines 153–179why, one step back153 return processResult(this, result, scope)154 } else {155 result = recipe(base)156 if (result === NOTHING) return undefined157 if (result === undefined) result = base158 maybeFreeze(this, result, true)159 return result160 }161 }162163 produceWithPatches(arg1: any, arg2?: any, arg3?: any): any {164 if (typeof arg1 === "function") {165 return (state: any, ...args: any[]) =>166 this.produceWithPatches(state, (draft: any) => arg1(draft, ...args))167 }168 // non-curried form169 /* istanbul ignore next */170 if (arg3) die()171 let patches: Patch[], inversePatches: Patch[]172 const nextState = this.produce(arg1, arg2, (p: Patch[], ip: Patch[]) => {173 patches = p174 inversePatches = ip175 })176 return [nextState, patches!, inversePatches!]177 }178179 createDraft<T extends Objectish>(base: T): Draft<T> {use invariant -321 bytesMichel Weststratebefore adoptionac57da5
line 180why, one step back180 invariant(isDraftable(base), "First argument to `createDraft` must be a plain object, an array, or an immerable object") // prettier-ignoreMangle properties, -114 bytesMichel Weststratebefore adoptionbfa7ddd
line 181why, one step back181 const scope = ImmerScope.enter_(this)More WIPMichel Weststratebefore adoptionee1c977
line 182why, one step back182 const proxy = createProxy(this, base, undefined)Mangle properties, -114 bytesMichel Weststratebefore adoptionbfa7ddd
lines 183–184why, one step back183 proxy[DRAFT_STATE].isManual_ = true184 scope.leave_()More WIPMichel Weststratebefore adoptionee1c977
lines 185–192why, one step back185 return proxy as any186 }187188 finishDraft<D extends Draft<any>>(189 draft: D,190 patchListener?: PatchListener191 ): D extends Draft<infer T> ? T : never {192 const state: ImmerState = draft && draft[DRAFT_STATE]Mangle properties, -114 bytesMichel Weststratebefore adoptionbfa7ddd
lines 193–196why, one step back193 invariant(state && state.isManual_, "First argument to `finishDraft` must be a draft returned by `createDraft`") // prettier-ignore194 invariant(!state.finalized_, "The given draft is already finalized") // prettier-ignore195 const {scope_: scope} = state196 scope.usePatches_(patchListener)More WIPMichel Weststratebefore adoptionee1c977
lines 197–255why, one step back197 return processResult(this, undefined, scope)198 }199200 /**201 * Pass true to automatically freeze all copies created by Immer.202 *203 * By default, auto-freezing is disabled in production.204 */205 setAutoFreeze(value: boolean) {206 this.autoFreeze = value207 }208209 /**210 * Pass true to use the ES2015 `Proxy` class when creating drafts, which is211 * always faster than using ES5 proxies.212 *213 * By default, feature detection is used, so calling this is rarely necessary.214 */215 setUseProxies(value: boolean) {216 this.useProxies = value217 }218219 applyPatches(base: Objectish, patches: Patch[]) {220 // If a patch replaces the entire state, take that replacement as base221 // before applying patches222 let i: number223 for (i = patches.length - 1; i >= 0; i--) {224 const patch = patches[i]225 if (patch.path.length === 0 && patch.op === "replace") {226 base = patch.value227 break228 }229 }230231 if (isDraft(base)) {232 // N.B: never hits if some patch a replacement, patches are never drafts233 return applyPatches(base, patches)234 }235 // Otherwise, produce a copy of the base state.236 return this.produce(base, (draft: Drafted) =>237 applyPatches(draft, patches.slice(i + 1))238 )239 }240}241242export function createProxy<T extends Objectish>(243 immer: Immer,244 value: T,245 parent?: ImmerState246): Drafted<T, ImmerState> {247 // precondition: createProxy should be guarded by isDraftable, so we know we can safely draft248 const draft: Drafted = isMap(value)249 ? proxyMap(value, parent)250 : isSet(value)251 ? proxySet(value, parent)252 : immer.useProxies253 ? createProxyProxy(value, parent)254 : createES5Proxy(value, parent)255Mangle properties, -114 bytesMichel Weststratebefore adoptionbfa7ddd
lines 256–257why, one step back256 const scope = parent ? parent.scope_ : ImmerScope.current_!257 scope.drafts_.push(draft)More WIPMichel Weststratebefore adoptionee1c977
lines 258–276why, one step back258 return draft259}260261export function willFinalize(262 immer: Immer,263 scope: ImmerScope,264 thing: any,265 isReplaced: boolean266) {267 if (!immer.useProxies) willFinalizeES5(scope, thing, isReplaced)268}269270export function markChanged(immer: Immer, state: ImmerState) {271 if (immer.useProxies) {272 markChangedProxy(state)273 } else {274 markChangedES5(state)275 }276}