feat(web): rework layout and quality of life (#12)
- App shell: top bar with connection state and Chat/Terminal toggles, per-column scrolling, sidebar only on the Notebooks page. - Hash routes (#/notebooks/<path>, #/hosts, #/settings) so reloads and links keep the open notebook and page. - Parameters sit beside the notebook on wide screens, collapsible, with missing-count summary and Reset; non-secret values are remembered per notebook in localStorage (secrets and undeclared names never stored). - Sticky notebook header with breadcrumbs, check summary and run-all; Ctrl/Cmd+S saves the Markdown draft. - Step cards show target, one deduplicated hint for missing values and copy feedback. - Shared Dialog, Menu and CopyButton components; notebook and host actions move into menus and modal dialogs. - Hosts page as a compact list; Settings split into cards with sign out for this browser.
This commit is contained in:
+292
-182
@@ -42,6 +42,9 @@ import { ParamsForm, type ParamGroup } from "./ParamsForm";
|
||||
import { HostBlockCard } from "./HostBlockCard";
|
||||
import { StepCard } from "./StepCard";
|
||||
import { ChatPanel } from "./ChatPanel";
|
||||
import { parseRoute, routeHash } from "./route";
|
||||
import { recallValues, rememberValues } from "./paramMemory";
|
||||
import { Dialog } from "./ui";
|
||||
const TerminalSlot = lazy(() =>
|
||||
import("./TerminalSlot").then((module) => ({ default: module.TerminalSlot })),
|
||||
);
|
||||
@@ -68,11 +71,16 @@ function includedGroups(blocks: Block[]): ParamGroup[] {
|
||||
: [],
|
||||
);
|
||||
}
|
||||
/** Values that are set; unset ones stay visible as `{{name}}` in prose. */
|
||||
function setValuesOnly(values: ParamValues): ParamValues {
|
||||
return Object.fromEntries(Object.entries(values).filter(([, value]) => value));
|
||||
}
|
||||
export function App({ api }: { api: Api }) {
|
||||
const initialRoute = useRef(parseRoute(location.hash));
|
||||
const [auth, setAuth] = useState<"loading" | "login" | "setup" | "ready">("loading");
|
||||
const [page, setPage] = useState<NavigationPage>("Notebooks");
|
||||
const [page, setPage] = useState<NavigationPage>(initialRoute.current.page);
|
||||
const [password, setPassword] = useState("");
|
||||
const [list, setList] = useState<NotebookSummary[]>([]);
|
||||
const [list, setList] = useState<NotebookSummary[]>();
|
||||
const [hosts, setHosts] = useState<HostInfo[]>([]);
|
||||
const [doc, setDoc] = useState<NotebookResponse>();
|
||||
const [source, setSource] = useState("");
|
||||
@@ -113,7 +121,7 @@ export function App({ api }: { api: Api }) {
|
||||
setConflict(false);
|
||||
setError("");
|
||||
if (!same) {
|
||||
setValues({});
|
||||
setValues(recallValues(path, next.notebook));
|
||||
setEdit(false);
|
||||
setCheckIds([]);
|
||||
}
|
||||
@@ -123,6 +131,7 @@ export function App({ api }: { api: Api }) {
|
||||
},
|
||||
[api],
|
||||
);
|
||||
const leave = () => !current.current.dirty || window.confirm("Discard unsaved edits?");
|
||||
useEffect(() => {
|
||||
void api
|
||||
.me()
|
||||
@@ -144,7 +153,10 @@ export function App({ api }: { api: Api }) {
|
||||
if (!active) return;
|
||||
setList(notebooks.notebooks);
|
||||
setHosts(inventory.hosts);
|
||||
if (notebooks.notebooks[0]) void load(notebooks.notebooks[0].path);
|
||||
// Open the notebook from the URL, else the first one.
|
||||
const wanted = initialRoute.current.notebook;
|
||||
const first = notebooks.notebooks.find((n) => n.path === wanted) ?? notebooks.notebooks[0];
|
||||
if (first) void load(first.path);
|
||||
})
|
||||
.catch((e) => setError(String(e)));
|
||||
const close = api.events((event: ServerEvent) => {
|
||||
@@ -190,6 +202,25 @@ export function App({ api }: { api: Api }) {
|
||||
window.addEventListener("beforeunload", guard);
|
||||
return () => window.removeEventListener("beforeunload", guard);
|
||||
}, [dirty]);
|
||||
// Keep the page and notebook in the URL; back/forward navigate between them.
|
||||
useEffect(() => {
|
||||
if (auth !== "ready") return;
|
||||
// Until the first notebook is open, keep the requested one in the URL.
|
||||
if (page === "Notebooks" && !doc && list === undefined) return;
|
||||
const hash = routeHash({ page, notebook: doc?.path });
|
||||
if (location.hash === hash) return;
|
||||
if (location.hash) history.pushState(null, "", hash);
|
||||
else history.replaceState(null, "", hash);
|
||||
}, [auth, page, doc, list]);
|
||||
useEffect(() => {
|
||||
const follow = () => {
|
||||
const route = parseRoute(location.hash);
|
||||
setPage(route.page);
|
||||
if (route.notebook && route.notebook !== current.current.doc?.path && leave()) void load(route.notebook);
|
||||
};
|
||||
window.addEventListener("hashchange", follow);
|
||||
return () => window.removeEventListener("hashchange", follow);
|
||||
}, [load]);
|
||||
|
||||
// The saved notebook comes composed from the server; a draft shows its includes after saving.
|
||||
const notebook = doc
|
||||
@@ -218,6 +249,10 @@ export function App({ api }: { api: Api }) {
|
||||
};
|
||||
const runFor = (id: string) =>
|
||||
session.runs[session.latest[stepKey(path, id)] ?? ""];
|
||||
function changeValues(next: ParamValues) {
|
||||
setValues(next);
|
||||
if (doc) rememberValues(doc.path, doc.notebook, next);
|
||||
}
|
||||
async function start(request: StartRunRequest) {
|
||||
const key = stepKey(request.notebookPath, request.stepId);
|
||||
setPending((previous) => new Set(previous).add(key));
|
||||
@@ -274,7 +309,7 @@ export function App({ api }: { api: Api }) {
|
||||
<ReactMarkdown>
|
||||
{renderText(
|
||||
block.text,
|
||||
{ ...runtime, ...resolved.values },
|
||||
setValuesOnly({ ...runtime, ...resolved.values }),
|
||||
notebook,
|
||||
)}
|
||||
</ReactMarkdown>
|
||||
@@ -360,6 +395,8 @@ export function App({ api }: { api: Api }) {
|
||||
);
|
||||
});
|
||||
}
|
||||
const canSave =
|
||||
dirty && !conflict && !notebook?.diagnostics.some((d) => d.severity === "error");
|
||||
async function save() {
|
||||
if (!doc) return;
|
||||
try {
|
||||
@@ -379,15 +416,44 @@ export function App({ api }: { api: Api }) {
|
||||
else setError(String(e));
|
||||
}
|
||||
}
|
||||
// Ctrl/Cmd+S saves the open draft.
|
||||
const saveRef = useRef(save);
|
||||
saveRef.current = save;
|
||||
const canSaveRef = useRef(canSave);
|
||||
canSaveRef.current = canSave && edit;
|
||||
useEffect(() => {
|
||||
const key = (e: KeyboardEvent) => {
|
||||
if ((e.ctrlKey || e.metaKey) && e.key.toLowerCase() === "s" && canSaveRef.current) {
|
||||
e.preventDefault();
|
||||
void saveRef.current();
|
||||
}
|
||||
};
|
||||
window.addEventListener("keydown", key);
|
||||
return () => window.removeEventListener("keydown", key);
|
||||
}, []);
|
||||
const keyPrompt = Object.values(session.runs).find(
|
||||
(run) => run.status === "hostKey" && requests.current.has(run.runId),
|
||||
);
|
||||
const checksBusy = notebook
|
||||
? steps(notebook.blocks).some(
|
||||
(s) =>
|
||||
runFor(s.attrs.id)?.status === "running" ||
|
||||
pending.has(stepKey(path, s.attrs.id)),
|
||||
)
|
||||
: false;
|
||||
const openTerminal = () => {
|
||||
setTerminalOpened(true);
|
||||
setChat(false);
|
||||
setTerminal(true);
|
||||
};
|
||||
if (auth === "setup") return <SetupScreen onComplete={() => setAuth("ready")} />;
|
||||
if (auth === "login")
|
||||
return (
|
||||
<main className="login">
|
||||
<h1>ShellBook</h1>
|
||||
<p>Sign in to your workspace</p>
|
||||
<h1>
|
||||
ShellBook<span>RUNBOOKS</span>
|
||||
</h1>
|
||||
<p className="muted">Sign in to your workspace</p>
|
||||
<form
|
||||
onSubmit={(e) => {
|
||||
e.preventDefault();
|
||||
@@ -417,193 +483,237 @@ export function App({ api }: { api: Api }) {
|
||||
</label>
|
||||
<button className="primary">Sign in</button>
|
||||
</form>
|
||||
{error && <p role="alert">{error}</p>}
|
||||
{error && <p role="alert" className="error">{error}</p>}
|
||||
</main>
|
||||
);
|
||||
return (
|
||||
<div className={`app ${terminal || chat ? "with-terminal" : ""}`}>
|
||||
<aside className="sidebar">
|
||||
<h1>
|
||||
ShellBook<span>RUNBOOKS</span>
|
||||
</h1>
|
||||
<NotebookList
|
||||
api={api}
|
||||
list={list}
|
||||
path={path}
|
||||
version={doc?.version}
|
||||
canLeave={() => !dirty || window.confirm("Discard unsaved edits?")}
|
||||
onSelect={(next) => {
|
||||
if (!dirty || window.confirm("Discard unsaved edits?"))
|
||||
void load(next);
|
||||
}}
|
||||
onChanged={async (next) => {
|
||||
const result = await api.list();
|
||||
setList(result.notebooks);
|
||||
if (next) await load(next);
|
||||
else {
|
||||
++loadSequence.current;
|
||||
setDoc(undefined);
|
||||
setSource("");
|
||||
setConflict(false);
|
||||
}
|
||||
}}
|
||||
/>
|
||||
<small className="connection">
|
||||
{import.meta.env.VITE_MOCK === "1" ? "DEMO · " : ""}
|
||||
{connected
|
||||
? "● Events connected"
|
||||
: "○ Events disconnected · reload to reconnect"}
|
||||
</small>
|
||||
</aside>
|
||||
<main>
|
||||
<div className="app">
|
||||
<header className="topbar">
|
||||
<span className="brand">
|
||||
ShellBook
|
||||
{import.meta.env.VITE_MOCK === "1" && <span className="chip">demo</span>}
|
||||
</span>
|
||||
<HeaderNavigation page={page} onChange={setPage} />
|
||||
{page === "Settings" && <SettingsPage openTerminal={() => { setTerminalOpened(true); setTerminal(true); }} />}
|
||||
{page === "Hosts" && <HostsPage onChange={() => { void api.hosts().then(result => setHosts(result.hosts)).catch(e => setError(String(e))); }} />}
|
||||
<div hidden={page !== "Notebooks"}>
|
||||
<div className="toolbar">
|
||||
<button aria-expanded={chat} onClick={() => { setChat(!chat); setTerminal(false); }}>Chat</button>
|
||||
<span>{doc?.notebook.title ?? "Loading workspace…"}</span>
|
||||
<button onClick={() => setEdit(!edit)}>
|
||||
{edit ? "Close editor" : "Edit Markdown"}
|
||||
</button>
|
||||
<button
|
||||
aria-expanded={terminal}
|
||||
onClick={() => {
|
||||
setTerminalOpened(true);
|
||||
setChat(false);
|
||||
setTerminal(!terminal);
|
||||
}}
|
||||
>
|
||||
Terminal {terminal ? "→" : "←"}
|
||||
</button>
|
||||
</div>
|
||||
{error && (
|
||||
<p className="banner error" role="alert">
|
||||
{error}
|
||||
<button onClick={() => location.reload()}>Retry</button>
|
||||
</p>
|
||||
)}
|
||||
{conflict && (
|
||||
<div className="banner error" role="alert">
|
||||
The file changed on disk. Your draft has been retained.
|
||||
<button
|
||||
onClick={() => {
|
||||
if (!dirty || window.confirm("Discard your draft and reload?"))
|
||||
void load(path);
|
||||
<span className="spacer" />
|
||||
<span
|
||||
className={`connection ${connected ? "ok" : "bad"}`}
|
||||
title={connected ? "Live updates connected" : "Live updates disconnected; reload to reconnect"}
|
||||
>
|
||||
{connected ? "Live" : "Offline · reload"}
|
||||
</span>
|
||||
<button
|
||||
aria-expanded={chat}
|
||||
className={chat ? "toggled" : ""}
|
||||
onClick={() => {
|
||||
setChat(!chat);
|
||||
setTerminal(false);
|
||||
}}
|
||||
>
|
||||
Chat
|
||||
</button>
|
||||
<button
|
||||
aria-expanded={terminal}
|
||||
className={terminal ? "toggled" : ""}
|
||||
onClick={() => {
|
||||
if (terminal) setTerminal(false);
|
||||
else openTerminal();
|
||||
}}
|
||||
>
|
||||
Terminal
|
||||
</button>
|
||||
</header>
|
||||
<div className="workspace">
|
||||
{page === "Notebooks" && (
|
||||
<aside className="sidebar" aria-label="Notebook list">
|
||||
<NotebookList
|
||||
api={api}
|
||||
list={list ?? []}
|
||||
path={path}
|
||||
version={doc?.version}
|
||||
canLeave={leave}
|
||||
onSelect={(next) => {
|
||||
if (next !== path && leave()) void load(next);
|
||||
}}
|
||||
onChanged={async (next) => {
|
||||
const result = await api.list();
|
||||
setList(result.notebooks);
|
||||
if (next) await load(next);
|
||||
else {
|
||||
++loadSequence.current;
|
||||
setDoc(undefined);
|
||||
setSource("");
|
||||
setConflict(false);
|
||||
}
|
||||
}}
|
||||
>
|
||||
Reload from disk
|
||||
</button>
|
||||
</div>
|
||||
)}
|
||||
{notebook && (
|
||||
<>
|
||||
<ParamsForm
|
||||
notebook={notebook}
|
||||
values={resolved.values}
|
||||
errors={resolved.errors}
|
||||
hosts={hosts}
|
||||
groups={groups}
|
||||
onChange={(name, value) =>
|
||||
setValues((previous) => ({ ...previous, [name]: value }))
|
||||
}
|
||||
/>
|
||||
<div className="notebook">
|
||||
{edit && (
|
||||
<section>
|
||||
<div className="actions">
|
||||
<strong>Markdown editor {dirty ? "· unsaved" : ""}</strong>
|
||||
<button
|
||||
className="primary"
|
||||
disabled={
|
||||
!dirty ||
|
||||
conflict ||
|
||||
notebook.diagnostics.some((d) => d.severity === "error")
|
||||
}
|
||||
onClick={() => void save()}
|
||||
>
|
||||
Save
|
||||
</button>
|
||||
</div>
|
||||
<Suspense fallback={<p>Loading editor…</p>}>
|
||||
<Editor
|
||||
key={`${path}:${doc?.version}`}
|
||||
source={source}
|
||||
onChange={setSource}
|
||||
/>
|
||||
</Suspense>
|
||||
<p className="muted">
|
||||
Live preview below. Save changes before running steps.
|
||||
</p>
|
||||
</section>
|
||||
)}
|
||||
{notebook.diagnostics.map((d, i) => (
|
||||
<p role="alert" className="error" key={i}>
|
||||
{d.line && `Line ${d.line}: `}
|
||||
{d.message}
|
||||
</p>
|
||||
))}
|
||||
<div className="actions">
|
||||
</aside>
|
||||
)}
|
||||
<main className="main">
|
||||
{error && (
|
||||
<p className="banner error" role="alert">
|
||||
{error}
|
||||
<button onClick={() => location.reload()}>Retry</button>
|
||||
</p>
|
||||
)}
|
||||
{page === "Settings" && (
|
||||
<SettingsPage openTerminal={openTerminal} onSignOut={() => setAuth("login")} />
|
||||
)}
|
||||
{page === "Hosts" && <HostsPage onChange={() => { void api.hosts().then(result => setHosts(result.hosts)).catch(e => setError(String(e))); }} />}
|
||||
<div className="notebook-page" hidden={page !== "Notebooks"}>
|
||||
{conflict && (
|
||||
<div className="banner error" role="alert">
|
||||
The file changed on disk. Your draft has been retained.
|
||||
<button
|
||||
disabled={
|
||||
!connected ||
|
||||
dirty ||
|
||||
activeChecks.length === 0 ||
|
||||
!activeChecks.every(runnable) ||
|
||||
steps(notebook.blocks).some(
|
||||
(s) =>
|
||||
runFor(s.attrs.id)?.status === "running" ||
|
||||
pending.has(stepKey(path, s.attrs.id)),
|
||||
)
|
||||
}
|
||||
onClick={() => {
|
||||
setCheckIds(activeChecks.map((s) => s.attrs.id));
|
||||
activeChecks.forEach(requestRun);
|
||||
if (!dirty || window.confirm("Discard your draft and reload?"))
|
||||
void load(path);
|
||||
}}
|
||||
>
|
||||
Run all checks
|
||||
Reload from disk
|
||||
</button>
|
||||
{checkIds.length > 0 && (
|
||||
<span role="status">
|
||||
✅{" "}
|
||||
{
|
||||
checkIds.filter((id) => runFor(id)?.status === "success")
|
||||
.length
|
||||
}{" "}
|
||||
/ {checkIds.length} · ❌{" "}
|
||||
{
|
||||
checkIds.filter((id) => runFor(id)?.status === "failure")
|
||||
.length
|
||||
}
|
||||
</span>
|
||||
)}
|
||||
</div>
|
||||
{blocks(notebook.blocks)}
|
||||
</div>
|
||||
</>
|
||||
)}
|
||||
{!notebook && (
|
||||
<div className="empty">
|
||||
{list === undefined
|
||||
? "Loading workspace…"
|
||||
: list.length
|
||||
? "Select a notebook."
|
||||
: "No notebooks yet. Create one with + in the sidebar, or ask Claude in Chat."}
|
||||
</div>
|
||||
)}
|
||||
{notebook && (
|
||||
<div className="notebook-layout">
|
||||
<ParamsForm
|
||||
notebook={notebook}
|
||||
values={resolved.values}
|
||||
errors={resolved.errors}
|
||||
hosts={hosts}
|
||||
groups={groups}
|
||||
onChange={(name, value) => changeValues({ ...values, [name]: value })}
|
||||
onReset={() => changeValues({})}
|
||||
/>
|
||||
<article className="notebook">
|
||||
<header className="notebook-header">
|
||||
<span className="crumbs" title={path}>
|
||||
{path.split("/").map((part, i, parts) => (
|
||||
<span key={i} className={i === parts.length - 1 ? "file" : ""}>
|
||||
{part}
|
||||
</span>
|
||||
))}
|
||||
{dirty && <span className="chip warn">unsaved</span>}
|
||||
</span>
|
||||
<span className="spacer" />
|
||||
{checkIds.length > 0 && (
|
||||
<span role="status" className="check-summary">
|
||||
✅{" "}
|
||||
{checkIds.filter((id) => runFor(id)?.status === "success").length}{" "}
|
||||
/ {checkIds.length} · ❌{" "}
|
||||
{checkIds.filter((id) => runFor(id)?.status === "failure").length}
|
||||
</span>
|
||||
)}
|
||||
<button
|
||||
title={
|
||||
activeChecks.length
|
||||
? "Runs every check step; checks never change hosts"
|
||||
: "This notebook has no check steps"
|
||||
}
|
||||
disabled={
|
||||
!connected ||
|
||||
dirty ||
|
||||
activeChecks.length === 0 ||
|
||||
!activeChecks.every(runnable) ||
|
||||
checksBusy
|
||||
}
|
||||
onClick={() => {
|
||||
setCheckIds(activeChecks.map((s) => s.attrs.id));
|
||||
activeChecks.forEach(requestRun);
|
||||
}}
|
||||
>
|
||||
Run all checks
|
||||
</button>
|
||||
<button
|
||||
className={edit ? "toggled" : ""}
|
||||
onClick={() => setEdit(!edit)}
|
||||
>
|
||||
{edit ? "Close editor" : "Edit Markdown"}
|
||||
</button>
|
||||
</header>
|
||||
{edit && (
|
||||
<section className="editor-panel">
|
||||
<div className="actions">
|
||||
<strong>Markdown</strong>
|
||||
<span className="muted">
|
||||
{dirty ? "Unsaved changes · Ctrl+S saves" : "Saved"}
|
||||
</span>
|
||||
<span className="spacer" />
|
||||
{dirty && (
|
||||
<button
|
||||
onClick={() => {
|
||||
if (window.confirm("Discard your unsaved changes?") && doc) setSource(doc.source);
|
||||
}}
|
||||
>
|
||||
Discard
|
||||
</button>
|
||||
)}
|
||||
<button
|
||||
className="primary"
|
||||
disabled={!canSave}
|
||||
onClick={() => void save()}
|
||||
>
|
||||
Save
|
||||
</button>
|
||||
</div>
|
||||
<Suspense fallback={<p>Loading editor…</p>}>
|
||||
<Editor
|
||||
key={`${path}:${doc?.version}`}
|
||||
source={source}
|
||||
onChange={setSource}
|
||||
/>
|
||||
</Suspense>
|
||||
<p className="muted">
|
||||
Live preview below. Save changes before running steps.
|
||||
</p>
|
||||
</section>
|
||||
)}
|
||||
{notebook.diagnostics.map((d, i) => (
|
||||
<p role="alert" className="banner error" key={i}>
|
||||
{d.line && `Line ${d.line}: `}
|
||||
{d.message}
|
||||
</p>
|
||||
))}
|
||||
{blocks(notebook.blocks)}
|
||||
</article>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
</main>
|
||||
{chat && (
|
||||
<ChatPanel
|
||||
notebookPath={doc?.path}
|
||||
openNotebook={(next) => {
|
||||
if (leave()) {
|
||||
setPage("Notebooks");
|
||||
void load(next);
|
||||
}
|
||||
}}
|
||||
openTerminal={openTerminal}
|
||||
onClose={() => setChat(false)}
|
||||
/>
|
||||
)}
|
||||
</div>
|
||||
</main>
|
||||
{chat && <ChatPanel notebookPath={doc?.path} openNotebook={path => {
|
||||
if (!dirty || window.confirm("Discard unsaved edits?")) void load(path);
|
||||
}} openTerminal={() => { setChat(false); setTerminalOpened(true); setTerminal(true); }} />}
|
||||
{terminalOpened && (
|
||||
<Suspense fallback={<p>Loading terminal...</p>}>
|
||||
<TerminalSlot collapsed={!terminal} />
|
||||
</Suspense>
|
||||
)}
|
||||
{terminalOpened && (
|
||||
<Suspense fallback={<p>Loading terminal…</p>}>
|
||||
<TerminalSlot collapsed={!terminal} onClose={() => setTerminal(false)} />
|
||||
</Suspense>
|
||||
)}
|
||||
</div>
|
||||
{confirm && (
|
||||
<div className="modal-backdrop">
|
||||
<section
|
||||
role="dialog"
|
||||
aria-modal="true"
|
||||
aria-labelledby="confirm-title"
|
||||
>
|
||||
<h2 id="confirm-title">Confirm execution</h2>
|
||||
<p>
|
||||
Run “{confirm.stepId}” with the displayed parameters? This step
|
||||
can change the target host.
|
||||
</p>
|
||||
<Dialog title="Confirm execution" onClose={() => setConfirm(undefined)}>
|
||||
<p>
|
||||
Run “{confirm.stepId}” with the displayed parameters? This step
|
||||
can change the target host.
|
||||
</p>
|
||||
<div className="dialog-actions">
|
||||
<button onClick={() => setConfirm(undefined)}>Cancel</button>
|
||||
<button
|
||||
className="primary"
|
||||
@@ -614,8 +724,8 @@ export function App({ api }: { api: Api }) {
|
||||
>
|
||||
Confirm and run
|
||||
</button>
|
||||
</section>
|
||||
</div>
|
||||
</div>
|
||||
</Dialog>
|
||||
)}
|
||||
{keyPrompt?.hostKey && <HostKeyConfirmation
|
||||
{...keyPrompt.hostKey}
|
||||
|
||||
@@ -12,8 +12,8 @@ const connectChat = (): ChatSocket => new WebSocket(`${location.protocol === "ht
|
||||
type Message = { role: "user" | "assistant" | "tool"; text: string; path?: string };
|
||||
|
||||
/** notebookPath and openNotebook use app paths (relative to notebooks/); the chat wire uses workspace paths. */
|
||||
export function ChatPanel({ notebookPath, openNotebook, openTerminal, connect = connectChat }: {
|
||||
notebookPath?: string; openNotebook(path: string): void; openTerminal(): void; connect?: () => ChatSocket;
|
||||
export function ChatPanel({ notebookPath, openNotebook, openTerminal, onClose, connect = connectChat }: {
|
||||
notebookPath?: string; openNotebook(path: string): void; openTerminal(): void; onClose?(): void; connect?: () => ChatSocket;
|
||||
}) {
|
||||
const [history, setHistory] = useState<ChatConversation[]>([]);
|
||||
const [selected, setSelected] = useState("");
|
||||
@@ -68,10 +68,15 @@ export function ChatPanel({ notebookPath, openNotebook, openTerminal, connect =
|
||||
setError(""); setLogin(false); setSummary(""); setAllowShell(false);
|
||||
}
|
||||
function send(message: ChatClientMessage) { try { socket.current?.send(JSON.stringify(message)); } catch { setBusy(false); setError("Cannot send chat message. Reconnect to continue."); } }
|
||||
return <aside className="chat-panel" aria-label="Chat panel">
|
||||
<h2>Chat with Claude</h2>
|
||||
<div className="actions"><button disabled={busy} onClick={() => choose("")}>New conversation</button>
|
||||
{!ready && <button onClick={() => setAttempt(n => n + 1)}>Reconnect chat</button>}</div>
|
||||
return <aside className="chat-panel side-panel" aria-label="Chat panel">
|
||||
<header className="panel-header">
|
||||
<h2>Chat with Claude</h2>
|
||||
<span className="spacer" />
|
||||
{!ready && <button onClick={() => setAttempt(n => n + 1)}>Reconnect chat</button>}
|
||||
<button disabled={busy} onClick={() => choose("")}>New conversation</button>
|
||||
{onClose && <button className="icon" aria-label="Close chat" onClick={onClose}>×</button>}
|
||||
</header>
|
||||
{notebookPath && <p className="muted">About: <code>{notebookPath}</code></p>}
|
||||
<label>Conversation history<select aria-label="Conversation history" disabled={busy} value={selected} onChange={e => choose(e.target.value)}>
|
||||
<option value="">New conversation</option>{[...history].reverse().map(c => <option key={c.id} value={c.id}>{c.title}</option>)}
|
||||
</select></label>
|
||||
|
||||
+320
-224
@@ -9,8 +9,15 @@ import type {
|
||||
import { json } from "./api";
|
||||
import "./hosts.css";
|
||||
import { HostKeyConfirmation } from "./HostKeyConfirmation";
|
||||
import { CopyButton, Dialog, Menu } from "./ui";
|
||||
const base = "/host-management";
|
||||
const url = (name: string) => `${base}/${encodeURIComponent(name)}`;
|
||||
const credentialNames: Record<string, string> = {
|
||||
shellbook: "ShellBook key",
|
||||
password: "Password",
|
||||
privateKey: "Private key",
|
||||
certificate: "Certificate",
|
||||
};
|
||||
const empty: HostInfo = {
|
||||
name: "",
|
||||
address: "",
|
||||
@@ -23,6 +30,8 @@ export function HostsPage({ onChange }: { onChange?: () => void }) {
|
||||
const [draft, setDraft] = useState<HostInfo>({ ...empty });
|
||||
const [editVersion, setEditVersion] = useState("");
|
||||
const [editing, setEditing] = useState<string>();
|
||||
/** The add/edit server dialog is open. */
|
||||
const [form, setForm] = useState(false);
|
||||
const [credentialHost, setCredentialHost] = useState<string>();
|
||||
const [type, setType] = useState<HostCredentialInput["type"]>("shellbook");
|
||||
const [password, setPassword] = useState("");
|
||||
@@ -84,54 +93,101 @@ export function HostsPage({ onChange }: { onChange?: () => void }) {
|
||||
);
|
||||
}
|
||||
}
|
||||
const closeForm = () => {
|
||||
setForm(false);
|
||||
setEditing(undefined);
|
||||
setDraft({ ...empty });
|
||||
};
|
||||
const closeCredentials = () => {
|
||||
setCredentialHost(undefined);
|
||||
setPassword("");
|
||||
setPrivateKey("");
|
||||
setPassphrase("");
|
||||
};
|
||||
return (
|
||||
<section className="hosts-page" aria-label="Server management">
|
||||
<h1>Servers and SSH credentials</h1>
|
||||
{error && <p role="alert">{error}</p>}
|
||||
{status && <p role="status">{status}</p>}
|
||||
<button
|
||||
disabled={busy}
|
||||
onClick={() =>
|
||||
void perform(async () => {
|
||||
await load();
|
||||
<section className="page hosts-page" aria-label="Server management">
|
||||
<header className="page-header">
|
||||
<div>
|
||||
<h1>Hosts</h1>
|
||||
<p className="muted">
|
||||
Servers ShellBook connects to over SSH, and how it signs in.
|
||||
</p>
|
||||
</div>
|
||||
<span className="spacer" />
|
||||
<button disabled={busy} onClick={() => void perform(load)}>
|
||||
Reload
|
||||
</button>
|
||||
<button
|
||||
className="primary"
|
||||
disabled={!inventory}
|
||||
onClick={() => {
|
||||
setEditing(undefined);
|
||||
setDraft({ ...empty });
|
||||
})
|
||||
}
|
||||
>
|
||||
Reload hosts
|
||||
</button>
|
||||
setForm(true);
|
||||
}}
|
||||
>
|
||||
Add server
|
||||
</button>
|
||||
</header>
|
||||
{error && !form && !credentialHost && (
|
||||
<p role="alert" className="banner error">
|
||||
{error}
|
||||
</p>
|
||||
)}
|
||||
{status && (
|
||||
<p role="status" className="banner ok">
|
||||
{status}
|
||||
</p>
|
||||
)}
|
||||
{inventory && (
|
||||
<>
|
||||
<h2>ShellBook public key</h2>
|
||||
<pre>{inventory.publicKey}</pre>
|
||||
<button
|
||||
onClick={() =>
|
||||
void perform(async () => {
|
||||
await navigator.clipboard.writeText(inventory.publicKey);
|
||||
setStatus("Public key copied");
|
||||
})
|
||||
}
|
||||
>
|
||||
Copy public key
|
||||
</button>
|
||||
<p>{inventory.certificateSupport.reason}</p>
|
||||
<div className="host-list">
|
||||
{!inventory.hosts.length && (
|
||||
<p className="empty">
|
||||
No servers yet. Add one, or run a notebook such as
|
||||
infra/lxc-container.md that adds the machine it creates.
|
||||
</p>
|
||||
)}
|
||||
{inventory.hosts.map((host) => (
|
||||
<article key={host.name}>
|
||||
<h2>{host.name}</h2>
|
||||
<p>
|
||||
{host.user}@{host.address}:{host.port}
|
||||
</p>
|
||||
<p>{host.tags.join(", ")}</p>
|
||||
<p>
|
||||
Authentication: {host.credential.type}{" "}
|
||||
{host.credential.fingerprint}{" "}
|
||||
{host.credential.setAt && `set ${host.credential.setAt}`}
|
||||
</p>
|
||||
<article key={host.name} className="host-row" aria-label={host.name}>
|
||||
<div className="host-main">
|
||||
<h2>{host.name}</h2>
|
||||
<code>
|
||||
{host.user}@{host.address}
|
||||
{host.port === 22 ? "" : `:${host.port}`}
|
||||
</code>
|
||||
</div>
|
||||
<div className="host-meta">
|
||||
{host.tags.map((tag) => (
|
||||
<span key={tag} className={`chip ${tag === "prod" ? "warn" : ""}`}>
|
||||
{tag}
|
||||
</span>
|
||||
))}
|
||||
<span
|
||||
className="chip"
|
||||
title={[
|
||||
host.credential.fingerprint,
|
||||
host.credential.setAt && `set ${host.credential.setAt}`,
|
||||
]
|
||||
.filter(Boolean)
|
||||
.join(" · ")}
|
||||
>
|
||||
{credentialNames[host.credential.type] ?? host.credential.type}
|
||||
</span>
|
||||
</div>
|
||||
<div className="actions">
|
||||
<button
|
||||
disabled={busy}
|
||||
aria-label={`Test connection to ${host.name}`}
|
||||
onClick={() =>
|
||||
void perform(() => action(host.name, { action: "test" }))
|
||||
}
|
||||
>
|
||||
Test
|
||||
</button>
|
||||
<button
|
||||
disabled={busy}
|
||||
aria-label={`Edit ${host.name}`}
|
||||
onClick={() => {
|
||||
setEditing(host.name);
|
||||
setEditVersion(inventory.version);
|
||||
@@ -142,12 +198,15 @@ export function HostsPage({ onChange }: { onChange?: () => void }) {
|
||||
port: host.port,
|
||||
tags: host.tags,
|
||||
});
|
||||
setError("");
|
||||
setForm(true);
|
||||
}}
|
||||
>
|
||||
Edit {host.name}
|
||||
Edit
|
||||
</button>
|
||||
<button
|
||||
disabled={busy}
|
||||
aria-label={`SSH credentials for ${host.name}`}
|
||||
onClick={() => {
|
||||
setCredentialHost(host.name);
|
||||
setType("shellbook");
|
||||
@@ -156,168 +215,201 @@ export function HostsPage({ onChange }: { onChange?: () => void }) {
|
||||
setPassphrase("");
|
||||
}}
|
||||
>
|
||||
SSH credentials for {host.name}
|
||||
</button>
|
||||
<button
|
||||
disabled={busy}
|
||||
onClick={() =>
|
||||
void perform(() => action(host.name, { action: "test" }))
|
||||
}
|
||||
>
|
||||
Test connection to {host.name}
|
||||
</button>
|
||||
<button
|
||||
disabled={busy || host.credential.type !== "password"}
|
||||
onClick={() =>
|
||||
void perform(async () => {
|
||||
const { script } = await json<{ script: string }>(
|
||||
`${url(host.name)}/install-key`,
|
||||
);
|
||||
setInstall({ host: host.name, script });
|
||||
})
|
||||
}
|
||||
>
|
||||
Install ShellBook key on {host.name}
|
||||
</button>
|
||||
<button
|
||||
disabled={busy}
|
||||
onClick={() => {
|
||||
if (
|
||||
window.confirm(
|
||||
`Forget trusted SSH host key for ${host.name}? The next connection requires verification.`,
|
||||
)
|
||||
)
|
||||
void perform(async () => {
|
||||
await json(`${url(host.name)}/known-key`, "DELETE");
|
||||
setStatus("Host key forgotten");
|
||||
});
|
||||
}}
|
||||
>
|
||||
Forget host key for {host.name}
|
||||
</button>
|
||||
<button
|
||||
disabled={busy}
|
||||
onClick={() => {
|
||||
if (
|
||||
window.confirm(
|
||||
`Delete ${host.name} and its stored credential?`,
|
||||
)
|
||||
)
|
||||
void perform(async () => {
|
||||
await json(url(host.name), "DELETE", {
|
||||
baseVersion: inventory.version,
|
||||
});
|
||||
await load();
|
||||
onChange?.();
|
||||
});
|
||||
}}
|
||||
>
|
||||
Delete {host.name}
|
||||
Credentials
|
||||
</button>
|
||||
<Menu label={`More actions for ${host.name}`}>
|
||||
{(close) => (
|
||||
<>
|
||||
<button
|
||||
role="menuitem"
|
||||
disabled={busy || host.credential.type !== "password"}
|
||||
title={
|
||||
host.credential.type === "password"
|
||||
? undefined
|
||||
: "Needs a saved password"
|
||||
}
|
||||
onClick={() => {
|
||||
close();
|
||||
void perform(async () => {
|
||||
const { script } = await json<{ script: string }>(
|
||||
`${url(host.name)}/install-key`,
|
||||
);
|
||||
setInstall({ host: host.name, script });
|
||||
});
|
||||
}}
|
||||
>
|
||||
Install ShellBook key on {host.name}
|
||||
</button>
|
||||
<button
|
||||
role="menuitem"
|
||||
disabled={busy}
|
||||
onClick={() => {
|
||||
close();
|
||||
if (
|
||||
window.confirm(
|
||||
`Forget trusted SSH host key for ${host.name}? The next connection requires verification.`,
|
||||
)
|
||||
)
|
||||
void perform(async () => {
|
||||
await json(`${url(host.name)}/known-key`, "DELETE");
|
||||
setStatus("Host key forgotten");
|
||||
});
|
||||
}}
|
||||
>
|
||||
Forget host key
|
||||
</button>
|
||||
<button
|
||||
role="menuitem"
|
||||
className="danger"
|
||||
disabled={busy}
|
||||
onClick={() => {
|
||||
close();
|
||||
if (
|
||||
window.confirm(
|
||||
`Delete ${host.name} and its stored credential?`,
|
||||
)
|
||||
)
|
||||
void perform(async () => {
|
||||
await json(url(host.name), "DELETE", {
|
||||
baseVersion: inventory.version,
|
||||
});
|
||||
await load();
|
||||
onChange?.();
|
||||
});
|
||||
}}
|
||||
>
|
||||
Delete {host.name}
|
||||
</button>
|
||||
</>
|
||||
)}
|
||||
</Menu>
|
||||
</div>
|
||||
</article>
|
||||
))}
|
||||
</div>
|
||||
<h2>{editing ? `Edit ${editing}` : "Add server"}</h2>
|
||||
<form
|
||||
onSubmit={(e) => {
|
||||
e.preventDefault();
|
||||
void perform(async () => {
|
||||
await json(
|
||||
editing ? url(editing) : base,
|
||||
editing ? "PUT" : "POST",
|
||||
{
|
||||
host: draft,
|
||||
baseVersion: editing ? editVersion : inventory.version,
|
||||
},
|
||||
);
|
||||
setEditing(undefined);
|
||||
setDraft({ ...empty });
|
||||
await load();
|
||||
onChange?.();
|
||||
});
|
||||
}}
|
||||
>
|
||||
<label>
|
||||
Name
|
||||
<input
|
||||
required
|
||||
pattern="[A-Za-z0-9._-]+"
|
||||
value={draft.name}
|
||||
onChange={(e) => setDraft({ ...draft, name: e.target.value })}
|
||||
/>
|
||||
</label>
|
||||
<label>
|
||||
Address
|
||||
<input
|
||||
required
|
||||
value={draft.address}
|
||||
onChange={(e) =>
|
||||
setDraft({ ...draft, address: e.target.value })
|
||||
}
|
||||
/>
|
||||
</label>
|
||||
<label>
|
||||
SSH user
|
||||
<input
|
||||
required
|
||||
value={draft.user}
|
||||
onChange={(e) => setDraft({ ...draft, user: e.target.value })}
|
||||
/>
|
||||
</label>
|
||||
<label>
|
||||
Port
|
||||
<input
|
||||
required
|
||||
type="number"
|
||||
min="1"
|
||||
max="65535"
|
||||
value={draft.port}
|
||||
onChange={(e) =>
|
||||
setDraft({ ...draft, port: Number(e.target.value) })
|
||||
}
|
||||
/>
|
||||
</label>
|
||||
<label>
|
||||
Tags (comma separated)
|
||||
<input
|
||||
value={draft.tags.join(",")}
|
||||
onChange={(e) =>
|
||||
setDraft({
|
||||
...draft,
|
||||
tags: e.target.value
|
||||
.split(",")
|
||||
.map((t) => t.trim())
|
||||
.filter(Boolean),
|
||||
})
|
||||
}
|
||||
/>
|
||||
</label>
|
||||
<button disabled={busy}>Save server</button>
|
||||
<button
|
||||
type="button"
|
||||
onClick={() => {
|
||||
setEditing(undefined);
|
||||
setDraft({ ...empty });
|
||||
}}
|
||||
<details className="card public-key">
|
||||
<summary>ShellBook public key</summary>
|
||||
<p className="muted">
|
||||
Add it to <code>~/.ssh/authorized_keys</code> on a server, or save
|
||||
the server's password under Credentials and use “Install
|
||||
ShellBook key” from its ⋯ menu.
|
||||
</p>
|
||||
<pre>{inventory.publicKey}</pre>
|
||||
<div className="actions">
|
||||
<CopyButton label="Copy public key" text={() => inventory.publicKey} />
|
||||
</div>
|
||||
<p className="muted">{inventory.certificateSupport.reason}</p>
|
||||
</details>
|
||||
{form && (
|
||||
<Dialog
|
||||
title={editing ? `Edit ${editing}` : "Add server"}
|
||||
onClose={closeForm}
|
||||
>
|
||||
New server
|
||||
</button>
|
||||
</form>
|
||||
<form
|
||||
className="grid-form"
|
||||
onSubmit={(e) => {
|
||||
e.preventDefault();
|
||||
void perform(async () => {
|
||||
await json(
|
||||
editing ? url(editing) : base,
|
||||
editing ? "PUT" : "POST",
|
||||
{
|
||||
host: draft,
|
||||
baseVersion: editing ? editVersion : inventory.version,
|
||||
},
|
||||
);
|
||||
closeForm();
|
||||
await load();
|
||||
onChange?.();
|
||||
});
|
||||
}}
|
||||
>
|
||||
<label>
|
||||
Name
|
||||
<input
|
||||
required
|
||||
pattern="[A-Za-z0-9._-]+"
|
||||
placeholder="web-1"
|
||||
value={draft.name}
|
||||
onChange={(e) => setDraft({ ...draft, name: e.target.value })}
|
||||
/>
|
||||
</label>
|
||||
<label>
|
||||
Address
|
||||
<input
|
||||
required
|
||||
placeholder="10.0.0.5 or host.example.org"
|
||||
value={draft.address}
|
||||
onChange={(e) =>
|
||||
setDraft({ ...draft, address: e.target.value })
|
||||
}
|
||||
/>
|
||||
</label>
|
||||
<label>
|
||||
SSH user
|
||||
<input
|
||||
required
|
||||
value={draft.user}
|
||||
onChange={(e) => setDraft({ ...draft, user: e.target.value })}
|
||||
/>
|
||||
</label>
|
||||
<label>
|
||||
Port
|
||||
<input
|
||||
required
|
||||
type="number"
|
||||
min="1"
|
||||
max="65535"
|
||||
value={draft.port}
|
||||
onChange={(e) =>
|
||||
setDraft({ ...draft, port: Number(e.target.value) })
|
||||
}
|
||||
/>
|
||||
</label>
|
||||
<label className="full">
|
||||
Tags (comma separated; “prod” asks before every run)
|
||||
<input
|
||||
value={draft.tags.join(",")}
|
||||
onChange={(e) =>
|
||||
setDraft({
|
||||
...draft,
|
||||
tags: e.target.value
|
||||
.split(",")
|
||||
.map((t) => t.trim())
|
||||
.filter(Boolean),
|
||||
})
|
||||
}
|
||||
/>
|
||||
</label>
|
||||
{error && (
|
||||
<p role="alert" className="error full">
|
||||
{error}
|
||||
</p>
|
||||
)}
|
||||
<div className="dialog-actions full">
|
||||
<button type="button" onClick={closeForm}>
|
||||
Cancel
|
||||
</button>
|
||||
<button className="primary" disabled={busy}>
|
||||
Save server
|
||||
</button>
|
||||
</div>
|
||||
</form>
|
||||
</Dialog>
|
||||
)}
|
||||
</>
|
||||
)}
|
||||
{credentialHost && (
|
||||
<section
|
||||
role="dialog"
|
||||
aria-modal="true"
|
||||
aria-label={`SSH credentials for ${credentialHost}`}
|
||||
<Dialog
|
||||
title={`SSH credentials for ${credentialHost}`}
|
||||
onClose={closeCredentials}
|
||||
>
|
||||
<h2>SSH credentials for {credentialHost}</h2>
|
||||
<p>
|
||||
<p className="muted">
|
||||
Saved secrets cannot be read back. Blank fields do not represent the
|
||||
existing credential.
|
||||
</p>
|
||||
<form
|
||||
className="stack"
|
||||
onSubmit={(e) => {
|
||||
e.preventDefault();
|
||||
const credential: HostCredentialInput =
|
||||
@@ -372,6 +464,7 @@ export function HostsPage({ onChange }: { onChange?: () => void }) {
|
||||
Private key
|
||||
<textarea
|
||||
required
|
||||
rows={6}
|
||||
value={privateKey}
|
||||
onChange={(e) => setPrivateKey(e.target.value)}
|
||||
/>
|
||||
@@ -402,51 +495,54 @@ export function HostsPage({ onChange }: { onChange?: () => void }) {
|
||||
</label>
|
||||
</>
|
||||
)}
|
||||
<button disabled={busy}>Save authentication</button>
|
||||
<button
|
||||
type="button"
|
||||
onClick={() => {
|
||||
setCredentialHost(undefined);
|
||||
setPassword("");
|
||||
setPrivateKey("");
|
||||
setPassphrase("");
|
||||
}}
|
||||
>
|
||||
Cancel
|
||||
</button>
|
||||
{error && (
|
||||
<p role="alert" className="error">
|
||||
{error}
|
||||
</p>
|
||||
)}
|
||||
<div className="dialog-actions">
|
||||
<button type="button" onClick={closeCredentials}>
|
||||
Cancel
|
||||
</button>
|
||||
<button className="primary" disabled={busy}>
|
||||
Save authentication
|
||||
</button>
|
||||
</div>
|
||||
</form>
|
||||
</section>
|
||||
</Dialog>
|
||||
)}
|
||||
{install && (
|
||||
<section
|
||||
role="dialog"
|
||||
aria-modal="true"
|
||||
aria-label="Install ShellBook key"
|
||||
<Dialog
|
||||
wide
|
||||
title={`Install ShellBook key on ${install.host}`}
|
||||
onClose={() => setInstall(undefined)}
|
||||
>
|
||||
<h2>Install ShellBook key on {install.host}</h2>
|
||||
<p>
|
||||
<p className="muted">
|
||||
This exact script runs using the stored password. After success,
|
||||
select ShellBook key in SSH credentials to remove the saved
|
||||
password.
|
||||
</p>
|
||||
<pre>{install.script}</pre>
|
||||
<button
|
||||
disabled={busy}
|
||||
onClick={() =>
|
||||
void perform(() =>
|
||||
action(install.host, {
|
||||
action: "install-key",
|
||||
script: install.script,
|
||||
}),
|
||||
)
|
||||
}
|
||||
>
|
||||
Run displayed script
|
||||
</button>
|
||||
<button onClick={() => setInstall(undefined)}>
|
||||
Cancel installation
|
||||
</button>
|
||||
</section>
|
||||
<pre className="script">{install.script}</pre>
|
||||
<div className="dialog-actions">
|
||||
<button onClick={() => setInstall(undefined)}>
|
||||
Cancel installation
|
||||
</button>
|
||||
<button
|
||||
className="primary"
|
||||
disabled={busy}
|
||||
onClick={() =>
|
||||
void perform(() =>
|
||||
action(install.host, {
|
||||
action: "install-key",
|
||||
script: install.script,
|
||||
}),
|
||||
)
|
||||
}
|
||||
>
|
||||
Run displayed script
|
||||
</button>
|
||||
</div>
|
||||
</Dialog>
|
||||
)}
|
||||
{trust && (
|
||||
<HostKeyConfirmation
|
||||
|
||||
+109
-63
@@ -3,6 +3,7 @@ import { useState } from "react";
|
||||
import type { NotebookSummary } from "@shellbook/core";
|
||||
import type { Api } from "./api";
|
||||
import { newNotebook } from "./authoring";
|
||||
import { Dialog, Menu } from "./ui";
|
||||
type Node = { folders: Map<string, Node>; files: NotebookSummary[] };
|
||||
function tree(list: NotebookSummary[]): Node {
|
||||
const root: Node = { folders: new Map(), files: [] };
|
||||
@@ -40,6 +41,10 @@ export function NotebookList({
|
||||
>();
|
||||
const [error, setError] = useState("");
|
||||
const [busy, setBusy] = useState(false);
|
||||
const choose = (op: "rename" | "duplicate" | "delete") => {
|
||||
setAction(op);
|
||||
setError("");
|
||||
};
|
||||
const render = (node: Node) => (
|
||||
<>
|
||||
{[...node.folders]
|
||||
@@ -51,67 +56,94 @@ export function NotebookList({
|
||||
</details>
|
||||
))}
|
||||
{node.files.map((item) => (
|
||||
<button
|
||||
className={item.path === path ? "selected" : ""}
|
||||
<div
|
||||
className={`notebook-item ${item.path === path ? "selected" : ""}`}
|
||||
key={item.path}
|
||||
onClick={() => onSelect(item.path)}
|
||||
>
|
||||
{item.title}
|
||||
<small>{item.path}</small>
|
||||
</button>
|
||||
<button
|
||||
aria-current={item.path === path ? "page" : undefined}
|
||||
title={item.path}
|
||||
onClick={() => onSelect(item.path)}
|
||||
>
|
||||
{item.title}
|
||||
</button>
|
||||
{item.path === path && (
|
||||
<Menu label={`Actions for ${item.title}`}>
|
||||
{(close) =>
|
||||
(["rename", "duplicate", "delete"] as const).map((op) => (
|
||||
<button
|
||||
key={op}
|
||||
role="menuitem"
|
||||
className={op === "delete" ? "danger" : ""}
|
||||
onClick={() => {
|
||||
close();
|
||||
choose(op);
|
||||
}}
|
||||
>
|
||||
{op === "rename"
|
||||
? "Rename / move"
|
||||
: op === "duplicate"
|
||||
? "Duplicate"
|
||||
: "Delete"}
|
||||
</button>
|
||||
))
|
||||
}
|
||||
</Menu>
|
||||
)}
|
||||
</div>
|
||||
))}
|
||||
</>
|
||||
);
|
||||
const shown = list.filter((n) =>
|
||||
`${n.path} ${n.title}`.toLowerCase().includes(search.toLowerCase()),
|
||||
);
|
||||
return (
|
||||
<>
|
||||
<label>
|
||||
Search notebooks
|
||||
<div className="sidebar-tools">
|
||||
<input
|
||||
type="search"
|
||||
aria-label="Search notebooks"
|
||||
placeholder="Search notebooks"
|
||||
value={search}
|
||||
onChange={(e) => setSearch(e.target.value)}
|
||||
/>
|
||||
</label>
|
||||
<button
|
||||
onClick={() => {
|
||||
setAction("new");
|
||||
setError("");
|
||||
}}
|
||||
>
|
||||
New notebook
|
||||
</button>
|
||||
<button
|
||||
className="icon"
|
||||
aria-label="New notebook"
|
||||
title="New notebook"
|
||||
onClick={() => {
|
||||
setAction("new");
|
||||
setError("");
|
||||
}}
|
||||
>
|
||||
+
|
||||
</button>
|
||||
</div>
|
||||
<nav aria-label="Notebooks">
|
||||
{render(
|
||||
tree(
|
||||
list.filter((n) =>
|
||||
`${n.path} ${n.title}`
|
||||
.toLowerCase()
|
||||
.includes(search.toLowerCase()),
|
||||
),
|
||||
),
|
||||
{render(tree(shown))}
|
||||
{!shown.length && (
|
||||
<p className="muted">
|
||||
{list.length ? "No notebook matches." : "No notebooks yet."}
|
||||
</p>
|
||||
)}
|
||||
</nav>
|
||||
{path && (
|
||||
<div className="actions">
|
||||
{(["rename", "duplicate", "delete"] as const).map((op) => (
|
||||
<button
|
||||
key={op}
|
||||
onClick={() => {
|
||||
setAction(op);
|
||||
setError("");
|
||||
}}
|
||||
>
|
||||
{op === "rename"
|
||||
? "Rename / move"
|
||||
: op === "duplicate"
|
||||
? "Duplicate"
|
||||
: "Delete"}
|
||||
</button>
|
||||
))}
|
||||
</div>
|
||||
)}
|
||||
{action && (
|
||||
<Dialog
|
||||
title={
|
||||
action === "new"
|
||||
? "New notebook"
|
||||
: action === "rename"
|
||||
? "Rename or move notebook"
|
||||
: action === "duplicate"
|
||||
? "Duplicate notebook"
|
||||
: "Delete notebook"
|
||||
}
|
||||
onClose={() => {
|
||||
if (!busy) setAction(undefined);
|
||||
}}
|
||||
>
|
||||
<form
|
||||
className="stack"
|
||||
key={`${action}:${path}`}
|
||||
aria-label="Manage notebook"
|
||||
onSubmit={async (e) => {
|
||||
@@ -158,18 +190,22 @@ export function NotebookList({
|
||||
}
|
||||
}}
|
||||
>
|
||||
<strong>
|
||||
{action === "delete"
|
||||
? `Delete ${path}? This cannot be undone.`
|
||||
: action === "new"
|
||||
? "New notebook"
|
||||
: `${action} ${path}`}
|
||||
</strong>
|
||||
{action === "delete" ? (
|
||||
<p>
|
||||
Delete <code>{path}</code>? This cannot be undone.
|
||||
</p>
|
||||
) : (
|
||||
action !== "new" && (
|
||||
<p className="muted">
|
||||
From <code>{path}</code>
|
||||
</p>
|
||||
)
|
||||
)}
|
||||
{action === "new" ? (
|
||||
<>
|
||||
<label>
|
||||
Name
|
||||
<input name="name" required />
|
||||
<input name="name" required placeholder="debian-upgrade" />
|
||||
</label>
|
||||
<label>
|
||||
Folder (optional)
|
||||
@@ -196,18 +232,28 @@ export function NotebookList({
|
||||
</label>
|
||||
)
|
||||
)}
|
||||
<button disabled={busy}>
|
||||
{action === "delete" ? "Confirm delete" : "Apply"}
|
||||
</button>
|
||||
<button
|
||||
type="button"
|
||||
disabled={busy}
|
||||
onClick={() => setAction(undefined)}
|
||||
>
|
||||
Cancel
|
||||
</button>
|
||||
{error && <p role="alert">{error}</p>}
|
||||
{error && (
|
||||
<p role="alert" className="error">
|
||||
{error}
|
||||
</p>
|
||||
)}
|
||||
<div className="dialog-actions">
|
||||
<button
|
||||
type="button"
|
||||
disabled={busy}
|
||||
onClick={() => setAction(undefined)}
|
||||
>
|
||||
Cancel
|
||||
</button>
|
||||
<button
|
||||
className={action === "delete" ? "danger" : "primary"}
|
||||
disabled={busy}
|
||||
>
|
||||
{action === "delete" ? "Confirm delete" : "Apply"}
|
||||
</button>
|
||||
</div>
|
||||
</form>
|
||||
</Dialog>
|
||||
)}
|
||||
</>
|
||||
);
|
||||
|
||||
@@ -1,3 +1,4 @@
|
||||
import { useState } from "react";
|
||||
import type { HostInfo, Notebook, ParamDef, ParamValues } from "@shellbook/core";
|
||||
|
||||
/** An included notebook (`::use`) whose parameters the form shows as a group. */
|
||||
@@ -13,6 +14,7 @@ export function ParamsForm({
|
||||
hosts,
|
||||
groups = [],
|
||||
onChange,
|
||||
onReset,
|
||||
}: {
|
||||
notebook: Notebook;
|
||||
values: ParamValues;
|
||||
@@ -21,7 +23,10 @@ export function ParamsForm({
|
||||
/** Active included notebooks; parameters of inactive ones are hidden. */
|
||||
groups?: ParamGroup[];
|
||||
onChange(name: string, value: string): void;
|
||||
/** Clears the values typed for this notebook. */
|
||||
onReset?(): void;
|
||||
}) {
|
||||
const [open, setOpen] = useState(true);
|
||||
const field = (param: ParamDef) => {
|
||||
const id = `param-${param.name}`;
|
||||
const local = param.scope ? param.name.slice(param.scope.length + 1) : param.name;
|
||||
@@ -31,6 +36,8 @@ export function ParamsForm({
|
||||
value: values[param.name] ?? "",
|
||||
"aria-labelledby": `${id}-label`,
|
||||
"aria-invalid": !!errors[param.name],
|
||||
// Red only for a wrong value; an empty field just still needs one.
|
||||
className: errors[param.name] && values[param.name] ? "invalid" : undefined,
|
||||
"aria-describedby": errors[param.name] ? `${id}-error` : undefined,
|
||||
onChange: (
|
||||
e: React.ChangeEvent<HTMLInputElement | HTMLSelectElement>,
|
||||
@@ -61,21 +68,47 @@ export function ParamsForm({
|
||||
/>
|
||||
)}
|
||||
{errors[param.name] && (
|
||||
<small id={`${id}-error`} className="error">
|
||||
// An empty field only needs a value: say so quietly; a wrong value is an error.
|
||||
<small id={`${id}-error`} className={values[param.name] ? "error" : "muted"}>
|
||||
{errors[param.name]}
|
||||
</small>
|
||||
)}
|
||||
</label>
|
||||
);
|
||||
};
|
||||
const shown = [
|
||||
...notebook.params.filter((param) => !param.scope),
|
||||
...groups.flatMap((group) => notebook.params.filter((param) => param.scope === group.scope)),
|
||||
];
|
||||
const missing = shown.filter((param) => param.required && !values[param.name]).length;
|
||||
if (!shown.length) return null;
|
||||
return (
|
||||
<form
|
||||
className="params"
|
||||
aria-label="Notebook parameters"
|
||||
onSubmit={(e) => e.preventDefault()}
|
||||
>
|
||||
{notebook.params.filter((param) => !param.scope).map(field)}
|
||||
{groups.map((group) => {
|
||||
<header>
|
||||
<h2>Parameters</h2>
|
||||
<small className={missing ? "pending" : "ok"}>
|
||||
{missing ? `${missing} required missing` : "All required set"}
|
||||
</small>
|
||||
{onReset && open && (
|
||||
<button type="button" className="link" onClick={onReset}>
|
||||
Reset
|
||||
</button>
|
||||
)}
|
||||
<button
|
||||
type="button"
|
||||
className="link"
|
||||
aria-expanded={open}
|
||||
onClick={() => setOpen(!open)}
|
||||
>
|
||||
{open ? "Hide" : "Show"}
|
||||
</button>
|
||||
</header>
|
||||
{open && notebook.params.filter((param) => !param.scope).map(field)}
|
||||
{open && groups.map((group) => {
|
||||
const params = notebook.params.filter((param) => param.scope === group.scope);
|
||||
return params.length ? (
|
||||
<fieldset key={group.scope}>
|
||||
|
||||
+112
-63
@@ -6,105 +6,154 @@ import type {
|
||||
} from "@shellbook/core";
|
||||
import { settingsApi } from "./settingsApi";
|
||||
import { PasswordForm } from "./PasswordForm";
|
||||
export function SettingsPage({ openTerminal }: { openTerminal: () => void }) {
|
||||
|
||||
function duration(seconds: number): string {
|
||||
const days = seconds / 86400;
|
||||
return days >= 1
|
||||
? `${Number.isInteger(days) ? days : days.toFixed(1)} day${days === 1 ? "" : "s"}`
|
||||
: `${Math.round(seconds / 3600)} hours`;
|
||||
}
|
||||
|
||||
export function SettingsPage({
|
||||
openTerminal,
|
||||
onSignOut,
|
||||
}: {
|
||||
openTerminal: () => void;
|
||||
/** Called after this browser signed out. */
|
||||
onSignOut?: () => void;
|
||||
}) {
|
||||
const [info, setInfo] = useState<SystemInfoResponse>();
|
||||
const [claude, setClaude] = useState<ClaudeStatusResponse>();
|
||||
const [claude, setClaude] = useState<ClaudeStatusResponse | "error">();
|
||||
const [session, setSession] = useState<SessionSettingsResponse>();
|
||||
const [message, setMessage] = useState("");
|
||||
const [busy, setBusy] = useState(false);
|
||||
useEffect(() => {
|
||||
let active = true;
|
||||
Promise.all([
|
||||
settingsApi.system(),
|
||||
settingsApi.claude(),
|
||||
settingsApi.session(),
|
||||
])
|
||||
.then(([i, c, s]) => {
|
||||
if (active) {
|
||||
setInfo(i);
|
||||
setClaude(c);
|
||||
setSession(s);
|
||||
}
|
||||
})
|
||||
.catch(() => {
|
||||
if (active)
|
||||
setMessage("Unable to load settings. Sign in again or retry.");
|
||||
});
|
||||
const failed = () => {
|
||||
if (active) setMessage("Unable to load settings. Sign in again or retry.");
|
||||
};
|
||||
// Independent requests: the slower Claude check must not hold back the rest.
|
||||
settingsApi.system().then((i) => active && setInfo(i), failed);
|
||||
settingsApi.session().then((s) => active && setSession(s), failed);
|
||||
settingsApi.claude().then(
|
||||
(c) => active && setClaude(c),
|
||||
() => active && setClaude("error"),
|
||||
);
|
||||
return () => {
|
||||
active = false;
|
||||
};
|
||||
}, []);
|
||||
return (
|
||||
<div className="notebook">
|
||||
<h1>Settings</h1>
|
||||
<section>
|
||||
<div className="page settings-page">
|
||||
<header className="page-header">
|
||||
<div>
|
||||
<h1>Settings</h1>
|
||||
<p className="muted">Sign-in, the Claude CLI and this installation.</p>
|
||||
</div>
|
||||
</header>
|
||||
{message && (
|
||||
<p role="status" className="banner">
|
||||
{message}
|
||||
</p>
|
||||
)}
|
||||
<section className="card">
|
||||
<h2>Password and sessions</h2>
|
||||
<PasswordForm submit={settingsApi.password} />
|
||||
<hr />
|
||||
{session && (
|
||||
<p>
|
||||
Session lifetime: {session.lifetimeSeconds} seconds (
|
||||
{session.lifetimeSeconds / 86400} days).
|
||||
<p className="muted">
|
||||
Sessions last {duration(session.lifetimeSeconds)} (
|
||||
{session.lifetimeSeconds} seconds).
|
||||
</p>
|
||||
)}
|
||||
<button
|
||||
disabled={busy}
|
||||
onClick={async () => {
|
||||
setBusy(true);
|
||||
try {
|
||||
await settingsApi.revoke();
|
||||
setMessage(
|
||||
"Other sessions signed out. This browser remains signed in.",
|
||||
);
|
||||
} catch {
|
||||
setMessage("Unable to sign out sessions. Try again.");
|
||||
} finally {
|
||||
setBusy(false);
|
||||
}
|
||||
}}
|
||||
>
|
||||
Sign out all sessions
|
||||
</button>
|
||||
<div className="actions">
|
||||
<button
|
||||
disabled={busy}
|
||||
onClick={async () => {
|
||||
setBusy(true);
|
||||
try {
|
||||
await settingsApi.revoke();
|
||||
setMessage(
|
||||
"Other sessions signed out. This browser remains signed in.",
|
||||
);
|
||||
} catch {
|
||||
setMessage("Unable to sign out sessions. Try again.");
|
||||
} finally {
|
||||
setBusy(false);
|
||||
}
|
||||
}}
|
||||
>
|
||||
Sign out all sessions
|
||||
</button>
|
||||
{onSignOut && (
|
||||
<button
|
||||
disabled={busy}
|
||||
onClick={async () => {
|
||||
try {
|
||||
await settingsApi.logout();
|
||||
onSignOut();
|
||||
} catch {
|
||||
setMessage("Unable to sign out. Try again.");
|
||||
}
|
||||
}}
|
||||
>
|
||||
Sign out this browser
|
||||
</button>
|
||||
)}
|
||||
</div>
|
||||
</section>
|
||||
<section>
|
||||
<section className="card">
|
||||
<h2>Claude CLI</h2>
|
||||
{claude ? (
|
||||
<>
|
||||
<p>
|
||||
{claude === undefined ? (
|
||||
<p className="muted">Checking the Claude CLI…</p>
|
||||
) : claude === "error" ? (
|
||||
<p className="error">Unable to check the Claude CLI.</p>
|
||||
) : (
|
||||
<ul className="checklist">
|
||||
<li className={claude.available ? "ok" : "bad"}>
|
||||
{claude.available
|
||||
? `Available: ${claude.version}`
|
||||
: "Claude is unavailable on PATH or did not respond."}
|
||||
</p>
|
||||
<p>
|
||||
</li>
|
||||
<li className={claude.loginAppearsPresent ? "ok" : "bad"}>
|
||||
{claude.loginAppearsPresent
|
||||
? "Credentials file exists; login may be available."
|
||||
: "No credentials file found."}
|
||||
</p>
|
||||
</>
|
||||
) : (
|
||||
<p>Checking CLI...</p>
|
||||
</li>
|
||||
</ul>
|
||||
)}
|
||||
<button onClick={openTerminal}>Open terminal to log in</button>
|
||||
<p>
|
||||
Run <code>claude</code>, then <code>/login</code>. Credentials are
|
||||
checked for existence only.
|
||||
<p className="muted">
|
||||
Run <code>claude</code> in the terminal, then <code>/login</code>.
|
||||
Credentials are checked for existence only.
|
||||
</p>
|
||||
<div className="actions">
|
||||
<button onClick={openTerminal}>Open terminal to log in</button>
|
||||
</div>
|
||||
</section>
|
||||
<section>
|
||||
<h2>About/System</h2>
|
||||
{info && (
|
||||
<dl>
|
||||
<section className="card">
|
||||
<h2>About this installation</h2>
|
||||
{info ? (
|
||||
<dl className="facts">
|
||||
<dt>ShellBook version</dt>
|
||||
<dd>{info.version}</dd>
|
||||
<dt>Workspace</dt>
|
||||
<dd>{info.workspacePath}</dd>
|
||||
<dd>
|
||||
<code>{info.workspacePath}</code>
|
||||
</dd>
|
||||
<dt>Data directory</dt>
|
||||
<dd>{info.dataDirPath}</dd>
|
||||
<dd>
|
||||
<code>{info.dataDirPath}</code>
|
||||
</dd>
|
||||
<dt>Node version</dt>
|
||||
<dd>{info.nodeVersion}</dd>
|
||||
</dl>
|
||||
) : (
|
||||
<p className="muted">Loading…</p>
|
||||
)}
|
||||
<p className="muted">
|
||||
Update from the container with <code>shellbook-update</code>.
|
||||
</p>
|
||||
</section>
|
||||
{message && <p role="status">{message}</p>}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
+40
-36
@@ -1,10 +1,10 @@
|
||||
import { ArtifactDownload } from "./ArtifactDownload";
|
||||
import { useState } from "react";
|
||||
import hljs from "highlight.js/lib/core";
|
||||
import bash from "highlight.js/lib/languages/bash";
|
||||
import type { HostInfo, RenderedStep, Step } from "@shellbook/core";
|
||||
import type { DownloadState, RunState } from "./events";
|
||||
import { sshCommand } from "./ssh";
|
||||
import { CopyButton } from "./ui";
|
||||
hljs.registerLanguage("bash", bash);
|
||||
|
||||
function Script({ script }: { script: string }) {
|
||||
@@ -28,6 +28,20 @@ function Script({ script }: { script: string }) {
|
||||
</pre>
|
||||
);
|
||||
}
|
||||
/** One short hint for what a step still needs, without repeating a name. */
|
||||
export function stepProblems(rendered: RenderedStep): string[] {
|
||||
const problems: string[] = [];
|
||||
if (rendered.missing.length)
|
||||
problems.push(`Fill in ${rendered.missing.join(", ")} to run this step.`);
|
||||
const unresolvedHost = !!rendered.host?.includes("{{");
|
||||
for (const [name, error] of Object.entries(rendered.invalid)) {
|
||||
if (rendered.missing.includes(name)) continue;
|
||||
// The target follows from a missing value; the hint above already covers it.
|
||||
if (name === "host" && unresolvedHost && rendered.missing.length) continue;
|
||||
problems.push(`${name}: ${error}`);
|
||||
}
|
||||
return problems;
|
||||
}
|
||||
export function StepCard({
|
||||
step,
|
||||
rendered,
|
||||
@@ -47,56 +61,47 @@ export function StepCard({
|
||||
connected?: boolean;
|
||||
onArtifactState?(runId: string, name: string, state: DownloadState): void;
|
||||
}) {
|
||||
const [notice, setNotice] = useState("");
|
||||
const invalid =
|
||||
rendered.missing.length > 0 || Object.keys(rendered.invalid).length > 0;
|
||||
const problems = stepProblems(rendered);
|
||||
const invalid = problems.length > 0;
|
||||
const busy = run?.status === "running" || run?.status === "hostKey";
|
||||
async function copy(ssh: boolean) {
|
||||
try {
|
||||
await navigator.clipboard.writeText(
|
||||
ssh && host
|
||||
? sshCommand(host, rendered.script, step.attrs.sudo)
|
||||
: rendered.script,
|
||||
);
|
||||
setNotice("Copied");
|
||||
} catch {
|
||||
setNotice("Copy failed. Select and copy the script manually.");
|
||||
}
|
||||
}
|
||||
const target = rendered.local
|
||||
? "ShellBook server"
|
||||
: rendered.host && !rendered.host.includes("{{")
|
||||
? host
|
||||
? `${host.user}@${host.name}`
|
||||
: rendered.host
|
||||
: "no host selected";
|
||||
return (
|
||||
<article
|
||||
className={`step ${run?.status ?? ""}`}
|
||||
className={`step ${step.kind} ${run?.status ?? ""}`}
|
||||
aria-label={step.attrs.title ?? step.attrs.id}
|
||||
>
|
||||
<header>
|
||||
<span className="badge">{step.kind}</span>
|
||||
<span className={`badge kind-${step.kind}`}>{step.kind}</span>
|
||||
<h3>{step.attrs.title ?? step.attrs.id}</h3>
|
||||
<span className="target">
|
||||
{rendered.local
|
||||
? "local · ShellBook server"
|
||||
: (rendered.host ?? "No host selected")}
|
||||
</span>
|
||||
{step.attrs.sudo && <span className="badge">sudo</span>}
|
||||
{(step.attrs.confirm ||
|
||||
(step.kind === "run" && host?.tags.includes("prod"))) && (
|
||||
<span className="badge">confirm</span>
|
||||
<span className="badge warn">confirm</span>
|
||||
)}
|
||||
<span className={`target ${host || rendered.local ? "" : "unset"}`} title="Runs on">
|
||||
→ {target}
|
||||
</span>
|
||||
</header>
|
||||
<Script script={rendered.script} />
|
||||
{invalid && (
|
||||
<p className="error" role="status">
|
||||
{rendered.missing.length > 0 &&
|
||||
`Missing: ${rendered.missing.join(", ")}. `}
|
||||
{Object.entries(rendered.invalid)
|
||||
.map(([name, error]) => `${name}: ${error}`)
|
||||
.join("; ")}
|
||||
<p className="hint" role="status">
|
||||
{problems.join(" ")}
|
||||
</p>
|
||||
)}
|
||||
<div className="actions">
|
||||
<button onClick={() => void copy(false)}>Copy</button>
|
||||
<button disabled={!host || invalid} onClick={() => void copy(true)}>
|
||||
Copy as ssh one-liner
|
||||
</button>
|
||||
<CopyButton text={() => rendered.script} />
|
||||
<CopyButton
|
||||
label="Copy ssh command"
|
||||
title="An ssh one-liner for your own terminal"
|
||||
disabled={!host || invalid}
|
||||
text={() => sshCommand(host!, rendered.script, step.attrs.sudo)}
|
||||
/>
|
||||
<span className="spacer" />
|
||||
<button
|
||||
className="primary"
|
||||
@@ -106,10 +111,9 @@ export function StepCard({
|
||||
{busy ? "Running…" : step.kind === "check" ? "Check" : "Run"}
|
||||
</button>
|
||||
</div>
|
||||
{notice && <small role="status">{notice}</small>}
|
||||
{run && (
|
||||
<section className="result" aria-label="Run output">
|
||||
<div role="status">
|
||||
<div role="status" className="result-status">
|
||||
{run.status === "success"
|
||||
? "✅ Succeeded"
|
||||
: run.status === "failure"
|
||||
|
||||
@@ -9,8 +9,10 @@ import type { TerminalClientMessage } from "@shellbook/core";
|
||||
export function TerminalSlot({
|
||||
collapsed = false,
|
||||
connect = terminalTransport,
|
||||
onClose,
|
||||
}: {
|
||||
collapsed?: boolean;
|
||||
onClose?: () => void;
|
||||
connect?: (session: string) => TerminalTransport;
|
||||
}) {
|
||||
const container = useRef<HTMLDivElement>(null);
|
||||
@@ -105,18 +107,26 @@ export function TerminalSlot({
|
||||
if (!collapsed) refit.current();
|
||||
}, [collapsed]);
|
||||
return (
|
||||
<aside className="terminal" aria-label="Terminal panel" hidden={collapsed}>
|
||||
<h2>Terminal · main</h2>
|
||||
<p>
|
||||
Run `claude` here — it edits notebooks in this workspace; the view
|
||||
reloads live.
|
||||
</p>
|
||||
<div className="actions">
|
||||
<span role="status">{state}</span>
|
||||
<aside className="terminal side-panel" aria-label="Terminal panel" hidden={collapsed}>
|
||||
<header className="panel-header">
|
||||
<h2>Terminal</h2>
|
||||
<span role="status" className={`dot-status ${state === "Connected" ? "ok" : state === "Disconnected" ? "bad" : ""}`}>
|
||||
{state}
|
||||
</span>
|
||||
{state === "Disconnected" && (
|
||||
<button onClick={() => setAttempt((n) => n + 1)}>Reconnect</button>
|
||||
)}
|
||||
</div>
|
||||
<span className="spacer" />
|
||||
{onClose && (
|
||||
<button className="icon" aria-label="Close terminal" onClick={onClose}>
|
||||
×
|
||||
</button>
|
||||
)}
|
||||
</header>
|
||||
<p className="muted">
|
||||
tmux session “main” on the ShellBook server. Run <code>claude</code>{" "}
|
||||
here; notebook edits show up live.
|
||||
</p>
|
||||
<div className="terminal-screen" ref={container} />
|
||||
</aside>
|
||||
);
|
||||
|
||||
+37
-12
@@ -1,12 +1,37 @@
|
||||
.chat-panel { position: sticky; top: 0; height: 100vh; min-width: 0; display: flex; flex-direction: column; gap: .6rem; padding: 1rem; border-left: 1px solid #64748b; box-sizing: border-box; }
|
||||
.chat-panel h2, .chat-panel p { margin: .25rem 0; }
|
||||
.chat-panel select, .chat-panel textarea { width: 100%; box-sizing: border-box; }
|
||||
.chat-panel label { display: block; }
|
||||
.chat-messages { flex: 1; min-height: 120px; overflow-y: auto; overflow-wrap: anywhere; }
|
||||
.chat-messages pre { overflow-x: auto; }
|
||||
.chat-message { padding: .6rem 0; border-bottom: 1px solid #64748b55; }
|
||||
.chat-message.user { opacity: .85; }
|
||||
.chat-shell { margin-top: .5rem; }
|
||||
.chat-panel form { flex-shrink: 0; }
|
||||
@media (max-width: 900px) { .chat-panel { position: static; grid-column: 1 / -1; height: min(800px, 100dvh); } }
|
||||
@media (max-width: 580px) { .with-terminal { display: block; } .chat-panel { padding: .7rem; } }
|
||||
.chat-panel select,
|
||||
.chat-panel textarea {
|
||||
width: 100%;
|
||||
}
|
||||
.chat-messages {
|
||||
flex: 1;
|
||||
min-height: 120px;
|
||||
overflow-y: auto;
|
||||
overflow-wrap: anywhere;
|
||||
border-top: 1px solid var(--line);
|
||||
border-bottom: 1px solid var(--line);
|
||||
}
|
||||
.chat-messages pre {
|
||||
overflow-x: auto;
|
||||
}
|
||||
.chat-message {
|
||||
padding: 0.6rem 0;
|
||||
border-bottom: 1px solid #64748b55;
|
||||
}
|
||||
.chat-message.user {
|
||||
opacity: 0.85;
|
||||
}
|
||||
.chat-panel label.chat-shell {
|
||||
flex-direction: row;
|
||||
align-items: center;
|
||||
gap: 6px;
|
||||
margin-top: 0.5rem;
|
||||
}
|
||||
.chat-panel form {
|
||||
flex-shrink: 0;
|
||||
}
|
||||
.chat-panel form .actions {
|
||||
margin: 8px 0 0;
|
||||
}
|
||||
.chat-panel > p {
|
||||
margin: 0;
|
||||
}
|
||||
|
||||
+50
-41
@@ -1,49 +1,58 @@
|
||||
.hosts-page {
|
||||
padding: 1rem;
|
||||
max-width: 70rem;
|
||||
.host-list {
|
||||
border: 1px solid var(--line);
|
||||
border-radius: 8px;
|
||||
background: var(--panel);
|
||||
margin: 16px 0;
|
||||
}
|
||||
.host-list .empty {
|
||||
padding: 32px 20px;
|
||||
margin: 0;
|
||||
}
|
||||
.host-row {
|
||||
display: grid;
|
||||
grid-template-columns: minmax(0, 1.3fr) minmax(0, 1fr) auto;
|
||||
align-items: center;
|
||||
gap: 12px;
|
||||
padding: 12px 16px;
|
||||
}
|
||||
.host-row + .host-row {
|
||||
border-top: 1px solid var(--line);
|
||||
}
|
||||
.host-main {
|
||||
min-width: 0;
|
||||
}
|
||||
.hosts-page pre {
|
||||
.host-main h2 {
|
||||
font-size: 15px;
|
||||
margin: 0 0 2px;
|
||||
}
|
||||
.host-main code {
|
||||
color: var(--muted);
|
||||
font-size: 12.5px;
|
||||
overflow-wrap: anywhere;
|
||||
}
|
||||
.host-meta {
|
||||
display: flex;
|
||||
flex-wrap: wrap;
|
||||
gap: 6px;
|
||||
}
|
||||
.host-row .actions {
|
||||
margin: 0;
|
||||
flex-wrap: nowrap;
|
||||
}
|
||||
.public-key pre {
|
||||
white-space: pre-wrap;
|
||||
overflow-wrap: anywhere;
|
||||
background: var(--code);
|
||||
border: 1px solid var(--line);
|
||||
border-radius: 5px;
|
||||
padding: 10px 12px;
|
||||
font-size: 12px;
|
||||
}
|
||||
.hosts-page form {
|
||||
display: flex;
|
||||
flex-wrap: wrap;
|
||||
gap: 0.8rem;
|
||||
align-items: end;
|
||||
}
|
||||
.hosts-page label {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
gap: 0.3rem;
|
||||
flex: 1 1 12rem;
|
||||
min-width: 0;
|
||||
}
|
||||
.hosts-page input,
|
||||
.hosts-page textarea,
|
||||
.hosts-page select {
|
||||
width: 100%;
|
||||
box-sizing: border-box;
|
||||
}
|
||||
.hosts-page article,
|
||||
.hosts-page [role="dialog"] {
|
||||
border: 1px solid #777;
|
||||
padding: 1rem;
|
||||
margin-block: 1rem;
|
||||
overflow-wrap: anywhere;
|
||||
}
|
||||
.hosts-page .actions {
|
||||
flex-wrap: wrap;
|
||||
}
|
||||
.hosts-page button {
|
||||
white-space: normal;
|
||||
}
|
||||
@media (max-width: 600px) {
|
||||
.app:has(.hosts-page) {
|
||||
display: block;
|
||||
@media (max-width: 760px) {
|
||||
.host-row {
|
||||
grid-template-columns: minmax(0, 1fr);
|
||||
}
|
||||
.app:has(.hosts-page) .sidebar {
|
||||
width: auto;
|
||||
.host-row .actions {
|
||||
flex-wrap: wrap;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,3 +1,4 @@
|
||||
/* Authoring toolbar above the Markdown editor. */
|
||||
.authoring {
|
||||
display: flex;
|
||||
align-items: end;
|
||||
@@ -5,30 +6,17 @@
|
||||
gap: 0.5rem;
|
||||
margin: 0.75rem 0;
|
||||
}
|
||||
.authoring label,
|
||||
.sidebar form label {
|
||||
.authoring label {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
gap: 0.25rem;
|
||||
font-size: 12px;
|
||||
}
|
||||
.authoring form,
|
||||
.authoring details {
|
||||
flex-basis: 100%;
|
||||
}
|
||||
.sidebar form {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
gap: 0.75rem;
|
||||
margin-top: 1rem;
|
||||
}
|
||||
.sidebar input {
|
||||
min-width: 0;
|
||||
max-width: 100%;
|
||||
}
|
||||
.sidebar nav details {
|
||||
margin-left: 0.5rem;
|
||||
}
|
||||
.sidebar nav summary {
|
||||
cursor: pointer;
|
||||
padding: 0.5rem 0;
|
||||
.authoring input,
|
||||
.authoring select {
|
||||
width: auto;
|
||||
}
|
||||
|
||||
@@ -0,0 +1,39 @@
|
||||
import type { Notebook, ParamValues } from "@shellbook/core";
|
||||
|
||||
/**
|
||||
* Remembers the parameter values typed for a notebook in this browser, so a reload or a
|
||||
* return visit keeps them. Secrets are never stored, and only declared params are kept.
|
||||
*/
|
||||
const key = (path: string) => `shellbook:params:${path}`;
|
||||
|
||||
function storable(notebook: Notebook, values: ParamValues): ParamValues {
|
||||
const kept: ParamValues = {};
|
||||
for (const def of notebook.params) {
|
||||
const value = Object.hasOwn(values, def.name) ? values[def.name] : undefined;
|
||||
if (def.type !== "secret" && value) kept[def.name] = value;
|
||||
}
|
||||
return kept;
|
||||
}
|
||||
|
||||
export function recallValues(path: string, notebook: Notebook): ParamValues {
|
||||
try {
|
||||
const stored: unknown = JSON.parse(localStorage.getItem(key(path)) ?? "{}");
|
||||
if (!stored || typeof stored !== "object" || Array.isArray(stored)) return {};
|
||||
const strings = Object.fromEntries(
|
||||
Object.entries(stored).filter((entry): entry is [string, string] => typeof entry[1] === "string"),
|
||||
);
|
||||
return storable(notebook, strings);
|
||||
} catch {
|
||||
return {};
|
||||
}
|
||||
}
|
||||
|
||||
export function rememberValues(path: string, notebook: Notebook, values: ParamValues): void {
|
||||
try {
|
||||
const kept = storable(notebook, values);
|
||||
if (Object.keys(kept).length) localStorage.setItem(key(path), JSON.stringify(kept));
|
||||
else localStorage.removeItem(key(path));
|
||||
} catch {
|
||||
// Storage may be unavailable (private mode); values then last for this page only.
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,33 @@
|
||||
import type { NavigationPage } from "./HeaderNavigation";
|
||||
|
||||
/** The page and open notebook, kept in the URL hash so reloads and links keep them. */
|
||||
export interface Route {
|
||||
page: NavigationPage;
|
||||
notebook?: string;
|
||||
}
|
||||
|
||||
const pages: Record<string, NavigationPage> = {
|
||||
notebooks: "Notebooks",
|
||||
hosts: "Hosts",
|
||||
settings: "Settings",
|
||||
};
|
||||
|
||||
export function parseRoute(hash: string): Route {
|
||||
const [, page = "", ...rest] = hash.replace(/^#/, "").split("/");
|
||||
const known = pages[page];
|
||||
if (!known) return { page: "Notebooks" };
|
||||
if (known !== "Notebooks" || !rest.length) return { page: known };
|
||||
try {
|
||||
const notebook = rest.map(decodeURIComponent).join("/");
|
||||
return notebook ? { page: known, notebook } : { page: known };
|
||||
} catch {
|
||||
return { page: known };
|
||||
}
|
||||
}
|
||||
|
||||
export function routeHash(route: Route): string {
|
||||
const page = route.page.toLowerCase();
|
||||
return route.page === "Notebooks" && route.notebook
|
||||
? `#/${page}/${route.notebook.split("/").map(encodeURIComponent).join("/")}`
|
||||
: `#/${page}`;
|
||||
}
|
||||
@@ -25,6 +25,7 @@ export const settingsApi = {
|
||||
password: (body: ChangePasswordRequest) =>
|
||||
request<void>("/settings/password", body),
|
||||
revoke: () => request<void>("/settings/sessions/revoke", {}),
|
||||
logout: () => request<void>("/auth/logout", {}),
|
||||
session: () => request<SessionSettingsResponse>("/settings/session"),
|
||||
claude: () => request<ClaudeStatusResponse>("/settings/claude"),
|
||||
system: () => request<SystemInfoResponse>("/settings/system"),
|
||||
|
||||
+912
-465
File diff suppressed because it is too large
Load Diff
@@ -26,6 +26,8 @@ it("adds hosts with accessible fields and optimistic version", async () => {
|
||||
vi.mocked(json).mockResolvedValue(inventory);
|
||||
render(<HostsPage />);
|
||||
await screen.findByText("demo");
|
||||
fireEvent.click(screen.getByRole("button", { name: "Add server" }));
|
||||
expect(screen.getByRole("dialog", { name: "Add server" })).toBeInTheDocument();
|
||||
fireEvent.change(screen.getByLabelText("Name"), { target: { value: "new" } });
|
||||
fireEvent.change(screen.getByLabelText("Address"), {
|
||||
target: { value: "::1" },
|
||||
@@ -42,7 +44,7 @@ it("sends credentials once and clears password fields", async () => {
|
||||
vi.mocked(json).mockResolvedValue(inventory);
|
||||
render(<HostsPage />);
|
||||
await screen.findByText("demo");
|
||||
fireEvent.click(screen.getByText("SSH credentials for demo"));
|
||||
fireEvent.click(screen.getByRole("button", { name: "SSH credentials for demo" }));
|
||||
fireEvent.change(screen.getByLabelText("Authentication"), {
|
||||
target: { value: "password" },
|
||||
});
|
||||
@@ -79,7 +81,8 @@ it("requires fingerprint confirmation and resends the displayed installation scr
|
||||
});
|
||||
render(<HostsPage />);
|
||||
await screen.findByText("demo");
|
||||
fireEvent.click(screen.getByText("Install ShellBook key on demo"));
|
||||
fireEvent.click(screen.getByRole("button", { name: "More actions for demo" }));
|
||||
fireEvent.click(screen.getByRole("menuitem", { name: "Install ShellBook key on demo" }));
|
||||
await screen.findByText("literal script");
|
||||
expect(json).not.toHaveBeenCalledWith(
|
||||
"/host-management/demo/action",
|
||||
@@ -104,7 +107,7 @@ it("loads external changes without silently changing the version of an open edit
|
||||
vi.mocked(json).mockResolvedValue(inventory);
|
||||
render(<HostsPage />);
|
||||
await screen.findByText("demo");
|
||||
fireEvent.click(screen.getByText("Edit demo"));
|
||||
fireEvent.click(screen.getByRole("button", { name: "Edit demo" }));
|
||||
vi.mocked(json).mockResolvedValue({ ...inventory, version: "v2" });
|
||||
window.dispatchEvent(new Event("shellbook:hosts-changed"));
|
||||
await waitFor(() => expect(json).toHaveBeenCalledTimes(2));
|
||||
@@ -124,7 +127,7 @@ it("shows the server's reason for a failed connection test without a conflict hi
|
||||
});
|
||||
render(<HostsPage />);
|
||||
await screen.findByText("demo");
|
||||
fireEvent.click(screen.getByText("Test connection to demo"));
|
||||
fireEvent.click(screen.getByRole("button", { name: "Test connection to demo" }));
|
||||
const alert = await screen.findByText(/SSH authentication failed/);
|
||||
expect(alert.textContent).toBe("SSH authentication failed: check the user and the saved password or key");
|
||||
});
|
||||
|
||||
@@ -75,7 +75,7 @@ it("requires explicit delete confirmation and uses the displayed version", async
|
||||
deleteNotebook: remove,
|
||||
} as unknown as Api
|
||||
}
|
||||
list={[]}
|
||||
list={[{ path: "a.md", title: "A" }]}
|
||||
path="a.md"
|
||||
version="latest"
|
||||
onSelect={vi.fn()}
|
||||
@@ -83,7 +83,10 @@ it("requires explicit delete confirmation and uses the displayed version", async
|
||||
canLeave={() => true}
|
||||
/>,
|
||||
);
|
||||
fireEvent.click(screen.getByRole("button", { name: "Delete" }));
|
||||
// The open notebook has an actions menu; deleting asks again in a dialog.
|
||||
fireEvent.click(screen.getByRole("button", { name: "Actions for A" }));
|
||||
fireEvent.click(screen.getByRole("menuitem", { name: "Delete" }));
|
||||
expect(screen.getByRole("dialog", { name: "Delete notebook" })).toHaveTextContent("a.md");
|
||||
expect(remove).not.toHaveBeenCalled();
|
||||
fireEvent.click(screen.getByRole("button", { name: "Confirm delete" }));
|
||||
await waitFor(() => expect(remove).toHaveBeenCalledWith("a.md", "latest"));
|
||||
|
||||
@@ -1,4 +1,9 @@
|
||||
import "@testing-library/jest-dom/vitest";
|
||||
import { cleanup } from "@testing-library/react";
|
||||
import { afterEach } from "vitest";
|
||||
afterEach(cleanup);
|
||||
afterEach(() => {
|
||||
cleanup();
|
||||
// The app keeps its route in the URL and typed values in localStorage.
|
||||
localStorage.clear();
|
||||
history.replaceState(null, "", "/");
|
||||
});
|
||||
|
||||
@@ -0,0 +1,112 @@
|
||||
import { fireEvent, render, screen, waitFor } from "@testing-library/react";
|
||||
import { expect, it, vi } from "vitest";
|
||||
vi.mock("../Editor", () => ({
|
||||
Editor: ({ source, onChange }: { source: string; onChange(value: string): void }) => (
|
||||
<textarea aria-label="Notebook Markdown" value={source} onChange={(e) => onChange(e.target.value)} />
|
||||
),
|
||||
}));
|
||||
import { parseNotebook } from "@shellbook/core";
|
||||
import type { RenderedStep } from "@shellbook/core";
|
||||
import { App } from "../App";
|
||||
import type { Api } from "../api";
|
||||
import { parseRoute, routeHash } from "../route";
|
||||
import { recallValues, rememberValues } from "../paramMemory";
|
||||
import { stepProblems } from "../StepCard";
|
||||
import { Dialog } from "../ui";
|
||||
import source from "../mock/ssh-key.md?raw";
|
||||
|
||||
const secretBook = parseNotebook(`---
|
||||
params:
|
||||
host: { type: host }
|
||||
token: { type: secret }
|
||||
---
|
||||
# T
|
||||
`);
|
||||
|
||||
it("round-trips page and notebook routes, including encoded segments", () => {
|
||||
for (const route of [
|
||||
{ page: "Hosts" as const },
|
||||
{ page: "Settings" as const },
|
||||
{ page: "Notebooks" as const, notebook: "ops/linux/a b#1.md" },
|
||||
])
|
||||
expect(parseRoute(routeHash(route))).toEqual(route);
|
||||
expect(routeHash({ page: "Notebooks", notebook: "a b.md" })).toBe("#/notebooks/a%20b.md");
|
||||
expect(parseRoute("")).toEqual({ page: "Notebooks" });
|
||||
expect(parseRoute("#/unknown/x")).toEqual({ page: "Notebooks" });
|
||||
expect(parseRoute("#/notebooks/%E0%A4%A")).toEqual({ page: "Notebooks" });
|
||||
});
|
||||
|
||||
it("remembers typed values but never secrets or undeclared names", () => {
|
||||
rememberValues("a.md", secretBook, { host: "web", token: "s3cret", other: "x" });
|
||||
expect(localStorage.getItem("shellbook:params:a.md")).not.toContain("s3cret");
|
||||
expect(recallValues("a.md", secretBook)).toEqual({ host: "web" });
|
||||
// Stored data is untrusted: a secret written by hand is still dropped.
|
||||
localStorage.setItem("shellbook:params:a.md", JSON.stringify({ token: "x", host: 1 }));
|
||||
expect(recallValues("a.md", secretBook)).toEqual({});
|
||||
localStorage.setItem("shellbook:params:a.md", "not json");
|
||||
expect(recallValues("a.md", secretBook)).toEqual({});
|
||||
rememberValues("a.md", secretBook, {});
|
||||
expect(localStorage.getItem("shellbook:params:a.md")).toBeNull();
|
||||
});
|
||||
|
||||
it("names a missing value once instead of repeating it as an invalid host", () => {
|
||||
const rendered: RenderedStep = {
|
||||
stepId: "s", kind: "check", local: false, host: "{{host}}", script: "id",
|
||||
artifacts: [], uploads: [], missing: ["host"],
|
||||
invalid: { host: "Unknown or missing target host" },
|
||||
};
|
||||
expect(stepProblems(rendered)).toEqual(["Fill in host to run this step."]);
|
||||
expect(stepProblems({ ...rendered, host: "gone", missing: [], invalid: { host: "Unknown or missing target host", port: "bad" } }))
|
||||
.toEqual(["host: Unknown or missing target host", "port: bad"]);
|
||||
});
|
||||
|
||||
it("closes dialogs with Escape", () => {
|
||||
const close = vi.fn();
|
||||
render(<Dialog title="Example" onClose={close}><input aria-label="Field" /></Dialog>);
|
||||
expect(screen.getByLabelText("Field")).toHaveFocus();
|
||||
fireEvent.keyDown(document, { key: "Escape" });
|
||||
expect(close).toHaveBeenCalledOnce();
|
||||
});
|
||||
|
||||
function api(): Api {
|
||||
const notebook = (path: string) => ({ path, source, notebook: parseNotebook(source), includes: [], builtins: {}, version: "1" });
|
||||
return {
|
||||
create: vi.fn(), move: vi.fn(), deleteNotebook: vi.fn(),
|
||||
me: vi.fn().mockResolvedValue({}),
|
||||
login: vi.fn(),
|
||||
list: vi.fn().mockResolvedValue({ notebooks: [{ path: "a.md", title: "A" }, { path: "ops/b.md", title: "B" }] }),
|
||||
hosts: vi.fn().mockResolvedValue({ hosts: [{ name: "staging", user: "admin", address: "x", port: 22, tags: [] }] }),
|
||||
notebook: vi.fn(async (path: string) => notebook(path)),
|
||||
save: vi.fn().mockResolvedValue({ version: "2" }),
|
||||
addHost: vi.fn(),
|
||||
run: vi.fn(),
|
||||
events: (_callback, connected) => { connected(true); return () => {}; },
|
||||
artifact: () => "",
|
||||
};
|
||||
}
|
||||
|
||||
it("opens the notebook named in the URL, keeps typed values across reloads and shows the route", async () => {
|
||||
history.replaceState(null, "", "/#/notebooks/ops/b.md");
|
||||
const first = api();
|
||||
const view = render(<App api={first} />);
|
||||
fireEvent.change(await screen.findByLabelText("Target server *"), { target: { value: "staging" } });
|
||||
expect(first.notebook).toHaveBeenCalledWith("ops/b.md");
|
||||
expect(first.notebook).not.toHaveBeenCalledWith("a.md");
|
||||
await waitFor(() => expect(location.hash).toBe("#/notebooks/ops/b.md"));
|
||||
view.unmount();
|
||||
render(<App api={api()} />);
|
||||
await waitFor(() => expect(screen.getByLabelText("Target server *")).toHaveValue("staging"));
|
||||
fireEvent.click(screen.getByRole("button", { name: "Reset" }));
|
||||
expect(screen.getByLabelText("Target server *")).toHaveValue("");
|
||||
fireEvent.click(screen.getByRole("button", { name: "Hosts" }));
|
||||
await waitFor(() => expect(location.hash).toBe("#/hosts"));
|
||||
});
|
||||
|
||||
it("saves the draft with Ctrl+S", async () => {
|
||||
const live = api();
|
||||
render(<App api={live} />);
|
||||
fireEvent.click(await screen.findByRole("button", { name: "Edit Markdown" }));
|
||||
fireEvent.change(await screen.findByLabelText("Notebook Markdown"), { target: { value: source + "\nMore\n" } });
|
||||
fireEvent.keyDown(window, { key: "s", ctrlKey: true });
|
||||
await waitFor(() => expect(live.save).toHaveBeenCalledWith("a.md", source + "\nMore\n", "1"));
|
||||
});
|
||||
@@ -0,0 +1,150 @@
|
||||
import { useEffect, useId, useRef, useState, type ReactNode } from "react";
|
||||
|
||||
/** Modal dialog: Escape and the backdrop cancel; focus moves into it on open. */
|
||||
export function Dialog({
|
||||
title,
|
||||
onClose,
|
||||
children,
|
||||
wide = false,
|
||||
}: {
|
||||
title: string;
|
||||
onClose(): void;
|
||||
children: ReactNode;
|
||||
wide?: boolean;
|
||||
}) {
|
||||
const id = useId();
|
||||
const box = useRef<HTMLElement>(null);
|
||||
const close = useRef(onClose);
|
||||
close.current = onClose;
|
||||
useEffect(() => {
|
||||
const previous = document.activeElement as HTMLElement | null;
|
||||
const first = box.current?.querySelector<HTMLElement>(
|
||||
"input:not([type=hidden]), select, textarea, button:not(.dialog-close)",
|
||||
);
|
||||
first?.focus();
|
||||
const key = (e: KeyboardEvent) => {
|
||||
if (e.key === "Escape") close.current();
|
||||
};
|
||||
document.addEventListener("keydown", key);
|
||||
return () => {
|
||||
document.removeEventListener("keydown", key);
|
||||
previous?.focus?.();
|
||||
};
|
||||
}, []);
|
||||
return (
|
||||
<div
|
||||
className="modal-backdrop"
|
||||
onMouseDown={(e) => {
|
||||
if (e.target === e.currentTarget) onClose();
|
||||
}}
|
||||
>
|
||||
<section
|
||||
ref={box}
|
||||
className={wide ? "dialog wide" : "dialog"}
|
||||
role="dialog"
|
||||
aria-modal="true"
|
||||
aria-labelledby={id}
|
||||
>
|
||||
<header>
|
||||
<h2 id={id}>{title}</h2>
|
||||
<button type="button" className="dialog-close icon" aria-label="Close" onClick={onClose}>
|
||||
×
|
||||
</button>
|
||||
</header>
|
||||
{children}
|
||||
</section>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
/** A small popup menu; closes on outside click, Escape, or after choosing an item. */
|
||||
export function Menu({
|
||||
label,
|
||||
text = "⋯",
|
||||
children,
|
||||
}: {
|
||||
label: string;
|
||||
text?: ReactNode;
|
||||
children: (close: () => void) => ReactNode;
|
||||
}) {
|
||||
const [open, setOpen] = useState(false);
|
||||
const root = useRef<HTMLDivElement>(null);
|
||||
useEffect(() => {
|
||||
if (!open) return;
|
||||
const outside = (e: MouseEvent) => {
|
||||
if (!root.current?.contains(e.target as Node)) setOpen(false);
|
||||
};
|
||||
const key = (e: KeyboardEvent) => {
|
||||
if (e.key === "Escape") setOpen(false);
|
||||
};
|
||||
document.addEventListener("mousedown", outside);
|
||||
document.addEventListener("keydown", key);
|
||||
return () => {
|
||||
document.removeEventListener("mousedown", outside);
|
||||
document.removeEventListener("keydown", key);
|
||||
};
|
||||
}, [open]);
|
||||
return (
|
||||
<div className="menu" ref={root}>
|
||||
<button
|
||||
type="button"
|
||||
className="icon"
|
||||
aria-label={label}
|
||||
aria-haspopup="menu"
|
||||
aria-expanded={open}
|
||||
onClick={() => setOpen(!open)}
|
||||
>
|
||||
{text}
|
||||
</button>
|
||||
{open && (
|
||||
<div className="menu-items" role="menu" aria-label={label}>
|
||||
{children(() => setOpen(false))}
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
/** Copies text and briefly confirms on the button itself. */
|
||||
export function CopyButton({
|
||||
text,
|
||||
label = "Copy",
|
||||
disabled,
|
||||
title,
|
||||
}: {
|
||||
text: () => string;
|
||||
label?: string;
|
||||
disabled?: boolean;
|
||||
title?: string;
|
||||
}) {
|
||||
const [state, setState] = useState<"" | "done" | "failed">("");
|
||||
useEffect(() => {
|
||||
if (!state) return;
|
||||
const timer = setTimeout(() => setState(""), 1800);
|
||||
return () => clearTimeout(timer);
|
||||
}, [state]);
|
||||
return (
|
||||
<>
|
||||
<button
|
||||
type="button"
|
||||
disabled={disabled}
|
||||
title={title}
|
||||
onClick={async () => {
|
||||
try {
|
||||
await navigator.clipboard.writeText(text());
|
||||
setState("done");
|
||||
} catch {
|
||||
setState("failed");
|
||||
}
|
||||
}}
|
||||
>
|
||||
{label}
|
||||
</button>
|
||||
{state && (
|
||||
<small role="status" className={state === "failed" ? "error" : "ok"}>
|
||||
{state === "done" ? "Copied" : "Copy failed. Select and copy manually."}
|
||||
</small>
|
||||
)}
|
||||
</>
|
||||
);
|
||||
}
|
||||
Reference in New Issue
Block a user