es5.js
This file
Path
es5.js
259 lines · 8.6 KiB · JavaScript
Last changed by
Merge pull request #22 from mweststrate/feature/es5Michel Weststratebefore adoption4165abb
History of this fileTake it
Merge pull request #22 from mweststrate/feature/es5Michel Weststratebefore adoption4165abb
lines 1–259why, one step back1"use strict"2// @ts-check34const PROXY_TARGET = Symbol("immer-proxy")5const CHANGED_STATE = Symbol("immer-changed-state")6const PARENT = Symbol("immer-parent")78let autoFreeze = true910/**11 * Immer takes a state, and runs a function against it.12 * That function can freely mutate the state, as it will create copies-on-write.13 * This means that the original state will stay unchanged, and once the function finishes, the modified state is returned14 *15 * @export16 * @param {any} baseState - the state to start with17 * @param {Function} thunk - function that receives a proxy of the base state as first argument and which can be freely modified18 * @returns {any} a new state, or the base state if nothing was modified19 */20function immer(baseState, thunk) {21 let finalizing = false22 let finished = false23 const descriptors = {}24 const proxies = []2526 // creates a proxy for plain objects / arrays27 function createProxy(base, parent) {28 let proxy29 if (isPlainObject(base)) proxy = createObjectProxy(base)30 else if (Array.isArray(base)) proxy = createArrayProxy(base)31 else throw new Error("Expected a plain object or array")32 createHiddenProperty(proxy, PROXY_TARGET, base)33 createHiddenProperty(proxy, CHANGED_STATE, false)34 createHiddenProperty(proxy, PARENT, parent)35 proxies.push(proxy)36 return proxy37 }3839 function assertUnfinished() {40 if (finished)41 throw new Error(42 "Cannot use a proxy that has been revoked. Did you pass an object from inside an immer function to an async process?"43 )44 }4546 function proxySet(proxy, prop, value) {47 // immer func not ended?48 assertUnfinished()49 // actually a change?50 if (Object.is(proxy[prop], value)) return51 // mark changed52 markDirty(proxy)53 // and stop proxying, we know this object has changed54 Object.defineProperty(proxy, prop, {55 enumerable: true,56 writable: true,57 configurable: true,58 value: value59 })60 }6162 function createPropertyProxy(prop) {63 return (64 descriptors[prop] ||65 (descriptors[prop] = {66 configurable: true,67 enumerable: true,68 get() {69 assertUnfinished()70 // find the target object71 const target = this[PROXY_TARGET]72 // find the original value73 const value = target[prop]74 // if we are finalizing, don't bother creating proxies, just return base value75 if (finalizing) return value76 // if not proxy-able, return value77 if (!isPlainObject(value) && !Array.isArray(value))78 return value79 // otherwise, create proxy80 const proxy = createProxy(value, this)81 // and make sure this proxy is returned from this prop in the future if read82 // (write behavior as is)83 Object.defineProperty(this, prop, {84 configurable: true,85 enumerable: true,86 get() {87 return proxy88 },89 set(value) {90 proxySet(this, prop, value)91 }92 })93 return proxy94 },95 set(value) {96 proxySet(this, prop, value)97 }98 })99 )100 }101102 function createObjectProxy(base) {103 const proxy = {}104 Object.keys(base).forEach(prop =>105 Object.defineProperty(proxy, prop, createPropertyProxy(prop))106 )107 return proxy108 }109110 function createArrayProxy(base) {111 const proxy = []112 for (let i = 0; i < base.length; i++)113 Object.defineProperty(proxy, "" + i, createPropertyProxy("" + i))114 return proxy115 }116117 // this sounds very expensive, but actually it is not that extensive in practice118 // as it will only visit proxies, and only do key-based change detection for objects for119 // which it is not already know that they are changed (that is, only object for which no known key was changed)120 function markChanges() {121 // intentionally we process the proxies in reverse order;122 // ideally we start by processing leafs in the tree, because if a child has changed, we don't have to check the parent anymore123 // reverse order of proxy creation approximates this124 for (let i = proxies.length - 1; i >= 0; i--) {125 const proxy = proxies[i]126 if (127 proxy[CHANGED_STATE] === false &&128 ((isPlainObject(proxy) && hasObjectChanges(proxy)) ||129 (Array.isArray(proxy) && hasArrayChanges(proxy)))130 ) {131 markDirty(proxy)132 }133 }134 }135136 function hasObjectChanges(proxy) {137 const baseKeys = Object.keys(proxy[PROXY_TARGET])138 const keys = Object.keys(proxy)139 return !shallowEqual(baseKeys, keys)140 }141142 function hasArrayChanges(proxy) {143 return proxy[PROXY_TARGET].length !== proxy.length144 }145146 function finalize(proxy) {147 // given a base object, returns it if unmodified, or return the changed cloned if modified148 if (!isProxy(proxy)) return proxy149 if (!proxy[CHANGED_STATE]) return proxy[PROXY_TARGET] // return the original target150 if (isPlainObject(proxy)) return finalizeObject(proxy)151 if (Array.isArray(proxy)) return finalizeArray(proxy)152 throw new Error("Illegal state")153 }154155 function finalizeObject(proxy) {156 const res = {}157 Object.keys(proxy).forEach(prop => {158 res[prop] = finalize(proxy[prop])159 })160 return freeze(res)161 }162163 function finalizeArray(proxy) {164 return freeze(proxy.map(finalize))165 }166167 // create proxy for root168 const rootClone = createProxy(baseState, undefined)169 // execute the thunk170 const maybeVoidReturn = thunk(rootClone)171 //values either than undefined will trigger warning;172 !Object.is(maybeVoidReturn, undefined) &&173 console.warn(174 `Immer callback expects no return value. However ${typeof maybeVoidReturn} was returned`175 )176 // and finalize the modified proxy177 finalizing = true178 // find and mark all changes (for parts not done yet)179 markChanges()180 const res = finalize(rootClone)181 // make sure all proxies become unusable182 finished = true183 return res184}185186function markDirty(proxy) {187 proxy[CHANGED_STATE] = true188 let parent = proxy189 while ((parent = parent[PARENT])) {190 if (parent[CHANGED_STATE] === true) return191 parent[CHANGED_STATE] = true192 }193}194195function isPlainObject(value) {196 if (value === null || typeof value !== "object") return false197 const proto = Object.getPrototypeOf(value)198 return proto === Object.prototype || proto === null199}200201function isProxy(value) {202 return !!(value && value[PROXY_TARGET])203}204205function freeze(value) {206 if (autoFreeze) {207 Object.freeze(value)208 }209 return value210}211212function createHiddenProperty(target, prop, value) {213 Object.defineProperty(target, prop, {214 value: value,215 enumerable: false,216 writable: true217 })218}219220function shallowEqual(objA, objB) {221 //From: https://github.com/facebook/fbjs/blob/c69904a511b900266935168223063dd8772dfc40/packages/fbjs/src/core/shallowEqual.js222 if (Object.is(objA, objB)) return true223 if (224 typeof objA !== "object" ||225 objA === null ||226 typeof objB !== "object" ||227 objB === null228 ) {229 return false230 }231 const keysA = Object.keys(objA)232 const keysB = Object.keys(objB)233 if (keysA.length !== keysB.length) return false234 for (let i = 0; i < keysA.length; i++) {235 if (236 !hasOwnProperty.call(objB, keysA[i]) ||237 !Object.is(objA[keysA[i]], objB[keysA[i]])238 ) {239 return false240 }241 }242 return true243}244245/**246 * Automatically freezes any state trees generated by immer.247 * This protects against accidental modifications of the state tree outside of an immer function.248 * This comes with a performance impact, so it is recommended to disable this option in production.249 * It is by default enabled.250 *251 * @returns {void}252 */253function setAutoFreeze(enableAutoFreeze) {254 autoFreeze = enableAutoFreeze255}256257createHiddenProperty(exports, "__esModule", true)258module.exports.default = immer259module.exports.setAutoFreeze = setAutoFreeze