proxy.ts
This file
Path
src/proxy.ts
246 lines · 6.7 KiB · TypeScript
Last changed by
Further cleanup in progressMichel Weststratebefore adoptionaeba1ff
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"Introduced proper state typesMichel Weststratebefore adoption3842f85
line 14why, one step back14import {AnyObject, Drafted, ImmerState, AnyArray} 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}43Merge branch 'master' into map-fixesMichel Weststratebefore adoptioncb63fb0
lines 44–50why, one step back44/**45 * Returns a new draft of the `base` object.46 *47 * The second argument is the parent draft-state (used internally).48 */49export function createProxy<T extends object>(50 base: T,clean up create proxyMichel Weststratebefore adoptionc182c1e
line 51why, one step back51 parent?: ImmerStateIntroduced proper state typesMichel Weststratebefore adoption3842f85
lines 52–55why, one step back52): Drafted<T, ProxyObjectState | ProxyArrayState> {53 const isArray = Array.isArray(base)54 const state: ProxyObjectState | ProxyArrayState = {55 type: isArray ? "proxy_array" : ("proxy_object" as any),Merge branch 'master' into map-fixesMichel Weststratebefore adoptioncb63fb0
line 56why, one step back56 // Track which produce call this is associated with.clean up create proxyMichel Weststratebefore adoptionc182c1e
line 57why, one step back57 scope: parent ? parent.scope : ImmerScope.current!,Merge branch 'master' into map-fixesMichel Weststratebefore adoptioncb63fb0
lines 58–68why, one step back58 // True for both shallow and deep changes.59 modified: false,60 // Used during finalization.61 finalized: false,62 // Track which properties have been assigned (true) or deleted (false).63 assigned: {},64 // The parent draft state.65 parent,66 // The base state.67 base,68 // The base proxy.Introduced proper state typesMichel Weststratebefore adoption3842f85
line 69why, one step back69 draft: null as any, // set belowMerge branch 'master' into map-fixesMichel Weststratebefore adoptioncb63fb0
lines 70–89why, one step back70 // Any property proxies.71 drafts: {},72 // The base copy with any updated values.73 copy: null,74 // Called by the `produce` function.75 revoke: null76 }7778 // the traps must target something, a bit like the 'real' base.79 // but also, we need to be able to determine from the target what the relevant state is80 // (to avoid creating traps per instance to capture the state in closure,81 // and to avoid creating weird hidden properties as well)82 // So the trick is to use 'state' as the actual 'target'! (and make sure we intercept everything)83 // Note that in the case of an array, we put the state in an array to have better Reflect defaults ootb84 let target: T = state as any85 let traps: ProxyHandler<object | Array<any>> = objectTraps86 if (Array.isArray(base)) {87 target = [state] as any88 traps = arrayTraps89 }basic map tests succeedingMichel Weststratebefore adoption735c402
line 90why, one step back90Merge branch 'master' into map-fixesMichel Weststratebefore adoptioncb63fb0
line 91why, one step back91 const {revoke, proxy} = Proxy.revocable(target, traps)Introduced proper state typesMichel Weststratebefore adoption3842f85
line 92why, one step back92 state.draft = proxy as anyMerge branch 'master' into map-fixesMichel Weststratebefore adoptioncb63fb0
line 93why, one step back93 state.revoke = revokeIntroduced proper state typesMichel Weststratebefore adoption3842f85
line 94why, one step back94 return proxy as anyMerge branch 'master' into map-fixesMichel Weststratebefore adoptioncb63fb0
lines 95–99why, one step back95}9697/**98 * Object drafts99 */Introduced proper state typesMichel Weststratebefore adoption3842f85
line 100why, one step back100const objectTraps: ProxyHandler<ProxyObjectState | ProxyArrayState> = {Merge branch 'master' into map-fixesMichel Weststratebefore adoptioncb63fb0
lines 101–106why, one step back101 get(state, prop) {102 if (prop === DRAFT_STATE) return state103 let {drafts} = state104105 // Check for existing draft in unmodified state.106 if (!state.modified && has(drafts, prop)) {Introduced proper state typesMichel Weststratebefore adoption3842f85
line 107why, one step back107 return drafts[prop as any]Merge branch 'master' into map-fixesMichel Weststratebefore adoptioncb63fb0
lines 108–119why, one step back108 }109110 const value = latest(state)[prop]111 if (state.finalized || !isDraftable(value)) {112 return value113 }114115 // Check for existing draft in modified state.116 if (state.modified) {117 // Assigned values are never drafted. This catches any drafts we created, too.118 if (value !== peek(state.base, prop)) return value119 // Store drafts on the copy (when one exists).Introduced proper state typesMichel Weststratebefore adoption3842f85
line 120why, one step back120 // @ts-ignore TODO: this line seems of?Merge branch 'master' into map-fixesMichel Weststratebefore adoptioncb63fb0
lines 121–123why, one step back121 drafts = state.copy122 }123clean up create proxyMichel Weststratebefore adoptionc182c1e
line 124why, one step back124 return (drafts[prop as any] = state.scope.immer.createProxy(value, state))Merge branch 'master' into map-fixesMichel Weststratebefore adoptioncb63fb0
lines 125–131why, one step back125 },126 has(state, prop) {127 return prop in latest(state)128 },129 ownKeys(state) {130 return Reflect.ownKeys(latest(state))131 },Introduced proper state typesMichel Weststratebefore adoption3842f85
line 132why, one step back132 set(state, prop: string /* strictly not, but helps TS */, value) {Merge branch 'master' into map-fixesMichel Weststratebefore adoptioncb63fb0
lines 133–141why, one step back133 if (!state.modified) {134 const baseValue = peek(state.base, prop)135 // Optimize based on value's truthiness. Truthy values are guaranteed to136 // never be undefined, so we can avoid the `in` operator. Lastly, truthy137 // values may be drafts, but falsy values are never drafts.138 const isUnchanged = value139 ? is(baseValue, value) || value === state.drafts[prop]140 : is(baseValue, value) && prop in state.base141 if (isUnchanged) return truebasic map tests succeedingMichel Weststratebefore adoption735c402
line 142why, one step back142 prepareCopy(state)Merge branch 'master' into map-fixesMichel Weststratebefore adoptioncb63fb0
lines 143–145why, one step back143 markChanged(state)144 }145 state.assigned[prop] = trueIntroduced proper state typesMichel Weststratebefore adoption3842f85
line 146why, one step back146 state.copy![prop] = valueMerge branch 'master' into map-fixesMichel Weststratebefore adoptioncb63fb0
lines 147–148why, one step back147 return true148 },Introduced proper state typesMichel Weststratebefore adoption3842f85
line 149why, one step back149 deleteProperty(state, prop: string) {Merge branch 'master' into map-fixesMichel Weststratebefore adoptioncb63fb0
lines 150–152why, one step back150 // The `undefined` check is a fast path for pre-existing keys.151 if (peek(state.base, prop) !== undefined || prop in state.base) {152 state.assigned[prop] = falsebasic map tests succeedingMichel Weststratebefore adoption735c402
line 153why, one step back153 prepareCopy(state)Merge branch 'master' into map-fixesMichel Weststratebefore adoptioncb63fb0
lines 154–187why, one step back154 markChanged(state)155 } else if (state.assigned[prop]) {156 // if an originally not assigned property was deleted157 delete state.assigned[prop]158 }159 if (state.copy) delete state.copy[prop]160 return true161 },162 // Note: We never coerce `desc.value` into an Immer draft, because we can't make163 // the same guarantee in ES5 mode.164 getOwnPropertyDescriptor(state, prop) {165 const owner = latest(state)166 const desc = Reflect.getOwnPropertyDescriptor(owner, prop)167 if (desc) {168 desc.writable = true169 desc.configurable = !Array.isArray(owner) || prop !== "length"170 }171 return desc172 },173 defineProperty() {174 throw new Error("Object.defineProperty() cannot be used on an Immer draft") // prettier-ignore175 },176 getPrototypeOf(state) {177 return Object.getPrototypeOf(state.base)178 },179 setPrototypeOf() {180 throw new Error("Object.setPrototypeOf() cannot be used on an Immer draft") // prettier-ignore181 }182}183184/**185 * Array drafts186 */187Introduced proper state typesMichel Weststratebefore adoption3842f85
line 188why, one step back188const arrayTraps: ProxyHandler<[ProxyArrayState]> = {}Merge branch 'master' into map-fixesMichel Weststratebefore adoptioncb63fb0
lines 189–221why, one step back189each(objectTraps, (key, fn) => {190 arrayTraps[key] = function() {191 arguments[0] = arguments[0][0]192 return fn.apply(this, arguments)193 }194})195arrayTraps.deleteProperty = function(state, prop) {196 if (isNaN(parseInt(prop as any))) {197 throw new Error("Immer only supports deleting array indices") // prettier-ignore198 }199 return objectTraps.deleteProperty!.call(this, state[0], prop)200}201arrayTraps.set = function(state, prop, value) {202 if (prop !== "length" && isNaN(parseInt(prop as any))) {203 throw new Error("Immer only supports setting array indices and the 'length' property") // prettier-ignore204 }205 return objectTraps.set!.call(this, state[0], prop, value, state[0])206}207208/**209 * Map drafts210 */211212// Access a property without creating an Immer draft.213function peek(draft, prop) {214 const state = draft[DRAFT_STATE]215 const desc = Reflect.getOwnPropertyDescriptor(216 state ? latest(state) : draft,217 prop218 )219 return desc && desc.value220}221basic map tests succeedingMichel Weststratebefore adoption735c402
lines 222–223why, one step back222// TODO: unify with ES5 version, by getting rid of the drafts vs copy distinction?223export function markChanged(state) {Merge branch 'master' into map-fixesMichel Weststratebefore adoptioncb63fb0
lines 224–226why, one step back224 if (!state.modified) {225 state.modified = true226 const {base, drafts, parent} = statebasic map tests succeedingMichel Weststratebefore adoption735c402
lines 227–228why, one step back227 if (!isMap(base) && !isSet(base)) {228 // TODO: drop creating copies here?some build fixesMichel Weststratebefore adoption65a377f
line 229why, one step back229 const copy = (state.copy = shallowCopy(base))Dropped Object.assignMichel Weststratebefore adoption79a1d2c
lines 230–232why, one step back230 each(drafts, (key, value) => {231 copy[key] = value232 })Merge branch 'master' into map-fixesMichel Weststratebefore adoptioncb63fb0
lines 233–238why, one step back233 state.drafts = null234 }235236 if (parent) {237 markChanged(parent)238 }basic map tests succeedingMichel Weststratebefore adoption735c402
lines 239–244why, one step back239 }240}241242function prepareCopy(state) {243 if (!state.copy) {244 state.copy = shallowCopy(state.base)Merge branch 'master' into map-fixesMichel Weststratebefore adoptioncb63fb0
lines 245–246why, one step back245 }246}