feat(frontend): add Spotlight-style command palette with recent tracking

- Add CommandPalette component with keyboard navigation (arrows, Enter, Shift+Enter, Esc)
- Add useCommandPaletteStore Zustand store with localStorage-persisted recently viewed
- Show two distinct sections: Library results and TMDB Results (no duplicates)
- Exclude library entries from TMDB Results section by TMDB ID index
- Add "View all" links: Library section → /library, TMDB section → /search
- Persist non-library TMDB entries in localStorage for recently viewed support
- Register global Ctrl+P / Cmd+P / slash shortcuts in AppLayout
- Track entry visits in EntryDetailsPage for recently viewed
- Track TMDB preview visits in TmdbPreviewPage for recently viewed
- Updated related docs files

Co-authored-by: Copilot <copilot@github.com>
This commit is contained in:
Mohammed AbadandCopilot committed 2026-05-04 08:33:27 +01:00
1 parent 4303b33677
commit 3448142242
9 files changed
+710 -3

No files matched your search

@@ -0,0 +1,494 @@
import { useState, useEffect, useRef, useCallback, useMemo } from 'react';
import { useNavigate } from 'react-router-dom';
import { useQuery } from '@tanstack/react-query';
import {
Search,
Film,
Tv,
Library,
Star,
BarChart3,
Settings,
BookOpen,
Calendar,
Users,
ArrowUp,
ArrowDown,
CornerDownLeft,
ArrowRight,
} from 'lucide-react';
import { tmdbApi } from '@/api/tmdb';
import { useLibraryStore } from '@/stores/useLibraryStore';
import { useCommandPaletteStore } from '@/stores/useCommandPaletteStore';
import { useCreateEntry } from '@/hooks/useEntries';
import { getTmdbImageUrl } from '@/lib/api';
import { cn } from '@/lib/utils';
import type { TmdbEntry } from '@/types';
interface CommandItem {
id: string;
type: 'command' | 'library' | 'tmdb';
title: string;
subtitle?: string;
year?: string;
mediaType?: 'movie' | 'tv';
posterPath?: string | null;
icon?: React.ReactNode;
inLibrary?: boolean;
libraryId?: number;
tmdbId?: number;
rating?: number | null;
}
const NAVIGATION_COMMANDS: CommandItem[] = [
{ id: 'cmd-library', type: 'command', title: 'Go to Library', icon: <Library className="h-4 w-4" /> },
{ id: 'cmd-watchlist', type: 'command', title: 'Go to Watchlist', icon: <BookOpen className="h-4 w-4" /> },
{ id: 'cmd-stats', type: 'command', title: 'Go to Statistics', icon: <BarChart3 className="h-4 w-4" /> },
{ id: 'cmd-calendar', type: 'command', title: 'Go to Calendar', icon: <Calendar className="h-4 w-4" /> },
{ id: 'cmd-people', type: 'command', title: 'Go to People', icon: <Users className="h-4 w-4" /> },
{ id: 'cmd-settings', type: 'command', title: 'Go to Settings', icon: <Settings className="h-4 w-4" /> },
{ id: 'cmd-favorites', type: 'command', title: 'Go to Favorites', icon: <Star className="h-4 w-4" /> },
];
const COMMAND_ROUTES: Record<string, string> = {
'cmd-library': '/library',
'cmd-watchlist': '/watchlist',
'cmd-stats': '/dashboard',
'cmd-calendar': '/calendar',
'cmd-people': '/people',
'cmd-settings': '/settings',
'cmd-favorites': '/library?filter=favorites',
};
export function CommandPalette() {
const { isOpen, close, recentlyViewed } = useCommandPaletteStore();
const navigate = useNavigate();
const createEntry = useCreateEntry();
const libraryEntries = useLibraryStore((s) => s.entries);
const inputRef = useRef<HTMLInputElement>(null);
const listRef = useRef<HTMLDivElement>(null);
const [query, setQuery] = useState('');
const [debouncedQuery, setDebouncedQuery] = useState('');
const [selectedIndex, setSelectedIndex] = useState(0);
// Debounce search query
useEffect(() => {
const timer = setTimeout(() => setDebouncedQuery(query), 250);
return () => clearTimeout(timer);
}, [query]);
// Focus input when opened
useEffect(() => {
if (isOpen) {
setQuery('');
setDebouncedQuery('');
setSelectedIndex(0);
setTimeout(() => inputRef.current?.focus(), 50);
}
}, [isOpen]);
// TMDB search
const { data: tmdbResults, isFetching: tmdbLoading } = useQuery({
queryKey: ['command-palette', 'tmdb', debouncedQuery],
queryFn: () => tmdbApi.search(debouncedQuery, 1),
enabled: debouncedQuery.length > 1,
staleTime: 60 * 1000,
});
// Build library TMDB ID index for fast lookups
const libraryTmdbIndex = useMemo(() => {
const index = new Map<number, { id: number; title: string; is_tvseries: boolean; poster_path: string | null; rating: number | null }>();
libraryEntries.forEach((entry) => {
if (entry.entryIds?.tmdb_id) {
index.set(entry.entryIds.tmdb_id, {
id: entry.id,
title: entry.title,
is_tvseries: entry.is_tvseries,
poster_path: entry.poster_path,
rating: entry.entryRatings?.user_rating ?? null,
});
}
});
return index;
}, [libraryEntries]);
// Local library search
const localResults = useMemo((): CommandItem[] => {
if (!query.trim()) return [];
const lower = query.toLowerCase();
const results: CommandItem[] = [];
libraryEntries.forEach((entry) => {
if (entry.title.toLowerCase().includes(lower)) {
results.push({
id: `lib-${entry.id}`,
type: 'library',
title: entry.title,
year: entry.release_date?.slice(0, 4),
mediaType: entry.is_tvseries ? 'tv' : 'movie',
posterPath: entry.poster_path,
inLibrary: true,
libraryId: entry.id,
tmdbId: entry.entryIds?.tmdb_id ?? undefined,
rating: entry.entryRatings?.user_rating ?? null,
});
}
});
return results.slice(0, 5);
}, [query, libraryEntries]);
// TMDB results — fully exclude entries already in library
const tmdbItems = useMemo((): CommandItem[] => {
if (!tmdbResults?.results) return [];
return tmdbResults.results
.filter((r: TmdbEntry) => !libraryTmdbIndex.has(r.id))
.slice(0, 8)
.map((r: TmdbEntry) => {
const mediaType = r.media_type === 'tv' || r.name ? 'tv' : 'movie';
const title = r.title || r.name || 'Unknown';
const year = (r.release_date || r.first_air_date)?.slice(0, 4);
return {
id: `tmdb-${r.id}`,
type: 'tmdb' as const,
title,
year,
mediaType,
posterPath: r.poster_path,
inLibrary: false,
tmdbId: r.id,
rating: r.vote_average ? Math.round(r.vote_average * 10) / 10 : null,
};
});
}, [tmdbResults, libraryTmdbIndex]);
// Filtered commands
const filteredCommands = useMemo((): CommandItem[] => {
if (!query.trim()) return NAVIGATION_COMMANDS;
const lower = query.toLowerCase();
return NAVIGATION_COMMANDS.filter((c) => c.title.toLowerCase().includes(lower));
}, [query]);
// Recently viewed items (shown when no query)
const recentItems = useMemo((): CommandItem[] => {
if (query.trim()) return [];
return recentlyViewed.map((r) => ({
id: `recent-${r.id}`,
type: (r.libraryId ? 'library' : 'tmdb') as 'library' | 'tmdb',
title: r.title,
mediaType: r.type,
posterPath: r.poster_path,
inLibrary: !!r.libraryId,
libraryId: r.libraryId,
tmdbId: r.tmdbId,
}));
}, [query, recentlyViewed]);
// All items combined
const allItems = useMemo(() => {
return [...filteredCommands, ...localResults, ...tmdbItems, ...(query ? [] : recentItems)];
}, [filteredCommands, localResults, tmdbItems, recentItems, query]);
// Keep selected index in bounds
useEffect(() => {
if (selectedIndex >= allItems.length) {
setSelectedIndex(Math.max(0, allItems.length - 1));
}
}, [allItems.length, selectedIndex]);
// Scroll selected item into view
useEffect(() => {
const el = listRef.current?.querySelector(`[data-index="${selectedIndex}"]`);
el?.scrollIntoView({ block: 'nearest' });
}, [selectedIndex]);
const handleSelect = useCallback(
(item: CommandItem, quickAdd = false) => {
if (item.type === 'command') {
const route = COMMAND_ROUTES[item.id];
if (route) navigate(route);
close();
return;
}
if (item.inLibrary && item.libraryId) {
navigate(`/entry/${item.libraryId}`);
close();
return;
}
if (quickAdd && item.tmdbId && item.mediaType) {
createEntry.mutate(
{ tmdb_id: item.tmdbId, is_tvserie: item.mediaType === 'tv' },
{
onSuccess: (entry) => {
navigate(`/entry/${entry.id}`);
close();
},
}
);
return;
}
// Open TMDB preview
if (item.tmdbId && item.mediaType) {
navigate(`/entry/tmdb/${item.mediaType}/${item.tmdbId}`);
close();
}
},
[navigate, close, createEntry]
);
const handleKeyDown = useCallback(
(e: React.KeyboardEvent) => {
switch (e.key) {
case 'ArrowDown':
e.preventDefault();
setSelectedIndex((i) => Math.min(i + 1, allItems.length - 1));
break;
case 'ArrowUp':
e.preventDefault();
setSelectedIndex((i) => Math.max(i - 1, 0));
break;
case 'Enter': {
e.preventDefault();
const item = allItems[selectedIndex];
if (item) handleSelect(item, e.shiftKey);
break;
}
case 'Escape':
e.preventDefault();
close();
break;
}
},
[allItems, selectedIndex, handleSelect, close]
);
if (!isOpen) return null;
return (
<div className="fixed inset-0 z-50 flex items-start justify-center pt-[15vh]" onClick={close}>
{/* Backdrop */}
<div className="fixed inset-0 bg-black/50 backdrop-blur-sm" />
{/* Palette */}
<div
className="relative z-50 w-full max-w-xl animate-in fade-in-0 zoom-in-95 duration-150 rounded-xl border border-border bg-popover shadow-2xl"
onClick={(e) => e.stopPropagation()}
onKeyDown={handleKeyDown}
>
{/* Search input */}
<div className="flex items-center gap-3 border-b border-border px-4 py-3">
<Search className="h-5 w-5 shrink-0 text-muted-foreground" />
<input
ref={inputRef}
type="text"
value={query}
onChange={(e) => {
setQuery(e.target.value);
setSelectedIndex(0);
}}
placeholder="Search movies, shows, or type a command..."
className="flex-1 bg-transparent text-base outline-none placeholder:text-muted-foreground"
/>
{tmdbLoading && (
<div className="h-4 w-4 animate-spin rounded-full border-2 border-muted-foreground border-t-transparent" />
)}
</div>
{/* Results list */}
<div ref={listRef} className="max-h-[50vh] overflow-y-auto p-2">
{/* Commands section */}
{filteredCommands.length > 0 && (
<div>
<div className="px-2 py-1.5 text-xs font-medium text-muted-foreground">
{query ? 'Commands' : 'Quick Actions'}
</div>
{filteredCommands.map((item, i) => {
const idx = i;
return (
<ResultRow
key={item.id}
item={item}
isSelected={selectedIndex === idx}
dataIndex={idx}
onClick={() => handleSelect(item)}
/>
);
})}
</div>
)}
{/* Recently viewed (no query) */}
{!query && recentItems.length > 0 && (
<div>
<div className="px-2 py-1.5 text-xs font-medium text-muted-foreground">
Recently Viewed
</div>
{recentItems.map((item, i) => {
const idx = filteredCommands.length + i;
return (
<ResultRow
key={item.id}
item={item}
isSelected={selectedIndex === idx}
dataIndex={idx}
onClick={() => handleSelect(item)}
/>
);
})}
</div>
)}
{/* Library results */}
{localResults.length > 0 && (
<div>
<div className="flex items-center justify-between px-2 py-1.5">
<span className="text-xs font-medium text-muted-foreground">Library</span>
<button
className="flex items-center gap-1 text-xs text-muted-foreground hover:text-foreground transition-colors"
onClick={() => {
navigate(`/library?search=${encodeURIComponent(query)}`);
close();
}}
>
View all <ArrowRight className="h-3 w-3" />
</button>
</div>
{localResults.map((item, i) => {
const idx = filteredCommands.length + i;
return (
<ResultRow
key={item.id}
item={item}
isSelected={selectedIndex === idx}
dataIndex={idx}
onClick={() => handleSelect(item)}
/>
);
})}
</div>
)}
{/* TMDB results */}
{tmdbItems.length > 0 && (
<div>
<div className="flex items-center justify-between px-2 py-1.5">
<span className="text-xs font-medium text-muted-foreground">TMDB Results</span>
<button
className="flex items-center gap-1 text-xs text-muted-foreground hover:text-foreground transition-colors"
onClick={() => {
navigate(`/search?q=${encodeURIComponent(query)}`);
close();
}}
>
View all <ArrowRight className="h-3 w-3" />
</button>
</div>
{tmdbItems.map((item, i) => {
const idx = filteredCommands.length + localResults.length + i;
return (
<ResultRow
key={item.id}
item={item}
isSelected={selectedIndex === idx}
dataIndex={idx}
onClick={() => handleSelect(item)}
/>
);
})}
</div>
)}
{/* Empty state */}
{query && allItems.length === 0 && !tmdbLoading && (
<div className="px-4 py-8 text-center text-sm text-muted-foreground">
No results found for "{query}"
</div>
)}
</div>
{/* Bottom hint bar */}
<div className="flex items-center gap-4 border-t border-border px-4 py-2 text-xs text-muted-foreground">
<span className="flex items-center gap-1">
<CornerDownLeft className="h-3 w-3" /> Open
</span>
<span className="flex items-center gap-1">
<kbd className="rounded border border-border px-1 font-mono text-[10px]">⇧</kbd>
<CornerDownLeft className="h-3 w-3" /> Quick Add
</span>
<span className="flex items-center gap-1">
<ArrowUp className="h-3 w-3" />
<ArrowDown className="h-3 w-3" /> Navigate
</span>
<span className="ml-auto">
<kbd className="rounded border border-border px-1 font-mono text-[10px]">Esc</kbd> Close
</span>
</div>
</div>
</div>
);
}
function ResultRow({
item,
isSelected,
dataIndex,
onClick,
}: {
item: CommandItem;
isSelected: boolean;
dataIndex: number;
onClick: () => void;
}) {
return (
<div
data-index={dataIndex}
className={cn(
'flex cursor-pointer items-center gap-3 rounded-lg px-2 py-2 transition-colors',
isSelected ? 'bg-accent text-accent-foreground' : 'hover:bg-muted'
)}
onClick={onClick}
>
{/* Poster or icon */}
{item.type === 'command' ? (
<div className="flex h-9 w-9 shrink-0 items-center justify-center rounded-md bg-muted">
{item.icon}
</div>
) : item.posterPath ? (
<img
src={getTmdbImageUrl(item.posterPath, 'w92')}
alt=""
className="h-12 w-8 shrink-0 rounded object-cover"
/>
) : (
<div className="flex h-12 w-8 shrink-0 items-center justify-center rounded bg-muted">
{item.mediaType === 'tv' ? <Tv className="h-4 w-4 text-muted-foreground" /> : <Film className="h-4 w-4 text-muted-foreground" />}
</div>
)}
{/* Content */}
<div className="min-w-0 flex-1">
<div className="flex items-center gap-2">
<span className="truncate font-medium">{item.title}</span>
</div>
{(item.year || item.mediaType) && (
<div className="flex items-center gap-2 text-xs text-muted-foreground">
{item.year && <span>{item.year}</span>}
{item.mediaType && (
<span className="capitalize">{item.mediaType === 'tv' ? 'TV Series' : 'Movie'}</span>
)}
{item.rating != null && item.type !== 'command' && (
<span className="flex items-center gap-0.5">
<Star className="h-3 w-3 fill-yellow-500 text-yellow-500" />
{item.rating}
</span>
)}
</div>
)}
</div>
</div>
);
}
@@ -10,6 +10,8 @@ import {
} from '@/components/ui/sheet';
import { Sidebar, MobileSidebarContent } from './Sidebar';
import { TitleBar } from './TitleBar';
import { CommandPalette } from '@/components/CommandPalette';
import { useCommandPaletteStore } from '@/stores/useCommandPaletteStore';
const isElectron = import.meta.env.VITE_ELECTRON === 'true' || !!window.electron?.isElectron;
@@ -17,14 +19,41 @@ export function AppLayout() {
const [mobileOpen, setMobileOpen] = useState(false);
const mainRef = useRef<HTMLElement>(null);
const { pathname } = useLocation();
const openPalette = useCommandPaletteStore((s) => s.open);
useEffect(() => {
mainRef.current?.scrollTo(0, 0);
}, [pathname]);
// Global keyboard shortcut: Ctrl+P or "/" when not in input
useEffect(() => {
function handleKeyDown(e: KeyboardEvent) {
if ((e.ctrlKey || e.metaKey) && e.key === 'p') {
e.preventDefault();
openPalette();
return;
}
if (
e.key === '/' &&
!e.ctrlKey &&
!e.metaKey &&
!e.altKey &&
!(e.target instanceof HTMLInputElement) &&
!(e.target instanceof HTMLTextAreaElement) &&
!(e.target as HTMLElement)?.isContentEditable
) {
e.preventDefault();
openPalette();
}
}
document.addEventListener('keydown', handleKeyDown);
return () => document.removeEventListener('keydown', handleKeyDown);
}, [openPalette]);
return (
<div className="flex h-screen flex-col overflow-hidden">
{isElectron && <TitleBar />}
<CommandPalette />
<div className="flex flex-1 overflow-hidden">
{/* Desktop sidebar */}