'use client' import dynamic from 'next/dynamic' import { useEffect, useLayoutEffect, useRef, useState } from 'react' import type { PointerEvent as ReactPointerEvent } from 'react' import { BookmarkPlus, Highlighter, MessageSquareQuote, MoreHorizontal, StickyNote, Underline, } from 'lucide-react' import { useTranslation } from 'react-i18next' import Tooltip from '@/shared/ui/Tooltip' import { useDevice } from '@/hooks/useDevice' import { ANNOTATION_COLORS, ANNOTATION_SWATCH, type AnnotationColor } from '@/lib/reading-api' import { PlayAudioButton } from '@/components/voice/SpeechButton' const AddToNote = dynamic(() => import('@/features/notes/components/AddToNote'), { ssr: false }) export interface AnnotationPopoverProps { /** Viewport coordinates of the selection's end. */ anchor: { x: number; y: number } quote: string noteSource?: { title: string; url: string; id: string } onHighlight: (color: AnnotationColor) => void onUnderline: (color: AnnotationColor) => void onNote: (note: string, color: AnnotationColor) => void onCitation: (color: AnnotationColor) => void onAsk: () => void onDismiss: () => void /** * AI actions on the selection, shown as a second row under the marking * tools. Without them the popover is the annotation toolbar it always was, * with "Ask about this" as its last icon. */ aiActions?: PopoverAiAction[] } export interface PopoverAiAction { key: string /** Short chip text ("Explain"); `title` carries the full name. */ label: string title: string onClick: () => void } /** Chips that fit on the row before the rest go behind ⋯. */ const INLINE_AI_ACTIONS = 3 /** How far the sheet must be pulled down before the drag counts as "close". */ const DRAG_CLOSE_THRESHOLD = 48 /** * Toolbar that appears over a selection. * * On a desktop it is positioned in fixed coordinates and clamped to the * window after mount, so a selection near the top or right edge still shows * the whole toolbar instead of being cut off — the failure people actually * hit, since the interesting text is often at the top of a page. * * Below 768px it is a bottom card instead (#916): the anchored popover that * a long-press summons competes with the system selection menu for the same * few pixels around the finger, so on a phone the panel drops to the bottom * of the screen. The collapsed rows fit without scrolling; the expanded * states — the note editor, the extra AI actions — get a capped, scrollable * body; and a drag handle offers pull-down-to-dismiss next to Escape and * tapping the page. * * Dismissal is on Escape and on pointerdown outside. Deliberately not on blur: * clicking a colour swatch blurs the toolbar, and a blur-based dismissal would * race the click and eat every second annotation. */ export function AnnotationPopover({ anchor, quote, noteSource, onHighlight, onUnderline, onNote, onCitation, onAsk, onDismiss, aiActions, }: AnnotationPopoverProps) { const { t } = useTranslation() const { isMobile } = useDevice() const ref = useRef(null) const [color, setColor] = useState('yellow') const [noteOpen, setNoteOpen] = useState(false) const [note, setNote] = useState('') const [overflowOpen, setOverflowOpen] = useState(false) const inlineAi = aiActions?.slice(0, INLINE_AI_ACTIONS) ?? [] const overflowAi = aiActions?.slice(INLINE_AI_ACTIONS) ?? [] const [position, setPosition] = useState({ left: anchor.x, top: anchor.y }) // -- pull-down-to-dismiss ------------------------------------------------ // // Only the handle drags; the body stays live so a scroll or a tap inside // the card never reads as "close". The threshold is generous: an accidental // nudge moves the sheet visually without closing it. const dragRef = useRef<{ id: number; startY: number } | null>(null) const [dragOffset, setDragOffset] = useState(0) const onHandlePointerDown = (event: ReactPointerEvent) => { dragRef.current = { id: event.pointerId, startY: event.clientY } try { event.currentTarget.setPointerCapture(event.pointerId) } catch { // jsdom / rare engines without capture: element handlers still fire. } } const onHandlePointerMove = (event: ReactPointerEvent) => { const drag = dragRef.current if (!drag || drag.id !== event.pointerId) return setDragOffset(Math.max(0, event.clientY - drag.startY)) } const onHandlePointerEnd = (event: ReactPointerEvent) => { const drag = dragRef.current if (!drag || drag.id !== event.pointerId) return dragRef.current = null const travelled = Math.max(0, event.clientY - drag.startY) setDragOffset(0) if (travelled >= DRAG_CLOSE_THRESHOLD) onDismiss() } useLayoutEffect(() => { if (isMobile) return const element = ref.current if (!element) return const box = element.getBoundingClientRect() const margin = 10 // Prefer above the selection; flip below when there is no room up there. let top = anchor.y - box.height - margin if (top < margin) top = anchor.y + 24 const left = Math.min( Math.max(margin, anchor.x - box.width / 2), window.innerWidth - box.width - margin ) setPosition({ left, top: Math.min(top, window.innerHeight - box.height - margin), }) }, [anchor.x, anchor.y, isMobile, noteOpen, overflowOpen]) useEffect(() => { const onKey = (event: KeyboardEvent) => { if (event.key === 'Escape') { event.stopPropagation() onDismiss() } } const onPointerDown = (event: PointerEvent) => { if (!ref.current?.contains(event.target as Node)) onDismiss() } document.addEventListener('keydown', onKey) // Capture phase: the reader's own mouseup handler would otherwise clear the // selection before this listener ran. document.addEventListener('pointerdown', onPointerDown, true) return () => { document.removeEventListener('keydown', onKey) document.removeEventListener('pointerdown', onPointerDown, true) } }, [onDismiss]) // The rows are shared by both presentations; only the frame they sit in // differs. `expanded` is what makes the body long: the note editor and the // overflow action list are the states whose content can outgrow a thumb's // reach, so they are the ones that switch the body to capped-and-scrollable. const expanded = noteOpen || overflowOpen const body = ( <>
event.preventDefault()}>
{ANNOTATION_COLORS.map(swatch => (
onHighlight(color)} /> onUnderline(color)} /> setNoteOpen(open => !open)} /> onCitation(color)} /> {aiActions ? null : ( )}
{noteSource && ( )} {aiActions && (
{inlineAi.map(action => ( ))} {overflowAi.length > 0 && ( setOverflowOpen(open => !open)} /> )}
)} {overflowOpen && overflowAi.length > 0 && (
{overflowAi.map(action => ( ))}
)} {noteOpen && (

“{quote}”