immer.js
This file
Path
src/immer.js
285 lines · 9.4 KiB · JavaScript
Last changed by
Faster, simpler implementationMichel Weststratebefore adoptionc420f0d
History of this fileTake it
transpile es5 codeMichel Weststratebefore adoptionf012154
lines 1–48why, 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) {initial solutionMichel Weststratebefore adoptiond618d28
line 49why, one step back49 return prop === PROXY_STATE || prop in target[0].sourcetranspile es5 codeMichel Weststratebefore adoptionf012154
lines 50–83why, one step back50 },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–200why, 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 = Proxy.revocable([state], arrayTraps)186 } else {187 proxy = Proxy.revocable(state, objectTraps)188 }189 revocableProxies.push(proxy)190 return proxy.proxy191 }192193 // given a base object, returns it if unmodified, or return the changed cloned if modified194 function finalize(base) {195 if (isProxy(base)) {196 const state = base[PROXY_STATE]197 if (state.modified === true) {198 if (Array.isArray(state.base)) return finalizeArray(state)199 return finalizeObject(state)200 } else return state.baseFaster, simpler implementationMichel Weststratebefore adoptionc420f0d
lines 201–208why, one step back201 } else if (base !== null && typeof base === "object") {202 // 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 original203 // tree and it could contain proxies at arbitrarily places. Let's find and finalize them as well204 if (Array.isArray(base)) {205 for (let i = 0; i < base.length; i++)206 base[i] = finalize(base[i])207 return freeze(base)208 }initial solutionMichel Weststratebefore adoptiond618d28
lines 209–210why, one step back209 const proto = Object.getPrototypeOf(base)210 if (proto === null || proto === Object.prototype) {Faster, simpler implementationMichel Weststratebefore adoptionc420f0d
lines 211–212why, one step back211 for (let key in base) base[key] = finalize(base[key])212 return freeze(base)initial solutionMichel Weststratebefore adoptiond618d28
line 213why, one step back213 }transpile es5 codeMichel Weststratebefore adoptionf012154
lines 214–219why, one step back214 }215 return base216 }217218 function finalizeObject(state) {219 const copy = state.copyFaster, simpler implementationMichel Weststratebefore adoptionc420f0d
lines 220–223why, one step back220 const base = state.base221 for (var prop in copy) {222 if (copy[prop] !== base[prop]) copy[prop] = finalize(copy[prop])223 }transpile es5 codeMichel Weststratebefore adoptionf012154
lines 224–228why, one step back224 return freeze(copy)225 }226227 function finalizeArray(state) {228 const copy = state.copyFaster, simpler implementationMichel Weststratebefore adoptionc420f0d
lines 229–232why, one step back229 const base = state.base230 for (let i = 0; i < copy.length; i++) {231 if (copy[i] !== base[i]) copy[i] = finalize(copy[i])232 }transpile es5 codeMichel Weststratebefore adoptionf012154
lines 233–260why, one step back233 return freeze(copy)234 }235236 // create proxy for root237 const rootClone = createProxy(undefined, baseState)238 // execute the thunk239 const maybeVoidReturn = producer(rootClone)240 //values either than undefined will trigger warning;241 !Object.is(maybeVoidReturn, undefined) &&242 console.warn(243 `Immer callback expects no return value. However ${typeof maybeVoidReturn} was returned`244 )245 // and finalize the modified proxy246 const res = finalize(rootClone)247 // revoke all proxies248 revocableProxies.forEach(p => p.revoke())249 return res250}251252function isProxy(value) {253 return !!value && !!value[PROXY_STATE]254}255256function isProxyable(value) {257 if (!value) return false258 if (typeof value !== "object") return false259 if (Array.isArray(value)) return true260 const proto = Object.getPrototypeOf(value)initial solutionMichel Weststratebefore adoptiond618d28
line 261why, one step back261 return proto === null || proto === Object.prototypetranspile es5 codeMichel Weststratebefore adoptionf012154
lines 262–282why, one step back262}263264function freeze(value) {265 // short circuit to achieve 100% code coverage instead of 98%266 /*267 if(autoFreeze) {268 Object.freeze(value)269 }270 * */271 autoFreeze && Object.freeze(value)272 return value273}274275/**276 * Automatically freezes any state trees generated by immer.277 * This protects against accidental modifications of the state tree outside of an immer function.278 * This comes with a performance impact, so it is recommended to disable this option in production.279 * It is by default enabled.280 *281 * @returns {void}282 */Default build includes both Proxy and ES5 implementationMichel Weststratebefore adoptionbd9c47b
line 283why, one step back283export function setAutoFreeze(enableAutoFreeze) {transpile es5 codeMichel Weststratebefore adoptionf012154
lines 284–285why, one step back284 autoFreeze = enableAutoFreeze285}