Skip to content
Myr

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 file

Take it

Merge branch 'master' into map-fixesMichel Weststratebefore adoptioncb63fb0

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

Merge branch 'master' into map-fixesMichel Weststratebefore adoptioncb63fb0

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

Introduced proper state typesMichel Weststratebefore adoption3842f85

line 14why, one step back
14import {AnyObject, Drafted, ImmerState, AnyArray} from "./types"

Merge branch 'master' into map-fixesMichel Weststratebefore adoptioncb63fb0

line 15why, one step back
15

Introduced proper state typesMichel Weststratebefore adoption3842f85

line 16why, one step back
16interface ProxyBaseState {

Merge branch 'master' into map-fixesMichel Weststratebefore adoptioncb63fb0

lines 17–19why, one step back
17 scope: ImmerScope
18 modified: boolean19 finalized: boolean

Introduced proper state typesMichel Weststratebefore adoption3842f85

lines 20–22why, one step back
20 assigned: {
21 [property: string]: boolean22 }

clean up create proxyMichel Weststratebefore adoptionc182c1e

line 23why, one step back
23 parent?: ImmerState

Introduced proper state typesMichel Weststratebefore adoption3842f85

lines 24–26why, one step back
24 drafts: {
25 [property: string]: Drafted<any, any>26 }

Merge branch 'master' into map-fixesMichel Weststratebefore adoptioncb63fb0

lines 27–29why, one step back
27 revoke: null | (() => void)
28}29

Introduced proper state typesMichel Weststratebefore adoption3842f85

lines 30–43why, one step back
30export 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}43

Merge branch 'master' into map-fixesMichel Weststratebefore adoptioncb63fb0

lines 44–50why, one step back
44/**
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 back
51 parent?: ImmerState

Introduced proper state typesMichel Weststratebefore adoption3842f85

lines 52–55why, one step back
52): 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 back
56 // Track which produce call this is associated with.

clean up create proxyMichel Weststratebefore adoptionc182c1e

line 57why, one step back
57 scope: parent ? parent.scope : ImmerScope.current!,

Merge branch 'master' into map-fixesMichel Weststratebefore adoptioncb63fb0

lines 58–68why, one step back
58 // 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 back
69 draft: null as any, // set below

Merge branch 'master' into map-fixesMichel Weststratebefore adoptioncb63fb0

lines 70–89why, one step back
70 // 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 back
90

Merge branch 'master' into map-fixesMichel Weststratebefore adoptioncb63fb0

line 91why, one step back
91 const {revoke, proxy} = Proxy.revocable(target, traps)

Introduced proper state typesMichel Weststratebefore adoption3842f85

line 92why, one step back
92 state.draft = proxy as any

Merge branch 'master' into map-fixesMichel Weststratebefore adoptioncb63fb0

line 93why, one step back
93 state.revoke = revoke

Introduced proper state typesMichel Weststratebefore adoption3842f85

line 94why, one step back
94 return proxy as any

Merge branch 'master' into map-fixesMichel Weststratebefore adoptioncb63fb0

lines 95–99why, one step back
95}
9697/**98 * Object drafts99 */

Introduced proper state typesMichel Weststratebefore adoption3842f85

line 100why, one step back
100const objectTraps: ProxyHandler<ProxyObjectState | ProxyArrayState> = {

Merge branch 'master' into map-fixesMichel Weststratebefore adoptioncb63fb0

lines 101–106why, one step back
101 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 back
107 return drafts[prop as any]

Merge branch 'master' into map-fixesMichel Weststratebefore adoptioncb63fb0

lines 108–119why, one step back
108 }
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 back
120 // @ts-ignore TODO: this line seems of?

Merge branch 'master' into map-fixesMichel Weststratebefore adoptioncb63fb0

lines 121–123why, one step back
121 drafts = state.copy
122 }123

clean up create proxyMichel Weststratebefore adoptionc182c1e

line 124why, one step back
124 return (drafts[prop as any] = state.scope.immer.createProxy(value, state))

Merge branch 'master' into map-fixesMichel Weststratebefore adoptioncb63fb0

lines 125–131why, one step back
125 },
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 back
132 set(state, prop: string /* strictly not, but helps TS */, value) {

Merge branch 'master' into map-fixesMichel Weststratebefore adoptioncb63fb0

lines 133–141why, one step back
133 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 true

basic map tests succeedingMichel Weststratebefore adoption735c402

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

Merge branch 'master' into map-fixesMichel Weststratebefore adoptioncb63fb0

lines 143–145why, one step back
143 markChanged(state)
144 }145 state.assigned[prop] = true

Introduced proper state typesMichel Weststratebefore adoption3842f85

line 146why, one step back
146 state.copy![prop] = value

Merge branch 'master' into map-fixesMichel Weststratebefore adoptioncb63fb0

lines 147–148why, one step back
147 return true
148 },

Introduced proper state typesMichel Weststratebefore adoption3842f85

line 149why, one step back
149 deleteProperty(state, prop: string) {

Merge branch 'master' into map-fixesMichel Weststratebefore adoptioncb63fb0

lines 150–152why, one step back
150 // 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] = false

basic map tests succeedingMichel Weststratebefore adoption735c402

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

Merge branch 'master' into map-fixesMichel Weststratebefore adoptioncb63fb0

lines 154–187why, one step back
154 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 */187

Introduced proper state typesMichel Weststratebefore adoption3842f85

line 188why, one step back
188const arrayTraps: ProxyHandler<[ProxyArrayState]> = {}

Merge branch 'master' into map-fixesMichel Weststratebefore adoptioncb63fb0

lines 189–221why, one step back
189each(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}221

basic map tests succeedingMichel Weststratebefore adoption735c402

lines 222–223why, one step back
222// 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 back
224 if (!state.modified) {
225 state.modified = true226 const {base, drafts, parent} = state

basic map tests succeedingMichel Weststratebefore adoption735c402

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

some build fixesMichel Weststratebefore adoption65a377f

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

Dropped Object.assignMichel Weststratebefore adoption79a1d2c

lines 230–232why, one step back
230 each(drafts, (key, value) => {
231 copy[key] = value232 })

Merge branch 'master' into map-fixesMichel Weststratebefore adoptioncb63fb0

lines 233–238why, one step back
233 state.drafts = null
234 }235236 if (parent) {237 markChanged(parent)238 }

basic map tests succeedingMichel Weststratebefore adoption735c402

lines 239–244why, one step back
239 }
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 back
245 }
246}