Lutra/ui/src/stores/notifications.ts
danny 750ecf5e51 F1: conflict toast closes when the merge ends, toasts keep off the commit box
The merge store dismisses its conflict warning once the status lists no
conflicted file (resolved, committed or aborted) and replaces it on a new
conflicted merge. The toast stack moves above areas registered with
keepClearOf; the Changes window registers its commit box.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-02 18:53:08 +01:00

343 lines
10 KiB
TypeScript

/**
* Notifications shown as toasts at the bottom right of the window.
*
* Toasts come from the engine's `notification` events (startup, journal,
* picker and pump errors, replayed by the shell on `engine_ready`), from
* `watchFailed` events, which the frontend maps to a warning, and from
* frontend code through {@link useNotificationsStore}'s `notify` and
* `notifyError` for failed commands that have no UI of their own.
*
* Info toasts dismiss themselves after {@link INFO_TIMEOUT_MS}; warnings
* and errors stay until closed. At most {@link MAX_VISIBLE} toasts show;
* older ones collapse into a "+n more" entry.
*
* Areas the stack must never cover (the commit box) register themselves
* with `keepClear`; the stack then sits above them ({@link stackBottom}).
*/
import { defineStore } from "pinia";
import { computed, ref, shallowRef } from "vue";
import { hasMessage, t, type MessageParams } from "../i18n";
import { onEngineEvent, type EngineError, type EngineEventPayload } from "../ipc";
/** Severity of a toast. */
export type NotificationLevel = "info" | "warning" | "error";
/** Time after which an info toast dismisses itself, in milliseconds. */
export const INFO_TIMEOUT_MS = 5000;
/** Most toasts shown at once; older ones collapse into "+n more". */
export const MAX_VISIBLE = 5;
/** Most toasts kept; the oldest are dropped beyond that. */
export const MAX_KEPT = 100;
/** Catalog key of the toast for a `watchFailed` event. Params: `reason`. */
export const KEY_WATCH_FAILED = "notification.watch.failed";
/** Catalog key of the toast for a failed command. Params: `command`, `message`. */
export const KEY_COMMAND_FAILED = "notification.command.failed";
/** Distance of the stack from the window's bottom edge, in pixels. */
export const STACK_BOTTOM = 36;
/** Distance of the stack from the window's right edge, in pixels. */
export const STACK_RIGHT = 16;
/** Widest the stack gets, in pixels. */
export const STACK_WIDTH = 420;
/** Gap kept between the stack and an area it must not cover, in pixels. */
export const KEEP_CLEAR_GAP = 8;
/** Where an area sits in the window, as `getBoundingClientRect` gives it. */
export interface Area {
/** Left edge. */
left: number;
/** Right edge. */
right: number;
/** Top edge. */
top: number;
/** Bottom edge. */
bottom: number;
}
/**
* The stack's distance from the window's bottom edge so that it covers
* none of the given areas, however tall it grows: above the highest one
* it overlaps horizontally, else {@link STACK_BOTTOM}. Hidden areas (no
* width or height, as under `v-show`) are skipped.
*
* @param width - the window's inner width.
* @param height - the window's inner height.
* @param areas - the areas to keep clear.
* @returns the CSS `bottom` in pixels.
*/
export function stackBottom(width: number, height: number, areas: readonly Area[]): number {
const right = width - STACK_RIGHT;
const left = right - Math.min(STACK_WIDTH, width - 2 * STACK_RIGHT);
let bottom = STACK_BOTTOM;
for (const area of areas) {
const hidden = area.right <= area.left || area.bottom <= area.top;
const beside = area.right <= left || area.left >= right;
if (!hidden && !beside) {
bottom = Math.max(bottom, height - area.top + KEEP_CLEAR_GAP);
}
}
return bottom;
}
/** A toast as the stack shows it. */
export interface Toast {
/** Unique id: the engine's (`n1`…) or a frontend one (`ui1`…). */
id: string;
/** Severity. */
level: NotificationLevel;
/** The text, already looked up in the catalog. */
text: string;
}
/** What a notification says, before it is turned into a toast. */
export interface NotificationInput {
/** Id from the engine; a frontend id is made when absent. */
id?: string | undefined;
/** Severity. */
level: NotificationLevel;
/** Catalog key of the text. */
messageKey?: string | undefined;
/** English text, used when the key is absent or not in the catalog. */
message?: string | undefined;
/** Values for the catalog text's placeholders. */
params?: MessageParams | undefined;
}
/**
* The text of a notification: the catalog message for its key if the
* catalog has it, else the English text, else the key.
*
* @param input - the notification.
*/
export function notificationText(input: NotificationInput): string {
if (input.messageKey !== undefined && hasMessage(input.messageKey)) {
return t(input.messageKey, input.params);
}
return input.message ?? input.messageKey ?? "";
}
/**
* Reads untrusted params from the engine: string and number values are
* kept, anything else is shown as JSON.
*
* @param raw - the `params` field of the event.
*/
function toParams(raw: unknown): MessageParams | undefined {
if (typeof raw !== "object" || raw === null || Array.isArray(raw)) {
return undefined;
}
const params: Record<string, string | number> = {};
for (const [name, value] of Object.entries(raw)) {
params[name] = typeof value === "string" || typeof value === "number" ? value : JSON.stringify(value);
}
return params;
}
/**
* Checks the level of an untrusted event; an unknown level counts as an
* error so that it is not missed.
*
* @param raw - the `level` field of the event.
*/
function toLevel(raw: unknown): NotificationLevel {
return raw === "info" || raw === "warning" ? raw : "error";
}
/**
* The notification an engine event asks for, or null for other events.
*
* @param event - the engine event.
*/
export function notificationFromEvent(event: EngineEventPayload): NotificationInput | null {
if (event.kind === "notification") {
return {
id: typeof event.id === "string" ? event.id : undefined,
level: toLevel(event.level),
messageKey: typeof event.messageKey === "string" ? event.messageKey : undefined,
message: typeof event.message === "string" ? event.message : undefined,
params: toParams(event.params),
};
}
if (event.kind === "watchFailed") {
return {
level: "warning",
messageKey: KEY_WATCH_FAILED,
message: event.message,
params: { reason: event.message },
};
}
return null;
}
/** Store of the toast stack. */
export const useNotificationsStore = defineStore("notifications", () => {
/** Every toast not yet dismissed, oldest first. */
const toasts = ref<Toast[]>([]);
/** Whether the collapsed older toasts are shown. */
const expanded = ref(false);
/** Number of frontend ids handed out. */
let made = 0;
/** Auto-dismiss timers of info toasts, by id. */
const timers = new Map<string, ReturnType<typeof setTimeout>>();
/** Elements the stack must not cover, in registration order. */
const keepClear = shallowRef<HTMLElement[]>([]);
/** Ends the engine event subscription; set while started. */
let unsubscribe: (() => void) | null = null;
/** The toasts shown: the newest {@link MAX_VISIBLE}, or all when expanded. */
const visible = computed(() =>
expanded.value ? toasts.value : toasts.value.slice(-MAX_VISIBLE),
);
/** Number of older toasts collapsed into "+n more". */
const hiddenCount = computed(() => toasts.value.length - visible.value.length);
/**
* Shows a toast. A notification whose id is already shown (an engine
* replay after a reload) is ignored.
*
* @param input - the notification.
* @returns the toast's id.
*/
function notify(input: NotificationInput): string {
made += 1;
const id = input.id ?? `ui${String(made)}`;
if (toasts.value.some((toast) => toast.id === id)) {
return id;
}
toasts.value.push({ id, level: input.level, text: notificationText(input) });
while (toasts.value.length > MAX_KEPT) {
const dropped = toasts.value.shift();
if (dropped) {
clearTimer(dropped.id);
}
}
if (input.level === "info") {
timers.set(
id,
setTimeout(() => {
dismiss(id);
}, INFO_TIMEOUT_MS),
);
}
return id;
}
/**
* Shows an error toast for a failed command that has no UI of its own.
*
* @param command - the command id.
* @param error - the error it failed with.
* @returns the toast's id.
*/
function notifyError(command: string, error: EngineError): string {
return notify({
level: "error",
messageKey: KEY_COMMAND_FAILED,
message: error.message,
params: { command, message: error.message },
});
}
/**
* Stops the auto-dismiss timer of a toast, if it has one.
*
* @param id - the toast's id.
*/
function clearTimer(id: string): void {
const timer = timers.get(id);
if (timer !== undefined) {
clearTimeout(timer);
timers.delete(id);
}
}
/**
* Closes a toast. Once nothing is collapsed any more, the stack folds
* again.
*
* @param id - the toast's id; an unknown id does nothing.
*/
function dismiss(id: string): void {
clearTimer(id);
toasts.value = toasts.value.filter((toast) => toast.id !== id);
if (toasts.value.length <= MAX_VISIBLE) {
expanded.value = false;
}
}
/** Closes every toast. */
function dismissAll(): void {
for (const id of timers.keys()) {
clearTimer(id);
}
toasts.value = [];
expanded.value = false;
}
/**
* Keeps the stack off an element until the returned function is called.
*
* @param element - the element, e.g. the commit box.
* @returns a function that releases the element again.
*/
function keepClearOf(element: HTMLElement): () => void {
keepClear.value = [...keepClear.value, element];
return () => {
keepClear.value = keepClear.value.filter((kept) => kept !== element);
};
}
/** Shows the toasts collapsed into "+n more". */
function expand(): void {
expanded.value = true;
}
/**
* Applies one engine event: notifications and `watchFailed` become
* toasts, other events are ignored.
*
* @param event - the event.
*/
function handleEvent(event: EngineEventPayload): void {
const input = notificationFromEvent(event);
if (input) {
notify(input);
}
}
/** Starts showing engine notifications. Calling it again does nothing. */
function start(): void {
unsubscribe ??= onEngineEvent(handleEvent);
}
/** Stops showing engine notifications; shown toasts stay. */
function stop(): void {
unsubscribe?.();
unsubscribe = null;
}
return {
toasts,
visible,
hiddenCount,
expanded,
keepClear,
keepClearOf,
notify,
notifyError,
dismiss,
dismissAll,
expand,
handleEvent,
start,
stop,
};
});