immer.ts
This file
Path
src/immer.ts
286 lines · 7.7 KiB · TypeScript
Last changed by
Further cleanup in progressMichel Weststratebefore adoptionaeba1ff
History of this fileTake it
Stop abusing modules as exportsMichel Weststratebefore adoption7b0ad53
lines 1–2why, one step back1import {createES5Proxy, willFinalizeES5, markChangedES5} from "./es5"2import {createProxy, markChanged} from "./proxy"basic map tests succeedingMichel Weststratebefore adoption735c402
line 3why, one step back3Merge branch 'master' into map-fixesMichel Weststratebefore adoptioncb63fb0
lines 4–17why, one step back4import {applyPatches, generatePatches} from "./patches"5import {6 each,7 has,8 is,9 isDraft,10 isSet,11 get,12 isMap,13 isDraftable,14 isEnumerable,15 shallowCopy,16 DRAFT_STATE,17 NOTHING,basic map tests succeedingMichel Weststratebefore adoption735c402
line 18why, one step back18 freeze,clean up create proxyMichel Weststratebefore adoptionc182c1e
lines 19–20why, one step back19 isPlainObject,20 DRAFTABLEMerge branch 'master' into map-fixesMichel Weststratebefore adoptioncb63fb0
lines 21–22why, one step back21} from "./common"22import {ImmerScope} from "./scope"Stop abusing modules as exportsMichel Weststratebefore adoption7b0ad53
lines 23–29why, one step back23import {24 ImmerState,25 IProduce,26 IProduceWithPatches,27 Objectish,28 PatchListener,29 Draft,clean up create proxyMichel Weststratebefore adoptionc182c1e
lines 30–31why, one step back30 Patch,31 DraftedStop abusing modules as exportsMichel Weststratebefore adoption7b0ad53
line 32why, one step back32} from "./types"clean up create proxyMichel Weststratebefore adoptionc182c1e
line 33why, one step back33import {proxyMap} from "./map"Further cleanup in progressMichel Weststratebefore adoptionaeba1ff
lines 34–35why, one step back34import {proxySet, SetState} from "./set"35import {processResult, maybeFreeze} from "./finalize"Merge branch 'master' into map-fixesMichel Weststratebefore adoptioncb63fb0
lines 36–60why, one step back3637function verifyMinified() {}3839const configDefaults = {40 useProxies:41 typeof Proxy !== "undefined" &&42 typeof Proxy.revocable !== "undefined" &&43 typeof Reflect !== "undefined",44 autoFreeze:45 typeof process !== "undefined"46 ? process.env.NODE_ENV !== "production"47 : verifyMinified.name === "verifyMinified",48 onAssign: null,49 onDelete: null,50 onCopy: null51}5253interface ProducersFns {54 produce: IProduce55 produceWithPatches: IProduceWithPatches56}5758export class Immer implements ProducersFns {59 useProxies: boolean = false60 autoFreeze: boolean = falseStop abusing modules as exportsMichel Weststratebefore adoption7b0ad53
line 61why, one step back61 onAssign?: (state: ImmerState, prop: string | number, value: unknown) => voidMerge branch 'master' into map-fixesMichel Weststratebefore adoptioncb63fb0
lines 62–75why, one step back62 onDelete?: (state: ImmerState, prop: string | number) => void63 onCopy?: (state: ImmerState) => void6465 constructor(config?: {66 useProxies?: boolean67 autoFreeze?: boolean68 onAssign?: (69 state: ImmerState,70 prop: string | number,71 value: unknown72 ) => void73 onDelete?: (state: ImmerState, prop: string | number) => void74 onCopy?: (state: ImmerState) => void75 }) {Dropped Object.assignMichel Weststratebefore adoption79a1d2c
lines 76–82why, one step back76 each(configDefaults, (key, value) => {77 this[key] = value78 })79 config &&80 each(config, (key, value) => {81 this[key] = value82 })Merge branch 'master' into map-fixesMichel Weststratebefore adoptioncb63fb0
lines 83–132why, one step back83 this.setUseProxies(this.useProxies)84 this.produce = this.produce.bind(this)85 this.produceWithPatches = this.produceWithPatches.bind(this)86 }8788 /**89 * The `produce` function takes a value and a "recipe function" (whose90 * return value often depends on the base state). The recipe function is91 * free to mutate its first argument however it wants. All mutations are92 * only ever applied to a __copy__ of the base state.93 *94 * Pass only a function to create a "curried producer" which relieves you95 * from passing the recipe function every time.96 *97 * Only plain objects and arrays are made mutable. All other objects are98 * considered uncopyable.99 *100 * Note: This function is __bound__ to its `Immer` instance.101 *102 * @param {any} base - the initial state103 * @param {Function} producer - function that receives a proxy of the base state as first argument and which can be freely modified104 * @param {Function} patchListener - optional function that will be called with all the patches produced here105 * @returns {any} a new state, or the initial state if nothing was modified106 */107 produce(base, recipe?, patchListener?) {108 // curried invocation109 if (typeof base === "function" && typeof recipe !== "function") {110 const defaultBase = recipe111 recipe = base112113 const self = this114 return function curriedProduce(this: any, base = defaultBase, ...args) {115 return self.produce(base, draft => recipe.call(this, draft, ...args)) // prettier-ignore116 }117 }118119 // prettier-ignore120 {121 if (typeof recipe !== "function") {122 throw new Error("The first or second argument to `produce` must be a function")123 }124 if (patchListener !== undefined && typeof patchListener !== "function") {125 throw new Error("The third argument to `produce` must be a function or undefined")126 }127 }128129 let result130131 // Only plain objects, arrays, and "immerable classes" are drafted.132 if (isDraftable(base)) {map unification WIPMichel Weststratebefore adoption9bcefb6
lines 133–134why, one step back133 const scope = ImmerScope.enter(this)134 const proxy = this.createProxy(base, undefined)Merge branch 'master' into map-fixesMichel Weststratebefore adoptioncb63fb0
lines 135–147why, one step back135 let hasError = true136 try {137 result = recipe(proxy)138 hasError = false139 } finally {140 // finally instead of catch + rethrow better preserves original stack141 if (hasError) scope.revoke()142 else scope.leave()143 }144 if (typeof Promise !== "undefined" && result instanceof Promise) {145 return result.then(146 result => {147 scope.usePatches(patchListener)Further cleanup in progressMichel Weststratebefore adoptionaeba1ff
line 148why, one step back148 return processResult(this, result, scope)Merge branch 'master' into map-fixesMichel Weststratebefore adoptioncb63fb0
lines 149–156why, one step back149 },150 error => {151 scope.revoke()152 throw error153 }154 )155 }156 scope.usePatches(patchListener)Further cleanup in progressMichel Weststratebefore adoptionaeba1ff
line 157why, one step back157 return processResult(this, result, scope)Merge branch 'master' into map-fixesMichel Weststratebefore adoptioncb63fb0
lines 158–161why, one step back158 } else {159 result = recipe(base)160 if (result === NOTHING) return undefined161 if (result === undefined) result = baseFurther cleanup in progressMichel Weststratebefore adoptionaeba1ff
line 162why, one step back162 maybeFreeze(this, result, true)Merge branch 'master' into map-fixesMichel Weststratebefore adoptioncb63fb0
lines 163–187why, one step back163 return result164 }165 }166167 produceWithPatches(arg1, arg2?, arg3?): any {168 if (typeof arg1 === "function") {169 const self = this170 return (state, ...args) =>171 this.produceWithPatches(state, draft => arg1(draft, ...args))172 }173 // non-curried form174 if (arg3)175 throw new Error("A patch listener cannot be passed to produceWithPatches")176 let patches, inversePatches177 const nextState = this.produce(arg1, arg2, (p, ip) => {178 patches = p179 inversePatches = ip180 })181 return [nextState, patches, inversePatches]182 }183184 createDraft<T extends Objectish>(base: T): Draft<T> {185 if (!isDraftable(base)) {186 throw new Error("First argument to `createDraft` must be a plain object, an array, or an immerable object") // prettier-ignore187 }map unification WIPMichel Weststratebefore adoption9bcefb6
lines 188–189why, one step back188 const scope = ImmerScope.enter(this)189 const proxy = this.createProxy(base, undefined)Merge branch 'master' into map-fixesMichel Weststratebefore adoptioncb63fb0
lines 190–191why, one step back190 proxy[DRAFT_STATE].isManual = true191 scope.leave()Further cleanup in progressMichel Weststratebefore adoptionaeba1ff
line 192why, one step back192 return proxyMerge branch 'master' into map-fixesMichel Weststratebefore adoptioncb63fb0
lines 193–194why, one step back193 }194Stop abusing modules as exportsMichel Weststratebefore adoption7b0ad53
lines 195–198why, one step back195 finishDraft<D extends Draft<any>>(196 draft: D,197 patchListener: PatchListener198 ): D extends Draft<infer T> ? T : never {Merge branch 'master' into map-fixesMichel Weststratebefore adoptioncb63fb0
lines 199–207why, one step back199 const state = draft && draft[DRAFT_STATE]200 if (!state || !state.isManual) {201 throw new Error("First argument to `finishDraft` must be a draft returned by `createDraft`") // prettier-ignore202 }203 if (state.finalized) {204 throw new Error("The given draft is already finalized") // prettier-ignore205 }206 const {scope} = state207 scope.usePatches(patchListener)Further cleanup in progressMichel Weststratebefore adoptionaeba1ff
line 208why, one step back208 return processResult(this, undefined, scope)Merge branch 'master' into map-fixesMichel Weststratebefore adoptioncb63fb0
lines 209–251why, one step back209 }210211 /**212 * Pass true to automatically freeze all copies created by Immer.213 *214 * By default, auto-freezing is disabled in production.215 */216 setAutoFreeze(value: boolean) {217 this.autoFreeze = value218 }219220 /**221 * Pass true to use the ES2015 `Proxy` class when creating drafts, which is222 * always faster than using ES5 proxies.223 *224 * By default, feature detection is used, so calling this is rarely necessary.225 */226 setUseProxies(value: boolean) {227 this.useProxies = value228 }229230 applyPatches(base: Objectish, patches: Patch[]) {231 // If a patch replaces the entire state, take that replacement as base232 // before applying patches233 let i234 for (i = patches.length - 1; i >= 0; i--) {235 const patch = patches[i]236 if (patch.path.length === 0 && patch.op === "replace") {237 base = patch.value238 break239 }240 }241242 if (isDraft(base)) {243 // N.B: never hits if some patch a replacement, patches are never drafts244 return applyPatches(base, patches)245 }246 // Otherwise, produce a copy of the base state.247 return this.produce(base, draft =>248 applyPatches(draft, patches.slice(i + 1))249 )250 }251clean up create proxyMichel Weststratebefore adoptionc182c1e
lines 252–272why, one step back252 createProxy<T>(value: any, parent?: ImmerState) {253 if (!value || typeof value !== "object") return value254255 let draft: Drafted256257 if (258 isPlainObject(value) ||259 Array.isArray(value) ||260 value[DRAFTABLE] ||261 value?.constructor?.[DRAFTABLE]262 ) {263 draft = this.useProxies264 ? createProxy(value, parent)265 : createES5Proxy(value, parent)266 } else if (isMap(value)) draft = proxyMap(value, parent)267 else if (isSet(value)) draft = proxySet(value, parent)268 else return value269270 const scope = parent ? parent.scope : ImmerScope.current!271 scope.drafts.push(draft)272 return draftStop abusing modules as exportsMichel Weststratebefore adoption7b0ad53
lines 273–284why, one step back273 }274275 willFinalize(scope: ImmerScope, thing: any, isReplaced: boolean) {276 if (!this.useProxies) willFinalizeES5(scope, thing, isReplaced)277 }278279 markChanged(state: any) {280 if (this.useProxies) {281 markChanged(state)282 } else {283 markChangedES5(state)284 }Merge branch 'master' into map-fixesMichel Weststratebefore adoptioncb63fb0
lines 285–286why, one step back285 }286}