Skip to content
Myr

immer.js

This file

Path

immer.js

223 lines · 7.3 KiB · JavaScript

Last changed by

Added performance measurements, fixes #6Michel Weststratebefore adoption553299f

History of this file

Take it

Merge pull request #15 from mweststrate/feature/freezeMichel Weststratebefore adoption0d24494

lines 1–3why, one step back
1"use strict"
2// @ts-check3

Merge pull request #14 from benbraou/issue10Michel Weststratebefore adoptione775cca

lines 4–9why, one step back
4/**
5 * @typedef {Object} RevocableProxy6 * @property {any} proxy7 * @property {Function} revoke8 */9

Merge pull request #15 from mweststrate/feature/freezeMichel Weststratebefore adoption0d24494

line 10why, one step back
10const IMMER_PROXY = Symbol("immer-proxy") // TODO: create per closure, to avoid sharing proxies between multiple immer version

More repo setupMichel Weststratebefore adoption1637393

line 11why, one step back
11

Merge pull request #15 from mweststrate/feature/freezeMichel Weststratebefore adoption0d24494

lines 12–14why, one step back
12// This property indicates that the current object is cloned for another object,
13// to make sure the proxy of a frozen object is writeable14const CLONE_TARGET = Symbol("immer-clone-target")

Fixed bug, wrote readmeMichel Weststratebefore adoption1b8a694

line 15why, one step back
15

Merge pull request #15 from mweststrate/feature/freezeMichel Weststratebefore adoption0d24494

lines 16–17why, one step back
16let autoFreeze = true
17

More repo setupMichel Weststratebefore adoption1637393

line 18why, one step back
18/**

Merge pull request #9 from benbraou/typosMichel Weststratebefore adoptionae0182f

line 19why, one step back
19 * Immer takes a state, and runs a function against it.

More repo setupMichel Weststratebefore adoption1637393

lines 20–28why, one step back
20 * That function can freely mutate the state, as it will create copies-on-write.
21 * This means that the original state will stay unchanged, and once the function finishes, the modified state is returned22 *23 * @export24 * @param {any} baseState - the state to start with25 * @param {Function} thunk - function that receives a proxy of the base state as first argument and which can be freely modified26 * @returns {any} a new state, or the base state if nothing was modified27 */28function immer(baseState, thunk) {

Merge pull request #14 from benbraou/issue10Michel Weststratebefore adoptione775cca

lines 29–33why, one step back
29 /**
30 * Maps baseState objects to revocable proxies31 * @type {Map<Object,RevocableProxy>}32 */33 const revocableProxies = new Map()

Code cleanupMichel Weststratebefore adoption2b2d0cb

line 34why, one step back
34 // Maps baseState objects to their copies

Merge pull request #14 from benbraou/issue10Michel Weststratebefore adoptione775cca

line 35why, one step back
35

More repo setupMichel Weststratebefore adoption1637393

lines 36–39why, one step back
36 const copies = new Map()
3738 const objectTraps = {39 get(target, prop) {

Merge pull request #15 from mweststrate/feature/freezeMichel Weststratebefore adoption0d24494

line 40why, one step back
40 if (prop === IMMER_PROXY) return target

Code cleanupMichel Weststratebefore adoption2b2d0cb

line 41why, one step back
41 return createProxy(getCurrentSource(target)[prop])

More repo setupMichel Weststratebefore adoption1637393

lines 42–49why, one step back
42 },
43 has(target, prop) {44 return prop in getCurrentSource(target)45 },46 ownKeys(target) {47 return Reflect.ownKeys(getCurrentSource(target))48 },49 set(target, prop, value) {

Code cleanupMichel Weststratebefore adoption2b2d0cb

lines 50–51why, one step back
50 const current = createProxy(getCurrentSource(target)[prop])
51 const newValue = createProxy(value)

More repo setupMichel Weststratebefore adoption1637393

line 52why, one step back
52 if (current !== newValue) {

Add support for arraysMichel Weststratebefore adoptiond3696cb

line 53why, one step back
53 const copy = getOrCreateCopy(target)

Merge branch 'Gregjarvez-master'Michel Weststratebefore adoptiona151fed

line 54why, one step back
54 copy[prop] = isProxy(newValue)

Merge pull request #15 from mweststrate/feature/freezeMichel Weststratebefore adoption0d24494

line 55why, one step back
55 ? newValue[IMMER_PROXY]

Merge branch 'Gregjarvez-master'Michel Weststratebefore adoptiona151fed

line 56why, one step back
56 : newValue

More repo setupMichel Weststratebefore adoption1637393

lines 57–60why, one step back
57 }
58 return true59 },60 deleteProperty(target, property) {

Add support for arraysMichel Weststratebefore adoptiond3696cb

line 61why, one step back
61 const copy = getOrCreateCopy(target)

More repo setupMichel Weststratebefore adoption1637393

lines 62–63why, one step back
62 delete copy[property]
63 return true

Merge branch 'Gregjarvez-master'Michel Weststratebefore adoptiona151fed

line 64why, one step back
64 },

More repo setupMichel Weststratebefore adoption1637393

lines 65–66why, one step back
65 }
66

Code cleanupMichel Weststratebefore adoption2b2d0cb

lines 67–69why, one step back
67 // creates a copy for a base object if there ain't one
68 function getOrCreateCopy(base) {69 let copy = copies.get(base)

Merge pull request #15 from mweststrate/feature/freezeMichel Weststratebefore adoption0d24494

lines 70–75why, one step back
70 if (copy) return copy
71 const cloneTarget = base[CLONE_TARGET]72 if (cloneTarget) {73 // base is a clone already (source was frozen), no need to create addtional copy74 copies.set(cloneTarget, base)75 return base

More repo setupMichel Weststratebefore adoption1637393

line 76why, one step back
76 }

Merge pull request #15 from mweststrate/feature/freezeMichel Weststratebefore adoption0d24494

lines 77–79why, one step back
77 // create a fresh copy
78 copy = Array.isArray(base) ? base.slice() : Object.assign({}, base)79 copies.set(base, copy)

More repo setupMichel Weststratebefore adoption1637393

lines 80–82why, one step back
80 return copy
81 }82

Merge pull request #9 from benbraou/typosMichel Weststratebefore adoptionae0182f

line 83why, one step back
83 // returns the current source of truth for a base object

Code cleanupMichel Weststratebefore adoption2b2d0cb

lines 84–86why, one step back
84 function getCurrentSource(base) {
85 const copy = copies.get(base)86 return copy || base

More repo setupMichel Weststratebefore adoption1637393

line 87why, one step back
87 }

Merge pull request #15 from mweststrate/feature/freezeMichel Weststratebefore adoption0d24494

line 88why, one step back
88

Code cleanupMichel Weststratebefore adoption2b2d0cb

lines 89–91why, one step back
89 // creates a proxy for plain objects / arrays
90 function createProxy(base) {91 if (isPlainObject(base) || Array.isArray(base)) {

Fixed bug, wrote readmeMichel Weststratebefore adoption1b8a694

line 92why, one step back
92 if (isProxy(base)) return base // avoid double wrapping

Merge pull request #15 from mweststrate/feature/freezeMichel Weststratebefore adoption0d24494

lines 93–110why, one step back
93 if (revocableProxies.has(base))
94 return revocableProxies.get(base).proxy95 let proxyTarget96 // special case, if the base tree is frozen, we cannot modify it's proxy it in strict mode, clone first.97 if (Object.isFrozen(base)) {98 proxyTarget = Array.isArray(base)99 ? base.slice()100 : Object.assign({}, base)101 Object.defineProperty(proxyTarget, CLONE_TARGET, {102 enumerable: false,103 value: base,104 configurable: true,105 })106 } else {107 proxyTarget = base108 }109 // create the proxy110 const revocableProxy = Proxy.revocable(proxyTarget, objectTraps)

Merge pull request #14 from benbraou/issue10Michel Weststratebefore adoptione775cca

lines 111–112why, one step back
111 revocableProxies.set(base, revocableProxy)
112 return revocableProxy.proxy

Code cleanupMichel Weststratebefore adoption2b2d0cb

lines 113–114why, one step back
113 }
114 return base

More repo setupMichel Weststratebefore adoption1637393

lines 115–116why, one step back
115 }
116

Code cleanupMichel Weststratebefore adoption2b2d0cb

lines 117–119why, one step back
117 // checks if the given base object has modifications, either because it is modified, or
118 // because one of it's children is119 function hasChanges(base) {

Merge pull request #14 from benbraou/issue10Michel Weststratebefore adoptione775cca

line 120why, one step back
120 const proxy = revocableProxies.get(base)

More repo setupMichel Weststratebefore adoption1637393

lines 121–125why, one step back
121 if (!proxy) return false // nobody did read this object
122 if (copies.has(base)) return true // a copy was created, so there are changes123 // look deeper124 const keys = Object.keys(base)125 for (let i = 0; i < keys.length; i++) {

Fixed bug, wrote readmeMichel Weststratebefore adoption1b8a694

line 126why, one step back
126 const value = base[keys[i]]

Merge branch 'Gregjarvez-master'Michel Weststratebefore adoptiona151fed

lines 127–131why, one step back
127 if (
128 (Array.isArray(value) || isPlainObject(value)) &&129 hasChanges(value)130 )131 return true

More repo setupMichel Weststratebefore adoption1637393

lines 132–135why, one step back
132 }
133 return false134 }135

Code cleanupMichel Weststratebefore adoption2b2d0cb

lines 136–142why, one step back
136 // given a base object, returns it if unmodified, or return the changed cloned if modified
137 function finalize(base) {138 if (isPlainObject(base)) return finalizeObject(base)139 if (Array.isArray(base)) return finalizeArray(base)140 return base141 }142

More repo setupMichel Weststratebefore adoption1637393

line 143why, one step back
143 function finalizeObject(thing) {

Code cleanupMichel Weststratebefore adoption2b2d0cb

line 144why, one step back
144 if (!hasChanges(thing)) return thing

Merge pull request #15 from mweststrate/feature/freezeMichel Weststratebefore adoption0d24494

line 145why, one step back
145 const copy = getOrCreateCopy(thing) // TODO: getOrCreate is weird here..

More repo setupMichel Weststratebefore adoption1637393

line 146why, one step back
146 Object.keys(copy).forEach(prop => {

Code cleanupMichel Weststratebefore adoption2b2d0cb

line 147why, one step back
147 copy[prop] = finalize(copy[prop])

Add support for arraysMichel Weststratebefore adoptiond3696cb

line 148why, one step back
148 })

Merge pull request #15 from mweststrate/feature/freezeMichel Weststratebefore adoption0d24494

lines 149–150why, one step back
149 delete copy[CLONE_TARGET]
150 return freeze(copy)

Add support for arraysMichel Weststratebefore adoptiond3696cb

lines 151–153why, one step back
151 }
152153 function finalizeArray(thing) {

Code cleanupMichel Weststratebefore adoption2b2d0cb

line 154why, one step back
154 if (!hasChanges(thing)) return thing

Merge pull request #15 from mweststrate/feature/freezeMichel Weststratebefore adoption0d24494

line 155why, one step back
155 const copy = getOrCreateCopy(thing) // TODO: getOrCreate is weird here..

Add support for arraysMichel Weststratebefore adoptiond3696cb

line 156why, one step back
156 copy.forEach((value, index) => {

Code cleanupMichel Weststratebefore adoption2b2d0cb

line 157why, one step back
157 copy[index] = finalize(copy[index])

More repo setupMichel Weststratebefore adoption1637393

line 158why, one step back
158 })

Merge pull request #15 from mweststrate/feature/freezeMichel Weststratebefore adoption0d24494

lines 159–160why, one step back
159 delete copy[CLONE_TARGET]
160 return freeze(copy)

More repo setupMichel Weststratebefore adoption1637393

lines 161–162why, one step back
161 }
162

Code cleanupMichel Weststratebefore adoption2b2d0cb

lines 163–165why, one step back
163 // create proxy for root
164 const rootClone = createProxy(baseState)165 // execute the thunk

Merge branch 'Gregjarvez-master'Michel Weststratebefore adoptiona151fed

lines 166–171why, one step back
166 const maybeVoidReturn = thunk(rootClone)
167 //values either than undefined will trigger warning;168 !Object.is(maybeVoidReturn, undefined) &&169 console.warn(170 `Immer callback expects no return value. However ${typeof maybeVoidReturn} was returned`,171 )

Added performance measurements, fixes #6Michel Weststratebefore adoption553299f

line 172why, one step back
172 // console.log(`proxies: ${revocableProxies.size}, copies: ${copies.size}`)

Merge pull request #14 from benbraou/issue10Michel Weststratebefore adoptione775cca

lines 173–174why, one step back
173 // revoke all proxies
174 revoke(revocableProxies)

Code cleanupMichel Weststratebefore adoption2b2d0cb

lines 175–176why, one step back
175 // and finalize the modified proxy
176 return finalize(baseState)

Merge pull request #14 from benbraou/issue10Michel Weststratebefore adoptione775cca

lines 177–180why, one step back
177}
178179/**180 * Revoke all the proxies stored in the revocableProxies map

Merge pull request #15 from mweststrate/feature/freezeMichel Weststratebefore adoption0d24494

line 181why, one step back
181 *

Merge pull request #14 from benbraou/issue10Michel Weststratebefore adoptione775cca

lines 182–183why, one step back
182 * @param {Map<Object,RevocableProxy>} revocableProxies
183 */

Merge pull request #15 from mweststrate/feature/freezeMichel Weststratebefore adoption0d24494

line 184why, one step back
184function revoke(revocableProxies) {

Merge pull request #14 from benbraou/issue10Michel Weststratebefore adoptione775cca

lines 185–187why, one step back
185 for (var revocableProxy of revocableProxies.values()) {
186 revocableProxy.revoke()187 }

More repo setupMichel Weststratebefore adoption1637393

lines 188–193why, one step back
188}
189190function isPlainObject(value) {191 if (value === null || typeof value !== "object") return false192 const proto = Object.getPrototypeOf(value)193 return proto === Object.prototype || proto === null

Fixed bug, wrote readmeMichel Weststratebefore adoption1b8a694

lines 194–196why, one step back
194}
195196function isProxy(value) {

Merge pull request #15 from mweststrate/feature/freezeMichel Weststratebefore adoption0d24494

line 197why, one step back
197 return !!value && !!value[IMMER_PROXY]

More repo setupMichel Weststratebefore adoption1637393

lines 198–199why, one step back
198}
199

Merge pull request #15 from mweststrate/feature/freezeMichel Weststratebefore adoption0d24494

lines 200–223why, one step back
200function freeze(value) {
201 if (autoFreeze) {202 Object.freeze(value)203 }204 return value205}206207/**208 * Automatically freezes any state trees generated by immer.209 * This protects against accidental modifications of the state tree outside of an immer function.210 * This comes with a performance impact, so it is recommended to disable this option in production.211 * It is by default enabled.212 *213 * @returns {void}214 */215function setAutoFreeze(enableAutoFreeze) {216 autoFreeze = enableAutoFreeze217}218219Object.defineProperty(exports, "__esModule", {220 value: true,221})222module.exports.default = immer223module.exports.setAutoFreeze = setAutoFreeze