antd#Form TypeScript Examples

The following examples show how to use antd#Form. 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: TableContainer.tsx    From generator-earth with MIT License 6 votes vote down vote up
render() {
        // expandedRowRender={this.getExpandedRowRender}

        const Items: React.ReactNode | null = this.getSearchItems();

        return (
            <React.Fragment>

                {Items && (
                    <div className="ui-background">
                        <Form {...this.formProps()} onSubmit={this.submitForm}>
                            {Items}
                        </Form>
                    </div>
                )}

                <div className="ui-background clearfix">
                    {this.getTableExtraContent()}
                    <Table
                        bordered
                        title={this.getTitle()}
                        rowKey={this.getRowKey}
                        dataSource={this.getDataSource()}
                        columns={this.getColumns()}
                        onChange={this.handleTableChange}
                        pagination={this.getPagination()}
                        scroll={this.getScroll()}
                        rowSelection={this.rowSelection()}
                    />
                </div>
            </React.Fragment>

        )
    }
Example #2
Source File: CompositionField.tsx    From jmix-frontend with Apache License 2.0 6 votes vote down vote up
CompositionField = observer((props: CompositionFieldProps) => {

  const {
    entityName, 
    propertyName, 
    componentProps,
    disabled, 
    formItemProps,
    compositionType
  } = props;

  const metadata = useMetadata();
  const mainStore = useMainStore();

  const combinedFormItemProps = {...getDefaultFormItemProps(metadata.entities, entityName, propertyName, mainStore?.messages), ...formItemProps};
  if (combinedFormItemProps.rules == null) {
    combinedFormItemProps.rules = [];
  }
  // Add a passthrough rule. This will clear server-side errors on `validateTrigger` without having to manually set errors on fields.
  combinedFormItemProps.rules.push(passthroughRule);


  return (
    <FieldPermissionContainer entityName={entityName} propertyName={propertyName} renderField={(isReadOnly: boolean) => {
      const compositionComponentProps = {...componentProps, disabled: disabled || isReadOnly} as CompositionComponentProps
      return (
        <Form.Item 
          {...combinedFormItemProps}
        >
          {renderCompositionComponent(compositionType, compositionComponentProps)}
        </Form.Item>
      )

    }}/>);

})
Example #3
Source File: index.tsx    From drip-table with MIT License 6 votes vote down vote up
public renderFormItem(config: DTGComponentPropertySchema, index: number) {
    const { helpMsg } = this.state;
    const labelCol = config['ui:layout']?.labelCol || 8;
    const wrapperCol = config['ui:layout']?.wrapperCol || 16;
    const formItemLayout = {
      labelCol: { xs: { span: labelCol }, sm: { span: labelCol } },
      wrapperCol: { xs: { span: wrapperCol }, sm: { span: wrapperCol } },
    };
    const key = config.name;
    const visible = this.visible(config);
    if (!visible) { return null; }
    return (
      <React.Fragment key={index}>
        <Form.Item
          key={key}
          label={this.renderTitleLabel(config)}
          colon={false}
          validateStatus={helpMsg[key] ? 'error' : 'success'}
          help={config['ui:layout']?.customHelpMsg ? '' : helpMsg[key]}
          required={config.required}
          style={config['ui:wrapperStyle']}
          {...formItemLayout}
        >
          { !config['ui:layout']?.extraRow && this.renderFormComponent(config) }
          { config['ui:layout']?.customHelpMsg && helpMsg[key] && (
            <Alert style={{ padding: '4px 12px', height: '32px' }} message={helpMsg[key]} type="error" showIcon />
          ) }
        </Form.Item>
        { config['ui:layout']?.extraRow && (
          <Row>
            <Col span={24}>
              { this.renderFormComponent(config) }
            </Col>
          </Row>
        ) }
      </React.Fragment>
    );
  }
Example #4
Source File: Login.tsx    From vite-react-ts with MIT License 6 votes vote down vote up
Login: React.FC = () => {
  const { login, loading } = useStore((state) => ({ ...state }));

  return (
    <div className={cls.loginBox}>
      <Card className="_bg" bordered={false}>
        <Form
          onFinish={({ username, password }) => {
            if (username === 'admin' && password === '123456') {
              return login({ username, password });
            }
            message.error('账号或密码错误,请重试!');
          }}>
          <Form.Item
            name="username"
            rules={[{ required: true, message: '请输入用户名' }]}>
            <Input prefix={<UserOutlined />} placeholder="请输入用户名:admin" />
          </Form.Item>
          <Form.Item name="password" rules={[{ required: true, message: '请输入密码' }]}>
            <Input prefix={<LockOutlined />} placeholder="请输入密码:123456" />
          </Form.Item>
          <Form.Item>
            <Button
              loading={loading}
              type="primary"
              htmlType="submit"
              className={cls.button}>
              登陆
            </Button>
          </Form.Item>
        </Form>
      </Card>
    </div>
  );
}
Example #5
Source File: StepField.tsx    From posthog-foss with MIT License 6 votes vote down vote up
export function StepField({ field, step, item, label, caption }: StepFieldProps): JSX.Element {
    const selected = step && ((step as any)[`${item}_selected`] as boolean)
    const fieldStyle = selected ? {} : { opacity: 0.5 }

    return (
        <div className={selected ? 'action-field action-field-selected' : 'action-field'}>
            <Form.Item style={{ margin: 0 }}>
                {item === 'href' && step?.href && <SelectorCount selector={`a[href="${cssEscape(step.href)}"]`} />}
                {item === 'selector' && step?.selector && <SelectorCount selector={step.selector} />}

                <Form.Item
                    name={[field.name, `${item}_selected`]}
                    fieldKey={[field.fieldKey, `${item}_selected`] as unknown as number}
                    valuePropName="checked"
                    noStyle
                >
                    <Checkbox>{label}</Checkbox>
                </Form.Item>
                {caption && <div className="action-field-caption">{caption}</div>}
            </Form.Item>
            {item === 'url' ? (
                <Form.Item
                    name={[field.name, `${item}_matching`]}
                    fieldKey={[field.fieldKey, `${item}_matching`] as unknown as number}
                >
                    <UrlMatchingToggle style={fieldStyle} />
                </Form.Item>
            ) : null}
            <Form.Item name={[field.name, item]} fieldKey={[field.fieldKey, item] as unknown as number}>
                {item === 'selector' ? <Input.TextArea autoSize style={fieldStyle} /> : <Input style={fieldStyle} />}
            </Form.Item>
            {item === 'url' && step?.url_matching && step.url_matching in URL_MATCHING_HINTS ? (
                <div className="action-field-hint">{URL_MATCHING_HINTS[step.url_matching]}</div>
            ) : null}
        </div>
    )
}
Example #6
Source File: questionnaire.tsx    From RareCamp with Apache License 2.0 6 votes vote down vote up
OFForm = styled(Form)`
  margin-top: 24px;
  max-width: 530px;
  .ant-radio-wrapper {
    display: block;
    height: 30px;
    line-height: 30px;
  }
`
Example #7
Source File: Example.stories.tsx    From ant-extensions with MIT License 6 votes vote down vote up
Example = () => {
  const { i18n, t } = useTranslation();
  return (
    <ConfigProvider direction={i18n.dir()}>
      <div style={{ padding: "2em", maxWidth: 450, margin: "auto" }}>
        <Form layout="vertical">
          <Form.Item label={t("labelDate")}>
            <InlineDatePicker />
          </Form.Item>
        </Form>
      </div>
    </ConfigProvider>
  );
}
Example #8
Source File: Align.tsx    From dnde with GNU General Public License v3.0 6 votes vote down vote up
Align = () => {
  const [visible, path] = useVisibility({ attribute: ATTRIBUTE });
  const { mjmlJson, setMjmlJson } = useEditor();
  const { active } = useHtmlWrapper();

  const onClick = (align: string) => {
    if (active && visible && path) {
      let item = _.get(mjmlJson, path);
      if (item && item.attributes && item.attributes) {
        item.attributes['align'] = align;
        const updated = _.set(mjmlJson, path, item);
        setMjmlJson({ ...updated });
      }
    }
  };

  return visible ? (
    <Row>
      <Col flex="3">
        <Form.Item label="Align"></Form.Item>
      </Col>
      <Col flex="2">
        <Row justify="space-between">
          {alignOptions.map(({ prop, component, title }, key) => {
            return (
              <Col key={key}>
                <Tooltip title={title}>
                  <Button onClick={() => onClick(prop)} type="ghost" icon={component} />
                </Tooltip>
              </Col>
            );
          })}
        </Row>
      </Col>
    </Row>
  ) : null;
}
Example #9
Source File: form.tsx    From XFlow with MIT License 6 votes vote down vote up
CmdForm = () => {
  const { commandService } = usePanelContext()
  const [form] = Form.useForm<IFormValues>()

  const onFinish = async (values: IFormValues) => {
    commandService.executeCommand<NsNodeCmd.BackNode.IArgs>(XFlowNodeCommands.BACK_NODE.id, values)
    console.log('executeCommand with args', values)
    message.success(`${XFlowNodeCommands.BACK_NODE.label}: 命令执行成功`)
    form.setFieldsValue({
      nodeId: values.nodeId === 'node1' ? 'node2' : 'node1',
    })
  }

  return (
    <FormBuilder<IFormValues>
      form={form}
      formItems={formItems}
      onFinish={onFinish}
      initialValues={{
        nodeId: 'node1',
      }}
    />
  )
}
Example #10
Source File: DendronLookupPanel.tsx    From dendron with GNU Affero General Public License v3.0 6 votes vote down vote up
export default function DendronLookupPanel({ ide }: DendronProps) {
  const [form] = Form.useForm();

  // on each render
  useEffect(() => {
    // ask vscode for controller state if it's not set yet.
    if (ide.lookupModifiers === undefined) {
      postVSCodeMessage({
        type: LookupViewMessageEnum.onRequestControllerState,
        data: {},
        source: DMessageSource.webClient,
      } as LookupViewMessage);
    }
  });

  return (
    <>
      <h4>Modifiers</h4>
      <LookupViewForm ide={ide} form={form} />
    </>
  );
}
Example #11
Source File: edit-policy-access-drawe.tsx    From shippo with MIT License 5 votes vote down vote up
Component: React.ForwardRefRenderFunction<
  EditPolicyAccessDrawerRef,
  EditPolicyAccessDrawerProps
> = (props, ref) => {
  const { onClose } = props
  const [policy, setPolicy] = useState<IPermissionPolicy>(__defaultPolicy)
  const [dataSource, setDataSource] = useState<IPermissionAccess[]>([])

  const [visible, setVisible] = useState(false)
  const [selectedRowKeys, setSelectedRowKeys] = useState<number[]>([])

  // ref
  useImperativeHandle(ref, () => {
    return {
      // 打开抽屉
      open: (policy: IPermissionPolicy) => {
        services.permissionAccess.find_all_ext_status({ id: policy.id }).then((hr) => {
          setDataSource(hr.data.resource)
          setSelectedRowKeys(hr.data.resource.filter((item) => item.status).map((item) => item.id))
        })
        setPolicy(policy)
        setVisible(true)
      },
    }
  })

  // 关闭抽屉
  const closeDrawer = useCallback(() => {
    onClose && onClose()
    setVisible(false)
  }, [onClose])

  const handleSave = useCallback(async () => {
    console.log(policy)
    services.permissionPolicy.update_access({ id: policy.id, access: selectedRowKeys })
    closeDrawer()
  }, [policy, selectedRowKeys, closeDrawer])

  return (
    <Drawer
      title="访问规则配置"
      width={720}
      onClose={closeDrawer}
      visible={visible}
      bodyStyle={{ paddingBottom: 80 }}
    >
      <Form layout="vertical" requiredMark={false}>
        <Form.Item>
          <Table
            rowKey="id"
            rowSelection={{
              selectedRowKeys,
              onChange: (keys) => setSelectedRowKeys(keys as number[]),
            }}
            columns={columns}
            dataSource={dataSource}
            size="small"
          />
        </Form.Item>
        <Form.Item>
          <Space>
            <Button onClick={closeDrawer}>关闭</Button>
            <Button onClick={handleSave} type="primary">
              保存
            </Button>
          </Space>
        </Form.Item>
      </Form>
    </Drawer>
  )
}
Example #12
Source File: DateRangePicker.tsx    From generator-earth with MIT License 5 votes vote down vote up
FormItem = Form.Item
Example #13
Source File: Login.tsx    From jmix-frontend with Apache License 2.0 5 votes vote down vote up
Login = observer(() => {
  const intl = useIntl();

  const mainStore = useMainStore();

  const [login, setLogin] = useState("");
  const [password, setPassword] = useState("");
  const [performingLoginRequest, setPerformingLoginRequest] = useState(false);

  const changeLogin = useCallback((e: ChangeEvent<HTMLInputElement>) => setLogin(e.target.value), [setLogin]);
  const changePassword = useCallback((e: ChangeEvent<HTMLInputElement>) => setPassword(e.target.value), [setPassword]);

  const doLogin = useCallback(() => {
    setPerformingLoginRequest(true);
    mainStore
      .login(login, password)
      .then(action(() => {
        setPerformingLoginRequest(false);
      }))
      .catch(action((error: JmixServerError) => {
        setPerformingLoginRequest(false);

        const loginMessageErrorIntlId = loginMapJmixRestErrorToIntlId(error);
        message.error(intl.formatMessage({id: loginMessageErrorIntlId}));
      }));
  }, [setPerformingLoginRequest, mainStore, intl, login, password]);

  return (
    <Card className={styles.loginForm}>
      <JmixDarkIcon className={styles.logo} />

      <div className={styles.title}>
        <%= title %>
      </div>

      <Form layout='vertical' onFinish={doLogin}>
        <Form.Item>
          <Input id='input_login'
                  placeholder={intl.formatMessage({id: 'login.placeholder.login'})}
                  onChange={changeLogin}
                  value={login}
                  prefix={<UserOutlined style={{ margin: "0 11px 0 0" }}/>}
                  size='large'/>
        </Form.Item>
        <Form.Item>
          <Input id='input_password'
                  placeholder={intl.formatMessage({id: 'login.placeholder.password'})}
                  onChange={changePassword}
                  value={password}
                  type='password'
                  prefix={<LockOutlined style={{ margin: "0 11px 0 0" }}/>}
                  size='large'/>
        </Form.Item>
        <Form.Item>
          <div className={styles.languageSwitcherContainer}>
            <LanguageSwitcher />
          </div>
        </Form.Item>
        <Form.Item>
          <Button type='primary'
                  htmlType='submit'
                  size='large'
                  block={true}
                  loading={performingLoginRequest}>
            <FormattedMessage id='login.loginBtn'/>
          </Button>
        </Form.Item>
      </Form>
    </Card>
  );
})
Example #14
Source File: PasswordInput.tsx    From posthog-foss with MIT License 5 votes vote down vote up
PasswordInput = React.forwardRef(function PasswordInputInternal(
    {
        label = 'Password',
        showStrengthIndicator,
        validateMinLength,
        style,
        validationDisabled,
        disabled,
        inputName = 'password',
        ...props
    }: PasswordInputProps,
    ref: React.Ref<Input>
): JSX.Element {
    return (
        <div style={{ marginBottom: 24, ...style }} className="password-input">
            <div style={{ display: 'flex', alignItems: 'center' }} className="ant-form-item-label">
                <label htmlFor="password">{label}</label>
                {showStrengthIndicator && (
                    <Form.Item
                        shouldUpdate={(prevValues, currentValues) => prevValues.password !== currentValues.password}
                        className="password-input-strength-indicator"
                    >
                        {({ getFieldValue }) => (
                            <Suspense fallback={<></>}>
                                <div
                                    style={{
                                        display: 'flex',
                                        overflow: 'hidden',
                                        whiteSpace: 'nowrap',
                                        paddingLeft: '60%',
                                    }}
                                >
                                    <PasswordStrength password={getFieldValue('password')} />
                                </div>
                            </Suspense>
                        )}
                    </Form.Item>
                )}
            </div>
            <Form.Item
                name={inputName}
                rules={
                    !validationDisabled
                        ? [
                              {
                                  required: true,
                                  message: (
                                      <>
                                          <ExclamationCircleFilled style={{ marginRight: 4 }} /> Please enter your
                                          password to continue
                                      </>
                                  ),
                              },
                              {
                                  min: validateMinLength ? 8 : undefined,
                                  message: (
                                      <>
                                          <ExclamationCircleFilled style={{ marginRight: 4 }} /> Password must be at
                                          least 8 characters
                                      </>
                                  ),
                              },
                          ]
                        : undefined
                }
                style={showStrengthIndicator ? { marginBottom: 0 } : undefined}
                {...props}
            >
                <Input.Password
                    ref={ref}
                    className="ph-ignore-input"
                    data-attr="password"
                    placeholder="••••••••••"
                    disabled={disabled}
                />
            </Form.Item>
        </div>
    )
})
Example #15
Source File: TaskBudgetCell.tsx    From RareCamp with Apache License 2.0 5 votes vote down vote up
EditTask = styled(Form.Item)`
  padding: 0;
  margin: 0;
  input {
    border: none;
  }
`
Example #16
Source File: RelativeForm.tsx    From ant-extensions with MIT License 5 votes vote down vote up
RelativeForm: React.FC<BaseProps> = React.memo(({ value, onChange }) => {
  const { t } = useTranslation(I18nKey);

  const [_start, setStart] = useState<DateValue>("$hour-1");
  const [_end, setEnd] = useState<DateValue>("$hour-1");

  useEffect(() => {
    if (value && superDateType(value) === Type.RELATIVE) {
      const [start, end] = value.split("|");
      setStart(start);
      setEnd(end);
    }
  }, [value]);

  const applyRelative = useCallback(() => {
    if (_start && _end) {
      onChange && onChange(makeSuperDate(_start, _end));
    }
  }, [_start, _end, onChange]);

  return (
    <div className="ant-ext-sd__relativeForm">
      <Form>
        <Form.Item {...fieldProps} label={t("label.from")}>
          <RelativeInput value={_start} onChange={setStart} />
        </Form.Item>
        <Form.Item {...fieldProps} label={t("label.to")}>
          <RelativeInput value={_end} onChange={setEnd} />
        </Form.Item>
        <Row justify="end">
          <Col>
            <Button size="small" type="primary" onClick={applyRelative}>
              {t("label.apply")}
            </Button>
          </Col>
        </Row>
      </Form>
    </div>
  );
})
Example #17
Source File: Background.tsx    From dnde with GNU General Public License v3.0 5 votes vote down vote up
Background = ({ activePath, label, overrideAttribute }: BackgroundProps) => {
  const attribute = overrideAttribute || ATTRIBUTE;
  const { mjmlJson, setMjmlJson } = useEditor();
  const [active, setActive] = useState(() => false);
  const [color, setColor] = useState(() => '#ccc');
  const [visible, path] = useVisibility({ attribute, customPath: activePath });

  useEffect(() => {
    if (visible && path) {
      const item = _.get(mjmlJson, path);
      if (item && item.attributes && item.attributes[attribute]) {
        setColor(item.attributes[attribute]);
      }
    }
    logger.log('background reloading,', path, visible);
  }, [path, visible]);

  const handleColorChange = (color: any) => {
    const hexCode = `${color.hex}${decimalToHex(color.rgb.a)}`;
    setColor(hexCode);
    if (path && visible) {
      let element = _.get(mjmlJson, path);
      element.attributes[attribute] = hexCode;
      let json = _.set(mjmlJson, path, element);

      setMjmlJson({ ...json });
    }
  };

  return visible ? (
    <>
      <Row>
        <Col flex="auto">
          <Form.Item label={label ? label : 'Background'}></Form.Item>
        </Col>

        <ColorPicker color={color} flex="none">
          <div className="swatch" onClick={() => setActive(true)}>
            <div className="color"></div>
          </div>
          {active ? (
            <div className="popover">
              <div className="cover" onClick={() => setActive(false)}></div>
              <ChromePicker disableAlpha={false} color={color} onChange={(color: any) => handleColorChange(color)} />
            </div>
          ) : null}
        </ColorPicker>
      </Row>
    </>
  ) : null;
}
Example #18
Source File: index.tsx    From antdp with MIT License 5 votes vote down vote up
FormItem = Form.Item
Example #19
Source File: form.tsx    From XFlow with MIT License 5 votes vote down vote up
CmdForm = () => {
  const { commandService } = usePanelContext()
  const [form] = Form.useForm<IFormValues>()
  const [hasGroup, setGroup] = React.useState(false)
  const onFinish = async (values: IFormValues) => {
    const nodeConfig = {
      ...values,
      groupHeaderHeight: parseInt(values.groupHeaderHeight as any, 10),
      groupPadding: parseInt(values.groupPadding as any, 10),
      groupCollapsedSize: GROUP_COLLAPSED_SIZE,
    }
    setGroup(true)
    console.log(nodeConfig)
    await commandService.executeCommand<NsGroupCmd.AddGroup.IArgs>(
      XFlowGroupCommands.ADD_GROUP.id,
      {
        nodeConfig: nodeConfig,
      },
    )

    message.success(`${XFlowGroupCommands.ADD_GROUP.label}: 命令执行成功`)
  }

  return (
    <FormBuilder<IFormValues>
      form={form}
      formItems={formItems}
      onFinish={onFinish}
      initialValues={{
        id: uuidv4(),
        groupChildren: ['node1', 'node2', 'node3', 'node4'],
        label: 'Group_1',
        groupHeaderHeight: 40,
        groupPadding: 12,
        renderKey: GROUP_NODE_RENDER_ID,
      }}
      submitButton={
        <Button type="primary" htmlType="submit" style={{ width: '100%' }} disabled={hasGroup}>
          执行命令
        </Button>
      }
    />
  )
}