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