proxy.ts
This file
Path
src/core/proxy.ts
271 lines · 7.3 KiB · TypeScript
Last changed by
fix: reconcile if the original value is assigned after creating a draft. Fixes #659Michel Weststratebefore adoptionc0e6749
History of this fileTake it
Merge pull request #536 from immerjs/multi-bundleMichel Weststratebefore adoption0d87fc8
lines 1–20why, 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"fix: reconcile if the original value is assigned after creating a draft. Fixes #659Michel Weststratebefore adoptionc0e6749
line 21why, one step back21import {isDraft} from "../utils/common"Merge pull request #536 from immerjs/multi-bundleMichel Weststratebefore adoption0d87fc8
lines 22–32why, one step back2223interface ProxyBaseState extends ImmerBaseState {24 assigned_: {25 [property: string]: boolean26 }27 parent_?: ImmerState28 revoke_(): void29}3031export interface ProxyObjectState extends ProxyBaseState {32 type_: typeof ProxyTypeProxyObjectImmer 7Michel Weststratebefore adoption467ea5d
lines 33–34why, one step back33 base_: any34 copy_: anyMerge pull request #536 from immerjs/multi-bundleMichel Weststratebefore adoption0d87fc8
lines 35–101why, one step back35 draft_: Drafted<AnyObject, ProxyObjectState>36}3738export interface ProxyArrayState extends ProxyBaseState {39 type_: typeof ProxyTypeProxyArray40 base_: AnyArray41 copy_: AnyArray | null42 draft_: Drafted<AnyArray, ProxyArrayState>43}4445type ProxyState = ProxyObjectState | ProxyArrayState4647/**48 * Returns a new draft of the `base` object.49 *50 * The second argument is the parent draft-state (used internally).51 */52export function createProxyProxy<T extends Objectish>(53 base: T,54 parent?: ImmerState55): Drafted<T, ProxyState> {56 const isArray = Array.isArray(base)57 const state: ProxyState = {58 type_: isArray ? ProxyTypeProxyArray : (ProxyTypeProxyObject as any),59 // Track which produce call this is associated with.60 scope_: parent ? parent.scope_ : getCurrentScope()!,61 // True for both shallow and deep changes.62 modified_: false,63 // Used during finalization.64 finalized_: false,65 // Track which properties have been assigned (true) or deleted (false).66 assigned_: {},67 // The parent draft state.68 parent_: parent,69 // The base state.70 base_: base,71 // The base proxy.72 draft_: null as any, // set below73 // The base copy with any updated values.74 copy_: null,75 // Called by the `produce` function.76 revoke_: null as any,77 isManual_: false78 }7980 // the traps must target something, a bit like the 'real' base.81 // but also, we need to be able to determine from the target what the relevant state is82 // (to avoid creating traps per instance to capture the state in closure,83 // and to avoid creating weird hidden properties as well)84 // So the trick is to use 'state' as the actual 'target'! (and make sure we intercept everything)85 // Note that in the case of an array, we put the state in an array to have better Reflect defaults ootb86 let target: T = state as any87 let traps: ProxyHandler<object | Array<any>> = objectTraps88 if (isArray) {89 target = [state] as any90 traps = arrayTraps91 }9293 const {revoke, proxy} = Proxy.revocable(target, traps)94 state.draft_ = proxy as any95 state.revoke_ = revoke96 return proxy as any97}9899/**100 * Object drafts101 */Immer 7Michel Weststratebefore adoption467ea5d
line 102why, one step back102export const objectTraps: ProxyHandler<ProxyState> = {Merge pull request #536 from immerjs/multi-bundleMichel Weststratebefore adoption0d87fc8
lines 103–105why, one step back103 get(state, prop) {104 if (prop === DRAFT_STATE) return state105Immer 7Michel Weststratebefore adoption467ea5d
lines 106–109why, one step back106 const source = latest(state)107 if (!has(source, prop)) {108 // non-existing or non-own property...109 return readPropFromProto(state, source, prop)Merge pull request #536 from immerjs/multi-bundleMichel Weststratebefore adoption0d87fc8
line 110why, one step back110 }Immer 7Michel Weststratebefore adoption467ea5d
line 111why, one step back111 const value = source[prop]Merge pull request #536 from immerjs/multi-bundleMichel Weststratebefore adoption0d87fc8
lines 112–115why, one step back112 if (state.finalized_ || !isDraftable(value)) {113 return value114 }115 // Check for existing draft in modified state.Immer 7Michel Weststratebefore adoption467ea5d
lines 116–123why, one step back116 // Assigned values are never drafted. This catches any drafts we created, too.117 if (value === peek(state.base_, prop)) {118 prepareCopy(state)119 return (state.copy_![prop as any] = createProxy(120 state.scope_.immer_,121 value,122 state123 ))Merge pull request #536 from immerjs/multi-bundleMichel Weststratebefore adoption0d87fc8
line 124why, one step back124 }Immer 7Michel Weststratebefore adoption467ea5d
line 125why, one step back125 return valueMerge pull request #536 from immerjs/multi-bundleMichel Weststratebefore adoption0d87fc8
lines 126–132why, one step back126 },127 has(state, prop) {128 return prop in latest(state)129 },130 ownKeys(state) {131 return Reflect.ownKeys(latest(state))132 },fix: reconcile if the original value is assigned after creating a draft. Fixes #659Michel Weststratebefore adoptionc0e6749
lines 133–137why, one step back133 set(134 state: ProxyObjectState,135 prop: string /* strictly not, but helps TS */,136 value137 ) {fix: Trigger setters with the correct context, fixes #604Michel Weststratebefore adoption2697430
lines 138–144why, one step back138 const desc = getDescriptorFromProto(latest(state), prop)139 if (desc?.set) {140 // special case: if this write is captured by a setter, we have141 // to trigger it with the correct context142 desc.set.call(state.draft_, value)143 return true144 }Merge pull request #536 from immerjs/multi-bundleMichel Weststratebefore adoption0d87fc8
line 145why, one step back145 if (!state.modified_) {fix: make sure changing an undefined value to undefined is not picked up as change. Fixes #646Michel Weststratebefore adoption5521527
lines 146–147why, one step back146 // the last check is because we need to be able to distinguish setting a non-existig to undefined (which is a change)147 // 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 148–153why, one step back148 const current = peek(latest(state), prop)149 // special case, if we assigning the original value to a draft, we can ignore the assignment150 const currentState: ProxyObjectState = current?.[DRAFT_STATE]151 if (currentState && currentState.base_ === value) {152 state.copy_![prop] = value153 state.assigned_[prop] = falseImmer 7Michel Weststratebefore adoption467ea5d
line 154why, one step back154 return truefix: reconcile if the original value is assigned after creating a draft. Fixes #659Michel Weststratebefore adoptionc0e6749
lines 155–157why, one step back155 }156 if (is(value, current) && (value !== undefined || has(state.base_, prop)))157 return trueMerge pull request #536 from immerjs/multi-bundleMichel Weststratebefore adoption0d87fc8
line 158why, one step back158 prepareCopy(state)Immer 7Michel Weststratebefore adoption467ea5d
line 159why, one step back159 markChanged(state)Merge pull request #536 from immerjs/multi-bundleMichel Weststratebefore adoption0d87fc8
lines 160–162why, one step back160 }161 // @ts-ignore162 state.copy_![prop] = valuefix: reconcile if the original value is assigned after creating a draft. Fixes #659Michel Weststratebefore adoptionc0e6749
line 163why, one step back163 state.assigned_[prop] = trueMerge pull request #536 from immerjs/multi-bundleMichel Weststratebefore adoption0d87fc8
lines 164–170why, one step back164 return true165 },166 deleteProperty(state, prop: string) {167 // The `undefined` check is a fast path for pre-existing keys.168 if (peek(state.base_, prop) !== undefined || prop in state.base_) {169 state.assigned_[prop] = false170 prepareCopy(state)Immer 7Michel Weststratebefore adoption467ea5d
lines 171–172why, one step back171 markChanged(state)172 } else {Merge pull request #536 from immerjs/multi-bundleMichel Weststratebefore adoption0d87fc8
lines 173–184why, one step back173 // if an originally not assigned property was deleted174 delete state.assigned_[prop]175 }176 // @ts-ignore177 if (state.copy_) delete state.copy_[prop]178 return true179 },180 // Note: We never coerce `desc.value` into an Immer draft, because we can't make181 // the same guarantee in ES5 mode.182 getOwnPropertyDescriptor(state, prop) {183 const owner = latest(state)184 const desc = Reflect.getOwnPropertyDescriptor(owner, prop)Immer 7Michel Weststratebefore adoption467ea5d
lines 185–190why, one step back185 if (!desc) return desc186 return {187 writable: true,188 configurable: state.type_ !== ProxyTypeProxyArray || prop !== "length",189 enumerable: desc.enumerable,190 value: owner[prop]Merge pull request #536 from immerjs/multi-bundleMichel Weststratebefore adoption0d87fc8
lines 191–225why, one step back191 }192 },193 defineProperty() {194 die(11)195 },196 getPrototypeOf(state) {197 return Object.getPrototypeOf(state.base_)198 },199 setPrototypeOf() {200 die(12)201 }202}203204/**205 * Array drafts206 */207208const arrayTraps: ProxyHandler<[ProxyArrayState]> = {}209each(objectTraps, (key, fn) => {210 // @ts-ignore211 arrayTraps[key] = function() {212 arguments[0] = arguments[0][0]213 return fn.apply(this, arguments)214 }215})216arrayTraps.deleteProperty = function(state, prop) {217 if (__DEV__ && isNaN(parseInt(prop as any))) die(13)218 return objectTraps.deleteProperty!.call(this, state[0], prop)219}220arrayTraps.set = function(state, prop, value) {221 if (__DEV__ && prop !== "length" && isNaN(parseInt(prop as any))) die(14)222 return objectTraps.set!.call(this, state[0], prop, value, state[0])223}224225// Access a property without creating an Immer draft.Immer 7Michel Weststratebefore adoption467ea5d
line 226why, one step back226function peek(draft: Drafted, prop: PropertyKey) {Merge pull request #536 from immerjs/multi-bundleMichel Weststratebefore adoption0d87fc8
line 227why, one step back227 const state = draft[DRAFT_STATE]Immer 7Michel Weststratebefore adoption467ea5d
lines 228–229why, one step back228 const source = state ? latest(state) : draft229 return source[prop]Merge pull request #536 from immerjs/multi-bundleMichel Weststratebefore adoption0d87fc8
lines 230–231why, one step back230}231Immer 7Michel Weststratebefore adoption467ea5d
line 232why, one step back232function readPropFromProto(state: ImmerState, source: any, prop: PropertyKey) {fix: Trigger setters with the correct context, fixes #604Michel Weststratebefore adoption2697430
lines 233–246why, one step back233 const desc = getDescriptorFromProto(source, prop)234 return desc235 ? `value` in desc236 ? desc.value237 : // This is a very special case, if the prop is a getter defined by the238 // prototype, we should invoke it with the draft as context!239 desc.get?.call(state.draft_)240 : undefined241}242243function getDescriptorFromProto(244 source: any,245 prop: PropertyKey246): PropertyDescriptor | undefined {Immer 7Michel Weststratebefore adoption467ea5d
lines 247–251why, one step back247 // 'in' checks proto!248 if (!(prop in source)) return undefined249 let proto = Object.getPrototypeOf(source)250 while (proto) {251 const desc = Object.getOwnPropertyDescriptor(proto, prop)fix: Trigger setters with the correct context, fixes #604Michel Weststratebefore adoption2697430
line 252why, one step back252 if (desc) return descImmer 7Michel Weststratebefore adoption467ea5d
lines 253–258why, one step back253 proto = Object.getPrototypeOf(proto)254 }255 return undefined256}257258export function markChanged(state: ImmerState) {Merge pull request #536 from immerjs/multi-bundleMichel Weststratebefore adoption0d87fc8
lines 259–261why, one step back259 if (!state.modified_) {260 state.modified_ = true261 if (state.parent_) {Immer 7Michel Weststratebefore adoption467ea5d
line 262why, one step back262 markChanged(state.parent_)Merge pull request #536 from immerjs/multi-bundleMichel Weststratebefore adoption0d87fc8
lines 263–266why, one step back263 }264 }265}266Immer 7Michel Weststratebefore adoption467ea5d
line 267why, one step back267export function prepareCopy(state: {base_: any; copy_: any}) {Merge pull request #536 from immerjs/multi-bundleMichel Weststratebefore adoption0d87fc8
lines 268–271why, one step back268 if (!state.copy_) {269 state.copy_ = shallowCopy(state.base_)270 }271}