feat: create run ui directory

This commit is contained in:
amhsirak
2025-01-09 20:02:58 +05:30
parent 4325070c39
commit 82b8b4d51f
10 changed files with 11 additions and 11 deletions

View File

@@ -0,0 +1,245 @@
import { Box, Tabs, Typography, Tab, Paper, Button } from "@mui/material";
import Highlight from "react-highlight";
import * as React from "react";
import { Data } from "./RunsTable";
import { TabPanel, TabContext } from "@mui/lab";
import ArticleIcon from '@mui/icons-material/Article';
import ImageIcon from '@mui/icons-material/Image';
import { useEffect, useState } from "react";
import Table from '@mui/material/Table';
import TableBody from '@mui/material/TableBody';
import TableCell from '@mui/material/TableCell';
import TableContainer from '@mui/material/TableContainer';
import TableHead from '@mui/material/TableHead';
import TableRow from '@mui/material/TableRow';
import 'highlight.js/styles/github.css';
import { useTranslation } from "react-i18next";
interface RunContentProps {
row: Data,
currentLog: string,
interpretationInProgress: boolean,
logEndRef: React.RefObject<HTMLDivElement>,
abortRunHandler: () => void,
}
export const RunContent = ({ row, currentLog, interpretationInProgress, logEndRef, abortRunHandler }: RunContentProps) => {
const { t } = useTranslation();
const [tab, setTab] = React.useState<string>('log');
const [tableData, setTableData] = useState<any[]>([]);
const [columns, setColumns] = useState<string[]>([]);
useEffect(() => {
setTab(tab);
}, [interpretationInProgress]);
useEffect(() => {
if (row.serializableOutput && Object.keys(row.serializableOutput).length > 0) {
const firstKey = Object.keys(row.serializableOutput)[0];
const data = row.serializableOutput[firstKey];
if (Array.isArray(data)) {
// Filter out completely empty rows
const filteredData = data.filter(row =>
Object.values(row).some(value => value !== undefined && value !== "")
);
setTableData(filteredData);
if (filteredData.length > 0) {
setColumns(Object.keys(filteredData[0]));
}
}
}
}, [row.serializableOutput]);
// Function to convert table data to CSV format
const convertToCSV = (data: any[], columns: string[]): string => {
const header = columns.join(',');
const rows = data.map(row =>
columns.map(col => JSON.stringify(row[col], null, 2)).join(',')
);
return [header, ...rows].join('\n');
};
const downloadCSV = () => {
const csvContent = convertToCSV(tableData, columns);
const blob = new Blob([csvContent], { type: 'text/csv;charset=utf-8;' });
const url = URL.createObjectURL(blob);
const link = document.createElement("a");
link.href = url;
link.setAttribute("download", "data.csv");
document.body.appendChild(link);
link.click();
document.body.removeChild(link);
};
return (
<Box sx={{ width: '100%' }}>
<TabContext value={tab}>
<Box sx={{ borderBottom: 1, borderColor: 'divider' }}>
<Tabs
value={tab}
onChange={(e, newTab) => setTab(newTab)}
aria-label="run-content-tabs"
sx={{
// Remove the default blue indicator
'& .MuiTabs-indicator': {
backgroundColor: '#FF00C3', // Change to pink
},
// Remove default transition effects
'& .MuiTab-root': {
'&.Mui-selected': {
color: '#FF00C3',
},
}
}}
>
<Tab
label={t('run_content.tabs.output_data')}
value='output'
sx={{
color: (theme) => theme.palette.mode === 'dark' ? '#fff' : '#000',
'&:hover': {
color: '#FF00C3'
},
'&.Mui-selected': {
color: '#FF00C3',
}
}}
/>
<Tab
label={t('run_content.tabs.log')}
value='log'
sx={{
color: (theme) => theme.palette.mode === 'dark' ? '#fff' : '#000',
'&:hover': {
color: '#FF00C3'
},
'&.Mui-selected': {
color: '#FF00C3',
}
}}
/>
</Tabs>
</Box>
<TabPanel value='log'>
<Box sx={{
margin: 1,
background: '#19171c',
overflowY: 'scroll',
overflowX: 'scroll',
width: '700px',
height: 'fit-content',
maxHeight: '450px',
}}>
<div>
<Highlight className="javascript">
{interpretationInProgress ? currentLog : row.log}
</Highlight>
<div style={{ float: "left", clear: "both" }}
ref={logEndRef} />
</div>
</Box>
{interpretationInProgress ? <Button
color="error"
onClick={abortRunHandler}
>
{t('run_content.buttons.stop')}
</Button> : null}
</TabPanel>
<TabPanel value='output' sx={{ width: '700px' }}>
{!row || !row.serializableOutput || !row.binaryOutput
|| (Object.keys(row.serializableOutput).length === 0 && Object.keys(row.binaryOutput).length === 0)
? <Typography>{t('run_content.empty_output')}</Typography> : null}
{row.serializableOutput &&
Object.keys(row.serializableOutput).length !== 0 &&
<div>
<Typography variant='h6' sx={{ display: 'flex', alignItems: 'center' }}>
<ArticleIcon sx={{ marginRight: '15px' }} />
{t('run_content.captured_data.title')}
</Typography>
<Box sx={{ display: 'flex', alignItems: 'center', gap: 2, mt: 2 }}>
<Typography>
<a style={{ textDecoration: 'none' }} href={`data:application/json;utf8,${JSON.stringify(row.serializableOutput, null, 2)}`}
download="data.json">
{t('run_content.captured_data.download_json')}
</a>
</Typography>
<Typography
onClick={downloadCSV}
>
<a style={{ textDecoration: 'none', cursor: 'pointer' }}>{t('run_content.captured_data.download_csv')}</a>
</Typography>
</Box>
{tableData.length > 0 ? (
<TableContainer component={Paper} sx={{ maxHeight: 440, marginTop: 2 }}>
<Table stickyHeader aria-label="sticky table">
<TableHead>
<TableRow>
{columns.map((column) => (
<TableCell key={column}>{column}</TableCell>
))}
</TableRow>
</TableHead>
<TableBody>
{tableData.map((row, index) => (
<TableRow key={index}>
{columns.map((column) => (
<TableCell key={column}>
{row[column] === undefined || row[column] === "" ? "-" : row[column]}
</TableCell>
))}
</TableRow>
))}
</TableBody>
</Table>
</TableContainer>
) : (
<Box sx={{
width: 'fit-content',
background: 'rgba(0,0,0,0.06)',
maxHeight: '300px',
overflow: 'scroll',
backgroundColor: '#19171c'
}}>
<pre>
{JSON.stringify(row.serializableOutput, null, 2)}
</pre>
</Box>
)}
</div>
}
{row.binaryOutput && Object.keys(row.binaryOutput).length !== 0 &&
<div>
<Typography variant='h6' sx={{ display: 'flex', alignItems: 'center' }}>
<ImageIcon sx={{ marginRight: '15px' }} />
{t('run_content.captured_screenshot.title')}
</Typography>
{Object.keys(row.binaryOutput).map((key) => {
try {
const imageUrl = row.binaryOutput[key];
return (
<Box key={`number-of-binary-output-${key}`} sx={{
width: 'max-content',
}}>
<Typography sx={{ margin: '20px 0px' }}>
<a href={imageUrl} download={key} style={{ textDecoration: 'none' }}>{t('run_content.captured_screenshot.download')}</a>
</Typography>
<img src={imageUrl} alt={key} height='auto' width='700px' />
</Box>
)
} catch (e) {
console.log(e)
return <Typography key={`number-of-binary-output-${key}`}>
{key}: {t('run_content.captured_screenshot.render_failed')}
</Typography>
}
})}
</div>
}
</TabPanel>
</TabContext>
</Box>
);
};

View File

@@ -0,0 +1,122 @@
import React, { useState } from 'react';
import { GenericModal } from "../ui/GenericModal";
import { MenuItem, TextField, Typography, Switch, FormControlLabel } from "@mui/material";
import { Dropdown } from "../ui/DropdownMui";
import Button from "@mui/material/Button";
import { modalStyle } from "../molecules/AddWhereCondModal";
interface RunSettingsProps {
isOpen: boolean;
handleStart: (settings: RunSettings) => void;
handleClose: () => void;
isTask: boolean;
params?: string[];
}
export interface RunSettings {
maxConcurrency: number;
maxRepeats: number;
debug: boolean;
params?: any;
}
export const RunSettingsModal = ({ isOpen, handleStart, handleClose, isTask, params }: RunSettingsProps) => {
const [settings, setSettings] = useState<RunSettings>({
maxConcurrency: 1,
maxRepeats: 1,
debug: true,
});
const [showInterpreterSettings, setShowInterpreterSettings] = useState(false);
return (
<GenericModal
isOpen={isOpen}
onClose={handleClose}
modalStyle={modalStyle}
>
<div style={{
display: 'flex',
flexDirection: 'column',
alignItems: 'flex-start',
marginLeft: '65px',
}}>
{isTask && (
<React.Fragment>
<Typography sx={{ margin: '20px 0px' }}>Recording parameters:</Typography>
{params?.map((item, index) => (
<TextField
sx={{ marginBottom: '15px' }}
key={`param-${index}`}
type="string"
label={item}
required
onChange={(e) =>
setSettings({
...settings,
params: settings.params
? { ...settings.params, [item]: e.target.value }
: { [item]: e.target.value },
})
}
/>
))}
</React.Fragment>
)}
<FormControlLabel
control={<Switch checked={showInterpreterSettings} onChange={() => setShowInterpreterSettings(!showInterpreterSettings)} />}
label="Developer Mode Settings"
sx={{ margin: '20px 0px' }}
/>
{showInterpreterSettings && (
<React.Fragment>
<TextField
sx={{ marginBottom: '15px' }}
type="number"
label="Max Concurrency"
required
onChange={(e) =>
setSettings({
...settings,
maxConcurrency: parseInt(e.target.value, 10),
})
}
defaultValue={settings.maxConcurrency}
/>
<TextField
sx={{ marginBottom: '15px' }}
type="number"
label="Max Repeats"
required
onChange={(e) =>
setSettings({
...settings,
maxRepeats: parseInt(e.target.value, 10),
})
}
defaultValue={settings.maxRepeats}
/>
<Dropdown
id="debug"
label="Debug Mode"
value={settings.debug?.toString()}
handleSelect={(e) =>
setSettings({
...settings,
debug: e.target.value === "true",
})
}
>
<MenuItem value="true">true</MenuItem>
<MenuItem value="false">false</MenuItem>
</Dropdown>
</React.Fragment>
)}
<Button variant="contained" onClick={() => handleStart(settings)} sx={{ marginTop: '20px' }}>Run Robot</Button>
</div>
</GenericModal>
);
};

View File

@@ -0,0 +1,27 @@
import React, { useEffect } from 'react';
import { Grid } from "@mui/material";
import { RunsTable } from "./RunsTable";
interface RunsProps {
currentInterpretationLog: string;
abortRunHandler: () => void;
runId: string;
runningRecordingName: string;
}
export const Runs = (
{ currentInterpretationLog, abortRunHandler, runId, runningRecordingName }: RunsProps) => {
return (
<Grid container direction="column" sx={{ padding: '30px' }}>
<Grid item xs>
<RunsTable
currentInterpretationLog={currentInterpretationLog}
abortRunHandler={abortRunHandler}
runId={runId}
runningRecordingName={runningRecordingName}
/>
</Grid>
</Grid>
);
}

View File

@@ -0,0 +1,209 @@
import * as React from 'react';
import { useEffect, useState } from "react";
import { useTranslation } from 'react-i18next';
import Paper from '@mui/material/Paper';
import Table from '@mui/material/Table';
import TableBody from '@mui/material/TableBody';
import TableCell from '@mui/material/TableCell';
import TableContainer from '@mui/material/TableContainer';
import TableHead from '@mui/material/TableHead';
import TablePagination from '@mui/material/TablePagination';
import TableRow from '@mui/material/TableRow';
import { Accordion, AccordionSummary, AccordionDetails, Typography, Box, TextField } from '@mui/material';
import ExpandMoreIcon from '@mui/icons-material/ExpandMore';
import SearchIcon from '@mui/icons-material/Search';
import { useGlobalInfoStore } from "../../context/globalInfo";
import { getStoredRuns } from "../../api/storage";
import { RunSettings } from "./RunSettings";
import { CollapsibleRow } from "../molecules/ColapsibleRow";
// Export columns before the component
export const columns: readonly Column[] = [
{ id: 'runStatus', label: 'Status', minWidth: 80 },
{ id: 'name', label: 'Name', minWidth: 80 },
{ id: 'startedAt', label: 'Started At', minWidth: 80 },
{ id: 'finishedAt', label: 'Finished At', minWidth: 80 },
{ id: 'settings', label: 'Settings', minWidth: 80 },
{ id: 'delete', label: 'Delete', minWidth: 80 },
];
interface Column {
id: 'runStatus' | 'name' | 'startedAt' | 'finishedAt' | 'delete' | 'settings';
label: string;
minWidth?: number;
align?: 'right';
format?: (value: string) => string;
}
export interface Data {
id: number;
status: string;
name: string;
startedAt: string;
finishedAt: string;
runByUserId?: string;
runByScheduleId?: string;
runByAPI?: boolean;
log: string;
runId: string;
robotId: string;
robotMetaId: string;
interpreterSettings: RunSettings;
serializableOutput: any;
binaryOutput: any;
}
interface RunsTableProps {
currentInterpretationLog: string;
abortRunHandler: () => void;
runId: string;
runningRecordingName: string;
}
export const RunsTable: React.FC<RunsTableProps> = ({
currentInterpretationLog,
abortRunHandler,
runId,
runningRecordingName
}) => {
const { t } = useTranslation();
// Update column labels using translation if needed
const translatedColumns = columns.map(column => ({
...column,
label: t(`runstable.${column.id}`, column.label)
}));
const [page, setPage] = useState(0);
const [rowsPerPage, setRowsPerPage] = useState(10);
const [rows, setRows] = useState<Data[]>([]);
const [searchTerm, setSearchTerm] = useState('');
const { notify, rerenderRuns, setRerenderRuns } = useGlobalInfoStore();
const handleChangePage = (event: unknown, newPage: number) => {
setPage(newPage);
};
const handleChangeRowsPerPage = (event: React.ChangeEvent<HTMLInputElement>) => {
setRowsPerPage(+event.target.value);
setPage(0);
};
const handleSearchChange = (event: React.ChangeEvent<HTMLInputElement>) => {
setSearchTerm(event.target.value);
setPage(0);
};
const fetchRuns = async () => {
const runs = await getStoredRuns();
if (runs) {
const parsedRows: Data[] = runs.map((run: any, index: number) => ({
id: index,
...run,
}));
setRows(parsedRows);
} else {
notify('error', t('runstable.notifications.no_runs'));
}
};
useEffect(() => {
if (rows.length === 0 || rerenderRuns) {
fetchRuns();
setRerenderRuns(false);
}
}, [rerenderRuns, rows.length, setRerenderRuns]);
const handleDelete = () => {
setRows([]);
notify('success', t('runstable.notifications.delete_success'));
fetchRuns();
};
// Filter rows based on search term
const filteredRows = rows.filter((row) =>
row.name.toLowerCase().includes(searchTerm.toLowerCase())
);
// Group filtered rows by robot meta id
const groupedRows = filteredRows.reduce((acc, row) => {
if (!acc[row.robotMetaId]) {
acc[row.robotMetaId] = [];
}
acc[row.robotMetaId].push(row);
return acc;
}, {} as Record<string, Data[]>);
return (
<React.Fragment>
<Box display="flex" justifyContent="space-between" alignItems="center" mb={2}>
<Typography variant="h6" gutterBottom>
{t('runstable.runs', 'Runs')}
</Typography>
<TextField
size="small"
placeholder={t('runstable.search', 'Search runs...')}
value={searchTerm}
onChange={handleSearchChange}
InputProps={{
startAdornment: <SearchIcon sx={{ color: 'action.active', mr: 1 }} />
}}
sx={{ width: '250px' }}
/>
</Box>
<TableContainer component={Paper} sx={{ width: '100%', overflow: 'hidden' }}>
{Object.entries(groupedRows).map(([id, data]) => (
<Accordion key={id}>
<AccordionSummary expandIcon={<ExpandMoreIcon />}>
<Typography variant="h6">{data[data.length - 1].name}</Typography>
</AccordionSummary>
<AccordionDetails>
<Table stickyHeader aria-label="sticky table">
<TableHead>
<TableRow>
<TableCell />
{translatedColumns.map((column) => (
<TableCell
key={column.id}
align={column.align}
style={{ minWidth: column.minWidth }}
>
{column.label}
</TableCell>
))}
</TableRow>
</TableHead>
<TableBody>
{data
.slice(page * rowsPerPage, page * rowsPerPage + rowsPerPage)
.map((row) => (
<CollapsibleRow
row={row}
handleDelete={handleDelete}
key={`row-${row.id}`}
isOpen={runId === row.runId && runningRecordingName === row.name}
currentLog={currentInterpretationLog}
abortRunHandler={abortRunHandler}
runningRecordingName={runningRecordingName}
/>
))}
</TableBody>
</Table>
</AccordionDetails>
</Accordion>
))}
</TableContainer>
<TablePagination
rowsPerPageOptions={[10, 25, 50]}
component="div"
count={filteredRows.length}
rowsPerPage={rowsPerPage}
page={page}
onPageChange={handleChangePage}
onRowsPerPageChange={handleChangeRowsPerPage}
/>
</React.Fragment>
);
};