Files
openchamber/packages/ui/src/components/session/SessionSwitcherDropdown.tsx
T
0d15cdc838 fix(ui): reveal overlay scrollbar on hover or active scroll (re-port to bindScrollbar) (#3219)
* fix(ui): reveal overlay scrollbar on hover or active scroll (re-port to bindScrollbar)

Re-ports #2825's container-hover reveal onto the rewritten bindScrollbar
architecture that landed on main after the original PR branch was created.

- pointerenter/pointerleave on the scroll container reveal the thumb
  immediately (deliberate intent on every mouse-pointer runtime; inert
  on touch via an event.pointerType === 'mouse' guard, since the Pointer
  Events spec fires pointerenter on touch taps as well)
- hide-timer re-checks pointerOverContainer at fire time, so the thumb does
  not vanish when the pointer moves from container onto the sibling thumb
- suppressVisibility (chat auto-follow) still suppresses hover reveal
- on hover, schedule a re-measure so the horizontal thumb reflects the
  current geometry: if the container has horizontal overflow the thumb is
  revealed, otherwise it stays hidden. This matches the original PR's
  updateMetrics() approach and avoids the regression where onScroll (which
  does not measure) would leave a legitimately overflowing horizontal
  thumb hidden while hovering
- index.css: drop the Settings-specific overlay-scrollbar display:none
  (thumb is never permanently visible anywhere now)
- regression tests: horizontal thumb reveals on hover when overflow exists,
  stays hidden when it does not; touch pointerenter is inert; hand-off
  race (container pointerleave followed by thumb pointerover) keeps the
  thumb visible; pointerleave hides the thumb

* ci(ui): add overlay scrollbar interaction recording workflow

Records the hover-reveal/hide interaction of the overlay scrollbar
(PR #3219 re-port to bindScrollbar) as a webm + GIF via Playwright
recordVideo, converted with ffmpeg palettegen/paletteuse.

- scripts/record-overlay-scrollbar.mjs: drives hover in/out, forces
  overflow on the first .overlay-scrollbar-target so the demo works on
  a clean data dir, exports overlay-scrollbar-hover.{webm,gif}.
- .github/workflows/interaction-recording.yml: mirrors the validated
  screenshots.yml pattern (auth disabled server, Playwright chromium,
  15-min timeout), adds ffmpeg install step.

* docs(ui): add overlay scrollbar interaction recording

Animated GIF captured by the interaction-recording workflow (Playwright
recordVideo + ffmpeg) showing the hover-reveal/hide behavior of the
re-ported overlay scrollbar (bindScrollbar): thumb fades in on pointer
enter, hides again after the hide delay once the pointer leaves.

* feat(ui): adopt ScrollableOverlay in remaining native-scroll panels

Extends the overlay scrollbar (hover-reveal, hide-on-leave) to panels
that still used native overflow-y-auto scrolling:

- Sidebar (left nav): outer flex-1 scroll region
- ContextSidebarTab: full-height tab content
- SessionSwitcherDropdown: session list dropdown (preserves contentRef
  for scrollIntoView / switcher item queries)
- HelpDialog: help content region

All four merge sizing into outerClassName (flex-1 min-h-0 / h-full /
max-h-[60vh]) and keep visual classes on className, with disableHorizontal
where the original hid horizontal overflow. Type-check passes; unit test
failures in OverlayScrollbar.test.tsx and event-pipeline.test.js are
pre-existing (reproduce on pristine HEAD).

* test(ui): flush hide timer before asserting thumb hidden

The hide path always schedules a setTimeout (hideDelayMs: 0 still
schedules a 0ms timer). happy-dom runs real timers, so the test must
let the macrotask fire before asserting dataset.visible — flushing rAF
frames alone is not enough. Fixes the one failing test in
OverlayScrollbar.test.tsx (12/13 -> 13/13).

* fix(ci): make scrollbar interaction recording hover retry across targets

The record script picked the first .overlay-scrollbar-target and moved the
pointer to its center; layout/hydration order varies between CI runs, so
the hover sometimes landed on a target whose thumb cannot reveal (empty
container), failing the run. Now it iterates targets in DOM order until
the vertical thumb actually appears (or fails after exhausting all).

* fix(ci): record workflow + i18n + overlay-chrome hide

- .github/workflows/interaction-recording.yml: drop 'ref: rework' so the
  workflow checks out the PR head SHA on upstream (where 'rework' branch
  does not exist). Replace with persist-credentials: true.
- packages/ui/src/lib/i18n/messages/tr.ts: add 4 missing gitView.empty
  keys (parity fix, only tr.ts was behind en.ts). Translations are
  approximate; the parity test only checks key existence.
- scripts/record-overlay-scrollbar.mjs: on a fresh data dir the web
  build can render onboarding modals (ChooserScreen, AboutDialog,
  ConfigUpdateOverlay) that float above the MainLayout with a blurred
  backdrop. The thumb's isThumbVisible() returns true (DOM-mounted)
  but the captured frame is dominated by the modal, so the user sees
  'dialog in front, blurred background' instead of the scrollbar
  reveal. hideOverlayChrome() injects CSS to hide every plausible
  overlay root and best-effort closes known UI store dialogs.

* fix(ci): drop fork-specific ref in record workflow + add tr locale gitView.empty keys

- .github/workflows/interaction-recording.yml: drop 'ref: rework' so the
  workflow checks out the PR head SHA on upstream (where 'rework' branch
  does not exist). Replace with persist-credentials: true.
- packages/ui/src/lib/i18n/messages/tr.ts: add 4 missing gitView.empty
  keys (parity fix, only tr.ts was behind en.ts). Translations are
  approximate; the parity test only checks key existence.
- scripts/record-overlay-scrollbar.mjs: hide onboarding chrome (modals,
  backdrops, dialogs) that float above the MainLayout when recording
  against a fresh data dir, so the captured GIF shows the actual
  scrollbar reveal instead of a blurred-overlay dialog screen.
- docs/interaction-recordings/overlay-scrollbar-hover.gif: regenerate
  (489 KB) with overlay chrome hidden (same artifact as CI run
  33507731092 which passed).

* ci: noop push to retrigger 'pr checks' on a fresh runner

The 'pr checks' check on this PR's prior head (0509212c3) failed with
'releaseJob is not a function' in packages/web/server/lib/walkthrough/
routes.test.js. This test lives in upstream main and is not touched by
this PR's diff. The same flake is currently hitting PR #3265 and
feat/scheduled-preflight-gate.

Confirmed the two latest upstream main commits (bec7a82568 sidebar
sort, 40e4b6f857 request-security) do not touch walkthrough/, so the
failure is a 20ms timing flake in the test's executor Promise, not a
code regression. This empty commit triggers a new CI run on a
different runner with a different scheduling window.

* feat(settings): adopt ScrollableOverlay in settings shell and dialogs

Several settings surfaces still rendered their scroll containers with
native browser scrollbars (overflow-y-auto / overflow-y-scroll), which
read inconsistently against the overlay scrollbar used everywhere else
in the app once content exceeded the viewport.

Wrap the relevant containers in <ScrollableOverlay>:

  - SettingsView: nav sidebar (mobile), mobile fallback, mobile page
    sidebar, mobile page content, and desktop split view
  - DirectoryExplorerDialog: results list
  - GitHubIntegrationDialog: issues / PRs list
  - GitHubIssuePickerDialog, GitHubPrPickerDialog: lists
  - NewWorktreeDialog: form body

The settings sub-pages (OpenChamberPage, VoiceSettings, PasskeySettings,
etc.) do not carry their own overflow — they inherit the scroll host
from SettingsView, so the shell change is sufficient for them.

type-check, lint, and ui tests (368/369, the one failure is a pre-existing
event-pipeline flake unrelated to this change) all pass.

* ci(record): re-run overlay scrollbar recording on a fresh runner window

* ci(record): give overlay thumb 1500ms to reveal on hover

The 'hover did not reveal the thumb on any target' check has been
flaky across runs since the workflow landed in this branch (about
half the runs fail with the same error). 700ms was tight on cold
GitHub-hosted runners; 1500ms absorbs the cold-start variance
without changing what the GIF captures (the thumb's hide animation
runs after pointerleave, unaffected by the longer pre-leave wait).

* ci(record): debug thumb visibility timing on hover

* ci(record): drop debug logging, keep 1500ms hover wait

Debug logging was used to identify that 200ms is enough on a
healthy runner, but 700ms was not. The flake was the OpenChamber
server being slow to initialize the OpenCode side on cold
runners — the thumb itself renders quickly once the app is up.
Keeping 1500ms absorbs that cold-start variance without slowing
successful runs by more than the GIF's existing post-hover
animation wait (1000ms hideDelayMs).

---------

Co-authored-by: sergiofspedro <sergiofspedro@users.noreply.github.com>
Co-authored-by: openchamber-ops <ops@openchamber.dev>
Co-authored-by: Bohdan Triapitsyn <artmore@protonmail.com>
2026-09-08 00:11:47 +03:00

353 lines
13 KiB
TypeScript

import React from 'react';
import { Menu as BaseMenu } from '@base-ui/react/menu';
import type { Session } from '@opencode-ai/sdk/v2';
import {
DropdownMenu,
DropdownMenuContent,
DropdownMenuTrigger,
} from '@/components/ui/dropdown-menu';
import { Icon } from '@/components/icon/Icon';
import { useSessionUIStore } from '@/sync/session-ui-store';
import { useGlobalSessionStatus } from '@/sync/sync-context';
import { useSessionUnseenCount } from '@/sync/notification-store';
import {
findSwitcherItemAncestorIds,
useSwitcherItems,
type SwitcherItem,
} from '@/components/session/sidebar/shell/useSwitcherItems';
import { useUIStore } from '@/stores/useUIStore';
import { resolveGlobalSessionDirectory } from '@/stores/useGlobalSessionsStore';
import { formatSessionCompactDateLabel } from './sidebar/utils';
import type { SessionNode } from './sidebar/types';
import { useI18n } from '@/lib/i18n';
import { cn } from '@/lib/utils';
import { ScrollableOverlay } from '@/components/ui/ScrollableOverlay';
type SecondaryMeta = SwitcherItem['secondaryMeta'];
type SwitcherVariant = 'default' | 'compact';
const NEW_SESSION_SWITCHER_TARGET = 'new-session';
type SessionSwitcherDropdownProps = {
children: React.ReactNode;
variant?: SwitcherVariant;
scopeProjectId?: string | null;
align?: 'start' | 'center' | 'end';
};
export function SessionSwitcherDropdown({
children,
variant = 'default',
scopeProjectId = null,
align = 'start',
}: SessionSwitcherDropdownProps): React.ReactElement {
const isOpen = useUIStore((state) => state.isSessionDropdownOpen);
const setOpen = useUIStore((state) => state.setSessionDropdownOpen);
return (
<DropdownMenu open={isOpen} onOpenChange={setOpen} modal={false} disableGlobalShortcuts>
<DropdownMenuTrigger asChild>{children}</DropdownMenuTrigger>
<DropdownMenuContent
align={align}
sideOffset={6}
className={cn(
'overflow-hidden p-1 max-w-[calc(100vw-32px)]',
variant === 'compact' ? 'w-[280px]' : 'w-[360px]',
)}
>
{isOpen ? (
<SwitcherContent
onSelect={() => setOpen(false)}
variant={variant}
scopeProjectId={scopeProjectId}
/>
) : null}
</DropdownMenuContent>
</DropdownMenu>
);
}
type SwitcherContentProps = {
onSelect: () => void;
variant: SwitcherVariant;
scopeProjectId: string | null;
};
function SwitcherContent({ onSelect, variant, scopeProjectId }: SwitcherContentProps): React.ReactElement {
const currentSessionId = useSessionUIStore((state) => state.currentSessionId);
const isNewSessionDraftOpen = useSessionUIStore((state) => state.newSessionDraft.open === true);
const items = useSwitcherItems(true, { scopeProjectId, currentSessionId });
const openNewSessionDraft = useSessionUIStore((state) => state.openNewSessionDraft);
const { t } = useI18n();
const handleNewSession = React.useCallback(() => {
onSelect();
openNewSessionDraft();
}, [onSelect, openNewSessionDraft]);
const [expandedParents, setExpandedParents] = React.useState<Set<string>>(new Set());
const contentRef = React.useRef<HTMLElement>(null);
const initialFocusCompleteRef = React.useRef(false);
const initialTarget = isNewSessionDraftOpen ? NEW_SESSION_SWITCHER_TARGET : currentSessionId;
const toggleParent = React.useCallback((sessionId: string) => {
setExpandedParents((prev) => {
const next = new Set(prev);
if (next.has(sessionId)) {
next.delete(sessionId);
} else {
next.add(sessionId);
}
return next;
});
}, []);
React.useLayoutEffect(() => {
if (initialFocusCompleteRef.current || !initialTarget) return;
const ancestorIds = initialTarget === NEW_SESSION_SWITCHER_TARGET
? []
: findSwitcherItemAncestorIds(items, initialTarget);
if (!ancestorIds) return;
if (ancestorIds.some((id) => !expandedParents.has(id))) {
setExpandedParents((previous) => new Set([...previous, ...ancestorIds]));
return;
}
const animationFrame = requestAnimationFrame(() => {
const item = Array.from(
contentRef.current?.querySelectorAll<HTMLElement>('[data-switcher-item-id]') ?? [],
).find((element) => element.dataset.switcherItemId === initialTarget);
if (!item) return;
item.focus();
item.scrollIntoView({ block: 'nearest' });
initialFocusCompleteRef.current = true;
});
return () => cancelAnimationFrame(animationFrame);
}, [expandedParents, initialTarget, items]);
return (
<ScrollableOverlay
ref={contentRef}
outerClassName="max-h-[60vh]"
disableHorizontal
>
<div className="space-y-0.5">
<BaseMenu.Item
data-switcher-item-id={NEW_SESSION_SWITCHER_TARGET}
onClick={handleNewSession}
className={cn(
'group relative flex w-full cursor-pointer items-center gap-2 rounded-lg px-2 py-1.5 outline-hidden select-none',
'data-[highlighted]:bg-interactive-hover hover:bg-interactive-hover',
)}
>
<Icon name="chat-new" className="h-4 w-4 flex-shrink-0 text-muted-foreground" />
<span className="truncate text-[14px] font-normal leading-tight text-foreground">
{t('sessions.sidebar.header.actions.newSession')}
</span>
</BaseMenu.Item>
{items.length === 0 ? (
<div className="px-3 py-4 text-center typography-meta text-muted-foreground">
{t('sessions.switcher.empty')}
</div>
) : (
items.map((item) => (
<SwitcherNode
key={item.node.session.id}
item={item}
depth={0}
variant={variant}
expandedParents={expandedParents}
toggleParent={toggleParent}
closeDropdown={onSelect}
/>
))
)}
</div>
</ScrollableOverlay>
);
}
type SwitcherNodeProps = {
item: { node: SessionNode; projectId: string | null; groupDirectory: string | null; secondaryMeta: SecondaryMeta };
depth: number;
variant: SwitcherVariant;
expandedParents: Set<string>;
toggleParent: (sessionId: string) => void;
closeDropdown: () => void;
};
function SwitcherNode({ item, depth, variant, expandedParents, toggleParent, closeDropdown }: SwitcherNodeProps): React.ReactElement {
const { node, secondaryMeta } = item;
const session = node.session;
const hasChildren = node.children.length > 0;
const isExpanded = expandedParents.has(session.id);
return (
<>
<SwitcherRow
session={session}
depth={depth}
variant={variant}
secondaryMeta={secondaryMeta}
hasChildren={hasChildren}
isExpanded={isExpanded}
onToggleExpand={hasChildren ? () => toggleParent(session.id) : undefined}
closeDropdown={closeDropdown}
/>
{hasChildren && isExpanded
? node.children.map((childNode) => (
<SwitcherNode
key={childNode.session.id}
item={{ node: childNode, projectId: item.projectId, groupDirectory: item.groupDirectory, secondaryMeta }}
depth={depth + 1}
variant={variant}
expandedParents={expandedParents}
toggleParent={toggleParent}
closeDropdown={closeDropdown}
/>
))
: null}
</>
);
}
type SwitcherRowProps = {
session: Session;
depth: number;
variant: SwitcherVariant;
secondaryMeta: SecondaryMeta;
hasChildren: boolean;
isExpanded: boolean;
onToggleExpand?: () => void;
closeDropdown: () => void;
};
function SwitcherRow({ session, depth, variant, secondaryMeta, hasChildren, isExpanded, onToggleExpand, closeDropdown }: SwitcherRowProps): React.ReactElement {
const { t } = useI18n();
const currentSessionId = useSessionUIStore((state) => state.currentSessionId);
const setCurrentSession = useSessionUIStore((state) => state.setCurrentSession);
const notifyOnSubtasks = useUIStore((state) => state.notifyOnSubtasks);
const sessionStatus = useGlobalSessionStatus(session.id);
const unseenCount = useSessionUnseenCount(session.id);
const isActive = currentSessionId === session.id;
const sessionTitle = session.title?.trim() || t('sessions.sidebar.session.untitled');
const isSubtask = Boolean((session as Session & { parentID?: string | null }).parentID);
const needsAttention = unseenCount > 0 && (!isSubtask || notifyOnSubtasks);
const statusType = sessionStatus?.type ?? 'idle';
const isStreaming = statusType === 'busy' || statusType === 'retry';
const showUnreadDot = !isStreaming && needsAttention && !isActive;
const timestamp = session.time?.updated || session.time?.created || Date.now();
const timeLabel = formatSessionCompactDateLabel(timestamp);
const projectLabel = secondaryMeta?.projectLabel?.trim() || null;
const rawBranchLabel = secondaryMeta?.branchLabel?.trim() || null;
const branchLabel = rawBranchLabel && rawBranchLabel !== 'HEAD' ? rawBranchLabel : null;
const handleSelect = React.useCallback(() => {
if (isActive) {
closeDropdown();
return;
}
const directory = resolveGlobalSessionDirectory(session);
setCurrentSession(session.id, directory ?? null);
closeDropdown();
}, [closeDropdown, isActive, session, setCurrentSession]);
return (
<BaseMenu.Item
onClick={(event) => {
if ((event.target as HTMLElement | null)?.closest('[data-switcher-expand]')) {
event.preventDefault();
return;
}
handleSelect();
}}
data-slot="session-switcher-item"
data-switcher-item-id={session.id}
className={cn(
'group relative flex w-full cursor-pointer items-start gap-2 rounded-lg px-2 py-1.5 outline-hidden select-none',
'data-[highlighted]:bg-interactive-hover hover:bg-interactive-hover',
)}
style={{ paddingLeft: 8 + depth * 12 }}
>
<div className="flex min-w-0 flex-1 flex-col gap-0.5">
<div className="flex min-w-0 items-center gap-1.5">
{variant === 'compact' && hasChildren ? (
<span
role="button"
tabIndex={-1}
data-switcher-expand
onClick={(event) => {
event.preventDefault();
event.stopPropagation();
onToggleExpand?.();
}}
className="inline-flex h-3.5 w-3.5 flex-shrink-0 items-center justify-center rounded text-muted-foreground/70 hover:text-foreground"
aria-label={isExpanded ? t('sessions.sidebar.session.subsessions.collapse') : t('sessions.sidebar.session.subsessions.expand')}
>
{isExpanded ? <Icon name="arrow-down-s" className="h-3.5 w-3.5" /> : <Icon name="arrow-right-s" className="h-3.5 w-3.5" />}
</span>
) : null}
<span className={cn('truncate text-[14px] font-normal leading-tight', isActive ? 'text-primary' : 'text-foreground')}>
{sessionTitle}
</span>
</div>
{variant === 'default' ? (
<div
className="flex min-w-0 items-center gap-1.5 truncate text-muted-foreground/70 leading-tight"
style={{ fontSize: 'calc(var(--text-ui-label) * 0.85)' }}
>
{hasChildren ? (
<span
role="button"
tabIndex={-1}
data-switcher-expand
onClick={(event) => {
event.preventDefault();
event.stopPropagation();
onToggleExpand?.();
}}
className="inline-flex h-3 w-3 flex-shrink-0 items-center justify-center rounded text-muted-foreground/70 hover:text-foreground"
aria-label={isExpanded ? t('sessions.sidebar.session.subsessions.collapse') : t('sessions.sidebar.session.subsessions.expand')}
>
{isExpanded ? <Icon name="arrow-down-s" className="h-3 w-3" /> : <Icon name="arrow-right-s" className="h-3 w-3" />}
</span>
) : null}
<span className="flex-shrink-0">{timeLabel}</span>
{projectLabel ? <span className="truncate">{projectLabel}</span> : null}
{branchLabel ? (
<span className="inline-flex min-w-0 items-center gap-0.5">
<Icon name="git-branch" className="h-3 w-3 flex-shrink-0 text-muted-foreground/70" />
<span className="truncate">{branchLabel}</span>
</span>
) : null}
</div>
) : null}
</div>
{isStreaming || showUnreadDot ? (
<span className="flex h-3 w-3 flex-shrink-0 items-center justify-center self-center">
{isStreaming ? (
<span
className="h-1.5 w-1.5 rounded-full bg-primary animate-busy-pulse"
aria-label={t('sessions.sidebar.session.status.active')}
title={t('sessions.sidebar.session.status.active')}
/>
) : (
<span
className="h-1.5 w-1.5 rounded-full bg-[var(--status-info)]"
aria-label={t('sessions.sidebar.session.status.unread')}
title={t('sessions.sidebar.session.status.unread')}
/>
)}
</span>
) : null}
</BaseMenu.Item>
);
}