Skip to content
Myr

proxy.js

This file

Path

src/proxy.js

407 lines · 11.3 KiB · JavaScript

Last changed by

feat: `Set` draftsAndrey Goncharovbefore adoption4355b63

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: `Set` draftsAndrey Goncharovbefore adoption4355b63

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

feat: `Map` drafts and patcheskeenondrumsbefore adoption30db0f3

line 63why, one step back
63 }

feat: add `Immer` classaleclarsonbefore adoptionecd04dc

line 64why, one step back
64

feat: `Map` drafts and patcheskeenondrumsbefore adoption30db0f3

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

feat: add `Immer` classaleclarsonbefore adoptionecd04dc

lines 67–69why, one step back
67 state.draft = proxy
68 state.revoke = revoke69

Merge branch 'async-recipes'Michel Weststratebefore adoptionff210d8

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

feat: add `Immer` classaleclarsonbefore adoptionecd04dc

lines 71–73why, one step back
71 return proxy
72}73

chore: reorganize src/proxy.jsAlec Larsonbefore adoption3163a7d

lines 74–77why, one step back
74/**
75 * Object drafts76 */77

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

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

chore: reorganize src/proxy.jsAlec Larsonbefore adoption3163a7d

lines 79–102why, one step back
79 get(state, prop) {
80 if (prop === DRAFT_STATE) return state81 let {drafts} = state8283 // Check for existing draft in unmodified state.84 if (!state.modified && has(drafts, prop)) {85 return drafts[prop]86 }8788 const value = source(state)[prop]89 if (state.finalized || !isDraftable(value)) {90 return value91 }9293 // Check for existing draft in modified state.94 if (state.modified) {95 // Assigned values are never drafted. This catches any drafts we created, too.96 if (value !== peek(state.base, prop)) return value97 // Store drafts on the copy (when one exists).98 drafts = state.copy99 }100101 return (drafts[prop] = createProxy(value, state))102 },

nit: argument namesAlec Larsonbefore adoptiona674a78

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

chore: reorganize src/proxy.jsAlec Larsonbefore adoptione809ffc

line 105why, one step back
105 },

nit: argument namesAlec Larsonbefore adoptiona674a78

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

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

line 108why, one step back
108 },

chore: reorganize src/proxy.jsAlec Larsonbefore adoption3163a7d

lines 109–144why, one step back
109 set(state, prop, value) {
110 if (!state.modified) {111 const baseValue = peek(state.base, prop)112 // Optimize based on value's truthiness. Truthy values are guaranteed to113 // never be undefined, so we can avoid the `in` operator. Lastly, truthy114 // values may be drafts, but falsy values are never drafts.115 const isUnchanged = value116 ? is(baseValue, value) || value === state.drafts[prop]117 : is(baseValue, value) && prop in state.base118 if (isUnchanged) return true119 markChanged(state)120 }121 state.assigned[prop] = true122 state.copy[prop] = value123 return true124 },125 deleteProperty(state, prop) {126 // The `undefined` check is a fast path for pre-existing keys.127 if (peek(state.base, prop) !== undefined || prop in state.base) {128 state.assigned[prop] = false129 markChanged(state)130 }131 if (state.copy) delete state.copy[prop]132 return true133 },134 // Note: We never coerce `desc.value` into an Immer draft, because we can't make135 // the same guarantee in ES5 mode.136 getOwnPropertyDescriptor(state, prop) {137 const owner = source(state)138 const desc = Reflect.getOwnPropertyDescriptor(owner, prop)139 if (desc) {140 desc.writable = true141 desc.configurable = !Array.isArray(owner) || prop !== "length"142 }143 return desc144 },

feat: limited class supportaleclarsonbefore adoption9877d64

lines 145–147why, one step back
145 defineProperty() {
146 throw new Error("Object.defineProperty() cannot be used on an Immer draft") // prettier-ignore147 },

nit: argument namesAlec Larsonbefore adoptiona674a78

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

fix: Object.getPrototypeOf with a draftaleclarsonbefore adoptiond5d07e8

line 150why, one step back
150 },

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

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

feat: limited class supportaleclarsonbefore adoption9877d64

line 152why, one step back
152 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 153–155why, one step back
153 }
154}155

chore: reorganize src/proxy.jsAlec Larsonbefore adoption3163a7d

lines 156–159why, one step back
156/**
157 * Array drafts158 */159

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

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

feat: limited class supportaleclarsonbefore adoption9877d64

lines 168–170why, one step back
168 if (isNaN(parseInt(prop))) {
169 throw new Error("Immer only supports deleting array indices") // prettier-ignore170 }

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

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

feat: limited class supportaleclarsonbefore adoption9877d64

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

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

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

feat: `Map` drafts and patcheskeenondrumsbefore adoption30db0f3

lines 178–179why, one step back
178}
179

chore: reorganize src/proxy.jsAlec Larsonbefore adoption3163a7d

lines 180–183why, one step back
180/**
181 * Map drafts182 */183

feat: `Map` drafts and patcheskeenondrumsbefore adoption30db0f3

lines 184–185why, one step back
184const mapTraps = {
185 get(state, prop, receiver) {

feat: `Set` draftsAndrey Goncharovbefore adoption4355b63

lines 186–187why, one step back
186 return mapGetters.hasOwnProperty(prop)
187 ? mapGetters[prop](state, prop, receiver)

chore: reorganize src/proxy.jsAlec Larsonbefore adoption3163a7d

lines 188–191why, one step back
188 : Reflect.get(state, prop, receiver)
189 }190}191const mapGetters = {

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

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

chore: reorganize src/proxy.jsAlec Larsonbefore adoption3163a7d

lines 193–198why, one step back
193 size: state => source(state).size,
194 has(state, prop) {195 state = source(state)196 return state.has.bind(state)197 },198 set: state => (key, value) => {

feat: `Set` draftsAndrey Goncharovbefore adoption4355b63

lines 199–204why, one step back
199 const stateSource = source(state)
200 if (!stateSource.has(key) || stateSource.get(key) !== value) {201 markChanged(state)202 state.assigned[key] = true203 state.copy.set(key, value)204 }

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

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

chore: reorganize src/proxy.jsAlec Larsonbefore adoption3163a7d

lines 206–216why, one step back
206 },
207 delete: state => key => {208 markChanged(state)209 state.assigned[key] = false210 return state.copy.delete(key)211 },212 clear: state => () => {213 markChanged(state)214 state.assigned = {}215 for (const key of source(state).keys()) {216 state.assigned[key] = false

feat: `Map` drafts and patcheskeenondrumsbefore adoption30db0f3

line 217why, one step back
217 }

chore: reorganize src/proxy.jsAlec Larsonbefore adoption3163a7d

lines 218–227why, one step back
218 return state.copy.clear()
219 },220 forEach: (state, _, receiver) => (cb, thisArg) =>221 source(state).forEach((_, key, map) => {222 const value = receiver.get(key)223 cb.call(thisArg, value, key, map)224 }),225 get: state => key => {226 if (!state.modified && has(state.drafts, key)) {227 return state.drafts[key]

feat: `Map` drafts and patcheskeenondrumsbefore adoption30db0f3

line 228why, one step back
228 }

chore: reorganize src/proxy.jsAlec Larsonbefore adoption3163a7d

lines 229–231why, one step back
229
230 if (state.modified && state.copy.has(key)) {231 return state.copy.get(key)

feat: `Map` drafts and patcheskeenondrumsbefore adoption30db0f3

line 232why, one step back
232 }

chore: reorganize src/proxy.jsAlec Larsonbefore adoption3163a7d

lines 233–237why, one step back
233
234 const value = source(state).get(key)235236 if (state.finalized || !isDraftable(value)) {237 return value

feat: `Map` drafts and patcheskeenondrumsbefore adoption30db0f3

lines 238–239why, one step back
238 }
239

chore: reorganize src/proxy.jsAlec Larsonbefore adoption3163a7d

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

feat: `Map` drafts and patcheskeenondrumsbefore adoption30db0f3

line 241why, one step back
241

chore: reorganize src/proxy.jsAlec Larsonbefore adoption3163a7d

lines 242–246why, one step back
242 if (!state.modified) {
243 state.drafts[key] = draft244 } else {245 state.copy.set(key, draft)246 }

feat: `Map` drafts and patcheskeenondrumsbefore adoption30db0f3

line 247why, one step back
247

chore: reorganize src/proxy.jsAlec Larsonbefore adoption3163a7d

lines 248–249why, one step back
248 return draft
249 },

refactor: simplify mapGetters.keysAlec Larsonbefore adoption3298a77

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

chore: reorganize src/proxy.jsAlec Larsonbefore adoption3163a7d

lines 251–254why, one step back
251 values: iterateMapValues,
252 entries: iterateMapValues,253 [Symbol.iterator]: iterateMapValues254}

feat: `Map` drafts and patcheskeenondrumsbefore adoption30db0f3

line 255why, one step back
255

chore: reorganize src/proxy.jsAlec Larsonbefore adoption3163a7d

lines 256–260why, one step back
256/** Map.prototype.values _-or-_ Map.prototype.entries */
257function iterateMapValues(state, prop, receiver) {258 const getYieldable =259 prop === "values" ? (key, value) => value : (key, value) => [key, value]260

fix: remove "function*" syntaxAlec Larsonbefore adoption08d88b8

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

chore: reorganize src/proxy.jsAlec Larsonbefore adoption3163a7d

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

fix: remove "function*" syntaxAlec Larsonbefore adoption08d88b8

lines 263–271why, one step back
263 return makeIterable(() => {
264 const result = iterator.next()265 if (!result.done) {266 const [key] = result.value267 const value = receiver.get(key)268 result.value = getYieldable(key, value)269 }270 return result271 })

feat: `Map` drafts and patcheskeenondrumsbefore adoption30db0f3

line 272why, one step back
272 }

feat: `Map` supportkeenondrumsbefore adoption8276a6c

lines 273–274why, one step back
273}
274

chore: reorganize src/proxy.jsAlec Larsonbefore adoption3163a7d

line 275why, one step back
275/**

feat: `Set` draftsAndrey Goncharovbefore adoption4355b63

lines 276–359why, one step back
276 * Set drafts
277 */278279const setTraps = {280 get(state, prop, receiver) {281 return setGetters.hasOwnProperty(prop)282 ? setGetters[prop](state, prop, receiver)283 : Reflect.get(state, prop, receiver)284 },285 ownKeys(state) {286 return Reflect.ownKeys(source(state))287 }288}289const setGetters = {290 [DRAFT_STATE]: state => state,291 size: state => source(state).size,292 has(state, prop) {293 state = source(state)294 return state.has.bind(state)295 },296 add: state => value => {297 if (!source(state).has(value)) {298 markChanged(state)299 state.copy.add(value)300 }301 return state.draft302 },303 delete: state => value => {304 markChanged(state)305 return state.copy.delete(value)306 },307 clear: state => () => {308 markChanged(state)309 return state.copy.clear()310 },311 forEach: state => (cb, thisArg) => {312 const iterator = iterateSetValues(state)()313 let result = iterator.next()314 while (!result.done) {315 cb.call(thisArg, result.value, result.value, state.draft)316 result = iterator.next()317 }318 },319 keys: iterateSetValues,320 values: iterateSetValues,321 entries: iterateSetValues,322 [Symbol.iterator]: iterateSetValues323}324325function iterateSetValues(state, prop) {326 return () => {327 const iterator = source(state)[Symbol.iterator]()328329 return makeIterable(() => {330 const result = iterator.next()331 if (!result.done) {332 const valueWrapped = wrapSetValue(state, result.value)333 result.value = valueWrapped334 if (prop === "entries") {335 result.value = [valueWrapped, valueWrapped]336 }337 }338 return result339 })340 }341}342343function wrapSetValue(state, value) {344 const key = original(value) || value345 let draft = state.drafts.get(key)346 if (!draft) {347 if (state.finalized || !isDraftable(value)) {348 return value349 }350 draft = createProxy(value, state)351 state.drafts.set(key, draft)352 if (state.modified) {353 state.copy.add(draft)354 }355 }356 return draft357}358359/**

chore: reorganize src/proxy.jsAlec Larsonbefore adoption3163a7d

lines 360–362why, one step back
360 * Helpers
361 */362

fix: revert Map supportAlec Larsonbefore adoption47529d3

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

chore: reorganize src/proxy.jsAlec Larsonbefore adoptione809ffc

line 367why, one step back
367

fix: revert Map supportAlec Larsonbefore adoption47529d3

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

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

lines 376–378why, one step back
376}
377378function markChanged(state) {

feat: `Set` draftsAndrey Goncharovbefore adoption4355b63

lines 379–390why, one step back
379 let resetDrafts = true
380 let assignFn = assign381 if (isMap(state.base)) {382 assignFn = assignMap383 } else if (isSet(state.base)) {384 assignFn = assignSet385 // We need to keep track of how non-proxied objects are related to proxied ones.386 // For other data structures that support keys we can use those keys to access the item, notwithstanding it being a proxy or not.387 // Sets, however, do not have keys.388 // We use original objects as keys and keep proxified values as values.389 resetDrafts = false390 }

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

lines 391–392why, one step back
391 if (!state.modified) {
392 state.modified = true

feat: `Set` draftsAndrey Goncharovbefore adoption4355b63

lines 393–396why, one step back
393 state.copy = assignFn(shallowCopy(state.base), state.drafts)
394 if (resetDrafts) {395 state.drafts = null396 }

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

lines 397–398why, one step back
397 if (state.parent) markChanged(state.parent)
398 }

fix: remove "function*" syntaxAlec Larsonbefore adoption08d88b8

lines 399–406why, one step back
399}
400401function makeIterable(next) {402 let self403 return (self = {404 [Symbol.iterator]: () => self,405 next406 })

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

line 407why, one step back
407}