Implement editable row

This commit is contained in:
Viet Anh Nguyen 2024-02-22 09:03:15 +07:00
parent efd2da3a82
commit d89cc70ec5

View File

@ -1,10 +1,10 @@
import { t } from '@lingui/macro';
import { Button, Input, Table, Tag, DatePicker, Form, Modal, Select, Space, Checkbox } from 'antd';
import { useState, useEffect } from 'react';
import { Button, Input, Table, Tag, DatePicker, Form, Modal, Select, Space, Spin, message } from 'antd';
import React, { useContext, useEffect, useRef, useState } from 'react';
import type { GetRef } from 'antd';
import { Layout } from 'antd';
import {
EditOutlined, DownloadOutlined, CheckCircleOutlined,
ClockCircleOutlined,
ArrowLeftOutlined,
ArrowRightOutlined,
FullscreenOutlined,
@ -16,6 +16,7 @@ const { Sider, Content } = Layout;
import { baseURL } from "request/api";
import moment from 'moment';
const siderStyle: React.CSSProperties = {
backgroundColor: '#fafafa',
padding: 10,
@ -29,6 +30,110 @@ const StyledTable = styled(Table)`
}
`;
type InputRef = GetRef<typeof Input>;
type FormInstance<T> = GetRef<typeof Form<T>>;
const EditableContext = React.createContext<FormInstance<any> | null>(null);
interface Item {
key: string;
accuracy: number;
submitted: string;
revised: string;
action: string;
}
interface EditableRowProps {
index: number;
}
const EditableRow: React.FC<EditableRowProps> = ({ index, ...props }) => {
const [form] = Form.useForm();
return (
<Form form={form} component={false}>
<EditableContext.Provider value={form}>
<tr {...props} />
</EditableContext.Provider>
</Form>
);
};
interface EditableCellProps {
title: React.ReactNode;
editable: boolean;
children: React.ReactNode;
dataIndex: keyof Item;
record: Item;
handleSave: (record: Item) => void;
}
const EditableCell: React.FC<EditableCellProps> = ({
title,
editable,
children,
dataIndex,
record,
handleSave,
...restProps
}) => {
const [editing, setEditing] = useState(false);
const inputRef = useRef<InputRef>(null);
const form = useContext(EditableContext)!;
useEffect(() => {
if (editing) {
inputRef.current!.focus();
}
}, [editing]);
const toggleEdit = () => {
setEditing(!editing);
form.setFieldsValue({ [dataIndex]: record[dataIndex] });
};
const save = async () => {
try {
const values = await form.validateFields();
toggleEdit();
handleSave({ ...record, ...values });
} catch (errInfo) {
console.log('Save failed:', errInfo);
}
};
let childNode = children;
if (editable) {
childNode = editing ? (
<Form.Item
style={{ margin: 0 }}
name={dataIndex}
rules={[
{
required: true,
message: `${title} is required.`,
},
]}
>
<Input ref={inputRef} onPressEnter={save} onBlur={save} />
</Form.Item>
) : (
<div className="editable-cell-value-wrap" style={{ paddingRight: 24 }} onClick={toggleEdit}>
{children}
</div>
);
}
return <td {...restProps}>{childNode}</td>;
};
type EditableTableProps = Parameters<typeof Table>[0];
type ColumnTypes = Exclude<EditableTableProps['columns'], undefined>;
const StyledEditOutlined = styled(EditOutlined)`
& {
@ -40,7 +145,7 @@ const StyledEditOutlined = styled(EditOutlined)`
}
`;
const columns = [
const defaultColumns = [
{
title: 'Key',
dataIndex: 'key',
@ -70,23 +175,7 @@ const columns = [
title: 'Revised',
dataIndex: 'revised',
key: 'revised',
render: (text, record) => {
return (
<div style={{
display: 'flex',
lineHeight: '2',
}}>
{text}
</div>
)
},
},
{
title: 'Action',
key: 'operation',
fixed: 'right',
width: 100,
render: () => <a><StyledEditOutlined /></a>,
editable: true,
},
];
@ -194,6 +283,7 @@ const fetchRequest = async (id) => {
};
const ReviewPage = () => {
const [loading, setLoading] = useState(false);
const [fullscreen, setFullscreen] = useState(false);
const [isModalOpen, setIsModalOpen] = useState(false);
const [selectedFileId, setSelectedFileId] = useState(0);
@ -219,18 +309,13 @@ const ReviewPage = () => {
// purchase_date: "2024-01-20",
// retailername: "Test Retailer",
// sold_to_party: "Test Party",
const dataSource = [
// {
// key: "imei_number",
// predicted: "352271450941944",
// submitted: "352271450941944",
// revised: "352271450941944",
// },
];
const dataSource = [];
const predicted = (currentRequest && currentRequest["Reviewed Result"]) ? currentRequest["Reviewed Result"] : {};
const submitted = (currentRequest && currentRequest["Feedback Result"]) ? currentRequest["Feedback Result"] : {};
const revised = (currentRequest && currentRequest["Reviewed Result"]) ? currentRequest["Reviewed Result"] : {};
const keys = Object.keys(predicted);
for (let i = 0; i < keys.length; i++) {
let instance = {};
@ -241,37 +326,38 @@ const ReviewPage = () => {
dataSource.push(instance);
}
const gotoNextRequest = () => {
const nextRequestIndex = currentRequestIndex + 1;
setCurrentRequestIndex(nextRequestIndex);
fetchAllRequests(filterDateRange, filterSubsidiaries, filterReviewState, filterIncludeTests, nextRequestIndex, 2).then((data) => {
const [pageIndexToGoto, setPageIndexToGoto] = useState(1);
const loadCurrentRequest = (requestID) => {
setLoading(true);
fetchAllRequests(filterDateRange, filterSubsidiaries, filterReviewState, filterIncludeTests, requestID, 2).then((data) => {
setRequests(data?.subscription_requests);
setHasNextRequest(data?.subscription_requests.length > 1);
setTotalPages(data?.page?.total_pages);
const requestData = fetchRequest(data?.subscription_requests[0].RequestID);
requestData.then(async (data) => {
console.log(data)
if (data) setCurrentRequest(data);
}).finally(() => {
setLoading(false);
});
}).finally(() => {
setLoading(false);
});
};
const gotoNextRequest = () => {
const nextRequestIndex = currentRequestIndex + 1;
setCurrentRequestIndex(nextRequestIndex);
loadCurrentRequest(nextRequestIndex);
};
const gotoPreviousRequest = () => {
if (currentRequestIndex === 1) {
return;
}
const previousRequestIndex = currentRequestIndex - 1;
setCurrentRequestIndex(previousRequestIndex);
fetchAllRequests(filterDateRange, filterSubsidiaries, filterReviewState, filterIncludeTests, previousRequestIndex, 2).then((data) => {
setRequests(data?.subscription_requests);
setHasNextRequest(data?.subscription_requests.length > 1);
setTotalPages(data?.page?.total_pages);
const requestData = fetchRequest(data?.subscription_requests[0].RequestID);
requestData.then(async (data) => {
console.log(data)
if (data) setCurrentRequest(data);
});
});
loadCurrentRequest(previousRequestIndex);
};
@ -304,11 +390,54 @@ const ReviewPage = () => {
});
}, []);
const fileURL = currentRequest ? baseURL + currentRequest["Files"][selectedFileId]["File URL"].replace("http://be-ctel-sbt:9000/api", "") : "dummy.pdf";
const fileURL = (currentRequest && currentRequest["Files"][selectedFileId]) ? baseURL + currentRequest["Files"][selectedFileId]["File URL"].replace("http://be-ctel-sbt:9000/api", "") : "dummy.pdf";
const components = {
body: {
row: EditableRow,
cell: EditableCell,
},
};
// "Key", "Accuracy", "Submitted", "Revised"
interface DataType {
key: string;
accuracy: number;
submitted: string;
revised: string;
};
const handleSave = (row: DataType) => {
const newData = [...dataSource];
console.log(row);
// const index = newData.findIndex((item) => row.key === item.key);
// const item = newData[index];
// newData.splice(index, 1, {
// ...item,
// ...row,
// });
// setDataSource(newData);
};
const columns = defaultColumns.map((col) => {
if (!col.editable) {
return col;
}
return {
...col,
onCell: (record: DataType) => ({
record,
editable: col.editable,
dataIndex: col.dataIndex,
title: col.title,
handleSave,
}),
};
});
return (
<div style={fullscreen ? {
position: 'absolute',
position: 'fixed',
top: 0,
left: 0,
width: '100%',
@ -317,7 +446,22 @@ const ReviewPage = () => {
zIndex: 1000,
} : {
height: '100%',
position: 'relative',
}}>
<div
style={{ height: '100%', position: 'absolute', top: 0, left: 0, width: '100%', background: "#00000033", zIndex: 1000, display: loading? 'block' : 'none' }}
>
<Spin spinning={true} style={{
position: 'absolute',
top: '50%',
left: '50%',
marginTop: -12,
marginLeft: -12,
width: 24,
height: 24,
borderRadius: '50%',
}} size='large' />
</div>
<div>
<Button onClick={() => {
setFullscreen(!fullscreen);
@ -424,10 +568,27 @@ const ReviewPage = () => {
<ArrowRightOutlined />
</Button>
<Input size='middle' addonBefore="To" style={{ marginBottom: "4px", marginLeft: "4px", width: 180 }} defaultValue={currentRequestIndex} addonAfter={
<Button type="default">
<Button type="default"
onClick={() => {
if (pageIndexToGoto > totalPages) {
message.error("RequestID is out of range.");
return;
}
if (pageIndexToGoto < 1) {
message.error("RequestID is out of range.");
return;
}
setCurrentRequestIndex(pageIndexToGoto);
loadCurrentRequest(pageIndexToGoto);
}}>
Go to
</Button>
} />
}
value={pageIndexToGoto}
onChange={e => {
setPageIndexToGoto(parseInt(e.target.value));
}}
/>
</div>
</div>
<h2 style={{ margin: "20px 0 10px 0" }}>{totalPages ? ("Request: " + currentRequestIndex + "/" + totalPages) : "No Request. Adjust your search criteria to see more results."}</h2>
@ -573,7 +734,9 @@ const ReviewPage = () => {
overflowY: 'auto',
}}
>
<StyledTable dataSource={dataSource} columns={columns}
<StyledTable components={components}
rowClassName={() => 'editable-row'}
bordered dataSource={dataSource} columns={columns}
/>
</div>
</div>