Open History to see the last commit
1import type { ServerConfigStreamEvent } from "@t3tools/contracts";
2
3const KEYBINDINGS_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 lastToast: { readonly key: string; readonly at: number } | null = null;
18 let lastInvalidKey: string | null = null;
19
20 return {
21 handle: (event) => {
22 // A file already invalid when the app connects arrives in the snapshot, not as a reload.
23 const issues =
24 event?.type === "keybindingsUpdated"
25 ? event.payload.issues
26 : event?.type === "snapshot"
27 ? event.config.issues
28 : null;
29 if (issues === null) {
30 return null;
31 }
32
33 const issue = issues.find((entry) => entry.kind.startsWith("keybindings."));
34 const key = issue ? `invalid:${issue.message}` : "success";
35 const alreadyWarned = key === lastInvalidKey;
36 lastInvalidKey = issue ? key : null;
37 // Every reconnect sends a snapshot: warn once per distinct problem, never a success toast.
38 if (event?.type === "snapshot" && (!issue || alreadyWarned)) {
39 return null;
40 }
41
42 const decision: KeybindingsUpdateToastDecision = issue
43 ? { _tag: "InvalidConfiguration", message: issue.message }
44 : { _tag: "Success" };
45
46 // A save and the server's file watcher each publish the same snapshot,
47 // so an identical toast inside the cooldown is the same change twice.
48 const currentTime = now();
49 if (
50 lastToast !== null &&
51 lastToast.key === key &&
52 currentTime - lastToast.at < KEYBINDINGS_TOAST_COOLDOWN_MS
53 ) {
54 return null;
55 }
56
57 lastToast = { key, at: currentTime };
58 return decision;
59 },
60 };
61}