1033 lines
32 KiB
Vue
1033 lines
32 KiB
Vue
<script setup lang="ts">
|
||
interface Drama {
|
||
id: string | number;
|
||
title: string;
|
||
image: string;
|
||
payType?: string;
|
||
corner?: string;
|
||
locked?: boolean;
|
||
limitedFree?: boolean;
|
||
}
|
||
|
||
interface Section {
|
||
key: string;
|
||
name: string;
|
||
note: string;
|
||
items: Drama[];
|
||
loading: boolean;
|
||
page: number;
|
||
pages: number;
|
||
}
|
||
|
||
interface PageEvent {
|
||
key: string;
|
||
name: string;
|
||
note?: string;
|
||
items?: Drama[];
|
||
done?: boolean;
|
||
page?: number;
|
||
pages?: number;
|
||
}
|
||
|
||
interface CardSlot {
|
||
id: string;
|
||
item: Drama;
|
||
style: { width: string; height: string; transform: string };
|
||
}
|
||
|
||
const props = defineProps<{
|
||
token: string;
|
||
device: object | null;
|
||
apiBase?: string;
|
||
remoteSearch?: boolean;
|
||
}>();
|
||
const apiBase = computed(() => props.apiBase || "/api");
|
||
|
||
const sections = shallowRef<Section[]>([]);
|
||
const expanded = ref<string[]>([]);
|
||
const selected = ref<Set<string>>(new Set());
|
||
const selectedInSection = reactive<Record<string, number>>({});
|
||
const busy = ref(false);
|
||
const stopped = ref(false);
|
||
const error = ref("");
|
||
const query = ref("");
|
||
const searchHint = ref("");
|
||
const flashKey = ref("");
|
||
let catalogAbort: AbortController | null = null;
|
||
let catalogGeneration = 0;
|
||
let searchCursor = 0;
|
||
let lastQuery = "";
|
||
let revealGeneration = 0;
|
||
const flashSerial = ref(0);
|
||
const directory = ref("");
|
||
const starting = ref(false);
|
||
const footError = ref("");
|
||
const coverStatus = reactive<Record<string, "ready" | "failed">>({});
|
||
const coverDone = ref(0);
|
||
const coverTotal = ref(0);
|
||
const scrollTop = ref(0);
|
||
const viewHeight = ref(800);
|
||
const gridWidth = ref(720);
|
||
const gridTops = ref<Record<string, number>>({});
|
||
const emit = defineEmits<{ started: []; play: [Drama] }>();
|
||
const scrollEl = ref<HTMLElement | null>(null);
|
||
const grids = new Map<string, HTMLElement>();
|
||
const gridBinders = new Map<string, (el: unknown) => void>();
|
||
let resizeObserver: ResizeObserver | null = null;
|
||
let measureFrame = 0;
|
||
let flushFrame = 0;
|
||
let pendingPages: PageEvent[] = [];
|
||
let coverQueue: string[] = [];
|
||
const coverQueued = new Set<string>();
|
||
let coverRunning = 0;
|
||
let coverToken = 0;
|
||
const COVER_CONCURRENCY = 2;
|
||
const GRID_GAP = 12;
|
||
const TITLE_HEIGHT = 52;
|
||
const MIN_CARD = 148;
|
||
|
||
function coverOf(image: string) {
|
||
if (!image) return "";
|
||
if (image.startsWith("/api/")) return image;
|
||
if (image.startsWith("http")) return image;
|
||
return `https://apis.raptdrama.com${image.startsWith("/") ? image : `/${image}`}`;
|
||
}
|
||
|
||
function coverState(image: string): "empty" | "loading" | "ready" | "failed" {
|
||
const src = coverOf(image);
|
||
if (!src) return "empty";
|
||
const status = coverStatus[src];
|
||
if (status === "ready" || status === "failed") return status;
|
||
return "loading";
|
||
}
|
||
|
||
function markCover(src: string, ok: boolean) {
|
||
if (!src || coverStatus[src]) return;
|
||
coverStatus[src] = ok ? "ready" : "failed";
|
||
}
|
||
|
||
function onCoverError(event: Event, image: string) {
|
||
const target = event.target;
|
||
if (target instanceof HTMLImageElement && !target.isConnected) return;
|
||
markCover(coverOf(image), false);
|
||
}
|
||
|
||
function resetCovers() {
|
||
coverToken += 1;
|
||
coverQueue = [];
|
||
coverQueued.clear();
|
||
coverRunning = 0;
|
||
coverDone.value = 0;
|
||
coverTotal.value = 0;
|
||
for (const key of Object.keys(coverStatus)) delete coverStatus[key];
|
||
}
|
||
|
||
function enqueueCovers(items: Drama[]) {
|
||
const token = coverToken;
|
||
let added = 0;
|
||
for (const item of items) {
|
||
const src = coverOf(item.image);
|
||
if (!src || coverStatus[src] || coverQueued.has(src)) continue;
|
||
coverQueued.add(src);
|
||
coverQueue.push(src);
|
||
added += 1;
|
||
}
|
||
if (!added) return;
|
||
coverTotal.value += added;
|
||
pumpCovers(token);
|
||
}
|
||
|
||
function pumpCovers(token: number) {
|
||
while (coverRunning < COVER_CONCURRENCY && coverQueue.length) {
|
||
const src = coverQueue.shift();
|
||
if (!src) break;
|
||
coverRunning += 1;
|
||
void prefetchCover(src).then(
|
||
(ok) => settleCover(token, src, ok),
|
||
() => settleCover(token, src, false),
|
||
);
|
||
}
|
||
}
|
||
|
||
async function prefetchCover(src: string) {
|
||
if (src.startsWith("/api/")) {
|
||
const response = await fetch(src);
|
||
if (!response.ok) return false;
|
||
await response.arrayBuffer();
|
||
return true;
|
||
}
|
||
await new Promise<void>((resolve, reject) => {
|
||
const image = new Image();
|
||
image.onload = () => resolve();
|
||
image.onerror = () => reject(new Error("cover"));
|
||
image.src = src;
|
||
});
|
||
return true;
|
||
}
|
||
|
||
function settleCover(token: number, src: string, ok: boolean) {
|
||
if (token !== coverToken) return;
|
||
coverRunning = Math.max(0, coverRunning - 1);
|
||
markCover(src, ok);
|
||
coverDone.value += 1;
|
||
pumpCovers(token);
|
||
}
|
||
|
||
function isExpanded(key: string) {
|
||
return expanded.value.includes(key);
|
||
}
|
||
|
||
function toggleExpanded(key: string) {
|
||
expanded.value = isExpanded(key)
|
||
? expanded.value.filter((item) => item !== key)
|
||
: [...expanded.value, key];
|
||
void nextTick(() => measure());
|
||
}
|
||
|
||
function selectedCount(section: Section) {
|
||
return selectedInSection[section.key] || 0;
|
||
}
|
||
|
||
function syncSelectedCounts() {
|
||
const chosen = selected.value;
|
||
for (const section of sections.value) {
|
||
let count = 0;
|
||
for (const item of section.items) {
|
||
if (chosen.has(dramaKey(item.id))) count += 1;
|
||
}
|
||
selectedInSection[section.key] = count;
|
||
}
|
||
}
|
||
|
||
function allChecked(section: Section) {
|
||
return section.items.length > 0 && selectedCount(section) === section.items.length;
|
||
}
|
||
|
||
function someChecked(section: Section) {
|
||
const count = selectedCount(section);
|
||
return count > 0 && count < section.items.length;
|
||
}
|
||
|
||
function dramaKey(id: string | number) {
|
||
return String(id);
|
||
}
|
||
|
||
function toggleDrama(id: string | number, checked: boolean) {
|
||
const next = new Set(selected.value);
|
||
const key = dramaKey(id);
|
||
if (checked) next.add(key);
|
||
else next.delete(key);
|
||
selected.value = next;
|
||
syncSelectedCounts();
|
||
}
|
||
|
||
function toggleSection(section: Section, checked: boolean) {
|
||
const next = new Set(selected.value);
|
||
for (const item of section.items) {
|
||
const key = dramaKey(item.id);
|
||
if (checked) next.add(key);
|
||
else next.delete(key);
|
||
}
|
||
selected.value = next;
|
||
syncSelectedCounts();
|
||
}
|
||
|
||
function clearSelection() {
|
||
selected.value = new Set();
|
||
syncSelectedCounts();
|
||
}
|
||
|
||
function pruneSelection() {
|
||
const ids = new Set(sections.value.flatMap((section) => section.items.map((item) => dramaKey(item.id))));
|
||
selected.value = new Set([...selected.value].filter((id) => ids.has(id)));
|
||
syncSelectedCounts();
|
||
}
|
||
|
||
function publishSections() {
|
||
sections.value = sections.value.slice();
|
||
}
|
||
|
||
function showOutline(list: { key: string; name: string; note?: string; loading?: boolean }[]) {
|
||
for (const key of Object.keys(selectedInSection)) delete selectedInSection[key];
|
||
sections.value = list.map((item) => ({
|
||
key: item.key,
|
||
name: item.name,
|
||
note: item.note || "",
|
||
items: [],
|
||
loading: item.loading !== false,
|
||
page: 0,
|
||
pages: 0,
|
||
}));
|
||
}
|
||
|
||
function applyPage(event: PageEvent) {
|
||
let section = sections.value.find((item) => item.key === event.key);
|
||
if (!section) {
|
||
section = {
|
||
key: event.key,
|
||
name: event.name,
|
||
note: event.note || "",
|
||
items: [],
|
||
loading: !event.done,
|
||
page: 0,
|
||
pages: 0,
|
||
};
|
||
sections.value.push(section);
|
||
}
|
||
if (event.note) section.note = event.note;
|
||
if (event.page) section.page = event.page;
|
||
if (event.pages) section.pages = event.pages;
|
||
if (event.items?.length) {
|
||
section.items.push(...event.items);
|
||
enqueueCovers(event.items);
|
||
}
|
||
if (event.done) section.loading = false;
|
||
}
|
||
|
||
function scheduleFlush(generation: number) {
|
||
if (flushFrame) return;
|
||
flushFrame = requestAnimationFrame(() => {
|
||
flushFrame = 0;
|
||
if (generation !== catalogGeneration) {
|
||
pendingPages = [];
|
||
return;
|
||
}
|
||
const batch = pendingPages.splice(0, 6);
|
||
const extra: PageEvent[] = [];
|
||
for (const event of batch) {
|
||
const items = event.items || [];
|
||
const chunk = items.slice(0, 180);
|
||
const rest = items.slice(180);
|
||
applyPage({ ...event, items: chunk, done: rest.length ? false : event.done });
|
||
if (rest.length) extra.push({ ...event, items: rest });
|
||
}
|
||
if (extra.length) pendingPages.unshift(...extra);
|
||
publishSections();
|
||
void nextTick(() => measure());
|
||
if (pendingPages.length) scheduleFlush(generation);
|
||
});
|
||
}
|
||
|
||
function queuePage(event: PageEvent, generation: number) {
|
||
if (generation !== catalogGeneration) return;
|
||
pendingPages.push(event);
|
||
scheduleFlush(generation);
|
||
}
|
||
|
||
function waitFrame() {
|
||
return new Promise<void>((resolve) => {
|
||
requestAnimationFrame(() => resolve());
|
||
});
|
||
}
|
||
|
||
function finishSections() {
|
||
for (const section of sections.value) section.loading = false;
|
||
publishSections();
|
||
}
|
||
|
||
function stopLoad() {
|
||
if (!busy.value) return;
|
||
stopped.value = true;
|
||
catalogAbort?.abort();
|
||
finishSections();
|
||
busy.value = false;
|
||
}
|
||
|
||
async function reload(refresh = false) {
|
||
catalogAbort?.abort();
|
||
const current = new AbortController();
|
||
catalogAbort = current;
|
||
const generation = ++catalogGeneration;
|
||
pendingPages = [];
|
||
stopped.value = false;
|
||
error.value = "";
|
||
busy.value = true;
|
||
sections.value = [];
|
||
grids.clear();
|
||
gridBinders.clear();
|
||
resetCovers();
|
||
try {
|
||
const response = await fetch(`${apiBase.value}/catalog`, {
|
||
method: "POST",
|
||
headers: { "Content-Type": "application/json" },
|
||
body: JSON.stringify({ token: props.token, device: props.device, refresh }),
|
||
signal: current.signal,
|
||
});
|
||
if (generation !== catalogGeneration) return;
|
||
if (!response.ok || !response.body) {
|
||
let message = "获取清单失败";
|
||
try {
|
||
const payload = await response.json();
|
||
if (typeof payload.detail === "string") message = payload.detail;
|
||
} catch {
|
||
// 失败响应没有 JSON 时沿用默认提示
|
||
}
|
||
throw new Error(message);
|
||
}
|
||
const reader = response.body.getReader();
|
||
const decoder = new TextDecoder();
|
||
let buffer = "";
|
||
let queued = 0;
|
||
while (true) {
|
||
const { done, value } = await reader.read();
|
||
if (generation !== catalogGeneration) return;
|
||
if (done) break;
|
||
buffer += decoder.decode(value, { stream: true });
|
||
const lines = buffer.split("\n");
|
||
buffer = lines.pop() ?? "";
|
||
for (const line of lines) {
|
||
if (!line.trim() || generation !== catalogGeneration) continue;
|
||
const event = JSON.parse(line);
|
||
if (event.type === "error") throw new Error(event.message || "获取清单失败");
|
||
if (event.type === "outline") {
|
||
showOutline(event.sections || []);
|
||
continue;
|
||
}
|
||
if (event.type === "done") {
|
||
pruneSelection();
|
||
continue;
|
||
}
|
||
if (event.type !== "page") continue;
|
||
queuePage(event, generation);
|
||
queued += 1;
|
||
if (queued >= 6) {
|
||
queued = 0;
|
||
await waitFrame();
|
||
if (generation !== catalogGeneration) return;
|
||
}
|
||
}
|
||
}
|
||
} catch (exc) {
|
||
if (exc instanceof DOMException && exc.name === "AbortError") return;
|
||
if (generation !== catalogGeneration) return;
|
||
error.value = exc instanceof Error ? exc.message : "获取清单失败";
|
||
finishSections();
|
||
} finally {
|
||
if (generation !== catalogGeneration) return;
|
||
let spins = 0;
|
||
while (generation === catalogGeneration && (pendingPages.length || flushFrame) && spins < 600) {
|
||
spins += 1;
|
||
await waitFrame();
|
||
}
|
||
if (generation === catalogGeneration) busy.value = false;
|
||
}
|
||
}
|
||
|
||
function cardKey(sectionKey: string, id: string | number) {
|
||
return `${sectionKey}-${dramaKey(id)}`;
|
||
}
|
||
|
||
function matches() {
|
||
const keyword = query.value.trim().toLowerCase();
|
||
const found: { sectionKey: string; id: string | number }[] = [];
|
||
if (!keyword) return found;
|
||
for (const section of sections.value) {
|
||
for (const item of section.items) {
|
||
if (item.title.toLowerCase().includes(keyword)) {
|
||
found.push({ sectionKey: section.key, id: item.id });
|
||
}
|
||
}
|
||
}
|
||
return found;
|
||
}
|
||
|
||
function clearSearch() {
|
||
searchHint.value = "";
|
||
flashKey.value = "";
|
||
lastQuery = "";
|
||
searchCursor = 0;
|
||
}
|
||
|
||
function finishFlash(key: string, serial: number, event: AnimationEvent) {
|
||
if (event.animationName !== "drama-flash") return;
|
||
if (flashKey.value === key && flashSerial.value === serial) flashKey.value = "";
|
||
}
|
||
|
||
function layoutOf(section: Section) {
|
||
const width = Math.max(MIN_CARD, gridWidth.value);
|
||
const cols = Math.max(1, Math.floor((width + GRID_GAP) / (MIN_CARD + GRID_GAP)));
|
||
const cardWidth = (width - GRID_GAP * (cols - 1)) / cols;
|
||
const cardHeight = cardWidth * 4 / 3 + TITLE_HEIGHT;
|
||
const rowHeight = cardHeight + GRID_GAP;
|
||
const rows = section.items.length ? Math.ceil(section.items.length / cols) : 0;
|
||
const height = rows ? rows * rowHeight - GRID_GAP : 0;
|
||
return { cols, cardWidth, cardHeight, rowHeight, height };
|
||
}
|
||
|
||
function visibleSlots(section: Section): CardSlot[] {
|
||
const box = layoutOf(section);
|
||
const count = section.items.length;
|
||
if (!count) return [];
|
||
const gridTop = gridTops.value[section.key] ?? 0;
|
||
const top = scrollTop.value;
|
||
const bottom = top + Math.max(viewHeight.value, 1);
|
||
let startRow = Math.floor((top - gridTop) / box.rowHeight) - 1;
|
||
let endRow = Math.ceil((bottom - gridTop) / box.rowHeight) + 1;
|
||
const rowCount = Math.ceil(count / box.cols);
|
||
if (endRow < 0 || startRow >= rowCount) return [];
|
||
startRow = Math.max(0, startRow);
|
||
endRow = Math.min(rowCount, Math.max(startRow + 1, endRow));
|
||
const start = startRow * box.cols;
|
||
const end = Math.min(count, endRow * box.cols);
|
||
const slots: CardSlot[] = [];
|
||
for (let index = start; index < end; index += 1) {
|
||
const item = section.items[index];
|
||
const col = index % box.cols;
|
||
const row = Math.floor(index / box.cols);
|
||
slots.push({
|
||
id: dramaKey(item.id),
|
||
item,
|
||
style: {
|
||
width: `${box.cardWidth}px`,
|
||
height: `${box.cardHeight}px`,
|
||
transform: `translate(${col * (box.cardWidth + GRID_GAP)}px, ${row * box.rowHeight}px)`,
|
||
},
|
||
});
|
||
}
|
||
return slots;
|
||
}
|
||
|
||
function bindGrid(key: string, el: unknown) {
|
||
if (el instanceof HTMLElement) grids.set(key, el);
|
||
else grids.delete(key);
|
||
}
|
||
|
||
function gridBinder(key: string) {
|
||
let binder = gridBinders.get(key);
|
||
if (!binder) {
|
||
binder = (el: unknown) => bindGrid(key, el);
|
||
gridBinders.set(key, binder);
|
||
}
|
||
return binder;
|
||
}
|
||
|
||
function measure() {
|
||
const scroller = scrollEl.value;
|
||
if (!scroller) return;
|
||
const nextTop = scroller.scrollTop;
|
||
const nextHeight = scroller.clientHeight || viewHeight.value;
|
||
let nextWidth = 0;
|
||
const tops: Record<string, number> = {};
|
||
const scrollRect = scroller.getBoundingClientRect();
|
||
for (const [key, el] of grids) {
|
||
const rect = el.getBoundingClientRect();
|
||
tops[key] = nextTop + rect.top - scrollRect.top;
|
||
if (el.clientWidth > 0) nextWidth = el.clientWidth;
|
||
}
|
||
if (!nextWidth) nextWidth = Math.max(MIN_CARD, scroller.clientWidth - 80);
|
||
scrollTop.value = nextTop;
|
||
viewHeight.value = nextHeight;
|
||
if (nextWidth !== gridWidth.value) gridWidth.value = nextWidth;
|
||
gridTops.value = tops;
|
||
}
|
||
|
||
function onScroll() {
|
||
if (measureFrame) return;
|
||
measureFrame = requestAnimationFrame(() => {
|
||
measureFrame = 0;
|
||
measure();
|
||
});
|
||
}
|
||
|
||
function scrollIndexIntoView(sectionKey: string, index: number) {
|
||
const section = sections.value.find((item) => item.key === sectionKey);
|
||
const scroller = scrollEl.value;
|
||
if (!section || !scroller || index < 0) return;
|
||
const box = layoutOf(section);
|
||
const row = Math.floor(index / box.cols);
|
||
const top = (gridTops.value[sectionKey] ?? 0) + row * box.rowHeight;
|
||
scroller.scrollTop = Math.max(0, top - 72);
|
||
measure();
|
||
}
|
||
|
||
async function find(keyword = query.value) {
|
||
const generation = ++revealGeneration;
|
||
const text = keyword.trim();
|
||
query.value = text;
|
||
if (!text) {
|
||
searchHint.value = "请输入名称";
|
||
return;
|
||
}
|
||
let found = matches();
|
||
if (!found.length && props.remoteSearch) {
|
||
await searchRemote(text, generation);
|
||
if (generation !== revealGeneration) return;
|
||
found = matches();
|
||
}
|
||
if (!found.length) {
|
||
searchHint.value = "没有找到";
|
||
flashKey.value = "";
|
||
return;
|
||
}
|
||
if (text.toLowerCase() !== lastQuery) {
|
||
lastQuery = text.toLowerCase();
|
||
searchCursor = 0;
|
||
} else {
|
||
searchCursor = (searchCursor + 1) % found.length;
|
||
}
|
||
const hit = found[searchCursor];
|
||
const key = cardKey(hit.sectionKey, hit.id);
|
||
searchHint.value = found.length > 1 ? `${searchCursor + 1}/${found.length}` : "";
|
||
flashKey.value = "";
|
||
if (!isExpanded(hit.sectionKey)) {
|
||
expanded.value = [...expanded.value, hit.sectionKey];
|
||
}
|
||
await nextTick();
|
||
if (generation !== revealGeneration) return;
|
||
measure();
|
||
const section = sections.value.find((item) => item.key === hit.sectionKey);
|
||
const index = section?.items.findIndex((item) => dramaKey(item.id) === dramaKey(hit.id)) ?? -1;
|
||
scrollIndexIntoView(hit.sectionKey, index);
|
||
await nextTick();
|
||
if (generation !== revealGeneration) return;
|
||
flashSerial.value += 1;
|
||
flashKey.value = "";
|
||
await nextTick();
|
||
if (generation !== revealGeneration) return;
|
||
flashKey.value = key;
|
||
}
|
||
const loadedCount = computed(() =>
|
||
sections.value.reduce((sum, section) => sum + (section.key === "search" ? 0 : section.items.length), 0),
|
||
);
|
||
const coverPending = computed(() => coverTotal.value > 0 && coverDone.value < coverTotal.value);
|
||
const showProgress = computed(() => busy.value || stopped.value || coverPending.value);
|
||
const progress = computed(() => {
|
||
if (!busy.value && coverPending.value && coverTotal.value) {
|
||
return Math.min(100, Math.round((coverDone.value / coverTotal.value) * 100));
|
||
}
|
||
let got = 0;
|
||
let total = 0;
|
||
for (const section of sections.value) {
|
||
if (!section.pages || section.key === "search") continue;
|
||
total += section.pages;
|
||
got += section.loading ? Math.min(section.page, section.pages) : section.pages;
|
||
}
|
||
if (!total) return busy.value ? 0 : 100;
|
||
return Math.min(100, Math.round((got / total) * 100));
|
||
});
|
||
const progressText = computed(() => {
|
||
const count = loadedCount.value;
|
||
if (busy.value) return `已加载 ${count} 部`;
|
||
if (stopped.value && coverPending.value) {
|
||
return `已停止,共 ${count} 部,封面 ${coverDone.value}/${coverTotal.value}`;
|
||
}
|
||
if (stopped.value) return `已停止,共 ${count} 部`;
|
||
if (coverPending.value) return `封面 ${coverDone.value}/${coverTotal.value}`;
|
||
return "";
|
||
});
|
||
|
||
onMounted(() => {
|
||
void reload();
|
||
void loadDirectory();
|
||
resizeObserver = new ResizeObserver(() => onScroll());
|
||
if (scrollEl.value) resizeObserver.observe(scrollEl.value);
|
||
measure();
|
||
});
|
||
onBeforeUnmount(() => {
|
||
catalogGeneration += 1;
|
||
coverToken += 1;
|
||
pendingPages = [];
|
||
catalogAbort?.abort();
|
||
resizeObserver?.disconnect();
|
||
if (measureFrame) cancelAnimationFrame(measureFrame);
|
||
if (flushFrame) cancelAnimationFrame(flushFrame);
|
||
});
|
||
defineExpose({ reload, busy, stopLoad, showProgress, progress, progressText, find, searchHint, clearSearch, loadDirectory });
|
||
|
||
async function searchRemote(keyword: string, generation: number) {
|
||
searchHint.value = "正在搜索";
|
||
try {
|
||
const response = await fetch(`${apiBase.value}/search`, {
|
||
method: "POST",
|
||
headers: { "Content-Type": "application/json" },
|
||
body: JSON.stringify({ token: props.token, device: props.device, keyword }),
|
||
});
|
||
const payload = await response.json().catch(() => ({}));
|
||
if (generation !== revealGeneration) return;
|
||
if (!response.ok) {
|
||
searchHint.value = typeof payload.detail === "string" ? payload.detail : "搜索失败";
|
||
return;
|
||
}
|
||
const items = Array.isArray(payload.items) ? payload.items : [];
|
||
const key = "search";
|
||
const existing = sections.value.find((section) => section.key === key);
|
||
if (existing) {
|
||
existing.items = items;
|
||
existing.loading = false;
|
||
existing.note = items.length ? "" : "没有搜索结果";
|
||
} else {
|
||
sections.value.unshift({
|
||
key,
|
||
name: "搜索结果",
|
||
note: items.length ? "" : "没有搜索结果",
|
||
items,
|
||
loading: false,
|
||
page: 0,
|
||
pages: 0,
|
||
});
|
||
}
|
||
enqueueCovers(items);
|
||
publishSections();
|
||
syncSelectedCounts();
|
||
if (!isExpanded(key)) expanded.value = [...expanded.value, key];
|
||
void nextTick(() => measure());
|
||
} catch {
|
||
if (generation === revealGeneration) searchHint.value = "搜索失败";
|
||
}
|
||
}
|
||
|
||
async function loadDirectory() {
|
||
const response = await fetch(`${apiBase.value}/downloads`);
|
||
if (!response.ok) return;
|
||
const payload = await response.json();
|
||
directory.value = payload.directory || "";
|
||
}
|
||
|
||
async function chooseDirectory() {
|
||
footError.value = "";
|
||
const response = await fetch(`${apiBase.value}/downloads/pick`, { method: "POST" });
|
||
if (!response.ok) {
|
||
const payload = await response.json().catch(() => ({}));
|
||
const detail = typeof payload.detail === "string" ? payload.detail : "";
|
||
if (detail) footError.value = detail;
|
||
return;
|
||
}
|
||
const payload = await response.json();
|
||
if (payload.directory) directory.value = payload.directory;
|
||
}
|
||
|
||
async function startDownload() {
|
||
const seen = new Set<string>();
|
||
const items: { id: string; title: string; image: string }[] = [];
|
||
for (const section of sections.value) {
|
||
for (const item of section.items) {
|
||
const key = dramaKey(item.id);
|
||
if (!selected.value.has(key) || seen.has(key)) continue;
|
||
seen.add(key);
|
||
items.push({ id: key, title: item.title, image: item.image });
|
||
}
|
||
}
|
||
if (!items.length) return;
|
||
starting.value = true;
|
||
footError.value = "";
|
||
try {
|
||
const response = await fetch(`${apiBase.value}/downloads`, {
|
||
method: "POST",
|
||
headers: { "Content-Type": "application/json" },
|
||
body: JSON.stringify({ token: props.token, device: props.device, items }),
|
||
});
|
||
const payload = await response.json();
|
||
if (!response.ok) {
|
||
throw new Error(typeof payload.detail === "string" ? payload.detail : "加入下载失败");
|
||
}
|
||
emit("started");
|
||
} catch (exc) {
|
||
footError.value = exc instanceof Error ? exc.message : "加入下载失败";
|
||
} finally {
|
||
starting.value = false;
|
||
}
|
||
}
|
||
</script>
|
||
|
||
<template>
|
||
<div class="download-page">
|
||
<div v-if="showProgress" class="load-strip">
|
||
<n-progress
|
||
class="load-strip-bar"
|
||
type="line"
|
||
:percentage="progress"
|
||
:show-indicator="false"
|
||
:processing="busy || coverPending"
|
||
:height="8"
|
||
/>
|
||
<n-text class="load-strip-text" depth="3">{{ progressText }}</n-text>
|
||
<n-tooltip v-if="busy">
|
||
<template #trigger>
|
||
<n-button size="small" secondary @click="stopLoad">停止</n-button>
|
||
</template>
|
||
停止后不再获取新剧目,已拿到的封面会继续加载
|
||
</n-tooltip>
|
||
</div>
|
||
<div class="download-body">
|
||
<div ref="scrollEl" class="download-scroll" @scroll="onScroll">
|
||
<n-alert v-if="error" class="catalog-error" type="error" :show-icon="false">{{ error }}</n-alert>
|
||
<section v-for="section in sections" :key="section.key" class="category">
|
||
<div class="category-bar">
|
||
<n-tooltip placement="top">
|
||
<template #trigger>
|
||
<n-button quaternary circle :aria-label="isExpanded(section.key) ? '收起' : '展开'" @click="toggleExpanded(section.key)">
|
||
<span class="chevron" :class="{ open: isExpanded(section.key) }">▸</span>
|
||
</n-button>
|
||
</template>
|
||
{{ isExpanded(section.key) ? "收起" : "展开" }}
|
||
</n-tooltip>
|
||
<n-text strong>{{ section.name }}</n-text>
|
||
<n-text depth="3">{{ section.items.length }} 部</n-text>
|
||
<n-text depth="3">已选 {{ selectedCount(section) }}</n-text>
|
||
<span class="bar-gap"></span>
|
||
<span v-if="section.loading" class="category-spin" aria-label="正在加载"></span>
|
||
<n-tooltip placement="top">
|
||
<template #trigger>
|
||
<n-checkbox
|
||
:checked="allChecked(section)"
|
||
:indeterminate="someChecked(section)"
|
||
:disabled="section.loading || section.items.length === 0"
|
||
@update:checked="toggleSection(section, $event)"
|
||
>
|
||
{{ section.loading ? "加载中" : allChecked(section) ? "取消全选" : "全选" }}
|
||
</n-checkbox>
|
||
</template>
|
||
{{ section.loading ? "这一栏还在加载" : allChecked(section) ? "取消全选" : "全选" }}
|
||
</n-tooltip>
|
||
</div>
|
||
<div v-if="isExpanded(section.key)" class="category-body">
|
||
<n-text v-if="section.note" depth="3">{{ section.note }}</n-text>
|
||
<n-text v-else-if="!section.loading && section.items.length === 0" depth="3">暂无剧集</n-text>
|
||
<div
|
||
v-else
|
||
class="drama-grid"
|
||
:style="{ height: `${layoutOf(section).height}px` }"
|
||
:ref="gridBinder(section.key)"
|
||
>
|
||
<article
|
||
v-for="slot in visibleSlots(section)"
|
||
:key="slot.id"
|
||
class="drama-card"
|
||
:data-card="cardKey(section.key, slot.item.id)"
|
||
:style="slot.style"
|
||
@click="toggleDrama(slot.item.id, !selected.has(dramaKey(slot.item.id)))"
|
||
>
|
||
<div class="cover" :class="coverState(slot.item.image)">
|
||
<span v-if="coverState(slot.item.image) === 'loading'" class="cover-spin" aria-hidden="true"></span>
|
||
<img
|
||
v-if="coverOf(slot.item.image)"
|
||
:src="coverOf(slot.item.image)"
|
||
:alt="slot.item.title"
|
||
decoding="async"
|
||
@load="markCover(coverOf(slot.item.image), true)"
|
||
@error="onCoverError($event, slot.item.image)"
|
||
/>
|
||
<span v-if="slot.item.corner || slot.item.locked || slot.item.limitedFree" class="cover-tag">{{ slot.item.corner || (slot.item.limitedFree ? "限免" : slot.item.payType || "付费") }}</span>
|
||
<div v-if="coverState(slot.item.image) !== 'loading'" class="cover-play-layer">
|
||
<n-tooltip placement="top">
|
||
<template #trigger>
|
||
<button type="button" class="cover-play" aria-label="播放" @click.stop="emit('play', slot.item)">
|
||
<svg viewBox="0 0 24 24" aria-hidden="true"><path fill="currentColor" d="M9 7.5v9l8-4.5z" /></svg>
|
||
</button>
|
||
</template>
|
||
播放
|
||
</n-tooltip>
|
||
</div>
|
||
</div>
|
||
<div class="pick" @click.stop>
|
||
<n-tooltip placement="left">
|
||
<template #trigger>
|
||
<n-checkbox :checked="selected.has(dramaKey(slot.item.id))" @update:checked="toggleDrama(slot.item.id, $event)" />
|
||
</template>
|
||
{{ selected.has(dramaKey(slot.item.id)) ? "取消选择" : "选择" }}
|
||
</n-tooltip>
|
||
</div>
|
||
<div class="drama-title">{{ slot.item.title }}</div>
|
||
<div
|
||
v-if="flashKey === cardKey(section.key, slot.item.id)"
|
||
:key="flashSerial"
|
||
class="drama-mask"
|
||
@animationend="finishFlash(cardKey(section.key, slot.item.id), flashSerial, $event)"
|
||
></div>
|
||
</article>
|
||
</div>
|
||
</div>
|
||
</section>
|
||
</div>
|
||
</div>
|
||
<footer class="download-foot">
|
||
<div class="foot-selected">
|
||
<n-text>已选 {{ selected.size }} 部</n-text>
|
||
<n-button secondary size="small" :disabled="selected.size === 0" @click="clearSelection">取消选择</n-button>
|
||
</div>
|
||
<div class="foot-actions">
|
||
<n-text class="foot-dir" depth="3" :title="directory">{{ directory || "未设置下载目录" }}</n-text>
|
||
<n-button secondary size="small" @click="chooseDirectory">选择</n-button>
|
||
<n-button type="primary" size="small" :disabled="selected.size === 0" :loading="starting" @click="startDownload">下载</n-button>
|
||
</div>
|
||
</footer>
|
||
<n-text v-if="footError" class="foot-error" type="error">{{ footError }}</n-text>
|
||
</div>
|
||
</template>
|
||
|
||
<style>
|
||
.download-page { height: 100%; min-height: 0; display: flex; flex-direction: column; overflow: hidden; }
|
||
.load-strip {
|
||
flex: none;
|
||
display: flex;
|
||
align-items: center;
|
||
gap: 12px;
|
||
min-height: 44px;
|
||
padding: 8px 20px;
|
||
border-bottom: 1px solid rgba(255, 255, 255, 0.08);
|
||
background: #18181c;
|
||
}
|
||
.load-strip-bar { width: 180px; flex: none; }
|
||
.load-strip-text { flex: 1; min-width: 0; }
|
||
.download-body { position: relative; flex: 1; min-height: 0; display: flex; flex-direction: column; overflow: hidden; }
|
||
.download-scroll { flex: 1; min-height: 0; overflow: auto; padding: 0 0 12px; }
|
||
.download-foot {
|
||
position: relative;
|
||
z-index: 2;
|
||
flex: none;
|
||
display: flex;
|
||
align-items: center;
|
||
justify-content: space-between;
|
||
gap: 12px;
|
||
padding: 12px 20px;
|
||
border-top: 1px solid rgba(255, 255, 255, 0.12);
|
||
background: #18181c;
|
||
}
|
||
.foot-actions { display: flex; align-items: center; gap: 8px; min-width: 0; }
|
||
.foot-selected { display: flex; align-items: center; gap: 8px; flex: none; }
|
||
.foot-dir { max-width: 420px; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }
|
||
.foot-error { display: block; padding: 0 20px 8px; text-align: right; }
|
||
.catalog-error { margin: 8px 20px 12px; }
|
||
.category { margin-bottom: 8px; }
|
||
.category-bar {
|
||
position: sticky;
|
||
top: 0;
|
||
z-index: 3;
|
||
display: flex;
|
||
align-items: center;
|
||
gap: 8px;
|
||
min-height: 44px;
|
||
padding: 0 20px;
|
||
background: #101014;
|
||
border-bottom: 1px solid rgba(255, 255, 255, 0.08);
|
||
}
|
||
.category-spin {
|
||
width: 14px;
|
||
height: 14px;
|
||
flex: none;
|
||
border-radius: 50%;
|
||
border: 2px solid rgba(99, 226, 183, 0.28);
|
||
border-top-color: #63e2b7;
|
||
animation: category-spin 0.7s linear infinite;
|
||
}
|
||
@keyframes category-spin { to { transform: rotate(360deg); } }
|
||
.bar-gap { flex: 1; }
|
||
.chevron { display: inline-block; transition: transform 0.15s ease; }
|
||
.chevron.open { transform: rotate(90deg); }
|
||
.category-body { padding: 8px 20px 12px 60px; }
|
||
.drama-grid {
|
||
position: relative;
|
||
width: 100%;
|
||
}
|
||
.drama-card {
|
||
position: absolute;
|
||
top: 0;
|
||
left: 0;
|
||
display: flex;
|
||
flex-direction: column;
|
||
border-radius: 8px;
|
||
overflow: hidden;
|
||
background: rgba(255, 255, 255, 0.04);
|
||
cursor: pointer;
|
||
}
|
||
.cover {
|
||
position: relative;
|
||
flex: 1;
|
||
min-height: 0;
|
||
display: flex;
|
||
align-items: center;
|
||
justify-content: center;
|
||
background: transparent;
|
||
}
|
||
.cover-spin {
|
||
width: 28px;
|
||
height: 28px;
|
||
border-radius: 50%;
|
||
border: 2px solid rgba(99, 226, 183, 0.28);
|
||
border-top-color: #63e2b7;
|
||
animation: category-spin 0.7s linear infinite;
|
||
}
|
||
.cover-tag {
|
||
position: absolute;
|
||
left: 6px;
|
||
top: 6px;
|
||
z-index: 2;
|
||
max-width: calc(100% - 12px);
|
||
padding: 1px 6px;
|
||
border-radius: 4px;
|
||
background: rgba(0, 0, 0, 0.62);
|
||
color: #fff;
|
||
font-size: 11px;
|
||
line-height: 16px;
|
||
overflow: hidden;
|
||
text-overflow: ellipsis;
|
||
white-space: nowrap;
|
||
}
|
||
.cover img { display: block; width: 100%; height: 100%; object-fit: cover; }
|
||
.cover.loading img,
|
||
.cover.failed img { position: absolute; width: 0; height: 0; opacity: 0; }
|
||
.cover-play-layer {
|
||
position: absolute;
|
||
inset: 0;
|
||
z-index: 1;
|
||
display: flex;
|
||
align-items: center;
|
||
justify-content: center;
|
||
pointer-events: none;
|
||
}
|
||
.cover-play {
|
||
position: relative;
|
||
pointer-events: auto;
|
||
width: 44px;
|
||
height: 44px;
|
||
display: flex;
|
||
align-items: center;
|
||
justify-content: center;
|
||
padding: 0;
|
||
border: 0;
|
||
border-radius: 50%;
|
||
background: rgba(0, 0, 0, 0.55);
|
||
color: #fff;
|
||
cursor: pointer;
|
||
}
|
||
.cover-play svg { width: 22px; height: 22px; display: block; }
|
||
.cover-play:hover { background: rgba(0, 0, 0, 0.72); }
|
||
.pick {
|
||
position: absolute;
|
||
top: 8px;
|
||
right: 8px;
|
||
width: 28px;
|
||
height: 28px;
|
||
display: flex;
|
||
align-items: center;
|
||
justify-content: center;
|
||
border-radius: 6px;
|
||
background: rgba(0, 0, 0, 0.45);
|
||
}
|
||
.drama-mask {
|
||
position: absolute;
|
||
inset: 0;
|
||
z-index: 2;
|
||
pointer-events: none;
|
||
opacity: 0;
|
||
background: rgba(99, 226, 183, 0.42);
|
||
animation: drama-flash 0.45s ease-in-out 3;
|
||
}
|
||
@keyframes drama-flash {
|
||
0%, 100% { opacity: 0; }
|
||
50% { opacity: 1; }
|
||
}
|
||
.drama-title {
|
||
flex: none;
|
||
height: 52px;
|
||
box-sizing: border-box;
|
||
padding: 8px;
|
||
overflow: hidden;
|
||
font-size: 13px;
|
||
line-height: 1.35;
|
||
display: -webkit-box;
|
||
-webkit-line-clamp: 2;
|
||
-webkit-box-orient: vertical;
|
||
}
|
||
</style>
|