Files
codecraft/web/src/dialogs.tsx
T
Richard ZinkandClaude Sonnet 5.5 6b1a1742b2 Web UI on Ant Design, scrollable factory columns, fix empty page after deleting the open chat
Buttons, fields, drop-downs, check boxes, tabs, dialogs and notices are Ant Design components;
their tokens come from the theme variables (web/src/ui). Every factory board column has its own
vertical scrollbar. ChatView rendered fewer hooks once its chat was deleted.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-11-27 12:32:57 +01:00

163 lines
5.7 KiB
TypeScript

import { App, Button, Input, type InputRef } from "antd";
import { UploadPanel } from "./components/UploadPanel";
// In-app dialogs and toasts instead of the browser's alert/confirm/prompt.
import { useEffect, useRef, useState, useSyncExternalStore } from "react";
import { t } from "./i18n";
import { Modal } from "./ui/Modal";
interface ConfirmOpts {
title?: string;
message: string;
confirmLabel?: string;
/** Destructive action: red button. */
danger?: boolean;
}
interface PromptOpts {
title?: string;
message: string;
defaultValue?: string;
placeholder?: string;
password?: boolean;
confirmLabel?: string;
}
interface ChoiceOpts {
title?: string;
message: string;
choices: { value: string; label: string; danger?: boolean }[];
}
type Dialog =
| ({ kind: "confirm"; id: number; resolve: (v: boolean) => void } & ConfirmOpts)
| ({ kind: "choice"; id: number; resolve: (v: string | null) => void } & ChoiceOpts)
| ({ kind: "prompt"; id: number; resolve: (v: string | null) => void } & PromptOpts);
interface Toast {
id: number;
message: string;
kind: "error" | "info" | "success";
}
let dialogs: Dialog[] = [];
/** Shows a notice; set by the DialogHost once it is mounted. */
let show: ((x: Toast) => void) | undefined;
const waiting: Toast[] = [];
let seq = 0;
const listeners = new Set<() => void>();
const emit = () => listeners.forEach((l) => l());
const subscribe = (l: () => void) => (listeners.add(l), () => listeners.delete(l));
export function confirmDialog(opts: ConfirmOpts | string): Promise<boolean> {
const o = typeof opts === "string" ? { message: opts } : opts;
return new Promise((resolve) => {
dialogs = [...dialogs, { kind: "confirm", id: ++seq, resolve, ...o }];
emit();
});
}
/** Several actions to choose from (plus Cancel): resolves to the chosen value, or null. */
export function choiceDialog(opts: ChoiceOpts): Promise<string | null> {
return new Promise((resolve) => {
dialogs = [...dialogs, { kind: "choice", id: ++seq, resolve, ...opts }];
emit();
});
}
export function promptDialog(opts: PromptOpts | string): Promise<string | null> {
const o = typeof opts === "string" ? { message: opts } : opts;
return new Promise((resolve) => {
dialogs = [...dialogs, { kind: "prompt", id: ++seq, resolve, ...o }];
emit();
});
}
export function toast(message: unknown, kind: Toast["kind"] = "error") {
const text = message instanceof Error ? message.message : typeof message === "string" ? message : String((message as any)?.message ?? message);
const x = { id: ++seq, message: text, kind };
if (show) show(x);
else waiting.push(x);
}
function close(d: Dialog, value: any) {
dialogs = dialogs.filter((x) => x.id !== d.id);
emit();
(d.resolve as (v: any) => void)(value);
}
function DialogView({ d }: { d: Dialog }) {
const [value, setValue] = useState(d.kind === "prompt" ? d.defaultValue ?? "" : "");
const input = useRef<InputRef>(null);
const ok = useRef<HTMLButtonElement>(null);
const cancelValue = d.kind === "confirm" ? false : null;
useEffect(() => {
// After the window has opened (it takes the focus itself first).
const timer = setTimeout(() => (d.kind === "prompt" ? input.current?.focus({ cursor: "all" }) : ok.current?.focus()), 60);
return () => clearTimeout(timer);
// eslint-disable-next-line react-hooks/exhaustive-deps
}, []);
const submit = () => close(d, d.kind === "confirm" ? true : value);
const field = {
ref: input,
value,
placeholder: d.kind === "prompt" ? d.placeholder : undefined,
onChange: (e: React.ChangeEvent<HTMLInputElement>) => setValue(e.target.value),
};
return (
<Modal onClose={() => close(d, cancelValue)} className="dialog">
<form role={d.kind === "confirm" ? "alertdialog" : "dialog"} aria-label={d.title ?? d.message} onSubmit={(e) => (e.preventDefault(), submit())}>
{d.title && <h3>{d.title}</h3>}
<p className="dialog-message">{d.message}</p>
{d.kind === "prompt" && (d.password ? <Input.Password {...field} autoComplete="new-password" /> : <Input {...field} autoComplete="off" />)}
{d.kind === "choice" ? (
<div className="row dialog-actions dialog-choices">
<Button onClick={() => close(d, null)}>{t("common.cancel")}</Button>
{d.choices.map((c, i) => {
const last = i === d.choices.length - 1;
return (
<Button key={c.value} ref={last ? ok : undefined} type={c.danger || last ? "primary" : "default"} danger={c.danger} onClick={() => close(d, c.value)}>
{c.label}
</Button>
);
})}
</div>
) : (
<div className="row dialog-actions">
<Button onClick={() => close(d, cancelValue)}>{t("common.cancel")}</Button>
<Button ref={ok} htmlType="submit" type="primary" danger={d.kind === "confirm" && d.danger}>
{d.confirmLabel ?? t("common.ok")}
</Button>
</div>
)}
</form>
</Modal>
);
}
/** Renders open dialogs and toasts; mounted once in App. */
export function DialogHost() {
const state = useSyncExternalStore(subscribe, () => dialogs);
const { message } = App.useApp();
useEffect(() => {
show = (x) =>
void message.open({
key: x.id,
type: x.kind,
// A click dismisses the notice.
content: <span onClick={() => message.destroy(x.id)}>{x.message}</span>,
duration: x.kind === "error" ? 7 : 3.5,
});
// Notices raised before the host was there.
waiting.splice(0).forEach(show);
return () => void (show = undefined);
}, [message]);
return (
<>
{state.map((d) => (
<DialogView key={d.id} d={d} />
))}
<UploadPanel />
</>
);
}