Skip to content
Myr

immer.js

This file

Path

src/immer.js

260 lines · 8.1 KiB · JavaScript

Last changed by

leaner implementationMichel Weststratebefore adoption7b13028

History of this file

Take it

transpile es5 codeMichel Weststratebefore adoptionf012154

lines 1–8why, one step back
1"use strict"
2// @ts-check34if (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 )8

Making several improvements at onceMichel Weststratebefore adoption1116ccf

line 9why, one step back
9const PROXY_STATE = Symbol("immer-proxy-state")

transpile es5 codeMichel Weststratebefore adoptionf012154

line 10why, one step back
10let autoFreeze = true

extracted class methods from Proxy implMichel Weststratebefore adoptiond20adea

line 11why, one step back
11let revocableProxies = null

transpile es5 codeMichel Weststratebefore adoptionf012154

lines 12–13why, one step back
12
13const objectTraps = {

leaner implementationMichel Weststratebefore adoption7b13028

line 14why, one step back
14 get,

transpile es5 codeMichel Weststratebefore adoptionf012154

line 15why, one step back
15 has(target, prop) {

extracted class methods from Proxy implMichel Weststratebefore adoptiond20adea

line 16why, one step back
16 return prop in source(target)

transpile es5 codeMichel Weststratebefore adoptionf012154

lines 17–18why, one step back
17 },
18 ownKeys(target) {

extracted class methods from Proxy implMichel Weststratebefore adoptiond20adea

line 19why, one step back
19 return Reflect.ownKeys(source(target))

transpile es5 codeMichel Weststratebefore adoptionf012154

line 20why, one step back
20 },

leaner implementationMichel Weststratebefore adoption7b13028

lines 21–24why, one step back
21 set,
22 deleteProperty,23 getOwnPropertyDescriptor,24 defineProperty,

transpile es5 codeMichel Weststratebefore adoptionf012154

lines 25–29why, one step back
25 setPrototypeOf() {
26 throw new Error("Don't even try this...")27 }28}29

leaner implementationMichel Weststratebefore adoption7b13028

lines 30–34why, one step back
30const arrayTraps = {}
31for (let key in objectTraps) {32 arrayTraps[key] = function() {33 arguments[0] = arguments[0][0]34 return objectTraps[key].apply(this, arguments)

transpile es5 codeMichel Weststratebefore adoptionf012154

lines 35–37why, one step back
35 }
36}37

extracted class methods from Proxy implMichel Weststratebefore adoptiond20adea

lines 38–53why, one step back
38class State {
39 constructor(parent, base) {40 this.modified = false41 this.finalized = false42 this.parent = parent43 this.base = base44 this.copy = undefined45 this.proxies = {}46 }47}4849function source(state) {50 return state.modified === true ? state.copy : state.base51}5253function get(state, prop) {

leaner implementationMichel Weststratebefore adoption7b13028

line 54why, one step back
54 if (prop === PROXY_STATE) return state

extracted class methods from Proxy implMichel Weststratebefore adoptiond20adea

lines 55–74why, one step back
55 if (state.modified) {
56 const value = state.copy[prop]57 if (!isProxy(value) && isProxyable(value))58 return (state.copy[prop] = createProxy(state, value))59 return value60 } else {61 if (prop in state.proxies) return state.proxies[prop]62 const value = state.base[prop]63 if (!isProxy(value) && isProxyable(value))64 return (state.proxies[prop] = createProxy(state, value))65 return value66 }67}6869function set(state, prop, value) {70 if (!state.modified) {71 if (72 (prop in state.base && Object.is(state.base[prop], value)) ||73 (prop in state.proxies && state.proxies[prop] === value)74 )

leaner implementationMichel Weststratebefore adoption7b13028

line 75why, one step back
75 return true

extracted class methods from Proxy implMichel Weststratebefore adoptiond20adea

lines 76–78why, one step back
76 markChanged(state)
77 }78 state.copy[prop] = value

leaner implementationMichel Weststratebefore adoption7b13028

line 79why, one step back
79 return true

extracted class methods from Proxy implMichel Weststratebefore adoptiond20adea

lines 80–81why, one step back
80}
81

leaner implementationMichel Weststratebefore adoption7b13028

line 82why, one step back
82function deleteProperty(state, prop) {

extracted class methods from Proxy implMichel Weststratebefore adoptiond20adea

lines 83–84why, one step back
83 markChanged(state)
84 delete state.copy[prop]

leaner implementationMichel Weststratebefore adoption7b13028

line 85why, one step back
85 return true

extracted class methods from Proxy implMichel Weststratebefore adoptiond20adea

lines 86–172why, one step back
86}
8788function getOwnPropertyDescriptor(state, prop) {89 const owner = state.modified90 ? state.copy91 : prop in state.proxies ? state.proxies : state.base92 const descriptor = Reflect.getOwnPropertyDescriptor(owner, prop)93 if (descriptor && !(Array.isArray(owner) && prop === "length"))94 descriptor.configurable = true95 return descriptor96}9798function defineProperty() {99 throw new Error(100 "Immer does currently not support defining properties on draft objects"101 )102}103104function markChanged(state) {105 if (!state.modified) {106 state.modified = true107 state.copy = Array.isArray(state.base)108 ? state.base.slice()109 : Object.assign({}, state.base) // TODO: eliminate those isArray checks?110 Object.assign(state.copy, state.proxies) // yup that works for arrays as well111 if (state.parent) markChanged(state.parent)112 }113}114115// creates a proxy for plain objects / arrays116function createProxy(parentState, base) {117 const state = new State(parentState, base)118 let proxy119 if (Array.isArray(base)) {120 proxy = Proxy.revocable([state], arrayTraps)121 } else {122 proxy = Proxy.revocable(state, objectTraps)123 }124 revocableProxies.push(proxy)125 return proxy.proxy126}127128// given a base object, returns it if unmodified, or return the changed cloned if modified129function finalize(base) {130 if (isProxy(base)) {131 const state = base[PROXY_STATE]132 if (state.modified === true) {133 if (state.finalized === true) return state.copy134 state.finalized = true135 if (Array.isArray(state.base)) return finalizeArray(state)136 return finalizeObject(state)137 } else return state.base138 } else if (base !== null && typeof base === "object") {139 // If finalize is called on an object that was not a proxy, it means that it is an object that was not there in the original140 // tree and it could contain proxies at arbitrarily places. Let's find and finalize them as well141 // TODO: optimize this; walk the tree without writing to find proxies142 if (Array.isArray(base)) {143 for (let i = 0; i < base.length; i++) base[i] = finalize(base[i])144 return freeze(base)145 }146 const proto = Object.getPrototypeOf(base)147 if (proto === null || proto === Object.prototype) {148 for (let key in base) base[key] = finalize(base[key])149 return freeze(base)150 }151 }152 return base153}154155function finalizeObject(state) {156 const copy = state.copy157 const base = state.base158 for (var prop in copy) {159 if (copy[prop] !== base[prop]) copy[prop] = finalize(copy[prop])160 }161 return freeze(copy)162}163164function finalizeArray(state) {165 const copy = state.copy166 const base = state.base167 for (let i = 0; i < copy.length; i++) {168 if (copy[i] !== base[i]) copy[i] = finalize(copy[i])169 }170 return freeze(copy)171}172

transpile es5 codeMichel Weststratebefore adoptionf012154

lines 173–182why, one step back
173/**
174 * produce takes a state, and runs a function against it.175 * That function can freely mutate the state, as it will create copies-on-write.176 * This means that the original state will stay unchanged, and once the function finishes, the modified state is returned177 *178 * @export179 * @param {any} baseState - the state to start with180 * @param {Function} producer - function that receives a proxy of the base state as first argument and which can be freely modified181 * @returns {any} a new state, or the base state if nothing was modified182 */

Default build includes both Proxy and ES5 implementationMichel Weststratebefore adoptionbd9c47b

line 183why, one step back
183export default function produce(baseState, producer) {

transpile es5 codeMichel Weststratebefore adoptionf012154

lines 184–204why, one step back
184 // curried invocation
185 if (arguments.length === 1) {186 const producer = baseState187 // prettier-ignore188 if (typeof producer !== "function") throw new Error("if produce is called with 1 argument, the first argument should be a function")189 return function() {190 const args = arguments191 return produce(args[0], draft => {192 args[0] = draft // blegh!193 baseState.apply(null, args)194 })195 }196 }197198 // prettier-ignore199 {200 if (arguments.length !== 2) throw new Error("produce expects 1 or 2 arguments, got " + arguments.length)201 if (!isProxyable(baseState)) throw new Error("the first argument to produce should be a plain object or array, got " + (typeof baseState))202 if (typeof producer !== "function") throw new Error("the second argument to produce should be a function")203 }204

extracted class methods from Proxy implMichel Weststratebefore adoptiond20adea

lines 205–215why, one step back
205 const previousProxies = revocableProxies
206 revocableProxies = []207 try {208 // create proxy for root209 const rootClone = createProxy(undefined, baseState)210 // execute the thunk211 const maybeVoidReturn = producer(rootClone)212 //values either than undefined will trigger warning;213 !Object.is(maybeVoidReturn, undefined) &&214 console.warn(215 `Immer callback expects no return value. However ${typeof maybeVoidReturn} was returned`

transpile es5 codeMichel Weststratebefore adoptionf012154

line 216why, one step back
216 )

extracted class methods from Proxy implMichel Weststratebefore adoptiond20adea

lines 217–223why, one step back
217 // and finalize the modified proxy
218 const res = finalize(rootClone)219 // revoke all proxies220 revocableProxies.forEach(p => p.revoke())221 return res222 } finally {223 revocableProxies = previousProxies

transpile es5 codeMichel Weststratebefore adoptionf012154

lines 224–235why, one step back
224 }
225}226227function isProxy(value) {228 return !!value && !!value[PROXY_STATE]229}230231function isProxyable(value) {232 if (!value) return false233 if (typeof value !== "object") return false234 if (Array.isArray(value)) return true235 const proto = Object.getPrototypeOf(value)

initial solutionMichel Weststratebefore adoptiond618d28

line 236why, one step back
236 return proto === null || proto === Object.prototype

transpile es5 codeMichel Weststratebefore adoptionf012154

lines 237–257why, one step back
237}
238239function freeze(value) {240 // short circuit to achieve 100% code coverage instead of 98%241 /*242 if(autoFreeze) {243 Object.freeze(value)244 }245 * */246 autoFreeze && Object.freeze(value)247 return value248}249250/**251 * Automatically freezes any state trees generated by immer.252 * This protects against accidental modifications of the state tree outside of an immer function.253 * This comes with a performance impact, so it is recommended to disable this option in production.254 * It is by default enabled.255 *256 * @returns {void}257 */

Default build includes both Proxy and ES5 implementationMichel Weststratebefore adoptionbd9c47b

line 258why, one step back
258export function setAutoFreeze(enableAutoFreeze) {

transpile es5 codeMichel Weststratebefore adoptionf012154

lines 259–260why, one step back
259 autoFreeze = enableAutoFreeze
260}