@patternfly/react-core#ModalVariant JavaScript Examples

The following examples show how to use @patternfly/react-core#ModalVariant. 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: delete-modal.js    From ibutsu-server with MIT License 6 votes vote down vote up
render () {
    return (
      <Modal
        variant={ModalVariant.small}
        title={this.props.title}
        isOpen={this.props.isOpen}
        onClose={this.onClose}
        actions={[
          <Button key="delete" variant="danger" onClick={this.onDelete}>Delete</Button>,
          <Button key="cancel" variant="link" onClick={this.onClose}>Cancel</Button>
        ]}
      >
      <Text>{this.props.body}</Text>
      </Modal>
    );
  }
Example #2
Source File: new-dashboard-modal.js    From ibutsu-server with MIT License 6 votes vote down vote up
render () {
    return (
      <Modal
        variant={ModalVariant.small}
        title="New Dashboard"
        isOpen={this.props.isOpen}
        onClose={this.onClose}
        actions={[
          <Button key="save" variant="primary" onClick={this.onSave}>Save</Button>,
          <Button key="cancel" variant="link" onClick={this.onClose}>Cancel</Button>
        ]}
      >
        <Form>
          <FormGroup label="Title" fieldId="dashboard-title" helperTextInvalid="A dashboard title is required" helperTextInvalidIcon={<ExclamationCircleIcon />} validated={this.state.isTitleValid} isRequired>

            <TextInput type="text" id="dashboard-title" name="dashboard-title" value={this.state.title} onChange={this.onTitleChange} validated={this.state.isTitleValid} isRequired />
          </FormGroup>
          <FormGroup label="Description" fieldId="dashboard-description">
            <TextInput type="text" id="dashboard-description" name="dashboard-description" value={this.state.description} onChange={this.onDescriptionChange} />
          </FormGroup>
        </Form>
      </Modal>
    );
  }
Example #3
Source File: CreateActivationKeyModal.js    From sed-frontend with Apache License 2.0 5 votes vote down vote up
CreateActivationKeyModal = (props) => {
  const queryClient = useQueryClient();
  const [created, setCreated] = React.useState(false);
  const [error, setError] = React.useState(false);
  const { handleModalToggle, isOpen } = props;
  const { mutate, isLoading } = useCreateActivationKey();
  const submitForm = (name, role, serviceLevel, usage) => {
    mutate(
      { name, role, serviceLevel, usage },
      {
        onSuccess: () => {
          setError(false);
          setCreated(true);
          queryClient.invalidateQueries('activation_keys');
        },
        onError: () => {
          setError(true);
          setCreated(false);
        },
      }
    );
  };
  return (
    <Modal
      variant={ModalVariant.large}
      title="Create new activation key"
      description=""
      isOpen={isOpen}
      onClose={handleModalToggle}
    >
      {isLoading ? (
        <Loading />
      ) : (
        <ActivationKeyForm
          handleModalToggle={handleModalToggle}
          submitForm={submitForm}
          isSuccess={created}
          isError={error}
        />
      )}
    </Modal>
  );
}
Example #4
Source File: DeleteActivationKeyConfirmationModal.js    From sed-frontend with Apache License 2.0 5 votes vote down vote up
DeleteActivationKeyConfirmationModal = (props) => {
  const { isOpen, handleModalToggle, name } = props;
  const { addSuccessNotification, addErrorNotification } = useNotifications();
  const { mutate, isLoading } = useDeleteActivationKey();
  const queryClient = useQueryClient();

  const deleteActivationKey = (name) => {
    mutate(name, {
      onSuccess: (_data, name) => {
        queryClient.setQueryData('activation_keys', (oldData) =>
          oldData.filter((entry) => entry.name != name)
        );
        addSuccessNotification(`Activation Key ${name} deleted`);
        handleModalToggle();
      },
      onError: () => {
        addErrorNotification('Something went wrong. Please try again');
        handleModalToggle();
      },
    });
    mutate;
  };
  const actions = [
    <Button
      key="confirm"
      variant="danger"
      onClick={() => deleteActivationKey(name)}
      data-testid="delete-activation-key-confirmation-modal-confirm-button"
    >
      Delete
    </Button>,
    <Button key="cancel" variant="link" onClick={handleModalToggle}>
      Cancel
    </Button>,
  ];

  const title = (
    <>
      <TextContent>
        <Text component={TextVariants.h2}>
          <ExclamationTriangleIcon size="md" color="#F0AB00" /> Delete
          Activation Key?
        </Text>
      </TextContent>
    </>
  );
  const content = () => {
    if (isLoading) {
      return <Loading />;
    } else {
      return (
        <TextContent>
          <Text component={TextVariants.p}>
            <b>{name}</b> will no longer be available for use. This operation
            cannot be undone.
          </Text>
        </TextContent>
      );
    }
  };

  return (
    <Modal
      title={title}
      isOpen={isOpen}
      onClose={handleModalToggle}
      variant={ModalVariant.small}
      actions={actions}
    >
      {content()}
    </Modal>
  );
}
Example #5
Source File: EditActivationKeyModal.js    From sed-frontend with Apache License 2.0 5 votes vote down vote up
EditActivationKeyModal = (props) => {
  const { activationKeyName } = props;
  const queryClient = useQueryClient();
  const [updated, setUpdated] = React.useState(false);
  const [error, setError] = React.useState(false);
  const { handleModalToggle, isOpen } = props;
  const { mutate, isLoading } = useUpdateActivationKey();
  const {
    isLoading: isKeyLoading,
    error: keyError,
    data: activationKey,
  } = useActivationKey(activationKeyName);
  const submitForm = (name, role, serviceLevel, usage) => {
    mutate(
      { activationKeyName, role, serviceLevel, usage },
      {
        onSuccess: () => {
          setError(false);
          setUpdated(true);
          queryClient.invalidateQueries('activation_keys');
          queryClient.resetQueries(`activation_key_${activationKeyName}`);
        },
        onError: () => {
          setError(true);
          setUpdated(false);
        },
      }
    );
  };
  return (
    <Modal
      variant={ModalVariant.large}
      title="Edit activation key"
      description=""
      isOpen={isOpen}
      onClose={handleModalToggle}
    >
      {(isLoading || isKeyLoading) && !keyError ? (
        <Loading />
      ) : (
        <ActivationKeyForm
          activationKey={activationKey}
          handleModalToggle={handleModalToggle}
          submitForm={submitForm}
          isSuccess={updated}
          isError={error}
        />
      )}
    </Modal>
  );
}
Example #6
Source File: add-token-modal.js    From ibutsu-server with MIT License 5 votes vote down vote up
render () {
    return (
      <Modal
        variant={ModalVariant.small}
        title="Add Token"
        isOpen={this.props.isOpen}
        onClose={this.onClose}
        actions={[
          <Button key="save" variant="primary" onClick={this.onSave}>Save</Button>,
          <Button key="cancel" variant="link" onClick={this.onClose}>Cancel</Button>
        ]}
      >
        <Form>
          <FormGroup
            label="Name"
            fieldId="token-name"
            helperTextInvalid="A token name is required"
            helperTextInvalidIcon={<ExclamationCircleIcon />}
            validated={this.state.isNameValid ? ValidatedOptions.default : ValidatedOptions.error}
            isRequired
          >
            <TextInput
              type="text"
              id="token-name"
              name="token-name"
              value={this.state.name}
              onChange={this.onNameChange}
              validated={this.state.isNameValid ? ValidatedOptions.default : ValidatedOptions.error}
              isRequired
            />
          </FormGroup>
          <FormGroup
            label="Expiry"
            fieldId="token-expiry-date"
            helperTextInvalid="A valid epiry date is required"
            helperTextInvalidIcon={<ExclamationCircleIcon />}
            validated={this.state.isExpiryValid ? ValidatedOptions.default : ValidatedOptions.error}
            isRequired
          >
            <DatePicker
              onChange={this.onExpiryDateChange}
              value={this.state.expiryDate}
              inputProps={{
                id: "token-expiry-date",
                validated: this.state.isExpiryValid ? ValidatedOptions.default : ValidatedOptions.error
              }}
            />
          </FormGroup>
        </Form>
      </Modal>
    );
  }
Example #7
Source File: ModalConfirm.js    From cockpit-wicked with GNU General Public License v2.0 5 votes vote down vote up
ModalConfirm = ({
    caption,
    title,
    isOpen = false,
    onConfirm,
    onConfirmDisable = false,
    onConfirmLabel = _("Confirm"),
    onCancel,
    onCancelLabel = _("Cancel"),
    variant = ModalVariant.small,
    children
}) => {
    if (!isOpen) return;

    return (
        <Modal
            aria-label={title}
            variant={variant}
            isOpen={isOpen}
            showClose={false}
            header={
                <>
                    <Text component={TextVariants.small} className='modal-form-caption'>
                        {caption}
                    </Text>
                    <Title headingLevel="h1">
                        {title}
                    </Title>
                </>
            }
            footer={
                <ActionGroup>
                    <Button key="confirm" variant="danger" onClick={onConfirm}>
                        {onConfirmLabel}
                    </Button>

                    <Button key="cancel" variant="link" onClick={onCancel}>
                        {onCancelLabel}
                    </Button>
                </ActionGroup>
            }
        >
            {children}
        </Modal>
    );
}
Example #8
Source File: ModalForm.js    From cockpit-wicked with GNU General Public License v2.0 5 votes vote down vote up
ModalForm = ({
    caption,
    title,
    isOpen = false,
    onSubmit,
    onSubmitDisable = false,
    onSubmitLabel = _("Apply"),
    onCancel,
    onCancelLabel = _("Cancel"),
    variant = ModalVariant.small,
    children
}) => {
    if (!isOpen) return;

    return (
        <Modal
            aria-label={title}
            variant={variant}
            isOpen={isOpen}
            showClose={false}
            header={
                <>
                    <Text component={TextVariants.small} className='modal-form-caption'>
                        {caption}
                    </Text>
                    <Title headingLevel="h1">
                        {title}
                    </Title>
                </>
            }
            footer={
                <ActionGroup>
                    <Button key="submit" onClick={onSubmit} isDisabled={onSubmitDisable}>
                        {onSubmitLabel}
                    </Button>

                    <Button key="cancel" variant="link" onClick={onCancel}>
                        {onCancelLabel}
                    </Button>
                </ActionGroup>
            }
        >

            <Form>
                {children}
            </Form>
        </Modal>
    );
}
Example #9
Source File: StartMode.js    From cockpit-wicked with GNU General Public License v2.0 5 votes vote down vote up
StartMode = ({ connection }) => {
    const [isOpen, setIsOpen] = useState(false);
    const [startMode, setStartMode] = useState(connection.startMode);
    const dispatch = useNetworkDispatch();

    const closeForm = () => setIsOpen(false);
    const openForm = () => setIsOpen(true);

    const handleSubmit = () => {
        // TODO: notify that something went wrong.
        if (connection.exists) {
            updateConnection(dispatch, connection, { startMode });
        } else {
            addConnection(dispatch, { ...connection, startMode });
        }

        closeForm();
    };

    const renderLink = () => {
        const label = connection.exists ? startModeEnum.label(connection.startMode) : _("Not configured");

        return <a href="#" onClick={openForm}>{label}</a>;
    };

    const renderModalForm = () => {
        if (!isOpen) return;

        return (
            <ModalForm
              caption={connection.name}
              title={_("Start Mode")}
              variant={ModalVariant.small}
              isOpen={isOpen}
              onSubmit={handleSubmit}
              onCancel={closeForm}
            >
                <FormSelect value={startMode} onChange={setStartMode} id="startMode">
                    {startModeOptions.map((option, index) => (
                        <FormSelectOption key={index} value={option.value} label={option.label} />
                    ))}
                </FormSelect>
            </ModalForm>
        );
    };

    return (
        <>
            { renderLink() }
            { renderModalForm() }
        </>
    );
}
Example #10
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 #11
Source File: IPSettingsForm.js    From cockpit-wicked with GNU General Public License v2.0 4 votes vote down vote up
IPSettingsForm = ({ connection, ipVersion = 'ipv4', isOpen, onClose }) => {
    const dispatch = useNetworkDispatch();
    const settings = connection[ipVersion];
    const [bootProto, setBootProto] = useState(settings.bootProto);
    const [addresses, setAddresses] = useState(settings.addresses);
    const [addressRequired, setAddressRequired] = useState(settings.bootProto === bootProtocol.STATIC);
    const [errorMessages, setErrorMessages] = useState([]);

    /**
     * Performs an update of the internal addresses state
     *
     * When the "Static" boot protocol is selected, it ensures that there is at least one {@link
     * module:/model~AddressConfig} in the collection, which helps displaying needed fields in the
     * UI.
     *
     * @param {Array<module:model~AddressConfig>} [nextAddresses] - Addresses to be used for the
     *   update. When not given, current addresses will be used.
     */
    const forceAddressesUpdate = useCallback((nextAddresses) => {
        nextAddresses ||= addresses;

        if (bootProto === bootProtocol.STATIC && nextAddresses.length === 0) {
            nextAddresses = [createAddressConfig()];
        }

        setAddresses(nextAddresses);
    }, [addresses, bootProto]);

    /**
     * Performs validations using given addresses
     *
     * @param {Array<module:model~AddressConfig>} sanitizedAddresses - a collection of sanitize
     *   addresses. See {@link sanitize}
     * @return {boolean} true when all validations success; false otherwise
     */
    const validate = (sanitizedAddresses) => {
        /**
         * TODO: improve validations
         * TODO: highlight addresses with errors?
         */
        let result = true;
        const errors = [];

        // Clean previous error messages
        setErrorMessages([]);

        if (bootProto === bootProtocol.STATIC && sanitizedAddresses.length === 0) {
            result = false;
            errors.push({
                key: 'static-address-required',
                message: format(
                    _('At least one address must be provided when using the "$bootProto" boot protocol'),
                    { bootProto: bootProtocol.label(bootProtocol.STATIC) }
                )
            });
        }

        if (findInvalidIP(sanitizedAddresses)) {
            result = false;
            errors.push({
                key: 'invalid-ips',
                message: _("There are invalid IPs")
            });
        }

        if (findRepeatedLabel(sanitizedAddresses)) {
            result = false;
            errors.push({
                key: 'repeated-labels',
                message: _("There are repeated labels")
            });
        }

        setErrorMessages(errors);

        return result;
    };

    /**
     * Handles the form submit, performing a connection update when proceed
     *
     * @see {@link validate}
     * @see {@link module/context/network~updateConnection}
     */
    const handleSubmit = () => {
        const sanitizedAddresses = sanitize(addresses);

        // Do not proceed if errors were found
        if (!validate(sanitizedAddresses)) {
            forceAddressesUpdate(sanitizedAddresses);
            return;
        }

        // If everything looks good, send requested changes and close
        updateConnection(
            dispatch,
            connection,
            { [ipVersion]: { bootProto, addresses: sanitizedAddresses } }
        );

        onClose();
    };

    /**
     * Updates the UI according to the bootProtocol selected
     *
     * Basically, setting the internal form state in order to ensure that the AddressDataList
     * component displays the fields for at least one {@link module/model~AddressConfig} item.
     */
    useEffect(() => {
        forceAddressesUpdate();
        setAddressRequired(bootProto === bootProtocol.STATIC);
    }, [forceAddressesUpdate, bootProto]);

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

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

    return (
        <ModalForm
            caption={connection.name}
            title={_(`${ipVersion.toUpperCase()} Settings`)}
            isOpen={isOpen}
            onSubmit={handleSubmit}
            onCancel={onClose}
            variant={ModalVariant.medium}
        >
            {renderErrors()}

            <FormGroup label={_("Boot Protocol")} isRequired>
                <BootProtoSelector value={bootProto} onChange={setBootProto} />
            </FormGroup>

            <FormGroup label={_("Addresses")}>
                <AddressesDataList
                    addresses={addresses}
                    updateAddresses={setAddresses}
                    allowEmpty={!addressRequired}
                />
            </FormGroup>
        </ModalForm>
    );
}
Example #12
Source File: WirelessForm.js    From cockpit-wicked with GNU General Public License v2.0 4 votes vote down vote up
WirelessForm = ({ isOpen, onClose, iface, connection }) => {
    const { wireless } = connection || {};
    const isEditing = !!connection;
    const [essid, setEssid] = useState(wireless?.essid);
    const [mode, setMode] = useState(wireless?.mode || wirelessModes.MANAGED);
    const [authMode, setAuthMode] = useState(wireless?.authMode || wirelessAuthModes.WEP_OPEN);
    const [password, setPassword] = useState(wireless?.password || "");
    const dispatch = useNetworkDispatch();

    const addOrUpdateConnection = () => {
        if (isEditing) {
            updateConnection(
                dispatch, connection,
                { wireless: { essid, mode, authMode, password } }
            );
        } else {
            addConnection(
                dispatch, { name: iface.name, type: interfaceType.WIRELESS, wireless: { essid, mode, authMode, password } }
            );
        }
        onClose();
    };

    return (
        <Modal
            variant={ModalVariant.small}
            title={isEditing ? _("Edit WiFi settings") : _("Add WiFi settings")}
            isOpen={isOpen}
            onClose={onClose}
            actions={[
                <Button key="confirm" variant="primary" onClick={addOrUpdateConnection}>
                    {isEditing ? _("Change") : _("Add")}
                </Button>,
                <Button key="cancel" variant="link" onClick={onClose}>
                    {_("Cancel")}
                </Button>
            ]}
        >
            <Form>
                <FormGroup
                    label={_("Mode")}
                    isRequired
                    fieldId="wireless-mode"
                >
                    <FormSelect value={mode} onChange={setMode} id="wireless-mode">
                        {modeOptions.map((option, index) => (
                            <FormSelectOption key={index} {...option} />
                        ))}
                    </FormSelect>
                </FormGroup>

                <FormGroup
                    label={_("ESSID")}
                    isRequired
                    fieldId="essid"
                >
                    <WirelessEssidSelect essid={essid} setEssid={setEssid} iface={iface} />
                </FormGroup>
                <FormGroup
                    label={_("Auth Mode")}
                    isRequired
                    fieldId="wireless-auth-mode"
                >
                    <FormSelect value={authMode} onChange={setAuthMode} id="wireless-auth-mode">
                        {authModeOptions.map((option, index) => (
                            <FormSelectOption key={index} {...option} />
                        ))}
                    </FormSelect>
                </FormGroup>
                { (authMode === "psk") &&
                    <FormGroup
                        label={_("Password")}
                        isRequired
                        fieldId="password"
                    >
                        <TextInput
                            isRequired
                            id="password"
                            value={password}
                            onChange={setPassword}
                            type='password'
                        />
                    </FormGroup>}
            </Form>
        </Modal>
    );
}