/*
* Copyright (C) 2018 Red Hat, Inc.
* SPDX-License-Identifier: LGPL-2.1-or-later
*/
/* STORAGE DIALOGS
To show a modal dialog, make a call like this:
dialog_show({ Title: _("What is your name?"),
Fields: [
TextInput("name", _("Name"),
{ validate: val => (val == ""? _("Name can't be empty") : null) })
]
Action: {
Title: _("Ok"),
action: vals => { console.log("Hello, " + vals.name + "!"); }
}
});
The call to dialog_show will open the dialog and return
immediately. Later, when the user clicks on "Ok", the "action"
function will be called with the values of the dialog fields. The
action function usually returns a promise, although it does not in
the example above. When that promise resolves, the dialog is
closed. When the promise is rejected, it's error is displayed in
the dialog, and the dialog stays open.
Fields are described by calling functions such as TextInput. A
number of generic ones are defined here, and you can define more
specialized ones yourself.
They are all called like this:
FieldFunction(tag, title, { option: value, ... })
The "tag" is used to uniquely identify this field in the dialog.
The action function will receive the values of all fields in an
object, and the tag of a field is the key in that object, for
example. The tag is also used to interact with a field from tests.
ACTION FUNCTIONS
The action function is called like this:
action(values, progress_callback)
The "values" parameter contains the validated values of the dialog
fields and the "progress_callback" can be called by the action function
to update the progress information in the dialog while it runs.
The progress callback should be called like this:
progress_callback(message, cancel_callback)
The "message" will be displayed in the dialog and if "cancel_callback" is
not null, the Cancel button in the dialog will be enabled and
"cancel_callback" will be called when the user clicks it.
The return value of the action function is normally a promise. When
it is resolved, the dialog is closed. When it is rejected the value
given in the rejection is displayed as an error in the dialog.
If the error value is a string, it is displayed as a global failure
message. When it is an object, it contains errors for individual
fields in this form:
{ tag1: message, tag2: message }
As a special case, when "message" is "true", the field is rendered
as having an error (with a red outline, say), but without any
directly associated text. The idea is that a group of fields is in
error, and the error message for all of them is shown below the last
one in the group.
COMMON FIELD OPTIONS
Each field function describes its options. However, there are some
options that apply to all fields:
- value
The initial value of the field.
- visible: vals -> boolean
This function determines whether the field is shown or not.
- validate: (val, vals) -> null-or-error-string (or promise)
The validate function receives the current value of the field and
should return "null" (or something falsey) when that value is
acceptable. Otherwise, it should return a suitable error message.
The second argument has all values of all fields, in case you need
to look at more than one field.
It is permissible to overwrite fields of "vals" to change the final
value of a field.
The validate function can also return a promise which resolves to
null or an error message. If that promise is rejected, that error
is shown globally in the dialog as if the action function had
failed.
The validate function will only be called for currently visible
fields.
- widest_title
This is a hack to force the column of titles to be a certain
minimum width, namely the width of the widest_title. This matters
when there are rows that are only sometimes visible and the layout
would jump around when they change visibility.
Technically, the first column of a row shows the "title" but is as
wide as its "widest_title". The idea is that you put the widest
title of all fields in the widest_title option of one of the rows
that are always visible.
- explanation
A test to show below the field, as an explanation.
RUNNING TASKS AND DYNAMIC UPDATES
The dialog_show function returns an object that can be used to interact
with the dialog in various ways while it is open.
dlg = dialog_show(...)
One can run asynchronous tasks:
dlg.run("title", promise)
This will disable the footer buttons and wait for promise to be resolved
or rejected while showing "title" and a spinner.
One can set field values and options:
dlg.set_values({ tag1: value1, tag2: value2, ... })
dlg.set_options(tag, { opt1: value1, opt2: value2, ... })
It is also possible to specify a "update" function when creating the dialog:
dialog_show({ ...
update: function (dlg, vals, trigger) { }
... })
This function is called whenever the values of fields are changed. The
"trigger" argument is the tag of the field that has just been changed.
DEFINING NEW FIELD TYPES
To define a new field type, just define a new function that follows
a few rules. Here is TextInput:
export const TextInput = (tag, title, options) => {
return {
tag: tag,
title: title,
options: options,
initial_value: "",
render: (val, change) =>
change(event.target.value)}/>
}
}
As you can see, a field function should return an object with a
couple of fields. The "tag", "title", and "options" field just
store the parameters to the field function. The rest are these:
- initial_value
This is the initial value of the field.
- render: (val, change) -> React components
This should render the value part of the field, that is, the second
column in the table layout. The title is in the first column and
is rendered by the generic dialog machinery.
The "val" parameter is the current value and you should make sure
that the DOM element really shows that value, and not something
that might have left behind by previous user interactions.
The "change" parameter is a function that should be called with a
new value for the field whenever the user has interacted with it.
For the benefits of the integration tests, the DOM elements should
also contain "data-field" and maybe a "data-field-type" attributes. The
"data-field" value should be that tag of the field, and
"data-field-type" type is used by the tests to know how to interact
with the field. If you find to need it, just pick a reasonable value
and extend the test suite to handle it.
This function is not called at all for invisible fields.
*/
import cockpit from "cockpit";
import React, { useState } from "react";
import { Alert } from "@patternfly/react-core/dist/esm/components/Alert/index.js";
import { FormSelect, FormSelectOption } from "@patternfly/react-core/dist/esm/components/FormSelect/index.js";
import { Button } from "@patternfly/react-core/dist/esm/components/Button/index.js";
import { Checkbox } from "@patternfly/react-core/dist/esm/components/Checkbox/index.js";
import { DataList, DataListCell, DataListCheck, DataListItem, DataListItemCells, DataListItemRow } from "@patternfly/react-core/dist/esm/components/DataList/index.js";
import { Form, FormGroup } from "@patternfly/react-core/dist/esm/components/Form/index.js";
import { Grid, GridItem } from "@patternfly/react-core/dist/esm/layouts/Grid/index.js";
import { Radio } from "@patternfly/react-core/dist/esm/components/Radio/index.js";
import { Slider } from "@patternfly/react-core/dist/esm/components/Slider/index.js";
import { Spinner } from "@patternfly/react-core/dist/esm/components/Spinner/index.js";
import { Split } from "@patternfly/react-core/dist/esm/layouts/Split/index.js";
import { TextInput as TextInputPF4 } from "@patternfly/react-core/dist/esm/components/TextInput/index.js";
import { Popover } from "@patternfly/react-core/dist/esm/components/Popover/index.js";
import { HelperText, HelperTextItem } from "@patternfly/react-core/dist/esm/components/HelperText/index.js";
import { List, ListItem } from "@patternfly/react-core/dist/esm/components/List/index.js";
import { ExclamationTriangleIcon, InfoIcon, HelpIcon, EyeIcon, EyeSlashIcon } from "@patternfly/react-icons";
import { InputGroup } from "@patternfly/react-core/dist/esm/components/InputGroup/index.js";
import { Table, Tbody, Tr, Td } from '@patternfly/react-table';
import { TypeaheadSelect } from "cockpit-components-typeahead-select";
import { show_modal_dialog, apply_modal_dialog } from "cockpit-components-dialog.jsx";
import { ListingTable } from "cockpit-components-table.jsx";
import { FormHelper } from "cockpit-components-form-helper";
import {
decode_filename, fmt_size, block_name, format_size_and_text, format_delay, for_each_async, get_byte_units,
BTRFS_TOOL_MOUNT_PATH
} from "./utils.js";
import { fmt_to_fragments } from "utils.jsx";
import client from "./client.js";
import fsys_is_empty_sh from "./fsys-is-empty.sh";
const _ = cockpit.gettext;
function make_rows(fields, values, errors, onChange) {
return fields.map((f, i) => )
.filter(r => r);
}
function is_visible(field, values) {
return !field.options || field.options.visible == undefined || field.options.visible(values);
}
const Field = ({ field, values, errors, onChange }) => {
const { tag, options } = field;
if (!is_visible(field, values))
return null;
const error = errors && errors[tag];
const explanation = options && options.explanation;
const validated = (tag && errors && errors[tag]) ? 'error' : 'default';
function change(val) {
values[tag] = val;
onChange(tag);
}
return (
<>
{field.render(values[tag], change, validated, error)}
>);
};
const Row = ({ field, values, errors, onChange }) => {
const { title, options } = field;
if (!is_visible(field, values))
return null;
const field_elts = ;
let nested_elts = [];
if (options && options.nested_fields) {
if (field.is_group)
nested_elts = options.nested_fields.map(f => );
else
nested_elts = make_rows(options.nested_fields, values, errors, onChange);
}
if (title || title == "") {
let titleLabel = title;
if (options.widest_title)
titleLabel = (
<>
{options.widest_title}
{title}
>
);
return (
{ field_elts }
{ nested_elts }
);
} else if (!field.bare) {
return (
{ field_elts }
{ nested_elts }
);
} else
return field_elts;
};
const Body = ({ body, teardown, fields, values, errors, isFormHorizontal, onChange }) => {
let error_alert = null;
if (errors && errors.toString() != "[object Object]") {
// This is a global error from a failed action
error_alert = ;
errors = null;
}
return (
<>
{ error_alert }
{ body || null }
{ fields.length > 0
?
: null }
{ teardown }
>
);
};
const ExtraConfirmation = ({ text, onChange }) => {
const [confirmed, setConfirmed] = useState(false);
return (
{
setConfirmed(val);
onChange(val);
}} />);
};
function flatten_fields(fields) {
return fields.reduce(
(acc, val) => acc.concat([val]).concat(val.options && val.options.nested_fields
? flatten_fields(val.options.nested_fields)
: []),
[]);
}
export const dialog_open = (def) => {
const nested_fields = def.Fields || [];
const fields = flatten_fields(nested_fields);
const values = { };
let confirmation = null;
let confirmed = false;
let errors = null;
fields.forEach(f => { values[f.tag] = f.initial_value });
// We reconstruct the body every time the values change so that it
// will be re-rendered. This could be done with some state in the
// Body component maybe, but we also want the values up here so
// that we can pass them to validate and the action function.
const update = () => {
dlg.setProps(props());
};
const props = () => {
return {
id: "dialog",
title: def.Title,
titleIconVariant: (def.Action && (def.Action.Danger || def.Action.DangerButton)) ? "warning" : null,
body: {
errors = null;
if (def.update)
def.update(self, values, trigger);
update();
}} />
};
};
const update_footer = (running_title, running_promise) => {
dlg.setFooterProps(footer_props(running_title, running_promise));
};
function run_action(progress_callback, variant) {
const func = () => {
return validate(variant)
.then(validated_values => {
const visible_values = { variant };
fields.forEach(f => {
if (is_visible(f, values))
visible_values[f.tag] = validated_values[f.tag];
});
if (def.Action.wrapper)
return def.Action.wrapper(visible_values, progress_callback,
def.Action.action);
else
return def.Action.action(visible_values, progress_callback);
})
.catch(errs => {
if (errs && errs.toString() != "[object Object]") {
// Log errors from failed actions, for debugging and
// to allow the test suite to catch known issues.
console.warn(errs.toString());
}
errors = errs;
update();
update_footer();
return Promise.reject();
});
};
return client.run(func);
}
const footer_props = (running_title, running_promise) => {
const actions = [];
function add_action(variant) {
actions.push({
caption: variant.Title,
style: actions.length == 0 ? "primary" : "secondary",
danger: def.Action.Danger || def.Action.DangerButton,
disabled: (running_promise != null ||
(def.Action.disable_on_error &&
errors && errors.toString() != "[object Object]") ||
(confirmation && !confirmed)),
clicked: progress_callback => run_action(progress_callback, variant.tag),
});
}
if (def.Action) {
if (def.Action.Title) {
add_action({
Title: def.Action.Title,
tag: null,
});
}
if (def.Action.Variants) {
for (const v of def.Action.Variants) {
add_action(v);
}
}
}
let extra = null;
if (confirmation) {
extra = {
confirmed = val;
update_footer();
}} />;
} else if (def.Action && def.Action.Danger) {
extra = (
{def.Action.Danger}
);
}
return {
idle_message: (running_promise
? <>
{running_title}
>
: null),
extra_element: extra,
actions,
cancel_button: def.Action ? {} : { text: _("Close"), variant: "secondary" }
};
};
const validate = (variant) => {
// The validation functions sometimes change the dialog values
// for the benefit of the action functions. For example, a
// SizeSlider will convert from "text plus unit" to a numeric
// value during validation.
//
// However, if the action fails, we don't want the values in
// the dialog to change. The SizeSlider would convert back
// from a numeric value to "text plus unit", for example, and
// that conversion might change what the user had type.
//
// So we make a copy of the dialog state and let the validate
// and action functions work with that.
//
const validated_values = { ...values };
return Promise.all(fields.map(f => {
if (is_visible(f, values) && f.options && f.options.validate)
return f.options.validate(validated_values[f.tag], validated_values, variant);
else
return null;
})).then(results => {
const errors = { };
let scrolled = false;
fields.forEach((f, i) => {
if (results[i]) {
if (!scrolled) {
show_field(f.tag);
scrolled = true;
}
errors[f.tag] = results[i];
}
});
if (Object.keys(errors).length > 0)
return Promise.reject(errors);
return validated_values;
});
};
const dlg = show_modal_dialog(props(), footer_props(null, null));
function show_field(tag) {
function scroll() {
const field_element = document.querySelector('#dialog [data-field="' + tag + '"]');
if (field_element)
field_element.scrollIntoView({ behavior: "smooth", block: "nearest" });
}
// By the time show_field is called from the "update"
// callback, newly visible fields don't exist yet in the
// DOM, so delay the scrolling a bit.
window.setTimeout(scroll, 10);
}
const self = {
run: (title, promise) => {
update_footer(title, promise);
promise.then(
() => {
update_footer(null, null);
},
(errs) => {
if (errs) {
errors = errs;
update();
}
update_footer(null, null);
});
},
set_values: (new_vals) => {
Object.assign(values, new_vals);
update();
},
get_value: (tag) => {
return values[tag];
},
update_actions: (new_actions) => {
Object.assign(def.Action, new_actions);
update_footer(null, null);
},
set_nested_values: (key, new_vals) => {
const updated = values[key];
Object.assign(updated, new_vals);
values[key] = updated;
update();
},
get_options: (tag) => {
for (const f of fields) {
if (f.tag == tag) {
return f.options;
}
}
},
set_options: (tag, new_options) => {
fields.forEach(f => {
if (f.tag == tag) {
Object.assign(f.options, new_options);
update();
}
});
},
set_attribute: (name, value) => {
def[name] = value;
update();
},
add_danger: (danger) => {
def.Action.Danger = <>{def.Action.Danger} {danger}>;
update();
},
need_confirmation: (conf) => {
confirmation = conf;
confirmed = false;
def.Action.Danger = null;
def.Action.DangerButton = true;
update_footer();
},
show_field,
close: () => {
dlg.footerProps.dialog_done();
}
};
for_each_async(def.Inits || [],
init => {
if (init) {
const promise = init.func(self);
self.run(init.title, promise);
return promise;
} else
return Promise.resolve();
});
return self;
};
/* GENERIC FIELD TYPES
*/
export const TextInput = (tag, title, options) => {
return {
tag,
title,
options,
initial_value: options.value || "",
render: (val, change, validated) =>
change(value)} />
};
};
const PassInputElement = ({ tag, title, options, val, change, validated }) => {
const [show, setShow] = useState(false);
return (
change(value)} />
);
};
export const PassInput = (tag, title, options) => {
return {
tag,
title,
options,
initial_value: options.value || "",
render: (val, change, validated) =>
};
};
const TypeAheadSelectElement = ({ value, options, change }) => {
return (
cockpit.format(_("Use $0"), val)}
selected={value}
onSelect={(_, value) => change(value)}
onClearSelection={() => change("")}
isDisabled={options.disabled}
selectOptions={options.choices.map(entry => ({ value: entry, content: entry }))} />
);
};
export const ComboBox = (tag, title, options) => {
return {
tag,
title,
options,
initial_value: options.value || "",
render: (val, change, validated) => {
return (