Skip to content
Myr

immer.js

This file

Path

src/immer.js

313 lines · 10.5 KiB · JavaScript

Last changed by

feat: `onCopy` for `Sets`keenondrumsbefore adoptione56ad54

History of this file

Take it

The walk stopped after 200 commits: lines older than 53e9ce8 point at it.

feat: add `Immer` classaleclarsonbefore adoptionecd04dc

lines 1–2why, one step back
1import * as legacyProxy from "./es5"
2import * as modernProxy from "./proxy"

fix: applyPatches should mutate draftsaleclarsonbefore adoptiond41be77

line 3why, one step back
3import {applyPatches, generatePatches} from "./patches"

feat: add `Immer` classaleclarsonbefore adoptionecd04dc

lines 4–6why, one step back
4import {
5 assign,6 each,

feat: `onAssign` for `Maps`keenondrumsbefore adoptioneaea1b0

line 7why, one step back
7 get,

fix(es5): onDelete hookaleclarsonbefore adoption46cc6a1

line 8why, one step back
8 has,

feat: add `Immer` classaleclarsonbefore adoptionecd04dc

lines 9–11why, one step back
9 is,
10 isDraft,11 isDraftable,

nit: remove old `each` and rename `eachOwn`aleclarsonbefore adoptionc0ea419

line 12why, one step back
12 isEnumerable,

feat: `Map` drafts and patcheskeenondrumsbefore adoption30db0f3

line 13why, one step back
13 isMap,

feat: add `Immer` classaleclarsonbefore adoptionecd04dc

lines 14–15why, one step back
14 shallowCopy,
15 DRAFT_STATE,

feat: `Set` draftsAndrey Goncharovbefore adoption4355b63

line 16why, one step back
16 NOTHING,

feat: `onAssign` for `Sets`keenondrumsbefore adoptionaa24f65

lines 17–18why, one step back
17 isSet,
18 original

perf: proxy assignaleclarsonbefore adoption53e9ce8

line 19why, one step back
19} from "./common"

Merge branch 'async-recipes'Michel Weststratebefore adoptionff210d8

line 20why, one step back
20import {ImmerScope} from "./scope"

perf: proxy assignaleclarsonbefore adoption53e9ce8

line 21why, one step back
21

feat: add `Immer` classaleclarsonbefore adoptionecd04dc

line 22why, one step back
22function verifyMinified() {}

perf: proxy assignaleclarsonbefore adoption53e9ce8

line 23why, one step back
23

feat: add `Immer` classaleclarsonbefore adoptionecd04dc

lines 24–28why, one step back
24const configDefaults = {
25 useProxies: typeof Proxy !== "undefined" && typeof Reflect !== "undefined",26 autoFreeze:27 typeof process !== "undefined"28 ? process.env.NODE_ENV !== "production"

feat: add hooks to the `Immer` classaleclarsonbefore adoption7f50364

lines 29–32why, one step back
29 : verifyMinified.name === "verifyMinified",
30 onAssign: null,31 onDelete: null,32 onCopy: null

feat: add `Immer` classaleclarsonbefore adoptionecd04dc

line 33why, one step back
33}

perf: proxy assignaleclarsonbefore adoption53e9ce8

line 34why, one step back
34

feat: add `Immer` classaleclarsonbefore adoptionecd04dc

lines 35–45why, one step back
35export class Immer {
36 constructor(config) {37 assign(this, configDefaults, config)38 this.setUseProxies(this.useProxies)39 this.produce = this.produce.bind(this)40 }41 produce(base, recipe, patchListener) {42 // curried invocation43 if (typeof base === "function" && typeof recipe !== "function") {44 const defaultBase = recipe45 recipe = base

perf: proxy assignaleclarsonbefore adoption53e9ce8

line 46why, one step back
46

refactor(ts): curriedProduce functionAlec Larsonbefore adoption1282f04

line 47why, one step back
47 const self = this

feat: `this` in recipe is no longer the draft, but unboundMichel Weststratebefore adoption3f40298

line 48why, one step back
48 return function curriedProduce(base = defaultBase, ...args) {

refactor(ts): curriedProduce functionAlec Larsonbefore adoption1282f04

line 49why, one step back
49 return self.produce(base, draft => recipe.call(this, draft, ...args)) // prettier-ignore

feat: `this` in recipe is no longer the draft, but unboundMichel Weststratebefore adoption3f40298

line 50why, one step back
50 }

perf: proxy assignaleclarsonbefore adoption53e9ce8

lines 51–52why, one step back
51 }
52

feat: add `Immer` classaleclarsonbefore adoptionecd04dc

lines 53–54why, one step back
53 // prettier-ignore
54 {

nit: improved error messagesAlec Larsonbefore adoptiona951f40

lines 55–60why, one step back
55 if (typeof recipe !== "function") {
56 throw new Error("The first or second argument to `produce` must be a function")57 }58 if (patchListener !== undefined && typeof patchListener !== "function") {59 throw new Error("The third argument to `produce` must be a function or undefined")60 }

feat: add `Immer` classaleclarsonbefore adoptionecd04dc

line 61why, one step back
61 }

perf: proxy assignaleclarsonbefore adoption53e9ce8

line 62why, one step back
62

feat: add `Immer` classaleclarsonbefore adoptionecd04dc

line 63why, one step back
63 let result

perf: proxy assignaleclarsonbefore adoption53e9ce8

line 64why, one step back
64

Merge branch 'async-recipes'Michel Weststratebefore adoptionff210d8

lines 65–70why, one step back
65 // Only plain objects, arrays, and "immerable classes" are drafted.
66 if (isDraftable(base)) {67 const scope = ImmerScope.enter()68 const proxy = this.createProxy(base)69 let hasError = true70 try {

feat: `this` in recipe is no longer the draft, but unboundMichel Weststratebefore adoption3f40298

line 71why, one step back
71 result = recipe(proxy)

Merge branch 'async-recipes'Michel Weststratebefore adoptionff210d8

line 72why, one step back
72 hasError = false

feat: add `Immer` classaleclarsonbefore adoptionecd04dc

line 73why, one step back
73 } finally {

Merge branch 'async-recipes'Michel Weststratebefore adoptionff210d8

lines 74–76why, one step back
74 // finally instead of catch + rethrow better preserves original stack
75 if (hasError) scope.revoke()76 else scope.leave()

feat: add `Immer` classaleclarsonbefore adoptionecd04dc

line 77why, one step back
77 }

Merge branch 'async-recipes'Michel Weststratebefore adoptionff210d8

lines 78–95why, one step back
78 if (result instanceof Promise) {
79 return result.then(80 result => {81 scope.usePatches(patchListener)82 return this.processResult(result, scope)83 },84 error => {85 scope.revoke()86 throw error87 }88 )89 }90 scope.usePatches(patchListener)91 return this.processResult(result, scope)92 } else {93 result = recipe(base)94 if (result === undefined) return base95 return result !== NOTHING ? result : undefined

feat: add `Immer` classaleclarsonbefore adoptionecd04dc

lines 96–97why, one step back
96 }
97 }

Merge branch 'async-recipes'Michel Weststratebefore adoptionff210d8

line 98why, one step back
98 createDraft(base) {

nit: improved error messagesAlec Larsonbefore adoptiona951f40

lines 99–101why, one step back
99 if (!isDraftable(base)) {
100 throw new Error("First argument to `createDraft` must be a plain object, an array, or an immerable object") // prettier-ignore101 }

Merge branch 'async-recipes'Michel Weststratebefore adoptionff210d8

lines 102–103why, one step back
102 const scope = ImmerScope.enter()
103 const proxy = this.createProxy(base)

nit: improved error messagesAlec Larsonbefore adoptiona951f40

line 104why, one step back
104 proxy[DRAFT_STATE].isManual = true

Merge branch 'async-recipes'Michel Weststratebefore adoptionff210d8

lines 105–108why, one step back
105 scope.leave()
106 return proxy107 }108 finishDraft(draft, patchListener) {

nit: improved error messagesAlec Larsonbefore adoptiona951f40

lines 109–115why, one step back
109 const state = draft && draft[DRAFT_STATE]
110 if (!state || !state.isManual) {111 throw new Error("First argument to `finishDraft` must be a draft returned by `createDraft`") // prettier-ignore112 }113 if (state.finalized) {114 throw new Error("The given draft is already finalized") // prettier-ignore115 }

Merge branch 'async-recipes'Michel Weststratebefore adoptionff210d8

lines 116–119why, one step back
116 const {scope} = state
117 scope.usePatches(patchListener)118 return this.processResult(undefined, scope)119 }

feat: add `Immer` classaleclarsonbefore adoptionecd04dc

lines 120–125why, one step back
120 setAutoFreeze(value) {
121 this.autoFreeze = value122 }123 setUseProxies(value) {124 this.useProxies = value125 assign(this, value ? modernProxy : legacyProxy)

fix: applyPatches should mutate draftsaleclarsonbefore adoptiond41be77

lines 126–133why, one step back
126 }
127 applyPatches(base, patches) {128 // Mutate the base state when a draft is passed.129 if (isDraft(base)) {130 return applyPatches(base, patches)131 }132 // Otherwise, produce a copy of the base state.133 return this.produce(base, draft => applyPatches(draft, patches))

feat: add `Immer` classaleclarsonbefore adoptionecd04dc

line 134why, one step back
134 }

Merge branch 'async-recipes'Michel Weststratebefore adoptionff210d8

lines 135–170why, one step back
135 /** @internal */
136 processResult(result, scope) {137 const baseDraft = scope.drafts[0]138 const isReplaced = result !== undefined && result !== baseDraft139 this.willFinalize(scope, result, isReplaced)140 if (isReplaced) {141 if (baseDraft[DRAFT_STATE].modified) {142 scope.revoke()143 throw new Error("An immer producer returned a new value *and* modified its draft. Either return a new value *or* modify the draft.") // prettier-ignore144 }145 if (isDraftable(result)) {146 // Finalize the result in case it contains (or is) a subset of the draft.147 result = this.finalize(result, null, scope)148 }149 if (scope.patches) {150 scope.patches.push({151 op: "replace",152 path: [],153 value: result154 })155 scope.inversePatches.push({156 op: "replace",157 path: [],158 value: baseDraft[DRAFT_STATE].base159 })160 }161 } else {162 // Finalize the base draft.163 result = this.finalize(baseDraft, [], scope)164 }165 scope.revoke()166 if (scope.patches) {167 scope.patchListener(scope.patches, scope.inversePatches)168 }169 return result !== NOTHING ? result : undefined170 }

feat: add `Immer` classaleclarsonbefore adoptionecd04dc

lines 171–175why, one step back
171 /**
172 * @internal173 * Finalize a draft, returning either the unmodified base state or a modified174 * copy of the base state.175 */

Merge branch 'async-recipes'Michel Weststratebefore adoptionff210d8

line 176why, one step back
176 finalize(draft, path, scope) {

feat: add `Immer` classaleclarsonbefore adoptionecd04dc

lines 177–179why, one step back
177 const state = draft[DRAFT_STATE]
178 if (!state) {179 if (Object.isFrozen(draft)) return draft

Merge branch 'async-recipes'Michel Weststratebefore adoptionff210d8

line 180why, one step back
180 return this.finalizeTree(draft, null, scope)

feat: add `Immer` classaleclarsonbefore adoptionecd04dc

line 181why, one step back
181 }

Merge branch 'async-recipes'Michel Weststratebefore adoptionff210d8

lines 182–183why, one step back
182 // Never finalize drafts owned by another scope.
183 if (state.scope !== scope) {

feat: passing drafts to producealeclarsonbefore adoption9c53415

lines 184–185why, one step back
184 return draft
185 }

Merge branch 'async-recipes'Michel Weststratebefore adoptionff210d8

lines 186–188why, one step back
186 if (!state.modified) {
187 return state.base188 }

feat: add `Immer` classaleclarsonbefore adoptionecd04dc

lines 189–190why, one step back
189 if (!state.finalized) {
190 state.finalized = true

Merge branch 'async-recipes'Michel Weststratebefore adoptionff210d8

lines 191–192why, one step back
191 this.finalizeTree(state.draft, path, scope)
192

feat: `onCopy` for `Sets`keenondrumsbefore adoptione56ad54

lines 193–194why, one step back
193 // We cannot really delete anything inside of a Set. We can only replace the whole Set.
194 if (this.onDelete && !isSet(state.base)) {

fix(es5): onDelete hookaleclarsonbefore adoption46cc6a1

lines 195–197why, one step back
195 // The `assigned` object is unreliable with ES5 drafts.
196 if (this.useProxies) {197 const {assigned} = state

feat: `onDelete` for `Maps`keenondrumsbefore adoption1ca49ef

lines 198–200why, one step back
198 each(assigned, (prop, assignedValue) => {
199 if (!assignedValue) this.onDelete(state, prop)200 })

fix(es5): onDelete hookaleclarsonbefore adoption46cc6a1

line 201why, one step back
201 } else {

feat: `Set` draftsAndrey Goncharovbefore adoption4355b63

line 202why, one step back
202 // TODO: Figure it out for Maps and Sets if we need to support ES5

fix(es5): onDelete hookaleclarsonbefore adoption46cc6a1

line 203why, one step back
203 const {base, copy} = state

nit: remove old `each` and rename `eachOwn`aleclarsonbefore adoptionc0ea419

line 204why, one step back
204 each(base, prop => {

fix(es5): onDelete hookaleclarsonbefore adoption46cc6a1

lines 205–207why, one step back
205 if (!has(copy, prop)) this.onDelete(state, prop)
206 })207 }

feat: add hooks to the `Immer` classaleclarsonbefore adoption7f50364

line 208why, one step back
208 }

Merge branch 'async-recipes'Michel Weststratebefore adoptionff210d8

lines 209–211why, one step back
209 if (this.onCopy) {
210 this.onCopy(state)211 }

feat: passing drafts to producealeclarsonbefore adoption9c53415

line 212why, one step back
212

Merge branch 'async-recipes'Michel Weststratebefore adoptionff210d8

lines 213–215why, one step back
213 // At this point, all descendants of `state.copy` have been finalized,
214 // so we can be sure that `scope.canAutoFreeze` is accurate.215 if (this.autoFreeze && scope.canAutoFreeze) {

feat: passing drafts to producealeclarsonbefore adoption9c53415

lines 216–218why, one step back
216 Object.freeze(state.copy)
217 }218

Merge branch 'async-recipes'Michel Weststratebefore adoptionff210d8

lines 219–226why, one step back
219 if (path && scope.patches) {
220 generatePatches(221 state,222 path,223 scope.patches,224 scope.inversePatches225 )226 }

feat: add `Immer` classaleclarsonbefore adoptionecd04dc

lines 227–233why, one step back
227 }
228 return state.copy229 }230 /**231 * @internal232 * Finalize all drafts in the given state tree.233 */

Merge branch 'async-recipes'Michel Weststratebefore adoptionff210d8

line 234why, one step back
234 finalizeTree(root, rootPath, scope) {

feat: add `Immer` classaleclarsonbefore adoptionecd04dc

lines 235–236why, one step back
235 const state = root[DRAFT_STATE]
236 if (state) {

feat: limited class supportaleclarsonbefore adoption9877d64

line 237why, one step back
237 if (!this.useProxies) {

chore: comments and formattingAlec Larsonbefore adoptionff96173

line 238why, one step back
238 // Create the final copy, with added keys and without deleted keys.

feat: limited class supportaleclarsonbefore adoption9877d64

lines 239–241why, one step back
239 state.copy = shallowCopy(state.draft, true)
240 }241 root = state.copy

feat: add `Immer` classaleclarsonbefore adoptionecd04dc

line 242why, one step back
242 }

refactor: Immer#finalizeTree methodaleclarsonbefore adoption483a27a

line 243why, one step back
243

Merge branch 'async-recipes'Michel Weststratebefore adoptionff210d8

line 244why, one step back
244 const needPatches = !!rootPath && !!scope.patches

feat: add `Immer` classaleclarsonbefore adoptionecd04dc

line 245why, one step back
245 const finalizeProperty = (prop, value, parent) => {

fix: throw on circular referencesaleclarsonbefore adoption9c6603e

lines 246–249why, one step back
246 if (value === parent) {
247 throw Error("Immer forbids circular references")248 }249

Merge branch 'async-recipes'Michel Weststratebefore adoptionff210d8

lines 250–251why, one step back
250 // In the `finalizeTree` method, only the `root` object may be a draft.
251 const isDraftProp = !!state && parent === root

feat: `onAssign` for `Sets`keenondrumsbefore adoptionaa24f65

line 252why, one step back
252 const isSetMember = isSet(parent)

feat: add hooks to the `Immer` classaleclarsonbefore adoption7f50364

line 253why, one step back
253

refactor: Immer#finalizeTree methodaleclarsonbefore adoption483a27a

line 254why, one step back
254 if (isDraft(value)) {

Merge branch 'async-recipes'Michel Weststratebefore adoptionff210d8

line 255why, one step back
255 const path =

feat: `Set` draftsAndrey Goncharovbefore adoption4355b63

lines 256–257why, one step back
256 isDraftProp &&
257 needPatches &&

feat: `onAssign` for `Sets`keenondrumsbefore adoptionaa24f65

line 258why, one step back
258 !isSetMember &&

feat: add support of non-primitive keys for `Maps`keenondrumsbefore adoption6501ec5

line 259why, one step back
259 !has(state.assigned, prop)

Merge branch 'async-recipes'Michel Weststratebefore adoptionff210d8

lines 260–261why, one step back
260 ? rootPath.concat(prop)
261 : null

feat: passing drafts to producealeclarsonbefore adoption9c53415

line 262why, one step back
262

Merge branch 'async-recipes'Michel Weststratebefore adoptionff210d8

lines 263–270why, one step back
263 // Drafts owned by `scope` are finalized here.
264 value = this.finalize(value, path, scope)265266 // Drafts from another scope must prevent auto-freezing.267 if (isDraft(value)) {268 scope.canAutoFreeze = false269 }270

chore: reorganize src/proxy.jsAlec Larsonbefore adoption3163a7d

line 271why, one step back
271 setProperty(parent, prop, value)

feat: limited class supportaleclarsonbefore adoption9877d64

lines 272–273why, one step back
272
273 // Unchanged drafts are never passed to the `onAssign` hook.

feat: `onAssign` for `Maps`keenondrumsbefore adoptioneaea1b0

line 274why, one step back
274 if (isDraftProp && value === get(state.base, prop)) return

refactor: Immer#finalizeTree methodaleclarsonbefore adoption483a27a

line 275why, one step back
275 }

feat: passing drafts to producealeclarsonbefore adoption9c53415

line 276why, one step back
276 // Unchanged draft properties are ignored.

feat: `onAssign` for `Maps`keenondrumsbefore adoptioneaea1b0

line 277why, one step back
277 else if (isDraftProp && is(value, get(state.base, prop))) {

feat: add hooks to the `Immer` classaleclarsonbefore adoption7f50364

line 278why, one step back
278 return

feat: add `Immer` classaleclarsonbefore adoptionecd04dc

line 279why, one step back
279 }

refactor: Immer#finalizeTree methodaleclarsonbefore adoption483a27a

lines 280–281why, one step back
280 // Search new objects for unfinalized drafts. Frozen objects should never contain drafts.
281 else if (isDraftable(value) && !Object.isFrozen(value)) {

nit: remove old `each` and rename `eachOwn`aleclarsonbefore adoptionc0ea419

line 282why, one step back
282 each(value, finalizeProperty)

refactor: Immer#finalizeTree methodaleclarsonbefore adoption483a27a

lines 283–284why, one step back
283 }
284

feat: `onAssign` for `Sets`keenondrumsbefore adoptionaa24f65

lines 285–286why, one step back
285 // We cannot really assign anything inside of a Set. We can only replace the whole Set.
286 if (isDraftProp && this.onAssign && !isSetMember) {

Merge branch 'async-recipes'Michel Weststratebefore adoptionff210d8

line 287why, one step back
287 this.onAssign(state, prop, value)

feat: add hooks to the `Immer` classaleclarsonbefore adoption7f50364

line 288why, one step back
288 }

feat: add `Immer` classaleclarsonbefore adoptionecd04dc

line 289why, one step back
289 }

refactor: Immer#finalizeTree methodaleclarsonbefore adoption483a27a

line 290why, one step back
290

nit: remove old `each` and rename `eachOwn`aleclarsonbefore adoptionc0ea419

line 291why, one step back
291 each(root, finalizeProperty)

feat: add `Immer` classaleclarsonbefore adoptionecd04dc

line 292why, one step back
292 return root

feat: `Map` drafts and patcheskeenondrumsbefore adoption30db0f3

line 293why, one step back
293 }

chore: reorganize src/proxy.jsAlec Larsonbefore adoption3163a7d

line 294why, one step back
294}

feat: `Map` drafts and patcheskeenondrumsbefore adoption30db0f3

line 295why, one step back
295

chore: reorganize src/proxy.jsAlec Larsonbefore adoption3163a7d

lines 296–300why, one step back
296function setProperty(parent, prop, value) {
297 // Preserve non-enumerable properties.298 if (Array.isArray(parent) || isEnumerable(parent, prop)) {299 parent[prop] = value300 return

feat: `Map` supportkeenondrumsbefore adoption8276a6c

line 301why, one step back
301 }

chore: reorganize src/proxy.jsAlec Larsonbefore adoption3163a7d

lines 302–303why, one step back
302 if (isMap(parent)) {
303 parent.set(prop, value)

feat: `Set` draftsAndrey Goncharovbefore adoption4355b63

lines 304–309why, one step back
304 return
305 }306 if (isSet(parent)) {307 // Here prop is a proxied value308 parent.delete(prop)309 parent.add(value)

chore: reorganize src/proxy.jsAlec Larsonbefore adoption3163a7d

lines 310–312why, one step back
310 return
311 }312 Object.defineProperty(parent, prop, {value})

feat: add `Immer` classaleclarsonbefore adoptionecd04dc

line 313why, one step back
313}