Skip to content
Myr

immer.js

This file

Path

src/immer.js

283 lines · 7.6 KiB · JavaScript

Last changed by

style: use tabsuse-tabsbefore adoptiona9c0fd0

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–14why, one step back
5 assign,
6 each,7 has,8 is,9 isDraft,10 isDraftable,11 isEnumerable,12 shallowCopy,13 DRAFT_STATE,14 NOTHING

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

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

Merge branch 'async-recipes'Michel Weststratebefore adoptionff210d8

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

Merge pull request #237 from mweststrate/curryMichel Weststratebefore adoption7d2f308

line 17why, one step back
17

feat: add `Immer` classaleclarsonbefore adoptionecd04dc

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

Merge pull request #237 from mweststrate/curryMichel Weststratebefore adoption7d2f308

line 19why, one step back
19

feat: add `Immer` classaleclarsonbefore adoptionecd04dc

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

style: use tabsuse-tabsbefore adoptiona9c0fd0

lines 21–28why, one step back
21 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: null

feat: add `Immer` classaleclarsonbefore adoptionecd04dc

line 29why, one step back
29}

Merge pull request #237 from mweststrate/curryMichel Weststratebefore adoption7d2f308

line 30why, one step back
30

feat: add `Immer` classaleclarsonbefore adoptionecd04dc

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

style: use tabsuse-tabsbefore adoptiona9c0fd0

lines 32–41why, one step back
32 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 = base

Merge pull request #237 from mweststrate/curryMichel Weststratebefore adoption7d2f308

line 42why, one step back
42

style: use tabsuse-tabsbefore adoptiona9c0fd0

lines 43–47why, one step back
43 const self = this
44 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 back
48

style: use tabsuse-tabsbefore adoptiona9c0fd0

lines 49–57why, one step back
49 // prettier-ignore
50 {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 back
58

style: use tabsuse-tabsbefore adoptiona9c0fd0

line 59why, one step back
59 let result

nit: dedupe some codealeclarsonbefore adoptionc9e1d98

line 60why, one step back
60

style: use tabsuse-tabsbefore adoptiona9c0fd0

lines 61–187why, one step back
61 // 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 }94 createDraft(base) {95 if (!isDraftable(base)) {96 throw new Error("First argument to `createDraft` must be a plain object, an array, or an immerable object") // prettier-ignore97 }98 const scope = ImmerScope.enter()99 const proxy = this.createProxy(base)100 proxy[DRAFT_STATE].isManual = true101 scope.leave()102 return proxy103 }104 finishDraft(draft, patchListener) {105 const state = draft && draft[DRAFT_STATE]106 if (!state || !state.isManual) {107 throw new Error("First argument to `finishDraft` must be a draft returned by `createDraft`") // prettier-ignore108 }109 if (state.finalized) {110 throw new Error("The given draft is already finalized") // prettier-ignore111 }112 const {scope} = state113 scope.usePatches(patchListener)114 return this.processResult(undefined, scope)115 }116 setAutoFreeze(value) {117 this.autoFreeze = value118 }119 setUseProxies(value) {120 this.useProxies = value121 assign(this, value ? modernProxy : legacyProxy)122 }123 applyPatches(base, patches) {124 // Mutate the base state when a draft is passed.125 if (isDraft(base)) {126 return applyPatches(base, patches)127 }128 // Otherwise, produce a copy of the base state.129 return this.produce(base, draft => applyPatches(draft, patches))130 }131 /** @internal */132 processResult(result, scope) {133 const baseDraft = scope.drafts[0]134 const isReplaced = result !== undefined && result !== baseDraft135 this.willFinalize(scope, result, isReplaced)136 if (isReplaced) {137 if (baseDraft[DRAFT_STATE].modified) {138 scope.revoke()139 throw new Error("An immer producer returned a new value *and* modified its draft. Either return a new value *or* modify the draft.") // prettier-ignore140 }141 if (isDraftable(result)) {142 // Finalize the result in case it contains (or is) a subset of the draft.143 result = this.finalize(result, null, scope)144 }145 if (scope.patches) {146 scope.patches.push({147 op: "replace",148 path: [],149 value: result150 })151 scope.inversePatches.push({152 op: "replace",153 path: [],154 value: baseDraft[DRAFT_STATE].base155 })156 }157 } else {158 // Finalize the base draft.159 result = this.finalize(baseDraft, [], scope)160 }161 scope.revoke()162 if (scope.patches) {163 scope.patchListener(scope.patches, scope.inversePatches)164 }165 return result !== NOTHING ? result : undefined166 }167 /**168 * @internal169 * Finalize a draft, returning either the unmodified base state or a modified170 * copy of the base state.171 */172 finalize(draft, path, scope) {173 const state = draft[DRAFT_STATE]174 if (!state) {175 if (Object.isFrozen(draft)) return draft176 return this.finalizeTree(draft, null, scope)177 }178 // Never finalize drafts owned by another scope.179 if (state.scope !== scope) {180 return draft181 }182 if (!state.modified) {183 return state.base184 }185 if (!state.finalized) {186 state.finalized = true187 this.finalizeTree(state.draft, path, scope)

Merge branch 'async-recipes'Michel Weststratebefore adoptionff210d8

line 188why, one step back
188

style: use tabsuse-tabsbefore adoptiona9c0fd0

lines 189–205why, one step back
189 if (this.onDelete) {
190 // The `assigned` object is unreliable with ES5 drafts.191 if (this.useProxies) {192 const {assigned} = state193 for (const prop in assigned) {194 if (!assigned[prop]) this.onDelete(state, prop)195 }196 } else {197 const {base, copy} = state198 each(base, prop => {199 if (!has(copy, prop)) this.onDelete(state, prop)200 })201 }202 }203 if (this.onCopy) {204 this.onCopy(state)205 }

feat: passing drafts to producealeclarsonbefore adoption9c53415

line 206why, one step back
206

style: use tabsuse-tabsbefore adoptiona9c0fd0

lines 207–211why, one step back
207 // At this point, all descendants of `state.copy` have been finalized,
208 // so we can be sure that `scope.canAutoFreeze` is accurate.209 if (this.autoFreeze && scope.canAutoFreeze) {210 Object.freeze(state.copy)211 }

feat: passing drafts to producealeclarsonbefore adoption9c53415

line 212why, one step back
212

style: use tabsuse-tabsbefore adoptiona9c0fd0

lines 213–231why, one step back
213 if (path && scope.patches) {
214 generatePatches(state, path, scope.patches, scope.inversePatches)215 }216 }217 return state.copy218 }219 /**220 * @internal221 * Finalize all drafts in the given state tree.222 */223 finalizeTree(root, rootPath, scope) {224 const state = root[DRAFT_STATE]225 if (state) {226 if (!this.useProxies) {227 // Create the final copy, with added keys and without deleted keys.228 state.copy = shallowCopy(state.draft, true)229 }230 root = state.copy231 }

refactor: Immer#finalizeTree methodaleclarsonbefore adoption483a27a

line 232why, one step back
232

style: use tabsuse-tabsbefore adoptiona9c0fd0

lines 233–237why, one step back
233 const needPatches = !!rootPath && !!scope.patches
234 const finalizeProperty = (prop, value, parent) => {235 if (value === parent) {236 throw Error("Immer forbids circular references")237 }

fix: throw on circular referencesaleclarsonbefore adoption9c6603e

line 238why, one step back
238

style: use tabsuse-tabsbefore adoptiona9c0fd0

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

feat: add hooks to the `Immer` classaleclarsonbefore adoption7f50364

line 241why, one step back
241

style: use tabsuse-tabsbefore adoptiona9c0fd0

lines 242–246why, one step back
242 if (isDraft(value)) {
243 const path =244 isDraftProp && needPatches && !state.assigned[prop]245 ? rootPath.concat(prop)246 : null

feat: passing drafts to producealeclarsonbefore adoption9c53415

line 247why, one step back
247

style: use tabsuse-tabsbefore adoptiona9c0fd0

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

Merge branch 'async-recipes'Michel Weststratebefore adoptionff210d8

line 250why, one step back
250

style: use tabsuse-tabsbefore adoptiona9c0fd0

lines 251–254why, one step back
251 // Drafts from another scope must prevent auto-freezing.
252 if (isDraft(value)) {253 scope.canAutoFreeze = false254 }

Merge branch 'async-recipes'Michel Weststratebefore adoptionff210d8

line 255why, one step back
255

style: use tabsuse-tabsbefore adoptiona9c0fd0

lines 256–261why, one step back
256 // Preserve non-enumerable properties.
257 if (Array.isArray(parent) || isEnumerable(parent, prop)) {258 parent[prop] = value259 } else {260 Object.defineProperty(parent, prop, {value})261 }

feat: limited class supportaleclarsonbefore adoption9877d64

line 262why, one step back
262

style: use tabsuse-tabsbefore adoptiona9c0fd0

lines 263–273why, one step back
263 // Unchanged drafts are never passed to the `onAssign` hook.
264 if (isDraftProp && value === state.base[prop]) return265 }266 // Unchanged draft properties are ignored.267 else if (isDraftProp && is(value, state.base[prop])) {268 return269 }270 // Search new objects for unfinalized drafts. Frozen objects should never contain drafts.271 else if (isDraftable(value) && !Object.isFrozen(value)) {272 each(value, finalizeProperty)273 }

refactor: Immer#finalizeTree methodaleclarsonbefore adoption483a27a

line 274why, one step back
274

style: use tabsuse-tabsbefore adoptiona9c0fd0

lines 275–278why, one step back
275 if (isDraftProp && this.onAssign) {
276 this.onAssign(state, prop, value)277 }278 }

refactor: Immer#finalizeTree methodaleclarsonbefore adoption483a27a

line 279why, one step back
279

style: use tabsuse-tabsbefore adoptiona9c0fd0

lines 280–282why, one step back
280 each(root, finalizeProperty)
281 return root282 }

feat: add `Immer` classaleclarsonbefore adoptionecd04dc

line 283why, one step back
283}