antd#InputNumber TypeScript Examples

The following examples show how to use antd#InputNumber. 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: BigDecimalInput.test.tsx    From jmix-frontend with Apache License 2.0 6 votes vote down vote up
describe('BigDecimalInput', () => {
  const ref = React.createRef<typeof InputNumber>();
  let bigDecimalInputTestRenderer: ReactTestRenderer;
  it('Renders correctly with required props', () => {
    act(() => {
      bigDecimalInputTestRenderer = create(<BigDecimalInput ref={ref} />);
    });
  })

  it('Passes refs to the container component', () => {
    const input = bigDecimalInputTestRenderer.root.findByType(InputNumber).instance;
    expect(input).toEqual(ref.current);
  });

  it('Unmounts', () => {
    act(() => bigDecimalInputTestRenderer.unmount());
  })
})
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 (
      <InputNumber
        {...uiProps}
        max={uiProps.max as number}
        min={uiProps.min as number}
        precision={uiProps.precision as number}
        value={this.props.value}
        placeholder={uiProps.placeholder as string}
        disabled={uiProps.disabled as boolean}
        style={{ width: 240, ...uiProps.style }}
        onChange={(value) => {
          this.props.onChange?.(Number(value));
          if (config.validate) {
            const res = config.validate(Number(value));
            (res instanceof Promise ? res : Promise.resolve(res))
              .then((msg) => {
                this.props.onValidate?.(msg);
                return msg;
              })
              .catch((error) => { throw error; });
          }
        }}
      />
    );
  }
Example #3
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 #4
Source File: house.tsx    From S2 with MIT License 6 votes vote down vote up
RangeSelect = (props) => {
  const { data, dataName, onChange } = props;
  const min = Math.min(...data);
  const max = Math.max(...data);
  const [info, setInfo] = useState({ min, max });
  const handleChange = (value, key) => {
    const tempInfo = Object.assign({}, info);
    tempInfo[key] = value;
    setInfo(tempInfo);

    onChange({
      key: dataName,
      value: [tempInfo.min, tempInfo.max],
    });
  };

  return (
    <Space>
      <InputNumber
        placeholder={'最小值'}
        min={min}
        max={max}
        defaultValue={min}
        onChange={(e) => handleChange(e, 'min')}
      />
      <InputNumber
        placeholder={'最大值'}
        min={min}
        max={max}
        defaultValue={max}
        onChange={(e) => handleChange(e, 'max')}
      />
    </Space>
  );
}
Example #5
Source File: form.tsx    From XFlow with MIT License 6 votes vote down vote up
formItems: IFormSchema[] = [
  {
    name: 'nodeId',
    label: 'nodeId',
    rules: [{ required: true }],
    render: Input,
  },
  {
    name: 'stroke',
    label: 'stroke',
    rules: [{ required: true }],
    render: Input,
  },
  {
    name: 'strokeWidth',
    label: 'strokeWidth',
    render: InputNumber,
    renderProps: {
      min: 1,
      max: 7,
    },
  },
]
Example #6
Source File: index.ts    From brick-design with MIT License 6 votes vote down vote up
TYPES_TO_COMPONENT: any = {
  [PROPS_TYPES.object]: ObjectComponent,
  [PROPS_TYPES.objectArray]: ObjectArrayComponent,
  [PROPS_TYPES.string]: StringComponent,
  [PROPS_TYPES.function]: FunctionComponent,
  [PROPS_TYPES.numberArray]: NumberArray,
  [PROPS_TYPES.stringArray]: StringArray,
  [PROPS_TYPES.enum]: EnumComponent,
  [PROPS_TYPES.json]: JsonTextArea,
  [PROPS_TYPES.boolean]: Switch,
  [PROPS_TYPES.number]: InputNumber,
}
Example #7
Source File: NumberValidatorInput.spec.tsx    From next-basics with GNU General Public License v3.0 6 votes vote down vote up
describe("NumberValidatorInput", () => {
  it("should work", () => {
    const props = {
      value: [
        { method: "gt", value: 10 },
        { method: "lt", value: 20 },
      ],
      onAdd: jest.fn(),
      onRemove: jest.fn(),
      onChange: jest.fn(),
    };
    const wrapper = shallow(<NumberValidatorInput {...props} />);

    wrapper.find(Select).at(0).invoke("onChange")("gte", undefined);
    expect(props.onChange.mock.calls[0][0]).toEqual([
      { method: "gte", value: 10 },
      { method: "lt", value: 20 },
    ]);

    act(() => {
      wrapper.find(".iconBtn").last().simulate("click");
    });

    expect(props.onAdd).toHaveBeenCalled();

    act(() => {
      wrapper.find(".iconBtn").at(0).simulate("click");
    });

    expect(props.onRemove).toHaveBeenCalledWith(0);

    wrapper.find(InputNumber).at(0).invoke("onChange")(12);

    expect(props.onChange.mock.calls[1][0]).toEqual([
      { method: "gt", value: 12 },
      { method: "lt", value: 20 },
    ]);
  });
});
Example #8
Source File: property-field.tsx    From erda-ui with GNU Affero General Public License v3.0 6 votes vote down vote up
stringMinLengthField = (dataTempStorage: Obj) => {
  return {
    type: InputNumber,
    label: i18n.t('dop:Minimum length'),
    name: 'minLength',
    colSpan: 8,
    required: false,
    customProps: {
      className: 'w-full',
      precision: 0,
      ...DEFAULT_LENGTH_PROPS,
    },
    rules: [
      {
        validator: (_rule: any, value: number, callback: (msg?: string) => void) => {
          const maxLength = dataTempStorage?.maxLength;
          if (maxLength === undefined || maxLength >= value) {
            callback();
          } else {
            callback(i18n.t('dop:the minimum value must be less than or equal to the maximum value'));
          }
        },
      },
    ],
  };
}
Example #9
Source File: index.tsx    From scorpio-h5-design with MIT License 6 votes vote down vote up
export default function Font() {
  const { selectComponent, changeContainerPropsState } = useModel('bridge');
  const { color, fontSize, fontWeight } = selectComponent?.containerProps ?? {};

  return (
    <Descriptions column={1}>
      <Descriptions.Item label="颜色">
        <div className="font-color-input">
          <ColorPicker onChange={(value: string) => { changeContainerPropsState('color', value); }} value={color ?? '#fff'} />
        </div>
      </Descriptions.Item>
      <Descriptions.Item label="字号">
        <div className="font-size-weight">
          <Select
            value={fontWeight ?? 100}
            style={{ width: 120 }}
            onChange={(value) => { changeContainerPropsState('fontWeight', value); }}
          >
            <Select.Option value={100}>普通</Select.Option>
            <Select.Option value={800}>粗体</Select.Option>
          </Select>
          <InputNumber
            formatter={(value) => `${value}px`}
            parser={(value) => Number((value ?? '').replace('px', ''))}
            value={fontSize ?? 30}
            onChange={(value) => { changeContainerPropsState('fontSize', value); }}
          />
        </div>
      </Descriptions.Item>
    </Descriptions>
  );
}
Example #10
Source File: number.admin.tsx    From ui with GNU Affero General Public License v3.0 6 votes vote down vote up
NumberAdmin: React.FC<FieldAdminProps> = (props) => {
  const { t } = useTranslation()

  return (
    <div>
      <Form.Item
        label={t('type:number:default')}
        name={[props.field.name as string, 'defaultValue']}
        labelCol={{ span: 6 }}
      >
        <InputNumber precision={2} />
      </Form.Item>
    </div>
  )
}
Example #11
Source File: BasicInputNumber.tsx    From datart with Apache License 2.0 6 votes vote down vote up
BasicInputNumber: FC<ItemLayoutProps<ChartStyleConfig>> = memo(
  ({ ancestors, translate: t = title => title, data, onChange }) => {
    const { options, comType, ...rest } = data;
    const [formValue, debouncedUpdateValue] = useDebouncedFormValue(
      data?.value,
      {
        ancestors,
        needRefresh: options?.needRefresh,
        delay: 500,
      },
      onChange,
    );

    return (
      <BW label={t(data?.label, true)}>
        <InputNumber
          className="datart-ant-input-number"
          {...rest}
          {...options}
          value={formValue}
          onChange={debouncedUpdateValue}
          defaultValue={data?.default}
        />
      </BW>
    );
  },
  itemLayoutComparer,
)
Example #12
Source File: FunnelBinsPicker.tsx    From posthog-foss with MIT License 5 votes vote down vote up
export function FunnelBinsPicker(): JSX.Element {
    const { insightProps } = useValues(insightLogic)
    const { filters, numericBinCount } = useValues(funnelLogic(insightProps))
    const { setBinCount } = useActions(funnelLogic(insightProps))

    return (
        <Select
            id="funnel-bin-filter"
            dropdownClassName="funnel-bin-filter-dropdown"
            data-attr="funnel-bin-filter"
            defaultValue={BinCountAuto}
            value={filters.bin_count || BinCountAuto}
            onSelect={(count) => setBinCount(count)}
            dropdownRender={(menu) => {
                return (
                    <>
                        {menu}
                        <div>
                            <InputNumber
                                className="funnel-bins-custom-picker"
                                size="middle"
                                min={MIN}
                                max={MAX}
                                value={numericBinCount}
                                onChange={(count) => {
                                    const parsedCount = typeof count === 'string' ? parseInt(count) : count
                                    if (parsedCount) {
                                        setBinCount(parsedCount)
                                    }
                                }}
                            />{' '}
                            bins
                        </div>
                    </>
                )
            }}
            listHeight={440}
            bordered={false}
            dropdownMatchSelectWidth={false}
            dropdownAlign={ANTD_TOOLTIP_PLACEMENTS.bottomRight}
            optionLabelProp="label"
        >
            <Select.OptGroup label="Bin Count">
                {options.map((option) => {
                    if (option.value === 'custom') {
                        return null
                    }
                    return (
                        <Select.Option
                            className={clsx({ 'select-option-hidden': !option.display })}
                            key={option.value}
                            value={option.value}
                            label={
                                <>
                                    <BarChartOutlined /> {option.label}
                                </>
                            }
                        >
                            {option.label}
                        </Select.Option>
                    )
                })}
            </Select.OptGroup>
        </Select>
    )
}
Example #13
Source File: RelativeInput.tsx    From ant-extensions with MIT License 5 votes vote down vote up
RelativeInput: React.FC<BaseProps> = React.memo(({ value, onChange }) => {
  const { t } = useTranslation(I18nKey);
  const [parts, setParts] = useState<IDatePart>({ part: DateParts.HOUR, diff: 1, op: "-" });

  useEffect(() => {
    if (!isDate(value)) {
      setParts(getDateParts(value) || { part: DateParts.HOUR, diff: 1, op: "-" });
    }
  }, [value]);

  const setPart = useCallback(
    (key: keyof IDatePart, value: AnyObject) => {
      const newParts = { ...parts, [key]: value };
      setParts(newParts);
      onChange && onChange(`${newParts.part}${newParts.op}${newParts.diff}`);
    },
    [parts, onChange]
  );

  return (
    <Input.Group compact>
      <InputNumber
        min={1}
        onChange={(v) => setPart("diff", v)}
        value={parts.diff}
        style={{ width: 80 }}
      />
      <Select
        onChange={(v) => setPart("part", v.toString())}
        value={parts.part}
        style={{ width: 120 }}
      >
        {Object.values(DateParts)
          .slice(1)
          .map((key) => (
            <Select.Option key={key} value={key}>
              {t(`label.${key}`)}
            </Select.Option>
          ))}
      </Select>
      <Select onChange={(v) => setPart("op", v.toString())} value={parts.op} style={{ width: 120 }}>
        <Select.Option value="-">{t("label.-")}</Select.Option>
        <Select.Option value="+">{t("label.+")}</Select.Option>
      </Select>
    </Input.Group>
  );
})
Example #14
Source File: NumberComponent.tsx    From brick-design with MIT License 5 votes vote down vote up
function NumberComponent(props: NumberComponentPropsType) {
	const {
		units = UNITS,
		hasUnit = false,
		numberSpan = 13,
		value,
		unitSpan = 11,
		size,
		numberDisabled,
		onChange,
	} = props
	const { formatNumber, formatUnit = 'px' }: any = formatValue(
		value,
		units,
		hasUnit,
	)

	const [number, setNumber] = useState(formatNumber)
	const [unit, setUnit] = useState(formatUnit)
	const outputValue = hasUnit ? `${number}${unit}` : number

	useEffect(() => {
		const { formatNumber, formatUnit = 'px' }: any = formatValue(
			value,
			units,
			hasUnit,
		)
		setNumber(formatNumber)
		setUnit(formatUnit)
	}, [value, units, hasUnit,setNumber,setUnit])

	useEffect(() => {
		let timer = setTimeout(
			() => onChange && onChange(number && outputValue),
			100,
		)
		return () => clearTimeout(timer)
	}, [number, unit,onChange])

	return (
		<Row className={styles['number-unit-container']}>
			<Col span={numberSpan}>
				<InputNumber
					className={styles['input-num']}
					disabled={numberDisabled}
					value={number}
					size={size}
					onChange={(newNumber) => setNumber(newNumber)}
				/>
			</Col>
			{hasUnit && (
				<Col span={unitSpan}>
					<EnumComponent
						allowClear={false}
						value={unit}
						enumData={units}
						onChange={(newUnit) => setUnit(newUnit)}
					/>
				</Col>
			)}
		</Row>
	)
}
Example #15
Source File: NumberValidatorInput.tsx    From next-basics with GNU General Public License v3.0 5 votes vote down vote up
export function NumberValidatorInput(
  props: NumberValidatorInputProps
): React.ReactElement {
  const { t } = useTranslation(NS_FLOW_BUILDER);

  const handleChange = (
    value: string | number,
    field: "method" | "value",
    index: number
  ): void => {
    const newValue = update(props.value, {
      $splice: [[index, 1, { ...props.value[index], [field]: value }]],
    });
    props.onChange?.(newValue);
  };

  return (
    <div>
      {props.value?.map((item, index) => (
        <div key={index} className={styles.wrapper}>
          <Input.Group compact style={{ flex: 1 }}>
            <Select
              value={item.method}
              style={{ width: 100 }}
              placeholder={t(K.COMPARE_METHOD_PLACEHOLDER)}
              onChange={(value) => handleChange(value, "method", index)}
            >
              {compareMethodList.map((name) => (
                <Select.Option key={name} value={name}>
                  {name}
                </Select.Option>
              ))}
            </Select>
            <InputNumber
              value={item.value}
              style={{ width: "calc(100% - 100px)" }}
              min={0}
              step={1}
              placeholder={t(K.COMPARE_VALUE_PLACEHOLDER)}
              onChange={(value) =>
                handleChange(value as number, "value", index)
              }
            />
          </Input.Group>
          <Button
            className={editorStyles.iconBtn}
            type="link"
            style={{ flexBasis: 30 }}
            onClick={() => props.onRemove(index)}
          >
            <MinusOutlined />
          </Button>
        </div>
      ))}
      <Button
        className={editorStyles.iconBtn}
        type="link"
        onClick={props.onAdd}
      >
        <PlusCircleOutlined />
      </Button>
    </div>
  );
}
Example #16
Source File: NumberInput.tsx    From yugong with MIT License 5 votes vote down vote up
QuadrangularSelect: React.FC<Props> = ({
    unit,
    label,
    defaultValue,
    onChange,
    ...other
}) => {
    const ref = useRef(null);
    const moduleId = useSelector(
        (state: RootState) => state.activationItem.moduleId
    );

    useEffect(() => {
        if (ref.current) {
            (ref.current as any).blur();
        }
    }, [moduleId]);

    const [onDebounce, setOnDebounce] = useState(false);
    const onFocus = useCallback(() => {
        // 开启防抖禁止defaultValue回填
        setOnDebounce(true);
    }, []);
    const onBlur = useCallback(() => {
        // 关闭防抖允许defaultValue回填
        setValue(defaultValue);
        setOnDebounce(false);
    }, [defaultValue]);

    // 接管默认值
    const [value, setValue] = useState(defaultValue);

    useEffect(() => {
      if (!onDebounce) {
        setValue(defaultValue);
      } 
    }, [defaultValue, onDebounce]);

    const refChange = useSafeCallback(onChange);

    /**
     * 高频编辑防抖处理
     */
    const onChangeDebounce = useMemo(
        () =>
            throttle((e: number) => {
                refChange(e);
            }, 500),
        [refChange]
    );

    const onChangeValue = useCallback(
      (e) => {
        setValue(e);
        onChangeDebounce(e);
      },
      [onChangeDebounce],
    )
    
    return (
        <Row className={s.row} gutter={4}>
            <Col className={s.label} span={7}>
                {label || ''}
            </Col>
            <Col span={17}>
                <InputNumber
                    {...other}
                    onChange={onChangeValue}
                    onBlur={onBlur}
                    onFocus={onFocus}
                    value={value}
                    ref={ref}
                    addonAfter={<span className={s.suf}>{unit}</span>}
                />
            </Col>
        </Row>
    );
}
Example #17
Source File: antd.tsx    From erda-ui with GNU Affero General Public License v3.0 5 votes vote down vote up
CustomComp = ({ value, onChange }: { value: string; onChange: (v: string) => void }) => {
  // eslint-disable-next-line no-console
  console.log('render child');
  return <InputNumber style={{ width: '100%' }} value={value} onChange={onChange} />;
}
Example #18
Source File: section.tsx    From jetlinks-ui-antd with MIT License 5 votes vote down vote up
ArrayInputNumber = (props: ArrayInputNumberProps) => {
  const [value, setValue] = useState<number | undefined>(undefined);
  const [value2, setValue2] = useState<number | undefined>(undefined);

  useEffect(() => {
    if (props.value) {
      setValue(props.value[0]);
      setValue2(props.value[1]);
    }
  }, [props.value]);

  const chnageValue = useCallback((_value, type) => {
    let _arr = [value, value2];
    if (type === 1) {
      setValue(_value)
    } else {
      setValue2(_value)
    }
    _arr[type - 1] = _value;
    if (props.onChange) {
      props.onChange(
        {
          target: {
            value: _arr
          }
        }
      )
    }
  }, [value, value2]);

  return <div>
    <InputNumber value={value} onChange={(e) => {
      chnageValue(e, 1)
    }} placeholder='起始端口'/>
    至
    <InputNumber value={value2} onChange={(e) => {
      chnageValue(e, 2)
    }} placeholder='终止端口'/>
  </div>
}
Example #19
Source File: index.tsx    From ant-simple-draw with MIT License 5 votes vote down vote up
Border: FC<FormProps<valueType>> = memo(function Border({ value, onChange }) {
  const [border, setBorder] = useSetState<Partial<valueType>>({
    w: undefined,
    s: undefined,
    c: undefined,
  });

  const triggerChange = (changedValue: Partial<valueType>) => {
    onChange && onChange({ ...border, ...changedValue });
  };

  const handle = (flag: keyof valueType, val: any) => {
    if (flag === 'w' || flag === 's') {
      triggerChange({ [flag]: val });
    } else {
      triggerChange({ [flag]: val.target.value });
    }
  };
  useEffect(() => {
    if (value) {
      setBorder(value);
    }
  }, [value]);
  return (
    <Space style={{ display: 'flex' }}>
      <InputNumber
        min={0}
        style={{ width: '100%' }}
        onChange={(val) => handle('w', val)}
        value={border.w}
        title="宽度"
      />
      <Select
        data={lineList}
        valKey="key"
        valName="name"
        onChange={(val) => handle('s', val)}
        value={border.s}
      />
      <Input type={'color'} onChange={(val) => handle('c', val)} value={border.c} title="颜色" />
    </Space>
  );
})
Example #20
Source File: size.tsx    From visual-layout with MIT License 5 votes vote down vote up
Size: React.FC<SizeProps> = ({ value, onChange }) => {
  return (
    <>
      <Select
        defaultValue={models[0].key}
        onChange={key => {
          const modal = models.find(modal => modal.key === key);
          onChange?.({
            key: modal?.key || 'custom',
            width: modal?.width || value?.width || '0',
            height: modal?.height || value?.height || '0',
          });
        }}
      >
        <>
          <Option value="custom">自定义</Option>
          {models.map(({ key }) => {
            return (
              <Option value={key} key={key}>
                {key}
              </Option>
            );
          })}
        </>
      </Select>
      <div className={styles.inputNumbers}>
        <InputNumber
          min={0}
          value={value?.width ?? 0}
          formatter={value => `${value}px`}
          disabled={value?.key !== 'custom'}
          parser={value => value?.replace('px', '') || ''}
          onChange={width => {
            if (width) {
              onChange?.({
                key: 'custom',
                width: `${String(width)}`,
                height: value?.height || '0',
              });
            }
          }}
        />
        <span className={styles.close}>
          <CloseOutlined />
        </span>
        <InputNumber
          min={0}
          value={value?.height ?? 0}
          formatter={value => `${value}px`}
          disabled={value?.key !== 'custom'}
          parser={value => value?.replace('px', '') || ''}
          onChange={height => {
            if (height) {
              onChange?.({
                key: 'custom',
                width: value?.width || '0',
                height: `${String(height)}`,
              });
            }
          }}
        />
      </div>
    </>
  );
}
Example #21
Source File: index.tsx    From scorpio-h5-design with MIT License 5 votes vote down vote up
export default function Border() {
  const { selectComponent, changeContainerPropsState } = useModel('bridge');
  const { borderColor, borderWidth, borderStyle, borderRadius } = selectComponent?.containerProps ?? {};

  return (
    <Descriptions column={1}>
      <Descriptions.Item label="圆角">
        <InputNumber
          formatter={(value) => `${value}px`}
          parser={(value) => Number((value ?? '').replace('px', ''))}
          value={borderRadius ?? 0}
          onChange={(value) => { changeContainerPropsState('borderRadius', value); }}
        />
      </Descriptions.Item>
      <Descriptions.Item label="样式">
        <Radio.Group
          size="small"
          options={[
            { label: '无边框', value: 'none' },
            { label: '实线', value: 'solid' },
            { label: '虚线', value: 'dashed' },
            { label: '点线', value: 'dotted' },
          ]}
          onChange={(e) => { changeContainerPropsState('borderStyle', e.target.value); }}
          value={borderStyle ?? 'none'}
          optionType="button"
          buttonStyle="solid"
        />
      </Descriptions.Item>
      <Descriptions.Item label="宽度">
        <InputNumber
          formatter={(value) => `${value}px`}
          parser={(value) => (value ?? '').replace('px', '')}
          value={borderWidth ?? 0}
          onChange={(value) => { changeContainerPropsState('borderWidth', value); }}
        />
      </Descriptions.Item>
      <Descriptions.Item label="颜色">
        <ColorPicker
          onChange={(value: string) => { changeContainerPropsState('borderColor', value); }}
          value={borderColor}
        />
      </Descriptions.Item>
    </Descriptions>
  );
}
Example #22
Source File: index.tsx    From metaplex with Apache License 2.0 5 votes vote down vote up
RoyaltiesSplitter = (props: {
  creators: Array<UserValue>;
  royalties: Array<Royalty>;
  setRoyalties: Function;
  isShowErrors?: boolean;
}) => {
  return (
    <Col>
      <Row gutter={[0, 24]}>
        {props.creators.map((creator, idx) => {
          const royalty = props.royalties.find(
            royalty => royalty.creatorKey === creator.key,
          );
          if (!royalty) return null;

          const amt = royalty.amount;

          const handleChangeShare = (newAmt: number) => {
            props.setRoyalties(
              props.royalties.map(_royalty => {
                return {
                  ..._royalty,
                  amount:
                    _royalty.creatorKey === royalty.creatorKey
                      ? newAmt
                      : _royalty.amount,
                };
              }),
            );
          };

          return (
            <Col span={24} key={idx}>
              <Row
                align="middle"
                gutter={[0, 16]}
                style={{ margin: '5px auto' }}
              >
                <Col span={4} style={{ padding: 10 }}>
                  {creator.label}
                </Col>
                <Col span={3}>
                  <InputNumber<number>
                    min={0}
                    max={100}
                    formatter={value => `${value}%`}
                    value={amt}
                    parser={value => parseInt(value?.replace('%', '') ?? '0')}
                    onChange={handleChangeShare}
                    className="royalties-input"
                  />
                </Col>
                <Col span={4} style={{ paddingLeft: 12 }}>
                  <Slider value={amt} onChange={handleChangeShare} />
                </Col>
                {props.isShowErrors && amt === 0 && (
                  <Col style={{ paddingLeft: 12 }}>
                    <Text type="danger">
                      The split percentage for this creator cannot be 0%.
                    </Text>
                  </Col>
                )}
              </Row>
            </Col>
          );
        })}
      </Row>
    </Col>
  );
}
Example #23
Source File: index.tsx    From fe-v5 with Apache License 2.0 5 votes vote down vote up
export default function index(props: IProps) {
  const { preNamePrefix = [], namePrefix = ['options', 'standardOptions'] } = props;

  return (
    <Panel header='高级设置'>
      <>
        <Form.Item
          label={
            <div>
              单位{' '}
              <Tooltip
                overlayInnerStyle={{
                  width: 500,
                }}
                getTooltipContainer={() => document.body}
                title={
                  <div>
                    <div>默认会做 SI Prefixes 处理,如不想默认的处理可选择 none 关闭</div>
                    <div>Data(SI): 基数为 1000, 单位为 B、kB、MB、GB、TB、PB、EB、ZB、YB</div>
                    <div>Data(IEC): 基数为 1024, 单位为 B、KiB、MiB、GiB、TiB、PiB、EiB、ZiB、YiB</div>
                    <div>bits: b</div>
                    <div>bytes: B</div>
                  </div>
                }
              >
                <InfoCircleOutlined />
              </Tooltip>
            </div>
          }
          name={[...namePrefix, 'util']}
        >
          <Select suffixIcon={<CaretDownOutlined />} placeholder='auto' allowClear>
            <Option value='none'>none</Option>
            <OptGroup label='Data(SI)'>
              <Option value='bitsSI'>bits(SI)</Option>
              <Option value='bytesSI'>bytes(SI)</Option>
            </OptGroup>
            <OptGroup label='Data(IEC)'>
              <Option value='bitsIEC'>bits(IEC)</Option>
              <Option value='bytesIEC'>bytes(IEC)</Option>
            </OptGroup>
            <OptGroup label='百分比'>
              <Option value='percent'>百分比(0-100)</Option>
              <Option value='percentUnit'>百分比(0.0-1.0)</Option>
            </OptGroup>
            <OptGroup label='时间'>
              <Option value='seconds'>seconds</Option>
              <Option value='milliseconds'>milliseconds</Option>
              <Option value='humantimeSeconds'>humanize(seconds)</Option>
              <Option value='humantimeMilliseconds'>humanize(milliseconds)</Option>
            </OptGroup>
          </Select>
        </Form.Item>
        <Row gutter={10}>
          <Col span={8}>
            <Form.Item label='最小值' name={[...namePrefix, 'min']}>
              <InputNumber placeholder='auto' style={{ width: '100%' }} />
            </Form.Item>
          </Col>
          <Col span={8}>
            <Form.Item label='最大值' name={[...namePrefix, 'max']}>
              <InputNumber placeholder='auto' style={{ width: '100%' }} />
            </Form.Item>
          </Col>
          <Col span={8}>
            <Form.Item label='小数点' name={[...namePrefix, 'decimals']}>
              <InputNumber placeholder='auto' style={{ width: '100%' }} />
            </Form.Item>
          </Col>
        </Row>
      </>
    </Panel>
  );
}
Example #24
Source File: useMeterTableColumns.tsx    From condo with MIT License 5 votes vote down vote up
MeterReadingInput = ({ record, newMeterReadings, setNewMeterReadings }) => {
    const intl = useIntl()
    const AddMeterReadingPlaceholderMessage = intl.formatMessage({ id: 'pages.condo.meter.create.AddMeterReadingPlaceholder' })

    const meterId = get(record, ['meter', 'id'])
    const tariffNumber = get(record, 'tariffNumber')
    const meterResourceMeasure = get(record, ['meter', 'resource', 'measure'])
    const inputValue = get(newMeterReadings, [meterId, tariffNumber], '')

    const updateMeterReadingsValue = useCallback((oldMeterReadings, newTariffValue) => {
        const newReadingsFromOtherTariffs = get(oldMeterReadings, [meterId], {})
        const newMeterMeterReadings = pickBy({ ...newReadingsFromOtherTariffs, [tariffNumber]: newTariffValue })
        const pickMeterReadingCondition = meterReading => !isEmpty(meterReading)

        return pickBy({ ...oldMeterReadings, [meterId]: newMeterMeterReadings }, pickMeterReadingCondition)
    }, [meterId, tariffNumber])

    const meterReadingValueChangeHandler = useCallback((e) => {
        const newTariffValue = e ? String(e) : ''
        setNewMeterReadings(oldMeterReadings => updateMeterReadingsValue(oldMeterReadings, newTariffValue))
    }, [setNewMeterReadings, updateMeterReadingsValue])

    const handleInputContainerClick = useCallback(e => e.stopPropagation(), [])

    return (
        <div style={INPUT_CONTAINER_STYLE} onClick={handleInputContainerClick}>
            <InputNumber
                placeholder={AddMeterReadingPlaceholderMessage}
                css={inputNumberCSS}
                stringMode
                onChange={meterReadingValueChangeHandler}
                value={inputValue}
                formatter={inputMeterReadingFormatter}
                parser={inputMeterReadingParser}
                min={0}
            />
            <div style={METER_READING_INPUT_ADDON_STYLE}>
                {meterResourceMeasure}
            </div>
        </div>
    )
}
Example #25
Source File: BasicMarginWidth.tsx    From datart with Apache License 2.0 5 votes vote down vote up
BasicMarginWidth: FC<ItemLayoutProps<ChartStyleConfig>> = memo(
  ({ ancestors, translate: t = title => title, data, onChange }) => {
    const { value: mixedValue, label } = data;
    const widthModeTypes = ['px', '%'];

    const getMode = (value?: string | number) => {
      if (value === null || value === undefined) {
        return widthModeTypes[0];
      }
      return `${value}`.includes(widthModeTypes[1])
        ? widthModeTypes[1]
        : widthModeTypes[0];
    };

    const getNumber = (value?: string | number) => {
      if (value === null || value === undefined) {
        return 0;
      }
      return `${value}`.replaceAll(widthModeTypes[1], '');
    };

    const handleValueChange = newValue => {
      if (getMode(mixedValue) === widthModeTypes[0]) {
        onChange?.(ancestors, newValue);
      }
      if (getMode(mixedValue) === widthModeTypes[1]) {
        onChange?.(ancestors, (newValue || '') + widthModeTypes[1]);
      }
    };

    const handleModeChange = newMode => {
      if (newMode === widthModeTypes[0]) {
        onChange?.(ancestors, getNumber(mixedValue));
      }
      if (newMode === widthModeTypes[1]) {
        onChange?.(ancestors, getNumber(mixedValue) + widthModeTypes[1]);
      }
    };

    return (
      <StyledBasicMarginWidth
        label={t(label, true)}
        labelCol={{ span: 10 }}
        wrapperCol={{ span: 14 }}
      >
        <Space>
          <InputNumber
            className="datart-ant-input-number"
            value={getNumber(mixedValue)}
            onChange={handleValueChange}
          />
          <Select
            className="datart-ant-select"
            value={getMode(mixedValue)}
            onChange={handleModeChange}
          >
            <Select.Option value={widthModeTypes[0]}>
              {widthModeTypes[0]}
            </Select.Option>
            <Select.Option value={widthModeTypes[1]}>
              {widthModeTypes[1]}
            </Select.Option>
          </Select>
        </Space>
      </StyledBasicMarginWidth>
    );
  },
  itemLayoutComparer,
)
Example #26
Source File: index.tsx    From react_admin with MIT License 4 votes vote down vote up
FromAdd: React.FC<{}> = props => {
  const [visible, setVisible] = useState(false)
  const [form] = Form.useForm()

  const submitData = (values: any) => {
    setVisible(false)
    message.success('提交数据成功!!!')
    form.resetFields()
  }
  const onFinishFailed = (errorInfo: any) => {
    console.log('Failed:', errorInfo)
  }
  const layout = {
    labelCol: { span: 4 },
    wrapperCol: { span: 20 },
  }
  return (
    <>
      <Button
        onClick={() => setVisible(true)}
        size="large"
        type="primary"
        className="btn-bottom"
      >
        添加新数据
      </Button>
      <Modal
        title="提交数据"
        onCancel={() => setVisible(false)}
        visible={visible}
        footer={null}
      >
        <Form
          form={form}
          initialValues={{ ji: true, level: 2020 }}
          name="basic"
          onFinish={submitData}
          onFinishFailed={onFinishFailed}
          {...layout}
        >
          <Form.Item label="时间" name="time" rules={[{ required: true }]}>
            <DatePicker format="YYYY-MM-DD" />
          </Form.Item>
          <Form.Item label="赛事名称" name="title" rules={[{ required: true }]}>
            <Input placeholder="请输入赛事名称" />
          </Form.Item>
          <Form.Item label="赛事级别" name="ji" rules={[{ required: true }]}>
            <Radio.Group>
              <Radio value={true}>省赛</Radio>
              <Radio value={false}>校赛</Radio>
            </Radio.Group>
          </Form.Item>
          <Form.Item label="年度" name="level" rules={[{ required: true }]}>
            <InputNumber max={2020} min={2010} />
          </Form.Item>
          <Form.Item label="学校" name="school" rules={[{ required: true }]}>
            <Input placeholder="请输入学校" />
          </Form.Item>
          <Form.Item label="地址" name="address" rules={[{ required: true }]}>
            <Input placeholder="请输入地址" />
          </Form.Item>
          <Form.Item label="描述信息" name="desc" rules={[{ required: true }]}>
            <Input placeholder="请输入描述信息" />
          </Form.Item>
          <Form.Item wrapperCol={{ offset: 4, span: 20 }}>
            <Space>
              <Button type="primary" htmlType="submit">
                提交
              </Button>
              <Button
                onClick={() => form.resetFields()}
                type="default"
                htmlType="reset"
              >
                重置
              </Button>
            </Space>
          </Form.Item>
        </Form>
      </Modal>
    </>
  )
}
Example #27
Source File: palette.tsx    From jmix-frontend with Apache License 2.0 4 votes vote down vote up
palette = () => (
  <Palette>
    <Category name="Text">
      <Component name="Formatted Message">
        <Variant>
          <FormattedMessage />
        </Variant>
      </Component>
      <Component name="Heading">
        <Variant name="h1">
          <Typography.Title></Typography.Title>
        </Variant>
        <Variant name="h2">
          <Typography.Title level={2}></Typography.Title>
        </Variant>
        <Variant name="h3">
          <Typography.Title level={3}></Typography.Title>
        </Variant>
        <Variant name="h4">
          <Typography.Title level={4}></Typography.Title>
        </Variant>
        <Variant name="h5">
          <Typography.Title level={5}></Typography.Title>
        </Variant>
      </Component>
      <Component name="Text">
        <Variant>
          <Typography.Text></Typography.Text>
        </Variant>
        <Variant name="Secondary">
          <Typography.Text type="secondary"></Typography.Text>
        </Variant>
        <Variant name="Success">
          <Typography.Text type="success"></Typography.Text>
        </Variant>
        <Variant name="Warning">
          <Typography.Text type="warning"></Typography.Text>
        </Variant>
        <Variant name="Danger">
          <Typography.Text type="danger"></Typography.Text>
        </Variant>
        <Variant name="Disabled">
          <Typography.Text disabled></Typography.Text>
        </Variant>
      </Component>
    </Category>
    <Category name="Layout">
      <Component name="Divider">
        <Variant>
          <Divider />
        </Variant>
      </Component>

      <Component name="Grid">
        <Variant name="Simple Row">
          <Row></Row>
        </Variant>
        <Variant name="Two columns">
          <Row>
            <Col span={12}></Col>
            <Col span={12}></Col>
          </Row>
        </Variant>
        <Variant name="Three columns">
          <Row>
            <Col span={8}></Col>
            <Col span={8}></Col>
            <Col span={8}></Col>
          </Row>
        </Variant>
      </Component>

      <Component name="Space">
        <Variant>
          <Space />
        </Variant>
        <Variant name="Small">
          <Space size={"small"} />
        </Variant>
        <Variant name="Large">
          <Space size={"large"} />
        </Variant>
      </Component>
    </Category>
    <Category name="Controls">
      <Component name="Autocomplete">
        <Variant>
          <AutoComplete placeholder="input here" />
        </Variant>
      </Component>

      <Component name="Button">
        <Variant>
          <Button></Button>
        </Variant>
        <Variant name="Primary">
          <Button type="primary"></Button>
        </Variant>
        <Variant name="Link">
          <Button type="link"></Button>
        </Variant>
        <Variant name="Dropdown">
          <Dropdown
            trigger={["click"]}
            overlay={
              <Menu>
                <Menu.Item></Menu.Item>
                <Menu.Item></Menu.Item>
                <Menu.Item></Menu.Item>
              </Menu>
            }
          >
            <Button></Button>
          </Dropdown>
        </Variant>
      </Component>

      <Component name="Checkbox">
        <Variant>
          <Checkbox />
        </Variant>
      </Component>

      <Component name="Switch">
        <Variant>
          <Switch />
        </Variant>
      </Component>

      <Component name="Radio Group">
        <Variant>
          <Radio.Group>
            <Radio value={1}>A</Radio>
            <Radio value={2}>B</Radio>
            <Radio value={3}>C</Radio>
            <Radio value={4}>D</Radio>
          </Radio.Group>
        </Variant>
        <Variant name="Button">
          <Radio.Group>
            <Radio.Button value={1}>A</Radio.Button>
            <Radio.Button value={2}>B</Radio.Button>
            <Radio.Button value={3}>C</Radio.Button>
            <Radio.Button value={4}>D</Radio.Button>
          </Radio.Group>
        </Variant>
      </Component>

      <Component name="DatePicker">
        <Variant>
          <DatePicker />
        </Variant>
        <Variant name="Range">
          <DatePicker.RangePicker />
        </Variant>
      </Component>

      <Component name="TimePicker">
        <Variant>
          <TimePicker />
        </Variant>
        <Variant name="Range">
          <TimePicker.RangePicker />
        </Variant>
      </Component>

      <Component name="Input">
        <Variant>
          <Input />
        </Variant>
        <Variant name="Number">
          <InputNumber />
        </Variant>
      </Component>

      <Component name="Select">
        <Variant>
          <Select defaultValue="1">
            <Select.Option value="1">1</Select.Option>
            <Select.Option value="2">2</Select.Option>
          </Select>
        </Variant>
        <Variant name="Multiple">
          <Select defaultValue={["1"]} mode="multiple" allowClear>
            <Select.Option value="1">1</Select.Option>
            <Select.Option value="2">2</Select.Option>
          </Select>
        </Variant>
      </Component>

      <Component name="Link">
        <Variant>
          <Typography.Link href="" target="_blank"></Typography.Link>
        </Variant>
      </Component>

      <Component name="Slider">
        <Variant>
          <Slider defaultValue={30} />
        </Variant>
        <Variant name="Range">
          <Slider range defaultValue={[20, 50]} />
        </Variant>
      </Component>
    </Category>
    <Category name="Data Display">
      <Component name="Field">
        <Variant>
          <Field
            entityName={ENTITY_NAME}
            disabled={readOnlyMode}
            propertyName=""
            formItemProps={{
              style: { marginBottom: "12px" }
            }}
          />
        </Variant>
      </Component>
      <Component name="Card">
        <Variant>
          <Card />
        </Variant>
        <Variant name="With Title">
          <Card>
            <Card title="Card title">
              <p>Card content</p>
            </Card>
          </Card>
        </Variant>
        <Variant name="My custom card">
          <Card>
            <Card title="Card title">
              <p>Card content</p>
              <Avatar />
            </Card>
          </Card>
        </Variant>
      </Component>
      <Component name="Tabs">
        <Variant>
          <Tabs defaultActiveKey="1">
            <Tabs.TabPane tab="Tab 1" key="1">
              Content of Tab Pane 1
            </Tabs.TabPane>
            <Tabs.TabPane tab="Tab 2" key="2">
              Content of Tab Pane 2
            </Tabs.TabPane>
            <Tabs.TabPane tab="Tab 3" key="3">
              Content of Tab Pane 3
            </Tabs.TabPane>
          </Tabs>
        </Variant>
        <Variant name="Tab Pane">
          <Tabs.TabPane></Tabs.TabPane>
        </Variant>
      </Component>
      <Component name="Collapse">
        <Variant>
          <Collapse defaultActiveKey="1">
            <Collapse.Panel
              header="This is panel header 1"
              key="1"
            ></Collapse.Panel>
            <Collapse.Panel
              header="This is panel header 2"
              key="2"
            ></Collapse.Panel>
            <Collapse.Panel
              header="This is panel header 3"
              key="3"
            ></Collapse.Panel>
          </Collapse>
        </Variant>
      </Component>
      <Component name="Image">
        <Variant>
          <Image width={200} src="" />
        </Variant>
      </Component>
      <Component name="Avatar">
        <Variant>
          <Avatar icon={<UserOutlined />} />
        </Variant>
        <Variant name="Image">
          <Avatar src="https://joeschmoe.io/api/v1/random" />
        </Variant>
      </Component>
      <Component name="Badge">
        <Variant>
          <Badge count={1}></Badge>
        </Variant>
      </Component>
      <Component name="Statistic">
        <Variant>
          <Statistic title="Title" value={112893} />
        </Variant>
      </Component>
      <Component name="Alert">
        <Variant name="Success">
          <Alert message="Text" type="success" />
        </Variant>
        <Variant name="Info">
          <Alert message="Text" type="info" />
        </Variant>
        <Variant name="Warning">
          <Alert message="Text" type="warning" />
        </Variant>
        <Variant name="Error">
          <Alert message="Text" type="error" />
        </Variant>
      </Component>
      <Component name="List">
        <Variant>
          <List
            bordered
            dataSource={[]}
            renderItem={item => <List.Item></List.Item>}
          />
        </Variant>
      </Component>
    </Category>
    <Category name="Icons">
      <Component name="Arrow">
        <Variant name="Up">
          <ArrowUpOutlined />
        </Variant>
        <Variant name="Down">
          <ArrowDownOutlined />
        </Variant>
        <Variant name="Left">
          <ArrowLeftOutlined />
        </Variant>
        <Variant name="Right">
          <ArrowRightOutlined />
        </Variant>
      </Component>
      <Component name="Question">
        <Variant>
          <QuestionOutlined />
        </Variant>
        <Variant name="Circle">
          <QuestionCircleOutlined />
        </Variant>
      </Component>
      <Component name="Plus">
        <Variant>
          <PlusOutlined />
        </Variant>
        <Variant name="Circle">
          <PlusCircleOutlined />
        </Variant>
      </Component>
      <Component name="Info">
        <Variant>
          <InfoOutlined />
        </Variant>
        <Variant name="Circle">
          <InfoCircleOutlined />
        </Variant>
      </Component>
      <Component name="Exclamation">
        <Variant>
          <ExclamationOutlined />
        </Variant>
        <Variant name="Circle">
          <ExclamationCircleOutlined />
        </Variant>
      </Component>
      <Component name="Close">
        <Variant>
          <CloseOutlined />
        </Variant>
        <Variant name="Circle">
          <CloseCircleOutlined />
        </Variant>
      </Component>
      <Component name="Check">
        <Variant>
          <CheckOutlined />
        </Variant>
        <Variant name="Circle">
          <CheckCircleOutlined />
        </Variant>
      </Component>
      <Component name="Edit">
        <Variant>
          <EditOutlined />
        </Variant>
      </Component>
      <Component name="Copy">
        <Variant>
          <CopyOutlined />
        </Variant>
      </Component>
      <Component name="Delete">
        <Variant>
          <DeleteOutlined />
        </Variant>
      </Component>
      <Component name="Bars">
        <Variant>
          <BarsOutlined />
        </Variant>
      </Component>
      <Component name="Bell">
        <Variant>
          <BellOutlined />
        </Variant>
      </Component>
      <Component name="Clear">
        <Variant>
          <ClearOutlined />
        </Variant>
      </Component>
      <Component name="Download">
        <Variant>
          <DownloadOutlined />
        </Variant>
      </Component>
      <Component name="Upload">
        <Variant>
          <UploadOutlined />
        </Variant>
      </Component>
      <Component name="Sync">
        <Variant>
          <SyncOutlined />
        </Variant>
      </Component>
      <Component name="Save">
        <Variant>
          <SaveOutlined />
        </Variant>
      </Component>
      <Component name="Search">
        <Variant>
          <SearchOutlined />
        </Variant>
      </Component>
      <Component name="Settings">
        <Variant>
          <SettingOutlined />
        </Variant>
      </Component>
      <Component name="Paperclip">
        <Variant>
          <PaperClipOutlined />
        </Variant>
      </Component>
      <Component name="Phone">
        <Variant>
          <PhoneOutlined />
        </Variant>
      </Component>
      <Component name="Mail">
        <Variant>
          <MailOutlined />
        </Variant>
      </Component>
      <Component name="Home">
        <Variant>
          <HomeOutlined />
        </Variant>
      </Component>
      <Component name="Contacts">
        <Variant>
          <ContactsOutlined />
        </Variant>
      </Component>
      <Component name="User">
        <Variant>
          <UserOutlined />
        </Variant>
        <Variant name="Add">
          <UserAddOutlined />
        </Variant>
        <Variant name="Remove">
          <UserDeleteOutlined />
        </Variant>
      </Component>
      <Component name="Team">
        <Variant>
          <TeamOutlined />
        </Variant>
      </Component>
    </Category>
    <Category name="Screens">
      <Component name="ExampleCustomScreen">
        <Variant>
          <ExampleCustomScreen />
        </Variant>
      </Component>
      <Component name="CustomEntityFilterTest">
        <Variant>
          <CustomEntityFilterTest />
        </Variant>
      </Component>
      <Component name="CustomFormControls">
        <Variant>
          <CustomFormControls />
        </Variant>
      </Component>
      <Component name="CustomDataDisplayComponents">
        <Variant>
          <CustomDataDisplayComponents />
        </Variant>
      </Component>
      <Component name="CustomAppLayouts">
        <Variant>
          <CustomAppLayouts />
        </Variant>
      </Component>
      <Component name="CustomControls">
        <Variant>
          <CustomControls />
        </Variant>
      </Component>
      <Component name="ErrorBoundaryTests">
        <Variant>
          <ErrorBoundaryTests />
        </Variant>
      </Component>
      <Component name="TestBlankScreen">
        <Variant>
          <TestBlankScreen />
        </Variant>
      </Component>
      <Component name="CarEditor">
        <Variant>
          <CarEditor />
        </Variant>
      </Component>
      <Component name="CarBrowserCards">
        <Variant>
          <CarBrowserCards />
        </Variant>
      </Component>
      <Component name="CarBrowserList">
        <Variant>
          <CarBrowserList />
        </Variant>
      </Component>
      <Component name="CarBrowserTable">
        <Variant>
          <CarBrowserTable />
        </Variant>
      </Component>
      <Component name="CarCardsGrid">
        <Variant>
          <CarCardsGrid />
        </Variant>
      </Component>
      <Component name="FavoriteCars">
        <Variant>
          <FavoriteCars />
        </Variant>
      </Component>
      <Component name="CarCardsWithDetails">
        <Variant>
          <CarCardsWithDetails />
        </Variant>
      </Component>
      <Component name="CarTableWithFilters">
        <Variant>
          <CarTableWithFilters />
        </Variant>
      </Component>
      <Component name="CarMasterDetail">
        <Variant>
          <CarMasterDetail />
        </Variant>
      </Component>
      <Component name="FormWizardCompositionO2O">
        <Variant>
          <FormWizardCompositionO2O />
        </Variant>
      </Component>
      <Component name="FormWizardEditor">
        <Variant>
          <FormWizardEditor />
        </Variant>
      </Component>
      <Component name="FormWizardBrowserTable">
        <Variant>
          <FormWizardBrowserTable />
        </Variant>
      </Component>
      <Component name="CarMultiSelectionTable">
        <Variant>
          <CarMultiSelectionTable />
        </Variant>
      </Component>
      <Component name="DatatypesTestEditor">
        <Variant>
          <DatatypesTestEditor />
        </Variant>
      </Component>
      <Component name="DatatypesTestBrowserCards">
        <Variant>
          <DatatypesTestBrowserCards />
        </Variant>
      </Component>
      <Component name="DatatypesTestBrowserList">
        <Variant>
          <DatatypesTestBrowserList />
        </Variant>
      </Component>
      <Component name="DatatypesTestBrowserTable">
        <Variant>
          <DatatypesTestBrowserTable />
        </Variant>
      </Component>
      <Component name="DatatypesTestCards">
        <Variant>
          <DatatypesTestCards />
        </Variant>
      </Component>
      <Component name="AssociationO2OEditor">
        <Variant>
          <AssociationO2OEditor />
        </Variant>
      </Component>
      <Component name="AssociationO2OBrowserTable">
        <Variant>
          <AssociationO2OBrowserTable />
        </Variant>
      </Component>
      <Component name="AssociationO2MEditor">
        <Variant>
          <AssociationO2MEditor />
        </Variant>
      </Component>
      <Component name="AssociationO2MBrowserTable">
        <Variant>
          <AssociationO2MBrowserTable />
        </Variant>
      </Component>
      <Component name="AssociationM2OEditor">
        <Variant>
          <AssociationM2OEditor />
        </Variant>
      </Component>
      <Component name="AssociationM2OBrowserTable">
        <Variant>
          <AssociationM2OBrowserTable />
        </Variant>
      </Component>
      <Component name="AssociationM2MEditor">
        <Variant>
          <AssociationM2MEditor />
        </Variant>
      </Component>
      <Component name="AssociationM2MBrowserTable">
        <Variant>
          <AssociationM2MBrowserTable />
        </Variant>
      </Component>
      <Component name="CompositionO2OEditor">
        <Variant>
          <CompositionO2OEditor />
        </Variant>
      </Component>
      <Component name="CompositionO2OBrowserTable">
        <Variant>
          <CompositionO2OBrowserTable />
        </Variant>
      </Component>
      <Component name="CompositionO2MEditor">
        <Variant>
          <CompositionO2MEditor />
        </Variant>
      </Component>
      <Component name="CompositionO2MBrowserTable">
        <Variant>
          <CompositionO2MBrowserTable />
        </Variant>
      </Component>
      <Component name="DeeplyNestedTestEntityEditor">
        <Variant>
          <DeeplyNestedTestEntityEditor />
        </Variant>
      </Component>
      <Component name="DeeplyNestedO2MTestEntityTable">
        <Variant>
          <DeeplyNestedO2MTestEntityTable />
        </Variant>
      </Component>
      <Component name="DeeplyNestedO2MTestEntityEditor">
        <Variant>
          <DeeplyNestedO2MTestEntityEditor />
        </Variant>
      </Component>
      <Component name="IntIdEditor">
        <Variant>
          <IntIdEditor />
        </Variant>
      </Component>
      <Component name="IntIdBrowserTable">
        <Variant>
          <IntIdBrowserTable />
        </Variant>
      </Component>
      <Component name="IntIdBrowserCards">
        <Variant>
          <IntIdBrowserCards />
        </Variant>
      </Component>
      <Component name="IntIdBrowserList">
        <Variant>
          <IntIdBrowserList />
        </Variant>
      </Component>
      <Component name="IntIdentityIdCards">
        <Variant>
          <IntIdentityIdCards />
        </Variant>
      </Component>
      <Component name="IntIdentityIdEditor">
        <Variant>
          <IntIdentityIdEditor />
        </Variant>
      </Component>
      <Component name="IntIdentityIdBrowserTable">
        <Variant>
          <IntIdentityIdBrowserTable />
        </Variant>
      </Component>
      <Component name="IntIdentityIdBrowserCards">
        <Variant>
          <IntIdentityIdBrowserCards />
        </Variant>
      </Component>
      <Component name="IntIdentityIdBrowserList">
        <Variant>
          <IntIdentityIdBrowserList />
        </Variant>
      </Component>
      <Component name="StringIdCards">
        <Variant>
          <StringIdCards />
        </Variant>
      </Component>
      <Component name="StringIdMgtCardsEdit">
        <Variant>
          <StringIdMgtCardsEdit />
        </Variant>
      </Component>
      <Component name="StringIdBrowserCards">
        <Variant>
          <StringIdBrowserCards />
        </Variant>
      </Component>
      <Component name="StringIdBrowserList">
        <Variant>
          <StringIdBrowserList />
        </Variant>
      </Component>
      <Component name="StringIdBrowserTable">
        <Variant>
          <StringIdBrowserTable />
        </Variant>
      </Component>
      <Component name="WeirdStringIdEditor">
        <Variant>
          <WeirdStringIdEditor />
        </Variant>
      </Component>
      <Component name="WeirdStringIdBrowserCards">
        <Variant>
          <WeirdStringIdBrowserCards />
        </Variant>
      </Component>
      <Component name="WeirdStringIdBrowserList">
        <Variant>
          <WeirdStringIdBrowserList />
        </Variant>
      </Component>
      <Component name="WeirdStringIdBrowserTable">
        <Variant>
          <WeirdStringIdBrowserTable />
        </Variant>
      </Component>
      <Component name="BoringStringIdEditor">
        <Variant>
          <BoringStringIdEditor />
        </Variant>
      </Component>
      <Component name="BoringStringIdBrowserTable">
        <Variant>
          <BoringStringIdBrowserTable />
        </Variant>
      </Component>
      <Component name="TrickyIdEditor">
        <Variant>
          <TrickyIdEditor />
        </Variant>
      </Component>
      <Component name="TrickyIdBrowserTable">
        <Variant>
          <TrickyIdBrowserTable />
        </Variant>
      </Component>
    </Category>
  </Palette>
)
Example #28
Source File: index.tsx    From drip-table with MIT License 4 votes vote down vote up
private renderAttributeComponent(schema: DTGComponentPropertySchema, index: number, parentIndex: number) {
    const currentValue = (this.props.value || [])[parentIndex] || {};
    const options = schema['ui:props']?.options as LabeledValue[] || this.props.fieldOptions || [];
    if (schema['ui:type'] === 'radio') {
      return (
        <Radio.Group
          style={{ width: '100%' }}
          defaultValue={schema.default}
          value={currentValue[schema.name]}
          onChange={e => this.changeColumnItem(schema.name, e.target.value, parentIndex)}
        >
          {
            options?.map(
              (option, i) =>
                <Radio key={i} value={option.value}>{ option.label }</Radio>,
            )
          }
        </Radio.Group>
      );
    }
    if (schema['ui:type'] === 'input') {
      return (
        <Input
          style={{ width: '100%' }}
          defaultValue={schema.default as string}
          value={currentValue[schema.name] as string}
          placeholder={schema['ui:props']?.placeholder as string}
          onChange={e => this.changeColumnItem(schema.name, e.target.value, parentIndex)}
        />
      );
    }
    if (schema['ui:type'] === 'text') {
      return (
        <Input.TextArea
          style={{ width: '100%' }}
          autoSize={schema['ui:autoSize']}
          defaultValue={schema.default as string}
          value={currentValue[schema.name] as string}
          placeholder={schema['ui:props']?.placeholder as string}
          onChange={e => this.changeColumnItem(schema.name, e.target.value, parentIndex)}
        />
      );
    }
    if (schema['ui:type'] === 'auto-complete') {
      return (
        <AutoComplete
          style={{ width: '100%' }}
          defaultValue={schema.default as string}
          value={currentValue[schema.name] as string}
          options={options}
          onChange={value => this.changeColumnItem(schema.name, value, parentIndex)}
        />
      );
    }
    if (schema['ui:type'] === 'number') {
      return (
        <InputNumber
          style={{ width: '100%' }}
          min={schema['ui:minium']}
          max={schema['ui:maximum']}
          step={schema['ui:step']}
          defaultValue={Number(schema.default)}
          value={Number(currentValue[schema.name])}
          onChange={value => this.changeColumnItem(schema.name, Number(value), parentIndex)}
        />
      );
    }
    if (schema['ui:type'] === 'switch') {
      const value = typeof currentValue[schema.name] === 'undefined' ? schema.default : currentValue[schema.name];
      return (
        <Switch
          checked={value as boolean}
          checkedChildren={schema['ui:checkedContent']}
          unCheckedChildren={schema['ui:unCheckedContent']}
          onChange={checked => this.changeColumnItem(schema.name, checked, parentIndex)}
        />
      );
    }
    if (schema['ui:type'] === 'select') {
      const formattedValue = (schema['ui:mode'] === 'multiple' || schema['ui:mode'] === 'tags') && !Array.isArray(currentValue[schema.name]) ? [currentValue[schema.name]] : currentValue[schema.name];
      return (
        <Select
          showSearch
          style={{ width: '100%' }}
          mode={schema['ui:mode']}
          defaultValue={schema.default as SelectValue}
          value={formattedValue as SelectValue}
          options={options}
          onChange={value => this.changeColumnItem(schema.name, value, parentIndex)}
        />
      );
    }
    if (schema['ui:type'] === 'array-list') {
      return (
        <ArrayComponent
          theme={this.props.theme}
          schema={schema}
          value={currentValue[schema.name] as Record<string, unknown>[] | undefined}
          onChange={value => this.changeColumnItem(schema.name, value, parentIndex)}
          onValidate={msg => this.props.onValidate?.(msg)}
        />
      );
    }
    return null;
  }
Example #29
Source File: index.tsx    From vite-react-ts with MIT License 4 votes vote down vote up
Home: React.FC = () => {
  const [form] = Form.useForm();
  const list = useStore((state) => state.list);
  const loading = useStore((state) => state.loading);
  const editItem = useStore((state) => state.editItem);
  const { getList, removeList, editList, addList, setEditItem } = useStore.getState();

  const [visible, setVisible] = useState<boolean>(false);

  useEffect(() => {
    getList();
  }, []);

  const columns = [
    {
      title: '姓名',
      dataIndex: 'name',
      key: 'name',
    },
    {
      title: '年龄',
      dataIndex: 'age',
      key: 'age',
    },
    {
      title: '住址',
      dataIndex: 'address',
      key: 'address',
    },
    {
      title: 'Tags',
      key: 'tags',
      dataIndex: 'tags',
      // eslint-disable-next-line react/display-name
      render: (tags: any[]) => (
        <>
          {tags?.map((tag) => {
            let color = tag.length > 5 ? 'geekblue' : 'green';
            if (tag === 'loser') {
              color = 'volcano';
            }
            return (
              <Tag color={color} key={tag}>
                {tag.toUpperCase()}
              </Tag>
            );
          })}
        </>
      ),
    },
    {
      title: 'Action',
      key: 'action',
      // eslint-disable-next-line react/display-name
      render: (_: any, record: { key: string }) => (
        <Space size="middle">
          <Button
            type="primary"
            onClick={() => {
              setEditItem(record);
              setVisible(true);
              form.setFieldsValue(record);
            }}>
            修改
          </Button>
          <Button danger onClick={() => removeList(record.key)}>
            删除
          </Button>
        </Space>
      ),
    },
  ];

  const handleCancle = () => {
    setVisible(false);
  };

  const hanldeOk = () => {
    handleCancle();
    form.validateFields().then((res) => {
      console.log(res);
      editItem ? editList(res) : addList(res);
    });
  };
  console.log('list', list);
  return (
    <div>
      <h2>Home</h2>
      <Space>
        {/* <Button type="primary" onClick={() => setVisible(true)}>
          新增
        </Button>
        <Button onClick={() => getList()}>refresh</Button> */}
      </Space>
      <Card loading={loading}>
        <Table dataSource={list} columns={columns} />
      </Card>
      {/* transitionName=""和maskTransitionName=""是去除弹框动画属性 */}
      <Modal
        // transitionName=""
        // maskTransitionName=""
        title={editItem ? '修改信息' : '新增信息'}
        visible={visible}
        onOk={hanldeOk}
        onCancel={handleCancle}
        afterClose={() => {
          form.resetFields();
          setEditItem(undefined);
        }}>
        <Form form={form}>
          <Form.Item required label="姓名" name="name">
            <Input />
          </Form.Item>
          <Form.Item label="年龄" name="age">
            <InputNumber />
          </Form.Item>
          <Form.Item name="tags" label="Tags">
            <Select allowClear>
              <Option key="nice" value="nice">
                nice
              </Option>
              <Option key="developer" value="developer">
                developer
              </Option>
              <Option value="loser">loser</Option>
              <Option value="cool">cool</Option>
              <Option value="teacher">teacher</Option>
            </Select>
          </Form.Item>
        </Form>
      </Modal>
    </div>
  );
}