@ant-design/icons#DeleteOutlined JavaScript Examples

The following examples show how to use @ant-design/icons#DeleteOutlined. 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: 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 #2
Source File: Card.jsx    From notence with MIT License 6 votes vote down vote up
Card = ({ title, properties, onDelete, innerRef, ...rest }) => {
  const handleClick = (event) => {
    event.stopPropagation();

    onDelete();
  };

  const propertyList = (
    <div className="property-list">
      {properties.map(({ Display, property, value }) => (
        <div className="property" key={property.id}>
          <Display property={property} value={value} />
        </div>
      ))}
    </div>
  );

  return (
    // eslint-disable-next-line react/jsx-props-no-spreading
    <CardWrapper ref={innerRef} {...rest}>
      <h2 className="title">{title}</h2>

      {propertyList}

      <DeleteOutlined className="delete-btn" onClick={handleClick} />
    </CardWrapper>
  );
}
Example #3
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 #4
Source File: QuadraticDiplomacyCreate.jsx    From quadratic-diplomacy with MIT License 6 votes vote down vote up
VoterInput = ({ index, voters, setVoters, mainnetProvider }) => {
  return (
    <>
      <Form.Item label={`Voter ${index + 1}`} name={`address[${index}]`} style={{ marginBottom: "16px" }}>
        <Row gutter={8} align="middle">
          <Col span={16}>
            <AddressInput
              autoFocus
              ensProvider={mainnetProvider}
              placeholder="Enter address"
              value={voters[index]}
              onChange={address => {
                setVoters(prevVoters => {
                  const nextVoters = [...prevVoters];
                  nextVoters[index] = address;
                  return nextVoters;
                });
              }}
            />
          </Col>
          <Col span={8}>
            <DeleteOutlined
              style={{ cursor: "pointer", color: "#ff6666" }}
              onClick={event => {
                setVoters(prevVoters => {
                  const nextVoters = [...prevVoters];
                  return nextVoters.filter((_, i) => i !== index);
                });
              }}
            />
          </Col>
        </Row>
      </Form.Item>
    </>
  );
}
Example #5
Source File: CrudDataTable.jsx    From starter-antd-admin-crud-auth-mern with MIT License 6 votes vote down vote up
function DropDownRowMenu({ row }) {
  const dispatch = useDispatch();
  const { crudContextAction } = useCrudContext();
  const { panel, collapsedBox, modal, 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 Delete() {
    dispatch(crud.currentAction("delete", item));
    modal.open();
  }
  return (
    <Menu style={{ width: 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={<DeleteOutlined />}
        onClick={Delete}
      >
        Delete
      </Menu.Item>
    </Menu>
  );
}
Example #6
Source File: index.js    From gobench with Apache License 2.0 5 votes vote down vote up
AppsGallery = () => {
  return (
    <div>
      <Helmet title="Gallery" />
      <div className="card">
        <div className="card-body">
          <div className="d-flex flex-wrap mb-4">
            <Checkbox>Models</Checkbox>
            <Checkbox>Fashion</Checkbox>
            <Checkbox>Cars</Checkbox>
            <Checkbox checked>Wallpapers</Checkbox>
          </div>
          <div className={style.items}>
            {data.map(item => (
              <div key={Math.random()} className={style.item}>
                <div className={style.itemContent}>
                  <div className={style.itemControl}>
                    <div className={style.itemControlContainer}>
                      <Button.Group size="default">
                        <Button>
                          <EditOutlined />
                        </Button>
                        <Button>
                          <DeleteOutlined />
                        </Button>
                      </Button.Group>
                    </div>
                  </div>
                  <img src={item.path} alt="Gallery" />
                </div>
                <div className="text-gray-6">
                  <div>{item.name}</div>
                  <div>{item.size}</div>
                </div>
              </div>
            ))}
          </div>
        </div>
      </div>
    </div>
  )
}
Example #7
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 #8
Source File: Relations.js    From label-studio-frontend with Apache License 2.0 5 votes vote down vote up
ListItem = observer(({ item }) => {
  const node = getRoot(item).annotationStore.selected.highlightedNode;
  const isSelected = node === item.node1 || node === item.node2;

  return (
    <List.Item
      className={isSelected && styles.selected}
      key={item.id}
      actions={[]}
      onMouseEnter={() => {
        item.toggleHighlight();
        item.setSelfHighlight(true);
      }}
      onMouseLeave={() => {
        item.toggleHighlight();
        item.setSelfHighlight(false);
      }}
    >
      <div className={styles.item}>
        <div>
          <Relation rl={item} />
        </div>
        <div>
          {item.hasRelations && (
            <Button
              size="small"
              onClick={() => {
                item.toggleMeta();
              }}
              className={styles.button}
            >
              <MoreOutlined />
            </Button>
          )}
          &nbsp;
          <Button
            size="small"
            className={styles.button}
            onClick={() => {
              item.node1.setHighlight(false);
              item.node2.setHighlight(false);
              item.parent.deleteRelation(item);
              return false;
            }}
            danger
          >
            <DeleteOutlined />
          </Button>
        </div>
      </div>
      {item.showMeta && <RelationMeta rl={item} />}
    </List.Item>
  );
})
Example #9
Source File: AdminDataTable.jsx    From erp-crm 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({ data: item }));
    panel.open();
    collapsedBox.open();
    readBox.open();
  };
  function Edit() {
    dispatch(crud.currentItem({ data: item }));
    dispatch(crud.currentAction({ actionType: 'update', data: item }));
    editBox.open();
    panel.open();
    collapsedBox.open();
  }
  function UpdatePassword() {
    dispatch(crud.currentItem({ data: item }));
    dispatch(crud.currentAction({ actionType: 'update', data: item }));
    advancedBox.open();
    panel.open();
    collapsedBox.open();
  }
  function Delete() {
    dispatch(crud.currentAction({ actionType: 'delete', data: 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 #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: File.js    From getlink-next with MIT License 5 votes vote down vote up
export default function File({
  loading,
  list,
  handleRemove,
}) {
  const { isAdmin, user } = useContext(Context);
  const columns = useMemo(() => [
    {
      title: 'Name',
      dataIndex: 'name',
      key: 'name',
    },
    {
      title: 'Date',
      dataIndex: 'createdAt',
      key: 'createdAt',
      render: createdAt => new Date(createdAt).toLocaleString(),
    },
    {
      title: '',
      key: 'op',
      width: 220,
      fixed: 'right',
      render: (text, record) => (
        <div>
          <Popover
            content={(
              <img
                alt="loading"
                style={{ width: 150, height: 150 }}
                src={cdnQrcode(record.key, 'file', isAdmin)}
              />
            )}>
            <Button style={{ marginLeft: 10 }}>
              <QrcodeOutlined />
            </Button>
          </Popover>
          {user && (
            <Popconfirm
              title="Are you sure to delete this ?"
              onConfirm={() => handleRemove(record.objectId)}
            >
              <Button style={{ marginLeft: 10 }} type="danger">
                <DeleteOutlined />
              </Button>
            </Popconfirm>
          )}
          <CopyToClipboard text={cdnUrl(record.key, 'file', isAdmin)}
            onCopy={() => message.success('Copied successfully')}>
            <Button style={{ marginLeft: 10 }} type="primary">Copy</Button>
          </CopyToClipboard>
        </div>
      ),
    },
  ], [handleRemove]);

  return (
    <Table
      loading={loading}
      dataSource={list}
      columns={columns}
      pagination={false}
    />
  );
}
Example #12
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 #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: FilterInput.jsx    From notence with MIT License 5 votes vote down vote up
DeleteBtn = styled(DeleteOutlined)`
  margin-left: 6px;
  cursor: pointer;
`
Example #15
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 #16
Source File: deadlineList.js    From deadviz with MIT License 5 votes vote down vote up
DeadlineList = ({pinned, data, onPin, onUnpin, onDelete}) => {
    const formatDate = date => `${date.getDate()}/${date.getMonth() + 1}/${date.getFullYear()}`;
    const formatDescription = item => `${formatDate(new Date(item.start))} ~ ${formatDate(new Date(item.end))}`;

    return (
        <Container>
            {pinned ? <Fragment>
                <PinnedDeadline
                    title={pinned.name}
                    description={formatDescription(pinned)}
                    onUnpin={onUnpin}
                />
                <Divider />
            </Fragment> : null}
            <StyledList
                itemLayout="horizontal"
                dataSource={data}
                renderItem={(item, index) => (
                    <List.Item
                        actions={[
                            <Popconfirm
                                title="Are you sure?"
                                okText="Yes"
                                placement="left"
                                cancelText="No"
                                onConfirm={() => onPin(index)}>
                                <PushpinFilled />
                            </Popconfirm>,
                            <Popconfirm
                                title="Are you sure?"
                                okText="Yes"
                                placement="left"
                                cancelText="No"
                                onConfirm={() => onDelete(item.id, index)}>
                                <Button
                                    type="primary"
                                    danger
                                    shape="circle"
                                    icon={
                                        <DeleteOutlined />
                                    }/>
                            </Popconfirm>]}>
                        <List.Item.Meta
                            title={item.name}
                            description={formatDescription(item)}
                        />
                    </List.Item>
                )}
            />
        </Container>
    );
}
Example #17
Source File: Table.jsx    From React-Nest-Admin with MIT License 5 votes vote down vote up
render() {
    const { data } = this.props;

    return (
      <>
        <Table
          dataSource={data}
          rowKey={record => record._id}
          pagination={false}
        >
          <Column title="文件名" dataIndex="fileName" key="fileName" />
          <Column
            title="上传者"
            dataIndex="uploader"
            key="uploader"
            render={record => (
              <span>
                {record === "admin" ? (
                  <Tag color="geekblue">admin</Tag>
                ) : (
                  record
                )}
              </span>
            )}
          />
          <Column
            title="上传时间"
            dataIndex="timeOfUpload"
            key="timeOfUpload"
            render={record => <span>{numberToTime(record)}</span>}
          />
          <Column
            title="文件大小"
            dataIndex="fileSize"
            key="fileSize"
            render={record => <span>{kbToMb(record)}</span>}
          />
          <Column
            title="操作"
            key="action"
            render={record => (
              <span>
                <DeleteOutlined
                  onClick={() =>
                    this.deleteHanler(record["_id"], record["filePath"])
                  }
                />
              </span>
            )}
          />
        </Table>
        <div
          style={{
            display: "flex",
            justifyContent: "flex-end",
            paddingTop: "20px",
            paddingRight: "20px"
          }}
        >
          <Pagination
            defaultCurrent={1}
            defaultPageSize={10}
            total={50}
            hideOnSinglePage
          />
        </div>
      </>
    );
  }
Example #18
Source File: ChatList.js    From react-chat-app with MIT License 4 votes vote down vote up
ChatList = props => {
    const didMountRef = useRef(false)
    const [hasMoreChats, setHasMoreChats] = useState(true)
    const [editingProfile, setEditingProfile] = useState(false)
    const [logoSource, setLogoSource] = useState(chatLogo);
    const [theme, setTheme] = useState("dark");
    const { conn, chats, setChats, setActiveChat, activeChat } = useContext(ChatEngineContext)
    const chat = chats && chats[activeChat];

    const name = props.chatAppState.userName
    const secret = props.chatAppState.userSecret

    useEffect(() => {

        const themeValue = localStorage.getItem("theme");

        if (themeValue === "light") {
            document.querySelector(".app").classList.add("light");
            setLogoSource(chatLogoWhite)

        } else if (themeValue === "dark") {
            document.querySelector(".app").classList.remove("light");
            setLogoSource(chatLogo)

        } else {
            localStorage.setItem("theme", theme);
        }
    }, [theme]);

    function deleteActiveChat(chatID) {
        var myHeaders = new Headers();

        let otherPerson = chat.people.find(
            (person) => person.person.username !== name
        )
            ? chat.people.find((person) => person.person.username !== name)
            : chat.people.find((person) => person.person.username === name);

        myHeaders.append("Project-ID", process.env.REACT_APP_PROJECT_ID);
        myHeaders.append("User-Name", name);
        myHeaders.append("User-Secret", secret);

        var raw = `{"username": "${name}"}`;
        var raw2 = `{"username": "${otherPerson.person.username}"}`;

        var firstUser = {
            method: "DELETE",
            headers: myHeaders,
            body: raw,
            redirect: "follow",
        };
        var secondUser = {
            method: "DELETE",
            headers: myHeaders,
            body: raw2,
            redirect: "follow",
        };

        fetch(`https://api.chatengine.io/chats/${chatID}/people/`, firstUser)
            .then((response) => response.text())
            .then((result) => console.log(result))
            .catch((error) => console.log("error", error));

        fetch(`https://api.chatengine.io/chats/${chatID}/people/`, secondUser)
            .then((response) => response.text())
            .then((result) => console.log(result))
            .catch((error) => console.log("error", error));
    }
    function getDateTime(date, offset) {
        if (!date) return ''

        date = date.replace(' ', 'T')
        offset = offset ? offset : 0

        const year = date.substr(0, 4)
        const month = date.substr(5, 2)
        const day = date.substr(8, 2)
        const hour = date.substr(11, 2)
        const minute = date.substr(14, 2)
        const second = date.substr(17, 2)

        var d = new Date(`${year}-${month}-${day}T${hour}:${minute}:${second}`)
        d.setHours(d.getHours() + offset)
        return d
    }

    function renderChats(chats) {
        return chats.map((chat, index) => {
            if (!chat) {
                return <div key={`chat_${index}`} />

            } else if (props.chatAppState.renderChatCard) {
                return <div key={`chat_${index}`}>{props.chatAppState.renderChatCard(chat, index)}</div>

            } else {
                return (""
                )
            }
        })
    }

    function sortChats(chats) {
        return chats.sort((a, b) => {
            const aDate = a.last_message && a.last_message.created ? getDateTime(a.last_message.created, props.chatAppState.offset) : getDateTime(a.created, props.chatAppState.offset)
            const bDate = b.last_message && b.last_message.created ? getDateTime(b.last_message.created, props.chatAppState.offset) : getDateTime(b.created, props.chatAppState.offset)
            return new Date(bDate) - new Date(aDate);
        })
    }

    function onGetChats(chatList) {
        const oldChats = chats !== null ? chats : {}
        const newChats = _.mapKeys({ ...chatList }, 'id')
        const allChats = { ...oldChats, ...newChats }
        setChats(allChats);
        (count && count > Object.keys(allChats).length) && setHasMoreChats(false);
    }

    useEffect(() => {
        if (!didMountRef.current && name && secret) {
            didMountRef.current = true

            getLatestChats(
                props.chatAppState,
                count,
                (chats) => {
                    onGetChats(chats)
                    const chatList = sortChats(chats)
                    chatList.length > 0 && setActiveChat(chatList[0].id)
                }
            )
        }
    })

    useEffect(() => {
        if (!activeChat) {
            activeConversation()
        }
    }, [chats, activeChat])

    const chatList = sortChats(
        chats ?
            Object.values(chats) :
            [{}, {}, {}, {}, {}, {}, {}, {}, {}, {}, {}, {}, {}, {}, {}]
    )
    function activeConversation() {
        if (chatList[0]) {
            setActiveChat(chatList[0].id)
        }
    }
    if (chats == null) return <div />;
    return (
        <div className="chat-left-wing">
            <div className="chat-bar">
                <div className="chat-bar-logo">
                    {(window.screen.availWidth > 700) ?
                        <img src={logoSource} alt="" /> :
                        <div className="mobile-toggler">
                            <CloseOutlined
                                onClick={() => {
                                    document.querySelector(".chat-container").children[0].children[1].children[0].style.display = "none";
                                    document.querySelector(".chat-container").children[0].children[1].children[1].style.display = "block";
                                }}
                            />
                        </div>
                    }
                </div>
                <div className="chat-bar-options">
                    <div className="chat-bar-option">
                        <UserOutlined
                            onClick={
                                () => {
                                    if (editingProfile && (window.screen.availWidth > 1150)) {
                                        setEditingProfile(!editingProfile)
                                        document.querySelector(".ce-chats-container").style.height = "530px"
                                    }
                                    else if (!editingProfile && (window.screen.availWidth > 1150)) {
                                        setEditingProfile(!editingProfile)
                                        document.querySelector(".ce-chats-container").style.height = "425px"
                                    }
                                    else if (editingProfile && (window.screen.availWidth <= 1150)) {
                                        setEditingProfile(!editingProfile)
                                        document.querySelector(".ce-chats-container").style.height = "calc(100vh - 76px)"
                                    } else {
                                        setEditingProfile(!editingProfile)
                                        document.querySelector(".ce-chats-container").style.height = "calc(100vh - 166px)"
                                    }

                                }
                            }
                        />
                    </div>
                    <div className="chat-bar-option">
                        <BgColorsOutlined onClick={() => {
                            const themeValue = localStorage.getItem("theme");
                            if (themeValue === "dark") {
                                setTheme("light")
                                localStorage.setItem("theme", "light");
                                document.querySelector(".app").classList.add("light");
                                setLogoSource(chatLogoWhite)
                            } else if (themeValue === "light") {
                                setTheme("dark")
                                localStorage.setItem("theme", "dark");
                                document.querySelector(".app").classList.remove("light");
                                setLogoSource(chatLogo)
                            }
                        }} />
                    </div>
                    <div className="chat-bar-option">
                    
                    <a href="https://github.com/matt765/react-chat-app" target="_blank"><GithubOutlined /></a>
                    </div>
                    <div className="chat-bar-option">
                        <DeleteOutlined onClick={() => {
                            if (name === "john%20doe") {
                                alert("Deleting conversations is disabled on sample account, sorry!");
                                return
                            }

                            if (window.confirm("Press OK if you want to delete active chat. Conversation with this person will be lost")) {
                                deleteActiveChat(activeChat)
                            }

                        }} />
                    </div>
                    <div className="chat-bar-option"> <LogoutOutlined onClick={() => {
                        if (window.confirm("Press OK if you want to logout")) {
                            fb.auth.signOut().then(console.log("logged out"))
                            document.querySelector(".app").classList.remove("light");
                        }
                    }} /></div>
                </div>
            </div>
            <div className="chat-left-wing-list">
                {editingProfile ?
                    <ChatProfile
                        chat={chat}
                        conn={conn}
                        name={props.chatAppState.userName}
                        secret={props.chatAppState.userSecret}
                    /> : ""}
                <div style={styles.chatListContainer} className='ce-chat-list'>
                    {
                        props.chatAppState.renderNewChatForm ?
                            props.chatAppState.renderNewChatForm(conn) :
                            <NewChatForm onClose={props.chatAppState.onClose ? () => props.chatAppState.onClose() : undefined} />
                    }
                    <div style={styles.chatsContainer} className='ce-chats-container'>
                        {renderChats(chatList)}
                        {
                            hasMoreChats && chatList.length > 0 &&
                            <div>

                                <div style={{ height: '8px' }} />
                            </div>
                        }
                    </div>
                </div>
            </div>
        </div>
    )
}
Example #19
Source File: ChannelSetting.js    From network-rc with Apache License 2.0 4 votes vote down vote up
export default function ChannelSetting({
  saveServerConfig,
  serverConfig,
  resetChannel,
}) {
  const [form] = Form.useForm();

  useEffect(() => {
    form.resetFields();
  }, [serverConfig, form]);

  const ui = (index, fields, { add, remove }) => {
    return (
      <Space align="baseline" split={<Divider type="vertical" />} wrap>
        {fields.map((field) => {
          const uiId = form.getFieldValue([
            "channelList",
            index,
            "ui",
            field.name,
            "id",
          ]);
          const uiComponent = serverConfig.uiComponentList.find(
            (i) => i.id === uiId
          );
          return (
            <Space key={field.key} align="baseline">
              <Form.Item
                label="UI"
                {...field}
                name={[field.name, "id"]}
                fieldKey={[field.fieldKey, "id"]}
                rules={[{ required: true, message: "客官!选一个!" }]}
              >
                <Select style={{ width: 80 }}>
                  {serverConfig.uiComponentList.map(({ id, name }) => (
                    <Option value={id}> {name} </Option>
                  ))}
                </Select>
              </Form.Item>
              {uiComponent && uiComponent.type === "joystick" && (
                <Form.Item
                  label="轴"
                  {...field}
                  name={[field.name, "axis"]}
                  fieldKey={[field.fieldKey, "axis"]}
                  rules={[{ required: true, message: "客官!选一个!" }]}
                >
                  <Select style={{ width: 80 }}>
                    <Option value="x">x</Option>
                    <Option value="y">y</Option>
                  </Select>
                </Form.Item>
              )}
              <Form.Item
                label="控制方向"
                {...field}
                name={[field.name, "positive"]}
                fieldKey={[field.fieldKey, "positive"]}
                valuePropName="checked"
              >
                <Switch checkedChildren="正向" unCheckedChildren="反向" />
              </Form.Item>
              <Form.Item
                label="控制方式"
                {...field}
                name={[field.name, "method"]}
                fieldKey={[field.fieldKey, "method"]}
              >
                <Select style={{ width: 80 }}>
                  <Option value="default">默认</Option>
                  <Option value="step">步进</Option>
                </Select>
              </Form.Item>
              <Form.Item
                label="步进速度"
                {...field}
                name={[field.name, "speed"]}
                fieldKey={[field.fieldKey, "speed"]}
                initialValue={0.5}
              >
                <InputNumber
                  step={0.1}
                  min={0}
                  disabled={
                    "step" !==
                    form.getFieldValue([
                      "channelList",
                      index,
                      "ui",
                      field.name,
                      "method",
                    ])
                  }
                />
              </Form.Item>
              <MinusCircleOutlined onClick={() => remove(field.name)} />
            </Space>
          );
        })}
        <PlusCircleOutlined
          onClick={() =>
            add({
              positive: true,
              method: "default",
            })
          }
        />
      </Space>
    );
  };

  const keyboard = (index, fields, { add, remove }) => {
    const type = form.getFieldValue(["channelList", index, "type"]);
    return (
      <Space align="baseline" direction="vertical">
        {fields.map((field) => {
          const method = form.getFieldValue([
            "channelList",
            index,
            "keyboard",
            field.name,
            "method",
          ]);

          return (
            <Space key={field.key} align="baseline">
              <Form.Item
                {...field}
                name={[field.name, "name"]}
                fieldKey={[field.fieldKey, "name"]}
                rules={[{ required: true, message: "客官!选一个按键!" }]}
                extra="键盘按键"
              >
                <Input style={{ width: 80 }} />
              </Form.Item>

              {type === "pwm" && (
                <Form.Item
                  {...field}
                  name={[field.name, "method"]}
                  fieldKey={[field.fieldKey, "method"]}
                  defaultValue="default"
                  extra="控制方式"
                >
                  <Radio.Group size="middle">
                    <Radio.Button value="default">默认</Radio.Button>
                    <Radio.Button value="step">步进</Radio.Button>
                  </Radio.Group>
                </Form.Item>
              )}

              {type === "pwm" && (
                <Form.Item
                  {...field}
                  name={[field.name, "speed"]}
                  fieldKey={[field.fieldKey, "speed"]}
                  extra={
                    method === "default"
                      ? "-1 ~ 1, 0 为归位"
                      : "每秒步进速度系数"
                  }
                >
                  <InputNumber max={1} min={-1} step={0.1} />
                </Form.Item>
              )}

              {/* {type === "switch" && (
                <Form.Item
                  {...field}
                  name={[field.name, "speed"]}
                  fieldKey={[field.fieldKey, "speed"]}
                  extra="高低电平"
                >
                  <Radio.Group size="middle">
                    <Radio.Button value={1}>高</Radio.Button>
                    <Radio.Button value={-1}>低</Radio.Button>
                  </Radio.Group>
                </Form.Item>
              )} */}

              {(method === "default" || type === "switch") && (
                <Form.Item
                  {...field}
                  name={[field.name, "autoReset"]}
                  fieldKey={[field.fieldKey, "autoReset"]}
                  extra="释放键盘是否复位"
                  valuePropName="checked"
                  defaultValue={true}
                >
                  <Switch />
                </Form.Item>
              )}

              <MinusCircleOutlined onClick={() => remove(field.name)} />
            </Space>
          );
        })}
        <PlusCircleOutlined
          onClick={() =>
            add({
              speed: 1,
              autoReset: true,
              method: "default",
            })
          }
        />
      </Space>
    );
  };

  const gamepad = (index, fields, { add, remove }) => {
    const type = form.getFieldValue(["channelList", index, "type"]);

    return (
      <Space align="baseline" split={<Divider type="vertical" />} wrap>
        {fields.map((field) => {
          // const method = form.getFieldValue([
          //   "channelList",
          //   index,
          //   "gamepad",
          //   field.name,
          //   "method",
          // ]);
          return (
            <Space key={field.key} align="baseline">
              <Form.Item
                {...field}
                name={[field.name, "name"]}
                fieldKey={[field.fieldKey, "name"]}
                rules={[{ required: true, message: "客官!选一个!" }]}
                extra="摇杆轴或按键"
              >
                <Select style={{ width: 100 }}>
                  {gamePadInputList.map(({ value, name }) => (
                    <Option value={value}> {name} </Option>
                  ))}
                </Select>
              </Form.Item>

              {type === "pwm" && (
                <Form.Item
                  {...field}
                  name={[field.name, "method"]}
                  fieldKey={[field.fieldKey, "method"]}
                  defaultValue="default"
                  extra="控制方式"
                >
                  <Radio.Group size="middle">
                    <Radio.Button value="default">默认</Radio.Button>
                    <Radio.Button value="step">步进</Radio.Button>
                  </Radio.Group>
                </Form.Item>
              )}

              {type === "pwm" && (
                <Form.Item
                  {...field}
                  name={[field.name, "speed"]}
                  fieldKey={[field.fieldKey, "speed"]}
                  extra="控制系数,-1 ~ 1"
                >
                  <InputNumber min={-1} max={1} step={0.1} />
                </Form.Item>
              )}

              {/* {method === "default" && (
                <Form.Item
                  {...field}
                  name={[field.name, "autoReset"]}
                  fieldKey={[field.fieldKey, "autoReset"]}
                  extra="释放按钮是否复位"
                  valuePropName="checked"
                  defaultValue={true}
                >
                  <Switch />
                </Form.Item>
              )} */}

              {/* {type === "switch" && (
                <Form.Item
                  {...field}
                  name={[field.name, "speed"]}
                  fieldKey={[field.fieldKey, "speed"]}
                  extra="高低电平"
                >
                  <Radio.Group size="middle">
                    <Radio.Button value={1}>高</Radio.Button>
                    <Radio.Button value={-1}>低</Radio.Button>
                  </Radio.Group>
                </Form.Item>
              )} */}

              <MinusCircleOutlined onClick={() => remove(field.name)} />
            </Space>
          );
        })}
        <PlusCircleOutlined
          onClick={() =>
            add({
              speed: 1,
              autoReset: true,
              method: "default",
            })
          }
        />
      </Space>
    );
  };

  return (
    <Form form={form} onFinish={saveServerConfig} initialValues={serverConfig}>
      <Form.List name="channelList">
        {(fields, { add, remove }) => (
          <Space
            key={fields.key}
            direction="vertical"
            style={{ width: "100%" }}
          >
            {fields.map((field) => (
              <Card
                key={field.key}
                title={
                  <Space key={field.key} align="baseline" wrap>
                    <Form.Item
                      {...field}
                      name={[field.name, "enabled"]}
                      fieldKey={[field.fieldKey, "enabled"]}
                      valuePropName="checked"
                    >
                      <Switch checkedChildren="开启" unCheckedChildren="禁用" />
                    </Form.Item>
                    <Form.Item
                      {...field}
                      label="名称"
                      name={[field.name, "name"]}
                      fieldKey={[field.fieldKey, "name"]}
                    >
                      <Input style={{ width: 80 }} />
                    </Form.Item>
                    <Button danger onClick={() => remove(field.name)}>
                      <DeleteOutlined />
                    </Button>
                  </Space>
                }
              >
                <Row>
                  <Space key={field.key} align="baseline" wrap>
                    <Form.Item
                      {...field}
                      label="GPIO"
                      name={[field.name, "pin"]}
                      fieldKey={[field.fieldKey, "pin"]}
                      rules={[{ required: true, message: "仔细想想" }]}
                    >
                      <Select style={{ width: 60 }}>
                        {pins.map((pin) => (
                          <Option key={pin} value={pin}>
                            {pin}
                          </Option>
                        ))}
                      </Select>
                    </Form.Item>
                    <Form.Item
                      {...field}
                      label="类型"
                      name={[field.name, "type"]}
                      fieldKey={[field.fieldKey, "type"]}
                      rules={[{ required: true, message: "你不能没有我!" }]}
                    >
                      <Select style={{ width: 80 }}>
                        {types.map(({ value, label }) => (
                          <Option key={value} value={value}>
                            {label}
                          </Option>
                        ))}
                      </Select>
                    </Form.Item>
                    {form.getFieldValue([
                      "channelList",
                      field.fieldKey,
                      "type",
                    ]) === "pwm" && (
                      <>
                        <Form.Item
                          {...field}
                          label="最大值"
                          name={[field.name, "valuePostive"]}
                          fieldKey={[field.fieldKey, "valuePostive"]}
                        >
                          <InputNumber
                            step={0.1}
                            max={2}
                            min={form.getFieldValue([
                              "channelList",
                              field.fieldKey,
                              "valueReset",
                            ])}
                          />
                        </Form.Item>
                        <Form.Item
                          {...field}
                          label="复位值"
                          name={[field.name, "valueReset"]}
                          fieldKey={[field.fieldKey, "valueReset"]}
                          shouldUpdate
                        >
                          <InputNumber
                            step={0.1}
                            min={form.getFieldValue([
                              "channelList",
                              field.fieldKey,
                              "valueNegative",
                            ])}
                            max={form.getFieldValue([
                              "channelList",
                              field.fieldKey,
                              "valuePostive",
                            ])}
                          />
                        </Form.Item>
                        <Form.Item
                          {...field}
                          label="最小值"
                          name={[field.name, "valueNegative"]}
                          fieldKey={[field.fieldKey, "valueNegative"]}
                        >
                          <InputNumber
                            step={0.1}
                            min={-2}
                            max={form.getFieldValue([
                              "channelList",
                              field.fieldKey,
                              "valueReset",
                            ])}
                          />
                        </Form.Item>
                      </>
                    )}
                  </Space>
                </Row>

                <Collapse align="start">
                  <Panel header="UI 控件" size="small">
                    <Form.List name={[field.name, "ui"]}>
                      {(...props) => ui(field.fieldKey, ...props)}
                    </Form.List>
                  </Panel>
                  <Panel header="键盘" size="small">
                    <Form.List name={[field.name, "keyboard"]}>
                      {(...props) => keyboard(field.fieldKey, ...props)}
                    </Form.List>
                  </Panel>
                  <Panel header="手柄" size="small">
                    <Form.List name={[field.name, "gamepad"]}>
                      {(...props) => gamepad(field.fieldKey, ...props)}
                    </Form.List>
                  </Panel>
                  <Panel header="手机重力感应" size="small">
                    <Form.Item
                      {...field}
                      label="方向"
                      name={[field.name, "orientation", "axis"]}
                      fieldKey={[field.fieldKey, "orientation", "axis"]}
                    >
                      <Select style={{ width: 80 }} allowClear>
                        {[
                          { name: "水平", value: "x" },
                          { name: "垂直", value: "y" },
                        ].map((i) => (
                          <Option key={i.value} value={i.value}>
                            {i.name}
                          </Option>
                        ))}
                      </Select>
                    </Form.Item>
                    <Form.Item
                      {...field}
                      label="系数"
                      name={[field.name, "orientation", "coefficient"]}
                      fieldKey={[field.fieldKey, "orientation", "coefficient"]}
                    >
                      <Slider defaultValue={1} max={2} min={-2} step={0.01} />
                    </Form.Item>
                  </Panel>
                </Collapse>
              </Card>
            ))}

            <Form.Item>
              <Button
                onClick={() =>
                  add({
                    id: uuid(),
                    enabled: true,
                    valuePostive: 1,
                    valueNegative: -1,
                    valueReset: 0,
                  })
                }
                block
                icon={<PlusOutlined />}
              >
                添加通道
              </Button>
            </Form.Item>
          </Space>
        )}
      </Form.List>

      <Form.Item>
        <Space>
          <Button type="primary" htmlType="submit">
            保存
          </Button>
          <Button
            type="danger"
            onClick={() => {
              resetChannel();
              store.remove("ui-position");
            }}
          >
            恢复默认通道设置
          </Button>
        </Space>
      </Form.Item>
    </Form>
  );
}
Example #20
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 #21
Source File: ProjectDescription.jsx    From node-project-manager with Apache License 2.0 4 votes vote down vote up
ProjectDescription = ({ project,projects,removeProject,selectedProject}) => {

  const [edited, setEdited] = useState(false);
  const [name, setName] = useState(project.nombre);
  const [description, setDescription] = useState(project.descripcion);
  const [editName, setEditName] = useState(true);
  const [editDesc, setEditDesc] = useState(true);
  const [showUserEditForm, setShowUserEditForm] = useState(false);
  const [showTeacherForm, setShowTeacherForm] = useState(false);
  const [showTechForm, setShowTechForm] = useState(false);
  const [showSaved, setShowSaved] = useState(true);
  const [alertMessage, setAlertMessage] = useState("");
  const [typeMessage, setTypeMessage] = useState("");

  const openNotification = result => {
    // TODO : 
    switch (result.type){
      case "success":
        notification.success({
          message: `${result.message}`,
          placement:'bottomRight'
        });
        break;
      default:
        notification.error({
          message: `Something went wrong`,
          placement:'bottomRight'
        });
    }
  };



  const saveProject = async () => {

    project.nombre=name;
    project.descripcion=description;

    const result = await Http.post(project,'/api/projects/updateProject/'+project.id);
    
    if(result){
      openNotification(result);
    }

    setEdited(false);
    setEditDesc(true);
    setEditName(true);

  }

  const deleteProject = async() =>{

      const result = await Http.get('/api/projects/deleteProject/'+project.id);
      if(result){
        console.log(result);
        selectedProject(projects[1]);
        removeProject(project.id);
      }  
  }


  //Cada vez que cambiamos de proyecto, seteamos las variables al valor de cada proyecto
  useEffect(() => {
    
    setEditName(true);
    setEditDesc(true);
    setShowSaved(false);
    setName(project.nombre);
    setDescription(project.descripcion);
    setAlertMessage(" ");
    setTypeMessage(" ");
    
  }, [project]);

  return (
    <div className="descripciones">
      <Descriptions className="itemsDescripciones"
        title={
          <span className="titulo">
            {project.nombre}
            <div className="projectActions">
              <Button
              type="danger"
              onClick={deleteProject}
              >
               <DeleteOutlined /> Borrar</Button>
            </div>
            {showSaved ? <div> <Modal 
                         title="Usuario editado"
                         visible={showSaved}
                         destroyOnClose={true}
                         okText="Salir"
                         onOk={() => {
                           setShowSaved(!showSaved);
                         }}
                         cancelText="Cancelar"
                         onCancel={() => {
                           setShowSaved(!showSaved);
                         }}
            ><Alert className="alertaUpdate" message={alertMessage} type={typeMessage} /> </Modal></div>:""}
            {edited ? (
              <span className="botonsitoGuardar">
                <Button
                  type="primary"
                  shape="round"
                  icon={<SaveOutlined />}
                  onClick={saveProject}
                >
                  Guardar
                </Button>
              </span>
            ) : (
              ""
            )}
          </span>
        }
        bordered
        column={{ xxl: 4, xl: 4, lg: 3, md: 3, sm: 2, xs: 2 }}
      >
        <Descriptions.Item
        className="nombreProyecto"
          label={
            <span>
              Nombre Proyecto &nbsp;
              <EditOutlined
                onClick={() => {
                  project.seleccionado = "";
                  setEditName(!editName);
                }}
              />
            </span>
          }
        >
          {editName ? (
            <span onDoubleClick={()=>{project.seleccionado="";setEditName(!editName)}}>{project.nombre}</span>
          ) : (
            <Input
              defaultValue={project.nombre}
              onChange={(e) => {
                setName(e.target.value);
                setEdited(true);
              }}
              
              size="small"
            />
          )}
        </Descriptions.Item>
        
        <Descriptions.Item className="alumnos" label={<span> Alumnos <EditOutlined
          onClick={()=>{
            setShowUserEditForm(!showUserEditForm);
          }}/></span>}>
          
          <Modal
            title="Editar Alumnos"
            visible={showUserEditForm}
            destroyOnClose={true}
            okText="Salir"
            onOk={() => {
              setEdited(true);
              setShowUserEditForm(!showUserEditForm);
            }}
            cancelText="Cancelar"
            onCancel={() => {
              setShowUserEditForm(!showUserEditForm);
            }}
          >
            <TransferFormStudents/>
          </Modal>
          {project.usuarios.alumnos
            ? project.usuarios.alumnos.map((usr) => {
                usr.icon = require("../../img/" + usr.avatar);
                return (
                  <Popover content={contentPopOverUsers(usr)} key={usr.id}>
                    <Avatar src={usr.icon} /> &nbsp;
                  </Popover>
                );
              })
            : ""}
        </Descriptions.Item>
            
        <Descriptions.Item className="profesores"label={<span>Profesores <EditOutlined
          onClick={()=>{
            setShowTeacherForm(!showTeacherForm);
          }}/></span>}>
          
          <Modal
            title="Editar Alumnos"
            visible={showTeacherForm}
            destroyOnClose={true}
            okText="Salir"
            onOk={() => {
              setEdited(true);
              setShowTeacherForm(!showTeacherForm);
            }}
            cancelText="Cancelar"
            onCancel={() => {
              setShowTeacherForm(!showTeacherForm);
            }}
          >
            <TransferFormTeachers/>
          </Modal>
          {project.usuarios.profesores
            ? project.usuarios.profesores.map((usr) => {
                usr.icon = require("../../img/" + usr.avatar);
                return (
                  <Popover content={contentPopOverUsers(usr)} key={usr.id}>
                    <Avatar src={usr.icon} /> &nbsp;
                  </Popover>
                );
              })
            : ""}
        </Descriptions.Item>




        <Descriptions.Item className="tecnologias" label={<span>Tecnologías <EditOutlined
          onClick={()=>{
            setShowTechForm(!showTechForm);
          }}/></span>}>

        <Modal
            title="Editar usuarios"
            visible={showTechForm}
            destroyOnClose={true}
            okText="Salir"
            onOk={() => {
              setEdited(true);
              setShowTechForm(!showTechForm);
            }}
            cancelText="Cancelar"
            onCancel={() => {
              setShowTechForm(!showTechForm);
            }}
          >
            <TransferTechForm/>
          </Modal>

          {project.tecnologias
            ? project.tecnologias.map((tech) => {
                tech.icon = require("../../img/techs/" + tech.logo);
                return (
                  <Popover content={contentPopOverTechs(tech)} key={tech.id}>
                    <Avatar src={tech.icon} /> &nbsp;
                  </Popover>
                );
              })
            : ""}

        </Descriptions.Item>
        <Descriptions.Item
          className="descripciones"
          label={
            <span>
              Descripcion &nbsp;
              <EditOutlined
                onClick={() => {
                  project.seleccionado = "";
                  setEditDesc(!editDesc);
                }}
              />
            </span>
          }
        >
          {editDesc ? (
            <pre onDoubleClick={()=>{project.seleccionado = ""; setEditDesc(!editDesc)}}>{project.descripcion}</pre>
          ) : (
            <Input.TextArea
              defaultValue={project.descripcion}
              onChange={(e) => {
                setDescription(e.target.value);
                setEdited(true);
                }
              }
              size="small"
            />
          )}
        </Descriptions.Item>
      </Descriptions>
    </div>
  );
}
Example #22
Source File: tasks.js    From hashcat.launcher with MIT License 4 votes vote down vote up
render() {
		const { taskKey, task } = this.state;

		return (
			<>
				<PageHeader
					title="Tasks"
				/>
				<Content style={{ padding: '16px 24px' }}>
					<Row gutter={16} className="height-100 tree-height-100">
						<Col className="max-height-100" span={5}>
							<Tree
								showIcon
								blockNode
								treeData={this.state.data}
								onSelect={this.onSelect}
								selectedKeys={[taskKey]}
								style={{
									height: '100%',
									paddingRight: '.5rem',
									overflow: 'auto',
									background: '#0a0a0a',
									border: '1px solid #303030'
								}}
							/>
						</Col>
						<Col className="max-height-100" span={19}>
							{task ? (
								<Row gutter={[16, 14]} className="height-100" style={{ flexDirection: "column", flexWrap: "nowrap" }}>
									<Col flex="0 0 auto">
										<Row gutter={[16, 14]}>
											<Col span={24}>
												<PageHeader
													title={task.id}
													tags={
														task.stats.hasOwnProperty("status") ? (	
															HASHCAT_STATUS_BADGE_WARNING.indexOf(task.stats["status"]) > -1 ? (
																<Tag color="warning">{HASHCAT_STATUS_MESSAGES[task.stats["status"]]}</Tag>
															) : HASHCAT_STATUS_BADGE_PROCESSING.indexOf(task.stats["status"]) > -1 ? (
																<Tag color="processing">{HASHCAT_STATUS_MESSAGES[task.stats["status"]]}</Tag>
															) : HASHCAT_STATUS_BADGE_ERROR.indexOf(task.stats["status"]) > -1 ? (
																<Tag color="error">{HASHCAT_STATUS_MESSAGES[task.stats["status"]]}</Tag>
															) : HASHCAT_STATUS_BADGE_SUCCESS.indexOf(task.stats["status"]) > -1 ? (
																<Tag color="success">{HASHCAT_STATUS_MESSAGES[task.stats["status"]]}</Tag>
															) : HASHCAT_STATUS_BADGE_PINK.indexOf(task.stats["status"]) > -1 ? (
																<Tag color="pink">{HASHCAT_STATUS_MESSAGES[task.stats["status"]]}</Tag>
															) : HASHCAT_STATUS_BADGE_YELLOW.indexOf(task.stats["status"]) > -1 ? (
																<Tag color="yellow">{HASHCAT_STATUS_MESSAGES[task.stats["status"]]}</Tag>
															) : (
																<Tag color="default">{HASHCAT_STATUS_MESSAGES[task.stats["status"]]}</Tag>
															)
														) : null
													}
													style={{ padding: 0 }}
													extra={
														<Form layout="inline">
															<Form.Item
																label="Priority"
															>
																<InputNumber
																	min={-1}
																	max={999}
																	value={task.priority}
																	onChange={this.onChangePriority}
																	readOnly={this.state.isReadOnlyPriority}
																	bordered={false}
																/>
															</Form.Item>
															<Button
																icon={<ControlOutlined />}
																onClick={this.onClickArguments}
																style={{ marginRight: '1rem' }}
															>
																Arguments
															</Button>
															<Popconfirm
																placement="topRight"
																title="Are you sure you want to delete this task?"
																onConfirm={this.onClickDelete}
																okText="Yes"
																cancelText="No"
															>
																<Button
																	type="danger"
																	icon={<DeleteOutlined />}
																	loading={this.state.isLoadingDelete}
																>
																	Delete
																</Button>
															</Popconfirm>
														</Form>
													}
												/>
											</Col>
											<Col span={24}>
												{task.stats.hasOwnProperty("progress") ? (
													<Progress type="line" percent={Math.trunc((task.stats["progress"][0] / task.stats["progress"][1])*100)} />
												) : (
													<Progress type="line" percent={0} />
												)}
											</Col>
											<Col span={24}>
												<Row gutter={[12, 10]}>
													<Col>
														<Button
															type="primary"
															icon={<PlayCircleOutlined />}
															onClick={this.onClickStart}
															loading={this.state.isLoadingStart}
														>
															Start
														</Button>
													</Col>
													<Col>
														<Button
															icon={<ReloadOutlined />}
															onClick={this.onClickRefresh}
															loading={this.state.isLoadingRefresh}
														>
															Refresh
														</Button>
													</Col>
													<Col>
														<Button
															icon={<PauseOutlined />}
															onClick={this.onClickPause}
															loading={this.state.isLoadingPause}
														>
															Pause
														</Button>
													</Col>
													<Col>
														<Button
															icon={<CaretRightOutlined />}
															onClick={this.onClickResume}
															loading={this.state.isLoadingResume}
														>
															Resume
														</Button>
													</Col>
													<Col>
														<Button
															icon={<EnvironmentOutlined />}
															onClick={this.onClickCheckpoint}
															loading={this.state.isLoadingCheckpoint}
														>
															Checkpoint
														</Button>
													</Col>
													<Col>
														<Button
															icon={<StepForwardOutlined />}
															onClick={this.onClickSkip}
															loading={this.state.isLoadingSkip}
														>
															Skip
														</Button>
													</Col>
													<Col>
														<Popconfirm
															placement="topRight"
															title="Are you sure you want to quit this task?"
															onConfirm={this.onClickQuit}
															okText="Yes"
															cancelText="No"
														>
															<Button
																type="danger"
																icon={<CloseOutlined />}
																loading={this.state.isLoadingQuit}
															>
																Quit
															</Button>
														</Popconfirm>
													</Col>
												</Row>
											</Col>
										</Row>
									</Col>
									<Col flex="1 1 auto">
										<Row gutter={[16, 14]} className="height-100">
											<Col className="max-height-100" span={16}>
												<Descriptions
													column={2}
													layout="horizontal"
													bordered
												>
													{task.stats.hasOwnProperty("status") && (
														<Descriptions.Item label="Status" span={2}>
															{HASHCAT_STATUS_BADGE_WARNING.indexOf(task.stats["status"]) > -1 ? (
																<Badge status="warning" text={HASHCAT_STATUS_MESSAGES[task.stats["status"]]} />
															) : HASHCAT_STATUS_BADGE_PROCESSING.indexOf(task.stats["status"]) > -1 ? (
																<Badge status="processing" text={HASHCAT_STATUS_MESSAGES[task.stats["status"]]} />
															) : HASHCAT_STATUS_BADGE_ERROR.indexOf(task.stats["status"]) > -1 ? (
																<Badge status="error" text={HASHCAT_STATUS_MESSAGES[task.stats["status"]]} />
															) : HASHCAT_STATUS_BADGE_SUCCESS.indexOf(task.stats["status"]) > -1 ? (
																<Badge status="success" text={HASHCAT_STATUS_MESSAGES[task.stats["status"]]} />
															) : HASHCAT_STATUS_BADGE_PINK.indexOf(task.stats["status"]) > -1 ? (
																<Badge color="pink" text={HASHCAT_STATUS_MESSAGES[task.stats["status"]]} />
															) : HASHCAT_STATUS_BADGE_YELLOW.indexOf(task.stats["status"]) > -1 ? (
																<Badge color="yellow" text={HASHCAT_STATUS_MESSAGES[task.stats["status"]]} />
															) : (
																<Badge status="default" text={HASHCAT_STATUS_MESSAGES[task.stats["status"]]} />
															)}
														</Descriptions.Item>
													)}
													{task.stats.hasOwnProperty("target") && (
														<Descriptions.Item label="Target" span={2}>
															{task.stats["target"]}
														</Descriptions.Item>
													)}
													{task.stats.hasOwnProperty("progress") && (
														<Descriptions.Item label="Progress" span={2}>
															{task.stats["progress"][0] + " / " + task.stats["progress"][1] + " (" + Math.trunc((task.stats["progress"][0] / task.stats["progress"][1])*100) + "%)"}
															{task.stats.hasOwnProperty("guess") && (
																<Tooltip title={
																	<Descriptions bordered size="small" column={1} layout="horizontal">
																		{task.stats.guess.guess_base !== null ? (
																			<Descriptions.Item label="Guess Base">{task.stats.guess.guess_base} ({task.stats.guess.guess_base_offset}/{task.stats.guess.guess_base_count})</Descriptions.Item>
																		) : (
																			<Descriptions.Item label="Guess Base">-</Descriptions.Item>
																		)}
																		{task.stats.guess.guess_mod !== null ? (
																			<Descriptions.Item label="Guess Mod">{task.stats.guess.guess_mod} ({task.stats.guess.guess_mod_offset}/{task.stats.guess.guess_mod_count})</Descriptions.Item>
																		) : (
																			<Descriptions.Item label="Guess Mod">-</Descriptions.Item>
																		)}
																	</Descriptions>
																}>
																	<InfoCircleOutlined style={{ marginLeft: ".5rem" }} />
																</Tooltip>
															)}
														</Descriptions.Item>
													)}
													{task.stats.hasOwnProperty("rejected") && (
														<Descriptions.Item label="Rejected" span={1}>
															{task.stats["rejected"]}
														</Descriptions.Item>
													)}
													{task.stats.hasOwnProperty("restore_point") && (
														<Descriptions.Item label="Restore point" span={1}>
															{task.stats["restore_point"]}
														</Descriptions.Item>
													)}
													{task.stats.hasOwnProperty("recovered_hashes") && (
														<Descriptions.Item label="Recovered hashes" span={1}>
															{task.stats["recovered_hashes"][0] + " / " + task.stats["recovered_hashes"][1] + " (" + Math.trunc((task.stats["recovered_hashes"][0] / task.stats["recovered_hashes"][1])*100) + "%)"}
														</Descriptions.Item>
													)}
													{task.stats.hasOwnProperty("recovered_salts") && (
														<Descriptions.Item label="Recovered salts" span={1}>
															{task.stats["recovered_salts"][0] + " / " + task.stats["recovered_salts"][1] + " (" + Math.trunc((task.stats["recovered_salts"][0] / task.stats["recovered_salts"][1])*100) + "%)"}
														</Descriptions.Item>
													)}
													{task.stats.hasOwnProperty("devices") && (
														<Descriptions.Item label="Speed" span={2}>
															{humanizeSpeed(totalSpeed(task.stats["devices"]))}
															<Tooltip title={
																<Table
																	columns={[
																		{
																			title: 'ID',
																			dataIndex: 'id',
																			key: 'ID'
																		},
																		{
																			title: 'Speed',
																			dataIndex: 'speed',
																			key: 'Speed'
																		},
																		{
																			title: 'Temp',
																			dataIndex: 'temp',
																			key: 'Temp'
																		},
																		{
																			title: 'Util',
																			dataIndex: 'util',
																			key: 'Util'
																		}
																	]}
																	dataSource={task.stats["devices"].map(device =>
																		({
																			key: device.device_id,
																			id: device.device_id,
																			speed: humanizeSpeed(device.speed),
																			temp: device.hasOwnProperty("temp") ? device.temp + " °C": "-",
																			util: device.util + "%",
																		})
																	)}
																	size="small"
																	pagination={false}
																	style={{ overflow: 'auto' }}
																/>
															}>
																<InfoCircleOutlined style={{ marginLeft: ".5rem" }} />
															</Tooltip>
														</Descriptions.Item>
													)}
													{task.stats.hasOwnProperty("time_start") && (
														<Descriptions.Item label="Started" span={1}>
															<Tooltip title={moment.unix(task.stats["time_start"]).format("MMMM Do YYYY, HH:mm")}>
																{moment.unix(task.stats["time_start"]).fromNow()}
															</Tooltip>
														</Descriptions.Item>
													)}
													{task.stats.hasOwnProperty("estimated_stop") && (
														<Descriptions.Item label="ETA" span={1}>
															<Tooltip title={moment.unix(task.stats["estimated_stop"]).format("MMMM Do YYYY, HH:mm")}>
																{moment.unix(task.stats["estimated_stop"]).fromNow()}
															</Tooltip>
														</Descriptions.Item>
													)}
												</Descriptions>
											</Col>
											<Col className="max-height-100" span={8}>
												<div className="height-100" style={{ display: "flex", flexDirection: "column" }}>
												<span><CodeOutlined /> Terminal</span>
												<pre style={{
													flex: 'auto',
													overflow: 'auto',
													padding: '.5rem',
													margin: '0',
													border: '1px solid #303030'
												}}>
													{task.journal.map(j => j.message + "\n")}
												</pre>
												</div>
											</Col>
										</Row>
									</Col>
								</Row>
							) : (
								"No selected task."
							)}
						</Col>
					</Row>
				</Content>
			</>
		)
	}
Example #23
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 addContentType({ ...fields });
      hide();
      message.success('添加成功');
      return true;
    } catch (error) {
      return dealError(error, addFormRef, hide, "添加");
    }
  };

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

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

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

    try {
      const ids = selectedRows.map(row => row.id).join(',');
      await removeContentType(ids);
      hide();
      message.success('删除成功');
      return true;
    } catch (error) {
      hide()
      return dealRemoveError(error, "删除");
    }
  };
 
  const dateFieldList = []
  const base_columns = [{
                             title: 'id',
                             
        hideInForm: true,
        hideInSearch: true,
        
                             
                             dataIndex: 'id',
                             valueType: 'digit',
                             rules: [
                                     
                             ],
                             
                             
                        },
                      {
                             title: 'app_label',
                             
                             
                             dataIndex: 'app_label',
                             
                             rules: [
                                     {
                      required: true,
                      message: 'app_label为必填项',
                     },
                             ],
                             
                             
                        },
                      {
                             title: 'model',
                             
                             
                             dataIndex: 'model',
                             
                             rules: [
                                     {
                      required: true,
                      message: 'model为必填项',
                     },
                             ],
                             
                             
                        },
                          {
                              title: '操作',
                              dataIndex: 'option',
                              valueType: 'option',
                                    fixed: 'right',
          width: 100,
                              render: (text, record) => (
                                <>

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

  let cp = deepCopy(base_columns);

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

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

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

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

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

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

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


   

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

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

            if (success) {
              handleModalVisible(false);

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

            if (success) {
              handleUpdateModalVisible(false);

              if (actionRef.current) {
                actionRef.current.reload();
              }
            }
          }}
          rowKey="key"
          search={{}}
          type="form"
          form={{
            initialValues: updateFormValues, labelCol: { span: 6 },
            labelAlign: 'left',
          }}
          columns={update_columns}
          rowSelection={{}}
        />
      </UpdateForm>
       
    </PageHeaderWrapper>
  );
}
Example #24
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 #25
Source File: Settings.js    From ctf_platform with MIT License 4 votes vote down vote up
render() {
        return (
            <Layout className="layout-style">

                {this.state.loading ? (
                    <div style={{ position: "absolute", left: "55%", transform: "translate(-55%, 0%)", zIndex: 10 }}>
                        <Ellipsis color="#177ddc" size={120} />
                    </div>
                ) : (
                    <div>
                        <Modal
                            title={"Delete Account"}
                            visible={this.state.deleteAccountModal}
                            footer={null}
                            onCancel={() => { this.setState({ deleteAccountModal: false }) }}
                            confirmLoading={this.state.modalLoading}
                        >

                            <DeleteAccountForm logout={this.props.logout.bind(this)} setState={this.setState.bind(this)} />
                        </Modal>


                        <Divider />
                        <div style={{ display: "flex", marginRight: "5ch", alignItems: "center", justifyItems: "center" }}>
                            <div style={{ display: "flex", flexDirection: "column", justifyContent: "initial", width: "20ch", overflow: "hidden" }}>
                                <Avatar style={{ backgroundColor: "transparent", width: "12ch", height: "12ch" }} size='large' src={"/static/profile/" + this.props.username + ".webp"} />
                                <div style={{ marginTop: "2ch", display: "flex" }}>
                                    <Upload
                                        fileList={this.state.fileList}
                                        disabled={this.state.disableUpload}
                                        accept=".png, .jpg, .jpeg, .webp"
                                        action={window.ipAddress + "/v1/profile/upload"}
                                        maxCount={1}
                                        onChange={(file) => {
                                            this.setState({ fileList: file.fileList })
                                            if (file.file.status === "uploading") {
                                                this.setState({ disableUpload: true })
                                            }
                                            else if ("response" in file.file) {
                                                if (file.file.response.success) {
                                                    message.success("Uploaded profile picture")
                                                    message.success("Reload the page to see your shiny new picture :)!")
                                                }
                                                else {
                                                    message.error("Failed to upload profile picture")
                                                    if (file.file.response.error === "too-large") {
                                                        message.info("Please upload a file smaller than " + file.file.response.size.toString() + " Bytes.")
                                                    }
                                                }
                                                this.setState({ fileList: [], disableUpload: false })
                                            }
                                        }}
                                        headers={{ "Authorization": window.IRSCTFToken }}
                                        name="profile_pic"
                                        beforeUpload={file => {
                                            const exts = ["image/png", "image/jpg", "image/jpeg", "image/webp"]
                                            if (!exts.includes(file.type)) {
                                                message.error(`${file.name} is not an image file.`);
                                                return Upload.LIST_IGNORE
                                            }
                                            return true
                                        }}>
                                        <Tooltip title={<span>Upload a custom profile picture.</span>}>
                                            <Button type="primary" icon={<UploadOutlined />}>Upload</Button>
                                        </Tooltip>
                                    </Upload>
                                    <Tooltip title={<span>Reset your profile picture to the default profile picture.</span>}>
                                        <Button danger type="primary" icon={<DeleteOutlined />} style={{ marginLeft: "1ch" }} onClick={() => { this.deleteProfilePic() }} />
                                    </Tooltip>
                                </div>
                            </div>
                            <h1 style={{ fontSize: "5ch", marginLeft: "1ch" }}>{this.props.username}</h1>
                        </div>

                        <Divider />

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

                            <div className="form-style">
                                <h1 className="settings-header"><KeyOutlined /> Change Password</h1>
                                <ChangePasswordForm />
                            </div>

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


                            <div className="form-style">
                                <h1 className="settings-header"><MailOutlined /> Change Email</h1>
                                <ChangeEmailForm email={this.state.email} />
                            </div>
                        </div>

                        <Divider />

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

                            <div className="form-style">
                                <h1 className="settings-header"><ApartmentOutlined /> Select Participant Category</h1>
                                <SelectParticipantCategoryForm participantCategory={this.state.participantCategory} categoryList={this.state.categoryList} />
                            </div>
                        </div>

                        <Divider />


                        <div>
                            <h3>Very Very Dangerous Button</h3>
                            <Button danger type="primary" icon={<DeleteOutlined />} onClick={() => { this.setState({ deleteAccountModal: true }) }} >Delete Account</Button>
                            <p>You will be asked to key in your password to confirm</p>
                        </div>
                    </div>
                )}
            </Layout>
        )
    }
Example #26
Source File: index.js    From pretty-derby with GNU General Public License v3.0 4 votes vote down vote up
Seed = () => {
  document.title = TITLE;
  useDidRecover(() => {
    document.title = TITLE;
  });
  const [isSeedInputVisible, setIsSeedInputVisible] = useState(false);
  const [seedList, setSeedList] = useState([]);
  const [total, setTotal] = useState(0);
  // const [current, setCurrent] = useState(0)
  const [value, setValue] = useState();

  const columns = [
    {
      title: "玩家id",
      dataIndex: "gameId",
      key: "gameId",
      render: (text, seed) => (
        <>
          <Row>
            <p>{text}</p>
            <CopyToClipboard text={text} onCopy={() => message.info("成功")}>
              <CopyOutlined />
            </CopyToClipboard>
          </Row>
          <Row align="middle">
            <SmileOutlined onClick={() => like(seed)} />
            <p>{seed.likes}</p>
          </Row>
          <Row align="middle">
            <FrownOutlined onClick={() => dislike(seed)} />
            <p>{seed.dislikes}</p>
          </Row>
          {seed.userId === userId && (
            <Row align="middle">
              <DeleteOutlined onClick={() => deleteSeed(seed)} />
            </Row>
          )}
        </>
      ),
    },
    {
      title: "主要",
      dataIndex: "playerId0",
      key: "playerId0",
      render: (text) => <PlayerImage id={text} />,
    },
    {
      title: "蓝色因子",
      dataIndex: "blue0",
      key: "blue0",
      render: (text, record) => (
        <span className="rate-label">{`${SEED_BLUE_LABELS[text]}\xa0\xa0${record["blueLevel0"]}`}</span>
      ),
    },
    {
      title: "红色因子",
      dataIndex: "red0",
      key: "red0",
      render: (text, record) => (
        <span className="rate-label">{`${SEED_RED_LABELS[text]}\xa0\xa0${record["redLevel0"]}`}</span>
      ),
    },
    {
      title: "绿色因子",
      dataIndex: "greenLevel0",
      key: "greenLevel0",
      render: (text, record) => (
        <span className="rate-label">{`固有\xa0\xa0${record["greenLevel0"]}`}</span>
      ),
    },
    {
      title: "URA",
      dataIndex: "uraLevel0",
      key: "uraLevel0",
      render: (text, record) => (
        <span className="rate-label">
          {`${record["uraLevel0"] ? `URA  ${record["uraLevel0"]}` : ""}`}
        </span>
      ),
    },
    {
      title: "父辈1",
      dataIndex: "playerId1",
      key: "playerId1",
      render: (text) => <PlayerImage id={text} />,
    },
    {
      title: "父辈2",
      dataIndex: "playerId2",
      key: "playerId2",
      render: (text) => <PlayerImage id={text} />,
    },
    {
      title: "总计蓝色",
      key: "allBlue",
      render: (text, record) =>
        Object.keys(SEED_BLUE_LABELS).map((key) => {
          if (record[key]) {
            return (
              <span
                key={key}
                className="rate-label"
              >{`${SEED_BLUE_LABELS[key]}\xa0\xa0${record[key]}`}</span>
            );
          } else {
            return null;
          }
        }),
    },
    {
      title: "总计红色",
      key: "allRed",
      render: (text, record) =>
        Object.keys(SEED_RED_LABELS).map((key) => {
          if (record[key]) {
            return (
              <span
                key={key}
                className="rate-label"
              >{`${SEED_RED_LABELS[key]}\xa0\xa0${record[key]}`}</span>
            );
          } else {
            return null;
          }
        }),
    },
    { title: "总计URA", dataIndex: "uraLevel", key: "uraLevel", render: (text) => text },
    { title: "总计白色", dataIndex: "white", key: "white", render: (text) => text },
    {
      title: "支援卡",
      dataIndex: "supportId",
      key: "supportId",
      render: (text) => <SupportImage id={text} />,
    },
    {
      title: "突破等级",
      dataIndex: "supportLevel",
      key: "supportLevel",
      render: (text, record) => (
        <Row>
          <Rate count={4} value={record["supportLevel"]} disabled />
        </Row>
      ),
    },
  ];

  const showSeedInput = (index) => {
    setIsSeedInputVisible(true);
  };
  const closeSeedInput = () => {
    setIsSeedInputVisible(false);
  };
  const showMySeed = () => {
    search({ attrs: ["userId"], levels: [userId] });
  };
  const deleteSeed = async (value) => {
    const res = await axios.post("https://urarawin.com/api/sqlite/delete", value);
    if (res.data) {
      message.info("成功删除");
    } else {
      message.info("出错了");
    }
  };
  const search = async (value) => {
    setValue(value);
    const res = await axios.post("https://urarawin.com/api/sqlite/search", value);
    // setCurrent(0)
    if (res.data) {
      if (res.data.count) {
        setSeedList([...res.data.list]);
        setTotal(res.data.count);
      } else {
        setSeedList([]);
        setTotal(0);
        message.info("暂无数据");
      }
    } else {
      message.info("出错了");
    }
  };
  const like = async (seed) => {
    if (!userId) {
      message.info("刷新后重试");
      return;
    }
    let id = seed.id;
    const res = await axios.post("https://urarawin.com/api/sqlite/like", { id, userId });
    if (res.data) {
      message.info("成功");
      seed.likes += 1;
    }
    setSeedList([...seedList]);
  };
  const dislike = async (seed) => {
    if (!userId) {
      message.info("刷新后重试");
      return;
    }
    let id = seed.id;
    const res = await axios.post("https://urarawin.com/api/sqlite/dislike", { id, userId });
    if (res.data) {
      message.info("成功");
      seed.dislikes += 1;
    }
    setSeedList([...seedList]);
  };
  const onChange = (e) => {
    search({
      ...value,
      count: e.total,
      offset: e.current * 10 - 10,
    });
  };
  return (
    <>
      <div className="seed-container">
        <Card className="card" title="过滤条件">
          <SearchForm search={search} />
          <Button onClick={() => showSeedInput()}>配置我的种子</Button>
          <Button onClick={() => showMySeed()}>查看我的种子</Button>
        </Card>
        <Card className="card" title="结果">
          <Table
            columns={columns}
            dataSource={seedList}
            onChange={onChange}
            pagination={{
              pageSize: 10,
              total: total,
              simple: true,
              showQuickJumper: false,
              position: ["topRight", "bottomRight"],
            }}
            rowKey={"id"}
          />
        </Card>
      </div>
      <Modal
        visible={isSeedInputVisible}
        onOk={closeSeedInput}
        onCancel={closeSeedInput}
        footer={null}
        width={"80%"}
      >
        <SeedInput onFinish={closeSeedInput} />
      </Modal>
    </>
  );
}
Example #27
Source File: adminUsers.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>Change User Permissions <ClusterOutlined /></span>}
                    visible={this.state.permissionModal}
                    onOk={this.changePermissions}
                    onCancel={() => { this.setState({ permissionModal: false }) }}
                    confirmLoading={this.state.modalLoading}
                >
                    <Select size="large" value={this.state.permissionChangeTo} style={{ width: "30ch" }} onSelect={(value) => { this.setState({ permissionChangeTo: value }) }}>
                        <Option value="0">0 - Normal User</Option>
                        <Option value="1">1 - Challenge Creator User</Option>
                        <Option value="2">2 - Admin User</Option>
                    </Select>
                    <br />
                    <br />

                    <ul>
                        <li><b>0 - Normal User</b>: Has access to the basic functions and nothing else</li>
                        <li><b>1 - Challenge Creator User</b>: Has the additional power of submitting new challenges, but not modifying existing ones</li>
                        <li><b>2 - Admin User</b>: Has full access to the platform via the admin panel.</li>
                    </ul>
                </Modal>

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

                    <RegisterForm createAccount={this.createAccount.bind(this)} setState={this.setState.bind(this)} />
                </Modal>

                <Modal
                    title={"Changing Account Password For: " + this.state.username}
                    visible={this.state.passwordResetModal}
                    footer={null}
                    onCancel={() => { this.setState({ passwordResetModal: false }) }}
                >

                    <ChangePasswordForm username={this.state.username} setState={this.setState.bind(this)} />
                </Modal>

                <Modal
                    title={"Changing Category For: " + this.state.username}
                    visible={this.state.categoryChangeModal}
                    footer={null}
                    onCancel={() => { this.setState({ categoryChangeModal: false }) }}
                >

                    <SelectParticipantCategoryForm fillTableData={this.fillTableData.bind(this)} categoryList={this.state.categoryList} username={this.state.username} participantCategory={this.state.participantCategory} />
                </Modal>

                <Modal
                    title={"Changing Email For: " + this.state.username}
                    visible={this.state.emailChangeModal}
                    footer={null}
                    onCancel={() => { this.setState({ emailChangeModal: false }) }}
                >

                    <ChangeEmailForm fillTableData={this.fillTableData.bind(this)} username={this.state.username} setState={this.setState.bind(this)} />
                </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={<UserOutlined />} onClick={() => { this.setState({ createUserModal: true }) }}>Create New User</Button>
                        {this.state.loading && (
                            <div style={{ display: "flex", justifyContent: "center", alignItems: "center" }}>
                                <Ellipsis color="#177ddc" size={60} ></Ellipsis>
                                <h1>Loading Users</h1>
                            </div>
                        )}
                    </div>
                    <Button loading={this.state.loading} type="primary" shape="circle" size="large" style={{ marginBottom: "2vh", maxWidth: "25ch" }} icon={<RedoOutlined />} onClick={async () => { await Promise.all([this.fillTableData(), this.getDisableStates()]); message.success("Users 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 user(s) (' + this.state.selectedTableKeys.join(", ") + ')? This action is irreversible.',
                            icon: <ExclamationCircleOutlined />,
                            onOk: (close) => { this.deleteAccounts(close.bind(this), this.state.selectedTableKeys) },
                            onCancel: () => { },
                        });
                    }}>Delete Users</Button>
                    <Button type="default" disabled={this.state.disableEditButtons} style={{ marginBottom: "2vh", marginRight: "1ch", backgroundColor: "#6e6e6e" }} icon={<CheckOutlined style={{ color: "#49aa19" }} />} onClick={() => {
                        confirm({
                            confirmLoading: this.state.disableEditButtons,
                            title: 'Are you sure you want to verify the user(s) (' + this.state.selectedTableKeys.join(", ") + ')?',
                            icon: <ExclamationCircleOutlined />,
                            onOk: (close) => { this.verifyAccounts(close.bind(this), this.state.selectedTableKeys) },
                            onCancel: () => { },
                        });
                    }}>Verify Users</Button>
                    <Button type="default" disabled={this.state.disableEditButtons} style={{ marginBottom: "2vh", marginRight: "1ch", backgroundColor: "#6e6e6e" }} icon={<CloseOutlined style={{ color: "#a61d24" }} />} onClick={() => {
                        confirm({
                            confirmLoading: this.state.disableEditButtons,
                            title: 'Are you sure you want to un-verify the user(s) (' + this.state.selectedTableKeys.join(", ") + ')?',
                            content: 'Please note that this action will send a new email per user asking them to re-verify.',
                            icon: <ExclamationCircleOutlined />,
                            onOk: (close) => { this.unverifyAccounts(close.bind(this), this.state.selectedTableKeys) },
                            onCancel: () => { },
                        });
                    }}>Un-Verify Users</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 users found/created</h1>
                        </div>
                    )
                }}>
                    <Column title="Username" dataIndex="username" key="username"
                        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 Username"
                                    value={selectedKeys[0]}
                                    onChange={e => setSelectedKeys(e.target.value ? [e.target.value] : [])}
                                    onPressEnter={() => confirm()}
                                    style={{ marginBottom: 8, display: 'block' }}
                                    autoFocus
                                />
                                <Space>
                                    <Button
                                        type="primary"
                                        onClick={() => { confirm() }}
                                        icon={<SearchOutlined />}
                                    >
                                        Search
                                    </Button>
                                    <Button onClick={() => clearFilters()}>
                                        Reset
                                    </Button>
                                </Space>
                            </div>
                        )}
                        onFilter={(value, record) => record.username.toLowerCase().trim().includes(value.toLowerCase())}
                        filterIcon={filtered => <SearchOutlined style={{ color: filtered ? '#1890ff' : undefined }} />}
                        sorter={(a, b) => {
                            if (a.username < b.username) return -1
                            else return 1
                        }}
                    />
                    <Column title="Email" dataIndex="email" key="email"
                        filterDropdown={({ setSelectedKeys, selectedKeys, confirm, clearFilters }) => (
                            <div style={{ padding: 8 }}>
                                <Input
                                    placeholder="Search Email"
                                    value={selectedKeys[0]}
                                    onChange={e => setSelectedKeys(e.target.value ? [e.target.value] : [])}
                                    onPressEnter={() => confirm()}
                                    style={{ marginBottom: 8, display: 'block' }}
                                    autoFocus
                                />
                                <Space>
                                    <Button
                                        type="primary"
                                        onClick={() => { confirm() }}
                                        icon={<SearchOutlined />}
                                    >
                                        Search
                                    </Button>
                                    <Button onClick={() => clearFilters()}>
                                        Reset
                                    </Button>
                                </Space>
                            </div>
                        )}
                        onFilter={(value, record) => record.email.toLowerCase().trim().includes(value.toLowerCase())}
                        filterIcon={filtered => <SearchOutlined style={{ color: filtered ? '#1890ff' : undefined }} />}
                    />
                    <Column title="Permissions" dataIndex="type" key="type" filters={[{ text: "Normal User (0)", value: 0 }, { text: "Challenge Creator (1)", value: 1 }, { text: "Admin (2)", value: 2 }]} onFilter={(value, record) => { return value === record.type }} />
                    <Column title="Team" dataIndex="team" key="team"
                        render={(text, row, index) => {
                            if (text != "N/A") return <Link to={"/Team/" + text}><a style={{ fontWeight: 700 }}>{text}</a></Link>;
                            else return text;
                        }}
                        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' }}
                                    autoFocus
                                />
                                <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 title="Verified" dataIndex="verified" key="verified" filters={[{ text: "Verified", value: "True" }, { text: "Unverified", value: "False" }]} onFilter={(value, record) => { return value === record.verified }} />
                    <Column
                        title=""
                        key="action"
                        render={(text, record) => (
                            <Dropdown trigger={['click']} overlay={
                                <Menu>
                                    <Menu.Item onClick={() => {
                                        this.setState({ permissionModal: true, username: record.username, permissionChangeTo: record.type.toString() })
                                    }}>
                                        <span>
                                            Change Permissions <ClusterOutlined />
                                        </span>
                                    </Menu.Item>
                                    <Menu.Item onClick={() => {
                                        this.setState({ passwordResetModal: true, username: record.username })
                                    }}>
                                        <span>
                                            Change Password <KeyOutlined />
                                        </span>
                                    </Menu.Item>
                                    <Menu.Item onClick={() => {
                                        this.setState({ emailChangeModal: true, username: record.username })
                                    }}>
                                        <span>
                                            Change Email <MailOutlined />
                                        </span>
                                    </Menu.Item>
                                    <Menu.Item onClick={() => {
                                        this.setState({ categoryChangeModal: true, username: record.username, participantCategory: record.category })
                                    }}>
                                        <span>
                                            Change Category <ApartmentOutlined />
                                        </span>
                                    </Menu.Item>
                                </Menu>
                            } placement="bottomCenter">
                                <Button>Actions</Button>
                            </Dropdown>
                        )}
                    />
                </Table>

                <Divider />

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

                    <Card className="settings-card">
                        <h3>Disable User Registration:  <Switch disabled={this.state.disableLoading} onClick={(value) => this.disableSetting("registerDisable", value)} checked={this.state.registerDisable} /></h3>
                        <p>Disables user registration for unregistered users. Admins can still create users from this page.</p>
                    </Card>

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

                    <Card className="settings-card">
                        <h3>Disable User Logins:  <Switch disabled={this.state.disableLoading2} onClick={(value) => this.disableSetting("loginDisable", value)} checked={this.state.loginDisable} /></h3>
                        <p>Disables user login except for admin users. <br /><b>Note:</b> Users already logged into the platform will remain authenticated as tokens cannot be revoked. If you want to restrict a user from accessing the platform anymore, simply delete their account.</p>
                    </Card>

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

                    <Card className="settings-card">
                        <h3>Disable Admin Scores:  <Switch disabled={this.state.disableLoading2} onClick={(value) => this.disableSetting("adminShowDisable", value)} checked={this.state.adminShowDisable} /></h3>
                        <p>Prevents admin scores from showing up on scoreboards and profile pages. Admin solves will still appear under the solve list in challenges. <br /> Please note that disabling/enabling this will require users to reopen ctfx to resync the scoreboard.</p>
                    </Card>
                </div>

                <Divider />

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

                    <Card className="settings-card">
                        <h3>Profile Picture Max Upload Size: <InputNumber
                            formatter={value => `${value}B`}
                            parser={value => value.replace('B', '')}
                            value={this.state.uploadSize}
                            disabled={this.state.uploadLoading}
                            onChange={(value) => this.setState({ uploadSize: value })}
                            onPressEnter={(e) => { this.changeSetting("uploadSize", this.state.uploadSize) }} /></h3>

                        <p>Sets the maximum file upload size for profile pictures (in Bytes). Press <b>Enter</b> to save</p>
                    </Card>

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

                    <Card className="settings-card">
                        <h3>Disable Category Switches:  <Switch disabled={this.state.disableLoading2} onClick={(value) => this.disableSetting("categorySwitchDisable", value)} checked={this.state.categorySwitchDisable} /></h3>
                        <p>Prevents users from switching their scoreboard category. Useful during competitions where you want to lock the user into a category</p>
                    </Card>

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

                    <Card className="settings-card">
                        <h3>User Category Management <UserOutlined /></h3>
                        <Space direction="vertical">
                            {this.state.categoryList.map((category) => {
                                return (
                                    <div style={{ display: 'flex', alignItems: "center" }}>
                                        <Input disabled value={category} />
                                         <MinusCircleOutlined onClick={() => { this.removeCategory(category) }} style={{ cursor: "pointer", marginLeft: "1ch", color: "#f5222d" }} />
                                    </div>
                                )
                            })}
                            <div style={{ display: "flex" }}>
                                <Input value={this.state.newCategoryValue} onChange={(e) => { this.setState({ newCategoryValue: e.target.value }) }} />
                                <Button
                                    loading={this.state.addCategoryLoading}
                                    style={{ marginLeft: "1ch" }}
                                    type="dashed"
                                    onClick={() => {
                                        this.addCategory()
                                    }}
                                >
                                    <PlusOutlined /> Add Category
                                </Button>
                            </div>
                        </Space>
                    </Card>
                </div>

                <Divider />

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

                    <Card className="settings-card">
                        <h3>Max Team Size: <InputNumber
                            value={this.state.teamMaxSize}
                            onChange={(value) => this.setState({ teamMaxSize: value })}
                            onPressEnter={(e) => { this.changeSetting("teamMaxSize", this.state.teamMaxSize) }} />
                        </h3>
                        <p>Sets the maximum number of members in a team. Press <b>Enter</b> to save</p>
                    </Card>

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

                    <Card className="settings-card">
                        <h3>Enable Teams:  <Switch disabled={this.state.disableLoading3} onClick={(value) => this.disableSetting("teamMode", value)} checked={this.state.teamMode} /></h3>
                        <p>Enable teams for the platform. Users in a team will have their scores combined on the scoreboard <br /> Please note that disabling/enabling this will require users to reopen ctfx to resync the scoreboard.</p>
                    </Card>

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

                    <Card className="settings-card">
                        <h3>Disable Team Switching:  <Switch disabled={this.state.disableLoading3} onClick={(value) => this.disableSetting("teamChangeDisable", value)} checked={this.state.teamChangeDisable} /></h3>
                        <p>Prevents users from leaving, joining & creating a team. Enable this option if you want to prevent any team changes during a competition</p>
                    </Card>
                </div>

                <Divider />

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

                    <Card className="settings-card">
                        <h3>Enable Password Reset  <Switch disabled={this.state.disableLoading2} onClick={(value) => this.disableSetting("forgotPass", value)} checked={this.state.forgotPass} /></h3>
                        <p>Allow users to use the "Forgot Password" option to reset their password. <br />Please ensure that you have connected to an SMTP server correctly in the "Email" tab</p>
                    </Card>

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

                    <Card className="settings-card">
                        <h3>Enable Email Verification  <Switch disabled={this.state.disableLoading2} onClick={(value) => this.disableSetting("emailVerify", value)} checked={this.state.emailVerify} /></h3>
                        <p>Forces newly registered users to <b>verify their email</b> before being able to access the site.</p>
                    </Card>

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

                    <Card className="settings-card">
                        <h3>Profile Picture Upload Path
                            <Input
                                value={this.state.uploadPath}
                                onChange={(e) => this.setState({ uploadPath: e.target.value })}
                                onPressEnter={(e) => { this.changeSetting("uploadPath", this.state.uploadPath) }} /></h3>
                        <p>Sets the file upload path for profile pictures. Please ensure that the folder has the appropriate permissions <br />set for the Node process to save the file there. Press <b>Enter</b> to save</p>
                    </Card>
                </div>

            </Layout>
        );
    }
Example #28
Source File: ItemRow.jsx    From erp-crm with MIT License 4 votes vote down vote up
export default function ItemRow({
  field,
  remove,

  current = null,
}) {
  const [totalState, setTotal] = useState(undefined);
  const [price, setPrice] = useState(0);
  const [quantity, setQuantity] = useState(0);
  const money = useMoney();
  const updateQt = (value) => {
    setQuantity(value);
  };
  const updatePrice = (value) => {
    setPrice(value);
  };

  useEffect(() => {
    if (current) {
      const { items } = current;
      const item = items[field.fieldKey];
      if (item) {
        setQuantity(item.quantity);
        setPrice(item.price);
      }
    }
  }, [current]);

  useEffect(() => {
    const currentTotal = price * quantity;

    setTotal(currentTotal.toFixed(2));
  }, [price, quantity]);

  return (
    <Row gutter={[12, 12]} style={{ position: 'relative' }}>
      <Col className="gutter-row" span={5}>
        <Form.Item
          name={[field.name, 'itemName']}
          fieldKey={[field.fieldKey, 'itemName']}
          rules={[{ required: true, message: 'Missing itemName name' }]}
        >
          <Input placeholder="Item Name" />
        </Form.Item>
      </Col>
      <Col className="gutter-row" span={7}>
        <Form.Item name={[field.name, 'description']} fieldKey={[field.fieldKey, 'description']}>
          <Input placeholder="description Name" />
        </Form.Item>
      </Col>
      <Col className="gutter-row" span={3}>
        <Form.Item
          name={[field.name, 'quantity']}
          fieldKey={[field.fieldKey, 'quantity']}
          rules={[{ required: true, message: 'Missing item quantity' }]}
        >
          <InputNumber style={{ width: '100%' }} min={0} onChange={updateQt} />
        </Form.Item>
      </Col>
      <Col className="gutter-row" span={4}>
        <Form.Item
          name={[field.name, 'price']}
          fieldKey={[field.fieldKey, 'price']}
          rules={[{ required: true, message: 'Missing item price' }]}
        >
          <InputNumber
            className="moneyInput"
            onChange={updatePrice}
            min={0}
            controls={false}
            addonAfter={money.currencyPosition === 'after' ? money.currencySymbol : undefined}
            addonBefore={money.currencyPosition === 'before' ? money.currencySymbol : undefined}
          />
        </Form.Item>
      </Col>
      <Col className="gutter-row" span={5}>
        <Form.Item name={[field.name, 'total']}>
          <Form.Item>
            <InputNumber
              readOnly
              className="moneyInput"
              value={totalState}
              min={0}
              controls={false}
              addonAfter={money.currencyPosition === 'after' ? money.currencySymbol : undefined}
              addonBefore={money.currencyPosition === 'before' ? money.currencySymbol : undefined}
              formatter={(value) => money.amountFormatter({ amount: value })}
            />
          </Form.Item>
        </Form.Item>
      </Col>

      <div style={{ position: 'absolute', right: '-20px', top: ' 5px' }}>
        <DeleteOutlined onClick={() => remove(field.name)} />
      </div>
    </Row>
  );
}
Example #29
Source File: OfflineSession.js    From next-terminal with GNU Affero General Public License v3.0 4 votes vote down vote up
render() {

        const columns = [{
            title: '序号',
            dataIndex: 'id',
            key: 'id',
            render: (id, record, index) => {
                return index + 1;
            },
        }, {
            title: '来源IP',
            dataIndex: 'clientIp',
            key: 'clientIp'
        }, {
            title: '接入方式',
            dataIndex: 'mode',
            key: 'mode',
            render: (text) => {
                return (
                    <Tag color={MODE_COLORS[text]}>{text}</Tag>
                )
            }
        }, {
            title: '用户昵称',
            dataIndex: 'creatorName',
            key: 'creatorName'
        }, {
            title: '资产名称',
            dataIndex: 'assetName',
            key: 'assetName'
        }, {
            title: '连接协议',
            dataIndex: 'protocol',
            key: 'protocol',
            render: (text, record) => {
                const title = `${record.username}@${record.ip}:${record.port}`;
                return (
                    <Tooltip title={title}>
                        <Tag color={PROTOCOL_COLORS[text]}>{text}</Tag>
                    </Tooltip>
                )
            }
        }, {
            title: '接入时间',
            dataIndex: 'connectedTime',
            key: 'connectedTime',
            render: (text, record) => {
                return (
                    <Tooltip title={text}>
                        {dayjs(text).fromNow()}
                    </Tooltip>
                )
            }
        }, {
            title: '接入时长',
            dataIndex: 'connectedTime',
            key: 'connectedTime',
            render: (text, record) => {
                return differTime(new Date(record['connectedTime']), new Date(record['disconnectedTime']));
            }
        },
            {
                title: '操作',
                key: 'action',
                render: (text, record) => {
                    let disabled = true;
                    if (record['recording'] && record['recording'] === '1') {
                        disabled = false
                    }

                    return (
                        <div>
                            <Button type="link" size='small'
                                    disabled={disabled}
                                    onClick={() => this.showPlayback(record)}>回放</Button>
                            <Button type="link" size='small'
                                    onClick={() => {
                                        confirm({
                                            title: '您确定要禁止该IP访问本系统吗?',
                                            content: '',
                                            okText: '确定',
                                            okType: 'danger',
                                            cancelText: '取消',
                                            onOk: async () => {
                                                // 向后台提交数据
                                                let formData = {
                                                    ip: record['clientIp'],
                                                    rule: 'reject',
                                                    priority: 99,
                                                }
                                                const result = await request.post('/securities', formData);
                                                if (result.code === 1) {
                                                    message.success('禁用成功');
                                                } else {
                                                    message.error(result.message, 10);
                                                }
                                            }
                                        });
                                    }}>禁用IP</Button>
                            <Button type="link" size='small' danger onClick={() => {
                                confirm({
                                    title: '您确定要删除此会话吗?',
                                    content: '',
                                    okText: '确定',
                                    okType: 'danger',
                                    cancelText: '取消',
                                    onOk: () => {
                                        this.del(record.id)
                                    }
                                });
                            }}>删除</Button>
                        </div>
                    )
                },
            }
        ];

        const selectedRowKeys = this.state.selectedRowKeys;
        const rowSelection = {
            selectedRowKeys: this.state.selectedRowKeys,
            onChange: (selectedRowKeys, selectedRows) => {
                this.setState({selectedRowKeys});
            },
        };
        const hasSelected = selectedRowKeys.length > 0;

        const userOptions = this.state.users.map(d => <Select.Option key={d.id}
                                                                     value={d.id}>{d.nickname}</Select.Option>);
        const assetOptions = this.state.assets.map(d => <Select.Option key={d.id}
                                                                       value={d.id}>{d.name}</Select.Option>);

        return (
            <>
                <Content className="site-layout-background page-content">
                    <div style={{marginBottom: 20}}>
                        <Row justify="space-around" align="middle" gutter={24}>
                            <Col span={4} key={1}>
                                <Title level={3}>离线会话列表</Title>
                            </Col>
                            <Col span={20} key={2} style={{textAlign: 'right'}}>
                                <Space>

                                    <Search
                                        ref={this.inputRefOfClientIp}
                                        placeholder="来源IP"
                                        allowClear
                                        onSearch={this.handleSearchByClientIp}
                                    />

                                    <Select
                                        style={{width: 140}}
                                        showSearch
                                        value={this.state.queryParams.userId}
                                        placeholder='用户昵称'
                                        onSearch={this.handleSearchByNickname}
                                        onChange={this.handleChangeByUserId}
                                        filterOption={false}
                                        allowClear
                                    >
                                        {userOptions}
                                    </Select>

                                    <Select
                                        style={{width: 140}}
                                        showSearch
                                        value={this.state.queryParams.assetId}
                                        placeholder='资产名称'
                                        onSearch={this.handleSearchByAssetName}
                                        onChange={this.handleChangeByAssetId}
                                        filterOption={false}
                                    >
                                        {assetOptions}
                                    </Select>

                                    <Select onChange={this.handleChangeByRead}
                                            value={this.state.queryParams.reviewed ? this.state.queryParams.reviewed : ''}
                                            style={{width: 100}}>
                                        <Select.Option value="">全部会话</Select.Option>
                                        <Select.Option value="true">只看已读</Select.Option>
                                        <Select.Option value="false">只看未读</Select.Option>
                                    </Select>

                                    <Select onChange={this.handleChangeByProtocol}
                                            value={this.state.queryParams.protocol ? this.state.queryParams.protocol : ''}
                                            style={{width: 100}}>
                                        <Select.Option value="">全部协议</Select.Option>
                                        <Select.Option value="rdp">rdp</Select.Option>
                                        <Select.Option value="ssh">ssh</Select.Option>
                                        <Select.Option value="vnc">vnc</Select.Option>
                                        <Select.Option value="telnet">telnet</Select.Option>
                                        <Select.Option value="kubernetes">kubernetes</Select.Option>
                                    </Select>

                                    <Tooltip title='重置查询'>

                                        <Button icon={<UndoOutlined/>} onClick={() => {
                                            this.inputRefOfClientIp.current.setValue('');
                                            this.loadTableData({
                                                pageIndex: 1,
                                                pageSize: 10,
                                                protocol: ''
                                            })
                                        }}>

                                        </Button>
                                    </Tooltip>

                                    <Divider type="vertical"/>

                                    <Tooltip title="刷新列表">
                                        <Button icon={<SyncOutlined/>} onClick={() => {
                                            this.loadTableData(this.state.queryParams)
                                        }}>

                                        </Button>
                                    </Tooltip>

                                    <Tooltip title="全部标为已阅">
                                        <Button icon={<CheckOutlined />}
                                                loading={this.state.reviewedAllBtnLoading}
                                                onClick={this.handleAllReviewed}>
                                        </Button>
                                    </Tooltip>

                                    <Tooltip title="标为已阅">
                                        <Button disabled={!hasSelected} icon={<EyeOutlined />}
                                                loading={this.state.reviewedBtnLoading}
                                                onClick={this.handleReviewed}>

                                        </Button>
                                    </Tooltip>

                                    <Tooltip title="标为未阅">
                                        <Button disabled={!hasSelected} icon={<EyeInvisibleOutlined />}
                                                loading={this.state.unreviewedBtnLoading}
                                                onClick={this.handleUnreviewed}>

                                        </Button>
                                    </Tooltip>

                                    <Tooltip title="批量删除">
                                        <Button type="primary" danger disabled={!hasSelected} icon={<DeleteOutlined/>}
                                                loading={this.state.delBtnLoading}
                                                onClick={() => {
                                                    const content = <div>
                                                        您确定要删除选中的<Text style={{color: '#1890FF'}}
                                                                       strong>{this.state.selectedRowKeys.length}</Text>条记录吗?
                                                    </div>;
                                                    confirm({
                                                        icon: <ExclamationCircleOutlined/>,
                                                        content: content,
                                                        onOk: () => {
                                                            this.batchDelete()
                                                        },
                                                        onCancel() {

                                                        },
                                                    });
                                                }}>
                                        </Button>
                                    </Tooltip>

                                    <Tooltip title="清空">
                                        <Button type="primary" danger icon={<ClearOutlined/>}
                                                loading={this.state.clearBtnLoading}
                                                onClick={() => {
                                                    const content = <Text style={{color: 'red'}}
                                                                          strong>您确定要清空全部的离线会话吗?</Text>;
                                                    confirm({
                                                        icon: <ExclamationCircleOutlined/>,
                                                        content: content,
                                                        okType: 'danger',
                                                        onOk: this.clearSession,
                                                        onCancel() {

                                                        },
                                                    });
                                                }}>

                                        </Button>
                                    </Tooltip>

                                </Space>
                            </Col>
                        </Row>
                    </div>

                    <Table rowSelection={rowSelection}
                           dataSource={this.state.items}
                           columns={columns}
                           position={'both'}
                           pagination={{
                               showSizeChanger: true,
                               current: this.state.queryParams.pageIndex,
                               pageSize: this.state.queryParams.pageSize,
                               onChange: this.handleChangPage,
                               total: this.state.total,
                               showTotal: total => `总计 ${total} 条`
                           }}
                           loading={this.state.loading}
                           rowClassName={(record, index) => {
                               return record['reviewed'] ? '' : 'unreviewed';
                           }}
                    />

                    {
                        this.state.playbackVisible ?
                            <Modal
                                className='modal-no-padding'
                                title={`会话回放 来源IP:${this.state.selectedRow['clientIp']} 用户昵称:${this.state.selectedRow['creatorName']} 资产名称:${this.state.selectedRow['assetName']} 网络:${this.state.selectedRow['username']}@${this.state.selectedRow['ip']}:${this.state.selectedRow['port']}`}
                                centered={true}
                                visible={this.state.playbackVisible}
                                onCancel={this.hidePlayback}
                                width={window.innerWidth * 0.8}
                                footer={null}
                                destroyOnClose
                                maskClosable={false}
                            >
                                {
                                    this.state.selectedRow['mode'] === 'native' || this.state.selectedRow['mode'] === 'terminal' ?
                                        <iframe
                                            title='recording'
                                            style={{
                                                width: '100%',
                                                // height: this.state.iFrameHeight,
                                                overflow: 'visible'
                                            }}
                                            onLoad={() => {
                                                // constant obj = ReactDOM.findDOMNode(this);
                                                // this.setState({
                                                //     "iFrameHeight": obj.contentWindow.document.body.scrollHeight + 'px'
                                                // });
                                            }}
                                            ref="iframe"
                                            src={'./asciinema.html?sessionId=' + this.state.selectedRow['id']}
                                            width="100%"
                                            height={window.innerHeight * 0.8}
                                            frameBorder="0"
                                        />
                                        : <Playback sessionId={this.state.selectedRow['id']}/>
                                }

                            </Modal> : undefined
                    }

                </Content>
            </>
        );
    }