immer.js
This file
Path
src/immer.js
168 lines · 6.0 KiB · JavaScript
Last changed by
feat: add `Immer` classaleclarsonbefore adoptionecd04dc
History of this fileTake it
feat: add `Immer` classaleclarsonbefore adoptionecd04dc
lines 1–13why, one step back1import * as legacyProxy from "./es5"2import * as modernProxy from "./proxy"3import {generatePatches} from "./patches"4import {5 assign,6 each,7 has,8 is,9 isDraft,10 isDraftable,11 shallowCopy,12 DRAFT_STATE,13 NOTHINGMerge remote-tracking branch 'origin/v1.8'Michel Weststratebefore adoption7790417
line 14why, one step back14} from "./common"Renamed `index.js` -> `immer.js`Michel Weststratebefore adoptionc4f5667
line 15why, one step back15feat: add `Immer` classaleclarsonbefore adoptionecd04dc
line 16why, one step back16function verifyMinified() {}Renamed `index.js` -> `immer.js`Michel Weststratebefore adoptionc4f5667
line 17why, one step back17feat: add `Immer` classaleclarsonbefore adoptionecd04dc
lines 18–24why, one step back18const configDefaults = {19 useProxies: typeof Proxy !== "undefined" && typeof Reflect !== "undefined",20 autoFreeze:21 typeof process !== "undefined"22 ? process.env.NODE_ENV !== "production"23 : verifyMinified.name === "verifyMinified"24}Merge pull request #121 from pkerschbaum/feature/initial-state-for-curry-fnMichel Weststratebefore adoption2cb5496
line 25why, one step back25feat: add `Immer` classaleclarsonbefore adoptionecd04dc
lines 26–36why, one step back26export class Immer {27 constructor(config) {28 assign(this, configDefaults, config)29 this.setUseProxies(this.useProxies)30 this.produce = this.produce.bind(this)31 }32 produce(base, recipe, patchListener) {33 // curried invocation34 if (typeof base === "function" && typeof recipe !== "function") {35 const defaultBase = recipe36 recipe = baseMerge pull request #121 from pkerschbaum/feature/initial-state-for-curry-fnMichel Weststratebefore adoption2cb5496
line 37why, one step back37feat: add `Immer` classaleclarsonbefore adoptionecd04dc
lines 38–40why, one step back38 // prettier-ignore39 return (base = defaultBase, ...args) =>40 this.produce(base, draft => recipe.call(draft, draft, ...args))Renamed `index.js` -> `immer.js`Michel Weststratebefore adoptionc4f5667
lines 41–42why, one step back41 }42feat: add `Immer` classaleclarsonbefore adoptionecd04dc
lines 43–47why, one step back43 // prettier-ignore44 {45 if (typeof recipe !== "function") throw new Error("if first argument is not a function, the second argument to produce should be a function")46 if (patchListener !== undefined && typeof patchListener !== "function") throw new Error("the third argument of a producer should not be set or a function")47 }Renamed `index.js` -> `immer.js`Michel Weststratebefore adoptionc4f5667
line 48why, one step back48feat: add `Immer` classaleclarsonbefore adoptionecd04dc
lines 49–66why, one step back49 let result50 // Only create proxies for plain objects/arrays.51 if (!isDraftable(base)) {52 result = recipe(base)53 if (result === undefined) return base54 }55 // See #100, don't nest producers56 else if (isDraft(base)) {57 result = recipe.call(base, base)58 if (result === undefined) return base59 }60 // The given value must be proxied.61 else {62 this.scopes.push([])63 const baseDraft = this.createDraft(base)64 try {65 result = recipe.call(baseDraft, baseDraft)66 this.willFinalize(result, baseDraft, !!patchListener)nit: dedupe some codealeclarsonbefore adoptionc9e1d98
line 67why, one step back67feat: add `Immer` classaleclarsonbefore adoptionecd04dc
lines 68–70why, one step back68 // Never generate patches when no listener exists.69 var patches = patchListener && [],70 inversePatches = patchListener && []Merge pull request #157 from stefanwille/fix-148-default-returned-valueMichel Weststratebefore adoptiond87d637
line 71why, one step back71feat: add `Immer` classaleclarsonbefore adoptionecd04dc
lines 72–85why, one step back72 // Finalize the modified draft...73 if (result === undefined || result === baseDraft) {74 result = this.finalize(75 baseDraft,76 [],77 patches,78 inversePatches79 )80 }81 // ...or use a replacement value.82 else {83 // Users must never modify the draft _and_ return something else.84 if (baseDraft[DRAFT_STATE].modified)85 throw new Error("An immer producer returned a new value *and* modified its draft. Either return a new value *or* modify the draft.") // prettier-ignore`produce` is now exported as both default and name export. Implements #136Michel Weststratebefore adoption05e3015
line 86why, one step back86feat: add `Immer` classaleclarsonbefore adoptionecd04dc
lines 87–88why, one step back87 // Finalize the replacement in case it contains (or is) a subset of the draft.88 if (isDraftable(result)) result = this.finalize(result)Introduced the concept of `nothing`Michel Weststratebefore adoption798d2b2
line 89why, one step back89feat: add `Immer` classaleclarsonbefore adoptionecd04dc
lines 90–168why, one step back90 if (patchListener) {91 patches.push({92 op: "replace",93 path: [],94 value: result95 })96 inversePatches.push({97 op: "replace",98 path: [],99 value: base100 })101 }102 }103 } finally {104 this.currentScope().forEach(state => state.revoke())105 this.scopes.pop()106 }107 patchListener && patchListener(patches, inversePatches)108 }109 // Normalize the result.110 return result === NOTHING ? undefined : result111 }112 setAutoFreeze(value) {113 this.autoFreeze = value114 }115 setUseProxies(value) {116 this.useProxies = value117 assign(this, value ? modernProxy : legacyProxy)118 }119 /**120 * @internal121 * Finalize a draft, returning either the unmodified base state or a modified122 * copy of the base state.123 */124 finalize(draft, path, patches, inversePatches) {125 const state = draft[DRAFT_STATE]126 if (!state) {127 if (Object.isFrozen(draft)) return draft128 return this.finalizeTree(draft)129 }130 if (!state.modified) return state.base131 if (!state.finalized) {132 state.finalized = true133 this.finalizeTree(state.draft, path, patches, inversePatches)134 if (this.autoFreeze) Object.freeze(state.copy)135 if (patches) generatePatches(state, path, patches, inversePatches)136 }137 return state.copy138 }139 /**140 * @internal141 * Finalize all drafts in the given state tree.142 */143 finalizeTree(root, path, patches, inversePatches) {144 const state = root[DRAFT_STATE]145 if (state) {146 root = this.useProxies147 ? state.copy148 : (state.copy = shallowCopy(state.draft))149 }150 const finalizeProperty = (prop, value, parent) => {151 // Skip unchanged properties in draft objects.152 if (state && parent === root && is(value, state.base[prop])) return153 if (!isDraftable(value)) return154 if (!isDraft(value)) {155 // Frozen values are already finalized.156 return Object.isFrozen(value) || each(value, finalizeProperty)157 }158 // prettier-ignore159 parent[prop] =160 // Patches are never generated for assigned properties.161 patches && parent === root && !(state && has(state.assigned, prop))162 ? this.finalize(value, path.concat(prop), patches, inversePatches)163 : this.finalize(value)164 }165 each(root, finalizeProperty)166 return root167 }168}