diff --git a/frontend/src/components/chat/ChatQuestionMinimap.test.ts b/frontend/src/components/chat/ChatQuestionMinimap.test.ts new file mode 100644 index 00000000..8598941f --- /dev/null +++ b/frontend/src/components/chat/ChatQuestionMinimap.test.ts @@ -0,0 +1,86 @@ +import assert from 'node:assert/strict' +import test from 'node:test' +import { readFileSync } from 'node:fs' + +const component = readFileSync(new URL('./ChatQuestionMinimap.vue', import.meta.url), 'utf8') +const composable = readFileSync(new URL('../../composables/useChatQuestionMinimap.ts', import.meta.url), 'utf8') + +test('does not render the rail until the thread overflows', () => { + assert.match(component, /v-if="visible"/) +}) + +test('opens a following Q&A card to the right of the left-side rail', () => { + assert.match(component, /question-minimap__panel/) + assert.match(component, /question-minimap__bridge/) + assert.match(component, /question-minimap__question/) + assert.match(component, /question-minimap__answer/) + assert.match(component, /CLOSE_DELAY_MS = 150/) + assert.match(component, /left: `\$\{RAIL_INSET_PX\}px`/) + assert.match(component, /top: `\$\{peakYPx\}px`/) + assert.doesNotMatch(component, /flex-direction: row-reverse/) + assert.doesNotMatch(component, /right: `\$\{scrollbarGutterPx \+ RAIL_INSET_PX\}px`/) +}) + +test('grows nearby ticks into a mountain under the pointer', () => { + assert.match(component, /tickMountainScale/) + assert.match(component, /nearestTickId/) + assert.match(component, /scaleX\(/) + assert.match(component, /handleRailPointerMove/) +}) + +test('centers the rail and panel in the thread instead of stretching top to bottom', () => { + assert.match(component, /top: 50%/) + assert.match(component, /transform: translateY\(-50%\)/) + assert.match(component, /height: `\$\{trackHeight\}px`/) + assert.doesNotMatch(component, /inset-block: 0/) + assert.doesNotMatch(component, /align-self: flex-start/) + assert.doesNotMatch(component, /height: min\(360px, 50%\)/) + assert.match(composable, /questionMinimapTrackHeight\(measured\.length, el\.clientHeight\)/) +}) + +test('jumps through data-message-id via the jump event', () => { + assert.match(component, /emit\('jump'/) + assert.match(component, /anchoredIds/) +}) + +test('uses chat question minimap i18n keys', () => { + assert.match(component, /chat\.questionMinimapTitle/) + assert.match(component, /chat\.questionMinimapAriaLabel/) + assert.match(component, /chat\.questionMinimapAttachmentPlaceholder/) + assert.match(component, /chat\.questionMinimapAnswerPending/) +}) + +test('wraps the overlay in navigation without overriding the rail button role', () => { + assert.match(component, / { + assert.doesNotMatch(component, /watch\(activeId/) +}) + +test('does not draw a second scrollbar thumb next to the native scrollbar', () => { + assert.doesNotMatch(component, /question-minimap__viewport/) + assert.match(component, /RAIL_INSET_PX = 16/) + assert.match(component, /scrollbar-width: none/) +}) + +test('does not paint the first question green on hover-open', () => { + assert.match(component, /keyboardIndex\.value = -1/) + assert.doesNotMatch(component, /question-minimap__row--active/) + assert.doesNotMatch(component, /question-minimap__row:hover,\s*\.question-minimap__row--active/) +}) + +test('highlights the matching tick for the peaked question', () => { + assert.match(component, /peakId/) + assert.match(component, /tick\.id === peakId/) +}) + +test('uses only approved TDesign tokens in minimap styles', () => { + assert.doesNotMatch(component, /--td-brand-color-light/) + assert.doesNotMatch(component, /--td-border-level-2-color/) + assert.doesNotMatch(component, /--td-shadow-2/) + assert.doesNotMatch(component, /--td-text-color-primary/) +}) diff --git a/frontend/src/components/chat/ChatQuestionMinimap.vue b/frontend/src/components/chat/ChatQuestionMinimap.vue new file mode 100644 index 00000000..1d927563 --- /dev/null +++ b/frontend/src/components/chat/ChatQuestionMinimap.vue @@ -0,0 +1,392 @@ + + + + + diff --git a/frontend/src/composables/useChatQuestionMinimap.ts b/frontend/src/composables/useChatQuestionMinimap.ts new file mode 100644 index 00000000..45952ef9 --- /dev/null +++ b/frontend/src/composables/useChatQuestionMinimap.ts @@ -0,0 +1,186 @@ +import { + computed, + onBeforeUnmount, + onMounted, + ref, + toValue, + watch, + type ComputedRef, + type Ref, +} from 'vue' +import { + activeQuestionId, + collectUserQuestions, + isChatOverflowing, + mapQuestionTicks, + offsetFromScrollContent, + questionMinimapTrackHeight, + shouldShowQuestionMinimap, + viewportBand, + type ChatMessageLike, + type QuestionTick, + type UserQuestion, + type ViewportBand, +} from '@/utils/chatQuestionMinimap' + +export function useChatQuestionMinimap(options: { + scrollContainer: Ref + messages: ChatMessageLike[] | Ref +}): { + visible: ComputedRef + questions: ComputedRef + ticks: Ref + viewport: Ref + activeId: Ref + anchoredIds: Ref> + scrollbarGutterPx: Ref + trackHeight: Ref +} { + const questions = computed(() => collectUserQuestions(toValue(options.messages))) + const overflowing = ref(false) + const ticks = ref([]) + const viewport = ref({ topPx: 0, heightPx: 0 }) + const activeId = ref(null) + const anchoredIds = ref>(new Set()) + const scrollbarGutterPx = ref(0) + const trackHeight = ref(0) + + const visible = computed(() => ( + shouldShowQuestionMinimap(overflowing.value, questions.value.length) + )) + + let resizeObserver: ResizeObserver | null = null + let observedContainer: HTMLElement | null = null + let observedContent: Element | null = null + let frameId: number | null = null + + const reset = () => { + overflowing.value = false + ticks.value = [] + viewport.value = { topPx: 0, heightPx: 0 } + activeId.value = null + anchoredIds.value = new Set() + scrollbarGutterPx.value = 0 + trackHeight.value = 0 + } + + const disconnectObserver = () => { + resizeObserver?.disconnect() + resizeObserver = null + observedContainer = null + observedContent = null + } + + const measureNow = () => { + const el = options.scrollContainer.value + if (!el) { + reset() + return + } + + overflowing.value = isChatOverflowing(el.scrollHeight, el.clientHeight) + const anchors = Array.from(el.querySelectorAll('[data-message-id]')) + const anchorByMessageId = new Map() + for (const anchor of anchors) { + const messageId = anchor.dataset.messageId + if (messageId) anchorByMessageId.set(messageId, anchor) + } + const containerTop = el.getBoundingClientRect().top + scrollbarGutterPx.value = Math.max(0, el.offsetWidth - el.clientWidth) + const measured = questions.value.flatMap((question) => { + const anchor = anchorByMessageId.get(question.id) + if (!anchor) return [] + + return [{ + id: question.id, + offsetTop: offsetFromScrollContent( + anchor.getBoundingClientRect().top, + containerTop, + el.scrollTop, + ), + }] + }) + + trackHeight.value = questionMinimapTrackHeight(measured.length, el.clientHeight) + ticks.value = mapQuestionTicks(measured, trackHeight.value) + viewport.value = viewportBand(el.scrollTop, el.clientHeight, el.scrollHeight, trackHeight.value) + activeId.value = activeQuestionId(measured, el.scrollTop) + anchoredIds.value = new Set(measured.map((item) => item.id)) + } + + const scheduleMeasure = () => { + if (frameId !== null) return + + frameId = window.requestAnimationFrame(() => { + frameId = null + measureNow() + }) + } + + const observeCurrentContainer = () => { + const el = options.scrollContainer.value + if (!el || typeof ResizeObserver === 'undefined') return + + const content = el.firstElementChild + if (resizeObserver && observedContainer === el && observedContent === content) return + + disconnectObserver() + resizeObserver = new ResizeObserver(scheduleMeasure) + resizeObserver.observe(el) + if (content) resizeObserver.observe(content) + observedContainer = el + observedContent = content + } + + const bind = () => { + const el = options.scrollContainer.value + if (!el) { + disconnectObserver() + reset() + return + } + + el.addEventListener('scroll', scheduleMeasure, { passive: true }) + window.addEventListener('resize', scheduleMeasure) + observeCurrentContainer() + scheduleMeasure() + } + + const unbind = (el: HTMLElement | null) => { + el?.removeEventListener('scroll', scheduleMeasure) + window.removeEventListener('resize', scheduleMeasure) + disconnectObserver() + } + + watch(options.scrollContainer, (el, previousEl) => { + unbind(previousEl) + if (el) bind() + else reset() + }, { flush: 'post' }) + + watch(questions, () => { + observeCurrentContainer() + scheduleMeasure() + }, { flush: 'post' }) + + onMounted(bind) + + onBeforeUnmount(() => { + unbind(options.scrollContainer.value) + if (frameId !== null) { + window.cancelAnimationFrame(frameId) + frameId = null + } + }) + + return { + visible, + questions, + ticks, + viewport, + activeId, + anchoredIds, + scrollbarGutterPx, + trackHeight, + } +} diff --git a/frontend/src/i18n/locales/en-US.ts b/frontend/src/i18n/locales/en-US.ts index 98b6b1d8..72e893fb 100755 --- a/frontend/src/i18n/locales/en-US.ts +++ b/frontend/src/i18n/locales/en-US.ts @@ -3235,6 +3235,10 @@ export default { referencesDrawerDocsSection: 'Documents', referencesDrawerToolsSection: 'Tools', referencesDrawerEmpty: 'No sources available', + questionMinimapTitle: 'Questions', + questionMinimapAriaLabel: 'Question outline', + questionMinimapAttachmentPlaceholder: '(Attachment)', + questionMinimapAnswerPending: 'Generating', referenceChunkCount: '{count} chunk(s)', fallbackHint: 'No relevant content found in knowledge base. Above is a direct response from the model.', requestInfoTitle: 'Request info', diff --git a/frontend/src/i18n/locales/ko-KR.ts b/frontend/src/i18n/locales/ko-KR.ts index e489281e..74ed2e52 100755 --- a/frontend/src/i18n/locales/ko-KR.ts +++ b/frontend/src/i18n/locales/ko-KR.ts @@ -3252,6 +3252,10 @@ export default { referencesDrawerDocsSection: '지식베이스 문서', referencesDrawerToolsSection: '도구', referencesDrawerEmpty: '참고 출처가 없습니다', + questionMinimapTitle: '질문', + questionMinimapAriaLabel: '질문 목차', + questionMinimapAttachmentPlaceholder: '(첨부)', + questionMinimapAnswerPending: '생성 중', referenceChunkCount: '{count}개 청크', fallbackHint: '지식 베이스에서 관련 내용을 찾지 못했습니다. 위는 모델의 직접 응답입니다.', requestInfoTitle: 'Request info', diff --git a/frontend/src/i18n/locales/ru-RU.ts b/frontend/src/i18n/locales/ru-RU.ts index cad81307..100d165b 100755 --- a/frontend/src/i18n/locales/ru-RU.ts +++ b/frontend/src/i18n/locales/ru-RU.ts @@ -3252,6 +3252,10 @@ export default { referencesDrawerDocsSection: 'Документы базы знаний', referencesDrawerToolsSection: 'Инструменты', referencesDrawerEmpty: 'Источники отсутствуют', + questionMinimapTitle: 'Вопросы', + questionMinimapAriaLabel: 'Содержание вопросов', + questionMinimapAttachmentPlaceholder: '(Вложение)', + questionMinimapAnswerPending: 'Генерация', referenceChunkCount: '{count} фрагмент(ов)', fallbackHint: 'В базе знаний не найдено релевантного содержимого. Выше представлен прямой ответ модели.', requestInfoTitle: 'Request info', diff --git a/frontend/src/i18n/locales/zh-CN.ts b/frontend/src/i18n/locales/zh-CN.ts index 8bbbb260..90d071e4 100755 --- a/frontend/src/i18n/locales/zh-CN.ts +++ b/frontend/src/i18n/locales/zh-CN.ts @@ -3254,6 +3254,10 @@ export default { referencesDrawerDocsSection: '知识库文档', referencesDrawerToolsSection: '工具', referencesDrawerEmpty: '暂无参考来源', + questionMinimapTitle: '提问', + questionMinimapAriaLabel: '提问目录', + questionMinimapAttachmentPlaceholder: '(附件)', + questionMinimapAnswerPending: '生成中', referenceChunkCount: '{count}个片段', fallbackHint: '未从知识库中检索到相关内容,以上为模型直接回答', requestInfoTitle: '请求信息', diff --git a/frontend/src/utils/chatQuestionMinimap.test.ts b/frontend/src/utils/chatQuestionMinimap.test.ts new file mode 100644 index 00000000..57a3326d --- /dev/null +++ b/frontend/src/utils/chatQuestionMinimap.test.ts @@ -0,0 +1,166 @@ +import assert from 'node:assert/strict' +import test from 'node:test' + +import { + ACTIVE_QUESTION_TOP_OFFSET_PX, + QUESTION_MINIMAP_TRACK_MAX_PX, + QUESTION_TICK_GAP_PX, + QUESTION_TICK_MOUNTAIN_GAIN, + activeQuestionId, + answerPreviewText, + collectUserQuestions, + isChatOverflowing, + mapQuestionTicks, + nearestTickId, + offsetFromScrollContent, + questionDisplayText, + questionMinimapTrackHeight, + shouldShowQuestionMinimap, + tickMountainScale, + viewportBand, +} from './chatQuestionMinimap.ts' + +test('isChatOverflowing is false when content fits or matches the viewport', () => { + assert.equal(isChatOverflowing(800, 800), false) + assert.equal(isChatOverflowing(799, 800), false) + assert.equal(isChatOverflowing(801, 800), true) +}) + +test('questionMinimapTrackHeight packs ticks with a small gap instead of filling the rail', () => { + assert.equal(questionMinimapTrackHeight(1, 800), QUESTION_TICK_GAP_PX) + assert.equal(questionMinimapTrackHeight(3, 800), 2 * QUESTION_TICK_GAP_PX) + assert.equal(questionMinimapTrackHeight(0, 800), 0) + assert.equal(questionMinimapTrackHeight(3, 0), 0) +}) + +test('questionMinimapTrackHeight still caps a long cluster to the centered rail', () => { + assert.equal(questionMinimapTrackHeight(100, 800), QUESTION_MINIMAP_TRACK_MAX_PX) + assert.equal(questionMinimapTrackHeight(100, 400), 200) +}) + +test('shouldShowQuestionMinimap requires overflow and at least one question', () => { + assert.equal(shouldShowQuestionMinimap(true, 1), true) + assert.equal(shouldShowQuestionMinimap(true, 0), false) + assert.equal(shouldShowQuestionMinimap(false, 4), false) +}) + +test('collectUserQuestions keeps loaded user turns with ids, in list order', () => { + const questions = collectUserQuestions([ + { role: 'assistant', id: 'a1', content: 'hi' }, + { role: 'user', content: 'no id yet' }, + { role: 'user', id: 'u1', content: 'first', images: [{}] }, + { role: 'assistant', id: 'a2', content: 'answer one' }, + { role: 'user', id: 'u2', content: ' ', attachments: [{}] }, + ]) + assert.deepEqual( + questions.map((q) => ({ id: q.id, hasAttachments: q.hasAttachments, answerContent: q.answerContent })), + [ + { id: 'u1', hasAttachments: true, answerContent: 'answer one' }, + { id: 'u2', hasAttachments: true, answerContent: '' }, + ], + ) +}) + +test('answerPreviewText strips markdown and uses the pending placeholder when empty', () => { + assert.equal( + answerPreviewText('## Hello\n**world** and [link](https://x)', '生成中'), + 'Hello world and link', + ) + assert.equal(answerPreviewText(' ', '生成中'), '生成中') + assert.equal(answerPreviewText(undefined, '生成中'), '生成中') +}) + +test('tickMountainScale is 1 without a pointer and peaks at the hovered tick', () => { + assert.equal(tickMountainScale(100, null), 1) + assert.equal(tickMountainScale(100, 100), 1 + QUESTION_TICK_MOUNTAIN_GAIN) + assert.ok(tickMountainScale(100, 100) > tickMountainScale(135, 100)) + assert.ok(tickMountainScale(135, 100) > tickMountainScale(200, 100)) +}) + +test('nearestTickId picks the closest tick to the pointer', () => { + const ticks = [ + { id: 'u1', yPx: 10 }, + { id: 'u2', yPx: 45 }, + { id: 'u3', yPx: 80 }, + ] + assert.equal(nearestTickId(ticks, 12), 'u1') + assert.equal(nearestTickId(ticks, 50), 'u2') + assert.equal(nearestTickId([], 10), null) +}) + +test('questionDisplayText uses trimmed content, else the placeholder', () => { + assert.equal(questionDisplayText(' hello\nworld ', '(附件)'), 'hello world') + assert.equal(questionDisplayText(' ', '(附件)'), '(附件)') + assert.equal(questionDisplayText(undefined, '(附件)'), '(附件)') +}) + +test('offsetFromScrollContent is viewport-relative plus scrollTop', () => { + assert.equal(offsetFromScrollContent(120, 40, 80), 160) +}) + +test('mapQuestionTicks clusters ticks in the center with a compact equal gap', () => { + const ticks = mapQuestionTicks( + [ + { id: 'u1' }, + { id: 'u2' }, + { id: 'u3' }, + ], + 200, + ) + assert.equal(ticks[1].yPx - ticks[0].yPx, QUESTION_TICK_GAP_PX) + assert.equal(ticks[2].yPx - ticks[1].yPx, QUESTION_TICK_GAP_PX) + assert.equal((ticks[0].yPx + ticks[2].yPx) / 2, 100) +}) + +test('mapQuestionTicks ignores message offsets and keeps equal gaps', () => { + const ticks = mapQuestionTicks( + [ + { id: 'u1', offsetTop: 0 }, + { id: 'u2', offsetTop: 2 }, + ], + 200, + ) + assert.equal(ticks[1].yPx - ticks[0].yPx, QUESTION_TICK_GAP_PX) + assert.equal((ticks[0].yPx + ticks[1].yPx) / 2, 100) +}) + +test('mapQuestionTicks still fits many ticks inside a short rail', () => { + const ticks = mapQuestionTicks( + [ + { id: 'a' }, + { id: 'b' }, + { id: 'c' }, + { id: 'd' }, + ], + 20, + ) + assert.equal(ticks.length, 4) + assert.ok(ticks[0].yPx >= 0) + assert.ok(ticks[3].yPx <= 20) + const gap = ticks[1].yPx - ticks[0].yPx + for (let i = 1; i < ticks.length; i++) { + assert.ok(Math.abs(ticks[i].yPx - ticks[i - 1].yPx - gap) < 1e-9) + } +}) + +test('viewportBand maps the visible window onto the track with a 16px floor', () => { + const band = viewportBand(250, 250, 1000, 200) + assert.equal(band.topPx, 50) + assert.equal(band.heightPx, 50) + + const tiny = viewportBand(0, 10, 1000, 200) + assert.equal(tiny.topPx, 0) + assert.equal(tiny.heightPx, 16) +}) + +test('activeQuestionId picks the last question at or above the top offset', () => { + const items = [ + { id: 'u1', offsetTop: 0 }, + { id: 'u2', offsetTop: 400 }, + { id: 'u3', offsetTop: 800 }, + ] + assert.equal(activeQuestionId(items, 0), 'u1') + assert.equal(activeQuestionId(items, 400 - ACTIVE_QUESTION_TOP_OFFSET_PX), 'u2') + assert.equal(activeQuestionId(items, 900), 'u3') + assert.equal(activeQuestionId([], 0), null) +}) diff --git a/frontend/src/utils/chatQuestionMinimap.ts b/frontend/src/utils/chatQuestionMinimap.ts new file mode 100644 index 00000000..fbc93ce4 --- /dev/null +++ b/frontend/src/utils/chatQuestionMinimap.ts @@ -0,0 +1,224 @@ +export const QUESTION_TICK_RADIUS_PX = 3 +export const QUESTION_TICK_GAP_PX = 35 +export const QUESTION_TICK_MOUNTAIN_GAIN = 2.2 +export const ACTIVE_QUESTION_TOP_OFFSET_PX = 72 +export const VIEWPORT_BAND_MIN_HEIGHT_PX = 16 +export const QUESTION_MINIMAP_TRACK_MAX_PX = 360 +export const QUESTION_MINIMAP_TRACK_RATIO = 0.5 + +export function questionMinimapTrackHeight( + questionCount: number, + clientHeight: number, +): number { + if (questionCount <= 0 || clientHeight <= 0) return 0 + const maxHeight = Math.min( + QUESTION_MINIMAP_TRACK_MAX_PX, + clientHeight * QUESTION_MINIMAP_TRACK_RATIO, + ) + const naturalHeight = questionCount === 1 + ? QUESTION_TICK_GAP_PX + : (questionCount - 1) * QUESTION_TICK_GAP_PX + return Math.min(naturalHeight, maxHeight) +} + +export type ChatMessageLike = { + id?: string + role?: string + content?: string + images?: unknown[] + attachments?: unknown[] +} + +export type UserQuestion = { + id: string + content: string + hasAttachments: boolean + answerContent: string +} + +export type QuestionTick = { + id: string + yRatio: number + yPx: number +} + +export type ViewportBand = { + topPx: number + heightPx: number +} + +export function isChatOverflowing(scrollHeight: number, clientHeight: number): boolean { + return scrollHeight > clientHeight +} + +export function shouldShowQuestionMinimap(overflowing: boolean, questionCount: number): boolean { + return overflowing && questionCount >= 1 +} + +export function collectUserQuestions(messages: ChatMessageLike[]): UserQuestion[] { + const questions: UserQuestion[] = [] + + for (let index = 0; index < messages.length; index++) { + const message = messages[index] + if (message.role !== 'user' || !message.id) continue + + let answerContent = '' + for (let next = index + 1; next < messages.length; next++) { + const following = messages[next] + if (following.role === 'user') break + if (following.role === 'assistant') { + answerContent = following.content ?? '' + break + } + } + + questions.push({ + id: message.id, + content: message.content ?? '', + hasAttachments: + (message.images?.length ?? 0) > 0 || (message.attachments?.length ?? 0) > 0, + answerContent, + }) + } + + return questions +} + +export function questionDisplayText( + content: string | undefined, + attachmentPlaceholder: string, +): string { + const normalized = (content ?? '').replace(/\s+/g, ' ').trim() + return normalized.length > 0 ? normalized : attachmentPlaceholder +} + +export function answerPreviewText( + content: string | undefined, + pendingPlaceholder: string, +): string { + const normalized = (content ?? '') + .replace(/```[\s\S]*?```/g, ' ') + .replace(/`([^`]+)`/g, '$1') + .replace(/\[([^\]]+)\]\([^)]*\)/g, '$1') + .replace(/[#>*_~-]+/g, ' ') + .replace(/\s+/g, ' ') + .trim() + return normalized.length > 0 ? normalized : pendingPlaceholder +} + +export function tickMountainScale(tickY: number, pointerY: number | null): number { + if (pointerY === null) return 1 + const dy = tickY - pointerY + const sigma = QUESTION_TICK_GAP_PX + return 1 + QUESTION_TICK_MOUNTAIN_GAIN * Math.exp(-0.5 * (dy / sigma) ** 2) +} + +export function nearestTickId( + ticks: Array<{ id: string; yPx: number }>, + pointerY: number, +): string | null { + if (ticks.length === 0) return null + + let bestId = ticks[0].id + let bestDist = Math.abs(ticks[0].yPx - pointerY) + for (let index = 1; index < ticks.length; index++) { + const dist = Math.abs(ticks[index].yPx - pointerY) + if (dist < bestDist) { + bestDist = dist + bestId = ticks[index].id + } + } + return bestId +} + +export function offsetFromScrollContent( + anchorTop: number, + containerTop: number, + scrollTop: number, +): number { + return anchorTop - containerTop + scrollTop +} + +export function mapQuestionTicks( + items: Array<{ id: string; offsetTop?: number }>, + trackHeight: number, +): QuestionTick[] { + const n = items.length + if (n === 0 || trackHeight <= 0) { + return [] + } + + if (n === 1) { + return [{ + id: items[0].id, + yRatio: 0.5, + yPx: trackHeight / 2, + }] + } + + const preferredSpan = (n - 1) * QUESTION_TICK_GAP_PX + const minY = Math.min(QUESTION_TICK_RADIUS_PX, trackHeight / 2) + const maxY = Math.max(minY, trackHeight - minY) + const available = maxY - minY + const span = preferredSpan <= trackHeight ? preferredSpan : available + const start = (trackHeight - span) / 2 + + return items.map((item, index) => { + const yRatio = index / (n - 1) + return { + id: item.id, + yRatio, + yPx: start + yRatio * span, + } + }) +} + +export function viewportBand( + scrollTop: number, + clientHeight: number, + scrollHeight: number, + trackHeight: number, + minHeightPx: number = VIEWPORT_BAND_MIN_HEIGHT_PX, +): ViewportBand { + if (scrollHeight <= 0 || trackHeight <= 0) { + return { topPx: 0, heightPx: minHeightPx } + } + + let topPx = (scrollTop / scrollHeight) * trackHeight + let heightPx = Math.max(minHeightPx, (clientHeight / scrollHeight) * trackHeight) + + heightPx = Math.min(heightPx, trackHeight) + + if (topPx + heightPx > trackHeight) { + topPx = trackHeight - heightPx + } + + topPx = Math.max(0, topPx) + + if (topPx + heightPx > trackHeight) { + heightPx = trackHeight - topPx + } + + return { topPx, heightPx } +} + +export function activeQuestionId( + items: Array<{ id: string; offsetTop: number }>, + scrollTop: number, + topOffsetPx: number = ACTIVE_QUESTION_TOP_OFFSET_PX, +): string | null { + if (items.length === 0) { + return null + } + + const threshold = scrollTop + topOffsetPx + let activeId: string | null = null + + for (const item of items) { + if (item.offsetTop <= threshold) { + activeId = item.id + } + } + + return activeId ?? items[0].id +} diff --git a/frontend/src/views/chat/index.vue b/frontend/src/views/chat/index.vue index 8f2c7269..0dbd60aa 100644 --- a/frontend/src/views/chat/index.vue +++ b/frontend/src/views/chat/index.vue @@ -5,8 +5,9 @@ 'has-references-panel': referencesDrawerVisible, }"> -
-
+
+
+
@@ -73,40 +74,49 @@ 这是历史加载时白屏 + layout shift 蔓延到 session 列表的根因。 仅对极少数尚未拿到 id 的本地占位消息 fallback 到 role+created_at+index。 --> -
- +
+ -
- - +
+ + +
+
+ + + +
-
- - - +
+
-
- -
+
@@ -151,6 +161,7 @@ import ChatReferencesDrawer from '@/components/ChatReferencesDrawer.vue'; import ChatAttachmentPreviewDrawer from '@/components/ChatAttachmentPreviewDrawer.vue'; import FollowUpSuggestions from '@/components/chat/FollowUpSuggestions.vue'; import MessageTimestamp from '@/components/chat/MessageTimestamp.vue'; +import ChatQuestionMinimap from '@/components/chat/ChatQuestionMinimap.vue'; import { shouldShowConversationTimestamp } from '@/utils/messageTimestamp'; import ChatHeader from '@/components/ChatHeader.vue'; import { @@ -267,6 +278,8 @@ let fullContent = ref('') const scrollContainer = ref(null) const userHasScrolledUp = ref(false) const SCROLL_BOTTOM_THRESHOLD = 80 +const minimapTargetId = ref('') +let minimapFlashTimer = null const isNearBottom = () => { if (!scrollContainer.value) return true; @@ -274,6 +287,34 @@ const isNearBottom = () => { return scrollHeight - scrollTop - clientHeight < SCROLL_BOTTOM_THRESHOLD; } +const clearMinimapFlash = () => { + if (minimapFlashTimer) { + clearTimeout(minimapFlashTimer) + minimapFlashTimer = null + } + minimapTargetId.value = '' +} + +const jumpToQuestion = (id) => { + const root = scrollContainer.value + if (!root || !id) return + const el = root.querySelector(`[data-message-id="${CSS.escape(id)}"]`) + if (!el) return + + const offset = el.getBoundingClientRect().top - root.getBoundingClientRect().top + root.scrollTop + const nearEnd = root.scrollHeight - offset < root.clientHeight + SCROLL_BOTTOM_THRESHOLD + userHasScrolledUp.value = !nearEnd + + el.scrollIntoView({ block: 'start', behavior: 'smooth' }) + + minimapTargetId.value = id + if (minimapFlashTimer) clearTimeout(minimapFlashTimer) + minimapFlashTimer = setTimeout(() => { + minimapTargetId.value = '' + minimapFlashTimer = null + }, 1200) +} + const handleKBEditorSuccess = (kbId) => { navigateToKnowledgeBaseList(kbId) } @@ -1004,12 +1045,14 @@ const clearData = () => { referencesDrawer.close(); isReplying.value = false; fullContent.value = ''; + clearMinimapFlash(); // Stop any IM-reply recovery poll for the session we're leaving/switching. if (recoverPollTimer) { clearTimeout(recoverPollTimer); recoverPollTimer = null; } isImRecovering.value = false; } onUnmounted(() => { window.removeEventListener(SESSION_MUTATION_EVENT, handleSessionMutation); + clearMinimapFlash(); if (recoverPollTimer) { clearTimeout(recoverPollTimer); recoverPollTimer = null; } }); onBeforeRouteLeave((to, from, next) => { @@ -1034,8 +1077,8 @@ onBeforeRouteUpdate((to, from, next) => { flex: 1; // The parent .platform-route-outlet is a flex column with min-height:0 // and overflow:hidden — we also need min-height:0 here so that our - // own flex:1 child (.chat_scroll_box) can shrink below its content - // height and scroll instead of pushing .input-container out of view. + // own flex:1 child (.chat_thread) can shrink below its content + // height and keep the input container in view. min-height: 0; position: relative; display: flex; @@ -1102,13 +1145,18 @@ onBeforeRouteUpdate((to, from, next) => { } } +.chat_thread { + position: relative; + flex: 1; + min-height: 0; + width: 100%; + display: flex; + flex-direction: column; + overflow: hidden; +} + .chat_scroll_box { flex: 1; - // Without min-height: 0, a flex-column child defaults to min-height: auto - // and expands to fit all inner content. When there are many messages, - // that pushes .input-container out of the viewport. Clamping min-height - // to 0 lets overflow-y: auto take effect so the messages scroll inside - // this box instead of stretching it. min-height: 0; width: 100%; padding-top: 8px; @@ -1257,6 +1305,10 @@ onBeforeRouteUpdate((to, from, next) => { display: flex; flex-direction: column; width: 100%; + + &.is-minimap-target { + animation: minimap-target-flash 1.2s ease; + } } .botanswer_laoding_gif { @@ -1289,6 +1341,16 @@ onBeforeRouteUpdate((to, from, next) => { } } +@keyframes minimap-target-flash { + 0% { + background: color-mix(in srgb, var(--td-brand-color) 18%, transparent); + } + + 100% { + background: transparent; + } +} + @media (prefers-reduced-motion: reduce) { .chat-global-wait__spinner { animation: none;