proxy.js
This file
Path
src/proxy.js
434 lines · 12.1 KiB · JavaScript
Last changed by
refactor: markChanged functionAlec Larsonbefore adoption5857d63
History of this fileTake 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 back1"use strict"2import {fix: always use `assign` polyfillaleclarsonbefore adoption241a648
lines 3–4why, one step back3 assign,4 each,fix: use proxies only if Reflect exists (#227)Alec Larsonbefore adoption1f93af2
line 5why, one step back5 has,fix: always use `assign` polyfillaleclarsonbefore adoption241a648
line 6why, one step back6 is,feat: add `Immer` classaleclarsonbefore adoptionecd04dc
lines 7–8why, one step back7 isDraftable,8 isDraft,feat: `Map` drafts and patcheskeenondrumsbefore adoption30db0f3
line 9why, one step back9 isMap,feat: `Set` draftsAndrey Goncharovbefore adoption4355b63
line 10why, one step back10 isSet,fix: use proxies only if Reflect exists (#227)Alec Larsonbefore adoption1f93af2
line 11why, one step back11 shallowCopy,feat: `Set` draftsAndrey Goncharovbefore adoption4355b63
lines 12–15why, one step back12 DRAFT_STATE,13 assignMap,14 assignSet,15 originalfix: use proxies only if Reflect exists (#227)Alec Larsonbefore adoption1f93af2
line 16why, one step back16} from "./common"Merge branch 'async-recipes'Michel Weststratebefore adoptionff210d8
line 17why, one step back17import {ImmerScope} from "./scope"fix: use proxies only if Reflect exists (#227)Alec Larsonbefore adoption1f93af2
line 18why, one step back18feat: add `Immer` classaleclarsonbefore adoptionecd04dc
lines 19–21why, one step back19// Do nothing before being finalized.20export function willFinalize() {}21chore: reorganize src/proxy.jsAlec Larsonbefore adoption3163a7d
lines 22–26why, one step back22/**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 back27export function createProxy(base, parent) {28 const scope = parent ? parent.scope : ImmerScope.currentfeat: add `Immer` classaleclarsonbefore adoptionecd04dc
line 29why, one step back29 const state = {feat: passing drafts to producealeclarsonbefore adoption9c53415
line 30why, one step back30 // Track which produce call this is associated with.Merge branch 'async-recipes'Michel Weststratebefore adoptionff210d8
line 31why, one step back31 scope,feat: passing drafts to producealeclarsonbefore adoption9c53415
lines 32–38why, one step back32 // 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 back39 parent,feat: passing drafts to producealeclarsonbefore adoption9c53415
line 40why, one step back40 // The base state.feat: add `Immer` classaleclarsonbefore adoptionecd04dc
line 41why, one step back41 base,feat: passing drafts to producealeclarsonbefore adoption9c53415
lines 42–46why, one step back42 // 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 back47 copy: null,feat: passing drafts to producealeclarsonbefore adoption9c53415
lines 48–49why, one step back48 // Called by the `produce` function.49 revoke: nullfeat: add `Immer` classaleclarsonbefore adoptionecd04dc
lines 50–51why, one step back50 }51feat: `Map` drafts and patcheskeenondrumsbefore adoption30db0f3
lines 52–58why, one step back52 let proxyTarget = state53 let traps = objectTraps54 if (Array.isArray(base)) {55 proxyTarget = [state]56 traps = arrayTraps57 } else if (isMap(base)) {58 traps = mapTrapsfeat: `Set` draftsAndrey Goncharovbefore adoption4355b63
lines 59–62why, one step back59 } 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 back63 }feat: add `Immer` classaleclarsonbefore adoptionecd04dc
line 64why, one step back64feat: `Map` drafts and patcheskeenondrumsbefore adoption30db0f3
lines 65–66why, one step back65 const {revoke, proxy} = Proxy.revocable(proxyTarget, traps)66feat: add `Immer` classaleclarsonbefore adoptionecd04dc
lines 67–69why, one step back67 state.draft = proxy68 state.revoke = revoke69Merge branch 'async-recipes'Michel Weststratebefore adoptionff210d8
line 70why, one step back70 scope.drafts.push(proxy)feat: add `Immer` classaleclarsonbefore adoptionecd04dc
lines 71–73why, one step back71 return proxy72}73chore: reorganize src/proxy.jsAlec Larsonbefore adoption3163a7d
lines 74–77why, one step back74/**75 * Object drafts76 */77fix: use proxies only if Reflect exists (#227)Alec Larsonbefore adoption1f93af2
line 78why, one step back78const objectTraps = {chore: reorganize src/proxy.jsAlec Larsonbefore adoption3163a7d
lines 79–102why, one step back79 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 back103 has(state, prop) {104 return prop in source(state)chore: reorganize src/proxy.jsAlec Larsonbefore adoptione809ffc
line 105why, one step back105 },nit: argument namesAlec Larsonbefore adoptiona674a78
lines 106–107why, one step back106 ownKeys(state) {107 return Reflect.ownKeys(source(state))fix: use proxies only if Reflect exists (#227)Alec Larsonbefore adoption1f93af2
line 108why, one step back108 },chore: reorganize src/proxy.jsAlec Larsonbefore adoption3163a7d
lines 109–144why, one step back109 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 back145 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 back148 getPrototypeOf(state) {149 return Object.getPrototypeOf(state.base)fix: Object.getPrototypeOf with a draftaleclarsonbefore adoptiond5d07e8
line 150why, one step back150 },fix: use proxies only if Reflect exists (#227)Alec Larsonbefore adoption1f93af2
line 151why, one step back151 setPrototypeOf() {feat: limited class supportaleclarsonbefore adoption9877d64
line 152why, one step back152 throw new Error("Object.setPrototypeOf() cannot be used on an Immer draft") // prettier-ignorefix: use proxies only if Reflect exists (#227)Alec Larsonbefore adoption1f93af2
lines 153–155why, one step back153 }154}155chore: reorganize src/proxy.jsAlec Larsonbefore adoption3163a7d
lines 156–159why, one step back156/**157 * Array drafts158 */159fix: use proxies only if Reflect exists (#227)Alec Larsonbefore adoption1f93af2
lines 160–167why, one step back160const 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 back168 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 back171 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 back174 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 back177 return objectTraps.set.call(this, state[0], prop, value)feat: `Map` drafts and patcheskeenondrumsbefore adoption30db0f3
lines 178–179why, one step back178}179chore: reorganize src/proxy.jsAlec Larsonbefore adoption3163a7d
lines 180–184why, one step back180/**181 * Map drafts182 */183184const mapGetters = {fix: add Map getter for DRAFT_STATE, make isEnumerable more resilientkeenondrumsbefore adoption7bbec0a
line 185why, one step back185 [DRAFT_STATE]: state => state,chore: reorganize src/proxy.jsAlec Larsonbefore adoption3163a7d
lines 186–191why, one step back186 size: state => source(state).size,187 has(state, prop) {188 state = source(state)189 return state.has.bind(state)190 },191 set: state => (key, value) => {feat: `Set` draftsAndrey Goncharovbefore adoption4355b63
lines 192–197why, one step back192 const stateSource = source(state)193 if (!stateSource.has(key) || stateSource.get(key) !== value) {194 markChanged(state)195 state.assigned[key] = true196 state.copy.set(key, value)197 }fix: Map.prototype.set should return a draftAndrey Goncharovbefore adoption7001201
line 198why, one step back198 return state.draftchore: reorganize src/proxy.jsAlec Larsonbefore adoption3163a7d
lines 199–209why, one step back199 },200 delete: state => key => {201 markChanged(state)202 state.assigned[key] = false203 return state.copy.delete(key)204 },205 clear: state => () => {206 markChanged(state)207 state.assigned = {}208 for (const key of source(state).keys()) {209 state.assigned[key] = falsefeat: `Map` drafts and patcheskeenondrumsbefore adoption30db0f3
line 210why, one step back210 }chore: reorganize src/proxy.jsAlec Larsonbefore adoption3163a7d
lines 211–220why, one step back211 return state.copy.clear()212 },213 forEach: (state, _, receiver) => (cb, thisArg) =>214 source(state).forEach((_, key, map) => {215 const value = receiver.get(key)216 cb.call(thisArg, value, key, map)217 }),218 get: state => key => {219 if (!state.modified && has(state.drafts, key)) {220 return state.drafts[key]feat: `Map` drafts and patcheskeenondrumsbefore adoption30db0f3
line 221why, one step back221 }chore: reorganize src/proxy.jsAlec Larsonbefore adoption3163a7d
lines 222–224why, one step back222223 if (state.modified && state.copy.has(key)) {224 return state.copy.get(key)feat: `Map` drafts and patcheskeenondrumsbefore adoption30db0f3
line 225why, one step back225 }chore: reorganize src/proxy.jsAlec Larsonbefore adoption3163a7d
lines 226–230why, one step back226227 const value = source(state).get(key)228229 if (state.finalized || !isDraftable(value)) {230 return valuefeat: `Map` drafts and patcheskeenondrumsbefore adoption30db0f3
lines 231–232why, one step back231 }232chore: reorganize src/proxy.jsAlec Larsonbefore adoption3163a7d
line 233why, one step back233 const draft = createProxy(value, state)feat: `Map` drafts and patcheskeenondrumsbefore adoption30db0f3
line 234why, one step back234chore: reorganize src/proxy.jsAlec Larsonbefore adoption3163a7d
lines 235–239why, one step back235 if (!state.modified) {236 state.drafts[key] = draft237 } else {238 state.copy.set(key, draft)239 }feat: `Map` drafts and patcheskeenondrumsbefore adoption30db0f3
line 240why, one step back240chore: reorganize src/proxy.jsAlec Larsonbefore adoption3163a7d
lines 241–242why, one step back241 return draft242 },refactor: simplify mapGetters.keysAlec Larsonbefore adoption3298a77
line 243why, one step back243 keys: state => () => source(state).keys(),chore: reorganize src/proxy.jsAlec Larsonbefore adoption3163a7d
lines 244–247why, one step back244 values: iterateMapValues,245 entries: iterateMapValues,246 [Symbol.iterator]: iterateMapValues247}refactor: traps for Maps and Setskeenondrumsbefore adoptiondd82d89
line 248why, one step back248const mapTraps = makeTrapsForGetters(mapGetters)feat: `Map` drafts and patcheskeenondrumsbefore adoption30db0f3
line 249why, one step back249chore: reorganize src/proxy.jsAlec Larsonbefore adoption3163a7d
lines 250–254why, one step back250/** Map.prototype.values _-or-_ Map.prototype.entries */251function iterateMapValues(state, prop, receiver) {252 const getYieldable =253 prop === "values" ? (key, value) => value : (key, value) => [key, value]254fix: remove "function*" syntaxAlec Larsonbefore adoption08d88b8
line 255why, one step back255 return () => {chore: reorganize src/proxy.jsAlec Larsonbefore adoption3163a7d
line 256why, one step back256 const iterator = source(state)[Symbol.iterator]()fix: remove "function*" syntaxAlec Larsonbefore adoption08d88b8
lines 257–265why, one step back257 return makeIterable(() => {258 const result = iterator.next()259 if (!result.done) {260 const [key] = result.value261 const value = receiver.get(key)262 result.value = getYieldable(key, value)263 }264 return result265 })feat: `Map` drafts and patcheskeenondrumsbefore adoption30db0f3
line 266why, one step back266 }feat: `Map` supportkeenondrumsbefore adoption8276a6c
lines 267–268why, one step back267}268chore: reorganize src/proxy.jsAlec Larsonbefore adoption3163a7d
line 269why, one step back269/**feat: `Set` draftsAndrey Goncharovbefore adoption4355b63
lines 270–307why, one step back270 * Set drafts271 */272273const setGetters = {274 [DRAFT_STATE]: state => state,275 size: state => source(state).size,276 has(state, prop) {277 state = source(state)278 return state.has.bind(state)279 },280 add: state => value => {281 if (!source(state).has(value)) {282 markChanged(state)283 state.copy.add(value)284 }285 return state.draft286 },287 delete: state => value => {288 markChanged(state)289 return state.copy.delete(value)290 },291 clear: state => () => {292 markChanged(state)293 return state.copy.clear()294 },295 forEach: state => (cb, thisArg) => {296 const iterator = iterateSetValues(state)()297 let result = iterator.next()298 while (!result.done) {299 cb.call(thisArg, result.value, result.value, state.draft)300 result = iterator.next()301 }302 },303 keys: iterateSetValues,304 values: iterateSetValues,305 entries: iterateSetValues,306 [Symbol.iterator]: iterateSetValues307}refactor: traps for Maps and Setskeenondrumsbefore adoptiondd82d89
line 308why, one step back308const setTraps = makeTrapsForGetters(setGetters)feat: `Set` draftsAndrey Goncharovbefore adoption4355b63
lines 309–344why, one step back309310function iterateSetValues(state, prop) {311 return () => {312 const iterator = source(state)[Symbol.iterator]()313314 return makeIterable(() => {315 const result = iterator.next()316 if (!result.done) {317 const valueWrapped = wrapSetValue(state, result.value)318 result.value = valueWrapped319 if (prop === "entries") {320 result.value = [valueWrapped, valueWrapped]321 }322 }323 return result324 })325 }326}327328function wrapSetValue(state, value) {329 const key = original(value) || value330 let draft = state.drafts.get(key)331 if (!draft) {332 if (state.finalized || !isDraftable(value)) {333 return value334 }335 draft = createProxy(value, state)336 state.drafts.set(key, draft)337 if (state.modified) {338 state.copy.add(draft)339 }340 }341 return draft342}343344/**chore: reorganize src/proxy.jsAlec Larsonbefore adoption3163a7d
lines 345–347why, one step back345 * Helpers346 */347fix: revert Map supportAlec Larsonbefore adoption47529d3
lines 348–351why, one step back348// returns the object we should be reading the current value from, which is base, until some change has been made349function source(state) {350 return state.copy || state.base351}chore: reorganize src/proxy.jsAlec Larsonbefore adoptione809ffc
line 352why, one step back352fix: revert Map supportAlec Larsonbefore adoption47529d3
lines 353–360why, one step back353// Access a property without creating an Immer draft.354function peek(draft, prop) {355 const state = draft[DRAFT_STATE]356 const desc = Reflect.getOwnPropertyDescriptor(357 state ? source(state) : draft,358 prop359 )360 return desc && desc.valuefix: use proxies only if Reflect exists (#227)Alec Larsonbefore adoption1f93af2
lines 361–365why, one step back361}362363function markChanged(state) {364 if (!state.modified) {365 state.modified = truerefactor: markChanged functionAlec Larsonbefore adoption5857d63
lines 366–377why, one step back366367 const {base, drafts, parent} = state368 const copy = shallowCopy(base)369370 if (isSet(base)) {371 // Note: The `drafts` property is preserved for Set objects, since372 // we need to keep track of which values are drafted.373 assignSet(copy, drafts)374 } else {375 // Merge nested drafts into the copy.376 if (isMap(base)) assignMap(copy, drafts)377 else assign(copy, drafts)feat: `Set` draftsAndrey Goncharovbefore adoption4355b63
lines 378–379why, one step back378 state.drafts = null379 }refactor: markChanged functionAlec Larsonbefore adoption5857d63
lines 380–384why, one step back380381 state.copy = copy382 if (parent) {383 markChanged(parent)384 }fix: use proxies only if Reflect exists (#227)Alec Larsonbefore adoption1f93af2
line 385why, one step back385 }fix: remove "function*" syntaxAlec Larsonbefore adoption08d88b8
lines 386–393why, one step back386}387388function makeIterable(next) {389 let self390 return (self = {391 [Symbol.iterator]: () => self,392 next393 })refactor: traps for Maps and Setskeenondrumsbefore adoptiondd82d89
lines 394–404why, one step back394}395396function makeTrapsForGetters(getters) {397 return {398 get(state, prop, receiver) {399 return getters.hasOwnProperty(prop)400 ? getters[prop](state, prop, receiver)401 : Reflect.get(state, prop, receiver)402 },403 ownKeys(state) {404 return Reflect.ownKeys(source(state))fix: add more traps for Maps and SetsAndrey Goncharovbefore adoption930b4ab
lines 405–431why, one step back405 },406 set(state, ...args) {407 return Reflect.set(source(state), ...args)408 },409 has(state, ...args) {410 return Reflect.has(source(state), ...args)411 },412 deleteProperty(state, ...args) {413 return Reflect.deleteProperty(source(state), ...args)414 },415 defineProperty(state, ...args) {416 return Reflect.defineProperty(source(state), ...args)417 },418 getOwnPropertyDescriptor(state, ...args) {419 return Reflect.getOwnPropertyDescriptor(source(state), ...args)420 },421 preventExtensions(state) {422 return Reflect.preventExtensions(source(state))423 },424 isExtensible(state) {425 return Reflect.isExtensible(source(state))426 },427 getPrototypeOf(state) {428 return Reflect.getPrototypeOf(source(state))429 },430 setPrototypeOf(state) {431 throw new Error("Object.setPrototypeOf() cannot be used on an Immer draft") // prettier-ignorerefactor: traps for Maps and Setskeenondrumsbefore adoptiondd82d89
lines 432–433why, one step back432 }433 }fix: use proxies only if Reflect exists (#227)Alec Larsonbefore adoption1f93af2
line 434why, one step back434}