Initial public release

This commit is contained in:
Bohdan Triapitsyn
2025-12-07 19:32:53 +02:00
commit 4b2edf7318
319 changed files with 81600 additions and 0 deletions
@@ -0,0 +1,478 @@
import React, { useEffect } from 'react';
import {
Tooltip,
TooltipContent,
TooltipTrigger,
} from '@/components/ui/tooltip';
import { Button } from '@/components/ui/button';
import { RiArrowDownSLine, RiArrowUpSLine, RiChat1Line, RiCodeLine, RiGitBranchLine, RiLayoutLeftLine, RiTerminalBoxLine, type RemixiconComponentType } from '@remixicon/react';
import { useUIStore, type MainTab } from '@/stores/useUIStore';
import { useConfigStore } from '@/stores/useConfigStore';
import { useSessionStore } from '@/stores/useSessionStore';
import { ContextUsageDisplay } from '@/components/ui/ContextUsageDisplay';
import { useDeviceInfo } from '@/lib/device';
import { cn } from '@/lib/utils';
import { useDiffFileCount } from '@/components/views/DiffView';
interface TabConfig {
id: MainTab;
label: string;
icon: RemixiconComponentType;
badge?: number;
}
export const FixedSessionsButton: React.FC = () => {
const setSessionSwitcherOpen = useUIStore((state) => state.setSessionSwitcherOpen);
const toggleSidebar = useUIStore((state) => state.toggleSidebar);
const { isMobile } = useDeviceInfo();
const [isDesktopApp, setIsDesktopApp] = React.useState<boolean>(() => {
if (typeof window === 'undefined') {
return false;
}
return typeof (window as typeof window & { opencodeDesktop?: unknown }).opencodeDesktop !== 'undefined';
});
const isMacPlatform = React.useMemo(() => {
if (typeof navigator === 'undefined') {
return false;
}
return /Macintosh|Mac OS X/.test(navigator.userAgent || '');
}, []);
React.useEffect(() => {
if (typeof window === 'undefined') {
return;
}
const detected = typeof (window as typeof window & { opencodeDesktop?: unknown }).opencodeDesktop !== 'undefined';
setIsDesktopApp(detected);
}, []);
const handleOpenSessionSwitcher = React.useCallback(() => {
if (isMobile) {
setSessionSwitcherOpen(true);
} else {
toggleSidebar();
}
}, [isMobile, setSessionSwitcherOpen, toggleSidebar]);
const headerIconButtonClass = 'app-region-no-drag inline-flex h-9 w-9 items-center justify-center gap-2 p-2 typography-ui-label font-medium text-muted-foreground focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-primary disabled:pointer-events-none disabled:opacity-50 hover:text-foreground';
if (isMobile || !isDesktopApp || !isMacPlatform) {
return null;
}
return (
<div className="fixed top-[0.375rem] left-[5.25rem] z-[9999]" style={{ pointerEvents: 'auto' }}>
<button
type="button"
onClick={handleOpenSessionSwitcher}
aria-label="Open sessions"
className={headerIconButtonClass}
>
<RiLayoutLeftLine className="h-5 w-5" />
</button>
</div>
);
};
export const Header: React.FC = () => {
const setSessionSwitcherOpen = useUIStore((state) => state.setSessionSwitcherOpen);
const toggleSidebar = useUIStore((state) => state.toggleSidebar);
const isSidebarOpen = useUIStore((state) => state.isSidebarOpen);
const sidebarWidth = useUIStore((state) => state.sidebarWidth);
const activeMainTab = useUIStore((state) => state.activeMainTab);
const setActiveMainTab = useUIStore((state) => state.setActiveMainTab);
const { getCurrentModel } = useConfigStore();
const getContextUsage = useSessionStore((state) => state.getContextUsage);
const { isMobile } = useDeviceInfo();
const diffFileCount = useDiffFileCount();
const headerRef = React.useRef<HTMLElement | null>(null);
const [isDesktopApp, setIsDesktopApp] = React.useState<boolean>(() => {
if (typeof window === 'undefined') {
return false;
}
return typeof (window as typeof window & { opencodeDesktop?: unknown }).opencodeDesktop !== 'undefined';
});
const isMacPlatform = React.useMemo(() => {
if (typeof navigator === 'undefined') {
return false;
}
return /Macintosh|Mac OS X/.test(navigator.userAgent || '');
}, []);
useEffect(() => {
if (typeof window === 'undefined') {
return;
}
const detected = typeof (window as typeof window & { opencodeDesktop?: unknown }).opencodeDesktop !== 'undefined';
setIsDesktopApp(detected);
}, []);
const currentModel = getCurrentModel();
const limit = currentModel && typeof currentModel.limit === 'object' && currentModel.limit !== null
? (currentModel.limit as Record<string, unknown>)
: null;
const contextLimit = (limit && typeof limit.context === 'number' ? limit.context : 0);
const outputLimit = (limit && typeof limit.output === 'number' ? limit.output : 0);
const contextUsage = getContextUsage(contextLimit, outputLimit);
const [isMobileDetailsOpen, setIsMobileDetailsOpen] = React.useState(false);
const isSessionSwitcherOpen = useUIStore((state) => state.isSessionSwitcherOpen);
const handleOpenSessionSwitcher = React.useCallback(() => {
if (isMobile) {
setSessionSwitcherOpen(!isSessionSwitcherOpen);
return;
}
toggleSidebar();
}, [isMobile, isSessionSwitcherOpen, setSessionSwitcherOpen, toggleSidebar]);
const headerIconButtonClass = 'app-region-no-drag inline-flex h-9 w-9 items-center justify-center gap-2 p-2 typography-ui-label font-medium text-muted-foreground focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-primary disabled:pointer-events-none disabled:opacity-50 hover:text-foreground';
const desktopPaddingClass = React.useMemo(() => {
if (isDesktopApp && isMacPlatform) {
return isSidebarOpen ? 'pl-0' : 'pl-[8.0rem]';
}
return 'pl-3';
}, [isDesktopApp, isMacPlatform, isSidebarOpen]);
const updateHeaderHeight = React.useCallback(() => {
if (typeof document === 'undefined') {
return;
}
const height = headerRef.current?.getBoundingClientRect().height;
if (height) {
document.documentElement.style.setProperty('--oc-header-height', `${height}px`);
}
}, []);
useEffect(() => {
if (typeof window === 'undefined') {
return;
}
updateHeaderHeight();
const node = headerRef.current;
if (!node || typeof ResizeObserver === 'undefined') {
return () => {};
}
const observer = new ResizeObserver(() => {
updateHeaderHeight();
});
observer.observe(node);
window.addEventListener('resize', updateHeaderHeight);
window.addEventListener('orientationchange', updateHeaderHeight);
return () => {
observer.disconnect();
window.removeEventListener('resize', updateHeaderHeight);
window.removeEventListener('orientationchange', updateHeaderHeight);
};
}, [updateHeaderHeight]);
useEffect(() => {
updateHeaderHeight();
}, [updateHeaderHeight, isMobile, isMobileDetailsOpen]);
const formatTokenValue = React.useCallback((tokens: number) => {
if (tokens >= 1_000_000) {
return `${(tokens / 1_000_000).toFixed(1)}M`;
}
if (tokens >= 1_000) {
return `${(tokens / 1_000).toFixed(1)}K`;
}
return tokens.toFixed(1).replace(/\.0$/, '');
}, []);
const handleDragStart = React.useCallback(async (e: React.MouseEvent) => {
if ((e.target as HTMLElement).closest('button, a, input, select, textarea')) {
return;
}
if (e.button !== 0) {
return;
}
if (isDesktopApp) {
try {
const { getCurrentWindow } = await import('@tauri-apps/api/window');
const window = getCurrentWindow();
await window.startDragging();
} catch (error) {
console.error('Failed to start window dragging:', error);
}
}
}, [isDesktopApp]);
const handleActiveTabDragStart = React.useCallback(async (e: React.MouseEvent) => {
if (e.button !== 0) {
return;
}
if (isDesktopApp) {
try {
const { getCurrentWindow } = await import('@tauri-apps/api/window');
const window = getCurrentWindow();
await window.startDragging();
} catch (error) {
console.error('Failed to start window dragging:', error);
}
}
}, [isDesktopApp]);
const tabs: TabConfig[] = React.useMemo(() => [
{ id: 'chat', label: 'Chat', icon: RiChat1Line },
{ id: 'diff', label: 'Diff', icon: RiCodeLine, badge: diffFileCount > 0 ? diffFileCount : undefined },
{ id: 'terminal', label: 'Terminal', icon: RiTerminalBoxLine },
{ id: 'git', label: 'Git', icon: RiGitBranchLine },
], [diffFileCount]);
useEffect(() => {
const handleKeyDown = (e: KeyboardEvent) => {
if ((e.metaKey || e.ctrlKey) && !e.shiftKey && !e.altKey) {
const num = parseInt(e.key, 10);
if (num >= 1 && num <= tabs.length) {
e.preventDefault();
setActiveMainTab(tabs[num - 1].id);
}
}
};
window.addEventListener('keydown', handleKeyDown);
return () => window.removeEventListener('keydown', handleKeyDown);
}, [tabs, setActiveMainTab]);
const renderTab = (tab: TabConfig, isLast: boolean) => {
const isActive = activeMainTab === tab.id;
const Icon = tab.icon;
const isChatTab = tab.id === 'chat';
const isGitTab = tab.id === 'git';
return (
<React.Fragment key={tab.id}>
<button
type="button"
onClick={() => setActiveMainTab(tab.id)}
onMouseDown={isActive ? handleActiveTabDragStart : undefined}
className={cn(
'relative flex h-full items-center gap-2 px-4 typography-ui-label font-medium transition-colors',
isActive ? 'app-region-drag' : 'app-region-no-drag',
'hover:text-foreground focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-inset focus-visible:ring-primary',
isActive ? 'text-foreground' : 'text-muted-foreground',
isActive && 'after:absolute after:bottom-[-1px] after:left-0 after:right-0 after:h-[2px] after:bg-background',
isActive && isChatTab && isSidebarOpen && 'before:absolute before:bottom-[-1px] before:right-full before:h-px before:bg-[var(--interactive-border)] before:w-[var(--sidebar-w)]',
isChatTab && !(isDesktopApp && isMacPlatform && isSidebarOpen) && 'border-l',
isGitTab && 'border-r',
isChatTab && !isMobile && 'min-w-[165px]'
)}
style={{
...(isActive && isChatTab && isSidebarOpen ? {
['--sidebar-w' as string]: (isDesktopApp && isMacPlatform) ? `${sidebarWidth}px` : '64px'
} : {}),
...((isChatTab && !(isDesktopApp && isMacPlatform && isSidebarOpen)) || isGitTab ? { borderColor: 'var(--interactive-border)' } : {}),
}}
aria-selected={isActive}
role="tab"
>
{isMobile ? (
<Icon size={20} />
) : (
<>
<Icon size={16} />
<span>{tab.label}</span>
</>
)}
{}
{isChatTab && !isMobile && contextUsage && contextUsage.totalTokens > 0 && (
<span className="ml-1">
<ContextUsageDisplay
totalTokens={contextUsage.totalTokens}
percentage={contextUsage.percentage}
contextLimit={contextUsage.contextLimit}
outputLimit={contextUsage.outputLimit ?? 0}
size="compact"
/>
</span>
)}
{}
{tab.badge !== undefined && tab.badge > 0 && (
<span className="text-xs font-semibold text-primary">
{tab.badge}
</span>
)}
</button>
{}
{!isLast && (
<div className="h-full w-px bg-border" aria-hidden="true" />
)}
</React.Fragment>
);
};
const renderDesktop = () => (
<div
onMouseDown={handleDragStart}
className={cn(
'app-region-drag relative flex h-12 select-none items-center',
desktopPaddingClass
)}
role="tablist"
aria-label="Main navigation"
>
{}
{!(isDesktopApp && isMacPlatform) && (
<>
<button
type="button"
onClick={handleOpenSessionSwitcher}
aria-label="Open sessions"
className={`${headerIconButtonClass} mr-2.5`}
>
<RiLayoutLeftLine className="h-5 w-5" />
</button>
</>
)}
{}
<div className="flex h-full items-center">
{tabs.map((tab, index) => renderTab(tab, index === tabs.length - 1))}
</div>
{}
<div className="flex-1" />
</div>
);
const renderMobile = () => (
<div className="app-region-drag relative flex flex-col gap-1 px-3 py-2 select-none">
<div className="flex items-center justify-between gap-2">
<div className="flex items-center gap-2">
<button
onClick={handleOpenSessionSwitcher}
className="app-region-no-drag h-9 w-9 p-2 text-muted-foreground hover:text-foreground focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-primary"
aria-label="Open sessions"
>
<RiLayoutLeftLine className="h-5 w-5" />
</button>
{contextUsage && contextUsage.totalTokens > 0 && activeMainTab === 'chat' && (
<ContextUsageDisplay
totalTokens={contextUsage.totalTokens}
percentage={contextUsage.percentage}
contextLimit={contextUsage.contextLimit}
outputLimit={contextUsage.outputLimit ?? 0}
size="compact"
/>
)}
</div>
<div className="app-region-no-drag flex items-center gap-1.5">
{}
<div className="flex items-center" role="tablist" aria-label="Main navigation">
{tabs.map((tab) => {
const isActive = activeMainTab === tab.id;
const Icon = tab.icon;
return (
<Tooltip key={tab.id} delayDuration={500}>
<TooltipTrigger asChild>
<button
type="button"
onClick={() => setActiveMainTab(tab.id)}
aria-label={tab.label}
aria-selected={isActive}
role="tab"
className={cn(
headerIconButtonClass,
isActive && 'text-foreground'
)}
>
<Icon className="h-5 w-5" />
{tab.badge !== undefined && tab.badge > 0 && (
<span className="absolute -top-1 -right-1 text-[10px] font-semibold text-primary">
{tab.badge}
</span>
)}
</button>
</TooltipTrigger>
<TooltipContent>
<p>{tab.label}</p>
</TooltipContent>
</Tooltip>
);
})}
</div>
<Button
type="button"
variant="ghost"
size="icon"
aria-expanded={isMobileDetailsOpen}
aria-controls="mobile-header-details"
onClick={() => setIsMobileDetailsOpen((prev) => !prev)}
className="app-region-no-drag h-8 w-8"
>
{isMobileDetailsOpen ? <RiArrowUpSLine className="h-4 w-4" /> : <RiArrowDownSLine className="h-4 w-4" />}
</Button>
</div>
</div>
{isMobileDetailsOpen && (
<div
id="mobile-header-details"
className="app-region-no-drag absolute left-0 right-0 top-full z-40 translate-y-2 px-3"
>
<div className="flex flex-col gap-4 rounded-xl border border-border/40 bg-background/95 px-3 py-3 shadow-none">
{contextUsage && contextUsage.totalTokens > 0 && (
<div className="flex flex-col gap-1">
<span className="typography-micro text-muted-foreground">Context usage</span>
<div className="rounded-lg border border-border/40 bg-muted/10 px-3 py-2 space-y-0.5">
<p className="typography-meta">
Used tokens: <span className="font-semibold text-foreground">{formatTokenValue(contextUsage.totalTokens)}</span>
</p>
<p className="typography-meta">
Context limit: <span className="font-semibold text-foreground">{formatTokenValue(contextUsage.contextLimit)}</span>
</p>
<p className="typography-meta">
Output limit: <span className="font-semibold text-foreground">{formatTokenValue(contextUsage.outputLimit ?? 0)}</span>
</p>
</div>
</div>
)}
</div>
</div>
)}
</div>
);
const headerClassName = cn(
'header-safe-area border-b relative z-10',
isDesktopApp ? 'bg-background' : 'bg-background/95 backdrop-blur supports-[backdrop-filter]:bg-background/80'
);
return (
<header
ref={headerRef}
className={headerClassName}
style={{ borderColor: 'var(--interactive-border)' }}
>
{isMobile ? renderMobile() : renderDesktop()}
</header>
);
};
@@ -0,0 +1,161 @@
import React from 'react';
import { Header, FixedSessionsButton } from './Header';
import { Sidebar } from './Sidebar';
import { SettingsDialog } from './SettingsDialog';
import { ErrorBoundary } from '../ui/ErrorBoundary';
import { CommandPalette } from '../ui/CommandPalette';
import { HelpDialog } from '../ui/HelpDialog';
import { SessionSidebar } from '@/components/session/SessionSidebar';
import { SessionDialogs } from '@/components/session/SessionDialogs';
import { MobileOverlayPanel } from '@/components/ui/MobileOverlayPanel';
import { useUIStore } from '@/stores/useUIStore';
import { useDeviceInfo } from '@/lib/device';
import { useEdgeSwipe } from '@/hooks/useEdgeSwipe';
import { cn } from '@/lib/utils';
import { ChatView, GitView, DiffView, TerminalView } from '@/components/views';
export const MainLayout: React.FC = () => {
const {
isSidebarOpen,
activeMainTab,
setIsMobile,
isSessionSwitcherOpen,
setSessionSwitcherOpen,
isSettingsDialogOpen,
setSettingsDialogOpen,
} = useUIStore();
const { isMobile } = useDeviceInfo();
const [isDesktopRuntime, setIsDesktopRuntime] = React.useState<boolean>(() => {
if (typeof window === 'undefined') {
return false;
}
return typeof window.opencodeDesktop !== 'undefined';
});
React.useEffect(() => {
if (typeof window === 'undefined') {
return;
}
setIsDesktopRuntime(typeof window.opencodeDesktop !== 'undefined');
}, []);
useEdgeSwipe({ enabled: true });
React.useEffect(() => {
const previous = useUIStore.getState().isMobile;
if (previous !== isMobile) {
setIsMobile(isMobile);
}
}, [isMobile, setIsMobile]);
React.useEffect(() => {
if (typeof window === 'undefined') {
return;
}
let timeoutId: number | undefined;
const handleResize = () => {
if (timeoutId !== undefined) {
window.clearTimeout(timeoutId);
}
timeoutId = window.setTimeout(() => {
useUIStore.getState().updateProportionalSidebarWidths();
}, 150);
};
window.addEventListener('resize', handleResize);
return () => {
window.removeEventListener('resize', handleResize);
if (timeoutId !== undefined) {
window.clearTimeout(timeoutId);
}
};
}, []);
const secondaryView = React.useMemo(() => {
switch (activeMainTab) {
case 'git':
return <GitView />;
case 'diff':
return <DiffView />;
case 'terminal':
return <TerminalView />;
default:
return null;
}
}, [activeMainTab]);
const isChatActive = activeMainTab === 'chat';
return (
<div
className={cn(
'main-content-safe-area h-[100dvh]',
isMobile ? 'flex flex-col' : 'flex',
isDesktopRuntime ? 'bg-transparent' : 'bg-background'
)}
>
<CommandPalette />
<HelpDialog />
<SessionDialogs />
<SettingsDialog isOpen={isSettingsDialogOpen} onClose={() => setSettingsDialogOpen(false)} />
{isMobile ? (
<>
<Header />
<div className="flex flex-1 overflow-hidden bg-background">
<main className="flex-1 overflow-hidden bg-background relative">
<div className={cn('absolute inset-0', !isChatActive && 'invisible')}>
<ErrorBoundary><ChatView /></ErrorBoundary>
</div>
{secondaryView && (
<div className="absolute inset-0">
<ErrorBoundary>{secondaryView}</ErrorBoundary>
</div>
)}
</main>
</div>
<MobileOverlayPanel
open={isSessionSwitcherOpen}
onClose={() => setSessionSwitcherOpen(false)}
title="Sessions"
>
<SessionSidebar mobileVariant />
</MobileOverlayPanel>
</>
) : (
<>
<Sidebar isOpen={isSidebarOpen} isMobile={isMobile}>
<SessionSidebar />
</Sidebar>
<div className="flex flex-1 flex-col overflow-hidden">
<Header />
<div className="flex flex-1 overflow-hidden bg-background">
<main className="flex-1 overflow-hidden bg-background relative">
<div className={cn('absolute inset-0', !isChatActive && 'invisible')}>
<ErrorBoundary><ChatView /></ErrorBoundary>
</div>
{secondaryView && (
<div className="absolute inset-0">
<ErrorBoundary>{secondaryView}</ErrorBoundary>
</div>
)}
</main>
</div>
</div>
</>
)}
<FixedSessionsButton />
</div>
);
};
@@ -0,0 +1,244 @@
import React from 'react';
import {
Dialog,
DialogContent,
DialogDescription,
DialogHeader,
DialogTitle,
} from '@/components/ui/dialog';
import { cn } from '@/lib/utils';
import { SIDEBAR_SECTIONS } from '@/constants/sidebar';
import type { SidebarSection } from '@/constants/sidebar';
import { RiArrowLeftSLine } from '@remixicon/react';
import { Button } from '@/components/ui/button';
import { AgentsSidebar } from '@/components/sections/agents/AgentsSidebar';
import { AgentsPage } from '@/components/sections/agents/AgentsPage';
import { CommandsSidebar } from '@/components/sections/commands/CommandsSidebar';
import { CommandsPage } from '@/components/sections/commands/CommandsPage';
import { ProvidersSidebar } from '@/components/sections/providers/ProvidersSidebar';
import { ProvidersPage } from '@/components/sections/providers/ProvidersPage';
import { GitIdentitiesSidebar } from '@/components/sections/git-identities/GitIdentitiesSidebar';
import { GitIdentitiesPage } from '@/components/sections/git-identities/GitIdentitiesPage';
import { SettingsPage } from '@/components/sections/settings/SettingsPage';
import { useDeviceInfo } from '@/lib/device';
import { ErrorBoundary } from '@/components/ui/ErrorBoundary';
import { SIDEBAR_CONTENT_WIDTH } from '@/components/layout/Sidebar';
import { MobileOverlayPanel } from '@/components/ui/MobileOverlayPanel';
interface SettingsDialogProps {
isOpen: boolean;
onClose: () => void;
}
const SETTINGS_SECTIONS = (() => {
const filtered = SIDEBAR_SECTIONS.filter(section => section.id !== 'sessions');
const settingsSection = filtered.find(s => s.id === 'settings');
const otherSections = filtered.filter(s => s.id !== 'settings');
return settingsSection ? [settingsSection, ...otherSections] : filtered;
})();
export const SettingsDialog: React.FC<SettingsDialogProps> = ({ isOpen, onClose }) => {
const [activeTab, setActiveTab] = React.useState<SidebarSection>('settings');
const [showPageContent, setShowPageContent] = React.useState(false);
const { isMobile } = useDeviceInfo();
React.useEffect(() => {
if (isOpen) {
setActiveTab('settings');
setShowPageContent(false);
}
}, [isOpen]);
const handleTabChange = React.useCallback((tab: SidebarSection) => {
setActiveTab(tab);
if (isMobile) {
setShowPageContent(false);
}
}, [isMobile]);
const handleItemSelect = React.useCallback(() => {
if (isMobile) {
setShowPageContent(true);
}
}, [isMobile]);
const renderSidebarContent = () => {
if (activeTab === 'settings') {
return null;
}
const content = (() => {
switch (activeTab) {
case 'agents':
return <AgentsSidebar />;
case 'commands':
return <CommandsSidebar />;
case 'providers':
return <ProvidersSidebar />;
case 'git-identities':
return <GitIdentitiesSidebar />;
default:
return null;
}
})();
if (isMobile) {
return <div onClick={handleItemSelect}>{content}</div>;
}
return content;
};
const renderPageContent = () => {
switch (activeTab) {
case 'agents':
return <AgentsPage />;
case 'commands':
return <CommandsPage />;
case 'providers':
return <ProvidersPage />;
case 'git-identities':
return <GitIdentitiesPage />;
case 'settings':
return <SettingsPage />;
default:
return null;
}
};
const activeSection = SETTINGS_SECTIONS.find(s => s.id === activeTab);
const useMobileOverlay = isMobile;
const headerContent = (
<DialogHeader
className="border-b border-border/40 px-6 pb-4 pt-[calc(var(--oc-safe-area-top,0px)+0.5rem)]"
>
<div className="relative flex items-center justify-center">
{isMobile && showPageContent && (
<Button
variant="ghost"
size="icon"
onClick={() => setShowPageContent(false)}
className="absolute left-0 h-6 w-6 flex-shrink-0"
>
<RiArrowLeftSLine className="h-5 w-5" />
<span className="sr-only">Back to sidebar</span>
</Button>
)}
<DialogTitle className="typography-ui-header">Settings</DialogTitle>
</div>
{activeSection && (
<DialogDescription className="typography-meta text-muted-foreground hidden sm:block">
{activeSection.description}
</DialogDescription>
)}
</DialogHeader>
);
const mainContent = (
<div className="flex flex-1 flex-col overflow-hidden">
<div className="flex flex-wrap items-center gap-1 border-b border-border/40 bg-background/95 px-3 py-1.5">
{SETTINGS_SECTIONS.map(({ id, label, icon: Icon }) => {
const isActive = activeTab === id;
const PhosphorIcon = Icon as React.ComponentType<{ className?: string; weight?: string }>;
return (
<button
key={id}
onClick={() => handleTabChange(id)}
className={cn(
'flex items-center gap-1 rounded-md px-2.5 py-1.5 text-xs font-medium whitespace-nowrap',
'focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-primary',
isActive ? 'text-primary' : 'text-muted-foreground hover:text-foreground'
)}
aria-pressed={isActive}
aria-label={label}
>
<PhosphorIcon className={cn('h-5 w-5 sm:h-4 sm:w-4')} weight="regular" />
<span className="hidden sm:inline">{label}</span>
</button>
);
})}
</div>
<div className="flex flex-1 overflow-hidden">
{activeTab !== 'settings' && (!isMobile || !showPageContent) && (
<div
className={cn(
'overflow-hidden border-r bg-sidebar',
isMobile && 'w-full border-r-0'
)}
style={
!isMobile
? {
width: `${SIDEBAR_CONTENT_WIDTH}px`,
minWidth: `${SIDEBAR_CONTENT_WIDTH}px`,
}
: undefined
}
>
<ErrorBoundary>{renderSidebarContent()}</ErrorBoundary>
</div>
)}
{(activeTab === 'settings' || !isMobile || showPageContent) && (
<div className={cn('flex-1 overflow-hidden bg-background', isMobile && 'w-full')}>
<ErrorBoundary>{renderPageContent()}</ErrorBoundary>
</div>
)}
</div>
</div>
);
const panelContent = (
<div className="flex h-full flex-col overflow-hidden">
{!useMobileOverlay && headerContent}
{mainContent}
</div>
);
if (useMobileOverlay) {
return (
<MobileOverlayPanel
open={isOpen}
onClose={onClose}
title="Settings"
className="max-w-full"
renderHeader={(closeButton) => (
<div className="flex items-center justify-between px-3 py-2 border-b border-border/40">
<div className="relative flex flex-1 items-center justify-center">
{showPageContent && (
<Button
variant="ghost"
size="icon"
onClick={() => setShowPageContent(false)}
className="absolute left-0 h-6 w-6 flex-shrink-0"
>
<RiArrowLeftSLine className="h-5 w-5" />
<span className="sr-only">Back to sidebar</span>
</Button>
)}
<span className="typography-ui-header">Settings</span>
</div>
{closeButton}
</div>
)}
>
{mainContent}
</MobileOverlayPanel>
);
}
return (
<Dialog open={isOpen} onOpenChange={(open) => !open && onClose()}>
<DialogContent
className={cn(
'flex flex-col gap-0 p-0',
'h-[88vh] w-[65vw] max-w-[900px]'
)}
>
{panelContent}
</DialogContent>
</Dialog>
);
};
@@ -0,0 +1,218 @@
import React from 'react';
import { RiDownloadLine, RiSettings3Line } from '@remixicon/react';
import { cn } from '@/lib/utils';
import { ErrorBoundary } from '../ui/ErrorBoundary';
import { useUIStore } from '@/stores/useUIStore';
import { useUpdateCheck } from '@/hooks/useUpdateCheck';
import { UpdateDialog } from '../ui/UpdateDialog';
export const SIDEBAR_CONTENT_WIDTH = 264;
const SIDEBAR_MIN_WIDTH = 200;
const SIDEBAR_MAX_WIDTH = 500;
const MAC_TITLEBAR_SAFE_AREA = 40;
interface SidebarProps {
isOpen: boolean;
isMobile: boolean;
children: React.ReactNode;
}
export const Sidebar: React.FC<SidebarProps> = ({ isOpen, isMobile, children }) => {
const { sidebarWidth, setSidebarWidth, setSettingsDialogOpen } = useUIStore();
const [isResizing, setIsResizing] = React.useState(false);
const startXRef = React.useRef(0);
const startWidthRef = React.useRef(sidebarWidth || SIDEBAR_CONTENT_WIDTH);
const [updateDialogOpen, setUpdateDialogOpen] = React.useState(false);
const update = useUpdateCheck();
const [isDesktopApp, setIsDesktopApp] = React.useState<boolean>(() => {
if (typeof window === 'undefined') {
return false;
}
return typeof (window as typeof window & { opencodeDesktop?: unknown }).opencodeDesktop !== 'undefined';
});
const isMacPlatform = React.useMemo(() => {
if (typeof navigator === 'undefined') {
return false;
}
return /Macintosh|Mac OS X/.test(navigator.userAgent || '');
}, []);
React.useEffect(() => {
if (typeof window === 'undefined') {
return;
}
const detected = typeof (window as typeof window & { opencodeDesktop?: unknown }).opencodeDesktop !== 'undefined';
setIsDesktopApp(detected);
}, []);
React.useEffect(() => {
if (isMobile || !isResizing) {
return;
}
const handlePointerMove = (event: PointerEvent) => {
const delta = event.clientX - startXRef.current;
const nextWidth = Math.min(
SIDEBAR_MAX_WIDTH,
Math.max(SIDEBAR_MIN_WIDTH, startWidthRef.current + delta)
);
setSidebarWidth(nextWidth);
};
const handlePointerUp = () => {
setIsResizing(false);
};
window.addEventListener('pointermove', handlePointerMove);
window.addEventListener('pointerup', handlePointerUp, { once: true });
return () => {
window.removeEventListener('pointermove', handlePointerMove);
window.removeEventListener('pointerup', handlePointerUp);
};
}, [isMobile, isResizing, setSidebarWidth]);
React.useEffect(() => {
if (isMobile && isResizing) {
setIsResizing(false);
}
}, [isMobile, isResizing]);
const handleTitlebarDragStart = React.useCallback(async (e: React.MouseEvent) => {
if (e.button !== 0) {
return;
}
if (isDesktopApp) {
try {
const { getCurrentWindow } = await import('@tauri-apps/api/window');
const window = getCurrentWindow();
await window.startDragging();
} catch (error) {
console.error('Failed to start window dragging from sidebar:', error);
}
}
}, [isDesktopApp]);
if (isMobile) {
return null;
}
const appliedWidth = isOpen ? Math.min(
SIDEBAR_MAX_WIDTH,
Math.max(SIDEBAR_MIN_WIDTH, sidebarWidth || SIDEBAR_CONTENT_WIDTH)
) : 0;
const shouldRenderTitlebarSpacer = isDesktopApp && isMacPlatform;
const handlePointerDown = (event: React.PointerEvent) => {
if (!isOpen) {
return;
}
setIsResizing(true);
startXRef.current = event.clientX;
startWidthRef.current = appliedWidth;
event.preventDefault();
};
return (
<aside
className={cn(
'relative flex h-full overflow-hidden border-r',
isDesktopApp
? 'bg-[color:var(--sidebar-overlay-strong)] backdrop-blur supports-[backdrop-filter]:bg-[color:var(--sidebar-overlay-soft)]'
: 'bg-sidebar',
isResizing ? 'transition-none' : '',
!isOpen && 'border-r-0'
)}
style={{
width: `${appliedWidth}px`,
minWidth: `${appliedWidth}px`,
maxWidth: `${appliedWidth}px`,
pointerEvents: !isOpen ? 'none' : undefined,
borderColor: 'var(--interactive-border)',
overflowX: 'clip',
}}
aria-hidden={!isOpen || appliedWidth === 0}
>
{isOpen && (
<div
className={cn(
'absolute right-0 top-0 z-20 h-full w-[6px] -mr-[3px] cursor-col-resize',
isResizing ? 'bg-primary/30' : 'bg-transparent hover:bg-primary/20'
)}
onPointerDown={handlePointerDown}
role="separator"
aria-orientation="vertical"
aria-label="Resize left panel"
/>
)}
<div
className={cn(
'relative z-10 flex h-full flex-col transition-opacity duration-200 ease-in-out',
!isOpen && 'pointer-events-none select-none opacity-0'
)}
style={{ width: `${appliedWidth}px`, overflowX: 'hidden' }}
aria-hidden={!isOpen}
>
{shouldRenderTitlebarSpacer && (
<div
className="flex-shrink-0 select-none"
style={{ height: `${MAC_TITLEBAR_SAFE_AREA}px` }}
onMouseDown={handleTitlebarDragStart}
aria-hidden
/>
)}
<div className="flex-1 overflow-hidden">
<ErrorBoundary>{children}</ErrorBoundary>
</div>
<div className="flex-shrink-0 border-t border-border p-2">
<div className="flex items-center justify-between gap-2">
<button
onClick={() => setSettingsDialogOpen(true)}
className={cn(
'flex items-center gap-2 rounded-md px-3 py-2',
'text-sm text-muted-foreground',
'hover:bg-accent hover:text-accent-foreground',
'transition-colors'
)}
>
<RiSettings3Line className="h-4 w-4" />
<span>Settings</span>
</button>
{(update.available || update.downloaded) && (
<button
onClick={() => setUpdateDialogOpen(true)}
className={cn(
'flex items-center gap-1.5 rounded-md px-2.5 py-1.5',
'text-xs font-medium',
'bg-primary/10 text-primary',
'hover:bg-primary/20',
'transition-colors'
)}
>
<RiDownloadLine className="h-3.5 w-3.5" />
<span>Update</span>
</button>
)}
</div>
</div>
<UpdateDialog
open={updateDialogOpen}
onOpenChange={setUpdateDialogOpen}
info={update.info}
downloading={update.downloading}
downloaded={update.downloaded}
progress={update.progress}
error={update.error}
onDownload={update.downloadUpdate}
onRestart={update.restartToUpdate}
/>
</div>
</aside>
);
};
@@ -0,0 +1,61 @@
import React from 'react';
import { useSessionStore } from '@/stores/useSessionStore';
import { useDirectoryStore } from '@/stores/useDirectoryStore';
import { cn } from '@/lib/utils';
interface SidebarContextSummaryProps {
className?: string;
}
const formatSessionTitle = (title?: string | null) => {
if (!title) {
return 'Untitled Session';
}
const trimmed = title.trim();
return trimmed.length > 0 ? trimmed : 'Untitled Session';
};
const formatDirectoryPath = (path?: string) => {
if (!path || path.length === 0) {
return '/';
}
return path;
};
export const SidebarContextSummary: React.FC<SidebarContextSummaryProps> = ({ className }) => {
const currentSessionId = useSessionStore((state) => state.currentSessionId);
const sessions = useSessionStore((state) => state.sessions);
const { currentDirectory } = useDirectoryStore();
const activeSessionTitle = React.useMemo(() => {
if (!currentSessionId) {
return 'No active session';
}
const session = sessions.find((item) => item.id === currentSessionId);
return session ? formatSessionTitle(session.title) : 'No active session';
}, [currentSessionId, sessions]);
const directoryFull = React.useMemo(() => {
return formatDirectoryPath(currentDirectory);
}, [currentDirectory]);
const directoryDisplay = React.useMemo(() => {
if (!directoryFull || directoryFull === '/') {
return directoryFull;
}
const segments = directoryFull.split('/').filter(Boolean);
return segments.length ? segments[segments.length - 1] : directoryFull;
}, [directoryFull]);
return (
<div className={cn('hidden min-h-[48px] flex-col justify-center gap-0.5 border-b border-border/40 bg-sidebar/60 px-3 py-2 backdrop-blur md:flex md:pb-2', className)}>
<span className="typography-meta text-muted-foreground">Session</span>
<span className="typography-ui-label font-semibold text-foreground truncate" title={activeSessionTitle}>
{activeSessionTitle}
</span>
<span className="typography-meta text-muted-foreground truncate" title={directoryFull}>
{directoryDisplay}
</span>
</div>
);
};