Skip to content

🤯 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.

10.2 KB
Raw Blame
'use client';

import { type ChatInputProps } from '@lobehub/editor/react';
import { ChatInput, ChatInputActionBar } from '@lobehub/editor/react';
// oxlint-disable-next-line stylex-migration/no-emotion-styles -- leftContent is an arbitrary ReactNode
import { Center, createStaticStyles, cx, Flexbox, Skeleton, Text } from '@lobehub/ui';
import { cssVar } from '@lobehub/ui/stylex/cssVar.stylex';
import * as stylex from '@stylexjs/stylex';
import { memo, type ReactNode, use, useEffect } from 'react';
import { createPortal } from 'react-dom';
import { useTranslation } from 'react-i18next';

import ChatInputNotice from '@/features/ChatInput/ChatInputNotice';
import ComposerExpandButton from '@/features/ChatInput/components/ComposerExpandButton';
import { useChatInputStore } from '@/features/ChatInput/store';
import { LayoutContainerContext } from '@/features/DesktopLayoutContainer/LayoutContainerContext';
import { useChatStore } from '@/store/chat';
import { chatSelectors } from '@/store/chat/selectors';
import { useGlobalStore } from '@/store/global';
import { systemStatusSelectors } from '@/store/global/selectors';

import ActionBar from '../ActionBar';
import { type ActionToolbarProps } from '../ActionBar';
import ControlBar from '../ControlBar';
import InputEditor from '../InputEditor';
import { useSkillDrop } from '../InputEditor/ActionTag/useSkillDrop';
import { type PlaceholderVariant } from '../InputEditor/Placeholder';
import { useDocumentDrop } from '../InputEditor/ReferDocument/useDocumentDrop';
import { useTopicDrop } from '../InputEditor/ReferTopic/useTopicDrop';
import { useWorkspaceFileDrop } from '../InputEditor/useWorkspaceFileDrop';
import { composerHoverMarker } from '../markers.stylex';
import { McpAppContextChips } from '../McpAppContextChips';
import SendArea from '../SendArea';
import TypoBar from '../TypoBar';
import ContextContainer from './ContextContainer';

const styles = stylex.create({
  footnote: { fontSize: '10px' },
  fullscreen: {
    position: 'absolute',
    zIndex: 100,
    inset: 0,
    width: '100%',
    height: '100%',
    marginBlockStart: '0',
    backgroundColor: cssVar.colorBgContainer,
    backgroundImage: 'none',
  },
  inputFullscreen: {
    borderStyle: 'none',
    borderStartStartRadius: '0 !important',
    borderStartEndRadius: '0 !important',
    borderEndStartRadius: '0 !important',
    borderEndEndRadius: '0 !important',
  },
  leftActions: { flex: 'none', minWidth: '0' },
  leftSlot: { overflow: 'hidden', flex: '1', minWidth: '0' },
});

const fallback = createStaticStyles(({ css }) => ({
  leftActions: css`
    > * {
      flex: none !important;
    }
  `,
}));

interface DesktopChatInputProps extends ActionToolbarProps {
  actionBarStyle?: React.CSSProperties;
  /**
   * Collapse the editor to a single bordered row by dropping the action bar footer.
   * Send still works through the Enter keybinding; the rest of the chrome
   * (control bar / footnote) is independently gated by `showControlBar` /
   * `showFootnote`. Defaults to false — other surfaces stay untouched.
   */
  compact?: boolean;
  /**
   * Custom node to render in place of the default ControlBar.
   * When provided, used instead of `<ControlBar />` (ignores `showControlBar`).
   */
  controlBarSlot?: ReactNode;
  extentHeaderContent?: ReactNode;
  hidden?: boolean;
  initialContent?: string;
  inputContainerProps?: ChatInputProps;
  /**
   * Swap the action bar and send area for skeleton placeholders while
   * the underlying agent / group / session config is still hydrating.
   * The editor itself stays usable. Wins over `leftContent` / `rightContent`.
   */
  isConfigLoading?: boolean;
  leftContent?: ReactNode;
  placeholder?: ReactNode;
  placeholderVariant?: PlaceholderVariant;
  rightContent?: ReactNode;
  sendAreaPrefix?: ReactNode;
  showControlBar?: boolean;
  showFootnote?: boolean;
}

const DesktopChatInput = memo<DesktopChatInputProps>(
  ({
    showFootnote,
    showControlBar = true,
    compact = false,
    controlBarSlot,
    inputContainerProps,
    extentHeaderContent,
    actionBarStyle,
    borderRadius,
    extraActionItems,
    dropdownPlacement,
    hidden,
    initialContent,
    isConfigLoading = false,
    leftContent,
    placeholder,
    placeholderVariant,
    rightContent,
    sendAreaPrefix,
  }) => {
    const { t } = useTranslation('chat');
    const layoutContainerRef = use(LayoutContainerContext);
    const [chatInputHeight, updateSystemStatus] = useGlobalStore((s) => [
      systemStatusSelectors.chatInputHeight(s),
      s.updateSystemStatus,
    ]);
    const [slashMenuRef, expand, showTypoBar, editor] = useChatInputStore((s) => [
      s.slashMenuRef,
      s.expand,
      s.showTypoBar,
      s.editor,
    ]);

    const chatKey = useChatStore(chatSelectors.currentChatKey);

    // The ControlBar (or the custom slot standing in for it) hosts the
    // context-window token tag; without one, SendArea keeps it beside Send.
    const hasControlBar = Boolean(controlBarSlot) || showControlBar;

    const setExpand = useChatInputStore((s) => s.setExpand);
    const skillDrop = useSkillDrop();
    const topicDrop = useTopicDrop();
    const documentDrop = useDocumentDrop();
    const workspaceFileDrop = useWorkspaceFileDrop();

    // Fan a single drag event out to every custom-MIME drop handler. Each one
    // no-ops unless its own MIME is present, so ordering is irrelevant.
    const handleDragOver = (event: React.DragEvent) => {
      skillDrop.onDragOver(event);
      topicDrop.onDragOver(event);
      documentDrop.onDragOver(event);
      workspaceFileDrop.onDragOver(event);
    };
    const handleDrop = (event: React.DragEvent) => {
      skillDrop.onDrop(event);
      topicDrop.onDrop(event);
      documentDrop.onDrop(event);
      workspaceFileDrop.onDrop(event);
    };

    useEffect(() => {
      if (editor) editor.focus();
      setExpand(false);
    }, [chatKey, editor, setExpand]);

    // Always mounted, at zero height while empty: mounting it with the first attachment
    // would skip its height transition (its first measurement never animates), and
    // unmounting it with the last would cut the card's exit and the collapse.
    const contextContainerNode = (
      <>
        <McpAppContextChips />
        <ContextContainer />
      </>
    );

    const loadingLeftSlot = isConfigLoading ? (
      <Flexbox horizontal align="center" gap={6} paddingInline={4}>
        <Skeleton height={28} radius={'50%'} width={28} />
        <Skeleton height={28} radius={'50%'} width={28} />
      </Flexbox>
    ) : null;
    const loadingRightSlot = isConfigLoading ? (
      <Skeleton radius={999} style={{ height: 32, minWidth: 64, width: 64 }} />
    ) : null;
    const noticeNode = !isConfigLoading && <ChatInputNotice />;
    // The action bar is `width: 100%`, so a sibling placed *inside* its
    // shrink-to-fit box is pushed past the bar's right edge and leaves a
    // one-slot hole between the last action and the expand toggle. Keep the
    // toggle in a row outside that box.
    // NOTICE: The hover-only expand button stays in layout at zero opacity to
    // prevent shifting. Keep the notice before it so the hidden 32px control
    // does not create a false gap after the microphone action.
    const leftSlotContent = (
      <Flexbox horizontal align={'center'} flex={'none'} gap={2}>
        <Flexbox
          horizontal
          align={'center'}
          className={cx(stylex.props(styles.leftActions).className, fallback.leftActions)}
        >
          {leftContent ?? (
            <ActionBar
              disableCollapse
              borderRadius={borderRadius}
              dropdownPlacement={dropdownPlacement}
              extraActionItems={extraActionItems}
            />
          )}
        </Flexbox>
        {noticeNode}
        <ComposerExpandButton />
      </Flexbox>
    );
    const leftSlot = noticeNode ? (
      <Flexbox horizontal align={'center'} className={stylex.props(styles.leftSlot).className}>
        {leftSlotContent}
      </Flexbox>
    ) : (
      leftSlotContent
    );

    const content = (
      <Flexbox
        className={stylex.props(composerHoverMarker, expand && styles.fullscreen).className}
        gap={8}
        paddingBlock={expand ? 0 : showFootnote ? '0 12px' : '0 8px'}
        style={{ display: hidden ? 'none' : undefined }}
        onDragOver={handleDragOver}
        onDrop={handleDrop}
      >
        <ChatInput
          data-testid="chat-input"
          defaultHeight={chatInputHeight || 32}
          fullscreen={expand}
          maxHeight={320}
          minHeight={36}
          resize={true}
          slashMenuRef={slashMenuRef}
          footer={
            compact ? undefined : (
              <ChatInputActionBar
                left={loadingLeftSlot ?? leftSlot}
                style={actionBarStyle ?? { paddingRight: 8 }}
                right={
                  loadingRightSlot ??
                  rightContent ?? (
                    <SendArea hideContextWindow={hasControlBar} prefix={sendAreaPrefix} />
                  )
                }
              />
            )
          }
          header={
            <Flexbox gap={0}>
              {extentHeaderContent}
              {showTypoBar && <TypoBar />}
              {contextContainerNode}
            </Flexbox>
          }
          onSizeChange={(height) => {
            updateSystemStatus({ chatInputHeight: height });
          }}
          {...inputContainerProps}
          className={cx(
            stylex.props(expand && styles.inputFullscreen).className,
            inputContainerProps?.className,
          )}
        >
          <InputEditor
            initialContent={initialContent}
            placeholder={placeholder}
            placeholderVariant={placeholderVariant}
          />
        </ChatInput>
        {controlBarSlot ?? (showControlBar && <ControlBar />)}
        {showFootnote && !expand && (
          <Center style={{ pointerEvents: 'none', zIndex: 100 }}>
            <Text className={stylex.props(styles.footnote).className} type={'secondary'}>
              {t('input.disclaimer')}
            </Text>
          </Center>
        )}
      </Flexbox>
    );

    if (expand && layoutContainerRef.current)
      return createPortal(content, layoutContainerRef.current);

    return content;
  },
);

DesktopChatInput.displayName = 'DesktopChatInput';

export default DesktopChatInput;