diff --git a/.claude/skills/supabase-migration/SKILL.md b/.claude/skills/supabase-migration/SKILL.md index 702ebb9..d39092e 100644 --- a/.claude/skills/supabase-migration/SKILL.md +++ b/.claude/skills/supabase-migration/SKILL.md @@ -9,10 +9,10 @@ kasane ships its Supabase **publishable** key in the client bundle (`src/api/sup ## The two data classes -| Class | Tables | Rule | -| ------------------------------- | --------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------- | -| **Catalog** (public, read-only) | `series`, `arc_mappings`, `movies`, `search_aliases`, `genre_filters` | `for select using (true)`; `grant select ... to anon, authenticated`. No client writes, ever. | -| **User data** (owner-scoped) | `user_progress`, `user_preferences` | `for all using (auth.uid() = user_id) with check (auth.uid() = user_id)`; `grant select, insert, update, delete ... to authenticated` only. | +| Class | Tables | Rule | +| ------------------------------- | ---------------------------------------------------------------------------------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | +| **Catalog** (public, read-only) | `series`, `arc_mappings`, `movies`, `search_aliases`, `genre_filters`, `mangadex_series` | `for select using (true)`; `grant select ... to anon, authenticated`. No client writes, ever. `mangadex_series` is filled by `scripts/refresh-mangadex.ts` with the service role. | +| **User data** (owner-scoped) | `user_progress`, `user_preferences` | `for all using (auth.uid() = user_id) with check (auth.uid() = user_id)`; `grant select, insert, update, delete ... to authenticated` only. | A new table joins one of these classes. If it fits neither, that is the design question to resolve before writing SQL. diff --git a/.github/workflows/pull-request-checks.yml b/.github/workflows/pull-request-checks.yml index 67821fc..52f0473 100644 --- a/.github/workflows/pull-request-checks.yml +++ b/.github/workflows/pull-request-checks.yml @@ -16,6 +16,8 @@ concurrency: # whatever bun the machine has, so this is the only place CI's version is fixed. env: BUN_VERSION: 1.4.2 + # Netlify builds with the same major (`netlify.toml`). + NODE_VERSION: 24 jobs: # The `system-check` script minus `build:web`, which `build` owns so that the @@ -74,6 +76,13 @@ jobs: with: bun-version: ${{ env.BUN_VERSION }} + # `expo export` runs under Node and loads `metro.config.js`, which needs + # the type stripping of Node 24, the version Netlify builds with. + - name: 🟢 Set up Node + uses: actions/setup-node@v5 + with: + node-version: ${{ env.NODE_VERSION }} + - name: 📦 Install dependencies run: bun install --frozen-lockfile diff --git a/.gitignore b/.gitignore index 690822b..4832392 100644 --- a/.gitignore +++ b/.gitignore @@ -59,3 +59,12 @@ src-tauri/Cargo.lock .claude/*.lock .claude/settings.local.json + +# Supabase CLI local state (secrets, snapshots) +supabase/.temp/ +supabase/.branches/ +supabase/.snapshots/ + +# Netlify CLI state, and the edge bundler's lock of its own bootstrap modules. +.netlify/ +deno.lock diff --git a/app/_layout.tsx b/app/_layout.tsx index a17ed5e..e0d5505 100644 --- a/app/_layout.tsx +++ b/app/_layout.tsx @@ -13,7 +13,7 @@ import { StatusBar } from "expo-status-bar"; import * as SplashScreen from "expo-splash-screen"; import { CATALOG_QUERY_KEY, useCatalogQuery } from "@/queries/catalog"; import { COVERS_QUERY_KEY } from "@/queries/covers"; -import { MINUTE_MS, WEEK_MS } from "@/queries/shared"; +import { MINUTE_MS, WEEK_MS } from "@/data/time"; import { useFonts, SpaceGrotesk_400Regular, diff --git a/app/index.tsx b/app/index.tsx index efaac91..dd9163a 100644 --- a/app/index.tsx +++ b/app/index.tsx @@ -9,14 +9,14 @@ import { } from "react-native"; import { pairResults } from "@/data/pairing"; import { useCatalog, useGenreFilters } from "@/queries/catalog"; -import { useLatestAnime, useSearch } from "@/queries/search"; +import { useSearch } from "@/queries/search"; import { splitHiddenForAniList } from "@/data/genreFilters"; import { Footer } from "@/components/Footer"; import { SeriesCard } from "@/components/SeriesCard"; -import { GenreFilters } from "@/components/GenreFilters"; +import { HomeToolbar } from "@/components/HomeToolbar"; import { LatestReleases } from "@/components/LatestReleases"; -import { MappedOnlyToggle } from "@/components/MappedOnlyToggle"; import { useDebouncedValue } from "@/components/useDebouncedValue"; +import { useHomeChrome } from "@/state/homeChrome"; import { usePreferences } from "@/state/preferences"; import { COLOR, FONT, SPACE } from "@/theme"; @@ -26,6 +26,7 @@ export default function HomeScreen() { const hiddenGenres = usePreferences((s) => s.hiddenGenres); const genreFilters = useGenreFilters(); const [mappedOnly, setMappedOnly] = useState(true); + const [filtersOpen, setFiltersOpen] = useState(false); const { findMapping } = useCatalog(); // Chips update `hiddenGenres` immediately so they stay responsive, but the @@ -44,10 +45,8 @@ export default function HomeScreen() { error, } = useSearch({ query: debouncedQuery, filters, enabled: isSearching }); - const { data: latestAnime, isFetching: latestFetching } = useLatestAnime({ - filters, - enabled: !isSearching, - }); + // Scrolling the latest grid hands the screen over to the covers. + const immersive = useHomeChrome((s) => s.immersive); const pairedResults = useMemo( () => pairResults(searchResults ?? []), @@ -66,27 +65,36 @@ export default function HomeScreen() { ); const hiddenByMapping = pairedResults.length - visibleResults.length; + // One toolbar, headed in the latest grid and bare above search results. + const toolbar = ( + + ); + return ( - - Find which anime episodes cover which manga chapters. - - - - - - - + {!immersive && ( + + )} {error && ( Something went wrong. Try again. @@ -103,6 +111,8 @@ export default function HomeScreen() { data={visibleResults} keyExtractor={(item) => `series-${item.routeId}`} renderItem={({ item }) => } + ListHeaderComponent={toolbar} + ListHeaderComponentStyle={styles.listHeader} ListEmptyComponent={ !isFetching && query === debouncedQuery ? ( @@ -120,7 +130,7 @@ export default function HomeScreen() { /> ) : ( - + )} ); @@ -128,12 +138,6 @@ export default function HomeScreen() { const styles = StyleSheet.create({ root: { flex: 1, padding: SPACE.xl, gap: SPACE.xl }, - tagline: { - color: COLOR.textSecondary, - fontSize: 16, - letterSpacing: -0.2, - fontFamily: FONT.medium, - }, input: { backgroundColor: COLOR.surface, color: COLOR.textPrimary, @@ -146,6 +150,7 @@ const styles = StyleSheet.create({ borderLeftColor: COLOR.accent, }, spinnerWrap: { paddingTop: SPACE.xxxl }, + listHeader: { paddingBottom: SPACE.xl }, emptyWrap: { paddingTop: SPACE.page }, empty: { color: COLOR.textMuted, diff --git a/app/series/[id]/index.tsx b/app/series/[id]/index.tsx index 6e031ea..06fee15 100644 --- a/app/series/[id]/index.tsx +++ b/app/series/[id]/index.tsx @@ -7,9 +7,8 @@ import { } from "react-native"; import { useLocalSearchParams } from "expo-router"; import { detailStats } from "@/data/seriesStats"; -import { useFranchise, useMangaDex } from "@/queries/media"; +import { useMangaDex } from "@/queries/media"; import { useSeries } from "@/queries/series"; -import { FranchiseSeasons } from "@/components/FranchiseSeasons"; import { MappingSection } from "@/components/MappingSection"; import { SeriesHeader } from "@/components/SeriesHeader"; import { TitlesList } from "@/components/TitlesList"; @@ -25,10 +24,8 @@ export default function SeriesDetail() { Number.isNaN(mediaId) ? null : mediaId, ); const manga = entry?.manga ?? null; - const anime = entry?.anime ?? null; const { data: mangadex, isFetching: mangadexLoading } = useMangaDex(manga); - const { data: franchise } = useFranchise(anime); if (isLoading) { return ( @@ -47,12 +44,14 @@ export default function SeriesDetail() { } const { primary, badge, routeId } = entry; - const totalChapters = mangadex?.chapters ?? manga?.chapters ?? null; + // AniList's totals first: MangaDex only counts what it hosts, a fraction of + // a licensed run. MangaDex fills in while AniList has no total yet. + const totalChapters = manga?.chapters ?? mangadex?.chapters ?? null; const subParts = detailStats({ entry, mapping: resolved?.mapping ?? null, chapters: totalChapters, - volumes: mangadex?.volumes ?? manga?.volumes ?? null, + volumes: manga?.volumes ?? mangadex?.volumes ?? null, }); return ( @@ -64,10 +63,6 @@ export default function SeriesDetail() { isMapped={resolved?.source === "curated"} /> - {!!anime && !!franchise && franchise.seasons.length > 1 && ( - - )} - `, the catalog's + * own key, so it holds whatever display title AniList returns. + * + * AniList allows 30 requests a minute per IP (`x-ratelimit-limit`), and twenty + * parallel page loads trip it, which the app shows as "Something went wrong". + * So the searches run one at a time, spaced out, and every AniList request + * other than the search itself (the home grid, covers) is answered with an + * empty page: only the search reaches AniList, one request per test. + */ +const SEARCH_OPERATIONS = /query\s+Search\b/; +const SPACING_MS = 3_000; + +// Probes AniList once and, if the rest of the suite has used much of this +// minute's allowance, waits for the window to reset before searching. +const waitForAniListHeadroom = async (): Promise => { + const res = await fetch("https://graphql.anilist.co", { + method: "POST", + headers: { "content-type": "application/json" }, + body: JSON.stringify({ query: "{ Media(id: 1) { id } }" }), + }); + const remaining = Number(res.headers.get("x-ratelimit-remaining") ?? 0); + const resetAt = Number(res.headers.get("x-ratelimit-reset") ?? 0) * 1000; + const retryAfter = Number(res.headers.get("retry-after") ?? 0) * 1000; + const wait = + res.status === 429 + ? retryAfter || 60_000 + : remaining < 25 + ? Math.max(resetAt - Date.now(), 0) || 60_000 + : 0; + await new Promise((resolve) => setTimeout(resolve, wait)); +}; + +const onlySearchReachesAniList = async (page: Page): Promise => { + await page.route("https://graphql.anilist.co/**", (route) => + SEARCH_OPERATIONS.test(route.request().postData() ?? "") + ? route.continue() + : route.fulfill({ json: { data: { Page: { media: [] } } } }), + ); +}; +const POPULAR: readonly { query: string; title: string; seriesId: number }[] = [ + { query: "attack", title: "Attack on Titan", seriesId: 53390 }, + { query: "one piece", title: "One Piece", seriesId: 30013 }, + { query: "naruto", title: "Naruto", seriesId: 30011 }, + { query: "demon slayer", title: "Demon Slayer", seriesId: 87216 }, + { query: "jujutsu", title: "Jujutsu Kaisen", seriesId: 101517 }, + { query: "my hero", title: "My Hero Academia", seriesId: 85486 }, + { query: "death note", title: "Death Note", seriesId: 30021 }, + { query: "fullmetal", title: "Fullmetal Alchemist", seriesId: 30025 }, + { query: "hunter x hunter", title: "Hunter x Hunter", seriesId: 30026 }, + { query: "chainsaw", title: "Chainsaw Man", seriesId: 105778 }, + { query: "spy x family", title: "SPY x FAMILY", seriesId: 108556 }, + { query: "bleach", title: "Bleach", seriesId: 30012 }, + { query: "dragon ball", title: "Dragon Ball", seriesId: 30042 }, + { query: "one punch", title: "One-Punch Man", seriesId: 74347 }, + { query: "tokyo ghoul", title: "Tokyo Ghoul", seriesId: 63327 }, + { query: "mob psycho", title: "Mob Psycho 100", seriesId: 85189 }, + { query: "black clover", title: "Black Clover", seriesId: 86123 }, + { query: "haikyu", title: "Haikyu!!", seriesId: 65243 }, + { query: "frieren", title: "Frieren", seriesId: 118586 }, + { query: "solo leveling", title: "Solo Leveling", seriesId: 105398 }, +]; + +test.describe("popular searches", () => { + test.describe.configure({ mode: "default", timeout: 90_000 }); + + test.beforeAll(async () => { + test.setTimeout(90_000); + await waitForAniListHeadroom(); + }); + + test.beforeEach(async ({ page }) => { + await page.waitForTimeout(SPACING_MS); + await onlySearchReachesAniList(page); + }); + + POPULAR.forEach(({ query, title, seriesId }) => { + test(`"${query}" finds ${title}`, async ({ page }) => { + await page.goto("/"); + const box = page.getByPlaceholder(/search/i); + await expect(box).toBeVisible(); + await box.fill(query); + await expect( + page.locator(`a[href="/series/${seriesId}"]`).first(), + ).toBeVisible(); + }); + }); +}); diff --git a/e2e/serve.ts b/e2e/serve.ts index 8824607..35074e7 100644 --- a/e2e/serve.ts +++ b/e2e/serve.ts @@ -1,10 +1,11 @@ /** * Static server for the Expo web export, used by Playwright. * - * Mirrors the two `netlify.toml` behaviours the app depends on: the SPA fallback - * to `index.html` (Expo Router web output is a single document with client - * routing) and the `/_mdx/*` proxy to the MangaDex API. Serving the real `dist/` - * means the e2e suite exercises the same bundle that ships. + * Mirrors the `netlify.toml` behaviours the app depends on: the SPA fallback to + * `index.html` (Expo Router web output is a single document with client + * routing) and the MangaDex proxies, shared with the Metro dev server through + * `scripts/mangadexProxy.ts` and `src/data/mangadexRoutes.ts`. Serving the + * real `dist/` means the e2e suite exercises the same bundle that ships. * * Uses node APIs rather than `Bun.serve` so it typechecks under the repo's * tsconfig without pulling in Bun's global types. @@ -14,10 +15,11 @@ import * as fs from "fs"; import * as http from "http"; import * as path from "path"; +import { MANGADEX_USER_AGENT, upstreamUrl } from "@/data/mangadexRoutes"; +import { proxyMangaDex } from "@scripts/mangadexProxy"; const PORT = Number(process.env.E2E_PORT ?? 4173); const DIST = path.resolve(__dirname, "..", "dist"); -const MANGADEX = "https://api.mangadex.org"; const MIME: Record = { ".html": "text/html; charset=utf-8", @@ -47,33 +49,23 @@ const resolveFile = (pathname: string): string | null => { : null; }; -const proxyMangaDex = async ( - url: string, - res: http.ServerResponse, -): Promise => { - const upstream = await fetch(`${MANGADEX}${url.slice("/_mdx".length)}`); - const body = await upstream.text(); - res.writeHead(upstream.status, { - "Content-Type": upstream.headers.get("content-type") ?? "application/json", - }); - res.end(body); -}; - const server = http.createServer((req, res) => { const url = req.url ?? "/"; - if (url.startsWith("/_mdx/")) { - proxyMangaDex(url, res).catch(() => { - res.writeHead(502).end("mangadex proxy failed"); + proxyMangaDex({ + req, + res, + upstreamUrl, + userAgent: MANGADEX_USER_AGENT, + }).then((handled) => { + if (handled) return; + const file = + resolveFile(url.split("?")[0]) ?? path.join(DIST, "index.html"); + res.writeHead(200, { + "Content-Type": MIME[path.extname(file)] ?? "application/octet-stream", }); - return; - } - - const file = resolveFile(url.split("?")[0]) ?? path.join(DIST, "index.html"); - res.writeHead(200, { - "Content-Type": MIME[path.extname(file)] ?? "application/octet-stream", + fs.createReadStream(file).pipe(res); }); - fs.createReadStream(file).pipe(res); }); server.listen(PORT, () => { diff --git a/e2e/smoke.spec.ts b/e2e/smoke.spec.ts index 3dd8d7a..b65af1a 100644 --- a/e2e/smoke.spec.ts +++ b/e2e/smoke.spec.ts @@ -26,6 +26,14 @@ test.describe("catalog", () => { await search(page, "One Piece"); await expect(page.getByText(/one piece/i).first()).toBeVisible(); }); + + // AniList ranks Attack on Titan past its first page for "attack", and + // "Mapped only" is on by default, so this once came back empty. + test("a partial title finds the mapped series", async ({ page }) => { + await page.goto("/"); + await search(page, "attack"); + await expect(page.getByText("Attack on Titan").first()).toBeVisible(); + }); }); test.describe("series detail", () => { @@ -58,6 +66,49 @@ test.describe("series detail", () => { }); }); +test.describe("movies", () => { + // Naruto: a mapped series with a long film list. + const NARUTO = "/series/30011"; + + test("stay collapsed until opened, with no seasons list above", async ({ + page, + }) => { + await page.goto(NARUTO); + const toggle = page.getByRole("button", { name: /^movies,/i }); + await expect(toggle).toBeVisible(); + await expect(toggle).toHaveAttribute("aria-expanded", "false"); + await expect(page.getByText(/after ep 713/i)).toHaveCount(0); + // The franchise's seasons were a text list under the header; it is gone. + await expect(page.getByText(/seasons & entries/i)).toHaveCount(0); + await expect( + page.getByRole("link", { name: /^the last: naruto the movie/i }), + ).toHaveCount(0); + + await toggle.click(); + await expect(toggle).toHaveAttribute("aria-expanded", "true"); + await expect(page.getByText(/after ep 713/i)).toBeVisible(); + }); +}); + +test.describe("mangadex proxy", () => { + // MangaDex refuses browser User-Agents, so a cover can only arrive through + // the same-origin proxy. Fullmetal Alchemist: a stable, fully mapped series. + test("volume covers load through /_mdx-covers", async ({ page }) => { + await page.goto("/series/5114"); + await expect(page.getByText("Volumes", { exact: true })).toBeVisible(); + const cover = page.locator('img[src^="/_mdx-covers/"]').first(); + await expect(cover).toBeVisible({ timeout: 30_000 }); + await expect + .poll(() => + cover.evaluate((img) => + img instanceof HTMLImageElement ? img.naturalWidth : 0, + ), + ) + .toBeGreaterThan(0); + await expect(page.getByText(/no volume art/i)).toHaveCount(0); + }); +}); + test.describe("accounts", () => { test("login route renders a sign-in form", async ({ page }) => { await page.goto("/login"); diff --git a/metro.config.js b/metro.config.js new file mode 100644 index 0000000..bf325e4 --- /dev/null +++ b/metro.config.js @@ -0,0 +1,34 @@ +// Metro config for `expo start` and `expo export`. The dev server also answers +// the MangaDex proxy paths that Netlify provides in production, so a localhost +// build loads volume covers like the deployed site does. +// +// Both handler and routes are TypeScript modules, which `require` can load +// since Node strips types (22.6 behind a flag, 24 by default): see +// `engines.node`. Neither has imports, so no tsconfig alias is involved. +const { getDefaultConfig } = require("expo/metro-config"); +const { proxyMangaDex } = require("./scripts/mangadexProxy.ts"); +const { + MANGADEX_USER_AGENT, + upstreamUrl, +} = require("./src/data/mangadexRoutes.ts"); + +const config = getDefaultConfig(__dirname); + +config.server = { + ...config.server, + enhanceMiddleware: (metroMiddleware) => async (req, res, next) => { + try { + const handled = await proxyMangaDex({ + req, + res, + upstreamUrl, + userAgent: MANGADEX_USER_AGENT, + }); + if (!handled) metroMiddleware(req, res, next); + } catch (error) { + next(error); + } + }, +}; + +module.exports = config; diff --git a/netlify.toml b/netlify.toml index 0c75f10..c6fec8d 100644 --- a/netlify.toml +++ b/netlify.toml @@ -2,8 +2,10 @@ command = "bun install && bun run build:web" publish = "dist" +# `metro.config.js` requires a TypeScript module, which Node strips types from +# since 22.6 and by default since 24. Keep in step with `engines.node`. [build.environment] - NODE_VERSION = "20" + NODE_VERSION = "24" # Long-cache the hashed Expo bundle output [[headers]] @@ -29,14 +31,22 @@ Referrer-Policy = "no-referrer" Permissions-Policy = "camera=(), microphone=(), geolocation=()" -# MangaDex API proxy — api.mangadex.org only returns Access-Control-Allow-Origin -# for localhost, so browser fetches from the deployed site are blocked. Proxying -# server-side makes the call same-origin to the browser. -[[redirects]] - from = "/_mdx/*" - to = "https://api.mangadex.org/:splat" - status = 200 - force = true +# MangaDex proxies. `api.mangadex.org` and the covers CDN both answer a browser +# User-Agent with a bot challenge, and the API only returns +# Access-Control-Allow-Origin for localhost, so the deployed site never calls +# them directly. A rewrite cannot help: Netlify forwards the visitor's +# User-Agent and ignores a `headers` override of it. The edge function makes +# the upstream request itself with a non-browser User-Agent and streams the +# reply back, same-origin to the browser. `metro.config.js` and `e2e/serve.ts` +# mirror it for local runs through the same `src/data/mangadexRoutes.ts` and +# `scripts/mangadexProxy.ts`. +[[edge_functions]] + path = "/_mdx/*" + function = "mangadex" + +[[edge_functions]] + path = "/_mdx-covers/*" + function = "mangadex" # SPA fallback — Expo Router web output is a single index.html with client routing. # Must be last so it doesn't shadow static assets above. @@ -44,3 +54,8 @@ from = "/*" to = "/index.html" status = 200 + +# Lets the edge function import `@/data/mangadexRoutes` by the same alias +# `tsconfig.json` gives Bun, Metro and tsc. +[functions] + deno_import_map = "netlify/import_map.json" diff --git a/netlify/edge-functions/mangadex.ts b/netlify/edge-functions/mangadex.ts new file mode 100644 index 0000000..923754d --- /dev/null +++ b/netlify/edge-functions/mangadex.ts @@ -0,0 +1,29 @@ +import { MANGADEX_USER_AGENT, upstreamUrl } from "@/data/mangadexRoutes"; + +/** + * The MangaDex proxy at Netlify's edge, mounted on `/_mdx/*` and + * `/_mdx-covers/*` by `netlify.toml`. MangaDex answers a browser User-Agent + * with a bot challenge, and a Netlify rewrite forwards that header unchanged, + * so this function makes the upstream request itself with a non-browser + * User-Agent and streams the reply back. `src/data/mangadexRoutes.ts` owns the + * routes and the User-Agent; `netlify/import_map.json` maps the alias for + * Deno. Edge functions must be the module's default export. + */ +export default async function mangadex( + request: Request, +): Promise { + const url = new URL(request.url); + const target = upstreamUrl(`${url.pathname}${url.search}`); + if (!target) return undefined; + const upstream = await fetch(target, { + headers: { "User-Agent": MANGADEX_USER_AGENT }, + }); + return new Response(upstream.body, { + status: upstream.status, + headers: { + "Content-Type": + upstream.headers.get("content-type") ?? "application/octet-stream", + "Cache-Control": upstream.headers.get("cache-control") ?? "no-store", + }, + }); +} diff --git a/netlify/import_map.json b/netlify/import_map.json new file mode 100644 index 0000000..809f8b9 --- /dev/null +++ b/netlify/import_map.json @@ -0,0 +1,5 @@ +{ + "imports": { + "@/data/mangadexRoutes": "../src/data/mangadexRoutes.ts" + } +} diff --git a/package.json b/package.json index 1278d24..c865d22 100644 --- a/package.json +++ b/package.json @@ -18,8 +18,9 @@ "lint:actions": "github-actionlint -color", "spellcheck": "typos", "spellcheck:fix": "typos --write-changes", - "test": "bun test src --reporter=dots --parallel", + "test": "bun test src scripts --reporter=dots --parallel", "e2e": "playwright test", + "mangadex:refresh": "bun --env-file=scripts/.env.local run scripts/refresh-mangadex.ts", "e2e:install": "playwright install chromium", "format": "oxfmt", "format:check": "oxfmt --check", @@ -74,7 +75,8 @@ "typescript": "7.0.2" }, "engines": { - "bun": ">=1.4.2" + "bun": ">=1.4.2", + "node": ">=24" }, "packageManager": "bun@1.4.2", "trustedDependencies": [ diff --git a/playwright.config.ts b/playwright.config.ts index bb7a39a..9c32b67 100644 --- a/playwright.config.ts +++ b/playwright.config.ts @@ -31,7 +31,21 @@ export default defineConfig({ trace: "on-first-retry", screenshot: "only-on-failure", }, - projects: [{ name: "chromium", use: { ...devices["Desktop Chrome"] } }], + projects: [ + { + name: "chromium", + use: { ...devices["Desktop Chrome"] }, + testIgnore: "**/popular-search.spec.ts", + }, + // Twenty live AniList searches need the per-minute rate limit to + // themselves, so they run once everything else has finished. + { + name: "popular-searches", + use: { ...devices["Desktop Chrome"] }, + testMatch: "**/popular-search.spec.ts", + dependencies: ["chromium"], + }, + ], webServer: { command: "bun run e2e/serve.ts", url: BASE_URL, diff --git a/scripts/mangadexProxy.test.ts b/scripts/mangadexProxy.test.ts new file mode 100644 index 0000000..065b0d5 --- /dev/null +++ b/scripts/mangadexProxy.test.ts @@ -0,0 +1,66 @@ +import { afterEach, describe, expect, it, spyOn } from "bun:test"; +import { IncomingMessage, ServerResponse } from "http"; +import { Socket } from "net"; +import { MANGADEX_USER_AGENT, upstreamUrl } from "@/data/mangadexRoutes"; +import { proxyMangaDex } from "@scripts/mangadexProxy"; + +describe("proxyMangaDex", () => { + // Real Node request and response objects, unattached to a socket, so the + // handler is exercised through the same API the servers give it. + const exchange = (url: string) => { + const req = new IncomingMessage(new Socket()); + req.url = url; + return { + req, + res: new ServerResponse(req), + upstreamUrl, + userAgent: MANGADEX_USER_AGENT, + }; + }; + + const fetchSpy = spyOn(globalThis, "fetch"); + + afterEach(() => { + fetchSpy.mockReset(); + }); + + it("forwards with the non-browser User-Agent and relays the reply", async () => { + fetchSpy.mockResolvedValue( + new Response("{}", { + status: 200, + headers: { "content-type": "application/json", "cache-control": "x" }, + }), + ); + const options = exchange("/_mdx/manga?title=Naruto"); + + await expect(proxyMangaDex(options)).resolves.toBe(true); + + expect(fetchSpy.mock.calls[0]?.[0]).toBe( + "https://api.mangadex.org/manga?title=Naruto", + ); + expect(fetchSpy.mock.calls[0]?.[1]?.headers).toEqual({ + "User-Agent": MANGADEX_USER_AGENT, + }); + expect(options.res.statusCode).toBe(200); + expect(options.res.getHeader("content-type")).toBe("application/json"); + expect(options.res.getHeader("cache-control")).toBe("x"); + }); + + it("answers 502 when MangaDex cannot be reached", async () => { + fetchSpy.mockRejectedValue(new Error("offline")); + const options = exchange("/_mdx-covers/m1/a.png"); + + await expect(proxyMangaDex(options)).resolves.toBe(true); + + expect(options.res.statusCode).toBe(502); + }); + + it("leaves a request outside the proxy paths untouched", async () => { + const options = exchange("/series/30011"); + + await expect(proxyMangaDex(options)).resolves.toBe(false); + + expect(fetchSpy).not.toHaveBeenCalled(); + expect(options.res.headersSent).toBe(false); + }); +}); diff --git a/scripts/mangadexProxy.ts b/scripts/mangadexProxy.ts new file mode 100644 index 0000000..9f066c7 --- /dev/null +++ b/scripts/mangadexProxy.ts @@ -0,0 +1,48 @@ +import type { IncomingMessage, ServerResponse } from "node:http"; + +/** + * The Node side of the MangaDex proxy, for the Metro dev server + * (`metro.config.js`) and the e2e static server (`e2e/serve.ts`). Netlify + * runs the same idea at the edge in `netlify/edge-functions/mangadex.ts`. + * + * The routes and User-Agent come in as arguments from `@/data/mangadexRoutes` + * rather than being imported, so this file has no imports Node's `require` + * would have to resolve through a tsconfig alias. + */ +export type MangaDexProxyOptions = { + req: IncomingMessage; + res: ServerResponse; + /** The MangaDex URL a request path maps to, or null when it is not proxied. */ + upstreamUrl: (path: string) => string | null; + /** The non-browser User-Agent MangaDex accepts. */ + userAgent: string; +}; + +/** + * Answers a proxied MangaDex request with the upstream status, body and + * content type. Resolves false, touching nothing, when `req` is not one. + */ +export async function proxyMangaDex({ + req, + res, + upstreamUrl, + userAgent, +}: MangaDexProxyOptions): Promise { + const target = upstreamUrl(req.url ?? "/"); + if (!target) return false; + try { + const upstream = await fetch(target, { + headers: { "User-Agent": userAgent }, + }); + const body = new Uint8Array(await upstream.arrayBuffer()); + res.writeHead(upstream.status, { + "Content-Type": + upstream.headers.get("content-type") ?? "application/octet-stream", + "Cache-Control": upstream.headers.get("cache-control") ?? "no-store", + }); + res.end(body); + } catch { + res.writeHead(502).end("mangadex proxy failed"); + } + return true; +} diff --git a/scripts/refresh-mangadex.ts b/scripts/refresh-mangadex.ts new file mode 100644 index 0000000..8123761 --- /dev/null +++ b/scripts/refresh-mangadex.ts @@ -0,0 +1,162 @@ +/** + * MangaDex cache refresh. + * + * Looks every catalog manga up on MangaDex the way the app does (title search, + * covers, aggregate) and writes the result to `mangadex_series`, so a series + * page reads one Supabase row instead of making three to five MangaDex calls + * through the proxy. The app still falls back to the live lookup for a manga + * with no row here. + * + * Writes need the service role, which never reaches the client. Set + * `SUPABASE_SERVICE_ROLE_KEY` in the environment or `scripts/.env.local`, + * which `bun run mangadex:refresh` loads; `SUPABASE_URL` overrides the + * production URL (for the local stack). + * + * Run: + * bun run mangadex:refresh # rows older than 7 days + * bun run mangadex:refresh -- --force # every row + * bun run mangadex:refresh -- --series naruto + * bun run mangadex:refresh -- --dry-run # look up, write nothing + */ +import { createClient } from "@supabase/supabase-js"; +import { getMediaByIds } from "@/api/anilist"; +import { getMangaDexSnapshot, scriptMangaDexClient } from "@/api/mangadex"; +import { SUPABASE_URL } from "@/api/supabaseConfig"; +import { englishTitle } from "@/data/format"; +import type { MangaDexSnapshot } from "@/data/mangadexSnapshot"; +import { DAY_MS } from "@/data/time"; +import type { Database } from "@/types/supabase"; + +const MANGADEX_PAUSE_MS = 1500; +const STALE_AFTER_MS = 7 * DAY_MS; + +type Target = { anilistMangaId: number; title: string }; +type Outcome = "written" | "unmatched" | "failed" | "skipped"; + +const sleep = (ms: number): Promise => + new Promise((resolve) => setTimeout(resolve, ms)); + +const main = async (): Promise => { + const argv = process.argv.slice(2); + const dryRun = argv.includes("--dry-run"); + const force = argv.includes("--force"); + const only = argv.includes("--series") + ? (argv[argv.indexOf("--series") + 1] ?? "").toLowerCase() + : null; + + const serviceKey = process.env.SUPABASE_SERVICE_ROLE_KEY; + if (!serviceKey) { + console.error( + "SUPABASE_SERVICE_ROLE_KEY is not set. Add it to scripts/.env.local.", + ); + process.exit(1); + } + const supabase = createClient( + process.env.SUPABASE_URL ?? SUPABASE_URL, + serviceKey, + { auth: { persistSession: false } }, + ); + + const [seriesRes, cachedRes] = await Promise.all([ + supabase.from("series").select("anilist_manga_id, title"), + supabase.from("mangadex_series").select("anilist_manga_id, fetched_at"), + ]); + if (seriesRes.error) throw new Error(seriesRes.error.message); + if (cachedRes.error) throw new Error(cachedRes.error.message); + + const freshUntil = Date.now() - STALE_AFTER_MS; + const fresh = new Set( + cachedRes.data + .filter((r) => new Date(r.fetched_at).getTime() > freshUntil) + .map((r) => r.anilist_manga_id), + ); + const wanted = [ + ...new Map( + seriesRes.data + .filter((s) => !only || s.title.toLowerCase().includes(only)) + .filter((s) => force || !fresh.has(s.anilist_manga_id)) + .map((s) => [s.anilist_manga_id, s.title]), + ), + ]; + console.log( + `${seriesRes.data.length} catalog series, ${wanted.length} to refresh${dryRun ? " (dry run)" : ""}`, + ); + if (wanted.length === 0) return; + + // The app searches MangaDex by AniList's English title, so the cache does + // the same rather than trusting the catalog's own title column. + const media = await getMediaByIds(wanted.map(([id]) => id)); + const titles = new Map(media.map((m) => [m.id, englishTitle(m.title)])); + const targets: Target[] = wanted.map(([anilistMangaId, catalogTitle]) => ({ + anilistMangaId, + title: titles.get(anilistMangaId) ?? catalogTitle, + })); + + const write = async ( + target: Target, + snapshot: MangaDexSnapshot, + ): Promise => { + const now = new Date().toISOString(); + const { error } = await supabase.from("mangadex_series").upsert( + { + anilist_manga_id: target.anilistMangaId, + mangadex_id: snapshot.mangadexId, + titles: snapshot.titles, + covers: snapshot.covers, + volumes: snapshot.volumes, + chapters: snapshot.chapters, + fetched_at: now, + updated_at: now, + }, + { onConflict: "anilist_manga_id" }, + ); + if (error) throw new Error(error.message); + }; + + const refresh = async (target: Target): Promise => { + try { + const snapshot = await getMangaDexSnapshot({ + client: scriptMangaDexClient, + anilistId: target.anilistMangaId, + title: target.title, + }); + if (!snapshot) { + console.log(` ? ${target.title}: no MangaDex match`); + return "unmatched"; + } + console.log( + ` ${dryRun ? "·" : "✓"} ${target.title}: ${snapshot.covers.length} covers, ${snapshot.volumes} vol, ${snapshot.chapters} ch`, + ); + if (dryRun) return "skipped"; + await write(target, snapshot); + return "written"; + } catch (error) { + console.log( + ` ✗ ${target.title}: ${error instanceof Error ? error.message : String(error)}`, + ); + return "failed"; + } + }; + + // One series at a time with a pause: MangaDex allows about five requests a + // second and each lookup is three or more. + const outcomes = await targets.reduce>( + async (accPromise, target, i) => { + const acc = await accPromise; + if (i > 0) await sleep(MANGADEX_PAUSE_MS); + return [...acc, await refresh(target)]; + }, + Promise.resolve([]), + ); + + const count = (o: Outcome): number => outcomes.filter((x) => x === o).length; + console.log( + `written ${count("written")}, unmatched ${count("unmatched")}, failed ${count("failed")}${dryRun ? `, looked up ${count("skipped")}` : ""}`, + ); + if (count("failed") > 0) process.exit(1); +}; + +main().catch((error: unknown) => { + console.error(error instanceof Error ? error.message : String(error)); + process.exit(1); +}); diff --git a/src/api/anilist.test.ts b/src/api/anilist.test.ts index ba166ed..d7d5733 100644 --- a/src/api/anilist.test.ts +++ b/src/api/anilist.test.ts @@ -1,157 +1,12 @@ import { describe, expect, it } from "bun:test"; -import { - getAnimeFranchise, - getLatestAnime, - hasAnimeSequels, - type FranchiseRawNode, -} from "./anilist"; +import { getLatestAnime, searchWithCatalog } from "./anilist"; // `graphql-request` is replaced with this mock by the preload in // `test/setup.ts`, so every request below is served from fixtures. import { graphqlRequestMock } from "@test/mocks/graphql"; import { makeEdge, makeMedia } from "@test/fixtures/media"; -// Typed against the real `FRANCHISE_NODE_QUERY` result so a change to the query -// shape breaks the fixture rather than letting it drift. -type FranchiseEdge = FranchiseRawNode["relations"]["edges"][number]; - -const franchiseNode = ({ - id, - format, - episodes, - year, - edges = [], -}: { - id: number; - format: string | null; - episodes: number | null; - year: number | null; - edges?: FranchiseEdge[]; -}): FranchiseRawNode => ({ - id, - title: { romaji: `Season ${id}`, english: null }, - format, - episodes, - startDate: { year }, - relations: { edges }, -}); - -const page = (media: unknown[]) => ({ Page: { media } }); - -describe("hasAnimeSequels", () => { - it("detects an anime sequel relation", () => { - const anime = makeMedia({ - id: 1, - type: "ANIME", - relations: [makeEdge({ relationType: "SEQUEL", id: 2, type: "ANIME" })], - }); - expect(hasAnimeSequels(anime)).toBe(true); - }); - - it("ignores sequel relations pointing at manga", () => { - const anime = makeMedia({ - id: 1, - type: "ANIME", - relations: [makeEdge({ relationType: "SEQUEL", id: 2, type: "MANGA" })], - }); - expect(hasAnimeSequels(anime)).toBe(false); - }); - - it("is false for manga even with anime sequel edges", () => { - const manga = makeMedia({ - id: 1, - type: "MANGA", - relations: [makeEdge({ relationType: "SEQUEL", id: 2, type: "ANIME" })], - }); - expect(hasAnimeSequels(manga)).toBe(false); - }); - - it("is false with no relations at all", () => { - expect(hasAnimeSequels(makeMedia({ id: 1, type: "ANIME" }))).toBe(false); - }); -}); - -describe("getAnimeFranchise", () => { - it("walks sequels and side stories, summing TV episodes only", async () => { - // Root (2013, TV 25) → SEQUEL season 2 (2015, TV 12) and SIDE_STORY - // OVA (2016, 1 ep). The sequel points back at the root, which must not - // trigger a third fetch, and manga edges must be ignored. - graphqlRequestMock - .mockResolvedValueOnce( - page([ - franchiseNode({ - id: 1, - format: "TV", - episodes: 25, - year: 2013, - edges: [ - { relationType: "SEQUEL", node: { id: 2, type: "ANIME" } }, - { relationType: "SIDE_STORY", node: { id: 3, type: "ANIME" } }, - { relationType: "ADAPTATION", node: { id: 9, type: "MANGA" } }, - ], - }), - ]), - ) - .mockResolvedValueOnce( - page([ - franchiseNode({ - id: 2, - format: "TV", - episodes: 12, - year: 2015, - edges: [ - { relationType: "PREQUEL", node: { id: 1, type: "ANIME" } }, - ], - }), - franchiseNode({ id: 3, format: "OVA", episodes: 1, year: 2016 }), - ]), - ); - - const franchise = await getAnimeFranchise(1); - - expect(graphqlRequestMock).toHaveBeenCalledTimes(2); - expect(graphqlRequestMock.mock.calls[1][1]).toEqual({ ids: [2, 3] }); - expect(franchise).toEqual({ - rootId: 1, - seasons: [ - { - id: 1, - title: "Season 1", - romajiTitle: "Season 1", - format: "TV", - episodes: 25, - year: 2013, - }, - { - id: 2, - title: "Season 2", - romajiTitle: "Season 2", - format: "TV", - episodes: 12, - year: 2015, - }, - { - id: 3, - title: "Season 3", - romajiTitle: "Season 3", - format: "OVA", - episodes: 1, - year: 2016, - }, - ], - totalTvEpisodes: 37, - tvSeasonCount: 2, - }); - }); - - it("sorts seasons by year with unknown years last", async () => { - graphqlRequestMock.mockResolvedValueOnce( - page([franchiseNode({ id: 1, format: "TV", episodes: 12, year: null })]), - ); - - const franchise = await getAnimeFranchise(1); - expect(franchise.seasons.map((s) => s.id)).toEqual([1]); - expect(franchise.totalTvEpisodes).toBe(12); - }); +const page = (media: unknown[], hasNextPage = false) => ({ + Page: { pageInfo: { hasNextPage }, media }, }); describe("getLatestAnime franchise-root filtering", () => { @@ -218,7 +73,67 @@ describe("getLatestAnime franchise-root filtering", () => { ]), ); - const latest = await getLatestAnime({ genreNotIn: null, tagNotIn: null }); - expect(latest.map((m) => m.id)).toEqual([1, 4, 5]); + const latest = await getLatestAnime({ + filters: { genreNotIn: null, tagNotIn: null }, + page: 1, + }); + expect(latest.media.map((m) => m.id)).toEqual([1, 4, 5]); + }); + + it("requests the given page and reports whether another follows", async () => { + graphqlRequestMock.mockResolvedValueOnce(page([], true)); + + const latest = await getLatestAnime({ + filters: { genreNotIn: ["Hentai"], tagNotIn: null }, + page: 3, + }); + expect(latest.hasNextPage).toBe(true); + expect(graphqlRequestMock.mock.calls.at(-1)?.[1]).toEqual({ + page: 3, + genreNotIn: ["Hentai"], + tagNotIn: null, + }); + }); +}); + +describe("searchWithCatalog", () => { + const filters = { genreNotIn: ["Hentai"], tagNotIn: ["Gore"] }; + + it("skips the catalog page when there are no catalog ids", async () => { + const hit = makeMedia({ id: 55391, type: "MANGA" }); + graphqlRequestMock.mockImplementation(() => + Promise.resolve({ search: { media: [hit] } }), + ); + expect( + await searchWithCatalog({ query: "attack", ids: [], filters }), + ).toEqual({ search: [hit], catalog: [] }); + expect(graphqlRequestMock.mock.calls.at(-1)?.[1]).toEqual({ + query: "attack", + ids: [], + hasCatalog: false, + ...filters, + }); + }); + + it("fetches search and catalog ids in one request", async () => { + const hit = makeMedia({ id: 55391, type: "MANGA" }); + const aot = makeMedia({ id: 16498, type: "ANIME" }); + graphqlRequestMock.mockImplementation(() => + Promise.resolve({ search: { media: [hit] }, catalog: { media: [aot] } }), + ); + expect( + await searchWithCatalog({ + query: "attack", + ids: [16498, 53390], + filters, + }), + ).toEqual({ search: [hit], catalog: [aot] }); + expect(graphqlRequestMock).toHaveBeenCalledTimes(1); + expect(graphqlRequestMock.mock.calls.at(-1)?.[1]).toEqual({ + query: "attack", + ids: [16498, 53390], + hasCatalog: true, + ...filters, + }); }); }); diff --git a/src/api/anilist.ts b/src/api/anilist.ts index 93933d4..7a3a878 100644 --- a/src/api/anilist.ts +++ b/src/api/anilist.ts @@ -1,14 +1,6 @@ import { GraphQLClient, gql } from "graphql-request"; -import { englishTitle } from "@/data/format"; import type { SplitFilters } from "@/data/genreFilters"; -import type { - AniListMedia, - AniListMediaDetail, - AnimeFranchise, - FranchiseSeason, - MediaCover, - MediaType, -} from "@/types"; +import type { AniListMedia, AniListMediaDetail, MediaCover } from "@/types"; const client = new GraphQLClient("https://graphql.anilist.co"); @@ -70,25 +62,12 @@ function isFranchiseRoot(media: AniListMedia): boolean { ); } -const SEARCH_QUERY = gql` - query Search($query: String!, $genreNotIn: [String], $tagNotIn: [String]) { - Page(perPage: ${SEARCH_PAGE_SIZE}) { - media( - search: $query - sort: SEARCH_MATCH - isAdult: false - genre_not_in: $genreNotIn - tag_not_in: $tagNotIn - ) { - ${MEDIA_FIELDS} - } - } - } -`; - const LATEST_ANIME_QUERY = gql` - query LatestAnime($genreNotIn: [String], $tagNotIn: [String]) { - Page(perPage: ${PAGE_SIZE}) { + query LatestAnime($page: Int!, $genreNotIn: [String], $tagNotIn: [String]) { + Page(page: $page, perPage: ${PAGE_SIZE}) { + pageInfo { + hasNextPage + } media( type: ANIME format: TV @@ -114,6 +93,42 @@ const MEDIA_BY_IDS_QUERY = gql` } `; +// The search page and the catalog's title matches in one request, so a search +// costs one call against AniList's per-minute rate limit rather than two. The +// catalog page is skipped when there are no ids: an empty `id_in` would not +// filter anything. +const SEARCH_QUERY = gql` + query Search( + $query: String! + $ids: [Int]! + $hasCatalog: Boolean! + $genreNotIn: [String] + $tagNotIn: [String] + ) { + search: Page(perPage: ${SEARCH_PAGE_SIZE}) { + media( + search: $query + sort: SEARCH_MATCH + isAdult: false + genre_not_in: $genreNotIn + tag_not_in: $tagNotIn + ) { + ${MEDIA_FIELDS} + } + } + catalog: Page(perPage: ${PAGE_SIZE}) @include(if: $hasCatalog) { + media( + id_in: $ids + isAdult: false + genre_not_in: $genreNotIn + tag_not_in: $tagNotIn + ) { + ${MEDIA_FIELDS} + } + } + } +`; + const DETAIL_QUERY = gql` query Detail($id: Int!) { Media(id: $id) { @@ -123,30 +138,52 @@ const DETAIL_QUERY = gql` } `; -/** AniList search, with the hidden genres and tags excluded server-side. */ -export async function searchMedia({ +export type SearchWithCatalog = { + search: AniListMedia[]; + catalog: AniListMedia[]; +}; + +/** + * AniList search plus the given catalog media ids, both under the search's + * genre and tag exclusions, in a single request. + */ +export async function searchWithCatalog({ query, + ids, filters, }: { query: string; + ids: readonly number[]; filters: SplitFilters; -}): Promise { - if (!query.trim()) return []; - const data = await client.request<{ Page: { media: AniListMedia[] } }>( - SEARCH_QUERY, - { query, ...filters }, - ); - return data.Page.media; +}): Promise { + const data = await client.request<{ + search: { media: AniListMedia[] }; + catalog?: { media: AniListMedia[] }; + }>(SEARCH_QUERY, { query, ids, hasCatalog: ids.length > 0, ...filters }); + return { search: data.search.media, catalog: data.catalog?.media ?? [] }; } -export async function getLatestAnime( - filters: SplitFilters, -): Promise { - const data = await client.request<{ Page: { media: AniListMedia[] } }>( - LATEST_ANIME_QUERY, - { ...filters }, - ); - return data.Page.media.filter(isFranchiseRoot); +/** One page of the latest-releases feed. */ +export type LatestAnimePage = { media: AniListMedia[]; hasNextPage: boolean }; + +/** + * Page `page` (1-based) of the newest TV anime, one entry per franchise. + * Later seasons are dropped, so a page can hold fewer than `PAGE_SIZE`. + */ +export async function getLatestAnime({ + filters, + page, +}: { + filters: SplitFilters; + page: number; +}): Promise { + const data = await client.request<{ + Page: { pageInfo: { hasNextPage: boolean }; media: AniListMedia[] }; + }>(LATEST_ANIME_QUERY, { page, ...filters }); + return { + media: data.Page.media.filter(isFranchiseRoot), + hasNextPage: data.Page.pageInfo.hasNextPage, + }; } export async function getMedia(id: number): Promise { @@ -157,13 +194,36 @@ export async function getMedia(id: number): Promise { return data.Media; } -export async function getMediaByIds(ids: number[]): Promise { - if (ids.length === 0) return []; - const data = await client.request<{ Page: { media: AniListMedia[] } }>( - MEDIA_BY_IDS_QUERY, - { ids }, - ); - return data.Page.media; +/** + * `ids`, de-duplicated and cut into AniList pages, each fetched by `request` + * one after another: firing a dozen pages at once trips AniList's burst limit, + * and a rate-limited response comes back without CORS headers, so on web it + * fails outright rather than retrying. + */ +const inPages = ( + ids: readonly number[], + request: (page: number[]) => Promise, +): Promise => { + const unique = [...new Set(ids)]; + return Array.from({ length: Math.ceil(unique.length / PAGE_SIZE) }, (_, i) => + unique.slice(i * PAGE_SIZE, (i + 1) * PAGE_SIZE), + ).reduce>(async (acc, page) => { + const done = await acc; + return [...done, ...(await request(page))]; + }, Promise.resolve([])); +}; + +/** Full media records for any number of ids, batched at AniList's page limit. */ +export async function getMediaByIds( + ids: readonly number[], +): Promise { + return inPages(ids, async (page) => { + const data = await client.request<{ Page: { media: AniListMedia[] } }>( + MEDIA_BY_IDS_QUERY, + { ids: page }, + ); + return data.Page.media; + }); } const COVERS_BY_IDS_QUERY = gql` @@ -181,135 +241,17 @@ const COVERS_BY_IDS_QUERY = gql` `; /** - * Cover art for an arbitrary number of media ids, batched at AniList's page - * limit. The batches run one after another: firing all dozen of the catalog's - * pages at once trips AniList's burst limit, and a rate-limited response comes - * back without CORS headers, so on web it fails outright rather than retrying. - * The result is cached for a week, so this runs about once per device. + * Cover art for any number of media ids, batched at AniList's page limit. The + * result is cached for a week, so this runs about once per device. */ export async function getCoversByIds( ids: readonly number[], ): Promise { - const unique = [...new Set(ids)]; - return Array.from({ length: Math.ceil(unique.length / PAGE_SIZE) }, (_, i) => - unique.slice(i * PAGE_SIZE, (i + 1) * PAGE_SIZE), - ).reduce>(async (acc, batch) => { - const covers = await acc; - const page = await client.request<{ Page: { media: MediaCover[] } }>( + return inPages(ids, async (page) => { + const data = await client.request<{ Page: { media: MediaCover[] } }>( COVERS_BY_IDS_QUERY, - { ids: batch }, + { ids: page }, ); - return [...covers, ...page.Page.media]; - }, Promise.resolve([])); -} - -const FRANCHISE_NODE_QUERY = gql` - query FranchiseNode($ids: [Int]) { - Page(perPage: ${PAGE_SIZE}) { - media(id_in: $ids, type: ANIME) { - id - title { - romaji - english - } - format - episodes - startDate { - year - } - relations { - edges { - relationType(version: 2) - node { - id - type - } - } - } - } - } - } -`; - -export type FranchiseRawNode = { - id: number; - title: { romaji: string; english: string | null }; - format: string | null; - episodes: number | null; - startDate: { year: number | null }; - relations: { - edges: { relationType: string; node: { id: number; type: MediaType } }[]; - }; -}; - -const FRANCHISE_RELATIONS = new Set([ - "SEQUEL", - "PREQUEL", - "PARENT", - "SIDE_STORY", -]); - -async function collectFranchiseNodes( - frontier: number[], - visited: Map, -): Promise { - const ids = frontier.filter((id) => !visited.has(id)); - if (ids.length === 0) return Array.from(visited.values()); - - const data = await client.request<{ Page: { media: FranchiseRawNode[] } }>( - FRANCHISE_NODE_QUERY, - { ids }, - ); - const nextVisited = data.Page.media.reduce( - (acc, node) => acc.set(node.id, node), - new Map(visited), - ); - const next = data.Page.media.flatMap((node) => - node.relations.edges - .filter( - (edge) => - FRANCHISE_RELATIONS.has(edge.relationType) && - edge.node.type === "ANIME" && - !nextVisited.has(edge.node.id), - ) - .map((edge) => edge.node.id), - ); - return collectFranchiseNodes([...new Set(next)], nextVisited); -} - -export async function getAnimeFranchise( - rootId: number, -): Promise { - const nodes = await collectFranchiseNodes([rootId], new Map()); - - const seasons: FranchiseSeason[] = nodes - .map((n) => ({ - id: n.id, - title: englishTitle(n.title), - romajiTitle: n.title.romaji, - format: n.format, - episodes: n.episodes, - year: n.startDate.year, - })) - .sort((a, b) => (a.year ?? 9999) - (b.year ?? 9999)); - - const tvSeasons = seasons.filter((s) => s.format === "TV"); - const totalTvEpisodes = tvSeasons.reduce( - (sum, s) => sum + (s.episodes ?? 0), - 0, - ); - - return { - rootId, - seasons, - totalTvEpisodes, - tvSeasonCount: tvSeasons.length, - }; -} - -export function hasAnimeSequels(media: AniListMedia): boolean { - if (media.type !== "ANIME") return false; - return media.relations.edges.some( - (e) => e.relationType === "SEQUEL" && e.node.type === "ANIME", - ); + return data.Page.media; + }); } diff --git a/src/api/mangadex.test.ts b/src/api/mangadex.test.ts index 04cbd58..c1a447d 100644 --- a/src/api/mangadex.test.ts +++ b/src/api/mangadex.test.ts @@ -1,9 +1,14 @@ import { describe, expect, it } from "bun:test"; +import { MANGADEX_USER_AGENT } from "@/data/mangadexRoutes"; import { + appMangaDexClient, countAggregate, hasVolume, isCoverRecord, isMangaRecord, + nativeMangaDexClient, + scriptMangaDexClient, + webMangaDexClient, pickBestMatch, preferredTitle, } from "./mangadex"; @@ -200,3 +205,25 @@ describe("countAggregate", () => { expect(countAggregate(null)).toEqual({ volumeCount: 0, chapterCount: 0 }); }); }); + +describe("MangaDex clients", () => { + it("send a web build through the same-origin proxies with no User-Agent", () => { + expect(webMangaDexClient).toEqual({ + api: "/_mdx", + covers: "/_mdx-covers", + headers: {}, + }); + }); + + it("let a script call MangaDex directly with the non-browser User-Agent", () => { + expect(scriptMangaDexClient).toEqual({ + api: "https://api.mangadex.org", + covers: "https://uploads.mangadex.org/covers", + headers: { "User-Agent": MANGADEX_USER_AGENT }, + }); + }); + + it("read directly under bun, where there is no window", () => { + expect(appMangaDexClient).toBe(nativeMangaDexClient); + }); +}); diff --git a/src/api/mangadex.ts b/src/api/mangadex.ts index b22b855..5ada49b 100644 --- a/src/api/mangadex.ts +++ b/src/api/mangadex.ts @@ -1,21 +1,45 @@ -import type { MangaDexInfo, MangaDexVolumeCover, MangaDexTitle } from "@/types"; - -// api.mangadex.org only returns Access-Control-Allow-Origin for localhost, so -// on a deployed web origin we hit the Netlify proxy at /_mdx instead. Native -// builds and local dev call MangaDex directly. -function resolveBase(): string { - if (typeof window === "undefined" || !window.location) { - return "https://api.mangadex.org"; - } - const host = window.location.hostname; - if (host === "localhost" || host === "127.0.0.1") { - return "https://api.mangadex.org"; - } - return "/_mdx"; -} +import { isRecord } from "@/data/guards"; +import { MANGADEX_ROUTES, MANGADEX_USER_AGENT } from "@/data/mangadexRoutes"; +import type { MangaDexSnapshot } from "@/data/mangadexSnapshot"; +import type { MangaDexTitle } from "@/types"; + +/** Where requests go and what they carry. */ +export type MangaDexClient = { + api: string; + covers: string; + headers: Record; +}; -const BASE = resolveBase(); -const UPLOADS = "https://uploads.mangadex.org"; +/** + * The web build's client. `api.mangadex.org` and the covers CDN both answer a + * browser User-Agent with a bot challenge, and the API only allows + * cross-origin reads from localhost, so a browser reaches MangaDex through the + * same-origin proxy paths. It cannot set `User-Agent`, so it sends none. + */ +export const webMangaDexClient: MangaDexClient = { + api: MANGADEX_ROUTES.api.proxy, + covers: MANGADEX_ROUTES.covers.proxy, + headers: {}, +}; + +/** Native apps are not challenged and call MangaDex directly. */ +export const nativeMangaDexClient: MangaDexClient = { + api: MANGADEX_ROUTES.api.upstream, + covers: MANGADEX_ROUTES.covers.upstream, + headers: {}, +}; + +/** A script calls MangaDex directly with the non-browser User-Agent it accepts. */ +export const scriptMangaDexClient: MangaDexClient = { + ...nativeMangaDexClient, + headers: { "User-Agent": MANGADEX_USER_AGENT }, +}; + +/** The client the app itself reads MangaDex through. */ +export const appMangaDexClient = + typeof window !== "undefined" && !!window.location + ? webMangaDexClient + : nativeMangaDexClient; type MangaDexRecord = { id: string; @@ -38,9 +62,6 @@ type CoverRecord = { // MangaDex responses arrive as `unknown` and are narrowed here, so a changed // or partial payload is dropped rather than trusted. -const isRecord = (value: unknown): value is Record => - typeof value === "object" && value !== null && !Array.isArray(value); - const isStringRecord = (value: unknown): value is Record => isRecord(value) && Object.values(value).every((v) => typeof v === "string"); @@ -77,8 +98,14 @@ export function hasVolume( return !!cover.attributes.volume; } -async function fetchJson(url: string): Promise { - const res = await fetch(url); +async function fetchJson({ + client, + url, +}: { + client: MangaDexClient; + url: string; +}): Promise { + const res = await fetch(url, { headers: client.headers }); if (!res.ok) throw new Error(`MangaDex ${res.status} for ${url}`); const body: unknown = await res.json(); return body; @@ -120,20 +147,17 @@ function buildTitles(record: MangaDexRecord): MangaDexTitle[] { return [...new Map(all.map((t) => [`${t.locale}::${t.value}`, t])).values()]; } -function coverUrl( - mangaId: string, - fileName: string, - size: "256" | "512" | "full", -): string { - if (size === "full") return `${UPLOADS}/covers/${mangaId}/${fileName}`; - return `${UPLOADS}/covers/${mangaId}/${fileName}.${size}.jpg`; -} - const SAFE_RATINGS = "contentRating%5B%5D=safe&contentRating%5B%5D=suggestive"; -async function searchByTitle(title: string): Promise { - const url = `${BASE}/manga?title=${encodeURIComponent(title)}&limit=10&${SAFE_RATINGS}`; - return listOf(await fetchJson(url), isMangaRecord, url); +async function searchByTitle({ + client, + title, +}: { + client: MangaDexClient; + title: string; +}): Promise { + const url = `${client.api}/manga?title=${encodeURIComponent(title)}&limit=10&${SAFE_RATINGS}`; + return listOf(await fetchJson({ client, url }), isMangaRecord, url); } // Re-prints and color editions on MangaDex often own the AniList link even when @@ -183,13 +207,19 @@ export function pickBestMatch( const COVER_PAGE_SIZE = 100; const COVER_MAX_PAGES = 5; -async function fetchCoverPage( - mangaId: string, - offset: number, - acc: CoverRecord[], -): Promise { - const url = `${BASE}/cover?manga%5B%5D=${mangaId}&limit=${COVER_PAGE_SIZE}&offset=${offset}&order%5Bvolume%5D=asc`; - const body = await fetchJson(url); +async function fetchCovers({ + client, + mangaId, + offset = 0, + acc = [], +}: { + client: MangaDexClient; + mangaId: string; + offset?: number; + acc?: CoverRecord[]; +}): Promise { + const url = `${client.api}/cover?manga%5B%5D=${mangaId}&limit=${COVER_PAGE_SIZE}&offset=${offset}&order%5Bvolume%5D=asc`; + const body = await fetchJson({ client, url }); const page = listOf(body, isCoverRecord, url); const total = isRecord(body) && typeof body.total === "number" ? body.total : 0; @@ -199,7 +229,9 @@ async function fetchCoverPage( page.length < COVER_PAGE_SIZE || newOffset >= total || newOffset >= COVER_PAGE_SIZE * COVER_MAX_PAGES; - return done ? next : fetchCoverPage(mangaId, newOffset, next); + return done + ? next + : fetchCovers({ client, mangaId, offset: newOffset, acc: next }); } // An empty aggregate comes back as `[]` rather than `{}`, so anything that is @@ -222,40 +254,53 @@ export function countAggregate(body: unknown): { }; } -async function fetchAggregate( - mangaId: string, -): Promise<{ volumeCount: number; chapterCount: number }> { - return countAggregate(await fetchJson(`${BASE}/manga/${mangaId}/aggregate`)); +async function fetchAggregate({ + client, + mangaId, +}: { + client: MangaDexClient; + mangaId: string; +}): Promise<{ volumeCount: number; chapterCount: number }> { + return countAggregate( + await fetchJson({ + client, + url: `${client.api}/manga/${mangaId}/aggregate`, + }), + ); } -export async function getMangaDexInfoByAniListId( - anilistId: number, - searchTitle: string, -): Promise { - const candidates = await searchByTitle(searchTitle); - const match = pickBestMatch(candidates, anilistId, searchTitle); +/** + * The MangaDex entry for an AniList manga, found by title and confirmed by + * AniList link or exact title: its id, titles, hosted counts and the file name + * of every volume cover. Null when nothing on MangaDex matches. + */ +export async function getMangaDexSnapshot({ + client, + anilistId, + title, +}: { + client: MangaDexClient; + anilistId: number; + title: string; +}): Promise { + const candidates = await searchByTitle({ client, title }); + const match = pickBestMatch(candidates, anilistId, title); if (!match) return null; const [covers, aggregate] = await Promise.all([ - fetchCoverPage(match.id, 0, []), - fetchAggregate(match.id), + fetchCovers({ client, mangaId: match.id }), + fetchAggregate({ client, mangaId: match.id }), ]); - const coverList: MangaDexVolumeCover[] = covers - .filter(hasVolume) - .map((c) => ({ - volume: c.attributes.volume, - locale: c.attributes.locale ?? "ja", - url: coverUrl(match.id, c.attributes.fileName, "512"), - thumbUrl: coverUrl(match.id, c.attributes.fileName, "256"), - })); - - const titles = buildTitles(match); - return { - titles, + mangadexId: match.id, + titles: buildTitles(match), volumes: aggregate.volumeCount, chapters: aggregate.chapterCount, - covers: coverList, + covers: covers.filter(hasVolume).map((c) => ({ + volume: c.attributes.volume, + locale: c.attributes.locale ?? "ja", + fileName: c.attributes.fileName, + })), }; } diff --git a/src/api/mangadexCache.test.ts b/src/api/mangadexCache.test.ts new file mode 100644 index 0000000..cab39ec --- /dev/null +++ b/src/api/mangadexCache.test.ts @@ -0,0 +1,45 @@ +// `@/api/supabase` is replaced with the mocks from `@test/mocks/supabase` by the +// bun test preload in `test/setup.ts`. +import { describe, expect, it } from "bun:test"; +import { fetchCachedMangaDex } from "./mangadexCache"; +import { fromMock, singleRowOf } from "@test/mocks/supabase"; +import type { MangaDexSeriesRow } from "@/data/mangadexSnapshot"; + +const row: MangaDexSeriesRow = { + id: 7, + anilist_manga_id: 30011, + mangadex_id: "m1", + titles: [{ locale: "en", value: "Naruto" }], + covers: [{ volume: "1", locale: "ja", fileName: "a.png" }], + volumes: 72, + chapters: 700, + fetched_at: "2026-11-08T00:00:00Z", + created_at: "2026-11-08T00:00:00Z", + updated_at: "2026-11-08T00:00:00Z", +}; + +describe("fetchCachedMangaDex", () => { + it("reads the cached row for the manga and lifts it into a snapshot", async () => { + fromMock.mockImplementationOnce(() => singleRowOf(row)); + expect(await fetchCachedMangaDex(30011)).toEqual({ + mangadexId: "m1", + titles: [{ locale: "en", value: "Naruto" }], + volumes: 72, + chapters: 700, + covers: [{ volume: "1", locale: "ja", fileName: "a.png" }], + }); + expect(fromMock).toHaveBeenCalledWith("mangadex_series"); + }); + + it("resolves null for a manga the cache has no row for", async () => { + fromMock.mockImplementationOnce(() => singleRowOf(null)); + expect(await fetchCachedMangaDex(1)).toBeNull(); + }); + + it("surfaces a query error", async () => { + fromMock.mockImplementationOnce(() => + singleRowOf(null, { message: "down" }), + ); + expect(fetchCachedMangaDex(1)).rejects.toEqual({ message: "down" }); + }); +}); diff --git a/src/api/mangadexCache.ts b/src/api/mangadexCache.ts new file mode 100644 index 0000000..21ab8d7 --- /dev/null +++ b/src/api/mangadexCache.ts @@ -0,0 +1,19 @@ +import { supabase } from "@/api/supabase"; +import { rowToSnapshot, type MangaDexSnapshot } from "@/data/mangadexSnapshot"; + +/** + * The cached MangaDex lookup for an AniList manga, or null when the cache has + * no row for it. `scripts/refresh-mangadex.ts` fills the table for every + * catalog series; the caller falls back to the live lookup on null. + */ +export async function fetchCachedMangaDex( + anilistMangaId: number, +): Promise { + const { data, error } = await supabase + .from("mangadex_series") + .select("*") + .eq("anilist_manga_id", anilistMangaId) + .maybeSingle(); + if (error) throw error; + return data ? rowToSnapshot(data) : null; +} diff --git a/src/components/Footer.tsx b/src/components/Footer.tsx index 528c17d..e25f704 100644 --- a/src/components/Footer.tsx +++ b/src/components/Footer.tsx @@ -5,9 +5,13 @@ import { COLOR, pressFeedback, FOOTER_OFFSET, SPACE, TEXT } from "@/theme"; const AUTHOR_URL = "https://github.com/codebend3r"; const SOURCE_URL = "https://github.com/codebend3r/kasane"; -export function Footer() { +/** + * The credits bar. At the end of a page it sits well clear of the content; + * `pinned` tightens it for a screen that holds it fixed under a scroll area. + */ +export function Footer({ pinned = false }: { pinned?: boolean }) { return ( - + Built by Linking.openURL(AUTHOR_URL)} @@ -44,6 +48,7 @@ const styles = StyleSheet.create({ borderTopWidth: 1, borderTopColor: COLOR.surface, }, + barPinned: { paddingTop: SPACE.lg, paddingBottom: SPACE.xs }, copy: { ...TEXT.buttonLabel, color: COLOR.textMuted }, link: { ...TEXT.buttonLabel, color: COLOR.textPrimary }, spacer: { flex: 1 }, diff --git a/src/components/FranchiseSeasons.tsx b/src/components/FranchiseSeasons.tsx deleted file mode 100644 index 0528541..0000000 --- a/src/components/FranchiseSeasons.tsx +++ /dev/null @@ -1,106 +0,0 @@ -import { Pressable, StyleSheet, Text, View } from "react-native"; -import { Link } from "expo-router"; -import type { AnimeFranchise } from "@/types"; -import { COLOR, FONT, pressFeedback, SPACE, TEXT } from "@/theme"; - -/** - * Every season and side story in an anime franchise, with the TV total across - * them. Each card opens that entry's own series screen. - */ -export function FranchiseSeasons({ - franchise, - currentId, -}: { - franchise: AnimeFranchise; - currentId: number; -}) { - return ( - - Seasons & entries - {franchise.tvSeasonCount > 1 && ( - - Franchise total: {franchise.totalTvEpisodes} TV eps across{" "} - {franchise.tvSeasonCount} seasons - - )} - - {franchise.seasons.map((s) => { - const isCurrent = s.id === currentId; - return ( - - [ - styles.seasonCard, - isCurrent && styles.seasonCardActive, - pressFeedback(state), - ]} - > - - {s.title} - - - {s.format ?? "—"} - {s.episodes ? ` · ${s.episodes} eps` : ""} - {s.year ? ` · ${s.year}` : ""} - - {isCurrent && ( - VIEWING - )} - - - ); - })} - - - ); -} - -const styles = StyleSheet.create({ - seasons: { gap: SPACE.mdl }, - sectionTitle: { ...TEXT.sectionTitle, color: COLOR.textPrimary }, - franchiseTotal: { - color: COLOR.accent, - fontSize: 13, - letterSpacing: -0.2, - fontFamily: FONT.semibold, - }, - seasonGrid: { flexDirection: "row", flexWrap: "wrap", gap: SPACE.mdl }, - seasonCard: { - width: 220, - padding: SPACE.lg, - backgroundColor: COLOR.surface, - borderLeftWidth: 3, - borderLeftColor: COLOR.accent, - gap: SPACE.sm, - }, - seasonCardActive: { - backgroundColor: COLOR.surfaceNotice, - borderLeftColor: COLOR.notice, - }, - seasonCardTitle: { - color: COLOR.textPrimary, - fontSize: 14, - lineHeight: 18, - fontFamily: FONT.semibold, - letterSpacing: -0.2, - }, - seasonCardMeta: { - color: COLOR.textMuted, - fontSize: 11, - letterSpacing: 0.8, - textTransform: "uppercase", - fontFamily: FONT.semibold, - }, - seasonCardCurrent: { - color: COLOR.notice, - fontSize: 10, - letterSpacing: 1.4, - fontFamily: FONT.bold, - }, -}); diff --git a/src/components/GenreFilters.tsx b/src/components/GenreFilters.tsx index 1637d75..0db72e2 100644 --- a/src/components/GenreFilters.tsx +++ b/src/components/GenreFilters.tsx @@ -6,45 +6,65 @@ import { Text, View, } from "react-native"; -import { useState } from "react"; import type { GenreFilter } from "@/data/genreFilters"; import { useGenreFilters } from "@/queries/catalog"; import { usePreferences } from "@/state/preferences"; import { useIsNarrow } from "@/components/useIsNarrow"; import { COLOR, FONT, pressFeedback, SPACE, TEXT } from "@/theme"; +/** + * The "Filter genres" button. The chips it opens live in `GenreFilterPanel`, + * so a toolbar can place the button in its row and the panel beneath it. + */ +export function GenreFilterButton({ + open, + onToggle, +}: { + open: boolean; + onToggle: () => void; +}) { + const hiddenCount = usePreferences((s) => s.hiddenGenres.length); + const isMobile = useIsNarrow(); + + return ( + [styles.filterToggle, pressFeedback(state)]} + > + + {hiddenCount > 0 + ? `Filter genres · ${hiddenCount} hidden` + : "Filter genres"} + + + {open && !isMobile ? "▴" : "▾"} + + + ); +} + /** * The genre chips: an inline row on wider viewports, a bottom sheet on a * phone. Reads and writes the hidden set straight from preferences. */ -export function GenreFilters() { +export function GenreFilterPanel({ + open, + onClose, +}: { + open: boolean; + onClose: () => void; +}) { const filters = useGenreFilters(); const hiddenGenres = usePreferences((s) => s.hiddenGenres); const onToggle = usePreferences((s) => s.toggleHiddenGenre); const onSetHidden = usePreferences((s) => s.setHiddenGenres); const isMobile = useIsNarrow(); - const [open, setOpen] = useState(false); - const hiddenCount = hiddenGenres.length; return ( <> - setOpen(!open)} - accessibilityRole="button" - accessibilityLabel="Filter genres" - accessibilityState={{ expanded: open }} - style={(state) => [styles.filterToggle, pressFeedback(state)]} - > - - {hiddenCount > 0 - ? `Filter genres · ${hiddenCount} hidden` - : "Filter genres"} - - - {open && !isMobile ? "▴" : "▾"} - - - {!isMobile && open && ( setOpen(false)} + onClose={onClose} /> )} @@ -204,7 +224,6 @@ const styles = StyleSheet.create({ filterToggle: { flexDirection: "row", alignItems: "center", - alignSelf: "flex-start", gap: SPACE.md, paddingHorizontal: SPACE.lgx, paddingVertical: SPACE.md, diff --git a/src/components/GlobalHeader.tsx b/src/components/GlobalHeader.tsx index 831a25b..47042cd 100644 --- a/src/components/GlobalHeader.tsx +++ b/src/components/GlobalHeader.tsx @@ -1,14 +1,17 @@ import { Pressable, StyleSheet, Text, View } from "react-native"; import { usePathname, useRouter } from "expo-router"; +import { HeaderWordmark } from "@/components/HeaderWordmark"; import { useIsNarrow } from "@/components/useIsNarrow"; import { useAuthEmail } from "@/state/auth"; +import { useHomeChrome } from "@/state/homeChrome"; import { usePreferences } from "@/state/preferences"; import { useSideMenu } from "@/state/sideMenu"; import { COLOR, FONT, pressFeedback, SPACE } from "@/theme"; /** * The bar above every screen: menu, back, wordmark, the title-language toggle - * and the account chip. + * and the account chip. While the home grid is being scrolled the bar tightens + * and the wordmark goes compact, leaving room for covers. */ export function GlobalHeader() { const router = useRouter(); @@ -21,11 +24,17 @@ export function GlobalHeader() { const japanese = usePreferences((s) => s.japanese); const toggleJapanese = usePreferences((s) => s.toggleJapanese); const email = useAuthEmail(); - + const compact = useHomeChrome((s) => isHome && s.immersive); const openMenu = useSideMenu((s) => s.openMenu); return ( - + openMenu()} hitSlop={10} @@ -46,30 +55,11 @@ export function GlobalHeader() { ← )} - router.replace("/")} - hitSlop={8} - accessibilityRole="link" - accessibilityLabel="Kasane, go to home" - style={(state) => [styles.wordmarkPressable, pressFeedback(state)]} - > - - Kasane - - {/* The wide-tracked subheading is what pushes the header past a phone - viewport once the back arrow is present, so drop it when narrow. */} - {!isNarrow && ( - <> - - anime + manga - - - - )} - + /> void; +}) { + const [shrink] = useState(() => new Animated.Value(0)); + + useEffect(() => { + Animated.timing(shrink, { + toValue: compact ? 1 : 0, + duration: SHRINK_MS, + useNativeDriver: false, + }).start(); + }, [compact, shrink]); + + const full = narrow ? styles.wordmarkNarrow : styles.wordmark; + const small = styles.wordmarkNarrow; + const wordmarkSize = { + fontSize: shrink.interpolate({ + inputRange: [0, 1], + outputRange: [full.fontSize, small.fontSize], + }), + lineHeight: shrink.interpolate({ + inputRange: [0, 1], + outputRange: [full.lineHeight, small.lineHeight], + }), + }; + + return ( + [styles.pressable, pressFeedback(state)]} + > + + Kasane + + {/* The wide-tracked subheading is what pushes the header past a phone + viewport once the back arrow is present, so drop it when narrow. */} + {!narrow && !compact && ( + <> + + anime + manga + + + + )} + + ); +} + +const styles = StyleSheet.create({ + pressable: { + gap: SPACE.xs, + flexShrink: 1, + }, + // Scaled down rather than allowed to shrink-wrap, which broke "Kasane" + // across two lines on a phone. + wordmarkNarrow: { fontSize: 34, lineHeight: 38, letterSpacing: -1 }, + wordmark: { + color: COLOR.textPrimary, + fontSize: 64, + lineHeight: 68, + letterSpacing: -2, + fontFamily: FONT.display, + paddingBottom: SPACE.xxs, + }, + subheading: { + color: COLOR.textSecondary, + fontSize: 13, + letterSpacing: 6, + textTransform: "uppercase", + fontFamily: FONT.bold, + paddingBottom: SPACE.sm, + }, + subAccent: { + color: COLOR.accent, + fontFamily: FONT.bold, + }, + rule: { + height: 4, + width: 64, + backgroundColor: COLOR.accent, + }, +}); diff --git a/src/components/HomeToolbar.tsx b/src/components/HomeToolbar.tsx new file mode 100644 index 0000000..a520fc9 --- /dev/null +++ b/src/components/HomeToolbar.tsx @@ -0,0 +1,70 @@ +import { StyleSheet, Text, View } from "react-native"; +import { GenreFilterButton, GenreFilterPanel } from "@/components/GenreFilters"; +import { MappedOnlyToggle } from "@/components/MappedOnlyToggle"; +import { COLOR, SPACE, TEXT } from "@/theme"; + +/** + * The home screen's control row: an optional section heading on the left, + * "Mapped only" and "Filter genres" on the right. The row wraps on a narrow + * window, dropping the controls under the heading, and the genre chips open + * beneath the whole row. The screen owns `filtersOpen`: the toolbar moves + * between the search results and the latest grid, and the panel should stay + * open across that move. + */ +export function HomeToolbar({ + heading, + mappedOnly, + onMappedOnlyChange, + filtersOpen, + onFiltersOpenChange, +}: { + heading?: { eyebrow: string; title: string }; + mappedOnly: boolean; + onMappedOnlyChange: (next: boolean) => void; + filtersOpen: boolean; + onFiltersOpenChange: (open: boolean) => void; +}) { + return ( + + + {!!heading && ( + + {heading.eyebrow} + {heading.title} + + )} + + + onFiltersOpenChange(!filtersOpen)} + /> + + + onFiltersOpenChange(false)} + /> + + ); +} + +const styles = StyleSheet.create({ + root: { gap: SPACE.lg }, + row: { + flexDirection: "row", + flexWrap: "wrap", + alignItems: "flex-end", + justifyContent: "space-between", + gap: SPACE.lg, + }, + heading: { gap: SPACE.xxs }, + eyebrow: { ...TEXT.eyebrow, color: COLOR.accent }, + title: { ...TEXT.blockTitle, color: COLOR.textPrimary }, + controls: { + flexDirection: "row", + flexWrap: "wrap", + alignItems: "center", + gap: SPACE.xl, + }, +}); diff --git a/src/components/LatestReleases.tsx b/src/components/LatestReleases.tsx index 670bc99..209cefe 100644 --- a/src/components/LatestReleases.tsx +++ b/src/components/LatestReleases.tsx @@ -1,4 +1,4 @@ -import { useMemo } from "react"; +import { useEffect, useMemo, type ReactNode } from "react"; import { ActivityIndicator, Image, @@ -10,41 +10,78 @@ import { useWindowDimensions, } from "react-native"; import { Link } from "expo-router"; -import type { AniListMedia, SeriesEntry } from "@/types"; +import type { SeriesEntry } from "@/types"; import { displayTitle, englishTitle, trimSeasonSuffix } from "@/data/format"; +import type { SplitFilters } from "@/data/genreFilters"; import { BADGE_SHORT_LABEL, pairResults } from "@/data/pairing"; +import { useLatestAnime } from "@/queries/search"; import { usePreferences } from "@/state/preferences"; import { ContinueSection } from "@/components/ContinueSection"; import { CoverCarousel } from "@/components/CoverCarousel"; import { Footer } from "@/components/Footer"; +import { useInfiniteScroll } from "@/components/useInfiniteScroll"; import { useIsNarrow } from "@/components/useIsNarrow"; import { useLayoutWidth } from "@/components/useLayoutWidth"; import { releaseColumns, tileWidthFor } from "@/data/gridLayout"; -import { BADGE_COLOR, COLOR, FONT, pressFeedback, SPACE, TEXT } from "@/theme"; +import { uniqueMedia, wholeRows } from "@/data/infiniteScroll"; +import { useHomeChrome } from "@/state/homeChrome"; +import { BADGE_COLOR, COLOR, FONT, pressFeedback, SPACE } from "@/theme"; const GRID_ITEM_WIDTH = 160; const GRID_ITEM_HEIGHT = 280; const GRID_GAP = SPACE.xl; +/** + * The home screen's "Latest anime" grid, under the reader's in-progress + * series. `header` sits between the two, so the screen can put its own + * controls in the same row as the section heading. + * + * The grid owns its feed: `useLatestAnime` under `filters`, a page at a time. + * On wider screens it scrolls without end, asking for the next page as the + * reader nears the bottom, and scrolling past the top puts the screen in + * immersive mode, where the header shrinks and the search field hides. The + * footer is pinned below the scroll area rather than inside it. + */ export function LatestReleases({ - data, - loading, + filters, + header, }: { - data: AniListMedia[]; - loading: boolean; + filters: SplitFilters; + header: ReactNode; }) { const { width: windowWidth } = useWindowDimensions(); const isMobile = useIsNarrow(); const [contentWidth, onContentLayout] = useLayoutWidth(); const japanese = usePreferences((s) => s.japanese); + const trackOffset = useHomeChrome((s) => s.trackOffset); + const resetChrome = useHomeChrome((s) => s.reset); + const { data, isFetching, isFetchingNextPage, hasNextPage, fetchNextPage } = + useLatestAnime({ filters, enabled: true }); - const entries = useMemo(() => pairResults(data), [data]); + // Leaving the grid (a search, another tab) restores the full header. + useEffect(() => () => resetChrome(), [resetChrome]); - // Desktop shows only whole rows, so the grid never ends on a short one. + // The phone layout is a carousel, so only the grid pages and goes immersive. + const scroll = useInfiniteScroll({ + enabled: !isMobile, + onEndReached: () => { + if (hasNextPage && !isFetching) fetchNextPage(); + }, + onOffsetChange: trackOffset, + }); + + const entries = useMemo( + () => pairResults(uniqueMedia(data?.pages.map((p) => p.media) ?? [])), + [data], + ); + + // Desktop shows only whole rows, so the grid never ends on a short one + // while another page is on its way. const columns = releaseColumns(windowWidth); const visible = isMobile ? entries - : entries.slice(0, Math.floor(entries.length / columns) * columns); + : wholeRows({ items: entries, columns, complete: !hasNextPage }); + const tileWidth = tileWidthFor({ available: contentWidth, columns, @@ -98,58 +135,61 @@ export function LatestReleases({ ); return ( - - - - Now airing - Latest anime - - {loading && entries.length === 0 ? ( - - - - ) : ( - // Measured rather than read from the window, so a classic scrollbar - // narrows the tiles instead of wrapping the last one. - - {isMobile ? ( - String(entry.routeId)} - itemWidth={GRID_ITEM_WIDTH} - itemHeight={GRID_ITEM_HEIGHT} - containerWidth={contentWidth} - renderItem={(entry) => renderCard(entry)} - /> - ) : ( - - {tileWidth > 0 && - visible.map((entry) => ( - - {renderCard(entry)} - - ))} - - )} - - )} -