Merge branch 'upstream/main' into main
All checks were successful
Build and Push Container Image / build-and-push (push) Successful in 9m21s

This commit is contained in:
2026-06-15 21:37:41 +02:00
150 changed files with 7982 additions and 5572 deletions

View File

@@ -2,15 +2,12 @@ import "./theme";
import "./toast";
import "./htmx";
import "./dropdown";
import "./discover";
import "./anime";
import "./timezone";
import "./search";
import "./sort_filter";
import "./dedupe";
import "./shell";
import "./watchlist";
import "./top_pick_carousel";
import "./continue_watching_carousel";
import "./login";
import "./schedule";

BIN
static/assets/app-icon.png Normal file

Binary file not shown.

After

Width:  |  Height:  |  Size: 80 KiB

View File

@@ -1,18 +0,0 @@
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 100 100" width="100" height="100">
<defs>
<radialGradient id="bg" cx="35%" cy="35%" r="75%">
<stop offset="0%" style="stop-color: var(--accent, #0466c8)" />
<stop offset="100%" style="stop-color: var(--accent-dark, #1d4ed8)" />
</radialGradient>
</defs>
<!-- Background square (for mobile home screen / maskable) -->
<rect width="100" height="100" fill="url(#bg)" />
<!-- Crescent moon cutout -->
<path
d="M70 50a25 25 0 1 1 -25 -25 20 20 0 1 0 25 25z"
fill="#FFF7ED"
transform="translate(-2 -2)"
/>
</svg>

Before

Width:  |  Height:  |  Size: 608 B

View File

@@ -1,18 +0,0 @@
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 100 100" width="100" height="100">
<defs>
<radialGradient id="bg" cx="35%" cy="35%" r="75%">
<stop offset="0%" style="stop-color: var(--accent, #0466c8)" />
<stop offset="100%" style="stop-color: var(--accent-dark, #1d4ed8)" />
</radialGradient>
</defs>
<!-- Background square (for mobile home screen / maskable) -->
<rect width="100" height="100" fill="url(#bg)" />
<!-- Crescent moon cutout -->
<path
d="M70 50a25 25 0 1 1 -25 -25 20 20 0 1 0 25 25z"
fill="#FFF7ED"
transform="translate(-2 -2)"
/>
</svg>

Before

Width:  |  Height:  |  Size: 608 B

Binary file not shown.

After

Width:  |  Height:  |  Size: 7.3 KiB

View File

@@ -1,18 +0,0 @@
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 100 100" width="100" height="100">
<defs>
<radialGradient id="bg" cx="35%" cy="35%" r="75%">
<stop offset="0%" style="stop-color: var(--accent, #0466c8)" />
<stop offset="100%" style="stop-color: var(--accent-dark, #1d4ed8)" />
</radialGradient>
</defs>
<!-- Background square (for mobile home screen / maskable) -->
<rect width="100" height="100" fill="url(#bg)" />
<!-- Crescent moon cutout -->
<path
d="M70 50a25 25 0 1 1 -25 -25 20 20 0 1 0 25 25z"
fill="#FFF7ED"
transform="translate(-2 -2)"
/>
</svg>

Before

Width:  |  Height:  |  Size: 608 B

View File

@@ -1,18 +0,0 @@
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 100 100" width="100" height="100">
<defs>
<radialGradient id="bg" cx="35%" cy="35%" r="75%">
<stop offset="0%" style="stop-color: var(--accent, #0466c8)" />
<stop offset="100%" style="stop-color: var(--accent-dark, #1d4ed8)" />
</radialGradient>
</defs>
<!-- Background square (for mobile home screen / maskable) -->
<rect width="100" height="100" fill="url(#bg)" />
<!-- Crescent moon cutout -->
<path
d="M70 50a25 25 0 1 1 -25 -25 20 20 0 1 0 25 25z"
fill="#FFF7ED"
transform="translate(-2 -2)"
/>
</svg>

Before

Width:  |  Height:  |  Size: 608 B

Binary file not shown.

After

Width:  |  Height:  |  Size: 13 KiB

View File

@@ -1,18 +0,0 @@
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 100 100" width="100" height="100">
<defs>
<radialGradient id="bg" cx="35%" cy="35%" r="75%">
<stop offset="0%" style="stop-color: var(--accent, #0466c8)" />
<stop offset="100%" style="stop-color: var(--accent-dark, #1d4ed8)" />
</radialGradient>
</defs>
<!-- Background square (for mobile home screen / maskable) -->
<rect width="100" height="100" fill="url(#bg)" />
<!-- Crescent moon cutout -->
<path
d="M70 50a25 25 0 1 1 -25 -25 20 20 0 1 0 25 25z"
fill="#FFF7ED"
transform="translate(-2 -2)"
/>
</svg>

Before

Width:  |  Height:  |  Size: 608 B

BIN
static/assets/favicon.png Normal file

Binary file not shown.

After

Width:  |  Height:  |  Size: 113 KiB

View File

@@ -1,23 +0,0 @@
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 100 100" width="100" height="100">
<defs>
<radialGradient id="bg" cx="35%" cy="35%" r="75%">
<stop offset="0%" style="stop-color: var(--accent, #0466c8)" />
<stop offset="100%" style="stop-color: var(--accent-dark, #1d4ed8)" />
</radialGradient>
<clipPath id="clip">
<circle cx="50" cy="50" r="45" />
</clipPath>
</defs>
<!-- Base -->
<circle cx="50" cy="50" r="45" fill="url(#bg)" />
<!-- Crescent moon cutout -->
<g clip-path="url(#clip)">
<path
d="M70 50a25 25 0 1 1 -25 -25 20 20 0 1 0 25 25z"
fill="#FFF7ED"
transform="translate(-2 -2)"
/>
</g>
</svg>

Before

Width:  |  Height:  |  Size: 685 B

BIN
static/assets/logo.png Normal file

Binary file not shown.

After

Width:  |  Height:  |  Size: 392 KiB

View File

@@ -4,19 +4,19 @@
"description": "Personal Anime Watchlist and Discovery",
"start_url": "/",
"display": "standalone",
"background_color": "#0a0a0a",
"theme_color": "#fb923c",
"background_color": "#ffffff",
"theme_color": "#007a85",
"icons": [
{
"src": "/static/assets/app-icon.svg",
"sizes": "any",
"type": "image/svg+xml",
"src": "/static/assets/app-icon.png",
"sizes": "512x512",
"type": "image/png",
"purpose": "any"
},
{
"src": "/static/assets/app-icon.svg",
"sizes": "any",
"type": "image/svg+xml",
"src": "/static/assets/app-icon.png",
"sizes": "512x512",
"type": "image/png",
"purpose": "maskable"
}
]

View File

@@ -1,23 +0,0 @@
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 100 100" width="100" height="100">
<defs>
<radialGradient id="bg" cx="35%" cy="35%" r="75%">
<stop offset="0%" style="stop-color: var(--accent, #0466c8)" />
<stop offset="100%" style="stop-color: var(--accent-dark, #1d4ed8)" />
</radialGradient>
<clipPath id="clip">
<circle cx="50" cy="50" r="45" />
</clipPath>
</defs>
<!-- Base -->
<circle cx="50" cy="50" r="45" fill="url(#bg)" />
<!-- Crescent moon cutout -->
<g clip-path="url(#clip)">
<path
d="M70 50a25 25 0 1 1 -25 -25 20 20 0 1 0 25 25z"
fill="#FFF7ED"
transform="translate(-2 -2)"
/>
</g>
</svg>

Before

Width:  |  Height:  |  Size: 685 B

View File

@@ -1,23 +0,0 @@
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 100 100" width="100" height="100">
<defs>
<radialGradient id="bg" cx="35%" cy="35%" r="75%">
<stop offset="0%" style="stop-color: var(--accent, #0466c8)" />
<stop offset="100%" style="stop-color: var(--accent-dark, #1d4ed8)" />
</radialGradient>
<clipPath id="clip">
<circle cx="50" cy="50" r="45" />
</clipPath>
</defs>
<!-- Base -->
<circle cx="50" cy="50" r="45" fill="url(#bg)" />
<!-- Crescent moon cutout -->
<g clip-path="url(#clip)">
<path
d="M70 50a25 25 0 1 1 -25 -25 20 20 0 1 0 25 25z"
fill="#FFF7ED"
transform="translate(-2 -2)"
/>
</g>
</svg>

Before

Width:  |  Height:  |  Size: 685 B

BIN
static/assets/real_logo.png Normal file

Binary file not shown.

After

Width:  |  Height:  |  Size: 1.9 MiB

View File

@@ -4,57 +4,48 @@
@source "../**/*.ts";
@theme {
--color-background: light-dark(#ffffff, #0b0c10);
--color-background-sidebar: light-dark(#f7f7f7, #0f1115);
--color-background-header: light-dark(#fbfbfb, #0f1115);
--color-background-surface: light-dark(#ffffff, #17181c);
--color-background-button: light-dark(#f5f5f5, #131417);
--color-background-button-hover: light-dark(#ececec, #1c1d22);
--color-foreground: light-dark(#111111, #f3f4f6);
--color-accent: #00b3c4;
--color-background: light-dark(#ffffff, #101113);
--color-background-sidebar: light-dark(#f7f7f7, #161719);
--color-background-header: light-dark(#fbfbfb, #161719);
--color-background-surface: light-dark(#ffffff, #1b1c1f);
--color-background-button: light-dark(#f5f5f5, #202125);
--color-background-button-hover: light-dark(#ececec, #292a2f);
--color-foreground: light-dark(#111111, #f4f1ea);
--color-accent: light-dark(#007a85, #00b3c4);
--color-on-accent: light-dark(#ffffff, #000000);
--color-surface-hover: light-dark(rgba(0, 0, 0, 0.04), rgba(255, 255, 255, 0.05));
}
@layer base {
button,
input,
select,
textarea,
a {
border-radius: 0;
}
}
.scrollbar-hidden {
-ms-overflow-style: none;
scrollbar-width: none;
}
.scrollbar-hidden::-webkit-scrollbar {
display: none;
}
:root {
color-scheme: light dark;
--skeleton-base: light-dark(#e5e5e5, #1f1f1f);
--skeleton-highlight: light-dark(#d4d4d4, #2a2a2a);
--bg: var(--color-background);
--panel: light-dark(#f7f7f7, #181818);
--panel-soft: light-dark(#ececec, #202020);
--header: light-dark(#ffffff, #101010);
--text: light-dark(#111111, #e7e5e4);
--text-muted: light-dark(#666666, #a8a29e);
--text-faint: light-dark(#9a9a9a, #78716c);
--accent: var(--color-accent);
--danger: #dc2626;
--surface-thumb: light-dark(#cccccc, #44403c);
--surface-tab-hover: light-dark(#e4e4e4, #202020);
--surface-tab-active: light-dark(#1e1b17, #fafaf9);
--text-tab-active: light-dark(#fafaf9, #0c0a09);
--surface-select: light-dark(#ffffff, #181818);
--text-on-accent: light-dark(#fafaf9, #0c0a09);
--overlay-subtle: light-dark(rgba(0, 0, 0, 0.04), rgba(255, 255, 255, 0.04));
--border: light-dark(rgba(0, 0, 0, 0.08), rgba(255, 255, 255, 0.07));
--border-light: light-dark(rgba(0, 0, 0, 0.04), rgba(255, 255, 255, 0.035));
--shadow-subtle: light-dark(0 1px 2px rgba(0, 0, 0, 0.04), 0 1px 2px rgba(0, 0, 0, 0.18));
--shadow-card: light-dark(0 2px 8px rgba(0, 0, 0, 0.04), 0 2px 10px rgba(0, 0, 0, 0.28));
--shadow-card-hover: light-dark(0 6px 18px rgba(0, 0, 0, 0.06), 0 6px 20px rgba(0, 0, 0, 0.34));
--scrollbar-track: light-dark(rgba(0, 0, 0, 0.04), rgba(255, 255, 255, 0.05));
--scrollbar-thumb: light-dark(rgba(0, 0, 0, 0.16), rgba(255, 255, 255, 0.2));
--scrollbar-thumb-hover: light-dark(rgba(0, 0, 0, 0.26), rgba(255, 255, 255, 0.3));
--space-1: 0.25rem;
--space-2: 0.5rem;
--space-3: 0.75rem;
--space-4: 1rem;
--space-5: 1.25rem;
--space-6: 1.5rem;
--space-8: 2rem;
--poster-max-height: 360px;
--font: "DM Sans", "Segoe UI", system-ui, sans-serif;
--font-serif: "Newsreader", ui-serif, Georgia, serif;
--font-mono: ui-monospace, "SF Mono", "Geist Mono", "JetBrains Mono", monospace;
--radius: 0px;
--skeleton-base: light-dark(#e5e5e5, #242529);
--skeleton-highlight: light-dark(#d4d4d4, #303137);
--border: light-dark(rgba(0, 0, 0, 0.08), rgba(244, 241, 234, 0.08));
--border-light: light-dark(rgba(0, 0, 0, 0.04), rgba(244, 241, 234, 0.04));
--shadow-card: light-dark(0 2px 8px rgba(0, 0, 0, 0.04), 0 2px 12px rgba(0, 0, 0, 0.32));
--scrollbar-track: light-dark(rgba(0, 0, 0, 0.04), rgba(244, 241, 234, 0.05));
--scrollbar-thumb: light-dark(rgba(0, 0, 0, 0.16), rgba(244, 241, 234, 0.22));
--scrollbar-thumb-hover: light-dark(rgba(0, 0, 0, 0.26), rgba(244, 241, 234, 0.32));
--player-segment: #f5c542;
}
html[data-theme="light"] {
@@ -68,7 +59,7 @@ html[data-theme="dark"] {
html,
body {
background-color: var(--color-background);
color: var(--text);
color: var(--color-foreground);
}
.skeleton {

View File

@@ -1,25 +1,34 @@
import { onHtmxLoad, onReady } from "./utils";
const dedupeWithin = (root: ParentNode): void => {
export const dedupeByID = <T>(items: T[], idForItem: (item: T) => string | undefined): T[] => {
const seen = new Set<string>();
const elements = root.querySelectorAll<HTMLElement>(":scope > [data-id]");
elements.forEach((item) => {
const id = item.dataset.id;
return items.filter((item) => {
const id = idForItem(item);
if (!id) {
return;
return true;
}
if (seen.has(id)) {
item.remove();
return;
return false;
}
seen.add(id);
return true;
});
};
const dedupe = (root: ParentNode = document): void => {
export const dedupeWithin = (root: ParentNode): void => {
const elements = root.querySelectorAll<HTMLElement>(":scope > [data-id]");
const uniqueElements = new Set(dedupeByID(Array.from(elements), (item) => item.dataset.id));
elements.forEach((item) => {
if (!uniqueElements.has(item)) {
item.remove();
}
});
};
export const dedupe = (root: ParentNode = document): void => {
const containers = new Set<ParentNode>();
const elements = root.querySelectorAll<HTMLElement>("[data-id]");

View File

@@ -1,96 +0,0 @@
import { parseClassList } from "./utils";
const setActiveDiscoverTab = (clickedTab: Element): void => {
const group = clickedTab.closest('[data-tab-group="discover"]');
if (!group) {
return;
}
// reset all tabs in group
const triggers = group.querySelectorAll("[data-tab-trigger]");
triggers.forEach((tab) => {
const activeClasses = parseClassList(tab.getAttribute("data-tab-active-classes"));
const inactiveClasses = parseClassList(tab.getAttribute("data-tab-inactive-classes"));
tab.classList.remove(...activeClasses);
tab.classList.add(...inactiveClasses);
});
// mark clicked tab as active
const activeClasses = parseClassList(clickedTab.getAttribute("data-tab-active-classes"));
const inactiveClasses = parseClassList(clickedTab.getAttribute("data-tab-inactive-classes"));
clickedTab.classList.remove(...inactiveClasses);
clickedTab.classList.add(...activeClasses);
};
const onDiscoverTabClick = (event: MouseEvent): void => {
const target = event.target;
if (!(target instanceof Element)) {
return;
}
const trigger = target.closest("[data-tab-trigger]");
if (!trigger) {
return;
}
setActiveDiscoverTab(trigger);
};
const initDiscoverTabs = (): void => {
document.addEventListener("click", onDiscoverTabClick);
};
initDiscoverTabs();
const initSurpriseMe = (): void => {
let isFetchingRandom = false;
const onClick = async (): Promise<void> => {
if (isFetchingRandom) return;
const btn = document.getElementById("surprise-btn") as HTMLButtonElement | null;
if (!btn) return;
isFetchingRandom = true;
const spinner = document.getElementById("surprise-spinner");
const text = document.getElementById("surprise-text");
const icon = document.getElementById("surprise-icon");
btn.disabled = true;
spinner?.classList.remove("hidden");
icon?.classList.add("hidden");
if (text) text.textContent = "Picking…";
try {
const res = await fetch(`/api/jikan/random/anime?t=${Date.now()}`, { cache: "no-store" });
if (!res.ok) throw new Error("Failed to fetch random anime");
const json = (await res.json()) as unknown;
const data = (json as { data?: unknown }).data as { mal_id?: unknown } | undefined;
const malId = typeof data?.mal_id === "number" ? data.mal_id : 0;
if (malId > 0) {
window.location.href = `/anime/${malId}`;
return;
}
throw new Error("Random anime missing mal_id");
} catch (error) {
console.error(error);
alert("Could not pick a random anime right now. Please try again.");
} finally {
isFetchingRandom = false;
btn.disabled = false;
spinner?.classList.add("hidden");
icon?.classList.remove("hidden");
if (text) text.textContent = "Surprise Me";
}
};
document.addEventListener("click", (e) => {
const target = e.target;
if (!(target instanceof Element)) return;
const surprise = target.closest("[data-surprise-me]");
if (!surprise) return;
void onClick();
});
};
initSurpriseMe();

View File

@@ -3,11 +3,12 @@ import type { SkipSegment } from "../types";
import { resolveActiveSegments, renderSegments } from "../skip/segments";
import { updateSubtitleOptions } from "../subtitles";
import { updateQualityOptions } from "../quality";
import { updateModeButtons } from "../mode";
import { hydrateAlternateMode, updateModeButtons } from "../mode";
import { updateOverlay, isAutoplayEnabled, switchEpisodeRange } from "./ui";
import { markEpisodeTransition } from "../progress";
import { safeLocalStorage } from "../storage";
import { completeAnime } from "./complete";
import { loadVideoSource } from "../video";
/**
* Handles video end: either marks complete or loads next episode.
@@ -89,8 +90,9 @@ export const goToNextEpisode = async (): Promise<void> => {
// load new video (keep preferences)
const preferredQuality = safeLocalStorage.getItem("mal:preferred-quality") || "best";
state.video.src = `${state.streamURL}?mode=${encodeURIComponent(fallback)}&token=${encodeURIComponent(state.modeSources[fallback].token)}${preferredQuality !== "best" ? `&quality=${encodeURIComponent(preferredQuality)}` : ""}`;
state.video.load();
const source = state.modeSources[fallback];
const nextSourceURL = `${state.streamURL}?mode=${encodeURIComponent(fallback)}&token=${encodeURIComponent(source.token)}${source.type === "m3u8" ? "&hls=1" : ""}${preferredQuality !== "best" ? `&quality=${encodeURIComponent(preferredQuality)}` : ""}`;
loadVideoSource(nextSourceURL, source.type);
if (!state.video.paused) {
state.video.play().catch(() => undefined);
}
@@ -105,6 +107,7 @@ export const goToNextEpisode = async (): Promise<void> => {
updateQualityOptions();
updateModeButtons();
updateOverlay(state.currentEpisode, data.episode_title ?? "");
void hydrateAlternateMode();
// update skip segments
if (data.segments?.length) {

View File

@@ -5,7 +5,7 @@ import { setupKeyboard } from "./keyboard";
import { setupSubtitles, updateSubtitleOptions, updateSubtitleRender } from "./subtitles";
import { setupSkip, updateSkipButton, updateAutoSkipButton } from "./skip";
import { setupQuality, updateQualityOptions } from "./quality";
import { setupMode, updateModeButtons } from "./mode";
import { hydrateAlternateMode, setupMode, updateModeButtons } from "./mode";
import { setupAutoplayButton, updateEpisodeHighlight, switchEpisodeRange } from "./episodes/ui";
import { goToNextEpisode } from "./episodes/nav";
import { resolveActiveSegments, renderSegments } from "./skip/segments";
@@ -13,6 +13,7 @@ import { setupSegmentEditor } from "./skip/editor";
import { setupThumbnails } from "./episodes/thumbnails";
import { markEpisodeTransition, saveEndedProgress, setupProgress } from "./progress";
import { safeLocalStorage } from "./storage";
import { destroyVideoSource, loadVideoSource } from "./video";
import {
absoluteTimeFromDisplay,
absoluteTimeFromRatio,
@@ -49,6 +50,7 @@ const showPreviewPopover = (): void => {
};
const teardownPlayer = (): void => {
destroyVideoSource();
cleanup?.();
cleanup = null;
currentContainer = null;
@@ -117,7 +119,9 @@ const initPlayer = (): void => {
const preferredQuality = safeLocalStorage.getItem("mal:preferred-quality") || "best";
const streamToken = state.modeSources[state.currentMode]?.token;
if (streamToken) {
state.video.src = `${state.streamURL}?mode=${encodeURIComponent(state.currentMode)}&token=${encodeURIComponent(streamToken)}${preferredQuality !== "best" ? `&quality=${encodeURIComponent(preferredQuality)}` : ""}`;
const source = state.modeSources[state.currentMode];
const url = `${state.streamURL}?mode=${encodeURIComponent(state.currentMode)}&token=${encodeURIComponent(streamToken)}${source?.type === "m3u8" ? "&hls=1" : ""}${preferredQuality !== "best" ? `&quality=${encodeURIComponent(preferredQuality)}` : ""}`;
loadVideoSource(url, source?.type);
}
setupProgress();
@@ -385,6 +389,7 @@ const initPlayer = (): void => {
}
setupThumbnails();
void hydrateAlternateMode(signal);
};
onReady(initPlayer);

View File

@@ -5,6 +5,86 @@ import { updateQualityOptions } from "./quality";
import { safeLocalStorage } from "./storage";
import { streamUrlForMode } from "./source";
import { loadVideoSource } from "./video";
import type { ModeSource } from "./types";
const isRecord = (v: unknown): v is Record<string, unknown> =>
typeof v === "object" && v !== null && !Array.isArray(v);
const isStringArray = (v: unknown): v is string[] =>
Array.isArray(v) && v.every((item) => typeof item === "string");
const isSubtitleItemArray = (v: unknown): v is { lang: string; token: string }[] =>
Array.isArray(v) &&
v.every(
(item) => isRecord(item) && typeof item.lang === "string" && typeof item.token === "string",
);
const parseModeSources = (v: unknown): Record<string, ModeSource> => {
if (!isRecord(v)) return {};
const out: Record<string, ModeSource> = {};
for (const [key, value] of Object.entries(v)) {
if (!isRecord(value)) continue;
if (typeof value.token !== "string" || value.token === "") continue;
const subtitles = value.subtitles == null ? [] : value.subtitles;
if (!isSubtitleItemArray(subtitles)) continue;
const qualities = value.qualities;
out[key] = {
token: value.token,
type: typeof value.type === "string" ? value.type : undefined,
subtitles,
qualities: isStringArray(qualities) ? qualities : undefined,
};
}
return out;
};
const alternateModeFor = (mode: string): "sub" | "dub" | null => {
if (mode === "sub") return "dub";
if (mode === "dub") return "sub";
return null;
};
const mergeAvailableMode = (mode: string): void => {
if (state.availableModes.includes(mode)) return;
state.availableModes = [...state.availableModes, mode].sort();
};
export const hydrateAlternateMode = async (signal?: AbortSignal): Promise<void> => {
const alternateMode = alternateModeFor(state.currentMode);
if (!alternateMode) return;
if (state.modeSources[alternateMode]?.token) return;
try {
const res = await fetch(
`/api/watch/episode/${state.malID}/${encodeURIComponent(state.currentEpisode)}?mode=${encodeURIComponent(alternateMode)}`,
{ signal },
);
if (!res.ok) return;
const data: unknown = await res.json();
if (!isRecord(data)) return;
const sources = parseModeSources(data.mode_sources);
const alternateSource = sources[alternateMode];
if (!alternateSource?.token) return;
state.modeSources = {
...state.modeSources,
[alternateMode]: alternateSource,
};
mergeAvailableMode(alternateMode);
updateSubtitleOptions();
updateQualityOptions();
updateModeButtons();
} catch (error: unknown) {
if (error instanceof DOMException && error.name === "AbortError") return;
}
};
/**
* Switches between sub/dub mode.
@@ -18,7 +98,7 @@ export const switchMode = (mode: string): void => {
"[data-quality-select]",
) as HTMLSelectElement | null;
const url = streamUrlForMode(mode, qualitySelect?.value);
loadVideoSource(url);
loadVideoSource(url, state.modeSources[mode]?.type);
// Fallback: if the media element doesn't actually switch sources (some browsers can get "stuck"),
// reload the page with the desired mode and resume time via sessionStorage.

View File

@@ -11,7 +11,7 @@ export const switchQuality = (quality: string): void => {
const url = streamUrlForMode(state.currentMode, quality);
if (!url) return;
safeLocalStorage.setItem("mal:preferred-quality", quality);
loadVideoSource(url);
loadVideoSource(url, state.modeSources[state.currentMode]?.type);
};
/**

View File

@@ -3,10 +3,16 @@ import { formatTime, showControls } from "../controls";
import { resolveActiveSegments, renderSegments } from "./segments";
type SkipType = "op" | "ed";
type ClosableDropdown = HTMLElement & {
close: (options?: { restoreFocus?: boolean }) => void;
};
const qs = <T extends Element>(root: ParentNode, sel: string): T | null =>
root.querySelector(sel) as T | null;
const isClosableDropdown = (element: Element | null): element is ClosableDropdown =>
element instanceof HTMLElement && "close" in element && typeof element.close === "function";
export const setupSegmentEditor = (): void => {
const root = document.querySelector("[data-segment-editor-root]") as HTMLElement | null;
if (!root) return;
@@ -76,8 +82,16 @@ export const setupSegmentEditor = (): void => {
};
toggleBtn.addEventListener("click", () => {
if (panel.classList.contains("hidden")) open();
else close();
if (!panel.classList.contains("hidden")) {
close();
return;
}
const dropdown = toggleBtn.closest("ui-dropdown");
if (isClosableDropdown(dropdown)) {
dropdown.close({ restoreFocus: false });
}
open();
});
closeBtn?.addEventListener("click", close);
@@ -135,10 +149,10 @@ export const setupSegmentEditor = (): void => {
const v = (btn.getAttribute("data-value") || "ed") as SkipType;
if (typeValue) typeValue.value = v;
if (typeLabel) typeLabel.textContent = v === "op" ? "Opening (OP)" : "Ending (ED)";
// close dropdown popover if it exists
const dropdown = btn.closest("ui-dropdown");
const content = dropdown?.querySelector("[data-content]") as HTMLElement | null;
content?.classList.add("hidden");
if (isClosableDropdown(dropdown)) {
dropdown.close({ restoreFocus: false });
}
showControls();
});
});

View File

@@ -61,14 +61,12 @@ export const renderSegments = (): void => {
const bounds = state.video.duration;
if (bounds <= 0) return;
// create clearly visible colored bars for each segment
state.activeSegments.forEach((s) => {
const bar = document.createElement("div");
// use distinct colors so segments are readable over buffered/progress fills
bar.className = "absolute top-0 h-full opacity-95";
// distinct colors for OP/ED, rendered above buffered/progress fills
const t = (s.type || "").toLowerCase();
bar.style.backgroundColor = t === "ed" ? "#60a5fa" : "#f5c542";
bar.className = "absolute opacity-95";
bar.style.backgroundColor = "var(--player-segment)";
bar.style.top = "-1px";
bar.style.height = "calc(100% + 2px)";
bar.style.left = `${(s.start / bounds) * 100}%`;
bar.style.width = `${((s.end - s.start) / bounds) * 100}%`;
track.appendChild(bar);

View File

@@ -5,6 +5,9 @@ export const streamUrlForMode = (mode: string, quality?: string): string => {
if (!src?.token) return "";
let url = `${state.streamURL}?mode=${encodeURIComponent(mode)}&token=${encodeURIComponent(src.token)}`;
if (src.type === "m3u8") {
url += "&hls=1";
}
if (quality && quality !== "best") {
url += `&quality=${encodeURIComponent(quality)}`;
}

View File

@@ -203,6 +203,7 @@ export const initState = (c: HTMLElement): boolean => {
const qualities = value.qualities;
out[key] = {
token: value.token,
type: typeof value.type === "string" ? value.type : undefined,
subtitles,
qualities: isStringArray(qualities) ? qualities : undefined,
};

View File

@@ -1,6 +1,7 @@
// stream source for a single mode (sub/dub)
export interface ModeSource {
token: string;
type?: string;
subtitles: SubtitleItem[];
qualities?: string[];
}

View File

@@ -1,25 +1,55 @@
import Hls from "hls.js";
import { state } from "./state";
import { absoluteTimeFromDisplay, displayTimeFromAbsolute, invalidateBounds } from "./timeline";
let hls: Hls | null = null;
const destroyHLS = (): void => {
hls?.destroy();
hls = null;
};
export const destroyVideoSource = (): void => {
destroyHLS();
state.video.pause();
state.video.removeAttribute("src");
state.video.load();
};
const shouldUseHLS = (type: string | undefined, url: string): boolean => {
if (type === "m3u8") return true;
try {
const parsed = new URL(url, window.location.href);
if (parsed.searchParams.get("hls") === "1") return true;
return parsed.pathname.toLowerCase().endsWith(".m3u8");
} catch {
return url.toLowerCase().includes(".m3u8");
}
};
/**
* Force-loads a new video source and preserves playback position.
*
* Some browsers can be flaky when switching between HLS URLs while playing.
* Clearing `src` first ensures the media element fully resets before the new URL is set.
*/
export const loadVideoSource = (url: string): void => {
export const loadVideoSource = (url: string, type?: string): void => {
if (!url) return;
const wasPlaying = !state.video.paused;
const prevDisplayTime = displayTimeFromAbsolute(state.video.currentTime);
// Fully reset the element before setting a new source.
state.video.pause();
state.video.removeAttribute("src");
state.video.load();
destroyVideoSource();
state.video.src = url;
state.video.load();
if (shouldUseHLS(type, url) && Hls.isSupported()) {
hls = new Hls();
hls.loadSource(url);
hls.attachMedia(state.video);
} else {
state.video.src = url;
state.video.load();
}
// Try an eager seek; if metadata isn't ready yet, main.ts will restore via pendingSeekTime.
state.pendingSeekTime = prevDisplayTime;

View File

@@ -1,505 +1,3 @@
interface CommandPaletteItem {
id: string;
type: string;
label: string;
subtitle: string;
href: string;
image?: string;
icon?: string;
}
import { initSearchOverlay } from "./search/overlay";
const commandPaletteInitializedKey = Symbol("commandPaletteInitialized");
const globalWindow = window as Window & { [commandPaletteInitializedKey]?: boolean };
const paletteInput = document.getElementById("command-palette-input") as HTMLInputElement | null;
const paletteResults = document.querySelector(
"[data-command-palette-results]",
) as HTMLElement | null;
const paletteDialog = document.querySelector("[data-command-palette-dialog]") as HTMLElement | null;
const paletteRoot = document.querySelector("[data-command-palette-root]") as HTMLElement | null;
const paletteOpenButtons = document.querySelectorAll("[data-command-palette-open]");
const paletteCloseButtons = document.querySelectorAll("[data-command-palette-close]");
const shortcutHints = document.querySelectorAll("[data-command-palette-shortcut]");
let allPaletteItems: CommandPaletteItem[] = [];
let paletteItems: CommandPaletteItem[] = [];
let selectedIndex = 0;
let fetchTimeout: number | undefined;
let lastQuery = "";
let continueExpanded = false;
let activeRequestController: AbortController | undefined;
const responseCache = new Map<string, CommandPaletteItem[]>();
let lastFocusedPaletteOpener: HTMLElement | null = null;
const iconPaths: Record<string, string> = {
bookmark: "M19 21l-7-4-7 4V5a2 2 0 0 1 2-2h10a2 2 0 0 1 2 2v16z",
compass:
"M12 2a10 10 0 1 0 0 20 10 10 0 0 0 0-20z M16.24 7.76l-2.12 6.36-6.36 2.12 2.12-6.36 6.36-2.12z",
play: "M8 5v14l11-7z",
search: "M11 19a8 8 0 1 1 5.65-2.35L21 21 M16.65 16.65 21 21",
trending: "M3 17l6-6 4 4 8-8 M14 7h7v7",
};
const isMac = (): boolean => /Mac|iPhone|iPad|iPod/.test(navigator.platform);
const isSafeImageUrl = (rawUrl?: string): boolean => {
if (!rawUrl || typeof rawUrl !== "string") {
return false;
}
try {
const parsed = new URL(rawUrl, window.location.origin);
return parsed.protocol === "https:" || parsed.protocol === "http:";
} catch {
return false;
}
};
const isTypingTarget = (target: EventTarget | null): boolean =>
target instanceof HTMLInputElement ||
target instanceof HTMLTextAreaElement ||
target instanceof HTMLSelectElement ||
(target instanceof HTMLElement && target.isContentEditable);
const isOpen = (): boolean => paletteDialog?.classList.contains("flex") ?? false;
const setDialogState = (open: boolean): void => {
if (!paletteDialog) return;
paletteDialog.classList.toggle("hidden", !open);
paletteDialog.classList.toggle("flex", open);
paletteDialog.setAttribute("aria-hidden", open ? "false" : "true");
};
const setShortcutHints = (): void => {
shortcutHints.forEach((hint) => {
hint.textContent = isMac() ? "⌘P" : "Ctrl P";
});
};
const clearResults = (): void => {
paletteResults?.replaceChildren();
};
const buildSearchActionItem = (query: string): CommandPaletteItem => ({
id: "search:" + query.toLowerCase(),
type: "search",
label: `Search anime for "${query}"`,
subtitle: "Browse",
href: "/browse?q=" + encodeURIComponent(query),
icon: "search",
});
const buildIcon = (item: CommandPaletteItem): HTMLElement => {
if (isSafeImageUrl(item.image)) {
const img = document.createElement("img");
img.className = "h-11 w-8 shrink-0 bg-background-surface object-cover";
img.src = item.image || "";
img.alt = "";
return img;
}
const icon = document.createElement("div");
icon.className = "flex h-8 w-8 shrink-0 items-center justify-center text-foreground-muted";
const svg = document.createElementNS("http://www.w3.org/2000/svg", "svg");
svg.setAttribute("viewBox", "0 0 24 24");
svg.setAttribute("fill", item.icon === "play" ? "currentColor" : "none");
svg.setAttribute("stroke", "currentColor");
svg.setAttribute("stroke-width", "1.7");
svg.setAttribute("stroke-linecap", "round");
svg.setAttribute("stroke-linejoin", "round");
svg.classList.add("size-5");
const path = document.createElementNS("http://www.w3.org/2000/svg", "path");
path.setAttribute("d", iconPaths[item.icon || "search"] || iconPaths.search);
svg.appendChild(path);
icon.appendChild(svg);
return icon;
};
const buildSvgIcon = (pathData: string, className: string): SVGSVGElement => {
const svg = document.createElementNS("http://www.w3.org/2000/svg", "svg");
svg.setAttribute("viewBox", "0 0 24 24");
svg.setAttribute("fill", "none");
svg.setAttribute("stroke", "currentColor");
svg.setAttribute("stroke-width", "2");
svg.setAttribute("stroke-linecap", "round");
svg.setAttribute("stroke-linejoin", "round");
svg.setAttribute("aria-hidden", "true");
svg.classList.add(...className.split(" "));
const path = document.createElementNS("http://www.w3.org/2000/svg", "path");
path.setAttribute("d", pathData);
svg.appendChild(path);
return svg;
};
const selectItem = (index: number): void => {
if (!paletteResults || paletteItems.length === 0) {
selectedIndex = 0;
return;
}
selectedIndex = Math.max(0, Math.min(index, paletteItems.length - 1));
paletteResults.querySelectorAll<HTMLElement>("[data-command-palette-item]").forEach((row, i) => {
const selected = i === selectedIndex;
row.classList.toggle("bg-surface-hover", selected);
row.setAttribute("aria-selected", String(selected));
if (selected) {
row.scrollIntoView({ block: "nearest" });
}
});
};
const runSelectedItem = (): void => {
const item = paletteItems[selectedIndex];
if (!item) {
return;
}
window.location.href = item.href;
};
const removeContinueWatchingItem = (item: CommandPaletteItem): void => {
const animeID = item.id.replace("continue:", "");
if (!animeID || animeID === item.id) {
return;
}
fetch("/api/continue-watching/" + encodeURIComponent(animeID), { method: "DELETE" })
.then((res: Response) => {
if (!res.ok) {
return;
}
allPaletteItems = allPaletteItems.filter((candidate) => candidate.id !== item.id);
paletteItems = paletteItems.filter((candidate) => candidate.id !== item.id);
responseCache.clear();
removeContinueWatchingCard(animeID);
renderItems(allPaletteItems);
})
.catch((err: unknown) => {
console.error("Continue watching remove error:", err);
});
};
const removeContinueWatchingCard = (animeID: string): void => {
document.getElementById("continue-watching-" + animeID)?.remove();
const section = document.getElementById("continue-watching-section");
if (!section) {
return;
}
if (section.querySelectorAll(".continue-watching-item").length === 0) {
section.remove();
}
};
const buildRow = (item: CommandPaletteItem, index: number): HTMLAnchorElement => {
const row = document.createElement("a");
row.href = item.href;
row.className =
"flex min-h-12 items-center gap-3 px-4 py-2 text-foreground no-underline transition-colors hover:bg-surface-hover hover:no-underline focus-visible:bg-surface-hover focus-visible:outline-none";
row.dataset.commandPaletteItem = item.id;
row.setAttribute("role", "option");
row.setAttribute("aria-selected", String(index === selectedIndex));
row.addEventListener("mouseenter", () => selectItem(index));
row.appendChild(buildIcon(item));
const copy = document.createElement("div");
copy.className = "grid min-w-0 flex-1 gap-0.5";
const label = document.createElement("div");
label.className = "truncate text-sm font-normal text-foreground";
label.textContent = item.label;
copy.appendChild(label);
if (item.subtitle && item.type !== "navigation") {
const subtitle = document.createElement("div");
subtitle.className = "truncate text-xs font-normal text-foreground-muted";
subtitle.textContent = item.subtitle;
copy.appendChild(subtitle);
}
row.appendChild(copy);
if (item.type === "continue") {
const removeButton = document.createElement("button");
removeButton.type = "button";
removeButton.className =
"flex h-8 w-8 shrink-0 items-center justify-center text-red-500/70 transition-colors hover:text-red-500 focus-visible:outline-none focus-visible:ring-1 focus-visible:ring-accent";
removeButton.setAttribute("aria-label", "Remove from Continue Watching");
removeButton.appendChild(buildSvgIcon("M18 6 6 18 M6 6l12 12", "size-4"));
removeButton.addEventListener("click", (event) => {
event.preventDefault();
event.stopPropagation();
removeContinueWatchingItem(item);
});
row.appendChild(removeButton);
} else {
const hint = document.createElement("div");
hint.className = "hidden text-xs text-foreground-muted sm:block";
hint.textContent = index === selectedIndex ? "Enter" : "";
row.appendChild(hint);
}
return row;
};
const buildContinueToggle = (hiddenCount: number): HTMLButtonElement => {
const button = document.createElement("button");
button.type = "button";
button.className =
"flex w-full items-center gap-3 px-4 py-2 text-left text-xs font-normal text-foreground-muted transition-colors hover:bg-surface-hover hover:text-foreground focus-visible:outline-none focus-visible:ring-1 focus-visible:ring-accent";
const spacer = document.createElement("span");
spacer.className = "h-8 w-8 shrink-0";
button.appendChild(spacer);
const label = document.createElement("span");
label.className = "flex-1";
label.textContent = continueExpanded
? "Hide extra continue watching"
: `Show ${hiddenCount} more continue watching`;
button.appendChild(label);
const chevron = buildSvgIcon(continueExpanded ? "m18 15-6-6-6 6" : "m6 9 6 6 6-6", "size-4");
button.appendChild(chevron);
button.addEventListener("click", () => {
continueExpanded = !continueExpanded;
renderItems(allPaletteItems);
});
return button;
};
const visiblePaletteItems = (items: CommandPaletteItem[]): CommandPaletteItem[] => {
if (lastQuery !== "") {
return items;
}
const continueItems = items.filter((item) => item.type === "continue");
if (continueItems.length <= 1 || continueExpanded) {
return items;
}
let firstContinueShown = false;
return items.filter((item) => {
if (item.type !== "continue") {
return true;
}
if (!firstContinueShown) {
firstContinueShown = true;
return true;
}
return false;
});
};
const renderItems = (items: CommandPaletteItem[]): void => {
if (!paletteResults) {
return;
}
allPaletteItems = items;
paletteItems = visiblePaletteItems(items);
selectedIndex = 0;
if (paletteItems.length === 0) {
const empty = document.createElement("div");
empty.className = "px-4 py-8 text-center text-sm font-normal text-foreground-muted";
empty.textContent = "No commands found";
paletteResults.replaceChildren(empty);
return;
}
const list = document.createElement("div");
list.setAttribute("role", "listbox");
list.setAttribute("aria-label", "Command palette results");
paletteItems.forEach((item, index) => {
list.appendChild(buildRow(item, index));
const continueCount = items.filter((candidate) => candidate.type === "continue").length;
if (lastQuery === "" && continueCount > 1 && item.type === "continue" && index === 0) {
list.appendChild(buildContinueToggle(continueCount - 1));
}
});
paletteResults.replaceChildren(list);
selectItem(0);
};
const renderPendingQuery = (query: string): void => {
if (!query) {
return;
}
renderItems([buildSearchActionItem(query)]);
};
const fetchPaletteItems = (query: string): void => {
lastQuery = query;
if (activeRequestController) {
activeRequestController.abort();
activeRequestController = undefined;
}
const cached = responseCache.get(query);
if (cached) {
renderItems(cached);
return;
}
renderPendingQuery(query);
const controller = new AbortController();
activeRequestController = controller;
fetch("/api/command-palette?q=" + encodeURIComponent(query), { signal: controller.signal })
.then((res: Response) => {
if (!res.ok) {
return [];
}
return res.json();
})
.then((items: CommandPaletteItem[]) => {
if (controller.signal.aborted || query !== lastQuery) {
return;
}
activeRequestController = undefined;
responseCache.set(query, items);
renderItems(items);
})
.catch((err: unknown) => {
if (controller.signal.aborted) {
return;
}
activeRequestController = undefined;
console.error("Command palette error:", err);
renderItems([]);
});
};
const scheduleFetch = (): void => {
if (fetchTimeout) {
window.clearTimeout(fetchTimeout);
}
const query = paletteInput?.value.trim() || "";
fetchTimeout = window.setTimeout(() => fetchPaletteItems(query), query.length >= 2 ? 300 : 120);
};
const openPalette = (): void => {
if (!paletteDialog || !paletteInput) {
return;
}
lastFocusedPaletteOpener =
document.activeElement instanceof HTMLElement ? document.activeElement : null;
setDialogState(true);
paletteInput.value = "";
paletteInput.focus();
continueExpanded = false;
fetchPaletteItems("");
};
const closePalette = (): void => {
if (!paletteDialog || !paletteInput) {
return;
}
setDialogState(false);
if (activeRequestController) {
activeRequestController.abort();
activeRequestController = undefined;
}
paletteInput.value = "";
allPaletteItems = [];
paletteItems = [];
continueExpanded = false;
clearResults();
lastFocusedPaletteOpener?.focus();
};
const onDocumentClick = (event: MouseEvent): void => {
if (event.target === paletteDialog) {
closePalette();
}
};
const onInputKeydown = (event: KeyboardEvent): void => {
if (event.key === "ArrowDown") {
event.preventDefault();
selectItem(selectedIndex + 1);
return;
}
if (event.key === "ArrowUp") {
event.preventDefault();
selectItem(selectedIndex - 1);
return;
}
if (event.key === "Enter") {
event.preventDefault();
runSelectedItem();
}
};
const onDocumentKeydown = (event: KeyboardEvent): void => {
const commandShortcut = event.key.toLowerCase() === "p" && (event.metaKey || event.ctrlKey);
if (commandShortcut && !isTypingTarget(event.target)) {
event.preventDefault();
if (isOpen()) {
closePalette();
} else {
openPalette();
}
return;
}
if (event.key === "/" && !isTypingTarget(event.target)) {
event.preventDefault();
openPalette();
return;
}
if (event.key === "Escape" && isOpen()) {
event.preventDefault();
closePalette();
}
};
const initCommandPalette = (): void => {
if (globalWindow[commandPaletteInitializedKey]) {
return;
}
globalWindow[commandPaletteInitializedKey] = true;
if (!paletteInput || !paletteResults || !paletteRoot) {
return;
}
setShortcutHints();
paletteOpenButtons.forEach((button) => {
button.addEventListener("click", openPalette);
});
paletteCloseButtons.forEach((button) => {
button.addEventListener("click", closePalette);
});
paletteInput.addEventListener("input", scheduleFetch);
paletteInput.addEventListener("keydown", onInputKeydown);
document.addEventListener("click", onDocumentClick);
document.addEventListener("keydown", onDocumentKeydown);
paletteDialog?.setAttribute("aria-hidden", "true");
closestFocusable(paletteRoot ?? document.body);
};
initCommandPalette();
import { closestFocusable } from "./utils";
initSearchOverlay();

52
static/search/actions.ts Normal file
View File

@@ -0,0 +1,52 @@
import { state, searchInput, searchDialog } from "./state";
import { setSearchState, setClearButtonState, clearResults } from "./render";
import { cancelScheduledFetch, fetchSearchItems } from "./fetch";
export const openSearch = (): void => {
if (!searchInput) {
window.location.href = "/search";
return;
}
state.lastFocusedSearchOpener =
document.activeElement instanceof HTMLElement ? document.activeElement : null;
if (searchDialog) {
setSearchState(true);
searchInput.value = "";
state.lastQuery = "";
cancelScheduledFetch();
setClearButtonState(false);
clearResults();
}
searchInput.focus();
};
export const closeSearch = (): void => {
if (!searchDialog || !searchInput) {
return;
}
setSearchState(false);
cancelScheduledFetch();
if (state.activeRequestController) {
state.activeRequestController.abort();
state.activeRequestController = undefined;
}
searchInput.value = "";
state.lastQuery = "";
setClearButtonState(false);
clearResults();
state.lastFocusedSearchOpener?.focus();
};
export const clearSearchInput = (): void => {
if (!searchInput) {
return;
}
searchInput.value = "";
searchInput.focus();
cancelScheduledFetch();
setClearButtonState(false);
fetchSearchItems("");
};

192
static/search/fetch.ts Normal file
View File

@@ -0,0 +1,192 @@
import type { CommandPaletteItem, CommandPaletteResponse } from "./state";
import { state, searchInput, searchResults, responseCache } from "./state";
import {
setClearButtonState,
clearResults,
renderEmptyState,
renderItems,
appendItems,
} from "./render";
const parseCommandPaletteResponse = (payload: unknown): CommandPaletteResponse => {
if (Array.isArray(payload)) {
return { items: payload as CommandPaletteItem[], hasNextPage: false };
}
if (
payload &&
typeof payload === "object" &&
Array.isArray((payload as CommandPaletteResponse).items)
) {
const response = payload as CommandPaletteResponse;
return {
items: response.items,
hasNextPage: response.hasNextPage,
nextPage: response.nextPage,
};
}
return { items: [], hasNextPage: false };
};
const visibleSearchItems = (items: CommandPaletteItem[], query: string): CommandPaletteItem[] => {
if (query === "") {
return [];
}
return items.filter((item) => item.type === "anime");
};
const renderPendingQuery = (query: string): void => {
if (!query) {
return;
}
clearResults();
};
export const cancelScheduledFetch = (): void => {
if (!state.fetchTimeout) {
return;
}
window.clearTimeout(state.fetchTimeout);
state.fetchTimeout = undefined;
};
export const fetchSearchItems = (query: string): void => {
state.lastQuery = query;
setClearButtonState(query !== "");
if (state.activeRequestController) {
state.activeRequestController.abort();
state.activeRequestController = undefined;
}
if (query === "") {
clearResults();
renderEmptyState("");
return;
}
const cached = responseCache.get(query);
if (cached) {
state.nextSearchPage = cached.nextPage;
state.hasNextSearchPage = cached.hasNextPage;
renderItems(visibleSearchItems(cached.items, query));
return;
}
renderPendingQuery(query);
const controller = new AbortController();
state.activeRequestController = controller;
fetch("/api/command-palette?q=" + encodeURIComponent(query), { signal: controller.signal })
.then((res: Response) => {
if (!res.ok) {
return { items: [], hasNextPage: false };
}
return res.json();
})
.then((payload: unknown) => {
if (controller.signal.aborted || query !== state.lastQuery) {
return;
}
const response = parseCommandPaletteResponse(payload);
const visibleItems = visibleSearchItems(response.items, query);
state.activeRequestController = undefined;
state.nextSearchPage = response.nextPage;
state.hasNextSearchPage = response.hasNextPage;
responseCache.set(query, response);
renderItems(visibleItems);
})
.catch((err: unknown) => {
if (controller.signal.aborted) {
return;
}
state.activeRequestController = undefined;
console.error("Search overlay error:", err);
renderItems([]);
});
};
export const fetchNextSearchPage = (): void => {
if (
!state.lastQuery ||
!state.hasNextSearchPage ||
!state.nextSearchPage ||
state.isFetchingNextPage
) {
return;
}
state.isFetchingNextPage = true;
const query = state.lastQuery;
const page = state.nextSearchPage;
fetch(
"/api/command-palette?q=" +
encodeURIComponent(query) +
"&page=" +
encodeURIComponent(String(page)),
)
.then((res: Response) => {
if (!res.ok) {
return { items: [], hasNextPage: false };
}
return res.json();
})
.then((payload: unknown) => {
if (query !== state.lastQuery) {
return;
}
const response = parseCommandPaletteResponse(payload);
const visibleItems = visibleSearchItems(response.items, query);
const cached = responseCache.get(query);
if (cached) {
responseCache.set(query, {
items: [...cached.items, ...response.items],
hasNextPage: response.hasNextPage,
nextPage: response.nextPage,
});
}
state.nextSearchPage = response.nextPage;
state.hasNextSearchPage = response.hasNextPage;
appendItems(visibleItems);
})
.catch((err: unknown) => {
console.error("Search overlay pagination error:", err);
})
.finally(() => {
state.isFetchingNextPage = false;
});
};
export const onResultsScroll = (): void => {
if (!searchResults) {
return;
}
const remainingScroll =
searchResults.scrollHeight - searchResults.scrollTop - searchResults.clientHeight;
if (remainingScroll < 480) {
fetchNextSearchPage();
}
};
export const scheduleFetch = (): void => {
if (state.fetchTimeout) {
window.clearTimeout(state.fetchTimeout);
}
const query = searchInput?.value.trim() || "";
setClearButtonState(query !== "");
state.fetchTimeout = window.setTimeout(
() => fetchSearchItems(query),
query.length >= 2 ? 240 : 80,
);
};

113
static/search/overlay.ts Normal file
View File

@@ -0,0 +1,113 @@
import {
state,
commandPaletteInitializedKey,
globalWindow,
searchInput,
searchResults,
searchRoot,
searchPage,
searchOpenButtons,
searchCloseButtons,
searchClearButtons,
searchDialog,
isSearchOpen,
isTypingTarget,
} from "./state";
import { setShortcutHints, selectItem, runSelectedItem, renderEmptyState } from "./render";
import { scheduleFetch, fetchSearchItems, onResultsScroll } from "./fetch";
import { openSearch, closeSearch, clearSearchInput } from "./actions";
const onDocumentClick = (event: MouseEvent): void => {
if (event.target === searchDialog) {
closeSearch();
}
};
const onInputKeydown = (event: KeyboardEvent): void => {
if (event.key === "ArrowDown") {
event.preventDefault();
selectItem(state.selectedIndex + 1, true);
return;
}
if (event.key === "ArrowUp") {
event.preventDefault();
selectItem(state.selectedIndex - 1, true);
return;
}
if (event.key === "Enter") {
event.preventDefault();
runSelectedItem();
}
};
const onDocumentKeydown = (event: KeyboardEvent): void => {
const commandShortcut = event.key.toLowerCase() === "p" && (event.metaKey || event.ctrlKey);
if (commandShortcut && !isTypingTarget(event.target)) {
event.preventDefault();
if (searchPage) {
searchInput?.focus();
} else if (isSearchOpen()) {
closeSearch();
} else {
openSearch();
}
return;
}
if (event.key === "/" && !isTypingTarget(event.target)) {
event.preventDefault();
if (searchPage) {
searchInput?.focus();
} else {
openSearch();
}
return;
}
if (event.key === "Escape" && isSearchOpen()) {
event.preventDefault();
closeSearch();
}
};
export const initSearchOverlay = (): void => {
if (globalWindow[commandPaletteInitializedKey]) {
return;
}
globalWindow[commandPaletteInitializedKey] = true;
if (!searchInput || !searchResults || !searchRoot) {
return;
}
setShortcutHints();
searchOpenButtons.forEach((button) => {
button.addEventListener("click", openSearch);
});
searchCloseButtons.forEach((button) => {
button.addEventListener("click", closeSearch);
});
searchClearButtons.forEach((button) => {
button.addEventListener("click", clearSearchInput);
});
searchInput.addEventListener("input", scheduleFetch);
searchInput.addEventListener("keydown", onInputKeydown);
searchResults.addEventListener("scroll", onResultsScroll);
document.addEventListener("click", onDocumentClick);
document.addEventListener("keydown", onDocumentKeydown);
searchDialog?.setAttribute("aria-hidden", "true");
const initialQuery = new URLSearchParams(window.location.search).get("q")?.trim() || "";
if (initialQuery) {
searchInput.value = initialQuery;
fetchSearchItems(initialQuery);
} else {
renderEmptyState("");
}
if (searchPage) {
searchInput.focus();
}
};

383
static/search/render.ts Normal file
View File

@@ -0,0 +1,383 @@
import { dedupeByID, dedupeWithin } from "../dedupe";
import type { CommandPaletteItem } from "./state";
import {
state,
searchResults,
searchClearButtons,
shortcutHints,
searchDialog,
responseCache,
iconPaths,
typeLabels,
groupOrder,
maxPosterImageRetries,
isSafeImageUrl,
isMac,
} from "./state";
export const setSearchState = (open: boolean): void => {
if (!searchDialog) {
return;
}
searchDialog.classList.toggle("hidden", !open);
searchDialog.classList.toggle("flex", open);
searchDialog.setAttribute("aria-hidden", open ? "false" : "true");
document.body.classList.toggle("overflow-hidden", open);
};
export const setShortcutHints = (): void => {
shortcutHints.forEach((hint) => {
hint.textContent = isMac() ? "⌘P" : "Ctrl P";
});
};
export const setClearButtonState = (hasQuery: boolean): void => {
searchClearButtons.forEach((button) => {
button.classList.toggle("opacity-0", !hasQuery);
button.classList.toggle("pointer-events-none", !hasQuery);
});
};
const buildSvgIcon = (pathData: string, className: string): SVGSVGElement => {
const svg = document.createElementNS("http://www.w3.org/2000/svg", "svg");
svg.setAttribute("viewBox", "0 0 24 24");
svg.setAttribute("fill", "none");
svg.setAttribute("stroke", "currentColor");
svg.setAttribute("stroke-width", "1.8");
svg.setAttribute("stroke-linecap", "round");
svg.setAttribute("stroke-linejoin", "round");
svg.setAttribute("aria-hidden", "true");
svg.classList.add(...className.split(" "));
const path = document.createElementNS("http://www.w3.org/2000/svg", "path");
path.setAttribute("d", pathData);
svg.appendChild(path);
return svg;
};
const buildFallbackIcon = (item: CommandPaletteItem): HTMLElement => {
const icon = document.createElement("div");
icon.className =
"flex aspect-2/3 w-full items-center justify-center bg-background-button text-foreground-muted";
const path = iconPaths[item.icon || "search"] || iconPaths.search;
icon.appendChild(buildSvgIcon(path, "size-7"));
return icon;
};
const buildPosterImage = (item: CommandPaletteItem): HTMLElement => {
if (!isSafeImageUrl(item.image)) {
return buildFallbackIcon(item);
}
const source = item.image || "";
let retries = 0;
const img = document.createElement("img");
img.className = "aspect-2/3 w-full bg-background-button object-cover";
img.alt = "";
img.loading = "lazy";
img.addEventListener("error", () => {
if (retries < maxPosterImageRetries) {
retries += 1;
const retryURL = new URL(source);
retryURL.searchParams.set("_retry", String(retries));
img.src = retryURL.toString();
return;
}
img.replaceWith(buildFallbackIcon(item));
});
img.src = source;
return img;
};
export const clearResults = (): void => {
state.resultItems = [];
state.selectedIndex = 0;
state.nextSearchPage = undefined;
state.hasNextSearchPage = false;
state.isFetchingNextPage = false;
searchResults?.replaceChildren();
};
export const selectItem = (index: number, scrollIntoView: boolean): void => {
if (!searchResults || state.resultItems.length === 0) {
state.selectedIndex = 0;
return;
}
state.selectedIndex = Math.max(0, Math.min(index, state.resultItems.length - 1));
searchResults.querySelectorAll<HTMLElement>("[data-command-palette-item]").forEach((item) => {
const selected = Number(item.dataset.resultIndex) === state.selectedIndex;
item.classList.toggle("opacity-75", selected);
item.setAttribute("aria-selected", String(selected));
if (selected && scrollIntoView) {
item.scrollIntoView({ block: "nearest" });
}
});
};
export const runSelectedItem = (): void => {
const item = state.resultItems[state.selectedIndex];
if (!item) {
return;
}
window.location.href = item.href;
};
const removeContinueWatchingCard = (animeID: string): void => {
document.getElementById("continue-watching-" + animeID)?.remove();
const section = document.getElementById("continue-watching-section");
if (!section) {
return;
}
if (section.querySelectorAll(".continue-watching-item").length === 0) {
section.remove();
}
};
export const removeContinueWatchingItem = (item: CommandPaletteItem): void => {
const animeID = item.id.replace("continue:", "");
if (!animeID || animeID === item.id) {
return;
}
fetch("/api/continue-watching/" + encodeURIComponent(animeID), { method: "DELETE" })
.then((res: Response) => {
if (!res.ok) {
return;
}
responseCache.clear();
removeContinueWatchingCard(animeID);
renderItems(state.resultItems.filter((candidate) => candidate.id !== item.id));
})
.catch((err: unknown) => {
console.error("Continue watching remove error:", err);
});
};
const cleanLabel = (item: CommandPaletteItem): string => {
if (item.type === "continue") {
return item.label.replace(/^Continue watching\s+/i, "");
}
if (item.type === "navigation") {
return item.label.replace(/^Go to\s+/i, "");
}
return item.label;
};
const buildCard = (item: CommandPaletteItem, index: number): HTMLAnchorElement => {
const card = document.createElement("a");
card.href = item.href;
card.className =
"group block min-w-0 text-foreground no-underline transition focus-visible:outline-none hover:no-underline";
card.dataset.commandPaletteItem = item.id;
card.dataset.id = item.id;
card.dataset.resultIndex = String(index);
card.setAttribute("role", "option");
card.setAttribute("aria-selected", String(index === state.selectedIndex));
card.addEventListener("mouseenter", () => selectItem(index, false));
const media = document.createElement("div");
media.className = "relative mb-3 overflow-hidden bg-background-button";
media.appendChild(buildPosterImage(item));
if (item.type === "continue") {
const removeButton = document.createElement("button");
removeButton.type = "button";
removeButton.className =
"absolute right-2 top-2 flex size-8 items-center justify-center bg-black/70 text-white opacity-0 transition hover:bg-black group-hover:opacity-100 focus-visible:opacity-100 focus-visible:outline-none focus-visible:ring-1 focus-visible:ring-accent";
removeButton.setAttribute("aria-label", "Remove from Continue Watching");
removeButton.appendChild(buildSvgIcon("M18 6 6 18 M6 6l12 12", "size-4"));
removeButton.addEventListener("click", (event) => {
event.preventDefault();
event.stopPropagation();
removeContinueWatchingItem(item);
});
media.appendChild(removeButton);
}
card.appendChild(media);
const title = document.createElement("div");
title.className = "line-clamp-2 text-sm font-semibold leading-snug text-foreground";
title.textContent = cleanLabel(item);
card.appendChild(title);
if (item.subtitle) {
const subtitle = document.createElement("div");
subtitle.className = "mt-1 truncate text-xs font-medium text-foreground-muted";
subtitle.textContent = item.subtitle;
card.appendChild(subtitle);
}
return card;
};
const buildCompactItem = (item: CommandPaletteItem, index: number): HTMLAnchorElement => {
const row = document.createElement("a");
row.href = item.href;
row.className =
"group flex min-h-16 items-center gap-3 px-3 py-2 text-foreground no-underline transition hover:bg-surface-hover hover:no-underline focus-visible:outline-none";
row.dataset.commandPaletteItem = item.id;
row.dataset.id = item.id;
row.dataset.resultIndex = String(index);
row.setAttribute("role", "option");
row.setAttribute("aria-selected", String(index === state.selectedIndex));
row.addEventListener("mouseenter", () => selectItem(index, false));
const thumb = document.createElement("div");
thumb.className = "w-11 shrink-0 overflow-hidden";
thumb.appendChild(buildPosterImage(item));
row.appendChild(thumb);
const copy = document.createElement("div");
copy.className = "min-w-0 flex-1";
const title = document.createElement("div");
title.className = "truncate text-sm font-semibold text-foreground";
title.textContent = cleanLabel(item);
copy.appendChild(title);
if (item.subtitle) {
const subtitle = document.createElement("div");
subtitle.className = "mt-0.5 truncate text-xs text-foreground-muted";
subtitle.textContent = item.subtitle;
copy.appendChild(subtitle);
}
row.appendChild(copy);
return row;
};
const buildSection = (
title: string,
items: CommandPaletteItem[],
startIndex: number,
variant: "grid" | "compact",
): HTMLElement => {
const section = document.createElement("section");
section.className = "min-w-0";
const heading = document.createElement("h2");
heading.className = "mb-4 text-base font-bold text-foreground md:text-lg";
heading.textContent = title;
section.appendChild(heading);
const list = document.createElement("div");
list.setAttribute("role", "listbox");
list.setAttribute("aria-label", title);
list.className =
variant === "grid"
? "grid grid-cols-2 gap-x-5 gap-y-7 sm:grid-cols-3 lg:grid-cols-4"
: "grid gap-1 sm:grid-cols-2";
items.forEach((item, itemIndex) => {
const index = startIndex + itemIndex;
list.appendChild(variant === "grid" ? buildCard(item, index) : buildCompactItem(item, index));
});
section.appendChild(list);
return section;
};
export const renderEmptyState = (query: string): void => {
if (!searchResults) {
return;
}
const empty = document.createElement("div");
empty.className =
"mx-auto flex min-h-80 w-full max-w-5xl flex-col justify-center px-5 py-14 text-center md:px-8";
const title = document.createElement("div");
title.className = "text-2xl font-semibold text-foreground";
title.textContent = query ? "No results found" : "Start typing to search your anime";
empty.appendChild(title);
const subtitle = document.createElement("p");
subtitle.className = "mx-auto mt-3 max-w-lg text-sm leading-6 text-foreground-muted";
subtitle.textContent = query
? "Try a shorter title, alternate spelling, or browse the full search results."
: "Search opens title results first, then your watchlist and quick links when they matter.";
empty.appendChild(subtitle);
searchResults.replaceChildren(empty);
};
const groupedItems = (items: CommandPaletteItem[]): Map<string, CommandPaletteItem[]> => {
const groups = new Map<string, CommandPaletteItem[]>();
items.forEach((item) => {
const key = item.type in typeLabels ? item.type : "anime";
const group = groups.get(key) || [];
group.push(item);
groups.set(key, group);
});
return groups;
};
const orderedGroupKeys = (groups: Map<string, CommandPaletteItem[]>): string[] => {
return groupOrder.filter((key) => groups.has(key));
};
export const renderItems = (items: CommandPaletteItem[]): void => {
if (!searchResults) {
return;
}
state.selectedIndex = 0;
if (items.length === 0) {
renderEmptyState(state.lastQuery);
return;
}
const shell = document.createElement("div");
shell.className = "mx-auto w-full max-w-5xl px-5 py-9 md:px-8 md:py-12";
const groups = groupedItems(dedupeByID(items, (item) => item.id));
const keys = orderedGroupKeys(groups);
state.resultItems = keys.flatMap((key) => groups.get(key) || []);
let cursor = 0;
keys.forEach((key) => {
const groupItems = groups.get(key);
if (!groupItems) {
return;
}
const variant = key === "anime" ? "grid" : "compact";
const section = buildSection(typeLabels[key] || "Results", groupItems, cursor, variant);
section.classList.add("mb-12");
shell.appendChild(section);
cursor += groupItems.length;
});
searchResults.replaceChildren(shell);
shell.querySelectorAll<HTMLElement>("[role='listbox']").forEach((list) => dedupeWithin(list));
selectItem(0, false);
};
export const appendItems = (items: CommandPaletteItem[]): void => {
if (!searchResults || items.length === 0) {
return;
}
const existingIDs = new Set(state.resultItems.map((item) => item.id));
const nextItems = dedupeByID(items, (item) => item.id).filter(
(item) => !existingIDs.has(item.id),
);
if (nextItems.length === 0) {
return;
}
renderItems([...state.resultItems, ...nextItems]);
};

91
static/search/state.ts Normal file
View File

@@ -0,0 +1,91 @@
export interface CommandPaletteItem {
id: string;
type: string;
label: string;
subtitle: string;
href: string;
image?: string;
icon?: string;
}
export interface CommandPaletteResponse {
items: CommandPaletteItem[];
hasNextPage: boolean;
nextPage?: number;
}
export const commandPaletteInitializedKey = Symbol("commandPaletteInitialized");
export const globalWindow = window as Window & { [commandPaletteInitializedKey]?: boolean };
export const searchInput = document.getElementById(
"command-palette-input",
) as HTMLInputElement | null;
export const searchResults = document.querySelector(
"[data-command-palette-results]",
) as HTMLElement | null;
export const searchDialog = document.querySelector(
"[data-command-palette-dialog]",
) as HTMLElement | null;
export const searchRoot = document.querySelector(
"[data-command-palette-root]",
) as HTMLElement | null;
export const searchPage = document.querySelector(
"[data-command-palette-page]",
) as HTMLElement | null;
export const searchOpenButtons = document.querySelectorAll("[data-command-palette-open]");
export const searchCloseButtons = document.querySelectorAll("[data-command-palette-close]");
export const searchClearButtons = document.querySelectorAll("[data-command-palette-clear]");
export const shortcutHints = document.querySelectorAll("[data-command-palette-shortcut]");
export const state = {
resultItems: [] as CommandPaletteItem[],
selectedIndex: 0,
fetchTimeout: undefined as number | undefined,
lastQuery: "",
activeRequestController: undefined as AbortController | undefined,
nextSearchPage: undefined as number | undefined,
hasNextSearchPage: false,
isFetchingNextPage: false,
lastFocusedSearchOpener: null as HTMLElement | null,
};
export const responseCache = new Map<string, CommandPaletteResponse>();
export const iconPaths: Record<string, string> = {
bookmark: "M19 21l-7-4-7 4V5a2 2 0 0 1 2-2h10a2 2 0 0 1 2 2v16z",
compass:
"M12 2a10 10 0 1 0 0 20 10 10 0 0 0 0-20z M16.24 7.76l-2.12 6.36-6.36 2.12 2.12-6.36 6.36-2.12z",
play: "M8 5v14l11-7z",
search: "M11 19a8 8 0 1 1 5.65-2.35L21 21 M16.65 16.65 21 21",
trending: "M3 17l6-6 4 4 8-8 M14 7h7v7",
};
export const typeLabels: Record<string, string> = {
anime: "Top results",
};
export const groupOrder = ["anime"];
export const maxPosterImageRetries = 2;
export const isMac = (): boolean => /Mac|iPhone|iPad|iPod/.test(navigator.platform);
export const isTypingTarget = (target: EventTarget | null): boolean =>
target instanceof HTMLInputElement ||
target instanceof HTMLTextAreaElement ||
target instanceof HTMLSelectElement ||
(target instanceof HTMLElement && target.isContentEditable);
export const isSearchOpen = (): boolean => searchDialog?.classList.contains("flex") ?? false;
export const isSafeImageUrl = (rawUrl?: string): boolean => {
if (!rawUrl) {
return false;
}
try {
const parsed = new URL(rawUrl, window.location.origin);
return parsed.protocol === "https:" || parsed.protocol === "http:";
} catch {
return false;
}
};

View File

@@ -1,88 +0,0 @@
export {};
import { onReady } from "./utils";
const isMobileViewport = (): boolean => window.matchMedia("(max-width: 1023px)").matches;
const initSidebarTransitions = (): void => {
requestAnimationFrame(() => {
document.documentElement.classList.add("sidebar-ready");
});
};
const initMobileMenu = (): void => {
const menu = document.getElementById("mobile-menu");
const backdrop = document.getElementById("mobile-menu-backdrop");
const toggle = document.querySelector("[data-mobile-menu-toggle]");
if (!(menu instanceof HTMLElement)) return;
if (!(backdrop instanceof HTMLElement)) return;
if (!(toggle instanceof HTMLElement)) return;
const body = document.body;
let lastFocused: HTMLElement | null = null;
const setOpen = (nextOpen: boolean): void => {
menu.dataset.mobileOpen = nextOpen ? "true" : "false";
backdrop.dataset.mobileOpen = nextOpen ? "true" : "false";
backdrop.classList.toggle("hidden", !nextOpen);
toggle.setAttribute("aria-expanded", nextOpen ? "true" : "false");
body.classList.toggle("overflow-hidden", nextOpen);
};
const openMenu = (): void => {
if (!isMobileViewport()) return;
if (menu.dataset.mobileOpen === "true") return;
lastFocused = document.activeElement instanceof HTMLElement ? document.activeElement : null;
setOpen(true);
const focusTarget = menu.querySelector<HTMLElement>(
'a, button, input, [tabindex]:not([tabindex="-1"])',
);
focusTarget?.focus();
};
const closeMenu = (): void => {
if (menu.dataset.mobileOpen !== "true") return;
setOpen(false);
lastFocused?.focus();
};
toggle.addEventListener("click", () => {
if (menu.dataset.mobileOpen === "true") {
closeMenu();
return;
}
openMenu();
});
backdrop.addEventListener("click", closeMenu);
document.addEventListener("keydown", (event) => {
if (event.key !== "Escape") return;
if (menu.dataset.mobileOpen !== "true") return;
event.preventDefault();
closeMenu();
});
menu.addEventListener("click", (event) => {
const target = event.target;
if (!(target instanceof Element)) return;
if (!target.closest("a, button")) return;
if (!isMobileViewport()) return;
closeMenu();
});
window.addEventListener("resize", () => {
if (!isMobileViewport()) {
setOpen(false);
}
});
};
onReady(() => {
initSidebarTransitions();
initMobileMenu();
});