proxy.ts
This file
Path
src/proxy.ts
252 lines · 6.7 KiB · TypeScript
Last changed by
Several refactoringsMichel Weststratebefore adoptionc7f8f5b
History of this fileTake it
Merge branch 'master' into map-fixesMichel Weststratebefore adoptioncb63fb0
lines 1–8why, one step back1"use strict"2import {3 each,4 has,5 is,6 isDraftable,7 shallowCopy,8 DRAFT_STATE,map unification WIPMichel Weststratebefore adoption9bcefb6
line 9why, one step back9 latestMerge branch 'master' into map-fixesMichel Weststratebefore adoptioncb63fb0
lines 10–11why, one step back10} from "./common"11import {ImmerScope} from "./scope"Processed bunch of todosMichel Weststratebefore adoption00425e1
lines 12–19why, one step back12import {13 AnyObject,14 Drafted,15 ImmerState,16 AnyArray,17 Objectish,18 ImmerBaseState19} from "./types"Merge branch 'master' into map-fixesMichel Weststratebefore adoptioncb63fb0
line 20why, one step back20Processed bunch of todosMichel Weststratebefore adoption00425e1
line 21why, one step back21interface ProxyBaseState extends ImmerBaseState {Introduced proper state typesMichel Weststratebefore adoption3842f85
lines 22–24why, one step back22 assigned: {23 [property: string]: boolean24 }clean up create proxyMichel Weststratebefore adoptionc182c1e
line 25why, one step back25 parent?: ImmerStateProcessed bunch of todosMichel Weststratebefore adoption00425e1
line 26why, one step back26 drafts?: {Introduced proper state typesMichel Weststratebefore adoption3842f85
lines 27–28why, one step back27 [property: string]: Drafted<any, any>28 }Processed bunch of todosMichel Weststratebefore adoption00425e1
line 29why, one step back29 revoke(): voidMerge branch 'master' into map-fixesMichel Weststratebefore adoptioncb63fb0
lines 30–31why, one step back30}31Introduced proper state typesMichel Weststratebefore adoption3842f85
lines 32–45why, one step back32export interface ProxyObjectState extends ProxyBaseState {33 type: "proxy_object"34 base: AnyObject35 copy: AnyObject | null36 draft: Drafted<AnyObject, ProxyObjectState>37}3839export interface ProxyArrayState extends ProxyBaseState {40 type: "proxy_array"41 base: AnyArray42 copy: AnyArray | null43 draft: Drafted<AnyArray, ProxyArrayState>44}45TS type improvementsMichel Weststratebefore adoptiondd1808e
lines 46–47why, one step back46type ProxyState = ProxyObjectState | ProxyArrayState47Merge branch 'master' into map-fixesMichel Weststratebefore adoptioncb63fb0
lines 48–52why, one step back48/**49 * Returns a new draft of the `base` object.50 *51 * The second argument is the parent draft-state (used internally).52 */TS type improvementsMichel Weststratebefore adoptiondd1808e
line 53why, one step back53export function createProxy<T extends Objectish>(Merge branch 'master' into map-fixesMichel Weststratebefore adoptioncb63fb0
line 54why, one step back54 base: T,clean up create proxyMichel Weststratebefore adoptionc182c1e
line 55why, one step back55 parent?: ImmerStateTS type improvementsMichel Weststratebefore adoptiondd1808e
line 56why, one step back56): Drafted<T, ProxyState> {Introduced proper state typesMichel Weststratebefore adoption3842f85
line 57why, one step back57 const isArray = Array.isArray(base)TS type improvementsMichel Weststratebefore adoptiondd1808e
line 58why, one step back58 const state: ProxyState = {Introduced proper state typesMichel Weststratebefore adoption3842f85
line 59why, one step back59 type: isArray ? "proxy_array" : ("proxy_object" as any),Merge branch 'master' into map-fixesMichel Weststratebefore adoptioncb63fb0
line 60why, one step back60 // Track which produce call this is associated with.clean up create proxyMichel Weststratebefore adoptionc182c1e
line 61why, one step back61 scope: parent ? parent.scope : ImmerScope.current!,Merge branch 'master' into map-fixesMichel Weststratebefore adoptioncb63fb0
lines 62–72why, one step back62 // True for both shallow and deep changes.63 modified: false,64 // Used during finalization.65 finalized: false,66 // Track which properties have been assigned (true) or deleted (false).67 assigned: {},68 // The parent draft state.69 parent,70 // The base state.71 base,72 // The base proxy.Introduced proper state typesMichel Weststratebefore adoption3842f85
line 73why, one step back73 draft: null as any, // set belowMerge branch 'master' into map-fixesMichel Weststratebefore adoptioncb63fb0
lines 74–78why, one step back74 // Any property proxies.75 drafts: {},76 // The base copy with any updated values.77 copy: null,78 // Called by the `produce` function.Processed bunch of todosMichel Weststratebefore adoption00425e1
lines 79–80why, one step back79 revoke: null as any,80 isManual: falseMerge branch 'master' into map-fixesMichel Weststratebefore adoptioncb63fb0
lines 81–90why, one step back81 }8283 // the traps must target something, a bit like the 'real' base.84 // but also, we need to be able to determine from the target what the relevant state is85 // (to avoid creating traps per instance to capture the state in closure,86 // and to avoid creating weird hidden properties as well)87 // So the trick is to use 'state' as the actual 'target'! (and make sure we intercept everything)88 // Note that in the case of an array, we put the state in an array to have better Reflect defaults ootb89 let target: T = state as any90 let traps: ProxyHandler<object | Array<any>> = objectTrapsSeveral refactoringsMichel Weststratebefore adoptionc7f8f5b
line 91why, one step back91 if (isArray) {Merge branch 'master' into map-fixesMichel Weststratebefore adoptioncb63fb0
lines 92–94why, one step back92 target = [state] as any93 traps = arrayTraps94 }basic map tests succeedingMichel Weststratebefore adoption735c402
line 95why, one step back95Merge branch 'master' into map-fixesMichel Weststratebefore adoptioncb63fb0
line 96why, one step back96 const {revoke, proxy} = Proxy.revocable(target, traps)Introduced proper state typesMichel Weststratebefore adoption3842f85
line 97why, one step back97 state.draft = proxy as anyMerge branch 'master' into map-fixesMichel Weststratebefore adoptioncb63fb0
line 98why, one step back98 state.revoke = revokeIntroduced proper state typesMichel Weststratebefore adoption3842f85
line 99why, one step back99 return proxy as anyMerge branch 'master' into map-fixesMichel Weststratebefore adoptioncb63fb0
lines 100–104why, one step back100}101102/**103 * Object drafts104 */TS type improvementsMichel Weststratebefore adoptiondd1808e
line 105why, one step back105const objectTraps: ProxyHandler<ProxyState> = {Merge branch 'master' into map-fixesMichel Weststratebefore adoptioncb63fb0
lines 106–111why, one step back106 get(state, prop) {107 if (prop === DRAFT_STATE) return state108 let {drafts} = state109110 // Check for existing draft in unmodified state.111 if (!state.modified && has(drafts, prop)) {Processed bunch of todosMichel Weststratebefore adoption00425e1
line 112why, one step back112 return drafts![prop as any]Merge branch 'master' into map-fixesMichel Weststratebefore adoptioncb63fb0
lines 113–124why, one step back113 }114115 const value = latest(state)[prop]116 if (state.finalized || !isDraftable(value)) {117 return value118 }119120 // Check for existing draft in modified state.121 if (state.modified) {122 // Assigned values are never drafted. This catches any drafts we created, too.123 if (value !== peek(state.base, prop)) return value124 // Store drafts on the copy (when one exists).Processed bunch of todosMichel Weststratebefore adoption00425e1
line 125why, one step back125 // @ts-ignoreMerge branch 'master' into map-fixesMichel Weststratebefore adoptioncb63fb0
lines 126–128why, one step back126 drafts = state.copy127 }128Processed bunch of todosMichel Weststratebefore adoption00425e1
line 129why, one step back129 return (drafts![prop as any] = state.scope.immer.createProxy(value, state))Merge branch 'master' into map-fixesMichel Weststratebefore adoptioncb63fb0
lines 130–136why, one step back130 },131 has(state, prop) {132 return prop in latest(state)133 },134 ownKeys(state) {135 return Reflect.ownKeys(latest(state))136 },Introduced proper state typesMichel Weststratebefore adoption3842f85
line 137why, one step back137 set(state, prop: string /* strictly not, but helps TS */, value) {Merge branch 'master' into map-fixesMichel Weststratebefore adoptioncb63fb0
lines 138–143why, one step back138 if (!state.modified) {139 const baseValue = peek(state.base, prop)140 // Optimize based on value's truthiness. Truthy values are guaranteed to141 // never be undefined, so we can avoid the `in` operator. Lastly, truthy142 // values may be drafts, but falsy values are never drafts.143 const isUnchanged = valueProcessed bunch of todosMichel Weststratebefore adoption00425e1
line 144why, one step back144 ? is(baseValue, value) || value === state.drafts![prop]Merge branch 'master' into map-fixesMichel Weststratebefore adoptioncb63fb0
lines 145–146why, one step back145 : is(baseValue, value) && prop in state.base146 if (isUnchanged) return truebasic map tests succeedingMichel Weststratebefore adoption735c402
line 147why, one step back147 prepareCopy(state)Merge branch 'master' into map-fixesMichel Weststratebefore adoptioncb63fb0
lines 148–150why, one step back148 markChanged(state)149 }150 state.assigned[prop] = trueTS type improvementsMichel Weststratebefore adoptiondd1808e
line 151why, one step back151 // @ts-ignoreIntroduced proper state typesMichel Weststratebefore adoption3842f85
line 152why, one step back152 state.copy![prop] = valueMerge branch 'master' into map-fixesMichel Weststratebefore adoptioncb63fb0
lines 153–154why, one step back153 return true154 },Introduced proper state typesMichel Weststratebefore adoption3842f85
line 155why, one step back155 deleteProperty(state, prop: string) {Merge branch 'master' into map-fixesMichel Weststratebefore adoptioncb63fb0
lines 156–158why, one step back156 // The `undefined` check is a fast path for pre-existing keys.157 if (peek(state.base, prop) !== undefined || prop in state.base) {158 state.assigned[prop] = falsebasic map tests succeedingMichel Weststratebefore adoption735c402
line 159why, one step back159 prepareCopy(state)Merge branch 'master' into map-fixesMichel Weststratebefore adoptioncb63fb0
lines 160–164why, one step back160 markChanged(state)161 } else if (state.assigned[prop]) {162 // if an originally not assigned property was deleted163 delete state.assigned[prop]164 }TS type improvementsMichel Weststratebefore adoptiondd1808e
line 165why, one step back165 // @ts-ignoreMerge branch 'master' into map-fixesMichel Weststratebefore adoptioncb63fb0
lines 166–175why, one step back166 if (state.copy) delete state.copy[prop]167 return true168 },169 // Note: We never coerce `desc.value` into an Immer draft, because we can't make170 // the same guarantee in ES5 mode.171 getOwnPropertyDescriptor(state, prop) {172 const owner = latest(state)173 const desc = Reflect.getOwnPropertyDescriptor(owner, prop)174 if (desc) {175 desc.writable = trueSeveral refactoringsMichel Weststratebefore adoptionc7f8f5b
line 176why, one step back176 desc.configurable = state.type !== "proxy_array" || prop !== "length"Merge branch 'master' into map-fixesMichel Weststratebefore adoptioncb63fb0
lines 177–194why, one step back177 }178 return desc179 },180 defineProperty() {181 throw new Error("Object.defineProperty() cannot be used on an Immer draft") // prettier-ignore182 },183 getPrototypeOf(state) {184 return Object.getPrototypeOf(state.base)185 },186 setPrototypeOf() {187 throw new Error("Object.setPrototypeOf() cannot be used on an Immer draft") // prettier-ignore188 }189}190191/**192 * Array drafts193 */194Introduced proper state typesMichel Weststratebefore adoption3842f85
line 195why, one step back195const arrayTraps: ProxyHandler<[ProxyArrayState]> = {}Merge branch 'master' into map-fixesMichel Weststratebefore adoptioncb63fb0
line 196why, one step back196each(objectTraps, (key, fn) => {TS type improvementsMichel Weststratebefore adoptiondd1808e
line 197why, one step back197 // @ts-ignoreMerge branch 'master' into map-fixesMichel Weststratebefore adoptioncb63fb0
lines 198–220why, one step back198 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.TS type improvementsMichel Weststratebefore adoptiondd1808e
line 221why, one step back221function peek(draft: Drafted, prop: PropertyKey): any {Merge branch 'master' into map-fixesMichel Weststratebefore adoptioncb63fb0
lines 222–229why, one step back222 const state = draft[DRAFT_STATE]223 const desc = Reflect.getOwnPropertyDescriptor(224 state ? latest(state) : draft,225 prop226 )227 return desc && desc.value228}229TS type improvementsMichel Weststratebefore adoptiondd1808e
line 230why, one step back230export function markChanged(state: ImmerState) {Merge branch 'master' into map-fixesMichel Weststratebefore adoptioncb63fb0
lines 231–232why, one step back231 if (!state.modified) {232 state.modified = trueProcessed bunch of todosMichel Weststratebefore adoption00425e1
lines 233–235why, one step back233 if (state.type === "proxy_object" || state.type === "proxy_array") {234 const copy = (state.copy = shallowCopy(state.base))235 each(state.drafts!, (key, value) => {TS type improvementsMichel Weststratebefore adoptiondd1808e
line 236why, one step back236 // @ts-ignoreDropped Object.assignMichel Weststratebefore adoption79a1d2c
lines 237–238why, one step back237 copy[key] = value238 })Processed bunch of todosMichel Weststratebefore adoption00425e1
line 239why, one step back239 state.drafts = undefinedMerge branch 'master' into map-fixesMichel Weststratebefore adoptioncb63fb0
lines 240–241why, one step back240 }241Processed bunch of todosMichel Weststratebefore adoption00425e1
lines 242–243why, one step back242 if (state.parent) {243 markChanged(state.parent)Merge branch 'master' into map-fixesMichel Weststratebefore adoptioncb63fb0
line 244why, one step back244 }basic map tests succeedingMichel Weststratebefore adoption735c402
lines 245–247why, one step back245 }246}247TS type improvementsMichel Weststratebefore adoptiondd1808e
line 248why, one step back248function prepareCopy(state: ProxyState) {basic map tests succeedingMichel Weststratebefore adoption735c402
lines 249–250why, one step back249 if (!state.copy) {250 state.copy = shallowCopy(state.base)Merge branch 'master' into map-fixesMichel Weststratebefore adoptioncb63fb0
lines 251–252why, one step back251 }252}