Jan is an open source alternative to ChatGPT that runs 100% offline on your computer.
feat: search dialog
Faisal Amire51f093768b5
diff --git a/web-app/src/constants/localStorage.ts b/web-app/src/constants/localStorage.tsindex a752589ea..aff9f1402 100644--- a/web-app/src/constants/localStorage.ts+++ b/web-app/src/constants/localStorage.ts@@ -23,6 +23,7 @@ export const localStorageKey = {setupCompleted: 'setup-completed',threadManagement: 'thread-management',modelSupportCache: 'jan_model_support_cache',+ recentSearches: 'recent-searches',}export const CACHE_EXPIRY_MS = 1000 * 60 * 60 * 24diff --git a/web-app/src/containers/LeftPanel.tsx b/web-app/src/containers/LeftPanel.tsxindex a7e7d0de3..8af04c421 100644--- a/web-app/src/containers/LeftPanel.tsx+++ b/web-app/src/containers/LeftPanel.tsx@@ -10,7 +10,6 @@ import {IconFolderPlus,IconMessage,IconApps,- IconX,IconSearch,IconFolder,IconPencil,@@ -37,7 +36,7 @@ import { DownloadManagement } from '@/containers/DownloadManegement'import { useSmallScreen } from '@/hooks/useMediaQuery'import { useClickOutside } from '@/hooks/useClickOutside'-import { DeleteAllThreadsDialog } from '@/containers/dialogs'+import { DeleteAllThreadsDialog, SearchDialog } from '@/containers/dialogs'import AddProjectDialog from '@/containers/dialogs/AddProjectDialog'import { DeleteProjectDialog } from '@/containers/dialogs/DeleteProjectDialog'@@ -77,15 +76,13 @@ const LeftPanel = () => {const setLeftPanel = useLeftPanel((state) => state.setLeftPanel)const { t } = useTranslation()const navigate = useNavigate()- const [searchTerm, setSearchTerm] = useState('')const projectsEnabled = PlatformFeatures[PlatformFeature.PROJECTS]+ const [searchDialogOpen, setSearchDialogOpen] = useState(false)const isSmallScreen = useSmallScreen()const prevScreenSizeRef = useRef<boolean | null>(null)const isInitialMountRef = useRef(true)const panelRef = useRef<HTMLElement>(null)- const searchContainerRef = useRef<HTMLDivElement>(null)- const searchContainerMacRef = useRef<HTMLDivElement>(null)// Determine if we're in a resizable context (large screen with panel open)const isResizableContext = !isSmallScreen && open@@ -98,11 +95,7 @@ const LeftPanel = () => {}},null,- [- panelRef.current,- searchContainerRef.current,- searchContainerMacRef.current,- ]+ [panelRef.current])// Auto-collapse panel only when window is resized@@ -168,26 +161,19 @@ const LeftPanel = () => {null)- const filteredThreads = useMemo(() => {- return getFilteredThreads(searchTerm)+ const allThreads = useMemo(() => {+ return getFilteredThreads('')// eslint-disable-next-line react-hooks/exhaustive-deps- }, [getFilteredThreads, searchTerm, threads])+ }, [getFilteredThreads, threads])- const filteredProjects = useMemo(() => {- if (!searchTerm) return folders- return folders.filter((folder) =>- folder.name.toLowerCase().includes(searchTerm.toLowerCase())- )- }, [folders, searchTerm])-- // Memoize categorized threads based on filteredThreads+ // Memoize categorized threads based on allThreadsconst favoritedThreads = useMemo(() => {- return filteredThreads.filter((t) => t.isFavorite)- }, [filteredThreads])+ return allThreads.filter((t: Thread) => t.isFavorite)+ }, [allThreads])const unFavoritedThreads = useMemo(() => {- return filteredThreads.filter((t) => !t.isFavorite && !t.metadata?.project)- }, [filteredThreads])+ return allThreads.filter((t: Thread) => !t.isFavorite && !t.metadata?.project)+ }, [allThreads])// Project handlersconst handleProjectDelete = (id: string) => {@@ -234,16 +220,7 @@ const LeftPanel = () => {{isSmallScreen && open && !IS_IOS && !IS_ANDROID && (<divclassName="fixed inset-0 bg-black/50 backdrop-blur z-30"- onClick={(e) => {- // Don't close if clicking on search container or if currently searching- if (- searchContainerRef.current?.contains(e.target as Node) ||- searchContainerMacRef.current?.contains(e.target as Node)- ) {- return- }- setLeftPanel(false)- }}+ onClick={() => setLeftPanel(false)}/>)}<aside@@ -279,72 +256,20 @@ const LeftPanel = () => {<IconLayoutSidebar size={18} className="text-left-panel-fg" /></div></button>- {!IS_MACOS && (- <div- ref={searchContainerRef}- className={cn(- 'relative top-1.5 mb-4 mt-1 z-50',- isResizableContext- ? 'mx-2 w-[calc(100%-48px)]'- : 'mx-1 w-[calc(100%-32px)]'- )}- data-ignore-outside-clicks- >- <IconSearch className="absolute size-4 top-1/2 left-2 -translate-y-1/2 text-left-panel-fg/50" />- <input- type="text"- placeholder={t('common:search')}- className="w-full pl-7 pr-8 py-1 bg-left-panel-fg/10 rounded-sm text-left-panel-fg focus:outline-none focus:ring-1 focus:ring-left-panel-fg/10"- value={searchTerm}- onChange={(e) => setSearchTerm(e.target.value)}- />- {searchTerm && (- <button- className="absolute right-2 top-1/2 -translate-y-1/2 text-left-panel-fg/70 hover:text-left-panel-fg"- onClick={(e) => {- e.preventDefault()- e.stopPropagation() // prevent bubbling- setSearchTerm('')- }}- >- <IconX size={14} />- </button>- )}- </div>- )}</div><div className="flex flex-col gap-y-1 overflow-hidden mt-0 !h-[calc(100%-42px)]"><div className="space-y-1 py-1">- {IS_MACOS && (- <div- ref={searchContainerMacRef}- className={cn('relative mb-2 mt-1 mx-1')}- data-ignore-outside-clicks- >- <IconSearch className="absolute size-4 top-1/2 left-2 -translate-y-1/2 text-left-panel-fg/50" />- <input- type="text"- placeholder={t('common:search')}- className="w-full pl-7 pr-8 py-1 bg-left-panel-fg/10 rounded-sm text-left-panel-fg focus:outline-none focus:ring-1 focus:ring-left-panel-fg/10"- value={searchTerm}- onChange={(e) => setSearchTerm(e.target.value)}- />- {searchTerm && (- <button- data-ignore-outside-clicks- className="absolute right-2 top-1/2 -translate-y-1/2 text-left-panel-fg/70 hover:text-left-panel-fg"- onClick={(e) => {- e.preventDefault()- e.stopPropagation() // prevent bubbling- setSearchTerm('')- }}- >- <IconX size={14} />- </button>- )}- </div>- )}+ {/* Search button */}+ <button+ onClick={() => setSearchDialogOpen(true)}+ className="flex items-center gap-1.5 cursor-pointer hover:bg-left-panel-fg/10 py-1 px-1 rounded w-full"+ >+ <IconSearch size={18} className="text-left-panel-fg/70" />+ <span className="font-medium text-left-panel-fg/90">+ {t('common:search')}+ </span>+ </button>{mainMenus.map((menu) => {if (!menu.isEnabled) {@@ -385,7 +310,7 @@ const LeftPanel = () => {</div>{projectsEnabled &&- filteredProjects.length > 0 &&+ folders.length > 0 &&!(IS_IOS || IS_ANDROID) && (<div className="space-y-1 py-1"><div className="flex items-center justify-between mb-2">@@ -394,7 +319,7 @@ const LeftPanel = () => {</span></div><div className="flex flex-col max-h-[140px] overflow-y-scroll">- {filteredProjects+ {folders.slice().sort((a, b) => b.updated_at - a.updated_at).map((folder) => {@@ -568,26 +493,8 @@ const LeftPanel = () => {</div>)}- {filteredThreads.length === 0 && searchTerm.length > 0 && (- <div className="px-1 mt-2">- <span className="block text-xs text-left-panel-fg/50 px-1 font-semibold mb-2">- {t('common:recents')}- </span>-- <div className="flex items-center gap-1 text-left-panel-fg/80">- <IconSearch size={18} />- <h6 className="font-medium text-base">- {t('common:noResultsFound')}- </h6>- </div>- <p className="text-left-panel-fg/60 mt-1 text-xs leading-relaxed">- {t('common:noResultsFoundDesc')}- </p>- </div>- )}-{/* Show "No threads yet" when there are no threads at all OR when all threads are in projects */}- {(Object.keys(threads).length === 0 || (Object.keys(threads).length > 0 && unFavoritedThreads.length === 0 && favoritedThreads.length === 0)) && !searchTerm && (+ {(Object.keys(threads).length === 0 || (Object.keys(threads).length > 0 && unFavoritedThreads.length === 0 && favoritedThreads.length === 0)) && (<><div className="px-1 mt-2"><div className="flex items-center gap-1 text-left-panel-fg/80">@@ -675,6 +582,9 @@ const LeftPanel = () => {/></>)}++ {/* Search Dialog */}+ <SearchDialog open={searchDialogOpen} onOpenChange={setSearchDialogOpen} /></>)}diff --git a/web-app/src/containers/__tests__/LeftPanel.test.tsx b/web-app/src/containers/__tests__/LeftPanel.test.tsxindex 069514a3b..09d9c5fba 100644--- a/web-app/src/containers/__tests__/LeftPanel.test.tsx+++ b/web-app/src/containers/__tests__/LeftPanel.test.tsx@@ -129,6 +129,7 @@ vi.mock('@/containers/auth/UserProfileMenu', () => ({// Mock the dialogsvi.mock('@/containers/dialogs', () => ({DeleteAllThreadsDialog: () => <div data-testid="delete-all-threads-dialog">Dialog</div>,+ SearchDialog: ({ open }: { open: boolean }) => open ? <div data-testid="search-dialog">SearchDialog</div> : null,}))// Mock the store@@ -175,11 +176,11 @@ describe('LeftPanel', () => {toggle: vi.fn(),close: vi.fn(),})-+render(<LeftPanel />)-+// Check that the panel is rendered (it should contain some basic elements)- expect(screen.getByPlaceholderText('common:search')).toBeDefined()+ expect(screen.getByText('common:search')).toBeDefined()})it('should hide panel when closed', () => {@@ -214,19 +215,18 @@ describe('LeftPanel', () => {// Note: assistants and hub may be filtered by platform features})- it('should render search input', () => {+ it('should render search button', () => {vi.mocked(useLeftPanel).mockReturnValue({open: true,setLeftPanel: vi.fn(),toggle: vi.fn(),close: vi.fn(),})-+render(<LeftPanel />)-- const searchInput = screen.getByPlaceholderText('common:search')- expect(searchInput).toBeDefined()- expect(searchInput).toHaveAttribute('type', 'text')++ const searchButton = screen.getByText('common:search')+ expect(searchButton).toBeDefined()})it('should render download management component', () => {@@ -249,13 +249,13 @@ describe('LeftPanel', () => {toggle: vi.fn(),close: vi.fn(),})-+render(<LeftPanel />)-+// Check that basic structure exists- const searchInput = screen.getByPlaceholderText('common:search')- expect(searchInput).toBeDefined()-+ const searchButton = screen.getByText('common:search')+ expect(searchButton).toBeDefined()+const downloadComponent = screen.getByTestId('download-management')expect(downloadComponent).toBeDefined()})diff --git a/web-app/src/containers/dialogs/SearchDialog.tsx b/web-app/src/containers/dialogs/SearchDialog.tsxnew file mode 100644index 000000000..74d601a8c--- /dev/null+++ b/web-app/src/containers/dialogs/SearchDialog.tsx@@ -0,0 +1,361 @@+import { useEffect, useState, useMemo, useRef } from 'react'+import { useNavigate } from '@tanstack/react-router'+import { route } from '@/constants/routes'+import {+ Dialog,+ DialogContent,+ DialogTitle,+} from '@/components/ui/dialog'+import {+ IconSearch,+ IconMessage,+ IconHistory,+ IconCirclePlus,+ IconFolder,+} from '@tabler/icons-react'+import { useThreads } from '@/hooks/useThreads'+import { localStorageKey } from '@/constants/localStorage'+import { useTranslation } from '@/i18n/react-i18next-compat'+import { cn } from '@/lib/utils'+import { VisuallyHidden } from '@radix-ui/react-visually-hidden'++const MAX_RECENT_SEARCHES = 5++interface SearchDialogProps {+ open: boolean+ onOpenChange: (open: boolean) => void+}++export function SearchDialog({ open, onOpenChange }: SearchDialogProps) {+ const navigate = useNavigate()+ const { t } = useTranslation()+ const [searchQuery, setSearchQuery] = useState('')+ const [selectedIndex, setSelectedIndex] = useState(0)+ const [recentVersion, setRecentVersion] = useState(0)+ const inputRef = useRef<HTMLInputElement>(null)++ const threads = useThreads((state) => state.threads)+ const getFilteredThreads = useThreads((state) => state.getFilteredThreads)++ // Focus input when dialog opens+ useEffect(() => {+ if (open) {+ setSearchQuery('')+ setSelectedIndex(0)+ setTimeout(() => {+ inputRef.current?.focus()+ }, 0)+ }+ }, [open])++ // Load recent searches from localStorage+ const recentSearches = useMemo(() => {+ if (!open) return []++ const stored = localStorage.getItem(localStorageKey.recentSearches)+ if (!stored) return []++ try {+ const threadIds = JSON.parse(stored) as string[]+ return threadIds+ .map((id) => threads[id])+ .filter((thread): thread is Thread => thread !== undefined)+ .slice(0, MAX_RECENT_SEARCHES)+ } catch {+ return []+ }+ // eslint-disable-next-line react-hooks/exhaustive-deps+ }, [open, threads, recentVersion])++ const handleClearRecent = (e: React.MouseEvent) => {+ e.preventDefault()+ e.stopPropagation()+ localStorage.removeItem(localStorageKey.recentSearches)+ setRecentVersion((v) => v + 1)+ }++ const handleClose = () => {+ setSearchQuery('')+ onOpenChange(false)+ }++ const handleSelectThread = (threadId: string) => {+ // Save to recent searches+ const stored = localStorage.getItem(localStorageKey.recentSearches)+ let threadIds: string[] = []++ if (stored) {+ try {+ threadIds = JSON.parse(stored) as string[]+ } catch {+ threadIds = []+ }+ }++ // Remove if already exists and add to front+ threadIds = threadIds.filter((id) => id !== threadId)+ threadIds.unshift(threadId)++ // Keep only MAX_RECENT_SEARCHES+ threadIds = threadIds.slice(0, MAX_RECENT_SEARCHES)++ localStorage.setItem(+ localStorageKey.recentSearches,+ JSON.stringify(threadIds)+ )++ handleClose()+ navigate({ to: route.threadsDetail, params: { threadId } })+ }++ // Filter and group threads based on search query+ const searchResults = useMemo(() => {+ if (!searchQuery) return { withProject: [], withoutProject: [] }++ const filteredThreads = getFilteredThreads(searchQuery)+ const withProject: Array<{+ thread: Thread+ projectName: string+ }> = []+ const withoutProject: Thread[] = []++ filteredThreads.forEach((thread) => {+ const projectName = thread.metadata?.project?.name+ if (projectName) {+ withProject.push({ thread, projectName })+ } else {+ withoutProject.push(thread)+ }+ })++ return { withProject, withoutProject }+ }, [searchQuery, getFilteredThreads])++ // Calculate all selectable items for keyboard navigation+ const allItems = useMemo(() => {+ const items: Array<{ type: 'new' | 'recent' | 'result'; id: string }> = []++ if (!searchQuery) {+ // Start new chat option+ items.push({ type: 'new', id: 'new-chat' })+ // Recent searches+ recentSearches.forEach((thread) => {+ items.push({ type: 'recent', id: thread.id })+ })+ } else {+ // Search results with project+ searchResults.withProject.forEach(({ thread }) => {+ items.push({ type: 'result', id: thread.id })+ })+ // Search results without project+ searchResults.withoutProject.forEach((thread) => {+ items.push({ type: 'result', id: thread.id })+ })+ }++ return items+ }, [searchQuery, recentSearches, searchResults])++ // Reset selected index when items change+ useEffect(() => {+ setSelectedIndex(0)+ }, [allItems.length])++ const handleKeyDown = (e: React.KeyboardEvent) => {+ if (e.key === 'ArrowDown') {+ e.preventDefault()+ setSelectedIndex((prev) => Math.min(prev + 1, allItems.length - 1))+ } else if (e.key === 'ArrowUp') {+ e.preventDefault()+ setSelectedIndex((prev) => Math.max(prev - 1, 0))+ } else if (e.key === 'Enter') {+ e.preventDefault()+ const selectedItem = allItems[selectedIndex]+ if (selectedItem) {+ if (selectedItem.type === 'new') {+ handleStartNewChat()+ } else {+ handleSelectThread(selectedItem.id)+ }+ }+ }+ }++ const handleStartNewChat = () => {+ handleClose()+ navigate({ to: '/' })+ }++ const showStartNewChat = !searchQuery+ const hasResults =+ searchResults.withProject.length > 0 ||+ searchResults.withoutProject.length > 0++ return (+ <Dialog open={open} onOpenChange={onOpenChange}>+ <DialogContent+ className="sm:max-w-xl p-0 gap-0 overflow-hidden"+ showCloseButton={false}+ aria-describedby={undefined}+ >+ <VisuallyHidden>+ <DialogTitle>{t('common:search')}</DialogTitle>+ </VisuallyHidden>++ {/* Search Input */}+ <div className="flex items-center border-b border-main-view-fg/10 px-3">+ <IconSearch className="size-4 text-main-view-fg/50 shrink-0" />+ <input+ ref={inputRef}+ type="text"+ placeholder={t('common:searchThreads')}+ className="flex-1 h-12 px-3 bg-transparent text-main-view-fg placeholder:text-main-view-fg/50 focus:outline-none"+ value={searchQuery}+ onChange={(e) => setSearchQuery(e.target.value)}+ onKeyDown={handleKeyDown}+ />+ </div>++ {/* Results */}+ <div className="max-h-80 overflow-y-auto px-1 py-2">+ {/* Empty state when searching */}+ {searchQuery && !hasResults && (+ <div className="flex flex-col items-center justify-center py-12 px-4 text-center">+ <IconSearch className="size-6 text-main-view-fg/50 mb-2" />+ <h3 className="text-base font-medium mb-1">+ {t('common:noResultsFound')}+ </h3>+ <p className="text-xs leading-relaxed text-main-view-fg/60 w-1/2 mx-auto">+ {t('common:noResultsFoundDesc')}+ </p>+ </div>+ )}++ {/* Start new chat - shown when no search query */}+ {showStartNewChat && (+ <div className="p-1">+ <button+ onClick={handleStartNewChat}+ className={cn(+ 'w-full flex items-center gap-2 px-3 py-2 rounded-md text-left hover:bg-main-view-fg/5 transition-colors cursor-pointer',+ selectedIndex === 0 && 'bg-main-view-fg/5'+ )}+ >+ <IconCirclePlus className="size-4 text-main-view-fg/70" />+ <span className="text-sm">{t('common:newChat')}</span>+ </button>+ </div>+ )}++ {/* Recent searches - shown when search is empty */}+ {!searchQuery && recentSearches.length > 0 && (+ <div className="p-1">+ <div className="px-3 pt-1.5 flex items-center justify-between">+ <span className="text-xs font-medium text-main-view-fg/50">+ {t('common:recents')}+ </span>+ <button+ onClick={handleClearRecent}+ className="text-xs text-main-view-fg/50 hover:text-main-view-fg transition-colors cursor-pointer"+ >+ {t('common:clearRecent')}+ </button>+ </div>+ {recentSearches.map((thread, index) => {+ const itemIndex = 1 + index // +1 for new chat option+ return (+ <button+ key={thread.id}+ onClick={() => handleSelectThread(thread.id)}+ className={cn(+ 'w-full flex items-center gap-2 px-3 py-2 rounded-md text-left hover:bg-main-view-fg/5 transition-colors cursor-pointer',+ selectedIndex === itemIndex && 'bg-main-view-fg/5'+ )}+ >+ <IconHistory className="size-4 text-main-view-fg/70 shrink-0" />+ <span className="text-sm truncate">{thread.title}</span>+ </button>+ )+ })}+ </div>+ )}++ {/* Search results with project name */}+ {searchQuery && searchResults.withProject.length > 0 && (+ <div className="p-1">+ {searchResults.withProject.map(({ thread, projectName }, index) => {+ const itemIndex = index+ return (+ <button+ key={thread.id}+ onClick={() => handleSelectThread(thread.id)}+ className={cn(+ 'w-full flex items-center gap-2 px-3 py-2 rounded-md text-left hover:bg-main-view-fg/5 transition-colors cursor-pointer',+ selectedIndex === itemIndex && 'bg-main-view-fg/5'+ )}+ >+ <IconMessage className="size-4 text-main-view-fg/70 shrink-0" />+ <div className="flex items-center min-w-0">+ <span className="text-xs text-main-view-fg/50 flex items-center gap-1">+ <IconFolder className="size-3" />+ {projectName} - + </span>+ <span className="text-sm truncate">{thread.title}</span>+ </div>+ </button>+ )+ })}+ </div>+ )}++ {/* Search results without project name */}+ {searchQuery && searchResults.withoutProject.length > 0 && (+ <div className="p-1">+ {searchResults.withoutProject.map((thread, index) => {+ const itemIndex =+ searchResults.withProject.length + index+ return (+ <button+ key={thread.id}+ onClick={() => handleSelectThread(thread.id)}+ className={cn(+ 'w-full flex items-center gap-2 px-3 py-2 rounded-md text-left hover:bg-main-view-fg/5 transition-colors cursor-pointer',+ selectedIndex === itemIndex && 'bg-main-view-fg/5'+ )}+ >+ <IconMessage className="size-4 text-main-view-fg/70 shrink-0" />+ <span className="text-sm truncate">{thread.title}</span>+ </button>+ )+ })}+ </div>+ )}+ </div>++ {/* Footer with keyboard hints */}+ <div className="flex items-center justify-between border-t border-main-view-fg/10 px-3 py-2 text-xs text-main-view-fg/50">+ <div className="flex items-center gap-3">+ <span className="flex items-center gap-1">+ <kbd className="px-1.5 py-0.5 bg-main-view-fg/10 rounded text-[10px]">+ ↑↓+ </kbd>+ {t('common:toNavigate')}+ </span>+ <span className="flex items-center gap-1">+ <kbd className="px-1.5 py-0.5 bg-main-view-fg/10 rounded text-[10px]">+ ↵+ </kbd>+ {t('common:toSelect')}+ </span>+ </div>+ <span className="flex items-center gap-1">+ <kbd className="px-1.5 py-0.5 bg-main-view-fg/10 rounded text-[10px]">+ esc+ </kbd>+ {t('common:toClose')}+ </span>+ </div>+ </DialogContent>+ </Dialog>+ )+}diff --git a/web-app/src/containers/dialogs/index.ts b/web-app/src/containers/dialogs/index.tsindex 3f96e5d17..737a6091d 100644--- a/web-app/src/containers/dialogs/index.ts+++ b/web-app/src/containers/dialogs/index.ts@@ -8,3 +8,4 @@ export { FactoryResetDialog } from './FactoryResetDialog'export { DeleteAssistantDialog } from './DeleteAssistantDialog'export { DeleteProjectDialog } from './DeleteProjectDialog'export { AddProviderDialog } from './AddProviderDialog'+export { SearchDialog } from './SearchDialog'diff --git a/web-app/src/locales/en/common.json b/web-app/src/locales/en/common.jsonindex a8a74c502..7090fe42c 100644--- a/web-app/src/locales/en/common.json+++ b/web-app/src/locales/en/common.json@@ -38,6 +38,11 @@"profile": "Profile","reset": "Reset","search": "Search",+ "searchThreads": "Search threads...",+ "toNavigate": "to navigate",+ "toSelect": "to select",+ "toClose": "to close",+ "clearRecent": "Clear","name": "Name","cancel": "Cancel","create": "Create",