Some dots
Before adoption: this commit came in with the history the project adopted, so no landing records it.
authored by Michel Weststrate · committed by Michel Weststrate · parent 198e05f · Browse files · 16 files·+308 added−72 removed
This commit
State
Before adoption: this commit came in with the history the project adopted, so no landing records it.
Diff stats
16 files+308 added−72 removed
- tests:+120 added−0 removed
- other:+188 added−72 removed
Provenance
- Commit
4e438d0- Tree
7c46462- Author
Michel Weststrate <mweststrate@fb.com>- Committer
Michel Weststrate <mweststrate@fb.com>- Parent
198e05f
16 files changed+308 added−72 removed
modified:__tests__/base.js+93 added
2237 unmodified lines2238 expect(state._bar).toEqual(0)2239 expect(state.bar).toEqual(0)2240 })2241 })2242+2243+ describe("setter only", () => {2244+ let setterCalled = 02245+ class State {2246+ [immerable] = true2247+ x = 02248+ set y(value) {2249+ setterCalled++2250+ this.x = value2251+ }2252+ }2253+2254+ const state = new State()2255+ const next = produce(state, draft => {2256+ expect(draft.y).toBeUndefined()2257+ draft.y = 2 // setter is inherited, so works2258+ expect(draft.x).toBe(2)2259+ })2260+ expect(setterCalled).toBe(1)2261+ expect(next.x).toBe(2)2262+ expect(state.x).toBe(0)2263+ })2264+2265+ describe("getter only", () => {2266+ let getterCalled = 02267+ class State {2268+ [immerable] = true2269+ x = 02270+ get y() {2271+ getterCalled++2272+ return this.x2273+ }2274+ }2275+2276+ const state = new State()2277+ const next = produce(state, draft => {2278+ expect(draft.y).toBe(0)2279+ expect(() => {2280+ draft.y = 22281+ }).toThrow("Cannot set property y")2282+ draft.x = 22283+ expect(draft.y).toBe(2)2284+ })2285+ expect(next.x).toBe(2)2286+ expect(next.y).toBe(2)2287+ expect(state.x).toBe(0)2288+ })2289+2290+ describe("own setter only", () => {2291+ let setterCalled = 02292+ const state = {2293+ x: 0,2294+ set y(value) {2295+ setterCalled++2296+ this.x = value2297+ }2298+ }2299+2300+ const next = produce(state, draft => {2301+ expect(draft.y).toBeUndefined()2302+ // setter is not preserved, so we can write2303+ draft.y = 22304+ expect(draft.x).toBe(0)2305+ expect(draft.y).toBe(2)2306+ })2307+ expect(setterCalled).toBe(0)2308+ expect(next.x).toBe(0)2309+ expect(next.y).toBe(2)2310+ expect(state.x).toBe(0)2311+ })2312+2313+ describe("own getter only", () => {2314+ let getterCalled = 02315+ const state = {2316+ x: 0,2317+ get y() {2318+ getterCalled++2319+ return this.x2320+ }2321+ }2322+2323+ const next = produce(state, draft => {2324+ expect(draft.y).toBe(0)2325+ // de-referenced, so stores it locally2326+ draft.y = 22327+ expect(draft.y).toBe(2)2328+ expect(draft.x).toBe(0)2329+ })2330+ expect(getterCalled).not.toBe(1)2331+ expect(next.x).toBe(0)2332+ expect(next.y).toBe(2)2333+ expect(state.x).toBe(0)2334+ })2335 }2336 2337 function testLiteralTypes(produce) {2338 class Foo {}68 unmodified linesmodified:__tests__/readme.js+27 added
232 unmodified lines233 expect(usersById_v1.size).toBe(0)234 // And trying to change a Map outside a producers is going to: NO!235 expect(() => usersById_v3.clear()).toThrowErrorMatchingSnapshot()236 })237+238+test("clock class", () => {239+ class Clock {240+ [immerable] = true241+242+ constructor(hour, minute) {243+ this.hour = hour244+ this.minute = minute245+ }246+247+ get time() {248+ return `${this.hour}:${this.minute}`249+ }250+251+ tick() {252+ return produce(this, draft => {253+ draft.minute++254+ })255+ }256+ }257+258+ const clock1 = new Clock(12, 10)259+ const clock2 = clock1.tick()260+ expect(clock1.time).toEqual("12:10") // 12:10261+ expect(clock2.time).toEqual("12:11") // 12:11262+ expect(clock2).toBeInstanceOf(Clock)263+})modified:docs/api.md+1 added
10 unmodified lines11121314151617181930 unmodified lines10 unmodified lines| `applyPatches` | Given a base state or draft, and a set of patches, applies the patches | [Patches](patches.md) || `castDraft` | Converts any immutable type to its mutable counterpart. This is just a cast and doesn't actually do anything. | [TypeScript](typescript.md) || `castImmutable` | Converts any mutable type to its immutable counterpart. This is just a cast and doesn't actually do anything. | [TypeScript](typescript.md) || `createDraft` | Given a base state, creates a mutable draft for which any modifications will be recorded | [Async](async.md) || `current` | Given a draft object (doesn't have to be a tree root), takes a snapshot of the current state of the draft | [Current](current.md) || `Draft<T>` | Exposed TypeScript type to convert an immutable type to a mutable type | [TypeScript](typescript.md) || `enableAllPlugins()` | Enables all plugins mentioned below | [Installation](installation#pick-your-immer-version) || `enableES5()` | Enables support for older JavaScript engines, such as Internet Explorer and React Native | [Installation](installation#pick-your-immer-version) || `enableMapSet()` | Enables support for `Map` and `Set` collections. | [Installation](installation#pick-your-immer-version) |30 unmodified linesmodified:docs/complex-objects.md+47 added-54 removed
12334567889101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657101112136 unmodified lines2021222372242574262728762930317832333435363738394041424344454647484950515253545556575859606162636465666768697071---id: complex-objectstitle: Working with Map, Set and classestitle: Classes---
<div id="codefund"><!-- fallback content --></div>
_⚠ Since version 6 support for `Map`s and `Set`s has to be enabled explicitly by calling [`enableMapSet()`](installation#pick-your-immer-version) once when starting your application._Plain objects (objects without a prototype), arrays, `Map`s and `Set`s are always drafted by Immer. Every other object must use the `immerable` symbol to mark itself as compatible with Immer. When one of these objects is mutated within a producer, its prototype is preserved between copies.
Plain objects, arrays, `Map`s and `Set`s are always drafted by Immer. An example of using Maps with immer:
```javascripttest("Producers can update Maps", () => { const usersById_v1 = new Map()
const usersById_v2 = produce(usersById_v1, draft => { // Modifying a map results in a new map draft.set("michel", {name: "Michel Weststrate", country: "NL"}) })
const usersById_v3 = produce(usersById_v2, draft => { // Making a change deep inside a map, results in a new map as well! draft.get("michel").country = "UK" })
// We got a new map each time! expect(usersById_v2).not.toBe(usersById_v1) expect(usersById_v3).not.toBe(usersById_v2) // With different content obviously expect(usersById_v1).toMatchInlineSnapshot(`Map {}`) expect(usersById_v2).toMatchInlineSnapshot(` Map { "michel" => Object { "country": "NL", "name": "Michel Weststrate", }, } `) expect(usersById_v3).toMatchInlineSnapshot(` Map { "michel" => Object { "country": "UK", "name": "Michel Weststrate", }, } `) // The old one was never modified expect(usersById_v1.size).toBe(0) // And trying to change a Map outside a producers is going to: NO! expect(() => usersById_v3.clear()).toThrowErrorMatchingInlineSnapshot( `"This object has been frozen and should not be mutated"` )})```
Every other object must use the `immerable` symbol to mark itself as compatible with Immer. When one of these objects is mutated within a producer, its prototype is preserved between copies.
```jsimport {immerable} from "immer"
class Foo {6 unmodified lines
Foo[immerable] = true // Option 3```
For arrays, only numeric properties and the `length` property can be mutated. Custom properties are not preserved on arrays.### Example
When working with `Date` objects, you should always create a new `Date` instance instead of mutating an existing `Date` object.```jsimport {immerable, produce} from "immer"
Maps and Sets that are produced by Immer will be made artificially immutable. This means that they will throw an exception when trying mutative methods like `set`, `clear` etc. outside a producer.class Clock { [immerable] = true
_Note: The **keys** of a map are never drafted! This is done to avoid confusing semantics and keep keys always referentially equal_ constructor(hour, minute) { this.hour = hour this.minute = minute }
get time() { return `${this.hour}:${minute}` }
tick() { return produce(this, draft => { draft.minute++ }) }}
const clock1 = new Clock(12, 10)const clock2 = clock1.tick()console.log(clock1.time) // 12:10console.log(clock2.time) // 12:11console.log(clock2 instanceof Clock) // true```
### Semantics in detail
The semantics on how classes are drafted are as follows:
1. A draft of a class is a fresh object but with the same prototype as the original object.2. When creating a draft, Immer will copy all _own_ properties from the base to the draft.This includes non-enumerable and symbolic properties.3. _Own_ getters will be invoked during the copy process, just like `Object.assign` would.4. Inherited getters and methods will remain as is and be inherited by the draft.5. Immer will not invoke constructor functions.6. The final instance will be constructed with the same mechanism as the draft was created.7. Only getters that have a setter as well will be writable in the draft, as otherwise the value can't be copied back.
Because Immer will dereference own getters of objects into normal properties, it is possible to use objects that use getter/setter traps on their fields, like MobX and Vue do.
Immer does not support exotic objects such as DOM Nodes or Buffers.
So when working for example with `Date` objects, you should always create a new `Date` instance instead of mutating an existing `Date` object.added:docs/current.md+56 added
1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556---id: currenttitle: Extracting the current state from a draftsidebar_label: Current---
<div id="codefund"><!-- fallback content --></div>
Immer exposes a named export `current` that create a copy of the current state of the draft. This can be very useful for debugging purposes (as those objects won't be Proxy objects and not be logged as such). Also, references to `current` can be safely leaked from a produce function. Put differently, `current` provides a snapshot of the current state of a draft.
Objects generated by `current` work similar to the objects created by produce itself.
1. Unmodified objects will be structurally shared with the original objects.1. If no changes are made to a draft, generally it holds that `original(draft) === current(draft)`, but this is not guaranteed.1. Future changes to the draft won't be reflected in the object produced by `current` (except for references to undraftable objects)1. Unlinke `produce` objects created by `current` will _not_ be frozen.
Use `current` sparingly, it can be a potentially expensive operation, especially when using ES5.
Note that `current` cannot be invoked on objects that aren't drafts.
### Example
The following example shows the effect of `current` (and `original`):
```jsconst base = { x: 0}
const next = produce(base, draft => { draft.x++ const orig = original(draft) const copy = current(draft) console.log(orig.x) console.log(copy.x)
setTimeout(() => { // this will execute after the produce has finised! console.log(orig.x) console.log(copy.x) }, 100)
draft.x++ console.log(draft.x)})console.log(next.x)
// This will print// 0 (orig.x)// 1 (copy.x)// 2 (draft.x)// 2 (next.x)// 0 (after timeout, orig.x)// 1 (after timeout, copy.x)```modified:docs/freezing.md+2 added
14 unmodified lines1516171819202114 unmodified lines</details>
Immer automatically freezes any state trees that are modified using `produce`. This protects against accidental modifications of the state tree outside of a producer. This comes with a performance impact, so it is recommended to disable this option in production. By default, it is turned on during local development and turned off in production. Use `setAutoFreeze(true / false)` to explicitly turn this feature on or off.
Immer will never freeze (the contents of) non-enumerable, non-own or symbolic properties, unless their content was drafted.
_⚠️ If auto freezing is enabled, recipes are not entirely side-effect free: Any plain object or array that ends up in the produced result, will be frozen, even when these objects were not frozen before the start of the producer! ⚠️_modified:docs/installation.md+7 added-7 removed
10 unmodified lines11 - NPM: `npm install immer`12 - CDN: Exposed global is `immer`13 - Unpkg: `<script src="https://unpkg.com/immer"></script>`14 - JSDelivr: `<script src="https://cdn.jsdelivr.net/npm/immer"></script>`15- - ⚠️ When using a CDN, it is best to check the url in your browser and see what version it resolves to, so that your users aren't accidentally served a newer version in the future when updates are release. So use an url like: https://unpkg.com/immer@6.0.3/dist/immer.umd.production.min.js instead. Substitute `production.min` with `development` in the URL for a development build. 15+ - ⚠️ When using a CDN, it is best to check the url in your browser and see what version it resolves to, so that your users aren't accidentally served a newer version in the future when updates are release. So use an url like: https://unpkg.com/immer@6.0.3/dist/immer.umd.production.min.js instead. Substitute `production.min` with `development` in the URL for a development build.16 17 ## Pick your Immer version18 19 _This section only applies to version 6 and later_38 unmodified lines58 Import size report for immer:59 ┌───────────────────────┬───────────┬────────────┬───────────┐60 │ (index) │ just this │ cumulative │ increment │61 ├───────────────────────┼───────────┼────────────┼───────────┤62-│ import * from 'immer' │ 5606 │ 0 │ 0 │63-│ produce │ 3085 │ 3085 │ 0 │64-│ enableES5 │ 3870 │ 3878 │ 793 │65-│ enableMapSet │ 3893 │ 4654 │ 776 │66-│ enablePatches │ 3826 │ 5387 │ 733 │67-│ enableAllPlugins │ 5382 │ 5421 │ 34 │62+│ import * from 'immer' │ 5662 │ 0 │ 0 │63+│ produce │ 3100 │ 3100 │ 0 │64+│ enableES5 │ 3761 │ 3770 │ 670 │65+│ enableMapSet │ 3885 │ 4527 │ 757 │66+│ enablePatches │ 3891 │ 5301 │ 774 │67+│ enableAllPlugins │ 5297 │ 5348 │ 47 │68 └───────────────────────┴───────────┴────────────┴───────────┘69 (this report was generated by npmjs.com/package/import-size)70 ```71 5 unmodified linesadded:docs/map-set.md+58 added
1+---2+id: map-set3+title: Map and Set4+---5+6+<div id="codefund"><!-- fallback content --></div>7+8+_⚠ Since version 6 support for `Map`s and `Set`s has to be enabled explicitly by calling [`enableMapSet()`](installation#pick-your-immer-version) once when starting your application._9+10+Plain objects, arrays, `Map`s and `Set`s are always drafted by Immer. An example of using Maps with immer:11+12+```javascript13+test("Producers can update Maps", () => {14+ const usersById_v1 = new Map()15+16+ const usersById_v2 = produce(usersById_v1, draft => {17+ // Modifying a map results in a new map18+ draft.set("michel", {name: "Michel Weststrate", country: "NL"})19+ })20+21+ const usersById_v3 = produce(usersById_v2, draft => {22+ // Making a change deep inside a map, results in a new map as well!23+ draft.get("michel").country = "UK"24+ })25+26+ // We got a new map each time!27+ expect(usersById_v2).not.toBe(usersById_v1)28+ expect(usersById_v3).not.toBe(usersById_v2)29+ // With different content obviously30+ expect(usersById_v1).toMatchInlineSnapshot(`Map {}`)31+ expect(usersById_v2).toMatchInlineSnapshot(`32+ Map {33+ "michel" => Object {34+ "country": "NL",35+ "name": "Michel Weststrate",36+ },37+ }38+ `)39+ expect(usersById_v3).toMatchInlineSnapshot(`40+ Map {41+ "michel" => Object {42+ "country": "UK",43+ "name": "Michel Weststrate",44+ },45+ }46+ `)47+ // The old one was never modified48+ expect(usersById_v1.size).toBe(0)49+ // And trying to change a Map outside a producers is going to: NO!50+ expect(() => usersById_v3.clear()).toThrowErrorMatchingInlineSnapshot(51+ `"This object has been frozen and should not be mutated"`52+ )53+})54+```55+56+Maps and Sets that are produced by Immer will be made artificially immutable. This means that they will throw an exception when trying mutative methods like `set`, `clear` etc. outside a producer.57+58+_Note: The **keys** of a map are never drafted! This is done to avoid confusing semantics and keep keys always referentially equal_modified:docs/original.md+2 added-2 removed
1 ---2 id: original3-title: Extracting the original object from a proxied instance3+title: Extracting the original state from a draft4 sidebar_label: Original5 ---6 7 <div id="codefund"><!-- fallback content --></div>8 unmodified lines16 original(draftState.users) // is === baseState.users17 })18 ```19 20-Just want to know if a value is a proxied instance? Use the `isDraft` function!20+Just want to know if a value is a proxied instance? Use the `isDraft` function! Note that `original` cannot be invoked on objects that aren't drafts.21 22 ```js23 import {isDraft, produce} from "immer"24 8 unmodified linesmodified:docs/pitfalls.md+1 added
10 unmodified lines11 1. Since Immer uses proxies, reading huge amounts of data from state comes with an overhead (especially in the ES5 implementation). If this ever becomes an issue (measure before you optimize!), do the current state analysis before entering the producer function or read from the `currentState` rather than the `draftState`. Also, realize that immer is opt-in everywhere, so it is perfectly fine to manually write super performance critical reducers, and use immer for all the normal ones. Also note that `original` can be used to get the original state of an object, which is cheaper to read.12 1. It is possible to return values from producers, except, it is not possible to return `undefined` that way, as it is indistinguishable from not updating the draft at all! If you want to replace the draft with `undefined`, just return `nothing` from the producer.13 1. Immer [does not support exotic objects](https://github.com/immerjs/immer/issues/504) such as window.location.14 1. You will need to enable your own classes to work properly with Immer. For docs on the topic, check out the section on [working with complex objects](https://immerjs.github.io/immer/docs/complex-objects).15+1. For arrays, only numeric properties and the `length` property can be mutated. Custom properties are not preserved on arrays.16 1. Note that data that comes from the closure, and not from the base state, will never be drafted, even when the data has become part of the new draft:17 18 ```javascript19 function onReceiveTodo(todo) {13 unmodified linesmodified:src/core/current.ts+1 added
41 unmodified lines42 each(copy, (key, childValue) => {43 if (state && get(state.base_, key) === childValue) return // no need to copy or search in something that didn't change44 set(copy, key, currentImpl(childValue))45 })46+ // In the future, we might consider freezing here, based on the current settings47 return archType === ArchtypeSet ? new Set(copy) : copy48 }49 50 function copyHelper(value: any, archType: number): any {10 unmodified linesmodified:src/plugins/es5.ts-2 removed
43 unmodified lines44 }45 46 function createES5Draft(isArray: boolean, base: any) {47 // Create a new object / array, where each own property is trapped with an accessor48- // TODO: extract all utils used in this fn?48 const descriptors = Object.getOwnPropertyDescriptors(base)49 // Descriptors we want to skip:50 if (isArray) delete descriptors.length51 delete descriptors[DRAFT_STATE as any]19 unmodified lines71 const isArray = Array.isArray(base)72 const draft = createES5Draft(isArray, base)73 74 const state: ES5ObjectState | ES5ArrayState = {76- // TODO: reuse this object construction from proxy?75 type_: isArray ? ProxyTypeES5Array : (ProxyTypeES5Object as any),76 scope_: parent ? parent.scope_ : getCurrentScope(),77 modified_: false,78 finalized_: false,188 unmodified linesmodified:src/utils/common.ts+2 added-3 removed
153 unmodified lines154 }155 // like object.assign, we will read any _own_, get/set accessors. This helps in dealing156 // with libraries that trap values, like mobx or vue157 // unlike object.assign, non-enumerables will be copied as well158- // TODO: document!159- if (desc.get)158+ if (desc.get || desc.set)159 descriptors[key] = {160 configurable: true,162- writable: !!desc.set, // could live with 'true' as well here...161+ writable: true, // could live with !!desc.set as well here...162 enumerable: desc.enumerable,163 value: base[key]164 }165 }21 unmodified linesmodified:website/i18n/en.json+9 added-2 removed
14 unmodified lines15 "built-with": {16 "title": "Built with Immer"17 },18 "complex-objects": {19- "title": "Working with Map, Set and classes"19+ "title": "Classes"20 },21+ "current": {22+ "title": "Extracting the current state from a draft",23+ "sidebar_label": "Current"24+ },25 "curried-produce": {26 "title": "Curried producers"27 },28 "example-reducer": {15 unmodified lines44 "introduction": {45 "title": "Introduction to Immer",46 "sidebar_label": "Introduction"47 },48+ "map-set": {49+ "title": "Map and Set"50+ },51 "original": {45- "title": "Extracting the original object from a proxied instance",52+ "title": "Extracting the original state from a draft",53 "sidebar_label": "Original"54 },55 "patches": {56 "title": "Patches"41 unmodified linesmodified:website/sidebars.json+1 added-1 removed
1 {2 "Immer": {3 "Basics": ["introduction", "installation", "produce", "curried-produce", "example-reducer", "example-setstate"],4- "Advanced Features": ["api", "typescript", "return", "patches", "freezing", "original", "async", "complex-objects"],4+ "Advanced Features": ["api", "map-set", "complex-objects", "current", "original", "patches", "freezing", "return", "async", "typescript"],5 "Resources": ["performance", "resources", "faq", "pitfalls", "built-with", "support"]6 }7 }modified:package.json+1 added-1 removed
1 {2 "name": "immer",3- "version": "6.0.0-alpha.4",3+ "version": "7.0.0-beta.0",4 "description": "Create your next immutable state by mutating the current one",5 "main": "dist/index.js",6 "module": "dist/immer.esm.js",7 "umd:main": "dist/immer.umd.production.min.js",92 unmodified lines