proxy.ts
This file
Path
src/core/proxy.ts
267 lines · 6.9 KiB · TypeScript
Last changed by
wipMichel Weststratebefore adoptionf33d6b6
History of this fileTake it
Merge pull request #536 from immerjs/multi-bundleMichel Weststratebefore adoption0d87fc8
lines 1–21why, one step back1"use strict"2import {3 each,4 has,5 is,6 isDraftable,7 shallowCopy,8 latest,9 ImmerBaseState,10 ImmerState,11 Drafted,12 AnyObject,13 AnyArray,14 Objectish,15 getCurrentScope,16 DRAFT_STATE,17 die,18 createProxy,19 ProxyTypeProxyObject,20 ProxyTypeProxyArray21} from "../internal"fix: make sure getters are invoked with the correct scope, fixes #558Michel Weststratebefore adoptiond2a47b6
line 22why, one step back22import {isPlainObject} from "../utils/common"Merge pull request #536 from immerjs/multi-bundleMichel Weststratebefore adoption0d87fc8
lines 23–117why, one step back2324interface ProxyBaseState extends ImmerBaseState {25 assigned_: {26 [property: string]: boolean27 }28 parent_?: ImmerState29 drafts_?: {30 [property: string]: Drafted<any, any>31 }32 revoke_(): void33}3435export interface ProxyObjectState extends ProxyBaseState {36 type_: typeof ProxyTypeProxyObject37 base_: AnyObject38 copy_: AnyObject | null39 draft_: Drafted<AnyObject, ProxyObjectState>40}4142export interface ProxyArrayState extends ProxyBaseState {43 type_: typeof ProxyTypeProxyArray44 base_: AnyArray45 copy_: AnyArray | null46 draft_: Drafted<AnyArray, ProxyArrayState>47}4849type ProxyState = ProxyObjectState | ProxyArrayState5051/**52 * Returns a new draft of the `base` object.53 *54 * The second argument is the parent draft-state (used internally).55 */56export function createProxyProxy<T extends Objectish>(57 base: T,58 parent?: ImmerState59): Drafted<T, ProxyState> {60 const isArray = Array.isArray(base)61 const state: ProxyState = {62 type_: isArray ? ProxyTypeProxyArray : (ProxyTypeProxyObject as any),63 // Track which produce call this is associated with.64 scope_: parent ? parent.scope_ : getCurrentScope()!,65 // True for both shallow and deep changes.66 modified_: false,67 // Used during finalization.68 finalized_: false,69 // Track which properties have been assigned (true) or deleted (false).70 assigned_: {},71 // The parent draft state.72 parent_: parent,73 // The base state.74 base_: base,75 // The base proxy.76 draft_: null as any, // set below77 // Any property proxies.78 drafts_: {},79 // The base copy with any updated values.80 copy_: null,81 // Called by the `produce` function.82 revoke_: null as any,83 isManual_: false84 }8586 // the traps must target something, a bit like the 'real' base.87 // but also, we need to be able to determine from the target what the relevant state is88 // (to avoid creating traps per instance to capture the state in closure,89 // and to avoid creating weird hidden properties as well)90 // So the trick is to use 'state' as the actual 'target'! (and make sure we intercept everything)91 // Note that in the case of an array, we put the state in an array to have better Reflect defaults ootb92 let target: T = state as any93 let traps: ProxyHandler<object | Array<any>> = objectTraps94 if (isArray) {95 target = [state] as any96 traps = arrayTraps97 }9899 const {revoke, proxy} = Proxy.revocable(target, traps)100 state.draft_ = proxy as any101 state.revoke_ = revoke102 return proxy as any103}104105/**106 * Object drafts107 */108const objectTraps: ProxyHandler<ProxyState> = {109 get(state, prop) {110 if (prop === DRAFT_STATE) return state111 let {drafts_: drafts} = state112113 // Check for existing draft in unmodified state.114 if (!state.modified_ && has(drafts, prop)) {115 return drafts![prop as any]116 }117fix: make sure getters are invoked with the correct scope, fixes #558Michel Weststratebefore adoptiond2a47b6
lines 118–126why, one step back118 const l = latest(state)119 const desc = Object.getOwnPropertyDescriptor(120 isPlainObject(l) ? l : Object.getPrototypeOf(l),121 prop122 )123 // If the prop is a getter, don't proxy the full prop, but invoke the getter with the correct scope. Fixes #558124 if (desc?.get) return desc.get.call(state.draft_)125126 const value = l[prop]Merge pull request #536 from immerjs/multi-bundleMichel Weststratebefore adoption0d87fc8
lines 127–250why, one step back127 if (state.finalized_ || !isDraftable(value)) {128 return value129 }130131 // Check for existing draft in modified state.132 if (state.modified_) {133 // Assigned values are never drafted. This catches any drafts we created, too.134 if (value !== peek(state.base_, prop)) return value135 // Store drafts on the copy (when one exists).136 // @ts-ignore137 drafts = state.copy_138 }139140 return (drafts![prop as any] = createProxy(141 state.scope_.immer_,142 value,143 state144 ))145 },146 has(state, prop) {147 return prop in latest(state)148 },149 ownKeys(state) {150 return Reflect.ownKeys(latest(state))151 },152 set(state, prop: string /* strictly not, but helps TS */, value) {153 if (!state.modified_) {154 const baseValue = peek(state.base_, prop)155 // Optimize based on value's truthiness. Truthy values are guaranteed to156 // never be undefined, so we can avoid the `in` operator. Lastly, truthy157 // values may be drafts, but falsy values are never drafts.158 const isUnchanged = value159 ? is(baseValue, value) || value === state.drafts_![prop]160 : is(baseValue, value) && prop in state.base_161 if (isUnchanged) return true162 prepareCopy(state)163 markChangedProxy(state)164 }165 state.assigned_[prop] = true166 // @ts-ignore167 state.copy_![prop] = value168 return true169 },170 deleteProperty(state, prop: string) {171 // The `undefined` check is a fast path for pre-existing keys.172 if (peek(state.base_, prop) !== undefined || prop in state.base_) {173 state.assigned_[prop] = false174 prepareCopy(state)175 markChangedProxy(state)176 } else if (state.assigned_[prop]) {177 // if an originally not assigned property was deleted178 delete state.assigned_[prop]179 }180 // @ts-ignore181 if (state.copy_) delete state.copy_[prop]182 return true183 },184 // Note: We never coerce `desc.value` into an Immer draft, because we can't make185 // the same guarantee in ES5 mode.186 getOwnPropertyDescriptor(state, prop) {187 const owner = latest(state)188 const desc = Reflect.getOwnPropertyDescriptor(owner, prop)189 if (desc) {190 desc.writable = true191 desc.configurable =192 state.type_ !== ProxyTypeProxyArray || prop !== "length"193 }194 return desc195 },196 defineProperty() {197 die(11)198 },199 getPrototypeOf(state) {200 return Object.getPrototypeOf(state.base_)201 },202 setPrototypeOf() {203 die(12)204 }205}206207/**208 * Array drafts209 */210211const arrayTraps: ProxyHandler<[ProxyArrayState]> = {}212each(objectTraps, (key, fn) => {213 // @ts-ignore214 arrayTraps[key] = function() {215 arguments[0] = arguments[0][0]216 return fn.apply(this, arguments)217 }218})219arrayTraps.deleteProperty = function(state, prop) {220 if (__DEV__ && isNaN(parseInt(prop as any))) die(13)221 return objectTraps.deleteProperty!.call(this, state[0], prop)222}223arrayTraps.set = function(state, prop, value) {224 if (__DEV__ && prop !== "length" && isNaN(parseInt(prop as any))) die(14)225 return objectTraps.set!.call(this, state[0], prop, value, state[0])226}227228/**229 * Map drafts230 */231232// Access a property without creating an Immer draft.233function peek(draft: Drafted, prop: PropertyKey): any {234 const state = draft[DRAFT_STATE]235 const desc = Reflect.getOwnPropertyDescriptor(236 state ? latest(state) : draft,237 prop238 )239 return desc && desc.value240}241242export function markChangedProxy(state: ImmerState) {243 if (!state.modified_) {244 state.modified_ = true245 if (246 state.type_ === ProxyTypeProxyObject ||247 state.type_ === ProxyTypeProxyArray248 ) {249 const copy = (state.copy_ = shallowCopy(state.base_))250 each(state.drafts_!, (key, value) => {fix: make sure getters are invoked with the correct scope, fixes #558Michel Weststratebefore adoptiond2a47b6
lines 251–252why, one step back251 // @ts-ignore252 copy[key] = valueMerge pull request #536 from immerjs/multi-bundleMichel Weststratebefore adoption0d87fc8
lines 253–267why, one step back253 })254 state.drafts_ = undefined255 }256257 if (state.parent_) {258 markChangedProxy(state.parent_)259 }260 }261}262263function prepareCopy(state: ProxyState) {264 if (!state.copy_) {265 state.copy_ = shallowCopy(state.base_)266 }267}