immer.js
This file
Path
immer.js
270 lines · 8.2 KiB · JavaScript
Last changed by
currying WIPMichel Weststratebefore adoption0789ed4
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 #38 from mweststrate/feature/performanceMichel Weststratebefore adoption670fcff
lines 9–10why, one step back9const PROXY_STATE = Symbol("immer-proxy-state") // TODO: create per closure, to avoid sharing proxies between multiple immer version10let autoFreeze = trueMerge pull request #14 from benbraou/issue10Michel Weststratebefore adoptione775cca
line 11why, one step back11Merge pull request #38 from mweststrate/feature/performanceMichel Weststratebefore adoption670fcff
lines 12–41why, one step back12const objectTraps = {13 get(target, prop) {14 if (prop === PROXY_STATE) return target15 return target.get(prop)16 },17 has(target, prop) {18 return prop in target.source19 },20 ownKeys(target) {21 return Reflect.ownKeys(target.source)22 },23 set(target, prop, value) {24 target.set(prop, value)25 return true26 },27 deleteProperty(target, prop) {28 target.deleteProp(prop)29 return true30 },31 getOwnPropertyDescriptor(target, prop) {32 return target.getOwnPropertyDescriptor(prop)33 },34 defineProperty(target, property, descriptor) {35 target.defineProperty(property, descriptor)36 return true37 },38 setPrototypeOf() {39 throw new Error("Don't even try this...")40 }41}More repo setupMichel Weststratebefore adoption1637393
line 42why, one step back42Merge pull request #38 from mweststrate/feature/performanceMichel Weststratebefore adoption670fcff
lines 43–72why, one step back43const arrayTraps = {44 get(target, prop) {45 if (prop === PROXY_STATE) return target[0]46 return target[0].get(prop)47 },48 has(target, prop) {49 return prop in target[0].source50 },51 ownKeys(target) {52 return Reflect.ownKeys(target[0].source)53 },54 set(target, prop, value) {55 target[0].set(prop, value)56 return true57 },58 deleteProperty(target, prop) {59 target[0].deleteProp(prop)60 return true61 },62 getOwnPropertyDescriptor(target, prop) {63 return target[0].getOwnPropertyDescriptor(prop)64 },65 defineProperty(target, property, descriptor) {66 target[0].defineProperty(property, descriptor)67 return true68 },69 setPrototypeOf() {70 throw new Error("Don't even try this...")71 }72}Fixed bug, wrote readmeMichel Weststratebefore adoption1b8a694
line 73why, one step back73More repo setupMichel Weststratebefore adoption1637393
line 74why, one step back74/**Merge pull request #9 from benbraou/typosMichel Weststratebefore adoptionae0182f
line 75why, one step back75 * Immer takes a state, and runs a function against it.More repo setupMichel Weststratebefore adoption1637393
lines 76–84why, one step back76 * That function can freely mutate the state, as it will create copies-on-write.77 * This means that the original state will stay unchanged, and once the function finishes, the modified state is returned78 *79 * @export80 * @param {any} baseState - the state to start with81 * @param {Function} thunk - function that receives a proxy of the base state as first argument and which can be freely modified82 * @returns {any} a new state, or the base state if nothing was modified83 */84function immer(baseState, thunk) {currying WIPMichel Weststratebefore adoption0789ed4
lines 85–98why, one step back85 // curried invocation86 if (arguments.length === 1) {87 // TODO: check arg is fn88 return function() {89 // TODO: check arg1 is object / array90 const args = arguments91 return immer(args[0], draft => {92 args[0] = draft // blegh!93 baseState.apply(null, args)94 })95 }96 }9798 // TODO: check argsMerge pull request #38 from mweststrate/feature/performanceMichel Weststratebefore adoption670fcff
line 99why, one step back99 const revocableProxies = []Merge pull request #14 from benbraou/issue10Michel Weststratebefore adoptione775cca
line 100why, one step back100Merge pull request #38 from mweststrate/feature/performanceMichel Weststratebefore adoption670fcff
lines 101–108why, one step back101 class State {102 constructor(parent, base) {103 this.modified = false104 this.parent = parent105 this.base = base106 this.copy = undefined107 this.proxies = {}108 }More repo setupMichel Weststratebefore adoption1637393
line 109why, one step back109Merge pull request #38 from mweststrate/feature/performanceMichel Weststratebefore adoption670fcff
lines 110–125why, one step back110 get source() {111 return this.modified === true ? this.copy : this.base112 }113114 get(prop) {115 if (this.modified) {116 const value = this.copy[prop]117 if (!isProxy(value) && isProxyable(value))118 return (this.copy[prop] = createProxy(this, value))119 return value120 } else {121 if (prop in this.proxies) return this.proxies[prop]122 const value = this.base[prop]123 if (!isProxy(value) && isProxyable(value))124 return (this.proxies[prop] = createProxy(this, value))125 return valueMore repo setupMichel Weststratebefore adoption1637393
line 126why, one step back126 }No trailing commas, might break babel, fixes #21Michel Weststratebefore adoption2a1da31
line 127why, one step back127 }More repo setupMichel Weststratebefore adoption1637393
line 128why, one step back128Merge pull request #38 from mweststrate/feature/performanceMichel Weststratebefore adoption670fcff
lines 129–138why, one step back129 set(prop, value) {130 if (!this.modified) {131 if (132 (prop in this.base && this.base[prop] === value) ||133 (prop in this.proxies && this.proxies[prop] === value)134 )135 return136 this.markChanged()137 }138 this.copy[prop] = valueMore repo setupMichel Weststratebefore adoption1637393
lines 139–140why, one step back139 }140Merge pull request #38 from mweststrate/feature/performanceMichel Weststratebefore adoption670fcff
lines 141–144why, one step back141 deleteProp(prop) {142 this.markChanged()143 delete this.copy[prop]144 }Merge pull request #15 from mweststrate/feature/freezeMichel Weststratebefore adoption0d24494
line 145why, one step back145Merge pull request #38 from mweststrate/feature/performanceMichel Weststratebefore adoption670fcff
lines 146–162why, one step back146 getOwnPropertyDescriptor(prop) {147 const owner = this.modified148 ? this.copy149 : prop in this.proxies ? this.proxies : this.base150 const descriptor = Reflect.getOwnPropertyDescriptor(owner, prop)151 if (descriptor) descriptor.configurable = true // XXX: is this really needed?152 return descriptor153 }154155 defineProperty(property, descriptor) {156 this.markChanged()157 Object.defineProperty(this.copy, property, descriptor)158 }159160 markChanged() {161 if (!this.modified) {162 this.modified = truecurrying WIPMichel Weststratebefore adoption0789ed4
line 163why, one step back163 this.copy = Array.isArray(this.base)Merge pull request #38 from mweststrate/feature/performanceMichel Weststratebefore adoption670fcff
line 164why, one step back164 ? this.base.slice()currying WIPMichel Weststratebefore adoption0789ed4
line 165why, one step back165 : Object.assign({}, this.base) // TODO: eliminate those isArray checks?Merge pull request #38 from mweststrate/feature/performanceMichel Weststratebefore adoption670fcff
lines 166–167why, one step back166 Object.assign(this.copy, this.proxies) // yup that works for arrays as well167 if (this.parent) this.parent.markChanged()Merge pull request #15 from mweststrate/feature/freezeMichel Weststratebefore adoption0d24494
line 168why, one step back168 }Code cleanupMichel Weststratebefore adoption2b2d0cb
line 169why, one step back169 }More repo setupMichel Weststratebefore adoption1637393
lines 170–171why, one step back170 }171Merge pull request #38 from mweststrate/feature/performanceMichel Weststratebefore adoption670fcff
lines 172–181why, one step back172 // creates a proxy for plain objects / arrays173 function createProxy(parentState, base) {174 const state = new State(parentState, base)175 let proxy176 if (Array.isArray(base)) {177 // Proxy should be created with an array to make it an array for JS178 // so... here you have it!179 proxy = Proxy.revocable([state], arrayTraps)180 } else {181 proxy = Proxy.revocable(state, objectTraps)More repo setupMichel Weststratebefore adoption1637393
line 182why, one step back182 }Merge pull request #38 from mweststrate/feature/performanceMichel Weststratebefore adoption670fcff
lines 183–184why, one step back183 revocableProxies.push(proxy)184 return proxy.proxyMore repo setupMichel Weststratebefore adoption1637393
lines 185–186why, one step back185 }186Code cleanupMichel Weststratebefore adoption2b2d0cb
lines 187–188why, one step back187 // given a base object, returns it if unmodified, or return the changed cloned if modified188 function finalize(base) {Merge pull request #38 from mweststrate/feature/performanceMichel Weststratebefore adoption670fcff
lines 189–195why, one step back189 if (isProxy(base)) {190 const state = base[PROXY_STATE]191 if (state.modified === true) {192 if (Array.isArray(state.base)) return finalizeArray(state)193 return finalizeObject(state)194 } else return state.base195 }Code cleanupMichel Weststratebefore adoption2b2d0cb
lines 196–198why, one step back196 return base197 }198Merge pull request #38 from mweststrate/feature/performanceMichel Weststratebefore adoption670fcff
lines 199–200why, one step back199 function finalizeObject(state) {200 const copy = state.copyMore repo setupMichel Weststratebefore adoption1637393
line 201why, one step back201 Object.keys(copy).forEach(prop => {Code cleanupMichel Weststratebefore adoption2b2d0cb
line 202why, one step back202 copy[prop] = finalize(copy[prop])Add support for arraysMichel Weststratebefore adoptiond3696cb
line 203why, one step back203 })Merge pull request #15 from mweststrate/feature/freezeMichel Weststratebefore adoption0d24494
line 204why, one step back204 return freeze(copy)Add support for arraysMichel Weststratebefore adoptiond3696cb
lines 205–206why, one step back205 }206Merge pull request #38 from mweststrate/feature/performanceMichel Weststratebefore adoption670fcff
lines 207–208why, one step back207 function finalizeArray(state) {208 const copy = state.copyAdd support for arraysMichel Weststratebefore adoptiond3696cb
line 209why, one step back209 copy.forEach((value, index) => {Code cleanupMichel Weststratebefore adoption2b2d0cb
line 210why, one step back210 copy[index] = finalize(copy[index])More repo setupMichel Weststratebefore adoption1637393
line 211why, one step back211 })Merge pull request #15 from mweststrate/feature/freezeMichel Weststratebefore adoption0d24494
line 212why, one step back212 return freeze(copy)More repo setupMichel Weststratebefore adoption1637393
lines 213–214why, one step back213 }214Code cleanupMichel Weststratebefore adoption2b2d0cb
line 215why, one step back215 // create proxy for rootMerge pull request #38 from mweststrate/feature/performanceMichel Weststratebefore adoption670fcff
line 216why, one step back216 const rootClone = createProxy(undefined, baseState)Code cleanupMichel Weststratebefore adoption2b2d0cb
line 217why, one step back217 // execute the thunkMerge branch 'Gregjarvez-master'Michel Weststratebefore adoptiona151fed
lines 218–221why, one step back218 const maybeVoidReturn = thunk(rootClone)219 //values either than undefined will trigger warning;220 !Object.is(maybeVoidReturn, undefined) &&221 console.warn(Merge pull request #21 from sallyhill/patch-1Michel Weststratebefore adoptionc8718e7
line 222why, one step back222 `Immer callback expects no return value. However ${typeof maybeVoidReturn} was returned`Merge branch 'Gregjarvez-master'Michel Weststratebefore adoptiona151fed
line 223why, one step back223 )Code cleanupMichel Weststratebefore adoption2b2d0cb
line 224why, one step back224 // and finalize the modified proxyMerge pull request #38 from mweststrate/feature/performanceMichel Weststratebefore adoption670fcff
lines 225–228why, one step back225 const res = finalize(rootClone)226 // revoke all proxies227 revocableProxies.forEach(p => p.revoke())228 return resMerge pull request #14 from benbraou/issue10Michel Weststratebefore adoptione775cca
lines 229–230why, one step back229}230Merge pull request #38 from mweststrate/feature/performanceMichel Weststratebefore adoption670fcff
lines 231–232why, one step back231function isProxy(value) {232 return !!value && !!value[PROXY_STATE]More repo setupMichel Weststratebefore adoption1637393
lines 233–234why, one step back233}234Merge pull request #38 from mweststrate/feature/performanceMichel Weststratebefore adoption670fcff
lines 235–238why, one step back235function isProxyable(value) {236 if (!value) return false237 if (typeof value !== "object") return false238 if (Array.isArray(value)) return trueMore repo setupMichel Weststratebefore adoption1637393
line 239why, one step back239 const proto = Object.getPrototypeOf(value)Merge pull request #38 from mweststrate/feature/performanceMichel Weststratebefore adoption670fcff
line 240why, one step back240 return (proto === proto) === null || Object.prototypeMore repo setupMichel Weststratebefore adoption1637393
lines 241–242why, one step back241}242Merge pull request #15 from mweststrate/feature/freezeMichel Weststratebefore adoption0d24494
line 243why, one step back243function freeze(value) {Merge pull request #25 from Gregjarvez/travisMichel Weststratebefore adoption55ec6d0
lines 244–246why, one step back244 // short circuit to achieve 100% code coverage instead of 98%245 /*246 if(autoFreeze) {Merge pull request #15 from mweststrate/feature/freezeMichel Weststratebefore adoption0d24494
lines 247–248why, one step back247 Object.freeze(value)248 }Merge pull request #25 from Gregjarvez/travisMichel Weststratebefore adoption55ec6d0
line 249why, one step back249 * */currying WIPMichel Weststratebefore adoption0789ed4
line 250why, one step back250 autoFreeze && Object.freeze(value)Merge pull request #15 from mweststrate/feature/freezeMichel Weststratebefore adoption0d24494
lines 251–266why, one step back251 return value252}253254/**255 * Automatically freezes any state trees generated by immer.256 * This protects against accidental modifications of the state tree outside of an immer function.257 * This comes with a performance impact, so it is recommended to disable this option in production.258 * It is by default enabled.259 *260 * @returns {void}261 */262function setAutoFreeze(enableAutoFreeze) {263 autoFreeze = enableAutoFreeze264}265266Object.defineProperty(exports, "__esModule", {No trailing commas, might break babel, fixes #21Michel Weststratebefore adoption2a1da31
line 267why, one step back267 value: trueMerge pull request #15 from mweststrate/feature/freezeMichel Weststratebefore adoption0d24494
lines 268–270why, one step back268})269module.exports.default = immer270module.exports.setAutoFreeze = setAutoFreeze