antd#InputNumber JavaScript 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: alerts_confirm.js    From doraemon with GNU General Public License v3.0 6 votes vote down vote up
render() {
    const { getFieldDecorator } = this.props.form
    const { visible } = this.state

    return (
      <Modal
        title="报警确认"
        visible={visible}
        onOk={this.handleOk}
        onCancel={this.handleCancel}
        maskClosable={false}
      >
        <Form {...formItemLayout} layout="horizontal">
          <Form.Item label="确认时长(分)">
            {getFieldDecorator('duration', {
              rules: [
                { required: true, message: '请输入时长' },
              ],
            })(<InputNumber style={{ width: '100%' }} />)}
          </Form.Item>
        </Form>
      </Modal>
    )
  }
Example #2
Source File: index.js    From gobench with Apache License 2.0 6 votes vote down vote up
render() {
    return (
      <div>
        <h5 className="mb-3">
          <strong>Basic</strong>
        </h5>
        <div className="mb-5">
          <InputNumber min={1} max={10} defaultValue={3} onChange={onChange} />
        </div>
      </div>
    )
  }
Example #3
Source File: skuTable.js    From egoshop with Apache License 2.0 6 votes vote down vote up
renderColumns({ text, record, index, dataIndex }) {
        const { onChange, skus } = this.props
        return (
            <InputNumber
                value={text}
                onChange={(e) => {
                    const _skus = [...skus]
                    _skus[index][dataIndex] = e
                    onChange(_skus)
                }}
            />
        )
    }
Example #4
Source File: postageType.js    From camel-store-admin with Apache License 2.0 6 votes vote down vote up
render(){
    const { set_postage, disabled } = this.conversionObject();

    return(
      <Fragment>
        <List
          className={styles.postage}
          dataSource={set_postage}
          itemLayout="horizontal"
          renderItem={item => (
            <List.Item
              actions={[<a onClick={() => this.disthandle(item,'',item.key)} style={{color:'red'}}>删除</a>]}>
              配送距离(km)
              <InputNumber style={{width:60}} size="small" value= {item.start} min={0}
                           disabled={disabled}
                           onChange={(e) => this.disthandle(e,'start',item.key) }/>
              <span style={{marginLeft: 10,marginRight: 10}}>-</span>
              <InputNumber style={{width:60}} size="small" value= {item.end} min={0}
                           disabled={disabled}
                           onChange={(e) => this.disthandle(e,'end',item.key) }/>
              <span style={{marginLeft: 30,marginRight: 10}}>运费金额</span>
              <InputNumber style={{width:60}} size="small" value= {item.cost} min={0}
                           disabled={disabled}
                           onChange={(e) => this.disthandle(e,'cost',item.key) }/>
            </List.Item>
          )}
          footer={(<Button size="small" disabled={disabled} type="dashed" style={{width:'100%'}} onClick={this.adddist}>添加</Button>)}
        />
      </Fragment>
    )
  }
Example #5
Source File: index.jsx    From erp-crm with MIT License 6 votes vote down vote up
export default function MoneyInputFormItem({ updatePrice, value = 0, readOnly = false }) {
  const money = useMoney();

  return (
    <Form.Item>
      <InputNumber
        readOnly={readOnly}
        className="moneyInput"
        onChange={updatePrice}
        value={value}
        controls={false}
        addonAfter={money.currencyPosition === 'after' ? money.currencySymbol : undefined}
        addonBefore={money.currencyPosition === 'before' ? money.currencySymbol : undefined}
        formatter={(value) => money.amountFormatter({ amount: value })}
      />
    </Form.Item>
  );
}
Example #6
Source File: Settings.js    From 4IZ268-2021-2022-ZS with MIT License 6 votes vote down vote up
RefetchIntervalInput = () => {

    const refetchInterval = usePersonalSettings((state) => state.refetchInterval)
    const setRefetchInterval = usePersonalSettings((state) => state.setRefetchInterval)
    const autoRefetch = usePersonalSettings((state) => state.autoRefetch)
    const setAutoRefetch = usePersonalSettings((state) => state.setAutoRefetch)

    const onChange = (val) => {
        if (val >= 15 && val < 1000) {
            setRefetchInterval(val * 1000)
        }
    }

    const onDisableChange = (val) => {
        setAutoRefetch(val)
    }

    return (
        <>
            <span>Automatické aktualizace:</span>
            <br />
            <Switch checked={autoRefetch} onChange={onDisableChange} />
            {autoRefetch ?
                <>
                    <br />
                    <span>Aktualizace po: (s)</span>
                    <br />
                    <InputNumber value={refetchInterval / 1000} onChange={onChange} min={15} max={1000} />
                </>
                : null}
        </>
    )
}
Example #7
Source File: disabled.jsx    From virtuoso-design-system with MIT License 6 votes vote down vote up
render() {
    return (
      <>
        <InputNumber min={1} max={10} disabled={this.state.disabled} defaultValue={3} />
        <div style={{ marginTop: 20 }}>
          <Button onClick={this.toggle} type="primary">
            Toggle disabled
          </Button>
        </div>
      </>
    );
  }
Example #8
Source File: create-edit-maintain.js    From doraemon with GNU General Public License v3.0 5 votes vote down vote up
render() {
    const { getFieldDecorator } = this.props.form
    const { id, visiable } = this.state
    return (
      <Modal
        title={id ? '编辑维护组' : '添加维护组'}
        visible={visiable}
        onOk={this.handleOk}
        onCancel={this.handleCancel}
        maskClosable={false}
      >
        <Form {...formItemLayout} layout="horizontal">
          <Form.Item label="维护时间段" required style={{ marginBottom: 0 }}>
            <Form.Item style={{ display: 'inline-block', width: 'calc(50% - 10px)' }}>
              {getFieldDecorator('time_start', {
                rules: [{ type: 'object', required: true, message: 'Please select time!' }],
              })(<TimePicker style={{ width: '100%' }} format="HH:mm" />)}
            </Form.Item>
            <span style={{ display: 'inline-block', width: '20px', textAlign: 'center' }}>~</span>
            <Form.Item style={{ display: 'inline-block', width: 'calc(50% - 10px)' }}>
              {getFieldDecorator('time_end', {
                rules: [
                  { type: 'object', required: true, message: 'Please select time!' },
                ],
              })(<TimePicker style={{ width: '100%' }} format="HH:mm" />)}
            </Form.Item>
          </Form.Item>
          <Form.Item label="维护月" required>
            {getFieldDecorator('month', {
              rules: [
                { type: 'array', required: true, message: 'Please select month' },
              ]
            })(<Select mode="multiple">
              { new Array(12).fill(1).map((item, index) => (<Option value={index + 1}>{index + 1}</Option>))}
            </Select>)}
          </Form.Item>
          <Form.Item label="维护日期" required style={{ marginBottom: 0 }}>
            <Form.Item style={{ display: 'inline-block', width: 'calc(50% - 10px)' }}>
              {getFieldDecorator('day_start', {
                rules: [{ required: true, message: 'Please input day!' }],
              })(<InputNumber style={{ width: '100%' }} format="HH:mm" />)}
            </Form.Item>
            <span style={{ display: 'inline-block', width: '20px', textAlign: 'center' }}>~</span>
            <Form.Item style={{ display: 'inline-block', width: 'calc(50% - 10px)' }}>
              {getFieldDecorator('day_end', {
                rules: [
                  { required: true, message: 'Please input day!' },
                  { validator: this.dayEndValid },
                ],
              })(<InputNumber style={{ width: '100%' }} format="HH:mm" />)}
            </Form.Item>
          </Form.Item>
          <Form.Item label="有效期">
            {getFieldDecorator('valid', {
              rules: [
                { required: true, message: '请填写有效期' },
              ],
            })(<DatePicker
              style={{ width: '100%' }}
              showTime={{ defaultValue: moment('00:00:00', 'HH:mm:ss') }}
              format="YYYY-MM-DD HH:mm:ss"
              placeholder={['请填写有效期']}
            />)}
          </Form.Item>
          <Form.Item label="机器列表">
            {getFieldDecorator('hosts', {
              rules: [
                { required: true, message: '请输入成员' },
              ],
            })(<Input.TextArea autoSize={{ minRows: 2 }} />)}
          </Form.Item>
        </Form>
      </Modal>
    )
  }
Example #9
Source File: index.js    From topology-react with MIT License 5 votes vote down vote up
Layout = ({ form: { getFieldDecorator, validateFields } }) => {

  const startLayout = () => {
    validateFields((err, value) => {
      if(err) return;
      if(canvas) {
        layout(canvas.data.pens, value);
        canvas.updateProps(true, canvas.data.pens);
      }
    });
  }

  return (
    <Form {...formLayout} style={{ margin: '10px 10px' }}>
      <Row>
        <Col span={24}>
          <Form.Item label="最大宽度">
            {getFieldDecorator('maxWidth', {
              initialValue: 1000
            })(<InputNumber style={{ width: '100%' }} min={0} placeholder="请输入最大宽度" />)}
          </Form.Item>
        </Col>
        <Col span={24}>
          <Form.Item label="节点宽度">
            {getFieldDecorator('nodeWidth', {
              initialValue: 0
            })(<InputNumber style={{ width: '100%' }} min={0} placeholder="请输入节点宽度" />)}
          </Form.Item>
        </Col>
        <Col span={24}>
          <Form.Item label="节点高度">
            {getFieldDecorator('nodeHeight', {
              initialValue: 0
            })(<InputNumber style={{ width: '100%' }} min={0} placeholder="请输入节点高度" />)}
          </Form.Item>
        </Col>

        <Col span={24}>
          <Form.Item label="水平个数">
            {getFieldDecorator('maxCount', {
              initialValue: 0
            })(<InputNumber style={{ width: '100%' }} min={0} placeholder="请输入水平个数" />)}
          </Form.Item>
        </Col>

        <Col span={24}>
          <Form.Item label="水平间距">
            {getFieldDecorator('spaceWidth', {
              initialValue: 30
            })(<InputNumber style={{ width: '100%' }} min={0} placeholder="请输入水平间距" />)}
          </Form.Item>
        </Col>
        <Col span={24}>
          <Form.Item label="垂直间距">
            {getFieldDecorator('spaceHeight', {
              initialValue: 30
            })(<InputNumber style={{ width: '100%' }} min={0} placeholder="请输入垂直间距" />)}
          </Form.Item>
        </Col>

        <Col span={24}>
          <Button
            type="primary"
            style={{ marginLeft: 22, width: 245 }}
            onClick={() => startLayout()}
          >
            开始排版
          </Button>
        </Col>
      </Row>
    </Form>
  );
}
Example #10
Source File: index.js    From scalable-form-platform with MIT License 5 votes vote down vote up
render() {
        let options = this.props.options;
        let schema = this.props.schema,
            readonly = this.props.readonly,
            autofocus = this.props.autofocus,
            onChange = this.props.onChange,
            disabled = this.props.disabled,
            value = this.props.value;
        let max = (typeof schema.maximum === 'number') ? schema.maximum : Infinity;
        let min = (typeof schema.minimum === 'number') ? schema.minimum : -Infinity;
        let step = schema.multipleOf || 1;
        //解析schema中约定的_errorType字段,用来标识是validate中哪种类型校验不通过
        let validateMessage = '';
        let {_errorType, validate, ...otherOptions} = options;
        otherOptions = this._filterSystemOptions(otherOptions);
        _errorType = _errorType || '';
        if (_errorType !== '' && typeof validate !== 'undefined') {
            validateMessage = this._getValidateMessage(_errorType, validate);
        }

        return (
            <div className={classnames({
                'ant-form-item-control': true,
                'xform-custom-widget': true,
                'xform-custom-number-input': true,
                'has-error': _errorType !== ''
            })}>
                <InputNumber
                    max={max}
                    min={min}
                    step={step}
                    value={value}
                    disabled={disabled}
                    readOnly={readonly}
                    autoFocus={autofocus}
                    onChange={(value) => {
                        onChange(value);
                    }}
                    {...otherOptions}
                />
                <div className="ant-form-explain">{validateMessage}</div>
            </div>
        );
    }
Example #11
Source File: index.js    From egoshop with Apache License 2.0 5 votes vote down vote up
render() {
        const { freightList, freightListLoading, onChange } = this.props;
        const { freight_type, freight_id, freight_fee } = this.state;

        return (
            <RadioGroup
                onChange={(e) => {
                    this.setState({ freight_type: e.target.value });
                }}
                value={freight_type}
            >
                <Radio value={"freight_fee"}>
                    统一邮费
                    {freight_type === "freight_fee" ? <InputNumber
                        placeholder="请输入"
                        style={{
                            width: 150,
                            marginLeft: 20
                        }}
                        formatter={value => `¥ ${value}`}
                        min={0}
                        precision={2}
                        value={freight_fee}
                        onChange={(freight_fee) => {
                            this.setState({ freight_fee });
                            onChange({ freight_type: "freight_id", freight_id: 0, freight_fee });
                        }}
                    /> : null}
                </Radio>
                <br />
                <Radio value={"freight_id"}>
                    运费模板
                    {freight_type === "freight_id" ? <Fragment><Select
                            showSearch
                            style={{ width: 240, marginLeft: 20 }}
                            placeholder="请选择"
                            optionFilterProp="children"
                            onChange={(value) => {
                                this.setState({
                                    freight_id: value
                                });
                                onChange({ freight_type: "freight_id", freight_id: value, freight_fee: 0 });
                            }}
                            value={freight_id === 0 ? null : freight_id}
                            filterOption={(input, option) => option.props.children.props.children.toLowerCase().indexOf(input.toLowerCase()) >= 0}
                        >
                            {
                                freightList.map((e) => (
                                    <Option value={e.id} key={e.id}>
                                        <p>{e.name}</p>
                                    </Option>
                                ))
                            }
                        </Select>
                            <Button
                                type="primary"
                                style={{
                                    marginLeft: 10
                                }}
                                size={"small"}
                                loading={freightListLoading}
                                onClick={this.initList}
                            >
                                刷新
                            </Button>
                        </Fragment>
                        : null}
                </Radio>
            </RadioGroup>
        );
    }
Example #12
Source File: index.jsx    From mixbox with GNU General Public License v3.0 5 votes vote down vote up
function getElement(item) {
    const {type = 'input', component, ...props} = item;

    const commonProps = {
        size: 'default',
    };
    // 样式
    // const width = props.width || '100%';
    // const elementCommonStyle = {width};
    // props.style = props.style ? {...elementCommonStyle, ...props.style} : elementCommonStyle;

    // 如果 component 存在,说明是自定义组件
    if (component) {
        return typeof component === 'function' ? component() : component;
    }

    if (isInputLikeElement(type)) {
        if (type === 'number') return <InputNumber {...commonProps} {...props}/>;
        if (type === 'textarea') return <TextArea {...commonProps} {...props}/>;
        if (type === 'password') return <Password {...commonProps} {...props}/>;

        return <Input {...commonProps} type={type} {...props}/>;
    }

    if (type === 'select') {
        const {options = [], ...others} = props;

        return (
            <Select {...commonProps} {...others}>
                {
                    options.map(opt => <Select.Option key={opt.value} {...opt}>{opt.label}</Select.Option>)
                }
            </Select>
        );
    }

    if (type === 'select-tree') return <TreeSelect {...commonProps} {...props} treeData={props.options}/>;

    if (type === 'checkbox') return <Checkbox {...commonProps} {...props}>{props.label}</Checkbox>;
    if (type === 'checkbox-group') return <Checkbox.Group {...commonProps} {...props}/>;

    if (type === 'radio') return <Radio {...commonProps} {...props}>{props.label}</Radio>;
    if (type === 'radio-group') return <Radio.Group {...commonProps} {...props}/>;
    if (type === 'radio-button') {
        const {options = [], ...others} = props;
        return (
            <Radio.Group buttonStyle="solid" {...commonProps} {...others}>
                {options.map(opt => <Radio.Button key={opt.value} {...opt}>{opt.label}</Radio.Button>)}
            </Radio.Group>
        );
    }

    if (type === 'cascader') return <Cascader {...commonProps} {...props}/>;

    if (type === 'switch') return <Switch {...commonProps} {...props} style={{...props.style, width: 'auto'}}/>;

    if (type === 'date') return <DatePicker {...commonProps} {...props}/>;

    if (type === 'date-time') return <DatePicker {...commonProps} showTime {...props}/>;

    if (type === 'date-range') return <DatePicker.RangePicker {...commonProps} {...props}/>;

    if (type === 'month') return <DatePicker.MonthPicker {...commonProps} {...props}/>;

    if (type === 'time') return <TimePicker {...commonProps} {...props}/>;

    if (type === 'transfer') return <Transfer {...commonProps} {...props}/>;

    if (type === 'icon-picker') return <IconPicker {...commonProps} {...props}/>;

    throw new Error(`no such type: ${type}`);
}
Example #13
Source File: TableList.js    From camel-store-admin with Apache License 2.0 5 votes vote down vote up
renderAdvancedForm() {
    const {
      form: { getFieldDecorator },
    } = this.props;
    return (
      <Form onSubmit={this.handleSearch} layout="inline">
        <Row gutter={{ md: 8, lg: 24, xl: 48 }}>
          <Col md={8} sm={24}>
            <FormItem label="规则名称">
              {getFieldDecorator('name')(<Input placeholder="请输入" />)}
            </FormItem>
          </Col>
          <Col md={8} sm={24}>
            <FormItem label="使用状态">
              {getFieldDecorator('status')(
                <Select placeholder="请选择" style={{ width: '100%' }}>
                  <Option value="0">关闭</Option>
                  <Option value="1">运行中</Option>
                </Select>
              )}
            </FormItem>
          </Col>
          <Col md={8} sm={24}>
            <FormItem label="调用次数">
              {getFieldDecorator('number')(<InputNumber style={{ width: '100%' }} />)}
            </FormItem>
          </Col>
        </Row>
        <Row gutter={{ md: 8, lg: 24, xl: 48 }}>
          <Col md={8} sm={24}>
            <FormItem label="更新日期">
              {getFieldDecorator('date')(
                <DatePicker style={{ width: '100%' }} placeholder="请输入更新日期" />
              )}
            </FormItem>
          </Col>
          <Col md={8} sm={24}>
            <FormItem label="使用状态">
              {getFieldDecorator('status3')(
                <Select placeholder="请选择" style={{ width: '100%' }}>
                  <Option value="0">关闭</Option>
                  <Option value="1">运行中</Option>
                </Select>
              )}
            </FormItem>
          </Col>
          <Col md={8} sm={24}>
            <FormItem label="使用状态">
              {getFieldDecorator('status4')(
                <Select placeholder="请选择" style={{ width: '100%' }}>
                  <Option value="0">关闭</Option>
                  <Option value="1">运行中</Option>
                </Select>
              )}
            </FormItem>
          </Col>
        </Row>
        <div style={{ overflow: 'hidden' }}>
          <div style={{ float: 'right', marginBottom: 24 }}>
            <Button type="primary" htmlType="submit">
              查询
            </Button>
            <Button style={{ marginLeft: 8 }} onClick={this.handleFormReset}>
              重置
            </Button>
            <a style={{ marginLeft: 8 }} onClick={this.toggleForm}>
              收起 <Icon type="up" />
            </a>
          </div>
        </div>
      </Form>
    );
  }
Example #14
Source File: SliderWithInput.jsx    From ui with MIT License 5 votes vote down vote up
SliderWithInput = (props) => {
  const {
    min, max, value, onUpdate, disabled, step,
  } = props;

  const [, handleChange] = useUpdateThrottled(onUpdate, value);

  const [localValue, setLocalValue] = useState(value);

  const debouncedOnChange = useCallback(
    _.debounce((changedValue) => handleChange(changedValue), 1000), [],
  );

  useEffect(() => {
    setLocalValue(parseFloat(value));
  }, [value]);

  const stepToSet = step ?? max / 200;

  return (
    <div style={{ display: 'flex', whiteSpace: 'nowrap' }}>
      <Slider
        value={localValue}
        min={min}
        max={max}
        onChange={setLocalValue}
        onAfterChange={() => handleChange(localValue)}
        step={stepToSet}
        disabled={disabled}
        style={{ minWidth: 100, display: 'inline-block', flexGrow: 100 }}
      />

      <InputNumber
        value={localValue}
        min={min}
        max={max}
        onChange={(changedValue) => {
          if (changedValue === value) { return; }

          const changedValueWithinBounds = Math.min(Math.max(changedValue, min), max);

          setLocalValue(changedValueWithinBounds);

          debouncedOnChange(changedValueWithinBounds);
        }}
        onPressEnter={() => { handleChange(localValue); }}
        onStep={(newValue) => {
          handleChange(newValue);
        }}
        step={stepToSet}
        disabled={disabled}
        style={{ width: 80, display: 'inline-block' }}
      />
    </div>
  );
}
Example #15
Source File: PaymentInvoiceForm.jsx    From erp-crm with MIT License 5 votes vote down vote up
export default function PaymentInvoiceForm({ maxAmount = null, isUpdateForm = false }) {
  const { TextArea } = Input;
  const money = useMoney();
  return (
    <>
      <Form.Item
        label="Number"
        name="number"
        initialValue={1}
        rules={[
          {
            required: true,
          },
        ]}
        style={{ width: '50%', float: 'left', paddingRight: '20px' }}
      >
        <InputNumber style={{ width: '100%' }} />
      </Form.Item>
      <Form.Item
        name="date"
        label="Date"
        rules={[
          {
            required: true,
            type: 'object',
          },
        ]}
        initialValue={dayjs().add(30, 'days')}
        style={{ width: '50%' }}
      >
        <DatePicker format={'DD/MM/YYYY'} style={{ width: '100%' }} />
      </Form.Item>
      <Form.Item
        label="Amount"
        name="amount"
        rules={[{ required: true, message: 'Amount is required' }]}
      >
        {/* <InputNumber
          className="moneyInput"
          min={0}
          max={maxAmount}
          controls={false}
          addonAfter={money.currencyPosition === 'after' ? money.currencySymbol : undefined}
          addonBefore={money.currencyPosition === 'before' ? money.currencySymbol : undefined}
        /> */}
        <InputNumber
          style={{ width: '100%' }}
          min={0}
          max={maxAmount}
          formatter={(value) => `$ ${value}`.replace(/\B(?=(\d{3})+(?!\d))/g, ' ')}
        />
      </Form.Item>
      <Form.Item
        label="Payment Mode"
        name="paymentMode"
        rules={[
          {
            required: true,
          },
        ]}
      >
        <SelectAsync entity={'paymentMode'} displayLabels={['name']}></SelectAsync>
      </Form.Item>
      <Form.Item label="Reference" name="ref">
        <Input />
      </Form.Item>
      <Form.Item label="Description" name="description">
        <TextArea />
      </Form.Item>
    </>
  );
}
Example #16
Source File: Placeholder.js    From getlink-next with MIT License 5 votes vote down vote up
export default function Placeholder() {
  const [text, setText] = useState('');
  const [width, setWidth] = useState(0);
  const [height, setHeight] = useState(0);
  const [backgroundColor, setBackgroundColor] = useState('CCCCCC');
  const [textColor, setTextColor] = useState('A3A3A3');

  const [
    a, b, c, d, e
  ] = useDebounce([text, width, height, backgroundColor, textColor], 500);

  let url = `https://p.302.at/${b}x${c}/${d || 'CCCCCC'}/${e || 'A3A3A3'}.png`;
  if (a) {
    url = `${url}?text=${a}`;
  }

  return (
    <div>
      <div>
        <Form {...layout}>
          <Form.Item label="Size(px)">
            <InputNumber
              value={width}
              onChange={(value) => setWidth(value / 1)}
              placeholder="width"
              step={1}
              precision={0}
              min={0}
            />
            ✖️
            <InputNumber
              value={height}
              onChange={(value) => setHeight(value / 1)}
              placeholder="height"
              step={1}
              precision={0}
              min={0}
            />
          </Form.Item>
          <Form.Item label="Background Color">
            <Input
              style={{ width: 110 }}
              addonBefore="#"
              value={backgroundColor}
              onChange={(e) => setBackgroundColor(e.target.value)}
            />
          </Form.Item>
          <Form.Item label="Text Color">
            <Input
              style={{ width: 110 }}
              addonBefore="#"
              value={textColor}
              onChange={(e) => setTextColor(e.target.value)}
            />
          </Form.Item>
          <Form.Item label="Text">
            <Input value={text} onChange={(e) => setText(e.target.value)} />
          </Form.Item>
          {(width > 0 && height > 0) && (
            <Form.Item label="Preview">
              <div>
                <Input style={{ width: 250 }} disabled value={url} />
                <CopyToClipboard text={url}
                  onCopy={() => message.success('Copied successfully')}>
                  <Button style={{ margin: '0 10px' }} type="primary">Copy</Button>
                </CopyToClipboard>
                <Button href={url} download>Download</Button>
                <div style={{ marginTop: 20 }}>
                  <img style={{ maxWidth: '100%', maxHeight: 300 }} src={url} />
                </div>
              </div>
            </Form.Item>
          )}
        </Form>
      </div>
    </div>
  );
}
Example #17
Source File: AiDrive.js    From network-rc with Apache License 2.0 5 votes vote down vote up
render() {
    const {
      state: { isPredicting, actionKey, probability, interval },
      props: { cameraEnabled, ai },
      drive,
      stop,
      test,
      loadModel,
    } = this;
    return (
      <div className="ai-train">
        <Form layout="inline">
          <Form.Item label="操作间隔">
            <InputNumber
              value={interval}
              onChange={(interval) => this.setState({ interval })}
            />
          </Form.Item>
          <Form.Item label="动作">
            <Tag>
              {aiAction[actionKey].name} {aiAction[actionKey].icon}{" "}
              {probability.toFixed(2)}
            </Tag>
          </Form.Item>
        </Form>
        <br />
        <Form layout="inline">
          <Form.Item>
            <Button
              icon={<ImportOutlined />}
              loading={isPredicting}
              onClick={loadModel}
            >
              导入模型
            </Button>
          </Form.Item>
          <Form.Item>
            <Button
              icon={<BugOutlined />}
              loading={isPredicting}
              onClick={test}
              disabled={!cameraEnabled || !ai || !ai.model}
            >
              测试
            </Button>
            &nbsp;&nbsp;&nbsp;&nbsp;
            <Button
              type="danger"
              key="predic"
              loading={isPredicting}
              onClick={drive}
              icon={<CarOutlined />}
              disabled={!cameraEnabled || !ai || !ai.model}
            >
              开始 Ai 驾驶
            </Button>
          </Form.Item>

          <Form.Item>
            <Button
              onClick={stop}
              icon={<StopOutlined />}
              disabled={!isPredicting}
              key="stop"
            >
              停止 Ai 驾驶
            </Button>
          </Form.Item>
          <br />
        </Form>
      </div>
    );
  }
Example #18
Source File: TableList.js    From youdidao-unmanned-shop with MIT License 5 votes vote down vote up
renderAdvancedForm() {
    const {
      form: { getFieldDecorator },
    } = this.props;
    return (
      <Form onSubmit={this.handleSearch} layout="inline">
        <Row gutter={{ md: 8, lg: 24, xl: 48 }}>
          <Col md={8} sm={24}>
            <FormItem label="规则名称">
              {getFieldDecorator('name')(<Input placeholder="请输入" />)}
            </FormItem>
          </Col>
          <Col md={8} sm={24}>
            <FormItem label="使用状态">
              {getFieldDecorator('status')(
                <Select placeholder="请选择" style={{ width: '100%' }}>
                  <Option value="0">关闭</Option>
                  <Option value="1">运行中</Option>
                </Select>
              )}
            </FormItem>
          </Col>
          <Col md={8} sm={24}>
            <FormItem label="调用次数">
              {getFieldDecorator('number')(<InputNumber style={{ width: '100%' }} />)}
            </FormItem>
          </Col>
        </Row>
        <Row gutter={{ md: 8, lg: 24, xl: 48 }}>
          <Col md={8} sm={24}>
            <FormItem label="更新日期">
              {getFieldDecorator('date')(
                <DatePicker style={{ width: '100%' }} placeholder="请输入更新日期" />
              )}
            </FormItem>
          </Col>
          <Col md={8} sm={24}>
            <FormItem label="使用状态">
              {getFieldDecorator('status3')(
                <Select placeholder="请选择" style={{ width: '100%' }}>
                  <Option value="0">关闭</Option>
                  <Option value="1">运行中</Option>
                </Select>
              )}
            </FormItem>
          </Col>
          <Col md={8} sm={24}>
            <FormItem label="使用状态">
              {getFieldDecorator('status4')(
                <Select placeholder="请选择" style={{ width: '100%' }}>
                  <Option value="0">关闭</Option>
                  <Option value="1">运行中</Option>
                </Select>
              )}
            </FormItem>
          </Col>
        </Row>
        <div style={{ overflow: 'hidden' }}>
          <div style={{ marginBottom: 24 }}>
            <Button type="primary" htmlType="submit">
              查询
            </Button>
            <Button style={{ marginLeft: 8 }} onClick={this.handleFormReset}>
              重置
            </Button>
            <a style={{ marginLeft: 8 }} onClick={this.toggleForm}>
              收起 <Icon type="up" />
            </a>
          </div>
        </div>
      </Form>
    );
  }
Example #19
Source File: popModel.js    From ant-simple-pro with MIT License 5 votes vote down vote up
PopModel = memo(function PopModel({visible,dropTarget,onClose}) {

  const [form] = Form.useForm();

  useEffect(() => {
    if(visible){
      const { x,y,w,h,type } = dropTarget;
      form.setFieldsValue({x:spacing*x,y:spacing*y,w:spacing*w,h:spacing*h,type});
    }
  }, [visible,dropTarget])

  const handleClose = ()=>{
    onClose({visible:false});
  }

  return (
    <>
      <Drawer
        title="组件元素"
        placement="right"
        mask={false}
        onClose={handleClose}
        visible={visible}
      >
          <Form form={form} labelAlign='left'>
           <Form.Item label="组件类型" name="type">
             <Input size='middle' />
            </Form.Item>
            <Form.Item label="x" name="x">
              <InputNumber size='middle' />
            </Form.Item>
            <Form.Item label="y" name="y">
              <InputNumber size='middle' />
            </Form.Item>
            <Form.Item label="w" name="w">
              <InputNumber size='middle' />
            </Form.Item>
            <Form.Item label="h" name="h">
              <InputNumber size='middle' />
            </Form.Item>
          </Form>
      </Drawer>
    </>
  )
})
Example #20
Source File: Year.js    From hzero-front with Apache License 2.0 5 votes vote down vote up
render() {
    const {
      year: { type, start, end },
    } = this.props;
    return (
      <div>
        <Group
          value={type}
          onChange={(e) => {
            this.changeParams('type', e.target.value);
          }}
          defaultValue=""
        >
          <List size="small" bordered>
            <List.Item>
              <Radio value="">不指定</Radio>
            </List.Item>
            <List.Item>
              <Radio value="*">每年</Radio>
            </List.Item>
            <List.Item>
              <Radio value="period">周期</Radio>
              <InputNumber
                min={0}
                defaultValue={2018}
                value={start}
                placeholder="年"
                onChange={(value) => {
                  this.changeParams('start', value);
                }}
              />
              &nbsp;-&nbsp;
              <InputNumber
                min={0}
                defaultValue={2019}
                value={end}
                placeholder="年"
                onChange={(value) => {
                  this.changeParams('end', value);
                }}
              />
            </List.Item>
          </List>
        </Group>
      </div>
    );
  }
Example #21
Source File: styles.js    From bank-client with MIT License 5 votes vote down vote up
StyledInputNumber = styled(InputNumber)`
  width: 100%;

  .ant-input-number-handler-wrap {
    display: none;
  }
`
Example #22
Source File: SalaryDetails.js    From placement-portal with MIT License 5 votes vote down vote up
render(){
        const {getFieldDecorator} = this.props.form;
        return(
            <div style={{textAlign: 'center'}}>
                <Form onSubmit={this.handleSubmit} colon={false}>
                   
                        <Typography.Paragraph style={{textAlign: "left"}}>
                            Please Note: <br/> 1. Performance based bonus should not be declared as part of Gross/CTC but to be indicated in Bonus/Perks/Incentive section. <br/> 2. Any amount to be disbursed later than the end of first 12 months should not be a part of Gross/CTC. <br/> 3. Joining Bonus/Signing Bonus to be indicated in Bonus/Perks/Incentive section.<br/> 4. Statutory Annual Payouts (e.g., Medical, LTC etc.) not to be a part of Gross.
                        </Typography.Paragraph>
                   
                    <Form.Item label="Cost To Company">
                        {getFieldDecorator("ctc", {
                            rules: [
                                {
                                    required: true,
                                    message: "Please input the CTC"
                                }
                            ],
                            initialValue: this.props.ctc
                        })(
                            <InputNumber
                                min={100000}
                            />
                        )}
                    </Form.Item>
                    <Form.Item label="Gross salary (Before tax, after deductions)">
                        {getFieldDecorator("gross_salary", {
                            rules: [
                                {
                                    required: true,
                                    message: "Please input the Gross Salary"
                                }
                            ],
                            initialValue: this.props.ctc
                        })(
                            <InputNumber
                                min={100000}
                            />
                        )}
                    </Form.Item>
                    <Form.Item label="Bonus (Perks/Incentives)">
                        {getFieldDecorator("bonus_perks", {
                            initialValue: this.props.bonus_perks
                        })(
                            <Input.TextArea
                                rows={4}
                                placeholder="Specify Bonus/perks (if any)"
                            />
                        )}
                    </Form.Item>
                    <Form.Item label="Other Variable Pay">
                        {getFieldDecorator("variable_pay", {
                            initialValue: this.props.variable_pay
                        })(
                            <Input.TextArea
                                rows={4}
                                placeholder="Specify Other Variable Pay (if any)"
                            />
                        )}
                    </Form.Item>
                    <Form.Item>
                        <Button onClick={this.handleBack} style={{margin: 5}}>
                            Back
                        </Button>
                        <Button type='primary' htmlType='submit' style={{margin: 5}}>
                        Next
                        </Button>
                    </Form.Item>
                </Form>
            </div>
        )
    }
Example #23
Source File: align.jsx    From virtuoso-design-system with MIT License 5 votes vote down vote up
storiesOf('antd/Input', module).add('align', () => 
  <>
    <Mentions style={{ width: 100 }} rows={1} />
    <Input.TextArea rows={1} style={{ width: 100 }} />
    <Button type="primary">Button</Button>
    <Input style={{ width: 100 }} />
    <Text copyable>Ant Design</Text>
    <Input prefix="1" suffix="2" style={{ width: 100 }} />
    <Input addonBefore="1" addonAfter="2" style={{ width: 100 }} />
    <InputNumber style={{ width: 100 }} />
    <DatePicker style={{ width: 100 }} />
    <TimePicker style={{ width: 100 }} />
    <Select style={{ width: 100 }} defaultValue="jack">
      <Option value="jack">Jack</Option>
      <Option value="lucy">Lucy</Option>
      <Option value="disabled" disabled>
        Disabled
      </Option>
      <Option value="Yiminghe">yiminghe</Option>
    </Select>
    <TreeSelect style={{ width: 100 }} />
    <Cascader defaultValue={['zhejiang', 'hangzhou', 'xihu']} options={options} />
    <RangePicker />
    <DatePicker picker="month" />
    <Radio.Group defaultValue="a">
      <Radio.Button value="a">Hangzhou</Radio.Button>
      <Radio.Button value="b">Shanghai</Radio.Button>
    </Radio.Group>
    <AutoComplete style={{ width: 100 }} placeholder="input here" />
    <br />
    <Input prefix="$" addonBefore="Http://" addonAfter=".com" defaultValue="mysite" />
    <Input style={narrowStyle} suffix="Y" />
    <Input style={narrowStyle} />
    <Input style={narrowStyle} defaultValue="1" suffix="Y" />
  </>,
  { docs: { page: () => (<><hr />
<p>order: 99
title:
  zh-CN: 文本对齐
  en-US: Text Align</p>
<h2 id="debugtrue">debug: true</h2></>) } });
Example #24
Source File: index.js    From react_management_template with Apache License 2.0 4 votes vote down vote up
render() {
        const formItemLayout = {
            labelCol: { span: 8 },
            wrapperCol: { span: 16 },
          };

        const offsetLayout={
            wrapperCol:{
                xs:24,
                sm:{
                    span:16,
                    offset:6
                }
            }
        }
        
        const RadioGroup = Radio.Group;
        const { Option } = Select;
        const TextArea = Input.TextArea;
 
        

        return (
            <div>
                <Card title="注册表单" className="card-wrap">
                    <Form name="normal_login" className="login-form" initialValues={{ remember: true }}>
                            <Form.Item {...formItemLayout} name="username" label="用户名" rules={[{ required: true, message: '请输入用户名!!!' }]}>
                                <Input name="username" prefix={<UserOutlined className="site-form-item-icon" />} placeholder="请输入用户名" onChange={this.onInputChange} />
                            </Form.Item>
                            <Form.Item {...formItemLayout} name="password" label="密码" rules={[{ required: true, message: '请输入密码!!!' }]}>
                                <Input name="password" prefix={<LockOutlined className="site-form-item-icon" />} type="password" placeholder="请输入密码" onChange={this.onInputChange}/>
                            </Form.Item>

                            <Form.Item {...formItemLayout} name="sex" label="性别" rules={[{ required: true }]}>
                                <RadioGroup defaultValue="1">
                                    <Radio value="1">男</Radio>
                                    <Radio value="2">女</Radio>
                                </RadioGroup>
                            </Form.Item>

                            <Form.Item {...formItemLayout} name="age" label="年龄" rules={[{ required: true }]}>
                                <InputNumber min={1} max={100} defaultValue={18}/>
                            </Form.Item>

                            <Form.Item {...formItemLayout} name="state"  label="状态" rules={[{ required: true }]}>
                                <Select defaultValue="3">
                                    <Option value="1">上学</Option>
                                    <Option value="2">工作</Option>
                                    <Option value="3">财富自由</Option>
                                </Select>
                            </Form.Item>
                            
                            <Form.Item {...formItemLayout} name="hobby"  label="爱好" rules={[{ required: true }]}>
                                <Select mode="multiple" defaultValue="4">
                                    <Option value="1">游泳</Option>
                                    <Option value="2">打篮球</Option>
                                    <Option value="3">踢足球</Option>
                                    <Option value="4">跑步</Option>
                                    <Option value="5">爬山</Option>
                                    <Option value="6">骑行</Option>
                                    <Option value="7">桌球</Option>
                                    <Option value="8">麦霸</Option>
                                </Select>
                            </Form.Item>

                            <Form.Item {...formItemLayout} name="is_married" label="是否已婚">
                               <Switch defaultChecked/>
                            </Form.Item>

                            <Form.Item {...formItemLayout} name="time" label="生日">
                                <DatePicker showTime format="YYYY-MM-DD HH:mm:ss"/>
                            </Form.Item>

                            <Form.Item {...formItemLayout} name="address" label="地址">
                               <TextArea/>
                            </Form.Item>


                            <Form.Item {...formItemLayout} name="icon" label="头像">
                                <Upload
                                    name="avatar"
                                    listType="picture-card"
                                    className="avatar-uploader"
                                    showUploadList={false}
                                    action="https://www.mocky.io/v2/5cc8019d300000980a055e76"
                                    onChange={this.handleChange}
                                >
                                {this.state.userImg ? <img src={this.state.userImg} alt="avatar" style={{ width: '100%' }} /> : <PlusOutlined />}
                                </Upload>
                            </Form.Item>

                            <Form.Item {...offsetLayout} name="xieyi" >
                                <Checkbox>我已阅读过<a href="#">协议</a></Checkbox>
                            </Form.Item>

                            <Form.Item {...offsetLayout} name="register" >
                               <Button type="primary" >注册 </Button>
                            </Form.Item>

                        </Form>
                </Card>
            </div>
        );
    }
Example #25
Source File: adminChallengeCreate.js    From ctf_platform with MIT License 4 votes vote down vote up
CreateChallengeForm = (props) => {
    const [form] = Form.useForm();
    const [editorValue, setEditorValue] = React.useState("")
    const [existingCats, setExistingCats] = React.useState([])
    const [finalSortedChalls, setfinalSortedChalls] = React.useState([])

    useEffect(() => {
        var currentValues = form.getFieldsValue()
        currentValues.flags = [""]

        form.setFieldsValue(currentValues)
        //Render existing categories select options
        let existCats = []
        for (let i = 0; i < props.allCat.length; i++) {
            existCats.push(<Option key={props.allCat[i].key} value={props.allCat[i].key}>{props.allCat[i].key}</Option>)
        }
        setExistingCats(existCats)
        //Render existing challenges select options
        let existChalls = {}
        for (let i = 0; i < props.challenges.length; i++) {
            if (!(props.challenges[i].category in existChalls)) existChalls[props.challenges[i].category] = []
            existChalls[props.challenges[i].category].push({
                value: props.challenges[i]._id,
                label: props.challenges[i].name
            })
        }

        let finalChalls = []
        for (const category in existChalls) {
            finalChalls.push({
                value: category,
                label: category,
                children: existChalls[category]
            })
        }
        setfinalSortedChalls(finalChalls)
    }, [])

    return (
        <Form
            form={form}
            name="create_challenge_form"
            className="create_challenge_form"
            onValuesChange={() => { if (props.state.edited === false) props.setState({ edited: true }) }}
            onFinish={async (values) => {
                props.setState({ edited: false })
                if (typeof values.flags === "undefined") {
                    message.warn("Please enter at least 1 flag")
                }
                else {
                    //console.log(values)
                    props.setState({ loading: true })
                    if (values.visibility === "false") {
                        values.visibility = false
                    }
                    else {
                        values.visibility = true
                    }
                    if (values.dynamic === "false") {
                        values.dynamic = false
                    }
                    else {
                        values.dynamic = true
                    }
                    if (typeof values.writeup !== "undefined") {
                        if (typeof values.writeupComplete === "undefined") {
                            values.writeupComplete = true
                        }
                    }
                    const category = (typeof values.category1 !== "undefined") ? values.category1 : values.category2
                    let requires = undefined
                    if (values.requires && values.requires.length > 0) requires = values.requires[1]
                    await fetch(window.ipAddress + "/v1/challenge/new", {
                        method: 'post',
                        headers: { 'Content-Type': 'application/json', "Authorization": window.IRSCTFToken },
                        body: JSON.stringify({
                            "name": values.name,
                            "category": category,
                            "description": values.description,
                            "points": values.points,
                            "flags": values.flags,
                            "tags": values.tags,
                            "hints": values.hints,
                            "max_attempts": values.max_attempts,
                            "visibility": values.visibility,
                            "writeup": values.writeup,
                            "writeupComplete": values.writeupComplete,
                            "requires": requires,
                            "dynamic": values.dynamic,
                            "initial": values.initial,
                            "minSolves": values.minSolves,
                            "minimum": values.minimum
                        })
                    }).then((results) => {
                        return results.json(); //return data in JSON (since its JSON data)
                    }).then((data) => {
                        //console.log(data)
                        if (data.success === true) {
                            message.success({ content: "Created challenge " + values.name + " successfully!" })
                            form.resetFields()
                            props.handleCreateBack()
                        }
                        else if (data.error === "exists") {
                            message.warn("A challenge with an existing name exists")
                        }
                        else {
                            message.error({ content: "Oops. Unknown error, please contact an admin." })
                        }



                    }).catch((error) => {
                        console.log(error)
                        message.error({ content: "Oops. Issue connecting with the server or client error, please check console and report the error. " });
                    })
                    props.setState({ loading: false })


                }

            }}

        >
            <Prompt
                when={props.state.edited}
                message='The challenge details you entered have not been saved. Are you sure you want to leave?'
            />

            <h1>Challenge Name:</h1>
            <Form.Item
                name="name"
                rules={[{ required: true, message: 'Please enter a challenge name' }]}
            >

                <Input allowClear placeholder="Challenge name" />
            </Form.Item>

            <Divider />
            <h1>Challenge Category:</h1>
            <h4>Select an Existing Category: </h4>
            <Form.Item
                name="category1"
                rules={[{ required: !props.state.selectCatDisabled, message: 'Please enter a challenge category' }]}
            >

                <Select
                    disabled={props.state.selectCatDisabled}
                    allowClear
                    showSearch
                    placeholder="Select an existing Category"
                    onChange={(value) => {
                        if (value) {
                            props.setState({ inputCatDisabled: true })
                        }
                        else {
                            props.setState({ inputCatDisabled: false })
                        }
                    }}
                >
                    {existingCats}
                </Select>

            </Form.Item>
            <h4>Enter a New Category</h4>
            <Form.Item
                name="category2"
                rules={[{ required: !props.state.inputCatDisabled, message: 'Please enter a challenge category' }]}
            >

                <Input onChange={(e) => {
                    e.target.value.length > 0 ? props.setState({ selectCatDisabled: true }) : props.setState({ selectCatDisabled: false })
                }} disabled={props.state.inputCatDisabled} allowClear placeholder="Enter a new challenge category" />
            </Form.Item>

            <Divider />

            <Suspense fallback={<div style={{ height: "100%", width: "100%", display: "flex", justifyContent: "center", alignItems: "center", zIndex: 15 }}>
                <Ellipsis color="#177ddc" size={120} ></Ellipsis>
            </div>}>
                <h1>Challenge Description (Supports <a href="https://guides.github.com/features/mastering-markdown/" target="_blank" rel="noreferrer">Markdown</a> and <a href="https://github.com/rehypejs/rehype-raw" target="_blank" rel="noreferrer">HTML</a>):</h1>
                <Form.Item
                    name="description"
                    rules={[{ required: true, message: 'Please enter a description' }]}
                    valuePropName={editorValue}
                >
                    <MDEditor value={editorValue} onChange={(value) => { setEditorValue(value) }} preview="edit" />
                </Form.Item>
                <h3>Challenge Description Preview</h3>
                <Card
                    type="inner"
                    bordered={true}
                    bodyStyle={{ backgroundColor: "#262626", textAlign: "center" }}
                    className="challengeModal"
                >
                    <MarkdownRender>{editorValue}</MarkdownRender>
                </Card>
            </Suspense>


            <Divider />

            <div className="settings-responsive2" style={{ display: "flex", justifyContent: "space-around" }}>

                <div style={{ display: "flex", flexDirection: "column", justifyContent: "center" }}>

                    <Card>
                        <h1>Challenge Points:</h1>
                        <Form.Item
                            name="points"
                            rules={[{ required: true, message: 'Please enter challenge points' }, {
                                type: 'integer',
                                message: "Please enter a valid integer between 0-100000",
                            },]}
                            initialValue={0}
                        >

                            <InputNumber disabled={props.state.dynamic} min={0} max={100000} style={{ width: "30ch" }} ></InputNumber>
                        </Form.Item>
                    </Card>

                    <Card>
                        <h1>Maximum Number of Attempts (Set to 0 for unlimited)</h1>
                        <Form.Item
                            name="max_attempts"
                            rules={[{ required: true, message: 'Please enter the maximum number of attempts' }, {
                                type: 'integer',
                                message: "Please enter a valid integer between 0-10000",
                            },]}
                            style={{ alignText: 'center' }}
                            initialValue={0}
                        >

                            <InputNumber min={0} max={10000} style={{ width: "30ch" }}></InputNumber>
                        </Form.Item>
                    </Card>
                </div>

                <Divider type="vertical" style={{ height: "inherit" }} />

                <div style={{ display: "flex", flexDirection: "column" }}>
                    <Form.List name="flags" >
                        {(fields, { add, remove }) => {
                            return (
                                <Card>
                                    <h1>Flags</h1>
                                    {fields.map(field => (
                                        <Space key={field.key} style={{ display: 'flex', marginBottom: 8 }} align="start">
                                            <Form.Item
                                                {...field}
                                                name={[field.name]}
                                                fieldKey={[field.fieldKey]}
                                                rules={[{ required: true, message: 'Missing flag' }, { message: "Please enter a flag that is < 1000 characters", pattern: /^.{1,1000}$/ }]}
                                            >
                                                <Input style={{ width: "50ch" }} placeholder="Flag" />
                                            </Form.Item>

                                            {fields.length > 1 ? (
                                                <MinusCircleOutlined
                                                    className="dynamic-delete-button"
                                                    style={{ margin: '0 8px', color: "red" }}
                                                    onClick={() => {
                                                        remove(field.name);
                                                    }}
                                                />
                                            ) : null}
                                        </Space>
                                    ))}

                                    <Form.Item>
                                        <Button
                                            type="dashed"
                                            onLoad={() => { if (fields.length < 1) add() }}
                                            onClick={() => {
                                                add();
                                            }}
                                            block
                                            style={{ width: "50ch" }}
                                        >
                                            <PlusOutlined /> Add Flag
                                        </Button>
                                    </Form.Item>


                                </Card>
                            );
                        }}
                    </Form.List>

                    <Form.List name="tags">
                        {(fields, { add, remove }) => {
                            return (
                                <Card>
                                    <h1>Tags</h1>
                                    {fields.map(field => (
                                        <Space key={field.key} style={{ display: 'flex', marginBottom: 8 }} align="start">

                                            <Form.Item
                                                {...field}
                                                name={[field.name]}
                                                fieldKey={[field.fieldKey]}
                                                rules={[{ required: true, message: 'Missing tag' }]}
                                            >
                                                <Input placeholder="Tag" style={{ width: "50ch" }} />
                                            </Form.Item>


                                            <MinusCircleOutlined
                                                className="dynamic-delete-button"
                                                style={{ margin: '0 8px', color: "red" }}
                                                onClick={() => {
                                                    remove(field.name);
                                                }}
                                            />
                                        </Space>
                                    ))}

                                    <Form.Item>
                                        <Button
                                            type="dashed"
                                            onClick={() => {
                                                add();
                                            }}
                                            block
                                            style={{ width: "50ch" }}
                                        >
                                            <PlusOutlined /> Add Tag
                                        </Button>
                                    </Form.Item>
                                </Card>
                            );
                        }}
                    </Form.List>
                </div>
            </div>

            <Divider />


            <div className="settings-responsive2" style={{ display: "flex", justifyContent: "space-around" }}>

                <div style={{ display: "flex", flexDirection: "column" }}>

                    <Form.List name="hints" >
                        {(fields, { add, remove }) => {
                            return (
                                <Card>
                                    <h1>Hints</h1>
                                    {fields.map(field => (
                                        <Space key={field.key} style={{ display: 'flex', marginBottom: 8 }} align="start">
                                            <Form.Item
                                                {...field}
                                                name={[field.name, "hint"]}
                                                fieldKey={[field.fieldKey, "hint"]}
                                                rules={[{ required: true, message: 'Missing hint' }]}
                                            >
                                                <Input placeholder="Hint" style={{ width: "20vw" }} />
                                            </Form.Item>

                                            <Form.Item
                                                {...field}
                                                name={[field.name, "cost"]}
                                                fieldKey={[field.fieldKey, "cost"]}
                                                rules={[{ required: true, message: 'Missing cost for hint' }, {
                                                    type: 'integer',
                                                    message: "Please enter a valid integer between 0-10000",
                                                },]}
                                            >
                                                <InputNumber min={0} max={10000} placeholder="Cost"></InputNumber>
                                            </Form.Item>

                                            <MinusCircleOutlined
                                                style={{ color: "red" }}
                                                onClick={() => {
                                                    remove(field.name);
                                                }}
                                            />
                                        </Space>
                                    ))}

                                    <Form.Item>
                                        <Button
                                            type="dashed"
                                            onClick={() => {
                                                add();
                                            }}
                                            block
                                            style={{ width: "50ch" }}
                                        >
                                            <PlusOutlined /> Add Hint
                                        </Button>
                                    </Form.Item>
                                </Card>
                            );
                        }}
                    </Form.List>

                    <Card>
                        <h1>Writeup Link (Optional)</h1>
                        <Form.Item
                            name="writeup"
                            rules={[
                                {
                                    type: 'url',
                                    message: "Please enter a valid link",
                                }]}
                        >

                            <Input allowClear style={{ width: "50ch" }} placeholder="Enter a writeup link for this challenge" />
                        </Form.Item>
                        <div style={{ display: "flex", alignContent: "center" }}>
                            <h4 style={{ marginRight: "2ch" }}>Release Writeup Only After Completion: </h4>
                            <Form.Item
                                name="writeupComplete"
                            >
                                <Switch defaultChecked />
                            </Form.Item>
                        </div>
                    </Card>

                    <Card>
                        <h1>Visibility</h1>
                        <Form.Item
                            name="visibility"
                            rules={[{ required: true, message: 'Please set the challenge visibility' }]}
                            initialValue="false"
                        >
                            <Select style={{ width: "20ch" }}>
                                <Option value="false"><span style={{ color: "#d32029" }}>Hidden <EyeInvisibleOutlined /></span></Option>
                                <Option value="true"><span style={{ color: "#49aa19" }}>Visible <EyeOutlined /></span></Option>
                            </Select>

                        </Form.Item>
                    </Card>
                </div>

                <Divider type="vertical" style={{ height: "inherit" }} />

                <div style={{ display: "flex", flexDirection: "column" }}>

                    <Card>
                        <h1>Challenge Required: </h1>
                        <Form.Item
                            name="requires"
                        >

                            <Cascader
                                options={finalSortedChalls}
                                allowClear
                                showSearch
                                placeholder="Select an existing challenge" />

                        </Form.Item>
                        <p>Locks this challenge until the provided challenge above has been solved.</p>
                    </Card>

                    <Card>
                        <h1>Dynamic Scoring</h1>
                        <Form.Item
                            name="dynamic"
                            rules={[{ required: true, message: 'Please set whether the challenge uses dynamic scoring' }]}
                            initialValue="false"
                        >
                            <Select onSelect={(option) => { option === "false" ? props.setState({ dynamic: false }) : props.setState({ dynamic: true }) }} style={{ width: "20ch" }}>
                                <Option value="false"><span style={{ color: "#d32029" }}>Disabled</span></Option>
                                <Option value="true"><span style={{ color: "#49aa19" }}>Enabled</span></Option>
                            </Select>

                        </Form.Item>

                        <h1>Initial Points:</h1>
                        <Form.Item
                            name="initial"
                            rules={[{ required: props.state.dynamic, message: 'Please enter the initial challenge points' }, {
                                type: 'integer',
                                message: "Please enter a valid integer between 1-100000",
                            },]}
                            initialValue={500}
                        >
                            <InputNumber disabled={!props.state.dynamic} min={1} max={100000} ></InputNumber>
                        </Form.Item>
                        <p>Initial number of points when there are 0/1 solves on a challenge</p>

                        <h1>Minimum Points:</h1>
                        <Form.Item
                            name="minimum"
                            rules={[{ required: props.state.dynamic, message: 'Please enter the minimum challenge points' }, {
                                type: 'integer',
                                message: "Please enter a valid integer between 0-100000",
                            },]}
                            initialValue={100}
                        >
                            <InputNumber disabled={!props.state.dynamic} min={0} max={100000} ></InputNumber>
                        </Form.Item>
                        <p>Minimum amount of points that the challenge can decay too</p>

                        <h1>Solves to Minimum:</h1>
                        <Form.Item
                            name="minSolves"
                            rules={[{ required: props.state.dynamic, message: 'Please enter the solves to minimum' }, {
                                type: 'integer',
                                message: "Please enter a valid integer between 1-100000",
                            },]}
                            initialValue={50}
                        >
                            <InputNumber disabled={!props.state.dynamic} min={1} max={100000} ></InputNumber>
                        </Form.Item>
                        <p>Number of solves on the challenge till it decays to the minimum point.</p>
                    </Card>
                </div>

            </div>

            <Form.Item>
                <div style={{ display: "flex", justifyContent: "space-between", flexDirection: "row", marginTop: "2vh" }}>
                    <div>
                        <Button style={{ marginBottom: "1.5vh", marginRight: "2vw", backgroundColor: "#d4b106", borderColor: "", color: "white" }} onClick={() => { props.previewChallenge(form.getFieldsValue()); }}>Preview</Button>
                        <Button loading={props.loadingStatus} type="primary" htmlType="submit" className="login-form-button" style={{ marginBottom: "1.5vh" }}>Create Challenge</Button>
                    </div>
                    <div>
                        <Button style={{ marginRight: "2vw" }} type="primary" danger onClick={() => { form.resetFields() }}>Clear</Button>
                    </div>
                </div>
            </Form.Item>

        </Form>
    );
}
Example #26
Source File: create-edit-receiver.js    From doraemon with GNU General Public License v3.0 4 votes vote down vote up
render() {
    const { getFieldDecorator } = this.props.form
    const { mode, visible, groupState } = this.state

    return (
        <Modal
    title={mode === 'edit' ? '编辑报警策略' : '添加报警策略'}
    visible={visible}
    onOk={this.handleOk}
    onCancel={this.handleCancel}
    maskClosable={false}
        >
        <Form {...formItemLayout} layout="horizontal" onValuesChange={this.groupChange}>
        <Form.Item label="报警时间段" style={{ marginBottom: 0 }}>
  <Form.Item style={{ display: 'inline-block', width: 'calc(50% - 10px)' }}>
    {getFieldDecorator('start_time', {
      rules: [{ type: 'object', required: true, message: 'Please select time!' }],
    })(<TimePicker style={{ width: '100%' }} format="HH:mm" onChange={this.startTimeChange} />)}
    </Form.Item>
    <span style={{ display: 'inline-block', width: '20px', textAlign: 'center' }}>~</span>
    <Form.Item style={{ display: 'inline-block', width: 'calc(50% - 10px)' }}>
      {getFieldDecorator('end_time', {
        rules: [
          { type: 'object', required: true, message: 'Please select time!' },
          // { validator: this.endTimeValid}
        ],
      })(<TimePicker style={{ width: '100%' }} format="HH:mm" />)}
    </Form.Item>
    </Form.Item>
    <Form.Item label="报警延迟">
        {getFieldDecorator('start', {
      rules: [
        { required: true, message: '请输入报警延迟' },
        { validator: this.delayValid },
      ],
    })(<InputNumber type="number" style={{ width: '100%' }} />)}
    </Form.Item>
    <Form.Item label="报警周期"
      wrapperCol={{
      xs: { span: 24 },
      sm: { span: 16 },
    }}
    >
      {getFieldDecorator('period', {
        rules: [
          { required: true, message: '请输入报警周期' },
          { validator: this.cycleValid },
        ],
      })(<InputNumber type="number" style={{ width: 'calc(100% - 20px)' }} />)}
      <span style={{ width: '20px', display: 'inline-block', textAlign: 'right' }}>分</span>
      </Form.Item>
      <Form.Item label="报警用户">
          {getFieldDecorator('user', {
        rules: [
          { required: groupState.user, message: '请输入报警用户' },
        ],
      })(<DInput onChange={this.groupChange} />)}
      </Form.Item>
      <Form.Item label="值班组">
          {getFieldDecorator('duty_group', {
        rules: [
          { required: groupState.duty_group, message: '请输入报警用户' },
        ],
      })(<DInput onChange={this.groupChange} />)}
      </Form.Item>
      <Form.Item label="报警用户组">
          {getFieldDecorator('group', {
        rules: [
          { required: groupState.group, message: '请输入报警用户组' },
        ],
      })(<DInput onChange={this.groupChange} />)}
      </Form.Item>
      <Form.Item label="Filter表达式">
          {getFieldDecorator('expression', {})(<Input />)}
      </Form.Item>
      <Form.Item label="报警方式">
          {getFieldDecorator('method', {
        initialValue: 'LANXIN',
            rules: [
          { required: true, message: '请输入报警用户组' },
        ],
      })(<Select onChange={this.selectMethod}>
          <Option value="LANXIN">LANXIN</Option>
          <Option value="CALL">CALL</Option>
          <Option value="SMS">SMS</Option>
          <Option value="HOOK">HOOK</Option>
          <Option value="DINGTALK">DINGTALK</Option>
          </Select>)}
          </Form.Item>
        {this.state.method === 'HOOK' ?
        <Form.Item label="HOOK URL">
            {getFieldDecorator('hookurl', {
          // initialValue: hookurl,
          rules: [
            { required: true, message: '请输入HOOK URL' },
          ],
        })(<Input />)}
        </Form.Item> : null
        }
        {this.state.method === 'DINGTALK' ?
        <Form.Item label="钉钉机器人URL">
            {getFieldDecorator('dingtalkUrl', {
          // initialValue: dingtalkUrl,
          rules: [
            { required: true, message: '请输入DINGTALK URL' },
          ],
        })(<Input />)}
        </Form.Item> : null
        }
        {this.state.method === 'DINGTALK' ?
        <Form.Item label="钉钉加签密钥">
            {getFieldDecorator('dingtalkSecret', {
          rules: [
            { required: true, message: '请输入钉钉加签密钥' },
          ],
        })(<Input />)}
        </Form.Item> : null
        }
      </Form>
      </Modal>
      )
      }
Example #27
Source File: index.js    From certificate-generator with MIT License 4 votes vote down vote up
function ListEvents(props) {

const { Meta } = Card;
	/*Recebe o organizador e o JSON de organizadores*/
	const { organizador, users } = props

	/*Trabalham para trocar a tela da lista de eventos com o formulário de edição/criação*/
	const [ toEditFormEvent, setToEditFormEvent] = useState(false);
	const [ toCreateFormEvent, setToCreateFormEvent] = useState(false);
	const [ toProfile, setProfile] = useState(false);
	const [ toList, setList] = useState(false);
	const [ toSeeEvents, setSeeEvents] = useState(false);

	/*Esta variavel guarda o evento referente quando o botão check participantes for acionado*/
	const [ eventChecked, setEventChecked] = useState('');

	/*JSON dos eventos*/
	const [ eventos, setEventos ] = useState(eventosData)

	/*Vaiável para saber qual evento foi editado*/
	const [ eventEdited, setEventEdited ] = useState('')
	  
	//Dados do evento:
	//Serão usados para editar no formulário
	const [ company, setCompany] = useState('');
	const [ course, setCourse ] = useState('');
	const [ startDate, setStartDate ] = useState('');
	const [ finishDate, setFinishDate ] = useState('');
	const [ workload, setWorkload ] = useState('');

	/*---------- Assinatura Digital ----------*/
	const [ imageURL, setImageURL ] = useState(null)

	const sigCanvas = useRef({})

	const clear = () => sigCanvas.current.clear();

	const save = () => {
		setImageURL(sigCanvas.current.getTrimmedCanvas().toDataURL("image/png"))
	}

	/*--------- Formulário para criar evento ---------*/
	const { RangePicker } = DatePicker;

	/*Constroi o layout do input de datas*/
	const formItemLayout = {
	  labelCol: {
	    xs: {
	      span: 24,
	    },
	    sm: {
	      span: 8,
	    },
	  },
	  wrapperCol: {
	    xs: {
	      span: 24,
	    },
	    sm: {
	      span: 16,
	    },
	  },
	};

	/*Constroi o layout do input de name/curso*/
	const formInputLayout = {
	  labelCol: {
	    span: 4,
	  },
	  wrapperCol: {
	    span: 8,
	  },
	};

	/*Define as regras para que a data seja aceita */
	const rangeConfig = {
	  rules: [
	    {
	      type: 'array',
	      required: true,
	      message: 'Este campo é obrigatório!',
	    },
	  ],
	};

	/*Define as regras para que os inputs de texto sejam aceitos */
	const rangeInputs = {
		rules: [
	    	{
	        	required: true,
	            message: 'Por favor, preencha esse campo',
	        },
		],
	};

	/*Função acionada quando um evento for ser criado*/
	/*Ela não é chamada caso os campos não forem preeenchidos*/
	const onFinish = fieldsValue => {

	    /*Dados do calendário*/
	    const rangeValue = fieldsValue['range-picker'];

	    if(imageURL === null) {
	    	message.error('Por favor, escreva sua assinatura digital')
	    } else {
	    	setEventos([
				...eventos, {
				user: organizador,
				company: fieldsValue.company, 
				course: fieldsValue.course,
				startDate: rangeValue[0].format('DD-MM-YYYY'), 
				finishDate: rangeValue[1].format('DD-MM-YYYY'), 
				workload: fieldsValue.workload, 
				logo: "https://miro.medium.com/max/478/1*jriufqYKgJTW4DKrBizU5w.png", 
				digitalSignature: imageURL
			}
		])

		message.success('Evento criado com sucesso')

		/*Retira o componente do formulário de eventos e volta para a lista*/
	    setToCreateFormEvent(false)
	    }  
	};

	/*Buscando os eventos do organizador*/

	let eventsOfOrganizer = []

	eventos.map(evento => {
		if(evento.user === organizador) {
			eventsOfOrganizer.push(evento)
		}
	})

	/*Verifica se existem eventos cadastrados para mostrar elemento do Antd 'No Data'*/
	let noEvents = true

	/* ------------- Deletando Eventos ---------------*/
	const deleteEvent = (eventToBeDeleted) => {

		message.success('O evento foi excluido')

		setEventos( eventsOfOrganizer.filter(evento => {
			if(evento.course !== eventToBeDeleted) {
				return evento
			}
		}))
	}

	/* -------------- Editando eventos ----------------*/
	const beforeEdit = () => {

		if( !company || !course || !startDate || !finishDate || ! workload || !imageURL){
			message.error('Por favor, não deixe seus dados vazios.')
			//quando o formulário aparece na tela, essa mensagem aparece, caso o campo não tenha sido preenchido.
		} else {
			setToEditFormEvent(!toEditFormEvent)
		}
	}

	//Ao salvar as informações editadas:
	const saveEditFormEvent = (e) => {
		e.preventDefault();
		//Os campos que devem ser preenchidos:
		if( !company || !course || !startDate || !finishDate || ! workload || !imageURL){
			message.error('Por favor, preencha todos os campos do formulário.')
			//quando o formulário aparece na tela, essa mensagem aparece, caso o campo não tenha sido preenchido.

		} else {
			/*Atualizando o evento do organizador*/
			setEventos(eventsOfOrganizer.map(evento => {
				
				/*Mudando somente o evento requerido*/
				if(eventEdited === evento.course) {
					evento['company'] = company
					evento['course'] = course
					evento['startDate'] = startDate
					evento['finishDate'] = finishDate
					evento['workload'] = workload
					evento['digitalSignature'] = imageURL

					return evento;
				} else {
					return evento;
				}
				
			}) )

			message.success('Os dados do evento foram atualizados com sucesso!')

			/*Voltando para a lista de eventos*/
			//setToEditFormEvent(!toEditFormEvent)
		}
		
	}

	const clickEditFormEvent = (eventToBeEdit) => {

		/*Trocando a lista de eventos pelo formulário de edição*/
		setToEditFormEvent(!toEditFormEvent)

		/*Guardando qual evento será editado*/
		setEventEdited(eventToBeEdit.course)

		setCompany(eventToBeEdit.company)
		setCourse(eventToBeEdit.course)
		setStartDate(eventToBeEdit.startDate)
		setFinishDate(eventToBeEdit.finishDate)
		setWorkload(eventToBeEdit.workload)
	}

	/*Esta função é acionada quando o botão para o check list é acionado*/
	const saveEventToList = (eventToList) => {
		setList(true)
		setEventChecked(eventToList)
	}

	/*Esta função é acionada quando o botão para mais infomações do evento*/
	const seeEvents = (eventToList) => {
		setSeeEvents(true)
		setEventChecked(eventToList)
	}

	return(
		<>
		
		<div style={{ display: ( toEditFormEvent || toCreateFormEvent || toProfile || toList || toSeeEvents )?  'none' : null }}>

			<h1 className="title-2-list-events"><UserOutlined onClick={() => setProfile(true)}/> {organizador}</h1>

			<Button className="button-add" onClick={() => setToCreateFormEvent(true)}><UsergroupAddOutlined/> Cadastrar mais um evento</Button>
			
			<br/>
			<h1 className="title">Eventos Cadastrados</h1>
			<div className="listEvents">
			{
				eventos.map(eventoJson => {

					if(eventoJson.user === organizador ){
						noEvents = false
						return(
							<Card 
								style={{ width: 300 }}
								    cover={
								     	<img
								   			alt="Poster do evento"
								    		src="https://jaquelinecramos.files.wordpress.com/2018/03/dyfqkqaw0aad5xm.jpg?w=776"
								      />
								    }
								    actions={[
								    	<>
								    	<Popover content={<h5>Ver mais info. do evento</h5>}>
								     		<Button style={{ borderColor: 'transparent'}} onClick={() => seeEvents(eventoJson) }><HeartOutlined key="edit" /></Button>
								     	</Popover>

								     	<Popover content={<h5>Editar evento</h5>}>
								     		<Button style={{ borderColor: 'transparent'}} onClick={() =>  clickEditFormEvent(eventoJson) } ><FormOutlined key="edit" /></Button>
								     	</Popover>

								     	<Popover content={<h5>Participantes</h5>}>
								     		<Button style={{ borderColor: 'transparent'}} onClick={() =>  saveEventToList(eventoJson)}><TeamOutlined key="ellipsis" /></Button>
								    	</Popover>

								     	<Popconfirm 
								     		title="Você tem certeza de que quer excluir este evento?"
								     		onConfirm={() => deleteEvent(eventoJson.course) }
								     		okText="Sim"
								     		cancelText="Não"
								     	>
								    		<Button style={{ borderColor: 'transparent'}} ><CloseOutlined key="edit" /></Button>
								    	</Popconfirm>
								    	</>
								    ]}
								  >
								    <Meta
								      avatar={<Avatar src="https://cdn-images-1.medium.com/max/1200/1*B8rGvo7fJ7qL4uFJ_II_-w.png" />}
								      title={<h4 style={{ color: '#C6255A'}}>{eventoJson.course}</h4>}
								      description={
								      		<>
								      			<h5 style={{ fontSize: '12px'}}>Inicio: &nbsp;{eventoJson.startDate}</h5>
								      			
								      			<h5 style={{ fontSize: '12px'}}>Encerramento: &nbsp;{eventoJson.finishDate}</h5>
								      		</>
								      	}
								    />
							</Card>
						)
					}
				})
			}
			{ noEvents && <Empty style={{marginTop: '5%'}}/> }
			</div>

		</div>
		{toEditFormEvent && 
		// Mostra na tela o formulário com os campos para serem editados
		//o value está trazendo as informações do último cadastrado "Lucas...."
		//quando eu troco o nome do course (Evento), altera o nome dos 3 eventos que estão sendo mostrados na tela
			<div className="edit-event"
				style={{ display: toEditFormEvent ?  'block' : 'none' }} >

				<h2 className="edit-event-title">Edite os dados do seu evento:</h2>
				<h4>Comunidade:</h4>
				<Input 
					className="edit-event-input" 
					placeholder="Comunidade" 
					value={company} 
					onChange={ newValue => setCompany(newValue.target.value) } />
				<br/>
				<h4>Evento:</h4>
				<Input 
					className="edit-event-input" 
					placeholder="Evento" 
					value={course} 
					onChange={ newValue => setCourse(newValue.target.value) }/>
				<br/>
				<h4>Data de Inicio:</h4>
				<Input 
					className="edit-event-input" 
					placeholder="Data de Início" 
					value={startDate} 
					onChange={ newValue => setStartDate(newValue.target.value) }/>
				<br/>
				<h4>Data de Encerramento:</h4>
				<Input 
					className="edit-event-input" 
					placeholder="Data de Fim" 
					value={finishDate} 
					onChange={ newValue => setFinishDate(newValue.target.value) }/>
				<br/>
				<h4>Carga Horaria:</h4>
				<Input 
					className="edit-event-input" 
					placeholder="Carga Horária" 
					value={workload} 
					onChange={ newValue => setWorkload(newValue.target.value) }/>
				<br/>
				<h4>Assinatura Digital:</h4>
				<div>
					<Popup modal trigger={<Button className="button-open-pad">Abrir Pad para assinar</Button>}>
						{ close => (
							<>
								<SignaturePad ref={sigCanvas}
											  canvasProps={{
											  	className: 'signatureCanvas'
											  }}
								/>
								<Button onClick={save} className="button-save">Salvar</Button>
								<Button onClick={clear} >Apagar Tudo</Button>
								<Button onClick={close} className="button-close" >Fechar</Button>
							</>
						)}
					</Popup>
					<br/>
					<br/>
					{ imageURL ? (
						<img
							src={imageURL}
							alt="Minha assinatura Digital"
							className="buttons-pad"

						/>
					) : null }
				</div>

				<Button 
					className="button-edit-event" type="primary" primary 
					onClick={saveEditFormEvent}>Atualizar dados</Button>
				<br/>

				<Button className="back-edit-event" onClick={beforeEdit}>Voltar para a lista de eventos</Button>
			</div>
		}

		{ toCreateFormEvent && 
			<>
				
				<Form name="time_related_controls" {...formItemLayout} onFinish={onFinish}>  
			      <div className="inputs-event">
			        <h1 className="h1-form-event">Criando um novo evento</h1>
			        <Form.Item
				        {...formInputLayout}
				        {...rangeInputs}
			          className="input-1-event"
				        name="company"
				        label="Comunidade" >

			          <Input placeholder="Digite a comunidade responsável pelo evento" />
			        </Form.Item>

			        <Form.Item
			          {...formInputLayout}
			          {...rangeInputs}
			          className="input-2-event"
			          name="course"
			          label="Curso/Evento">
			          <Input placeholder="Digite o nome do evento"  />
			        </Form.Item>

			        <Form.Item 
			          {...rangeInputs}
			          className="input-3-event"
			          label="Carga Horária" 
			          name="workload" >
			          <InputNumber /> 
			        </Form.Item>

			        <Form.Item 
			          name="range-picker" 
			          className="input-4-event"
			          label="Data de inicio/fim do evento" 
			          {...rangeConfig}>
			          <RangePicker />
			        </Form.Item>

			        <div className="upload-assinature">
			        	<h3 className="h3-form-event">Assinatura Digital:</h3>
			        	<div>
							<Popup modal trigger={<Button className="button-open-pad">Abrir Pad para assinar</Button>}>
								{ close => (
									<>
										<SignaturePad ref={sigCanvas}
													  canvasProps={{
													  	className: 'signatureCanvas'
													  }}
										/>
										<Button onClick={save} className="button-save">Salvar</Button>
										<Button onClick={clear} >Apagar Tudo</Button>
										<Button onClick={close} className="button-close" >Fechar</Button>
									</>
								)}
							</Popup>
							<br/>
							<br/>
							{ imageURL ? (
								<img
									src={imageURL}
									alt="Minha assinatura Digital"
									className="buttons-pad"
								/>
							) : <h4 style={{ color: 'red'}}>Sem assinatura</h4> }
						</div>
			        </div>


			        <Form.Item>
			        	<Button type="primary" htmlType="submit" className="button-events">
			        		Cadastrar Novo Evento
			        	</Button>
			            <br/>
			        </Form.Item>

			         
			      </div>
			    </Form>
				<Button 
					onClick={() => setToCreateFormEvent(false)} 
					className="button-back-from-create"
					>
	                Voltar para a lista de Eventos
	            </Button>
			</>
		}

		{ toProfile && 
			<>
				<ProfileCard organizador={organizador} users={users} assinatura={imageURL}/>
				<Button 
					onClick={() => setProfile(false)}
					className="button-back-of-profile" 
					>
	                Voltar para a lista de Eventos
	            </Button>
			</>
		}

		{ toList &&
			<>
				<ListOfPresents evento={eventChecked}/>
				<Button onClick={() => setList(false)} className="button-back-from-list" style={{ marginButtom: '-20%'}}>
	                Voltar para a lista de Eventos
	            </Button>
	        </>
		}

		{
			toSeeEvents && 
				<>
					<InfoEvent evento={eventChecked}/>
					<Button 
						onClick={() => setSeeEvents(false)}
						className="button-back-of-profile" 
						>
	                	Voltar para a lista de Eventos
	            	</Button>
	            </>
		}
		</>		
			
	);
}
Example #28
Source File: index.js    From topology-react with MIT License 4 votes vote down vote up
CanvasProps = ({ data, form: { getFieldDecorator }, form, onFormValueChange }) => {

  const { lineWidth, dash, strokeStyle, name, fromArrow, toArrow } = data?.line || {};

  useEffect(() => {
    form.validateFields((err, value) => {
      if (err) return;
      if (Object.keys(data).length === 0) return;
      if (value.lineWidth === lineWidth && value.dash === dash && value.strokeStyle === strokeStyle && value.name === name && value.toArrow === toArrow && value.fromArrow === fromArrow) return;
      onFormValueChange(value);
      form.resetFields();
    })
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, [form])

  /**
  * 渲染位置和大小的表单
  */

  const renderForm = useMemo(() => {
    return <Form>
      <Row>
        <Col span={24}>
          <Form.Item label="线条颜色">
            {getFieldDecorator('strokeStyle', {
              initialValue: strokeStyle
            })(<Input type="color" />)}
          </Form.Item>
        </Col>
        <Col span={24}>
          <Form.Item label="线条类型">
            {getFieldDecorator('name', {
              initialValue: name
            })(
              <Select style={{ width: '95%' }}>
                <Option value="curve">贝塞尔曲线</Option>
                <Option value="polyline">折线</Option>
                <Option value="line">直线</Option>
              </Select>
            )}
          </Form.Item>
        </Col>
        <Col span={12}>
          <Form.Item label="线条样式">
            {getFieldDecorator('dash', {
              initialValue: dash
            })(
              <Select style={{ width: '95%' }}>
                <Option value={0}>_________</Option>
                <Option value={1}>---------</Option>
                <Option value={2}>_ _ _ _ _</Option>
                <Option value={3}>- . - . - .</Option>
              </Select>
            )}
          </Form.Item>
        </Col>
        <Col offset={1} span={11}>
          <Form.Item label="线条宽度">
            {getFieldDecorator('lineWidth', {
              initialValue: lineWidth
            })(<InputNumber style={{ width: '100%' }} />)}
          </Form.Item>
        </Col>
        <Col span={24}>
          <Form.Item label="起点箭头">
            {getFieldDecorator('fromArrow', {
              initialValue: fromArrow
            })(
              <Select style={{ width: '95%' }}>
                <Option value="">无箭头</Option>
                <Option value="triangleSolid">实心三角形</Option>
                <Option value="triangle">空心三角形</Option>
                <Option value="diamondSolid">实心菱形</Option>
                <Option value="diamond">空心菱形</Option>
                <Option value="circleSolid">实心圆</Option>
                <Option value="circle">空心圆</Option>
                <Option value="line">线型箭头</Option>
                <Option value="lineUp">上单边线箭头</Option>
                <Option value="lineDown">下单边线箭头</Option>
              </Select>
            )}
          </Form.Item>
        </Col>
        <Col span={24}>
          <Form.Item label="结束箭头">
            {getFieldDecorator('toArrow', {
              initialValue: toArrow
            })(
              <Select style={{ width: '95%' }}>
                <Option value="">无箭头</Option>
                <Option value="triangleSolid">实心三角形</Option>
                <Option value="triangle">空心三角形</Option>
                <Option value="diamondSolid">实心菱形</Option>
                <Option value="diamond">空心菱形</Option>
                <Option value="circleSolid">实心圆</Option>
                <Option value="circle">空心圆</Option>
                <Option value="line">线型箭头</Option>
                <Option value="lineUp">上单边线箭头</Option>
                <Option value="lineDown">下单边线箭头</Option>
              </Select>
            )}
          </Form.Item>
        </Col>
      </Row>
    </Form>
  }, [lineWidth, dash, name, toArrow, fromArrow, strokeStyle, getFieldDecorator]);


  return (
    <div className="rightArea">
      <Tabs defaultActiveKey="1">
        <TabPane tab="外观" key="1" style={{ margin: 0 }}>
          <Collapse defaultActiveKey={['1']}>
            <Panel header="样式" key="1">
              {
                renderForm
              }
            </Panel>
          </Collapse>
        </TabPane>
      </Tabs>
    </div>
  );
}
Example #29
Source File: L2Bridge.jsx    From Tai-Shang-NFT-Wallet with MIT License 4 votes vote down vote up
/*
This is a component for bridging between L1 & L2
Currently it supports Testnet deposits for Arbitrum & Optimism

 __          _______ _____
 \ \        / /_   _|  __ \
  \ \  /\  / /  | | | |__) |
   \ \/  \/ /   | | |  ___/
    \  /\  /   _| |_| |
     \/  \/   |_____|_|


*/

export default function L2ArbitrumBridge({ address, userSigner }) {
  const [L1EthBalance, setL1EthBalance] = useState("...");
  const [L2EthBalance, setL2EthBalance] = useState("...");
  const [L1Provider, setL1Provider] = useState("");
  const [L2Provider, setL2Provider] = useState("");
  const [rollup, setRollup] = useState("arbitrum");
  const [environment, setEnvironment] = useState("test");

  const rollupConfig = {
    arbitrum: {
      test: { L1: NETWORKS.rinkeby, L2: NETWORKS.rinkebyArbitrum },
      main: { L1: NETWORKS.mainnet, L2: NETWORKS.arbitrum },
      local: { L1: NETWORKS.localArbitrumL1, L2: NETWORKS.localArbitrum },
    },
    optimism: {
      test: { L1: NETWORKS.kovan, L2: NETWORKS.kovanOptimism },
      local: { L1: NETWORKS.localOptimismL1, L2: NETWORKS.localOptimism },
    },
  };

  const activeConfig = rollupConfig[rollup][environment];

  const selectedChainId =
    userSigner && userSigner.provider && userSigner.provider._network && userSigner.provider._network.chainId;

  const tx = Transactor(userSigner);

  useEffect(() => {
    async function setProviders() {
      const L1 = activeConfig.L1;
      const L2 = activeConfig.L2;
      setL1Provider(new ethers.providers.StaticJsonRpcProvider(L1.rpcUrl));
      setL2Provider(new ethers.providers.StaticJsonRpcProvider(L2.rpcUrl));
      setL1EthBalance("...");
      setL2EthBalance("...");
    }
    setProviders();
  }, [rollup]);

  const contracts = useContractLoader(userSigner, { externalContracts: L1BridgeMetadata, hardhatContracts: {} });

  useOnBlock(L1Provider, async () => {
    console.log(`⛓ A new mainnet block is here: ${L1Provider._lastBlockNumber}`);
    const yourL1Balance = await L1Provider.getBalance(address);
    setL1EthBalance(yourL1Balance ? ethers.utils.formatEther(yourL1Balance) : "...");
    const yourL2Balance = await L2Provider.getBalance(address);
    setL2EthBalance(yourL2Balance ? ethers.utils.formatEther(yourL2Balance) : "...");
  });

  const { Option } = Select;
  const formItemLayout = {
    labelCol: {
      xs: { span: 24 },
      sm: { span: 8 },
    },
    wrapperCol: {
      xs: { span: 24 },
      sm: { span: 12 },
    },
  };
  const tailFormItemLayout = {
    wrapperCol: {
      xs: {
        span: 24,
        offset: 0,
      },
      sm: {
        span: 12,
        offset: 8,
      },
    },
  };

  const columns = [
    {
      title: "",
      dataIndex: "token",
      key: "token",
      align: "center",
    },
    {
      title: `${activeConfig.L1.name} L1 Balance`,
      dataIndex: "l1",
      key: "l1",
      align: "center",
    },
    {
      title: `${activeConfig.L1.name} ${rollup} Balance`,
      dataIndex: "l2",
      key: "l2",
      align: "center",
    },
  ];

  const data = [
    {
      key: "1",
      token: "ETH",
      l1: "Ξ" + L1EthBalance,
      l2: "Ξ" + L2EthBalance,
    },
  ];

  const [form] = Form.useForm();

  const onAssetChange = value => {
    console.log(value);
  };

  async function onFinish(values) {
    console.log(contracts);
    console.log(values.amount.toString());
    console.log(rollup);
    let newTx;
    try {
      if (rollup === "arbitrum") {
        newTx = await tx(
          contracts.Inbox.depositEth(1_300_000, {
            value: utils.parseEther(values.amount.toString()),
            gasLimit: 300000,
          }),
        );
      } else if (rollup === "optimism") {
        newTx = await tx(
          contracts.OVM_L1StandardBridge.depositETH(1_300_000, "0x", {
            value: utils.parseEther(values.amount.toString()),
          }),
        );
      }
      await newTx.wait();
      console.log("woop!");
    } catch (e) {
      console.log(e);
      console.log("something went wrong!");
    }
  }

  const onReset = () => {
    form.resetFields();
  };

  const wrongNetwork = selectedChainId !== activeConfig.L1.chainId;

  return (
    <div style={{ padding: 16, width: 800, margin: "auto", marginBottom: 128 }}>
      <div style={{ border: "1px solid #cccccc", padding: 16, width: 800, margin: "auto", marginBottom: 128 }}>
        <h2>Welcome to the L2 Deposit Bridge!</h2>
        <Radio.Group
          value={rollup}
          onChange={e => {
            setRollup(e.target.value);
          }}
          style={{ marginBottom: 10 }}
        >
          <Radio.Button value="arbitrum">Arbitrum</Radio.Button>
          <Radio.Button value="optimism">Optimism</Radio.Button>
        </Radio.Group>

        <Table columns={columns} dataSource={data} pagination={false} style={{ marginBottom: 20 }} />

        <Form
          {...formItemLayout}
          form={form}
          name="control-hooks"
          onFinish={onFinish}
          initialValues={{ assetType: "eth" }}
        >
          <Form.Item
            name="assetType"
            label="Select Asset Type"
            rules={[
              {
                required: true,
              },
            ]}
          >
            <Select placeholder="Select an asset type" onChange={onAssetChange} allowClear>
              <Option value="eth">ETH</Option>
              <Option disabled value="erc20">
                ERC-20
              </Option>
            </Select>
          </Form.Item>
          <Form.Item name="address" label="Address">
            <Input disabled placeholder={address} />
          </Form.Item>
          <Form.Item
            name="amount"
            label="Amount to bridge"
            rules={[
              {
                required: true,
              },
            ]}
          >
            <InputNumber />
          </Form.Item>
          <Form.Item {...tailFormItemLayout}>
            <Button type="primary" htmlType="submit" disabled={wrongNetwork}>
              {wrongNetwork ? `Switch wallet to ${activeConfig.L1.name}` : "Deposit"}
            </Button>
          </Form.Item>
        </Form>
      </div>
    </div>
  );
}