Files
openchamber/packages/ui/src/components/sections/commands/CommandsSidebar.tsx
T

432 lines
14 KiB
TypeScript

import React from 'react';
import { Button } from '@/components/ui/button';
import { ButtonLarge } from '@/components/ui/button-large';
import { Input } from '@/components/ui/input';
import { toast } from '@/components/ui';
import {
Dialog,
DialogContent,
DialogDescription,
DialogFooter,
DialogHeader,
DialogTitle,
} from '@/components/ui/dialog';
import {
DropdownMenu,
DropdownMenuContent,
DropdownMenuItem,
DropdownMenuTrigger,
} from '@/components/ui/dropdown-menu';
import { RiAddLine, RiTerminalBoxLine, RiMore2Line, RiDeleteBinLine, RiFileCopyLine, RiRestartLine, RiEditLine } from '@remixicon/react';
import { useCommandsStore, isCommandBuiltIn, type Command } from '@/stores/useCommandsStore';
import { useUIStore } from '@/stores/useUIStore';
import { useDeviceInfo } from '@/lib/device';
import { isVSCodeRuntime } from '@/lib/desktop';
import { ScrollableOverlay } from '@/components/ui/ScrollableOverlay';
import { cn } from '@/lib/utils';
interface CommandsSidebarProps {
onItemSelect?: () => void;
}
export const CommandsSidebar: React.FC<CommandsSidebarProps> = ({ onItemSelect }) => {
const [renameDialogCommand, setRenameDialogCommand] = React.useState<Command | null>(null);
const [renameNewName, setRenameNewName] = React.useState('');
const {
selectedCommandName,
commands,
setSelectedCommand,
setCommandDraft,
createCommand,
deleteCommand,
loadCommands,
} = useCommandsStore();
const { setSidebarOpen } = useUIStore();
const { isMobile } = useDeviceInfo();
const [isDesktopRuntime, setIsDesktopRuntime] = React.useState<boolean>(() => {
if (typeof window === 'undefined') return false;
return typeof window.opencodeDesktop !== 'undefined';
});
const isVSCode = React.useMemo(() => isVSCodeRuntime(), []);
React.useEffect(() => {
if (typeof window === 'undefined') return;
setIsDesktopRuntime(typeof window.opencodeDesktop !== 'undefined');
}, []);
React.useEffect(() => {
loadCommands();
}, [loadCommands]);
const bgClass = isDesktopRuntime
? 'bg-transparent'
: isVSCode
? 'bg-background'
: 'bg-sidebar';
const handleCreateNew = () => {
// Generate unique name
const baseName = 'new-command';
let newName = baseName;
let counter = 1;
while (commands.some((c) => c.name === newName)) {
newName = `${baseName}-${counter}`;
counter++;
}
// Set draft and open the page for editing
setCommandDraft({ name: newName, scope: 'user' });
setSelectedCommand(newName);
onItemSelect?.();
if (isMobile) {
setSidebarOpen(false);
}
};
const handleDeleteCommand = async (command: Command) => {
if (isCommandBuiltIn(command)) {
toast.error('Built-in commands cannot be deleted');
return;
}
if (window.confirm(`Are you sure you want to delete command "${command.name}"?`)) {
const success = await deleteCommand(command.name);
if (success) {
toast.success(`Command "${command.name}" deleted successfully`);
} else {
toast.error('Failed to delete command');
}
}
};
const handleResetCommand = async (command: Command) => {
if (!isCommandBuiltIn(command)) {
return;
}
if (window.confirm(`Are you sure you want to reset command "${command.name}" to its default configuration?`)) {
const success = await deleteCommand(command.name);
if (success) {
toast.success(`Command "${command.name}" reset to default`);
} else {
toast.error('Failed to reset command');
}
}
};
const handleDuplicateCommand = (command: Command) => {
const baseName = command.name;
let copyNumber = 1;
let newName = `${baseName}-copy`;
while (commands.some((c) => c.name === newName)) {
copyNumber++;
newName = `${baseName}-copy-${copyNumber}`;
}
// Set draft with prefilled values from source command
setCommandDraft({
name: newName,
scope: command.scope || 'user',
description: command.description,
template: command.template,
agent: command.agent,
model: command.model,
subtask: command.subtask,
});
setSelectedCommand(newName);
if (isMobile) {
setSidebarOpen(false);
}
};
const handleOpenRenameDialog = (command: Command) => {
setRenameNewName(command.name);
setRenameDialogCommand(command);
};
const handleRenameCommand = async () => {
if (!renameDialogCommand) return;
const sanitizedName = renameNewName.trim().replace(/\s+/g, '-');
if (!sanitizedName) {
toast.error('Command name is required');
return;
}
if (sanitizedName === renameDialogCommand.name) {
setRenameDialogCommand(null);
return;
}
if (commands.some((cmd) => cmd.name === sanitizedName)) {
toast.error('A command with this name already exists');
return;
}
// Create new command with new name and all existing config
const success = await createCommand({
name: sanitizedName,
description: renameDialogCommand.description,
template: renameDialogCommand.template,
agent: renameDialogCommand.agent,
model: renameDialogCommand.model,
subtask: renameDialogCommand.subtask,
});
if (success) {
// Delete old command
const deleteSuccess = await deleteCommand(renameDialogCommand.name);
if (deleteSuccess) {
toast.success(`Command renamed to "${sanitizedName}"`);
setSelectedCommand(sanitizedName);
} else {
toast.error('Failed to remove old command after rename');
}
} else {
toast.error('Failed to rename command');
}
setRenameDialogCommand(null);
};
const builtInCommands = commands.filter(isCommandBuiltIn);
const customCommands = commands.filter((cmd) => !isCommandBuiltIn(cmd));
return (
<div className={cn('flex h-full flex-col', bgClass)}>
<div className={cn('border-b px-3', isMobile ? 'mt-2 py-3' : 'py-3')}>
<div className="flex items-center justify-between gap-2">
<span className="typography-meta text-muted-foreground">Total {commands.length}</span>
<Button
type="button"
variant="ghost"
size="icon"
className="h-7 w-7 -my-1 text-muted-foreground"
onClick={handleCreateNew}
>
<RiAddLine className="size-4" />
</Button>
</div>
</div>
<ScrollableOverlay outerClassName="flex-1 min-h-0" className="space-y-1 px-3 py-2">
{commands.length === 0 ? (
<div className="py-12 px-4 text-center text-muted-foreground">
<RiTerminalBoxLine className="mx-auto mb-3 h-10 w-10 opacity-50" />
<p className="typography-ui-label font-medium">No commands configured</p>
<p className="typography-meta mt-1 opacity-75">Use the + button above to create one</p>
</div>
) : (
<>
{builtInCommands.length > 0 && (
<>
<div className="px-2 pb-1.5 pt-2 text-xs font-semibold uppercase tracking-wide text-muted-foreground">
Built-in Commands
</div>
{[...builtInCommands].sort((a, b) => a.name.localeCompare(b.name)).map((command) => (
<CommandListItem
key={command.name}
command={command}
isSelected={selectedCommandName === command.name}
onSelect={() => {
setSelectedCommand(command.name);
onItemSelect?.();
if (isMobile) {
setSidebarOpen(false);
}
}}
onReset={() => handleResetCommand(command)}
onDuplicate={() => handleDuplicateCommand(command)}
/>
))}
</>
)}
{customCommands.length > 0 && (
<>
<div className="px-2 pb-1.5 pt-3 text-xs font-semibold uppercase tracking-wide text-muted-foreground">
Custom Commands
</div>
{[...customCommands].sort((a, b) => a.name.localeCompare(b.name)).map((command) => (
<CommandListItem
key={command.name}
command={command}
isSelected={selectedCommandName === command.name}
onSelect={() => {
setSelectedCommand(command.name);
onItemSelect?.();
if (isMobile) {
setSidebarOpen(false);
}
}}
onRename={() => handleOpenRenameDialog(command)}
onDelete={() => handleDeleteCommand(command)}
onDuplicate={() => handleDuplicateCommand(command)}
/>
))}
</>
)}
</>
)}
</ScrollableOverlay>
{/* Rename Dialog */}
<Dialog open={renameDialogCommand !== null} onOpenChange={(open) => !open && setRenameDialogCommand(null)}>
<DialogContent>
<DialogHeader>
<DialogTitle>Rename Command</DialogTitle>
<DialogDescription>
Enter a new name for the command "/{renameDialogCommand?.name}"
</DialogDescription>
</DialogHeader>
<Input
value={renameNewName}
onChange={(e) => setRenameNewName(e.target.value)}
placeholder="New command name..."
className="text-foreground placeholder:text-muted-foreground"
onKeyDown={(e) => {
if (e.key === 'Enter') {
handleRenameCommand();
}
}}
/>
<DialogFooter>
<Button
variant="ghost"
onClick={() => setRenameDialogCommand(null)}
className="text-foreground hover:bg-muted hover:text-foreground"
>
Cancel
</Button>
<ButtonLarge onClick={handleRenameCommand}>
Rename
</ButtonLarge>
</DialogFooter>
</DialogContent>
</Dialog>
</div>
);
};
interface CommandListItemProps {
command: Command;
isSelected: boolean;
onSelect: () => void;
onDelete?: () => void;
onReset?: () => void;
onRename?: () => void;
onDuplicate: () => void;
}
const CommandListItem: React.FC<CommandListItemProps> = ({
command,
isSelected,
onSelect,
onDelete,
onReset,
onRename,
onDuplicate,
}) => {
return (
<div
className={cn(
'group relative flex items-center rounded-md px-1.5 py-1 transition-all duration-200',
isSelected ? 'dark:bg-accent/80 bg-primary/12' : 'hover:dark:bg-accent/40 hover:bg-primary/6'
)}
>
<div className="flex min-w-0 flex-1 items-center">
<button
onClick={onSelect}
className="flex min-w-0 flex-1 flex-col gap-0 rounded-sm text-left focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-primary/50"
tabIndex={0}
>
<div className="flex items-center gap-2">
<span className="typography-ui-label font-normal truncate text-foreground">
/{command.name}
</span>
{(command.scope || isCommandBuiltIn(command)) && (
<span className="typography-micro text-muted-foreground bg-muted px-1 rounded flex-shrink-0 leading-none pb-px border border-border/50">
{isCommandBuiltIn(command) ? 'system' : command.scope}
</span>
)}
</div>
{command.description && (
<div className="typography-micro text-muted-foreground/60 truncate leading-tight">
{command.description}
</div>
)}
</button>
<DropdownMenu>
<DropdownMenuTrigger asChild>
<Button
size="icon"
variant="ghost"
className="h-6 w-6 flex-shrink-0 -mr-1 opacity-100 transition-opacity md:opacity-0 md:group-hover:opacity-100"
>
<RiMore2Line className="h-3.5 w-3.5" />
</Button>
</DropdownMenuTrigger>
<DropdownMenuContent align="end" className="w-fit min-w-20">
{onRename && (
<DropdownMenuItem
onClick={(e) => {
e.stopPropagation();
onRename();
}}
>
<RiEditLine className="h-4 w-4 mr-px" />
Rename
</DropdownMenuItem>
)}
<DropdownMenuItem
onClick={(e) => {
e.stopPropagation();
onDuplicate();
}}
>
<RiFileCopyLine className="h-4 w-4 mr-px" />
Duplicate
</DropdownMenuItem>
{onReset && (
<DropdownMenuItem
onClick={(e) => {
e.stopPropagation();
onReset();
}}
>
<RiRestartLine className="h-4 w-4 mr-px" />
Reset
</DropdownMenuItem>
)}
{onDelete && (
<DropdownMenuItem
onClick={(e) => {
e.stopPropagation();
onDelete();
}}
className="text-destructive focus:text-destructive"
>
<RiDeleteBinLine className="h-4 w-4 mr-px" />
Delete
</DropdownMenuItem>
)}
</DropdownMenuContent>
</DropdownMenu>
</div>
</div>
);
};