diff --git a/src/Updux.ts b/src/Updux.ts index 2ee4ea8..54e8aa0 100644 --- a/src/Updux.ts +++ b/src/Updux.ts @@ -1,15 +1,18 @@ import R from 'remeda'; +import { Action, ActionGenerator } from './actions'; /** * Configuration object typically passed to the constructor of the class Updux. */ -export interface UpduxConfig { +export interface UpduxConfig = Record, TSubduxes = {}> { /** * Local initial state. * @default {} */ initial?: TState; + actions?: TActions; + /** * Subduxes to be merged to this dux. */ @@ -22,13 +25,35 @@ export type DuxStateSubduxes = keyof C extends never ? unknown : { [K in keyof C]: StateOf }; -export class Updux { +// type UnionArrayTypes = A[number]; + +// type ActionType = A extends ActionGenerator ? B : never; + +// type ActionAsObject = Record< ActionType, A > }>; + +// type UnionToIntersection = +// (U extends any ? (k: U)=>void : never) extends ((k: infer I)=>void) ? I : never + +// type ActionsAsObject = ActionAsObject< A[number]> + +export class Updux { #localInitial: any = {}; #subduxes; + #actions : TActions; - constructor(config: UpduxConfig) { + constructor(config: UpduxConfig) { this.#localInitial = config.initial ?? {}; this.#subduxes = config.subduxes ?? {}; + + this.#actions = config.actions ?? ([] as any); + } + + get actions() { + return this.#actions; + } + + get action(): ActionsAsObject { + return Object.fromEntries(this.#actions.map( a => [ a.type, a ] )); } get initial(): TState & DuxStateSubduxes { diff --git a/src/actions.test.ts b/src/actions.test.ts index 7651c5a..16d20ae 100644 --- a/src/actions.test.ts +++ b/src/actions.test.ts @@ -2,6 +2,8 @@ import { test, expect } from 'vitest'; import { action } from './actions.js'; +import { Updux } from './Updux.js'; + test('basic action', () => { const foo = action('foo', (thing: string) => ({ thing })); @@ -12,3 +14,24 @@ test('basic action', () => { }, }); }); + +test( "Updux config accepts actions", () => { + const foo = new Updux({ + actions: { + one: action('one', (x: string) => ({x})), + two: action('two', x => x), + } + }); + + expect(Object.keys(foo.actions)).toHaveLength(2); + + expect( foo.actions.one ).toBeTypeOf('function'); + expect( foo.actions.one("potato") ).toEqual({ + type: 'one', + payload: { + x: 'potato' + } + }); + +} ) +