proxy.ts
This file
Path
src/proxy.ts
253 lines · 6.8 KiB · TypeScript
Last changed by
🎵...killing me softly, with your fingers... 🎶Michel Weststratebefore adoption19a6b66
History of this fileTake it
Merge branch 'master' into map-fixesMichel Weststratebefore adoptioncb63fb0
lines 1–16why, one step back1"use strict"2import {3 assign,4 each,5 has,6 is,7 isDraftable,8 isDraft,9 isMap,10 isSet,11 hasSymbol,12 shallowCopy,13 DRAFT_STATE,14 assignMap,15 assignSet,16 original,map unification WIPMichel Weststratebefore adoption9bcefb6
line 17why, one step back17 latestMerge branch 'master' into map-fixesMichel Weststratebefore adoptioncb63fb0
lines 18–19why, one step back18} from "./common"19import {ImmerScope} from "./scope"some build fixesMichel Weststratebefore adoption65a377f
lines 20–21why, one step back20import {proxyMap} from "./map"21import {proxySet} from "./set"Introduced proper state typesMichel Weststratebefore adoption3842f85
line 22why, one step back22import {AnyObject, Drafted, ImmerState, AnyArray} from "./types"Merge branch 'master' into map-fixesMichel Weststratebefore adoptioncb63fb0
line 23why, one step back23Introduced proper state typesMichel Weststratebefore adoption3842f85
line 24why, one step back24interface ProxyBaseState {Merge branch 'master' into map-fixesMichel Weststratebefore adoptioncb63fb0
lines 25–27why, one step back25 scope: ImmerScope26 modified: boolean27 finalized: booleanIntroduced proper state typesMichel Weststratebefore adoption3842f85
lines 28–30why, one step back28 assigned: {29 [property: string]: boolean30 }clean up create proxyMichel Weststratebefore adoptionc182c1e
line 31why, one step back31 parent?: ImmerStateIntroduced proper state typesMichel Weststratebefore adoption3842f85
lines 32–34why, one step back32 drafts: {33 [property: string]: Drafted<any, any>34 }Merge branch 'master' into map-fixesMichel Weststratebefore adoptioncb63fb0
lines 35–37why, one step back35 revoke: null | (() => void)36}37Introduced proper state typesMichel Weststratebefore adoption3842f85
lines 38–51why, one step back38export interface ProxyObjectState extends ProxyBaseState {39 type: "proxy_object"40 base: AnyObject41 copy: AnyObject | null42 draft: Drafted<AnyObject, ProxyObjectState>43}4445export interface ProxyArrayState extends ProxyBaseState {46 type: "proxy_array"47 base: AnyArray48 copy: AnyArray | null49 draft: Drafted<AnyArray, ProxyArrayState>50}51Merge branch 'master' into map-fixesMichel Weststratebefore adoptioncb63fb0
lines 52–58why, one step back52/**53 * Returns a new draft of the `base` object.54 *55 * The second argument is the parent draft-state (used internally).56 */57export function createProxy<T extends object>(58 base: T,clean up create proxyMichel Weststratebefore adoptionc182c1e
line 59why, one step back59 parent?: ImmerStateIntroduced proper state typesMichel Weststratebefore adoption3842f85
lines 60–63why, one step back60): Drafted<T, ProxyObjectState | ProxyArrayState> {61 const isArray = Array.isArray(base)62 const state: ProxyObjectState | ProxyArrayState = {63 type: isArray ? "proxy_array" : ("proxy_object" as any),Merge branch 'master' into map-fixesMichel Weststratebefore adoptioncb63fb0
line 64why, one step back64 // Track which produce call this is associated with.clean up create proxyMichel Weststratebefore adoptionc182c1e
line 65why, one step back65 scope: parent ? parent.scope : ImmerScope.current!,Merge branch 'master' into map-fixesMichel Weststratebefore adoptioncb63fb0
lines 66–76why, one step back66 // True for both shallow and deep changes.67 modified: false,68 // Used during finalization.69 finalized: false,70 // Track which properties have been assigned (true) or deleted (false).71 assigned: {},72 // The parent draft state.73 parent,74 // The base state.75 base,76 // The base proxy.Introduced proper state typesMichel Weststratebefore adoption3842f85
line 77why, one step back77 draft: null as any, // set belowMerge branch 'master' into map-fixesMichel Weststratebefore adoptioncb63fb0
lines 78–97why, one step back78 // Any property proxies.79 drafts: {},80 // The base copy with any updated values.81 copy: null,82 // Called by the `produce` function.83 revoke: null84 }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 (Array.isArray(base)) {95 target = [state] as any96 traps = arrayTraps97 }basic map tests succeedingMichel Weststratebefore adoption735c402
line 98why, one step back98Merge branch 'master' into map-fixesMichel Weststratebefore adoptioncb63fb0
line 99why, one step back99 const {revoke, proxy} = Proxy.revocable(target, traps)Introduced proper state typesMichel Weststratebefore adoption3842f85
line 100why, one step back100 state.draft = proxy as anyMerge branch 'master' into map-fixesMichel Weststratebefore adoptioncb63fb0
line 101why, one step back101 state.revoke = revokeIntroduced proper state typesMichel Weststratebefore adoption3842f85
line 102why, one step back102 return proxy as anyMerge branch 'master' into map-fixesMichel Weststratebefore adoptioncb63fb0
lines 103–107why, one step back103}104105/**106 * Object drafts107 */Introduced proper state typesMichel Weststratebefore adoption3842f85
line 108why, one step back108const objectTraps: ProxyHandler<ProxyObjectState | ProxyArrayState> = {Merge branch 'master' into map-fixesMichel Weststratebefore adoptioncb63fb0
lines 109–114why, one step back109 get(state, prop) {110 if (prop === DRAFT_STATE) return state111 let {drafts} = state112113 // Check for existing draft in unmodified state.114 if (!state.modified && has(drafts, prop)) {Introduced proper state typesMichel Weststratebefore adoption3842f85
line 115why, one step back115 return drafts[prop as any]Merge branch 'master' into map-fixesMichel Weststratebefore adoptioncb63fb0
lines 116–127why, one step back116 }117118 const value = latest(state)[prop]119 if (state.finalized || !isDraftable(value)) {120 return value121 }122123 // Check for existing draft in modified state.124 if (state.modified) {125 // Assigned values are never drafted. This catches any drafts we created, too.126 if (value !== peek(state.base, prop)) return value127 // Store drafts on the copy (when one exists).Introduced proper state typesMichel Weststratebefore adoption3842f85
line 128why, one step back128 // @ts-ignore TODO: this line seems of?Merge branch 'master' into map-fixesMichel Weststratebefore adoptioncb63fb0
lines 129–131why, one step back129 drafts = state.copy130 }131clean up create proxyMichel Weststratebefore adoptionc182c1e
line 132why, one step back132 return (drafts[prop as any] = state.scope.immer.createProxy(value, state))Merge branch 'master' into map-fixesMichel Weststratebefore adoptioncb63fb0
lines 133–139why, one step back133 },134 has(state, prop) {135 return prop in latest(state)136 },137 ownKeys(state) {138 return Reflect.ownKeys(latest(state))139 },Introduced proper state typesMichel Weststratebefore adoption3842f85
line 140why, one step back140 set(state, prop: string /* strictly not, but helps TS */, value) {Merge branch 'master' into map-fixesMichel Weststratebefore adoptioncb63fb0
lines 141–149why, one step back141 if (!state.modified) {142 const baseValue = peek(state.base, prop)143 // Optimize based on value's truthiness. Truthy values are guaranteed to144 // never be undefined, so we can avoid the `in` operator. Lastly, truthy145 // values may be drafts, but falsy values are never drafts.146 const isUnchanged = value147 ? is(baseValue, value) || value === state.drafts[prop]148 : is(baseValue, value) && prop in state.base149 if (isUnchanged) return truebasic map tests succeedingMichel Weststratebefore adoption735c402
line 150why, one step back150 prepareCopy(state)Merge branch 'master' into map-fixesMichel Weststratebefore adoptioncb63fb0
lines 151–153why, one step back151 markChanged(state)152 }153 state.assigned[prop] = trueIntroduced proper state typesMichel Weststratebefore adoption3842f85
line 154why, one step back154 state.copy![prop] = valueMerge branch 'master' into map-fixesMichel Weststratebefore adoptioncb63fb0
lines 155–156why, one step back155 return true156 },Introduced proper state typesMichel Weststratebefore adoption3842f85
line 157why, one step back157 deleteProperty(state, prop: string) {Merge branch 'master' into map-fixesMichel Weststratebefore adoptioncb63fb0
lines 158–160why, one step back158 // The `undefined` check is a fast path for pre-existing keys.159 if (peek(state.base, prop) !== undefined || prop in state.base) {160 state.assigned[prop] = falsebasic map tests succeedingMichel Weststratebefore adoption735c402
line 161why, one step back161 prepareCopy(state)Merge branch 'master' into map-fixesMichel Weststratebefore adoptioncb63fb0
lines 162–195why, one step back162 markChanged(state)163 } else if (state.assigned[prop]) {164 // if an originally not assigned property was deleted165 delete state.assigned[prop]166 }167 if (state.copy) delete state.copy[prop]168 return true169 },170 // Note: We never coerce `desc.value` into an Immer draft, because we can't make171 // the same guarantee in ES5 mode.172 getOwnPropertyDescriptor(state, prop) {173 const owner = latest(state)174 const desc = Reflect.getOwnPropertyDescriptor(owner, prop)175 if (desc) {176 desc.writable = true177 desc.configurable = !Array.isArray(owner) || prop !== "length"178 }179 return desc180 },181 defineProperty() {182 throw new Error("Object.defineProperty() cannot be used on an Immer draft") // prettier-ignore183 },184 getPrototypeOf(state) {185 return Object.getPrototypeOf(state.base)186 },187 setPrototypeOf() {188 throw new Error("Object.setPrototypeOf() cannot be used on an Immer draft") // prettier-ignore189 }190}191192/**193 * Array drafts194 */195Introduced proper state typesMichel Weststratebefore adoption3842f85
line 196why, one step back196const arrayTraps: ProxyHandler<[ProxyArrayState]> = {}Merge branch 'master' into map-fixesMichel Weststratebefore adoptioncb63fb0
lines 197–229why, one step back197each(objectTraps, (key, fn) => {198 arrayTraps[key] = function() {199 arguments[0] = arguments[0][0]200 return fn.apply(this, arguments)201 }202})203arrayTraps.deleteProperty = function(state, prop) {204 if (isNaN(parseInt(prop as any))) {205 throw new Error("Immer only supports deleting array indices") // prettier-ignore206 }207 return objectTraps.deleteProperty!.call(this, state[0], prop)208}209arrayTraps.set = function(state, prop, value) {210 if (prop !== "length" && isNaN(parseInt(prop as any))) {211 throw new Error("Immer only supports setting array indices and the 'length' property") // prettier-ignore212 }213 return objectTraps.set!.call(this, state[0], prop, value, state[0])214}215216/**217 * Map drafts218 */219220// Access a property without creating an Immer draft.221function peek(draft, prop) {222 const state = draft[DRAFT_STATE]223 const desc = Reflect.getOwnPropertyDescriptor(224 state ? latest(state) : draft,225 prop226 )227 return desc && desc.value228}229basic map tests succeedingMichel Weststratebefore adoption735c402
lines 230–231why, one step back230// TODO: unify with ES5 version, by getting rid of the drafts vs copy distinction?231export function markChanged(state) {Merge branch 'master' into map-fixesMichel Weststratebefore adoptioncb63fb0
lines 232–234why, one step back232 if (!state.modified) {233 state.modified = true234 const {base, drafts, parent} = statebasic map tests succeedingMichel Weststratebefore adoption735c402
lines 235–236why, one step back235 if (!isMap(base) && !isSet(base)) {236 // TODO: drop creating copies here?some build fixesMichel Weststratebefore adoption65a377f
line 237why, one step back237 const copy = (state.copy = shallowCopy(base))basic map tests succeedingMichel Weststratebefore adoption735c402
line 238why, one step back238 assign(copy, drafts)Merge branch 'master' into map-fixesMichel Weststratebefore adoptioncb63fb0
lines 239–244why, one step back239 state.drafts = null240 }241242 if (parent) {243 markChanged(parent)244 }basic map tests succeedingMichel Weststratebefore adoption735c402
lines 245–251why, one step back245 }246}247248// TODO: unify with ES5 version249function prepareCopy(state) {250 if (!state.copy) {251 state.copy = shallowCopy(state.base)Merge branch 'master' into map-fixesMichel Weststratebefore adoptioncb63fb0
lines 252–253why, one step back252 }253}