Skip to content
Myr

proxy.ts

This file

Path

src/core/proxy.ts

258 lines · 6.6 KiB · TypeScript

Last changed by

unclassed scopeMichel Weststratebefore adoption7a38af9

History of this file

Take it

Moving files into foldersMichel Weststratebefore adoptionab49edc

lines 1–14why, one step back
1"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,

unclassed scopeMichel Weststratebefore adoption7a38af9

line 15why, one step back
15 getCurrentScope,

Moving files into foldersMichel Weststratebefore adoptionab49edc

lines 16–62why, one step back
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.

unclassed scopeMichel Weststratebefore adoption7a38af9

line 63why, one step back
63 scope_: parent ? parent.scope_ : getCurrentScope()!,

Moving files into foldersMichel Weststratebefore adoptionab49edc

lines 64–258why, one step back
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 const {revoke, proxy} = Proxy.revocable(target, traps)99 state.draft_ = proxy as any100 state.revoke_ = revoke101 return proxy as any102}103104/**105 * Object drafts106 */107const objectTraps: ProxyHandler<ProxyState> = {108 get(state, prop) {109 if (prop === DRAFT_STATE) return state110 let {drafts_: drafts} = state111112 // Check for existing draft in unmodified state.113 if (!state.modified_ && has(drafts, prop)) {114 return drafts![prop as any]115 }116117 const value = latest(state)[prop]118 if (state.finalized_ || !isDraftable(value)) {119 return value120 }121122 // Check for existing draft in modified state.123 if (state.modified_) {124 // Assigned values are never drafted. This catches any drafts we created, too.125 if (value !== peek(state.base_, prop)) return value126 // Store drafts on the copy (when one exists).127 // @ts-ignore128 drafts = state.copy_129 }130131 return (drafts![prop as any] = createProxy(132 state.scope_.immer_,133 value,134 state135 ))136 },137 has(state, prop) {138 return prop in latest(state)139 },140 ownKeys(state) {141 return Reflect.ownKeys(latest(state))142 },143 set(state, prop: string /* strictly not, but helps TS */, value) {144 if (!state.modified_) {145 const baseValue = peek(state.base_, prop)146 // Optimize based on value's truthiness. Truthy values are guaranteed to147 // never be undefined, so we can avoid the `in` operator. Lastly, truthy148 // values may be drafts, but falsy values are never drafts.149 const isUnchanged = value150 ? is(baseValue, value) || value === state.drafts_![prop]151 : is(baseValue, value) && prop in state.base_152 if (isUnchanged) return true153 prepareCopy(state)154 markChangedProxy(state)155 }156 state.assigned_[prop] = true157 // @ts-ignore158 state.copy_![prop] = value159 return true160 },161 deleteProperty(state, prop: string) {162 // The `undefined` check is a fast path for pre-existing keys.163 if (peek(state.base_, prop) !== undefined || prop in state.base_) {164 state.assigned_[prop] = false165 prepareCopy(state)166 markChangedProxy(state)167 } else if (state.assigned_[prop]) {168 // if an originally not assigned property was deleted169 delete state.assigned_[prop]170 }171 // @ts-ignore172 if (state.copy_) delete state.copy_[prop]173 return true174 },175 // Note: We never coerce `desc.value` into an Immer draft, because we can't make176 // the same guarantee in ES5 mode.177 getOwnPropertyDescriptor(state, prop) {178 const owner = latest(state)179 const desc = Reflect.getOwnPropertyDescriptor(owner, prop)180 if (desc) {181 desc.writable = true182 desc.configurable =183 state.type_ !== ProxyTypeProxyArray || prop !== "length"184 }185 return desc186 },187 defineProperty() {188 die(11)189 },190 getPrototypeOf(state) {191 return Object.getPrototypeOf(state.base_)192 },193 setPrototypeOf() {194 die(12)195 }196}197198/**199 * Array drafts200 */201202const arrayTraps: ProxyHandler<[ProxyArrayState]> = {}203each(objectTraps, (key, fn) => {204 // @ts-ignore205 arrayTraps[key] = function() {206 arguments[0] = arguments[0][0]207 return fn.apply(this, arguments)208 }209})210arrayTraps.deleteProperty = function(state, prop) {211 if (__DEV__ && isNaN(parseInt(prop as any))) die(13)212 return objectTraps.deleteProperty!.call(this, state[0], prop)213}214arrayTraps.set = function(state, prop, value) {215 if (__DEV__ && prop !== "length" && isNaN(parseInt(prop as any))) die(14)216 return objectTraps.set!.call(this, state[0], prop, value, state[0])217}218219/**220 * Map drafts221 */222223// Access a property without creating an Immer draft.224function peek(draft: Drafted, prop: PropertyKey): any {225 const state = draft[DRAFT_STATE]226 const desc = Reflect.getOwnPropertyDescriptor(227 state ? latest(state) : draft,228 prop229 )230 return desc && desc.value231}232233export function markChangedProxy(state: ImmerState) {234 if (!state.modified_) {235 state.modified_ = true236 if (237 state.type_ === ProxyTypeProxyObject ||238 state.type_ === ProxyTypeProxyArray239 ) {240 const copy = (state.copy_ = shallowCopy(state.base_))241 each(state.drafts_!, (key, value) => {242 // @ts-ignore243 copy[key] = value244 })245 state.drafts_ = undefined246 }247248 if (state.parent_) {249 markChangedProxy(state.parent_)250 }251 }252}253254function prepareCopy(state: ProxyState) {255 if (!state.copy_) {256 state.copy_ = shallowCopy(state.base_)257 }258}