proxy.js
This file
Path
src/proxy.js
367 lines · 8.9 KiB · JavaScript
Last changed by
feat: added first class support for `Map` and `Set`Michel Weststratebefore adoptionb6f1d40
History of this fileTake it
The walk stopped after 200 commits: lines older than e0d26ba point at it.
chore: remove husky pre-publish hookaleclarsonbefore adoptione0d26ba
lines 1–2why, one step back1"use strict"2import {style: use tabsuse-tabsbefore adoptiona9c0fd0
lines 3–8why, one step back3 assign,4 each,5 has,6 is,7 isDraftable,8 isDraft,feat: added first class support for `Map` and `Set`Michel Weststratebefore adoptionb6f1d40
lines 9–11why, one step back9 isMap,10 isSet,11 hasSymbol,style: use tabsuse-tabsbefore adoptiona9c0fd0
line 12why, one step back12 shallowCopy,feat: added first class support for `Map` and `Set`Michel Weststratebefore adoptionb6f1d40
lines 13–19why, one step back13 makeIterable,14 DRAFT_STATE,15 assignMap,16 assignSet,17 original,18 iterateMapValues,19 makeIterateSetValueschore: remove husky pre-publish hookaleclarsonbefore adoptione0d26ba
line 20why, one step back20} from "./common"Merge branch 'async-recipes'Michel Weststratebefore adoptionff210d8
line 21why, one step back21import {ImmerScope} from "./scope"chore: remove husky pre-publish hookaleclarsonbefore adoptione0d26ba
line 22why, one step back22feat: add `Immer` classaleclarsonbefore adoptionecd04dc
lines 23–25why, one step back23// Do nothing before being finalized.24export function willFinalize() {}25feat: added first class support for `Map` and `Set`Michel Weststratebefore adoptionb6f1d40
lines 26–30why, one step back26/**27 * Returns a new draft of the `base` object.28 *29 * The second argument is the parent draft-state (used internally).30 */Merge branch 'async-recipes'Michel Weststratebefore adoptionff210d8
line 31why, one step back31export function createProxy(base, parent) {style: use tabsuse-tabsbefore adoptiona9c0fd0
lines 32–54why, one step back32 const scope = parent ? parent.scope : ImmerScope.current33 const state = {34 // Track which produce call this is associated with.35 scope,36 // True for both shallow and deep changes.37 modified: false,38 // Used during finalization.39 finalized: false,40 // Track which properties have been assigned (true) or deleted (false).41 assigned: {},42 // The parent draft state.43 parent,44 // The base state.45 base,46 // The base proxy.47 draft: null,48 // Any property proxies.49 drafts: {},50 // The base copy with any updated values.51 copy: null,52 // Called by the `produce` function.53 revoke: null54 }feat: add `Immer` classaleclarsonbefore adoptionecd04dc
line 55why, one step back55feat: added first class support for `Map` and `Set`Michel Weststratebefore adoptionb6f1d40
lines 56–73why, one step back56 let target = state57 let traps = objectTraps58 if (Array.isArray(base)) {59 target = [state]60 traps = arrayTraps61 }62 // Map drafts must support object keys, so we use Map objects to track changes.63 else if (isMap(base)) {64 traps = mapTraps65 state.drafts = new Map()66 state.assigned = new Map()67 }68 // Set drafts use a Map object to track which of its values are drafted.69 // And we don't need the "assigned" property, because Set objects have no keys.70 else if (isSet(base)) {71 traps = setTraps72 state.drafts = new Map()73 }feat: add `Immer` classaleclarsonbefore adoptionecd04dc
line 74why, one step back74feat: added first class support for `Map` and `Set`Michel Weststratebefore adoptionb6f1d40
lines 75–76why, one step back75 const {revoke, proxy} = Proxy.revocable(target, traps)76style: use tabsuse-tabsbefore adoptiona9c0fd0
lines 77–78why, one step back77 state.draft = proxy78 state.revoke = revokefeat: add `Immer` classaleclarsonbefore adoptionecd04dc
line 79why, one step back79style: use tabsuse-tabsbefore adoptiona9c0fd0
lines 80–81why, one step back80 scope.drafts.push(proxy)81 return proxyfeat: add `Immer` classaleclarsonbefore adoptionecd04dc
lines 82–83why, one step back82}83feat: added first class support for `Map` and `Set`Michel Weststratebefore adoptionb6f1d40
lines 84–87why, one step back84/**85 * Object drafts86 */87chore: remove husky pre-publish hookaleclarsonbefore adoptione0d26ba
line 88why, one step back88const objectTraps = {feat: added first class support for `Map` and `Set`Michel Weststratebefore adoptionb6f1d40
lines 89–111why, one step back89 get(state, prop) {90 if (prop === DRAFT_STATE) return state91 let {drafts} = state9293 // Check for existing draft in unmodified state.94 if (!state.modified && has(drafts, prop)) {95 return drafts[prop]96 }9798 const value = latest(state)[prop]99 if (state.finalized || !isDraftable(value)) {100 return value101 }102103 // Check for existing draft in modified state.104 if (state.modified) {105 // Assigned values are never drafted. This catches any drafts we created, too.106 if (value !== peek(state.base, prop)) return value107 // Store drafts on the copy (when one exists).108 drafts = state.copy109 }110111 return (drafts[prop] = createProxy(value, state))style: use tabsuse-tabsbefore adoptiona9c0fd0
line 112why, one step back112 },feat: added first class support for `Map` and `Set`Michel Weststratebefore adoptionb6f1d40
lines 113–114why, one step back113 has(state, prop) {114 return prop in latest(state)style: use tabsuse-tabsbefore adoptiona9c0fd0
line 115why, one step back115 },feat: added first class support for `Map` and `Set`Michel Weststratebefore adoptionb6f1d40
lines 116–157why, one step back116 ownKeys(state) {117 return Reflect.ownKeys(latest(state))118 },119 set(state, prop, value) {120 if (!state.modified) {121 const baseValue = peek(state.base, prop)122 // Optimize based on value's truthiness. Truthy values are guaranteed to123 // never be undefined, so we can avoid the `in` operator. Lastly, truthy124 // values may be drafts, but falsy values are never drafts.125 const isUnchanged = value126 ? is(baseValue, value) || value === state.drafts[prop]127 : is(baseValue, value) && prop in state.base128 if (isUnchanged) return true129 markChanged(state)130 }131 state.assigned[prop] = true132 state.copy[prop] = value133 return true134 },135 deleteProperty(state, prop) {136 // The `undefined` check is a fast path for pre-existing keys.137 if (peek(state.base, prop) !== undefined || prop in state.base) {138 state.assigned[prop] = false139 markChanged(state)140 } else if (state.assigned[prop]) {141 // if an originally not assigned property was deleted142 delete state.assigned[prop]143 }144 if (state.copy) delete state.copy[prop]145 return true146 },147 // Note: We never coerce `desc.value` into an Immer draft, because we can't make148 // the same guarantee in ES5 mode.149 getOwnPropertyDescriptor(state, prop) {150 const owner = latest(state)151 const desc = Reflect.getOwnPropertyDescriptor(owner, prop)152 if (desc) {153 desc.writable = true154 desc.configurable = !Array.isArray(owner) || prop !== "length"155 }156 return desc157 },style: use tabsuse-tabsbefore adoptiona9c0fd0
lines 158–160why, one step back158 defineProperty() {159 throw new Error("Object.defineProperty() cannot be used on an Immer draft") // prettier-ignore160 },feat: added first class support for `Map` and `Set`Michel Weststratebefore adoptionb6f1d40
lines 161–162why, one step back161 getPrototypeOf(state) {162 return Object.getPrototypeOf(state.base)style: use tabsuse-tabsbefore adoptiona9c0fd0
lines 163–166why, one step back163 },164 setPrototypeOf() {165 throw new Error("Object.setPrototypeOf() cannot be used on an Immer draft") // prettier-ignore166 }chore: remove husky pre-publish hookaleclarsonbefore adoptione0d26ba
lines 167–168why, one step back167}168feat: added first class support for `Map` and `Set`Michel Weststratebefore adoptionb6f1d40
lines 169–172why, one step back169/**170 * Array drafts171 */172chore: remove husky pre-publish hookaleclarsonbefore adoptione0d26ba
lines 173–174why, one step back173const arrayTraps = {}174each(objectTraps, (key, fn) => {style: use tabsuse-tabsbefore adoptiona9c0fd0
lines 175–178why, one step back175 arrayTraps[key] = function() {176 arguments[0] = arguments[0][0]177 return fn.apply(this, arguments)178 }chore: remove husky pre-publish hookaleclarsonbefore adoptione0d26ba
lines 179–180why, one step back179})180arrayTraps.deleteProperty = function(state, prop) {style: use tabsuse-tabsbefore adoptiona9c0fd0
lines 181–184why, one step back181 if (isNaN(parseInt(prop))) {182 throw new Error("Immer only supports deleting array indices") // prettier-ignore183 }184 return objectTraps.deleteProperty.call(this, state[0], prop)chore: remove husky pre-publish hookaleclarsonbefore adoptione0d26ba
lines 185–186why, one step back185}186arrayTraps.set = function(state, prop, value) {style: use tabsuse-tabsbefore adoptiona9c0fd0
lines 187–190why, one step back187 if (prop !== "length" && isNaN(parseInt(prop))) {188 throw new Error("Immer only supports setting array indices and the 'length' property") // prettier-ignore189 }190 return objectTraps.set.call(this, state[0], prop, value)feat: `Map` supportkeenondrumsbefore adoption8276a6c
lines 191–192why, one step back191}192feat: added first class support for `Map` and `Set`Michel Weststratebefore adoptionb6f1d40
lines 193–308why, one step back193// Used by Map and Set drafts194const reflectTraps = makeReflectTraps([195 "ownKeys",196 "has",197 "set",198 "deleteProperty",199 "defineProperty",200 "getOwnPropertyDescriptor",201 "preventExtensions",202 "isExtensible",203 "getPrototypeOf"204])205206/**207 * Map drafts208 */209210const mapTraps = makeTrapsForGetters({211 [DRAFT_STATE]: state => state,212 size: state => latest(state).size,213 has: state => key => latest(state).has(key),214 set: state => (key, value) => {215 const values = latest(state)216 if (!values.has(key) || values.get(key) !== value) {217 markChanged(state)218 state.assigned.set(key, true)219 state.copy.set(key, value)220 }221 return state.draft222 },223 delete: state => key => {224 if (latest(state).has(key)) {225 markChanged(state)226 state.assigned.set(key, false)227 return state.copy.delete(key)228 }229 return false230 },231 clear: state => () => {232 markChanged(state)233 state.assigned = new Map()234 for (const key of latest(state).keys()) {235 state.assigned.set(key, false)236 }237 return state.copy.clear()238 },239 forEach: (state, _, receiver) => (cb, thisArg) =>240 latest(state).forEach((_, key, map) => {241 const value = receiver.get(key)242 cb.call(thisArg, value, key, map)243 }),244 get: state => key => {245 const drafts = state[state.modified ? "copy" : "drafts"]246 if (drafts.has(key)) {247 return drafts.get(key)248 }249250 const value = latest(state).get(key)251 if (state.finalized || !isDraftable(value)) {252 return value253 }254255 const draft = createProxy(value, state)256 drafts.set(key, draft)257 return draft258 },259 keys: state => () => latest(state).keys(),260 values: iterateMapValues,261 entries: iterateMapValues,262 [hasSymbol ? Symbol.iterator : "@@iterator"]: iterateMapValues263})264265const iterateSetValues = makeIterateSetValues(createProxy)266/**267 * Set drafts268 */269270const setTraps = makeTrapsForGetters({271 [DRAFT_STATE]: state => state,272 size: state => latest(state).size,273 has: state => key => latest(state).has(key),274 add: state => value => {275 if (!latest(state).has(value)) {276 markChanged(state)277 state.copy.add(value)278 }279 return state.draft280 },281 delete: state => value => {282 markChanged(state)283 return state.copy.delete(value)284 },285 clear: state => () => {286 markChanged(state)287 return state.copy.clear()288 },289 forEach: state => (cb, thisArg) => {290 const iterator = iterateSetValues(state)()291 let result = iterator.next()292 while (!result.done) {293 cb.call(thisArg, result.value, result.value, state.draft)294 result = iterator.next()295 }296 },297 keys: iterateSetValues,298 values: iterateSetValues,299 entries: iterateSetValues,300 [hasSymbol ? Symbol.iterator : "@@iterator"]: iterateSetValues301})302303/**304 * Helpers305 */306307// Retrieve the latest values of the draft.308function latest(state) {style: use tabsuse-tabsbefore adoptiona9c0fd0
line 309why, one step back309 return state.copy || state.basefix: revert Map supportAlec Larsonbefore adoption47529d3
line 310why, one step back310}chore: reorganize src/proxy.jsAlec Larsonbefore adoptione809ffc
line 311why, one step back311fix: revert Map supportAlec Larsonbefore adoption47529d3
lines 312–313why, one step back312// Access a property without creating an Immer draft.313function peek(draft, prop) {style: use tabsuse-tabsbefore adoptiona9c0fd0
lines 314–315why, one step back314 const state = draft[DRAFT_STATE]315 const desc = Reflect.getOwnPropertyDescriptor(feat: added first class support for `Map` and `Set`Michel Weststratebefore adoptionb6f1d40
line 316why, one step back316 state ? latest(state) : draft,style: use tabsuse-tabsbefore adoptiona9c0fd0
lines 317–319why, one step back317 prop318 )319 return desc && desc.valuechore: reorganize src/proxy.jsAlec Larsonbefore adoptione809ffc
lines 320–321why, one step back320}321feat: added first class support for `Map` and `Set`Michel Weststratebefore adoptionb6f1d40
lines 322–324why, one step back322function markChanged(state) {323 if (!state.modified) {324 state.modified = truechore: reorganize src/proxy.jsAlec Larsonbefore adoptione809ffc
line 325why, one step back325feat: added first class support for `Map` and `Set`Michel Weststratebefore adoptionb6f1d40
lines 326–327why, one step back326 const {base, drafts, parent} = state327 const copy = shallowCopy(base)chore: reorganize src/proxy.jsAlec Larsonbefore adoptione809ffc
line 328why, one step back328feat: added first class support for `Map` and `Set`Michel Weststratebefore adoptionb6f1d40
lines 329–338why, one step back329 if (isSet(base)) {330 // Note: The `drafts` property is preserved for Set objects, since331 // we need to keep track of which values are drafted.332 assignSet(copy, drafts)333 } else {334 // Merge nested drafts into the copy.335 if (isMap(base)) assignMap(copy, drafts)336 else assign(copy, drafts)337 state.drafts = null338 }feat: `Map` supportkeenondrumsbefore adoption8276a6c
line 339why, one step back339feat: added first class support for `Map` and `Set`Michel Weststratebefore adoptionb6f1d40
lines 340–343why, one step back340 state.copy = copy341 if (parent) {342 markChanged(parent)343 }style: use tabsuse-tabsbefore adoptiona9c0fd0
line 344why, one step back344 }chore: reorganize src/proxy.jsAlec Larsonbefore adoptione809ffc
line 345why, one step back345}feat: `Map` supportkeenondrumsbefore adoption8276a6c
line 346why, one step back346feat: added first class support for `Map` and `Set`Michel Weststratebefore adoptionb6f1d40
lines 347–352why, one step back347/** Create traps that all use the `Reflect` API on the `latest(state)` */348function makeReflectTraps(names) {349 return names.reduce((traps, name) => {350 traps[name] = (state, ...args) => Reflect[name](latest(state), ...args)351 return traps352 }, {})chore: remove husky pre-publish hookaleclarsonbefore adoptione0d26ba
lines 353–354why, one step back353}354feat: added first class support for `Map` and `Set`Michel Weststratebefore adoptionb6f1d40
lines 355–365why, one step back355function makeTrapsForGetters(getters) {356 return {357 ...reflectTraps,358 get(state, prop, receiver) {359 return getters.hasOwnProperty(prop)360 ? getters[prop](state, prop, receiver)361 : Reflect.get(state, prop, receiver)362 },363 setPrototypeOf(state) {364 throw new Error("Object.setPrototypeOf() cannot be used on an Immer draft") // prettier-ignore365 }style: use tabsuse-tabsbefore adoptiona9c0fd0
line 366why, one step back366 }chore: remove husky pre-publish hookaleclarsonbefore adoptione0d26ba
line 367why, one step back367}