@ant-design/icons#EditOutlined JavaScript Examples

The following examples show how to use @ant-design/icons#EditOutlined. 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: meta.jsx    From virtuoso-design-system with MIT License 6 votes vote down vote up
storiesOf('antd/card', module).add('meta', () => 
  <Card
    style={{ width: 300 }}
    cover={
      <img
        alt="example"
        src="https://gw.alipayobjects.com/zos/rmsportal/JiqGstEfoWAOHiTxclqi.png"
      />
    }
    actions={[
      <SettingOutlined key="setting" />,
      <EditOutlined key="edit" />,
      <EllipsisOutlined key="ellipsis" />,
    ]}
  >
    <Meta
      avatar={<Avatar src="https://zos.alipayobjects.com/rmsportal/ODTLcjxAfvqbxHnVXCYX.png" />}
      title="Card title"
      description="This is the description"
    />
  </Card>,
  { docs: { page: () => (<><h1 id="enus">en-US</h1>
<p>A Card that supports <code>cover</code>, <code>avatar</code>, <code>title</code> and <code>description</code>.</p></>) } });
Example #2
Source File: HtxTextBox.js    From label-studio-frontend with Apache License 2.0 6 votes vote down vote up
renderView() {
    const { onChange, onDelete, text, ...props } = this.props;

    return (
      <>
        <Paragraph {...props}>
          <span ref={this.textRef}>{text}</span>
          {onChange && <EditOutlined onClick={this.startEditing} className="ant-typography-edit" />}
        </Paragraph>
        {onDelete && <DeleteOutlined className={styles.delete} onClick={onDelete} />}
      </>
    );
  }
Example #3
Source File: index.js    From mixbox with GNU General Public License v3.0 6 votes vote down vote up
render() {
        const user = getLoginUser() || {};
        const name = user.name;

        const { className, theme } = this.props;

        const menu = (
            <Menu styleName="menu" theme={theme} selectedKeys={[]} onClick={this.handleMenuClick}>
                <Item key="modifyPassword"><EditOutlined />修改密码</Item>
                <Item><Link to="/settings"><SettingOutlined />设置</Link></Item>
                <Menu.Divider />
                <Item key="logout"><LogoutOutlined />退出登录</Item>
            </Menu>
        );
        return (
            <div styleName="user-menu" ref={node => this.userMenu = node}>
                <Dropdown trigger="click" overlay={menu} getPopupContainer={() => (this.userMenu || document.body)}>
                    <span styleName="account" className={className}>
                        <span styleName="user-name">{name}</span>
                        <CaretDownOutlined />
                    </span>
                </Dropdown>

                <ModifyPassword
                    visible={this.state.passwordVisible}
                    onOk={() => this.setState({ passwordVisible: false })}
                    onCancel={() => this.setState({ passwordVisible: false })}
                />
            </div>
        );
    }
Example #4
Source File: index.jsx    From erp-crm with MIT License 6 votes vote down vote up
function DropDownRowMenu({ row }) {
  const Show = () => {};
  function Edit() {}
  function Delete() {}
  return (
    <Menu style={{ width: 130 }}>
      <Menu.Item icon={<EyeOutlined />} onClick={Show}>
        Show
      </Menu.Item>
      <Menu.Item icon={<EditOutlined />} onClick={Edit}>
        Edit
      </Menu.Item>
      <Menu.Item icon={<DeleteOutlined />} onClick={Delete}>
        Delete
      </Menu.Item>
    </Menu>
  );
}
Example #5
Source File: index.jsx    From starter-antd-admin-crud-auth-mern with MIT License 6 votes vote down vote up
function DropDownRowMenu({ row }) {
  const Show = () => {};
  function Edit() {}
  function Delete() {}
  return (
    <Menu style={{ width: 130 }}>
      <Menu.Item icon={<EyeOutlined />} onClick={Show}>
        Show
      </Menu.Item>
      <Menu.Item icon={<EditOutlined />} onClick={Edit}>
        Edit
      </Menu.Item>
      <Menu.Item icon={<DeleteOutlined />} onClick={Delete}>
        Delete
      </Menu.Item>
    </Menu>
  );
}
Example #6
Source File: baseForm.js    From FP with MIT License 6 votes vote down vote up
BaseFormEl = (props) => {
  const {isEdit, onEdit, onDel, onAdd} = props
  const handleEdit = (v) => {
    onEdit && onEdit(v)
  }
  return <div className={styles.formControl} style={{border: `1px solid ${isEdit ? 'red' : 'transparent'}`}}>
    <div className={styles.formItem}>{ props.children }</div>
    <div className={styles.actionBar}>
      <span className={styles.actionItem} onClick={onDel}><MinusCircleOutlined /></span>
      <span className={styles.actionItem} onClick={onAdd}><PlusCircleOutlined /></span>
      <span className={styles.actionItem} onClick={handleEdit}><EditOutlined /></span>
    </div>
  </div>
}
Example #7
Source File: Stats.js    From placement-portal with MIT License 6 votes vote down vote up
render() {
        const {Title, Number, Color} = this.props;
        return (
             <Col sm={{span: 24}} md={{span: 8}} xl={{span: 8}} xxl={{span: 6}}>
                 <Card
                     style={{background: Color, margin: 10}}
                     actions={[
                         <PieChartOutlined key="statistics" />,
                         <EditOutlined key="details" />
                     ]}
                 >
                     <Row type={'flex'} justify={'center'}>
                         <Col>
                             <Row type={'flex'} justify={'center'}>
                                 <Typography.Title style={{color: '#ffffff', fontSize: '1.8em'}}>
                                     {Title}
                                 </Typography.Title>
                             </Row>
                             <Row type={'flex'} justify={'end'}>
                                 <Typography.Title style={{color: '#ffffff', fontSize: '2em'}}>
                                     {Number}
                                 </Typography.Title>
                             </Row>
                         </Col>
                     </Row>
                 </Card>
             </Col>

        );
    }
Example #8
Source File: loading.jsx    From virtuoso-design-system with MIT License 6 votes vote down vote up
render() {
    const { loading } = this.state;

    return (
      <>
        <Switch checked={!loading} onChange={this.onChange} />

        <Card style={{ width: 300, marginTop: 16 }} loading={loading}>
          <Meta
            avatar={
              <Avatar src="https://zos.alipayobjects.com/rmsportal/ODTLcjxAfvqbxHnVXCYX.png" />
            }
            title="Card title"
            description="This is the description"
          />
        </Card>

        <Card
          style={{ width: 300, marginTop: 16 }}
          actions={[
            <SettingOutlined key="setting" />,
            <EditOutlined key="edit" />,
            <EllipsisOutlined key="ellipsis" />,
          ]}
        >
          <Skeleton loading={loading} avatar active>
            <Meta
              avatar={
                <Avatar src="https://zos.alipayobjects.com/rmsportal/ODTLcjxAfvqbxHnVXCYX.png" />
              }
              title="Card title"
              description="This is the description"
            />
          </Skeleton>
        </Card>
      </>
    );
  }
Example #9
Source File: UserStatus.js    From react-chat-app with MIT License 5 votes vote down vote up
UserStatus = (props) => {
const { conn } = useContext(ChatEngineContext);
  const [userStatusAvailable, setUserStatusAvailable] = useState(false);
  const [editing, setEditing] = useState(false);
  const { userObject, convertedName } = useAuth();
  const [currentStatus, setCurrentStatus] = useState(props.userStatus)

  useEffect(() => {
    setUserStatusAvailable(true);
  }, [editing])

  const updateProfile = (newStatus) => {
    const myHeaders = new Headers();
    myHeaders.append("Project-ID", process.env.REACT_APP_PROJECT_ID);
    myHeaders.append("User-Name", convertedName);
    myHeaders.append("User-Secret", userObject.uid);

    const formdata = new FormData();
    formdata.append("first_name", newStatus);

    const requestOptions = {
      method: "PATCH",
      headers: myHeaders,
      body: formdata,
      redirect: "follow",
    };

    fetch("https://api.chatengine.io/users/me/", requestOptions).then(() => {
      setCurrentStatus(newStatus)
    });
  };

  return (
    <div className="chat-list-user-status">
      {editing ?
        <EditProfile
          userstatus={currentStatus}
          close={() => {
            setEditing(false)
          }}
          onSubmit={(newStatus) => {
            updateProfile(newStatus)
            setEditing(false)
          }}
        />
        :
        <>
          <div className="user-status">
            {/* Anti-spam to make demo account possible
            currentStatus ? currentStatus : "" */}
             {(conn.userName === "john%20doe") ? "sample status" : <>{currentStatus ? currentStatus : ""}</>   }  
             </div>
        </>}
      {!editing ?
        <EditOutlined onClick={() => setEditing(true)} /> :
        <CloseOutlined onClick={() => setEditing(false)} />
      }
    </div>
  )
}
Example #10
Source File: AdminDataTable.jsx    From starter-antd-admin-crud-auth-mern with MIT License 5 votes vote down vote up
function DropDownRowMenu({ row }) {
  const dispatch = useDispatch();
  const { crudContextAction } = useCrudContext();
  const {
    panel,
    collapsedBox,
    modal,
    advancedBox,
    readBox,
    editBox,
  } = crudContextAction;
  const item = useSelector(selectItemById(row._id));
  const Show = () => {
    dispatch(crud.currentItem(item));
    panel.open();
    collapsedBox.open();
    readBox.open();
  };
  function Edit() {
    dispatch(crud.currentAction("update", item));
    editBox.open();
    panel.open();
    collapsedBox.open();
  }
  function UpdatePassword() {
    dispatch(crud.currentAction("update", item));
    advancedBox.open();
    panel.open();
    collapsedBox.open();
  }
  function Delete() {
    dispatch(crud.currentAction("delete", item));
    modal.open();
  }
  return (
    <Menu style={{ minWidth: 130 }}>
      <Menu.Item key={`${uniqueId()}`} icon={<EyeOutlined />} onClick={Show}>
        Show
      </Menu.Item>
      <Menu.Item key={`${uniqueId()}`} icon={<EditOutlined />} onClick={Edit}>
        Edit
      </Menu.Item>
      <Menu.Item
        key={`${uniqueId()}`}
        icon={<LockOutlined />}
        onClick={UpdatePassword}
      >
        Update Password
      </Menu.Item>
      <Menu.Item
        key={`${uniqueId()}`}
        icon={<DeleteOutlined />}
        onClick={Delete}
      >
        Delete
      </Menu.Item>
    </Menu>
  );
}
Example #11
Source File: index.js    From quick_redis_blog with MIT License 5 votes vote down vote up
render() {
        return (
            <div>
                <Form initialValues={{ ...this.initValues }} ref="form">
                    <Row gutter={8}>
                        <Col span={14}>
                            <Form.Item
                                name="redisKey"
                                rules={[
                                    {
                                        required: true,
                                    },
                                ]}
                                style={{ marginBottom: "1px" }}
                            >
                                <Search
                                    prefix="key :"
                                    enterButton={
                                        <Button
                                            icon={<EditOutlined />}
                                        ></Button>
                                    }
                                    size="middle"
                                    onSearch={this.renameKey.bind(this)}
                                />
                            </Form.Item>
                        </Col>
                        <Col span={5}>
                            <Form.Item
                                name="ttl"
                                rules={[
                                    {
                                        required: true,
                                    },
                                ]}
                                style={{ marginBottom: "1px" }}
                            >
                                <Search
                                    prefix="ttl :"
                                    enterButton={
                                        <Button
                                            icon={<EditOutlined />}
                                        ></Button>
                                    }
                                    size="middle"
                                    onSearch={this.updateTtl.bind(this)}
                                />
                            </Form.Item>
                        </Col>
                        <Col span={5}>
                            <Space>
                                <Form.Item style={{ marginBottom: "1px" }}>
                                    <Popconfirm
                                        title={intl.get(
                                            "HostKey.header.key.delete.notice"
                                        )}
                                        onConfirm={() => {
                                            this.deleteKey();
                                        }}
                                    >
                                        <Button
                                            icon={<DeleteOutlined />}
                                        ></Button>
                                    </Popconfirm>
                                </Form.Item>
                                <Form.Item style={{ marginBottom: "1px" }}>
                                    <Button
                                        icon={<ReloadOutlined />}
                                        onClick={this.refreshAll.bind(this)}
                                    ></Button>
                                </Form.Item>
                            </Space>
                        </Col>
                    </Row>
                </Form>
            </div>
        );
    }
Example #12
Source File: DataTableDropMenu.jsx    From erp-crm with MIT License 5 votes vote down vote up
export default function DataTableDropMenu({ row, entity }) {
  const dispatch = useDispatch();
  const { erpContextAction } = useErpContext();
  const { readPanel, updatePanel, recordPanel, modal } = erpContextAction;
  const item = useSelector(selectItemById(row._id));
  function Read() {
    dispatch(erp.currentItem({ data: item }));
    readPanel.open();
  }
  function RecordPayment() {
    dispatch(erp.currentAction({ actionType: 'recordPayment', data: item }));
    recordPanel.open();
    dispatch(erp.currentItem({ data: item }));
  }
  function Edit() {
    dispatch(erp.currentAction({ actionType: 'update', data: item }));
    updatePanel.open();
  }
  function Delete() {
    dispatch(erp.currentAction({ actionType: 'delete', data: item }));
    modal.open();
  }
  function Download() {
    window.open(`${DOWNLOAD_BASE_URL}${entity}/${entity}-${row._id}.pdf`, '_blank');
  }
  return (
    <Menu style={{ minWidth: 130 }}>
      <Menu.Item key={`${uniqueId()}`} icon={<EyeOutlined />} onClick={Read}>
        Show
      </Menu.Item>
      <Menu.Item key={`${uniqueId()}`} icon={<CreditCardOutlined />} onClick={RecordPayment}>
        Record Payment
      </Menu.Item>
      <Menu.Item key={`${uniqueId()}`} icon={<EditOutlined />} onClick={Edit}>
        Edit
      </Menu.Item>
      <Menu.Item key={`${uniqueId()}`} icon={<FilePdfOutlined />} onClick={Download}>
        Download
      </Menu.Item>
      <Menu.Item key={`${uniqueId()}`} icon={<DeleteOutlined />} onClick={Delete}>
        Delete
      </Menu.Item>
    </Menu>
  );
}
Example #13
Source File: ActionMenu.js    From react-admin-portal with MIT License 5 votes vote down vote up
function useActionMenu({ selectedRow, updateEntityPath }) {
  const history = useHistory();

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

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

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

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

  return [actionColumnView];
}
Example #14
Source File: index.js    From react_management_template with Apache License 2.0 5 votes vote down vote up
render() {
        return (
            <div>
                <Row>
                    <Card title="基础按钮" className="base_button" >
                        <Button type="primary">按钮</Button>
                        <Button>按钮</Button>
                        <Button type="dashed">按钮</Button>
                        <Button type="danger">按钮</Button>
                        <Button disabled>按钮</Button>
                    </Card>

                    <Card title="图形按钮" className="base_button" >
                        <Button icon={<PlusOutlined />}>创建</Button>
                        <Button icon={<EditOutlined />}>编辑</Button>
                        <Button icon={<DeleteOutlined />}type="dashed">删除</Button>
                        <Button icon={<SearchOutlined />} type="primary">搜索</Button>
                        <Button icon={<DownloadOutlined />}  type="primary">下载</Button>
                    </Card>


                    <Card title="Loading按钮" className="base_button" >
                        <Button type="primary" loading={this.state.loading}>确定</Button>
                        <Button type="primary" shape="circle" loading={this.state.loading}></Button>
                        <Button loading={this.state.loading}>点击加载</Button>
                        <Button shape="circle" loading={this.state.loading}></Button>
                        <Button type="primary" onClick={this.handleCloseLoading}>关闭</Button>
                    </Card>

                    <Card title="按钮组" className="base_button" >
                        <Button.Group>
                            <Button type="primary" icon={<LeftOutlined/>}>返回</Button>
                            <Button  type="primary" icon={<RightOutlined/>}>前进</Button>
                        </Button.Group>
                    </Card>


                    <Card title="按钮尺寸" className="base_button" >
                        <Radio.Group value={this.state.size} onChange={this.handleChange}>
                            <Radio value="small">小</Radio>
                            <Radio value="default">中</Radio>
                            <Radio value="large">大</Radio>
                        </Radio.Group>

                        <Button size={this.state.size} type="primary">按钮</Button>
                        <Button size={this.state.size} >按钮</Button>
                        <Button size={this.state.size} type="dashed">按钮</Button>
                        <Button size={this.state.size} type="danger">按钮</Button>
                        <Button size={this.state.size} disabled>按钮</Button>
                    </Card>
                </Row>
            </div>
        );
    }
Example #15
Source File: index.js    From gobench with Apache License 2.0 5 votes vote down vote up
render() {
    return (
      <div>
        <div className="row">
          <div className="col-lg-6">
            <h5 className="mb-3">
              <strong>Basic</strong>
            </h5>
            <div className="mb-5">
              <div className="mb-3">
                <Card title="Default size card" extra={<a href="#">More</a>} style={{ width: 300 }}>
                  <p>Card content</p>
                  <p>Card content</p>
                  <p>Card content</p>
                </Card>
              </div>
              <div className="mb-3">
                <Card
                  size="small"
                  title="Small size card"
                  extra={<a href="#">More</a>}
                  style={{ width: 300 }}
                >
                  <p>Card content</p>
                  <p>Card content</p>
                  <p>Card content</p>
                </Card>
              </div>
            </div>
          </div>
          <div className="col-lg-6">
            <h5 className="mb-3">
              <strong>Advanced</strong>
            </h5>
            <div className="mb-5">
              <div className="mb-3">
                <Card
                  style={{ width: 300 }}
                  cover={
                    <img
                      alt="example"
                      src="https://gw.alipayobjects.com/zos/rmsportal/JiqGstEfoWAOHiTxclqi.png"
                    />
                  }
                  actions={[
                    <SettingOutlined key="setting" />,
                    <EditOutlined key="edit" />,
                    <EllipsisOutlined key="ellipsis" />,
                  ]}
                >
                  <Meta
                    avatar={
                      <Avatar src="https://zos.alipayobjects.com/rmsportal/ODTLcjxAfvqbxHnVXCYX.png" />
                    }
                    title="Card title"
                    description="This is the description"
                  />
                </Card>
              </div>
              <div className="mb-3">
                <Card style={{ width: 300, marginTop: 16 }} loading>
                  <Meta
                    avatar={
                      <Avatar src="https://zos.alipayobjects.com/rmsportal/ODTLcjxAfvqbxHnVXCYX.png" />
                    }
                    title="Card title"
                    description="This is the description"
                  />
                </Card>
              </div>
            </div>
          </div>
        </div>
      </div>
    )
  }
Example #16
Source File: EditTeam.js    From video-journal-for-teams-fe with MIT License 5 votes vote down vote up
EditTeam = () => {
	const [showModal, setShowModal] = useState(false);
	const [values, setValues] = useState(null);
	const currentName = useSelector((state) => state.Team.team.name);
	const { team_id } = useParams();
	const dispatch = useDispatch();
	const history = useHistory();

	const handleOpen = () => {
		setShowModal(true);
	};

	const handleOk = () => {
		if (values) {
			const updates = { name: values };
			AxiosWithAuth()
				.put(`/v2/teams/${team_id}`, updates)
				.then((res) => {
					dispatch(fetchTeamById(team_id));
					setShowModal(!showModal);
					setValues(null);
				})
				.catch((err) => console.log(err));
		}
	};

	const handleCancel = () => {
		setShowModal(false);
	};

	const handleChange = (e) => {
		setValues(e.target.value);
	};
	function iDelete() {
		AxiosWithAuth()
			.delete(`/v2/teams/${team_id}`)
			.then((res) => history.push("/user-dashboard"))
			.catch((err) => console.log(err));
	}

	return (
		<div>
			<Button
				type="primary"
				style={{
					color: "#6954EA",
					border: "none",
					fontSize: "1rem",
					textAlign: "left",
					backgroundColor: "transparent",
					boxShadow: "none",
				}}
				onClick={handleOpen}>
				<EditOutlined style={{ fontSize: "1.6rem" }} />
			</Button>

			<Modal
				title={`Current Name: ${currentName}`}
				visible={showModal}
				onOk={handleOk}
				onCancel={handleCancel}
				okButtonProps={{ style: { backgroundColor: "#6954EA", color: "white", border: "none" } }}>
				<Form name="basic" initialValues={{ remember: false }}>
					<Form.Item
						label="New Team Name"
						name="team_name"
						rules={[{ required: true, message: "Please enter a new team name!" }]}
						onChange={handleChange}>
						<Input value={values} onChange={handleChange} />
					</Form.Item>
				</Form>
			</Modal>
		</div>
	);
}
Example #17
Source File: index.js    From react_management_template with Apache License 2.0 5 votes vote down vote up
render() {
        return (
            <div>
                <Row>
                    <Card title="Tab基础演示" className="base_button" >
                        <Tabs>
                            <TabPane tab="tab1" key="1">
                                content of tabl
                            </TabPane>
                            
                            <TabPane tab="tab2" key="2">
                                content of tab2
                            </TabPane>

                            <TabPane tab="tab3" key="3">
                                content of tab3
                            </TabPane>
                        </Tabs>
                    </Card>


                    <Card title="Tab带图标演示" className="base_button" >
                        <Tabs>
                            <TabPane tab={<span><PlusOutlined/>"tab1"</span>} key="1">
                                content of tabl
                            </TabPane>
                            
                            <TabPane tab={<span><EditOutlined/>"tab2"</span>} key="2">
                                content of tab2
                            </TabPane>

                            <TabPane tab={<span><DeleteOutlined/>"tab3"</span>} key="3">
                                content of tab3
                            </TabPane>
                        </Tabs>
                    </Card>


                    <Card title="Tab带图的页签" className="card-wrap">
                    <Tabs 
                        onChange={this.onChange}
                        activeKey={this.state.activeKey}
                        type="editable-card"
                        onEdit={this.onEdit}
                    >
                        {
                            this.state.panes.map((panel)=>{
                                return <TabPane 
                                    tab={panel.title}
                                    key={panel.key}

                                />
                            })
                        }
                    </Tabs>
                </Card>

                </Row>
            </div>
        );
    }
Example #18
Source File: index.jsx    From the-eye-knows-the-garbage with MIT License 4 votes vote down vote up
TableList = () => {
  const [createModalVisible, handleModalVisible] = useState(false);
  const [updateModalVisible, handleUpdateModalVisible] = useState(false);
  const [updateFormValues, setUpdateFormValues] = useState({});
  const actionRef = useRef();
  const addFormRef = useRef();
  const updateFormRef = useRef();

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

  try {
    await addTyAdminSysLog({...fields});
    hide();
    message.success('添加成功');
    return true;
  } catch (error) {
      if ('fields_errors' in error.data) {
        for (let key in error.data.fields_errors) {
          var value = error.data.fields_errors[key];
          addFormRef.current.setFields([
            {
              name: key,
              errors: value,
            },
          ]);
        }
      } else {
        message.error('非字段类型错误');
      }
    hide();
    message.error('添加失败');
    return false;
  }
};

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

  try {
    await updateTyAdminSysLog(value, current_id);
    hide();
    message.success('修改成功');
    return true;
  } catch (error) {
            if ('fields_errors' in error.data) {
        for (let key in error.data.fields_errors) {
          var value = error.data.fields_errors[key];
          updateFormRef.current.setFields([
            {
              name: key,
              errors: value,
            },
          ]);
        }
      } else {
        message.error('非字段类型错误');
      }
    hide();
    message.error('修改失败请重试!');
    return false;
  }
};

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

  try {
    const ids = selectedRows.map(row => row.id).join(',');
    await removeTyAdminSysLog(ids);
    hide();
    message.success('删除成功');
    return true;
  } catch (error) {
    hide();
    message.error('删除失败,请重试');
    return false;
  }
};
  const dateFieldList = ["action_time"]
  const base_columns = [{
                              title: 'ID',
                              dataIndex: 'id',
                              hideInForm: true,
                              hideInSearch: true,
                              rules: [
                                {
                                  required: true,
                                  message: 'ID为必填项',
                                },
                              ],
                            },{
          title: '动作时间',
          dataIndex: 'action_time',
          valueType: 'dateTime',
          hideInForm: true,
          rules: [
            {
              required: true,
              message: '动作时间为必填项',
            },
          ],
                                   render: (text, record) => {
      return dealDateTimeDisplay(text);
    },
        },{
                  title: '操作ip',
                  dataIndex: 'ip_addr',
                  rules: [
                    {
                      required: true,
                      message: '操作ip为必填项',
                    },
                  ],
                },{
                  title: '操作flag',
                  dataIndex: 'action_flag',
                  rules: [
                    {
                      required: true,
                      message: '操作flag为必填项',
                    },
                  ],
                },{
                              title: '日志记录',
                              dataIndex: 'message',
                            valueType: 'textarea',
                             ellipsis: true,
                              rules: [
                                {
                                  required: true,
                                  message: '日志记录为必填项',
                                },
                              ],
                            },{
                  title: '日志类型',
                  dataIndex: 'log_type',
                  rules: [
                    {
                      required: true,
                      message: '日志类型为必填项',
                    },
                  ],
                },{
                  title: '用户',
                  dataIndex: 'user_name',
                  rules: [
                    {
                      required: true,
                      message: '用户为必填项',
                    },
                  ],
                },    {
                          title: '操作',
                          dataIndex: 'option',
                          valueType: 'option',
                                fixed: 'right',
      width: 100,
                          render: (text, record) => (
                            <>

                              <EditOutlined title="编辑" className="icon" onClick={async () => {
                                record.action_time = moment(record.action_time);
                                handleUpdateModalVisible(true);
                                setUpdateFormValues(record);
                              }} />
                              <Divider type="vertical" />
                              <Popconfirm
                                title="您确定要删除系统日志吗?"
                                placement="topRight"
                                onConfirm={() => {
                                  handleRemove([record])
                                  actionRef.current.reloadAndRest();
                                }}
                                okText="确定"
                                cancelText="取消"
                              >
                                <DeleteOutlined title="删除" className="icon" />
                              </Popconfirm>
                            </>
                          ),
                        },];

  let cp = deepCopy(base_columns);
  const table_columns = getTableColumns(cp);

  const update_columns = [...base_columns];

  const create_columns = [...base_columns];

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

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

  


    
  return (
    <PageHeaderWrapper>
      <ProTable
           beforeSearchSubmit={(params => {
                         dealTime(params, dateFieldList);
          return params;
        })}
        params={paramState}
        scroll={{x: '100%'}}
        columnsStateMap={columnsStateMap}
        onColumnsStateChange={(map) => setColumnsStateMap(map)}
        headerTitle="系统日志表格"
        actionRef={actionRef}
        rowKey="id"
        toolBarRender={(action, {selectedRows}) => [
          <Button type="primary" onClick={() => handleModalVisible(true)}>
            <PlusOutlined /> 新建
          </Button>,
          <Input.Search style={{marginRight: 20}} placeholder="搜索系统日志 " onSearch={value => {
            setParamState({
              search: value,
            });
            actionRef.current.reload();
          }} />,
          selectedRows && selectedRows.length > 0 && (
            <Dropdown
              overlay={
                <Menu
                  onClick={async e => {
                    if (e.key === 'remove') {
                      await handleRemove(selectedRows);
                      actionRef.current.reloadAndRest();
                    }
                  }}
                  selectedKeys={[]}
                >
                  <Menu.Item key="remove">批量删除</Menu.Item>
                </Menu>
              }
            >
              <Button>
                批量操作 <DownOutlined />
              </Button>
            </Dropdown>
          ),
        ]}
        tableAlertRender={({selectedRowKeys, selectedRows}) => (
          selectedRowKeys.length > 0 ? <div>
            已选择{' '}
            <a
              style={{
                fontWeight: 600,
              }}
            >
              {selectedRowKeys.length}
            </a>{' '}
            项&nbsp;&nbsp;
          </div> : false

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

            if (success) {
              handleModalVisible(false);

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

            if (success) {
              handleUpdateModalVisible(false);

              if (actionRef.current) {
                actionRef.current.reload();
              }
            }
          }}
          rowKey="key"
          
          type="form"
          form={{
            initialValues: updateFormValues, labelCol: {span: 6},
            labelAlign: 'left',
          }}
          columns={update_columns}
          rowSelection={{}}
        />
      </UpdateForm>
    </PageHeaderWrapper>
  );
}
Example #19
Source File: Timeline.jsx    From Tai-Shang-NFT-Wallet with MIT License 4 votes vote down vote up
// displays a timeline for scaffold-eth usage

export default function TimelineDisplay(props) {
  return (
    <Timeline mode="right">
      <Timeline.Item dot="?">
        <Text delete>
          Clone and Install from the{" "}
          <a target="_blank" rel="noopener noreferrer" href="https://github.com/austintgriffith/scaffold-eth">
            github repo
          </a>
        </Text>
      </Timeline.Item>

      <Timeline.Item dot="⚛️">
        <Text delete>
          Start your frontend app with: <Text strong>yarn start</Text>
        </Text>
      </Timeline.Item>

      <Timeline.Item dot="⛓">
        <Text delete={props.chainIsUp}>
          Start your local blockchain with: <Text strong>yarn run chain</Text> (and refresh)
        </Text>
      </Timeline.Item>

      <Timeline.Item dot="?">
        <Text delete={props.hasOwner}>
          Compile and deploy your smart contract: <Text strong>yarn run deploy</Text>
        </Text>
      </Timeline.Item>

      <Timeline.Item dot="?">
        <Text delete={props.isNotSmoort}>
          Fix error in <Text code>SmartContractWallet.sol</Text> then: <Text strong>yarn run deploy</Text>
        </Text>
      </Timeline.Item>

      <Timeline.Item dot={<SendOutlined style={{ fontSize: "16px" }} />} color={props.hasEther ? "green" : "blue"}>
        <Text delete={props.hasEther}>
          Send test ether to your{" "}
          <Blockies seed={(props.address ? props.address : "").toLowerCase()} size={8} scale={2} /> address using
          (bottom left) faucet
        </Text>
      </Timeline.Item>

      <Timeline.Item
        dot={<DownloadOutlined style={{ fontSize: "16px" }} />}
        color={props.contractHasEther ? "green" : "blue"}
      >
        <Text delete={props.contractHasEther}>
          Deposit some funds into your{" "}
          <Blockies seed={(props.contractAddress ? props.contractAddress : "").toLowerCase()} size={8} scale={2} />{" "}
          smart contract wallet
        </Text>
      </Timeline.Item>

      <Timeline.Item
        dot={<EditOutlined style={{ fontSize: "16px" }} />}
        color={props.amOwnerOfContract ? "green" : "blue"}
      >
        <Text delete={props.amOwnerOfContract}>
          Set <b>owner</b> of your{" "}
          <Blockies seed={(props.contractAddress ? props.contractAddress : "").toLowerCase()} size={8} scale={2} />{" "}
          smart contract wallet to your{" "}
          <Blockies seed={(props.address ? props.address : "").toLowerCase()} size={8} scale={2} /> address
        </Text>
      </Timeline.Item>

      <Timeline.Item dot="☢️">
        <Text>
          Yikes, anyone can take ownership of <Text code>SmartContractWallet.sol</Text>
        </Text>
      </Timeline.Item>

      <Timeline.Item dot="?">
        <Text>
          Test your contract with <Text code>buidler/test/myTest.js</Text> then:
          <Text strong>yarn run test</Text>
        </Text>
      </Timeline.Item>

      <Timeline.Item dot="?">
        <Text>
          Build something awesome with ? <a href="https://github.com/austintgriffith/scaffold-eth">scaffold-eth</a> and{" "}
          <a target="_blank" rel="noopener noreferrer" href="https://twitter.com/austingriffith">
            @ me
          </a>
          !
        </Text>
      </Timeline.Item>

      <Timeline.Item dot="?">
        <Text>
          Read more about{" "}
          <a target="_blank" rel="noopener noreferrer" href="https://ethereum.org/developers">
            Ethereum
          </a>
          ,{" "}
          <a target="_blank" rel="noopener noreferrer" href="https://solidity.readthedocs.io/en/develop/contracts.html">
            Solidity
          </a>
          , and{" "}
          <a target="_blank" rel="noopener noreferrer" href="https://buidler.dev/tutorial">
            Buidler
          </a>
        </Text>
      </Timeline.Item>
    </Timeline>
  );
}
Example #20
Source File: adminChallenges.js    From ctf_platform with MIT License 4 votes vote down vote up
render() {
        return (

            <Layout style={{ height: "100%", width: "100%", backgroundColor: "rgba(0, 0, 0, 0)" }}>

                <Modal title={<span><UploadOutlined/> Upload Challenges</span>} visible={this.state.uploadModalVisible} footer={null} onCancel={() => {this.setState({uploadModalVisible: false})}}>
                    <UploadChallengesForm handleRefresh={this.handleRefresh.bind(this)} closeUploadChallenges={() => {this.setState({uploadModalVisible: false})}}/>
                </Modal>
                <div style={{ display: (!this.state.challengeCreate && !this.state.editChallenge) ? "initial" : "none" }}>
                    <div style={{ display: "flex", justifyContent: "space-between", alignItems: "center" }}>
                        <div style={{ display: "flex", alignItems: "center", height: "2ch" }}>
                            <Button type="primary" style={{ marginBottom: "2vh", marginRight: "1ch" }} icon={<FlagOutlined />} onClick={() => { this.setState({ challengeCreate: true }, this.props.history.push("/Admin/Challenges/Create")) }}>Create New Challenge</Button>
                            <Button type="primary" style={{ marginBottom: "2vh", marginRight: "1ch" }} icon={<UploadOutlined />} onClick={() => { this.setState({uploadModalVisible: true}) }}>Upload Challenges</Button>
                            {this.state.loading && (
                                <div style={{ display: "flex", justifyContent: "center", alignItems: "center" }}>
                                    <Ellipsis color="#177ddc" size={60} />
                                    <h1>Loading Challenges</h1>
                                </div>
                            )}
                        </div>
                        <Button loading={this.state.loading} type="primary" shape="circle" size="large" style={{ marginBottom: "2vh", maxWidth: "25ch" }} icon={<RedoOutlined />} onClick={async () => { await this.handleRefresh(); message.success("Challenge list refreshed.") }} />

                    </div>
                    <div style={{ display: "flex", alignItems: "center", justifyContent: "space-between" }}>
                        <div style={{ display: "flex", alignItems: "center" }}>
                            <Button disabled={this.state.disableEditButtons} type="default" style={{ marginBottom: "2vh", marginRight: "1ch", backgroundColor: "#6e6e6e" }} icon={<EyeOutlined style={{ color: "#49aa19" }} />} onClick={() => { this.editChallengeVisibility(true, this.state.selectedTableKeys, this.state.selectedRows) }}>Show</Button>
                            <Button disabled={this.state.disableEditButtons} type="default" style={{ marginBottom: "2vh", marginRight: "1ch", backgroundColor: "#6e6e6e" }} icon={<EyeInvisibleOutlined style={{ color: "#d32029" }} />} onClick={() => { this.editChallengeVisibility(false, this.state.selectedTableKeys, this.state.selectedRows) }}>Hide</Button>
                            <Button disabled={this.state.disableEditButtons} style={{ marginBottom: "2vh", marginRight: "1ch", backgroundColor: "#a61d24" }} icon={<DeleteOutlined />} onClick={() => {
                                confirm({
                                    confirmLoading: this.state.disableEditButtons,
                                    title: 'Are you sure you want to delete the challenge(s) (' + this.state.selectedTableKeys.join(", ") + ')? This action is irreversible.',
                                    icon: <ExclamationCircleOutlined />,
                                    onOk: (close) => { this.deleteChallenge(close.bind(this), this.state.selectedTableKeys, this.state.selectedRows) },
                                    onCancel: () => { },
                                });
                            }}>Delete Challenges</Button>
                        </div>
                        <div>
                            <Button disabled={this.state.disableEditButtons} type="primary" style={{ marginBottom: "2vh", marginRight: "1ch" }} icon={<DownloadOutlined />} onClick={() => { this.downloadChallenges(this.state.selectedRows) }}>Download</Button>
                        </div>
                    </div>
                    <Table rowSelection={{ selectedRowKeys: this.state.selectedTableKeys, onChange: this.handleTableSelect.bind(this) }} style={{ overflow: "auto" }} dataSource={this.state.dataSource} locale={{
                        emptyText: (
                            <div style={{ display: "flex", flexDirection: "column", alignItems: "center", justifyContent: "center", marginTop: "10vh" }}>
                                <FileUnknownTwoTone style={{ color: "#177ddc", fontSize: "400%", zIndex: 1 }} />
                                <h1 style={{ fontSize: "200%" }}>No Challenges Found/Created</h1>
                            </div>
                        )
                    }}>
                        <Column title="Name" dataIndex="name" key="name"
                            render={(text, row, index) => {
                                return <Link to={"/Challenges/" + row._id}><a style={{ fontWeight: 700 }}>{text}</a></Link>;
                            }}
                            filterDropdown={({ setSelectedKeys, selectedKeys, confirm, clearFilters }) => (
                                <div style={{ padding: 8 }}>
                                    <Input
                                        autoFocus
                                        placeholder="Search Challenge Name"
                                        value={selectedKeys[0]}
                                        onChange={e => setSelectedKeys(e.target.value ? [e.target.value] : [])}
                                        onPressEnter={() => confirm()}
                                        style={{ marginBottom: 8, display: 'block' }}
                                    />
                                    <Space>
                                        <Button
                                            type="primary"
                                            onClick={() => { confirm() }}
                                            icon={<SearchOutlined />}
                                        >
                                            Search
                                        </Button>
                                        <Button onClick={() => clearFilters()}>
                                            Reset
                                        </Button>
                                    </Space>
                                </div>
                            )}
                            onFilter={(value, record) => record.name.toLowerCase().trim().includes(value.toLowerCase())}
                            filterIcon={filtered => <SearchOutlined style={{ color: filtered ? '#1890ff' : undefined }} />}
                            sorter={(a, b) => {
                                if (a.name < b.name) return -1
                                else return 1
                            }}
                        />
                        <Column filters={this.state.allCat.map(value => { return { text: value.key, value: value.key } })} onFilter={(value, record) => value === record.category} title="Category" dataIndex="category" key="category" render={(text, row, index) => {
                            return <Link to={"/Challenges/" + row.category}><a style={{ fontWeight: 700 }}>{text}</a></Link>;
                        }} />
                        <Column sorter={(a, b) => a.points - b.points} title="Points" dataIndex="points" key="points" />
                        <Column sorter={(a, b) => a.points - b.points} title="Initial Points" dataIndex="initial" key="initial" />
                        <Column sorter={(a, b) => a.points - b.points} title="Solves to Min." dataIndex="minSolves" key="minSolves" />
                        <Column sorter={(a, b) => a.points - b.points} title="Min. Points" dataIndex="minimum" key="minimum" />
                        <Column filters={[{ text: "Visible", value: "true" }, { text: "Hidden", value: "false" }]} onFilter={(value, record) => { return value === record.visibility.props.visibility }} title="Visbility" dataIndex="visibility" key="visibility" />
                        <Column title="Required Challenge" dataIndex="requires" key="requires"
                            render={(text, row, index) => {
                                return <Link to={"/Challenges/" + text}><a style={{ fontWeight: 700 }}>{this.state.IDNameMapping[text]}</a></Link>;
                            }}
                            filterDropdown={({ setSelectedKeys, selectedKeys, confirm, clearFilters }) => (
                                <div style={{ padding: 8 }}>
                                    <Input
                                        autoFocus
                                        placeholder="Search Challenge Name"
                                        value={selectedKeys[0]}
                                        onChange={e => setSelectedKeys(e.target.value ? [e.target.value] : [])}
                                        onPressEnter={() => confirm()}
                                        style={{ marginBottom: 8, display: 'block' }}
                                    />
                                    <Space>
                                        <Button
                                            type="primary"
                                            onClick={() => { confirm() }}
                                            icon={<SearchOutlined />}
                                        >
                                            Search
                                        </Button>
                                        <Button onClick={() => clearFilters()}>
                                            Reset
                                        </Button>
                                    </Space>
                                </div>
                            )}
                            onFilter={(value, record) => { if (record.requires) return this.state.IDNameMapping[record.requires].toLowerCase().includes(value) }}
                            filterIcon={filtered => <SearchOutlined style={{ color: filtered ? '#1890ff' : undefined }} />}
                            sorter={(a, b) => {
                                if (!a.requires) return -1
                                if (!b.requires) return 1
                                if (this.state.IDNameMapping[a.requires] < this.state.IDNameMapping[b.requires]) return -1
                                else return 1
                            }}
                        />
                        <Column
                            title=""
                            key="edit"
                            render={(text, record) => (
                                <Button icon={<EditOutlined />} onClick={() => { this.setState({ editChallenge: true, id: record._id }); this.props.history.push("/Admin/Challenges/Edit") }}> Edit</Button>
                            )}
                        />
                    </Table>

                    <Divider />
                    <div style={{ display: "flex", alignItems: "center" }}>
                        <h1 style={{ fontSize: "150%" }}>Category Management </h1>{this.state.transferDisabled && (<Ellipsis color="#177ddc" size={50} />)}
                    </div>

                    <Card className="settings-card">
                        <h3>Category Meta Information Editor <EyeOutlined /></h3>
                        <p>Select a category to edit info such as Name, Cover Pictures etc.</p>

                        <Select style={{ width: "30ch" }} value={this.state.categorySelect} onChange={this.openCategoryEditor.bind(this)}>
                            {this.state.categoryOptions}
                        </Select>

                        {this.state.currentEditCategory && (
                            <div style={{ padding: "10px", marginTop: "20px", backgroundColor: "rgba(0, 0, 0, 0.3)", border: "5px solid transparent", borderRadius: "10px" }}>
                                <EditCategoryForm initialData={this.state.currentEditCategory} handleEditCategoryDone={this.handleEditCategoryDone.bind(this)} />
                            </div>
                        )}
                    </Card>
                    <Card className="settings-card">
                        <h3>Category Visibility <EyeOutlined /></h3>
                        <Transfer
                            dataSource={this.state.allCat}
                            titles={[<span style={{ color: "#49aa19" }}>Visible Categories <EyeOutlined /></span>, <span style={{ color: "#d32029" }} >Hidden Categories <EyeInvisibleOutlined /></span>]}
                            targetKeys={this.state.targetKeys}
                            selectedKeys={this.state.selectedKeys}
                            onChange={this.handleChange}
                            onSelectChange={this.handleSelectChange}
                            render={item => item.key}
                            pagination
                            disabled={this.state.transferDisabled}
                        />
                    </Card>

                    <Divider />

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

                        <Card className="settings-card">
                            <h3>Disable Submissions:  <AntdSwitch disabled={this.state.disableLoading} onClick={(value) => this.disableSetting("submissionDisabled", value)} checked={this.state.submissionDisabled} /></h3>
                            <p>Prevents users from submitting any new submissions for all challenges. Hints can still be bought</p>
                        </Card>

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

                        <Card className="settings-card">
                            <h3>Set Socket Limit:  <InputNumber
                                value={this.state.maxSockets}
                                disabled={this.state.disableLoading}
                                onChange={(value) => this.setState({ maxSockets: value })}
                                onPressEnter={(e) => { this.changeSetting("maxSockets", this.state.maxSockets) }} /></h3>
                            <p>Sets the maximum number of socket connections allowed <b>per account</b> to connect to the live scoreboard. <br /> <b>Press "Enter" to save</b></p>
                        </Card>

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

                        <Card className="settings-card">
                        <h3>Disable First Blood for No Category:  <AntdSwitch disabled={this.state.disableLoading} onClick={(value) => this.disableSetting("disableNonCatFB", value)} checked={this.state.disableNonCatFB} /></h3>
                            <p>Prevents people with no categories from attaining first blood. Useful if you want to limit First Blood prizes to only eligible participants.</p>
                        </Card>


                    </div>


                </div>


                <Switch>
                    <Route exact path='/Admin/Challenges/Create' render={(props) => <AdminChallengeCreate {...props} challenges={this.state.dataSource} handleBack={this.handleBack.bind(this)} handleCreateBack={this.handleCreateBack.bind(this)} allCat={this.state.allCat} />} />
                    <Route exact path='/Admin/Challenges/Edit' render={(props) => <AdminChallengeEdit {...props} allCat={this.state.allCat} IDNameMapping={this.state.IDNameMapping} challenges={this.state.dataSource} id={this.state.id} handleEditBack={this.handleEditBack.bind(this)} handleEditChallBack={this.handleEditChallBack.bind(this)} />} />

                </Switch>

            </Layout>
        );
    }
Example #21
Source File: index.js    From pretty-derby with GNU General Public License v3.0 4 votes vote down vote up
Nurturing = (props) => {
  const { t } = useTranslation();
  const history = useHistory();
  document.title = TITLE;
  useDidRecover(() => {
    document.title = TITLE;
  });
  const [needSelect, setNeedSelect] = useState(false);
  const [isPlayerVisible, setIsPlayerVisible] = useState(false);

  const [isSupportVisible, setIsSupportVisible] = useState(false);
  const [supportIndex, setSupportIndex] = useState(1);

  // const [isRaceVisible, setIsRaceVisible] = useState(false);

  const selected = dbL.get("selected").value();
  const [supports, setSupports] = useState(selected.supports);
  const [player, setPlayer] = useState(selected.player);
  const [raceFilterCondition, setRaceFilterCondition] = useState(
    selected.raceFilterCondition || {
      distanceType: [],
      grade: [],
      ground: [],
    }
  );
  const [filterRace, setFilterRace] = useState(selected.filterRace || {});
  const [decks, setDecks] = useState(dbL.get("myDecks").value());
  const db = useDB();
  if (!db) return null;
  const races = db.get("races").value();
  const showPlayer = () => {
    setIsPlayerVisible(true);
  };
  const closePlayer = () => {
    setIsPlayerVisible(false);
  };
  const handleSelectPlayer = (data) => {
    setIsPlayerVisible(false);
    setPlayer(data);

    // save
    selected.player = data;
    dbL.get("selected").assign(selected).write();
    closePlayer();
  };

  const showSupport = (index) => {
    setNeedSelect(true);
    setIsSupportVisible(true);
    setSupportIndex(index);
  };
  const showSupport2 = (index) => {
    setNeedSelect(false);
    setIsSupportVisible(true);
    setSupportIndex(index);
  };

  const closeSupport = () => {
    setIsSupportVisible(false);
  };
  const handleSelectSupport = (data) => {
    let newData = {};
    newData[supportIndex] = data;
    setSupports(Object.assign({}, supports, newData));
    setIsSupportVisible(false);

    // save
    selected.supports[supportIndex] = data;
    dbL.get("selected").assign(selected).write();
    closeSupport();
  };
  const handleSelectSupportShow = (data) => {
    history.push(`/support-detail/${data.id}`);
    closeSupport();
  };
  // 卡组相关操作
  const saveDeck = (deck) => {
    let tmpDeck = {
      imgUrls: [],
      supportsId: [],
    };
    if (player.id) {
      tmpDeck.playerId = player.id;
      tmpDeck.imgUrls.push(player.imgUrl);
    }
    [0, 1, 2, 3, 4, 5].forEach((index) => {
      if (supports[index] && supports[index].id) {
        tmpDeck.imgUrls.push(supports[index].imgUrl);
        tmpDeck.supportsId.push(supports[index].id);
      } else {
        tmpDeck.supportsId.push(null);
      }
    });
    if (deck) {
      //update
      dbL.get("myDecks").find({ id: deck.id }).assign(tmpDeck).write();
    } else {
      //
      tmpDeck.id = shortid.generate();
      dbL.get("myDecks").push(tmpDeck).write();
    }
    setDecks([...dbL.get("myDecks").value()]);
  };
  const loadDeck = (deck) => {
    selected.supports = { 0: {}, 1: {}, 2: {}, 3: {}, 4: {}, 5: {} };
    selected.player = {};
    if (deck.playerId) {
      selected.player = db.get("players").find({ id: deck.playerId }).value();
    }
    setPlayer(selected.player);
    deck.supportsId.forEach((id, index) => {
      if (id) {
        selected.supports[index] = db.get("supports").find({ id: id }).value();
      }
    });
    setSupports({ ...selected.supports });
    db.get("selected").assign(selected).write();
  };
  const deleteDeck = (deck) => {
    dbL.get("myDecks").remove({ id: deck.id }).write();
    setDecks([...dbL.get("myDecks").value()]);
  };
  // race checkbox发生变化
  const onChangeRace = (filterCondition) => {
    setRaceFilterCondition(filterCondition);
    //根据条件过滤
    let tmpRaceList = Object.values(filterCondition).some((f) => f.length > 0)
      ? Object.entries(filterCondition)
          .filter(([key, filters]) => filters.length > 0)
          .reduce(
            (result, [key, filters]) => result.filter((race) => filters.includes(race[key])),
            races
          )
      : [];
    //过滤后整理成 dataNum:[raceId]
    let tmpFilterRace = {};
    for (let race of tmpRaceList) {
      if (tmpFilterRace[race.dateNum]) {
        tmpFilterRace[race.dateNum].push(race.id);
      } else {
        tmpFilterRace[race.dateNum] = [race.id];
      }
    }
    //更新state
    setFilterRace(tmpFilterRace);
    selected.raceFilterCondition = filterCondition;
    selected.filterRace = tmpFilterRace;
    dbL
      .get("selected")
      .assign({ ...selected })
      .write();
  };

  const toSupportDetail = (id) => {
    props.history.push(`/support-detail/${id}`);
  };
  const toPlayerDetail = (id) => {
    props.history.push(`/player-detail/${id}/1`);
  };
  const toBuffList = (id) => {
    props.history.push(`/buff`);
  };

  return (
    <>
      <div style={{ display: "flex", justifyContent: "center" }}>
        {player.imgUrl && (
          <img
            src={CDN_SERVER + player.imgUrl}
            alt={player.imgUrl}
            width="128"
            onClick={() => toPlayerDetail(player.id)}
          />
        )}
        <div className="flex-auto flex flex-wrap items-center">
          <Button size="sm" buttonType="outline" onClick={showPlayer}>
            {t("选择马娘")}
          </Button>
          <Button size="sm" buttonType="outline" onClick={showSupport2}>
            {t("支援卡查询")}
          </Button>
          <Button size="sm" buttonType="outline" onClick={toBuffList}>
            {t("BUFF")}
          </Button>
          <Popover
            trigger="click"
            content={
              <RaceCheckbox onChange={onChangeRace} raceFilterCondition={raceFilterCondition} />
            }
          >
            <Button>{t("比赛")}</Button>
          </Popover>
          <Popover
            trigger="click"
            width={"80%"}
            content={
              <>
                <Button size="sm" buttonType="outline" onClick={() => saveDeck()}>
                  {t("保存为新卡组")}
                </Button>
                {decks.map((deck) => (
                  <Row key={deck.id}>
                    {deck.imgUrls.map((imgUrl) => (
                      <Col span={3} key={imgUrl}>
                        <img src={CDN_SERVER + imgUrl} alt={imgUrl} width={"100"} />
                      </Col>
                    ))}
                    <Col span={3}>
                      <Button
                        size="sm"
                        buttonType="outline"
                        type="primary"
                        onClick={() => loadDeck(deck)}
                      >
                        {t("读取卡组")}
                      </Button>
                      <Popconfirm title="确认覆盖?" onConfirm={() => saveDeck(deck)}>
                        <Button size="sm" buttonType="outline" danger type="dashed">
                          {t("覆盖卡组")}
                        </Button>
                      </Popconfirm>
                      <Popconfirm title="确认删除?" onConfirm={() => deleteDeck(deck)}>
                        <Button size="sm" buttonType="outline" danger type="dashed">
                          {t("删除卡组")}
                        </Button>
                      </Popconfirm>
                    </Col>
                  </Row>
                ))}
              </>
            }
          >
            <Button>{t("我的卡组")}</Button>
          </Popover>
        </div>
      </div>

      <Row justify="space-around">
        {[0, 1, 2, 3, 4, 5].map((index) => (
          <Col span={7} key={index} style={{}}>
            <Button
              size="sm"
              buttonType="outline"
              icon={<EditOutlined />}
              onClick={() => showSupport(index)}
            >
              {t("选择支援卡")}
            </Button>
            {supports[index] && supports[index].id && (
              <img
                src={CDN_SERVER + supports[index].imgUrl}
                alt={supports[index].name}
                width={"100%"}
                onClick={() => toSupportDetail(supports[index].id)}
              />
            )}
          </Col>
        ))}
      </Row>

      <Divider>比赛</Divider>
      <div style={{ overflow: "auto", paddingTop: "10px", width: "100%", height: "400px" }}>
        <RaceTimeline raceList={player.raceList} filterRace={filterRace} />
      </div>

      <Modal
        visible={isPlayerVisible}
        onOk={closePlayer}
        onCancel={closePlayer}
        footer={null}
        width={"100%"}
        bodyStyle={{ maxHeight: "80vh", overflow: "auto" }}
      >
        <PlayerList sortFlag={true} onClick={handleSelectPlayer} />
      </Modal>
      <Modal
        visible={isSupportVisible}
        onOk={closeSupport}
        onCancel={closeSupport}
        footer={null}
        width={"100%"}
        bodyStyle={{ height: "80vh", overflow: "auto" }}
      >
        <SupportListWithFilter
          formName="nurSupMo"
          onClick={needSelect ? handleSelectSupport : handleSelectSupportShow}
          sortFlag={true}
        />
      </Modal>
    </>
  );
}
Example #22
Source File: index.jsx    From prometheusPro with MIT License 4 votes vote down vote up
Applications = props => {
  const { list } = props;
  const itemMenu = (
    <Menu>
      <Menu.Item>
        <a target="_blank" rel="noopener noreferrer" href="https://www.alipay.com/">
          1st menu item
        </a>
      </Menu.Item>
      <Menu.Item>
        <a target="_blank" rel="noopener noreferrer" href="https://www.taobao.com/">
          2nd menu item
        </a>
      </Menu.Item>
      <Menu.Item>
        <a target="_blank" rel="noopener noreferrer" href="https://www.tmall.com/">
          3d menu item
        </a>
      </Menu.Item>
    </Menu>
  );

  const CardInfo = ({ activeUser, newUser }) => (
    <div className={stylesApplications.cardInfo}>
      <div>
        <p>活跃用户</p>
        <p>{activeUser}</p>
      </div>
      <div>
        <p>新增用户</p>
        <p>{newUser}</p>
      </div>
    </div>
  );

  return (
    <List
      rowKey="id"
      className={stylesApplications.filterCardList}
      grid={{
        gutter: 24,
        xxl: 3,
        xl: 2,
        lg: 2,
        md: 2,
        sm: 2,
        xs: 1,
      }}
      dataSource={list}
      renderItem={item => (
        <List.Item key={item.id}>
          <Card
            hoverable
            bodyStyle={{
              paddingBottom: 20,
            }}
            actions={[
              <Tooltip key="download" title="下载">
                <DownloadOutlined />
              </Tooltip>,
              <Tooltip title="编辑" key="edit">
                <EditOutlined />
              </Tooltip>,
              <Tooltip title="分享" key="share">
                <ShareAltOutlined />
              </Tooltip>,
              <Dropdown overlay={itemMenu} key="ellipsis">
                <EllipsisOutlined />
              </Dropdown>,
            ]}
          >
            <Card.Meta avatar={<Avatar size="small" src={item.avatar} />} title={item.title} />
            <div className={stylesApplications.cardItemContent}>
              <CardInfo
                activeUser={formatWan(item.activeUser)}
                newUser={numeral(item.newUser).format('0,0')}
              />
            </div>
          </Card>
        </List.Item>
      )}
    />
  );
}
Example #23
Source File: adminSubmissions.js    From ctf_platform with MIT License 4 votes vote down vote up
render() {
        return (

            <Layout style={{ height: "100%", width: "100%", backgroundColor: "rgba(0, 0, 0, 0)" }}>

                <Modal
                    title="Create New Transaction"
                    visible={this.state.createTModal}
                    footer={null}
                    onCancel={() => { this.setState({ createTModal: false }) }}
                >

                    <CreateT refresh={this.refresh.bind(this)} challengeList={this.state.challengeList} setState={this.setState.bind(this)}></CreateT>
                </Modal>

                <Modal
                    title="Edit Transaction"
                    visible={this.state.editTModal}
                    footer={null}
                    destroyOnClose
                    onCancel={() => { this.setState({ editTModal: false }) }}
                >

                    <EditT initialData={this.state.initialData} refresh={this.refresh.bind(this)} challengeList={this.state.challengeList} setState={this.setState.bind(this)}></EditT>
                </Modal>

                <div style={{ display: "flex", justifyContent: "space-between", alignItems: "center" }}>
                    <div style={{ display: "flex", alignItems: "center", height: "2ch" }}>
                        <Button type="primary" style={{ marginBottom: "2vh", marginRight: "1ch" }} icon={<FileOutlined />} onClick={() => { this.setState({ createTModal: true }) }}>Create New Transaction</Button>
                        {this.state.loading && (
                            <div style={{ display: "flex", justifyContent: "center", alignItems: "center" }}>
                                <Ellipsis color="#177ddc" size={60} ></Ellipsis>
                                <h1>Loading Transactions</h1>
                            </div>
                        )}
                    </div>
                    <Button loading={this.state.loading} type="primary" shape="circle" size="large" style={{ marginBottom: "2vh", maxWidth: "25ch" }} icon={<RedoOutlined />} onClick={async () => { await this.fillTableData(); message.success("Submissions list refreshed.") }} />
                </div>
                <div style={{ display: "flex", alignItems: "center" }}>
                    <Button disabled={this.state.disableEditButtons} style={{ marginBottom: "2vh", marginRight: "1ch", backgroundColor: "#a61d24" }} icon={<DeleteOutlined />} onClick={() => {
                        confirm({
                            confirmLoading: this.state.disableEditButtons,
                            title: 'Are you sure you want to delete the transactions(s) [' + this.state.selectedTableKeys.join(", ") + ']? This action is irreversible.',
                            icon: <ExclamationCircleOutlined />,
                            onOk: (close) => { this.deleteTransactions(close.bind(this), this.state.selectedTableKeys) },
                            onCancel: () => { },
                        });
                    }}>Delete Transactions</Button>
                </div>
                <Table rowSelection={{ selectedRowKeys: this.state.selectedTableKeys, onChange: this.handleTableSelect.bind(this) }} style={{ overflow: "auto" }} dataSource={this.state.dataSource} locale={{
                    emptyText: (
                        <div style={{ display: "flex", flexDirection: "column", alignItems: "center", justifyContent: "center", marginTop: "10vh" }}>
                            <FileUnknownTwoTone style={{ color: "#177ddc", fontSize: "400%", zIndex: 1 }} />
                            <h1 style={{ fontSize: "200%" }}>No Submissions Found/Created.</h1>
                        </div>
                    )
                }}>
                    <Column title="Time" dataIndex="timestamp" key="timestamp" />
                    <Column title="Submittor" dataIndex="author" key="author" render={(text, row, index) => {
                        return <Link to={"/Profile/" + text}><a style={{ fontWeight: 700 }}>{text}</a></Link>;
                    }}
                        filterDropdown={({ setSelectedKeys, selectedKeys, confirm, clearFilters }) => (
                            <div style={{ padding: 8 }}>
                                <Input
                                    placeholder="Search Submittor"
                                    value={selectedKeys[0]}
                                    onChange={e => setSelectedKeys(e.target.value ? [e.target.value] : [])}
                                    onPressEnter={() => confirm()}
                                    style={{ marginBottom: 8, display: 'block' }}
                                />
                                <Space>
                                    <Button
                                        type="primary"
                                        onClick={() => { confirm() }}
                                        icon={<SearchOutlined />}
                                    >
                                        Search
                                    </Button>
                                    <Button onClick={() => clearFilters()}>
                                        Reset
                                    </Button>
                                </Space>
                            </div>
                        )}
                        onFilter={(value, record) => record.author.toLowerCase().trim().includes(value.toLowerCase())}
                        filterIcon={filtered => <SearchOutlined style={{ color: filtered ? '#1890ff' : undefined }} />}

                    />
                    <Column title="Team" dataIndex="team" key="team" render={(text, row, index) => {
                        return <Link to={"/Team/" + text}><a style={{ fontWeight: 700 }}>{text}</a></Link>;
                    }}
                        filterDropdown={({ setSelectedKeys, selectedKeys, confirm, clearFilters }) => (
                            <div style={{ padding: 8 }}>
                                <Input
                                    placeholder="Search Team"
                                    value={selectedKeys[0]}
                                    onChange={e => setSelectedKeys(e.target.value ? [e.target.value] : [])}
                                    onPressEnter={() => confirm()}
                                    style={{ marginBottom: 8, display: 'block' }}
                                />
                                <Space>
                                    <Button
                                        type="primary"
                                        onClick={() => { confirm() }}
                                        icon={<SearchOutlined />}
                                    >
                                        Search
                                    </Button>
                                    <Button onClick={() => clearFilters()}>
                                        Reset
                                    </Button>
                                </Space>
                            </div>
                        )}
                        onFilter={(value, record) => record.team.toLowerCase().trim().includes(value.toLowerCase())}
                        filterIcon={filtered => <SearchOutlined style={{ color: filtered ? '#1890ff' : undefined }} />}

                    />
                    <Column title="Category" dataIndex="category" key="category" filters={
                        this.state.categoryList.map((category) => {
                            return { text: category, value: category }
                        })} onFilter={(value, record) => { return value === record.category }} />
                    <Column render={(text, row, index) => {
                        return <Link to={"/Challenges/" + row.challengeID}><a style={{ fontWeight: 700 }}>{text}</a></Link>;
                    }} title="Challenge" dataIndex="challenge" key="challenge"
                        filterDropdown={({ setSelectedKeys, selectedKeys, confirm, clearFilters }) => (
                            <div style={{ padding: 8 }}>
                                <Input
                                    placeholder="Search Challenge Name"
                                    value={selectedKeys[0]}
                                    onChange={e => setSelectedKeys(e.target.value ? [e.target.value] : [])}
                                    onPressEnter={() => confirm()}
                                    style={{ marginBottom: 8, display: 'block' }}
                                />
                                <Space>
                                    <Button
                                        type="primary"
                                        onClick={() => { confirm() }}
                                        icon={<SearchOutlined />}
                                    >
                                        Search
                                    </Button>
                                    <Button onClick={() => clearFilters()}>
                                        Reset
                                    </Button>
                                </Space>
                            </div>
                        )}
                        onFilter={(value, record) => record.challenge.toLowerCase().trim().includes(value.toLowerCase())}
                        filterIcon={filtered => <SearchOutlined style={{ color: filtered ? '#1890ff' : undefined }} />} />
                    <Column title="Hint ID" dataIndex="hint_id" key="hint_id" filterDropdown={({ setSelectedKeys, selectedKeys, confirm, clearFilters }) => (
                        <div style={{ padding: 8 }}>
                            <Input
                                placeholder="Search Hint ID"
                                value={selectedKeys[0]}
                                onChange={e => setSelectedKeys(e.target.value ? [e.target.value] : [])}
                                onPressEnter={() => confirm()}
                                style={{ marginBottom: 8, display: 'block' }}
                            />
                            <Space>
                                <Button
                                    type="primary"
                                    onClick={() => { confirm() }}
                                    icon={<SearchOutlined />}
                                >
                                    Search
                                </Button>
                                <Button onClick={() => clearFilters()}>
                                    Reset
                                </Button>
                            </Space>
                        </div>
                    )}
                        onFilter={(value, record) => record.hint_id == parseInt(value)}
                        filterIcon={filtered => <SearchOutlined style={{ color: filtered ? '#1890ff' : undefined }} />} />
                    <Column title="Type" dataIndex="type" key="type" filters={[{ text: "Submission", value: "submission" }, { text: "Hint", value: "hint" }, { text: "Blocked Submission", value: "blocked_submission" }, { text: "Initial Register", value: "initial_register" }]} onFilter={(value, record) => { return value === record.type }} />
                    <Column title="Points Awarded" dataIndex="points" key="points" sorter={(a, b) => a.points - b.points} />

                    <Column title="Flag Submitted" dataIndex="submission" key="submission" />
                    <Column title="Correct" dataIndex="correct" key="correct" filters={[{ text: "✅", value: "✅" }, { text: "❌", value: "❌" }]} onFilter={(value, record) => { return value === record.correct }} />
                    <Column
                        title=""
                        key="edit"
                        render={(text, record) => (
                            <Button icon={<EditOutlined />} onClick={() => { this.setState({ editTModal: true, initialData: record }) }}> Edit</Button>
                        )}
                    />
                </Table>
            </Layout >
        );
    }
Example #24
Source File: HierarchicalTree.test.jsx    From ui with MIT License 4 votes vote down vote up
describe('HierarchicalTree', () => {
  it('Renders correctly', () => {
    const treeData = [{
      key: '1',
      name: 'my element',
      rootNode: false,
      color: '#000000',
    }];

    const component = mount(
      <HierarchicalTree treeData={treeData} experimentId={fake.EXPERIMENT_ID} />,
    );
    waitForComponentToPaint(component);
    const tree = component.find('HierarchicalTree Tree');
    expect(tree).toHaveLength(1);
  });

  it('can drag first component at the last position', () => {
    const treeData = [
      {
        key: '1',
        name: 'element 1',
        rootNode: true,
        children: [
          firstChild,
          secondChild,
          thirdChild,
        ],
      },
    ];

    const dropInfo = {
      dragNode: {
        ...firstChild,
        pos: '0-0-0',
      },
      dropPosition: 2,
      dropToGap: true,
      node: {
        ...thirdChild,
        pos: '0-0-3',
      },
    };

    const mockOnCellSetReorder = jest.fn();
    const component = mount(
      <HierarchicalTree
        experimentId={fake.EXPERIMENT_ID}
        treeData={treeData}
        onCellSetReorder={mockOnCellSetReorder}
      />,
    );
    waitForComponentToPaint(component);
    const tree = component.find('HierarchicalTree Tree');

    tree.getElement().props.onDrop(dropInfo);
    component.update();

    expect(mockOnCellSetReorder).toHaveBeenCalledTimes(1);
    const [cellSetKey, newPosition] = mockOnCellSetReorder.mock.calls[0];

    expect(cellSetKey).toEqual('1a');
    expect(newPosition).toEqual(1);
  });

  it('Can\'t have child component change parent', () => {
    const treeData = [
      {
        key: '1',
        name: 'parent 1',
        rootNode: true,
        children: [
          firstChild,
        ],
      },
      secondParent,
    ];

    const dropInfo = {
      dragNode: {
        ...firstChild,
        pos: '0-0-0',
      },
      dropPosition: 1,
      dropToGap: true,
      node: {
        ...secondParent,
        pos: '0-1-2',
      },
    };

    const mockOnCellSetReorder = jest.fn();
    const component = mount(
      <HierarchicalTree
        treeData={treeData}
        experimentId={fake.EXPERIMENT_ID}
        onCellSetReorder={mockOnCellSetReorder}
      />,
    );
    waitForComponentToPaint(component);
    const tree = component.find('HierarchicalTree Tree');
    tree.getElement().props.onDrop(dropInfo);
    component.update();

    expect(mockOnCellSetReorder).toHaveBeenCalledTimes(0);
  });

  it("Can't drop parent inside node", () => {
    const treeData = [
      firstParent,
      secondParent,
    ];

    const dropInfo = {
      dragNode: {
        ...secondParent,
        pos: '0-0',
      },
      dropPosition: 1,
      dropToGap: true,
      node: {
        ...firstParent,
        pos: '0-0-1',
      },
    };

    const mockOnCellSetReorder = jest.fn();

    const component = mount(
      <HierarchicalTree
        treeData={treeData}
        experimentId={fake.EXPERIMENT_ID}
        onCellSetReorder={mockOnCellSetReorder}
      />,
    );
    waitForComponentToPaint(component);
    const tree = component.find('HierarchicalTree Tree');
    tree.getElement().props.onDrop(dropInfo);
    component.update();

    expect(mockOnCellSetReorder).toHaveBeenCalledTimes(0);
  });

  it("Can't drag child across parent nodes", () => {
    const treeData = [
      firstParent,
      secondParent,
    ];

    const dropInfo = {
      dragNode: {
        ...firstChild,
        pos: '0-0-1',
      },
      dropPosition: 4,
      dropToGap: true,
      node: {
        ...secondParent,
        pos: '0-1-0',
      },
    };

    const mockOnCellSetReorder = jest.fn();

    const component = mount(
      <HierarchicalTree
        treeData={treeData}
        experimentId={fake.EXPERIMENT_ID}
        onCellSetReorder={mockOnCellSetReorder}
      />,
    );

    waitForComponentToPaint(component);
    const tree = component.find('HierarchicalTree Tree');
    tree.getElement().props.onDrop(dropInfo);
    component.update();

    expect(mockOnCellSetReorder).toHaveBeenCalledTimes(0);
  });

  it("Doesn't trigger drop if positions don't change", () => {
    const treeData = [
      firstParent,
      secondParent,
    ];

    const dropInfo = {
      dragNode: {
        ...firstChild,
        pos: '0-0-1',
      },
      dropPosition: 1,
      dropToGap: true,
      node: {
        ...firstChild,
        key: '1b',
        pos: '0-0-1',
      },
    };

    const mockOnCellSetReorder = jest.fn();

    const component = mount(
      <HierarchicalTree
        treeData={treeData}
        experimentId={fake.EXPERIMENT_ID}
        onCellSetReorder={mockOnCellSetReorder}
      />,
    );

    waitForComponentToPaint(component);
    const tree = component.find('HierarchicalTree Tree');
    tree.getElement().props.onDrop(dropInfo);
    component.update();

    expect(mockOnCellSetReorder).toHaveBeenCalledTimes(0);
  });

  it("Can't drop into a child, only in a gap", () => {
    const treeData = [
      firstParent,
      secondParent,
    ];

    const dropInfo = {
      dragNode: {
        ...firstChild,
        pos: '0-0-1',
      },
      dropPosition: 4,
      dropToGap: false,
      node: {
        ...firstChild,
        key: '1b',
        pos: '0-0-5',
      },
    };

    const mockOnCellSetReorder = jest.fn();

    const component = mount(
      <HierarchicalTree
        treeData={treeData}
        experimentId={fake.EXPERIMENT_ID}
        onCellSetReorder={mockOnCellSetReorder}
      />,
    );

    waitForComponentToPaint(component);
    const tree = component.find('HierarchicalTree Tree');
    tree.getElement().props.onDrop(dropInfo);
    component.update();

    expect(mockOnCellSetReorder).toHaveBeenCalledTimes(0);

    // but dropToGap: false can be false when the dropInfo is rootNode
    // (we see this when we are moving the cell set into the first spot)
    const newDropInfo = {
      ...dropInfo,
      node: {
        ...firstParent,
        pos: '0-0',
      },
    };

    tree.getElement().props.onDrop(newDropInfo);
    component.update();
    expect(mockOnCellSetReorder).toHaveBeenCalledTimes(1);
  });

  it('tree data is not checked by default', async () => {
    const treeData = [{ key: 'louvain' }];
    const mockOnCheck = jest.fn();

    const component = mount(
      <HierarchicalTree
        treeData={treeData}
        experimentId={fake.EXPERIMENT_ID}
        onCheck={mockOnCheck}
      />,
    );

    await waitForComponentToPaint(component);

    expect(mockOnCheck).toHaveBeenCalledTimes(0);
  });

  it('triggers onNodeUpdate if a color was changed', async () => {
    const treeData = [
      firstParent,
    ];

    const mockOnNodeUpdate = jest.fn();

    const component = mount(
      <HierarchicalTree
        treeData={treeData}
        experimentId={fake.EXPERIMENT_ID}
        onNodeUpdate={mockOnNodeUpdate}
      />,
    );

    await waitForComponentToPaint(component);

    // Only 2 color pickers are shown
    expect(component.find('ColorPicker')).toHaveLength(2);

    // On changing one color
    const childColorPicker = component.find('ColorPicker').at(0);
    childColorPicker.getElement().props.onColorChange('white');
    component.update();

    // The callback is triggered
    expect(mockOnNodeUpdate).toHaveBeenCalledTimes(1);
    expect(mockOnNodeUpdate).toHaveBeenCalledWith('1a', { color: 'white' });
  });

  it('triggers onNodeUpdate if a name was changed', async () => {
    const treeData = [
      firstParent,
    ];

    const mockOnNodeUpdate = jest.fn();

    const component = mount(
      <HierarchicalTree
        treeData={treeData}
        experimentId={fake.EXPERIMENT_ID}
        onNodeUpdate={mockOnNodeUpdate}
      />,
    );

    await waitForComponentToPaint(component);

    const childEditableField = component.find('EditableField').at(0);
    const parentEditableField = component.find('EditableField').at(2);

    // The child node can be edited
    expect(childEditableField.find(EditOutlined)).toHaveLength(1);

    // The root node scratchpad can't be edited
    expect(parentEditableField.find(EditOutlined)).toHaveLength(0);

    // When we edit
    childEditableField.getElement().props.onAfterSubmit('New name');
    component.update();

    // Callback is triggered
    expect(mockOnNodeUpdate).toHaveBeenCalledTimes(1);
    expect(mockOnNodeUpdate).toHaveBeenCalledWith('1a', { name: 'New name' });
  });

  it('triggers onNodeDelete if a node was deleted', async () => {
    const treeData = [
      firstParent,
    ];

    const mockOnNodeDelete = jest.fn();

    const component = mount(
      <HierarchicalTree
        treeData={treeData}
        experimentId={fake.EXPERIMENT_ID}
        onNodeDelete={mockOnNodeDelete}
      />,
    );

    await waitForComponentToPaint(component);

    const childEditableField = component.find('EditableField').at(0);
    const parentEditableField = component.find('EditableField').at(2);

    // The child node can be edited
    expect(childEditableField.find(DeleteOutlined)).toHaveLength(1);

    // The root node scratchpad can't be deleted
    expect(parentEditableField.find(DeleteOutlined)).toHaveLength(0);

    childEditableField.getElement().props.onDelete();
    component.update();

    expect(mockOnNodeDelete).toHaveBeenCalledTimes(1);
    expect(mockOnNodeDelete).toHaveBeenCalledWith('1a');
  });

  it('Doesn\'t crash if callbacks aren\'t defined', async () => {
    const treeData = [
      firstParent,
    ];

    const component = mount(
      <HierarchicalTree
        treeData={treeData}
        experimentId={fake.EXPERIMENT_ID}
      />,
    );

    const childEditableField = component.find('EditableField').at(0);
    const childColorPicker = component.find('ColorPicker').at(0);
    const tree = component.find('HierarchicalTree Tree');

    childEditableField.getElement().props.onDelete();
    component.update();

    childEditableField.getElement().props.onAfterSubmit();
    component.update();

    childColorPicker.getElement().props.onColorChange();
    component.update();

    tree.getElement().props.onCheck();
    component.update();

    const dropInfo = {
      dragNode: {
        ...firstChild,
        pos: '0-0-0',
      },
      dropPosition: 2,
      dropToGap: true,
      node: {
        ...secondChild,
        pos: '0-0-1',
      },
    };

    tree.getElement().props.onDrop(dropInfo);
    component.update();
  });
});
Example #25
Source File: incident_table.js    From art-dashboard-ui with Apache License 2.0 4 votes vote down vote up
render() {

        const columns = [
            {
              title: "Incident ID",
              key: "pk",
              dataIndex: "pk"
            },
            {
                title: "Start Time",
                render: (data, record) => {
                    let start_time = null;
                    if (record["fields"]["incident_start"] === null){
                        start_time = "Not Available";
                    }else{
                        start_time = record["fields"]["incident_start"];
                        start_time = start_time.split("Z")[0];
                        start_time = start_time.split("T");
                        start_time = start_time[0] + " " + start_time[1].split(".")[0];
                    }
                    return (
                        <div>
                            <p>{start_time}</p>
                        </div>
                    )
                }
            },
            {
                title: "End Time",
                render: (data, record) => {
                    let end_time = null;
                    if (record["fields"]["incident_end"] === null){
                        end_time = "Not Available";
                    }else{
                        end_time = record["fields"]["incident_end"];
                        end_time = end_time.split("Z")[0];
                        end_time = end_time.split("T");
                        end_time = end_time[0] + " " + end_time[1].split(".")[0];
                    }
                    return (
                        <div>
                            <p>{end_time}</p>
                        </div>
                    )
                }
            },
            {
                title: "Title",
                render: (data, record) => {
                    return(
                        <div>
                            <Paragraph ellipsis={{rows: 2, expandable: false}}> {record["fields"]["title"]}</Paragraph>
                        </div>
                    )
                }
            },
            {
                title: "Update",
                render: (data, record) => {
                    return(
                            <div>
                                <a>
                                    <EditOutlined  onClick={() => this.props.history.push("/incidents/?page=update&id="+record["pk"])}/>
                                </a>
                                <Update_incident_drawer visibility = {this.state["visible_update_"+record["pk"]]} data={record} modal_close_function={this.hide_incident_update_view} refresh_callback={this.props.refresh_callback}/>
                            </div>
                        )

                }
            },
            {
                title: "Detailed View",
                render: (data, record) =>{
                    return(
                        <div>
                            <a>
                                <a>
                                    {/*<ExpandOutlined  onClick={() => this.show_incident_detailed_view(record)}/>*/}
                                    <ExpandOutlined  onClick={() => this.props.history.push("/incidents/?page=detailed&id="+record["pk"])}/>
                                </a>
                            </a>
                            <Detailed_view_modal visible= {this.state["visible_modal_"+record["pk"]]} data={record} modal_close_function={this.hide_incident_detailed_view} update_view_show_callback={this.show_update_view_callback_from_detailed_view}/>
                        </div>
                    )
                }
            },
            {
                title: "Delete",
                render: (data, record) =>{
                    return(
                        <div>
                            <Popconfirm
                                title="Are you sure you want to delete this incident record?"
                                onConfirm={() => {
                                    delete_incident(record["pk"]).then(data=>{
                                        if(data["status"] === 0){
                                            message.success({content: "Incident Deleted", duration: 2, style: {position: "fixed", left: "50%", top: "20%", color: "#316DC1"}})
                                            this.props.refresh_callback();
                                        }else{
                                            message.error({content: "Failed to delete Incident", duration: 2, style: {position: "fixed", left: "50%", top: "20%", color: "#316DC1"}})
                                        }
                                    })
                                }}
                                onCancel={()=>{

                                }}
                                okText="Delete"
                                cancelText="Cancel"
                                okButtonProps={{"record": record}}
                            >
                                <a>
                                    <DeleteOutlined/>
                                </a>
                            </Popconfirm>
                        </div>
                    )
                }
            }

        ]


        return (
            <div>
                <Table columns={columns} dataSource={this.state.data}/>
            </div>
        );
    }
Example #26
Source File: AdminUser.jsx    From node-project-manager with Apache License 2.0 4 votes vote down vote up
AdminUser = ({ users, getAllUsers, removeUser, userEdit }) => {
  const [showUserForm, setShowUserForm] = useState(false);
  const [showUserEditForm, setShowUserEditForm] = useState(false);

  const deleteUser = async id => {
    const data = await Http.delete("/api/users/deleteUser/" + id);
    if (!data.msg) removeUser(id);
  };

  const replenishTable = useCallback(async () => {
    const dataSource = await Http.get("/api/users/getAllUsers");
    getAllUsers(
      dataSource.map(item => {
        item.key = item.id;
        return item;
      })
    );
  }, [getAllUsers]);

  const columns = [
    {
      title: "ID",
      dataIndex: "id",
      key: "id"
    },
    {
      title: "Nickname",
      dataIndex: "nickname",
      key: "nickname",
      render: text => <span>{text}</span>
    },
    {
      title: "Correo",
      dataIndex: "email",
      key: "email"
    },
    {
      title: "Nombre",
      dataIndex: "nombre",
      key: "nombre"
    },
    {
      title: "Apellidos",
      dataIndex: "apellidos",
      key: "apellidos"
    },
    {
      title: "Permisos",
      key: "admin",
      dataIndex: "admin",
      render: tags => (
        <span>
          {tags ? <Tag color="blue">Admin</Tag> : <Tag color="grey">User</Tag>}
        </span>
      )
    },
    {
      title: "Action",
      key: "action",
      render: (text, record) => (
        <span>
          <EditOutlined
            style={{ marginRight: 16 }}
            onClick={() => {
              userEdit(record.id);
              setShowUserEditForm(!showUserEditForm);
            }}
          />
          <DeleteOutlined
            style={{ color: "red" }}
            onClick={() => {
              deleteUser(record.id);
            }}
          />
        </span>
      )
    }
  ];

  useEffect(() => {
    // Wait for loading data user
    //setLoading(true);

    replenishTable();
    //setLoading(false);
  }, [replenishTable]);

  return (
    <div>
      <Header />
      <div className="adminUserBody">
        <Button
          className="addUserButton"
          size="large"
          icon={<UserAddOutlined />}
          onClick={() => {
            setShowUserForm(!showUserForm);
            //Modal.info({title:"Crear usuarios",content:(<UserForm/>),onOk(){}})
          }}
        >
          Añadir Usuarios
        </Button>

        <Modal
          title="Crear Usuarios"
          visible={showUserForm}
          okText="Salir"
          destroyOnClose={true}
          onOk={() => {
            setShowUserForm(!showUserForm);
          }}
          cancelText="Cancelar"
          onCancel={() => {
            setShowUserForm(!showUserForm);
          }}
        >
          <UserForm />
        </Modal>
        <Modal
          title="Editar Usuarios"
          visible={showUserEditForm}
          destroyOnClose={true}
          okText="Salir"
          onOk={() => {
            setShowUserEditForm(!showUserEditForm);
          }}
          cancelText="Cancelar"
          onCancel={() => {
            setShowUserEditForm(!showUserEditForm);
          }}
        >
          <UserEditForm />
        </Modal>

        <Table className="tablaUsuarios" columns={columns} dataSource={users} />
      </div>
    </div>
  );
}
Example #27
Source File: Timeline.jsx    From moonshot with MIT License 4 votes vote down vote up
// displays a timeline for scaffold-eth usage

export default function TimelineDisplay(props) {
  return (
    <Timeline mode="right">
      <Timeline.Item dot="?">
        <Text delete>
          Clone and Install from the{" "}
          <a target="_blank" rel="noopener noreferrer" href="https://github.com/austintgriffith/scaffold-eth">
            github repo
          </a>
        </Text>
      </Timeline.Item>

      <Timeline.Item dot="⚛️">
        <Text delete>
          Start your frontend app with: <Text strong>yarn start</Text>
        </Text>
      </Timeline.Item>

      <Timeline.Item dot="⛓">
        <Text delete={props.chainIsUp}>
          Start your local blockchain with: <Text strong>yarn run chain</Text> (and refresh)
        </Text>
      </Timeline.Item>

      <Timeline.Item dot="?">
        <Text delete={props.hasOwner}>
          Compile and deploy your smart contract: <Text strong>yarn run deploy</Text>
        </Text>
      </Timeline.Item>

      <Timeline.Item dot="?">
        <Text delete={props.isNotSmoort}>
          Fix error in <Text code>SmartContractWallet.sol</Text> then: <Text strong>yarn run deploy</Text>
        </Text>
      </Timeline.Item>

      <Timeline.Item dot={<SendOutlined style={{ fontSize: "16px" }} />} color={props.hasEther ? "green" : "blue"}>
        <Text delete={props.hasEther}>
          Send test ether to your{" "}
          <Blockies seed={(props.address ? props.address : "").toLowerCase()} size={8} scale={2} /> address using
          (bottom left) faucet
        </Text>
      </Timeline.Item>

      <Timeline.Item
        dot={<DownloadOutlined style={{ fontSize: "16px" }} />}
        color={props.contractHasEther ? "green" : "blue"}
      >
        <Text delete={props.contractHasEther}>
          Deposit some funds into your{" "}
          <Blockies seed={(props.contractAddress ? props.contractAddress : "").toLowerCase()} size={8} scale={2} />{" "}
          smart contract wallet
        </Text>
      </Timeline.Item>

      <Timeline.Item
        dot={<EditOutlined style={{ fontSize: "16px" }} />}
        color={props.amOwnerOfContract ? "green" : "blue"}
      >
        <Text delete={props.amOwnerOfContract}>
          Set <b>owner</b> of your{" "}
          <Blockies seed={(props.contractAddress ? props.contractAddress : "").toLowerCase()} size={8} scale={2} />{" "}
          smart contract wallet to your{" "}
          <Blockies seed={(props.address ? props.address : "").toLowerCase()} size={8} scale={2} /> address
        </Text>
      </Timeline.Item>

      <Timeline.Item dot="☢️">
        <Text>
          Yikes, anyone can take ownership of <Text code>SmartContractWallet.sol</Text>
        </Text>
      </Timeline.Item>

      <Timeline.Item dot="?">
        <Text>
          Test your contract with <Text code>buidler/test/myTest.js</Text> then:
          <Text strong>yarn run test</Text>
        </Text>
      </Timeline.Item>

      <Timeline.Item dot="?">
        <Text>
          Build something awesome with ? <a href="https://github.com/austintgriffith/scaffold-eth">scaffold-eth</a> and{" "}
          <a target="_blank" rel="noopener noreferrer" href="https://twitter.com/austingriffith">
            @ me
          </a>
          !
        </Text>
      </Timeline.Item>

      <Timeline.Item dot="?">
        <Text>
          Read more about{" "}
          <a target="_blank" rel="noopener noreferrer" href="https://ethereum.org/developers">
            Ethereum
          </a>
          ,{" "}
          <a target="_blank" rel="noopener noreferrer" href="https://solidity.readthedocs.io/en/develop/contracts.html">
            Solidity
          </a>
          , and{" "}
          <a target="_blank" rel="noopener noreferrer" href="https://buidler.dev/tutorial">
            Buidler
          </a>
        </Text>
      </Timeline.Item>
    </Timeline>
  );
}
Example #28
Source File: DepositsTables.js    From bonded-stablecoin-ui with MIT License 4 votes vote down vote up
DepositsTables = ({
  timestamp,
  my,
  all,
  growth_factor,
  new_growth_factor,
  minProtectionRatio,
  setVisibleEditRecipient,
  setWithdrawProtection,
  setAddProtection,
  setWithdrawInterest
}) => {
  const [width] = useWindowSize();
  const { t } = useTranslation();

  const { activeWallet } = useSelector((state) => state.settings);
  const {
    deposit_state,
    deposit_aa,
    bonded_state,
    symbol2,
    symbol3,
    reserve_asset_symbol,
    params
  } = useSelector((state) => state.active);

  const actualParams = getParams(params, bonded_state);

  const mySortedDeposits = my.sort((a, b) => b.ts - a.ts);
  const allSortedDeposits = all.sort((a, b) => a.protection_ratio - b.protection_ratio);
  const recipientSortedDeposits = all.filter((item) => item.interest_recipient === activeWallet && item.owner !== activeWallet).sort((a, b) => b.amount - a.amount).map((item) => ({ ...item, inRecipientTab: true }));
  
  const columns = [
    {
      title: t("trade.tabs.deposits.opened", "Opened"),
      dataIndex: "ts",
      key: "ts",
      render: (value) => {
        return (
          <Tooltip title={moment.unix(value).format("DD-MM-YYYY HH:mm")}>
            {timestamp - value > 60 * 60 * 24
              ? moment.unix(value).format("DD-MM-YYYY")
              : moment.unix(value).format("HH:mm")}
          </Tooltip>
        );
      },
    },
    {
      title: (
        <Label
          label={symbol2 || t("trade.tabs.deposits.interest_title", "Interest tokens")}
          descr={t("trade.tabs.deposits.interest_title_desc", "Amount of interest tokens")}
        />
      ),
      dataIndex: "amount",
      key: "interest",
      render: (value) => {
        return (
          <ShowDecimalsValue decimals={actualParams.decimals2} value={value} />
        );
      },
    },
    {
      title: (
        <Label
          label={symbol3 || t("trade.tabs.deposits.stable_title", "Stable tokens")}
          descr={t("trade.tabs.deposits.stable_title_desc", "Amount of stable tokens issued against the deposit")}
        />
      ),
      dataIndex: "stable_amount",
      key: "stable",
      render: (value) => {
        return (
          <ShowDecimalsValue decimals={actualParams.decimals2} value={value} />
        );
      },
    },
    {
      title: (
        <Label
          label={t("trade.tabs.deposits.protection", "Protection (ratio)")}
          descr={t("trade.tabs.deposits.protection_desc", "Additional deposit in {{reserve}} that protects the deposit from being closed by others. The deposit with the least ratio of protection to deposit amount can be closed by anybody. There is no direct loss to you when your deposit is closed but you stop receiving interest from it.", {
            reserve: actualParams.reserve_asset in config.reserves
              ? config.reserves[actualParams.reserve_asset].name
              : reserve_asset_symbol || "reserve asset"
          })}
        />
      ),
      dataIndex: "protection",
      key: "protection",
      render: (value, records) => {
        const ratio = Number(records.protection_ratio).toPrecision(3);
        return (
          <>
            {value ? (
              <>
                <ShowDecimalsValue
                  decimals={actualParams.reserve_asset_decimals}
                  value={value}
                />{" "}
                {actualParams.reserve_asset === "base"
                  ? "GBYTE"
                  : config.reserves[actualParams.reserve_asset]
                    ? config.reserves[actualParams.reserve_asset].name
                    : reserve_asset_symbol || ''}{" "}
                ({ratio})
              </>
            ) : (
                0
              )}
            {records.isMy && <Tooltip title={t("trade.tabs.deposits.add_protection", "Add protection")}>
              <Button
                type="link"
                disabled={records.owner !== activeWallet || records.id.match(/^dummy\d+$/)}
                onClick={() => setAddProtection(records)}
                size="middle"
                icon={<DownloadOutlined />}
              />
            </Tooltip>}
            {records.isMy && <Tooltip title={t("trade.tabs.deposits.withdraw_protection", "Withdraw protection")}>
              <Button
                disabled={
                  records.owner !== activeWallet ||
                  !records.protection ||
                  records.protection === 0
                }
                type="link"
                size="middle"
                onClick={() => setWithdrawProtection(records)}
                icon={<ExportOutlined />}
              />
            </Tooltip>}
          </>
        );
      },
    },
    {
      title: (
        <Label label={t("trade.tabs.deposits.interest", "Interest")} descr={t("trade.tabs.deposits.interest_desc", "Interest available for withdrawal")} />
      ),
      dataIndex: "amount",
      key: "amount",
      render: (value, records) => {
        const new_stable_amount = Math.floor(records.amount * growth_factor);
        const interest = new_stable_amount - records.stable_amount;

        return (
          <>
            {records.closer ? (
              <ShowDecimalsValue
                decimals={actualParams.decimals2}
                value={records.close_interest}
              />
            ) : (
                <ShowDecimalsValue
                  decimals={actualParams.decimals2}
                  value={interest}
                />
              )}
            {(records.isMy || (activeWallet === records.interest_recipient && records.inRecipientTab)) && <Tooltip title={t("trade.tabs.deposits.withdraw_interest", "Withdraw interest")}>
              <Button
                type="link"
                onClick={() => setWithdrawInterest({ ...records, interest })}
                disabled={
                  interest <= 0 ||
                  (records.interest_recipient
                    ? activeWallet !== records.interest_recipient
                    : activeWallet !== records.owner) ||
                  records.closer ||
                  records.id.match(/^dummy\d+$/)
                }
                icon={<ExportOutlined />}
              />
            </Tooltip>}
          </>
        );
      },
    },
    {
      title: (
        <Label
          label={t("trade.tabs.deposits.interest_recipient", "Interest recipient")}
          descr={t("trade.tabs.deposits.interest_recipient_desc", "Who receives interest (deposit owner by default)")}
        />
      ),
      dataIndex: "interest_recipient",
      render: (value, records) => {
        const recipientName =
          value && config.interestRecipients.find((a) => a.address === value);
        return (
          <>
            {(!value && records.owner === activeWallet) || (value && value === activeWallet)
              ? t("trade.tabs.deposits.you", "you")
              : (recipientName && (
                <span style={{ fontSize: 12 }}>{recipientName.name}</span>
              )) ||
              (value || records.owner).slice(0, 9) + "..."}

            {records.isMy && <Tooltip title={t("trade.tabs.deposits.edit_interest_recipient", "Edit interest recipient")}>
              <Button
                type="link"
                size="small"
                style={{ padding: 0 }}
                disabled={records.owner !== activeWallet || records.id.match(/^dummy\d+$/)}
                onClick={() =>
                  setVisibleEditRecipient({
                    id: records.id,
                    current: records.interest_recipient || records.owner,
                  })
                }
                icon={<EditOutlined />}
              />
            </Tooltip>}
          </>
        );
      },
    },
    {
      id: "action",
      render: (_, records) => {
        const closeUrl = generateLink(
          records.closer ? 1e4 : Math.ceil(records.amount * new_growth_factor),
          {
            id: records.id,
            commit_force_close: records.closer ? 1 : undefined
          },
          activeWallet,
          deposit_aa,
          records.closer ? "base" : deposit_state.asset
        );

        const challengeLink = records.weakerId ? generateLink(
          1e4,
          {
            id: records.id,
            challenge_force_close: 1,
            weaker_id: records.weakerId
          },
          activeWallet,
          deposit_aa
        ) : null;

        const aboveMin = {
          is: !records.isMy && minProtectionRatio !== null && records.protection_ratio > minProtectionRatio,
          info: t("trade.tabs.deposits.less_last", "This deposit's protection ratio is above the smallest")
        };

        const tooNew = {
          is: records.ts + actualParams.min_deposit_term > timestamp || records.id.match(/^dummy\d+$/),
          info: t("trade.tabs.deposits.too_new", "This deposit was opened less than {{hours}} hours ago and can't be closed yet", { hours: +Number(actualParams.min_deposit_term / 3600).toFixed(3) })
        };

        const inChallengingPeriod = {
          is: (records.closer && records.force_close_ts && records.force_close_ts + actualParams.challenging_period > timestamp),
          info: t("trade.tabs.deposits.challenging_period", "Commit will be available in {{hours}} hours when the challenging period expires", { hours: +Number((records.force_close_ts + actualParams.challenging_period - timestamp) / 3600).toFixed(3) })
        };

        const tooltip = aboveMin.is ? aboveMin.info : (tooNew.is ? tooNew.info : (inChallengingPeriod.is ? inChallengingPeriod.info : undefined));

        return (
          <Space size="large">
            {!records.weakerId && <QRButton
              config={{
                tooltipMobile: tooltip,
                tooltip
              }}
              type="link"
              size="small"
              style={{ padding: 0 }}
              href={closeUrl}
              onClick={() => {
                ReactGA.event({
                  category: "Stablecoin",
                  action: "Close deposit",
                });
              }}
              disabled={inChallengingPeriod.is || tooNew.is || (aboveMin.is && records.owner !== activeWallet)}
            >
              {!records.closer && (records.owner === activeWallet ? t("trade.tabs.deposits.close", "Close") : t("trade.tabs.deposits.force_close", "Force close"))}
              {records.closer && t("trade.tabs.deposits.commit_force_close", "Commit force close")}
            </QRButton>}
            {records.weakerId ? <QRButton style={{ padding: 0 }} size="small" type="link" href={challengeLink}>{t("trade.tabs.deposits.challenge", "Challenge")}</QRButton> : null}
          </Space>
        );
      },
    },
  ];

  const isSingle = all.length === 1;

  return (
    <Tabs defaultActiveKey="my-1">
      <TabPane tab={t("trade.tabs.deposits.my_deposits", "My deposits")} key="my-1">
        {width > 1279 ? (
          <Table
            dataSource={mySortedDeposits}
            columns={columns}
            onRow={(record) => {
              return {
                style: {
                  color: (minProtectionRatio !== null && record.protection_ratio <= minProtectionRatio && !isSingle) ? "#e74c3c" : "inherit",
                },
              };
            }}
            locale={{
              emptyText: <DepositLocaleForEmpty isActive={bonded_state.interest_rate} />,
            }}
            pagination={{ pageSize: 20, hideOnSinglePage: true }}
          />
        ) : (
            <List
              pagination={{ pageSize: 10, hideOnSinglePage: true }}
              grid={{ column: 1 }}
              bordered={false}
              dataSource={mySortedDeposits}
              locale={{
                emptyText: <DepositLocaleForEmpty isActive={bonded_state.interest_rate} />,
              }}
              renderItem={(item) => (
                <DepositsItem
                  item={item}
                  width={width}
                  decimals={actualParams.decimals2}
                  reserve_asset_decimals={actualParams.reserve_asset_decimals}
                  reserve_asset_symbol={reserve_asset_symbol}
                  min_deposit_term={actualParams.min_deposit_term}
                  reserve_asset={actualParams.reserve_asset}
                  growth_factor={growth_factor}
                  activeWallet={activeWallet}
                  deposit_aa={deposit_aa}
                  timestamp={timestamp}
                  asset={deposit_state.asset}
                  setVisibleEditRecipient={setVisibleEditRecipient}
                  setAddProtection={setAddProtection}
                  setWithdrawProtection={setWithdrawProtection}
                  new_growth_factor={new_growth_factor}
                  challenging_period={actualParams.challenging_period}
                  symbol2={symbol2}
                  symbol3={symbol3}
                  minProtectionRatio={minProtectionRatio}
                  isSingle={isSingle}
                />
              )}
            />
          )}
      </TabPane>

      {activeWallet && <TabPane tab={t("trade.tabs.deposits.me_as_interest_recipient", "Me as interest recipient")} key="recipient-2">
        <InterestRecipientDepositsInfo />
        {width > 1279 ? (
          <Table
            dataSource={recipientSortedDeposits}
            columns={columns.filter((column) => column.dataIndex !== "interest_recipient" && column.id !== "action")}
            onRow={(record) => {
              return {
                style: {
                  color: (minProtectionRatio !== null && record.protection_ratio <= minProtectionRatio && !isSingle)
                    ? "#e74c3c"
                    : "inherit",
                },
              };

            }}
            locale={{
              emptyText: <DepositLocaleForEmpty isActive={bonded_state.interest_rate} />,
            }}
            pagination={{ pageSize: 20, hideOnSinglePage: true }}
          />
        ) : (
            <List
              pagination={{ pageSize: 10, hideOnSinglePage: true }}
              grid={{ column: 1 }}
              bordered={false}
              dataSource={recipientSortedDeposits}
              locale={{
                emptyText: <DepositLocaleForEmpty isActive={bonded_state.interest_rate} />,
              }}
              renderItem={(item) => (
                <DepositsItem
                  item={item}
                  width={width}
                  decimals={actualParams.decimals2}
                  reserve_asset_decimals={actualParams.reserve_asset_decimals}
                  reserve_asset_symbol={reserve_asset_symbol}
                  min_deposit_term={actualParams.min_deposit_term}
                  reserve_asset={actualParams.reserve_asset}
                  growth_factor={growth_factor}
                  activeWallet={activeWallet}
                  deposit_aa={deposit_aa}
                  timestamp={timestamp}
                  asset={deposit_state.asset}
                  setVisibleEditRecipient={setVisibleEditRecipient}
                  setAddProtection={setAddProtection}
                  setWithdrawProtection={setWithdrawProtection}
                  new_growth_factor={new_growth_factor}
                  challenging_period={actualParams.challenging_period}
                  inRecipientTab={true}
                  symbol2={symbol2}
                  symbol3={symbol3}
                  minProtectionRatio={minProtectionRatio}
                  isSingle={isSingle}
                />
              )}
            />
          )}
      </TabPane>}

      <TabPane tab={t("trade.tabs.deposits.all_deposits", "All deposits")} key="all-3">
        <ForceCloseDepositsInfo
          challengingPeriodInHours={+Number(actualParams.challenging_period / 3600).toFixed(2)}
          depositAa={deposit_aa}
          symbol2={symbol2}
          symbol3={symbol3}
        />
        {width > 1279 ? (
          <Table
            dataSource={allSortedDeposits}
            columns={columns}
            onRow={(record) => {
              return {
                style: {
                  color:
                    (minProtectionRatio !== null && record.protection_ratio <= minProtectionRatio && !isSingle)
                      ? "#e74c3c"
                      : "inherit",
                  background: record.owner === activeWallet ? "#f5f5f5" : "#fff",
                },
              };

            }}
            locale={{
              emptyText: <DepositLocaleForEmpty isActive={bonded_state.interest_rate} />,
            }}
            pagination={{ pageSize: 20, hideOnSinglePage: true }}
          />
        ) : (
            <List
              pagination={{ pageSize: 10, hideOnSinglePage: true }}
              grid={{ column: 1 }}
              bordered={false}
              dataSource={allSortedDeposits}
              locale={{
                emptyText: <DepositLocaleForEmpty isActive={bonded_state.interest_rate} />,
              }}
              renderItem={(item) => (
                <DepositsItem
                  item={item}
                  width={width}
                  decimals={actualParams.decimals2}
                  reserve_asset_decimals={actualParams.reserve_asset_decimals}
                  reserve_asset_symbol={reserve_asset_symbol}
                  min_deposit_term={actualParams.min_deposit_term}
                  reserve_asset={actualParams.reserve_asset}
                  growth_factor={growth_factor}
                  activeWallet={activeWallet}
                  deposit_aa={deposit_aa}
                  timestamp={timestamp}
                  asset={deposit_state.asset}
                  setVisibleEditRecipient={setVisibleEditRecipient}
                  setAddProtection={setAddProtection}
                  setWithdrawProtection={setWithdrawProtection}
                  new_growth_factor={new_growth_factor}
                  challenging_period={actualParams.challenging_period}
                  symbol2={symbol2}
                  symbol3={symbol3}
                  inAllTab={true}
                  minProtectionRatio={minProtectionRatio}
                  isSingle={isSingle}
                />
              )}
            />
          )}
      </TabPane>
    </Tabs>
  )
}
Example #29
Source File: AppRouter.jsx    From React-Nest-Admin with MIT License 4 votes vote down vote up
sidebar = () => {
  return (
    <Menu theme="dark" mode="inline" defaultSelectedKeys={["1"]}>
      <Menu.Item key="1">
        <Link to={{ pathname: "/" }}>
          <HomeOutlined />
          <span>首页</span>
        </Link>
      </Menu.Item>
      <Menu.Item key="5">
        <Link to={{ pathname: "/user-management" }}>
          <UserOutlined />
          <span>用户管理</span>
        </Link>
      </Menu.Item>
      <SubMenu
        key="sub1"
        title={
          <span>
            <FileOutlined />
            <span>文件管理</span>
          </span>
        }
      >
        <Menu.Item key="sub1-1">
          <Link to={{ pathname: "/file/list" }}>
            <OrderedListOutlined />
            <span>文件列表</span>
          </Link>
        </Menu.Item>
        <Menu.Item key="sub1-2">
          <Link to={{ pathname: "/file/add" }}>
            <UploadOutlined />
            <span>文件上传</span>
          </Link>
        </Menu.Item>
      </SubMenu>
      <SubMenu
        key="sub2"
        title={
          <span>
            <DashboardOutlined />
            <span>可视化图表</span>
          </span>
        }
      >
        <Menu.Item key="sub2-1">
          <Link to={{ pathname: "/charts/line-chart" }}>
            <LineChartOutlined />
            <span>折线图</span>
          </Link>
        </Menu.Item>
        <Menu.Item key="sub2-2">
          <Link to={{ pathname: "/charts/bar-chart" }}>
            <BarChartOutlined />
            <span>柱状图</span>
          </Link>
        </Menu.Item>
        <Menu.Item key="sub2-3">
          <Link to={{ pathname: "/charts/pie-chart" }}>
            <PieChartOutlined />
            <span>饼状图</span>
          </Link>
        </Menu.Item>
      </SubMenu>

      <SubMenu
        key="sub5"
        title={
          <span>
            <FileExcelOutlined />
            <span>Excel表格</span>
          </span>
        }
      >
        <Menu.Item key="sub5-1">
          <Link to={{ pathname: "/excel/export-csv" }}>
            <ExportOutlined />
            <span>Export csv</span>
          </Link>
        </Menu.Item>
      </SubMenu>

      <SubMenu
        key="sub4"
        title={
          <span>
            <EditOutlined />
            <span>文本编辑器</span>
          </span>
        }
      >
        <Menu.Item key="sub4-1">
          <Link to={{ pathname: "/rich-text-editor" }}>
            <Html5Outlined />
            <span>富文本编辑器</span>
          </Link>
        </Menu.Item>
        <Menu.Item key="sub4-2">
          <Link to={{ pathname: "/md-editor" }}>
            <FileMarkdownOutlined />
            <span>Markdown编辑器</span>
          </Link>
        </Menu.Item>
      </SubMenu>

      <SubMenu
        key="sub3"
        title={
          <span>
            <BugOutlined />
            <span>错误页面</span>
          </span>
        }
      >
        <Menu.Item key="sub3-1">
          <Link to={{ pathname: "/not-found" }}>
            <InboxOutlined />
            <span>404</span>
          </Link>
        </Menu.Item>
        <Menu.Item key="sub3-2">
          <Link to={{ pathname: "/not-allow" }}>
            <StopOutlined />
            <span>403</span>
          </Link>
        </Menu.Item>
      </SubMenu>

      <Menu.Item key="6">
        <a
          href="https://github.com/cnscorpions/React-Nest-Admin"
          target="_blank"
          rel="noopener noreferrer"
        >
          <GithubOutlined />
          <span>Github</span>
        </a>
      </Menu.Item>
    </Menu>
  );
}