cheogram-www

created pr with cheogram-www/button-grid.1 on 2026-11-12T04:41:10Z · by 9e834e0d
added cheogram-www/button-grid.2 on 2026-11-12T04:53:26Z · by 9e834e0d
1: 76d4c03 ! 1: 58cc44c Render single selection form as button grid
added cheogram-www/button-grid.3 on 2026-11-12T05:17:58Z · by 9e834e0d
1: 58cc44c ! 1: dd6d21a Render single selection form as button grid
-: ------- > 2: 9eabb7a Support icons on list options
added cheogram-www/button-grid.4 on 2026-11-13T16:25:21Z · by 3c31bc8c
1: dd6d21a = 1: 6df9e5d Render single selection form as button grid
2: 9eabb7a = 2: 94950ef Support icons on list options
commented on 2026-11-13T16:25:21Z · by 3c31bc8c
src/components/Form.tsx:158 — is this more like selected rather than default?
commented on 2026-11-13T16:25:23Z · by 3c31bc8c
src/components/Form.tsx:222 — value here is whatever's currently selected? so we prefill the custom value with that? does that make sense if someone has picked custom value?
commented on 2026-11-13T16:25:26Z · by 3c31bc8c
src/components/Form.tsx:544 — Inside FormField we switch based on field type. Isn't this kind of like a field type? why have to logic out here instead of inside FormField. Could still render the ButtonGridField component from in there
cmds
checkout latest patchset:
ssh pr.pico.sh pull cheogram-www:button-grid | git am -3
checkout specific patchset revision:
ssh pr.pico.sh pull cheogram-www:button-grid [rev] | git am -3
add changes to patch request:
git format-patch main --stdout | ssh pr.pico.sh cheogram-www:button-grid
add comment to patch request:
ssh pr.pico.sh comment cheogram-www:button-grid "lgtm!"
+4 -0 src/App.scss #
......@@ -388,6 +388,10 @@ li.MuiListSubheader-root {
388388 margin: auto;
389389 max-width: 100%;
390390
391+ &.button-grid-form {
392+ width: min(100%, 40rem);
393+ }
394+
391395 > section:first-of-type > .MuiStack-root > h1:first-of-type {
392396 display: none; /* Shown in tab already */
393397 }
+23 -7 src/components/CommandSession.tsx #
......@@ -4,7 +4,7 @@ import { Suspense, useRef, useState } from "react";
44 import { useAsyncValue, Await } from "react-router";
55 import { CircularProgress } from "@mui/material";
66
7-import { FormSection } from "./Form";
7+import { FormSection, getButtonGridField } from "./Form";
88 import { ios, webkit } from "../util";
99
1010 const CommandSessionInner = ({
......@@ -42,14 +42,21 @@ const CommandSessionInner = ({
4242 if (action !== "cancel") logStep(form, data ?? new FormData());
4343 };
4444
45+ const buttonGridField = form.isResult()
46+ ? null
47+ : getButtonGridField(form, session.actions);
48+ const actions = buttonGridField
49+ ? session.actions.filter((action) =>
50+ ["cancel", "prev"].includes(action.value),
51+ )
52+ : session.actions;
53+
4554 const commandActions = () => {
4655 return (
4756 <div className="command-actions">
48- {session.actions.toReversed().map((action) => (
57+ {actions.toReversed().map((action) => (
4958 <Button
50- type={
51- action.value === session.actions[0]?.value ? "submit" : "button"
52- }
59+ type={action.value === actions[0]?.value ? "submit" : "button"}
5360 key={action.value}
5461 onClick={() => execute(action.value)}
5562 >
......@@ -80,8 +87,17 @@ const CommandSessionInner = ({
8087 {commandActions()}
8188 </>
8289 ) : (
83- <form method="dialog" ref={formRef}>
84- <FormSection section={form} isResult={form.isResult()} />
90+ <form
91+ method="dialog"
92+ ref={formRef}
93+ className={buttonGridField ? "button-grid-form" : undefined}
94+ >
95+ <FormSection
96+ section={form}
97+ isResult={form.isResult()}
98+ buttonGridField={buttonGridField?.name}
99+ onSubmit={() => execute(null)}
100+ />
85101 {commandActions()}
86102 </form>
87103 )}
+156 -0 src/components/Form.test.tsx #
......@@ -0,0 +1,156 @@
1+// @vitest-environment jsdom
2+
3+import type * as borogove from "borogove";
4+import { cleanup, fireEvent, render, screen } from "@testing-library/react";
5+import { afterEach, expect, it, vi } from "vitest";
6+import { FormSection, getButtonGridField } from "./Form";
7+
8+afterEach(cleanup);
9+
10+const field = (
11+ overrides: Partial<borogove.FormField> = {},
12+): borogove.FormField => ({
13+ name: "choice",
14+ label: "Choice",
15+ desc: null,
16+ value: [],
17+ required: false,
18+ type: "list-single",
19+ datatype: "xs:string",
20+ options: [],
21+ open: false,
22+ rangeMin: null,
23+ rangeMax: null,
24+ regex: null,
25+ ...overrides,
26+});
27+
28+const section = (fields: borogove.FormField[]): borogove.FormSection => ({
29+ title: () => null,
30+ items: () =>
31+ fields.map(
32+ (item) =>
33+ ({
34+ text: null,
35+ field: item,
36+ section: null,
37+ status: null,
38+ tableHeader: null,
39+ tableRows: null,
40+ }) as borogove.FormItem,
41+ ),
42+});
43+
44+const choice = field({
45+ options: [
46+ { label: "One", value: "one" },
47+ { label: "Two", value: "two" },
48+ ],
49+});
50+
51+it("renders a single-choice field as buttons and submits the selected option", () => {
52+ const onSubmit = vi.fn();
53+ const { container } = render(
54+ <form>
55+ <FormSection
56+ section={section([choice])}
57+ buttonGridField={choice.name}
58+ onSubmit={onSubmit}
59+ />
60+ </form>,
61+ );
62+
63+ fireEvent.click(screen.getByRole("button", { name: "Two" }));
64+
65+ expect(
66+ (container.querySelector('input[name="choice"]') as HTMLInputElement).value,
67+ ).toBe("two");
68+ expect(onSubmit).toHaveBeenCalledOnce();
69+});
70+
71+it("synthesizes No and Yes buttons for a boolean field", () => {
72+ const enabled = field({
73+ name: "enabled",
74+ label: "Enabled",
75+ type: "boolean",
76+ });
77+ const { container } = render(
78+ <form>
79+ <FormSection
80+ section={section([enabled])}
81+ buttonGridField={enabled.name}
82+ />
83+ </form>,
84+ );
85+
86+ expect(screen.getByRole("button", { name: "No" })).toBeDefined();
87+ fireEvent.click(screen.getByRole("button", { name: "Yes" }));
88+
89+ expect(
90+ (container.querySelector('input[name="enabled"]') as HTMLInputElement)
91+ .value,
92+ ).toBe("true");
93+});
94+
95+it("does not use a button grid for a boolean that already has a value", () => {
96+ const enabled = field({
97+ name: "enabled",
98+ label: "Enabled",
99+ type: "boolean",
100+ value: ["true"],
101+ });
102+ const { container } = render(
103+ <form>
104+ <FormSection section={section([enabled])} />
105+ </form>,
106+ );
107+
108+ expect(screen.queryByRole("button", { name: "Yes" })).toBeNull();
109+ expect(container.querySelector('input[type="checkbox"]')).not.toBeNull();
110+});
111+
112+it("allows an open button-grid field to submit a custom value", () => {
113+ const onSubmit = vi.fn();
114+ const openChoice = field({
115+ open: true,
116+ options: [{ label: "One", value: "one" }],
117+ });
118+ const { container } = render(
119+ <form>
120+ <FormSection
121+ section={section([openChoice])}
122+ buttonGridField={openChoice.name}
123+ onSubmit={onSubmit}
124+ />
125+ </form>,
126+ );
127+
128+ fireEvent.click(screen.getByRole("button", { name: "other / custom" }));
129+ fireEvent.change(screen.getByRole("textbox"), {
130+ target: { value: "custom" },
131+ });
132+ fireEvent.click(screen.getByRole("button", { name: "Go" }));
133+
134+ expect(
135+ (container.querySelector('input[name="choice"]') as HTMLInputElement).value,
136+ ).toBe("custom");
137+ expect(onSubmit).toHaveBeenCalledOnce();
138+});
139+
140+it("selects a button grid field only when there is one eligible field", () => {
141+ const only = field({
142+ options: [{ label: "One", value: "one" }],
143+ });
144+ expect(getButtonGridField(section([only]), [])).toBe(only);
145+
146+ const enabled = field({
147+ name: "enabled",
148+ type: "boolean",
149+ value: ["true"],
150+ });
151+ expect(getButtonGridField(section([enabled]), [])).toBeNull();
152+
153+ expect(
154+ getButtonGridField(section([only, field({ name: "other" })]), []),
155+ ).toBeNull();
156+});
+187 -6 src/components/Form.tsx #
......@@ -2,9 +2,17 @@ import * as borogove from "borogove";
22 import {
33 Alert,
44 Autocomplete,
5+ Box,
6+ Button,
7+ Dialog,
8+ DialogActions,
9+ DialogContent,
10+ DialogTitle,
511 Switch,
612 FormControl,
713 FormControlLabel,
14+ FormHelperText,
15+ FormLabel,
816 MenuItem,
917 IconButton,
1018 TextField,
......@@ -16,11 +24,12 @@ import {
1624 useMaterialReactTable,
1725 } from "material-react-table";
1826 import {
27+ forwardRef,
1928 useId,
20- useState,
21- useMemo,
2229 useImperativeHandle,
23- forwardRef,
30+ useMemo,
31+ useRef,
32+ useState,
2433 } from "react";
2534 import Visibility from "@mui/icons-material/Visibility";
2635 import VisibilityOff from "@mui/icons-material/VisibilityOff";
......@@ -57,6 +66,169 @@ const openOptionValue = (v: borogove.FormOption | string | null): string => {
5766 return v.value ?? "";
5867 };
5968
69+const isFillable = (field: borogove.FormField) =>
70+ field.name !== "" && field.type !== "hidden" && field.type !== "fixed";
71+
72+const countProceed = (actions: borogove.FormOption[]) =>
73+ actions.filter((action) => !["cancel", "prev"].includes(action.value)).length;
74+
75+const flattenFields = (items: borogove.FormItem[]): borogove.FormField[] =>
76+ items.flatMap((item) => [
77+ ...(item.field ? [item.field] : []),
78+ ...(item.section ? flattenFields(item.section.items()) : []),
79+ ]);
80+
81+const fillableFields = (section: borogove.FormSection) =>
82+ flattenFields(section.items()).filter(isFillable);
83+
84+export const getButtonGridField = (
85+ section: borogove.FormSection,
86+ actions: borogove.FormOption[],
87+): borogove.FormField | null => {
88+ const fields = fillableFields(section);
89+ console.log("XYZZY", fields, countProceed(actions));
90+ if (fields.length !== 1 || countProceed(actions) > 1) return null;
91+ const field = fields[0];
92+ if (field.type === "boolean") return field.value.length === 0 ? field : null;
93+ if (field.type === "list-single" && field.options.length < 50) return field;
94+ return null;
95+};
96+
97+const ButtonGridField = ({
98+ field,
99+ onSubmit,
100+}: {
101+ field: borogove.FormField;
102+ onSubmit?: () => void;
103+}) => {
104+ const [value, setValue] = useState(field.value[0] ?? "");
105+ const [open, setOpen] = useState(false);
106+ const [customValue, setCustomValue] = useState("");
107+ const hiddenInput = useRef<HTMLInputElement>(null);
108+
109+ const options: borogove.FormOption[] =
110+ field.type === "boolean"
111+ ? [
112+ { label: "No", value: "false" },
113+ { label: "Yes", value: "true" },
114+ ]
115+ : field.options;
116+
117+ const defaultOption = !value
118+ ? null
119+ : (options.find((option) => option.value === value) ?? {
120+ label: value,
121+ value,
122+ });
123+
124+ const submit = (next: string) => {
125+ setValue(next);
126+ if (hiddenInput.current) {
127+ hiddenInput.current.value = next;
128+ hiddenInput.current.disabled = false;
129+ }
130+ onSubmit?.();
131+ };
132+
133+ return (
134+ <>
135+ <FormControl fullWidth>
136+ {field.label && <FormLabel>{field.label}</FormLabel>}
137+ <input
138+ ref={hiddenInput}
139+ type="hidden"
140+ name={field.name}
141+ value={value}
142+ disabled={!value}
143+ />
144+ {defaultOption && (
145+ <>
146+ <Button
147+ type="button"
148+ variant="contained"
149+ sx={{
150+ alignSelf: "center",
151+ my: 2,
152+ }}
153+ onClick={() => submit(defaultOption.value)}
154+ >
155+ {defaultOption.label || defaultOption.value}
156+ </Button>
157+ <FormHelperText sx={{ textAlign: "center" }}>or</FormHelperText>
158+ </>
159+ )}
160+ <Box
161+ sx={{
162+ display: "grid",
163+ gridTemplateColumns:
164+ "repeat(auto-fit, minmax(min(100%, 7.5rem), 1fr))",
165+ gridAutoRows: "1fr",
166+ gap: 1,
167+ mt: 1,
168+ }}
169+ >
170+ {options
171+ .filter((option) => option.value !== defaultOption?.value)
172+ .map((option) => (
173+ <Button
174+ key={option.value}
175+ type="button"
176+ variant="outlined"
177+ sx={{ minWidth: 0, whiteSpace: "normal" }}
178+ onClick={() => submit(option.value)}
179+ >
180+ {option.label || option.value}
181+ </Button>
182+ ))}
183+ </Box>
184+ {field.open && (
185+ <Button
186+ type="button"
187+ variant="text"
188+ sx={{ mt: 2 }}
189+ onClick={() => {
190+ setCustomValue(value);
191+ setOpen(true);
192+ }}
193+ >
194+ other / custom
195+ </Button>
196+ )}
197+ {field.desc && (
198+ <FormHelperText sx={{ textAlign: "center" }}>
199+ {field.desc}
200+ </FormHelperText>
201+ )}
202+ </FormControl>
203+ <Dialog open={open} onClose={() => setOpen(false)} fullWidth>
204+ <DialogTitle>{field.label || field.name}</DialogTitle>
205+ <DialogContent>
206+ <TextField
207+ autoFocus
208+ fullWidth
209+ margin="dense"
210+ label={field.desc ?? undefined}
211+ value={customValue}
212+ onChange={(e) => setCustomValue(e.target.value)}
213+ />
214+ </DialogContent>
215+ <DialogActions>
216+ <Button onClick={() => setOpen(false)}>Cancel</Button>
217+ <Button
218+ variant="contained"
219+ onClick={() => {
220+ setOpen(false);
221+ submit(customValue);
222+ }}
223+ >
224+ Go
225+ </Button>
226+ </DialogActions>
227+ </Dialog>
228+ </>
229+ );
230+};
231+
60232 const ResultField = forwardRef(
61233 ({ field }: { field: borogove.FormField }, ref) => {
62234 useImperativeHandle(ref, () => ({ focus: () => {}, value: field.value }), [
......@@ -308,9 +480,13 @@ export const FormTable = ({
308480 export const FormSection = ({
309481 section,
310482 isResult,
483+ buttonGridField,
484+ onSubmit,
311485 }: {
312486 section: borogove.FormSection;
313487 isResult?: boolean;
488+ buttonGridField?: string | null;
489+ onSubmit?: () => void;
314490 }) => {
315491 return (
316492 <section>
......@@ -331,9 +507,12 @@ export const FormSection = ({
331507 <Alert severity="error">{item.text}</Alert>
332508 )}
333509 {item.text && !item.status && <p>{item.text}</p>}
334- {item.field && (
335- <FormField field={item.field} isResult={isResult ?? false} />
336- )}
510+ {item.field &&
511+ (item.field.name === buttonGridField ? (
512+ <ButtonGridField field={item.field} onSubmit={onSubmit} />
513+ ) : (
514+ <FormField field={item.field} isResult={isResult ?? false} />
515+ ))}
337516 {item.tableHeader && item.tableRows && (
338517 <FormTable header={item.tableHeader} rows={item.tableRows} />
339518 )}
......@@ -341,6 +520,8 @@ export const FormSection = ({
341520 <FormSection
342521 section={item.section}
343522 isResult={isResult ?? false}
523+ buttonGridField={buttonGridField}
524+ onSubmit={onSubmit}
344525 />
345526 )}
346527 </>
Back to top