Skip to content
Myr

immer.js

This file

Path

immer.js

241 lines · 8.0 KiB · JavaScript

Last changed by

Merge pull request #33 from mweststrate/fix/32Michel Weststratebefore adoptionfae0957

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 #22 from mweststrate/feature/es5Michel Weststratebefore adoption4165abb

lines 4–8why, one step back
4if (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

Merge pull request #14 from benbraou/issue10Michel Weststratebefore adoptione775cca

lines 9–14why, one step back
9/**
10 * @typedef {Object} RevocableProxy11 * @property {any} proxy12 * @property {Function} revoke13 */14

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

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

More repo setupMichel Weststratebefore adoption1637393

line 16why, one step back
16

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

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

Fixed bug, wrote readmeMichel Weststratebefore adoption1b8a694

line 20why, one step back
20

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

lines 21–22why, one step back
21let autoFreeze = true
22

More repo setupMichel Weststratebefore adoption1637393

line 23why, one step back
23/**

Merge pull request #9 from benbraou/typosMichel Weststratebefore adoptionae0182f

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

More repo setupMichel Weststratebefore adoption1637393

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

Merge pull request #14 from benbraou/issue10Michel Weststratebefore adoptione775cca

lines 34–38why, one step back
34 /**
35 * Maps baseState objects to revocable proxies36 * @type {Map<Object,RevocableProxy>}37 */38 const revocableProxies = new Map()

Code cleanupMichel Weststratebefore adoption2b2d0cb

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

Merge pull request #14 from benbraou/issue10Michel Weststratebefore adoptione775cca

line 40why, one step back
40

More repo setupMichel Weststratebefore adoption1637393

lines 41–44why, one step back
41 const copies = new Map()
4243 const objectTraps = {44 get(target, prop) {

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

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

Code cleanupMichel Weststratebefore adoption2b2d0cb

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

More repo setupMichel Weststratebefore adoption1637393

lines 47–54why, one step back
47 },
48 has(target, prop) {49 return prop in getCurrentSource(target)50 },51 ownKeys(target) {52 return Reflect.ownKeys(getCurrentSource(target))53 },54 set(target, prop, value) {

Code cleanupMichel Weststratebefore adoption2b2d0cb

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

More repo setupMichel Weststratebefore adoption1637393

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

Add support for arraysMichel Weststratebefore adoptiond3696cb

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

Merge branch 'Gregjarvez-master'Michel Weststratebefore adoptiona151fed

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

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

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

Merge branch 'Gregjarvez-master'Michel Weststratebefore adoptiona151fed

line 61why, one step back
61 : newValue

More repo setupMichel Weststratebefore adoption1637393

lines 62–65why, one step back
62 }
63 return true64 },65 deleteProperty(target, property) {

Add support for arraysMichel Weststratebefore adoptiond3696cb

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

More repo setupMichel Weststratebefore adoption1637393

lines 67–68why, one step back
67 delete copy[property]
68 return true

Merge pull request #33 from mweststrate/fix/32Michel Weststratebefore adoptionfae0957

lines 69–81why, one step back
69 },
70 getOwnPropertyDescriptor(target, prop) {71 return Reflect.getOwnPropertyDescriptor(72 getCurrentSource(target),73 prop74 )75 },76 defineProperty(target, property, descriptor) {77 Object.defineProperty(getOrCreateCopy(target), property, descriptor)78 return true79 },80 setPrototypeOf() {81 throw new Error("Don't even try this...")

No trailing commas, might break babel, fixes #21Michel Weststratebefore adoption2a1da31

line 82why, one step back
82 }

More repo setupMichel Weststratebefore adoption1637393

lines 83–84why, one step back
83 }
84

Code cleanupMichel Weststratebefore adoption2b2d0cb

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

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

lines 88–93why, one step back
88 if (copy) return copy
89 const cloneTarget = base[CLONE_TARGET]90 if (cloneTarget) {91 // base is a clone already (source was frozen), no need to create addtional copy92 copies.set(cloneTarget, base)93 return base

More repo setupMichel Weststratebefore adoption1637393

line 94why, one step back
94 }

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

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

More repo setupMichel Weststratebefore adoption1637393

lines 98–100why, one step back
98 return copy
99 }100

Merge pull request #9 from benbraou/typosMichel Weststratebefore adoptionae0182f

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

Code cleanupMichel Weststratebefore adoption2b2d0cb

lines 102–104why, one step back
102 function getCurrentSource(base) {
103 const copy = copies.get(base)104 return copy || base

More repo setupMichel Weststratebefore adoption1637393

line 105why, one step back
105 }

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

line 106why, one step back
106

Code cleanupMichel Weststratebefore adoption2b2d0cb

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

Fixed bug, wrote readmeMichel Weststratebefore adoption1b8a694

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

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

lines 111–121why, one step back
111 if (revocableProxies.has(base))
112 return revocableProxies.get(base).proxy113 let proxyTarget114 // special case, if the base tree is frozen, we cannot modify it's proxy it in strict mode, clone first.115 if (Object.isFrozen(base)) {116 proxyTarget = Array.isArray(base)117 ? base.slice()118 : Object.assign({}, base)119 Object.defineProperty(proxyTarget, CLONE_TARGET, {120 enumerable: false,121 value: base,

No trailing commas, might break babel, fixes #21Michel Weststratebefore adoption2a1da31

line 122why, one step back
122 configurable: true

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

lines 123–128why, one step back
123 })
124 } else {125 proxyTarget = base126 }127 // create the proxy128 const revocableProxy = Proxy.revocable(proxyTarget, objectTraps)

Merge pull request #14 from benbraou/issue10Michel Weststratebefore adoptione775cca

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

Code cleanupMichel Weststratebefore adoption2b2d0cb

lines 131–132why, one step back
131 }
132 return base

More repo setupMichel Weststratebefore adoption1637393

lines 133–134why, one step back
133 }
134

Code cleanupMichel Weststratebefore adoption2b2d0cb

lines 135–137why, one step back
135 // checks if the given base object has modifications, either because it is modified, or
136 // because one of it's children is137 function hasChanges(base) {

Merge pull request #14 from benbraou/issue10Michel Weststratebefore adoptione775cca

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

More repo setupMichel Weststratebefore adoption1637393

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

Fixed bug, wrote readmeMichel Weststratebefore adoption1b8a694

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

Merge branch 'Gregjarvez-master'Michel Weststratebefore adoptiona151fed

lines 145–149why, one step back
145 if (
146 (Array.isArray(value) || isPlainObject(value)) &&147 hasChanges(value)148 )149 return true

More repo setupMichel Weststratebefore adoption1637393

lines 150–153why, one step back
150 }
151 return false152 }153

Code cleanupMichel Weststratebefore adoption2b2d0cb

lines 154–160why, one step back
154 // given a base object, returns it if unmodified, or return the changed cloned if modified
155 function finalize(base) {156 if (isPlainObject(base)) return finalizeObject(base)157 if (Array.isArray(base)) return finalizeArray(base)158 return base159 }160

More repo setupMichel Weststratebefore adoption1637393

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

Code cleanupMichel Weststratebefore adoption2b2d0cb

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

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

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

More repo setupMichel Weststratebefore adoption1637393

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

Code cleanupMichel Weststratebefore adoption2b2d0cb

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

Add support for arraysMichel Weststratebefore adoptiond3696cb

line 166why, one step back
166 })

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

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

Add support for arraysMichel Weststratebefore adoptiond3696cb

lines 169–171why, one step back
169 }
170171 function finalizeArray(thing) {

Code cleanupMichel Weststratebefore adoption2b2d0cb

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

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

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

Add support for arraysMichel Weststratebefore adoptiond3696cb

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

Code cleanupMichel Weststratebefore adoption2b2d0cb

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

More repo setupMichel Weststratebefore adoption1637393

line 176why, one step back
176 })

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

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

More repo setupMichel Weststratebefore adoption1637393

lines 179–180why, one step back
179 }
180

Code cleanupMichel Weststratebefore adoption2b2d0cb

lines 181–183why, one step back
181 // create proxy for root
182 const rootClone = createProxy(baseState)183 // execute the thunk

Merge branch 'Gregjarvez-master'Michel Weststratebefore adoptiona151fed

lines 184–187why, one step back
184 const maybeVoidReturn = thunk(rootClone)
185 //values either than undefined will trigger warning;186 !Object.is(maybeVoidReturn, undefined) &&187 console.warn(

Merge pull request #21 from sallyhill/patch-1Michel Weststratebefore adoptionc8718e7

line 188why, one step back
188 `Immer callback expects no return value. However ${typeof maybeVoidReturn} was returned`

Merge branch 'Gregjarvez-master'Michel Weststratebefore adoptiona151fed

line 189why, one step back
189 )

Added performance measurements, fixes #6Michel Weststratebefore adoption553299f

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

Merge pull request #14 from benbraou/issue10Michel Weststratebefore adoptione775cca

lines 191–192why, one step back
191 // revoke all proxies
192 revoke(revocableProxies)

Code cleanupMichel Weststratebefore adoption2b2d0cb

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

Merge pull request #14 from benbraou/issue10Michel Weststratebefore adoptione775cca

lines 195–198why, one step back
195}
196197/**198 * Revoke all the proxies stored in the revocableProxies map

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

line 199why, one step back
199 *

Merge pull request #14 from benbraou/issue10Michel Weststratebefore adoptione775cca

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

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

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

Merge pull request #14 from benbraou/issue10Michel Weststratebefore adoptione775cca

lines 203–205why, one step back
203 for (var revocableProxy of revocableProxies.values()) {
204 revocableProxy.revoke()205 }

More repo setupMichel Weststratebefore adoption1637393

lines 206–211why, one step back
206}
207208function isPlainObject(value) {209 if (value === null || typeof value !== "object") return false210 const proto = Object.getPrototypeOf(value)211 return proto === Object.prototype || proto === null

Fixed bug, wrote readmeMichel Weststratebefore adoption1b8a694

lines 212–214why, one step back
212}
213214function isProxy(value) {

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

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

More repo setupMichel Weststratebefore adoption1637393

lines 216–217why, one step back
216}
217

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

lines 218–237why, one step back
218function freeze(value) {
219 if (autoFreeze) {220 Object.freeze(value)221 }222 return value223}224225/**226 * Automatically freezes any state trees generated by immer.227 * This protects against accidental modifications of the state tree outside of an immer function.228 * This comes with a performance impact, so it is recommended to disable this option in production.229 * It is by default enabled.230 *231 * @returns {void}232 */233function setAutoFreeze(enableAutoFreeze) {234 autoFreeze = enableAutoFreeze235}236237Object.defineProperty(exports, "__esModule", {

No trailing commas, might break babel, fixes #21Michel Weststratebefore adoption2a1da31

line 238why, one step back
238 value: true

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

lines 239–241why, one step back
239})
240module.exports.default = immer241module.exports.setAutoFreeze = setAutoFreeze