proxy.js
This file
Path
src/proxy.js
374 lines · 9.0 KiB · JavaScript
Last changed by
Merge branch 'master' into map-fixesMichel Weststratebefore adoptione4117ff
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–244why, 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 => {Merge branch 'master' into map-fixesMichel Weststratebefore adoptione4117ff
lines 245–246why, one step back245 const drafts = state.modified ? state.copy : state.drafts246feat: added first class support for `Map` and `Set`Michel Weststratebefore adoptionb6f1d40
line 247why, one step back247 if (drafts.has(key)) {Merge branch 'master' into map-fixesMichel Weststratebefore adoptione4117ff
lines 248–254why, one step back248 const value = drafts.get(key)249250 if (isDraft(value) || !isDraftable(value)) return value251252 const draft = createProxy(value, state)253 drafts.set(key, draft)254 return draftfeat: added first class support for `Map` and `Set`Michel Weststratebefore adoptionb6f1d40
lines 255–315why, one step back255 }256257 const value = latest(state).get(key)258 if (state.finalized || !isDraftable(value)) {259 return value260 }261262 const draft = createProxy(value, state)263 drafts.set(key, draft)264 return draft265 },266 keys: state => () => latest(state).keys(),267 values: iterateMapValues,268 entries: iterateMapValues,269 [hasSymbol ? Symbol.iterator : "@@iterator"]: iterateMapValues270})271272const iterateSetValues = makeIterateSetValues(createProxy)273/**274 * Set drafts275 */276277const setTraps = makeTrapsForGetters({278 [DRAFT_STATE]: state => state,279 size: state => latest(state).size,280 has: state => key => latest(state).has(key),281 add: state => value => {282 if (!latest(state).has(value)) {283 markChanged(state)284 state.copy.add(value)285 }286 return state.draft287 },288 delete: state => value => {289 markChanged(state)290 return state.copy.delete(value)291 },292 clear: state => () => {293 markChanged(state)294 return state.copy.clear()295 },296 forEach: state => (cb, thisArg) => {297 const iterator = iterateSetValues(state)()298 let result = iterator.next()299 while (!result.done) {300 cb.call(thisArg, result.value, result.value, state.draft)301 result = iterator.next()302 }303 },304 keys: iterateSetValues,305 values: iterateSetValues,306 entries: iterateSetValues,307 [hasSymbol ? Symbol.iterator : "@@iterator"]: iterateSetValues308})309310/**311 * Helpers312 */313314// Retrieve the latest values of the draft.315function latest(state) {style: use tabsuse-tabsbefore adoptiona9c0fd0
line 316why, one step back316 return state.copy || state.basefix: revert Map supportAlec Larsonbefore adoption47529d3
line 317why, one step back317}chore: reorganize src/proxy.jsAlec Larsonbefore adoptione809ffc
line 318why, one step back318fix: revert Map supportAlec Larsonbefore adoption47529d3
lines 319–320why, one step back319// Access a property without creating an Immer draft.320function peek(draft, prop) {style: use tabsuse-tabsbefore adoptiona9c0fd0
lines 321–322why, one step back321 const state = draft[DRAFT_STATE]322 const desc = Reflect.getOwnPropertyDescriptor(feat: added first class support for `Map` and `Set`Michel Weststratebefore adoptionb6f1d40
line 323why, one step back323 state ? latest(state) : draft,style: use tabsuse-tabsbefore adoptiona9c0fd0
lines 324–326why, one step back324 prop325 )326 return desc && desc.valuechore: reorganize src/proxy.jsAlec Larsonbefore adoptione809ffc
lines 327–328why, one step back327}328feat: added first class support for `Map` and `Set`Michel Weststratebefore adoptionb6f1d40
lines 329–331why, one step back329function markChanged(state) {330 if (!state.modified) {331 state.modified = truechore: reorganize src/proxy.jsAlec Larsonbefore adoptione809ffc
line 332why, one step back332feat: added first class support for `Map` and `Set`Michel Weststratebefore adoptionb6f1d40
lines 333–334why, one step back333 const {base, drafts, parent} = state334 const copy = shallowCopy(base)chore: reorganize src/proxy.jsAlec Larsonbefore adoptione809ffc
line 335why, one step back335feat: added first class support for `Map` and `Set`Michel Weststratebefore adoptionb6f1d40
lines 336–345why, one step back336 if (isSet(base)) {337 // Note: The `drafts` property is preserved for Set objects, since338 // we need to keep track of which values are drafted.339 assignSet(copy, drafts)340 } else {341 // Merge nested drafts into the copy.342 if (isMap(base)) assignMap(copy, drafts)343 else assign(copy, drafts)344 state.drafts = null345 }feat: `Map` supportkeenondrumsbefore adoption8276a6c
line 346why, one step back346feat: added first class support for `Map` and `Set`Michel Weststratebefore adoptionb6f1d40
lines 347–350why, one step back347 state.copy = copy348 if (parent) {349 markChanged(parent)350 }style: use tabsuse-tabsbefore adoptiona9c0fd0
line 351why, one step back351 }chore: reorganize src/proxy.jsAlec Larsonbefore adoptione809ffc
line 352why, one step back352}feat: `Map` supportkeenondrumsbefore adoption8276a6c
line 353why, one step back353feat: added first class support for `Map` and `Set`Michel Weststratebefore adoptionb6f1d40
lines 354–359why, one step back354/** Create traps that all use the `Reflect` API on the `latest(state)` */355function makeReflectTraps(names) {356 return names.reduce((traps, name) => {357 traps[name] = (state, ...args) => Reflect[name](latest(state), ...args)358 return traps359 }, {})chore: remove husky pre-publish hookaleclarsonbefore adoptione0d26ba
lines 360–361why, one step back360}361feat: added first class support for `Map` and `Set`Michel Weststratebefore adoptionb6f1d40
lines 362–372why, one step back362function makeTrapsForGetters(getters) {363 return {364 ...reflectTraps,365 get(state, prop, receiver) {366 return getters.hasOwnProperty(prop)367 ? getters[prop](state, prop, receiver)368 : Reflect.get(state, prop, receiver)369 },370 setPrototypeOf(state) {371 throw new Error("Object.setPrototypeOf() cannot be used on an Immer draft") // prettier-ignore372 }style: use tabsuse-tabsbefore adoptiona9c0fd0
line 373why, one step back373 }chore: remove husky pre-publish hookaleclarsonbefore adoptione0d26ba
line 374why, one step back374}