Files
openchamber/packages/ui/src/apps/MobileSessionSwitcher.tsx
T
Bohdan Triapitsyn 96c011a8ef feat(mobile): tablet layout pass and foldable-ready size class (#2569)
The tablet ran the phone layout with a half-finished iPad draft on top: two
custom sidebars, a leftover overflow menu, split Files/Changes header buttons,
and phone-width sheets stretched across a 13" screen. This brings it onto the
phone's navigation model and keeps only the differences a large screen earns.

- Sessions are a persistent resizable left sidebar; the overflow menu is gone
  and its destinations moved into that sidebar's footer (connected instance,
  settings, pending web update) and into the workspace drawer.
- The workspace (Changes / Files / Terminal / Notes / MCP) is the phone's
  drawer everywhere: a resizable right sidebar where the screen can host one
  (up to 900px) and the full-cover drawer otherwise, with its mounted panes —
  an open diff, an edited file, an attached terminal — surviving rotation.
- Header dropdowns are anchored popovers: the recents switcher mirrors the
  usage overlay on the left, and its trigger is sized to the title rather than
  to the free width.
- App-level pages (settings, instances, update, an opened plan) render as
  centered dialogs instead of covering the screen.
- Overlays center on the chat column through published insets, so the model
  and directory pickers no longer sit off-centre; the directory picker also
  stops overriding the shared width clamp.
- Wide chat layout applies to mobile surfaces, where a tablet chat column is
  finally wide enough for the setting to mean anything.

The layout gate is a live size class rather than a device check, so Android
tablets and foldables are covered by the same code:

- `enabled` when the shortest viewport side is at le
  sw600dp). The short side is what makes this a size question instead of a
  device question — a phone reports ~360-430 whichev
  unfolded book foldable ~600+, and folding shut drops back under it. iPads
  also answer on identity, since iPadOS hands out od
- `roomyForPanels` when landscape and at least 1000px wide, which is what it
  takes to host the sidebar, the panel and a readabl
  foldables miss it in BOTH orientations — their long side is barely wider
  than a tablet's short one — so they keep the portr

Every consumer re-decides instead of remembering wha
open sidebar closes if the device folds shut under it. iPad behaviour is
unchanged: its landscape widths all clear the panel
ones do not, exactly as the previous orientation check did.

Hardware keyboards are read natively. iOS reports them through GCKeyboard,
published to the web layer at document start and kep
disconnect and foregrounding; the layer stops inferring once that answers. A
single early publish was not enough — the connect no
already-attached keyboard fires before the page exists, and GameController can
populate late — so the state is re-published across
resume. With a keyboard attached the draft screen keeps its starter chips and
the composer never collapses; tablets skip the colla
Runtimes with no native answer fall back to inferring it from the keyboard
bridge, and only ever conclude "hardware" from silen

Also: sidebar rows no longer sit on a differently ti
footer is no longer clipped by an over-tall content box, the resize handles
moved above the panes' own overlays so they can actu
now-unreachable overflow menu, fullscreen terminal/MCP/notes surfaces and their
locale key are deleted.

Device behaviour is unverified — the tablet layout,
keyboard bridge and the foldable size class have not been exercised on
hardware, and the 600/1000 thresholds are derived fr
rather than measured on a foldable.
2026-08-02 16:25:16 +03:00

236 lines
9.8 KiB
TypeScript

import React from 'react';
import type { Session } from '@opencode-ai/sdk/v2';
import { Icon } from '@/components/icon/Icon';
import { formatSessionCompactDateLabel } from '@/components/session/sidebar/utils';
import { useSwitcherItems } from '@/components/session/sidebar/hooks/useSwitcherItems';
import { useTabletLayout } from '@/lib/device';
import { useI18n } from '@/lib/i18n';
import { cn } from '@/lib/utils';
import { refreshGlobalSessions, resolveGlobalSessionDirectory } from '@/stores/useGlobalSessionsStore';
import { useProjectsStore } from '@/stores/useProjectsStore';
import { useSessionUnseenCount } from '@/sync/notification-store';
import { useSessionUIStore } from '@/sync/session-ui-store';
import { useGlobalSessionStatus } from '@/sync/sync-context';
const RECENT_SESSIONS_LIMIT = 10;
/** Matches the metadata popover's width so both header dropdowns read as a pair. */
const TABLET_POPOVER_WIDTH = 380;
const getSessionTitle = (session: Session, fallback: string): string =>
session.title?.trim() || fallback;
/** One switcher row: live status (busy spinner / attention dot), title,
"project · branch", compact time. Mirrors the desktop SessionSwitcherDropdown
indicator conventions; no subsession chevrons on mobile by design. */
const SwitcherRow: React.FC<{
session: Session;
meta: string;
active: boolean;
onSelect: () => void;
}> = ({ session, meta, active, onSelect }) => {
const { t } = useI18n();
const status = useGlobalSessionStatus(session.id);
const unseenCount = useSessionUnseenCount(session.id);
const statusType = status?.type ?? 'idle';
const isStreaming = statusType === 'busy' || statusType === 'retry';
const showUnreadDot = !isStreaming && unseenCount > 0 && !active;
const timeLabel = formatSessionCompactDateLabel(session.time?.updated ?? session.time?.created ?? 0);
return (
<button
type="button"
className={cn(
'flex w-full items-center gap-3 rounded-xl px-2.5 py-2 text-left transition-colors active:bg-interactive-hover focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-inset focus-visible:ring-primary',
active && 'bg-[color-mix(in_srgb,var(--primary)_10%,transparent)]',
)}
onClick={onSelect}
style={{ touchAction: 'manipulation' }}
>
<span className="flex min-w-0 flex-1 flex-col">
<span className={cn('block truncate typography-ui-label', active ? 'text-primary' : 'text-foreground')}>
{getSessionTitle(session, t('sessions.sidebar.session.untitled'))}
</span>
{meta ? (
<span className="block truncate typography-micro text-muted-foreground">{meta}</span>
) : null}
</span>
{/* Activity sits on the right, before the time — no reserved left gutter. */}
{isStreaming ? (
<Icon name="loader-4" className="size-3.5 shrink-0 animate-spin text-primary" aria-hidden />
) : showUnreadDot ? (
<span className="size-1.5 shrink-0 rounded-full bg-[var(--status-info)]" aria-hidden />
) : null}
{timeLabel ? (
<span className="shrink-0 typography-micro text-muted-foreground tabular-nums">{timeLabel}</span>
) : null}
</button>
);
};
/** Recent-sessions popover under the mobile header, opened by tapping the
session title. Same visual family as the metadata/usage overlay. */
export const MobileSessionSwitcher: React.FC<{
open: boolean;
onClose: () => void;
anchorRef: React.RefObject<HTMLElement | null>;
}> = ({ open, onClose, anchorRef }) => {
const { t } = useI18n();
const panelRef = React.useRef<HTMLDivElement>(null);
const [shouldRender, setShouldRender] = React.useState(open);
const [isExiting, setIsExiting] = React.useState(false);
// Tablet: a phone-width sheet stretched across the whole chat column looks
// broken — anchor a popover under the title instead. Mirror image of the
// metadata/usage popover, which anchors to the ring on the right.
const { enabled: isTabletLayout } = useTabletLayout();
const wrapperRef = React.useRef<HTMLDivElement>(null);
const [anchorLeft, setAnchorLeft] = React.useState<number | null>(null);
// The shell has transformed ancestors, so the fixed wrapper's containing
// block is the chat column, NOT the viewport — anchor in the wrapper's own
// coordinate space (see SessionMetadataOverlay for the same reasoning).
React.useLayoutEffect(() => {
if (!open || !isTabletLayout || !shouldRender) return;
const compute = () => {
const anchorRect = anchorRef.current?.getBoundingClientRect();
const wrapperRect = wrapperRef.current?.getBoundingClientRect();
if (!anchorRect || !wrapperRect) {
setAnchorLeft(null);
return;
}
const relativeLeft = anchorRect.left - wrapperRect.left;
setAnchorLeft(Math.min(
Math.max(relativeLeft, 8),
Math.max(8, wrapperRect.width - TABLET_POPOVER_WIDTH - 8),
));
};
compute();
// Re-anchor if the chat column shifts while the popover is open (sidebar
// toggle/resize, orientation change) — the header buttons move with it.
const wrapper = wrapperRef.current;
if (typeof ResizeObserver === 'undefined' || !wrapper) return;
const observer = new ResizeObserver(compute);
observer.observe(wrapper);
return () => observer.disconnect();
}, [anchorRef, isTabletLayout, open, shouldRender]);
const isPopover = isTabletLayout && anchorLeft !== null;
const currentSessionId = useSessionUIStore((state) => state.currentSessionId);
const setCurrentSession = useSessionUIStore((state) => state.setCurrentSession);
const setActiveProjectIdOnly = useProjectsStore((state) => state.setActiveProjectIdOnly);
const items = useSwitcherItems(open || shouldRender, { maxParents: RECENT_SESSIONS_LIMIT });
React.useEffect(() => {
if (open) {
// Fresh authoritative snapshot on open — updated stamps re-sort recents
// (see raiseSessionOrderingBaselines) while the cached list shows first.
void refreshGlobalSessions();
setShouldRender(true);
setIsExiting(false);
return;
}
if (!shouldRender) return;
setIsExiting(true);
const timeoutId = window.setTimeout(() => {
setShouldRender(false);
setIsExiting(false);
}, 140);
return () => window.clearTimeout(timeoutId);
}, [open, shouldRender]);
React.useEffect(() => {
if (!open) return;
const handleKey = (event: KeyboardEvent) => {
if (event.key === 'Escape') onClose();
};
document.addEventListener('keydown', handleKey);
return () => document.removeEventListener('keydown', handleKey);
}, [onClose, open]);
React.useEffect(() => {
if (!open) return;
const closeIfOutside = (event: PointerEvent) => {
const target = event.target;
if (!(target instanceof Node)) {
onClose();
return;
}
if (panelRef.current?.contains(target) || anchorRef.current?.contains(target)) return;
onClose();
};
document.addEventListener('pointerdown', closeIfOutside, true);
return () => document.removeEventListener('pointerdown', closeIfOutside, true);
}, [anchorRef, onClose, open]);
const handleSelect = React.useCallback((session: Session) => {
void setCurrentSession(session.id, resolveGlobalSessionDirectory(session));
onClose();
}, [onClose, setCurrentSession]);
if (!shouldRender) return null;
return (
<div ref={wrapperRef} className="fixed inset-x-0 bottom-0 top-[calc(var(--oc-safe-area-top,0px)+var(--oc-header-height,56px))] z-20 pointer-events-none">
<div
ref={panelRef}
role="dialog"
aria-label={t('sessions.switcher.openAria')}
className={cn(
'flex flex-col overflow-hidden rounded-[20px] border border-border/70 bg-[var(--surface-elevated)] p-2 shadow-[0_12px_32px_rgb(0_0_0_/_0.2)] will-change-transform',
isPopover ? 'absolute origin-top-left' : 'mx-3 mt-2',
isExiting ? 'pointer-events-none' : 'pointer-events-auto',
)}
style={{
animation: `${isExiting ? 'session-switcher-out' : 'session-switcher-in'} ${isExiting ? 140 : 170}ms cubic-bezier(0.32, 0.72, 0, 1) forwards`,
maxHeight: 'min(72dvh, calc(100dvh - var(--oc-safe-area-top, 0px) - var(--oc-header-height, 56px) - 1rem))',
...(isPopover
? {
top: 8,
left: anchorLeft ?? 8,
width: `min(${TABLET_POPOVER_WIDTH}px, calc(100% - 16px))`,
}
: null),
}}
>
<div className="oc-hide-scrollbar min-h-0 flex-1 space-y-0.5 overflow-y-auto overscroll-contain">
{items.length === 0 ? (
<p className="px-3 py-6 text-center typography-small text-muted-foreground">
{t('sessions.switcher.empty')}
</p>
) : (
items.map((item) => {
const session = item.node.session;
const meta = [item.secondaryMeta?.projectLabel, item.secondaryMeta?.branchLabel]
.filter(Boolean)
.join(' · ');
return (
<SwitcherRow
key={session.id}
session={session}
meta={meta}
active={session.id === currentSessionId}
onSelect={() => {
if (item.projectId) setActiveProjectIdOnly(item.projectId);
handleSelect(session);
}}
/>
);
})
)}
</div>
</div>
<style>{`
@keyframes session-switcher-in {
from { opacity: 0; transform: translateY(-8px) scale(0.985); }
to { opacity: 1; transform: translateY(0) scale(1); }
}
@keyframes session-switcher-out {
from { opacity: 1; transform: translateY(0) scale(1); }
to { opacity: 0; transform: translateY(-6px) scale(0.985); }
}
`}</style>
</div>
);
};