/* * Copyright (C) 2025 Red Hat, Inc. * * SPDX-License-Identifier: LGPL-2.1-or-later */ import React, { useState, useReducer, useId } from "react"; import { createRoot } from 'react-dom/client'; import cockpit from 'cockpit'; import '../lib/patternfly/patternfly-6-cockpit.scss'; import { Page, PageSection } from "@patternfly/react-core/dist/esm/components/Page/index.js"; import { Bullseye } from "@patternfly/react-core/dist/esm/layouts/Bullseye"; import { Button } from "@patternfly/react-core/dist/esm/components/Button/index.js"; import { Checkbox } from "@patternfly/react-core/dist/esm/components/Checkbox"; import { Split, SplitItem } from "@patternfly/react-core/dist/esm/layouts/Split/index.js"; import { Modal, ModalBody, ModalHeader, ModalFooter } from '@patternfly/react-core/dist/esm/components/Modal'; import { Form, FormGroup } from "@patternfly/react-core/dist/esm/components/Form"; import { DescriptionList, DescriptionListDescription, DescriptionListGroup, DescriptionListTerm } from "@patternfly/react-core/dist/esm/components/DescriptionList/index.js"; import { Spinner } from "@patternfly/react-core/dist/esm/components/Spinner"; import { WithDialogs, useDialogs } from 'dialogs'; import { useDialogState, DialogState, useDialogState_async, DialogError, DialogErrorMessage, DialogField, DialogCheckbox, DialogTextInput, DialogRadioSelect, DialogDropdownSelect, DialogDropdownSelectObject, DialogHelperText, DialogActionButton, DialogCancelButton, } from 'cockpit/dialog'; import { FileChooser, DialogFileChooserInput } from "cockpit/react/FileChooser"; import 'cockpit-dark-theme'; // once per page import 'page.scss'; function List({ label, field, Component, init, } : { label: string field: DialogField, Component: ({ field } : { field: DialogField }) => React.ReactNode, init: T, }) { return ( { field.map((f, i) => ( ))} ); } const StringList = ({ field, label, } : { field: DialogField, label: string }) => { return ( ); }; interface Name { name: string; _length: number; } const NameInput = ({ field, } : { field: DialogField, }) => { return ; }; function validate_Name(field: DialogField, countAsyncValidation: () => void) { field.sub("name").validate_async(async (n, signal) => { await async_sleep(2000); countAsyncValidation(); if (!signal.aborted) field.sub("_length").set(n.length); if (n.length % 2) return "Must have even number of characters"; }); } const NameList = ({ field, label, } : { field: DialogField, label: string }) => { return ( ); }; const OptionalTextInput = ({ field_label, checkbox_label, field, } : { field_label: string, checkbox_label: string; field: DialogField, }) => { const id = useId(); const val = field.get(); let body; if (val === false) { body = ( field.set("")} /> ); } else { body = ( <> field.set(false)} /> ); } return ( {body} ); }; function async_sleep(n: number) { return new Promise(resolve => { window.setTimeout(resolve, n); }); } interface Color { name: string, red: number, green: number, blue: number, } const colors: Color[] = [ { name: "red", red: 1, green: 0, blue: 0 }, { name: "green", red: 0, green: 1, blue: 0 }, { name: "blue", red: 0, green: 0, blue: 1 }, ]; interface ExampleValues { flag: boolean; text: string; text2: string; radio: string; dropdown: string; text3: string; color: Color, list: string[]; async: Name[]; alternative: false | string; error: string; allow_force: boolean; file: string; file_explanation: string; dir: string; } const ExampleDialog = ({ setResult, countAsyncValidation, countAsyncUpdate, countAsyncCancel, } : { setResult: (values: ExampleValues) => void, countAsyncValidation: () => void, countAsyncUpdate: () => void, countAsyncCancel: () => void, }) => { const Dialogs = useDialogs(); const init: ExampleValues = { flag: false, text: "", text2: "", radio: "one", dropdown: "one", text3: "", color: colors[0], list: [], async: [], alternative: false, error: "none", allow_force: false, file: "", file_explanation: "", dir: "", }; function validate(dlg: DialogState) { if (dlg.values.flag) { dlg.field("text").validate(v => { if (!v) return "Text can not be empty"; }); } if (dlg.values.dropdown === "three") { dlg.field("text3").validate(v => { if (!v) return "Can't be empty"; }); } dlg.field("list").forEach(v => { v.validate(vv => { if (vv === "magic") dlg.field("text").set("magic"); if (vv === ".") return "No dots"; }); }); dlg.field("async").forEach(v => validate_Name(v, countAsyncValidation)); dlg.field("file").validate(v => { if (v && v[0] !== "/") return "Must be absolute"; }); } const dlg = useDialogState(init, validate); async function apply(values: ExampleValues, variant: string) { setResult(values); if (variant === "force") return; if (values.error === "custom") { throw new DialogError("This is a failure", 1234-567-98A); } else if (values.error === "from") { const err = new Error("no such file or scraper"); throw DialogError.fromError("Tool not found", err); } else if (values.error === "from-random") { const err = [1, 2, 3, 4]; throw DialogError.fromError("Too random", err); } else if (values.error === "message") { // eslint-disable-next-line no-throw-literal throw { message: "segmentation fault" }; } else if (values.error === "spawn") { await cockpit.spawn(["ls", "--no-such-option"], { err: "message" }); } else if (values.error === "random") { // eslint-disable-next-line no-throw-literal throw [1, 2, 3, 4]; } } function color_changed() { dlg.field("color").get_async(async (val, signal) => { signal.onabort = countAsyncCancel; await async_sleep(2000); if (!signal.aborted) { countAsyncUpdate(); dlg.field("text").set(val.name); } }); } function dropdown_changed(val: string) { dlg.field("text2").set_async(async () => { await async_sleep(2000); return val; }); } function file_changed(val: string) { dlg.field("file_explanation").set_async(async () => { if (val[0] === "/") return cockpit.spawn(["file", "-b", val], { superuser: "try" }); else return "--"; }); } return (
{ // Calling "map" on a non-array should just do nothing. dlg.field("text").map((v, i) => {v.get()}) } { dlg.values.dropdown === "three" && } c.name} /> !n.includes(".") }, ], shortcuts: [ { label: "Test files", path: "/var/lib/cockpittest" } ], collections: [ { label: "Some files", emptyLabel: "Nothing there", list: async () => { return [ "/var/lib/cockpittest/file-chooser-test/dots.txt", "/var/lib/cockpittest/file-chooser-test/foo", ]; } } ] } } />
apply(values, "main")} onClose={Dialogs.close} > Apply apply(values, "force")} ouiaId="apply-force" variant="danger" onClose={Dialogs.close} excuse={dlg.values.allow_force ? undefined : "Force not allowed"} > Apply with force CANCEL!
); }; const ExampleButton = () => { const Dialogs = useDialogs(); const [values, setValues] = useState(null); const [asyncValidationsBase, setAsyncValidationsBase] = useState(0); const [asyncValidations, countAsyncValidation] = useReducer(x => x + 1, 0); const [asyncUpdatesBase, setAsyncUpdatesBase] = useState(0); const [asyncUpdates, countAsyncUpdate] = useReducer(x => x + 1, 0); const [asyncCancelsBase, setAsyncCancelsBase] = useState(0); const [asyncCancels, countAsyncCancel] = useReducer(x => x + 1, 0); function entry(id: string, val: string) { return ( {id} {val} ); } return ( <> { values && { entry("flag", String(values.flag)) } { values.flag && entry("text", values.text) } { entry("text2", values.text2) } { entry("radio", values.radio) } { entry("dropdown", values.dropdown) } { entry("color", values.color.red + "/" + values.color.green + "/" + values.color.blue) } { entry("list", values.list.join("/")) } { entry("async", values.async.map(n => n.name + ":" + String(n._length)).join("/")) } { entry("asyncVals", String(asyncValidations - asyncValidationsBase)) } { entry("asyncUps", String(asyncUpdates - asyncUpdatesBase)) } { entry("asyncCancels", String(asyncCancels - asyncCancelsBase)) } { entry("alternative", JSON.stringify(values.alternative)) } } ); }; interface ExampleWithInitFuncValues { text: string; text2: string; } const ExampleDialogWithInitFunc = () => { const Dialogs = useDialogs(); function init(): ExampleWithInitFuncValues { return { text: "foo", text2: "bar", }; } function validate(dlg: DialogState) { dlg.top().validate(v => { if (v.text === "foo" && v.text2 !== "bar") { return { text: "No foo without bar", }; } if (v.text2 === "bar" && v.text !== "foo") { return { text2: { "": "No bar without foo" }, }; } }); } const dlg = useDialogState(init, validate); return (
{}} onClose={Dialogs.close}> Apply
); }; interface AsyncExampleValues { text: string; } const AsyncExampleDialog = ({ throwError = 0, cancelCallback = null, } : { throwError?: number, cancelCallback?: null | (() => void), }) => { const Dialogs = useDialogs(); async function init(): Promise { if (throwError === 1) throw new Error("can't get the thing"); else if (throwError === 2) throw new DialogError("Getting the thing failed", can't get it); await async_sleep(500); return { text: "", }; } function validate(dlg: DialogState) { dlg.field("text").validate_async(async () => { throw Error("upps"); }); } const dlg = useDialogState_async(init, validate); async function apply() { cockpit.assert(dlg instanceof DialogState); dlg.set_cancel(cancelCallback); await async_sleep(1000); Dialogs.close(); } function top_changed(values: AsyncExampleValues) { console.log("TOP", JSON.stringify(values)); } let body; if (!dlg) { body = ( ); } else if (dlg instanceof DialogError) { body = null; } else if (dlg instanceof DialogState) { const fields = dlg.top(top_changed); body = (
); } return ( { body } Apply ); }; const SimpleExampleButtons = () => { const Dialogs = useDialogs(); const [cancelled, setCancelled] = useState(false); return ( <>
Cancelled: {cancelled ? "yes" : "no"}
); }; const FileChooserButton = () => { const Dialogs = useDialogs(); async function loadFile(path: string) { const data = await cockpit.file(path).read(); if (!data.startsWith("foo")) throw new Error("Does not start with \"foo\""); } return ( ); }; const Demo = () => { return ( ); }; document.addEventListener("DOMContentLoaded", function() { window.debugging = "dialog"; createRoot(document.getElementById('app')!).render(); });