-
Notifications
You must be signed in to change notification settings - Fork 625
feat: implement auto-scroll to latest message and scroll-to-bottom button #780
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Conversation
WalkthroughAdds programmatic scroll-to-bottom behavior to MessageNavigationSidebar.vue using refs, a hidden anchor, and an IntersectionObserver. Introduces a bottom “scroll to bottom” button shown when not searching and there are unseen messages. Hooks into lifecycle and watchers (messages.length, isOpen) to auto-scroll and manage observer setup/cleanup. Changes
Sequence Diagram(s)sequenceDiagram
autonumber
actor U as User
participant M as MessageNavigationSidebar
participant DOM as DOM/Refs
participant IO as IntersectionObserver
rect rgb(245,248,255)
note over M: Mount / Open
M->>DOM: init refs (messagesContainer, scrollAnchor)
M->>IO: setupScrollObserver(root=messagesContainer)
alt isOpen and not searching
M->>M: nextTick()
M->>DOM: scrollAnchor.scrollIntoView(end, instant)
end
end
rect rgb(245,255,245)
note over M: New message arrives
M->>M: watch(messages.length)
alt not searching
M->>M: nextTick()
M->>DOM: scrollAnchor.scrollIntoView(end, instant)
end
end
rect rgb(255,248,240)
note over IO: Visibility changes
IO-->>M: scrollAnchor intersecting?
M->>M: toggle showScrollToBottomButton
end
U->>M: Click "Scroll to bottom"
M->>M: scrollToBottom()
M->>DOM: scrollAnchor.scrollIntoView(end, instant)
note over M: onUnmounted -> IO.disconnect()
Estimated code review effort🎯 3 (Moderate) | ⏱️ ~25 minutes Possibly related PRs
Suggested reviewers
Poem
Tip 🔌 Remote MCP (Model Context Protocol) integration is now available!Pro plan users can now connect to remote MCP servers from the Integrations page. Connect with popular remote MCPs such as Notion and Linear to add more context to your reviews and chats. ✨ Finishing Touches🧪 Generate unit tests
Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out. 🪧 TipsChatThere are 3 ways to chat with CodeRabbit:
SupportNeed help? Create a ticket on our support page for assistance with any issues or questions. CodeRabbit Commands (Invoked using PR/Issue comments)Type Other keywords and placeholders
CodeRabbit Configuration File (
|
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Actionable comments posted: 1
Caution
Some comments are outside the diff and can’t be posted inline due to platform limitations.
⚠️ Outside diff range comments (1)
src/renderer/src/components/MessageNavigationSidebar.vue (1)
86-88: Avoid v-html on untrusted message content (XSS risk)
v-htmlrenders raw HTML. Since message previews come from user/assistant content, malicious markup could execute. Either render tokenized text nodes (preferred) or at minimum escape HTML before wrapping highlights.Minimal mitigation (escape then highlight):
-// 高亮搜索关键词 -const highlightSearchQuery = (text: string): string => { - if (!searchQuery.value.trim()) { - return text - } - - const query = searchQuery.value.trim() - const regex = new RegExp(`(${query.replace(/[.*+?^${}()|[\]\\]/g, '\\$&')})`, 'gi') - return text.replace( - regex, - '<mark class="bg-yellow-200 dark:bg-yellow-800 px-1 rounded">$1</mark>' - ) -} +// Highlight search query with HTML-escaped content to avoid XSS +const escapeHtml = (s: string) => + s + .replace(/&/g, '&') + .replace(/</g, '<') + .replace(/>/g, '>') + .replace(/"/g, '"') + .replace(/'/g, ''') + +const highlightSearchQuery = (text: string): string => { + const escaped = escapeHtml(text) + if (!searchQuery.value.trim()) return escaped + const query = searchQuery.value.trim() + const regex = new RegExp(`(${query.replace(/[.*+?^${}()|[\\]\\\\]/g, '\\\\$&')})`, 'gi') + return escaped.replace( + regex, + '<mark class="bg-yellow-200 dark:bg-yellow-800 px-1 rounded">$1</mark>' + ) +}Preferred (no v-html): split text into parts and render with
<span v-for>; I can provide a patch if you want that approach.
🧹 Nitpick comments (7)
src/renderer/src/components/MessageNavigationSidebar.vue (7)
105-115: Add i18n’d a11y labels and use smooth scroll only on user clickMake the button accessible and intentional: add aria-label/title via i18n and call
scrollToBottom({ smooth: true }). Consider hiding the button when there are no messages.- <div v-if="showScrollToBottomButton && !searchQuery.trim()" class="absolute bottom-4 right-4"> + <div v-if="showScrollToBottomButton && !searchQuery.trim() && messages.length > 0" class="absolute bottom-4 right-4"> <Button variant="outline" size="icon" class="h-8 w-8 rounded-full shadow-lg bg-background border" - @click="scrollToBottom" + :aria-label="t('chat.navigation.scrollToBottom')" + :title="t('chat.navigation.scrollToBottom')" + @click="scrollToBottom({ smooth: true })" > <Icon icon="lucide:arrow-down" class="h-4 w-4" /> </Button> </div>Follow-up: add the new i18n key
chat.navigation.scrollToBottomin your locales.
264-275: Auto-scroll only if panel is open and user is already at bottomCurrent logic will yank the viewport to the bottom even if the user scrolled up to read earlier messages. Gate on
props.isOpenand only scroll when the bottom anchor is visible (i.e.,!showScrollToBottomButton). Also avoid the outer nextTick sincescrollToBottomalready schedules one.watch( () => props.messages.length, (newLength, oldLength) => { // 只在新增消息时滚动,避免过度滚动 - if (newLength > oldLength && !searchQuery.value.trim()) { - nextTick(() => { - scrollToBottom() - }) - } + if ( + newLength > oldLength && + !searchQuery.value.trim() && + props.isOpen && + !showScrollToBottomButton.value + ) { + scrollToBottom({ smooth: false }) + } } )
276-290: Initialize observer before scrolling and pause it when panel closesCreate the observer first so its state is accurate, then scroll (if needed). When the panel closes (isOpen → false), disconnect to save work.
watch( () => props.isOpen, (newIsOpen) => { - if (newIsOpen && !searchQuery.value.trim()) { - nextTick(() => { - scrollToBottom() - setupScrollObserver() - }) - } else if (newIsOpen) { - nextTick(() => { - setupScrollObserver() - }) - } + if (newIsOpen) { + nextTick(() => { + setupScrollObserver() + if (!searchQuery.value.trim()) { + scrollToBottom({ smooth: false }) + } + }) + } else { + if (intersectionObserver) { + intersectionObserver.disconnect() + } + } } )
294-314: Harden IntersectionObserver setupGuard against missing refs and fall back to viewport as the root if the container is not yet ready. Also nullify the old instance to avoid accidental reuse.
const setupScrollObserver = () => { if (intersectionObserver) { - intersectionObserver.disconnect() + intersectionObserver.disconnect() + intersectionObserver = null } - intersectionObserver = new IntersectionObserver( + // Guard: ensure target exists + if (!scrollAnchor.value) return + + intersectionObserver = new IntersectionObserver( (entries) => { const entry = entries[0] showScrollToBottomButton.value = !entry.isIntersecting }, { - root: messagesContainer.value, + // Fallback to viewport if container is not yet ready + root: messagesContainer.value ?? null, rootMargin: '0px 0px 20px 0px', threshold: 0 } ) - if (scrollAnchor.value) { - intersectionObserver.observe(scrollAnchor.value) - } + intersectionObserver.observe(scrollAnchor.value) }
316-329: Order of operations: observer first, then scrollThis avoids a brief flicker of the button state on mount and removes one nextTick layer.
-// 组件挂载时滚动到底部 onMounted(() => { - if (props.isOpen && !searchQuery.value.trim()) { - nextTick(() => { - scrollToBottom() - setupScrollObserver() - }) - } else { - nextTick(() => { - setupScrollObserver() - }) - } + nextTick(() => { + setupScrollObserver() + if (props.isOpen && !searchQuery.value.trim()) { + scrollToBottom({ smooth: false }) + } + }) })
153-156: Type refs as nullable and initialize to nullThis avoids
undefinedvsnullambiguity and plays nicer with strict TS inference in Vue templates.-const messagesContainer = ref<HTMLDivElement>() -const scrollAnchor = ref<HTMLDivElement>() +const messagesContainer = ref<HTMLDivElement | null>(null) +const scrollAnchor = ref<HTMLDivElement | null>(null) const showScrollToBottomButton = ref(false)
102-106: Use English comments to match repo guidelinesThe repository guidelines require English for logs and comments. Update the newly added comments.
- <!-- 滚动锚点 --> + <!-- Scroll anchor --> - <!-- 滚动到底部按钮 --> + <!-- Scroll-to-bottom button --> -// 滚动到底部 +// Scroll to bottom -// 组件挂载时滚动到底部 +// Scroll to bottom on mount (when open) -// 清理观察器 +// Cleanup observerAlso applies to: 330-336, 249-249, 316-316
📜 Review details
Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro
💡 Knowledge Base configuration:
- MCP integration is disabled by default for public repositories
- Jira integration is disabled by default for public repositories
- Linear integration is disabled by default for public repositories
You can enable these sources in your CodeRabbit configuration.
📒 Files selected for processing (1)
src/renderer/src/components/MessageNavigationSidebar.vue(5 hunks)
🧰 Additional context used
📓 Path-based instructions (9)
**/*.{ts,tsx,js,jsx,vue}
📄 CodeRabbit inference engine (CLAUDE.md)
Use English for logs and comments
Files:
src/renderer/src/components/MessageNavigationSidebar.vue
src/renderer/src/**/*.vue
📄 CodeRabbit inference engine (CLAUDE.md)
src/renderer/src/**/*.vue: Use Composition API for all Vue 3 components
Use Tailwind CSS with scoped styles for styling
Organize components by feature in src/renderer/src/
Follow existing component patterns in src/renderer/src/ when creating new UI components
Use Composition API with proper TypeScript typing for new UI components
Implement responsive design with Tailwind CSS for new UI components
Add proper error handling and loading states for new UI componentsUse scoped styles to prevent CSS conflicts between components
Files:
src/renderer/src/components/MessageNavigationSidebar.vue
src/renderer/src/**/*.{ts,tsx,vue}
📄 CodeRabbit inference engine (CLAUDE.md)
src/renderer/src/**/*.{ts,tsx,vue}: Use Pinia for frontend state management
Renderer to Main: Use usePresenter.ts composable for direct presenter method calls
Files:
src/renderer/src/components/MessageNavigationSidebar.vue
src/renderer/src/**/*
📄 CodeRabbit inference engine (.cursor/rules/i18n.mdc)
src/renderer/src/**/*: All user-facing strings must use i18n keys (avoid hardcoded user-visible text in code)
Use the 'vue-i18n' framework for all internationalization in the renderer
Ensure all user-visible text in the renderer uses the translation system
Files:
src/renderer/src/components/MessageNavigationSidebar.vue
src/renderer/**/*.{vue,ts,js,tsx,jsx}
📄 CodeRabbit inference engine (.cursor/rules/project-structure.mdc)
渲染进程代码放在
src/renderer
Files:
src/renderer/src/components/MessageNavigationSidebar.vue
src/renderer/src/**/*.{vue,ts,tsx,js,jsx}
📄 CodeRabbit inference engine (.cursor/rules/vue-best-practices.mdc)
src/renderer/src/**/*.{vue,ts,tsx,js,jsx}: Use the Composition API for better code organization and reusability
Implement proper state management with Pinia
Utilize Vue Router for navigation and route management
Leverage Vue's built-in reactivity system for efficient data handling
Files:
src/renderer/src/components/MessageNavigationSidebar.vue
src/renderer/**/*.{ts,tsx,vue}
📄 CodeRabbit inference engine (.cursor/rules/vue-shadcn.mdc)
src/renderer/**/*.{ts,tsx,vue}: Use descriptive variable names with auxiliary verbs (e.g., isLoading, hasError).
Use TypeScript for all code; prefer types over interfaces.
Avoid enums; use const objects instead.
Use arrow functions for methods and computed properties.
Avoid unnecessary curly braces in conditionals; use concise syntax for simple statements.
Files:
src/renderer/src/components/MessageNavigationSidebar.vue
src/renderer/**/*.{vue,ts}
📄 CodeRabbit inference engine (.cursor/rules/vue-shadcn.mdc)
Implement lazy loading for routes and components.
Files:
src/renderer/src/components/MessageNavigationSidebar.vue
src/renderer/**/*.{ts,vue}
📄 CodeRabbit inference engine (.cursor/rules/vue-shadcn.mdc)
src/renderer/**/*.{ts,vue}: Use useFetch and useAsyncData for data fetching.
Implement SEO best practices using Nuxt's useHead and useSeoMeta.
Files:
src/renderer/src/components/MessageNavigationSidebar.vue
🧠 Learnings (5)
📚 Learning: 2025-07-23T00:45:57.322Z
Learnt from: CR
PR: ThinkInAIXYZ/deepchat#0
File: .cursor/rules/vue-shadcn.mdc:0-0
Timestamp: 2025-07-23T00:45:57.322Z
Learning: Applies to src/renderer/**/*.{vue} : Import Icon component from Iconify/Vue.
Applied to files:
src/renderer/src/components/MessageNavigationSidebar.vue
📚 Learning: 2025-07-23T00:45:57.322Z
Learnt from: CR
PR: ThinkInAIXYZ/deepchat#0
File: .cursor/rules/vue-shadcn.mdc:0-0
Timestamp: 2025-07-23T00:45:57.322Z
Learning: Applies to src/renderer/**/*.{vue} : Use Iconify/Vue for icon implementation.
Applied to files:
src/renderer/src/components/MessageNavigationSidebar.vue
📚 Learning: 2025-07-23T00:45:57.322Z
Learnt from: CR
PR: ThinkInAIXYZ/deepchat#0
File: .cursor/rules/vue-shadcn.mdc:0-0
Timestamp: 2025-07-23T00:45:57.322Z
Learning: Applies to src/renderer/**/*.{vue} : Leverage ref, reactive, and computed for reactive state management.
Applied to files:
src/renderer/src/components/MessageNavigationSidebar.vue
📚 Learning: 2025-07-23T00:45:57.322Z
Learnt from: CR
PR: ThinkInAIXYZ/deepchat#0
File: .cursor/rules/vue-shadcn.mdc:0-0
Timestamp: 2025-07-23T00:45:57.322Z
Learning: Applies to src/renderer/**/*.{vue} : Use <script setup> syntax for concise component definitions.
Applied to files:
src/renderer/src/components/MessageNavigationSidebar.vue
📚 Learning: 2025-07-21T01:45:33.790Z
Learnt from: CR
PR: ThinkInAIXYZ/deepchat#0
File: CLAUDE.md:0-0
Timestamp: 2025-07-21T01:45:33.790Z
Learning: Applies to src/renderer/src/**/*.vue : Use Composition API with proper TypeScript typing for new UI components
Applied to files:
src/renderer/src/components/MessageNavigationSidebar.vue
⏰ Context from checks skipped due to timeout of 90000ms. You can increase the timeout in your CodeRabbit configuration to a maximum of 15 minutes (900000ms). (1)
- GitHub Check: build-check (x64)
🔇 Additional comments (3)
src/renderer/src/components/MessageNavigationSidebar.vue (3)
127-127: Imports look goodThe added lifecycle and reactivity imports (watch, nextTick, onMounted, onUnmounted) fit the new behavior.
48-49: Container wiring LGTMUsing a ref on the scroll container is the right choice;
relativeis necessary for absolutely positioning the button.
331-336: Cleanup is correctObserver is disconnected and nulled on unmount.
| // 滚动到底部 | ||
| const scrollToBottom = () => { | ||
| nextTick(() => { | ||
| scrollAnchor.value?.scrollIntoView({ | ||
| behavior: 'instant', | ||
| block: 'end' | ||
| }) | ||
| }) | ||
| } | ||
|
|
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
🛠️ Refactor suggestion
Fix non‑standard scrollIntoView option and add smooth/auto mode
behavior: 'instant' is not a valid ScrollBehavior (valid: 'auto' | 'smooth'), so browsers may ignore it. Also, you’ll likely want smooth scrolling for the button click and non-animated scrolling for auto-scroll on new messages. Expose an options param and switch behavior accordingly.
Apply this diff:
-// 滚动到底部
-const scrollToBottom = () => {
- nextTick(() => {
- scrollAnchor.value?.scrollIntoView({
- behavior: 'instant',
- block: 'end'
- })
- })
-}
+// Scroll to bottom
+type ScrollToBottomOpts = { smooth?: boolean }
+const scrollToBottom = (opts: ScrollToBottomOpts = {}) => {
+ nextTick(() => {
+ const container = messagesContainer.value
+ const smooth = !!opts.smooth
+ const prevBehavior = container?.style.scrollBehavior
+ // If container has CSS 'scroll-behavior: smooth', force instant for programmatic auto-scrolls
+ if (!smooth && container) container.style.scrollBehavior = 'auto'
+ scrollAnchor.value?.scrollIntoView({
+ behavior: smooth ? 'smooth' : 'auto',
+ block: 'end'
+ })
+ if (!smooth && container) container.style.scrollBehavior = prevBehavior ?? ''
+ })
+}📝 Committable suggestion
‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.
| // 滚动到底部 | |
| const scrollToBottom = () => { | |
| nextTick(() => { | |
| scrollAnchor.value?.scrollIntoView({ | |
| behavior: 'instant', | |
| block: 'end' | |
| }) | |
| }) | |
| } | |
| // Scroll to bottom | |
| type ScrollToBottomOpts = { smooth?: boolean } | |
| const scrollToBottom = (opts: ScrollToBottomOpts = {}) => { | |
| nextTick(() => { | |
| const container = messagesContainer.value | |
| const smooth = !!opts.smooth | |
| const prevBehavior = container?.style.scrollBehavior | |
| // If container has CSS 'scroll-behavior: smooth', force instant for programmatic auto-scrolls | |
| if (!smooth && container) container.style.scrollBehavior = 'auto' | |
| scrollAnchor.value?.scrollIntoView({ | |
| behavior: smooth ? 'smooth' : 'auto', | |
| block: 'end' | |
| }) | |
| if (!smooth && container) container.style.scrollBehavior = prevBehavior ?? '' | |
| }) | |
| } |
🤖 Prompt for AI Agents
In src/renderer/src/components/MessageNavigationSidebar.vue around lines 249 to
258, the scrollToBottom function uses a non‑standard behavior value ('instant')
for scrollIntoView; change it to accept an options parameter (e.g. mode: 'auto'
| 'smooth' with a default) and call scrollAnchor.value?.scrollIntoView({
behavior: mode, block: 'end' }) inside nextTick; update all callers so the
button click passes 'smooth' and automatic/new‑message calls pass 'auto' (or
rely on the default) to ensure valid values and the desired animated vs
non‑animated scrolling.
implement auto-scroll to latest message and scroll-to-bottom button
Summary by CodeRabbit
New Features
Improvements