Skip to content
Myr

immerClass.ts

This file

Path

src/immerClass.ts

283 lines · 7.6 KiB · TypeScript

Last changed by

More WIPMichel Weststratebefore adoptionee1c977

History of this file

Take it

More WIPMichel Weststratebefore adoptionee1c977

lines 1–283why, 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"3031/* istanbul ignore next */32function verifyMinified() {}3334const configDefaults = {35 useProxies:36 typeof Proxy !== "undefined" &&37 typeof Proxy.revocable !== "undefined" &&38 typeof Reflect !== "undefined",39 autoFreeze:40 typeof process !== "undefined"41 ? process.env.NODE_ENV !== "production"42 : /* istanbul ignore next */43 verifyMinified.name === "verifyMinified",44 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 }115116 // prettier-ignore117 {118 if (typeof recipe !== "function") {119 throw new Error("The first or second argument to `produce` must be a function")120 }121 if (patchListener !== undefined && typeof patchListener !== "function") {122 throw new Error("The third argument to `produce` must be a function or undefined")123 }124 }125126 let result127128 // Only plain objects, arrays, and "immerable classes" are drafted.129 if (isDraftable(base)) {130 const scope = ImmerScope.enter(this)131 const proxy = createProxy(this, base, undefined)132 let hasError = true133 try {134 result = recipe(proxy)135 hasError = false136 } finally {137 // finally instead of catch + rethrow better preserves original stack138 if (hasError) scope.revoke()139 else scope.leave()140 }141 if (typeof Promise !== "undefined" && result instanceof Promise) {142 return result.then(143 result => {144 scope.usePatches(patchListener)145 return processResult(this, result, scope)146 },147 error => {148 scope.revoke()149 throw error150 }151 )152 }153 scope.usePatches(patchListener)154 return processResult(this, result, scope)155 } else {156 result = recipe(base)157 if (result === NOTHING) return undefined158 if (result === undefined) result = base159 maybeFreeze(this, result, true)160 return result161 }162 }163164 produceWithPatches(arg1: any, arg2?: any, arg3?: any): any {165 if (typeof arg1 === "function") {166 return (state: any, ...args: any[]) =>167 this.produceWithPatches(state, (draft: any) => arg1(draft, ...args))168 }169 // non-curried form170 /* istanbul ignore next */171 if (arg3) die()172 let patches: Patch[], inversePatches: Patch[]173 const nextState = this.produce(arg1, arg2, (p: Patch[], ip: Patch[]) => {174 patches = p175 inversePatches = ip176 })177 return [nextState, patches!, inversePatches!]178 }179180 createDraft<T extends Objectish>(base: T): Draft<T> {181 if (!isDraftable(base)) {182 throw new Error("First argument to `createDraft` must be a plain object, an array, or an immerable object") // prettier-ignore183 }184 const scope = ImmerScope.enter(this)185 const proxy = createProxy(this, base, undefined)186 proxy[DRAFT_STATE].isManual = true187 scope.leave()188 return proxy as any189 }190191 finishDraft<D extends Draft<any>>(192 draft: D,193 patchListener?: PatchListener194 ): D extends Draft<infer T> ? T : never {195 const state: ImmerState = draft && draft[DRAFT_STATE]196 if (!state || !state.isManual) {197 throw new Error("First argument to `finishDraft` must be a draft returned by `createDraft`") // prettier-ignore198 }199 if (state.finalized) {200 throw new Error("The given draft is already finalized") // prettier-ignore201 }202 const {scope} = state203 scope.usePatches(patchListener)204 return processResult(this, undefined, scope)205 }206207 /**208 * Pass true to automatically freeze all copies created by Immer.209 *210 * By default, auto-freezing is disabled in production.211 */212 setAutoFreeze(value: boolean) {213 this.autoFreeze = value214 }215216 /**217 * Pass true to use the ES2015 `Proxy` class when creating drafts, which is218 * always faster than using ES5 proxies.219 *220 * By default, feature detection is used, so calling this is rarely necessary.221 */222 setUseProxies(value: boolean) {223 this.useProxies = value224 }225226 applyPatches(base: Objectish, patches: Patch[]) {227 // If a patch replaces the entire state, take that replacement as base228 // before applying patches229 let i: number230 for (i = patches.length - 1; i >= 0; i--) {231 const patch = patches[i]232 if (patch.path.length === 0 && patch.op === "replace") {233 base = patch.value234 break235 }236 }237238 if (isDraft(base)) {239 // N.B: never hits if some patch a replacement, patches are never drafts240 return applyPatches(base, patches)241 }242 // Otherwise, produce a copy of the base state.243 return this.produce(base, (draft: Drafted) =>244 applyPatches(draft, patches.slice(i + 1))245 )246 }247}248249export function createProxy<T extends Objectish>(250 immer: Immer,251 value: T,252 parent?: ImmerState253): Drafted<T, ImmerState> {254 // precondition: createProxy should be guarded by isDraftable, so we know we can safely draft255 const draft: Drafted = isMap(value)256 ? proxyMap(value, parent)257 : isSet(value)258 ? proxySet(value, parent)259 : immer.useProxies260 ? createProxyProxy(value, parent)261 : createES5Proxy(value, parent)262263 const scope = parent ? parent.scope : ImmerScope.current!264 scope.drafts.push(draft)265 return draft266}267268export function willFinalize(269 immer: Immer,270 scope: ImmerScope,271 thing: any,272 isReplaced: boolean273) {274 if (!immer.useProxies) willFinalizeES5(scope, thing, isReplaced)275}276277export function markChanged(immer: Immer, state: ImmerState) {278 if (immer.useProxies) {279 markChangedProxy(state)280 } else {281 markChangedES5(state)282 }283}