immer.js
This file
Path
src/immer.js
287 lines · 9.5 KiB · JavaScript
Last changed by
Object.is for equality, more tests. Fixes #43, #42, #48Michel Weststratebefore adoptione29a792
History of this fileTake it
transpile es5 codeMichel Weststratebefore adoptionf012154
lines 1–8why, 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 )8Making several improvements at onceMichel Weststratebefore adoption1116ccf
line 9why, one step back9const PROXY_STATE = Symbol("immer-proxy-state")transpile es5 codeMichel Weststratebefore adoptionf012154
lines 10–47why, one step back10let 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 },37 setPrototypeOf() {38 throw new Error("Don't even try this...")39 }40}4142const arrayTraps = {43 get(target, prop) {44 if (prop === PROXY_STATE) return target[0]45 return target[0].get(prop)46 },47 has(target, prop) {initial solutionMichel Weststratebefore adoptiond618d28
line 48why, one step back48 return prop === PROXY_STATE || prop in target[0].sourcetranspile es5 codeMichel Weststratebefore adoptionf012154
lines 49–81why, one step back49 },50 ownKeys(target) {51 return Reflect.ownKeys(target[0].source)52 },53 set(target, prop, value) {54 target[0].set(prop, value)55 return true56 },57 deleteProperty(target, prop) {58 target[0].deleteProp(prop)59 return true60 },61 getOwnPropertyDescriptor(target, prop) {62 return target[0].getOwnPropertyDescriptor(prop)63 },64 defineProperty(target, property, descriptor) {65 target[0].defineProperty(property, descriptor)66 },67 setPrototypeOf() {68 throw new Error("Don't even try this...")69 }70}7172/**73 * produce takes a state, and runs a function against it.74 * That function can freely mutate the state, as it will create copies-on-write.75 * This means that the original state will stay unchanged, and once the function finishes, the modified state is returned76 *77 * @export78 * @param {any} baseState - the state to start with79 * @param {Function} producer - function that receives a proxy of the base state as first argument and which can be freely modified80 * @returns {any} a new state, or the base state if nothing was modified81 */Default build includes both Proxy and ES5 implementationMichel Weststratebefore adoptionbd9c47b
line 82why, one step back82export default function produce(baseState, producer) {transpile es5 codeMichel Weststratebefore adoptionf012154
lines 83–107why, one step back83 // curried invocation84 if (arguments.length === 1) {85 const producer = baseState86 // prettier-ignore87 if (typeof producer !== "function") throw new Error("if produce is called with 1 argument, the first argument should be a function")88 return function() {89 const args = arguments90 return produce(args[0], draft => {91 args[0] = draft // blegh!92 baseState.apply(null, args)93 })94 }95 }9697 // prettier-ignore98 {99 if (arguments.length !== 2) throw new Error("produce expects 1 or 2 arguments, got " + arguments.length)100 if (!isProxyable(baseState)) throw new Error("the first argument to produce should be a plain object or array, got " + (typeof baseState))101 if (typeof producer !== "function") throw new Error("the second argument to produce should be a function")102 }103 const revocableProxies = []104105 class State {106 constructor(parent, base) {107 this.modified = falseObject.is for equality, more tests. Fixes #43, #42, #48Michel Weststratebefore adoptione29a792
line 108why, one step back108 this.finalized = falsetranspile es5 codeMichel Weststratebefore adoptionf012154
lines 109–136why, one step back109 this.parent = parent110 this.base = base111 this.copy = undefined112 this.proxies = {}113 }114115 get source() {116 return this.modified === true ? this.copy : this.base117 }118119 get(prop) {120 if (this.modified) {121 const value = this.copy[prop]122 if (!isProxy(value) && isProxyable(value))123 return (this.copy[prop] = createProxy(this, value))124 return value125 } else {126 if (prop in this.proxies) return this.proxies[prop]127 const value = this.base[prop]128 if (!isProxy(value) && isProxyable(value))129 return (this.proxies[prop] = createProxy(this, value))130 return value131 }132 }133134 set(prop, value) {135 if (!this.modified) {136 if (Making several improvements at onceMichel Weststratebefore adoption1116ccf
line 137why, one step back137 (prop in this.base && Object.is(this.base[prop], value)) ||transpile es5 codeMichel Weststratebefore adoptionf012154
lines 138–196why, one step back138 (prop in this.proxies && this.proxies[prop] === value)139 )140 return141 this.markChanged()142 }143 this.copy[prop] = value144 }145146 deleteProp(prop) {147 this.markChanged()148 delete this.copy[prop]149 }150151 getOwnPropertyDescriptor(prop) {152 const owner = this.modified153 ? this.copy154 : prop in this.proxies ? this.proxies : this.base155 const descriptor = Reflect.getOwnPropertyDescriptor(owner, prop)156 if (descriptor && !(Array.isArray(owner) && prop === "length"))157 descriptor.configurable = true158 return descriptor159 }160161 defineProperty(property, descriptor) {162 throw new Error(163 "Immer does currently not support defining properties on draft objects"164 )165 }166167 markChanged() {168 if (!this.modified) {169 this.modified = true170 this.copy = Array.isArray(this.base)171 ? this.base.slice()172 : Object.assign({}, this.base) // TODO: eliminate those isArray checks?173 Object.assign(this.copy, this.proxies) // yup that works for arrays as well174 if (this.parent) this.parent.markChanged()175 }176 }177 }178179 // creates a proxy for plain objects / arrays180 function createProxy(parentState, base) {181 const state = new State(parentState, base)182 let proxy183 if (Array.isArray(base)) {184 proxy = Proxy.revocable([state], arrayTraps)185 } else {186 proxy = Proxy.revocable(state, objectTraps)187 }188 revocableProxies.push(proxy)189 return proxy.proxy190 }191192 // given a base object, returns it if unmodified, or return the changed cloned if modified193 function finalize(base) {194 if (isProxy(base)) {195 const state = base[PROXY_STATE]196 if (state.modified === true) {Object.is for equality, more tests. Fixes #43, #42, #48Michel Weststratebefore adoptione29a792
lines 197–198why, one step back197 if (state.finalized === true) return state.copy198 state.finalized = truetranspile es5 codeMichel Weststratebefore adoptionf012154
lines 199–201why, one step back199 if (Array.isArray(state.base)) return finalizeArray(state)200 return finalizeObject(state)201 } else return state.baseFaster, simpler implementationMichel Weststratebefore adoptionc420f0d
lines 202–204why, one step back202 } else if (base !== null && typeof base === "object") {203 // 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 original204 // tree and it could contain proxies at arbitrarily places. Let's find and finalize them as wellMaking several improvements at onceMichel Weststratebefore adoption1116ccf
line 205why, one step back205 // TODO: optimize this; walk the tree without writing to find proxiesFaster, simpler implementationMichel Weststratebefore adoptionc420f0d
lines 206–210why, one step back206 if (Array.isArray(base)) {207 for (let i = 0; i < base.length; i++)208 base[i] = finalize(base[i])209 return freeze(base)210 }initial solutionMichel Weststratebefore adoptiond618d28
lines 211–212why, one step back211 const proto = Object.getPrototypeOf(base)212 if (proto === null || proto === Object.prototype) {Faster, simpler implementationMichel Weststratebefore adoptionc420f0d
lines 213–214why, one step back213 for (let key in base) base[key] = finalize(base[key])214 return freeze(base)initial solutionMichel Weststratebefore adoptiond618d28
line 215why, one step back215 }transpile es5 codeMichel Weststratebefore adoptionf012154
lines 216–221why, one step back216 }217 return base218 }219220 function finalizeObject(state) {221 const copy = state.copyFaster, simpler implementationMichel Weststratebefore adoptionc420f0d
lines 222–225why, one step back222 const base = state.base223 for (var prop in copy) {224 if (copy[prop] !== base[prop]) copy[prop] = finalize(copy[prop])225 }transpile es5 codeMichel Weststratebefore adoptionf012154
lines 226–230why, one step back226 return freeze(copy)227 }228229 function finalizeArray(state) {230 const copy = state.copyFaster, simpler implementationMichel Weststratebefore adoptionc420f0d
lines 231–234why, one step back231 const base = state.base232 for (let i = 0; i < copy.length; i++) {233 if (copy[i] !== base[i]) copy[i] = finalize(copy[i])234 }transpile es5 codeMichel Weststratebefore adoptionf012154
lines 235–262why, one step back235 return freeze(copy)236 }237238 // create proxy for root239 const rootClone = createProxy(undefined, baseState)240 // execute the thunk241 const maybeVoidReturn = producer(rootClone)242 //values either than undefined will trigger warning;243 !Object.is(maybeVoidReturn, undefined) &&244 console.warn(245 `Immer callback expects no return value. However ${typeof maybeVoidReturn} was returned`246 )247 // and finalize the modified proxy248 const res = finalize(rootClone)249 // revoke all proxies250 revocableProxies.forEach(p => p.revoke())251 return res252}253254function isProxy(value) {255 return !!value && !!value[PROXY_STATE]256}257258function isProxyable(value) {259 if (!value) return false260 if (typeof value !== "object") return false261 if (Array.isArray(value)) return true262 const proto = Object.getPrototypeOf(value)initial solutionMichel Weststratebefore adoptiond618d28
line 263why, one step back263 return proto === null || proto === Object.prototypetranspile es5 codeMichel Weststratebefore adoptionf012154
lines 264–284why, one step back264}265266function freeze(value) {267 // short circuit to achieve 100% code coverage instead of 98%268 /*269 if(autoFreeze) {270 Object.freeze(value)271 }272 * */273 autoFreeze && Object.freeze(value)274 return value275}276277/**278 * Automatically freezes any state trees generated by immer.279 * This protects against accidental modifications of the state tree outside of an immer function.280 * This comes with a performance impact, so it is recommended to disable this option in production.281 * It is by default enabled.282 *283 * @returns {void}284 */Default build includes both Proxy and ES5 implementationMichel Weststratebefore adoptionbd9c47b
line 285why, one step back285export function setAutoFreeze(enableAutoFreeze) {transpile es5 codeMichel Weststratebefore adoptionf012154
lines 286–287why, one step back286 autoFreeze = enableAutoFreeze287}