web: self-hosted search API with native results page (dev-gated)
- Commit
dac72073666bedfd045ff63016ef6195067ba44c- Author
- vayun-mathur <[email protected]>
- When
- 2026-10-23 22:52 UTC (1 month ago)
- Parents
493f653
Diff
web/src/main/java/com/vayunmathur/web/data/WebSearch.kt
diff --git a/web/src/main/java/com/vayunmathur/web/data/WebSearch.kt b/web/src/main/java/com/vayunmathur/web/data/WebSearch.ktnew file mode 100644index 0000000000..01bc4069df--- /dev/null+++ b/web/src/main/java/com/vayunmathur/web/data/WebSearch.kt@@ -0,0 +1,53 @@+package com.vayunmathur.web.data++import kotlinx.serialization.SerialName+import kotlinx.serialization.Serializable++/**+ * Wire contract for GET https://api.maproj.org/api/search+ * (`location_share_server/src/handlers/search.rs`).+ *+ * Single-shape envelope: only the requested `type` field is populated.+ * Field names must match the Rust serde structs exactly.+ */+@Serializable+data class WebSearchResponse(+ @SerialName("type") val kind: String = "text",+ val query: String = "",+ val text: List<WebSearchTextItem>? = null,+ val images: List<WebSearchImageItem>? = null,+ val news: List<WebSearchNewsItem>? = null,+ val error: String? = null,+ @SerialName("fallback_url") val fallbackUrl: String? = null,+)++@Serializable+data class WebSearchTextItem(+ val title: String = "",+ val url: String = "",+ val snippet: String = "",+)++@Serializable+data class WebSearchImageItem(+ val title: String = "",+ @SerialName("image_url") val imageUrl: String = "",+ val thumbnail: String = "",+ @SerialName("source_url") val sourceUrl: String = "",+)++@Serializable+data class WebSearchNewsItem(+ val title: String = "",+ val url: String = "",+ val snippet: String = "",+ val date: Long = 0L,+ val source: String = "",+)++/** Result category, matching the server `type` query param. */+enum class WebSearchKind(val param: String) {+ TEXT("text"),+ IMAGES("images"),+ NEWS("news"),+}
web/src/main/java/com/vayunmathur/web/data/WebSearchRepository.kt
diff --git a/web/src/main/java/com/vayunmathur/web/data/WebSearchRepository.kt b/web/src/main/java/com/vayunmathur/web/data/WebSearchRepository.ktnew file mode 100644index 0000000000..48748cfbd1--- /dev/null+++ b/web/src/main/java/com/vayunmathur/web/data/WebSearchRepository.kt@@ -0,0 +1,43 @@+package com.vayunmathur.web.data++import com.vayunmathur.library.network.NetworkClient+import com.vayunmathur.library.network.Urls++/**+ * Client for the self-hosted search API+ * (GET https://api.maproj.org/api/search, see+ * `location_share_server/src/handlers/search.rs`).+ *+ * Goes through [NetworkClient] like all app networking — never raw+ * OkHttp/`HttpURLConnection`. `web/` inits `TrustBundle.SYSTEM`, which+ * covers our first-party host too.+ */+object WebSearchRepository {++ const val BASE_URL = "https://api.maproj.org/api/search"++ /**+ * Runs one search. `safeSearch=true` (parental supervision switch) maps to+ * the server's strict mode; otherwise moderate. Throws IOException on+ * transport failure — callers show the error state with a fallback button.+ * A degraded server reply (upstream DDG blocked) still parses: [WebSearchResponse.error]+ * is set and the result lists are empty.+ */+ suspend fun search(+ query: String,+ kind: WebSearchKind = WebSearchKind.TEXT,+ safeSearch: Boolean = false,+ page: Int = 1,+ ): WebSearchResponse {+ val url = Urls.appendQuery(+ BASE_URL,+ mapOf(+ "q" to query,+ "type" to kind.param,+ "safe_search" to if (safeSearch) "on" else "moderate",+ "page" to page.coerceAtLeast(1).toString(),+ ),+ )+ return NetworkClient.getJson(url)+ }+}
web/src/main/java/com/vayunmathur/web/platform/BrowserState.kt
diff --git a/web/src/main/java/com/vayunmathur/web/platform/BrowserState.kt b/web/src/main/java/com/vayunmathur/web/platform/BrowserState.ktindex 7879517211..9a23c6ffa9 100644--- a/web/src/main/java/com/vayunmathur/web/platform/BrowserState.kt+++ b/web/src/main/java/com/vayunmathur/web/platform/BrowserState.kt@@ -39,7 +39,14 @@ enum class SearchEngine( // so it is left null instead of guessing at one. STARTPAGE("Startpage", "https://www.startpage.com/do/search?q=%s", "https://www.startpage.com"), ECOSIA("Ecosia", "https://www.ecosia.org/search?q=%s", "https://www.ecosia.org", "safesearch=1"),- QWANT("Qwant", "https://www.qwant.com/?q=%s", "https://www.qwant.com", "safesearch=2");+ QWANT("Qwant", "https://www.qwant.com/?q=%s", "https://www.qwant.com", "safesearch=2"),+ /**+ * First-party search: queries go to our own API and render in a native+ * Compose results page instead of loading engine HTML in a WebView.+ * [searchUrl] is only a template for [buildQueryUrl]; navigation is+ * intercepted in [navigateActiveTab] before any WebView load.+ */+ SELF_HOSTED("Maproj Search", "https://api.maproj.org/api/search?q=%s", "https://api.maproj.org/api/search", "safe_search=on"); fun buildQueryUrl(query: String): String = searchUrl.replace("%s", Uri.encode(query))@@ -63,8 +70,26 @@ enum class SearchEngine( /** Used when the selected engine has no strict-filter parameter of its own. */ val SAFE_FALLBACK = DUCKDUCKGO + /**+ * Engines offered in the Settings picker. [SELF_HOSTED] is dev-only+ * (its backend text scraping is datacenter-blocked and the UI is+ * unfinished): release builds never offer it. R8 folds+ * [com.vayunmathur.web.BuildConfig.DEV_BUILD], so the reference is+ * stripped from release.+ */+ val PICKABLE: List<SearchEngine> =+ if (com.vayunmathur.web.BuildConfig.DEV_BUILD) entries else entries - SELF_HOSTED+ fun fromName(name: String): SearchEngine = entries.find { it.name == name } ?: DEFAULT++ /**+ * The engine to actually use: [SELF_HOSTED] outside a dev build falls+ * back to [DEFAULT] (e.g. a dev-build pref restored on release).+ */+ fun effective(engine: SearchEngine): SearchEngine =+ if (engine == SELF_HOSTED && !com.vayunmathur.web.BuildConfig.DEV_BUILD) DEFAULT+ else engine } }
web/src/main/java/com/vayunmathur/web/platform/SearchUrls.kt
diff --git a/web/src/main/java/com/vayunmathur/web/platform/SearchUrls.kt b/web/src/main/java/com/vayunmathur/web/platform/SearchUrls.ktnew file mode 100644index 0000000000..a4722629ec--- /dev/null+++ b/web/src/main/java/com/vayunmathur/web/platform/SearchUrls.kt@@ -0,0 +1,34 @@+package com.vayunmathur.web.platform++import android.net.Uri++/**+ * Native self-hosted search tab URLs.+ *+ * A `search://results?q=...` pseudo-URL in a tab means "render [SearchResultsPage]+ * natively" rather than loading engine HTML in a WebView. Living in `platform/`+ * (not `ui/`) so the tab model, omnibox chrome, and tab switcher can all share+ * them without `platform` depending on `ui`.+ */++/** Builds the pseudo-URL stored in a tab for a native self-hosted search. */+fun nativeSearchUrl(query: String): String =+ "search://results?q=" + Uri.encode(query)++/** Whether [url] is a native self-hosted search page rather than a WebView page. */+fun isNativeSearchUrl(url: String): Boolean = url.startsWith("search://")++/** Extracts the query from a [nativeSearchUrl], or "" if it is not one. */+fun nativeSearchQuery(url: String): String {+ if (!isNativeSearchUrl(url)) return ""+ return runCatching { Uri.parse(url).getQueryParameter("q").orEmpty() }.getOrDefault("")+}++/**+ * What the omnibox pill and tab tiles show for [url]: the query for a native+ * search tab, "" for blank tabs, the raw URL otherwise.+ */+fun displayTextForUrl(url: String): String {+ if (url.isBlank() || url == "about:blank") return ""+ return nativeSearchQuery(url).ifBlank { url }+}
web/src/main/java/com/vayunmathur/web/platform/WebViewModel.kt
diff --git a/web/src/main/java/com/vayunmathur/web/platform/WebViewModel.kt b/web/src/main/java/com/vayunmathur/web/platform/WebViewModel.ktindex b8003e5bab..0c1fdfa534 100644--- a/web/src/main/java/com/vayunmathur/web/platform/WebViewModel.kt+++ b/web/src/main/java/com/vayunmathur/web/platform/WebViewModel.kt@@ -394,7 +394,10 @@ class WebViewModel( runCatching { CacheMode.valueOf(it) }.getOrNull()?.let { cm -> cacheMode = cm } } searchEngineName?.let {- runCatching { SearchEngine.valueOf(it) }.getOrNull()?.let { se -> searchEngine = se }+ runCatching { SearchEngine.valueOf(it) }.getOrNull()?.let { se ->+ // Dev-gated engine never survives into a release build.+ searchEngine = SearchEngine.effective(se)+ } } jsEnabled = js blockThirdPartyCookies = blockThird
web/src/main/java/com/vayunmathur/web/platform/WebViewModelSettings.kt
diff --git a/web/src/main/java/com/vayunmathur/web/platform/WebViewModelSettings.kt b/web/src/main/java/com/vayunmathur/web/platform/WebViewModelSettings.ktindex 2530c1c0ca..51a55852de 100644--- a/web/src/main/java/com/vayunmathur/web/platform/WebViewModelSettings.kt+++ b/web/src/main/java/com/vayunmathur/web/platform/WebViewModelSettings.kt@@ -8,7 +8,9 @@ fun WebViewModel.updateCacheMode(mode: CacheMode) { } fun WebViewModel.updateSearchEngine(engine: SearchEngine) {- searchEngine = engine+ // Dev-gated engine can never be selected on release (belt-and-braces:+ // the picker already hides it there).+ searchEngine = SearchEngine.effective(engine) persistPrefs() }
web/src/main/java/com/vayunmathur/web/platform/WebViewModelTabs.kt
diff --git a/web/src/main/java/com/vayunmathur/web/platform/WebViewModelTabs.kt b/web/src/main/java/com/vayunmathur/web/platform/WebViewModelTabs.ktindex 95fab06ca9..a413092109 100644--- a/web/src/main/java/com/vayunmathur/web/platform/WebViewModelTabs.kt+++ b/web/src/main/java/com/vayunmathur/web/platform/WebViewModelTabs.kt@@ -22,7 +22,8 @@ fun WebViewModel.onTabUrlChange(tabId: String, url: String) { updateTab(tabId) { it.copy(url = url) } persistTabs() if (tabId == activeTabId && !omniboxFocused) {- omniboxText = if (url.isBlank() || url == "about:blank") "" else url+ // A native search tab shows its query, not its search:// pseudo-URL.+ omniboxText = displayTextForUrl(url) } if (url.startsWith("http")) { val origin = BrowserUtils.originFromUrl(url)@@ -78,7 +79,7 @@ fun WebViewModel.newTab(url: String = "", makeActive: Boolean = true, isPrivate: if (makeActive) { activeTabId = tab.id omniboxFocused = false- omniboxText = if (url.isBlank() || url == "about:blank") "" else url+ omniboxText = displayTextForUrl(url) searchDraft = if (url.isBlank() || url == "about:blank") "" else url } persistTabs()@@ -108,8 +109,9 @@ fun WebViewModel.closeTab(tabId: String) { else -> tabs.last().id } val cur = activeTab- omniboxText = if (cur == null || cur.url.isBlank() || cur.url == "about:blank") "" else cur.url- searchDraft = omniboxText+ val url = cur?.url.orEmpty()+ omniboxText = displayTextForUrl(url)+ searchDraft = if (url.isBlank() || url == "about:blank") "" else url } persistTabs() }@@ -128,18 +130,41 @@ fun WebViewModel.switchToTab(tabId: String) { if (tabId != activeTabId) captureActiveTab() activeTabId = tabId val cur = activeTab- omniboxText = if (cur == null || cur.url.isBlank() || cur.url == "about:blank") "" else cur.url- searchDraft = omniboxText+ val url = cur?.url.orEmpty()+ omniboxText = displayTextForUrl(url)+ searchDraft = if (url.isBlank() || url == "about:blank") "" else url showTabSwitcher = false persistTabs() } fun WebViewModel.navigateActiveTab(input: String) { val active = activeTab ?: return+ // Self-hosted engine renders results natively (SearchResultsPage) instead of+ // loading engine HTML in a WebView. The query is stored as a search://+ // pseudo-URL in the tab so tab switching, persistence, and the omnibox keep+ // working unchanged; BrowserContent branches on the scheme. URLs and blank+ // input still go through the normal path below. Dev-gated: release builds+ // resolve SELF_HOSTED to the default engine via SearchEngine.effective.+ val engine = SearchEngine.effective(searchEngine)+ if (engine == SearchEngine.SELF_HOSTED) {+ val trimmed = input.trim()+ val isUrl = trimmed.startsWith("http://") || trimmed.startsWith("https://") ||+ BrowserUtils.looksLikeUrl(trimmed)+ if (trimmed.isNotEmpty() && !isUrl) {+ val dest = nativeSearchUrl(trimmed)+ markFreshNavigation(active.id)+ onTabUrlChange(active.id, dest)+ // The query itself is not history-logged (a search box is not a+ // visit); result taps are recorded when their pages load.+ omniboxText = trimmed+ omniboxFocused = false+ return+ }+ } // Read live rather than from a cached field: a parent can turn search filtering on while // the browser is open, and the next search should honour it. val safeSearch = ContentFilters.filterSearchResults(context)- val dest = BrowserUtils.toNavigationUrl(input, searchEngine, safeSearch)+ val dest = BrowserUtils.toNavigationUrl(input, engine, safeSearch) noteNavigation(dest) markFreshNavigation(active.id) onTabUrlChange(active.id, dest)
web/src/main/java/com/vayunmathur/web/ui/BrowserOverlays.kt
diff --git a/web/src/main/java/com/vayunmathur/web/ui/BrowserOverlays.kt b/web/src/main/java/com/vayunmathur/web/ui/BrowserOverlays.ktindex b5d0c75f6c..cb8edc0cd2 100644--- a/web/src/main/java/com/vayunmathur/web/ui/BrowserOverlays.kt+++ b/web/src/main/java/com/vayunmathur/web/ui/BrowserOverlays.kt@@ -26,10 +26,13 @@ import com.vayunmathur.web.platform.closeTab import com.vayunmathur.web.platform.denyGeolocation import com.vayunmathur.web.platform.farblingConfig import com.vayunmathur.web.platform.grantGeolocation+import com.vayunmathur.web.platform.BrowserUtils import com.vayunmathur.web.platform.isMultipleSelection+import com.vayunmathur.web.platform.isNativeSearchUrl import com.vayunmathur.web.platform.isNewTab import com.vayunmathur.web.platform.markFreshNavigation import com.vayunmathur.web.platform.moveTab+import com.vayunmathur.web.platform.nativeSearchQuery import com.vayunmathur.web.platform.newTab import com.vayunmathur.web.platform.safeAcceptTypes import com.vayunmathur.web.platform.switchToTab@@ -219,6 +222,18 @@ internal fun BrowserContent( modifier = Modifier.fillMaxSize() ) }+ } else if (activeTab != null && isNativeSearchUrl(activeTab.url)) {+ // Self-hosted engine: native Compose results instead of a WebView.+ // Result taps go through the normal tab navigation so history,+ // shields, and thumbnails behave like any other page load.+ key(activeTab.id, activeTab.url) {+ SearchResultsPage(+ query = nativeSearchQuery(activeTab.url),+ onOpenResult = { url -> onOpenUrl(activeTab, url) },+ onOpenFallback = { url -> onOpenUrl(activeTab, url) },+ modifier = Modifier.fillMaxSize(),+ )+ } } else if (activeTab != null) { Box(Modifier.fillMaxSize()) { // Force a new WebViewBrowser composition per tabId so the AndroidView
web/src/main/java/com/vayunmathur/web/ui/BrowserPage.kt
diff --git a/web/src/main/java/com/vayunmathur/web/ui/BrowserPage.kt b/web/src/main/java/com/vayunmathur/web/ui/BrowserPage.ktindex 459c0b44e9..58a256be82 100644--- a/web/src/main/java/com/vayunmathur/web/ui/BrowserPage.kt+++ b/web/src/main/java/com/vayunmathur/web/ui/BrowserPage.kt@@ -36,6 +36,7 @@ import com.vayunmathur.web.platform.getProgress import com.vayunmathur.web.platform.isNewTab import com.vayunmathur.web.platform.markFreshNavigation import com.vayunmathur.web.platform.navigateActiveTab+import com.vayunmathur.web.platform.nativeSearchQuery import com.vayunmathur.web.platform.newTab import com.vayunmathur.web.platform.onTabUrlChange @@ -143,8 +144,9 @@ fun BrowserPage( progress = if (activeTab != null && !isNewTabActive) progress else 0f, atBottom = viewModel.searchBarAtBottom, onOmniboxClick = {- val full = activeTab?.url?.let { if (it.isBlank() || it == "about:blank") "" else it } ?: ""- viewModel.searchDraft = full+ val raw = activeTab?.url?.let { if (it.isBlank() || it == "about:blank") "" else it } ?: ""+ // A native search tab edits as its query, not its search:// pseudo-URL.+ viewModel.searchDraft = nativeSearchQuery(raw).ifBlank { raw } viewModel.omniboxFocused = true }, onTabSwitcherClick = {
web/src/main/java/com/vayunmathur/web/ui/SearchImageResults.kt
diff --git a/web/src/main/java/com/vayunmathur/web/ui/SearchImageResults.kt b/web/src/main/java/com/vayunmathur/web/ui/SearchImageResults.ktnew file mode 100644index 0000000000..e5a7f28ef2--- /dev/null+++ b/web/src/main/java/com/vayunmathur/web/ui/SearchImageResults.kt@@ -0,0 +1,187 @@+package com.vayunmathur.web.ui++import androidx.compose.foundation.clickable+import androidx.compose.foundation.layout.Arrangement+import androidx.compose.foundation.layout.Box+import androidx.compose.foundation.layout.Column+import androidx.compose.foundation.layout.PaddingValues+import androidx.compose.foundation.layout.Row+import androidx.compose.foundation.layout.Spacer+import androidx.compose.foundation.layout.aspectRatio+import androidx.compose.foundation.layout.fillMaxSize+import androidx.compose.foundation.layout.fillMaxWidth+import androidx.compose.foundation.layout.height+import androidx.compose.foundation.layout.padding+import androidx.compose.foundation.lazy.grid.GridCells+import androidx.compose.foundation.lazy.grid.LazyVerticalGrid+import androidx.compose.foundation.lazy.grid.items+import androidx.compose.runtime.Composable+import androidx.compose.runtime.LaunchedEffect+import androidx.compose.runtime.getValue+import androidx.compose.runtime.mutableIntStateOf+import androidx.compose.runtime.mutableStateOf+import androidx.compose.runtime.remember+import androidx.compose.runtime.rememberCoroutineScope+import androidx.compose.runtime.setValue+import androidx.compose.ui.Alignment+import androidx.compose.ui.Modifier+import androidx.compose.ui.draw.clip+import androidx.compose.ui.layout.ContentScale+import androidx.compose.ui.platform.LocalContext+import androidx.compose.ui.res.stringResource+import androidx.compose.ui.text.style.TextOverflow+import androidx.compose.ui.unit.dp+import com.vayunmathur.library.image.compose.AsyncImage+import com.vayunmathur.library.ui.Button+import com.vayunmathur.library.ui.CircularProgressIndicator+import com.vayunmathur.library.ui.EmptyState+import com.vayunmathur.library.ui.MaterialTheme+import com.vayunmathur.library.ui.OutlinedButton+import com.vayunmathur.library.ui.Text+import com.vayunmathur.web.R+import com.vayunmathur.web.data.WebSearchImageItem+import com.vayunmathur.web.data.WebSearchKind+import com.vayunmathur.web.data.WebSearchRepository+import com.vayunmathur.web.data.WebSearchResponse+import com.vayunmathur.web.platform.BrowserUtils+import com.vayunmathur.web.platform.ContentFilters+import com.vayunmathur.web.platform.SearchEngine+import kotlinx.coroutines.launch++/**+ * Image-result grid for [SearchResultsPage].+ *+ * Owns its fetch (rather than sharing the page's response) because the grid+ * needs append-on-"more" semantics while text/news replace per tab switch.+ */+@Composable+fun SearchImageResults(+ query: String,+ onOpenResult: (String) -> Unit,+ onOpenFallback: (String) -> Unit,+) {+ val context = LocalContext.current+ val scope = rememberCoroutineScope()+ var items by remember(query) { mutableStateOf<List<WebSearchImageItem>>(emptyList()) }+ var loading by remember(query) { mutableStateOf(true) }+ var failure by remember(query) { mutableStateOf<String?>(null) }+ var degraded by remember(query) { mutableStateOf<WebSearchResponse?>(null) }+ var imgPage by remember(query) { mutableIntStateOf(1) }++ fun load(requestedPage: Int) {+ loading = true+ failure = null+ scope.launch {+ runCatching {+ WebSearchRepository.search(+ query = query,+ kind = WebSearchKind.IMAGES,+ safeSearch = ContentFilters.filterSearchResults(context),+ page = requestedPage,+ )+ }.onSuccess {+ val fetched = it.images.orEmpty()+ if (requestedPage == 1) {+ items = fetched+ // Degraded server reply (DDG blocked): empty list + error set.+ degraded = if (fetched.isEmpty() && it.error != null) it else null+ } else {+ items = items + fetched+ }+ imgPage = requestedPage+ loading = false+ }.onFailure { e ->+ failure = e.message ?: e.toString()+ loading = false+ }+ }+ }++ LaunchedEffect(query) { load(1) }++ val errorState = degraded ?: failure?.let {+ WebSearchResponse(kind = "images", query = query, error = it)+ }+ when {+ loading && items.isEmpty() -> Box(Modifier.fillMaxSize(), contentAlignment = Alignment.Center) {+ CircularProgressIndicator()+ }+ errorState != null && items.isEmpty() -> SearchImageErrorState(+ message = errorState.error.orEmpty(),+ fallbackUrl = errorState.fallbackUrl,+ query = query,+ onRetry = { load(1) },+ onOpenFallback = onOpenFallback,+ )+ items.isEmpty() -> EmptyState(+ title = stringResource(R.string.search_no_results),+ modifier = Modifier.fillMaxSize(),+ )+ else -> LazyVerticalGrid(+ columns = GridCells.Adaptive(120.dp),+ modifier = Modifier.fillMaxSize(),+ contentPadding = PaddingValues(8.dp),+ horizontalArrangement = Arrangement.spacedBy(8.dp),+ verticalArrangement = Arrangement.spacedBy(8.dp),+ ) {+ items(items, key = { it.imageUrl + it.title }) { item ->+ AsyncImage(+ model = item.thumbnail.ifBlank { item.imageUrl },+ contentDescription = item.title,+ contentScale = ContentScale.Crop,+ modifier = Modifier+ .aspectRatio(1f)+ .clip(MaterialTheme.shapes.medium)+ .clickable { onOpenResult(item.sourceUrl.ifBlank { item.imageUrl }) },+ )+ }+ if (!loading) {+ item {+ Box(Modifier.fillMaxWidth().padding(8.dp), contentAlignment = Alignment.Center) {+ OutlinedButton(onClick = { load(imgPage + 1) }) {+ Text(stringResource(R.string.search_more_results))+ }+ }+ }+ }+ }+ }+}++@Composable+private fun SearchImageErrorState(+ message: String,+ fallbackUrl: String?,+ query: String,+ onRetry: () -> Unit,+ onOpenFallback: (String) -> Unit,+) {+ Column(+ Modifier.fillMaxSize().padding(24.dp),+ horizontalAlignment = Alignment.CenterHorizontally,+ verticalArrangement = Arrangement.Center,+ ) {+ EmptyState(title = stringResource(R.string.search_failed))+ if (message.isNotBlank()) {+ Spacer(Modifier.height(8.dp))+ Text(+ message,+ style = MaterialTheme.typography.bodySmall,+ color = MaterialTheme.colorScheme.onSurfaceVariant,+ maxLines = 3,+ overflow = TextOverflow.Ellipsis,+ )+ }+ Spacer(Modifier.height(16.dp))+ Row(horizontalArrangement = Arrangement.spacedBy(12.dp)) {+ Button(onClick = onRetry) { Text(stringResource(R.string.retry)) }+ OutlinedButton(onClick = {+ onOpenFallback(+ fallbackUrl ?: BrowserUtils.toNavigationUrl(query, SearchEngine.DUCKDUCKGO),+ )+ }) {+ Text(stringResource(R.string.search_open_classic))+ }+ }+ }+}
web/src/main/java/com/vayunmathur/web/ui/SearchNewsResults.kt
diff --git a/web/src/main/java/com/vayunmathur/web/ui/SearchNewsResults.kt b/web/src/main/java/com/vayunmathur/web/ui/SearchNewsResults.ktnew file mode 100644index 0000000000..9b7f7c5f4b--- /dev/null+++ b/web/src/main/java/com/vayunmathur/web/ui/SearchNewsResults.kt@@ -0,0 +1,86 @@+package com.vayunmathur.web.ui++import androidx.compose.foundation.clickable+import androidx.compose.foundation.layout.Arrangement+import androidx.compose.foundation.layout.Column+import androidx.compose.foundation.layout.PaddingValues+import androidx.compose.foundation.layout.fillMaxSize+import androidx.compose.foundation.lazy.LazyColumn+import androidx.compose.foundation.lazy.items+import androidx.compose.runtime.Composable+import androidx.compose.ui.Modifier+import androidx.compose.ui.res.stringResource+import androidx.compose.ui.text.style.TextOverflow+import androidx.compose.ui.unit.dp+import com.vayunmathur.library.ui.EmptyState+import com.vayunmathur.library.ui.ListItem+import com.vayunmathur.library.ui.MaterialTheme+import com.vayunmathur.library.ui.Text+import com.vayunmathur.web.R+import com.vayunmathur.web.data.WebSearchNewsItem+import kotlinx.datetime.TimeZone+import kotlinx.datetime.toLocalDateTime+import kotlin.time.Instant++/** News-result list for [SearchResultsPage]: source + date meta over snippets. */+@Composable+fun SearchNewsResults(+ items: List<WebSearchNewsItem>,+ onOpenResult: (String) -> Unit,+) {+ if (items.isEmpty()) {+ EmptyState(+ title = stringResource(R.string.search_no_results),+ modifier = Modifier.fillMaxSize(),+ )+ return+ }+ LazyColumn(+ modifier = Modifier.fillMaxSize(),+ contentPadding = PaddingValues(vertical = 8.dp),+ verticalArrangement = Arrangement.spacedBy(2.dp),+ ) {+ items(items, key = { it.url + it.title }) { item ->+ ListItem(+ headlineContent = {+ Text(item.title.ifBlank { item.url }, maxLines = 2, overflow = TextOverflow.Ellipsis)+ },+ supportingContent = {+ Column {+ val meta = listOfNotNull(+ item.source.takeIf { it.isNotBlank() },+ formatNewsDate(item.date),+ ).joinToString(" • ")+ if (meta.isNotBlank()) {+ Text(+ meta,+ maxLines = 1,+ overflow = TextOverflow.Ellipsis,+ style = MaterialTheme.typography.bodySmall,+ color = MaterialTheme.colorScheme.primary,+ )+ }+ if (item.snippet.isNotBlank()) {+ Text(+ item.snippet,+ maxLines = 3,+ overflow = TextOverflow.Ellipsis,+ style = MaterialTheme.typography.bodySmall,+ color = MaterialTheme.colorScheme.onSurfaceVariant,+ )+ }+ }+ },+ modifier = Modifier.clickable { onOpenResult(item.url) },+ )+ }+ }+}++private fun formatNewsDate(unixSecs: Long): String? {+ if (unixSecs <= 0) return null+ return runCatching {+ Instant.fromEpochSeconds(unixSecs)+ .toLocalDateTime(TimeZone.currentSystemDefault()).date.toString()+ }.getOrNull()+}
web/src/main/java/com/vayunmathur/web/ui/SearchResultsPage.kt
diff --git a/web/src/main/java/com/vayunmathur/web/ui/SearchResultsPage.kt b/web/src/main/java/com/vayunmathur/web/ui/SearchResultsPage.ktnew file mode 100644index 0000000000..8c590f2e39--- /dev/null+++ b/web/src/main/java/com/vayunmathur/web/ui/SearchResultsPage.kt@@ -0,0 +1,260 @@+package com.vayunmathur.web.ui++import androidx.compose.foundation.layout.Arrangement+import androidx.compose.foundation.layout.Box+import androidx.compose.foundation.layout.Column+import androidx.compose.foundation.layout.Row+import androidx.compose.foundation.layout.Spacer+import androidx.compose.foundation.layout.fillMaxSize+import androidx.compose.foundation.layout.height+import androidx.compose.foundation.layout.padding+import androidx.compose.runtime.Composable+import androidx.compose.runtime.LaunchedEffect+import androidx.compose.runtime.getValue+import androidx.compose.runtime.mutableIntStateOf+import androidx.compose.runtime.mutableStateOf+import androidx.compose.runtime.remember+import androidx.compose.runtime.rememberCoroutineScope+import androidx.compose.runtime.setValue+import androidx.compose.ui.Alignment+import androidx.compose.ui.Modifier+import androidx.compose.ui.platform.LocalContext+import androidx.compose.ui.res.stringResource+import androidx.compose.ui.text.style.TextOverflow+import androidx.compose.ui.unit.dp+import com.vayunmathur.library.ui.AppScaffold+import com.vayunmathur.library.ui.Button+import com.vayunmathur.library.ui.CircularProgressIndicator+import com.vayunmathur.library.ui.DesktopMaxWidthContainer+import com.vayunmathur.library.ui.EmptyState+import com.vayunmathur.library.ui.ExperimentalMaterial3Api+import com.vayunmathur.library.ui.MaterialTheme+import com.vayunmathur.library.ui.OutlinedButton+import com.vayunmathur.library.ui.Tab+import com.vayunmathur.library.ui.TabRow+import com.vayunmathur.library.ui.Text+import com.vayunmathur.library.ui.appBarScrollBehavior+import com.vayunmathur.library.ui.rememberMessenger+import com.vayunmathur.web.R+import com.vayunmathur.web.data.WebSearchKind+import com.vayunmathur.web.data.WebSearchRepository+import com.vayunmathur.web.data.WebSearchResponse+import com.vayunmathur.web.platform.BrowserUtils+import com.vayunmathur.web.platform.ContentFilters+import com.vayunmathur.web.platform.SearchEngine+import kotlinx.coroutines.launch++/**+ * Native search results page for the self-hosted engine ([SearchEngine.SELF_HOSTED]).+ *+ * Calls the JSON API and renders results with on-device Compose UI — no WebView,+ * no engine HTML. Shown by [BrowserContent] when the active tab holds a+ * `search://` pseudo-URL (see [nativeSearchUrl]).+ *+ * Query logging decision: the query itself is NOT written to history — only+ * result taps the user opens are recorded (via [onOpenResult]). A search box+ * is not a visit, and logging every keystroke-confirmed query would pollute+ * history with non-pages.+ */+@OptIn(ExperimentalMaterial3Api::class)+@Composable+fun SearchResultsPage(+ query: String,+ onOpenResult: (String) -> Unit,+ onOpenFallback: (String) -> Unit,+ modifier: Modifier = Modifier,+) {+ val context = LocalContext.current+ val messenger = rememberMessenger()+ val scope = rememberCoroutineScope()+ var selectedTab by remember { mutableIntStateOf(0) }+ // Explicit tab->kind order (never WebSearchKind.entries[selectedTab]: a+ // future enum reorder must not silently mismatch tabs).+ val kind = when (selectedTab) {+ 1 -> WebSearchKind.IMAGES+ 2 -> WebSearchKind.NEWS+ else -> WebSearchKind.TEXT+ }+ var response by remember(query) { mutableStateOf<WebSearchResponse?>(null) }+ var loading by remember(query) { mutableStateOf(true) }+ var failure by remember(query) { mutableStateOf<String?>(null) }+ var page by remember(query) { mutableIntStateOf(1) }++ fun load(requestedPage: Int) {+ // Guard against the tab-switch race: capture the kind at request time+ // and drop completions that arrive after the user moved on, so a slow+ // TEXT reply cannot overwrite the NEWS response (or vice versa).+ val requestKind = kind+ loading = true+ failure = null+ scope.launch {+ runCatching {+ WebSearchRepository.search(+ query = query,+ kind = requestKind,+ safeSearch = ContentFilters.filterSearchResults(context),+ page = requestedPage,+ )+ }.onSuccess {+ if (requestKind != kind) return@onSuccess+ response = if (requestedPage > 1 && response?.query == it.query) {+ appendPage(response, it)+ } else {+ it+ }+ page = requestedPage+ loading = false+ }.onFailure { e ->+ if (requestKind != kind) return@onFailure+ failure = e.message ?: e.toString()+ loading = false+ messenger.show(context.getString(R.string.search_failed))+ }+ }+ }++ LaunchedEffect(query, selectedTab) {+ // SearchImageResults owns its own paginated fetch (the grid needs+ // append semantics the shared response does not have). Clear the shared+ // slot so switching tabs never flashes the previous kind's results.+ if (kind == WebSearchKind.IMAGES) {+ loading = false+ failure = null+ response = null+ } else {+ response = null+ load(1)+ }+ }++ AppScaffold(+ title = query,+ scrollBehavior = appBarScrollBehavior(),+ modifier = modifier,+ ) { paddingValues ->+ DesktopMaxWidthContainer(modifier = Modifier.padding(paddingValues)) {+ Column(Modifier.fillMaxSize()) {+ TabRow(selectedTabIndex = selectedTab) {+ Tab(+ selected = selectedTab == 0,+ onClick = { selectedTab = 0 },+ text = { Text(stringResource(R.string.search_tab_text)) },+ )+ Tab(+ selected = selectedTab == 1,+ onClick = { selectedTab = 1 },+ text = { Text(stringResource(R.string.search_tab_images)) },+ )+ Tab(+ selected = selectedTab == 2,+ onClick = { selectedTab = 2 },+ text = { Text(stringResource(R.string.search_tab_news)) },+ )+ }+ Box(Modifier.fillMaxSize().weight(1f)) {+ when {+ loading && response == null -> Box(+ Modifier.fillMaxSize(),+ contentAlignment = Alignment.Center,+ ) { CircularProgressIndicator() }++ failure != null && response == null -> SearchErrorState(+ message = failure.orEmpty(),+ onRetry = { load(1) },+ onOpenFallback = {+ onOpenFallback(+ BrowserUtils.toNavigationUrl(query, SearchEngine.DUCKDUCKGO),+ )+ },+ )++ else -> {+ val resp = response+ // Degraded server reply (DDG blocked): lists are empty but+ // error/fallback_url are set.+ if (resp?.error != null && resp.text.isNullOrEmpty() &&+ resp.images.isNullOrEmpty() && resp.news.isNullOrEmpty()+ ) {+ SearchErrorState(+ message = resp.error.orEmpty(),+ onRetry = { load(1) },+ onOpenFallback = {+ onOpenFallback(+ resp.fallbackUrl ?: BrowserUtils.toNavigationUrl(+ query,+ SearchEngine.DUCKDUCKGO,+ ),+ )+ },+ )+ } else when (kind) {+ WebSearchKind.TEXT -> SearchTextResults(+ items = resp?.text.orEmpty(),+ loadingMore = loading,+ onOpenResult = onOpenResult,+ onLoadMore = { load(page + 1) },+ )+ WebSearchKind.IMAGES -> SearchImageResults(+ query = query,+ onOpenResult = onOpenResult,+ onOpenFallback = onOpenFallback,+ )+ WebSearchKind.NEWS -> SearchNewsResults(+ items = resp?.news.orEmpty(),+ onOpenResult = onOpenResult,+ )+ }+ }+ }+ }+ }+ }+ }+}++@Composable+private fun SearchErrorState(+ message: String,+ onRetry: () -> Unit,+ onOpenFallback: () -> Unit,+) {+ Column(+ Modifier.fillMaxSize().padding(24.dp),+ horizontalAlignment = Alignment.CenterHorizontally,+ verticalArrangement = Arrangement.Center,+ ) {+ EmptyState(title = stringResource(R.string.search_failed))+ if (message.isNotBlank()) {+ Spacer(Modifier.height(8.dp))+ Text(+ message,+ style = MaterialTheme.typography.bodySmall,+ color = MaterialTheme.colorScheme.onSurfaceVariant,+ maxLines = 3,+ overflow = TextOverflow.Ellipsis,+ )+ }+ Spacer(Modifier.height(16.dp))+ Row(horizontalArrangement = Arrangement.spacedBy(12.dp)) {+ Button(onClick = onRetry) { Text(stringResource(R.string.retry)) }+ OutlinedButton(onClick = onOpenFallback) {+ Text(stringResource(R.string.search_open_classic))+ }+ }+ }+}++/** Appends page 2+ results onto the accumulated [previous] response. */+private fun appendPage(+ previous: WebSearchResponse?,+ next: WebSearchResponse,+): WebSearchResponse {+ if (previous == null) return next+ return previous.copy(+ text = (previous.text.orEmpty() + next.text.orEmpty()).ifEmpty { null },+ news = (previous.news.orEmpty() + next.news.orEmpty()).ifEmpty { null },+ // Images paginate inside SearchImageResults, which owns its own accumulation.+ error = next.error,+ fallbackUrl = next.fallbackUrl,+ )+}
web/src/main/java/com/vayunmathur/web/ui/SearchTextResults.kt
diff --git a/web/src/main/java/com/vayunmathur/web/ui/SearchTextResults.kt b/web/src/main/java/com/vayunmathur/web/ui/SearchTextResults.ktnew file mode 100644index 0000000000..3b826e84d3--- /dev/null+++ b/web/src/main/java/com/vayunmathur/web/ui/SearchTextResults.kt@@ -0,0 +1,96 @@+package com.vayunmathur.web.ui++import androidx.compose.foundation.clickable+import androidx.compose.foundation.layout.Arrangement+import androidx.compose.foundation.layout.Box+import androidx.compose.foundation.layout.Column+import androidx.compose.foundation.layout.PaddingValues+import androidx.compose.foundation.layout.fillMaxSize+import androidx.compose.foundation.layout.fillMaxWidth+import androidx.compose.foundation.layout.padding+import androidx.compose.foundation.lazy.LazyColumn+import androidx.compose.foundation.lazy.items+import androidx.compose.runtime.Composable+import androidx.compose.ui.Alignment+import androidx.compose.ui.Modifier+import androidx.compose.ui.res.stringResource+import androidx.compose.ui.text.style.TextOverflow+import androidx.compose.ui.unit.dp+import com.vayunmathur.library.ui.CircularProgressIndicator+import com.vayunmathur.library.ui.EmptyState+import com.vayunmathur.library.ui.ListItem+import com.vayunmathur.library.ui.MaterialTheme+import com.vayunmathur.library.ui.OutlinedButton+import com.vayunmathur.library.ui.Text+import com.vayunmathur.web.R+import com.vayunmathur.web.data.WebSearchTextItem+import com.vayunmathur.web.platform.BrowserUtils++/**+ * Text-result list for [SearchResultsPage]: title + host + snippet rows with+ * a trailing "more results" affordance that appends the next page.+ */+@Composable+fun SearchTextResults(+ items: List<WebSearchTextItem>,+ loadingMore: Boolean,+ onOpenResult: (String) -> Unit,+ onLoadMore: () -> Unit,+) {+ if (items.isEmpty()) {+ EmptyState(+ title = stringResource(R.string.search_no_results),+ modifier = Modifier.fillMaxSize(),+ )+ return+ }+ LazyColumn(+ modifier = Modifier.fillMaxSize(),+ contentPadding = PaddingValues(vertical = 8.dp),+ verticalArrangement = Arrangement.spacedBy(2.dp),+ ) {+ items(items, key = { it.url + it.title }) { item ->+ ListItem(+ headlineContent = {+ Text(item.title.ifBlank { item.url }, maxLines = 2, overflow = TextOverflow.Ellipsis)+ },+ supportingContent = {+ Column {+ Text(+ BrowserUtils.prettyUrl(item.url),+ maxLines = 1,+ overflow = TextOverflow.Ellipsis,+ style = MaterialTheme.typography.bodySmall,+ color = MaterialTheme.colorScheme.primary,+ )+ if (item.snippet.isNotBlank()) {+ Text(+ item.snippet,+ maxLines = 3,+ overflow = TextOverflow.Ellipsis,+ style = MaterialTheme.typography.bodySmall,+ color = MaterialTheme.colorScheme.onSurfaceVariant,+ )+ }+ }+ },+ modifier = Modifier.clickable { onOpenResult(item.url) },+ )+ }+ if (loadingMore) {+ item {+ Box(Modifier.fillMaxWidth().padding(16.dp), contentAlignment = Alignment.Center) {+ CircularProgressIndicator()+ }+ }+ } else {+ item {+ Box(Modifier.fillMaxWidth().padding(16.dp), contentAlignment = Alignment.Center) {+ OutlinedButton(onClick = onLoadMore) {+ Text(stringResource(R.string.search_more_results))+ }+ }+ }+ }+ }+}
web/src/main/java/com/vayunmathur/web/ui/SettingsPage.kt
diff --git a/web/src/main/java/com/vayunmathur/web/ui/SettingsPage.kt b/web/src/main/java/com/vayunmathur/web/ui/SettingsPage.ktindex 09a663d469..8fc4abce59 100644--- a/web/src/main/java/com/vayunmathur/web/ui/SettingsPage.kt+++ b/web/src/main/java/com/vayunmathur/web/ui/SettingsPage.kt@@ -267,7 +267,7 @@ fun SettingsPage( title = { Text(stringResource(R.string.search_engine)) }, text = { Column(verticalArrangement = Arrangement.spacedBy(2.dp)) {- SearchEngine.entries.forEach { engine ->+ SearchEngine.PICKABLE.forEach { engine -> Row( modifier = Modifier.fillMaxWidth().clickable { viewModel.updateSearchEngine(engine); showSearchEngineDialog = false
web/src/main/java/com/vayunmathur/web/ui/components/TabTile.kt
diff --git a/web/src/main/java/com/vayunmathur/web/ui/components/TabTile.kt b/web/src/main/java/com/vayunmathur/web/ui/components/TabTile.ktindex 3961063d47..a012d84d9e 100644--- a/web/src/main/java/com/vayunmathur/web/ui/components/TabTile.kt+++ b/web/src/main/java/com/vayunmathur/web/ui/components/TabTile.kt@@ -31,6 +31,7 @@ import com.vayunmathur.web.R import com.vayunmathur.web.platform.BrowserTab import com.vayunmathur.web.platform.BrowserUtils import com.vayunmathur.web.platform.isNewTab+import com.vayunmathur.web.platform.nativeSearchQuery /** * One square in the tab switcher: a favicon-and-title header with the page preview below it.@@ -66,8 +67,10 @@ fun TabTile( gestureModifier: Modifier = Modifier, ) { val newTabLabel = stringResource(R.string.new_tab)+ val searchQuery = nativeSearchQuery(tab.url) val displayTitle = when { tab.isNewTab -> newTabLabel+ searchQuery.isNotBlank() -> searchQuery tab.title.isNotBlank() -> tab.title else -> BrowserUtils.prettyUrl(tab.url).ifBlank { newTabLabel } }
web/src/main/res/values/strings.xml
diff --git a/web/src/main/res/values/strings.xml b/web/src/main/res/values/strings.xmlindex 574b7bfe41..c80db5668d 100644--- a/web/src/main/res/values/strings.xml+++ b/web/src/main/res/values/strings.xml@@ -123,4 +123,12 @@ <string name="cleartext_blocked_message">%1$s was requested over plain HTTP. Unencrypted connections are only allowed to devices on your local network.</string> <string name="local_network_title">Allow local network access?</string> <string name="local_network_message">%1$s looks like a device on your network. Android needs local network permission before this page can load.</string>+ <string name="search_tab_text">Web</string>+ <string name="search_tab_images">Images</string>+ <string name="search_tab_news">News</string>+ <string name="search_failed">Search failed</string>+ <string name="search_no_results">No results found</string>+ <string name="search_more_results">More results</string>+ <string name="search_open_classic">Open classic search</string>+ <string name="retry">Retry</string> </resources>