proxy.ts
This file
Path
src/proxy.ts
254 lines · 6.8 KiB · TypeScript
Last changed by
TS type improvementsMichel Weststratebefore adoptiondd1808e
History of this fileTake it
Merge branch 'master' into map-fixesMichel Weststratebefore adoptioncb63fb0
lines 1–10why, one step back1"use strict"2import {3 each,4 has,5 is,6 isDraftable,7 isMap,8 isSet,9 shallowCopy,10 DRAFT_STATE,map unification WIPMichel Weststratebefore adoption9bcefb6
line 11why, one step back11 latestMerge branch 'master' into map-fixesMichel Weststratebefore adoptioncb63fb0
lines 12–13why, one step back12} from "./common"13import {ImmerScope} from "./scope"TS type improvementsMichel Weststratebefore adoptiondd1808e
line 14why, one step back14import {AnyObject, Drafted, ImmerState, AnyArray, Objectish} from "./types"Merge branch 'master' into map-fixesMichel Weststratebefore adoptioncb63fb0
line 15why, one step back15Introduced proper state typesMichel Weststratebefore adoption3842f85
line 16why, one step back16interface ProxyBaseState {Merge branch 'master' into map-fixesMichel Weststratebefore adoptioncb63fb0
lines 17–19why, one step back17 scope: ImmerScope18 modified: boolean19 finalized: booleanIntroduced proper state typesMichel Weststratebefore adoption3842f85
lines 20–22why, one step back20 assigned: {21 [property: string]: boolean22 }clean up create proxyMichel Weststratebefore adoptionc182c1e
line 23why, one step back23 parent?: ImmerStateIntroduced proper state typesMichel Weststratebefore adoption3842f85
lines 24–26why, one step back24 drafts: {25 [property: string]: Drafted<any, any>26 }Merge branch 'master' into map-fixesMichel Weststratebefore adoptioncb63fb0
lines 27–29why, one step back27 revoke: null | (() => void)28}29Introduced proper state typesMichel Weststratebefore adoption3842f85
lines 30–43why, one step back30export interface ProxyObjectState extends ProxyBaseState {31 type: "proxy_object"32 base: AnyObject33 copy: AnyObject | null34 draft: Drafted<AnyObject, ProxyObjectState>35}3637export interface ProxyArrayState extends ProxyBaseState {38 type: "proxy_array"39 base: AnyArray40 copy: AnyArray | null41 draft: Drafted<AnyArray, ProxyArrayState>42}43TS type improvementsMichel Weststratebefore adoptiondd1808e
lines 44–45why, one step back44type ProxyState = ProxyObjectState | ProxyArrayState45Merge branch 'master' into map-fixesMichel Weststratebefore adoptioncb63fb0
lines 46–50why, one step back46/**47 * Returns a new draft of the `base` object.48 *49 * The second argument is the parent draft-state (used internally).50 */TS type improvementsMichel Weststratebefore adoptiondd1808e
line 51why, one step back51export function createProxy<T extends Objectish>(Merge branch 'master' into map-fixesMichel Weststratebefore adoptioncb63fb0
line 52why, one step back52 base: T,clean up create proxyMichel Weststratebefore adoptionc182c1e
line 53why, one step back53 parent?: ImmerStateTS type improvementsMichel Weststratebefore adoptiondd1808e
line 54why, one step back54): Drafted<T, ProxyState> {Introduced proper state typesMichel Weststratebefore adoption3842f85
line 55why, one step back55 const isArray = Array.isArray(base)TS type improvementsMichel Weststratebefore adoptiondd1808e
line 56why, one step back56 const state: ProxyState = {Introduced proper state typesMichel Weststratebefore adoption3842f85
line 57why, one step back57 type: isArray ? "proxy_array" : ("proxy_object" as any),Merge branch 'master' into map-fixesMichel Weststratebefore adoptioncb63fb0
line 58why, one step back58 // Track which produce call this is associated with.clean up create proxyMichel Weststratebefore adoptionc182c1e
line 59why, one step back59 scope: parent ? parent.scope : ImmerScope.current!,Merge branch 'master' into map-fixesMichel Weststratebefore adoptioncb63fb0
lines 60–70why, one step back60 // True for both shallow and deep changes.61 modified: false,62 // Used during finalization.63 finalized: false,64 // Track which properties have been assigned (true) or deleted (false).65 assigned: {},66 // The parent draft state.67 parent,68 // The base state.69 base,70 // The base proxy.Introduced proper state typesMichel Weststratebefore adoption3842f85
line 71why, one step back71 draft: null as any, // set belowMerge branch 'master' into map-fixesMichel Weststratebefore adoptioncb63fb0
lines 72–91why, one step back72 // Any property proxies.73 drafts: {},74 // The base copy with any updated values.75 copy: null,76 // Called by the `produce` function.77 revoke: null78 }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 (Array.isArray(base)) {89 target = [state] as any90 traps = arrayTraps91 }basic map tests succeedingMichel Weststratebefore adoption735c402
line 92why, one step back92Merge branch 'master' into map-fixesMichel Weststratebefore adoptioncb63fb0
line 93why, one step back93 const {revoke, proxy} = Proxy.revocable(target, traps)Introduced proper state typesMichel Weststratebefore adoption3842f85
line 94why, one step back94 state.draft = proxy as anyMerge branch 'master' into map-fixesMichel Weststratebefore adoptioncb63fb0
line 95why, one step back95 state.revoke = revokeIntroduced proper state typesMichel Weststratebefore adoption3842f85
line 96why, one step back96 return proxy as anyMerge branch 'master' into map-fixesMichel Weststratebefore adoptioncb63fb0
lines 97–101why, one step back97}9899/**100 * Object drafts101 */TS type improvementsMichel Weststratebefore adoptiondd1808e
line 102why, one step back102const objectTraps: ProxyHandler<ProxyState> = {Merge branch 'master' into map-fixesMichel Weststratebefore adoptioncb63fb0
lines 103–108why, one step back103 get(state, prop) {104 if (prop === DRAFT_STATE) return state105 let {drafts} = state106107 // Check for existing draft in unmodified state.108 if (!state.modified && has(drafts, prop)) {Introduced proper state typesMichel Weststratebefore adoption3842f85
line 109why, one step back109 return drafts[prop as any]Merge branch 'master' into map-fixesMichel Weststratebefore adoptioncb63fb0
lines 110–121why, one step back110 }111112 const value = latest(state)[prop]113 if (state.finalized || !isDraftable(value)) {114 return value115 }116117 // Check for existing draft in modified state.118 if (state.modified) {119 // Assigned values are never drafted. This catches any drafts we created, too.120 if (value !== peek(state.base, prop)) return value121 // Store drafts on the copy (when one exists).Introduced proper state typesMichel Weststratebefore adoption3842f85
line 122why, one step back122 // @ts-ignore TODO: this line seems of?Merge branch 'master' into map-fixesMichel Weststratebefore adoptioncb63fb0
lines 123–125why, one step back123 drafts = state.copy124 }125clean up create proxyMichel Weststratebefore adoptionc182c1e
line 126why, one step back126 return (drafts[prop as any] = state.scope.immer.createProxy(value, state))Merge branch 'master' into map-fixesMichel Weststratebefore adoptioncb63fb0
lines 127–133why, one step back127 },128 has(state, prop) {129 return prop in latest(state)130 },131 ownKeys(state) {132 return Reflect.ownKeys(latest(state))133 },Introduced proper state typesMichel Weststratebefore adoption3842f85
line 134why, one step back134 set(state, prop: string /* strictly not, but helps TS */, value) {Merge branch 'master' into map-fixesMichel Weststratebefore adoptioncb63fb0
lines 135–143why, one step back135 if (!state.modified) {136 const baseValue = peek(state.base, prop)137 // Optimize based on value's truthiness. Truthy values are guaranteed to138 // never be undefined, so we can avoid the `in` operator. Lastly, truthy139 // values may be drafts, but falsy values are never drafts.140 const isUnchanged = value141 ? is(baseValue, value) || value === state.drafts[prop]142 : is(baseValue, value) && prop in state.base143 if (isUnchanged) return truebasic map tests succeedingMichel Weststratebefore adoption735c402
line 144why, one step back144 prepareCopy(state)Merge branch 'master' into map-fixesMichel Weststratebefore adoptioncb63fb0
lines 145–147why, one step back145 markChanged(state)146 }147 state.assigned[prop] = trueTS type improvementsMichel Weststratebefore adoptiondd1808e
line 148why, one step back148 // @ts-ignoreIntroduced proper state typesMichel Weststratebefore adoption3842f85
line 149why, one step back149 state.copy![prop] = valueMerge branch 'master' into map-fixesMichel Weststratebefore adoptioncb63fb0
lines 150–151why, one step back150 return true151 },Introduced proper state typesMichel Weststratebefore adoption3842f85
line 152why, one step back152 deleteProperty(state, prop: string) {Merge branch 'master' into map-fixesMichel Weststratebefore adoptioncb63fb0
lines 153–155why, one step back153 // The `undefined` check is a fast path for pre-existing keys.154 if (peek(state.base, prop) !== undefined || prop in state.base) {155 state.assigned[prop] = falsebasic map tests succeedingMichel Weststratebefore adoption735c402
line 156why, one step back156 prepareCopy(state)Merge branch 'master' into map-fixesMichel Weststratebefore adoptioncb63fb0
lines 157–161why, one step back157 markChanged(state)158 } else if (state.assigned[prop]) {159 // if an originally not assigned property was deleted160 delete state.assigned[prop]161 }TS type improvementsMichel Weststratebefore adoptiondd1808e
line 162why, one step back162 // @ts-ignoreMerge branch 'master' into map-fixesMichel Weststratebefore adoptioncb63fb0
lines 163–191why, one step back163 if (state.copy) delete state.copy[prop]164 return true165 },166 // Note: We never coerce `desc.value` into an Immer draft, because we can't make167 // the same guarantee in ES5 mode.168 getOwnPropertyDescriptor(state, prop) {169 const owner = latest(state)170 const desc = Reflect.getOwnPropertyDescriptor(owner, prop)171 if (desc) {172 desc.writable = true173 desc.configurable = !Array.isArray(owner) || prop !== "length"174 }175 return desc176 },177 defineProperty() {178 throw new Error("Object.defineProperty() cannot be used on an Immer draft") // prettier-ignore179 },180 getPrototypeOf(state) {181 return Object.getPrototypeOf(state.base)182 },183 setPrototypeOf() {184 throw new Error("Object.setPrototypeOf() cannot be used on an Immer draft") // prettier-ignore185 }186}187188/**189 * Array drafts190 */191Introduced proper state typesMichel Weststratebefore adoption3842f85
line 192why, one step back192const arrayTraps: ProxyHandler<[ProxyArrayState]> = {}Merge branch 'master' into map-fixesMichel Weststratebefore adoptioncb63fb0
line 193why, one step back193each(objectTraps, (key, fn) => {TS type improvementsMichel Weststratebefore adoptiondd1808e
line 194why, one step back194 // @ts-ignoreMerge branch 'master' into map-fixesMichel Weststratebefore adoptioncb63fb0
lines 195–217why, one step back195 arrayTraps[key] = function() {196 arguments[0] = arguments[0][0]197 return fn.apply(this, arguments)198 }199})200arrayTraps.deleteProperty = function(state, prop) {201 if (isNaN(parseInt(prop as any))) {202 throw new Error("Immer only supports deleting array indices") // prettier-ignore203 }204 return objectTraps.deleteProperty!.call(this, state[0], prop)205}206arrayTraps.set = function(state, prop, value) {207 if (prop !== "length" && isNaN(parseInt(prop as any))) {208 throw new Error("Immer only supports setting array indices and the 'length' property") // prettier-ignore209 }210 return objectTraps.set!.call(this, state[0], prop, value, state[0])211}212213/**214 * Map drafts215 */216217// Access a property without creating an Immer draft.TS type improvementsMichel Weststratebefore adoptiondd1808e
line 218why, one step back218function peek(draft: Drafted, prop: PropertyKey): any {Merge branch 'master' into map-fixesMichel Weststratebefore adoptioncb63fb0
lines 219–226why, one step back219 const state = draft[DRAFT_STATE]220 const desc = Reflect.getOwnPropertyDescriptor(221 state ? latest(state) : draft,222 prop223 )224 return desc && desc.value225}226TS type improvementsMichel Weststratebefore adoptiondd1808e
line 227why, one step back227export function markChanged(state: ImmerState) {Merge branch 'master' into map-fixesMichel Weststratebefore adoptioncb63fb0
lines 228–229why, one step back228 if (!state.modified) {229 state.modified = trueTS type improvementsMichel Weststratebefore adoptiondd1808e
line 230why, one step back230 // @ts-ignore TODOMerge branch 'master' into map-fixesMichel Weststratebefore adoptioncb63fb0
line 231why, one step back231 const {base, drafts, parent} = stateTS type improvementsMichel Weststratebefore adoptiondd1808e
line 232why, one step back232 // TODO: get rid of isMap and isSetbasic map tests succeedingMichel Weststratebefore adoption735c402
lines 233–234why, one step back233 if (!isMap(base) && !isSet(base)) {234 // TODO: drop creating copies here?some build fixesMichel Weststratebefore adoption65a377f
line 235why, one step back235 const copy = (state.copy = shallowCopy(base))Dropped Object.assignMichel Weststratebefore adoption79a1d2c
line 236why, one step back236 each(drafts, (key, value) => {TS type improvementsMichel Weststratebefore adoptiondd1808e
line 237why, one step back237 // @ts-ignoreDropped Object.assignMichel Weststratebefore adoption79a1d2c
lines 238–239why, one step back238 copy[key] = value239 })TS type improvementsMichel Weststratebefore adoptiondd1808e
line 240why, one step back240 // @ts-ignore TODOMerge branch 'master' into map-fixesMichel Weststratebefore adoptioncb63fb0
lines 241–246why, one step back241 state.drafts = null242 }243244 if (parent) {245 markChanged(parent)246 }basic map tests succeedingMichel Weststratebefore adoption735c402
lines 247–249why, one step back247 }248}249TS type improvementsMichel Weststratebefore adoptiondd1808e
line 250why, one step back250function prepareCopy(state: ProxyState) {basic map tests succeedingMichel Weststratebefore adoption735c402
lines 251–252why, one step back251 if (!state.copy) {252 state.copy = shallowCopy(state.base)Merge branch 'master' into map-fixesMichel Weststratebefore adoptioncb63fb0
lines 253–254why, one step back253 }254}