feat(web): parameter fields in the text and collapsible groups (#16)

Inline fields share the value with the parameter panel. Groups and
included notebooks render as collapsible sections whose outline shows
the input status (orange missing, green complete, grey optional) and
remember their open state. The panel groups use the same colors. The
authoring toolbar inserts groups and fields; the demo serves the guided
example.
This commit is contained in:
Florian Schmidt
2026-11-16 16:49:47 +01:00
parent eb31de7120
commit 381c7f555e
9 changed files with 504 additions and 118 deletions
+60 -32
View File
@@ -14,6 +14,7 @@ import {
import ReactMarkdown from "react-markdown";
import {
blockActive,
groupInputs,
notebookIncludes,
parseNotebook,
renderHost,
@@ -38,7 +39,8 @@ import { HostsPage } from "./HostsPage";
import { HttpError } from "./api";
import type { Api } from "./api";
import { emptySession, eventReducer, stepKey } from "./events";
import { ParamsForm, type ParamGroup } from "./ParamsForm";
import { ParamField, ParamsForm, type ParamGroup } from "./ParamsForm";
import { GroupSection } from "./GroupSection";
import { HostBlockCard } from "./HostBlockCard";
import { StepCard } from "./StepCard";
import { ChatPanel } from "./ChatPanel";
@@ -55,21 +57,14 @@ const Editor = lazy(() =>
function steps(blocks: Block[]): Step[] {
return blocks.flatMap((block) =>
block.type === "step"
? [block.step]
: block.type === "markdown" || block.type === "host"
? []
: steps(block.blocks),
block.type === "step" ? [block.step] : "blocks" in block ? steps(block.blocks) : [],
);
}
/** Included notebooks (`::use`, nested too) as parameter groups. */
function includedGroups(blocks: Block[]): ParamGroup[] {
return blocks.flatMap((block): ParamGroup[] =>
block.type === "use"
? [{ scope: block.scope, title: `${block.title ?? block.path} (${block.scope})` }, ...includedGroups(block.blocks)]
: block.type === "after" || block.type === "when"
? includedGroups(block.blocks)
: [],
type UseBlock = Extract<Block, { type: "use" }>;
/** Included notebooks (`::use`, nested too), whose parameters the form shows as groups. */
function includes(blocks: Block[]): UseBlock[] {
return blocks.flatMap((block): UseBlock[] =>
block.type === "use" ? [block, ...includes(block.blocks)] : "blocks" in block ? includes(block.blocks) : [],
);
}
/** Values that are set; unset ones stay visible as `{{name}}` in prose. */
@@ -239,8 +234,14 @@ export function App({ api }: { api: Api }) {
? resolveParams(notebook, values, hostNames, runtime)
: { values: {}, errors: {} };
const active = (id: string) => !!notebook && blockActive(notebook, id, resolved.values);
const groups = notebook
? includedGroups(notebook.blocks).filter((group) => scopeActive(notebook, group.scope, resolved.values))
const groups: ParamGroup[] = notebook
? includes(notebook.blocks)
.filter((block) => scopeActive(notebook, block.scope, resolved.values))
.map((block) => ({
scope: block.scope,
title: `${block.title ?? block.path} (${block.scope})`,
status: groupInputs(notebook, block, values, hostNames, runtime).status,
}))
: [];
const activeChecks = notebook
? steps(notebook.blocks).filter((s) => s.kind === "check" && active(s.attrs.id))
@@ -302,21 +303,46 @@ export function App({ api }: { api: Api }) {
setConfirm(request);
else void start(request);
}
const changeValue = (name: string, value: string) => changeValues({ ...values, [name]: value });
function blocks(items: Block[]): React.ReactNode {
if (!notebook) return null;
const prose = (text: string) => renderText(text, setValuesOnly({ ...runtime, ...resolved.values }), notebook);
return items.map((block, i) => {
if (block.type === "markdown")
return (
<div className="prose" key={i}>
<ReactMarkdown>
{renderText(
block.text,
setValuesOnly({ ...runtime, ...resolved.values }),
notebook,
)}
</ReactMarkdown>
<ReactMarkdown>{prose(block.text)}</ReactMarkdown>
</div>
);
if (block.type === "param") {
const def = notebook.params.find((param) => param.name === block.name);
// The parser reports unknown names; the panel still lists every parameter.
return def ? (
<div className="inline-param" key={i}>
<ParamField
param={def}
value={resolved.values[def.name]}
error={resolved.errors[def.name]}
hosts={hosts}
idPrefix={`inline-${i}-${block.range.startLine}`}
onChange={changeValue}
/>
</div>
) : null;
}
if (block.type === "group")
return (
<GroupSection
key={`${path}:${block.range.startLine}`}
title={prose(block.title)}
inputs={groupInputs(notebook, block, values, hostNames, runtime)}
params={notebook.params}
storageKey={`${path}:${block.title}`}
defaultOpen={!block.collapsed}
>
{blocks(block.blocks)}
</GroupSection>
);
if (block.type === "when")
return block.values.includes(resolved.values[block.param] ?? "") ? (
<div className="when" key={i}>
@@ -325,19 +351,21 @@ export function App({ api }: { api: Api }) {
) : null;
if (block.type === "use")
return (
<details className="included" open key={i}>
<summary>
{block.title ?? block.path}
<small>
{block.path} · as {block.scope}
</small>
</summary>
<GroupSection
key={`${path}:use:${block.scope}`}
className="included"
title={block.title ?? block.path}
subtitle={`${block.path} · as ${block.scope}`}
inputs={groupInputs(notebook, block, values, hostNames, runtime)}
params={notebook.params}
storageKey={`${path}:use:${block.scope}`}
>
{block.blocks.length ? (
blocks(block.blocks)
) : (
<p className="muted">Save the notebook to load {block.path}.</p>
)}
</details>
</GroupSection>
);
if (block.type === "host") {
const rendered = renderHost(notebook, block, resolved.values, runtime, hostNames);
@@ -599,7 +627,7 @@ export function App({ api }: { api: Api }) {
writeFlag("params-open", next);
setParamsOpen(next);
}}
onChange={(name, value) => changeValues({ ...values, [name]: value })}
onChange={changeValue}
onReset={() => changeValues({})}
/>
<article className="notebook">
+32
View File
@@ -3,7 +3,9 @@ import { parseNotebook, type ParamDef } from "@shellbook/core";
import {
addParameter,
afterSnippet,
groupSnippet,
hostSnippet,
paramFieldSnippet,
notebookSteps,
stepSnippet,
useSnippet,
@@ -28,6 +30,7 @@ export function AuthoringToolbar({
const [after, setAfter] = useState("");
const [when, setWhen] = useState("");
const [include, setInclude] = useState(false);
const [field, setField] = useState("");
const steps = notebookSteps(notebook.blocks);
const choices = notebook.params.flatMap((p) =>
p.type === "choice" ? (p.options ?? []).map((o) => ({ param: p.name, option: o })) : [],
@@ -104,6 +107,27 @@ export function AuthoringToolbar({
>
Insert when section
</button>
<button type="button" onClick={() => insert(groupSnippet())}>
Group
</button>
<label>
Field in text
<select value={field} onChange={(e) => setField(e.target.value)}>
<option value="">Choose a parameter</option>
{notebook.params.map((p) => (
<option key={p.name} value={p.name}>
{p.name}
</option>
))}
</select>
</label>
<button
type="button"
disabled={!notebook.params.some((p) => p.name === field)}
onClick={() => insert(paramFieldSnippet(field))}
>
Insert field
</button>
<button type="button" onClick={() => setInclude(!include)}>
Use notebook
</button>
@@ -227,6 +251,14 @@ export function AuthoringToolbar({
adds a created machine to Hosts. {"{{shellbook.public_key}}"} is
ShellBook's SSH public key.
</p>
<p>
Guided text: {"::param{name=host}"} on its own line shows that
parameter&apos;s input there (same value as the panel).{" "}
{':::group{title="Network" collapsed}'} … {":::"} is a collapsible
section for anything; its outline is orange while needed values are
missing, green when all are filled, grey when only optional ones remain.
{" collapsed"} starts it closed. Groups never block steps.
</p>
<p>
Artifact and upload snippets are examples: choose files and commands
appropriate to your runbook before running.
+76
View File
@@ -0,0 +1,76 @@
import { useState, type ReactNode } from "react";
import type { GroupInputs, ParamDef } from "@shellbook/core";
import { paramLabel } from "./ParamsForm";
import { readFlag, writeFlag } from "./uiPrefs";
/** What the outline color means, in words (color is never the only signal). */
function statusText(inputs: GroupInputs, labelOf: (name: string) => string): string {
if (inputs.status === "missing") {
const names = [...inputs.missing, ...inputs.invalid];
const shown = names.slice(0, 3).map(labelOf).join(", ");
const more = names.length > 3 ? ` +${names.length - 3}` : "";
return inputs.missing.length ? `needs ${shown}${more}` : `check ${shown}${more}`;
}
if (inputs.status === "filled") return "complete";
if (inputs.status === "optional") return "optional";
return "";
}
/**
* A titled, collapsible container (`:::group`, and `::use` sections). The outline shows
* whether its inputs are filled in: orange — needed values missing, green — complete,
* grey — optional or no inputs. The open state is remembered per `storageKey`.
*/
export function GroupSection({
title,
subtitle,
inputs,
params,
storageKey,
defaultOpen = true,
className = "",
children,
}: {
title: string;
subtitle?: string;
inputs: GroupInputs;
/** The notebook's parameters, for labels in the status text. */
params: ParamDef[];
storageKey: string;
defaultOpen?: boolean;
className?: string;
children: ReactNode;
}) {
const flag = `group:${storageKey}`;
const [open, setOpen] = useState(() => readFlag(flag, defaultOpen));
const labelOf = (name: string) => {
const def = params.find((param) => param.name === name);
return def ? paramLabel(def) : name;
};
const status = statusText(inputs, labelOf);
return (
<section className={`group status-${inputs.status} ${className}`.trim()} aria-label={title}>
<header>
<button
type="button"
className="group-toggle"
aria-expanded={open}
onClick={() => {
writeFlag(flag, !open);
setOpen(!open);
}}
>
<span className="caret" aria-hidden="true">
{open ? "▾" : "▸"}
</span>
<span className="group-title">{title}</span>
</button>
{subtitle && <small className="muted">{subtitle}</small>}
{status && <small className="group-status">{status}</small>}
</header>
<div className="group-body" hidden={!open}>
{children}
</div>
</section>
);
}
+86 -52
View File
@@ -1,15 +1,84 @@
import { useEffect, useState } from "react";
import type { HostInfo, Notebook, ParamDef, ParamValues } from "@shellbook/core";
import type { HostInfo, InputStatus, Notebook, ParamDef, ParamValues } from "@shellbook/core";
import { readFlag, writeFlag } from "./uiPrefs";
/** An included notebook (`::use`) whose parameters the form shows as a group. */
export interface ParamGroup {
scope: string;
title: string;
/** Input status of the included notebook (core groupInputs), shown as the outline color. */
status?: InputStatus;
}
const groupFlag = (title: string) => `params-group:${title}`;
/** The label a parameter is shown with; included ones without a label use their local name. */
export const paramLabel = (param: ParamDef) =>
param.label ?? (param.scope ? param.name.slice(param.scope.length + 1) : param.name);
/**
* One parameter input, used by the parameter panel and by `::param` fields in the text.
* `idPrefix` keeps element ids unique when the same parameter appears in both places.
*/
export function ParamField({
param,
value,
error,
hosts,
idPrefix = "param",
onChange,
}: {
param: ParamDef;
value: string | undefined;
error: string | undefined;
hosts: HostInfo[];
idPrefix?: string;
onChange(name: string, value: string): void;
}) {
const id = `${idPrefix}-${param.name}`;
const label = paramLabel(param);
const common = {
id,
required: param.required,
value: value ?? "",
"aria-labelledby": `${id}-label`,
"aria-invalid": !!error,
// Red only for a wrong value; an empty field just still needs one.
className: error && value ? "invalid" : undefined,
"aria-describedby": error ? `${id}-error` : undefined,
onChange: (e: React.ChangeEvent<HTMLInputElement | HTMLSelectElement>) => onChange(param.name, e.target.value),
};
return (
<label htmlFor={id}>
<span id={`${id}-label`} title={label}>
{label}
{param.required && <b title="Required"> *</b>}
</span>
{param.type === "host" || param.type === "choice" ? (
<select {...common}>
<option value="">Select…</option>
{(param.type === "host" ? hosts.map((h) => h.name) : (param.options ?? [])).map((option) => (
<option key={option}>{option}</option>
))}
</select>
) : (
<input
{...common}
type={param.type === "secret" ? "password" : "text"}
autoComplete={param.type === "secret" ? "new-password" : "off"}
spellCheck={false}
/>
)}
{error && (
// An empty field only needs a value: say so quietly; a wrong value is an error.
<small id={`${id}-error`} className={value ? "error" : "muted"}>
{error}
</small>
)}
</label>
);
}
export function ParamsForm({
notebook,
values,
@@ -58,8 +127,7 @@ export function ParamsForm({
const missingOf = (params: ParamDef[]) =>
params.filter((param) => param.required && !values[param.name]).length;
const missing = missingOf(shown);
const labelOf = (param: ParamDef) =>
param.label ?? (param.scope ? param.name.slice(param.scope.length + 1) : param.name);
const labelOf = paramLabel;
const reveal = (param: ParamDef) => {
if (!open) onToggle?.(true);
@@ -107,54 +175,16 @@ export function ParamsForm({
);
};
const field = (param: ParamDef) => {
const id = `param-${param.name}`;
const common = {
id,
required: param.required,
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>,
) => onChange(param.name, e.target.value),
};
return (
<label key={param.name} htmlFor={id}>
<span id={`${id}-label`} title={labelOf(param)}>
{labelOf(param)}
{param.required && <b title="Required"> *</b>}
</span>
{param.type === "host" || param.type === "choice" ? (
<select {...common}>
<option value="">Select…</option>
{(param.type === "host"
? hosts.map((h) => h.name)
: (param.options ?? [])
).map((option) => (
<option key={option}>{option}</option>
))}
</select>
) : (
<input
{...common}
type={param.type === "secret" ? "password" : "text"}
autoComplete={param.type === "secret" ? "new-password" : "off"}
spellCheck={false}
/>
)}
{errors[param.name] && (
// 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 field = (param: ParamDef) => (
<ParamField
key={param.name}
param={param}
value={values[param.name]}
error={errors[param.name]}
hosts={hosts}
onChange={onChange}
/>
);
return (
<form
@@ -191,7 +221,11 @@ export function ParamsForm({
const expanded = isGroupOpen(group.title);
const groupMissing = missingOf(params);
return (
<fieldset key={group.scope} className={expanded ? "" : "collapsed"} aria-label={group.title}>
<fieldset
key={group.scope}
className={`status-${group.status ?? "none"}${expanded ? "" : " collapsed"}`}
aria-label={group.title}
>
<legend>
<button
type="button"
+18 -5
View File
@@ -8,11 +8,7 @@ import {
} from "@shellbook/core";
export function notebookSteps(blocks: Block[]): Step[] {
return blocks.flatMap((b) =>
b.type === "step"
? [b.step]
: b.type === "markdown" || b.type === "host"
? []
: notebookSteps(b.blocks),
b.type === "step" ? [b.step] : "blocks" in b ? notebookSteps(b.blocks) : [],
);
}
const attr = (value: string) =>
@@ -72,6 +68,23 @@ export function useSnippet(path: string, alias: string): string {
throw new Error("Alias must use letters, digits or _ (not shellbook)");
return `\n\n::use{notebook=${attr(path)} as=${alias}}\n`;
}
/** A titled, collapsible container; its outline shows whether its inputs are filled in. */
export function groupSnippet(title = "Group title"): string {
return `
:::group{title=${attr(title)}}
Explain this part here.
:::
`;
}
/** The parameter's input field at this point of the text. */
export function paramFieldSnippet(name: string): string {
if (!/^[A-Za-z_][A-Za-z0-9_]*$/.test(name)) throw new Error("Invalid parameter name");
return `
::param{name=${name}}
`;
}
/** Add the machine a notebook created to Hosts; replace the example templates. */
export function hostSnippet(): string {
return '\n\n::host{name="{{hostname}}" address="{{address}}" user=root port=22 capture=host}\n';
+31 -18
View File
@@ -2,9 +2,18 @@ import type { ServerEvent, StartRunRequest } from "@shellbook/core";
import type { Api } from "../api";
import { HttpError } from "../api";
import { findStep, parseNotebook, renderStep } from "@shellbook/core";
import initial from "./ssh-key.md?raw";
let source = initial;
let version = 1;
import sshKey from "./ssh-key.md?raw";
import adminUser from "../../../../templates/workspace/notebooks/admin-user.md?raw";
// Demo notebooks, editable in this browser session only.
const files: Record<string, { title: string; source: string; version: number }> = {
"ssh-key.md": { title: "New server SSH key", source: sshKey, version: 1 },
"admin-user.md": { title: "Create an admin user", source: adminUser, version: 1 },
};
const file = (path: string) => {
const entry = files[path];
if (!entry) throw new HttpError(404);
return entry;
};
let counter = 0;
const listeners = new Set<(event: ServerEvent) => void>();
const emit = (event: ServerEvent) =>
@@ -43,26 +52,30 @@ export const mockApi: Api = {
me: async () => ({ authenticated: true }),
login: async () => undefined,
list: async () => ({
notebooks: [{ path: "ssh-key.md", title: "New server SSH key" }],
notebooks: Object.entries(files).map(([path, entry]) => ({ path, title: entry.title })),
}),
hosts: async () => ({ hosts }),
notebook: async (path) => ({
path,
source,
notebook: parseNotebook(source),
includes: [],
builtins: { "shellbook.public_key": "ssh-ed25519 AAAADEMO shellbook" },
version: String(version),
}),
notebook: async (path) => {
const { source, version } = file(path);
return {
path,
source,
notebook: parseNotebook(source),
includes: [],
builtins: { "shellbook.public_key": "ssh-ed25519 AAAADEMO shellbook" },
version: String(version),
};
},
addHost: async (host) => {
if (hosts.some((h) => h.name === host.name)) throw new HttpError(409, "Host already exists");
hosts.push({ ...host });
},
save: async (_path, next, base) => {
if (base !== String(version)) throw new HttpError(409);
source = next;
version++;
return { version: String(version) };
save: async (path, next, base) => {
const entry = file(path);
if (base !== String(entry.version)) throw new HttpError(409);
entry.source = next;
entry.version++;
return { version: String(entry.version) };
},
events: (receive, connected) => {
listeners.add(receive);
@@ -73,7 +86,7 @@ export const mockApi: Api = {
},
artifact: () => artifactUrl,
run: async (request: StartRunRequest) => {
const notebook = parseNotebook(source);
const notebook = parseNotebook(file(request.notebookPath).source);
const step = findStep(notebook.blocks, request.stepId);
if (!step) throw new Error("Unknown demo step");
const rendered = renderStep(
+91 -11
View File
@@ -615,6 +615,12 @@ nav[aria-label="Main navigation"] button[aria-current="page"] {
.params fieldset.collapsed {
padding-bottom: 8px;
}
.params fieldset.status-missing {
border-color: var(--warn);
}
.params fieldset.status-filled {
border-color: var(--ok);
}
.params legend {
font-size: 12px;
font-weight: 600;
@@ -805,22 +811,96 @@ pre.script {
border-left: 3px solid var(--accent);
padding-left: 18px;
}
/* Chained notebooks (::use): the included notebook, collapsible. */
.included {
border: 1px dashed var(--line);
/*
* Groups (:::group) and included notebooks (::use): collapsible containers whose outline
* shows their input status — orange: needed values missing, green: complete, grey: optional.
*/
.group {
--group-line: var(--line);
border: 1px solid var(--group-line);
border-left-width: 4px;
border-radius: 8px;
padding: 4px 18px;
padding: 0 18px;
margin: 20px 0;
}
.included > summary {
cursor: pointer;
padding: 10px 0;
font-weight: 600;
.group.status-missing {
--group-line: var(--warn);
}
.included > summary small {
font-weight: normal;
.group.status-filled {
--group-line: var(--ok);
}
.group.included {
border-style: dashed;
border-left-style: solid;
}
.group > header {
display: flex;
align-items: baseline;
flex-wrap: wrap;
gap: 4px 10px;
padding: 10px 0;
}
.group-toggle {
display: inline-flex;
align-items: baseline;
gap: 8px;
border: none;
background: none;
padding: 0;
color: var(--text);
font: inherit;
font-size: 15px;
font-weight: 600;
text-align: left;
}
.group-toggle:hover {
color: var(--accent);
}
.group-toggle .caret {
width: 10px;
color: var(--muted);
margin-left: 8px;
}
.group > header > small {
font-size: 12px;
}
.group-status {
margin-left: auto;
color: var(--muted);
}
.group.status-missing > header > .group-status {
color: var(--warn);
}
.group.status-filled > header > .group-status {
color: var(--ok);
}
.group.status-filled > header > .group-status::before {
content: "✓ ";
}
.group-body {
padding-bottom: 6px;
}
.group-body > .prose:first-child > :first-child {
margin-top: 0;
}
/* ::param — a parameter's input inside the text, bound to the same value as the panel. */
.inline-param {
max-width: 420px;
margin: 12px 0;
}
.inline-param label {
display: flex;
flex-direction: column;
gap: 4px;
font-size: 12.5px;
}
.inline-param label > span {
color: var(--muted);
}
.inline-param b {
color: var(--accent);
}
.inline-param + .inline-param {
margin-top: -2px;
}
.host-block > p {
margin: 10px 14px;
+11
View File
@@ -89,3 +89,14 @@ it("generates valid chaining snippets", async () => {
expect(() => useSnippet("../x.md", "ct")).toThrow("dir/name.md");
expect(() => useSnippet("x.md", "shellbook")).toThrow("Alias");
});
it("generates valid group and parameter field snippets", async () => {
const { groupSnippet, paramFieldSnippet } = await import("../authoring");
const base = "---\nparams:\n hostname: {type: name}\n---\n";
const notebook = parseNotebook(base + groupSnippet('Say "hi"') + paramFieldSnippet("hostname"));
expect(notebook.diagnostics).toEqual([]);
expect(notebook.blocks.filter((b) => b.type !== "markdown")).toEqual([
expect.objectContaining({ type: "group", title: 'Say "hi"', collapsed: false }),
expect.objectContaining({ type: "param", name: "hostname" }),
]);
expect(() => paramFieldSnippet("a b")).toThrow("Invalid parameter name");
});
+99
View File
@@ -0,0 +1,99 @@
import { fireEvent, render, screen, within } from "@testing-library/react";
import { beforeEach, expect, it, vi } from "vitest";
vi.mock("../Editor", () => ({ Editor: () => null }));
import { App } from "../App";
import type { Api } from "../api";
import { parseNotebook } from "@shellbook/core";
const source = `---
title: Guided setup
params:
host: {type: host, required: true, label: Target server}
user: {type: name, label: Login user}
note: {type: string}
---
# Guided setup
:::group{title="1. Connect"}
Pick the server first:
::param{name=host}
\`\`\`sh {check host="{{host}}" id=whoami title="Who am I"}
id {{user}}
\`\`\`
:::
:::group{title="2. Notes" collapsed}
::param{name=note}
:::
`;
function api(): Api {
return {
create: vi.fn(), move: vi.fn(), deleteNotebook: vi.fn(),
me: vi.fn().mockResolvedValue({}),
login: vi.fn(),
list: vi.fn().mockResolvedValue({ notebooks: [{ path: "guide.md", title: "Guided setup" }] }),
hosts: vi.fn().mockResolvedValue({ hosts: [{ name: "pve", address: "10.0.0.2", user: "root", port: 22, tags: [] }] }),
notebook: vi.fn().mockResolvedValue({
path: "guide.md", source, notebook: parseNotebook(source), includes: [], builtins: {}, version: "1",
}),
save: vi.fn(),
run: vi.fn(),
addHost: vi.fn(),
events: (_callback, connected) => { connected(true); return () => {}; },
artifact: () => "/download",
};
}
beforeEach(() => localStorage.clear());
it("shows parameter fields in the text, bound to the same value as the panel", async () => {
render(<App api={api()} />);
const connect = await screen.findByRole("region", { name: "1. Connect" });
const inline = within(connect).getByLabelText(/Target server/);
const panel = within(screen.getByRole("form", { name: "Notebook parameters" })).getByLabelText(/Target server/);
expect(inline).not.toBe(panel);
fireEvent.change(inline, { target: { value: "pve" } });
expect(panel).toHaveValue("pve");
fireEvent.change(panel, { target: { value: "" } });
expect(inline).toHaveValue("");
});
it("colors a group by the state of its inputs and says so in text", async () => {
render(<App api={api()} />);
const connect = await screen.findByRole("region", { name: "1. Connect" });
// The check needs host (required) and user (referenced by the script).
expect(connect).toHaveClass("status-missing");
expect(within(connect).getByText("needs Target server, Login user")).toBeInTheDocument();
fireEvent.change(within(connect).getByLabelText(/Target server/), { target: { value: "pve" } });
expect(connect).toHaveTextContent("needs Login user");
fireEvent.change(within(screen.getByRole("form", { name: "Notebook parameters" })).getByLabelText(/Login user/), {
target: { value: "admin" },
});
expect(connect).toHaveClass("status-filled");
expect(within(connect).getByText("complete")).toBeInTheDocument();
// Only optional inputs: grey.
expect(screen.getByRole("region", { name: "2. Notes" })).toHaveClass("status-optional");
});
it("collapses groups, starts collapsed ones closed and remembers the choice", async () => {
const { unmount } = render(<App api={api()} />);
const notes = await screen.findByRole("region", { name: "2. Notes" });
const toggle = within(notes).getByRole("button", { name: "2. Notes" });
expect(toggle).toHaveAttribute("aria-expanded", "false");
expect(within(notes).getByLabelText("note", { selector: "input" })).not.toBeVisible();
fireEvent.click(toggle);
expect(within(notes).getByLabelText("note", { selector: "input" })).toBeVisible();
const connect = screen.getByRole("region", { name: "1. Connect" });
fireEvent.click(within(connect).getByRole("button", { name: "1. Connect" }));
expect(within(connect).getByText("Who am I")).not.toBeVisible();
unmount();
render(<App api={api()} />);
const again = await screen.findByRole("region", { name: "1. Connect" });
expect(within(again).getByRole("button", { name: "1. Connect" })).toHaveAttribute("aria-expanded", "false");
expect(within(screen.getByRole("region", { name: "2. Notes" })).getByRole("button", { name: "2. Notes" }))
.toHaveAttribute("aria-expanded", "true");
});