| 1 | import type { EnvironmentId } from "@t3tools/contracts"; |
| 2 | import { Atom } from "effect/reactivity"; |
| 3 | |
| 4 | import { appAtomRegistry } from "../../state/atom-registry"; |
| 5 | import type { ScheduledTaskDraft } from "./scheduledTaskDraft"; |
| 6 | |
| 7 | export type ScheduledTaskEditor = { |
| 8 | readonly environmentId: EnvironmentId; |
| 9 | readonly environmentLabel: string; |
| 10 | readonly draft: ScheduledTaskDraft; |
| 11 | }; |
| 12 | |
| 13 | type ScheduledTaskEditorSession = { |
| 14 | readonly id: number; |
| 15 | readonly initial: ScheduledTaskEditor | null; |
| 16 | readonly current: ScheduledTaskEditor | null; |
| 17 | }; |
| 18 | |
| 19 | export const scheduledTaskEditorSessionAtom = Atom.make<ScheduledTaskEditorSession | null>( |
| 20 | null, |
| 21 | ).pipe(Atom.keepAlive); |
| 22 | let nextEditorId = 0; |
| 23 | |
| 24 | export function startScheduledTaskEditor(next: ScheduledTaskEditor | null): void { |
| 25 | appAtomRegistry.set(scheduledTaskEditorSessionAtom, { |
| 26 | id: ++nextEditorId, |
| 27 | initial: next, |
| 28 | current: next, |
| 29 | }); |
| 30 | } |
| 31 | |
| 32 | export function updateScheduledTaskEditor( |
| 33 | update: |
| 34 | | ScheduledTaskEditor |
| 35 | | null |
| 36 | | ((current: ScheduledTaskEditor | null) => ScheduledTaskEditor | null), |
| 37 | defaultEditor: ScheduledTaskEditor | null, |
| 38 | ): void { |
| 39 | const session = appAtomRegistry.get(scheduledTaskEditorSessionAtom); |
| 40 | const previous = session ? session.current : defaultEditor; |
| 41 | appAtomRegistry.set(scheduledTaskEditorSessionAtom, { |
| 42 | id: session?.id ?? 0, |
| 43 | initial: session ? session.initial : previous, |
| 44 | current: typeof update === "function" ? update(previous) : update, |
| 45 | }); |
| 46 | } |
| 47 | |
| 48 | export function readScheduledTaskEditor( |
| 49 | voiceOwnerKey: string, |
| 50 | defaultEditor: ScheduledTaskEditor | null, |
| 51 | ): ScheduledTaskEditor | null { |
| 52 | const session = appAtomRegistry.get(scheduledTaskEditorSessionAtom); |
| 53 | if (`scheduled-task:${session?.id ?? 0}` !== voiceOwnerKey) return null; |
| 54 | return session ? session.current : defaultEditor; |
| 55 | } |