immer.js
This file
Path
immer.js
268 lines · 8.8 KiB · JavaScript
Last changed by
Simple optimization in ES5Michel Weststratebefore adoption24b5d42
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 */14WIPMichel Weststratebefore adoptiona758751
lines 15–16why, one step back15const IS_PROXY = Symbol("immer-proxy") // TODO: create per closure, to avoid sharing proxies between multiple immer version16const PROXY_STATE = Symbol("immer-proxy-state") // TODO: create per closure, to avoid sharing proxies between multiple immer versionMore repo setupMichel Weststratebefore adoption1637393
line 17why, one step back17Merge pull request #15 from mweststrate/feature/freezeMichel Weststratebefore adoption0d24494
lines 18–20why, one step back18// This property indicates that the current object is cloned for another object,19// to make sure the proxy of a frozen object is writeable20const CLONE_TARGET = Symbol("immer-clone-target")Fixed bug, wrote readmeMichel Weststratebefore adoption1b8a694
line 21why, one step back21Merge pull request #15 from mweststrate/feature/freezeMichel Weststratebefore adoption0d24494
lines 22–23why, one step back22let autoFreeze = true23More repo setupMichel Weststratebefore adoption1637393
line 24why, one step back24/**Merge pull request #9 from benbraou/typosMichel Weststratebefore adoptionae0182f
line 25why, one step back25 * Immer takes a state, and runs a function against it.More repo setupMichel Weststratebefore adoption1637393
lines 26–34why, one step back26 * That function can freely mutate the state, as it will create copies-on-write.27 * This means that the original state will stay unchanged, and once the function finishes, the modified state is returned28 *29 * @export30 * @param {any} baseState - the state to start with31 * @param {Function} thunk - function that receives a proxy of the base state as first argument and which can be freely modified32 * @returns {any} a new state, or the base state if nothing was modified33 */34function immer(baseState, thunk) {Fixed remaining failing testsMichel Weststratebefore adoption4e7f44a
lines 35–36why, one step back35 const revocableProxies = []36WIPMichel Weststratebefore adoptiona758751
lines 37–38why, one step back37 class State {38 constructor(parent, base) {Allmost feature complete!Michel Weststratebefore adoption82ac66c
line 39why, one step back39 this.modified = falseWIPMichel Weststratebefore adoptiona758751
lines 40–41why, one step back40 this.parent = parent41 this.base = baseAllmost feature complete!Michel Weststratebefore adoption82ac66c
line 42why, one step back42 this.copy = undefinedWIPMichel Weststratebefore adoptiona758751
lines 43–44why, one step back43 this.proxies = {}44 }More repo setupMichel Weststratebefore adoption1637393
line 45why, one step back45WIPMichel Weststratebefore adoptiona758751
lines 46–50why, one step back46 get source() {47 return this.modified === true ? this.copy : this.base48 }4950 get(prop) {Allmost feature complete!Michel Weststratebefore adoption82ac66c
lines 51–62why, one step back51 if (this.modified) {52 const value = this.copy[prop]53 if (!isProxy(value) && isProxyable(value))54 return (this.copy[prop] = createProxy(this, value))55 return value56 } else {57 if (prop in this.proxies) return this.proxies[prop]58 const value = this.base[prop]59 if (!isProxy(value) && isProxyable(value))60 return (this.proxies[prop] = createProxy(this, value))61 return value62 }WIPMichel Weststratebefore adoptiona758751
lines 63–66why, one step back63 }6465 set(prop, value) {66 if (!this.modified) {Allmost feature complete!Michel Weststratebefore adoption82ac66c
lines 67–70why, one step back67 if (68 (prop in this.base && this.base[prop] === value) ||69 (prop in this.proxies && this.proxies[prop] === value)70 )WIPMichel Weststratebefore adoptiona758751
lines 71–79why, one step back71 return72 this.markChanged()73 }74 this.copy[prop] = value75 }7677 markChanged() {78 if (!this.modified) {79 this.modified = trueAllmost feature complete!Michel Weststratebefore adoption82ac66c
line 80why, one step back80 this.copy = Array.isArray(this.base) // TODO: eliminate those isArray checks?WIP on arraysMichel Weststratebefore adoptioncab47bb
lines 81–82why, one step back81 ? this.base.slice()82 : Object.assign({}, this.base)Allmost feature complete!Michel Weststratebefore adoption82ac66c
line 83why, one step back83 Object.assign(this.copy, this.proxies) // yup that works for arrays as wellWIPMichel Weststratebefore adoptiona758751
lines 84–88why, one step back84 if (this.parent) this.parent.markChanged()85 }86 }87 }88More repo setupMichel Weststratebefore adoption1637393
lines 89–90why, one step back89 const objectTraps = {90 get(target, prop) {WIPMichel Weststratebefore adoptiona758751
lines 91–93why, one step back91 if (prop === IS_PROXY) return true92 if (prop === PROXY_STATE) return target93 return target.get(prop)More repo setupMichel Weststratebefore adoption1637393
lines 94–95why, one step back94 },95 has(target, prop) {WIPMichel Weststratebefore adoptiona758751
line 96why, one step back96 return prop in target.sourceMore repo setupMichel Weststratebefore adoption1637393
lines 97–98why, one step back97 },98 ownKeys(target) {WIPMichel Weststratebefore adoptiona758751
line 99why, one step back99 return Reflect.ownKeys(target.source)More repo setupMichel Weststratebefore adoption1637393
lines 100–101why, one step back100 },101 set(target, prop, value) {WIPMichel Weststratebefore adoptiona758751
line 102why, one step back102 target.set(prop, value)More repo setupMichel Weststratebefore adoption1637393
lines 103–105why, one step back103 return true104 },105 deleteProperty(target, property) {WIPMichel Weststratebefore adoptiona758751
lines 106–107why, one step back106 target.markChanged()107 delete target.copy[property]More repo setupMichel Weststratebefore adoption1637393
line 108why, one step back108 return trueMerge pull request #33 from mweststrate/fix/32Michel Weststratebefore adoptionfae0957
lines 109–110why, one step back109 },110 getOwnPropertyDescriptor(target, prop) {Allmost feature complete!Michel Weststratebefore adoption82ac66c
lines 111–114why, one step back111 // TOOD: move to state112 const owner = target.modified113 ? target.copy114 : prop in target.proxies ? target.proxies : target.baseFixed remaining failing testsMichel Weststratebefore adoption4e7f44a
lines 115–117why, one step back115 const descriptor = Reflect.getOwnPropertyDescriptor(owner, prop)116 if (descriptor) descriptor.configurable = true // XXX: is this really needed?117 return descriptorMerge pull request #33 from mweststrate/fix/32Michel Weststratebefore adoptionfae0957
lines 118–119why, one step back118 },119 defineProperty(target, property, descriptor) {WIPMichel Weststratebefore adoptiona758751
lines 120–121why, one step back120 target.markChanged()121 Object.defineProperty(target.copy, property, descriptor)Merge pull request #33 from mweststrate/fix/32Michel Weststratebefore adoptionfae0957
lines 122–125why, one step back122 return true123 },124 setPrototypeOf() {125 throw new Error("Don't even try this...")No trailing commas, might break babel, fixes #21Michel Weststratebefore adoption2a1da31
line 126why, one step back126 }More repo setupMichel Weststratebefore adoption1637393
lines 127–128why, one step back127 }128WIP on arraysMichel Weststratebefore adoptioncab47bb
lines 129–149why, one step back129 const arrayTraps = {130 get(target, prop) {131 if (prop === IS_PROXY) return true132 if (prop === PROXY_STATE) return target[0]133 return target[0].get(prop)134 },135 has(target, prop) {136 return prop in target[0].source137 },138 ownKeys(target) {139 return Reflect.ownKeys(target[0].source)140 },141 set(target, prop, value) {142 target[0].set(prop, value)143 return true144 },145 deleteProperty(target, property) {146 target[0].markChanged()147 delete target[0].copy[property]148 return true149 },Allmost feature complete!Michel Weststratebefore adoption82ac66c
line 150why, one step back150 getOwnPropertyDescriptor(target_, prop) {Fixed remaining failing testsMichel Weststratebefore adoption4e7f44a
line 151why, one step back151 // TOOD: move to stateAllmost feature complete!Michel Weststratebefore adoption82ac66c
lines 152–155why, one step back152 const target = target_[0]153 const owner = target.modified154 ? target.copy155 : prop in target.proxies ? target.proxies : target.baseFixed remaining failing testsMichel Weststratebefore adoption4e7f44a
lines 156–158why, one step back156 const descriptor = Reflect.getOwnPropertyDescriptor(owner, prop)157 if (descriptor) descriptor.configurable = true // XXX: is this really needed?158 return descriptorWIP on arraysMichel Weststratebefore adoptioncab47bb
lines 159–169why, one step back159 },160 defineProperty(target, property, descriptor) {161 target[0].markChanged()162 Object.defineProperty(target[0].copy, property, descriptor)163 return true164 },165 setPrototypeOf() {166 throw new Error("Don't even try this...")167 }168 }169Code cleanupMichel Weststratebefore adoption2b2d0cb
line 170why, one step back170 // creates a proxy for plain objects / arraysWIPMichel Weststratebefore adoptiona758751
lines 171–172why, one step back171 function createProxy(parentState, base) {172 const state = new State(parentState, base)Fixed remaining failing testsMichel Weststratebefore adoption4e7f44a
line 173why, one step back173 let proxyWIP on arraysMichel Weststratebefore adoptioncab47bb
lines 174–176why, one step back174 if (Array.isArray(base)) {175 // Proxy should be created with an array to make it an array for JS176 // so... here you have it!Fixed remaining failing testsMichel Weststratebefore adoption4e7f44a
line 177why, one step back177 proxy = Proxy.revocable([state], arrayTraps)WIP on arraysMichel Weststratebefore adoptioncab47bb
line 178why, one step back178 } else {Fixed remaining failing testsMichel Weststratebefore adoption4e7f44a
line 179why, one step back179 proxy = Proxy.revocable(state, objectTraps)WIP on arraysMichel Weststratebefore adoptioncab47bb
line 180why, one step back180 }Fixed remaining failing testsMichel Weststratebefore adoption4e7f44a
lines 181–182why, one step back181 revocableProxies.push(proxy)182 return proxy.proxyMore repo setupMichel Weststratebefore adoption1637393
lines 183–184why, one step back183 }184Code cleanupMichel Weststratebefore adoption2b2d0cb
lines 185–186why, one step back185 // given a base object, returns it if unmodified, or return the changed cloned if modified186 function finalize(base) {WIPMichel Weststratebefore adoptiona758751
lines 187–189why, one step back187 if (isProxy(base)) {188 const state = base[PROXY_STATE]189 if (state.modified === true) {Allmost feature complete!Michel Weststratebefore adoption82ac66c
lines 190–191why, one step back190 if (isPlainObject(state.base)) return finalizeObject(state)191 if (Array.isArray(state.base)) return finalizeArray(state)WIPMichel Weststratebefore adoptiona758751
lines 192–193why, one step back192 } else return state.base193 }Code cleanupMichel Weststratebefore adoption2b2d0cb
lines 194–196why, one step back194 return base195 }196WIPMichel Weststratebefore adoptiona758751
lines 197–198why, one step back197 function finalizeObject(state) {198 const copy = state.copyMore repo setupMichel Weststratebefore adoption1637393
line 199why, one step back199 Object.keys(copy).forEach(prop => {Allmost feature complete!Michel Weststratebefore adoption82ac66c
line 200why, one step back200 copy[prop] = finalize(copy[prop]) // TODO: make sure no new proxies are generated!Add support for arraysMichel Weststratebefore adoptiond3696cb
line 201why, one step back201 })Merge pull request #15 from mweststrate/feature/freezeMichel Weststratebefore adoption0d24494
line 202why, one step back202 return freeze(copy)Add support for arraysMichel Weststratebefore adoptiond3696cb
lines 203–204why, one step back203 }204Allmost feature complete!Michel Weststratebefore adoption82ac66c
line 205why, one step back205 function finalizeArray(state) {WIPMichel Weststratebefore adoptiona758751
line 206why, one step back206 const copy = state.copyAdd support for arraysMichel Weststratebefore adoptiond3696cb
line 207why, one step back207 copy.forEach((value, index) => {Code cleanupMichel Weststratebefore adoption2b2d0cb
line 208why, one step back208 copy[index] = finalize(copy[index])More repo setupMichel Weststratebefore adoption1637393
line 209why, one step back209 })Merge pull request #15 from mweststrate/feature/freezeMichel Weststratebefore adoption0d24494
line 210why, one step back210 return freeze(copy)More repo setupMichel Weststratebefore adoption1637393
lines 211–212why, one step back211 }212Code cleanupMichel Weststratebefore adoption2b2d0cb
line 213why, one step back213 // create proxy for rootWIPMichel Weststratebefore adoptiona758751
line 214why, one step back214 const rootClone = createProxy(undefined, baseState)Code cleanupMichel Weststratebefore adoption2b2d0cb
line 215why, one step back215 // execute the thunkMerge branch 'Gregjarvez-master'Michel Weststratebefore adoptiona151fed
lines 216–219why, one step back216 const maybeVoidReturn = thunk(rootClone)217 //values either than undefined will trigger warning;218 !Object.is(maybeVoidReturn, undefined) &&219 console.warn(Merge pull request #21 from sallyhill/patch-1Michel Weststratebefore adoptionc8718e7
line 220why, one step back220 `Immer callback expects no return value. However ${typeof maybeVoidReturn} was returned`Merge branch 'Gregjarvez-master'Michel Weststratebefore adoptiona151fed
line 221why, one step back221 )Code cleanupMichel Weststratebefore adoption2b2d0cb
line 222why, one step back222 // and finalize the modified proxyFixed remaining failing testsMichel Weststratebefore adoption4e7f44a
lines 223–226why, one step back223 const res = finalize(rootClone)224 // revoke all proxies225 revocableProxies.forEach(p => p.revoke())226 return resMore repo setupMichel Weststratebefore adoption1637393
lines 227–232why, one step back227}228229function isPlainObject(value) {230 if (value === null || typeof value !== "object") return false231 const proto = Object.getPrototypeOf(value)232 return proto === Object.prototype || proto === nullFixed bug, wrote readmeMichel Weststratebefore adoption1b8a694
lines 233–235why, one step back233}234235function isProxy(value) {WIPMichel Weststratebefore adoptiona758751
lines 236–242why, one step back236 return !!value && !!value[IS_PROXY]237}238239function isProxyable(value) {240 if (!value) return false241 if (typeof value !== "object") return false242 return Array.isArray(value) || isPlainObject(value)More repo setupMichel Weststratebefore adoption1637393
lines 243–244why, one step back243}244Merge pull request #15 from mweststrate/feature/freezeMichel Weststratebefore adoption0d24494
lines 245–264why, one step back245function freeze(value) {246 if (autoFreeze) {247 Object.freeze(value)248 }249 return value250}251252/**253 * Automatically freezes any state trees generated by immer.254 * This protects against accidental modifications of the state tree outside of an immer function.255 * This comes with a performance impact, so it is recommended to disable this option in production.256 * It is by default enabled.257 *258 * @returns {void}259 */260function setAutoFreeze(enableAutoFreeze) {261 autoFreeze = enableAutoFreeze262}263264Object.defineProperty(exports, "__esModule", {No trailing commas, might break babel, fixes #21Michel Weststratebefore adoption2a1da31
line 265why, one step back265 value: trueMerge pull request #15 from mweststrate/feature/freezeMichel Weststratebefore adoption0d24494
lines 266–268why, one step back266})267module.exports.default = immer268module.exports.setAutoFreeze = setAutoFreeze