A self-hostable bookmark-everything app (links, notes and images) with AI-based automatic tagging and full text search
feat(mobile): add semantic search mode selector
Mohamed Bassem8175539ef326
diff --git a/apps/mobile/app/dashboard/(tabs)/(search)/index.ios.tsx b/apps/mobile/app/dashboard/(tabs)/(search)/index.ios.tsxindex 07683d9c..709838c2 100644--- a/apps/mobile/app/dashboard/(tabs)/(search)/index.ios.tsx+++ b/apps/mobile/app/dashboard/(tabs)/(search)/index.ios.tsx@@ -2,6 +2,10 @@ import { useCallback, useRef, useState } from "react";import { Stack, useFocusEffect } from "expo-router";import type { SearchBarCommands } from "react-native-screens";import BookmarkSearchResults from "@/components/search/BookmarkSearchResults";+import {+ SearchModeSelector,+ SEARCH_MODE_PLACEHOLDERS,+} from "@/components/search/SearchModeSelector";import { useBookmarkSearchState } from "@/lib/useBookmarkSearchState";export default function SearchTab() {@@ -35,7 +39,7 @@ export default function SearchTab() {options={{headerSearchBarOptions: {ref: searchBarRef,- placeholder: "Search bookmarks...",+ placeholder: SEARCH_MODE_PLACEHOLDERS[state.searchMode],onChangeText: (event) => setSearch(event.nativeEvent.text),onFocus: () => setIsSearchFocused(true),onBlur: () => {@@ -54,6 +58,13 @@ export default function SearchTab() {isInputFocused={isSearchFocused}state={state}onSelectHistory={handleSearchSubmit}+ header={+ <SearchModeSelector+ value={state.searchMode}+ onValueChange={state.setSearchMode}+ className="px-4"+ />+ }/></>);diff --git a/apps/mobile/components/search/BookmarkSearchResults.tsx b/apps/mobile/components/search/BookmarkSearchResults.tsxindex cdabbfce..8658ca57 100644--- a/apps/mobile/components/search/BookmarkSearchResults.tsx+++ b/apps/mobile/components/search/BookmarkSearchResults.tsx@@ -10,12 +10,14 @@ interface BookmarkSearchResultsProps {isInputFocused: boolean;state: BookmarkSearchState;onSelectHistory: (term: string) => void;+ header?: React.ReactElement;}export default function BookmarkSearchResults({rawSearch,state,onSelectHistory,+ header,}: BookmarkSearchResultsProps) {const {history,@@ -47,15 +49,18 @@ export default function BookmarkSearchResults({renderItem={renderHistoryItem}keyExtractor={(item, index) => `${item}-${index}`}ListHeaderComponent={- <View className="flex-row items-center justify-between p-3">- <Text className="text-sm font-bold text-gray-500">- Recent Searches- </Text>- {history.length > 0 && (- <Pressable onPress={clearHistory}>- <Text className="text-sm text-blue-500">Clear</Text>- </Pressable>- )}+ <View>+ {header}+ <View className="flex-row items-center justify-between p-3">+ <Text className="text-sm font-bold text-gray-500">+ Recent Searches+ </Text>+ {history.length > 0 && (+ <Pressable onPress={clearHistory}>+ <Text className="text-sm text-blue-500">Clear</Text>+ </Pressable>+ )}+ </View></View>}ListEmptyComponent={@@ -79,6 +84,7 @@ export default function BookmarkSearchResults({isFetchingNextPage={isFetchingNextPage}onRefresh={onRefresh}isRefreshing={isPending}+ header={header}/>);}diff --git a/apps/mobile/components/search/InlineSearch.tsx b/apps/mobile/components/search/InlineSearch.tsxindex 5778156a..422c6db8 100644--- a/apps/mobile/components/search/InlineSearch.tsx+++ b/apps/mobile/components/search/InlineSearch.tsx@@ -2,6 +2,10 @@ import { useRef, useState } from "react";import { Pressable, TextInput, View } from "react-native";import { useSafeAreaInsets } from "react-native-safe-area-context";import BookmarkSearchResults from "@/components/search/BookmarkSearchResults";+import {+ SearchModeSelector,+ SEARCH_MODE_PLACEHOLDERS,+} from "@/components/search/SearchModeSelector";import { useBookmarkSearchState } from "@/lib/useBookmarkSearchState";import { TailwindResolver } from "@/components/TailwindResolver";import { SearchInput } from "@/components/ui/SearchInput";@@ -42,7 +46,7 @@ export default function InlineSearch({<View className="flex-1"><SearchInputref={inputRef}- placeholder="Search bookmarks..."+ placeholder={SEARCH_MODE_PLACEHOLDERS[state.searchMode]}value={search}onChangeText={setSearch}onFocus={() => setIsInputFocused(true)}@@ -71,6 +75,10 @@ export default function InlineSearch({/></Pressable></View>+ <SearchModeSelector+ value={state.searchMode}+ onValueChange={state.setSearchMode}+ /><BookmarkSearchResultsrawSearch={search}isInputFocused={isInputFocused}diff --git a/apps/mobile/components/search/SearchModeSelector.tsx b/apps/mobile/components/search/SearchModeSelector.tsxnew file mode 100644index 00000000..4ff28b5c--- /dev/null+++ b/apps/mobile/components/search/SearchModeSelector.tsx@@ -0,0 +1,140 @@+import { Platform, Pressable, View } from "react-native";+import * as Haptics from "expo-haptics";+import { TailwindResolver } from "@/components/TailwindResolver";+import { Text } from "@/components/ui/Text";+import { useClientConfig } from "@/lib/client-config";+import { useMenuIconColors } from "@/lib/useMenuIconColors";+import { cn } from "@/lib/utils";+import { MenuView } from "@react-native-menu/menu";+import {+ Blend,+ BrainCircuit,+ ChevronDown,+ TextSearch,+} from "lucide-react-native";++import type { ZBookmarkSearchMode } from "@karakeep/shared/types/bookmarks";++const SEARCH_MODES = [+ {+ value: "fts",+ label: "Keyword",+ description: "Match exact words across your bookmarks.",+ image: "text.magnifyingglass",+ Icon: TextSearch,+ },+ {+ value: "hybrid",+ label: "Hybrid",+ description: "Balance exact matches and related ideas.",+ image: "arrow.up.arrow.down",+ Icon: Blend,+ },+ {+ value: "semantic",+ label: "Semantic",+ description: "Find related ideas when the words differ.",+ image: "brain",+ Icon: BrainCircuit,+ },+] as const;++export const SEARCH_MODE_PLACEHOLDERS: Record<ZBookmarkSearchMode, string> = {+ fts: "Search bookmarks...",+ hybrid: "Search by words or meaning...",+ semantic: "Describe what you remember...",+};++export function SearchModeSelector({+ value,+ onValueChange,+ className,+}: {+ value: ZBookmarkSearchMode;+ onValueChange: (value: ZBookmarkSearchMode) => void;+ className?: string;+}) {+ const { semanticSearchEnabled } = useClientConfig().search;+ const { menuIconColor } = useMenuIconColors();++ if (!semanticSearchEnabled) {+ return null;+ }++ const activeMode =+ SEARCH_MODES.find((mode) => mode.value === value) ?? SEARCH_MODES[0];+ const ActiveIcon = activeMode.Icon;++ const actions = SEARCH_MODES.map((mode) => ({+ id: mode.value,+ title:+ Platform.OS === "android" && mode.value === value+ ? `✓ ${mode.label}`+ : mode.label,+ subtitle: mode.description,+ state: mode.value === value ? ("on" as const) : ("off" as const),+ image: Platform.select({ ios: mode.image }),+ imageColor: Platform.select({ ios: menuIconColor }),+ }));++ return (+ <View className={cn("flex-row justify-end py-1", className)}>+ <MenuView+ title="Search mode"+ actions={actions}+ shouldOpenOnLongPress={false}+ onPressAction={({ nativeEvent }) => {+ const mode = SEARCH_MODES.find(+ (option) => option.value === nativeEvent.event,+ );+ if (!mode || mode.value === value) {+ return;+ }+ if (Platform.OS === "ios") {+ void Haptics.selectionAsync();+ }+ onValueChange(mode.value);+ }}+ >+ <Pressable+ accessibilityLabel={`Search mode: ${activeMode.label}`}+ accessibilityHint="Opens the search mode menu"+ accessibilityRole="button"+ className={cn(+ "min-h-11 flex-row items-center gap-1.5 rounded-full border px-3",+ value === "fts"+ ? "border-border bg-card"+ : "border-primary/20 bg-primary/10",+ )}+ >+ <TailwindResolver+ className={+ value === "fts" ? "text-muted-foreground" : "text-primary"+ }+ comp={(styles) => (+ <ActiveIcon size={16} color={styles?.color?.toString()} />+ )}+ />+ <Text+ variant="footnote"+ className={+ value === "fts"+ ? "font-medium text-muted-foreground"+ : "font-medium text-primary"+ }+ >+ {activeMode.label}+ </Text>+ <TailwindResolver+ className={+ value === "fts" ? "text-muted-foreground" : "text-primary"+ }+ comp={(styles) => (+ <ChevronDown size={14} color={styles?.color?.toString()} />+ )}+ />+ </Pressable>+ </MenuView>+ </View>+ );+}diff --git a/apps/mobile/lib/client-config.tsx b/apps/mobile/lib/client-config.tsxnew file mode 100644index 00000000..d2da2d25--- /dev/null+++ b/apps/mobile/lib/client-config.tsx@@ -0,0 +1,29 @@+import { useQuery } from "@tanstack/react-query";++import {+ ClientConfigProvider as SharedClientConfigProvider,+ useClientConfig,+} from "@karakeep/shared-react/providers/client-config-provider";+import { useTRPC } from "@karakeep/shared-react/trpc";++export function ClientConfigProvider({+ children,+}: {+ children: React.ReactNode;+}) {+ const api = useTRPC();+ const { data } = useQuery(+ api.config.clientConfig.queryOptions(undefined, {+ staleTime: 5 * 60 * 1000,+ retry: 1,+ }),+ );++ return (+ <SharedClientConfigProvider value={data}>+ {children}+ </SharedClientConfigProvider>+ );+}++export { useClientConfig };diff --git a/apps/mobile/lib/providers.tsx b/apps/mobile/lib/providers.tsxindex 77aa4f02..7d79c225 100644--- a/apps/mobile/lib/providers.tsx+++ b/apps/mobile/lib/providers.tsx@@ -13,6 +13,7 @@ import {setupCachePersistence,setupOnlineManager,} from "./offlineCache";+import { ClientConfigProvider } from "./client-config";import { ConnectionStatusProvider } from "./useConnectionStatus";import { ReaderSettingsProvider } from "./readerSettings";import useAppSettings from "./settings";@@ -50,12 +51,14 @@ export function Providers({ children }: { children: React.ReactNode }) {persistOptions={persistOptions}><TRPCSettingsProvider settings={settings} queryClient={queryClient}>- <ConnectionStatusProvider enabled={!!settings.apiKey}>- <ReaderSettingsProvider>- {children}- <Toaster />- </ReaderSettingsProvider>- </ConnectionStatusProvider>+ <ClientConfigProvider>+ <ConnectionStatusProvider enabled={!!settings.apiKey}>+ <ReaderSettingsProvider>+ {children}+ <Toaster />+ </ReaderSettingsProvider>+ </ConnectionStatusProvider>+ </ClientConfigProvider></TRPCSettingsProvider></PersistQueryClientProvider>);diff --git a/apps/mobile/lib/useBookmarkSearchState.ts b/apps/mobile/lib/useBookmarkSearchState.tsindex bc24f360..0300eae4 100644--- a/apps/mobile/lib/useBookmarkSearchState.ts+++ b/apps/mobile/lib/useBookmarkSearchState.ts@@ -1,4 +1,4 @@-import { useMemo } from "react";+import { useMemo, useState } from "react";import AsyncStorage from "@react-native-async-storage/async-storage";import {keepPreviousData,@@ -9,12 +9,24 @@ import {import { useSearchHistory } from "@karakeep/shared-react/hooks/search-history";import { useDebounce } from "@karakeep/shared-react/hooks/use-debounce";import { useTRPC } from "@karakeep/shared-react/trpc";+import { parseSearchQuery } from "@karakeep/shared/searchQueryParser";++import type { ZBookmarkSearchMode } from "@karakeep/shared/types/bookmarks";++import { useClientConfig } from "./client-config";const MAX_DISPLAY_SUGGESTIONS = 5;const DEBOUNCE_MS = 10;export function useBookmarkSearchState(rawSearch: string) {const query = useDebounce(rawSearch, DEBOUNCE_MS);+ const { semanticSearchEnabled } = useClientConfig().search;+ const [searchMode, setSearchMode] = useState<ZBookmarkSearchMode>("fts");+ const parsedQuery = useMemo(() => parseSearchQuery(query), [query]);+ const effectiveSearchMode =+ semanticSearchEnabled && parsedQuery.text.trim().length > 0+ ? searchMode+ : "fts";const { history, addTerm, clearHistory } = useSearchHistory({getItem: (k: string) => AsyncStorage.getItem(k),@@ -32,7 +44,7 @@ export function useBookmarkSearchState(rawSearch: string) {const { data, error, refetch, isPending, fetchNextPage, isFetchingNextPage } =useInfiniteQuery(api.bookmarks.searchBookmarks.infiniteQueryOptions(- { text: query },+ { text: query, searchMode: effectiveSearchMode },{enabled: query.trim().length > 0,placeholderData: keepPreviousData,@@ -61,6 +73,9 @@ export function useBookmarkSearchState(rawSearch: string) {return {query,+ searchMode,+ setSearchMode,+ semanticSearchEnabled,history,filteredHistory,addTerm,diff --git a/apps/web/lib/clientConfig.tsx b/apps/web/lib/clientConfig.tsxindex 75b7f9bb..d2f05f66 100644--- a/apps/web/lib/clientConfig.tsx+++ b/apps/web/lib/clientConfig.tsx@@ -1,40 +1 @@-import { createContext, useContext } from "react";--import type { ClientConfig } from "@karakeep/shared/config";--export const ClientConfigCtx = createContext<ClientConfig>({- publicUrl: "",- publicApiUrl: "",- demoMode: undefined,- auth: {- disableSignups: false,- disablePasswordAuth: false,- oauthAutoRedirect: false,- },- turnstile: null,- inference: {- isConfigured: false,- inferredTagLang: "english",- enableAutoTagging: false,- enableAutoSummarization: false,- },- chat: {- enabled: false,- },- search: {- semanticSearchEnabled: false,- },- stripe: {- isConfigured: false,- },- legal: {- termsOfServiceUrl: undefined,- privacyPolicyUrl: undefined,- },- serverVersion: undefined,- disableNewReleaseCheck: true,-});--export function useClientConfig() {- return useContext(ClientConfigCtx);-}+export { useClientConfig } from "@karakeep/shared-react/providers/client-config-provider";diff --git a/apps/web/lib/providers.tsx b/apps/web/lib/providers.tsxindex c794d996..d329317f 100644--- a/apps/web/lib/providers.tsx+++ b/apps/web/lib/providers.tsx@@ -12,12 +12,12 @@ import superjson from "superjson";import type { ClientConfig } from "@karakeep/shared/config";import type { AppRouter } from "@karakeep/trpc/routers/_app";+import { ClientConfigProvider } from "@karakeep/shared-react/providers/client-config-provider";import {TRPC_MAX_URL_LENGTH_INTERNAL,TRPCProvider,} from "@karakeep/shared-react/trpc";-import { ClientConfigCtx } from "./clientConfig";import CustomI18nextProvider from "./i18n/provider";function makeQueryClient() {@@ -80,7 +80,7 @@ export default function Providers({);return (- <ClientConfigCtx.Provider value={clientConfig}>+ <ClientConfigProvider value={clientConfig}><UserLocalSettingsCtx.Provider value={userLocalSettings}><SessionProvider session={session}><QueryClientProvider client={queryClient}>@@ -101,6 +101,6 @@ export default function Providers({</QueryClientProvider></SessionProvider></UserLocalSettingsCtx.Provider>- </ClientConfigCtx.Provider>+ </ClientConfigProvider>);}diff --git a/packages/shared-react/providers/client-config-provider.tsx b/packages/shared-react/providers/client-config-provider.tsxnew file mode 100644index 00000000..49b1a290--- /dev/null+++ b/packages/shared-react/providers/client-config-provider.tsx@@ -0,0 +1,85 @@+import { createContext, use, useMemo } from "react";++import type { ZClientConfig } from "@karakeep/shared/types/config";++export const DEFAULT_CLIENT_CONFIG: ZClientConfig = {+ publicUrl: "",+ publicApiUrl: "",+ auth: {+ disableSignups: false,+ disablePasswordAuth: false,+ oauthAutoRedirect: false,+ },+ turnstile: null,+ inference: {+ isConfigured: false,+ inferredTagLang: "english",+ enableAutoTagging: false,+ enableAutoSummarization: false,+ },+ chat: {+ enabled: false,+ },+ search: {+ semanticSearchEnabled: false,+ },+ stripe: {+ isConfigured: false,+ },+ legal: {},+ disableNewReleaseCheck: true,+};++const ClientConfigContext = createContext<ZClientConfig>(DEFAULT_CLIENT_CONFIG);++export function ClientConfigProvider({+ children,+ value,+}: {+ children: React.ReactNode;+ value?: ZClientConfig;+}) {+ // Merge every nested group so an older server can omit newly introduced+ // capabilities without breaking a newer client.+ const config = useMemo<ZClientConfig>(+ () => ({+ ...DEFAULT_CLIENT_CONFIG,+ ...value,+ auth: {+ ...DEFAULT_CLIENT_CONFIG.auth,+ ...value?.auth,+ },+ inference: {+ ...DEFAULT_CLIENT_CONFIG.inference,+ ...value?.inference,+ },+ chat: {+ ...DEFAULT_CLIENT_CONFIG.chat,+ ...value?.chat,+ },+ search: {+ ...DEFAULT_CLIENT_CONFIG.search,+ ...value?.search,+ },+ stripe: {+ ...DEFAULT_CLIENT_CONFIG.stripe,+ ...value?.stripe,+ },+ legal: {+ ...DEFAULT_CLIENT_CONFIG.legal,+ ...value?.legal,+ },+ }),+ [value],+ );++ return (+ <ClientConfigContext.Provider value={config}>+ {children}+ </ClientConfigContext.Provider>+ );+}++export function useClientConfig() {+ return use(ClientConfigContext);+}diff --git a/packages/shared/types/config.ts b/packages/shared/types/config.tsindex cb28229a..de245b2e 100644--- a/packages/shared/types/config.ts+++ b/packages/shared/types/config.ts@@ -12,6 +12,7 @@ export const zClientConfigSchema = z.object({auth: z.object({disableSignups: z.boolean(),disablePasswordAuth: z.boolean(),+ oauthAutoRedirect: z.boolean(),}),turnstile: z.object({@@ -30,6 +31,9 @@ export const zClientConfigSchema = z.object({search: z.object({semanticSearchEnabled: z.boolean(),}),+ stripe: z.object({+ isConfigured: z.boolean(),+ }),legal: z.object({termsOfServiceUrl: z.string().optional(),privacyPolicyUrl: z.string().optional(),@@ -37,3 +41,5 @@ export const zClientConfigSchema = z.object({serverVersion: z.string().optional(),disableNewReleaseCheck: z.boolean(),});++export type ZClientConfig = z.infer<typeof zClientConfigSchema>;