index.tsx 7.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258
  1. import { View, ScrollView } from "@tarojs/components";
  2. import NavBarNormal from "@/components/NavBarNormal/index";
  3. import PageCustom from "@/components/page-custom/index";
  4. import { useDidShow, useRouter, useUnload } from "@tarojs/taro";
  5. import ChatMessage from "@/components/chat-message";
  6. import InputBar from "./components/InputBar";
  7. import { useEffect, useState } from "react";
  8. import { useTextChat } from "@/store/textChatStore";
  9. import { formatMessageTime } from "@/utils/timeUtils";
  10. import ChatGreeting from "./components/ChatGreeting";
  11. import PersonalCard from "./components/PersonalCard";
  12. import ButtonEnableStreamVoice from "./components/OptionButtons/ButtonEnableStreamVoice";
  13. import RecommendQuestions from "./components/RecommendQuestions";
  14. import { usePersistentState } from "@/hooks/usePersistentState";
  15. import style from './index.module.less'
  16. // 导入我们抽离的 hooks 和常量
  17. import {
  18. useChatMessages,
  19. useChatScrollManager,
  20. useChatUI,
  21. useChatAgent,
  22. } from "./hooks";
  23. import { useChatInput } from "./components/InputBar/useChatInput";
  24. export default function Index() {
  25. const router = useRouter();
  26. const { agentId, isVisitor } = router.params;
  27. if (!agentId) {
  28. return <View>没有相应的智能体</View>;
  29. }
  30. // 使用抽离的 hooks
  31. const { agent } = useChatAgent(agentId, isVisitor);
  32. const {
  33. historyList,
  34. groupedMessages,
  35. messagesLength,
  36. loadMore,
  37. pageIndex,
  38. mutate,
  39. resetAndLoadFirstPage,
  40. resetAndClearData
  41. } = useChatMessages(agentId, isVisitor);
  42. // const loadMoreCallback = isNewChat ? null : loadMore
  43. // 获取原始历史消息列表长度(用于UI状态判断)
  44. const rawHistoryListLength = historyList.length;
  45. const {
  46. scrollViewRef,
  47. scrollTop,
  48. keyboardHeight,
  49. marginTopOffset,
  50. handleScrollToUpper,
  51. handleTouchMove,
  52. handleScrollToLower,
  53. } = useChatScrollManager(messagesLength, pageIndex, loadMore);
  54. // InputBar 相关状态
  55. const [isVoice, setIsVoice] = useState(false);
  56. const [disabled, setDisabled] = useState(false);
  57. const [contextMenuVisible, setContextMenuVisible] = useState(false);
  58. // 获取当前消息列表长度
  59. const currentMessageListLength = useTextChat((state) => state.list.length);
  60. const isNewChat = useTextChat((state) => state.isNewChat);
  61. const messageStopHandle = useTextChat((state) => state.messageStopHandle);
  62. const { destroy, genSessionId, clearList } = useTextChat();
  63. const {
  64. showWelcome,
  65. haveBg,
  66. inputContainerHeight,
  67. inputContainerBottomOffset,
  68. setShowWelcome,
  69. getBgContent,
  70. createNavLeftRenderer,
  71. } = useChatUI(agent, rawHistoryListLength, currentMessageListLength, isNewChat);
  72. const [streamVoiceEnable, setStreamVoiceEnable] = usePersistentState(
  73. "streamVoiceEnable",
  74. false
  75. );
  76. // 统一的聊天输入逻辑 - 只在主组件中实例化一次
  77. const chatInputActions = useChatInput({
  78. agent,
  79. enableOutputAudioStream: streamVoiceEnable,
  80. setShowWelcome,
  81. setIsVoice,
  82. setDisabled,
  83. historyList,
  84. });
  85. // 首次进入聊天生成 session id
  86. useEffect(() => {
  87. genSessionId();
  88. // 重新拉取第一页数据,
  89. resetAndLoadFirstPage()
  90. }, [genSessionId]);
  91. // 页面卸载时清理
  92. useUnload(() => {
  93. destroy();
  94. });
  95. // 加载更多的处理函数(已经在 useChatScrollManager 中处理)
  96. const onScrollToUpper = handleScrollToUpper;
  97. // const PersonalCardWrap = ()=> <PersonalCard />
  98. // 使用工厂函数创建导航栏左侧渲染器
  99. const renderNavLeft = createNavLeftRenderer(PersonalCard, contextMenuVisible, ()=> {
  100. console.log('clear chat')
  101. messageStopHandle?.();
  102. clearList()
  103. resetAndClearData()
  104. }, (menuVisible: boolean) => {
  105. setContextMenuVisible(menuVisible)
  106. });
  107. // 页面点击时关闭清除上下文菜单
  108. const handlePageClick = () => {
  109. setContextMenuVisible(false)
  110. }
  111. return (
  112. <PageCustom
  113. fullPage
  114. style={{ overflow: "hidden" }}
  115. styleBg={getBgContent()}
  116. onClick={handlePageClick}
  117. >
  118. <NavBarNormal blur leftColumn={renderNavLeft}>
  119. {/* <>{`${isNewChat ? 'isnew': 'notnew'}`}--</> */}
  120. </NavBarNormal>
  121. <View
  122. className="flex flex-col w-full h-full relative z-10 flex-1"
  123. style={{ top: `${marginTopOffset}px` }}
  124. >
  125. <ScrollView
  126. ref={scrollViewRef}
  127. scrollY
  128. id="scrollView"
  129. style={{
  130. flex: 1,
  131. height: "1px", // 高度自适应
  132. }}
  133. // scrollTop={scrollTop}
  134. scrollWithAnimation
  135. onScrollToUpper={onScrollToUpper}
  136. onScrollToLower={handleScrollToLower}
  137. className="scale-y-[-1]"
  138. >
  139. <View className="pb-40 pt-8 scale-y-[-1]">
  140. {agent && (
  141. <RecommendQuestions
  142. enableOutputAudioStream={streamVoiceEnable}
  143. agent={agent}
  144. chatInputActions={chatInputActions}
  145. />
  146. )}
  147. </View>
  148. <View
  149. id="messageList"
  150. className="flex flex-col gap-16 px-18 scale-y-[-1] min-h-full"
  151. onTouchMove={handleTouchMove}
  152. >
  153. {isNewChat && <View className="text-white-70 text-12 leading-20 text-center pt-22 scale-y-[-1]">聊聊新话题</View>}
  154. {showWelcome && <ChatGreeting agent={agent} chatInputActions={chatInputActions} />}
  155. {groupedMessages.map((group, groupIndex) => {
  156. return (
  157. <View key={groupIndex} className="flex flex-col gap-16">
  158. <View
  159. className={`text-12 leading-20 block text-center w-full ${
  160. haveBg
  161. ? "text-white-70"
  162. : "text-black-25"
  163. }`}
  164. >
  165. {formatMessageTime(group.dt)}
  166. </View>
  167. {group.list.map((message) => {
  168. const reasoningContent =
  169. (message as any).reasoningContent || "";
  170. return (
  171. <ChatMessage
  172. key={message.msgUk}
  173. textReasoning={reasoningContent}
  174. agent={agent}
  175. role={message.role}
  176. text={message.content}
  177. message={message}
  178. mutate={mutate as any}
  179. />
  180. );
  181. })}
  182. </View>
  183. );
  184. })}
  185. </View>
  186. </ScrollView>
  187. <View
  188. className="w-full h-60"
  189. style={{
  190. height: inputContainerHeight,
  191. }}
  192. ></View>
  193. {/* ${keyboardHeight <= 0 ? 'transition-[bottom] delay-300' : ''} */}
  194. <View
  195. className={`bottom-bar px-16 pt-12 z-50`}
  196. id="inputContainer"
  197. style={{
  198. bottom: `${keyboardHeight + inputContainerBottomOffset}px`,
  199. }}
  200. >
  201. <View className="bg-[#F5FAFF]">
  202. {agent && (
  203. <View className="flex flex-col w-full gap-8">
  204. <View>
  205. <ButtonEnableStreamVoice
  206. setEnable={setStreamVoiceEnable}
  207. enable={streamVoiceEnable}
  208. />
  209. </View>
  210. <InputBar
  211. enableOutputAudioStream={streamVoiceEnable}
  212. agent={agent}
  213. // histories={historyList}
  214. setShowWelcome={setShowWelcome}
  215. chatInputActions={chatInputActions}
  216. isVoice={isVoice}
  217. setIsVoice={setIsVoice}
  218. disabled={disabled}
  219. />
  220. </View>
  221. )}
  222. <View className={`${style.aiTips} ${keyboardHeight > 0 ? 'opacity-0': ''} `}>内容由AI生成,仅供参考</View>
  223. </View>
  224. </View>
  225. </View>
  226. </PageCustom>
  227. );
  228. }