immer.js
This file
Path
immer.js
241 lines · 8.0 KiB · JavaScript
Last changed by
Merge pull request #33 from mweststrate/fix/32Michel Weststratebefore adoptionfae0957
History of this fileTake it
Merge pull request #15 from mweststrate/feature/freezeMichel Weststratebefore adoption0d24494
lines 1–3why, one step back1"use strict"2// @ts-check3Merge pull request #22 from mweststrate/feature/es5Michel Weststratebefore adoption4165abb
lines 4–8why, one step back4if (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 )8Merge pull request #14 from benbraou/issue10Michel Weststratebefore adoptione775cca
lines 9–14why, one step back9/**10 * @typedef {Object} RevocableProxy11 * @property {any} proxy12 * @property {Function} revoke13 */14Merge pull request #15 from mweststrate/feature/freezeMichel Weststratebefore adoption0d24494
line 15why, one step back15const IMMER_PROXY = Symbol("immer-proxy") // TODO: create per closure, to avoid sharing proxies between multiple immer versionMore repo setupMichel Weststratebefore adoption1637393
line 16why, one step back16Merge pull request #15 from mweststrate/feature/freezeMichel Weststratebefore adoption0d24494
lines 17–19why, one step back17// This property indicates that the current object is cloned for another object,18// to make sure the proxy of a frozen object is writeable19const CLONE_TARGET = Symbol("immer-clone-target")Fixed bug, wrote readmeMichel Weststratebefore adoption1b8a694
line 20why, one step back20Merge pull request #15 from mweststrate/feature/freezeMichel Weststratebefore adoption0d24494
lines 21–22why, one step back21let autoFreeze = true22More repo setupMichel Weststratebefore adoption1637393
line 23why, one step back23/**Merge pull request #9 from benbraou/typosMichel Weststratebefore adoptionae0182f
line 24why, one step back24 * Immer takes a state, and runs a function against it.More repo setupMichel Weststratebefore adoption1637393
lines 25–33why, one step back25 * That function can freely mutate the state, as it will create copies-on-write.26 * This means that the original state will stay unchanged, and once the function finishes, the modified state is returned27 *28 * @export29 * @param {any} baseState - the state to start with30 * @param {Function} thunk - function that receives a proxy of the base state as first argument and which can be freely modified31 * @returns {any} a new state, or the base state if nothing was modified32 */33function immer(baseState, thunk) {Merge pull request #14 from benbraou/issue10Michel Weststratebefore adoptione775cca
lines 34–38why, one step back34 /**35 * Maps baseState objects to revocable proxies36 * @type {Map<Object,RevocableProxy>}37 */38 const revocableProxies = new Map()Code cleanupMichel Weststratebefore adoption2b2d0cb
line 39why, one step back39 // Maps baseState objects to their copiesMerge pull request #14 from benbraou/issue10Michel Weststratebefore adoptione775cca
line 40why, one step back40More repo setupMichel Weststratebefore adoption1637393
lines 41–44why, one step back41 const copies = new Map()4243 const objectTraps = {44 get(target, prop) {Merge pull request #15 from mweststrate/feature/freezeMichel Weststratebefore adoption0d24494
line 45why, one step back45 if (prop === IMMER_PROXY) return targetCode cleanupMichel Weststratebefore adoption2b2d0cb
line 46why, one step back46 return createProxy(getCurrentSource(target)[prop])More repo setupMichel Weststratebefore adoption1637393
lines 47–54why, one step back47 },48 has(target, prop) {49 return prop in getCurrentSource(target)50 },51 ownKeys(target) {52 return Reflect.ownKeys(getCurrentSource(target))53 },54 set(target, prop, value) {Code cleanupMichel Weststratebefore adoption2b2d0cb
lines 55–56why, one step back55 const current = createProxy(getCurrentSource(target)[prop])56 const newValue = createProxy(value)More repo setupMichel Weststratebefore adoption1637393
line 57why, one step back57 if (current !== newValue) {Add support for arraysMichel Weststratebefore adoptiond3696cb
line 58why, one step back58 const copy = getOrCreateCopy(target)Merge branch 'Gregjarvez-master'Michel Weststratebefore adoptiona151fed
line 59why, one step back59 copy[prop] = isProxy(newValue)Merge pull request #15 from mweststrate/feature/freezeMichel Weststratebefore adoption0d24494
line 60why, one step back60 ? newValue[IMMER_PROXY]Merge branch 'Gregjarvez-master'Michel Weststratebefore adoptiona151fed
line 61why, one step back61 : newValueMore repo setupMichel Weststratebefore adoption1637393
lines 62–65why, one step back62 }63 return true64 },65 deleteProperty(target, property) {Add support for arraysMichel Weststratebefore adoptiond3696cb
line 66why, one step back66 const copy = getOrCreateCopy(target)More repo setupMichel Weststratebefore adoption1637393
lines 67–68why, one step back67 delete copy[property]68 return trueMerge pull request #33 from mweststrate/fix/32Michel Weststratebefore adoptionfae0957
lines 69–81why, one step back69 },70 getOwnPropertyDescriptor(target, prop) {71 return Reflect.getOwnPropertyDescriptor(72 getCurrentSource(target),73 prop74 )75 },76 defineProperty(target, property, descriptor) {77 Object.defineProperty(getOrCreateCopy(target), property, descriptor)78 return true79 },80 setPrototypeOf() {81 throw new Error("Don't even try this...")No trailing commas, might break babel, fixes #21Michel Weststratebefore adoption2a1da31
line 82why, one step back82 }More repo setupMichel Weststratebefore adoption1637393
lines 83–84why, one step back83 }84Code cleanupMichel Weststratebefore adoption2b2d0cb
lines 85–87why, one step back85 // creates a copy for a base object if there ain't one86 function getOrCreateCopy(base) {87 let copy = copies.get(base)Merge pull request #15 from mweststrate/feature/freezeMichel Weststratebefore adoption0d24494
lines 88–93why, one step back88 if (copy) return copy89 const cloneTarget = base[CLONE_TARGET]90 if (cloneTarget) {91 // base is a clone already (source was frozen), no need to create addtional copy92 copies.set(cloneTarget, base)93 return baseMore repo setupMichel Weststratebefore adoption1637393
line 94why, one step back94 }Merge pull request #15 from mweststrate/feature/freezeMichel Weststratebefore adoption0d24494
lines 95–97why, one step back95 // create a fresh copy96 copy = Array.isArray(base) ? base.slice() : Object.assign({}, base)97 copies.set(base, copy)More repo setupMichel Weststratebefore adoption1637393
lines 98–100why, one step back98 return copy99 }100Merge pull request #9 from benbraou/typosMichel Weststratebefore adoptionae0182f
line 101why, one step back101 // returns the current source of truth for a base objectCode cleanupMichel Weststratebefore adoption2b2d0cb
lines 102–104why, one step back102 function getCurrentSource(base) {103 const copy = copies.get(base)104 return copy || baseMore repo setupMichel Weststratebefore adoption1637393
line 105why, one step back105 }Merge pull request #15 from mweststrate/feature/freezeMichel Weststratebefore adoption0d24494
line 106why, one step back106Code cleanupMichel Weststratebefore adoption2b2d0cb
lines 107–109why, one step back107 // creates a proxy for plain objects / arrays108 function createProxy(base) {109 if (isPlainObject(base) || Array.isArray(base)) {Fixed bug, wrote readmeMichel Weststratebefore adoption1b8a694
line 110why, one step back110 if (isProxy(base)) return base // avoid double wrappingMerge pull request #15 from mweststrate/feature/freezeMichel Weststratebefore adoption0d24494
lines 111–121why, one step back111 if (revocableProxies.has(base))112 return revocableProxies.get(base).proxy113 let proxyTarget114 // special case, if the base tree is frozen, we cannot modify it's proxy it in strict mode, clone first.115 if (Object.isFrozen(base)) {116 proxyTarget = Array.isArray(base)117 ? base.slice()118 : Object.assign({}, base)119 Object.defineProperty(proxyTarget, CLONE_TARGET, {120 enumerable: false,121 value: base,No trailing commas, might break babel, fixes #21Michel Weststratebefore adoption2a1da31
line 122why, one step back122 configurable: trueMerge pull request #15 from mweststrate/feature/freezeMichel Weststratebefore adoption0d24494
lines 123–128why, one step back123 })124 } else {125 proxyTarget = base126 }127 // create the proxy128 const revocableProxy = Proxy.revocable(proxyTarget, objectTraps)Merge pull request #14 from benbraou/issue10Michel Weststratebefore adoptione775cca
lines 129–130why, one step back129 revocableProxies.set(base, revocableProxy)130 return revocableProxy.proxyCode cleanupMichel Weststratebefore adoption2b2d0cb
lines 131–132why, one step back131 }132 return baseMore repo setupMichel Weststratebefore adoption1637393
lines 133–134why, one step back133 }134Code cleanupMichel Weststratebefore adoption2b2d0cb
lines 135–137why, one step back135 // checks if the given base object has modifications, either because it is modified, or136 // because one of it's children is137 function hasChanges(base) {Merge pull request #14 from benbraou/issue10Michel Weststratebefore adoptione775cca
line 138why, one step back138 const proxy = revocableProxies.get(base)More repo setupMichel Weststratebefore adoption1637393
lines 139–143why, one step back139 if (!proxy) return false // nobody did read this object140 if (copies.has(base)) return true // a copy was created, so there are changes141 // look deeper142 const keys = Object.keys(base)143 for (let i = 0; i < keys.length; i++) {Fixed bug, wrote readmeMichel Weststratebefore adoption1b8a694
line 144why, one step back144 const value = base[keys[i]]Merge branch 'Gregjarvez-master'Michel Weststratebefore adoptiona151fed
lines 145–149why, one step back145 if (146 (Array.isArray(value) || isPlainObject(value)) &&147 hasChanges(value)148 )149 return trueMore repo setupMichel Weststratebefore adoption1637393
lines 150–153why, one step back150 }151 return false152 }153Code cleanupMichel Weststratebefore adoption2b2d0cb
lines 154–160why, one step back154 // given a base object, returns it if unmodified, or return the changed cloned if modified155 function finalize(base) {156 if (isPlainObject(base)) return finalizeObject(base)157 if (Array.isArray(base)) return finalizeArray(base)158 return base159 }160More repo setupMichel Weststratebefore adoption1637393
line 161why, one step back161 function finalizeObject(thing) {Code cleanupMichel Weststratebefore adoption2b2d0cb
line 162why, one step back162 if (!hasChanges(thing)) return thingMerge pull request #15 from mweststrate/feature/freezeMichel Weststratebefore adoption0d24494
line 163why, one step back163 const copy = getOrCreateCopy(thing) // TODO: getOrCreate is weird here..More repo setupMichel Weststratebefore adoption1637393
line 164why, one step back164 Object.keys(copy).forEach(prop => {Code cleanupMichel Weststratebefore adoption2b2d0cb
line 165why, one step back165 copy[prop] = finalize(copy[prop])Add support for arraysMichel Weststratebefore adoptiond3696cb
line 166why, one step back166 })Merge pull request #15 from mweststrate/feature/freezeMichel Weststratebefore adoption0d24494
lines 167–168why, one step back167 delete copy[CLONE_TARGET]168 return freeze(copy)Add support for arraysMichel Weststratebefore adoptiond3696cb
lines 169–171why, one step back169 }170171 function finalizeArray(thing) {Code cleanupMichel Weststratebefore adoption2b2d0cb
line 172why, one step back172 if (!hasChanges(thing)) return thingMerge pull request #15 from mweststrate/feature/freezeMichel Weststratebefore adoption0d24494
line 173why, one step back173 const copy = getOrCreateCopy(thing) // TODO: getOrCreate is weird here..Add support for arraysMichel Weststratebefore adoptiond3696cb
line 174why, one step back174 copy.forEach((value, index) => {Code cleanupMichel Weststratebefore adoption2b2d0cb
line 175why, one step back175 copy[index] = finalize(copy[index])More repo setupMichel Weststratebefore adoption1637393
line 176why, one step back176 })Merge pull request #15 from mweststrate/feature/freezeMichel Weststratebefore adoption0d24494
lines 177–178why, one step back177 delete copy[CLONE_TARGET]178 return freeze(copy)More repo setupMichel Weststratebefore adoption1637393
lines 179–180why, one step back179 }180Code cleanupMichel Weststratebefore adoption2b2d0cb
lines 181–183why, one step back181 // create proxy for root182 const rootClone = createProxy(baseState)183 // execute the thunkMerge branch 'Gregjarvez-master'Michel Weststratebefore adoptiona151fed
lines 184–187why, one step back184 const maybeVoidReturn = thunk(rootClone)185 //values either than undefined will trigger warning;186 !Object.is(maybeVoidReturn, undefined) &&187 console.warn(Merge pull request #21 from sallyhill/patch-1Michel Weststratebefore adoptionc8718e7
line 188why, one step back188 `Immer callback expects no return value. However ${typeof maybeVoidReturn} was returned`Merge branch 'Gregjarvez-master'Michel Weststratebefore adoptiona151fed
line 189why, one step back189 )Added performance measurements, fixes #6Michel Weststratebefore adoption553299f
line 190why, one step back190 // console.log(`proxies: ${revocableProxies.size}, copies: ${copies.size}`)Merge pull request #14 from benbraou/issue10Michel Weststratebefore adoptione775cca
lines 191–192why, one step back191 // revoke all proxies192 revoke(revocableProxies)Code cleanupMichel Weststratebefore adoption2b2d0cb
lines 193–194why, one step back193 // and finalize the modified proxy194 return finalize(baseState)Merge pull request #14 from benbraou/issue10Michel Weststratebefore adoptione775cca
lines 195–198why, one step back195}196197/**198 * Revoke all the proxies stored in the revocableProxies mapMerge pull request #15 from mweststrate/feature/freezeMichel Weststratebefore adoption0d24494
line 199why, one step back199 *Merge pull request #14 from benbraou/issue10Michel Weststratebefore adoptione775cca
lines 200–201why, one step back200 * @param {Map<Object,RevocableProxy>} revocableProxies201 */Merge pull request #15 from mweststrate/feature/freezeMichel Weststratebefore adoption0d24494
line 202why, one step back202function revoke(revocableProxies) {Merge pull request #14 from benbraou/issue10Michel Weststratebefore adoptione775cca
lines 203–205why, one step back203 for (var revocableProxy of revocableProxies.values()) {204 revocableProxy.revoke()205 }More repo setupMichel Weststratebefore adoption1637393
lines 206–211why, one step back206}207208function isPlainObject(value) {209 if (value === null || typeof value !== "object") return false210 const proto = Object.getPrototypeOf(value)211 return proto === Object.prototype || proto === nullFixed bug, wrote readmeMichel Weststratebefore adoption1b8a694
lines 212–214why, one step back212}213214function isProxy(value) {Merge pull request #15 from mweststrate/feature/freezeMichel Weststratebefore adoption0d24494
line 215why, one step back215 return !!value && !!value[IMMER_PROXY]More repo setupMichel Weststratebefore adoption1637393
lines 216–217why, one step back216}217Merge pull request #15 from mweststrate/feature/freezeMichel Weststratebefore adoption0d24494
lines 218–237why, one step back218function freeze(value) {219 if (autoFreeze) {220 Object.freeze(value)221 }222 return value223}224225/**226 * Automatically freezes any state trees generated by immer.227 * This protects against accidental modifications of the state tree outside of an immer function.228 * This comes with a performance impact, so it is recommended to disable this option in production.229 * It is by default enabled.230 *231 * @returns {void}232 */233function setAutoFreeze(enableAutoFreeze) {234 autoFreeze = enableAutoFreeze235}236237Object.defineProperty(exports, "__esModule", {No trailing commas, might break babel, fixes #21Michel Weststratebefore adoption2a1da31
line 238why, one step back238 value: trueMerge pull request #15 from mweststrate/feature/freezeMichel Weststratebefore adoption0d24494
lines 239–241why, one step back239})240module.exports.default = immer241module.exports.setAutoFreeze = setAutoFreeze