diff --git a/packages/editor/App.tsx b/packages/editor/App.tsx index 5056dba..d75e730 100644 --- a/packages/editor/App.tsx +++ b/packages/editor/App.tsx @@ -1,4 +1,4 @@ -import React, { useState, useEffect, useMemo, useRef } from 'react'; +import React, { useState, useEffect, useLayoutEffect, useMemo, useRef } from 'react'; import { type Origin, getAgentName } from '@plannotator/shared/agents'; import { parseMarkdownToBlocks, exportAnnotations, exportLinkedDocAnnotations, exportEditorAnnotations, extractFrontmatter, wrapFeedbackForAgent, Frontmatter } from '@plannotator/ui/utils/parser'; import { Viewer, ViewerHandle } from '@plannotator/ui/components/Viewer'; @@ -6,7 +6,7 @@ import { AnnotationPanel } from '@plannotator/ui/components/AnnotationPanel'; import { ExportModal } from '@plannotator/ui/components/ExportModal'; import { ImportModal } from '@plannotator/ui/components/ImportModal'; import { ConfirmDialog } from '@plannotator/ui/components/ConfirmDialog'; -import { Annotation, Block, EditorMode, type InputMethod, type ImageAttachment } from '@plannotator/ui/types'; +import { Annotation, Block, EditorMode, type InputMethod, type ImageAttachment, type ActionsLabelMode } from '@plannotator/ui/types'; import { ThemeProvider } from '@plannotator/ui/components/ThemeProvider'; import { AnnotationToolstrip } from '@plannotator/ui/components/AnnotationToolstrip'; import { StickyHeaderLane } from '@plannotator/ui/components/StickyHeaderLane'; @@ -97,6 +97,36 @@ const App: React.FC = () => { return stored === 'true'; }); const [uiPrefs, setUiPrefs] = useState(() => getUIPreferences()); + + // Plan-area width (inside the OverlayScrollArea, after sidebar/panel + // shrinkage) drives the action button label compactness. ResizeObserver + // fires every frame during a resize drag, so we store only the BUCKET + // ('full' | 'short' | 'icon') in state — App.tsx then re-renders at + // most twice across an entire drag (once per threshold crossing) instead + // of on every pixel, which would chug the whole tree. + // + // full → "Global comment" / "Copy plan" — fits when planArea >= 800 + // short → "Comment" / "Copy" — fits when planArea >= 680 + // icon → labels hidden — fallback below that + const planAreaRef = useRef(null); + const [actionsLabelMode, setActionsLabelMode] = useState('full'); + // useLayoutEffect + synchronous getBoundingClientRect so the initial + // bucket is set before the browser paints. Otherwise narrow viewports + // get a one-frame flash of "Global comment"/"Copy plan" labels before + // the ResizeObserver callback collapses them. + useLayoutEffect(() => { + const el = planAreaRef.current; + if (!el) return; + const bucket = (w: number): ActionsLabelMode => + w >= 800 ? 'full' : w >= 680 ? 'short' : 'icon'; + setActionsLabelMode(bucket(el.getBoundingClientRect().width)); + const ro = new ResizeObserver(([entry]) => { + const next = bucket(entry.contentRect.width); + setActionsLabelMode((prev) => (prev === next ? prev : next)); + }); + ro.observe(el); + return () => ro.disconnect(); + }, []); const [isApiMode, setIsApiMode] = useState(false); const [origin, setOrigin] = useState(null); const [gitUser, setGitUser] = useState(); @@ -1431,7 +1461,7 @@ const App: React.FC = () => { showVaultTab={showVaultTab} hasFileAnnotations={hasFileAnnotations} hasVaultAnnotations={hasVaultAnnotations} - className="hidden lg:flex" + className="hidden lg:flex absolute left-0 top-0 z-10" /> )} @@ -1492,7 +1522,7 @@ const App: React.FC = () => { {/* Document Area */} @@ -1506,7 +1536,7 @@ const App: React.FC = () => { cancelText="Dismiss" showCancel /> -
+
{/* Sticky header lane — ghost bar that pins the toolstrip + badges at top: 12px once the user scrolls. Invisible at top of doc; original toolstrip/badges remain the source of @@ -1526,6 +1556,7 @@ const App: React.FC = () => { onPlanDiffToggle={() => setIsPlanDiffActive(!isPlanDiffActive)} archiveInfo={archive.currentInfo} maxWidth={planMaxWidth} + remountToken={linkedDocHook.isActive ? `doc:${linkedDocHook.filepath}` : 'plan'} /> )} @@ -1605,6 +1636,7 @@ const App: React.FC = () => { archiveInfo={archive.currentInfo} onToggleCheckbox={checkbox.toggle} checkboxOverrides={checkbox.overrides} + actionsLabelMode={actionsLabelMode} />
@@ -1622,7 +1654,6 @@ const App: React.FC = () => { onSelect={setSelectedAnnotationId} onDelete={handleDeleteAnnotation} onEdit={handleEditAnnotation} - shareUrl={shareUrl} sharingEnabled={sharingEnabled} width={panelResize.width} editorAnnotations={editorAnnotations} @@ -1631,6 +1662,7 @@ const App: React.FC = () => { onQuickCopy={async () => { await navigator.clipboard.writeText(wrapFeedbackForAgent(annotationsOutput)); }} + onShare={shareUrl ? () => { setIsPanelOpen(false); setInitialExportTab('share'); setShowExport(true); } : undefined} otherFileAnnotations={otherFileAnnotations} onOtherFileAnnotationsClick={handleFlashAnnotatedFiles} /> diff --git a/packages/ui/components/AgentsTab.tsx b/packages/ui/components/AgentsTab.tsx index 8be0758..3cd1eca 100644 --- a/packages/ui/components/AgentsTab.tsx +++ b/packages/ui/components/AgentsTab.tsx @@ -264,9 +264,9 @@ export const AgentsTab: React.FC = ({ diff --git a/packages/ui/components/AnnotationPanel.tsx b/packages/ui/components/AnnotationPanel.tsx index 83ca3d1..b76c4fa 100644 --- a/packages/ui/components/AnnotationPanel.tsx +++ b/packages/ui/components/AnnotationPanel.tsx @@ -14,13 +14,13 @@ interface PanelProps { onDelete: (id: string) => void; onEdit?: (id: string, updates: Partial) => void; selectedId: string | null; - shareUrl?: string; sharingEnabled?: boolean; width?: number; editorAnnotations?: EditorAnnotation[]; onDeleteEditorAnnotation?: (id: string) => void; onClose?: () => void; onQuickCopy?: () => Promise; + onShare?: () => void; otherFileAnnotations?: { count: number; files: number }; onOtherFileAnnotationsClick?: () => void; } @@ -33,18 +33,17 @@ export const AnnotationPanel: React.FC = ({ onDelete, onEdit, selectedId, - shareUrl, sharingEnabled = true, width, editorAnnotations, onDeleteEditorAnnotation, onClose, onQuickCopy, + onShare, otherFileAnnotations, onOtherFileAnnotationsClick, }) => { const isMobile = useIsMobile(); - const [copied, setCopied] = useState(false); const [copiedText, setCopiedText] = useState(false); const listRef = useRef(null); const sortedAnnotations = [...annotations].sort((a, b) => a.createdA - b.createdA); @@ -59,17 +58,6 @@ export const AnnotationPanel: React.FC = ({ } }, [selectedId]); - const handleQuickShare = async () => { - if (!shareUrl) return; - try { - await navigator.clipboard.writeText(shareUrl); - setCopied(true); - setTimeout(() => setCopied(false), 2000); - } catch (e) { - console.error('Failed to copy:', e); - } - }; - if (!isOpen) return null; const panel = ( @@ -187,31 +175,20 @@ export const AnnotationPanel: React.FC = ({ - Quick Copy + Copy )} )} - {sharingEnabled && shareUrl && ( + {sharingEnabled && onShare && ( )} diff --git a/packages/ui/components/AttachmentsButton.tsx b/packages/ui/components/AttachmentsButton.tsx index 17e979f..3d0f187 100644 --- a/packages/ui/components/AttachmentsButton.tsx +++ b/packages/ui/components/AttachmentsButton.tsx @@ -46,6 +46,9 @@ interface AttachmentsButtonProps { onAdd: (image: ImageAttachment) => void; onRemove: (path: string) => void; variant?: 'toolbar' | 'inline'; + /** Hide the "Images" label (icon-only). When images.length > 0 the + * numeric badge still shows so the user can see the count. */ + hideLabel?: boolean; } export const AttachmentsButton: React.FC = ({ @@ -53,6 +56,7 @@ export const AttachmentsButton: React.FC = ({ onAdd, onRemove, variant = 'toolbar', + hideLabel = false, }) => { const [isOpen, setIsOpen] = useState(false); const [manualPath, setManualPath] = useState(''); @@ -210,6 +214,8 @@ export const AttachmentsButton: React.FC = ({ ref={buttonRef} type="button" onClick={() => setIsOpen(!isOpen)} + aria-label="Attachments" + title="Attachments" className="group relative flex items-center gap-1.5 px-2 py-1.5 rounded-md text-xs font-medium text-muted-foreground hover:text-foreground hover:bg-muted/50 transition-colors" > {/* Show stacked thumbnails if we have images */} @@ -254,9 +260,11 @@ export const AttachmentsButton: React.FC = ({ )} - - {images.length > 0 ? `${images.length}` : 'Images'} - + {(!hideLabel || images.length > 0) && ( + + {images.length > 0 ? `${images.length}` : 'Images'} + + )} {/* Popover */} diff --git a/packages/ui/components/StickyHeaderLane.tsx b/packages/ui/components/StickyHeaderLane.tsx index 90e7850..3c9216d 100644 --- a/packages/ui/components/StickyHeaderLane.tsx +++ b/packages/ui/components/StickyHeaderLane.tsx @@ -5,13 +5,20 @@ * At rest (top of doc): invisible, non-interactive. The original toolstrip * and badge cluster on the card remain the visible source of truth. * - * Scrolled, sm+ (640px): fades + slides in at top: 12px, sitting on the - * same horizontal lane as the already-sticky action buttons inside the - * Viewer card. Single horizontal header. + * Layout is driven by two ResizeObserver measurements — the sticky + * wrapper's actual width AND the Viewer action button cluster's actual + * width — so the bar fits exactly into the space between its left edge + * and the buttons, with no fixed pixel reserves. * - * Scrolled, mobile (<640px): pins at top: 52px on its OWN full-width row, - * directly below the action buttons row. Toolstrip switches to icon-only - * (no labels) so the diff badges have room. + * availableForBar = wrapperWidth - LEFT_OFFSET - actionsWidth - GAP + * + * Three states based on availableForBar: + * wide (>= WIDE_BAR_WIDTH): shared lane, toolstrip with active labels. + * tight (>= MIN_BAR_WIDTH): shared lane, toolstrip icon-only — gives + * the bar another ~160px of room before + * forcing a layout change. + * narrow (< MIN_BAR_WIDTH): stacked below the action buttons on its + * own full-width row, icon-only toolstrip. * * Composes + . * No state is duplicated — all props are passed through from App.tsx. @@ -20,9 +27,34 @@ import React, { useEffect, useRef, useState } from 'react'; import { AnnotationToolstrip } from './AnnotationToolstrip'; import { DocBadges } from './DocBadges'; +import { useScrollViewport } from '../hooks/useScrollViewport'; import type { EditorMode, InputMethod } from '../types'; import type { PlanDiffStats } from '../utils/planDiffEngine'; +// Snap a measured pixel width to a 16px grid. ResizeObserver fires every +// frame during a drag; without quantization the sticky bar would +// re-render on every pixel. Hoisted to module scope so the effects +// (which use [] deps) can't accidentally close over a stale instance. +// Floor (not round) so wrapper undershoots and actions overshoots — both +// errors push toward a more cautious layout, avoiding a one-bucket overlap +// flash right at the 300/460 thresholds during a slow drag. +const snap = (n: number) => Math.floor(n / 16) * 16; + +// Layout geometry — static tuning constants, hoisted alongside `snap`. +// LEFT_OFFSET: matches the bar's `md:left-5` (20px). +// GAP: minimum breathing room between the bar's right edge and the +// action button cluster's left edge when they share a lane. +// Two-stage shared-lane shrinkage, mirroring the right side: +// WIDE_BAR_WIDTH: full toolstrip (active labels Pinpoint/Markup ~300px) +// + badges (~140px) on a single line. +// MIN_BAR_WIDTH: icon-only toolstrip (~140px) + badges (~140px). +// Below MIN, even the icon-only bar can't fit beside the (likely also +// icon-only) action cluster — stack as the final fallback. +const LEFT_OFFSET = 20; +const GAP = 16; +const WIDE_BAR_WIDTH = 460; +const MIN_BAR_WIDTH = 300; + interface StickyHeaderLaneProps { // Toolstrip state inputMethod: InputMethod; @@ -41,6 +73,14 @@ interface StickyHeaderLaneProps { // Layout maxWidth?: number; + + // Re-query token for the [data-sticky-actions] ResizeObserver. When the + // Viewer remounts (e.g., toggling a linked doc), its `data-sticky-actions` + // node is replaced — but StickyHeaderLane itself does NOT remount, so + // its observer would otherwise stay attached to the now-detached old + // node and freeze `actionsWidth`. Pass a string that changes whenever + // Viewer remounts and the effect re-runs against the fresh DOM. + remountToken?: string; } export const StickyHeaderLane: React.FC = ({ @@ -56,92 +96,125 @@ export const StickyHeaderLane: React.FC = ({ onPlanDiffToggle, archiveInfo, maxWidth, + remountToken, }) => { const sentinelRef = useRef(null); + const wrapperRef = useRef(null); const [isStuck, setIsStuck] = useState(false); - const [isMobile, setIsMobile] = useState(false); + const [wrapperWidth, setWrapperWidth] = useState(0); + const [actionsWidth, setActionsWidth] = useState(0); + const scrollViewport = useScrollViewport(); + + // Space available for the bar in the shared lane = wrapper width, minus + // the bar's left offset, minus the action buttons' measured width, minus + // the breathing gap. + const availableForBar = wrapperWidth - LEFT_OFFSET - actionsWidth - GAP; + + // Narrow = not enough room in the shared lane for even the icon-only + // bar. Falls back to a stacked row below the action buttons. + // actionsWidth=0 before measurement is treated as "don't know yet" + // (not narrow), so we don't flash the wrong layout on first paint. + const measured = wrapperWidth > 0 && actionsWidth > 0; + const isNarrow = measured && availableForBar < MIN_BAR_WIDTH; + // Tight = shared lane still fits, but only if the toolstrip drops its + // active labels and goes icon-only. Lets us stay horizontally aligned + // for an extra ~160px of width before stacking. + const isToolstripIconOnly = + measured && !isNarrow && availableForBar < WIDE_BAR_WIDTH; - // Match the `sm` Tailwind breakpoint (640px). Below it the bar lives on - // its own row and switches the toolstrip to icon-only so the diff - // badges have room. useEffect(() => { - const mq = window.matchMedia('(max-width: 639px)'); - const handler = () => setIsMobile(mq.matches); - handler(); - mq.addEventListener('change', handler); - return () => mq.removeEventListener('change', handler); + if (!wrapperRef.current) return; + const ro = new ResizeObserver(([entry]) => { + const next = snap(entry.contentRect.width); + setWrapperWidth((prev) => (prev === next ? prev : next)); + }); + ro.observe(wrapperRef.current); + return () => ro.disconnect(); }, []); + // Measure the Viewer's action button cluster so the right reserve + // reflects its REAL width (which varies with viewport — short vs full + // labels — and with button count). No more guessing at ~310/360/400px. + // The action button div is tagged with `data-sticky-actions` in + // Viewer.tsx. It's a sibling in the DOM by the time effects fire. + // Re-runs when `remountToken` changes so we re-query after Viewer + // unmounts/remounts (e.g., linked-doc toggle) instead of leaving the + // observer attached to a detached node. + useEffect(() => { + // Reset to the unmeasured state so the bar falls back to the safe + // "no maxWidth cap" path for the one frame between Viewer remounting + // and the new observer firing its first callback. + setActionsWidth(0); + const el = document.querySelector('[data-sticky-actions]'); + if (!el) return; + const ro = new ResizeObserver(([entry]) => { + const next = snap(entry.contentRect.width); + setActionsWidth((prev) => (prev === next ? prev : next)); + }); + ro.observe(el); + return () => ro.disconnect(); + }, [remountToken]); + // IntersectionObserver-on-sentinel pattern (mirrors Viewer.tsx:257-267). - // Sentinel sits inline at the natural position the bar would occupy; when - // it leaves the viewport, the bar pins. The positive top rootMargin grows - // the effective viewport upward so the sentinel is considered "visible" - // for an extra ~72px of scroll — delaying the bar's appearance until the - // real toolstrip has actually scrolled past the top of
. Without - // this, the sentinel (which sits at the top of the column, above the - // toolstrip) fires the moment scrolling begins and the bar doubles up - // with the still-visible toolstrip. + // Sentinel sits inline at the top of the column. The 80px positive top + // rootMargin grows the effective viewport upward so the sentinel is + // considered "visible" for an extra ~80px of scroll — delaying the bar's + // appearance until the real toolstrip has actually scrolled past. Without + // this, the sentinel fires the moment scrolling begins and the ghost bar + // doubles up with the still-visible toolstrip. Root is the OverlayScrollArea + // viewport from context, NOT
(which doesn't actually scroll). useEffect(() => { - if (!sentinelRef.current) return; - const scrollContainer = document.querySelector('main'); + if (!sentinelRef.current || !scrollViewport) return; const observer = new IntersectionObserver( ([entry]) => setIsStuck(!entry.isIntersecting), - { root: scrollContainer, rootMargin: '72px 0px 0px 0px', threshold: 0 } + { root: scrollViewport, rootMargin: '80px 0px 0px 0px', threshold: 0 } ); observer.observe(sentinelRef.current); return () => observer.disconnect(); - }, []); + }, [scrollViewport]); return ( <> - {/* Sentinel — zero-size, rendered in normal flow at the top of
. - When it scrolls out of the viewport, the sticky bar fades in. */} + {/* Sentinel — zero-size, rendered in normal flow at the top of the + column. When it scrolls out of the OverlayScrollArea viewport, + the sticky bar fades in. */}