Modern Apps git

← Modern-Apps.git

shop: full search, store names, in-app merchant links; drop Merchants tab; search as top bar, no cart bar

Commit
de7db6788108bb86997fe30ead5961b4423dccd2
Author
Vayun Mathur <[email protected]>
When
2026-11-01 16:51 UTC (1 month ago)
Parents
a6cce70

Diff

library/ui/src/main/java/com/vayunmathur/library/ui/AppScaffold.kt
diff --git a/library/ui/src/main/java/com/vayunmathur/library/ui/AppScaffold.kt b/library/ui/src/main/java/com/vayunmathur/library/ui/AppScaffold.ktindex 05b11d6550..9c70d7b6eb 100644--- a/library/ui/src/main/java/com/vayunmathur/library/ui/AppScaffold.kt+++ b/library/ui/src/main/java/com/vayunmathur/library/ui/AppScaffold.kt@@ -128,6 +128,28 @@ fun AppScaffold(     ) } +/**+ * [AppScaffold] whose top bar is supplied by the screen (e.g. a search field), or+ * omitted entirely with `topBar = {}`. Without a bar the content padding still+ * covers the status bar.+ */+@Composable+fun AppScaffold(+    topBar: @Composable () -> Unit,+    modifier: Modifier = Modifier,+    floatingActionButton: @Composable () -> Unit = {},+    bottomBar: @Composable () -> Unit = {},+    snackbarHost: (@Composable () -> Unit)? = null,+    content: @Composable (PaddingValues) -> Unit,+) = Scaffold(+    modifier = modifier,+    topBar = topBar,+    floatingActionButton = floatingActionButton,+    bottomBar = bottomBar,+    snackbarHost = snackbarHost,+    content = content,+)+ /** [AppScaffold] for a screen that owns a back stack, wiring the back button to it. */ @Composable fun <T : NavKey> AppScaffold(
metadata_data/photos/shop/phone/1.png
diff --git a/metadata_data/photos/shop/phone/1.png b/metadata_data/photos/shop/phone/1.pngindex b06ce1f18b..a2b6a8b264 100644Binary files a/metadata_data/photos/shop/phone/1.png and b/metadata_data/photos/shop/phone/1.png differ
metadata_data/photos/shop/phone/2.png
diff --git a/metadata_data/photos/shop/phone/2.png b/metadata_data/photos/shop/phone/2.pngindex 8e30e64895..e8b0e37014 100644Binary files a/metadata_data/photos/shop/phone/2.png and b/metadata_data/photos/shop/phone/2.png differ
metadata_data/photos/shop/phone/3.png
diff --git a/metadata_data/photos/shop/phone/3.png b/metadata_data/photos/shop/phone/3.pngindex a11b3cceaf..840d3a6cf1 100644Binary files a/metadata_data/photos/shop/phone/3.png and b/metadata_data/photos/shop/phone/3.png differ
metadata_data/photos/shop/phone/4.png
diff --git a/metadata_data/photos/shop/phone/4.png b/metadata_data/photos/shop/phone/4.pngindex 840d3a6cf1..f7323d2bbb 100644Binary files a/metadata_data/photos/shop/phone/4.png and b/metadata_data/photos/shop/phone/4.png differ
metadata_data/photos/shop/phone/5.png
diff --git a/metadata_data/photos/shop/phone/5.png b/metadata_data/photos/shop/phone/5.pngdeleted file mode 100644index ecf44fd489..0000000000Binary files a/metadata_data/photos/shop/phone/5.png and /dev/null differ
metadata_data/shop.md
diff --git a/metadata_data/shop.md b/metadata_data/shop.mdindex 61eb803dc9..1e088ff038 100644--- a/metadata_data/shop.md+++ b/metadata_data/shop.md@@ -1,7 +1,8 @@ Discover UCP merchants and review shopping checkouts  Features:-- Search compatible UCP merchants via Shopify Global Catalog, merchant domain entry, or the public UCPList directory+- One search box finds products across Shopify's Global Catalog and the UCPList stores that best match what you typed+- Store links open right in the app: product pages show the product, other pages search that store - Validate each merchant's live advertised profile before showing products; directory badges are leads, not access grants - Refresh product details to confirm the exact variant before adding integer-quantity items to the cart - Prepare checkout sessions with per-merchant totals plus authoritative checkout totals and legal links
scripts/shop/generate_merchant_links.py
diff --git a/scripts/shop/generate_merchant_links.py b/scripts/shop/generate_merchant_links.pynew file mode 100644index 0000000000..f53709d470--- /dev/null+++ b/scripts/shop/generate_merchant_links.py@@ -0,0 +1,73 @@+#!/usr/bin/env python3+"""Regenerate the Shop app's merchant link intent-filter from the live directory.++Android only lets an app become the default handler for web links whose hosts are+declared in the manifest. Merchant sites can't host our assetlinks.json, so the+filter is unverified and users approve it once in "Open by default".++Rerun before each release:  python3 scripts/shop/generate_merchant_links.py+"""++import json+import pathlib+import re+import sys+import urllib.request++DIRECTORY_URL = "https://api.maproj.org/shop/v1/merchants"+MANIFEST = pathlib.Path(__file__).resolve().parents[2] / "shop/src/main/AndroidManifest.xml"+BEGIN = "<!-- BEGIN MERCHANT LINKS (generated by scripts/shop/generate_merchant_links.py) -->"+END = "<!-- END MERCHANT LINKS -->"+HOST = re.compile(r"^(?=.{1,253}$)([a-z0-9]([a-z0-9-]{0,61}[a-z0-9])?\.)+[a-z]{2,63}$")+INDENT = " " * 12+++def fetch_domains() -> list[str]:+    request = urllib.request.Request(+        DIRECTORY_URL, headers={"Accept": "application/json", "User-Agent": "ModernApps-build/1.0"}+    )+    with urllib.request.urlopen(request, timeout=60) as response:+        merchants = json.load(response)["merchants"]+    hosts = set()+    for merchant in merchants:+        domain = str(merchant.get("domain", "")).strip().lower()+        if not HOST.match(domain):+            continue+        bare = domain.removeprefix("www.")+        hosts.update({bare, f"www.{bare}"})+    return sorted(hosts)+++def render(hosts: list[str]) -> str:+    lines = [+        BEGIN,+        '<intent-filter android:autoVerify="false" tools:ignore="AppLinkUrlError,AppLinkWarning">',+        '    <action android:name="android.intent.action.VIEW" />',+        '    <category android:name="android.intent.category.DEFAULT" />',+        '    <category android:name="android.intent.category.BROWSABLE" />',+        '    <data android:scheme="https" />',+        '    <data android:scheme="http" />',+        *[f'    <data android:host="{host}" />' for host in hosts],+        "</intent-filter>",+        END,+    ]+    return "\n".join(INDENT + line for line in lines)+++def main() -> int:+    hosts = fetch_domains()+    if not hosts:+        print("Directory returned no usable domains; manifest left unchanged.", file=sys.stderr)+        return 1+    text = MANIFEST.read_text()+    start, end = text.find(INDENT + BEGIN), text.find(END)+    if start < 0 or end < 0:+        print(f"Markers not found in {MANIFEST}", file=sys.stderr)+        return 1+    MANIFEST.write_text(text[:start] + render(hosts) + text[end + len(END):])+    print(f"Wrote {len(hosts)} hosts to {MANIFEST}")+    return 0+++if __name__ == "__main__":+    sys.exit(main())
shop/AGENTS.md
diff --git a/shop/AGENTS.md b/shop/AGENTS.mdindex bd8294f6d3..75dc8d9df0 100644--- a/shop/AGENTS.md+++ b/shop/AGENTS.md@@ -9,14 +9,15 @@ Entry types: MainActivity, Route, Navigation. Navigation remains a root-only gra - The `network/` package holds only the thin `ShopBackend` interface + DTOs over `library:network`. Dated discovery, REST/MCP transport, versioning, SSRF guards, wire limits, and the idempotency ledger live server-side. - Anonymous catalog and checkout preparation using supported UCP 2026-08-25 and 2026-04-08 profiles, resolved server-side. The server selects one complete advertised profile and exact capability/service versions; it never merges releases. - Server error codes mirror the former client `UcpError` (`transport | rate_limited | http | malformed | rpc | unsupported | uncertain`, plus `retryAfterMs`): `unsupported` routes to the merchant website, anything else on a write is uncertain and never auto-retried on either side.-- The Merchants tab loads the directory through the proxy. Cache/filter locally; the server validates on first use.+- Every search is a full search: the server embeds directory merchants (name + description), picks the few closest to the query, and searches them alongside the Global Catalog. There is no merchant directory tab or domain field; a merchant-scoped search only comes from an opened merchant link and is dismissible.+- Directory merchant links open in the app via an unverified intent-filter generated into `AndroidManifest.xml` by `scripts/shop/generate_merchant_links.py` (rerun per release). Product URLs (`/products/<handle>`) open the product; other URLs open a scoped search. A one-time card sends the user to "Open by default" to approve the hosts. - The buyer profile (first name, last name, email, phone required; delivery address optional) is stored only in the module's SQLCipher Room database (`ProfileRepository`). The app is locked behind the profile form until the required fields validate; the Profile tab edits it. - Checkout takes no buyer input: every session field comes from the saved profile (`ProfileCheckout`). Merchant shipping-option choices remain selectable. Merchant totals and legal links are authoritative. - Checkout writes require explicit user action and a stable idempotency key per intent. Never replay an uncertain mutation automatically. One Create press may issue a second write that carries the saved delivery address, only after the create succeeded and the merchant advertised shipping or reported `delivery_address_required`. - Preserve cart lines through partial failures and browser handoffs. A session or browser return is not a paid order. - No raw card entry, wallet tokenization, completion or authenticated order-read integration while provider authorization is unavailable. - Only supported integer quantities can be added. Detail refresh sends the product ID and selected options, and must confirm the exact variant before cart actions. If a valid detail response returns only another featured option, one fresh advertised merchant search may confirm the exact SKU. Cached snapshots and empty lookup responses are not verification; denied/rate-limited calls are never retried automatically.-- Use variant seller identity for Global Catalog routing, not the shop.app product-page host. Display the publishing store name when provided and its domain otherwise.+- Use variant seller identity for Global Catalog routing, not the shop.app product-page host. Show store names (cart lines and pending orders persist `storeName`); fall back to the domain only when no name is known. - Product HTML is converted to inert styled text without a WebView; only validated public HTTPS description links may open externally. - Product responses remain session-scoped; persisted cart snapshots omit remote image URLs. - Merchant image hosts and cdn.shopify.com are allowed; other image hosts are dropped.
shop/src/main/AndroidManifest.xml
diff --git a/shop/src/main/AndroidManifest.xml b/shop/src/main/AndroidManifest.xmlindex ad74918447..07abf7003a 100644--- a/shop/src/main/AndroidManifest.xml+++ b/shop/src/main/AndroidManifest.xml@@ -1,5 +1,6 @@ <?xml version="1.0" encoding="utf-8"?>-<manifest xmlns:android="http://schemas.android.com/apk/res/android">+<manifest xmlns:android="http://schemas.android.com/apk/res/android"+    xmlns:tools="http://schemas.android.com/tools">      <uses-permission android:name="android.permission.INTERNET" />     <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />@@ -21,6 +22,229 @@                 <action android:name="android.intent.action.MAIN" />                 <category android:name="android.intent.category.LAUNCHER" />             </intent-filter>+            <!-- BEGIN MERCHANT LINKS (generated by scripts/shop/generate_merchant_links.py) -->+            <intent-filter android:autoVerify="false" tools:ignore="AppLinkUrlError,AppLinkWarning">+                <action android:name="android.intent.action.VIEW" />+                <category android:name="android.intent.category.DEFAULT" />+                <category android:name="android.intent.category.BROWSABLE" />+                <data android:scheme="https" />+                <data android:scheme="http" />+                <data android:host="aesop.com" />+                <data android:host="allbirds.com" />+                <data android:host="anastasiabeverlyhills.com" />+                <data android:host="anker.com" />+                <data android:host="asos.com" />+                <data android:host="bando.com" />+                <data android:host="beardbrand.com" />+                <data android:host="bestbuy.com" />+                <data android:host="blenderseyewear.com" />+                <data android:host="blueland.com" />+                <data android:host="bombas.com" />+                <data android:host="boyish.com" />+                <data android:host="brooklinen.com" />+                <data android:host="carawayhome.com" />+                <data android:host="carrefour.com" />+                <data android:host="casper.com" />+                <data android:host="ceremonycoffee.com" />+                <data android:host="chewy.com" />+                <data android:host="chubbiesshorts.com" />+                <data android:host="colourpop.com" />+                <data android:host="costco.com" />+                <data android:host="cotopaxi.com" />+                <data android:host="cutsclothing.com" />+                <data android:host="cuyana.com" />+                <data android:host="dagnedover.com" />+                <data android:host="deathwishcoffee.com" />+                <data android:host="decathlon.com" />+                <data android:host="drinkhydrant.com" />+                <data android:host="drinkspindrift.com" />+                <data android:host="drsquatch.com" />+                <data android:host="ekster.com" />+                <data android:host="everlane.com" />+                <data android:host="facerealityskincare.com" />+                <data android:host="fahertybrand.com" />+                <data android:host="feastables.com" />+                <data android:host="fentybeauty.com" />+                <data android:host="flipkart.com" />+                <data android:host="forhims.com" />+                <data android:host="frankandoak.com" />+                <data android:host="fromourplace.com" />+                <data android:host="gap.com" />+                <data android:host="glossier.com" />+                <data android:host="graza.co" />+                <data android:host="greatjonesgoods.com" />+                <data android:host="greats.com" />+                <data android:host="gymshark.com" />+                <data android:host="harrys.com" />+                <data android:host="hauslabs.com" />+                <data android:host="hedleyandbennett.com" />+                <data android:host="herocosmetics.us" />+                <data android:host="hm.com" />+                <data android:host="homedepot.com" />+                <data android:host="honeylove.com" />+                <data android:host="ikea.com" />+                <data android:host="italic.com" />+                <data android:host="jdsports.com" />+                <data android:host="jeffreestarcosmetics.com" />+                <data android:host="jonesroadbeauty.com" />+                <data android:host="kith.com" />+                <data android:host="koio.co" />+                <data android:host="kroger.com" />+                <data android:host="liquid-iv.com" />+                <data android:host="lowes.com" />+                <data android:host="macys.com" />+                <data android:host="magicspoon.com" />+                <data android:host="marinelayer.com" />+                <data android:host="marksandspencer.com" />+                <data android:host="materialkitchen.com" />+                <data android:host="mejuri.com" />+                <data android:host="milkmakeup.com" />+                <data android:host="morphe.com" />+                <data android:host="mudwtr.com" />+                <data android:host="nativecos.com" />+                <data android:host="newegg.com" />+                <data android:host="next.co.uk" />+                <data android:host="nike.com" />+                <data android:host="nordstrom.com" />+                <data android:host="olaplex.com" />+                <data android:host="outdoorvoices.com" />+                <data android:host="parachutehome.com" />+                <data android:host="petalandpup.com" />+                <data android:host="pixibeauty.com" />+                <data android:host="prose.com" />+                <data android:host="publicgoods.com" />+                <data android:host="puravidabracelets.com" />+                <data android:host="ridgewallet.com" />+                <data android:host="rothys.com" />+                <data android:host="seed.com" />+                <data android:host="sephora.com" />+                <data android:host="shopee.com" />+                <data android:host="skims.com" />+                <data android:host="stance.com" />+                <data android:host="stevemadden.com" />+                <data android:host="sundayriley.com" />+                <data android:host="takearecess.com" />+                <data android:host="taylorstitch.com" />+                <data android:host="tentree.com" />+                <data android:host="thursdayboots.com" />+                <data android:host="trueclassictees.com" />+                <data android:host="ulta.com" />+                <data android:host="untuckit.com" />+                <data android:host="vercel.store" />+                <data android:host="vitruvi.com" />+                <data android:host="wearpepper.com" />+                <data android:host="wildone.com" />+                <data android:host="www.aesop.com" />+                <data android:host="www.allbirds.com" />+                <data android:host="www.anastasiabeverlyhills.com" />+                <data android:host="www.anker.com" />+                <data android:host="www.asos.com" />+                <data android:host="www.bando.com" />+                <data android:host="www.beardbrand.com" />+                <data android:host="www.bestbuy.com" />+                <data android:host="www.blenderseyewear.com" />+                <data android:host="www.blueland.com" />+                <data android:host="www.bombas.com" />+                <data android:host="www.boyish.com" />+                <data android:host="www.brooklinen.com" />+                <data android:host="www.carawayhome.com" />+                <data android:host="www.carrefour.com" />+                <data android:host="www.casper.com" />+                <data android:host="www.ceremonycoffee.com" />+                <data android:host="www.chewy.com" />+                <data android:host="www.chubbiesshorts.com" />+                <data android:host="www.colourpop.com" />+                <data android:host="www.costco.com" />+                <data android:host="www.cotopaxi.com" />+                <data android:host="www.cutsclothing.com" />+                <data android:host="www.cuyana.com" />+                <data android:host="www.dagnedover.com" />+                <data android:host="www.deathwishcoffee.com" />+                <data android:host="www.decathlon.com" />+                <data android:host="www.drinkhydrant.com" />+                <data android:host="www.drinkspindrift.com" />+                <data android:host="www.drsquatch.com" />+                <data android:host="www.ekster.com" />+                <data android:host="www.everlane.com" />+                <data android:host="www.facerealityskincare.com" />+                <data android:host="www.fahertybrand.com" />+                <data android:host="www.feastables.com" />+                <data android:host="www.fentybeauty.com" />+                <data android:host="www.flipkart.com" />+                <data android:host="www.forhims.com" />+                <data android:host="www.frankandoak.com" />+                <data android:host="www.fromourplace.com" />+                <data android:host="www.gap.com" />+                <data android:host="www.glossier.com" />+                <data android:host="www.graza.co" />+                <data android:host="www.greatjonesgoods.com" />+                <data android:host="www.greats.com" />+                <data android:host="www.gymshark.com" />+                <data android:host="www.harrys.com" />+                <data android:host="www.hauslabs.com" />+                <data android:host="www.hedleyandbennett.com" />+                <data android:host="www.herocosmetics.us" />+                <data android:host="www.hm.com" />+                <data android:host="www.homedepot.com" />+                <data android:host="www.honeylove.com" />+                <data android:host="www.ikea.com" />+                <data android:host="www.italic.com" />+                <data android:host="www.jdsports.com" />+                <data android:host="www.jeffreestarcosmetics.com" />+                <data android:host="www.jonesroadbeauty.com" />+                <data android:host="www.kith.com" />+                <data android:host="www.koio.co" />+                <data android:host="www.kroger.com" />+                <data android:host="www.liquid-iv.com" />+                <data android:host="www.lowes.com" />+                <data android:host="www.macys.com" />+                <data android:host="www.magicspoon.com" />+                <data android:host="www.marinelayer.com" />+                <data android:host="www.marksandspencer.com" />+                <data android:host="www.materialkitchen.com" />+                <data android:host="www.mejuri.com" />+                <data android:host="www.milkmakeup.com" />+                <data android:host="www.morphe.com" />+                <data android:host="www.mudwtr.com" />+                <data android:host="www.nativecos.com" />+                <data android:host="www.newegg.com" />+                <data android:host="www.next.co.uk" />+                <data android:host="www.nike.com" />+                <data android:host="www.nordstrom.com" />+                <data android:host="www.olaplex.com" />+                <data android:host="www.outdoorvoices.com" />+                <data android:host="www.parachutehome.com" />+                <data android:host="www.petalandpup.com" />+                <data android:host="www.pixibeauty.com" />+                <data android:host="www.prose.com" />+                <data android:host="www.publicgoods.com" />+                <data android:host="www.puravidabracelets.com" />+                <data android:host="www.ridgewallet.com" />+                <data android:host="www.rothys.com" />+                <data android:host="www.seed.com" />+                <data android:host="www.sephora.com" />+                <data android:host="www.shopee.com" />+                <data android:host="www.skims.com" />+                <data android:host="www.stance.com" />+                <data android:host="www.stevemadden.com" />+                <data android:host="www.sundayriley.com" />+                <data android:host="www.takearecess.com" />+                <data android:host="www.taylorstitch.com" />+                <data android:host="www.tentree.com" />+                <data android:host="www.thursdayboots.com" />+                <data android:host="www.trueclassictees.com" />+                <data android:host="www.ulta.com" />+                <data android:host="www.untuckit.com" />+                <data android:host="www.vercel.store" />+                <data android:host="www.vitruvi.com" />+                <data android:host="www.wearpepper.com" />+                <data android:host="www.wildone.com" />+                <data android:host="www.zalando.com" />+                <data android:host="www.zara.com" />+                <data android:host="zalando.com" />+                <data android:host="zara.com" />+            </intent-filter>+            <!-- END MERCHANT LINKS -->         </activity>     </application> 
shop/src/main/java/com/vayunmathur/shop/MainActivity.kt
diff --git a/shop/src/main/java/com/vayunmathur/shop/MainActivity.kt b/shop/src/main/java/com/vayunmathur/shop/MainActivity.ktindex 0963f05092..f740670317 100644--- a/shop/src/main/java/com/vayunmathur/shop/MainActivity.kt+++ b/shop/src/main/java/com/vayunmathur/shop/MainActivity.kt@@ -1,5 +1,6 @@ package com.vayunmathur.shop +import android.content.Intent import androidx.activity.viewModels import androidx.compose.runtime.Composable import com.vayunmathur.library.ui.MaActivity@@ -12,6 +13,22 @@ class MainActivity : MaActivity() {     override fun onCreateBeforeContent() {         // Trust-bundle warm-up off the main thread; screens await AppInit.awaitReady().         AppInit.start(this)+        // The ViewModel outlives configuration changes, which re-deliver the launch intent.+        if (!viewModel.launchLinkHandled) {+            viewModel.launchLinkHandled = true+            handleLink(intent)+        }+    }++    override fun onNewIntent(intent: Intent) {+        super.onNewIntent(intent)+        setIntent(intent)+        handleLink(intent)+    }++    private fun handleLink(intent: Intent?) {+        if (intent?.action != Intent.ACTION_VIEW) return+        intent.dataString?.let(viewModel::openLink)     }      @Composable
shop/src/main/java/com/vayunmathur/shop/Navigation.kt
diff --git a/shop/src/main/java/com/vayunmathur/shop/Navigation.kt b/shop/src/main/java/com/vayunmathur/shop/Navigation.ktindex 0d3973fdfa..ad8c463895 100644--- a/shop/src/main/java/com/vayunmathur/shop/Navigation.kt+++ b/shop/src/main/java/com/vayunmathur/shop/Navigation.kt@@ -23,6 +23,11 @@ fun Navigation(viewModel: ShopViewModel) {         return     }     val backStack = rememberNavBackStack<Route>(Route.Search)+    LaunchedEffect(viewModel.pendingRoute) {+        val route = viewModel.pendingRoute ?: return@LaunchedEffect+        if (route == Route.Search) backStack.reset(Route.Search) else backStack.reset(Route.Search, route)+        viewModel.consumePendingRoute()+    }     MainNavigation(backStack) {         entry<Route.Search> {             ShopTabs(@@ -44,7 +49,7 @@ fun Navigation(viewModel: ShopViewModel) {             )         }         entry<Route.Cart> {-            CartScreen(viewModel, onBack = { backStack.pop() }, onCheckout = { backStack.add(Route.Checkout) })+            CartScreen(viewModel, onCheckout = { backStack.add(Route.Checkout) })         }         entry<Route.Checkout> {             CheckoutScreen(viewModel = viewModel, onBack = { backStack.pop() })
shop/src/main/java/com/vayunmathur/shop/data/UcpModels.kt
diff --git a/shop/src/main/java/com/vayunmathur/shop/data/UcpModels.kt b/shop/src/main/java/com/vayunmathur/shop/data/UcpModels.ktindex dc73ee6b88..dd0e353741 100644--- a/shop/src/main/java/com/vayunmathur/shop/data/UcpModels.kt+++ b/shop/src/main/java/com/vayunmathur/shop/data/UcpModels.kt@@ -54,7 +54,10 @@ data class CartLine(     val platformId: String = "shopify",     val shopDomain: String = "",     val quantity: Int = 1,-)+    val storeName: String = "",+) {+    val displayName: String get() = storeName.ifBlank { shopDomain }+}  @Serializable data class UcpTotals(@@ -108,7 +111,10 @@ data class PlacedOrder(     val totalEntries: List<UcpTotalEntry> = emptyList(),     val expiresAt: String? = null,     val version: String = "2026-08-25",-)+    val storeName: String = "",+) {+    val displayName: String get() = storeName.ifBlank { shopDomain }+}  sealed interface UcpError {     data class Transport(val reason: String) : UcpError
shop/src/main/java/com/vayunmathur/shop/domain/MerchantLinks.kt
diff --git a/shop/src/main/java/com/vayunmathur/shop/domain/MerchantLinks.kt b/shop/src/main/java/com/vayunmathur/shop/domain/MerchantLinks.ktnew file mode 100644index 0000000000..5f7d5eb92d--- /dev/null+++ b/shop/src/main/java/com/vayunmathur/shop/domain/MerchantLinks.kt@@ -0,0 +1,52 @@+package com.vayunmathur.shop.domain++import java.net.URI+import java.net.URLDecoder+import java.util.Locale++/** Classifies an incoming merchant web link. */+sealed interface MerchantLink {+    val host: String++    data class Product(override val host: String, val handle: String) : MerchantLink+    data class Search(override val host: String, val query: String) : MerchantLink+    data class Merchant(override val host: String) : MerchantLink+}++object MerchantLinks {+    private val handlePattern = Regex("^[a-z0-9][a-z0-9-]{0,199}$")+    private val webSchemes = setOf("https", "http")+    private val webPorts = setOf(-1, 80, 443)+    private const val MAX_QUERY = 200++    fun parse(url: String): MerchantLink? {+        val uri = runCatching { URI(url.trim()) }.getOrNull()?.takeIf(::isPlainWebLink) ?: return null+        val host = MerchantUrls.domain(uri.host.orEmpty()) ?: return null+        val segments = uri.rawPath.orEmpty().split('/').filter { it.isNotEmpty() }.map(::decode)+        val query = productHandle(segments)?.let { return MerchantLink.Product(host, it) }+            ?: query(uri.rawQuery)+            ?: collection(segments)+        return if (query != null) MerchantLink.Search(host, query) else MerchantLink.Merchant(host)+    }++    private fun isPlainWebLink(uri: URI): Boolean =+        uri.scheme?.lowercase(Locale.US) in webSchemes && uri.userInfo == null && uri.port in webPorts++    private fun productHandle(segments: List<String>): String? {+        val index = segments.indexOf("products")+        if (index < 0) return null+        return segments.getOrNull(index + 1)?.lowercase(Locale.US)?.takeIf(handlePattern::matches)+    }++    private fun collection(segments: List<String>): String? =+        segments.takeIf { it.firstOrNull() == "collections" }?.getOrNull(1)?.takeIf { it != "all" }?.let(::words)++    private fun query(rawQuery: String?): String? = rawQuery.orEmpty().split('&')+        .map { it.substringBefore('=') to decode(it.substringAfter('=', "")) }+        .firstOrNull { (key, value) -> key in setOf("q", "query") && value.isNotBlank() }+        ?.second?.trim()?.take(MAX_QUERY)++    private fun words(handle: String): String = handle.replace('-', ' ').trim()++    private fun decode(value: String): String = runCatching { URLDecoder.decode(value, "UTF-8") }.getOrDefault(value)+}
shop/src/main/java/com/vayunmathur/shop/domain/NativeCheckoutCoordinator.kt
diff --git a/shop/src/main/java/com/vayunmathur/shop/domain/NativeCheckoutCoordinator.kt b/shop/src/main/java/com/vayunmathur/shop/domain/NativeCheckoutCoordinator.ktindex 46b6a65952..91b191663e 100644--- a/shop/src/main/java/com/vayunmathur/shop/domain/NativeCheckoutCoordinator.kt+++ b/shop/src/main/java/com/vayunmathur/shop/domain/NativeCheckoutCoordinator.kt@@ -124,7 +124,8 @@ internal class NativeCheckoutCoordinator(             // Persist only the existing pending history projection, never buyer, address, messages or raw response.             sink.save(PlacedOrder(checkoutId = checkout.checkoutId, placedAtMs = now(), total = checkout.totals.total,                 itemCount = lines.sumOf { it.quantity }, continueUrl = MerchantUrls.httpsUrl(checkout.continueUrl).orEmpty(),-                status = "pending", platformId = platform, shopDomain = shop, lines = lines.map { it.copy(imageUrl = "") },+                status = "pending", platformId = platform, shopDomain = shop, storeName = lines.firstNotNullOfOrNull { it.storeName.ifBlank { null } }.orEmpty(),+                lines = lines.map { it.copy(imageUrl = "") },                 totalEntries = checkout.totalEntries.map { it.copy(label = it.type) }, expiresAt = checkout.expiresAt, version = checkout.version))         } catch (cancelled: CancellationException) {             if (mutationStarted) states[key]?.let { publish(key, it.copy(phase = CheckoutPhase.Uncertain, message = "Request interrupted. Do not retry; use the merchant website.")) }
shop/src/main/java/com/vayunmathur/shop/network/ShopBackend.kt
diff --git a/shop/src/main/java/com/vayunmathur/shop/network/ShopBackend.kt b/shop/src/main/java/com/vayunmathur/shop/network/ShopBackend.ktindex e0454e3edb..04fdd79704 100644--- a/shop/src/main/java/com/vayunmathur/shop/network/ShopBackend.kt+++ b/shop/src/main/java/com/vayunmathur/shop/network/ShopBackend.kt@@ -37,6 +37,7 @@ interface ShopBackend {         title: String? = null,         selectedOptions: List<CatalogOptionSelection> = emptyList(),     ): Result<UcpProduct>+    suspend fun getProductByHandle(shop: String, handle: String): Result<UcpProduct>     suspend fun createCheckout(shop: String, lines: List<CartLine>, inputs: CheckoutInputs, idempotencyKey: String): Result<UcpCheckout>     suspend fun getCheckout(shop: String, sessionId: String): Result<UcpCheckout>     suspend fun updateCheckout(shop: String, sessionId: String, lines: List<CartLine>, inputs: CheckoutInputs, idempotencyKey: String): Result<UcpCheckout>@@ -103,6 +104,12 @@ internal object ShopHttpBackend : ShopBackend {         get(url).parse<ShopProductResponse>().product.toModel()     } +    override suspend fun getProductByHandle(shop: String, handle: String): Result<UcpProduct> = catching {+        require(shop.isNotBlank() && handle.isNotBlank()) { "Invalid product request" }+        val url = "$BASE/product?shop=${shop.encode()}&handle=${handle.encode()}"+        get(url).parse<ShopProductResponse>().product.toModel()+    }+     override suspend fun createCheckout(shop: String, lines: List<CartLine>, inputs: CheckoutInputs, idempotencyKey: String): Result<UcpCheckout> =         catching {             checkLines(lines, shop)
shop/src/main/java/com/vayunmathur/shop/platform/LinkDefaults.kt
diff --git a/shop/src/main/java/com/vayunmathur/shop/platform/LinkDefaults.kt b/shop/src/main/java/com/vayunmathur/shop/platform/LinkDefaults.ktnew file mode 100644index 0000000000..f5d7b7d55c--- /dev/null+++ b/shop/src/main/java/com/vayunmathur/shop/platform/LinkDefaults.kt@@ -0,0 +1,43 @@+package com.vayunmathur.shop.platform++import android.content.ActivityNotFoundException+import android.content.Context+import android.content.Intent+import android.content.pm.verify.domain.DomainVerificationManager+import android.content.pm.verify.domain.DomainVerificationUserState+import android.net.Uri+import android.provider.Settings+import androidx.core.content.edit++/**+ * Merchant links are declared without verification (we can't host assetlinks on merchant+ * sites), so Android only opens them here after the user selects them in "Open by default".+ */+object LinkDefaults {+    private const val PREFS = "shop_link_defaults"+    private const val KEY_DISMISSED = "dismissed"++    fun shouldPrompt(context: Context): Boolean {+        if (context.getSharedPreferences(PREFS, Context.MODE_PRIVATE).getBoolean(KEY_DISMISSED, false)) return false+        val manager = context.getSystemService(DomainVerificationManager::class.java) ?: return false+        val state = runCatching { manager.getDomainVerificationUserState(context.packageName) }.getOrNull()+            ?: return false+        return state.hostToStateMap.values.any { it == DomainVerificationUserState.DOMAIN_STATE_NONE }+    }++    fun openSettings(context: Context) {+        dismiss(context)+        val packageUri = Uri.parse("package:${context.packageName}")+        val openByDefault = Intent(Settings.ACTION_APP_OPEN_BY_DEFAULT_SETTINGS, packageUri)+        val appDetails = Intent(Settings.ACTION_APPLICATION_DETAILS_SETTINGS, packageUri)+        try {+            context.startActivity(openByDefault.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK))+        } catch (_: ActivityNotFoundException) {+            context.startActivity(appDetails.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK))+        }+    }++    fun dismiss(context: Context) {+        context.getSharedPreferences(PREFS, Context.MODE_PRIVATE).edit { putBoolean(KEY_DISMISSED, true) }+    }+}
shop/src/main/java/com/vayunmathur/shop/platform/ShopViewModel.kt
diff --git a/shop/src/main/java/com/vayunmathur/shop/platform/ShopViewModel.kt b/shop/src/main/java/com/vayunmathur/shop/platform/ShopViewModel.ktindex 7c13bc7698..3191291774 100644--- a/shop/src/main/java/com/vayunmathur/shop/platform/ShopViewModel.kt+++ b/shop/src/main/java/com/vayunmathur/shop/platform/ShopViewModel.kt@@ -6,12 +6,14 @@ import androidx.compose.runtime.mutableStateOf import androidx.compose.runtime.setValue import androidx.lifecycle.ViewModel import androidx.lifecycle.viewModelScope+import com.vayunmathur.shop.Route import com.vayunmathur.shop.data.CheckoutInputs import com.vayunmathur.shop.data.CheckoutPhase import com.vayunmathur.shop.data.NativeCheckoutState import com.vayunmathur.shop.domain.NativeCheckoutCoordinator import com.vayunmathur.shop.domain.PendingCheckoutSink import com.vayunmathur.shop.data.CartLine+import com.vayunmathur.shop.data.MerchantListing import com.vayunmathur.shop.data.OrderStore import com.vayunmathur.shop.data.PlacedOrder import com.vayunmathur.shop.data.ProfileRepository@@ -20,6 +22,8 @@ import com.vayunmathur.shop.data.ShopProfile import com.vayunmathur.shop.data.UcpCheckout import com.vayunmathur.shop.data.UcpProduct import com.vayunmathur.shop.data.message+import com.vayunmathur.shop.domain.MerchantLink+import com.vayunmathur.shop.domain.MerchantLinks import com.vayunmathur.shop.domain.MerchantUrls import com.vayunmathur.shop.domain.ProfileCheckout import com.vayunmathur.shop.network.ShopBackend@@ -34,8 +38,18 @@ class ShopViewModel( ) : ViewModel() {     var query by mutableStateOf("")         private set-    var searchShopDomain by mutableStateOf("")+    var scopeDomain by mutableStateOf<String?>(null)         private set+    var scopeName by mutableStateOf<String?>(null)+        private set+    var focusSearchRequest by mutableStateOf(0)+        private set+    var pendingRoute by mutableStateOf<Route?>(null)+        private set+    var linkedProducts by mutableStateOf<List<UcpProduct>>(emptyList())+        private set+    private var merchants: List<MerchantListing>? = null+    var launchLinkHandled = false     var results by mutableStateOf<List<UcpProduct>>(emptyList())         private set     var searching by mutableStateOf(false)@@ -124,7 +138,59 @@ class ShopViewModel(     }      fun updateQuery(value: String) { query = value }-    fun updateShopDomain(value: String) { searchShopDomain = value }++    fun consumePendingRoute() { pendingRoute = null }++    fun clearScope() {+        scopeDomain = null+        scopeName = null+        results = emptyList()+        search()+    }++    /** Opens a merchant web link: product pages in-app, anything else as a search scoped to that store. */+    fun openLink(url: String) {+        val link = MerchantLinks.parse(url) ?: return+        viewModelScope.launch {+            AppInit.awaitReady()+            val merchant = merchantFor(link.host)+            val domain = merchant?.domain ?: link.host+            val name = merchant?.name?.takeIf { it.isNotBlank() } ?: domain+            when (link) {+                is MerchantLink.Product -> backend.getProductByHandle(domain, link.handle).fold(+                    onSuccess = { product ->+                        val variant = product.variants.firstOrNull()+                        if (variant == null) {+                            scopedSearch(domain, name, link.handle.replace('-', ' '))+                        } else {+                            linkedProducts = (linkedProducts + product).takeLast(LINKED_PRODUCT_LIMIT)+                            val publisher = variant.shopDomain.ifBlank { product.shopDomain }+                            pendingRoute = Route.ProductDetail(variant.id, product.platformId, publisher)+                        }+                    },+                    onFailure = { scopedSearch(domain, name, link.handle.replace('-', ' ')) },+                )+                is MerchantLink.Search -> scopedSearch(domain, name, link.query)+                is MerchantLink.Merchant -> scopedSearch(domain, name, "")+            }+        }+    }++    private fun scopedSearch(domain: String, name: String, scopedQuery: String) {+        scopeDomain = domain+        scopeName = name+        query = scopedQuery+        results = emptyList()+        pendingRoute = Route.Search+        focusSearchRequest+++        if (scopedQuery.isNotBlank()) search()+    }++    private suspend fun merchantFor(host: String): MerchantListing? {+        val list = merchants ?: backend.listMerchants().getOrNull()?.also { merchants = it } ?: return null+        val bare = host.removePrefix("www.")+        return list.firstOrNull { it.domain == host } ?: list.firstOrNull { it.domain.removePrefix("www.") == bare }+    }      fun loadCart(context: Context) {         viewModelScope.launch { cart = ShopCartStore.getAll(context) }@@ -137,18 +203,14 @@ class ShopViewModel(     fun search() {         val q = query.trim()         if (q.isEmpty() || searching) return-        val shop = if (searchShopDomain.isBlank()) null else MerchantUrls.domain(searchShopDomain)-        if (searchShopDomain.isNotBlank() && shop == null) {-            searchError = "Enter a public HTTPS merchant domain without a path."-            return-        }+        val shop = scopeDomain         searching = true         searchError = null         results = emptyList()         viewModelScope.launch {             try {                 AppInit.awaitReady()-                backend.search(q, shop).fold(+                backend.search(q, shop, limit = SEARCH_LIMIT).fold(                     onSuccess = { results = it },                     onFailure = { searchError = it.toBackendMessage() },                 )@@ -178,6 +240,7 @@ class ShopViewModel(                 platformId = product.platformId,                 shopDomain = product.shopDomain,                 quantity = quantity,+                storeName = variant.storeName.ifBlank { product.storeName },             )         }         browserCheckouts = emptyList()@@ -220,4 +283,9 @@ class ShopViewModel(     private fun Throwable.toBackendMessage(): String =         (this as? ShopBackendException)?.error?.message()             ?: "Couldn't reach the store. Check your connection and try again."++    private companion object {+        const val SEARCH_LIMIT = 40+        const val LINKED_PRODUCT_LIMIT = 20+    } }
shop/src/main/java/com/vayunmathur/shop/ui/CartScreen.kt
diff --git a/shop/src/main/java/com/vayunmathur/shop/ui/CartScreen.kt b/shop/src/main/java/com/vayunmathur/shop/ui/CartScreen.ktindex 0a2ef9aedf..2bee0f5304 100644--- a/shop/src/main/java/com/vayunmathur/shop/ui/CartScreen.kt+++ b/shop/src/main/java/com/vayunmathur/shop/ui/CartScreen.kt@@ -33,7 +33,6 @@ import com.vayunmathur.library.ui.CircularProgressIndicator import com.vayunmathur.library.ui.IconShoppingCart import com.vayunmathur.library.ui.MaterialTheme import com.vayunmathur.library.ui.Text-import com.vayunmathur.library.ui.appBarScrollBehavior import com.vayunmathur.library.ui.rememberMessenger import com.vayunmathur.library.util.AppMessages import com.vayunmathur.shop.R@@ -48,7 +47,6 @@ import com.vayunmathur.shop.platform.ShopViewModel @Composable fun CartScreen(     viewModel: ShopViewModel,-    onBack: (() -> Unit)?,     onCheckout: () -> Unit, ) {     val messenger = rememberMessenger()@@ -60,11 +58,7 @@ fun CartScreen(     }     // Persistence context hoisted once: rows stay stateless and context-free.     val context = androidx.compose.ui.platform.LocalContext.current-    AppScaffold(-        title = stringResource(R.string.cart),-        onNavigateBack = onBack,-        scrollBehavior = appBarScrollBehavior(),-    ) { padding ->+    AppScaffold(topBar = {}) { padding ->         CartContent(             cart = viewModel.cart,             placing = viewModel.placingCheckout,@@ -115,7 +109,7 @@ internal fun CartContent(             byShop.forEach { (shop, lines) ->                 item(key = "header-$shop") {                     Text(-                        shop,+                        lines.first().displayName.ifBlank { "Unknown store" },                         style = MaterialTheme.typography.titleSmall,                         color = MaterialTheme.colorScheme.onSurfaceVariant,                     )
shop/src/main/java/com/vayunmathur/shop/ui/CheckoutScreen.kt
diff --git a/shop/src/main/java/com/vayunmathur/shop/ui/CheckoutScreen.kt b/shop/src/main/java/com/vayunmathur/shop/ui/CheckoutScreen.ktindex cccf104305..3a824d8e9d 100644--- a/shop/src/main/java/com/vayunmathur/shop/ui/CheckoutScreen.kt+++ b/shop/src/main/java/com/vayunmathur/shop/ui/CheckoutScreen.kt@@ -50,7 +50,7 @@ fun CheckoutScreen(viewModel: ShopViewModel, onBack: () -> Unit) {                 val state = viewModel.nativeCheckouts.firstOrNull { it.platformId == key.first && it.shopDomain == key.second }                     ?: NativeCheckoutState(key.first, key.second)                 item(key = "merchant-${key.first}-${key.second}") {-                    DetailSection(key.second.ifBlank { "Unknown store" }) {+                    DetailSection(lines.first().displayName.ifBlank { "Unknown store" }) {                         lines.forEach { line -> Text("${line.productTitle} x ${line.quantity}", style = MaterialTheme.typography.bodyMedium) }                         val editable = !state.busy && !viewModel.placingCheckout && state.phase !in setOf(CheckoutPhase.Uncertain, CheckoutPhase.Expired, CheckoutPhase.BrowserRequired)                         val profileInputs = viewModel.checkoutInputs(state)
shop/src/main/java/com/vayunmathur/shop/ui/MerchantDirectoryScreen.kt
diff --git a/shop/src/main/java/com/vayunmathur/shop/ui/MerchantDirectoryScreen.kt b/shop/src/main/java/com/vayunmathur/shop/ui/MerchantDirectoryScreen.ktdeleted file mode 100644index 0f46f8d604..0000000000--- a/shop/src/main/java/com/vayunmathur/shop/ui/MerchantDirectoryScreen.kt+++ /dev/null@@ -1,137 +0,0 @@-package com.vayunmathur.shop.ui--import androidx.compose.foundation.layout.Arrangement-import androidx.compose.foundation.layout.Column-import androidx.compose.foundation.layout.PaddingValues-import androidx.compose.foundation.layout.Row-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.runtime.getValue-import androidx.compose.runtime.mutableStateOf-import androidx.compose.runtime.remember-import androidx.compose.runtime.rememberCoroutineScope-import androidx.compose.runtime.setValue-import androidx.compose.ui.Modifier-import androidx.compose.ui.platform.LocalContext-import androidx.compose.ui.unit.dp-import com.vayunmathur.library.ui.AppScaffold-import com.vayunmathur.library.ui.Button-import com.vayunmathur.library.ui.Card-import com.vayunmathur.library.ui.CircularProgressIndicator-import com.vayunmathur.library.ui.CommonSearchBar-import com.vayunmathur.library.ui.MaterialTheme-import com.vayunmathur.library.ui.Text-import com.vayunmathur.library.ui.TextButton-import com.vayunmathur.library.ui.appBarScrollBehavior-import com.vayunmathur.shop.data.MerchantListing-import com.vayunmathur.shop.data.message-import com.vayunmathur.shop.network.ShopBackend-import com.vayunmathur.shop.network.ShopBackendException-import com.vayunmathur.shop.network.ShopHttpBackend-import com.vayunmathur.shop.platform.AppInit-import kotlinx.coroutines.launch--@Composable-fun MerchantDirectoryScreen(onMerchantSelected: (String) -> Unit) {-    val backend: ShopBackend = ShopHttpBackend-    val scope = rememberCoroutineScope()-    val context = LocalContext.current-    var rows by remember { mutableStateOf(emptyList<MerchantListing>()) }-    var query by remember { mutableStateOf("") }-    var loading by remember { mutableStateOf(false) }-    var loaded by remember { mutableStateOf(false) }-    var error by remember { mutableStateOf<String?>(null) }-    AppScaffold(title = "Merchants", scrollBehavior = appBarScrollBehavior()) { padding ->-        MerchantDirectoryContent(-            rows = rows,-            query = query,-            onQueryChange = { query = it },-            loaded = loaded,-            loading = loading,-            checking = null,-            error = error,-            onLoad = {-                if (!loading) scope.launch {-                    loading = true-                    error = null-                    try {-                        AppInit.awaitReady()-                        backend.listMerchants(refresh = loaded).fold(-                            onSuccess = { listings -> rows = listings; loaded = true },-                            onFailure = { failure -> error = (failure as? ShopBackendException)?.error?.message() ?: "Couldn't load the merchant directory." },-                        )-                    } finally { loading = false }-                }-            },-            // Compatibility is checked server-side on first search; the-            // directory entry is only a discovery lead.-            onUse = { row -> onMerchantSelected(row.domain) },-            onOpenSite = { openContinueUrl(context, it.siteUrl) },-            modifier = Modifier.fillMaxSize().padding(padding),-        )-    }-}--@Composable-internal fun MerchantDirectoryContent(-    rows: List<MerchantListing>,-    query: String,-    onQueryChange: (String) -> Unit,-    loaded: Boolean,-    loading: Boolean,-    checking: String?,-    error: String?,-    onLoad: () -> Unit,-    onUse: (MerchantListing) -> Unit,-    onOpenSite: (MerchantListing) -> Unit,-    modifier: Modifier = Modifier,-) {-    val matches = rows.filter {-        query.isBlank() || it.name.contains(query, true) || it.domain.contains(query, true)-    }.take(100)-    Column(modifier.fillMaxSize()) {-        Text(-            "Directory entries are discovery leads, not verified access or payment permission. Catalog compatibility is checked when you select a merchant.",-            style = MaterialTheme.typography.bodyMedium,-            modifier = Modifier.padding(16.dp),-        )-        Row(Modifier.fillMaxWidth().padding(horizontal = 16.dp), horizontalArrangement = Arrangement.SpaceBetween) {-            Text(if (loaded) "${rows.size} merchants cached" else "Load the public UCPList directory", modifier = Modifier.weight(1f))-            Button(onClick = onLoad, enabled = !loading && checking == null) {-                Text(if (loaded) "Refresh" else "Load")-            }-        }-        CommonSearchBar(value = query, onValueChange = onQueryChange, placeholder = "Filter merchants locally")-        if (loading) CircularProgressIndicator(modifier = Modifier.padding(16.dp))-        error?.let { Text(it, color = MaterialTheme.colorScheme.error, modifier = Modifier.padding(16.dp)) }-        if (loaded && matches.isEmpty()) Text("No matching merchants.", modifier = Modifier.padding(16.dp))-        LazyColumn(-            contentPadding = PaddingValues(16.dp),-            verticalArrangement = Arrangement.spacedBy(12.dp),-            modifier = Modifier.weight(1f),-        ) {-            items(matches, key = { "${it.id}|${it.domain}" }) { row ->-                Card(modifier = Modifier.fillMaxWidth()) {-                    Column(Modifier.padding(16.dp), verticalArrangement = Arrangement.spacedBy(6.dp)) {-                        Text(row.name, style = MaterialTheme.typography.titleMedium)-                        Text(row.domain, style = MaterialTheme.typography.bodyMedium)-                        Text("Directory status: ${row.directoryStatus.ifBlank { "unknown" }}. Not independently verified.", style = MaterialTheme.typography.bodySmall)-                        Row(horizontalArrangement = Arrangement.spacedBy(12.dp)) {-                            Button(onClick = { onUse(row) }, enabled = !loading && checking == null) {-                                Text(if (checking == row.id) "Checking..." else "Use merchant")-                            }-                            TextButton(onClick = { onOpenSite(row) }) { Text("Open site") }-                        }-                    }-                }-            }-        }-        if (rows.size > 100 && query.isBlank()) {-            Text("Showing the first 100. Filter to find another merchant.", modifier = Modifier.padding(16.dp))-        }-    }-}
shop/src/main/java/com/vayunmathur/shop/ui/OrdersScreen.kt
diff --git a/shop/src/main/java/com/vayunmathur/shop/ui/OrdersScreen.kt b/shop/src/main/java/com/vayunmathur/shop/ui/OrdersScreen.ktindex 3b0f69ec11..b47e22f58e 100644--- a/shop/src/main/java/com/vayunmathur/shop/ui/OrdersScreen.kt+++ b/shop/src/main/java/com/vayunmathur/shop/ui/OrdersScreen.kt@@ -80,7 +80,7 @@ private fun OrderRow(order: PlacedOrder, onOpen: () -> Unit) {                     style = MaterialTheme.typography.titleSmall,                 )                 Text(stringResource(R.string.checkout_pending), style = MaterialTheme.typography.labelMedium)-                if (order.shopDomain.isNotBlank()) Text(order.shopDomain, style = MaterialTheme.typography.bodySmall)+                if (order.displayName.isNotBlank()) Text(order.displayName, style = MaterialTheme.typography.bodySmall)                 Spacer(Modifier.height(2.dp))                 Text(                     DateFormat.getDateTimeInstance(DateFormat.MEDIUM, DateFormat.SHORT)
shop/src/main/java/com/vayunmathur/shop/ui/ProductScreen.kt
diff --git a/shop/src/main/java/com/vayunmathur/shop/ui/ProductScreen.kt b/shop/src/main/java/com/vayunmathur/shop/ui/ProductScreen.ktindex 27b84eeaaf..491e908fe2 100644--- a/shop/src/main/java/com/vayunmathur/shop/ui/ProductScreen.kt+++ b/shop/src/main/java/com/vayunmathur/shop/ui/ProductScreen.kt@@ -67,7 +67,7 @@ fun ProductScreen(     val context = LocalContext.current     val messenger = rememberMessenger()     var product by remember(variantId, platformId, shopDomain) {-        mutableStateOf(viewModel.results.firstOrNull { candidate ->+        mutableStateOf((viewModel.results + viewModel.linkedProducts).firstOrNull { candidate ->             candidate.platformId == platformId && candidate.variants.any {                 it.id == variantId && (candidate.shopDomain == shopDomain || it.shopDomain == shopDomain)             }@@ -242,11 +242,8 @@ internal fun ProductDetailContent(             }         }         item {-            DetailSection("Publishing store") {-                Text(storeName.ifBlank { storeDomain.ifBlank { "Publishing store" } }, style = MaterialTheme.typography.titleMedium)-                if (storeName.isNotBlank()) {-                    Text(storeDomain.ifBlank { "Store domain unavailable" }, style = MaterialTheme.typography.bodyMedium)-                }+            DetailSection("Store") {+                Text(storeName.ifBlank { storeDomain.ifBlank { "Store" } }, style = MaterialTheme.typography.titleMedium)             }         }         item {
shop/src/main/java/com/vayunmathur/shop/ui/SearchScreen.kt
diff --git a/shop/src/main/java/com/vayunmathur/shop/ui/SearchScreen.kt b/shop/src/main/java/com/vayunmathur/shop/ui/SearchScreen.ktindex f07d0f7640..c03fb9d1db 100644--- a/shop/src/main/java/com/vayunmathur/shop/ui/SearchScreen.kt+++ b/shop/src/main/java/com/vayunmathur/shop/ui/SearchScreen.kt@@ -6,46 +6,61 @@ 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.WindowInsets 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.layout.width+import androidx.compose.foundation.layout.statusBars+import androidx.compose.foundation.layout.windowInsetsPadding 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.mutableStateOf+import androidx.compose.runtime.remember+import androidx.compose.runtime.setValue import androidx.compose.ui.Alignment import androidx.compose.ui.Modifier+import androidx.compose.ui.focus.FocusRequester+import androidx.compose.ui.focus.focusRequester import androidx.compose.ui.layout.ContentScale+import androidx.compose.ui.platform.LocalContext+import androidx.compose.ui.platform.LocalFocusManager import androidx.compose.ui.res.stringResource import androidx.compose.ui.unit.dp import com.vayunmathur.library.image.compose.AsyncImage import com.vayunmathur.library.ui.AppScaffold-import com.vayunmathur.library.ui.Button import com.vayunmathur.library.ui.Card import com.vayunmathur.library.ui.CircularProgressIndicator-import com.vayunmathur.library.ui.CommonSearchBar+import com.vayunmathur.library.ui.IconButton+import com.vayunmathur.library.ui.IconClose+import com.vayunmathur.library.ui.IconSearch+import com.vayunmathur.library.ui.InputChip import com.vayunmathur.library.ui.MaterialTheme+import com.vayunmathur.library.ui.SearchBarInputField import com.vayunmathur.library.ui.Text-import com.vayunmathur.library.ui.appBarScrollBehavior+import com.vayunmathur.library.ui.TextButton import com.vayunmathur.library.ui.rememberMessenger import com.vayunmathur.shop.R import com.vayunmathur.shop.data.UcpProduct import com.vayunmathur.shop.domain.MoneyFormat+import com.vayunmathur.shop.platform.LinkDefaults import com.vayunmathur.shop.platform.ShopViewModel  /**- * Global Catalog search: query → product grid. Tapping a card opens the product detail- * for the first variant; the detail resolves the exact variant.+ * Full search: the query is matched to stores server-side, then searched across them.+ * Tapping a card opens the product detail for the first variant; the detail resolves the exact variant.  */ @Composable fun SearchScreen(     viewModel: ShopViewModel,     onProductClick: (variantId: String, platformId: String, shopDomain: String) -> Unit, ) {+    val context = LocalContext.current     val messenger = rememberMessenger()     LaunchedEffect(viewModel.searchError) {         viewModel.searchError?.let { error ->@@ -53,27 +68,29 @@ fun SearchScreen(             viewModel.dismissSearchError()         }     }-    AppScaffold(-        title = stringResource(R.string.app_name),-        scrollBehavior = appBarScrollBehavior(),-    ) { padding ->-        SearchContent(-            query = viewModel.query,-            onQueryChange = viewModel::updateQuery,-            searching = viewModel.searching,-            results = viewModel.results,-            onSearch = viewModel::search,-            onProductClick = onProductClick,-            modifier = Modifier.fillMaxSize().padding(padding),-            shopDomain = viewModel.searchShopDomain,-            onShopDomainChange = viewModel::updateShopDomain,-        )-    }+    var showLinkPrompt by remember { mutableStateOf(LinkDefaults.shouldPrompt(context)) }+    SearchContent(+        query = viewModel.query,+        onQueryChange = viewModel::updateQuery,+        searching = viewModel.searching,+        results = viewModel.results,+        onSearch = viewModel::search,+        onProductClick = onProductClick,+        scopeName = viewModel.scopeName,+        onClearScope = viewModel::clearScope,+        focusRequest = viewModel.focusSearchRequest,+        linkPrompt = if (!showLinkPrompt) null else LinkPrompt(+            onOpenSettings = { LinkDefaults.openSettings(context); showLinkPrompt = false },+            onDismiss = { LinkDefaults.dismiss(context); showLinkPrompt = false },+        ),+    ) } +internal data class LinkPrompt(val onOpenSettings: () -> Unit, val onDismiss: () -> Unit)+ /**- * The search page without ViewModel or scaffold, so previews and screenshot tests can- * render it with fixture data. Search stays explicit (button, not per-keystroke): the+ * The search page without ViewModel, so previews and screenshot tests can render it with+ * fixture data. Search stays explicit (IME action or search button, not per-keystroke): the  * anonymous tier shares one IP pool and every keystroke would burn shared quota.  */ @Composable@@ -85,43 +102,86 @@ internal fun SearchContent(     onSearch: () -> Unit,     onProductClick: (variantId: String, platformId: String, shopDomain: String) -> Unit,     modifier: Modifier = Modifier,-    shopDomain: String = "",-    onShopDomainChange: (String) -> Unit = {},+    scopeName: String? = null,+    onClearScope: () -> Unit = {},+    focusRequest: Int = 0,+    linkPrompt: LinkPrompt? = null, ) {-    Column(modifier.fillMaxSize()) {-        com.vayunmathur.library.ui.OutlinedTextField(-            value = shopDomain,-            onValueChange = onShopDomainChange,-            label = { Text(stringResource(R.string.store_domain)) },-            supportingText = { Text(stringResource(R.string.store_domain_hint)) },-            singleLine = true,-            modifier = Modifier.fillMaxWidth().padding(horizontal = 16.dp),-        )-        Row(-            modifier = Modifier.fillMaxWidth(),-            verticalAlignment = Alignment.CenterVertically,-        ) {-            CommonSearchBar(-                value = query,-                onValueChange = onQueryChange,-                placeholder = stringResource(R.string.search_products),+    AppScaffold(+        modifier = modifier,+        topBar = { SearchTopBar(query, onQueryChange, onSearch, enabled = !searching, focusRequest = focusRequest) },+    ) { padding ->+        Column(Modifier.fillMaxSize().padding(padding)) {+            linkPrompt?.let { LinkPromptCard(it) }+            scopeName?.let { name ->+                InputChip(+                    selected = true,+                    onClick = onClearScope,+                    label = { Text("Results from $name") },+                    trailingIcon = { IconClose() },+                    modifier = Modifier.padding(horizontal = 16.dp),+                )+            }+            ProductResults(+                results = results,+                searching = searching,+                onProductClick = onProductClick,                 modifier = Modifier.weight(1f),             )-            Button(-                onClick = onSearch,-                enabled = !searching && query.isNotBlank(),-                modifier = Modifier.padding(end = 16.dp),-            ) {-                Text(stringResource(R.string.search))+        }+    }+}++@Composable+private fun SearchTopBar(+    query: String,+    onQueryChange: (String) -> Unit,+    onSearch: () -> Unit,+    enabled: Boolean,+    focusRequest: Int,+) {+    val focusManager = LocalFocusManager.current+    val focusRequester = remember { FocusRequester() }+    LaunchedEffect(focusRequest) { if (focusRequest > 0) focusRequester.requestFocus() }+    val submit = {+        if (enabled && query.isNotBlank()) {+            focusManager.clearFocus()+            onSearch()+        }+    }+    SearchBarInputField(+        query = query,+        onQueryChange = onQueryChange,+        onSearch = { submit() },+        expanded = false,+        onExpandedChange = {},+        modifier = Modifier+            .fillMaxWidth()+            .windowInsetsPadding(WindowInsets.statusBars)+            .padding(horizontal = 16.dp, vertical = 8.dp)+            .focusRequester(focusRequester),+        placeholder = { Text(stringResource(R.string.search_products)) },+        leadingIcon = { IconButton(onClick = submit) { IconSearch() } },+        trailingIcon = if (query.isEmpty()) null else {+            { IconButton(onClick = { onQueryChange("") }) { IconClose() } }+        },+    )+}++@Composable+private fun LinkPromptCard(prompt: LinkPrompt) {+    Card(modifier = Modifier.fillMaxWidth().padding(horizontal = 16.dp, vertical = 8.dp)) {+        Column(Modifier.padding(16.dp)) {+            Text("Open store links in Shop", style = MaterialTheme.typography.titleSmall)+            Text(+                "In the next screen, tap \"Add link\" and select all to open store links here.",+                style = MaterialTheme.typography.bodySmall,+            )+            Row(Modifier.fillMaxWidth(), horizontalArrangement = Arrangement.End) {+                TextButton(onClick = prompt.onDismiss) { Text("Not now") }+                TextButton(onClick = prompt.onOpenSettings) { Text("Open settings") }             }-            Spacer(Modifier.width(8.dp))         }-        ProductResults(-            results = results,-            searching = searching,-            onProductClick = onProductClick,-            modifier = Modifier.weight(1f),-        )     } } @@ -162,7 +222,7 @@ private fun ProductResults(         horizontalArrangement = Arrangement.spacedBy(12.dp),         modifier = modifier,     ) {-        items(results, key = { "${it.platformId}|${it.shopDomain}|${it.id}" }) { product ->+        items(results.distinctBy { it.gridKey }, key = { it.gridKey }) { product ->             ProductCard(product = product, onClick = {                 val variant = product.variants.firstOrNull() ?: return@ProductCard                 onProductClick(variant.id, product.platformId, variant.shopDomain.ifBlank { product.shopDomain })@@ -171,6 +231,8 @@ private fun ProductResults(     } } +private val UcpProduct.gridKey: String get() = "$platformId|$shopDomain|$id"+ @Composable private fun ProductCard(product: UcpProduct, onClick: () -> Unit) {     Card(onClick = onClick) {@@ -196,6 +258,14 @@ private fun ProductCard(product: UcpProduct, onClick: () -> Unit) {                     style = MaterialTheme.typography.bodyMedium,                     color = MaterialTheme.colorScheme.primary,                 )+                product.storeName.takeIf { it.isNotBlank() }?.let {+                    Text(+                        text = it,+                        style = MaterialTheme.typography.bodySmall,+                        color = MaterialTheme.colorScheme.onSurfaceVariant,+                        maxLines = 1,+                    )+                }             }         }     }
shop/src/main/java/com/vayunmathur/shop/ui/ShopTabs.kt
diff --git a/shop/src/main/java/com/vayunmathur/shop/ui/ShopTabs.kt b/shop/src/main/java/com/vayunmathur/shop/ui/ShopTabs.ktindex 4a7763c679..e653a6c21f 100644--- a/shop/src/main/java/com/vayunmathur/shop/ui/ShopTabs.kt+++ b/shop/src/main/java/com/vayunmathur/shop/ui/ShopTabs.kt@@ -3,14 +3,11 @@ package com.vayunmathur.shop.ui import androidx.compose.foundation.pager.rememberPagerState import androidx.compose.runtime.Composable import androidx.compose.runtime.LaunchedEffect-import androidx.compose.runtime.rememberCoroutineScope-import kotlinx.coroutines.launch import androidx.compose.ui.platform.LocalContext import androidx.compose.ui.res.stringResource import com.vayunmathur.library.ui.IconPerson import com.vayunmathur.library.ui.IconReceipt import com.vayunmathur.library.ui.IconSearch-import com.vayunmathur.library.ui.IconStore import com.vayunmathur.library.ui.IconShoppingCart import com.vayunmathur.library.ui.PagerTab import com.vayunmathur.library.ui.TabStyle@@ -25,20 +22,17 @@ fun ShopTabs(viewModel: ShopViewModel, onProductClick: (String, String, String)         viewModel.loadCart(context)         viewModel.loadOrders(context)     }-    val scope = rememberCoroutineScope()-    val pagerState = rememberPagerState(initialPage = 0, pageCount = { 5 })+    val pagerState = rememberPagerState(initialPage = 0, pageCount = { 4 })+    // A scoped search opened from a merchant link always lands on the Search tab.+    LaunchedEffect(viewModel.focusSearchRequest) {+        if (viewModel.focusSearchRequest > 0) pagerState.animateScrollToPage(0)+    }     val tabs = listOf(         PagerTab(stringResource(R.string.search), { IconSearch() }) {             SearchScreen(viewModel, onProductClick)         },-        PagerTab("Merchants", { IconStore() }) {-            MerchantDirectoryScreen { domain ->-                viewModel.updateShopDomain(domain)-                scope.launch { pagerState.animateScrollToPage(0) }-            }-        },         PagerTab(stringResource(R.string.cart), { IconShoppingCart() }) {-            CartScreen(viewModel, onBack = null, onCheckout = onCheckout)+            CartScreen(viewModel, onCheckout = onCheckout)         },         PagerTab(stringResource(R.string.orders), { IconReceipt() }) {             OrdersScreen(viewModel)
shop/src/main/res/values/strings.xml
diff --git a/shop/src/main/res/values/strings.xml b/shop/src/main/res/values/strings.xmlindex abc6a94617..92414cea6c 100644--- a/shop/src/main/res/values/strings.xml+++ b/shop/src/main/res/values/strings.xml@@ -12,8 +12,6 @@     <string name="no_orders_yet">No checkout history yet</string>     <string name="continue_in_browser">Continue in browser</string>     <string name="place_order">Prepare checkout</string>-    <string name="store_domain">Merchant domain (optional)</string>-    <string name="store_domain_hint">Leave empty for Shopify search, or enter a UCP merchant domain.</string>     <string name="estimated_subtotal">Estimated subtotal</string>     <string name="checkout_pending">Payment not confirmed</string>     <string name="checkout_handoff_notice">Review final prices, shipping and payment on the merchant site. Cart items remain until you remove them.</string>
shop/src/screenshotTest/kotlin/com/vayunmathur/shop/ui/CheckoutMetadataPreviews.kt
diff --git a/shop/src/screenshotTest/kotlin/com/vayunmathur/shop/ui/CheckoutMetadataPreviews.kt b/shop/src/screenshotTest/kotlin/com/vayunmathur/shop/ui/CheckoutMetadataPreviews.ktindex 510f721e17..669c2a9a51 100644--- a/shop/src/screenshotTest/kotlin/com/vayunmathur/shop/ui/CheckoutMetadataPreviews.kt+++ b/shop/src/screenshotTest/kotlin/com/vayunmathur/shop/ui/CheckoutMetadataPreviews.kt@@ -55,9 +55,9 @@ class CheckoutMetadataPreviews {     )      @PreviewTest-    @Preview(name = "4-checkout", group = "phone", widthDp = 360, heightDp = 780)+    @Preview(name = "3-checkout", group = "phone", widthDp = 360, heightDp = 780)     @Composable-    fun Preview4Checkout() {+    fun Preview3Checkout() {         DynamicTheme(darkTheme = false) {             AppScaffold(title = "Checkout review", scrollBehavior = appBarScrollBehavior()) { padding ->                 CheckoutReviewContent(
shop/src/screenshotTest/kotlin/com/vayunmathur/shop/ui/DirectoryMetadataPreviews.kt
diff --git a/shop/src/screenshotTest/kotlin/com/vayunmathur/shop/ui/DirectoryMetadataPreviews.kt b/shop/src/screenshotTest/kotlin/com/vayunmathur/shop/ui/DirectoryMetadataPreviews.ktdeleted file mode 100644index 42ad92278d..0000000000--- a/shop/src/screenshotTest/kotlin/com/vayunmathur/shop/ui/DirectoryMetadataPreviews.kt+++ /dev/null@@ -1,40 +0,0 @@-package com.vayunmathur.shop.ui--import androidx.compose.foundation.layout.fillMaxSize-import androidx.compose.foundation.layout.padding-import androidx.compose.runtime.Composable-import androidx.compose.ui.Modifier-import androidx.compose.ui.tooling.preview.Preview-import com.android.tools.screenshot.PreviewTest-import com.vayunmathur.library.ui.AppScaffold-import com.vayunmathur.library.ui.DynamicTheme-import com.vayunmathur.library.ui.appBarScrollBehavior-import com.vayunmathur.shop.data.MerchantListing--class DirectoryMetadataPreviews {-    @PreviewTest-    @Preview(name = "3-merchants", group = "phone", widthDp = 360, heightDp = 780)-    @Composable-    fun Preview3Merchants() {-        DynamicTheme(darkTheme = false) {-            AppScaffold(title = "Merchants", scrollBehavior = appBarScrollBehavior()) { padding ->-                MerchantDirectoryContent(-                    rows = listOf(-                        MerchantListing("trail", "Trail Supply", "trail.example", "https://trail.example", directoryStatus = "live"),-                        MerchantListing("home", "Home Goods", "home.example", "https://home.example", directoryStatus = "pending"),-                    ),-                    query = "",-                    onQueryChange = {},-                    loaded = true,-                    loading = false,-                    checking = null,-                    error = null,-                    onLoad = {},-                    onUse = {},-                    onOpenSite = {},-                    modifier = Modifier.fillMaxSize().padding(padding),-                )-            }-        }-    }-}
shop/src/screenshotTest/kotlin/com/vayunmathur/shop/ui/MetadataPreviews.kt
diff --git a/shop/src/screenshotTest/kotlin/com/vayunmathur/shop/ui/MetadataPreviews.kt b/shop/src/screenshotTest/kotlin/com/vayunmathur/shop/ui/MetadataPreviews.ktindex 47abb12623..5c077c3e1e 100644--- a/shop/src/screenshotTest/kotlin/com/vayunmathur/shop/ui/MetadataPreviews.kt+++ b/shop/src/screenshotTest/kotlin/com/vayunmathur/shop/ui/MetadataPreviews.kt@@ -5,7 +5,6 @@ import androidx.compose.foundation.layout.fillMaxSize import androidx.compose.foundation.layout.padding import androidx.compose.ui.Modifier import com.vayunmathur.library.ui.AppScaffold-import com.vayunmathur.library.ui.appBarScrollBehavior import androidx.compose.ui.tooling.preview.Preview import com.android.tools.screenshot.PreviewTest import com.vayunmathur.library.ui.DynamicTheme@@ -57,6 +56,7 @@ class MetadataPreviews {             priceRangeMax = Money(14999, "USD"),             platformId = "shopify",             shopDomain = "example.myshopify.com",+            storeName = "Trail Co.",             variants = variants,             checkoutEligible = true,         ),@@ -68,6 +68,7 @@ class MetadataPreviews {             priceRangeMax = Money(18900, "USD"),             platformId = "shopify",             shopDomain = "example.myshopify.com",+            storeName = "Trail Co.",             variants = listOf(                 ProductVariant(                     id = "gid://shopify/ProductVariant/21",@@ -87,6 +88,7 @@ class MetadataPreviews {             unitPrice = Money(12999, "USD"),             platformId = "shopify",             shopDomain = "example.myshopify.com",+            storeName = "Trail Co.",             quantity = 1,         ),         CartLine(@@ -96,6 +98,7 @@ class MetadataPreviews {             unitPrice = Money(18900, "USD"),             platformId = "shopify",             shopDomain = "example.myshopify.com",+            storeName = "Trail Co.",             quantity = 2,         ),     )@@ -105,17 +108,15 @@ class MetadataPreviews {     @Composable     fun Preview1Search() {         DynamicTheme(darkTheme = false) {-            AppScaffold(title = "Shop", scrollBehavior = appBarScrollBehavior()) { padding ->-                SearchContent(-                    query = "trail shoes",-                    onQueryChange = {},-                    searching = false,-                    results = products,-                    onSearch = {},-                    onProductClick = { _, _, _ -> },-                    modifier = Modifier.fillMaxSize().padding(padding),-                )-            }+            SearchContent(+                query = "trail shoes",+                onQueryChange = {},+                searching = false,+                results = products,+                onSearch = {},+                onProductClick = { _, _, _ -> },+                modifier = Modifier.fillMaxSize(),+            )         }     } @@ -124,7 +125,7 @@ class MetadataPreviews {     @Composable     fun Preview2Cart() {         DynamicTheme(darkTheme = false) {-            AppScaffold(title = "Cart", scrollBehavior = appBarScrollBehavior()) { padding ->+            AppScaffold(topBar = {}) { padding ->                 CartContent(cart = cart, modifier = Modifier.fillMaxSize().padding(padding))             }         }
shop/src/screenshotTest/kotlin/com/vayunmathur/shop/ui/ProductMetadataPreviews.kt
diff --git a/shop/src/screenshotTest/kotlin/com/vayunmathur/shop/ui/ProductMetadataPreviews.kt b/shop/src/screenshotTest/kotlin/com/vayunmathur/shop/ui/ProductMetadataPreviews.ktindex b414e6b359..bfd49a2c5f 100644--- a/shop/src/screenshotTest/kotlin/com/vayunmathur/shop/ui/ProductMetadataPreviews.kt+++ b/shop/src/screenshotTest/kotlin/com/vayunmathur/shop/ui/ProductMetadataPreviews.kt@@ -48,9 +48,9 @@ class ProductMetadataPreviews {     )      @PreviewTest-    @Preview(name = "5-product", group = "phone", widthDp = 360, heightDp = 780)+    @Preview(name = "4-product", group = "phone", widthDp = 360, heightDp = 780)     @Composable-    fun Preview5Product() {+    fun Preview4Product() {         DynamicTheme(darkTheme = false) {             AppScaffold(title = product.title, scrollBehavior = appBarScrollBehavior()) { padding ->                 ProductDetailContent(
shop/src/test/java/com/vayunmathur/shop/domain/MerchantLinksTest.kt
diff --git a/shop/src/test/java/com/vayunmathur/shop/domain/MerchantLinksTest.kt b/shop/src/test/java/com/vayunmathur/shop/domain/MerchantLinksTest.ktnew file mode 100644index 0000000000..147f9287ea--- /dev/null+++ b/shop/src/test/java/com/vayunmathur/shop/domain/MerchantLinksTest.kt@@ -0,0 +1,42 @@+package com.vayunmathur.shop.domain++import com.vayunmathur.shop.data.CartLine+import com.vayunmathur.shop.data.PlacedOrder+import kotlinx.serialization.json.Json+import kotlin.test.Test+import kotlin.test.assertEquals+import kotlin.test.assertNull++class MerchantLinksTest {+    @Test+    fun productLinksYieldTheHandle() {+        assertEquals(MerchantLink.Product("www.allbirds.com", "tree-runner"),+            MerchantLinks.parse("https://www.allbirds.com/products/tree-runner?variant=123"))+        assertEquals(MerchantLink.Product("allbirds.com", "tree-runner"),+            MerchantLinks.parse("https://allbirds.com/collections/men/products/Tree-Runner/"))+    }++    @Test+    fun searchAndCollectionLinksBecomeScopedQueries() {+        assertEquals(MerchantLink.Search("allbirds.com", "wool socks"), MerchantLinks.parse("https://allbirds.com/search?q=wool+socks"))+        assertEquals(MerchantLink.Search("allbirds.com", "mens runners"), MerchantLinks.parse("https://allbirds.com/collections/mens-runners"))+        assertEquals(MerchantLink.Merchant("allbirds.com"), MerchantLinks.parse("https://allbirds.com/collections/all"))+        assertEquals(MerchantLink.Merchant("allbirds.com"), MerchantLinks.parse("http://allbirds.com/pages/about"))+    }++    @Test+    fun rejectsNonWebAndLocalLinks() {+        listOf("intent://allbirds.com/products/x", "https://localhost/products/x", "https://[email protected]/", "not a url")+            .forEach { assertNull(MerchantLinks.parse(it), it) }+    }++    @Test+    fun legacyCartAndOrderJsonFallBackToDomain() {+        val json = Json { ignoreUnknownKeys = true }+        val line = json.decodeFromString<CartLine>("""{"variantId":"v","shopDomain":"allbirds.com"}""")+        assertEquals("", line.storeName)+        assertEquals("allbirds.com", line.displayName)+        assertEquals("Allbirds", line.copy(storeName = "Allbirds").displayName)+        assertEquals("allbirds.com", json.decodeFromString<PlacedOrder>("""{"checkoutId":"c","shopDomain":"allbirds.com"}""").displayName)+    }+}