immer.js
This file
Path
immer.js
218 lines · 7.2 KiB · JavaScript
Last changed by
Fixed merge issueMichel Weststratebefore adoption53a6f87
History of this fileTake it
Added support for frozen trees, and automatically freeze generated treesMichel Weststratebefore adoptionab8987f
line 1why, one step back1"use strict"More repo setupMichel Weststratebefore adoption1637393
lines 2–3why, one step back2// @ts-check3Merge branch 'master' into feature/freezeMichel Weststratebefore adoptionf08403a
lines 4–9why, one step back4/**5 * @typedef {Object} RevocableProxy6 * @property {any} proxy7 * @property {Function} revoke8 */9Added support for frozen trees, and automatically freeze generated treesMichel Weststratebefore adoptionab8987f
line 10why, one step back10const IMMER_PROXY = Symbol("immer-proxy") // TODO: create per closure, to avoid sharing proxies between multiple immer versionFixed bug, wrote readmeMichel Weststratebefore adoption1b8a694
line 11why, one step back11Added support for frozen trees, and automatically freeze generated treesMichel Weststratebefore adoptionab8987f
lines 12–17why, one step back12// This property indicates that the current object is cloned for another object,13// to make sure the proxy of a frozen object is writeable14const CLONE_TARGET = Symbol("immer-clone-target")1516let autoFreeze = true17More repo setupMichel Weststratebefore adoption1637393
line 18why, one step back18/**Merge pull request #9 from benbraou/typosMichel Weststratebefore adoptionae0182f
line 19why, one step back19 * Immer takes a state, and runs a function against it.More repo setupMichel Weststratebefore adoption1637393
lines 20–28why, one step back20 * 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 */28function immer(baseState, thunk) {Merge branch 'master' into feature/freezeMichel Weststratebefore adoptionf08403a
lines 29–33why, one step back29 /**30 * Maps baseState objects to revocable proxies31 * @type {Map<Object,RevocableProxy>}32 */33 const revocableProxies = new Map()Code cleanupMichel Weststratebefore adoption2b2d0cb
line 34why, one step back34 // Maps baseState objects to their copiesMerge branch 'master' into feature/freezeMichel Weststratebefore adoptionf08403a
line 35why, one step back35More repo setupMichel Weststratebefore adoption1637393
lines 36–39why, one step back36 const copies = new Map()3738 const objectTraps = {39 get(target, prop) {Added support for frozen trees, and automatically freeze generated treesMichel Weststratebefore adoptionab8987f
line 40why, one step back40 if (prop === IMMER_PROXY) return targetCode cleanupMichel Weststratebefore adoption2b2d0cb
line 41why, one step back41 return createProxy(getCurrentSource(target)[prop])More repo setupMichel Weststratebefore adoption1637393
lines 42–49why, one step back42 },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) {Code cleanupMichel Weststratebefore adoption2b2d0cb
lines 50–51why, one step back50 const current = createProxy(getCurrentSource(target)[prop])51 const newValue = createProxy(value)More repo setupMichel Weststratebefore adoption1637393
line 52why, one step back52 if (current !== newValue) {Add support for arraysMichel Weststratebefore adoptiond3696cb
line 53why, one step back53 const copy = getOrCreateCopy(target)Merge branch 'master' into feature/freezeMichel Weststratebefore adoptionf08403a
lines 54–56why, one step back54 copy[prop] = isProxy(newValue)55 ? newValue[IMMER_PROXY]56 : newValueMore repo setupMichel Weststratebefore adoption1637393
lines 57–60why, one step back57 }58 return true59 },60 deleteProperty(target, property) {Add support for arraysMichel Weststratebefore adoptiond3696cb
line 61why, one step back61 const copy = getOrCreateCopy(target)More repo setupMichel Weststratebefore adoption1637393
lines 62–63why, one step back62 delete copy[property]63 return trueMerge branch 'master' into feature/freezeMichel Weststratebefore adoptionf08403a
line 64why, one step back64 },More repo setupMichel Weststratebefore adoption1637393
lines 65–66why, one step back65 }66Code cleanupMichel Weststratebefore adoption2b2d0cb
lines 67–69why, one step back67 // creates a copy for a base object if there ain't one68 function getOrCreateCopy(base) {69 let copy = copies.get(base)Added support for frozen trees, and automatically freeze generated treesMichel Weststratebefore adoptionab8987f
lines 70–75why, one step back70 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 baseMore repo setupMichel Weststratebefore adoption1637393
line 76why, one step back76 }Added support for frozen trees, and automatically freeze generated treesMichel Weststratebefore adoptionab8987f
lines 77–79why, one step back77 // create a fresh copy78 copy = Array.isArray(base) ? base.slice() : Object.assign({}, base)79 copies.set(base, copy)More repo setupMichel Weststratebefore adoption1637393
lines 80–82why, one step back80 return copy81 }82Merge pull request #9 from benbraou/typosMichel Weststratebefore adoptionae0182f
line 83why, one step back83 // returns the current source of truth for a base objectCode cleanupMichel Weststratebefore adoption2b2d0cb
lines 84–86why, one step back84 function getCurrentSource(base) {85 const copy = copies.get(base)86 return copy || baseMore repo setupMichel Weststratebefore adoption1637393
lines 87–88why, one step back87 }88Code cleanupMichel Weststratebefore adoption2b2d0cb
lines 89–91why, one step back89 // creates a proxy for plain objects / arrays90 function createProxy(base) {91 if (isPlainObject(base) || Array.isArray(base)) {Fixed bug, wrote readmeMichel Weststratebefore adoption1b8a694
line 92why, one step back92 if (isProxy(base)) return base // avoid double wrappingMerge branch 'master' into feature/freezeMichel Weststratebefore adoptionf08403a
lines 93–94why, one step back93 if (revocableProxies.has(base))94 return revocableProxies.get(base).proxyAdded support for frozen trees, and automatically freeze generated treesMichel Weststratebefore adoptionab8987f
lines 95–97why, one step back95 let proxyTarget = base96 // special case, if the base tree is frozen, we cannot modify it's proxy it in strict mode, clone first.97 if (Object.isFrozen(proxyTarget)) {Merge branch 'master' into feature/freezeMichel Weststratebefore adoptionf08403a
lines 98–100why, one step back98 proxyTarget = Array.isArray(proxyTarget)99 ? proxyTarget.slice()100 : {...proxyTarget}Added support for frozen trees, and automatically freeze generated treesMichel Weststratebefore adoptionab8987f
lines 101–103why, one step back101 Object.defineProperty(proxyTarget, CLONE_TARGET, {102 enumerable: false,103 value: base,Merge branch 'master' into feature/freezeMichel Weststratebefore adoptionf08403a
line 104why, one step back104 configurable: true,Added support for frozen trees, and automatically freeze generated treesMichel Weststratebefore adoptionab8987f
lines 105–107why, one step back105 })106 }107 // create the proxyFixed merge issueMichel Weststratebefore adoption53a6f87
line 108why, one step back108 const revocableProxy = Proxy.revocable(proxyTarget, objectTraps)Merge branch 'master' into feature/freezeMichel Weststratebefore adoptionf08403a
lines 109–110why, one step back109 revocableProxies.set(base, revocableProxy)110 return revocableProxy.proxyCode cleanupMichel Weststratebefore adoption2b2d0cb
lines 111–112why, one step back111 }112 return baseMore repo setupMichel Weststratebefore adoption1637393
lines 113–114why, one step back113 }114Code cleanupMichel Weststratebefore adoption2b2d0cb
lines 115–117why, one step back115 // checks if the given base object has modifications, either because it is modified, or116 // because one of it's children is117 function hasChanges(base) {Merge branch 'master' into feature/freezeMichel Weststratebefore adoptionf08403a
line 118why, one step back118 const proxy = revocableProxies.get(base)More repo setupMichel Weststratebefore adoption1637393
lines 119–123why, one step back119 if (!proxy) return false // nobody did read this object120 if (copies.has(base)) return true // a copy was created, so there are changes121 // look deeper122 const keys = Object.keys(base)123 for (let i = 0; i < keys.length; i++) {Fixed bug, wrote readmeMichel Weststratebefore adoption1b8a694
line 124why, one step back124 const value = base[keys[i]]Merge branch 'master' into feature/freezeMichel Weststratebefore adoptionf08403a
lines 125–129why, one step back125 if (126 (Array.isArray(value) || isPlainObject(value)) &&127 hasChanges(value)128 )129 return trueMore repo setupMichel Weststratebefore adoption1637393
lines 130–133why, one step back130 }131 return false132 }133Code cleanupMichel Weststratebefore adoption2b2d0cb
lines 134–140why, one step back134 // given a base object, returns it if unmodified, or return the changed cloned if modified135 function finalize(base) {136 if (isPlainObject(base)) return finalizeObject(base)137 if (Array.isArray(base)) return finalizeArray(base)138 return base139 }140More repo setupMichel Weststratebefore adoption1637393
line 141why, one step back141 function finalizeObject(thing) {Code cleanupMichel Weststratebefore adoption2b2d0cb
line 142why, one step back142 if (!hasChanges(thing)) return thingAdded support for frozen trees, and automatically freeze generated treesMichel Weststratebefore adoptionab8987f
line 143why, one step back143 const copy = getOrCreateCopy(thing) // TODO: getOrCreate is weird here..More repo setupMichel Weststratebefore adoption1637393
line 144why, one step back144 Object.keys(copy).forEach(prop => {Code cleanupMichel Weststratebefore adoption2b2d0cb
line 145why, one step back145 copy[prop] = finalize(copy[prop])Add support for arraysMichel Weststratebefore adoptiond3696cb
line 146why, one step back146 })Added support for frozen trees, and automatically freeze generated treesMichel Weststratebefore adoptionab8987f
lines 147–148why, one step back147 delete copy[CLONE_TARGET]148 return freeze(copy)Add support for arraysMichel Weststratebefore adoptiond3696cb
lines 149–151why, one step back149 }150151 function finalizeArray(thing) {Code cleanupMichel Weststratebefore adoption2b2d0cb
line 152why, one step back152 if (!hasChanges(thing)) return thingAdded support for frozen trees, and automatically freeze generated treesMichel Weststratebefore adoptionab8987f
line 153why, one step back153 const copy = getOrCreateCopy(thing) // TODO: getOrCreate is weird here..Add support for arraysMichel Weststratebefore adoptiond3696cb
line 154why, one step back154 copy.forEach((value, index) => {Code cleanupMichel Weststratebefore adoption2b2d0cb
line 155why, one step back155 copy[index] = finalize(copy[index])More repo setupMichel Weststratebefore adoption1637393
line 156why, one step back156 })Added support for frozen trees, and automatically freeze generated treesMichel Weststratebefore adoptionab8987f
lines 157–158why, one step back157 delete copy[CLONE_TARGET]158 return freeze(copy)More repo setupMichel Weststratebefore adoption1637393
lines 159–160why, one step back159 }160Code cleanupMichel Weststratebefore adoption2b2d0cb
lines 161–163why, one step back161 // create proxy for root162 const rootClone = createProxy(baseState)163 // execute the thunkMerge branch 'master' into feature/freezeMichel Weststratebefore adoptionf08403a
lines 164–171why, one step back164 const maybeVoidReturn = thunk(rootClone)165 //values either than undefined will trigger warning;166 !Object.is(maybeVoidReturn, undefined) &&167 console.warn(168 `Immer callback expects no return value. However ${typeof maybeVoidReturn} was returned`,169 )170 // revoke all proxies171 revoke(revocableProxies)Code cleanupMichel Weststratebefore adoption2b2d0cb
lines 172–173why, one step back172 // and finalize the modified proxy173 return finalize(baseState)More repo setupMichel Weststratebefore adoption1637393
lines 174–175why, one step back174}175Merge branch 'master' into feature/freezeMichel Weststratebefore adoptionf08403a
lines 176–186why, one step back176/**177 * Revoke all the proxies stored in the revocableProxies map178 *179 * @param {Map<Object,RevocableProxy>} revocableProxies180 */181function revoke(revocableProxies) {182 for (var revocableProxy of revocableProxies.values()) {183 revocableProxy.revoke()184 }185}186More repo setupMichel Weststratebefore adoption1637393
lines 187–190why, one step back187function isPlainObject(value) {188 if (value === null || typeof value !== "object") return false189 const proto = Object.getPrototypeOf(value)190 return proto === Object.prototype || proto === nullFixed bug, wrote readmeMichel Weststratebefore adoption1b8a694
lines 191–193why, one step back191}192193function isProxy(value) {Added support for frozen trees, and automatically freeze generated treesMichel Weststratebefore adoptionab8987f
line 194why, one step back194 return !!value && !!value[IMMER_PROXY]More repo setupMichel Weststratebefore adoption1637393
lines 195–196why, one step back195}196Added support for frozen trees, and automatically freeze generated treesMichel Weststratebefore adoptionab8987f
lines 197–213why, one step back197function freeze(value) {198 if (autoFreeze) {199 Object.freeze(value)200 }201 return value202}203204/**205 * Automatically freezes any state trees generated by immer.206 * This protects against accidental modifications of the state tree outside of an immer function.207 * This comes with a performance impact, so it is recommended to disable this option in production.208 * It is by default enabled.209 */210function setAutoFreeze(enableAutoFreeze) {211 autoFreeze = enableAutoFreeze212}213`__esModule` should be non-enumerableMichel Weststratebefore adoption0190958
line 214why, one step back214Object.defineProperty(exports, "__esModule", {Merge branch 'master' into feature/freezeMichel Weststratebefore adoptionf08403a
line 215why, one step back215 value: true,`__esModule` should be non-enumerableMichel Weststratebefore adoption0190958
line 216why, one step back216})Added support for frozen trees, and automatically freeze generated treesMichel Weststratebefore adoptionab8987f
lines 217–218why, one step back217module.exports.default = immer218module.exports.setAutoFreeze = setAutoFreeze