Debian Codegraph @

pkg/playground/dialog.tsx

raw
1 /*
2 * Copyright (C) 2025 Red Hat, Inc.
3 *
4 * SPDX-License-Identifier: LGPL-2.1-or-later
5 */
6
7 import React, { useState, useReducer, useId } from "react";
8 import { createRoot } from 'react-dom/client';
9 import cockpit from 'cockpit';
10
11 import '../lib/patternfly/patternfly-6-cockpit.scss';
12
13 import { Page, PageSection } from "@patternfly/react-core/dist/esm/components/Page/index.js";
14 import { Bullseye } from "@patternfly/react-core/dist/esm/layouts/Bullseye";
15 import { Button } from "@patternfly/react-core/dist/esm/components/Button/index.js";
16 import { Checkbox } from "@patternfly/react-core/dist/esm/components/Checkbox";
17 import { Split, SplitItem } from "@patternfly/react-core/dist/esm/layouts/Split/index.js";
18 import { Modal, ModalBody, ModalHeader, ModalFooter } from '@patternfly/react-core/dist/esm/components/Modal';
19 import { Form, FormGroup } from "@patternfly/react-core/dist/esm/components/Form";
20 import { DescriptionList, DescriptionListDescription, DescriptionListGroup, DescriptionListTerm } from "@patternfly/react-core/dist/esm/components/DescriptionList/index.js";
21 import { Spinner } from "@patternfly/react-core/dist/esm/components/Spinner";
22
23 import { WithDialogs, useDialogs } from 'dialogs';
24
25 import {
26 useDialogState, DialogState,
27 useDialogState_async,
28 DialogError,
29 DialogErrorMessage,
30 DialogField,
31 DialogCheckbox,
32 DialogTextInput,
33 DialogRadioSelect,
34 DialogDropdownSelect, DialogDropdownSelectObject,
35 DialogHelperText,
36 DialogActionButton, DialogCancelButton,
37 } from 'cockpit/dialog';
38
39 import { FileChooser, DialogFileChooserInput } from "cockpit/react/FileChooser";
40
41 import 'cockpit-dark-theme'; // once per page
42 import 'page.scss';
43
44 function List<T>({
45 label,
46 field,
47 Component,
48 init,
49 } : {
50 label: string
51 field: DialogField<T[]>,
52 Component: ({ field } : { field: DialogField<T> }) => React.ReactNode,
53 init: T,
54 }) {
55 return (
56 <FormGroup label={label} data-ouia-component-id={field.ouia_id()}>
57 { field.map((f, i) => (
58 <Split key={i}>
59 <SplitItem isFilled>
60 <Component field={f} />
61 </SplitItem>
62 <SplitItem>
63 <Button
64 ouiaId={f.ouia_id("remove")}
65 variant="link"
66 onClick={() => field.remove(i)}
67 >
68 Remove
69 </Button>
70 </SplitItem>
71 </Split>
72 ))}
73 <DialogHelperText field={field} />
74 <Button
75 ouiaId={field.ouia_id("add")}
76 variant="link"
77 onClick={() => field.add(init)}
78 >
79 Add
80 </Button>
81 </FormGroup>
82 );
83 }
84
85 const StringList = ({
86 field,
87 label,
88 } : {
89 field: DialogField<string[]>,
90 label: string
91 }) => {
92 return (
93 <List
94 label={label}
95 field={field}
96 Component={DialogTextInput}
97 init=""
98 />
99 );
100 };
101
102 interface Name {
103 name: string;
104 _length: number;
105 }
106
107 const NameInput = ({
108 field,
109 } : {
110 field: DialogField<Name>,
111 }) => {
112 return <DialogTextInput field={field.sub("name")} debounce={1000} />;
113 };
114
115 function validate_Name(field: DialogField<Name>, countAsyncValidation: () => void) {
116 field.sub("name").validate_async(async (n, signal) => {
117 await async_sleep(2000);
118 countAsyncValidation();
119 if (!signal.aborted)
120 field.sub("_length").set(n.length);
121 if (n.length % 2)
122 return "Must have even number of characters";
123 });
124 }
125
126 const NameList = ({
127 field,
128 label,
129 } : {
130 field: DialogField<Name[]>,
131 label: string
132 }) => {
133 return (
134 <List
135 label={label}
136 field={field}
137 Component={NameInput}
138 init={{ name: "", _length: 0 }}
139 />
140 );
141 };
142
143 const OptionalTextInput = ({
144 field_label,
145 checkbox_label,
146 field,
147 } : {
148 field_label: string,
149 checkbox_label: string;
150 field: DialogField<false | string>,
151 }) => {
152 const id = useId();
153 const val = field.get();
154 let body;
155
156 if (val === false) {
157 body = (
158 <Checkbox
159 id={id}
160 ouiaId={field.ouia_id("checkbox")}
161 isChecked={false}
162 label={checkbox_label}
163 onChange={() => field.set("")}
164 />
165 );
166 } else {
167 body = (
168 <>
169 <Checkbox
170 id={id}
171 ouiaId={field.ouia_id("checkbox")}
172 isChecked
173 label={checkbox_label}
174 onChange={() => field.set(false)}
175 />
176 <DialogTextInput field={field.at(val)} />
177 </>
178 );
179 }
180
181 return (
182 <FormGroup
183 label={field_label}
184 >
185 {body}
186 <DialogHelperText field={field} />
187 </FormGroup>
188 );
189 };
190
191 function async_sleep(n: number) {
192 return new Promise(resolve => {
193 window.setTimeout(resolve, n);
194 });
195 }
196
197 interface Color {
198 name: string,
199 red: number,
200 green: number,
201 blue: number,
202 }
203
204 const colors: Color[] = [
205 { name: "red", red: 1, green: 0, blue: 0 },
206 { name: "green", red: 0, green: 1, blue: 0 },
207 { name: "blue", red: 0, green: 0, blue: 1 },
208 ];
209
210 interface ExampleValues {
211 flag: boolean;
212 text: string;
213 text2: string;
214 radio: string;
215 dropdown: string;
216 text3: string;
217 color: Color,
218 list: string[];
219 async: Name[];
220 alternative: false | string;
221 error: string;
222 allow_force: boolean;
223 file: string;
224 file_explanation: string;
225 dir: string;
226 }
227
228 const ExampleDialog = ({
229 setResult,
230 countAsyncValidation,
231 countAsyncUpdate,
232 countAsyncCancel,
233 } : {
234 setResult: (values: ExampleValues) => void,
235 countAsyncValidation: () => void,
236 countAsyncUpdate: () => void,
237 countAsyncCancel: () => void,
238 }) => {
239 const Dialogs = useDialogs();
240
241 const init: ExampleValues = {
242 flag: false,
243 text: "",
244 text2: "",
245 radio: "one",
246 dropdown: "one",
247 text3: "",
248 color: colors[0],
249 list: [],
250 async: [],
251 alternative: false,
252 error: "none",
253 allow_force: false,
254 file: "",
255 file_explanation: "",
256 dir: "",
257 };
258
259 function validate(dlg: DialogState<ExampleValues>) {
260 if (dlg.values.flag) {
261 dlg.field("text").validate(v => {
262 if (!v)
263 return "Text can not be empty";
264 });
265 }
266 if (dlg.values.dropdown === "three") {
267 dlg.field("text3").validate(v => {
268 if (!v)
269 return "Can't be empty";
270 });
271 }
272 dlg.field("list").forEach(v => {
273 v.validate(vv => {
274 if (vv === "magic")
275 dlg.field("text").set("magic");
276 if (vv === ".")
277 return "No dots";
278 });
279 });
280 dlg.field("async").forEach(v => validate_Name(v, countAsyncValidation));
281 dlg.field("file").validate(v => {
282 if (v && v[0] !== "/")
283 return "Must be absolute";
284 });
285 }
286
287 const dlg = useDialogState(init, validate);
288
289 async function apply(values: ExampleValues, variant: string) {
290 setResult(values);
291
292 if (variant === "force")
293 return;
294
295 if (values.error === "custom") {
296 throw new DialogError("This is a failure", <code>1234-567-98A</code>);
297 } else if (values.error === "from") {
298 const err = new Error("no such file or scraper");
299 throw DialogError.fromError("Tool not found", err);
300 } else if (values.error === "from-random") {
301 const err = [1, 2, 3, 4];
302 throw DialogError.fromError("Too random", err);
303 } else if (values.error === "message") {
304 // eslint-disable-next-line no-throw-literal
305 throw { message: "segmentation fault" };
306 } else if (values.error === "spawn") {
307 await cockpit.spawn(["ls", "--no-such-option"], { err: "message" });
308 } else if (values.error === "random") {
309 // eslint-disable-next-line no-throw-literal
310 throw [1, 2, 3, 4];
311 }
312 }
313
314 function color_changed() {
315 dlg.field("color").get_async(async (val, signal) => {
316 signal.onabort = countAsyncCancel;
317 await async_sleep(2000);
318 if (!signal.aborted) {
319 countAsyncUpdate();
320 dlg.field("text").set(val.name);
321 }
322 });
323 }
324
325 function dropdown_changed(val: string) {
326 dlg.field("text2").set_async(async () => {
327 await async_sleep(2000);
328 return val;
329 });
330 }
331
332 function file_changed(val: string) {
333 dlg.field("file_explanation").set_async(async () => {
334 if (val[0] === "/")
335 return cockpit.spawn(["file", "-b", val], { superuser: "try" });
336 else
337 return "--";
338 });
339 }
340
341 return (
342 <Modal
343 id="dialog"
344 position="top"
345 variant="medium"
346 isOpen
347 onClose={Dialogs.close}
348 >
349 <ModalHeader title="Demo" />
350 <ModalBody>
351 <DialogErrorMessage dialog={dlg} />
352 <Form isHorizontal>
353 <DialogCheckbox
354 field_label="Checkbox"
355 checkbox_label="Enable text"
356 field={dlg.field("flag")}
357 />
358 <DialogTextInput
359 label="Text"
360 field={dlg.field("text")}
361 debounce={0}
362 excuse={!dlg.values.flag && "Disabled"}
363 explanation="Explanation"
364 warning={dlg.values.text === "warn" ? "Warning" : null}
365 />
366 <DialogTextInput
367 label="Text2"
368 field={dlg.field("text2")}
369 />
370 {
371 // Calling "map" on a non-array should just do nothing.
372 dlg.field("text").map((v, i) => <span key={i}>{v.get()}</span>)
373 }
374 <DialogRadioSelect
375 label="Radio"
376 field={dlg.field("radio")}
377 options={
378 [
379 {
380 value: "one",
381 label: "Eins",
382 explanation: "One explanation"
383 },
384 {
385 value: "two",
386 label: "Zwei",
387 explanation: "Two explanation",
388 excuse: "disabled",
389 },
390 {
391 value: "three",
392 label: "Drei",
393 },
394 ]
395 }
396 />
397 <DialogDropdownSelect
398 label="Dropdown"
399 field={dlg.field("dropdown", dropdown_changed)}
400 options={
401 [
402 { value: "one", label: "Eins" },
403 { value: "two", label: "Zwei" },
404 { value: "three", label: "Drei" },
405 ]
406 }
407 warning={dlg.field("dropdown").get() === "two" ? "There is a discount if you buy three." : null}
408 />
409 {
410 dlg.values.dropdown === "three" &&
411 <DialogTextInput label="Text3" field={dlg.field("text3")} debounce={1000} />
412 }
413 <DialogDropdownSelectObject
414 label="DropdownObject"
415 field={dlg.field("color").notify(color_changed)}
416 options={colors}
417 option_label={c => c.name}
418 />
419 <StringList label="List" field={dlg.field("list")} />
420 <NameList label="Async" field={dlg.field("async")} />
421 <OptionalTextInput
422 field_label="Alternative"
423 checkbox_label="Custom value"
424 field={dlg.field("alternative")}
425 />
426 <DialogDropdownSelectObject
427 label="Error"
428 field={dlg.field("error")}
429 options={["none", "custom", "from", "from-random", "message", "spawn", "random"]}
430 warning={dlg.field("error").get() !== "none" ? "There will be an error unless you apply with force" : null}
431 />
432 <DialogCheckbox
433 field_label="Action options"
434 checkbox_label="Allow force"
435 field={dlg.field("allow_force")}
436 />
437 <DialogFileChooserInput
438 label="File"
439 field={dlg.field("file", file_changed)}
440 explanation={dlg.values.file_explanation}
441 fileChooserProps={
442 {
443 title: "Select a file",
444 superuser: "try",
445 filters: [
446 { label: "No dots", filter: n => !n.includes(".") },
447 ],
448 shortcuts: [
449 { label: "Test files", path: "/var/lib/cockpittest" }
450 ],
451 collections: [
452 {
453 label: "Some files",
454 emptyLabel: "Nothing there",
455 list: async () => {
456 return [
457 "/var/lib/cockpittest/file-chooser-test/dots.txt",
458 "/var/lib/cockpittest/file-chooser-test/foo",
459 ];
460 }
461 }
462 ]
463 }
464 }
465 />
466 <DialogFileChooserInput
467 label="Directory"
468 field={dlg.field("dir")}
469 fileChooserProps={
470 {
471 title: "Select a directory",
472 onlyDirectories: true,
473 superuser: "try",
474 shortcuts: [
475 { label: "Test files", path: "/var/lib/cockpittest" }
476 ],
477 }
478 }
479 />
480 </Form>
481 </ModalBody>
482 <ModalFooter>
483 <DialogActionButton
484 dialog={dlg}
485 action={values => apply(values, "main")}
486 onClose={Dialogs.close}
487 >
488 Apply
489 </DialogActionButton>
490 <DialogActionButton
491 dialog={dlg}
492 action={values => apply(values, "force")}
493 ouiaId="apply-force"
494 variant="danger"
495 onClose={Dialogs.close}
496 excuse={dlg.values.allow_force ? undefined : "Force not allowed"}
497 >
498 Apply with force
499 </DialogActionButton>
500 <DialogCancelButton dialog={dlg} onClose={Dialogs.close}>
501 CANCEL!
502 </DialogCancelButton>
503 </ModalFooter>
504 </Modal>
505 );
506 };
507
508 const ExampleButton = () => {
509 const Dialogs = useDialogs();
510 const [values, setValues] = useState<ExampleValues | null>(null);
511 const [asyncValidationsBase, setAsyncValidationsBase] = useState<number>(0);
512 const [asyncValidations, countAsyncValidation] = useReducer(x => x + 1, 0);
513 const [asyncUpdatesBase, setAsyncUpdatesBase] = useState<number>(0);
514 const [asyncUpdates, countAsyncUpdate] = useReducer(x => x + 1, 0);
515 const [asyncCancelsBase, setAsyncCancelsBase] = useState<number>(0);
516 const [asyncCancels, countAsyncCancel] = useReducer(x => x + 1, 0);
517
518 function entry(id: string, val: string) {
519 return (
520 <DescriptionListGroup>
521 <DescriptionListTerm>{id}</DescriptionListTerm>
522 <DescriptionListDescription id={id}>{val}</DescriptionListDescription>
523 </DescriptionListGroup>
524 );
525 }
526
527 return (
528 <>
529 <Button
530 id="open"
531 onClick={
532 () => {
533 setAsyncValidationsBase(asyncValidations);
534 setAsyncUpdatesBase(asyncUpdates);
535 setAsyncCancelsBase(asyncCancels);
536 Dialogs.show(
537 <ExampleDialog
538 setResult={setValues}
539 countAsyncValidation={countAsyncValidation}
540 countAsyncUpdate={countAsyncUpdate}
541 countAsyncCancel={countAsyncCancel}
542 />
543 );
544 }
545 }
546 >
547 Open dialog
548 </Button>
549 { values &&
550 <DescriptionList isHorizontal>
551 { entry("flag", String(values.flag)) }
552 { values.flag && entry("text", values.text) }
553 { entry("text2", values.text2) }
554 { entry("radio", values.radio) }
555 { entry("dropdown", values.dropdown) }
556 { entry("color", values.color.red + "/" + values.color.green + "/" + values.color.blue) }
557 { entry("list", values.list.join("/")) }
558 { entry("async", values.async.map(n => n.name + ":" + String(n._length)).join("/")) }
559 { entry("asyncVals", String(asyncValidations - asyncValidationsBase)) }
560 { entry("asyncUps", String(asyncUpdates - asyncUpdatesBase)) }
561 { entry("asyncCancels", String(asyncCancels - asyncCancelsBase)) }
562 { entry("alternative", JSON.stringify(values.alternative)) }
563 </DescriptionList>
564 }
565 </>
566 );
567 };
568
569 interface ExampleWithInitFuncValues {
570 text: string;
571 text2: string;
572 }
573
574 const ExampleDialogWithInitFunc = () => {
575 const Dialogs = useDialogs();
576
577 function init(): ExampleWithInitFuncValues {
578 return {
579 text: "foo",
580 text2: "bar",
581 };
582 }
583
584 function validate(dlg: DialogState<ExampleWithInitFuncValues>) {
585 dlg.top().validate(v => {
586 if (v.text === "foo" && v.text2 !== "bar") {
587 return {
588 text: "No foo without bar",
589 };
590 }
591 if (v.text2 === "bar" && v.text !== "foo") {
592 return {
593 text2: { "": "No bar without foo" },
594 };
595 }
596 });
597 }
598
599 const dlg = useDialogState(init, validate);
600
601 return (
602 <Modal
603 id="dialog"
604 position="top"
605 variant="medium"
606 isOpen
607 onClose={Dialogs.close}
608 >
609 <ModalHeader title="Demo" />
610 <ModalBody>
611 <DialogErrorMessage dialog={dlg} />
612 <Form isHorizontal>
613 <DialogTextInput
614 label="Text"
615 field={dlg.field("text")}
616 />
617 <DialogTextInput
618 label="Text 2"
619 field={dlg.field("text2")}
620 />
621 </Form>
622 </ModalBody>
623 <ModalFooter>
624 <DialogActionButton dialog={dlg} action={async () => {}} onClose={Dialogs.close}>
625 Apply
626 </DialogActionButton>
627 <DialogCancelButton dialog={dlg} onClose={Dialogs.close} />
628 </ModalFooter>
629 </Modal>
630 );
631 };
632
633 interface AsyncExampleValues {
634 text: string;
635 }
636
637 const AsyncExampleDialog = ({
638 throwError = 0,
639 cancelCallback = null,
640 } : {
641 throwError?: number,
642 cancelCallback?: null | (() => void),
643 }) => {
644 const Dialogs = useDialogs();
645
646 async function init(): Promise<AsyncExampleValues> {
647 if (throwError === 1)
648 throw new Error("can't get the thing");
649 else if (throwError === 2)
650 throw new DialogError("Getting the thing failed", <i>can't get it</i>);
651
652 await async_sleep(500);
653 return {
654 text: "",
655 };
656 }
657
658 function validate(dlg: DialogState<AsyncExampleValues>) {
659 dlg.field("text").validate_async(async () => {
660 throw Error("upps");
661 });
662 }
663
664 const dlg = useDialogState_async(init, validate);
665
666 async function apply() {
667 cockpit.assert(dlg instanceof DialogState);
668
669 dlg.set_cancel(cancelCallback);
670
671 await async_sleep(1000);
672 Dialogs.close();
673 }
674
675 function top_changed(values: AsyncExampleValues) {
676 console.log("TOP", JSON.stringify(values));
677 }
678
679 let body;
680 if (!dlg) {
681 body = (
682 <Bullseye>
683 <Spinner />
684 </Bullseye>
685 );
686 } else if (dlg instanceof DialogError) {
687 body = null;
688 } else if (dlg instanceof DialogState) {
689 const fields = dlg.top(top_changed);
690 body = (
691 <Form isHorizontal>
692 <DialogTextInput label="Text" field={fields.sub("text")} />
693 </Form>
694 );
695 }
696
697 return (
698 <Modal
699 id="dialog"
700 position="top"
701 variant="medium"
702 isOpen
703 onClose={Dialogs.close}
704 >
705 <ModalHeader title="Async Demo" />
706 <ModalBody>
707 <DialogErrorMessage dialog={dlg} />
708 { body }
709 </ModalBody>
710 <ModalFooter>
711 <DialogActionButton dialog={dlg} action={apply}>
712 Apply
713 </DialogActionButton>
714 <DialogCancelButton dialog={dlg} onClose={Dialogs.close} />
715 </ModalFooter>
716 </Modal>
717 );
718 };
719
720 const SimpleExampleButtons = () => {
721 const Dialogs = useDialogs();
722 const [cancelled, setCancelled] = useState(false);
723
724 return (
725 <>
726 <Button
727 id="open-with-func"
728 onClick={() => Dialogs.show(<ExampleDialogWithInitFunc />)}
729 >
730 Open init-func dialog
731 </Button>
732 <Button
733 id="open-async"
734 onClick={
735 () => {
736 setCancelled(false);
737 Dialogs.show(<AsyncExampleDialog cancelCallback={() => setCancelled(true)} />);
738 }
739 }
740 >
741 Open async dialog
742 </Button>
743 <div id="cancelled">
744 Cancelled: {cancelled ? "yes" : "no"}
745 </div>
746 <Button
747 id="open-error"
748 onClick={() => Dialogs.show(<AsyncExampleDialog throwError={1} />)}
749 >
750 Open Error dialog
751 </Button>
752 <Button
753 id="open-dialog-error"
754 onClick={() => Dialogs.show(<AsyncExampleDialog throwError={2} />)}
755 >
756 Open DialogError dialog
757 </Button>
758 </>
759 );
760 };
761
762 const FileChooserButton = () => {
763 const Dialogs = useDialogs();
764
765 async function loadFile(path: string) {
766 const data = await cockpit.file(path).read();
767 if (!data.startsWith("foo"))
768 throw new Error("Does not start with \"foo\"");
769 }
770
771 return (
772 <Button
773 id="open-file-chooser"
774 onClick={
775 () => Dialogs.show(
776 <FileChooser
777 title={"Select a file that starts with \"foo\""}
778 actionLabel="Load"
779 action={loadFile}
780 filters={
781 [
782 {
783 label: "TXT files",
784 filter: (name, type) => type === "reg" && !!name.match("\\.txt$")
785 },
786 ]
787 }
788 shortcuts={
789 async () => {
790 await async_sleep(500);
791 return [
792 { label: "Test files", path: "/var/lib/cockpittest" }
793 ];
794 }
795 }
796 collections={
797 async () => {
798 return [
799 {
800 label: "Some TXT files",
801 emptyLabel: "Nothing there",
802 list: async () => {
803 return [
804 "/var/lib/cockpittest/file-chooser-test/text/foo.txt",
805 "/var/lib/cockpittest/file-chooser-test/no-such-file.txt"
806 ];
807 }
808 }
809 ];
810 }
811 }
812 />
813 )
814 }
815 >
816 Open FileChooser
817 </Button>
818 );
819 };
820
821 const Demo = () => {
822 return (
823 <WithDialogs>
824 <Page isContentFilled className="no-masthead-sidebar">
825 <PageSection>
826 <ExampleButton />
827 <SimpleExampleButtons />
828 <FileChooserButton />
829 </PageSection>
830 </Page>
831 </WithDialogs>
832 );
833 };
834
835 document.addEventListener("DOMContentLoaded", function() {
836 window.debugging = "dialog";
837 createRoot(document.getElementById('app')!).render(<Demo />);
838 });