LinkMedChat.vue
33.3 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
<template>
<div class="linkmed-chat">
<!-- 主聊天区域 -->
<div class="chat-main" :class="{ 'with-sidebar': showReferenceSidebar }">
<div class="chat-messages" ref="messagesContainer" @scroll="handleScroll">
<!-- 流式回答状态提示 -->
<div v-if="chatApiStore.streamingError" class="websocket-error">
<i class="fas fa-exclamation-triangle"></i>
<span>{{ chatApiStore.streamingError }}</span>
</div>
<div v-for="message in chatApiStore.messages" :key="message.questionId">
<!-- 用户消息 -->
<div class="message user">
<div class="message-content">
<div
class="message-text"
v-html="formatMessage(message.question)"
></div>
<div class="message-tools">
<img
src="/fuzhi.svg"
alt="复制"
class="icon-svg"
:title="t('chat.copy')"
@click="handleCopy(message.question)"
/>
</div>
</div>
</div>
<!-- AI回答 -->
<div
v-for="answer in message.answers"
:key="answer.id"
class="message assistant"
>
<div class="message-content">
<!-- 错误状态 -->
<div
v-if="streamingError && answer.status === 'thinking'"
class="message-text error-message"
>
<i class="fas fa-warning"></i>
{{ streamingError }}
</div>
<!-- AI思考状态 -->
<div v-else-if="answer.status === 'thinking'" class="ai-thinking">
<div class="thinking-dots">
<span></span>
<span></span>
<span></span>
</div>
<span class="thinking-text">{{
$t("agent.thinking") || "AI正在思考中..."
}}</span>
</div>
<!-- 打字机效果显示回答 -->
<div
v-else-if="answer.status === 'typing'"
class="message-text typewriter"
>
<span
class="typewriter-content"
v-html="formatMarkdownContent(answer.answerContent)"
></span>
</div>
<!-- 错误状态 -->
<div
v-else-if="answer.status === 'error'"
class="message-text error-message"
>
<i class="fas fa-warning"></i>
{{ answer.answerContent }}
</div>
<!-- 正常显示回答 -->
<div
v-else
class="message-text"
v-html="formatMarkdownContent(answer.answerContent)"
style="display: block; white-space: normal"
></div>
<!-- 工具图标 -->
<div
class="message-tools"
v-if="
answer.answerContent &&
answer.status !== 'thinking' &&
answer.status !== 'typing' &&
answer.status !== 'error'
"
>
<img
src="/bianji.svg"
alt="生成文档并编辑"
class="icon-svg"
:class="{ disabled: !isAnswerCompleted(answer) }"
:title="t('chat.generateDocument')"
@click="handleSaveAndEdit(message, answer)"
/>
<img
src="/fuzhi.svg"
alt="复制"
class="icon-svg"
:class="{ disabled: !isAnswerCompleted(answer) }"
:title="t('chat.copy')"
@click="handleCopyAnswer(answer)"
/>
</div>
</div>
</div>
</div>
</div>
<div class="chat-input-area">
<CentralInput
ref="chatInputRef"
:loading="loading"
@submit="handleSubmit"
@stop="handleStop"
@tool-click="handleToolClick"
/>
</div>
</div>
<!-- 右侧参考文献边栏 -->
<div
v-if="showReferenceSidebar"
class="reference-sidebar"
:class="{ 'sidebar-visible': showReferenceSidebar }"
>
<div class="sidebar-header">
<div>{{ t("chat.references") }}</div>
<button
class="close-btn"
@click="showReferenceSidebar = false"
:title="t('chat.closeReferences')"
>
<i class="fas fa-close"></i>
</button>
</div>
<div class="sidebar-content">
<div
v-for="reference in currentReferences"
:key="reference.id"
class="reference-item"
>
<div class="reference-title">
{{ reference.id }}.{{ reference.title }}
</div>
<div class="reference-authors">{{ reference.authors }}</div>
<div class="reference-journal">
{{ reference.journal }}. {{ reference.year }};{{
reference.volume
}}({{ reference.issue }}):{{ reference.pages }}.
</div>
<div class="reference-doi">
<a
:href="`https://doi.org/${reference.doi}`"
target="_blank"
rel="noopener noreferrer"
class="doi-link"
>
DOI: {{ reference.doi }}
</a>
</div>
<div class="reference-tags">
<span
v-for="tag in reference.tags"
:key="tag"
class="reference-tag"
>
{{ tag }}
</span>
</div>
</div>
</div>
</div>
</div>
</template>
<script setup lang="ts">
import { ref, nextTick, computed, watch, onMounted, onUnmounted } from "vue";
import { useI18n } from "vue-i18n";
import { ElMessage, ElLoading } from "element-plus";
import { useRouter } from "vue-router";
import { useChatApiStore } from "@/stores/chatApi";
import { useUserStore } from "@/stores/user";
import { useAppStore } from "@/stores/app";
import CentralInput from "@/components/WorkspaceWelcome/CentralInput.vue";
import { markdownToHtml, ensureKatexReady } from "@/utils/renderMarkdown";
import {
apiCreateDraftFromQuestion,
apiSaveDraftToKnowledge,
} from "@/api/drafts";
import { getFiles, createFolder, getFileContent } from "@/api/files";
import { triggerNewbieTask } from "@/utils/newbieTask";
// 引入 KaTeX 样式以支持数学公式渲染(仅样式,JS 通过 ensureKatexReady 按需加载)
import "katex/dist/katex.min.css";
const { t } = useI18n();
// Props
interface Props {
currentSession?: any;
initialMessage?: string;
}
const props = defineProps<Props>();
// Emits
const emit = defineEmits<{
(e: "session-created", session: any): void;
(e: "message-sent", message: any): void;
}>();
const router = useRouter();
const chatApiStore = useChatApiStore();
const userStore = useUserStore();
const messagesContainer = ref<HTMLElement | null>(null);
const chatInputRef = ref<InstanceType<typeof CentralInput> | null>(null);
// 状态判断:是否正在发送或接收消息
const loading = computed(() => {
return chatApiStore.aiThinking || chatApiStore.streamingAnswer || false;
});
const showReferenceSidebar = ref(false);
const currentReferences = ref<any[]>([]);
const isUserAtBottom = ref(true); // 用户是否在底部
// Computed
const streamingError = computed(() => chatApiStore.streamingError);
// 按需加载 KaTeX:进入 LinkMed Chat 时才加载 katex 相关 JS
onMounted(() => {
ensureKatexReady().catch(() => {
// 加载失败时降级为普通 Markdown 渲染
});
});
// 格式化消息
const formatMessage = (content: string) => {
return content.replace(/\n/g, "<br>");
};
// 格式化 Markdown 内容
const formatMarkdownContent = (content: string) => {
if (!content) return "";
try {
return markdownToHtml(content);
} catch (error) {
console.error("Markdown 渲染失败:", error);
return content.replace(/\n/g, "<br>");
}
};
// 检查回答是否已完成
const isAnswerCompleted = (answer: any) => {
if (!answer.status) return true;
return answer.status === "completed";
};
// 处理提交
const handleSubmit = async (content: string) => {
if (!content || !content.trim() || loading.value) return;
try {
loading.value = true;
// 立即添加用户消息
const tempQuestionId = `temp_${Date.now()}`;
chatApiStore.addMessage({
questionId: tempQuestionId,
question: content.trim(),
questionCreatedAt: new Date().toISOString(),
answers: [
{
id: `answer_${Date.now()}`,
questionId: tempQuestionId,
answerContent: "",
createdAt: new Date().toISOString(),
status: "thinking",
},
],
});
nextTick(() => scrollToBottom());
// 如果没有当前会话,创建新会话
if (!props.currentSession) {
// 使用用户输入的问题作为会话名称(完整内容)
const sessionResult = await chatApiStore.createSession(content.trim());
if (!sessionResult.success || !sessionResult.data) {
ElMessage.error(t("chat.createSessionFailed"));
return;
}
const session = sessionResult.data;
await chatApiStore.selectSession({ session, fetchMessages: false });
emit("session-created", session);
// 发送消息
const questionResult = await chatApiStore.sendMessage({
sessionId: session.sessionId || session.id,
question: content.trim(),
});
if (questionResult.success) {
const realQuestionId = questionResult.data?.questionId;
if (realQuestionId) {
chatApiStore.updateMessageId({
oldId: tempQuestionId,
newId: realQuestionId,
});
}
emit("message-sent", questionResult.data);
} else {
ElMessage.error(t("chat.sendMessageFailed"));
}
} else {
// 使用现有会话发送消息
const result = await chatApiStore.sendMessage({
sessionId: props.currentSession.sessionId || props.currentSession.id,
question: content.trim(),
});
if (result.success) {
const realQuestionId = result.data?.questionId;
if (realQuestionId) {
chatApiStore.updateMessageId({
oldId: tempQuestionId,
newId: realQuestionId,
});
}
emit("message-sent", result.data);
} else {
ElMessage.error(t("chat.sendMessageFailed"));
}
}
} catch (error) {
console.error("发送消息失败:", error);
ElMessage.error(t("chat.sendMessageError"));
}
};
const handleStop = () => {
chatApiStore.closeAllEventSources();
ElMessage.info(t("chat.stopStreaming") || "已中止当前生成");
};
// 处理工具点击
const handleToolClick = (tool: string) => {
console.log("工具按钮点击:", tool);
ElMessage.info(`${tool} ${t("chat.toolFunctionDeveloping")}`);
};
// 处理复制
const handleCopy = async (content: string) => {
try {
if (!content) {
ElMessage.warning(t("chat.noContentToCopy"));
return;
}
await navigator.clipboard.writeText(content);
ElMessage.success(t("chat.contentCopied"));
} catch (error) {
console.error("复制失败:", error);
ElMessage.error(t("chat.copyFailed"));
}
};
// 处理复制回答
const handleCopyAnswer = async (answer: any) => {
await handleCopy(answer.answerContent);
};
// 处理保存并编辑
const handleSaveAndEdit = async (message: any, answer: any) => {
try {
console.log("LinkMedChat: 处理保存并编辑", { message, answer });
if (!answer.answerContent) {
ElMessage.warning(t("chat.noContentToSave"));
return;
}
// 检查回答状态
if (answer.status === "thinking") {
ElMessage.warning(t("chat.aiThinking"));
return;
}
if (answer.status === "typing") {
ElMessage.warning(t("chat.generatingAnswer"));
return;
}
if (answer.status === "error") {
ElMessage.warning(t("chat.answerError"));
return;
}
// 只有当状态为 completed 或者没有状态字段时才允许保存
if (answer.status && answer.status !== "completed") {
ElMessage.warning(t("chat.answerNotCompleted"));
return;
}
if (!message.questionId) {
ElMessage.error(t("chat.missingQuestionId"));
return;
}
if (!props.currentSession) {
ElMessage.error(t("chat.missingSessionInfo"));
return;
}
try {
// 1. 获取文件名 (前20个字符)
let title = message.question || "未命名文档";
title = title.replace(/\n/g, " ").substring(0, 20).trim();
if (!title) title = "未命名文档";
// 2. 检查并创建“草稿”目录
let draftFolderId: number | undefined;
const rootFilesRes = await getFiles();
if (
rootFilesRes.status === 200 &&
rootFilesRes.data
) {
const items = Array.isArray(rootFilesRes.data) ? rootFilesRes.data : (rootFilesRes.data.items || []);
const draftFolder = items.find(
(item: any) =>
(item.type === "folder" || item.isFolder) && item.name === "草稿",
);
if (draftFolder) {
draftFolderId = draftFolder.id;
}
}
if (!draftFolderId) {
const createFolderRes = await createFolder({ name: "草稿" });
if (createFolderRes.status === 200 && createFolderRes.data) {
draftFolderId = createFolderRes.data.id;
}
}
// 3. 调用保存API创建草稿
const response = await apiCreateDraftFromQuestion(message.questionId, {
title,
});
console.log("保存响应:", response);
if (response.status === 200 && response.data) {
const draftInfo = response.data;
const draftContent = draftInfo.content || "";
// 4. 将草稿保存到“草稿”目录
const saveRes = await apiSaveDraftToKnowledge(draftInfo.id, {
parentId: draftFolderId,
fileName: title + ".md",
});
console.log("保存到知识库响应:", saveRes);
if (saveRes.status === 200 && saveRes.data) {
const fileInfo = saveRes.data;
// 5. 添加到对话框引用 (LinkMedChat 目前使用 CentralInput,暂时不直接支持显示引用)
// 但我们可以通过 store 或者其他方式告知输入框
// TODO: 如果 CentralInput 支持显示引用,可以在这里添加
// 6. 跳转到工作台编辑器
await openInWorkspace({
id: fileInfo.id,
title: fileInfo.name || fileInfo.fileName,
isDraft: false,
preloadContent: draftContent, // 传递预抓取的内容
});
// 7. 触发全局事件和状态信号,刷新文件列表
window.dispatchEvent(
new CustomEvent("refresh-file-hierarchy", {
detail: { folderId: draftFolderId },
}),
);
const appStore = useAppStore();
appStore.triggerRefreshFileHierarchy(draftFolderId);
ElMessage.success("已保存到草稿目录");
// 触发新手任务:生成/编辑文档
triggerNewbieTask("doc_generate_edit");
} else {
throw new Error("保存到目录失败");
}
} else {
throw new Error((response as any)?.data?.message || "创建草稿失败");
}
} catch (apiError: any) {
console.error("API调用失败:", apiError);
if (!apiError.response && apiError.request) {
ElMessage.error("网络请求失败,请检查网络连接");
} else if (!apiError.response && !apiError.request) {
ElMessage.error(apiError.message || "保存失败");
}
}
} catch (error) {
console.error("保存并编辑失败:", error);
ElMessage.error(t("chat.operationFailed"));
}
};
// 在工作台编辑器中打开文件
const openInWorkspace = async (fileInfo: any) => {
// 显示加载状态
const loading = ElLoading.service({
lock: true,
text: t("chat.preparingDocument"),
background: "rgba(0, 0, 0, 0.7)",
});
try {
console.log("准备在工作台中打开文件:", fileInfo);
// 先下载文件内容,确保文件可以正常访问
let fileContent = fileInfo.preloadContent || "";
try {
if (!fileContent) {
console.log("开始下载文件内容,fileId:", fileInfo.id);
// 统一使用常规文件 API
const contentResponse = await getFileContent(fileInfo.id);
fileContent = contentResponse.data;
console.log("文件内容下载成功,内容长度:", fileContent.length);
} else {
console.log("使用预传递的文件内容,内容长度:", fileContent.length);
}
} catch (downloadError) {
console.error("下载文件内容失败:", downloadError);
// 如果下载失败,仍然尝试跳转,让工作台组件自己处理
ElMessage.warning(t("chat.filePreloadFailed"));
}
// 构建跳转参数,包含文件内容
const params: any = {
fileId: fileInfo.id,
fileName: fileInfo.title || fileInfo.name,
fileType: "md", // 默认为 markdown
isChatAnswer: fileInfo.isDraft === false ? "false" : "true", // 明确标记是否为智能体回答文件(草稿)
};
// 如果成功获取到内容,也传递过去(可选)
if (fileContent) {
params.preloadContent = encodeURIComponent(fileContent);
}
// 跳转到工作台页面,并传递文件参数
await performRouterNavigation(params);
} catch (error) {
console.error("打开工作台编辑器失败:", error);
ElMessage.error(t("chat.openEditorFailed"));
} finally {
loading.close();
}
};
// 执行路由跳转的辅助方法
const performRouterNavigation = async (params: any) => {
try {
console.log("开始执行路由跳转,参数:", params);
// 首先尝试使用路由名称跳转
try {
await router.push({
name: "Workspace",
query: params,
});
console.log("使用路由名称跳转成功");
return;
} catch (nameError) {
console.warn("路由名称跳转失败:", nameError);
}
// 如果路由名称失败,尝试使用路径跳转
try {
await router.push({
path: "/app/workspace",
query: params,
});
console.log("使用路径跳转成功");
return;
} catch (pathError) {
console.warn("路径跳转失败:", pathError);
}
// 尝试其他可能的路径
const possiblePaths = ["/workspace", "/Workspace", "/app/Workspace"];
for (const path of possiblePaths) {
try {
await router.push({
path: path,
query: params,
});
console.log(`使用路径 ${path} 跳转成功`);
return;
} catch (error) {
console.warn(`路径 ${path} 跳转失败:`, error);
}
}
// 如果所有Vue Router方式都失败,显示错误信息
console.error("所有路由跳转方式都失败");
ElMessage.error(t("chat.cannotNavigateToWorkspace"));
// 可选:提供手动跳转的提示
const queryString = new URLSearchParams(params).toString();
const targetUrl = `#/app/workspace?${queryString}`;
console.log("如需手动跳转,请访问:", targetUrl);
} catch (error) {
console.error("路由跳转过程中发生错误:", error);
ElMessage.error(t("chat.navigationFailed"));
}
};
// 检查用户是否在底部
const checkIfUserAtBottom = () => {
const container = messagesContainer.value;
if (!container) return true;
const threshold = 50; // 阈值,距离底部50px内认为在底部
const distanceFromBottom =
container.scrollHeight - container.scrollTop - container.clientHeight;
return distanceFromBottom <= threshold;
};
// 处理滚动事件
const handleScroll = () => {
isUserAtBottom.value = checkIfUserAtBottom();
};
// 滚动到底部
const scrollToBottom = (smooth = true) => {
nextTick(() => {
const container = messagesContainer.value;
if (container) {
container.scrollTo({
top: container.scrollHeight,
behavior: smooth ? "smooth" : "auto",
});
isUserAtBottom.value = true;
}
});
};
// 监听消息变化,智能滚动
watch(
() => chatApiStore.messages,
() => {
nextTick(() => {
// 只有用户在底部时才自动滚动
if (isUserAtBottom.value) {
scrollToBottom();
}
});
},
{ deep: true },
);
onMounted(() => {
// 设置用户ID
if (userStore.userInfo?.id) {
chatApiStore.setUserId(userStore.userInfo.id.toString());
}
// 如果有初始消息,自动发送
if (props.initialMessage) {
console.log("LinkMed: 收到初始消息,自动发送:", props.initialMessage);
nextTick(() => {
handleSubmit(props.initialMessage!);
});
}
});
</script>
<style lang="scss" scoped>
.linkmed-chat {
display: flex;
flex-direction: row;
height: 100vh;
width: 100%;
position: relative;
}
/* 主聊天区域 */
.chat-main {
display: flex;
flex-direction: column;
align-items: center;
height: 100vh;
width: 100%;
&.with-sidebar {
width: calc(100% - 680px);
}
}
.chat-messages {
flex: 1;
overflow-y: auto;
padding: 16px;
display: flex;
flex-direction: column;
gap: 16px;
background: var(--color-bg, #141518);
width: 100%;
max-width: 800px;
min-height: 0;
/* 隐藏滚动条 */
&::-webkit-scrollbar {
width: 0;
display: none;
}
/* Firefox */
scrollbar-width: none;
/* IE and Edge */
-ms-overflow-style: none;
}
.chat-input-area {
padding: 16px;
background: transparent;
flex-shrink: 0;
display: flex;
justify-content: center;
width: 100%;
max-width: 800px;
margin: 0 auto;
}
/* 消息样式 */
.message {
margin-bottom: 16px;
&.user {
display: flex;
flex-direction: column;
align-items: flex-end;
.message-content {
text-align: right;
}
.message-text {
padding: 12px 16px;
background: var(--color-card);
color: var(--user-question-text);
border-radius: 8px;
line-height: 1.5;
white-space: pre-wrap;
word-break: break-word;
max-width: 100%;
word-wrap: break-word;
font-size: 14px;
transition: background-color 0.2s ease;
}
}
&.assistant {
display: flex;
flex-direction: column;
align-items: flex-start;
.message-content {
text-align: left;
position: relative;
width: 100%;
}
.message-text {
background: var(--ai-answer-bg);
color: var(--ai-answer-text);
border: 1px solid transparent;
border-radius: 8px;
line-height: 1.5;
white-space: pre-wrap;
word-break: break-word;
max-width: 100%;
word-wrap: break-word;
font-size: 14px;
transition: border-color 0.2s ease;
}
}
}
.message-content {
position: relative;
}
/* AI 思考状态 */
.ai-thinking {
display: flex;
align-items: center;
gap: 8px;
color: var(--color-text-secondary, #999);
}
.thinking-dots {
display: flex;
gap: 4px;
span {
width: 8px;
height: 8px;
border-radius: 50%;
background: var(--color-primary, #409eff);
animation: thinking-dot 1.4s infinite ease-in-out;
&:nth-child(1) {
animation-delay: -0.32s;
}
&:nth-child(2) {
animation-delay: -0.16s;
}
}
}
@keyframes thinking-dot {
0%,
80%,
100% {
opacity: 0.3;
transform: scale(0.8);
}
40% {
opacity: 1;
transform: scale(1);
}
}
.thinking-text {
font-size: 14px;
}
/* 错误消息 */
.error-message {
color: var(--color-error, #f56c6c);
i {
margin-right: 8px;
}
}
/* 打字机效果 */
.typewriter {
padding: 12px;
background: var(--ai-answer-bg);
color: var(--ai-answer-text);
border: 1px solid transparent;
border-radius: 8px;
line-height: 1.5;
white-space: pre-wrap;
word-break: break-word;
max-width: 100%;
word-wrap: break-word;
font-size: 14px;
transition: border-color 0.2s ease;
.typewriter-content {
display: block;
white-space: normal;
}
}
/* 工具图标 */
.message-tools {
display: flex;
margin-top: 8px;
flex-wrap: wrap;
column-gap: 12px;
background: var(--ai-answer-bg);
color: var(--ai-answer-text);
border: 1px solid transparent;
transition: border-color 0.2s ease;
.icon-svg {
width: 16px;
height: 16px;
cursor: pointer;
opacity: 0.7;
transition: opacity 0.2s;
&:hover {
opacity: 1;
}
&.disabled {
opacity: 0.3;
cursor: not-allowed;
}
}
}
.message.user .message-tools {
justify-content: flex-end;
background: transparent;
}
/* 右侧参考文献边栏 */
.reference-sidebar {
position: fixed;
top: 0;
right: 0;
width: 680px;
height: 100vh;
border-left: 1px solid var(--color-border, #333);
display: flex;
flex-direction: column;
z-index: 1000;
transform: translateX(100%);
transition: transform 0.3s ease;
background: var(--color-bg, #141518);
&.sidebar-visible {
transform: translateX(0);
}
}
.sidebar-header {
display: flex;
align-items: center;
justify-content: space-between;
padding: 5px 24px;
border-bottom: 1px solid var(--color-border, #333);
color: var(--color-text);
flex-shrink: 0;
font-size: 14px;
font-weight: 600;
}
.close-btn {
width: 32px;
height: 32px;
border: none;
background: transparent;
color: var(--color-text-secondary, #999);
cursor: pointer;
display: flex;
align-items: center;
justify-content: center;
transition: all 0.2s ease;
font-size: 14px;
&:hover {
background: var(--color-hover, #37373d);
color: var(--color-text, #eee);
}
}
.sidebar-content {
flex: 1;
overflow-y: auto;
padding: 16px 8px;
}
.reference-item {
padding: 10px 16px;
transition: border-color 0.2s ease;
}
.reference-title {
font-size: 14px;
font-weight: 600;
color: #3399ff;
line-height: 1.4;
margin-bottom: 8px;
}
.reference-authors {
font-size: 12px;
color: var(--color-text);
margin-bottom: 6px;
}
.reference-journal {
font-size: 12px;
color: var(--color-text-secondary);
margin-bottom: 8px;
}
.reference-doi {
font-size: 12px;
}
.doi-link {
color: var(--color-text-secondary);
text-decoration: none;
transition: color 0.2s ease;
&:hover {
color: var(--color-text-secondary);
text-decoration: underline;
}
}
.reference-tags {
display: flex;
flex-wrap: wrap;
gap: 6px;
margin-top: 8px;
}
.reference-tag {
display: inline-block;
padding: 4px 8px;
background: #f5f5f5;
color: #666;
border-radius: 4px;
font-size: 12px;
line-height: 1.2;
white-space: nowrap;
border: 1px solid #e0e0e0;
}
.websocket-error {
display: flex;
align-items: center;
gap: 8px;
padding: 12px 16px;
background: rgba(245, 108, 108, 0.1);
border: 1px solid var(--color-error, #f56c6c);
border-radius: 8px;
color: var(--color-error, #f56c6c);
margin-bottom: 16px;
}
/* Markdown 内容样式 */
.typewriter-content,
.message-text {
// 基础文本样式
p {
margin: 8px 0 !important;
line-height: 1.6 !important;
white-space: normal !important;
}
// 列表样式
ul,
ol {
margin: 8px 0 !important;
padding-left: 20px !important;
white-space: normal !important;
}
li {
margin: 4px 0 !important;
line-height: 1.5 !important;
white-space: normal !important;
display: list-item !important;
list-style: disc !important;
}
// 引用块样式
blockquote {
margin: 16px 0;
padding: 8px 16px;
border-left: 4px solid var(--color-primary, #2871f6);
background: rgba(40, 113, 246, 0.05);
font-style: italic;
}
// 行内代码样式
code {
background: rgba(40, 113, 246, 0.1);
padding: 2px 6px;
border-radius: 4px;
font-family: "Consolas", "Monaco", "Courier New", monospace;
font-size: 0.9em;
}
// 代码块样式
pre {
background: rgba(40, 113, 246, 0.05);
padding: 12px;
border-radius: 6px;
overflow-x: auto;
margin: 12px 0;
code {
background: none;
padding: 0;
}
}
// 表格样式
table {
border-collapse: collapse;
width: 100%;
margin: 12px 0;
}
th,
td {
border: 1px solid var(--color-border, #333);
padding: 8px 12px;
text-align: left;
}
th {
background: rgba(40, 113, 246, 0.1);
font-weight: 600;
}
// 链接样式
a {
color: var(--color-primary, #2871f6);
text-decoration: none;
&:hover {
text-decoration: underline;
}
}
// 加粗和斜体
strong {
font-weight: 600 !important;
}
em {
font-style: italic;
}
// 水平线
hr {
border: none;
border-top: 1px solid var(--color-border, #333);
margin: 16px 0;
}
// 任务列表
.task-list-item {
list-style: none;
margin-left: -20px;
input[type="checkbox"] {
margin-right: 8px;
}
}
}
/* 响应式设计 */
@media (max-width: 768px) {
.reference-sidebar {
width: 100%;
}
.chat-main.with-sidebar {
width: 100%;
}
}
</style>
<!-- 全局 Markdown 样式 - 不使用 scoped 以确保正确渲染 -->
<style>
/* 全局 Markdown 样式 - 不使用 scoped 以确保优先级 */
.linkmed-chat .typewriter-content h1,
.linkmed-chat .typewriter-content h2,
.linkmed-chat .typewriter-content h3,
.linkmed-chat .typewriter-content h4,
.linkmed-chat .typewriter-content h5,
.linkmed-chat .typewriter-content h6,
.linkmed-chat .message-text h1,
.linkmed-chat .message-text h2,
.linkmed-chat .message-text h3,
.linkmed-chat .message-text h4,
.linkmed-chat .message-text h5,
.linkmed-chat .message-text h6 {
font-weight: bold !important;
margin: 16px 0 8px 0 !important;
line-height: 1.3 !important;
display: block !important;
color: inherit !important;
}
.linkmed-chat .typewriter-content h1,
.linkmed-chat .message-text h1 {
font-size: 1.5em !important;
}
.linkmed-chat .typewriter-content h2,
.linkmed-chat .message-text h2 {
font-size: 1.3em !important;
}
.linkmed-chat .typewriter-content h3,
.linkmed-chat .message-text h3 {
font-size: 1.2em !important;
}
.linkmed-chat .typewriter-content h4,
.linkmed-chat .message-text h4 {
font-size: 1.1em !important;
}
.linkmed-chat .typewriter-content h5,
.linkmed-chat .message-text h5 {
font-size: 1em !important;
}
.linkmed-chat .typewriter-content h6,
.linkmed-chat .message-text h6 {
font-size: 0.9em !important;
}
.linkmed-chat .typewriter-content strong,
.linkmed-chat .message-text strong {
font-weight: bold !important;
color: inherit !important;
}
.linkmed-chat .typewriter-content ul,
.linkmed-chat .typewriter-content ol,
.linkmed-chat .message-text ul,
.linkmed-chat .message-text ol {
margin: 8px 0 !important;
padding-left: 20px !important;
display: block !important;
color: inherit !important;
}
.linkmed-chat .typewriter-content li,
.linkmed-chat .message-text li {
display: list-item !important;
list-style: disc !important;
margin: 4px 0 !important;
color: inherit !important;
}
.linkmed-chat .typewriter-content p,
.linkmed-chat .message-text p {
margin: 8px 0 !important;
line-height: 1.6 !important;
display: block !important;
color: inherit !important;
}
.linkmed-chat .typewriter-content code,
.linkmed-chat .message-text code {
background: rgba(40, 113, 246, 0.1) !important;
padding: 2px 6px !important;
border-radius: 4px !important;
font-family: "Consolas", "Monaco", "Courier New", monospace !important;
font-size: 0.9em !important;
color: inherit !important;
}
.linkmed-chat .typewriter-content pre,
.linkmed-chat .message-text pre {
background: rgba(40, 113, 246, 0.05) !important;
padding: 12px !important;
border-radius: 6px !important;
overflow-x: auto !important;
margin: 12px 0 !important;
}
.linkmed-chat .typewriter-content pre code,
.linkmed-chat .message-text pre code {
background: none !important;
padding: 0 !important;
}
.linkmed-chat .typewriter-content blockquote,
.linkmed-chat .message-text blockquote {
margin: 16px 0 !important;
padding: 8px 16px !important;
border-left: 4px solid var(--color-primary, #2871f6) !important;
background: rgba(40, 113, 246, 0.05) !important;
font-style: italic !important;
color: inherit !important;
}
.linkmed-chat .typewriter-content table,
.linkmed-chat .message-text table {
border-collapse: collapse !important;
width: 100% !important;
margin: 12px 0 !important;
}
.linkmed-chat .typewriter-content th,
.linkmed-chat .typewriter-content td,
.linkmed-chat .message-text th,
.linkmed-chat .message-text td {
border: 1px solid var(--color-border, #333) !important;
padding: 8px 12px !important;
text-align: left !important;
color: inherit !important;
}
.linkmed-chat .typewriter-content th,
.linkmed-chat .message-text th {
background: rgba(40, 113, 246, 0.1) !important;
font-weight: 600 !important;
}
.linkmed-chat .typewriter-content a,
.linkmed-chat .message-text a {
color: var(--color-primary, #2871f6) !important;
text-decoration: none !important;
}
.linkmed-chat .typewriter-content a:hover,
.linkmed-chat .message-text a:hover {
text-decoration: underline !important;
}
.linkmed-chat .typewriter-content em,
.linkmed-chat .message-text em {
font-style: italic !important;
}
.linkmed-chat .typewriter-content hr,
.linkmed-chat .message-text hr {
border: none !important;
border-top: 1px solid var(--color-border, #333) !important;
margin: 16px 0 !important;
}
</style>