Skip to content

armgit / alook

Public Imported from GitHub
0

Multi-Agent Collaboration for Team and Friends

fix(community): re-pin scroll on async tail growth + auto-focus composer

Generb1a6bd2a4096
diff --git a/src/web/src/app/community/channels/[serverId]/[channelId]/page.tsx b/src/web/src/app/community/channels/[serverId]/[channelId]/page.tsx
index b6aeb3150..7ab36c465 100644
--- a/src/web/src/app/community/channels/[serverId]/[channelId]/page.tsx
+++ b/src/web/src/app/community/channels/[serverId]/[channelId]/page.tsx
@@ -530,6 +530,7 @@ function ChannelView() {
onTyping={handleTyping}
replyingTo={replyTo?.authorName}
onCancelReply={() => setReplyTo(null)}
+ autoFocus={bp !== "mobile"}
/>
</main>
@@ -640,6 +641,7 @@ function ChannelView() {
onTyping={handleTyping}
replyingTo={replyTo?.authorName}
onCancelReply={() => setReplyTo(null)}
+ autoFocus={bp !== "mobile"}
/>
</main>
diff --git a/src/web/src/app/community/me/[dmId]/page.tsx b/src/web/src/app/community/me/[dmId]/page.tsx
index 9d136403d..672766a86 100644
--- a/src/web/src/app/community/me/[dmId]/page.tsx
+++ b/src/web/src/app/community/me/[dmId]/page.tsx
@@ -236,6 +236,7 @@ function DmView() {
onTyping={handleTyping}
replyingTo={replyTo?.authorName}
onCancelReply={() => setReplyTo(null)}
+ autoFocus={bp !== "mobile"}
/>
)}
</main>
diff --git a/src/web/src/components/community/composer.tsx b/src/web/src/components/community/composer.tsx
index f66a35f74..ec6077f95 100644
--- a/src/web/src/components/community/composer.tsx
+++ b/src/web/src/components/community/composer.tsx
@@ -28,7 +28,7 @@ import {
// Enter sends, Shift+Enter adds a newline; while the mention popover is open
// Enter/Tab/Arrow keys drive selection instead. @everyone / @here are virtual
// candidates in channel + thread contexts (hidden in DM).
-export function Composer({ channel, context, members, onSearchMembers, onSend, onCreateThread, onTyping, replyingTo, onCancelReply }: {
+export function Composer({ channel, context, members, onSearchMembers, onSend, onCreateThread, onTyping, replyingTo, onCancelReply, autoFocus = false }: {
channel: string
context: MentionContext
members: Member[]
@@ -43,6 +43,9 @@ export function Composer({ channel, context, members, onSearchMembers, onSend, o
// when set, shows a "Replying to X" bar above the input
replyingTo?: string
onCancelReply?: () => void
+ // Auto-focus the editor on mount and on channel change. Desktop only —
+ // callers pass `bp !== "mobile"` to avoid unexpected soft-keyboard pop-up.
+ autoFocus?: boolean
}) {
const {
pendingFiles,
@@ -54,7 +57,7 @@ export function Composer({ channel, context, members, onSearchMembers, onSend, o
handleDragEnter,
handleDragLeave,
handleDragOver,
- handleDrop,
+ handleDrop: handleDropRaw,
} = useFileAttachments()
const typingTimer = useRef<NodeJS.Timeout | null>(null)
@@ -178,6 +181,22 @@ export function Composer({ channel, context, members, onSearchMembers, onSend, o
setMentionPopup(EMPTY_MENTION_STATE)
}
+ // Auto-focus on mount + on channel switch. `<Composer>` is not remounted
+ // per channel (only `<MessageList>` is keyed by channelId), so keying this
+ // effect on `channel` is what refocuses when the user navigates channels.
+ useEffect(() => {
+ if (!autoFocus || !editor) return
+ editor.commands.focus("end")
+ }, [autoFocus, editor, channel])
+
+ // Refocus editor after a drop so the user can start typing without
+ // clicking. The drop landed on the composer container — the intent is
+ // clear.
+ const handleDrop = (e: React.DragEvent) => {
+ handleDropRaw(e)
+ editor?.commands.focus()
+ }
+
return (
<div
className="relative px-3 pb-3 pt-0"
@@ -240,14 +259,14 @@ export function Composer({ channel, context, members, onSearchMembers, onSend, o
<EditorContent editor={editor} className="max-h-40 overflow-y-auto thin-scrollbar text-base chat-input-line-height outline-none" />
</div>
{/* Attach button — fixed bottom-left */}
- <DropdownMenu>
+ <DropdownMenu onOpenChange={(open) => { if (!open) editor?.commands.focus() }}>
<DropdownMenuTrigger
render={<button className="absolute left-2 bottom-2 grid size-8 place-items-center rounded-full text-muted-foreground hover:text-foreground aria-expanded:text-foreground" aria-label="Add" />}
>
<PlusCircle className="size-5" />
</DropdownMenuTrigger>
<DropdownMenuContent side="top" align="start" className="w-44">
- <DropdownMenuItem onClick={() => fileInputRef.current?.click()}><Upload className="size-4" /> Upload a File</DropdownMenuItem>
+ <DropdownMenuItem onClick={() => { fileInputRef.current?.click(); editor?.commands.focus() }}><Upload className="size-4" /> Upload a File</DropdownMenuItem>
{context === "channel" && <DropdownMenuItem onClick={onCreateThread}><MessagesSquare className="size-4" /> Create Thread</DropdownMenuItem>}
</DropdownMenuContent>
</DropdownMenu>
diff --git a/src/web/src/components/community/message-list.tsx b/src/web/src/components/community/message-list.tsx
index 549300454..2e73048fe 100644
--- a/src/web/src/components/community/message-list.tsx
+++ b/src/web/src/components/community/message-list.tsx
@@ -90,6 +90,15 @@ export function MessageList({
// Owners key `<MessageList>` on channelId/dmId, so channel switches
// remount the component and reset this ref — no explicit reset logic
// needed here.
+ //
+ // Cold-cache guard (RO watchdog): on a hard reload the browser hasn't
+ // decoded any embedded images yet, so `scrollHeight` when the initial
+ // scroll fires is the pre-image height. Images arrive over the next
+ // few hundred ms and push the target out of view. A ResizeObserver on
+ // the scroll container re-invokes the same action on every subsequent
+ // layout change, until the user scrolls or 3s elapses. Later mounts
+ // (channel switch within session) skip this because the browser image
+ // cache is warm and layout is stable on the first frame.
useLayoutEffect(() => {
const el = scrollRef.current
if (!el) return
@@ -100,18 +109,26 @@ export function MessageList({
// to the bottom and burns the one-shot gate.
if (!initialScrollReady) return
+ let action: () => void
if (newDividerBefore) {
const target = el.querySelector<HTMLElement>(
`[data-msg-id="${cssEscape(newDividerBefore)}"]`,
)
if (target) {
- target.scrollIntoView({ block: "center", behavior: "smooth" })
- didInitialScrollRef.current = true
- return
+ // Instant, not smooth — same reason as the self-send effect
+ // below: smooth animations race the RO re-pins on some engines
+ // and can snap back to the pre-image target.
+ action = () => target.scrollIntoView({ block: "center" })
+ } else {
+ action = () => el.scrollTo({ top: el.scrollHeight })
}
+ } else {
+ action = () => el.scrollTo({ top: el.scrollHeight })
}
- el.scrollTo({ top: el.scrollHeight, behavior: "smooth" })
+ action()
didInitialScrollRef.current = true
+
+ return watchAsyncGrowth(el, action)
}, [messages, newDividerBefore, initialScrollReady])
// Rule #3: when the viewer sends a message, snap to the bottom.
@@ -120,6 +137,13 @@ export function MessageList({
// older rows and leaves the tail id unchanged, so paging up never triggers
// a jump. Peer sends move the tail but with a different authorId — those
// stay on the "↓ N" pill path.
+ //
+ // The tail row can keep growing after the initial scrollTo — images
+ // decode, mermaid diagrams render, invite cards resolve — all shove the
+ // composer off the viewport. A ResizeObserver on the tail row re-pins to
+ // the bottom on every size change, regardless of the source. Bails once
+ // the user scrolls away (`wheel` / `touchstart`), so an image loading in
+ // the background never yanks a scrolled-up reader.
const lastTailIdRef = useRef<string | null>(null)
useLayoutEffect(() => {
const el = scrollRef.current
@@ -135,7 +159,14 @@ export function MessageList({
if (prev === tail.id) return
if (!viewerUserId) return
if (tail.authorId !== viewerUserId) return
- el.scrollTo({ top: el.scrollHeight, behavior: "smooth" })
+ // Instant, not smooth. `behavior: 'smooth'` conflicts with the RO
+ // re-pins below — the browser's ongoing smooth animation and our
+ // subsequent instant scrollTo race, and on some engines the smooth
+ // animation "wins" by continuing to its stored target after the
+ // instant jump lands, snapping the view back up.
+ const action = () => el.scrollTo({ top: el.scrollHeight })
+ action()
+ return watchAsyncGrowth(el, action)
}, [messages, viewerUserId])
// Live count of messages sitting below the viewport. Recomputed on scroll,
@@ -279,6 +310,71 @@ export function MessageList({
)
}
+// Re-invoke `action` whenever the scroll container's own size changes.
+// Serves both initial scroll (images decoding on a cold browser cache
+// arrive after the first scrollTo — target row was still short at that
+// moment) and self-send (composer stays in view when an image the user
+// just attached finishes decoding).
+//
+// Bails when:
+// - the user scrolls (wheel / touchstart — the only reliable "user
+// intent" signal during async growth; programmatic scroll fires its
+// own `scroll` events, so scrollTop comparisons can't distinguish).
+// - the watchdog window elapses (3s — long enough for large images and
+// mermaid renders, short enough that the effect doesn't linger).
+//
+// rAF coalescing: multiple ResizeObserver fires in the same frame
+// dispatch one `action` call. Without this, several images finishing
+// decode in one layout tick would each call `action` on an intermediate
+// scrollHeight before the browser settles on the final value.
+//
+// Returns a cleanup that owners MUST return from their effect.
+const ASYNC_GROWTH_WINDOW_MS = 3000
+function watchAsyncGrowth(el: HTMLElement, action: () => void): () => void {
+ // Observe the scroll container's FIRST child — the content wrapper.
+ // The scroll container itself has a fixed (`flex-1`) box; its size
+ // doesn't change when children grow. The wrapper does grow, and its
+ // border-box growth is what pushes `scrollHeight` up.
+ const content = el.firstElementChild as HTMLElement | null
+ if (!content) return () => {}
+
+ let userIntervened = false
+ const markIntervened = () => { userIntervened = true }
+ el.addEventListener("wheel", markIntervened, { passive: true })
+ el.addEventListener("touchstart", markIntervened, { passive: true })
+
+ // Skip the RO's synchronous initial callback (fired once with the
+ // current size at observe() time) — otherwise we'd re-run `action`
+ // against the pre-growth height and waste a frame.
+ let firstCallback = true
+ let rafId: number | null = null
+ const scheduleAction = () => {
+ if (rafId !== null) return
+ rafId = requestAnimationFrame(() => {
+ rafId = null
+ if (userIntervened) return
+ action()
+ })
+ }
+ const ro = new ResizeObserver(() => {
+ if (firstCallback) { firstCallback = false; return }
+ scheduleAction()
+ })
+ ro.observe(content)
+
+ const timeoutId = window.setTimeout(() => {
+ ro.disconnect()
+ }, ASYNC_GROWTH_WINDOW_MS)
+
+ return () => {
+ el.removeEventListener("wheel", markIntervened)
+ el.removeEventListener("touchstart", markIntervened)
+ if (rafId !== null) cancelAnimationFrame(rafId)
+ window.clearTimeout(timeoutId)
+ ro.disconnect()
+ }
+}
+
// Escape a message id for safe use inside an attribute selector. Message ids
// are nanoids in production (URL-safe alphabet), but the temp-id path
// (`temp_<Date.now()>_<rand>`) contains underscores that CSS accepts unescaped