antd/lib/form#FormInstance TypeScript Examples

The following examples show how to use antd/lib/form#FormInstance. 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: index.tsx    From generator-earth with MIT License 5 votes vote down vote up
formRef = React.createRef<FormInstance>();
Example #2
Source File: index.tsx    From nebula-dashboard with Apache License 2.0 5 votes vote down vote up
formRef = React.createRef<FormInstance>();
Example #3
Source File: index.tsx    From nebula-dashboard with Apache License 2.0 5 votes vote down vote up
formRef = React.createRef<FormInstance>();
Example #4
Source File: index.tsx    From nebula-dashboard with Apache License 2.0 5 votes vote down vote up
formRef = React.createRef<FormInstance>();
Example #5
Source File: index.tsx    From nebula-dashboard with Apache License 2.0 5 votes vote down vote up
formRef = React.createRef<FormInstance>();
Example #6
Source File: DragSortEditTable.tsx    From datart with Apache License 2.0 5 votes vote down vote up
EditableContext = createContext<FormInstance<any> | null>(null)
Example #7
Source File: editModal.tsx    From imove with MIT License 5 votes vote down vote up
EditModal: React.FC<IEditorModalProps> = (props: IEditorModalProps) => {
  const { visible, onOk, onCancel } = props;
  const formRef = useRef<FormInstance>(null);

  // events
  const onClickOk = (): void => {
    if (formRef.current) {
      formRef.current
        .validateFields()
        .then((formValues) => {
          updateLocalConfig(formValues as ILocalConfig);
          onOk();
        })
        .catch((error) => {
          console.log(error.message);
        });
    }
  };

  return (
    <Modal
      className={styles.editModal}
      visible={visible}
      okText={'保存'}
      cancelText={'取消'}
      title={'配置'}
      onOk={onClickOk}
      onCancel={onCancel}
    >
      <Form
        ref={formRef}
        labelCol={{ span: 6 }}
        labelAlign="right"
        initialValues={getLocalConfig()}
      >
        <Form.Item
          label={'本地连接 IP'}
          name={'ip'}
          rules={makeRules(IP_REGEX, 'IP格式不合法')}
        >
          <Input />
        </Form.Item>
        <Form.Item
          label={'本地连接端口'}
          name={'port'}
          rules={makeRules(PORT_REGEX, '端口格式不合法')}
        >
          <Input />
        </Form.Item>
        <Form.Item
          label={'NPM 源'}
          name={'npmRegistry'}
          rules={makeRules(NPM_REGISTRY_REGEX, 'NPM 源地址不合法')}
        >
          <Input />
        </Form.Item>
      </Form>
    </Modal>
  );
}
Example #8
Source File: index.tsx    From next-basics with GNU General Public License v3.0 5 votes vote down vote up
private _formUtils = React.createRef<Partial<FormInstance>>();
Example #9
Source File: index.tsx    From generator-earth with MIT License 5 votes vote down vote up
formRef = React.createRef<FormInstance>();
Example #10
Source File: index.tsx    From generator-earth with MIT License 5 votes vote down vote up
formRef = React.createRef<FormInstance>();
Example #11
Source File: index.tsx    From generator-earth with MIT License 5 votes vote down vote up
formRef = React.createRef<FormInstance>();
Example #12
Source File: useBaseForm.ts    From generator-earth with MIT License 5 votes vote down vote up
export function useBaseForm({
    formData,
    resetTable,
    updateTable,
    autoSubmit = true,
    adaptFormData = values => values,
}: IProps = {}): [
        // antd-form 实例
        FormInstance,
        // 提交表单
        (values: IAnyObject) => void,
        // 重置表单
        () => void,
        // 导出表单数据
        (api: string) => void
    ] {

    const [form] = Form.useForm()

    // 初始化调用,进入页面请求列表
    useEffect(() => {
        initFetch()
        // eslint-disable-next-line react-hooks/exhaustive-deps
    }, [])

    function initFetch(): void {
        if (!formData) {
            return;
        }
        if (!isEmpty(formData)) {
            form.setFieldsValue(formData)
            // 这时使用redux缓存数据更新,可以直接请求上传查看页面
            autoSubmit && updateTable && updateTable(formData)
            return;
        }
        // 首次进入页面,自动触发submit
        autoSubmit && form.submit()
    }

    // 手动触发提交表单
    function onFinish(values: IAnyObject): void {
        // 重置table
        resetTable && resetTable()
        // _formData里的一些值需要适配
        const _formData: IAnyObject = adaptFormData(values)
        // action
        updateTable && updateTable(_formData)
    }

    // 重置表单
    function onReset(): void {
        form.resetFields()
    }

    // 导出表单
    async function onExport(exportApi: string) {
        console.log(form.getFieldsValue())
        if (!exportApi) return
        try {
            await download(exportApi, { ...formData, ...form.getFieldsValue() })
        } catch (e) {
            showError(e)
        }
    }

    return [form, onFinish, onReset, onExport]
}
Example #13
Source File: index.tsx    From generator-earth with MIT License 5 votes vote down vote up
formRef = React.createRef<FormInstance>();
Example #14
Source File: index.tsx    From generator-earth with MIT License 5 votes vote down vote up
formRef = React.createRef<FormInstance>();
Example #15
Source File: index.tsx    From generator-earth with MIT License 5 votes vote down vote up
formRef = React.createRef<FormInstance>();
Example #16
Source File: EventConfigForm.tsx    From next-basics with GNU General Public License v3.0 4 votes vote down vote up
export function LegacyEventConfigForm(
  props: EventConfigFormProps,
  ref: React.Ref<Partial<FormInstance>>
): React.ReactElement {
  const { t } = useTranslation(NS_NEXT_BUILDER);
  const theme = useCurrentTheme();
  const {
    labelCol,
    wrapperCol,
    onValuesChange,
    providerList,
    type,
    docUrl,
    lifeCycle,
    pathList,
    segueList,
    useInCustomTemplate,
    highlightTokens,
    onClickHighlightToken,
  } = props;
  const [form] = Form.useForm();

  useImperativeHandle(
    ref,
    () => ({
      setFieldsValue: form.setFieldsValue,
      resetFields: form.resetFields,
      validateFields: form.validateFields,
    }),
    [form]
  );

  const debounceHandleChange = useMemo(
    () => debounce(onValuesChange, 600),
    [onValuesChange]
  );

  const inlineFormItemStyle = useMemo(
    () => ({
      display: "inline-block",
      width: "calc(100% - 20px)",
      margin: "0 6px 0 0",
    }),
    []
  );

  const getCodeEditorItem = useCallback(
    (options = {}): React.ReactNode => {
      return (
        <CodeEditorItem
          tabSize={2}
          minLines={6}
          maxLines="Infinity"
          printMargin={false}
          showLineNumbers={true}
          theme={theme === "dark-v2" ? "monokai" : "tomorrow"}
          enableLiveAutocompletion={true}
          mode="brick_next_yaml"
          highlightTokens={highlightTokens}
          onClickHighlightToken={onClickHighlightToken}
          {...options}
        ></CodeEditorItem>
      );
    },
    [highlightTokens, onClickHighlightToken, theme]
  );

  const HandleTypeChange = useCallback(
    (e: RadioChangeEvent): void => {
      const type = e.target.value;
      if (
        type === HandlerType.UseProvider &&
        isNil(form.getFieldValue("providerType"))
      ) {
        form.setFieldsValue({ providerType: "provider" });
      }
    },
    [form]
  );

  const handlerTypeItem = useMemo(
    () => (
      <Form.Item
        hidden={lifeCycle === LifeCycle.UseResolves}
        name="handlerType"
        label={t(K.HANDLE_TYPE_LABEL)}
        rules={[{ required: true }]}
      >
        <Radio.Group onChange={HandleTypeChange}>
          <Radio value={HandlerType.BuiltinAction}>
            {t(K.EVENTS_HANDLER_BUILTIN_ACTION)}
          </Radio>
          <Radio value={HandlerType.UseProvider}>
            {t(K.EVENTS_HANDLER_USE_PROVIDER)}
          </Radio>
          <Radio value={HandlerType.CustomBrick}>
            {t(K.EVENTS_CUSTOM_BRICK_INTERACTION)}
          </Radio>
        </Radio.Group>
      </Form.Item>
    ),
    [t, HandleTypeChange, lifeCycle]
  );

  const ifItem = useMemo(
    () => (
      <Form.Item name="if" label={t(K.IF_LABEL)}>
        {getCodeEditorItem({
          minLines: 3,
          schemaRef: "#/definitions/UseProviderResolveConf/properties/if",
        })}
      </Form.Item>
    ),
    [t, getCodeEditorItem]
  );

  const actionItem = useMemo(
    () => (
      <Form.Item
        noStyle
        shouldUpdate={(prevValues, currentValues) =>
          prevValues.handlerType !== currentValues.handlerType
        }
      >
        {({ getFieldValue }) =>
          getFieldValue("handlerType") === HandlerType.BuiltinAction && (
            <Form.Item label={t(K.SELECT_ACTION_LABEL)} required>
              <Form.Item
                name="action"
                messageVariables={{ label: "action" }}
                rules={[{ required: true }]}
                style={docUrl && inlineFormItemStyle}
              >
                <AutoComplete
                  options={getActionOptions(builtinActions, recommendActionIds)}
                  filterOption={(inputValue, option) =>
                    option?.options?.some(
                      (item: BuiltinAction) =>
                        item.value
                          .toUpperCase()
                          .indexOf(inputValue.toUpperCase()) !== -1
                    )
                  }
                ></AutoComplete>
              </Form.Item>
              {docUrl && (
                <Tooltip title={t(K.LINK_TO_NEXT_DOCS)}>
                  <Link target="_blank" href={docUrl}>
                    <FileSearchOutlined />
                  </Link>
                </Tooltip>
              )}
            </Form.Item>
          )
        }
      </Form.Item>
    ),
    [t, inlineFormItemStyle, docUrl]
  );

  const segueIdItem = useMemo(
    () => (
      <Form.Item
        noStyle
        shouldUpdate={(prevValues, currentValues) =>
          prevValues.handlerType !== currentValues.handlerType ||
          prevValues.action !== currentValues.action
        }
      >
        {({ getFieldValue }) =>
          getFieldValue("handlerType") === HandlerType.BuiltinAction &&
          getFieldValue("action") === "segue.push" && (
            <Form.Item
              name="segueId"
              label={t(K.SEGUE_ID_ITEM_LABEL)}
              rules={[{ required: true }]}
            >
              <AutoComplete
                options={segueList?.map((item) => ({
                  value: item.value,
                  label: (
                    <div style={{ display: "flex", gap: 8 }} title={item.label}>
                      <span>{item.value}</span>
                      <span
                        title={item.label}
                        style={{
                          fontSize: 12,
                          color: "rgba(137, 137, 137, 0.8)",
                        }}
                      >
                        [to: {item.label}]
                      </span>
                    </div>
                  ),
                }))}
                filterOption={(inputValue, option) =>
                  option?.value
                    .toUpperCase()
                    .indexOf(inputValue.toUpperCase()) !== -1
                }
              />
            </Form.Item>
          )
        }
      </Form.Item>
    ),
    [t, segueList]
  );

  const historyPathItem = useMemo(
    () => (
      <Form.Item
        noStyle
        shouldUpdate={(prevValues, currentValues) =>
          prevValues.handlerType !== currentValues.handlerType ||
          prevValues.action !== currentValues.action
        }
      >
        {({ getFieldValue }) =>
          getFieldValue("handlerType") === HandlerType.BuiltinAction &&
          getFieldValue("action") === "history.push" && (
            <Form.Item
              name="path"
              label={t(K.HISTORY_PATH_ITEM_LABEL)}
              tooltip={t(K.HISTORY_PATH_ITEM_TOOLTIP)}
              rules={[{ required: true }]}
            >
              <AutoComplete
                options={pathList?.map((path) => ({ value: path }))}
                filterOption={(inputValue, option) =>
                  option?.value
                    .toUpperCase()
                    .indexOf(inputValue.toUpperCase()) !== -1
                }
              />
            </Form.Item>
          )
        }
      </Form.Item>
    ),
    [pathList, t]
  );

  const providerTypeItem = useMemo(
    () => (
      <Form.Item
        noStyle
        shouldUpdate={(prevValues, currentValues) =>
          prevValues.handlerType !== currentValues.handlerType
        }
      >
        {({ getFieldValue }) =>
          getFieldValue("handlerType") === HandlerType.UseProvider && (
            <Form.Item
              name="providerType"
              label={t(K.PROVIDER_TYPE_LABEL)}
              rules={[{ required: true }]}
            >
              <Radio.Group>
                <Radio.Button value="provider">
                  {t(K.BUILTIN_PROVIDER)}
                </Radio.Button>
                <Radio.Button value="flow">{t(K.FLOW_API)}</Radio.Button>
              </Radio.Group>
            </Form.Item>
          )
        }
      </Form.Item>
    ),
    [t]
  );

  const providerItem = useMemo(
    () => (
      <Form.Item
        noStyle
        shouldUpdate={(prevValues, currentValues) =>
          prevValues.handlerType !== currentValues.handlerType ||
          prevValues.providerType !== currentValues.providerType
        }
      >
        {({ getFieldValue }) =>
          getFieldValue("handlerType") === HandlerType.UseProvider &&
          getFieldValue("providerType") === "provider" && (
            <Form.Item label="Provider" required>
              <Form.Item
                name="provider"
                rules={[{ required: true }]}
                messageVariables={{ label: "provider" }}
                style={inlineFormItemStyle}
              >
                <AutoComplete
                  options={providerList?.map((provider) => ({
                    value: provider,
                  }))}
                  filterOption={(inputValue, option) =>
                    option?.value
                      .toUpperCase()
                      .indexOf(inputValue.toUpperCase()) !== -1
                  }
                ></AutoComplete>
              </Form.Item>
              <Tooltip title={t(K.LINK_TO_DEVELOPER_PROVIDER_DOC)}>
                <Link target="_blank" to="/developers/providers">
                  <FileSearchOutlined />
                </Link>
              </Tooltip>
            </Form.Item>
          )
        }
      </Form.Item>
    ),
    [providerList, t, inlineFormItemStyle]
  );

  const flowApiItem = useMemo(
    () => (
      <Form.Item
        noStyle
        shouldUpdate={(prevValues, currentValues) =>
          prevValues.handlerType !== currentValues.handlerType ||
          prevValues.providerType !== currentValues.providerType
        }
      >
        {({ getFieldValue }) =>
          getFieldValue("handlerType") === HandlerType.UseProvider &&
          getFieldValue("providerType") === "flow" && (
            <Form.Item label="Flow" required>
              <Form.Item
                name="flow"
                rules={[{ required: true }]}
                messageVariables={{ label: "flow" }}
                style={inlineFormItemStyle}
              >
                <ContractAutoComplete />
              </Form.Item>
              <Tooltip title={t(K.LINK_TO_FLOWER_BUILDER)}>
                <Link target="_blank" to="/flow-builder">
                  <FileSearchOutlined />
                </Link>
              </Tooltip>
            </Form.Item>
          )
        }
      </Form.Item>
    ),
    [t, inlineFormItemStyle]
  );

  const useProviderMethod = useMemo(
    () => (
      <Form.Item
        noStyle
        shouldUpdate={(prevValues, currentValues) =>
          prevValues.handlerType !== currentValues.handlerType
        }
      >
        {({ getFieldValue }) =>
          getFieldValue("handlerType") === HandlerType.UseProvider && (
            <Form.Item
              label={t(K.METHOD)}
              name="useProviderMethod"
              initialValue="resolve"
            >
              <Radio.Group>
                <Radio value="resolve">resolve</Radio>
                <Radio value="saveAs">saveAs</Radio>
              </Radio.Group>
            </Form.Item>
          )
        }
      </Form.Item>
    ),
    [t]
  );

  const pollEnabledItem = useMemo(
    () => (
      <Form.Item
        noStyle
        shouldUpdate={(prevValues, currentValues) =>
          prevValues.handlerType !== currentValues.handlerType
        }
      >
        {({ getFieldValue }) =>
          getFieldValue("handlerType") === HandlerType.UseProvider && (
            <Form.Item
              label={t(K.POLLING_LABEL)}
              name="pollEnabled"
              valuePropName="checked"
            >
              <Switch></Switch>
            </Form.Item>
          )
        }
      </Form.Item>
    ),
    [t]
  );

  const pollItem = useMemo(
    () => (
      <Form.Item
        noStyle
        shouldUpdate={(prevValues, currentValues) =>
          prevValues.handlerType !== currentValues.handlerType ||
          prevValues.pollingEnabled !== currentValues.handlerType
        }
      >
        {({ getFieldValue }) =>
          getFieldValue("handlerType") === HandlerType.UseProvider &&
          getFieldValue("pollEnabled") && (
            <Form.Item name="poll" wrapperCol={{ offset: labelCol.span }}>
              {getCodeEditorItem({
                placeholder: t(K.POLLING_ITEM_PLACEHOLDER),
              })}
            </Form.Item>
          )
        }
      </Form.Item>
    ),
    [getCodeEditorItem, labelCol, t]
  );

  const callbackItem = useMemo(
    () => (
      <Form.Item
        noStyle
        // only hidden but Still Collect field value
        hidden={true}
        shouldUpdate={(prevValues, currentValues) =>
          prevValues.handlerType !== currentValues.handlerType ||
          prevValues.action !== currentValues.action ||
          prevValues.brickEventType !== currentValues.brickEventType
        }
      >
        {({ getFieldValue }) =>
          (getFieldValue("handlerType") === HandlerType.UseProvider ||
            (getFieldValue("handlerType") === HandlerType.CustomBrick &&
              getFieldValue("brickEventType") ===
                CustomBrickEventType.ExecuteMethod) ||
            hasCallbackActions.includes(getFieldValue("action"))) && (
            <Form.Item name="callback" label={t(K.CALLBACK_LABEL)}>
              {getCodeEditorItem()}
            </Form.Item>
          )
        }
      </Form.Item>
    ),
    [t, getCodeEditorItem]
  );

  const brickInteractionItem = useMemo(
    () => (
      <Form.Item
        noStyle
        shouldUpdate={(prevValues, currentValues) =>
          prevValues.handlerType !== currentValues.handlerType
        }
      >
        {({ getFieldValue }) =>
          getFieldValue("handlerType") === HandlerType.CustomBrick && (
            <Form.Item
              initialValue={CustomBrickEventType.SetProps}
              name="brickEventType"
              label={t(K.BRICK_EVENT_LABEL)}
            >
              <Radio.Group>
                <Radio.Button value={CustomBrickEventType.SetProps}>
                  {t(K.CUSTOM_EVENTS_SET_PROP)}
                </Radio.Button>
                <Radio.Button value={CustomBrickEventType.ExecuteMethod}>
                  {t(K.CUSTOM_EVENTS_USE_METHOD)}
                </Radio.Button>
              </Radio.Group>
            </Form.Item>
          )
        }
      </Form.Item>
    ),
    [t]
  );

  const brickItem = useMemo(
    () => (
      <Form.Item
        noStyle
        shouldUpdate={(prevValues, currentValues) =>
          prevValues.handlerType !== currentValues.handlerType
        }
      >
        {({ getFieldValue }) =>
          getFieldValue("handlerType") === HandlerType.CustomBrick && (
            <Form.Item label={t(K.BRICK_SELECTOR_LABEL)} required>
              <Input.Group compact>
                <Form.Item
                  name="selectorType"
                  noStyle
                  initialValue={useInCustomTemplate ? "targetRef" : "target"}
                >
                  <Select style={{ width: "105px" }}>
                    {useInCustomTemplate && (
                      <Select.Option value="targetRef">targetRef</Select.Option>
                    )}
                    <Select.Option value="target">target</Select.Option>
                  </Select>
                </Form.Item>
                <Form.Item
                  name="brickSelector"
                  noStyle
                  rules={[{ required: true }]}
                  messageVariables={{ label: "brickSelector" }}
                >
                  <AutoComplete
                    style={{ width: "calc(100% - 105px)" }}
                  ></AutoComplete>
                </Form.Item>
              </Input.Group>
            </Form.Item>
          )
        }
      </Form.Item>
    ),
    [useInCustomTemplate, t]
  );

  const brickMethodItem = useMemo(
    () => (
      <Form.Item
        noStyle
        shouldUpdate={(prevValues, currentValues) =>
          prevValues.handlerType !== currentValues.handlerType ||
          prevValues.brickEventType !== currentValues.brickEventType
        }
      >
        {({ getFieldValue }) =>
          getFieldValue("handlerType") === HandlerType.CustomBrick &&
          getFieldValue("brickEventType") ===
            CustomBrickEventType.ExecuteMethod && (
            <Form.Item
              name="method"
              label={t(K.USE_METHOD_LABEL)}
              rules={[{ required: true }]}
            >
              <AutoComplete></AutoComplete>
            </Form.Item>
          )
        }
      </Form.Item>
    ),
    [t]
  );

  const argsItem = useMemo(
    () => (
      <Form.Item
        noStyle
        shouldUpdate={(prevValues, currentValues) =>
          prevValues.handlerType !== currentValues.handlerType ||
          prevValues.brickEventType !== currentValues.brickEventType
        }
      >
        {({ getFieldValue }) =>
          ([HandlerType.UseProvider, HandlerType.BuiltinAction].includes(
            getFieldValue("handlerType")
          ) ||
            (getFieldValue("handlerType") === HandlerType.CustomBrick &&
              getFieldValue("brickEventType") ===
                CustomBrickEventType.ExecuteMethod)) && (
            <Form.Item name="args" label={t(K.ARGS_LABEL)}>
              {getCodeEditorItem({
                schemaRef:
                  "#/definitions/UseProviderResolveConf/properties/args",
              })}
            </Form.Item>
          )
        }
      </Form.Item>
    ),
    [t, getCodeEditorItem]
  );

  const propertiesItem = useMemo(
    () => (
      <Form.Item
        noStyle
        shouldUpdate={(prevValues, currentValues) =>
          prevValues.handlerType !== currentValues.handlerType ||
          prevValues.brickEventType !== currentValues.brickEventType
        }
      >
        {({ getFieldValue }) =>
          getFieldValue("handlerType") === HandlerType.CustomBrick &&
          getFieldValue("brickEventType") === CustomBrickEventType.SetProps && (
            <Form.Item name="properties" label={t(K.PROPERTIES_LABEL)}>
              {getCodeEditorItem()}
            </Form.Item>
          )
        }
      </Form.Item>
    ),
    [t, getCodeEditorItem]
  );

  const useResolvesItem = useMemo(
    () => (
      <>
        {handlerTypeItem}
        {ifItem}
        {providerTypeItem}
        {providerItem}
        {flowApiItem}
        {argsItem}
        <Form.Item noStyle>
          <Form.Item name="transform" label={t(K.TRANSFORM_LABEL)}>
            {getCodeEditorItem()}
          </Form.Item>
          <Form.Item
            name="transformFrom"
            label={t(K.TRANSFORM_FROM_LABEL)}
            tooltip={t(K.TRANSFORM_FROM_TOOLTIP)}
          >
            {getCodeEditorItem({ minLines: 3, mode: "text" })}
          </Form.Item>
          <Form.Item
            name="transformMapArray"
            label={t(K.TRANSFORM_MAP_ARRAY)}
            tooltip={t(K.TRANSFORM_MAP_ARRAY_TOOLTIP)}
            initialValue="auto"
          >
            <Radio.Group>
              <Radio value="auto"> auto </Radio>
              <Radio value={true}> true </Radio>
              <Radio value={false}> false </Radio>
            </Radio.Group>
          </Form.Item>
          <Form.Item name="onReject" label={t(K.REJECT_LABEL)}>
            {getCodeEditorItem()}
          </Form.Item>
        </Form.Item>
      </>
    ),
    [
      argsItem,
      flowApiItem,
      handlerTypeItem,
      ifItem,
      providerItem,
      providerTypeItem,
      getCodeEditorItem,
      t,
    ]
  );

  const allEventTypeItem = (
    <>
      {handlerTypeItem}
      {providerTypeItem}
      {brickInteractionItem}
      {ifItem}
      {actionItem}
      {segueIdItem}
      {historyPathItem}
      {providerItem}
      {flowApiItem}
      {useProviderMethod}
      {brickItem}
      {brickMethodItem}
      {argsItem}
      {propertiesItem}
      {pollEnabledItem}
      {pollItem}
      {callbackItem}
    </>
  );

  const getFormItem = (
    type: string,
    lifeCycle?: string
  ): React.ReactElement => {
    if (type === "lifeCycle" && lifeCycle === LifeCycle.UseResolves) {
      return useResolvesItem;
    } else {
      return allEventTypeItem;
    }
  };

  return (
    <Form
      name="eventConfigForm"
      form={form}
      labelCol={labelCol}
      wrapperCol={wrapperCol}
      onValuesChange={debounceHandleChange}
    >
      {getFormItem(type, lifeCycle)}
    </Form>
  );
}
Example #17
Source File: logic.block.tsx    From ui with GNU Affero General Public License v3.0 4 votes vote down vote up
LogicBlock: React.FC<Props> = ({
  form,
  field,
  fields,
  remove,
  index,
}) => {
  const { t } = useTranslation()
  const evaluator = useMath()

  return (
    <div
      style={{
        borderRight: '5px solid #DDD',
        paddingRight: 10,
      }}
    >
      <Form.Item
        name={[field.name as string, 'formula']}
        labelCol={{ span: 6 }}
        label={'Formula'}
        rules={[{ required: true, message: 'combine other fields' }]}
        extra={'Save form to get new @IDs and $slugs. (example: $slug < 21 or @id = 42)'}
      >
        <Mentions rows={1}>
          {fields.map((field) => (
            <Mentions.Option key={field.id} value={field.id}>
              {field.title}
            </Mentions.Option>
          ))}
        </Mentions>
      </Form.Item>

      <Form.Item noStyle shouldUpdate>
        {(form: FormInstance & { prefixName: string[] }) => {
          try {
            const defaults = {}

            fields.forEach((field) => {
              defaults[`@${field.id}`] = field.defaultValue

              if (field.slug) {
                defaults[`$${field.slug}`] = field.defaultValue
              }
            })

            const result = evaluator(
              form.getFieldValue([
                ...form.prefixName,
                field.name as string,
                'formula',
              ]),
              defaults
            )

            return (
              <Alert
                type={result ? 'success' : 'warning'}
                message={
                  result
                    ? 'would trigger action with current default values'
                    : 'would NOT trigger action with current default values'
                }
                style={{ marginBottom: 24 }}
              />
            )
          } catch (e) {
            return (
              <Alert
                message={(e as Error).message || 'Failed to process formula'}
                type={'error'}
                style={{ marginBottom: 24 }}
              />
            )
          }
        }}
      </Form.Item>
      <Form.Item name={[field.name as string, 'action']} labelCol={{ span: 6 }} label={'Action'}>
        <Select
          options={[
            {
              value: 'jumpTo',
              label: t('form:logic.action.jumpTo'),
            },
            {
              value: 'visible',
              label: t('form:logic.action.visible'),
            },
            {
              value: 'disable',
              label: t('form:logic.action.disable'),
            },
            {
              value: 'require',
              label: t('form:logic.action.require'),
            },
          ]}
        />
      </Form.Item>
      <Form.Item noStyle shouldUpdate>
        {(form: FormInstance & { prefixName: string[] }) => {
          return (
            <Form.Item
              hidden={
                form.getFieldValue([
                  ...form.prefixName, field.name as string, 'action',
                ]) !==
                'jumpTo'
              }
              labelCol={{ span: 6 }}
              label={t('form:logic.action.jumpTo')}
              rules={[{ required: true, message: 'Jump target is required' }]}
              extra={'after selecting field (works best with clickable values)'}
            >
              <Select
                options={fields
                  .filter((field) => !/NEW/i.test(field.id))
                  .map((field) => ({
                    value: field.id,
                    label: field.title,
                  }))}
              />
            </Form.Item>
          )
        }}
      </Form.Item>

      <Form.Item noStyle shouldUpdate>
        {(form: FormInstance & { prefixName: string[] }) => {
          return (
            <Form.Item
              hidden={
                form.getFieldValue([
                  ...form.prefixName, field.name as string, 'action',
                ]) !==
                'visible'
              }
              initialValue={true}
              labelCol={{ span: 6 }}
              label={t('form:logic.action.visible')}
              valuePropName={'checked'}
              getValueFromEvent={(checked: boolean) => (checked ? '1' : '')}
              getValueProps={(e: string) => ({ checked: !!e })}
            >
              <Checkbox />
            </Form.Item>
          )
        }}
      </Form.Item>

      <Form.Item noStyle shouldUpdate>
        {(form: FormInstance & { prefixName: string[] }) => {
          return (
            <Form.Item
              hidden={
                form.getFieldValue([
                  ...form.prefixName, field.name as string, 'action',
                ]) !==
                'disable'
              }
              initialValue={false}
              labelCol={{ span: 6 }}
              label={t('form:logic.action.disable')}
              valuePropName={'checked'}
              getValueFromEvent={(checked: boolean) => (checked ? '1' : '')}
              getValueProps={(e: string) => ({ checked: !!e })}
            >
              <Checkbox />
            </Form.Item>
          )
        }}
      </Form.Item>

      <Form.Item noStyle shouldUpdate>
        {(form: FormInstance & { prefixName: string[] }) => {
          return (
            <Form.Item
              hidden={
                form.getFieldValue([
                  ...form.prefixName, field.name as string, 'action',
                ]) !==
                'require'
              }
              initialValue={true}
              labelCol={{ span: 6 }}
              label={t('form:logic.action.require')}
              valuePropName={'checked'}
              getValueFromEvent={(checked: boolean) => (checked ? '1' : '')}
              getValueProps={(e: string) => ({ checked: !!e })}
            >
              <Checkbox />
            </Form.Item>
          )
        }}
      </Form.Item>

      <Form.Item>
        <div style={{ textAlign: 'right' }}>
          <Popconfirm
            placement={'right'}
            title={t('type:confirmDelete')}
            okText={t('type:deleteNow')}
            okButtonProps={{ danger: true }}
            onConfirm={() => {
              remove(index)
            }}
          >
            <Button danger>
              <DeleteOutlined />
            </Button>
          </Popconfirm>
        </div>
      </Form.Item>
    </div>
  )
}
Example #18
Source File: index.tsx    From electron with MIT License 4 votes vote down vote up
FormWrap: React.FC<BaseProps> = forwardRef((props, ref) => {
  const { mapSource, Footer, FooterProps, onValuesChange, onChange } = props;
  const [formInstance] = Form.useForm();
  const [fockUpdate, setFockUpdate] = useState(Date.now());
  const FormREF = useRef(null);
  useImperativeHandle(ref, () => FormREF.current);
  /**
   * @Message 组件渲染完成后重新渲染一次,让提供的 钩子内部可以访问到初始化的值
   * */
  useEffect(() => {
    setFockUpdate(Date.now());
  }, []);
  Reflect.set(FormWrap, 'fockUpdateDate', fockUpdate);

  if (!mapSource.length) return null;

  const AntdFormProps: Partial<BaseProps> = { ...props };
  delete AntdFormProps.mapSource;
  delete AntdFormProps.Footer;
  delete AntdFormProps.FooterProps;
  delete AntdFormProps.ref;
  return (
    <Form
      {...AntdFormProps}
      ref={FormREF}
      form={formInstance}
      /** 提交表单且数据验证成功后回调事件 */
      /** onFinish={onFinish || function () {}} */
      /** 提交表单且数据验证失败后回调事件 */
      /** onFinishFailed={onFinishFailed || function () {}} */
      /** 字段更新时触发回调事件 */
      /** onFieldsChange={onFieldsChange || function () {}} */
      /** 字段值更新时触发回调事件 */
      onValuesChange={(changedValues, values) => {
        setFockUpdate(Date.now());
        onValuesChange && onValuesChange(changedValues, values);
      }}
      onChange={(event) => {
        setFockUpdate(Date.now());
        onChange && onChange(event);
      }}
    >
      {mapSource.map((itemProps, index) => {
        const FormItemProps: Partial<BaseFormItemProps> = { ...itemProps };
        delete FormItemProps.render;
        delete FormItemProps.field;
        delete FormItemProps.title;
        FormItemProps.name = itemProps.field as string;

        const { render } = itemProps;
        if (render && typeof render === 'function' && !render(formInstance as FormInstance<never>)) {
          return null;
        }
        if (itemProps.title) {
          return (
            <Form.Item key={String(index)} {...FormItemProps}>
              {render(formInstance as FormInstance<never>)}
            </Form.Item>
          );
        }
        return (
          <Form.Item key={(itemProps.field as string) + String(index)} {...FormItemProps} shouldUpdate>
            {render(formInstance as FormInstance<never>)}
          </Form.Item>
        );
      })}
      {Footer === null ? null : (
        <Form.Item {...FooterProps}>
          {React.isValidElement(Footer) ? (
            Footer
          ) : (
            <>
              <Button type="primary" htmlType="submit">
                提交
              </Button>
              <Button htmlType="button" onClick={() => formInstance.resetFields()}>
                重置
              </Button>
            </>
          )}
        </Form.Item>
      )}
    </Form>
  );
})