proxy.js
This file
Path
src/proxy.js
363 lines · 8.7 KiB · JavaScript
Last changed by
run prettier with master config before mergingMichel Weststratebefore adoptionae80361
History of this fileTake it
The walk stopped after 200 commits: lines older than 53e9ce8 point at it.
perf: proxy assignaleclarsonbefore adoption53e9ce8
lines 1–2why, one step back1"use strict"2import {run prettier with master config before mergingMichel Weststratebefore adoptionae80361
lines 3–18why, one step back3 assign,4 each,5 has,6 is,7 isDraftable,8 isDraft,9 isMap,10 isSet,11 shallowCopy,12 makeIterable,13 DRAFT_STATE,14 assignMap,15 assignSet,16 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
line 30why, one step back30export function createProxy(base, parent) {run prettier with master config before mergingMichel Weststratebefore adoptionae80361
lines 31–53why, one step back31 const scope = parent ? parent.scope : ImmerScope.current32 const state = {33 // Track which produce call this is associated with.34 scope,35 // 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.42 parent,43 // The base state.44 base,45 // The base proxy.46 draft: null,47 // Any property proxies.48 drafts: {},49 // The base copy with any updated values.50 copy: null,51 // Called by the `produce` function.52 revoke: null53 }feat: add `Immer` classaleclarsonbefore adoptionecd04dc
line 54why, one step back54run prettier with master config before mergingMichel Weststratebefore adoptionae80361
lines 55–72why, one step back55 let target = state56 let traps = objectTraps57 if (Array.isArray(base)) {58 target = [state]59 traps = arrayTraps60 }61 // Map drafts must support object keys, so we use Map objects to track changes.62 else if (isMap(base)) {63 traps = mapTraps64 state.drafts = new Map()65 state.assigned = new Map()66 }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)) {70 traps = setTraps71 state.drafts = new Map()72 }feat: add `Immer` classaleclarsonbefore adoptionecd04dc
line 73why, one step back73run prettier with master config before mergingMichel Weststratebefore adoptionae80361
line 74why, one step back74 const {revoke, proxy} = Proxy.revocable(target, traps)feat: `Map` drafts and patcheskeenondrumsbefore adoption30db0f3
line 75why, one step back75run prettier with master config before mergingMichel Weststratebefore adoptionae80361
lines 76–77why, one step back76 state.draft = proxy77 state.revoke = revokefeat: add `Immer` classaleclarsonbefore adoptionecd04dc
line 78why, one step back78run prettier with master config before mergingMichel Weststratebefore adoptionae80361
lines 79–80why, one step back79 scope.drafts.push(proxy)80 return proxyfeat: add `Immer` classaleclarsonbefore adoptionecd04dc
lines 81–82why, one step back81}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 = {run prettier with master config before mergingMichel Weststratebefore adoptionae80361
lines 88–90why, one step back88 get(state, prop) {89 if (prop === DRAFT_STATE) return state90 let {drafts} = statechore: reorganize src/proxy.jsAlec Larsonbefore adoption3163a7d
line 91why, one step back91run prettier with master config before mergingMichel Weststratebefore adoptionae80361
lines 92–95why, one step back92 // Check for existing draft in unmodified state.93 if (!state.modified && has(drafts, prop)) {94 return drafts[prop]95 }chore: reorganize src/proxy.jsAlec Larsonbefore adoption3163a7d
line 96why, one step back96run prettier with master config before mergingMichel Weststratebefore adoptionae80361
lines 97–100why, one step back97 const value = latest(state)[prop]98 if (state.finalized || !isDraftable(value)) {99 return value100 }chore: reorganize src/proxy.jsAlec Larsonbefore adoption3163a7d
line 101why, one step back101run prettier with master config before mergingMichel Weststratebefore adoptionae80361
lines 102–108why, one step back102 // 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 }chore: reorganize src/proxy.jsAlec Larsonbefore adoption3163a7d
line 109why, one step back109run prettier with master config before mergingMichel Weststratebefore adoptionae80361
lines 110–162why, one step back110 return (drafts[prop] = createProxy(value, state))111 },112 has(state, prop) {113 return prop in latest(state)114 },115 ownKeys(state) {116 return Reflect.ownKeys(latest(state))117 },118 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) {146 const owner = latest(state)147 const desc = Reflect.getOwnPropertyDescriptor(owner, prop)148 if (desc) {149 desc.writable = true150 desc.configurable = !Array.isArray(owner) || prop !== "length"151 }152 return desc153 },154 defineProperty() {155 throw new Error("Object.defineProperty() cannot be used on an Immer draft") // prettier-ignore156 },157 getPrototypeOf(state) {158 return Object.getPrototypeOf(state.base)159 },160 setPrototypeOf() {161 throw new Error("Object.setPrototypeOf() cannot be used on an Immer draft") // prettier-ignore162 }perf: proxy assignaleclarsonbefore adoption53e9ce8
lines 163–164why, one step back163}164chore: reorganize src/proxy.jsAlec Larsonbefore adoption3163a7d
lines 165–168why, one step back165/**166 * Array drafts167 */168perf: proxy assignaleclarsonbefore adoption53e9ce8
lines 169–170why, one step back169const arrayTraps = {}170each(objectTraps, (key, fn) => {run prettier with master config before mergingMichel Weststratebefore adoptionae80361
lines 171–174why, one step back171 arrayTraps[key] = function() {172 arguments[0] = arguments[0][0]173 return fn.apply(this, arguments)174 }perf: proxy assignaleclarsonbefore adoption53e9ce8
lines 175–176why, one step back175})176arrayTraps.deleteProperty = function(state, prop) {run prettier with master config before mergingMichel Weststratebefore adoptionae80361
lines 177–180why, one step back177 if (isNaN(parseInt(prop))) {178 throw new Error("Immer only supports deleting array indices") // prettier-ignore179 }180 return objectTraps.deleteProperty.call(this, state[0], prop)perf: proxy assignaleclarsonbefore adoption53e9ce8
lines 181–182why, one step back181}182arrayTraps.set = function(state, prop, value) {run prettier with master config before mergingMichel Weststratebefore adoptionae80361
lines 183–186why, 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 }186 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–190why, one step back189// Used by Map and Set drafts190const reflectTraps = makeReflectTraps([run prettier with master config before mergingMichel Weststratebefore adoptionae80361
lines 191–199why, one step back191 "ownKeys",192 "has",193 "set",194 "deleteProperty",195 "defineProperty",196 "getOwnPropertyDescriptor",197 "preventExtensions",198 "isExtensible",199 "getPrototypeOf"refactor: makeTrapsForGetters functionAlec Larsonbefore adoption5093fd0
lines 200–201why, one step back200])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({run prettier with master config before mergingMichel Weststratebefore adoptionae80361
lines 207–244why, one step back207 [DRAFT_STATE]: state => state,208 size: state => latest(state).size,209 has: state => key => latest(state).has(key),210 set: state => (key, value) => {211 const values = latest(state)212 if (!values.has(key) || values.get(key) !== value) {213 markChanged(state)214 state.assigned.set(key, true)215 state.copy.set(key, value)216 }217 return state.draft218 },219 delete: state => key => {220 if (latest(state).has(key)) {221 markChanged(state)222 state.assigned.set(key, false)223 return state.copy.delete(key)224 }225 return false226 },227 clear: state => () => {228 markChanged(state)229 state.assigned = new Map()230 for (const key of latest(state).keys()) {231 state.assigned.set(key, false)232 }233 return state.copy.clear()234 },235 forEach: (state, _, receiver) => (cb, thisArg) =>236 latest(state).forEach((_, key, map) => {237 const value = receiver.get(key)238 cb.call(thisArg, value, key, map)239 }),240 get: state => key => {241 const drafts = state[state.modified ? "copy" : "drafts"]242 if (drafts.has(key)) {243 return drafts.get(key)244 }chore: reorganize src/proxy.jsAlec Larsonbefore adoption3163a7d
line 245why, one step back245run prettier with master config before mergingMichel Weststratebefore adoptionae80361
lines 246–249why, one step back246 const value = latest(state).get(key)247 if (state.finalized || !isDraftable(value)) {248 return value249 }feat: `Map` drafts and patcheskeenondrumsbefore adoption30db0f3
line 250why, one step back250run prettier with master config before mergingMichel Weststratebefore adoptionae80361
lines 251–258why, one step back251 const draft = createProxy(value, state)252 drafts.set(key, draft)253 return draft254 },255 keys: state => () => latest(state).keys(),256 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({run prettier with master config before mergingMichel Weststratebefore adoptionae80361
lines 267–296why, one step back267 [DRAFT_STATE]: state => state,268 size: state => latest(state).size,269 has: state => key => latest(state).has(key),270 add: state => value => {271 if (!latest(state).has(value)) {272 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) {run prettier with master config before mergingMichel Weststratebefore adoptionae80361
line 305why, one step back305 return state.copy || state.basefix: revert Map supportAlec Larsonbefore adoption47529d3
line 306why, one step back306}chore: reorganize src/proxy.jsAlec Larsonbefore adoptione809ffc
line 307why, one step back307fix: revert Map supportAlec Larsonbefore adoption47529d3
lines 308–309why, one step back308// Access a property without creating an Immer draft.309function peek(draft, prop) {run prettier with master config before mergingMichel Weststratebefore adoptionae80361
lines 310–315why, one step back310 const state = draft[DRAFT_STATE]311 const desc = Reflect.getOwnPropertyDescriptor(312 state ? latest(state) : draft,313 prop314 )315 return desc && desc.valueperf: proxy assignaleclarsonbefore adoption53e9ce8
lines 316–318why, one step back316}317318function markChanged(state) {run prettier with master config before mergingMichel Weststratebefore adoptionae80361
lines 319–320why, one step back319 if (!state.modified) {320 state.modified = truerefactor: markChanged functionAlec Larsonbefore adoption5857d63
line 321why, one step back321run prettier with master config before mergingMichel Weststratebefore adoptionae80361
lines 322–323why, one step back322 const {base, drafts, parent} = state323 const copy = shallowCopy(base)refactor: markChanged functionAlec Larsonbefore adoption5857d63
line 324why, one step back324run prettier with master config before mergingMichel Weststratebefore adoptionae80361
lines 325–334why, one step back325 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)333 state.drafts = null334 }refactor: markChanged functionAlec Larsonbefore adoption5857d63
line 335why, one step back335run prettier with master config before mergingMichel Weststratebefore adoptionae80361
lines 336–340why, one step back336 state.copy = copy337 if (parent) {338 markChanged(parent)339 }340 }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
line 344why, one step back344function makeReflectTraps(names) {run prettier with master config before mergingMichel Weststratebefore adoptionae80361
lines 345–348why, one step back345 return names.reduce((traps, name) => {346 traps[name] = (state, ...args) => Reflect[name](latest(state), ...args)347 return traps348 }, {})refactor: makeTrapsForGetters functionAlec Larsonbefore adoption5093fd0
lines 349–350why, one step back349}350refactor: traps for Maps and Setskeenondrumsbefore adoptiondd82d89
line 351why, one step back351function makeTrapsForGetters(getters) {run prettier with master config before mergingMichel Weststratebefore adoptionae80361
lines 352–362why, one step back352 return {353 ...reflectTraps,354 get(state, prop, receiver) {355 return getters.hasOwnProperty(prop)356 ? getters[prop](state, prop, receiver)357 : Reflect.get(state, prop, receiver)358 },359 setPrototypeOf(state) {360 throw new Error("Object.setPrototypeOf() cannot be used on an Immer draft") // prettier-ignore361 }362 }perf: proxy assignaleclarsonbefore adoption53e9ce8
line 363why, one step back363}