1import type { ServerConfigStreamEvent } from "@t3tools/contracts";
2
3export const KEYBINDINGS_SUCCESS_TOAST_COOLDOWN_MS = 2_000;
4
5export type KeybindingsUpdateToastDecision =
6 | { readonly _tag: "Success" }
7 | { readonly _tag: "InvalidConfiguration"; readonly message: string };
8
9export interface KeybindingsUpdateToastController {
10 readonly handle: (event: ServerConfigStreamEvent | null) => KeybindingsUpdateToastDecision | null;
11}
12
13export function createKeybindingsUpdateToastController(input: {
14 readonly now?: () => number;
15}): KeybindingsUpdateToastController {
16 const now = input.now ?? Date.now;
17 let lastSuccessToastAt: number | null = null;
18
19 return {
20 handle: (event) => {
21 if (event?.type !== "keybindingsUpdated") {
22 return null;
23 }
24
25 const issue = event.payload.issues.find((entry) => entry.kind.startsWith("keybindings."));
26 if (issue) {
27 return {
28 _tag: "InvalidConfiguration",
29 message: issue.message,
30 };
31 }
32
33 const currentTime = now();
34 if (
35 lastSuccessToastAt !== null &&
36 currentTime - lastSuccessToastAt < KEYBINDINGS_SUCCESS_TOAST_COOLDOWN_MS
37 ) {
38 return null;
39 }
40
41 lastSuccessToastAt = currentTime;
42 return { _tag: "Success" };
43 },
44 };
45}