immer.js
This file
Path
src/immer.js
296 lines · 7.9 KiB · JavaScript
Last changed by
fix: don't unnecessary modify draft if replaying patches results in a new state anywayMichel Weststratebefore adoption96f2b2e
History of this fileTake it
The walk stopped after 200 commits: lines older than 7d2f308 point at it.
feat: add `Immer` classaleclarsonbefore adoptionecd04dc
lines 1–2why, one step back1import * as legacyProxy from "./es5"2import * as modernProxy from "./proxy"fix: applyPatches should mutate draftsaleclarsonbefore adoptiond41be77
line 3why, one step back3import {applyPatches, generatePatches} from "./patches"feat: add `Immer` classaleclarsonbefore adoptionecd04dc
line 4why, one step back4import {style: use tabsuse-tabsbefore adoptiona9c0fd0
lines 5–14why, one step back5 assign,6 each,7 has,8 is,9 isDraft,10 isDraftable,11 isEnumerable,12 shallowCopy,13 DRAFT_STATE,14 NOTHINGMerge remote-tracking branch 'origin/v1.8'Michel Weststratebefore adoption7790417
line 15why, one step back15} from "./common"Merge branch 'async-recipes'Michel Weststratebefore adoptionff210d8
line 16why, one step back16import {ImmerScope} from "./scope"Merge pull request #237 from mweststrate/curryMichel Weststratebefore adoption7d2f308
line 17why, one step back17feat: add `Immer` classaleclarsonbefore adoptionecd04dc
line 18why, one step back18function verifyMinified() {}Merge pull request #237 from mweststrate/curryMichel Weststratebefore adoption7d2f308
line 19why, one step back19feat: add `Immer` classaleclarsonbefore adoptionecd04dc
line 20why, one step back20const configDefaults = {style: use tabsuse-tabsbefore adoptiona9c0fd0
lines 21–28why, one step back21 useProxies: typeof Proxy !== "undefined" && typeof Reflect !== "undefined",22 autoFreeze:23 typeof process !== "undefined"24 ? process.env.NODE_ENV !== "production"25 : verifyMinified.name === "verifyMinified",26 onAssign: null,27 onDelete: null,28 onCopy: nullfeat: add `Immer` classaleclarsonbefore adoptionecd04dc
line 29why, one step back29}Merge pull request #237 from mweststrate/curryMichel Weststratebefore adoption7d2f308
line 30why, one step back30feat: add `Immer` classaleclarsonbefore adoptionecd04dc
line 31why, one step back31export class Immer {style: use tabsuse-tabsbefore adoptiona9c0fd0
lines 32–41why, one step back32 constructor(config) {33 assign(this, configDefaults, config)34 this.setUseProxies(this.useProxies)35 this.produce = this.produce.bind(this)36 }37 produce(base, recipe, patchListener) {38 // curried invocation39 if (typeof base === "function" && typeof recipe !== "function") {40 const defaultBase = recipe41 recipe = baseMerge pull request #237 from mweststrate/curryMichel Weststratebefore adoption7d2f308
line 42why, one step back42style: use tabsuse-tabsbefore adoptiona9c0fd0
lines 43–47why, one step back43 const self = this44 return function curriedProduce(base = defaultBase, ...args) {45 return self.produce(base, draft => recipe.call(this, draft, ...args)) // prettier-ignore46 }47 }Merge pull request #237 from mweststrate/curryMichel Weststratebefore adoption7d2f308
line 48why, one step back48style: use tabsuse-tabsbefore adoptiona9c0fd0
lines 49–57why, one step back49 // prettier-ignore50 {51 if (typeof recipe !== "function") {52 throw new Error("The first or second argument to `produce` must be a function")53 }54 if (patchListener !== undefined && typeof patchListener !== "function") {55 throw new Error("The third argument to `produce` must be a function or undefined")56 }57 }Merge pull request #237 from mweststrate/curryMichel Weststratebefore adoption7d2f308
line 58why, one step back58style: use tabsuse-tabsbefore adoptiona9c0fd0
line 59why, one step back59 let resultnit: dedupe some codealeclarsonbefore adoptionc9e1d98
line 60why, one step back60style: use tabsuse-tabsbefore adoptiona9c0fd0
lines 61–123why, one step back61 // Only plain objects, arrays, and "immerable classes" are drafted.62 if (isDraftable(base)) {63 const scope = ImmerScope.enter()64 const proxy = this.createProxy(base)65 let hasError = true66 try {67 result = recipe(proxy)68 hasError = false69 } finally {70 // finally instead of catch + rethrow better preserves original stack71 if (hasError) scope.revoke()72 else scope.leave()73 }74 if (result instanceof Promise) {75 return result.then(76 result => {77 scope.usePatches(patchListener)78 return this.processResult(result, scope)79 },80 error => {81 scope.revoke()82 throw error83 }84 )85 }86 scope.usePatches(patchListener)87 return this.processResult(result, scope)88 } else {89 result = recipe(base)90 if (result === undefined) return base91 return result !== NOTHING ? result : undefined92 }93 }94 createDraft(base) {95 if (!isDraftable(base)) {96 throw new Error("First argument to `createDraft` must be a plain object, an array, or an immerable object") // prettier-ignore97 }98 const scope = ImmerScope.enter()99 const proxy = this.createProxy(base)100 proxy[DRAFT_STATE].isManual = true101 scope.leave()102 return proxy103 }104 finishDraft(draft, patchListener) {105 const state = draft && draft[DRAFT_STATE]106 if (!state || !state.isManual) {107 throw new Error("First argument to `finishDraft` must be a draft returned by `createDraft`") // prettier-ignore108 }109 if (state.finalized) {110 throw new Error("The given draft is already finalized") // prettier-ignore111 }112 const {scope} = state113 scope.usePatches(patchListener)114 return this.processResult(undefined, scope)115 }116 setAutoFreeze(value) {117 this.autoFreeze = value118 }119 setUseProxies(value) {120 this.useProxies = value121 assign(this, value ? modernProxy : legacyProxy)122 }123 applyPatches(base, patches) {fix: don't unnecessary modify draft if replaying patches results in a new state anywayMichel Weststratebefore adoption96f2b2e
lines 124–134why, one step back124 // If a patch replaces the entire state, take that replacement as base125 // before applying patches126 let i127 for (i = patches.length - 1; i >= 0; i--) {128 const patch = patches[i]129 if (patch.path.length === 0 && patch.op === "replace") {130 base = patch.value131 break132 }133 }134style: use tabsuse-tabsbefore adoptiona9c0fd0
line 135why, one step back135 if (isDraft(base)) {fix: don't unnecessary modify draft if replaying patches results in a new state anywayMichel Weststratebefore adoption96f2b2e
line 136why, one step back136 // N.B: never hits if some patch a replacement, patches are never draftsstyle: use tabsuse-tabsbefore adoptiona9c0fd0
lines 137–139why, one step back137 return applyPatches(base, patches)138 }139 // Otherwise, produce a copy of the base state.fix: don't unnecessary modify draft if replaying patches results in a new state anywayMichel Weststratebefore adoption96f2b2e
lines 140–142why, one step back140 return this.produce(base, draft =>141 applyPatches(draft, patches.slice(i + 1))142 )style: use tabsuse-tabsbefore adoptiona9c0fd0
lines 143–200why, one step back143 }144 /** @internal */145 processResult(result, scope) {146 const baseDraft = scope.drafts[0]147 const isReplaced = result !== undefined && result !== baseDraft148 this.willFinalize(scope, result, isReplaced)149 if (isReplaced) {150 if (baseDraft[DRAFT_STATE].modified) {151 scope.revoke()152 throw new Error("An immer producer returned a new value *and* modified its draft. Either return a new value *or* modify the draft.") // prettier-ignore153 }154 if (isDraftable(result)) {155 // Finalize the result in case it contains (or is) a subset of the draft.156 result = this.finalize(result, null, scope)157 }158 if (scope.patches) {159 scope.patches.push({160 op: "replace",161 path: [],162 value: result163 })164 scope.inversePatches.push({165 op: "replace",166 path: [],167 value: baseDraft[DRAFT_STATE].base168 })169 }170 } else {171 // Finalize the base draft.172 result = this.finalize(baseDraft, [], scope)173 }174 scope.revoke()175 if (scope.patches) {176 scope.patchListener(scope.patches, scope.inversePatches)177 }178 return result !== NOTHING ? result : undefined179 }180 /**181 * @internal182 * Finalize a draft, returning either the unmodified base state or a modified183 * copy of the base state.184 */185 finalize(draft, path, scope) {186 const state = draft[DRAFT_STATE]187 if (!state) {188 if (Object.isFrozen(draft)) return draft189 return this.finalizeTree(draft, null, scope)190 }191 // Never finalize drafts owned by another scope.192 if (state.scope !== scope) {193 return draft194 }195 if (!state.modified) {196 return state.base197 }198 if (!state.finalized) {199 state.finalized = true200 this.finalizeTree(state.draft, path, scope)Merge branch 'async-recipes'Michel Weststratebefore adoptionff210d8
line 201why, one step back201style: use tabsuse-tabsbefore adoptiona9c0fd0
lines 202–218why, one step back202 if (this.onDelete) {203 // The `assigned` object is unreliable with ES5 drafts.204 if (this.useProxies) {205 const {assigned} = state206 for (const prop in assigned) {207 if (!assigned[prop]) this.onDelete(state, prop)208 }209 } else {210 const {base, copy} = state211 each(base, prop => {212 if (!has(copy, prop)) this.onDelete(state, prop)213 })214 }215 }216 if (this.onCopy) {217 this.onCopy(state)218 }feat: passing drafts to producealeclarsonbefore adoption9c53415
line 219why, one step back219style: use tabsuse-tabsbefore adoptiona9c0fd0
lines 220–224why, one step back220 // At this point, all descendants of `state.copy` have been finalized,221 // so we can be sure that `scope.canAutoFreeze` is accurate.222 if (this.autoFreeze && scope.canAutoFreeze) {223 Object.freeze(state.copy)224 }feat: passing drafts to producealeclarsonbefore adoption9c53415
line 225why, one step back225style: use tabsuse-tabsbefore adoptiona9c0fd0
lines 226–244why, one step back226 if (path && scope.patches) {227 generatePatches(state, path, scope.patches, scope.inversePatches)228 }229 }230 return state.copy231 }232 /**233 * @internal234 * Finalize all drafts in the given state tree.235 */236 finalizeTree(root, rootPath, scope) {237 const state = root[DRAFT_STATE]238 if (state) {239 if (!this.useProxies) {240 // Create the final copy, with added keys and without deleted keys.241 state.copy = shallowCopy(state.draft, true)242 }243 root = state.copy244 }refactor: Immer#finalizeTree methodaleclarsonbefore adoption483a27a
line 245why, one step back245style: use tabsuse-tabsbefore adoptiona9c0fd0
lines 246–250why, one step back246 const needPatches = !!rootPath && !!scope.patches247 const finalizeProperty = (prop, value, parent) => {248 if (value === parent) {249 throw Error("Immer forbids circular references")250 }fix: throw on circular referencesaleclarsonbefore adoption9c6603e
line 251why, one step back251style: use tabsuse-tabsbefore adoptiona9c0fd0
lines 252–253why, one step back252 // In the `finalizeTree` method, only the `root` object may be a draft.253 const isDraftProp = !!state && parent === rootfeat: add hooks to the `Immer` classaleclarsonbefore adoption7f50364
line 254why, one step back254style: use tabsuse-tabsbefore adoptiona9c0fd0
lines 255–259why, one step back255 if (isDraft(value)) {256 const path =257 isDraftProp && needPatches && !state.assigned[prop]258 ? rootPath.concat(prop)259 : nullfeat: passing drafts to producealeclarsonbefore adoption9c53415
line 260why, one step back260style: use tabsuse-tabsbefore adoptiona9c0fd0
lines 261–262why, one step back261 // Drafts owned by `scope` are finalized here.262 value = this.finalize(value, path, scope)Merge branch 'async-recipes'Michel Weststratebefore adoptionff210d8
line 263why, one step back263style: use tabsuse-tabsbefore adoptiona9c0fd0
lines 264–267why, one step back264 // Drafts from another scope must prevent auto-freezing.265 if (isDraft(value)) {266 scope.canAutoFreeze = false267 }Merge branch 'async-recipes'Michel Weststratebefore adoptionff210d8
line 268why, one step back268style: use tabsuse-tabsbefore adoptiona9c0fd0
lines 269–274why, one step back269 // Preserve non-enumerable properties.270 if (Array.isArray(parent) || isEnumerable(parent, prop)) {271 parent[prop] = value272 } else {273 Object.defineProperty(parent, prop, {value})274 }feat: limited class supportaleclarsonbefore adoption9877d64
line 275why, one step back275style: use tabsuse-tabsbefore adoptiona9c0fd0
lines 276–286why, one step back276 // Unchanged drafts are never passed to the `onAssign` hook.277 if (isDraftProp && value === state.base[prop]) return278 }279 // Unchanged draft properties are ignored.280 else if (isDraftProp && is(value, state.base[prop])) {281 return282 }283 // Search new objects for unfinalized drafts. Frozen objects should never contain drafts.284 else if (isDraftable(value) && !Object.isFrozen(value)) {285 each(value, finalizeProperty)286 }refactor: Immer#finalizeTree methodaleclarsonbefore adoption483a27a
line 287why, one step back287style: use tabsuse-tabsbefore adoptiona9c0fd0
lines 288–291why, one step back288 if (isDraftProp && this.onAssign) {289 this.onAssign(state, prop, value)290 }291 }refactor: Immer#finalizeTree methodaleclarsonbefore adoption483a27a
line 292why, one step back292style: use tabsuse-tabsbefore adoptiona9c0fd0
lines 293–295why, one step back293 each(root, finalizeProperty)294 return root295 }feat: add `Immer` classaleclarsonbefore adoptionecd04dc
line 296why, one step back296}