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)}
-
- ))}
-
- )}
-
- )}
-
-
+
+
+
+ {header}
+ {isFetching && 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)}
+
+ ))}
+
+ )}
+
+ )}
+ {isFetchingNextPage && (
+
+
+
+ )}
+
+
+
);
}
const styles = StyleSheet.create({
+ root: { flex: 1 },
spinnerWrap: { paddingTop: SPACE.xxxl },
- latestScroll: { paddingBottom: SPACE.page, gap: SPACE.xl },
- latestHeader: { gap: SPACE.xxs },
+ moreSpinner: { paddingVertical: SPACE.xl },
+ latestScroll: { paddingBottom: SPACE.xl, gap: SPACE.xl },
grid: {
flexDirection: "row",
flexWrap: "wrap",
gap: GRID_GAP,
alignItems: "flex-start",
},
- latestEyebrow: { ...TEXT.eyebrow, color: COLOR.accent },
- latestTitle: { ...TEXT.blockTitle, color: COLOR.textPrimary },
gridItem: {
gap: SPACE.md,
},
diff --git a/src/components/MappedOnlyToggle.tsx b/src/components/MappedOnlyToggle.tsx
index 878f866..a9ffa69 100644
--- a/src/components/MappedOnlyToggle.tsx
+++ b/src/components/MappedOnlyToggle.tsx
@@ -30,7 +30,6 @@ const styles = StyleSheet.create({
mappedToggle: {
flexDirection: "row",
alignItems: "center",
- alignSelf: "flex-start",
gap: SPACE.md,
paddingVertical: SPACE.xs,
},
diff --git a/src/components/SeriesMovies.tsx b/src/components/SeriesMovies.tsx
index 53cb47f..b75bc95 100644
--- a/src/components/SeriesMovies.tsx
+++ b/src/components/SeriesMovies.tsx
@@ -1,45 +1,84 @@
-import { StyleSheet, Text, View } from "react-native";
+import { useMemo, useState } from "react";
+import { Pressable, StyleSheet, Text, View } from "react-native";
import type { MovieEntry } from "@/types";
-import { COLOR, FONT, MOVIE_COLOR, SPACE, TEXT } from "@/theme";
+import { COLOR, FONT, MOVIE_COLOR, pressFeedback, SPACE, TEXT } from "@/theme";
+/**
+ * A franchise's films, placed against the episodes they follow. Collapsed by
+ * default: a long-running series can carry a dozen films, and the screen's
+ * focus is the episode and chapter map above.
+ */
export function SeriesMovies({ movies }: { movies: MovieEntry[] }) {
- const ordered = [...movies].sort(
- (a, b) =>
- (a.afterEpisode ?? Number.MAX_SAFE_INTEGER) -
- (b.afterEpisode ?? Number.MAX_SAFE_INTEGER) || a.year - b.year,
+ const [open, setOpen] = useState(false);
+ const ordered = useMemo(
+ () =>
+ [...movies].sort(
+ (a, b) =>
+ (a.afterEpisode ?? Number.MAX_SAFE_INTEGER) -
+ (b.afterEpisode ?? Number.MAX_SAFE_INTEGER) || a.year - b.year,
+ ),
+ [movies],
);
+ const count = `${movies.length} ${movies.length === 1 ? "movie" : "movies"}`;
return (
- Movies
-
- {ordered.map((movie, idx) => (
-
-
-
- {typeof movie.afterEpisode === "number"
- ? `◆ AFTER EP ${movie.afterEpisode}`
- : "◆ MOVIE"}
-
-
- {movie.year}
- {movie.chapters
- ? ` · ch ${movie.chapters[0]}–${movie.chapters[1]}`
- : ""}
-
+ setOpen(!open)}
+ accessibilityRole="button"
+ accessibilityLabel={`Movies, ${count}`}
+ accessibilityHint={open ? "Collapses the list" : "Expands the list"}
+ aria-expanded={open}
+ style={(state) => [styles.header, pressFeedback(state)]}
+ >
+ Movies
+ {count}
+ {open ? "▴" : "▾"}
+
+
+ {open && (
+
+ {ordered.map((movie, idx) => (
+
+
+
+ {typeof movie.afterEpisode === "number"
+ ? `◆ AFTER EP ${movie.afterEpisode}`
+ : "◆ MOVIE"}
+
+
+ {movie.year}
+ {movie.chapters
+ ? ` · ch ${movie.chapters[0]}–${movie.chapters[1]}`
+ : ""}
+
+
+ {movie.title}
+ {!!movie.note && {movie.note}}
- {movie.title}
- {!!movie.note && {movie.note}}
-
- ))}
-
+ ))}
+
+ )}
);
}
const styles = StyleSheet.create({
container: { gap: SPACE.lg },
+ header: {
+ flexDirection: "row",
+ alignItems: "baseline",
+ alignSelf: "flex-start",
+ gap: SPACE.md,
+ paddingVertical: SPACE.xs,
+ },
sectionTitle: { ...TEXT.sectionTitle, color: COLOR.textPrimary },
+ count: { ...TEXT.chipLabel, color: COLOR.textMuted },
+ chevron: {
+ color: MOVIE_COLOR,
+ fontSize: 14,
+ fontFamily: FONT.bold,
+ },
list: { gap: SPACE.md },
card: {
padding: SPACE.lg,
diff --git a/src/components/useInfiniteScroll.ts b/src/components/useInfiniteScroll.ts
new file mode 100644
index 0000000..2121ba7
--- /dev/null
+++ b/src/components/useInfiniteScroll.ts
@@ -0,0 +1,63 @@
+import { useRef } from "react";
+import type {
+ LayoutChangeEvent,
+ NativeScrollEvent,
+ NativeSyntheticEvent,
+ ScrollViewProps,
+} from "react-native";
+import { isNearEnd } from "@/data/infiniteScroll";
+
+/**
+ * Infinite scrolling for a `ScrollView`: spread the returned props onto it,
+ * and `onEndReached` fires as the reader nears the bottom of the content.
+ *
+ * A first page shorter than the window never scrolls, so the viewport and the
+ * content are measured as they lay out too, and the hook keeps asking until
+ * the content overflows. `onOffsetChange` reports every scroll position for
+ * anything else that tracks it, such as the home screen's immersive mode.
+ * Disabled, the hook hands back no props at all and the list scrolls plainly.
+ */
+export function useInfiniteScroll({
+ enabled,
+ onEndReached,
+ onOffsetChange,
+}: {
+ enabled: boolean;
+ onEndReached: () => void;
+ onOffsetChange?: (offset: number) => void;
+}): ScrollViewProps {
+ // Scroll geometry, read by the handlers below and never rendered.
+ const metrics = useRef({ offset: 0, viewport: 0, content: 0 });
+
+ const checkEnd = () => {
+ if (isNearEnd(metrics.current)) onEndReached();
+ };
+
+ const onScroll = (e: NativeSyntheticEvent) => {
+ const { contentOffset, layoutMeasurement, contentSize } = e.nativeEvent;
+ metrics.current = {
+ offset: contentOffset.y,
+ viewport: layoutMeasurement.height,
+ content: contentSize.height,
+ };
+ onOffsetChange?.(contentOffset.y);
+ checkEnd();
+ };
+
+ const onLayout = (e: LayoutChangeEvent) => {
+ metrics.current = {
+ ...metrics.current,
+ viewport: e.nativeEvent.layout.height,
+ };
+ checkEnd();
+ };
+
+ const onContentSizeChange = (_width: number, height: number) => {
+ metrics.current = { ...metrics.current, content: height };
+ checkEnd();
+ };
+
+ return enabled
+ ? { onScroll, onLayout, onContentSizeChange, scrollEventThrottle: 16 }
+ : {};
+}
diff --git a/src/data/catalogSearch.test.ts b/src/data/catalogSearch.test.ts
new file mode 100644
index 0000000..73a2e09
--- /dev/null
+++ b/src/data/catalogSearch.test.ts
@@ -0,0 +1,101 @@
+import { describe, expect, it } from "bun:test";
+import {
+ catalogMediaIds,
+ matchCatalogTitles,
+ mergeSearchResults,
+} from "./catalogSearch";
+import { makeMedia } from "@test/fixtures/media";
+import type { SeriesMapping } from "@/types";
+
+const series = ({
+ title,
+ anime,
+ manga,
+}: {
+ title: string;
+ anime: number;
+ manga: number;
+}): SeriesMapping => ({
+ title,
+ anilistAnimeId: anime,
+ anilistMangaId: manga,
+ mappings: [],
+ movies: [],
+});
+
+const twoHit = series({
+ title: "Do You Love Your Mom and Her Two-Hit Multi-Target Attacks?",
+ anime: 104723,
+ manga: 98280,
+});
+const aot = series({ title: "Attack on Titan", anime: 16498, manga: 53390 });
+const counter = series({ title: "Counterattack", anime: 1, manga: 2 });
+const naruto = series({ title: "Naruto", anime: 20, manga: 30 });
+const mappings = [twoHit, counter, naruto, aot];
+
+describe("matchCatalogTitles", () => {
+ it("finds Attack on Titan for a partial query", () => {
+ expect(matchCatalogTitles({ query: "attack", mappings })).toContain(aot);
+ });
+
+ it("ranks title prefix, then word prefix, then substring", () => {
+ expect(matchCatalogTitles({ query: "attack", mappings })).toEqual([
+ aot,
+ twoHit,
+ counter,
+ ]);
+ });
+
+ it("ignores case and punctuation", () => {
+ expect(matchCatalogTitles({ query: " ATTACK-on ", mappings })).toEqual([
+ aot,
+ ]);
+ });
+
+ it("returns nothing for a one-character or empty query", () => {
+ expect(matchCatalogTitles({ query: "a", mappings })).toEqual([]);
+ expect(matchCatalogTitles({ query: " ", mappings })).toEqual([]);
+ });
+
+ it("returns nothing when no title matches", () => {
+ expect(matchCatalogTitles({ query: "bleach", mappings })).toEqual([]);
+ });
+
+ it("caps the matches at the limit", () => {
+ expect(matchCatalogTitles({ query: "attack", mappings, limit: 1 })).toEqual(
+ [aot],
+ );
+ });
+});
+
+describe("catalogMediaIds", () => {
+ it("lists anime then manga ids for each match, without repeats", () => {
+ expect(catalogMediaIds([aot, aot, naruto])).toEqual([16498, 53390, 20, 30]);
+ });
+});
+
+describe("mergeSearchResults", () => {
+ it("puts catalog media first in id order and drops repeats", () => {
+ const anime = makeMedia({ id: 16498, type: "ANIME" });
+ const manga = makeMedia({ id: 53390, type: "MANGA" });
+ const other = makeMedia({ id: 55391, type: "MANGA" });
+ expect(
+ mergeSearchResults({
+ ids: [16498, 53390],
+ catalogMedia: [manga, anime],
+ searchMedia: [other, anime],
+ }).map((m) => m.id),
+ ).toEqual([16498, 53390, 55391]);
+ });
+
+ it("skips ids AniList did not return, such as a hidden genre", () => {
+ const other = makeMedia({ id: 55391, type: "MANGA" });
+ expect(
+ mergeSearchResults({
+ ids: [16498],
+ catalogMedia: [],
+ searchMedia: [other],
+ }).map((m) => m.id),
+ ).toEqual([55391]);
+ });
+});
diff --git a/src/data/catalogSearch.ts b/src/data/catalogSearch.ts
new file mode 100644
index 0000000..3057f49
--- /dev/null
+++ b/src/data/catalogSearch.ts
@@ -0,0 +1,90 @@
+import type { AniListMedia, SeriesMapping } from "@/types";
+
+// AniList ranks a search by text match alone and returns one page, so a short
+// query like "attack" can push a curated series (Attack on Titan sits at #21)
+// off the page entirely, and "Mapped only" then hides everything that is left.
+// Matching the catalog's own titles locally guarantees every mapped series the
+// query names is fetched and shown first.
+
+/** How many catalog matches to fetch alongside the AniList page. */
+export const CATALOG_MATCH_LIMIT = 10;
+
+const normalize = (text: string): string =>
+ text
+ .toLowerCase()
+ .replace(/[^a-z0-9]+/g, " ")
+ .trim();
+
+// 0: the title starts with the query, 1: a word does, 2: it appears anywhere.
+const matchRank = ({
+ title,
+ query,
+}: {
+ title: string;
+ query: string;
+}): number | null => {
+ if (title.startsWith(query)) return 0;
+ if (` ${title}`.includes(` ${query}`)) return 1;
+ return title.includes(query) ? 2 : null;
+};
+
+/**
+ * The catalog series whose title contains `query`, best match first: titles
+ * that start with it, then titles with a word that starts with it, then any
+ * other substring match, each group in catalog order.
+ */
+export function matchCatalogTitles({
+ query,
+ mappings,
+ limit = CATALOG_MATCH_LIMIT,
+}: {
+ query: string;
+ mappings: readonly SeriesMapping[];
+ limit?: number;
+}): SeriesMapping[] {
+ const needle = normalize(query);
+ if (needle.length < 2) return [];
+ return mappings
+ .map((mapping, index) => ({
+ mapping,
+ index,
+ rank: matchRank({ title: normalize(mapping.title), query: needle }),
+ }))
+ .filter(
+ (m): m is { mapping: SeriesMapping; index: number; rank: number } =>
+ m.rank !== null,
+ )
+ .toSorted((a, b) => a.rank - b.rank || a.index - b.index)
+ .slice(0, limit)
+ .map((m) => m.mapping);
+}
+
+/** Both AniList ids of every matched series, anime first, without repeats. */
+export function catalogMediaIds(matches: readonly SeriesMapping[]): number[] {
+ return [
+ ...new Set(matches.flatMap((m) => [m.anilistAnimeId, m.anilistMangaId])),
+ ];
+}
+
+/**
+ * The catalog's media ahead of AniList's page, each id once. Catalog media
+ * keep the order of `ids`, so the best title match leads.
+ */
+export function mergeSearchResults({
+ ids,
+ catalogMedia,
+ searchMedia,
+}: {
+ ids: readonly number[];
+ catalogMedia: readonly AniListMedia[];
+ searchMedia: readonly AniListMedia[];
+}): AniListMedia[] {
+ const byId = new Map(
+ catalogMedia.map((m): [number, AniListMedia] => [m.id, m]),
+ );
+ const ordered = ids
+ .map((id) => byId.get(id))
+ .filter((m): m is AniListMedia => !!m);
+ const seen = new Set(ordered.map((m) => m.id));
+ return [...ordered, ...searchMedia.filter((m) => !seen.has(m.id))];
+}
diff --git a/src/data/gridLayout.test.ts b/src/data/gridLayout.test.ts
index 53720c0..b46ac9e 100644
--- a/src/data/gridLayout.test.ts
+++ b/src/data/gridLayout.test.ts
@@ -49,6 +49,9 @@ describe("releaseColumns", () => {
expect(releaseColumns(700)).toBe(3);
expect(releaseColumns(800)).toBe(4);
expect(releaseColumns(1280)).toBe(6);
- expect(releaseColumns(2560)).toBe(12);
+ // A 15" MacBook Air's full-width browser window.
+ expect(releaseColumns(1710)).toBe(10);
+ expect(releaseColumns(2000)).toBe(12);
+ expect(releaseColumns(2560)).toBe(15);
});
});
diff --git a/src/data/gridLayout.ts b/src/data/gridLayout.ts
index e59bd58..616749f 100644
--- a/src/data/gridLayout.ts
+++ b/src/data/gridLayout.ts
@@ -47,9 +47,9 @@ export const gridLayout = ({
};
const RELEASE_COLUMNS = [
- { minWidth: 2400, columns: 12 },
- { minWidth: 2000, columns: 9 },
- { minWidth: 1700, columns: 8 },
+ { minWidth: 2400, columns: 15 },
+ { minWidth: 2000, columns: 12 },
+ { minWidth: 1700, columns: 10 },
{ minWidth: 1450, columns: 7 },
{ minWidth: 1200, columns: 6 },
{ minWidth: 1000, columns: 5 },
diff --git a/src/data/guards.test.ts b/src/data/guards.test.ts
index 1d43019..000b876 100644
--- a/src/data/guards.test.ts
+++ b/src/data/guards.test.ts
@@ -1,5 +1,20 @@
import { describe, expect, it } from "bun:test";
-import { hasBoundingRect } from "./guards";
+import { hasBoundingRect, isRecord } from "./guards";
+
+describe("isRecord", () => {
+ it("accepts a plain object", () => {
+ expect(isRecord({})).toBe(true);
+ expect(isRecord({ a: 1 })).toBe(true);
+ });
+
+ it("rejects null, arrays and primitives", () => {
+ expect(isRecord(null)).toBe(false);
+ expect(isRecord([])).toBe(false);
+ expect(isRecord("a")).toBe(false);
+ expect(isRecord(1)).toBe(false);
+ expect(isRecord(undefined)).toBe(false);
+ });
+});
describe("hasBoundingRect", () => {
it("accepts a node that can measure itself", () => {
diff --git a/src/data/guards.ts b/src/data/guards.ts
index 881b9e3..10b67a6 100644
--- a/src/data/guards.ts
+++ b/src/data/guards.ts
@@ -1,3 +1,7 @@
+/** A plain object: not null, not an array. The first step of most guards. */
+export const isRecord = (value: unknown): value is Record =>
+ typeof value === "object" && value !== null && !Array.isArray(value);
+
/**
* A rendered node that can report its on-screen box. react-native-web hands
* back the DOM element from a `View` ref; native refs have no such method.
@@ -6,8 +10,7 @@ export function hasBoundingRect(
node: unknown,
): node is { getBoundingClientRect: () => DOMRect } {
return (
- typeof node === "object" &&
- node !== null &&
+ isRecord(node) &&
"getBoundingClientRect" in node &&
typeof node.getBoundingClientRect === "function"
);
diff --git a/src/data/infiniteScroll.test.ts b/src/data/infiniteScroll.test.ts
new file mode 100644
index 0000000..d12f8ca
--- /dev/null
+++ b/src/data/infiniteScroll.test.ts
@@ -0,0 +1,61 @@
+import { describe, expect, it } from "bun:test";
+import { isNearEnd, uniqueMedia, wholeRows } from "@/data/infiniteScroll";
+import { makeMedia } from "@test/fixtures/media";
+
+describe("isNearEnd", () => {
+ it("fires once the viewport reaches the load-ahead band", () => {
+ expect(
+ isNearEnd({ offset: 0, viewport: 800, content: 3000, ahead: 500 }),
+ ).toBe(false);
+ expect(
+ isNearEnd({ offset: 1700, viewport: 800, content: 3000, ahead: 500 }),
+ ).toBe(true);
+ });
+
+ it("fires when the content is shorter than the viewport", () => {
+ expect(isNearEnd({ offset: 0, viewport: 900, content: 600 })).toBe(true);
+ });
+
+ // Before the first layout the viewport reads 0, which is not a real end.
+ it("never fires before the viewport is measured", () => {
+ expect(isNearEnd({ offset: 0, viewport: 0, content: 0 })).toBe(false);
+ });
+});
+
+describe("uniqueMedia", () => {
+ it("flattens pages in order and keeps the first copy of each id", () => {
+ const pages = [
+ [
+ makeMedia({ id: 1, type: "ANIME" }),
+ makeMedia({ id: 2, type: "ANIME" }),
+ ],
+ [
+ makeMedia({ id: 2, type: "ANIME" }),
+ makeMedia({ id: 3, type: "ANIME" }),
+ ],
+ ];
+ expect(uniqueMedia(pages).map((m) => m.id)).toEqual([1, 2, 3]);
+ });
+
+ it("returns nothing for no pages", () => {
+ expect(uniqueMedia([])).toEqual([]);
+ });
+});
+
+describe("wholeRows", () => {
+ const items = [1, 2, 3, 4, 5, 6, 7];
+
+ it("drops the short last row while more is coming", () => {
+ expect(wholeRows({ items, columns: 3, complete: false })).toEqual([
+ 1, 2, 3, 4, 5, 6,
+ ]);
+ });
+
+ it("keeps everything once the feed is complete", () => {
+ expect(wholeRows({ items, columns: 3, complete: true })).toEqual(items);
+ });
+
+ it("keeps everything for a nonsensical column count", () => {
+ expect(wholeRows({ items, columns: 0, complete: false })).toEqual(items);
+ });
+});
diff --git a/src/data/infiniteScroll.ts b/src/data/infiniteScroll.ts
new file mode 100644
index 0000000..045f1d0
--- /dev/null
+++ b/src/data/infiniteScroll.ts
@@ -0,0 +1,45 @@
+import type { AniListMedia } from "@/types";
+
+/** How close to the end of the content, in points, the next page loads. */
+export const LOAD_AHEAD = 800;
+
+/** True once the viewport's bottom edge is within `ahead` of the content's. */
+export function isNearEnd({
+ offset,
+ viewport,
+ content,
+ ahead = LOAD_AHEAD,
+}: {
+ offset: number;
+ viewport: number;
+ content: number;
+ ahead?: number;
+}): boolean {
+ return viewport > 0 && offset + viewport >= content - ahead;
+}
+
+/**
+ * Every page's media in order, each id once. A title can shift between pages
+ * while the feed is being read, and the second copy would repeat a tile.
+ */
+export function uniqueMedia(pages: readonly AniListMedia[][]): AniListMedia[] {
+ const seen = new Set();
+ return pages.flat().filter((m) => !seen.has(m.id) && !!seen.add(m.id));
+}
+
+/**
+ * `items` cut to whole rows of `columns`, so the grid never ends on a short
+ * row while more is coming. Once the feed is `complete` the last row stays.
+ */
+export function wholeRows({
+ items,
+ columns,
+ complete,
+}: {
+ items: readonly T[];
+ columns: number;
+ complete: boolean;
+}): T[] {
+ if (complete || columns < 1) return [...items];
+ return items.slice(0, Math.floor(items.length / columns) * columns);
+}
diff --git a/src/data/mangadexRoutes.test.ts b/src/data/mangadexRoutes.test.ts
new file mode 100644
index 0000000..ceeb6f4
--- /dev/null
+++ b/src/data/mangadexRoutes.test.ts
@@ -0,0 +1,21 @@
+import { describe, expect, it } from "bun:test";
+import { upstreamUrl } from "./mangadexRoutes";
+
+describe("upstreamUrl", () => {
+ it("maps the API path onto api.mangadex.org, query included", () => {
+ expect(upstreamUrl("/_mdx/manga?title=Naruto&limit=10")).toBe(
+ "https://api.mangadex.org/manga?title=Naruto&limit=10",
+ );
+ });
+
+ it("maps the covers path onto the covers CDN", () => {
+ expect(upstreamUrl("/_mdx-covers/m1/a.png.256.jpg")).toBe(
+ "https://uploads.mangadex.org/covers/m1/a.png.256.jpg",
+ );
+ });
+
+ it("leaves every other path to the server", () => {
+ expect(upstreamUrl("/series/30011")).toBeNull();
+ expect(upstreamUrl("/_mdxish/manga")).toBeNull();
+ });
+});
diff --git a/src/data/mangadexRoutes.ts b/src/data/mangadexRoutes.ts
new file mode 100644
index 0000000..ffba897
--- /dev/null
+++ b/src/data/mangadexRoutes.ts
@@ -0,0 +1,32 @@
+/**
+ * Where MangaDex lives and how the app reaches it. `api.mangadex.org` and the
+ * covers CDN both answer a browser User-Agent with a bot challenge, so the web
+ * build calls the same-origin proxy paths below and a proxy forwards with the
+ * non-browser User-Agent. This is the one place the paths, hosts and
+ * User-Agent are written down: the client (`src/api/mangadex.ts`) and every
+ * proxy (`netlify/edge-functions/mangadex.ts`, `metro.config.js`,
+ * `e2e/serve.ts`) read them from here.
+ *
+ * No imports, on purpose: Node's `require` loads it for Metro, the Deno edge
+ * runtime loads it through `netlify/import_map.json`, and the web bundle loads
+ * it like any other module.
+ */
+export const MANGADEX_USER_AGENT =
+ "kasane (+https://github.com/codebend3r/kasane)";
+
+/** Each MangaDex host the app reads, and the same-origin path that proxies it. */
+export const MANGADEX_ROUTES = {
+ api: { proxy: "/_mdx", upstream: "https://api.mangadex.org" },
+ covers: {
+ proxy: "/_mdx-covers",
+ upstream: "https://uploads.mangadex.org/covers",
+ },
+} as const;
+
+/** The MangaDex URL a request path maps to, or null when it is not proxied. */
+export function upstreamUrl(path: string): string | null {
+ const route = Object.values(MANGADEX_ROUTES).find((r) =>
+ path.startsWith(`${r.proxy}/`),
+ );
+ return route ? `${route.upstream}${path.slice(route.proxy.length)}` : null;
+}
diff --git a/src/data/mangadexSnapshot.test.ts b/src/data/mangadexSnapshot.test.ts
new file mode 100644
index 0000000..f7f8118
--- /dev/null
+++ b/src/data/mangadexSnapshot.test.ts
@@ -0,0 +1,126 @@
+import { describe, expect, it } from "bun:test";
+import {
+ coverUrl,
+ isMangaDexCoverFile,
+ isMangaDexTitle,
+ rowToSnapshot,
+ snapshotToInfo,
+ type MangaDexSeriesRow,
+ type MangaDexSnapshot,
+} from "./mangadexSnapshot";
+
+const snapshot: MangaDexSnapshot = {
+ mangadexId: "m1",
+ titles: [{ locale: "en", value: "Naruto" }],
+ volumes: 2,
+ chapters: 9,
+ covers: [
+ { volume: "1", locale: "ja", fileName: "a.png" },
+ { volume: "2", locale: "en", fileName: "b.jpg" },
+ ],
+};
+
+// Stray and malformed entries sit among the good ones on purpose.
+const row: MangaDexSeriesRow = {
+ id: 7,
+ anilist_manga_id: 30011,
+ mangadex_id: "m1",
+ titles: [
+ { locale: "en", value: "Naruto" },
+ { locale: "ja", value: 3 },
+ "stray",
+ ],
+ covers: [
+ { volume: "1", locale: "ja", fileName: "a.png" },
+ { volume: 2, locale: "en", fileName: "x.jpg" },
+ { volume: "2", locale: "en", fileName: "b.jpg" },
+ ],
+ volumes: 2,
+ chapters: 9,
+ fetched_at: "2026-11-08T00:00:00Z",
+ created_at: "2026-11-08T00:00:00Z",
+ updated_at: "2026-11-08T00:00:00Z",
+};
+
+describe("isMangaDexTitle", () => {
+ it("accepts a locale and value pair of strings", () => {
+ expect(isMangaDexTitle({ locale: "en", value: "Naruto" })).toBe(true);
+ });
+
+ it("rejects anything else", () => {
+ expect(isMangaDexTitle({ locale: "en", value: 3 })).toBe(false);
+ expect(isMangaDexTitle({ locale: "en" })).toBe(false);
+ expect(isMangaDexTitle("Naruto")).toBe(false);
+ expect(isMangaDexTitle(null)).toBe(false);
+ expect(isMangaDexTitle([])).toBe(false);
+ });
+});
+
+describe("isMangaDexCoverFile", () => {
+ it("accepts a volume, locale and file name of strings", () => {
+ expect(
+ isMangaDexCoverFile({ volume: "1", locale: "ja", fileName: "a.png" }),
+ ).toBe(true);
+ });
+
+ it("rejects a missing or non-string field", () => {
+ expect(
+ isMangaDexCoverFile({ volume: 1, locale: "ja", fileName: "a.png" }),
+ ).toBe(false);
+ expect(isMangaDexCoverFile({ volume: "1", locale: "ja" })).toBe(false);
+ expect(isMangaDexCoverFile(null)).toBe(false);
+ });
+});
+
+describe("coverUrl", () => {
+ const cover = { base: "/_mdx-covers", mangaId: "m1", fileName: "a.png" };
+
+ it("asks for MangaDex's resized JPEG for a thumbnail size", () => {
+ expect(coverUrl({ ...cover, size: "256" })).toBe(
+ "/_mdx-covers/m1/a.png.256.jpg",
+ );
+ expect(coverUrl({ ...cover, size: "512" })).toBe(
+ "/_mdx-covers/m1/a.png.512.jpg",
+ );
+ });
+
+ it("leaves the original file name alone at full size", () => {
+ expect(coverUrl({ ...cover, size: "full" })).toBe("/_mdx-covers/m1/a.png");
+ });
+});
+
+describe("rowToSnapshot", () => {
+ it("lifts a cached row into a snapshot, keeping only well-formed entries", () => {
+ expect(rowToSnapshot(row)).toEqual(snapshot);
+ });
+
+ it("reads a non-array column as empty", () => {
+ expect(
+ rowToSnapshot({ ...row, titles: { en: "Naruto" }, covers: null }),
+ ).toEqual({ ...snapshot, titles: [], covers: [] });
+ });
+});
+
+describe("snapshotToInfo", () => {
+ it("resolves every cover to a 512 image and a 256 thumbnail under the base", () => {
+ expect(snapshotToInfo({ snapshot, coversBase: "/_mdx-covers" })).toEqual({
+ titles: [{ locale: "en", value: "Naruto" }],
+ volumes: 2,
+ chapters: 9,
+ covers: [
+ {
+ volume: "1",
+ locale: "ja",
+ url: "/_mdx-covers/m1/a.png.512.jpg",
+ thumbUrl: "/_mdx-covers/m1/a.png.256.jpg",
+ },
+ {
+ volume: "2",
+ locale: "en",
+ url: "/_mdx-covers/m1/b.jpg.512.jpg",
+ thumbUrl: "/_mdx-covers/m1/b.jpg.256.jpg",
+ },
+ ],
+ });
+ });
+});
diff --git a/src/data/mangadexSnapshot.ts b/src/data/mangadexSnapshot.ts
new file mode 100644
index 0000000..68d27ac
--- /dev/null
+++ b/src/data/mangadexSnapshot.ts
@@ -0,0 +1,109 @@
+import { isRecord } from "@/data/guards";
+import type { MangaDexInfo, MangaDexTitle, MangaDexVolumeCover } from "@/types";
+import type { Database, Json } from "@/types/supabase";
+
+export type MangaDexSeriesRow =
+ Database["public"]["Tables"]["mangadex_series"]["Row"];
+
+/** A volume cover as MangaDex names it, before any URL is built for it. */
+export type MangaDexCoverFile = {
+ volume: string;
+ locale: string;
+ fileName: string;
+};
+
+/**
+ * Everything the app keeps from a MangaDex lookup, independent of where the
+ * images are served from. Both the live lookup and the Supabase cache produce
+ * one; `snapshotToInfo` turns it into what the screens render.
+ */
+export type MangaDexSnapshot = {
+ mangadexId: string;
+ titles: MangaDexTitle[];
+ volumes: number;
+ chapters: number;
+ covers: MangaDexCoverFile[];
+};
+
+/** A `{ locale, value }` title as the `titles` column stores it. */
+export function isMangaDexTitle(value: unknown): value is MangaDexTitle {
+ return (
+ isRecord(value) &&
+ typeof value.locale === "string" &&
+ typeof value.value === "string"
+ );
+}
+
+/** A `{ volume, locale, fileName }` cover as the `covers` column stores it. */
+export function isMangaDexCoverFile(
+ value: unknown,
+): value is MangaDexCoverFile {
+ return (
+ isRecord(value) &&
+ typeof value.volume === "string" &&
+ typeof value.locale === "string" &&
+ typeof value.fileName === "string"
+ );
+}
+
+/** The well-formed items of a jsonb list column; anything else is dropped. */
+function listFromJson(json: Json, isItem: (v: unknown) => v is T): T[] {
+ const items: readonly unknown[] = Array.isArray(json) ? json : [];
+ return items.filter(isItem);
+}
+
+/** A cover image under `base`: the original, or MangaDex's resized JPEG. */
+export function coverUrl({
+ base,
+ mangaId,
+ fileName,
+ size,
+}: {
+ base: string;
+ mangaId: string;
+ fileName: string;
+ size: "256" | "512" | "full";
+}): string {
+ const file = size === "full" ? fileName : `${fileName}.${size}.jpg`;
+ return `${base}/${mangaId}/${file}`;
+}
+
+/** A cached row as a snapshot, so both sources render through one path. */
+export function rowToSnapshot(row: MangaDexSeriesRow): MangaDexSnapshot {
+ return {
+ mangadexId: row.mangadex_id,
+ titles: listFromJson(row.titles, isMangaDexTitle),
+ volumes: row.volumes,
+ chapters: row.chapters,
+ covers: listFromJson(row.covers, isMangaDexCoverFile),
+ };
+}
+
+/** The snapshot with every cover resolved to URLs under `coversBase`. */
+export function snapshotToInfo({
+ snapshot,
+ coversBase,
+}: {
+ snapshot: MangaDexSnapshot;
+ coversBase: string;
+}): MangaDexInfo {
+ const sized = (c: MangaDexCoverFile, size: "256" | "512"): string =>
+ coverUrl({
+ base: coversBase,
+ mangaId: snapshot.mangadexId,
+ fileName: c.fileName,
+ size,
+ });
+ const covers: MangaDexVolumeCover[] = snapshot.covers.map((c) => ({
+ volume: c.volume,
+ locale: c.locale,
+ url: sized(c, "512"),
+ thumbUrl: sized(c, "256"),
+ }));
+ return {
+ titles: snapshot.titles,
+ volumes: snapshot.volumes,
+ chapters: snapshot.chapters,
+ covers,
+ };
+}
diff --git a/src/data/time.test.ts b/src/data/time.test.ts
new file mode 100644
index 0000000..a41a847
--- /dev/null
+++ b/src/data/time.test.ts
@@ -0,0 +1,11 @@
+import { describe, expect, it } from "bun:test";
+import { DAY_MS, HOUR_MS, MINUTE_MS, WEEK_MS } from "./time";
+
+describe("time constants", () => {
+ it("build on one another", () => {
+ expect(MINUTE_MS).toBe(60_000);
+ expect(HOUR_MS).toBe(60 * MINUTE_MS);
+ expect(DAY_MS).toBe(24 * HOUR_MS);
+ expect(WEEK_MS).toBe(7 * DAY_MS);
+ });
+});
diff --git a/src/data/time.ts b/src/data/time.ts
new file mode 100644
index 0000000..b038d37
--- /dev/null
+++ b/src/data/time.ts
@@ -0,0 +1,5 @@
+// Durations in milliseconds: query staleness windows, cache ages, pauses.
+export const MINUTE_MS = 60 * 1000;
+export const HOUR_MS = 60 * MINUTE_MS;
+export const DAY_MS = 24 * HOUR_MS;
+export const WEEK_MS = 7 * DAY_MS;
diff --git a/src/queries/catalog.ts b/src/queries/catalog.ts
index 46e577b..7b23bf9 100644
--- a/src/queries/catalog.ts
+++ b/src/queries/catalog.ts
@@ -4,7 +4,7 @@ import { fetchCatalog } from "@/api/catalog";
import { indexByMediaId, type Catalog } from "@/data/catalog";
import type { GenreFilter } from "@/data/genreFilters";
import { buildSyntheticMapping } from "@/data/pairing";
-import { HOUR_MS, WEEK_MS } from "@/queries/shared";
+import { HOUR_MS, WEEK_MS } from "@/data/time";
import type { AniListMedia, ResolvedMapping, SeriesMapping } from "@/types";
export const CATALOG_QUERY_KEY = ["catalog"] as const;
diff --git a/src/queries/covers.ts b/src/queries/covers.ts
index bbb97cb..ff15c22 100644
--- a/src/queries/covers.ts
+++ b/src/queries/covers.ts
@@ -1,7 +1,7 @@
import { useMemo } from "react";
import { useQuery } from "@tanstack/react-query";
import { getCoversByIds } from "@/api/anilist";
-import { WEEK_MS } from "@/queries/shared";
+import { WEEK_MS } from "@/data/time";
export type Cover = { url: string; color: string | null };
export type CoverMap = Record;
diff --git a/src/queries/media.test.ts b/src/queries/media.test.ts
index 905d934..e7a3880 100644
--- a/src/queries/media.test.ts
+++ b/src/queries/media.test.ts
@@ -1,12 +1,9 @@
-import { describe, expect, it } from "bun:test";
-import {
- useFranchise,
- useMangaDex,
- useMedia,
- useMediaByIds,
-} from "@/queries/media";
+import { afterEach, describe, expect, it, spyOn } from "bun:test";
+import { useMangaDex, useMedia, useMediaByIds } from "@/queries/media";
import { graphqlRequestMock } from "@test/mocks/graphql";
-import { makeEdge, makeMedia } from "@test/fixtures/media";
+import { fromMock, singleRowOf } from "@test/mocks/supabase";
+import { makeMedia } from "@test/fixtures/media";
+import type { MangaDexSeriesRow } from "@/data/mangadexSnapshot";
import { last, renderHook, settle } from "@test/renderHook";
describe("useMedia", () => {
@@ -49,53 +46,75 @@ describe("useMediaByIds", () => {
});
});
-describe("useFranchise", () => {
- it("skips the walk for an anime with no sequels", () => {
- const standalone = makeMedia({ id: 1, type: "ANIME" });
- const { captures, unmount } = renderHook(() => useFranchise(standalone));
+const cachedRow: 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("useMangaDex", () => {
+ const manga = makeMedia({ id: 30011, type: "MANGA" });
+ const fetchSpy = spyOn(globalThis, "fetch");
+ afterEach(() => {
+ fetchSpy.mockReset();
+ });
+
+ it("waits without a request while the manga is unknown", () => {
+ const { captures, unmount } = renderHook(() => useMangaDex(null));
try {
expect(last(captures).fetchStatus).toBe("idle");
- expect(graphqlRequestMock).not.toHaveBeenCalled();
} finally {
unmount();
}
});
- it("walks the franchise for an anime with a sequel", async () => {
- const root = makeMedia({
- id: 1,
- type: "ANIME",
- relations: [makeEdge({ relationType: "SEQUEL", id: 2, type: "ANIME" })],
- });
- graphqlRequestMock.mockResolvedValueOnce({
- Page: {
- media: [
- {
- id: 1,
- title: { romaji: "Root", english: null },
- format: "TV",
- episodes: 12,
- startDate: { year: 2020 },
- relations: { edges: [] },
- },
- ],
- },
- });
- const { captures, unmount } = renderHook(() => useFranchise(root));
+ it("serves a cached series without touching MangaDex", async () => {
+ fromMock.mockImplementationOnce(() => singleRowOf(cachedRow));
+ const { captures, unmount } = renderHook(() => useMangaDex(manga));
try {
- await settle(() => last(captures).isSuccess, "the franchise");
- expect(last(captures).data?.totalTvEpisodes).toBe(12);
+ await settle(() => last(captures).isSuccess, "the cached lookup");
+ const info = last(captures).data;
+ expect(info?.volumes).toBe(72);
+ expect(info?.covers[0]?.thumbUrl).toBe(
+ "https://uploads.mangadex.org/covers/m1/a.png.256.jpg",
+ );
+ expect(fetchSpy).not.toHaveBeenCalled();
} finally {
unmount();
}
});
-});
-describe("useMangaDex", () => {
- it("waits without a request while the manga is unknown", () => {
- const { captures, unmount } = renderHook(() => useMangaDex(null));
+ it("falls back to the live lookup when the cache has no row", async () => {
+ fromMock.mockImplementationOnce(() => singleRowOf(null));
+ fetchSpy.mockResolvedValueOnce(Response.json({ data: [] }));
+ const { captures, unmount } = renderHook(() => useMangaDex(manga));
try {
- expect(last(captures).fetchStatus).toBe("idle");
+ await settle(() => last(captures).isSuccess, "the live lookup");
+ expect(last(captures).data).toBeNull();
+ expect(fetchSpy).toHaveBeenCalledTimes(1);
+ expect(String(fetchSpy.mock.calls[0]?.[0])).toContain("/manga?title=");
+ } finally {
+ unmount();
+ }
+ });
+
+ it("falls back to the live lookup when the cache read fails", async () => {
+ fromMock.mockImplementationOnce(() =>
+ singleRowOf(null, { message: "relation does not exist" }),
+ );
+ fetchSpy.mockResolvedValueOnce(Response.json({ data: [] }));
+ const { captures, unmount } = renderHook(() => useMangaDex(manga));
+ try {
+ await settle(() => last(captures).isSuccess, "the live lookup");
+ expect(last(captures).data).toBeNull();
+ expect(fetchSpy).toHaveBeenCalledTimes(1);
} finally {
unmount();
}
diff --git a/src/queries/media.ts b/src/queries/media.ts
index 0c01f85..ec0f2d3 100644
--- a/src/queries/media.ts
+++ b/src/queries/media.ts
@@ -1,13 +1,11 @@
import { useQuery } from "@tanstack/react-query";
-import {
- getAnimeFranchise,
- getMedia,
- getMediaByIds,
- hasAnimeSequels,
-} from "@/api/anilist";
-import { getMangaDexInfoByAniListId } from "@/api/mangadex";
+import { getMedia, getMediaByIds } from "@/api/anilist";
+import { appMangaDexClient, getMangaDexSnapshot } from "@/api/mangadex";
+import { fetchCachedMangaDex } from "@/api/mangadexCache";
import { englishTitle } from "@/data/format";
-import { DAY_MS, HOUR_MS, MINUTE_MS, disabledQuery } from "@/queries/shared";
+import { snapshotToInfo } from "@/data/mangadexSnapshot";
+import { DAY_MS, HOUR_MS, MINUTE_MS } from "@/data/time";
+import { disabledQuery } from "@/queries/shared";
import type { AniListMedia } from "@/types";
/** One AniList entry with its relations; `null` waits for an id. */
@@ -24,33 +22,39 @@ export function useMedia(id: number | null) {
export function useMediaByIds(ids: readonly number[]) {
return useQuery({
queryKey: ["media-by-ids", ids.join(",")],
- queryFn: () => getMediaByIds([...ids]),
+ queryFn: () => getMediaByIds(ids),
enabled: ids.length > 0,
staleTime: HOUR_MS,
});
}
-/** Every season of an anime's franchise; skipped when it has no sequels. */
-export function useFranchise(anime: AniListMedia | null) {
- return useQuery({
- queryKey: ["franchise", anime?.id ?? null],
- queryFn: () =>
- anime === null ? disabledQuery() : getAnimeFranchise(anime.id),
- enabled: anime !== null && hasAnimeSequels(anime),
- staleTime: DAY_MS,
- });
-}
-
-/** MangaDex covers, titles and counts for a manga, matched by its title. */
+/**
+ * MangaDex covers, titles and counts for a manga. The Supabase cache first, one
+ * read for the whole series; the live lookup by title for a manga the cache
+ * has no row for. A failed cache read also falls through, so the cache can
+ * only speed the page up, never blank it.
+ */
export function useMangaDex(manga: AniListMedia | null) {
const title = manga ? englishTitle(manga.title) : "";
return useQuery({
queryKey: ["mangadex", manga?.id ?? null, title],
- queryFn: () =>
- manga === null
- ? disabledQuery()
- : getMangaDexInfoByAniListId(manga.id, title),
+ queryFn: async () => {
+ if (manga === null) return disabledQuery();
+ const snapshot =
+ (await fetchCachedMangaDex(manga.id).catch(() => null)) ??
+ (await getMangaDexSnapshot({
+ client: appMangaDexClient,
+ anilistId: manga.id,
+ title,
+ }));
+ // Covers resolve under the client's covers base, so a web build routes
+ // them through its proxy and a native one reads the CDN directly.
+ return (
+ snapshot &&
+ snapshotToInfo({ snapshot, coversBase: appMangaDexClient.covers })
+ );
+ },
enabled: manga !== null && !!title,
- staleTime: HOUR_MS,
+ staleTime: DAY_MS,
});
}
diff --git a/src/queries/search.test.ts b/src/queries/search.test.ts
index 2e17c38..81aee53 100644
--- a/src/queries/search.test.ts
+++ b/src/queries/search.test.ts
@@ -2,12 +2,18 @@ import { describe, expect, it } from "bun:test";
import { useLatestAnime, useSearch } from "@/queries/search";
import { graphqlRequestMock } from "@test/mocks/graphql";
import { serveCatalog } from "@test/fixtures/catalog";
+import { makeMedia } from "@test/fixtures/media";
import { last, renderHook, settle } from "@test/renderHook";
import type { SplitFilters } from "@/data/genreFilters";
const filters: SplitFilters = { genreNotIn: ["Hentai"], tagNotIn: null };
-const emptyPage = () => Promise.resolve({ Page: { media: [] } });
+// Answers both the latest-anime page and the search request.
+const emptyPage = () =>
+ Promise.resolve({
+ Page: { pageInfo: { hasNextPage: false }, media: [] },
+ search: { media: [] },
+ });
const searchedTerms = (): unknown[] =>
graphqlRequestMock.mock.calls.map(([, variables]) => variables?.query);
@@ -27,6 +33,42 @@ describe("useSearch", () => {
await settle(() => last(captures).isSuccess, "the search to settle");
expect(graphqlRequestMock.mock.calls.at(-1)?.[1]).toEqual({
query: "Attack on Titan",
+ ids: [16498, 53390],
+ hasCatalog: true,
+ genreNotIn: ["Hentai"],
+ tagNotIn: null,
+ });
+ } finally {
+ unmount();
+ }
+ });
+
+ it("leads with catalog series whose title matches the query", async () => {
+ serveCatalog({});
+ const aot = makeMedia({ id: 16498, type: "ANIME" });
+ const other = makeMedia({ id: 55391, type: "MANGA", title: "Attack!!" });
+ graphqlRequestMock.mockImplementation((_doc, variables) =>
+ Promise.resolve(
+ variables?.hasCatalog
+ ? { search: { media: [other] }, catalog: { media: [aot] } }
+ : { search: { media: [other] } },
+ ),
+ );
+ const { captures, unmount } = renderHook(() =>
+ useSearch({ query: "attack", filters, enabled: true }),
+ );
+ try {
+ await settle(
+ () => (last(captures).data ?? []).some((m) => m.id === 16498),
+ "the catalog match",
+ );
+ expect((last(captures).data ?? []).map((m) => m.id)).toEqual([
+ 16498, 55391,
+ ]);
+ expect(graphqlRequestMock.mock.calls.at(-1)?.[1]).toEqual({
+ query: "attack",
+ ids: [16498, 53390],
+ hasCatalog: true,
genreNotIn: ["Hentai"],
tagNotIn: null,
});
@@ -50,6 +92,40 @@ describe("useSearch", () => {
});
describe("useLatestAnime", () => {
+ it("fetches the next page only when asked, and stops at the last", async () => {
+ graphqlRequestMock
+ .mockResolvedValueOnce({
+ Page: {
+ pageInfo: { hasNextPage: true },
+ media: [makeMedia({ id: 1, type: "ANIME" })],
+ },
+ })
+ .mockResolvedValueOnce({
+ Page: {
+ pageInfo: { hasNextPage: false },
+ media: [makeMedia({ id: 2, type: "ANIME" })],
+ },
+ });
+ const { captures, unmount } = renderHook(() =>
+ useLatestAnime({ filters, enabled: true }),
+ );
+ try {
+ await settle(() => last(captures).isSuccess, "the first page");
+ expect(last(captures).hasNextPage).toBe(true);
+ expect(graphqlRequestMock).toHaveBeenCalledTimes(1);
+
+ await last(captures).fetchNextPage();
+ await settle(
+ () => last(captures).data?.pages.length === 2,
+ "the second page",
+ );
+ expect(graphqlRequestMock.mock.calls[1]?.[1]).toMatchObject({ page: 2 });
+ expect(last(captures).hasNextPage).toBe(false);
+ } finally {
+ unmount();
+ }
+ });
+
it("passes the hidden genres through to AniList", async () => {
graphqlRequestMock.mockImplementation(emptyPage);
const { captures, unmount } = renderHook(() =>
@@ -58,6 +134,7 @@ describe("useLatestAnime", () => {
try {
await settle(() => last(captures).isSuccess, "the latest anime");
expect(graphqlRequestMock.mock.calls[0]?.[1]).toEqual({
+ page: 1,
genreNotIn: ["Hentai"],
tagNotIn: null,
});
diff --git a/src/queries/search.ts b/src/queries/search.ts
index fc12558..dd6827b 100644
--- a/src/queries/search.ts
+++ b/src/queries/search.ts
@@ -1,14 +1,21 @@
-import { useQuery } from "@tanstack/react-query";
-import { getLatestAnime, searchMedia } from "@/api/anilist";
+import { useMemo } from "react";
+import { useInfiniteQuery, useQuery } from "@tanstack/react-query";
+import { getLatestAnime, searchWithCatalog } from "@/api/anilist";
+import {
+ catalogMediaIds,
+ matchCatalogTitles,
+ mergeSearchResults,
+} from "@/data/catalogSearch";
import type { SplitFilters } from "@/data/genreFilters";
import { applySearchAlias } from "@/data/searchAliases";
-import { useSearchAliases } from "@/queries/catalog";
-import { HOUR_MS, MINUTE_MS } from "@/queries/shared";
+import { useCatalog, useSearchAliases } from "@/queries/catalog";
+import { HOUR_MS, MINUTE_MS } from "@/data/time";
/**
- * AniList search for `query`, rewritten through the catalog's alias table. The
- * key holds the resolved term, so a search that ran before the aliases loaded
- * is not served again once they have.
+ * AniList search for `query`, rewritten through the catalog's alias table, with
+ * every catalog series whose title matches fetched and placed first. The key
+ * holds the resolved term and the matched ids, so a search that ran before the
+ * catalog loaded is not served again once it has.
*/
export function useSearch({
query,
@@ -20,15 +27,41 @@ export function useSearch({
enabled: boolean;
}) {
const term = applySearchAlias({ query, aliases: useSearchAliases() });
+ const { mappings } = useCatalog();
+ const catalogIds = useMemo(
+ () => catalogMediaIds(matchCatalogTitles({ query: term, mappings })),
+ [term, mappings],
+ );
return useQuery({
- queryKey: ["search", term, filters.genreNotIn, filters.tagNotIn],
- queryFn: () => searchMedia({ query: term, filters }),
+ queryKey: [
+ "search",
+ term,
+ catalogIds,
+ filters.genreNotIn,
+ filters.tagNotIn,
+ ],
+ queryFn: async () => {
+ const { search, catalog } = await searchWithCatalog({
+ query: term,
+ ids: catalogIds,
+ filters,
+ });
+ return mergeSearchResults({
+ ids: catalogIds,
+ catalogMedia: catalog,
+ searchMedia: search,
+ });
+ },
enabled,
staleTime: 5 * MINUTE_MS,
});
}
-/** The newest TV anime, one entry per franchise. */
+/**
+ * The newest TV anime, one entry per franchise, a page at a time for the home
+ * screen's infinite grid. Each page is one AniList request, fetched only when
+ * the reader nears the end of what is loaded.
+ */
export function useLatestAnime({
filters,
enabled,
@@ -36,9 +69,12 @@ export function useLatestAnime({
filters: SplitFilters;
enabled: boolean;
}) {
- return useQuery({
+ return useInfiniteQuery({
queryKey: ["latest-anime", filters.genreNotIn, filters.tagNotIn],
- queryFn: () => getLatestAnime(filters),
+ queryFn: ({ pageParam }) => getLatestAnime({ filters, page: pageParam }),
+ initialPageParam: 1,
+ getNextPageParam: (lastPage, _pages, lastPageParam) =>
+ lastPage.hasNextPage ? lastPageParam + 1 : undefined,
enabled,
staleTime: HOUR_MS,
});
diff --git a/src/queries/shared.test.ts b/src/queries/shared.test.ts
index d96bfa6..2854667 100644
--- a/src/queries/shared.test.ts
+++ b/src/queries/shared.test.ts
@@ -1,5 +1,5 @@
import { describe, expect, it } from "bun:test";
-import { DAY_MS, HOUR_MS, MINUTE_MS, WEEK_MS, disabledQuery } from "./shared";
+import { disabledQuery } from "./shared";
describe("disabledQuery", () => {
// Reaching it means a hook's `enabled` guard and its `queryFn` disagree.
@@ -7,11 +7,3 @@ describe("disabledQuery", () => {
expect(disabledQuery).toThrow("query ran while disabled");
});
});
-
-describe("staleness windows", () => {
- it("build up from one minute", () => {
- expect([MINUTE_MS, HOUR_MS, DAY_MS, WEEK_MS]).toEqual([
- 60_000, 3_600_000, 86_400_000, 604_800_000,
- ]);
- });
-});
diff --git a/src/queries/shared.ts b/src/queries/shared.ts
index 57a02d2..c63850e 100644
--- a/src/queries/shared.ts
+++ b/src/queries/shared.ts
@@ -1,11 +1,6 @@
-// Staleness windows and helpers shared by every query hook. Every `useQuery`
-// in the app lives under `src/queries/`, so its key and cache policy are
-// declared once and in one place.
-
-export const MINUTE_MS = 60 * 1000;
-export const HOUR_MS = 60 * MINUTE_MS;
-export const DAY_MS = 24 * HOUR_MS;
-export const WEEK_MS = 7 * DAY_MS;
+// Helpers shared by every query hook. Every `useQuery` in the app lives under
+// `src/queries/`, so its key and cache policy are declared once and in one
+// place. Staleness windows come from `@/data/time`.
/**
* The `queryFn` branch for a missing input. `enabled` already stops the query
diff --git a/src/state/homeChrome.test.ts b/src/state/homeChrome.test.ts
new file mode 100644
index 0000000..29d8176
--- /dev/null
+++ b/src/state/homeChrome.test.ts
@@ -0,0 +1,40 @@
+import { beforeEach, describe, expect, it } from "bun:test";
+import {
+ IMMERSIVE_ENTER,
+ IMMERSIVE_EXIT,
+ useHomeChrome,
+} from "@/state/homeChrome";
+
+const immersive = () => useHomeChrome.getState().immersive;
+const track = (offset: number) => useHomeChrome.getState().trackOffset(offset);
+
+beforeEach(() => {
+ useHomeChrome.getState().reset();
+});
+
+describe("useHomeChrome", () => {
+ it("starts with the full chrome showing", () => {
+ expect(immersive()).toBe(false);
+ });
+
+ it("enters only past the entry threshold", () => {
+ track(IMMERSIVE_ENTER);
+ expect(immersive()).toBe(false);
+ track(IMMERSIVE_ENTER + 1);
+ expect(immersive()).toBe(true);
+ });
+
+ it("stays immersive until back near the top", () => {
+ track(IMMERSIVE_ENTER + 1);
+ track(IMMERSIVE_ENTER);
+ expect(immersive()).toBe(true);
+ track(IMMERSIVE_EXIT);
+ expect(immersive()).toBe(false);
+ });
+
+ it("resets to the full chrome", () => {
+ track(IMMERSIVE_ENTER + 1);
+ useHomeChrome.getState().reset();
+ expect(immersive()).toBe(false);
+ });
+});
diff --git a/src/state/homeChrome.ts b/src/state/homeChrome.ts
new file mode 100644
index 0000000..8ce5823
--- /dev/null
+++ b/src/state/homeChrome.ts
@@ -0,0 +1,28 @@
+import { create } from "zustand";
+
+/** Scrolled past this, the home screen drops its chrome for the grid. */
+export const IMMERSIVE_ENTER = 48;
+
+/** Back above this, the chrome returns. Lower than the entry point so a
+ * small scroll jitter around one threshold cannot flicker the header. */
+export const IMMERSIVE_EXIT = 8;
+
+type State = {
+ /** The reader is scrolling the home grid: the header shrinks and the
+ * search field and filters give way to the covers. */
+ immersive: boolean;
+ /** Enters or leaves immersive mode for the grid's scroll offset. */
+ trackOffset: (offset: number) => void;
+ /** Leaving the grid restores the full chrome. */
+ reset: () => void;
+};
+
+// Not persisted: every launch opens on the full home screen.
+export const useHomeChrome = create()((set) => ({
+ immersive: false,
+ trackOffset: (offset) =>
+ set(({ immersive }) => ({
+ immersive: immersive ? offset > IMMERSIVE_EXIT : offset > IMMERSIVE_ENTER,
+ })),
+ reset: () => set({ immersive: false }),
+}));
diff --git a/src/types/index.ts b/src/types/index.ts
index 2d5ea8f..e80989f 100644
--- a/src/types/index.ts
+++ b/src/types/index.ts
@@ -128,22 +128,6 @@ export type MangaDexTitle = {
value: string;
};
-export type FranchiseSeason = {
- id: number;
- title: string;
- romajiTitle: string;
- format: string | null;
- episodes: number | null;
- year: number | null;
-};
-
-export type AnimeFranchise = {
- rootId: number;
- seasons: FranchiseSeason[];
- totalTvEpisodes: number;
- tvSeasonCount: number;
-};
-
export type MangaDexInfo = {
titles: MangaDexTitle[];
volumes: number;
diff --git a/src/types/supabase.ts b/src/types/supabase.ts
index 9cd35c3..60cc6b0 100644
--- a/src/types/supabase.ts
+++ b/src/types/supabase.ts
@@ -85,6 +85,45 @@ export type Database = {
};
Relationships: [];
};
+ mangadex_series: {
+ Row: {
+ anilist_manga_id: number;
+ chapters: number;
+ covers: Json;
+ created_at: string;
+ fetched_at: string;
+ id: number;
+ mangadex_id: string;
+ titles: Json;
+ updated_at: string;
+ volumes: number;
+ };
+ Insert: {
+ anilist_manga_id: number;
+ chapters?: number;
+ covers?: Json;
+ created_at?: string;
+ fetched_at?: string;
+ id?: never;
+ mangadex_id: string;
+ titles?: Json;
+ updated_at?: string;
+ volumes?: number;
+ };
+ Update: {
+ anilist_manga_id?: number;
+ chapters?: number;
+ covers?: Json;
+ created_at?: string;
+ fetched_at?: string;
+ id?: never;
+ mangadex_id?: string;
+ titles?: Json;
+ updated_at?: string;
+ volumes?: number;
+ };
+ Relationships: [];
+ };
movies: {
Row: {
after_episode: number | null;
diff --git a/supabase/migrations/20261108120000_mangadex_cache.sql b/supabase/migrations/20261108120000_mangadex_cache.sql
new file mode 100644
index 0000000..608cb56
--- /dev/null
+++ b/supabase/migrations/20261108120000_mangadex_cache.sql
@@ -0,0 +1,37 @@
+-- kasane: MangaDex cache
+--
+-- MangaDex answers a browser User-Agent with a bot challenge, so the web app
+-- reaches it through a same-origin proxy, three to five hops per series page
+-- (title search, cover pages, aggregate). This table holds the result of that
+-- lookup per catalog manga, filled by `scripts/refresh-mangadex.ts` with the
+-- service role and read by the client in one query. A series with no row here
+-- still falls back to the live lookup.
+--
+-- Catalog data: public read-only, written by scripts only. The row is a cache
+-- blob the client always reads whole, so titles and covers are jsonb columns
+-- rather than child tables.
+
+create table public.mangadex_series (
+ id bigint generated always as identity primary key,
+ anilist_manga_id integer not null unique,
+ mangadex_id text not null,
+ -- `[{ "locale": "en", "value": "..." }, ...]`, main titles first.
+ titles jsonb not null default '[]'::jsonb,
+ -- `[{ "volume": "1", "locale": "ja", "fileName": "..." }, ...]`. The file
+ -- sits under `uploads.mangadex.org/covers/{mangadex_id}/`; the client builds
+ -- the sized URL so it can route through its proxy.
+ covers jsonb not null default '[]'::jsonb,
+ -- Counts of what MangaDex hosts, from `/manga/{id}/aggregate`.
+ volumes integer not null default 0,
+ chapters integer not null default 0,
+ fetched_at timestamptz not null default now(),
+ created_at timestamptz not null default now(),
+ updated_at timestamptz not null default now()
+);
+
+alter table public.mangadex_series enable row level security;
+
+create policy "mangadex_series are readable by everyone"
+ on public.mangadex_series for select using (true);
+
+grant select on public.mangadex_series to anon, authenticated;
diff --git a/test/mocks/supabase.ts b/test/mocks/supabase.ts
index c477b91..19bceec 100644
--- a/test/mocks/supabase.ts
+++ b/test/mocks/supabase.ts
@@ -76,6 +76,31 @@ export const tableOf = (rows: unknown[]): SelectBuilder => {
};
};
+type SingleResponse = { data: unknown; error: { message: string } | null };
+
+type SingleBuilder = {
+ select: () => {
+ eq: (
+ column: string,
+ value: unknown,
+ ) => {
+ maybeSingle: () => Promise;
+ };
+ };
+};
+
+/** Query-builder stub for a `select().eq().maybeSingle()` read of one row. */
+export const singleRowOf = (
+ row: unknown,
+ error: { message: string } | null = null,
+): SingleBuilder => ({
+ select: () => ({
+ eq: () => ({
+ maybeSingle: () => Promise.resolve({ data: row, error }),
+ }),
+ }),
+});
+
// Typed loosely on purpose: a test serves whichever table builders the module
// under test reaches for (`tableOf` for catalog reads, richer fakes for sync).
export const fromMock = mock<(table: string) => object>(() => {
diff --git a/tsconfig.json b/tsconfig.json
index ebd1a1d..27d07b9 100644
--- a/tsconfig.json
+++ b/tsconfig.json
@@ -5,6 +5,7 @@
"paths": {
"@/*": ["./src/*"],
"@test/*": ["./test/*"],
+ "@scripts/*": ["./scripts/*"],
"@pkg": ["./package.json"]
},
"types": ["bun", "node"]