AI助手与对话
ConversationList
@mox-hub/patterns · AI · 助手与对话 · canonical
conversation-list@mox-hub/patternsNavigationcanonicalsrc/components/conversation-list.tsx变体演示conversation-list
Props API
| Prop | 类型 | 默认值 | 说明 |
|---|---|---|---|
| conversations* | ConversationSummary[] | — | — |
| activeId* | string | — | — |
| loading* | boolean | false | — |
| searchable* | boolean | true | — |
| onCreate* | () => void | — | — |
| onSelect* | (id: string) => void | — | — |
| onRename* | (id: string, title: string) => void | — | — |
| onDelete* | (id: string) => void | — | — |
| onTogglePin* | (id: string, pinned: boolean) => void | — | — |
| labels* | Partial<ConversationListLabels> | — | — |
| className* | string | — | — |
源码
/**
* ConversationList —— 会话侧栏列表(搜索 / 新建 / 重命名 / 删除 / 置顶)。
*
* 只做展示与交互编排:会话数据、排序依据与所有变更动作均由消费方注入;
* 置顶优先 + updatedAt 降序,未置顶项按「今天 / 昨天 / 更早」分组。
*
* 不做什么:
* - 不取数、不发请求、不持久化,也不内置删除确认框(消费方可接 ConfirmDialog);
* - 不依赖 router / i18n 框架,文案经 labels 覆写,默认 zh-CN;
* - 不持有当前会话的权威状态:activeId 完全受控。
*/
import { useId, useState } from 'react';
import { Pencil, Pin, PinOff, Search, SquarePen, Trash2 } from 'lucide-react';
import { cn } from '@mox-hub/ui';
import { Button } from '@mox-hub/ui/components/button';
import { Input } from '@mox-hub/ui/components/input';
import { ScrollArea } from '@mox-hub/ui/components/scroll-area';
import { formatDate, formatRelative } from '@mox-hub/ui/format';
import { useFormatters, useI18n } from '@mox-hub/ui/i18n';
import { usePatternLabels } from '../lib/i18n';
/** 会话摘要:只保留侧栏渲染需要的字段(与 ordo 类型结构兼容)。 */
export interface ConversationSummary {
id: string;
title?: string | null;
updatedAt: string;
messageCount?: number;
pinned?: boolean;
}
/** 组件内文案缺省(中文常量;消费方经 labels 覆写接入 i18n)。 */
export interface ConversationListLabels {
new: string;
search: string;
empty: string;
noResults: string;
loading: string;
untitled: string;
pinnedGroup: string;
todayGroup: string;
yesterdayGroup: string;
earlierGroup: string;
pin: string;
unpin: string;
rename: string;
delete: string;
}
export const CONVERSATION_LIST_DEFAULT_LABELS: ConversationListLabels = {
new: '新建对话',
search: '搜索对话',
empty: '还没有对话',
noResults: '没有匹配的对话',
loading: '加载中…',
untitled: '未命名对话',
pinnedGroup: '置顶',
todayGroup: '今天',
yesterdayGroup: '昨天',
earlierGroup: '更早',
pin: '置顶',
unpin: '取消置顶',
rename: '重命名',
delete: '删除',
};
export interface ConversationListProps {
conversations: ConversationSummary[];
activeId?: string | null;
loading?: boolean;
searchable?: boolean;
onCreate?: () => void;
onSelect: (id: string) => void;
onRename?: (id: string, title: string) => void;
onDelete?: (id: string) => void;
onTogglePin?: (id: string, pinned: boolean) => void;
labels?: Partial<ConversationListLabels>;
className?: string;
}
interface ConversationGroup {
key: 'pinned' | 'today' | 'yesterday' | 'earlier';
label: string;
items: ConversationSummary[];
}
const DAY_MS = 24 * 60 * 60 * 1000;
function updatedAtTimestamp(conversation: ConversationSummary): number {
const timestamp = Date.parse(conversation.updatedAt);
return Number.isNaN(timestamp) ? 0 : timestamp;
}
/**
* 分组:置顶优先,其余按本地日历日切「今天 / 昨天 / 更早」;
* 每组内按 updatedAt 降序。无效日期归入「更早」,避免脏数据打断排序。
*/
function buildGroups(
conversations: ConversationSummary[],
labels: ConversationListLabels,
now = Date.now(),
): ConversationGroup[] {
const sorted = [...conversations].sort(
(a, b) => updatedAtTimestamp(b) - updatedAtTimestamp(a),
);
const todayKey = formatDate(now);
const yesterdayKey = formatDate(now - DAY_MS);
const pinned: ConversationSummary[] = [];
const today: ConversationSummary[] = [];
const yesterday: ConversationSummary[] = [];
const earlier: ConversationSummary[] = [];
for (const conversation of sorted) {
if (conversation.pinned) {
pinned.push(conversation);
continue;
}
const dayKey = formatDate(conversation.updatedAt);
if (dayKey !== '' && dayKey === todayKey) {
today.push(conversation);
} else if (dayKey !== '' && dayKey === yesterdayKey) {
yesterday.push(conversation);
} else {
earlier.push(conversation);
}
}
const groups: ConversationGroup[] = [
{ key: 'pinned', label: labels.pinnedGroup, items: pinned },
{ key: 'today', label: labels.todayGroup, items: today },
{ key: 'yesterday', label: labels.yesterdayGroup, items: yesterday },
{ key: 'earlier', label: labels.earlierGroup, items: earlier },
];
return groups.filter((group) => group.items.length > 0);
}
export function ConversationList({
conversations,
activeId,
loading = false,
searchable = true,
onCreate,
onSelect,
onRename,
onDelete,
onTogglePin,
labels,
className,
}: ConversationListProps) {
const D = usePatternLabels('conversationList', CONVERSATION_LIST_DEFAULT_LABELS);
const text: ConversationListLabels = {
new: labels?.new ?? D.new,
search: labels?.search ?? D.search,
empty: labels?.empty ?? D.empty,
noResults: labels?.noResults ?? D.noResults,
loading: labels?.loading ?? D.loading,
untitled: labels?.untitled ?? D.untitled,
pinnedGroup: labels?.pinnedGroup ?? D.pinnedGroup,
todayGroup: labels?.todayGroup ?? D.todayGroup,
yesterdayGroup: labels?.yesterdayGroup ?? D.yesterdayGroup,
earlierGroup: labels?.earlierGroup ?? D.earlierGroup,
pin: labels?.pin ?? D.pin,
unpin: labels?.unpin ?? D.unpin,
rename: labels?.rename ?? D.rename,
delete: labels?.delete ?? D.delete,
};
const F = useFormatters();
const { locale } = useI18n();
const headingPrefix = useId();
const [query, setQuery] = useState('');
const [editingId, setEditingId] = useState<string | null>(null);
const [draftTitle, setDraftTitle] = useState('');
const normalizedQuery = query.trim().toLocaleLowerCase();
const filtered = normalizedQuery
? conversations.filter((conversation) =>
(conversation.title ?? '').toLocaleLowerCase().includes(normalizedQuery),
)
: conversations;
const groups = buildGroups(filtered, text);
const startRename = (conversation: ConversationSummary) => {
setEditingId(conversation.id);
setDraftTitle(conversation.title ?? '');
};
const cancelRename = () => {
setEditingId(null);
setDraftTitle('');
};
const commitRename = (conversation: ConversationSummary) => {
const nextTitle = draftTitle.trim();
if (nextTitle !== '') {
onRename?.(conversation.id, nextTitle);
}
setEditingId(null);
setDraftTitle('');
};
const formatUpdatedAt = (updatedAt: string) =>
formatRelative(updatedAt, { locale }) || F.date(updatedAt);
return (
<div
data-ai-component="conversation.list"
className={cn('flex min-h-0 flex-col gap-2', className)}
>
<Button
type="button"
variant="outline"
disabled={loading || !onCreate}
onClick={onCreate}
className="h-8 justify-start gap-2 text-xs"
data-ai-action="conversation.new.click"
>
<SquarePen className="size-3.5" aria-hidden="true" />
{text.new}
</Button>
{searchable ? (
<div className="relative">
<Search
aria-hidden="true"
className="pointer-events-none absolute start-2.5 top-1/2 size-3.5 -translate-y-1/2 text-content-text-muted"
/>
<Input
type="search"
value={query}
disabled={loading}
onChange={(event) => setQuery(event.target.value)}
placeholder={text.search}
aria-label={text.search}
className="h-8 ps-8 text-xs"
data-ai-action="conversation.search.input"
/>
</div>
) : null}
{loading ? (
<div role="status" className="flex flex-col gap-1 px-1 py-2">
<span className="sr-only">{text.loading}</span>
{[0, 1, 2].map((index) => (
<div
key={index}
aria-hidden="true"
className="h-8 animate-pulse rounded-md bg-muted/60"
/>
))}
</div>
) : groups.length === 0 ? (
<p className="px-2 py-6 text-center text-xs text-content-text-muted">
{normalizedQuery !== '' ? text.noResults : text.empty}
</p>
) : (
<ScrollArea
overscrollContain
className="min-h-0 flex-1"
contentClassName="pb-1 pe-2"
>
<div className="flex flex-col gap-3 px-1">
{groups.map((group, groupIndex) => {
const headingId = `${headingPrefix}-group-${groupIndex}`;
return (
<section
key={group.key}
aria-labelledby={headingId}
className="flex flex-col gap-1"
>
<h3
id={headingId}
className="px-2 text-caption font-medium text-content-text-muted"
>
{group.label}
</h3>
<ul className="flex flex-col gap-0.5">
{group.items.map((conversation) => {
const isActive = conversation.id === activeId;
const isEditing = conversation.id === editingId;
const title =
conversation.title?.trim() || text.untitled;
const actionSuffix = `:${title}`;
return (
<li key={conversation.id} className="group relative">
<div
className={cn(
'flex items-center gap-1 rounded-md',
isActive && 'bg-accent',
)}
>
{isEditing ? (
<div className="flex min-w-0 flex-1 items-center px-1 py-1">
<Input
autoFocus
value={draftTitle}
onChange={(event) =>
setDraftTitle(event.target.value)
}
onKeyDown={(event) => {
if (
event.key === 'Enter' &&
!event.nativeEvent.isComposing
) {
event.preventDefault();
commitRename(conversation);
} else if (event.key === 'Escape') {
event.preventDefault();
cancelRename();
}
}}
aria-label={`${text.rename}${actionSuffix}`}
className="h-7 text-xs"
/>
</div>
) : (
<Button
type="button"
variant="ghost"
onClick={() => onSelect(conversation.id)}
aria-current={isActive ? 'true' : undefined}
className="h-auto min-h-12 min-w-0 flex-1 flex-col items-start justify-start gap-0.5 px-2 py-1.5 text-start font-normal whitespace-normal"
data-ai-action="conversation.select.click"
>
<span
className="w-full shrink-0 truncate text-label text-content-text"
title={title}
>
{title}
</span>
<span className="shrink-0 text-caption whitespace-nowrap text-content-text-muted">
{formatUpdatedAt(conversation.updatedAt)}
</span>
</Button>
)}
{isEditing ? null : (
<div className="flex shrink-0 items-center gap-0.5 pe-1 invisible opacity-0 transition-opacity duration-fast group-hover:visible group-hover:opacity-100 group-focus-within:visible group-focus-within:opacity-100 pointer-coarse:visible pointer-coarse:opacity-100">
{onTogglePin ? (
<Button
type="button"
variant="ghost"
size="icon-2xs"
aria-label={`${
conversation.pinned ? text.unpin : text.pin
}${actionSuffix}`}
title={
conversation.pinned ? text.unpin : text.pin
}
onClick={() =>
onTogglePin(
conversation.id,
!conversation.pinned,
)
}
>
{conversation.pinned ? (
<PinOff aria-hidden="true" />
) : (
<Pin aria-hidden="true" />
)}
</Button>
) : null}
{onRename ? (
<Button
type="button"
variant="ghost"
size="icon-2xs"
aria-label={`${text.rename}${actionSuffix}`}
title={text.rename}
onClick={() => startRename(conversation)}
>
<Pencil aria-hidden="true" />
</Button>
) : null}
{onDelete ? (
<Button
type="button"
variant="ghost-danger"
size="icon-2xs"
aria-label={`${text.delete}${actionSuffix}`}
title={text.delete}
onClick={() => onDelete(conversation.id)}
>
<Trash2 aria-hidden="true" />
</Button>
) : null}
</div>
)}
</div>
</li>
);
})}
</ul>
</section>
);
})}
</div>
</ScrollArea>
)}
</div>
);
}
可访问性与 RTL
- 键盘:交互件保留
:focus-visible焦点环;浮层支持 Escape 关闭与焦点归还,菜单 / 页签按 Base UI 约定支持方向键。 筛选菜单、拖拽排序、执行树与模型 listbox 等关键键盘流由 Playwright 断言覆盖,见规范示例 · 交互与可访问性。 - RTL:间距、对齐与方向性图标使用逻辑属性 (
ms-*/text-start/rtl:-scale-x-100);通过ThemeProvider或I18nProvider的direction="rtl"驱动,`lint:rtl` 会拦截新增物理类。 - 文案:优先用组件
labels/translate/translatorprops,其次用I18nProvider目录;内置 zh-CN 默认值,en-US 为参考翻译。见Theming · i18n 与 RTL。 - 对比度:高对比度 token、2px 控件边框与 3px 焦点环由主题层统一提供,见Foundations · Contrast。
用法说明
会话侧栏:搜索、置顶、重命名、删除、选择;loading/empty 两态,时间格式化与新建动作由消费方注入。