feat: bubble 组件调整

This commit is contained in:
rd
2025-08-21 16:26:57 +08:00
parent df01af0656
commit cb9b0715b1
10 changed files with 302 additions and 38 deletions

View File

@ -62,8 +62,8 @@ export default function useListData(
*/
const listData = computed(() =>
(items.value || []).map((bubbleData, i) => {
// 生成唯一key如果没有提供key则使用预设格式
const mergedKey = bubbleData.key ?? `preset_${i}`;
// 生成唯一key:优先使用传入的 key其次使用 id最后回退到预设格式
const mergedKey = (bubbleData as any).key ?? (bubbleData as any).id ?? `preset_${i}`;
return {
// 先应用角色配置(作为默认值)

View File

@ -34,6 +34,7 @@ const useTypedEffect = (
typingEnabled: Ref<boolean>,
typingStep: Ref<number>,
typingInterval: Ref<number>,
abortRef?: Ref<boolean>,
): [typedContent: Ref<BubbleContentType>, isTyping: Ref<boolean>] => {
// 记录上一次的内容,用于检测内容变化
const [prevContent, setPrevContent] = useState<BubbleContentType>('');
@ -51,9 +52,12 @@ const useTypedEffect = (
// 更新上一次的内容记录
setPrevContent(content.value);
// 如果未启用打字效果且内容为字符串,直接显示全部内容
// 如果未启用打字效果且内容为字符串
if (!mergedTypingEnabled.value && isString(content.value)) {
setTypingIndex(content.value.length);
// 若外部触发中止,则保持当前索引,不再自动跳到全文
if (!(abortRef && abortRef.value)) {
setTypingIndex(content.value.length);
}
} else if (
// 如果内容为字符串,且新内容不是以旧内容开头,重置打字索引
isString(content.value) &&
@ -68,10 +72,15 @@ const useTypedEffect = (
// 启动打字效果
watch(
[typingIndex, typingEnabled, content],
[typingIndex, typingEnabled, content, abortRef as any],
() => {
// 只有在启用打字、内容为字符串且未显示完所有内容时才执行
if (mergedTypingEnabled.value && isString(content.value) && unref(typingIndex) < content.value.length) {
if (
mergedTypingEnabled.value &&
isString(content.value) &&
unref(typingIndex) < content.value.length &&
!(abortRef && abortRef.value)
) {
// 设置定时器,逐步增加显示字符数
const id = setTimeout(() => {
setTypingIndex(unref(typingIndex) + typingStep.value);
@ -88,8 +97,11 @@ const useTypedEffect = (
// 计算当前应该显示的内容
const mergedTypingContent = computed(() =>
// 如果启用打字且内容为字符串,显示部分内容;否则显示全部内容
mergedTypingEnabled.value && isString(content.value) ? content.value.slice(0, unref(typingIndex)) : content.value,
// 如果启用打字且内容为字符串,显示部分内容;
// 或外部中止时,固定在当前索引;否则显示全部内容
(mergedTypingEnabled.value || (abortRef && abortRef.value)) && isString(content.value)
? content.value.slice(0, unref(typingIndex))
: content.value,
);
return [

View File

@ -1,4 +1,5 @@
.xt-bubble-list {
height: 100%;
gap: 8px;
display: flex;
flex-direction: column;
@ -78,6 +79,31 @@
&-corner {
border-radius: 4px;
}
:deep(table) {
border-collapse: collapse;
thead {
tr {
th {
@include cts;
padding: 6px 8px;
border: 1px solid #E6E6E8;
text-align: left;
}
}
}
tbody {
tr {
td {
@include cts;
border: 1px solid #E6E6E8;
padding: 16px 8px;
text-align: left;
}
}
}
}
}
.xt-bubble-header {
@ -94,4 +120,5 @@
display: inline-block;
min-width: 36px;
}
}

View File

@ -119,6 +119,8 @@ export interface BubbleProps<ContentType extends BubbleContentType = string>
export interface BubbleRef {
/** 气泡组件的原生DOM元素 */
nativeElement: HTMLElement;
/** 中止当前打字效果并立即展示完整内容 */
abortTyping: VoidFunction;
}
/**

View File

@ -11,7 +11,7 @@ export default defineComponent({
name: 'Bubble',
inheritAttrs: false,
props: {} as any,
setup(_, { attrs, slots }) {
setup(_, { attrs, slots, expose }) {
const props = attrs as unknown as BubbleProps<BubbleContentType> & { style?: any; class?: any };
const content = ref<BubbleContentType>(props.content ?? '');
@ -26,7 +26,19 @@ export default defineComponent({
const { onUpdate } = unref(useBubbleContextInject());
const [typingEnabled, typingStep, typingInterval, typingSuffix] = useTypingConfig(() => props.typing);
const [typedContent, isTyping] = useTypedEffect(content as any, typingEnabled, typingStep, typingInterval);
const abortRef = ref(false);
const [typedContent, isTyping] = useTypedEffect(
content as any,
typingEnabled,
typingStep,
typingInterval,
abortRef,
);
// 提供中止打字的能力关闭typing并立即展示完整内容
const abortTyping = () => {
abortRef.value = true;
};
const triggerTypingCompleteRef = ref(false);
watch(typedContent, () => {
@ -97,6 +109,10 @@ export default defineComponent({
return typeof f === 'function' ? f({ content: typedContent.value as any, info, item: props }) : f;
};
expose({
abortTyping,
});
return () => (
<div class={mergedCls.value} style={{ ...(props.style || {}) }}>
{(slots.avatar || props.avatar) && (

View File

@ -24,7 +24,7 @@ export default defineComponent({
name: 'BubbleList',
inheritAttrs: false,
props: {} as any,
setup(_, { attrs, slots }) {
setup(_, { attrs, slots, expose }) {
const props = attrs as unknown as BubbleListProps & { class?: any; style?: any };
const passThroughAttrs = useAttrs();
@ -48,7 +48,7 @@ export default defineComponent({
const listRef = ref<HTMLDivElement | null>(null);
const bubbleRefs = ref<Record<string | number, BubbleRef>>({});
const listPrefixCls = 'xt-bubble-list'
const listPrefixCls = 'xt-bubble-list';
const [initialized, setInitialized] = useState(false);
watchPostEffect(() => {
@ -102,6 +102,19 @@ export default defineComponent({
});
const context = computed(() => ({ onUpdate: onBubbleUpdate }));
// 暴露控制方法
const abortTypingByKey = (key: string | number) => {
bubbleRefs.value[key]?.abortTyping?.();
};
// 对外暴露能力
expose({
nativeElement: listRef as any,
abortTypingByKey,
scrollTo: (info: any) => {
unref(listRef)?.scrollTo?.(info);
},
});
return () => (
<BubbleContextProvider value={context.value}>
<div

View File

@ -21,7 +21,6 @@ const userStore = useUserStore();
const router = useRouter();
const route = useRoute();
useResponsive(true);
const showSider = computed(() => {
@ -30,12 +29,18 @@ const showSider = computed(() => {
const isHomeRoute = computed(() => {
return route.name === 'Home';
});
const showInOnePage = computed(() => {
return isHomeRoute.value;
});
const layoutPageClass = computed(() => {
let result = showInOnePage.value ? 'overflow-hidden' : '';
if (isHomeRoute.value) {
return 'pb-8px pr-8px';
result += ' pb-8px pr-8px';
} else {
result += ' pb-24px pr-24px';
}
return 'pb-24px pr-24px';
return result;
});
const siderWidth = computed(() => {

View File

@ -1,13 +1,15 @@
<script lang="tsx">
import { message, Tooltip } from 'ant-design-vue';
import { BubbleList } from '@/components/xt-chat/xt-bubble';
import type { BubbleListProps } from 'ant-design-x-vue';
import { useRoute } from 'vue-router';
import SenderInput from '../sender-input/index.vue';
import markdownit from 'markdown-it';
import { Typography } from 'ant-design-vue';
import RightView from './rightView.vue';
import { useRoute } from 'vue-router';
import markdownit from 'markdown-it';
import { useClipboard } from '@vueuse/core';
import { genRandomId } from '@/utils/tools';
import type { BubbleListProps } from '@/components/xt-chat/xt-bubble/types';
const QUESTION_ROLE = 'question';
const ANSWER_ROLE = 'text';
@ -15,13 +17,25 @@ const ANSWER_ROLE = 'text';
export default {
setup(props, { emit, expose }) {
const route = useRoute();
const { copy, copied, isSupported } = useClipboard();
const { copy } = useClipboard();
const senderRef = ref(null);
const rightViewRef = ref(null);
const bubbleListRef = ref<any>(null);
const searchValue = ref('');
const generateLoading = ref(false);
const conversationList = ref([]);
const md = markdownit({ html: true, breaks: true });
const currentAnswerId = ref<string | null>(null);
const showRightView = ref(false);
const rightViewContent = ref('');
const md = markdownit({
html: true,
breaks: true,
linkify: true,
typographer: true,
});
const conversationId = computed(() => {
return route.params.conversationId;
@ -60,9 +74,49 @@ export default {
loading: true,
role: ANSWER_ROLE,
});
currentAnswerId.value = tempId;
setTimeout(() => {
const content = `> Render as markdown content to show rich text!`;
const content = `# 测试数据表格
## 用户信息表
| 表头1 | 表头2 |
|---|---|
| 内容1 | 内容2 |
## 项目统计表
| 项目名称 | 负责人 | 进度 | 状态 | 预算(万元) | 完成度 |
|----------|--------|------|------|------------|--------|
| 电商平台重构 | 张三 | 75% | 进行中 | 50 | 🟡 |
| 移动端APP | 李四 | 90% | 测试中 | 30 | 🟢 |
| 数据分析系统 | 王五 | 45% | 开发中 | 80 | 🟡 |
| 客户管理系统 | 赵六 | 100% | 已完成 | 25 | 🟢 |
| 营销自动化 | 钱七 | 30% | 规划中 | 60 | 🔴 |
## 销售数据
| 月份 | 销售额(万) | 订单数 | 客户数 | 增长率 | 备注 |
|------|------------|--------|--------|--------|------|
| 1月 | 120.5 | 156 | 89 | +12% | 春节促销 |
| 2月 | 98.3 | 134 | 76 | -18% | 淡季 |
| 3月 | 145.2 | 189 | 102 | +48% | 新品上市 |
| 4月 | 167.8 | 203 | 115 | +16% | 稳定增长 |
| 5月 | 189.6 | 234 | 128 | +13% | 持续增长 |
> 以上数据仅供参考,实际数据请以系统为准。
**注意事项:**
- 所有数据均为测试数据
- 表格支持Markdown格式渲染
- 可以包含表情符号和特殊字符`;
showRightView.value = true;
rightViewContent.value = '';
nextTick(() => {
rightViewContent.value = content;
});
searchValue.value = '';
conversationList.value.splice(tempIndex, 1, {
id: tempId,
@ -98,6 +152,13 @@ export default {
const handleCancel = () => {
generateLoading.value = false;
// 中止当前正在输出的回答
if (currentAnswerId.value && bubbleListRef.value?.abortTypingByKey) {
bubbleListRef.value.abortTypingByKey(currentAnswerId.value);
}
if (showRightView.value) {
rightViewRef.value?.abortTyping?.();
}
message.info('取消生成');
};
@ -109,33 +170,55 @@ export default {
onTypingComplete: () => {
console.log('onTypingComplete');
generateLoading.value = false;
currentAnswerId.value = null;
},
style: {
width: '600px',
margin: '0 auto',
},
},
[QUESTION_ROLE]: {
placement: 'end',
shape: 'round',
style: {
width: '600px',
margin: '0 auto',
},
},
};
return () => (
<div class="conversation-detail-wrap w-full h-full flex">
<div class="flex-1 flex justify-center">
<section class="main w-600px h-full relative flex flex-col pt-20px">
<BubbleList class="flex-1" roles={roles} items={conversationList.value} />
<div class="w-full flex flex-col justify-center items-center">
<SenderInput
class="w-full"
ref={senderRef}
placeholder="继续追问..."
loading={generateLoading.value}
v-model={searchValue.value}
onSubmit={handleSubmit}
onCancel={handleCancel}
/>
<p class="cts !color-#939499 text-12px !lh-20px my-4px">内容由AI生成仅供参考</p>
</div>
</section>
</div>
<section class="flex-1 flex flex-col pt-20px justify-center relative px-16px">
{/* <div class="w-full h-full flex "> */}
<div class="flex-1 overflow-hidden pb-20px">
<BubbleList ref={bubbleListRef} roles={roles} items={conversationList.value} />
</div>
<div class="w-full flex flex-col justify-center items-center">
<SenderInput
class="w-600px"
ref={senderRef}
placeholder="继续追问..."
loading={generateLoading.value}
v-model={searchValue.value}
onSubmit={handleSubmit}
onCancel={handleCancel}
data-ne='123'
/>
<p class="cts !color-#939499 text-12px !lh-20px my-4px">内容由AI生成仅供参考</p>
</div>
{/* </div> */}
</section>
{/* 右侧展示区域 */}
{showRightView.value && (
<RightView
ref={rightViewRef}
rightViewContent={rightViewContent.value}
showRightView={showRightView.value}
onClose={() => (showRightView.value = false)}
/>
)}
</div>
);
},

View File

@ -0,0 +1,102 @@
<script lang="tsx">
import { Button } from '@arco-design/web-vue';
import { Bubble } from '@/components/xt-chat/xt-bubble';
import { downloadByUrl } from '@/utils/tools';
import markdownit from 'markdown-it';
export default {
emits: ['close'],
props: {
showRightView: {
type: Boolean,
default: false,
},
rightViewContent: {
type: String,
default: '',
},
},
setup(props, { emit, expose }) {
const bubbleRef = ref(null);
const md = markdownit({
html: true,
breaks: true,
linkify: true,
typographer: true,
});
const onDownload = () => {
// downloadByUrl('');
};
const abortTyping = () => {
bubbleRef.value?.abortTyping?.();
};
const renderHeader = () => {
return (
<header class="header flex justify-end items-center mb-16px px-32px">
<Button type="outline" size="medium" class="mr-16px" v-slots={{ icon: () => <icon-plus size="14" /> }}>
素材中心
</Button>
<Button type="outline" size="medium" class="mr-16px" v-slots={{ icon: () => <icon-plus size="14" /> }}>
任务管理
</Button>
<Button
type="outline"
size="medium"
class="mr-16px"
v-slots={{ icon: () => <icon-download size="14" /> }}
onClick={onDownload}
>
下载
</Button>
<div class="line mr-24px w-1px h-16px bg-#B1B2B5"></div>
<icon-close size={20} class="color-#737478 cursor-pointer" onClick={() => emit('close')} />
</header>
);
};
const renderContainer = () => {
return (
<section class="flex-1 overflow-y-auto content flex justify-center px-32px">
<Bubble
ref={bubbleRef}
placement="start"
variant="borderless"
style={{ width: '100%' }}
typing={{ step: 2, interval: 100 }}
content={props.rightViewContent}
onTypingComplete={() => {
console.log('onTypingComplete');
}}
messageRender={(content) => <div v-html={md.render(content)}></div>}
/>
</section>
);
};
expose({
abortTyping,
});
return () => (
<div class="right-view-wrap flex-1 flex flex-col overflow-hidden py-20px">
{renderHeader()}
{renderContainer()}
</div>
);
},
};
</script>
<style lang="scss" scoped>
.right-view-wrap {
box-shadow: 0 4px 8px 0 rgba(0, 0, 0, 0.1);
@media (max-width: 900px) {
.header,
.content {
padding-left: 16px !important;
padding-right: 16px !important;
}
}
}
</style>

View File

@ -17,6 +17,10 @@ export default defineConfig(({ mode }: ConfigEnv): UserConfig => {
const setServer = setServerConfig({ env });
return {
define: {
__VUE_PROD_DEVTOOLS__: false,
__VUE_PROD_HYDRATION_MISMATCH_DETAILS__: false,
},
css: {
preprocessorOptions: {
scss: {