Skip to content
Myr

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 file

Take it

The walk stopped after 200 commits: lines older than 3c7f374 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

lines 16–17why, one step back
16 NOTHING,
17 isSet

nit: simplify hasObjectChanges loopaleclarsonbefore adoption3c7f374

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

Merge branch 'async-recipes'Michel Weststratebefore adoptionff210d8

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

nit: simplify hasObjectChanges loopaleclarsonbefore adoption3c7f374

line 20why, one step back
20

feat: add `Immer` classaleclarsonbefore adoptionecd04dc

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

nit: simplify hasObjectChanges loopaleclarsonbefore adoption3c7f374

line 22why, one step back
22

feat: add `Immer` classaleclarsonbefore adoptionecd04dc

lines 23–27why, one step back
23const 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 back
28 : verifyMinified.name === "verifyMinified",
29 onAssign: null,30 onDelete: null,31 onCopy: null

feat: add `Immer` classaleclarsonbefore adoptionecd04dc

line 32why, one step back
32}

nit: simplify hasObjectChanges loopaleclarsonbefore adoption3c7f374

line 33why, one step back
33

feat: add `Immer` classaleclarsonbefore adoptionecd04dc

lines 34–44why, one step back
34export 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 = base

nit: simplify hasObjectChanges loopaleclarsonbefore adoption3c7f374

line 45why, one step back
45

refactor(ts): curriedProduce functionAlec Larsonbefore adoption1282f04

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

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

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

refactor(ts): curriedProduce functionAlec Larsonbefore adoption1282f04

line 48why, one step back
48 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 49why, one step back
49 }

nit: simplify hasObjectChanges loopaleclarsonbefore adoption3c7f374

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

feat: add `Immer` classaleclarsonbefore adoptionecd04dc

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

nit: improved error messagesAlec Larsonbefore adoptiona951f40

lines 54–59why, one step back
54 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 back
60 }

nit: simplify hasObjectChanges loopaleclarsonbefore adoption3c7f374

line 61why, one step back
61

feat: add `Immer` classaleclarsonbefore adoptionecd04dc

line 62why, one step back
62 let result

nit: simplify hasObjectChanges loopaleclarsonbefore adoption3c7f374

line 63why, one step back
63

Merge branch 'async-recipes'Michel Weststratebefore adoptionff210d8

lines 64–69why, one step back
64 // 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 back
70 result = recipe(proxy)

Merge branch 'async-recipes'Michel Weststratebefore adoptionff210d8

line 71why, one step back
71 hasError = false

feat: add `Immer` classaleclarsonbefore adoptionecd04dc

line 72why, one step back
72 } finally {

Merge branch 'async-recipes'Michel Weststratebefore adoptionff210d8

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

feat: add `Immer` classaleclarsonbefore adoptionecd04dc

line 76why, one step back
76 }

Merge branch 'async-recipes'Michel Weststratebefore adoptionff210d8

lines 77–94why, one step back
77 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 : undefined

feat: add `Immer` classaleclarsonbefore adoptionecd04dc

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

Merge branch 'async-recipes'Michel Weststratebefore adoptionff210d8

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

nit: improved error messagesAlec Larsonbefore adoptiona951f40

lines 98–100why, one step back
98 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 back
101 const scope = ImmerScope.enter()
102 const proxy = this.createProxy(base)

nit: improved error messagesAlec Larsonbefore adoptiona951f40

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

Merge branch 'async-recipes'Michel Weststratebefore adoptionff210d8

lines 104–107why, one step back
104 scope.leave()
105 return proxy106 }107 finishDraft(draft, patchListener) {

nit: improved error messagesAlec Larsonbefore adoptiona951f40

lines 108–114why, one step back
108 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 back
115 const {scope} = state
116 scope.usePatches(patchListener)117 return this.processResult(undefined, scope)118 }

feat: add `Immer` classaleclarsonbefore adoptionecd04dc

lines 119–124why, one step back
119 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 back
125 }
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 back
133 }

Merge branch 'async-recipes'Michel Weststratebefore adoptionff210d8

lines 134–169why, one step back
134 /** @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 back
170 /**
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 back
175 finalize(draft, path, scope) {

feat: add `Immer` classaleclarsonbefore adoptionecd04dc

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

Merge branch 'async-recipes'Michel Weststratebefore adoptionff210d8

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

feat: add `Immer` classaleclarsonbefore adoptionecd04dc

line 180why, one step back
180 }

Merge branch 'async-recipes'Michel Weststratebefore adoptionff210d8

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

feat: passing drafts to producealeclarsonbefore adoption9c53415

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

Merge branch 'async-recipes'Michel Weststratebefore adoptionff210d8

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

feat: add `Immer` classaleclarsonbefore adoptionecd04dc

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

Merge branch 'async-recipes'Michel Weststratebefore adoptionff210d8

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

feat: `Set` draftsAndrey Goncharovbefore adoption4355b63

line 192why, one step back
192 // 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 back
193 if (this.onDelete) {

fix(es5): onDelete hookaleclarsonbefore adoption46cc6a1

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

feat: `onDelete` for `Maps`keenondrumsbefore adoption1ca49ef

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

fix(es5): onDelete hookaleclarsonbefore adoption46cc6a1

line 200why, one step back
200 } else {

feat: `Set` draftsAndrey Goncharovbefore adoption4355b63

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

fix(es5): onDelete hookaleclarsonbefore adoption46cc6a1

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

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

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

fix(es5): onDelete hookaleclarsonbefore adoption46cc6a1

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

feat: add hooks to the `Immer` classaleclarsonbefore adoption7f50364

line 207why, one step back
207 }

Merge branch 'async-recipes'Michel Weststratebefore adoptionff210d8

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

feat: passing drafts to producealeclarsonbefore adoption9c53415

line 211why, one step back
211

Merge branch 'async-recipes'Michel Weststratebefore adoptionff210d8

lines 212–214why, one step back
212 // 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 back
215 Object.freeze(state.copy)
216 }217

Merge branch 'async-recipes'Michel Weststratebefore adoptionff210d8

lines 218–225why, one step back
218 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 back
226 }
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 back
233 finalizeTree(root, rootPath, scope) {

feat: add `Immer` classaleclarsonbefore adoptionecd04dc

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

feat: limited class supportaleclarsonbefore adoption9877d64

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

chore: comments and formattingAlec Larsonbefore adoptionff96173

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

feat: limited class supportaleclarsonbefore adoption9877d64

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

feat: add `Immer` classaleclarsonbefore adoptionecd04dc

line 241why, one step back
241 }

refactor: Immer#finalizeTree methodaleclarsonbefore adoption483a27a

line 242why, one step back
242

Merge branch 'async-recipes'Michel Weststratebefore adoptionff210d8

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

feat: add `Immer` classaleclarsonbefore adoptionecd04dc

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

fix: throw on circular referencesaleclarsonbefore adoption9c6603e

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

Merge branch 'async-recipes'Michel Weststratebefore adoptionff210d8

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

feat: add hooks to the `Immer` classaleclarsonbefore adoption7f50364

line 251why, one step back
251

refactor: Immer#finalizeTree methodaleclarsonbefore adoption483a27a

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

Merge branch 'async-recipes'Michel Weststratebefore adoptionff210d8

line 253why, one step back
253 const path =

feat: `Set` draftsAndrey Goncharovbefore adoption4355b63

lines 254–256why, one step back
254 isDraftProp &&
255 needPatches &&256 !isSet(parent) &&

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

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

Merge branch 'async-recipes'Michel Weststratebefore adoptionff210d8

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

feat: passing drafts to producealeclarsonbefore adoption9c53415

line 260why, one step back
260

Merge branch 'async-recipes'Michel Weststratebefore adoptionff210d8

lines 261–268why, one step back
261 // 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 }268

chore: reorganize src/proxy.jsAlec Larsonbefore adoption3163a7d

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

feat: limited class supportaleclarsonbefore adoption9877d64

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

feat: `onDelete` for `Maps`keenondrumsbefore adoption1ca49ef

line 272why, one step back
272 // TODO: Add tests and support for Sets

feat: `onAssign` for `Maps`keenondrumsbefore adoptioneaea1b0

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

refactor: Immer#finalizeTree methodaleclarsonbefore adoption483a27a

line 274why, one step back
274 }

feat: passing drafts to producealeclarsonbefore adoption9c53415

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

feat: `onAssign` for `Maps`keenondrumsbefore adoptioneaea1b0

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

feat: add hooks to the `Immer` classaleclarsonbefore adoption7f50364

line 277why, one step back
277 return

feat: add `Immer` classaleclarsonbefore adoptionecd04dc

line 278why, one step back
278 }

refactor: Immer#finalizeTree methodaleclarsonbefore adoption483a27a

lines 279–280why, one step back
279 // 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 back
281 each(value, finalizeProperty)

refactor: Immer#finalizeTree methodaleclarsonbefore adoption483a27a

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

Merge branch 'async-recipes'Michel Weststratebefore adoptionff210d8

lines 284–285why, one step back
284 if (isDraftProp && this.onAssign) {
285 this.onAssign(state, prop, value)

feat: add hooks to the `Immer` classaleclarsonbefore adoption7f50364

line 286why, one step back
286 }

feat: add `Immer` classaleclarsonbefore adoptionecd04dc

line 287why, one step back
287 }

refactor: Immer#finalizeTree methodaleclarsonbefore adoption483a27a

line 288why, one step back
288

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

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

feat: add `Immer` classaleclarsonbefore adoptionecd04dc

line 290why, one step back
290 return root

feat: `Map` drafts and patcheskeenondrumsbefore adoption30db0f3

line 291why, one step back
291 }

chore: reorganize src/proxy.jsAlec Larsonbefore adoption3163a7d

line 292why, one step back
292}

feat: `Map` drafts and patcheskeenondrumsbefore adoption30db0f3

line 293why, one step back
293

chore: reorganize src/proxy.jsAlec Larsonbefore adoption3163a7d

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

feat: `Map` supportkeenondrumsbefore adoption8276a6c

line 299why, one step back
299 }

chore: reorganize src/proxy.jsAlec Larsonbefore adoption3163a7d

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

feat: `Set` draftsAndrey Goncharovbefore adoption4355b63

lines 302–307why, one step back
302 return
303 }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 back
308 return
309 }310 Object.defineProperty(parent, prop, {value})

feat: add `Immer` classaleclarsonbefore adoptionecd04dc

line 311why, one step back
311}