proxy.js
This file
Path
src/proxy.js
363 lines · 10.1 KiB · JavaScript
Last changed by
Merge pull request #437 from runnez/es5-map-and-set-supportMichel Weststratebefore adoption85656cb
History of this fileTake it
The walk stopped after 200 commits: lines older than 53e9ce8 point at it.
perf: proxy assignaleclarsonbefore adoption53e9ce8
lines 1–6why, one step back1"use strict"2import {3 assign,4 each,5 has,6 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,perf: proxy assignaleclarsonbefore adoption53e9ce8
line 11why, one step back11 shallowCopy,Merge pull request #437 from runnez/es5-map-and-set-supportMichel Weststratebefore adoption85656cb
line 12why, one step back12 makeIterable,feat: `Set` draftsAndrey Goncharovbefore adoption4355b63
lines 13–15why, one step back13 DRAFT_STATE,14 assignMap,15 assignSet,Merge pull request #437 from runnez/es5-map-and-set-supportMichel Weststratebefore adoption85656cb
lines 16–18why, one step back16 original,17 iterateMapValues,18 makeIterateSetValuesperf: proxy assignaleclarsonbefore adoption53e9ce8
line 19why, one step back19} from "./common"Merge branch 'async-recipes'Michel Weststratebefore adoptionff210d8
line 20why, one step back20import {ImmerScope} from "./scope"perf: proxy assignaleclarsonbefore adoption53e9ce8
line 21why, one step back21feat: add `Immer` classaleclarsonbefore adoptionecd04dc
lines 22–24why, one step back22// Do nothing before being finalized.23export function willFinalize() {}24chore: reorganize src/proxy.jsAlec Larsonbefore adoption3163a7d
lines 25–29why, one step back25/**26 * Returns a new draft of the `base` object.27 *28 * The second argument is the parent draft-state (used internally).29 */Merge branch 'async-recipes'Michel Weststratebefore adoptionff210d8
lines 30–31why, one step back30export function createProxy(base, parent) {31 const scope = parent ? parent.scope : ImmerScope.currentfeat: add `Immer` classaleclarsonbefore adoptionecd04dc
line 32why, one step back32 const state = {feat: passing drafts to producealeclarsonbefore adoption9c53415
line 33why, one step back33 // Track which produce call this is associated with.Merge branch 'async-recipes'Michel Weststratebefore adoptionff210d8
line 34why, one step back34 scope,feat: passing drafts to producealeclarsonbefore adoption9c53415
lines 35–41why, one step back35 // True for both shallow and deep changes.36 modified: false,37 // Used during finalization.38 finalized: false,39 // Track which properties have been assigned (true) or deleted (false).40 assigned: {},41 // The parent draft state.feat: add `Immer` classaleclarsonbefore adoptionecd04dc
line 42why, one step back42 parent,feat: passing drafts to producealeclarsonbefore adoption9c53415
line 43why, one step back43 // The base state.feat: add `Immer` classaleclarsonbefore adoptionecd04dc
line 44why, one step back44 base,feat: passing drafts to producealeclarsonbefore adoption9c53415
lines 45–49why, one step back45 // The base proxy.46 draft: null,47 // Any property proxies.48 drafts: {},49 // The base copy with any updated values.feat: add `Immer` classaleclarsonbefore adoptionecd04dc
line 50why, one step back50 copy: null,feat: passing drafts to producealeclarsonbefore adoption9c53415
lines 51–52why, one step back51 // Called by the `produce` function.52 revoke: nullfeat: add `Immer` classaleclarsonbefore adoptionecd04dc
lines 53–54why, one step back53 }54nit: minor refactoringAlec Larsonbefore adoptiona2c4754
line 55why, one step back55 let target = statefeat: `Map` drafts and patcheskeenondrumsbefore adoption30db0f3
lines 56–57why, one step back56 let traps = objectTraps57 if (Array.isArray(base)) {nit: minor refactoringAlec Larsonbefore adoptiona2c4754
line 58why, one step back58 target = [state]feat: `Map` drafts and patcheskeenondrumsbefore adoption30db0f3
line 59why, one step back59 traps = arrayTrapsnit: minor refactoringAlec Larsonbefore adoptiona2c4754
lines 60–62why, one step back60 }61 // Map drafts must support object keys, so we use Map objects to track changes.62 else if (isMap(base)) {feat: `Map` drafts and patcheskeenondrumsbefore adoption30db0f3
line 63why, one step back63 traps = mapTrapsfeat: add support of non-primitive keys for `Maps`keenondrumsbefore adoption6501ec5
lines 64–65why, one step back64 state.drafts = new Map()65 state.assigned = new Map()nit: minor refactoringAlec Larsonbefore adoptiona2c4754
lines 66–69why, one step back66 }67 // Set drafts use a Map object to track which of its values are drafted.68 // And we don't need the "assigned" property, because Set objects have no keys.69 else if (isSet(base)) {feat: `Set` draftsAndrey Goncharovbefore adoption4355b63
lines 70–71why, one step back70 traps = setTraps71 state.drafts = new Map()feat: `Map` drafts and patcheskeenondrumsbefore adoption30db0f3
line 72why, one step back72 }feat: add `Immer` classaleclarsonbefore adoptionecd04dc
line 73why, one step back73nit: minor refactoringAlec Larsonbefore adoptiona2c4754
line 74why, one step back74 const {revoke, proxy} = Proxy.revocable(target, traps)feat: `Map` drafts and patcheskeenondrumsbefore adoption30db0f3
line 75why, one step back75feat: add `Immer` classaleclarsonbefore adoptionecd04dc
lines 76–78why, one step back76 state.draft = proxy77 state.revoke = revoke78Merge branch 'async-recipes'Michel Weststratebefore adoptionff210d8
line 79why, one step back79 scope.drafts.push(proxy)feat: add `Immer` classaleclarsonbefore adoptionecd04dc
lines 80–82why, one step back80 return proxy81}82chore: reorganize src/proxy.jsAlec Larsonbefore adoption3163a7d
lines 83–86why, one step back83/**84 * Object drafts85 */86perf: proxy assignaleclarsonbefore adoption53e9ce8
line 87why, one step back87const objectTraps = {chore: reorganize src/proxy.jsAlec Larsonbefore adoption3163a7d
lines 88–96why, one step back88 get(state, prop) {89 if (prop === DRAFT_STATE) return state90 let {drafts} = state9192 // Check for existing draft in unmodified state.93 if (!state.modified && has(drafts, prop)) {94 return drafts[prop]95 }96refactor: rename "source" helper to "latest"Alec Larsonbefore adoptioneba300f
line 97why, one step back97 const value = latest(state)[prop]chore: reorganize src/proxy.jsAlec Larsonbefore adoption3163a7d
lines 98–111why, one step back98 if (state.finalized || !isDraftable(value)) {99 return value100 }101102 // Check for existing draft in modified state.103 if (state.modified) {104 // Assigned values are never drafted. This catches any drafts we created, too.105 if (value !== peek(state.base, prop)) return value106 // Store drafts on the copy (when one exists).107 drafts = state.copy108 }109110 return (drafts[prop] = createProxy(value, state))111 },nit: argument namesAlec Larsonbefore adoptiona674a78
line 112why, one step back112 has(state, prop) {refactor: rename "source" helper to "latest"Alec Larsonbefore adoptioneba300f
line 113why, one step back113 return prop in latest(state)chore: reorganize src/proxy.jsAlec Larsonbefore adoptione809ffc
line 114why, one step back114 },nit: argument namesAlec Larsonbefore adoptiona674a78
line 115why, one step back115 ownKeys(state) {refactor: rename "source" helper to "latest"Alec Larsonbefore adoptioneba300f
line 116why, one step back116 return Reflect.ownKeys(latest(state))perf: proxy assignaleclarsonbefore adoption53e9ce8
line 117why, one step back117 },chore: reorganize src/proxy.jsAlec Larsonbefore adoption3163a7d
lines 118–145why, one step back118 set(state, prop, value) {119 if (!state.modified) {120 const baseValue = peek(state.base, prop)121 // Optimize based on value's truthiness. Truthy values are guaranteed to122 // never be undefined, so we can avoid the `in` operator. Lastly, truthy123 // values may be drafts, but falsy values are never drafts.124 const isUnchanged = value125 ? is(baseValue, value) || value === state.drafts[prop]126 : is(baseValue, value) && prop in state.base127 if (isUnchanged) return true128 markChanged(state)129 }130 state.assigned[prop] = true131 state.copy[prop] = value132 return true133 },134 deleteProperty(state, prop) {135 // The `undefined` check is a fast path for pre-existing keys.136 if (peek(state.base, prop) !== undefined || prop in state.base) {137 state.assigned[prop] = false138 markChanged(state)139 }140 if (state.copy) delete state.copy[prop]141 return true142 },143 // Note: We never coerce `desc.value` into an Immer draft, because we can't make144 // the same guarantee in ES5 mode.145 getOwnPropertyDescriptor(state, prop) {refactor: rename "source" helper to "latest"Alec Larsonbefore adoptioneba300f
line 146why, one step back146 const owner = latest(state)chore: reorganize src/proxy.jsAlec Larsonbefore adoption3163a7d
lines 147–153why, one step back147 const desc = Reflect.getOwnPropertyDescriptor(owner, prop)148 if (desc) {149 desc.writable = true150 desc.configurable = !Array.isArray(owner) || prop !== "length"151 }152 return desc153 },feat: limited class supportaleclarsonbefore adoption9877d64
lines 154–156why, one step back154 defineProperty() {155 throw new Error("Object.defineProperty() cannot be used on an Immer draft") // prettier-ignore156 },nit: argument namesAlec Larsonbefore adoptiona674a78
lines 157–158why, one step back157 getPrototypeOf(state) {158 return Object.getPrototypeOf(state.base)fix: Object.getPrototypeOf with a draftaleclarsonbefore adoptiond5d07e8
line 159why, one step back159 },perf: proxy assignaleclarsonbefore adoption53e9ce8
line 160why, one step back160 setPrototypeOf() {feat: limited class supportaleclarsonbefore adoption9877d64
line 161why, one step back161 throw new Error("Object.setPrototypeOf() cannot be used on an Immer draft") // prettier-ignoreperf: proxy assignaleclarsonbefore adoption53e9ce8
lines 162–164why, one step back162 }163}164chore: reorganize src/proxy.jsAlec Larsonbefore adoption3163a7d
lines 165–168why, one step back165/**166 * Array drafts167 */168perf: proxy assignaleclarsonbefore adoption53e9ce8
lines 169–176why, one step back169const arrayTraps = {}170each(objectTraps, (key, fn) => {171 arrayTraps[key] = function() {172 arguments[0] = arguments[0][0]173 return fn.apply(this, arguments)174 }175})176arrayTraps.deleteProperty = function(state, prop) {feat: limited class supportaleclarsonbefore adoption9877d64
lines 177–179why, one step back177 if (isNaN(parseInt(prop))) {178 throw new Error("Immer only supports deleting array indices") // prettier-ignore179 }perf: proxy assignaleclarsonbefore adoption53e9ce8
lines 180–182why, one step back180 return objectTraps.deleteProperty.call(this, state[0], prop)181}182arrayTraps.set = function(state, prop, value) {feat: limited class supportaleclarsonbefore adoption9877d64
lines 183–185why, one step back183 if (prop !== "length" && isNaN(parseInt(prop))) {184 throw new Error("Immer only supports setting array indices and the 'length' property") // prettier-ignore185 }perf: proxy assignaleclarsonbefore adoption53e9ce8
line 186why, one step back186 return objectTraps.set.call(this, state[0], prop, value)feat: `Map` drafts and patcheskeenondrumsbefore adoption30db0f3
lines 187–188why, one step back187}188refactor: makeTrapsForGetters functionAlec Larsonbefore adoption5093fd0
lines 189–201why, one step back189// Used by Map and Set drafts190const reflectTraps = makeReflectTraps([191 "ownKeys",192 "has",193 "set",194 "deleteProperty",195 "defineProperty",196 "getOwnPropertyDescriptor",197 "preventExtensions",198 "isExtensible",199 "getPrototypeOf"200])201chore: reorganize src/proxy.jsAlec Larsonbefore adoption3163a7d
lines 202–205why, one step back202/**203 * Map drafts204 */205refactor: makeTrapsForGetters functionAlec Larsonbefore adoption5093fd0
line 206why, one step back206const mapTraps = makeTrapsForGetters({fix: add Map getter for DRAFT_STATE, make isEnumerable more resilientkeenondrumsbefore adoption7bbec0a
line 207why, one step back207 [DRAFT_STATE]: state => state,refactor: rename "source" helper to "latest"Alec Larsonbefore adoptioneba300f
lines 208–209why, one step back208 size: state => latest(state).size,209 has: state => key => latest(state).has(key),chore: reorganize src/proxy.jsAlec Larsonbefore adoption3163a7d
line 210why, one step back210 set: state => (key, value) => {refactor: rename "source" helper to "latest"Alec Larsonbefore adoptioneba300f
lines 211–212why, one step back211 const values = latest(state)212 if (!values.has(key) || values.get(key) !== value) {feat: `Set` draftsAndrey Goncharovbefore adoption4355b63
line 213why, one step back213 markChanged(state)feat: add support of non-primitive keys for `Maps`keenondrumsbefore adoption6501ec5
line 214why, one step back214 state.assigned.set(key, true)feat: `Set` draftsAndrey Goncharovbefore adoption4355b63
lines 215–216why, one step back215 state.copy.set(key, value)216 }fix: Map.prototype.set should return a draftAndrey Goncharovbefore adoption7001201
line 217why, one step back217 return state.draftchore: reorganize src/proxy.jsAlec Larsonbefore adoption3163a7d
lines 218–219why, one step back218 },219 delete: state => key => {refactor: rename "source" helper to "latest"Alec Larsonbefore adoptioneba300f
line 220why, one step back220 if (latest(state).has(key)) {feat: `onDelete` for `Maps`keenondrumsbefore adoption1ca49ef
lines 221–225why, one step back221 markChanged(state)222 state.assigned.set(key, false)223 return state.copy.delete(key)224 }225 return falsechore: reorganize src/proxy.jsAlec Larsonbefore adoption3163a7d
lines 226–228why, one step back226 },227 clear: state => () => {228 markChanged(state)feat: add support of non-primitive keys for `Maps`keenondrumsbefore adoption6501ec5
line 229why, one step back229 state.assigned = new Map()refactor: rename "source" helper to "latest"Alec Larsonbefore adoptioneba300f
line 230why, one step back230 for (const key of latest(state).keys()) {feat: add support of non-primitive keys for `Maps`keenondrumsbefore adoption6501ec5
line 231why, one step back231 state.assigned.set(key, false)feat: `Map` drafts and patcheskeenondrumsbefore adoption30db0f3
line 232why, one step back232 }chore: reorganize src/proxy.jsAlec Larsonbefore adoption3163a7d
lines 233–235why, one step back233 return state.copy.clear()234 },235 forEach: (state, _, receiver) => (cb, thisArg) =>refactor: rename "source" helper to "latest"Alec Larsonbefore adoptioneba300f
line 236why, one step back236 latest(state).forEach((_, key, map) => {chore: reorganize src/proxy.jsAlec Larsonbefore adoption3163a7d
lines 237–240why, one step back237 const value = receiver.get(key)238 cb.call(thisArg, value, key, map)239 }),240 get: state => key => {refactor: "get" trap for MapsAlec Larsonbefore adoptionddf5dbb
lines 241–243why, one step back241 const drafts = state[state.modified ? "copy" : "drafts"]242 if (drafts.has(key)) {243 return drafts.get(key)feat: `Map` drafts and patcheskeenondrumsbefore adoption30db0f3
line 244why, one step back244 }chore: reorganize src/proxy.jsAlec Larsonbefore adoption3163a7d
line 245why, one step back245refactor: rename "source" helper to "latest"Alec Larsonbefore adoptioneba300f
line 246why, one step back246 const value = latest(state).get(key)chore: reorganize src/proxy.jsAlec Larsonbefore adoption3163a7d
lines 247–248why, one step back247 if (state.finalized || !isDraftable(value)) {248 return valuefeat: `Map` drafts and patcheskeenondrumsbefore adoption30db0f3
lines 249–250why, one step back249 }250chore: reorganize src/proxy.jsAlec Larsonbefore adoption3163a7d
line 251why, one step back251 const draft = createProxy(value, state)refactor: "get" trap for MapsAlec Larsonbefore adoptionddf5dbb
line 252why, one step back252 drafts.set(key, draft)chore: reorganize src/proxy.jsAlec Larsonbefore adoption3163a7d
lines 253–254why, one step back253 return draft254 },refactor: rename "source" helper to "latest"Alec Larsonbefore adoptioneba300f
line 255why, one step back255 keys: state => () => latest(state).keys(),chore: reorganize src/proxy.jsAlec Larsonbefore adoption3163a7d
lines 256–258why, one step back256 values: iterateMapValues,257 entries: iterateMapValues,258 [Symbol.iterator]: iterateMapValuesrefactor: makeTrapsForGetters functionAlec Larsonbefore adoption5093fd0
line 259why, one step back259})feat: `Map` drafts and patcheskeenondrumsbefore adoption30db0f3
line 260why, one step back260Merge pull request #437 from runnez/es5-map-and-set-supportMichel Weststratebefore adoption85656cb
line 261why, one step back261const iterateSetValues = makeIterateSetValues(createProxy)chore: reorganize src/proxy.jsAlec Larsonbefore adoption3163a7d
line 262why, one step back262/**feat: `Set` draftsAndrey Goncharovbefore adoption4355b63
lines 263–265why, one step back263 * Set drafts264 */265refactor: makeTrapsForGetters functionAlec Larsonbefore adoption5093fd0
line 266why, one step back266const setTraps = makeTrapsForGetters({feat: `Set` draftsAndrey Goncharovbefore adoption4355b63
line 267why, one step back267 [DRAFT_STATE]: state => state,refactor: rename "source" helper to "latest"Alec Larsonbefore adoptioneba300f
lines 268–269why, one step back268 size: state => latest(state).size,269 has: state => key => latest(state).has(key),feat: `Set` draftsAndrey Goncharovbefore adoption4355b63
line 270why, one step back270 add: state => value => {refactor: rename "source" helper to "latest"Alec Larsonbefore adoptioneba300f
line 271why, one step back271 if (!latest(state).has(value)) {feat: `Set` draftsAndrey Goncharovbefore adoption4355b63
lines 272–296why, one step back272 markChanged(state)273 state.copy.add(value)274 }275 return state.draft276 },277 delete: state => value => {278 markChanged(state)279 return state.copy.delete(value)280 },281 clear: state => () => {282 markChanged(state)283 return state.copy.clear()284 },285 forEach: state => (cb, thisArg) => {286 const iterator = iterateSetValues(state)()287 let result = iterator.next()288 while (!result.done) {289 cb.call(thisArg, result.value, result.value, state.draft)290 result = iterator.next()291 }292 },293 keys: iterateSetValues,294 values: iterateSetValues,295 entries: iterateSetValues,296 [Symbol.iterator]: iterateSetValuesrefactor: makeTrapsForGetters functionAlec Larsonbefore adoption5093fd0
line 297why, one step back297})feat: `Set` draftsAndrey Goncharovbefore adoption4355b63
lines 298–299why, one step back298299/**chore: reorganize src/proxy.jsAlec Larsonbefore adoption3163a7d
lines 300–302why, one step back300 * Helpers301 */302refactor: rename "source" helper to "latest"Alec Larsonbefore adoptioneba300f
lines 303–304why, one step back303// Retrieve the latest values of the draft.304function latest(state) {fix: revert Map supportAlec Larsonbefore adoption47529d3
lines 305–306why, one step back305 return state.copy || state.base306}chore: reorganize src/proxy.jsAlec Larsonbefore adoptione809ffc
line 307why, one step back307fix: revert Map supportAlec Larsonbefore adoption47529d3
lines 308–311why, one step back308// Access a property without creating an Immer draft.309function peek(draft, prop) {310 const state = draft[DRAFT_STATE]311 const desc = Reflect.getOwnPropertyDescriptor(refactor: rename "source" helper to "latest"Alec Larsonbefore adoptioneba300f
line 312why, one step back312 state ? latest(state) : draft,fix: revert Map supportAlec Larsonbefore adoption47529d3
lines 313–315why, one step back313 prop314 )315 return desc && desc.valueperf: proxy assignaleclarsonbefore adoption53e9ce8
lines 316–320why, one step back316}317318function markChanged(state) {319 if (!state.modified) {320 state.modified = truerefactor: markChanged functionAlec Larsonbefore adoption5857d63
lines 321–332why, one step back321322 const {base, drafts, parent} = state323 const copy = shallowCopy(base)324325 if (isSet(base)) {326 // Note: The `drafts` property is preserved for Set objects, since327 // we need to keep track of which values are drafted.328 assignSet(copy, drafts)329 } else {330 // Merge nested drafts into the copy.331 if (isMap(base)) assignMap(copy, drafts)332 else assign(copy, drafts)feat: `Set` draftsAndrey Goncharovbefore adoption4355b63
lines 333–334why, one step back333 state.drafts = null334 }refactor: markChanged functionAlec Larsonbefore adoption5857d63
lines 335–339why, one step back335336 state.copy = copy337 if (parent) {338 markChanged(parent)339 }perf: proxy assignaleclarsonbefore adoption53e9ce8
line 340why, one step back340 }refactor: traps for Maps and Setskeenondrumsbefore adoptiondd82d89
lines 341–342why, one step back341}342refactor: rename "source" helper to "latest"Alec Larsonbefore adoptioneba300f
line 343why, one step back343/** Create traps that all use the `Reflect` API on the `latest(state)` */refactor: makeTrapsForGetters functionAlec Larsonbefore adoption5093fd0
lines 344–345why, one step back344function makeReflectTraps(names) {345 return names.reduce((traps, name) => {refactor: rename "source" helper to "latest"Alec Larsonbefore adoptioneba300f
line 346why, one step back346 traps[name] = (state, ...args) => Reflect[name](latest(state), ...args)refactor: makeTrapsForGetters functionAlec Larsonbefore adoption5093fd0
lines 347–350why, one step back347 return traps348 }, {})349}350refactor: traps for Maps and Setskeenondrumsbefore adoptiondd82d89
lines 351–352why, one step back351function makeTrapsForGetters(getters) {352 return {refactor: makeTrapsForGetters functionAlec Larsonbefore adoption5093fd0
line 353why, one step back353 ...reflectTraps,refactor: traps for Maps and Setskeenondrumsbefore adoptiondd82d89
lines 354–357why, one step back354 get(state, prop, receiver) {355 return getters.hasOwnProperty(prop)356 ? getters[prop](state, prop, receiver)357 : Reflect.get(state, prop, receiver)fix: add more traps for Maps and SetsAndrey Goncharovbefore adoption930b4ab
lines 358–360why, one step back358 },359 setPrototypeOf(state) {360 throw new Error("Object.setPrototypeOf() cannot be used on an Immer draft") // prettier-ignorerefactor: traps for Maps and Setskeenondrumsbefore adoptiondd82d89
lines 361–362why, one step back361 }362 }perf: proxy assignaleclarsonbefore adoption53e9ce8
line 363why, one step back363}