Skip to content
Myr

immer.js

This file

Path

immer.js

228 lines · 7.5 KiB · JavaScript

Last changed by

Merge pull request #22 from mweststrate/feature/es5Michel Weststratebefore adoption4165abb

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

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

line 69why, one step back
69 }

More repo setupMichel Weststratebefore adoption1637393

lines 70–71why, one step back
70 }
71

Code cleanupMichel Weststratebefore adoption2b2d0cb

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

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

lines 75–80why, one step back
75 if (copy) return copy
76 const cloneTarget = base[CLONE_TARGET]77 if (cloneTarget) {78 // base is a clone already (source was frozen), no need to create addtional copy79 copies.set(cloneTarget, base)80 return base

More repo setupMichel Weststratebefore adoption1637393

line 81why, one step back
81 }

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

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

More repo setupMichel Weststratebefore adoption1637393

lines 85–87why, one step back
85 return copy
86 }87

Merge pull request #9 from benbraou/typosMichel Weststratebefore adoptionae0182f

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

Code cleanupMichel Weststratebefore adoption2b2d0cb

lines 89–91why, one step back
89 function getCurrentSource(base) {
90 const copy = copies.get(base)91 return copy || base

More repo setupMichel Weststratebefore adoption1637393

line 92why, one step back
92 }

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

line 93why, one step back
93

Code cleanupMichel Weststratebefore adoption2b2d0cb

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

Fixed bug, wrote readmeMichel Weststratebefore adoption1b8a694

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

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

lines 98–108why, one step back
98 if (revocableProxies.has(base))
99 return revocableProxies.get(base).proxy100 let proxyTarget101 // special case, if the base tree is frozen, we cannot modify it's proxy it in strict mode, clone first.102 if (Object.isFrozen(base)) {103 proxyTarget = Array.isArray(base)104 ? base.slice()105 : Object.assign({}, base)106 Object.defineProperty(proxyTarget, CLONE_TARGET, {107 enumerable: false,108 value: base,

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

line 109why, one step back
109 configurable: true

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

lines 110–115why, one step back
110 })
111 } else {112 proxyTarget = base113 }114 // create the proxy115 const revocableProxy = Proxy.revocable(proxyTarget, objectTraps)

Merge pull request #14 from benbraou/issue10Michel Weststratebefore adoptione775cca

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

Code cleanupMichel Weststratebefore adoption2b2d0cb

lines 118–119why, one step back
118 }
119 return base

More repo setupMichel Weststratebefore adoption1637393

lines 120–121why, one step back
120 }
121

Code cleanupMichel Weststratebefore adoption2b2d0cb

lines 122–124why, one step back
122 // checks if the given base object has modifications, either because it is modified, or
123 // because one of it's children is124 function hasChanges(base) {

Merge pull request #14 from benbraou/issue10Michel Weststratebefore adoptione775cca

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

More repo setupMichel Weststratebefore adoption1637393

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

Fixed bug, wrote readmeMichel Weststratebefore adoption1b8a694

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

Merge branch 'Gregjarvez-master'Michel Weststratebefore adoptiona151fed

lines 132–136why, one step back
132 if (
133 (Array.isArray(value) || isPlainObject(value)) &&134 hasChanges(value)135 )136 return true

More repo setupMichel Weststratebefore adoption1637393

lines 137–140why, one step back
137 }
138 return false139 }140

Code cleanupMichel Weststratebefore adoption2b2d0cb

lines 141–147why, one step back
141 // given a base object, returns it if unmodified, or return the changed cloned if modified
142 function finalize(base) {143 if (isPlainObject(base)) return finalizeObject(base)144 if (Array.isArray(base)) return finalizeArray(base)145 return base146 }147

More repo setupMichel Weststratebefore adoption1637393

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

Code cleanupMichel Weststratebefore adoption2b2d0cb

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

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

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

More repo setupMichel Weststratebefore adoption1637393

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

Code cleanupMichel Weststratebefore adoption2b2d0cb

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

Add support for arraysMichel Weststratebefore adoptiond3696cb

line 153why, one step back
153 })

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

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

Add support for arraysMichel Weststratebefore adoptiond3696cb

lines 156–158why, one step back
156 }
157158 function finalizeArray(thing) {

Code cleanupMichel Weststratebefore adoption2b2d0cb

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

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

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

Add support for arraysMichel Weststratebefore adoptiond3696cb

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

Code cleanupMichel Weststratebefore adoption2b2d0cb

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

More repo setupMichel Weststratebefore adoption1637393

line 163why, one step back
163 })

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

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

More repo setupMichel Weststratebefore adoption1637393

lines 166–167why, one step back
166 }
167

Code cleanupMichel Weststratebefore adoption2b2d0cb

lines 168–170why, one step back
168 // create proxy for root
169 const rootClone = createProxy(baseState)170 // execute the thunk

Merge branch 'Gregjarvez-master'Michel Weststratebefore adoptiona151fed

lines 171–174why, one step back
171 const maybeVoidReturn = thunk(rootClone)
172 //values either than undefined will trigger warning;173 !Object.is(maybeVoidReturn, undefined) &&174 console.warn(

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

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

Merge branch 'Gregjarvez-master'Michel Weststratebefore adoptiona151fed

line 176why, one step back
176 )

Added performance measurements, fixes #6Michel Weststratebefore adoption553299f

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

Merge pull request #14 from benbraou/issue10Michel Weststratebefore adoptione775cca

lines 178–179why, one step back
178 // revoke all proxies
179 revoke(revocableProxies)

Code cleanupMichel Weststratebefore adoption2b2d0cb

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

Merge pull request #14 from benbraou/issue10Michel Weststratebefore adoptione775cca

lines 182–185why, one step back
182}
183184/**185 * Revoke all the proxies stored in the revocableProxies map

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

line 186why, one step back
186 *

Merge pull request #14 from benbraou/issue10Michel Weststratebefore adoptione775cca

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

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

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

Merge pull request #14 from benbraou/issue10Michel Weststratebefore adoptione775cca

lines 190–192why, one step back
190 for (var revocableProxy of revocableProxies.values()) {
191 revocableProxy.revoke()192 }

More repo setupMichel Weststratebefore adoption1637393

lines 193–198why, one step back
193}
194195function isPlainObject(value) {196 if (value === null || typeof value !== "object") return false197 const proto = Object.getPrototypeOf(value)198 return proto === Object.prototype || proto === null

Fixed bug, wrote readmeMichel Weststratebefore adoption1b8a694

lines 199–201why, one step back
199}
200201function isProxy(value) {

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

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

More repo setupMichel Weststratebefore adoption1637393

lines 203–204why, one step back
203}
204

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

lines 205–224why, one step back
205function freeze(value) {
206 if (autoFreeze) {207 Object.freeze(value)208 }209 return value210}211212/**213 * Automatically freezes any state trees generated by immer.214 * This protects against accidental modifications of the state tree outside of an immer function.215 * This comes with a performance impact, so it is recommended to disable this option in production.216 * It is by default enabled.217 *218 * @returns {void}219 */220function setAutoFreeze(enableAutoFreeze) {221 autoFreeze = enableAutoFreeze222}223224Object.defineProperty(exports, "__esModule", {

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

line 225why, one step back
225 value: true

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

lines 226–228why, one step back
226})
227module.exports.default = immer228module.exports.setAutoFreeze = setAutoFreeze