immer.js
This file
Path
immer.js
234 lines · 7.7 KiB · JavaScript
Last changed by
improved test setupMichel Weststratebefore adoption6990c33
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 trueimproved test setupMichel Weststratebefore adoption6990c33
lines 69–74why, one step back69 },70 getOwnPropertyDescriptor(target, prop) {71 return Reflect.getOwnPropertyDescriptor(72 getCurrentSource(target),73 prop74 )No trailing commas, might break babel, fixes #21Michel Weststratebefore adoption2a1da31
line 75why, one step back75 }More repo setupMichel Weststratebefore adoption1637393
lines 76–77why, one step back76 }77Code cleanupMichel Weststratebefore adoption2b2d0cb
lines 78–80why, one step back78 // creates a copy for a base object if there ain't one79 function getOrCreateCopy(base) {80 let copy = copies.get(base)Merge pull request #15 from mweststrate/feature/freezeMichel Weststratebefore adoption0d24494
lines 81–86why, one step back81 if (copy) return copy82 const cloneTarget = base[CLONE_TARGET]83 if (cloneTarget) {84 // base is a clone already (source was frozen), no need to create addtional copy85 copies.set(cloneTarget, base)86 return baseMore repo setupMichel Weststratebefore adoption1637393
line 87why, one step back87 }Merge pull request #15 from mweststrate/feature/freezeMichel Weststratebefore adoption0d24494
lines 88–90why, one step back88 // create a fresh copy89 copy = Array.isArray(base) ? base.slice() : Object.assign({}, base)90 copies.set(base, copy)More repo setupMichel Weststratebefore adoption1637393
lines 91–93why, one step back91 return copy92 }93Merge pull request #9 from benbraou/typosMichel Weststratebefore adoptionae0182f
line 94why, one step back94 // returns the current source of truth for a base objectCode cleanupMichel Weststratebefore adoption2b2d0cb
lines 95–97why, one step back95 function getCurrentSource(base) {96 const copy = copies.get(base)97 return copy || baseMore repo setupMichel Weststratebefore adoption1637393
line 98why, one step back98 }Merge pull request #15 from mweststrate/feature/freezeMichel Weststratebefore adoption0d24494
line 99why, one step back99Code cleanupMichel Weststratebefore adoption2b2d0cb
lines 100–102why, one step back100 // creates a proxy for plain objects / arrays101 function createProxy(base) {102 if (isPlainObject(base) || Array.isArray(base)) {Fixed bug, wrote readmeMichel Weststratebefore adoption1b8a694
line 103why, one step back103 if (isProxy(base)) return base // avoid double wrappingMerge pull request #15 from mweststrate/feature/freezeMichel Weststratebefore adoption0d24494
lines 104–114why, one step back104 if (revocableProxies.has(base))105 return revocableProxies.get(base).proxy106 let proxyTarget107 // special case, if the base tree is frozen, we cannot modify it's proxy it in strict mode, clone first.108 if (Object.isFrozen(base)) {109 proxyTarget = Array.isArray(base)110 ? base.slice()111 : Object.assign({}, base)112 Object.defineProperty(proxyTarget, CLONE_TARGET, {113 enumerable: false,114 value: base,No trailing commas, might break babel, fixes #21Michel Weststratebefore adoption2a1da31
line 115why, one step back115 configurable: trueMerge pull request #15 from mweststrate/feature/freezeMichel Weststratebefore adoption0d24494
lines 116–121why, one step back116 })117 } else {118 proxyTarget = base119 }120 // create the proxy121 const revocableProxy = Proxy.revocable(proxyTarget, objectTraps)Merge pull request #14 from benbraou/issue10Michel Weststratebefore adoptione775cca
lines 122–123why, one step back122 revocableProxies.set(base, revocableProxy)123 return revocableProxy.proxyCode cleanupMichel Weststratebefore adoption2b2d0cb
lines 124–125why, one step back124 }125 return baseMore repo setupMichel Weststratebefore adoption1637393
lines 126–127why, one step back126 }127Code cleanupMichel Weststratebefore adoption2b2d0cb
lines 128–130why, one step back128 // checks if the given base object has modifications, either because it is modified, or129 // because one of it's children is130 function hasChanges(base) {Merge pull request #14 from benbraou/issue10Michel Weststratebefore adoptione775cca
line 131why, one step back131 const proxy = revocableProxies.get(base)More repo setupMichel Weststratebefore adoption1637393
lines 132–136why, one step back132 if (!proxy) return false // nobody did read this object133 if (copies.has(base)) return true // a copy was created, so there are changes134 // look deeper135 const keys = Object.keys(base)136 for (let i = 0; i < keys.length; i++) {Fixed bug, wrote readmeMichel Weststratebefore adoption1b8a694
line 137why, one step back137 const value = base[keys[i]]Merge branch 'Gregjarvez-master'Michel Weststratebefore adoptiona151fed
lines 138–142why, one step back138 if (139 (Array.isArray(value) || isPlainObject(value)) &&140 hasChanges(value)141 )142 return trueMore repo setupMichel Weststratebefore adoption1637393
lines 143–146why, one step back143 }144 return false145 }146Code cleanupMichel Weststratebefore adoption2b2d0cb
lines 147–153why, one step back147 // given a base object, returns it if unmodified, or return the changed cloned if modified148 function finalize(base) {149 if (isPlainObject(base)) return finalizeObject(base)150 if (Array.isArray(base)) return finalizeArray(base)151 return base152 }153More repo setupMichel Weststratebefore adoption1637393
line 154why, one step back154 function finalizeObject(thing) {Code cleanupMichel Weststratebefore adoption2b2d0cb
line 155why, one step back155 if (!hasChanges(thing)) return thingMerge pull request #15 from mweststrate/feature/freezeMichel Weststratebefore adoption0d24494
line 156why, one step back156 const copy = getOrCreateCopy(thing) // TODO: getOrCreate is weird here..More repo setupMichel Weststratebefore adoption1637393
line 157why, one step back157 Object.keys(copy).forEach(prop => {Code cleanupMichel Weststratebefore adoption2b2d0cb
line 158why, one step back158 copy[prop] = finalize(copy[prop])Add support for arraysMichel Weststratebefore adoptiond3696cb
line 159why, one step back159 })Merge pull request #15 from mweststrate/feature/freezeMichel Weststratebefore adoption0d24494
lines 160–161why, one step back160 delete copy[CLONE_TARGET]161 return freeze(copy)Add support for arraysMichel Weststratebefore adoptiond3696cb
lines 162–164why, one step back162 }163164 function finalizeArray(thing) {Code cleanupMichel Weststratebefore adoption2b2d0cb
line 165why, one step back165 if (!hasChanges(thing)) return thingMerge pull request #15 from mweststrate/feature/freezeMichel Weststratebefore adoption0d24494
line 166why, one step back166 const copy = getOrCreateCopy(thing) // TODO: getOrCreate is weird here..Add support for arraysMichel Weststratebefore adoptiond3696cb
line 167why, one step back167 copy.forEach((value, index) => {Code cleanupMichel Weststratebefore adoption2b2d0cb
line 168why, one step back168 copy[index] = finalize(copy[index])More repo setupMichel Weststratebefore adoption1637393
line 169why, one step back169 })Merge pull request #15 from mweststrate/feature/freezeMichel Weststratebefore adoption0d24494
lines 170–171why, one step back170 delete copy[CLONE_TARGET]171 return freeze(copy)More repo setupMichel Weststratebefore adoption1637393
lines 172–173why, one step back172 }173Code cleanupMichel Weststratebefore adoption2b2d0cb
lines 174–176why, one step back174 // create proxy for root175 const rootClone = createProxy(baseState)176 // execute the thunkMerge branch 'Gregjarvez-master'Michel Weststratebefore adoptiona151fed
lines 177–180why, one step back177 const maybeVoidReturn = thunk(rootClone)178 //values either than undefined will trigger warning;179 !Object.is(maybeVoidReturn, undefined) &&180 console.warn(Merge pull request #21 from sallyhill/patch-1Michel Weststratebefore adoptionc8718e7
line 181why, one step back181 `Immer callback expects no return value. However ${typeof maybeVoidReturn} was returned`Merge branch 'Gregjarvez-master'Michel Weststratebefore adoptiona151fed
line 182why, one step back182 )Added performance measurements, fixes #6Michel Weststratebefore adoption553299f
line 183why, one step back183 // console.log(`proxies: ${revocableProxies.size}, copies: ${copies.size}`)Merge pull request #14 from benbraou/issue10Michel Weststratebefore adoptione775cca
lines 184–185why, one step back184 // revoke all proxies185 revoke(revocableProxies)Code cleanupMichel Weststratebefore adoption2b2d0cb
lines 186–187why, one step back186 // and finalize the modified proxy187 return finalize(baseState)Merge pull request #14 from benbraou/issue10Michel Weststratebefore adoptione775cca
lines 188–191why, one step back188}189190/**191 * Revoke all the proxies stored in the revocableProxies mapMerge pull request #15 from mweststrate/feature/freezeMichel Weststratebefore adoption0d24494
line 192why, one step back192 *Merge pull request #14 from benbraou/issue10Michel Weststratebefore adoptione775cca
lines 193–194why, one step back193 * @param {Map<Object,RevocableProxy>} revocableProxies194 */Merge pull request #15 from mweststrate/feature/freezeMichel Weststratebefore adoption0d24494
line 195why, one step back195function revoke(revocableProxies) {Merge pull request #14 from benbraou/issue10Michel Weststratebefore adoptione775cca
lines 196–198why, one step back196 for (var revocableProxy of revocableProxies.values()) {197 revocableProxy.revoke()198 }More repo setupMichel Weststratebefore adoption1637393
lines 199–204why, one step back199}200201function isPlainObject(value) {202 if (value === null || typeof value !== "object") return false203 const proto = Object.getPrototypeOf(value)204 return proto === Object.prototype || proto === nullFixed bug, wrote readmeMichel Weststratebefore adoption1b8a694
lines 205–207why, one step back205}206207function isProxy(value) {Merge pull request #15 from mweststrate/feature/freezeMichel Weststratebefore adoption0d24494
line 208why, one step back208 return !!value && !!value[IMMER_PROXY]More repo setupMichel Weststratebefore adoption1637393
lines 209–210why, one step back209}210Merge pull request #15 from mweststrate/feature/freezeMichel Weststratebefore adoption0d24494
lines 211–230why, one step back211function freeze(value) {212 if (autoFreeze) {213 Object.freeze(value)214 }215 return value216}217218/**219 * Automatically freezes any state trees generated by immer.220 * This protects against accidental modifications of the state tree outside of an immer function.221 * This comes with a performance impact, so it is recommended to disable this option in production.222 * It is by default enabled.223 *224 * @returns {void}225 */226function setAutoFreeze(enableAutoFreeze) {227 autoFreeze = enableAutoFreeze228}229230Object.defineProperty(exports, "__esModule", {No trailing commas, might break babel, fixes #21Michel Weststratebefore adoption2a1da31
line 231why, one step back231 value: trueMerge pull request #15 from mweststrate/feature/freezeMichel Weststratebefore adoption0d24494
lines 232–234why, one step back232})233module.exports.default = immer234module.exports.setAutoFreeze = setAutoFreeze