fix: model list duplicate

This commit is contained in:
jialin
2024-07-09 16:59:35 +08:00
parent 734368dd49
commit fe14edbb4e
22 changed files with 247 additions and 69 deletions
+6
View File
@@ -18,6 +18,12 @@ export default defineConfig({
base: process.env.npm_config_base || '/', base: process.env.npm_config_base || '/',
...(isProduction ...(isProduction
? { ? {
jsMinifierOptions: {
compress: {
drop_console: true,
drop_debugger: true
}
},
scripts: [ scripts: [
{ {
src: `/js/umi.${t}.js` src: `/js/umi.${t}.js`
+8 -5
View File
@@ -31,11 +31,14 @@ const DropdownButtons: React.FC<DropdownButtonsProps> = ({
return ( return (
<> <>
{items?.length === 1 ? ( {items?.length === 1 ? (
<Button <Tooltip title={_.head(items)?.label}>
icon={_.get(items, '0.icon')} <Button
size={size} {..._.head(items)}
onClick={handleButtonClick} icon={_.get(items, '0.icon')}
></Button> size={size}
onClick={handleButtonClick}
></Button>
</Tooltip>
) : ( ) : (
<Dropdown.Button <Dropdown.Button
menu={{ menu={{
-1
View File
@@ -1,6 +1,5 @@
// footer all styles // footer all styles
.footer { .footer {
position: fixed;
bottom: 0; bottom: 0;
width: 100%; width: 100%;
background-color: transparent; background-color: transparent;
+1 -1
View File
@@ -1,7 +1,7 @@
import { createFromIconfontCN } from '@ant-design/icons'; import { createFromIconfontCN } from '@ant-design/icons';
const IconFont = createFromIconfontCN({ const IconFont = createFromIconfontCN({
scriptUrl: '//at.alicdn.com/t/c/font_4613488_clxjnjvlf6m.js' scriptUrl: '//at.alicdn.com/t/c/font_4613488_n8fe7jbl7n.js'
}); });
export default IconFont; export default IconFont;
@@ -17,6 +17,7 @@ const TableRow: React.FC<
rowIndex, rowIndex,
expandable, expandable,
rowSelection, rowSelection,
expandedRowKeys,
rowKey, rowKey,
columns, columns,
pollingChildren, pollingChildren,
@@ -31,12 +32,14 @@ const TableRow: React.FC<
const [checked, setChecked] = useState(false); const [checked, setChecked] = useState(false);
const [childrenData, setChildrenData] = useState<any[]>([]); const [childrenData, setChildrenData] = useState<any[]>([]);
const [loading, setLoading] = useState(false); const [loading, setLoading] = useState(false);
const [firstLoad, setFirstLoad] = useState(true);
const pollTimer = useRef<any>(null); const pollTimer = useRef<any>(null);
const chunkRequestRef = useRef<any>(null); const chunkRequestRef = useRef<any>(null);
console.log('table row===='); console.log('table row====');
const { updateChunkedList } = useUpdateChunkedList(childrenData, { const { updateChunkedList } = useUpdateChunkedList(childrenData, {
setDataList: setChildrenData setDataList: setChildrenData,
callback: (list) => renderChildren?.(list)
}); });
useEffect(() => { useEffect(() => {
@@ -50,6 +53,14 @@ const TableRow: React.FC<
} }
}, [rowSelection]); }, [rowSelection]);
useEffect(() => {
if (expandedRowKeys?.includes(record[rowKey])) {
setExpanded(true);
} else {
setExpanded(false);
}
}, [expandedRowKeys]);
useEffect(() => { useEffect(() => {
return () => { return () => {
if (pollTimer.current) { if (pollTimer.current) {
@@ -75,6 +86,7 @@ const TableRow: React.FC<
}; };
const handleLoadChildren = async () => { const handleLoadChildren = async () => {
console.log('first load=====', firstLoad);
try { try {
setLoading(true); setLoading(true);
const data = await loadChildren?.(record); const data = await loadChildren?.(record);
@@ -83,6 +95,8 @@ const TableRow: React.FC<
} catch (error) { } catch (error) {
setChildrenData([]); setChildrenData([]);
setLoading(false); setLoading(false);
} finally {
setFirstLoad(false);
} }
}; };
@@ -113,9 +127,9 @@ const TableRow: React.FC<
const handleRowExpand = async () => { const handleRowExpand = async () => {
setExpanded(!expanded); setExpanded(!expanded);
onExpand?.(!expanded, record); onExpand?.(!expanded, record, record[rowKey]);
console.log('expanded=====', record);
chunkRequestRef.current?.current?.cancel?.();
if (pollTimer.current) { if (pollTimer.current) {
clearInterval(pollTimer.current); clearInterval(pollTimer.current);
} }
@@ -149,10 +163,15 @@ const TableRow: React.FC<
}; };
useEffect(() => { useEffect(() => {
if (childrenData.length) { if (!firstLoad && expanded) {
createChunkRequest(); createChunkRequest();
} else {
chunkRequestRef.current?.current?.cancel?.();
} }
}, [childrenData]); return () => {
chunkRequestRef.current?.current?.cancel?.();
};
}, [firstLoad, expanded]);
const renderRowPrefix = () => { const renderRowPrefix = () => {
if (expandable && rowSelection) { if (expandable && rowSelection) {
+2
View File
@@ -12,6 +12,7 @@ const SealTable: React.FC<SealTableProps> = (props) => {
children, children,
rowKey, rowKey,
onExpand, onExpand,
expandedRowKeys,
loading, loading,
expandable, expandable,
pollingChildren, pollingChildren,
@@ -144,6 +145,7 @@ const SealTable: React.FC<SealTableProps> = (props) => {
loadChildren={loadChildren} loadChildren={loadChildren}
loadChildrenAPI={loadChildrenAPI} loadChildrenAPI={loadChildrenAPI}
onExpand={onExpand} onExpand={onExpand}
expandedRowKeys={expandedRowKeys}
></TableRow> ></TableRow>
); );
})} })}
+2 -1
View File
@@ -24,6 +24,7 @@ export interface RowSelectionProps {
onChange: (selectedRowKeys: React.Key[]) => void; onChange: (selectedRowKeys: React.Key[]) => void;
} }
export interface SealTableProps { export interface SealTableProps {
expandedRowKeys?: React.Key[];
rowSelection?: RowSelectionProps; rowSelection?: RowSelectionProps;
children: React.ReactNode[]; children: React.ReactNode[];
empty?: React.ReactNode; empty?: React.ReactNode;
@@ -32,7 +33,7 @@ export interface SealTableProps {
pollingChildren?: boolean; pollingChildren?: boolean;
watchChildren?: boolean; watchChildren?: boolean;
loading?: boolean; loading?: boolean;
onExpand?: (expanded: boolean, record: any) => void; onExpand?: (expanded: boolean, record: any, rowKey: any) => void;
renderChildren?: (data: any) => React.ReactNode; renderChildren?: (data: any) => React.ReactNode;
loadChildren?: (record: any) => Promise<any[]>; loadChildren?: (record: any) => Promise<any[]>;
loadChildrenAPI?: (record: any) => string; loadChildrenAPI?: (record: any) => string;
+35
View File
@@ -0,0 +1,35 @@
import { useCallback, useState } from 'react';
export default function useExpandedRowKeys() {
const [expandedRowKeys, setExpandedRowKeys] = useState<React.Key[]>([]);
const handleExpandChange = useCallback(
(expanded: boolean, record: any, rowKey: any) => {
if (expanded) {
setExpandedRowKeys((keys) => [...keys, rowKey]);
} else {
setExpandedRowKeys((keys) => keys.filter((key) => key !== rowKey));
}
},
[]
);
const updateExpandedRowKeys = (keys: React.Key[]) => {
// remove expanded row keys that are in the deleted keys
const newExpandedRowKeys = expandedRowKeys.filter(
(key) => !keys.includes(key)
);
setExpandedRowKeys(newExpandedRowKeys);
};
const clearExpandedRowKeys = () => {
setExpandedRowKeys([]);
};
return {
expandedRowKeys,
clearExpandedRowKeys,
updateExpandedRowKeys,
handleExpandChange
};
}
+17 -16
View File
@@ -8,17 +8,17 @@ interface ChunkedCollection {
type: string | number; type: string | number;
} }
// Only used to update lists without nested state // Only used to update lists without nested state
export function useUpdateChunkedList( export function useUpdateChunkedList(options: {
dataList: { id: string | number }[], setDataList: (args: any) => void;
options: { callback?: (args: any) => void;
setDataList: (args: any) => void; filterFun?: (args: any) => boolean;
callback?: (args: any) => void; mapFun?: (args: any) => any;
filterFun?: (args: any) => boolean; computedID?: (d: object) => string;
mapFun?: (args: any) => any; }) {
computedID?: (d: object) => string; const updateChunkedList = (
} data: ChunkedCollection,
) { dataList: { id: string | number }[]
const updateChunkedList = (data: ChunkedCollection) => { ) => {
let collections = data?.collection || []; let collections = data?.collection || [];
if (options?.computedID) { if (options?.computedID) {
collections = _.map(collections, (item: any) => { collections = _.map(collections, (item: any) => {
@@ -42,16 +42,17 @@ export function useUpdateChunkedList(
); );
if (updateIndex === -1) { if (updateIndex === -1) {
const updateItem = _.cloneDeep(item); const updateItem = _.cloneDeep(item);
options.setDataList((preDataList: any) => { options.setDataList?.((preDataList: any) => {
return _.concat(updateItem, preDataList); return _.concat(updateItem, preDataList);
}); });
} }
console.log('create=========', updateIndex, dataList, collections);
}); });
} }
// DELETE // DELETE
if (data?.type === WatchEventType.DELETE) { if (data?.type === WatchEventType.DELETE) {
options.setDataList((prevDataList: any) => { options.setDataList?.(() => {
const updatedList = _.filter(prevDataList, (item: any) => { const updatedList = _.filter(dataList, (item: any) => {
return !_.find(ids, (id: any) => id === item.id); return !_.find(ids, (id: any) => id === item.id);
}); });
return updatedList; return updatedList;
@@ -59,8 +60,8 @@ export function useUpdateChunkedList(
} }
// UPDATE // UPDATE
if (data?.type === WatchEventType.UPDATE) { if (data?.type === WatchEventType.UPDATE) {
options.setDataList((prevDataList: any[]) => { options.setDataList?.(() => {
const updatedDataList = _.cloneDeep(prevDataList); const updatedDataList = _.cloneDeep(dataList);
_.each(collections, (item: any) => { _.each(collections, (item: any) => {
const updateIndex = _.findIndex( const updateIndex = _.findIndex(
+1 -1
View File
@@ -70,7 +70,7 @@ export function getRightRenderContent(opts: {
mode: 'vertical', mode: 'vertical',
expandIcon: false, expandIcon: false,
inlineCollapsed: collapsed, inlineCollapsed: collapsed,
triggerSubMenuAction: 'hover', triggerSubMenuAction: 'click',
items: [ items: [
{ {
key: 'lang', key: 'lang',
@@ -12,18 +12,24 @@ import { ModelInstanceListItem } from '../config/types';
interface InstanceItemProps { interface InstanceItemProps {
list: ModelInstanceListItem[]; list: ModelInstanceListItem[];
handleChildSelect: (val: string, item: ModelInstanceListItem) => void; handleChildSelect: (
val: string,
item: ModelInstanceListItem,
list: ModelInstanceListItem[]
) => void;
} }
const InstanceItem: React.FC<InstanceItemProps> = ({ const InstanceItem: React.FC<InstanceItemProps> = ({
list, list,
handleChildSelect handleChildSelect
}) => { }) => {
console.log('instance item====');
const intl = useIntl(); const intl = useIntl();
const childActionList = [ const childActionList = [
{ {
label: intl.formatMessage({ id: 'common.button.viewlog' }), label: intl.formatMessage({ id: 'common.button.viewlog' }),
key: 'viewlog', key: 'viewlog',
status: [InstanceStatusMap.Running, InstanceStatusMap.Error],
icon: <FieldTimeOutlined /> icon: <FieldTimeOutlined />
}, },
{ {
@@ -33,9 +39,16 @@ const InstanceItem: React.FC<InstanceItemProps> = ({
icon: <DeleteOutlined /> icon: <DeleteOutlined />
} }
]; ];
const testStatus = {
state: InstanceStatusMap.Scheduled const setChildActionList = (item: ModelInstanceListItem) => {
return _.filter(childActionList, (action: any) => {
if (action.key === 'viewlog') {
return InstanceStatusMap.Running.includes(item.state);
}
return true;
});
}; };
const getWorkerIp = (item: ModelInstanceListItem) => { const getWorkerIp = (item: ModelInstanceListItem) => {
if (item.worker_ip) { if (item.worker_ip) {
return item.port ? `${item.worker_ip}:${item.port}` : item.worker_ip; return item.port ? `${item.worker_ip}:${item.port}` : item.worker_ip;
@@ -90,8 +103,10 @@ const InstanceItem: React.FC<InstanceItemProps> = ({
<Col span={5}> <Col span={5}>
<div style={{ paddingLeft: 39 }}> <div style={{ paddingLeft: 39 }}>
<DropdownButtons <DropdownButtons
items={childActionList} items={setChildActionList(item)}
onSelect={(val: string) => handleChildSelect(val, item)} onSelect={(val: string) =>
handleChildSelect(val, item, list)
}
></DropdownButtons> ></DropdownButtons>
</div> </div>
</Col> </Col>
+15 -11
View File
@@ -4,6 +4,7 @@ import SealTable from '@/components/seal-table';
import SealColumn from '@/components/seal-table/components/seal-column'; import SealColumn from '@/components/seal-table/components/seal-column';
import { PageAction } from '@/config'; import { PageAction } from '@/config';
import type { PageActionType } from '@/config/types'; import type { PageActionType } from '@/config/types';
import useExpandedRowKeys from '@/hooks/use-expanded-row-keys';
import useTableRowSelection from '@/hooks/use-table-row-selection'; import useTableRowSelection from '@/hooks/use-table-row-selection';
import useTableSort from '@/hooks/use-table-sort'; import useTableSort from '@/hooks/use-table-sort';
import { handleBatchRequest } from '@/utils'; import { handleBatchRequest } from '@/utils';
@@ -18,7 +19,7 @@ import { PageContainer } from '@ant-design/pro-components';
import { Access, useAccess, useIntl, useNavigate } from '@umijs/max'; import { Access, useAccess, useIntl, useNavigate } from '@umijs/max';
import { Button, Input, Modal, Space, message } from 'antd'; import { Button, Input, Modal, Space, message } from 'antd';
import dayjs from 'dayjs'; import dayjs from 'dayjs';
import { memo, useCallback, useEffect, useState } from 'react'; import { memo, useCallback, useState } from 'react';
import { import {
MODELS_API, MODELS_API,
MODEL_INSTANCE_API, MODEL_INSTANCE_API,
@@ -57,11 +58,9 @@ const Models: React.FC<ModelsProps> = ({
handleSearch, handleSearch,
handleShowSizeChange, handleShowSizeChange,
handlePageChange, handlePageChange,
createModelsChunkRequest,
queryParams, queryParams,
loading, loading,
total, total
fetchData
}) => { }) => {
// const { modal } = App.useApp(); // const { modal } = App.useApp();
console.log('model list====2'); console.log('model list====2');
@@ -69,6 +68,8 @@ const Models: React.FC<ModelsProps> = ({
const intl = useIntl(); const intl = useIntl();
const navigate = useNavigate(); const navigate = useNavigate();
const rowSelection = useTableRowSelection(); const rowSelection = useTableRowSelection();
const { handleExpandChange, updateExpandedRowKeys, expandedRowKeys } =
useExpandedRowKeys();
const { sortOrder, setSortOrder } = useTableSort({ const { sortOrder, setSortOrder } = useTableSort({
defaultSortOrder: 'descend' defaultSortOrder: 'descend'
}); });
@@ -145,6 +146,7 @@ const Models: React.FC<ModelsProps> = ({
async onOk() { async onOk() {
await deleteModel(row.id); await deleteModel(row.id);
message.success(intl.formatMessage({ id: 'common.message.success' })); message.success(intl.formatMessage({ id: 'common.message.success' }));
updateExpandedRowKeys([row.id]);
}, },
onCancel() { onCancel() {
console.log('Cancel'); console.log('Cancel');
@@ -162,6 +164,7 @@ const Models: React.FC<ModelsProps> = ({
await handleBatchRequest(rowSelection.selectedRowKeys, deleteModel); await handleBatchRequest(rowSelection.selectedRowKeys, deleteModel);
message.success(intl.formatMessage({ id: 'common.message.success' })); message.success(intl.formatMessage({ id: 'common.message.success' }));
rowSelection.clearSelections(); rowSelection.clearSelections();
updateExpandedRowKeys(rowSelection.selectedRowKeys);
}, },
onCancel() { onCancel() {
console.log('Cancel'); console.log('Cancel');
@@ -181,7 +184,7 @@ const Models: React.FC<ModelsProps> = ({
console.log('error:', error); console.log('error:', error);
} }
}; };
const handleDeleteInstace = (row: any) => { const handleDeleteInstace = (row: any, list: ModelInstanceListItem[]) => {
Modal.confirm({ Modal.confirm({
title: '', title: '',
content: intl.formatMessage( content: intl.formatMessage(
@@ -191,6 +194,9 @@ const Models: React.FC<ModelsProps> = ({
async onOk() { async onOk() {
await deleteModelInstance(row.id); await deleteModelInstance(row.id);
message.success(intl.formatMessage({ id: 'common.message.success' })); message.success(intl.formatMessage({ id: 'common.message.success' }));
if (list.length === 1) {
updateExpandedRowKeys([row.model_id]);
}
}, },
onCancel() { onCancel() {
console.log('Cancel'); console.log('Cancel');
@@ -232,9 +238,9 @@ const Models: React.FC<ModelsProps> = ({
}, []); }, []);
const handleChildSelect = useCallback( const handleChildSelect = useCallback(
(val: any, row: ModelInstanceListItem) => { (val: any, row: ModelInstanceListItem, list: ModelInstanceListItem[]) => {
if (val === 'delete') { if (val === 'delete') {
handleDeleteInstace(row); handleDeleteInstace(row, list);
} }
if (val === 'viewlog') { if (val === 'viewlog') {
handleViewLogs(row); handleViewLogs(row);
@@ -252,10 +258,6 @@ const Models: React.FC<ModelsProps> = ({
); );
}; };
useEffect(() => {
createModelsChunkRequest();
}, []);
return ( return (
<> <>
<PageContainer <PageContainer
@@ -309,6 +311,8 @@ const Models: React.FC<ModelsProps> = ({
<SealTable <SealTable
dataSource={dataSource} dataSource={dataSource}
rowSelection={rowSelection} rowSelection={rowSelection}
expandedRowKeys={expandedRowKeys}
onExpand={handleExpandChange}
loading={loading} loading={loading}
rowKey="id" rowKey="id"
expandable={true} expandable={true}
@@ -1,7 +1,8 @@
import LogsViewer from '@/components/logs-viewer'; import LogsViewer from '@/components/logs-viewer';
import { FullscreenExitOutlined, FullscreenOutlined } from '@ant-design/icons';
import { useIntl } from '@umijs/max'; import { useIntl } from '@umijs/max';
import { Modal } from 'antd'; import { Button, Modal } from 'antd';
import React from 'react'; import React, { useState } from 'react';
type ViewModalProps = { type ViewModalProps = {
open: boolean; open: boolean;
@@ -12,14 +13,36 @@ type ViewModalProps = {
const ViewCodeModal: React.FC<ViewModalProps> = (props) => { const ViewCodeModal: React.FC<ViewModalProps> = (props) => {
console.log('viewlogs======'); console.log('viewlogs======');
const { open, url, onCancel } = props || {}; const { open, url, onCancel } = props || {};
const [modalSize, setModalSize] = useState<any>({
width: 600,
height: 450
});
const isFullScreenRef = React.useRef(false);
const intl = useIntl(); const intl = useIntl();
if (!open) { const handleFullscreenToggle = () => {
return null; isFullScreenRef.current = !isFullScreenRef.current;
} setModalSize((size: any) => {
return {
width: size.width === 600 ? '100%' : 600,
height: size.height === 450 ? 'calc(100vh - 100px)' : 450
};
});
};
return ( return (
<Modal <Modal
title={intl.formatMessage({ id: 'common.button.viewlog' })} title={
<span className="flex flex-center">
<span> {intl.formatMessage({ id: 'common.button.viewlog' })}</span>
<Button size="middle" type="text" onClick={handleFullscreenToggle}>
{isFullScreenRef.current ? (
<FullscreenExitOutlined />
) : (
<FullscreenOutlined />
)}
</Button>
</span>
}
open={open} open={open}
centered={true} centered={true}
onCancel={onCancel} onCancel={onCancel}
@@ -27,11 +50,11 @@ const ViewCodeModal: React.FC<ViewModalProps> = (props) => {
closeIcon={true} closeIcon={true}
maskClosable={false} maskClosable={false}
keyboard={false} keyboard={false}
width={600} width={modalSize.width}
footer={null} footer={null}
> >
<LogsViewer <LogsViewer
height={500} height={modalSize.height}
url={url} url={url}
params={{ params={{
follow: true follow: true
+4 -2
View File
@@ -25,7 +25,8 @@ export const InstanceStatusMap = {
Scheduled: 'Scheduled', Scheduled: 'Scheduled',
Error: 'Error', Error: 'Error',
Downloading: 'Downloading', Downloading: 'Downloading',
Unknown: 'Unknown' Unknown: 'Unknown',
Analyzing: 'Analyzing'
}; };
export const status: any = { export const status: any = {
@@ -35,7 +36,8 @@ export const status: any = {
[InstanceStatusMap.Scheduled]: StatusMaps.success, [InstanceStatusMap.Scheduled]: StatusMaps.success,
[InstanceStatusMap.Error]: StatusMaps.error, [InstanceStatusMap.Error]: StatusMaps.error,
[InstanceStatusMap.Downloading]: StatusMaps.transitioning, [InstanceStatusMap.Downloading]: StatusMaps.transitioning,
[InstanceStatusMap.Unknown]: StatusMaps.inactive [InstanceStatusMap.Unknown]: StatusMaps.inactive,
[InstanceStatusMap.Analyzing]: StatusMaps.transitioning
}; };
export const ActionList = [ export const ActionList = [
+18 -3
View File
@@ -17,7 +17,9 @@ const Models: React.FC = () => {
const [total, setTotal] = useState(100); const [total, setTotal] = useState(100);
const [loading, setLoading] = useState(false); const [loading, setLoading] = useState(false);
const [dataSource, setDataSource] = useState<ListItem[]>([]); const [dataSource, setDataSource] = useState<ListItem[]>([]);
const [firstLoad, setFirstLoad] = useState(true);
const chunkRequedtRef = useRef<any>(); const chunkRequedtRef = useRef<any>();
const dataSourceRef = useRef<any>();
let axiosToken = createAxiosToken(); let axiosToken = createAxiosToken();
const [queryParams, setQueryParams] = useState({ const [queryParams, setQueryParams] = useState({
page: 1, page: 1,
@@ -26,10 +28,14 @@ const Models: React.FC = () => {
}); });
// request data // request data
const { updateChunkedList } = useUpdateChunkedList(dataSource, { const { updateChunkedList } = useUpdateChunkedList({
setDataList: setDataSource setDataList: setDataSource
}); });
useEffect(() => {
dataSourceRef.current = dataSource;
}, [dataSource]);
const fetchData = useCallback(async () => { const fetchData = useCallback(async () => {
axiosToken?.cancel?.(); axiosToken?.cancel?.();
axiosToken = createAxiosToken(); axiosToken = createAxiosToken();
@@ -49,6 +55,7 @@ const Models: React.FC = () => {
console.log('error', error); console.log('error', error);
} finally { } finally {
setLoading(false); setLoading(false);
setFirstLoad(false);
} }
}, [queryParams]); }, [queryParams]);
@@ -76,7 +83,7 @@ const Models: React.FC = () => {
const updateHandler = (list: any) => { const updateHandler = (list: any) => {
_.each(list, (data: any) => { _.each(list, (data: any) => {
updateChunkedList(data); updateChunkedList(data, dataSourceRef.current);
}); });
}; };
@@ -110,9 +117,17 @@ const Models: React.FC = () => {
); );
useEffect(() => { useEffect(() => {
fetchData(); if (!firstLoad) {
createModelsChunkRequest();
}
return () => { return () => {
chunkRequedtRef.current?.current?.cancel?.(); chunkRequedtRef.current?.current?.cancel?.();
};
}, [firstLoad]);
useEffect(() => {
fetchData();
return () => {
axiosToken?.cancel?.(); axiosToken?.cancel?.();
}; };
}, [queryParams]); }, [queryParams]);
+4
View File
@@ -17,4 +17,8 @@
:local(.box) { :local(.box) {
padding-top: 10%; padding-top: 10%;
display: flex;
flex-direction: column;
justify-content: space-between;
min-height: 100vh;
} }
+3
View File
@@ -21,6 +21,9 @@ const Login = () => {
useEffect(() => { useEffect(() => {
gotoDefaultPage(userInfo); gotoDefaultPage(userInfo);
}, [userInfo]); }, [userInfo]);
useEffect(() => {
document.title = 'GPUStack';
}, []);
return ( return (
<> <>
@@ -13,6 +13,7 @@ import '../style/chat-footer.less';
interface ChatFooterProps { interface ChatFooterProps {
onSubmit: () => void; onSubmit: () => void;
onStop: () => void;
onClear: () => void; onClear: () => void;
onNewMessage: () => void; onNewMessage: () => void;
onView: () => void; onView: () => void;
@@ -26,6 +27,7 @@ const ChatFooter: React.FC<ChatFooterProps> = (props) => {
const { const {
onSubmit, onSubmit,
onClear, onClear,
onStop,
onNewMessage, onNewMessage,
onView, onView,
feedback, feedback,
@@ -40,6 +42,26 @@ const ChatFooter: React.FC<ChatFooterProps> = (props) => {
{ enabled: !disabled } { enabled: !disabled }
); );
const renderSubmitButton = () => {
if (disabled) {
return (
<>
{intl.formatMessage({ id: 'common.button.stop' })}
<span className="m-l-5">
<IconFont type="icon-stop"></IconFont>
</span>
</>
);
}
return (
<>
{intl.formatMessage({ id: 'common.button.submit' })}
<span className="m-l-5 opct-7">
<IconFont type="icon-command"></IconFont> + <EnterOutlined />
</span>
</>
);
};
return ( return (
<div className="chat-footer"> <div className="chat-footer">
<Row style={{ width: '100%' }}> <Row style={{ width: '100%' }}>
@@ -71,12 +93,21 @@ const ChatFooter: React.FC<ChatFooterProps> = (props) => {
> >
{intl.formatMessage({ id: 'playground.viewcode' })} {intl.formatMessage({ id: 'playground.viewcode' })}
</Button> </Button>
<Button disabled={disabled} type="primary" onClick={onSubmit}> {!disabled ? (
{intl.formatMessage({ id: 'common.button.submit' })} <Button type="primary" disabled={disabled} onClick={onSubmit}>
<span className="m-l-5 opct-7"> {intl.formatMessage({ id: 'common.button.submit' })}
<IconFont type="icon-command"></IconFont> + <EnterOutlined /> <span className="m-l-5 opct-7">
</span> <IconFont type="icon-command"></IconFont> + <EnterOutlined />
</Button> </span>
</Button>
) : (
<Button type="primary" onClick={onStop}>
{intl.formatMessage({ id: 'common.button.stop' })}
<span className="m-l-5">
<IconFont type="icon-stop"></IconFont>
</span>
</Button>
)}
</Space> </Space>
</Col> </Col>
</Row> </Row>
@@ -47,6 +47,7 @@ const MessageList: React.FC<MessageProps> = (props) => {
const [currentIsFocus, setCurrentIsFocus] = useState(false); const [currentIsFocus, setCurrentIsFocus] = useState(false);
const systemRef = useRef<any>(null); const systemRef = useRef<any>(null);
const contentRef = useRef<any>(''); const contentRef = useRef<any>('');
const controllerRef = useRef<any>(null);
const handleSystemMessageChange = (e: any) => { const handleSystemMessageChange = (e: any) => {
setSystemMessage(e.target.value); setSystemMessage(e.target.value);
@@ -88,11 +89,21 @@ const MessageList: React.FC<MessageProps> = (props) => {
console.log('messageList=====', messageList, messageId.current, chunk); console.log('messageList=====', messageList, messageId.current, chunk);
return false; return false;
}; };
const handleStopConversation = () => {
controllerRef.current?.abort?.();
setLoading(false);
};
const submitMessage = async () => { const submitMessage = async () => {
try { try {
setLoading(true); setLoading(true);
setMessageId(); setMessageId();
setTokenResult(null); setTokenResult(null);
controllerRef.current?.abort?.();
controllerRef.current = new AbortController();
const signal = controllerRef.current.signal;
contentRef.current = ''; contentRef.current = '';
const chatParams = { const chatParams = {
messages: systemMessage messages: systemMessage
@@ -109,7 +120,8 @@ const MessageList: React.FC<MessageProps> = (props) => {
}; };
const result = await fetchChunkedData({ const result = await fetchChunkedData({
data: chatParams, data: chatParams,
url: CHAT_API url: CHAT_API,
signal
}); });
if (!result) { if (!result) {
@@ -246,6 +258,7 @@ const MessageList: React.FC<MessageProps> = (props) => {
onNewMessage={handleNewMessage} onNewMessage={handleNewMessage}
onSubmit={handleSubmit} onSubmit={handleSubmit}
onView={handleView} onView={handleView}
onStop={handleStopConversation}
disabled={loading} disabled={loading}
hasTokenResult={!!tokenResult} hasTokenResult={!!tokenResult}
feedback={<ReferenceParams usage={tokenResult}></ReferenceParams>} feedback={<ReferenceParams usage={tokenResult}></ReferenceParams>}
@@ -43,7 +43,7 @@ const ReferenceParams = (props: ReferenceParamsProps) => {
<span> <span>
{intl.formatMessage({ id: 'playground.tokenoutput' })}:{' '} {intl.formatMessage({ id: 'playground.tokenoutput' })}:{' '}
{usage.tokens_per_second * 1000} Tokens/s {usage.tokens_per_second} Tokens/s
</span> </span>
</div> </div>
); );
@@ -137,7 +137,7 @@ const ViewCodeModal: React.FC<ViewModalProps> = (props) => {
closeIcon={true} closeIcon={true}
maskClosable={false} maskClosable={false}
keyboard={false} keyboard={false}
width={660} width={600}
footer={null} footer={null}
> >
<div style={{ marginBottom: '10px' }}> <div style={{ marginBottom: '10px' }}>
@@ -152,7 +152,7 @@ const ViewCodeModal: React.FC<ViewModalProps> = (props) => {
onChangeLang={handleOnChangeLang} onChangeLang={handleOnChangeLang}
> >
<Editor <Editor
height="min(500px, 90vh)" height="min(450px, 90vh)"
theme="vs-dark" theme="vs-dark"
className="monaco-editor" className="monaco-editor"
defaultLanguage="shell" defaultLanguage="shell"
+2
View File
@@ -30,6 +30,7 @@ export const fetchChunkedData = async (params: {
data?: any; data?: any;
url: string; url: string;
params?: any; params?: any;
signal?: AbortSignal;
method?: string; method?: string;
}) => { }) => {
const method = params.method || 'POST'; const method = params.method || 'POST';
@@ -40,6 +41,7 @@ export const fetchChunkedData = async (params: {
const response = await fetch(url, { const response = await fetch(url, {
method, method,
body: method === 'POST' ? JSON.stringify(params.data) : null, body: method === 'POST' ? JSON.stringify(params.data) : null,
signal: params.signal,
headers: { headers: {
'Content-Type': 'application/json' 'Content-Type': 'application/json'
} }