proxy.ts
This file
Path
src/proxy.ts
390 lines · 9.7 KiB · TypeScript
Last changed by
fixed most testsMichel Weststratebefore adoption385c0a4
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
line 19why, one step back19 latestMerge branch 'master' into map-fixesMichel Weststratebefore adoptioncb63fb0
lines 20–21why, one step back20} from "./common"21import {ImmerScope} from "./scope"added set and iteror stuffMichel Weststratebefore adoption08f4682
line 22why, one step back22import { proxyMap } from "./map"fixed most testsMichel Weststratebefore adoption385c0a4
line 23why, one step back23import { proxySet } from "./set"Merge branch 'master' into map-fixesMichel Weststratebefore adoptioncb63fb0
lines 24–59why, 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 {fixed most testsMichel Weststratebefore adoption385c0a4
lines 60–65why, one step back60 // TODO: dedupe61 if (!base || typeof base !== "object" || !isDraftable(base)) {62 // TODO: || isDraft ?63 return base as any // TODO: fix64 }65Merge branch 'master' into map-fixesMichel Weststratebefore adoptioncb63fb0
line 66why, one step back66 const scope = parent ? parent.scope : ImmerScope.current!basic map tests succeedingMichel Weststratebefore adoption735c402
line 67why, one step back67fixed most testsMichel Weststratebefore adoption385c0a4
line 68why, one step back68 // TODO: dedupe this, it is the same for ES5basic map tests succeedingMichel Weststratebefore adoption735c402
lines 69–73why, one step back69 if (isMap(base)) {70 const draft = proxyMap(base, parent) as any // TODO: typefix71 scope.drafts.push(draft);72 return draft;73 }fixed most testsMichel Weststratebefore adoption385c0a4
lines 74–78why, one step back74 if (isSet(base)) {75 const draft = proxySet(base, parent) as any // TODO: typefix76 scope.drafts.push(draft);77 return draft;78 }basic map tests succeedingMichel Weststratebefore adoption735c402
line 79why, one step back79Merge branch 'master' into map-fixesMichel Weststratebefore adoptioncb63fb0
lines 80–114why, one step back80 const state: ES6State<T> = {81 // Track which produce call this is associated with.82 scope,83 // True for both shallow and deep changes.84 modified: false,85 // Used during finalization.86 finalized: false,87 // Track which properties have been assigned (true) or deleted (false).88 assigned: {},89 // The parent draft state.90 parent,91 // The base state.92 base,93 // The base proxy.94 draft: null,95 // Any property proxies.96 drafts: {},97 // The base copy with any updated values.98 copy: null,99 // Called by the `produce` function.100 revoke: null101 }102103 // the traps must target something, a bit like the 'real' base.104 // but also, we need to be able to determine from the target what the relevant state is105 // (to avoid creating traps per instance to capture the state in closure,106 // and to avoid creating weird hidden properties as well)107 // So the trick is to use 'state' as the actual 'target'! (and make sure we intercept everything)108 // Note that in the case of an array, we put the state in an array to have better Reflect defaults ootb109 let target: T = state as any110 let traps: ProxyHandler<object | Array<any>> = objectTraps111 if (Array.isArray(base)) {112 target = [state] as any113 traps = arrayTraps114 }basic map tests succeedingMichel Weststratebefore adoption735c402
line 115why, one step back115Merge branch 'master' into map-fixesMichel Weststratebefore adoptioncb63fb0
lines 116–168why, one step back116 const {revoke, proxy} = Proxy.revocable(target, traps)117118 state.draft = proxy119 state.revoke = revoke120121 scope.drafts!.push(proxy)122 return proxy123}124125/**126 * Object drafts127 */128const objectTraps: ProxyHandler<ES6State> = {129 get(state, prop) {130 if (prop === DRAFT_STATE) return state131 let {drafts} = state132133 // Check for existing draft in unmodified state.134 if (!state.modified && has(drafts, prop)) {135 return drafts[prop]136 }137138 const value = latest(state)[prop]139 if (state.finalized || !isDraftable(value)) {140 return value141 }142143 // Check for existing draft in modified state.144 if (state.modified) {145 // Assigned values are never drafted. This catches any drafts we created, too.146 if (value !== peek(state.base, prop)) return value147 // Store drafts on the copy (when one exists).148 drafts = state.copy149 }150151 return (drafts[prop] = createProxy(value, state))152 },153 has(state, prop) {154 return prop in latest(state)155 },156 ownKeys(state) {157 return Reflect.ownKeys(latest(state))158 },159 set(state, prop, value) {160 if (!state.modified) {161 const baseValue = peek(state.base, prop)162 // Optimize based on value's truthiness. Truthy values are guaranteed to163 // never be undefined, so we can avoid the `in` operator. Lastly, truthy164 // values may be drafts, but falsy values are never drafts.165 const isUnchanged = value166 ? is(baseValue, value) || value === state.drafts[prop]167 : is(baseValue, value) && prop in state.base168 if (isUnchanged) return truebasic map tests succeedingMichel Weststratebefore adoption735c402
line 169why, one step back169 prepareCopy(state)Merge branch 'master' into map-fixesMichel Weststratebefore adoptioncb63fb0
lines 170–179why, one step back170 markChanged(state)171 }172 state.assigned[prop] = true173 state.copy[prop] = value174 return true175 },176 deleteProperty(state, prop) {177 // The `undefined` check is a fast path for pre-existing keys.178 if (peek(state.base, prop) !== undefined || prop in state.base) {179 state.assigned[prop] = falsebasic map tests succeedingMichel Weststratebefore adoption735c402
line 180why, one step back180 prepareCopy(state)Merge branch 'master' into map-fixesMichel Weststratebefore adoptioncb63fb0
lines 181–333why, one step back181 markChanged(state)182 } else if (state.assigned[prop]) {183 // if an originally not assigned property was deleted184 delete state.assigned[prop]185 }186 if (state.copy) delete state.copy[prop]187 return true188 },189 // Note: We never coerce `desc.value` into an Immer draft, because we can't make190 // the same guarantee in ES5 mode.191 getOwnPropertyDescriptor(state, prop) {192 const owner = latest(state)193 const desc = Reflect.getOwnPropertyDescriptor(owner, prop)194 if (desc) {195 desc.writable = true196 desc.configurable = !Array.isArray(owner) || prop !== "length"197 }198 return desc199 },200 defineProperty() {201 throw new Error("Object.defineProperty() cannot be used on an Immer draft") // prettier-ignore202 },203 getPrototypeOf(state) {204 return Object.getPrototypeOf(state.base)205 },206 setPrototypeOf() {207 throw new Error("Object.setPrototypeOf() cannot be used on an Immer draft") // prettier-ignore208 }209}210211/**212 * Array drafts213 */214215const arrayTraps: ProxyHandler<[ES6State]> = {}216each(objectTraps, (key, fn) => {217 arrayTraps[key] = function() {218 arguments[0] = arguments[0][0]219 return fn.apply(this, arguments)220 }221})222arrayTraps.deleteProperty = function(state, prop) {223 if (isNaN(parseInt(prop as any))) {224 throw new Error("Immer only supports deleting array indices") // prettier-ignore225 }226 return objectTraps.deleteProperty!.call(this, state[0], prop)227}228arrayTraps.set = function(state, prop, value) {229 if (prop !== "length" && isNaN(parseInt(prop as any))) {230 throw new Error("Immer only supports setting array indices and the 'length' property") // prettier-ignore231 }232 return objectTraps.set!.call(this, state[0], prop, value, state[0])233}234235// Used by Map and Set drafts236const reflectTraps = makeReflectTraps([237 "ownKeys",238 "has",239 "set",240 "deleteProperty",241 "defineProperty",242 "getOwnPropertyDescriptor",243 "preventExtensions",244 "isExtensible",245 "getPrototypeOf"246])247248/**249 * Map drafts250 */251252const mapTraps = makeTrapsForGetters<Map<any, any>>({253 [DRAFT_STATE]: state => state,254 size: state => latest(state).size,255 has: state => key => latest(state).has(key),256 set: state => (key, value) => {257 const values = latest(state)258 if (!values.has(key) || values.get(key) !== value) {259 markChanged(state)260 // @ts-ignore261 state.assigned.set(key, true)262 state.copy!.set(key, value)263 }264 return state.draft265 },266 delete: state => key => {267 if (latest(state).has(key)) {268 markChanged(state)269 // @ts-ignore270 state.assigned.set(key, false)271 return state.copy!.delete(key)272 }273 return false274 },275 clear: state => () => {276 markChanged(state)277 state.assigned = new Map()278 each(latest(state).keys(), (_, key) => {279 // @ts-ignore280 state.assigned.set(key, false)281 })282 return state.copy!.clear()283 },284 // @ts-ignore285 forEach: (state, _, receiver) => (cb, thisArg) =>286 latest(state).forEach((_, key, map) => {287 const value = receiver.get(key)288 cb.call(thisArg, value, key, map)289 }),290 get: state => key => {291 const drafts = state.modified ? state.copy : state.drafts292293 // @ts-ignore TODO: ...or fix by using different ES6Draft types (but better just unify to maps)294 if (drafts!.has(key)) {295 // @ts-ignore296 const value = drafts.get(key)297298 if (isDraft(value) || !isDraftable(value)) return value299300 const draft = createProxy(value, state)301 // @ts-ignore302 drafts.set(key, draft)303 return draft304 }305306 const value = latest(state).get(key)307 if (state.finalized || !isDraftable(value)) {308 return value309 }310311 const draft = createProxy(value, state)312 //@ts-ignore313 drafts.set(key, draft)314 return draft315 },316 keys: state => () => latest(state).keys(),317 //@ts-ignore318 values: iterateMapValues,319 //@ts-ignore320 entries: iterateMapValues,321 [hasSymbol ? Symbol.iterator : "@@iterator"]: iterateMapValues322})323324// Access a property without creating an Immer draft.325function peek(draft, prop) {326 const state = draft[DRAFT_STATE]327 const desc = Reflect.getOwnPropertyDescriptor(328 state ? latest(state) : draft,329 prop330 )331 return desc && desc.value332}333basic map tests succeedingMichel Weststratebefore adoption735c402
lines 334–335why, one step back334// TODO: unify with ES5 version, by getting rid of the drafts vs copy distinction?335export function markChanged(state) {Merge branch 'master' into map-fixesMichel Weststratebefore adoptioncb63fb0
lines 336–338why, one step back336 if (!state.modified) {337 state.modified = true338 const {base, drafts, parent} = statebasic map tests succeedingMichel Weststratebefore adoption735c402
lines 339–342why, one step back339 if (!isMap(base) && !isSet(base)) {340 // TODO: drop creating copies here?341 const copy = state.copy = shallowCopy(base)342 assign(copy, drafts)Merge branch 'master' into map-fixesMichel Weststratebefore adoptioncb63fb0
lines 343–348why, one step back343 state.drafts = null344 }345346 if (parent) {347 markChanged(parent)348 }basic map tests succeedingMichel Weststratebefore adoption735c402
lines 349–355why, one step back349 }350}351352// TODO: unify with ES5 version353function prepareCopy(state) {354 if (!state.copy) {355 state.copy = shallowCopy(state.base)Merge branch 'master' into map-fixesMichel Weststratebefore adoptioncb63fb0
lines 356–390why, one step back356 }357}358359/** Create traps that all use the `Reflect` API on the `latest(state)` */360function makeReflectTraps<T extends object>(361 names: (keyof typeof Reflect)[]362): ProxyHandler<T> {363 return names.reduce(364 (traps, name) => {365 // @ts-ignore366 traps[name] = (state, ...args) => Reflect[name](latest(state), ...args)367 return traps368 },369 {} as any370 )371}372373function makeTrapsForGetters<T extends object>(374 getters: {375 [K in keyof T]: (376 state: ES6State<T>377 ) => /* Skip first arg of: ProxyHandler<T>[K] */ any378 }379): ProxyHandler<T> {380 return assign({}, reflectTraps, {381 get(state, prop, receiver) {382 return getters.hasOwnProperty(prop)383 ? getters[prop](state, prop, receiver)384 : Reflect.get(state, prop, receiver)385 },386 setPrototypeOf(state) {387 throw new Error("Object.setPrototypeOf() cannot be used on an Immer draft") // prettier-ignore388 }389 })390}