proxy.js
This file
Path
src/proxy.js
431 lines · 12.0 KiB · JavaScript
Last changed by
feat: add support of non-primitive keys for `Maps`keenondrumsbefore adoption6501ec5
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: add support of non-primitive keys for `Maps`keenondrumsbefore adoption6501ec5
lines 59–61why, one step back59 // Maps need to support non-primitive keys and objects do not support other objects as keys60 state.drafts = new Map()61 state.assigned = new Map()feat: `Set` draftsAndrey Goncharovbefore adoption4355b63
lines 62–65why, one step back62 } 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 back66 // 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 valuesfeat: `Map` drafts and patcheskeenondrumsbefore adoption30db0f3
line 67why, one step back67 }feat: add `Immer` classaleclarsonbefore adoptionecd04dc
line 68why, one step back68feat: `Map` drafts and patcheskeenondrumsbefore adoption30db0f3
lines 69–70why, one step back69 const {revoke, proxy} = Proxy.revocable(proxyTarget, traps)70feat: add `Immer` classaleclarsonbefore adoptionecd04dc
lines 71–73why, one step back71 state.draft = proxy72 state.revoke = revoke73Merge branch 'async-recipes'Michel Weststratebefore adoptionff210d8
line 74why, one step back74 scope.drafts.push(proxy)feat: add `Immer` classaleclarsonbefore adoptionecd04dc
lines 75–77why, one step back75 return proxy76}77chore: reorganize src/proxy.jsAlec Larsonbefore adoption3163a7d
lines 78–81why, one step back78/**79 * Object drafts80 */81fix: use proxies only if Reflect exists (#227)Alec Larsonbefore adoption1f93af2
line 82why, one step back82const objectTraps = {chore: reorganize src/proxy.jsAlec Larsonbefore adoption3163a7d
lines 83–106why, one step back83 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 back107 has(state, prop) {108 return prop in source(state)chore: reorganize src/proxy.jsAlec Larsonbefore adoptione809ffc
line 109why, one step back109 },nit: argument namesAlec Larsonbefore adoptiona674a78
lines 110–111why, one step back110 ownKeys(state) {111 return Reflect.ownKeys(source(state))fix: use proxies only if Reflect exists (#227)Alec Larsonbefore adoption1f93af2
line 112why, one step back112 },chore: reorganize src/proxy.jsAlec Larsonbefore adoption3163a7d
lines 113–148why, one step back113 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 back149 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 back152 getPrototypeOf(state) {153 return Object.getPrototypeOf(state.base)fix: Object.getPrototypeOf with a draftaleclarsonbefore adoptiond5d07e8
line 154why, one step back154 },fix: use proxies only if Reflect exists (#227)Alec Larsonbefore adoption1f93af2
line 155why, one step back155 setPrototypeOf() {feat: limited class supportaleclarsonbefore adoption9877d64
line 156why, one step back156 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 157–159why, one step back157 }158}159chore: reorganize src/proxy.jsAlec Larsonbefore adoption3163a7d
lines 160–163why, one step back160/**161 * Array drafts162 */163fix: use proxies only if Reflect exists (#227)Alec Larsonbefore adoption1f93af2
lines 164–171why, one step back164const 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 back172 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 back175 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 back178 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 back181 return objectTraps.set.call(this, state[0], prop, value)feat: `Map` drafts and patcheskeenondrumsbefore adoption30db0f3
lines 182–183why, one step back182}183refactor: makeTrapsForGetters functionAlec Larsonbefore adoption5093fd0
lines 184–196why, one step back184// Used by Map and Set drafts185const reflectTraps = makeReflectTraps([186 "ownKeys",187 "has",188 "set",189 "deleteProperty",190 "defineProperty",191 "getOwnPropertyDescriptor",192 "preventExtensions",193 "isExtensible",194 "getPrototypeOf"195])196chore: reorganize src/proxy.jsAlec Larsonbefore adoption3163a7d
lines 197–200why, one step back197/**198 * Map drafts199 */200refactor: makeTrapsForGetters functionAlec Larsonbefore adoption5093fd0
line 201why, one step back201const mapTraps = makeTrapsForGetters({fix: add Map getter for DRAFT_STATE, make isEnumerable more resilientkeenondrumsbefore adoption7bbec0a
line 202why, one step back202 [DRAFT_STATE]: state => state,chore: reorganize src/proxy.jsAlec Larsonbefore adoption3163a7d
lines 203–208why, one step back203 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 back209 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 back212 state.assigned.set(key, true)feat: `Set` draftsAndrey Goncharovbefore adoption4355b63
lines 213–214why, one step back213 state.copy.set(key, value)214 }fix: Map.prototype.set should return a draftAndrey Goncharovbefore adoption7001201
line 215why, one step back215 return state.draftchore: reorganize src/proxy.jsAlec Larsonbefore adoption3163a7d
lines 216–218why, one step back216 },217 delete: state => key => {218 markChanged(state)feat: add support of non-primitive keys for `Maps`keenondrumsbefore adoption6501ec5
line 219why, one step back219 state.assigned.set(key, false)chore: reorganize src/proxy.jsAlec Larsonbefore adoption3163a7d
lines 220–223why, one step back220 return state.copy.delete(key)221 },222 clear: state => () => {223 markChanged(state)feat: add support of non-primitive keys for `Maps`keenondrumsbefore adoption6501ec5
line 224why, one step back224 state.assigned = new Map()chore: reorganize src/proxy.jsAlec Larsonbefore adoption3163a7d
line 225why, one step back225 for (const key of source(state).keys()) {feat: add support of non-primitive keys for `Maps`keenondrumsbefore adoption6501ec5
line 226why, one step back226 state.assigned.set(key, false)feat: `Map` drafts and patcheskeenondrumsbefore adoption30db0f3
line 227why, one step back227 }chore: reorganize src/proxy.jsAlec Larsonbefore adoption3163a7d
lines 228–235why, one step back228 return state.copy.clear()229 },230 forEach: (state, _, receiver) => (cb, thisArg) =>231 source(state).forEach((_, key, map) => {232 const value = receiver.get(key)233 cb.call(thisArg, value, key, map)234 }),235 get: state => key => {feat: add support of non-primitive keys for `Maps`keenondrumsbefore adoption6501ec5
lines 236–237why, one step back236 if (!state.modified && state.drafts.has(key)) {237 return state.drafts.get(key)feat: `Map` drafts and patcheskeenondrumsbefore adoption30db0f3
line 238why, one step back238 }chore: reorganize src/proxy.jsAlec Larsonbefore adoption3163a7d
lines 239–241why, one step back239240 if (state.modified && state.copy.has(key)) {241 return state.copy.get(key)feat: `Map` drafts and patcheskeenondrumsbefore adoption30db0f3
line 242why, one step back242 }chore: reorganize src/proxy.jsAlec Larsonbefore adoption3163a7d
lines 243–247why, one step back243244 const value = source(state).get(key)245246 if (state.finalized || !isDraftable(value)) {247 return valuefeat: `Map` drafts and patcheskeenondrumsbefore adoption30db0f3
lines 248–249why, one step back248 }249chore: reorganize src/proxy.jsAlec Larsonbefore adoption3163a7d
line 250why, one step back250 const draft = createProxy(value, state)feat: `Map` drafts and patcheskeenondrumsbefore adoption30db0f3
line 251why, one step back251chore: reorganize src/proxy.jsAlec Larsonbefore adoption3163a7d
line 252why, one step back252 if (!state.modified) {feat: add support of non-primitive keys for `Maps`keenondrumsbefore adoption6501ec5
line 253why, one step back253 state.drafts.set(key, draft)chore: reorganize src/proxy.jsAlec Larsonbefore adoption3163a7d
lines 254–256why, one step back254 } else {255 state.copy.set(key, draft)256 }feat: `Map` drafts and patcheskeenondrumsbefore adoption30db0f3
line 257why, one step back257chore: reorganize src/proxy.jsAlec Larsonbefore adoption3163a7d
lines 258–259why, one step back258 return draft259 },refactor: simplify mapGetters.keysAlec Larsonbefore adoption3298a77
line 260why, one step back260 keys: state => () => source(state).keys(),chore: reorganize src/proxy.jsAlec Larsonbefore adoption3163a7d
lines 261–263why, one step back261 values: iterateMapValues,262 entries: iterateMapValues,263 [Symbol.iterator]: iterateMapValuesrefactor: makeTrapsForGetters functionAlec Larsonbefore adoption5093fd0
line 264why, one step back264})feat: `Map` drafts and patcheskeenondrumsbefore adoption30db0f3
line 265why, one step back265chore: reorganize src/proxy.jsAlec Larsonbefore adoption3163a7d
lines 266–270why, one step back266/** Map.prototype.values _-or-_ Map.prototype.entries */267function iterateMapValues(state, prop, receiver) {268 const getYieldable =269 prop === "values" ? (key, value) => value : (key, value) => [key, value]270fix: remove "function*" syntaxAlec Larsonbefore adoption08d88b8
line 271why, one step back271 return () => {chore: reorganize src/proxy.jsAlec Larsonbefore adoption3163a7d
line 272why, one step back272 const iterator = source(state)[Symbol.iterator]()fix: remove "function*" syntaxAlec Larsonbefore adoption08d88b8
lines 273–281why, one step back273 return makeIterable(() => {274 const result = iterator.next()275 if (!result.done) {276 const [key] = result.value277 const value = receiver.get(key)278 result.value = getYieldable(key, value)279 }280 return result281 })feat: `Map` drafts and patcheskeenondrumsbefore adoption30db0f3
line 282why, one step back282 }feat: `Map` supportkeenondrumsbefore adoption8276a6c
lines 283–284why, one step back283}284chore: reorganize src/proxy.jsAlec Larsonbefore adoption3163a7d
line 285why, one step back285/**feat: `Set` draftsAndrey Goncharovbefore adoption4355b63
lines 286–288why, one step back286 * Set drafts287 */288refactor: makeTrapsForGetters functionAlec Larsonbefore adoption5093fd0
line 289why, one step back289const setTraps = makeTrapsForGetters({feat: `Set` draftsAndrey Goncharovbefore adoption4355b63
lines 290–322why, one step back290 [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]: iterateSetValuesrefactor: makeTrapsForGetters functionAlec Larsonbefore adoption5093fd0
line 323why, one step back323})feat: `Set` draftsAndrey Goncharovbefore adoption4355b63
lines 324–359why, one step back324325function 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 back360 * Helpers361 */362fix: revert Map supportAlec Larsonbefore adoption47529d3
lines 363–366why, one step back363// returns the object we should be reading the current value from, which is base, until some change has been made364function source(state) {365 return state.copy || state.base366}chore: reorganize src/proxy.jsAlec Larsonbefore adoptione809ffc
line 367why, one step back367fix: revert Map supportAlec Larsonbefore adoption47529d3
lines 368–375why, one step back368// 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.valuefix: use proxies only if Reflect exists (#227)Alec Larsonbefore adoption1f93af2
lines 376–380why, one step back376}377378function markChanged(state) {379 if (!state.modified) {380 state.modified = truerefactor: markChanged functionAlec Larsonbefore adoption5857d63
lines 381–392why, one step back381382 const {base, drafts, parent} = state383 const copy = shallowCopy(base)384385 if (isSet(base)) {386 // Note: The `drafts` property is preserved for Set objects, since387 // we need to keep track of which values are drafted.388 assignSet(copy, drafts)389 } else {390 // Merge nested drafts into the copy.391 if (isMap(base)) assignMap(copy, drafts)392 else assign(copy, drafts)feat: `Set` draftsAndrey Goncharovbefore adoption4355b63
lines 393–394why, one step back393 state.drafts = null394 }refactor: markChanged functionAlec Larsonbefore adoption5857d63
lines 395–399why, one step back395396 state.copy = copy397 if (parent) {398 markChanged(parent)399 }fix: use proxies only if Reflect exists (#227)Alec Larsonbefore adoption1f93af2
line 400why, one step back400 }fix: remove "function*" syntaxAlec Larsonbefore adoption08d88b8
lines 401–408why, one step back401}402403function makeIterable(next) {404 let self405 return (self = {406 [Symbol.iterator]: () => self,407 next408 })refactor: traps for Maps and Setskeenondrumsbefore adoptiondd82d89
lines 409–410why, one step back409}410refactor: makeTrapsForGetters functionAlec Larsonbefore adoption5093fd0
lines 411–418why, one step back411/** Create traps that all use the `Reflect` API on the `source(state)` */412function makeReflectTraps(names) {413 return names.reduce((traps, name) => {414 traps[name] = (state, ...args) => Reflect[name](source(state), ...args)415 return traps416 }, {})417}418refactor: traps for Maps and Setskeenondrumsbefore adoptiondd82d89
lines 419–420why, one step back419function makeTrapsForGetters(getters) {420 return {refactor: makeTrapsForGetters functionAlec Larsonbefore adoption5093fd0
line 421why, one step back421 ...reflectTraps,refactor: traps for Maps and Setskeenondrumsbefore adoptiondd82d89
lines 422–425why, one step back422 get(state, prop, receiver) {423 return getters.hasOwnProperty(prop)424 ? getters[prop](state, prop, receiver)425 : Reflect.get(state, prop, receiver)fix: add more traps for Maps and SetsAndrey Goncharovbefore adoption930b4ab
lines 426–428why, one step back426 },427 setPrototypeOf(state) {428 throw new Error("Object.setPrototypeOf() cannot be used on an Immer draft") // prettier-ignorerefactor: traps for Maps and Setskeenondrumsbefore adoptiondd82d89
lines 429–430why, one step back429 }430 }fix: use proxies only if Reflect exists (#227)Alec Larsonbefore adoption1f93af2
line 431why, one step back431}