import React, { useEffect, useState } from 'react'; import { Button, Label, Pagination, Table } from 'semantic-ui-react'; import { API, showError, timestamp2string } from '../helpers'; import { ITEMS_PER_PAGE } from '../constants'; function renderTimestamp(timestamp) { return ( <> {timestamp2string(timestamp)} ); } function renderType(type) { switch (type) { case 1: return ; case 2: return ; default: return ; } } const LogsTable = () => { const [logs, setLogs] = useState([]); const [loading, setLoading] = useState(true); const [activePage, setActivePage] = useState(1); const [searchKeyword, setSearchKeyword] = useState(''); const [searching, setSearching] = useState(false); const loadLogs = async (startIdx) => { const res = await API.get(`/api/log/self/?p=${startIdx}`); const { success, message, data } = res.data; if (success) { if (startIdx === 0) { setLogs(data); } else { let newLogs = logs; newLogs.push(...data); setLogs(newLogs); } } else { showError(message); } setLoading(false); }; const onPaginationChange = (e, { activePage }) => { (async () => { if (activePage === Math.ceil(logs.length / ITEMS_PER_PAGE) + 1) { // In this case we have to load more data and then append them. await loadLogs(activePage - 1); } setActivePage(activePage); })(); }; const refresh = async () => { setLoading(true); await loadLogs(0); }; useEffect(() => { loadLogs(0) .then() .catch((reason) => { showError(reason); }); }, []); const searchLogs = async () => { if (searchKeyword === '') { // if keyword is blank, load files instead. await loadLogs(0); setActivePage(1); return; } setSearching(true); const res = await API.get(`/api/log/self/search?keyword=${searchKeyword}`); const { success, message, data } = res.data; if (success) { setLogs(data); setActivePage(1); } else { showError(message); } setSearching(false); }; const handleKeywordChange = async (e, { value }) => { setSearchKeyword(value.trim()); }; const sortLog = (key) => { if (logs.length === 0) return; setLoading(true); let sortedLogs = [...logs]; sortedLogs.sort((a, b) => { return ('' + a[key]).localeCompare(b[key]); }); if (sortedLogs[0].id === logs[0].id) { sortedLogs.reverse(); } setLogs(sortedLogs); setLoading(false); }; return ( <> { sortLog('created_time'); }} width={3} > 时间 { sortLog('type'); }} width={2} > 类型 { sortLog('content'); }} width={11} > 详情 {logs .slice( (activePage - 1) * ITEMS_PER_PAGE, activePage * ITEMS_PER_PAGE ) .map((log, idx) => { if (log.deleted) return <>; return ( {renderTimestamp(log.created_at)} {renderType(log.type)} {log.content} ); })}
); }; export default LogsTable;