@tsplc/agent 0.5.8 → 0.5.10

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (49) hide show
  1. package/dist/cli.js +2462 -533
  2. package/dist/cli.js.map +30 -17
  3. package/dist/client.js +238 -36
  4. package/dist/client.js.map +4 -4
  5. package/dist/index.js +2162 -416
  6. package/dist/index.js.map +25 -13
  7. package/package.json +5 -5
  8. package/src/access.ts +257 -0
  9. package/src/agent.ts +101 -29
  10. package/src/audit.ts +64 -0
  11. package/src/cli.ts +58 -4
  12. package/src/client.ts +181 -36
  13. package/src/dashboard/index.ts +116 -0
  14. package/src/dashboard/ui/access.ts +192 -0
  15. package/src/dashboard/ui/actions.ts +142 -0
  16. package/src/dashboard/ui/api.ts +147 -0
  17. package/src/dashboard/ui/app.ts +41 -0
  18. package/src/dashboard/ui/approval.ts +132 -0
  19. package/src/dashboard/ui/audit.ts +115 -0
  20. package/src/dashboard/ui/contract.ts +16 -0
  21. package/src/dashboard/ui/dashboard.css +1332 -0
  22. package/src/dashboard/ui/deployment.ts +432 -0
  23. package/src/dashboard/ui/deployments.ts +317 -0
  24. package/src/dashboard/ui/details.ts +240 -0
  25. package/src/dashboard/ui/dom.ts +91 -0
  26. package/src/dashboard/ui/environment.ts +224 -0
  27. package/src/dashboard/ui/format.ts +118 -0
  28. package/src/dashboard/ui/logs.ts +127 -0
  29. package/src/dashboard/ui/main.ts +86 -0
  30. package/src/dashboard/ui/overlay.ts +146 -0
  31. package/src/dashboard/ui/shell.ts +171 -0
  32. package/src/dashboard/ui/source.ts +144 -0
  33. package/src/deploy.ts +138 -144
  34. package/src/deployments/health.ts +80 -0
  35. package/src/deployments/retention.ts +45 -0
  36. package/src/deployments/routes.ts +273 -0
  37. package/src/deployments/runner.ts +877 -0
  38. package/src/deployments/store.ts +233 -0
  39. package/src/environment.ts +205 -0
  40. package/src/index.ts +4 -0
  41. package/src/operations.ts +5 -1
  42. package/src/protocol.ts +218 -2
  43. package/src/releases.ts +73 -1
  44. package/src/routes.ts +52 -0
  45. package/src/secrets.ts +43 -2
  46. package/src/server-process.ts +33 -16
  47. package/src/sessions.ts +58 -0
  48. package/src/state.ts +2 -0
  49. package/src/tailscale.ts +112 -0
@@ -0,0 +1,224 @@
1
+ import { errorMessage } from "../../errors";
2
+ import { api, type EnvironmentEntry } from "./api";
3
+ import { type App, attempt } from "./app";
4
+ import { badge, dot, empty, fill, h, pageHeader, type View } from "./dom";
5
+ import { confirm, dialog } from "./overlay";
6
+
7
+ /** Asks for a secret's value, never showing one: the agent stores it and never sends it back. */
8
+ const askValue = (name: string | null) => {
9
+ const nameInput = h("input", {
10
+ class: "input mono",
11
+ placeholder: "NAME",
12
+ autocomplete: "off",
13
+ spellcheck: "false",
14
+ required: true,
15
+ pattern: "[A-Za-z_][A-Za-z0-9_]*",
16
+ });
17
+ const valueInput = h("input", {
18
+ class: "input mono",
19
+ type: "password",
20
+ autocomplete: "new-password",
21
+ placeholder: "Value",
22
+ });
23
+ return dialog<{ name: string; value: string }>({
24
+ title: name ? `Set ${name}` : "Add a variable",
25
+ body: [
26
+ name
27
+ ? null
28
+ : h("label", { class: "field" }, h("span", {}, "Name"), nameInput),
29
+ h("label", { class: "field" }, h("span", {}, "Value"), valueInput),
30
+ h(
31
+ "p",
32
+ { class: "muted" },
33
+ "The value is stored on the agent's PC and never shown again. The server reads it when it next starts.",
34
+ ),
35
+ ],
36
+ actions: (close) => [
37
+ h(
38
+ "button",
39
+ {
40
+ class: "button primary",
41
+ onclick: () => {
42
+ const chosen = name ?? nameInput.value.trim();
43
+ if (!chosen || (!nameInput.checkValidity() && !name)) {
44
+ nameInput.reportValidity();
45
+ return;
46
+ }
47
+ close({ name: chosen, value: valueInput.value });
48
+ },
49
+ },
50
+ "Save",
51
+ ),
52
+ ],
53
+ });
54
+ };
55
+
56
+ /** The release's secrets: which are declared and set, never their values. */
57
+ export const environmentView = (app: App): View => {
58
+ const admin = app.can("admin");
59
+ const body = h("tbody");
60
+ const table = h(
61
+ "table",
62
+ { class: "table" },
63
+ h(
64
+ "thead",
65
+ {},
66
+ h(
67
+ "tr",
68
+ {},
69
+ h("th", {}, "Name"),
70
+ h("th", {}, "Declared"),
71
+ h("th", {}, "Value"),
72
+ admin ? h("th", {}, "") : null,
73
+ ),
74
+ ),
75
+ body,
76
+ );
77
+ const holder = h("div", {}, empty("Loading the environment…"));
78
+
79
+ const set = async (name: string | null) => {
80
+ const entered = await askValue(name);
81
+ if (
82
+ entered &&
83
+ (await attempt(
84
+ () => api.setEnvironment(entered.name, entered.value),
85
+ `Saved ${entered.name}. Restart the server to apply it.`,
86
+ )) !== null
87
+ ) {
88
+ await load();
89
+ }
90
+ };
91
+
92
+ const remove = async (entry: EnvironmentEntry) => {
93
+ const confirmed = await confirm({
94
+ title: `Delete ${entry.name}?`,
95
+ body: [
96
+ h(
97
+ "p",
98
+ {},
99
+ entry.declared
100
+ ? "The release declares it, so its server can't start without it after the next restart."
101
+ : "No release declares it.",
102
+ ),
103
+ ],
104
+ confirm: "Delete",
105
+ tone: "danger",
106
+ });
107
+ if (
108
+ confirmed &&
109
+ (await attempt(
110
+ () => api.deleteEnvironment(entry.name),
111
+ `Deleted ${entry.name}`,
112
+ )) !== null
113
+ ) {
114
+ await load();
115
+ }
116
+ };
117
+
118
+ const row = (entry: EnvironmentEntry) =>
119
+ h(
120
+ "tr",
121
+ {},
122
+ h("td", { class: "mono" }, entry.name),
123
+ h(
124
+ "td",
125
+ {},
126
+ entry.declared
127
+ ? badge("Declared", "neutral")
128
+ : h("span", { class: "muted" }, "Not declared"),
129
+ ),
130
+ h(
131
+ "td",
132
+ {},
133
+ h(
134
+ "span",
135
+ { class: "state" },
136
+ dot(entry.set ? "ok" : entry.declared ? "error" : "idle"),
137
+ entry.set
138
+ ? h("span", { class: "mono muted" }, "••••••••")
139
+ : "Not set",
140
+ ),
141
+ ),
142
+ admin
143
+ ? h(
144
+ "td",
145
+ { class: "row-actions" },
146
+ h(
147
+ "button",
148
+ { class: "button small", onclick: () => void set(entry.name) },
149
+ entry.set ? "Replace" : "Set",
150
+ ),
151
+ entry.set
152
+ ? h(
153
+ "button",
154
+ {
155
+ class: "button small danger-text",
156
+ onclick: () => void remove(entry),
157
+ },
158
+ "Delete",
159
+ )
160
+ : null,
161
+ )
162
+ : null,
163
+ );
164
+
165
+ const load = async () => {
166
+ try {
167
+ const entries = await api.environment();
168
+ fill(body, ...entries.map(row));
169
+ fill(
170
+ holder,
171
+ entries.length
172
+ ? table
173
+ : empty("The deployed release declares no secrets."),
174
+ );
175
+ } catch (error) {
176
+ fill(holder, h("p", { class: "error-text" }, errorMessage(error)));
177
+ }
178
+ };
179
+
180
+ const restart = async () => {
181
+ const confirmed = await confirm({
182
+ title: "Restart the server?",
183
+ body: [
184
+ h(
185
+ "p",
186
+ {},
187
+ "The line's server stops and starts again with the environment as it is now. The controller keeps running.",
188
+ ),
189
+ ],
190
+ confirm: "Restart",
191
+ tone: "primary",
192
+ });
193
+ if (confirmed) {
194
+ await attempt(() => api.restartServer(), "The server restarted");
195
+ }
196
+ };
197
+
198
+ void load();
199
+ return {
200
+ element: h(
201
+ "div",
202
+ { class: "page" },
203
+ pageHeader(
204
+ "Environment",
205
+ "The secrets the release's server reads. Values are write-only, and new ones apply when the server restarts.",
206
+ app.can("deployer")
207
+ ? h(
208
+ "button",
209
+ { class: "button", onclick: () => void restart() },
210
+ "Restart server",
211
+ )
212
+ : null,
213
+ admin
214
+ ? h(
215
+ "button",
216
+ { class: "button primary", onclick: () => void set(null) },
217
+ "Add variable",
218
+ )
219
+ : null,
220
+ ),
221
+ holder,
222
+ ),
223
+ };
224
+ };
@@ -0,0 +1,118 @@
1
+ import { formatAge, formatDuration } from "@tsplc/debug/format";
2
+ import type {
3
+ DeploymentRecord,
4
+ DeploymentState,
5
+ GitSource,
6
+ } from "../../protocol";
7
+
8
+ export type Phase = DeploymentRecord["phases"][number];
9
+ export type PhaseName = Phase["name"];
10
+
11
+ /** How each state is shown, and whether the deployment has finished in it. */
12
+ export const states: Record<
13
+ DeploymentState,
14
+ {
15
+ label: string;
16
+ tone: "ok" | "error" | "active" | "waiting" | "idle";
17
+ finished: boolean;
18
+ }
19
+ > = {
20
+ queued: { label: "Queued", tone: "idle", finished: false },
21
+ building: { label: "Building", tone: "active", finished: false },
22
+ awaitingApproval: {
23
+ label: "Awaiting approval",
24
+ tone: "waiting",
25
+ finished: false,
26
+ },
27
+ applying: { label: "Applying", tone: "active", finished: false },
28
+ starting: { label: "Starting", tone: "active", finished: false },
29
+ verifying: { label: "Verifying", tone: "active", finished: false },
30
+ ready: { label: "Ready", tone: "ok", finished: true },
31
+ error: { label: "Error", tone: "error", finished: true },
32
+ canceled: { label: "Canceled", tone: "idle", finished: true },
33
+ };
34
+
35
+ export const phaseLabels: Record<PhaseName, string> = {
36
+ queue: "Queue",
37
+ build: "Build",
38
+ review: "Review",
39
+ apply: "Apply",
40
+ server: "Server",
41
+ health: "Health check",
42
+ };
43
+
44
+ /** A deployment can still be canceled: it hasn't started changing the controller. */
45
+ export const cancelable = (state: DeploymentState) =>
46
+ state === "queued" || state === "building" || state === "awaitingApproval";
47
+
48
+ const hour = 3_600_000;
49
+ const day = 86_400_000;
50
+
51
+ /** A length of time: the debugger's durations within an hour, then hours and minutes, since approval can wait for days. */
52
+ export const formatSpan = (ms: number) =>
53
+ ms < hour
54
+ ? formatDuration(ms)
55
+ : `${Math.floor(ms / hour)} h ${Math.floor((ms % hour) / 60_000)} min`;
56
+
57
+ /** How long before `now` `iso` was: the debugger's ages within a day, then days. A clock ahead of the browser's reads as now. */
58
+ export const formatAgo = (iso: string, now: number) => {
59
+ const elapsed = Math.max(0, now - Date.parse(iso));
60
+ return elapsed < day
61
+ ? formatAge(elapsed)
62
+ : `${Math.floor(elapsed / day)} d ago`;
63
+ };
64
+
65
+ /** A phase's length so far: to `now` while it runs. */
66
+ export const phaseDuration = (phase: Phase, now: number) =>
67
+ (phase.finishedAt === null ? now : Date.parse(phase.finishedAt)) -
68
+ Date.parse(phase.startedAt);
69
+
70
+ /**
71
+ * How long a deployment took, from its first phase to the end of its last, or to `now` while it
72
+ * hasn't finished; null before it has a phase.
73
+ */
74
+ export const deploymentDuration = (record: DeploymentRecord, now: number) => {
75
+ const [first] = record.phases;
76
+ if (!first) {
77
+ return null;
78
+ }
79
+ const end = states[record.state].finished
80
+ ? Math.max(
81
+ ...record.phases.map((phase) =>
82
+ Date.parse(phase.finishedAt ?? phase.startedAt),
83
+ ),
84
+ )
85
+ : now;
86
+ return Math.max(0, end - Date.parse(first.startedAt));
87
+ };
88
+
89
+ export const formatDeploymentDuration = (
90
+ record: DeploymentRecord,
91
+ now: number,
92
+ ) => {
93
+ const duration = deploymentDuration(record, now);
94
+ return duration === null ? "—" : formatSpan(duration);
95
+ };
96
+
97
+ /** A deployment id as a list shows it: without the `dpl_` prefix, to nine characters. */
98
+ export const shortId = (id: string) => id.replace(/^dpl_/, "").slice(0, 9);
99
+
100
+ export const shortCommit = (git: GitSource) => git.commit.slice(0, 7);
101
+
102
+ /** A date and time in the browser's locale, to the second. */
103
+ export const formatTimestamp = (iso: string) =>
104
+ new Date(iso).toLocaleString(undefined, {
105
+ dateStyle: "medium",
106
+ timeStyle: "medium",
107
+ });
108
+
109
+ /** A file size: bytes, then kB and MB. */
110
+ export const formatSize = (bytes: number) => {
111
+ if (bytes < 1000) {
112
+ return `${bytes} B`;
113
+ }
114
+ if (bytes < 1_000_000) {
115
+ return `${(bytes / 1000).toFixed(1)} kB`;
116
+ }
117
+ return `${(bytes / 1_000_000).toFixed(1)} MB`;
118
+ };
@@ -0,0 +1,127 @@
1
+ import { formatClock } from "@tsplc/debug/format";
2
+ import type { DeploymentLogLine } from "../../protocol";
3
+ import { empty, fill, h } from "./dom";
4
+ import { type PhaseName, phaseLabels } from "./format";
5
+
6
+ const allPhases = "all";
7
+
8
+ /**
9
+ * A deployment's log: lines coloured by level, filtered by phase and text, and kept scrolled to
10
+ * the newest line while following.
11
+ */
12
+ export const logViewer = (lines: readonly DeploymentLogLine[]) => {
13
+ const phase = h("select", { class: "input", "aria-label": "Phase" });
14
+ const search = h("input", {
15
+ class: "input search",
16
+ type: "search",
17
+ placeholder: "Search the log…",
18
+ });
19
+ const follow = h("input", { type: "checkbox", checked: true });
20
+ const count = h("span", { class: "muted mono count" });
21
+ const output = h("div", { class: "log", tabindex: 0 });
22
+ const shown: DeploymentLogLine[] = [];
23
+
24
+ const matches = (line: DeploymentLogLine) => {
25
+ const text = search.value.trim().toLowerCase();
26
+ return (
27
+ (phase.value === allPhases || line.phase === phase.value) &&
28
+ (!text || line.message.toLowerCase().includes(text))
29
+ );
30
+ };
31
+
32
+ const lineElement = (line: DeploymentLogLine) =>
33
+ h(
34
+ "div",
35
+ { class: `log-line l-${line.level}` },
36
+ h("span", { class: "log-seq" }, String(line.seq)),
37
+ h("time", { class: "log-time", title: line.at }, formatClock(line.at)),
38
+ h(
39
+ "span",
40
+ { class: "log-phase" },
41
+ line.phase ? phaseLabels[line.phase] : "",
42
+ ),
43
+ h("span", { class: "log-message" }, line.message),
44
+ );
45
+
46
+ const phasesSeen = () => [
47
+ ...new Set(lines.flatMap((line) => (line.phase ? [line.phase] : []))),
48
+ ];
49
+
50
+ const renderPhases = () => {
51
+ const selected = phase.value || allPhases;
52
+ const seen: PhaseName[] = phasesSeen();
53
+ if (phase.options.length === seen.length + 1) {
54
+ return;
55
+ }
56
+ fill(
57
+ phase,
58
+ h("option", { value: allPhases }, "All phases"),
59
+ ...seen.map((name) => h("option", { value: name }, phaseLabels[name])),
60
+ );
61
+ phase.value = selected;
62
+ };
63
+
64
+ const updateCount = () => {
65
+ count.textContent =
66
+ shown.length === lines.length
67
+ ? `${lines.length} lines`
68
+ : `${shown.length} of ${lines.length} lines`;
69
+ };
70
+
71
+ const scrollToEnd = () => {
72
+ if (follow.checked) {
73
+ output.scrollTop = output.scrollHeight;
74
+ }
75
+ };
76
+
77
+ const render = () => {
78
+ shown.splice(0, shown.length, ...lines.filter(matches));
79
+ fill(
80
+ output,
81
+ ...(shown.length
82
+ ? shown.map(lineElement)
83
+ : [empty(lines.length ? "No line matches." : "No log lines yet.")]),
84
+ );
85
+ updateCount();
86
+ scrollToEnd();
87
+ };
88
+
89
+ // Scrolling up stops following; scrolling back to the end follows again.
90
+ output.addEventListener("scroll", () => {
91
+ follow.checked =
92
+ output.scrollHeight - output.scrollTop - output.clientHeight < 24;
93
+ });
94
+ phase.addEventListener("change", render);
95
+ search.addEventListener("input", render);
96
+ follow.addEventListener("change", scrollToEnd);
97
+ renderPhases();
98
+ render();
99
+
100
+ return {
101
+ element: h(
102
+ "div",
103
+ { class: "log-viewer" },
104
+ h(
105
+ "div",
106
+ { class: "toolbar" },
107
+ search,
108
+ phase,
109
+ h("label", { class: "check" }, follow, "Follow"),
110
+ count,
111
+ ),
112
+ output,
113
+ ),
114
+ /** Shows lines added to `lines` since the last call. */
115
+ added: (added: readonly DeploymentLogLine[]) => {
116
+ renderPhases();
117
+ const matching = added.filter(matches);
118
+ if (matching.length && shown.length === 0) {
119
+ output.replaceChildren();
120
+ }
121
+ shown.push(...matching);
122
+ output.append(...matching.map(lineElement));
123
+ updateCount();
124
+ scrollToEnd();
125
+ },
126
+ };
127
+ };
@@ -0,0 +1,86 @@
1
+ import { errorMessage } from "../../errors";
2
+ import { accessView } from "./access";
3
+ import { ApiError, api } from "./api";
4
+ import { type App, createApp } from "./app";
5
+ import { auditView } from "./audit";
6
+ import { deploymentView } from "./deployment";
7
+ import { deploymentsView } from "./deployments";
8
+ import { h, type View } from "./dom";
9
+ import { environmentView } from "./environment";
10
+ import { shell, signInForm } from "./shell";
11
+
12
+ type Page = View & { navigate?(pathname: string): boolean };
13
+
14
+ const pageFor = (app: App, pathname: string): Page => {
15
+ if (pathname.startsWith("/deployments/")) {
16
+ return deploymentView(app, pathname);
17
+ }
18
+ if (pathname === "/environment") {
19
+ return environmentView(app);
20
+ }
21
+ if (pathname === "/audit") {
22
+ return auditView(app);
23
+ }
24
+ if (pathname === "/access") {
25
+ return accessView(app);
26
+ }
27
+ return deploymentsView(app);
28
+ };
29
+
30
+ const root = () => {
31
+ const element = document.getElementById("app");
32
+ if (!element) {
33
+ throw new Error("The page has no #app element");
34
+ }
35
+ return element;
36
+ };
37
+
38
+ const start = async () => {
39
+ const identity = await api.session().catch((error: unknown) => {
40
+ if (error instanceof ApiError && error.status === 401) {
41
+ return null;
42
+ }
43
+ throw error;
44
+ });
45
+ if (!identity) {
46
+ root().replaceChildren(signInForm(() => void start()));
47
+ return;
48
+ }
49
+ let page: Page | null = null;
50
+ const main = h("div", { class: "content" });
51
+ const show = (pathname: string) => {
52
+ top.setActive(pathname);
53
+ if (page?.navigate?.(pathname)) {
54
+ return;
55
+ }
56
+ page?.dispose?.();
57
+ page = pageFor(app, pathname);
58
+ main.replaceChildren(page.element);
59
+ scrollTo(0, 0);
60
+ };
61
+ const app = createApp(identity, (path) => {
62
+ if (path !== location.pathname) {
63
+ history.pushState(null, "", path);
64
+ }
65
+ show(path);
66
+ });
67
+ const top = shell(app);
68
+ root().replaceChildren(top.element, main);
69
+ addEventListener("popstate", () => show(location.pathname));
70
+ show(location.pathname);
71
+ };
72
+
73
+ start().catch((error: unknown) =>
74
+ root().replaceChildren(
75
+ h(
76
+ "div",
77
+ { class: "sign-in" },
78
+ h(
79
+ "div",
80
+ { class: "card" },
81
+ h("h1", {}, "The dashboard could not start"),
82
+ h("p", { class: "error-text" }, errorMessage(error)),
83
+ ),
84
+ ),
85
+ ),
86
+ );
@@ -0,0 +1,146 @@
1
+ import { type Child, h, icon, icons } from "./dom";
2
+
3
+ /** A menu item: an action, or a link to follow. */
4
+ export type MenuItem =
5
+ | {
6
+ label: string;
7
+ run: () => void;
8
+ tone?: "danger";
9
+ disabled?: boolean;
10
+ }
11
+ | "separator";
12
+
13
+ let closeOpenMenu: (() => void) | null = null;
14
+
15
+ /** Whether a menu or dialog is open, so a refresh doesn't pull the rows out from under it. */
16
+ export const overlayOpen = () =>
17
+ closeOpenMenu !== null || document.querySelector("dialog[open]") !== null;
18
+
19
+ const openMenu = (anchor: HTMLElement, items: MenuItem[]) => {
20
+ closeOpenMenu?.();
21
+ const menu = h(
22
+ "div",
23
+ { class: "menu", role: "menu" },
24
+ ...items.map((item) =>
25
+ item === "separator"
26
+ ? h("div", { class: "menu-separator" })
27
+ : h(
28
+ "button",
29
+ {
30
+ class: `menu-item${item.tone ? ` ${item.tone}` : ""}`,
31
+ role: "menuitem",
32
+ disabled: item.disabled,
33
+ onclick: (event) => {
34
+ event.stopPropagation();
35
+ close();
36
+ item.run();
37
+ },
38
+ },
39
+ item.label,
40
+ ),
41
+ ),
42
+ );
43
+ const outside = (event: Event) => {
44
+ if (event.target instanceof Node && !menu.contains(event.target)) {
45
+ close();
46
+ }
47
+ };
48
+ const onKey = (event: KeyboardEvent) => {
49
+ if (event.key === "Escape") {
50
+ close();
51
+ }
52
+ };
53
+ const close = () => {
54
+ menu.remove();
55
+ document.removeEventListener("click", outside, true);
56
+ document.removeEventListener("keydown", onKey);
57
+ closeOpenMenu = null;
58
+ };
59
+ document.body.append(menu);
60
+ const box = anchor.getBoundingClientRect();
61
+ menu.style.top = `${box.bottom + window.scrollY + 4}px`;
62
+ menu.style.left = `${Math.max(8, box.right + window.scrollX - menu.offsetWidth)}px`;
63
+ document.addEventListener("click", outside, true);
64
+ document.addEventListener("keydown", onKey);
65
+ closeOpenMenu = close;
66
+ menu.querySelector<HTMLButtonElement>("button:not([disabled])")?.focus();
67
+ };
68
+
69
+ /** The "…" button that opens a row's menu. */
70
+ export const menuButton = (label: string, items: () => MenuItem[]) =>
71
+ h(
72
+ "button",
73
+ {
74
+ class: "icon-button",
75
+ title: label,
76
+ "aria-label": label,
77
+ "aria-haspopup": "menu",
78
+ onclick: (event) => {
79
+ event.stopPropagation();
80
+ if (event.currentTarget instanceof HTMLElement) {
81
+ openMenu(event.currentTarget, items());
82
+ }
83
+ },
84
+ },
85
+ icon(icons.more),
86
+ );
87
+
88
+ /**
89
+ * A modal dialog. `actions` builds its buttons, given `close`; it resolves with what `close` was
90
+ * given, or null when dismissed.
91
+ */
92
+ export const dialog = <T>(options: {
93
+ title: string;
94
+ body: Child[];
95
+ actions: (close: (value: T) => void) => Child[];
96
+ }) =>
97
+ new Promise<T | null>((resolve) => {
98
+ const element = h("dialog", { class: "dialog" });
99
+ let result: T | null = null;
100
+ const close = (value: T) => {
101
+ result = value;
102
+ element.close();
103
+ };
104
+ element.addEventListener("close", () => {
105
+ element.remove();
106
+ resolve(result);
107
+ });
108
+ element.append(
109
+ h("h2", {}, options.title),
110
+ h("div", { class: "dialog-body" }, ...options.body),
111
+ h("div", { class: "dialog-actions" }, ...options.actions(close)),
112
+ );
113
+ document.body.append(element);
114
+ element.showModal();
115
+ });
116
+
117
+ /** Asks to confirm an action: resolves true once confirmed. */
118
+ export const confirm = async (options: {
119
+ title: string;
120
+ body: Child[];
121
+ confirm: string;
122
+ tone: "primary" | "danger";
123
+ }) =>
124
+ (await dialog<boolean>({
125
+ title: options.title,
126
+ body: options.body,
127
+ actions: (close) => [
128
+ h("button", { class: "button", onclick: () => close(false) }, "Cancel"),
129
+ h(
130
+ "button",
131
+ { class: `button ${options.tone}`, onclick: () => close(true) },
132
+ options.confirm,
133
+ ),
134
+ ],
135
+ })) === true;
136
+
137
+ const toasts = () =>
138
+ document.querySelector(".toasts") ??
139
+ document.body.appendChild(h("div", { class: "toasts", role: "status" }));
140
+
141
+ /** A short notice in the corner, gone after a few seconds. */
142
+ export const toast = (message: string, tone: "ok" | "error") => {
143
+ const element = h("div", { class: `toast t-${tone}` }, message);
144
+ toasts().append(element);
145
+ setTimeout(() => element.remove(), tone === "error" ? 8000 : 4000);
146
+ };