copied implementation
Before adoption: this commit came in with the history the project adopted, so no landing records it.
authored by Michel Weststrate · committed by Michel Weststrate · parent f895e01 · Browse files · 2 files·+224 added−1 removed
This commit
State
Before adoption: this commit came in with the history the project adopted, so no landing records it.
Diff stats
2 files+224 added−1 removed
- other:+224 added−1 removed
Provenance
- Commit
a3924fb- Tree
77449cc- Author
Michel Weststrate <mweststrate@gmail.com>- Committer
Michel Weststrate <mweststrate@gmail.com>- Parent
f895e01
2 files changed+224 added−1 removed
added:immer-es5.js+223 added
1+"use strict"2+// @ts-check3+4+/**5+ * @typedef {Object} RevocableProxy6+ * @property {any} proxy7+ * @property {Function} revoke8+ */9+10+const IMMER_PROXY = Symbol("immer-proxy") // TODO: create per closure, to avoid sharing proxies between multiple immer version11+12+// This property indicates that the current object is cloned for another object,13+// to make sure the proxy of a frozen object is writeable14+const CLONE_TARGET = Symbol("immer-clone-target")15+16+let autoFreeze = true17+18+/**19+ * Immer takes a state, and runs a function against it.20+ * That function can freely mutate the state, as it will create copies-on-write.21+ * This means that the original state will stay unchanged, and once the function finishes, the modified state is returned22+ *23+ * @export24+ * @param {any} baseState - the state to start with25+ * @param {Function} thunk - function that receives a proxy of the base state as first argument and which can be freely modified26+ * @returns {any} a new state, or the base state if nothing was modified27+ */28+function immer(baseState, thunk) {29+ /**30+ * Maps baseState objects to revocable proxies31+ * @type {Map<Object,RevocableProxy>}32+ */33+ const revocableProxies = new Map()34+ // Maps baseState objects to their copies35+36+ const copies = new Map()37+38+ const objectTraps = {39+ get(target, prop) {40+ if (prop === IMMER_PROXY) return target41+ return createProxy(getCurrentSource(target)[prop])42+ },43+ has(target, prop) {44+ return prop in getCurrentSource(target)45+ },46+ ownKeys(target) {47+ return Reflect.ownKeys(getCurrentSource(target))48+ },49+ set(target, prop, value) {50+ const current = createProxy(getCurrentSource(target)[prop])51+ const newValue = createProxy(value)52+ if (current !== newValue) {53+ const copy = getOrCreateCopy(target)54+ copy[prop] = isProxy(newValue)55+ ? newValue[IMMER_PROXY]56+ : newValue57+ }58+ return true59+ },60+ deleteProperty(target, property) {61+ const copy = getOrCreateCopy(target)62+ delete copy[property]63+ return true64+ },65+ }66+67+ // creates a copy for a base object if there ain't one68+ function getOrCreateCopy(base) {69+ let copy = copies.get(base)70+ if (copy) return copy71+ const cloneTarget = base[CLONE_TARGET]72+ if (cloneTarget) {73+ // base is a clone already (source was frozen), no need to create addtional copy74+ copies.set(cloneTarget, base)75+ return base76+ }77+ // create a fresh copy78+ copy = Array.isArray(base) ? base.slice() : Object.assign({}, base)79+ copies.set(base, copy)80+ return copy81+ }82+83+ // returns the current source of truth for a base object84+ function getCurrentSource(base) {85+ const copy = copies.get(base)86+ return copy || base87+ }88+89+ // creates a proxy for plain objects / arrays90+ function createProxy(base) {91+ if (isPlainObject(base) || Array.isArray(base)) {92+ if (isProxy(base)) return base // avoid double wrapping93+ if (revocableProxies.has(base))94+ return revocableProxies.get(base).proxy95+ let proxyTarget96+ // special case, if the base tree is frozen, we cannot modify it's proxy it in strict mode, clone first.97+ if (Object.isFrozen(base)) {98+ proxyTarget = Array.isArray(base)99+ ? base.slice()100+ : Object.assign({}, base)101+ Object.defineProperty(proxyTarget, CLONE_TARGET, {102+ enumerable: false,103+ value: base,104+ configurable: true,105+ })106+ } else {107+ proxyTarget = base108+ }109+ // create the proxy110+ const revocableProxy = Proxy.revocable(proxyTarget, objectTraps)111+ revocableProxies.set(base, revocableProxy)112+ return revocableProxy.proxy113+ }114+ return base115+ }116+117+ // checks if the given base object has modifications, either because it is modified, or118+ // because one of it's children is119+ function hasChanges(base) {120+ const proxy = revocableProxies.get(base)121+ if (!proxy) return false // nobody did read this object122+ if (copies.has(base)) return true // a copy was created, so there are changes123+ // look deeper124+ const keys = Object.keys(base)125+ for (let i = 0; i < keys.length; i++) {126+ const value = base[keys[i]]127+ if (128+ (Array.isArray(value) || isPlainObject(value)) &&129+ hasChanges(value)130+ )131+ return true132+ }133+ return false134+ }135+136+ // given a base object, returns it if unmodified, or return the changed cloned if modified137+ function finalize(base) {138+ if (isPlainObject(base)) return finalizeObject(base)139+ if (Array.isArray(base)) return finalizeArray(base)140+ return base141+ }142+143+ function finalizeObject(thing) {144+ if (!hasChanges(thing)) return thing145+ const copy = getOrCreateCopy(thing) // TODO: getOrCreate is weird here..146+ Object.keys(copy).forEach(prop => {147+ copy[prop] = finalize(copy[prop])148+ })149+ delete copy[CLONE_TARGET]150+ return freeze(copy)151+ }152+153+ function finalizeArray(thing) {154+ if (!hasChanges(thing)) return thing155+ const copy = getOrCreateCopy(thing) // TODO: getOrCreate is weird here..156+ copy.forEach((value, index) => {157+ copy[index] = finalize(copy[index])158+ })159+ delete copy[CLONE_TARGET]160+ return freeze(copy)161+ }162+163+ // create proxy for root164+ const rootClone = createProxy(baseState)165+ // execute the thunk166+ const maybeVoidReturn = thunk(rootClone)167+ //values either than undefined will trigger warning;168+ !Object.is(maybeVoidReturn, undefined) &&169+ console.warn(170+ `Immer callback expects no return value. However ${typeof maybeVoidReturn} was returned`,171+ )172+ // console.log(`proxies: ${revocableProxies.size}, copies: ${copies.size}`)173+ // revoke all proxies174+ revoke(revocableProxies)175+ // and finalize the modified proxy176+ return finalize(baseState)177+}178+179+/**180+ * Revoke all the proxies stored in the revocableProxies map181+ *182+ * @param {Map<Object,RevocableProxy>} revocableProxies183+ */184+function revoke(revocableProxies) {185+ for (var revocableProxy of revocableProxies.values()) {186+ revocableProxy.revoke()187+ }188+}189+190+function isPlainObject(value) {191+ if (value === null || typeof value !== "object") return false192+ const proto = Object.getPrototypeOf(value)193+ return proto === Object.prototype || proto === null194+}195+196+function isProxy(value) {197+ return !!value && !!value[IMMER_PROXY]198+}199+200+function freeze(value) {201+ if (autoFreeze) {202+ Object.freeze(value)203+ }204+ return value205+}206+207+/**208+ * Automatically freezes any state trees generated by immer.209+ * This protects against accidental modifications of the state tree outside of an immer function.210+ * This comes with a performance impact, so it is recommended to disable this option in production.211+ * It is by default enabled.212+ *213+ * @returns {void}214+ */215+function setAutoFreeze(enableAutoFreeze) {216+ autoFreeze = enableAutoFreeze217+}218+219+Object.defineProperty(exports, "__esModule", {220+ value: true,221+})222+module.exports.default = immer223+module.exports.setAutoFreeze = setAutoFreezemodified:package.json+1 added-1 removed
123455678942 unmodified lines{ "name": "immer", "version": "0.1.0", "description": "Create your next immutable state by mutating the current one", "main": "immer.js", "main": "immer-es5.js", "types": "./index.d.ts", "scripts": { "test": "jest", "prettier": "prettier \"*/**/*.js\" --ignore-path ./.prettierignore --write && git add . && git status"42 unmodified lines