antd#Checkbox TypeScript Examples

The following examples show how to use antd#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: CheckboxField.tsx    From jmix-frontend with Apache License 2.0 6 votes vote down vote up
export function CheckboxField({
  entityName, propertyName, formItemProps, value, onChange, ...rest
}: JmixFormFieldProps & CheckboxProps) {
  return (
    <JmixFormFieldWrapper entityName={entityName}
                          propertyName={propertyName}
                          formItemProps={{valuePropName: "checked", ...formItemProps}}
                          renderField={(isReadOnly) => (
                            <Checkbox value={value}
                                      onChange={onChange}
                                      disabled={isReadOnly}
                                      {...rest}
                            />
                          )}
    />
  );
}
Example #2
Source File: index.tsx    From drip-table with MIT License 6 votes vote down vote up
public render() {
    const config = this.props.schema;
    const uiProps = this.props.schema['ui:props'] || {};

    return (
      <Checkbox.Group
        {...filterAttributes(uiProps, 'options')}
        defaultValue={config.default as CheckboxGroupProps['defaultValue']}
        value={this.props.value}
        onChange={(value) => {
          this.props.onChange?.(value);
        }}
      >
        { (this.options as CheckboxOptionType[])?.map((option, i) => {
          if (typeof option === 'string') {
            option = { label: option, value: option };
          }
          return (
            <Checkbox key={i} value={option.value} style={option.style} disabled={option.disabled}>
              { option.icon && this.iconRender(option.icon) }
              { option.label }
              { option.description && (
                <Popover content={option.description}>
                  <QuestionCircleOutlined style={{ margin: '0 8px' }} />
                </Popover>
              ) }
            </Checkbox>
          );
        }) }
      </Checkbox.Group>
    );
  }
Example #3
Source File: CompareFilter.tsx    From posthog-foss with MIT License 6 votes vote down vote up
export function CompareFilter(): JSX.Element | null {
    const { insightProps } = useValues(insightLogic)
    const { compare, disabled } = useValues(compareFilterLogic(insightProps))
    const { setCompare } = useActions(compareFilterLogic(insightProps))

    // Hide compare filter control when disabled to avoid states where control is "disabled but checked"
    if (disabled) {
        return null
    }

    return (
        <Checkbox
            onChange={(e) => {
                setCompare(e.target.checked)
            }}
            checked={compare}
            style={{ marginLeft: 8, marginRight: 6 }}
            disabled={disabled}
        >
            Compare<span className="hide-lte-md"> to previous</span>
        </Checkbox>
    )
}
Example #4
Source File: Checkbox.tsx    From html2sketch with MIT License 6 votes vote down vote up
SwitchDemo: FC = () => {
  const { elements, ref } = useElements();

  return (
    <TestLayout elements={elements}>
      <div ref={ref}>
        <Checkbox checked>no checked</Checkbox>
        <Checkbox>Checkbox</Checkbox>
      </div>
    </TestLayout>
  );
}
Example #5
Source File: utils.tsx    From antdp with MIT License 6 votes vote down vote up
getItem = ({ attr, type, inputNode }: {
  attr?: Partial<ItemChildAttr<any, any>>;
  type?: ItemChildType;
  inputNode?: ((...arg: any[]) => React.ReactNode) | React.ReactNode;
}) => {
  let renderItem = undefined;
  if (type === 'Input') {
    const inputAttr = attr as InputProps;
    renderItem = <Input {...inputAttr} />;
  } else if (type === 'TextArea') {
    const inputAttr = attr as TextAreaProps;
    renderItem = <Input.TextArea {...inputAttr} />;
  } else if (type === 'InputNumber') {
    const inputAttr = attr as InputNumberProps;
    renderItem = <InputNumber {...inputAttr} />;
  } else if (type === 'AutoComplete') {
    const inputAttr = attr as AutoCompleteProps;
    renderItem = <AutoComplete {...inputAttr} />;
  } else if (type === 'Cascader') {
    const inputAttr = attr as CascaderProps;
    renderItem = <Cascader {...inputAttr} />;
  } else if (type === 'DatePicker') {
    const inputAttr = attr as DatePickerProps;
    renderItem = <DatePicker {...inputAttr} />;
  } else if (type === 'Rate') {
    const inputAttr = attr as RateProps;
    renderItem = <Rate {...inputAttr} />;
  } else if (type === 'Slider') {
    const inputAttr = attr as SliderSingleProps;
    renderItem = <Slider {...inputAttr} />;
  } else if (type === 'TreeSelect') {
    const inputAttr = attr as TreeSelectProps<any>;
    renderItem = <TreeSelect {...inputAttr} />;
  } else if (type === 'Select') {
    const inputAttr = attr as SelectProps<any>;
    renderItem = <Select {...inputAttr} />;
  } else if (type === 'Checkbox') {
    const inputAttr = attr as CheckboxGroupProps;
    renderItem = <Checkbox.Group {...inputAttr} />;
  } else if (type === 'Mentions') {
    const inputAttr = attr as MentionProps;
    renderItem = <Mentions {...inputAttr} />;
  } else if (type === 'Radio') {
    const inputAttr = attr as RadioProps;
    renderItem = <Radio.Group {...inputAttr} />;
  } else if (type === 'Switch') {
    const inputAttr = attr as SwitchProps;
    renderItem = <Switch {...inputAttr} />;
  } else if (type === 'TimePicker') {
    const inputAttr = attr as TimePickerProps;
    renderItem = <TimePicker {...inputAttr} />;
  } else if (type === 'Upload') {
    const inputAttr = attr as UploadProps;
    renderItem = <Upload {...inputAttr} />;
  } else if (type === 'RangePicker') {
    const inputAttr = attr as RangePickerProps;
    renderItem = <RangePicker {...inputAttr} />;
  } else if (type === 'Custom') {
    renderItem = inputNode;
  }
  return renderItem;
}
Example #6
Source File: index.tsx    From S2 with MIT License 6 votes vote down vote up
ShowList = ({ columns, setColumns, allChecked }) => {
  return (
    <Popover
      trigger="click"
      placement="bottomRight"
      title={
        <div>
          <Checkbox
            checked={allChecked}
            onChange={() =>
              allChecked ? setColumns([]) : setColumns([...initColumns])
            }
          >
            全选 {columns.length} / {initColumns.length}
          </Checkbox>
        </div>
      }
      content={initColumns.map((e, i) => (
        <div key={e}>
          <Checkbox
            checked={columns.includes(e)}
            onChange={() =>
              columns.includes(e)
                ? setColumns((fields) => fields.filter((item) => e !== item))
                : setColumns((fields) => [...fields, e])
            }
          >
            {e}
          </Checkbox>
        </div>
      ))}
    >
      <Button>隐藏列</Button>
    </Popover>
  );
}
Example #7
Source File: InformMethodsForm.tsx    From next-basics with GNU General Public License v3.0 6 votes vote down vote up
InformMethodsFormItem = forwardRef<
  HTMLDivElement,
  InformMethodsFormItemProps
>((props, ref) => {
  const { value, informMethodList, onChange } = props;

  const renderGroup = (): React.ReactElement => {
    const options = informMethodList.map((informMethods) => ({
      label: informMethods.description,
      value: informMethods.inform_type,
    }));

    return (
      <Checkbox.Group options={options} onChange={onChange} value={value} />
    );
  };

  return <span ref={ref}>{informMethodList && renderGroup()}</span>;
})
Example #8
Source File: index.tsx    From erda-ui with GNU Affero General Public License v3.0 6 votes vote down vote up
OptionContainer = ({ list, value, clickItem, optionRender, isMultiple, viewType }: ICompProps) => {
  return (
    <>
      {map(list, (item) => {
        const curOpt = find(value, (cItem) => `${cItem.value}` === `${item.value}`) as IOption;
        const checked = !!curOpt;
        const options = optionRender ? optionRender(item, (viewType || '').toLowerCase()) : item.label || item.value;
        return isMultiple ? (
          <Checkbox
            className="load-more-list-item"
            key={item.value}
            checked={checked}
            onChange={(e: any) => clickItem(item, e.target.checked)}
          >
            {options}
          </Checkbox>
        ) : (
          <div
            className={`load-more-list-item radio-item ${checked ? 'checked' : ''}`}
            key={item.value}
            onClick={() => clickItem(item, !checked)}
          >
            <div className="w-full flex justify-between items-center">
              <Ellipsis className="flex-1" title={options} />
              {checked ? <ErdaIcon type="check" className="ml-2 text-purple-deep" /> : null}
            </div>
          </div>
        );
      })}
    </>
  );
}
Example #9
Source File: index.tsx    From jetlinks-ui-antd with MIT License 6 votes vote down vote up
render() {
    const { checkedList } = this.state;
    return (
      <PageHeaderWrapper title="人员管理">
        <Card bordered={false}>
          <div style={{ borderBottom: '1px solid #E9E9E9' }}>
            <Checkbox
              indeterminate={!!checkedList.length && checkedList.length < plainOptions.length}
              onChange={this.onCheckAllChange}
              checked={checkedList.length === plainOptions.length}
            >
              Check all
            </Checkbox>
          </div>
          <br />
          <Checkbox.Group value={checkedList} options={plainOptions} onChange={this.onChange} />
        </Card>
      </PageHeaderWrapper>
    );
  }
Example #10
Source File: index.tsx    From ant-simple-draw with MIT License 6 votes vote down vote up
TaskList: FC<{ keyName: string }> = memo(({ keyName }) => {
  return (
    <>
      <Form.List name={[keyName, 'list']}>
        {(fields, { add, remove }) => (
          <>
            {fields.map(({ key, name, ...restField }) => (
              <Space
                key={key}
                style={{ display: 'flex', marginBottom: 8, justifyContent: 'space-around' }}
                align="baseline"
              >
                <Form.Item
                  {...restField}
                  name={[name, 'check']}
                  style={{ marginBottom: '16px' }}
                  valuePropName="checked"
                >
                  <Checkbox></Checkbox>
                </Form.Item>
                <Form.Item {...restField} name={[name, 'text']} style={{ marginBottom: '16px' }}>
                  <Input />
                </Form.Item>
                <MinusCircleOutlined onClick={() => remove(name)} title="移除" />
              </Space>
            ))}
            <Form.Item style={{ marginBottom: '16px' }}>
              <Button onClick={() => add()} block icon={<PlusOutlined />}>
                添加数据
              </Button>
            </Form.Item>
          </>
        )}
      </Form.List>
    </>
  );
})
Example #11
Source File: Checkbox.tsx    From tailchat with GNU General Public License v3.0 6 votes vote down vote up
MetaFormCheckbox: MetaFormFieldComponent = React.memo((props) => {
  const { name, label, value, onChange, error } = props;

  return (
    <Form.Item
      label={label}
      validateStatus={getValidateStatus(error)}
      help={error}
    >
      <Checkbox
        name={name}
        checked={Boolean(value)}
        onChange={(e) => onChange(e.target.checked)}
      >
        {label}
      </Checkbox>
    </Form.Item>
  );
})
Example #12
Source File: checkbox.tsx    From ui with GNU Affero General Public License v3.0 6 votes vote down vote up
Field = styled(Checkbox)`
  color: ${(props: Props) => props.design.colors.answer};
  border-color: ${(props: Props) => props.design.colors.answer};
  background: none;

  .ant-radio {
    .ant-radio-inner {
      border-color: ${(props: Props) => props.design.colors.answer};

      &::after {
        background: ${(props: Props) => props.design.colors.answer};
      }
    }

    &::after {
      border-color: ${(props: Props) => props.design.colors.answer};
    }
  }

  .anticon {
    color: ${(props: Props) => props.design.colors.answer};
  }
`
Example #13
Source File: index.tsx    From surveyo with Apache License 2.0 6 votes vote down vote up
function QuestionCard({question, updateQuestion, deleteQuestion}: any) {
  return (
    <div>
      <Card
        bordered={false}
        actions={[
          <DeleteOutlined
            key="setting"
            onClick={e => {
              deleteQuestion();
            }}
          />,
        ]}
      >
        <Input
          placeholder="Enter your question here"
          allowClear
          value={question.title}
          onChange={e => updateQuestion({...question, title: e.target.value})}
        />
        <Checkbox
          onChange={e =>
            updateQuestion({...question, required: e.target.checked})
          }
        >
          Required
        </Checkbox>
        <div>{createQuestionField({question, updateQuestion})}</div>
      </Card>
    </div>
  );
}
Example #14
Source File: BasicCheckbox.tsx    From datart with Apache License 2.0 6 votes vote down vote up
BasicCheckbox: FC<ItemLayoutProps<ChartStyleConfig>> = memo(
  ({ ancestors, translate: t = title => title, data: row, onChange }) => {
    const { comType, options, ...rest } = row;

    const handleCheckedChange = (e: CheckboxChangeEvent) => {
      onChange?.(ancestors, e.target?.checked, options?.needRefresh);
    };

    return (
      <StyledVizBasicCheckbox
        label={!options?.hideLabel ? t(row.label, true) : ''}
        labelCol={{ span: 20 }}
        wrapperCol={{ span: 4 }}
      >
        <Checkbox
          {...rest}
          {...options}
          checked={row.value}
          onChange={handleCheckedChange}
        />
      </StyledVizBasicCheckbox>
    );
  },
  itemLayoutComparer,
)
Example #15
Source File: index.tsx    From memex with MIT License 6 votes vote down vote up
renderInboxOptions() {
    return (
      <div className="inbox-drawer-header">
        <div>
          <Checkbox />
        </div>
        <div>
          <Tooltip placement="left" title="Commit">
            <Button
              style={{ border: 'none' }}
              onClick={() => {
                this.confirmCommitDocs();
              }}
              shape="circle"
              icon={<FileAddOutlined style={{ fontSize: 14 }} />}
            />
          </Tooltip>
          <Tooltip placement="left" title="Refresh">
            <Button
              style={{ border: 'none' }}
              onClick={() => {
                this.getInbox();
              }}
              shape="circle"
              icon={<ReloadOutlined style={{ fontSize: 14 }} />}
            />
          </Tooltip>
        </div>
      </div>
    );
  }
Example #16
Source File: index.tsx    From amiya with MIT License 6 votes vote down vote up
export default function Selection(props: AySelectionProps) {
  const { selection, rowKey, addSelection, removeSelection } = useContext(AySearchTableContext)
  const { disabledKeys, setDisabledKeys } = useContext(AyListContext)
  const { record, disabled, ...extendProps } = props

  const isChecked = selection.some((row: Record) => getKey(record, rowKey) === getKey(row, rowKey))
  const toggleChecked = (checked: boolean) => {
    if (checked) {
      addSelection([record])
    } else {
      removeSelection(null, record)
    }
  }

  useEffect(() => {
    if (disabled) {
      // 如果禁用了,没有注册过就补一个
      if (!disabledKeys.includes(getKey(record, rowKey))) {
        setDisabledKeys([...disabledKeys, getKey(record, rowKey)])
      }
    } else {
      // 如果没有禁用,注册过就删掉
      if (disabledKeys.includes(getKey(record, rowKey))) {
        setDisabledKeys(disabledKeys.filter((key: string) => key !== getKey(record, rowKey)))
      }
    }
  }, [disabled, disabledKeys])

  return (
    <Checkbox
      {...extendProps}
      disabled={disabled}
      checked={isChecked}
      onChange={e => toggleChecked(e.target.checked)}
    />
  )
}
Example #17
Source File: BatchExecutorPage.tsx    From yakit with GNU Affero General Public License v3.0 6 votes vote down vote up
YakScriptWithCheckboxLine: React.FC<YakScriptWithCheckboxLineProp> = (props) => {
    const {plugin} = props;
    const script = plugin;

    return <Card
        key={plugin.ScriptName} style={{marginBottom: 6}} size={"small"}
        bodyStyle={{paddingLeft: 12, paddingTop: 8, paddingBottom: 8, paddingRight: 12}}
        hoverable={true}
    >
        <div style={{width: "100%", display: "flex", flexDirection: "row"}}>
            <Checkbox style={{marginBottom: 0}} checked={props.selected} onChange={r => {
                if (r.target.checked) {
                    props.onSelected(plugin)
                } else {
                    props.onUnselected(plugin)
                }
            }}>
                <Space>
                    <OneLine maxWidth={270} overflow={"hidden"} title={plugin.ScriptName}>{plugin.ScriptName}</OneLine>
                    {script.Help && <Button
                        size={"small"} type={"link"} onClick={() => {
                        showModal({
                            width: "40%",
                            title: "Help", content: <>
                                {script.Help}
                            </>
                        })
                    }}
                        icon={<QuestionCircleOutlined/>}/>}
                </Space>
            </Checkbox>
            <div style={{flex: 1, textAlign: "right"}}>
                {script.Author && <Tooltip title={script.Author}>
                    <Button size={"small"} type={"link"} icon={<UserOutlined/>}/>
                </Tooltip>}
            </div>
        </div>
    </Card>
}
Example #18
Source File: RowCheckbox.tsx    From pcap2socks-gui with MIT License 6 votes vote down vote up
render() {
    return (
      <Row gutter={[this.props.gutter, this.props.tail ? 0 : this.props.gutter]}>
        <Col span={8} style={{ display: "flex", alignItems: "center", justifyContent: "center" }}>
          <Tooltip title={this.props.tooltip}>
            <span style={{ marginLeft: this.props.offset + "px" }}>{this.props.label}</span>
          </Tooltip>
        </Col>
        <Col span={16} style={{ display: "flex" }}>
          <Tooltip title={this.props.valueTooltip}>
            <Checkbox
              checked={this.props.value}
              onChange={(ev) => {
                if (this.props.onChange) {
                  this.props.onChange(ev.target.checked);
                }
              }}
            >
              {this.props.text}
            </Checkbox>
          </Tooltip>
        </Col>
      </Row>
    );
  }
Example #19
Source File: DataTableCell.tsx    From jmix-frontend with Apache License 2.0 5 votes vote down vote up
DataTableCell = <EntityType extends unknown>(props: DataTableCellProps<EntityType>): ReactNode => {

  const {type, attributeType, cardinality, name} = props.propertyInfo;

  if ((type as PropertyType) === 'Boolean') {
    return (
      <Checkbox
        checked={props.text as boolean}
        disabled={true}
      />
    );
  }

  if (attributeType === 'ENUM') {
    return (
      <EnumCell text={props.text} propertyInfo={props.propertyInfo} mainStore={props.mainStore!}/>
    );
  }

  if (attributeType === 'ASSOCIATION' && (cardinality === 'MANY_TO_MANY' || cardinality === 'ONE_TO_MANY') ||
    attributeType === 'COMPOSITION' && cardinality === 'ONE_TO_MANY') {
    const associatedEntities = props.record?.[name as keyof EntityType] as unknown as SerializedEntityProps[];
    const quantity = associatedEntities.length;
    const content = <>
      {associatedEntities.map((entity, idx) => <div key = {idx}>
        {entity._instanceName}
      </div>)}
    </>

    if (quantity > 2) {
      return <Popover content={content}>
        <Button type="link" style = {{ margin: 0 }}>
          <FormattedMessage id="jmix.nestedEntityField.xEntities" values={{ quantity }}/>
        </Button>
      </Popover>
    }

    const displayValue = associatedEntities?.map(entity => entity._instanceName).join(', ');

    return (
      <div>{displayValue}</div>
    );
  }

  return (
    <div>{toDisplayValue(props.text, props.propertyInfo)}</div>
  );
}
Example #20
Source File: DayPane.tsx    From ii-admin-base with MIT License 5 votes vote down vote up
CheckboxGroup = Checkbox.Group
Example #21
Source File: PropertyNamesSelect.tsx    From posthog-foss with MIT License 5 votes vote down vote up
PropertyNamesSearch = (): JSX.Element => {
    const { query, filteredProperties, isSelected } = useValues(propertySelectLogic)
    const { setQuery, toggleProperty } = useActions(propertySelectLogic)

    return (
        <>
            <Input
                onChange={({ target: { value } }) => setQuery(value)}
                allowClear
                className="search-box"
                placeholder="Search for properties"
                prefix={<SearchOutlined />}
            />
            <div className="search-results">
                {filteredProperties.length ? (
                    filteredProperties.map((property) => (
                        <Checkbox
                            key={property.name}
                            className={'checkbox' + (isSelected(property.name) ? ' checked' : '')}
                            checked={isSelected(property.name)}
                            onChange={() => toggleProperty(property.name)}
                        >
                            {property.highlightedNameParts.map((part, index) =>
                                part.toLowerCase() === query.toLowerCase() ? (
                                    <b key={index}>{part}</b>
                                ) : (
                                    <React.Fragment key={index}>{part}</React.Fragment>
                                )
                            )}
                        </Checkbox>
                    ))
                ) : (
                    <p className="no-results-message">
                        No properties match <b>“{query}”</b>. Refine your search to try again.
                    </p>
                )}
            </div>
        </>
    )
}
Example #22
Source File: resize.tsx    From S2 with MIT License 5 votes vote down vote up
ResizeConfig: FC<{
  setThemeCfg: (cb: (theme: ThemeCfg) => ThemeCfg) => void;
  setOptions: (cb: (prev: S2Options) => S2Options) => void;
}> = ({ setThemeCfg, setOptions }) => {
  const [showResizeArea, setShowResizeArea] = React.useState(false);
  const [rowResizeAffectCurrent, setRowResizeAffectCurrent] =
    React.useState(false);

  const onShowResizeAreaChange = (enable: boolean) => {
    const theme = {
      resizeArea: {
        backgroundOpacity: enable ? 1 : 0,
      },
    };
    setShowResizeArea(enable);
    setThemeCfg((prev) => customMerge({}, prev, { theme }));
  };

  const onSwitchRowResizeType = (enable: boolean) => {
    const opts = {
      interaction: {
        resize: {
          rowResizeType: enable ? ResizeType.CURRENT : ResizeType.ALL,
        },
      },
    };
    setRowResizeAffectCurrent(enable);
    setOptions((prev) => customMerge({}, prev, opts));
  };

  const onResizeActiveChange = (checkedAreas: string[]) => {
    const resize = RESIZE_CONFIG.reduce((cfg, item) => {
      const type = item.value;
      cfg[type] = checkedAreas.includes(type);
      return cfg;
    }, {});

    const updatedOptions = {
      interaction: {
        resize,
      },
    } as S2Options;

    setOptions((prev) => customMerge({}, prev, updatedOptions));
  };

  return (
    <>
      <Switch
        checkedChildren="宽高调整热区开"
        unCheckedChildren="宽高调整热区关"
        defaultChecked={showResizeArea}
        onChange={onShowResizeAreaChange}
      />
      <Checkbox.Group
        options={RESIZE_CONFIG}
        defaultValue={RESIZE_CONFIG.map((item) => item.value)}
        onChange={onResizeActiveChange}
      />
      <Switch
        checkedChildren="行高单行调整开"
        unCheckedChildren="行高单行调整关"
        defaultChecked={rowResizeAffectCurrent}
        onChange={onSwitchRowResizeType}
      />
    </>
  );
}
Example #23
Source File: ItemsType.tsx    From yforms with MIT License 5 votes vote down vote up
itemsType: YFormItemsType = {
  // 纯文本类
  input: { component: <Input />, formatStr: '请输入${label}' },
  password: { component: <Input.Password />, formatStr: '请输入${label}' },
  textarea: { component: <TextArea />, formatStr: '请输入${label}', modifyProps: textModify },
  money: { component: <Money />, formatStr: '请输入${label}', modifyProps: moneyModify },
  text: { component: <CustomTypography />, formatStr: '请输入${label}' },
  // 日期类
  datePicker: {
    component: <DatePicker />,
    formatStr: '请选择${label}',
    modifyProps: datePickerModify,
  },
  rangePicker: {
    component: <DatePicker.RangePicker />,
    formatStr: '请选择${label}',
    modifyProps: rangePickerModify,
  },
  // 单选复选类
  checkbox: { component: <Checkbox />, formatStr: '请选择${label}', modifyProps: checkboxModify },
  switch: { component: <Switch />, formatStr: '请选择${label}', modifyProps: switchModify },
  checkboxGroup: {
    component: <CheckboxGroup />,
    formatStr: '请选择${label}',
    modifyProps: checkboxGroupModify,
  },
  radio: { component: <Radio />, modifyProps: radioModify, formatStr: '请选择${label}' },
  select: {
    component: <Select {...searchSelect} />,
    formatStr: '请选择${label}',
    modifyProps: selectModify,
  },
  // 工具类
  oneLine: { component: <OneLine />, modifyProps: oneLineModify },
  card: { component: <Card /> },
  list: { component: <List />, hasFormItem: false },
  button: { component: <Button /> },
  secureButton: { component: <SecureButton /> },
  submit: { component: <Submit />, hasFormItem: false, modifyProps: submitModify },
  // 展示类
  custom: { modifyProps: CustomModify },
  view: { component: <ComponentView /> },
  space: { component: <Space />, modifyProps: SpaceModify },
}
Example #24
Source File: TypeItem.spec.tsx    From next-basics with GNU General Public License v3.0 5 votes vote down vote up
describe("TypeItem", () => {
  it("should work with simple type", () => {
    const props = {
      value: "string",
      onChange: jest.fn(),
    };
    const wrapper = mount(<TypeItem {...props} />);

    wrapper.find(Select).invoke("onChange")("boolean", null);
    expect(props.onChange).toHaveBeenCalledWith("boolean");

    wrapper.find(Select).invoke("onSearch")("object");

    jest.advanceTimersByTime(500);

    wrapper.find(Select).invoke("onChange")("DeployType", null);

    expect(props.onChange).toHaveBeenCalledWith("DeployType");

    wrapper.find(Checkbox).invoke("onChange")({ target: { checked: true } });

    expect(props.onChange).toHaveBeenCalledWith("DeployType[]");
  });

  it("should work with model type", () => {
    const mockChangeSizeFn = jest.fn();
    (useContractModels as jest.Mock).mockReturnValue([
      {
        q: "yy",
        modelList: [
          { name: "DeployType", namespaceId: "api.easyops.DeployType" },
        ],
      },
      jest.fn(),
      mockChangeSizeFn,
    ]);
    const props = {
      value: "DeployType",
      type: "model",
      onChange: jest.fn(),
    };
    const wrapper = mount(<TypeItem {...props} />);

    wrapper
      .find(Select)
      .prop("dropdownRender")(null)
      .props.children[1].props.onChange(100);

    expect(mockChangeSizeFn).toHaveBeenCalled();
  });
});
Example #25
Source File: Login.tsx    From yugong with MIT License 5 votes vote down vote up
Login: React.FC<Props> = ({ labelCol, wrapperCol, onLogin }) => {
  const onFinish = useCallback(
    (values: any) => {
      loading.show();
      login(values)
        .then(user => {
          loading.hide();
          if (onLogin instanceof Function) {
            onLogin(user)
          }
        }).catch(({ error }) => {
          loading.hide();
          message.error(error || '登录失败')
        });
    },
    [onLogin]
  );

  const onFinishFailed = (errorInfo: any) => {
    console.log("Failed:", errorInfo);
  };

  return (
    <>
      <h2 style={{ textAlign: "center", marginBottom: "20px" }}>登录</h2>
      <Form
        name="basic"
        labelCol={{ span: labelCol || 8 }}
        wrapperCol={{ span: wrapperCol || 16 }}
        initialValues={{ remember: true }}
        onFinish={onFinish}
        onFinishFailed={onFinishFailed}
      >
        <Form.Item
          label="用户名"
          name="username"
          rules={[{ required: true, message: "请输入用户名!" }]}
        >
          <Input />
        </Form.Item>

        <Form.Item
          label="密码"
          name="password"
          rules={[{ required: true, message: "请输入密码!" }]}
        >
          <Input.Password />
        </Form.Item>

        <Form.Item
          name="remember"
          valuePropName="checked"
          wrapperCol={{ offset: labelCol || 8, span: wrapperCol || 16 }}
        >
          <Checkbox>记住密码</Checkbox>
        </Form.Item>

        <Form.Item
          wrapperCol={{ offset: labelCol || 8, span: wrapperCol || 16 }}
        >
          <Button type="primary" htmlType="submit">
            登录
          </Button>
        </Form.Item>
      </Form>
    </>
  );
}
Example #26
Source File: table-config.tsx    From erda-ui with GNU Affero General Public License v3.0 5 votes vote down vote up
function TableConfig<T extends object = any>({
  slot,
  columns,
  setColumns,
  onReload,
  sortColumn = {},
  hideColumnConfig = false,
  hideReload = false,
  whiteHead,
}: TableConfigProps<T>) {
  const { column, order } = sortColumn;
  const onCheck = (checked: boolean, title: string) => {
    const newColumns = columns.map((item) => (item.title === title ? { ...item, hidden: !checked } : item));

    setColumns(newColumns);
  };

  const showLength = columns.filter((item) => !item.hidden).length;
  const columnsFilter = columns
    .filter((item) => item.title && item.dataIndex)
    .map((item: ColumnProps<T>) => (
      <div key={`${item.dataIndex}`}>
        <Checkbox
          className="whitespace-nowrap"
          checked={!item.hidden}
          onChange={(e) => onCheck(e.target.checked, item.title as string)}
          disabled={showLength === 1 && !item.hidden}
        >
          {typeof item.title === 'function' ? item.title({ sortColumn: column, sortOrder: order }) : item.title}
        </Checkbox>
      </div>
    ));

  return (
    <div className={`erda-table-filter flex justify-between ${whiteHead ? 'bg-white' : 'bg-default-02'}`}>
      <div className="erda-table-filter-content flex-1 flex items-center">
        <div className="flex-1">{slot}</div>
      </div>
      <div className="erda-table-filter-ops flex items-center">
        {!hideReload ? (
          <ErdaIcon
            size="20"
            className={`icon-hover ml-3 bg-hover p-1`}
            type="refresh"
            color="currentColor"
            onClick={onReload}
          />
        ) : null}
        {!hideColumnConfig ? (
          <Popover
            content={columnsFilter}
            trigger="click"
            placement="bottomRight"
            overlayClassName="erda-table-columns-filter"
            getPopupContainer={(triggerNode) => triggerNode.parentElement as HTMLElement}
          >
            <ErdaIcon type="config" size="20" className={`ml-3 icon-hover bg-hover p-1`} />
          </Popover>
        ) : null}
      </div>
    </div>
  );
}
Example #27
Source File: SaveAsModal.tsx    From gant-design with MIT License 5 votes vote down vote up
function SaveAsModal(props: SaveAsModalProps) {
  const {
    form: { getFieldDecorator, validateFieldsAndScroll },
    visible,
    loading,
    onCancel,
    onSubmit,
    ...nextProps
  } = props;


  const onOk = useCallback(() => {
    validateFieldsAndScroll((errors: any, values: object) => {
      if (errors) return;
      onSubmit && onSubmit(values);
    });
  }, [onSubmit]);

  return (
    <Receiver>
      {(locale) => <Modal
        visible={visible}
        title={locale.viewSaveAs}
        onCancel={onCancel}
        centered
        destroyOnClose
        footer={
          <div>
            <Button size="small" icon="close-circle" onClick={onCancel}>
              {locale.cancel}
            </Button>
            <Button size="small" type="primary" icon="save" loading={loading} onClick={onOk}>
              {locale.save}
            </Button>
          </div>
        }
        {...nextProps}
      >
        <Form>
          <Form.Item label={locale.viewName}>
            {getFieldDecorator('name', {
              rules: [{ required: true, message: locale.viewNameRequired }],
            })(<Input placeholder={locale.viewNamePlaceholder} maxLength={500} />)}
          </Form.Item>
          <Form.Item>
            {getFieldDecorator('isDefault', {
              valuePropName: 'checked',
              initialValue: false,
            })(<Checkbox>{locale.setDefault}</Checkbox>)}
          </Form.Item>
        </Form>
      </Modal>}
    </Receiver>
  );
}
Example #28
Source File: content.tsx    From jetlinks-ui-antd with MIT License 5 votes vote down vote up
Content: React.FC<Props> = props => {

  const {
    form: { getFieldDecorator },
    form,
  } = props;

  useEffect(() => {

  }, []);

  const onContentForm = async () => {
    form.validateFields((err, fileValue) => {
      if (err) return;
      props.save(fileValue.data);
    });
  };

  return (
    <Modal
      title='地图显示要素'
      visible
      okText="确定"
      cancelText="取消"
      onOk={() => {
        onContentForm();
      }}
      onCancel={() => props.close()}
    >
      <Form labelCol={{ span: 4 }} wrapperCol={{ span: 20 }}>
        <Form.Item key="data" label="显示要素">
          {getFieldDecorator('data', {
            initialValue: props.data,
          })(
            <Checkbox.Group options={[
              { label: '区域面(bg)', value: 'bg' },
              { label: '线/道路(road)', value: 'road' },
              { label: '标注(point)', value: 'point' },
              { label: '建筑物(building)', value: 'building' },
            ]}/>,
          )}
        </Form.Item>
      </Form>
    </Modal>
  );
}
Example #29
Source File: preview.tsx    From visual-layout with MIT License 5 votes vote down vote up
Preview: React.FC<{ projectService: ProjectService }> = ({
  projectService,
}) => {
  const page = projectService.getCurrentPage();
  const options = page?.options;

  return (
    <Popover
      content={
        <Checkbox.Group
          value={options?.previewStyle
            .filter(({ isCanUse }) => isCanUse)
            .map(({ key }) => key)}
          style={{ width: '100%' }}
          onChange={(checkedValue: CheckboxValueType[]) => {
            page.setOptions({
              previewStyle: options?.previewStyle.map(option => {
                return {
                  ...option,
                  isCanUse: checkedValue.includes(option.key) ? true : false,
                };
              }),
            });
          }}
        >
          {options?.previewStyle.map(style => {
            return (
              <Row key={style.key}>
                <Checkbox value={style.key}>{style?.title}</Checkbox>
              </Row>
            );
          })}
        </Checkbox.Group>
      }
      title="预览样式设置"
      placement="bottom"
    >
      <EyeOutlined style={{ fontSize: 20 }} />
    </Popover>
  );
}