Skip to content
Myr

immerClass.ts

This file

Path

src/immerClass.ts

282 lines · 7.6 KiB · TypeScript

Last changed by

New build set. Current statsMichel Weststratebefore adoption9aec0fe

History of this file

Take it

More WIPMichel Weststratebefore adoptionee1c977

lines 1–30why, one step back
1import {
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"30

New build set. Current statsMichel Weststratebefore adoption9aec0fe

line 31why, one step back
31declare const __DEV__: boolean

More WIPMichel Weststratebefore adoptionee1c977

lines 32–39why, one step back
32/* istanbul ignore next */
33function verifyMinified() {}3435const configDefaults = {36 useProxies:37 typeof Proxy !== "undefined" &&38 typeof Proxy.revocable !== "undefined" &&39 typeof Reflect !== "undefined",

New build set. Current statsMichel Weststratebefore adoption9aec0fe

lines 40–42why, one step back
40 autoFreeze: __DEV__
41 ? false /* istanbul ignore next */42 : verifyMinified.name === "verifyMinified",

More WIPMichel Weststratebefore adoptionee1c977

lines 43–282why, one step back
43 onAssign: null,
44 onDelete: null,45 onCopy: null46} as const4748interface ProducersFns {49 produce: IProduce50 produceWithPatches: IProduceWithPatches51}5253export class Immer implements ProducersFns {54 useProxies: boolean = false55 autoFreeze: boolean = false56 onAssign?: (state: ImmerState, prop: string | number, value: unknown) => void57 onDelete?: (state: ImmerState, prop: string | number) => void58 onCopy?: (state: ImmerState) => void5960 constructor(config?: {61 useProxies?: boolean62 autoFreeze?: boolean63 onAssign?: (64 state: ImmerState,65 prop: string | number,66 value: unknown67 ) => void68 onDelete?: (state: ImmerState, prop: string | number) => void69 onCopy?: (state: ImmerState) => void70 }) {71 each(configDefaults, (key, value) => {72 // @ts-ignore73 this[key] = config?.[key] ?? value74 })75 this.setUseProxies(this.useProxies)76 this.produce = this.produce.bind(this)77 this.produceWithPatches = this.produceWithPatches.bind(this)78 }7980 /**81 * The `produce` function takes a value and a "recipe function" (whose82 * return value often depends on the base state). The recipe function is83 * free to mutate its first argument however it wants. All mutations are84 * only ever applied to a __copy__ of the base state.85 *86 * Pass only a function to create a "curried producer" which relieves you87 * from passing the recipe function every time.88 *89 * Only plain objects and arrays are made mutable. All other objects are90 * considered uncopyable.91 *92 * Note: This function is __bound__ to its `Immer` instance.93 *94 * @param {any} base - the initial state95 * @param {Function} producer - function that receives a proxy of the base state as first argument and which can be freely modified96 * @param {Function} patchListener - optional function that will be called with all the patches produced here97 * @returns {any} a new state, or the initial state if nothing was modified98 */99 produce(base: any, recipe?: any, patchListener?: any) {100 // curried invocation101 if (typeof base === "function" && typeof recipe !== "function") {102 const defaultBase = recipe103 recipe = base104105 const self = this106 return function curriedProduce(107 this: any,108 base = defaultBase,109 ...args: any[]110 ) {111 return self.produce(base, (draft: Drafted) => recipe.call(this, draft, ...args)) // prettier-ignore112 }113 }114115 // prettier-ignore116 {117 if (typeof recipe !== "function") {118 throw new Error("The first or second argument to `produce` must be a function")119 }120 if (patchListener !== undefined && typeof patchListener !== "function") {121 throw new Error("The third argument to `produce` must be a function or undefined")122 }123 }124125 let result126127 // Only plain objects, arrays, and "immerable classes" are drafted.128 if (isDraftable(base)) {129 const scope = ImmerScope.enter(this)130 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 stack137 if (hasError) scope.revoke()138 else scope.leave()139 }140 if (typeof Promise !== "undefined" && result instanceof Promise) {141 return result.then(142 result => {143 scope.usePatches(patchListener)144 return processResult(this, result, scope)145 },146 error => {147 scope.revoke()148 throw error149 }150 )151 }152 scope.usePatches(patchListener)153 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> {180 if (!isDraftable(base)) {181 throw new Error("First argument to `createDraft` must be a plain object, an array, or an immerable object") // prettier-ignore182 }183 const scope = ImmerScope.enter(this)184 const proxy = createProxy(this, base, undefined)185 proxy[DRAFT_STATE].isManual = true186 scope.leave()187 return proxy as any188 }189190 finishDraft<D extends Draft<any>>(191 draft: D,192 patchListener?: PatchListener193 ): D extends Draft<infer T> ? T : never {194 const state: ImmerState = draft && draft[DRAFT_STATE]195 if (!state || !state.isManual) {196 throw new Error("First argument to `finishDraft` must be a draft returned by `createDraft`") // prettier-ignore197 }198 if (state.finalized) {199 throw new Error("The given draft is already finalized") // prettier-ignore200 }201 const {scope} = state202 scope.usePatches(patchListener)203 return processResult(this, undefined, scope)204 }205206 /**207 * Pass true to automatically freeze all copies created by Immer.208 *209 * By default, auto-freezing is disabled in production.210 */211 setAutoFreeze(value: boolean) {212 this.autoFreeze = value213 }214215 /**216 * Pass true to use the ES2015 `Proxy` class when creating drafts, which is217 * always faster than using ES5 proxies.218 *219 * By default, feature detection is used, so calling this is rarely necessary.220 */221 setUseProxies(value: boolean) {222 this.useProxies = value223 }224225 applyPatches(base: Objectish, patches: Patch[]) {226 // If a patch replaces the entire state, take that replacement as base227 // before applying patches228 let i: number229 for (i = patches.length - 1; i >= 0; i--) {230 const patch = patches[i]231 if (patch.path.length === 0 && patch.op === "replace") {232 base = patch.value233 break234 }235 }236237 if (isDraft(base)) {238 // N.B: never hits if some patch a replacement, patches are never drafts239 return applyPatches(base, patches)240 }241 // Otherwise, produce a copy of the base state.242 return this.produce(base, (draft: Drafted) =>243 applyPatches(draft, patches.slice(i + 1))244 )245 }246}247248export function createProxy<T extends Objectish>(249 immer: Immer,250 value: T,251 parent?: ImmerState252): Drafted<T, ImmerState> {253 // precondition: createProxy should be guarded by isDraftable, so we know we can safely draft254 const draft: Drafted = isMap(value)255 ? proxyMap(value, parent)256 : isSet(value)257 ? proxySet(value, parent)258 : immer.useProxies259 ? createProxyProxy(value, parent)260 : createES5Proxy(value, parent)261262 const scope = parent ? parent.scope : ImmerScope.current!263 scope.drafts.push(draft)264 return draft265}266267export function willFinalize(268 immer: Immer,269 scope: ImmerScope,270 thing: any,271 isReplaced: boolean272) {273 if (!immer.useProxies) willFinalizeES5(scope, thing, isReplaced)274}275276export function markChanged(immer: Immer, state: ImmerState) {277 if (immer.useProxies) {278 markChangedProxy(state)279 } else {280 markChangedES5(state)281 }282}