antd#Switch JavaScript Examples

The following examples show how to use antd#Switch. 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: ThemeSwitch.jsx    From Tai-Shang-NFT-Wallet with MIT License 6 votes vote down vote up
export default function ThemeSwitcher() {
  const theme = window.localStorage.getItem("theme");
  const [isDarkMode, setIsDarkMode] = useState(!(!theme || theme === "light"));
  const { switcher, currentTheme, status, themes } = useThemeSwitcher();

  useEffect(() => {
    window.localStorage.setItem("theme", currentTheme);
  }, [currentTheme]);

  const toggleTheme = isChecked => {
    setIsDarkMode(isChecked);
    switcher({ theme: isChecked ? themes.dark : themes.light });
  };

  // Avoid theme change flicker
  // if (status === "loading") {
  //   return null;
  // }

  return (
    <div className="main fade-in" style={{ position: "fixed", right: 8, bottom: 8 }}>
      <span style={{ padding: 8 }}>{currentTheme === "light" ? "☀️" : "?"}</span>
      <Switch checked={isDarkMode} onChange={toggleTheme} />
    </div>
  );
}
Example #2
Source File: index.js    From scalable-form-platform with MIT License 6 votes vote down vote up
render() {
        const {id, disabled, readonly, value, options, autofocus} = this.props;
        let {_errorType, validate, ...otherOptions} = options;
        otherOptions = this._filterSystemOptions(otherOptions);

        //解析schema中约定的_errorType字段,用来标识是validate中哪种类型校验不通过
        let validateMessage = '';
        _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-switch': true,
                'has-error': _errorType !== ''
            })}>
                <Switch
                    id={id}
                    autoFocus={autofocus}
                    disabled={disabled}
                    readOnly={readonly}
                    checked={value}
                    onChange={this.handleSwitchChange}
                    {...otherOptions}
                />
                <div className="ant-form-explain">{validateMessage}</div>
            </div>
        );
    }
Example #3
Source File: ThemeSwitch.jsx    From moonshot with MIT License 6 votes vote down vote up
export default function ThemeSwitcher() {

  const theme = window.localStorage.getItem("theme");
  const [isDarkMode, setIsDarkMode] = useState(!theme || theme == "light" ? false : true);
  const { switcher, currentTheme, status, themes } = useThemeSwitcher();

  useEffect(() => {
    window.localStorage.setItem("theme", currentTheme);
  }, [currentTheme]);

  const toggleTheme = (isChecked) => {
    setIsDarkMode(isChecked);
    switcher({ theme: isChecked ? themes.dark : themes.light });
  };

  // Avoid theme change flicker
  // if (status === "loading") {
  //   return null;
  // }

  return (
    <div className="main fade-in" style={{position:"fixed",right:8,bottom:8}}>
      <span style={{padding:8}}>{currentTheme=="light" ? "☀️" : "?"}</span>
      <Switch checked={isDarkMode} onChange={toggleTheme} />
    </div>
  );
}
Example #4
Source File: UserManagement.jsx    From React-Nest-Admin with MIT License 6 votes vote down vote up
columns = [
  {
    title: "用户名",
    dataIndex: "username",
    key: "username",
    render: username => <span>{username}</span>
  },
  {
    title: "角色",
    key: "roles",
    dataIndex: "roles",
    render: roles => (
      <span>
        {roles.map(role => {
          let color = role === "admin" ? "geekblue" : "green";
          return (
            <Tag color={color} key={role}>
              {role.toUpperCase()}
            </Tag>
          );
        })}
      </span>
    )
  },
  {
    title: "是否停用",
    key: "isEnabled",
    render: ({ isEnabled }) => (
      <Switch
        disabled
        checkedChildren="停用"
        unCheckedChildren="启用"
        checked={isEnabled}
      />
    )
  }
]
Example #5
Source File: TestPlatform.jsx    From juno with Apache License 2.0 6 votes vote down vote up
function TestPlatformSetting(props) {
  const [saveField, settingProps, form, editing] = useSettingBlock(
    'test_platform',
    props.dispatch,
    false,
  );
  const { setting } = props;

  useEffect(() => {
    form.setFieldsValue(setting);
  }, [setting]);

  return (
    <SettingBlock {...settingProps} title={'测试平台'}>
      <Form form={form}>
        <Form.Item label={'启用'} valuePropName={'checked'} name={'enable'}>
          <Switch disabled={!editing} onChange={(checked) => saveField({ enable: checked })} />
        </Form.Item>
      </Form>
    </SettingBlock>
  );
}
Example #6
Source File: index.js    From gobench with Apache License 2.0 6 votes vote down vote up
render() {
    const { disabled } = this.state
    return (
      <div>
        <h5 className="mb-3">
          <strong>Basic</strong>
        </h5>
        <div className="mb-5">
          <Slider defaultValue={30} disabled={disabled} />
          <Slider range defaultValue={[20, 50]} disabled={disabled} />
          <br />
          <Switch
            unCheckedChildren="enabled"
            checkedChildren="disabled"
            checked={disabled}
            onChange={this.handleDisabledChange}
          />
        </div>
      </div>
    )
  }
Example #7
Source File: NotifyByEmail.jsx    From ui with MIT License 6 votes vote down vote up
NotifyByEmail = (props) => {
  const { experimentId } = props;
  const experiment = useSelector((state) => state.experiments[experimentId]) || false;
  const dispatch = useDispatch();
  const changeEmailNotification = (value) => {
    dispatch(updateExperiment(experimentId, { notifyByEmail: value }));
  };
  const { activeExperimentId } = useSelector((state) => state?.experiments?.meta) || false;

  useEffect(() => {
    if (!activeExperimentId) {
      dispatch(loadExperiments());
    }
  }, []);

  return (
    <Space direction='horizontal'>
      <Text>Get notified about your pipeline status via email  </Text>
      <Switch
        checked={experiment?.notifyByEmail}
        onChange={(value) => changeEmailNotification(value)}
      />
    </Space>
  );
}
Example #8
Source File: HtmlEditor.js    From youdidao-unmanned-shop with MIT License 6 votes vote down vote up
render() {
    const { raw, value } = this.state;
    


    return (
      <div>
        <Switch
          checkedChildren="开启"
          unCheckedChildren="关闭"
          value={raw}
          onChange={this.onSwitchChange}
        />
        {' HTML'}
        {raw ? 
          <TextArea value={value} rows={4} onChange={this.onTextAreaChange} /> 
          : null}
        <div
          ref={ref => {
            this.editorElem = ref;
          }}
        />
      </div>
    );
  }
Example #9
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 #10
Source File: utils.js    From the-eye-knows-the-garbage with MIT License 6 votes vote down vote up
BooleanDisplay = (text) => {
  return <Switch disabled checked={text} />;
}
Example #11
Source File: change.jsx    From virtuoso-design-system with MIT License 6 votes vote down vote up
render() {
    return (
      <div>
        <div>
          <Badge count={this.state.count}>
            <a href="#" className="head-example" />
          </Badge>
          <ButtonGroup>
            <Button onClick={this.decline}>
              <MinusOutlined />
            </Button>
            <Button onClick={this.increase}>
              <PlusOutlined />
            </Button>
            <Button onClick={this.random}>
              <QuestionOutlined />
            </Button>
          </ButtonGroup>
        </div>
        <div style={{ marginTop: 10 }}>
          <Badge dot={this.state.show}>
            <a href="#" className="head-example" />
          </Badge>
          <Switch onChange={this.onChange} checked={this.state.show} />
        </div>
      </div>
    );
  }
Example #12
Source File: index.jsx    From schema-plugin-flow with MIT License 5 votes vote down vote up
SettingPanel = props => {
  const {
    settingType = 'bizPlg', onTypeChange,
    useSavedSchema = false, onSchemaTypeChange,
    sysExtTypes,
    sysExts, customer, customerTyps,
    onCustomExtChange, onSysExtChange
  } = props;
  return (
    <>
      <h3 className="setting-title">页面扩展设置</h3>
      <Switch
        className="setting-type"
        checked={settingType === 'bizPlg'}
        onChange={onTypeChange}
        checkedChildren="业务态"
        unCheckedChildren="开发态"
      />
      <Switch checked={useSavedSchema} onChange={onSchemaTypeChange} checkedChildren="使用保存的schema" unCheckedChildren="使用默认的schema" />
      <div>
        {
          settingType === 'bizPlg' ? (
            <Settings
              sysExtTypes={sysExtTypes}
              sysExts={sysExts}
              customer={customer}
              customerTyps={customerTyps}
              onCustomExtChange={onCustomExtChange}
              onSysExtChange={onSysExtChange}
            />
          ) : (
            <div>
              使用Sifo拖拽插件构建新的schema,允许对初始schema的节点进行拖拽编辑,也支持添加注册的组件节点。
            </div>
          )
        }
      </div>
    </>
  );
}
Example #13
Source File: CreatePage.js    From bonded-stablecoin-ui with MIT License 5 votes vote down vote up
CreatePage = () => {
  const [current, setCurrent] = useState(0);
  const [type, setType] = useState(2)
  const [data, setData] = useState({});
  const [width] = useWindowSize();
  const { t } = useTranslation();

  useEffect(() => {
    setCurrent(0)
    setData({});
  }, [type])

  return (
    <div>
      <Helmet title="Bonded stablecoins - Create" />
      <Title level={1}>{t("create.title", "Create")}</Title>
      <div style={{ display: "flex" }}>
        <Paragraph style={{ marginRight: 10 }}>Enable "Decision engine" (v2 stablecoins)</Paragraph> <Switch defaultChecked onChange={(c) => setType(c ? 2 : 1)} />
      </div>
      <div><Paragraph type="secondary">{t("create.de_desc", "The decision engine automatically intervenes when it is necessary to return the price back to the peg. A Stability Fund is created to make this possible, all growth tokens are held by the Fund, and investors buy shares in the Fund.")}</Paragraph></div>
      {type && <div>
        <Steps
          size="large"
          current={current}
          type={width >= 992 ? "navigation" : undefined}
          direction={width >= 760 ? "horizontal" : "vertical"}
          style={{ marginBottom: 35 }}
        >
          <Step title={t("create.steps.curve", "Curve")} description={t("create.setting", "Parameter setting")} />
          <Step title={t("create.steps.capacitor", "Capacitor")} description={t("create.setting", "Parameter setting")} />
          <Step title={t("create.steps.governance", "Governance")} description={t("create.setting", "Parameter setting")} />
          {type === 2 && <Step title={t("create.steps.decision", "Decision engine")} description={t("create.setting", "Parameter setting")} />}
          <Step title={t("create.steps.create", "Create")} description={t("create.sending", "Sending a request")} />
        </Steps>

        {current === 0 && (
          <CurverStep type={type} setCurrent={setCurrent} setData={setData} />
        )}
        {current === 1 && (
          <CapacitorStep type={type} setCurrent={setCurrent} setData={setData} />
        )}
        {current === 2 && (
          <GovernanceStep setCurrent={setCurrent} setData={setData} />
        )}

        {current === 3 && type === 2 && <DecisionStep setCurrent={setCurrent} setData={setData} />}
        {((type === 2 && current === 4) || (type === 1 && current === 3)) && <CreateStep setCurrent={setCurrent} data={data} type={type} />}
        {((type === 2 && current !== 4) || (type === 1 && current !== 3)) && (
          <div style={{ fontSize: 16, paddingTop: 18 }}>
            <span style={{ color: "red " }}>*</span> - {t("create.required", "Required field")}
          </div>
        )}
      </div>}
    </div>
  );
}
Example #14
Source File: index.jsx    From juno with Apache License 2.0 5 votes vote down vote up
function ModalEdit(props) {
  const { visible, onOk } = props;
  const { id, sub_path, title, is_rewrite, proxy_addr } = props.resource;
  const [form] = Form.useForm();

  useEffect(() => {
    if (!visible) {
      return;
    }
    form.resetFields();
  }, [visible]);

  return (
    <Modal
      width={700}
      visible={props.visible}
      title={'编辑'}
      onOk={() => {
        form.submit();
      }}
      onCancel={() => props.showModalEdit({ visible: false })}
    >
      <Form
        form={form}
        labelCol={{ span: 3 }}
        onFinish={(fields) => {
          createItem({
            id: id,
            ...fields,
            is_rewrite: fields.is_rewrite ? 1 : 0,
          }).then((r) => {
            if (r.code !== 0) {
              message.error('更新失败:' + r.msg);
              return;
            }
            if (props.onOk) props.onOk();
            message.success('更新成功');
            props.showModalEdit(false);
            return;
          });
        }}
      >
        <Form.Item
          label={'名称'}
          name={'title'}
          rules={[{ required: true, message: '请输入名称' }]}
          initialValue={title}
        >
          <Input />
        </Form.Item>
        <Form.Item
          label={'子路径'}
          name={'sub_path'}
          rules={[{ required: true, message: '请输入子路径' }]}
          initialValue={sub_path}
        >
          <Input />
        </Form.Item>
        <Form.Item
          label={'代理路径'}
          name={'proxy_addr'}
          rules={[{ required: true, message: '请输入代理路径' }]}
          initialValue={proxy_addr}
        >
          <Input />
        </Form.Item>
        <Form.Item
          label={'是否重写'}
          name={'is_rewrite'}
          valuePropName="checked"
          rules={[{ required: true, message: '选择是否重写' }]}
          initialValue={is_rewrite === 1}
        >
          <Switch checkedChildren="开启" unCheckedChildren="关闭" />
        </Form.Item>
      </Form>
    </Modal>
  );
}
Example #15
Source File: index.js    From YApi-X with MIT License 5 votes vote down vote up
render() {
    return (
      <div className="m-panel">
        <Form>
          <FormItem
            label={
              <span>
                是否开启&nbsp;<a
                  target="_blank"
                  rel="noopener noreferrer"
                  href="https://hellosean1025.github.io/yapi/documents/project.html#%E5%85%A8%E5%B1%80mock"
                >
                  <Tooltip title="点击查看文档">
                    <Icon type="question-circle-o" />
                  </Tooltip>
                </a>
              </span>
            }
            {...formItemLayout}
          >
            <Switch
              checked={this.state.is_mock_open}
              onChange={this.onChange}
              checkedChildren="开"
              unCheckedChildren="关"
            />
          </FormItem>
          <FormItem label="Mock脚本" {...formItemLayout}>
            <AceEditor
              data={this.state.project_mock_script}
              onChange={this.handleMockJsInput}
              style={{ minHeight: '500px' }}
            />
          </FormItem>
          <FormItem {...tailFormItemLayout}>
            <Button type="primary" htmlType="submit" onClick={this.handleSubmit}>
              保存
            </Button>
          </FormItem>
        </Form>
      </div>
    );
  }
Example #16
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 #17
Source File: Editpage.js    From camel-store-admin with Apache License 2.0 5 votes vote down vote up
render(){
    const {  categorydata, CategoryLoading, onUpload, visible } = this.state;
    const { location, upload } = this.props
    let id = location.query.id

    const createTem = this.getAuth('createTemplate');
    const wh = window.screen.height;

    return(
      <PageHeaderWrapper loading={CategoryLoading}>
        <Card className={styles.main} title={id ? '编辑商品类别' : '新增商品类别'}>
          <Spin spinning={Boolean(onUpload || upload)} tip='正在操作中'>
          <Form className={styles.editform}>
            <FormItem label="类别名" required {...formItemLayout}>
              <Input style={{ width: 150 }} placeholder='请输入分类名称'
                value={categorydata.name}
                onChange={(e) => this.handlecategory(e.target.value,'name')}
              />
            </FormItem>
            <FormItem label="排序" {...formItemLayout}>
              <InputNumber style={{ width: 150 }} placeholder='请输入排序'
                           onChange={(e) => this.handlecategory(e,'index')}
                           value={categorydata.index}
                           min={0}
              />
            </FormItem>
            {/*<FormItem label="类别图" required {...formItemLayout}*/}
              {/*className={styles.imageItem}*/}
              {/*help="支持PNG, JPG, 图片大小不超过200K,建议像素为900 * 500。"*/}
            {/*>*/}
              {/*<UploadImage*/}
                {/*limit={1}*/}
                {/*openSource={categorydata.image ? [categorydata.image].length < 1 : [].length < 1}*/}
                {/*fileList={categorydata.image ? [categorydata.image] : []}*/}
                {/*onChange={(e,list) => this.handleUpload(e,'image',list)}*/}
                {/*handleSource={() => this.openModal(categorydata.image ? [categorydata.image].length < 1 : [].length < 1)}*/}
                {/*restprops={{ openFileDialogOnClick: false }}*/}
              {/*/>*/}
            {/*</FormItem>*/}
            <FormItem label="是否启用" {...formItemLayout}>
              <Switch checked={categorydata.is_active} onChange={(e) => this.handlecategory(e,'is_active')} />
            </FormItem>
            {
              id && (
                <FormItem label="小程序页面路径" help={`/pages/util/index?cid=${id}`} required={false}>
                  <Button size='small' onClick={() => copy(`/pages/util/index?cid=${id}`)}>
                    复制
                  </Button>
                </FormItem>
              )
            }
            <Row>
              <Col span={24} style={{ textAlign: 'right' }}>
                <Link to='/good/categorylist'>
                  <Button>取消</Button>
                </Link>
                <Button type='primary' style={{ marginLeft: 10 }} onClick={this.handleSubmit}>保存</Button>
              </Col>
            </Row>
          </Form>
          </Spin>
          <Modal width="60%" title="素材选择"
                 visible={visible}
                 centered
                 onCancel={() => this.setState({ visible:false })}
                 onOk={() => this.handleSelect()}
                 bodyStyle={{maxHeight: `${wh-300}px`, overflowY: 'auto'}}>
            <SourceImageTab
              limit={1}
              visible={visible}
              onSelectItem={(list) => this.setState({ _selectList: list })}
              {...this.props}/>
          </Modal>
        </Card>
      </PageHeaderWrapper>
    )
  }
Example #18
Source File: index.js    From discern with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
render() {
    const loading2 = this.state.loading2
    return (
      <div>
        <CustomBreadcrumb arr={['反馈','加载中']}/>
        <TypingCard source='页面局部处于等待异步数据或正在渲染过程时,合适的加载动效会有效缓解用户的焦虑。'/>
        <Row gutter={16}>
          <Col span={12}>
            <Card bordered={false} className='card-item'>
              <Spin/>&emsp;
              <Spin indicator={<Icon type='loading'/>}/>
            </Card>
            <Card bordered={false} className='card-item'>
              <Spin tip="Loading...">
                <Alert
                  message="Alert message title"
                  description="Further details about the context of this alert."
                  type="info"
                />
              </Spin>
            </Card>
            <Card bordered={false} className='card-item'>
              <Button onClick={this.NProgressStart} loading={loading2}>页面顶部进度条加载</Button>&emsp;
              <Button onClick={this.NProgressDone}>顶部进度条加载完成</Button>
            </Card>
          </Col>
          <Col span={12}>
            <Card bordered={false} className='card-item'>
              <Spin size='small'/>&emsp;
              <Spin/>&emsp;
              <Spin size='large'/>
            </Card>
            <Card bordered={false} className='card-item'>
              <div style={{marginBottom: '1em'}}>
                <Spin tip="Loading..." spinning={this.state.loading}>
                  <Alert
                    message="Alert message title"
                    description="Further details about the context of this alert."
                    type="info"
                  />
                </Spin>
              </div>
              Loading state:<Switch onChange={(checked) => this.setState({loading: checked})}/>
            </Card>
          </Col>
        </Row>
      </div>
    )
  }
Example #19
Source File: PaymentModeForm.jsx    From erp-crm with MIT License 5 votes vote down vote up
export default function PaymentModeForm({ isUpdateForm = false }) {
  return (
    <>
      <Form.Item
        label="Payment Mode Name"
        name="name"
        rules={[
          {
            required: true,
          },
        ]}
      >
        <Input />
      </Form.Item>
      <Form.Item
        label="Description"
        name="description"
        rules={[
          {
            required: true,
          },
        ]}
      >
        <Input />
      </Form.Item>

      <Form.Item
        label="Mode enabled"
        name="enabled"
        style={{
          display: 'inline-block',
          width: 'calc(50%)',
          paddingRight: '5px',
        }}
        valuePropName="checked"
        initialValue={true}
      >
        <Switch checkedChildren={<CheckOutlined />} unCheckedChildren={<CloseOutlined />} />
      </Form.Item>
      <Form.Item
        label="Is Default Mode"
        name="isDefault"
        style={{
          display: 'inline-block',
          width: 'calc(50%)',
          paddingLeft: '5px',
        }}
        valuePropName="checked"
      >
        <Switch checkedChildren={<CheckOutlined />} unCheckedChildren={<CloseOutlined />} />
      </Form.Item>
    </>
  );
}
Example #20
Source File: Map.js    From network-rc with Apache License 2.0 5 votes vote down vote up
export default function Map({ editabled = false, statusInfo: { gps } = {} }) {
  const [history, setHistory] = useState(store.get("gps history") || []);
  const [defaultLng, defaultLat] = history.length
    ? history[history.length - 1]
    : [117.2, 34.2];
  const { lat = defaultLat, lng = defaultLng } = gps || {};
  const center = [lng, lat];
  const [enabled, setEnabled] = useState(store.get("map enabled"));
  const [zoom, setZoom] = useState(store.get("map zoom") || 15);

  useEffect(() => {
    console.log("GPS", { lat, lng });
    console.log("history", history);
    const { length } = history;
    if (
      length === 0 ||
      lng !== history[length - 1][0] ||
      lat !== history[length - 1][1]
    ) {
      const newHistory = [...history, [lng, lat]]
        .filter(([lng, lat]) => lat !== undefined && lng !== undefined)
        .slice(0, 1000);
      console.log("newHistory", newHistory);
      setHistory(newHistory);
      store.set("gps history", newHistory);
    }
  }, [lat, lng, history]);

  useEffect(() => {
    store.set("map enabled", enabled);
  }, [enabled]);

  useEffect(() => {
    store.set("map zoom", zoom);
  }, [zoom]);

  return (
    <div className={styles.mapContainer}>
      {editabled ? (
        <div className={styles.editor}>
          <Space size="small" align="center" gutter={8}>
            <Switch onChange={setEnabled} checked={enabled} />
            <Button onClick={() => setHistory([])}>清空</Button>
          </Space>
        </div>
      ) : null}
      {enabled && (
        <>
          <Slider
            className={styles.zoom}
            min={2}
            max={20}
            value={zoom}
            onChange={(v) => setZoom(v)}
          />
          <Amap zoom={zoom} center={center}>
            <Marker
              position={center}
              label={{
                direction: "bottom",
              }}
              draggable
            />
            <Polyline path={history} />
          </Amap>
        </>
      )}
    </div>
  );
}
Example #21
Source File: slideNav.js    From ant-simple-pro with MIT License 5 votes vote down vote up
render() {
    const { Sider } = Layout;
    const { getMenuTree, collapsed, location, loadingMenuTree } = this.props;
    const { openKeys , theme } = this.state;
    const defaultProps = collapsed ? {} : { openKeys };
    const defaultSelectedKeys = location.pathname;
    return (
        <Sider trigger={null} collapsible collapsed={collapsed} collapsedWidth={collapsed ? 80 : 200} className={theme === 'light' ? 'ant-layout-sider-light' : 'ant-layout-sider-dark'}>
          <div className={theme === 'light' ?`${style.logon} ${style.Shadow}`:`${style.logon}`}>
            <Link to="/home">
              <SvgIcon iconClass='logon' fontSize='30px' />
              <CSSTransition in={!collapsed} classNames="fade" timeout={200} unmountOnExit>
                 <h2>Ant Simple Pro</h2>
               </CSSTransition>
            </Link>
          </div>
          <div className={style.menuContainer}>
            {
              loadingMenuTree ?
                (getMenuTree.length ? (<Menu mode="inline"
                  onOpenChange={this.onOpenChange}
                  defaultSelectedKeys={[defaultSelectedKeys]}
                  selectedKeys={[defaultSelectedKeys]}
                  defaultOpenKeys={openKeys}
                  {...defaultProps}
                  theme={theme}
                  className={style.menu}>
                    {this.rednerMenu(getMenuTree)}
                </Menu>) : <Empty image={Empty.PRESENTED_IMAGE_SIMPLE} className={style.empty} />) : <LoadingData />
            }
          </div>
          <div className={style.switchThem}>
            <CSSTransition in={!collapsed} classNames="fade" timeout={200} unmountOnExit>
              <Tooltip placement="leftTop" title='主题'>
                <BulbOutlined />
              </Tooltip>
            </CSSTransition>
            <Switch checkedChildren="dark" unCheckedChildren="light" checked={theme === 'dark'} onChange={this.changeTheme}/>
          </div>
        </Sider>
    );
  }
Example #22
Source File: config-provider.jsx    From virtuoso-design-system with MIT License 5 votes vote down vote up
render() {
    const { customize } = this.state;
    return (
      <div>
        <Switch
          unCheckedChildren="default"
          checkedChildren="customize"
          checked={customize}
          onChange={val => {
            this.setState({ customize: val });
          }}
        />

        <Divider />

        <ConfigProvider renderEmpty={customize && customizeRenderEmpty}>
          <div className="config-provider">
            <h4>Select</h4>
            <Select style={style} />

            <h4>TreeSelect</h4>
            <TreeSelect style={style} treeData={[]} />

            <h4>Cascader</h4>
            <Cascader style={style} options={[]} showSearch />

            <h4>Transfer</h4>
            <Transfer />

            <h4>Table</h4>
            <Table
              style={{ marginTop: 8 }}
              columns={[
                {
                  title: 'Name',
                  dataIndex: 'name',
                  key: 'name',
                },
                {
                  title: 'Age',
                  dataIndex: 'age',
                  key: 'age',
                },
              ]}
            />

            <h4>List</h4>
            <List />
          </div>
        </ConfigProvider>
      </div>
    );
  }
Example #23
Source File: PropertiesDropdown.jsx    From notence with MIT License 5 votes vote down vote up
function PropertiesDropdown({
  showProperties,
  properties,
  onPropertyCreate,
  onPropertyDelete,
  onPropertyToggle,
}) {
  const [dropdownVisible, setDropdownVisible] = useState(false);
  const [modalVisible, setModalVisible] = useState(false);

  const inShowProperties = (propertyId) => showProperties.indexOf(propertyId) > -1;

  const openModal = () => setModalVisible(true);
  const closeModal = () => setModalVisible(false);

  const handlePropertyFormFinish = (property) => {
    onPropertyCreate(property);
    closeModal();
  };

  const createPropertyModal = (
    <Modal title="Create property" visible={modalVisible} onCancel={closeModal} footer={null}>
      <PropertyForm onFinish={handlePropertyFormFinish} />
    </Modal>
  );

  const propertyList = properties.map((property) => (
    <PropertyItem key={property.id}>
      <span className="name">{property.name}</span>
      <Switch
        size="small"
        onChange={() => onPropertyToggle(property.id)}
        checked={inShowProperties(property.id)}
      />
      <DeleteBtn onClick={() => onPropertyDelete(property.id)} />
    </PropertyItem>
  ));

  const menu = (
    <Menu>
      {propertyList}

      <Menu.Divider />
      <Menu.Item>
        <Button onClick={openModal} size="small" type="default" icon={<PlusOutlined />}>
          Add a property
        </Button>

        {createPropertyModal}
      </Menu.Item>
    </Menu>
  );

  return (
    <Dropdown
      visible={dropdownVisible}
      onVisibleChange={setDropdownVisible}
      overlay={menu}
      trigger={["click"]}
    >
      <Button size="small" type="link">
        Properties
      </Button>
    </Dropdown>
  );
}
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: index.js    From QiskitFlow with Apache License 2.0 4 votes vote down vote up
export function Run({ run, match, getRun, setPublic }) {
  useInjectReducer({ key: 'run', reducer });
  useInjectSaga({ key: 'run', saga });

  const runId = match.params.id;
  const didMount = useRef(true);
  useEffect(() => {
    if (didMount.current) getRun(runId);
    didMount.current = false;
  });

  const counts = run.counts.map((cnt, idx) => {
    const cats = cnt.entries.map(m => m.key);
    const values = cnt.entries.map(m => m.value);
    const options = {
      chart: { type: 'column' },
      title: { text: `Count [${cnt.name}]` },
      xAxis: { categories: cats, title: { text: null } },
      yAxis: {
        min: 0,
        title: { text: 'Value', align: 'middle' },
        labels: { overflow: 'justify' },
      },
      tooltip: { valueSuffix: '' },
      plotOptions: { bar: { dataLabels: { enabled: true } } },
      credits: { enabled: false },
      series: [
        {
          name: cnt.name,
          data: values,
          color: '#6929C2',
        },
      ],
    };

    return (
      // eslint-disable-next-line react/no-array-index-key
      <Card key={`counts_chart_${idx}`} style={{ margin: '20px 0' }}>
        <HighchartsReact highcharts={Highcharts} options={options} />
        <Divider />
      </Card>
    );
  });

  const parameters = run.parameters.map((param, i) => (
    // eslint-disable-next-line react/no-array-index-key
    <div key={`parameter_${param.name}_${param.value}_${i}`}>
      <b>{param.name}</b>: {param.value}
      <br />
    </div>
  ));

  const description = run.description ? (
    <p>{run.description}</p>
  ) : (
    <p>No description provided...</p>
  );

  const metrics = run.metrics.map((metric, i) => ({ ...metric, key: i }));

  return (
    <div>
      <Helmet>
        <title>Run</title>
        <meta name="description" content="Description of Run" />
      </Helmet>
      <div>
        <h1>{`Run [${runId}]`}</h1>
        <Divider />
        <Row gutter={[16, 16]}>
          <Col span={12}>
            <Card
              title="Information & parameters"
              extra={
                <Switch
                  checkedChildren="public"
                  unCheckedChildren="private"
                  checked={run.is_public}
                  onClick={setPublic}
                />
              }
            >
              <b>QiskitFlow version</b>: {run.version}
              <br />
              <br />
              {parameters}
              <br />
              <b>Execute experiment</b>: <Text code>...</Text>
              <br />
              <br />
              <b>BibTeX</b>:
              <Paragraph copyable>
                {`...`}
              </Paragraph>
            </Card>
            <br />
            <Table
              key="metrics_table"
              dataSource={metrics}
              columns={columns}
              pagination={false}
            />
            <br />
            <Card title="State vectors">
              <List
                size="small"
                dataSource={run.state_vectors}
                renderItem={sv => {
                  const vector = sv.vector
                    .map(c => `${c.real}+j${c.img} `)
                    .concat();

                  return (
                    <List.Item>
                      <b>{sv.name}</b>: {vector}
                    </List.Item>
                  );
                }}
              />
            </Card>
          </Col>
          <Col span={12}>
            <Card
              title="Experiment description"
              style={{ margin: '0 0 20px 0' }}
            >
              {description}
            </Card>
            <Card title="Files">
              <Tree
                showLine
                switcherIcon={<DownOutlined />}
                defaultExpandedKeys={['0-0-0']}
                treeData={[
                  {
                    title: 'run.json',
                    key: '0-0',
                  },
                ]}
              />
            </Card>
            {counts}
          </Col>
        </Row>
      </div>
    </div>
  );
}
Example #27
Source File: index.jsx    From react-antd-admin-template with MIT License 4 votes vote down vote up
RightPanel = (props) => {
  const {
    settingPanelVisible,
    toggleSettingPanel,
    changeSetting,
    sidebarLogo: defaultSidebarLogo,
    fixedHeader: defaultFixedHeader,
    tagsView: defaultTagsView,
  } = props;

  const [sidebarLogo, setSidebarLogo] = useState(defaultSidebarLogo);
  const [fixedHeader, setFixedHeader] = useState(defaultFixedHeader);
  const [tagsView, setTagsView] = useState(defaultTagsView);

  const sidebarLogoChange = (checked) => {
    setSidebarLogo(checked);
    changeSetting({ key: "sidebarLogo", value: checked });
  };

  const fixedHeaderChange = (checked) => {
    setFixedHeader(checked);
    changeSetting({ key: "fixedHeader", value: checked });
  };

  const tagsViewChange = (checked) => {
    setTagsView(checked);
    changeSetting({ key: "tagsView", value: checked });
  };

  const handleCopy = (e) => {
    let config = `
    export default {
      showSettings: true,
      sidebarLogo: ${sidebarLogo},
      fixedHeader: ${fixedHeader},
      tagsView: ${tagsView},
    }
    `;
    clip(config, e);
  };

  return (
    <div className="rightSettings">
      <Drawer
        title="系统设置"
        placement="right"
        width={350}
        onClose={toggleSettingPanel}
        visible={settingPanelVisible}
      >
        <Row>
          <Col span={12}>
            <span>侧边栏 Logo</span>
          </Col>
          <Col span={12}>
            <Switch
              checkedChildren="开"
              unCheckedChildren="关"
              defaultChecked={sidebarLogo}
              onChange={sidebarLogoChange}
            />
          </Col>
        </Row>
        <Divider dashed />
        <Row>
          <Col span={12}>
            <span>固定 Header</span>
          </Col>
          <Col span={12}>
            <Switch
              checkedChildren="开"
              unCheckedChildren="关"
              defaultChecked={fixedHeader}
              onChange={fixedHeaderChange}
            />
          </Col>
        </Row>
        <Divider dashed />
        <Row>
          <Col span={12}>
            <span>开启 Tags-View</span>
          </Col>
          <Col span={12}>
            <Switch
              checkedChildren="开"
              unCheckedChildren="关"
              defaultChecked={tagsView}
              onChange={tagsViewChange}
            />
          </Col>
        </Row>
        <Divider dashed />
        <Row>
          <Col span={24}>
            <Alert
              message="开发者请注意:"
              description="配置栏只在开发环境用于预览,生产环境不会展现,请拷贝后手动修改/src/defaultSettings.js配置文件"
              type="warning"
              showIcon
              icon={<Icon type="notification" />}
              style={{ marginBottom: "16px" }}
            />
            <Button style={{ width: "100%" }} icon="copy" onClick={handleCopy}>
              拷贝配置
            </Button>
          </Col>
        </Row>
      </Drawer>
    </div>
  );
}
Example #28
Source File: index.js    From topology-react with MIT License 4 votes vote down vote up
Page = ({ canvasData, form: { getFieldDecorator } }) => {
  const node = canvasData.node;


  const onHandleStyleSelectChange = (e) => {
    node.animateFrames = [];
    node.fillStyle = '';
    node.rotate = '';
    const state = Node.cloneState(node);
    switch (e) {
      case 'upDown':
        state.rect.y -= 10;
        state.rect.ey -= 10;
        node.animateFrames.push({
          duration: 100,
          linear: true,
          state: Node.cloneState(state)
        });
        node.animateStart = Date.now();
        break;
      case 'leftRight':
        state.rect.x -= 10;
        state.rect.ex -= 10;
        node.animateFrames.push({
          duration: 100,
          linear: true,
          state: Node.cloneState(state)
        });

        state.rect.x += 20;
        state.rect.ex += 20;
        node.animateFrames.push({
          duration: 100,
          linear: true,
          state: Node.cloneState(state)
        });
        node.animateStart = Date.now();
        break;
      case 'heart':
        state.rect.x -= 5;
        state.rect.ex += 5;
        state.rect.y -= 5;
        state.rect.ey += 5;
        state.rect.width += 5;
        state.rect.height += 10;
        node.animateFrames.push({
          duration: 100,
          linear: true,
          state: Node.cloneState(state)
        });
        node.animateStart = Date.now();
        break;
      case 'success':
        state.strokeStyle = '#237804';
        node.animateFrames.push({
          duration: 100,
          linear: true,
          state: Node.cloneState(state)
        });
        state.strokeStyle = '#237804';
        state.fillStyle = '#389e0d22';
        node.animateFrames.push({
          duration: 300,
          linear: true,
          state: Node.cloneState(state)
        });
        node.animateStart = Date.now();
        break;
      case 'warning':
        state.strokeStyle = '#fa8c16';
        state.dash = 2;
        node.animateFrames.push({
          duration: 100,
          linear: true,
          state: Node.cloneState(state)
        });
        state.fillStyle = '#fa8c16';
        state.dash = 0;
        node.animateFrames.push({
          duration: 300,
          linear: true,
          state: Node.cloneState(state)
        });
        node.animateStart = Date.now();
        break;
        case 'show':
          state.rotate = -10;
          node.animateFrames.push({
            duration: 100,
            linear: true,
            state: Node.cloneState(state)
          });
          state.rotate = 10;
          node.animateFrames.push({
            duration: 300,
            linear: true,
            state: Node.cloneState(state)
          });
          node.animateStart = Date.now();
          break;
      default:
        break;
    }

    node.animateDuration = 0;
    for (const item of node.animateFrames) {
      node.animateDuration += item.duration;
    }
  };

  const onHandleSwitchChange = (e) => {
    if (e) {
      node.animateStart = Date.now();
      canvas.animate();
    } else {
      node.animateStart = 0;
    }
  };

  const renderAnimateForm = () => {
    return (
      <Form>
        <Col span={24}>
          <Form.Item label="特效">
            {getFieldDecorator('style', {
              initialValue: void 0
            })(
              <Select onSelect={e => onHandleStyleSelectChange(e)}>
                <Select.Option value="upDown" key="topDown">
                  上下跳动
                </Select.Option>
                <Select.Option value="leftRight" key="leftRight">
                  左右跳动
                </Select.Option>
                <Select.Option value="heart" key="heart">
                  心跳
                </Select.Option>
                <Select.Option value="success" key="success">
                  成功
                </Select.Option>
                <Select.Option value="warning" key="warning">
                  警告
                </Select.Option>
                <Select.Option value="show" key="show">
                  炫耀
                </Select.Option>
              </Select>
            )}
          </Form.Item>
        </Col>
        <Col span={24}>
          <Form.Item label="播放">
            {getFieldDecorator('start', {
              initialValue: void 0
            })(
              <Switch
                checkedChildren="开"
                unCheckedChildren="关"
                onChange={(e) => onHandleSwitchChange(e)}
              />
            )}
          </Form.Item>
        </Col>
      </Form>
    );
  };

  return (
    <div>
      <Collapse defaultActiveKey={['1']}>
        <Panel header="动画" key="1">
          {renderAnimateForm()}
        </Panel>
      </Collapse>
    </div>
  );
}
Example #29
Source File: ExampleUI.jsx    From Tai-Shang-NFT-Wallet with MIT License 4 votes vote down vote up
export default function ExampleUI({
  purpose,
  setPurposeEvents,
  address,
  mainnetProvider,
  localProvider,
  yourLocalBalance,
  price,
  tx,
  readContracts,
  writeContracts,
}) {
  const [newPurpose, setNewPurpose] = useState("loading...");

  return (
    <div>
      {/*
        ⚙️ Here is an example UI that displays and sets the purpose in your smart contract:
      */}
      <div style={{ border: "1px solid #cccccc", padding: 16, width: 400, margin: "auto", marginTop: 64 }}>
        <h2>Example UI:</h2>
        <h4>purpose: {purpose}</h4>
        <Divider />
        <div style={{ margin: 8 }}>
          <Input
            onChange={e => {
              setNewPurpose(e.target.value);
            }}
          />
          <Button
            style={{ marginTop: 8 }}
            onClick={async () => {
              /* look how you call setPurpose on your contract: */
              /* notice how you pass a call back for tx updates too */
              const result = tx(writeContracts.YourContract.setPurpose(newPurpose), update => {
                console.log("? Transaction Update:", update);
                if (update && (update.status === "confirmed" || update.status === 1)) {
                  console.log(" ? Transaction " + update.hash + " finished!");
                  console.log(
                    " ⛽️ " +
                      update.gasUsed +
                      "/" +
                      (update.gasLimit || update.gas) +
                      " @ " +
                      parseFloat(update.gasPrice) / 1000000000 +
                      " gwei",
                  );
                }
              });
              console.log("awaiting metamask/web3 confirm result...", result);
              console.log(await result);
            }}
          >
            Set Purpose!
          </Button>
        </div>
        <Divider />
        Your Address:
        <Address address={address} ensProvider={mainnetProvider} fontSize={16} />
        <Divider />
        ENS Address Example:
        <Address
          address="0x34aA3F359A9D614239015126635CE7732c18fDF3" /* this will show as austingriffith.eth */
          ensProvider={mainnetProvider}
          fontSize={16}
        />
        <Divider />
        {/* use utils.formatEther to display a BigNumber: */}
        <h2>Your Balance: {yourLocalBalance ? utils.formatEther(yourLocalBalance) : "..."}</h2>
        <div>OR</div>
        <Balance address={address} provider={localProvider} price={price} />
        <Divider />
        <div>? Example Whale Balance:</div>
        <Balance balance={utils.parseEther("1000")} provider={localProvider} price={price} />
        <Divider />
        {/* use utils.formatEther to display a BigNumber: */}
        <h2>Your Balance: {yourLocalBalance ? utils.formatEther(yourLocalBalance) : "..."}</h2>
        <Divider />
        Your Contract Address:
        <Address
          address={readContracts && readContracts.YourContract ? readContracts.YourContract.address : null}
          ensProvider={mainnetProvider}
          fontSize={16}
        />
        <Divider />
        <div style={{ margin: 8 }}>
          <Button
            onClick={() => {
              /* look how you call setPurpose on your contract: */
              tx(writeContracts.YourContract.setPurpose("? Cheers"));
            }}
          >
            Set Purpose to &quot;? Cheers&quot;
          </Button>
        </div>
        <div style={{ margin: 8 }}>
          <Button
            onClick={() => {
              /*
              you can also just craft a transaction and send it to the tx() transactor
              here we are sending value straight to the contract's address:
            */
              tx({
                to: writeContracts.YourContract.address,
                value: utils.parseEther("0.001"),
              });
              /* this should throw an error about "no fallback nor receive function" until you add it */
            }}
          >
            Send Value
          </Button>
        </div>
        <div style={{ margin: 8 }}>
          <Button
            onClick={() => {
              /* look how we call setPurpose AND send some value along */
              tx(
                writeContracts.YourContract.setPurpose("? Paying for this one!", {
                  value: utils.parseEther("0.001"),
                }),
              );
              /* this will fail until you make the setPurpose function payable */
            }}
          >
            Set Purpose With Value
          </Button>
        </div>
        <div style={{ margin: 8 }}>
          <Button
            onClick={() => {
              /* you can also just craft a transaction and send it to the tx() transactor */
              tx({
                to: writeContracts.YourContract.address,
                value: utils.parseEther("0.001"),
                data: writeContracts.YourContract.interface.encodeFunctionData("setPurpose(string)", [
                  "? Whoa so 1337!",
                ]),
              });
              /* this should throw an error about "no fallback nor receive function" until you add it */
            }}
          >
            Another Example
          </Button>
        </div>
      </div>

      {/*
        ? Maybe display a list of events?
          (uncomment the event and emit line in YourContract.sol! )
      */}
      <div style={{ width: 600, margin: "auto", marginTop: 32, paddingBottom: 32 }}>
        <h2>Events:</h2>
        <List
          bordered
          dataSource={setPurposeEvents}
          renderItem={item => {
            return (
              <List.Item key={item.blockNumber + "_" + item.sender + "_" + item.purpose}>
                <Address address={item[0]} ensProvider={mainnetProvider} fontSize={16} />
                {item[1]}
              </List.Item>
            );
          }}
        />
      </div>

      <div style={{ width: 600, margin: "auto", marginTop: 32, paddingBottom: 256 }}>
        <Card>
          Check out all the{" "}
          <a
            href="https://github.com/austintgriffith/scaffold-eth/tree/master/packages/react-app/src/components"
            target="_blank"
            rel="noopener noreferrer"
          >
            ? components
          </a>
        </Card>

        <Card style={{ marginTop: 32 }}>
          <div>
            There are tons of generic components included from{" "}
            <a href="https://ant.design/components/overview/" target="_blank" rel="noopener noreferrer">
              ? ant.design
            </a>{" "}
            too!
          </div>

          <div style={{ marginTop: 8 }}>
            <Button type="primary">Buttons</Button>
          </div>

          <div style={{ marginTop: 8 }}>
            <SyncOutlined spin /> Icons
          </div>

          <div style={{ marginTop: 8 }}>
            Date Pickers?
            <div style={{ marginTop: 2 }}>
              <DatePicker onChange={() => {}} />
            </div>
          </div>

          <div style={{ marginTop: 32 }}>
            <Slider range defaultValue={[20, 50]} onChange={() => {}} />
          </div>

          <div style={{ marginTop: 32 }}>
            <Switch defaultChecked onChange={() => {}} />
          </div>

          <div style={{ marginTop: 32 }}>
            <Progress percent={50} status="active" />
          </div>

          <div style={{ marginTop: 32 }}>
            <Spin />
          </div>
        </Card>
      </div>
    </div>
  );
}