proxy.ts
This file
Path
src/proxy.ts
432 lines · 10.6 KiB · TypeScript
Last changed by
added set and iteror stuffMichel Weststratebefore adoption08f4682
History of this fileTake it
Merge branch 'master' into map-fixesMichel Weststratebefore adoptioncb63fb0
lines 1–18why, one step back1"use strict"2import {3 assign,4 each,5 has,6 is,7 isDraftable,8 isDraft,9 isMap,10 isSet,11 hasSymbol,12 shallowCopy,13 makeIterable,14 DRAFT_STATE,15 assignMap,16 assignSet,17 original,18 iterateMapValues,map unification WIPMichel Weststratebefore adoption9bcefb6
lines 19–20why, one step back19 makeIterateSetValues,20 latestMerge branch 'master' into map-fixesMichel Weststratebefore adoptioncb63fb0
lines 21–22why, one step back21} from "./common"22import {ImmerScope} from "./scope"added set and iteror stuffMichel Weststratebefore adoption08f4682
line 23why, one step back23import { proxyMap } from "./map"Merge branch 'master' into map-fixesMichel Weststratebefore adoptioncb63fb0
lines 24–60why, one step back2425// Do nothing before being finalized.26export function willFinalize() {}2728interface ES6Draft {}2930interface ES6State<T = any> {31 scope: ImmerScope32 modified: boolean33 finalized: boolean34 assigned:35 | {36 [property: string]: boolean37 }38 | Map<string, boolean> // TODO: always use a Map?39 parent: ES6State40 base: T41 draft: ES6Draft | null42 drafts:43 | {44 [property: string]: ES6Draft45 }46 | Map<string, ES6Draft> // TODO: always use a Map?47 copy: T | null48 revoke: null | (() => void)49}5051/**52 * Returns a new draft of the `base` object.53 *54 * The second argument is the parent draft-state (used internally).55 */56export function createProxy<T extends object>(57 base: T,58 parent: ES6State59): ES6Draft {60 const scope = parent ? parent.scope : ImmerScope.current!basic map tests succeedingMichel Weststratebefore adoption735c402
lines 61–67why, one step back6162 if (isMap(base)) {63 const draft = proxyMap(base, parent) as any // TODO: typefix64 scope.drafts.push(draft);65 return draft;66 }67Merge branch 'master' into map-fixesMichel Weststratebefore adoptioncb63fb0
lines 68–102why, one step back68 const state: ES6State<T> = {69 // Track which produce call this is associated with.70 scope,71 // True for both shallow and deep changes.72 modified: false,73 // Used during finalization.74 finalized: false,75 // Track which properties have been assigned (true) or deleted (false).76 assigned: {},77 // The parent draft state.78 parent,79 // The base state.80 base,81 // The base proxy.82 draft: null,83 // Any property proxies.84 drafts: {},85 // The base copy with any updated values.86 copy: null,87 // Called by the `produce` function.88 revoke: null89 }9091 // the traps must target something, a bit like the 'real' base.92 // but also, we need to be able to determine from the target what the relevant state is93 // (to avoid creating traps per instance to capture the state in closure,94 // and to avoid creating weird hidden properties as well)95 // So the trick is to use 'state' as the actual 'target'! (and make sure we intercept everything)96 // Note that in the case of an array, we put the state in an array to have better Reflect defaults ootb97 let target: T = state as any98 let traps: ProxyHandler<object | Array<any>> = objectTraps99 if (Array.isArray(base)) {100 target = [state] as any101 traps = arrayTraps102 }basic map tests succeedingMichel Weststratebefore adoption735c402
line 103why, one step back103Merge branch 'master' into map-fixesMichel Weststratebefore adoptioncb63fb0
lines 104–163why, one step back104 // Set drafts use a Map object to track which of its values are drafted.105 // And we don't need the "assigned" property, because Set objects have no keys.106 else if (isSet(base)) {107 traps = setTraps108 state.drafts = new Map()109 }110111 const {revoke, proxy} = Proxy.revocable(target, traps)112113 state.draft = proxy114 state.revoke = revoke115116 scope.drafts!.push(proxy)117 return proxy118}119120/**121 * Object drafts122 */123const objectTraps: ProxyHandler<ES6State> = {124 get(state, prop) {125 if (prop === DRAFT_STATE) return state126 let {drafts} = state127128 // Check for existing draft in unmodified state.129 if (!state.modified && has(drafts, prop)) {130 return drafts[prop]131 }132133 const value = latest(state)[prop]134 if (state.finalized || !isDraftable(value)) {135 return value136 }137138 // Check for existing draft in modified state.139 if (state.modified) {140 // Assigned values are never drafted. This catches any drafts we created, too.141 if (value !== peek(state.base, prop)) return value142 // Store drafts on the copy (when one exists).143 drafts = state.copy144 }145146 return (drafts[prop] = createProxy(value, state))147 },148 has(state, prop) {149 return prop in latest(state)150 },151 ownKeys(state) {152 return Reflect.ownKeys(latest(state))153 },154 set(state, prop, value) {155 if (!state.modified) {156 const baseValue = peek(state.base, prop)157 // Optimize based on value's truthiness. Truthy values are guaranteed to158 // never be undefined, so we can avoid the `in` operator. Lastly, truthy159 // values may be drafts, but falsy values are never drafts.160 const isUnchanged = value161 ? is(baseValue, value) || value === state.drafts[prop]162 : is(baseValue, value) && prop in state.base163 if (isUnchanged) return truebasic map tests succeedingMichel Weststratebefore adoption735c402
line 164why, one step back164 prepareCopy(state)Merge branch 'master' into map-fixesMichel Weststratebefore adoptioncb63fb0
lines 165–174why, one step back165 markChanged(state)166 }167 state.assigned[prop] = true168 state.copy[prop] = value169 return true170 },171 deleteProperty(state, prop) {172 // The `undefined` check is a fast path for pre-existing keys.173 if (peek(state.base, prop) !== undefined || prop in state.base) {174 state.assigned[prop] = falsebasic map tests succeedingMichel Weststratebefore adoption735c402
line 175why, one step back175 prepareCopy(state)Merge branch 'master' into map-fixesMichel Weststratebefore adoptioncb63fb0
lines 176–318why, one step back176 markChanged(state)177 } else if (state.assigned[prop]) {178 // if an originally not assigned property was deleted179 delete state.assigned[prop]180 }181 if (state.copy) delete state.copy[prop]182 return true183 },184 // Note: We never coerce `desc.value` into an Immer draft, because we can't make185 // the same guarantee in ES5 mode.186 getOwnPropertyDescriptor(state, prop) {187 const owner = latest(state)188 const desc = Reflect.getOwnPropertyDescriptor(owner, prop)189 if (desc) {190 desc.writable = true191 desc.configurable = !Array.isArray(owner) || prop !== "length"192 }193 return desc194 },195 defineProperty() {196 throw new Error("Object.defineProperty() cannot be used on an Immer draft") // prettier-ignore197 },198 getPrototypeOf(state) {199 return Object.getPrototypeOf(state.base)200 },201 setPrototypeOf() {202 throw new Error("Object.setPrototypeOf() cannot be used on an Immer draft") // prettier-ignore203 }204}205206/**207 * Array drafts208 */209210const arrayTraps: ProxyHandler<[ES6State]> = {}211each(objectTraps, (key, fn) => {212 arrayTraps[key] = function() {213 arguments[0] = arguments[0][0]214 return fn.apply(this, arguments)215 }216})217arrayTraps.deleteProperty = function(state, prop) {218 if (isNaN(parseInt(prop as any))) {219 throw new Error("Immer only supports deleting array indices") // prettier-ignore220 }221 return objectTraps.deleteProperty!.call(this, state[0], prop)222}223arrayTraps.set = function(state, prop, value) {224 if (prop !== "length" && isNaN(parseInt(prop as any))) {225 throw new Error("Immer only supports setting array indices and the 'length' property") // prettier-ignore226 }227 return objectTraps.set!.call(this, state[0], prop, value, state[0])228}229230// Used by Map and Set drafts231const reflectTraps = makeReflectTraps([232 "ownKeys",233 "has",234 "set",235 "deleteProperty",236 "defineProperty",237 "getOwnPropertyDescriptor",238 "preventExtensions",239 "isExtensible",240 "getPrototypeOf"241])242243/**244 * Map drafts245 */246247const mapTraps = makeTrapsForGetters<Map<any, any>>({248 [DRAFT_STATE]: state => state,249 size: state => latest(state).size,250 has: state => key => latest(state).has(key),251 set: state => (key, value) => {252 const values = latest(state)253 if (!values.has(key) || values.get(key) !== value) {254 markChanged(state)255 // @ts-ignore256 state.assigned.set(key, true)257 state.copy!.set(key, value)258 }259 return state.draft260 },261 delete: state => key => {262 if (latest(state).has(key)) {263 markChanged(state)264 // @ts-ignore265 state.assigned.set(key, false)266 return state.copy!.delete(key)267 }268 return false269 },270 clear: state => () => {271 markChanged(state)272 state.assigned = new Map()273 each(latest(state).keys(), (_, key) => {274 // @ts-ignore275 state.assigned.set(key, false)276 })277 return state.copy!.clear()278 },279 // @ts-ignore280 forEach: (state, _, receiver) => (cb, thisArg) =>281 latest(state).forEach((_, key, map) => {282 const value = receiver.get(key)283 cb.call(thisArg, value, key, map)284 }),285 get: state => key => {286 const drafts = state.modified ? state.copy : state.drafts287288 // @ts-ignore TODO: ...or fix by using different ES6Draft types (but better just unify to maps)289 if (drafts!.has(key)) {290 // @ts-ignore291 const value = drafts.get(key)292293 if (isDraft(value) || !isDraftable(value)) return value294295 const draft = createProxy(value, state)296 // @ts-ignore297 drafts.set(key, draft)298 return draft299 }300301 const value = latest(state).get(key)302 if (state.finalized || !isDraftable(value)) {303 return value304 }305306 const draft = createProxy(value, state)307 //@ts-ignore308 drafts.set(key, draft)309 return draft310 },311 keys: state => () => latest(state).keys(),312 //@ts-ignore313 values: iterateMapValues,314 //@ts-ignore315 entries: iterateMapValues,316 [hasSymbol ? Symbol.iterator : "@@iterator"]: iterateMapValues317})318map unification WIPMichel Weststratebefore adoption9bcefb6
line 319why, one step back319const iterateSetValues = makeIterateSetValues()Merge branch 'master' into map-fixesMichel Weststratebefore adoptioncb63fb0
lines 320–375why, one step back320/**321 * Set drafts322 */323324const setTraps = makeTrapsForGetters<Set<any>>({325 //@ts-ignore326 [DRAFT_STATE]: state => state,327 size: state => latest(state).size,328 has: state => key => latest(state).has(key),329 add: state => value => {330 if (!latest(state).has(value)) {331 markChanged(state)332 //@ts-ignore333 state.copy.add(value)334 }335 return state.draft336 },337 delete: state => value => {338 markChanged(state)339 //@ts-ignore340 return state.copy.delete(value)341 },342 clear: state => () => {343 markChanged(state)344 //@ts-ignore345 return state.copy.clear()346 },347 forEach: state => (cb, thisArg) => {348 const iterator = iterateSetValues(state)()349 let result = iterator.next()350 while (!result.done) {351 cb.call(thisArg, result.value, result.value, state.draft)352 result = iterator.next()353 }354 },355 keys: iterateSetValues,356 values: iterateSetValues,357 entries: iterateSetValues,358 [hasSymbol ? Symbol.iterator : "@@iterator"]: iterateSetValues359})360361/**362 * Helpers363 */364365366// Access a property without creating an Immer draft.367function peek(draft, prop) {368 const state = draft[DRAFT_STATE]369 const desc = Reflect.getOwnPropertyDescriptor(370 state ? latest(state) : draft,371 prop372 )373 return desc && desc.value374}375basic map tests succeedingMichel Weststratebefore adoption735c402
lines 376–377why, one step back376// TODO: unify with ES5 version, by getting rid of the drafts vs copy distinction?377export function markChanged(state) {Merge branch 'master' into map-fixesMichel Weststratebefore adoptioncb63fb0
lines 378–380why, one step back378 if (!state.modified) {379 state.modified = true380 const {base, drafts, parent} = statebasic map tests succeedingMichel Weststratebefore adoption735c402
lines 381–384why, one step back381 if (!isMap(base) && !isSet(base)) {382 // TODO: drop creating copies here?383 const copy = state.copy = shallowCopy(base)384 assign(copy, drafts)Merge branch 'master' into map-fixesMichel Weststratebefore adoptioncb63fb0
lines 385–390why, one step back385 state.drafts = null386 }387388 if (parent) {389 markChanged(parent)390 }basic map tests succeedingMichel Weststratebefore adoption735c402
lines 391–397why, one step back391 }392}393394// TODO: unify with ES5 version395function prepareCopy(state) {396 if (!state.copy) {397 state.copy = shallowCopy(state.base)Merge branch 'master' into map-fixesMichel Weststratebefore adoptioncb63fb0
lines 398–432why, one step back398 }399}400401/** Create traps that all use the `Reflect` API on the `latest(state)` */402function makeReflectTraps<T extends object>(403 names: (keyof typeof Reflect)[]404): ProxyHandler<T> {405 return names.reduce(406 (traps, name) => {407 // @ts-ignore408 traps[name] = (state, ...args) => Reflect[name](latest(state), ...args)409 return traps410 },411 {} as any412 )413}414415function makeTrapsForGetters<T extends object>(416 getters: {417 [K in keyof T]: (418 state: ES6State<T>419 ) => /* Skip first arg of: ProxyHandler<T>[K] */ any420 }421): ProxyHandler<T> {422 return assign({}, reflectTraps, {423 get(state, prop, receiver) {424 return getters.hasOwnProperty(prop)425 ? getters[prop](state, prop, receiver)426 : Reflect.get(state, prop, receiver)427 },428 setPrototypeOf(state) {429 throw new Error("Object.setPrototypeOf() cannot be used on an Immer draft") // prettier-ignore430 }431 })432}