refactor: repartition server-side and client-side code

This commit is contained in:
LIlGG
2025-10-11 18:26:07 +08:00
parent 7acc4949fb
commit e9b573a276
309 changed files with 631 additions and 962 deletions

View File

@@ -0,0 +1,178 @@
import { useParams } from '@remix-run/react';
import classNames from 'classnames';
import { type ForwardedRef, forwardRef, useCallback } from 'react';
import { Checkbox } from '~/.client/components/ui/Checkbox';
import WithTooltip from '~/.client/components/ui/Tooltip';
import { useEditChatDescription } from '~/.client/hooks';
import type { ServerChatItem } from '~/.client/hooks/useChatEntries';
interface HistoryItemProps {
item: ServerChatItem;
onDelete?: (event: React.UIEvent) => void;
onDuplicate?: (id: string) => void;
selectionMode?: boolean;
isSelected?: boolean;
onToggleSelection?: (id: string) => void;
}
export function HistoryItem({
item,
onDelete,
onDuplicate,
selectionMode = false,
isSelected = false,
onToggleSelection,
}: HistoryItemProps) {
const { id } = useParams();
const isActiveChat = id === item.id;
const { editing, handleChange, handleBlur, handleSubmit, handleKeyDown, currentDescription, toggleEditMode } =
useEditChatDescription({
initialDescription: item.description || '',
chatId: item.id,
});
const handleItemClick = useCallback(
(e: React.MouseEvent) => {
if (selectionMode) {
e.preventDefault();
e.stopPropagation();
console.log('Item clicked in selection mode:', item.id);
onToggleSelection?.(item.id);
}
},
[selectionMode, item.id, onToggleSelection],
);
const handleCheckboxChange = useCallback(() => {
console.log('Checkbox changed for item:', item.id);
onToggleSelection?.(item.id);
}, [item.id, onToggleSelection]);
const handleDeleteClick = useCallback(
(event: React.MouseEvent<HTMLButtonElement, MouseEvent>) => {
event.preventDefault();
event.stopPropagation();
console.log('Delete button clicked for item:', item.id);
if (onDelete) {
onDelete(event as unknown as React.UIEvent);
}
},
[onDelete, item.id],
);
return (
<div
className={classNames(
'group rounded-lg text-sm text-gray-700 dark:text-gray-300 hover:text-gray-900 dark:hover:text-white hover:bg-gray-50/80 dark:hover:bg-gray-800/30 overflow-hidden flex justify-between items-center px-1 py-2.5 transition-colors',
{ 'text-gray-900 dark:text-white bg-gray-50/80 dark:bg-gray-800/30': isActiveChat },
{ 'cursor-pointer': selectionMode },
)}
onClick={selectionMode ? handleItemClick : undefined}
>
<div
className={classNames('flex items-center mr-2 invisible group-hover:visible', {
'!visible': selectionMode,
})}
onClick={(e) => e.stopPropagation()}
>
<Checkbox
id={`select-${item.id}`}
checked={isSelected}
onCheckedChange={handleCheckboxChange}
className="size-4"
/>
</div>
{editing ? (
<form onSubmit={handleSubmit} className="flex-1 flex items-center gap-2 pr-2">
<input
type="text"
className="flex-1 bg-white dark:bg-gray-900 text-gray-900 dark:text-white rounded-md px-3 py-1.5 text-sm border border-gray-200 dark:border-gray-800 focus:outline-none focus:ring-1 focus:ring-purple-500/50"
autoFocus
value={currentDescription}
onChange={handleChange}
onBlur={handleBlur}
onKeyDown={handleKeyDown}
/>
<button
type="submit"
className="i-ph:check size-4 text-gray-500 hover:text-purple-500 transition-colors"
onMouseDown={handleSubmit}
/>
</form>
) : (
<a
href={`/chat/${item.id}`}
className="flex w-full relative items-center"
onClick={selectionMode ? handleItemClick : undefined}
>
<span className="truncate max-w-[calc(100%-90px)] pl-2">{currentDescription}</span>
<div
className={classNames(
'absolute right-0 top-0 bottom-0 flex items-center px-2 transition-colors',
'min-w-[80px] justify-end z-10',
'bg-gradient-to-l from-upage-elements-background-depth-1 via-upage-elements-background-depth-1 to-transparent',
)}
>
<div className="flex items-center gap-2.5 text-gray-400 dark:text-gray-500 opacity-0 group-hover:opacity-100 transition-opacity">
{onDuplicate && (
<ChatActionButton
toolTipContent="复制"
icon="i-mingcute:copy-2-line size-4"
onClick={(event) => {
event.preventDefault();
onDuplicate?.(item.id);
}}
/>
)}
<ChatActionButton
toolTipContent="重命名"
icon="i-mingcute:edit-2-line size-4"
onClick={(event) => {
event.preventDefault();
toggleEditMode();
}}
/>
<ChatActionButton
toolTipContent="删除"
icon="i-mingcute:delete-2-line size-4"
className="hover:text-red-500 dark:hover:text-red-400"
onClick={handleDeleteClick}
/>
</div>
</div>
</a>
)}
</div>
);
}
const ChatActionButton = forwardRef(
(
{
toolTipContent,
icon,
className,
onClick,
}: {
toolTipContent: string;
icon: string;
className?: string;
onClick: (event: React.MouseEvent<HTMLButtonElement, MouseEvent>) => void;
btnTitle?: string;
},
ref: ForwardedRef<HTMLButtonElement>,
) => {
return (
<WithTooltip tooltip={toolTipContent} position="bottom" sideOffset={4}>
<button
ref={ref}
type="button"
className={`text-gray-400 dark:text-gray-500 hover:text-purple-500 dark:hover:text-purple-400 transition-colors ${icon} ${className ? className : ''}`}
onClick={onClick}
/>
</WithTooltip>
);
},
);

View File

@@ -0,0 +1,23 @@
import { memo, useEffect, useState } from 'react';
import { IconButton } from '~/.client/components/ui/IconButton';
import { toggleSidebar } from '~/.client/stores/sidebar';
interface HistorySwitchProps {
className?: string;
}
export const HistorySwitch = memo(({ className }: HistorySwitchProps) => {
const [domLoaded, setDomLoaded] = useState(false);
useEffect(() => {
setDomLoaded(true);
}, []);
return (
domLoaded && (
<IconButton className={className} title="查看历史" onClick={toggleSidebar}>
<div className="i-mingcute:history-line text-xl"></div>
</IconButton>
)
);
});

View File

@@ -0,0 +1,381 @@
import { useStore } from '@nanostores/react';
import classNames from 'classnames';
import { motion, type Variants } from 'framer-motion';
import { memo, useCallback, useEffect, useMemo, useRef, useState } from 'react';
import { toast } from 'sonner';
import { ControlPanel } from '~/.client/components/@settings/core/ControlPanel';
import { Dialog, DialogButton, DialogDescription, DialogRoot, DialogTitle } from '~/.client/components/ui/Dialog';
import { SettingsButton } from '~/.client/components/ui/SettingsButton';
import { useAuth } from '~/.client/hooks';
import { type ServerChatItem, useChatEntries } from '~/.client/hooks/useChatEntries';
import { useChatOperate } from '~/.client/hooks/useChatOperate';
import { aiState } from '~/.client/stores/ai-state';
import { sidebarStore } from '~/.client/stores/sidebar';
import { cubicEasingFn } from '~/.client/utils/easings';
import WithTooltip from '../ui/Tooltip';
import { binDates } from './date-binning';
import { HistoryItem } from './HistoryItem.client';
const menuVariants = {
closed: {
opacity: 0,
visibility: 'hidden',
left: '-340px',
transition: {
duration: 0.2,
ease: cubicEasingFn,
},
},
open: {
opacity: 1,
visibility: 'initial',
left: 0,
transition: {
duration: 0.2,
ease: cubicEasingFn,
},
},
} satisfies Variants;
type DialogContent = { type: 'delete'; item: ServerChatItem } | { type: 'bulkDelete'; items: ServerChatItem[] } | null;
export const Menu = memo(() => {
const { duplicateCurrentChat, deleteChat, deleteSelectedItems } = useChatOperate();
const { entries, isLoading, loadChatEntries } = useChatEntries();
const { chatId } = useStore(aiState);
const menuRef = useRef<HTMLDivElement>(null);
const [dialogContent, setDialogContent] = useState<DialogContent>(null);
const [isSettingsOpen, setIsSettingsOpen] = useState(false);
const [selectedItems, setSelectedItems] = useState<string[]>([]);
const [isInitialized, setIsInitialized] = useState(false);
const sidebar = useStore(sidebarStore);
const [searchTerm, setSearchTerm] = useState('');
const { isAuthenticated } = useAuth();
const isShowMenu = useMemo(() => {
return isAuthenticated && sidebar;
}, [isAuthenticated, sidebar]);
// 处理搜索
const handleSearch = useCallback(
(e: React.ChangeEvent<HTMLInputElement>) => {
const value = e.target.value;
setSearchTerm(value);
// 重新加载
loadChatEntries(value);
},
[loadChatEntries],
);
// 初始加载聊天列表,仅在组件挂载时执行一次
useEffect(() => {
if (isShowMenu && !isInitialized) {
loadChatEntries();
setIsInitialized(true);
}
}, [isShowMenu, loadChatEntries, isInitialized]);
const deleteItem = useCallback(
async (event: React.UIEvent, item: ServerChatItem) => {
event.preventDefault();
event.stopPropagation();
console.log('Attempting to delete chat:', { id: item.id, description: item.description });
try {
await deleteChat(item.id);
toast.success('聊天已删除成功');
if (chatId === item.id) {
console.log('Navigating away from deleted chat');
window.location.pathname = '/';
}
} catch (error) {
console.error('Failed to delete chat:', error);
toast.error('删除聊天失败');
} finally {
loadChatEntries();
}
},
[loadChatEntries, deleteChat, chatId],
);
const closeDialog = () => {
setDialogContent(null);
};
const toggleItemSelection = useCallback((id: string) => {
setSelectedItems((prev) => {
const newSelectedItems = prev.includes(id) ? prev.filter((itemId) => itemId !== id) : [...prev, id];
console.log('Selected items updated:', newSelectedItems);
return newSelectedItems;
});
}, []);
const handleBulkDeleteClick = useCallback(() => {
if (selectedItems.length === 0) {
toast.info('至少选择一个聊天来删除');
return;
}
const selectedChats = entries.filter((item) => selectedItems.includes(item.id));
if (selectedChats.length === 0) {
toast.error('未找到选中的聊天');
return;
}
setDialogContent({ type: 'bulkDelete', items: selectedChats });
}, [selectedItems, entries]);
const selectAll = useCallback(() => {
const allFilteredIds = entries.map((item) => item.id);
setSelectedItems((prev) => {
const allFilteredAreSelected = allFilteredIds.length > 0 && allFilteredIds.every((id) => prev.includes(id));
if (allFilteredAreSelected) {
// Deselect only the filtered items
const newSelectedItems = prev.filter((id) => !allFilteredIds.includes(id));
console.log('Deselecting all filtered items. New selection:', newSelectedItems);
return newSelectedItems;
}
// Select all filtered items, adding them to any existing selections
const newSelectedItems = [...new Set([...prev, ...allFilteredIds])];
console.log('Selecting all filtered items. New selection:', newSelectedItems);
return newSelectedItems;
});
}, [entries]);
const handleDuplicate = async (id: string) => {
await duplicateCurrentChat(id);
loadChatEntries();
};
const handleSettingsClick = () => {
setIsSettingsOpen(true);
};
const handleSettingsClose = () => {
setIsSettingsOpen(false);
};
const setDialogContentWithLogging = useCallback((content: DialogContent) => {
console.log('Setting dialog content:', content);
setDialogContent(content);
}, []);
const handleDeleteSelectedItems = useCallback(
async (itemsToDeleteNow: string[]) => {
try {
await deleteSelectedItems(itemsToDeleteNow);
// 清空选择项
setSelectedItems([]);
// 检查是否需要导航
const currentChatId = chatId;
if (currentChatId && itemsToDeleteNow.includes(currentChatId)) {
console.log('Navigating away from deleted chat');
window.location.pathname = '/';
}
toast.success(`${itemsToDeleteNow.length} 个聊天已删除成功`);
} catch (error) {
console.error('Failed to delete chats:', error);
toast.error('删除聊天失败');
} finally {
loadChatEntries();
}
},
[deleteSelectedItems, loadChatEntries, chatId],
);
return (
<>
<motion.div
ref={menuRef}
initial="closed"
animate={isShowMenu ? 'open' : 'closed'}
variants={menuVariants}
style={{ width: '300px' }}
className={classNames(
'flex selection-accent flex-col side-menu absolute h-full',
'bg-upage-elements-background-depth-1 border-r border-gray-100 dark:border-gray-800/50',
'shadow-sm text-sm',
isSettingsOpen ? 'z-40' : 'z-sidebar',
)}
>
<div className="flex-1 flex flex-col size-full overflow-hidden">
<div className="p-4 space-y-3">
<a
href="/"
className="flex gap-2 items-center bg-purple-50 dark:bg-purple-500/10 text-purple-700 dark:text-purple-300 hover:bg-purple-100 dark:hover:bg-purple-500/20 rounded-lg px-4 py-2.5 transition-colors"
>
<span className="inline-block i-ph:plus-circle size-4" />
<span className="text-sm font-medium"></span>
</a>
<div className="relative w-full">
<div className="absolute left-3 top-1/2 -translate-y-1/2 z-1">
<div
className={`i-mingcute:search-2-line size-4 ${isLoading ? 'animate-pulse text-purple-500' : 'text-gray-400 dark:text-gray-500'}`}
/>
</div>
<input
className="w-full bg-gray-50 dark:bg-gray-900 relative pl-9 pr-3 py-2 rounded-lg focus:outline-none focus:ring-1 focus:ring-purple-500/50 text-sm text-gray-900 dark:text-gray-100 placeholder-gray-500 dark:placeholder-gray-500 border border-gray-200 dark:border-gray-800"
type="search"
placeholder="搜索聊天记录..."
value={searchTerm}
onChange={handleSearch}
aria-label="搜索聊天记录"
/>
</div>
</div>
<div className="flex-1 overflow-auto px-2 pb-20">
{isLoading && entries.length === 0 ? (
<div className="px-4 text-gray-500 dark:text-gray-400 text-sm">...</div>
) : (
entries.length === 0 && (
<div className="px-4 text-gray-500 dark:text-gray-400 text-sm"></div>
)
)}
<DialogRoot open={dialogContent !== null}>
{binDates(entries).map(({ category, items }) => (
<div key={category} className="mt-2 first:mt-0 space-y-1">
<div className="text-xs font-medium text-gray-500 dark:text-gray-400 sticky top-0 z-1 bg-upage-elements-background-depth-1 px-3 py-1">
{category}
</div>
<div className="space-y-0.5 pr-1">
{items.map((item) => (
<HistoryItem
key={item.id}
item={item}
onDelete={(event) => {
event.preventDefault();
event.stopPropagation();
setDialogContentWithLogging({ type: 'delete', item });
}}
onDuplicate={() => handleDuplicate(item.id)}
selectionMode={selectedItems.length > 0}
isSelected={selectedItems.includes(item.id)}
onToggleSelection={toggleItemSelection}
/>
))}
</div>
</div>
))}
<Dialog onBackdrop={closeDialog} onClose={closeDialog}>
{dialogContent?.type === 'delete' && (
<>
<div className="p-6 bg-white dark:bg-gray-950">
<DialogTitle className="text-gray-900 dark:text-white"></DialogTitle>
<DialogDescription className="mt-2 text-gray-600 dark:text-gray-400">
{' '}
<span className="font-medium text-gray-900 dark:text-white">
{dialogContent.item.description}
</span>{' '}
</DialogDescription>
</div>
<div className="flex justify-end gap-3 px-6 py-4 bg-gray-50 dark:bg-gray-900 border-t border-gray-100 dark:border-gray-800">
<DialogButton type="secondary" onClick={closeDialog}>
</DialogButton>
<DialogButton
type="danger"
onClick={(event) => {
deleteItem(event, dialogContent.item);
closeDialog();
}}
>
</DialogButton>
</div>
</>
)}
{dialogContent?.type === 'bulkDelete' && (
<>
<div className="p-6 bg-white dark:bg-gray-950">
<DialogTitle className="text-gray-900 dark:text-white"></DialogTitle>
<DialogDescription className="mt-2 text-gray-600 dark:text-gray-400">
{dialogContent.items.length}
<div className="mt-2 max-h-32 overflow-auto border border-gray-100 dark:border-gray-800 rounded-md bg-gray-50 dark:bg-gray-900 p-2">
<ul className="list-disc pl-5 space-y-1">
{dialogContent.items.map((item) => (
<li key={item.id} className="text-sm">
<span className="font-medium text-gray-900 dark:text-white">{item.description}</span>
</li>
))}
</ul>
</div>
<span className="mt-3 block"></span>
</DialogDescription>
</div>
<div className="flex justify-end gap-3 px-6 py-4 bg-gray-50 dark:bg-gray-900 border-t border-gray-100 dark:border-gray-800">
<DialogButton type="secondary" onClick={closeDialog}>
</DialogButton>
<DialogButton
type="danger"
onClick={() => {
/*
* Pass the current selectedItems to the delete function.
* This captures the state at the moment the user confirms.
*/
const itemsToDeleteNow = [...selectedItems];
handleDeleteSelectedItems(itemsToDeleteNow);
closeDialog();
}}
>
</DialogButton>
</div>
</>
)}
</Dialog>
</DialogRoot>
</div>
{selectedItems.length > 0 && (
<motion.div
initial={{ opacity: 0, y: 10 }}
animate={{ opacity: 1, y: 0 }}
exit={{ opacity: 0, y: 10 }}
transition={{ duration: 0.3, ease: 'easeOut' }}
className="absolute bottom-20 z-1 w-full flex justify-center"
>
<div className="rounded-full bg-upage-elements-background-depth-1 flex items-center justify-center border border-gray-200 dark:border-gray-800 shadow-md dark:shadow-gray-950/50 p-2.5 gap-3 transition-all duration-200">
<WithTooltip tooltip={selectedItems.length === entries.length ? '取消全选' : '全选'}>
<button
onClick={selectAll}
className="rounded-full bg-gray-50 dark:bg-gray-800 p-2.5 hover:bg-gray-100 dark:hover:bg-gray-700 flex items-center justify-center transition-colors duration-200"
>
{selectedItems.length === entries.length ? (
<div className="i-mingcute:checkbox-fill size-5 text-blue-500" />
) : (
<div className="i-mingcute:checkbox-line size-5 text-blue-500" />
)}
</button>
</WithTooltip>
<WithTooltip tooltip="删除选中项">
<button
onClick={handleBulkDeleteClick}
className="rounded-full bg-gray-50 dark:bg-gray-800 p-2.5 hover:bg-gray-100 dark:hover:bg-gray-700 flex items-center justify-center transition-colors duration-200"
>
<div className="i-mingcute:delete-2-line size-5 text-red-500" />
</button>
</WithTooltip>
</div>
</motion.div>
)}
{import.meta.env.MODE === 'development' && (
<div className="flex items-center justify-between border-t border-gray-200 dark:border-gray-800 px-4 py-3">
<SettingsButton onClick={handleSettingsClick} />
</div>
)}
</div>
</motion.div>
{import.meta.env.MODE === 'development' && <ControlPanel open={isSettingsOpen} onClose={handleSettingsClose} />}
</>
);
});

View File

@@ -0,0 +1,60 @@
import { format, isAfter, isThisWeek, isThisYear, isToday, isYesterday, subDays } from 'date-fns';
import { zhCN } from 'date-fns/locale/zh-CN';
import type { ServerChatItem } from '~/.client/hooks/useChatEntries';
type Bin = { category: string; items: ServerChatItem[] };
export function binDates(_list: ServerChatItem[]) {
const list = _list.slice().sort((a, b) => Date.parse(b.timestamp) - Date.parse(a.timestamp));
const binLookup: Record<string, Bin> = {};
const bins: Array<Bin> = [];
list.forEach((item) => {
const category = dateCategory(new Date(item.timestamp));
if (!(category in binLookup)) {
const bin = {
category,
items: [item],
};
binLookup[category] = bin;
bins.push(bin);
} else {
binLookup[category].items.push(item);
}
});
return bins;
}
function dateCategory(date: Date) {
if (isToday(date)) {
return '今天';
}
if (isYesterday(date)) {
return '昨天';
}
if (isThisWeek(date)) {
// e.g., "Mon" instead of "Monday"
return format(date, 'EEE', { locale: zhCN });
}
const thirtyDaysAgo = subDays(new Date(), 30);
if (isAfter(date, thirtyDaysAgo)) {
return '过去 30 天';
}
if (isThisYear(date)) {
// e.g., "Jan" instead of "January"
return format(date, 'LLL', { locale: zhCN });
}
// e.g., "Jan 2023" instead of "January 2023"
return format(date, 'LLL yyyy', { locale: zhCN });
}