Skip to content
Myr

immer.js

This file

Path

immer.js

234 lines · 7.7 KiB · JavaScript

Last changed by

improved test setupMichel Weststratebefore adoption6990c33

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

improved test setupMichel Weststratebefore adoption6990c33

lines 69–74why, one step back
69 },
70 getOwnPropertyDescriptor(target, prop) {71 return Reflect.getOwnPropertyDescriptor(72 getCurrentSource(target),73 prop74 )

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

line 75why, one step back
75 }

More repo setupMichel Weststratebefore adoption1637393

lines 76–77why, one step back
76 }
77

Code cleanupMichel Weststratebefore adoption2b2d0cb

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

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

lines 81–86why, one step back
81 if (copy) return copy
82 const cloneTarget = base[CLONE_TARGET]83 if (cloneTarget) {84 // base is a clone already (source was frozen), no need to create addtional copy85 copies.set(cloneTarget, base)86 return base

More repo setupMichel Weststratebefore adoption1637393

line 87why, one step back
87 }

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

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

More repo setupMichel Weststratebefore adoption1637393

lines 91–93why, one step back
91 return copy
92 }93

Merge pull request #9 from benbraou/typosMichel Weststratebefore adoptionae0182f

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

Code cleanupMichel Weststratebefore adoption2b2d0cb

lines 95–97why, one step back
95 function getCurrentSource(base) {
96 const copy = copies.get(base)97 return copy || base

More repo setupMichel Weststratebefore adoption1637393

line 98why, one step back
98 }

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

line 99why, one step back
99

Code cleanupMichel Weststratebefore adoption2b2d0cb

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

Fixed bug, wrote readmeMichel Weststratebefore adoption1b8a694

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

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

lines 104–114why, one step back
104 if (revocableProxies.has(base))
105 return revocableProxies.get(base).proxy106 let proxyTarget107 // special case, if the base tree is frozen, we cannot modify it's proxy it in strict mode, clone first.108 if (Object.isFrozen(base)) {109 proxyTarget = Array.isArray(base)110 ? base.slice()111 : Object.assign({}, base)112 Object.defineProperty(proxyTarget, CLONE_TARGET, {113 enumerable: false,114 value: base,

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

line 115why, one step back
115 configurable: true

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

lines 116–121why, one step back
116 })
117 } else {118 proxyTarget = base119 }120 // create the proxy121 const revocableProxy = Proxy.revocable(proxyTarget, objectTraps)

Merge pull request #14 from benbraou/issue10Michel Weststratebefore adoptione775cca

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

Code cleanupMichel Weststratebefore adoption2b2d0cb

lines 124–125why, one step back
124 }
125 return base

More repo setupMichel Weststratebefore adoption1637393

lines 126–127why, one step back
126 }
127

Code cleanupMichel Weststratebefore adoption2b2d0cb

lines 128–130why, one step back
128 // checks if the given base object has modifications, either because it is modified, or
129 // because one of it's children is130 function hasChanges(base) {

Merge pull request #14 from benbraou/issue10Michel Weststratebefore adoptione775cca

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

More repo setupMichel Weststratebefore adoption1637393

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

Fixed bug, wrote readmeMichel Weststratebefore adoption1b8a694

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

Merge branch 'Gregjarvez-master'Michel Weststratebefore adoptiona151fed

lines 138–142why, one step back
138 if (
139 (Array.isArray(value) || isPlainObject(value)) &&140 hasChanges(value)141 )142 return true

More repo setupMichel Weststratebefore adoption1637393

lines 143–146why, one step back
143 }
144 return false145 }146

Code cleanupMichel Weststratebefore adoption2b2d0cb

lines 147–153why, one step back
147 // given a base object, returns it if unmodified, or return the changed cloned if modified
148 function finalize(base) {149 if (isPlainObject(base)) return finalizeObject(base)150 if (Array.isArray(base)) return finalizeArray(base)151 return base152 }153

More repo setupMichel Weststratebefore adoption1637393

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

Code cleanupMichel Weststratebefore adoption2b2d0cb

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

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

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

More repo setupMichel Weststratebefore adoption1637393

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

Code cleanupMichel Weststratebefore adoption2b2d0cb

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

Add support for arraysMichel Weststratebefore adoptiond3696cb

line 159why, one step back
159 })

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

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

Add support for arraysMichel Weststratebefore adoptiond3696cb

lines 162–164why, one step back
162 }
163164 function finalizeArray(thing) {

Code cleanupMichel Weststratebefore adoption2b2d0cb

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

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

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

Add support for arraysMichel Weststratebefore adoptiond3696cb

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

Code cleanupMichel Weststratebefore adoption2b2d0cb

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

More repo setupMichel Weststratebefore adoption1637393

line 169why, one step back
169 })

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

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

More repo setupMichel Weststratebefore adoption1637393

lines 172–173why, one step back
172 }
173

Code cleanupMichel Weststratebefore adoption2b2d0cb

lines 174–176why, one step back
174 // create proxy for root
175 const rootClone = createProxy(baseState)176 // execute the thunk

Merge branch 'Gregjarvez-master'Michel Weststratebefore adoptiona151fed

lines 177–180why, one step back
177 const maybeVoidReturn = thunk(rootClone)
178 //values either than undefined will trigger warning;179 !Object.is(maybeVoidReturn, undefined) &&180 console.warn(

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

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

Merge branch 'Gregjarvez-master'Michel Weststratebefore adoptiona151fed

line 182why, one step back
182 )

Added performance measurements, fixes #6Michel Weststratebefore adoption553299f

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

Merge pull request #14 from benbraou/issue10Michel Weststratebefore adoptione775cca

lines 184–185why, one step back
184 // revoke all proxies
185 revoke(revocableProxies)

Code cleanupMichel Weststratebefore adoption2b2d0cb

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

Merge pull request #14 from benbraou/issue10Michel Weststratebefore adoptione775cca

lines 188–191why, one step back
188}
189190/**191 * Revoke all the proxies stored in the revocableProxies map

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

line 192why, one step back
192 *

Merge pull request #14 from benbraou/issue10Michel Weststratebefore adoptione775cca

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

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

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

Merge pull request #14 from benbraou/issue10Michel Weststratebefore adoptione775cca

lines 196–198why, one step back
196 for (var revocableProxy of revocableProxies.values()) {
197 revocableProxy.revoke()198 }

More repo setupMichel Weststratebefore adoption1637393

lines 199–204why, one step back
199}
200201function isPlainObject(value) {202 if (value === null || typeof value !== "object") return false203 const proto = Object.getPrototypeOf(value)204 return proto === Object.prototype || proto === null

Fixed bug, wrote readmeMichel Weststratebefore adoption1b8a694

lines 205–207why, one step back
205}
206207function isProxy(value) {

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

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

More repo setupMichel Weststratebefore adoption1637393

lines 209–210why, one step back
209}
210

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

lines 211–230why, one step back
211function freeze(value) {
212 if (autoFreeze) {213 Object.freeze(value)214 }215 return value216}217218/**219 * Automatically freezes any state trees generated by immer.220 * This protects against accidental modifications of the state tree outside of an immer function.221 * This comes with a performance impact, so it is recommended to disable this option in production.222 * It is by default enabled.223 *224 * @returns {void}225 */226function setAutoFreeze(enableAutoFreeze) {227 autoFreeze = enableAutoFreeze228}229230Object.defineProperty(exports, "__esModule", {

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

line 231why, one step back
231 value: true

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

lines 232–234why, one step back
232})
233module.exports.default = immer234module.exports.setAutoFreeze = setAutoFreeze