Skip to content
Myr

proxy.js

This file

Path

src/proxy.js

434 lines · 12.1 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 1f93af2 point at it.

fix: use proxies only if Reflect exists (#227)Alec Larsonbefore adoption1f93af2

lines 1–2why, one step back
1"use strict"
2import {

fix: always use `assign` polyfillaleclarsonbefore adoption241a648

lines 3–4why, one step back
3 assign,
4 each,

fix: use proxies only if Reflect exists (#227)Alec Larsonbefore adoption1f93af2

line 5why, one step back
5 has,

fix: always use `assign` polyfillaleclarsonbefore adoption241a648

line 6why, one step back
6 is,

feat: add `Immer` classaleclarsonbefore adoptionecd04dc

lines 7–8why, one step back
7 isDraftable,
8 isDraft,

feat: `Map` drafts and patcheskeenondrumsbefore adoption30db0f3

line 9why, one step back
9 isMap,

feat: `Set` draftsAndrey Goncharovbefore adoption4355b63

line 10why, one step back
10 isSet,

fix: use proxies only if Reflect exists (#227)Alec Larsonbefore adoption1f93af2

line 11why, one step back
11 shallowCopy,

feat: `Set` draftsAndrey Goncharovbefore adoption4355b63

lines 12–15why, one step back
12 DRAFT_STATE,
13 assignMap,14 assignSet,15 original

fix: use proxies only if Reflect exists (#227)Alec Larsonbefore adoption1f93af2

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

Merge branch 'async-recipes'Michel Weststratebefore adoptionff210d8

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

fix: use proxies only if Reflect exists (#227)Alec Larsonbefore adoption1f93af2

line 18why, one step back
18

feat: add `Immer` classaleclarsonbefore adoptionecd04dc

lines 19–21why, one step back
19// Do nothing before being finalized.
20export function willFinalize() {}21

chore: reorganize src/proxy.jsAlec Larsonbefore adoption3163a7d

lines 22–26why, one step back
22/**
23 * Returns a new draft of the `base` object.24 *25 * The second argument is the parent draft-state (used internally).26 */

Merge branch 'async-recipes'Michel Weststratebefore adoptionff210d8

lines 27–28why, one step back
27export function createProxy(base, parent) {
28 const scope = parent ? parent.scope : ImmerScope.current

feat: add `Immer` classaleclarsonbefore adoptionecd04dc

line 29why, one step back
29 const state = {

feat: passing drafts to producealeclarsonbefore adoption9c53415

line 30why, one step back
30 // Track which produce call this is associated with.

Merge branch 'async-recipes'Michel Weststratebefore adoptionff210d8

line 31why, one step back
31 scope,

feat: passing drafts to producealeclarsonbefore adoption9c53415

lines 32–38why, one step back
32 // True for both shallow and deep changes.
33 modified: false,34 // Used during finalization.35 finalized: false,36 // Track which properties have been assigned (true) or deleted (false).37 assigned: {},38 // The parent draft state.

feat: add `Immer` classaleclarsonbefore adoptionecd04dc

line 39why, one step back
39 parent,

feat: passing drafts to producealeclarsonbefore adoption9c53415

line 40why, one step back
40 // The base state.

feat: add `Immer` classaleclarsonbefore adoptionecd04dc

line 41why, one step back
41 base,

feat: passing drafts to producealeclarsonbefore adoption9c53415

lines 42–46why, one step back
42 // The base proxy.
43 draft: null,44 // Any property proxies.45 drafts: {},46 // The base copy with any updated values.

feat: add `Immer` classaleclarsonbefore adoptionecd04dc

line 47why, one step back
47 copy: null,

feat: passing drafts to producealeclarsonbefore adoption9c53415

lines 48–49why, one step back
48 // Called by the `produce` function.
49 revoke: null

feat: add `Immer` classaleclarsonbefore adoptionecd04dc

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

feat: `Map` drafts and patcheskeenondrumsbefore adoption30db0f3

lines 52–58why, one step back
52 let proxyTarget = state
53 let traps = objectTraps54 if (Array.isArray(base)) {55 proxyTarget = [state]56 traps = arrayTraps57 } else if (isMap(base)) {58 traps = mapTraps

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

lines 59–61why, one step back
59 // Maps need to support non-primitive keys and objects do not support other objects as keys
60 state.drafts = new Map()61 state.assigned = new Map()

feat: `Set` draftsAndrey Goncharovbefore adoption4355b63

lines 62–65why, one step back
62 } else if (isSet(base)) {
63 traps = setTraps64 // We use values of a Set as keys and objects do not support other objects as keys65 state.drafts = new Map()

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

line 66why, one step back
66 // Sets do not need .assigned override since you cannot really assign (read as 'replace') any value in s Set. You can only add or remove values

feat: `Map` drafts and patcheskeenondrumsbefore adoption30db0f3

line 67why, one step back
67 }

feat: add `Immer` classaleclarsonbefore adoptionecd04dc

line 68why, one step back
68

feat: `Map` drafts and patcheskeenondrumsbefore adoption30db0f3

lines 69–70why, one step back
69 const {revoke, proxy} = Proxy.revocable(proxyTarget, traps)
70

feat: add `Immer` classaleclarsonbefore adoptionecd04dc

lines 71–73why, one step back
71 state.draft = proxy
72 state.revoke = revoke73

Merge branch 'async-recipes'Michel Weststratebefore adoptionff210d8

line 74why, one step back
74 scope.drafts.push(proxy)

feat: add `Immer` classaleclarsonbefore adoptionecd04dc

lines 75–77why, one step back
75 return proxy
76}77

chore: reorganize src/proxy.jsAlec Larsonbefore adoption3163a7d

lines 78–81why, one step back
78/**
79 * Object drafts80 */81

fix: use proxies only if Reflect exists (#227)Alec Larsonbefore adoption1f93af2

line 82why, one step back
82const objectTraps = {

chore: reorganize src/proxy.jsAlec Larsonbefore adoption3163a7d

lines 83–106why, one step back
83 get(state, prop) {
84 if (prop === DRAFT_STATE) return state85 let {drafts} = state8687 // Check for existing draft in unmodified state.88 if (!state.modified && has(drafts, prop)) {89 return drafts[prop]90 }9192 const value = source(state)[prop]93 if (state.finalized || !isDraftable(value)) {94 return value95 }9697 // Check for existing draft in modified state.98 if (state.modified) {99 // Assigned values are never drafted. This catches any drafts we created, too.100 if (value !== peek(state.base, prop)) return value101 // Store drafts on the copy (when one exists).102 drafts = state.copy103 }104105 return (drafts[prop] = createProxy(value, state))106 },

nit: argument namesAlec Larsonbefore adoptiona674a78

lines 107–108why, one step back
107 has(state, prop) {
108 return prop in source(state)

chore: reorganize src/proxy.jsAlec Larsonbefore adoptione809ffc

line 109why, one step back
109 },

nit: argument namesAlec Larsonbefore adoptiona674a78

lines 110–111why, one step back
110 ownKeys(state) {
111 return Reflect.ownKeys(source(state))

fix: use proxies only if Reflect exists (#227)Alec Larsonbefore adoption1f93af2

line 112why, one step back
112 },

chore: reorganize src/proxy.jsAlec Larsonbefore adoption3163a7d

lines 113–148why, one step back
113 set(state, prop, value) {
114 if (!state.modified) {115 const baseValue = peek(state.base, prop)116 // Optimize based on value's truthiness. Truthy values are guaranteed to117 // never be undefined, so we can avoid the `in` operator. Lastly, truthy118 // values may be drafts, but falsy values are never drafts.119 const isUnchanged = value120 ? is(baseValue, value) || value === state.drafts[prop]121 : is(baseValue, value) && prop in state.base122 if (isUnchanged) return true123 markChanged(state)124 }125 state.assigned[prop] = true126 state.copy[prop] = value127 return true128 },129 deleteProperty(state, prop) {130 // The `undefined` check is a fast path for pre-existing keys.131 if (peek(state.base, prop) !== undefined || prop in state.base) {132 state.assigned[prop] = false133 markChanged(state)134 }135 if (state.copy) delete state.copy[prop]136 return true137 },138 // Note: We never coerce `desc.value` into an Immer draft, because we can't make139 // the same guarantee in ES5 mode.140 getOwnPropertyDescriptor(state, prop) {141 const owner = source(state)142 const desc = Reflect.getOwnPropertyDescriptor(owner, prop)143 if (desc) {144 desc.writable = true145 desc.configurable = !Array.isArray(owner) || prop !== "length"146 }147 return desc148 },

feat: limited class supportaleclarsonbefore adoption9877d64

lines 149–151why, one step back
149 defineProperty() {
150 throw new Error("Object.defineProperty() cannot be used on an Immer draft") // prettier-ignore151 },

nit: argument namesAlec Larsonbefore adoptiona674a78

lines 152–153why, one step back
152 getPrototypeOf(state) {
153 return Object.getPrototypeOf(state.base)

fix: Object.getPrototypeOf with a draftaleclarsonbefore adoptiond5d07e8

line 154why, one step back
154 },

fix: use proxies only if Reflect exists (#227)Alec Larsonbefore adoption1f93af2

line 155why, one step back
155 setPrototypeOf() {

feat: limited class supportaleclarsonbefore adoption9877d64

line 156why, one step back
156 throw new Error("Object.setPrototypeOf() cannot be used on an Immer draft") // prettier-ignore

fix: use proxies only if Reflect exists (#227)Alec Larsonbefore adoption1f93af2

lines 157–159why, one step back
157 }
158}159

chore: reorganize src/proxy.jsAlec Larsonbefore adoption3163a7d

lines 160–163why, one step back
160/**
161 * Array drafts162 */163

fix: use proxies only if Reflect exists (#227)Alec Larsonbefore adoption1f93af2

lines 164–171why, one step back
164const arrayTraps = {}
165each(objectTraps, (key, fn) => {166 arrayTraps[key] = function() {167 arguments[0] = arguments[0][0]168 return fn.apply(this, arguments)169 }170})171arrayTraps.deleteProperty = function(state, prop) {

feat: limited class supportaleclarsonbefore adoption9877d64

lines 172–174why, one step back
172 if (isNaN(parseInt(prop))) {
173 throw new Error("Immer only supports deleting array indices") // prettier-ignore174 }

fix: use proxies only if Reflect exists (#227)Alec Larsonbefore adoption1f93af2

lines 175–177why, one step back
175 return objectTraps.deleteProperty.call(this, state[0], prop)
176}177arrayTraps.set = function(state, prop, value) {

feat: limited class supportaleclarsonbefore adoption9877d64

lines 178–180why, one step back
178 if (prop !== "length" && isNaN(parseInt(prop))) {
179 throw new Error("Immer only supports setting array indices and the 'length' property") // prettier-ignore180 }

fix: use proxies only if Reflect exists (#227)Alec Larsonbefore adoption1f93af2

line 181why, one step back
181 return objectTraps.set.call(this, state[0], prop, value)

feat: `Map` drafts and patcheskeenondrumsbefore adoption30db0f3

lines 182–183why, one step back
182}
183

refactor: makeTrapsForGetters functionAlec Larsonbefore adoption5093fd0

lines 184–196why, one step back
184// Used by Map and Set drafts
185const reflectTraps = makeReflectTraps([186 "ownKeys",187 "has",188 "set",189 "deleteProperty",190 "defineProperty",191 "getOwnPropertyDescriptor",192 "preventExtensions",193 "isExtensible",194 "getPrototypeOf"195])196

chore: reorganize src/proxy.jsAlec Larsonbefore adoption3163a7d

lines 197–200why, one step back
197/**
198 * Map drafts199 */200

refactor: makeTrapsForGetters functionAlec Larsonbefore adoption5093fd0

line 201why, one step back
201const mapTraps = makeTrapsForGetters({

fix: add Map getter for DRAFT_STATE, make isEnumerable more resilientkeenondrumsbefore adoption7bbec0a

line 202why, one step back
202 [DRAFT_STATE]: state => state,

chore: reorganize src/proxy.jsAlec Larsonbefore adoption3163a7d

lines 203–208why, one step back
203 size: state => source(state).size,
204 has(state, prop) {205 state = source(state)206 return state.has.bind(state)207 },208 set: state => (key, value) => {

feat: `Set` draftsAndrey Goncharovbefore adoption4355b63

lines 209–211why, one step back
209 const stateSource = source(state)
210 if (!stateSource.has(key) || stateSource.get(key) !== value) {211 markChanged(state)

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

line 212why, one step back
212 state.assigned.set(key, true)

feat: `Set` draftsAndrey Goncharovbefore adoption4355b63

lines 213–214why, one step back
213 state.copy.set(key, value)
214 }

fix: Map.prototype.set should return a draftAndrey Goncharovbefore adoption7001201

line 215why, one step back
215 return state.draft

chore: reorganize src/proxy.jsAlec Larsonbefore adoption3163a7d

lines 216–217why, one step back
216 },
217 delete: state => key => {

feat: `onDelete` for `Maps`keenondrumsbefore adoption1ca49ef

lines 218–223why, one step back
218 if (source(state).has(key)) {
219 markChanged(state)220 state.assigned.set(key, false)221 return state.copy.delete(key)222 }223 return false

chore: reorganize src/proxy.jsAlec Larsonbefore adoption3163a7d

lines 224–226why, one step back
224 },
225 clear: state => () => {226 markChanged(state)

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

line 227why, one step back
227 state.assigned = new Map()

chore: reorganize src/proxy.jsAlec Larsonbefore adoption3163a7d

line 228why, one step back
228 for (const key of source(state).keys()) {

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

line 229why, one step back
229 state.assigned.set(key, false)

feat: `Map` drafts and patcheskeenondrumsbefore adoption30db0f3

line 230why, one step back
230 }

chore: reorganize src/proxy.jsAlec Larsonbefore adoption3163a7d

lines 231–238why, one step back
231 return state.copy.clear()
232 },233 forEach: (state, _, receiver) => (cb, thisArg) =>234 source(state).forEach((_, key, map) => {235 const value = receiver.get(key)236 cb.call(thisArg, value, key, map)237 }),238 get: state => key => {

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

lines 239–240why, one step back
239 if (!state.modified && state.drafts.has(key)) {
240 return state.drafts.get(key)

feat: `Map` drafts and patcheskeenondrumsbefore adoption30db0f3

line 241why, one step back
241 }

chore: reorganize src/proxy.jsAlec Larsonbefore adoption3163a7d

lines 242–244why, one step back
242
243 if (state.modified && state.copy.has(key)) {244 return state.copy.get(key)

feat: `Map` drafts and patcheskeenondrumsbefore adoption30db0f3

line 245why, one step back
245 }

chore: reorganize src/proxy.jsAlec Larsonbefore adoption3163a7d

lines 246–250why, one step back
246
247 const value = source(state).get(key)248249 if (state.finalized || !isDraftable(value)) {250 return value

feat: `Map` drafts and patcheskeenondrumsbefore adoption30db0f3

lines 251–252why, one step back
251 }
252

chore: reorganize src/proxy.jsAlec Larsonbefore adoption3163a7d

line 253why, one step back
253 const draft = createProxy(value, state)

feat: `Map` drafts and patcheskeenondrumsbefore adoption30db0f3

line 254why, one step back
254

chore: reorganize src/proxy.jsAlec Larsonbefore adoption3163a7d

line 255why, one step back
255 if (!state.modified) {

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

line 256why, one step back
256 state.drafts.set(key, draft)

chore: reorganize src/proxy.jsAlec Larsonbefore adoption3163a7d

lines 257–259why, one step back
257 } else {
258 state.copy.set(key, draft)259 }

feat: `Map` drafts and patcheskeenondrumsbefore adoption30db0f3

line 260why, one step back
260

chore: reorganize src/proxy.jsAlec Larsonbefore adoption3163a7d

lines 261–262why, one step back
261 return draft
262 },

refactor: simplify mapGetters.keysAlec Larsonbefore adoption3298a77

line 263why, one step back
263 keys: state => () => source(state).keys(),

chore: reorganize src/proxy.jsAlec Larsonbefore adoption3163a7d

lines 264–266why, one step back
264 values: iterateMapValues,
265 entries: iterateMapValues,266 [Symbol.iterator]: iterateMapValues

refactor: makeTrapsForGetters functionAlec Larsonbefore adoption5093fd0

line 267why, one step back
267})

feat: `Map` drafts and patcheskeenondrumsbefore adoption30db0f3

line 268why, one step back
268

chore: reorganize src/proxy.jsAlec Larsonbefore adoption3163a7d

lines 269–273why, one step back
269/** Map.prototype.values _-or-_ Map.prototype.entries */
270function iterateMapValues(state, prop, receiver) {271 const getYieldable =272 prop === "values" ? (key, value) => value : (key, value) => [key, value]273

fix: remove "function*" syntaxAlec Larsonbefore adoption08d88b8

line 274why, one step back
274 return () => {

chore: reorganize src/proxy.jsAlec Larsonbefore adoption3163a7d

line 275why, one step back
275 const iterator = source(state)[Symbol.iterator]()

fix: remove "function*" syntaxAlec Larsonbefore adoption08d88b8

lines 276–284why, one step back
276 return makeIterable(() => {
277 const result = iterator.next()278 if (!result.done) {279 const [key] = result.value280 const value = receiver.get(key)281 result.value = getYieldable(key, value)282 }283 return result284 })

feat: `Map` drafts and patcheskeenondrumsbefore adoption30db0f3

line 285why, one step back
285 }

feat: `Map` supportkeenondrumsbefore adoption8276a6c

lines 286–287why, one step back
286}
287

chore: reorganize src/proxy.jsAlec Larsonbefore adoption3163a7d

line 288why, one step back
288/**

feat: `Set` draftsAndrey Goncharovbefore adoption4355b63

lines 289–291why, one step back
289 * Set drafts
290 */291

refactor: makeTrapsForGetters functionAlec Larsonbefore adoption5093fd0

line 292why, one step back
292const setTraps = makeTrapsForGetters({

feat: `Set` draftsAndrey Goncharovbefore adoption4355b63

lines 293–325why, one step back
293 [DRAFT_STATE]: state => state,
294 size: state => source(state).size,295 has(state, prop) {296 state = source(state)297 return state.has.bind(state)298 },299 add: state => value => {300 if (!source(state).has(value)) {301 markChanged(state)302 state.copy.add(value)303 }304 return state.draft305 },306 delete: state => value => {307 markChanged(state)308 return state.copy.delete(value)309 },310 clear: state => () => {311 markChanged(state)312 return state.copy.clear()313 },314 forEach: state => (cb, thisArg) => {315 const iterator = iterateSetValues(state)()316 let result = iterator.next()317 while (!result.done) {318 cb.call(thisArg, result.value, result.value, state.draft)319 result = iterator.next()320 }321 },322 keys: iterateSetValues,323 values: iterateSetValues,324 entries: iterateSetValues,325 [Symbol.iterator]: iterateSetValues

refactor: makeTrapsForGetters functionAlec Larsonbefore adoption5093fd0

line 326why, one step back
326})

feat: `Set` draftsAndrey Goncharovbefore adoption4355b63

lines 327–362why, one step back
327
328function iterateSetValues(state, prop) {329 return () => {330 const iterator = source(state)[Symbol.iterator]()331332 return makeIterable(() => {333 const result = iterator.next()334 if (!result.done) {335 const valueWrapped = wrapSetValue(state, result.value)336 result.value = valueWrapped337 if (prop === "entries") {338 result.value = [valueWrapped, valueWrapped]339 }340 }341 return result342 })343 }344}345346function wrapSetValue(state, value) {347 const key = original(value) || value348 let draft = state.drafts.get(key)349 if (!draft) {350 if (state.finalized || !isDraftable(value)) {351 return value352 }353 draft = createProxy(value, state)354 state.drafts.set(key, draft)355 if (state.modified) {356 state.copy.add(draft)357 }358 }359 return draft360}361362/**

chore: reorganize src/proxy.jsAlec Larsonbefore adoption3163a7d

lines 363–365why, one step back
363 * Helpers
364 */365

fix: revert Map supportAlec Larsonbefore adoption47529d3

lines 366–369why, one step back
366// returns the object we should be reading the current value from, which is base, until some change has been made
367function source(state) {368 return state.copy || state.base369}

chore: reorganize src/proxy.jsAlec Larsonbefore adoptione809ffc

line 370why, one step back
370

fix: revert Map supportAlec Larsonbefore adoption47529d3

lines 371–378why, one step back
371// Access a property without creating an Immer draft.
372function peek(draft, prop) {373 const state = draft[DRAFT_STATE]374 const desc = Reflect.getOwnPropertyDescriptor(375 state ? source(state) : draft,376 prop377 )378 return desc && desc.value

fix: use proxies only if Reflect exists (#227)Alec Larsonbefore adoption1f93af2

lines 379–383why, one step back
379}
380381function markChanged(state) {382 if (!state.modified) {383 state.modified = true

refactor: markChanged functionAlec Larsonbefore adoption5857d63

lines 384–395why, one step back
384
385 const {base, drafts, parent} = state386 const copy = shallowCopy(base)387388 if (isSet(base)) {389 // Note: The `drafts` property is preserved for Set objects, since390 // we need to keep track of which values are drafted.391 assignSet(copy, drafts)392 } else {393 // Merge nested drafts into the copy.394 if (isMap(base)) assignMap(copy, drafts)395 else assign(copy, drafts)

feat: `Set` draftsAndrey Goncharovbefore adoption4355b63

lines 396–397why, one step back
396 state.drafts = null
397 }

refactor: markChanged functionAlec Larsonbefore adoption5857d63

lines 398–402why, one step back
398
399 state.copy = copy400 if (parent) {401 markChanged(parent)402 }

fix: use proxies only if Reflect exists (#227)Alec Larsonbefore adoption1f93af2

line 403why, one step back
403 }

fix: remove "function*" syntaxAlec Larsonbefore adoption08d88b8

lines 404–411why, one step back
404}
405406function makeIterable(next) {407 let self408 return (self = {409 [Symbol.iterator]: () => self,410 next411 })

refactor: traps for Maps and Setskeenondrumsbefore adoptiondd82d89

lines 412–413why, one step back
412}
413

refactor: makeTrapsForGetters functionAlec Larsonbefore adoption5093fd0

lines 414–421why, one step back
414/** Create traps that all use the `Reflect` API on the `source(state)` */
415function makeReflectTraps(names) {416 return names.reduce((traps, name) => {417 traps[name] = (state, ...args) => Reflect[name](source(state), ...args)418 return traps419 }, {})420}421

refactor: traps for Maps and Setskeenondrumsbefore adoptiondd82d89

lines 422–423why, one step back
422function makeTrapsForGetters(getters) {
423 return {

refactor: makeTrapsForGetters functionAlec Larsonbefore adoption5093fd0

line 424why, one step back
424 ...reflectTraps,

refactor: traps for Maps and Setskeenondrumsbefore adoptiondd82d89

lines 425–428why, one step back
425 get(state, prop, receiver) {
426 return getters.hasOwnProperty(prop)427 ? getters[prop](state, prop, receiver)428 : Reflect.get(state, prop, receiver)

fix: add more traps for Maps and SetsAndrey Goncharovbefore adoption930b4ab

lines 429–431why, one step back
429 },
430 setPrototypeOf(state) {431 throw new Error("Object.setPrototypeOf() cannot be used on an Immer draft") // prettier-ignore

refactor: traps for Maps and Setskeenondrumsbefore adoptiondd82d89

lines 432–433why, one step back
432 }
433 }

fix: use proxies only if Reflect exists (#227)Alec Larsonbefore adoption1f93af2

line 434why, one step back
434}