Skip to content
Myr

proxy.js

This file

Path

src/proxy.js

189 lines · 5.5 KiB · JavaScript

Last changed by

less builds is more?Michel Weststratebefore adoption74a97b6

History of this file

Take it

less builds is more?Michel Weststratebefore adoption74a97b6

lines 1–189why, one step back
1"use strict"
2// @ts-check34import {autoFreeze, isProxyable, isProxy, freeze, PROXY_STATE} from "./common"56let revocableProxies = null78const objectTraps = {9 get,10 has(target, prop) {11 return prop in source(target)12 },13 ownKeys(target) {14 return Reflect.ownKeys(source(target))15 },16 set,17 deleteProperty,18 getOwnPropertyDescriptor,19 defineProperty,20 setPrototypeOf() {21 throw new Error("Don't even try this...")22 }23}2425const arrayTraps = {}26for (let key in objectTraps) {27 arrayTraps[key] = function() {28 arguments[0] = arguments[0][0]29 return objectTraps[key].apply(this, arguments)30 }31}3233function createState(parent, base) {34 return {35 modified: false,36 finalized: false,37 parent,38 base,39 copy: undefined,40 proxies: {}41 }42}4344function source(state) {45 return state.modified === true ? state.copy : state.base46}4748function get(state, prop) {49 if (prop === PROXY_STATE) return state50 if (state.modified) {51 const value = state.copy[prop]52 if (!isProxy(value) && isProxyable(value))53 return (state.copy[prop] = createProxy(state, value))54 return value55 } else {56 if (prop in state.proxies) return state.proxies[prop]57 const value = state.base[prop]58 if (!isProxy(value) && isProxyable(value))59 return (state.proxies[prop] = createProxy(state, value))60 return value61 }62}6364function set(state, prop, value) {65 if (!state.modified) {66 if (67 (prop in state.base && Object.is(state.base[prop], value)) ||68 (prop in state.proxies && state.proxies[prop] === value)69 )70 return true71 markChanged(state)72 }73 state.copy[prop] = value74 return true75}7677function deleteProperty(state, prop) {78 markChanged(state)79 delete state.copy[prop]80 return true81}8283function getOwnPropertyDescriptor(state, prop) {84 const owner = state.modified85 ? state.copy86 : prop in state.proxies ? state.proxies : state.base87 const descriptor = Reflect.getOwnPropertyDescriptor(owner, prop)88 if (descriptor && !(Array.isArray(owner) && prop === "length"))89 descriptor.configurable = true90 return descriptor91}9293function defineProperty() {94 throw new Error(95 "Immer does currently not support defining properties on draft objects"96 )97}9899function markChanged(state) {100 if (!state.modified) {101 state.modified = true102 state.copy = Array.isArray(state.base)103 ? state.base.slice()104 : Object.assign({}, state.base) // TODO: eliminate those isArray checks?105 Object.assign(state.copy, state.proxies) // yup that works for arrays as well106 if (state.parent) markChanged(state.parent)107 }108}109110// creates a proxy for plain objects / arrays111function createProxy(parentState, base) {112 const state = createState(parentState, base)113 let proxy114 if (Array.isArray(base)) {115 proxy = Proxy.revocable([state], arrayTraps)116 } else {117 proxy = Proxy.revocable(state, objectTraps)118 }119 revocableProxies.push(proxy)120 return proxy.proxy121}122123// given a base object, returns it if unmodified, or return the changed cloned if modified124function finalize(base) {125 if (isProxy(base)) {126 const state = base[PROXY_STATE]127 if (state.modified === true) {128 if (state.finalized === true) return state.copy129 state.finalized = true130 if (Array.isArray(state.base)) return finalizeArray(state)131 return finalizeObject(state)132 } else return state.base133 } else if (base !== null && typeof base === "object") {134 // If finalize is called on an object that was not a proxy, it means that it is an object that was not there in the original135 // tree and it could contain proxies at arbitrarily places. Let's find and finalize them as well136 // TODO: optimize this; walk the tree without writing to find proxies137 if (Array.isArray(base)) {138 for (let i = 0; i < base.length; i++) base[i] = finalize(base[i])139 return freeze(base)140 }141 const proto = Object.getPrototypeOf(base)142 if (proto === null || proto === Object.prototype) {143 for (let key in base) base[key] = finalize(base[key])144 return freeze(base)145 }146 }147 return base148}149150function finalizeObject(state) {151 const copy = state.copy152 const base = state.base153 for (var prop in copy) {154 if (copy[prop] !== base[prop]) copy[prop] = finalize(copy[prop])155 }156 return freeze(copy)157}158159function finalizeArray(state) {160 const copy = state.copy161 const base = state.base162 for (let i = 0; i < copy.length; i++) {163 if (copy[i] !== base[i]) copy[i] = finalize(copy[i])164 }165 return freeze(copy)166}167168export function produceProxy(baseState, producer) {169 const previousProxies = revocableProxies170 revocableProxies = []171 try {172 // create proxy for root173 const rootClone = createProxy(undefined, baseState)174 // execute the thunk175 const maybeVoidReturn = producer(rootClone)176 //values either than undefined will trigger warning;177 !Object.is(maybeVoidReturn, undefined) &&178 console.warn(179 `Immer callback expects no return value. However ${typeof maybeVoidReturn} was returned`180 )181 // and finalize the modified proxy182 const res = finalize(rootClone)183 // revoke all proxies184 revocableProxies.forEach(p => p.revoke())185 return res186 } finally {187 revocableProxies = previousProxies188 }189}