immer.js
This file
Path
src/immer.js
272 lines · 8.6 KiB · JavaScript
Last changed by
Default build includes both Proxy and ES5 implementationMichel Weststratebefore adoptionbd9c47b
History of this fileTake it
transpile es5 codeMichel Weststratebefore adoptionf012154
lines 1–83why, one step back1"use strict"2// @ts-check34if (typeof Proxy === "undefined")5 throw new Error(6 "Immer requires `Proxy` to be available, but it seems to be not available on your platform. Consider requiring immer '\"immer/es5\"' instead."7 )89const PROXY_STATE = Symbol("immer-proxy-state") // TODO: create per closure, to avoid sharing proxies between multiple immer version10let autoFreeze = true1112const objectTraps = {13 get(target, prop) {14 if (prop === PROXY_STATE) return target15 return target.get(prop)16 },17 has(target, prop) {18 return prop in target.source19 },20 ownKeys(target) {21 return Reflect.ownKeys(target.source)22 },23 set(target, prop, value) {24 target.set(prop, value)25 return true26 },27 deleteProperty(target, prop) {28 target.deleteProp(prop)29 return true30 },31 getOwnPropertyDescriptor(target, prop) {32 return target.getOwnPropertyDescriptor(prop)33 },34 defineProperty(target, property, descriptor) {35 target.defineProperty(property, descriptor)36 return true37 },38 setPrototypeOf() {39 throw new Error("Don't even try this...")40 }41}4243const arrayTraps = {44 get(target, prop) {45 if (prop === PROXY_STATE) return target[0]46 return target[0].get(prop)47 },48 has(target, prop) {49 return prop in target[0].source50 },51 ownKeys(target) {52 return Reflect.ownKeys(target[0].source)53 },54 set(target, prop, value) {55 target[0].set(prop, value)56 return true57 },58 deleteProperty(target, prop) {59 target[0].deleteProp(prop)60 return true61 },62 getOwnPropertyDescriptor(target, prop) {63 return target[0].getOwnPropertyDescriptor(prop)64 },65 defineProperty(target, property, descriptor) {66 target[0].defineProperty(property, descriptor)67 return true68 },69 setPrototypeOf() {70 throw new Error("Don't even try this...")71 }72}7374/**75 * produce takes a state, and runs a function against it.76 * That function can freely mutate the state, as it will create copies-on-write.77 * This means that the original state will stay unchanged, and once the function finishes, the modified state is returned78 *79 * @export80 * @param {any} baseState - the state to start with81 * @param {Function} producer - function that receives a proxy of the base state as first argument and which can be freely modified82 * @returns {any} a new state, or the base state if nothing was modified83 */Default build includes both Proxy and ES5 implementationMichel Weststratebefore adoptionbd9c47b
line 84why, one step back84export default function produce(baseState, producer) {transpile es5 codeMichel Weststratebefore adoptionf012154
lines 85–269why, one step back85 // curried invocation86 if (arguments.length === 1) {87 const producer = baseState88 // prettier-ignore89 if (typeof producer !== "function") throw new Error("if produce is called with 1 argument, the first argument should be a function")90 return function() {91 const args = arguments92 return produce(args[0], draft => {93 args[0] = draft // blegh!94 baseState.apply(null, args)95 })96 }97 }9899 // prettier-ignore100 {101 if (arguments.length !== 2) throw new Error("produce expects 1 or 2 arguments, got " + arguments.length)102 if (!isProxyable(baseState)) throw new Error("the first argument to produce should be a plain object or array, got " + (typeof baseState))103 if (typeof producer !== "function") throw new Error("the second argument to produce should be a function")104 }105 const revocableProxies = []106107 class State {108 constructor(parent, base) {109 this.modified = false110 this.parent = parent111 this.base = base112 this.copy = undefined113 this.proxies = {}114 }115116 get source() {117 return this.modified === true ? this.copy : this.base118 }119120 get(prop) {121 if (this.modified) {122 const value = this.copy[prop]123 if (!isProxy(value) && isProxyable(value))124 return (this.copy[prop] = createProxy(this, value))125 return value126 } else {127 if (prop in this.proxies) return this.proxies[prop]128 const value = this.base[prop]129 if (!isProxy(value) && isProxyable(value))130 return (this.proxies[prop] = createProxy(this, value))131 return value132 }133 }134135 set(prop, value) {136 if (!this.modified) {137 if (138 (prop in this.base && this.base[prop] === value) ||139 (prop in this.proxies && this.proxies[prop] === value)140 )141 return142 this.markChanged()143 }144 this.copy[prop] = value145 }146147 deleteProp(prop) {148 this.markChanged()149 delete this.copy[prop]150 }151152 getOwnPropertyDescriptor(prop) {153 const owner = this.modified154 ? this.copy155 : prop in this.proxies ? this.proxies : this.base156 const descriptor = Reflect.getOwnPropertyDescriptor(owner, prop)157 if (descriptor && !(Array.isArray(owner) && prop === "length"))158 descriptor.configurable = true159 return descriptor160 }161162 defineProperty(property, descriptor) {163 throw new Error(164 "Immer does currently not support defining properties on draft objects"165 )166 }167168 markChanged() {169 if (!this.modified) {170 this.modified = true171 this.copy = Array.isArray(this.base)172 ? this.base.slice()173 : Object.assign({}, this.base) // TODO: eliminate those isArray checks?174 Object.assign(this.copy, this.proxies) // yup that works for arrays as well175 if (this.parent) this.parent.markChanged()176 }177 }178 }179180 // creates a proxy for plain objects / arrays181 function createProxy(parentState, base) {182 const state = new State(parentState, base)183 let proxy184 if (Array.isArray(base)) {185 // Proxy should be created with an array to make it an array for JS186 // so... here you have it!187 proxy = Proxy.revocable([state], arrayTraps)188 } else {189 proxy = Proxy.revocable(state, objectTraps)190 }191 revocableProxies.push(proxy)192 return proxy.proxy193 }194195 // given a base object, returns it if unmodified, or return the changed cloned if modified196 function finalize(base) {197 if (isProxy(base)) {198 const state = base[PROXY_STATE]199 if (state.modified === true) {200 if (Array.isArray(state.base)) return finalizeArray(state)201 return finalizeObject(state)202 } else return state.base203 }204 return base205 }206207 function finalizeObject(state) {208 const copy = state.copy209 Object.keys(copy).forEach(prop => {210 copy[prop] = finalize(copy[prop])211 })212 return freeze(copy)213 }214215 function finalizeArray(state) {216 const copy = state.copy217 copy.forEach((value, index) => {218 copy[index] = finalize(copy[index])219 })220 return freeze(copy)221 }222223 // create proxy for root224 const rootClone = createProxy(undefined, baseState)225 // execute the thunk226 const maybeVoidReturn = producer(rootClone)227 //values either than undefined will trigger warning;228 !Object.is(maybeVoidReturn, undefined) &&229 console.warn(230 `Immer callback expects no return value. However ${typeof maybeVoidReturn} was returned`231 )232 // and finalize the modified proxy233 const res = finalize(rootClone)234 // revoke all proxies235 revocableProxies.forEach(p => p.revoke())236 return res237}238239function isProxy(value) {240 return !!value && !!value[PROXY_STATE]241}242243function isProxyable(value) {244 if (!value) return false245 if (typeof value !== "object") return false246 if (Array.isArray(value)) return true247 const proto = Object.getPrototypeOf(value)248 return (proto === proto) === null || Object.prototype249}250251function freeze(value) {252 // short circuit to achieve 100% code coverage instead of 98%253 /*254 if(autoFreeze) {255 Object.freeze(value)256 }257 * */258 autoFreeze && Object.freeze(value)259 return value260}261262/**263 * Automatically freezes any state trees generated by immer.264 * This protects against accidental modifications of the state tree outside of an immer function.265 * This comes with a performance impact, so it is recommended to disable this option in production.266 * It is by default enabled.267 *268 * @returns {void}269 */Default build includes both Proxy and ES5 implementationMichel Weststratebefore adoptionbd9c47b
line 270why, one step back270export function setAutoFreeze(enableAutoFreeze) {transpile es5 codeMichel Weststratebefore adoptionf012154
lines 271–272why, one step back271 autoFreeze = enableAutoFreeze272}