Restore: allow produce to be called with primitives
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 0592d3c · Browse files · 8 files·+76 added−64 removed
This commit
State
Before adoption: this commit came in with the history the project adopted, so no landing records it.
Diff stats
8 files+76 added−64 removed
- tests:+59 added−45 removed
- other:+17 added−19 removed
Provenance
- Commit
e7983c4- Tree
3b9fce2- Author
Michel Weststrate <mweststrate@fb.com>- Committer
Michel Weststrate <mweststrate@fb.com>- Parent
0592d3c
8 files changed+76 added−64 removed
modified:__tests__/base.js+32 added-9 removed
3 unmodified lines4 nothing,5 original,6 isDraft,7 immerable,8- enableAllPlugins,9- isDraftable8+ enableAllPlugins9 } from "../src/immer"10 import {each, shallowCopy, DRAFT_STATE} from "../src/internal"11 import deepFreeze from "deep-freeze"12 import cloneDeep from "lodash.clonedeep"1448 unmodified lines1461 it("'this' should not be bound anymore - 2", () => {1462 const incrementor = produce(function() {1463 expect(this).toBe(undefined)1464 })1466- incrementor({})1465+ incrementor()1466 })1467 1468 it("should be possible to use dynamic bound this", () => {1469 const world = {370 unmodified lines1840 expect(nextState).not.toBe(baseState)1841 })1842 1843 it("cannot produce undefined by returning undefined", () => {1844+ const base = 31845+ expect(produce(base, () => 4)).toBe(4)1846+ expect(produce(base, () => null)).toBe(null)1847+ expect(produce(base, () => undefined)).toBe(3)1848+ expect(produce(base, () => {})).toBe(3)1849+ expect(produce(base, () => nothing)).toBe(undefined)1850+1851 expect(produce({}, () => undefined)).toEqual({})1852 expect(produce({}, () => nothing)).toBe(undefined)1853+ expect(produce(3, () => nothing)).toBe(undefined)1854 1855 expect(produce(() => undefined)({})).toEqual({})1856 expect(produce(() => nothing)({})).toBe(undefined)1850- expect(produce(() => nothing, {})(undefined)).toEqual(undefined)1857+ expect(produce(() => nothing)(3)).toBe(undefined)1858 })1859 1860 describe("base state type", () => {1861 if (!global.USES_BUILD) testObjectTypes(produce)367 unmodified lines2229 for (const name in values) {2230 describe(name, () => {2231 const value = values[name]2232 2226- it("does not create a draft", () => {2227- expect(() => produce(value, () => {})).toThrow(2228- /produce can only be called on things that are draftable/2229- )2230- })2233+ if (value && typeof value == "object") {2234+ it("does not return a copy when changes are made", () => {2235+ expect(() =>2236+ produce(value, draft => {2237+ draft.foo = true2238+ })2239+ ).toThrowError(2240+ "produce can only be called on things that are draftable"2241+ )2242+ })2243+ } else {2244+ it("does not create a draft", () => {2245+ produce(value, draft => {2246+ expect(draft).toBe(value)2247+ })2248+ })2249+2250+ it("returns the base state when no changes are made", () => {2251+ expect(produce(value, () => {})).toBe(value)2252+ })2253+ }2254 })2255 }2256 }2257 14 unmodified linesmodified:__tests__/curry.js+3 added-3 removed
34 unmodified lines3536373839394041424344454645464748495054 unmodified lines34 unmodified lines })
it("should support returning new states from curring", () => { const reducer = produce((item, index) => { if (!item.x) { if (!item) { return {hello: "world"} } item.index = index })
expect(reducer({}, 3)).toEqual({hello: "world"}) expect(reducer({x: true}, 3)).toEqual({x: true, index: 3}) expect(reducer(undefined, 3)).toEqual({hello: "world"}) expect(reducer({}, 3)).toEqual({index: 3}) })
it("should support passing an initial state as second argument", () => { const reducer = produce(54 unmodified linesmodified:__tests__/frozen.js+8 added
118 unmodified lines119 expect(next).toBe(base)120 expect(isFrozen(next)).toBeTruthy()121 expect(isFrozen(next.a)).toBeTruthy()122 })123+124+ it("a new object replaces a primitive base", () => {125+ const obj = {a: {}}126+ const next = produce(null, () => obj)127+ expect(next).toBe(obj)128+ expect(isFrozen(next)).toBeTruthy()129+ expect(isFrozen(next.a)).toBeTruthy()130+ })131 })132 133 it("can handle already frozen trees", () => {134 const a = []90 unmodified linesmodified:__tests__/null.js+2 added-5 removed
3 unmodified lines4567891011128910113 unmodified linesdescribe("null functionality", () => { const baseState = null
it("should return the original without modifications", () => { expect(() => produce(baseState, () => {}) ).toThrowErrorMatchingInlineSnapshot( `"[Immer] produce can only be called on things that are draftable: plain objects, arrays, Map, Set or classes that are marked with '[immerable]: true'. Got 'null'"` ) const nextState = produce(baseState, () => {}) expect(nextState).toBe(baseState) })})modified:__tests__/patch.js+1 added-1 removed
757 unmodified lines758 )759 })760 761 describe("simple replacement", () => {762- runPatchTest({x: 3}, _d => [], [{op: "replace", path: [], value: []}])762+ runPatchTest({x: 3}, _d => 4, [{op: "replace", path: [], value: 4}])763 })764 765 describe("same value replacement - 1", () => {766 runPatchTest(284 unmodified linesmodified:__tests__/produce.ts+13 added-27 removed
76 unmodified lines77 let foo = produce((_: Draft<State>) => {})78 assert(foo, _ as Recipe)79 })80 81-it("does not allow recipes for primitives", () => {82- let foo = produce((x: number) => {})83- if (false) {84- // @ts-expect-error85- foo(3)86- }87-})88-89-it("does not allow recipes for primitives - 2", () => {90- let foo = produce((x: number) => {})91- if (false) {92- // @ts-expect-error93- foo(3)94- }95-})96-81 it("can infer state type from recipe function with arguments", () => {82 type State = {readonly a: string} | {readonly b: string}83 type Recipe = <S extends State>(state: S, x: number) => S84 8 unmodified lines93 let foo = produce((draft: Draft<State>, x: number) => {}, _ as State)94 assert(foo, _ as Recipe)95 })96 113-it("won't accept non draftables", () => {114- if (false) {115- // @ts-expect-error116- produce(3, () => {})117- }97+it("cannot infer state type when the function type and default state are missing", () => {98+ type Recipe = <S extends any>(state: S) => S99+ const foo = produce((_: any) => {})100+ // @ts-expect-error101+ assert(foo, _ as Recipe)102 })103 104 it("can update readonly state via curried api", () => {105 const newState = produce((draft: Draft<State>) => {50 unmodified lines156 {157 type Recipe = <S extends State>(state: S, a: number, b: number) => S158 let foo = produce((s: State, a: number, b: number) => {})159 assert(foo, _ as Recipe)176- foo({} as State, 1, 2)160+ foo(_ as State, 1, 2)161 }162 163 // Using argument parameters:164 {165 type Recipe = <S extends State>(state: S, ...rest: number[]) => S166 let woo = produce((state: Draft<State>, ...args: number[]) => {})167 assert(woo, _ as Recipe)184- woo({} as State, 1, 2)168+ woo(_ as State, 1, 2)169 }170 171 // With initial state:172 {3 unmodified lines176 ) => S177 let bar = produce((state: Draft<State>, ...args: number[]) => {},178 _ as State)179 assert(bar, _ as Recipe)196- bar({} as State, 1, 2)197- bar({} as State)180+ bar(_ as State, 1, 2)181+ bar(_ as State)182+ bar()183 }184 185 // When args is a tuple:186 {7 unmodified lines194 _ as State195 )196 assert(tup, _ as Recipe)197 tup({a: 1}, "", 2)198+ tup(undefined, "", 2)199 }200 })201 202 it("can be passed a readonly array", () => {18 unmodified lines221 })222 })223 224 it("works with return type of: number", () => {239- let base = {} as {a: number}225+ let base = _ as {a: number}226 let result = produce(base, () => 1)227 assert(result, _ as number)228 })229 43 unmodified lines273 assert(result2, _ as typeof base | undefined)274 })275 276 it("can return the draft itself", () => {291- let base = {} as {readonly a: number}277+ let base = _ as {readonly a: number}278 let result = produce(base, draft => draft)279 280 // Currently, the `readonly` modifier is lost.281 assert(result, _ as {a: number})198 unmodified linesmodified:src/core/immerClass.ts+10 added-3 removed
20 unmodified lines21 enterScope,22 revokeScope,23 leaveScope,24 usePatchesInScope,25- getCurrentScope25+ getCurrentScope,26+ NOTHING,27+ freeze28 } from "../internal"29 30 interface ProducersFns {31 produce: IProduce81 unmodified lines113 )114 }115 usePatchesInScope(scope, patchListener)116 return processResult(result, scope)115- }116- die(21, base)117+ } else if (!base || typeof base !== "object") {118+ result = recipe(base)119+ if (result === NOTHING) return undefined120+ if (result === undefined) result = base121+ if (this.autoFreeze_) freeze(result, true)122+ return result123+ } else die(21, base)124 }125 126 produceWithPatches(arg1: any, arg2?: any, arg3?: any): any {127 if (typeof arg1 === "function") {99 unmodified linesmodified:src/types/types-external.ts+7 added-16 removed
1-import {Nothing, DRAFTABLE} from "../internal"1+import {Nothing} from "../internal"2 3 type Tail<T extends any[]> = ((...t: T) => any) extends (4 _: any,5 ...tail: infer TT41 unmodified lines47 : T extends object48 ? {readonly [K in keyof T]: Immutable<T[K]>}49 : T50 51-export type Draftable =52- | {readonly [K in keyof any]: any}53- | ReadonlyMap<any, any>54- | ReadonlySet<any>55- | ReadonlyArray<any>56- | {57- [DRAFTABLE]: true58- }59-51 export interface Patch {52 op: "replace" | "remove" | "add"53 path: (string | number)[]54 value?: any34 unmodified lines89 /** Curried producer */90 <91 Recipe extends (...args: any[]) => any,92 Params extends any[] = Parameters<Recipe>,102- T = Params[0] extends object ? Params[0] : never93+ T = Params[0]94 >(95 recipe: Recipe96 ): <Base extends Immutable<T>>(97 base: Base,6 unmodified lines104 /** Curried producer with initial state */105 <106 Recipe extends (...args: any[]) => any,107 Params extends any[] = Parameters<Recipe>,117- T = Params[0] extends object ? Params[0] : never108+ T = Params[0]109 >(110 recipe: Recipe,111 initialState: Immutable<T>112 ): <Base extends Immutable<T>>(1 unmodified line114 ...rest: Tail<Params>115 ) => Produced<Base, ReturnType<Recipe>>116 117 /** Normal producer */127- <Base extends Draftable, D = Draft<Base>, Return = void>(118+ <Base, D = Draft<Base>, Return = void>(119 base: Base,120 recipe: (draft: D) => Return,121 listener?: PatchListener122 ): Produced<Base, Return>9 unmodified lines132 /** Curried producer */133 <134 Recipe extends (...args: any[]) => any,135 Params extends any[] = Parameters<Recipe>,145- T = Params[0] extends object ? Params[0] : never136+ T = Params[0]137 >(138 recipe: Recipe139 ): <Base extends Immutable<T>>(140 base: Base,6 unmodified lines147 /** Curried producer with initial state */148 <149 Recipe extends (...args: any[]) => any,150 Params extends any[] = Parameters<Recipe>,160- T = Params[0] extends object ? Params[0] : never151+ T = Params[0]152 >(153 recipe: Recipe,154 initialState: Immutable<T>155 ): <Base extends Immutable<T>>(1 unmodified line157 ...rest: Tail<Params>158 ) => [Produced<Base, ReturnType<Recipe>>, Patch[], Patch[]]159 160 /** Normal producer */170- <Base extends Draftable, D = Draft<Base>, Return = void>(161+ <Base, D = Draft<Base>, Return = void>(162 base: Base,163 recipe: (draft: D) => Return164 ): [Produced<Base, Return>, Patch[], Patch[]]165 }4 unmodified lines