Skip to content
Myr

proxy.ts

This file

Path

src/proxy.ts

297 lines · 7.4 KiB · TypeScript

Last changed by

Some initial cleanupMichel Weststratebefore adoptionc53a75f

History of this file

Take it

Merge branch 'master' into map-fixesMichel Weststratebefore adoptioncb63fb0

lines 1–16why, one step back
1"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 back
17 latest

Merge branch 'master' into map-fixesMichel Weststratebefore adoptioncb63fb0

lines 18–19why, one step back
18} from "./common"
19import {ImmerScope} from "./scope"

some build fixesMichel Weststratebefore adoption65a377f

lines 20–21why, one step back
20import {proxyMap} from "./map"
21import {proxySet} from "./set"

Merge branch 'master' into map-fixesMichel Weststratebefore adoptioncb63fb0

lines 22–57why, one step back
22
23// Do nothing before being finalized.24export function willFinalize() {}2526interface ES6Draft {}2728interface ES6State<T = any> {29 scope: ImmerScope30 modified: boolean31 finalized: boolean32 assigned:33 | {34 [property: string]: boolean35 }36 | Map<string, boolean> // TODO: always use a Map?37 parent: ES6State38 base: T39 draft: ES6Draft | null40 drafts:41 | {42 [property: string]: ES6Draft43 }44 | Map<string, ES6Draft> // TODO: always use a Map?45 copy: T | null46 revoke: null | (() => void)47}4849/**50 * Returns a new draft of the `base` object.51 *52 * The second argument is the parent draft-state (used internally).53 */54export function createProxy<T extends object>(55 base: T,56 parent: ES6State57): ES6Draft {

fixed most testsMichel Weststratebefore adoption385c0a4

lines 58–63why, one step back
58 // TODO: dedupe
59 if (!base || typeof base !== "object" || !isDraftable(base)) {60 // TODO: || isDraft ?61 return base as any // TODO: fix62 }63

Merge branch 'master' into map-fixesMichel Weststratebefore adoptioncb63fb0

line 64why, one step back
64 const scope = parent ? parent.scope : ImmerScope.current!

basic map tests succeedingMichel Weststratebefore adoption735c402

line 65why, one step back
65

fixed most testsMichel Weststratebefore adoption385c0a4

line 66why, one step back
66 // TODO: dedupe this, it is the same for ES5

basic map tests succeedingMichel Weststratebefore adoption735c402

lines 67–68why, one step back
67 if (isMap(base)) {
68 const draft = proxyMap(base, parent) as any // TODO: typefix

some build fixesMichel Weststratebefore adoption65a377f

lines 69–70why, one step back
69 scope.drafts.push(draft)
70 return draft

basic map tests succeedingMichel Weststratebefore adoption735c402

line 71why, one step back
71 }

fixed most testsMichel Weststratebefore adoption385c0a4

lines 72–73why, one step back
72 if (isSet(base)) {
73 const draft = proxySet(base, parent) as any // TODO: typefix

some build fixesMichel Weststratebefore adoption65a377f

lines 74–75why, one step back
74 scope.drafts.push(draft)
75 return draft

fixed most testsMichel Weststratebefore adoption385c0a4

line 76why, one step back
76 }

basic map tests succeedingMichel Weststratebefore adoption735c402

line 77why, one step back
77

Merge branch 'master' into map-fixesMichel Weststratebefore adoptioncb63fb0

lines 78–112why, one step back
78 const state: ES6State<T> = {
79 // Track which produce call this is associated with.80 scope,81 // True for both shallow and deep changes.82 modified: false,83 // Used during finalization.84 finalized: false,85 // Track which properties have been assigned (true) or deleted (false).86 assigned: {},87 // The parent draft state.88 parent,89 // The base state.90 base,91 // The base proxy.92 draft: null,93 // Any property proxies.94 drafts: {},95 // The base copy with any updated values.96 copy: null,97 // Called by the `produce` function.98 revoke: null99 }100101 // the traps must target something, a bit like the 'real' base.102 // but also, we need to be able to determine from the target what the relevant state is103 // (to avoid creating traps per instance to capture the state in closure,104 // and to avoid creating weird hidden properties as well)105 // So the trick is to use 'state' as the actual 'target'! (and make sure we intercept everything)106 // Note that in the case of an array, we put the state in an array to have better Reflect defaults ootb107 let target: T = state as any108 let traps: ProxyHandler<object | Array<any>> = objectTraps109 if (Array.isArray(base)) {110 target = [state] as any111 traps = arrayTraps112 }

basic map tests succeedingMichel Weststratebefore adoption735c402

line 113why, one step back
113

Merge branch 'master' into map-fixesMichel Weststratebefore adoptioncb63fb0

lines 114–166why, one step back
114 const {revoke, proxy} = Proxy.revocable(target, traps)
115116 state.draft = proxy117 state.revoke = revoke118119 scope.drafts!.push(proxy)120 return proxy121}122123/**124 * Object drafts125 */126const objectTraps: ProxyHandler<ES6State> = {127 get(state, prop) {128 if (prop === DRAFT_STATE) return state129 let {drafts} = state130131 // Check for existing draft in unmodified state.132 if (!state.modified && has(drafts, prop)) {133 return drafts[prop]134 }135136 const value = latest(state)[prop]137 if (state.finalized || !isDraftable(value)) {138 return value139 }140141 // Check for existing draft in modified state.142 if (state.modified) {143 // Assigned values are never drafted. This catches any drafts we created, too.144 if (value !== peek(state.base, prop)) return value145 // Store drafts on the copy (when one exists).146 drafts = state.copy147 }148149 return (drafts[prop] = createProxy(value, state))150 },151 has(state, prop) {152 return prop in latest(state)153 },154 ownKeys(state) {155 return Reflect.ownKeys(latest(state))156 },157 set(state, prop, value) {158 if (!state.modified) {159 const baseValue = peek(state.base, prop)160 // Optimize based on value's truthiness. Truthy values are guaranteed to161 // never be undefined, so we can avoid the `in` operator. Lastly, truthy162 // values may be drafts, but falsy values are never drafts.163 const isUnchanged = value164 ? is(baseValue, value) || value === state.drafts[prop]165 : is(baseValue, value) && prop in state.base166 if (isUnchanged) return true

basic map tests succeedingMichel Weststratebefore adoption735c402

line 167why, one step back
167 prepareCopy(state)

Merge branch 'master' into map-fixesMichel Weststratebefore adoptioncb63fb0

lines 168–177why, one step back
168 markChanged(state)
169 }170 state.assigned[prop] = true171 state.copy[prop] = value172 return true173 },174 deleteProperty(state, prop) {175 // The `undefined` check is a fast path for pre-existing keys.176 if (peek(state.base, prop) !== undefined || prop in state.base) {177 state.assigned[prop] = false

basic map tests succeedingMichel Weststratebefore adoption735c402

line 178why, one step back
178 prepareCopy(state)

Merge branch 'master' into map-fixesMichel Weststratebefore adoptioncb63fb0

lines 179–259why, one step back
179 markChanged(state)
180 } else if (state.assigned[prop]) {181 // if an originally not assigned property was deleted182 delete state.assigned[prop]183 }184 if (state.copy) delete state.copy[prop]185 return true186 },187 // Note: We never coerce `desc.value` into an Immer draft, because we can't make188 // the same guarantee in ES5 mode.189 getOwnPropertyDescriptor(state, prop) {190 const owner = latest(state)191 const desc = Reflect.getOwnPropertyDescriptor(owner, prop)192 if (desc) {193 desc.writable = true194 desc.configurable = !Array.isArray(owner) || prop !== "length"195 }196 return desc197 },198 defineProperty() {199 throw new Error("Object.defineProperty() cannot be used on an Immer draft") // prettier-ignore200 },201 getPrototypeOf(state) {202 return Object.getPrototypeOf(state.base)203 },204 setPrototypeOf() {205 throw new Error("Object.setPrototypeOf() cannot be used on an Immer draft") // prettier-ignore206 }207}208209/**210 * Array drafts211 */212213const arrayTraps: ProxyHandler<[ES6State]> = {}214each(objectTraps, (key, fn) => {215 arrayTraps[key] = function() {216 arguments[0] = arguments[0][0]217 return fn.apply(this, arguments)218 }219})220arrayTraps.deleteProperty = function(state, prop) {221 if (isNaN(parseInt(prop as any))) {222 throw new Error("Immer only supports deleting array indices") // prettier-ignore223 }224 return objectTraps.deleteProperty!.call(this, state[0], prop)225}226arrayTraps.set = function(state, prop, value) {227 if (prop !== "length" && isNaN(parseInt(prop as any))) {228 throw new Error("Immer only supports setting array indices and the 'length' property") // prettier-ignore229 }230 return objectTraps.set!.call(this, state[0], prop, value, state[0])231}232233// Used by Map and Set drafts234const reflectTraps = makeReflectTraps([235 "ownKeys",236 "has",237 "set",238 "deleteProperty",239 "defineProperty",240 "getOwnPropertyDescriptor",241 "preventExtensions",242 "isExtensible",243 "getPrototypeOf"244])245246/**247 * Map drafts248 */249250// Access a property without creating an Immer draft.251function peek(draft, prop) {252 const state = draft[DRAFT_STATE]253 const desc = Reflect.getOwnPropertyDescriptor(254 state ? latest(state) : draft,255 prop256 )257 return desc && desc.value258}259

basic map tests succeedingMichel Weststratebefore adoption735c402

lines 260–261why, one step back
260// TODO: unify with ES5 version, by getting rid of the drafts vs copy distinction?
261export function markChanged(state) {

Merge branch 'master' into map-fixesMichel Weststratebefore adoptioncb63fb0

lines 262–264why, one step back
262 if (!state.modified) {
263 state.modified = true264 const {base, drafts, parent} = state

basic map tests succeedingMichel Weststratebefore adoption735c402

lines 265–266why, one step back
265 if (!isMap(base) && !isSet(base)) {
266 // TODO: drop creating copies here?

some build fixesMichel Weststratebefore adoption65a377f

line 267why, one step back
267 const copy = (state.copy = shallowCopy(base))

basic map tests succeedingMichel Weststratebefore adoption735c402

line 268why, one step back
268 assign(copy, drafts)

Merge branch 'master' into map-fixesMichel Weststratebefore adoptioncb63fb0

lines 269–274why, one step back
269 state.drafts = null
270 }271272 if (parent) {273 markChanged(parent)274 }

basic map tests succeedingMichel Weststratebefore adoption735c402

lines 275–281why, one step back
275 }
276}277278// TODO: unify with ES5 version279function prepareCopy(state) {280 if (!state.copy) {281 state.copy = shallowCopy(state.base)

Merge branch 'master' into map-fixesMichel Weststratebefore adoptioncb63fb0

lines 282–297why, one step back
282 }
283}284285/** Create traps that all use the `Reflect` API on the `latest(state)` */286function makeReflectTraps<T extends object>(287 names: (keyof typeof Reflect)[]288): ProxyHandler<T> {289 return names.reduce(290 (traps, name) => {291 // @ts-ignore292 traps[name] = (state, ...args) => Reflect[name](latest(state), ...args)293 return traps294 },295 {} as any296 )297}