Skip to content
Myr

immer.js

This file

Path

src/immer.js

307 lines · 10.3 KiB · JavaScript

Last changed by

initial solutionMichel Weststratebefore adoptiond618d28

History of this file

Take it

transpile es5 codeMichel Weststratebefore adoptionf012154

lines 1–48why, 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 )89const PROXY_STATE = Symbol("immer-proxy-state") // TODO: create per closure, to avoid sharing proxies between multiple immer version10let autoFreeze = true1112const 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}4243const arrayTraps = {44 get(target, prop) {45 if (prop === PROXY_STATE) return target[0]46 return target[0].get(prop)47 },48 has(target, prop) {

initial solutionMichel Weststratebefore adoptiond618d28

line 49why, one step back
49 return prop === PROXY_STATE || prop in target[0].source

transpile es5 codeMichel Weststratebefore adoptionf012154

lines 50–83why, one step back
50 },
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}7374/**75 * produce takes a state, and runs a function against it.76 * 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} producer - 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 */

Default build includes both Proxy and ES5 implementationMichel Weststratebefore adoptionbd9c47b

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

transpile es5 codeMichel Weststratebefore adoptionf012154

lines 85–105why, one step back
85 // curried invocation
86 if (arguments.length === 1) {87 const producer = baseState88 // prettier-ignore89 if (typeof producer !== "function") throw new Error("if produce is called with 1 argument, the first argument should be a function")90 return function() {91 const args = arguments92 return produce(args[0], draft => {93 args[0] = draft // blegh!94 baseState.apply(null, args)95 })96 }97 }9899 // prettier-ignore100 {101 if (arguments.length !== 2) throw new Error("produce expects 1 or 2 arguments, got " + arguments.length)102 if (!isProxyable(baseState)) throw new Error("the first argument to produce should be a plain object or array, got " + (typeof baseState))103 if (typeof producer !== "function") throw new Error("the second argument to produce should be a function")104 }105 const revocableProxies = []

initial solutionMichel Weststratebefore adoptiond618d28

lines 106–110why, one step back
106 // for objects that are created in the producer we don't know anything
107 // those could contain proxies anywhere (see #53)108 // we don't want to walk through the entire state tree to know which objects are unknown109 // so, we keep a set of objects that the user visited so that we know that any object outside that need to be investigated further110 const existingEdges = new Set()

transpile es5 codeMichel Weststratebefore adoptionf012154

lines 111–186why, one step back
111
112 class State {113 constructor(parent, base) {114 this.modified = false115 this.parent = parent116 this.base = base117 this.copy = undefined118 this.proxies = {}119 }120121 get source() {122 return this.modified === true ? this.copy : this.base123 }124125 get(prop) {126 if (this.modified) {127 const value = this.copy[prop]128 if (!isProxy(value) && isProxyable(value))129 return (this.copy[prop] = createProxy(this, value))130 return value131 } else {132 if (prop in this.proxies) return this.proxies[prop]133 const value = this.base[prop]134 if (!isProxy(value) && isProxyable(value))135 return (this.proxies[prop] = createProxy(this, value))136 return value137 }138 }139140 set(prop, value) {141 if (!this.modified) {142 if (143 (prop in this.base && this.base[prop] === value) ||144 (prop in this.proxies && this.proxies[prop] === value)145 )146 return147 this.markChanged()148 }149 this.copy[prop] = value150 }151152 deleteProp(prop) {153 this.markChanged()154 delete this.copy[prop]155 }156157 getOwnPropertyDescriptor(prop) {158 const owner = this.modified159 ? this.copy160 : prop in this.proxies ? this.proxies : this.base161 const descriptor = Reflect.getOwnPropertyDescriptor(owner, prop)162 if (descriptor && !(Array.isArray(owner) && prop === "length"))163 descriptor.configurable = true164 return descriptor165 }166167 defineProperty(property, descriptor) {168 throw new Error(169 "Immer does currently not support defining properties on draft objects"170 )171 }172173 markChanged() {174 if (!this.modified) {175 this.modified = true176 this.copy = Array.isArray(this.base)177 ? this.base.slice()178 : Object.assign({}, this.base) // TODO: eliminate those isArray checks?179 Object.assign(this.copy, this.proxies) // yup that works for arrays as well180 if (this.parent) this.parent.markChanged()181 }182 }183 }184185 // creates a proxy for plain objects / arrays186 function createProxy(parentState, base) {

initial solutionMichel Weststratebefore adoptiond618d28

line 187why, one step back
187 existingEdges.delete(base)

transpile es5 codeMichel Weststratebefore adoptionf012154

lines 188–190why, one step back
188 const state = new State(parentState, base)
189 let proxy190 if (Array.isArray(base)) {

initial solutionMichel Weststratebefore adoptiond618d28

lines 191–195why, one step back
191 for (let i = 0; i < base.length; i++) {
192 const value = base[i]193 if (value !== null && typeof value === "object")194 existingEdges.add(value)195 }

transpile es5 codeMichel Weststratebefore adoptionf012154

lines 196–199why, one step back
196 // Proxy should be created with an array to make it an array for JS
197 // so... here you have it!198 proxy = Proxy.revocable([state], arrayTraps)199 } else {

initial solutionMichel Weststratebefore adoptiond618d28

lines 200–204why, one step back
200 for (var key in base) {
201 const value = base[key]202 if (value !== null && typeof value === "object")203 existingEdges.add(value)204 }

transpile es5 codeMichel Weststratebefore adoptionf012154

lines 205–218why, one step back
205 proxy = Proxy.revocable(state, objectTraps)
206 }207 revocableProxies.push(proxy)208 return proxy.proxy209 }210211 // given a base object, returns it if unmodified, or return the changed cloned if modified212 function finalize(base) {213 if (isProxy(base)) {214 const state = base[PROXY_STATE]215 if (state.modified === true) {216 if (Array.isArray(state.base)) return finalizeArray(state)217 return finalizeObject(state)218 } else return state.base

initial solutionMichel Weststratebefore adoptiond618d28

lines 219–237why, one step back
219 } else if (
220 base !== null &&221 typeof base === "object" &&222 !existingEdges.has(base)223 ) {224 // This object was not part of the original tree, so anywhere deep inside it could be changed objects..225 // TODO optimize: unless we processed all proxies226 // TODO: first check deeply whether there are proxies in there?227 if (Array.isArray(base)) return freeze(base.map(finalize))228 const proto = Object.getPrototypeOf(base)229 if (proto === null || proto === Object.prototype) {230 // object231 const res = Object.assign({}, base)232 Object.keys(res).forEach(prop => {233 // TODO: optimize for loops234 res[prop] = finalize(res[prop])235 })236 return freeze(res)237 }

transpile es5 codeMichel Weststratebefore adoptionf012154

lines 238–282why, one step back
238 }
239 return base240 }241242 function finalizeObject(state) {243 const copy = state.copy244 Object.keys(copy).forEach(prop => {245 copy[prop] = finalize(copy[prop])246 })247 return freeze(copy)248 }249250 function finalizeArray(state) {251 const copy = state.copy252 copy.forEach((value, index) => {253 copy[index] = finalize(copy[index])254 })255 return freeze(copy)256 }257258 // create proxy for root259 const rootClone = createProxy(undefined, baseState)260 // execute the thunk261 const maybeVoidReturn = producer(rootClone)262 //values either than undefined will trigger warning;263 !Object.is(maybeVoidReturn, undefined) &&264 console.warn(265 `Immer callback expects no return value. However ${typeof maybeVoidReturn} was returned`266 )267 // and finalize the modified proxy268 const res = finalize(rootClone)269 // revoke all proxies270 revocableProxies.forEach(p => p.revoke())271 return res272}273274function isProxy(value) {275 return !!value && !!value[PROXY_STATE]276}277278function isProxyable(value) {279 if (!value) return false280 if (typeof value !== "object") return false281 if (Array.isArray(value)) return true282 const proto = Object.getPrototypeOf(value)

initial solutionMichel Weststratebefore adoptiond618d28

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

transpile es5 codeMichel Weststratebefore adoptionf012154

lines 284–304why, one step back
284}
285286function freeze(value) {287 // short circuit to achieve 100% code coverage instead of 98%288 /*289 if(autoFreeze) {290 Object.freeze(value)291 }292 * */293 autoFreeze && Object.freeze(value)294 return value295}296297/**298 * Automatically freezes any state trees generated by immer.299 * This protects against accidental modifications of the state tree outside of an immer function.300 * This comes with a performance impact, so it is recommended to disable this option in production.301 * It is by default enabled.302 *303 * @returns {void}304 */

Default build includes both Proxy and ES5 implementationMichel Weststratebefore adoptionbd9c47b

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

transpile es5 codeMichel Weststratebefore adoptionf012154

lines 306–307why, one step back
306 autoFreeze = enableAutoFreeze
307}