antd#Table JavaScript Examples
The following examples show how to use
antd#Table.
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: apytable.js From acy-dex-interface with MIT License | 6 votes |
APYtable = props => {
//read props
return (
<div className={styles.APYtable}>
<div className={styles.tableHead}>
<div className={styles.tableHeadBlock}>
<div className={styles.data}>APY 8.88%</div>
<div className={styles.expContent}>30 day trailing average</div>
</div>
<div className={styles.tableHeadBlock}>
<div className={styles.data}>564.18 OUSD</div>
<div className={styles.expContent}>Next rebase</div>
</div>
</div>
<div color="#fff">Daily APY for the last thirty days:</div>
<div className={styles.tableDate}>
<Table dataSource={dataSource} columns={columns} pagination={false} width/>
</div>
</div>
);
}
Example #2
Source File: index.js From QiskitFlow with Apache License 2.0 | 6 votes |
render() {
let experiments = this.state.experiments;
let data = experiments.map((experiment, i) => {
return {
key: i,
experiment: experiment.name,
author: 'Admin',
runs: experiment.runs,
createdAt: experiment.created_at,
}
})
return (
<div>
<Row>
<Col span={this.state.run ? 12 : 24}>
<div style={{ margin: "0 20px" }}>
<Table
className="components-table-demo-nested"
columns={experimentsColumns}
expandable={{ expandedRowRender: this.expandedRowRender.bind(this) }}
dataSource={data}
/>
</div>
</Col>
<Col span={this.state.run ? 12 : 0}>
<RunWidget run={this.state.run} />
</Col>
</Row>
</div>
)
}
Example #3
Source File: index.jsx From react-antd-admin-template with MIT License | 6 votes |
render() {
const cardContent = `此页面是用来展示通过项目内埋点收集到的异常信息。你可以点击不同种类的异常按钮,来观察捕获到的异常信息。`;
const { bugList } = this.props
return (
<div className="app-container">
<TypingCard title="Bug收集" source={cardContent} />
<br />
<Collapse defaultActiveKey={["1"]}>
<Panel header="报错" key="1">
<Button type="primary" onClick={this.jsError}>jsError</Button>
<Button type="primary" onClick={this.loadResourceError} style={{marginLeft:"20px"}}>资源加载异常</Button>
</Panel>
</Collapse>
<br />
<Table
bordered
rowKey={(record) => record.timestamp}
dataSource={bugList}
pagination={false}
>
<Column title="序号" dataIndex="id" key="id" width={60} render={(text,record,index) => index+1}/>
<Column title="监控指标" dataIndex="kind" key="kind" width={80} />
<Column title="异常类型" dataIndex="errorType" key="errorType" width={160} />
<Column title="url" dataIndex="url" key="url" width={150} />
<Column title="异常信息" dataIndex="desc" key="desc" width={300} ellipsis={true}/>
<Column title="异常堆栈" dataIndex="stack" key="stack" width={300} ellipsis={true}/>
<Column title="操作元素" dataIndex="selector" key="selector" width={195} ellipsis={true}/>
<Column title="userAgent" dataIndex="userAgent" key="userAgent" width={100} />
<Column title="时间" dataIndex="timestamp" key="timestamp" width={100} render={(value) => timestampToTime(value)}/>
</Table>
</div>
);
}
Example #4
Source File: tableList.js From doraemon with GNU General Public License v3.0 | 6 votes |
render() {
const {
currentPage,
pageSize,
totalCount,
onShowSizeChange,
onChange,
columns,
} = this.props
const hasMultiHead = columns.filter(one => !!one.children).length > 0
return (
<div className={`table-content ${hasMultiHead ? 'clear-overlap-border' : ''}`}>
<Table
pagination={false}
bordered
rowKey="id"
// rowClassName={this.props.rowClassName}
{...this.props}
/>
{ currentPage ?
<Pagination
total={totalCount || 0}
showSizeChanger // 是否可以改变pageSize
showQuickJumper={false}// 是否可以快速跳转某一页
onShowSizeChange={onShowSizeChange}
onChange={onChange}
showTotal={_totalCount => `共 ${_totalCount} 条`}
current={currentPage || 1}
pageSize={pageSize || 10}
{...this.props}
/> : null
}
</div>
)
}
Example #5
Source File: index.jsx From micro-front-template with MIT License | 6 votes |
List = () => {
// 设置列表信息
const [data, setData] = useState([]);
// 设置页码信息
const [page, setPage] = useState(1);
const [pageInfo, setPageInfo] = useState();
useEffect(() => {
console.log({ page });
(async () => {
const result = await fetchVegetable(page, 10);
const { vegetableList } = result.data;
setData(() => vegetableList.items);
setPageInfo(() => ({
current: vegetableList.page,
pageSize: vegetableList.pageSize,
total: vegetableList.total,
onChange: (page) => setPage(page),
}));
})();
}, [page]);
return (
<Card title="React 子应用列表页">
<Table rowKey="_id" dataSource={data} pagination={pageInfo}>
<Column dataIndex="poster" render={(text) => <Avatar src={text} />} />
<Column dataIndex="name" />
<Column dataIndex="price" render={(text) => <>¥ {text}</>} />
</Table>
</Card>
);
}
Example #6
Source File: index.js From online-test-platform with Apache License 2.0 | 6 votes |
render() {
const {
rule: { data },
loading,
} = this.props;
const { current, modalVisible } = this.state;
const parentMethods = {
handleAdd: this.handleAdd,
handleUpdate: this.handleUpdate,
handleModalVisible: this.handleModalVisible,
};
return (
<PageHeaderWrapper>
<Card bordered={false}>
<div className={styles.tableList}>
<div className={styles.tableListOperator}>
<Button icon="plus" type="primary" onClick={() => this.handleModalVisible(true)}>
新建
</Button>
</div>
<Table
rowKey="id"
loading={loading}
dataSource={data.list}
bordered
columns={this.columns}
pagination={{ showSizeChanger: true, showQuickJumper: true, ...data.pagination }}
onChange={this.handleStandardTableChange}
/>
</div>
</Card>
<CreateForm {...parentMethods} current={current} modalVisible={modalVisible} />
</PageHeaderWrapper>
);
}
Example #7
Source File: index.jsx From juno with Apache License 2.0 | 6 votes |
render() {
const { data, rowKey, ...rest } = this.props;
const { list = [], pagination = false } = data || {};
const paginationProps = pagination
? {
showSizeChanger: true,
showQuickJumper: true,
...pagination,
}
: false;
return (
<div className={styles.standardTable}>
<Table
key={Date.now()}
rowKey={rowKey || 'id'}
dataSource={list}
pagination={paginationProps}
onChange={this.handleTableChange}
{...rest}
/>
</div>
);
}
Example #8
Source File: SchemaTable.js From YApi-X with MIT License | 6 votes |
render() {
let product;
try {
product = json5.parse(this.props.dataSource);
} catch (e) {
product = null;
}
if (!product) {
return null;
}
let data = schemaTransformToTable(product);
data = _.isArray(data) ? data : [];
return <Table bordered size="small" pagination={false} dataSource={data} columns={columns} />;
}
Example #9
Source File: index.js From gobench with Apache License 2.0 | 6 votes |
Chart8 = () => {
return (
<div>
<div className={`${style.textDivider} mb-2`}>
<h4 className={`${style.textDividerContent} font-size-24 font-weight-bold`}>
Waiting actions
</h4>
</div>
<div className={style.table}>
<Table
columns={columns}
dataSource={data.table}
pagination={false}
rowSelection={rowSelection}
/>
</div>
</div>
)
}
Example #10
Source File: index.js From acy-dex-interface with MIT License | 5 votes |
render() {
const { selectedRowKeys, needTotalList } = this.state;
const { data = {}, rowKey, ...rest } = this.props;
const { list = [], pagination } = data;
const paginationProps = {
showSizeChanger: true,
showQuickJumper: true,
...pagination,
};
const rowSelection = {
selectedRowKeys,
onChange: this.handleRowSelectChange,
getCheckboxProps: record => ({
disabled: record.disabled,
}),
};
return (
<div className={styles.standardTable}>
<div className={styles.tableAlert}>
<Alert
message={
<Fragment>
已选择 <a style={{ fontWeight: 600 }}>{selectedRowKeys.length}</a> 项
{needTotalList.map(item => (
<span style={{ marginLeft: 8 }} key={item.dataIndex}>
{item.title}
总计
<span style={{ fontWeight: 600 }}>
{item.render ? item.render(item.total) : item.total}
</span>
</span>
))}
<a onClick={this.cleanSelectedKeys} style={{ marginLeft: 24 }}>
清空
</a>
</Fragment>
}
type="info"
showIcon
/>
</div>
<Table
rowKey={rowKey || 'key'}
rowSelection={rowSelection}
dataSource={list}
pagination={paginationProps}
onChange={this.handleTableChange}
{...rest}
/>
</div>
);
}
Example #11
Source File: FeedbackTable.js From video-journal-for-teams-fe with MIT License | 5 votes |
function FeedbackTable({ feedback }) {
return <Table columns={columns} dataSource={feedback} pagination={{pageSize: 100}}rowKey="id" />;
}
Example #12
Source File: Scoreboard.js From ctf_platform with MIT License | 5 votes |
{ Column } = Table
Example #13
Source File: index.js From QiskitFlow with Apache License 2.0 | 5 votes |
expandedRowRender(experiment) {
let runs = experiment.runs.map((run, i) => {
return {
key: i,
date: run.created_at,
name: run.uuid,
operation: run
}
})
const runColumns = [
{ title: 'Date', dataIndex: 'date', key: 'date' },
{ title: 'Run', dataIndex: 'name', key: 'name' },
{
title: 'Status',
key: 'state',
render: () => (
<span>
<Badge status="success" />
Finished
</span>
),
},
{ title: 'Tags', dataIndex: 'tags', key: 'tags', render: () => <Tag>Qiskit</Tag> },
{
title: 'Action',
dataIndex: 'operation',
key: 'operation',
render: (run) => (
<Space size="middle">
<a onClick={() => {
this.setState({...this.state, run: run})
}}>View</a>
<a>Rerun</a>
</Space>
),
},
];
return <Table
columns={runColumns}
dataSource={runs}
pagination={false} />;
}
Example #14
Source File: SimpleTableWidget.js From dexwebapp with Apache License 2.0 | 5 votes |
SimpleTableWidget = ({
columnBuilders,
rowData,
emptyText,
margin,
loading,
}) => {
const _rowData = rowData || [];
const customizeRenderEmpty = () => <EmptyTableIndicator text={emptyText} />;
const columns = columnBuilders.map((builder, j) => ({
...builder,
title: (
<Header margin={margin}>
<I s={builder.label} />
</Header>
),
dataIndex: 'col_' + j,
}));
const dataSource = _rowData.map((row, i) => {
var rowValue = { key: i };
columnBuilders.forEach((builder, j) => {
rowValue['col_' + j] = (
<Cell margin={margin} sortedValue={builder.sortedValue(row)}>
{builder.getColValue(row)}
</Cell>
);
});
return rowValue;
});
return (
<SimpleTableContainer>
<ConfigProvider
renderEmpty={dataSource.length === 0 && customizeRenderEmpty}
>
<TableLoadingSpin loading={loading}>
<Table
tableLayout="auto"
dataSource={dataSource}
columns={columns}
pagination={false}
/>
</TableLoadingSpin>
</ConfigProvider>
</SimpleTableContainer>
);
}
Example #15
Source File: index.jsx From react-antd-admin-template with MIT License | 5 votes |
{ Column } = Table
Example #16
Source File: group.js From doraemon with GNU General Public License v3.0 | 5 votes |
render() {
const { dataSource } = this.state;
const columns = [
{ title: '编号', align: 'center', dataIndex: 'id' },
{
title: '组名',
align: 'center',
dataIndex: 'name',
...this.getColumnSearchProps('name'),
filterDropdownVisible: this.state.filterItem.name,
},
{
title: '成员',
align: 'center',
dataIndex: 'user',
...this.getColumnSearchProps('user'),
filterDropdownVisible: this.state.filterItem.user,
},
{
title: '操作',
align: 'center',
key: 'action',
render: (text, record, index) => (
<span>
<a onClick={() => this.handleEdit(text, record)}>编辑</a>
<Popconfirm
title="确定要删除吗?"
onConfirm={() => this.handleDelete(record)}
okText="Yes"
cancelText="No"
>
<a href="#">删除</a>
</Popconfirm>
</span>
),
},
];
return (
<div>
<div id="top-section">
<Button type="primary" onClick={this.handleAdd}>添加</Button>
</div>
<CreateEditGroup onRef={c => this.onRef(c)} onSubmit={this.rulesUpdate} />
<Table dataSource={dataSource} columns={columns} rowKey="id" />
</div>
)
}
Example #17
Source File: index.jsx From micro-front-template with MIT License | 5 votes |
{ Column } = Table
Example #18
Source File: TransferFormStudents.jsx From node-project-manager with Apache License 2.0 | 5 votes |
TableTransfer = ({ leftColumns, rightColumns, ...restProps }) => (
<Transfer {...restProps} showSelectAll={false}>
{({
direction,
filteredItems,
onItemSelectAll,
onItemSelect,
selectedKeys: listSelectedKeys,
disabled: listDisabled,
}) => {
const columns = direction === "left" ? leftColumns : rightColumns;
const rowSelection = {
getCheckboxProps: (item) => ({
disabled: listDisabled || item.disabled,
}),
onSelectAll(selected, selectedRows) {
const treeSelectedKeys = selectedRows
.filter((item) => !item.disabled)
.map(({ key }) => key);
const diffKeys = selected
? difference(treeSelectedKeys, listSelectedKeys)
: difference(listSelectedKeys, treeSelectedKeys);
onItemSelectAll(diffKeys, selected);
},
onSelect({ key }, selected) {
onItemSelect(key, selected);
},
selectedRowKeys: listSelectedKeys,
};
return (
<Table
rowSelection={rowSelection}
columns={columns}
dataSource={filteredItems}
size="small"
style={{ pointerEvents: listDisabled ? "none" : null }}
onRow={({ key, disabled: itemDisabled }) => ({
onClick: () => {
if (itemDisabled || listDisabled) return;
onItemSelect(key, !listSelectedKeys.includes(key));
},
})}
/>
);
}}
</Transfer>
)
Example #19
Source File: Table.jsx From React-Nest-Admin with MIT License | 5 votes |
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 #20
Source File: MenteeList.js From codeclannigeria-frontend with MIT License | 5 votes |
function MenteeList({ mentees, userData, history, getUserMenteesProfileApi }) {
const columns = [
{
title: 'id',
dataIndex: 'id',
key: 'id',
render: text => (
<Link to={`/dashboard/mentor/mentee/${text}`}>{text}</Link>
),
},
{
title: 'First Name',
dataIndex: 'firstName',
sorter: (a, b) => a.firstName.length - b.firstName.length,
sortDirections: ['descend'],
},
{
title: 'Last Name',
dataIndex: 'lastName',
},
// {
// title: 'Track',
// dataIndex: 'tracks',
// render: (text, record) =>
// record.tracks && record.tracks.length > 0
// ? record.tracks[0].title
// : 'Not Enrolled Yet',
// },
];
useEffect(() => {
if (userData) {
const {
city,
country,
phoneNumber,
description,
technologies,
} = userData;
if (
!city ||
!country ||
!phoneNumber
) {
// return
history.push({
pathname: '/dashboard/mentor/profile',
state: { editProfile: true },
});
}
}
}, [userData, history]);
const fetchMentees = useCallback(() => {
getUserMenteesProfileApi();
}, [getUserMenteesProfileApi]);
useEffect(() => {
fetchMentees();
}, [fetchMentees]);
return (
<div>
<h2 className="ml-4">Your Mentees</h2>
<Table
className="mentee-table ml-4"
columns={columns}
dataSource={mentees}
size="small"
pagination={{ pageSize: 10 }}
// scroll={{ y: 240 }}
/>
</div>
);
}
Example #21
Source File: ListNewsletter.js From Peppermint with GNU General Public License v3.0 | 5 votes |
ListNewsletter = () => {
const [n, setN] = useState([]);
const getN = async () => {
await fetch(`/api/v1/newsletter/get`, {
method: "GET",
headers: {
"Content-Type": "application/json",
Authorization: "Bearer " + localStorage.getItem("jwt"),
},
})
.then((res) => res.json())
.then((res) => {
if (res) {
setN(res.newsletters);
}
});
};
useEffect(() => {
getN();
}, []);
const columns = [
{
title: "Title",
dataIndex: "title",
key: "title",
width: 300,
},
{
key: "action",
render: (text, record) => <ViewNewsletter n={record} />,
},
];
return (
<div>
<Table
showHeader={false}
dataSource={n}
columns={columns}
pagination={{
defaultPageSize: 10,
showSizeChanger: true,
pageSizeOptions: ["3", "5", "10"],
}}
/>
</div>
);
}
Example #22
Source File: index.jsx From AgileTC with Apache License 2.0 | 5 votes |
render() {
const rowSelection = {
onChange: (selectedRowKeys, selectedRows) => {
this.setState({ rowKeys: selectedRowKeys, rows: selectedRows })
},
getCheckboxProps: record => ({
disabled: this.state.rowKeys.length >= 2 && !this.state.rowKeys.includes(record.id),
name: record.name,
}),
}
return (
<section style={{ marginBottom: 30 }}>
<Headers />
<Card
bordered={false}
className={this.state.rowKeys.length >= 2 ? 'contras_card' : 'contras_card_default'}
>
<div className="contras_title">
{/* <span>历史版本</span> */}
<Tooltip
placement="top"
title={this.state.rowKeys.length < 2 ? '选择两个版本后,才可以对比哦~' : null}
>
<Button
type="primary"
disabled={this.state.rowKeys.length < 2}
onClick={this.contrastClick}
>
对比已选择版本
</Button>
</Tooltip>
</div>
<Table
rowKey="id"
rowSelection={rowSelection}
columns={this.setTableColums()}
dataSource={this.state.historyList}
/>
</Card>
</section>
)
}
Example #23
Source File: checkResource.jsx From juno with Apache License 2.0 | 5 votes |
render() {
const that = this;
const { list = [], show } = this.props;
const cols = [
{
key: 'key',
dataIndex: 'key',
title: 'Key',
},
{
key: 'resource_name',
dataIndex: 'resource_name',
title: '资源名',
},
{
key: 'config_value',
dataIndex: 'config_value',
title: '配置中的值',
},
{
key: 'resource_value',
dataIndex: 'resource_value',
title: '最新的资源值',
},
];
return (
<Modal
title="资源检查"
visible={show}
maskClosable
onCancel={this.props.cancel}
footer={null}
destroyOnClose
width={1200}
>
<div>
<Table columns={cols} dataSource={list} />
<Button type={'primary'} onClick={this.syncResource} disabled={list.length === 0}>
一键同步
</Button>
</div>
</Modal>
);
}
Example #24
Source File: SpamDays.js From react-portal with MIT License | 5 votes |
SpamDays = () => {
let today = new Date();
const [isLoading, setIsLoading] = useState(false);
const [users, setUsers] = useState([]);
const getBday = obj => {
let days;
if (obj.dob) {
let bday = new Date(obj.dob.split("T")[0]);
let bdayThisYear = new Date(
today.getFullYear(),
bday.getMonth(),
bday.getDate()
);
today.setHours(0, 0, 0, 0);
if (today > bdayThisYear) {
bdayThisYear.setFullYear(today.getFullYear() + 1);
}
let diff = bdayThisYear - today;
days = Math.round(diff / 8.64e7);
}
if (days <= 30) {
return { ...obj, daysLeft: days };
}
};
useEffect(() => {
(async () => {
setIsLoading(true);
let arr = [];
try {
let params = {
sortBy: "name"
};
const { data } = await getUsersService(params);
data.forEach(d => {
if (getBday(d)) arr.push(getBday(d));
});
setUsers(arr);
setIsLoading(false);
} catch (err) {
_notification("warning", "Error", err.message);
}
})();
// eslint-disable-next-line react-hooks/exhaustive-deps
}, []);
return (
<>
<Card style={{ marginTop: "16px" }}>
<div
style={{
display: "flex",
justifyContent: "space-between"
}}
>
<h2 style={{ fontWeight: 700 }}>Spam Days</h2>
<span>
<FaBirthdayCake
style={{ height: "2em", width: "auto" }}
/>
</span>
</div>
<hr />
<Table
loading={isLoading}
dataSource={users}
columns={columns}
pagination={false}
/>
</Card>
</>
);
}
Example #25
Source File: Broker.js From kafka-map with Apache License 2.0 | 5 votes |
render() {
const columns = [{
title: 'ID',
dataIndex: 'id',
key: 'id'
}, {
title: 'Host',
dataIndex: 'host',
key: 'host',
defaultSortOrder: 'ascend',
}, {
title: 'Port',
dataIndex: 'port',
key: 'port',
}, {
title: 'Partitions as Leader',
dataIndex: 'leaderPartitions',
key: 'leaderPartitions',
render: (leaderPartitions, record, index) => {
return <Tooltip title={leaderPartitions.join('、')}>
<Button type="link" size='small'>{leaderPartitions.length}</Button>
</Tooltip>;
}
}, {
title: 'Partitions as Follower',
dataIndex: 'followerPartitions',
key: 'followerPartitions',
render: (followerPartitions, record, index) => {
return <Tooltip title={followerPartitions.join('、')}>
<Button type="link" size='small'>{followerPartitions.length}</Button>
</Tooltip>;
}
}];
return (
<div>
<div className='kd-page-header'>
<PageHeader
className="site-page-header"
onBack={() => {
this.props.history.goBack();
}}
title={this.state.clusterName}
subTitle={<FormattedMessage id="broker-management" />}
/>
</div>
<div className='kd-content'>
<div style={{marginBottom: 20}}>
<Row justify="space-around" align="middle" gutter={24}>
<Col span={8} key={1}>
<Title level={3}>Broker</Title>
</Col>
<Col span={16} key={2} style={{textAlign: 'right'}}>
</Col>
</Row>
</div>
<Table
rowKey='id'
dataSource={this.state.items}
columns={columns}
position={'both'}
size={'small'}
loading={this.state.loading}
pagination={{
showSizeChanger: true,
total: this.state.items.length,
showTotal: total => <FormattedMessage id="total-items" values={{total}}/>
}}
/>
</div>
</div>
);
}
Example #26
Source File: View.js From YApi-X with MIT License | 5 votes |
req_query(query) {
const columns = [
{
title: '参数名称',
dataIndex: 'name',
width: 140,
key: 'name',
},
{
title: '类型',
dataIndex: 'type',
width: 140,
key: 'type',
},
{
title: '是否必须',
width: 100,
dataIndex: 'required',
key: 'required',
},
{
title: '示例',
dataIndex: 'example',
key: 'example',
width: 80,
render(_, item) {
return <p style={{ whiteSpace: 'pre-wrap' }}>{item.example}</p>
},
},
{
title: '备注',
dataIndex: 'value',
key: 'value',
render(_, item) {
return <p style={{ whiteSpace: 'pre-wrap' }}>{item.value}</p>
},
},
]
const dataSource = []
if (query && query.length) {
query.map((item, i) => {
dataSource.push({
key: i,
name: item.name,
value: item.desc,
example: item.example,
required: item.required == 0 ? '否' : '是',
type: item.type,
})
})
}
return (
<Table
bordered
size='small'
pagination={false}
columns={columns}
dataSource={dataSource}
/>
)
}
Example #27
Source File: SysDepartments.jsx From spring-boot-plus-admin-react with Apache License 2.0 | 5 votes |
render() {
const {SysDepartmentModel: {tree}, form, submitting} = this.props;
const {getFieldDecorator} = form;
const columns = [
{title: '部门名称', dataIndex: 'name'},
{title: '排序 ', dataIndex: 'sort'},
{
title: '部门状态', dataIndex: 'state',
render: (text, record) => this.renderStateTag(record.state),
},
{title: '备注', dataIndex: 'remark'},
{title: '创建时间', dataIndex: 'createTime'},
{
title: '操作', dataIndex: 'action',
render: (text, record) => (<Button.Group size="small">
<Button type="link" size="small" onClick={() => this.handlerGetById(record.id)}>修改</Button>
<Popconfirm
title={`你确定要删除部门 ${record.name} 吗?`}
onConfirm={() => this.handlerDeleteById(record.id)}
okText="是"
cancelText="否"
>
<Button type='link' size="small">删除</Button>
</Popconfirm>
</Button.Group>)
},
];
return (
<PageHeaderWrapper>
<Card>
<Form layout="inline" onSubmit={this.onSubmit}>
<Row gutter={24}>
<Col span={6}>
<Form.Item label="部门名">
{getFieldDecorator('Departmentname', {})(
<Input placeholder="请输入部门名"/>,
)}
</Form.Item>
</Col>
<Col span={12}>
<div style={{float: 'right'}}>
<Button type="primary" htmlType="submit" loading={submitting}>
查询
</Button>
<Button loading={submitting} style={{marginLeft: 8}} onClick={() => {
this.props.form.resetFields();
this.fetchSysDepartmentList();
}}>
重置
</Button>
</div>
</Col>
</Row>
</Form>
<Button type="primary" className={style.tool}
onClick={() => this.handlerVisibleAddModal()}>添加</Button>
<Table
className={style.table}
columns={columns}
rowKey={record => record.id}
loading={submitting}
dataSource={tree}
pagination={false}
/>
<SysDepartmentAdd
visible={this.state.visibleAddModal}
handlerVisibleAddModal={this.handlerVisibleAddModal}
/>
<SysDepartmentUpdate
visible={this.state.visibleUpdateModal}
handlerVisibleAddModal={this.handlerVisibleUpdateModal}
/>
</Card>
</PageHeaderWrapper>
);
}
Example #28
Source File: index.js From gobench with Apache License 2.0 | 5 votes |
Chart7 = () => {
return (
<div>
<div className="height-300 position-relative mb-3">
<VectorMap
map="us_aea"
backgroundColor="transparent"
containerStyle={{
width: '100%',
height: '100%',
}}
containerClassName="map"
regionStyle={{
initial: {
fill: '#d1e6fa',
'fill-opacity': 0.9,
stroke: '#fff',
'stroke-width': 2,
'stroke-opacity': 0.05,
},
hover: {
'fill-opacity': 0.8,
fill: '#1b55e3',
cursor: 'pointer',
},
}}
series={{
regions: [
{
attribute: 'fill',
values: {
'US-CA': '#69b2f8',
'US-MO': '#69b2f8',
'US-FL': '#69b2f8',
'US-OR': '#69b2f8',
'US-TX': '#69b2f8',
},
},
],
}}
/>
</div>
<div className={style.table}>
<Table columns={columns} dataSource={data.table} pagination={false} />
</div>
</div>
)
}
Example #29
Source File: index.js From acy-dex-interface with MIT License | 4 votes |
AcyLiquidityPositions = (props) => {
// const [userLiquidityPools, setUserLiquidityPools] = useState([]); // list of pools that user has share
const { account, chainId, library, tokenList: supportedTokens, scanUrlPrefix: { scanUrl: scanUrlPrefix }, farmSetting: { API_URL: apiUrlPrefix } } = useConstantLoader();
const { activate } = useWeb3React();
const [loading, setLoading] = useState(true);
const [isModalVisible, setIsModalVisible] = useState(false);
const [removeLiquidityPosition, setRemoveLiquidityPosition] = useState(null);
const [userLPHandlers, setUserLPHandlers] = useState([]);
// const [userLPData, setUserLPData] = useState([]); // fetch a list of valid pool from backend
const [userLPShares, setUserLPShares] = useState([]);
const [readListPointer, setReadListPointer] = useState(0); // last processed read position of "validPoolPairs"
const displayCountIncrement = 5;
// fullTableData = userLPData + volume/APR
const [fullTableData, setFullTableData] = useState([])
// search component
const [filteredData, setFilteredData] = useState();
const [keyword, setKeyword] = useState("");
const [showSearch, setShowSearch] = useState(false);
// table expanded row
const [expandedRowKey, setExpandedRowKey] = useState([]);
// const getColumnSearchProps = (dataIndex) => ({
// filterDropdown: ({
// setSelectedKeys,
// selectedKeys,
// confirm,
// clearFilters
// }) =>
// // {
// // setTableFilters([dataIndex, setSelectedKeys, selectedKeys, confirm, clearFilters])
// // return (<></>)
// // },
// (
// <div style={{ padding: 8, backgroundColor: "grey", borderRadius: "3px" }}>
// {/* {setTableFilters([dataIndex, setSelectedKeys, selectedKeys, confirm, clearFilters])} */}
// {setTableFilters(() => setSelectedKeys)}
// <Input
// onChange={(e) =>
// setSelectedKeys(e.target.value ? [e.target.value] : [])
// }
// onPressEnter={() =>
// handleSearch(selectedKeys, confirm, dataIndex)
// }
// style={{ width: 188, marginBottom: 8, display: "block" }}
// />
// <Button
// type="primary"
// onClick={() => handleSearch(selectedKeys, confirm, dataIndex)}
// icon="search"
// size="small"
// style={{ width: 90, marginRight: 8 }}
// >
// Search
// </Button>
// <Button
// onClick={() => handleReset(clearFilters)}
// size="small"
// style={{ width: 90, backgroundColor: "black" }}
// >
// Reset
// </Button>
// </div>
// ),
// filterDropdown: () => <> </>,
// filterIcon: (filtered) => (
// <Icon type="search" style={{ backgroundColor: "transparent", color: filtered ? "orange" : "white" }} onClick={() => {setShowSearch(!showSearch); console.log(showSearch) } } />
// ),
// onFilter: (value, record) => {
// console.log("onFilter");
// return record[dataIndex].toString().toLowerCase().includes(value.toLowerCase());
// },
// });
// const handleSearch = (selectedKeys, confirm, dataIndex) => {
// confirm();
// };
// const handleReset = (clearFilters) => {
// clearFilters();
// };
// table data definitions
const columns = useMemo(() => [
{
title: '#',
className: 'centerAlignTableHeader',
key: 'index',
render: (text, record, index) => (
<div>
{index + 1}
</div>
),
width: '3rem',
visible: !isMobile
},
{
title: <SearchField {...{ showSearch, setShowSearch, setKeyword }} />,
dataIndex: 'pool',
// key can be omitted if dataIndex is given (specified in docs)
// duplicate column keys will cause search filter problems.
className: 'centerAlignTableHeader',
// sort
// sorter: (a, b) => a.pool.localeCompare(b.pool),
// search
// ...getColumnSearchProps("pool"),
render: (text, record, index) => {
const addressLength = record.poolAddress.length;
const token0logo = getLogoURIWithSymbol(record.token0Symbol);
const token1logo = getLogoURIWithSymbol(record.token1Symbol);
return (
<div className={styles.pool}>
<img
src={token0logo}
alt={record.token0Symbol}
style={{
maxWidth: '24px',
maxHeight: '24px',
marginRight: '0.25rem',
marginTop: '0.1rem',
}}
/>
<img
src={token1logo}
alt={record.token1Symbol}
style={{
maxWidth: '24px',
maxHeight: '24px',
marginRight: '0.5rem',
marginTop: '0.1rem',
}}
/>
<div>
<p className={styles.bigtitle} onClick={() => {
setAddComponentPairs(record.token0, record.token1);
}} >
{record.pool}
</p>
<a target="_blank" href={`${scanUrlPrefix}/address/${record.poolAddress}`} >
<p className={styles.value}>
{`${record.poolAddress.slice(0, 5)}...${record.poolAddress.slice(
addressLength - 5,
addressLength
)}`}
</p>
</a>
</div>
</div>
);
},
visible: true,
},
{
title: "7D Volume",
dataIndex: 'volume',
className: 'centerAlignTableHeader',
key: 'volume',
render: (text, record, index) => {
return (<div>$ {(record.volume * 7).toFixed(2)}</div>)
},
visible: !isMobile,
},
{
title: "APR",
dataIndex: 'apr',
key: 'apr',
className: 'centerAlignTableHeader',
render: (text, record, index) => {
// const pairOverviewData = userLPOverview[record.poolAddress];
// if (!pairOverviewData) return;
// const aprPercentage = pairOverviewData.apr * 100;
return (
<div>{(record.apr * 100).toFixed(1)}%</div>
)
},
visible: !isMobile,
},
{
title: "Reserve",
key: 'token0Reserve',
dataIndex: 'token0Reserve',
className: 'centerAlignTableHeader',
render: (text, record, index) => (
<div style={{ color: "white" }}>
<p>{record.token0Reserve}</p>
<p>{record.token1Reserve}</p>
</div>
),
visible: true,
},
// { title: "Expand", key: "expand", visible: true},
]);
// fetch lists of valid pool
const getValidPoolList = () => {
setLoading(true);
console.log("fetching user pool list, urlPrefix", apiUrlPrefix);
axios.get(
// fetch valid pool list from remote
// `${apiUrlPrefix}/pool?chainId=${chainId}`
`${apiUrlPrefix}/userpool?walletId=${account}`
// `http://localhost:3001/api/userpool?walletId=${account}`
).then(async res => {
console.log(">> received data from backend", res);
const tokens = supportedTokens;
// construct pool list locally
const pools = res.data.pools;
if (!pools.length) {
setLoading(false);
return;
}
const fetchTask = [];
for (let pairAddr of pools) {
const token0addr = supportedTokens.findIndex(item => item.address.toLowerCase() === pairAddr.token0.toLowerCase());
const token1addr = supportedTokens.findIndex(item => item.address.toLowerCase() === pairAddr.token1.toLowerCase());
const { address: token0Address, symbol: token0Symbol, decimals: token0Decimal } = tokens[token0addr];
const { address: token1Address, symbol: token1Symbol, decimals: token1Decimal } = tokens[token1addr];
const token0 = new Token(chainId, token0Address, token0Decimal, token0Symbol);
const token1 = new Token(chainId, token1Address, token1Decimal, token1Symbol);
// queue get pair task
const pair = Fetcher.fetchPairData(token0, token1, library, chainId);
fetchTask.push(pair);
console.log("adding task to array")
}
const pairs = await Promise.allSettled(fetchTask);
console.log("fetched pairs", pairs);
const LPHandlers = pairs.map(pair => pair.value);
setUserLPHandlers(LPHandlers);
console.log("userLPHandlers is updated with length", LPHandlers.length);
}).catch(e => console.log("error: ", e));
}
const userLPData = useMemo(() => {
const userPools = [];
console.log("fetched pairs userLPHandlers", userLPHandlers);
for (let pair of userLPHandlers) {
if (!pair)
continue;
userPools.push({
token0: pair.token0,
token1: pair.token1,
token0LogoURI: getLogoURIWithSymbol(pair.token0.symbol),
token1LogoURI: getLogoURIWithSymbol(pair.token1.symbol),
token0Symbol: pair.token0.symbol,
token1Symbol: pair.token1.symbol,
pool: `${pair.token0.symbol}/${pair.token1.symbol}`,
poolAddress: `${pair.liquidityToken.address}`,
token0Reserve: `${pair.reserve0.toExact(2)} ${pair.token0.symbol}`,
token1Reserve: `${pair.reserve1.toExact(2)} ${pair.token1.symbol}`,
});
}
console.log("userLPData is updated with length", userPools.length);
console.log("test elapsed time", new Date());
return userPools;
}, [userLPHandlers]);
// search input component update
useEffect(() => {
let filtered = fullTableData;
if (keyword !== "" && filtered) {
const conditions = keyword.toLowerCase().split(/[\s\/,]+/);
filtered = filtered.filter(item => conditions.every(condition => item.pool.toLowerCase().includes(condition)));
}
setFilteredData(filtered);
}, [fullTableData, keyword]);
// show loading spinner until the end of loading phase, or 10 seconds has passed.
useEffect(() => {
if (fullTableData && fullTableData.length)
setLoading(false)
}, [loading, fullTableData]);
useEffect(() => {
// setTimeout(() => setLoading(false), 10000)
}, [])
// fetch user shares in above pools
async function getUserPoolShare() {
const fetchPoolShare = async (pair) => {
console.log("poolToken,", pair.liquidityToken)
let userPoolBalance = await getUserTokenBalanceRaw(pair.liquidityToken, account, library).catch(e => console.log("fetchPoolShare error", e));
if (userPoolBalance.isZero()) {
console.log("zero balance, discard", pair);
return {};
}
userPoolBalance = new TokenAmount(pair.liquidityToken, userPoolBalance);
const totalSupply = await getTokenTotalSupply(pair.liquidityToken, library, account);
const token0Deposited = pair.getLiquidityValue(
pair.token0,
totalSupply,
userPoolBalance,
false
);
const token1Deposited = pair.getLiquidityValue(
pair.token1,
totalSupply,
userPoolBalance,
false
);
const poolTokenPercentage = new Percent(userPoolBalance.raw, totalSupply.raw).toFixed(4);
const newData = {
token0Amount: `${token0Deposited.toSignificant(4)} ${pair.token0.symbol}`,
token1Amount: `${token1Deposited.toSignificant(4)} ${pair.token1.symbol}`,
share: `${poolTokenPercentage}%`,
};
console.log("userLPShares is updated: ", newData);
setUserLPShares(prev => ({ ...prev, [pair.liquidityToken.address]: newData }));
}
(async () => {
for (let pair of userLPHandlers) {
if (!pair)
continue;
fetchPoolShare(pair);
}
})()
}
const getFullTableData = async () => {
console.log("this is userLPData", userLPData);
const poolOverview = {};
const asyncTasks = [];
const calculateVolAndApr = async (pair) => {
const token0 = pair.token0;
const token1 = pair.token1;
console.log("this is", token0, token1)
return await axios.get(`${apiUrlPrefix}/poolchart/pair?token0=${token0.address}&token1=${token1.address}`).then(async (res) => {
// calculate volume in USD
console.log("this is return data", res.data)
const { token0: token0Vol, token1: token1Vol } = res.data.data.lastVolume;
const currentPriceDict = await getAllSupportedTokensPrice();
const vol0Usd = currentPriceDict[token0.symbol] * token0Vol;
const vol1Usd = currentPriceDict[token1.symbol] * token1Vol;
const poolVolumeInUsd = vol0Usd + vol1Usd;
// calculate reserve in USD
const { token0: token0Reserve, token1: token1Reserve } = res.data.data.lastReserves;
const reserve0Usd = currentPriceDict[token0.symbol] * token0Reserve;
const reserve1Usd = currentPriceDict[token1.symbol] * token1Reserve;
const poolReserveInUsd = reserve0Usd + reserve1Usd;
console.log("this is test1", currentPriceDict, poolReserveInUsd, poolVolumeInUsd)
// calculate APR
const apr = poolVolumeInUsd * 0.3 / 1000 * 365 / poolReserveInUsd;
const data = {
volume: poolVolumeInUsd,
apr
}
poolOverview[pair.poolAddress] = data;
}).catch(e => {
console.log("fetching pair volume error", e)
})
}
for (const pair of userLPData) {
asyncTasks.push(calculateVolAndApr(pair));
}
const resolved = await Promise.allSettled(asyncTasks)
console.log("here", poolOverview)
const completeTableData = userLPData.map(d => {
const overviewData = poolOverview[d.poolAddress]
let temp = d;
if (overviewData)
temp = { ...d, ...overviewData }
return temp
})
return completeTableData
}
useEffect(async () => {
const data = await getFullTableData();
setFullTableData(data);
}, [userLPData])
// link liquidity position table and add component together
const { dispatch, liquidity } = props;
const setAddComponentPairs = (token0, token1) => {
dispatch({
type: "liquidity/setAddTokens",
payload: {
token0: token0,
token1: token1
}
});
console.log("test done setAddTokens from table")
}
// // auto scroll to newly loaded data
// useEffect(() => {
// if (filteredData.length) {
// document.querySelector(`#liquidityPositionTable > div > div >div.ant-table-body > table > tbody > tr:last-child`).scrollIntoView({ behavior: "smooth" });
// console.log(`scroll last row of table into view`);
// }
// }, [filteredData]);
// first time loading
useEffect(() => {
setUserLPHandlers([]);
getValidPoolList();
}, [account, chainId]);
// refresh table data on add/remove liquidity
useEffect(() => {
if (liquidity.refreshTable) {
getValidPoolList();
setUserLPShares({});
getUserPoolShare();
dispatch({
type: "liquidity/setRefreshTable",
payload: false,
});
}
}, [liquidity.refreshTable]);
// useEffect(
// () => {
// console.log('library:',library);
// approveTokenWithSpender(
// '0xE971616d94335dec2E54939118AdFcB68E6dCAd6',
// '0x6ef448ecb7f650c3a1157acf37ca19ae86dee8da',
// library,
// account
// );
// },
// []
// );
useEffect(
async () => {
if (!chainId || !library || !account || !userLPHandlers) return;
console.log("getting user liquidity on chainId, userLPHandlers", chainId, userLPHandlers)
await getUserPoolShare();
},
[userLPHandlers]
);
return (
<div>
{loading && loading ? (
<h2 style={{ textAlign: "center", color: "white", top: "1rem", position: "relative" }}>Loading <Icon type="loading" /></h2>
) : (
<>
<Table
id="liquidityPositionTable"
style={{ textAlign: 'center' }}
rowKey="poolAddress"
rowClassName={(record, index) => record.poolAddress === expandedRowKey ? `${styles.rowExpanded} ant-table-expanded-row` : styles.rowNormal}
expandedRowKeys={expandedRowKey}
onExpand={(expanded, record) => { expandedRowKey === record.poolAddress ? setExpandedRowKey("") : setExpandedRowKey(record.poolAddress) }}
dataSource={filteredData || []}
// loading={{ indicator: <div><Icon type="loading" /></div>, spinning: loading}}
columns={columns.filter(item => item.visible)}
pagination={false}
scroll={{ y: 300 }} // this height is override by global.less #root > .ant-table-body
locale={{
emptyText: (
<span>
<h2>No positions available. </h2>
</span>
),
}}
// expandable row
expandRowByClick
expandIconAsCell={false}
expandIconColumnIndex={6}
expandIcon={(props) => {
if (props.expanded) {
return <a style={{ color: 'white' }} onClick={e => {
props.onExpand(props.record, e);
}}><Icon type="down" /></a>
} else {
return <a style={{ color: 'white' }} onClick={e => {
props.onExpand(props.record, e);
}}><Icon type="right" /></a>
}
}}
expandedRowRender={(record, index) => {
const data = userLPShares[record.poolAddress];
return (
<div style={{ display: "flex", paddingLeft: "3rem" }}>
<table id="expandedRowTable">
<tbody>
<tr>
<td>My liquidity</td>
{!isMobile && <td>Pool share</td>}
{!isMobile && <td></td>}
{/* the following height is randomly set to 10px,
it's only useful for its div children to get full height info */}
<td rowSpan="2" style={{ height: "10px" }}>
<div style={{ height: "100%", display: "flex", flexDirection: "column", alignItems: "center", justifyContent: "space-around" }} >
<button
className={styles.removeLiquidityButton}
style={{ background: "transparent", border: "1px solid green" }}
type="button"
onClick={() => {
setAddComponentPairs(record.token0, record.token1);
}}
>
Add
</button>
<button
className={styles.removeLiquidityButton}
style={{ background: "transparent", border: "1px solid green" }}
type="button"
onClick={() => {
setIsModalVisible(true);
setRemoveLiquidityPosition(record);
console.log("remove record", record);
}}
>
Remove
</button>
</div>
</td>
</tr>
<tr className={styles.whiteTextExpandableRow}>
<td>
<p>{data?.token0Amount || "loading..."}</p>
<p>{data?.token1Amount || "loading..."}</p>
</td>
{!isMobile &&
<td>
<p>{data?.share || "loading..."}</p>
</td>}
{!isMobile && <td></td>}
</tr>
</tbody>
</table>
</div>
)
}}
footer={() => (
<>
{userLPData.length < userLPData.length && (
<div className={styles.tableSeeMoreWrapper}>
<a
className={styles.tableSeeMore}
onClick={() => {
getAllUserLiquidityPositions()
}}
>
{loading ? <><Icon type="loading" /> Loading... </> : " See More..."}
</a>
</div>
)}
</>
)}
/>
{/* <Pagination
current={page}
defaultPageSize={pageEntryCount}
total={userLiquidityPositions.length}
onChange={(newPage) => setPage(newPage)}
/> */}
<AcyRemoveLiquidityModal
removeLiquidityPosition={removeLiquidityPosition}
isModalVisible={isModalVisible}
onCancel={() => {
setIsModalVisible(false);
}}
/>
</>
)}
</div>
);
}