Skip to content

armgit / alook

Public Imported from GitHub
0

Multi-Agent Collaboration for Team and Friends

fix(web): harden mobile community interactions

Gusa7f4975ad36a
diff --git a/src/web/src/app/globals.css b/src/web/src/app/globals.css
index 111b1c3c2..8dd9fbbf9 100644
--- a/src/web/src/app/globals.css
+++ b/src/web/src/app/globals.css
@@ -2688,6 +2688,14 @@ body {
scrollbar-color: var(--border) transparent;
}
+/* Chat text is intentionally copyable on iOS. Keep this scoped exception
+ stronger than the shell-wide callout suppression above; message actions
+ and menu labels remain separate controls with their own select-none styles. */
+[data-community-message-body] {
+ -webkit-touch-callout: default;
+ user-select: text;
+}
+
::-webkit-scrollbar {
width: 4px;
height: 4px;
diff --git a/src/web/src/components/agent-chat/agent-chat-view.tsx b/src/web/src/components/agent-chat/agent-chat-view.tsx
index fc6b0a401..6e49975cf 100644
--- a/src/web/src/components/agent-chat/agent-chat-view.tsx
+++ b/src/web/src/components/agent-chat/agent-chat-view.tsx
@@ -1127,7 +1127,7 @@ export function AgentChatView({
skills={slashCommand.skills}
selectedIndex={slashCommand.selectedIndex}
onSelect={slashCommand.selectSkill}
- anchorPos={slashCommand.anchorPos}
+ getAnchorRect={slashCommand.getAnchorRect}
/>
{/* Pending file previews — images and non-images in separate rows */}
{pendingFiles.length > 0 && (() => {
diff --git a/src/web/src/components/agent-chat/chat-composer.tsx b/src/web/src/components/agent-chat/chat-composer.tsx
index a88292c0c..26c8ca9e6 100644
--- a/src/web/src/components/agent-chat/chat-composer.tsx
+++ b/src/web/src/components/agent-chat/chat-composer.tsx
@@ -9,6 +9,11 @@ import {
type ReactNode,
} from "react";
import { useKeyboardScroll } from "@/hooks/use-keyboard-scroll";
+import {
+ anchoredPopoverStyle,
+ useAnchoredPopover,
+ type AnchorRect,
+} from "@/hooks/use-anchored-popover";
import { useEditor, EditorContent } from "@tiptap/react";
import StarterKit from "@tiptap/starter-kit";
import Placeholder from "@tiptap/extension-placeholder";
@@ -31,8 +36,8 @@ export interface ChatComposerHandle {
focus: () => void;
clear: () => void;
isEmpty: () => boolean;
- /** Viewport coords for a plain-text caret index — used to anchor the slash popup. */
- coordsAtTextIndex: (index: number) => { top: number; left: number } | null;
+ /** Viewport caret rect for a plain-text index — used to anchor the slash popup. */
+ coordsAtTextIndex: (index: number) => AnchorRect | null;
}
interface ChatComposerProps {
@@ -84,19 +89,20 @@ interface MentionPopupState {
items: Agent[];
selectedIndex: number;
command: ((props: { id: string; label: string }) => void) | null;
- rect: DOMRect | null;
+ getRect: (() => DOMRect | null) | null;
}
const EMPTY_MENTION_STATE: MentionPopupState = {
items: [],
selectedIndex: 0,
command: null,
- rect: null,
+ getRect: null,
};
function MentionList({ state }: { state: MentionPopupState }) {
const listRef = useRef<HTMLDivElement>(null);
- const { items, selectedIndex, command, rect } = state;
+ const { items, selectedIndex, command, getRect } = state;
+ const geometry = useAnchoredPopover(getRect, items.length > 0 && command !== null);
useEffect(() => {
if (!listRef.current) return;
@@ -104,22 +110,18 @@ function MentionList({ state }: { state: MentionPopupState }) {
el?.scrollIntoView({ block: "nearest" });
}, [selectedIndex]);
- if (!rect || items.length === 0 || !command) return null;
-
- // Popup is w-64 (256px). Clamp left so it never overflows the right edge (mobile).
- const POPUP_WIDTH = 256;
- const VIEWPORT_MARGIN = 8;
- const maxLeft = typeof window !== "undefined"
- ? Math.max(VIEWPORT_MARGIN, window.innerWidth - POPUP_WIDTH - VIEWPORT_MARGIN)
- : rect.left;
- const clampedLeft = Math.min(rect.left, maxLeft);
+ if (!geometry || items.length === 0 || !command) return null;
return createPortal(
<div
className="fixed z-100 w-64 rounded-lg border border-border bg-popover text-popover-foreground shadow-md"
- style={{ top: rect.top - 4, left: clampedLeft, transform: "translateY(-100%)" }}
+ style={anchoredPopoverStyle(geometry.rect, geometry.viewport, 256, 200)}
>
- <div ref={listRef} className="max-h-50 overflow-y-auto py-1 thin-scrollbar">
+ <div
+ ref={listRef}
+ className="overflow-y-auto py-1 thin-scrollbar"
+ style={{ maxHeight: "var(--anchored-popover-max-height)" }}
+ >
{items.map((agent, i) => (
<button
key={agent.id}
@@ -291,7 +293,7 @@ export const ChatComposer = forwardRef<ChatComposerHandle, ChatComposerProps>(
items: props.items ?? [],
selectedIndex: 0,
command: props.command,
- rect: props.clientRect?.() ?? null,
+ getRect: props.clientRect ?? null,
});
},
onUpdate: (props: MentionSuggestionProps) => {
@@ -300,7 +302,7 @@ export const ChatComposer = forwardRef<ChatComposerHandle, ChatComposerProps>(
selectedIndex:
cur.selectedIndex < (props.items?.length ?? 0) ? cur.selectedIndex : 0,
command: props.command,
- rect: props.clientRect?.() ?? null,
+ getRect: props.clientRect ?? null,
}));
},
onKeyDown: ({ event }: { event: KeyboardEvent }) => {
@@ -499,7 +501,12 @@ export const ChatComposer = forwardRef<ChatComposerHandle, ChatComposerProps>(
try {
// +1: plain-text index is 0-based; PM positions start at 1.
const coords = editor.view.coordsAtPos(index + 1);
- return { top: coords.top, left: coords.left };
+ return {
+ top: coords.top,
+ bottom: coords.bottom,
+ left: coords.left,
+ right: coords.right,
+ };
} catch {
return null;
}
diff --git a/src/web/src/components/agent-chat/slash-command-popup.tsx b/src/web/src/components/agent-chat/slash-command-popup.tsx
index b0a6abb39..030616c2c 100644
--- a/src/web/src/components/agent-chat/slash-command-popup.tsx
+++ b/src/web/src/components/agent-chat/slash-command-popup.tsx
@@ -2,13 +2,18 @@ import React, { useRef, useEffect } from "react"
import { createPortal } from "react-dom"
import type { SkillEntry } from "@alook/shared"
import { cn } from "@/lib/utils"
+import {
+ anchoredPopoverStyle,
+ useAnchoredPopover,
+ type AnchorRectResolver,
+} from "@/hooks/use-anchored-popover"
interface SlashCommandPopupProps {
isOpen: boolean
skills: SkillEntry[]
selectedIndex: number
onSelect: (skill: SkillEntry) => void
- anchorPos: { top: number; left: number }
+ getAnchorRect: AnchorRectResolver
}
function SkillRow({
@@ -50,8 +55,9 @@ function SkillRow({
)
}
-export function SlashCommandPopup({ isOpen, skills, selectedIndex, onSelect, anchorPos }: SlashCommandPopupProps) {
+export function SlashCommandPopup({ isOpen, skills, selectedIndex, onSelect, getAnchorRect }: SlashCommandPopupProps) {
const listRef = useRef<HTMLDivElement>(null)
+ const geometry = useAnchoredPopover(getAnchorRect, isOpen && skills.length > 0)
useEffect(() => {
if (!listRef.current) return
@@ -60,26 +66,18 @@ export function SlashCommandPopup({ isOpen, skills, selectedIndex, onSelect, anc
selected?.scrollIntoView({ block: "nearest" })
}, [selectedIndex])
- if (!isOpen || skills.length === 0) return null
-
- // Popup is w-70 (280px). Clamp left so it never overflows the right edge (mobile).
- const POPUP_WIDTH = 280
- const VIEWPORT_MARGIN = 8
- const maxLeft = typeof window !== "undefined"
- ? Math.max(VIEWPORT_MARGIN, window.innerWidth - POPUP_WIDTH - VIEWPORT_MARGIN)
- : anchorPos.left
- const clampedLeft = Math.min(anchorPos.left, maxLeft)
+ if (!isOpen || skills.length === 0 || !geometry) return null
return createPortal(
<div
className="fixed z-100 w-70 rounded-lg border border-border bg-popover text-popover-foreground shadow-md transition-opacity duration-150"
- style={{
- top: anchorPos.top - 4,
- left: clampedLeft,
- transform: "translateY(-100%)",
- }}
+ style={anchoredPopoverStyle(geometry.rect, geometry.viewport, 280, 240)}
>
- <div ref={listRef} className="max-h-60 overflow-y-auto py-1 thin-scrollbar">
+ <div
+ ref={listRef}
+ className="overflow-y-auto py-1 thin-scrollbar"
+ style={{ maxHeight: "var(--anchored-popover-max-height)" }}
+ >
{skills.map((skill, i) => (
<SkillRow
key={skill.name}
diff --git a/src/web/src/components/community/messages/composer-facade.contract.test.ts b/src/web/src/components/community/messages/composer-facade.contract.test.ts
index 25d634ffa..9b39dbc6a 100644
--- a/src/web/src/components/community/messages/composer-facade.contract.test.ts
+++ b/src/web/src/components/community/messages/composer-facade.contract.test.ts
@@ -24,7 +24,7 @@ describe("Composer public facade", () => {
>()
})
- it("retains the original-path eight-export facade", () => {
+ it("retains the original-path seven-export facade", () => {
const source = readWeb("src/components/community/messages/composer.tsx")
const namesFromBlocks = (pattern: RegExp) =>
[...source.matchAll(pattern)].flatMap((match) =>
@@ -49,7 +49,6 @@ describe("Composer public facade", () => {
"ComposerSkeleton",
"pendingFilesToSendAttachments",
"clipboardFiles",
- "popoverStyle",
]),
)
expect(source).not.toMatch(/export\s+(?:default|\*)/)
diff --git a/src/web/src/components/community/messages/composer-suggestion-popups.test.ts b/src/web/src/components/community/messages/composer-suggestion-popups.test.ts
index ac5534d8d..acc0e00a5 100644
--- a/src/web/src/components/community/messages/composer-suggestion-popups.test.ts
+++ b/src/web/src/components/community/messages/composer-suggestion-popups.test.ts
@@ -24,7 +24,6 @@ vi.mock("../channels/channel-icon", () => ({
import {
ChannelRefList,
CommunityMentionList,
- popoverStyle,
} from "./composer-suggestion-popups"
import {
EMPTY_CHANNEL_REF_STATE,
@@ -59,6 +58,17 @@ describe("Composer suggestion popups", () => {
beforeEach(() => {
const body = { nodeName: "BODY" }
vi.stubGlobal("document", { body })
+ vi.stubGlobal("window", {
+ innerWidth: 1024,
+ innerHeight: 768,
+ addEventListener: vi.fn(),
+ removeEventListener: vi.fn(),
+ requestAnimationFrame: vi.fn((callback: FrameRequestCallback) => {
+ callback(0)
+ return 1
+ }),
+ cancelAnimationFrame: vi.fn(),
+ })
mocks.createPortal.mockReset()
mocks.createPortal.mockImplementation((node) => node)
mocks.nextScrollTop.mockReset()
@@ -92,7 +102,7 @@ describe("Composer suggestion popups", () => {
items: [{ kind: "everyone", id: "everyone", label: "everyone" }],
selectedIndex: 0,
command: vi.fn(),
- rect: rect(500),
+ getRect: () => rect(500),
},
}),
)
@@ -103,15 +113,6 @@ describe("Composer suggestion popups", () => {
document.body,
)
- expect(popoverStyle(rect(500), 1024, 768)).toEqual({
- top: 496,
- left: 40,
- transform: "translateY(-100%)",
- })
- expect(popoverStyle(rect(100, 1000), 1024, 768)).toEqual({
- top: 120,
- left: 760,
- })
})
it("renders virtual/member rows in order and selects on mousedown", async () => {
@@ -132,7 +133,7 @@ describe("Composer suggestion popups", () => {
],
selectedIndex: 1,
command,
- rect: rect(500),
+ getRect: () => rect(500),
}
let renderer!: TestRenderer.ReactTestRenderer
await act(async () => {
@@ -140,7 +141,7 @@ describe("Composer suggestion popups", () => {
createElement(CommunityMentionList, { state }),
{
createNodeMock: (element) =>
- element.props.className?.includes("max-h-60") ? listNode : {},
+ element.props.className?.includes("overflow-y-auto") ? listNode : {},
},
)
})
@@ -190,13 +191,13 @@ describe("Composer suggestion popups", () => {
],
selectedIndex: 0,
command,
- rect: rect(500),
+ getRect: () => rect(500),
}
let renderer!: TestRenderer.ReactTestRenderer
await act(async () => {
renderer = TestRenderer.create(createElement(ChannelRefList, { state }), {
createNodeMock: (element) =>
- element.props.className?.includes("max-h-60") ? listNode : {},
+ element.props.className?.includes("overflow-y-auto") ? listNode : {},
})
})
const prefixes = renderer.root
diff --git a/src/web/src/components/community/messages/composer-suggestion-popups.tsx b/src/web/src/components/community/messages/composer-suggestion-popups.tsx
index 93c53a9fd..0fcd5efd7 100644
--- a/src/web/src/components/community/messages/composer-suggestion-popups.tsx
+++ b/src/web/src/components/community/messages/composer-suggestion-popups.tsx
@@ -1,6 +1,10 @@
-import { useEffect, useRef, type CSSProperties } from "react"
+import { useEffect, useRef } from "react"
import { createPortal } from "react-dom"
import { Users } from "lucide-react"
+import {
+ anchoredPopoverStyle,
+ useAnchoredPopover,
+} from "@/hooks/use-anchored-popover"
import { Avatar } from "../avatar"
import { ChannelIcon } from "../channels/channel-icon"
import { nextListScrollTop } from "@/lib/community/popup-scroll"
@@ -17,32 +21,6 @@ import type {
const POPUP_WIDTH = 256
const POPUP_MAX_HEIGHT = 240
-const VIEWPORT_MARGIN = 8
-
-export function popoverStyle(
- rect: DOMRect,
- viewportWidth: number,
- viewportHeight: number,
-): CSSProperties {
- const maxLeft = Math.max(
- VIEWPORT_MARGIN,
- viewportWidth - POPUP_WIDTH - VIEWPORT_MARGIN,
- )
- const left = Math.min(rect.left, maxLeft)
- const flipBelow =
- rect.top < POPUP_MAX_HEIGHT + VIEWPORT_MARGIN &&
- rect.bottom + POPUP_MAX_HEIGHT + VIEWPORT_MARGIN <= viewportHeight
- return flipBelow
- ? { top: rect.bottom + 4, left }
- : { top: rect.top - 4, left, transform: "translateY(-100%)" }
-}
-
-function viewportSize(): { w: number; h: number } {
- if (typeof window === "undefined") {
- return { w: POPUP_WIDTH, h: POPUP_MAX_HEIGHT }
- }
- return { w: window.innerWidth, h: window.innerHeight }
-}
function scrollSelectedRowIntoView(list: HTMLDivElement | null): void {
if (!list) return
@@ -62,25 +40,33 @@ export function CommunityMentionList({
state: MentionPopupState
}) {
const listRef = useRef<HTMLDivElement>(null)
- const { items, selectedIndex, command, rect } = state
+ const { items, selectedIndex, command, getRect } = state
+ const geometry = useAnchoredPopover(
+ getRect,
+ items.length > 0 && command !== null,
+ )
useEffect(() => {
scrollSelectedRowIntoView(listRef.current)
- }, [selectedIndex])
- if (!rect || items.length === 0 || !command) return null
+ }, [selectedIndex, geometry])
+ if (!geometry || items.length === 0 || !command) return null
const firstMemberIndex = items.findIndex((item) => item.kind === "member")
const hasVirtual = items.some((item) => item.kind !== "member")
const showMembersHeader = hasVirtual && firstMemberIndex > 0
- const viewport = viewportSize()
-
return createPortal(
<div
className="fixed z-100 w-64 rounded-lg border border-border bg-popover p-1 text-popover-foreground shadow-(--e2)"
- style={popoverStyle(rect, viewport.w, viewport.h)}
+ style={anchoredPopoverStyle(
+ geometry.rect,
+ geometry.viewport,
+ POPUP_WIDTH,
+ POPUP_MAX_HEIGHT,
+ )}
>
<div
ref={listRef}
- className="relative max-h-60 overflow-x-hidden overflow-y-auto thin-scrollbar"
+ className="relative overflow-x-hidden overflow-y-auto thin-scrollbar"
+ style={{ maxHeight: "var(--anchored-popover-max-height)" }}
>
{items.map((item, index) => (
<MentionRow
@@ -101,24 +87,33 @@ export function CommunityMentionList({
export function ChannelRefList({ state }: { state: ChannelRefPopupState }) {
const listRef = useRef<HTMLDivElement>(null)
- const { items, selectedIndex, command, rect } = state
+ const { items, selectedIndex, command, getRect } = state
+ const geometry = useAnchoredPopover(
+ getRect,
+ items.length > 0 && command !== null,
+ )
useEffect(() => {
scrollSelectedRowIntoView(listRef.current)
- }, [selectedIndex])
- if (!rect || items.length === 0 || !command) return null
+ }, [selectedIndex, geometry])
+ if (!geometry || items.length === 0 || !command) return null
const spansMultipleServers = items.some(
(item) => item.serverId !== items[0]?.serverId,
)
- const viewport = viewportSize()
return createPortal(
<div
className="fixed z-100 w-64 rounded-lg border border-border bg-popover p-1 text-popover-foreground shadow-(--e2)"
- style={popoverStyle(rect, viewport.w, viewport.h)}
+ style={anchoredPopoverStyle(
+ geometry.rect,
+ geometry.viewport,
+ POPUP_WIDTH,
+ POPUP_MAX_HEIGHT,
+ )}
>
<div
ref={listRef}
- className="relative max-h-60 overflow-x-hidden overflow-y-auto thin-scrollbar"
+ className="relative overflow-x-hidden overflow-y-auto thin-scrollbar"
+ style={{ maxHeight: "var(--anchored-popover-max-height)" }}
>
{items.map((item, index) => (
<ChannelRefRow
diff --git a/src/web/src/components/community/messages/composer.send-lifecycle.test.ts b/src/web/src/components/community/messages/composer.send-lifecycle.test.ts
index dbbcad8d4..a2b010e36 100644
--- a/src/web/src/components/community/messages/composer.send-lifecycle.test.ts
+++ b/src/web/src/components/community/messages/composer.send-lifecycle.test.ts
@@ -27,13 +27,13 @@ vi.mock("@tiptap/pm/model", () => ({
vi.mock("@/lib/community/mention-extension", () => ({
buildCommunityMentionExtension: vi.fn(() => ({})),
detectMentionType: vi.fn(() => undefined),
- EMPTY_MENTION_STATE: { items: [], selectedIndex: 0, command: null, rect: null },
+ EMPTY_MENTION_STATE: { items: [], selectedIndex: 0, command: null, getRect: null },
rankMentionItems: vi.fn(() => []),
}))
vi.mock("@/lib/community/channel-ref-extension", () => ({
buildCommunityChannelRefExtension: vi.fn(() => ({})),
- EMPTY_CHANNEL_REF_STATE: { items: [], selectedIndex: 0, command: null, rect: null },
+ EMPTY_CHANNEL_REF_STATE: { items: [], selectedIndex: 0, command: null, getRect: null },
rankChannelRefItems: vi.fn(() => []),
toChannelRefCommandProps: vi.fn(),
}))
diff --git a/src/web/src/components/community/messages/composer.test.ts b/src/web/src/components/community/messages/composer.test.ts
index 9ebd3d116..e3fa0d72f 100644
--- a/src/web/src/components/community/messages/composer.test.ts
+++ b/src/web/src/components/community/messages/composer.test.ts
@@ -1,5 +1,5 @@
import { describe, it, expect } from "vitest"
-import { clipboardFiles, pendingFilesToSendAttachments, popoverStyle } from "./composer"
+import { clipboardFiles, pendingFilesToSendAttachments } from "./composer"
import type { ComposerProps } from "./composer"
import type { PendingFile } from "@/hooks/use-file-attachments"
@@ -38,22 +38,6 @@ function itemList(entries: Array<{ kind: string; file: File | null }>): DataTran
return list
}
-function rectAt(top: number, opts: { left?: number; height?: number } = {}): DOMRect {
- const height = opts.height ?? 16
- const left = opts.left ?? 40
- return {
- top,
- bottom: top + height,
- left,
- right: left + 4,
- width: 4,
- height,
- x: left,
- y: top,
- toJSON() {},
- }
-}
-
// `pendingFilesToSendAttachments` is the pure mapping Composer.send() uses
// to build onSend's attachments argument — extracted so the width/height
// threading can be unit-tested without mounting the full tiptap editor
@@ -141,39 +125,3 @@ describe("clipboardFiles", () => {
expect(clipboardFiles(list)).toEqual([png])
})
})
-
-describe("popoverStyle", () => {
- const VW = 1024
- const VH = 768
-
- it("anchors above the caret (default) when there's room above", () => {
- const s = popoverStyle(rectAt(500), VW, VH)
- expect(s.transform).toBe("translateY(-100%)")
- expect(s.top).toBe(500 - 4)
- })
-
- it("flips below the caret when space above is insufficient (caret near viewport top)", () => {
- const s = popoverStyle(rectAt(100, { height: 16 }), VW, VH)
- // 100px above < 240+8, and below has room → flip
- expect(s.transform).toBeUndefined()
- expect(s.top).toBe(116 + 4) // rect.bottom + 4
- })
-
- it("stays above when neither side fully fits, rather than flipping into a worse spot", () => {
- // Short viewport: no room above (top=100) and no room below either.
- const s = popoverStyle(rectAt(100, { height: 16 }), VW, 200)
- // below would overflow (116+240+8 > 200) → keep the above default
- expect(s.transform).toBe("translateY(-100%)")
- })
-
- it("clamps left so the 256px popup never runs off the right edge", () => {
- const s = popoverStyle(rectAt(500, { left: 1000 }), VW, VH)
- // maxLeft = 1024 - 256 - 8 = 760
- expect(s.left).toBe(760)
- })
-
- it("keeps the caret's left when it's within bounds", () => {
- const s = popoverStyle(rectAt(500, { left: 40 }), VW, VH)
- expect(s.left).toBe(40)
- })
-})
diff --git a/src/web/src/components/community/messages/composer.tsx b/src/web/src/components/community/messages/composer.tsx
index 5ba190979..d983499c3 100644
--- a/src/web/src/components/community/messages/composer.tsx
+++ b/src/web/src/components/community/messages/composer.tsx
@@ -12,7 +12,6 @@ export {
clipboardFiles,
pendingFilesToSendAttachments,
} from "./composer-file-utils"
-export { popoverStyle } from "./composer-suggestion-popups"
export { ComposerSkeleton }
export const Composer = forwardRef<ComposerHandle, ComposerProps>(
diff --git a/src/web/src/components/community/messages/message-body.tsx b/src/web/src/components/community/messages/message-body.tsx
index 607235af7..d0cbb772e 100644
--- a/src/web/src/components/community/messages/message-body.tsx
+++ b/src/web/src/components/community/messages/message-body.tsx
@@ -107,7 +107,10 @@ function MessageBodyImpl({
[onOpenProfile],
)
return (
- <div className="markdown markdown-chat wrap-anywhere text-[15px] leading-snug text-foreground">
+ <div
+ data-community-message-body
+ className="markdown markdown-chat wrap-anywhere select-text text-[15px] leading-snug text-foreground"
+ >
<Streamdown
parseIncompleteMarkdown={false}
plugins={{ mermaid, cjk, math }}
diff --git a/src/web/src/components/community/messages/message-context-sheet.tsx b/src/web/src/components/community/messages/message-context-sheet.tsx
index ad3108335..de15c5173 100644
--- a/src/web/src/components/community/messages/message-context-sheet.tsx
+++ b/src/web/src/components/community/messages/message-context-sheet.tsx
@@ -20,6 +20,7 @@ import { useUiHandlers } from "@/stores/community"
import { usePinMessage, useUnpinMessage, useCreateThread, useToggleMark } from "@/hooks/community/mutations"
import type { FileAttachment, ImagePreview, MessagesPage, Msg, Reaction, RenderMsg } from "@/lib/community/models/message"
import type { OpenProfile } from "@/components/community/social/profile-types"
+import { useHoverCapable } from "@/hooks/use-hover-capable"
export type ReplyTarget = { id: string; authorName: string; text: string }
@@ -482,6 +483,7 @@ function ContextRows({
onPreviewAttachment: (attachment: FileAttachment) => void
onDownloadFile: (url: string, name: string) => void
}) {
+ const hoverCapable = useHoverCapable()
// Single-message share from the peek sheet. The sheet has no select-mode
// context (it's a read-only preview), so Share opens the dialog directly on
// the clicked row — via `onShareSingle`, independent of the list's select-mode
@@ -510,6 +512,7 @@ function ContextRows({
<div data-anchor-row={isTarget ? "1" : undefined}>
<MessageRow
m={m}
+ hoverCapable={hoverCapable}
viewerUserId={viewerUserId}
pinned={pinnedIds?.has(m.id)}
highlighted={isTarget}
diff --git a/src/web/src/components/community/messages/message-list-row.tsx b/src/web/src/components/community/messages/message-list-row.tsx
index 7d68031c6..1497eee7a 100644
--- a/src/web/src/components/community/messages/message-list-row.tsx
+++ b/src/web/src/components/community/messages/message-list-row.tsx
@@ -18,6 +18,7 @@ export function renderMessageListRow(
<div data-msg-id={item.m.id} data-testid={tid.message(item.m.id)}>
<MessageRow
m={item.m}
+ hoverCapable={props.hoverCapable}
viewerUserId={props.viewerUserId}
pinned={props.pinnedIds?.has(item.m.id)}
highlighted={controller.jumped === item.m.id}
diff --git a/src/web/src/components/community/messages/message-list-types.ts b/src/web/src/components/community/messages/message-list-types.ts
index 3634a8f66..0e723ec49 100644
--- a/src/web/src/components/community/messages/message-list-types.ts
+++ b/src/web/src/components/community/messages/message-list-types.ts
@@ -46,4 +46,5 @@ export type MessageListProps = {
export type ResolvedMessageListProps = MessageListProps & {
variant: "channel" | "dm"
initialScrollReady: boolean
+ hoverCapable: boolean
}
diff --git a/src/web/src/components/community/messages/message-list.tsx b/src/web/src/components/community/messages/message-list.tsx
index ce65f93d5..9bdfb2d28 100644
--- a/src/web/src/components/community/messages/message-list.tsx
+++ b/src/web/src/components/community/messages/message-list.tsx
@@ -1,6 +1,7 @@
"use client"
import { useMessageListController } from "./message-list-controller"
+import { useHoverCapable } from "@/hooks/use-hover-capable"
import type { MessageListProps, ResolvedMessageListProps } from "./message-list-types"
import { renderMessageListRow } from "./message-list-row"
import { renderMessageListView } from "./message-list-view"
@@ -11,10 +12,12 @@ export function MessageList({
initialScrollReady = true,
...props
}: MessageListProps) {
+ const hoverCapable = useHoverCapable()
const resolvedProps: ResolvedMessageListProps = {
...props,
variant,
initialScrollReady,
+ hoverCapable,
}
const controller = useMessageListController(resolvedProps)
return renderMessageListView(resolvedProps, controller, () => (
diff --git a/src/web/src/components/community/messages/message-menu.tsx b/src/web/src/components/community/messages/message-menu.tsx
index 4fdddca39..8f18eb655 100644
--- a/src/web/src/components/community/messages/message-menu.tsx
+++ b/src/web/src/components/community/messages/message-menu.tsx
@@ -80,11 +80,19 @@ export function MessageContextItems(props: MessageMenuHandlers) {
)
}
-export function MessageDropdownItems(props: MessageMenuHandlers) {
+export function MessageDropdownItems({
+ touch = false,
+ ...props
+}: MessageMenuHandlers & { touch?: boolean }) {
return (
<>
{messageMenuItems(props).map((it) => (
- <DropdownMenuItem key={it.label} onClick={it.onClick} variant={it.danger ? "destructive" : "default"}>
+ <DropdownMenuItem
+ key={it.label}
+ onClick={it.onClick}
+ variant={it.danger ? "destructive" : "default"}
+ className={touch ? "min-h-11" : undefined}
+ >
<IconSlot icon={it.icon} /> {it.label}
</DropdownMenuItem>
))}
diff --git a/src/web/src/components/community/messages/message-row.tsx b/src/web/src/components/community/messages/message-row.tsx
index 4f90b5d5e..6d76be224 100644
--- a/src/web/src/components/community/messages/message-row.tsx
+++ b/src/web/src/components/community/messages/message-row.tsx
@@ -19,6 +19,7 @@ import type { OpenProfile } from "@/components/community/social/profile-types"
export interface MessageRowProps {
m: RenderMsg
viewerUserId?: string
+ hoverCapable: boolean
pinned?: boolean
highlighted?: boolean
onOpenThread: (id: string) => void
@@ -53,7 +54,7 @@ export interface MessageRowProps {
function MessageRowImpl(props: MessageRowProps) {
const {
- m, viewerUserId, pinned, highlighted, onOpenThread, onOpenProfile,
+ m, viewerUserId, hoverCapable, pinned, highlighted, onOpenThread, onOpenProfile,
onToggleReactionId, onReactId, onReplyId, onPinId, onMarkId, onCreateThreadId,
onCopyId, onEditId, onRetryId, onDismissId, onJumpToId, onPreviewImage, onPreviewAttachment, onDownloadFile,
resolveUserName, onImageLoad,
@@ -92,6 +93,7 @@ function MessageRowImpl(props: MessageRowProps) {
<Message
m={m}
viewerUserId={viewerUserId}
+ hoverCapable={hoverCapable}
pinned={pinned}
highlighted={highlighted}
onOpenThread={onOpenThread}
diff --git a/src/web/src/components/community/messages/message-share-dialog.test.ts b/src/web/src/components/community/messages/message-share-dialog.test.ts
index 61eb486a4..7af9f6ec9 100644
--- a/src/web/src/components/community/messages/message-share-dialog.test.ts
+++ b/src/web/src/components/community/messages/message-share-dialog.test.ts
@@ -1,7 +1,11 @@
import { describe, expect, it, vi } from "vitest"
import React from "react"
import TestRenderer, { act } from "react-test-renderer"
-import { MessageShareDialog } from "./message-share-dialog"
+import {
+ MessageShareDialog,
+ ShareCardImageTimeoutError,
+ waitForShareCardImages,
+} from "./message-share-dialog"
import type { RenderMsg } from "@/lib/community/models/message"
vi.mock("html-to-image", () => ({ toBlob: vi.fn() }))
@@ -45,6 +49,16 @@ function renderMessage(m: RenderMsg) {
}
describe("MessageShareDialog message context", () => {
+ it("passes the custom avatar URL as an image source, not as fallback copy", () => {
+ const renderer = renderMessage(message({ authorAvatar: "/api/community/users/u1/avatar" }))
+ const avatar = renderer.root.findByType("mock-avatar")
+ expect(avatar.props).toMatchObject({
+ label: "Alice",
+ src: "/api/community/users/u1/avatar",
+ seed: "u1",
+ })
+ })
+
it("renders the reply author and plain-text excerpt above the shared message", () => {
const renderer = renderMessage(message({
replyTo: {
@@ -148,3 +162,97 @@ describe("MessageShareDialog message context", () => {
expect(contexts).toHaveLength(0)
})
})
+
+describe("waitForShareCardImages", () => {
+ function image(overrides: Partial<HTMLImageElement> = {}) {
+ const listeners = new Map<string, () => void>()
+ const value = {
+ complete: false,
+ naturalWidth: 0,
+ decode: vi.fn().mockResolvedValue(undefined),
+ addEventListener: vi.fn((type: string, listener: () => void) => listeners.set(type, listener)),
+ removeEventListener: vi.fn((type: string) => listeners.delete(type)),
+ ...overrides,
+ } as unknown as HTMLImageElement
+ return { value, listeners }
+ }
+
+ function card(images: HTMLImageElement[]): HTMLElement {
+ return { querySelectorAll: () => images } as unknown as HTMLElement
+ }
+
+ it("waits for a pending avatar load, decodes it, and yields a paint", async () => {
+ const avatar = image()
+ const paint = vi.fn().mockResolvedValue(undefined)
+ const waiting = waitForShareCardImages(card([avatar.value]), paint)
+
+ expect(paint).not.toHaveBeenCalled()
+ Object.defineProperty(avatar.value, "naturalWidth", { value: 40 })
+ avatar.listeners.get("load")?.()
+ await waiting
+
+ expect(avatar.value.decode).toHaveBeenCalledOnce()
+ expect(paint).toHaveBeenCalledOnce()
+ })
+
+ it("continues after an image error so Base UI can paint its fallback", async () => {
+ const avatar = image()
+ const paint = vi.fn().mockResolvedValue(undefined)
+ const waiting = waitForShareCardImages(card([avatar.value]), paint)
+ avatar.listeners.get("error")?.()
+ await waiting
+
+ expect(avatar.value.decode).not.toHaveBeenCalled()
+ expect(paint).toHaveBeenCalledOnce()
+ })
+
+ it("decodes an already-loaded cached avatar without waiting for another event", async () => {
+ const avatar = image({ complete: true, naturalWidth: 40 })
+ const paint = vi.fn().mockResolvedValue(undefined)
+ await waitForShareCardImages(card([avatar.value]), paint)
+
+ expect(avatar.value.addEventListener).not.toHaveBeenCalled()
+ expect(avatar.value.decode).toHaveBeenCalledOnce()
+ expect(paint).toHaveBeenCalledOnce()
+ })
+
+ it("rejects a pending-forever image within the bound and removes its listeners", async () => {
+ vi.useFakeTimers()
+ try {
+ const avatar = image()
+ const paint = vi.fn().mockResolvedValue(undefined)
+ const waiting = waitForShareCardImages(card([avatar.value]), paint, 50)
+ const rejected = expect(waiting).rejects.toBeInstanceOf(ShareCardImageTimeoutError)
+
+ await vi.advanceTimersByTimeAsync(50)
+ await rejected
+
+ expect(avatar.value.removeEventListener).toHaveBeenCalledWith("load", expect.any(Function))
+ expect(avatar.value.removeEventListener).toHaveBeenCalledWith("error", expect.any(Function))
+ expect(paint).not.toHaveBeenCalled()
+ } finally {
+ vi.useRealTimers()
+ }
+ })
+
+ it("bounds a pending-forever decode and degrades to the loaded bitmap", async () => {
+ vi.useFakeTimers()
+ try {
+ const avatar = image({
+ complete: true,
+ naturalWidth: 40,
+ decode: vi.fn(() => new Promise<void>(() => {})),
+ })
+ const paint = vi.fn().mockResolvedValue(undefined)
+ const waiting = waitForShareCardImages(card([avatar.value]), paint, 50)
+
+ await vi.advanceTimersByTimeAsync(50)
+ await waiting
+
+ expect(avatar.value.decode).toHaveBeenCalledOnce()
+ expect(paint).toHaveBeenCalledOnce()
+ } finally {
+ vi.useRealTimers()
+ }
+ })
+})
diff --git a/src/web/src/components/community/messages/message-share-dialog.tsx b/src/web/src/components/community/messages/message-share-dialog.tsx
index 7ed91baaa..5442755c3 100644
--- a/src/web/src/components/community/messages/message-share-dialog.tsx
+++ b/src/web/src/components/community/messages/message-share-dialog.tsx
@@ -15,6 +15,84 @@ import { tid } from "@/lib/community/testids"
import { applyHighlightToRange, clearHighlights, hasHighlights } from "@/lib/community/highlight-range"
import type { RenderMsg } from "@/lib/community/models/message"
+const SHARE_IMAGE_READY_TIMEOUT_MS = 5_000
+
+export class ShareCardImageTimeoutError extends Error {
+ constructor() {
+ super("A share-card image did not finish loading in time")
+ this.name = "ShareCardImageTimeoutError"
+ }
+}
+
+async function waitForImageLoad(
+ image: HTMLImageElement,
+ timeoutMs: number,
+): Promise<void> {
+ if (!image.complete) {
+ const settled = await new Promise<boolean>((resolve) => {
+ let finished = false
+ const finish = (didSettle: boolean) => {
+ if (finished) return
+ finished = true
+ image.removeEventListener("load", settle)
+ image.removeEventListener("error", settle)
+ clearTimeout(timer)
+ resolve(didSettle)
+ }
+ const settle = () => finish(true)
+ const timer = setTimeout(() => finish(false), timeoutMs)
+ image.addEventListener("load", settle, { once: true })
+ image.addEventListener("error", settle, { once: true })
+ // Close the tiny race where the resource settles between the initial
+ // `complete` read and listener registration.
+ if (image.complete) settle()
+ })
+ // A request that never emits load/error must fail this capture attempt so
+ // Download/Copy leave their busy state and the user can retry; capturing
+ // the avatar's transient empty branch would silently recreate the bug.
+ if (!settled) throw new ShareCardImageTimeoutError()
+ }
+ if (image.naturalWidth > 0 && image.decode) {
+ // Once load has supplied a real bitmap, decode() is only an optimization.
+ // Mobile WebKit may reject or never resolve it for cached images, so bound
+ // this wait and degrade to the already-loaded bitmap instead of deadlocking.
+ await new Promise<void>((resolve) => {
+ let finished = false
+ const finish = () => {
+ if (finished) return
+ finished = true
+ clearTimeout(timer)
+ resolve()
+ }
+ const timer = setTimeout(finish, timeoutMs)
+ Promise.resolve().then(() => image.decode()).then(finish, finish)
+ })
+ }
+}
+
+function nextPaint(): Promise<void> {
+ if (typeof requestAnimationFrame !== "function") return Promise.resolve()
+ return new Promise((resolve) => requestAnimationFrame(() => resolve()))
+}
+
+/**
+ * Base UI's photo avatar has a transient loading state where its root contains
+ * neither the photo nor the fallback. Desktop usually hits a warm cache;
+ * mobile share can rasterise during that gap and permanently export a blank
+ * circle. Settle every card image, then yield a paint so the avatar's loaded or
+ * fallback branch commits before html-to-image clones computed styles.
+ */
+export async function waitForShareCardImages(
+ node: HTMLElement,
+ waitForPaint: () => Promise<void> = nextPaint,
+ timeoutMs = SHARE_IMAGE_READY_TIMEOUT_MS,
+): Promise<void> {
+ await Promise.all(
+ [...node.querySelectorAll("img")].map((image) => waitForImageLoad(image, timeoutMs)),
+ )
+ await waitForPaint()
+}
+
// Share one OR several messages as an image. Renders a self-contained "share
// card" that mirrors the in-app message blob(s) (avatar / name / content — NO
// timestamp, per spec) plus an Alook brand footer, then rasterises THAT SAME
@@ -78,6 +156,7 @@ export function MessageShareDialog({ m, open, onClose }: {
const render = async (): Promise<Blob | null> => {
const node = cardRef.current
if (!node) return null
+ await waitForShareCardImages(node)
// Guarantee the Caveat brand font is loaded BEFORE rasterising. html-to-image
// inlines webfonts into the SVG it draws; if Caveat's async @font-face hasn't
// resolved yet, the footer silently falls back to a default font and the PNG
@@ -100,6 +179,7 @@ export function MessageShareDialog({ m, open, onClose }: {
// path that would drop the avatar from the PNG. Beam fallbacks are our own
// inline SVG, so they're unaffected either way.
cacheBust: true,
+ fetchRequestInit: { credentials: "same-origin" },
// Solid backdrop so the exported PNG never bleeds transparent corners
// (the card's own rounded bg sits on top of this).
backgroundColor: getComputedStyle(node).getPropertyValue("--card")?.trim() || undefined,
@@ -191,7 +271,7 @@ export function MessageShareDialog({ m, open, onClose }: {
<div className="flex gap-3">
{msg.grouped
? <div className="w-10 shrink-0" aria-hidden />
- : <Avatar label={msg.authorAvatar ?? "?"} seed={msg.authorId} size={40} />}
+ : <Avatar label={msg.authorName ?? "Unknown"} src={msg.authorAvatar} seed={msg.authorId} size={40} />}
<div className="min-w-0 flex-1">
{!msg.grouped && (
<div
diff --git a/src/web/src/components/community/messages/message.render.test.ts b/src/web/src/components/community/messages/message.render.test.ts
index c0c3a9c37..0f7da1ff8 100644
--- a/src/web/src/components/community/messages/message.render.test.ts
+++ b/src/web/src/components/community/messages/message.render.test.ts
@@ -1,8 +1,13 @@
import { describe, it, expect, vi, beforeEach, afterEach } from "vitest"
+import { readFileSync } from "node:fs"
import React from "react"
import TestRenderer, { act } from "react-test-renderer"
import { QueryClient, QueryClientProvider } from "@tanstack/react-query"
-import { Message, shouldActivateMessageOverlays } from "./message"
+import {
+ Message,
+ shouldActivateMessageOverlays,
+ shouldSuppressTouchMenuOpen,
+} from "./message"
import type { RenderMsg } from "@/lib/community/models/message"
// WS3 render-behavior tests (see plans/community-switch-perf-optimization.md):
@@ -122,6 +127,82 @@ describe("Message memo comparator", () => {
})
})
+describe("Message touch action menu", () => {
+ it("uses a tap dropdown and does not mount a long-press context-menu trigger", async () => {
+ let renderer: TestRenderer.ReactTestRenderer | undefined
+ await act(async () => {
+ renderer = TestRenderer.create(
+ makeTree({
+ m: baseMsg(),
+ hoverCapable: false,
+ onOpenThread: vi.fn(),
+ onReply: vi.fn(),
+ onCopy: vi.fn(),
+ }),
+ { createNodeMock: () => genericMock },
+ )
+ })
+
+ const triggers = renderer!.root.findAll(
+ (node) => node.props["data-slot"] === "dropdown-menu-trigger",
+ )
+ const trigger = triggers.find((node) => node.type === "button")
+ expect(trigger).toBeDefined()
+ expect(trigger?.props["aria-label"]).toBe("Message actions")
+ expect(trigger?.props.className).toContain("focus-visible:ring-2")
+ expect(renderer!.root.findAll(
+ (node) => node.props["data-slot"] === "context-menu-trigger",
+ )).toHaveLength(0)
+
+ const row = renderer!.root.find(
+ (node) => typeof node.props.className === "string"
+ && node.props.className.includes("group relative -mx-2"),
+ )
+ expect(row.props.className).not.toContain("select-none")
+ expect(row.props.role).toBeUndefined()
+ expect(row.props.tabIndex).toBeUndefined()
+ act(() => renderer!.unmount())
+ })
+
+ it("lets a short row tap reach the menu but suppresses long-press, selection, and nested-control taps", () => {
+ expect(shouldSuppressTouchMenuOpen({
+ nestedControl: false, selectionInsideRow: false, longPress: false,
+ })).toBe(false)
+ expect(shouldSuppressTouchMenuOpen({
+ nestedControl: false, selectionInsideRow: false, longPress: true,
+ })).toBe(true)
+ expect(shouldSuppressTouchMenuOpen({
+ nestedControl: false, selectionInsideRow: true, longPress: false,
+ })).toBe(true)
+ expect(shouldSuppressTouchMenuOpen({
+ nestedControl: true, selectionInsideRow: false, longPress: false,
+ })).toBe(true)
+ })
+
+ it("overrides the app-wide iOS callout suppression on selectable message text", async () => {
+ let renderer: TestRenderer.ReactTestRenderer | undefined
+ await act(async () => {
+ renderer = TestRenderer.create(
+ makeTree({
+ m: baseMsg(),
+ hoverCapable: false,
+ onOpenThread: vi.fn(),
+ onReply: vi.fn(),
+ }),
+ { createNodeMock: () => genericMock },
+ )
+ })
+
+ const body = renderer!.root.findByProps({ "data-community-message-body": true })
+ expect(body.props.className).toContain("select-text")
+ const globalCss = readFileSync(new URL("../../../app/globals.css", import.meta.url), "utf8")
+ expect(globalCss).toMatch(
+ /\[data-community-message-body\]\s*\{[^}]*-webkit-touch-callout:\s*default;[^}]*user-select:\s*text;/s,
+ )
+ act(() => renderer!.unmount())
+ })
+})
+
describe("Message image attachment layout", () => {
it("keeps a known portrait image intrinsic and constrains it by message width + max height", () => {
let renderer: TestRenderer.ReactTestRenderer
diff --git a/src/web/src/components/community/messages/message.tsx b/src/web/src/components/community/messages/message.tsx
index efdafbb18..efcf48e46 100644
--- a/src/web/src/components/community/messages/message.tsx
+++ b/src/web/src/components/community/messages/message.tsx
@@ -1,6 +1,6 @@
"use client"
-import { memo, useState } from "react"
+import { memo, useRef, useState } from "react"
import { useMessageMarked } from "@/hooks/community/use-inbox"
import type React from "react"
import {
@@ -46,12 +46,24 @@ export function shouldActivateMessageOverlays(target: EventTarget | null): boole
return !element?.closest?.("button, a, input, textarea, select, [role=button]")
}
+export function shouldSuppressTouchMenuOpen({
+ nestedControl,
+ selectionInsideRow,
+ longPress,
+}: {
+ nestedControl: boolean
+ selectionInsideRow: boolean
+ longPress: boolean
+}): boolean {
+ return nestedControl || selectionInsideRow || longPress
+}
+
function MessageImpl({
m, compact, pinned, onOpenThread, onOpenProfile, onJumpReply,
onToggleReaction, onReact, onReply, onPin, onMark, onCreateThread, onCopy, onEdit, onRetry, onDismiss,
onPreviewImage, onPreviewAttachment, onDownloadFile, highlighted, resolveUserName, onImageLoad,
selectMode, selected, onToggleSelect, onEnterSelect, onShareSingle,
- viewerUserId,
+ viewerUserId, hoverCapable = true,
}: {
m: RenderMsg
compact?: boolean
@@ -93,18 +105,28 @@ function MessageImpl({
onEnterSelect?: () => void
onShareSingle?: () => void
viewerUserId?: string
+ // Resolved once by MessageList and threaded into virtualized rows. Keeping
+ // the media-query subscription at the list level avoids one listener per
+ // visible message. Non-interactive standalone previews can use the desktop
+ // default without subscribing at all.
+ hoverCapable?: boolean
}) {
// keep the hover toolbar pinned open while its ⋯ dropdown is open
const [toolbarOpen, setToolbarOpen] = useState(false)
// Right-click context-menu open state — tracked so the Mark/Unmark label's
// lazy read fires for the context menu too, not just the ⋯ dropdown.
const [contextOpen, setContextOpen] = useState(false)
+ // Touch devices use a normal tap-triggered dropdown. Long-press is left to
+ // the browser so message text keeps native selection/copy behavior.
+ const [touchMenuOpen, setTouchMenuOpen] = useState(false)
+ const touchStartedAt = useRef<number | null>(null)
+ const suppressLongPressClick = useRef(false)
// The Mark/Unmark label needs to know if THIS message is already in the
// viewer's saved set. That's a single indexed row read, fired lazily only
// while a menu that shows the item is open (never per-row on mount) — so a
// channel scroll doesn't pre-load mark state for every row. Defaults to
// "Mark"; flips to "Unmark" silently once the read resolves (no spinner).
- const markMenuOpen = (toolbarOpen || contextOpen) && !!onMark
+ const markMenuOpen = (toolbarOpen || contextOpen || touchMenuOpen) && !!onMark
const { data: markedData } = useMessageMarked(m.id, markMenuOpen)
// Lazy-mount the row's Base UI overlay roots (ContextMenu / DropdownMenu /
// EmojiPicker Popover / reaction Tooltips). Eagerly mounting them per visible
@@ -141,7 +163,7 @@ function MessageImpl({
}
const showMenu = hasMessageMenu(menuHandlers)
const interactive = !compact && !m.failed && showMenu
- const activate = interactive && !activated
+ const activate = interactive && hoverCapable && !activated
? (event: React.SyntheticEvent<HTMLElement>) => {
if (shouldActivateMessageOverlays(event.target)) setActivated(true)
}
@@ -156,12 +178,59 @@ function MessageImpl({
"group relative -mx-2 flex gap-2 rounded px-2 transition-colors",
m.grouped ? "py-0" : "mt-3 pt-1.5 pb-0",
selectable ? "cursor-pointer pl-9" : "",
+ interactive && !hoverCapable && !selectMode ? "pr-11" : "",
selected ? "bg-primary/10" : highlighted ? "bg-primary/10" : selectable ? "hover:bg-accent/40" : "hover:bg-accent/40",
].join(" ")}
onPointerEnter={activate}
onFocusCapture={activate}
onKeyDownCapture={activate}
- onClick={selectable ? onToggleSelect : undefined}
+ onTouchStart={interactive && !hoverCapable
+ ? () => {
+ touchStartedAt.current = performance.now()
+ suppressLongPressClick.current = false
+ }
+ : undefined}
+ onTouchEnd={interactive && !hoverCapable
+ ? () => {
+ const startedAt = touchStartedAt.current
+ suppressLongPressClick.current = startedAt !== null
+ && performance.now() - startedAt >= 500
+ touchStartedAt.current = null
+ }
+ : undefined}
+ onTouchCancel={interactive && !hoverCapable
+ ? () => {
+ touchStartedAt.current = null
+ suppressLongPressClick.current = true
+ }
+ : undefined}
+ onClick={selectable
+ ? onToggleSelect
+ : interactive && !hoverCapable
+ ? (event) => {
+ const selection = window.getSelection()
+ const selectionInsideRow = !!selection
+ && !selection.isCollapsed
+ && !!selection.anchorNode
+ && event.currentTarget.contains(selection.anchorNode)
+ const nearestControl = (event.target as Element).closest(
+ "button, a, input, textarea, select, [role=button]",
+ )
+ const nestedControl = !!nearestControl && nearestControl !== event.currentTarget
+ const suppress = shouldSuppressTouchMenuOpen({
+ nestedControl,
+ selectionInsideRow,
+ longPress: suppressLongPressClick.current,
+ })
+ suppressLongPressClick.current = false
+ // The row itself remains non-interactive document content. Only a
+ // short tap on its non-control body opens the controlled menu;
+ // nested buttons/links and native long-press selection stay intact.
+ if (!suppress) {
+ setTouchMenuOpen(true)
+ }
+ }
+ : undefined}
>
{selectMode && (
// Checkbox overlay (absolute → no layout shift / no virtualizer
@@ -446,7 +515,38 @@ function MessageImpl({
</div>
)
- // Not interactive, or not yet activated → render the bare row (which carries
+ // Not interactive → render the bare row. In select mode the row itself is a
+ // toggle target, so no action-menu trigger is mounted.
+ if (!interactive || selectMode) return row
+
+ // Coarse/touch input: tap opens the existing dropdown menu. Deliberately do
+ // not mount ContextMenuTrigger here — its long-press gesture competes with
+ // native message-text selection on iOS/Android.
+ if (!hoverCapable) {
+ return (
+ <DropdownMenu open={touchMenuOpen} onOpenChange={setTouchMenuOpen}>
+ <div className="relative">
+ {row}
+ <DropdownMenuTrigger
+ render={(
+ <button
+ type="button"
+ aria-label={m.seq != null && m.seq > 0 ? `Actions for message ${m.seq}` : "Message actions"}
+ className={`absolute right-0 z-20 grid size-11 place-items-center rounded-lg text-muted-foreground hover:bg-accent hover:text-foreground focus-visible:ring-2 focus-visible:ring-ring focus-visible:outline-none ${m.grouped ? "top-0" : "top-3"}`}
+ />
+ )}
+ >
+ <MoreHorizontal className="size-5" />
+ </DropdownMenuTrigger>
+ </div>
+ <DropdownMenuContent align="end" className="w-48 select-none">
+ <MessageDropdownItems {...menuHandlers} touch />
+ </DropdownMenuContent>
+ </DropdownMenu>
+ )
+ }
+
+ // Not yet activated on desktop → render the bare row (which carries
// the pointerenter/focus/keydown activation handlers). The row's Base UI
// ContextMenu root is only mounted once hover/focus has activated it — and a
// right-click is always preceded by a pointerenter (mouse arriving on the
@@ -454,7 +554,7 @@ function MessageImpl({
// (The share-as-image dialog now lives in MessageList — the share button
// enters multi-select mode; the dialog opens from the select bar there.)
// In select mode the row is a toggle target — no context menu / toolbar.
- if (!interactive || !activated || selectMode) return row
+ if (!activated) return row
return (
<ContextMenu onOpenChange={setContextOpen}>
<ContextMenuTrigger className="select-text" render={row} />
@@ -505,6 +605,7 @@ function messagePropsEqual(prev: MessageProps, next: MessageProps): boolean {
prev.pinned === next.pinned &&
prev.highlighted === next.highlighted &&
prev.viewerUserId === next.viewerUserId &&
+ prev.hoverCapable === next.hoverCapable &&
prev.onOpenThread === next.onOpenThread &&
prev.onOpenProfile === next.onOpenProfile &&
prev.onJumpReply === next.onJumpReply &&
diff --git a/src/web/src/components/community/messages/use-composer-controller.test.ts b/src/web/src/components/community/messages/use-composer-controller.test.ts
index c739bbab3..ef6cc5bf1 100644
--- a/src/web/src/components/community/messages/use-composer-controller.test.ts
+++ b/src/web/src/components/community/messages/use-composer-controller.test.ts
@@ -159,10 +159,10 @@ describe("useComposerController", () => {
handleDrop: handleDropRaw,
}))
mocks.useSuggestions.mockImplementation(() => ({
- mentionPopup: { items: [], selectedIndex: 0, command: null, rect: null },
+ mentionPopup: { items: [], selectedIndex: 0, command: null, getRect: null },
mentionPopupRef,
mentionExtension: { name: "mention" },
- channelRefPopup: { items: [], selectedIndex: 0, command: null, rect: null },
+ channelRefPopup: { items: [], selectedIndex: 0, command: null, getRect: null },
channelRefPopupRef,
channelRefExtension: { name: "channel-ref" },
resetPopups,
diff --git a/src/web/src/components/community/messages/use-composer-suggestions.test.ts b/src/web/src/components/community/messages/use-composer-suggestions.test.ts
index 3791f7853..5f30c97c9 100644
--- a/src/web/src/components/community/messages/use-composer-suggestions.test.ts
+++ b/src/web/src/components/community/messages/use-composer-suggestions.test.ts
@@ -14,7 +14,7 @@ vi.mock("@/lib/community/mention-extension", () => ({
items: [],
selectedIndex: 0,
command: null,
- rect: null,
+ getRect: null,
},
buildCommunityMentionExtension: (...args: unknown[]) =>
mocks.buildMention(...args),
@@ -26,7 +26,7 @@ vi.mock("@/lib/community/channel-ref-extension", () => ({
items: [],
selectedIndex: 0,
command: null,
- rect: null,
+ getRect: null,
},
buildCommunityChannelRefExtension: (...args: unknown[]) =>
mocks.buildChannel(...args),
@@ -157,13 +157,13 @@ describe("useComposerSuggestions", () => {
items: [],
selectedIndex: 0,
command: vi.fn(),
- rect: null,
+ getRect: null,
})
channelOptions.setPopup({
items: [],
selectedIndex: 0,
command: vi.fn(),
- rect: null,
+ getRect: null,
})
})
@@ -243,7 +243,7 @@ describe("useComposerSuggestions", () => {
items: [initialItem, secondItem],
selectedIndex: 1,
command: vi.fn(),
- rect: null,
+ getRect: null,
})
})
@@ -314,13 +314,13 @@ describe("useComposerSuggestions", () => {
items: [{ kind: "everyone", id: "everyone", label: "everyone" }],
selectedIndex: 0,
command: vi.fn(),
- rect: null,
+ getRect: null,
})
channelOptions.setPopup({
items: [channel()],
selectedIndex: 0,
command: vi.fn(),
- rect: null,
+ getRect: null,
})
})
const previousState = resultRef.current!.channelRefPopup
@@ -344,7 +344,7 @@ describe("useComposerSuggestions", () => {
items: [channel(), second],
selectedIndex: 1,
command: vi.fn(),
- rect: null,
+ getRect: null,
})
})
mocks.rankChannel.mockReturnValue([
diff --git a/src/web/src/components/ui/markdown-editor.tsx b/src/web/src/components/ui/markdown-editor.tsx
index a24fafa8b..eace6d391 100644
--- a/src/web/src/components/ui/markdown-editor.tsx
+++ b/src/web/src/components/ui/markdown-editor.tsx
@@ -1,6 +1,6 @@
"use client";
-import { useEffect, useState, useRef } from "react";
+import { useCallback, useEffect, useState, useRef } from "react";
import { useEditor, EditorContent } from "@tiptap/react";
import StarterKit from "@tiptap/starter-kit";
import Placeholder from "@tiptap/extension-placeholder";
@@ -11,6 +11,7 @@ import { isImeConfirming } from "@/lib/ime";
import { isEmptyHtml, toAlookAddress } from "@alook/shared";
import type { Agent } from "@alook/shared";
import { createPortal } from "react-dom";
+import { anchoredPopoverStyle, useAnchoredPopover } from "@/hooks/use-anchored-popover";
export { isEmptyHtml };
@@ -52,6 +53,11 @@ function MentionList({
}) {
const listRef = useRef<HTMLDivElement>(null);
const { items, selectedIndex, command } = state;
+ const getRect = useCallback(
+ () => anchorEl?.getBoundingClientRect() ?? null,
+ [anchorEl],
+ );
+ const geometry = useAnchoredPopover(getRect, !!anchorEl && items.length > 0 && command !== null);
useEffect(() => {
if (!listRef.current) return;
@@ -59,16 +65,18 @@ function MentionList({
el?.scrollIntoView({ block: "nearest" });
}, [selectedIndex]);
- if (!anchorEl || items.length === 0 || !command) return null;
-
- const rect = anchorEl.getBoundingClientRect();
+ if (!anchorEl || !geometry || items.length === 0 || !command) return null;
return createPortal(
<div
className="fixed z-100 w-64 rounded-lg border border-border bg-popover text-popover-foreground shadow-md"
- style={{ top: rect.top - 4, left: rect.left, transform: "translateY(-100%)" }}
+ style={anchoredPopoverStyle(geometry.rect, geometry.viewport, 256, 200)}
>
- <div ref={listRef} className="max-h-50 overflow-y-auto py-1 thin-scrollbar">
+ <div
+ ref={listRef}
+ className="overflow-y-auto py-1 thin-scrollbar"
+ style={{ maxHeight: "var(--anchored-popover-max-height)" }}
+ >
{items.map((agent, i) => (
<button
key={agent.id}
diff --git a/src/web/src/hooks/use-anchored-popover.test.ts b/src/web/src/hooks/use-anchored-popover.test.ts
new file mode 100644
index 000000000..4b492446f
--- /dev/null
+++ b/src/web/src/hooks/use-anchored-popover.test.ts
@@ -0,0 +1,136 @@
+import { afterEach, beforeEach, describe, expect, it, vi } from "vitest"
+import {
+ anchoredPopoverStyle,
+ readVisualViewport,
+ subscribeAnchoredPopoverChanges,
+ type AnchorRect,
+ type VisualViewportRect,
+} from "./use-anchored-popover"
+
+const VIEWPORT: VisualViewportRect = { top: 100, left: 20, width: 320, height: 500 }
+
+function rect(top: number, left: number, height = 16): AnchorRect {
+ return { top, bottom: top + height, left, right: left + 4 }
+}
+
+describe("anchoredPopoverStyle", () => {
+ it("anchors above the caret when the visual viewport has room", () => {
+ const style = anchoredPopoverStyle(rect(400, 40), VIEWPORT, 256, 240)
+ expect(style.top).toBe(396)
+ expect(style.left).toBe(40)
+ expect(style.transform).toBe("translateY(-100%)")
+ expect(style["--anchored-popover-max-height"]).toBe("240px")
+ })
+
+ it("flips below a caret near the visual viewport top", () => {
+ const style = anchoredPopoverStyle(rect(120, 40), VIEWPORT, 256, 240)
+ expect(style.top).toBe(140)
+ expect(style.transform).toBeUndefined()
+ })
+
+ it("clamps both horizontal edges against a non-zero visual viewport origin", () => {
+ expect(anchoredPopoverStyle(rect(400, -100), VIEWPORT, 256, 240).left).toBe(28)
+ expect(anchoredPopoverStyle(rect(400, 500), VIEWPORT, 256, 240).left).toBe(76)
+ })
+
+ it("uses the roomier side and reduces list height when neither side fully fits", () => {
+ const shortViewport = { top: 100, left: 0, width: 320, height: 220 }
+ const style = anchoredPopoverStyle(rect(180, 20), shortViewport, 256, 240)
+ expect(style.transform).toBeUndefined()
+ expect(style["--anchored-popover-max-height"]).toBe("102px")
+ })
+})
+
+describe("visual viewport refresh signals", () => {
+ const originalWindow = Object.getOwnPropertyDescriptor(globalThis, "window")
+ let windowListeners: Map<string, Set<EventListener>>
+ let viewportListeners: Map<string, Set<EventListener>>
+ let frames: Map<number, FrameRequestCallback>
+ let nextFrame: number
+
+ const eventTarget = (listeners: Map<string, Set<EventListener>>) => ({
+ addEventListener(type: string, listener: EventListener) {
+ const current = listeners.get(type) ?? new Set<EventListener>()
+ current.add(listener)
+ listeners.set(type, current)
+ },
+ removeEventListener(type: string, listener: EventListener) {
+ listeners.get(type)?.delete(listener)
+ },
+ })
+
+ beforeEach(() => {
+ vi.useFakeTimers()
+ windowListeners = new Map()
+ viewportListeners = new Map()
+ frames = new Map()
+ nextFrame = 1
+ const viewportTarget = eventTarget(viewportListeners)
+ const windowTarget = eventTarget(windowListeners)
+ Object.defineProperty(globalThis, "window", {
+ configurable: true,
+ value: {
+ ...windowTarget,
+ innerWidth: 1024,
+ innerHeight: 768,
+ visualViewport: {
+ ...viewportTarget,
+ offsetTop: 100,
+ offsetLeft: 20,
+ width: 320,
+ height: 500,
+ },
+ requestAnimationFrame(callback: FrameRequestCallback) {
+ const id = nextFrame++
+ frames.set(id, callback)
+ return id
+ },
+ cancelAnimationFrame(id: number) {
+ frames.delete(id)
+ },
+ },
+ })
+ })
+
+ afterEach(() => {
+ vi.useRealTimers()
+ if (originalWindow) Object.defineProperty(globalThis, "window", originalWindow)
+ else Reflect.deleteProperty(globalThis, "window")
+ })
+
+ const dispatch = (listeners: Map<string, Set<EventListener>>, type: string) => {
+ for (const listener of listeners.get(type) ?? []) listener(new Event(type))
+ }
+
+ const flushFrame = () => {
+ const entries = [...frames.entries()]
+ frames.clear()
+ for (const [, callback] of entries) callback(0)
+ }
+
+ it("reads visual viewport offsets instead of assuming a zero-origin layout viewport", () => {
+ expect(readVisualViewport()).toEqual(VIEWPORT)
+ })
+
+ it("refreshes on visual viewport and capture-scroll changes, including a trailing keyboard settle", () => {
+ const onChange = vi.fn()
+ const unsubscribe = subscribeAnchoredPopoverChanges(onChange)
+
+ dispatch(viewportListeners, "resize")
+ flushFrame()
+ expect(onChange).toHaveBeenCalledTimes(1)
+
+ vi.advanceTimersByTime(200)
+ flushFrame()
+ expect(onChange).toHaveBeenCalledTimes(2)
+
+ dispatch(windowListeners, "scroll")
+ flushFrame()
+ expect(onChange).toHaveBeenCalledTimes(3)
+
+ unsubscribe()
+ dispatch(viewportListeners, "scroll")
+ flushFrame()
+ expect(onChange).toHaveBeenCalledTimes(3)
+ })
+})
diff --git a/src/web/src/hooks/use-anchored-popover.ts b/src/web/src/hooks/use-anchored-popover.ts
new file mode 100644
index 000000000..b2b165a0a
--- /dev/null
+++ b/src/web/src/hooks/use-anchored-popover.ts
@@ -0,0 +1,176 @@
+"use client"
+
+import { useEffect, useState, type CSSProperties } from "react"
+
+export interface AnchorRect {
+ top: number
+ bottom: number
+ left: number
+ right: number
+}
+
+export type AnchorRectResolver = () => AnchorRect | null
+
+export interface VisualViewportRect {
+ top: number
+ left: number
+ width: number
+ height: number
+}
+
+export interface AnchoredPopoverGeometry {
+ rect: AnchorRect
+ viewport: VisualViewportRect
+}
+
+type AnchoredPopoverStyle = CSSProperties & {
+ "--anchored-popover-max-height": string
+}
+
+const VIEWPORT_MARGIN = 8
+const POPOVER_GAP = 4
+const POPOVER_CHROME_HEIGHT = 10
+const MIN_LIST_HEIGHT = 48
+const SETTLE_REFRESH_MS = 200
+
+export function readVisualViewport(): VisualViewportRect | null {
+ if (typeof window === "undefined") return null
+ const viewport = window.visualViewport
+ return {
+ top: viewport?.offsetTop ?? 0,
+ left: viewport?.offsetLeft ?? 0,
+ width: viewport?.width ?? window.innerWidth,
+ height: viewport?.height ?? window.innerHeight,
+ }
+}
+
+function readAnchoredPopoverGeometry(
+ getRect: AnchorRectResolver,
+): AnchoredPopoverGeometry | null {
+ const rect = getRect()
+ const viewport = readVisualViewport()
+ return rect && viewport ? { rect, viewport } : null
+}
+
+function geometryEqual(
+ a: AnchoredPopoverGeometry | null,
+ b: AnchoredPopoverGeometry | null,
+): boolean {
+ if (a === b) return true
+ if (!a || !b) return false
+ return a.rect.top === b.rect.top
+ && a.rect.bottom === b.rect.bottom
+ && a.rect.left === b.rect.left
+ && a.rect.right === b.rect.right
+ && a.viewport.top === b.viewport.top
+ && a.viewport.left === b.viewport.left
+ && a.viewport.width === b.viewport.width
+ && a.viewport.height === b.viewport.height
+}
+
+/**
+ * Subscribe to every layout signal that can move a viewport-fixed caret menu.
+ * The trailing refresh is deliberate: `useKeyboardScroll` applies its iOS
+ * fallback transform after a 150ms debounce, after the original
+ * `visualViewport` event has already fired.
+ */
+export function subscribeAnchoredPopoverChanges(onChange: () => void): () => void {
+ if (typeof window === "undefined") return () => {}
+
+ let frame: number | null = null
+ let settleTimer: ReturnType<typeof setTimeout> | null = null
+
+ const scheduleFrame = () => {
+ if (frame !== null) return
+ frame = window.requestAnimationFrame(() => {
+ frame = null
+ onChange()
+ })
+ }
+ const handleViewportChange = () => {
+ scheduleFrame()
+ if (settleTimer !== null) clearTimeout(settleTimer)
+ settleTimer = setTimeout(scheduleFrame, SETTLE_REFRESH_MS)
+ }
+
+ window.addEventListener("resize", handleViewportChange)
+ window.addEventListener("scroll", handleViewportChange, true)
+ window.visualViewport?.addEventListener("resize", handleViewportChange)
+ window.visualViewport?.addEventListener("scroll", handleViewportChange)
+
+ return () => {
+ window.removeEventListener("resize", handleViewportChange)
+ window.removeEventListener("scroll", handleViewportChange, true)
+ window.visualViewport?.removeEventListener("resize", handleViewportChange)
+ window.visualViewport?.removeEventListener("scroll", handleViewportChange)
+ if (frame !== null) window.cancelAnimationFrame(frame)
+ if (settleTimer !== null) clearTimeout(settleTimer)
+ }
+}
+
+/** Re-resolves a live caret/element rect whenever the visible viewport moves. */
+export function useAnchoredPopover(
+ getRect: AnchorRectResolver | null,
+ active: boolean,
+): AnchoredPopoverGeometry | null {
+ const [snapshot, setSnapshot] = useState<{
+ getRect: AnchorRectResolver
+ geometry: AnchoredPopoverGeometry | null
+ } | null>(null)
+
+ useEffect(() => {
+ if (!active || !getRect) return
+ const refresh = () => {
+ const next = readAnchoredPopoverGeometry(getRect)
+ setSnapshot((current) => current?.getRect === getRect
+ && geometryEqual(current.geometry, next)
+ ? current
+ : { getRect, geometry: next })
+ }
+ refresh()
+ return subscribeAnchoredPopoverChanges(refresh)
+ }, [active, getRect])
+
+ return active && snapshot?.getRect === getRect ? snapshot.geometry : null
+}
+
+/**
+ * Position a fixed popup inside the visual viewport. Above is preferred; when
+ * neither side fits the full list, use the roomier side and shrink the list.
+ */
+export function anchoredPopoverStyle(
+ rect: AnchorRect,
+ viewport: VisualViewportRect,
+ popupWidth: number,
+ popupMaxHeight: number,
+): AnchoredPopoverStyle {
+ const viewportRight = viewport.left + viewport.width
+ const viewportBottom = viewport.top + viewport.height
+ const minLeft = viewport.left + VIEWPORT_MARGIN
+ const maxLeft = Math.max(minLeft, viewportRight - popupWidth - VIEWPORT_MARGIN)
+ const left = Math.min(Math.max(rect.left, minLeft), maxLeft)
+
+ const spaceAbove = rect.top - viewport.top
+ const spaceBelow = viewportBottom - rect.bottom
+ const fullHeight = popupMaxHeight + POPOVER_CHROME_HEIGHT + POPOVER_GAP + VIEWPORT_MARGIN
+ const placeBelow = spaceAbove < fullHeight
+ && (spaceBelow >= fullHeight || spaceBelow > spaceAbove)
+ const available = (placeBelow ? spaceBelow : spaceAbove)
+ - POPOVER_GAP
+ - VIEWPORT_MARGIN
+ - POPOVER_CHROME_HEIGHT
+ const listHeight = Math.min(popupMaxHeight, Math.max(MIN_LIST_HEIGHT, available))
+ const common = {
+ left,
+ maxWidth: Math.max(0, viewport.width - VIEWPORT_MARGIN * 2),
+ "--anchored-popover-max-height": `${listHeight}px`,
+ }
+
+ return placeBelow
+ ? { ...common, top: rect.bottom + POPOVER_GAP }
+ : {
+ ...common,
+ top: rect.top - POPOVER_GAP,
+ transform: "translateY(-100%)",
+ }
+}
diff --git a/src/web/src/hooks/use-slash-command.ts b/src/web/src/hooks/use-slash-command.ts
index 59c870945..e6bb6213b 100644
--- a/src/web/src/hooks/use-slash-command.ts
+++ b/src/web/src/hooks/use-slash-command.ts
@@ -1,5 +1,6 @@
import { useState, useCallback, useMemo, useRef, useEffect } from "react"
import type { SkillEntry } from "@alook/shared"
+import type { AnchorRect, AnchorRectResolver } from "@/hooks/use-anchored-popover"
/**
* Minimal keyboard-event shape the popup hooks need. Both React synthetic
@@ -16,7 +17,7 @@ export interface SlashCommandPopupState {
isOpen: boolean
query: string
selectedIndex: number
- anchorPos: { top: number; left: number }
+ getAnchorRect: AnchorRectResolver
skills: SkillEntry[]
activeSkill: SkillEntry | null
handleSlashKeyDown: (e: PopupKeyEvent) => boolean
@@ -32,11 +33,11 @@ interface UseSlashCommandParams {
onInputChange: (value: string) => void
initialActiveSkill?: SkillEntry | null
/**
- * Resolve the popup anchor position (viewport-relative top/left) for the
+ * Resolve the popup's viewport-relative caret rect for the
* slash trigger at `triggerStart`. The TipTap composer computes this from
* `editor.view.coordsAtPos`; returns null if it cannot be resolved yet.
*/
- getAnchorPos: (triggerStart: number) => { top: number; left: number } | null
+ getAnchorPos: (triggerStart: number) => AnchorRect | null
/** Called after a skill is selected so the caller can re-focus its editor. */
onAfterSelect?: () => void
}
@@ -70,7 +71,6 @@ export function useSlashCommand({
const [isOpen, setIsOpen] = useState(false)
const [query, setQuery] = useState("")
const [selectedIndex, setSelectedIndex] = useState(0)
- const [anchorPos, setAnchorPos] = useState({ top: 0, left: 0 })
const triggerStartRef = useRef<number | null>(null)
const filteredSkills = useMemo(() => {
@@ -109,14 +109,18 @@ export function useSlashCommand({
setQuery(trigger.query)
setIsOpen(true)
- const coords = getAnchorPos(trigger.start)
- if (coords) setAnchorPos(coords)
} else {
setIsOpen(false)
triggerStartRef.current = null
}
}, [input, caretIndex, getAnchorPos, activeSkill])
+ const getAnchorRect = useCallback<AnchorRectResolver>(() => {
+ const triggerStart = triggerStartRef.current
+ if (triggerStart === null) return null
+ return getAnchorPos(triggerStart)
+ }, [getAnchorPos])
+
const selectSkill = useCallback((skill: SkillEntry) => {
setActiveSkill(skill)
onInputChange("")
@@ -159,7 +163,7 @@ export function useSlashCommand({
isOpen,
query,
selectedIndex,
- anchorPos,
+ getAnchorRect,
skills: filteredSkills,
activeSkill,
handleSlashKeyDown,
diff --git a/src/web/src/lib/community/channel-ref-extension.ts b/src/web/src/lib/community/channel-ref-extension.ts
index df28b7303..cc172c7ed 100644
--- a/src/web/src/lib/community/channel-ref-extension.ts
+++ b/src/web/src/lib/community/channel-ref-extension.ts
@@ -32,14 +32,14 @@ export interface ChannelRefPopupState {
items: ChannelRefCandidate[]
selectedIndex: number
command: ((props: ChannelRefCommandProps) => void) | null
- rect: DOMRect | null
+ getRect: (() => DOMRect | null) | null
}
export const EMPTY_CHANNEL_REF_STATE: ChannelRefPopupState = {
items: [],
selectedIndex: 0,
command: null,
- rect: null,
+ getRect: null,
}
const CHANNEL_REF_LIMIT = 8
@@ -169,7 +169,7 @@ export function buildCommunityChannelRefExtension(opts: {
items: props.items ?? [],
selectedIndex: 0,
command: props.command,
- rect: props.clientRect?.() ?? null,
+ getRect: props.clientRect ?? null,
})
},
onUpdate: (props: SuggestionProps) => {
@@ -180,7 +180,7 @@ export function buildCommunityChannelRefExtension(opts: {
? cur.selectedIndex
: 0,
command: props.command,
- rect: props.clientRect?.() ?? null,
+ getRect: props.clientRect ?? null,
}))
},
onKeyDown: ({ event }: { event: KeyboardEvent }) => {
diff --git a/src/web/src/lib/community/mention-extension.ts b/src/web/src/lib/community/mention-extension.ts
index 2f68a03c1..e4b7653c9 100644
--- a/src/web/src/lib/community/mention-extension.ts
+++ b/src/web/src/lib/community/mention-extension.ts
@@ -87,20 +87,22 @@ export function rankMentionItems(
return [...virtual, ...sw, ...inc].slice(0, MENTION_LIMIT)
}
-// Popup state. `rect` is `clientRect()` from @tiptap/suggestion — it's the
-// caret position the popup floats above.
+// Keep TipTap's live `clientRect` resolver rather than a one-time DOMRect.
+// Mobile visualViewport and keyboard movement can move the caret without
+// causing another suggestion update; the popup subscribes to those signals
+// and re-reads this resolver.
export interface MentionPopupState {
items: MentionItem[]
selectedIndex: number
command: ((props: { id: string; label: string }) => void) | null
- rect: DOMRect | null
+ getRect: (() => DOMRect | null) | null
}
export const EMPTY_MENTION_STATE: MentionPopupState = {
items: [],
selectedIndex: 0,
command: null,
- rect: null,
+ getRect: null,
}
type SuggestionProps = {
@@ -158,7 +160,7 @@ export function buildCommunityMentionExtension(opts: {
items: props.items ?? [],
selectedIndex: 0,
command: props.command,
- rect: props.clientRect?.() ?? null,
+ getRect: props.clientRect ?? null,
})
},
onUpdate: (props: SuggestionProps) => {
@@ -169,7 +171,7 @@ export function buildCommunityMentionExtension(opts: {
? cur.selectedIndex
: 0,
command: props.command,
- rect: props.clientRect?.() ?? null,
+ getRect: props.clientRect ?? null,
}))
},
onKeyDown: ({ event }: { event: KeyboardEvent }) => {