Merge pull request #402 from immerjs/produce-with-patches
Before adoption: this commit came in with the history the project adopted, so no landing records it.
authored by Michel Weststrate · committed by GitHub · parents 615ca6f, 86be737 · Browse files · 6 files·+166 added−2 removed
This commit
State
Before adoption: this commit came in with the history the project adopted, so no landing records it.
Trailers
- feat: introduced produceWithPatches. Implements #400
Diff stats
6 files+166 added−2 removed
- tests:+60 added−2 removed
- other:+106 added−0 removed
Provenance
- Commit
a16deda- Tree
cfc34d4- Author
Michel Weststrate <mweststrate@gmail.com>- Committer
GitHub <noreply@github.com>- Parent 1
615ca6f- Parent 2
86be737
6 files changed+166 added−2 removed
modified:__tests__/curry.js+25 added-1 removed
122345661 unmodified lines6869707172737475767778798081828384858687888990919293949596"use strict"import produce, {setUseProxies} from "../src/index"import produce, {setUseProxies, produceWithPatches} from "../src/index"
runTests("proxy", true)runTests("es5", false)
61 unmodified lines expect(spread(base, {z: 3})).toEqual({x: 1, y: 1, z: 3}) expect(spread(base, {y: 1})).toBe(base) }) })
it("support currying for produceWithPatches", () => { const increment = produceWithPatches((draft, delta) => { draft.x += delta })
expect(increment({x: 5}, 2)).toEqual([ {x: 7}, [ { op: "replace", path: ["x"], value: 7 } ], [ { op: "replace", path: ["x"], value: 5 } ] ]) })}modified:__tests__/readme.js+35 added-1 removed
1 "use strict"2-import produce, {applyPatches, immerable} from "../src/index"2+import produce, {3+ applyPatches,4+ immerable,5+ produceWithPatches6+} from "../src/index"7 8 describe("readme example", () => {9 it("works", () => {10 const baseState = [160 unmodified lines171 expect(diner).not.toBe(lunch)172 expect(lunch).toBeInstanceOf(Clock)173 expect(diner.toString()).toBe("18:30")174 })175+176+ test("produceWithPatches", () => {177+ const result = produceWithPatches(178+ {179+ age: 33180+ },181+ draft => {182+ draft.age++183+ }184+ )185+ expect(result).toEqual([186+ {187+ age: 34188+ },189+ [190+ {191+ op: "replace",192+ path: ["age"],193+ value: 34194+ }195+ ],196+ [197+ {198+ op: "replace",199+ path: ["age"],200+ value: 33201+ }202+ ]203+ ])204+ })205 })modified:src/immer.d.ts+43 added
107 unmodified lines108 109 export const produce: IProduce110 export default produce111 112+/**113+ * Like `produce`, but instead of just returning the new state,114+ * a tuple is returned with [nextState, patches, inversePatches]115+ *116+ * Like produce, this function supports currying117+ */118+export interface IProduceWithPatches {119+ /** Curried producer */120+ <121+ Recipe extends (...args: any[]) => any,122+ Params extends any[] = Parameters<Recipe>,123+ T = Params[0]124+ >(125+ recipe: Recipe126+ ): <Base extends Immutable<T>>(127+ base: Base,128+ ...rest: Tail<Params>129+ ) => [Produced<Base, ReturnType<Recipe>>, Patch[], Patch[]]130+ // ^ by making the returned type generic, the actual type of the passed in object is preferred131+ // over the type used in the recipe. However, it does have to satisfy the immutable version used in the recipe132+ // Note: the type of S is the widened version of T, so it can have more props than T, but that is technically actually correct!133+134+ /** Curried producer with initial state */135+ <136+ Recipe extends (...args: any[]) => any,137+ Params extends any[] = Parameters<Recipe>,138+ T = Params[0]139+ >(140+ recipe: Recipe,141+ initialState: Immutable<T>142+ ): <Base extends Immutable<T>>(143+ base?: Base,144+ ...rest: Tail<Params>145+ ) => [Produced<Base, ReturnType<Recipe>>, Patch[], Patch[]]146+147+ /** Normal producer */148+ <Base, D = Draft<Base>, Return = void>(149+ base: Base,150+ recipe: (draft: D) => Return151+ ): [Produced<Base, Return>, Patch[], Patch[]]152+}153+export const produceWithPatches: IProduceWithPatches154+155 /** Use a class type for `nothing` so its type is unique */156 declare class Nothing {157 // This lets us do `Exclude<T, Nothing>`158 private _: any133 unmodified linesmodified:src/immer.js+16 added
89 unmodified lines90 if (result === undefined) return base91 return result !== NOTHING ? result : undefined92 }93 }94+ produceWithPatches(arg1, arg2, arg3) {95+ if (typeof arg1 === "function") {96+ const self = this97+ return (state, ...args) =>98+ this.produceWithPatches(state, draft => arg1(draft, ...args))99+ }100+ // non-curried form101+ if (arg3)102+ throw new Error("A patch listener cannot be passed to produceWithPatches")103+ let patches, inversePatches104+ const nextState = this.produce(arg1, arg2, (p, ip) => {105+ patches = p106+ inversePatches = ip107+ })108+ return [nextState, patches, inversePatches]109+ }110 createDraft(base) {111 if (!isDraftable(base)) {112 throw new Error("First argument to `createDraft` must be a plain object, an array, or an immerable object") // prettier-ignore113 }199 unmodified linesmodified:src/index.js+6 added
23 unmodified lines242526272829303132333435363742 unmodified lines23 unmodified linesexport const produce = immer.produceexport default produce
/** * Like `produce`, but `produceWithPatches` always returns a tuple * [nextState, patches, inversePatches] (instead of just the next state) */export const produceWithPatches = immer.produceWithPatches.bind(immer)
/** * Pass true to automatically freeze all copies created by Immer. * * By default, auto-freezing is disabled in production. */42 unmodified linesmodified:readme.md+41 added
331 unmodified lines332 {"op": "add", "path": ["tags", 3], "value": "kiddo"}333 ]334 ```335 336+### `produceWithPatches`337+338+Instead of setting up a patch listener, an easier way to obtain the patches is to use `produceWithPatches`, which has the same signature as `produce`, except that it doesn't return just the next state, but a tuple consisting of `[nextState, patches, inversePatches]`. Like `produce`, `produceWithPatches` supports currying as well.339+340+```javascript341+import {produceWithPatches} from "immer"342+343+const [nextState, patches, inversePatches] = produceWithPatches(344+ {345+ age: 33346+ },347+ draft => {348+ draft.age++349+ }350+)351+```352+353+Which produces:354+355+```javascript356+;[357+ {358+ age: 34359+ },360+ [361+ {362+ op: "replace",363+ path: ["age"],364+ value: 34365+ }366+ ],367+ [368+ {369+ op: "replace",370+ path: ["age"],371+ value: 33372+ }373+ ]374+]375+```376+377 For a more in-depth study, see [Distributing patches and rebasing actions using Immer](https://medium.com/@mweststrate/distributing-state-changes-using-snapshots-patches-and-actions-part-2-2f50d8363988)378 379 Tip: Check this trick to [compress patches](https://medium.com/@david.b.edelstein/using-immer-to-compress-immer-patches-f382835b6c69) produced over time.380 453 unmodified lines