immer.js
This file
Path
immer.js
228 lines · 7.5 KiB · JavaScript
Last changed by
Merge pull request #22 from mweststrate/feature/es5Michel Weststratebefore adoption4165abb
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 trueNo trailing commas, might break babel, fixes #21Michel Weststratebefore adoption2a1da31
line 69why, one step back69 }More repo setupMichel Weststratebefore adoption1637393
lines 70–71why, one step back70 }71Code cleanupMichel Weststratebefore adoption2b2d0cb
lines 72–74why, one step back72 // creates a copy for a base object if there ain't one73 function getOrCreateCopy(base) {74 let copy = copies.get(base)Merge pull request #15 from mweststrate/feature/freezeMichel Weststratebefore adoption0d24494
lines 75–80why, one step back75 if (copy) return copy76 const cloneTarget = base[CLONE_TARGET]77 if (cloneTarget) {78 // base is a clone already (source was frozen), no need to create addtional copy79 copies.set(cloneTarget, base)80 return baseMore repo setupMichel Weststratebefore adoption1637393
line 81why, one step back81 }Merge pull request #15 from mweststrate/feature/freezeMichel Weststratebefore adoption0d24494
lines 82–84why, one step back82 // create a fresh copy83 copy = Array.isArray(base) ? base.slice() : Object.assign({}, base)84 copies.set(base, copy)More repo setupMichel Weststratebefore adoption1637393
lines 85–87why, one step back85 return copy86 }87Merge pull request #9 from benbraou/typosMichel Weststratebefore adoptionae0182f
line 88why, one step back88 // returns the current source of truth for a base objectCode cleanupMichel Weststratebefore adoption2b2d0cb
lines 89–91why, one step back89 function getCurrentSource(base) {90 const copy = copies.get(base)91 return copy || baseMore repo setupMichel Weststratebefore adoption1637393
line 92why, one step back92 }Merge pull request #15 from mweststrate/feature/freezeMichel Weststratebefore adoption0d24494
line 93why, one step back93Code cleanupMichel Weststratebefore adoption2b2d0cb
lines 94–96why, one step back94 // creates a proxy for plain objects / arrays95 function createProxy(base) {96 if (isPlainObject(base) || Array.isArray(base)) {Fixed bug, wrote readmeMichel Weststratebefore adoption1b8a694
line 97why, one step back97 if (isProxy(base)) return base // avoid double wrappingMerge pull request #15 from mweststrate/feature/freezeMichel Weststratebefore adoption0d24494
lines 98–108why, one step back98 if (revocableProxies.has(base))99 return revocableProxies.get(base).proxy100 let proxyTarget101 // special case, if the base tree is frozen, we cannot modify it's proxy it in strict mode, clone first.102 if (Object.isFrozen(base)) {103 proxyTarget = Array.isArray(base)104 ? base.slice()105 : Object.assign({}, base)106 Object.defineProperty(proxyTarget, CLONE_TARGET, {107 enumerable: false,108 value: base,No trailing commas, might break babel, fixes #21Michel Weststratebefore adoption2a1da31
line 109why, one step back109 configurable: trueMerge pull request #15 from mweststrate/feature/freezeMichel Weststratebefore adoption0d24494
lines 110–115why, one step back110 })111 } else {112 proxyTarget = base113 }114 // create the proxy115 const revocableProxy = Proxy.revocable(proxyTarget, objectTraps)Merge pull request #14 from benbraou/issue10Michel Weststratebefore adoptione775cca
lines 116–117why, one step back116 revocableProxies.set(base, revocableProxy)117 return revocableProxy.proxyCode cleanupMichel Weststratebefore adoption2b2d0cb
lines 118–119why, one step back118 }119 return baseMore repo setupMichel Weststratebefore adoption1637393
lines 120–121why, one step back120 }121Code cleanupMichel Weststratebefore adoption2b2d0cb
lines 122–124why, one step back122 // checks if the given base object has modifications, either because it is modified, or123 // because one of it's children is124 function hasChanges(base) {Merge pull request #14 from benbraou/issue10Michel Weststratebefore adoptione775cca
line 125why, one step back125 const proxy = revocableProxies.get(base)More repo setupMichel Weststratebefore adoption1637393
lines 126–130why, one step back126 if (!proxy) return false // nobody did read this object127 if (copies.has(base)) return true // a copy was created, so there are changes128 // look deeper129 const keys = Object.keys(base)130 for (let i = 0; i < keys.length; i++) {Fixed bug, wrote readmeMichel Weststratebefore adoption1b8a694
line 131why, one step back131 const value = base[keys[i]]Merge branch 'Gregjarvez-master'Michel Weststratebefore adoptiona151fed
lines 132–136why, one step back132 if (133 (Array.isArray(value) || isPlainObject(value)) &&134 hasChanges(value)135 )136 return trueMore repo setupMichel Weststratebefore adoption1637393
lines 137–140why, one step back137 }138 return false139 }140Code cleanupMichel Weststratebefore adoption2b2d0cb
lines 141–147why, one step back141 // given a base object, returns it if unmodified, or return the changed cloned if modified142 function finalize(base) {143 if (isPlainObject(base)) return finalizeObject(base)144 if (Array.isArray(base)) return finalizeArray(base)145 return base146 }147More repo setupMichel Weststratebefore adoption1637393
line 148why, one step back148 function finalizeObject(thing) {Code cleanupMichel Weststratebefore adoption2b2d0cb
line 149why, one step back149 if (!hasChanges(thing)) return thingMerge pull request #15 from mweststrate/feature/freezeMichel Weststratebefore adoption0d24494
line 150why, one step back150 const copy = getOrCreateCopy(thing) // TODO: getOrCreate is weird here..More repo setupMichel Weststratebefore adoption1637393
line 151why, one step back151 Object.keys(copy).forEach(prop => {Code cleanupMichel Weststratebefore adoption2b2d0cb
line 152why, one step back152 copy[prop] = finalize(copy[prop])Add support for arraysMichel Weststratebefore adoptiond3696cb
line 153why, one step back153 })Merge pull request #15 from mweststrate/feature/freezeMichel Weststratebefore adoption0d24494
lines 154–155why, one step back154 delete copy[CLONE_TARGET]155 return freeze(copy)Add support for arraysMichel Weststratebefore adoptiond3696cb
lines 156–158why, one step back156 }157158 function finalizeArray(thing) {Code cleanupMichel Weststratebefore adoption2b2d0cb
line 159why, one step back159 if (!hasChanges(thing)) return thingMerge pull request #15 from mweststrate/feature/freezeMichel Weststratebefore adoption0d24494
line 160why, one step back160 const copy = getOrCreateCopy(thing) // TODO: getOrCreate is weird here..Add support for arraysMichel Weststratebefore adoptiond3696cb
line 161why, one step back161 copy.forEach((value, index) => {Code cleanupMichel Weststratebefore adoption2b2d0cb
line 162why, one step back162 copy[index] = finalize(copy[index])More repo setupMichel Weststratebefore adoption1637393
line 163why, one step back163 })Merge pull request #15 from mweststrate/feature/freezeMichel Weststratebefore adoption0d24494
lines 164–165why, one step back164 delete copy[CLONE_TARGET]165 return freeze(copy)More repo setupMichel Weststratebefore adoption1637393
lines 166–167why, one step back166 }167Code cleanupMichel Weststratebefore adoption2b2d0cb
lines 168–170why, one step back168 // create proxy for root169 const rootClone = createProxy(baseState)170 // execute the thunkMerge branch 'Gregjarvez-master'Michel Weststratebefore adoptiona151fed
lines 171–174why, one step back171 const maybeVoidReturn = thunk(rootClone)172 //values either than undefined will trigger warning;173 !Object.is(maybeVoidReturn, undefined) &&174 console.warn(Merge pull request #21 from sallyhill/patch-1Michel Weststratebefore adoptionc8718e7
line 175why, one step back175 `Immer callback expects no return value. However ${typeof maybeVoidReturn} was returned`Merge branch 'Gregjarvez-master'Michel Weststratebefore adoptiona151fed
line 176why, one step back176 )Added performance measurements, fixes #6Michel Weststratebefore adoption553299f
line 177why, one step back177 // console.log(`proxies: ${revocableProxies.size}, copies: ${copies.size}`)Merge pull request #14 from benbraou/issue10Michel Weststratebefore adoptione775cca
lines 178–179why, one step back178 // revoke all proxies179 revoke(revocableProxies)Code cleanupMichel Weststratebefore adoption2b2d0cb
lines 180–181why, one step back180 // and finalize the modified proxy181 return finalize(baseState)Merge pull request #14 from benbraou/issue10Michel Weststratebefore adoptione775cca
lines 182–185why, one step back182}183184/**185 * Revoke all the proxies stored in the revocableProxies mapMerge pull request #15 from mweststrate/feature/freezeMichel Weststratebefore adoption0d24494
line 186why, one step back186 *Merge pull request #14 from benbraou/issue10Michel Weststratebefore adoptione775cca
lines 187–188why, one step back187 * @param {Map<Object,RevocableProxy>} revocableProxies188 */Merge pull request #15 from mweststrate/feature/freezeMichel Weststratebefore adoption0d24494
line 189why, one step back189function revoke(revocableProxies) {Merge pull request #14 from benbraou/issue10Michel Weststratebefore adoptione775cca
lines 190–192why, one step back190 for (var revocableProxy of revocableProxies.values()) {191 revocableProxy.revoke()192 }More repo setupMichel Weststratebefore adoption1637393
lines 193–198why, one step back193}194195function isPlainObject(value) {196 if (value === null || typeof value !== "object") return false197 const proto = Object.getPrototypeOf(value)198 return proto === Object.prototype || proto === nullFixed bug, wrote readmeMichel Weststratebefore adoption1b8a694
lines 199–201why, one step back199}200201function isProxy(value) {Merge pull request #15 from mweststrate/feature/freezeMichel Weststratebefore adoption0d24494
line 202why, one step back202 return !!value && !!value[IMMER_PROXY]More repo setupMichel Weststratebefore adoption1637393
lines 203–204why, one step back203}204Merge pull request #15 from mweststrate/feature/freezeMichel Weststratebefore adoption0d24494
lines 205–224why, one step back205function freeze(value) {206 if (autoFreeze) {207 Object.freeze(value)208 }209 return value210}211212/**213 * Automatically freezes any state trees generated by immer.214 * This protects against accidental modifications of the state tree outside of an immer function.215 * This comes with a performance impact, so it is recommended to disable this option in production.216 * It is by default enabled.217 *218 * @returns {void}219 */220function setAutoFreeze(enableAutoFreeze) {221 autoFreeze = enableAutoFreeze222}223224Object.defineProperty(exports, "__esModule", {No trailing commas, might break babel, fixes #21Michel Weststratebefore adoption2a1da31
line 225why, one step back225 value: trueMerge pull request #15 from mweststrate/feature/freezeMichel Weststratebefore adoption0d24494
lines 226–228why, one step back226})227module.exports.default = immer228module.exports.setAutoFreeze = setAutoFreeze