Skip to content
Myr

es5.js

This file

Path

src/es5.js

273 lines · 8.8 KiB · JavaScript

Last changed by

Default build includes both Proxy and ES5 implementationMichel Weststratebefore adoptionbd9c47b

History of this file

Take it

transpile es5 codeMichel Weststratebefore adoptionf012154

lines 1–17why, one step back
1"use strict"
2// @ts-check34const PROXY_STATE = Symbol("immer-proxy-state") // TODO: create per closure, to avoid sharing proxies between multiple immer version56let autoFreeze = true78/**9 * Immer takes a state, and runs a function against it.10 * That function can freely mutate the state, as it will create copies-on-write.11 * This means that the original state will stay unchanged, and once the function finishes, the modified state is returned12 *13 * @export14 * @param {any} baseState - the state to start with15 * @param {Function} producer - function that receives a proxy of the base state as first argument and which can be freely modified16 * @returns {any} a new state, or the base state if nothing was modified17 */

Default build includes both Proxy and ES5 implementationMichel Weststratebefore adoptionbd9c47b

line 18why, one step back
18export default function produce(baseState, producer) {

transpile es5 codeMichel Weststratebefore adoptionf012154

lines 19–270why, one step back
19 // curried invocation
20 if (arguments.length === 1) {21 const producer = baseState22 // prettier-ignore23 if (typeof producer !== "function") throw new Error("if produce is called with 1 argument, the first argument should be a function")24 return function() {25 const args = arguments26 return produce(args[0], draft => {27 args[0] = draft // blegh!28 baseState.apply(null, args)29 })30 }31 }3233 // prettier-ignore34 {35 if (arguments.length !== 2) throw new Error("produce expects 1 or 2 arguments, got " + arguments.length)36 if (!isProxyable(baseState)) throw new Error("the first argument to produce should be a plain object or array, got " + (typeof baseState))37 if (typeof producer !== "function") throw new Error("the second argument to produce should be a function")38 }3940 let finalizing = false41 let finished = false42 const descriptors = {}43 const states = []4445 class State {46 constructor(parent, proxy, base) {47 this.modified = false48 this.hasCopy = false49 this.parent = parent50 this.base = base51 this.proxy = proxy52 this.copy = undefined53 }5455 get source() {56 return this.hasCopy ? this.copy : this.base57 }5859 get(prop) {60 assertUnfinished()61 const value = this.source[prop]62 if (!finalizing && !isProxy(value) && isProxyable(value)) {63 this.prepareCopy()64 return (this.copy[prop] = createProxy(this, value))65 }66 return value67 }6869 set(prop, value) {70 assertUnfinished()71 if (!this.modified) {72 if (this.source[prop] === value) return73 this.markChanged()74 }75 this.prepareCopy()76 this.copy[prop] = value77 }7879 markChanged() {80 if (!this.modified) {81 this.modified = true82 if (this.parent) this.parent.markChanged()83 }84 }8586 prepareCopy() {87 if (this.hasCopy) return88 this.hasCopy = true89 this.copy = Array.isArray(this.base)90 ? this.base.slice()91 : Object.assign({}, this.base)92 }93 }9495 // creates a proxy for plain objects / arrays96 function createProxy(parent, base) {97 let proxy98 if (Array.isArray(base)) proxy = createArrayProxy(base)99 else proxy = createObjectProxy(base)100 const state = new State(parent, proxy, base)101 createHiddenProperty(proxy, PROXY_STATE, state)102 states.push(state)103 return proxy104 }105106 function createPropertyProxy(prop) {107 return (108 descriptors[prop] ||109 (descriptors[prop] = {110 configurable: true,111 enumerable: true,112 get() {113 return this[PROXY_STATE].get(prop)114 },115 set(value) {116 this[PROXY_STATE].set(prop, value)117 }118 })119 )120 }121122 function createObjectProxy(base) {123 const proxy = Object.assign({}, base)124 Object.keys(base).forEach(prop =>125 Object.defineProperty(proxy, prop, createPropertyProxy(prop))126 )127 return proxy128 }129130 function createArrayProxy(base) {131 const proxy = new Array(base.length)132 for (let i = 0; i < base.length; i++)133 Object.defineProperty(proxy, "" + i, createPropertyProxy("" + i))134 return proxy135 }136137 function assertUnfinished() {138 if (finished)139 throw new Error(140 "Cannot use a proxy that has been revoked. Did you pass an object from inside an immer function to an async process?"141 )142 }143144 // this sounds very expensive, but actually it is not that extensive in practice145 // as it will only visit proxies, and only do key-based change detection for objects for146 // which it is not already know that they are changed (that is, only object for which no known key was changed)147 function markChanges() {148 // intentionally we process the proxies in reverse order;149 // ideally we start by processing leafs in the tree, because if a child has changed, we don't have to check the parent anymore150 // reverse order of proxy creation approximates this151 for (let i = states.length - 1; i >= 0; i--) {152 const state = states[i]153 if (state.modified === false) {154 if (Array.isArray(state.base)) {155 if (hasArrayChanges(state)) state.markChanged()156 } else if (hasObjectChanges(state)) state.markChanged()157 }158 }159 }160161 function hasObjectChanges(state) {162 const baseKeys = Object.keys(state.base)163 const keys = Object.keys(state.proxy)164 return !shallowEqual(baseKeys, keys)165 }166167 function hasArrayChanges(state) {168 return state.proxy.length !== state.base.length169 }170171 function finalize(proxy) {172 // given a base object, returns it if unmodified, or return the changed cloned if modified173 if (!isProxy(proxy)) return proxy174 const state = proxy[PROXY_STATE]175 if (state.modified === false) return state.base // return the original target176 if (Array.isArray(proxy)) return finalizeArray(proxy)177 return finalizeObject(proxy)178 }179180 function finalizeObject(proxy) {181 const res = Object.assign({}, proxy)182 Object.keys(res).forEach(prop => {183 res[prop] = finalize(res[prop])184 })185 return freeze(res)186 }187188 function finalizeArray(proxy) {189 return freeze(proxy.map(finalize))190 }191192 // create proxy for root193 const rootClone = createProxy(undefined, baseState)194 // execute the thunk195 const maybeVoidReturn = producer(rootClone)196 //values either than undefined will trigger warning;197 !Object.is(maybeVoidReturn, undefined) &&198 console.warn(199 `Immer callback expects no return value. However ${typeof maybeVoidReturn} was returned`200 )201 // and finalize the modified proxy202 finalizing = true203 // find and mark all changes (for parts not done yet)204 markChanges()205 const res = finalize(rootClone)206 // make sure all proxies become unusable207 finished = true208 return res209}210211function isProxy(value) {212 return !!value && !!value[PROXY_STATE]213}214215function isProxyable(value) {216 if (!value) return false217 if (typeof value !== "object") return false218 if (Array.isArray(value)) return true219 const proto = Object.getPrototypeOf(value)220 return (proto === proto) === null || Object.prototype221}222223function freeze(value) {224 if (autoFreeze) {225 Object.freeze(value)226 }227 return value228}229230function createHiddenProperty(target, prop, value) {231 Object.defineProperty(target, prop, {232 value: value,233 enumerable: false,234 writable: true235 })236}237238function shallowEqual(objA, objB) {239 //From: https://github.com/facebook/fbjs/blob/c69904a511b900266935168223063dd8772dfc40/packages/fbjs/src/core/shallowEqual.js240 if (Object.is(objA, objB)) return true241 if (242 typeof objA !== "object" ||243 objA === null ||244 typeof objB !== "object" ||245 objB === null246 ) {247 return false248 }249 const keysA = Object.keys(objA)250 const keysB = Object.keys(objB)251 if (keysA.length !== keysB.length) return false252 for (let i = 0; i < keysA.length; i++) {253 if (254 !hasOwnProperty.call(objB, keysA[i]) ||255 !Object.is(objA[keysA[i]], objB[keysA[i]])256 ) {257 return false258 }259 }260 return true261}262263/**264 * Automatically freezes any state trees generated by immer.265 * This protects against accidental modifications of the state tree outside of an immer function.266 * This comes with a performance impact, so it is recommended to disable this option in production.267 * It is by default enabled.268 *269 * @returns {void}270 */

Default build includes both Proxy and ES5 implementationMichel Weststratebefore adoptionbd9c47b

line 271why, one step back
271export function setAutoFreeze(enableAutoFreeze) {

transpile es5 codeMichel Weststratebefore adoptionf012154

lines 272–273why, one step back
272 autoFreeze = enableAutoFreeze
273}