immer.js
This file
Path
src/immer.js
311 lines · 10.4 KiB · JavaScript
Last changed by
feat: `onDelete` for `Maps`keenondrumsbefore adoption1ca49ef
History of this fileTake it
The walk stopped after 200 commits: lines older than 3c7f374 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
lines 4–6why, one step back4import {5 assign,6 each,feat: `onAssign` for `Maps`keenondrumsbefore adoptioneaea1b0
line 7why, one step back7 get,fix(es5): onDelete hookaleclarsonbefore adoption46cc6a1
line 8why, one step back8 has,feat: add `Immer` classaleclarsonbefore adoptionecd04dc
lines 9–11why, one step back9 is,10 isDraft,11 isDraftable,nit: remove old `each` and rename `eachOwn`aleclarsonbefore adoptionc0ea419
line 12why, one step back12 isEnumerable,feat: `Map` drafts and patcheskeenondrumsbefore adoption30db0f3
line 13why, one step back13 isMap,feat: add `Immer` classaleclarsonbefore adoptionecd04dc
lines 14–15why, one step back14 shallowCopy,15 DRAFT_STATE,feat: `Set` draftsAndrey Goncharovbefore adoption4355b63
lines 16–17why, one step back16 NOTHING,17 isSetnit: simplify hasObjectChanges loopaleclarsonbefore adoption3c7f374
line 18why, one step back18} from "./common"Merge branch 'async-recipes'Michel Weststratebefore adoptionff210d8
line 19why, one step back19import {ImmerScope} from "./scope"nit: simplify hasObjectChanges loopaleclarsonbefore adoption3c7f374
line 20why, one step back20feat: add `Immer` classaleclarsonbefore adoptionecd04dc
line 21why, one step back21function verifyMinified() {}nit: simplify hasObjectChanges loopaleclarsonbefore adoption3c7f374
line 22why, one step back22feat: add `Immer` classaleclarsonbefore adoptionecd04dc
lines 23–27why, one step back23const configDefaults = {24 useProxies: typeof Proxy !== "undefined" && typeof Reflect !== "undefined",25 autoFreeze:26 typeof process !== "undefined"27 ? process.env.NODE_ENV !== "production"feat: add hooks to the `Immer` classaleclarsonbefore adoption7f50364
lines 28–31why, one step back28 : verifyMinified.name === "verifyMinified",29 onAssign: null,30 onDelete: null,31 onCopy: nullfeat: add `Immer` classaleclarsonbefore adoptionecd04dc
line 32why, one step back32}nit: simplify hasObjectChanges loopaleclarsonbefore adoption3c7f374
line 33why, one step back33feat: add `Immer` classaleclarsonbefore adoptionecd04dc
lines 34–44why, one step back34export class Immer {35 constructor(config) {36 assign(this, configDefaults, config)37 this.setUseProxies(this.useProxies)38 this.produce = this.produce.bind(this)39 }40 produce(base, recipe, patchListener) {41 // curried invocation42 if (typeof base === "function" && typeof recipe !== "function") {43 const defaultBase = recipe44 recipe = basenit: simplify hasObjectChanges loopaleclarsonbefore adoption3c7f374
line 45why, one step back45refactor(ts): curriedProduce functionAlec Larsonbefore adoption1282f04
line 46why, one step back46 const self = thisfeat: `this` in recipe is no longer the draft, but unboundMichel Weststratebefore adoption3f40298
line 47why, one step back47 return function curriedProduce(base = defaultBase, ...args) {refactor(ts): curriedProduce functionAlec Larsonbefore adoption1282f04
line 48why, one step back48 return self.produce(base, draft => recipe.call(this, draft, ...args)) // prettier-ignorefeat: `this` in recipe is no longer the draft, but unboundMichel Weststratebefore adoption3f40298
line 49why, one step back49 }nit: simplify hasObjectChanges loopaleclarsonbefore adoption3c7f374
lines 50–51why, one step back50 }51feat: add `Immer` classaleclarsonbefore adoptionecd04dc
lines 52–53why, one step back52 // prettier-ignore53 {nit: improved error messagesAlec Larsonbefore adoptiona951f40
lines 54–59why, one step back54 if (typeof recipe !== "function") {55 throw new Error("The first or second argument to `produce` must be a function")56 }57 if (patchListener !== undefined && typeof patchListener !== "function") {58 throw new Error("The third argument to `produce` must be a function or undefined")59 }feat: add `Immer` classaleclarsonbefore adoptionecd04dc
line 60why, one step back60 }nit: simplify hasObjectChanges loopaleclarsonbefore adoption3c7f374
line 61why, one step back61feat: add `Immer` classaleclarsonbefore adoptionecd04dc
line 62why, one step back62 let resultnit: simplify hasObjectChanges loopaleclarsonbefore adoption3c7f374
line 63why, one step back63Merge branch 'async-recipes'Michel Weststratebefore adoptionff210d8
lines 64–69why, one step back64 // Only plain objects, arrays, and "immerable classes" are drafted.65 if (isDraftable(base)) {66 const scope = ImmerScope.enter()67 const proxy = this.createProxy(base)68 let hasError = true69 try {feat: `this` in recipe is no longer the draft, but unboundMichel Weststratebefore adoption3f40298
line 70why, one step back70 result = recipe(proxy)Merge branch 'async-recipes'Michel Weststratebefore adoptionff210d8
line 71why, one step back71 hasError = falsefeat: add `Immer` classaleclarsonbefore adoptionecd04dc
line 72why, one step back72 } finally {Merge branch 'async-recipes'Michel Weststratebefore adoptionff210d8
lines 73–75why, one step back73 // finally instead of catch + rethrow better preserves original stack74 if (hasError) scope.revoke()75 else scope.leave()feat: add `Immer` classaleclarsonbefore adoptionecd04dc
line 76why, one step back76 }Merge branch 'async-recipes'Michel Weststratebefore adoptionff210d8
lines 77–94why, one step back77 if (result instanceof Promise) {78 return result.then(79 result => {80 scope.usePatches(patchListener)81 return this.processResult(result, scope)82 },83 error => {84 scope.revoke()85 throw error86 }87 )88 }89 scope.usePatches(patchListener)90 return this.processResult(result, scope)91 } else {92 result = recipe(base)93 if (result === undefined) return base94 return result !== NOTHING ? result : undefinedfeat: add `Immer` classaleclarsonbefore adoptionecd04dc
lines 95–96why, one step back95 }96 }Merge branch 'async-recipes'Michel Weststratebefore adoptionff210d8
line 97why, one step back97 createDraft(base) {nit: improved error messagesAlec Larsonbefore adoptiona951f40
lines 98–100why, one step back98 if (!isDraftable(base)) {99 throw new Error("First argument to `createDraft` must be a plain object, an array, or an immerable object") // prettier-ignore100 }Merge branch 'async-recipes'Michel Weststratebefore adoptionff210d8
lines 101–102why, one step back101 const scope = ImmerScope.enter()102 const proxy = this.createProxy(base)nit: improved error messagesAlec Larsonbefore adoptiona951f40
line 103why, one step back103 proxy[DRAFT_STATE].isManual = trueMerge branch 'async-recipes'Michel Weststratebefore adoptionff210d8
lines 104–107why, one step back104 scope.leave()105 return proxy106 }107 finishDraft(draft, patchListener) {nit: improved error messagesAlec Larsonbefore adoptiona951f40
lines 108–114why, one step back108 const state = draft && draft[DRAFT_STATE]109 if (!state || !state.isManual) {110 throw new Error("First argument to `finishDraft` must be a draft returned by `createDraft`") // prettier-ignore111 }112 if (state.finalized) {113 throw new Error("The given draft is already finalized") // prettier-ignore114 }Merge branch 'async-recipes'Michel Weststratebefore adoptionff210d8
lines 115–118why, one step back115 const {scope} = state116 scope.usePatches(patchListener)117 return this.processResult(undefined, scope)118 }feat: add `Immer` classaleclarsonbefore adoptionecd04dc
lines 119–124why, one step back119 setAutoFreeze(value) {120 this.autoFreeze = value121 }122 setUseProxies(value) {123 this.useProxies = value124 assign(this, value ? modernProxy : legacyProxy)fix: applyPatches should mutate draftsaleclarsonbefore adoptiond41be77
lines 125–132why, one step back125 }126 applyPatches(base, patches) {127 // Mutate the base state when a draft is passed.128 if (isDraft(base)) {129 return applyPatches(base, patches)130 }131 // Otherwise, produce a copy of the base state.132 return this.produce(base, draft => applyPatches(draft, patches))feat: add `Immer` classaleclarsonbefore adoptionecd04dc
line 133why, one step back133 }Merge branch 'async-recipes'Michel Weststratebefore adoptionff210d8
lines 134–169why, one step back134 /** @internal */135 processResult(result, scope) {136 const baseDraft = scope.drafts[0]137 const isReplaced = result !== undefined && result !== baseDraft138 this.willFinalize(scope, result, isReplaced)139 if (isReplaced) {140 if (baseDraft[DRAFT_STATE].modified) {141 scope.revoke()142 throw new Error("An immer producer returned a new value *and* modified its draft. Either return a new value *or* modify the draft.") // prettier-ignore143 }144 if (isDraftable(result)) {145 // Finalize the result in case it contains (or is) a subset of the draft.146 result = this.finalize(result, null, scope)147 }148 if (scope.patches) {149 scope.patches.push({150 op: "replace",151 path: [],152 value: result153 })154 scope.inversePatches.push({155 op: "replace",156 path: [],157 value: baseDraft[DRAFT_STATE].base158 })159 }160 } else {161 // Finalize the base draft.162 result = this.finalize(baseDraft, [], scope)163 }164 scope.revoke()165 if (scope.patches) {166 scope.patchListener(scope.patches, scope.inversePatches)167 }168 return result !== NOTHING ? result : undefined169 }feat: add `Immer` classaleclarsonbefore adoptionecd04dc
lines 170–174why, one step back170 /**171 * @internal172 * Finalize a draft, returning either the unmodified base state or a modified173 * copy of the base state.174 */Merge branch 'async-recipes'Michel Weststratebefore adoptionff210d8
line 175why, one step back175 finalize(draft, path, scope) {feat: add `Immer` classaleclarsonbefore adoptionecd04dc
lines 176–178why, one step back176 const state = draft[DRAFT_STATE]177 if (!state) {178 if (Object.isFrozen(draft)) return draftMerge branch 'async-recipes'Michel Weststratebefore adoptionff210d8
line 179why, one step back179 return this.finalizeTree(draft, null, scope)feat: add `Immer` classaleclarsonbefore adoptionecd04dc
line 180why, one step back180 }Merge branch 'async-recipes'Michel Weststratebefore adoptionff210d8
lines 181–182why, one step back181 // Never finalize drafts owned by another scope.182 if (state.scope !== scope) {feat: passing drafts to producealeclarsonbefore adoption9c53415
lines 183–184why, one step back183 return draft184 }Merge branch 'async-recipes'Michel Weststratebefore adoptionff210d8
lines 185–187why, one step back185 if (!state.modified) {186 return state.base187 }feat: add `Immer` classaleclarsonbefore adoptionecd04dc
lines 188–189why, one step back188 if (!state.finalized) {189 state.finalized = trueMerge branch 'async-recipes'Michel Weststratebefore adoptionff210d8
lines 190–191why, one step back190 this.finalizeTree(state.draft, path, scope)191feat: `Set` draftsAndrey Goncharovbefore adoption4355b63
line 192why, one step back192 // TODO: It won't fire for Sets because they don't use `assigned`. Is it an issue?feat: add hooks to the `Immer` classaleclarsonbefore adoption7f50364
line 193why, one step back193 if (this.onDelete) {fix(es5): onDelete hookaleclarsonbefore adoption46cc6a1
lines 194–196why, one step back194 // The `assigned` object is unreliable with ES5 drafts.195 if (this.useProxies) {196 const {assigned} = statefeat: `onDelete` for `Maps`keenondrumsbefore adoption1ca49ef
lines 197–199why, one step back197 each(assigned, (prop, assignedValue) => {198 if (!assignedValue) this.onDelete(state, prop)199 })fix(es5): onDelete hookaleclarsonbefore adoption46cc6a1
line 200why, one step back200 } else {feat: `Set` draftsAndrey Goncharovbefore adoption4355b63
line 201why, one step back201 // TODO: Figure it out for Maps and Sets if we need to support ES5fix(es5): onDelete hookaleclarsonbefore adoption46cc6a1
line 202why, one step back202 const {base, copy} = statenit: remove old `each` and rename `eachOwn`aleclarsonbefore adoptionc0ea419
line 203why, one step back203 each(base, prop => {fix(es5): onDelete hookaleclarsonbefore adoption46cc6a1
lines 204–206why, one step back204 if (!has(copy, prop)) this.onDelete(state, prop)205 })206 }feat: add hooks to the `Immer` classaleclarsonbefore adoption7f50364
line 207why, one step back207 }Merge branch 'async-recipes'Michel Weststratebefore adoptionff210d8
lines 208–210why, one step back208 if (this.onCopy) {209 this.onCopy(state)210 }feat: passing drafts to producealeclarsonbefore adoption9c53415
line 211why, one step back211Merge branch 'async-recipes'Michel Weststratebefore adoptionff210d8
lines 212–214why, one step back212 // At this point, all descendants of `state.copy` have been finalized,213 // so we can be sure that `scope.canAutoFreeze` is accurate.214 if (this.autoFreeze && scope.canAutoFreeze) {feat: passing drafts to producealeclarsonbefore adoption9c53415
lines 215–217why, one step back215 Object.freeze(state.copy)216 }217Merge branch 'async-recipes'Michel Weststratebefore adoptionff210d8
lines 218–225why, one step back218 if (path && scope.patches) {219 generatePatches(220 state,221 path,222 scope.patches,223 scope.inversePatches224 )225 }feat: add `Immer` classaleclarsonbefore adoptionecd04dc
lines 226–232why, one step back226 }227 return state.copy228 }229 /**230 * @internal231 * Finalize all drafts in the given state tree.232 */Merge branch 'async-recipes'Michel Weststratebefore adoptionff210d8
line 233why, one step back233 finalizeTree(root, rootPath, scope) {feat: add `Immer` classaleclarsonbefore adoptionecd04dc
lines 234–235why, one step back234 const state = root[DRAFT_STATE]235 if (state) {feat: limited class supportaleclarsonbefore adoption9877d64
line 236why, one step back236 if (!this.useProxies) {chore: comments and formattingAlec Larsonbefore adoptionff96173
line 237why, one step back237 // Create the final copy, with added keys and without deleted keys.feat: limited class supportaleclarsonbefore adoption9877d64
lines 238–240why, one step back238 state.copy = shallowCopy(state.draft, true)239 }240 root = state.copyfeat: add `Immer` classaleclarsonbefore adoptionecd04dc
line 241why, one step back241 }refactor: Immer#finalizeTree methodaleclarsonbefore adoption483a27a
line 242why, one step back242Merge branch 'async-recipes'Michel Weststratebefore adoptionff210d8
line 243why, one step back243 const needPatches = !!rootPath && !!scope.patchesfeat: add `Immer` classaleclarsonbefore adoptionecd04dc
line 244why, one step back244 const finalizeProperty = (prop, value, parent) => {fix: throw on circular referencesaleclarsonbefore adoption9c6603e
lines 245–248why, one step back245 if (value === parent) {246 throw Error("Immer forbids circular references")247 }248Merge branch 'async-recipes'Michel Weststratebefore adoptionff210d8
lines 249–250why, one step back249 // In the `finalizeTree` method, only the `root` object may be a draft.250 const isDraftProp = !!state && parent === rootfeat: add hooks to the `Immer` classaleclarsonbefore adoption7f50364
line 251why, one step back251refactor: Immer#finalizeTree methodaleclarsonbefore adoption483a27a
line 252why, one step back252 if (isDraft(value)) {Merge branch 'async-recipes'Michel Weststratebefore adoptionff210d8
line 253why, one step back253 const path =feat: `Set` draftsAndrey Goncharovbefore adoption4355b63
lines 254–256why, one step back254 isDraftProp &&255 needPatches &&256 !isSet(parent) &&feat: add support of non-primitive keys for `Maps`keenondrumsbefore adoption6501ec5
line 257why, one step back257 !has(state.assigned, prop)Merge branch 'async-recipes'Michel Weststratebefore adoptionff210d8
lines 258–259why, one step back258 ? rootPath.concat(prop)259 : nullfeat: passing drafts to producealeclarsonbefore adoption9c53415
line 260why, one step back260Merge branch 'async-recipes'Michel Weststratebefore adoptionff210d8
lines 261–268why, one step back261 // Drafts owned by `scope` are finalized here.262 value = this.finalize(value, path, scope)263264 // Drafts from another scope must prevent auto-freezing.265 if (isDraft(value)) {266 scope.canAutoFreeze = false267 }268chore: reorganize src/proxy.jsAlec Larsonbefore adoption3163a7d
line 269why, one step back269 setProperty(parent, prop, value)feat: limited class supportaleclarsonbefore adoption9877d64
lines 270–271why, one step back270271 // Unchanged drafts are never passed to the `onAssign` hook.feat: `onDelete` for `Maps`keenondrumsbefore adoption1ca49ef
line 272why, one step back272 // TODO: Add tests and support for Setsfeat: `onAssign` for `Maps`keenondrumsbefore adoptioneaea1b0
line 273why, one step back273 if (isDraftProp && value === get(state.base, prop)) returnrefactor: Immer#finalizeTree methodaleclarsonbefore adoption483a27a
line 274why, one step back274 }feat: passing drafts to producealeclarsonbefore adoption9c53415
line 275why, one step back275 // Unchanged draft properties are ignored.feat: `onAssign` for `Maps`keenondrumsbefore adoptioneaea1b0
line 276why, one step back276 else if (isDraftProp && is(value, get(state.base, prop))) {feat: add hooks to the `Immer` classaleclarsonbefore adoption7f50364
line 277why, one step back277 returnfeat: add `Immer` classaleclarsonbefore adoptionecd04dc
line 278why, one step back278 }refactor: Immer#finalizeTree methodaleclarsonbefore adoption483a27a
lines 279–280why, one step back279 // Search new objects for unfinalized drafts. Frozen objects should never contain drafts.280 else if (isDraftable(value) && !Object.isFrozen(value)) {nit: remove old `each` and rename `eachOwn`aleclarsonbefore adoptionc0ea419
line 281why, one step back281 each(value, finalizeProperty)refactor: Immer#finalizeTree methodaleclarsonbefore adoption483a27a
lines 282–283why, one step back282 }283Merge branch 'async-recipes'Michel Weststratebefore adoptionff210d8
lines 284–285why, one step back284 if (isDraftProp && this.onAssign) {285 this.onAssign(state, prop, value)feat: add hooks to the `Immer` classaleclarsonbefore adoption7f50364
line 286why, one step back286 }feat: add `Immer` classaleclarsonbefore adoptionecd04dc
line 287why, one step back287 }refactor: Immer#finalizeTree methodaleclarsonbefore adoption483a27a
line 288why, one step back288nit: remove old `each` and rename `eachOwn`aleclarsonbefore adoptionc0ea419
line 289why, one step back289 each(root, finalizeProperty)feat: add `Immer` classaleclarsonbefore adoptionecd04dc
line 290why, one step back290 return rootfeat: `Map` drafts and patcheskeenondrumsbefore adoption30db0f3
line 291why, one step back291 }chore: reorganize src/proxy.jsAlec Larsonbefore adoption3163a7d
line 292why, one step back292}feat: `Map` drafts and patcheskeenondrumsbefore adoption30db0f3
line 293why, one step back293chore: reorganize src/proxy.jsAlec Larsonbefore adoption3163a7d
lines 294–298why, one step back294function setProperty(parent, prop, value) {295 // Preserve non-enumerable properties.296 if (Array.isArray(parent) || isEnumerable(parent, prop)) {297 parent[prop] = value298 returnfeat: `Map` supportkeenondrumsbefore adoption8276a6c
line 299why, one step back299 }chore: reorganize src/proxy.jsAlec Larsonbefore adoption3163a7d
lines 300–301why, one step back300 if (isMap(parent)) {301 parent.set(prop, value)feat: `Set` draftsAndrey Goncharovbefore adoption4355b63
lines 302–307why, one step back302 return303 }304 if (isSet(parent)) {305 // Here prop is a proxied value306 parent.delete(prop)307 parent.add(value)chore: reorganize src/proxy.jsAlec Larsonbefore adoption3163a7d
lines 308–310why, one step back308 return309 }310 Object.defineProperty(parent, prop, {value})feat: add `Immer` classaleclarsonbefore adoptionecd04dc
line 311why, one step back311}