@ant-design/icons#DownOutlined JavaScript Examples

The following examples show how to use @ant-design/icons#DownOutlined. 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: overlay-visible.jsx    From virtuoso-design-system with MIT License 6 votes vote down vote up
render() {
    const menu = (
      <Menu onClick={this.handleMenuClick}>
        <Menu.Item key="1">Clicking me will not close the menu.</Menu.Item>
        <Menu.Item key="2">Clicking me will not close the menu also.</Menu.Item>
        <Menu.Item key="3">Clicking me will close the menu.</Menu.Item>
      </Menu>
    );
    return (
      <Dropdown
        overlay={menu}
        onVisibleChange={this.handleVisibleChange}
        visible={this.state.visible}
      >
        <a className="ant-dropdown-link" onClick={e => e.preventDefault()}>
          Hover me <DownOutlined />
        </a>
      </Dropdown>
    );
  }
Example #2
Source File: index.js    From the-eye-knows-the-garbage with MIT License 6 votes vote down vote up
getDefaultSearch = function getDefaultSearch(search, intl, isForm) {
  var config = {
    collapseRender: function collapseRender(collapsed) {
      if (collapsed) {
        return React.createElement(React.Fragment, null, intl.getMessage('tableForm.collapsed', '展开'), React.createElement(DownOutlined, {
          style: {
            marginLeft: '0.5em',
            transition: '0.3s all',
            transform: "rotate(".concat(collapsed ? 0 : 0.5, "turn)")
          }
        }));
      }

      return React.createElement(React.Fragment, null, intl.getMessage('tableForm.expand', '收起'), React.createElement(DownOutlined, {
        style: {
          marginLeft: '0.5em',
          transition: '0.3s all',
          transform: "rotate(".concat(collapsed ? 0 : 0.5, "turn)")
        }
      }));
    },
    searchText: intl.getMessage('tableForm.search', defaultSearch.searchText || '查询'),
    resetText: intl.getMessage('tableForm.reset', defaultSearch.resetText || '重置'),
    submitText: intl.getMessage('tableForm.submit', defaultSearch.submitText || '提交'),
    span: isForm ? defaultFormColConfig : defaultColConfig
  };

  if (search === undefined || search === true) {
    return config;
  }

  return _objectSpread(_objectSpread({}, config), search);
}
Example #3
Source File: basic.jsx    From virtuoso-design-system with MIT License 6 votes vote down vote up
menu = (
  <Menu>
    <Menu.Item>
      <a target="_blank" rel="noopener noreferrer" href="https://www.antgroup.com">
        1st menu item
      </a>
    </Menu.Item>
    <Menu.Item icon={<DownOutlined />} disabled>
      <a target="_blank" rel="noopener noreferrer" href="https://www.aliyun.com">
        2nd menu item (disabled)
      </a>
    </Menu.Item>
    <Menu.Item disabled>
      <a target="_blank" rel="noopener noreferrer" href="https://www.luohanacademy.com">
        3rd menu item (disabled)
      </a>
    </Menu.Item>
    <Menu.Item danger>a danger item</Menu.Item>
  </Menu>
)
Example #4
Source File: HelpButton.jsx    From ui with MIT License 6 votes vote down vote up
HelpButton = () => {
  const [visible, setVisible] = useState(false);

  const overlay = () => (
    <Card size='small' style={{ padding: '1em', width: '265px' }}>
      For tutorial videos, ‘how to’ guides and FAQs on how to use Cellenics, visit
      {' '}
      <a href='https://www.biomage.net/get-started' target='_blank' rel='noreferrer'>our website</a>
      .
      <br />
      <br />
      If you need additional help with your analysis, email:
      {' '}
      <a href='mailto:[email protected]'>[email protected]</a>
    </Card>
  );

  return (
    <Dropdown
      visible={visible}
      onVisibleChange={(v) => setVisible(v)}
      overlay={overlay}
      placement='bottomRight'
      trigger='click'
    >
      <Button
        type='dashed'
        icon={<QuestionCircleOutlined />}
      >
        Help & resources
        <DownOutlined />
      </Button>
    </Dropdown>
  );
}
Example #5
Source File: dropdown-button.jsx    From virtuoso-design-system with MIT License 6 votes vote down vote up
storiesOf('antd/dropdown', module).add('dropdown-button', () => 
  <Space wrap>
    <Dropdown.Button onClick={handleButtonClick} overlay={menu}>
      Dropdown
    </Dropdown.Button>
    <Dropdown.Button overlay={menu} placement="bottomCenter" icon={<UserOutlined />}>
      Dropdown
    </Dropdown.Button>
    <Dropdown.Button onClick={handleButtonClick} overlay={menu} disabled>
      Dropdown
    </Dropdown.Button>
    <Dropdown.Button
      overlay={menu}
      buttonsRender={([leftButton, rightButton]) => [
        <Tooltip title="tooltip" key="leftButton">
          {leftButton}
        </Tooltip>,
        React.cloneElement(rightButton, { loading: true }),
      ]}
    >
      With Tooltip
    </Dropdown.Button>
    <Dropdown overlay={menu}>
      <Button>
        Button <DownOutlined />
      </Button>
    </Dropdown>
  </Space>,
  { docs: { page: () => (<><h1 id="enus">en-US</h1>
<p>A button is on the left, and a related functional menu is on the right. You can set the icon property to modify the icon of right.</p></>) } });
Example #6
Source File: UserMenu.js    From react-drag with MIT License 6 votes vote down vote up
UserMenuDropdown = props => {
  const onMenuClick = event => {
    const { key } = event;
    const { dispatch } = props;

    if (key === 'logout') {
      if (dispatch) {
        dispatch({
          type: 'user/logout',
        });
      }

      return;
    }
  };

  const UserMenu = () => {
    return (
      <Menu onClick={onMenuClick}>
        <Menu.Item key="logout">退出登陆</Menu.Item>
      </Menu>
    );
  };

  return (
    <Dropdown overlay={UserMenu} trigger={['click']}>
      <div>
        <UserOutlined style={{ fontSize: '22px' }} />
        用户中心 <DownOutlined />
      </div>
    </Dropdown>
  );
}
Example #7
Source File: customized-icon.jsx    From virtuoso-design-system with MIT License 6 votes vote down vote up
storiesOf('antd/tree', module).add('customized-icon', () => 
  <Tree
    showIcon
    defaultExpandAll
    defaultSelectedKeys={['0-0-0']}
    switcherIcon={<DownOutlined />}
    treeData={treeData}
  />,
  { docs: { page: () => (<><h1 id="enus">en-US</h1>
<p>You can customize icons for different nodes.</p></>) } });
Example #8
Source File: Index.js    From credit with Apache License 2.0 5 votes vote down vote up
render() {
        const handleMenu = (p)=>{
            if(p.key === 'logout') {
                clearToken();
                this.props.history.push('/login');
            } else {
                message.info(p.key);
            }
        }
        const menu = (
            <Menu onClick={handleMenu}>
                <Menu.Item key="msg">
                    消息
                </Menu.Item>
                <Menu.Item key="setting">
                    设置
                </Menu.Item>
                <Menu.Item key="logout">
                    <LogoutOutlined />退出
                </Menu.Item>
            </Menu>
        );
        return (
            <Layout>
                <Header className="header">
                    <div className="logo">区块链信用模型共享及认证系统</div>
                    <Dropdown overlay={menu}>
                        <a className="ant-dropdown-link" href="/#" onClick={e => { e.preventDefault() }}>
                            <Avatar style={{ backgroundColor: '#f56a00' }}>U</Avatar><DownOutlined />
                        </a>
                    </Dropdown>
                </Header>
                <Layout>
                    <Sider width={200} className="site-layout-background">
                        <Menu
                            mode="inline"
                            defaultSelectedKeys={['1']}
                            defaultOpenKeys={['sub1']}
                            style={{ height: '100%', borderRight: 0 }}
                        >
                            {routes.map(route => {
                                return <Menu.Item key={route.path} onClick={p => this.props.history.push(p.key)}>
                                    <Icon component={route.icon}></Icon>
                                    {route.title}
                                </Menu.Item>
                            })}
                        </Menu>
                    </Sider>
                    <Layout style={{ padding: '16px' }}>
                        <Content
                            className="site-layout-background"
                            style={{
                                padding: 24,
                                margin: 0,
                                minHeight: 280,
                            }}
                        >
                            {this.props.children}
                        </Content>
                    </Layout>
                </Layout>
            </Layout>
        )
    }
Example #9
Source File: tag.js    From ant-simple-pro with MIT License 5 votes vote down vote up
render() {
    const { location } = this.props;
    const { tagsList, isHiddleTag } = this.state;
    return (
      <>
        <CSSTransition in={!isHiddleTag} classNames="fade" timeout={100} unmountOnExit>
          <div className={style['tag-wrapper']}>
            <div className={style.slider}>
              {
                tagsList.length ? (<ul className={`${style["tags"]}`}>
                  {
                    tagsList.map((item, index) => {
                      return (
                        <li className={item.path === location.pathname ? `${style['tags-li']} ${style['selected']}` : `${style['tags-li']}`} key={index}>
                          <NavLink to={item.path} className={style['tags-li-title']} title={item.title}>
                            {item.title}
                          </NavLink>
                          {
                            this.state.tagsList.length > 1 && <CloseOutlined className={style['del']} onClick={(e) => this.closeTags(index, item.path, e)} />
                          }
                        </li>
                      )
                    })
                  }
                </ul>) : <p className={style["tags"]}>未匹配到相关的路径~</p>
              }
            </div>
            <div className={style.option}>
              <Dropdown overlay={this.menu} arrow trigger={['click']}>
                <a onClick={e => e.preventDefault()}>
                  <span className={style.title}>标签设置</span>
                  <DownOutlined />
                </a>
              </Dropdown>
            </div>
          </div>
        </CSSTransition>
      </>
    );
  }
Example #10
Source File: ActionMenu.js    From react-admin-portal with MIT License 5 votes vote down vote up
function useActionMenu({ selectedRow, updateEntityPath }) {
  const history = useHistory();

  const handleMenuClick = action => {
    if (action.key === 'edit') {
      const updatePath = '/' + updateEntityPath + '/' + selectedRow.id;
      history.push(updatePath);
    }
  };

  const handleSingleDelete = () => {
    console.log('handleSingleDelete, selected:', selectedRow);
  };

  const actionMenu = (
    <Menu onClick={handleMenuClick}>
      <Menu.Item key="edit">
        <EditOutlined />
        Update
      </Menu.Item>
      <Menu.Item key="delete">
        <Popconfirm
          title="Sure to delete?"
          placement="left"
          icon={<QuestionCircleOutlined style={{ color: 'red' }} />}
          onConfirm={handleSingleDelete}
        >
          <DeleteOutlined type="delete" />
          Delete
        </Popconfirm>
      </Menu.Item>
    </Menu>
  );

  const actionColumnView = (
    <span>
      <Dropdown overlay={actionMenu} trigger={['click']}>
        <a className="ant-dropdown-link" href="#">
          Actions <DownOutlined />
        </a>
      </Dropdown>
    </span>
  );

  return [actionColumnView];
}
Example #11
Source File: replayRow.js    From virtuoso-design-system with MIT License 5 votes vote down vote up
ReplayRow = ({ authorEmail, recipients, typeOfReplay }) => {
  const [replyAll, setReplyAll] = useState(false);

  const handleMenuClick = (e) => {
    if (e.key === 'replay_all') {
      setReplyAll(true);
    } else {
      setReplyAll(false);
    }
    typeOfReplay(e.key);
  };

  const menu = (
    <Menu onClick={handleMenuClick} mode="inline">
      <Menu.Item key="secure_replay">Secure Reply</Menu.Item>
      {recipients?.length > 1 && <Menu.Item key="replay_all">Reply All</Menu.Item>}
    </Menu>
  );

  const menuRecipients = (
    <Menu mode="inline" style={{ pointerEvents: 'none' }}>
      {recipients?.map((recipient) => (
        <Menu.Item key={recipient}>{recipient}</Menu.Item>
      ))}
    </Menu>
  );

  return (
    <Row justify="space-between" className={styles.row}>
      <Col>
        <Dropdown overlay={menu} trigger="click">
          <Button type="link">
            <span className={styles.iconReply}>{replyAll ? <ReplyAll /> : <Reply />}</span>
            <DownOutlined />
          </Button>
        </Dropdown>
        {authorEmail}
      </Col>
      <Col>
        {replyAll && (
          <Dropdown overlay={menuRecipients}>
            <Button type="link">+{recipients?.length} more</Button>
          </Dropdown>
        )}
      </Col>
    </Row>
  );
}
Example #12
Source File: MarketStreamPanel.js    From websocket-demo with MIT License 5 votes vote down vote up
function MarketStreamPanel({ actions, selectedStream }) {
  const [type, setType] = useState('');
  const onSelectChange = value => {
    setType(value);
    actions.removeAllSelectedStream();
  };
  const onClickSubscribe = env => {
    if (selectedStream.codes.length === 0) {
      return notification['error']({
        message: i18n.t('label.error'),
        description: i18n.t('message.marketStreamInput')
      });
    }
    actions.subscribeMarketStream(env);
  };
  return (
    <>
      <Title level={5}>{i18n.t('label.marketStream')}</Title>
      <Form className="market-stream">
        <Form.Item label="Source">
          <Select placeholder={i18n.t('message.selectStream')} onChange={onSelectChange}>
            {allMarketStreams.map(streamType => (
              <Option key={streamType.type} value={streamType.type}>
                {i18n.t(`label.${streamType.type}`)}
              </Option>
            ))}
          </Select>
        </Form.Item>
        <Form.Item label="Streams">
          <Dropdown overlay={type && <StreamMenu actions={actions} type={type} />}>
            <span>
              {i18n.t('message.selectStream')} <DownOutlined />
            </span>
          </Dropdown>
        </Form.Item>
        {selectedStream.codes.length > 0 && (
          <Form.Item>
            <TagDisplay actions={actions} tags={selectedStream.codes} />
          </Form.Item>
        )}
      </Form>
      <Button type="default" style={{ margin: '5px' }} onClick={() => onClickSubscribe(TESTNET)}>
        {i18n.t('label.testSubscribe')}
      </Button>
      <Button type="primary" style={{ margin: '5px' }} onClick={() => onClickSubscribe(PROD)}>
        {i18n.t('label.prodSubscribe')}
      </Button>
    </>
  );
}
Example #13
Source File: event.jsx    From virtuoso-design-system with MIT License 5 votes vote down vote up
storiesOf('antd/dropdown', module).add('event', () => 
  <Dropdown overlay={menu}>
    <a className="ant-dropdown-link" onClick={e => e.preventDefault()}>
      Hover me, Click menu item <DownOutlined />
    </a>
  </Dropdown>,
  { docs: { page: () => (<><h1 id="enus">en-US</h1>
<p>An event will be triggered when you click menu items, in which you can make different operations according to item's key.</p></>) } });
Example #14
Source File: index.js    From gobench with Apache License 2.0 5 votes vote down vote up
columns = [
  {
    title: 'Name',
    dataIndex: 'name',
  },
  {
    title: 'Age',
    dataIndex: 'age',
    sorter: (a, b) => a.age - b.age,
  },
  {
    title: 'Address',
    dataIndex: 'address',
    filters: [
      {
        text: 'London',
        value: 'London',
      },
      {
        text: 'New York',
        value: 'New York',
      },
    ],
    onFilter: (value, record) => record.address.indexOf(value) === 0,
  },
  {
    title: 'Action',
    key: 'action',
    sorter: true,
    filters: [],
    onFilter: () => {},
    render: () => (
      <span>
        <a style={{ marginRight: 16 }}>Delete</a>
        <a className="ant-dropdown-link">
          More actions <DownOutlined />
        </a>
      </span>
    ),
  },
]
Example #15
Source File: sub-menu.jsx    From virtuoso-design-system with MIT License 5 votes vote down vote up
storiesOf('antd/dropdown', module).add('sub-menu', () => 
  <Dropdown overlay={menu}>
    <a className="ant-dropdown-link" onClick={e => e.preventDefault()}>
      Cascading menu <DownOutlined />
    </a>
  </Dropdown>,
  { docs: { page: () => (<><h1 id="enus">en-US</h1>
<p>The menu has multiple levels.</p></>) } });
Example #16
Source File: index.jsx    From prometheusPro with MIT License 5 votes vote down vote up
render() {
    const { value, expand } = this.state;
    const { children, hideCheckAll, className, style, expandable, actionsText = {} } = this.props;
    const checkedAll = this.getAllTags().length === value.length;
    const { expandText = '展开', collapseText = '收起', selectAllText = '全部' } = actionsText;
    const cls = classNames(styles.tagSelect, className, {
      [styles.hasExpandTag]: expandable,
      [styles.expanded]: expand,
    });
    return (
      <div className={cls} style={style}>
        {hideCheckAll ? null : (
          <CheckableTag checked={checkedAll} key="tag-select-__all__" onChange={this.onSelectAll}>
            {selectAllText}
          </CheckableTag>
        )}
        {value &&
          children &&
          React.Children.map(children, child => {
            if (this.isTagSelectOption(child)) {
              return React.cloneElement(child, {
                key: `tag-select-${child.props.value}`,
                value: child.props.value,
                checked: value.indexOf(child.props.value) > -1,
                onChange: this.handleTagChange,
              });
            }

            return child;
          })}
        {expandable && (
          <a className={styles.trigger} onClick={this.handleExpand}>
            {expand ? (
              <>
                {collapseText} <UpOutlined />
              </>
            ) : (
              <>
                {expandText}
                <DownOutlined />
              </>
            )}
          </a>
        )}
      </div>
    );
  }
Example #17
Source File: dark.jsx    From virtuoso-design-system with MIT License 5 votes vote down vote up
expandedRowRender = () => {
  const columnsExpand = [
    { title: 'Date', dataIndex: 'date', key: 'date' },
    { title: 'Name', dataIndex: 'name', key: 'name' },
    {
      title: 'Status',
      key: 'state',
      render: () => (
        <span>
          <Badge status="success" />
          Finished
        </span>
      ),
    },
    { title: 'Upgrade Status', dataIndex: 'upgradeNum', key: 'upgradeNum' },
    {
      title: 'Action',
      dataIndex: 'operation',
      key: 'operation',
      render: () => (
        <span className="table-operation">
          <a>Pause</a>
          <a>Stop</a>
          <Dropdown>
            <a>
              More <DownOutlined />
            </a>
          </Dropdown>
        </span>
      ),
    },
  ];

  const dataExpand = [];
  for (let i = 0; i < 3; ++i) {
    data.push({
      key: i,
      date: '2014-12-24 23:12:00',
      name: 'This is production name',
      upgradeNum: 'Upgraded: 56',
    });
  }
  return <Table columns={columnsExpand} dataSource={dataExpand} pagination={false} />;
}
Example #18
Source File: index.jsx    From prometheusPro with MIT License 4 votes vote down vote up
TableList = () => {
  const [createModalVisible, handleModalVisible] = useState(false);
  const [updateModalVisible, handleUpdateModalVisible] = useState(false);
  const [stepFormValues, setStepFormValues] = useState({});
  const actionRef = useRef();
  const columns = [
    {
      title: '规则名称',
      dataIndex: 'name',
    },
    {
      title: '描述',
      dataIndex: 'desc',
    },
    {
      title: '服务调用次数',
      dataIndex: 'callNo',
      sorter: true,
      renderText: val => `${val} 万`,
    },
    {
      title: '状态',
      dataIndex: 'status',
      valueEnum: {
        0: {
          text: '关闭',
          status: 'Default',
        },
        1: {
          text: '运行中',
          status: 'Processing',
        },
        2: {
          text: '已上线',
          status: 'Success',
        },
        3: {
          text: '异常',
          status: 'Error',
        },
      },
    },
    {
      title: '上次调度时间',
      dataIndex: 'updatedAt',
      sorter: true,
      valueType: 'dateTime',
    },
    {
      title: '操作',
      dataIndex: 'option',
      valueType: 'option',
      render: (_, record) => (
        <>
          <a
            onClick={() => {
              handleUpdateModalVisible(true);
              setStepFormValues(record);
            }}
          >
            配置
          </a>
          <Divider type="vertical" />
          <a href="">订阅警报</a>
        </>
      ),
    },
  ];
  return (
    <PageHeaderWrapper>
      <ProTable
        headerTitle="查询表格"
        actionRef={actionRef}
        rowKey="key"
        toolBarRender={(action, { selectedRows }) => [
          <Button icon={<PlusOutlined />} type="primary" onClick={() => handleModalVisible(true)}>
            新建
          </Button>,
          selectedRows && selectedRows.length > 0 && (
            <Dropdown
              overlay={
                <Menu
                  onClick={async e => {
                    if (e.key === 'remove') {
                      await handleRemove(selectedRows);
                      action.reload();
                    }
                  }}
                  selectedKeys={[]}
                >
                  <Menu.Item key="remove">批量删除</Menu.Item>
                  <Menu.Item key="approval">批量审批</Menu.Item>
                </Menu>
              }
            >
              <Button>
                批量操作 <DownOutlined />
              </Button>
            </Dropdown>
          ),
        ]}
        tableAlertRender={(selectedRowKeys, selectedRows) => (
          <div>
            已选择{' '}
            <a
              style={{
                fontWeight: 600,
              }}
            >
              {selectedRowKeys.length}
            </a>{' '}
            项&nbsp;&nbsp;
            <span>
              服务调用次数总计 {selectedRows.reduce((pre, item) => pre + item.callNo, 0)} 万
            </span>
          </div>
        )}
        request={params => queryRule(params)}
        columns={columns}
        rowSelection={{}}
      />
      <CreateForm
        onSubmit={async value => {
          const success = await handleAdd(value);

          if (success) {
            handleModalVisible(false);

            if (actionRef.current) {
              actionRef.current.reload();
            }
          }
        }}
        onCancel={() => handleModalVisible(false)}
        modalVisible={createModalVisible}
      />
      {stepFormValues && Object.keys(stepFormValues).length ? (
        <UpdateForm
          onSubmit={async value => {
            const success = await handleUpdate(value);

            if (success) {
              handleModalVisible(false);
              setStepFormValues({});

              if (actionRef.current) {
                actionRef.current.reload();
              }
            }
          }}
          onCancel={() => {
            handleUpdateModalVisible(false);
            setStepFormValues({});
          }}
          updateModalVisible={updateModalVisible}
          values={stepFormValues}
        />
      ) : null}
    </PageHeaderWrapper>
  );
}
Example #19
Source File: index.jsx    From the-eye-knows-the-garbage with MIT License 4 votes vote down vote up
TableList = () => {
  const [createModalVisible, handleModalVisible] = useState(false);
  const [updateModalVisible, handleUpdateModalVisible] = useState(false);
 const [updatePassWordModalVisible, handleUpdatePassWordModalVisible] = useState(false);
const [updatePasswordForm] = Form.useForm();
  const [updateFormValues, setUpdateFormValues] = useState({});
  const actionRef = useRef();
  const addFormRef = useRef();
  const updateFormRef = useRef();

  const handleAdd = async fields => {
    const hide = message.loading('正在添加');

    try {
      await addUserProfile({ ...fields });
      hide();
      message.success('添加成功');
      return true;
    } catch (error) {
      return dealError(error, addFormRef, hide, "添加");
    }
  };

  const handleUpdate = async (value, current_id) => {
    const hide = message.loading('正在修改');

    try {
      await updateUserProfile(value, current_id);
      hide();
      message.success('修改成功');
      return true;
    } catch (error) {
      return dealError(error, updateFormRef, hide, "修改");
    }
  };

  const handleRemove = async selectedRows => {
    const hide = message.loading('正在删除');
    if (!selectedRows) return true;

    try {
      const ids = selectedRows.map(row => row.id).join(',');
      await removeUserProfile(ids);
      hide();
      message.success('删除成功');
      return true;
    } catch (error) {
      hide()
      return dealRemoveError(error, "删除");
    }
  };
 const handlePassWordUpdate = () => {
    if (updatePasswordForm.getFieldValue('password') !== updatePasswordForm.getFieldValue('re_password')) {
      updatePasswordForm.setFields([{
        name: 're_password',
        errors: ['两次密码不一致'],
      }]);
    } else {
      updatePasswordForm.validateFields().then(
        value => {
          updateUserPassword({
            ...value,
            username: updateFormValues["username"],
          }).then(
            message.success('密码修改成功'),
            handleUpdatePassWordModalVisible(false),
          );
        },
      );
      updatePasswordForm.submit;
    }
  };
  const dateFieldList = ["last_login","date_joined"]
  const base_columns = [{
                             title: 'id',
                             
        hideInForm: true,
        hideInSearch: true,
        
                             
                             dataIndex: 'id',
                             valueType: 'digit',
                             rules: [
                                     
                             ],
                             
                             
                        },
                      {
                             title: 'password',
                             
        hideInTable: true,
        hideInSearch: true,
        
                             
                             dataIndex: 'password',
                             
                             rules: [
                                     {
                      required: true,
                      message: 'password为必填项',
                     },
                             ],
                             
                             
                        },
                      {
                             title: 'last_login',
                             
                             
                             dataIndex: 'last_login',
                             valueType: 'dateTime',
                             rules: [
                                     
                             ],
                             
                             
                        },
                      {
                             title: 'is_superuser',
                             
                             initialValue: false,
                             dataIndex: 'is_superuser',
                             
                             rules: [
                                     
                             ],
                             
                                     render: (text, record) => {
                                  return BooleanDisplay(text);
                                },
                        renderFormItem: (item, {value, onChange}) => {
                          return BooleanFormItem(value, onChange);
                        },
        
                             
                        },
                      {
                             title: 'username',
                             
                             
                             dataIndex: 'username',
                             
                             rules: [
                                     {
                      required: true,
                      message: 'username为必填项',
                     },
                             ],
                             
                             
                        },
                      {
                             title: 'first_name',
                             
                             
                             dataIndex: 'first_name',
                             
                             rules: [
                                     
                             ],
                             
                             
                        },
                      {
                             title: 'last_name',
                             
                             
                             dataIndex: 'last_name',
                             
                             rules: [
                                     
                             ],
                             
                             
                        },
                      {
                             title: 'email',
                             
                             
                             dataIndex: 'email',
                             
                             rules: [
                                     
                             ],
                             
                             
                        },
                      {
                             title: 'is_staff',
                             
                             initialValue: false,
                             dataIndex: 'is_staff',
                             
                             rules: [
                                     
                             ],
                             
                                     render: (text, record) => {
                                  return BooleanDisplay(text);
                                },
                        renderFormItem: (item, {value, onChange}) => {
                          return BooleanFormItem(value, onChange);
                        },
        
                             
                        },
                      {
                             title: 'is_active',
                             
                             initialValue: true,
                             dataIndex: 'is_active',
                             
                             rules: [
                                     
                             ],
                             
                                     render: (text, record) => {
                                  return BooleanDisplay(text);
                                },
                        renderFormItem: (item, {value, onChange}) => {
                          return BooleanFormItem(value, onChange);
                        },
        
                             
                        },
                      {
                             title: 'date_joined',
                             
            hideInForm: true,
            
                             
                             dataIndex: 'date_joined',
                             valueType: 'dateTime',
                             rules: [
                                     
                             ],
                             
                             
                        },
                      {
                             title: '性别',
                             
                             initialValue: "female",
                             dataIndex: 'gender',
                             
                             rules: [
                                     
                             ],
                             
                             valueEnum:{"male":"男","female":"女"}
                        },
                      {
                             title: '头像',
                             
        hideInSearch: true,
        
                             
                             dataIndex: 'image',
                             valueType: 'avatar',
                             rules: [
                                     {
                      required: true,
                      message: '头像为必填项',
                     },
                             ],
                             
        renderFormItem: (_, {type, defaultRender, ...rest}, form) => {
                                      const imageUrl = form.getFieldValue('image');
                                      return <UploadAvatar img={imageUrl}/>
                                    },
            
                             
                        },
                      {
                             title: 'groups',
                             
                             
                             dataIndex: 'groups',
                             
                             rules: [
                                     
                             ],
                             
                
                renderFormItem: (item, {value, onChange, type, defaultRender}) => {
                      return dealManyToManyField(item, value,onChange,type, groupsManyToManyList)
                },
               render: (text, record) => {
                    return renderManyToMany(text)
            }, 
        
                             
                        },
                      {
                             title: 'user_permissions',
                             
                             
                             dataIndex: 'user_permissions',
                             
                             rules: [
                                     
                             ],
                             
                
                renderFormItem: (item, {value, onChange, type, defaultRender}) => {
                      return dealManyToManyField(item, value,onChange,type, user_permissionsManyToManyList)
                },
               render: (text, record) => {
                    return renderManyToMany(text)
            }, 
        
                             
                        },
                          {
                                              title: '操作',
                                              dataIndex: 'option',
                                              valueType: 'option',
                                                    fixed: 'right',
                          width: 100,
                                              render: (text, record) => (
                                                <>

                                                  <EditOutlined title="编辑" className="icon" onClick={async () => {
                                                   record.last_login = record.last_login === null ? record.last_login : moment(record.last_login);record.date_joined = record.date_joined === null ? record.date_joined : moment(record.date_joined);
                                                    handleUpdateModalVisible(true);
                                                    setUpdateFormValues(record);
                                                  }} />
                                                  <Divider type="vertical" />
                                                  <KeyOutlined onClick={() => {
                                            handleUpdatePassWordModalVisible(true);
                                              setUpdateFormValues(record);
          }} />
                                                  <Divider type="vertical" />
                                                  <Popconfirm
                                                    title="您确定要删除登入管理吗?"
                                                    placement="topRight"
                                                    onConfirm={() => {
                                                      handleRemove([record])
                                                      actionRef.current.reloadAndRest();
                                                    }}
                                                    okText="确定"
                                                    cancelText="取消"
                                                  >
                                                    <DeleteOutlined title="删除" className="icon" />
                                                  </Popconfirm>
                                                </>
                                              ),
                                            },];

  let cp = deepCopy(base_columns);

  const [formOrder, setFormOrder] = useState([]);

  useEffect(() => {
    queryUserProfileDisplayOrder().then(r => {
      setFormOrder(r.form_order)
    })
  }, [])
  const table_columns = getTableColumns(cp);

  let order_cp = deepCopy(base_columns);
  const form_ordered = orderForm(formOrder, order_cp);

  const create_columns = [...form_ordered];
  const update_cp = deepCopy(form_ordered)
  const update_columns = getUpdateColumns(update_cp);

  const [columnsStateMap, setColumnsStateMap] = useState({});

  const [paramState, setParamState] = useState({});

  useEffect(() => {
    queryUserProfileListDisplay().then(value => {
      setColumnsStateMap(value)
    })
  }, [])


   

   const [groupsManyToManyList, setGroupsManyToManyList] = useState([]);
                        useEffect(() => {
                          queryGroup({all:1}).then(value => {
                            setGroupsManyToManyList(value);
                          });
                        }, []);const [user_permissionsManyToManyList, setUser_permissionsManyToManyList] = useState([]);
                        useEffect(() => {
                          queryPermission({all:1}).then(value => {
                            setUser_permissionsManyToManyList(value);
                          });
                        }, []);
  return (
    <PageHeaderWrapper>
      <ProTable
        beforeSearchSubmit={(params => {
          dealTime(params, dateFieldList);
          return params;
        })}
        params={paramState}
        scroll={{ x: '100%' }}
        columnsStateMap={columnsStateMap}
        onColumnsStateChange={(map) => setColumnsStateMap(map)}
        headerTitle="登入管理表格"
        actionRef={actionRef}
        rowKey="id"
        toolBarRender={(action, { selectedRows }) => [
          <Button type="primary" onClick={() => handleModalVisible(true)}>
            <PlusOutlined /> 新建
          </Button>,
          <Button type="primary" onClick={() => exportExcelAll(paramState, queryUserProfile, table_columns, '登入管理-All')}>
            <ExportOutlined /> 导出全部
          </Button>,
          <Input.Search style={{ marginRight: 20 }} placeholder="搜索登入管理" onSearch={value => {
            setParamState({
              search: value,
            });
            actionRef.current.reload();
          }} />,
          selectedRows && selectedRows.length > 0 && (
            <Dropdown
              overlay={
                <Menu
                  onClick={async e => {
                    if (e.key === 'remove') {
                      await handleRemove(selectedRows);
                      actionRef.current.reloadAndRest();
                    }
                    else if (e.key === 'export_current') {
                      exportExcelCurrent(selectedRows, table_columns, '登入管理-select')
                    }
                  }}
                  selectedKeys={[]}
                >
                  <Menu.Item key="remove">批量删除</Menu.Item>
                  <Menu.Item key="export_current">导出已选</Menu.Item>
                </Menu>
              }
            >
              <Button>
                批量操作 <DownOutlined />
              </Button>
            </Dropdown>
          ),
        ]}
        tableAlertRender={({ selectedRowKeys, selectedRows }) => (
          selectedRowKeys.length > 0 ? <div>
            已选择{' '}
            <a
              style={{
                fontWeight: 600,
              }}
            >
              {selectedRowKeys.length}
            </a>{' '}
            项&nbsp;&nbsp;
          </div> : false

        )}
        request={(params, sorter, filter) => queryUserProfile({ ...params, sorter, filter })}
        columns={table_columns}
        rowSelection={{}}
      />
      <CreateForm onCancel={() => handleModalVisible(false)} modalVisible={createModalVisible}>
        <ProTable
          formRef={addFormRef}
          onSubmit={async value => {
            richTrans(value);
            const success = await handleAdd(value);

            if (success) {
              handleModalVisible(false);

              if (actionRef.current) {
                actionRef.current.reload();
              }
            }
          }}
          rowKey="key"
          type="form"
          search={twoColumns}
          form={
            {
              labelCol: { span: 6 },
              labelAlign: 'left',
            }}
          columns={create_columns}
          rowSelection={{}}
        />
      </CreateForm>
      <UpdateForm onCancel={() => handleUpdateModalVisible(false)} modalVisible={updateModalVisible}>
        <ProTable
          formRef={updateFormRef}
          onSubmit={async value => {
            richTrans(value);
            const success = await handleUpdate(value, updateFormValues.id);

            if (success) {
              handleUpdateModalVisible(false);

              if (actionRef.current) {
                actionRef.current.reload();
              }
            }
          }}
          rowKey="key"
          search={twoColumns}
          type="form"
          form={{
            initialValues: updateFormValues, labelCol: { span: 6 },
            labelAlign: 'left',
          }}
          columns={update_columns}
          rowSelection={{}}
        />
      </UpdateForm>
             {
                      <UpdatePasswordForm
                        onCancel={() => {
                          handleUpdatePassWordModalVisible(false);
                        }}
                        handleUpdate={handlePassWordUpdate}
                        updateModalVisible={updatePassWordModalVisible}
                        userName={updateFormValues["username"]}
                      >
                        <Form form={updatePasswordForm}>
                          <FormItem
                            labelCol={{
                              span: 5,
                            }}
                            wrapperCol={{
                              span: 15,
                            }}
                            label="密码"
                            name="password"
                            rules={[
                              {
                                required: true,
                                message: '请输入密码!',
                              },
                            ]}
                          >
                            <Input.Password placeholder="请输入密码" type="password" />
                          </FormItem>
                          <FormItem
                            labelCol={{
                              span: 5,
                            }}
                            wrapperCol={{
                              span: 15,
                            }}
                            label="重复密码"
                            name="re_password"
                            rules={[
                              {
                                required: true,
                                message: '请输入重复密码',
                              },
                            ]}
                          >
                            <Input.Password placeholder="请再次输入密码" type="password" />
                          </FormItem>
    
                        </Form>
                      </UpdatePasswordForm>
                    }
    </PageHeaderWrapper>
  );
}
Example #20
Source File: dark.jsx    From virtuoso-design-system with MIT License 4 votes vote down vote up
render() {
    const { disabled, selectedKeys, targetKeys, showSearch } = this.state;
    const columns = [
      {
        title: 'Name',
        dataIndex: 'name',
        key: 'name',
        filters: [
          { text: 'Joe', value: 'Joe' },
          { text: 'Jim', value: 'Jim' },
        ],
        filteredValue: null,
        onFilter: (value, record) => record.name.includes(value),
        sorter: (a, b) => a.name.length - b.name.length,
        sortOrder: true,
        ellipsis: true,
      },
      {
        title: 'Age',
        dataIndex: 'age',
        key: 'age',
        sorter: false,
        sortOrder: true,
        ellipsis: true,
      },
      {
        title: 'Address',
        dataIndex: 'address',
        key: 'address',
        filters: [
          { text: 'London', value: 'London' },
          { text: 'New York', value: 'New York' },
        ],
        filteredValue: null,
        onFilter: (value, record) => record.address.includes(value),
        sorter: false,
        sortOrder: true,
        ellipsis: true,
      },
    ];
    return (
      <>
        <Button type="primary" onClick={this.showModal}>
          Open Modal
        </Button>
        <Modal
          title="Basic Modal"
          visible={this.state.visible}
          onOk={this.handleOk}
          onCancel={this.handleCancel}
        >
          <Switch
            unCheckedChildren="disabled"
            checkedChildren="disabled"
            checked={disabled}
            onChange={this.handleDisable}
            style={{ marginBottom: 16 }}
          />
          <Card title="Card Title">
            <Card.Grid>Content</Card.Grid>
            <Card.Grid hoverable={false}>Content</Card.Grid>
            <Card.Grid>Content</Card.Grid>
            <Card.Grid>Content</Card.Grid>
            <Card.Grid>Content</Card.Grid>
            <Card.Grid>Content</Card.Grid>
            <Card.Grid>Content</Card.Grid>
          </Card>
          <Collapse>
            <Panel header="This is panel header 1" key="1">
              <Collapse defaultActiveKey="1">
                <Panel header="This is panel nest panel" key="1">
                  <p>{text}</p>
                </Panel>
              </Collapse>
            </Panel>
            <Panel header="This is panel header 2" key="2">
              <p>{text}</p>
            </Panel>
            <Panel header="This is panel header 3" key="3">
              <p>{text}</p>
            </Panel>
          </Collapse>
          <Transfer
            dataSource={mockData}
            titles={['Source', 'Target']}
            targetKeys={targetKeys}
            selectedKeys={selectedKeys}
            onChange={this.handleTransferChange}
            onSelectChange={this.handleTransferSelectChange}
            render={item => item.title}
            disabled={disabled}
          />
          <TableTransfer
            dataSource={mockData}
            targetKeys={targetKeys}
            disabled={disabled}
            showSearch={showSearch}
            onChange={this.handleTableTransferChange}
            filterOption={(inputValue, item) =>
              item.title.indexOf(inputValue) !== -1 || item.tag.indexOf(inputValue) !== -1
            }
            leftColumns={[
              {
                dataIndex: 'title',
                title: 'Name',
              },
              {
                dataIndex: 'description',
                title: 'Description',
              },
            ]}
            rightColumns={[
              {
                dataIndex: 'title',
                title: 'Name',
              },
            ]}
          />
          <Switch
            unCheckedChildren="disabled"
            checkedChildren="disabled"
            checked={disabled}
            onChange={this.triggerDisable}
            style={{ marginTop: 16 }}
          />
          <Switch
            unCheckedChildren="showSearch"
            checkedChildren="showSearch"
            checked={showSearch}
            onChange={this.triggerShowSearch}
            style={{ marginTop: 16 }}
          />
          <Anchor>
            <Link href="#components-anchor-demo-basic" title="Basic demo" />
            <Link href="#components-anchor-demo-static" title="Static demo" />
            <Link
              href="#components-anchor-demo-basic"
              title="Basic demo with Target"
              target="_blank"
            />
            <Link href="#API" title="API">
              <Link href="#Anchor-Props" title="Anchor Props" />
              <Link href="#Link-Props" title="Link Props" />
            </Link>
          </Anchor>
          <Tabs type="card">
            <TabPane tab="Tab 1" key="1">
              Content of Tab Pane 1
            </TabPane>
            <TabPane tab="Tab 2" key="2">
              Content of Tab Pane 2
            </TabPane>
            <TabPane tab="Tab 3" key="3">
              Content of Tab Pane 3
            </TabPane>
          </Tabs>
          <Timeline>
            <Timeline.Item>Create a services site 2015-09-01</Timeline.Item>
            <Timeline.Item>Solve initial network problems 2015-09-01</Timeline.Item>
            <Timeline.Item dot={<ClockCircleOutlined style={{ fontSize: '16px' }} />} color="red">
              Technical testing 2015-09-01
            </Timeline.Item>
            <Timeline.Item>Network problems being solved 2015-09-01</Timeline.Item>
          </Timeline>
          <Calendar />
          <Tree showLine switcherIcon={<DownOutlined />} defaultExpandedKeys={['0-0-0']}>
            <TreeNode title="parent 1" key="0-0">
              <TreeNode title="parent 1-0" key="0-0-0">
                <TreeNode title="leaf" key="0-0-0-0" />
                <TreeNode title="leaf" key="0-0-0-1" />
                <TreeNode title="leaf" key="0-0-0-2" />
              </TreeNode>
              <TreeNode title="parent 1-1" key="0-0-1">
                <TreeNode title="leaf" key="0-0-1-0" />
              </TreeNode>
              <TreeNode title="parent 1-2" key="0-0-2">
                <TreeNode title="leaf" key="0-0-2-0" />
                <TreeNode title="leaf" key="0-0-2-1" />
              </TreeNode>
            </TreeNode>
          </Tree>
          <Table columns={columns} dataSource={data} footer={() => 'Footer'} />
          <Table
            columns={columnsTable}
            dataSource={dataTable}
            pagination={false}
            id="table-demo-summary"
            bordered
            summary={pageData => {
              let totalBorrow = 0;
              let totalRepayment = 0;

              pageData.forEach(({ borrow, repayment }) => {
                totalBorrow += borrow;
                totalRepayment += repayment;
              });

              return (
                <>
                  <tr>
                    <th>Total</th>
                    <td>
                      <Text type="danger">{totalBorrow}</Text>
                    </td>
                    <td>
                      <Text>{totalRepayment}</Text>
                    </td>
                  </tr>
                  <tr>
                    <th>Balance</th>
                    <td colSpan={2}>
                      <Text type="danger">{totalBorrow - totalRepayment}</Text>
                    </td>
                  </tr>
                </>
              );
            }}
          />
          <br />
          <Table columns={columnsNest} expandable={{ expandedRowRender }} dataSource={dataNest} />
          <Table columns={columnsFixed} dataSource={dataFixed} scroll={{ x: 1300, y: 100 }} />
          <Card
            hoverable
            style={{ width: 240 }}
            cover={
              <img alt="example" src="https://os.alipayobjects.com/rmsportal/QBnOOoLaAfKPirc.png" />
            }
          >
            <Meta title="Europe Street beat" description="www.instagram.com" />
          </Card>
          <Slider defaultValue={30} />
          <DatePicker defaultValue={moment('2015/01/01', 'YYYY/MM/DD')} format="YYYY/MM/DD" />
          <Badge count={5}>
            <a href="#" className="head-example" />
          </Badge>
        </Modal>
      </>
    );
  }
Example #21
Source File: index.jsx    From prometheusPro with MIT License 4 votes vote down vote up
render() {
    const {
      listAndbasicList: { list },
      loading,
    } = this.props;
    const {
      form: { getFieldDecorator },
    } = this.props;
    const { visible, done, current = {} } = this.state;

    const editAndDelete = (key, currentItem) => {
      if (key === 'edit') this.showEditModal(currentItem);
      else if (key === 'delete') {
        Modal.confirm({
          title: '删除任务',
          content: '确定删除该任务吗?',
          okText: '确认',
          cancelText: '取消',
          onOk: () => this.deleteItem(currentItem.id),
        });
      }
    };

    const modalFooter = done
      ? {
          footer: null,
          onCancel: this.handleDone,
        }
      : {
          okText: '保存',
          onOk: this.handleSubmit,
          onCancel: this.handleCancel,
        };

    const Info = ({ title, value, bordered }) => (
      <div className={styles.headerInfo}>
        <span>{title}</span>
        <p>{value}</p>
        {bordered && <em />}
      </div>
    );

    const extraContent = (
      <div className={styles.extraContent}>
        <RadioGroup defaultValue="all">
          <RadioButton value="all">全部</RadioButton>
          <RadioButton value="progress">进行中</RadioButton>
          <RadioButton value="waiting">等待中</RadioButton>
        </RadioGroup>
        <Search className={styles.extraContentSearch} placeholder="请输入" onSearch={() => ({})} />
      </div>
    );
    const paginationProps = {
      showSizeChanger: true,
      showQuickJumper: true,
      pageSize: 5,
      total: 50,
    };

    const ListContent = ({ data: { owner, createdAt, percent, status } }) => (
      <div className={styles.listContent}>
        <div className={styles.listContentItem}>
          <span>Owner</span>
          <p>{owner}</p>
        </div>
        <div className={styles.listContentItem}>
          <span>开始时间</span>
          <p>{moment(createdAt).format('YYYY-MM-DD HH:mm')}</p>
        </div>
        <div className={styles.listContentItem}>
          <Progress
            percent={percent}
            status={status}
            strokeWidth={6}
            style={{
              width: 180,
            }}
          />
        </div>
      </div>
    );

    const MoreBtn = ({ item }) => (
      <Dropdown
        overlay={
          <Menu onClick={({ key }) => editAndDelete(key, item)}>
            <Menu.Item key="edit">编辑</Menu.Item>
            <Menu.Item key="delete">删除</Menu.Item>
          </Menu>
        }
      >
        <a>
          更多 <DownOutlined />
        </a>
      </Dropdown>
    );

    const getModalContent = () => {
      if (done) {
        return (
          <Result
            status="success"
            title="操作成功"
            subTitle="一系列的信息描述,很短同样也可以带标点。"
            extra={
              <Button type="primary" onClick={this.handleDone}>
                知道了
              </Button>
            }
            className={styles.formResult}
          />
        );
      }

      return (
        <Form onSubmit={this.handleSubmit}>
          <FormItem label="任务名称" {...this.formLayout}>
            {getFieldDecorator('title', {
              rules: [
                {
                  required: true,
                  message: '请输入任务名称',
                },
              ],
              initialValue: current.title,
            })(<Input placeholder="请输入" />)}
          </FormItem>
          <FormItem label="开始时间" {...this.formLayout}>
            {getFieldDecorator('createdAt', {
              rules: [
                {
                  required: true,
                  message: '请选择开始时间',
                },
              ],
              initialValue: current.createdAt ? moment(current.createdAt) : null,
            })(
              <DatePicker
                showTime
                placeholder="请选择"
                format="YYYY-MM-DD HH:mm:ss"
                style={{
                  width: '100%',
                }}
              />,
            )}
          </FormItem>
          <FormItem label="任务负责人" {...this.formLayout}>
            {getFieldDecorator('owner', {
              rules: [
                {
                  required: true,
                  message: '请选择任务负责人',
                },
              ],
              initialValue: current.owner,
            })(
              <Select placeholder="请选择">
                <SelectOption value="付晓晓">付晓晓</SelectOption>
                <SelectOption value="周毛毛">周毛毛</SelectOption>
              </Select>,
            )}
          </FormItem>
          <FormItem {...this.formLayout} label="产品描述">
            {getFieldDecorator('subDescription', {
              rules: [
                {
                  message: '请输入至少五个字符的产品描述!',
                  min: 5,
                },
              ],
              initialValue: current.subDescription,
            })(<TextArea rows={4} placeholder="请输入至少五个字符" />)}
          </FormItem>
        </Form>
      );
    };

    return (
      <>
        <PageHeaderWrapper>
          <div className={styles.standardList}>
            <Card bordered={false}>
              <Row>
                <Col sm={8} xs={24}>
                  <Info title="我的待办" value="8个任务" bordered />
                </Col>
                <Col sm={8} xs={24}>
                  <Info title="本周任务平均处理时间" value="32分钟" bordered />
                </Col>
                <Col sm={8} xs={24}>
                  <Info title="本周完成任务数" value="24个任务" />
                </Col>
              </Row>
            </Card>

            <Card
              className={styles.listCard}
              bordered={false}
              title="基本列表"
              style={{
                marginTop: 24,
              }}
              bodyStyle={{
                padding: '0 32px 40px 32px',
              }}
              extra={extraContent}
            >
              <Button
                type="dashed"
                style={{
                  width: '100%',
                  marginBottom: 8,
                }}
                onClick={this.showModal}
                ref={component => {
                  // eslint-disable-next-line  react/no-find-dom-node
                  this.addBtn = findDOMNode(component);
                }}
              >
                <PlusOutlined />
                添加
              </Button>
              <List
                size="large"
                rowKey="id"
                loading={loading}
                pagination={paginationProps}
                dataSource={list}
                renderItem={item => (
                  <List.Item
                    actions={[
                      <a
                        key="edit"
                        onClick={e => {
                          e.preventDefault();
                          this.showEditModal(item);
                        }}
                      >
                        编辑
                      </a>,
                      <MoreBtn key="more" item={item} />,
                    ]}
                  >
                    <List.Item.Meta
                      avatar={<Avatar src={item.logo} shape="square" size="large" />}
                      title={<a href={item.href}>{item.title}</a>}
                      description={item.subDescription}
                    />
                    <ListContent data={item} />
                  </List.Item>
                )}
              />
            </Card>
          </div>
        </PageHeaderWrapper>

        <Modal
          title={done ? null : `任务${current ? '编辑' : '添加'}`}
          className={styles.standardListForm}
          width={640}
          bodyStyle={
            done
              ? {
                  padding: '72px 0',
                }
              : {
                  padding: '28px 0 0',
                }
          }
          destroyOnClose
          visible={visible}
          {...modalFooter}
        >
          {getModalContent()}
        </Modal>
      </>
    );
  }
Example #22
Source File: RightContent.js    From acy-dex-interface with MIT License 4 votes vote down vote up
GlobalHeaderRight = props => {
  const { global } = props;
  // 选择货币的弹窗
  const [visible, setVisible] = useState(false);
  const [visibleMetaMask, setVisibleMetaMask] = useState(false);
  const [visibleSetting, setVisibleSetting] = useState(false);
  const [only, setOnly] = useState(true);
  // 连接钱包函数
  const { library } = useConstantLoader();
  const { account, chainId, activate, deactivate, active } = useWeb3React();

  const [wallet, setWallet] = useState(localStorage.getItem("wallet"));

  const [selectedNetwork, setSelectedNetwork] = useState("BSC");
  const [supportedWallets, setSupportWallets] = useState([]);

  // 连接钱包 根据localStorage
  useEffect(() => {
    setWallet(localStorage.getItem("wallet"))
    if (!account) {
      if (!wallet) {
        console.log("localStroage dosen't exist");
        localStorage.setItem('wallet', 'binance');
      }
    }
  }, [account]);

  useEffect(() => {
    console.log('test current active', active)
    if (!active)
      deactivate();
  }, [active]);

  // 判断设备
  const [userSystem, setuserSystem] = useState("other");
  const [broswer, setBroswer] = useState();

  function getBroswer() {
    var userAgent = navigator.userAgent; //取得浏览器的userAgent字符串
    var isOpera = userAgent.indexOf("Opera") > -1;
    if (isOpera || userAgent.indexOf("OPR") > -1) {
      console.log(userAgent, 'ymj')
      return "Opera"
    }; //判断是否Opera浏览器
    if (userAgent.indexOf("Firefox") > -1) {
      return "FF";
    } //判断是否Firefox浏览器
    if (userAgent.indexOf("Chrome") > -1) {
      console.log(userAgent, 'ymj')
      return "Chrome";
    }
    if (userAgent.indexOf("Safari") > -1) {
      return "Safari";
    } //判断是否Safari浏览器
    if (userAgent.indexOf("compatible") > -1 && userAgent.indexOf("MSIE") > -1 && !isOpera) {
      return "IE";
    }; //判断是否IE浏览器

  }

  useEffect(() => {
    function fIsMobile() {
      return /Android|iPhone|iPad|iPod|BlackBerry|webOS|Windows Phone|SymbianOS|IEMobile|Opera Mini/i.test(navigator.userAgent);
    }
    var u = navigator.userAgent;
    var isAndroid = u.indexOf('Android') > -1 || u.indexOf('Adr') > -1; //android终端
    var isiOS = !!u.match(/\(i[^;]+;( U;)? CPU.+Mac OS X/); //ios终端
    if (u) {
      setuserSystem("isPC");
    } else if (isAndroid) {
      setuserSystem("isAndroid");
    } else if (isiOS) {
      setuserSystem("isiOS");
    } else setuserSystem("other");
    var b = getBroswer();
    setBroswer(b);
  }, [])

  useEffect(() => {
    if (account) {
      localStorage.setItem("login_status", "on");
    }
    else {
      //localStorage.setItem("login_status", "off");
      setNetworkListIndex(0)
    }
  }, [account]);

  const getNoticeData = () => {
    const { notices = [] } = props;
    if (notices.length === 0) {
      return {};
    }
    const newNotices = notices.map(notice => {
      const newNotice = { ...notice };
      if (newNotice.datetime) {
        newNotice.datetime = moment(notice.datetime).fromNow();
      }
      if (newNotice.id) {
        newNotice.key = newNotice.id;
      }
      if (newNotice.extra && newNotice.status) {
        const color = {
          todo: '',
          processing: 'blue',
          urgent: 'red',
          doing: 'gold',
        }[newNotice.status];
        newNotice.extra = (
          <Tag color={color} style={{ marginRight: 0 }}>
            {newNotice.extra}
          </Tag>
        );
      }
      return newNotice;
    });
    return groupBy(newNotices, 'type');
  };

  const getUnreadData = noticeData => {
    const unreadMsg = {};
    Object.entries(noticeData).forEach(([key, value]) => {
      if (!unreadMsg[key]) {
        unreadMsg[key] = 0;
      }
      if (Array.isArray(value)) {
        unreadMsg[key] = value.filter(item => !item.read).length;
      }
    });
    return unreadMsg;
  };

  const onhandCancel = () => {
    setVisibleMetaMask(false);
  };
  const onhandMetaMask = () => {
    setVisibleMetaMask(true);
    setNetworkListIndex(n_index(chainId));
    console.log(broswer, 'ymj')
  };
  const onhandCancelMetaMask = () => {
    setVisibleMetaMask(false);
  };
  const onhandSetting = flag => {
    setVisibleSetting(!!flag);
  };
  const handleVisibleChange = () => { }

  const [isModalVisible, setIsModalVisible] = useState(false);

  const showModal = () => {
    setIsModalVisible(true);
  };

  // 选择钱包
  const selectWallet = walletName => {
    if (walletName != localStorage.getItem("wallet"))
      localStorage.setItem("login_status", "off");
    console.log('selecting wallet', walletName);
    if (walletName === 'metamask') {
      try {
        ethereum;
        activate(injected);
      } catch (error) {
        message.info('No provider was found');
        if (account) {
          localStorage.setItem("login_status", "on");
        }
        return
      }
    } else if (walletName === 'bitkeep') {
      try {
        ethereum;
        activate(injected);
        if (!window.isBitKeep) {
          message.info('Wrong wallet, please make sure other wallet extensions has been closed');
        }
      } catch (error) {
        message.info('No provider was found');
        if (account) {
          localStorage.setItem("login_status", "on");
        }
        return
      }
    }
    else if (walletName === 'opera') {
      activate(injected);
    }
    else if (walletName === 'walletconnect') {
      activate(walletconnect);
    } else if (walletName === 'coinbase') {
      activate(walletlink);
    } else if (walletName === 'fortmatic') {
      activate(fortmatic);
    } else if (walletName === 'portis') {
      activate(portis);
    } else if (walletName === 'torus') {
      activate(torus);
    } else if (walletName === 'trezor') {
      activate(trezor);
    } else if (walletName === 'ledger') {
      activate(ledger);
    } else if (walletName === 'binance') {
      try {
        BinanceChain
        activate(binance);
      } catch (error) {
        message.info('No provider was found');
        if (account) {
          localStorage.setItem("login_status", "on");
        }
        return
      }
    } else if (walletName === 'nabox') {
      try {
        NaboxWallet;
        activate(nabox);
      } catch (error) {
        message.info('No provider was found');
        if (account) {
          localStorage.setItem("login_status", "on");
        }
        return
      }
    } else {
      console.log("wallet ERROR");
    }
    localStorage.setItem('wallet', walletName);
    setVisibleMetaMask(false);
  };
  // 初始网络显示
  const n_index = chainId => {
    if (chainId == 56 || chainId == 97) {
      return 2
    }
    if (chainId == 137 || chainId == 80001) {
      return 3
    }
    if (chainId == 1) {
      return 4
    }
    if (chainId == undefined) {
      return 0
    }
    return 1
  }
  // 通知钱包连接成功
  const checkChainNetwork = (chainId) => {
    if (!chainId) {
      switchEthereumChain("0x38"); //返回默认56链
      return
    }
    console.log("networkChanged:", chainId)
    console.log("supported chain?", supportedChainIds, chainId, supportedChainIds.indexOf(chainId) == -1)
    if (supportedChainIds && supportedChainIds.indexOf(Number(chainId)) == -1) {
      console.log("ERROR: unsupport NetWork");
      setIsModalVisible(true);
      switchEthereumChain("0x38"); //返回默认56链
    }
    else if (chainId == 97) {
      // 测试网 不显示给用户
      switchEthereumChain("0x61");
      setNetworkListIndex(0)
    }
    else {
      setIsModalVisible(false);
      setVisibleMetaMask(false);
      setNetworkListIndex(n_index(chainId))
    }
  }
  useEffect(() => {
    // todo....
    if (account) {
      console.log(account);
      setVisibleMetaMask(false);
    }
    checkChainNetwork(chainId);
    // 监听钱包网络变化 metamask
    if (localStorage.getItem("wallet") == "metamask" || localStorage.getItem("wallet") == "bitkeep") {
      try {
        ethereum.on('networkChanged', function (chainId) {
          checkChainNetwork(chainId);
        })
      } catch (error) {
        console.log("no metamask plugin");
      }
    }
    if (localStorage.getItem("wallet") == "nabox") {
      // Nabox 监听
      try {
        NaboxWallet.on('networkChanged', function (chainId) {
          checkChainNetwork(chainId);
        })
      } catch (error) {
        console.log("no nabox plugin");
      }
    }
    if (localStorage.getItem("wallet") == "binance") {
      try {
        BinanceChain.on('networkChanged', function (chainId) {
          checkChainNetwork(chainId);
        })
      } catch (error) {
        console.log("no binance plugin");
      }
    }
  }, [account, chainId, supportedChainIds, wallet]);
  const {
    currentUser,
    fetchingMoreNotices,
    fetchingNotices,
    loadedAllNotices,
    onNoticeVisibleChange,
    onMenuClick,
    onNoticeClear,
    skeletonCount,
    theme,
    isMobile,
  } = props;
  // const { visible, visibleMetaMask, visibleSetting } = this.state;
  const menu = (
    <Menu className={styles.menu} selectedKeys={[]} onClick={onMenuClick}>
      <Menu.Item key="userCenter">
        <Icon type="user" />
        <FormattedMessage id="menu.account.center" defaultMessage="account center" />
      </Menu.Item>
      <Menu.Item key="userinfo">
        <Icon type="setting" />
        <FormattedMessage id="menu.account.settings" defaultMessage="account settings" />
      </Menu.Item>
      <Menu.Item key="triggerError">
        <Icon type="close-circle" />
        <FormattedMessage id="menu.account.trigger" defaultMessage="Trigger Error" />
      </Menu.Item>
      <Menu.Divider />
      <Menu.Item key="logout">
        <Icon type="logout" />
        <FormattedMessage id="menu.account.logout" defaultMessage="logout" />
      </Menu.Item>
    </Menu>
  );
  const loadMoreProps = {
    skeletonCount,
    loadedAll: loadedAllNotices,
    loading: fetchingMoreNotices,
  };
  // 货币列表
  const MetaMask = [
    {
      name: 'MetaMask',
      icon: 'Metamask',
      onClick: () => {
        selectWallet('metamask');
      },
    },
  ];
  const BinanceWallet = [
    {
      name: 'Binance Wallet',
      icon: 'Binance',
      onClick: () => {
        selectWallet('binance');
      },
    },
  ];
  const OperaWallet = [
    {
      name: 'Opera',
      icon: 'Opera',
      svgicon: true,
      onClick: () => {
        selectWallet('opera');
      },
    },
  ]
  const walletListAllSupported = [
    {
      name: 'MetaMask',
      icon: 'Metamask',
      onClick: () => {
        selectWallet('metamask');
      },
    },
    {
      name: 'Nabox Wallet',
      icon: 'Nabox',
      onClick: () => {
        selectWallet('nabox');
      },
    },
    {
      name: 'Bitkeep Wallet',
      icon: 'Bitkeep',
      onClick: () => {
        selectWallet('bitkeep');
      },
    },
    {
      name: 'WalletConnect',
      icon: 'WalletConnect',
      onClick: () => {
        selectWallet('walletconnect');
      },
    },
    {
      name: 'TrustWallet',
      icon: 'TrustWallet',
      onClick: () => {
        selectWallet('walletconnect');
      },
    },

  ]

  const walletList = [
    {
      name: 'Coinbase Wallet',
      icon: 'Coinbase',
      onClick: () => {
        selectWallet('coinbase');
      },
    },
    {
      name: 'Nabox Wallet',
      icon: 'Nabox',
      onClick: () => {
        selectWallet('nabox');
      },
    },
    {
      name: 'Bitkeep Wallet',
      icon: 'Bitkeep',
      onClick: () => {
        selectWallet('bitkeep');
      },
    },
    {
      name: 'WalletConnect',
      icon: 'WalletConnect',
      onClick: () => {
        selectWallet('walletconnect');
      },
    },
    {
      name: 'TrustWallet',
      icon: 'TrustWallet',
      onClick: () => {
        selectWallet('walletconnect');
      },
    },
    // {
    //   name: 'Trezor',
    //   icon: 'Trezor',
    //   onClick: () => {
    //     selectWallet('trezor');
    //   },
    // },
    // {
    //   name: 'Ledger',
    //   icon: 'Ledger',
    //   onClick: () => {
    //     selectWallet('ledger');
    //   },
    // },
    // {
    //   name: 'Fortmatic',
    //   icon: 'Fortmatic',
    //   onClick: () => {
    //     selectWallet('fortmatic');
    //   },
    // },
    {
      name: 'Portis',
      icon: 'Portis',
      onClick: () => {
        selectWallet('portis');
      },
    },
    {
      name: 'Torus',
      icon: 'Torus',
      onClick: () => {
        selectWallet('torus');
      },
    },
    {
      name: 'Opera',
      icon: 'Opera',
      svgicon: true,
      onClick: () => {
        selectWallet('opera');
      },
    },
  ];
  const supportedWalletEth = [
    {
      name: 'Binance Wallet',
      icon: 'Binance',
      onClick: () => {
        selectWallet('binance');
      },
    },
    {
      name: 'Coinbase Wallet',
      icon: 'Coinbase',
      onClick: () => {
        selectWallet('coinbase');
      },
    },
    {
      name: 'Portis',
      icon: 'Portis',
      onClick: () => {
        selectWallet('portis');
      },
    },
    {
      name: 'Torus',
      icon: 'Torus',
      onClick: () => {
        selectWallet('torus');
      },
    },
  ]
  const supportedWalletBsc = [
    {
      name: 'Binance Wallet',
      icon: 'Binance',
      onClick: () => {
        selectWallet('binance');
      },
    },
  ]
  const supportedWalletPolygon = [
    {
      name: 'Torus',
      icon: 'Torus',
      onClick: () => {
        selectWallet('torus');
      },
    },
  ]

  const networkParams = {
    "0x38": {
      chainId: '0x38',
      chainName: 'Binance Smart Chain Netwaok',
      nativeCurrency: {
        name: 'Binance',
        symbol: 'BNB', // 2-6 characters long
        decimals: 18
      },
      blockExplorerUrls: ['https://bscscan.com'],
      rpcUrls: ['https://bsc-dataseed.binance.org/'],
    },
    "0x61": {
      chainId: '0x61',
      chainName: 'Binance Smart Chain Testnet',
      nativeCurrency: {
        name: 'Binance',
        symbol: 'BNB', // 2-6 characters long
        decimals: 18
      },
      blockExplorerUrls: ['https://testnet.bscscan.com'],
      rpcUrls: ['https://data-seed-prebsc-1-s1.binance.org:8545/'],
    },
    "0x89": {
      chainId: '0x89',
      chainName: 'Polygon',
      nativeCurrency: {
        name: 'Matic',
        symbol: 'MATIC', // 2-6 characters long
        decimals: 18
      },
      blockExplorerUrls: ['https://polygonscan.com/'],
      rpcUrls: ['https://polygon-rpc.com/'],
    },
    "0xA4B1": {
      chainId: '0xA4B1',
      chainName: 'Arbitrum',
      nativeCurrency: {
        name: 'ETH',
        symbol: 'ETH', // 2-6 characters long
        decimals: 18
      },
      blockExplorerUrls: ['https://arbiscan.io/'],
      rpcUrls: ['https://arb1.arbitrum.io/rpc'],
    },
  };

  const switchEthereumChain = async (chainId) => {
    if (localStorage.getItem("wallet") == "metamask") {
      try {
        await ethereum.request({
          method: 'wallet_switchEthereumChain',
          params: [{ chainId: chainId }],
        });
      } catch (e) {
        if (e.code === 4902) {
          try {
            await ethereum.request({
              method: 'wallet_addEthereumChain',
              params: [
                networkParams[chainId]
              ],
            });
          } catch (addError) {
            console.error(addError);
          }
        }
      }
    }
    else if (localStorage.getItem("wallet") == "nabox") {
      try {
        await NaboxWallet.request({
          method: 'wallet_switchEthereumChain',
          params: [{ chainId: chainId }],
        });
      } catch (e) {
        if (e.code === 4902) {
          try {
            await NaboxWallet.request({
              method: 'wallet_addEthereumChain',
              params: [
                networkParams[chainId]
              ],
            });
          } catch (addError) {
            console.error(addError);
          }
        }
      }
    }
    else if (localStorage.getItem("wallet") == "binance") {
      try {
        await BinanceChain.request({
          method: 'wallet_switchEthereumChain',
          params: [{ chainId: chainId }],
        });
      } catch (e) {
        if (e.code === 4902) {
          try {
            await BinanceChain.request({
              method: 'wallet_addEthereumChain',
              params: [
                networkParams[chainId]
              ],
            });
          } catch (addError) {
            console.error(addError);
          }
        }
      }
    }
    if (chainId == 1) {
      setSelectedNetwork('ETH');
    }
    else if (chainId == 56) {
      setSelectedNetwork('BNBChain');
    }
    else if (chainId == 137) {
      setSelectedNetwork('Polygon');
    }
  }
  const showMore = () => {
    setOnly(!only);
  };
  const noticeData = getNoticeData();
  const unreadMsg = getUnreadData(noticeData);
  let className = styles.right;
  if (theme === 'dark') {
    className = `${styles.right}  ${styles.dark}`;
  }
  // 网络列表
  const [networkListIndex, setNetworkListIndex] = useState(0);
  const networkList = [
    {
      name: 'NO Network',
      //icon: 'Polygon',
      onClick: async () => {
        setVisibleMetaMask(false);
      },
      onClick_showSupportedWallet: async () => {

      },
    },
    {
      name: 'Wrong Network',
      //icon: 'Polygon',
      onClick: async () => {
        setVisibleMetaMask(false);
      },
      onClick_showSupportedWallet: async () => {

      },
    },
    {
      name: 'BNB Chain',
      icon: 'Binance',
      onClick: async () => {
        await switchEthereumChain("0x38");
        setVisibleMetaMask(false);
      },
      onClick_showSupportedWallet: async () => {
        setSelectedNetwork('BNB Chain');
        setSupportWallets(supportedWalletBsc);
      },
    },
    {
      name: 'Polygon',
      icon: 'Polygon',
      onClick: async () => {
        await switchEthereumChain("0x89");
        setVisibleMetaMask(false);
      },
      onClick_showSupportedWallet: async () => {
        setSelectedNetwork('Polygon');
        setSupportWallets(supportedWalletPolygon);
      },
    },
    {
      name: 'Ethereum',
      icon: 'Eth',
      onClick: async () => {
        await switchEthereumChain("0x1");
        setVisibleMetaMask(false);
      },
      onClick_showSupportedWallet: async () => {
        setSelectedNetwork('Ethereum');
        setSupportWallets(supportedWalletEth);
      },
    },
    // {
    //   name: 'Arbitrum',
    //   icon: 'Arbitrum',
    //   onClick: async () => {
    //     await switchEthereumChain("0xA4B1");
    //     setVisibleMetaMask(false);
    //   },
    // },
  ];
  const networkListInCardList = (
    <div className={styles.networkListBlock}>
      <div className={styles.networkTitle}>
        <span>Select a Network</span>
      </div>
      <AcyCardList>
        {networkList.slice(2,).map((item) => {
          return (
            <AcyCardList.Thin className={styles.networkListLayout} onClick={() => item.onClick()}>
              {
                <AcyIcon.MyIcon width={20} type={item.icon} />
              }
              <span>{item.name}</span>
            </AcyCardList.Thin>
          );
        }
        )}
      </AcyCardList>
    </div>
  );
  const deactivateTest = () => {
    deactivate();
    localStorage.setItem("login_status", 'off')
  }

  return (
    <div className={className}>
      <Row wrap={false} style={{display: "inline-flex", fontSize: "0.7rem"}}>
        <Col flex="none">
          {/* <Button onClick={deactivateTest}>disconnected</Button> */}
          <Dropdown
            overlay={networkListInCardList}
            trigger={['click']}
            placement="bottomLeft"  
          //className={styles.networkButton}
          >
            <div type="primary" shape="round" className={styles.networkButton}>
              {[networkList[networkListIndex]].map(item => (
                <div>
                  <AcyIcon.MyIcon type={item.icon} /> {item.name} <DownOutlined /></div>
                //<Icon><DownOutlined /></Icon>
              ))}
            </div>
          </Dropdown>
        </Col>
        <Col flex="auto">
        {/* <AcyIcon onClick={this.onhandConnect} name="acy" /> */}
          <AcyConnectWallet
            chainId={chainId} // this is the chainId from useWeb3React
            isMobile={isMobile}
            onClick={onhandMetaMask}
            pendingLength={
              props.transaction.transactions.length
            }
          />
        </Col>
      </Row>


      {false && (
        <Dropdown
          overlay={
            <div className={styles.setting} onClick={e => e.preventDefault()}>
              <ul className={styles.list}>
                <li>
                  <AcySeting title="Gas Price" current="Rapid(85.1gwei) ~3">
                    <AcyRadioButton data={['Rapid(85.1gwei) ~3', 'Rapid(67.1gwei) ~6']} />
                  </AcySeting>
                </li>
                <li>
                  <AcySeting title="Endpoint" current="Global 122.0ms">
                    <AcyRadioButton data={['Global 122.0ms', 'Custom']} />
                  </AcySeting>
                </li>
                <li>
                  <AcySeting title="Network" current="ETH">
                    <AcyRadioButton
                      data={['ETH', 'BSC', 'Heco', 'Polygon', 'Arbitrum', 'OkChain']}
                    />
                  </AcySeting>
                </li>
                {/* <li style={{borderBottom:'1px solid rgb(64, 64, 64)',paddingBottom:'20px'}}>
                <AcySeting title="Language" current="English">
                  <AcyRadioButton data={['English', '中文']} />
                </AcySeting>
              </li> */}
                {/* <li style={{marginTop:'30px'}}>
                  <a className={styles.setitem}>
                    <Icon type="question-circle" />Help
                  </a>
                  <a className={styles.setitem}>
                  <Icon type="notification" />Announcements
                  </a>
                  <a className={styles.setitem}>
                  <Icon type="message" />Forum
                  </a>
              </li> */}
              </ul>
            </div>
          }
          trigger={['click']}
          placement="bottomLeft"
          visible={visibleSetting}
          onVisibleChange={onhandSetting}
        >
          <AcyIcon
            width={30}
            name={visibleSetting ? 'colors-active' : 'colors'}
            onClick={() => onhandSetting(true)}
          />
        </Dropdown>
      )}


      {!account && <div>
        <AcyModal width={420} visible={visibleMetaMask} onCancel={onhandCancel}
          bodyStyle={{
            padding: '21px',
            background: 'black',
            // backgroundColor: '#1b1b1c',
            borderRadius: ' 10px',
            // boxShadow: '0 0 14px #2d2d2d'
            border: '0.75px solid #333333',
          }}>
          <div className={styles.networkTitle}>
            <span>1. Select a Network</span>
          </div>
          {/*ymj*/}
          <AcyCardList grid={true}>
            {networkList.slice(2,).map((item) => {
              return (
                <AcyCardList.Thin className={selectedNetwork == item.name ? styles.networkListLayout_selected : styles.networkListLayout} onClick={() => {
                  item.onClick_showSupportedWallet()
                }}>
                  {
                    <AcyIcon.MyIcon width={20} type={item.icon} />
                  } 
                  <span>{item.name}</span>
                  {selectedNetwork == item.name &&
                    <span className={styles.networkListLayout_selectedCheck}>
                      <svg xmlns="http://www.w3.org/2000/svg" fill="#eb5c20" style={{ height: '18px' }} viewBox="0 0 50 50">
                        <path d="M21.05 33.1 35.2 18.95 32.9 16.7 21.05 28.55 15.05 22.55 12.8 24.8ZM24 44Q19.75 44 16.1 42.475Q12.45 40.95 9.75 38.25Q7.05 35.55 5.525 31.9Q4 28.25 4 24Q4 19.8 5.525 16.15Q7.05 12.5 9.75 9.8Q12.45 7.1 16.1 5.55Q19.75 4 24 4Q28.2 4 31.85 5.55Q35.5 7.1 38.2 9.8Q40.9 12.5 42.45 16.15Q44 19.8 44 24Q44 28.25 42.45 31.9Q40.9 35.55 38.2 38.25Q35.5 40.95 31.85 42.475Q28.2 44 24 44ZM24 24Q24 24 24 24Q24 24 24 24Q24 24 24 24Q24 24 24 24Q24 24 24 24Q24 24 24 24Q24 24 24 24Q24 24 24 24ZM24 41Q31.25 41 36.125 36.125Q41 31.25 41 24Q41 16.75 36.125 11.875Q31.25 7 24 7Q16.75 7 11.875 11.875Q7 16.75 7 24Q7 31.25 11.875 36.125Q16.75 41 24 41Z"/>
                      </svg>
                      {/* <CheckCircleTwoTone style={{color: '#eb5c20'}} /> */}
                    </span>}
                </AcyCardList.Thin>
              );
            }
            )}
          </AcyCardList>
          <div className={styles.walltitle}>
            <span style={{ marginLeft: '10px' }}>2. Select a Wallet</span>
          </div>


          {/* <AcyCardList>
          {MetaMask.map(item => (
            <AcyCardList.Thin onClick={() => item.onClick()}>
              {(item.svgicon && <Opera width={32} style={{ margin: '5px' }} />) || (
                <AcyIcon.MyIcon width={32} type={item.icon} />
              )}
              <span className={styles.fontBold}>{item.name}</span>
            </AcyCardList.Thin>
          ))}
          {BinanceWallet.map(item => (
            <AcyCardList.Thin onClick={() => item.onClick()}>
              {(item.svgicon && <Opera width={32} style={{ margin: '5px' }} />) || (
                <AcyIcon.MyIcon width={32} type={item.icon} />
              )}
              <span className={styles.fontBold}>{item.name}</span>
            </AcyCardList.Thin>
          ))}
        </AcyCardList> */}

          <AcyCardList grid={true}>
            { /*ymj */}
            {broswer === 'Opera' && OperaWallet.map((item, index) => {

              return (
                <AcyCardList.Thin className={styles.walletList} onClick={() => item.onClick()}>
                  {(item.svgicon && <Opera width={32} style={{ margin: '5px' }} />) || (
                    <AcyIcon.MyIcon width={32} type={item.icon} />
                  )}
                  <span className={styles.fontBold}>{item.name}</span>
                </AcyCardList.Thin>
              );

            })}

            {walletListAllSupported.map((item, index) => {

              return (
                <AcyCardList.Thin className={styles.walletList} onClick={() => item.onClick()}>
                  {(item.svgicon && <Opera width={32} style={{ margin: '5px' }} />) || (
                    <AcyIcon.MyIcon width={32} type={item.icon} />
                  )}
                  <span className={styles.fontBold}>{item.name}</span>
                </AcyCardList.Thin>
              );

            })}
            {supportedWallets.map((item, index) => {

              return (
                <AcyCardList.Thin className={styles.walletList} onClick={() => item.onClick()}>
                  {(item.svgicon && <Opera width={32} style={{ margin: '5px' }} />) || (
                    <AcyIcon.MyIcon width={32} type={item.icon} />
                  )}
                  <span className={styles.fontBold}>{item.name}</span>
                </AcyCardList.Thin>
              );

            })}
          </AcyCardList>
        </AcyModal>
      </div>}
      {account && <div>
        <AcyModal width={200} height={100} visible={visibleMetaMask} onCancel={onhandCancel}
          bodyStyle={{
            padding: '21px',
            background: '#2e3032',
            borderRadius: ' 20px',
          }}>
          <div type="primary" shape="round" className={styles.disconnectBtn} onClick={deactivateTest}><DisconnectOutlined /> Disconnect</div>
        </AcyModal>
      </div>}

      {/* 错误弹窗*/}
      <AcyModal width={420} visible={isModalVisible}>
        <p>ERROR: UNSUPPORT NETWORKS</p>
        <p>We are not ready for this networks, please change your networks!</p>
      </AcyModal>

    </div>
  );
}
Example #23
Source File: index.js    From gobench with Apache License 2.0 4 votes vote down vote up
DashboardBeta = () => {
  const [taskTableSelectedRowKeys, setTaskTableSelectedRowKeys] = useState([])

  const onSelectChange = keys => {
    setTaskTableSelectedRowKeys(keys)
  }

  const taskTableRowSelection = {
    taskTableSelectedRowKeys,
    onChange: onSelectChange
  }

  const dropdownMenu = (
    <Menu>
      <Menu.Item key='1'>1st menu item</Menu.Item>
      <Menu.Item key='2'>2nd menu item</Menu.Item>
      <Menu.Item key='3'>3rd item</Menu.Item>
    </Menu>
  )

  const taskTableColumns = [
    {
      title: 'Name',
      dataIndex: 'name',
      render: text => <a href=''>{text}</a>
    },
    {
      title: 'Username',
      dataIndex: 'username',
      render: text => <a href=''>{text}</a>
    },
    {
      title: 'Actions',
      dataIndex: 'actions',
      render: () => (
        <div className='pull-right'>
          <Dropdown overlay={dropdownMenu}>
            <Button style={{ marginLeft: 8 }} size='small'>
              Action <DownOutlined />
            </Button>
          </Dropdown>
        </div>
      )
    }
  ]

  const tableColumns = [
    {
      title: 'Name',
      dataIndex: 'name',
      key: 'name'
    },
    {
      title: 'Position',
      dataIndex: 'position',
      key: 'position'
    },
    {
      title: 'Age',
      dataIndex: 'age',
      key: 'age',
      sorter: (a, b) => a.age - b.age
    },
    {
      title: 'Office',
      dataIndex: 'office',
      key: 'office'
    },
    {
      title: 'Date',
      dataIndex: 'date',
      key: 'date'
    },
    {
      title: 'Salary',
      dataIndex: 'salary',
      key: 'salary',
      sorter: (a, b) => a.salary - b.salary
    }
  ]

  return (
    <div>
      <Helmet title='Dashboard: Beta' />
      <div className='row'>
        <div className='col-lg-12 col-xl-6'>
          <div className='card'>
            <div className='card-header'>
              <div className='cui__utils__heading mb-0'>
                <strong>Account Information</strong>
              </div>
              <div className='text-muted'>Block with important Account information</div>
            </div>
            <div className='card-body'>
              <General19 />
            </div>
          </div>
          <div className='card'>
            <div className='card-header'>
              <div className='cui__utils__heading mb-0'>
                <strong>Work Progress</strong>
              </div>
              <div className='text-muted'>Block with important Work Progress information</div>
            </div>
            <div className='card-body'>
              <div>
                <strong>{progressGroup.first.name}</strong>
                <p className='text-muted mb-1'>{progressGroup.first.description}</p>
                <div className='mb-3'>
                  <Progress
                    percent={progressGroup.first.progress}
                    status={progressGroup.first.status}
                  />
                </div>
                <strong>{progressGroup.second.name}</strong>
                <p className='text-muted mb-1'>{progressGroup.second.description}</p>
                <div className='mb-3'>
                  <Progress
                    percent={progressGroup.second.progress}
                    status={progressGroup.second.status}
                  />
                </div>
                <strong>{progressGroup.third.name}</strong>
                <p className='text-muted mb-1'>{progressGroup.third.description}</p>
                <div className='mb-3'>
                  <Progress
                    percent={progressGroup.third.progress}
                    status={progressGroup.third.status}
                  />
                </div>
                <strong>{progressGroup.fourth.name}</strong>
                <p className='text-muted mb-1'>{progressGroup.fourth.description}</p>
                <div className='mb-3'>
                  <Progress
                    percent={progressGroup.fourth.progress}
                    status={progressGroup.fourth.status}
                  />
                </div>
                <strong>{progressGroup.fives.name}</strong>
                <p className='text-muted mb-1'>{progressGroup.fives.description}</p>
                <div className='mb-3'>
                  <Progress percent={progressGroup.fives.progress} />
                </div>
              </div>
            </div>
          </div>
          <div className='card'>
            <div className='card-header'>
              <div className='cui__utils__heading mb-0'>
                <strong>Employees</strong>
              </div>
              <div className='text-muted'>Block with Employees important information</div>
            </div>
            <div className='card-body'>
              <div className='row'>
                <div className='col-md-6'>
                  <div className='card bg-light border-0 mb-0'>
                    <General23 />
                  </div>
                </div>
                <div className='col-md-6'>
                  <div className='card border-0 mb-0'>
                    <General23v1 />
                  </div>
                </div>
              </div>
            </div>
          </div>
          <div className='card'>
            <div className='card-header'>
              <div className='cui__utils__heading mb-0'>
                <strong>Task Table</strong>
              </div>
              <div className='text-muted'>Block with important Task Table information</div>
            </div>
            <div className='card-body'>
              <div className='row'>
                <div className='col-lg-12'>
                  <div className='kit__utils__table'>
                    <Table
                      columns={taskTableColumns}
                      dataSource={taskTableData}
                      rowSelection={taskTableRowSelection}
                      pagination={false}
                    />
                  </div>
                </div>
              </div>
            </div>
          </div>
          <div className='card'>
            <div className='card-header'>
              <div className='cui__utils__heading mb-0'>
                <strong>Information Cards</strong>
              </div>
              <div className='text-muted'>Block with important Information Cards information</div>
            </div>
            <div className='card-body'>
              <div className='card bg-primary border-0 mb-4'>
                <div className='card-body'>
                  <General24 />
                </div>
              </div>
              <div className='card bg-light border-0 mb-0'>
                <div className='card-body'>
                  <General24v1 />
                </div>
              </div>
            </div>
          </div>
        </div>
        <div className='col-lg-12 col-xl-6'>
          <div className='card'>
            <div className='card-header'>
              <div className='cui__utils__heading mb-0'>
                <strong>Server Info</strong>
              </div>
              <div className='text-muted'>Block with important Server Info information</div>
            </div>
            <div className='card-body'>
              <div className='row'>
                <div className='col-lg-6'>
                  <div className='overflow-hidden rounded card border-0 mb-0'>
                    <General20 />
                  </div>
                </div>
                <div className='col-lg-6'>
                  <div className='overflow-hidden rounded card border-0 mb-0'>
                    <General20v1 />
                  </div>
                </div>
              </div>
            </div>
          </div>
          <div className='card'>
            <div className='card-header'>
              <div className='cui__utils__heading mb-0'>
                <strong>Server Statistics</strong>
              </div>
              <div className='text-muted'>Block with important Server Statistics information</div>
            </div>
            <div className='card-body'>
              <div className='row'>
                <div className='col-lg-6'>
                  <General21 />
                  <General21v1 />
                </div>
                <div className='col-lg-6'>
                  <General21v2 />
                  <General21v3 />
                </div>
              </div>
            </div>
          </div>
          <div className='card'>
            <div className='card-header'>
              <div className='cui__utils__heading mb-0'>
                <strong>Server Configuration</strong>
              </div>
              <div className='text-muted'>
                Block with important Server Configuration information
              </div>
            </div>
            <div className='card-body'>
              <div className='mb-5'>
                <Slider marks={rangeMarks} defaultValue={rangeSlider.first} />
              </div>
              <div className='mb-4'>
                <Slider range marks={rangeMarks} defaultValue={rangeSlider.second} />
              </div>
            </div>
          </div>
          <div className='card'>
            <div className='card-header'>
              <div className='cui__utils__heading mb-0'>
                <strong>Week Revenue Statistics, Billions</strong>
              </div>
              <span className='mr-2'>
                <span className='kit__utils__donut kit__utils__donut--primary' />
                Nuts
              </span>
              <span className='mr-2'>
                <span className='kit__utils__donut kit__utils__donut--success' />
                Apples
              </span>
              <span className='mr-2'>
                <span className='kit__utils__donut kit__utils__donut--yellow' />
                Peaches
              </span>
            </div>
            <div className='card-body'>
              <ChartistGraph
                data={weekChartistData}
                options={weekChartistOptions}
                type='Line'
                className='chart-area height-300 mt-4 chartist'
              />
            </div>
          </div>
          <div className='card'>
            <div className='card-header'>
              <div className='cui__utils__heading mb-0'>
                <strong>Month Site Visits Growth, %</strong>
              </div>
              <span className='mr-2'>
                <span className='kit__utils__donut kit__utils__donut--primary' />
                Income
              </span>
              <span className='mr-2'>
                <span className='kit__utils__donut kit__utils__donut--success' />
                Outcome
              </span>
            </div>
            <div className='card-body'>
              <ChartistGraph
                data={monthCartistData}
                options={monthChartistOptions}
                type='Bar'
                className='chart-area height-300 mt-4 chartist'
              />
            </div>
          </div>
          <div className='card'>
            <div className='card-header'>
              <div className='cui__utils__heading mb-0'>
                <strong>Chat</strong>
              </div>
              <div className='text-muted'>Block with important Chat information</div>
            </div>
            <div className='card-body'>
              <General14 />
            </div>
          </div>
        </div>
      </div>
      <div className='row'>
        <div className='col-lg-12'>
          <div className='card'>
            <div className='card-body'>
              <div className='mb-4'>
                <General22 />
              </div>
              <div className='kit__utils__table'>
                <Table columns={tableColumns} dataSource={tableData} />
              </div>
            </div>
          </div>
          <div className='card'>
            <div className='card-header'>
              <div className='cui__utils__heading mb-0'>
                <strong>Calendar</strong>
              </div>
              <div className='text-muted'>Block with important Calendar information</div>
            </div>
            <div className='card-body'>
              <Calendar dateCellRender={dateCellRender} />
            </div>
          </div>
        </div>
      </div>
    </div>
  )
}
Example #24
Source File: _DetailBox.js    From acy-dex-interface with MIT License 4 votes vote down vote up
DetailBox = (props) => {

    const [shortModeProfitsModelVisible, setShortModeProfitsModelVisible] = useState(false);
    const [profitsIn, setProfitsIn] = useState("USDT");
    const {
        leverage,
        shortOrLong,
        marketOrLimit,
        entryPriceLimit,
        liqPrice,
        entryPriceMarket,
        exitPrice,
        borrowFee,
        token1Symbol,
        fromUsdMin,
        toUsdMax,
        toTokenInfo,
        triggerPriceValue,
        shortCollateralToken,
        toTokenAddress,
        shortCollateralAddress,
        positionsMap,
        positionKey,
        positions,
    } = props;

    const shortModeProfitsTokenList = [
        {
            name: 'USD Tether',
            symbol: 'USDT',
            address: '0x55d398326f99059ff775485246999027b3197955',
            decimals: 18,
            logoURI: 'https://storageapi.fleek.co/chwizdo-team-bucket/ACY Token List/USDT.svg',
            idOnCoingecko: "tether",
        },
        {
            name: 'ACY',
            symbol: 'ACY',
            address: '0xc94595b56e301f3ffedb8ccc2d672882d623e53a',
            decimals: 18,
            logoURI: 'https://acy.finance/static/media/logo.78c0179c.svg',
            idOnCoingecko: "acy-finance",
        },
    ]


    const profitsInOnClickHandle = () => {
        setShortModeProfitsModelVisible(true);
    }
    const onCancel = () => {
        setShortModeProfitsModelVisible(false);
    }

    const ShortModeProfitsModel = () => {
        return (
            <AcyModal onCancel={onCancel} width={400} visible={shortModeProfitsModelVisible}>
                <div>
                    <div className={styles.modelTitle}>
                        Profits In
                    </div>
                    {shortModeProfitsTokenList.map((token, index) => {
                        return (
                            // 感觉得重新写 先放着
                            <AcyCoinItem
                                data={token}
                                key={index}
                                customIcon={false}
                                //clickCallback={() => {console.log('ymj clickCallback wait for function');}}
                                selectToken={() => {
                                    onCancel();
                                    setProfitsIn(token.symbol);
                                }}
                            //constBal={token.symbol in tokenBalanceDict ? tokenBalanceDict[token.symbol] : null}
                            />
                        );
                    })}
                </div>
            </AcyModal>
        )
    }
    // position part
    const existingPosition = positionKey ? positionsMap[positionKey] : undefined;
    const hasExistingPosition =
        existingPosition && existingPosition.size && existingPosition.size.gt(0);
    // liquidation part start
    let entryMarkPrice;
    let exitMarkPrice;
    if (toTokenInfo) {
        entryMarkPrice =
            shortOrLong === LONG ? toTokenInfo.maxPrice : toTokenInfo.minPrice;
        exitMarkPrice =
            shortOrLong === LONG ? toTokenInfo.minPrice : toTokenInfo.maxPrice;
    }
    const triggerPriceUsd = marketOrLimit === MARKET ? 0 : parseValue(triggerPriceValue, USD_DECIMALS)
    let nextAveragePrice = marketOrLimit === MARKET ? entryMarkPrice : triggerPriceUsd;
    //const liquidationPrice = getLiquidationPrice({amount:expandDecimals(123, USD_DECIMALS), leverage:leverage})
    const liquidationPrice = getLiquidationPrice({
        isLong: shortOrLong === LONG ? true : false,
        size: hasExistingPosition ? existingPosition.size : bigNumberify(0),
        collateral: hasExistingPosition ? existingPosition.collateral : bigNumberify(0),
        averagePrice: nextAveragePrice,
        //averagePrice: BigNumber.from('2895270000000000000000000000000000'), // entryPrice
        entryFundingRate: hasExistingPosition ? existingPosition.entryFundingRate : bigNumberify(0),
        cumulativeFundingRate: hasExistingPosition ? existingPosition.cumulativeFundingRate : bigNumberify(0),
        sizeDelta: toUsdMax, // max price * to token amount
        collateralDelta: fromUsdMin, // min price * from token amount
        increaseCollateral: true,
        increaseSize: true
    })
    const existingLiquidationPrice = existingPosition ? getLiquidationPrice(existingPosition) : undefined;
    let displayLiquidationPrice = liquidationPrice ? liquidationPrice : existingLiquidationPrice;
    console.log('ymj liq price: ', displayLiquidationPrice);
    // fee
    let feesUsd;
    let positionFee;
    if (marketOrLimit === MARKET || marketOrLimit === LIMIT) {
        if (toUsdMax) {
            positionFee = toUsdMax
                .mul(MARGIN_FEE_BASIS_POINTS)
                .div(BASIS_POINTS_DIVISOR);
            feesUsd = positionFee;
        }
    }
    let hasZeroBorrowFee = false;
    let borrowFeeText;
    if (shortOrLong === LONG && toTokenInfo && toTokenInfo.fundingRate) {
        borrowFeeText = formatAmount(toTokenInfo.fundingRate, 4, 4) + "% / 1h";
        if (toTokenInfo.fundingRate.eq(0)) {
            // hasZeroBorrowFee = true
        }
    }
    if (shortOrLong === SHORT && shortCollateralToken && shortCollateralToken.fundingRate) {
        borrowFeeText =
            formatAmount(shortCollateralToken.fundingRate, 4, 4) + "% / 1h";
        if (shortCollateralToken.fundingRate.eq(0)) {
            // hasZeroBorrowFee = true
        }
    }

    // liquidation part end

    useEffect(() => {
        console.log('ymj detal box online', liquidationPrice, formatAmount(displayLiquidationPrice, USD_DECIMALS, 2, true))
    }, [])

    return (
        <div>
            <AcyCard className={styles.describeMain}>
                <div>
                    {shortOrLong === LONG &&
                        <p className={styles.describeTitle}>Profits In: <span className={styles.describeInfo}>{token1Symbol ? token1Symbol : '-'}</span></p>
                    }
                    {shortOrLong === SHORT &&
                        <p className={styles.describeTitle}>Profits In: <span className={styles.describeInfoClickable}
                            onClick={profitsInOnClickHandle}>
                            {profitsIn ? profitsIn : '-'} <DownOutlined />
                        </span></p>
                    }
                    <p className={styles.describeTitle}>Leverage:
                        <span className={styles.describeInfo}>
                            {hasExistingPosition && (
                                <span>
                                    {/*formatAmount(existingPosition.leverage, 4, 2)*/}
                                    {Number(leverage).toFixed(2)}
                                    x
                                    <SwapRightOutlined />
                                </span>
                            )}
                            {Number(leverage).toFixed(2)}x</span></p>
                    <p className={styles.describeTitle}>Entry Price:
                        <span className={styles.describeInfo}>
                            {hasExistingPosition && nextAveragePrice && (
                                <span>$
                                    {/* {formatAmount(
                                        existingPosition.averagePrice,
                                        USD_DECIMALS,
                                        2,
                                        true
                                    )} */}
                                    {Number(leverage).toFixed(2)}
                                    <SwapRightOutlined />
                                </span>
                            )}
                            {nextAveragePrice &&
                                `$${formatAmount(nextAveragePrice, USD_DECIMALS, 2, true)}`}
                            {!nextAveragePrice && `-`} USD</span></p>

                    <p className={styles.describeTitle}>Liq. Price:  <span className={styles.describeInfo}>
                        {hasExistingPosition && displayLiquidationPrice && (
                            <span>$
                                {/* {formatAmount(
                              existingLiquidationPrice,
                              USD_DECIMALS,
                              2,
                              true
                            )} */}
                                {Number(leverage).toFixed(2)}
                                <SwapRightOutlined />
                            </span>
                        )}
                        {displayLiquidationPrice ? formatAmount(displayLiquidationPrice, USD_DECIMALS, 2, true) : '-'}USD</span></p>
                    <p className={styles.describeTitle}>Fees:  <span className={styles.describeInfo}>
                        {!feesUsd && '-'}
                        {feesUsd && `$${formatAmount(feesUsd, USD_DECIMALS, 2, true)}`}
                    </span></p>
                    {shortOrLong === SWAP &&
                        <div>
                        </div>
                    }
                    {/* hj TODO : swap part not showing borrowFee */}

                </div>
                <div className={styles.describeMainTitle}>{shortOrLong} {token1Symbol}</div>
                <div>
                    <p className={styles.describeTitle}>Entry Price: <span className={styles.describeInfo}>
                        {!entryMarkPrice && '-'}
                        {entryMarkPrice && `$${formatAmount(entryMarkPrice, USD_DECIMALS, 2, true)}`} USD</span></p>
                    <p className={styles.describeTitle}>Exit Price:  <span className={styles.describeInfo}>
                        {!exitMarkPrice && '-'}
                        {exitMarkPrice && `$${formatAmount(exitMarkPrice, USD_DECIMALS, 2, true)}`} USD</span></p>
                    <p className={styles.describeTitle}>Borrow Fee:  <span className={styles.describeInfo}>
                        {!borrowFeeText && '-'}
                        {borrowFeeText && `${borrowFeeText}`}</span></p>
                </div>
            </AcyCard>
            <ShortModeProfitsModel />
        </div>

    )
}
Example #25
Source File: DashboardNav.js    From video-journal-for-teams-fe with MIT License 4 votes vote down vote up
DashboardNav = withRouter((props) => {
	// Use location from router as a key to show that link is selected.
	const {
		// location,
		// organization_id,
		organizations,
		userId,
		fetchUserOrganizations,
		defaultOrganization,
		selectedOrganization,
		fetchUserTeams,
		setUserSelectedOrganization,
		children,
	} = props;

	const { Sider } = Layout;
	const { Title } = Typography;
	const [showModal, setShowModal] = useState(false);
	const location = useLocation();

	let organization_id = "";

	if (typeof selectedOrganization === "undefined" || typeof defaultOrganization === "undefined") {
		organization_id = "";
	} else {
		organization_id = selectedOrganization.id ? selectedOrganization.id : defaultOrganization.id;
	}

	function handleClick(item) {
		setUserSelectedOrganization(item);
		// history.push('/user-dashboard');
	}

	const toggleModal = () => {
		setShowModal(!showModal);
	};

	let filteredOrg = organizations.filter((x) => x.id === organization_id);

	const menu = (
		<Menu>
			{organizations.map((item) => (
				<Link key={item.id} to="/user-dashboard">
					<Menu.Item style={{ textAlign: "center", color: "#FF7F50" }} key={item.id} onClick={() => handleClick(item)}>
						{item.name}
					</Menu.Item>
				</Link>
			))}
			<Menu.Item>
				<Organization />
			</Menu.Item>
		</Menu>
	);

	return (
		<Sider breakpoint="lg" collapsedWidth="0" width="240" style={{ backgroundColor: "#6954EA" }}>
			<div className={"userDashHeader"} style={{ backgroundColor: "#6954EA" }}>
				<Title level={3}>
					<Link
						to="/user-dashboard"
						className={"userDashHeaderFont"}
						style={{ color: "whitesmoke", marginTop: "12px" }}>
						<div className="logo">
							<img src={logo} alt="logo" />
						</div>	
						
					</Link>
				</Title>
			</div>
			<Menu style={{ backgroundColor: "#6954EA" }} mode="inline" className={"userDashMenu"}>
				<Dropdown overlay={menu} trigger="click">
					<a
						className="ant-dropdown-link"
						onClick={(e) => e.preventDefault()}
						style={{ display: "block", width: "500" }}>
						<div style={{ paddingLeft: "25px", color: "white", width: "200px", textOverflow: "ellipsis" }}>
							<BankOutlined style={{ paddingRight: "16px" }} />
							{selectedOrganization.hasOwnProperty("name")
								? selectedOrganization.name
								: defaultOrganization
								? defaultOrganization.name
								: ""}
							<DownOutlined />
						</div>
					</a>
				</Dropdown>


				<hr style={{ margin: "25px 0" }} />
				<Menu.Item key="/user-dashboard">
					<Link to="/user-dashboard" style={{ backgroundColor: "#6954EA", color: "#fff", display: "block" }}>
						<Icon type="home" theme="filled"/> Dashboard
					</Link>
				</Menu.Item>
				<Menu.Item key="/profile">
					<Link to="/profile" style={{ color: "#FFF", display: "block" }}>
						<Icon type="user" /> My Profile
					</Link>
				</Menu.Item>
				<Menu.Item key="/videos">
					<Link to="/videos" style={{ color: "#FFF", display: "block" }}>
						<Icon type="play-circle" theme="filled" /> My Videos
					</Link>
				</Menu.Item>

				{filteredOrg.length > 0 && filteredOrg[0].role_id === 3 ? (
					<Menu.Item key="/teams">
						<Link to={`/organizations/${organization_id}/teams`} style={{ color: "#FFF", display: "block" }}>
							<Icon type="calendar" theme="filled" /> All Teams
						</Link>
					</Menu.Item>
				) : null}

				{filteredOrg.length > 0 && filteredOrg[0].role_id === 3 ? (
					<Menu.Item key="/users">
						<Link to={`/organizations/${organization_id}/users`} style={{ color: "#FFF", display: "block" }}>
							<Icon type="calendar" theme="filled" /> All Users
						</Link>
					</Menu.Item>
				) : null}
				<Menu.Item key="/results">
					<Link to="/results" style={{ backgroundColor: "#6954EA", color: "#fff", display: "block" }}>
						<PieChartFilled /> My Results
					</Link>
				</Menu.Item>
				<hr style={{ margin: "40px 0" }} />
				{/* <Menu.Item key="/setting" disabled>
					<Icon type="setting" theme="filled" />
					Teams Settings
				</Menu.Item>
				
				<h3 style={{ color: "white", paddingLeft: "24px", paddingBottom: "20px" }}>Team Controls</h3>
				<Menu.Item key="/manage-teams" disabled>
					<Icon type="calendar" theme="filled" />
					<span>Manage Teams</span>
				</Menu.Item>
				<Menu.Item key="/team-archive" disabled>
					<Icon type="folder" theme="filled" />
					<span>Team Archive</span>
				</Menu.Item> */}
			</Menu>
		</Sider>
	);
})
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 VisGeo-ETL with MIT License 4 votes vote down vote up
Fields = ({ fields, tables }) => {
  const fieldsDebug = ['Campo 1', 'Campo 2', 'Campo 3', 'Campo 4', 'Campo 5', 'Campo 6'];
  const tablesDebug = ['Tabela 1', 'Tabela 2', 'Tabela 3', 'Tabela 4', 'Tabela 5', 'Tabela 6'];

  const [columns, setColumns] = useState([]);
  const [saveLoading, setSaveLoading] = useState(false);
  const [selectedTable, setSelectedTable] = useState('');
  const [openModal, setOpenModal] = useState(false);

  const handleOpenModal = () => {
    setOpenModal(true);
  };

  async function handleSaveDirectly () {
    setSaveLoading(true);
    const filename = localStorage.getItem('filename');

    try {
      await api.post('/saveDirectly', {
        filename,
        token: localStorage.getItem('token')
      });
      message.success('Salvo com sucesso');
    } catch (error) {
      message.error('Falha ao salvar arquivo no banco de dados');
    }
    
    setSaveLoading(false);
  };

  async function handleGetColumns(table) {
    setSelectedTable(table);

    const response = await api.post(`/columns/${table}`, {token: localStorage.getItem('token')});
    setColumns(response.data);
    message.info(`Tabela ${table} selecionada`);
  }

  const menu = (
    <Menu>
      {localStorage.getItem('MODE') === 'production'
        ? tables.map((table) => (
          <Menu.Item
            onClick={() => handleGetColumns(table)}
            key={table}
          >
            {table}
          </Menu.Item>
        ))
        : tablesDebug.map((table) => (
          <Menu.Item
            onClick={() => handleGetColumns(table)}
            key={table}
          >
            {table}
          </Menu.Item>
        ))}
    </Menu>
  );

  return (
    <Container>
      <ModalTables
        selectedTable={selectedTable}
        fields={fields}
        show={openModal}
        columns={columns}
        setShow={setOpenModal}
      />

      <div className="fields-search-container">
        <section>
          <h1>CAMPOS DISPONÍVEIS</h1>
          <div className="fields-container">
            {localStorage.getItem('MODE') === 'production'
              ? fields.map((eachField) => (
                <span className="fields">
                  {eachField}
                </span>
              )) : fieldsDebug.map((eachField) => (
                <span className="fields">
                  {eachField}
                </span>
              ))}
          </div>
        </section>

        <section>
          <div className="fields-container">

            <Dropdown overlay={menu} trigger={['click']}>
              <a className="ant-dropdown-link" href onClick={(e) => e.preventDefault()}>
                {selectedTable || "SELECIONE UMA TABELA"}
                {' '}
                <DownOutlined className="down-arrow-menu" />
              </a>
            </Dropdown>

            <button type="button" onClick={handleOpenModal} className="handle-button">
              Configurar de
              {' '}
              <ArrowRight />
              {' '}
              para

            </button>
          </div>
        </section>
      </div>

      <Button 
        className="saveDirectly"
        type="button"
        loading={saveLoading}
        onClick={handleSaveDirectly}
        title="Criar e salvar o shapefile inteiro em uma nova tabela"
      >
        {saveLoading ? "Enviando arquivos" : "Salvar diretamente"}
      </Button>
    </Container>
  );
}
Example #28
Source File: Statistics.js    From bonded-stablecoin-ui with MIT License 4 votes vote down vote up
Statistics = ({ windowWidth }) => {
  const {
    address,
    bonded_state,
    params,
    oraclePrice,
    deposit_state,
    symbol1,
    symbol2,
    symbol3,
    symbol4,
    reserve_asset_symbol,
    fund_aa,
    fund_state,
    fund_balance,
    stable_state
  } = useSelector((state) => state.active);
  const actualParams = getParams(params, bonded_state);
  const [timestamp, setTimestamp] = useState(Math.floor(Date.now() / 1000));
  const [showBlock, setShowBlock] = useState(false);
  const { t } = useTranslation();
  const { supply1, supply2, asset1 } = bonded_state;
  const { decimals1, decimals2, reserve_asset, m, n,reserve_asset_decimals } = actualParams;
  const supply = stable_state?.supply || deposit_state?.supply;
  const fund_supply = fund_state?.shares_supply;
  const s1 = supply1 / 10 ** decimals1;
  const s2 = supply2 / 10 ** decimals2;
  const p1 =
    params.m *
    s1 ** (params.m - 1) *
    s2 ** params.n *
    bonded_state.dilution_factor;

  const target_p2 =
    oraclePrice &&
    !isEmpty(bonded_state) &&
    $get_target_p2(
      oraclePrice,
      actualParams.leverage,
      actualParams.interest_rate,
      timestamp,
      bonded_state.rate_update_ts,
      bonded_state.growth_factor
    );

  useEffect(() => {
    const interval = setInterval(() => {
      setTimestamp(Math.floor(Date.now() / 1000));
    }, 1000);

    return () => {
      clearInterval(interval);
    };
  }, [address]);

  if (!address) return null;
  let currentPrice = 0;
  let targetPrice = 0;

  if ("p2" in bonded_state) {
    if ("oracles" in actualParams) {
      if (actualParams.oracles[0].op === "*" && !actualParams.leverage) {
        currentPrice = 1 / bonded_state.p2;
      } else {
        currentPrice = bonded_state.p2;
      }
    } else {
      if (actualParams.op1 === "*" && !actualParams.leverage) {
        currentPrice = 1 / bonded_state.p2;
      } else {
        currentPrice = bonded_state.p2;
      }
    }
  }

  let bPriceInversed = false;
  if ("oracles" in actualParams) {
    if (actualParams.oracles[0].op === "*" && !actualParams.leverage) {
      bPriceInversed = true;
      targetPrice = 1 / target_p2;
    } else {
      targetPrice = target_p2;
    }
  } else {
    if (actualParams.op1 === "*" && !actualParams.leverage) {
      bPriceInversed = true;
      targetPrice = 1 / target_p2;
    } else {
      targetPrice = target_p2;
    }
  }

  const displayOraclePrice = (bPriceInversed || actualParams.leverage) ? oraclePrice : 1 / oraclePrice;
  const reserve_symbol = reserve_asset in config.reserves ? config.reserves[reserve_asset].name : reserve_asset_symbol || "";
  const p2UnitsText = bPriceInversed
    ? t("trade.statistic.p2UnitsText.inversed", "The shown price is the price of the reserve asset {{reserveSymbolOrAsset}} in terms of Token2 ({{symbol2orAsset}}).", { reserveSymbolOrAsset: reserve_symbol || '', symbol2orAsset: symbol2 || bonded_state.asset2 })
    : t("trade.statistic.p2UnitsText.not_inversed", "The shown price is the price of Token2 ({{symbol2OrAsset}}) in terms of the reserve asset {{reserveSymbol}}.", { symbol2OrAsset: symbol2 || bonded_state.asset2, reserveSymbol: reserve_symbol || '' });
  const p2Unit = bPriceInversed ? symbol2 : reserve_symbol;

  const currentPriceDifference = bonded_state.p2
    ? (currentPrice - targetPrice) / targetPrice
    : 0;

  const shares_supply = fund_state?.shares_supply || 0
  const p1_in_full_units = m * s1 ** (m - 1) * s2 ** n;
  const p1_for_fund = p1_in_full_units * 10 ** (reserve_asset_decimals - decimals1);

  const balance = fund_balance?.[reserve_asset] + p1_for_fund * fund_balance?.[asset1];

  const share_price = shares_supply ? balance / shares_supply : 1;

  const statisticsData = [
    {
      title: fund_aa ? t("trade.statistic.fund_supply.name", "Fund tokens supply") : t("trade.statistic.token1_supply.name", "Tokens1 supply"),
      currency: fund_aa ? symbol4 : symbol1,
      descr: fund_aa ? t("trade.statistic.fund_supply.desc", "Total supply of fund tokens") : t("trade.statistic.token1_supply.desc", "Total supply of Token1 (growth tokens)"),
      value: fund_aa ? fund_supply : supply1,
      decimals: fund_aa ? reserve_asset_decimals : decimals1,
    },
    {
      title: t("trade.statistic.token2_supply.name", "Tokens2 supply"),
      currency: symbol2,
      descr: t("trade.statistic.token2_supply.desc", "Total supply of Token2 (interest tokens)"),
      value: supply2,
      decimals: decimals2,
    },
    {
      title: t("trade.statistic.token_stable_supply.name", "Stable tokens supply"),
      currency: symbol3,
      descr: t("trade.statistic.token_stable_supply.desc", "Total supply of the stable tokens"),
      value: supply,
      decimals: decimals2,
    },
    {
      title: t("trade.statistic.reserve.name", "Reserve"),
      descr: t("trade.statistic.reserve.desc", "Total amount of reserve locked to back the issuance of T1 and T2 tokens"),
      value: "reserve" in bonded_state ? bonded_state.reserve : 0,
      decimals: actualParams.reserve_asset_decimals,
      currency:
        reserve_asset in config.reserves ? config.reserves[reserve_asset].name : reserve_asset_symbol || '',
    },
    {
      title: fund_aa
      ? t("trade.statistic.fund_price.name", "{{symbol4}} price", { symbol4: symbol4 || "T_SF" })
      : t("trade.statistic.token1_price.name", "{{symbol1}} price", { symbol1: symbol1 || "T1" }),
      descr: fund_aa
      ? t("trade.statistic.fund_price.desc", "The current price of fund tokens.")
      : t("trade.statistic.token1_price.desc", "The current price of Token1 according to the bonding curve. It depends on the supplies of Token1 and Token2. The price is shown in terms of the reserve currency."),
      value: fund_aa ? share_price : p1,
      precision: 6,
      currency: reserve_asset in config.reserves ? config.reserves[reserve_asset].name : reserve_asset_symbol || "",
    },
    {
      title: t("trade.statistic.current_price.name", "Current price"),
      descr: t("trade.statistic.current_price.desc", "The current price according to the bonding curve. It depends on the supplies of Token1 and Token2. ") + " " + p2UnitsText,
      value: currentPrice,
      precision: 9,
      percent: currentPriceDifference,
    },
    {
      title: t("trade.statistic.target_price.name", "Target price"),
      descr: t("trade.statistic.target_price.desc", "The price Token2 is pegged to. It is the oracle price plus interest. ") + " " + p2UnitsText,
      value: targetPrice,
      precision: 9,
      currency: p2Unit,
      showZeros: true
    },
    {
      title: t("trade.statistic.oracle_price.name", "Oracle price"),
      descr: t("trade.statistic.oracle_price.desc", "Latest price reported by the oracle"),
      value: displayOraclePrice,
      precision: 9,
    },
  ];

  const rowStyle = !showBlock && windowWidth <= 640 ? {
    height: 40,
    opacity: 0.3,
    overflow: "hidden",
    paddingBottom: 0
  } : { marginBottom: -15 }

  return (
    <div
      style={{
        marginBottom: 20,
        background: "#fff",
        padding: 20,
        display: "block",
        boxSizing: "border-box",
        paddingBottom: !showBlock && windowWidth <= 640 ? 0 : 20
      }}
    >
      <Row justify="start" style={rowStyle}>
        {statisticsData.map((s, i) => (
          <Col
            xs={{ span: 20 }}
            sm={{ span: 12 }}
            lg={{ span: 6, offset: 0 }}
            style={{ marginBottom: 15 }}
            key={"stat-" + i}
          >
            <div className={styles.statisticsItem}>
              <Text type="secondary">
                <Label label={s.title} descr={s.descr} />
              </Text>
              <div style={{ marginTop: 3 }}>
                <span style={{ fontSize: 18 }}>
                  {s.decimals ? (
                    <ShowDecimalsValue
                      value={Number(s.value || 0)}
                      decimals={s.decimals}
                    />
                  ) : (
                    s.precision ? (s.showZeros ?  Number(s.value || 0).toPrecision(s.precision) : +Number(s.value || 0).toPrecision(s.precision)) : +Number(s.value || 0).toFixed(9)
                  )}{" "}
                  <span style={{ fontSize: 12, fontWeight: "normal" }}>
                    {s.currency}
                  </span>
                  <span
                    style={{
                      fontSize: 12,
                      fontWeight: "normal",
                    }}
                  >
                    {"percent" in s &&
                      "(" +
                      (s.percent > 0 ? "+" : "") +
                      ((s.percent || 0) * 100).toFixed(4) +
                      "%)"}
                  </span>
                </span>
              </div>
            </div>
          </Col>
        ))}
      </Row>
      {windowWidth <= 640 && !showBlock && <div
        onClick={() => setShowBlock(true)}
        style={{ paddingTop: 10, paddingBottom: 10, textAlign: "center", cursor: "pointer" }}
      >
        <Trans defaults="Show info" i18nKey="trade.statistic.show" /> <DownOutlined />
      </div>}
      {windowWidth <= 640 && showBlock && <div
        onClick={() => setShowBlock(false)}
        style={{ paddingTop: 10, textAlign: "center", cursor: "pointer" }}
      >
        <Trans defaults="Hide info" i18nKey="trade.statistic.hide" /> <UpOutlined />
      </div>}
    </div>
  );
}
Example #29
Source File: App.js    From next-terminal with GNU Affero General Public License v3.0 4 votes vote down vote up
render() {

        const menu = (
            <Menu>

                <Menu.Item>
                    <Link to={'/info'}>
                        <SolutionOutlined/> 个人中心
                    </Link>
                </Menu.Item>
                <Menu.Divider/>

                <Menu.Item>

                    <Popconfirm
                        key='login-btn-pop'
                        title="您确定要退出登录吗?"
                        onConfirm={this.confirm}
                        okText="确定"
                        cancelText="取消"
                        placement="left"
                    >
                        <LogoutOutlined/> 退出登录
                    </Popconfirm>
                </Menu.Item>

            </Menu>
        );

        return (

            <Switch>
                <Route path="/access" component={Access}/>
                <Route path="/term" component={Term}/>
                <Route path="/login"><Login updateUser={this.updateUser}/></Route>

                <Route path="/">
                    <Layout className="layout" style={{minHeight: '100vh'}}>

                        {
                            isAdmin() ?
                                <>
                                    <Sider collapsible collapsed={this.state.collapsed} trigger={null}>
                                        <div className="logo">
                                            <img src={this.state.logo} alt='logo' width={this.state.logoWidth}/>
                                        </div>

                                        <Menu
                                            onClick={(e) => this.setCurrent(e.key)}
                                            selectedKeys={[this.state.current]}
                                            onOpenChange={this.subMenuChange}
                                            defaultOpenKeys={this.state.openKeys}
                                            theme="dark" mode="inline" defaultSelectedKeys={['dashboard']}
                                            inlineCollapsed={this.state.collapsed}
                                            style={{lineHeight: '64px'}}>

                                            <Menu.Item key="dashboard" icon={<DashboardOutlined/>}>
                                                <Link to={'/'}>
                                                    控制面板
                                                </Link>
                                            </Menu.Item>

                                            <SubMenu key='resource' title='资源管理' icon={<CloudServerOutlined/>}>
                                                <Menu.Item key="asset" icon={<DesktopOutlined/>}>
                                                    <Link to={'/asset'}>
                                                        资产列表
                                                    </Link>
                                                </Menu.Item>
                                                <Menu.Item key="credential" icon={<IdcardOutlined/>}>
                                                    <Link to={'/credential'}>
                                                        授权凭证
                                                    </Link>
                                                </Menu.Item>
                                                <Menu.Item key="dynamic-command" icon={<CodeOutlined/>}>
                                                    <Link to={'/dynamic-command'}>
                                                        动态指令
                                                    </Link>
                                                </Menu.Item>
                                                <Menu.Item key="access-gateway" icon={<ApiOutlined/>}>
                                                    <Link to={'/access-gateway'}>
                                                        接入网关
                                                    </Link>
                                                </Menu.Item>
                                            </SubMenu>

                                            <SubMenu key='audit' title='会话审计' icon={<AuditOutlined/>}>
                                                <Menu.Item key="online-session" icon={<LinkOutlined/>}>
                                                    <Link to={'/online-session'}>
                                                        在线会话
                                                    </Link>
                                                </Menu.Item>

                                                <Menu.Item key="offline-session" icon={<DisconnectOutlined/>}>
                                                    <Link to={'/offline-session'}>
                                                        历史会话
                                                    </Link>
                                                </Menu.Item>
                                            </SubMenu>
                                            <SubMenu key='ops' title='系统运维' icon={<ControlOutlined/>}>
                                                <Menu.Item key="login-log" icon={<LoginOutlined/>}>
                                                    <Link to={'/login-log'}>
                                                        登录日志
                                                    </Link>
                                                </Menu.Item>

                                                <Menu.Item key="job" icon={<BlockOutlined/>}>
                                                    <Link to={'/job'}>
                                                        计划任务
                                                    </Link>
                                                </Menu.Item>

                                                <Menu.Item key="access-security" icon={<SafetyCertificateOutlined/>}>
                                                    <Link to={'/access-security'}>
                                                        访问安全
                                                    </Link>
                                                </Menu.Item>
                                                <Menu.Item key="storage" icon={<HddOutlined/>}>
                                                    <Link to={'/storage'}>
                                                        磁盘空间
                                                    </Link>
                                                </Menu.Item>
                                            </SubMenu>

                                            <SubMenu key='user-manage' title='用户管理' icon={<UserSwitchOutlined/>}>
                                                <Menu.Item key="user" icon={<UserOutlined/>}>
                                                    <Link to={'/user'}>
                                                        用户管理
                                                    </Link>
                                                </Menu.Item>
                                                <Menu.Item key="user-group" icon={<TeamOutlined/>}>
                                                    <Link to={'/user-group'}>
                                                        用户组管理
                                                    </Link>
                                                </Menu.Item>
                                                <Menu.Item key="strategy" icon={<InsuranceOutlined/>}>
                                                    <Link to={'/strategy'}>
                                                        授权策略
                                                    </Link>
                                                </Menu.Item>
                                            </SubMenu>
                                            <Menu.Item key="my-file" icon={<FolderOutlined/>}>
                                                <Link to={'/my-file'}>
                                                    我的文件
                                                </Link>
                                            </Menu.Item>
                                            <Menu.Item key="info" icon={<SolutionOutlined/>}>
                                                <Link to={'/info'}>
                                                    个人中心
                                                </Link>
                                            </Menu.Item>
                                            <Menu.Item key="setting" icon={<SettingOutlined/>}>
                                                <Link to={'/setting'}>
                                                    系统设置
                                                </Link>
                                            </Menu.Item>
                                        </Menu>
                                    </Sider>

                                    <Layout className="site-layout">
                                        <Header className="site-layout-background"
                                                style={{padding: 0, height: headerHeight, zIndex: 20}}>
                                            <div className='layout-header'>
                                                <div className='layout-header-left'>
                                                    {React.createElement(this.state.collapsed ? MenuUnfoldOutlined : MenuFoldOutlined, {
                                                        className: 'trigger',
                                                        onClick: this.onCollapse,
                                                    })}
                                                </div>

                                                <div className='layout-header-right'>
                                                    <div className={'layout-header-right-item'}>
                                                        <a style={{color: 'black'}} target='_blank'
                                                           href='https://github.com/dushixiang/next-terminal'
                                                           rel='noreferrer noopener'>
                                                            <GithubOutlined/>
                                                        </a>
                                                    </div>
                                                </div>

                                                <div className='layout-header-right'>
                                                    <Dropdown overlay={menu}>
                                                        <div className='nickname layout-header-right-item'>
                                                            {getCurrentUser()['nickname']} &nbsp;<DownOutlined/>
                                                        </div>
                                                    </Dropdown>
                                                </div>
                                            </div>
                                        </Header>

                                        <Route path="/" exact component={Dashboard}/>
                                        <Route path="/user" component={User}/>
                                        <Route path="/user-group" component={UserGroup}/>
                                        <Route path="/asset" component={Asset}/>
                                        <Route path="/credential" component={Credential}/>
                                        <Route path="/dynamic-command" component={DynamicCommand}/>
                                        <Route path="/batch-command" component={BatchCommand}/>
                                        <Route path="/online-session" component={OnlineSession}/>
                                        <Route path="/offline-session" component={OfflineSession}/>
                                        <Route path="/login-log" component={LoginLog}/>
                                        <Route path="/info" component={Info}/>
                                        <Route path="/setting" component={Setting}/>
                                        <Route path="/job" component={Job}/>
                                        <Route path="/access-security" component={Security}/>
                                        <Route path="/access-gateway" component={AccessGateway}/>
                                        <Route path="/my-file" component={MyFile}/>
                                        <Route path="/storage" component={Storage}/>
                                        <Route path="/strategy" component={Strategy}/>

                                        <Footer style={{textAlign: 'center'}}>
                                            Copyright © 2020-2022 dushixiang, All Rights Reserved.
                                            Version:{this.state.package['version']}
                                        </Footer>
                                    </Layout>
                                </> :
                                <>
                                    <Header style={{padding: 0}}>
                                        <div className='km-header'>
                                            <div style={{flex: '1 1 0%'}}>
                                                <Link to={'/'}>
                                                    <img src={this.state.logo} alt='logo' width={120}/>
                                                </Link>

                                                <Link to={'/my-file'}>
                                                    <Button type="text" style={{color: 'white'}}
                                                            icon={<FolderOutlined/>}>
                                                        文件
                                                    </Button>
                                                </Link>

                                                <Link to={'/dynamic-command'}>
                                                    <Button type="text" style={{color: 'white'}}
                                                            icon={<CodeOutlined/>}>
                                                        指令
                                                    </Button>
                                                </Link>
                                            </div>
                                            <div className='km-header-right'>
                                                <Dropdown overlay={menu}>
                                                <span className={'km-header-right-item'}>
                                                    {getCurrentUser()['nickname']}
                                                </span>
                                                </Dropdown>
                                            </div>
                                        </div>
                                    </Header>
                                    <Content className='km-container'>
                                        <Layout>
                                            <Route path="/" exact component={MyAsset}/>
                                            <Content className={'kd-content'}>
                                                <Route path="/info" component={Info}/>
                                                <Route path="/my-file" component={MyFile}/>
                                                <Route path="/dynamic-command" component={DynamicCommand}/>
                                            </Content>
                                        </Layout>
                                    </Content>
                                    <Footer style={{textAlign: 'center'}}>
                                        Copyright © 2020-2022 dushixiang, All Rights Reserved.
                                        Version:{this.state.package['version']}
                                    </Footer>
                                </>
                        }


                    </Layout>
                </Route>
            </Switch>

        );
    }