Skip to content

armgit / avibe

Public Imported from GitHub
0

Make your computer a home for your AI partner. Avibe is the local-first Agent OS: Vibey, its built-in AI partner, works out of the box, and Claude Code, Codex & OpenCode run unchanged beside it — reach them from your browser, phone, or any chat app.

fix(chat): keep mobile selection actions reachable on iOS (#2290)

Call White3986b454441f
diff --git a/docs/plans/mobile-selection-toolbar-ios27.md b/docs/plans/mobile-selection-toolbar-ios27.md
new file mode 100644
index 000000000..e4b75a836
--- /dev/null
+++ b/docs/plans/mobile-selection-toolbar-ios27.md
@@ -0,0 +1,53 @@
+# Mobile selection toolbar on iOS 27
+
+## Problem
+
+iOS 27 can keep a touch that starts near a native text-selection handle in its
+selection gesture recognizer. The WebView may deliver `pointerdown` while
+withholding the later `pointerup`, `pointercancel`, and capture-loss events.
+
+The selection toolbar is currently positioned only 8px from the selected range.
+That places its buttons inside the native handle hit region. PR #2249 added
+pointer ownership that is released only by those terminal events, so a withheld
+`pointerup` leaves the toolbar pinned to stale selection state.
+
+## Contract
+
+- A missing pointer end event must not leave the toolbar in a permanently owned
+ or stale state.
+- Clearing or changing the selection must hide or recompute the toolbar even if
+ a previous touch ended without a terminal event.
+- On coarse pointers, the toolbar is placed at least 44px plus the existing
+ 8px gap from the first or last selection line used as its anchor.
+- Quote, Ask in a new session, and Copy still activate once on a complete
+ pointer gesture; keyboard activation remains unchanged.
+- Desktop placement and selection behavior remain unchanged except for using
+ the same simpler activation handlers.
+
+## Implementation
+
+- Remove pointer capture and the `activePointerId` lifetime state. Keep only a
+ matching primary-button press record. New pointerdown, changed selection
+ text, scrolling, action dismissal, and component teardown clear the record.
+ A selectionchange during a press cancels any queued debounce, preserves the
+ rendered snapshot briefly, and either releases normally or is re-computed
+ when the bounded 700ms grace period expires.
+- Track the first and last client rects of the selection instead of only the
+ aggregate range rect.
+- Place the touch toolbar above the first line or below the last line with a
+ 52px safe offset. Evaluate those positions, the safe middle band, and the
+ viewport edges as full-rectangle candidates; choose a candidate that does
+ not intersect either expanded endpoint handle region, or the candidate with
+ the smallest overlap when no fully safe slot exists.
+
+## Validation
+
+- Component tests simulate pointerdown without any terminal pointer event,
+ clear the selection, select new text, and activate the new toolbar.
+- Geometry tests verify the toolbar clears the native 44px handle region.
+- Long-selection geometry tests cover endpoint lines near or beyond both
+ viewport edges and the safe middle band between visible endpoints.
+- Focused UI tests, changed-file lint, and production build are required.
+- Playwright WebKit and Chromium probes must include the missing-terminal-event
+ model; event-complete taps alone are not sufficient.
+- Physical iPhone iOS 27 PWA validation remains required for final confidence.
diff --git a/docs/plans/mobile-selection-toolbar.md b/docs/plans/mobile-selection-toolbar.md
index 4f4ba514d..8ab425085 100644
--- a/docs/plans/mobile-selection-toolbar.md
+++ b/docs/plans/mobile-selection-toolbar.md
@@ -1,49 +1,9 @@
# Mobile selection toolbar gesture lifetime
-## Contract
+> Superseded by [`mobile-selection-toolbar-ios27.md`](./mobile-selection-toolbar-ios27.md).
+> The implementation now uses a bounded press snapshot and full-rectangle
+> touch placement checks for the iOS 27 selection-handle behavior.
-A primary pointer press on a chat selection action owns the selected text until
-that gesture finishes. Selection collapse or transcript scrolling during the
-press must not remove the action before release. Quote, Ask in a new session,
-and Copy execute exactly once when the same pointer releases inside its button.
-Cancellation, lost capture, and release outside the button execute nothing and
-restore normal selection tracking. Keyboard activation remains available.
-
-This change belongs to `SelectionQuoteToolbar`; it does not change composer,
-fork, clipboard permission, or PWA installation contracts.
-
-Dependencies: none. No existing scenario-catalog ID covers this interaction;
-the toolbar component regression is its primary automated contract.
-
-## Validation
-
-- Component regression: an actual DOM selection collapses between pointer down
- and pointer up; the debounce elapses; each action still receives the original
- non-ASCII text exactly once. Existing tests do not exercise this toolbar's
- pointer/selection interaction.
-- Cancellation, capture loss, outside release, non-primary input, and ordinary
- selection dismissal cover gesture ownership boundaries.
-- Hermetic browser checks exercise native pointer capture and touch activation
- in Chromium and WebKit. WebKit touch emulation does not establish the exact
- event ordering of an iPhone's native selection menu.
-- Focused tests, changed-file lint, production UI build, exact-head Codex review,
- and required CI.
-
-## Local results
-
-- The pre-fix component failed the three selection-collapse action cases.
-- All 75 tests across the toolbar, archived-chat behavior, and composer shortcuts
- pass after the fix.
-- Chromium and WebKit each passed native touch taps for all three actions,
- native mouse pointer capture across selection collapse, and captured release
- outside the button. The probe served the actual component through Vite on
- loopback in disposable browser contexts; clipboard writes were intercepted to
- avoid changing the host clipboard. It reported no page errors.
-- No iPhone hardware or native iOS selection menu was exercised.
-
-## Known by design
-
-- The operating system's selection menu remains available.
-- Toolbar placement and transcript scroll behavior outside an active button
- gesture remain unchanged.
-- No production update, service restart, or merge is part of this change.
+This document records the earlier pointer-capture design from PR #2249 and is
+kept only as historical context. Do not use its gesture-lifetime or placement
+contract as the current behavior.
diff --git a/ui/src/components/workbench/SelectionQuoteToolbar.test.tsx b/ui/src/components/workbench/SelectionQuoteToolbar.test.tsx
index 1dad80df5..eb2f1a795 100644
--- a/ui/src/components/workbench/SelectionQuoteToolbar.test.tsx
+++ b/ui/src/components/workbench/SelectionQuoteToolbar.test.tsx
@@ -10,15 +10,25 @@ vi.mock('react-i18next', () => ({
}));
const TEXT = 'Selected 中文消息 🌱';
+const NEXT_TEXT = 'New selection 新消息';
const quote = vi.fn();
const ask = vi.fn();
const writeText = vi.fn().mockResolvedValue(undefined);
-const rect = { top: 200, bottom: 236, left: 40, right: 340, width: 300, height: 36 };
+const defaultBounds = {
+ top: 200,
+ bottom: 236,
+ left: 40,
+ right: 340,
+ width: 300,
+ height: 36,
+};
+
+let selectionBounds = defaultBounds;
+let selectionLineRects = [defaultBounds];
+let coarsePointer = true;
+const originalInnerHeight = window.innerHeight;
+const originalInnerWidth = window.innerWidth;
-// jsdom has selections but no layout, pointer capture, or PointerEvent. Only
-// those browser boundaries are supplied; selection tracking and action dispatch
-// come from the real component. Before the fix, clearing the selection during a
-// press unmounts the action and none of its consumers receive the selected text.
class TestPointerEvent extends MouseEvent {
pointerId: number;
isPrimary: boolean;
@@ -35,21 +45,28 @@ class TestPointerEvent extends MouseEvent {
beforeEach(() => {
vi.useFakeTimers();
vi.clearAllMocks();
+ coarsePointer = true;
vi.stubGlobal('PointerEvent', TestPointerEvent);
- vi.stubGlobal('matchMedia', () => ({ matches: true }));
+ vi.stubGlobal('matchMedia', () => ({ matches: coarsePointer }));
+ Object.defineProperty(window, 'innerHeight', { configurable: true, value: 844 });
+ Object.defineProperty(window, 'innerWidth', { configurable: true, value: 390 });
Object.defineProperty(Range.prototype, 'getBoundingClientRect', {
configurable: true,
- value: () => rect,
+ value: () => selectionBounds,
});
- vi.spyOn(HTMLElement.prototype, 'getBoundingClientRect').mockReturnValue(rect as DOMRect);
- Object.defineProperty(HTMLElement.prototype, 'setPointerCapture', {
+ Object.defineProperty(Range.prototype, 'getClientRects', {
configurable: true,
- value: vi.fn(),
+ value: () => selectionLineRects,
});
+ vi.spyOn(HTMLElement.prototype, 'getBoundingClientRect').mockReturnValue(
+ defaultBounds as DOMRect,
+ );
Object.defineProperty(navigator, 'clipboard', {
configurable: true,
value: { writeText },
});
+ selectionBounds = defaultBounds;
+ selectionLineRects = [defaultBounds];
});
afterEach(() => {
@@ -59,8 +76,16 @@ afterEach(() => {
vi.useRealTimers();
vi.restoreAllMocks();
vi.unstubAllGlobals();
+ Object.defineProperty(window, 'innerHeight', {
+ configurable: true,
+ value: originalInnerHeight,
+ });
+ Object.defineProperty(window, 'innerWidth', {
+ configurable: true,
+ value: originalInnerWidth,
+ });
Reflect.deleteProperty(Range.prototype, 'getBoundingClientRect');
- Reflect.deleteProperty(HTMLElement.prototype, 'setPointerCapture');
+ Reflect.deleteProperty(Range.prototype, 'getClientRects');
Reflect.deleteProperty(navigator, 'clipboard');
});
@@ -72,100 +97,292 @@ function mountToolbar() {
<SelectionQuoteToolbar containerRef={containerRef} onQuote={quote} onAskInNew={ask} />
</>,
);
+ selectContainer(containerRef.current!);
+ return containerRef.current!;
+}
+
+function selectContainer(container: HTMLDivElement) {
const range = document.createRange();
- range.selectNodeContents(containerRef.current!);
+ range.selectNodeContents(container);
+ window.getSelection()!.removeAllRanges();
window.getSelection()!.addRange(range);
fireEvent(document, new Event('selectionchange'));
act(() => vi.advanceTimersByTime(150));
- return containerRef.current!;
}
-function collapseSelection() {
+function clearSelection() {
window.getSelection()!.removeAllRanges();
fireEvent(document, new Event('selectionchange'));
act(() => vi.advanceTimersByTime(200));
}
-const press = { pointerId: 1, isPrimary: true, pointerType: 'touch', button: 0, clientX: 100, clientY: 220 };
+const press = {
+ pointerId: 1,
+ isPrimary: true,
+ pointerType: 'touch',
+ button: 0,
+ clientX: 100,
+ clientY: 220,
+};
describe('chat selection action gesture lifetime', () => {
it.each([
['quote', quote],
['askInNew', ask],
- ['copy', writeText],
- ] as const)('keeps %s alive until release after selection collapse and scrolling', async (action, consumer) => {
- const container = mountToolbar();
+ ] as const)('activates %s on a complete touch gesture', (action, consumer) => {
+ mountToolbar();
const button = screen.getByRole('button', { name: `chat.selection.${action}` });
- fireEvent.pointerDown(button, press);
- expect(consumer).not.toHaveBeenCalled();
- collapseSelection();
- fireEvent.scroll(container);
- act(() => vi.advanceTimersByTime(200));
- expect(screen.getByRole('toolbar').contains(button)).toBe(true);
+ fireEvent.pointerDown(button, press);
+ fireEvent.pointerUp(button, press);
- await act(async () => fireEvent.pointerUp(button, press));
- // Browsers may follow pointerup with click. It must not run the action twice.
- fireEvent.click(button, { detail: 1 });
expect(consumer).toHaveBeenCalledExactlyOnceWith(TEXT);
+ expect(screen.queryByRole('toolbar')).toBeNull();
});
- it.each(['pointerCancel', 'lostPointerCapture'] as const)(
- '%s ends ownership without activating',
- (event) => {
- mountToolbar();
- const button = screen.getByRole('button', { name: 'chat.selection.quote' });
+ it('copies on a complete touch gesture and then dismisses', async () => {
+ mountToolbar();
+ const button = screen.getByRole('button', { name: 'chat.selection.copy' });
+
+ await act(async () => {
fireEvent.pointerDown(button, press);
- collapseSelection();
- expect(screen.getByRole('toolbar').contains(button)).toBe(true);
- fireEvent[event](button, press);
- expect(screen.queryByRole('toolbar')).toBeNull();
- expect(quote).not.toHaveBeenCalled();
- },
- );
+ fireEvent.pointerUp(button, press);
+ await Promise.resolve();
+ });
+
+ expect(writeText).toHaveBeenCalledExactlyOnceWith(TEXT);
+ expect(screen.queryByRole('toolbar')).not.toBeNull();
+ act(() => vi.advanceTimersByTime(800));
+ expect(screen.queryByRole('toolbar')).toBeNull();
+ });
- it('does not activate when a captured pointer releases outside the button', () => {
+ it('keeps a complete gesture alive when the selection clears before release', () => {
mountToolbar();
const button = screen.getByRole('button', { name: 'chat.selection.quote' });
+
fireEvent.pointerDown(button, press);
- collapseSelection();
- expect(screen.getByRole('toolbar').contains(button)).toBe(true);
+ clearSelection();
+ fireEvent.pointerUp(button, press);
+
+ expect(quote).toHaveBeenCalledExactlyOnceWith(TEXT);
+ expect(screen.queryByRole('toolbar')).toBeNull();
+ });
+
+ it('recovers when iOS delivers pointerdown but never delivers an end event', () => {
+ const container = mountToolbar();
+ const button = screen.getByRole('button', { name: 'chat.selection.quote' });
+
+ // iOS can route this touch to its native selection recognizer. The page
+ // receives pointerdown, but no pointerup/cancel/lostpointercapture.
+ fireEvent.pointerDown(button, press);
+ clearSelection();
+ act(() => vi.advanceTimersByTime(600));
+ expect(screen.queryByRole('toolbar')).toBeNull();
+
+ container.textContent = NEXT_TEXT;
+ selectContainer(container);
+ const nextButton = screen.getByRole('button', { name: 'chat.selection.quote' });
+ fireEvent.pointerDown(nextButton, press);
+ fireEvent.pointerUp(nextButton, press);
+
+ expect(quote).toHaveBeenCalledExactlyOnceWith(NEXT_TEXT);
+ });
+
+ it('recomputes after a deferred press is released outside the button', () => {
+ mountToolbar();
+ const button = screen.getByRole('button', { name: 'chat.selection.quote' });
+
+ fireEvent.pointerDown(button, press);
+ clearSelection();
fireEvent.pointerUp(button, { ...press, clientX: 500 });
+
expect(quote).not.toHaveBeenCalled();
expect(screen.queryByRole('toolbar')).toBeNull();
});
- it('ignores another pointer while the primary press owns the selection', () => {
+ it('allows a long primary press to activate', () => {
mountToolbar();
const button = screen.getByRole('button', { name: 'chat.selection.quote' });
+
fireEvent.pointerDown(button, press);
- collapseSelection();
- fireEvent.pointerDown(button, { ...press, pointerId: 2, isPrimary: false });
- fireEvent.pointerUp(button, { ...press, pointerId: 2, isPrimary: false });
- expect(quote).not.toHaveBeenCalled();
+ act(() => vi.advanceTimersByTime(800));
fireEvent.pointerUp(button, press);
+
expect(quote).toHaveBeenCalledExactlyOnceWith(TEXT);
});
- it('does not treat a release without a primary press as activation', () => {
+ it('preserves a complete gesture across selectionchange', () => {
mountToolbar();
const button = screen.getByRole('button', { name: 'chat.selection.quote' });
- fireEvent.pointerDown(button, { ...press, button: 2 });
- fireEvent.pointerUp(button, { ...press, button: 2 });
- expect(quote).not.toHaveBeenCalled();
- collapseSelection();
- expect(screen.queryByRole('toolbar')).toBeNull();
+
+ fireEvent.pointerDown(button, press);
+ fireEvent(document, new Event('selectionchange'));
+ fireEvent.pointerUp(button, press);
+
+ expect(quote).toHaveBeenCalledExactlyOnceWith(TEXT);
});
- it.each(['Enter', ' '])('preserves %s keyboard activation', (key) => {
+ it('cancels a pending recompute when a press defers selection clearing', () => {
mountToolbar();
- fireEvent.keyDown(screen.getByRole('button', { name: 'chat.selection.quote' }), { key });
+ const button = screen.getByRole('button', { name: 'chat.selection.quote' });
+
+ fireEvent(document, new Event('selectionchange'));
+ act(() => vi.advanceTimersByTime(50));
+ fireEvent.pointerDown(button, press);
+ window.getSelection()!.removeAllRanges();
+ fireEvent(document, new Event('selectionchange'));
+
+ act(() => vi.advanceTimersByTime(100));
+ expect(screen.queryByRole('toolbar')).not.toBeNull();
+
+ fireEvent.pointerUp(button, press);
+
expect(quote).toHaveBeenCalledExactlyOnceWith(TEXT);
});
- it('dismisses a cleared selection when no action is being pressed', () => {
+ it.each([
+ ['secondary button', { ...press, button: 2, isPrimary: false }],
+ ['without a matching press', null],
+ ])('does not activate %s', (_case, down) => {
+ mountToolbar();
+ const button = screen.getByRole('button', { name: 'chat.selection.quote' });
+
+ if (down) fireEvent.pointerDown(button, down);
+ fireEvent.pointerUp(button, press);
+
+ expect(quote).not.toHaveBeenCalled();
+ });
+
+ it('does not activate when the pointer id or button does not match', () => {
+ mountToolbar();
+ const quoteButton = screen.getByRole('button', { name: 'chat.selection.quote' });
+ const askButton = screen.getByRole('button', { name: 'chat.selection.askInNew' });
+
+ fireEvent.pointerDown(quoteButton, press);
+ fireEvent.pointerUp(quoteButton, { ...press, pointerId: 2 });
+ expect(quote).not.toHaveBeenCalled();
+
+ fireEvent.pointerDown(quoteButton, press);
+ fireEvent.pointerUp(askButton, press);
+ expect(quote).not.toHaveBeenCalled();
+ expect(ask).not.toHaveBeenCalled();
+ });
+
+ it('does not reuse a press after a new gesture starts elsewhere', () => {
mountToolbar();
- collapseSelection();
+ const button = screen.getByRole('button', { name: 'chat.selection.quote' });
+
+ fireEvent.pointerDown(button, press);
+ fireEvent.pointerDown(document.body, press);
+ fireEvent.pointerUp(button, press);
+
+ expect(quote).not.toHaveBeenCalled();
+ });
+
+ it('hides after a cleared selection while scrolling', () => {
+ const container = mountToolbar();
+ expect(screen.queryByRole('toolbar')).not.toBeNull();
+
+ clearSelection();
+ fireEvent.scroll(container);
+ act(() => vi.advanceTimersByTime(200));
+
expect(screen.queryByRole('toolbar')).toBeNull();
});
+
+ it('keeps the touch toolbar outside the selection-handle hit region above', () => {
+ mountToolbar();
+ const toolbar = screen.getByRole('toolbar');
+ const top = Number.parseFloat(toolbar.getAttribute('style')!.match(/top:\s*([^;]+)/)![1]);
+
+ expect(top + 36).toBeLessThanOrEqual(selectionLineRects[0].top - 44 - 8);
+ });
+
+ it('keeps the touch toolbar outside the selection-handle hit region below', () => {
+ selectionBounds = { ...defaultBounds, top: 700, bottom: 736 };
+ selectionLineRects = [selectionBounds];
+ mountToolbar();
+ const toolbar = screen.getByRole('toolbar');
+ const top = Number.parseFloat(toolbar.getAttribute('style')!.match(/top:\s*([^;]+)/)![1]);
+
+ expect(top).toBeGreaterThanOrEqual(selectionBounds.bottom + 44 + 8);
+ });
+
+ it('clamps a touch toolbar when the selection is above the viewport', () => {
+ selectionBounds = { ...defaultBounds, top: -120, bottom: -84 };
+ selectionLineRects = [selectionBounds];
+ mountToolbar();
+ const toolbar = screen.getByRole('toolbar');
+ const top = Number.parseFloat(toolbar.getAttribute('style')!.match(/top:\s*([^;]+)/)![1]);
+
+ expect(top).toBe(8);
+ });
+
+ it('clamps a touch toolbar when the selection is below the viewport', () => {
+ selectionBounds = { ...defaultBounds, top: 900, bottom: 936 };
+ selectionLineRects = [selectionBounds];
+ mountToolbar();
+ const toolbar = screen.getByRole('toolbar');
+ const top = Number.parseFloat(toolbar.getAttribute('style')!.match(/top:\s*([^;]+)/)![1]);
+
+ expect(top).toBe(800);
+ });
+
+ it.each([
+ {
+ name: 'first line is near the top and the last line is below the viewport',
+ bounds: { top: 20, bottom: 1036, left: 40, right: 340, width: 300, height: 1016 },
+ lines: [
+ { top: 20, bottom: 56, left: 40, right: 340, width: 300, height: 36 },
+ { top: 1000, bottom: 1036, left: 40, right: 340, width: 300, height: 36 },
+ ],
+ },
+ {
+ name: 'first line is above the viewport and the last line is near the bottom',
+ bounds: { top: -120, bottom: 800, left: 40, right: 340, width: 300, height: 920 },
+ lines: [
+ { top: -120, bottom: -84, left: 40, right: 340, width: 300, height: 36 },
+ { top: 764, bottom: 800, left: 40, right: 340, width: 300, height: 36 },
+ ],
+ },
+ {
+ name: 'both endpoint lines are visible with a safe middle band',
+ bounds: { top: 80, bottom: 764, left: 40, right: 340, width: 300, height: 684 },
+ lines: [
+ { top: 80, bottom: 116, left: 40, right: 340, width: 300, height: 36 },
+ { top: 728, bottom: 764, left: 40, right: 340, width: 300, height: 36 },
+ ],
+ },
+ ])('avoids both endpoint hit regions when $name', ({ bounds, lines }) => {
+ selectionBounds = bounds;
+ selectionLineRects = lines;
+ mountToolbar();
+ const toolbar = screen.getByRole('toolbar');
+ const top = Number.parseFloat(toolbar.getAttribute('style')!.match(/top:\s*([^;]+)/)![1]);
+
+ for (const line of [lines[0], lines[lines.length - 1]]) {
+ const outsideHitRegion = (
+ top >= line.bottom + 44 + 8
+ || top + 36 <= line.top - 44 - 8
+ );
+ expect(outsideHitRegion).toBe(true);
+ }
+ });
+
+ it('keeps desktop placement at the original selection gap', () => {
+ coarsePointer = false;
+ selectionBounds = { ...defaultBounds, top: 80, bottom: 116 };
+ selectionLineRects = [selectionBounds];
+ mountToolbar();
+ const toolbar = screen.getByRole('toolbar');
+ const top = Number.parseFloat(toolbar.getAttribute('style')!.match(/top:\s*([^;]+)/)![1]);
+
+ expect(top).toBe(36);
+ });
+
+ it.each(['Enter', ' '])('preserves %s keyboard activation', (key) => {
+ mountToolbar();
+ fireEvent.keyDown(screen.getByRole('button', { name: 'chat.selection.quote' }), { key });
+ expect(quote).toHaveBeenCalledExactlyOnceWith(TEXT);
+ });
});
diff --git a/ui/src/components/workbench/SelectionQuoteToolbar.tsx b/ui/src/components/workbench/SelectionQuoteToolbar.tsx
index 683685bbc..0e86cbf55 100644
--- a/ui/src/components/workbench/SelectionQuoteToolbar.tsx
+++ b/ui/src/components/workbench/SelectionQuoteToolbar.tsx
@@ -6,11 +6,42 @@ import { Check, Copy, GitFork, TextQuote } from 'lucide-react';
import { Button } from '../ui/button';
import { copyTextToClipboard } from '../../lib/utils';
-type SelectionState = { text: string; top: number; bottom: number; left: number };
+type SelectionRect = {
+ top: number;
+ bottom: number;
+ left: number;
+ right: number;
+ width: number;
+ height: number;
+};
+
+type SelectionState = {
+ text: string;
+ top: number;
+ bottom: number;
+ left: number;
+ first: SelectionRect;
+ last: SelectionRect;
+};
const TOOLBAR_H = 36;
const GAP = 8;
const EDGE = 8;
+const PRESS_GRACE_MS = 700;
+// iOS keeps touch sequences that start within this padding around a selection
+// handle in its native selection gesture recognizer. Keep the web toolbar
+// outside that region so pointerup/touchend remains deliverable to the button.
+const SELECTION_HANDLE_PADDING = 44;
+const SELECTION_HANDLE_GAP = SELECTION_HANDLE_PADDING + GAP;
+
+const toSelectionRect = (rect: DOMRect | DOMRectReadOnly): SelectionRect => ({
+ top: rect.top,
+ bottom: rect.bottom,
+ left: rect.left,
+ right: rect.right,
+ width: rect.width,
+ height: rect.height,
+});
// A floating toolbar that appears over a text selection inside the chat
// transcript. "Quote" appends the (quoted) selection to the current composer
@@ -34,8 +65,15 @@ export const SelectionQuoteToolbar: React.FC<{
const [sel, setSel] = useState<SelectionState | null>(null);
const [copied, setCopied] = useState(false);
const toolbarRef = useRef<HTMLDivElement>(null);
- const activePointerId = useRef<number | null>(null);
+ const pressRef = useRef<{
+ pointerId: number;
+ button: HTMLButtonElement;
+ selectionText: string;
+ deferred: boolean;
+ } | null>(null);
+ const pressExpiryRef = useRef<number | null>(null);
const [width, setWidth] = useState(0);
+ const [height, setHeight] = useState(TOOLBAR_H);
// Touch (coarse pointer — phones AND tablets/iPads) is where the OS selection
// menu coexists; it drives the stagger-positioning + the touch-only Copy.
const [isTouch] = useState(
@@ -43,9 +81,6 @@ export const SelectionQuoteToolbar: React.FC<{
);
const recompute = useCallback(() => {
- // The press owns this snapshot until release/cancellation. Touch selection
- // changes can otherwise remove the button before its pointerup is delivered.
- if (activePointerId.current !== null) return;
const container = containerRef.current;
if (!container) return;
const selection = window.getSelection();
@@ -59,21 +94,69 @@ export const SelectionQuoteToolbar: React.FC<{
setSel(null);
return;
}
- const rect = range.getBoundingClientRect();
- if (!rect.width && !rect.height) {
+ const rect = toSelectionRect(range.getBoundingClientRect());
+ const lineRects = Array.from(range.getClientRects())
+ .filter((lineRect) => lineRect.width || lineRect.height)
+ .map(toSelectionRect);
+ if (!rect.width && !rect.height && lineRects.length === 0) {
setSel(null);
return;
}
- setSel({ text, top: rect.top, bottom: rect.bottom, left: rect.left + rect.width / 2 });
+ setSel({
+ text,
+ top: rect.top,
+ bottom: rect.bottom,
+ left: rect.left + rect.width / 2,
+ first: lineRects[0] ?? rect,
+ last: lineRects[lineRects.length - 1] ?? rect,
+ });
}, [containerRef]);
+ const clearPress = useCallback((recomputeDeferred = true) => {
+ const deferred = pressRef.current?.deferred ?? false;
+ if (pressExpiryRef.current !== null) {
+ window.clearTimeout(pressExpiryRef.current);
+ pressExpiryRef.current = null;
+ }
+ pressRef.current = null;
+ if (deferred && recomputeDeferred) recompute();
+ }, [recompute]);
+ const armPressExpiry = useCallback(() => {
+ const press = pressRef.current;
+ if (!press || pressExpiryRef.current !== null) return;
+ pressExpiryRef.current = window.setTimeout(() => {
+ if (pressRef.current !== press) return;
+ pressRef.current = null;
+ pressExpiryRef.current = null;
+ recompute();
+ }, PRESS_GRACE_MS);
+ }, [recompute]);
+
useEffect(() => {
const container = containerRef.current;
if (!container) return;
let timer = 0;
// Debounce so the toolbar appears when the selection settles, not on every
// intermediate range while dragging the selection / handles.
+ const onPointerDown = () => {
+ // A new gesture invalidates any prior button press, including one whose
+ // terminal event was delivered outside the toolbar or not delivered at all.
+ clearPress();
+ };
const onSelectionChange = () => {
+ const press = pressRef.current;
+ const currentText = window.getSelection()?.toString().trim() ?? '';
+ if (press && (!currentText || currentText === press.selectionText)) {
+ // Keep the rendered snapshot alive for a short time so a browser
+ // selectionchange between pointerdown and pointerup cannot cancel a
+ // valid tap. The expiry still releases missing terminal events.
+ window.clearTimeout(timer);
+ timer = 0;
+ press.deferred = true;
+ armPressExpiry();
+ return;
+ }
+ clearPress();
window.clearTimeout(timer);
timer = window.setTimeout(recompute, 150);
};
@@ -81,24 +164,30 @@ export const SelectionQuoteToolbar: React.FC<{
// at the new position once it settles. The toolbar persists as long as the
// selection exists, so the user can scroll to move it clear of the OS menu.
const onScroll = () => {
- if (activePointerId.current !== null) return;
+ clearPress();
setSel(null);
window.clearTimeout(timer);
timer = window.setTimeout(recompute, 150);
};
+ document.addEventListener('pointerdown', onPointerDown, true);
document.addEventListener('selectionchange', onSelectionChange);
container.addEventListener('scroll', onScroll, { passive: true });
return () => {
window.clearTimeout(timer);
+ clearPress(false);
+ document.removeEventListener('pointerdown', onPointerDown, true);
document.removeEventListener('selectionchange', onSelectionChange);
container.removeEventListener('scroll', onScroll);
};
- }, [containerRef, recompute]);
+ }, [armPressExpiry, clearPress, containerRef, recompute]);
// Measure the rendered toolbar so we can clamp it on-screen by its real width
- // (label widths vary by locale + which actions are shown).
+ // and height (label widths vary by locale + which actions are shown).
useLayoutEffect(() => {
- if (sel && toolbarRef.current) setWidth(toolbarRef.current.offsetWidth);
+ if (sel && toolbarRef.current) {
+ setWidth(toolbarRef.current.offsetWidth);
+ setHeight(toolbarRef.current.offsetHeight || TOOLBAR_H);
+ }
}, [sel, onQuote, onAskInNew, isTouch]);
if (!sel) return null;
@@ -107,7 +196,7 @@ export const SelectionQuoteToolbar: React.FC<{
if (!onQuote && !onAskInNew && !isTouch) return null;
const dismiss = () => {
- activePointerId.current = null;
+ clearPress(false);
window.getSelection()?.removeAllRanges();
setSel(null);
setCopied(false);
@@ -130,67 +219,120 @@ export const SelectionQuoteToolbar: React.FC<{
});
};
- const cancelPress = (e: React.PointerEvent) => {
- if (activePointerId.current !== e.pointerId) return;
- activePointerId.current = null;
- recompute();
- };
-
- // Capture the pointer so release/cancellation still arrives after it moves
- // away. Release must land inside the original button to activate; scrolling
- // the toolbar can cancel the gesture without accidentally quoting or forking.
- // preventDefault avoids a mouse press moving focus/selection. It does not
- // replace the explicit snapshot lifetime above.
- const pressHandlers = {
- onPointerDown: (e: React.PointerEvent<HTMLButtonElement>) => {
- if (!e.isPrimary || e.button !== 0 || activePointerId.current !== null) return;
- e.preventDefault();
- activePointerId.current = e.pointerId;
- e.currentTarget.setPointerCapture(e.pointerId);
- },
- onPointerCancel: cancelPress,
- onLostPointerCapture: cancelPress,
+ // Activate on pointerup (mouse + touch) and Enter/Space (keyboard). The
+ // pointerdown preventDefault keeps the text selection alive. We deliberately
+ // keep only a short-lived gesture match here: iOS can deliver pointerdown
+ // for a touch near a selection handle without ever delivering pointerup, so
+ // state that waits for an end event must not gate selection recomputation.
+ const handlePointerDown = (e: React.PointerEvent<HTMLButtonElement>) => {
+ clearPress();
+ if (!e.isPrimary || e.button !== 0) return;
+ e.preventDefault();
+ pressRef.current = {
+ pointerId: e.pointerId,
+ button: e.currentTarget,
+ selectionText: sel.text,
+ deferred: false,
+ };
};
- const releasePress = (e: React.PointerEvent<HTMLButtonElement>, run: () => void) => {
- if (activePointerId.current !== e.pointerId) return;
- activePointerId.current = null;
+ const handlePointerUp = (e: React.PointerEvent<HTMLButtonElement>, run: () => void) => {
+ const press = pressRef.current;
+ const mismatch = (
+ !press
+ || !e.isPrimary
+ || e.button !== 0
+ || press.pointerId !== e.pointerId
+ || press.button !== e.currentTarget
+ );
const rect = e.currentTarget.getBoundingClientRect();
- if (e.clientX >= rect.left && e.clientX <= rect.right
- && e.clientY >= rect.top && e.clientY <= rect.bottom) {
- run();
+ const releasedInside = (
+ !mismatch
+ && e.clientX >= rect.left
+ && e.clientX <= rect.right
+ && e.clientY >= rect.top
+ && e.clientY <= rect.bottom
+ );
+ clearPress(!releasedInside);
+ if (!releasedInside) {
+ return;
}
- recompute();
+ run();
};
- const activateWithKey = (e: React.KeyboardEvent, run: () => void) => {
+ const handleKeyDown = (e: React.KeyboardEvent, run: () => void) => {
if (e.key === 'Enter' || e.key === ' ') {
e.preventDefault();
run();
}
};
- const roomAbove = sel.top > TOOLBAR_H + GAP + EDGE;
- const roomBelow = window.innerHeight - sel.bottom > TOOLBAR_H + GAP + EDGE;
- let below: boolean;
- if (isTouch) {
- // The OS selection menu can't be queried or suppressed, but it sits toward
- // screen center: BELOW a selection in the top half, ABOVE one in the bottom
- // half. Stagger ours toward the nearer edge (the opposite side) so the two
- // don't overlap. Fall back if that edge is clipped.
- below = (sel.top + sel.bottom) / 2 >= window.innerHeight / 2;
- if (below && !roomBelow) below = false;
- else if (!below && !roomAbove) below = true;
- } else {
- // Desktop has no OS selection menu — just prefer above, flip if no room.
- below = !roomAbove;
- }
- const rawTop = below ? sel.bottom + GAP : sel.top - TOOLBAR_H - GAP;
- // Keep the toolbar on-screen vertically too, so it stays visible (and the
- // user can still act) when the selection is scrolled near a viewport edge.
- const top = Math.min(Math.max(rawTop, EDGE), window.innerHeight - TOOLBAR_H - EDGE);
+ const toolbarHeight = height || TOOLBAR_H;
+ const placementGap = isTouch ? SELECTION_HANDLE_GAP : GAP;
+ const topEdge = EDGE;
+ const bottomEdge = Math.max(EDGE, window.innerHeight - toolbarHeight - EDGE);
+ const clampTop = (rawTop: number) => Math.min(Math.max(rawTop, topEdge), bottomEdge);
+ const preferBelow = (sel.top + sel.bottom) / 2 >= window.innerHeight / 2;
+ const preferredAboveTop = clampTop(sel.first.top - toolbarHeight - placementGap);
+ const preferredBelowTop = clampTop(sel.last.bottom + placementGap);
// Clamp by the on-screen (capped) width so a toolbar wider than the viewport
// centers + scrolls internally instead of pushing an edge off-screen.
- const half = Math.min(width, window.innerWidth - 2 * EDGE) / 2;
- const left = Math.min(Math.max(sel.left, EDGE + half), window.innerWidth - EDGE - half);
+ const leftHalf = Math.min(width, window.innerWidth - 2 * EDGE) / 2;
+ const left = Math.min(
+ Math.max(sel.left, EDGE + leftHalf),
+ window.innerWidth - EDGE - leftHalf,
+ );
+
+ let top: number;
+ if (!isTouch) {
+ // Desktop has no OS selection menu — just prefer above, flip if no room.
+ top = sel.first.top >= toolbarHeight + GAP + EDGE
+ ? preferredAboveTop
+ : preferredBelowTop;
+ } else {
+ // A toolbar is safe only when its full rectangle misses both endpoint
+ // handle regions. This matters for long selections: neither the area above
+ // the first line nor the area below the last line may fit, while the
+ // middle band between those two regions still can.
+ const measuredWidth = width || Math.max(0, window.innerWidth - 2 * EDGE);
+ const measuredHalf = Math.min(measuredWidth, window.innerWidth - 2 * EDGE) / 2;
+ const toolbarLeft = left - measuredHalf;
+ const toolbarRight = left + measuredHalf;
+ const safeRects = [sel.first, sel.last].map((rect) => ({
+ top: rect.top - SELECTION_HANDLE_GAP,
+ bottom: rect.bottom + SELECTION_HANDLE_GAP,
+ left: rect.left - SELECTION_HANDLE_GAP,
+ right: rect.right + SELECTION_HANDLE_GAP,
+ }));
+ const intersectsSafeRect = (candidateTop: number) => safeRects.some((rect) => (
+ toolbarLeft < rect.right
+ && toolbarRight > rect.left
+ && candidateTop < rect.bottom
+ && candidateTop + toolbarHeight > rect.top
+ ));
+ const overlapArea = (candidateTop: number) => safeRects.reduce((total, rect) => {
+ const overlapWidth = Math.max(0, Math.min(toolbarRight, rect.right) - Math.max(toolbarLeft, rect.left));
+ const overlapHeight = Math.max(
+ 0,
+ Math.min(candidateTop + toolbarHeight, rect.bottom) - Math.max(candidateTop, rect.top),
+ );
+ return total + overlapWidth * overlapHeight;
+ }, 0);
+ const middleStart = sel.first.bottom + SELECTION_HANDLE_GAP;
+ const middleEnd = sel.last.top - SELECTION_HANDLE_GAP - toolbarHeight;
+ const middleTop = middleStart <= middleEnd
+ ? clampTop((middleStart + middleEnd) / 2)
+ : null;
+ const candidates = [
+ preferBelow ? preferredBelowTop : preferredAboveTop,
+ preferBelow ? preferredAboveTop : preferredBelowTop,
+ ...(middleTop === null ? [] : [middleTop]),
+ topEdge,
+ bottomEdge,
+ ];
+ const safeCandidate = candidates.find((candidateTop) => !intersectsSafeRect(candidateTop));
+ top = safeCandidate ?? candidates.reduce((best, candidateTop) => (
+ overlapArea(candidateTop) < overlapArea(best) ? candidateTop : best
+ ));
+ }
const itemClass = 'h-9 gap-1.5 rounded-none px-3 text-[13px] font-medium';
@@ -207,9 +349,9 @@ export const SelectionQuoteToolbar: React.FC<{
<Button
variant="ghost"
className={itemClass}
- {...pressHandlers}
- onPointerUp={(e) => releasePress(e, runQuote)}
- onKeyDown={(e) => activateWithKey(e, runQuote)}
+ onPointerDown={handlePointerDown}
+ onPointerUp={(e) => handlePointerUp(e, runQuote)}
+ onKeyDown={(e) => handleKeyDown(e, runQuote)}
>
<TextQuote className="size-3.5 text-muted" />
{t('chat.selection.quote')}
@@ -221,9 +363,9 @@ export const SelectionQuoteToolbar: React.FC<{
<Button
variant="ghost"
className={itemClass}
- {...pressHandlers}
- onPointerUp={(e) => releasePress(e, runAsk)}
- onKeyDown={(e) => activateWithKey(e, runAsk)}
+ onPointerDown={handlePointerDown}
+ onPointerUp={(e) => handlePointerUp(e, runAsk)}
+ onKeyDown={(e) => handleKeyDown(e, runAsk)}
>
<GitFork className="size-3.5 text-muted" />
{t('chat.selection.askInNew')}
@@ -236,9 +378,9 @@ export const SelectionQuoteToolbar: React.FC<{
<Button
variant="ghost"
className={itemClass}
- {...pressHandlers}
- onPointerUp={(e) => releasePress(e, runCopy)}
- onKeyDown={(e) => activateWithKey(e, runCopy)}
+ onPointerDown={handlePointerDown}
+ onPointerUp={(e) => handlePointerUp(e, runCopy)}
+ onKeyDown={(e) => handleKeyDown(e, runCopy)}
>
{copied ? <Check className="size-3.5 text-mint-ink" /> : <Copy className="size-3.5 text-muted" />}
{t('chat.selection.copy')}