antd#Breadcrumb JavaScript Examples

The following examples show how to use antd#Breadcrumb. 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: CoursePageBreadcrumbs.jsx    From ResoBin with MIT License 6 votes vote down vote up
StyledBreadcrumb = styled(Breadcrumb)`
  display: flex;
  align-items: center;
  margin: 1rem;
  font-size: ${fontSize.responsive.xs};

  & > span {
    display: flex;
  }

  .ant-breadcrumb-link {
    display: flex;
    align-items: center;
    justify-content: center;
    color: ${({ theme }) => theme.primary};

    a {
      display: flex;
      gap: 0.5rem;
      align-items: center;
      color: ${({ theme }) => theme.textColor};

      &:hover {
        text-decoration: underline;
        text-underline-offset: 1px;
      }
    }
  }
`
Example #2
Source File: SystemConfig.js    From kite-admin with MIT License 6 votes vote down vote up
render () {
    return (
      <div className="layout-main" id="system-config">
        <div className="layout-main-title">
          <Breadcrumb>
            <Breadcrumb.Item href="#/manager/index">
              <Icon type="home" />
            </Breadcrumb.Item>
            <Breadcrumb.Item href="#/manager/index">
              <span>主页</span>
            </Breadcrumb.Item>
            <Breadcrumb.Item href="#">
              <span>系统管理</span>
            </Breadcrumb.Item>
            <Breadcrumb.Item>系统配置</Breadcrumb.Item>
          </Breadcrumb>
        </div>

        <EmailBind />
        <WebsiteInfo />
        <WebConfig />
        <Oauth />
        <Theme />
        <Storage />
        <Alert
          message="备注"
          description="由于是系统配置,修改时请谨慎,修改成功某些配置后,如果未生效或者出现错误,请务必重启服务"
          type="warning"
          showIcon
        />
      </div>
    )
  }
Example #3
Source File: basic.jsx    From virtuoso-design-system with MIT License 6 votes vote down vote up
storiesOf('antd/breadcrumb', module).add('basic', () => 
  <Breadcrumb>
    <Breadcrumb.Item>Home</Breadcrumb.Item>
    <Breadcrumb.Item>
      <a href="">Application Center</a>
    </Breadcrumb.Item>
    <Breadcrumb.Item>
      <a href="">Application List</a>
    </Breadcrumb.Item>
    <Breadcrumb.Item>An Application</Breadcrumb.Item>
  </Breadcrumb>,
  { docs: { page: () => (<><h1 id="enus">en-US</h1>
<p>The simplest use.</p></>) } });
Example #4
Source File: AdminSystemLog.js    From kite-admin with MIT License 6 votes vote down vote up
render() {
    const { stateAdminSystemLog } = this.props
    const { loading } = this.state

    return (
      <div className="layout-main">
        <div className="layout-main-title">
          <Breadcrumb>
            <Breadcrumb.Item href="#/manager/index">
              <Icon type="home" />
            </Breadcrumb.Item>
            <Breadcrumb.Item href="#/manager/index">
              <span>主页</span>
            </Breadcrumb.Item>
            <Breadcrumb.Item href="#">
              <span>系统管理</span>
            </Breadcrumb.Item>
            <Breadcrumb.Item>系统日志</Breadcrumb.Item>
          </Breadcrumb>
        </div>

        <div className="card admin-system-tag">
          <div className="card-body layout-table">
            <Table
              columns={this.state.columns}
              dataSource={stateAdminSystemLog.list}
              loading={loading}
              onChange={this.TablePageChange.bind(this)}
              pagination={this.state.pagination}
              rowKey="id"
            />
          </div>
        </div>
      </div>
    )
  }
Example #5
Source File: separator-component.jsx    From virtuoso-design-system with MIT License 6 votes vote down vote up
storiesOf('antd/breadcrumb', module).add('separator-component', () => 
  <Breadcrumb separator="">
    <Breadcrumb.Item>Location</Breadcrumb.Item>
    <Breadcrumb.Separator>:</Breadcrumb.Separator>
    <Breadcrumb.Item href="">Application Center</Breadcrumb.Item>
    <Breadcrumb.Separator />
    <Breadcrumb.Item href="">Application List</Breadcrumb.Item>
    <Breadcrumb.Separator />
    <Breadcrumb.Item>An Application</Breadcrumb.Item>
  </Breadcrumb>,
  { docs: { page: () => (<><h1 id="enus">en-US</h1>
<p>The separator can be customized by setting the separator property: <code>Breadcrumb.Separator</code>.</p></>) } });
Example #6
Source File: index.jsx    From react-admin-template with MIT License 6 votes vote down vote up
function index() {
  //获取path
  let location = useLocation()
  let pathNameArr = location.pathname.substring(1).split('/')
  useEffect(() => {}, [location])

  return (
    <div className={'ml-1'}>
      <Breadcrumb>
        {pathNameArr.map((mItem) => {
          return (
            <Breadcrumb.Item key={mItem}>
              {mItem}
              {/*<a href="">{mItem}</a>*/}
            </Breadcrumb.Item>
          )
        })}
      </Breadcrumb>
    </div>
  )
}
Example #7
Source File: index.js    From aircon with GNU General Public License v3.0 6 votes vote down vote up
CustomBreadcrumb = (props) => (
  <Breadcrumb style={{ marginBottom: 16 }}>
    {props.arr &&
      props.arr.map((item) => {
        if (typeof item === 'object') {
          return (
            <Breadcrumb.Item key={item.title}>
              <Link to={item.to}>{item.title}</Link>
            </Breadcrumb.Item>
          );
        } else {
          return <Breadcrumb.Item key={item}>{item}</Breadcrumb.Item>;
        }
      })}
  </Breadcrumb>
)
Example #8
Source File: withIcon.jsx    From virtuoso-design-system with MIT License 6 votes vote down vote up
storiesOf('antd/breadcrumb', module).add('withIcon', () => 
  <Breadcrumb>
    <Breadcrumb.Item href="">
      <HomeOutlined />
    </Breadcrumb.Item>
    <Breadcrumb.Item href="">
      <UserOutlined />
      <span>Application List</span>
    </Breadcrumb.Item>
    <Breadcrumb.Item>Application</Breadcrumb.Item>
  </Breadcrumb>,
  { docs: { page: () => (<><h1 id="enus">en-US</h1>
<p>The icon should be placed in front of the text.</p></>) } });
Example #9
Source File: CoursePageBreadcrumbs.jsx    From ResoBin with MIT License 6 votes vote down vote up
CoursePageBreadcrumbs = ({ courseTitle }) => {
  const { isMobileS } = useResponsive()
  if (isMobileS) return null

  return (
    <StyledBreadcrumb separator={<StyledIcon Icon={ChevronRight} />}>
      <Breadcrumb.Item>
        <Link to="/">
          <StyledIcon Icon={Home} />
          <span>Home</span>
        </Link>
      </Breadcrumb.Item>

      <Breadcrumb.Item>
        <Link to="/courses">
          <StyledIcon Icon={BookOpen} />
          <span>Courses</span>
        </Link>
      </Breadcrumb.Item>

      <Breadcrumb.Item>
        <span>{courseTitle}</span>
      </Breadcrumb.Item>
    </StyledBreadcrumb>
  )
}
Example #10
Source File: index.js    From discern with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
CustomBreadcrumb = (props)=>(
  <Breadcrumb style={{marginBottom:16}}>
    <Breadcrumb.Item><Link to='/home'>首页</Link></Breadcrumb.Item>
    {props.arr && props.arr.map(item=>{
      if ((typeof item) === 'object'){
        return <Breadcrumb.Item key={item.title}><Link to={item.to}>{item.title}</Link></Breadcrumb.Item>
      } else {
        return <Breadcrumb.Item key={item}>{item}</Breadcrumb.Item>
      }
    })}
  </Breadcrumb>
)
Example #11
Source File: App.js    From QiskitFlow with Apache License 2.0 6 votes vote down vote up
App = () => (
  <Layout>
    <Header style={{ position: 'fixed', zIndex: 1, width: '100%' }}>
      <div className="logo" />
      <Menu theme="light" mode="horizontal" defaultSelectedKeys={['1']}>
        <Menu.Item key="logo"><img className="ant-menu-item" src={"qiskitflow_logo.png"}/></Menu.Item>
        <Menu.Item key="1"> 
          Experiments
        </Menu.Item>
      </Menu>
    </Header>
    <Content className="site-layout" style={{ padding: '0 50px', marginTop: 64 }}>
      <Breadcrumb style={{ margin: '16px 0' }}>
        <Breadcrumb.Item>QiskitFlow</Breadcrumb.Item>
        <Breadcrumb.Item>Experiments</Breadcrumb.Item>
      </Breadcrumb>
      <div className="site-layout-background" style={{ padding: 24, minHeight: "80vh", backgroundColor: "white" }}>
       <ExperimentsPage />
      </div>
    </Content>
    <Footer style={{ textAlign: 'center' }}>QiskitFlow ©2020 </Footer>
  </Layout>
)
Example #12
Source File: index.js    From mixbox with GNU General Public License v3.0 6 votes vote down vote up
render() {
        const {theme} = this.props;
        return (
            <div styleName="breadcrumb" className={`system-breadcrumb-${theme}`}>
                <Breadcrumb>
                    {this.renderItems()}
                </Breadcrumb>
            </div>
        );
    }
Example #13
Source File: index.js    From gobench with Apache License 2.0 6 votes vote down vote up
render() {
    return (
      <div>
        <h5 className="mb-3">
          <strong>Basic</strong>
        </h5>
        <div className="mb-5">
          <Breadcrumb>
            <Breadcrumb.Item>Home</Breadcrumb.Item>
            <Breadcrumb.Item>
              <a href="">Application Center</a>
            </Breadcrumb.Item>
            <Breadcrumb.Item>
              <a href="">Application List</a>
            </Breadcrumb.Item>
            <Breadcrumb.Item>An Application</Breadcrumb.Item>
          </Breadcrumb>
        </div>
        <h5 className="mb-3">
          <strong>With an Icon</strong>
        </h5>
        <div className="mb-5">
          <Breadcrumb>
            <Breadcrumb.Item href="">
              <HomeOutlined />
            </Breadcrumb.Item>
            <Breadcrumb.Item href="">
              <UserOutlined />
              <span>Application List</span>
            </Breadcrumb.Item>
            <Breadcrumb.Item>Application</Breadcrumb.Item>
          </Breadcrumb>
        </div>
      </div>
    )
  }
Example #14
Source File: Breadcrumb.js    From YApi-X with MIT License 6 votes vote down vote up
render() {
    const getItem = this.props.breadcrumb.map((item, index) => {
      if (item.href) {
        return (
          <Breadcrumb.Item key={index}>
            <Link to={item.href}>{item.name}</Link>
          </Breadcrumb.Item>
        );
      } else {
        return <Breadcrumb.Item key={index}>{item.name}</Breadcrumb.Item>;
      }
    });
    return (
      <div className="breadcrumb-container">
        <Breadcrumb>{getItem}</Breadcrumb>
      </div>
    );
  }
Example #15
Source File: index.jsx    From react-antd-admin-template with MIT License 6 votes vote down vote up
BreadCrumb = (props) => {
  const { location } = props;
  const { pathname } = location;
  let path = getPath(menuList, pathname);
  const first = path && path[0];
  if (first && first.title.trim() !== "首页") {
    path = [{ title: "首页", path: "/dashboard" }].concat(path);
  }
  return (
    <div className="Breadcrumb-container">
      <Breadcrumb>
        {path &&
          path.map((item) =>
            item.title === "首页" ? (
              <Breadcrumb.Item key={item.path}>
                <a href={`#${item.path}`}>{item.title}</a>
              </Breadcrumb.Item>
            ) : (
              <Breadcrumb.Item key={item.path}>{item.title}</Breadcrumb.Item>
            )
          )}
      </Breadcrumb>
    </div>
  );
}
Example #16
Source File: top.jsx    From virtuoso-design-system with MIT License 6 votes vote down vote up
storiesOf('antd/layout', module).add('top', () => 
  <Layout className="layout">
    <Header>
      <div className="logo" />
      <Menu theme="dark" mode="horizontal" defaultSelectedKeys={['2']}>
        {new Array(15).fill(null).map((_, index) => {
          const key = index + 1;
          return <Menu.Item key={key}>{`nav ${key}`}</Menu.Item>;
        })}
      </Menu>
    </Header>
    <Content style={{ padding: '0 50px' }}>
      <Breadcrumb style={{ margin: '16px 0' }}>
        <Breadcrumb.Item>Home</Breadcrumb.Item>
        <Breadcrumb.Item>List</Breadcrumb.Item>
        <Breadcrumb.Item>App</Breadcrumb.Item>
      </Breadcrumb>
      <div className="site-layout-content">Content</div>
    </Content>
    <Footer style={{ textAlign: 'center' }}>Ant Design ©2018 Created by Ant UED</Footer>
  </Layout>,
  { docs: { page: () => (<><h1 id="enus">en-US</h1>
<p>The most basic "header-content-footer" layout.</p>
<p>Generally, the mainnav is placed at the top of the page, and includes the logo, the first level navigation, and the secondary menu (users, settings, notifications) from left to right in it. We always put contents in a fixed size navigation (eg: <code>1200px</code>), the layout of the whole page is stable, it's not affected by viewing area.</p>
<p>Top-bottom structure is conform with the top-bottom viewing habit, it's a classical navigation pattern of websites. This pattern demonstrates efficiency in the main workarea, while using some vertical space. And because the horizontal space of the navigation is limited, this pattern is not suitable for cases when the first level navigation contains many elements or links.</p></>) } });
Example #17
Source File: index.js    From mixbox with GNU General Public License v3.0 5 votes vote down vote up
Item = Breadcrumb.Item
Example #18
Source File: side.jsx    From virtuoso-design-system with MIT License 5 votes vote down vote up
render() {
    const { collapsed } = this.state;
    return (
      <Layout style={{ minHeight: '100vh' }}>
        <Sider collapsible collapsed={collapsed} onCollapse={this.onCollapse}>
          <div className="logo" />
          <Menu theme="dark" defaultSelectedKeys={['1']} mode="inline">
            <Menu.Item key="1" icon={<PieChartOutlined />}>
              Option 1
            </Menu.Item>
            <Menu.Item key="2" icon={<DesktopOutlined />}>
              Option 2
            </Menu.Item>
            <SubMenu key="sub1" icon={<UserOutlined />} title="User">
              <Menu.Item key="3">Tom</Menu.Item>
              <Menu.Item key="4">Bill</Menu.Item>
              <Menu.Item key="5">Alex</Menu.Item>
            </SubMenu>
            <SubMenu key="sub2" icon={<TeamOutlined />} title="Team">
              <Menu.Item key="6">Team 1</Menu.Item>
              <Menu.Item key="8">Team 2</Menu.Item>
            </SubMenu>
            <Menu.Item key="9" icon={<FileOutlined />}>
              Files
            </Menu.Item>
          </Menu>
        </Sider>
        <Layout className="site-layout">
          <Header className="site-layout-background" style={{ padding: 0 }} />
          <Content style={{ margin: '0 16px' }}>
            <Breadcrumb style={{ margin: '16px 0' }}>
              <Breadcrumb.Item>User</Breadcrumb.Item>
              <Breadcrumb.Item>Bill</Breadcrumb.Item>
            </Breadcrumb>
            <div className="site-layout-background" style={{ padding: 24, minHeight: 360 }}>
              Bill is a cat.
            </div>
          </Content>
          <Footer style={{ textAlign: 'center' }}>Ant Design ©2018 Created by Ant UED</Footer>
        </Layout>
      </Layout>
    );
  }
Example #19
Source File: UserRole.js    From kite-admin with MIT License 4 votes vote down vote up
render () {
    const { stateUserRole, stateUserAuthority } = this.props
    const { loading, is_create, user_role_type_list } = this.state
    const { getFieldDecorator } = this.props.form
    const itemLayout = {
      labelCol: {
        xs: { span: 24 },
        sm: { span: 5 }
      },
      wrapperCol: {
        xs: { span: 24 },
        sm: { span: 19 }
      }
    }
    const tailItemLayout = {
      wrapperCol: {
        xs: {
          span: 24,
          offset: 0
        },
        sm: {
          span: 16,
          offset: 5
        }
      }
    }

    return (
      <div className="layout-main">
        <div className="layout-main-title">
          <Breadcrumb>
            <Breadcrumb.Item href="#/manager/index">
              <Icon type="home" />
            </Breadcrumb.Item>
            <Breadcrumb.Item href="#/manager/index">
              <span>主页</span>
            </Breadcrumb.Item>
            <Breadcrumb.Item href="#">
              <span>用户管理</span>
            </Breadcrumb.Item>
            <Breadcrumb.Item>用户角色</Breadcrumb.Item>
          </Breadcrumb>
        </div>

        <div className="layout-nav-btn">
          <button
            className="btn btn-danger"
            icon="plus"
            type="primary"
            onClick={() => this.showModal(0)}
          >
            创建用户角色
          </button>
        </div>

        <div className="card user-role">
          <div className="card-body">
            <Modal
              footer={null}
              onCancel={() => {
                this.setState({
                  modal_visible_edit: false
                })
              }}
              title="填写角色"
              visible={this.state.modal_visible_edit}
            >
              <Form className="from-view" onSubmit={this.handleSubmit}>
                <Form.Item {...itemLayout} label="角色名">
                  {getFieldDecorator('user_role_name', {
                    rules: [
                      {
                        required: true,
                        message: '请输入角色名!',
                        whitespace: true
                      }
                    ]
                  })(<Input placeholder="角色名" />)}
                </Form.Item>

                <Form.Item {...itemLayout} hasFeedback label="角色类型">
                  {getFieldDecorator('user_role_type', {
                    rules: [
                      {
                        required: true,
                        message: '请选择角色类型!'
                      }
                    ]
                  })(
                    <Select placeholder="请选择角色类型!">
                      {user_role_type_list.map((item, key) => (
                        <Option value={key} key={key}>
                          {item}
                        </Option>
                      ))}
                    </Select>
                  )}
                </Form.Item>

                <Form.Item {...itemLayout} label="角色名图标">
                  {getFieldDecorator('user_role_icon', {
                    rules: [
                      {
                        message: '请输入角色名图标!',
                        whitespace: true
                      }
                    ]
                  })(<Input placeholder="角色名图标" />)}
                </Form.Item>

                <Form.Item {...itemLayout} hasFeedback label="角色描述">
                  {getFieldDecorator('user_role_description', {
                    rules: [
                      {
                        required: true,
                        message: '请输入角色描述'
                      }
                    ]
                  })(<TextArea placeholder="请输入角色描述" type="text" />)}
                </Form.Item>

                <Form.Item {...itemLayout} label="是否显示">
                  {getFieldDecorator('is_show', { valuePropName: 'checked' })(
                    <Switch />
                  )}
                </Form.Item>

                <Form.Item {...itemLayout} label="是否有效">
                  {getFieldDecorator('enable', { valuePropName: 'checked' })(
                    <Switch />
                  )}
                </Form.Item>

                <Form.Item {...tailItemLayout}>
                  <Button
                    className="register-btn"
                    htmlType="submit"
                    type="primary"
                  >
                    {is_create ? '创建角色' : '更新'}
                  </Button>
                </Form.Item>
              </Form>
            </Modal>

            <Modal
              footer={null}
              onCancel={() => {
                this.setState({
                  visible_set_authority_modal: false
                })
              }}
              title="设置权限"
              visible={this.state.visible_set_authority_modal}
            >
              <Tree
                checkable
                checkedKeys={this.state.role_authority_list}
                onCheck={this.onCheck}
                defaultExpandAll={true}
                ref="tree"
                showLine
              >
                {this.renderTreeNodes(stateUserAuthority.user_authority_list)}
              </Tree>
              <div className="admin-role-foot">
                <Button
                  icon="save"
                  onClick={() => {
                    this.fetch_set_user_role_authority()
                  }}
                  type="primary"
                >
                  确定
                </Button>
                <Button
                  onClick={() => {
                    this.setState({
                      visible_set_authority_modal: false
                    })
                  }}
                >
                  取消
                </Button>
              </div>
            </Modal>

            <Table
              columns={this.state.columns}
              dataSource={stateUserRole.list}
              loading={loading}
              onChange={this.TablePageChange.bind(this)}
              pagination={this.state.pagination}
              rowKey="user_role_id"
            />
          </div>
        </div>
      </div>
    )
  }
Example #20
Source File: PoolInfo.js    From acy-dex-interface with MIT License 4 votes vote down vote up
function MarketPoolInfo(props) {
  let { address } = useParams();
  //const { chainId: walletChainId } = useWeb3React();
  const { account, marketNetwork: walletChainId } = useConstantLoader();

  const connectWalletByLocalStorage = useConnectWallet();
  useEffect(() => {
    if(!account){
      connectWalletByLocalStorage();
    }
  }, [account]);

  const [poolData, setPoolData] = useState({});
  const [graphTabIndex, setGraphTabIndex] = useState(0);
  const [isWatchlist, setIsWatchlist] = useState(false);

  const [selectChartDataVol, setSelectChartDataVol] = useState(
    graphSampleData[graphSampleData.length - 1][1]
  );
  const [selectChartIndexVol, setSelectChartIndexVol] = useState(graphSampleData.length - 1);

  const [selectChartDataTvl, setSelectChartDataTvl] = useState(
    graphSampleData[graphSampleData.length - 1][1]
  );
  const [selectChartIndexTvl, setSelectChartIndexTvl] = useState(graphSampleData.length - 1);

  const [selectChartDataLiq, setSelectChartDataLiq] = useState(
    graphSampleData[graphSampleData.length - 1][1]
  );
  const [selectChartIndexLiq, setSelectChartIndexLiq] = useState(graphSampleData.length - 1);

  // additional datas
  const [token0Price, setToken0Price] = useState(0);
  const [token1Price, setToken1Price] = useState(0);
  const [reserve0, setReserve0] = useState(0);
  const [reserve1, setReserve1] = useState(0);
  const [dayDatas, setDayDatas] = useState({});
  const [volume24h, setVolume24h] = useState(0);
  const [tvl, setTvl] = useState(0);
  const [volChange, setVolChange] = useState(0);
  const [tvlChange, setTvlChange] = useState(0);
  const [tx, setTx] = useState(null);
  const [token0Address, setToken0Address] = useState('');
  const [token1Address, setToken1Address] = useState('');
  const [pairArray,setPairArray] = useState({});

  // const refContainer = useRef();
  // refContainer.current = data;

  const navHistory = useHistory();

  function switchChart(dest) {
    setGraphTabIndex(dest);
  }

  const toggleWatchlist = data => {
    let oldArray = watchlistManagerPool.getData();
      if (oldArray.includes(data)) {
        oldArray = oldArray.filter(item => item != data);
      } else {
        oldArray.push(data);
      }
      watchlistManagerPool.saveData(oldArray);
      updateWatchlistStatus();
  };

  const updateWatchlistStatus = () => {
    let data = watchlistManagerPool.getData();
    if (data.includes(address))
      setIsWatchlist(true);
    else setIsWatchlist(false);
  };

  useEffect(() => {
    if (!address || !walletChainId) return;
    console.log(">>> start fetching data")

    // extract the pool day datas
    fetchPoolDayDataForPair(address).then(data => {

      console.log("fetching pool day INFO", data);
      let newData = [...data].reverse();
      console.log("printing", newData);
      data = newData;

      // extract graph datas
      let length = data.length;
      let volumeGraphData = [];
      let tvlGraphData = [];

      console.log(data);

      for (let i = 0; i < length; i++) {
        // new Date(item.date * 1000).toLocaleDateString('en-CA')
        let dataDate = new Date(data[i].date * 1000).toLocaleDateString('en-CA');

        volumeGraphData.push([dataDate, parseFloat(data[i].dailyVolumeUSD)]);
        tvlGraphData.push([dataDate, parseFloat(data[i].reserveUSD)]);
      }

      // set the graphdata
      setDayDatas({
        volumeDayData: volumeGraphData,
        tvlDayData: tvlGraphData,
      });

      console.log('VOLUME GRAPH', volumeGraphData);

      setSelectChartDataVol(abbrNumber(volumeGraphData[length - 1][1]));
      setSelectChartIndexVol(length - 1);
      setSelectChartDataTvl(abbrNumber(tvlGraphData[length - 1][1]));
      setSelectChartIndexTvl(length - 1);


      setVolume24h(parseFloat(data[data.length-1].dailyVolumeUSD));
      setTvl(parseFloat(data[data.length-1].reserveUSD));
      if (data.length > 1) {
        setTvlChange(calcPercentChange(parseFloat(data[data.length-1].reserveUSD),parseFloat(data[data.length-2].reserveUSD)));
        setVolChange(calcPercentChange(parseFloat(data[data.length-1].dailyVolumeUSD),parseFloat(data[data.length-2].dailyVolumeUSD)));
      }
    });

    let snapshotPromise = [];
    let volumeChanges = [0, 0, 0];
    let reserveChanges = [0, 0];
    let todayTimestamp = Math.floor(Date.now() / 1000);

    // extract the pair data
    snapshotPromise.push(
      fetchPoolInfo(address).then(pairInfo => {
        console.log("fetching pool INFOO: ", pairInfo);

        if(pairInfo){
        setPoolData({
          coin1: pairInfo.token0.symbol,
          coin2: pairInfo.token1.symbol,
          logoURI1 : pairInfo.token0.logoURI,
          logoURI2 : pairInfo.token1.logoURI,
          address: address,
          percent: 0,
          tvl: 0,
          volume24h: 0,
          volume7d: 0,
          price: 0,
        });

        setPairArray({
          token0 : pairInfo.token0.symbol,
          token0 : pairInfo.token1.symbol
        })

        volumeChanges[0] = parseFloat(pairInfo.untrackedVolumeUSD);
        reserveChanges[0] = parseFloat(pairInfo.reserveUSD);

        setToken0Price(parseFloat(pairInfo.token0Price));
        setToken1Price(parseFloat(pairInfo.token1Price));
        setToken0Address(pairInfo.token0.id);
        setToken1Address(pairInfo.token1.id);
        setReserve0(parseFloat(pairInfo.reserve0));
        setReserve1(parseFloat(pairInfo.reserve1));
      }
      }
      )
      
    );

    // extract snapshot form a day ago
    // snapshotPromise.push(
    //   fetchPoolInfo(address).then(pairInfo => {
    //     if(pairInfo){
    //     volumeChanges[1] = parseFloat(pairInfo.untrackedVolumeUSD);
    //     reserveChanges[1] = parseFloat(pairInfo.reserveUSD);
    //     }
    //   })
    // );

    // snapshotPromise.push(
    //   fetchPoolInfo(address).then(pairInfo => {
    //     volumeChanges[2] = parseFloat(pairInfo.untrackedVolumeUSD);
    //   })
    // );

    // Promise.all(snapshotPromise).then(() => {
    //   setVolume24h(volumeChanges[0] - volumeChanges[1]);
    //   setVolChange(
    //     calcPercentChange(volumeChanges[0] - volumeChanges[1], volumeChanges[1] - volumeChanges[2])
    //   );

    //   setTvl(reserveChanges[0]);
    //   setTvlChange(calcPercentChange(reserveChanges[0], reserveChanges[1]));
    // });

    // fetch transactions for this pool
    // console.log(pairArray);
    

    // set the watchlists
    updateWatchlistStatus();
  }, [walletChainId]);

  useEffect(() => {

    if(poolData.coin1 && poolData.coin2){
      fetchTransactionsForPair(poolData.coin1, poolData.coin2).then(transactions => {
        console.log('Pool TRANSAC', transactions);
        setTx(transactions);
      });
    }

  },[poolData]);

  const selectGraph = pt => {
    let index = ['Volume', 'TVL', 'Liquidity'].indexOf(pt);
    switchChart(index);
  };

  const redirectToLiq = useCallback(() => navHistory.push('/liquidity'), [history]);
  const redirectToEx = useCallback(() => navHistory.push('/exchange'), [history]);
  const redirectToToken = tokenAddress => {
    navHistory.push(`/market/info/token/${tokenAddress}`);
  }

  return (
    <div className={styles.marketRoot}>
      <MarketSearchBar
        dataSourceCoin={dataSourceCoin}
        dataSourcePool={dataSourcePool}
        onRefreshWatchlist={() => {
          updateWatchlistStatus();
        }}
      />
      <div className={styles.infoHeader}>
        <Breadcrumb
          separator={<span style={{ color: '#b5b5b6' }}>&gt;</span>}
          style={{ marginBottom: '20px', color: '#b5b5b6' }}
        >
          <Breadcrumb.Item>
            <Link style={{ color: '#b5b5b6' }} to="/market">
              Overview
            </Link>
          </Breadcrumb.Item>
          <Breadcrumb.Item>
            <Link style={{ color: '#b5b5b6' }} to="/market/list/pool">
              Pools
            </Link>
          </Breadcrumb.Item>
          <Breadcrumb.Item style={{ fontWeight: 'bold' }}>
            {poolData.coin1 ? `${poolData.coin1}/${poolData.coin2}` : <Icon type="loading" />}
          </Breadcrumb.Item>
        </Breadcrumb>
        <div className={styles.rightButton}>
          {poolData.coin1 ? (
            <>
              <AcyIcon
                name={isWatchlist ? 'star_active' : 'star'}
                width={16}
                style={{ marginLeft: '10px' }}
                onClick={() => toggleWatchlist(address)}
              />
              <AcyIcon
                name="redirect"
                style={{ marginLeft: '10px' }}
                width={16}
                onClick={() => {
                  openInNewTab(`${SCAN_URL_PREFIX()}token/${poolData.address}`);
                }}
              />
            </>
          ) : (
            <Icon type="loading" />
          )}
        </div>
      </div>

      {/* <div>
        <div className={styles.rightButton} />
      </div> */}
      {Object.keys(poolData).length === 0 ? (
        <Spin />
      ) : (
        <>
          <div
            style={{
              display: 'flex',
              justifyContent: 'space-between',
              alignItems: 'center',
              flexWrap: 'wrap',
            }}
          >
            <div className={styles.contentInfo}>
              <div style={{ display: 'flex', alignItems: 'center' }}>
                <AcyTokenIcon symbol={poolData.logoURI1} width={36} height={36} />
                <AcyTokenIcon symbol={poolData.logoURI2} width={36} height={36} />
                <span
                  style={{ fontSize: '26px', fontWeight: 'bold', marginLeft: '10px', color: "white" }}
                  className={styles.coinName}
                >
                  {poolData.coin1}{' '}/{' '}{poolData.coin2}
                </span>
                {/* <div
              className={styles.percentBadge}
              style={{ marginLeft: '20px', fontSize: '18px', lineHeight: '20px' }}
            >
              {poolData.percent} %
            </div> */}
              </div>
            </div>
          </div>
          <div className={styles.exchangeValuePadder}>
            <div className={styles.exchangeValueWrapper}>
              <div
                className={styles.exchangeValueCard}
                onClick={() => redirectToToken(token0Address)}
              >
                <AcyTokenIcon symbol={poolData.logoURI1} width={18} />
                <strong style={{ marginLeft: '7px' }}>
                  1 {poolData.coin1} = {abbrNumber(token0Price/token1Price)} {poolData.coin2}
                </strong>
              </div>
              <div className={styles.exchangeValueRight}>
                <div
                  className={styles.exchangeValueCard}
                  style={{
                    width: isDesktop() ? '30%' : '100%',
                    marginTop: isDesktop() ? 0 : '10px',
                    marginBottom: isDesktop() ? 0 : '10px',
                  }}
                  onClick={() => redirectToToken(token1Address)}
                >
                  <AcyTokenIcon symbol={poolData.logoURI2} width={18} />
                  <strong style={{ marginLeft: '7px' }}>
                    1 {poolData.coin2} = {abbrNumber(token1Price/token0Price)} {poolData.coin1}
                  </strong>
                </div>
                <div className={styles.contentCta}>
                  <div className={styles.ctaButton}>
                    <AcySmallButton
                      color="#2e3032"
                      borderColor="#2e3032"
                      borderRadius="15px"
                      padding="10px"
                      onClick={redirectToLiq}
                    >
                      <AcyIcon name="addlq" width={16} style={{ marginRight: '10px' }} />
                      Add Liquidity
                    </AcySmallButton>
                  </div>
                  <div className={styles.ctaButton}>
                    <AcySmallButton
                      color="#1e5d91"
                      borderColor="#1e5d91"
                      borderRadius="15px"
                      padding="10px"
                      onClick={redirectToEx}
                    >
                      Trade
                    </AcySmallButton>
                  </div>
                </div>
              </div>
            </div>
          </div>
          <div style={{ display: 'flex', flexWrap: 'wrap', justifyContent: 'space-between' }}>
            <div className={styles.contentStats}>
              <div className={styles.statEntry}>
                <strong>Total tokens locked</strong>
                <div className={styles.tokenLockEntry}>
                  <div className={styles.tokenLockName}>
                    {/* change data later */}
                    <AcyTokenIcon symbol={poolData.logoURI1} width={18} />
                    <div style={{ marginLeft: 10 }}>{poolData.coin1}</div>
                  </div>
                  <div>{abbrNumber(reserve0)}</div>
                </div>
                <div className={styles.tokenLockEntry}>
                  <div className={styles.tokenLockName}>
                    {/* change data later */}
                    <AcyTokenIcon symbol={poolData.logoURI2} width={18} />
                    <div style={{ marginLeft: 10 }}>{poolData.coin2}</div>
                  </div>
                  <div>{abbrNumber(reserve1)}</div>
                </div>
              </div>
              <div className={styles.statEntry}>
                <div className={styles.statEntryName}>TVL</div>
                <div className={styles.statEntryValue}>$ {abbrNumber(tvl)}</div>
                <div
                  className={styles.statEntryChange}
                  style={{ color: tvlChange >= 0 ? 'greenyellow' : 'red' }}
                >
                  {!isNaN(tvlChange) ? `${tvlChange.toFixed(2)} %` : '0.00 %'}
                </div>
              </div>
              <div className={styles.statEntry}>
                <div className={styles.statEntryName}>24h Trading Vol</div>
                <div className={styles.statEntryValue}>$ {abbrNumber(volume24h)}</div>
                <div
                  className={styles.statEntryChange}
                  style={{ color: volChange >= 0 ? 'greenyellow' : 'red' }}
                >
                  {' '}
                  {!isNaN(volChange) ? `${volChange.toFixed(2)} %` : '0.00 %'}
                </div>
              </div>
              <div className={styles.statEntry}>
                <div className={styles.statEntryName}>24h Fees</div>
                <div className={styles.statEntryValue}>$ {abbrNumber(volume24h * FEE_PERCENT)}</div>
                <div className={styles.statEntryChange} style={{ visibility: 'hidden' }}>
                  00{' '}
                </div>
              </div>
            </div>
            {Object.keys(dayDatas).length === 0 ? (
              <Spin />
            ) : (
              <div className={styles.contentCharts}>
                <div className={styles.contentChartsHeader}>
                  {graphTabIndex == 0 && (
                    <div className={styles.contentChartsIndicator}>
                      <div className={styles.chartIndicatorValue}>$ {selectChartDataVol}</div>
                      <div className={styles.chartIndicatorTime}>
                        {dayDatas.length && (dayDatas.volumeDayData[dayDatas.length-1][0])}
                      </div>
                    </div>
                  )}
                  {graphTabIndex == 1 && (
                    <div className={styles.contentChartsIndicator}>
                      <div className={styles.chartIndicatorValue}>$ {selectChartDataTvl}</div>
                      <div className={styles.chartIndicatorTime}>
                        {dayDatas.length && (dayDatas.tvlDayData[dayDatas.length-1][0])}
                      </div>
                    </div>
                  )}
                  {/* {graphTabIndex == 2 && (
            <div className={styles.contentChartsIndicator}>
              <div className={styles.chartIndicatorValue}>$ {selectChartDataLiq}</div>
              <div className={styles.chartIndicatorTime}>
                {graphSampleData[selectChartIndexLiq][0]}
              </div>
            </div>
          )} */}
                  <div className={styles.contentChartsSelector}>
                    <AcyPeriodTime onhandPeriodTimeChoose={selectGraph} times={['Volume', 'TVL']} />
                    {/* <AcySmallButton
              color={graphTabIndex == 0 ? '#1b1b1c' : '#757579'}
              textColor="white"
              borderColor="#757579"
              borderRadius="15px 0 0 15px"
              padding="2px 5px"
              onClick={() => switchChart(0)}
              id="0"
            >
              Volume
            </AcySmallButton>
            <AcySmallButton
              color={graphTabIndex == 1 ? '#1b1b1c' : '#757579'}
              textColor="white"
              borderColor="#757579"
              borderRadius="0 0 0 0"
              padding="2px 5px"
              onClick={() => switchChart(1)}
              id="1"
            >
              TVL
            </AcySmallButton>
            <AcySmallButton
              color={graphTabIndex == 2 ? '#1b1b1c' : '#757579'}
              textColor="white"
              borderColor="#757579"
              borderRadius="0 15px 15px 0"
              padding="2px 5px"
              onClick={() => switchChart(2)}
              id="2"
            >
              Liquidity
            </AcySmallButton> */}
                  </div>
                </div>
                <div className={styles.contentChartsBody}>
                  {graphTabIndex == 0 && (
                    <div className={styles.contentChartWrapper}>
                      <AcyBarChart
                        data={dayDatas.volumeDayData}
                        barColor="#1e5d91"
                        showXAxis
                        onHover={(data, index) => {
                          setSelectChartDataVol(abbrNumber(data));
                          setSelectChartIndexVol(index);
                        }}
                      />
                    </div>
                  )}
                  {graphTabIndex == 1 && (
                    <div className={styles.contentChartWrapper}>
                      <AcyLineChart
                        showXAxis={true}
                        data={dayDatas.tvlDayData}
                        showGradient={true}
                        lineColor="#1e5d91"
                        bgColor="#00000000"
                        onHover={(data, index) => {
                          setSelectChartDataTvl(abbrNumber(data));
                          setSelectChartIndexTvl(index);
                        }}
                      />
                    </div>
                  )}
                  {/* {graphTabIndex == 2 && (
                <div className={styles.contentChartWrapper}>
                  <AcyBarChart
                    backData={graphSampleData}
                    barColor="#1e5d91"
                    showXAxis
                    onHover={(data, index) => {
                      setSelectChartDataLiq(abbrNumber(data));
                      setSelectChartIndexLiq(index);
                    }}
                  />
                </div>
              )} */}
                </div>
              </div>
            )}
          </div>
          <h2>Transactions</h2>
          {!tx? (
         <Icon type="loading" />
           ) : (
           <TransactionTable dataSourceTransaction={tx} />
            )}
        </>
      )}

      <div style={{ height: '40px' }} />
    </div>
  );
}
Example #21
Source File: Dashboard.js    From Smart-Vehicle-Fleet-Manager with MIT License 4 votes vote down vote up
function Dashboard() {
  // Layout and Menu
  const { Content, Sider } = Layout;
  const { SubMenu } = Menu;

  // report an issue preventDefault
  const preventDefault = (event) => {
    event.preventDefault();
    window.location.href =
      "https://github.com/abhishekpatel946/Smart-Vehicle-Fleet-Manager/issues/new/choose";
  };

  // snakbar state
  const [vehicleAddSuccess, setvehicleAddSuccess] = React.useState(false);
  const [vehicleAddError, setvehicleAddError] = React.useState(false);
  const [maintainanceAddSuccess, setmaintainanceAddSuccess] = React.useState(
    false
  );
  const [maintainanceAddError, setmaintainanceAddError] = React.useState(false);
  const handleClose = (event, reason) => {
    if (reason === "clickaway") {
      return;
    }
    setvehicleAddSuccess(false);
    setvehicleAddError(false);
    setmaintainanceAddSuccess(false);
    setmaintainanceAddError(false);
  };

  // vehicleId & vehicleName for addVehicle
  const [vehicleNAME, setVehicleNAME] = useState("");
  const [vehicleID, setVehicleID] = useState("");

  // vehicleName, dateTime & cost for maintenace
  const [vehicleRegNumber, setVehicleRegNumber] = useState("");
  const [date, setDate] = useState(moment().toString());
  const [cost, setCost] = useState("");

  // set date
  const onDateChange = (val) => {
    setDate(val);
  };

  const [collapseState, setCollapseState] = useState(false);
  const onCollapse = (collapsed) => {
    setCollapseState({ collapsed });
  };

  // form onSubmit handler
  const submitHandler = (event) => {
    event.preventDefault();
    event.target.className += " was-validated";
  };

  // fetch vehicle model & regid
  // const [vehicleInfo, setVehicleInfo] = useState([]);
  // let vehicleModel = "";
  // let vehicleModelId = "";
  // db.collection("data")
  //   .doc("MP10ME7969")
  //   .get()
  //   .then((snapshot) => {
  //     const currentInfo = [];
  //     snapshot.forEach((doc) => {
  //       currentInfo.push(doc.data());
  //     });
  //     setVehicleInfo(currentInfo);
  //   });
  // vehicleInfo.forEach((data) => {
  //   vehicleModel = data.vehicleId;
  //   vehicleModelId = data.vehicleName;
  // });

  // fetch moduleState
  const [moduleState, setModuleState] = useState([]);
  let liveState = false;
  db.collection("data")
    .doc("MP10ME7969")
    .collection("module_state")
    .onSnapshot((docs) => {
      const currentState = [];
      docs.forEach((doc) => {
        currentState.push(doc.data());
      });
      setModuleState(currentState);
    });

  moduleState.forEach((data) => {
    liveState = data.state;
  });

  // form vehicleRegister submitHandler
  const vehicleRegister = (event) => {
    if (vehicleID && vehicleNAME) {
      // check if the doc are already available in the DB... then just give the warning to the user!

      // create a doc in DB with vehicleID and set it fields
      db.collection("data").doc(vehicleID).set({
        vehicleId: vehicleID,
        vehicleName: vehicleNAME,
      });

      // create a dummy collection for newly created vehicleID
      db.collection("data").doc(vehicleID).collection("fuel").doc().set({
        id: "0",
        amount: "0",
        timestamp: "0",
      });
      db.collection("data").doc(vehicleID).collection("fuel_refill").doc().set({
        id: "0",
        amount: "0",
        timestamp: "0",
      });
      db.collection("data")
        .doc(vehicleID)
        .collection("maintainance")
        .doc()
        .set({
          id: "0",
          amount: "0",
          timestamp: "0",
        });
      db.collection("data").doc(vehicleID).collection("overspeed").doc().set({
        id: "0",
        speed: "0",
        timestamp: "0",
      });
      db.collection("data").doc(vehicleID).collection("speed").doc().set({
        id: "0",
        speed: "0",
        timestamp: "0",
      });
      db.collection("data")
        .doc(vehicleID)
        .collection("accident_alert")
        .doc()
        .set({
          id: "0",
          accident: "0",
          geolocation_lat: "0",
          geolocation_long: "0",
          timestamp: "0",
        });
      db.collection("data")
        .doc(vehicleID)
        .collection("fuel_theft_alert")
        .doc()
        .set({
          id: "0",
          fuelTheft: "0",
          geolocation_lat: "0",
          geolocation_long: "0",
          timestamp: "0",
        });
      db.collection("data")
        .doc(vehicleID)
        .collection("module_state")
        .doc()
        .set({
          state: "0",
        });

      // success mgs for the all are right
      setvehicleAddError(false);
      setmaintainanceAddSuccess(false);
      setmaintainanceAddError(false);
      setvehicleAddSuccess(true);

      // set it to defualt to state
      setVehicleNAME("");
      setVehicleID("");
    } else {
      // alert("Both the fields are mandatory!!!");
      setvehicleAddSuccess(false);
      setmaintainanceAddSuccess(false);
      setmaintainanceAddError(false);
      setvehicleAddError(true);
    }
  };

  // from vehicleMaintenace submitHandler
  const addCost = (event) => {
    // store maintainance-cost into database
    db.collection("data")
      .doc(vehicleRegNumber)
      .collection("maintainance")
      .add({
        id: vehicleRegNumber,
        cose: cost,
        timestamp: date,
      })
      .then(function () {
        // success mgs for the all are right
        setvehicleAddSuccess(false);
        setvehicleAddError(false);
        setmaintainanceAddError(false);
        setmaintainanceAddSuccess(true);
      })
      .catch(function (error) {
        setvehicleAddSuccess(false);
        setvehicleAddError(false);
        setmaintainanceAddSuccess(false);
        setmaintainanceAddError(true);
      });
  };

  // render() {
  return (
    <Layout id="header">
      {/* Header Section */}
      <HeaderLayout className="header" />
      <Layout style={{ minHeight: "100vh" }}>
        <Sider
          collapsible
          collapsed={collapseState.collapsed}
          onCollapse={onCollapse}
        >
          <div className="logo" />
          <Menu
            theme="dark"
            defaultSelectedKeys={["stats"]}
            defaultOpenKeys={["track"]}
            mode="inline"
          >
            <Menu.Item key="stats" icon={<PieChartOutlined />}>
              Stats
            </Menu.Item>
            <SubMenu key="track" icon={<DesktopOutlined />} title="Track">
              <Menu.Item key="speed">
                <Link href="#speedSection">Speed</Link>
              </Menu.Item>
              <Menu.Item key="fuel">
                <Link href="#fuelSection">Fuel</Link>
              </Menu.Item>
              <Menu.Item key="fuel_refill">
                <Link href="#fuelRefillSection">Fuel Refill</Link>
              </Menu.Item>
              <Menu.Item key="overspeeding">
                <Link href="#overSpeedingSection">OverSpeeding</Link>
              </Menu.Item>
              <Menu.Item key="maintainance">
                <Link href="#maintainanceSection">Maintainance</Link>
              </Menu.Item>
            </SubMenu>
            <Menu.Item
              key="accidentAlert"
              icon={<NotificationsActiveOutlinedIcon />}
            >
              <Link href="#accidentAlertSection">Accident alert</Link>
            </Menu.Item>
            <Menu.Item
              key="fuelTheftAlert"
              icon={<NotificationImportantIcon />}
            >
              <Link href="#fuelTheftAlertSection">FuelTheft alert</Link>
            </Menu.Item>
            <Menu.Item key="addVehicle" icon={<LocalTaxiIcon />}>
              <Link href="#addVehicleSection">Add Vehicle</Link>
            </Menu.Item>
            <Menu.Item key="addMaintainance" icon={<PostAddIcon />}>
              <Link href="#addVehicleSection">Add Maintainance</Link>
            </Menu.Item>
            <Menu.Item key="reportIssue" icon={<ReportProblemOutlinedIcon />}>
              <Link
                href="https://github.com/abhishekpatel946/Smart-Vehicle-Fleet-Manager/issues/new/choose"
                onClick={preventDefault}
              >
                Report an issue
              </Link>
            </Menu.Item>
          </Menu>
        </Sider>

        {/* Breadcrum Naming */}
        <Layout className="site-layout">
          <Content style={{ margin: "0 16px" }}>
            <Breadcrumb style={{ margin: "16px 0" }}>
              <Breadcrumb.Item>User</Breadcrumb.Item>
              <Breadcrumb.Item>Dashboard</Breadcrumb.Item>
              <div>
                <p className="h6 text-left mb-1">
                  Status : {liveState ? "Active" : "Inactive"}
                  {/* {vehicleModel}
                  {vehicleModelId} */}
                </p>
              </div>
            </Breadcrumb>
            <div
              className="site-layout-background"
              style={{ padding: 24, minHeight: 560 }}
            >
              {/* Speed Section */}
              <Divider orientation="left" id="speedSection">
                Speed area
              </Divider>
              <MDBContainer>
                <SpeedLog />
              </MDBContainer>

              {/* Fuel Section */}
              <Divider orientation="left" id="fuelSection">
                Fuel area
              </Divider>
              <MDBContainer>
                <MDBRow>
                  <FuelLog />
                </MDBRow>
              </MDBContainer>

              {/* OverSpeeding Section */}
              <Divider orientation="left" id="overSpeedingSection">
                OverSpeeding area
              </Divider>
              <MDBContainer>
                <MDBRow>
                  <OverSpeedLog />
                </MDBRow>
              </MDBContainer>

              {/* Fuel Refill Section */}
              <Divider orientation="left" id="fuelRefillSection">
                Fuel Refill area
              </Divider>
              <MDBContainer>
                <MDBRow>
                  <FuelRefillLog />
                </MDBRow>
              </MDBContainer>

              {/* Maintainence Section */}
              <Divider orientation="left" id="maintainanceSection">
                Maintainance area
              </Divider>
              <MDBContainer>
                <MDBRow>
                  <MaintainenceLog />
                </MDBRow>
              </MDBContainer>

              {/* Accident Section */}
              <Divider orientation="left" id="accidentAlertSection">
                Accident Alert area
              </Divider>
              <MDBContainer>
                <MDBRow>
                  <AccidentAlert />
                </MDBRow>
              </MDBContainer>

              {/* FuelTheft Section */}
              <Divider orientation="left" id="fuelTheftAlertSection">
                FuelTheft Alert area
              </Divider>
              <MDBContainer>
                <MDBRow>
                  <FuelTheftAlert />
                </MDBRow>
              </MDBContainer>

              {/* addVehicle Section */}
              <Divider orientation="left" id="addVehicleSection">
                Add Vehicle
              </Divider>
              <MDBContainer>
                <MDBRow>
                  <MDBCol md="6">
                    <form
                      className="needs-validation"
                      onSubmit={submitHandler}
                      noValidate
                    >
                      <p className="h5 text-center mb-4">Register Vehicle</p>
                      <div className="grey-text">
                        <MDBInput
                          className="addVehicle_vehicleNAME"
                          name="vehicleNAME"
                          onChange={(event) =>
                            setVehicleNAME(event.target.value)
                          }
                          value={vehicleNAME}
                          label="Your vehicle name"
                          icon="car"
                          group
                          type="text"
                          validate
                          error="wrong"
                          success="right"
                          required
                        />
                        <MDBInput
                          className="addVehicle_vehicleID"
                          name="vehicleID"
                          onChange={(event) => setVehicleID(event.target.value)}
                          value={vehicleID}
                          label="Your vechile reg. number"
                          icon="registered"
                          group
                          type="text"
                          validate
                          error="wrong"
                          success="right"
                          required
                        />
                      </div>
                      <div className="text-center">
                        <MDBBtn outline type="submit" onClick={vehicleRegister}>
                          Register
                          <MDBIcon className="ml-1" />
                        </MDBBtn>
                      </div>
                    </form>
                  </MDBCol>
                  <MDBCol md="6">
                    <form
                      className="needs-validation"
                      onSubmit={submitHandler}
                      noValidate
                    >
                      <p className="h5 text-center mb-4">
                        Register Maintainance
                      </p>
                      <div className="grey-text">
                        <MDBInput
                          className="addVehicle_vehicleNAME"
                          name="vehicleName"
                          onChange={(event) =>
                            setVehicleRegNumber(event.target.value)
                          }
                          value={vehicleRegNumber}
                          label="Your vehicle Reg number"
                          icon="registered"
                          group
                          type="text"
                          validate
                          error="wrong"
                          success="right"
                          required
                        />
                        <div>
                          <MuiPickersUtilsProvider utils={DateFnsUtils}>
                            <KeyboardDatePicker
                              disableToolbar
                              fullWidth
                              variant="inline"
                              format="dd/MM/yyyy"
                              margin="normal"
                              id="date-picker-inline"
                              label="DD/MM/YYYY"
                              value={date}
                              onChange={onDateChange}
                              KeyboardButtonProps={{
                                "aria-label": "change date",
                              }}
                            />
                          </MuiPickersUtilsProvider>
                        </div>
                        <MDBInput
                          className="addVehicle_vehicleID"
                          name="cost"
                          onChange={(event) => setCost(event.target.value)}
                          value={cost}
                          label="Your mainatenace cost..."
                          icon="rupee-sign"
                          group
                          type="text"
                          validate
                          error="wrong"
                          success="right"
                          required
                        />
                      </div>
                      <div className="text-center">
                        <MDBBtn outline type="submit" onClick={addCost}>
                          Add Cost
                          <MDBIcon className="ml-1" />
                        </MDBBtn>
                      </div>
                    </form>
                  </MDBCol>
                </MDBRow>
              </MDBContainer>

              {/* back to top */}
              <Link href="#header">
                <Button
                  // ghost
                  icon={<NavigationIcon />}
                  style={{
                    float: "right",
                    margin: "auto 20px 10px 20px",
                  }}
                >
                  {" "}
                  Back to top{" "}
                </Button>
              </Link>

              {/* End */}
            </div>
          </Content>

          {/* snakbar notifiers */}
          <Snackbar
            open={vehicleAddSuccess}
            autoHideDuration={3000}
            onClose={handleClose}
          >
            <Alert onClose={handleClose} severity="success">
              Vehicle added successfully.
            </Alert>
          </Snackbar>
          <Snackbar
            open={vehicleAddError}
            autoHideDuration={3000}
            onClose={handleClose}
          >
            <Alert onClose={handleClose} severity="error">
              All the field's are mendatory!!!
            </Alert>
          </Snackbar>
          <Snackbar
            open={maintainanceAddSuccess}
            autoHideDuration={3000}
            onClose={handleClose}
          >
            <Alert onClose={handleClose} severity="success">
              Maintainance added successfully.
            </Alert>
          </Snackbar>
          <Snackbar
            open={maintainanceAddError}
            autoHideDuration={3000}
            onClose={handleClose}
          >
            <Alert onClose={handleClose} severity="error">
              All the field's are mendatory!!!
            </Alert>
          </Snackbar>

          {/* footer */}
          <FooterLayout />
        </Layout>
      </Layout>
    </Layout>
  );
}
Example #22
Source File: index.js    From AgileTC with Apache License 2.0 4 votes vote down vote up
render() {
    //this.props.match.params.iscore  0:需求case  3:执行记录详情
    const { match } = this.props;
    const { iscore, caseId, itemid } = match.params;
    const user = getCookies('username');
    const { recordDetail, casedetail } = this.state;
    let readOnly = false;
    let progressShow = false;
    let addFactor = false;
    if (iscore === '0' || iscore === '1') {
      readOnly = false;
      progressShow = false;
      addFactor = true;
    } else {
      readOnly = true;
      progressShow = true;
      addFactor = false;
    }
    return (
      <div style={{ position: 'relative', minHeight: '80vh' }}>
        <Breadcrumb style={{ marginBottom: 8, fontSize: 12 }}>
          <Breadcrumb.Item>
            <Link to="/case/caseList/1">
              {casedetail ? '用例' : '任务'}管理
            </Link>
          </Breadcrumb.Item>
          <Breadcrumb.Item>
            {casedetail ? '用例' : '任务'}详情:
            {recordDetail ? recordDetail.title : ''}
            {casedetail ? casedetail.title : ''}
          </Breadcrumb.Item>
        </Breadcrumb>
        <div
          style={{
            padding: 12,
            background: '#fff',
          }}
        >
          {(recordDetail && (
            <Row>
              <Col span={6} className="description-case elipsis-case">
                <Tooltip
                  title={recordDetail.description}
                  placement="bottomLeft"
                >
                  {recordDetail.description}
                </Tooltip>
              </Col>
              <Col span={1}></Col>

              <Col span={2} className="font-size-12">
                通过率: {recordDetail.passRate.toFixed(2) + '%'}
              </Col>
              <Col span={2} className="font-size-12">
                {' '}
                已测: {recordDetail.passCount + '/' + recordDetail.totalCount}
              </Col>
              <Col
                span={4}
                style={{ textAlign: 'center' }}
                className="progress"
              >
                <div>
                  {(
                    <Tooltip
                      title={`通过:${recordDetail.successCount} (${(
                        (recordDetail.successCount / recordDetail.totalCount) *
                        100
                      ).toFixed(2)}%)`}
                      className="font-size-12"
                    >
                      <div
                        className="div-wrap"
                        style={{
                          width: `${(recordDetail.successCount /
                            recordDetail.totalCount) *
                            100}%`,
                          backgroundColor: '#61C663',
                        }}
                      >
                        <span></span>
                      </div>
                    </Tooltip>
                  ) || null}
                  {(recordDetail.blockCount > 0 && (
                    <Tooltip
                      title={`阻塞:${recordDetail.blockCount} (${(
                        (recordDetail.blockCount / recordDetail.totalCount) *
                        100
                      ).toFixed(2)}%)`}
                      className="font-size-12"
                    >
                      <div
                        className="div-wrap"
                        style={{
                          width: `${(recordDetail.blockCount /
                            recordDetail.totalCount) *
                            100}%`,
                          backgroundColor: '#85A1D6',
                        }}
                      >
                        <span></span>
                      </div>
                    </Tooltip>
                  )) ||
                    null}
                  {(recordDetail.bugNum > 0 && (
                    <Tooltip
                      title={`失败:${recordDetail.bugNum} (${(
                        (recordDetail.bugNum / recordDetail.totalCount) *
                        100
                      ).toFixed(2)}%)`}
                    >
                      <div
                        className="div-wrap"
                        style={{
                          width: `${(recordDetail.bugNum /
                            recordDetail.totalCount) *
                            100}%`,
                          backgroundColor: '#FF7575',
                        }}
                      >
                        <span></span>
                      </div>
                    </Tooltip>
                  )) ||
                    null}
                  {(recordDetail.totalCount - recordDetail.passCount > 0 && (
                    <Tooltip
                      title={`未执行:${recordDetail.totalCount -
                        recordDetail.passCount} (${(
                        ((recordDetail.totalCount - recordDetail.passCount) /
                          recordDetail.totalCount) *
                        100
                      ).toFixed(2)}%)`}
                    >
                      <div
                        className="div-wrap"
                        style={{
                          width: `${((recordDetail.totalCount -
                            recordDetail.passCount) /
                            recordDetail.totalCount) *
                            100}%`,
                          backgroundColor: '#EDF0FA',
                        }}
                      >
                        <span></span>
                      </div>
                    </Tooltip>
                  )) ||
                    null}
                </div>
              </Col>
              <Col span={1}></Col>
              <Col span={2} className="font-size-12">
                计划周期:
              </Col>
              <Col span={4} className="font-size-12">
                {recordDetail.expectStartTime
                  ? moment(recordDetail.expectStartTime).format('YYYY/MM/DD')
                  : null}
                -{' '}
                {recordDetail.expectEndTime
                  ? moment(recordDetail.expectEndTime).format('YYYY/MM/DD')
                  : null}
              </Col>
            </Row>
          )) ||
            null}

          {(casedetail && (
            <Row>
              <Col span={6} className="description-case elipsis-case">
                <Tooltip title={casedetail.description} placement="topLeft">
                  {casedetail.description}
                </Tooltip>
              </Col>
              <Col span={1}></Col>
              <Col span={2} className="font-size-12">
                关联需求:
              </Col>
              <Col span={14} className="font-size-12">
                {casedetail ? casedetail.requirementId : ''}
              </Col>
            </Row>
          )) ||
            null}
           
          <AgileTCEditor
            ref={editorNode => (this.editorNode = editorNode)}
            tags={['前置条件', '执行步骤', '预期结果']}
            iscore={iscore}
            progressShow={progressShow}
            readOnly={readOnly}
            mediaShow={!progressShow}
            editorStyle={{ height: 'calc(100vh - 100px)' }}
            toolbar={{
              image: true,
              theme: ['classic-compact', 'fresh-blue', 'fresh-green-compat'],
              template: ['default', 'right', 'fish-bone'],
              noteTemplate: '# test',
              addFactor,
            }}
            baseUrl=""
            uploadUrl="/api/file/uploadAttachment"
            wsUrl={`http://${window.location.hostname}:8095`}
            wsParam = {{ transports:['websocket','xhr-polling','jsonp-polling'], query: { caseId: caseId, recordId: itemid, user: user }}}
            // wsUrl={`ws://localhost:8094/api/case/${caseId}/${itemid}/${iscore}/${user}`}
            onSave={
              Number(iscore) !== 2
                ? () => {
                    message.loading('保存中......', 1);
                    this.updateCase();
                  }
                : null
            }
          />
        </div>
      </div>
    );
  }
Example #23
Source File: dashboard.js    From zeroqueue with GNU General Public License v3.0 4 votes vote down vote up
export default function Dashboard() {
  const user = useUser({ redirectTo: '/' });

  const [showNewQueueForm, setShowNewQueueForm] = useState(false);
  const [newQueueLoading, setNewQueueLoading] = useState(false);

  const [queues, setQueues] = useState([]);
  const [loadingQueues, setLoadingQueues] = useState(false);
  useEffect(() => {
    const fetchQueues = async () => {
      try {
        if (!user) return;

        setLoadingQueues(true);
        const res = await fetch(`/api/queue`);
        const { data, error } = await res.json();

        switch (res.status) {
          case 200:
            setQueues(data);
            break;
          default:
            throw new Error(error);
        }
      } catch (error) {
        message.error(error.message);
      } finally {
        setLoadingQueues(false);
      }
    };
    fetchQueues();
  }, [user]);

  const [redis, setRedis] = useState([]);
  const [loadingRedis, setLoadingRedis] = useState(false);
  useEffect(() => {
    const fetchRedis = async () => {
      try {
        if (!user) return;

        setLoadingRedis(true);
        const res = await fetch(`/api/queue/redis`);
        const { data, error } = await res.json();

        switch (res.status) {
          case 200:
            setRedis(data);
            break;
          default:
            throw new Error(error);
        }
      } catch (error) {
        message.error(error.message);
      } finally {
        setLoadingRedis(false);
      }
    };
    fetchRedis();
  }, [user]);

  const onFinishFailed = (errorInfo) => {
    console.error('Failed:', errorInfo);
  };

  const onFinish = async (values) => {
    const body = {
      name: values.name,
      schedule: values.schedule,
    };

    try {
      setNewQueueLoading(true);
      const res = await fetch('/api/queue', {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify(body),
      });
      const { data, error } = await res.json();

      switch (res.status) {
        case 200:
          message.success('New queue successful');
          Router.push(`/queue/${data.id}`);
          break;
        default:
          throw new Error(error);
      }
    } catch (error) {
      message.error(error.message);
    } finally {
      setNewQueueLoading(false);
    }
  };

  return (
    <div>
      <Head>
        <title>Zero Queue</title>
        <link rel="icon" href="/favicon.ico" />
      </Head>
      {user && (
        <Layout className="dashboard-layout">
          <Sidebar defaultSelected={'overview'} />
          <Layout className="dashboard-layout">
            <Header className="dashboard-header">
              <div className="dashboard-header__space" />
              <Button type="link" href="/api/auth/logout">
                Logout
              </Button>
            </Header>
            <Content className="dashboard-content">
              <Breadcrumb className="dashboard-content__breadcrumb">
                <Breadcrumb.Item>ZeroQueue</Breadcrumb.Item>
                <Breadcrumb.Item>Overview</Breadcrumb.Item>
              </Breadcrumb>
              <Tabs className="dashboard-content__tabs" defaultActiveKey="queues" type="card">
                <TabPane tab="Queues" key="queues">
                  <div className="dashboard-content__background">
                    <div className="dashboard-overview-header">
                      <Title className="dashboard-overview-header__title" level={3}>
                        All Queues
                      </Title>
                      <Button
                        type="primary"
                        icon={<PlusOutlined />}
                        onClick={() => setShowNewQueueForm(true)}
                      >
                        New Queue
                      </Button>
                    </div>
                    <Table
                      rowKey="id"
                      loading={loadingQueues}
                      columns={queuesColumns}
                      dataSource={queues}
                    />
                  </div>
                </TabPane>
                <TabPane tab="Redis" key="redis">
                  <div className="dashboard-content__background">
                    <div className="dashboard-overview-header">
                      <Title className="dashboard-overview-header__title" level={3}>
                        Redis Statistics
                      </Title>
                    </div>
                    <Table
                      rowKey="name"
                      loading={loadingRedis}
                      columns={redisColumns}
                      dataSource={redis}
                    />
                  </div>
                </TabPane>
              </Tabs>
            </Content>
            <Footer className="dashboard-footer">
              <Button
                type="link"
                href="https://github.com/thezeroqueue/zeroqueue"
                target="blank"
                icon={<GithubFilled />}
              />
            </Footer>
          </Layout>
          <Modal
            title="Create a new queue"
            visible={showNewQueueForm}
            onCancel={() => setShowNewQueueForm(false)}
            footer={null}
          >
            <Form
              {...layout}
              name="basic"
              initialValues={{ remember: true }}
              onFinish={onFinish}
              onFinishFailed={onFinishFailed}
            >
              <Form.Item
                label="Name"
                name="name"
                rules={[{ required: true, message: 'Please input your queue name!' }]}
              >
                <Input />
              </Form.Item>

              <Form.Item
                label="Schedule (cron)"
                name="schedule"
                rules={[
                  () => ({
                    validator(_, value) {
                      if (value && !isValidCron(value)) {
                        return Promise.reject('Please input a valid cron!');
                      }

                      return Promise.resolve();
                    },
                  }),
                ]}
              >
                <Input />
              </Form.Item>

              <Form.Item {...tailLayout}>
                <Button loading={newQueueLoading} type="primary" htmlType="submit">
                  Create
                </Button>
              </Form.Item>
            </Form>
          </Modal>
        </Layout>
      )}
    </div>
  );
}
Example #24
Source File: AdminAuthority.js    From kite-admin with MIT License 4 votes vote down vote up
render () {
    const { stateAdminAuthority } = this.props
    const { getFieldDecorator } = this.props.form
    const { authority_type_select, authority_parent_name } = this.state

    const customLabel = data => {
      return (
        <div className="box-tree-title clearfix">
          <div className="pull-left">
            <span className="title">{data.authority_name} </span>
          </div>
          <div className="pull-right">
            <Icon
              onClick={() => {
                this.showCreateModal(data)
                this.setState({
                  is_create: true
                })
              }}
              type="plus-circle-o"
            />
            <Icon
              onClick={() => {
                this.showEditModal(data)
                this.setState({
                  is_create: false
                })
                this.props.dispatch({
                  type: 'SET_CURRENT_AUTHORITY_INFO',
                  data: data
                })
              }}
              type="edit"
            />
            <Icon
              onClick={() => this.handleDeleteAuthority(data)}
              type="delete"
            />
          </div>
        </div>
      )
    }

    const TreeNodeTree = data => {
      return data.length > 0
        ? data.map(item => {
          return (
            <TreeNode key={item.authority_id} title={customLabel(item)}>
              {TreeNodeTree(item.children)}
            </TreeNode>
          )
        })
        : null
    }

    const itemLayout = {
      labelCol: {
        xs: { span: 24 },
        sm: { span: 5 }
      },
      wrapperCol: {
        xs: { span: 24 },
        sm: { span: 19 }
      }
    }
    const tailItemLayout = {
      wrapperCol: {
        xs: {
          span: 24,
          offset: 0
        },
        sm: {
          span: 16,
          offset: 5
        }
      }
    }

    return (
      <div className="layout-main">
        <div className="layout-main-title">
          <Breadcrumb>
            <Breadcrumb.Item href="#/manager/index">
              <Icon type="home" />
            </Breadcrumb.Item>
            <Breadcrumb.Item href="#/manager/index">
              <span>主页</span>
            </Breadcrumb.Item>
            <Breadcrumb.Item href="#">
              <span>系统管理</span>
            </Breadcrumb.Item>
            <Breadcrumb.Item>管理员权限菜单</Breadcrumb.Item>
          </Breadcrumb>
        </div>

        <div className="layout-nav-btn">
          <button
            className="btn btn-danger"
            icon="plus"
            onClick={() => this.showCreateModal()}
            type="primary"
          >
            创建权限
          </button>
        </div>

        <div className="card admin-authority">
          <div className="card-body">
            <Modal
              footer={null}
              onCancel={this.handleCancel}
              title="权限"
              visible={this.state.visible}
            >
              <Form className="login-form" onSubmit={this.handleSubmit}>
                {authority_parent_name ? (
                  <Form.Item {...itemLayout} label="父权限名称">
                    <Input
                      disabled={true}
                      type="text"
                      value={this.state.authority_parent_name}
                    />
                  </Form.Item>
                ) : (
                    ''
                  )}

                <Form.Item {...itemLayout} hasFeedback label="权限名称">
                  {getFieldDecorator('authority_name', {
                    rules: [
                      {
                        required: true,
                        message: '请输入权限名称'
                      }
                    ]
                  })(<Input type="text" />)}
                </Form.Item>

                <Form.Item {...itemLayout} hasFeedback label="权限类型">
                  {getFieldDecorator('authority_type', {
                    rules: [
                      {
                        required: true,
                        message: '请选择权限类型!'
                      }
                    ]
                  })(
                    <Select
                      onChange={this.authorityTypeChange}
                      placeholder="请选择权限类型!"
                    >
                      <Option value="1">基础菜单</Option>
                      <Option value="2">操作和功能</Option>
                    </Select>
                  )}
                </Form.Item>

                {Number(authority_type_select) === 2 ? (
                  <Form.Item {...itemLayout} hasFeedback label="权限路径">
                    {getFieldDecorator('authority_url', {
                      rules: [
                        {
                          required: true,
                          message: '请输入权限路径'
                        }
                      ]
                    })(
                      <Input
                        addonBefore="/api-admin/v1"
                        placeholder="请输入权限路径"
                        type="text"
                      />
                    )}
                  </Form.Item>
                ) : (
                    <Form.Item {...itemLayout} hasFeedback label="权限Key">
                      {getFieldDecorator('authority_url', {
                        rules: [
                          {
                            required: true,
                            message: '请输入权限Key'
                          }
                        ]
                      })(<Input placeholder="请输入权限Key" type="text" />)}
                    </Form.Item>
                  )}

                <Form.Item {...itemLayout} label="排序">
                  {getFieldDecorator('authority_sort')(<InputNumber />)}
                </Form.Item>

                <Form.Item {...itemLayout} hasFeedback label="权限描述">
                  {getFieldDecorator('authority_description', {
                    rules: [
                      {
                        required: true,
                        message: '请输入权限描述'
                      }
                    ]
                  })(<Input placeholder="请输入权限描述" type="text" />)}
                </Form.Item>

                {Number(authority_type_select) !== 2 ? (
                  <Form.Item {...itemLayout} label="是否显示">
                    {getFieldDecorator('enable', { valuePropName: 'checked' })(
                      <Switch />
                    )}
                  </Form.Item>
                ) : (
                    ''
                  )}
                <Form.Item {...tailItemLayout}>
                  <Button
                    className="login-form-button"
                    htmlType="submit"
                    type="primary"
                  >
                    {this.state.is_create ? '提交' : '修改'}
                  </Button>
                  <Button onClick={this.handleReset} style={{ marginLeft: 8 }}>
                    重置
                  </Button>
                </Form.Item>
              </Form>
            </Modal>

            <Tree defaultExpandAll={true} showLine ref="tree">
              {stateAdminAuthority.admin_authority_list.map(item => {
                return (
                  <TreeNode key={item.authority_id} title={customLabel(item)}>
                    {TreeNodeTree(item.children)}
                  </TreeNode>
                )
              })}
            </Tree>
          </div>
        </div>
      </div>
    )
  }
Example #25
Source File: AccountInfo.js    From acy-dex-interface with MIT License 4 votes vote down vote up
function AccountInfo(props) {

  const INITIAL_ROW_NUMBER = 5;
  const [isWatchlist, setIsWatchlist] = useState(false);
  const [tableRow, setTableRow] = useState([]);
  const [rowNumber, setRowNumber] = useState(INITIAL_ROW_NUMBER);
  const [walletConnected, setWalletConnected] = useState(false);

  const { activate } = useWeb3React();
  const {account, library, chainId} = useConstantLoader();


  const [liquidityPositions, setLiquidityPositions] = useState([]);
  const [activePosition, setActivePosition] = useState(null);

  const [isMyFarms, setIsMyFarms] = useState(false);
  const [harvestAcy, setHarvestAcy] = useState();
  const [balanceAcy, setBalanceAcy] = useState();
  const [stakeACY, setStakeACY] = useState();

  const [isLoadingPool, setIsLoadingPool] = useState(true);
  const [isLoadingHarvest, setIsLoadingHarvest] = useState(true);
  const [isLoadingBalance, setIsLoadingBalance] = useState(true);

  //Wallet State Value Store
  const [userLiquidityOwn,setOwn] = useState(0);
  const [userLiquidityEarn, setEarn] = useState(0);
  
  // Fetch Account Transactions
  const [userTransactions, setUserTransactions] = useState(null)

  // wallet analytics
  const [totalNoOfTransactions, setTotalNoOfTransactions] = useState(0)
  const [totalValueSwapped, setTotalValueSwapped] = useState(0)
  const [totalFeesPaid, setTotalFeesPaid] = useState(0)
  const [liquidityIncludingFees, setLiquidityIncludingFees] = useState(0)

  const [userLPHandlers, setUserLPHandlers] = useState([]);
  // const [userLPData, setUserLPData] = useState([]); // fetch a list of valid pool from backend
  const [userLPShares, setUserLPShares] = useState([]);


  const injected = new InjectedConnector({
    supportedChainIds: [1, 3, 4, 5, 42, 56, 97, 80001],
  });
  const { address } = useParams();

  useEffect(() => {
    // fetch user transaction data
    if(library) {
      fetchAccountTransaction(account, library).then(accountTransactions => {
        console.log('accountTransactions', accountTransactions);
        if (accountTransactions) {
          setUserTransactions(accountTransactions);
          console.log(accountTransactions);
        };
      });
    }
  }, [library]);

  useEffect(() => {
    if (library) {
      // fetch total value swapped
      fetchTotalValueSwapped(account).then(valueSwapped => {
        setTotalValueSwapped(valueSwapped);
      })
      // fetch total fees paid
      fetchTotalFeesPaid(account).then(feesPaid => {
        setTotalFeesPaid(feesPaid);
      })

      // fetch total transactions
      fetchTotalTransactions(account).then(noOfTransactions => {
        setTotalNoOfTransactions(noOfTransactions);
      })

      // fetch liquidity including fees
      fetchLiqudityIncludingFees(account).then(liquidityFees => {
        setLiquidityIncludingFees(liquidityFees);
      })
    }
  }, [library])

  // method to hide/unhidden table row.
  const onRowClick = index =>
    setTableRow(prevState => {
      const prevTableRow = [...prevState];
      prevTableRow[index].hidden = !prevTableRow[index].hidden;
      return prevTableRow;
    });

  // method to prompt metamask extension for user to connect their wallet.
  useEffect(
    () => {
      // console.log("TEST HERE ADDRESS:",address);

      // fetchPoolsFromAccount(marketClient, address).then(data => {
      //   setLiquidityPositions(data);
      // });


      // const getPools = async (library, account) => {
      //   // get all pools from the farm contract.
      //   // todo: currently account refers to the current user viewing this webpage,
      //   // todo: needs to be change to the user in this webpage.
      //   const pools = (await getAllPools(library, account)).filter(pool => pool.hasUserPosition);
      //   const newFarmsContents = [];
      //   const block = await library.getBlockNumber();
      //   // format pools data to the required format that the table can read.
      //   pools.forEach(pool => {
      //     const newFarmsContent = {
      //       index: 0,
      //       poolId: pool.poolId,
      //       lpTokens: pool.lpTokenAddress,
      //       token1: pool.token0Symbol,
      //       token1Logo: getLogoURIWithSymbol(pool.token0Symbol),
      //       token2: pool.token1Symbol,
      //       token2Logo: getLogoURIWithSymbol(pool.token1Symbol),
      //       pendingReward: pool.rewardTokensSymbols.map((token, index) => ({
      //         token,
      //         amount: pool.rewardTokensAmount[index],
      //       })),
      //       totalApr: pool.apr.toFixed(2),
      //       tvl: pool.tvl.toFixed(2),
      //       hasUserPosition: pool.hasUserPosition,
      //       hidden: true,
      //       userRewards: pool.rewards,
      //       stakeData: pool.stakeData,
      //       poolLpScore: pool.lpScore,
      //       poolLpBalance: pool.lpBalance,
      //       endsIn: getDHM((pool.endBlock - block) * BLOCK_TIME),
      //       status: pool.endBlock - block > 0,
      //       ratio: pool.ratio,
      //       endAfter: (pool.endBlock - block) * BLOCK_TIME,
      //     };
      //     if(newFarmsContent.poolId == 0) {
      //       // const total = rewards[j].reduce((total, currentAmount) => total.add(parseInt(currentAmount)));
      //       if(newFarmsContent.stakeData){
      //         const myStakeAcy = newFarmsContent.stakeData.reduce((total, currentAmount) => total + parseFloat(currentAmount.lpAmount), 0);
      //         setStakeACY({
      //           myAcy: myStakeAcy,
      //           totalAcy: newFarmsContent.poolLpBalance
      //         });
      //       } else {
      //         setStakeACY({
      //           myAcy: 0,
      //           totalAcy: newFarmsContent.poolLpBalance
      //         });
      //       }
      //     }
      //     newFarmsContents.push(newFarmsContent);
      //   });
      //   setTableRow(newFarmsContents);
      //   setIsLoadingPool(false);
      // };


      // account will be returned if wallet is connected.
      // so if account is present, retrieve the farms contract.
      if (account) {
        setWalletConnected(true);
        // getPools(library, account);
        // initDao(library, account);
      } else {
        setWalletConnected(false);
      }
    },
    [account]
  );

  const dynamicPositions = activePosition ? [activePosition] : liquidityPositions;

  const aggregateFees = dynamicPositions?.reduce((total, position) => {
    return total + (isNaN(position.fees.sum) ? 0 : position.fees.sum);
  }, 0);

  const positionValue = useMemo(
    () => {
      if (!dynamicPositions) return;
      const reduced = dynamicPositions
        ? dynamicPositions.reduce((total, position) => {
            const positionUSDValue =
              (parseFloat(position.liquidityTokenBalance) / parseFloat(position.pair.totalSupply)) *
              parseFloat(position.pair.reserveUSD);
            return total + (isNaN(positionUSDValue) ? 0 : positionUSDValue);
          }, 0)
        : null;

      return reduced;
    },
    [dynamicPositions]
  );

  // calculate the UserLiquidityOwn --------------------------------------------------------------------------------------------------------------
  const getValidPoolList = (account) => {
    // setLoading(true);
 
    //const apiUrlPrefix = API_URL();
    const apiUrlPrefix = MARKET_API_URL();

    console.log("fetching user pool list");
    axios.get(
      // fetch valid pool list from remote
      `${apiUrlPrefix}/userpool?walletId=${account}`
    ).then(async res => {
      console.log("fetch pool data");
      console.log(res.data);

      const supportedTokens = TOKENLIST();
      const tokens = supportedTokens;

      // construct pool list locally
      const pools = res.data.pools;
      const fetchTask = [];
      for (let pairAddr of pools) {
        const token0addr = supportedTokens.findIndex(item => item.address === pairAddr.token0);
        const token1addr = supportedTokens.findIndex(item => item.address === pairAddr.token1);

        const { address: token0Address, symbol: token0Symbol, decimals: token0Decimal } = tokens[token0addr];
        const { address: token1Address, symbol: token1Symbol, decimals: token1Decimal } = tokens[token1addr];
        const token0 = new Token(chainId, token0Address, token0Decimal, token0Symbol);
        const token1 = new Token(chainId, token1Address, token1Decimal, token1Symbol);

        // queue get pair task
        const pair = Fetcher.fetchPairData(token0, token1, library, chainId);
        fetchTask.push(pair);
        console.log("adding task to array")
      }
      const pairs = await Promise.allSettled(fetchTask);
      console.log("fetched pairs", pairs);

      const LPHandlers = pairs.map(pair => pair.value);
      setUserLPHandlers(LPHandlers);
      console.log("userLPHandlers is updated with length", LPHandlers.length);      

    }).catch(e => console.log("error: ", e));
  }

  async function getUserPoolShare() {

    const fetchPoolShare = async (pair) => {
      console.log("poolToken,", pair.liquidityToken)
      let userPoolBalance = await getUserTokenBalanceRaw(pair.liquidityToken, account, library);
      if (userPoolBalance.isZero()) {
        console.log("zero balance, discard");
        return {};
      }

      userPoolBalance = new TokenAmount(pair.liquidityToken, userPoolBalance);

      const totalSupply = await getTokenTotalSupply(pair.liquidityToken, library, account);

      const tokenPrice = await getAllSupportedTokensPrice();

      // console.log(tokenPrice['ETH']);
      const token0Deposited = pair.getLiquidityValue(
        pair.token0,
        totalSupply,
        userPoolBalance,
        false
      );
      const token1Deposited = pair.getLiquidityValue(
        pair.token1,
        totalSupply,
        userPoolBalance,
        false
      );

      const poolTokenPercentage = new Percent(userPoolBalance.raw, totalSupply.raw).toFixed(4);

      const newData = {
        token0Amount: `${token0Deposited.toSignificant(4)}`,
        token0Symbol: `${pair.token0.symbol}`,
        token1Amount: `${token1Deposited.toSignificant(4)}`,
        token1Symbol: `${pair.token1.symbol}`,

        share: `${poolTokenPercentage}%`,
      };
      // console.log(tokenPrice[newData.token0Symbol]);
      //calculate user own in the same time
      // const token0value = tokenPrice[newData.token0Symbol] * newData.token0Amount;
      // const token1value = tokenPrice[newData.token1Symbol] * newData.token1Amount;
      console.log("new data value:");
      const valueSum = tokenPrice[newData.token0Symbol] * newData.token0Amount +   tokenPrice[newData.token1Symbol] * newData.token1Amount;
      setOwn(prev => (prev + valueSum));

      console.log("userLPShares is updated: ", newData);

      setUserLPShares(prev => ({ ...prev, [pair.liquidityToken.address]: newData }));
      console.log("UserLP infomation:");
    }

    (async () => { for (let pair of userLPHandlers) fetchPoolShare(pair); })();

  }

  useEffect(async () => {
    console.log("the user address is :" + account);    
    console.log("fetching the user pairs information");

    getValidPoolList(account);
      
  
    
  },[account]);

  useEffect(
    async () => {
      if (!chainId || !library || !account || !userLPHandlers) return;
      console.log("getting user liquidity")
      await getUserPoolShare();
    },
    [chainId, library, account, userLPHandlers]
  );

  // Formatter for liquidity including fees
  const formatString = (value) => {
    let formattedStr;
    if (value >= 1000000) {
      formattedStr = `$${(value / 1000000).toFixed(2)}mil`;
    } else if (value >= 1000) {
      formattedStr = `$${(value / 1000).toFixed(2)}k`;
    } else {
      formattedStr = `$${(value).toFixed(2)}`;
    }
    return formattedStr;
  }

  return (

    <div className={styles.marketRoot}>
      { address == account ? (
        <div>
          <MarketSearchBar
        dataSourceCoin={dataSourceCoin}
        dataSourcePool={dataSourcePool}
        // refreshWatchlist={refreshWatchlist}
      />

      {/* breadcrumb */}
      <div className={styles.infoHeader}>
        <Breadcrumb
          separator={<span style={{ color: '#b5b5b6' }}>&gt;</span>}
          style={{ marginBottom: '20px', color: '#b5b5b6' }}
        >
          <Breadcrumb.Item>
            <Link style={{ color: '#b5b5b6' }} to="/market">
              Overview
            </Link>
          </Breadcrumb.Item>
          <Breadcrumb.Item>
            <Link style={{ color: '#b5b5b6' }} to="/market/accounts">
              Accounts
            </Link>
          </Breadcrumb.Item>
          <Breadcrumb.Item style={{ fontWeight: 'bold' }}>{address}</Breadcrumb.Item>
        </Breadcrumb>
      </div>

      {/* name, hyperlink, watchlist */}
      <div
        className={styles.accountPageRow}
        style={{ display: 'flex', justifyContent: 'space-between' }}
      >
        <div>
          {/* <div style={{ fontSize: '26px', fontWeight: 'bold' }}>{address}</div> */}
          <a
            onClick={() => openInNewTab(`${SCAN_URL_PREFIX()}/address/${address}`)}
            style={{ color: '#e29227', fontWeight: 600 }}
          >
            View on {SCAN_NAME}
          </a>
        </div>
        <AcyIcon
          name={isWatchlist ? 'star_active' : 'star'}
          style={{ marginLeft: '10px' }}
          width={16}
          onClick={() => setIsWatchlist(!isWatchlist)}
        />
      </div>

      {/* dropdown */}
      <div className={styles.accountPageRow}>
        <PositionDropdown
          positions={[...new Set(liquidityPositions)]}
          onPositionClick={setActivePosition}
        />
      </div>

      {/* wallet stats */}
      <div className={styles.accountPageRow}>
        <h2>Wallet Stats</h2>
        <div style={{ display: 'flex' }} className={styles.walletStatCard}>
          <div className={styles.walletStatEntry}>
                <div className={styles.walletStatValue}>{totalValueSwapped}</div>
            <div className={styles.walletStatIndicator}>Total Value Swapped</div>
          </div>
          <div style={{ width: 20 }} />
          <div className={styles.walletStatEntry}>
            <div className={styles.walletStatValue}>{totalFeesPaid}</div>
            <div className={styles.walletStatIndicator}>Total Fees Paid</div>
          </div>
          <div style={{ width: 20 }} />
          <div className={styles.walletStatEntry}>
            <div className={styles.walletStatValue}>{totalNoOfTransactions}</div>
            <div className={styles.walletStatIndicator}>Total Transactions</div>
          </div>
        </div>
      </div>

      {/* liquidity and fees earned */}
      <div className={styles.accountPageRow}>
        <div style={{ display: 'flex' }} className={styles.walletStatCard}>
          <div className={styles.walletStatEntry}>
            <div className={styles.walletStatIndicator}>Liquidity (including fees)</div>

            <div className={styles.walletStatValue}>
              {/* {positionValue
                ? formattedNum(positionValue, true)
                : positionValue === 0
                ? formattedNum(userLiquidityOwn, true)
                : '-'} */}
                {formatString(userLiquidityOwn)}
            </div>
          </div>
          <div style={{ width: 20 }} />
          {/* <div className={styles.walletStatEntry}>
            <div className={styles.walletStatIndicator}>Fees earned (cumulative)</div>
            <div className={styles.walletStatValue} style={{ color: 'greenyellow' }}>
              {aggregateFees ? formattedNum(aggregateFees, true, true) : userLiquidityEarn}
            </div>
          </div> */}
        </div>
      </div>

      {/* graphs */}
      {/* <div className={styles.accountPageRow}>
        <div className={styles.accountGraphCard}>
          <div style={{ display: 'flex', justifyContent: 'space-between' }}>
            <AcyPeriodTime onhandPeriodTimeChoose={() => {}} times={['Liquidity', 'Fees']} />
            <AcyPeriodTime onhandPeriodTimeChoose={() => {}} times={['1W', '1M', 'All']} />
          </div>
          <div style={{ height: '50vh' }}>
            <AcyAccountChart lineColor="#1e5d91" />
          </div>
        </div>
      </div> */}

      {/* positions table */}
      {/* <div className={styles.accountPageRow}>
        <h2>Positions</h2>
        <PositionTable data={samplePositionData} />
      </div> */}

      {/* Farms */}
      {/* <div className={styles.accountPageRow}>
        <h2>Farms</h2>
        { (isLoadingHarvest || isLoadingPool || isLoadingBalance)? (
        <div>
          <PageLoading/>
        </div>
      ) : (
        <FarmsTable
          tableRow={tableRow}
          // onRowClick={onRowClick}
          tableTitle="User Farms"
          tableSubtitle="Stake your LP tokens and earn token rewards"
          rowNumber={rowNumber}
          setRowNumber={setRowNumber}
          hideDao={true}
          selectedTable={0}
          tokenFilter={false}
          setTokenFilter={() => {}}
          walletConnected={walletConnected}
          connectWallet={connectWallet}
          account={account}
          library={library}
          chainId={chainId}

          isMyFarms={true}
          harvestAcy={harvestAcy}
          balanceAcy={balanceAcy}
          refreshHarvestHistory={()=>{}}
          searchInput={''}
          isLoading={false}
          activeEnded={true}
        />
      )}
      </div> */}

      {/* transaction table */}
      <div className={styles.accountPageRow}>
      <h2>Transactions</h2>
      { !userTransactions ? (
          <h2 style={{ textAlign: "center", color: "white" }}>Loading <Icon type="loading" /></h2>
          ) : (
          <TransactionTable
            dataSourceTransaction={userTransactions}
          />
          )}
       
        {/* <TransactionTable dataSourceTransaction={userTransactions} /> */}
      </div>

      <div style={{ height: 20 }} />
        </div>
      ): (
        <div>
          Address does not matched with the connected account
        </div>
      )
      }
      
    </div>
  );
}
Example #26
Source File: Book.js    From kite-admin with MIT License 4 votes vote down vote up
render () {
    const { loading, title_val, status_val, edit_status_val } = this.state
    const { stateBook = {} } = this.props
    const { getFieldDecorator } = this.props.form

    const itemLayout = {
      labelCol: {
        xs: { span: 24 },
        sm: { span: 5 }
      },
      wrapperCol: {
        xs: { span: 24 },
        sm: { span: 19 }
      }
    }
    const tailItemLayout = {
      wrapperCol: {
        xs: {
          span: 24,
          offset: 0
        },
        sm: {
          span: 16,
          offset: 5
        }
      }
    }
    return (
      <div className="layout-main">
        <div className="layout-main-title">
          <Breadcrumb>
            <Breadcrumb.Item href="#/manager/index">
              <Icon type="home" />
            </Breadcrumb.Item>
            <Breadcrumb.Item href="#/manager/index">
              <span>主页</span>
            </Breadcrumb.Item>
            <Breadcrumb.Item href="#">
              <span>小书章节管理</span>
            </Breadcrumb.Item>
            <Breadcrumb.Item>小书章节汇总</Breadcrumb.Item>
          </Breadcrumb>
        </div>

        <div className="admin-book card">
          <div className="card-body">
            <div className="xsb-operation-menu">
              <Form layout="inline">
                <Form.Item label="小书章节标题">
                  <Input
                    value={title_val}
                    onChange={e => {
                      this.changeVal(e.target.value, 'title_val')
                    }}
                  />
                </Form.Item>
                <Form.Item label="状态">
                  <Select
                    className="select-view"
                    value={status_val}
                    onChange={value => {
                      this.changeVal(value, 'status_val')
                    }}
                  >
                    <Option value="">全部</Option>
                    {Object.keys(this.state.otherStatusListText).map(key => (
                      <Option key={key}>
                        {this.state.otherStatusListText[key]}
                      </Option>
                    ))}
                  </Select>
                </Form.Item>

                <Form.Item>
                  <button
                    type="primary"
                    className="btn btn-danger"
                    onClick={this.fetchBookList}
                  >
                    搜索
                  </button>
                  <button
                    type="primary"
                    className="btn btn-primary"
                    onClick={this.resetBarFrom}
                  >
                    重置
                  </button>
                </Form.Item>
              </Form>
            </div>

            <Modal
              footer={null}
              onCancel={() => {
                this.setState({
                  modal_visible_edit: false
                })
              }}
              title="修改小书章节"
              visible={this.state.modal_visible_edit}
            >
              <Form className="from-view" onSubmit={this.handleSubmit}>
                <Form.Item {...itemLayout} hasFeedback label="状态">
                  {getFieldDecorator('status', {
                    rules: [{ required: true, message: '请选择状态!' }]
                  })(
                    <Select
                      placeholder="状态"
                      onChange={value => {
                        this.setState({
                          edit_status_val: value
                        })
                      }}
                    >
                      {Object.keys(this.state.otherStatusListText).map(key => (
                        <Option key={key}>
                          {this.state.otherStatusListText[key]}
                        </Option>
                      ))}
                    </Select>
                  )}
                </Form.Item>

                {~[3, 5].indexOf(Number(edit_status_val)) ? (
                  <Form.Item {...itemLayout} label="拒绝的原因">
                    {getFieldDecorator('rejection_reason', {
                      rules: [
                        {
                          required: true,
                          message: '请输入拒绝的原因!',
                          whitespace: true
                        }
                      ]
                    })(<Input placeholder="小书章节被拒绝的原因" />)}
                  </Form.Item>
                ) : (
                    ''
                  )}

                <Form.Item {...tailItemLayout}>
                  <Button
                    className="register-btn"
                    htmlType="submit"
                    type="primary"
                  >
                    更新
                  </Button>
                </Form.Item>
              </Form>
            </Modal>

            <Table
              columns={this.state.columns}
              dataSource={stateBook.list}
              loading={loading}
              onChange={this.TablePageChange.bind(this)}
              pagination={this.state.pagination}
              rowKey="book_id"
            />
          </div>

          <Alert
            style={{ marginTop: '20px' }}
            message="备注"
            description="小书章节发表完成后状态是审核中,是仅对自己可见的,审核不通过也是仅自己可见,并且会标注审核不通过,更改为审核通过的小书章节对所有人开放,
          这种方式是人工审核的,暂时采用这种方案,后续会更改"
            type="info"
            showIcon
          />
        </div>
      </div>
    )
  }