diff --git a/.claude/skills/ani-kickoff/SKILL.md b/.claude/skills/ani-kickoff/SKILL.md index cc3ac2c7..ed606b94 100644 --- a/.claude/skills/ani-kickoff/SKILL.md +++ b/.claude/skills/ani-kickoff/SKILL.md @@ -242,7 +242,7 @@ than saying it was the only thing considered. Check candidate approaches against the conventions that actually bite here: -- **DI lifetimes** — services and flyout PageModels are singleton; pages and +- **DI lifetimes** — services and tab PageModels are singleton; pages and details PageModels are transient. Getting this wrong produces state that leaks across navigations or is silently discarded. See `/project-architecture`. - **Navigation** — routes plus lightweight query params, never full objects. diff --git a/.claude/skills/project-architecture/SKILL.md b/.claude/skills/project-architecture/SKILL.md index cccba8d1..0e4ecab9 100644 --- a/.claude/skills/project-architecture/SKILL.md +++ b/.claude/skills/project-architecture/SKILL.md @@ -10,17 +10,17 @@ description: "AniSprinkles project architecture reference: DI lifetimes, page/Pa | Registration | Lifetime | | ------------------------------------------------------------------------------------------------------------------------- | -------------------------------------------------------------- | | `ErrorReportService`, `HttpClient`, `IAuthService`, `IAniListClient`, `IAiringNotificationService`, `IOutageStateService`, `INavigationService`, `IUserFeedback` | Singleton | -| `MyAnimePageModel`, `DiscoverPageModel`, `SettingsPageModel` | **Singleton** (survive page recreation across flyout switches) | +| `MyAnimePageModel`, `DiscoverPageModel`, `SearchPageModel`, `SettingsPageModel` | **Singleton** (survive page recreation across tab switches) | | `LoggingHandler`, `AniListRateLimitHandler` | Transient | `IAniListClient` resolves to `CachingAniListClient` wrapping the concrete `AniListClient` (session-lifetime in-memory cache of character/staff reads, with request coalescing). The shared `HttpClient` pipeline is `AniListRateLimitHandler` → `LoggingHandler` → `HttpClientHandler`, so every AniList call is serialized and 429/`Retry-After`-aware app-wide. -| `MyAnimePage`, `DiscoverPage`, `SettingsPage`, `MediaDetailsPageModel`, `MediaDetailsPage`, `StaffDetailsPageModel`, `StaffDetailsPage`, `CharacterDetailsPageModel`, `CharacterDetailsPage`, `StudioDetailsPageModel`, `StudioDetailsPage`, `MediaBrowsePageModel`, `MediaBrowsePage` | Transient | +| `MyAnimePage`, `DiscoverPage`, `SearchPage`, `FeedPage`, `MyMangaPage`, `SettingsPage`, `MediaDetailsPageModel`, `MediaDetailsPage`, `StaffDetailsPageModel`, `StaffDetailsPage`, `CharacterDetailsPageModel`, `CharacterDetailsPage`, `StudioDetailsPageModel`, `StudioDetailsPage`, `MediaBrowsePageModel`, `MediaBrowsePage` | Transient | ## Page ↔ PageModel Binding Two-constructor pattern: parameterless (for XAML tooling) + DI constructor. `ServiceProviderHelper` provides `IServiceProvider` fallback via `IPlatformApplication.Current.Services` when `Application.Current.Handler` is not ready during Shell startup. -## OnAppearing Three-Branch Pattern (all flyout pages) +## OnAppearing Three-Branch Pattern (all tab pages) 1. Content alive → background refresh 2. Content gone + `HasLoadedData` → immediate rebuild + background refresh @@ -30,7 +30,8 @@ See `MyAnimePage.xaml.cs` and `SettingsPage.xaml.cs` for reference implementatio ## Discover / Browse / Search -- `DiscoverPageModel` (singleton): one aliased `DiscoverSections` request seeds every row (a `DiscoverRow` wrapping a `PaginatedSection`); rows then page themselves horizontally through `BrowseAnimePageAsync` (one request per row-page) via the shared `DiscoverSectionFetch` helper. Card badges follow the row's sort via `MediaMetricBadges.ForMediaSort`. Search is revealed by a toolbar icon (same toggle pattern as My Anime); debounced (600 ms, 2+ chars) queries swap the rows for a `PaginatedSection` results list via visibility (rows stay alive underneath). +- `DiscoverPageModel` (singleton): one aliased `DiscoverSections` request seeds every row (a `DiscoverRow` wrapping a `PaginatedSection`); rows then page themselves horizontally through `BrowseAnimePageAsync` (one request per row-page) via the shared `DiscoverSectionFetch` helper. Card badges follow the row's sort via `MediaMetricBadges.ForMediaSort`. Discover holds no search — it moved to its own tab in #43. +- `SearchPageModel` (singleton): global anime search on the Search tab, extracted from `DiscoverPageModel`. Debounced (600 ms, 2+ chars) queries seed a `PaginatedSection` via `SearchAnimePageAsync`; a keystroke cancels the pending or in-flight fetch, and `_activeSearchQuery` guards a superseded response from landing. Four visibility states: idle prompt / spinner / results / no matches. The singleton keeps the query across tab switches on purpose; `OnAppearingAsync` re-runs it when an auth or adult-toggle flip has changed what the results should contain. Long-press goes through its own `EntryActionCoordinator`, writing mutations back onto matching results. - `MediaBrowsePage` ("View All", transient): `DeferredContentLoader` + one `PaginatedSection` over the same `DiscoverSectionFetch`; `DiscoverSectionDefinitions` is the single source of truth for section title/sort/filters/format/rank. Has the My Anime view-mode switcher; the mode persists to the shared `ListViewModePreference` key, so My Anime and View All always match (My Anime re-syncs in `OnAppearing`). - `BrowseTemplates.xaml` (merged in App.xaml) holds the shared templates: `BrowseMediaRowTemplate` (Standard, also used by search results), `BrowseMediaLargeTemplate` (2-col grid), `BrowseMediaCompactTemplate`, plus `ListStatusPillStyle` — the ONE on-list status pill style. Rows/grid cards overlay it inline (their own layout); the 130×170 carousel cards get it for free from `CoverImage` (`ListStatusText`/`ListStatusColor` props), which is the shared cover used by the Discover carousel AND every detail-page media carousel (relations, recommendations, studio productions, staff production roles, character appearances). Those detail pages send the viewer token so `mediaListEntry` is populated. Tap commands resolve from the hosting CollectionView's BindingContext (`NavigateToMediaCommand`). - `EntryActionCoordinator` (`PageModels/`) owns the long-press action flows (menu, add/move/rate/edit-progress/complete/remove, persistence, toasts/snackbars) for My Anime AND the browse surfaces; page models supply `EntryActionHost` callbacks (optimistic removal, reload vs in-place chip update, error details). `CollectionViewLongPress` (`Views/`) is the reusable Android RecyclerView long-press hook for flat CollectionViews; navigate commands call `ShouldSuppressTap()` to swallow the synthetic tap that follows a long press. @@ -49,11 +50,11 @@ Spinner-first flow: lightweight shell page appears immediately, full content vie ## Navigation -Shell flyout (`my-anime`, `discover`, `settings`). Details routes registered in `AppShell.xaml.cs`: `media-details` → `MediaDetailsPage`, `staff-details` → `StaffDetailsPage`, `character-details` → `CharacterDetailsPage`, `studio-details` → `StudioDetailsPage`, `media-browse` → `MediaBrowsePage` (Discover "View All"; takes a `section` enum-name param decoded against `DiscoverSectionDefinitions`). Navigate via `Shell.Current.GoToAsync` (or the injected `INavigationService`) with lightweight query params (`mediaId` / `staffId` / `characterId` / `studioId` / `section` + trace IDs) — never pass full model objects. Rapid-tap prevention on My Anime → details. Default Shell back behavior — no custom Android back overrides. +Shell bottom tab bar (`my-anime` shown as "Library", `discover`, `search`, `feed`, `settings`). The Library tab holds two `ShellContent`s (`anime`, `manga`), which Shell renders as a native swipeable top tab strip. Placeholder pages: `manga` pending #12, `feed` pending #14. Details routes registered in `AppShell.xaml.cs`: `media-details` → `MediaDetailsPage`, `staff-details` → `StaffDetailsPage`, `character-details` → `CharacterDetailsPage`, `studio-details` → `StudioDetailsPage`, `media-browse` → `MediaBrowsePage` (Discover "View All"; takes a `section` enum-name param decoded against `DiscoverSectionDefinitions`). Navigate via `Shell.Current.GoToAsync` (or the injected `INavigationService`) with lightweight query params (`mediaId` / `staffId` / `characterId` / `studioId` / `section` + trace IDs) — never pass full model objects. Rapid-tap prevention on My Anime → details. Default Shell back behavior — no custom Android back overrides. ## Performance Defaults -- 5-minute stale refresh window for flyout pages. +- 5-minute stale refresh window for tab pages. - Compiled XAML bindings enabled (`MauiEnableXamlCBindingWithSourceCompilation`). - Details page: keep above-the-fold small; lazy-load extended sections below; one primary spinner per screen state. - My Anime selection clear deferred until after navigation begins. diff --git a/.claude/skills/run-anisprinkles/SKILL.md b/.claude/skills/run-anisprinkles/SKILL.md index 683482a8..034c4438 100644 --- a/.claude/skills/run-anisprinkles/SKILL.md +++ b/.claude/skills/run-anisprinkles/SKILL.md @@ -53,6 +53,21 @@ Takes **~6 minutes** from cold (`Time Elapsed 00:05:53`) and produces a ~97 MB A at `src/bin/Debug/net10.0-android/com.RainbowSprinkles.AniSprinkles-Signed.apk`. Skip it if you have not touched `src/` since the last build. +**Build the Android head exactly one way: `driver.ps1 build`.** It is tempting to run a +plain `dotnet build src/AniSprinkles.csproj -c Debug -f net10.0-android` to check for +warnings and then `driver.ps1 build` for the APK — that wastes a second ~6-minute build +*and* leaves a broken APK, because the plain build omits `EmbedAssembliesIntoApk` and +overwrites the deployable ~97 MB APK with a ~19 MB Fast Deployment one (see Gotchas). The +driver's build prints the same warning and error counts, so it covers the review pass too. + +`dotnet test` does **not** need any of this — the test project targets plain `net10.0`, so +run it directly and never build the Android head just to run tests. + +**Do not chain a build with device driving in one shell call.** `build` alone can run 6+ +minutes; adding `install`/`launch`/`tap` behind it means one stalled step burns the whole +timeout and takes the completed steps down with it. Build in its own call (background it if +you have other work), then drive in a second. + --- ## Run (agent path) @@ -84,8 +99,8 @@ Then drive it. Every command is `driver.ps1 [args]`: | `swipe up\|down\|left\|right` | one content-area swipe | | `scroll-to ` | swipe up until `` is on screen (max 10) | | `wait-for [secs]` | poll until `` appears (default 30s) | -| `flyout` / `goto ` | open the drawer / open the drawer and pick `My Anime`\|`Discover`\|`Settings` | -| `search` | tap the Discover toolbar search icon (see Gotchas) | +| `goto ` | switch tabs: `Library`\|`Discover`\|`Search`\|`Feed`\|`Settings` — a plain label tap, so it works from inside a pushed details stack too | +| `search` | shortcut for `goto Search` | | `logcat [n]` / `applog` | app-PID logcat tail / the on-device rotating file log | `driver.ps1 help` prints the same list. @@ -121,13 +136,13 @@ Then `Read` the two PNGs: heart outline → filled, Favourites `90,457` → `90, `CIAniListClient` serves a fixed set, so these strings are always tappable: -- **My Anime**: `ONE PIECE`, `Shingeki no Kyojin`, `Jujutsu Kaisen`, `HUNTER×HUNTER (2011)`; +- **Library › Anime** (nav title reads "Library"; sub-tabs are `ANIME` / `MANGA`): `ONE PIECE`, `Shingeki no Kyojin`, `Jujutsu Kaisen`, `HUNTER×HUNTER (2011)`; section headers `Watching` / `Planning` / `Completed` - **Media details** (ONE PIECE): `Monkey D. Luffy`, `Roronoa Zoro`, `Nami`, studios `Toei Animation` / `Madhouse` / `Studio Pierrot`; content-descs `Toggle favorite` and `Open studio Toei Animation` - **Discover**: `Currently Airing`, `Trending Now`, `Top Anime`, `View All ›` -- **Search** filters that same fixture list client-side — `one` matches `ONE PIECE`; +- **Search tab** filters that same fixture list client-side — `one` matches `ONE PIECE`; anything else (e.g. `cowboy bebop`) correctly renders `No anime found`. That is the stub, not a bug. @@ -181,22 +196,31 @@ works — that is what the driver above is for. post-tap settle. Always `wait-for ""` between them. I caught `Loading discover...` and a stale details page this way twice. -- **`DiscoverPageModel` is a singleton, so the search bar keeps its text forever** — - navigating away, backing out of the app entirely, and coming back still shows the - old query and its results, not the section rows. If `wait-for "Trending Now"` - times out on Discover, the search bar is open: `driver.ps1 search` toggles it - shut and the sections come back. - -- **MAUI Shell toolbar items are invisible to uiautomator.** Only the hamburger has - a content-desc; the search / sort / layout icons have no node at all, so there is - nothing to `tap-desc`. `driver.ps1 search` works around it by mirroring the - hamburger's x across the screen width (`1080 - 74 = 1006`), which is - resolution-independent. - -- **`back` at a flyout root exits the app silently** — no confirm dialog, you just +- **`SearchPageModel` is a singleton, so the Search tab keeps its query forever** — + leaving the tab, backing out of the app entirely, and coming back still shows the + old query and its results. That is deliberate, not a bug. Clear the field (or the + `clear` command) if a test needs the idle prompt back. Discover no longer has a + search bar at all, so a `wait-for "Trending Now"` timeout there means something + else went wrong. + +- **The Search tab's keyboard covers the bottom tab bar.** The field auto-focuses + when the query is empty, so arriving on the tab immediately raises the keyboard and + hides every tab label — a `goto` straight after typing taps the keyboard instead and + silently stays put. Send `back` first to dismiss it, then switch tabs. + +- **MAUI Shell toolbar items are invisible to uiautomator, and there is no longer an + anchor to mirror.** The page-level search / sort / layout icons have no node at + all. This used to be worked around by mirroring the hamburger's x across the + screen width, but the bottom tab bar (issue #43) removed the hamburger, so that + trick has no anchor left. Tab **labels** are real nodes, so navigation is fine — + it is only the in-page toolbar icons (My Anime's sort / search / layout) that now + need hand-computed coordinates: they sit in the nav-bar row, right-aligned, about + `74px` in from each edge at 1080 wide. + +- **`back` at a tab root exits the app silently** — no confirm dialog, you just land on the launcher and every subsequent `tap` fails with a confusing "No node with text=...". `driver.ps1 resume` gets you back in ~3s. Prefer `goto` - over `back` for switching pages. + over `back` for switching tabs. - **`View All ›` carries a multibyte chevron in its text node.** Exact-match `tap` never finds it; use `tap-prefix "View All"`. @@ -204,6 +228,24 @@ works — that is what the driver above is for. - **`KEYCODE_CTRL_A` is not select-all on Android.** `driver.ps1 clear` spams `KEYCODE_DEL` instead. +- **A plain `dotnet build` silently clobbers the deployable APK.** Running + `dotnet build src/AniSprinkles.csproj -c Debug -f net10.0-android` to check for + warnings is fine, but it omits `-p:EmbedAssembliesIntoApk=true` and leaves a + ~19 MB *Fast Deployment* APK where the ~97 MB one was. Installing that gives a + process that dies instantly, before any managed code, with no .NET stack trace — + just `SIGABRT` and, buried in logcat: + + ``` + F/monodroid: No assemblies found in '.../files/.__override__/x86_64' + Assuming this is part of Fast Deployment. Exiting... + ``` + + It reads like a crash in your change and is not one. **Check the APK size** — if + it is ~19 MB rather than ~97 MB, that is the whole story. Rebuild with + `driver.ps1 build` (which passes both flags) before installing. A leftover + `.__override__` directory can also survive an uninstall, so if it persists after + a correct rebuild, uninstall the package before reinstalling. + - **The debug APK is ~97 MB and installs land on `INSUFFICIENT_STORAGE`** once the AVD's `/data` gets tight (mine had 570 MB free and still failed). `driver.ps1 install` detects it, uninstalls the old copy, and retries. Note that `adb install` @@ -244,11 +286,12 @@ works — that is what the driver above is for. | `INSUFFICIENT_STORAGE: Failed to override installation location` | `driver.ps1 install` handles it; if it still fails, wipe the AVD from Device Manager. | | `UI dump was empty — is the app foregrounded?` | The app is backgrounded or crashed. `driver.ps1 resume`, then `driver.ps1 logcat`. | | `No node with text='X'` right after it worked | You probably backed out to the launcher. `driver.ps1 dump` to confirm, then `resume`. | -| `'X' never appeared within Ns` on Discover | Search bar is still open with an old query — `driver.ps1 search`. | +| `'X' never appeared within Ns` right after typing a query | The keyboard is covering the tab bar — `driver.ps1 back`, then `goto`. | | `More than one device attached — set ANDROID_SERIAL to choose` | Two emulators/devices online. Pick one with `ANDROID_SERIAL=`, or shut the other down. `driver.ps1 env` lists them. | | `sys.boot_completed never reached 1 after 180s` | The emulator attached to adb but never finished booting. Check the emulator window; a wipe-data from Device Manager usually clears it. | | `df 'C:/Program Files/Git/data': No such file` | Git Bash path mangling — `MSYS_NO_PATHCONV=1`. | | App runs but shows the signed-out screen | You built without `-p:CiBuild=true`. Rebuild with `driver.ps1 build`. | +| App dies instantly, `SIGABRT`, no .NET stack | APK is ~19 MB not ~97 MB — a plain `dotnet build` overwrote it. `driver.ps1 build`. | For deeper on-device diagnostics (ANR / jank / Glide cascades / NAVTRACE timings), switch to **`/ani-debug`** — it has the full log-collection and interpretation diff --git a/.claude/skills/run-anisprinkles/driver.ps1 b/.claude/skills/run-anisprinkles/driver.ps1 index 86202f1b..85a1ce73 100644 --- a/.claude/skills/run-anisprinkles/driver.ps1 +++ b/.claude/skills/run-anisprinkles/driver.ps1 @@ -78,6 +78,17 @@ function AdbOut { if ($script:Serial) { & $Adb -s $script:Serial exec-out @args } else { & $Adb exec-out @args } } +# Free 1K-blocks on /data, or $null if the output could not be parsed. `df` prints a header +# plus one row; column 4 is "Available". Returns $null rather than throwing so callers can +# treat "unknown" as "proceed and let the install tell us". +function FreeDataKb { + $row = @(AdbOut df /data 2>$null) | Where-Object { $_ -match '^\S+\s+\d+' } | Select-Object -Last 1 + if (-not $row) { return $null } + $cols = @(($row -split '\s+') | Where-Object { $_ }) + if ($cols.Count -ge 4 -and $cols[3] -match '^\d+$') { return [int64]$cols[3] } + return $null +} + function Say($msg) { Write-Host "[driver] $msg" } function Get-AttachedDevices { @@ -215,9 +226,8 @@ AniSprinkles driver — pwsh .claude/skills/run-anisprinkles/driver.ps1 Swipe up until appears (max 10) wait-for [secs] Poll the UI until appears (default 30s) - flyout Open the Shell navigation drawer - search Tap the Discover toolbar search icon (see Gotchas) - goto Open the drawer and pick a page + goto Switch tabs: Library|Discover|Search|Feed|Settings + search Shortcut for `goto Search` logcat [lines] App-PID logcat tail (default 200) applog Pull the on-device rotating file log @@ -298,24 +308,43 @@ function Cmd-Install { $mb = [math]::Round((Get-Item $Apk).Length / 1MB) Say "installing $(Split-Path $Apk -Leaf) (${mb} MB)" + # Android wants several times the APK size free during install, and the default AVD's + # 6 GB data partition sits close to full with just this app on it. Drop the old copy up + # front when space is short rather than discovering it through a failed install: the + # uninstall costs seconds, the failed install costs a whole retry cycle. + $freeKb = FreeDataKb + $needKb = [int64]((Get-Item $Apk).Length / 1KB) * 4 + if ($null -ne $freeKb -and $freeKb -lt $needKb) { + Say "only $([math]::Round($freeKb / 1024)) MB free on /data — removing the old copy first" + Adb uninstall $Package *> $null + } + + # Every adb call here goes through the `Adb` wrapper, not `& $Adb`: the wrapper adds + # `-s $script:Serial` from Resolve-Target. Calling the binary directly ignores that, so with + # ANDROID_SERIAL set or two devices attached the free-space check could read one device while + # the install targeted another — or adb would just fail on "more than one device". + # # NOTE: `adb install` prints "Failure [...]" to STDOUT and STILL exits 0 in some # adb builds, and a stale build of the package left installed would make a # naive `pm list packages` check pass. Parse the output text instead. - $out = (& $Adb install -r -d $Apk 2>&1) -join "`n" + $out = @(Adb install -r -d $Apk 2>&1) -join "`n" Write-Host $out if ($out -match 'INSUFFICIENT_STORAGE') { - # The CI-stub debug APK is ~100 MB (EmbedAssembliesIntoApk + debug symbols), - # and Android wants several times that free during install. Dropping the old - # copy first is usually enough. + # Space was fine (or unreadable) going in but the install still did not fit. Say 'insufficient storage — uninstalling old copy and retrying' - & $Adb uninstall $Package *> $null - $out = (& $Adb install $Apk 2>&1) -join "`n" + Adb uninstall $Package *> $null + $out = @(Adb install $Apk 2>&1) -join "`n" Write-Host $out } if ($out -notmatch 'Success') { - throw "install failed. Free space on the AVD:`n$((AdbOut df /data) -join "`n")" + # @() around every capture: AdbOut returns $null when the device is gone, and `-join` + # on $null throws "You cannot call a method on a null-valued expression", which used to + # replace this diagnostic with a PowerShell error that said nothing about the install. + $df = @(AdbOut df -h /data 2>$null) -join "`n" + if (-not $df) { $df = '(could not read free space — device gone?)' } + throw "install failed.`nadb said:`n$out`n`nFree space on the AVD:`n$df" } Say 'installed' } @@ -411,32 +440,19 @@ function Cmd-WaitFor { throw "'$Text' never appeared within ${Seconds}s" } -function Cmd-Flyout { - # The hamburger is the only Shell toolbar item uiautomator exposes with a - # content-desc; the page's own toolbar icons are invisible to it (see Gotchas). - Tap-By -Attr 'content-desc' -Value 'Open navigation drawer' - Start-Sleep -Milliseconds 800 -} - function Cmd-Goto { param([string]$Page) - Cmd-Flyout + # Bottom tab bar (issue #43): every tab label is a real uiautomator node carrying + # both text and content-desc, so a tab switch is a plain text tap. This replaced + # the old open-the-drawer-then-pick dance, and works from anywhere — including + # partway down a pushed details stack. Tap-By -Attr 'text' -Value $Page Start-Sleep -Seconds 2 } function Cmd-Search { - # MAUI Shell's page-level ToolbarItems are NOT exposed to uiautomator — they have - # no text and no content-desc, so there is no node to find. The hamburger IS - # exposed, and the toolbar is horizontally symmetric, so the rightmost icon sits - # at (screenWidth - hamburgerCX, hamburgerCY). Resolution-independent. - $b = Find-Bounds -Xml (Get-UiDump) -Attr 'content-desc' -Value 'Open navigation drawer' - if (-not $b) { throw 'toolbar hamburger not found — is a flyout page foregrounded?' } - $w, $null = Get-ScreenSize - $x = $w - $b.CX - Say "tap toolbar search at ($x,$($b.CY)) [mirror of hamburger $($b.CX),$($b.CY) on width $w]" - Adb shell input tap $x $b.CY *> $null - Start-Sleep -Milliseconds 1200 + # Search is its own tab now, so this is just a tab switch. + Cmd-Goto 'Search' } function Cmd-Logcat { @@ -495,7 +511,6 @@ switch ($cmd) { 'wait-for' { $secs = 30; $txt = $a -join ' ' if ($a.Count -gt 1 -and $a[-1] -match '^\d+$') { $secs = [int]$a[-1]; $txt = ($a[0..($a.Count - 2)] -join ' ') } Cmd-WaitFor $txt $secs } - 'flyout' { Cmd-Flyout } 'search' { Cmd-Search } 'goto' { Cmd-Goto ($a -join ' ') } 'logcat' { if ($a[0]) { Cmd-Logcat ([int]$a[0]) } else { Cmd-Logcat } } diff --git a/.github/workflows/ci-build-and-preview.yml b/.github/workflows/ci-build-and-preview.yml index 4ab6dfa9..204250aa 100644 --- a/.github/workflows/ci-build-and-preview.yml +++ b/.github/workflows/ci-build-and-preview.yml @@ -201,7 +201,7 @@ jobs: # Shared helper: find a UI node by attribute value, parse its bounds, and tap it. # Usage: _tap_by_attribute "text" "ONE PIECE" - # _tap_by_attribute "content-desc" "Open navigation drawer" + # _tap_by_attribute "content-desc" "Toggle favorite" _tap_by_attribute() { local attr="$1" value="$2" # Remove any previous dump so a failed dump cannot leave us parsing stale UI. @@ -247,7 +247,7 @@ jobs: tap_element_by_text() { _tap_by_attribute "text" "$1"; } # Tap a UI element by its content-desc attribute (for icon buttons with no label). - # Usage: tap_element_by_content_desc "Open navigation drawer" + # Usage: tap_element_by_content_desc "Toggle favorite" tap_element_by_content_desc() { _tap_by_attribute "content-desc" "$1"; } # Scroll until a target studio chip is visible, then tap it. Prefer the @@ -299,38 +299,13 @@ jobs: return 1 } - # Open the Discover search bar by tapping the lone right-side toolbar icon. MAUI Shell's - # action icons aren't exposed to uiautomator as findable nodes (only the hamburger has a - # content-desc), so we mirror the hamburger's position to the right edge: toolbars are - # horizontally symmetric, so the rightmost icon center sits at (screen_width - drawer_cx, - # drawer_cy). Resolution-independent and needs no node for the icon itself. - # Usage: tap_search_toggle - tap_search_toggle() { - adb shell rm -f /sdcard/ui_toolbar.xml >/dev/null 2>&1 || true - if ! adb shell uiautomator dump /sdcard/ui_toolbar.xml >/dev/null 2>&1 \ - || ! adb shell test -s /sdcard/ui_toolbar.xml >/dev/null 2>&1; then - echo "::warning::Failed to dump UI for the search toggle" - return 1 - fi - local drawer_bounds - drawer_bounds=$(adb shell cat /sdcard/ui_toolbar.xml 2>/dev/null | tr '>' '>\n' \ - | grep -o 'content-desc="Open navigation drawer"[^/]*bounds="\[[0-9]*,[0-9]*\]\[[0-9]*,[0-9]*\]"' \ - | grep -o 'bounds="\[[0-9]*,[0-9]*\]\[[0-9]*,[0-9]*\]"' | head -1 | sed 's/bounds="//;s/"//') || true - if [ -z "$drawer_bounds" ]; then - echo "::warning::Could not locate the toolbar hamburger to mirror the search icon" - return 1 - fi - local dl dt dr dbot dcx dcy width tap_x - dl=$(echo "$drawer_bounds" | sed 's/\[//g;s/\]/ /g' | awk -F'[, ]' '{print $1}') - dt=$(echo "$drawer_bounds" | sed 's/\[//g;s/\]/ /g' | awk -F'[, ]' '{print $2}') - dr=$(echo "$drawer_bounds" | sed 's/\[//g;s/\]/ /g' | awk -F'[, ]' '{print $3}') - dbot=$(echo "$drawer_bounds" | sed 's/\[//g;s/\]/ /g' | awk -F'[, ]' '{print $4}') - dcx=$(( (dl + dr) / 2 )); dcy=$(( (dt + dbot) / 2 )) - width=$(adb shell wm size | grep -o '[0-9]*x[0-9]*' | head -1 | cut -dx -f1) - [ -z "$width" ] && { echo "::warning::Could not read screen width"; return 1; } - tap_x=$(( width - dcx )) - echo "Tapping search toggle at (${tap_x}, ${dcy}) [mirror of hamburger ${dcx},${dcy} on width ${width}]" - adb shell input tap "$tap_x" "$dcy" + # Search is its own tab now (issue #43), with an always-visible search bar. The old + # helper here mirrored the hamburger's x across the screen width to find Discover's + # toolbar search icon, because MAUI toolbar icons expose no uiautomator node; the + # bottom tab bar removed both the hamburger anchor and the need for the trick. + # Usage: open_search_tab + open_search_tab() { + goto_tab "Search" } # Tap the first "View All ›" row link. Its text node carries the chevron (a multibyte @@ -363,23 +338,16 @@ jobs: adb shell input tap "$cx" "$cy" } - # Press BACK until the My Anime page (its toolbar title) is showing again, so the flyout - # step runs from the root regardless of how deep navigation went. - # Usage: back_to_my_anime [max_presses] - back_to_my_anime() { - local max="${1:-6}" i - for i in $(seq 1 "$max"); do - adb shell rm -f /sdcard/ui_back.xml >/dev/null 2>&1 || true - if adb shell uiautomator dump /sdcard/ui_back.xml >/dev/null 2>&1 \ - && adb shell cat /sdcard/ui_back.xml 2>/dev/null | grep -q "My Anime"; then - echo "Back on My Anime after $((i - 1)) back press(es)" - return 0 - fi - adb shell input keyevent KEYCODE_BACK - sleep 1.5 - done - echo "::warning::Did not return to My Anime after ${max} back press(es)" - return 1 + # Switch bottom tabs by tapping the tab's label (issue #43). Tab labels are real + # uiautomator nodes carrying both text and content-desc, so this is an ordinary text + # tap that works from anywhere — including partway down a pushed details stack, which + # is why it replaced the old back-out-then-open-the-drawer dance entirely. + # Returns non-zero when the tab label was not found, so callers can skip the + # screenshots that depend on having arrived (the trailing sleep must not mask it). + # Usage: goto_tab "Discover" + goto_tab() { + tap_element_by_text "$1" || return 1 + sleep 2 } # Locate the APK @@ -466,12 +434,17 @@ jobs: echo "::warning::Timed out waiting for page to load after ${MAX_WAIT}s — capturing anyway" fi + # Start from empty. The checkout carries the PREVIOUS run's screenshots (they are + # committed to the branch), so without this any capture that fails silently leaves last + # run's PNG on disk — and the publish step then commits and embeds it as if it were + # current. A missing screenshot is obvious; a stale one that looks plausible is not. + rm -rf screenshots mkdir -p screenshots - # Screenshot 1: My Anime page (default flyout destination) - adb shell screencap -p /sdcard/my_anime.png || echo "::warning::Failed to capture My Anime screenshot" - adb pull /sdcard/my_anime.png screenshots/my_anime.png || echo "::warning::Failed to pull My Anime screenshot" - echo "Captured: my_anime.png (My Anime — $AUTH_MODE)" + # Screenshot 1: Library tab, Anime sub-tab (the app's launch destination) + adb shell screencap -p /sdcard/my_anime.png || echo "::warning::Failed to capture Library screenshot" + adb pull /sdcard/my_anime.png screenshots/my_anime.png || echo "::warning::Failed to pull Library screenshot" + echo "Captured: my_anime.png (Library — $AUTH_MODE)" # Tap One Piece to open its details page tap_element_by_text "ONE PIECE" || echo "::warning::Could not find ONE PIECE in list" @@ -569,81 +542,55 @@ jobs: adb pull /sdcard/staff_details.png screenshots/staff_details.png || echo "::warning::Failed to pull staff screenshot" echo "Captured: staff_details.png (Mayumi Tanaka — $AUTH_MODE)" - # Navigate back to My Anime (now several levels deep), then open the flyout and tap Settings. - back_to_my_anime - - # Open the Shell flyout via the hamburger icon ("Open navigation drawer"). - # Android 10+ gesture navigation intercepts left-edge swipes before they - # reach the app, so tapping the DrawerToggle button is reliable regardless - # of the system navigation mode. - FLYOUT_OPENED=0 - for FLYOUT_ATTEMPT in 1 2 3; do - echo "Flyout open attempt ${FLYOUT_ATTEMPT}..." - tap_element_by_content_desc "Open navigation drawer" || true - sleep 1 - adb shell rm -f /sdcard/ui_flyout_check.xml >/dev/null 2>&1 || true - if adb shell uiautomator dump /sdcard/ui_flyout_check.xml >/dev/null 2>&1 && \ - adb shell test -s /sdcard/ui_flyout_check.xml >/dev/null 2>&1 && \ - adb shell cat /sdcard/ui_flyout_check.xml 2>/dev/null | grep -qi '"Settings"'; then - echo " Flyout confirmed open on attempt ${FLYOUT_ATTEMPT}" - FLYOUT_OPENED=1 - break + # Straight to the Settings tab. The details stack this leaves behind on the Library tab + # does not matter — the next section taps its own tab too. Guarded because `set -e` + # would otherwise abort the whole run (and lose every later screenshot) on one miss. + # Gated like the Discover capture below: on a missed tab we are still sitting on the + # staff details page, and capturing anyway would file THAT as settings.png. Skipping + # leaves the screenshot absent, which is visible; publishing the wrong page is not. + if goto_tab "Settings"; then + # Poll for Settings page to finish loading (up to 15s) + # "Display Preferences" is a static label always visible once loaded. + SETTINGS_LOAD_WAIT=0 + while [ $SETTINGS_LOAD_WAIT -lt 15 ]; do + adb shell uiautomator dump /sdcard/ui_settings_loaded.xml 2>/dev/null || true + SETTINGS_DUMP=$(adb shell cat /sdcard/ui_settings_loaded.xml 2>/dev/null || echo "") + if echo "$SETTINGS_DUMP" | grep -q "Loading settings"; then + echo " Still loading settings... (${SETTINGS_LOAD_WAIT}s)" + elif echo "$SETTINGS_DUMP" | grep -q "Display Preferences"; then + echo " Settings loaded after ${SETTINGS_LOAD_WAIT}s" + sleep 1 + break + fi + sleep 1 + SETTINGS_LOAD_WAIT=$((SETTINGS_LOAD_WAIT + 1)) + done + if [ $SETTINGS_LOAD_WAIT -ge 15 ]; then + echo "::warning::Settings page did not finish loading — capturing anyway" fi - done - if [ "$FLYOUT_OPENED" -eq 1 ]; then - tap_element_by_text "Settings" - sleep 2 + # Screenshot 6: Settings page + adb shell screencap -p /sdcard/settings.png || echo "::warning::Failed to capture Settings screenshot" + adb pull /sdcard/settings.png screenshots/settings.png || echo "::warning::Failed to pull Settings screenshot" + echo "Captured: settings.png (Settings — $AUTH_MODE)" else - echo "::warning::Flyout did not open — Settings screenshot may be incorrect" - fi - - # Poll for Settings page to finish loading (up to 15s) - # "Display Preferences" is a static label always visible once loaded. - SETTINGS_LOAD_WAIT=0 - while [ $SETTINGS_LOAD_WAIT -lt 15 ]; do - adb shell uiautomator dump /sdcard/ui_settings_loaded.xml 2>/dev/null || true - SETTINGS_DUMP=$(adb shell cat /sdcard/ui_settings_loaded.xml 2>/dev/null || echo "") - if echo "$SETTINGS_DUMP" | grep -q "Loading settings"; then - echo " Still loading settings... (${SETTINGS_LOAD_WAIT}s)" - elif echo "$SETTINGS_DUMP" | grep -q "Display Preferences"; then - echo " Settings loaded after ${SETTINGS_LOAD_WAIT}s" - sleep 1 - break - fi - sleep 1 - SETTINGS_LOAD_WAIT=$((SETTINGS_LOAD_WAIT + 1)) - done - if [ $SETTINGS_LOAD_WAIT -ge 15 ]; then - echo "::warning::Settings page did not finish loading — capturing anyway" + echo "::warning::Could not reach the Settings tab — skipping Settings screenshot" fi - # Screenshot 6: Settings page - adb shell screencap -p /sdcard/settings.png || echo "::warning::Failed to capture Settings screenshot" - adb pull /sdcard/settings.png screenshots/settings.png || echo "::warning::Failed to pull Settings screenshot" - echo "Captured: settings.png (Settings — $AUTH_MODE)" - # ---- Discover / View All / Search (issues #15/#16) ---- # All rendered from CI stub fixtures (popular SFW titles); the adult toggle defaults off, # so the 18+ rows are never requested. - # Open the flyout from Settings and tap Discover. + # Straight to the Discover tab. Kept behind DISCOVER_OPENED so a failure to reach the + # tab skips the dependent screenshots rather than capturing whatever was on screen. DISCOVER_OPENED=0 - for FLYOUT_ATTEMPT in 1 2 3; do - echo "Flyout open attempt ${FLYOUT_ATTEMPT} (Discover)..." - tap_element_by_content_desc "Open navigation drawer" || true - sleep 1 - adb shell rm -f /sdcard/ui_flyout_disc.xml >/dev/null 2>&1 || true - if adb shell uiautomator dump /sdcard/ui_flyout_disc.xml >/dev/null 2>&1 && \ - adb shell test -s /sdcard/ui_flyout_disc.xml >/dev/null 2>&1 && \ - adb shell cat /sdcard/ui_flyout_disc.xml 2>/dev/null | grep -qi '"Discover"'; then - DISCOVER_OPENED=1 - break - fi - done + if goto_tab "Discover"; then + DISCOVER_OPENED=1 + else + echo "::warning::Could not reach the Discover tab — skipping its screenshots" + fi if [ "$DISCOVER_OPENED" -eq 1 ]; then - tap_element_by_text "Discover" # Wait for the rows to populate (a known section header appears once loaded). DISC_WAIT=0 while [ $DISC_WAIT -lt 20 ]; do @@ -687,37 +634,40 @@ jobs: echo "::warning::Could not open a View All list — skipping browse screenshot" fi - # Screenshot 9: Search results. Open the search bar, focus the field, type a popular - # SFW query that matches a stub title, capture results. - if tap_search_toggle; then - sleep 1 - # Tap the revealed field by its hint to guarantee focus before typing (the field - # auto-focuses on reveal, but a tap is a cheap belt-and-suspenders for CI). - tap_element_by_text "Search all anime..." || true - sleep 1 - # "no" matches five romaji stub titles (Shingeki no Kyojin, Kimi no Na wa, Yakusoku - # no Neverland, Hagane no Renkinjutsushi, Kimetsu no Yaiba) so the results list is - # full and shows a mix of status pills (and some off-list rows). - adb shell input text "no" - SEARCH_WAIT=0 - while [ $SEARCH_WAIT -lt 12 ]; do - adb shell uiautomator dump /sdcard/ui_search.xml 2>/dev/null || true - if adb shell cat /sdcard/ui_search.xml 2>/dev/null | grep -qi "Shingeki no Kyojin"; then - echo " Search results ready after ${SEARCH_WAIT}s" - break - fi - sleep 1 - SEARCH_WAIT=$((SEARCH_WAIT + 1)) - done + else + echo "::warning::Discover tab unreachable — skipped Discover/View All screenshots" + fi + + # Screenshot 9: Search results. Its own tab since #43, so this deliberately sits OUTSIDE + # the Discover guard — nested under DISCOVER_OPENED, one failed Discover tap silently + # skipped the Search capture as well. goto_tab works from anywhere, including a pushed + # details stack, so there is nothing to unwind first. + if open_search_tab; then + sleep 1 + # Tap the field by its hint to guarantee focus before typing. The page focuses it + # on appear when empty, but a tap is a cheap belt-and-suspenders for CI. + tap_element_by_text "Search all anime..." || true + sleep 1 + # "no" matches five romaji stub titles (Shingeki no Kyojin, Kimi no Na wa, Yakusoku + # no Neverland, Hagane no Renkinjutsushi, Kimetsu no Yaiba) so the results list is + # full and shows a mix of status pills (and some off-list rows). + adb shell input text "no" + SEARCH_WAIT=0 + while [ $SEARCH_WAIT -lt 12 ]; do + adb shell uiautomator dump /sdcard/ui_search.xml 2>/dev/null || true + if adb shell cat /sdcard/ui_search.xml 2>/dev/null | grep -qi "Shingeki no Kyojin"; then + echo " Search results ready after ${SEARCH_WAIT}s" + break + fi sleep 1 - adb shell screencap -p /sdcard/search.png || echo "::warning::Failed to capture Search screenshot" - adb pull /sdcard/search.png screenshots/search.png || echo "::warning::Failed to pull Search screenshot" - echo "Captured: search.png (Discover Search — $AUTH_MODE)" - else - echo "::warning::Could not open the search bar — skipping search screenshot" - fi + SEARCH_WAIT=$((SEARCH_WAIT + 1)) + done + sleep 1 + adb shell screencap -p /sdcard/search.png || echo "::warning::Failed to capture Search screenshot" + adb pull /sdcard/search.png screenshots/search.png || echo "::warning::Failed to pull Search screenshot" + echo "Captured: search.png (Search — $AUTH_MODE)" else - echo "::warning::Flyout did not open for Discover — skipping Discover/View All/Search screenshots" + echo "::warning::Could not reach the Search tab — skipping search screenshot" fi echo "" @@ -832,10 +782,10 @@ jobs: const screenshotsPublished = process.env.SCREENSHOTS_PUBLISHED === 'true'; const screenshots = [ - { file: 'screenshots/my_anime.png', label: 'My Anime' }, + { file: 'screenshots/my_anime.png', label: 'Library' }, { file: 'screenshots/discover.png', label: 'Discover' }, { file: 'screenshots/browse.png', label: 'View All (Browse)' }, - { file: 'screenshots/search.png', label: 'Discover Search' }, + { file: 'screenshots/search.png', label: 'Search' }, { file: 'screenshots/one_piece_details.png', label: 'One Piece Details' }, { file: 'screenshots/studio_details.png', label: 'Toei Animation (Studio)' }, { file: 'screenshots/character_details.png', label: 'Luffy (Character)' }, @@ -929,10 +879,10 @@ jobs: echo "| Screenshot | Page |" >> $GITHUB_STEP_SUMMARY echo "|---|---|" >> $GITHUB_STEP_SUMMARY for shot in \ - "my_anime.png|My Anime" \ + "my_anime.png|Library" \ "discover.png|Discover" \ "browse.png|View All (Browse)" \ - "search.png|Discover Search" \ + "search.png|Search" \ "one_piece_details.png|One Piece Details" \ "studio_details.png|Toei Animation (Studio)" \ "character_details.png|Luffy (Character)" \ diff --git a/AGENTS.md b/AGENTS.md index 541728da..fed0bfaa 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -9,8 +9,8 @@ ## Architecture - **.NET MAUI Android-only** app (`net10.0-android`; `SupportedOSPlatformVersion` 31.0), single project in `src/`. App ID: `com.RainbowSprinkles.AniSprinkles`. -- **MVVM** via CommunityToolkit.Mvvm: PageModels extend `ObservableObject`, use `[ObservableProperty]`, `[RelayCommand]`, `[NotifyPropertyChangedFor]`. Shell flyout navigation (`my-anime`, `discover`, `settings`) with programmatic `media-details`, `staff-details`, `character-details`, `studio-details`, and `media-browse` routes. PageModels navigate through the injected `INavigationService` (routes + lightweight query params — never full objects); persist state via the injected `IPreferences`; marshal pool-thread continuations back to the UI via the injected `IDispatcher`. View-facing UX calls (`Shell.Current.DisplayAlertAsync`, `ShowPopupAsync`, `Browser.Default`) are allowed to keep using MAUI statics because they only run inside view-attached paths. -- **DI**: Services and flyout PageModels (`MyAnimePageModel`, `DiscoverPageModel`, `SettingsPageModel`) are singleton. All Pages and details PageModels (`MediaDetailsPageModel`, `StaffDetailsPageModel`, `CharacterDetailsPageModel`, `StudioDetailsPageModel`, `MediaBrowsePageModel`) are transient. See `/project-architecture` for the full DI table and page patterns. +- **MVVM** via CommunityToolkit.Mvvm: PageModels extend `ObservableObject`, use `[ObservableProperty]`, `[RelayCommand]`, `[NotifyPropertyChangedFor]`. Shell bottom-tab navigation (`my-anime` with `anime`/`manga` sub-tabs, `discover`, `search`, `feed`, `settings`) with programmatic `media-details`, `staff-details`, `character-details`, `studio-details`, and `media-browse` routes. PageModels navigate through the injected `INavigationService` (routes + lightweight query params — never full objects); persist state via the injected `IPreferences`; marshal pool-thread continuations back to the UI via the injected `IDispatcher`. View-facing UX calls (`Shell.Current.DisplayAlertAsync`, `ShowPopupAsync`, `Browser.Default`) are allowed to keep using MAUI statics because they only run inside view-attached paths. +- **DI**: Services and tab PageModels (`MyAnimePageModel`, `DiscoverPageModel`, `SearchPageModel`, `SettingsPageModel`) are singleton. All Pages and details PageModels (`MediaDetailsPageModel`, `StaffDetailsPageModel`, `CharacterDetailsPageModel`, `StudioDetailsPageModel`, `MediaBrowsePageModel`) are transient. See `/project-architecture` for the full DI table and page patterns. - **Services**: `AuthService` (OAuth + SecureStorage), `AniListClient` (GraphQL + viewer ID cache), `ErrorReportService` (Sentry + `ILogger` + token redaction), `FileLoggerProvider` (rotating async file log, Debug = 1 MB × 3 / Release = 256 KB × 3), `AndroidLogcatLoggerProvider` (bridges `ILogger` → `adb logcat` on Android), `LoggingHandler` (HTTP DelegatingHandler), `AiringNotificationService` (WorkManager periodic check). See `/airing-notifications` for the notification subsystem. - **Global usings** (`GlobalUsings.cs`): `Models`, `PageModels`, `Pages`, `Services`, `IconFont.Maui.FluentIcons`. `Converters` and `Utilities` require explicit `using`. - **Key NuGet packages**: `Microsoft.Maui.Controls`, `CommunityToolkit.Mvvm`, `CommunityToolkit.Maui`, `Sentry.Maui`, `Syncfusion.Maui.Toolkit`, `IconFont.Maui.FluentIcons`. @@ -32,7 +32,9 @@ See `/airing-notifications` for the full subsystem architecture, key files, Pref ## Build and Test ```powershell -# Debug build +# Debug build — compiles and runs analyzers, but does NOT produce an installable +# APK. Add -p:EmbedAssembliesIntoApk=true if you intend to deploy it, or the +# artifact is a ~19 MB Fast Deployment package that aborts at launch. dotnet build src/AniSprinkles.csproj -c Debug -f net10.0-android # Release AAB (CI uses this with signing args — see .github/workflows/android-release.yml) diff --git a/README.md b/README.md index d1016edc..229e3154 100644 --- a/README.md +++ b/README.md @@ -16,9 +16,9 @@ A colourful .NET MAUI Android app for tracking your anime with [AniList](https:/ ## Screenshots -| My Anime | Media Details | Character | Staff | Settings | +| Library | Media Details | Character | Staff | Settings | | :---: | :---: | :---: | :---: | :---: | -| ![My Anime](screenshots/my_anime.png) | ![One Piece Details](screenshots/one_piece_details.png) | ![Luffy](screenshots/character_details.png) | ![Mayumi Tanaka](screenshots/staff_details.png) | ![Settings](screenshots/settings.png) | +| ![Library](screenshots/my_anime.png) | ![One Piece Details](screenshots/one_piece_details.png) | ![Luffy](screenshots/character_details.png) | ![Mayumi Tanaka](screenshots/staff_details.png) | ![Settings](screenshots/settings.png) | > Screenshots generated automatically by CI using compile-time stub services — no OAuth token required. @@ -26,8 +26,9 @@ A colourful .NET MAUI Android app for tracking your anime with [AniList](https:/ ## Features -- **My Anime list** — library grouped by status (Watching, Rewatching, Planning, Completed, Paused, Dropped) with collapsible sections, sort controls, and pull-to-refresh -- **Discover** — Currently Airing, Trending Now, Top Anime, Top Movies, All Time Popular, and Upcoming Next Season rows (plus optional 18+ rows) with infinite scrolling and "View All" browse lists, plus debounced search across all of AniList; works signed-out, and shows your list status on every card when signed in +- **Library** — your anime list grouped by status (Watching, Rewatching, Planning, Completed, Paused, Dropped) with collapsible sections, sort controls, and pull-to-refresh; an Anime/Manga sub-tab strip sits above it, with manga still to come +- **Discover** — Currently Airing, Trending Now, Top Anime, Top Movies, All Time Popular, and Upcoming Next Season rows (plus optional 18+ rows) with infinite scrolling and "View All" browse lists; works signed-out, and shows your list status on every card when signed in +- **Search** — debounced search across all of AniList on its own tab, with infinite scrolling; works signed-out, and shows your list status on every result when signed in - **Quick list actions** — long-press any anime (in your list, Discover, browse, or search) to add it to a list or edit progress, rating, and status without leaving the page - **Media details** — full AniList metadata: synopsis with Read more/Show less, scores, airing schedule, genres, tags, rankings, studios, staff, related media, external links, and trailer - **List entry editing** — update watch progress, score, and status directly from the details page; changes sync back to AniList @@ -53,9 +54,14 @@ dotnet workload install maui-android ``` ```powershell -# Debug APK +# Debug compile (type-check + analyzers). NOT an installable APK: without +# EmbedAssembliesIntoApk this leaves a ~19 MB Fast Deployment package that aborts +# at launch with no managed stack trace. dotnet build src/AniSprinkles.csproj -c Debug -f net10.0-android +# Debug APK you can actually install (~97 MB) +dotnet build src/AniSprinkles.csproj -c Debug -f net10.0-android -p:EmbedAssembliesIntoApk=true + # Release AAB dotnet publish src/AniSprinkles.csproj -c Release -f net10.0-android -p:AndroidPackageFormat=aab -o output @@ -71,7 +77,7 @@ dotnet build src/AniSprinkles.csproj -c Debug -f net10.0-android -p:EmbedAssembl | ---------- | ------------------------------------------------------------------------------------------ | | Platform | .NET MAUI Android-only (`net10.0-android`, min SDK 31) | | Pattern | MVVM — CommunityToolkit.Mvvm (`[ObservableProperty]`, `[RelayCommand]`) | -| Navigation | Shell flyout + programmatic details routes (`media-details`, `character-details`, `staff-details`, `studio-details`) | +| Navigation | Shell bottom tab bar + programmatic details routes (`media-details`, `character-details`, `staff-details`, `studio-details`) | | Auth | AniList OAuth implicit grant; redirect URI `anisprinkles://auth`; token in `SecureStorage` | | HTTP | Singleton `HttpClient` with `LoggingHandler` (Bearer token redaction) | | Background | WorkManager periodic job for airing notifications | diff --git a/screenshots/.gitkeep b/screenshots/.gitkeep deleted file mode 100644 index e69de29b..00000000 diff --git a/screenshots/browse.png b/screenshots/browse.png index dff9ff6a..7c08fefa 100644 Binary files a/screenshots/browse.png and b/screenshots/browse.png differ diff --git a/screenshots/character_details.png b/screenshots/character_details.png index 36ab0cf9..02535393 100644 Binary files a/screenshots/character_details.png and b/screenshots/character_details.png differ diff --git a/screenshots/discover.png b/screenshots/discover.png index 5765491c..ca66af5f 100644 Binary files a/screenshots/discover.png and b/screenshots/discover.png differ diff --git a/screenshots/my_anime.png b/screenshots/my_anime.png index 7655d0de..ce100373 100644 Binary files a/screenshots/my_anime.png and b/screenshots/my_anime.png differ diff --git a/screenshots/one_piece_details.png b/screenshots/one_piece_details.png index 86f2a46f..bd3c6996 100644 Binary files a/screenshots/one_piece_details.png and b/screenshots/one_piece_details.png differ diff --git a/screenshots/search.png b/screenshots/search.png index 456940d5..7013a6e4 100644 Binary files a/screenshots/search.png and b/screenshots/search.png differ diff --git a/screenshots/settings.png b/screenshots/settings.png index 5dad7e2a..cdaac49c 100644 Binary files a/screenshots/settings.png and b/screenshots/settings.png differ diff --git a/screenshots/staff_details.png b/screenshots/staff_details.png index 320d5e50..cc4bbb04 100644 Binary files a/screenshots/staff_details.png and b/screenshots/staff_details.png differ diff --git a/screenshots/studio_details.png b/screenshots/studio_details.png index 3c774283..d1198c86 100644 Binary files a/screenshots/studio_details.png and b/screenshots/studio_details.png differ diff --git a/src/AppShell.xaml b/src/AppShell.xaml index e119d6f0..2ef59ded 100644 --- a/src/AppShell.xaml +++ b/src/AppShell.xaml @@ -4,19 +4,64 @@ xmlns="http://schemas.microsoft.com/dotnet/2021/maui" xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml" xmlns:pages="clr-namespace:AniSprinkles.Pages" + xmlns:icons="clr-namespace:IconFont.Maui.FluentIcons;assembly=IconFont.Maui.FluentIcons" Title="AniSprinkles" - FlyoutBehavior="Flyout" + FlyoutBehavior="Disabled" NavBarHasShadow="False"> - - - + + + + + + + + + + - - - + + + + + + - - - + + + + + + + + + + + + + + + + + + + + + diff --git a/src/AppShell.xaml.cs b/src/AppShell.xaml.cs index db2f05d6..14288fd7 100644 --- a/src/AppShell.xaml.cs +++ b/src/AppShell.xaml.cs @@ -1,3 +1,5 @@ +using IconFont.Maui.FluentIcons; + namespace AniSprinkles; public partial class AppShell : Shell @@ -8,6 +10,13 @@ public partial class AppShell : Shell private const string StudioDetailsRoute = "studio-details"; private const string MediaBrowseRoute = "media-browse"; + // Selected tabs show the Filled glyph, unselected the Regular one (issue #43). + // MAUI Shell has no per-state icon property — Android renders the bar through + // BottomNavigationView and Shell only maps a single Icon — so the swap is done + // here on Navigated. Both ImageSources per tab are built once and reused; a new + // FontImageSource per navigation would churn allocations on every tab tap. + private (Tab Tab, FontImageSource Regular, FontImageSource Filled)[] _tabIcons = []; + public AppShell() { InitializeComponent(); @@ -16,5 +25,43 @@ public AppShell() Routing.RegisterRoute(CharacterDetailsRoute, typeof(CharacterDetailsPage)); Routing.RegisterRoute(StudioDetailsRoute, typeof(StudioDetailsPage)); Routing.RegisterRoute(MediaBrowseRoute, typeof(MediaBrowsePage)); + + _tabIcons = + [ + BuildIcons(LibraryTab, FluentIconsRegular.Library24, FluentIconsFilled.Library24), + BuildIcons(DiscoverTab, FluentIconsRegular.Rocket24, FluentIconsFilled.Rocket24), + BuildIcons(SearchTab, FluentIconsRegular.Search24, FluentIconsFilled.Search24), + BuildIcons(FeedTab, FluentIconsRegular.Feed24, FluentIconsFilled.Feed24), + BuildIcons(SettingsTab, FluentIconsRegular.Settings24, FluentIconsFilled.Settings24), + ]; + + // Navigated covers tab taps and programmatic GoToAsync alike. Run once up front + // so the tab the app launches on starts filled rather than waiting for a switch. + Navigated += OnShellNavigated; + ApplySelectedTabIcons(); + } + + private static (Tab, FontImageSource, FontImageSource) BuildIcons(Tab tab, string regularGlyph, string filledGlyph) + => (tab, + new FontImageSource { Glyph = regularGlyph, FontFamily = FluentIconsRegular.FontFamily }, + new FontImageSource { Glyph = filledGlyph, FontFamily = FluentIconsFilled.FontFamily }); + + private void OnShellNavigated(object? sender, ShellNavigatedEventArgs e) => ApplySelectedTabIcons(); + + private void ApplySelectedTabIcons() + { + // Shell.CurrentItem is the TabBar; its CurrentItem is the selected Tab. + // No Color is set on either source, so the platform keeps applying + // Shell.TabBarForegroundColor / TabBarUnselectedColor from Styles.xaml. + var selected = CurrentItem?.CurrentItem; + + foreach (var (tab, regular, filled) in _tabIcons) + { + var wanted = ReferenceEquals(tab, selected) ? filled : regular; + if (!ReferenceEquals(tab.Icon, wanted)) + { + tab.Icon = wanted; + } + } } } diff --git a/src/MauiProgram.cs b/src/MauiProgram.cs index 45550876..ebc1c97f 100644 --- a/src/MauiProgram.cs +++ b/src/MauiProgram.cs @@ -130,6 +130,11 @@ public static MauiApp CreateMauiApp() builder.Services.AddTransient(); builder.Services.AddSingleton(); builder.Services.AddTransient(); + builder.Services.AddSingleton(); + builder.Services.AddTransient(); + // Placeholder pages: no PageModel until their features land (manga #12, feed #14). + builder.Services.AddTransient(); + builder.Services.AddTransient(); builder.Services.AddSingleton(); builder.Services.AddTransient(); builder.Services.AddTransient(); diff --git a/src/PageModels/DiscoverPageModel.cs b/src/PageModels/DiscoverPageModel.cs index 17c04bc5..fa552bb8 100644 --- a/src/PageModels/DiscoverPageModel.cs +++ b/src/PageModels/DiscoverPageModel.cs @@ -6,8 +6,9 @@ namespace AniSprinkles.PageModels; /// -/// Discover page (issues #15/#16): public browse sections + search, no auth required. -/// Singleton, like the other flyout page models — the section data doubles as the TTL cache: +/// Discover page (issue #15): public browse sections, no auth required. Search used to live +/// here behind a toolbar toggle; it moved to its own tab in #43 — see . +/// Singleton, like the other tab page models — the section data doubles as the TTL cache: /// Discover data changes slowly, so revisits within skip the network /// entirely and pull-to-refresh is the explicit bypass. A flipped adult-content toggle also /// invalidates the cache, since it changes both the query filters and which sections exist. @@ -15,12 +16,7 @@ namespace AniSprinkles.PageModels; public partial class DiscoverPageModel : ObservableObject { private static readonly TimeSpan SectionsTtl = TimeSpan.FromMinutes(20); - private static readonly TimeSpan SearchDebounceDelay = TimeSpan.FromMilliseconds(600); private const int SectionPerPage = 20; - private const int SearchPerPage = 20; - - /// Below this many trimmed characters no search fires (rate-limit caution + junk-match avoidance). - private const int SearchMinLength = 2; private readonly IAniListClient _aniListClient; private readonly IAuthService _authService; @@ -37,9 +33,10 @@ public partial class DiscoverPageModel : ObservableObject private bool _loadedWithAdultContent; private bool _loadedAuthenticated; - // Search debounce state: a new keystroke cancels the pending (or in-flight) search. - private CancellationTokenSource? _searchDebounceCts; - private string _activeSearchQuery = string.Empty; + /// True from the moment is entered until it finishes, which + /// includes the auth read that runs before IsBusy is set. Load More checks this so no + /// page can be fetched under a context the in-progress refresh is about to replace. + private bool _refreshEvaluating; public DiscoverPageModel( IAniListClient aniListClient, @@ -70,8 +67,8 @@ public DiscoverPageModel( .ToList(); // Shared long-press flows. A successful mutation is written back onto EVERY item showing - // that media (the same anime can sit in several rows plus the search results), keeping the - // chips and the TTL-cached sections consistent without a refetch. + // that media (the same anime can sit in several rows), keeping the chips and the + // TTL-cached sections consistent without a refetch. _entryActions = new EntryActionCoordinator(aniListClient, errorReportService, logger, new EntryActionHost { OpenDetailsAsync = entry => NavigateToMediaByIdAsync(entry.MediaId), @@ -80,23 +77,8 @@ public DiscoverPageModel( OnEntryRemovedAsync = entry => { ClearEntryFromItems(entry.MediaId); return Task.CompletedTask; }, SetErrorDetails = details => ErrorDetails = details, }); - - // Search results pagination: dedup + generation guarding live in the section; each new - // query re-Seeds it (the generation bump supersedes any in-flight Load More). - SearchSection = new PaginatedSection( - "SEARCH_MATCH", - (page, _, ct) => _aniListClient.SearchAnimePageAsync(_activeSearchQuery, AdultFilter, page, SearchPerPage, ct), - item => item.Node?.Id ?? 0); - SearchSection.Changed += () => - { - OnPropertyChanged(nameof(SearchIsLoadingMore)); - LoadMoreSearchResultsCommand.NotifyCanExecuteChanged(); - }; } - /// false = SFW only; null omits the filter (adult toggle on), letting 18+ titles match. - private static bool? AdultFilter => AppSettings.DisplayAdultContent ? null : false; - // ── Main page state ────────────────────────────────────────────── // Discover is public, so unlike My Anime there are no auth states: // InitialLoading → Content | Error @@ -141,6 +123,22 @@ private Task LoadMoreSection(string? sectionKey) return Task.CompletedTask; } + // A refresh being in flight means the row is not marked busy — PaginatedSection only knows + // about its own operations. That matters because DiscoverSectionFetch reads + // AppSettings.DisplayAdultContent live, per page: a Load More racing an adult-toggle + // refresh fetches under the NEW filter and appends onto items fetched under the OLD one, + // mixing 18+ results into a row that was SFW. A successful refresh re-Seeds and the + // generation bump discards the stray page, but a FAILED refresh never seeds — and Discover + // deliberately keeps showing content on refresh failure, so the mixed row is what the user + // is left looking at. + // + // Both flags are needed: IsBusy only goes up once the fetch starts, leaving the auth read + // ahead of it as an open window. + if (IsBusy || _refreshEvaluating) + { + return Task.CompletedTask; + } + return _listOps.RunAsync( $"Discover {section} · Load More", "discover", @@ -149,173 +147,54 @@ private Task LoadMoreSection(string? sectionKey) () => row.Items.Count); } - // ── Search ─────────────────────────────────────────────────────── - - /// Search results with infinite scroll; re-seeded per query. - public PaginatedSection SearchSection { get; } - - [ObservableProperty] - private string _searchText = string.Empty; + // ── Error state ────────────────────────────────────────────────── - /// Toolbar-icon toggle, mirroring My Anime's search reveal: shows/hides the search bar; - /// hiding clears the query, which restores the rows. [ObservableProperty] - private bool _isSearchVisible; - - [RelayCommand] - private void ToggleSearch() - { - IsSearchVisible = !IsSearchVisible; - if (!IsSearchVisible) - { - SearchText = string.Empty; - } - } + private string _errorTitle = string.Empty; - /// True while a query of + characters is entered — swaps the - /// section rows for the results list. The rows stay alive underneath, so clearing the search - /// restores them instantly with zero refetch. [ObservableProperty] - [NotifyPropertyChangedFor(nameof(AreSectionsVisible))] - private bool _isSearchActive; - - public bool AreSectionsVisible => !IsSearchActive; + private string _errorSubtitle = string.Empty; - /// True from first qualifying keystroke until the winning (non-superseded) fetch settles. [ObservableProperty] - private bool _isSearching; + private string _errorIconGlyph = string.Empty; [ObservableProperty] - private bool _hasNoSearchResults; - - public bool SearchIsLoadingMore => SearchSection.IsLoadingMore; - - partial void OnSearchTextChanged(string value) - { - // Cancel + dispose any pending debounce timer and any in-flight fetch it started, so the - // per-keystroke CTSs (and their Task.Delay registrations) don't accumulate over a session. - _searchDebounceCts?.Cancel(); - _searchDebounceCts?.Dispose(); - _searchDebounceCts = null; - - var query = value?.Trim() ?? string.Empty; - if (query.Length < SearchMinLength) - { - _activeSearchQuery = string.Empty; - IsSearchActive = false; - IsSearching = false; - HasNoSearchResults = false; - SearchSection.Reset(); - return; - } + private string _errorDetails = string.Empty; - IsSearchActive = true; - IsSearching = true; - HasNoSearchResults = false; // a previous query's empty state must not show under the new fetch - _searchDebounceCts = new CancellationTokenSource(); - _ = DebouncedSearchAsync(query, _searchDebounceCts.Token); - } + // ── Loading ────────────────────────────────────────────────────── - private async Task DebouncedSearchAsync(string query, CancellationToken token) + public async Task LoadAsync(bool forceReload = false) { - try - { - await Task.Delay(SearchDebounceDelay, token); - } - catch (TaskCanceledException) + if (IsBusy || _refreshEvaluating) { - // Another keystroke came in — this search is superseded. return; } - _activeSearchQuery = query; - _logger.LogInformation("Discover search firing for \"{Query}\"", query); - + // _refreshEvaluating is raised before the FIRST await, unlike IsBusy which is only set + // once the fetch actually starts. The auth read in LoadCoreAsync suspends while IsBusy is + // still false, so a row near its threshold could start a Load More that sailed past + // LoadMoreSection's IsBusy check, fetch under the new filter, and append onto rows still + // holding the old context. Gating Load More on IsBusy alone left exactly that window open. + _refreshEvaluating = true; try { - var (items, pageInfo) = await _aniListClient.SearchAnimePageAsync( - query, AdultFilter, page: 1, perPage: SearchPerPage, cancellationToken: token); - if (token.IsCancellationRequested || !string.Equals(_activeSearchQuery, query, StringComparison.Ordinal)) - { - return; // superseded while the fetch was in flight - } - - SearchSection.Seed(items, pageInfo); - HasNoSearchResults = items.Count == 0; - } - catch (OperationCanceledException) - { - return; - } - catch (Exception ex) - { - if (!string.Equals(_activeSearchQuery, query, StringComparison.Ordinal)) - { - return; - } - - // Keep whatever results are showing; the snackbar is the failure signal. - var apiEx = ex as AniListApiException; - await _feedback.ShowSnackbarAsync(apiEx?.UserTitle ?? "Search failed. Please try again."); - _errorReportService.Record(ex, "Discover search"); + await LoadCoreAsync(forceReload); } finally { - // Only the still-active, non-superseded query owns the spinner. The token check matters: - // a cancelled search can reach here BEFORE its successor's debounce sets _activeSearchQuery, - // and must not clear the spinner the successor's keystroke just turned on. - if (!token.IsCancellationRequested && string.Equals(_activeSearchQuery, query, StringComparison.Ordinal)) - { - IsSearching = false; - } + _refreshEvaluating = false; } } - [RelayCommand] - private Task LoadMoreSearchResults() - // Via ListOperationRunner like the section rows: PaginatedSection.LoadMoreAsync only - // swallows cancellation, so a network/API failure here would otherwise propagate out of - // the CollectionView's threshold command and crash. The runner swallows + snackbars it. - => SearchSection.CanLoadMore - ? _listOps.RunAsync( - "Discover Search · Load More", - "discover-search", - 0, - () => SearchSection.LoadMoreAsync(), - () => SearchSection.Items.Count) - : Task.CompletedTask; - - // ── Error state ────────────────────────────────────────────────── - - [ObservableProperty] - private string _errorTitle = string.Empty; - - [ObservableProperty] - private string _errorSubtitle = string.Empty; - - [ObservableProperty] - private string _errorIconGlyph = string.Empty; - - [ObservableProperty] - private string _errorDetails = string.Empty; - - // ── Loading ────────────────────────────────────────────────────── - - public async Task LoadAsync(bool forceReload = false) + private async Task LoadCoreAsync(bool forceReload) { - if (IsBusy) - { - return; - } - var displayAdult = AppSettings.DisplayAdultContent; var now = _timeProvider.GetUtcNow(); - // Two things invalidate the cached, viewer-relative section data AND any active search: + // Two things invalidate the cached, viewer-relative section data: // - an auth flip: mediaListEntry chips ride the results, so they must be refetched. - // - an adult-toggle flip: the search's AdultFilter changes, and stale results fetched - // under the old filter (e.g. 18+ covers after turning the toggle OFF) must not linger - // until the user edits the query. + // - an adult-toggle flip: it changes both the query filters and which sections exist. + // SearchPageModel runs the same check against its own results in OnAppearingAsync. var isAuthenticated = !string.IsNullOrWhiteSpace(await _authService.GetAccessTokenAsync()); var authChanged = _hasLoaded && isAuthenticated != _loadedAuthenticated; var adultChanged = _hasLoaded && _loadedWithAdultContent != displayAdult; @@ -325,15 +204,6 @@ public async Task LoadAsync(bool forceReload = false) "Discover cache invalidated (authChanged={AuthChanged}, adultChanged={AdultChanged}).", authChanged, adultChanged); forceReload = true; - IsSearchVisible = false; - if (!string.IsNullOrEmpty(SearchText)) - { - SearchText = string.Empty; // OnSearchTextChanged resets the search state - } - else - { - SearchSection.Reset(); // empty SearchText leaves no keystroke to trigger the reset - } } if (!forceReload @@ -448,7 +318,7 @@ private async Task NavigateToMedia(BrowseMediaItem? item) } // Same guard as the details-page carousels: Media Details queries type: ANIME, so a - // non-anime id (possible in search results) would 404. + // non-anime id would 404. if (media is { IsAnime: false }) { await _feedback.ShowToastAsync("Manga & Novel details aren't supported yet."); @@ -508,7 +378,7 @@ private void ClearEntryFromItems(int mediaId) } private IEnumerable AllItems() => - Rows.SelectMany(row => row.Items).Concat(SearchSection.Items); + Rows.SelectMany(row => row.Items); [RelayCommand] private async Task ViewAll(string? sectionKey) diff --git a/src/PageModels/MediaBrowsePageModel.cs b/src/PageModels/MediaBrowsePageModel.cs index d5ba070b..95defc1d 100644 --- a/src/PageModels/MediaBrowsePageModel.cs +++ b/src/PageModels/MediaBrowsePageModel.cs @@ -254,12 +254,23 @@ private void OnItemsChanged() [RelayCommand(CanExecute = nameof(CanLoadMore))] private Task LoadMore() - => _listOps.RunAsync( - $"MediaBrowse {_definition?.Section} · Load More", - "browse", - (int?)_definition?.Section ?? 0, - () => _items.LoadMoreAsync(_scope.EnsureActive()), - () => _items.Items.Count); + // Same guard as Discover's LoadMoreSection: IsBusy means a reload is in flight, and the + // section is not marked busy during it. DiscoverSectionFetch reads + // AppSettings.DisplayAdultContent live per page, so a Load More racing an adult-toggle + // reload appends new-filter items onto old-filter ones. The page load scope does not cover + // this ordering — Begin() cancels the PREVIOUS token, but a Load More started after the + // reload began shares the reload's token and so survives it. + // + // Checked here rather than in CanExecute: IsBusy changing does not notify the command, so + // folding it into the predicate risks leaving Load More stuck disabled after a reload. + => IsBusy + ? Task.CompletedTask + : _listOps.RunAsync( + $"MediaBrowse {_definition?.Section} · Load More", + "browse", + (int?)_definition?.Section ?? 0, + () => _items.LoadMoreAsync(_scope.EnsureActive()), + () => _items.Items.Count); private bool CanLoadMore() => _items.CanLoadMore; diff --git a/src/PageModels/MyAnimePageModel.cs b/src/PageModels/MyAnimePageModel.cs index 7bff8ae9..500675bb 100644 --- a/src/PageModels/MyAnimePageModel.cs +++ b/src/PageModels/MyAnimePageModel.cs @@ -68,7 +68,7 @@ public partial class MyAnimePageModel : ObservableObject private bool _isAuthenticated; [ObservableProperty] - private string _title = "My Anime"; + private string _title = "Library"; [ObservableProperty] private ObservableCollection _sections = []; @@ -251,7 +251,7 @@ public async Task LoadAsync(bool forceReload = false) CurrentState = PageState.InitialLoading; } - Title = "My Anime"; + Title = "Library"; ErrorDetails = string.Empty; // Sync display preferences from AniList before building the list so that diff --git a/src/PageModels/SearchPageModel.cs b/src/PageModels/SearchPageModel.cs new file mode 100644 index 00000000..7598c42b --- /dev/null +++ b/src/PageModels/SearchPageModel.cs @@ -0,0 +1,433 @@ +using CommunityToolkit.Mvvm.ComponentModel; +using CommunityToolkit.Mvvm.Input; +using Microsoft.Extensions.Logging; +using AniSprinkles.Utilities; + +namespace AniSprinkles.PageModels; + +/// +/// Search tab (issues #16/#43): global anime search, no auth required. Extracted from +/// when search became its own tab — the debounce, generation +/// guarding and long-press write-back are the same logic that shipped on Discover. +/// +/// Singleton, like the other tab page models, so the query and its results survive a tab +/// switch. That is deliberate here: coming back to the Search tab should show what you were +/// looking at, not a cleared box. An auth or adult-toggle flip does clear it, because both +/// change what the results should contain. +/// +public partial class SearchPageModel : ObservableObject +{ + private static readonly TimeSpan SearchDebounceDelay = TimeSpan.FromMilliseconds(600); + private const int SearchPerPage = 20; + + /// Below this many trimmed characters no search fires (rate-limit caution + junk-match avoidance). + private const int SearchMinLength = 2; + + private readonly IAniListClient _aniListClient; + private readonly IAuthService _authService; + private readonly INavigationService _navigationService; + private readonly IUserFeedback _feedback; + private readonly ErrorReportService _errorReportService; + private readonly ILogger _logger; + private readonly EntryActionCoordinator _entryActions; + private readonly ListOperationRunner _listOps; + + // Search debounce state: a new keystroke cancels the pending (or in-flight) search. + private CancellationTokenSource? _searchDebounceCts; + private string _activeSearchQuery = string.Empty; + + /// The DisplayAdultContent value page 1 of the current results was fetched under; + /// null when nothing is seeded. Every later page reuses it so one result set cannot mix + /// policies. See . + private bool? _seededDisplayAdult; + + // Context the current results were fetched under, so a flip can invalidate them. + private bool _hasSearchedThisSession; + private bool _searchedWithAdultContent; + private bool _searchedAuthenticated; + + public SearchPageModel( + IAniListClient aniListClient, + IAuthService authService, + INavigationService navigationService, + IUserFeedback feedback, + ErrorReportService errorReportService, + ILogger logger) + { + _aniListClient = aniListClient; + _authService = authService; + _navigationService = navigationService; + _feedback = feedback; + _errorReportService = errorReportService; + _logger = logger; + _listOps = new ListOperationRunner(logger, feedback); + + // Long-press flows, as on Discover. A successful mutation is written back onto every + // matching result so the status chips stay right without refetching the query. + _entryActions = new EntryActionCoordinator(aniListClient, errorReportService, logger, new EntryActionHost + { + OpenDetailsAsync = entry => NavigateToMediaByIdAsync(entry.MediaId), + OnEntrySavedInPlaceAsync = entry => { ApplyEntryToItems(entry); return Task.CompletedTask; }, + OnEntryStatusChangedAsync = entry => { ApplyEntryToItems(entry); return Task.CompletedTask; }, + OnEntryRemovedAsync = entry => { ClearEntryFromItems(entry.MediaId); return Task.CompletedTask; }, + SetErrorDetails = details => ErrorDetails = details, + }); + + // Results pagination: dedup + generation guarding live in the section; each new query + // re-Seeds it (the generation bump supersedes any in-flight Load More). + // + // Later pages reuse the filter page 1 was fetched under, NOT a fresh read of AdultFilter. + // The adult toggle does not reach AppSettings when the user flips it: Settings debounces + // for 1500 ms, saves, and only applies the value from the server response. So the user can + // toggle, return to Search inside that window, have OnAppearingAsync read the OLD value and + // find nothing to invalidate, and then have the new value land — at which point a live read + // here would page a different policy onto the results already on screen. Turning adult + // content OFF is the bad direction: 18+ page-1 items stay visible with SFW pages beneath. + SearchSection = new PaginatedSection( + "SEARCH_MATCH", + (page, _, ct) => _aniListClient.SearchAnimePageAsync( + _activeSearchQuery, ActiveAdultFilter, page, SearchPerPage, ct), + item => item.Node?.Id ?? 0); + SearchSection.Changed += () => + { + OnPropertyChanged(nameof(SearchIsLoadingMore)); + LoadMoreSearchResultsCommand.NotifyCanExecuteChanged(); + }; + } + + /// false = SFW only; null omits the filter (adult toggle on), letting 18+ titles match. + private static bool? ToAdultFilter(bool displayAdult) => displayAdult ? null : false; + + /// The filter as the setting stands right now — used to seed a new query. + private static bool? AdultFilter => ToAdultFilter(AppSettings.DisplayAdultContent); + + /// + /// The filter every page of the CURRENT result set must use. Falls back to the live setting + /// only before a query has been seeded. + /// + /// Deliberately keyed off the raw DisplayAdultContent bool rather than the derived + /// filter: the filter's own null means "adult allowed", so it cannot double as + /// "nothing seeded yet" — a null-coalesce here would silently fall back to a live read in + /// exactly the adult-enabled case. + /// + private bool? ActiveAdultFilter => + _seededDisplayAdult is bool seeded ? ToAdultFilter(seeded) : AdultFilter; + + /// Search results with infinite scroll; re-seeded per query. + public PaginatedSection SearchSection { get; } + + [ObservableProperty] + private string _searchText = string.Empty; + + /// True once a query of + characters is entered — swaps the + /// idle prompt for the results list. + [ObservableProperty] + [NotifyPropertyChangedFor(nameof(IsIdle))] + private bool _isSearchActive; + + /// Nothing typed yet (or below the minimum): show the "search for something" prompt. + /// The Search tab has no rows to fall back to the way Discover did. + public bool IsIdle => !IsSearchActive; + + /// True from first qualifying keystroke until the winning (non-superseded) fetch settles. + [ObservableProperty] + private bool _isSearching; + + [ObservableProperty] + private bool _hasNoSearchResults; + + [ObservableProperty] + private string _errorDetails = string.Empty; + + public bool SearchIsLoadingMore => SearchSection.IsLoadingMore; + + /// + /// Called from the page's OnAppearing. Discover used to fold this into its LoadAsync; with + /// search on its own tab there is no load to piggyback on, so the check happens on appear. + /// An auth flip changes the mediaListEntry chips riding the results, and an adult-toggle flip + /// changes AdultFilter — stale results fetched under the old filter (18+ covers after turning + /// the toggle off) must not linger until the user edits the query. + /// + public async Task OnAppearingAsync() + { + var displayAdult = AppSettings.DisplayAdultContent; + var isAuthenticated = !string.IsNullOrWhiteSpace(await _authService.GetAccessTokenAsync()); + + if (!_hasSearchedThisSession) + { + _searchedWithAdultContent = displayAdult; + _searchedAuthenticated = isAuthenticated; + return; + } + + var authChanged = isAuthenticated != _searchedAuthenticated; + var adultChanged = displayAdult != _searchedWithAdultContent; + if (!authChanged && !adultChanged) + { + return; + } + + _logger.LogInformation( + "Search results invalidated (authChanged={AuthChanged}, adultChanged={AdultChanged}).", + authChanged, adultChanged); + + _searchedWithAdultContent = displayAdult; + _searchedAuthenticated = isAuthenticated; + + if (!string.IsNullOrEmpty(SearchText)) + { + // Re-run the same query under the new context rather than dumping what the user typed. + var query = SearchText; + SearchText = string.Empty; // OnSearchTextChanged resets the section and cancels in-flight work + SearchText = query; + } + else + { + ResetResults(); + } + } + + partial void OnSearchTextChanged(string value) + { + // Cancel + dispose any pending debounce timer and any in-flight fetch it started, so the + // per-keystroke CTSs (and their Task.Delay registrations) don't accumulate over a session. + _searchDebounceCts?.Cancel(); + _searchDebounceCts?.Dispose(); + _searchDebounceCts = null; + + var query = value?.Trim() ?? string.Empty; + if (query.Length < SearchMinLength) + { + _activeSearchQuery = string.Empty; + IsSearchActive = false; + IsSearching = false; + HasNoSearchResults = false; + ResetResults(); + return; + } + + IsSearchActive = true; + IsSearching = true; + HasNoSearchResults = false; // a previous query's empty state must not show under the new fetch + + // Drop the previous query's results the moment a new query starts. Keeping them on screen + // through the debounce reads nicer, but it leaves items belonging to the OLD query sitting + // in the section with HasNextPage still set while _activeSearchQuery has moved on. If the + // new query's page 1 then FAILS, nothing re-seeds, and scrolling to the threshold fetches + // page 2 of the new query and appends it to the old query's results — one list, silently + // mixing two searches. Reset clears HasNextPage (so Load More cannot fire until a + // successful Seed) and bumps the generation, superseding any Load More already in flight. + ResetResults(); + + _searchDebounceCts = new CancellationTokenSource(); + _ = DebouncedSearchAsync(query, _searchDebounceCts.Token); + } + + private async Task DebouncedSearchAsync(string query, CancellationToken token) + { + try + { + await Task.Delay(SearchDebounceDelay, token); + } + catch (TaskCanceledException) + { + // Another keystroke came in — this search is superseded. + return; + } + + _activeSearchQuery = query; + _logger.LogInformation("Search firing for \"{Query}\"", query); + + // Record the context at issue time, not on success. If this is recorded only after the + // fetch lands, a first search still in flight leaves _hasSearchedThisSession false, so a + // user who tabs away, flips the adult toggle and returns hits OnAppearingAsync's + // "nothing to invalidate" branch — which baselines the NEW context without cancelling + // this request. The old-filter response would then land and be marked current, and no + // later appearance would ever invalidate it. Recording here means that user takes the + // normal path instead, which cancels this fetch and re-runs the query. + _hasSearchedThisSession = true; + _searchedWithAdultContent = AppSettings.DisplayAdultContent; + + // Pin the filter for this result set. Read once here so page 1 below and every Load More + // afterwards agree, no matter what the setting does in between. + _seededDisplayAdult = AppSettings.DisplayAdultContent; + + // Auth is read here too, so both halves of the context describe the same moment rather than + // the adult flag coming from issue time and auth from whenever the page last appeared. + // Deliberately outside the fetch's try below: that catch reports "Search failed", and a + // token read blowing up must not be presented to the user as a failed search. On failure, + // keep whatever OnAppearingAsync last recorded instead of guessing — a wrong value here + // either strands stale results or forces a pointless refetch. + bool? authenticated = null; + try + { + authenticated = !string.IsNullOrWhiteSpace(await _authService.GetAccessTokenAsync()); + } + catch (Exception ex) + { + _logger.LogWarning(ex, "Search auth-context read failed; keeping the previous baseline."); + } + + // That await is a new suspension point, so a keystroke may have superseded this search + // while it ran. Bail before spending the request — and before writing the context, since + // this continuation can resume AFTER a newer search has already recorded its own. Writing + // it here would let an older read clobber a newer one (reachable via token expiry, the one + // way auth flips without leaving the tab). + if (token.IsCancellationRequested) + { + return; + } + + if (authenticated.HasValue) + { + _searchedAuthenticated = authenticated.Value; + } + + try + { + var (items, pageInfo) = await _aniListClient.SearchAnimePageAsync( + query, ActiveAdultFilter, page: 1, perPage: SearchPerPage, cancellationToken: token); + if (token.IsCancellationRequested || !string.Equals(_activeSearchQuery, query, StringComparison.Ordinal)) + { + return; // superseded while the fetch was in flight + } + + SearchSection.Seed(items, pageInfo); + HasNoSearchResults = items.Count == 0; + } + catch (OperationCanceledException) + { + return; + } + catch (Exception ex) + { + if (!string.Equals(_activeSearchQuery, query, StringComparison.Ordinal)) + { + return; + } + + // Keep whatever results are showing; the snackbar is the failure signal. + var apiEx = ex as AniListApiException; + await _feedback.ShowSnackbarAsync(apiEx?.UserTitle ?? "Search failed. Please try again."); + _errorReportService.Record(ex, "Search"); + } + finally + { + // Only the still-active, non-superseded query owns the spinner. The token check matters: + // a cancelled search can reach here BEFORE its successor's debounce sets _activeSearchQuery, + // and must not clear the spinner the successor's keystroke just turned on. + if (!token.IsCancellationRequested && string.Equals(_activeSearchQuery, query, StringComparison.Ordinal)) + { + IsSearching = false; + } + } + } + + [RelayCommand] + private Task LoadMoreSearchResults() + // Via ListOperationRunner: PaginatedSection.LoadMoreAsync only swallows cancellation, so a + // network/API failure here would otherwise propagate out of the CollectionView's threshold + // command and crash. The runner swallows + snackbars it. + // + // No in-flight check needed: OnSearchTextChanged resets the section on every new query, so + // HasNextPage (and therefore CanLoadMore) stays false until a successful Seed for the + // CURRENT query. There is no window where the section can page a query its items did not + // come from. + => SearchSection.CanLoadMore + ? _listOps.RunAsync( + "Search · Load More", + "search", + 0, + () => SearchSection.LoadMoreAsync(), + () => SearchSection.Items.Count) + : Task.CompletedTask; + + [RelayCommand] + private async Task NavigateToMedia(BrowseMediaItem? item) + { + // A long-press release still triggers the card's tap recognizer — swallow it so the + // action sheet doesn't get a navigation underneath. + if (Views.CollectionViewLongPress.ShouldSuppressTap()) + { + return; + } + + var media = item?.Node; + var mediaId = media?.Id ?? 0; + _logger.LogInformation("NAVTRACE Search NavigateToMedia called with mediaId={MediaId}", mediaId); + if (mediaId <= 0) + { + return; + } + + // Media Details queries type: ANIME, so a non-anime id (search can return manga and + // novels) would 404. + if (media is { IsAnime: false }) + { + await _feedback.ShowToastAsync("Manga & Novel details aren't supported yet."); + return; + } + + await NavigateToMediaByIdAsync(mediaId); + } + + private Task NavigateToMediaByIdAsync(int mediaId) + => _navigationService.GoToAsync("media-details", animate: false, new Dictionary + { + ["mediaId"] = mediaId, + }); + + /// Long-press entry point: full menu for on-list media, Add to list otherwise. + [RelayCommand] + private async Task ShowItemActions(BrowseMediaItem? item) + { + if (item?.Node is null) + { + return; + } + + var token = await _authService.GetAccessTokenAsync(); + if (string.IsNullOrWhiteSpace(token)) + { + await _feedback.ShowToastAsync("Sign in to manage your list."); + return; + } + + var entry = item.ToListEntry(); + if (item.Node.ListStatus is null) + { + await _entryActions.ShowAddToListAsync(entry); + } + else + { + await _entryActions.ShowEntryMenuAsync(entry); + } + } + + /// + /// Clears the results and the adult filter they were pinned to, together. Always use this + /// rather than calling SearchSection.Reset() directly: a snapshot outliving the results + /// it describes would pin the NEXT query to the previous query's policy. + /// + private void ResetResults() + { + SearchSection.Reset(); + _seededDisplayAdult = null; + } + + private void ApplyEntryToItems(MediaListEntry entry) + { + foreach (var item in SearchSection.Items.Where(i => i.Node?.Id == entry.MediaId)) + { + item.ApplyListEntry(entry); + } + } + + private void ClearEntryFromItems(int mediaId) + { + foreach (var item in SearchSection.Items.Where(i => i.Node?.Id == mediaId)) + { + item.ClearListEntry(); + } + } +} diff --git a/src/PageModels/SettingsPageModel.cs b/src/PageModels/SettingsPageModel.cs index c90453ce..c038898f 100644 --- a/src/PageModels/SettingsPageModel.cs +++ b/src/PageModels/SettingsPageModel.cs @@ -50,7 +50,7 @@ public partial class SettingsPageModel : ObservableObject /// /// True when the singleton ViewModel already has authenticated profile data - /// available for immediate display (e.g. after a flyout page switch). + /// available for immediate display (e.g. after a tab switch). /// public bool HasLoadedData => _loadedUser is not null; diff --git a/src/Pages/DiscoverPage.xaml b/src/Pages/DiscoverPage.xaml index 0d9dc617..6090e3ed 100644 --- a/src/Pages/DiscoverPage.xaml +++ b/src/Pages/DiscoverPage.xaml @@ -4,26 +4,11 @@ xmlns:pageModels="clr-namespace:AniSprinkles.PageModels" xmlns:views="clr-namespace:AniSprinkles.Views" xmlns:toolkit="http://schemas.microsoft.com/dotnet/2022/maui/toolkit" - xmlns:icons="clr-namespace:IconFont.Maui.FluentIcons;assembly=IconFont.Maui.FluentIcons" x:Class="AniSprinkles.Pages.DiscoverPage" x:DataType="pageModels:DiscoverPageModel" Title="{Binding Title}" Shell.TitleColor="{Binding Title, Converter={StaticResource RainbowAccentConverter}}"> - - - - - - - - - + + + diff --git a/src/Pages/FeedPage.xaml.cs b/src/Pages/FeedPage.xaml.cs new file mode 100644 index 00000000..30811592 --- /dev/null +++ b/src/Pages/FeedPage.xaml.cs @@ -0,0 +1,13 @@ +namespace AniSprinkles.Pages; + +/// +/// Placeholder for the Feed tab (issue #43); filled in when the AniList social +/// features in #14 are built. Intentionally has no PageModel. +/// +public partial class FeedPage : ContentPage +{ + public FeedPage() + { + InitializeComponent(); + } +} diff --git a/src/Pages/MyAnimePage.xaml b/src/Pages/MyAnimePage.xaml index 50ebe014..c123a635 100644 --- a/src/Pages/MyAnimePage.xaml +++ b/src/Pages/MyAnimePage.xaml @@ -8,7 +8,7 @@ x:Class="AniSprinkles.Pages.MyAnimePage" x:DataType="pageModels:MyAnimePageModel" Title="{Binding Title}" - Shell.TitleColor="{Binding Title, Converter={StaticResource RainbowAccentConverter}}"> + Shell.TitleColor="{Binding Converter={StaticResource RainbowAccentConverter}, ConverterParameter='My Anime'}"> + + + + + + diff --git a/src/Pages/MyMangaPage.xaml.cs b/src/Pages/MyMangaPage.xaml.cs new file mode 100644 index 00000000..24f5ae6c --- /dev/null +++ b/src/Pages/MyMangaPage.xaml.cs @@ -0,0 +1,13 @@ +namespace AniSprinkles.Pages; + +/// +/// Placeholder for the manga half of the Library tab (issue #43); the real list +/// arrives with manga support in #12. Intentionally has no PageModel. +/// +public partial class MyMangaPage : ContentPage +{ + public MyMangaPage() + { + InitializeComponent(); + } +} diff --git a/src/Pages/SearchPage.xaml b/src/Pages/SearchPage.xaml new file mode 100644 index 00000000..f78139e1 --- /dev/null +++ b/src/Pages/SearchPage.xaml @@ -0,0 +1,115 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/src/Pages/SearchPage.xaml.cs b/src/Pages/SearchPage.xaml.cs new file mode 100644 index 00000000..d0ef310f --- /dev/null +++ b/src/Pages/SearchPage.xaml.cs @@ -0,0 +1,83 @@ +using AniSprinkles.PageModels; +using AniSprinkles.Utilities; +using AniSprinkles.Views; + +namespace AniSprinkles.Pages; + +/// +/// Search tab (issues #16/#43). Unlike Discover and My Anime there is no deferred content host: +/// the page is an Entry plus one CollectionView, light enough to build inline during the tab +/// transition. +/// +public partial class SearchPage : ContentPage +{ + private SearchPageModel? _viewModel; + + public SearchPage() + { + InitializeComponent(); + + // Same long-press hook the Discover rows and search results used. + CollectionViewLongPress.Attach(SearchResultsList, item => + { + if (BindingContext is SearchPageModel vm && vm.ShowItemActionsCommand.CanExecute(item)) + { + vm.ShowItemActionsCommand.Execute(item); + } + }); + } + + public SearchPage(SearchPageModel viewModel) + : this() + { + SetViewModel(viewModel); + } + + protected override async void OnAppearing() + { + base.OnAppearing(); + EnsureViewModel(); + if (_viewModel is null) + { + return; + } + + // Only steal focus when there is nothing to look at. Returning to the tab with results + // already on screen should not throw the keyboard up over them. + if (string.IsNullOrEmpty(_viewModel.SearchText)) + { + Dispatcher.Dispatch(() => SearchEntry.Focus()); + } + + await _viewModel.OnAppearingAsync(); + } + + private void EnsureViewModel() + { + if (_viewModel is not null) + { + return; + } + + try + { + var services = ServiceProviderHelper.GetServiceProvider(); + var viewModel = services?.GetService(); + if (viewModel is null) + { + return; + } + + SetViewModel(viewModel); + } + catch (InvalidOperationException) + { + } + } + + private void SetViewModel(SearchPageModel viewModel) + { + _viewModel = viewModel; + BindingContext = viewModel; + } +} diff --git a/src/Pages/SettingsPage.xaml.cs b/src/Pages/SettingsPage.xaml.cs index 99967a49..9d4b6f49 100644 --- a/src/Pages/SettingsPage.xaml.cs +++ b/src/Pages/SettingsPage.xaml.cs @@ -43,7 +43,7 @@ protected override async void OnAppearing() return; } - // Content survived the flyout switch — just refresh data in background. + // Content survived the tab switch — just refresh data in background. if (LoadedContentHost.Content is not null) { await _viewModel.LoadAsync(); diff --git a/src/Services/AuthService.cs b/src/Services/AuthService.cs index 66da0b55..251254f6 100644 --- a/src/Services/AuthService.cs +++ b/src/Services/AuthService.cs @@ -35,7 +35,35 @@ public AuthService(ILogger logger) if (IsExpired()) { _logger.LogInformation("AUTH token-check: expired (expiresAt={ExpiresAt}), signing out.", ExpiresAt); - await SignOutAsync(); + + // Guarded for the same reason as LoadAsync: SignOutAsync clears SecureStorage and + // drives the Android CookieManager on the main thread, either of which can throw, and + // this runs inside the token check that every tab's async void OnAppearing awaits. + // The answer is "no valid token" either way, so a failed cleanup must not become a + // crash. Explicit sign-out (the Settings button) still calls SignOutAsync directly + // and keeps surfacing its failures. + try + { + await SignOutAsync(); + } + catch (OperationCanceledException) when (cancellationToken.IsCancellationRequested) + { + // Propagate ONLY the caller's own cancellation. The filter is load-bearing: ten + // call sites across six page models call GetAccessTokenAsync with no token at all, + // from async void OnAppearing paths with nothing to catch. SignOutAsync drives the + // Android CookieManager through MainThread.InvokeOnMainThreadAsync, which can + // surface a cancellation of its own during teardown — rethrowing that to a caller + // who never asked for cancellation turns a survivable cleanup failure into a + // crash. Unfiltered, this catch did exactly that. + throw; + } + catch (Exception ex) + { + _logger.LogError(ex, "AUTH sign-out after expiry failed; reporting no token anyway."); + AccessToken = null; + ExpiresAt = null; + } + return null; } @@ -133,11 +161,39 @@ private static Uri BuildAuthorizeUri() private async Task LoadAsync(CancellationToken cancellationToken) { - AccessToken = await SecureStorage.Default.GetAsync(TokenKey); - var rawExpiry = await SecureStorage.Default.GetAsync(TokenExpiryKey); - if (DateTimeOffset.TryParse(rawExpiry, out var expiry)) + // SecureStorage sits on the Android keystore, which can fail for reasons that have nothing + // to do with us (corrupted keystore, a restored backup, a device-credential change). Those + // surface as assorted platform exceptions, hence the broad catch. Letting one escape would + // take the app down: every tab page model calls GetAccessTokenAsync from an async void + // OnAppearing, where there is nothing to catch it. An unreadable token is functionally the + // same as an absent one, so fall back to signed-out and let the user sign in again. + try + { + AccessToken = await SecureStorage.Default.GetAsync(TokenKey); + var rawExpiry = await SecureStorage.Default.GetAsync(TokenExpiryKey); + if (DateTimeOffset.TryParse(rawExpiry, out var expiry)) + { + ExpiresAt = expiry; + } + } + catch (OperationCanceledException) when (cancellationToken.IsCancellationRequested) + { + // Cancellation is the caller's business, not a storage failure. The detail page models + // pass a PageLoadScope token into GetAccessTokenAsync and expect navigating away to + // cancel rather than to quietly report "signed out" and wipe the shared auth state. + // Nothing below currently takes the token — MAUI's ISecureStorage.GetAsync has no + // overload for one — but this keeps the broad catch from swallowing a cancellation if + // that changes, which is exactly the kind of thing that would be silent for months. + // + // Filtered so only the CALLER'S cancellation escapes: most callers pass no token and + // await this from async void lifecycle paths, where an unfiltered rethrow is a crash. + throw; + } + catch (Exception ex) { - ExpiresAt = expiry; + _logger.LogError(ex, "AUTH token-load failed; treating as signed out."); + AccessToken = null; + ExpiresAt = null; } } diff --git a/src/Views/DiscoverLoadedContentView.xaml b/src/Views/DiscoverLoadedContentView.xaml index c461ae0f..4b9b83b0 100644 --- a/src/Views/DiscoverLoadedContentView.xaml +++ b/src/Views/DiscoverLoadedContentView.xaml @@ -4,91 +4,14 @@ xmlns:pageModels="clr-namespace:AniSprinkles.PageModels" xmlns:views="clr-namespace:AniSprinkles.Views" xmlns:pullToRefresh="clr-namespace:Syncfusion.Maui.Toolkit.PullToRefresh;assembly=Syncfusion.Maui.Toolkit" - xmlns:icons="clr-namespace:IconFont.Maui.FluentIcons;assembly=IconFont.Maui.FluentIcons" x:Class="AniSprinkles.Views.DiscoverLoadedContentView" x:DataType="pageModels:DiscoverPageModel" x:Name="RootView"> - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - + +