🤯 LobeHub - Super-Agents on Your Team. Add super-agents to the chats your team already uses.They take on work by themselves and get better every week.
TypeScript agentagent-collaborationagent-harnessloop-engineeringmcppersonal-assistantproactive-agentskillssuper-agenttask-management
♻️ refactor: move chat item into chat (#8970)
Arvin Xue09817e7a644
diff --git a/package.json b/package.jsonindex 450c1855571..48b5aabfd58 100644--- a/package.json+++ b/package.json@@ -300,7 +300,6 @@"@types/chroma-js": "^3.1.1","@types/crypto-js": "^4.2.2","@types/debug": "^4.1.12",- "@types/diff": "^8.0.0","@types/fs-extra": "^11.0.4","@types/ip": "^1.1.3","@types/json-schema": "^7.0.15",diff --git a/src/components/ChatItem/ChatItem.tsx b/src/components/ChatItem/ChatItem.tsxnew file mode 100644index 00000000000..a03c4bf4944--- /dev/null+++ b/src/components/ChatItem/ChatItem.tsx@@ -0,0 +1,183 @@+'use client';++import { useResponsive } from 'antd-style';+import { memo, useEffect, useRef, useState } from 'react';+import { Flexbox } from 'react-layout-kit';++import Actions from './components/Actions';+import Avatar from './components/Avatar';+import BorderSpacing from './components/BorderSpacing';+import ErrorContent from './components/ErrorContent';+import MessageContent from './components/MessageContent';+import Title from './components/Title';+import { useStyles } from './style';+import type { ChatItemProps } from './type';++const MOBILE_AVATAR_SIZE = 32;++const ChatItem = memo<ChatItemProps>(+ ({+ avatarAddon,+ onAvatarClick,+ avatarProps,+ actions,+ className,+ primary,+ loading,+ message,+ placeholderMessage = '...',+ placement = 'left',+ variant = 'bubble',+ avatar,+ error,+ showTitle,+ time,+ editing,+ onChange,+ onEditingChange,+ messageExtra,+ renderMessage,+ text,+ errorMessage,+ onDoubleClick,+ fontSize,+ aboveMessage,+ belowMessage,+ markdownProps,+ actionsWrapWidth = 54,+ ...rest+ }) => {+ const { mobile } = useResponsive();+ const { cx, styles } = useStyles({+ editing,+ placement,+ primary,+ showTitle,+ time,+ title: avatar.title,+ variant,+ });++ // 在 ChatItem 组件中添加+ const contentRef = useRef<HTMLDivElement>(null);+ const containerRef = useRef<HTMLDivElement>(null);+ const [layoutMode, setLayoutMode] = useState<'horizontal' | 'vertical'>(+ variant === 'bubble' ? 'horizontal' : 'vertical',+ );++ // 使用 ResizeObserver 监控内容和容器尺寸+ useEffect(() => {+ if (variant === 'docs') {+ setLayoutMode('vertical');+ return;+ }++ if (!contentRef.current || !containerRef.current) return;++ const observer = new ResizeObserver(() => {+ if (!contentRef.current || !containerRef.current) return;++ const containerWidth = containerRef.current.clientWidth;+ const contentWidth = contentRef.current.scrollWidth; // 使用scrollWidth获取实际内容宽度++ // 预留给Actions的最小空间 (根据实际Actions大小调整)++ // 只有当内容宽度 + Actions最小宽度 > 容器宽度时才切换布局+ setLayoutMode(contentWidth + actionsWrapWidth > containerWidth ? 'vertical' : 'horizontal');+ });++ observer.observe(contentRef.current);+ observer.observe(containerRef.current);++ return () => observer.disconnect();+ }, [variant, actionsWrapWidth]);++ return (+ <Flexbox+ className={cx(styles.container, className)}+ direction={placement === 'left' ? 'horizontal' : 'horizontal-reverse'}+ gap={mobile ? 6 : 12}+ {...rest}+ >+ <Avatar+ {...avatarProps}+ addon={avatarAddon}+ alt={avatarProps?.alt || avatar.title || 'avatar'}+ avatar={avatar}+ loading={loading}+ onClick={onAvatarClick}+ placement={placement}+ size={mobile ? MOBILE_AVATAR_SIZE : undefined}+ style={{+ marginTop: 6,+ ...avatarProps?.style,+ }}+ />+ <Flexbox+ align={placement === 'left' ? 'flex-start' : 'flex-end'}+ className={styles.messageContainer}+ ref={containerRef}+ >+ <Title avatar={avatar} placement={placement} showTitle={showTitle} time={time} />+ {aboveMessage}+ <Flexbox+ align={placement === 'left' ? 'flex-start' : 'flex-end'}+ className={styles.messageContent}+ data-layout={layoutMode} // 添加数据属性以方便样式选择+ direction={+ layoutMode === 'horizontal'+ ? placement === 'left'+ ? 'horizontal'+ : 'horizontal-reverse'+ : 'vertical'+ }+ gap={8}+ >+ <Flexbox ref={contentRef} width={'100%'}>+ {error && (message === placeholderMessage || !message) ? (+ <ErrorContent error={error} message={errorMessage} placement={placement} />+ ) : (+ <MessageContent+ editing={editing}+ fontSize={fontSize}+ markdownProps={markdownProps}+ message={message}+ messageExtra={+ <>+ {error && (+ <ErrorContent error={error} message={errorMessage} placement={placement} />+ )}+ {messageExtra}+ </>+ }+ onChange={onChange}+ onDoubleClick={onDoubleClick}+ onEditingChange={onEditingChange}+ placement={placement}+ primary={primary}+ renderMessage={renderMessage}+ text={text}+ variant={variant}+ />+ )}+ </Flexbox>+ {actions && (+ <Actions+ actions={actions}+ editing={editing}+ placement={placement}+ variant={variant}+ />+ )}+ </Flexbox>+ {belowMessage}+ </Flexbox>+ {mobile && variant === 'bubble' && <BorderSpacing borderSpacing={MOBILE_AVATAR_SIZE} />}+ </Flexbox>+ );+ },+);++export default ChatItem;++export type { ChatItemProps } from './type';diff --git a/src/components/ChatItem/components/Actions.tsx b/src/components/ChatItem/components/Actions.tsxnew file mode 100644index 00000000000..9dad8afdab2--- /dev/null+++ b/src/components/ChatItem/components/Actions.tsx@@ -0,0 +1,25 @@+import { type Ref, memo } from 'react';+import { Flexbox } from 'react-layout-kit';++import { useStyles } from '../style';+import { ChatItemProps } from '../type';++export interface ActionsProps {+ actions: ChatItemProps['actions'];+ editing?: boolean;+ placement?: ChatItemProps['placement'];+ ref?: Ref<HTMLDivElement>;+ variant?: ChatItemProps['variant'];+}++const Actions = memo<ActionsProps>(({ actions, placement, variant, editing, ref }) => {+ const { styles } = useStyles({ editing, placement, variant });++ return (+ <Flexbox align={'flex-start'} className={styles.actions} ref={ref} role="menubar">+ {actions}+ </Flexbox>+ );+});++export default Actions;diff --git a/src/components/ChatItem/components/Avatar.tsx b/src/components/ChatItem/components/Avatar.tsxnew file mode 100644index 00000000000..bea77ea8f94--- /dev/null+++ b/src/components/ChatItem/components/Avatar.tsx@@ -0,0 +1,50 @@+import { Avatar as A } from '@lobehub/ui';+import { type CSSProperties, memo } from 'react';+import { Flexbox } from 'react-layout-kit';++import { useStyles } from '../style';+import type { ChatItemProps } from '../type';+import Loading from './Loading';++export interface AvatarProps {+ addon?: ChatItemProps['avatarAddon'];+ alt?: string;+ avatar: ChatItemProps['avatar'];+ loading?: ChatItemProps['loading'];+ onClick?: ChatItemProps['onAvatarClick'];+ placement?: ChatItemProps['placement'];+ size?: number;+ style?: CSSProperties;+ unoptimized?: boolean;+}++const Avatar = memo<AvatarProps>(+ ({ loading, avatar, placement, unoptimized, addon, onClick, size = 40, style, alt }) => {+ const { styles } = useStyles({ avatarSize: size });+ const avatarContent = (+ <div className={styles.avatarContainer} style={style}>+ <A+ alt={alt || avatar.title}+ animation={loading}+ avatar={avatar.avatar}+ background={avatar.backgroundColor}+ onClick={onClick}+ size={size}+ title={avatar.title}+ unoptimized={unoptimized}+ />+ <Loading loading={loading} placement={placement} />+ </div>+ );++ if (!addon) return avatarContent;+ return (+ <Flexbox align={'center'} className={styles.avatarGroupContainer} gap={8}>+ {avatarContent}+ {addon}+ </Flexbox>+ );+ },+);++export default Avatar;diff --git a/src/components/ChatItem/components/BorderSpacing.tsx b/src/components/ChatItem/components/BorderSpacing.tsxnew file mode 100644index 00000000000..877f61a880a--- /dev/null+++ b/src/components/ChatItem/components/BorderSpacing.tsx@@ -0,0 +1,13 @@+import { memo } from 'react';++export interface BorderSpacingProps {+ borderSpacing?: number;+}++const BorderSpacing = memo<BorderSpacingProps>(({ borderSpacing }) => {+ if (!borderSpacing) return null;++ return <div style={{ flex: 'none', width: borderSpacing }} />;+});++export default BorderSpacing;diff --git a/src/components/ChatItem/components/ErrorContent.tsx b/src/components/ChatItem/components/ErrorContent.tsxnew file mode 100644index 00000000000..ade2397df51--- /dev/null+++ b/src/components/ChatItem/components/ErrorContent.tsx@@ -0,0 +1,24 @@+import { Alert } from '@lobehub/ui';+import { memo } from 'react';+import { Flexbox } from 'react-layout-kit';++import { useStyles } from '../style';+import { ChatItemProps } from '../type';++export interface ErrorContentProps {+ error?: ChatItemProps['error'];+ message?: ChatItemProps['errorMessage'];+ placement?: ChatItemProps['placement'];+}++const ErrorContent = memo<ErrorContentProps>(({ message, error, placement }) => {+ const { styles } = useStyles({ placement });++ return (+ <Flexbox className={styles.errorContainer}>+ <Alert closable={false} extra={message} showIcon type={'error'} {...error} />+ </Flexbox>+ );+});++export default ErrorContent;diff --git a/src/components/ChatItem/components/Loading.tsx b/src/components/ChatItem/components/Loading.tsxnew file mode 100644index 00000000000..06b2c9eec06--- /dev/null+++ b/src/components/ChatItem/components/Loading.tsx@@ -0,0 +1,26 @@+import { Icon } from '@lobehub/ui';+import { Loader2 } from 'lucide-react';+import { memo } from 'react';+import { Flexbox } from 'react-layout-kit';++import { useStyles } from '../style';+import { ChatItemProps } from '../type';++export interface LoadingProps {+ loading?: ChatItemProps['loading'];+ placement?: ChatItemProps['placement'];+}++const Loading = memo<LoadingProps>(({ loading, placement }) => {+ const { styles } = useStyles({ placement });++ if (!loading) return null;++ return (+ <Flexbox align={'center'} className={styles.loading} justify={'center'}>+ <Icon icon={Loader2} size={{ size: 12, strokeWidth: 3 }} spin />+ </Flexbox>+ );+});++export default Loading;diff --git a/src/components/ChatItem/components/MessageContent.tsx b/src/components/ChatItem/components/MessageContent.tsxnew file mode 100644index 00000000000..37d9326852c--- /dev/null+++ b/src/components/ChatItem/components/MessageContent.tsx@@ -0,0 +1,76 @@+import { MarkdownProps } from '@lobehub/ui';+import { EditableMessage } from '@lobehub/ui/chat';+import { useResponsive } from 'antd-style';+import { type ReactNode, memo } from 'react';+import { Flexbox } from 'react-layout-kit';++import { useStyles } from '../style';+import { ChatItemProps } from '../type';++export interface MessageContentProps {+ editing?: ChatItemProps['editing'];+ fontSize?: number;+ markdownProps?: Omit<MarkdownProps, 'className' | 'style' | 'children'>;+ message?: ReactNode;+ messageExtra?: ChatItemProps['messageExtra'];+ onChange?: ChatItemProps['onChange'];+ onDoubleClick?: ChatItemProps['onDoubleClick'];+ onEditingChange?: ChatItemProps['onEditingChange'];+ placement?: ChatItemProps['placement'];+ primary?: ChatItemProps['primary'];+ renderMessage?: ChatItemProps['renderMessage'];+ text?: ChatItemProps['text'];+ variant?: ChatItemProps['variant'];+}++const MessageContent = memo<MessageContentProps>(+ ({+ editing,+ onChange,+ onEditingChange,+ text,+ message,+ placement,+ messageExtra,+ renderMessage,+ variant,+ primary,+ onDoubleClick,+ fontSize,+ markdownProps,+ }) => {+ const { cx, styles } = useStyles({ editing, placement, primary, variant });+ const { mobile } = useResponsive();++ const content = (+ <EditableMessage+ classNames={{ input: styles.editingInput }}+ editButtonSize={'small'}+ editing={editing}+ fontSize={fontSize}+ fullFeaturedCodeBlock+ markdownProps={markdownProps}+ onChange={onChange}+ onEditingChange={onEditingChange}+ openModal={mobile ? editing : undefined}+ text={text}+ value={message ? String(message) : ''}+ />+ );+ const messageContent = renderMessage ? renderMessage(content) : content;++ return (+ <Flexbox+ className={cx(styles.message, editing && styles.editingContainer)}+ onDoubleClick={onDoubleClick}+ >+ {messageContent}+ {messageExtra && !editing ? (+ <div className={styles.messageExtra}>{messageExtra}</div>+ ) : null}+ </Flexbox>+ );+ },+);++export default MessageContent;diff --git a/src/components/ChatItem/components/Title.tsx b/src/components/ChatItem/components/Title.tsxnew file mode 100644index 00000000000..c2484bb0fd4--- /dev/null+++ b/src/components/ChatItem/components/Title.tsx@@ -0,0 +1,43 @@+import dayjs from 'dayjs';+import { memo } from 'react';+import { Flexbox } from 'react-layout-kit';++import { useStyles } from '../style';+import { ChatItemProps } from '../type';++export interface TitleProps {+ avatar: ChatItemProps['avatar'];+ placement?: ChatItemProps['placement'];+ showTitle?: ChatItemProps['showTitle'];+ time?: ChatItemProps['time'];+}++const formatTime = (time: number): string => {+ const now = dayjs();+ const target = dayjs(time);++ if (target.isSame(now, 'day')) {+ return target.format('HH:mm:ss');+ } else if (target.isSame(now, 'year')) {+ return target.format('MM-DD HH:mm:ss');+ } else {+ return target.format('YYYY-MM-DD HH:mm:ss');+ }+};++const Title = memo<TitleProps>(({ showTitle, placement, time, avatar }) => {+ const { styles } = useStyles({ placement, showTitle, time });++ return (+ <Flexbox+ className={styles.name}+ direction={placement === 'left' ? 'horizontal' : 'horizontal-reverse'}+ gap={4}+ >+ {showTitle ? avatar.title || 'untitled' : undefined}+ {time && <time>{formatTime(time)}</time>}+ </Flexbox>+ );+});++export default Title;diff --git a/src/components/ChatItem/index.ts b/src/components/ChatItem/index.tsnew file mode 100644index 00000000000..e5eca5e3127--- /dev/null+++ b/src/components/ChatItem/index.ts@@ -0,0 +1,2 @@+export { default as ChatItem } from './ChatItem';+export type * from './type';diff --git a/src/components/ChatItem/style.ts b/src/components/ChatItem/style.tsnew file mode 100644index 00000000000..a1b26e46748--- /dev/null+++ b/src/components/ChatItem/style.ts@@ -0,0 +1,208 @@+import { createStyles } from 'antd-style';+import { rgba } from 'polished';++export const useStyles = createStyles(+ (+ { cx, css, token, responsive },+ {+ placement,+ variant,+ title,+ avatarSize,+ editing,+ time,+ }: {+ avatarSize?: number;+ editing?: boolean;+ placement?: 'left' | 'right';+ primary?: boolean;+ showTitle?: boolean;+ time?: number;+ title?: string;+ variant?: 'bubble' | 'docs';+ },+ ) => {+ const blockStylish = css`+ padding-block: 8px;+ padding-inline: 12px;+ border: 1px solid ${rgba(token.colorBorderSecondary, 0.66)};+ border-radius: ${token.borderRadiusLG}px;++ background-color: ${token.colorBgContainer};+ `;++ const rawStylish = css`+ padding-block-start: ${title ? 0 : '6px'};+ `;++ const rawContainerStylish = css`+ margin-block-end: -16px;+ transition: background-color 100ms ${token.motionEaseOut};+ `;++ const typeStylish = variant === 'bubble' ? blockStylish : rawStylish;++ const editingStylish =+ editing &&+ css`+ width: 100%;+ `;++ return {+ actions: cx(+ css`+ flex: none;+ align-self: ${variant === 'bubble'+ ? 'flex-end'+ : placement === 'left'+ ? 'flex-start'+ : 'flex-end'};+ justify-content: ${placement === 'left' ? 'flex-end' : 'flex-start'};+ `,+ editing &&+ css`+ pointer-events: none !important;+ opacity: 0 !important;+ `,+ ),+ avatarContainer: css`+ position: relative;+ flex: none;+ width: ${avatarSize}px;+ height: ${avatarSize}px;+ `,+ avatarGroupContainer: css`+ width: ${avatarSize}px;+ `,+ container: cx(+ variant === 'docs' && rawContainerStylish,+ css`+ position: relative;++ width: 100%;+ max-width: 100vw;+ padding-block: 24px 12px;+ padding-inline: 12px;++ time {+ display: inline-block;+ white-space: nowrap;+ }++ div[role='menubar'] {+ display: flex;+ }++ time,+ div[role='menubar'] {+ pointer-events: none;+ opacity: 0;+ transition: opacity 200ms ${token.motionEaseOut};+ }++ &:hover {+ time,+ div[role='menubar'] {+ pointer-events: unset;+ opacity: 1;+ }+ }++ ${responsive.mobile} {+ padding-block-start: ${variant === 'docs' ? '16px' : '12px'};+ padding-inline: 8px;+ }+ `,+ ),+ editingContainer: cx(+ editingStylish,+ css`+ padding-block: 8px 12px;+ padding-inline: 12px;+ border: 1px solid ${token.colorBorderSecondary};++ &:active,+ &:hover {+ border-color: ${token.colorBorder};+ }+ `,+ variant === 'docs' &&+ css`+ border-radius: ${token.borderRadius}px;+ background: ${token.colorFillQuaternary};+ `,+ ),+ editingInput: css`+ width: 100%;+ `,+ errorContainer: css`+ position: relative;+ overflow: hidden;+ width: 100%;+ `,++ loading: css`+ position: absolute;+ inset-block-end: 0;+ inset-inline: ${placement === 'right' ? '-4px' : 'unset'}+ ${placement === 'left' ? '-4px' : 'unset'};++ width: 16px;+ height: 16px;+ border-radius: 50%;++ color: ${token.colorBgLayout};++ background: ${token.colorPrimary};+ `,+ message: cx(+ typeStylish,+ css`+ position: relative;+ overflow: hidden;+ max-width: 100%;++ ${responsive.mobile} {+ width: 100%;+ }+ `,+ ),+ messageContainer: cx(+ editingStylish,+ css`+ position: relative;+ overflow: hidden;+ max-width: 100%;+ margin-block-start: ${time ? -16 : 0}px;++ ${responsive.mobile} {+ overflow-x: auto;+ }+ `,+ ),+ messageContent: cx(+ editingStylish,+ css`+ position: relative;+ overflow: hidden;+ max-width: 100%;++ ${responsive.mobile} {+ flex-direction: column !important;+ }+ `,+ ),+ messageExtra: cx('message-extra'),+ name: css`+ pointer-events: none;++ margin-block-end: 6px;++ font-size: 12px;+ line-height: 1;+ color: ${token.colorTextDescription};+ text-align: ${placement === 'left' ? 'left' : 'right'};+ `,+ };+ },+);diff --git a/src/components/ChatItem/type.ts b/src/components/ChatItem/type.tsnew file mode 100644index 00000000000..0fd8dcf57cf--- /dev/null+++ b/src/components/ChatItem/type.ts@@ -0,0 +1,80 @@+import { AlertProps, AvatarProps, DivProps, MarkdownProps } from '@lobehub/ui';+import { EditableMessageProps, MetaData } from '@lobehub/ui/chat';+import { ReactNode } from 'react';+import { FlexboxProps } from 'react-layout-kit';++export interface ChatItemProps extends Omit<FlexboxProps, 'children' | 'onChange'> {+ aboveMessage?: ReactNode;+ /**+ * @description Actions to be displayed in the chat item+ */+ actions?: ReactNode;+ actionsWrapWidth?: number;+ /**+ * @description Metadata for the avatar+ */+ avatar: MetaData;+ avatarAddon?: ReactNode;+ avatarProps?: AvatarProps;+ belowMessage?: ReactNode;+ /**+ * @description Whether the chat item is in editing mode+ */+ editing?: boolean;+ /**+ * @description Props for Error render+ */+ error?: AlertProps;+ errorMessage?: ReactNode;+ fontSize?: number;+ /**+ * @description Whether the chat item is in loading state+ */+ loading?: boolean;+ markdownProps?: Omit<MarkdownProps, 'className' | 'style' | 'children'>;+ /**+ * @description The message content of the chat item+ */+ message?: ReactNode;+ messageExtra?: ReactNode;+ onAvatarClick?: () => void;+ /**+ * @description Callback when the message content changes+ * @param value - The new message content+ */+ onChange?: (value: string) => void;+ onDoubleClick?: DivProps['onDoubleClick'];+ /**+ * @description Callback when the editing mode changes+ * @param editing - The new editing mode+ */+ onEditingChange?: (editing: boolean) => void;+ /**+ * @default "..."+ */+ placeholderMessage?: string;+ /**+ * @description The placement of the chat item+ * @default 'left'+ */+ placement?: 'left' | 'right';+ /**+ * @description Whether the chat item is primary+ */+ primary?: boolean;+ renderMessage?: (content: ReactNode) => ReactNode;+ /**+ * @description Whether to show the title of the chat item+ */+ showTitle?: boolean;+ text?: EditableMessageProps['text'];+ /**+ * @description The timestamp of the chat item+ */+ time?: number;+ /**+ * @description The type of the chat item+ * @default 'bubble'+ */+ variant?: 'bubble' | 'docs';+}diff --git a/src/features/ChatItem/index.tsx b/src/features/ChatItem/index.tsxindex 35250ed119a..011d9fc5d0d 100644--- a/src/features/ChatItem/index.tsx+++ b/src/features/ChatItem/index.tsx@@ -1,9 +1,9 @@'use client';-import { ChatItemProps, ChatItem as ChatItemRaw } from '@lobehub/ui/chat';import isEqual from 'fast-deep-equal';import { memo, useMemo } from 'react';+import { ChatItemProps, ChatItem as ChatItemRaw } from '@/components/ChatItem';import { isDesktop } from '@/const/version';import { useElectronStore } from '@/store/electron';import { electronSyncSelectors } from '@/store/electron/selectors';