proxy.ts
This file
Path
src/proxy.ts
254 lines · 6.7 KiB · TypeScript
Last changed by
Processed bunch of todosMichel Weststratebefore adoption00425e1
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"Processed bunch of todosMichel Weststratebefore adoption00425e1
lines 14–21why, one step back14import {15 AnyObject,16 Drafted,17 ImmerState,18 AnyArray,19 Objectish,20 ImmerBaseState21} from "./types"Merge branch 'master' into map-fixesMichel Weststratebefore adoptioncb63fb0
line 22why, one step back22Processed bunch of todosMichel Weststratebefore adoption00425e1
line 23why, one step back23interface ProxyBaseState extends ImmerBaseState {Introduced proper state typesMichel Weststratebefore adoption3842f85
lines 24–26why, one step back24 assigned: {25 [property: string]: boolean26 }clean up create proxyMichel Weststratebefore adoptionc182c1e
line 27why, one step back27 parent?: ImmerStateProcessed bunch of todosMichel Weststratebefore adoption00425e1
line 28why, one step back28 drafts?: {Introduced proper state typesMichel Weststratebefore adoption3842f85
lines 29–30why, one step back29 [property: string]: Drafted<any, any>30 }Processed bunch of todosMichel Weststratebefore adoption00425e1
line 31why, one step back31 revoke(): voidMerge branch 'master' into map-fixesMichel Weststratebefore adoptioncb63fb0
lines 32–33why, one step back32}33Introduced proper state typesMichel Weststratebefore adoption3842f85
lines 34–47why, one step back34export interface ProxyObjectState extends ProxyBaseState {35 type: "proxy_object"36 base: AnyObject37 copy: AnyObject | null38 draft: Drafted<AnyObject, ProxyObjectState>39}4041export interface ProxyArrayState extends ProxyBaseState {42 type: "proxy_array"43 base: AnyArray44 copy: AnyArray | null45 draft: Drafted<AnyArray, ProxyArrayState>46}47TS type improvementsMichel Weststratebefore adoptiondd1808e
lines 48–49why, one step back48type ProxyState = ProxyObjectState | ProxyArrayState49Merge branch 'master' into map-fixesMichel Weststratebefore adoptioncb63fb0
lines 50–54why, one step back50/**51 * Returns a new draft of the `base` object.52 *53 * The second argument is the parent draft-state (used internally).54 */TS type improvementsMichel Weststratebefore adoptiondd1808e
line 55why, one step back55export function createProxy<T extends Objectish>(Merge branch 'master' into map-fixesMichel Weststratebefore adoptioncb63fb0
line 56why, one step back56 base: T,clean up create proxyMichel Weststratebefore adoptionc182c1e
line 57why, one step back57 parent?: ImmerStateTS type improvementsMichel Weststratebefore adoptiondd1808e
line 58why, one step back58): Drafted<T, ProxyState> {Introduced proper state typesMichel Weststratebefore adoption3842f85
line 59why, one step back59 const isArray = Array.isArray(base)TS type improvementsMichel Weststratebefore adoptiondd1808e
line 60why, one step back60 const state: ProxyState = {Introduced proper state typesMichel Weststratebefore adoption3842f85
line 61why, one step back61 type: isArray ? "proxy_array" : ("proxy_object" as any),Merge branch 'master' into map-fixesMichel Weststratebefore adoptioncb63fb0
line 62why, one step back62 // Track which produce call this is associated with.clean up create proxyMichel Weststratebefore adoptionc182c1e
line 63why, one step back63 scope: parent ? parent.scope : ImmerScope.current!,Merge branch 'master' into map-fixesMichel Weststratebefore adoptioncb63fb0
lines 64–74why, one step back64 // 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,72 // The base state.73 base,74 // The base proxy.Introduced proper state typesMichel Weststratebefore adoption3842f85
line 75why, one step back75 draft: null as any, // set belowMerge branch 'master' into map-fixesMichel Weststratebefore adoptioncb63fb0
lines 76–80why, one step back76 // Any property proxies.77 drafts: {},78 // The base copy with any updated values.79 copy: null,80 // Called by the `produce` function.Processed bunch of todosMichel Weststratebefore adoption00425e1
lines 81–82why, one step back81 revoke: null as any,82 isManual: falseMerge branch 'master' into map-fixesMichel Weststratebefore adoptioncb63fb0
lines 83–96why, one step back83 }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 (Array.isArray(base)) {94 target = [state] as any95 traps = arrayTraps96 }basic map tests succeedingMichel Weststratebefore adoption735c402
line 97why, one step back97Merge branch 'master' into map-fixesMichel Weststratebefore adoptioncb63fb0
line 98why, one step back98 const {revoke, proxy} = Proxy.revocable(target, traps)Introduced proper state typesMichel Weststratebefore adoption3842f85
line 99why, one step back99 state.draft = proxy as anyMerge branch 'master' into map-fixesMichel Weststratebefore adoptioncb63fb0
line 100why, one step back100 state.revoke = revokeIntroduced proper state typesMichel Weststratebefore adoption3842f85
line 101why, one step back101 return proxy as anyMerge branch 'master' into map-fixesMichel Weststratebefore adoptioncb63fb0
lines 102–106why, one step back102}103104/**105 * Object drafts106 */TS type improvementsMichel Weststratebefore adoptiondd1808e
line 107why, one step back107const objectTraps: ProxyHandler<ProxyState> = {Merge branch 'master' into map-fixesMichel Weststratebefore adoptioncb63fb0
lines 108–113why, one step back108 get(state, prop) {109 if (prop === DRAFT_STATE) return state110 let {drafts} = state111112 // Check for existing draft in unmodified state.113 if (!state.modified && has(drafts, prop)) {Processed bunch of todosMichel Weststratebefore adoption00425e1
line 114why, one step back114 return drafts![prop as any]Merge branch 'master' into map-fixesMichel Weststratebefore adoptioncb63fb0
lines 115–126why, one step back115 }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).Processed bunch of todosMichel Weststratebefore adoption00425e1
line 127why, one step back127 // @ts-ignoreMerge branch 'master' into map-fixesMichel Weststratebefore adoptioncb63fb0
lines 128–130why, one step back128 drafts = state.copy129 }130Processed bunch of todosMichel Weststratebefore adoption00425e1
line 131why, one step back131 return (drafts![prop as any] = state.scope.immer.createProxy(value, state))Merge branch 'master' into map-fixesMichel Weststratebefore adoptioncb63fb0
lines 132–138why, one step back132 },133 has(state, prop) {134 return prop in latest(state)135 },136 ownKeys(state) {137 return Reflect.ownKeys(latest(state))138 },Introduced proper state typesMichel Weststratebefore adoption3842f85
line 139why, one step back139 set(state, prop: string /* strictly not, but helps TS */, value) {Merge branch 'master' into map-fixesMichel Weststratebefore adoptioncb63fb0
lines 140–145why, one step back140 if (!state.modified) {141 const baseValue = peek(state.base, prop)142 // Optimize based on value's truthiness. Truthy values are guaranteed to143 // never be undefined, so we can avoid the `in` operator. Lastly, truthy144 // values may be drafts, but falsy values are never drafts.145 const isUnchanged = valueProcessed bunch of todosMichel Weststratebefore adoption00425e1
line 146why, one step back146 ? is(baseValue, value) || value === state.drafts![prop]Merge branch 'master' into map-fixesMichel Weststratebefore adoptioncb63fb0
lines 147–148why, one step back147 : is(baseValue, value) && prop in state.base148 if (isUnchanged) return truebasic map tests succeedingMichel Weststratebefore adoption735c402
line 149why, one step back149 prepareCopy(state)Merge branch 'master' into map-fixesMichel Weststratebefore adoptioncb63fb0
lines 150–152why, one step back150 markChanged(state)151 }152 state.assigned[prop] = trueTS type improvementsMichel Weststratebefore adoptiondd1808e
line 153why, one step back153 // @ts-ignoreIntroduced 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–166why, 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 }TS type improvementsMichel Weststratebefore adoptiondd1808e
line 167why, one step back167 // @ts-ignoreMerge branch 'master' into map-fixesMichel Weststratebefore adoptioncb63fb0
lines 168–196why, one step back168 if (state.copy) delete state.copy[prop]169 return true170 },171 // Note: We never coerce `desc.value` into an Immer draft, because we can't make172 // the same guarantee in ES5 mode.173 getOwnPropertyDescriptor(state, prop) {174 const owner = latest(state)175 const desc = Reflect.getOwnPropertyDescriptor(owner, prop)176 if (desc) {177 desc.writable = true178 desc.configurable = !Array.isArray(owner) || prop !== "length"179 }180 return desc181 },182 defineProperty() {183 throw new Error("Object.defineProperty() cannot be used on an Immer draft") // prettier-ignore184 },185 getPrototypeOf(state) {186 return Object.getPrototypeOf(state.base)187 },188 setPrototypeOf() {189 throw new Error("Object.setPrototypeOf() cannot be used on an Immer draft") // prettier-ignore190 }191}192193/**194 * Array drafts195 */196Introduced proper state typesMichel Weststratebefore adoption3842f85
line 197why, one step back197const arrayTraps: ProxyHandler<[ProxyArrayState]> = {}Merge branch 'master' into map-fixesMichel Weststratebefore adoptioncb63fb0
line 198why, one step back198each(objectTraps, (key, fn) => {TS type improvementsMichel Weststratebefore adoptiondd1808e
line 199why, one step back199 // @ts-ignoreMerge branch 'master' into map-fixesMichel Weststratebefore adoptioncb63fb0
lines 200–222why, one step back200 arrayTraps[key] = function() {201 arguments[0] = arguments[0][0]202 return fn.apply(this, arguments)203 }204})205arrayTraps.deleteProperty = function(state, prop) {206 if (isNaN(parseInt(prop as any))) {207 throw new Error("Immer only supports deleting array indices") // prettier-ignore208 }209 return objectTraps.deleteProperty!.call(this, state[0], prop)210}211arrayTraps.set = function(state, prop, value) {212 if (prop !== "length" && isNaN(parseInt(prop as any))) {213 throw new Error("Immer only supports setting array indices and the 'length' property") // prettier-ignore214 }215 return objectTraps.set!.call(this, state[0], prop, value, state[0])216}217218/**219 * Map drafts220 */221222// Access a property without creating an Immer draft.TS type improvementsMichel Weststratebefore adoptiondd1808e
line 223why, one step back223function peek(draft: Drafted, prop: PropertyKey): any {Merge branch 'master' into map-fixesMichel Weststratebefore adoptioncb63fb0
lines 224–231why, one step back224 const state = draft[DRAFT_STATE]225 const desc = Reflect.getOwnPropertyDescriptor(226 state ? latest(state) : draft,227 prop228 )229 return desc && desc.value230}231TS type improvementsMichel Weststratebefore adoptiondd1808e
line 232why, one step back232export function markChanged(state: ImmerState) {Merge branch 'master' into map-fixesMichel Weststratebefore adoptioncb63fb0
lines 233–234why, one step back233 if (!state.modified) {234 state.modified = trueProcessed bunch of todosMichel Weststratebefore adoption00425e1
lines 235–237why, one step back235 if (state.type === "proxy_object" || state.type === "proxy_array") {236 const copy = (state.copy = shallowCopy(state.base))237 each(state.drafts!, (key, value) => {TS type improvementsMichel Weststratebefore adoptiondd1808e
line 238why, one step back238 // @ts-ignoreDropped Object.assignMichel Weststratebefore adoption79a1d2c
lines 239–240why, one step back239 copy[key] = value240 })Processed bunch of todosMichel Weststratebefore adoption00425e1
line 241why, one step back241 state.drafts = undefinedMerge branch 'master' into map-fixesMichel Weststratebefore adoptioncb63fb0
lines 242–243why, one step back242 }243Processed bunch of todosMichel Weststratebefore adoption00425e1
lines 244–245why, one step back244 if (state.parent) {245 markChanged(state.parent)Merge branch 'master' into map-fixesMichel Weststratebefore adoptioncb63fb0
line 246why, one step back246 }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}