@patternfly/react-core#Checkbox JavaScript Examples

The following examples show how to use @patternfly/react-core#Checkbox. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: requestCertificate.jsx    From cockpit-certificates with GNU Lesser General Public License v2.1 6 votes vote down vote up
SetSigningParametersRow = ({ signingParameters, setSigningParameters }) => {
    return (
        <FormGroup>
            <Checkbox id='set-signing-parameters'
                      isChecked={signingParameters}
                      label={_("Set optional signing request parameters")}
                      onChange={() => setSigningParameters(!signingParameters)} />
        </FormGroup>
    );
}
Example #2
Source File: ImageOutputCheckbox.js    From edge-frontend with Apache License 2.0 5 votes vote down vote up
ImageOutputCheckbox = (props) => {
  const { getState } = useFormApi();
  const { input } = useFieldApi(props);
  const toggleCheckbox = useCallback(
    (checked, event) => {
      input.onChange(
        checked
          ? [...input.value, event.currentTarget.id]
          : input.value.filter((item) => item !== event.currentTarget.id)
      );
    },
    [input.onChange]
  );

  return (
    <FormGroup
      label="Output type"
      isHelperTextBeforeField
      hasNoPaddingTop
      isRequired
      isStack
    >
      {props.options.map(({ value, label }, index) => (
        <Fragment key={index}>
          <Checkbox
            label={label}
            id={value}
            isChecked={input.value.includes(value)}
            onChange={toggleCheckbox}
            isDisabled={value === 'rhel-edge-commit'}
          />
          <TextContent>
            {getState()?.initialValues?.isUpdate &&
            value === 'rhel-edge-installer' ? (
              <WarningInstallerHelperText />
            ) : (
              <HelperText className="pf-u-ml-lg pf-u-pb-sm">
                <HelperTextItem variant="indeterminate">
                  {outputHelperText[value]}
                </HelperTextItem>
              </HelperText>
            )}
          </TextContent>
          {value === 'rhel-edge-installer' && (
            <Fragment>
              <Text component={TextVariants.small}>
                <Text
                  target="_blank"
                  href="https://access.redhat.com/documentation/en-us/red_hat_enterprise_linux/8/html-single/composing_installing_and_managing_rhel_for_edge_images/index#edge-how-to-compose-and-deploy-a-rhel-for-edge-image_introducing-rhel-for-edge-images"
                  component={TextVariants.a}
                  isVisitedLink
                >
                  Learn more about image types.
                  <ExternalLinkAltIcon className="pf-u-ml-sm" />
                </Text>
              </Text>
            </Fragment>
          )}
        </Fragment>
      ))}
    </FormGroup>
  );
}
Example #3
Source File: RegistrationCreds.js    From edge-frontend with Apache License 2.0 5 votes vote down vote up
RegistrationCreds = (props) => {
  const { input, meta } = useFieldApi(props);
  const toggleCheckbox = useCallback(
    (checked, event) => {
      input.onChange(
        checked
          ? [...input.value, event.currentTarget.id]
          : input.value.filter((item) => item !== event.currentTarget.id)
      );
    },
    [input.onChange]
  );

  const { input: passwordInput } = useFieldApi({ name: 'password' });
  const { input: sshKeyInput } = useFieldApi({ name: 'sshKey' });

  return (
    <FormGroup
      label="Select at least one to validate credentials"
      isHelperTextBeforeField
      hasNoPaddingTop
      isRequired
      isStack
    >
      <Checkbox
        label="Password"
        id="password"
        isChecked={input.value.includes('password')}
        onChange={toggleCheckbox}
      />
      {input.value.includes('password') ? (
        <FormGroup
          helperTextInvalid={
            meta.dirty && meta.error['password'] !== undefined
              ? meta.error['password']
              : undefined
          }
        >
          <TextInput type="password" {...passwordInput} />
        </FormGroup>
      ) : null}
      <Checkbox
        label="SSH"
        id="sshKey"
        isChecked={input.value.includes('sshKey')}
        onChange={toggleCheckbox}
      />
      {input.value.includes('sshKey') ? (
        <FormGroup
          helperTextInvalid={
            meta.dirty && meta.error['sshKey'] !== undefined
              ? meta.error['sshKey']
              : undefined
          }
        >
          <TextArea {...sshKeyInput} />
        </FormGroup>
      ) : null}
    </FormGroup>
  );
}
Example #4
Source File: DescriptiveCheckbox.js    From user-preferences-frontend with Apache License 2.0 5 votes vote down vote up
DescriptiveCheckbox = (props) => {
  const {
    label,
    title,
    description,
    isDanger,
    isGlobal,
    checkedWarning,
    input: { onChange, checked, ...input },
  } = useFieldApi({
    ...props,
    type: 'checkbox',
  });
  const formOptions = useFormApi();

  return (
    <Checkbox
      {...input}
      isChecked={checked}
      id={`descriptive-checkbox-${input.name}`}
      onChange={(...props) => {
        if (isGlobal) {
          formOptions.batch(() => {
            formOptions.getRegisteredFields().forEach((field) => {
              if (typeof formOptions.getFieldState(field).value === 'boolean') {
                formOptions.change(field, false);
              }
            });
          });
        } else {
          formOptions.change('unsubscribe.from-all', false);
        }

        onChange(...props);
      }}
      data-type="descriptive-checkbox"
      className="pref-c-descriptive-checkbox"
      label={
        <span
          className={classNames('pref-c-checkbox-label', {
            'pref-c-checkbox-label-error': isDanger || isGlobal,
          })}
        >
          {label || title}
        </span>
      }
      description={
        <div>
          {description && (
            <span className="pref-c-checkbox-description">{description}</span>
          )}
          {checked && checkedWarning && (
            <span className="pref-c-checkbox-warning">
              <ExclamationTriangleIcon /> {checkedWarning}
            </span>
          )}
        </div>
      }
    />
  );
}
Example #5
Source File: classify-failures.js    From ibutsu-server with MIT License 5 votes vote down vote up
render() {
    const {
      columns,
      rows,
      selectedResults,
      includeSkipped,
      filters
    } = this.state;
    const { run_id } = this.props
    const pagination = {
      pageSize: this.state.pageSize,
      page: this.state.page,
      totalItems: this.state.totalItems
    }
    // filters for the metadata
    const resultFilters = [
      <MetaFilter
        key="metafilter"
        // user_properties fields shouldn't be injected here
        fieldOptions={FILTERABLE_RESULT_FIELDS}
        runId={run_id}
        setFilter={this.setFilter}
        customFilters={{'result': filters['result']}}
      />,
    ]
    return (
      <Card className="pf-u-mt-lg">
        <CardHeader>
          <Flex style={{ width: '100%' }}>
            <FlexItem grow={{ default: 'grow' }}>
              <TextContent>
                <Text component="h2" className="pf-c-title pf-m-xl">Test Failures</Text>
              </TextContent>
            </FlexItem>
            <FlexItem>
              <TextContent>
                <Checkbox id="include-skips" label="Include skips, xfails" isChecked={includeSkipped} aria-label="include-skips-checkbox" onChange={this.onSkipCheck}/>
              </TextContent>
            </FlexItem>
            <FlexItem>
              <MultiClassificationDropdown selectedResults={selectedResults} refreshFunc={this.refreshResults}/>
            </FlexItem>
            <FlexItem>
              <Button variant="secondary" onClick={this.refreshResults}>Refresh results</Button>
            </FlexItem>
          </Flex>
        </CardHeader>
        <CardBody>
          <FilterTable
            columns={columns}
            rows={rows}
            pagination={pagination}
            isEmpty={this.state.isEmpty}
            isError={this.state.isError}
            onCollapse={this.onCollapse}
            onSetPage={this.setPage}
            onSetPageSize={this.pageSizeSelect}
            canSelectAll={true}
            onRowSelect={this.onTableRowSelect}
            variant={TableVariant.compact}
            activeFilters={this.state.filters}
            filters={resultFilters}
            onRemoveFilter={this.removeFilter}
            hideFilters={["run_id", "project_id"]}
          />
        </CardBody>
      </Card>
    );
  }
Example #6
Source File: DisableRule.js    From ocp-advisor-frontend with Apache License 2.0 4 votes vote down vote up
DisableRule = ({
  isModalOpen,
  handleModalToggle,
  rule,
  afterFn,
  host,
  hosts,
}) => {
  const intl = useIntl();
  const [justification, setJustificaton] = useState('');
  const [singleHost, setSingleHost] = useState(!!host);
  const [multipleHosts, setMultipleHosts] = useState(hosts.length > 0);
  const [setAck] = useSetAckMutation();
  const dispatch = useDispatch();
  const notify = (data) => dispatch(addNotification(data));

  const bulkHostActions = async () => {
    // disable for a group of hosts (clusters)
    try {
      const requests = hosts.map((h) =>
        disableRuleForCluster({
          uuid: h.id,
          recId: rule.rule_id,
          justification,
        })
      );
      await Promise.all(requests);
      notify({
        variant: 'success',
        dismissable: true,
        timeout: true,
        title: intl.formatMessage(messages.recSuccessfullyDisabledForCluster),
      });
      afterFn && afterFn();
    } catch (error) {
      notify({
        variant: 'danger',
        dismissable: true,
        title: intl.formatMessage(messages.error),
        description: `${error}`,
      });
    }
  };

  const disableRule = async () => {
    try {
      if (singleHost) {
        // disable the rec for this single cluster
        await disableRuleForCluster({
          uuid: host,
          recId: rule.rule_id,
          justification,
        });
        notify({
          variant: 'success',
          timeout: true,
          dismissable: true,
          title: intl.formatMessage(messages.recSuccessfullyDisabledForCluster),
        });
      } else if (multipleHosts) {
        bulkHostActions();
      } else {
        // disable the whole rec
        await setAck({
          rule_id: rule.rule_id,
          justification,
        }).unwrap();
        notify({
          variant: 'success',
          timeout: true,
          dismissable: true,
          title: intl.formatMessage(messages.recSuccessfullyDisabled),
        });
      }
      setJustificaton('');
      afterFn && afterFn();
    } catch (error) {
      notify({
        variant: 'danger',
        dismissable: true,
        title: intl.formatMessage(messages.error),
        description: `${error}`,
      });
    }

    handleModalToggle(false);
  };

  return (
    <Modal
      variant="small"
      title={intl.formatMessage(messages.disableRule)}
      isOpen={isModalOpen}
      onClose={() => {
        handleModalToggle();
        setJustificaton('');
      }}
      actions={[
        <Button
          key="confirm"
          variant="primary"
          onClick={() => disableRule()}
          ouiaId="confirm"
        >
          {intl.formatMessage(messages.save)}
        </Button>,
        <Button
          key="cancel"
          variant="link"
          onClick={() => {
            handleModalToggle(false);
            setJustificaton('');
          }}
          ouiaId="cancel"
        >
          {intl.formatMessage(messages.cancel)}
        </Button>,
      ]}
      ouiaId="recommendation-disable"
    >
      {intl.formatMessage(messages.disableRuleBody)}
      <Form>
        <FormGroup fieldId="blank-form" />
        {(host || hosts.length > 0) && (
          <FormGroup fieldId="disable-rule-one-system">
            <Checkbox
              isChecked={singleHost || multipleHosts}
              onChange={() => {
                host
                  ? setSingleHost(!singleHost)
                  : setMultipleHosts(!multipleHosts);
              }}
              label={
                host
                  ? intl.formatMessage(messages.disableRuleSingleCluster)
                  : intl.formatMessage(messages.disableRuleForClusters)
              }
              id="disable-rule-one-system"
              name="disable-rule-one-system"
              ouiaId="disable-recommendation-one-cluster"
            />
          </FormGroup>
        )}
        <FormGroup
          label={intl.formatMessage(messages.justificationNote)}
          fieldId="disable-rule-justification"
        >
          <TextInput
            type="text"
            id="disable-rule-justification"
            aria-describedby="disable-rule-justification"
            value={justification}
            onChange={(text) => setJustificaton(text)}
            onKeyDown={(e) =>
              e.key === 'Enter' && (e.preventDefault(), disableRule())
            }
          />
        </FormGroup>
      </Form>
    </Modal>
  );
}
Example #7
Source File: certificateActions.jsx    From cockpit-certificates with GNU Lesser General Public License v2.1 4 votes vote down vote up
RemoveModal = ({ onClose, certs, cert, certPath, addAlert, appOnValueChanged, idPrefix }) => {
    const [deleteFiles, setDeleteFiles] = useState(false);

    const onRemoveResponse = () => {
        delete certs[certPath];

        appOnValueChanged("certs, certs");
        onClose();
    };

    const onRemove = () => {
        if (deleteFiles) {
            cockpit.file(cert["key-file"].v, { superuser: "try" }).replace(null) // delete key file
                    .then(() => cockpit.file(cert["cert-file"].v, { superuser: "try" }).replace(null)) // delete cert file
                    .then(() => removeRequest(certPath))
                    // There is no dbus signal for cert removal, so we have to update UI manually
                    .then(() => onRemoveResponse())
                    .catch(error => {
                        addAlert(_("Error: ") + (error.name || error.problem), error.message);
                        onClose();
                    });
        } else {
            removeRequest(certPath)
                    // There is no dbus signal for cert removal, so we have to update UI manually
                    .then(() => onRemoveResponse())
                    .catch(error => {
                        addAlert(_("Error: ") + error.name, error.message);
                        onClose();
                    });
        }
    };

    const title = _("Remove certificate: ") + (cert["cert-storage"].v === "FILE" ? cert.nickname.v : cert["cert-nickname"].v);

    const fileCertBody = (
        <Form isHorizontal>
            <FormGroup label={_("Certificate file")} hasNoPaddingTop>
                <samp id={idPrefix + "cert-file"}>
                    {cert["cert-file"].v}
                </samp>
            </FormGroup>

            <FormGroup label={_("Key file")}>
                <samp id={idPrefix + "key-file"} hasNoPaddingTop>
                    {cert["key-file"].v}
                </samp>
            </FormGroup>
        </Form>
    );

    const nssdbCertBody = (
        <Form isHorizontal>
            <FormGroup label={_("NSSDB path")} hasNoPaddingTop>
                <samp id={idPrefix + "cert-database"}>
                    {cert["cert-database"].v}
                </samp>
            </FormGroup>

            <FormGroup label={_("Nickname")} hasNoPaddingTop>
                <samp id={idPrefix + "cert-nickname"}>
                    {cert["cert-nickname"].v}
                </samp>
            </FormGroup>
        </Form>
    );

    const body = (<>
        { cert["cert-storage"].v === "FILE" ? fileCertBody : nssdbCertBody }
        { cert["key-file"] && cert["cert-file"] && cert["key-file"].v && cert["cert-file"].v && (
            <Checkbox id={idPrefix + "-delete-files"}
                      className="checkbox-delete-files"
                      isChecked={deleteFiles}
                      label={_("Also delete certificate and key files")}
                      onChange={e => setDeleteFiles(!deleteFiles)} />
        )}
    </>);

    return (
        <Modal id={idPrefix + "-remove-dialog"}
               position="top" variant="medium"
               onClose={onClose}
               isOpen
               title={title}
               footer={<>
                   <Button variant="danger" onClick={onRemove}>
                       { deleteFiles ? _("Remove and delete") : _("Remove") }
                   </Button>
                   <Button variant="link" className="btn-cancel" onClick={onClose}>
                       {_("Cancel")}
                   </Button>
               </>}>
            {body}
        </Modal>
    );
}
Example #8
Source File: certificateList.jsx    From cockpit-certificates with GNU Lesser General Public License v2.1 4 votes vote down vote up
generalDetails = ({ idPrefix, cas, cert, certPath, onAutorenewChanged }) => {
    const caName = getCAName(cas, cert);

    return (<Flex justifyContent={{ default: "justifyContentCenter" }}>
        <Flex direction={{ default:"column" }} flex={{ default: 'flex_1' }}>
            <DescriptionList isHorizontal>
                {cert.status && cert.status.v && <DescriptionListGroup>
                    <DescriptionListTerm>{_("Status")}</DescriptionListTerm>
                    <DescriptionListDescription id={`${idPrefix}-general-status`}>
                        {cert.stuck.v && (
                            <Flex alignItems={{ default: 'alignItemsCenter' }} spaceItems={{ default: 'spaceItemsSm' }}>
                                <ExclamationTriangleIcon className="ct-icon-exclamation-triangle" />
                                <span id={`${idPrefix}-general-stuck`}>{_("Stuck: ")}</span>
                            </Flex>
                        )}
                        <Flex alignItems={{ default: 'alignItemsCenter' }} spaceItems={{ default: 'spaceItemsSm' }}>
                            <FlexItem>
                                {cert.status.v.includes('_')
                                    ? cert.status.v
                                    : cert.status.v.charAt(0) + cert.status.v.slice(1).toLowerCase()}
                            </FlexItem>
                            <Tooltip position={TooltipPosition.top}
                                entryDelay={0}
                                content={certificateStates[cert.status.v]}>
                                <span className="info-circle">
                                    <InfoAltIcon />
                                </span>
                            </Tooltip>
                        </Flex>
                    </DescriptionListDescription>
                </DescriptionListGroup>}

                {cert.ca && cert.ca.v && <DescriptionListGroup>
                    <DescriptionListTerm>{_("Certificate authority")}</DescriptionListTerm>
                    <DescriptionListDescription id={`${idPrefix}-general-ca`}>{caName == "SelfSign" ? _("Self-signed") : caName}</DescriptionListDescription>
                </DescriptionListGroup>}

                {cert["not-valid-after"] && cert["not-valid-after"].v !== 0 && <DescriptionListGroup>
                    <DescriptionListTerm>
                        {_("Valid")}
                    </DescriptionListTerm>
                    <DescriptionListDescription id={`${idPrefix}-general-validity`}>
                        {prettyTime(cert["not-valid-before"].v) +
                        _(" to ") + prettyTime(cert["not-valid-after"].v)}
                    </DescriptionListDescription>
                </DescriptionListGroup>}

                {cert.autorenew && <DescriptionListGroup>
                    <DescriptionListTerm>
                        {_("Auto-renewal")}
                    </DescriptionListTerm>
                    <DescriptionListDescription>
                        <Checkbox id={`${idPrefix}-general-autorenewal`}
                                  isChecked={cert.autorenew.v}
                                  label={_("Renew before expiration")}
                                  onChange={() => onAutorenewChanged(cert, certPath)} />
                    </DescriptionListDescription>
                </DescriptionListGroup>}
            </DescriptionList>
        </Flex>
        <Flex direction={{ default:"column" }} flex={{ default: 'flex_1' }}>
            <DescriptionList isHorizontal>
                {cert.subject && cert.subject.v && <DescriptionListGroup>
                    <DescriptionListTerm>
                        {_("Subject name")}
                    </DescriptionListTerm>
                    <DescriptionListDescription>
                        <span id={`${idPrefix}-general-subject`}>{cert.subject.v}</span>
                    </DescriptionListDescription>
                </DescriptionListGroup>}

                {cert.principal && cert.principal.v.length > 0 && <DescriptionListGroup>
                    <DescriptionListTerm>
                        {_("Principal name")}
                    </DescriptionListTerm>
                    <DescriptionListDescription>
                        <span id={`${idPrefix}-general-principal`}>{cert.principal.v.join(", ")}</span>
                    </DescriptionListDescription>
                </DescriptionListGroup>}

                {cert.hostname && cert.hostname.v.length > 0 && <DescriptionListGroup>
                    <DescriptionListTerm>
                        {_("DNS name")}
                    </DescriptionListTerm>
                    <DescriptionListDescription>
                        <span id={`${idPrefix}-general-dns`}>{cert.hostname.v.join(", ")}</span>
                    </DescriptionListDescription>
                </DescriptionListGroup>}
            </DescriptionList>
        </Flex>
    </Flex>);
}
Example #9
Source File: new-widget-wizard.js    From ibutsu-server with MIT License 4 votes vote down vote up
render() {
    const { widgetTypes, selectedType, selectedTypeId, stepIdReached, isTitleValid, areParamsFilled } = this.state;
    const steps = [
      {
        id: 1,
        name: 'Select type',
        enableNext: selectedType,
        component: (
          <Form>
            <Title headingLevel="h1" size="xl">Select a widget type</Title>
            {widgetTypes.map(widgetType => {
              return (
                <div key={widgetType.id}>
                  <Radio id={widgetType.id} value={widgetType.id} label={widgetType.title} description={widgetType.description} isChecked={selectedTypeId === widgetType.id} onChange={this.onSelectType}/>
                </div>
              );
            })}
          </Form>
        )
      },
      {
        id: 2,
        name: 'Set info',
        canJumpTo: stepIdReached >= 2,
        enableNext: isTitleValid,
        component: (
          <Form isHorizontal>
            <Title headingLevel="h1" size="xl">Set widget information</Title>
            <FormGroup label="Title" fieldId="widget-title" helperText="A title for the widget" validated={this.isTitleValid} helperTextInvalid="Please enter a title for this widget" helperTextInvalidIcon={<ExclamationCircleIcon/>} isRequired>
              <TextInput type="text" id="widget-title" name="widget-title" value={this.state.title} onChange={this.onTitleChange} validated={this.state.isTitleValid} isRequired />
            </FormGroup>
            <FormGroup label="Weight" fieldId="widget-weight" helperText="How widgets are ordered on the dashboard">
              <TextInput type="number" id="widget-weight" name="widget-weight" value={this.state.weight} onChange={this.onWeightChange} />
            </FormGroup>
          </Form>
        )
      },
      {
        id: 3,
        name: 'Set parameters',
        canJumpTo: stepIdReached >= 3,
        enableNext: areParamsFilled,
        component: (
          <Form isHorizontal>
            <Title headingLevel="h1" size="xl">Set widget parameters</Title>
            {!!selectedType && selectedType.params.map(param => {
              return (
                <React.Fragment key={param.name}>
                {(param.type === 'string' || param.type === 'integer' || param.type === 'float') &&
                  <FormGroup
                    label={param.name}
                    fieldId={param.name}
                    helperText={<Linkify componentDecorator={linkifyDecorator}>{param.description}</Linkify>}
                    isRequired={param.required}>
                    <TextInput
                      value={this.state.params[param.name]}
                      type={(param.type === 'integer' || param.type === 'float') ? 'number' : 'text'}
                      id={param.name}
                      aria-describedby={`${param.name}-helper`}
                      name={param.name}
                      onChange={this.onParamChange}
                      isRequired={param.required}
                    />
                  </FormGroup>
                }
                {param.type === 'boolean' &&
                  <FormGroup
                    label={param.name}
                    fieldId={param.name}
                    isRequired={param.required}
                    hasNoPaddingTop>
                    <Checkbox
                      isChecked={this.state.params[param.name]}
                      onChange={this.onParamChange}
                      id={param.name}
                      name={param.name}
                      label={param.description} />
                  </FormGroup>
                }
                {param.type === 'list' &&
                  <FormGroup
                    label={param.name}
                    fieldId={param.name}
                    helperText={`${param.description}. Place items on separate lines.`}>
                    isRequired={param.required}
                    <TextArea
                      id={param.name}
                      name={param.name}
                      isRequired={param.required}
                      value={this.state.params[param.name]}
                      onChange={this.onParamChange}
                      resizeOrientation='vertical' />
                  </FormGroup>
                }
                </React.Fragment>
              );
            })}
          </Form>
        )
      },
      {
        id: 4,
        name: 'Review details',
        canJumpTo: stepIdReached >= 4,
        nextButtonText: 'Finish',
        component: (
          <Stack hasGutter>
            <StackItem>
              <Title headingLevel="h1" size="xl">Review details</Title>
            </StackItem>
            <StackItem>
              <Grid hasGutter>
                <GridItem span="2">
                  <Title headingLevel="h4">Title</Title>
                </GridItem>
                <GridItem span="10">
                  <TextContent><Text>{this.state.title}</Text></TextContent>
                </GridItem>
                <GridItem span="2">
                  <Title headingLevel="h4">Weight</Title>
                </GridItem>
                <GridItem span="10">
                  <TextContent><Text>{this.state.weight}</Text></TextContent>
                </GridItem>
                <GridItem span="2">
                  <Title headingLevel="h4">Parameters</Title>
                </GridItem>
                <GridItem span="10">
                  <Table
                    cells={["Name", "Value"]}
                    variant="compact"
                    borders="compactBorderless"
                    rows={Object.entries(this.state.params).map(param => { return [param[0], param[1].toString()]; })}
                    aria-label="Parameters">
                    <TableHeader />
                    <TableBody />
                  </Table>
                </GridItem>
              </Grid>
            </StackItem>
          </Stack>
        )
      }
    ];
    return (
      <Modal
        isOpen={this.props.isOpen}
        variant={ModalVariant.large}
        showClose={false}
        onClose={this.onClose}
        hasNoBodyWrapper
        aria-describedby="add-widget-description"
        aria-labelledby="add-widget-title"
      >
        <Wizard
          titleId="add-widget-title"
          descriptionId="add-widget-description"
          title="Add Widget"
          description="Add a widget to the current dashboard"
          steps={steps}
          onNext={this.onNext}
          onSave={this.onSave}
          onClose={this.onClose}
          height={400}
        />
      </Modal>
    );
  }
Example #10
Source File: test-history.js    From ibutsu-server with MIT License 4 votes vote down vote up
render() {
    const {
      columns,
      rows,
      onlyFailures,
      historySummary,
      dropdownSelection
    } = this.state;
    const pagination = {
      pageSize: this.state.pageSize,
      page: this.state.page,
      totalItems: this.state.totalItems
    }
    const dropdownValues = Object.assign({
      "1 Week": 0.25,
      "2 Weeks": 0.5,
      "1 Month": 1.0,
      "2 Months": 2.0,
      "3 Months": 3.0,
      "5 Months": 5.0
    })
    let dropdownItems = [];
    Object.keys(dropdownValues).forEach(key => {
      dropdownItems.push(
        <DropdownItem key={key} value={dropdownValues[key]} autoFocus={key === dropdownSelection}>
          {key}
        </DropdownItem>
      )
    });

    return (
      <Card className="pf-u-mt-lg">
        <CardHeader>
          <Flex style={{ width: '100%' }}>
            <FlexItem grow={{ default: 'grow' }}>
              <TextContent>
                <Text component="h2" className="pf-c-title pf-m-xl">
                  Test History
                </Text>
              </TextContent>
            </FlexItem>
            <FlexItem>
              <TextContent>
                <Checkbox id="only-failures" label="Only show failures/errors" isChecked={onlyFailures} aria-label="only-failures-checkbox" onChange={this.onFailuresCheck}/>
              </TextContent>
            </FlexItem>
            <FlexItem>
              <Dropdown
                toggle={<DropdownToggle isDisabled={false} onToggle={this.onDropdownToggle}>Time range</DropdownToggle>}
                onSelect={this.onDropdownSelect}
                isOpen={this.state.isDropdownOpen}
                dropdownItems={dropdownItems}
              />
            </FlexItem>
            <FlexItem>
              <Button variant="secondary" onClick={this.refreshResults}>Refresh results</Button>
            </FlexItem>
          </Flex>
        </CardHeader>
        <CardBody>
          <FilterTable
            columns={columns}
            rows={rows}
            pagination={pagination}
            isEmpty={this.state.isEmpty}
            isError={this.state.isError}
            onCollapse={this.onCollapse}
            onSetPage={this.setPage}
            onSetPageSize={this.pageSizeSelect}
            canSelectAll={false}
            variant={TableVariant.compact}
            activeFilters={this.state.filters}
            filters={[
              <Text key="summary" component="h4">
                Summary:&nbsp;
                {historySummary &&
                <RunSummary summary={historySummary}/>
                }
              </Text>,
              <Text key="last-passed" component="h4">Last passed:&nbsp;{this.state.lastPassedDate}</Text>,
            ]}
            onRemoveFilter={this.removeFilter}
            hideFilters={["project_id", "result", "test_id"]}
          />
        </CardBody>
      </Card>
    );
  }
Example #11
Source File: user-edit.js    From ibutsu-server with MIT License 4 votes vote down vote up
render() {
    const { user, projects, userProjects } = this.state;
    return (
      <React.Fragment>
        <PageSection variant={PageSectionVariants.light}>
          <Title headingLevel="h1" size='2xl' className="pf-c-title">
            Users / {user && user.name} {' '}
            {user && user.is_superadmin &&
              <Label className="super-admin-label" variant="outline" color="blue">Administrator</Label>
            }
          </Title>
        </PageSection>
        <PageSection>
          {!user && <Alert variant="info" title="Loading..." />}
          {user &&
          <Card>
            <CardBody>
              <Form>
                <FormGroup label="Name" isRequired fieldId="userName" helperText="The user's name">
                  <TextInput
                    isRequired
                    type="text"
                    id="userName"
                    name="userName"
                    aria-describedby="The user's name"
                    value={user.name}
                    onChange={this.onUserNameChanged}
                  />
                </FormGroup>
                <FormGroup label="E-mail" isRequired fieldId="userEmail" helperText="The user's e-mail address">
                  <TextInput
                    isRequired
                    type="email"
                    id="userEmail"
                    name="userEmail"
                    aria-describedby="The user's e-mail address"
                    value={user.email}
                    onChange={this.onUserEmailChanged}
                  />
                </FormGroup>
                <FormGroup fieldId="userStatus" label="User status">
                  <Checkbox
                    label="Is active"
                    id="userIsActive"
                    name="userIsActive"
                    aria-label="User is active"
                    isChecked={user.is_active}
                    onChange={this.onIsActiveToggle}
                  />
                  <Checkbox
                    label="Is administrator"
                    id="userIsAdmin"
                    name="userIsAdmin"
                    aria-label="User is administrator"
                    isChecked={user.is_superadmin}
                    onChange={this.onIsAdminToggle}
                  />
                </FormGroup>
                <FormGroup fieldId="userProjects" label="Projects" helperText="The projects to which a user has access">
                   <Select
                     variant={SelectVariant.typeaheadMulti}
                     typeAheadAriaLabel="Select one or more projects"
                     onToggle={this.onProjectsToggle}
                     onSelect={this.onProjectsSelect}
                     onClear={this.onProjectsClear}
                     selections={userProjects}
                     isOpen={this.state.isProjectsOpen}
                     aria-labelledby="userProjects"
                     placeholderText="Select one or more projects"
                   >
                     {projects.map(project => (
                       <SelectOption key={project.id} value={projectToOption(project)} description={project.name} />
                     ))}
                   </Select>
                </FormGroup>
                <ActionGroup>
                  <Button variant="primary" onClick={this.onSubmitClick}>Submit</Button>
                  <Button variant="secondary" onClick={this.props.history.goBack}>Cancel</Button>
                </ActionGroup>
              </Form>
            </CardBody>
          </Card>
          }
        </PageSection>
      </React.Fragment>
    );
  }
Example #12
Source File: BondForm.js    From cockpit-wicked with GNU General Public License v2.0 4 votes vote down vote up
BondForm = ({ isOpen, onClose, connection }) => {
    const { bond } = connection || {};
    const isEditing = !!connection;
    const [name, setName] = useState(connection?.name || "");
    const [mode, setMode] = useState(bond?.mode || bondingModes.ACTIVE_BACKUP);
    const [options, setOptions] = useState(bond?.options || "miimon=100");
    const [selectedInterfaces, setSelectedInterfaces] = useState(bond?.interfaces || []);
    const [candidateInterfaces, setCandidateInterfaces] = useState([]);
    const { interfaces } = useNetworkState();
    const dispatch = useNetworkDispatch();

    useEffect(() => {
        if (isEditing) {
            setCandidateInterfaces(Object.values(interfaces).filter(i => i.name !== connection.name));
        } else {
            setCandidateInterfaces(Object.values(interfaces));
        }
    }, [connection, isEditing, interfaces]);

    const addOrUpdateConnection = () => {
        const bondingAttrs = {
            name,
            bond: {
                mode,
                interfaces: selectedInterfaces,
                options
            }
        };

        if (isEditing) {
            updateConnection(dispatch, connection, bondingAttrs);
        } else {
            addConnection(dispatch, { ...bondingAttrs, type: interfaceType.BONDING });
        }
        onClose();
    };

    const handleSelectedInterfaces = (name) => (value) => {
        if (value) {
            setSelectedInterfaces([...selectedInterfaces, name]);
        } else {
            setSelectedInterfaces(selectedInterfaces.filter(i => i !== name));
        }
    };

    const isIncomplete = () => {
        return (name === "" || selectedInterfaces.length === 0);
    };

    return (
        <ModalForm
            caption={connection?.name}
            title={isEditing ? _("Edit Bond") : _("Add Bond")}
            isOpen={isOpen}
            onCancel={onClose}
            onSubmit={addOrUpdateConnection}
            onSubmitDisable={isIncomplete()}
            onSubmitLabel={isEditing ? _("Change") : _("Add")}
        >
            <FormGroup
                label={_("Name")}
                isRequired
                fieldId="interface-name"
                helperText={_("Please, provide the interface name (e.g., bond0)")}
            >
                <TextInput
                    isRequired
                    isDisabled={isEditing}
                    id="interface-name"
                    value={name}
                    onChange={setName}
                />
            </FormGroup>

            <FormGroup
                label={_("Interfaces")}
                isRequired
            >
                {candidateInterfaces.map(({ name }) => (
                    <Checkbox
                        label={name}
                        key={name}
                        isChecked={selectedInterfaces.includes(name)}
                        onChange={handleSelectedInterfaces(name)}
                    />
                ))}
            </FormGroup>

            <FormGroup
                label={_("Mode")}
                isRequired
                fieldId="bonding-mode"
            >
                <FormSelect value={mode} onChange={setMode} id="bonding-mode">
                    {modeOptions.map((option, index) => (
                        <FormSelectOption key={index} {...option} />
                    ))}
                </FormSelect>
            </FormGroup>

            <FormGroup
                label={_("Options")}
                fieldId="bond-options"
                helperText={_("Use this field to provide more options using the key=value format")}
            >
                <TextInput
                    isRequired
                    id="bond-options"
                    value={options}
                    onChange={setOptions}
                />
            </FormGroup>
        </ModalForm>
    );
}
Example #13
Source File: BridgeForm.js    From cockpit-wicked with GNU General Public License v2.0 4 votes vote down vote up
BridgeForm = ({ isOpen, onClose, connection }) => {
    const { bridge } = connection || {};
    const isEditing = !!connection;
    const [name, setName] = useState(connection?.name || "");
    const [selectedPorts, setSelectedPorts] = useState(bridge?.ports || []);
    const [candidatePorts, setCandidatePorts] = useState([]);
    const { interfaces } = useNetworkState();
    const dispatch = useNetworkDispatch();

    useEffect(() => {
        if (isEditing) {
            setCandidatePorts(Object.values(interfaces).filter(i => i.name !== connection.name));
        } else {
            setCandidatePorts(Object.values(interfaces));
        }
    }, [connection, isEditing, interfaces]);

    const addOrUpdateConnection = () => {
        if (isEditing) {
            updateConnection(
                dispatch, connection, { name, bridge: { ports: selectedPorts } }
            );
        } else {
            addConnection(
                dispatch, { name, type: interfaceType.BRIDGE, bridge: { ports: selectedPorts, } }
            );
        }
        onClose();
    };

    const handleSelectedPorts = (name) => (value) => {
        if (value) {
            setSelectedPorts([...selectedPorts, name]);
        } else {
            setSelectedPorts(selectedPorts.filter(i => i !== name));
        }
    };

    const isIncomplete = () => {
        return (name === "" || selectedPorts.length === 0);
    };

    return (
        <ModalForm
            caption={connection?.name}
            title={isEditing ? _("Edit Bridge") : _("Add Bridge")}
            isOpen={isOpen}
            onCancel={onClose}
            onSubmit={addOrUpdateConnection}
            onSubmitLabel={isEditing ? _("Change") : _("Add")}
            onSubmitDisable={isIncomplete()}
        >
            <FormGroup
                label={_("Name")}
                isRequired
                fieldId="interface-name"
                helperText={_("Please, provide the interface name (e.g., br0)")}
            >
                <TextInput
                    isRequired
                    isDisabled={isEditing}
                    id="interface-name"
                    value={name}
                    onChange={setName}
                />
            </FormGroup>

            <FormGroup
                label={_("Ports")}
                isRequired
            >
                {candidatePorts.map(({ name }) => (
                    <Checkbox
                        label={name}
                        key={name}
                        isChecked={selectedPorts.includes(name)}
                        onChange={handleSelectedPorts(name)}
                    />
                ))}
            </FormGroup>
        </ModalForm>
    );
}
Example #14
Source File: RouteForm.js    From cockpit-wicked with GNU General Public License v2.0 4 votes vote down vote up
RouteForm = ({ isOpen, onClose, route }) => {
    const isEditing = !!route;
    const [isDefault, setIsDefault] = useState(route?.isDefault || false);
    const [gateway, setGateway] = useState(route?.gateway || "");
    const [destination, setDestination] = useState(route?.destination || "");
    const [device, setDevice] = useState(route?.device || "");
    const [options, setOptions] = useState(route?.options || "");
    const [errors, setErrors] = useState([]);
    const { interfaces, routes } = useNetworkState();
    const [candidateInterfaces, setCandidateInterfaces] = useState([]);
    const dispatch = useNetworkDispatch();

    useEffect(() => {
        setCandidateInterfaces([{ name: "" }, ...Object.values(interfaces)]);
    }, [interfaces]);

    /**
     * Performs the form validations
     *
     * To be considered a valid form both, destination and gateway must be valid IPs values. There
     * is only an exception for destination, which can be "default" too.
     *
     * @return {boolean} true when route is valid; false otherwise
     */
    const validate = () => {
        const errors = [];

        if (!isDefault && !isValidIP(destination)) {
            errors.push({
                key: 'invalid-destination',
                message: _("Destination is not valid.")
            });
        }

        if (!isValidIP(gateway)) {
            errors.push({
                key: 'invalid-gateway',
                message: _("Gateway is not valid.")
            });
        }

        setErrors(errors);

        return errors.length === 0;
    };

    const addOrUpdateRoute = () => {
        if (!validate()) return;

        if (isEditing) {
            updateRoute(dispatch, routes, route.id, buildRouteData());
        } else {
            addRoute(dispatch, routes, buildRouteData());
        }

        onClose();
    };

    const buildRouteData = () => {
        return {
            isDefault,
            destination: isDefault ? "default" : destination,
            gateway,
            device,
            options
        };
    };

    const isIncomplete = () => {
        if (!isDefault && destination.length == 0) return true;
        if (gateway.length == 0) return true;

        return false;
    };

    /**
     * Renders error messages in an Patternfly/Alert component, if any
     */
    const renderErrors = () => {
        if (errors.length === 0) return null;

        return (
            <Alert
              isInline
              variant="danger"
              aria-live="polite"
              title={_("Route is not valid, please check it.")}
            >
                {errors.map(({ key, message }) => <p key={key}>{message}</p>)}
            </Alert>
        );
    };

    /**
     * Renders the destination input only when needed (i.e., route is not marked as a default)
     */
    const renderDestination = () => {
        if (isDefault) return null;

        return (
            <FormGroup
                isRequired
                label={_("Destination")}
                fieldId="destination"
                helperText={_("Destination")}
            >
                <TextInput
                    isRequired
                    id="destination"
                    value={destination}
                    onChange={setDestination}
                />
            </FormGroup>
        );
    };

    return (
        <ModalForm
            title={isEditing ? _("Edit Route") : _("Add Route")}
            isOpen={isOpen}
            onCancel={onClose}
            onSubmit={addOrUpdateRoute}
            onSubmitLabel={isEditing ? _("Change") : _("Add")}
            onSubmitDisable={isIncomplete()}
        >
            {renderErrors()}

            <FormGroup
                label={_("Default route")}
                fieldId="isDefault"
            >
                <Checkbox
                    id="isDefault"
                    isChecked={isDefault}
                    onChange={setIsDefault}
                />
            </FormGroup>

            {renderDestination()}

            <FormGroup
                isRequired
                label={_("Gateway")}
                fieldId="gateway"
            >
                <TextInput
                    isRequired
                    id="gateway"
                    value={gateway}
                    onChange={setGateway}
                />
            </FormGroup>

            <FormGroup
                label={_("Device")}
                fieldId="device"
            >
                <FormSelect value={device} onChange={setDevice} id="device">
                    {candidateInterfaces.map(({ name }, index) => (
                        <FormSelectOption key={index} value={name} label={name} />
                    ))}
                </FormSelect>
            </FormGroup>

            <FormGroup
                label={_("Options")}
                fieldId="options"
            >
                <TextInput
                    id="options"
                    value={options}
                    onChange={setOptions}
                />
            </FormGroup>
        </ModalForm>
    );
}