immer.js
This file
Path
src/immer.js
312 lines · 8.4 KiB · JavaScript
Last changed by
Merge pull request #402 from immerjs/produce-with-patchesMichel Weststratebefore adoptiona16deda
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–93why, 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 }Merge pull request #402 from immerjs/produce-with-patchesMichel Weststratebefore adoptiona16deda
lines 94–109why, one step back94 produceWithPatches(arg1, arg2, arg3) {95 if (typeof arg1 === "function") {96 const self = this97 return (state, ...args) =>98 this.produceWithPatches(state, draft => arg1(draft, ...args))99 }100 // non-curried form101 if (arg3)102 throw new Error("A patch listener cannot be passed to produceWithPatches")103 let patches, inversePatches104 const nextState = this.produce(arg1, arg2, (p, ip) => {105 patches = p106 inversePatches = ip107 })108 return [nextState, patches, inversePatches]109 }style: use tabsuse-tabsbefore adoptiona9c0fd0
lines 110–139why, one step back110 createDraft(base) {111 if (!isDraftable(base)) {112 throw new Error("First argument to `createDraft` must be a plain object, an array, or an immerable object") // prettier-ignore113 }114 const scope = ImmerScope.enter()115 const proxy = this.createProxy(base)116 proxy[DRAFT_STATE].isManual = true117 scope.leave()118 return proxy119 }120 finishDraft(draft, patchListener) {121 const state = draft && draft[DRAFT_STATE]122 if (!state || !state.isManual) {123 throw new Error("First argument to `finishDraft` must be a draft returned by `createDraft`") // prettier-ignore124 }125 if (state.finalized) {126 throw new Error("The given draft is already finalized") // prettier-ignore127 }128 const {scope} = state129 scope.usePatches(patchListener)130 return this.processResult(undefined, scope)131 }132 setAutoFreeze(value) {133 this.autoFreeze = value134 }135 setUseProxies(value) {136 this.useProxies = value137 assign(this, value ? modernProxy : legacyProxy)138 }139 applyPatches(base, patches) {fix: don't unnecessary modify draft if replaying patches results in a new state anywayMichel Weststratebefore adoption96f2b2e
lines 140–150why, one step back140 // If a patch replaces the entire state, take that replacement as base141 // before applying patches142 let i143 for (i = patches.length - 1; i >= 0; i--) {144 const patch = patches[i]145 if (patch.path.length === 0 && patch.op === "replace") {146 base = patch.value147 break148 }149 }150style: use tabsuse-tabsbefore adoptiona9c0fd0
line 151why, one step back151 if (isDraft(base)) {fix: don't unnecessary modify draft if replaying patches results in a new state anywayMichel Weststratebefore adoption96f2b2e
line 152why, one step back152 // N.B: never hits if some patch a replacement, patches are never draftsstyle: use tabsuse-tabsbefore adoptiona9c0fd0
lines 153–155why, one step back153 return applyPatches(base, patches)154 }155 // 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 156–158why, one step back156 return this.produce(base, draft =>157 applyPatches(draft, patches.slice(i + 1))158 )style: use tabsuse-tabsbefore adoptiona9c0fd0
lines 159–216why, one step back159 }160 /** @internal */161 processResult(result, scope) {162 const baseDraft = scope.drafts[0]163 const isReplaced = result !== undefined && result !== baseDraft164 this.willFinalize(scope, result, isReplaced)165 if (isReplaced) {166 if (baseDraft[DRAFT_STATE].modified) {167 scope.revoke()168 throw new Error("An immer producer returned a new value *and* modified its draft. Either return a new value *or* modify the draft.") // prettier-ignore169 }170 if (isDraftable(result)) {171 // Finalize the result in case it contains (or is) a subset of the draft.172 result = this.finalize(result, null, scope)173 }174 if (scope.patches) {175 scope.patches.push({176 op: "replace",177 path: [],178 value: result179 })180 scope.inversePatches.push({181 op: "replace",182 path: [],183 value: baseDraft[DRAFT_STATE].base184 })185 }186 } else {187 // Finalize the base draft.188 result = this.finalize(baseDraft, [], scope)189 }190 scope.revoke()191 if (scope.patches) {192 scope.patchListener(scope.patches, scope.inversePatches)193 }194 return result !== NOTHING ? result : undefined195 }196 /**197 * @internal198 * Finalize a draft, returning either the unmodified base state or a modified199 * copy of the base state.200 */201 finalize(draft, path, scope) {202 const state = draft[DRAFT_STATE]203 if (!state) {204 if (Object.isFrozen(draft)) return draft205 return this.finalizeTree(draft, null, scope)206 }207 // Never finalize drafts owned by another scope.208 if (state.scope !== scope) {209 return draft210 }211 if (!state.modified) {212 return state.base213 }214 if (!state.finalized) {215 state.finalized = true216 this.finalizeTree(state.draft, path, scope)Merge branch 'async-recipes'Michel Weststratebefore adoptionff210d8
line 217why, one step back217style: use tabsuse-tabsbefore adoptiona9c0fd0
lines 218–234why, one step back218 if (this.onDelete) {219 // The `assigned` object is unreliable with ES5 drafts.220 if (this.useProxies) {221 const {assigned} = state222 for (const prop in assigned) {223 if (!assigned[prop]) this.onDelete(state, prop)224 }225 } else {226 const {base, copy} = state227 each(base, prop => {228 if (!has(copy, prop)) this.onDelete(state, prop)229 })230 }231 }232 if (this.onCopy) {233 this.onCopy(state)234 }feat: passing drafts to producealeclarsonbefore adoption9c53415
line 235why, one step back235style: use tabsuse-tabsbefore adoptiona9c0fd0
lines 236–240why, one step back236 // At this point, all descendants of `state.copy` have been finalized,237 // so we can be sure that `scope.canAutoFreeze` is accurate.238 if (this.autoFreeze && scope.canAutoFreeze) {239 Object.freeze(state.copy)240 }feat: passing drafts to producealeclarsonbefore adoption9c53415
line 241why, one step back241style: use tabsuse-tabsbefore adoptiona9c0fd0
lines 242–260why, one step back242 if (path && scope.patches) {243 generatePatches(state, path, scope.patches, scope.inversePatches)244 }245 }246 return state.copy247 }248 /**249 * @internal250 * Finalize all drafts in the given state tree.251 */252 finalizeTree(root, rootPath, scope) {253 const state = root[DRAFT_STATE]254 if (state) {255 if (!this.useProxies) {256 // Create the final copy, with added keys and without deleted keys.257 state.copy = shallowCopy(state.draft, true)258 }259 root = state.copy260 }refactor: Immer#finalizeTree methodaleclarsonbefore adoption483a27a
line 261why, one step back261style: use tabsuse-tabsbefore adoptiona9c0fd0
lines 262–266why, one step back262 const needPatches = !!rootPath && !!scope.patches263 const finalizeProperty = (prop, value, parent) => {264 if (value === parent) {265 throw Error("Immer forbids circular references")266 }fix: throw on circular referencesaleclarsonbefore adoption9c6603e
line 267why, one step back267style: use tabsuse-tabsbefore adoptiona9c0fd0
lines 268–269why, one step back268 // In the `finalizeTree` method, only the `root` object may be a draft.269 const isDraftProp = !!state && parent === rootfeat: add hooks to the `Immer` classaleclarsonbefore adoption7f50364
line 270why, one step back270style: use tabsuse-tabsbefore adoptiona9c0fd0
lines 271–275why, one step back271 if (isDraft(value)) {272 const path =273 isDraftProp && needPatches && !state.assigned[prop]274 ? rootPath.concat(prop)275 : nullfeat: passing drafts to producealeclarsonbefore adoption9c53415
line 276why, one step back276style: use tabsuse-tabsbefore adoptiona9c0fd0
lines 277–278why, one step back277 // Drafts owned by `scope` are finalized here.278 value = this.finalize(value, path, scope)Merge branch 'async-recipes'Michel Weststratebefore adoptionff210d8
line 279why, one step back279style: use tabsuse-tabsbefore adoptiona9c0fd0
lines 280–283why, one step back280 // Drafts from another scope must prevent auto-freezing.281 if (isDraft(value)) {282 scope.canAutoFreeze = false283 }Merge branch 'async-recipes'Michel Weststratebefore adoptionff210d8
line 284why, one step back284style: use tabsuse-tabsbefore adoptiona9c0fd0
lines 285–290why, one step back285 // Preserve non-enumerable properties.286 if (Array.isArray(parent) || isEnumerable(parent, prop)) {287 parent[prop] = value288 } else {289 Object.defineProperty(parent, prop, {value})290 }feat: limited class supportaleclarsonbefore adoption9877d64
line 291why, one step back291style: use tabsuse-tabsbefore adoptiona9c0fd0
lines 292–302why, one step back292 // Unchanged drafts are never passed to the `onAssign` hook.293 if (isDraftProp && value === state.base[prop]) return294 }295 // Unchanged draft properties are ignored.296 else if (isDraftProp && is(value, state.base[prop])) {297 return298 }299 // Search new objects for unfinalized drafts. Frozen objects should never contain drafts.300 else if (isDraftable(value) && !Object.isFrozen(value)) {301 each(value, finalizeProperty)302 }refactor: Immer#finalizeTree methodaleclarsonbefore adoption483a27a
line 303why, one step back303style: use tabsuse-tabsbefore adoptiona9c0fd0
lines 304–307why, one step back304 if (isDraftProp && this.onAssign) {305 this.onAssign(state, prop, value)306 }307 }refactor: Immer#finalizeTree methodaleclarsonbefore adoption483a27a
line 308why, one step back308style: use tabsuse-tabsbefore adoptiona9c0fd0
lines 309–311why, one step back309 each(root, finalizeProperty)310 return root311 }feat: add `Immer` classaleclarsonbefore adoptionecd04dc
line 312why, one step back312}