LCOV - code coverage report
Current view: top level - pkg/playground - dialog.tsx Coverage Total Hit
Test: cockpit Lines: 97.7 % 567 554
Test Date: 2026-06-25 09:20:42

            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 } 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 { DialogFileChooserInput } from "cockpit/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 val = field.get();
     153            2 :     let body;
     154              : 
     155            2 :     if (val === false) {
     156            2 :         body = (
     157            2 :             <Checkbox
     158            2 :                 id={field.random_id()}
     159            2 :                 ouiaId={field.ouia_id("checkbox")}
     160            2 :                 isChecked={false}
     161            2 :                 label={checkbox_label}
     162            1 :                 onChange={() => field.set("")}
     163            2 :             />
     164              :         );
     165            1 :     } else {
     166            1 :         body = (
     167            1 :             <>
     168            1 :                 <Checkbox
     169            1 :                     id={field.random_id()}
     170            1 :                     ouiaId={field.ouia_id("checkbox")}
     171            1 :                     isChecked
     172            1 :                     label={checkbox_label}
     173            1 :                     onChange={() => field.set(false)}
     174            1 :                 />
     175            1 :                 <DialogTextInput field={field.at(val)} />
     176            1 :             </>
     177              :         );
     178            1 :     }
     179              : 
     180            2 :     return (
     181            2 :         <FormGroup
     182            2 :             label={field_label}
     183              :         >
     184            2 :             {body}
     185            2 :             <DialogHelperText field={field} />
     186            2 :         </FormGroup>
     187              :     );
     188            2 : };
     189              : 
     190            1 : function async_sleep(n: number) {
     191            1 :     return new Promise(resolve => {
     192            1 :         window.setTimeout(resolve, n);
     193            1 :     });
     194            1 : }
     195              : 
     196              : interface Color {
     197              :     name: string,
     198              :     red: number,
     199              :     green: number,
     200              :     blue: number,
     201              : }
     202              : 
     203            2 : const colors: Color[] = [
     204            2 :     { name: "red", red: 1, green: 0, blue: 0 },
     205            2 :     { name: "green", red: 0, green: 1, blue: 0 },
     206            2 :     { name: "blue", red: 0, green: 0, blue: 1 },
     207            2 : ];
     208              : 
     209              : interface ExampleValues {
     210              :     flag: boolean;
     211              :     text: string;
     212              :     text2: string;
     213              :     radio: string;
     214              :     dropdown: string;
     215              :     text3: string;
     216              :     color: Color,
     217              :     list: string[];
     218              :     async: Name[];
     219              :     alternative: false | string;
     220              :     error: string;
     221              :     file: string;
     222              :     file_explanation: string;
     223              :     dir: string;
     224              : }
     225              : 
     226            2 : const ExampleDialog = ({
     227            2 :     setResult,
     228            2 :     countAsyncValidation,
     229            2 :     countAsyncUpdate,
     230            2 :     countAsyncCancel,
     231            2 : } : {
     232              :     setResult: (values: ExampleValues) => void,
     233              :     countAsyncValidation: () => void,
     234              :     countAsyncUpdate: () => void,
     235              :     countAsyncCancel: () => void,
     236            2 : }) => {
     237            2 :     const Dialogs = useDialogs();
     238              : 
     239            2 :     const init: ExampleValues = {
     240            2 :         flag: false,
     241            2 :         text: "",
     242            2 :         text2: "",
     243            2 :         radio: "one",
     244            2 :         dropdown: "one",
     245            2 :         text3: "",
     246            2 :         color: colors[0],
     247            2 :         list: [],
     248            2 :         async: [],
     249            2 :         alternative: false,
     250            2 :         error: "none",
     251            2 :         file: "",
     252            2 :         file_explanation: "",
     253            2 :         dir: "",
     254            2 :     };
     255              : 
     256            1 :     function validate(dlg: DialogState<ExampleValues>) {
     257            1 :         if (dlg.values.flag) {
     258            1 :             dlg.field("text").validate(v => {
     259            1 :                 if (!v)
     260            1 :                     return "Text can not be empty";
     261            1 :             });
     262            1 :         }
     263            1 :         if (dlg.values.dropdown == "three") {
     264            1 :             dlg.field("text3").validate_async(1000, async v => {
     265            1 :                 if (!v)
     266            1 :                     return "Can't be empty";
     267            1 :             });
     268            1 :         }
     269            1 :         dlg.field("list").forEach(v => {
     270            1 :             v.validate(vv => {
     271            1 :                 if (vv == "magic")
     272            1 :                     dlg.field("text").set("magic");
     273            1 :                 if (vv == ".")
     274            0 :                     return "No dots";
     275            1 :             });
     276            1 :         });
     277            1 :         dlg.field("async").forEach(v => validate_Name(v, countAsyncValidation));
     278            1 :         dlg.field("file").validate(v => {
     279            0 :             if (v && v[0] != "/")
     280            0 :                 return "Must be absolute";
     281            1 :         });
     282            1 :     }
     283              : 
     284            2 :     const dlg = useDialogState(init, validate);
     285              : 
     286            1 :     async function apply(values: ExampleValues) {
     287            1 :         setResult(values);
     288              : 
     289            1 :         if (values.error == "custom") {
     290            1 :             throw new DialogError("This is a failure", <code>1234-567-98A</code>);
     291            1 :         } else if (values.error == "from") {
     292            1 :             const err = new Error("no such file or scraper");
     293            1 :             throw DialogError.fromError("Tool not found", err);
     294            1 :         } else if (values.error == "from-random") {
     295            1 :             const err = [1, 2, 3, 4];
     296            1 :             throw DialogError.fromError("Too random", err);
     297            1 :         } else if (values.error == "message") {
     298              :             // eslint-disable-next-line no-throw-literal
     299            1 :             throw { message: "segmentation fault" };
     300            1 :         } else if (values.error == "spawn") {
     301            0 :             await cockpit.spawn(["ls", "--no-such-option"], { err: "message" });
     302            0 :         } else if (values.error == "random") {
     303              :             // eslint-disable-next-line no-throw-literal
     304            1 :             throw [1, 2, 3, 4];
     305            1 :         }
     306            1 :     }
     307              : 
     308            1 :     function update_color() {
     309            1 :         dlg.field("color").get_async(0, async (val, signal) => {
     310            1 :             signal.onabort = countAsyncCancel;
     311            1 :             await async_sleep(2000);
     312            1 :             if (!signal.aborted) {
     313            1 :                 countAsyncUpdate();
     314            1 :                 dlg.field("text").set(val.name);
     315            1 :             }
     316            1 :         });
     317            1 :     }
     318              : 
     319            1 :     function update_dropdown(val: string) {
     320            1 :         dlg.field("text2").set_async(0, async () => {
     321            1 :             await async_sleep(2000);
     322            1 :             return val;
     323            1 :         });
     324            1 :     }
     325              : 
     326            1 :     function update_file(val: string) {
     327            1 :         dlg.field("file_explanation").set_async(250, async () => {
     328            1 :             if (val[0] == "/")
     329            1 :                 return cockpit.spawn(["file", "-b", val], { superuser: "try" });
     330              :             else
     331            1 :                 return "--";
     332            1 :         });
     333            1 :     }
     334              : 
     335            2 :     return (
     336            2 :         <Modal
     337            2 :             id="dialog"
     338            2 :             position="top"
     339            2 :             variant="medium"
     340            2 :             isOpen
     341            2 :             onClose={Dialogs.close}
     342              :         >
     343            2 :             <ModalHeader title="Demo" />
     344            2 :             <ModalBody>
     345            2 :                 <DialogErrorMessage dialog={dlg} />
     346            2 :                 <Form isHorizontal>
     347            2 :                     <DialogCheckbox
     348            2 :                         field_label="Checkbox"
     349            2 :                         checkbox_label="Enable text"
     350            2 :                         field={dlg.field("flag")}
     351            2 :                     />
     352            2 :                     <DialogTextInput
     353            2 :                         label="Text"
     354            2 :                         field={dlg.field("text")}
     355            2 :                         excuse={!dlg.values.flag && "Disabled"}
     356            2 :                         explanation="Explanation"
     357            1 :                         warning={dlg.values.text == "warn" ? "Warning" : null}
     358            2 :                     />
     359            2 :                     <DialogTextInput
     360            2 :                         label="Text2"
     361            2 :                         field={dlg.field("text2")}
     362            2 :                     />
     363              :                     {
     364              :                         // Calling "map" on a non-array should just do nothing.
     365            0 :                         dlg.field("text").map((v, i) => <span key={i}>{v.get()}</span>)
     366              :                     }
     367            2 :                     <DialogRadioSelect
     368            2 :                         label="Radio"
     369            2 :                         field={dlg.field("radio")}
     370            2 :                         options={
     371            2 :                             [
     372            2 :                                 {
     373            2 :                                     value: "one",
     374            2 :                                     label: "Eins",
     375            2 :                                     explanation: "One explanation"
     376            2 :                                 },
     377            2 :                                 {
     378            2 :                                     value: "two",
     379            2 :                                     label: "Zwei",
     380            2 :                                     explanation: "Two explanation",
     381            2 :                                     excuse: "disabled",
     382            2 :                                 },
     383            2 :                                 {
     384            2 :                                     value: "three",
     385            2 :                                     label: "Drei",
     386            2 :                                 },
     387            2 :                             ]
     388              :                         }
     389            2 :                     />
     390            2 :                     <DialogDropdownSelect
     391            2 :                         label="Dropdown"
     392            2 :                         field={dlg.field("dropdown", update_dropdown)}
     393            2 :                         options={
     394            2 :                             [
     395            2 :                                 { value: "one", label: "Eins" },
     396            2 :                                 { value: "two", label: "Zwei" },
     397            2 :                                 { value: "three", label: "Drei" },
     398            2 :                             ]
     399              :                         }
     400            1 :                         warning={dlg.field("dropdown").get() == "two" ? "There is a discount if you buy three." : null}
     401            2 :                     />
     402              :                     {
     403            2 :                         dlg.values.dropdown == "three" &&
     404            1 :                             <DialogTextInput label="Text3" field={dlg.field("text3")} />
     405              :                     }
     406            2 :                     <DialogDropdownSelectObject
     407            2 :                         label="DropdownObject"
     408            2 :                         field={dlg.field("color", update_color)}
     409            2 :                         options={colors}
     410            2 :                         option_label={c => c.name}
     411            2 :                     />
     412            2 :                     <StringList label="List" field={dlg.field("list")} />
     413            2 :                     <NameList label="Async" field={dlg.field("async")} />
     414            2 :                     <OptionalTextInput
     415            2 :                         field_label="Alternative"
     416            2 :                         checkbox_label="Custom value"
     417            2 :                         field={dlg.field("alternative")}
     418            2 :                     />
     419            2 :                     <DialogDropdownSelectObject
     420            2 :                         label="Error"
     421            2 :                         field={dlg.field("error")}
     422            2 :                         options={["none", "custom", "from", "from-random", "message", "spawn", "random"]}
     423            1 :                         warning={dlg.field("error").get() != "none" ? "There will be an error" : null}
     424            2 :                     />
     425            2 :                     <DialogFileChooserInput
     426            2 :                         label="File"
     427            2 :                         field={dlg.field("file", update_file)}
     428            2 :                         explanation={dlg.values.file_explanation}
     429            2 :                         fileChooserProps={
     430            2 :                             {
     431            2 :                                 title: "Select a file",
     432            2 :                                 superuser: "try",
     433            2 :                                 filters: [
     434            1 :                                     { label: "No dots", filter: n => !n.includes(".") },
     435            2 :                                 ],
     436            2 :                                 shortcuts: [
     437            2 :                                     { label: "Test files", path: "/var/lib/cockpittest" }
     438            2 :                                 ],
     439            2 :                                 collections: [
     440            2 :                                     {
     441            2 :                                         label: "Some files",
     442            0 :                                         list: async () => {
     443            0 :                                             return [
     444            0 :                                                 { name: "/home/admin/.ssh/id_rsa", type: "reg" },
     445            0 :                                                 { name: "/home/admin/Pictures", type: "dir" },
     446            0 :                                             ];
     447            0 :                                         }
     448            2 :                                     }
     449            2 :                                 ]
     450            2 :                             }
     451              :                         }
     452            2 :                     />
     453            2 :                     <DialogFileChooserInput
     454            2 :                         label="Directory"
     455            2 :                         field={dlg.field("dir")}
     456            2 :                         fileChooserProps={
     457            2 :                             {
     458            2 :                                 title: "Select a directory",
     459            2 :                                 onlyDirectories: true,
     460            2 :                                 superuser: "try",
     461            2 :                                 shortcuts: [
     462            2 :                                     { label: "Test files", path: "/var/lib/cockpittest" }
     463            2 :                                 ],
     464            2 :                             }
     465              :                         }
     466            2 :                     />
     467            2 :                 </Form>
     468            2 :             </ModalBody>
     469            2 :             <ModalFooter>
     470            2 :                 <DialogActionButton dialog={dlg} action={apply} onClose={Dialogs.close}>
     471              :                     Apply
     472            2 :                 </DialogActionButton>
     473            2 :                 <DialogCancelButton dialog={dlg} onClose={Dialogs.close} />
     474            2 :             </ModalFooter>
     475            2 :         </Modal>
     476              :     );
     477            2 : };
     478              : 
     479            2 : const ExampleButton = () => {
     480            2 :     const Dialogs = useDialogs();
     481            2 :     const [values, setValues] = useState<ExampleValues | null>(null);
     482            2 :     const [asyncValidationsBase, setAsyncValidationsBase] = useState<number>(0);
     483            1 :     const [asyncValidations, countAsyncValidation] = useReducer(x => x + 1, 0);
     484            2 :     const [asyncUpdatesBase, setAsyncUpdatesBase] = useState<number>(0);
     485            1 :     const [asyncUpdates, countAsyncUpdate] = useReducer(x => x + 1, 0);
     486            2 :     const [asyncCancelsBase, setAsyncCancelsBase] = useState<number>(0);
     487            1 :     const [asyncCancels, countAsyncCancel] = useReducer(x => x + 1, 0);
     488              : 
     489            1 :     function entry(id: string, val: string) {
     490            1 :         return (
     491            1 :             <DescriptionListGroup>
     492            1 :                 <DescriptionListTerm>{id}</DescriptionListTerm>
     493            1 :                 <DescriptionListDescription id={id}>{val}</DescriptionListDescription>
     494            1 :             </DescriptionListGroup>
     495              :         );
     496            1 :     }
     497              : 
     498            2 :     return (
     499            2 :         <>
     500            2 :             <Button
     501            2 :                 id="open"
     502            2 :                 onClick={
     503            2 :                     () => {
     504            2 :                         setAsyncValidationsBase(asyncValidations);
     505            2 :                         setAsyncUpdatesBase(asyncUpdates);
     506            2 :                         setAsyncCancelsBase(asyncCancels);
     507            2 :                         Dialogs.show(
     508            2 :                             <ExampleDialog
     509            2 :                                 setResult={setValues}
     510            2 :                                 countAsyncValidation={countAsyncValidation}
     511            2 :                                 countAsyncUpdate={countAsyncUpdate}
     512            2 :                                 countAsyncCancel={countAsyncCancel}
     513            2 :                             />
     514            2 :                         );
     515            2 :                     }
     516              :                 }
     517            2 :             >
     518              :                 Open dialog
     519            2 :             </Button>
     520            2 :             { values &&
     521            1 :                 <DescriptionList isHorizontal>
     522            1 :                     { entry("flag", String(values.flag)) }
     523            1 :                     { values.flag && entry("text", values.text) }
     524            1 :                     { entry("text2", values.text2) }
     525            1 :                     { entry("radio", values.radio) }
     526            1 :                     { entry("dropdown", values.dropdown) }
     527            1 :                     { entry("color", values.color.red + "/" + values.color.green + "/" + values.color.blue) }
     528            1 :                     { entry("list", values.list.join("/")) }
     529            1 :                     { entry("async", values.async.map(n => n.name + ":" + String(n._length)).join("/")) }
     530            1 :                     { entry("asyncVals", String(asyncValidations - asyncValidationsBase)) }
     531            1 :                     { entry("asyncUps", String(asyncUpdates - asyncUpdatesBase)) }
     532            1 :                     { entry("asyncCancels", String(asyncCancels - asyncCancelsBase)) }
     533            1 :                     { entry("alternative", JSON.stringify(values.alternative)) }
     534            1 :                 </DescriptionList>
     535              :             }
     536            2 :         </>
     537              :     );
     538            2 : };
     539              : 
     540              : interface ExampleWithInitFuncValues {
     541              :     text: string;
     542              :     text2: string;
     543              : }
     544              : 
     545            1 : const ExampleDialogWithInitFunc = () => {
     546            1 :     const Dialogs = useDialogs();
     547              : 
     548            1 :     function init(): ExampleWithInitFuncValues {
     549            1 :         return {
     550            1 :             text: "foo",
     551            1 :             text2: "bar",
     552            1 :         };
     553            1 :     }
     554              : 
     555            1 :     function validate(dlg: DialogState<ExampleWithInitFuncValues>) {
     556            1 :         dlg.top().validate(v => {
     557            1 :             if (v.text == "foo" && v.text2 != "bar") {
     558            1 :                 return {
     559            1 :                     text: "No foo without bar",
     560            1 :                 };
     561            1 :             }
     562            1 :             if (v.text2 == "bar" && v.text != "foo") {
     563            1 :                 return {
     564            1 :                     text2: { "": "No bar without foo" },
     565            1 :                 };
     566            1 :             }
     567            1 :         });
     568            1 :     }
     569              : 
     570            1 :     const dlg = useDialogState(init, validate);
     571              : 
     572            1 :     return (
     573            1 :         <Modal
     574            1 :             id="dialog"
     575            1 :             position="top"
     576            1 :             variant="medium"
     577            1 :             isOpen
     578            1 :             onClose={Dialogs.close}
     579              :         >
     580            1 :             <ModalHeader title="Demo" />
     581            1 :             <ModalBody>
     582            1 :                 <DialogErrorMessage dialog={dlg} />
     583            1 :                 <Form isHorizontal>
     584            1 :                     <DialogTextInput
     585            1 :                         label="Text"
     586            1 :                         field={dlg.field("text")}
     587            1 :                     />
     588            1 :                     <DialogTextInput
     589            1 :                         label="Text 2"
     590            1 :                         field={dlg.field("text2")}
     591            1 :                     />
     592            1 :                 </Form>
     593            1 :             </ModalBody>
     594            1 :             <ModalFooter>
     595            0 :                 <DialogActionButton dialog={dlg} action={async () => {}} onClose={Dialogs.close}>
     596              :                     Apply
     597            1 :                 </DialogActionButton>
     598            1 :                 <DialogCancelButton dialog={dlg} onClose={Dialogs.close} />
     599            1 :             </ModalFooter>
     600            1 :         </Modal>
     601              :     );
     602            1 : };
     603              : 
     604              : interface AsyncExampleValues {
     605              :     text: string;
     606              : }
     607              : 
     608            1 : const AsyncExampleDialog = ({
     609            1 :     throwError = 0,
     610            1 :     cancelCallback = null,
     611            1 : } : {
     612              :     throwError?: number,
     613              :     cancelCallback?: null | (() => void),
     614            1 : }) => {
     615            1 :     const Dialogs = useDialogs();
     616              : 
     617            1 :     async function init(): Promise<AsyncExampleValues> {
     618            1 :         if (throwError == 1)
     619            1 :             throw new Error("can't get the thing");
     620            1 :         else if (throwError == 2)
     621            1 :             throw new DialogError("Getting the thing failed", <i>can't get it</i>);
     622              : 
     623            1 :         await async_sleep(500);
     624            1 :         return {
     625            1 :             text: "",
     626            1 :         };
     627            1 :     }
     628              : 
     629            1 :     function validate(dlg: DialogState<AsyncExampleValues>) {
     630            1 :         dlg.field("text").validate_async(0, async () => {
     631            1 :             throw Error("upps");
     632            1 :         });
     633            1 :     }
     634              : 
     635            1 :     const dlg = useDialogState_async(init, validate);
     636              : 
     637            1 :     async function apply() {
     638            1 :         cockpit.assert(dlg instanceof DialogState);
     639              : 
     640            1 :         dlg.set_cancel(cancelCallback);
     641              : 
     642            1 :         await async_sleep(1000);
     643            1 :         Dialogs.close();
     644            1 :     }
     645              : 
     646            1 :     function update_top(values: AsyncExampleValues) {
     647            1 :         console.log("TOP", JSON.stringify(values));
     648            1 :     }
     649              : 
     650            1 :     let body;
     651            1 :     if (!dlg) {
     652            1 :         body = (
     653            1 :             <Bullseye>
     654            1 :                 <Spinner />
     655            1 :             </Bullseye>
     656              :         );
     657            1 :     } else if (dlg instanceof DialogError) {
     658            1 :         body = null;
     659            1 :     } else if (dlg instanceof DialogState) {
     660            1 :         const vals = dlg.top(update_top);
     661            1 :         body = (
     662            1 :             <Form isHorizontal>
     663            1 :                 <DialogTextInput label="Text" field={vals.sub("text")} />
     664            1 :             </Form>
     665              :         );
     666            1 :     }
     667              : 
     668            1 :     return (
     669            1 :         <Modal
     670            1 :             id="dialog"
     671            1 :             position="top"
     672            1 :             variant="medium"
     673            1 :             isOpen
     674            1 :             onClose={Dialogs.close}
     675              :         >
     676            1 :             <ModalHeader title="Async Demo" />
     677            1 :             <ModalBody>
     678            1 :                 <DialogErrorMessage dialog={dlg} />
     679            1 :                 { body }
     680            1 :             </ModalBody>
     681            1 :             <ModalFooter>
     682            1 :                 <DialogActionButton dialog={dlg} action={apply}>
     683              :                     Apply
     684            1 :                 </DialogActionButton>
     685            1 :                 <DialogCancelButton dialog={dlg} onClose={Dialogs.close} />
     686            1 :             </ModalFooter>
     687            1 :         </Modal>
     688              :     );
     689            1 : };
     690              : 
     691            2 : const SimpleExampleButtons = () => {
     692            2 :     const Dialogs = useDialogs();
     693            2 :     const [cancelled, setCancelled] = useState(false);
     694              : 
     695            2 :     return (
     696            2 :         <>
     697            2 :             <Button
     698            2 :                 id="open-with-func"
     699            1 :                 onClick={() => Dialogs.show(<ExampleDialogWithInitFunc />)}
     700            2 :             >
     701              :                 Open init-func dialog
     702            2 :             </Button>
     703            2 :             <Button
     704            2 :                 id="open-async"
     705            2 :                 onClick={
     706            1 :                     () => {
     707            1 :                         setCancelled(false);
     708            1 :                         Dialogs.show(<AsyncExampleDialog cancelCallback={() => setCancelled(true)} />);
     709            1 :                     }
     710              :                 }
     711            2 :             >
     712              :                 Open async dialog
     713            2 :             </Button>
     714            2 :             <div id="cancelled">
     715            1 :                 Cancelled: {cancelled ? "yes" : "no"}
     716            2 :             </div>
     717            2 :             <Button
     718            2 :                 id="open-error"
     719            1 :                 onClick={() => Dialogs.show(<AsyncExampleDialog throwError={1} />)}
     720            2 :             >
     721              :                 Open Error dialog
     722            2 :             </Button>
     723            2 :             <Button
     724            2 :                 id="open-dialog-error"
     725            1 :                 onClick={() => Dialogs.show(<AsyncExampleDialog throwError={2} />)}
     726            2 :             >
     727              :                 Open DialogError dialog
     728            2 :             </Button>
     729            2 :         </>
     730              :     );
     731            2 : };
     732              : 
     733            2 : const Demo = () => {
     734            2 :     return (
     735            2 :         <WithDialogs>
     736            2 :             <Page isContentFilled className="no-masthead-sidebar">
     737            2 :                 <PageSection>
     738            2 :                     <ExampleButton />
     739            2 :                     <SimpleExampleButtons />
     740            2 :                 </PageSection>
     741            2 :             </Page>
     742            2 :         </WithDialogs>
     743              :     );
     744            2 : };
     745              : 
     746            2 : document.addEventListener("DOMContentLoaded", function() {
     747            2 :     window.debugging = "dialog";
     748            2 :     createRoot(document.getElementById('app')!).render(<Demo />);
     749            2 : });
        

Generated by: LCOV version 2.0-1