reka-ui
Version:
Vue port for Radix UI Primitives.
1 lines • 2.16 kB
Source Map (JSON)
{"version":3,"file":"useStateMachine.cjs","sources":["../../src/shared/useStateMachine.ts"],"sourcesContent":["import { type Ref, ref } from 'vue'\n\ninterface Machine<S> {\n [k: string]: { [k: string]: S }\n}\ntype MachineState<T> = keyof T\ntype MachineEvent<T> = keyof UnionToIntersection<T[keyof T]>\n\n// 🤯 https://fettblog.eu/typescript-union-to-intersection/\ntype UnionToIntersection<T> = (T extends any ? (x: T) => any : never) extends (\n x: infer R\n) => any\n ? R\n : never\n\n/**\n * The `useStateMachine` function is a TypeScript function that creates a state machine and returns the\n * current state and a dispatch function to update the state based on events.\n * @param initialState - The `initialState` parameter is the initial state of the state machine. It\n * represents the starting point of the state machine's state.\n * @param machine - The `machine` parameter is an object that represents a state machine. It should\n * have keys that correspond to the possible states of the machine, and the values should be objects\n * that represent the possible events and their corresponding next states.\n * @returns The `useStateMachine` function returns an object with two properties: `state` and\n * `dispatch`.\n */\nexport function useStateMachine<M>(\n initialState: MachineState<M>,\n machine: M & Machine<MachineState<M>>,\n) {\n const state = ref(initialState) as Ref<MachineState<M>>\n\n function reducer(event: MachineEvent<M>) {\n // @ts-expect-error state.value is keyof M\n const nextState = machine[state.value][event]\n return nextState ?? state.value\n }\n\n const dispatch = (event: MachineEvent<M>) => {\n state.value = reducer(event)\n }\n\n return {\n state,\n dispatch,\n }\n}\n"],"names":["ref"],"mappings":";;;;AA0BgB,SAAA,eAAA,CACd,cACA,OACA,EAAA;AACA,EAAM,MAAA,KAAA,GAAQA,QAAI,YAAY,CAAA;AAE9B,EAAA,SAAS,QAAQ,KAAwB,EAAA;AAEvC,IAAA,MAAM,SAAY,GAAA,OAAA,CAAQ,KAAM,CAAA,KAAK,EAAE,KAAK,CAAA;AAC5C,IAAA,OAAO,aAAa,KAAM,CAAA,KAAA;AAAA;AAG5B,EAAM,MAAA,QAAA,GAAW,CAAC,KAA2B,KAAA;AAC3C,IAAM,KAAA,CAAA,KAAA,GAAQ,QAAQ,KAAK,CAAA;AAAA,GAC7B;AAEA,EAAO,OAAA;AAAA,IACL,KAAA;AAAA,IACA;AAAA,GACF;AACF;;;;"}