-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathSidebar.vue
More file actions
1459 lines (1298 loc) · 38.1 KB
/
Sidebar.vue
File metadata and controls
1459 lines (1298 loc) · 38.1 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
<template>
<Teleport to="body">
<div class="sidebar-wrapper" v-if="sidebarStore.isOpen" :style="{ width: `${sidebarWidth}px` }">
<div class="resize-handle" @mousedown="startResize"></div>
<div class="sidebar-header">
<h2>{{ $t('sidebar.assistant.title') }}</h2>
<div class="header-actions">
<button class="action-btn interactive-element" @click="clearHistory" title="清空对话历史">
<svg xmlns="http://www.w3.org/2000/svg" width="18" height="18" viewBox="0 0 24 24">
<path
fill="currentColor"
d="M6 19c0 1.1.9 2 2 2h8c1.1 0 2-.9 2-2V7H6v12zM19 4h-3.5l-1-1h-5l-1 1H5v2h14V4z"
/>
</svg>
</button>
<button class="close-btn interactive-element" @click="sidebarStore.closeSidebar">
<svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24">
<path
fill="currentColor"
d="M19 6.41L17.59 5L12 10.59L6.41 5L5 6.41L10.59 12L5 17.59L6.41 19L12 13.41L17.59 19L19 17.59L13.41 12L19 6.41z"
/>
</svg>
</button>
</div>
</div>
<div class="chat-container">
<div class="chat-messages" ref="chatMessagesRef">
<div
v-for="(message, index) in chatMessages"
:key="index"
:class="['message', message.role === 'user' ? 'user-message' : 'ai-message']"
>
<div class="message-avatar">
<div class="avatar-icon">
{{ message.role === 'user' ? '👤' : '🤖' }}
</div>
</div>
<div class="message-content">
<div class="message-header">
<span class="message-sender">{{
message.role === 'user' ? 'You' : $t('sidebar.assistant.title')
}}</span>
<span class="message-time">{{ message.time }}</span>
</div>
<!-- 图片消息 -->
<div v-if="message.hasImage" class="message-image">
<img
:src="message.image"
alt="用户上传图片"
@click="message.image && selectExistingImage(message.image)"
class="clickable-image"
/>
<div
v-if="
message.role === 'assistant' &&
sidebarStore.nodeInfo &&
canApplyToNode(sidebarStore.nodeInfo) &&
!serverMode
"
class="image-actions"
>
<button
class="apply-to-node-btn"
@click="applyImageToNode(message.image)"
:title="getNodeActionTitle(sidebarStore.nodeInfo)"
>
{{ getNodeActionText(sidebarStore.nodeInfo) }}
</button>
</div>
</div>
<!-- 文本消息 -->
<div class="message-text" v-html="message.content"></div>
</div>
</div>
<div v-if="isLoading" class="loading-indicator">
<div class="loading-text">{{ processingStatus }}</div>
<div class="loading-dots">
<div class="dot"></div>
<div class="dot"></div>
<div class="dot"></div>
</div>
</div>
</div>
<!-- 输入区域 -->
<div class="chat-input-area">
<div v-if="sidebarStore?.nodeInfo" style="display: flex; justify-content: space-around">
<div class="info-item">
<span class="label">{{ $t('sidebar.assistant.nodeName') }}:</span>
<span class="value">{{ sidebarStore.nodeInfo.title }}</span>
</div>
<div class="info-item">
<span class="label">{{ $t('sidebar.assistant.nodeType') }}:</span>
<span class="value">{{ sidebarStore.nodeInfo.type }}</span>
</div>
</div>
<div class="image-preview-area" v-if="previewImage">
<div class="preview-image-container">
<img :src="previewImage" alt="图片预览" class="preview-image-small" />
<button class="remove-image-btn" @click="removeImage">×</button>
</div>
</div>
<div class="input-controls">
<button
class="upload-image-btn interactive-element"
@click="triggerImageUpload"
:disabled="isLoading"
:title="$t('sidebar.assistant.uploadImage')"
>
<svg xmlns="http://www.w3.org/2000/svg" width="20" height="20" viewBox="0 0 24 24">
<path
fill="currentColor"
d="M19 5v14H5V5h14zm0-2H5c-1.1 0-2 .9-2 2v14c0 1.1.9 2 2 2h14c1.1 0 2-.9 2-2V5c0-1.1-.9-2-2-2zm-4.86 8.86l-3 3.87L9 13.14L6 17h12l-3.86-5.14z"
/>
</svg>
</button>
<div class="textarea-container interactive-element">
<textarea
class="interactive-element"
v-model="userInput"
:placeholder="$t('sidebar.assistant.inputPlaceholder')"
@keydown.enter="handleKeyDown"
ref="textareaRef"
:disabled="isLoading"
></textarea>
</div>
<!-- 回答时时禁用发送按钮 -->
<button
class="send-message-btn interactive-element"
@click="sendMessage()"
:disabled="isGenerating"
:title="$t('sidebar.assistant.sendMessage')"
>
<svg xmlns="http://www.w3.org/2000/svg" width="20" height="20" viewBox="0 0 24 24">
<path fill="currentColor" d="M2.01 21L23 12L2.01 3L2 10l15 2l-15 2l.01 7z" />
</svg>
</button>
<!-- 生成时显示取消按钮 -->
<button
v-if="isGenerating"
class="control-btn stop-btn interactive-element"
@click="abortGeneration"
title="取消生成"
>
<svg xmlns="http://www.w3.org/2000/svg" width="20" height="20" viewBox="0 0 24 24">
<path fill="currentColor" d="M6 6h12v12H6z" />
</svg>
</button>
</div>
<input
type="file"
ref="imageInputRef"
style="display: none"
accept="image/*"
@change="handleImageUpload"
/>
</div>
</div>
</div>
</Teleport>
</template>
<script setup lang="ts">
import { useSidebarStore } from '../../stores/sidebarStore'
import { onMounted, watch, ref, computed, onBeforeUnmount, nextTick } from 'vue'
import {
sendStreamChatRequest,
createImageUserMessage,
formatOutputTextLight,
handleImageWithKontextPro
} from './util'
import { useI18n } from 'vue-i18n'
import { useToaster } from '@/components/modules/toats/index'
import { v4 as uuidv4 } from 'uuid'
const { t } = useI18n()
const sidebarStore = useSidebarStore()
// 侧边栏宽度相关变量
const sidebarWidth = ref(550) // 默认宽度
const minWidth = 50 // 最小宽度
const maxWidth = 1300 // 最大宽度
const isResizing = ref(false)
// 开始拖拽
const startResize = (e: MouseEvent) => {
isResizing.value = true
document.addEventListener('mousemove', handleResize)
document.addEventListener('mouseup', stopResize)
// 防止选中文本
e.preventDefault()
}
const handleResize = (e: MouseEvent) => {
if (!isResizing.value) return
// 计算宽度 (窗口宽度 - 鼠标位置)
const newWidth = window.innerWidth - e.clientX
// 限制宽度范围
if (newWidth >= minWidth && newWidth <= maxWidth) {
sidebarWidth.value = newWidth
// 保存宽度到本地存储
localStorage.setItem('bizyair-sidebar-width', newWidth.toString())
}
}
// 停止拖拽
const stopResize = () => {
isResizing.value = false
document.removeEventListener('mousemove', handleResize)
document.removeEventListener('mouseup', stopResize)
}
// 组件卸载前清理事件监听器
onBeforeUnmount(() => {
document.removeEventListener('mousemove', handleResize)
document.removeEventListener('mouseup', stopResize)
})
;('---------------------------------------')
// 聊天相关状态
const chatMessages = ref<
Array<{
role: 'user' | 'assistant'
content: string
time: string
hasImage?: boolean
image?: string
id?: string
}>
>([])
const userInput = ref('')
const isLoading = ref(false)
const isGenerating = ref(false)
const processingStatus = ref('')
const previewImage = ref('')
const uploadedImageBase64 = ref('')
const chatMessagesRef = ref<HTMLElement | null>(null)
const textareaRef = ref<HTMLTextAreaElement | null>(null)
const imageInputRef = ref<HTMLInputElement | null>(null)
// 添加请求中止控制器
const abortController = ref<AbortController | null>(null)
// 计算属性:是否可以发送消息
const canSendMessage = computed(() => userInput.value.trim() !== '' || previewImage.value !== '')
// 获取当前时间格式化字符串
const getCurrentTime = () => {
const now = new Date()
const hours = now.getHours().toString().padStart(2, '0')
const minutes = now.getMinutes().toString().padStart(2, '0')
return `${hours}:${minutes}`
}
// 触发图片上传
const triggerImageUpload = () => imageInputRef.value?.click()
// 处理图片上传
const handleImageUpload = (event: Event) => {
const target = event.target as HTMLInputElement
if (!target.files?.length) return
const file = target.files[0]
// 验证文件类型
if (!file.type.startsWith('image/')) {
useToaster({
type: 'error',
message: t('sidebar.assistant.imageUploadError')
})
return
}
const reader = new FileReader()
reader.onload = e => {
const result = e.target?.result as string
previewImage.value = result
uploadedImageBase64.value = result.split(',')[1] // 去掉 data:image/png;base64, 前缀
}
reader.readAsDataURL(file)
}
// 移除已选图片
const removeImage = () => {
previewImage.value = ''
uploadedImageBase64.value = ''
if (imageInputRef.value) {
imageInputRef.value.value = ''
}
}
const promptId = ref('')
const requestId = ref('')
// 生成新的会话ID
const generateNewPromptId = () => {
promptId.value = uuidv4()
localStorage.setItem('bizyair-prompt-id', promptId.value)
}
// 生成新的请求ID
const generateNewRequestId = () => {
requestId.value = uuidv4()
}
// 清空对话历史
const clearHistory = () => {
if (isGenerating.value) {
abortGeneration()
}
// 创建一个新的欢迎消息
const welcomeMessage = {
role: 'assistant' as const,
content: t('sidebar.assistant.welcomeMessage'),
time: getCurrentTime()
}
setTimeout(() => {
chatMessages.value = [welcomeMessage]
generateNewPromptId()
}, 10)
}
// 中止生成
const abortGeneration = () => {
if (abortController.value) {
abortController.value.abort()
abortController.value = null
isLoading.value = false
isGenerating.value = false
processingStatus.value = ''
}
}
// 服务端模式
const serverMode = ref(false)
const sendMessage = async () => {
if (!canSendMessage.value || isLoading.value) return
generateNewRequestId()
const messageText = userInput.value
const currentTime = getCurrentTime()
const hasImage = !!previewImage.value
const isImageGeneration = messageText.trim().startsWith('生成图片:')
nextTick(() => {
isLoading.value = true
isGenerating.value = true
})
// 创建用户消息并添加到聊天记录
const userMessage = {
role: 'user' as const,
content: messageText || '',
time: currentTime,
hasImage: hasImage,
image: previewImage.value
}
chatMessages.value.push(userMessage)
// 清空输入并滚动到底部
userInput.value = ''
setTimeout(() => {
scrollToBottom()
}, 0)
try {
if (hasImage && !isImageGeneration) {
processingStatus.value = '正在编辑图片...'
try {
// 创建AbortController用于中止图片编辑请求
abortController.value = new AbortController()
const imageUrl = await handleImageWithKontextPro(
messageText || '请编辑这张图片',
previewImage.value,
abortController.value.signal
)
if (abortController.value?.signal.aborted) {
isLoading.value = false
isGenerating.value = false
processingStatus.value = ''
return
}
// Image预加载
const img = new Image()
await new Promise((resolve, reject) => {
img.onload = () => resolve(true)
img.onerror = () => reject(new Error('图片加载失败'))
img.src = imageUrl
})
// 图片加载成功后,添加带图片的消息
const assistantMessage = {
role: 'assistant' as const,
content: serverMode.value
? '已为您编辑图片'
: '已为您编辑图片,点击LoadImage节点可以直接应用。',
time: getCurrentTime(),
hasImage: true,
image: imageUrl
}
chatMessages.value.push(assistantMessage)
// 更新状态
isLoading.value = false
isGenerating.value = false
processingStatus.value = ''
removeImage() // 清除已处理的图片
// 滚动到底部
setTimeout(() => {
scrollToBottom()
}, 0)
return
} catch (error: any) {
const errorMsgTime = getCurrentTime()
let errorMessage = ''
if (error) {
errorMessage = error.message
}
chatMessages.value.push({
role: 'assistant',
content: `发生错误: ${errorMessage}<br><br><span style="color: #ff4d4f;">建议检查Bizyair是否更新到最新版本,并检查网络状态或者代理</span>`,
time: errorMsgTime
})
isLoading.value = false
isGenerating.value = false
processingStatus.value = ''
setTimeout(() => {
scrollToBottom()
}, 0)
return
}
}
// 创建AbortController用于中止请求
abortController.value = new AbortController()
// 准备历史对话数据
const historyMessages = chatMessages.value
.filter(msg => msg.role === 'user' || msg.role === 'assistant')
.slice(-6) // 保留最近6条消息传入
.map(msg => {
// 处理带图片的消息
if (msg.hasImage && msg.image && msg.role === 'user') {
return createImageUserMessage(msg.content, msg.image)
} else {
return {
role: msg.role,
content: msg.content
}
}
})
// 记录当前消息时间,用于标识当前回答
const currentMsgTime = getCurrentTime()
let isFirstToken = true
// 使用流式聊天请求
abortController.value = await sendStreamChatRequest(
historyMessages,
{
onStart: () => {
console.log('开始请求多模态模型...')
isLoading.value = true
// 立即滚动到底部
setTimeout(() => {
scrollToBottom()
removeImage()
}, 0)
},
onToken: (token: string) => {
// 首次接收到token时创建新的助手消息
if (isFirstToken) {
chatMessages.value.push({
role: 'assistant',
content: token,
time: currentMsgTime
})
isFirstToken = false
isLoading.value = false
} else {
// 找到刚创建的消息并更新
const currentAssistantMsg = chatMessages.value
.filter(msg => msg.role === 'assistant' && msg.time === currentMsgTime)
.pop()
if (currentAssistantMsg) {
currentAssistantMsg.content += token
// 实时应用格式化
const formattedText = formatOutputTextLight(currentAssistantMsg.content)
currentAssistantMsg.content = formattedText
}
}
// 滚动到底部
setTimeout(() => {
scrollToBottom()
}, 0)
},
onComplete: (fullText: string) => {
console.log('多模态模型响应完成')
// 更新状态
isLoading.value = false
isGenerating.value = false
processingStatus.value = ''
// 确保UI显示完整的回复
const currentAssistantMsg = chatMessages.value
.filter(msg => msg.role === 'assistant' && msg.time === currentMsgTime)
.pop()
if (currentAssistantMsg) {
currentAssistantMsg.content = fullText
}
// 滚动到底部
setTimeout(() => {
scrollToBottom()
}, 0)
// 清除上传的图片
// removeImage();
},
onError: error => {
console.error('多模态请求失败:', error)
const errorMsgTime = getCurrentTime()
let errorMessage = ''
if (error) {
errorMessage = error.message
}
// 添加错误消息
chatMessages.value.push({
role: 'assistant',
content: `发生错误: ${errorMessage}<br><br><span style="color: #ff4d4f;">建议检查Bizyair是否更新到最新版本,并检查网络状态或者代理</span>`,
time: errorMsgTime
})
// 更新状态
isLoading.value = false
isGenerating.value = false
processingStatus.value = ''
}
},
{
model: 'Pro/deepseek-ai/DeepSeek-V3',
prompt_id: promptId.value,
request_id: requestId.value
}
)
} catch (error) {
const errorMsgTime = getCurrentTime()
// 获取错误信息
let errorMessage = ''
if (
error &&
typeof error === 'object' &&
'message' in error &&
typeof error.message === 'string'
) {
errorMessage = error.message
} else {
errorMessage = String(error)
}
// 添加错误消息
chatMessages.value.push({
role: 'assistant',
content: String(error),
time: errorMsgTime
})
// 更新状态
isLoading.value = false
isGenerating.value = false
processingStatus.value = ''
} finally {
console.log('请求处理完成,重置状态')
processingStatus.value = ''
if (!abortController.value) {
abortController.value = null
}
// 滚动到底部
setTimeout(() => {
scrollToBottom()
}, 0)
}
}
// 滚动到聊天底部
const scrollToBottom = () => {
if (chatMessagesRef.value) {
chatMessagesRef.value.scrollTop = chatMessagesRef.value.scrollHeight
}
}
// 处理节点信息更新
watch(
() => sidebarStore.nodeInfo,
newValue => {
console.log('节点信息更新:', newValue)
if (newValue?.imageInfo?.url || newValue?.imageInfo?.base64) {
// 直接设置预览图片,就像用户上传了一样
const imageUrl = newValue.imageInfo.base64 || newValue.imageInfo.url || ''
// 设置上传的图片以便用户可以输入文本后发送
previewImage.value = imageUrl
// 处理base64数据
if (newValue.imageInfo.base64) {
// 检查是否已包含data:前缀
if (typeof newValue.imageInfo.base64 === 'string') {
uploadedImageBase64.value = newValue.imageInfo.base64.startsWith('data:')
? newValue.imageInfo.base64.split(',')[1]
: newValue.imageInfo.base64
}
} else if (newValue.imageInfo.url) {
// 如果没有base64,则尝试从URL加载并转换
fetch(newValue.imageInfo.url)
.then(response => response.blob())
.then(blob => {
const reader = new FileReader()
reader.onloadend = () => {
const base64data = reader.result
if (typeof base64data === 'string') {
uploadedImageBase64.value = base64data.split(',')[1] // 移除data:image/...前缀
}
}
reader.readAsDataURL(blob)
})
.catch(error => console.error('获取图片出错:', error))
}
// 聚焦到输入框
setTimeout(() => {
textareaRef.value?.focus()
}, 0)
}
},
{ deep: true }
)
// 修改canApplyToNode函数来返回更具体的操作类型
const canApplyToNode = (nodeInfo: any) => {
// 根据节点类型返回不同的操作类型
if (!nodeInfo || !nodeInfo.type) return false
const nodeType = nodeInfo.type
if (nodeType === 'LoadImage') {
return 'apply' // 应用到节点
} else if (nodeType === 'SaveImage') {
return 'save-output' // 保存到output目录
} else if (nodeType === 'PreviewImage') {
return 'save-temp' // 保存到temp目录
}
return false // 其他类型节点不支持操作
}
// 添加getNodeActionText函数,返回按钮文本
const getNodeActionText = (nodeInfo: any) => {
const actionType = canApplyToNode(nodeInfo)
if (actionType === 'apply') {
return '应用到当前节点'
} else if (actionType === 'save-output') {
return '保存到output目录'
} else if (actionType === 'save-temp') {
return '保存到temp目录'
}
return '应用到节点'
}
// 添加getNodeActionTitle函数,返回提示文本
const getNodeActionTitle = (nodeInfo: any) => {
const actionType = canApplyToNode(nodeInfo)
if (actionType === 'apply') {
return '将图片应用到LoadImage节点'
} else if (actionType === 'save-output') {
return '将图片保存到output目录'
} else if (actionType === 'save-temp') {
return '将图片保存到temp目录'
}
return ''
}
// 应用图片到当前节点
const applyImageToNode = async (imageUrl: string | undefined) => {
if (!sidebarStore.nodeInfo) {
console.error('没有选中的节点信息')
return
}
if (!imageUrl) {
console.error('没有图片URL')
return
}
let base64Data = imageUrl
if (!imageUrl.startsWith('data:')) {
try {
const response = await fetch(imageUrl)
const blob = await response.blob()
base64Data = await new Promise(resolve => {
const reader = new FileReader()
reader.onloadend = () => resolve(reader.result as string)
reader.readAsDataURL(blob)
})
} catch (error) {
console.error('获取图片数据失败:', error)
useToaster({
type: 'error',
message: '获取图片数据失败,无法应用到节点'
})
return
}
}
// 创建要发送到节点的图片数据对象
const imageData = {
nodeId: sidebarStore.nodeInfo.id,
imageBase64: base64Data,
nodeType: sidebarStore.nodeInfo.type
}
console.log(window.bizyAirLib, 'window.bizyAirLib-----')
// 如果window.bizyAirLib存在并有updateNodeImage方法,调用它
if (
typeof window.bizyAirLib !== 'undefined' &&
typeof window.bizyAirLib.updateNodeImage === 'function'
) {
window.bizyAirLib.updateNodeImage(imageData)
useToaster({
type: 'success',
message: '图片已应用到节点: ' + sidebarStore.nodeInfo.title
})
} else {
console.error('bizyAirLib.updateNodeImage未定义')
useToaster({
type: 'error',
message: '应用图片到节点失败'
})
}
}
// enter发送,shift+enter换行
const handleKeyDown = (e: KeyboardEvent) => {
if (e.shiftKey) {
return
}
// enter键,发送消息
e.preventDefault()
sendMessage()
}
// 选择现有图片
const selectExistingImage = (imageUrl: string) => {
if (!imageUrl) return
previewImage.value = imageUrl
// 如果图片URL以data:开头,则为base64格式
if (previewImage.value.includes('data:')) {
try {
// 提取base64部分
const base64Part = previewImage.value.split('base64,')[1]
if (base64Part) {
uploadedImageBase64.value = base64Part
console.log('已设置base64数据,长度:', uploadedImageBase64.value.length)
} else {
console.error('无法从图片URL提取base64数据')
}
} catch (error) {
console.error('解析base64数据出错:', error)
}
} else if (imageUrl.startsWith('http')) {
// 否则尝试将图片转换为base64
console.log('正在获取远程图片:', imageUrl.substring(0, 50) + '...')
fetch(imageUrl)
.then(response => {
if (!response.ok) {
throw new Error(`无法获取图片: ${response.status} ${response.statusText}`)
}
return response.blob()
})
.then(blob => {
const reader = new FileReader()
reader.onloadend = () => {
if (typeof reader.result === 'string') {
previewImage.value = reader.result
const base64data = reader.result.split('base64,')[1]
if (base64data) {
uploadedImageBase64.value = base64data
console.log('已转换远程图片为base64,长度:', uploadedImageBase64.value.length)
}
}
}
reader.readAsDataURL(blob)
})
.catch(error => console.error('获取图片出错:', error))
}
// 聚焦到输入框
setTimeout(() => {
textareaRef.value?.focus()
}, 0)
}
onMounted(() => {
// 从本地存储加载宽度设置
const savedWidth = localStorage.getItem('bizyair-sidebar-width')
if (savedWidth) {
const width = parseInt(savedWidth)
if (width >= minWidth && width <= maxWidth) {
sidebarWidth.value = width
}
}
const savedPromptId = localStorage.getItem('bizyair-prompt-id')
if (savedPromptId) {
promptId.value = savedPromptId
} else {
generateNewPromptId()
}
generateNewRequestId()
// 确保全局bizyAirLib对象存在
if (typeof window.bizyAirLib === 'undefined') {
;(window as any).bizyAirLib = {}
}
// 直接定义updateNodeImage方法
if (typeof (window as any).bizyAirLib.updateNodeImage !== 'function') {
;(window as any).bizyAirLib.updateNodeImage = function (imageData: any) {
if (!imageData || !imageData.nodeId || !imageData.imageBase64) {
console.error('应用图片到节点失败: 缺少必要的参数')
return
}
try {
console.log('正在尝试应用图片到节点...')
// 直接使用传入的imageData.nodeId通过IFRAME找到节点
// bizyAirLib直接传递postMessage到父窗口
window.parent.postMessage(
{
type: 'APPLY_IMAGE_TO_NODE',
data: {
nodeId: imageData.nodeId,
base64Data: imageData.imageBase64
}
},
'*'
)
console.log('已发送图片应用消息到ComfyUI')
} catch (error) {
console.error('应用图片到节点时发生异常:', error)
}
}
console.log('已添加updateNodeImage方法到bizyAirLib对象')
}
// 显示欢迎消息
const welcomeMessage = {
role: 'assistant' as const,
content: t('sidebar.assistant.welcomeMessage'),
time: getCurrentTime()
}
chatMessages.value = [welcomeMessage]
// 异步获取 server_mode
;(async () => {
try {
const res = await fetch('/bizyair/server_mode')
const data = await res.json()
serverMode.value = !!data?.data?.server_mode
} catch (e) {
serverMode.value = false
}
})()
})
</script>
<style>
.sidebar-wrapper {
position: fixed;
top: 0;
right: 0;
height: 100%;
background-color: #2d2d2d;
box-shadow: -2px 0 10px rgba(0, 0, 0, 0.2);
display: flex;
flex-direction: column;
overflow: hidden;
z-index: 99999;
transition: width 0.1s ease;
pointer-events: auto;
}
.resize-handle {
position: absolute;
top: 0;
left: 0;
width: 5px;
height: 100%;
cursor: col-resize;
background-color: transparent;
}
.resize-handle:hover,
.resize-handle:active {
background-color: rgba(124, 58, 237, 0.3);
}
/* 拖拽过程中添加样式到body */
body.resizing {
cursor: col-resize;
user-select: none;
}
.sidebar-header {
display: flex;
justify-content: space-between;
align-items: center;
padding: 12px 16px;
background-color: #333;
border-bottom: 1px solid #444;
flex-shrink: 0;
}
.sidebar-header h2 {
margin: 0;
font-size: 16px;
color: #fff;
}
.header-actions {
display: flex;
align-items: center;
gap: 8px;
}
.action-btn,
.close-btn {
background: none;
border: none;
color: #ccc;
cursor: pointer;
padding: 4px;
display: flex;
align-items: center;
justify-content: center;
border-radius: 4px;
}
.action-btn {
pointer-events: auto;
position: relative;
z-index: 1000;
}
.close-btn {
pointer-events: auto;
position: relative;
z-index: 1000;
}
.action-btn:hover,
.close-btn:hover {
color: #fff;
background-color: rgba(255, 255, 255, 0.1);
}
.sidebar-content {
flex: 1;
display: flex;
flex-direction: column;
overflow: hidden;
color: #eee;
height: 100%;
padding: 16px;
}
.node-info {
background-color: #333;
border-radius: 6px;
padding: 16px;
margin-bottom: 16px;
border: 1px solid #444;
}