Skip to content
Myr

immer.js

This file

Path

src/immer.js

349 lines · 9.5 KiB · JavaScript

Last changed by

feat: added first class support for `Map` and `Set`Michel Weststratebefore adoptionb6f1d40

History of this file

Take it

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

line 4why, one step back
4import {

style: use tabsuse-tabsbefore adoptiona9c0fd0

lines 5–9why, one step back
5 assign,
6 each,7 has,8 is,9 isDraft,

feat: added first class support for `Map` and `Set`Michel Weststratebefore adoptionb6f1d40

lines 10–12why, one step back
10 isSet,
11 get,12 isMap,

style: use tabsuse-tabsbefore adoptiona9c0fd0

lines 13–16why, one step back
13 isDraftable,
14 isEnumerable,15 shallowCopy,16 DRAFT_STATE,

BREAKING CHANGE: In development mode, any new value stored in a tree will be deeply frozen. Fixes #412 #363 #260 #230 #313 #229Michel Weststratebefore adoption9fa2581

line 17why, one step back
17 NOTHING,

feat: added first class support for `Map` and `Set`Michel Weststratebefore adoptionb6f1d40

line 18why, one step back
18 freeze

Merge remote-tracking branch 'origin/v1.8'Michel Weststratebefore adoption7790417

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

Merge branch 'async-recipes'Michel Weststratebefore adoptionff210d8

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

Merge pull request #237 from mweststrate/curryMichel Weststratebefore adoption7d2f308

line 21why, one step back
21

feat: add `Immer` classaleclarsonbefore adoptionecd04dc

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

Merge pull request #237 from mweststrate/curryMichel Weststratebefore adoption7d2f308

line 23why, one step back
23

feat: add `Immer` classaleclarsonbefore adoptionecd04dc

line 24why, one step back
24const configDefaults = {

fix: Don't use proxies if Proxy.revocable is not defined. Fixes #435Michel Weststratebefore adoptionc84aa53

lines 25–28why, one step back
25 useProxies:
26 typeof Proxy !== "undefined" &&27 typeof Proxy.revocable !== "undefined" &&28 typeof Reflect !== "undefined",

style: use tabsuse-tabsbefore adoptiona9c0fd0

lines 29–35why, one step back
29 autoFreeze:
30 typeof process !== "undefined"31 ? process.env.NODE_ENV !== "production"32 : verifyMinified.name === "verifyMinified",33 onAssign: null,34 onDelete: null,35 onCopy: null

feat: add `Immer` classaleclarsonbefore adoptionecd04dc

line 36why, one step back
36}

Merge pull request #237 from mweststrate/curryMichel Weststratebefore adoption7d2f308

line 37why, one step back
37

feat: add `Immer` classaleclarsonbefore adoptionecd04dc

line 38why, one step back
38export class Immer {

style: use tabsuse-tabsbefore adoptiona9c0fd0

lines 39–42why, one step back
39 constructor(config) {
40 assign(this, configDefaults, config)41 this.setUseProxies(this.useProxies)42 this.produce = this.produce.bind(this)

feat: added first class support for `Map` and `Set`Michel Weststratebefore adoptionb6f1d40

line 43why, one step back
43 this.produceWithPatches = this.produceWithPatches.bind(this)

style: use tabsuse-tabsbefore adoptiona9c0fd0

lines 44–49why, one step back
44 }
45 produce(base, recipe, patchListener) {46 // curried invocation47 if (typeof base === "function" && typeof recipe !== "function") {48 const defaultBase = recipe49 recipe = base

Merge pull request #237 from mweststrate/curryMichel Weststratebefore adoption7d2f308

line 50why, one step back
50

style: use tabsuse-tabsbefore adoptiona9c0fd0

lines 51–55why, one step back
51 const self = this
52 return function curriedProduce(base = defaultBase, ...args) {53 return self.produce(base, draft => recipe.call(this, draft, ...args)) // prettier-ignore54 }55 }

Merge pull request #237 from mweststrate/curryMichel Weststratebefore adoption7d2f308

line 56why, one step back
56

style: use tabsuse-tabsbefore adoptiona9c0fd0

lines 57–65why, one step back
57 // prettier-ignore
58 {59 if (typeof recipe !== "function") {60 throw new Error("The first or second argument to `produce` must be a function")61 }62 if (patchListener !== undefined && typeof patchListener !== "function") {63 throw new Error("The third argument to `produce` must be a function or undefined")64 }65 }

Merge pull request #237 from mweststrate/curryMichel Weststratebefore adoption7d2f308

line 66why, one step back
66

style: use tabsuse-tabsbefore adoptiona9c0fd0

line 67why, one step back
67 let result

nit: dedupe some codealeclarsonbefore adoptionc9e1d98

line 68why, one step back
68

style: use tabsuse-tabsbefore adoptiona9c0fd0

lines 69–81why, one step back
69 // Only plain objects, arrays, and "immerable classes" are drafted.
70 if (isDraftable(base)) {71 const scope = ImmerScope.enter()72 const proxy = this.createProxy(base)73 let hasError = true74 try {75 result = recipe(proxy)76 hasError = false77 } finally {78 // finally instead of catch + rethrow better preserves original stack79 if (hasError) scope.revoke()80 else scope.leave()81 }

feat: added first class support for `Map` and `Set`Michel Weststratebefore adoptionb6f1d40

line 82why, one step back
82 if (typeof Promise !== "undefined" && result instanceof Promise) {

style: use tabsuse-tabsbefore adoptiona9c0fd0

lines 83–97why, one step back
83 return result.then(
84 result => {85 scope.usePatches(patchListener)86 return this.processResult(result, scope)87 },88 error => {89 scope.revoke()90 throw error91 }92 )93 }94 scope.usePatches(patchListener)95 return this.processResult(result, scope)96 } else {97 result = recipe(base)

BREAKING CHANGE: In development mode, any new value stored in a tree will be deeply frozen. Fixes #412 #363 #260 #230 #313 #229Michel Weststratebefore adoption9fa2581

lines 98–101why, one step back
98 if (result === NOTHING) return undefined
99 if (result === undefined) result = base100 this.maybeFreeze(result, true)101 return result

style: use tabsuse-tabsbefore adoptiona9c0fd0

lines 102–103why, one step back
102 }
103 }

Merge pull request #402 from immerjs/produce-with-patchesMichel Weststratebefore adoptiona16deda

lines 104–119why, one step back
104 produceWithPatches(arg1, arg2, arg3) {
105 if (typeof arg1 === "function") {106 const self = this107 return (state, ...args) =>108 this.produceWithPatches(state, draft => arg1(draft, ...args))109 }110 // non-curried form111 if (arg3)112 throw new Error("A patch listener cannot be passed to produceWithPatches")113 let patches, inversePatches114 const nextState = this.produce(arg1, arg2, (p, ip) => {115 patches = p116 inversePatches = ip117 })118 return [nextState, patches, inversePatches]119 }

style: use tabsuse-tabsbefore adoptiona9c0fd0

lines 120–149why, one step back
120 createDraft(base) {
121 if (!isDraftable(base)) {122 throw new Error("First argument to `createDraft` must be a plain object, an array, or an immerable object") // prettier-ignore123 }124 const scope = ImmerScope.enter()125 const proxy = this.createProxy(base)126 proxy[DRAFT_STATE].isManual = true127 scope.leave()128 return proxy129 }130 finishDraft(draft, patchListener) {131 const state = draft && draft[DRAFT_STATE]132 if (!state || !state.isManual) {133 throw new Error("First argument to `finishDraft` must be a draft returned by `createDraft`") // prettier-ignore134 }135 if (state.finalized) {136 throw new Error("The given draft is already finalized") // prettier-ignore137 }138 const {scope} = state139 scope.usePatches(patchListener)140 return this.processResult(undefined, scope)141 }142 setAutoFreeze(value) {143 this.autoFreeze = value144 }145 setUseProxies(value) {146 this.useProxies = value147 assign(this, value ? modernProxy : legacyProxy)148 }149 applyPatches(base, patches) {

fix: don't unnecessary modify draft if replaying patches results in a new state anywayMichel Weststratebefore adoption96f2b2e

lines 150–160why, one step back
150 // If a patch replaces the entire state, take that replacement as base
151 // before applying patches152 let i153 for (i = patches.length - 1; i >= 0; i--) {154 const patch = patches[i]155 if (patch.path.length === 0 && patch.op === "replace") {156 base = patch.value157 break158 }159 }160

style: use tabsuse-tabsbefore adoptiona9c0fd0

line 161why, one step back
161 if (isDraft(base)) {

fix: don't unnecessary modify draft if replaying patches results in a new state anywayMichel Weststratebefore adoption96f2b2e

line 162why, one step back
162 // N.B: never hits if some patch a replacement, patches are never drafts

style: use tabsuse-tabsbefore adoptiona9c0fd0

lines 163–165why, one step back
163 return applyPatches(base, patches)
164 }165 // 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 166–168why, one step back
166 return this.produce(base, draft =>
167 applyPatches(draft, patches.slice(i + 1))168 )

style: use tabsuse-tabsbefore adoptiona9c0fd0

lines 169–182why, one step back
169 }
170 /** @internal */171 processResult(result, scope) {172 const baseDraft = scope.drafts[0]173 const isReplaced = result !== undefined && result !== baseDraft174 this.willFinalize(scope, result, isReplaced)175 if (isReplaced) {176 if (baseDraft[DRAFT_STATE].modified) {177 scope.revoke()178 throw new Error("An immer producer returned a new value *and* modified its draft. Either return a new value *or* modify the draft.") // prettier-ignore179 }180 if (isDraftable(result)) {181 // Finalize the result in case it contains (or is) a subset of the draft.182 result = this.finalize(result, null, scope)

BREAKING CHANGE: In development mode, any new value stored in a tree will be deeply frozen. Fixes #412 #363 #260 #230 #313 #229Michel Weststratebefore adoption9fa2581

line 183why, one step back
183 this.maybeFreeze(result)

style: use tabsuse-tabsbefore adoptiona9c0fd0

lines 184–222why, one step back
184 }
185 if (scope.patches) {186 scope.patches.push({187 op: "replace",188 path: [],189 value: result190 })191 scope.inversePatches.push({192 op: "replace",193 path: [],194 value: baseDraft[DRAFT_STATE].base195 })196 }197 } else {198 // Finalize the base draft.199 result = this.finalize(baseDraft, [], scope)200 }201 scope.revoke()202 if (scope.patches) {203 scope.patchListener(scope.patches, scope.inversePatches)204 }205 return result !== NOTHING ? result : undefined206 }207 /**208 * @internal209 * Finalize a draft, returning either the unmodified base state or a modified210 * copy of the base state.211 */212 finalize(draft, path, scope) {213 const state = draft[DRAFT_STATE]214 if (!state) {215 if (Object.isFrozen(draft)) return draft216 return this.finalizeTree(draft, null, scope)217 }218 // Never finalize drafts owned by another scope.219 if (state.scope !== scope) {220 return draft221 }222 if (!state.modified) {

BREAKING CHANGE: In development mode, any new value stored in a tree will be deeply frozen. Fixes #412 #363 #260 #230 #313 #229Michel Weststratebefore adoption9fa2581

line 223why, one step back
223 this.maybeFreeze(state.base, true)

style: use tabsuse-tabsbefore adoptiona9c0fd0

lines 224–228why, one step back
224 return state.base
225 }226 if (!state.finalized) {227 state.finalized = true228 this.finalizeTree(state.draft, path, scope)

Merge branch 'async-recipes'Michel Weststratebefore adoptionff210d8

line 229why, one step back
229

feat: added first class support for `Map` and `Set`Michel Weststratebefore adoptionb6f1d40

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

style: use tabsuse-tabsbefore adoptiona9c0fd0

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

feat: added first class support for `Map` and `Set`Michel Weststratebefore adoptionb6f1d40

lines 235–237why, one step back
235 each(assigned, (prop, exists) => {
236 if (!exists) this.onDelete(state, prop)237 })

style: use tabsuse-tabsbefore adoptiona9c0fd0

line 238why, one step back
238 } else {

feat: added first class support for `Map` and `Set`Michel Weststratebefore adoptionb6f1d40

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

style: use tabsuse-tabsbefore adoptiona9c0fd0

lines 240–248why, one step back
240 const {base, copy} = state
241 each(base, prop => {242 if (!has(copy, prop)) this.onDelete(state, prop)243 })244 }245 }246 if (this.onCopy) {247 this.onCopy(state)248 }

feat: passing drafts to producealeclarsonbefore adoption9c53415

line 249why, one step back
249

style: use tabsuse-tabsbefore adoptiona9c0fd0

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

feat: added first class support for `Map` and `Set`Michel Weststratebefore adoptionb6f1d40

line 253why, one step back
253 freeze(state.copy, false)

style: use tabsuse-tabsbefore adoptiona9c0fd0

line 254why, one step back
254 }

feat: passing drafts to producealeclarsonbefore adoption9c53415

line 255why, one step back
255

style: use tabsuse-tabsbefore adoptiona9c0fd0

lines 256–274why, one step back
256 if (path && scope.patches) {
257 generatePatches(state, path, scope.patches, scope.inversePatches)258 }259 }260 return state.copy261 }262 /**263 * @internal264 * Finalize all drafts in the given state tree.265 */266 finalizeTree(root, rootPath, scope) {267 const state = root[DRAFT_STATE]268 if (state) {269 if (!this.useProxies) {270 // Create the final copy, with added keys and without deleted keys.271 state.copy = shallowCopy(state.draft, true)272 }273 root = state.copy274 }

refactor: Immer#finalizeTree methodaleclarsonbefore adoption483a27a

line 275why, one step back
275

style: use tabsuse-tabsbefore adoptiona9c0fd0

lines 276–280why, one step back
276 const needPatches = !!rootPath && !!scope.patches
277 const finalizeProperty = (prop, value, parent) => {278 if (value === parent) {279 throw Error("Immer forbids circular references")280 }

fix: throw on circular referencesaleclarsonbefore adoption9c6603e

line 281why, one step back
281

style: use tabsuse-tabsbefore adoptiona9c0fd0

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

feat: added first class support for `Map` and `Set`Michel Weststratebefore adoptionb6f1d40

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

feat: add hooks to the `Immer` classaleclarsonbefore adoption7f50364

line 285why, one step back
285

style: use tabsuse-tabsbefore adoptiona9c0fd0

lines 286–287why, one step back
286 if (isDraft(value)) {
287 const path =

feat: added first class support for `Map` and `Set`Michel Weststratebefore adoptionb6f1d40

lines 288–291why, one step back
288 isDraftProp &&
289 needPatches &&290 !isSetMember && // Set objects are atomic since they have no keys.291 !has(state.assigned, prop) // Skip deep patches for assigned keys.

style: use tabsuse-tabsbefore adoptiona9c0fd0

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

feat: passing drafts to producealeclarsonbefore adoption9c53415

line 294why, one step back
294

style: use tabsuse-tabsbefore adoptiona9c0fd0

lines 295–296why, one step back
295 // Drafts owned by `scope` are finalized here.
296 value = this.finalize(value, path, scope)

feat: added first class support for `Map` and `Set`Michel Weststratebefore adoptionb6f1d40

line 297why, one step back
297 replace(parent, prop, value)

Merge branch 'async-recipes'Michel Weststratebefore adoptionff210d8

line 298why, one step back
298

style: use tabsuse-tabsbefore adoptiona9c0fd0

lines 299–302why, one step back
299 // Drafts from another scope must prevent auto-freezing.
300 if (isDraft(value)) {301 scope.canAutoFreeze = false302 }

Merge branch 'async-recipes'Michel Weststratebefore adoptionff210d8

line 303why, one step back
303

style: use tabsuse-tabsbefore adoptiona9c0fd0

line 304why, one step back
304 // Unchanged drafts are never passed to the `onAssign` hook.

feat: added first class support for `Map` and `Set`Michel Weststratebefore adoptionb6f1d40

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

style: use tabsuse-tabsbefore adoptiona9c0fd0

lines 306–307why, one step back
306 }
307 // Unchanged draft properties are ignored.

feat: added first class support for `Map` and `Set`Michel Weststratebefore adoptionb6f1d40

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

style: use tabsuse-tabsbefore adoptiona9c0fd0

lines 309–313why, one step back
309 return
310 }311 // Search new objects for unfinalized drafts. Frozen objects should never contain drafts.312 else if (isDraftable(value) && !Object.isFrozen(value)) {313 each(value, finalizeProperty)

BREAKING CHANGE: In development mode, any new value stored in a tree will be deeply frozen. Fixes #412 #363 #260 #230 #313 #229Michel Weststratebefore adoption9fa2581

line 314why, one step back
314 this.maybeFreeze(value)

style: use tabsuse-tabsbefore adoptiona9c0fd0

line 315why, one step back
315 }

refactor: Immer#finalizeTree methodaleclarsonbefore adoption483a27a

line 316why, one step back
316

feat: added first class support for `Map` and `Set`Michel Weststratebefore adoptionb6f1d40

line 317why, one step back
317 if (isDraftProp && this.onAssign && !isSetMember) {

style: use tabsuse-tabsbefore adoptiona9c0fd0

lines 318–320why, one step back
318 this.onAssign(state, prop, value)
319 }320 }

refactor: Immer#finalizeTree methodaleclarsonbefore adoption483a27a

line 321why, one step back
321

style: use tabsuse-tabsbefore adoptiona9c0fd0

lines 322–323why, one step back
322 each(root, finalizeProperty)
323 return root

BREAKING CHANGE: In development mode, any new value stored in a tree will be deeply frozen. Fixes #412 #363 #260 #230 #313 #229Michel Weststratebefore adoption9fa2581

lines 324–326why, one step back
324 }
325 maybeFreeze(value, deep = false) {326 if (this.autoFreeze && !isDraft(value)) {

feat: added first class support for `Map` and `Set`Michel Weststratebefore adoptionb6f1d40

line 327why, one step back
327 freeze(value, deep)

BREAKING CHANGE: In development mode, any new value stored in a tree will be deeply frozen. Fixes #412 #363 #260 #230 #313 #229Michel Weststratebefore adoption9fa2581

line 328why, one step back
328 }

feat: added first class support for `Map` and `Set`Michel Weststratebefore adoptionb6f1d40

lines 329–347why, one step back
329 }
330}331332function replace(parent, prop, value) {333 if (isMap(parent)) {334 parent.set(prop, value)335 } else if (isSet(parent)) {336 // In this case, the `prop` is actually a draft.337 parent.delete(prop)338 parent.add(value)339 } else if (Array.isArray(parent) || isEnumerable(parent, prop)) {340 // Preserve non-enumerable properties.341 parent[prop] = value342 } else {343 Object.defineProperty(parent, prop, {344 value,345 writable: true,346 configurable: true347 })

style: use tabsuse-tabsbefore adoptiona9c0fd0

line 348why, one step back
348 }

feat: add `Immer` classaleclarsonbefore adoptionecd04dc

line 349why, one step back
349}