ChatInput.tsx 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404
  1. import React, { useState, useCallback, useEffect, useRef } from "react";
  2. import {
  3. Affix,
  4. AutoComplete,
  5. Button,
  6. Card,
  7. Dropdown,
  8. Input,
  9. type MenuProps,
  10. Select,
  11. Space,
  12. Tooltip,
  13. Typography,
  14. Tag,
  15. } from "antd";
  16. import {
  17. SendOutlined,
  18. PaperClipOutlined,
  19. DownOutlined,
  20. SearchOutlined,
  21. } from "@ant-design/icons";
  22. import type { ChatInputProps } from "../../types/chat";
  23. import PromptButtonGroup from "./PromptButtonGroup";
  24. import type { IAiModel } from "../../api/ai";
  25. import { useAppSelector } from "../../hooks";
  26. import { siteInfo } from "../../reducers/layout";
  27. import { backend, _get } from "../../request";
  28. import type { SuggestionsResponse } from "../../types/search";
  29. const { TextArea } = Input;
  30. const { Text } = Typography;
  31. // 定义建议项类型
  32. interface SuggestionOption {
  33. value: string;
  34. label: React.ReactNode;
  35. text: string;
  36. source: string;
  37. score: number;
  38. resource_type?: string;
  39. language?: string;
  40. doc_id?: string;
  41. }
  42. // 定义搜索模式类型
  43. type SearchMode = "auto" | "none" | "team" | "word" | "explain" | "title";
  44. export function ChatInput({
  45. onSend,
  46. onModelChange,
  47. disabled,
  48. placeholder,
  49. }: ChatInputProps) {
  50. const [inputValue, setInputValue] = useState("");
  51. const [selectedModel, setSelectedModel] = useState<string>("");
  52. const [models, setModels] = useState<IAiModel[]>();
  53. const [searchMode, setSearchMode] = useState<SearchMode>("auto");
  54. const [suggestions, setSuggestions] = useState<SuggestionOption[]>([]);
  55. const [loading, setLoading] = useState(false);
  56. const site = useAppSelector(siteInfo);
  57. // 使用 ref 来防止过于频繁的请求
  58. const abortControllerRef = useRef<AbortController | null>(null);
  59. const debounceTimerRef = useRef<NodeJS.Timeout | null>(null);
  60. useEffect(() => {
  61. const allModels = site?.settings?.models?.chat ?? [];
  62. setModels(allModels);
  63. if (
  64. site?.settings?.models?.chat &&
  65. site?.settings?.models?.chat.length > 0
  66. ) {
  67. const modelId = site?.settings?.models?.chat[0].uid;
  68. setSelectedModel(modelId);
  69. onModelChange && onModelChange(allModels?.find((m) => m.uid === modelId));
  70. }
  71. }, [onModelChange, site?.settings?.models?.chat]);
  72. // 获取搜索建议
  73. const fetchSuggestions = useCallback(
  74. async (query: string) => {
  75. // 取消之前的请求
  76. if (abortControllerRef.current) {
  77. abortControllerRef.current.abort();
  78. }
  79. // 如果查询为空或搜索模式为 none,清空建议
  80. if (!query.trim() || searchMode === "none") {
  81. setSuggestions([]);
  82. return;
  83. }
  84. // 创建新的 AbortController
  85. abortControllerRef.current = new AbortController();
  86. setLoading(true);
  87. try {
  88. // 根据搜索模式确定查询字段
  89. let fields: string | undefined;
  90. switch (searchMode) {
  91. case "title":
  92. fields = "title";
  93. break;
  94. case "team":
  95. case "word":
  96. case "explain":
  97. fields = "title,content";
  98. break;
  99. case "auto":
  100. default:
  101. // 不指定 fields,查询所有字段
  102. fields = undefined;
  103. }
  104. // 构建查询参数
  105. const params = new URLSearchParams({
  106. q: query,
  107. limit: "10",
  108. });
  109. if (fields) {
  110. params.append("fields", fields);
  111. }
  112. // 发起请求
  113. const url = `/v3/search-suggest?${params.toString()}`;
  114. // 发起请求
  115. const response = await fetch(backend(url), {
  116. signal: abortControllerRef.current.signal,
  117. });
  118. if (!response.ok) {
  119. throw new Error("搜索建议请求失败");
  120. }
  121. const data: SuggestionsResponse = await response.json();
  122. if (data.success && data.data.suggestions) {
  123. // 转换为 AutoComplete 选项格式
  124. const options: SuggestionOption[] = data.data.suggestions.map(
  125. (item: any) => ({
  126. value: item.text,
  127. label: renderSuggestionItem(item),
  128. text: item.text,
  129. source: item.source,
  130. score: item.score,
  131. resource_type: item.resource_type,
  132. language: item.language,
  133. doc_id: item.doc_id,
  134. })
  135. );
  136. setSuggestions(options);
  137. } else {
  138. setSuggestions([]);
  139. }
  140. } catch (error: any) {
  141. // 忽略取消的请求
  142. if (error.name === "AbortError") {
  143. return;
  144. }
  145. console.error("获取搜索建议失败:", error);
  146. setSuggestions([]);
  147. } finally {
  148. setLoading(false);
  149. }
  150. },
  151. [searchMode]
  152. );
  153. // 渲染建议项
  154. const renderSuggestionItem = (item: any) => {
  155. // 来源标签颜色映射
  156. const sourceColors: Record<string, string> = {
  157. title: "blue",
  158. content: "green",
  159. page_refs: "orange",
  160. };
  161. // 语言标签
  162. const languageLabels: Record<string, string> = {
  163. pali: "巴利文",
  164. zh: "中文",
  165. en: "英文",
  166. };
  167. return (
  168. <div style={{ display: "flex", alignItems: "center", gap: "8px" }}>
  169. <span style={{ flex: 1 }}>{item.text}</span>
  170. <Space size={4}>
  171. {item.source && (
  172. <Tag
  173. color={sourceColors[item.source] || "default"}
  174. style={{ margin: 0, fontSize: "12px" }}
  175. >
  176. {item.source}
  177. </Tag>
  178. )}
  179. {item.language && (
  180. <Tag style={{ margin: 0, fontSize: "12px" }}>
  181. {languageLabels[item.language] || item.language}
  182. </Tag>
  183. )}
  184. </Space>
  185. </div>
  186. );
  187. };
  188. // 处理输入变化(带防抖)
  189. const handleInputChange = useCallback(
  190. (value: string) => {
  191. setInputValue(value);
  192. // 清除之前的定时器
  193. if (debounceTimerRef.current) {
  194. clearTimeout(debounceTimerRef.current);
  195. }
  196. // 如果输入为空,直接清空建议
  197. if (!value.trim()) {
  198. setSuggestions([]);
  199. return;
  200. }
  201. // 设置新的防抖定时器(300ms)
  202. debounceTimerRef.current = setTimeout(() => {
  203. fetchSuggestions(value);
  204. }, 300);
  205. },
  206. [fetchSuggestions]
  207. );
  208. // 处理选择建议项
  209. const handleSelect = useCallback(
  210. (value: string, _option: SuggestionOption) => {
  211. setInputValue(value);
  212. // 选择后清空建议列表
  213. setSuggestions([]);
  214. },
  215. []
  216. );
  217. const handleSend = useCallback(() => {
  218. if (!inputValue.trim() || disabled) return;
  219. onSend(inputValue.trim());
  220. setInputValue("");
  221. setSuggestions([]);
  222. }, [inputValue, disabled, onSend]);
  223. const handleKeyPress = useCallback(
  224. (e: React.KeyboardEvent<HTMLTextAreaElement>) => {
  225. if (e.key === "Enter" && !e.shiftKey) {
  226. e.preventDefault();
  227. handleSend();
  228. }
  229. },
  230. [handleSend]
  231. );
  232. const modelMenu: MenuProps = {
  233. selectedKeys: [selectedModel],
  234. onClick: ({ key }) => {
  235. console.log("setSelectedModel", key);
  236. setSelectedModel(key);
  237. onModelChange && onModelChange(models?.find((m) => m.uid === key));
  238. },
  239. items: models?.map((model) => ({
  240. key: model.uid,
  241. label: model.name,
  242. })),
  243. };
  244. const handleSearchModeChange = (value: SearchMode) => {
  245. setSearchMode(value);
  246. // 模式改变时,如果有输入内容,重新获取建议
  247. if (inputValue.trim() && value !== "none") {
  248. fetchSuggestions(inputValue);
  249. } else {
  250. setSuggestions([]);
  251. }
  252. };
  253. // 组件卸载时清理
  254. useEffect(() => {
  255. return () => {
  256. if (abortControllerRef.current) {
  257. abortControllerRef.current.abort();
  258. }
  259. if (debounceTimerRef.current) {
  260. clearTimeout(debounceTimerRef.current);
  261. }
  262. };
  263. }, []);
  264. return (
  265. <Affix offsetBottom={10}>
  266. <Card style={{ borderRadius: "10px", borderColor: "#d9d9d9" }}>
  267. <div style={{ maxWidth: "1200px", margin: "0 auto" }}>
  268. <div style={{ display: "flex", marginBottom: "8px", gap: "8px" }}>
  269. <Space>
  270. <SearchOutlined />
  271. <Select
  272. placement="topLeft"
  273. value={searchMode}
  274. style={{ width: 120 }}
  275. onChange={handleSearchModeChange}
  276. options={[
  277. {
  278. value: "auto",
  279. label: (
  280. <div>
  281. <div>{"自动"}</div>
  282. <div>
  283. <Text type="secondary" style={{ fontSize: "85%" }}>
  284. 关键词+语义模糊搜索
  285. </Text>
  286. </div>
  287. </div>
  288. ),
  289. },
  290. {
  291. value: "none",
  292. label: "关闭",
  293. },
  294. {
  295. value: "team",
  296. label: "术语百科",
  297. },
  298. {
  299. value: "word",
  300. label: "词义辨析",
  301. },
  302. {
  303. value: "explain",
  304. label: "经文解析",
  305. },
  306. {
  307. value: "title",
  308. label: "标题搜索",
  309. },
  310. ]}
  311. />
  312. </Space>
  313. <AutoComplete
  314. style={{ flex: 1 }}
  315. placement="topLeft"
  316. value={inputValue}
  317. options={suggestions}
  318. onSelect={handleSelect}
  319. onChange={handleInputChange}
  320. notFoundContent={loading ? "搜索中..." : null}
  321. disabled={disabled}
  322. >
  323. <TextArea
  324. onKeyPress={handleKeyPress}
  325. placeholder={
  326. placeholder || "提出你的问题,如:总结下面的内容..."
  327. }
  328. autoSize={{ minRows: 1, maxRows: 6 }}
  329. style={{ resize: "none", paddingRight: "48px" }}
  330. />
  331. </AutoComplete>
  332. </div>
  333. <div
  334. style={{
  335. display: "flex",
  336. justifyContent: "space-between",
  337. alignItems: "center",
  338. }}
  339. >
  340. <Space>
  341. <Tooltip title="附加文件">
  342. <Button size="small" type="text" icon={<PaperClipOutlined />} />
  343. </Tooltip>
  344. <PromptButtonGroup onText={setInputValue} />
  345. </Space>
  346. <Space>
  347. <Dropdown
  348. placement="topLeft"
  349. menu={modelMenu}
  350. trigger={["click"]}
  351. >
  352. <Button size="small" type="text">
  353. {models?.find((m) => m.uid === selectedModel)?.name}
  354. <DownOutlined />
  355. </Button>
  356. </Dropdown>
  357. <Button
  358. type="primary"
  359. icon={<SendOutlined />}
  360. onClick={handleSend}
  361. disabled={!inputValue.trim() || disabled}
  362. />
  363. </Space>
  364. </div>
  365. </div>
  366. </Card>
  367. </Affix>
  368. );
  369. }