proxy.ts
This file
Path
src/core/proxy.ts
260 lines · 6.7 KiB · TypeScript
Last changed by
Moving files into foldersMichel Weststratebefore adoptionab49edc
History of this fileTake it
Moving files into foldersMichel Weststratebefore adoptionab49edc
lines 1–260why, 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 ImmerScope,16 DRAFT_STATE,17 die,18 createProxy,19 ProxyTypeProxyObject,20 ProxyTypeProxyArray21} from "../internal"2223interface ProxyBaseState extends ImmerBaseState {24 assigned_: {25 [property: string]: boolean26 }27 parent_?: ImmerState28 drafts_?: {29 [property: string]: Drafted<any, any>30 }31 revoke_(): void32}3334export interface ProxyObjectState extends ProxyBaseState {35 type_: typeof ProxyTypeProxyObject36 base_: AnyObject37 copy_: AnyObject | null38 draft_: Drafted<AnyObject, ProxyObjectState>39}4041export interface ProxyArrayState extends ProxyBaseState {42 type_: typeof ProxyTypeProxyArray43 base_: AnyArray44 copy_: AnyArray | null45 draft_: Drafted<AnyArray, ProxyArrayState>46}4748type ProxyState = ProxyObjectState | ProxyArrayState4950/**51 * Returns a new draft of the `base` object.52 *53 * The second argument is the parent draft-state (used internally).54 */55export function createProxyProxy<T extends Objectish>(56 base: T,57 parent?: ImmerState58): Drafted<T, ProxyState> {59 const isArray = Array.isArray(base)60 const state: ProxyState = {61 type_: isArray ? ProxyTypeProxyArray : (ProxyTypeProxyObject as any),62 // Track which produce call this is associated with.63 scope_: parent ? parent.scope_ : ImmerScope.current_!,64 // True for both shallow and deep changes.65 modified_: false,66 // Used during finalization.67 finalized_: false,68 // Track which properties have been assigned (true) or deleted (false).69 assigned_: {},70 // The parent draft state.71 parent_: parent,72 // The base state.73 base_: base,74 // The base proxy.75 draft_: null as any, // set below76 // Any property proxies.77 drafts_: {},78 // The base copy with any updated values.79 copy_: null,80 // Called by the `produce` function.81 revoke_: null as any,82 isManual_: false83 }8485 // the traps must target something, a bit like the 'real' base.86 // but also, we need to be able to determine from the target what the relevant state is87 // (to avoid creating traps per instance to capture the state in closure,88 // and to avoid creating weird hidden properties as well)89 // So the trick is to use 'state' as the actual 'target'! (and make sure we intercept everything)90 // Note that in the case of an array, we put the state in an array to have better Reflect defaults ootb91 let target: T = state as any92 let traps: ProxyHandler<object | Array<any>> = objectTraps93 if (isArray) {94 target = [state] as any95 traps = arrayTraps96 }9798 // TODO: optimization: might be faster, cheaper if we created a non-revocable proxy99 // and administrate revoking ourselves100 const {revoke, proxy} = Proxy.revocable(target, traps)101 state.draft_ = proxy as any102 state.revoke_ = revoke103 return proxy as any104}105106/**107 * Object drafts108 */109const objectTraps: ProxyHandler<ProxyState> = {110 get(state, prop) {111 if (prop === DRAFT_STATE) return state112 let {drafts_: drafts} = state113114 // Check for existing draft in unmodified state.115 if (!state.modified_ && has(drafts, prop)) {116 return drafts![prop as any]117 }118119 const value = latest(state)[prop]120 if (state.finalized_ || !isDraftable(value)) {121 return value122 }123124 // Check for existing draft in modified state.125 if (state.modified_) {126 // Assigned values are never drafted. This catches any drafts we created, too.127 if (value !== peek(state.base_, prop)) return value128 // Store drafts on the copy (when one exists).129 // @ts-ignore130 drafts = state.copy_131 }132133 return (drafts![prop as any] = createProxy(134 state.scope_.immer_,135 value,136 state137 ))138 },139 has(state, prop) {140 return prop in latest(state)141 },142 ownKeys(state) {143 return Reflect.ownKeys(latest(state))144 },145 set(state, prop: string /* strictly not, but helps TS */, value) {146 if (!state.modified_) {147 const baseValue = peek(state.base_, prop)148 // Optimize based on value's truthiness. Truthy values are guaranteed to149 // never be undefined, so we can avoid the `in` operator. Lastly, truthy150 // values may be drafts, but falsy values are never drafts.151 const isUnchanged = value152 ? is(baseValue, value) || value === state.drafts_![prop]153 : is(baseValue, value) && prop in state.base_154 if (isUnchanged) return true155 prepareCopy(state)156 markChangedProxy(state)157 }158 state.assigned_[prop] = true159 // @ts-ignore160 state.copy_![prop] = value161 return true162 },163 deleteProperty(state, prop: string) {164 // The `undefined` check is a fast path for pre-existing keys.165 if (peek(state.base_, prop) !== undefined || prop in state.base_) {166 state.assigned_[prop] = false167 prepareCopy(state)168 markChangedProxy(state)169 } else if (state.assigned_[prop]) {170 // if an originally not assigned property was deleted171 delete state.assigned_[prop]172 }173 // @ts-ignore174 if (state.copy_) delete state.copy_[prop]175 return true176 },177 // Note: We never coerce `desc.value` into an Immer draft, because we can't make178 // the same guarantee in ES5 mode.179 getOwnPropertyDescriptor(state, prop) {180 const owner = latest(state)181 const desc = Reflect.getOwnPropertyDescriptor(owner, prop)182 if (desc) {183 desc.writable = true184 desc.configurable =185 state.type_ !== ProxyTypeProxyArray || prop !== "length"186 }187 return desc188 },189 defineProperty() {190 die(11)191 },192 getPrototypeOf(state) {193 return Object.getPrototypeOf(state.base_)194 },195 setPrototypeOf() {196 die(12)197 }198}199200/**201 * Array drafts202 */203204const arrayTraps: ProxyHandler<[ProxyArrayState]> = {}205each(objectTraps, (key, fn) => {206 // @ts-ignore207 arrayTraps[key] = function() {208 arguments[0] = arguments[0][0]209 return fn.apply(this, arguments)210 }211})212arrayTraps.deleteProperty = function(state, prop) {213 if (__DEV__ && isNaN(parseInt(prop as any))) die(13)214 return objectTraps.deleteProperty!.call(this, state[0], prop)215}216arrayTraps.set = function(state, prop, value) {217 if (__DEV__ && prop !== "length" && isNaN(parseInt(prop as any))) die(14)218 return objectTraps.set!.call(this, state[0], prop, value, state[0])219}220221/**222 * Map drafts223 */224225// Access a property without creating an Immer draft.226function peek(draft: Drafted, prop: PropertyKey): any {227 const state = draft[DRAFT_STATE]228 const desc = Reflect.getOwnPropertyDescriptor(229 state ? latest(state) : draft,230 prop231 )232 return desc && desc.value233}234235export function markChangedProxy(state: ImmerState) {236 if (!state.modified_) {237 state.modified_ = true238 if (239 state.type_ === ProxyTypeProxyObject ||240 state.type_ === ProxyTypeProxyArray241 ) {242 const copy = (state.copy_ = shallowCopy(state.base_))243 each(state.drafts_!, (key, value) => {244 // @ts-ignore245 copy[key] = value246 })247 state.drafts_ = undefined248 }249250 if (state.parent_) {251 markChangedProxy(state.parent_)252 }253 }254}255256function prepareCopy(state: ProxyState) {257 if (!state.copy_) {258 state.copy_ = shallowCopy(state.base_)259 }260}