ui : Search dialog (#31173)

* ui : replace the sidebar search mode with a search dialog

Search opens a spotlight dialog (Cmd+K or the Search entry under New chat in the sidebar) with keyboard navigation over recent chats and sidebar actions. Phones keep the search page.

Sidebar actions show their shortcuts, with new ones for Settings (Cmd+,) and Models (Shift+Cmd+M).

Assisted-by: Claude (Opus 5.5 Medium)

* ui : ignore search dialog keys while an IME is composing

Enter confirms an IME candidate and the arrow keys move through the candidates, so the search field leaves them to the IME instead of opening the highlighted result or moving the highlight.

Assisted-by: Claude (Opus 5.5 Medium)
This commit is contained in:
Aleksander Grygier authored and GitHub committed 2026-10-28 08:53:41 +02:00
1 parent 8ca4060b7e
commit 6886628cb1
20 files changed
+575 -279

No files matched your search

@@ -0,0 +1,261 @@
<script lang="ts">
import { ArrowDown, ArrowUp, CornerDownLeft, MessageSquare, Pin, X } from '@lucide/svelte';
import { goto } from '$app/navigation';
import { ActionIcon, KeyboardShortcutInfo } from '$lib/components/app';
import * as Dialog from '$lib/components/ui/dialog';
import {
ICON_CLASS_DEFAULT,
ICON_CLASS_SM,
ICON_CLASS_XS,
SIDEBAR_ACTIONS_ITEMS
} from '$lib/constants';
import { KeyboardKey, SidebarAction } from '$lib/enums';
import { RouterService } from '$lib/services/router.service';
import { conversationsStore } from '$lib/stores';
import { formatRelativeTime, isIMEComposing } from '$lib/utils';
import type { Component } from 'svelte';
interface Props {
open: boolean;
/** Runs a sidebar action picked from the actions section. */
onAction?: (action: SidebarAction) => void;
}
let { onAction, open = $bindable() }: Props = $props();
interface SearchEntry {
icon: Component;
id: string;
keys?: string[];
label: string;
meta?: string;
pinned?: boolean;
run: () => void;
}
interface SearchSection {
entries: SearchEntry[];
title: string;
}
/** Recent chats shown before typing, so the actions stay in view below them. */
const RECENT_LIMIT = 5;
/** Matches kept while typing; the rest stays reachable by typing more. */
const MATCH_LIMIT = 50;
let query = $state('');
let highlighted = $state(0);
let inputRef = $state<HTMLInputElement | null>(null);
const needle = $derived(query.trim().toLowerCase());
const limit = $derived(needle ? MATCH_LIMIT : RECENT_LIMIT);
function matches(label: string): boolean {
return !needle || label.toLowerCase().includes(needle);
}
const chatEntries = $derived.by((): SearchEntry[] =>
conversationsStore.conversations
.filter((conversation) => matches(conversation.name))
.sort((a, b) => b.lastModified - a.lastModified)
.slice(0, limit)
.map((conversation) => ({
icon: MessageSquare,
id: `chat-${conversation.id}`,
label: conversation.name,
meta: formatRelativeTime(conversation.lastModified),
pinned: conversation.pinned,
run: () => close(() => goto(RouterService.chat(conversation.id)))
}))
);
const actionEntries = $derived.by((): SearchEntry[] =>
// every sidebar action but Search itself, which is what opened this dialog
SIDEBAR_ACTIONS_ITEMS.filter((item) => item.action && item.action !== SidebarAction.SEARCH)
.map((item) => ({
icon: item.icon,
id: `action-${item.action}`,
keys: item.keys,
label: item.tooltip,
run: () => close(() => onAction?.(item.action!))
}))
.filter((entry) => matches(entry.label))
);
const sections = $derived<SearchSection[]>(
[
{ entries: chatEntries, title: needle ? 'Chats' : 'Recents' },
{ entries: actionEntries, title: 'Actions' }
].filter((section) => section.entries.length > 0)
);
const entries = $derived(sections.flatMap((section) => section.entries));
const activeIndex = $derived(Math.min(highlighted, entries.length - 1));
const emptyMessage = $derived(needle ? 'No results found' : 'No chats yet');
/** Closes the search first, so a dialog opened by `next` takes the focus. */
function close(next: () => void) {
handleOpenChange(false);
next();
}
function move(step: number) {
if (entries.length === 0) return;
highlighted = (activeIndex + step + entries.length) % entries.length;
document.getElementById(`search-result-${highlighted}`)?.scrollIntoView({ block: 'nearest' });
}
function handleKeydown(event: KeyboardEvent) {
// while an IME is composing, Enter confirms a candidate and the arrows move through them
if (isIMEComposing(event)) return;
if (event.key === KeyboardKey.ARROW_DOWN) {
event.preventDefault();
move(1);
} else if (event.key === KeyboardKey.ARROW_UP) {
event.preventDefault();
move(-1);
} else if (event.key === KeyboardKey.ENTER) {
event.preventDefault();
entries[activeIndex]?.run();
}
}
function handleOpenChange(nextOpen: boolean) {
if (!nextOpen) {
query = '';
highlighted = 0;
}
open = nextOpen;
}
</script>
{#snippet hint(label: string, keys: (string | Component)[])}
<span class="flex items-center gap-1.5">
{label}
<span class="flex items-center gap-1">
{#each keys as Key, index (index)}
<kbd
class="inline-flex h-5 min-w-5 items-center justify-center rounded border border-border/60 px-1 font-sans text-[11px]"
>
{#if typeof Key === 'string'}
{Key}
{:else}
<Key class={ICON_CLASS_XS} />
{/if}
</kbd>
{/each}
</span>
</span>
{/snippet}
<Dialog.Root onOpenChange={handleOpenChange} {open}>
<Dialog.Content
class="top-[12%] flex h-[min(36rem,76dvh)]! w-full max-w-2xl! translate-y-0 flex-col gap-0 overflow-hidden rounded-xl p-0 max-md:top-4 md:w-full md:max-w-2xl!"
onOpenAutoFocus={(event) => {
event.preventDefault();
inputRef?.focus();
}}
>
<Dialog.Title class="sr-only">Search</Dialog.Title>
<div class="border-b border-border/30 px-4 py-3 dark:border-border/20">
<div class="flex items-center gap-2">
<input
bind:this={inputRef}
bind:value={query}
aria-activedescendant={entries.length > 0 ? `search-result-${activeIndex}` : undefined}
aria-controls="search-results"
aria-expanded="true"
autocomplete="off"
class="h-10 min-w-0 flex-1 border-0 bg-transparent px-1 text-lg outline-none placeholder:text-muted-foreground focus:outline-none focus-visible:ring-0"
oninput={() => (highlighted = 0)}
onkeydown={handleKeydown}
placeholder="Search"
role="combobox"
spellcheck={false}
/>
<ActionIcon
ariaLabel="Close search"
class="h-8 w-8 shrink-0 text-muted-foreground"
icon={X}
iconSize={ICON_CLASS_DEFAULT}
onclick={() => handleOpenChange(false)}
/>
</div>
</div>
<div class="min-h-0 flex-1 overflow-y-auto p-2" id="search-results" role="listbox">
{#each sections as section, sectionIndex (section.title)}
{@const offset = sections
.slice(0, sectionIndex)
.reduce((total, previous) => total + previous.entries.length, 0)}
<div class="flex flex-col gap-0.5 {sectionIndex > 0 ? 'mt-3' : ''}" role="group">
<p class="px-2.5 pt-1 pb-1.5 text-xs font-medium text-muted-foreground">
{section.title}
</p>
{#each section.entries as entry, entryIndex (entry.id)}
{@const index = offset + entryIndex}
{@const isActive = index === activeIndex}
<button
aria-selected={isActive}
class="flex w-full cursor-pointer items-center gap-2.5 rounded-md px-2.5 py-2 text-left text-sm transition-colors {isActive
? 'bg-accent text-accent-foreground'
: ''}"
id="search-result-{index}"
onclick={entry.run}
onmousemove={() => (highlighted = index)}
role="option"
tabindex={-1}
type="button"
>
<entry.icon class="{ICON_CLASS_DEFAULT} shrink-0 text-muted-foreground" />
<span class="min-w-0 flex-1 truncate">{entry.label}</span>
{#if entry.pinned}
<Pin aria-label="Pinned" class="{ICON_CLASS_SM} shrink-0 text-muted-foreground" />
{/if}
{#if entry.meta}
<span class="max-w-[40%] shrink-0 truncate text-xs text-muted-foreground">
{entry.meta}
</span>
{/if}
{#if entry.keys}
<KeyboardShortcutInfo class="opacity-100" keys={entry.keys} />
{/if}
<CornerDownLeft
class="{ICON_CLASS_SM} shrink-0 text-muted-foreground {isActive
? 'opacity-100'
: 'opacity-0'}"
/>
</button>
{/each}
</div>
{:else}
<p class="px-3 py-12 text-center text-sm text-muted-foreground">{emptyMessage}</p>
{/each}
</div>
<div
class="flex items-center gap-5 border-t border-border/30 px-4 py-2.5 text-xs text-muted-foreground max-md:hidden dark:border-border/20"
>
{@render hint('Close', ['Esc'])}
{@render hint('Navigate', [ArrowUp, ArrowDown])}
<span class="ml-auto">{@render hint('Open', [CornerDownLeft])}</span>
</div>
</Dialog.Content>
</Dialog.Root>
@@ -108,6 +108,14 @@ export { default as DialogExportSettings } from './DialogExportSettings.svelte';
*/
export { default as DialogConfirmation } from './DialogConfirmation.svelte';
/**
* **DialogSearch** - Spotlight-style search over chats and sidebar actions
*
* Opens over the app with a focused input and a keyboard-driven result list:
* arrow keys move the highlight, Enter opens, Escape closes. Desktop only; phones use the `/search` page.
*/
export { default as DialogSearch } from './DialogSearch.svelte';
/**
* **DialogConfirmDownload** - Confirm a destructive download action
*
@@ -1,5 +1,6 @@
<script lang="ts">
import { ArrowBigUp } from '@lucide/svelte';
import { ICON_CLASS_DEFAULT } from '$lib/constants';
interface Props {
keys: string[];
@@ -19,7 +20,9 @@
<kbd class="{baseClasses} {variantClasses} {className}">
{#each keys as key, index (index)}
{#if key === 'shift'}
<ArrowBigUp class="h-1 w-1 {variant === 'destructive' ? 'text-destructive' : ''} -mr-1" />
<ArrowBigUp
class="{ICON_CLASS_DEFAULT} {variant === 'destructive' ? 'text-destructive' : ''} -mr-1"
/>
{:else if key === 'cmd'}
<span class={variant === 'destructive' ? 'text-destructive' : ''}>⌘</span>
{:else}
@@ -8,6 +8,7 @@
DialogConversationRename,
DialogDiscoverModels,
DialogMcpServers,
DialogSearch,
DialogSettingsChat,
Logo,
ModelsManagerModelDrawer,
@@ -23,7 +24,7 @@
SIDEBAR_OVERSTRETCH_PX,
SIDEBAR_SETTLE_MS
} from '$lib/constants';
import { TooltipSide } from '$lib/enums';
import { SidebarAction, TooltipSide } from '$lib/enums';
import { useKeyboardShortcuts } from '$lib/hooks/use-keyboard-shortcuts.svelte';
import { useMarqueeSelection } from '$lib/hooks/use-marquee-selection.svelte';
import { RouterService } from '$lib/services/router.service';
@@ -33,14 +34,10 @@
import { SvelteSet } from 'svelte/reactivity';
import { fade } from 'svelte/transition';
interface Props {
onSearchClick?: () => void;
}
let { onSearchClick = () => {} }: Props = $props();
const { handleKeydown } = useKeyboardShortcuts({
activateSearchMode: () => onSearchClick(),
openModelsManager: () => handleSidebarAction(SidebarAction.MANAGE_MODELS),
openSearch: () => handleSidebarAction(SidebarAction.SEARCH),
openSettings: () => handleSidebarAction(SidebarAction.SETTINGS),
toggleSidebar: () => toggleExpandedMode()
});
@@ -67,9 +64,6 @@
$effect(() => {
if (!uiStore.isSidebarExpanded) {
isSearchModeActive = false;
searchQuery = '';
if (isSelectionMode) exitSelectionMode();
cancelMobileCollapse();
@@ -83,22 +77,18 @@
});
let currentChatId = $derived(page.params.id);
let isSearchModeActive = $state(false);
let searchQuery = $state('');
let searchOpen = $state(false);
let filteredConversations = $derived.by(() => {
if (isSearchModeActive) {
if (searchQuery.trim().length > 0) {
return conversationsStore.conversations.filter((conversation: { name: string }) =>
conversation.name.toLowerCase().includes(searchQuery.toLowerCase())
);
}
// a phone shows the search page instead of the spotlight overlay
function openSearch() {
if (deviceStore.isMobile) {
void goto(ROUTES.SEARCH);
return [];
return;
}
return conversationsStore.conversations;
});
searchOpen = true;
}
let isSelectionMode = $state(false);
let selectedIds = new SvelteSet<string>();
@@ -111,7 +101,7 @@
let renameOriginalTitle = $state('');
const renderedOrderIds = $derived(
buildConversationTree(filteredConversations).map((t) => t.conversation.id)
buildConversationTree(conversationsStore.conversations).map((t) => t.conversation.id)
);
const allSelectedArePinned = $derived.by(() => {
@@ -151,7 +141,7 @@
});
const visibleSelectionStats = $derived.by(() => {
const visibleIds = filteredConversations.map((c) => c.id);
const visibleIds = conversationsStore.conversations.map((c) => c.id);
let selectedVisible = 0;
@@ -187,7 +177,7 @@
}
function toggleSelectAllVisible() {
const visibleIds = filteredConversations.map((c) => c.id);
const visibleIds = conversationsStore.conversations.map((c) => c.id);
const allSelected = visibleIds.length > 0 && visibleIds.every((id) => selectedIds.has(id));
if (allSelected) {
@@ -454,6 +444,36 @@
open();
}
/** Runs a sidebar action, whether picked from the icon strip, the search dialog or a shortcut. */
function handleSidebarAction(action: SidebarAction): void {
switch (action) {
case SidebarAction.NEW_CHAT:
if (deviceStore.isMobile) {
scheduleMobileCollapse();
}
void conversationsStore.openNewChat();
break;
case SidebarAction.SEARCH:
openSearch();
break;
case SidebarAction.MANAGE_MODELS:
openDialog(() => uiStore.openModelsManager());
break;
case SidebarAction.MCP:
openDialog(() => (mcpDialogOpen = true));
break;
case SidebarAction.SETTINGS:
openDialog(() => (settingsDialogOpen = true));
break;
}
}
</script>
<svelte:window bind:innerWidth onkeydown={handleKeydown} />
@@ -505,7 +525,7 @@
/>
</div>
{#if isOnMobile || (uiStore.isSidebarExpanded && !alwaysShowOnDesktop)}
{#if isOnMobile || uiStore.isSidebarExpanded}
<div
in:fade={{ delay: 50, duration: 150, easing: circIn }}
out:fade={{ duration: 100 }}
@@ -514,16 +534,18 @@
? 'opacity-0 h-0!'
: ''}"
>
<ActionIcon
ariaLabel="Collapse navigation"
class="backdrop-blur-none md:h-9 md:w-9 h-10 w-10 rounded-full mr-1 max-md:-mr-1 max-md:-mt-1 hover:bg-accent!"
icon={deviceStore.isMobile ? X : PanelLeftClose}
iconSize="h-4 w-4"
onclick={toggleExpandedMode}
size="lg"
tooltip="Close Sidebar"
tooltipSide={TooltipSide.LEFT}
/>
{#if isOnMobile || !alwaysShowOnDesktop}
<ActionIcon
ariaLabel="Collapse navigation"
class="backdrop-blur-none md:h-9 md:w-9 h-10 w-10 rounded-full mr-1 max-md:-mr-1 max-md:-mt-1 hover:bg-accent!"
icon={deviceStore.isMobile ? X : PanelLeftClose}
iconSize="h-4 w-4"
onclick={toggleExpandedMode}
size="lg"
tooltip="Close Sidebar"
tooltipSide={TooltipSide.LEFT}
/>
{/if}
</div>
{/if}
</div>
@@ -536,26 +558,14 @@
: ''} {deviceStore.isMobile && !uiStore.isSidebarExpanded ? 'opacity-0 !h-0' : ''}"
>
<SidebarNavigationActions
bind:isSearchModeActive
bind:searchQuery
class="px-2"
isExpandedMode={innerWidth > 768 ? uiStore.isSidebarExpanded : true}
onManageModelsClick={() => openDialog(() => uiStore.openModelsManager())}
onMcpClick={() => openDialog(() => (mcpDialogOpen = true))}
onNewChat={() => {
onAction={handleSidebarAction}
onNavigate={() => {
if (deviceStore.isMobile) {
scheduleMobileCollapse();
}
}}
onSearchClick={() => {
uiStore.isSidebarExpanded = true;
isSearchModeActive = true;
}}
onSearchDeactivated={() => {
isSearchModeActive = false;
searchQuery = '';
}}
onSettingsClick={() => openDialog(() => (settingsDialogOpen = true))}
/>
{#if uiStore.isSidebarExpanded || isOnMobile}
@@ -565,9 +575,8 @@
allVisibleSelected={visibleSelectionStats.visibleCount > 0 &&
visibleSelectionStats.selectedVisibleCount === visibleSelectionStats.visibleCount}
class="px-2"
conversations={conversationsStore.conversations}
{currentChatId}
{filteredConversations}
{isSearchModeActive}
{isSelectionMode}
onBulkDelete={handleBulkDelete}
onBulkExport={handleBulkExport}
@@ -583,7 +592,6 @@
onStop={handleStopGeneration}
onToggleSelect={toggleSelected}
{pinStateIsMixed}
{searchQuery}
{selectedIds}
someVisibleSelected={visibleSelectionStats.selectedVisibleCount > 0 &&
visibleSelectionStats.selectedVisibleCount < visibleSelectionStats.visibleCount}
@@ -638,6 +646,8 @@
<DialogSettingsChat bind:open={settingsDialogOpen} />
<DialogSearch bind:open={searchOpen} onAction={handleSidebarAction} />
<DialogMcpServers bind:open={mcpDialogOpen} />
<DialogDiscoverModels bind:open={uiStore.discoverModelsOpen} />
@@ -1,18 +1,16 @@
<script lang="ts">
import { Search } from '@lucide/svelte';
import { goto } from '$app/navigation';
import { page } from '$app/state';
import { ActionIcon, KeyboardShortcutInfo, SearchInput } from '$lib/components/app';
import { ActionIcon, KeyboardShortcutInfo } from '$lib/components/app';
import { Button } from '$lib/components/ui/button';
import {
ICON_CLASS_DEFAULT,
ICON_STRIP_TRANSITION_DELAY_MULTIPLIER,
ICON_STRIP_TRANSITION_DURATION,
ROUTES,
SIDEBAR_ACTIONS_ITEMS
} from '$lib/constants';
import { SidebarAction, TooltipSide } from '$lib/enums';
import { conversationsStore, deviceStore } from '$lib/stores';
import { deviceStore } from '$lib/stores';
import type { DesktopIconStripItem } from '$lib/types';
import type { Component } from 'svelte';
import { onMount } from 'svelte';
@@ -22,28 +20,12 @@
interface Props {
class: string;
isExpandedMode: boolean;
isSearchModeActive: boolean;
searchQuery: string;
onSearchDeactivated?: () => void;
onSearchClick?: () => void;
onManageModelsClick?: () => void;
onMcpClick?: () => void;
onNewChat?: () => void;
onSettingsClick?: () => void;
onAction?: (action: SidebarAction) => void;
/** Called before following a route item, so a phone can collapse the sidebar. */
onNavigate?: () => void;
}
let {
class: className,
isExpandedMode = false,
isSearchModeActive = $bindable(false),
onManageModelsClick,
onMcpClick,
onNewChat,
onSearchClick,
onSearchDeactivated,
onSettingsClick,
searchQuery = $bindable('')
}: Props = $props();
let { class: className, isExpandedMode = false, onAction, onNavigate }: Props = $props();
// the models manager stays desktop-only: a phone picks its models in the selector
const actions = $derived(
@@ -53,16 +35,9 @@
);
let initialized = $state(false);
let showIcons = $state(false);
let searchInputRef = $state<HTMLInputElement | null>(null);
const isOnMobile = $derived(deviceStore.isMobile);
$effect(() => {
if (isSearchModeActive && searchInputRef) {
searchInputRef.focus();
}
});
onMount(() => {
showIcons = true;
@@ -71,41 +46,22 @@
}, ICON_STRIP_TRANSITION_DELAY_MULTIPLIER * actions.length);
});
/** Click handler of one icon strip item: a sidebar action, a route, or the search. */
function itemClickHandler(
item: DesktopIconStripItem,
isSearchOnMobile: boolean
): (() => void) | undefined {
switch (item.action) {
case SidebarAction.NEW_CHAT:
return () => {
onNewChat?.();
void conversationsStore.openNewChat();
};
case SidebarAction.MANAGE_MODELS:
return () => onManageModelsClick?.();
case SidebarAction.MCP:
return () => onMcpClick?.();
case SidebarAction.SETTINGS:
return () => onSettingsClick?.();
default:
break;
/** Click handler of one icon strip item: a sidebar action or a route. */
function itemClickHandler(item: DesktopIconStripItem): (() => void) | undefined {
const { action, route } = item;
if (action) {
return () => onAction?.(action);
}
if (item.route) {
if (route) {
return () => {
onNewChat?.();
goto(item.route!);
onNavigate?.();
goto(route);
};
}
return isSearchOnMobile ? undefined : onSearchClick;
}
function handleSearchModeDeactivate() {
isSearchModeActive = false;
searchQuery = '';
onSearchDeactivated?.();
return undefined;
}
function isItemActive(item: {
@@ -133,17 +89,7 @@
<IconComponent class={ICON_CLASS_DEFAULT} />
{/snippet}
{#if isSearchModeActive}
<div class="px-4 my-2">
<SearchInput
bind:ref={searchInputRef}
bind:value={searchQuery}
onClose={handleSearchModeDeactivate}
onKeyDown={(e) => e.key === 'Escape' && handleSearchModeDeactivate()}
placeholder="Search conversations..."
/>
</div>
{:else if isExpandedMode || isOnMobile}
{#if isExpandedMode || isOnMobile}
<div
class="{className} flex flex-col gap-5 md:gap-1 mt-2 md:mt-0 {!isExpandedMode && isOnMobile
? 'hidden pointer-events-none'
@@ -151,9 +97,7 @@
>
{#each actions as item, i (item.tooltip)}
{@const isActive = isItemActive(item)}
{@const isSearchOnMobile = item.icon === Search && deviceStore.isMobile}
{@const itemHref = isSearchOnMobile ? ROUTES.SEARCH : item.route}
{@const itemOnClick = itemClickHandler(item, isSearchOnMobile)}
{@const itemOnClick = itemClickHandler(item)}
{@const itemTransition = {
delay: !initialized ? i * ICON_STRIP_TRANSITION_DELAY_MULTIPLIER : 0,
duration: ICON_STRIP_TRANSITION_DURATION,
@@ -166,7 +110,7 @@
class="w-full min-w-9 justify-between px-2 backdrop-blur-none! hover:[&>kbd]:opacity-100 {isActive
? 'bg-accent text-accent-foreground'
: ''}"
href={itemHref}
href={item.route}
onclick={itemOnClick}
size="default"
variant="ghost"
@@ -195,8 +139,7 @@
<div class="{className} flex-col gap-1 hidden md:flex">
{#each actions as item, i (item.tooltip)}
{@const isActive = isItemActive(item)}
{@const isSearchOnMobile = item.icon === Search && deviceStore.isMobile}
{@const itemOnClick = itemClickHandler(item, isSearchOnMobile)}
{@const itemOnClick = itemClickHandler(item)}
{@const itemTransition = {
delay: !initialized ? i * ICON_STRIP_TRANSITION_DELAY_MULTIPLIER : 0,
duration: ICON_STRIP_TRANSITION_DURATION,
@@ -16,7 +16,14 @@
import { TruncatedText } from '$lib/components/app';
import { Checkbox } from '$lib/components/ui/checkbox';
import * as Tooltip from '$lib/components/ui/tooltip';
import { FORK_TREE_DEPTH_PADDING, ICON_CLASS_DEFAULT, UI_DATA_ATTRS } from '$lib/constants';
import {
FORK_TREE_DEPTH_PADDING,
ICON_CLASS_DEFAULT,
SHORTCUT_DELETE_CONVERSATION,
SHORTCUT_EDIT_CONVERSATION,
SHORTCUT_EXPORT_CONVERSATION,
UI_DATA_ATTRS
} from '$lib/constants';
import { RouterService } from '$lib/services/router.service';
import { chatStore, conversationsStore, settingsStore, tabsStore } from '$lib/stores';
import { onMount } from 'svelte';
@@ -288,7 +295,7 @@
icon: Pencil,
label: 'Edit',
onclick: handleEdit,
shortcut: ['shift', 'cmd', 'e']
shortcut: SHORTCUT_EDIT_CONVERSATION
},
{
icon: Download,
@@ -297,7 +304,7 @@
e.stopPropagation();
conversationsStore.downloadConversation(conversation.id);
},
shortcut: ['shift', 'cmd', 's']
shortcut: SHORTCUT_EXPORT_CONVERSATION
},
{
icon: ListChecks,
@@ -309,7 +316,7 @@
label: 'Delete',
onclick: handleDelete,
separator: true,
shortcut: ['shift', 'cmd', 'd'],
shortcut: SHORTCUT_DELETE_CONVERSATION,
variant: 'destructive'
}
]}
@@ -1,16 +1,13 @@
<script lang="ts">
import SidebarNavigationConversationItem from './SidebarNavigationConversationItem.svelte';
import SidebarNavigationSearchResults from './SidebarNavigationSearchResults.svelte';
import SidebarNavigationSelectionBar from './SidebarNavigationSelectionBar.svelte';
import { Pin } from '@lucide/svelte';
import { buildConversationTree } from '$lib/utils';
interface Props {
class: string;
filteredConversations: DatabaseConversation[];
conversations: DatabaseConversation[];
currentChatId: string | undefined;
isSearchModeActive: boolean;
searchQuery: string;
isSelectionMode?: boolean;
selectedIds?: Set<string>;
onSelect: (id: string) => void;
@@ -37,9 +34,8 @@
allSelectedArePinned,
allVisibleSelected,
class: className,
conversations,
currentChatId,
filteredConversations,
isSearchModeActive,
isSelectionMode = false,
onBulkDelete,
onBulkExport,
@@ -55,13 +51,12 @@
onStop,
onToggleSelect,
pinStateIsMixed,
searchQuery,
selectedIds = new Set<string>(),
someVisibleSelected,
visibleCount
}: Props = $props();
let conversationTree = $derived(buildConversationTree(filteredConversations));
let conversationTree = $derived(buildConversationTree(conversations));
let pinnedConversations = $derived(
conversationTree.filter(({ conversation }) => conversation.pinned)
@@ -70,44 +65,62 @@
let unpinnedConversations = $derived(
conversationTree.filter(({ conversation }) => !conversation.pinned)
);
const recentEmptyMessage = $derived(
searchQuery.length > 0 ? 'No results found' : 'No conversations yet'
);
</script>
<div class="flex min-h-0 flex-1 flex-col">
{#if isSearchModeActive}
<SidebarNavigationSearchResults
class={className}
{currentChatId}
{filteredConversations}
{isSelectionMode}
{onDelete}
{onEdit}
{onEnterSelectionMode}
{onRowMouseDown}
{onSelect}
{onSelectionClick}
{onStop}
{onToggleSelect}
{searchQuery}
{selectedIds}
/>
{:else}
{#if pinnedConversations.length > 0}
<div class="py-2 flex whitespace-nowrap {className}">
<div
class="text-muted-foreground inline-flex h-8 shrink-0 items-center rounded-md px-2 text-xs font-medium gap-1"
>
<Pin class="h-3.5 w-3.5" />
{#if pinnedConversations.length > 0}
<div class="py-2 flex whitespace-nowrap {className}">
<div
class="text-muted-foreground inline-flex h-8 shrink-0 items-center rounded-md px-2 text-xs font-medium gap-1"
>
<Pin class="h-3.5 w-3.5" />
<span>Pinned</span>
</div>
<span>Pinned</span>
</div>
</div>
<ul class="flex w-full min-w-0 flex-col gap-4 md:gap-1 {className}">
{#each pinnedConversations as { conversation, depth } (conversation.id)}
<ul class="flex w-full min-w-0 flex-col gap-4 md:gap-1 {className}">
{#each pinnedConversations as { conversation, depth } (conversation.id)}
<li class="group/item relative mb-1 p-0">
<SidebarNavigationConversationItem
conversation={{
currNode: conversation.currNode,
forkedFromConversationId: conversation.forkedFromConversationId,
id: conversation.id,
lastModified: conversation.lastModified,
name: conversation.name,
pinned: conversation.pinned
}}
{depth}
isActive={currentChatId === conversation.id}
isSelected={selectedIds.has(conversation.id)}
{isSelectionMode}
{onDelete}
{onEdit}
{onEnterSelectionMode}
{onRowMouseDown}
{onSelect}
{onSelectionClick}
{onStop}
{onToggleSelect}
/>
</li>
{/each}
</ul>
{/if}
<div class="mt-2 flex min-h-0 flex-1 flex-col gap-4 md:gap-0 whitespace-nowrap {className}">
{#if conversations.length > 0}
<div
class="text-muted-foreground flex h-8 shrink-0 items-center rounded-md px-2 text-xs font-medium"
>
Recent conversations
</div>
{/if}
<div class="min-h-0 flex-1 md:overflow-y-auto">
<ul class="flex w-full min-w-0 flex-col gap-4 md:gap-0">
{#each unpinnedConversations as { conversation, depth } (conversation.id)}
<li class="group/item relative mb-1 p-0">
<SidebarNavigationConversationItem
conversation={{
@@ -133,73 +146,30 @@
/>
</li>
{/each}
{#if unpinnedConversations.length === 0}
<li class="px-2 py-4 text-center">
<p class="mb-4 p-4 text-sm text-muted-foreground">No conversations yet</p>
</li>
{/if}
</ul>
{/if}
<div class="mt-2 flex min-h-0 flex-1 flex-col gap-4 md:gap-0 whitespace-nowrap {className}">
{#if filteredConversations.length > 0}
<div
class="text-muted-foreground flex h-8 shrink-0 items-center rounded-md px-2 text-xs font-medium"
>
Recent conversations
</div>
{/if}
<div class="min-h-0 flex-1 md:overflow-y-auto">
<ul class="flex w-full min-w-0 flex-col gap-4 md:gap-0">
{#each unpinnedConversations as { conversation, depth } (conversation.id)}
<li class="group/item relative mb-1 p-0">
<SidebarNavigationConversationItem
conversation={{
currNode: conversation.currNode,
forkedFromConversationId: conversation.forkedFromConversationId,
id: conversation.id,
lastModified: conversation.lastModified,
name: conversation.name,
pinned: conversation.pinned
}}
{depth}
isActive={currentChatId === conversation.id}
isSelected={selectedIds.has(conversation.id)}
{isSelectionMode}
{onDelete}
{onEdit}
{onEnterSelectionMode}
{onRowMouseDown}
{onSelect}
{onSelectionClick}
{onStop}
{onToggleSelect}
/>
</li>
{/each}
{#if unpinnedConversations.length === 0}
<li class="px-2 py-4 text-center">
<p class="mb-4 p-4 text-sm text-muted-foreground">
{recentEmptyMessage}
</p>
</li>
{/if}
</ul>
</div>
</div>
</div>
{#if isSelectionMode}
<SidebarNavigationSelectionBar
{allVisibleSelected}
class="sticky top-0 z-10 m-2 mt-0"
{onBulkDelete}
{onBulkExport}
{onBulkPinToggle}
onClose={onCloseSelection}
{onSelectAllToggle}
{pinStateIsMixed}
selectedCount={selectedIds.size}
someSelectedPinned={allSelectedArePinned}
{someVisibleSelected}
{visibleCount}
/>
{/if}
{#if isSelectionMode}
<SidebarNavigationSelectionBar
{allVisibleSelected}
class="sticky top-0 z-10 m-2 mt-0"
{onBulkDelete}
{onBulkExport}
{onBulkPinToggle}
onClose={onCloseSelection}
{onSelectAllToggle}
{pinStateIsMixed}
selectedCount={selectedIds.size}
someSelectedPinned={allSelectedArePinned}
{someVisibleSelected}
{visibleCount}
/>
{/if}
</div>
@@ -66,14 +66,13 @@ export { default as DropdownMenuActions } from './DropdownMenuActions.svelte';
/**
* **SidebarNavigation** - Sidebar with actions menu and conversation list
*
* Collapsible sidebar displaying conversation history with search and
* management actions. Integrates with ShadCN sidebar component for
* Collapsible sidebar displaying conversation history and management actions. Integrates with ShadCN sidebar component for
* consistent styling and mobile responsiveness.
*
* **Architecture:**
* - Uses ShadCN Sidebar.* components for structure
* - Fetches conversations from conversationsStore
* - Manages search state and filtered results locally
* - Owns the search dialog (desktop) and routes phones to the search page
* - Handles conversation CRUD operations via conversationsStore
*
* **Navigation:**
@@ -88,7 +87,7 @@ export { default as DropdownMenuActions } from './DropdownMenuActions.svelte';
* - Delete All: Removes all conversations with confirmation
*
* **Features:**
* - Search/filter conversations by title
* - Search dialog (Cmd+K) over chats and sidebar actions
* - Conversation list with message previews (first message truncated)
* - Active conversation highlighting
* - Mobile-responsive collapse/expand via ShadCN sidebar
@@ -96,7 +95,6 @@ export { default as DropdownMenuActions } from './DropdownMenuActions.svelte';
* - Settings button opens DialogChatSettings
*
* **Exported API:**
* - `activateSearchMode()` - Focus search input programmatically
* - `editActiveConversation()` - Open rename dialog for current conversation
*
* @example
@@ -148,17 +146,14 @@ export { default as SidebarNavigationSelectionBar } from './SidebarNavigation/Si
* **SidebarNavigationConversationList** - Grouped conversation list
*
* Pure-presentational list of conversations. Splits items into a Pinned
* section (when not in search mode) and a Recent Conversations / Search
* Results section with the unpinned items. Item selection, edit, delete,
* section and a Recent Conversations section with the unpinned items. Item selection, edit, delete,
* and stop-generation are delegated to the caller via callbacks.
*
* @example
* ```svelte
* <SidebarNavigationConversationList
* {filteredConversations}
* {conversations}
* {currentChatId}
* {isSearchModeActive}
* {searchQuery}
* onSelect={...}
* onEdit={...}
* onDelete={...}
@@ -174,9 +169,8 @@ export { default as SidebarNavigationActions } from './SidebarNavigation/Sidebar
*
* Pure-presentational rendering of the search-mode subtree: "Search results"
* header, the matching items rendered through {@link SidebarNavigationConversationItem},
* and contextual empty-state messages. Used both inline inside
* {@link SidebarNavigationConversationList} (when search mode is active in the
* sidebar) and as the body of the mobile `/search` route.
* and contextual empty-state messages. Used as the body of the mobile `/search`
* route; desktop search goes through {@link DialogSearch}.
*
* The caller is expected to provide an already-filtered list via
* `filteredConversations` and a `searchQuery` for the empty-state messages.
@@ -1,6 +1,10 @@
export const MS_PER_SECOND = 1000;
export const SECONDS_PER_MINUTE = 60;
export const SECONDS_PER_HOUR = 3600;
export const SECONDS_PER_DAY = 86400;
/** Age past which a relative time label falls back to a plain date. */
export const RELATIVE_TIME_MAX_DAYS = 30;
export const SHORT_DURATION_THRESHOLD = 1;
export const MEDIUM_DURATION_THRESHOLD = 10;
+1
View File
@@ -30,6 +30,7 @@ export * from './css-classes.constants';
export * from './formatters.constants';
export * from './headers.constants';
export * from './key-value-pairs.constants';
export * from './keyboard-shortcuts.constants';
export * from './latex-protection.constants';
export * from './literal-html.constants';
export * from './markdown.constants';
@@ -0,0 +1,9 @@
// Key combinations shown in shortcut hints; `KeyboardShortcutInfo` renders 'shift' and 'cmd' as symbols.
export const SHORTCUT_NEW_CHAT = ['shift', 'cmd', 'o'];
export const SHORTCUT_SEARCH = ['cmd', 'k'];
export const SHORTCUT_MODELS = ['shift', 'cmd', 'm'];
export const SHORTCUT_SETTINGS = ['cmd', ','];
export const SHORTCUT_EDIT_CONVERSATION = ['shift', 'cmd', 'e'];
export const SHORTCUT_EXPORT_CONVERSATION = ['shift', 'cmd', 's'];
export const SHORTCUT_DELETE_CONVERSATION = ['shift', 'cmd', 'd'];
+10 -2
View File
@@ -1,4 +1,10 @@
import { MODEL_ICON } from './icons.constants';
import {
SHORTCUT_MODELS,
SHORTCUT_NEW_CHAT,
SHORTCUT_SEARCH,
SHORTCUT_SETTINGS
} from './keyboard-shortcuts.constants';
import { MODELS_ROUTE_ID } from './routes.constants';
import { Search, Settings, SquarePen } from '@lucide/svelte';
import McpLogo from '$lib/components/app/mcp/McpLogo.svelte';
@@ -90,14 +96,15 @@ export const SIDEBAR_ACTIONS_ITEMS: DesktopIconStripItem[] = [
{
action: SidebarAction.NEW_CHAT,
icon: SquarePen,
keys: ['shift', 'cmd', 'o'],
keys: SHORTCUT_NEW_CHAT,
tooltip: 'New chat'
},
{ icon: Search, keys: ['cmd', 'k'], tooltip: 'Search' },
{ action: SidebarAction.SEARCH, icon: Search, keys: SHORTCUT_SEARCH, tooltip: 'Search' },
{
action: SidebarAction.MANAGE_MODELS,
activeRouteId: MODELS_ROUTE_ID,
icon: MODEL_ICON,
keys: SHORTCUT_MODELS,
tooltip: 'Models'
},
{
@@ -108,6 +115,7 @@ export const SIDEBAR_ACTIONS_ITEMS: DesktopIconStripItem[] = [
{
action: SidebarAction.SETTINGS,
icon: Settings,
keys: SHORTCUT_SETTINGS,
tooltip: 'Settings'
}
];
+3
View File
@@ -9,6 +9,7 @@ export enum KeyboardKey {
B_LOWER = 'b',
BRACKET_LEFT = 'BracketLeft',
BRACKET_RIGHT = 'BracketRight',
COMMA = ',',
D_LOWER = 'd',
D_UPPER = 'D',
E_UPPER = 'E',
@@ -16,6 +17,8 @@ export enum KeyboardKey {
ESCAPE = 'Escape',
HOME = 'Home',
K_LOWER = 'k',
M_LOWER = 'm',
M_UPPER = 'M',
O_LOWER = 'o',
O_UPPER = 'O',
PAGE_UP = 'PageUp',
+1
View File
@@ -26,6 +26,7 @@ export enum SidebarAction {
MANAGE_MODELS = 'manage-models',
MCP = 'mcp',
NEW_CHAT = 'new-chat',
SEARCH = 'search',
SETTINGS = 'settings'
}
@@ -4,14 +4,15 @@ import { KeyboardKey } from '$lib/enums';
import { conversationsStore, settingsStore, tabsStore } from '$lib/stores';
interface KeyboardShortcutsCallbacks {
activateSearchMode?: () => void;
editActiveConversation?: () => void;
onSearchActivated?: () => void;
deleteActiveConversation?: () => void;
navigateToPrevConversation?: () => void;
navigateToNextConversation?: () => void;
navigateToPrevTab?: () => void;
navigateToNextTab?: () => void;
openModelsManager?: () => void;
openSearch?: () => void;
openSettings?: () => void;
toggleSidebar?: () => void;
}
@@ -21,8 +22,12 @@ export function useKeyboardShortcuts(callbacks: KeyboardShortcutsCallbacks) {
if (isCmdOrCtrl && event.key === KeyboardKey.K_LOWER) {
event.preventDefault();
callbacks.activateSearchMode?.();
callbacks.onSearchActivated?.();
callbacks.openSearch?.();
}
if (isCmdOrCtrl && event.key === KeyboardKey.COMMA) {
event.preventDefault();
callbacks.openSettings?.();
}
if (isCmdOrCtrl && event.key === KeyboardKey.B_LOWER) {
@@ -40,6 +45,15 @@ export function useKeyboardShortcuts(callbacks: KeyboardShortcutsCallbacks) {
void conversationsStore.openNewChat();
}
if (
isCmdOrCtrl &&
event.shiftKey &&
(event.key === KeyboardKey.M_LOWER || event.key === KeyboardKey.M_UPPER)
) {
event.preventDefault();
callbacks.openModelsManager?.();
}
if (event.shiftKey && isCmdOrCtrl && event.key === KeyboardKey.E_UPPER) {
event.preventDefault();
callbacks.editActiveConversation?.();
+30
View File
@@ -1,6 +1,8 @@
import {
MEDIUM_DURATION_THRESHOLD,
MS_PER_SECOND,
RELATIVE_TIME_MAX_DAYS,
SECONDS_PER_DAY,
SECONDS_PER_HOUR,
SECONDS_PER_MINUTE,
SHORT_DURATION_THRESHOLD
@@ -102,6 +104,34 @@ export function formatJsonPretty(jsonString: string): string {
}
}
/**
* Formats a past timestamp as a coarse relative label.
* Examples: "just now", "37 minutes ago", "1 hour ago", "3 days ago"
*
* @param timestamp - Epoch milliseconds in the past
* @returns Relative time string
*/
export function formatRelativeTime(timestamp: number): string {
const elapsedSeconds = (Date.now() - timestamp) / MS_PER_SECOND;
const plural = (value: number, unit: string) => `${value} ${unit}${value === 1 ? '' : 's'} ago`;
if (elapsedSeconds < SECONDS_PER_MINUTE) return 'just now';
if (elapsedSeconds < SECONDS_PER_HOUR) {
return plural(Math.floor(elapsedSeconds / SECONDS_PER_MINUTE), 'minute');
}
if (elapsedSeconds < SECONDS_PER_DAY) {
return plural(Math.floor(elapsedSeconds / SECONDS_PER_HOUR), 'hour');
}
if (elapsedSeconds < RELATIVE_TIME_MAX_DAYS * SECONDS_PER_DAY) {
return plural(Math.floor(elapsedSeconds / SECONDS_PER_DAY), 'day');
}
return new Date(timestamp).toLocaleDateString();
}
/**
* Format time as HH:MM:SS in 24-hour format
*
+1
View File
@@ -99,6 +99,7 @@ export {
formatJsonPretty,
formatTime,
formatPerformanceTime,
formatRelativeTime,
formatAttachmentText
} from './formatters';
+2 -16
View File
@@ -13,7 +13,6 @@
HEADERS,
MODELS_ROUTE_ID,
NEW_CHAT_TAB_ID,
ROUTES,
SETTINGS_KEYS,
TOOLTIP_DELAY_DURATION
} from '$lib/constants';
@@ -47,12 +46,7 @@
let innerHeight = $state<number | undefined>();
let innerWidth = $state(browser ? window.innerWidth : 0);
let chatSidebar:
| {
activateSearchMode?: () => void;
editActiveConversation?: () => void;
}
| undefined = $state();
let chatSidebar: { editActiveConversation?: () => void } | undefined = $state();
let showBuildVersion = $derived(
settingsStore.config[SETTINGS_KEYS.SHOW_BUILD_VERSION] as boolean
@@ -308,15 +302,7 @@
<Tooltip.Provider delayDuration={TOOLTIP_DELAY_DURATION}>
<div class="flex flex-col md:flex-row">
<SidebarNavigation
onSearchClick={() => {
if (deviceStore.isMobile) {
goto(ROUTES.SEARCH);
} else if (chatSidebar?.activateSearchMode) {
chatSidebar.activateSearchMode();
}
}}
/>
<SidebarNavigation />
<!-- min-w-0 lets the chat column shrink below its content width, so wide
code blocks and tables scroll inside their own containers instead of
@@ -1,6 +1,7 @@
<script lang="ts" module>
import { defineMeta } from '@storybook/addon-svelte-csf';
import SidebarNavigation from '$lib/components/app/navigation/SidebarNavigation/SidebarNavigation.svelte';
import { expect } from 'storybook/test';
import { waitFor } from 'storybook/test';
import { screen } from 'storybook/test';
@@ -85,7 +86,9 @@
await userEvent.click(logoTrigger);
const searchTrigger = screen.getByText('Search');
userEvent.click(searchTrigger);
await userEvent.click(searchTrigger);
await expect(await screen.findByRole('combobox')).toHaveFocus();
}}
>
<div class="flex-column h-screen w-72 bg-background">
+42 -2
View File
@@ -1,5 +1,12 @@
import { formatContextLength, formatParameters } from '$lib/utils/formatters';
import { describe, expect, it } from 'vitest';
import {
MS_PER_SECOND,
RELATIVE_TIME_MAX_DAYS,
SECONDS_PER_DAY,
SECONDS_PER_HOUR,
SECONDS_PER_MINUTE
} from '$lib/constants';
import { formatContextLength, formatParameters, formatRelativeTime } from '$lib/utils/formatters';
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
describe('formatContextLength', () => {
it('shows a dash when no value is known', () => {
@@ -22,3 +29,36 @@ describe('formatParameters', () => {
expect(formatParameters(512)).toBe('512');
});
});
describe('formatRelativeTime', () => {
const NOW = new Date('2026-06-15T12:00:00Z').getTime();
const ago = (seconds: number) => NOW - seconds * MS_PER_SECOND;
beforeEach(() => {
vi.useFakeTimers();
vi.setSystemTime(NOW);
});
afterEach(() => {
vi.useRealTimers();
});
it('says just now under a minute', () => {
expect(formatRelativeTime(ago(SECONDS_PER_MINUTE - 1))).toBe('just now');
});
it('counts minutes, hours and days with singular and plural units', () => {
expect(formatRelativeTime(ago(SECONDS_PER_MINUTE))).toBe('1 minute ago');
expect(formatRelativeTime(ago(37 * SECONDS_PER_MINUTE))).toBe('37 minutes ago');
expect(formatRelativeTime(ago(SECONDS_PER_HOUR))).toBe('1 hour ago');
expect(formatRelativeTime(ago(5 * SECONDS_PER_HOUR))).toBe('5 hours ago');
expect(formatRelativeTime(ago(SECONDS_PER_DAY))).toBe('1 day ago');
expect(formatRelativeTime(ago(3 * SECONDS_PER_DAY))).toBe('3 days ago');
});
it('falls back to a date once the age reaches the day limit', () => {
const timestamp = ago(RELATIVE_TIME_MAX_DAYS * SECONDS_PER_DAY);
expect(formatRelativeTime(timestamp)).toBe(new Date(timestamp).toLocaleDateString());
});
});