{"version":3,"file":"useStateMachine.js","sources":["../../src/shared/useStateMachine.ts"],"sourcesContent":["import type { Ref } from 'vue'\nimport { ref } from 'vue'\n\ninterface Machine {\n [k: string]: { [k: string]: S }\n}\ntype MachineState = keyof T\ntype MachineEvent = keyof UnionToIntersection\n\n// 🤯 https://fettblog.eu/typescript-union-to-intersection/\ntype UnionToIntersection = (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(\n initialState: MachineState,\n machine: M & Machine>,\n) {\n const state = ref(initialState) as Ref>\n\n function reducer(event: MachineEvent) {\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) => {\n state.value = reducer(event)\n }\n\n return {\n state,\n dispatch,\n }\n}\n"],"names":[],"mappings":";;AA2BgB,SAAA,eAAA,CACd,cACA,OACA,EAAA;AACA,EAAM,MAAA,KAAA,GAAQ,IAAI,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;;;;"}