proxy.ts
This file
Path
src/core/proxy.ts
273 lines · 7.3 KiB · TypeScript
Last changed by
chore: Fix typo in comment (#776)inokawabefore adoptionffa3972
History of this fileTake it
Merge pull request #536 from immerjs/multi-bundleMichel Weststratebefore adoption0d87fc8
lines 1–31why, one step back1import {2 each,3 has,4 is,5 isDraftable,6 shallowCopy,7 latest,8 ImmerBaseState,9 ImmerState,10 Drafted,11 AnyObject,12 AnyArray,13 Objectish,14 getCurrentScope,15 DRAFT_STATE,16 die,17 createProxy,18 ProxyTypeProxyObject,19 ProxyTypeProxyArray20} from "../internal"2122interface ProxyBaseState extends ImmerBaseState {23 assigned_: {24 [property: string]: boolean25 }26 parent_?: ImmerState27 revoke_(): void28}2930export interface ProxyObjectState extends ProxyBaseState {31 type_: typeof ProxyTypeProxyObjectImmer 7Michel Weststratebefore adoption467ea5d
lines 32–33why, one step back32 base_: any33 copy_: anyMerge pull request #536 from immerjs/multi-bundleMichel Weststratebefore adoption0d87fc8
lines 34–100why, one step back34 draft_: Drafted<AnyObject, ProxyObjectState>35}3637export interface ProxyArrayState extends ProxyBaseState {38 type_: typeof ProxyTypeProxyArray39 base_: AnyArray40 copy_: AnyArray | null41 draft_: Drafted<AnyArray, ProxyArrayState>42}4344type ProxyState = ProxyObjectState | ProxyArrayState4546/**47 * Returns a new draft of the `base` object.48 *49 * The second argument is the parent draft-state (used internally).50 */51export function createProxyProxy<T extends Objectish>(52 base: T,53 parent?: ImmerState54): Drafted<T, ProxyState> {55 const isArray = Array.isArray(base)56 const state: ProxyState = {57 type_: isArray ? ProxyTypeProxyArray : (ProxyTypeProxyObject as any),58 // Track which produce call this is associated with.59 scope_: parent ? parent.scope_ : getCurrentScope()!,60 // True for both shallow and deep changes.61 modified_: false,62 // Used during finalization.63 finalized_: false,64 // Track which properties have been assigned (true) or deleted (false).65 assigned_: {},66 // The parent draft state.67 parent_: parent,68 // The base state.69 base_: base,70 // The base proxy.71 draft_: null as any, // set below72 // The base copy with any updated values.73 copy_: null,74 // Called by the `produce` function.75 revoke_: null as any,76 isManual_: false77 }7879 // the traps must target something, a bit like the 'real' base.80 // but also, we need to be able to determine from the target what the relevant state is81 // (to avoid creating traps per instance to capture the state in closure,82 // and to avoid creating weird hidden properties as well)83 // So the trick is to use 'state' as the actual 'target'! (and make sure we intercept everything)84 // Note that in the case of an array, we put the state in an array to have better Reflect defaults ootb85 let target: T = state as any86 let traps: ProxyHandler<object | Array<any>> = objectTraps87 if (isArray) {88 target = [state] as any89 traps = arrayTraps90 }9192 const {revoke, proxy} = Proxy.revocable(target, traps)93 state.draft_ = proxy as any94 state.revoke_ = revoke95 return proxy as any96}9798/**99 * Object drafts100 */Immer 7Michel Weststratebefore adoption467ea5d
line 101why, one step back101export const objectTraps: ProxyHandler<ProxyState> = {Merge pull request #536 from immerjs/multi-bundleMichel Weststratebefore adoption0d87fc8
lines 102–104why, one step back102 get(state, prop) {103 if (prop === DRAFT_STATE) return state104Immer 7Michel Weststratebefore adoption467ea5d
lines 105–108why, one step back105 const source = latest(state)106 if (!has(source, prop)) {107 // non-existing or non-own property...108 return readPropFromProto(state, source, prop)Merge pull request #536 from immerjs/multi-bundleMichel Weststratebefore adoption0d87fc8
line 109why, one step back109 }Immer 7Michel Weststratebefore adoption467ea5d
line 110why, one step back110 const value = source[prop]Merge pull request #536 from immerjs/multi-bundleMichel Weststratebefore adoption0d87fc8
lines 111–114why, one step back111 if (state.finalized_ || !isDraftable(value)) {112 return value113 }114 // Check for existing draft in modified state.Immer 7Michel Weststratebefore adoption467ea5d
lines 115–122why, one step back115 // Assigned values are never drafted. This catches any drafts we created, too.116 if (value === peek(state.base_, prop)) {117 prepareCopy(state)118 return (state.copy_![prop as any] = createProxy(119 state.scope_.immer_,120 value,121 state122 ))Merge pull request #536 from immerjs/multi-bundleMichel Weststratebefore adoption0d87fc8
line 123why, one step back123 }Immer 7Michel Weststratebefore adoption467ea5d
line 124why, one step back124 return valueMerge pull request #536 from immerjs/multi-bundleMichel Weststratebefore adoption0d87fc8
lines 125–131why, one step back125 },126 has(state, prop) {127 return prop in latest(state)128 },129 ownKeys(state) {130 return Reflect.ownKeys(latest(state))131 },fix: reconcile if the original value is assigned after creating a draft. Fixes #659Michel Weststratebefore adoptionc0e6749
lines 132–136why, one step back132 set(133 state: ProxyObjectState,134 prop: string /* strictly not, but helps TS */,135 value136 ) {fix: Trigger setters with the correct context, fixes #604Michel Weststratebefore adoption2697430
lines 137–143why, one step back137 const desc = getDescriptorFromProto(latest(state), prop)138 if (desc?.set) {139 // special case: if this write is captured by a setter, we have140 // to trigger it with the correct context141 desc.set.call(state.draft_, value)142 return true143 }Merge pull request #536 from immerjs/multi-bundleMichel Weststratebefore adoption0d87fc8
line 144why, one step back144 if (!state.modified_) {chore: Fix typo in comment (#776)inokawabefore adoptionffa3972
line 145why, one step back145 // the last check is because we need to be able to distinguish setting a non-existing to undefined (which is a change)fix: make sure changing an undefined value to undefined is not picked up as change. Fixes #646Michel Weststratebefore adoption5521527
line 146why, one step back146 // from setting an existing property with value undefined to undefined (which is not a change)fix: reconcile if the original value is assigned after creating a draft. Fixes #659Michel Weststratebefore adoptionc0e6749
lines 147–152why, one step back147 const current = peek(latest(state), prop)148 // special case, if we assigning the original value to a draft, we can ignore the assignment149 const currentState: ProxyObjectState = current?.[DRAFT_STATE]150 if (currentState && currentState.base_ === value) {151 state.copy_![prop] = value152 state.assigned_[prop] = falseImmer 7Michel Weststratebefore adoption467ea5d
line 153why, one step back153 return truefix: reconcile if the original value is assigned after creating a draft. Fixes #659Michel Weststratebefore adoptionc0e6749
lines 154–156why, one step back154 }155 if (is(value, current) && (value !== undefined || has(state.base_, prop)))156 return trueMerge pull request #536 from immerjs/multi-bundleMichel Weststratebefore adoption0d87fc8
line 157why, one step back157 prepareCopy(state)Immer 7Michel Weststratebefore adoption467ea5d
line 158why, one step back158 markChanged(state)Merge pull request #536 from immerjs/multi-bundleMichel Weststratebefore adoption0d87fc8
line 159why, one step back159 }fix: Ignore equal reference assignments. Fixes #648Michel Weststratebefore adoption3b4286d
lines 160–162why, one step back160161 if (state.copy_![prop] === value && typeof value !== "number") return true162Merge pull request #536 from immerjs/multi-bundleMichel Weststratebefore adoption0d87fc8
lines 163–164why, one step back163 // @ts-ignore164 state.copy_![prop] = valuefix: reconcile if the original value is assigned after creating a draft. Fixes #659Michel Weststratebefore adoptionc0e6749
line 165why, one step back165 state.assigned_[prop] = trueMerge pull request #536 from immerjs/multi-bundleMichel Weststratebefore adoption0d87fc8
lines 166–172why, one step back166 return true167 },168 deleteProperty(state, prop: string) {169 // The `undefined` check is a fast path for pre-existing keys.170 if (peek(state.base_, prop) !== undefined || prop in state.base_) {171 state.assigned_[prop] = false172 prepareCopy(state)Immer 7Michel Weststratebefore adoption467ea5d
lines 173–174why, one step back173 markChanged(state)174 } else {Merge pull request #536 from immerjs/multi-bundleMichel Weststratebefore adoption0d87fc8
lines 175–186why, one step back175 // if an originally not assigned property was deleted176 delete state.assigned_[prop]177 }178 // @ts-ignore179 if (state.copy_) delete state.copy_[prop]180 return true181 },182 // Note: We never coerce `desc.value` into an Immer draft, because we can't make183 // the same guarantee in ES5 mode.184 getOwnPropertyDescriptor(state, prop) {185 const owner = latest(state)186 const desc = Reflect.getOwnPropertyDescriptor(owner, prop)Immer 7Michel Weststratebefore adoption467ea5d
lines 187–192why, one step back187 if (!desc) return desc188 return {189 writable: true,190 configurable: state.type_ !== ProxyTypeProxyArray || prop !== "length",191 enumerable: desc.enumerable,192 value: owner[prop]Merge pull request #536 from immerjs/multi-bundleMichel Weststratebefore adoption0d87fc8
lines 193–227why, one step back193 }194 },195 defineProperty() {196 die(11)197 },198 getPrototypeOf(state) {199 return Object.getPrototypeOf(state.base_)200 },201 setPrototypeOf() {202 die(12)203 }204}205206/**207 * Array drafts208 */209210const arrayTraps: ProxyHandler<[ProxyArrayState]> = {}211each(objectTraps, (key, fn) => {212 // @ts-ignore213 arrayTraps[key] = function() {214 arguments[0] = arguments[0][0]215 return fn.apply(this, arguments)216 }217})218arrayTraps.deleteProperty = function(state, prop) {219 if (__DEV__ && isNaN(parseInt(prop as any))) die(13)220 return objectTraps.deleteProperty!.call(this, state[0], prop)221}222arrayTraps.set = function(state, prop, value) {223 if (__DEV__ && prop !== "length" && isNaN(parseInt(prop as any))) die(14)224 return objectTraps.set!.call(this, state[0], prop, value, state[0])225}226227// Access a property without creating an Immer draft.Immer 7Michel Weststratebefore adoption467ea5d
line 228why, one step back228function peek(draft: Drafted, prop: PropertyKey) {Merge pull request #536 from immerjs/multi-bundleMichel Weststratebefore adoption0d87fc8
line 229why, one step back229 const state = draft[DRAFT_STATE]Immer 7Michel Weststratebefore adoption467ea5d
lines 230–231why, one step back230 const source = state ? latest(state) : draft231 return source[prop]Merge pull request #536 from immerjs/multi-bundleMichel Weststratebefore adoption0d87fc8
lines 232–233why, one step back232}233Immer 7Michel Weststratebefore adoption467ea5d
line 234why, one step back234function readPropFromProto(state: ImmerState, source: any, prop: PropertyKey) {fix: Trigger setters with the correct context, fixes #604Michel Weststratebefore adoption2697430
lines 235–248why, one step back235 const desc = getDescriptorFromProto(source, prop)236 return desc237 ? `value` in desc238 ? desc.value239 : // This is a very special case, if the prop is a getter defined by the240 // prototype, we should invoke it with the draft as context!241 desc.get?.call(state.draft_)242 : undefined243}244245function getDescriptorFromProto(246 source: any,247 prop: PropertyKey248): PropertyDescriptor | undefined {Immer 7Michel Weststratebefore adoption467ea5d
lines 249–253why, one step back249 // 'in' checks proto!250 if (!(prop in source)) return undefined251 let proto = Object.getPrototypeOf(source)252 while (proto) {253 const desc = Object.getOwnPropertyDescriptor(proto, prop)fix: Trigger setters with the correct context, fixes #604Michel Weststratebefore adoption2697430
line 254why, one step back254 if (desc) return descImmer 7Michel Weststratebefore adoption467ea5d
lines 255–260why, one step back255 proto = Object.getPrototypeOf(proto)256 }257 return undefined258}259260export function markChanged(state: ImmerState) {Merge pull request #536 from immerjs/multi-bundleMichel Weststratebefore adoption0d87fc8
lines 261–263why, one step back261 if (!state.modified_) {262 state.modified_ = true263 if (state.parent_) {Immer 7Michel Weststratebefore adoption467ea5d
line 264why, one step back264 markChanged(state.parent_)Merge pull request #536 from immerjs/multi-bundleMichel Weststratebefore adoption0d87fc8
lines 265–268why, one step back265 }266 }267}268Immer 7Michel Weststratebefore adoption467ea5d
line 269why, one step back269export function prepareCopy(state: {base_: any; copy_: any}) {Merge pull request #536 from immerjs/multi-bundleMichel Weststratebefore adoption0d87fc8
lines 270–273why, one step back270 if (!state.copy_) {271 state.copy_ = shallowCopy(state.base_)272 }273}