feat: bulk delete chats from sidebar (#1586)

* feat: Bulk Delete Chats from Sidebar

feat(sidebar): Implement bulk chat deletion

Adds the ability for users to select multiple chats from the history sidebar and delete them in bulk.

**Key Changes:**

*   **Selection Mode:** Introduced a selection mode toggled by a dedicated button next to "Start new chat".
*   **Checkboxes:** Added checkboxes to each `HistoryItem` visible only when selection mode is active.
*   **Bulk Actions:** Added "Select All" / "Deselect All" and "Delete Selected" buttons (`Button` component with `ghost` variant) that appear above the chat list in selection mode.
*   **Confirmation Dialog:** Implemented a confirmation dialog (`Dialog` component) to prevent accidental deletion, listing the chats selected for removal.
*   **Deletion Logic:** Updated `Menu.client.tsx` to handle the selection state and perform bulk deletion using `deleteById` from persistence layer.
*   **Styling:** Ensured all new UI elements (`Checkbox`, `Button`) adhere to the existing project design system and support both light and dark themes using appropriate CSS classes and UnoCSS icons (`i-ph:` prefix).
*   **Refinement:** Replaced initial plain `<button>` elements with the project's `Button` component for consistency. Fixed incorrect icon prefixes.

* Fix selection and Dark mode
This commit is contained in:
Stijnus 2025-04-06 20:36:53 +02:00 committed by GitHub
parent 03736df1ce
commit b54d160a3b
No known key found for this signature in database
GPG Key ID: B5690EEEBB952194
4 changed files with 400 additions and 48 deletions

View File

@ -149,6 +149,48 @@ export default function ConnectionsTab() {
</div>
</motion.div>
{/* Cloudflare Deployment Note - Highly visible */}
<motion.div
className="bg-gradient-to-r from-blue-50 to-blue-100 dark:from-blue-950/40 dark:to-blue-900/30 border border-blue-200 dark:border-blue-800/50 rounded-lg shadow-sm p-4 mb-6"
initial={{ opacity: 0, y: 20 }}
animate={{ opacity: 1, y: 0 }}
transition={{ delay: 0.3 }}
>
<div className="flex items-center gap-2 mb-2 text-blue-700 dark:text-blue-400">
<div className="i-ph:cloud-bold w-5 h-5" />
<h3 className="text-base font-medium">Using Cloudflare Pages?</h3>
</div>
<p className="text-sm text-blue-700 dark:text-blue-300 mb-2">
If you're experiencing GitHub connection issues (500 errors) on Cloudflare Pages deployments, you need to
configure environment variables in your Cloudflare dashboard:
</p>
<div className="bg-white/80 dark:bg-slate-900/60 rounded-md p-3 text-sm border border-blue-200 dark:border-blue-800/50">
<ol className="list-decimal list-inside pl-2 text-blue-700 dark:text-blue-300 space-y-2">
<li>
Go to <strong>Cloudflare Pages dashboard Your project Settings Environment variables</strong>
</li>
<li>
Add <strong>both</strong> of these secrets (Production environment):
<ul className="list-disc list-inside pl-4 mt-1 mb-1">
<li>
<code className="px-1 py-0.5 bg-blue-100 dark:bg-blue-800/40 rounded">GITHUB_ACCESS_TOKEN</code>{' '}
(server-side API calls)
</li>
<li>
<code className="px-1 py-0.5 bg-blue-100 dark:bg-blue-800/40 rounded">VITE_GITHUB_ACCESS_TOKEN</code>{' '}
(client-side access)
</li>
</ul>
</li>
<li>
Add <code className="px-1 py-0.5 bg-blue-100 dark:bg-blue-800/40 rounded">VITE_GITHUB_TOKEN_TYPE</code> if
using fine-grained tokens
</li>
<li>Deploy a fresh build after adding these variables</li>
</ol>
</div>
</motion.div>
<div className="grid grid-cols-1 gap-6">
<Suspense fallback={<LoadingFallback />}>
<GitHubConnection />

View File

@ -1,19 +1,30 @@
import { useParams } from '@remix-run/react';
import { classNames } from '~/utils/classNames';
import * as Dialog from '@radix-ui/react-dialog';
import { type ChatHistoryItem } from '~/lib/persistence';
import WithTooltip from '~/components/ui/Tooltip';
import { useEditChatDescription } from '~/lib/hooks';
import { forwardRef, type ForwardedRef } from 'react';
import { forwardRef, type ForwardedRef, useCallback } from 'react';
import { Checkbox } from '~/components/ui/Checkbox';
interface HistoryItemProps {
item: ChatHistoryItem;
onDelete?: (event: React.UIEvent) => void;
onDuplicate?: (id: string) => void;
exportChat: (id?: string) => void;
selectionMode?: boolean;
isSelected?: boolean;
onToggleSelection?: (id: string) => void;
}
export function HistoryItem({ item, onDelete, onDuplicate, exportChat }: HistoryItemProps) {
export function HistoryItem({
item,
onDelete,
onDuplicate,
exportChat,
selectionMode = false,
isSelected = false,
onToggleSelection,
}: HistoryItemProps) {
const { id: urlId } = useParams();
const isActiveChat = urlId === item.urlId;
@ -24,13 +35,56 @@ export function HistoryItem({ item, onDelete, onDuplicate, exportChat }: History
syncWithGlobalStore: isActiveChat,
});
const handleItemClick = useCallback(
(e: React.MouseEvent) => {
if (selectionMode) {
e.preventDefault();
e.stopPropagation();
console.log('Item clicked in selection mode:', item.id);
onToggleSelection?.(item.id);
}
},
[selectionMode, item.id, onToggleSelection],
);
const handleCheckboxChange = useCallback(() => {
console.log('Checkbox changed for item:', item.id);
onToggleSelection?.(item.id);
}, [item.id, onToggleSelection]);
const handleDeleteClick = useCallback(
(event: React.MouseEvent<HTMLButtonElement, MouseEvent>) => {
event.preventDefault();
event.stopPropagation();
console.log('Delete button clicked for item:', item.id);
if (onDelete) {
onDelete(event as unknown as React.UIEvent);
}
},
[onDelete, item.id],
);
return (
<div
className={classNames(
'group rounded-lg text-sm text-gray-700 dark:text-gray-300 hover:text-gray-900 dark:hover:text-white hover:bg-gray-50/80 dark:hover:bg-gray-800/30 overflow-hidden flex justify-between items-center px-3 py-2 transition-colors',
{ 'text-gray-900 dark:text-white bg-gray-50/80 dark:bg-gray-800/30': isActiveChat },
{ 'cursor-pointer': selectionMode },
)}
onClick={selectionMode ? handleItemClick : undefined}
>
{selectionMode && (
<div className="flex items-center mr-2" onClick={(e) => e.stopPropagation()}>
<Checkbox
id={`select-${item.id}`}
checked={isSelected}
onCheckedChange={handleCheckboxChange}
className="h-4 w-4"
/>
</div>
)}
{editing ? (
<form onSubmit={handleSubmit} className="flex-1 flex items-center gap-2">
<input
@ -49,14 +103,17 @@ export function HistoryItem({ item, onDelete, onDuplicate, exportChat }: History
/>
</form>
) : (
<a href={`/chat/${item.urlId}`} className="flex w-full relative truncate block">
<a
href={`/chat/${item.urlId}`}
className="flex w-full relative truncate block"
onClick={selectionMode ? handleItemClick : undefined}
>
<WithTooltip tooltip={currentDescription}>
<span className="truncate pr-24">{currentDescription}</span>
</WithTooltip>
<div
className={classNames(
'absolute right-0 top-0 bottom-0 flex items-center bg-white dark:bg-gray-950 group-hover:bg-gray-50/80 dark:group-hover:bg-gray-800/30 px-2',
{ 'bg-gray-50/80 dark:bg-gray-800/30': isActiveChat },
'absolute right-0 top-0 bottom-0 flex items-center bg-transparent px-2 transition-colors',
)}
>
<div className="flex items-center gap-2.5 text-gray-400 dark:text-gray-500 opacity-0 group-hover:opacity-100 transition-opacity">
@ -72,7 +129,10 @@ export function HistoryItem({ item, onDelete, onDuplicate, exportChat }: History
<ChatActionButton
toolTipContent="Duplicate"
icon="i-ph:copy h-4 w-4"
onClick={() => onDuplicate?.(item.id)}
onClick={(event) => {
event.preventDefault();
onDuplicate?.(item.id);
}}
/>
)}
<ChatActionButton
@ -83,17 +143,12 @@ export function HistoryItem({ item, onDelete, onDuplicate, exportChat }: History
toggleEditMode();
}}
/>
<Dialog.Trigger asChild>
<ChatActionButton
toolTipContent="Delete"
icon="i-ph:trash h-4 w-4"
className="hover:text-red-500"
onClick={(event) => {
event.preventDefault();
onDelete?.(event);
}}
className="hover:text-red-500 dark:hover:text-red-400"
onClick={handleDeleteClick}
/>
</Dialog.Trigger>
</div>
</div>
</a>

View File

@ -5,9 +5,9 @@ import { Dialog, DialogButton, DialogDescription, DialogRoot, DialogTitle } from
import { ThemeSwitch } from '~/components/ui/ThemeSwitch';
import { ControlPanel } from '~/components/@settings/core/ControlPanel';
import { SettingsButton } from '~/components/ui/SettingsButton';
import { Button } from '~/components/ui/Button';
import { db, deleteById, getAll, chatId, type ChatHistoryItem, useChatHistory } from '~/lib/persistence';
import { cubicEasingFn } from '~/utils/easings';
import { logger } from '~/utils/logger';
import { HistoryItem } from './HistoryItem';
import { binDates } from './date-binning';
import { useSearchFilter } from '~/lib/hooks/useSearchFilter';
@ -36,7 +36,10 @@ const menuVariants = {
},
} satisfies Variants;
type DialogContent = { type: 'delete'; item: ChatHistoryItem } | null;
type DialogContent =
| { type: 'delete'; item: ChatHistoryItem }
| { type: 'bulkDelete'; items: ChatHistoryItem[] }
| null;
function CurrentDateTime() {
const [dateTime, setDateTime] = useState(new Date());
@ -51,7 +54,7 @@ function CurrentDateTime() {
return (
<div className="flex items-center gap-2 px-4 py-2 text-sm text-gray-600 dark:text-gray-400 border-b border-gray-100 dark:border-gray-800/50">
<div className="h-4 w-4 i-lucide:clock opacity-80" />
<div className="h-4 w-4 i-ph:clock opacity-80" />
<div className="flex gap-2">
<span>{dateTime.toLocaleDateString()}</span>
<span>{dateTime.toLocaleTimeString([], { hour: '2-digit', minute: '2-digit' })}</span>
@ -68,6 +71,8 @@ export const Menu = () => {
const [dialogContent, setDialogContent] = useState<DialogContent>(null);
const [isSettingsOpen, setIsSettingsOpen] = useState(false);
const profile = useStore(profileStore);
const [selectionMode, setSelectionMode] = useState(false);
const [selectedItems, setSelectedItems] = useState<string[]>([]);
const { filteredItems: filteredList, handleSearchChange } = useSearchFilter({
items: list,
@ -83,35 +88,195 @@ export const Menu = () => {
}
}, []);
const deleteItem = useCallback((event: React.UIEvent, item: ChatHistoryItem) => {
event.preventDefault();
const deleteChat = useCallback(
async (id: string): Promise<void> => {
if (!db) {
throw new Error('Database not available');
}
if (db) {
deleteById(db, item.id)
// Delete chat snapshot from localStorage
try {
const snapshotKey = `snapshot:${id}`;
localStorage.removeItem(snapshotKey);
console.log('Removed snapshot for chat:', id);
} catch (snapshotError) {
console.error(`Error deleting snapshot for chat ${id}:`, snapshotError);
}
// Delete the chat from the database
await deleteById(db, id);
console.log('Successfully deleted chat:', id);
},
[db],
);
const deleteItem = useCallback(
(event: React.UIEvent, item: ChatHistoryItem) => {
event.preventDefault();
event.stopPropagation();
// Log the delete operation to help debugging
console.log('Attempting to delete chat:', { id: item.id, description: item.description });
deleteChat(item.id)
.then(() => {
toast.success('Chat deleted successfully', {
position: 'bottom-right',
autoClose: 3000,
});
// Always refresh the list
loadEntries();
if (chatId.get() === item.id) {
// hard page navigation to clear the stores
console.log('Navigating away from deleted chat');
window.location.pathname = '/';
}
})
.catch((error) => {
toast.error('Failed to delete conversation');
logger.error(error);
console.error('Failed to delete chat:', error);
toast.error('Failed to delete conversation', {
position: 'bottom-right',
autoClose: 3000,
});
// Still try to reload entries in case data has changed
loadEntries();
});
},
[loadEntries, deleteChat],
);
const deleteSelectedItems = useCallback(
async (itemsToDeleteIds: string[]) => {
if (!db || itemsToDeleteIds.length === 0) {
console.log('Bulk delete skipped: No DB or no items to delete.');
return;
}
console.log(`Starting bulk delete for ${itemsToDeleteIds.length} chats`, itemsToDeleteIds);
let deletedCount = 0;
const errors: string[] = [];
const currentChatId = chatId.get();
let shouldNavigate = false;
// Process deletions sequentially using the shared deleteChat logic
for (const id of itemsToDeleteIds) {
try {
await deleteChat(id);
deletedCount++;
if (id === currentChatId) {
shouldNavigate = true;
}
} catch (error) {
console.error(`Error deleting chat ${id}:`, error);
errors.push(id);
}
}
// Show appropriate toast message
if (errors.length === 0) {
toast.success(`${deletedCount} chat${deletedCount === 1 ? '' : 's'} deleted successfully`);
} else {
toast.warning(`Deleted ${deletedCount} of ${itemsToDeleteIds.length} chats. ${errors.length} failed.`, {
autoClose: 5000,
});
}
}, []);
// Reload the list after all deletions
await loadEntries();
// Clear selection state
setSelectedItems([]);
setSelectionMode(false);
// Navigate if needed
if (shouldNavigate) {
console.log('Navigating away from deleted chat');
window.location.pathname = '/';
}
},
[deleteChat, loadEntries, db],
);
const closeDialog = () => {
setDialogContent(null);
};
const toggleSelectionMode = () => {
setSelectionMode(!selectionMode);
if (selectionMode) {
// If turning selection mode OFF, clear selection
setSelectedItems([]);
}
};
const toggleItemSelection = useCallback((id: string) => {
setSelectedItems((prev) => {
const newSelectedItems = prev.includes(id) ? prev.filter((itemId) => itemId !== id) : [...prev, id];
console.log('Selected items updated:', newSelectedItems);
return newSelectedItems; // Return the new array
});
}, []); // No dependencies needed
const handleBulkDeleteClick = useCallback(() => {
if (selectedItems.length === 0) {
toast.info('Select at least one chat to delete');
return;
}
const selectedChats = list.filter((item) => selectedItems.includes(item.id));
if (selectedChats.length === 0) {
toast.error('Could not find selected chats');
return;
}
setDialogContent({ type: 'bulkDelete', items: selectedChats });
}, [selectedItems, list]); // Keep list dependency
const selectAll = useCallback(() => {
const allFilteredIds = filteredList.map((item) => item.id);
setSelectedItems((prev) => {
const allFilteredAreSelected = allFilteredIds.length > 0 && allFilteredIds.every((id) => prev.includes(id));
if (allFilteredAreSelected) {
// Deselect only the filtered items
const newSelectedItems = prev.filter((id) => !allFilteredIds.includes(id));
console.log('Deselecting all filtered items. New selection:', newSelectedItems);
return newSelectedItems;
} else {
// Select all filtered items, adding them to any existing selections
const newSelectedItems = [...new Set([...prev, ...allFilteredIds])];
console.log('Selecting all filtered items. New selection:', newSelectedItems);
return newSelectedItems;
}
});
}, [filteredList]); // Depends only on filteredList
useEffect(() => {
if (open) {
loadEntries();
}
}, [open]);
}, [open, loadEntries]);
// Exit selection mode when sidebar is closed
useEffect(() => {
if (!open && selectionMode) {
/*
* Don't clear selection state anymore when sidebar closes
* This allows the selection to persist when reopening the sidebar
*/
console.log('Sidebar closed, preserving selection state');
}
}, [open, selectionMode]);
useEffect(() => {
const enterThreshold = 40;
@ -138,11 +303,6 @@ export const Menu = () => {
};
}, [isSettingsOpen]);
const handleDeleteClick = (event: React.UIEvent, item: ChatHistoryItem) => {
event.preventDefault();
setDialogContent({ type: 'delete', item });
};
const handleDuplicate = async (id: string) => {
await duplicateCurrentChat(id);
loadEntries(); // Reload the list after duplication
@ -157,6 +317,11 @@ export const Menu = () => {
setIsSettingsOpen(false);
};
const setDialogContentWithLogging = useCallback((content: DialogContent) => {
console.log('Setting dialog content:', content);
setDialogContent(content);
}, []);
return (
<>
<motion.div
@ -196,16 +361,30 @@ export const Menu = () => {
<CurrentDateTime />
<div className="flex-1 flex flex-col h-full w-full overflow-hidden">
<div className="p-4 space-y-3">
<div className="flex gap-2">
<a
href="/"
className="flex gap-2 items-center bg-purple-50 dark:bg-purple-500/10 text-purple-700 dark:text-purple-300 hover:bg-purple-100 dark:hover:bg-purple-500/20 rounded-lg px-4 py-2 transition-colors"
className="flex-1 flex gap-2 items-center bg-purple-50 dark:bg-purple-500/10 text-purple-700 dark:text-purple-300 hover:bg-purple-100 dark:hover:bg-purple-500/20 rounded-lg px-4 py-2 transition-colors"
>
<span className="inline-block i-lucide:message-square h-4 w-4" />
<span className="inline-block i-ph:plus-circle h-4 w-4" />
<span className="text-sm font-medium">Start new chat</span>
</a>
<button
onClick={toggleSelectionMode}
className={classNames(
'flex gap-1 items-center rounded-lg px-3 py-2 transition-colors',
selectionMode
? 'bg-purple-600 dark:bg-purple-500 text-white border border-purple-700 dark:border-purple-600'
: 'bg-gray-100 dark:bg-gray-800 text-gray-700 dark:text-gray-300 hover:bg-gray-200 dark:hover:bg-gray-700 border border-gray-200 dark:border-gray-700',
)}
aria-label={selectionMode ? 'Exit selection mode' : 'Enter selection mode'}
>
<span className={selectionMode ? 'i-ph:x h-4 w-4' : 'i-ph:check-square h-4 w-4'} />
</button>
</div>
<div className="relative w-full">
<div className="absolute left-3 top-1/2 -translate-y-1/2">
<span className="i-lucide:search h-4 w-4 text-gray-400 dark:text-gray-500" />
<span className="i-ph:magnifying-glass h-4 w-4 text-gray-400 dark:text-gray-500" />
</div>
<input
className="w-full bg-gray-50 dark:bg-gray-900 relative pl-9 pr-3 py-2 rounded-lg focus:outline-none focus:ring-1 focus:ring-purple-500/50 text-sm text-gray-900 dark:text-gray-100 placeholder-gray-500 dark:placeholder-gray-500 border border-gray-200 dark:border-gray-800"
@ -216,7 +395,24 @@ export const Menu = () => {
/>
</div>
</div>
<div className="text-gray-600 dark:text-gray-400 text-sm font-medium px-4 py-2">Your Chats</div>
<div className="flex items-center justify-between text-sm px-4 py-2">
<div className="font-medium text-gray-600 dark:text-gray-400">Your Chats</div>
{selectionMode && (
<div className="flex items-center gap-2">
<Button variant="ghost" size="sm" onClick={selectAll}>
{selectedItems.length === filteredList.length ? 'Deselect all' : 'Select all'}
</Button>
<Button
variant="destructive"
size="sm"
onClick={handleBulkDeleteClick}
disabled={selectedItems.length === 0}
>
Delete selected
</Button>
</div>
)}
</div>
<div className="flex-1 overflow-auto px-3 pb-3">
{filteredList.length === 0 && (
<div className="px-4 text-gray-500 dark:text-gray-400 text-sm">
@ -235,8 +431,16 @@ export const Menu = () => {
key={item.id}
item={item}
exportChat={exportChat}
onDelete={(event) => handleDeleteClick(event, item)}
onDelete={(event) => {
event.preventDefault();
event.stopPropagation();
console.log('Delete triggered for item:', item);
setDialogContentWithLogging({ type: 'delete', item });
}}
onDuplicate={() => handleDuplicate(item.id)}
selectionMode={selectionMode}
isSelected={selectedItems.includes(item.id)}
onToggleSelection={toggleItemSelection}
/>
))}
</div>
@ -264,6 +468,7 @@ export const Menu = () => {
<DialogButton
type="danger"
onClick={(event) => {
console.log('Dialog delete button clicked for item:', dialogContent.item);
deleteItem(event, dialogContent.item);
closeDialog();
}}
@ -273,6 +478,49 @@ export const Menu = () => {
</div>
</>
)}
{dialogContent?.type === 'bulkDelete' && (
<>
<div className="p-6 bg-white dark:bg-gray-950">
<DialogTitle className="text-gray-900 dark:text-white">Delete Selected Chats?</DialogTitle>
<DialogDescription className="mt-2 text-gray-600 dark:text-gray-400">
<p>
You are about to delete {dialogContent.items.length}{' '}
{dialogContent.items.length === 1 ? 'chat' : 'chats'}:
</p>
<div className="mt-2 max-h-32 overflow-auto border border-gray-100 dark:border-gray-800 rounded-md bg-gray-50 dark:bg-gray-900 p-2">
<ul className="list-disc pl-5 space-y-1">
{dialogContent.items.map((item) => (
<li key={item.id} className="text-sm">
<span className="font-medium text-gray-900 dark:text-white">{item.description}</span>
</li>
))}
</ul>
</div>
<p className="mt-3">Are you sure you want to delete these chats?</p>
</DialogDescription>
</div>
<div className="flex justify-end gap-3 px-6 py-4 bg-gray-50 dark:bg-gray-900 border-t border-gray-100 dark:border-gray-800">
<DialogButton type="secondary" onClick={closeDialog}>
Cancel
</DialogButton>
<DialogButton
type="danger"
onClick={() => {
/*
* Pass the current selectedItems to the delete function.
* This captures the state at the moment the user confirms.
*/
const itemsToDeleteNow = [...selectedItems];
console.log('Bulk delete confirmed for', itemsToDeleteNow.length, 'items', itemsToDeleteNow);
deleteSelectedItems(itemsToDeleteNow);
closeDialog();
}}
>
Delete
</DialogButton>
</div>
</>
)}
</Dialog>
</DialogRoot>
</div>

View File

@ -10,13 +10,20 @@ const Checkbox = React.forwardRef<
<CheckboxPrimitive.Root
ref={ref}
className={classNames(
'peer h-4 w-4 shrink-0 rounded-sm border border-gray-300 focus:outline-none focus:ring-2 focus:ring-purple-500 focus:ring-offset-2 disabled:cursor-not-allowed disabled:opacity-50 dark:border-gray-700 dark:focus:ring-purple-400 dark:focus:ring-offset-gray-900',
'peer h-4 w-4 shrink-0 rounded-sm border transition-colors',
'bg-transparent dark:bg-transparent',
'border-gray-400 dark:border-gray-600',
'focus-visible:outline-none focus-visible:ring-1 focus-visible:ring-offset-1 focus-visible:ring-purple-500 focus-visible:ring-offset-white dark:focus-visible:ring-offset-gray-950',
'disabled:cursor-not-allowed disabled:opacity-50',
'data-[state=checked]:bg-purple-500 dark:data-[state=checked]:bg-purple-500',
'data-[state=checked]:border-purple-500 dark:data-[state=checked]:border-purple-500',
'data-[state=checked]:text-white',
className,
)}
{...props}
>
<CheckboxPrimitive.Indicator className="flex items-center justify-center">
<Check className="h-3 w-3 text-purple-500 dark:text-purple-400" />
<CheckboxPrimitive.Indicator className="flex items-center justify-center text-current">
<Check className="h-3 w-3" />
</CheckboxPrimitive.Indicator>
</CheckboxPrimitive.Root>
));