适用于桌面 Tampermonkey 和 iOS Userscripts 的 E-Hentai、ExHentai 和 nHentai 画廊浏览器。
// ==UserScript==
// @name Better EH
// @name:zh-CN Better EH 画廊浏览器
// @namespace better-eh
// @version 1.6.2
// @description A gallery browser for E-Hentai, ExHentai and nHentai on desktop and iOS
// @description:zh-CN 适用于桌面 Tampermonkey 和 iOS Userscripts 的 E-Hentai、ExHentai 和 nHentai 画廊浏览器。
// @match *://e-hentai.org/*
// @match *://exhentai.org/*
// @match *://upld.e-hentai.org/*
// @match *://nhentai.net/*
// @grant none
// @run-at document-end
// @noframes
// ==/UserScript==
/*
* Better EH 将以下依赖和授权说明一起放进单文件用户脚本。
* Vue 3.5.45 — https://github.com/vuejs/core
* Pinia 4.1.0 — https://github.com/vuejs/pinia
* @vueuse/core 15.0.0 — https://github.com/vueuse/vueuse
* @vueuse/motion 3.0.3 — https://github.com/vueuse/motion
* @lucide/vue 1.75.0 — https://github.com/lucide-icons/lucide
* es-toolkit 1.53.2 — https://github.com/toss/es-toolkit
* EH 标签翻译来自 EhTagTranslation Database 贡献者,版本为 v7.30120.1。
* https://github.com/EhTagTranslation/Database — CC BY-NC-SA 3.0 CN
* https://creativecommons.org/licenses/by-nc-sa/3.0/cn/
* nHentai 标签翻译来自 lgou2w / L2 Studio,使用 @l2studio/nhentai-tags 0.3.5。
* https://github.com/l2studio/nhentai-tags — 软件包采用 Apache-2.0,翻译数据采用 CC BY-SA 3.0。
* https://creativecommons.org/licenses/by-sa/3.0/ — 中文标签按需加载。
*/
(function() {
"use strict";
function readText(element) {
return element?.textContent?.trim().replace(/\s+/g, " ") ?? "";
}
function resolveHttpUrl(value, base) {
if (!value?.trim()) return;
try {
const url = new URL(value, base);
if ((url.protocol === "https:" || url.protocol === "http:") && !url.username && !url.password) return url;
} catch {
return;
}
}
function readLocalLink(element, base) {
const href = element?.getAttribute("href")?.trim();
if (!href || href.startsWith("#")) return;
const target = resolveHttpUrl(href, base);
if (target?.origin === base.origin) return target;
}
function readImageUrl(image, base) {
return (resolveHttpUrl(image?.getAttribute("data-src"), base) ?? resolveHttpUrl(image?.getAttribute("src"), base))?.href;
}
function localHref(value, base) {
const url = resolveHttpUrl(value, base);
if (!url || url.host !== base.host) return;
url.protocol = base.protocol;
return url.href;
}
function linkifyComment(text, base) {
const parts = [];
let end = 0;
for (const match of text.matchAll(/(?:[a-z][\w+.-]*:\/\/|\/\/|[a-z\d-]+(?:\.[a-z\d-]+)+(?=\/))[^\s<>"'()[\]{},。!?;:、]+/gi)) {
const address = match[0].replace(/[.,!?;:]+$/, "");
const absolute = /^(?:[a-z][\w+.-]*:)?\/\//i.test(address);
if (!absolute && /[\w@./%-]/.test(text.charAt(match.index - 1))) continue;
const href = localHref(absolute ? address : "//" + address, base);
if (!href) continue;
if (match.index > end) parts.push({ text: text.slice(end, match.index) });
parts.push({
text: address,
href
});
end = match.index + address.length;
}
if (end < text.length) parts.push({ text: text.slice(end) });
return parts;
}
function commentBody(element, base) {
const copy = element.cloneNode(true);
for (const node of copy.querySelectorAll("script, style, template")) node.remove();
for (const lineBreak of copy.querySelectorAll("br")) lineBreak.replaceWith("\n");
for (const block of copy.querySelectorAll("blockquote, div, li, p, pre")) {
block.before("\n");
block.after("\n");
}
const parts = [];
let pendingText = "";
function collect(node) {
if (node.nodeType === Node.TEXT_NODE) {
pendingText += node.nodeValue ?? "";
return;
}
if (node.nodeType !== Node.ELEMENT_NODE) return;
const element = node;
const href = element.tagName === "A" ? element.getAttribute("href") : null;
if (href !== null) {
parts.push(...linkifyComment(pendingText, base));
pendingText = "";
parts.push({
text: element.textContent ?? "",
href: localHref(href, base)
});
return;
}
for (const child of node.childNodes) collect(child);
}
collect(copy);
parts.push(...linkifyComment(pendingText, base));
const first = parts[0];
const last = parts.at(-1);
if (first) first.text = first.text.trimStart();
if (last) last.text = last.text.trimEnd();
return parts.filter((part) => part.text);
}
function uniqBy(arr, mapper) {
const map = new Map();
for (let i = 0; i < arr.length; i++) {
const item = arr[i];
const key = mapper(item, i, arr);
if (!map.has(key)) map.set(key, item);
}
return Array.from(map.values());
}
var globalThis_ = typeof globalThis === "object" && globalThis || typeof window === "object" && window || typeof self === "object" && self || typeof global === "object" && global || (function() {
return this;
})();
var DOMException = typeof globalThis_.DOMException !== "undefined" ? globalThis_.DOMException : Error;
var AbortError = class extends DOMException {
constructor(message = "The operation was aborted") {
super(message);
}
};
function delay(ms, { signal } = {}) {
return new Promise((resolve, reject) => {
const abortError = () => {
reject(new AbortError());
};
const abortHandler = () => {
clearTimeout(timeoutId);
abortError();
};
if (signal?.aborted) return abortError();
const timeoutId = setTimeout(() => {
signal?.removeEventListener("abort", abortHandler);
resolve();
}, ms);
signal?.addEventListener("abort", abortHandler, { once: true });
});
}
var nativePageFlag = "better-eh-native";
function catalogCacheGroup(url, paginationParams) {
const group = new URL(url);
group.pathname = group.pathname.replace(/\/$/, "");
group.hash = "";
for (const parameter of paginationParams) group.searchParams.delete(parameter);
group.searchParams.sort();
return {
kind: "catalog",
key: group.href
};
}
function pageUrl(href) {
const url = new URL(href, location.href);
url.hash = "";
return url;
}
function createPageLoader(adapter, initialUrl, initialPage, cache) {
const initial = pageUrl(initialUrl);
cache.set(adapter.pageCacheGroup(initial), initial.href, {
url: initialUrl,
page: initialPage
});
let availableAt = Date.now() + 900;
let blockedUntil = 0;
let tail = Promise.resolve();
function enqueue(run) {
const task = tail.then(run);
tail = task.catch(() => void 0);
return task;
}
async function read(url, signal, refresh, parse) {
if (signal.aborted) throw signal.reason;
if (blockedUntil > Date.now()) throw new Error("站点触发了访问限流,请稍后重试。");
const wait = availableAt - Date.now();
if (wait > 0) await delay(wait);
if (signal.aborted) throw signal.reason;
try {
const response = await fetch(url, {
credentials: "same-origin",
signal,
cache: refresh ? "reload" : "default"
});
const body = await response.text();
if (response.status === 429 || /(?:temporarily banned|excessive pageloads|too many requests)/i.test(body.slice(0, 1600))) {
const retryAfter = response.headers.get("Retry-After");
const milliseconds = retryAfter && /^\d+$/.test(retryAfter) ? Number(retryAfter) * 1e3 : Date.parse(retryAfter ?? "") - Date.now();
blockedUntil = Date.now() + (milliseconds > 0 ? milliseconds : 6e4);
throw new Error("站点触发了访问限流,请稍后重试。");
}
if (!response.ok) throw new Error("站点返回 HTTP " + response.status + "。");
const finalUrl = new URL(response.url || url.href);
if (finalUrl.origin !== url.origin || response.redirected && /^\/login\/?$/.test(finalUrl.pathname)) throw new Error("请在原站完成登录后重试。");
return parse(body, finalUrl);
} finally {
availableAt = Math.max(availableAt, Date.now() + 900);
}
}
function load(href, signal, refresh = false) {
const url = pageUrl(href);
if (url.origin !== location.origin) return Promise.reject(new Error("此链接需要在原站打开。"));
return enqueue(async () => {
if (signal.aborted) throw signal.reason;
const group = adapter.pageCacheGroup(url);
const cached = cache.get(group, url.href);
if (cached && !refresh) return cached;
return read(url, signal, refresh, (html, finalUrl) => {
const template = document.createElement("template");
template.innerHTML = html;
const page = adapter.parse(template.content, finalUrl);
if (!page) throw new Error("无法读取此页面,可以从原站打开。");
if (page.kind === "catalog") page.items = uniqBy(page.items, (item) => item.href);
const entry = {
url: finalUrl.href,
page
};
cache.set(group, url.href, entry);
return entry;
});
});
}
async function loadComments(href, signal, refresh) {
const { parseCommentsResponse } = adapter;
if (parseCommentsResponse) {
const url = pageUrl(href);
if (url.origin !== location.origin) throw new Error("评论链接无效。");
return enqueue(() => read(url, signal, refresh, parseCommentsResponse));
}
const comments = await readGalleryComments(href, signal, refresh);
if (comments.moreHref) throw new Error("无法读取完整评论。");
return comments;
}
async function readGalleryComments(href, signal, refresh) {
const { page } = await load(href, signal, refresh);
if (page.kind !== "gallery" || !page.comments) throw new Error("无法读取评论。");
return page.comments;
}
function refreshGalleryComments(href, signal) {
const url = adapter.galleryCommentsUrl?.(pageUrl(href));
return url ? loadComments(url, signal, true) : readGalleryComments(href, signal, true);
}
async function loadGalleryCommentTotal(href, signal) {
const url = adapter.galleryCommentsUrl?.(pageUrl(href), 1);
if (url) return (await loadComments(url, signal, false)).total;
}
async function updateGalleryFavorite(gallery) {
const favorite = gallery.favorite;
if (favorite && "submit" in favorite) {
const saved = await enqueue(() => favorite.submit(!favorite.saved));
return {
...favorite,
saved
};
}
const { page } = await load(gallery.href, new AbortController().signal, true);
if (page.kind !== "gallery" || !page.favorite) throw new Error("无法确认收藏状态,请刷新页面后重试。");
return page.favorite;
}
function submitTagChange(href, page, change) {
return enqueue(async () => {
const updated = await page.submit(change);
const url = pageUrl(href);
cache.update("catalog", (entry) => new URL(entry.url).origin === url.origin ? void 0 : entry);
cache.update("tags", (entry) => {
if (entry.page.kind !== "tags" || new URL(entry.url).origin !== url.origin) return entry;
if (entry.page.activeGroup === updated.activeGroup) return {
...entry,
page: updated
};
if (change.kind === "move" && entry.page.activeGroup === change.target) return;
return entry;
});
cache.set(adapter.pageCacheGroup(url), url.href, {
url: href,
page: updated
});
return updated;
});
}
return {
load,
loadComments,
refreshGalleryComments,
loadGalleryCommentTotal,
updateGalleryFavorite,
submitTagChange
};
}
function searchTokens(query) {
return Array.from(query.matchAll(/(?:[^\s"]+|"[^"]*(?:"|$))+/g), (match) => ({
text: match[0],
start: match.index,
end: match.index + match[0].length
}));
}
function searchCompletionRanges(query, caret) {
const tokens = searchTokens(query);
const index = tokens.findIndex(({ start, end }) => caret > start && caret <= end);
const current = tokens[index];
if (!current) return [];
const candidates = [current];
let next = current;
for (const previous of tokens.slice(Math.max(0, index - 4), index).reverse()) {
if (/^[-~]|\s|:|"/.test(next.text)) break;
if (/["$]/.test(previous.text) || /^(?:AND|OR|NOT)$/.test(previous.text)) break;
candidates.unshift(previous);
next = previous;
}
return candidates.map(({ start }, offset) => ({
start,
end: current.end,
phrase: start !== current.start,
existing: new Set([...tokens.slice(0, index + 1 - candidates.length + offset), ...tokens.slice(index + 1)].map(({ text }) => text.toLowerCase()))
}));
}
function normalize$1(value) {
return value.normalize("NFKC").trim().toLowerCase().replace(/\s+/g, " ");
}
function searchable(value) {
const text = normalize$1(value);
return {
text,
compact: text.replaceAll(" ", "")
};
}
function tagSearchEntry(namespace, key, name, label) {
return {
namespace,
key,
label,
name: searchable(name),
translation: searchable(label)
};
}
function matchScore(value, needle) {
if (value.text === needle.text) return 0;
if (value.compact === needle.compact) return 1;
const length = Math.min(value.text.length, 99);
if (value.text.startsWith(needle.text)) return 100 + length;
if (value.compact.startsWith(needle.compact)) return 200 + length;
if (value.text.includes(needle.text)) return 300 + length;
return value.compact.includes(needle.compact) ? 400 + length : Infinity;
}
function completeTagEntries(entries, contexts) {
for (const { namespace, needle, phrase, replace } of contexts) {
const term = searchable(needle);
if (!term.text) continue;
const best = [];
for (const entry of entries) {
if (namespace && entry.namespace !== namespace) continue;
const score = Math.min(matchScore(entry.name, term), matchScore(entry.translation, term));
if (phrase && score >= 200) continue;
if (!Number.isFinite(score) || score >= (best[7]?.score ?? Infinity)) continue;
const option = replace(entry.key, entry.label);
if (!option) continue;
const rank = best.findIndex((result) => result.score > score);
best.splice(rank < 0 ? best.length : rank, 0, {
option,
score
});
if (best.length > 8) best.pop();
}
if (best.length) return best.map(({ option }) => option);
}
return [];
}
function createTagDirectoryLoader(sources, parse) {
let directory;
async function download() {
for (const source of sources) {
const request = new AbortController();
const timeout = setTimeout(() => request.abort(), 8e3);
try {
const response = await fetch(source, {
credentials: "omit",
referrerPolicy: "no-referrer",
cache: "force-cache",
signal: request.signal
});
if (response.ok) return await parse(response);
} catch {} finally {
clearTimeout(timeout);
}
}
throw new Error("标签词库加载失败。");
}
return () => {
directory ??= download().catch((error) => {
directory = void 0;
throw error;
});
return directory;
};
}
var numeric = (value) => Number(value.match(/\d[\d,]*/)?.[0].replace(/,/g, "")) || 0;
var background = (style) => style?.backgroundImage.match(/^url\(["']?(.*?)["']?\)$/)?.[1];
function link(element, base) {
const target = readLocalLink(element, base);
if (target && target.href !== base.href) return target.href;
}
function image(element, base) {
const img = element.matches("img") ? element : element.querySelector("img[data-src], img");
return resolveHttpUrl(img?.getAttribute("data-src") || img?.getAttribute("src"), base)?.href;
}
var galleryPath$1 = /^\/g\/(\d+)\/[^/]+\/?$/;
var readerPath$1 = /^\/s\/[^/]+\/(\d+)-(\d+)\/?$/;
var defaultFilterParams = [
"f_sft",
"f_sfu",
"f_sfl"
];
function canonicalGalleryUrl$1(url) {
return new URL(url.pathname.replace(/\/$/, ""), url).href;
}
function galleryThumbnailPageUrl(gallery, batch) {
const url = new URL(gallery);
if (batch) url.searchParams.set("p", String(batch));
else url.searchParams.delete("p");
url.hash = "";
return url.href;
}
function searchUrl$1(base, query) {
const target = new URL("/", base);
if (query) target.searchParams.set("f_search", query);
for (const key of defaultFilterParams) if (base.searchParams.get(key) === "on") target.searchParams.set(key, "on");
return target.href;
}
var catalogPaginationParams = [
"next",
"prev",
"seek",
"jump",
"page"
];
function ehPageCacheGroup(url) {
const pathname = url.pathname.replace(/\/$/, "");
if (galleryPath$1.exec(url.pathname)?.[1]) return {
kind: "gallery",
key: new URL(pathname, url).href
};
const reader = readerPath$1.exec(url.pathname)?.[1];
if (reader) return {
kind: "reader",
key: new URL("/g/" + reader, url).href
};
if (pathname === "/mytags") return {
kind: "tags",
key: new URL(pathname, url).href
};
return catalogCacheGroup(url, catalogPaginationParams);
}
var sections = [
{
id: "home",
label: "首页",
href: "/"
},
{
id: "watched",
label: "关注",
href: "/watched"
},
{
id: "popular",
label: "热门",
href: "/popular"
},
{
id: "torrents",
label: "种子",
href: "/torrents.php",
native: true
},
{
id: "favorites",
label: "收藏夹",
href: "/favorites.php"
},
{
id: "settings",
label: "设置",
href: "/uconfig.php",
native: true
},
{
id: "uploads",
label: "我的上传",
href: "https://upld.e-hentai.org/manage",
native: true
},
{
id: "tags",
label: "我的标签",
href: "/mytags"
}
];
function ehNavigation(url) {
return sections.map((section) => ({
...section,
href: new URL(section.href, url).href
}));
}
function isNativePage(url) {
return sections.some((section) => section.native && new URL(section.href, url).pathname === url.pathname);
}
function gallerySummary(row, anchor, base) {
const href = link(anchor, base);
const title = readText(anchor.querySelector(".glink") ?? anchor);
if (!href || !title) return;
const coverArea = row.querySelector(".glthumb, .gl1e, .gl1t, .gl2c, .gl2m");
const posted = readText(row.querySelector("[id^='posted_'], [id^='postedpop_']"));
const count = Array.from(row.querySelectorAll("div,span")).find((element) => /^\d[\d,]* pages?$/i.test(readText(element)));
return {
href,
title,
posted,
cover: coverArea ? image(coverArea, base) : image(row, base),
category: readText(row.querySelector(".cn, .cs")),
pages: numeric(readText(count))
};
}
function firstCatalogPage(base) {
const target = new URL(base);
for (const key of catalogPaginationParams) target.searchParams.delete(key);
target.hash = "";
return target;
}
function defaultFilters(base) {
if (base.pathname !== "/") return;
const disabled = defaultFilterParams.every((key) => base.searchParams.get(key) === "on");
const target = firstCatalogPage(base);
for (const key of defaultFilterParams) if (disabled) target.searchParams.delete(key);
else target.searchParams.set(key, "on");
return {
href: target.href,
disabled
};
}
function categories(doc, base) {
const mask = numeric(base.searchParams.get("f_cats") ?? "");
return Array.from(doc.querySelectorAll("[id^='cat_']")).flatMap((element) => {
const bit = numeric(element.id);
const label = readText(element);
if (!bit || !label) return [];
const target = firstCatalogPage(base);
const filter = (mask ? mask : 1023 ^ bit) ^ (mask ? bit : 0);
if (filter && filter !== 1023) target.searchParams.set("f_cats", String(filter));
else target.searchParams.delete("f_cats");
return [{
href: target.href,
label,
selected: Boolean(mask && !(mask & bit))
}];
});
}
function parseCatalog$1(doc, base) {
if (!doc.querySelector(".itg, #f_search, .searchnav, .ip")) return;
const entries = new Map();
for (const anchor of doc.querySelectorAll(".itg a[href*='/g/']")) {
if (!anchor.querySelector(".glink") && !anchor.matches(".glink")) continue;
const row = anchor.closest("tr, .gl1t, .gl1e, .gl1m") ?? anchor.parentElement;
if (!row) continue;
const gallery = gallerySummary(row, anchor, base);
if (gallery) entries.set(gallery.href, gallery);
}
const query = base.searchParams.get("f_search") ?? "";
const section = ehNavigation(base).find((item) => item.id !== "home" && new URL(item.href).pathname === base.pathname);
return {
kind: "catalog",
title: base.pathname === "/favorites.php" ? "收藏夹" : query ? "搜索结果" : section?.label ?? "画廊索引",
query,
items: [...entries.values()],
categories: categories(doc, base),
defaultFilters: defaultFilters(base),
previous: link(doc.querySelector("#uprev, #dprev"), base),
next: link(doc.querySelector("#unext, #dnext"), base)
};
}
function parseComments$1(doc, base) {
const section = doc.querySelector("#cdiv");
if (!section) return;
const items = Array.from(section.querySelectorAll(".c6[id^='comment_']")).flatMap((element) => {
const body = commentBody(element, base);
if (!body.length) return [];
const row = element.closest(".c1");
const header = row?.querySelector(".c3");
const author = header?.querySelector("a")?.textContent?.trim() ?? "";
const posted = header?.textContent?.match(/Posted on\s+(.+?)\s+by:/i)?.[1] ?? "";
const score = row?.querySelector(".c4")?.textContent?.match(/\bScore:?\s*([+-]?\d+)/i)?.[1];
return [{
id: element.id,
author,
posted,
body,
score: score ? Number(score) : void 0
}];
});
if (base.searchParams.get("hc") !== "1") for (const link of section.querySelectorAll("#chd a[href*='hc=1']")) {
const target = readLocalLink(link, base);
if (!target || target.pathname.replace(/\/$/, "") !== base.pathname.replace(/\/$/, "") || target.searchParams.get("hc") !== "1") continue;
const hiddenCount = link.closest("p")?.textContent?.match(/(\d[\d,]*)\s+more comments?\b/i)?.[1];
const hidden = Number(hiddenCount?.replace(/,/g, ""));
return {
items,
moreHref: target.href,
total: Number.isSafeInteger(hidden) ? items.length + hidden : void 0
};
}
return {
items,
total: items.length
};
}
var dictionaryPath$1 = "EhTagTranslation/Database";
var dictionaryRevision = "932608f817bcbe709a56248d2b7fd954b898b009";
var dictionarySources$1 = ["https://raw.githubusercontent.com/" + dictionaryPath$1 + "/" + dictionaryRevision + "/db.text.json", "https://cdn.jsdelivr.net/gh/" + dictionaryPath$1 + "@" + dictionaryRevision + "/db.text.json"];
var namespaceAliases = new Map([
["a", "artist"],
["c", "character"],
["cos", "cosplayer"],
["f", "female"],
["g", "group"],
["l", "language"],
["loc", "location"],
["m", "male"],
["o", "other"],
["p", "parody"],
["r", "reclass"],
["x", "mixed"]
]);
var namespaces$1 = new Set(namespaceAliases.values());
function normalize(text) {
return text.normalize("NFKC").trim().toLowerCase();
}
function exactTagTerm(key) {
const colon = key.indexOf(":");
return `${colon < 0 ? "" : key.slice(0, colon + 1)}"${key.slice(colon + 1)}$"`;
}
function record(value) {
return typeof value === "object" && value !== null && !Array.isArray(value);
}
function makeDirectory$1(raw) {
if (!record(raw) || !Array.isArray(raw.data)) throw new Error("标签词库格式有误。");
const entries = [];
const translations = new Map();
for (const group of raw.data) {
if (!record(group) || typeof group.namespace !== "string" || !record(group.data)) continue;
const namespace = group.namespace;
if (!namespaces$1.has(namespace)) continue;
for (const [term, item] of Object.entries(group.data)) {
if (!record(item) || typeof item.name !== "string" || /["$\\\r\n]/.test(term)) continue;
const key = namespace + ":" + term;
const label = item.name.trim();
if (!label) continue;
entries.push(tagSearchEntry(namespace, key, term, label));
translations.set(normalize(key), label);
}
}
if (!entries.length) throw new Error("标签词库为空。");
return {
translate(key) {
const value = normalize(key);
const colon = value.indexOf(":");
if (colon < 0) return;
const namespace = value.slice(0, colon).trim();
return translations.get((namespaceAliases.get(namespace) ?? namespace) + ":" + value.slice(colon + 1).trim());
},
complete(query, caret) {
const contexts = searchCompletionRanges(query, caret).flatMap((range) => completionContext(query, caret, range) ?? []);
return completeTagEntries(entries, contexts);
}
};
}
function completionContext(query, caret, { start, end, existing, phrase }) {
let input = normalize(query.slice(start, caret));
const modifier = input.match(/^[-~]/)?.[0] ?? "";
input = input.slice(modifier.length);
const qualifier = input.startsWith("weak:") ? "weak:" : "";
input = input.slice(qualifier.length);
const colon = input.indexOf(":");
const prefix = colon < 0 ? "" : input.slice(0, colon);
const namespace = namespaceAliases.get(prefix) ?? prefix;
if (namespace && namespace !== "tag" && !namespaces$1.has(namespace)) return;
const needle = input.slice(colon + 1).replace(/^"|"$/g, "").trim();
if (!needle || /["$]/.test(needle)) return;
const suffix = query.slice(end) || " ";
return {
namespace: namespace && namespace !== "tag" ? namespace : void 0,
needle,
phrase,
replace(key, label) {
const value = modifier + qualifier + exactTagTerm(key);
if (existing.has(value.toLowerCase())) return;
return {
key,
label,
query: query.slice(0, start) + value + suffix,
caret: start + value.length + 1
};
}
};
}
var loadTagDirectory$1 = createTagDirectoryLoader(dictionarySources$1, async (response) => makeDirectory$1(await response.json()));
function thumbnail(anchor, base) {
const href = link(anchor, base);
if (!href) return;
const index = numeric(new URL(href).pathname.split("-").at(-1) ?? "");
const tile = anchor.querySelector("[style*='background']");
const sprite = resolveHttpUrl(background(tile?.style), base)?.href;
const width = numeric(tile?.style.width ?? "");
const height = numeric(tile?.style.height ?? "");
if (!sprite || !width || !height) return {
href,
index,
image: image(anchor, base)
};
const [x = "0", y = "0"] = (tile?.style.backgroundPosition || "0 0").split(" ");
return {
href,
index,
image: sprite,
sprite: {
width,
height,
x: Number.parseFloat(x) || 0,
y: Number.parseFloat(y) || 0
}
};
}
function thumbnailLinks(doc, base) {
const current = doc.querySelector(".ptt .ptds, .ptb .ptds");
return {
previous: link(current?.previousElementSibling?.querySelector("a"), base),
next: link(current?.nextElementSibling?.querySelector("a"), base)
};
}
function galleryFavorite$1(doc, base) {
const label = readText(doc.querySelector("#gdf #favoritelink"));
const gid = galleryPath$1.exec(base.pathname)?.[1];
const token = base.pathname.split("/")[3];
if (!label || !gid || !token) return;
const target = new URL("/gallerypopups.php", base);
target.search = new URLSearchParams({
gid,
t: token,
act: "addfav"
}).toString();
return {
saved: !/^add to favorites$/i.test(label),
href: target.href
};
}
function parseGallery$1(doc, base) {
const title = readText(doc.querySelector("#gn")) || readText(doc.querySelector("#gj"));
if (!title) return;
const info = new Map(Array.from(doc.querySelectorAll("#gdd tr"), (row) => [readText(row.querySelector(".gdt1")).replace(/:$/, ""), readText(row.querySelector(".gdt2"))]));
const cover = doc.querySelector("#gd1 [style*='background']");
const coverUrl = resolveHttpUrl(background(cover?.style), base)?.href ?? (cover && image(cover, base)) ?? void 0;
return {
kind: "gallery",
href: base.href,
title,
cover: coverUrl,
subtitle: readText(doc.querySelector("#gj")),
category: readText(doc.querySelector("#gdc .cs, #gdc .cn, #gdc")),
pages: numeric(info.get("Length") ?? ""),
posted: info.get("Posted") ?? "",
uploader: readText(doc.querySelector("#gdn a")),
language: info.get("Language") ?? "",
rating: readText(doc.querySelector("#rating_label")).replace(/^Average:\s*/i, ""),
tags: Array.from(doc.querySelectorAll("#taglist a")).flatMap((anchor) => {
const label = readText(anchor);
if (!label) return [];
const namespace = readText(anchor.closest("tr")?.querySelector(".tc")).replace(/:$/, "").trim();
const key = namespace ? namespace + ":" + label : label;
const searchTerm = exactTagTerm(key);
return [{
label,
namespace: namespace || void 0,
key,
searchTerm,
href: searchUrl$1(base, searchTerm)
}];
}),
thumbnails: Array.from(doc.querySelectorAll("#gdt a[href*='/s/']")).flatMap((anchor) => thumbnail(anchor, base) ?? []),
comments: parseComments$1(doc, base),
favorite: galleryFavorite$1(doc, base),
...thumbnailLinks(doc, base)
};
}
function readerReloadHref(doc, base) {
const handler = doc.querySelector("#loadfail")?.getAttribute("onclick") ?? "";
const key = /^\s*(?:return\s+)?nl\(\s*(['"])([\w-]+)\1\s*\)\s*;?\s*$/.exec(handler)?.[2];
if (!key || key === base.searchParams.get("nl")) return;
const url = new URL(base);
url.searchParams.set("nl", key);
url.hash = "";
return url.href;
}
function readerOriginalHref(doc, base) {
const route = readerPath$1.exec(base.pathname);
if (!route) return;
const [, galleryId, index] = route;
for (const anchor of doc.querySelectorAll("#i6 a[href]")) {
const href = link(anchor, base);
if (!href) continue;
const url = new URL(href);
const originalPath = /^\/fullimg\/(\d+)\/(\d+)(?:\/|$)/.exec(url.pathname);
if (originalPath?.[1] === galleryId && originalPath?.[2] === index) return href;
if (url.pathname === "/fullimg.php" && url.searchParams.get("gid") === galleryId && url.searchParams.get("page") === index) return href;
}
}
function parseReader$1(doc, base) {
const element = doc.querySelector("img#img");
if (!element) return;
const src = image(element, base);
if (!src) return;
const counters = Array.from(doc.querySelectorAll("#i2 .sn span"), (span) => numeric(readText(span)));
const frame = {
href: base.href,
image: src,
reloadHref: readerReloadHref(doc, base),
originalHref: readerOriginalHref(doc, base),
width: numeric(element.style.width || element.getAttribute("width") || ""),
height: numeric(element.style.height || element.getAttribute("height") || ""),
index: numeric(base.pathname.split("-").at(-1) ?? "") || counters[0] || 1
};
const galleryLink = link(doc.querySelector("#i5 a[href*='/g/'], #i7 a[href*='/g/'], .sb a[href*='/g/']"), base);
const gallery = galleryLink ? new URL(galleryLink) : void 0;
gallery?.searchParams.delete("p");
const firstPagePath = base.pathname.replace(/-\d+\/?$/, "-1").split("/").at(-1);
const first = Array.from(doc.querySelectorAll("#first, #i2 .sn a[href], #i5 .sn a[href]"), (anchor) => link(anchor, base)).find((href) => {
if (!href) return false;
const pathname = new URL(href).pathname.replace(/\/$/, "");
return pathname.startsWith("/s/") && pathname.endsWith("/" + firstPagePath);
});
return {
kind: "reader",
title: readText(doc.querySelector("h1")) || "阅读器",
image: src,
width: frame.width,
height: frame.height,
index: frame.index,
total: counters[1] || 0,
gallery: gallery?.href,
first,
previous: link(doc.querySelector("#prev"), base),
next: link(doc.querySelector("#next"), base),
frames: [frame]
};
}
function tagsUrl(base, group) {
const url = new URL("/mytags", base);
if (group !== "1") url.searchParams.set("tagset", group);
return url;
}
function readApi(doc, url) {
if (url.hostname !== "e-hentai.org" && url.hostname !== "exhentai.org") return;
const host = url.hostname === "exhentai.org" ? "s.exhentai.org" : "api.e-hentai.org";
for (const script of doc.querySelectorAll("script:not([src])")) {
const code = script.textContent ?? "";
const userId = Number(code.match(/\bapiuid\s*=\s*(\d+)/)?.[1]);
const key = code.match(/\bapikey\s*=\s*["']([a-z0-9_-]+)["']/i)?.[1];
if (userId > 0 && key) return {
url: "https://" + host + "/api.php",
userId,
key
};
}
}
function readTag(row) {
const id = row.id.match(/^usertag_([1-9]\d*)$/)?.[1];
if (!id) return;
const name = row.querySelector("[id^='tagpreview_']")?.getAttribute("title")?.trim() || row.querySelector("a[href*='/tag/']")?.textContent?.trim();
if (!name) return;
const input = (prefix) => row.querySelector("input[id^='" + prefix + "_']");
const weight = Number(input("tagweight")?.value ?? 10);
return {
id,
name,
watched: input("tagwatch")?.checked ?? false,
hidden: input("taghide")?.checked ?? false,
weight: Number.isFinite(weight) ? weight : 10,
color: input("tagcolor")?.value.trim() ?? ""
};
}
function buildTagsPage(data, source) {
return {
...data,
async submit(change) {
if (change.kind === "edit") {
if (!source.api || !data.tags.some((tag) => tag.id === change.id)) throw new Error("请在原站编辑此标签。");
await saveTag(source.api, change);
const { kind: _kind, ...preferences } = change;
return buildTagsPage({
...data,
tags: data.tags.map((tag) => tag.id === change.id ? {
...tag,
...preferences
} : tag)
}, source);
}
return submitTagForm(data, source, change);
}
};
}
async function saveTag(api, change) {
const response = await fetch(api.url, {
method: "POST",
credentials: "include",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({
method: "setusertag",
apiuid: api.userId,
apikey: api.key,
tagid: Number(change.id),
tagwatch: Number(change.watched),
taghide: Number(change.hidden),
tagcolor: change.color,
tagweight: String(change.weight)
})
});
if (!response.ok) throw new Error("保存标签失败(HTTP " + response.status + ")。");
const result = await response.json();
if (!result || typeof result !== "object") throw new Error("原站未确认保存。");
if ("login" in result && result.login) throw new Error("请先在原站登录。");
if ("error" in result && typeof result.error === "string" && result.error) throw new Error(result.error);
if (!("tagid" in result) || Number(result.tagid) !== Number(change.id)) throw new Error("原站未确认保存。");
}
function tagFormBody(page, source, change) {
const body = new URLSearchParams(source.hiddenFields);
body.set("tagname_new", "");
body.set("tagcolor_new", "");
body.set("tagweight_new", "10");
if (change.kind === "add") {
if (!page.canAdd) throw new Error("此标签组无法添加标签。");
body.set("usertag_action", "add");
body.set("tagname_new", change.name);
body.set("tagcolor_new", change.color);
body.set("tagweight_new", String(change.weight));
if (change.watched) body.set("tagwatch_new", "on");
if (change.hidden) body.set("taghide_new", "on");
} else {
if (!change.ids.length || change.ids.some((id) => !page.tags.some((tag) => tag.id === id))) throw new Error("请重新选择要操作的标签。");
const target = change.kind === "move" ? change.target : "0";
if (change.kind === "move" && !page.groups.some((group) => group.id === target && group.id !== page.activeGroup)) throw new Error("请选择其他标签组。");
body.set("usertag_action", "mass");
body.set("usertag_target", target);
for (const id of change.ids) body.append("modify_usertags[]", id);
}
return body;
}
async function submitTagForm(page, source, change) {
const body = tagFormBody(page, source, change);
const response = await fetch(source.url, {
method: "POST",
credentials: "same-origin",
body
});
if (!response.ok) throw new Error("标签操作失败(HTTP " + response.status + ")。");
const url = new URL(response.url || source.url.href);
const template = document.createElement("template");
template.innerHTML = await response.text();
const updated = url.origin === source.url.origin && parseTags$1(template.content, url);
if (!updated || updated.activeGroup !== page.activeGroup) throw new Error("无法确认操作结果,请在原站检查。");
if (change.kind === "add") {
const name = change.name.trim().toLowerCase();
const matchingTag = updated.tags.some((tag) => tag.name.toLowerCase() === name);
const addedTag = updated.tags.some((tag) => !page.tags.some((saved) => saved.id === tag.id));
if (!matchingTag && !addedTag) throw new Error("原站未添加此标签,请检查标签名称。");
} else if (updated.tags.some((tag) => change.ids.includes(tag.id))) throw new Error("部分标签仍在原分组,请检查后重试。");
return updated;
}
function parseTags$1(doc, url) {
if (url.pathname.replace(/\/$/, "") !== "/mytags") return;
const form = doc.querySelector("#usertag_form");
const tagList = doc.querySelector("#usertags_outer");
if (!form || !tagList) return;
const select = doc.querySelector("#tagset_outer select");
const activeGroup = select?.value || url.searchParams.get("tagset") || "1";
const groups = Array.from(select?.options ?? [], (option) => ({
id: option.value,
label: (option.textContent ?? "").trim() || option.value,
href: tagsUrl(url, option.value).href
}));
const tags = Array.from(tagList.querySelectorAll(":scope > [id^='usertag_']")).flatMap((row) => readTag(row) ?? []);
const api = readApi(doc, url);
const hiddenFields = Array.from(form.querySelectorAll("input[type='hidden'][name]:enabled")).filter((input) => ![
"usertag_action",
"usertag_target",
"modify_usertags[]"
].includes(input.name)).map((input) => [input.name, input.value]);
return buildTagsPage({
kind: "tags",
title: "我的标签",
groups,
activeGroup,
groupEnabled: doc.querySelector("#tagset_enable")?.checked ?? true,
defaultColor: doc.querySelector("#tagcolor")?.value.trim() ?? "",
tags,
canAdd: Boolean(form.querySelector("#tagname_new:enabled")),
canEdit: Boolean(api)
}, {
url: tagsUrl(url, activeGroup),
hiddenFields,
api
});
}
var ehAdapter = {
name: "E-Hentai",
home: (url) => new URL("/", url).href,
pageCacheGroup: ehPageCacheGroup,
canonicalGalleryUrl: canonicalGalleryUrl$1,
galleryThumbnailPageUrl,
navigation: ehNavigation,
loadTagDirectory: loadTagDirectory$1,
search: searchUrl$1,
parse(doc, url) {
if (url.pathname.replace(/\/$/, "") === "/mytags") return parseTags$1(doc, url);
if (isNativePage(url)) return;
if (galleryPath$1.test(url.pathname)) return parseGallery$1(doc, url);
if (readerPath$1.test(url.pathname)) return parseReader$1(doc, url);
return parseCatalog$1(doc, url);
}
};
function positiveInteger(value) {
const number = Number(value?.trim().replace(/,/g, ""));
return Number.isSafeInteger(number) && number > 0 ? number : 0;
}
var galleryPath = /^\/g\/([1-9]\d*)\/?$/;
var readerPath = /^\/g\/([1-9]\d*)\/([1-9]\d*)\/?$/;
var tagNamespaces = [
["languages", "language"],
["categories", "category"],
["tags", "tag"],
["parodies", "parody"],
["characters", "character"],
["artists", "artist"],
["groups", "group"]
];
var tagPath = new RegExp(`^/(${tagNamespaces.map(([, type]) => type).join("|")})/[^/]+/?$`);
var favoritesPath = "/user/favorites";
function galleryUrl(base, id) {
return new URL(`/g/${id}/`, base).href;
}
function readerUrl(base, id, index) {
return new URL(`/g/${id}/${index}/`, base).href;
}
function searchUrl(base, query) {
const target = new URL("/search/", base);
target.searchParams.set("q", query);
return target.href;
}
function canonicalGalleryUrl(url) {
const id = galleryPath.exec(url.pathname)?.[1];
return id ? galleryUrl(url, id) : url.href;
}
function readerPageUrl(gallery, index) {
const id = galleryPath.exec(gallery.pathname)?.[1];
if (id && Number.isSafeInteger(index) && index > 0) return readerUrl(gallery, id, index);
}
var searchPath = /^\/search(?:\/popular(?:-(?:today|week|month))?)?\/?$/;
function catalogTitle(doc, url) {
const path = url.pathname.replace(/\/$/, "");
if (path === "") return "画廊索引";
if (path === "/user/favorites") return "收藏夹";
if (searchPath.test(path)) return "搜索结果";
const section = path.replace(/\/popular(?:-(?:today|week|month))?$/, "");
if (tagPath.test(path) || tagPath.test(section)) return readText(doc.querySelector("#content h1, .index-container h1")) || "标签画廊";
}
function parseCard(card, base) {
const anchor = card.querySelector("a.cover[href]") ?? card.querySelector("a[href^='/g/']");
const target = readLocalLink(anchor, base);
const id = target && galleryPath.exec(target.pathname)?.[1];
const caption = card.querySelector(".caption");
const image = anchor?.querySelector("img");
const title = readText(caption) || caption?.getAttribute("title")?.trim() || image?.getAttribute("alt")?.trim();
if (!id || !title) return;
const pageCount = readText(card.querySelector(".page-count")).match(/^(\d[\d,]*)(?:\s+pages?)?$/i)?.[1];
const time = card.querySelector("time");
return {
href: galleryUrl(base, id),
title,
cover: readImageUrl(image, base),
category: readText(card.querySelector(".category")),
pages: positiveInteger(card.getAttribute("data-num-pages")) || positiveInteger(pageCount),
posted: time?.getAttribute("datetime") || readText(time)
};
}
function paginationLink(doc, base, selector) {
const target = readLocalLink(doc.querySelector(selector), base);
if (target && target.pathname.replace(/\/$/, "") === base.pathname.replace(/\/$/, "") && target.search !== base.search) return target.href;
}
function parseCatalog(doc, base) {
const title = catalogTitle(doc, base);
if (!title) return;
const home = base.pathname === "/";
const favorites = base.pathname.replace(/\/$/, "") === favoritesPath;
const cards = doc.querySelectorAll(".index-container .gallery, #content .gallery");
if (!cards.length && !doc.querySelector(favorites ? "#favcontainer, .index-container" : ".index-container")) {
if (!searchPath.test(base.pathname) || !doc.querySelector("#content .no-results")) return;
}
const entries = new Map();
const featured = new Map();
for (const card of cards) {
const gallery = parseCard(card, base);
if (!gallery) continue;
const group = home && card.closest(".index-popular") ? featured : entries;
if (!group.has(gallery.href)) group.set(gallery.href, gallery);
}
if (cards.length && !entries.size && !featured.size) return;
const query = base.searchParams.get("q") ?? "";
return {
kind: "catalog",
title,
query,
emptyMessage: favorites && !query ? "收藏夹暂无画廊。" : void 0,
featured: featured.size ? {
title: "当前热门",
items: [...featured.values()]
} : void 0,
itemsTitle: home ? "最新上传" : void 0,
items: [...entries.values()],
categories: [],
previous: paginationLink(doc, base, ".pagination a.previous, .pagination a[rel~='prev']"),
next: paginationLink(doc, base, ".pagination a.next, .pagination a[rel~='next']")
};
}
var pageSize = 30;
var maxPage = 2e3;
var commentSelector = ".comment[id^='comment-']";
function commentsUrl(base, galleryId, page, perPage = pageSize) {
const target = new URL(`/api/v2/galleries/${galleryId}/comments`, base);
target.searchParams.set("page", String(page));
target.searchParams.set("per_page", String(perPage));
return target.href;
}
function galleryCommentsUrl(gallery, perPage) {
const id = galleryPath.exec(gallery.pathname)?.[1];
if (id) return commentsUrl(gallery, id, 1, perPage);
}
function parseComments(doc, base, galleryId) {
const section = doc.querySelector("#comments");
if (!section) return {
items: [],
moreHref: commentsUrl(base, galleryId, 1)
};
const elements = Array.from(section.querySelectorAll(commentSelector));
const items = elements.flatMap((element) => {
const content = element.querySelector(".body");
if (!content) return [];
const body = commentBody(content, base);
if (!body.length) return [];
const time = element.querySelector("time");
return [{
id: element.id,
body,
author: readText(element.querySelector(".username")),
posted: readText(time) || time?.getAttribute("datetime")?.slice(0, 10) || ""
}];
});
const pages = section.querySelectorAll(".comments-page[data-page]");
const lastPage = pages[pages.length - 1];
const page = positiveInteger(lastPage?.getAttribute("data-page")) || 1;
const count = lastPage?.querySelectorAll(commentSelector).length ?? elements.length;
return {
items,
moreHref: count >= pageSize && page < maxPage ? commentsUrl(base, galleryId, page + 1) : void 0,
total: count < pageSize ? elements.length : void 0
};
}
function isRecord$1(value) {
return Boolean(value && typeof value === "object");
}
function parseCommentsResponse(body, url) {
const galleryId = /^\/api\/v2\/galleries\/([1-9]\d*)\/comments\/?$/.exec(url.pathname)?.[1];
const page = positiveInteger(url.searchParams.get("page"));
const perPage = positiveInteger(url.searchParams.get("per_page")) || pageSize;
const payload = JSON.parse(body);
if (!galleryId || !page || !isRecord$1(payload) || !Array.isArray(payload.result) || typeof payload.num_pages !== "number" || !Number.isSafeInteger(payload.num_pages) || payload.num_pages < 0) throw new Error("评论响应格式有误。");
const rows = payload.result;
return {
items: rows.flatMap((row) => {
if (!isRecord$1(row) || row.gallery_id !== Number(galleryId) || typeof row.id !== "number" || !Number.isSafeInteger(row.id) || typeof row.body !== "string" || !row.body.trim()) return [];
const date = typeof row.post_date === "number" ? new Date(row.post_date * 1e3) : void 0;
return [{
id: `comment-${row.id}`,
author: isRecord$1(row.poster) && typeof row.poster.username === "string" ? row.poster.username : "",
posted: date && Number.isFinite(date.getTime()) ? date.toISOString().slice(0, 10) : "",
body: linkifyComment(row.body.trim(), url)
}];
}),
total: typeof payload.total === "number" && Number.isSafeInteger(payload.total) && payload.total >= 0 ? payload.total : void 0,
moreHref: rows.length && page < Math.min(payload.num_pages, maxPage) ? commentsUrl(url, galleryId, page + 1, perPage) : void 0
};
}
function accessToken() {
const cookie = document.cookie.match(/(?:^|;\s*)access_token=([^;]+)/)?.[1];
if (cookie) return decodeURIComponent(cookie);
}
async function submitFavorite(url, saved) {
if (url.origin !== location.origin) throw new Error("请在原站操作收藏。");
const method = saved ? "POST" : "DELETE";
const options = {
credentials: "same-origin",
redirect: "error"
};
const send = (token) => fetch(url, {
...options,
method,
headers: { Authorization: "User " + token }
});
const token = accessToken();
let response = token ? await send(token) : void 0;
if (!response || response.status === 401) {
const refreshedToken = (await fetch(new URL("/auth/refresh", url), {
...options,
method: "POST"
})).ok && accessToken();
if (!refreshedToken) throw new Error("请在原站登录后重试。");
response = await send(refreshedToken);
}
if (response.status === 401 || response.status === 403) throw new Error("请在原站登录后重试。");
if (!response.ok) throw new Error("收藏操作失败,站点返回 HTTP " + response.status + "。");
const result = await response.json();
if (!result || typeof result !== "object" || !("favorited" in result) || typeof result.favorited !== "boolean") throw new Error("无法确认收藏状态,请重试。");
return result.favorited;
}
function galleryFavorite(doc, base, id) {
const label = readText(doc.querySelector("button#favorite:not([disabled])")?.querySelector(".text"));
if (label !== "Favorite" && label !== "Unfavorite") return;
const url = new URL(`/api/v2/galleries/${id}/favorite`, base);
return {
saved: label === "Unfavorite",
submit: (saved) => submitFavorite(url, saved)
};
}
var searchTag = new RegExp(`^(${tagNamespaces.map(([, type]) => type).join("|")}):(?:"[^"]+"|[^"\\s]+)$`, "i");
function parseTags(doc, base) {
const tags = new Map();
for (const anchor of doc.querySelectorAll("#tags a.tag, #tags a.tagchip")) {
const link = readLocalLink(anchor, base);
if (!link) continue;
const query = /^\/search\/?$/.test(link.pathname) ? link.searchParams.get("q") ?? "" : "";
const exactTerm = searchTag.exec(query);
const namespace = tagPath.exec(link.pathname)?.[1] ?? exactTerm?.[1]?.toLowerCase();
const label = readText(anchor.querySelector(".name"));
if (!namespace || !label) continue;
const key = `${namespace}:${label}`;
const searchTerm = exactTerm?.[0] ?? (/"/.test(label) ? void 0 : `${namespace}:"${label}"`);
tags.set(key, {
label,
namespace,
key,
href: searchTerm ? searchUrl(base, searchTerm) : link.href,
searchTerm
});
}
return [...tags.values()];
}
function parseThumbnails(doc, base, id) {
const thumbnails = new Map();
for (const anchor of doc.querySelectorAll("#thumbnail-container a[href], a.gallerythumb[href]")) {
const target = readLocalLink(anchor, base);
const route = target && readerPath.exec(target.pathname);
const index = positiveInteger(route?.[2]);
if (route?.[1] === id && index) thumbnails.set(index, {
href: readerUrl(base, id, index),
index,
image: readImageUrl(anchor.querySelector("img"), base)
});
}
return [...thumbnails.values()].sort((a, b) => a.index - b.index);
}
function pageCount(doc, base) {
for (const row of doc.querySelectorAll("#tags .tag-container")) {
const count = readText(row).match(/^Pages:\s*(\d[\d,]*)(?:\s|$)/i)?.[1];
if (count) return positiveInteger(count);
for (const anchor of row.querySelectorAll("a[href]")) {
const query = readLocalLink(anchor, base)?.searchParams.get("q") ?? "";
const pages = /^pages:(\d+)$/i.exec(query)?.[1];
if (pages) return positiveInteger(pages);
}
}
return 0;
}
function parseGallery(doc, base, id) {
const title = readText(doc.querySelector("#info h1"));
if (!title) return;
const tags = parseTags(doc, base);
const thumbnails = parseThumbnails(doc, base, id);
const time = doc.querySelector("#tags time");
return {
kind: "gallery",
href: galleryUrl(base, id),
title,
cover: readImageUrl(doc.querySelector("#cover img"), base),
subtitle: readText(doc.querySelector("#info h2")),
category: tags.find((tag) => tag.namespace === "category")?.label ?? "",
pages: pageCount(doc, base) || (thumbnails.at(-1)?.index ?? 0),
posted: time?.getAttribute("datetime")?.split("T")[0] || readText(time),
uploader: "",
language: tags.filter((tag) => tag.namespace === "language" && tag.label !== "translated").map((tag) => tag.label).join(" / "),
rating: "",
tags,
thumbnails,
comments: parseComments(doc, base, id),
favorite: galleryFavorite(doc, base, id)
};
}
function nhPageCacheGroup(url) {
const reader = readerPath.exec(url.pathname)?.[1];
if (reader) return {
kind: "reader",
key: galleryUrl(url, reader)
};
const gallery = galleryPath.exec(url.pathname)?.[1];
if (gallery) return {
kind: "gallery",
key: galleryUrl(url, gallery)
};
return catalogCacheGroup(url, ["page"]);
}
function nhNavigation(url) {
return [
{
id: "home",
label: "首页",
href: new URL("/", url).href
},
{
id: "favorites",
label: "收藏夹",
href: new URL(favoritesPath, url).href
},
{
id: "tags",
label: "标签目录",
href: new URL("/tags/", url).href,
native: true
}
];
}
function parseReader(doc, base, id, index) {
const element = doc.querySelector("#image-container img");
const image = readImageUrl(element, base);
if (!image || !index) return;
const total = positiveInteger(readText(doc.querySelector(".num-pages")));
if (total && index > total) return;
const nextLink = readLocalLink(doc.querySelector(".reader-bar a.next, .pagination a.next, #image-container a"), base);
const nextRoute = nextLink && readerPath.exec(nextLink.pathname);
const hasNext = total ? index < total : nextRoute?.[1] === id && positiveInteger(nextRoute[2]) === index + 1;
const heading = Array.from(doc.querySelectorAll("h1 a[href], h2 a[href]")).find((anchor) => {
const target = readLocalLink(anchor, base);
return target && galleryPath.exec(target.pathname)?.[1] === id && readText(anchor);
});
const documentTitle = readText(doc.querySelector("title")).replace(/(?:\s+[-–—]\s+Page\s+\d+)?\s*[-|–—»]\s*nhentai(?:\.net)?$/i, "");
return {
kind: "reader",
title: readText(heading) || documentTitle || `画廊 #${id}`,
image,
width: positiveInteger(element?.getAttribute("width")) || void 0,
height: positiveInteger(element?.getAttribute("height")) || void 0,
index,
total,
gallery: galleryUrl(base, id),
first: readerUrl(base, id, 1),
previous: index > 1 ? readerUrl(base, id, index - 1) : void 0,
next: hasNext ? readerUrl(base, id, index + 1) : void 0
};
}
var tagTypes = new Map(tagNamespaces.flatMap(([plural, type]) => [[plural, type], [type, type]]));
var namespaces = new Set(tagNamespaces.map(([, type]) => type));
var cache = new Map();
var limit = 10;
var containsHan = /\p{Script=Han}/u;
async function findTags(query, type, signal) {
const cacheKey = `${type ?? ""}:${query}`;
const cached = cache.get(cacheKey);
if (cached) return cached;
const response = await fetch("/api/v2/tags/search", {
method: "POST",
credentials: "same-origin",
headers: {
Accept: "application/json",
"Content-Type": "application/json"
},
body: JSON.stringify({
type,
query,
limit
}),
signal
});
if (!response.ok) throw new Error("标签联想请求失败。");
const result = await response.json();
if (!Array.isArray(result)) throw new Error("标签联想响应格式有误。");
const rows = result;
const tags = new Map();
for (const row of rows.slice(0, limit)) {
if (!row || typeof row !== "object" || !("type" in row) || typeof row.type !== "string" || !namespaces.has(row.type) || type && row.type !== type || !("name" in row) || typeof row.name !== "string") continue;
const label = row.name.trim();
if (!label || /["\\\r\n]/.test(label)) continue;
const key = `${row.type}:${label}`;
tags.set(key.toLowerCase(), {
key,
label
});
}
const matches = [...tags.values()];
cache.set(cacheKey, matches);
const oldest = cache.keys().next().value;
if (cache.size > 64 && oldest) cache.delete(oldest);
return matches;
}
function tagCompletionContexts(query, caret) {
return searchCompletionRanges(query, caret).flatMap(({ start, end, existing, phrase }) => {
const input = query.slice(start, caret).normalize("NFKC").toLowerCase();
const sign = input.startsWith("-") ? "-" : "";
const value = input.slice(sign.length);
const colon = value.indexOf(":");
const namespace = colon === -1 ? void 0 : tagTypes.get(value.slice(0, colon));
if (colon !== -1 && !namespace) return [];
const needle = value.slice(colon + 1).replace(/^"/, "").trim();
if (!needle || /"/.test(needle)) return [];
const prefix = query.slice(0, start);
const suffix = query.slice(end) || " ";
return [{
namespace,
needle,
phrase,
replace(key, label) {
const colon = key.indexOf(":");
const replacement = `${sign}${key.slice(0, colon + 1)}"${key.slice(colon + 1)}"`;
if (existing.has(replacement.toLowerCase())) return;
return {
key,
label,
query: prefix + replacement + suffix,
caret: start + replacement.length + 1
};
}
}];
});
}
var completeTags = async (query, caret, signal) => {
const contexts = tagCompletionContexts(query, caret);
const candidates = contexts.length > 1 ? [contexts[0], contexts.at(-1)] : contexts;
for (const context of candidates) {
if (!context || context.needle.length < 2 && !containsHan.test(context.needle)) continue;
const options = (await findTags(context.needle, context.namespace, signal)).flatMap(({ key, label }) => context.replace(key, label) ?? []);
if (options.length) return options;
}
return [];
};
var dictionaryPath = "@l2studio/[email protected]/dist/index.js";
var dictionarySources = ["https://cdn.jsdelivr.net/npm/" + dictionaryPath, "https://unpkg.com/" + dictionaryPath];
function makeDirectory(source) {
const labels = new Map();
const entries = [];
const groups = new Map(Array.from(source.matchAll(/^ (\w+): \{\r?\n([\s\S]*?)^ \},?$/gm), (match) => [match[1], match[2]]));
for (const [group, type] of tagNamespaces) {
const rows = groups.get(group);
if (!rows) throw new Error("标签词库格式有误。");
for (const [, quoted, bare, text] of rows.matchAll(/^ (?:'((?:\\.|[^'\\])*)'|([\w$]+)): \{ id: \d+, text: '((?:\\.|[^'\\])*)' \},?$/gm)) {
const name = (bare ?? quoted)?.replace(/\\'/g, "'");
const label = text?.replace(/\\'/g, "'").trim().replace(/[\t\r\n]+/g, " ");
if (!name || /["\\\t\r\n]/.test(name)) continue;
const key = type + ":" + name;
const translated = label && containsHan.test(label) && label.toLowerCase() !== name.toLowerCase() ? label : void 0;
if (translated) labels.set(key.toLowerCase(), translated);
entries.push(tagSearchEntry(type, key, name, translated ?? name));
}
}
if (!entries.length) throw new Error("标签词库为空。");
return {
translate: (key) => labels.get(key.trim().toLowerCase()),
complete(query, caret) {
const contexts = tagCompletionContexts(query, caret).filter(({ needle }) => needle.length >= 2 || containsHan.test(needle));
return completeTagEntries(entries, contexts);
}
};
}
var nhAdapter = {
name: "nh",
home: (url) => new URL("/", url).href,
pageCacheGroup: nhPageCacheGroup,
canonicalGalleryUrl,
readerPageUrl,
navigation: nhNavigation,
search(url, query) {
return query ? searchUrl(url, query) : nhAdapter.home(url);
},
completeTags,
parseCommentsResponse,
galleryCommentsUrl,
loadTagDirectory: createTagDirectoryLoader(dictionarySources, async (response) => makeDirectory(await response.text())),
parse(doc, url) {
const reader = readerPath.exec(url.pathname);
if (reader?.[1]) return parseReader(doc, url, reader[1], positiveInteger(reader[2]));
const id = galleryPath.exec(url.pathname)?.[1];
if (id) return parseGallery(doc, url, id);
return parseCatalog(doc, url);
}
};
function makeMap(str) {
const map = Object.create(null);
for (const key of str.split(",")) map[key] = 1;
return (val) => val in map;
}
var EMPTY_OBJ = {};
var EMPTY_ARR = [];
var NOOP = () => {};
var NO = () => false;
var isOn = (key) => key.charCodeAt(0) === 111 && key.charCodeAt(1) === 110 && (key.charCodeAt(2) > 122 || key.charCodeAt(2) < 97);
var isModelListener = (key) => key.startsWith("onUpdate:");
var extend = Object.assign;
var remove = (arr, el) => {
const i = arr.indexOf(el);
if (i > -1) arr.splice(i, 1);
};
var hasOwnProperty$1 = Object.prototype.hasOwnProperty;
var hasOwn = (val, key) => hasOwnProperty$1.call(val, key);
var isArray$1 = Array.isArray;
var isMap = (val) => toTypeString(val) === "[object Map]";
var isSet = (val) => toTypeString(val) === "[object Set]";
var isDate$1 = (val) => toTypeString(val) === "[object Date]";
var isFunction = (val) => typeof val === "function";
var isString$1 = (val) => typeof val === "string";
var isSymbol = (val) => typeof val === "symbol";
var isObject$3 = (val) => val !== null && typeof val === "object";
var isPromise = (val) => {
return (isObject$3(val) || isFunction(val)) && isFunction(val.then) && isFunction(val.catch);
};
var objectToString = Object.prototype.toString;
var toTypeString = (value) => objectToString.call(value);
var toRawType = (value) => {
return toTypeString(value).slice(8, -1);
};
var isPlainObject$2 = (val) => toTypeString(val) === "[object Object]";
var isIntegerKey = (key) => isString$1(key) && key !== "NaN" && key[0] !== "-" && "" + parseInt(key, 10) === key;
var isReservedProp = makeMap(",key,ref,ref_for,ref_key,onVnodeBeforeMount,onVnodeMounted,onVnodeBeforeUpdate,onVnodeUpdated,onVnodeBeforeUnmount,onVnodeUnmounted");
var cacheStringFunction$2 = (fn) => {
const cache = Object.create(null);
return ((str) => {
return cache[str] || (cache[str] = fn(str));
});
};
var camelizeRE$2 = /-\w/g;
var camelize$2 = cacheStringFunction$2((str) => {
return str.replace(camelizeRE$2, (c) => c.slice(1).toUpperCase());
});
var hyphenateRE$2 = /\B([A-Z])/g;
var hyphenate$2 = cacheStringFunction$2((str) => str.replace(hyphenateRE$2, "-$1").toLowerCase());
var capitalize = cacheStringFunction$2((str) => {
return str.charAt(0).toUpperCase() + str.slice(1);
});
var toHandlerKey = cacheStringFunction$2((str) => {
return str ? `on${capitalize(str)}` : ``;
});
var hasChanged = (value, oldValue) => !Object.is(value, oldValue);
var invokeArrayFns = (fns, ...arg) => {
for (let i = 0; i < fns.length; i++) fns[i](...arg);
};
var def = (obj, key, value, writable = false) => {
Object.defineProperty(obj, key, {
configurable: true,
enumerable: false,
writable,
value
});
};
var looseToNumber = (val) => {
const n = parseFloat(val);
return isNaN(n) ? val : n;
};
var toNumber = (val) => {
const n = isString$1(val) ? Number(val) : NaN;
return isNaN(n) ? val : n;
};
var _globalThis;
var getGlobalThis = () => {
return _globalThis || (_globalThis = typeof globalThis !== "undefined" ? globalThis : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : typeof global !== "undefined" ? global : {});
};
function normalizeStyle(value) {
if (isArray$1(value)) {
const res = {};
for (let i = 0; i < value.length; i++) {
const item = value[i];
const normalized = isString$1(item) ? parseStringStyle(item) : normalizeStyle(item);
if (normalized) for (const key in normalized) res[key] = normalized[key];
}
return res;
} else if (isString$1(value) || isObject$3(value)) return value;
}
var listDelimiterRE = /;(?![^(]*\))/g;
var propertyDelimiterRE = /:([^]+)/;
var styleCommentRE = /"(?:[^"\\]|\\[^])*"|'(?:[^'\\]|\\[^])*'|\\[^]|\/\*[^]*?\*\//g;
function parseStringStyle(cssText) {
const ret = {};
cssText.replace(styleCommentRE, (match) => match.startsWith("/*") ? "" : match).split(listDelimiterRE).forEach((item) => {
if (item) {
const tmp = item.split(propertyDelimiterRE);
tmp.length > 1 && (ret[tmp[0].trim()] = tmp[1].trim());
}
});
return ret;
}
function normalizeClass(value) {
let res = "";
if (isString$1(value)) res = value;
else if (isArray$1(value)) for (let i = 0; i < value.length; i++) {
const normalized = normalizeClass(value[i]);
if (normalized) res += normalized + " ";
}
else if (isObject$3(value)) {
for (const name in value) if (value[name]) res += name + " ";
}
return res.trim();
}
var isSpecialBooleanAttr = makeMap(`itemscope,allowfullscreen,disablepictureinpicture,disableremoteplayback,formnovalidate,ismap,nomodule,novalidate,playsinline,readonly`);
function includeBooleanAttr(value) {
return !!value || value === "";
}
function looseCompareArrays(a, b, seen) {
if (a.length !== b.length) return false;
let equal = true;
for (let i = 0; equal && i < a.length; i++) equal = looseEqual(a[i], b[i], seen);
return equal;
}
function looseCompareCollections(a, b, seen) {
if (a.size !== b.size) return false;
const candidates = Array.from(b);
const matched = new Uint8Array(candidates.length);
for (const item of a) {
let index = -1;
for (let i = 0; i < candidates.length; i++) if (!matched[i] && looseEqual(item, candidates[i], seen)) {
index = i;
break;
}
if (index < 0) return false;
matched[index] = 1;
}
return true;
}
function looseCompareObjects(a, b, seen) {
let aValidType = isMap(a);
let bValidType = isMap(b);
if (aValidType || bValidType) return aValidType && bValidType ? looseCompareCollections(a, b, seen) : false;
aValidType = isSet(a);
bValidType = isSet(b);
if (aValidType || bValidType) return aValidType && bValidType ? looseCompareCollections(a, b, seen) : false;
if (Object.keys(a).length !== Object.keys(b).length) return false;
for (const key in a) {
const aHasKey = a.hasOwnProperty(key);
const bHasKey = b.hasOwnProperty(key);
if (aHasKey && !bHasKey || !aHasKey && bHasKey || !looseEqual(a[key], b[key], seen)) return false;
}
return String(a) === String(b);
}
function looseCompareNested(a, b, seen, compare) {
if (!seen) seen = [new Map(), new Map()];
const [seenA, seenB] = seen;
if (seenA.has(a) || seenB.has(b)) return seenA.get(a) === b && seenB.get(b) === a;
seenA.set(a, b);
seenB.set(b, a);
const equal = compare(a, b, seen);
seenA.delete(a);
seenB.delete(b);
return equal;
}
function looseEqual(a, b, seen) {
if (a === b) return true;
let aValidType = isDate$1(a);
let bValidType = isDate$1(b);
if (aValidType || bValidType) return aValidType && bValidType ? a.getTime() === b.getTime() : false;
aValidType = isSymbol(a);
bValidType = isSymbol(b);
if (aValidType || bValidType) return a === b;
aValidType = isArray$1(a);
bValidType = isArray$1(b);
if (aValidType || bValidType) return aValidType && bValidType ? looseCompareNested(a, b, seen, looseCompareArrays) : false;
aValidType = isObject$3(a);
bValidType = isObject$3(b);
if (aValidType || bValidType) {
if (!aValidType || !bValidType) return false;
return looseCompareNested(a, b, seen, looseCompareObjects);
}
return String(a) === String(b);
}
function looseIndexOf(arr, val) {
return arr.findIndex((item) => looseEqual(item, val));
}
var isRef$1 = (val) => {
return !!(val && val["__v_isRef"] === true);
};
var toDisplayString = (val) => {
return isString$1(val) ? val : val == null ? "" : isArray$1(val) || isObject$3(val) && (val.toString === objectToString || !isFunction(val.toString)) ? isRef$1(val) ? toDisplayString(val.value) : JSON.stringify(val, replacer, 2) : String(val);
};
var replacer = (_key, val) => {
if (isRef$1(val)) return replacer(_key, val.value);
else if (isMap(val)) return { [`Map(${val.size})`]: [...val.entries()].reduce((entries, [key, val2], i) => {
entries[stringifySymbol(key, i) + " =>"] = val2;
return entries;
}, {}) };
else if (isSet(val)) return { [`Set(${val.size})`]: [...val.values()].map((v) => stringifySymbol(v)) };
else if (isSymbol(val)) return stringifySymbol(val);
else if (isObject$3(val) && !isArray$1(val) && !isPlainObject$2(val)) return String(val);
return val;
};
var stringifySymbol = (v, i = "") => {
var _a;
return isSymbol(v) ? `Symbol(${(_a = v.description) != null ? _a : i})` : v;
};
var activeEffectScope;
var EffectScope = class {
constructor(detached = false) {
this.detached = detached;
this._active = true;
this._on = 0;
this.effects = [];
this.cleanups = [];
this._isPaused = false;
this._warnOnRun = true;
this.__v_skip = true;
if (!detached && activeEffectScope) {
if (activeEffectScope.active) {
this.parent = activeEffectScope;
this.index = (activeEffectScope.scopes || (activeEffectScope.scopes = [])).push(this) - 1;
} else {
this._active = false;
this._warnOnRun = false;
}
}
}
get active() {
return this._active;
}
pause() {
if (this._active) {
this._isPaused = true;
let i, l;
if (this.scopes) {
const scopes = this.scopes.slice();
for (i = 0, l = scopes.length; i < l; i++) scopes[i].pause();
}
for (i = 0, l = this.effects.length; i < l; i++) this.effects[i].pause();
}
}
resume() {
if (this._active) {
if (this._isPaused) {
this._isPaused = false;
let i, l;
if (this.scopes) {
const scopes = this.scopes.slice();
for (i = 0, l = scopes.length; i < l; i++) scopes[i].resume();
}
const effects = this.effects.slice();
for (i = 0, l = effects.length; i < l; i++) effects[i].resume();
}
}
}
run(fn) {
if (this._active) {
const currentEffectScope = activeEffectScope;
try {
activeEffectScope = this;
return fn();
} finally {
activeEffectScope = currentEffectScope;
}
}
}
on() {
if (++this._on === 1) {
this.prevScope = activeEffectScope;
activeEffectScope = this;
}
}
off() {
if (this._on > 0 && --this._on === 0) {
if (activeEffectScope === this) activeEffectScope = this.prevScope;
else {
let current = activeEffectScope;
while (current) {
if (current.prevScope === this) {
current.prevScope = this.prevScope;
break;
}
current = current.prevScope;
}
}
this.prevScope = void 0;
}
}
stop(fromParent) {
if (this._active) {
this._active = false;
let i, l;
for (i = 0, l = this.effects.length; i < l; i++) this.effects[i].stop();
this.effects.length = 0;
for (i = 0, l = this.cleanups.length; i < l; i++) this.cleanups[i]();
this.cleanups.length = 0;
if (this.scopes) {
const scopes = this.scopes.slice();
for (i = 0, l = scopes.length; i < l; i++) scopes[i].stop(true);
this.scopes.length = 0;
}
if (!this.detached && this.parent && !fromParent) {
const last = this.parent.scopes.pop();
if (last && last !== this) {
this.parent.scopes[this.index] = last;
last.index = this.index;
}
}
this.parent = void 0;
}
}
};
function effectScope(detached) {
return new EffectScope(detached);
}
function getCurrentScope() {
return activeEffectScope;
}
function onScopeDispose(fn, failSilently = false) {
if (activeEffectScope) {
if (activeEffectScope.active) activeEffectScope.cleanups.push(fn);
else fn();
}
}
var activeSub;
var pausedQueueEffects = new WeakSet();
var ReactiveEffect = class {
constructor(fn) {
this.fn = fn;
this.deps = void 0;
this.depsTail = void 0;
this.flags = 5;
this.next = void 0;
this.cleanup = void 0;
this.scheduler = void 0;
if (activeEffectScope) {
if (activeEffectScope.active) activeEffectScope.effects.push(this);
else this.flags &= -2;
}
}
pause() {
this.flags |= 64;
}
resume() {
if (this.flags & 64) {
this.flags &= -65;
if (pausedQueueEffects.has(this)) {
pausedQueueEffects.delete(this);
this.trigger();
}
}
}
notify() {
if (this.flags & 2 && !(this.flags & 32)) return;
if (!(this.flags & 8)) batch(this);
}
run() {
if (!(this.flags & 1)) return this.fn();
this.flags |= 2;
cleanupEffect(this);
prepareDeps(this);
const prevEffect = activeSub;
const prevShouldTrack = shouldTrack;
activeSub = this;
shouldTrack = true;
try {
return this.fn();
} finally {
cleanupDeps(this);
activeSub = prevEffect;
shouldTrack = prevShouldTrack;
this.flags &= -3;
}
}
stop() {
if (this.flags & 1) {
for (let link = this.deps; link; link = link.nextDep) removeSub(link);
this.deps = this.depsTail = void 0;
cleanupEffect(this);
this.onStop && this.onStop();
this.flags &= -2;
}
}
trigger() {
if (this.flags & 64) pausedQueueEffects.add(this);
else if (this.scheduler) this.scheduler();
else this.runIfDirty();
}
runIfDirty() {
if (isDirty(this)) this.run();
}
get dirty() {
return isDirty(this);
}
};
var batchDepth = 0;
var batchedSub;
var batchedComputed;
function batch(sub, isComputed = false) {
sub.flags |= 8;
if (isComputed) {
sub.next = batchedComputed;
batchedComputed = sub;
return;
}
sub.next = batchedSub;
batchedSub = sub;
}
function startBatch() {
batchDepth++;
}
function endBatch() {
if (--batchDepth > 0) return;
if (batchedComputed) {
let e = batchedComputed;
batchedComputed = void 0;
while (e) {
const next = e.next;
e.next = void 0;
e.flags &= -9;
e = next;
}
}
let error;
while (batchedSub) {
let e = batchedSub;
batchedSub = void 0;
while (e) {
const next = e.next;
e.next = void 0;
e.flags &= -9;
if (e.flags & 1) try {
e.trigger();
} catch (err) {
if (!error) error = err;
}
e = next;
}
}
if (error) throw error;
}
function prepareDeps(sub) {
for (let link = sub.deps; link; link = link.nextDep) {
link.version = -1;
link.prevActiveLink = link.dep.activeLink;
link.dep.activeLink = link;
}
}
function cleanupDeps(sub) {
let head;
let tail = sub.depsTail;
let link = tail;
while (link) {
const prev = link.prevDep;
if (link.version === -1) {
if (link === tail) tail = prev;
removeSub(link);
removeDep(link);
} else head = link;
link.dep.activeLink = link.prevActiveLink;
link.prevActiveLink = void 0;
link = prev;
}
sub.deps = head;
sub.depsTail = tail;
}
function isDirty(sub) {
for (let link = sub.deps; link; link = link.nextDep) if (link.dep.version !== link.version || link.dep.computed && (refreshComputed(link.dep.computed) || link.dep.version !== link.version)) return true;
if (sub._dirty) return true;
return false;
}
function refreshComputed(computed) {
if (computed.flags & 4 && !(computed.flags & 16)) return;
computed.flags &= -17;
if (computed.globalVersion === globalVersion) return;
computed.globalVersion = globalVersion;
if (!computed.isSSR && computed.flags & 128 && (!computed.deps && !computed._dirty || !isDirty(computed))) return;
computed.flags |= 2;
const dep = computed.dep;
const prevSub = activeSub;
const prevShouldTrack = shouldTrack;
activeSub = computed;
shouldTrack = true;
try {
prepareDeps(computed);
const value = computed.fn(computed._value);
if (dep.version === 0 || hasChanged(value, computed._value)) {
computed.flags |= 128;
computed._value = value;
dep.version++;
}
} catch (err) {
dep.version++;
throw err;
} finally {
activeSub = prevSub;
shouldTrack = prevShouldTrack;
cleanupDeps(computed);
computed.flags &= -3;
}
}
function removeSub(link, soft = false) {
const { dep, prevSub, nextSub } = link;
if (prevSub) {
prevSub.nextSub = nextSub;
link.prevSub = void 0;
}
if (nextSub) {
nextSub.prevSub = prevSub;
link.nextSub = void 0;
}
if (dep.subs === link) {
dep.subs = prevSub;
if (!prevSub && dep.computed) {
dep.computed.flags &= -5;
for (let l = dep.computed.deps; l; l = l.nextDep) removeSub(l, true);
}
}
if (!soft && !--dep.sc && dep.map) dep.map.delete(dep.key);
}
function removeDep(link) {
const { prevDep, nextDep } = link;
if (prevDep) {
prevDep.nextDep = nextDep;
link.prevDep = void 0;
}
if (nextDep) {
nextDep.prevDep = prevDep;
link.nextDep = void 0;
}
}
var shouldTrack = true;
var trackStack = [];
function pauseTracking() {
trackStack.push(shouldTrack);
shouldTrack = false;
}
function resetTracking() {
const last = trackStack.pop();
shouldTrack = last === void 0 ? true : last;
}
function cleanupEffect(e) {
const { cleanup } = e;
e.cleanup = void 0;
if (cleanup) {
const prevSub = activeSub;
activeSub = void 0;
try {
cleanup();
} finally {
activeSub = prevSub;
}
}
}
var globalVersion = 0;
var Link = class {
constructor(sub, dep) {
this.sub = sub;
this.dep = dep;
this.version = dep.version;
this.nextDep = this.prevDep = this.nextSub = this.prevSub = this.prevActiveLink = void 0;
}
};
var Dep = class {
constructor(computed) {
this.computed = computed;
this.version = 0;
this.activeLink = void 0;
this.subs = void 0;
this.map = void 0;
this.key = void 0;
this.sc = 0;
this.__v_skip = true;
}
track(debugInfo) {
if (!activeSub || !shouldTrack || activeSub === this.computed) return;
let link = this.activeLink;
if (link === void 0 || link.sub !== activeSub) {
link = this.activeLink = new Link(activeSub, this);
if (!activeSub.deps) activeSub.deps = activeSub.depsTail = link;
else {
link.prevDep = activeSub.depsTail;
activeSub.depsTail.nextDep = link;
activeSub.depsTail = link;
}
addSub(link);
} else if (link.version === -1) {
link.version = this.version;
if (link.nextDep) {
const next = link.nextDep;
next.prevDep = link.prevDep;
if (link.prevDep) link.prevDep.nextDep = next;
link.prevDep = activeSub.depsTail;
link.nextDep = void 0;
activeSub.depsTail.nextDep = link;
activeSub.depsTail = link;
if (activeSub.deps === link) activeSub.deps = next;
}
}
return link;
}
trigger(debugInfo) {
this.version++;
globalVersion++;
this.notify(debugInfo);
}
notify(debugInfo) {
startBatch();
try {
for (let link = this.subs; link; link = link.prevSub) if (link.sub.notify()) link.sub.dep.notify();
} finally {
endBatch();
}
}
};
function addSub(link) {
link.dep.sc++;
if (link.sub.flags & 4) {
const computed = link.dep.computed;
if (computed && !link.dep.subs) {
computed.flags |= 20;
for (let l = computed.deps; l; l = l.nextDep) addSub(l);
}
const currentTail = link.dep.subs;
if (currentTail !== link) {
link.prevSub = currentTail;
if (currentTail) currentTail.nextSub = link;
}
link.dep.subs = link;
}
}
var targetMap = new WeakMap();
var ITERATE_KEY = Symbol("");
var MAP_KEY_ITERATE_KEY = Symbol("");
var ARRAY_ITERATE_KEY = Symbol("");
function track(target, type, key) {
if (shouldTrack && activeSub) {
let depsMap = targetMap.get(target);
if (!depsMap) targetMap.set(target, depsMap = new Map());
let dep = depsMap.get(key);
if (!dep) {
depsMap.set(key, dep = new Dep());
dep.map = depsMap;
dep.key = key;
}
dep.track();
}
}
function trigger(target, type, key, newValue, oldValue, oldTarget) {
const depsMap = targetMap.get(target);
if (!depsMap) {
globalVersion++;
return;
}
const run = (dep) => {
if (dep) dep.trigger();
};
startBatch();
if (type === "clear") depsMap.forEach(run);
else {
const targetIsArray = isArray$1(target);
const isArrayIndex = targetIsArray && isIntegerKey(key);
if (targetIsArray && key === "length") {
const newLength = Number(newValue);
depsMap.forEach((dep, key2) => {
if (key2 === "length" || key2 === ARRAY_ITERATE_KEY || !isSymbol(key2) && key2 >= newLength) run(dep);
});
} else {
if (key !== void 0 || depsMap.has(void 0)) run(depsMap.get(key));
if (isArrayIndex) run(depsMap.get(ARRAY_ITERATE_KEY));
switch (type) {
case "add":
if (!targetIsArray) {
run(depsMap.get(ITERATE_KEY));
if (isMap(target)) run(depsMap.get(MAP_KEY_ITERATE_KEY));
} else if (isArrayIndex) run(depsMap.get("length"));
break;
case "delete":
if (!targetIsArray) {
run(depsMap.get(ITERATE_KEY));
if (isMap(target)) run(depsMap.get(MAP_KEY_ITERATE_KEY));
}
break;
case "set": if (isMap(target)) run(depsMap.get(ITERATE_KEY));
}
}
}
endBatch();
}
function getDepFromReactive(object, key) {
const depMap = targetMap.get(object);
return depMap && depMap.get(key);
}
function reactiveReadArray(array) {
const raw = toRaw(array);
if (raw === array) return raw;
track(raw, "iterate", ARRAY_ITERATE_KEY);
if (isShallow(array)) return raw;
if (!isReadonly(array)) return raw.map(toReactive);
return isReactive(array) ? raw.map((item) => toReadonly(toReactive(item))) : raw.map(toReadonly);
}
function shallowReadArray(arr) {
track(arr = toRaw(arr), "iterate", ARRAY_ITERATE_KEY);
return arr;
}
function toWrapped(target, item) {
if (isReadonly(target)) return isReactive(target) ? toReadonly(toReactive(item)) : toReadonly(item);
return toReactive(item);
}
var arrayInstrumentations = {
__proto__: null,
[Symbol.iterator]() {
return iterator(this, Symbol.iterator, (item) => toWrapped(this, item));
},
concat(...args) {
return reactiveReadArray(this).concat(...args.map((x) => isArray$1(x) ? reactiveReadArray(x) : x));
},
entries() {
return iterator(this, "entries", (value) => {
value[1] = toWrapped(this, value[1]);
return value;
});
},
every(fn, thisArg) {
return apply(this, "every", fn, thisArg, void 0, arguments);
},
filter(fn, thisArg) {
return apply(this, "filter", fn, thisArg, (v) => v.map((item) => toWrapped(this, item)), arguments);
},
find(fn, thisArg) {
return apply(this, "find", fn, thisArg, (item) => toWrapped(this, item), arguments);
},
findIndex(fn, thisArg) {
return apply(this, "findIndex", fn, thisArg, void 0, arguments);
},
findLast(fn, thisArg) {
return apply(this, "findLast", fn, thisArg, (item) => toWrapped(this, item), arguments);
},
findLastIndex(fn, thisArg) {
return apply(this, "findLastIndex", fn, thisArg, void 0, arguments);
},
forEach(fn, thisArg) {
return apply(this, "forEach", fn, thisArg, void 0, arguments);
},
includes(...args) {
return searchProxy(this, "includes", args);
},
indexOf(...args) {
return searchProxy(this, "indexOf", args);
},
join(separator) {
return reactiveReadArray(this).join(separator);
},
lastIndexOf(...args) {
return searchProxy(this, "lastIndexOf", args);
},
map(fn, thisArg) {
return apply(this, "map", fn, thisArg, void 0, arguments);
},
pop() {
return noTracking(this, "pop");
},
push(...args) {
return noTracking(this, "push", args);
},
reduce(fn, ...args) {
return reduce(this, "reduce", fn, args);
},
reduceRight(fn, ...args) {
return reduce(this, "reduceRight", fn, args);
},
shift() {
return noTracking(this, "shift");
},
some(fn, thisArg) {
return apply(this, "some", fn, thisArg, void 0, arguments);
},
splice(...args) {
return noTracking(this, "splice", args);
},
toReversed() {
return reactiveReadArray(this).toReversed();
},
toSorted(comparer) {
return reactiveReadArray(this).toSorted(comparer);
},
toSpliced(...args) {
return reactiveReadArray(this).toSpliced(...args);
},
unshift(...args) {
return noTracking(this, "unshift", args);
},
values() {
return iterator(this, "values", (item) => toWrapped(this, item));
}
};
function iterator(self, method, wrapValue) {
const arr = shallowReadArray(self);
const methodFn = arr[method];
const iter = methodFn.call(arr);
if (arr !== self && !isShallow(self)) {
if (iter[Symbol.toStringTag] === "Array Iterator") {
const wrapped = Object.create(Object.getPrototypeOf(iter));
wrapped.next = () => wrapResult(iter.next(), wrapValue);
if (methodFn !== arrayProto[method]) Object.defineProperties(wrapped, {
return: { get() {
const fn = iter.return;
return typeof fn === "function" ? fn.bind(iter) : fn;
} },
throw: { get() {
const fn = iter.throw;
return typeof fn === "function" ? fn.bind(iter) : fn;
} }
});
return wrapped;
}
iter._next = iter.next;
iter.next = () => wrapResult(iter._next(), wrapValue);
}
return iter;
}
function wrapResult(result, wrapValue) {
if (!result.done) result.value = wrapValue(result.value);
return result;
}
var arrayProto = Array.prototype;
function apply(self, method, fn, thisArg, wrappedRetFn, args) {
const arr = shallowReadArray(self);
const needsWrap = arr !== self && !isShallow(self);
const methodFn = arr[method];
if (methodFn !== arrayProto[method]) {
const result2 = methodFn.apply(self, args);
return needsWrap ? toReactive(result2) : result2;
}
let wrappedFn = fn;
if (arr !== self) {
if (needsWrap) wrappedFn = function(item, index) {
return fn.call(this, toWrapped(self, item), index, self);
};
else if (fn.length > 2) wrappedFn = function(item, index) {
return fn.call(this, item, index, self);
};
}
const result = methodFn.call(arr, wrappedFn, thisArg);
return needsWrap && wrappedRetFn ? wrappedRetFn(result) : result;
}
function reduce(self, method, fn, args) {
const arr = shallowReadArray(self);
const needsWrap = arr !== self && !isShallow(self);
let wrappedFn = fn;
let wrapInitialAccumulator = false;
if (arr !== self) {
if (needsWrap) {
wrapInitialAccumulator = args.length === 0;
wrappedFn = function(acc, item, index) {
if (wrapInitialAccumulator) {
wrapInitialAccumulator = false;
acc = toWrapped(self, acc);
}
return fn.call(this, acc, toWrapped(self, item), index, self);
};
} else if (fn.length > 3) wrappedFn = function(acc, item, index) {
return fn.call(this, acc, item, index, self);
};
}
const result = arr[method](wrappedFn, ...args);
return wrapInitialAccumulator ? toWrapped(self, result) : result;
}
function searchProxy(self, method, args) {
const arr = toRaw(self);
track(arr, "iterate", ARRAY_ITERATE_KEY);
const res = arr[method](...args);
if ((res === -1 || res === false) && isProxy(args[0])) {
args[0] = toRaw(args[0]);
return arr[method](...args);
}
return res;
}
function noTracking(self, method, args = []) {
pauseTracking();
startBatch();
const res = toRaw(self)[method].apply(self, args);
endBatch();
resetTracking();
return res;
}
var isNonTrackableKeys = makeMap(`__proto__,__v_isRef,__isVue`);
var builtInSymbols = new Set(Object.getOwnPropertyNames(Symbol).filter((key) => key !== "arguments" && key !== "caller").map((key) => Symbol[key]).filter(isSymbol));
function hasOwnProperty(key) {
if (!isSymbol(key)) key = String(key);
const obj = toRaw(this);
track(obj, "has", key);
return obj.hasOwnProperty(key);
}
var BaseReactiveHandler = class {
constructor(_isReadonly = false, _isShallow = false) {
this._isReadonly = _isReadonly;
this._isShallow = _isShallow;
}
get(target, key, receiver) {
if (key === "__v_skip") return target["__v_skip"];
const isReadonly2 = this._isReadonly, isShallow2 = this._isShallow;
if (key === "__v_isReactive") return !isReadonly2;
else if (key === "__v_isReadonly") return isReadonly2;
else if (key === "__v_isShallow") return isShallow2;
else if (key === "__v_raw") {
if (receiver === (isReadonly2 ? isShallow2 ? shallowReadonlyMap : readonlyMap : isShallow2 ? shallowReactiveMap : reactiveMap).get(target) || Object.getPrototypeOf(target) === Object.getPrototypeOf(receiver)) return target;
return;
}
const targetIsArray = isArray$1(target);
if (!isReadonly2) {
let fn;
if (targetIsArray && (fn = arrayInstrumentations[key])) return fn;
if (key === "hasOwnProperty") return hasOwnProperty;
}
const res = Reflect.get(target, key, isRef(target) ? target : receiver);
if (isSymbol(key) ? builtInSymbols.has(key) : isNonTrackableKeys(key)) return res;
if (!isReadonly2) track(target, "get", key);
if (isShallow2) return res;
if (isRef(res)) {
const value = targetIsArray && isIntegerKey(key) ? res : res.value;
return isReadonly2 && isObject$3(value) ? readonly(value) : value;
}
if (isObject$3(res)) return isReadonly2 ? readonly(res) : reactive(res);
return res;
}
};
var MutableReactiveHandler = class extends BaseReactiveHandler {
constructor(isShallow2 = false) {
super(false, isShallow2);
}
set(target, key, value, receiver) {
let oldValue = target[key];
const isArrayWithIntegerKey = isArray$1(target) && isIntegerKey(key);
if (!this._isShallow) {
const isOldValueReadonly = isReadonly(oldValue);
if (!isShallow(value) && !isReadonly(value)) {
oldValue = toRaw(oldValue);
value = toRaw(value);
}
if (!isArrayWithIntegerKey && isRef(oldValue) && !isRef(value)) {
if (isOldValueReadonly) return true;
else {
oldValue.value = value;
return true;
}
}
}
const hadKey = isArrayWithIntegerKey ? Number(key) < target.length : hasOwn(target, key);
const result = Reflect.set(target, key, value, isRef(target) ? target : receiver);
if (target === toRaw(receiver) && result) {
if (!hadKey) trigger(target, "add", key, value);
else if (hasChanged(value, oldValue)) trigger(target, "set", key, value, oldValue);
}
return result;
}
deleteProperty(target, key) {
const hadKey = hasOwn(target, key);
const oldValue = target[key];
const result = Reflect.deleteProperty(target, key);
if (result && hadKey) trigger(target, "delete", key, void 0, oldValue);
return result;
}
has(target, key) {
const result = Reflect.has(target, key);
if (!isSymbol(key) || !builtInSymbols.has(key)) track(target, "has", key);
return result;
}
ownKeys(target) {
track(target, "iterate", isArray$1(target) ? "length" : ITERATE_KEY);
return Reflect.ownKeys(target);
}
};
var ReadonlyReactiveHandler = class extends BaseReactiveHandler {
constructor(isShallow2 = false) {
super(true, isShallow2);
}
set(target, key) {
return true;
}
deleteProperty(target, key) {
return true;
}
};
var mutableHandlers = new MutableReactiveHandler();
var readonlyHandlers = new ReadonlyReactiveHandler();
var shallowReactiveHandlers = new MutableReactiveHandler(true);
var shallowReadonlyHandlers = new ReadonlyReactiveHandler(true);
var toShallow = (value) => value;
var getProto = (v) => Reflect.getPrototypeOf(v);
function createIterableMethod(method, isReadonly2, isShallow2) {
return function(...args) {
const target = this["__v_raw"];
const rawTarget = toRaw(target);
const targetIsMap = isMap(rawTarget);
const isPair = method === "entries" || method === Symbol.iterator && targetIsMap;
const isKeyOnly = method === "keys" && targetIsMap;
const innerIterator = target[method](...args);
const wrap = isShallow2 ? toShallow : isReadonly2 ? toReadonly : toReactive;
!isReadonly2 && track(rawTarget, "iterate", isKeyOnly ? MAP_KEY_ITERATE_KEY : ITERATE_KEY);
return extend(Object.create(innerIterator), { next() {
const { value, done } = innerIterator.next();
return done ? {
value,
done
} : {
value: isPair ? [wrap(value[0]), wrap(value[1])] : wrap(value),
done
};
} });
};
}
function createReadonlyMethod(type) {
return function(...args) {
return type === "delete" ? false : type === "clear" ? void 0 : this;
};
}
function createInstrumentations(readonly, shallow) {
const instrumentations = {
get(key) {
const target = this["__v_raw"];
const rawTarget = toRaw(target);
const rawKey = toRaw(key);
if (!readonly) {
if (hasChanged(key, rawKey)) track(rawTarget, "get", key);
track(rawTarget, "get", rawKey);
}
const { has } = getProto(rawTarget);
const wrap = shallow ? toShallow : readonly ? toReadonly : toReactive;
if (has.call(rawTarget, key)) return wrap(target.get(key));
else if (has.call(rawTarget, rawKey)) return wrap(target.get(rawKey));
else if (target !== rawTarget) target.get(key);
},
get size() {
const target = this["__v_raw"];
!readonly && track(toRaw(target), "iterate", ITERATE_KEY);
return target.size;
},
has(key) {
const target = this["__v_raw"];
const rawTarget = toRaw(target);
const rawKey = toRaw(key);
if (!readonly) {
if (hasChanged(key, rawKey)) track(rawTarget, "has", key);
track(rawTarget, "has", rawKey);
}
return key === rawKey ? target.has(key) : target.has(key) || target.has(rawKey);
},
forEach(callback, thisArg) {
const observed = this;
const target = observed["__v_raw"];
const rawTarget = toRaw(target);
const wrap = shallow ? toShallow : readonly ? toReadonly : toReactive;
!readonly && track(rawTarget, "iterate", ITERATE_KEY);
return target.forEach((value, key) => {
return callback.call(thisArg, wrap(value), wrap(key), observed);
});
}
};
extend(instrumentations, readonly ? {
add: createReadonlyMethod("add"),
set: createReadonlyMethod("set"),
delete: createReadonlyMethod("delete"),
clear: createReadonlyMethod("clear")
} : {
add(value) {
const target = toRaw(this);
const proto = getProto(target);
const rawValue = toRaw(value);
const valueToAdd = !shallow && !isShallow(value) && !isReadonly(value) ? rawValue : value;
if (!(proto.has.call(target, valueToAdd) || hasChanged(value, valueToAdd) && proto.has.call(target, value) || hasChanged(rawValue, valueToAdd) && proto.has.call(target, rawValue))) {
target.add(valueToAdd);
trigger(target, "add", valueToAdd, valueToAdd);
}
return this;
},
set(key, value) {
if (!shallow && !isShallow(value) && !isReadonly(value)) value = toRaw(value);
const target = toRaw(this);
const { has, get } = getProto(target);
let hadKey = has.call(target, key);
if (!hadKey) {
key = toRaw(key);
hadKey = has.call(target, key);
}
const oldValue = get.call(target, key);
target.set(key, value);
if (!hadKey) trigger(target, "add", key, value);
else if (hasChanged(value, oldValue)) trigger(target, "set", key, value, oldValue);
return this;
},
delete(key) {
const target = toRaw(this);
const { has, get } = getProto(target);
let hadKey = has.call(target, key);
if (!hadKey) {
key = toRaw(key);
hadKey = has.call(target, key);
}
const oldValue = get ? get.call(target, key) : void 0;
const result = target.delete(key);
if (hadKey) trigger(target, "delete", key, void 0, oldValue);
return result;
},
clear() {
const target = toRaw(this);
const hadItems = target.size !== 0;
const oldTarget = void 0;
const result = target.clear();
if (hadItems) trigger(target, "clear", void 0, void 0, oldTarget);
return result;
}
});
[
"keys",
"values",
"entries",
Symbol.iterator
].forEach((method) => {
instrumentations[method] = createIterableMethod(method, readonly, shallow);
});
return instrumentations;
}
function createInstrumentationGetter(isReadonly2, shallow) {
const instrumentations = createInstrumentations(isReadonly2, shallow);
return (target, key, receiver) => {
if (key === "__v_isReactive") return !isReadonly2;
else if (key === "__v_isReadonly") return isReadonly2;
else if (key === "__v_isShallow") return shallow;
else if (key === "__v_raw") return target;
return Reflect.get(hasOwn(instrumentations, key) && key in target ? instrumentations : target, key, receiver);
};
}
var mutableCollectionHandlers = { get: createInstrumentationGetter(false, false) };
var shallowCollectionHandlers = { get: createInstrumentationGetter(false, true) };
var readonlyCollectionHandlers = { get: createInstrumentationGetter(true, false) };
var shallowReadonlyCollectionHandlers = { get: createInstrumentationGetter(true, true) };
var reactiveMap = new WeakMap();
var shallowReactiveMap = new WeakMap();
var readonlyMap = new WeakMap();
var shallowReadonlyMap = new WeakMap();
function targetTypeMap(rawType) {
switch (rawType) {
case "Object":
case "Array": return 1;
case "Map":
case "Set":
case "WeakMap":
case "WeakSet": return 2;
default: return 0;
}
}
function reactive(target) {
if (isReadonly(target)) return target;
return createReactiveObject(target, false, mutableHandlers, mutableCollectionHandlers, reactiveMap);
}
function shallowReactive(target) {
return createReactiveObject(target, false, shallowReactiveHandlers, shallowCollectionHandlers, shallowReactiveMap);
}
function readonly(target) {
return createReactiveObject(target, true, readonlyHandlers, readonlyCollectionHandlers, readonlyMap);
}
function shallowReadonly(target) {
return createReactiveObject(target, true, shallowReadonlyHandlers, shallowReadonlyCollectionHandlers, shallowReadonlyMap);
}
function createReactiveObject(target, isReadonly2, baseHandlers, collectionHandlers, proxyMap) {
if (!isObject$3(target)) return target;
if (target["__v_raw"] && !(isReadonly2 && target["__v_isReactive"])) return target;
if (target["__v_skip"] || !Object.isExtensible(target)) return target;
const existingProxy = proxyMap.get(target);
if (existingProxy) return existingProxy;
const targetType = targetTypeMap(toRawType(target));
if (targetType === 0) return target;
const proxy = new Proxy(target, targetType === 2 ? collectionHandlers : baseHandlers);
proxyMap.set(target, proxy);
return proxy;
}
function isReactive(value) {
if (isReadonly(value)) return isReactive(value["__v_raw"]);
return !!(value && value["__v_isReactive"]);
}
function isReadonly(value) {
return !!(value && value["__v_isReadonly"]);
}
function isShallow(value) {
return !!(value && value["__v_isShallow"]);
}
function isProxy(value) {
return value ? !!value["__v_raw"] : false;
}
function toRaw(observed) {
const raw = observed && observed["__v_raw"];
return raw ? toRaw(raw) : observed;
}
function markRaw(value) {
if (!hasOwn(value, "__v_skip") && Object.isExtensible(value)) def(value, "__v_skip", true);
return value;
}
var toReactive = (value) => isObject$3(value) ? reactive(value) : value;
var toReadonly = (value) => isObject$3(value) ? readonly(value) : value;
function isRef(r) {
return r ? r["__v_isRef"] === true : false;
}
function ref(value) {
return createRef(value, false);
}
function shallowRef(value) {
return createRef(value, true);
}
function createRef(rawValue, shallow) {
if (isRef(rawValue)) return rawValue;
return new RefImpl(rawValue, shallow);
}
var RefImpl = class {
constructor(value, isShallow2) {
this.dep = new Dep();
this["__v_isRef"] = true;
this["__v_isShallow"] = false;
this._rawValue = isShallow2 ? value : toRaw(value);
this._value = isShallow2 ? value : toReactive(value);
this["__v_isShallow"] = isShallow2;
}
get value() {
this.dep.track();
return this._value;
}
set value(newValue) {
const oldValue = this._rawValue;
const useDirectValue = this["__v_isShallow"] || isShallow(newValue) || isReadonly(newValue);
newValue = useDirectValue ? newValue : toRaw(newValue);
if (hasChanged(newValue, oldValue)) {
this._rawValue = newValue;
this._value = useDirectValue ? newValue : toReactive(newValue);
this.dep.trigger();
}
}
};
function triggerRef(ref2) {
if (ref2.dep) ref2.dep.trigger();
}
function unref(ref2) {
return isRef(ref2) ? ref2.value : ref2;
}
function toValue(source) {
return isFunction(source) ? source() : unref(source);
}
var shallowUnwrapHandlers = {
get: (target, key, receiver) => key === "__v_raw" ? target : unref(Reflect.get(target, key, receiver)),
set: (target, key, value, receiver) => {
const oldValue = target[key];
if (isRef(oldValue) && !isRef(value)) {
oldValue.value = value;
return true;
} else return Reflect.set(target, key, value, receiver);
}
};
function proxyRefs(objectWithRefs) {
return isReactive(objectWithRefs) ? objectWithRefs : new Proxy(objectWithRefs, shallowUnwrapHandlers);
}
var CustomRefImpl = class {
constructor(factory) {
this["__v_isRef"] = true;
this._value = void 0;
const dep = this.dep = new Dep();
const { get, set } = factory(dep.track.bind(dep), dep.trigger.bind(dep));
this._get = get;
this._set = set;
}
get value() {
return this._value = this._get();
}
set value(newVal) {
this._set(newVal);
}
};
function customRef(factory) {
return new CustomRefImpl(factory);
}
function toRefs(object) {
const ret = isArray$1(object) ? new Array(object.length) : {};
for (const key in object) ret[key] = propertyToRef(object, key);
return ret;
}
var ObjectRefImpl = class {
constructor(_object, key, _defaultValue) {
this._object = _object;
this._defaultValue = _defaultValue;
this["__v_isRef"] = true;
this._value = void 0;
this._key = isSymbol(key) ? key : String(key);
this._raw = toRaw(_object);
let shallow = true;
let obj = _object;
if (!isArray$1(_object) || isSymbol(this._key) || !isIntegerKey(this._key)) do
shallow = !isProxy(obj) || isShallow(obj);
while (shallow && (obj = obj["__v_raw"]));
this._shallow = shallow;
}
get value() {
let val = this._object[this._key];
if (this._shallow) val = unref(val);
return this._value = val === void 0 ? this._defaultValue : val;
}
set value(newVal) {
if (this._shallow && isRef(this._raw[this._key])) {
const nestedRef = this._object[this._key];
if (isRef(nestedRef)) {
nestedRef.value = newVal;
return;
}
}
this._object[this._key] = newVal;
}
get dep() {
return getDepFromReactive(this._raw, this._key);
}
};
var GetterRefImpl = class {
constructor(_getter) {
this._getter = _getter;
this["__v_isRef"] = true;
this["__v_isReadonly"] = true;
this._value = void 0;
}
get value() {
return this._value = this._getter();
}
};
function toRef$1(source, key, defaultValue) {
if (isRef(source)) return source;
else if (isFunction(source)) return new GetterRefImpl(source);
else if (isObject$3(source) && arguments.length > 1) return propertyToRef(source, key, defaultValue);
else return ref(source);
}
function propertyToRef(source, key, defaultValue) {
return new ObjectRefImpl(source, key, defaultValue);
}
var ComputedRefImpl = class {
constructor(fn, setter, isSSR) {
this.fn = fn;
this.setter = setter;
this._value = void 0;
this.dep = new Dep(this);
this.__v_isRef = true;
this.deps = void 0;
this.depsTail = void 0;
this.flags = 16;
this.globalVersion = globalVersion - 1;
this.next = void 0;
this.effect = this;
this["__v_isReadonly"] = !setter;
this.isSSR = isSSR;
}
notify() {
this.flags |= 16;
if (!(this.flags & 8) && activeSub !== this) {
batch(this, true);
return true;
}
}
get value() {
const link = this.dep.track();
refreshComputed(this);
if (link) link.version = this.dep.version;
return this._value;
}
set value(newValue) {
if (this.setter) this.setter(newValue);
}
};
function computed$1(getterOrOptions, debugOptions, isSSR = false) {
let getter;
let setter;
if (isFunction(getterOrOptions)) getter = getterOrOptions;
else {
getter = getterOrOptions.get;
setter = getterOrOptions.set;
}
return new ComputedRefImpl(getter, setter, isSSR);
}
var INITIAL_WATCHER_VALUE = {};
var cleanupMap = new WeakMap();
var activeWatcher = void 0;
function onWatcherCleanup(cleanupFn, failSilently = false, owner = activeWatcher) {
if (owner) {
let cleanups = cleanupMap.get(owner);
if (!cleanups) cleanupMap.set(owner, cleanups = []);
cleanups.push(cleanupFn);
}
}
function watch$1(source, cb, options = EMPTY_OBJ) {
const { immediate, deep, once, scheduler, augmentJob, call } = options;
const reactiveGetter = (source2) => {
if (deep) return source2;
if (isShallow(source2) || deep === false || deep === 0) return traverse(source2, 1);
return traverse(source2);
};
let effect;
let getter;
let cleanup;
let boundCleanup;
let forceTrigger = false;
let isMultiSource = false;
if (isRef(source)) {
getter = () => source.value;
forceTrigger = isShallow(source);
} else if (isReactive(source)) {
getter = () => reactiveGetter(source);
forceTrigger = true;
} else if (isArray$1(source)) {
isMultiSource = true;
forceTrigger = source.some((s) => isReactive(s) || isShallow(s));
getter = () => source.map((s) => {
if (isRef(s)) return s.value;
else if (isReactive(s)) return reactiveGetter(s);
else if (isFunction(s)) return call ? call(s, 2) : s();
});
} else if (isFunction(source)) {
if (cb) getter = call ? () => call(source, 2) : source;
else getter = () => {
if (cleanup) {
pauseTracking();
try {
cleanup();
} finally {
resetTracking();
}
}
const currentEffect = activeWatcher;
activeWatcher = effect;
try {
return call ? call(source, 3, [boundCleanup]) : source(boundCleanup);
} finally {
activeWatcher = currentEffect;
}
};
} else getter = NOOP;
if (cb && deep) {
const baseGetter = getter;
const depth = deep === true ? Infinity : deep;
getter = () => traverse(baseGetter(), depth);
}
const scope = getCurrentScope();
const watchHandle = () => {
effect.stop();
if (scope && scope.active) remove(scope.effects, effect);
};
if (once && cb) {
const _cb = cb;
cb = (...args) => {
try {
return _cb(...args);
} finally {
watchHandle();
}
};
}
let oldValue = isMultiSource ? new Array(source.length).fill(INITIAL_WATCHER_VALUE) : INITIAL_WATCHER_VALUE;
const job = (immediateFirstRun) => {
if (!(effect.flags & 1) || !effect.dirty && !immediateFirstRun) return;
if (cb) {
const newValue = effect.run();
if (immediateFirstRun || deep || forceTrigger || (isMultiSource ? newValue.some((v, i) => hasChanged(v, oldValue[i])) : hasChanged(newValue, oldValue))) {
const currentWatcher = activeWatcher;
pauseTracking();
try {
if (cleanup) cleanup();
activeWatcher = effect;
const args = [
newValue,
oldValue === INITIAL_WATCHER_VALUE ? void 0 : isMultiSource && oldValue[0] === INITIAL_WATCHER_VALUE ? [] : oldValue,
boundCleanup
];
oldValue = newValue;
call ? call(cb, 3, args) : cb(...args);
} finally {
activeWatcher = currentWatcher;
resetTracking();
}
}
} else effect.run();
};
if (augmentJob) augmentJob(job);
effect = new ReactiveEffect(getter);
effect.scheduler = scheduler ? () => scheduler(job, false) : job;
boundCleanup = (fn) => onWatcherCleanup(fn, false, effect);
cleanup = effect.onStop = () => {
const cleanups = cleanupMap.get(effect);
if (cleanups) {
if (call) call(cleanups, 4);
else for (const cleanup2 of cleanups) cleanup2();
cleanupMap.delete(effect);
}
};
if (cb) {
if (immediate) job(true);
else oldValue = effect.run();
} else if (scheduler) scheduler(job.bind(null, true), true);
else effect.run();
watchHandle.pause = effect.pause.bind(effect);
watchHandle.resume = effect.resume.bind(effect);
watchHandle.stop = watchHandle;
return watchHandle;
}
function traverse(value, depth = Infinity, seen) {
if (depth <= 0 || !isObject$3(value) || value["__v_skip"]) return value;
seen = seen || new Map();
if ((seen.get(value) || 0) >= depth) return value;
seen.set(value, depth);
depth--;
if (isRef(value)) traverse(value.value, depth, seen);
else if (isArray$1(value)) for (let i = 0; i < value.length; i++) traverse(value[i], depth, seen);
else if (isSet(value) || isMap(value)) value.forEach((v) => {
traverse(v, depth, seen);
});
else if (isPlainObject$2(value)) {
for (const key in value) traverse(value[key], depth, seen);
for (const key of Object.getOwnPropertySymbols(value)) if (Object.prototype.propertyIsEnumerable.call(value, key)) traverse(value[key], depth, seen);
}
return value;
}
function callWithErrorHandling(fn, instance, type, args) {
try {
return args ? fn(...args) : fn();
} catch (err) {
handleError(err, instance, type);
}
}
function callWithAsyncErrorHandling(fn, instance, type, args) {
if (isFunction(fn)) {
const res = callWithErrorHandling(fn, instance, type, args);
if (res && isPromise(res)) res.catch((err) => {
handleError(err, instance, type, void 0, true);
});
return res;
}
if (isArray$1(fn)) {
const values = [];
for (let i = 0; i < fn.length; i++) values.push(callWithAsyncErrorHandling(fn[i], instance, type, args));
return values;
}
}
function handleError(err, instance, type, throwInDev = true, isAsyncError = false) {
const contextVNode = instance ? instance.vnode : null;
const { errorHandler, throwUnhandledErrorInProduction } = instance && instance.appContext.config || EMPTY_OBJ;
if (instance) {
let cur = instance.parent;
const exposedInstance = instance.proxy;
const errorInfo = `https://vuejs.org/error-reference/#runtime-${type}`;
while (cur) {
const errorCapturedHooks = cur.ec;
if (errorCapturedHooks && !cur.isUnmounted && (!isAsyncError || cur.scope.active)) {
for (let i = 0; i < errorCapturedHooks.length; i++) if (errorCapturedHooks[i](err, exposedInstance, errorInfo) === false) return;
}
cur = cur.parent;
}
if (errorHandler) {
pauseTracking();
callWithErrorHandling(errorHandler, null, 10, [
err,
exposedInstance,
errorInfo
]);
resetTracking();
return;
}
}
logError(err, type, contextVNode, throwInDev, throwUnhandledErrorInProduction);
}
function logError(err, type, contextVNode, throwInDev = true, throwInProd = false) {
if (throwInProd) throw err;
else console.error(err);
}
var queue = [];
var flushIndex = -1;
var pendingPostFlushCbs = [];
var activePostFlushCbs = null;
var postFlushIndex = 0;
var resolvedPromise = Promise.resolve();
var currentFlushPromise = null;
function nextTick(fn) {
const p = currentFlushPromise || resolvedPromise;
return fn ? p.then(this ? fn.bind(this) : fn) : p;
}
function findInsertionIndex(id) {
let start = flushIndex + 1;
let end = queue.length;
while (start < end) {
const middle = start + end >>> 1;
const middleJob = queue[middle];
const middleJobId = getId(middleJob);
if (middleJobId < id || middleJobId === id && middleJob.flags & 2) start = middle + 1;
else end = middle;
}
return start;
}
function queueJob(job) {
if (!(job.flags & 1)) {
const jobId = getId(job);
const lastJob = queue[queue.length - 1];
if (!lastJob || !(job.flags & 2) && jobId >= getId(lastJob)) queue.push(job);
else queue.splice(findInsertionIndex(jobId), 0, job);
job.flags |= 1;
queueFlush();
}
}
function queueFlush() {
if (!currentFlushPromise) currentFlushPromise = resolvedPromise.then(flushJobs);
}
function queuePostFlushCb(cb) {
if (!isArray$1(cb)) {
if (activePostFlushCbs && cb.id === -1) activePostFlushCbs.splice(postFlushIndex + 1, 0, cb);
else if (!(cb.flags & 1)) {
pendingPostFlushCbs.push(cb);
cb.flags |= 1;
}
} else for (let i = 0; i < cb.length; i++) pendingPostFlushCbs.push(cb[i]);
queueFlush();
}
function flushPreFlushCbs(instance, minUid, seen, i = flushIndex + 1) {
for (; i < queue.length; i++) {
const cb = queue[i];
if (cb && cb.flags & 2) {
if (instance && cb.id !== instance.uid || minUid !== void 0 && !(cb.id >= minUid)) continue;
queue.splice(i, 1);
i = instance ? i - 1 : flushIndex;
if (cb.flags & 4) cb.flags &= -2;
cb();
if (!(cb.flags & 4)) cb.flags &= -2;
}
}
}
function flushPostFlushCbs(seen, skip, minUid = 0) {
if (pendingPostFlushCbs.length) {
let cbs = pendingPostFlushCbs;
let kept = 0;
if (skip) {
cbs = [];
for (let i = 0; i < pendingPostFlushCbs.length; i++) {
const cb = pendingPostFlushCbs[i];
if (cb.i !== void 0 ? !cb.i || cb.i.uid < minUid : skip.has(cb)) pendingPostFlushCbs[kept++] = cb;
else cbs.push(cb);
}
}
const deduped = [...new Set(cbs)].sort((a, b) => getId(a) - getId(b));
pendingPostFlushCbs.length = kept;
if (activePostFlushCbs) {
for (let i = 0; i < deduped.length; i++) activePostFlushCbs.push(deduped[i]);
return;
}
activePostFlushCbs = deduped;
for (postFlushIndex = 0; postFlushIndex < activePostFlushCbs.length; postFlushIndex++) {
const cb = activePostFlushCbs[postFlushIndex];
if (cb.flags & 4) cb.flags &= -2;
if (!(cb.flags & 8)) cb();
cb.flags &= -2;
}
activePostFlushCbs = null;
postFlushIndex = 0;
}
}
var isFlushing = false;
function flushOnAppMount(fn, minUid) {
if (isFlushing) {
fn();
return;
}
const queued = minUid === void 0 ? void 0 : new Set(pendingPostFlushCbs);
fn();
isFlushing = true;
try {
flushPreFlushCbs(void 0, minUid);
flushPostFlushCbs(void 0, queued, minUid);
} finally {
isFlushing = false;
}
}
var getId = (job) => job.id == null ? job.flags & 2 ? -1 : Infinity : job.id;
function flushJobs(seen) {
try {
for (flushIndex = 0; flushIndex < queue.length; flushIndex++) {
const job = queue[flushIndex];
if (job && !(job.flags & 8)) {
if (job.flags & 4) job.flags &= -2;
callWithErrorHandling(job, job.i, job.i ? 15 : 14);
if (!(job.flags & 4)) job.flags &= -2;
}
}
} finally {
for (; flushIndex < queue.length; flushIndex++) {
const job = queue[flushIndex];
if (job) job.flags &= -2;
}
flushIndex = -1;
queue.length = 0;
flushPostFlushCbs(seen);
currentFlushPromise = null;
if (queue.length || pendingPostFlushCbs.length) flushJobs(seen);
}
}
var currentRenderingInstance = null;
var currentScopeId = null;
function setCurrentRenderingInstance(instance) {
const prev = currentRenderingInstance;
currentRenderingInstance = instance;
currentScopeId = instance && instance.type.__scopeId || null;
return prev;
}
function withCtx(fn, ctx = currentRenderingInstance, isNonScopedSlot) {
if (!ctx) return fn;
if (fn._n) return fn;
const renderFnWithContext = (...args) => {
if (renderFnWithContext._d) setBlockTracking(-1);
const prevInstance = setCurrentRenderingInstance(ctx);
const prevStackSize = blockStack.length;
let res;
try {
res = fn(...args);
} finally {
for (let i = blockStack.length; i > prevStackSize; i--) closeBlock();
setCurrentRenderingInstance(prevInstance);
if (renderFnWithContext._d) setBlockTracking(1);
}
return res;
};
renderFnWithContext._n = true;
renderFnWithContext._c = true;
renderFnWithContext._d = true;
return renderFnWithContext;
}
function withDirectives(vnode, directives) {
if (currentRenderingInstance === null) return vnode;
const instance = getComponentPublicInstance(currentRenderingInstance);
const bindings = vnode.dirs || (vnode.dirs = []);
for (let i = 0; i < directives.length; i++) {
let [dir, value, arg, modifiers = EMPTY_OBJ] = directives[i];
if (dir) {
if (isFunction(dir)) dir = {
mounted: dir,
updated: dir
};
if (dir.deep) traverse(value);
bindings.push({
dir,
instance,
value,
oldValue: void 0,
arg,
modifiers
});
}
}
return vnode;
}
function invokeDirectiveHook(vnode, prevVNode, instance, name) {
let hookVNode = vnode;
if (name === "beforeMount") vnode._mount = vnode;
else if (name === "beforeUpdate") {
const mount = prevVNode && prevVNode._mount;
if (mount) {
mount._latest = vnode;
vnode._mount = mount;
}
} else if (name === "mounted") {
const latest = vnode._latest;
vnode._mount = vnode._latest = void 0;
if (latest) {
hookVNode = latest;
latest._mount = void 0;
}
}
const bindings = hookVNode.dirs;
const oldBindings = prevVNode && prevVNode.dirs;
for (let i = 0; i < bindings.length; i++) {
let binding = bindings[i];
if (oldBindings) binding.oldValue = oldBindings[i].value;
else if (name === "mounted" && binding.oldValue !== void 0) binding = extend({}, binding, { oldValue: void 0 });
let hook = binding.dir[name];
if (hook) {
pauseTracking();
callWithAsyncErrorHandling(hook, instance, 8, [
vnode.el,
binding,
hookVNode,
prevVNode
]);
resetTracking();
}
}
}
function provide(key, value) {
if (currentInstance) {
let provides = currentInstance.provides;
const parentProvides = currentInstance.parent && currentInstance.parent.provides;
if (parentProvides === provides) provides = currentInstance.provides = Object.create(parentProvides);
provides[key] = value;
}
}
function inject(key, defaultValue, treatDefaultAsFactory = false) {
const instance = getCurrentInstance();
if (instance || currentApp) {
let provides = currentApp ? currentApp._context.provides : instance ? instance.parent == null || instance.ce ? instance.vnode.appContext && instance.vnode.appContext.provides : instance.parent.provides : void 0;
if (provides && key in provides) return provides[key];
else if (arguments.length > 1) return treatDefaultAsFactory && isFunction(defaultValue) ? defaultValue.call(instance && instance.proxy) : defaultValue;
}
}
function hasInjectionContext() {
return !!(getCurrentInstance() || currentApp);
}
var ssrContextKey = Symbol.for("v-scx");
var useSSRContext = () => {
{
const ctx = inject(ssrContextKey);
if (!ctx) {}
return ctx;
}
};
function watchEffect(effect, options) {
return doWatch(effect, null, options);
}
function watchSyncEffect(effect, options) {
return doWatch(effect, null, { flush: "sync" });
}
function watch(source, cb, options) {
return doWatch(source, cb, options);
}
function doWatch(source, cb, options = EMPTY_OBJ) {
const { immediate, deep, flush, once } = options;
const baseWatchOptions = extend({}, options);
const runsImmediately = cb && immediate || !cb && flush !== "post";
let ssrCleanup;
if (isInSSRComponentSetup) {
if (flush === "sync") {
const ctx = useSSRContext();
ssrCleanup = ctx.__watcherHandles || (ctx.__watcherHandles = []);
} else if (!runsImmediately) {
const watchStopHandle = () => {};
watchStopHandle.stop = NOOP;
watchStopHandle.resume = NOOP;
watchStopHandle.pause = NOOP;
return watchStopHandle;
}
}
const instance = currentInstance;
baseWatchOptions.call = (fn, type, args) => callWithAsyncErrorHandling(fn, instance, type, args);
let isPre = false;
if (flush === "post") baseWatchOptions.scheduler = (job) => {
job.i = instance;
queuePostRenderEffect(job, instance && instance.suspense);
};
else if (flush !== "sync") {
isPre = true;
baseWatchOptions.scheduler = (job, isFirstRun) => {
if (isFirstRun) job();
else queueJob(job);
};
}
baseWatchOptions.augmentJob = (job) => {
if (cb) job.flags |= 4;
if (isPre) {
job.flags |= 2;
if (instance) {
job.id = instance.uid;
job.i = instance;
}
}
};
const watchHandle = watch$1(source, cb, baseWatchOptions);
if (isInSSRComponentSetup) {
if (ssrCleanup) ssrCleanup.push(watchHandle);
else if (runsImmediately) watchHandle();
}
return watchHandle;
}
function instanceWatch(source, value, options) {
const publicThis = this.proxy;
const getter = isString$1(source) ? source.includes(".") ? createPathGetter(publicThis, source) : () => publicThis[source] : source.bind(publicThis, publicThis);
let cb;
if (isFunction(value)) cb = value;
else {
cb = value.handler;
options = value;
}
const reset = setCurrentInstance(this);
const res = doWatch(getter, cb.bind(publicThis), options);
reset();
return res;
}
function createPathGetter(ctx, path) {
const segments = path.split(".");
return () => {
let cur = ctx;
for (let i = 0; i < segments.length && cur; i++) cur = cur[segments[i]];
return cur;
};
}
var pendingMounts = new WeakMap();
var TeleportEndKey = Symbol("_vte");
var isTeleport = (type) => type.__isTeleport;
var isTeleportDisabled = (props) => props && (props.disabled || props.disabled === "");
var isTeleportDeferred = (props) => props && (props.defer || props.defer === "");
var isTargetSVG = (target) => typeof SVGElement !== "undefined" && target instanceof SVGElement;
var isTargetMathML = (target) => typeof MathMLElement === "function" && target instanceof MathMLElement;
var resolveTarget = (props, select) => {
const targetSelector = props && props.to;
if (isString$1(targetSelector)) {
if (!select) return null;
else return select(targetSelector);
} else return targetSelector;
};
var TeleportImpl = {
name: "Teleport",
__isTeleport: true,
process(n1, n2, container, anchor, parentComponent, parentSuspense, namespace, slotScopeIds, optimized, internals) {
const { mc: mountChildren, pc: patchChildren, pbc: patchBlockChildren, o: { insert, querySelector, createText, createComment, parentNode } } = internals;
const disabled = isTeleportDisabled(n2.props);
let { dynamicChildren } = n2;
const mount = (vnode, container2, anchor2) => {
if (vnode.shapeFlag & 16) mountChildren(vnode.children, container2, anchor2, parentComponent, parentSuspense, namespace, slotScopeIds, optimized);
};
const mountToTarget = (vnode = n2) => {
const disabled2 = isTeleportDisabled(vnode.props);
const target = vnode.target = resolveTarget(vnode.props, querySelector);
const targetAnchor = prepareAnchor(target, vnode, createText, insert);
if (target) {
if (namespace !== "svg" && isTargetSVG(target)) namespace = "svg";
else if (namespace !== "mathml" && isTargetMathML(target)) namespace = "mathml";
if (parentComponent && parentComponent.isCE) (parentComponent.ce._teleportTargets || (parentComponent.ce._teleportTargets = new Set())).add(target);
if (!disabled2) {
mount(vnode, target, targetAnchor);
updateCssVars(vnode, false);
}
}
};
const queuePendingMount = (vnode) => {
const mountJob = () => {
if (pendingMounts.get(vnode) !== mountJob) return;
pendingMounts.delete(vnode);
if (isTeleportDisabled(vnode.props)) {
const mountContainer = parentNode(vnode.el) || container;
mount(vnode, mountContainer, vnode.anchor);
updateCssVars(vnode, true);
}
mountToTarget(vnode);
};
pendingMounts.set(vnode, mountJob);
queuePostRenderEffect(mountJob, parentSuspense);
};
if (n1 == null) {
const placeholder = n2.el = createText("");
const mainAnchor = n2.anchor = createText("");
insert(placeholder, container, anchor);
insert(mainAnchor, container, anchor);
if (isTeleportDeferred(n2.props) || parentSuspense && parentSuspense.pendingBranch) {
queuePendingMount(n2);
return;
}
if (disabled) {
mount(n2, container, mainAnchor);
updateCssVars(n2, true);
}
mountToTarget();
} else {
n2.el = n1.el;
const mainAnchor = n2.anchor = n1.anchor;
const pendingMount = pendingMounts.get(n1);
if (pendingMount) {
pendingMount.flags |= 8;
pendingMounts.delete(n1);
queuePendingMount(n2);
return;
}
n2.targetStart = n1.targetStart;
const target = n2.target = n1.target;
const targetAnchor = n2.targetAnchor = n1.targetAnchor;
const wasDisabled = isTeleportDisabled(n1.props);
const currentContainer = wasDisabled ? container : target;
const currentAnchor = wasDisabled ? mainAnchor : targetAnchor;
if (namespace === "svg" || isTargetSVG(target)) namespace = "svg";
else if (namespace === "mathml" || isTargetMathML(target)) namespace = "mathml";
if (dynamicChildren) {
patchBlockChildren(n1.dynamicChildren, dynamicChildren, currentContainer, parentComponent, parentSuspense, namespace, slotScopeIds);
traverseStaticChildren(n1, n2, true);
} else if (!optimized) patchChildren(n1, n2, currentContainer, currentAnchor, parentComponent, parentSuspense, namespace, slotScopeIds, false);
if (disabled) {
if (!wasDisabled) moveTeleport(n2, container, mainAnchor, internals, 1);
else if (n2.props && n1.props && n2.props.to !== n1.props.to) n2.props.to = n1.props.to;
} else if ((n2.props && n2.props.to) !== (n1.props && n1.props.to)) {
const nextTarget = resolveTarget(n2.props, querySelector);
if (nextTarget) {
n2.target = nextTarget;
moveTeleport(n2, nextTarget, null, internals, 0);
}
} else if (wasDisabled) moveTeleport(n2, target, targetAnchor, internals, 1);
updateCssVars(n2, disabled);
}
},
remove(vnode, parentComponent, parentSuspense, { um: unmount, o: { remove: hostRemove } }, doRemove) {
const { shapeFlag, children, anchor, targetStart, targetAnchor, target, props } = vnode;
const disabled = isTeleportDisabled(props);
const shouldRemove = doRemove || !disabled;
const pendingMount = pendingMounts.get(vnode);
if (pendingMount) {
pendingMount.flags |= 8;
pendingMounts.delete(vnode);
}
if (target) {
hostRemove(targetStart);
hostRemove(targetAnchor);
}
doRemove && hostRemove(anchor);
if (!pendingMount && (disabled || target) && shapeFlag & 16) for (let i = 0; i < children.length; i++) {
const child = children[i];
unmount(child, parentComponent, parentSuspense, shouldRemove, !!child.dynamicChildren);
}
},
move: moveTeleport,
hydrate: hydrateTeleport
};
function moveTeleport(vnode, container, parentAnchor, { o: { insert }, m: move }, moveType = 2) {
if (moveType === 0) {
if (vnode.targetStart) insert(vnode.targetStart, container, parentAnchor);
insert(vnode.targetAnchor, container, parentAnchor);
parentAnchor = vnode.targetAnchor;
}
const { el, anchor, shapeFlag, children, props } = vnode;
const isReorder = moveType === 2;
if (isReorder) insert(el, container, parentAnchor);
if (!pendingMounts.has(vnode) && (!isReorder || isTeleportDisabled(props))) {
if (shapeFlag & 16) for (let i = 0; i < children.length; i++) move(children[i], container, parentAnchor, 2);
}
if (isReorder) insert(anchor, container, parentAnchor);
}
function hydrateTeleport(node, vnode, parentComponent, parentSuspense, slotScopeIds, optimized, { o: { nextSibling, parentNode, querySelector, insert, createText } }, hydrateChildren) {
function hydrateAnchor(target2, targetNode) {
let targetAnchor = targetNode;
while (targetAnchor) {
if (targetAnchor && targetAnchor.nodeType === 8) {
if (targetAnchor.data === "teleport start anchor") vnode.targetStart = targetAnchor;
else if (targetAnchor.data === "teleport anchor") {
vnode.targetAnchor = targetAnchor;
target2._lpa = vnode.targetAnchor && nextSibling(vnode.targetAnchor);
break;
}
}
targetAnchor = nextSibling(targetAnchor);
}
}
function hydrateDisabledTeleport(node2, vnode2) {
vnode2.anchor = hydrateChildren(nextSibling(node2), vnode2, parentNode(node2), parentComponent, parentSuspense, slotScopeIds, optimized);
}
const target = vnode.target = resolveTarget(vnode.props, querySelector);
const disabled = isTeleportDisabled(vnode.props);
if (target) {
const targetNode = target._lpa || target.firstChild;
if (vnode.shapeFlag & 16) {
if (disabled) {
hydrateDisabledTeleport(node, vnode);
hydrateAnchor(target, targetNode);
if (!vnode.targetAnchor) prepareAnchor(target, vnode, createText, insert, parentNode(node) === target ? node : null);
} else {
vnode.anchor = nextSibling(node);
hydrateAnchor(target, targetNode);
if (!vnode.targetAnchor) prepareAnchor(target, vnode, createText, insert);
hydrateChildren(targetNode && nextSibling(targetNode), vnode, target, parentComponent, parentSuspense, slotScopeIds, optimized);
}
}
updateCssVars(vnode, disabled);
} else if (disabled) {
if (vnode.shapeFlag & 16) {
hydrateDisabledTeleport(node, vnode);
vnode.targetStart = node;
vnode.targetAnchor = nextSibling(node);
}
}
return vnode.anchor && nextSibling(vnode.anchor);
}
var Teleport = TeleportImpl;
function updateCssVars(vnode, isDisabled) {
const ctx = vnode.ctx;
if (ctx && ctx.ut) {
let node, anchor;
if (isDisabled) {
node = vnode.el;
anchor = vnode.anchor;
} else {
node = vnode.targetStart;
anchor = vnode.targetAnchor;
}
while (node && node !== anchor) {
if (node.nodeType === 1) node.setAttribute("data-v-owner", ctx.uid);
node = node.nextSibling;
}
ctx.ut();
}
}
function prepareAnchor(target, vnode, createText, insert, anchor = null) {
const targetStart = vnode.targetStart = createText("");
const targetAnchor = vnode.targetAnchor = createText("");
targetStart[TeleportEndKey] = targetAnchor;
if (target) {
insert(targetStart, target, anchor);
insert(targetAnchor, target, anchor);
}
return targetAnchor;
}
var leaveCbKey = Symbol("_leaveCb");
var enterCbKey = Symbol("_enterCb");
function useTransitionState() {
const state = {
isMounted: false,
isLeaving: false,
isUnmounting: false,
leavingVNodes: new Map()
};
onMounted(() => {
state.isMounted = true;
});
onBeforeUnmount(() => {
state.isUnmounting = true;
});
return state;
}
var TransitionHookValidator = [Function, Array];
var BaseTransitionPropsValidators = {
mode: String,
appear: Boolean,
persisted: Boolean,
onBeforeEnter: TransitionHookValidator,
onEnter: TransitionHookValidator,
onAfterEnter: TransitionHookValidator,
onEnterCancelled: TransitionHookValidator,
onBeforeLeave: TransitionHookValidator,
onLeave: TransitionHookValidator,
onAfterLeave: TransitionHookValidator,
onLeaveCancelled: TransitionHookValidator,
onBeforeAppear: TransitionHookValidator,
onAppear: TransitionHookValidator,
onAfterAppear: TransitionHookValidator,
onAppearCancelled: TransitionHookValidator
};
var BaseTransitionImpl = {
name: `BaseTransition`,
props: BaseTransitionPropsValidators,
setup(props, { slots }) {
const instance = getCurrentInstance();
const state = useTransitionState();
return () => {
const children = slots.default && getTransitionRawChildren(slots.default(), true);
const child = children && children.length ? findNonCommentChild(children) : instance.subTree ? createCommentVNode() : void 0;
if (!child) return;
const rawProps = toRaw(props);
const { mode } = rawProps;
if (state.isLeaving) return emptyPlaceholder(child);
const innerChild = getInnerChild$1(child);
if (!innerChild) return emptyPlaceholder(child);
const enterHooks = resolveTransitionHooks(innerChild, rawProps, state, instance);
if (innerChild.type !== Comment) setTransitionHooks(innerChild, enterHooks);
let oldInnerChild = instance.subTree && getInnerChild$1(instance.subTree);
if (oldInnerChild && oldInnerChild.type !== Comment && !isSameVNodeType(oldInnerChild, innerChild) && getTransitionRoot(instance.subTree)) {
let leavingHooks = resolveTransitionHooks(oldInnerChild, rawProps, state, instance);
setTransitionHooks(oldInnerChild, leavingHooks);
if (mode === "out-in" && innerChild.type !== Comment) {
state.isLeaving = true;
leavingHooks.afterLeave = () => {
state.isLeaving = false;
if (!(instance.job.flags & 8)) {
if (instance.effect.flags & 2) {
const job = () => {
if (!(instance.job.flags & 8)) instance.update();
};
job.i = instance;
queueJob(job);
} else instance.update();
}
delete leavingHooks.afterLeave;
oldInnerChild = void 0;
};
return emptyPlaceholder(child);
} else if (mode === "in-out" && innerChild.type !== Comment) leavingHooks.delayLeave = (el, earlyRemove, delayedLeave) => {
const leavingVNodesCache = getLeavingNodesForType(state, oldInnerChild);
leavingVNodesCache[String(oldInnerChild.key)] = oldInnerChild;
el[leaveCbKey] = () => {
earlyRemove();
el[leaveCbKey] = void 0;
delete enterHooks.delayedLeave;
oldInnerChild = void 0;
};
enterHooks.delayedLeave = () => {
delayedLeave();
delete enterHooks.delayedLeave;
oldInnerChild = void 0;
};
};
else oldInnerChild = void 0;
} else if (oldInnerChild) oldInnerChild = void 0;
return child;
};
}
};
function findNonCommentChild(children) {
let child = children[0];
if (children.length > 1) {
for (const c of children) if (c.type !== Comment) {
child = c;
break;
}
}
return child;
}
var BaseTransition = BaseTransitionImpl;
function getLeavingNodesForType(state, vnode) {
const { leavingVNodes } = state;
let leavingVNodesCache = leavingVNodes.get(vnode.type);
if (!leavingVNodesCache) {
leavingVNodesCache = Object.create(null);
leavingVNodes.set(vnode.type, leavingVNodesCache);
}
return leavingVNodesCache;
}
function resolveTransitionHooks(vnode, props, state, instance) {
const { appear, mode, persisted = false, onBeforeEnter, onEnter, onAfterEnter, onEnterCancelled, onBeforeLeave, onLeave, onAfterLeave, onLeaveCancelled, onBeforeAppear, onAppear, onAfterAppear, onAppearCancelled } = props;
const key = String(vnode.key);
const leavingVNodesCache = getLeavingNodesForType(state, vnode);
const callHook = (hook, args) => {
hook && callWithAsyncErrorHandling(hook, instance, 9, args);
};
const callAsyncHook = (hook, args) => {
const done = args[1];
callHook(hook, args);
if (isArray$1(hook)) {
if (hook.every((hook2) => hook2.length <= 1)) done();
} else if (hook.length <= 1) done();
};
const hooks = {
mode,
persisted,
beforeEnter(el) {
let hook = onBeforeEnter;
if (!state.isMounted) {
if (appear) hook = onBeforeAppear || onBeforeEnter;
else return;
}
if (el[leaveCbKey]) el[leaveCbKey](true);
const leavingVNode = leavingVNodesCache[key];
if (leavingVNode && isSameVNodeType(vnode, leavingVNode)) {
let leavingCb = leavingVNode.el[leaveCbKey];
if (!leavingCb) {
const leavingRoot = getTransitionRoot(leavingVNode);
leavingCb = leavingRoot && leavingRoot.el[leaveCbKey];
}
if (leavingCb) leavingCb();
}
callHook(hook, [el]);
},
enter(el) {
if (leavingVNodesCache[key] === vnode) return;
let hook = onEnter;
let afterHook = onAfterEnter;
let cancelHook = onEnterCancelled;
if (!state.isMounted) {
if (appear) {
hook = onAppear || onEnter;
afterHook = onAfterAppear || onAfterEnter;
cancelHook = onAppearCancelled || onEnterCancelled;
} else return;
}
let called = false;
el[enterCbKey] = (cancelled) => {
if (called) return;
called = true;
if (cancelled) callHook(cancelHook, [el]);
else callHook(afterHook, [el]);
if (hooks.delayedLeave) hooks.delayedLeave();
el[enterCbKey] = void 0;
};
const done = el[enterCbKey].bind(null, false);
if (hook) callAsyncHook(hook, [el, done]);
else done();
},
leave(el, remove) {
const key2 = String(vnode.key);
if (el[enterCbKey]) el[enterCbKey](true);
if (state.isUnmounting) return remove();
callHook(onBeforeLeave, [el]);
let called = false;
el[leaveCbKey] = (cancelled) => {
if (called) return;
called = true;
remove();
if (cancelled) callHook(onLeaveCancelled, [el]);
else callHook(onAfterLeave, [el]);
el[leaveCbKey] = void 0;
if (leavingVNodesCache[key2] === vnode) delete leavingVNodesCache[key2];
};
const done = el[leaveCbKey].bind(null, false);
leavingVNodesCache[key2] = vnode;
if (onLeave) callAsyncHook(onLeave, [el, done]);
else done();
},
clone(vnode2) {
const cloned = resolveTransitionHooks(vnode2, props, state, instance);
cloned.afterLeave = () => {
if (hooks.afterLeave) hooks.afterLeave();
};
cloned.delayLeave = (el, earlyRemove, delayedLeave) => {
if (hooks.delayLeave) hooks.delayLeave(el, earlyRemove, delayedLeave);
else delayedLeave();
};
cloned.delayedLeave = () => {
if (hooks.delayedLeave) hooks.delayedLeave();
};
return cloned;
}
};
return hooks;
}
function emptyPlaceholder(vnode) {
if (isKeepAlive(vnode)) {
vnode = cloneVNode(vnode);
vnode.children = null;
return vnode;
}
}
function getInnerChild$1(vnode) {
if (!isKeepAlive(vnode)) {
if (isTeleport(vnode.type) && vnode.children) return findNonCommentChild(vnode.children);
return vnode;
}
if (vnode.component) return vnode.component.subTree;
const { shapeFlag, children } = vnode;
if (children) {
if (shapeFlag & 16) return children[0];
if (shapeFlag & 32 && isFunction(children.default)) return children.default();
}
}
function setTransitionHooks(vnode, hooks) {
if (vnode.shapeFlag & 6 && vnode.component) {
vnode.transition = hooks;
const subTree = vnode.component.subTree;
setTransitionHooks(isTeleport(subTree.type) ? getInnerChild$1(subTree) || subTree : subTree, hooks);
} else if (vnode.shapeFlag & 128) {
const suspense = vnode.suspense;
if (suspense) {
const branch = suspense.isHydrating ? suspense.pendingBranch : suspense.activeBranch;
if (branch) setTransitionHooks(branch, hooks.clone(branch));
} else {
vnode.ssContent.transition = hooks.clone(vnode.ssContent);
vnode.ssFallback.transition = hooks.clone(vnode.ssFallback);
}
} else {
vnode.transition = hooks;
if (vnode.type === Fragment && isArray$1(vnode.children)) {
const child = filterSingleRoot(vnode.children, false);
if (child) setTransitionHooks(child, hooks);
}
}
}
function getTransitionRawChildren(children, keepComment = false, parentKey) {
let ret = [];
let keyedFragmentCount = 0;
for (let i = 0; i < children.length; i++) {
let child = children[i];
const key = parentKey == null ? child.key : String(parentKey) + String(child.key != null ? child.key : i);
if (child.type === Fragment) {
if (child.patchFlag & 128) keyedFragmentCount++;
ret = ret.concat(getTransitionRawChildren(child.children, keepComment, key));
} else if (keepComment || child.type !== Comment) ret.push(key != null ? cloneVNode(child, { key }) : child);
}
if (keyedFragmentCount > 1) for (let i = 0; i < ret.length; i++) ret[i].patchFlag = -2;
return ret;
}
function getTransitionRoot(vnode) {
if (vnode.component) return getTransitionRoot(vnode.component.subTree);
if (vnode.type === Fragment) {
const child = isArray$1(vnode.children) && filterSingleRoot(vnode.children, false);
return child ? getTransitionRoot(child) : void 0;
}
if (vnode.type !== Comment) return vnode;
}
function defineComponent(options, extraOptions) {
return isFunction(options) ? (() => extend({ name: options.name }, extraOptions, { setup: options }))() : options;
}
function useId() {
const i = getCurrentInstance();
if (i) return (i.appContext.config.idPrefix || "v") + "-" + i.ids[0] + i.ids[1]++;
return "";
}
function markAsyncBoundary(instance) {
instance.ids = [
instance.ids[0] + instance.ids[2]++ + "-",
0,
0
];
}
function useTemplateRef(key) {
const i = getCurrentInstance();
const r = shallowRef(null);
if (i) {
const refs = i.refs === EMPTY_OBJ ? i.refs = {} : i.refs;
Object.defineProperty(refs, key, {
enumerable: true,
get: () => r.value,
set: (val) => r.value = val
});
}
return r;
}
function isTemplateRefKey(refs, key) {
let desc;
return !!((desc = Object.getOwnPropertyDescriptor(refs, key)) && !desc.configurable);
}
var pendingSetRefMap = new WeakMap();
function setRef(rawRef, oldRawRef, parentSuspense, vnode, isUnmount = false) {
if (isArray$1(rawRef)) {
rawRef.forEach((r, i) => setRef(r, oldRawRef && (isArray$1(oldRawRef) ? oldRawRef[i] : oldRawRef), parentSuspense, vnode, isUnmount));
return;
}
if (isAsyncWrapper(vnode) && !isUnmount) {
if (vnode.shapeFlag & 512 && vnode.type.__asyncResolved && vnode.component.subTree.component) setRef(rawRef, oldRawRef, parentSuspense, vnode.component.subTree);
return;
}
const refValue = vnode.shapeFlag & 4 ? getComponentPublicInstance(vnode.component) : vnode.el;
const value = isUnmount ? null : refValue;
const { i: owner, r: ref } = rawRef;
const oldRef = oldRawRef && oldRawRef.r;
const refs = owner.refs === EMPTY_OBJ ? owner.refs = {} : owner.refs;
const setupState = owner.setupState;
const rawSetupState = toRaw(setupState);
const canSetSetupRef = setupState === EMPTY_OBJ ? NO : (key) => {
if (isTemplateRefKey(refs, key)) return false;
return hasOwn(rawSetupState, key);
};
const canSetRef = (ref2, key) => {
if (key && isTemplateRefKey(refs, key)) return false;
return true;
};
if (oldRef != null && oldRef !== ref) {
invalidatePendingSetRef(oldRawRef);
if (isString$1(oldRef)) {
refs[oldRef] = null;
if (canSetSetupRef(oldRef)) setupState[oldRef] = null;
} else if (isRef(oldRef)) {
const oldRawRefAtom = oldRawRef;
if (canSetRef(oldRef, oldRawRefAtom.k)) oldRef.value = null;
if (oldRawRefAtom.k) refs[oldRawRefAtom.k] = null;
}
}
if (isFunction(ref)) callWithErrorHandling(ref, owner, 12, [value, refs]);
else {
const _isString = isString$1(ref);
const _isRef = isRef(ref);
if (_isString || _isRef) {
const doSet = () => {
if (rawRef.f) {
const existing = _isString ? canSetSetupRef(ref) ? setupState[ref] : refs[ref] : canSetRef(ref) || !rawRef.k ? ref.value : refs[rawRef.k];
if (isUnmount) isArray$1(existing) && remove(existing, refValue);
else if (!isArray$1(existing)) {
if (_isString) {
refs[ref] = [refValue];
if (canSetSetupRef(ref)) setupState[ref] = refs[ref];
} else {
const newVal = [refValue];
if (canSetRef(ref, rawRef.k)) ref.value = newVal;
if (rawRef.k) refs[rawRef.k] = newVal;
}
} else if (!existing.includes(refValue)) existing.push(refValue);
} else if (_isString) {
refs[ref] = value;
if (canSetSetupRef(ref)) setupState[ref] = value;
} else if (_isRef) {
if (canSetRef(ref, rawRef.k)) ref.value = value;
if (rawRef.k) refs[rawRef.k] = value;
}
};
if (value) {
const job = () => {
doSet();
pendingSetRefMap.delete(rawRef);
};
job.id = -1;
pendingSetRefMap.set(rawRef, job);
queuePostRenderEffect(job, parentSuspense);
} else {
invalidatePendingSetRef(rawRef);
doSet();
}
}
}
}
function invalidatePendingSetRef(rawRef) {
const pendingSetRef = pendingSetRefMap.get(rawRef);
if (pendingSetRef) {
pendingSetRef.flags |= 8;
pendingSetRefMap.delete(rawRef);
}
}
getGlobalThis().requestIdleCallback;
getGlobalThis().cancelIdleCallback;
var isAsyncWrapper = (i) => !!i.type.__asyncLoader;
var isKeepAlive = (vnode) => vnode.type.__isKeepAlive;
function onActivated(hook, target) {
registerKeepAliveHook(hook, "a", target);
}
function onDeactivated(hook, target) {
registerKeepAliveHook(hook, "da", target);
}
function registerKeepAliveHook(hook, type, target = currentInstance) {
const wrappedHook = hook.__wdc || (hook.__wdc = () => {
let current = target;
while (current) {
if (current.isDeactivated) return;
current = current.parent;
}
return hook();
});
injectHook(type, wrappedHook, target);
if (target) {
let current = target.parent;
while (current && current.parent) {
if (isKeepAlive(current.parent.vnode)) injectToKeepAliveRoot(wrappedHook, type, target, current);
current = current.parent;
}
}
}
function injectToKeepAliveRoot(hook, type, target, keepAliveRoot) {
const injected = injectHook(type, hook, keepAliveRoot, true);
const removal = injectHook("um", () => remove(keepAliveRoot[type], injected), target);
removal.flags = 16;
}
function injectHook(type, hook, target = currentInstance, prepend = false) {
if (target) {
const hooks = target[type] || (target[type] = []);
const wrappedHook = hook.__weh || (hook.__weh = (...args) => {
pauseTracking();
const reset = setCurrentInstance(target);
const res = callWithAsyncErrorHandling(hook, target, type, args);
reset();
resetTracking();
return res;
});
if (prepend) hooks.unshift(wrappedHook);
else hooks.push(wrappedHook);
return wrappedHook;
}
}
var createHook = (lifecycle) => (hook, target = currentInstance) => {
if (!isInSSRComponentSetup || lifecycle === "sp") injectHook(lifecycle, (...args) => hook(...args), target);
};
var onBeforeMount = createHook("bm");
var onMounted = createHook("m");
var onBeforeUpdate = createHook("bu");
var onUpdated = createHook("u");
var onBeforeUnmount = createHook("bum");
var onUnmounted = createHook("um");
var onServerPrefetch = createHook("sp");
var onRenderTriggered = createHook("rtg");
var onRenderTracked = createHook("rtc");
function onErrorCaptured(hook, target = currentInstance) {
injectHook("ec", hook, target);
}
var COMPONENTS = "components";
var NULL_DYNAMIC_COMPONENT = Symbol.for("v-ndc");
function resolveDynamicComponent(component) {
if (isString$1(component)) return resolveAsset(COMPONENTS, component, false) || component;
else return component || NULL_DYNAMIC_COMPONENT;
}
function resolveAsset(type, name, warnMissing = true, maybeSelfReference = false) {
const instance = currentRenderingInstance || currentInstance;
if (instance) {
const Component = instance.type;
if (type === COMPONENTS) {
const selfName = getComponentName(Component, false);
if (selfName && (selfName === name || selfName === camelize$2(name) || selfName === capitalize(camelize$2(name)))) return Component;
}
const res = resolve(instance[type] || Component[type], name) || resolve(instance.appContext[type], name);
if (!res && maybeSelfReference) return Component;
return res;
}
}
function resolve(registry, name) {
return registry && (registry[name] || registry[camelize$2(name)] || registry[capitalize(camelize$2(name))]);
}
function renderList(source, renderItem, cache, index) {
let ret;
const cached = cache && cache[index];
const sourceIsArray = isArray$1(source);
if (sourceIsArray || isString$1(source)) {
const sourceIsReactiveArray = sourceIsArray && isReactive(source);
let needsWrap = false;
let isReadonlySource = false;
if (sourceIsReactiveArray) {
needsWrap = !isShallow(source);
isReadonlySource = isReadonly(source);
source = shallowReadArray(source);
}
ret = new Array(source.length);
for (let i = 0, l = source.length; i < l; i++) ret[i] = renderItem(needsWrap ? isReadonlySource ? toReadonly(toReactive(source[i])) : toReactive(source[i]) : source[i], i, void 0, cached && cached[i]);
} else if (typeof source === "number") {
if (!Number.isInteger(source) || source < 0) ret = [];
else {
ret = new Array(source);
for (let i = 0; i < source; i++) ret[i] = renderItem(i + 1, i, void 0, cached && cached[i]);
}
} else if (isObject$3(source)) {
if (source[Symbol.iterator]) ret = Array.from(source, (item, i) => renderItem(item, i, void 0, cached && cached[i]));
else {
const keys = Object.keys(source);
ret = new Array(keys.length);
for (let i = 0, l = keys.length; i < l; i++) {
const key = keys[i];
ret[i] = renderItem(source[key], key, i, cached && cached[i]);
}
}
} else ret = [];
if (cache) cache[index] = ret;
return ret;
}
function createSlots(slots, dynamicSlots) {
for (let i = 0; i < dynamicSlots.length; i++) {
const slot = dynamicSlots[i];
if (isArray$1(slot)) for (let j = 0; j < slot.length; j++) slots[slot[j].name] = slot[j].fn;
else if (slot) slots[slot.name] = slot.key ? (...args) => {
const res = slot.fn(...args);
if (res) res.key = slot.key;
return res;
} : slot.fn;
}
return slots;
}
function renderSlot(slots, name, props, fallback, noSlotted, branchKey) {
if (props == null) props = {};
if (currentRenderingInstance.ce || currentRenderingInstance.parent && isAsyncWrapper(currentRenderingInstance.parent) && currentRenderingInstance.parent.ce) {
const slotProps = branchKey != null && props.key == null ? extend({}, props, { key: branchKey }) : props;
const hasProps = Object.keys(slotProps).length > 0;
if (name !== "default") slotProps.name = name;
return openBlock(), createBlock(Fragment, null, [createVNode("slot", slotProps, fallback && fallback())], hasProps ? -2 : 64);
}
let slot = slots[name];
if (slot && slot._c) slot._d = false;
const prevStackSize = blockStack.length;
openBlock();
let rendered;
try {
const validSlotContent = slot && ensureValidVNode(slot(props));
const slotKey = props.key || branchKey || validSlotContent && validSlotContent.key;
rendered = createBlock(Fragment, { key: (slotKey && !isSymbol(slotKey) ? slotKey : `_${name}`) + (!validSlotContent && fallback ? "_fb" : "") }, validSlotContent || (fallback ? fallback() : []), validSlotContent && slots._ === 1 ? 64 : -2);
} catch (err) {
for (let i = blockStack.length; i > prevStackSize; i--) closeBlock();
throw err;
} finally {
if (slot && slot._c) slot._d = true;
}
if (!noSlotted && rendered.scopeId) rendered.slotScopeIds = [rendered.scopeId + "-s"];
return rendered;
}
function ensureValidVNode(vnodes) {
return vnodes.some((child) => {
if (!isVNode(child)) return true;
if (child.type === Comment) return false;
if (child.type === Fragment && !ensureValidVNode(child.children)) return false;
return true;
}) ? vnodes : null;
}
var getPublicInstance = (i) => {
if (!i) return null;
if (isStatefulComponent(i)) return getComponentPublicInstance(i);
return getPublicInstance(i.parent);
};
var publicPropertiesMap = extend(Object.create(null), {
$: (i) => i,
$el: (i) => i.vnode.el,
$data: (i) => i.data,
$props: (i) => i.props,
$attrs: (i) => i.attrs,
$slots: (i) => i.slots,
$refs: (i) => i.refs,
$parent: (i) => getPublicInstance(i.parent),
$root: (i) => getPublicInstance(i.root),
$host: (i) => i.ce,
$emit: (i) => i.emit,
$options: (i) => resolveMergedOptions(i),
$forceUpdate: (i) => i.f || (i.f = () => {
queueJob(i.update);
}),
$nextTick: (i) => i.n || (i.n = nextTick.bind(i.proxy)),
$watch: (i) => instanceWatch.bind(i)
});
var hasSetupBinding = (state, key) => state !== EMPTY_OBJ && !state.__isScriptSetup && hasOwn(state, key);
var PublicInstanceProxyHandlers = {
get({ _: instance }, key) {
if (key === "__v_skip") return true;
const { ctx, setupState, data, props, accessCache, type, appContext } = instance;
if (key[0] !== "$") {
const n = accessCache[key];
if (n !== void 0) switch (n) {
case 1: return setupState[key];
case 2: return data[key];
case 4: return ctx[key];
case 3: return props[key];
}
else if (hasSetupBinding(setupState, key)) {
accessCache[key] = 1;
return setupState[key];
} else if (data !== EMPTY_OBJ && hasOwn(data, key)) {
accessCache[key] = 2;
return data[key];
} else if (hasOwn(props, key)) {
accessCache[key] = 3;
return props[key];
} else if (ctx !== EMPTY_OBJ && hasOwn(ctx, key)) {
accessCache[key] = 4;
return ctx[key];
} else if (shouldCacheAccess) accessCache[key] = 0;
}
const publicGetter = publicPropertiesMap[key];
let cssModule, globalProperties;
if (publicGetter) {
if (key === "$attrs") track(instance.attrs, "get", "");
return publicGetter(instance);
} else if ((cssModule = type.__cssModules) && (cssModule = cssModule[key])) return cssModule;
else if (ctx !== EMPTY_OBJ && hasOwn(ctx, key)) {
accessCache[key] = 4;
return ctx[key];
} else if (globalProperties = appContext.config.globalProperties, hasOwn(globalProperties, key)) return globalProperties[key];
},
set({ _: instance }, key, value) {
const { data, setupState, ctx } = instance;
if (hasSetupBinding(setupState, key)) {
setupState[key] = value;
return true;
} else if (data !== EMPTY_OBJ && hasOwn(data, key)) {
data[key] = value;
return true;
} else if (hasOwn(instance.props, key)) return false;
if (key[0] === "$" && key.slice(1) in instance) return false;
else ctx[key] = value;
return true;
},
has({ _: { data, setupState, accessCache, ctx, appContext, props, type } }, key) {
let cssModules;
return !!(accessCache[key] || data !== EMPTY_OBJ && key[0] !== "$" && hasOwn(data, key) || hasSetupBinding(setupState, key) || hasOwn(props, key) || hasOwn(ctx, key) || hasOwn(publicPropertiesMap, key) || hasOwn(appContext.config.globalProperties, key) || (cssModules = type.__cssModules) && cssModules[key]);
},
defineProperty(target, key, descriptor) {
if (descriptor.get != null) target._.accessCache[key] = 0;
else if (hasOwn(descriptor, "value")) this.set(target, key, descriptor.value, null);
return Reflect.defineProperty(target, key, descriptor);
}
};
function normalizePropsOrEmits(props) {
return isArray$1(props) ? props.reduce((normalized, p) => (normalized[p] = null, normalized), {}) : props;
}
function mergeModels(a, b) {
if (!a || !b) return a || b;
if (isArray$1(a) && isArray$1(b)) return a.concat(b);
return extend({}, normalizePropsOrEmits(a), normalizePropsOrEmits(b));
}
var shouldCacheAccess = true;
function applyOptions(instance) {
const options = resolveMergedOptions(instance);
const publicThis = instance.proxy;
const ctx = instance.ctx;
shouldCacheAccess = false;
if (options.beforeCreate) callHook$1(options.beforeCreate, instance, "bc");
const { data: dataOptions, computed: computedOptions, methods, watch: watchOptions, provide: provideOptions, inject: injectOptions, created, beforeMount, mounted, beforeUpdate, updated, activated, deactivated, beforeDestroy, beforeUnmount, destroyed, unmounted, render, renderTracked, renderTriggered, errorCaptured, serverPrefetch, expose, inheritAttrs, components, directives, filters } = options;
const checkDuplicateProperties = null;
if (injectOptions) resolveInjections(injectOptions, ctx, checkDuplicateProperties);
if (methods) for (const key in methods) {
const methodHandler = methods[key];
if (isFunction(methodHandler)) ctx[key] = methodHandler.bind(publicThis);
}
if (dataOptions) {
const data = dataOptions.call(publicThis, publicThis);
if (!isObject$3(data)) {} else instance.data = reactive(data);
}
shouldCacheAccess = true;
if (computedOptions) for (const key in computedOptions) {
const opt = computedOptions[key];
const c = computed({
get: isFunction(opt) ? opt.bind(publicThis, publicThis) : isFunction(opt.get) ? opt.get.bind(publicThis, publicThis) : NOOP,
set: !isFunction(opt) && isFunction(opt.set) ? opt.set.bind(publicThis) : NOOP
});
Object.defineProperty(ctx, key, {
enumerable: true,
configurable: true,
get: () => c.value,
set: (v) => c.value = v
});
}
if (watchOptions) for (const key in watchOptions) createWatcher(watchOptions[key], ctx, publicThis, key);
if (provideOptions) {
const provides = isFunction(provideOptions) ? provideOptions.call(publicThis) : provideOptions;
Reflect.ownKeys(provides).forEach((key) => {
provide(key, provides[key]);
});
}
if (created) callHook$1(created, instance, "c");
function registerLifecycleHook(register, hook) {
if (isArray$1(hook)) hook.forEach((_hook) => register(_hook.bind(publicThis)));
else if (hook) register(hook.bind(publicThis));
}
registerLifecycleHook(onBeforeMount, beforeMount);
registerLifecycleHook(onMounted, mounted);
registerLifecycleHook(onBeforeUpdate, beforeUpdate);
registerLifecycleHook(onUpdated, updated);
registerLifecycleHook(onActivated, activated);
registerLifecycleHook(onDeactivated, deactivated);
registerLifecycleHook(onErrorCaptured, errorCaptured);
registerLifecycleHook(onRenderTracked, renderTracked);
registerLifecycleHook(onRenderTriggered, renderTriggered);
registerLifecycleHook(onBeforeUnmount, beforeUnmount);
registerLifecycleHook(onUnmounted, unmounted);
registerLifecycleHook(onServerPrefetch, serverPrefetch);
if (isArray$1(expose)) {
if (expose.length) {
const exposed = instance.exposed || (instance.exposed = {});
expose.forEach((key) => {
Object.defineProperty(exposed, key, {
get: () => publicThis[key],
set: (val) => publicThis[key] = val,
enumerable: true
});
});
} else if (!instance.exposed) instance.exposed = {};
}
if (render && instance.render === NOOP) instance.render = render;
if (inheritAttrs != null) instance.inheritAttrs = inheritAttrs;
if (components) instance.components = components;
if (directives) instance.directives = directives;
if (serverPrefetch) markAsyncBoundary(instance);
}
function resolveInjections(injectOptions, ctx, checkDuplicateProperties = NOOP) {
if (isArray$1(injectOptions)) injectOptions = normalizeInject(injectOptions);
for (const key in injectOptions) {
const opt = injectOptions[key];
let injected;
if (isObject$3(opt)) {
if ("default" in opt) injected = inject(opt.from || key, opt.default, true);
else injected = inject(opt.from || key);
} else injected = inject(opt);
if (isRef(injected)) Object.defineProperty(ctx, key, {
enumerable: true,
configurable: true,
get: () => injected.value,
set: (v) => injected.value = v
});
else ctx[key] = injected;
}
}
function callHook$1(hook, instance, type) {
callWithAsyncErrorHandling(isArray$1(hook) ? hook.map((h) => h.bind(instance.proxy)) : hook.bind(instance.proxy), instance, type);
}
function createWatcher(raw, ctx, publicThis, key) {
let getter = key.includes(".") ? createPathGetter(publicThis, key) : () => publicThis[key];
if (isString$1(raw)) {
const handler = ctx[raw];
if (isFunction(handler)) watch(getter, handler);
} else if (isFunction(raw)) watch(getter, raw.bind(publicThis));
else if (isObject$3(raw)) {
if (isArray$1(raw)) raw.forEach((r) => createWatcher(r, ctx, publicThis, key));
else {
const handler = isFunction(raw.handler) ? raw.handler.bind(publicThis) : ctx[raw.handler];
if (isFunction(handler)) watch(getter, handler, raw);
}
}
}
function resolveMergedOptions(instance) {
const base = instance.type;
const { mixins, extends: extendsOptions } = base;
const { mixins: globalMixins, optionsCache: cache, config: { optionMergeStrategies } } = instance.appContext;
const cached = cache.get(base);
let resolved;
if (cached) resolved = cached;
else if (!globalMixins.length && !mixins && !extendsOptions) resolved = base;
else {
resolved = {};
if (globalMixins.length) globalMixins.forEach((m) => mergeOptions(resolved, m, optionMergeStrategies, true));
mergeOptions(resolved, base, optionMergeStrategies);
}
if (isObject$3(base)) cache.set(base, resolved);
return resolved;
}
function mergeOptions(to, from, strats, asMixin = false) {
const { mixins, extends: extendsOptions } = from;
if (extendsOptions) mergeOptions(to, extendsOptions, strats, true);
if (mixins) mixins.forEach((m) => mergeOptions(to, m, strats, true));
for (const key in from) if (asMixin && key === "expose") {} else {
const strat = internalOptionMergeStrats[key] || strats && strats[key];
to[key] = strat ? strat(to[key], from[key]) : from[key];
}
return to;
}
var internalOptionMergeStrats = {
data: mergeDataFn,
props: mergeEmitsOrPropsOptions,
emits: mergeEmitsOrPropsOptions,
methods: mergeObjectOptions,
computed: mergeObjectOptions,
beforeCreate: mergeAsArray,
created: mergeAsArray,
beforeMount: mergeAsArray,
mounted: mergeAsArray,
beforeUpdate: mergeAsArray,
updated: mergeAsArray,
beforeDestroy: mergeAsArray,
beforeUnmount: mergeAsArray,
destroyed: mergeAsArray,
unmounted: mergeAsArray,
activated: mergeAsArray,
deactivated: mergeAsArray,
errorCaptured: mergeAsArray,
serverPrefetch: mergeAsArray,
components: mergeObjectOptions,
directives: mergeObjectOptions,
watch: mergeWatchOptions,
provide: mergeDataFn,
inject: mergeInject
};
function mergeDataFn(to, from) {
if (!from) return to;
if (!to) return from;
return function mergedDataFn() {
return extend(isFunction(to) ? to.call(this, this) : to, isFunction(from) ? from.call(this, this) : from);
};
}
function mergeInject(to, from) {
return mergeObjectOptions(normalizeInject(to), normalizeInject(from));
}
function normalizeInject(raw) {
if (isArray$1(raw)) {
const res = {};
for (let i = 0; i < raw.length; i++) res[raw[i]] = raw[i];
return res;
}
return raw;
}
function mergeAsArray(to, from) {
return to ? [...new Set([].concat(to, from))] : from;
}
function mergeObjectOptions(to, from) {
return to ? extend(Object.create(null), to, from) : from;
}
function mergeEmitsOrPropsOptions(to, from) {
if (to) {
if (isArray$1(to) && isArray$1(from)) return [...new Set([...to, ...from])];
return extend(Object.create(null), normalizePropsOrEmits(to), normalizePropsOrEmits(from != null ? from : {}));
} else return from;
}
function mergeWatchOptions(to, from) {
if (!to) return from;
if (!from) return to;
const merged = extend(Object.create(null), to);
for (const key in from) merged[key] = mergeAsArray(to[key], from[key]);
return merged;
}
function createAppContext() {
return {
app: null,
config: {
isNativeTag: NO,
performance: false,
globalProperties: {},
optionMergeStrategies: {},
errorHandler: void 0,
warnHandler: void 0,
compilerOptions: {}
},
mixins: [],
components: {},
directives: {},
provides: Object.create(null),
optionsCache: new WeakMap(),
propsCache: new WeakMap(),
emitsCache: new WeakMap()
};
}
var uid$1 = 0;
function createAppAPI(render, hydrate) {
return function createApp(rootComponent, rootProps = null) {
if (!isFunction(rootComponent)) rootComponent = extend({}, rootComponent);
if (rootProps != null && !isObject$3(rootProps)) rootProps = null;
const context = createAppContext();
const installedPlugins = new WeakSet();
const pluginCleanupFns = [];
let isMounted = false;
const app = context.app = {
_uid: uid$1++,
_component: rootComponent,
_props: rootProps,
_container: null,
_context: context,
_instance: null,
version,
get config() {
return context.config;
},
set config(v) {},
use(plugin, ...options) {
if (installedPlugins.has(plugin)) {} else if (plugin && isFunction(plugin.install)) {
installedPlugins.add(plugin);
plugin.install(app, ...options);
} else if (isFunction(plugin)) {
installedPlugins.add(plugin);
plugin(app, ...options);
}
return app;
},
mixin(mixin) {
if (!context.mixins.includes(mixin)) context.mixins.push(mixin);
return app;
},
component(name, component) {
if (!component) return context.components[name];
context.components[name] = component;
return app;
},
directive(name, directive) {
if (!directive) return context.directives[name];
context.directives[name] = directive;
return app;
},
mount(rootContainer, isHydrate, namespace) {
if (!isMounted) {
const vnode = app._ceVNode || createVNode(rootComponent, rootProps);
vnode.appContext = context;
if (namespace === true) namespace = "svg";
else if (namespace === false) namespace = void 0;
if (isHydrate && hydrate) hydrate(vnode, rootContainer);
else render(vnode, rootContainer, namespace);
isMounted = true;
app._container = rootContainer;
rootContainer.__vue_app__ = app;
return getComponentPublicInstance(vnode.component);
}
},
onUnmount(cleanupFn) {
pluginCleanupFns.push(cleanupFn);
},
unmount() {
if (isMounted) {
callWithAsyncErrorHandling(pluginCleanupFns, app._instance, 16);
render(null, app._container);
delete app._container.__vue_app__;
}
},
provide(key, value) {
context.provides[key] = value;
return app;
},
runWithContext(fn) {
const lastApp = currentApp;
currentApp = app;
try {
return fn();
} finally {
currentApp = lastApp;
}
}
};
return app;
};
}
var currentApp = null;
function useModel(props, name, options = EMPTY_OBJ) {
const i = getCurrentInstance();
const camelizedName = camelize$2(name);
const hyphenatedName = hyphenate$2(name);
const modifiers = getModelModifiers(props, camelizedName);
const res = customRef((track, trigger) => {
let localValue;
let prevSetValue = EMPTY_OBJ;
let prevEmittedValue;
watchSyncEffect(() => {
const propValue = props[camelizedName];
if (hasChanged(localValue, propValue)) {
localValue = propValue;
trigger();
}
});
return {
get() {
track();
return options.get ? options.get(localValue) : localValue;
},
set(value) {
const emittedValue = options.set ? options.set(value) : value;
if (!hasChanged(emittedValue, localValue) && !(prevSetValue !== EMPTY_OBJ && hasChanged(value, prevSetValue))) return;
const rawProps = i.vnode.props;
const hasVModel = !!(rawProps && (name in rawProps || camelizedName in rawProps || hyphenatedName in rawProps) && (`onUpdate:${name}` in rawProps || `onUpdate:${camelizedName}` in rawProps || `onUpdate:${hyphenatedName}` in rawProps));
if (!hasVModel) {
localValue = value;
trigger();
}
i.emit(`update:${name}`, emittedValue);
if (hasChanged(value, prevSetValue) && (hasChanged(value, emittedValue) && !hasChanged(emittedValue, prevEmittedValue) || hasVModel && prevSetValue !== EMPTY_OBJ && !hasChanged(emittedValue, localValue))) trigger();
prevSetValue = value;
prevEmittedValue = emittedValue;
}
};
});
res[Symbol.iterator] = () => {
let i2 = 0;
return { next() {
if (i2 < 2) return {
value: i2++ ? modifiers || EMPTY_OBJ : res,
done: false
};
else return { done: true };
} };
};
return res;
}
var getModelModifiers = (props, modelName) => {
return modelName === "modelValue" || modelName === "model-value" ? props.modelModifiers : props[`${modelName}Modifiers`] || props[`${camelize$2(modelName)}Modifiers`] || props[`${hyphenate$2(modelName)}Modifiers`];
};
function emit(instance, event, ...rawArgs) {
if (instance.isUnmounted) return;
const props = instance.vnode.props || EMPTY_OBJ;
let args = rawArgs;
const isModelListener = event.startsWith("update:");
const modifiers = isModelListener && getModelModifiers(props, event.slice(7));
if (modifiers) {
if (modifiers.trim) args = rawArgs.map((a) => isString$1(a) ? a.trim() : a);
if (modifiers.number) args = args.map(looseToNumber);
}
let handlerName;
let handler = props[handlerName = toHandlerKey(event)] || props[handlerName = toHandlerKey(camelize$2(event))];
if (!handler && isModelListener) handler = props[handlerName = toHandlerKey(hyphenate$2(event))];
if (handler) callWithAsyncErrorHandling(handler, instance, 6, args);
const onceHandler = props[handlerName + `Once`];
if (onceHandler) {
if (!instance.emitted) instance.emitted = {};
else if (instance.emitted[handlerName]) return;
instance.emitted[handlerName] = true;
callWithAsyncErrorHandling(onceHandler, instance, 6, args);
}
}
var mixinEmitsCache = new WeakMap();
function normalizeEmitsOptions(comp, appContext, asMixin = false) {
const cache = asMixin ? mixinEmitsCache : appContext.emitsCache;
const cached = cache.get(comp);
if (cached !== void 0) return cached;
const raw = comp.emits;
let normalized = {};
let hasExtends = false;
if (!isFunction(comp)) {
const extendEmits = (raw2) => {
const normalizedFromExtend = normalizeEmitsOptions(raw2, appContext, true);
if (normalizedFromExtend) {
hasExtends = true;
extend(normalized, normalizedFromExtend);
}
};
if (!asMixin && appContext.mixins.length) appContext.mixins.forEach(extendEmits);
if (comp.extends) extendEmits(comp.extends);
if (comp.mixins) comp.mixins.forEach(extendEmits);
}
if (!raw && !hasExtends) {
if (isObject$3(comp)) cache.set(comp, null);
return null;
}
if (isArray$1(raw)) raw.forEach((key) => normalized[key] = null);
else extend(normalized, raw);
if (isObject$3(comp)) cache.set(comp, normalized);
return normalized;
}
function isEmitListener(options, key) {
if (!options || !isOn(key)) return false;
key = key.slice(2);
key = key === "Once" ? key : key.replace(/Once$/, "");
return hasOwn(options, key[0].toLowerCase() + key.slice(1)) || hasOwn(options, hyphenate$2(key)) || hasOwn(options, key);
}
function renderComponentRoot(instance) {
const { type: Component, vnode, proxy, withProxy, propsOptions: [propsOptions], slots, attrs, emit, render, renderCache, props, data, setupState, ctx, inheritAttrs } = instance;
const prev = setCurrentRenderingInstance(instance);
let result;
let fallthroughAttrs;
try {
if (vnode.shapeFlag & 4) {
const proxyToUse = withProxy || proxy;
const thisProxy = proxyToUse;
result = normalizeVNode(render.call(thisProxy, proxyToUse, renderCache, props, setupState, data, ctx));
fallthroughAttrs = attrs;
} else {
const render2 = Component;
result = normalizeVNode(render2.length > 1 ? render2(props, {
attrs,
slots,
emit
}) : render2(props, null));
fallthroughAttrs = Component.props ? attrs : getFunctionalFallthrough(attrs);
}
} catch (err) {
blockStack.length = 0;
handleError(err, instance, 1);
result = createVNode(Comment);
}
let root = result;
if (fallthroughAttrs && inheritAttrs !== false) {
const keys = Object.keys(fallthroughAttrs);
const { shapeFlag } = root;
if (keys.length) {
if (shapeFlag & 7) {
if (propsOptions && keys.some(isModelListener)) fallthroughAttrs = filterModelListeners(fallthroughAttrs, propsOptions);
root = cloneVNode(root, fallthroughAttrs, false, true);
}
}
}
if (vnode.dirs) {
root = cloneVNode(root, null, false, true);
root.dirs = root.dirs ? root.dirs.concat(vnode.dirs) : vnode.dirs;
}
if (vnode.transition) setTransitionHooks(isTeleport(root.type) ? getInnerChild$1(root) || root : root, vnode.transition);
result = root;
setCurrentRenderingInstance(prev);
return result;
}
function filterSingleRoot(children, recurse = true) {
let singleRoot;
for (let i = 0; i < children.length; i++) {
const child = children[i];
if (isVNode(child)) {
if (child.type !== Comment || child.children === "v-if") {
if (singleRoot) return;
else singleRoot = child;
}
} else return;
}
return singleRoot;
}
var getFunctionalFallthrough = (attrs) => {
let res;
for (const key in attrs) if (key === "class" || key === "style" || isOn(key)) (res || (res = {}))[key] = attrs[key];
return res;
};
var filterModelListeners = (attrs, props) => {
const res = {};
for (const key in attrs) if (!isModelListener(key) || !(key.slice(9) in props)) res[key] = attrs[key];
return res;
};
function shouldUpdateComponent(prevVNode, nextVNode, optimized) {
const { props: prevProps, children: prevChildren, component } = prevVNode;
const { props: nextProps, children: nextChildren, patchFlag } = nextVNode;
const emits = component.emitsOptions;
if (nextVNode.dirs || nextVNode.transition) return true;
if (optimized && patchFlag >= 0) {
if (patchFlag & 1024) return true;
if (patchFlag & 16) {
if (!prevProps) return !!nextProps;
return hasPropsChanged(prevProps, nextProps, emits);
} else if (patchFlag & 8) {
const dynamicProps = nextVNode.dynamicProps;
for (let i = 0; i < dynamicProps.length; i++) {
const key = dynamicProps[i];
if (hasPropValueChanged(nextProps, prevProps, key) && !isEmitListener(emits, key)) return true;
}
}
} else {
if (prevChildren || nextChildren) {
if (!nextChildren || !nextChildren.$stable) return true;
}
if (prevProps === nextProps) return false;
if (!prevProps) return !!nextProps;
if (!nextProps) return true;
return hasPropsChanged(prevProps, nextProps, emits);
}
return false;
}
function hasPropsChanged(prevProps, nextProps, emitsOptions) {
const nextKeys = Object.keys(nextProps);
if (nextKeys.length !== Object.keys(prevProps).length) return true;
for (let i = 0; i < nextKeys.length; i++) {
const key = nextKeys[i];
if (!hasOwn(prevProps, key) || hasPropValueChanged(nextProps, prevProps, key) && !isEmitListener(emitsOptions, key)) return true;
}
return false;
}
function hasPropValueChanged(nextProps, prevProps, key) {
const nextProp = nextProps[key];
const prevProp = prevProps[key];
if (key === "style" && isObject$3(nextProp) && isObject$3(prevProp)) return !looseEqual(nextProp, prevProp);
return nextProp !== prevProp;
}
function updateHOCHostEl({ vnode, parent, suspense }, el) {
while (parent) {
const root = parent.subTree;
if (root.suspense && root.suspense.activeBranch === vnode) {
root.suspense.vnode.el = root.el = el;
vnode = root;
}
if (root === vnode) {
(vnode = parent.vnode).el = el;
parent = parent.parent;
} else break;
}
if (suspense && suspense.activeBranch === vnode) suspense.vnode.el = el;
}
var internalObjectProto = {};
var createInternalObject = () => Object.create(internalObjectProto);
var isInternalObject = (obj) => Object.getPrototypeOf(obj) === internalObjectProto;
function initProps(instance, rawProps, isStateful, isSSR = false) {
const props = {};
const attrs = createInternalObject();
instance.propsDefaults = Object.create(null);
setFullProps(instance, rawProps, props, attrs);
for (const key in instance.propsOptions[0]) if (!(key in props)) props[key] = void 0;
if (isStateful) instance.props = isSSR ? props : shallowReactive(props);
else if (!instance.type.props) instance.props = attrs;
else instance.props = props;
instance.attrs = attrs;
}
function updateProps(instance, rawProps, rawPrevProps, optimized) {
const { props, attrs, vnode: { patchFlag } } = instance;
const rawCurrentProps = toRaw(props);
const [options] = instance.propsOptions;
let hasAttrsChanged = false;
if ((optimized || patchFlag > 0) && !(patchFlag & 16)) {
if (patchFlag & 8) {
const propsToUpdate = instance.vnode.dynamicProps;
for (let i = 0; i < propsToUpdate.length; i++) {
let key = propsToUpdate[i];
if (isEmitListener(instance.emitsOptions, key)) continue;
const value = rawProps[key];
if (options) {
if (hasOwn(attrs, key)) {
if (value !== attrs[key]) {
attrs[key] = value;
hasAttrsChanged = true;
}
} else {
const camelizedKey = camelize$2(key);
props[camelizedKey] = resolvePropValue(options, rawCurrentProps, camelizedKey, value, instance, false);
}
} else if (value !== attrs[key]) {
attrs[key] = value;
hasAttrsChanged = true;
}
}
}
} else {
if (setFullProps(instance, rawProps, props, attrs)) hasAttrsChanged = true;
let kebabKey;
for (const key in rawCurrentProps) if (!rawProps || !hasOwn(rawProps, key) && ((kebabKey = hyphenate$2(key)) === key || !hasOwn(rawProps, kebabKey))) {
if (options) {
if (rawPrevProps && (rawPrevProps[key] !== void 0 || rawPrevProps[kebabKey] !== void 0)) props[key] = resolvePropValue(options, rawCurrentProps, key, void 0, instance, true);
} else delete props[key];
}
if (attrs !== rawCurrentProps) {
for (const key in attrs) if (!rawProps || !hasOwn(rawProps, key) && true) {
delete attrs[key];
hasAttrsChanged = true;
}
}
}
if (hasAttrsChanged) trigger(instance.attrs, "set", "");
}
function setFullProps(instance, rawProps, props, attrs) {
const [options, needCastKeys] = instance.propsOptions;
let hasAttrsChanged = false;
let rawCastValues;
if (rawProps) for (let key in rawProps) {
if (isReservedProp(key)) continue;
const value = rawProps[key];
let camelKey;
if (options && hasOwn(options, camelKey = camelize$2(key))) {
if (!needCastKeys || !needCastKeys.includes(camelKey)) props[camelKey] = value;
else (rawCastValues || (rawCastValues = {}))[camelKey] = value;
} else if (!isEmitListener(instance.emitsOptions, key)) {
if (!(key in attrs) || value !== attrs[key]) {
attrs[key] = value;
hasAttrsChanged = true;
}
}
}
if (needCastKeys) {
const rawCurrentProps = toRaw(props);
const castValues = rawCastValues || EMPTY_OBJ;
for (let i = 0; i < needCastKeys.length; i++) {
const key = needCastKeys[i];
props[key] = resolvePropValue(options, rawCurrentProps, key, castValues[key], instance, !hasOwn(castValues, key));
}
}
return hasAttrsChanged;
}
function resolvePropValue(options, props, key, value, instance, isAbsent) {
const opt = options[key];
if (opt != null) {
const hasDefault = hasOwn(opt, "default");
if (hasDefault && value === void 0) {
const defaultValue = opt.default;
if (opt.type !== Function && !opt.skipFactory && isFunction(defaultValue)) {
const { propsDefaults } = instance;
if (key in propsDefaults) value = propsDefaults[key];
else {
const reset = setCurrentInstance(instance);
value = propsDefaults[key] = defaultValue.call(null, props);
reset();
}
} else value = defaultValue;
if (instance.ce) instance.ce._setProp(key, value);
}
if (opt[0]) {
if (isAbsent && !hasDefault) value = false;
else if (opt[1] && (value === "" || value === hyphenate$2(key))) value = true;
}
}
return value;
}
var mixinPropsCache = new WeakMap();
function normalizePropsOptions(comp, appContext, asMixin = false) {
const cache = asMixin ? mixinPropsCache : appContext.propsCache;
const cached = cache.get(comp);
if (cached) return cached;
const raw = comp.props;
const normalized = {};
const needCastKeys = [];
let hasExtends = false;
if (!isFunction(comp)) {
const extendProps = (raw2) => {
hasExtends = true;
const [props, keys] = normalizePropsOptions(raw2, appContext, true);
extend(normalized, props);
if (keys) needCastKeys.push(...keys);
};
if (!asMixin && appContext.mixins.length) appContext.mixins.forEach(extendProps);
if (comp.extends) extendProps(comp.extends);
if (comp.mixins) comp.mixins.forEach(extendProps);
}
if (!raw && !hasExtends) {
if (isObject$3(comp)) cache.set(comp, EMPTY_ARR);
return EMPTY_ARR;
}
if (isArray$1(raw)) for (let i = 0; i < raw.length; i++) {
const normalizedKey = camelize$2(raw[i]);
if (validatePropName(normalizedKey)) normalized[normalizedKey] = EMPTY_OBJ;
}
else if (raw) for (const key in raw) {
const normalizedKey = camelize$2(key);
if (validatePropName(normalizedKey)) {
const opt = raw[key];
const prop = normalized[normalizedKey] = isArray$1(opt) || isFunction(opt) ? { type: opt } : extend({}, opt);
const propType = prop.type;
let shouldCast = false;
let shouldCastTrue = true;
if (isArray$1(propType)) for (let index = 0; index < propType.length; ++index) {
const type = propType[index];
const typeName = isFunction(type) && type.name;
if (typeName === "Boolean") {
shouldCast = true;
break;
} else if (typeName === "String") shouldCastTrue = false;
}
else shouldCast = isFunction(propType) && propType.name === "Boolean";
prop[0] = shouldCast;
prop[1] = shouldCastTrue;
if (shouldCast || hasOwn(prop, "default")) needCastKeys.push(normalizedKey);
}
}
const res = [normalized, needCastKeys];
if (isObject$3(comp)) cache.set(comp, res);
return res;
}
function validatePropName(key) {
if (key[0] !== "$" && !isReservedProp(key)) return true;
return false;
}
var isInternalKey = (key) => key === "_" || key === "_ctx" || key === "$stable";
var normalizeSlotValue = (value) => isArray$1(value) ? value.map(normalizeVNode) : [normalizeVNode(value)];
var normalizeSlot = (key, rawSlot, ctx) => {
if (rawSlot._n) return rawSlot;
const normalized = withCtx((...args) => {
return normalizeSlotValue(rawSlot(...args));
}, ctx);
normalized._c = false;
return normalized;
};
var normalizeObjectSlots = (rawSlots, slots, instance) => {
const ctx = rawSlots._ctx;
for (const key in rawSlots) {
if (isInternalKey(key)) continue;
const value = rawSlots[key];
if (isFunction(value)) slots[key] = normalizeSlot(key, value, ctx);
else if (value != null) {
const normalized = normalizeSlotValue(value);
slots[key] = () => normalized;
}
}
};
var normalizeVNodeSlots = (instance, children) => {
const normalized = normalizeSlotValue(children);
instance.slots.default = () => normalized;
};
var assignSlots = (slots, children, optimized) => {
for (const key in children) if (optimized || !isInternalKey(key)) slots[key] = children[key];
};
var initSlots = (instance, children, optimized) => {
const slots = instance.slots = createInternalObject();
if (instance.vnode.shapeFlag & 32) {
const type = children._;
if (type) {
assignSlots(slots, children, optimized);
if (optimized) def(slots, "_", type, true);
} else normalizeObjectSlots(children, slots);
} else if (children) normalizeVNodeSlots(instance, children);
};
var updateSlots = (instance, children, optimized) => {
const { vnode, slots } = instance;
let needDeletionCheck = true;
let deletionComparisonTarget = EMPTY_OBJ;
if (vnode.shapeFlag & 32) {
const type = children._;
if (type) {
if (optimized && type === 1) needDeletionCheck = false;
else assignSlots(slots, children, optimized);
} else {
needDeletionCheck = !children.$stable;
normalizeObjectSlots(children, slots);
}
deletionComparisonTarget = children;
} else if (children) {
normalizeVNodeSlots(instance, children);
deletionComparisonTarget = { default: 1 };
}
if (needDeletionCheck) {
for (const key in slots) if (!isInternalKey(key) && deletionComparisonTarget[key] == null) delete slots[key];
}
};
var queuePostRenderEffect = queueEffectWithSuspense;
function createRenderer(options) {
return baseCreateRenderer(options);
}
function baseCreateRenderer(options, createHydrationFns) {
const target = getGlobalThis();
target.__VUE__ = true;
const { insert: hostInsert, remove: hostRemove, patchProp: hostPatchProp, createElement: hostCreateElement, createText: hostCreateText, createComment: hostCreateComment, setText: hostSetText, setElementText: hostSetElementText, parentNode: hostParentNode, nextSibling: hostNextSibling, setScopeId: hostSetScopeId = NOOP, insertStaticContent: hostInsertStaticContent } = options;
const patch = (n1, n2, container, anchor = null, parentComponent = null, parentSuspense = null, namespace = void 0, slotScopeIds = null, optimized = !!n2.dynamicChildren) => {
if (n1 === n2) return;
if (n1 && !isSameVNodeType(n1, n2)) {
anchor = getNextHostNode(n1);
unmount(n1, parentComponent, parentSuspense, true);
n1 = null;
}
if (n2.patchFlag === -2) {
optimized = false;
n2.dynamicChildren = null;
}
if (n2.dynamicChildren && n1 && n1.dynamicChildren && n1.dynamicChildren.hasOnce) {
if (n2.dynamicChildren === EMPTY_ARR) n2.dynamicChildren = [];
n2.dynamicChildren.hasOnce = true;
}
const { type, ref, shapeFlag } = n2;
switch (type) {
case Text:
processText(n1, n2, container, anchor);
break;
case Comment:
processCommentNode(n1, n2, container, anchor);
break;
case Static:
if (n1 == null) mountStaticNode(n2, container, anchor, namespace);
break;
case Fragment:
processFragment(n1, n2, container, anchor, parentComponent, parentSuspense, namespace, slotScopeIds, optimized);
break;
default: if (shapeFlag & 1) processElement(n1, n2, container, anchor, parentComponent, parentSuspense, namespace, slotScopeIds, optimized);
else if (shapeFlag & 6) processComponent(n1, n2, container, anchor, parentComponent, parentSuspense, namespace, slotScopeIds, optimized);
else if (shapeFlag & 64) type.process(n1, n2, container, anchor, parentComponent, parentSuspense, namespace, slotScopeIds, optimized, internals);
else if (shapeFlag & 128) type.process(n1, n2, container, anchor, parentComponent, parentSuspense, namespace, slotScopeIds, optimized, internals);
}
if (ref != null && parentComponent) setRef(ref, n1 && n1.ref, parentSuspense, n2 || n1, !n2);
else if (ref == null && n1 && n1.ref != null) setRef(n1.ref, null, parentSuspense, n1, true);
};
const processText = (n1, n2, container, anchor) => {
if (n1 == null) hostInsert(n2.el = hostCreateText(n2.children), container, anchor);
else {
const el = n2.el = n1.el;
if (n2.children !== n1.children) hostSetText(el, n2.children);
}
};
const processCommentNode = (n1, n2, container, anchor) => {
if (n1 == null) hostInsert(n2.el = hostCreateComment(n2.children || ""), container, anchor);
else n2.el = n1.el;
};
const mountStaticNode = (n2, container, anchor, namespace) => {
[n2.el, n2.anchor] = hostInsertStaticContent(n2.children, container, anchor, namespace, n2.el, n2.anchor);
};
const moveStaticNode = ({ el, anchor }, container, nextSibling) => {
let next;
while (el && el !== anchor) {
next = hostNextSibling(el);
hostInsert(el, container, nextSibling);
el = next;
}
hostInsert(anchor, container, nextSibling);
};
const removeStaticNode = ({ el, anchor }) => {
let next;
while (el && el !== anchor) {
next = hostNextSibling(el);
hostRemove(el);
el = next;
}
hostRemove(anchor);
};
const processElement = (n1, n2, container, anchor, parentComponent, parentSuspense, namespace, slotScopeIds, optimized) => {
if (n2.type === "svg") namespace = "svg";
else if (n2.type === "math") namespace = "mathml";
if (n1 == null) mountElement(n2, container, anchor, parentComponent, parentSuspense, namespace, slotScopeIds, optimized);
else {
const customElement = n1.el && n1.el._isVueCE ? n1.el : null;
try {
if (customElement) customElement._beginPatch();
patchElement(n1, n2, parentComponent, parentSuspense, namespace, slotScopeIds, optimized);
} finally {
if (customElement) customElement._endPatch();
}
}
};
const mountElement = (vnode, container, anchor, parentComponent, parentSuspense, namespace, slotScopeIds, optimized) => {
let el;
let vnodeHook;
const { props, shapeFlag, transition, dirs } = vnode;
el = vnode.el = hostCreateElement(vnode.type, namespace, props && props.is, props);
if (shapeFlag & 8) hostSetElementText(el, vnode.children);
else if (shapeFlag & 16) mountChildren(vnode.children, el, null, parentComponent, parentSuspense, resolveChildrenNamespace(vnode, namespace), slotScopeIds, optimized);
if (dirs) invokeDirectiveHook(vnode, null, parentComponent, "created");
setScopeId(el, vnode, vnode.scopeId, slotScopeIds, parentComponent);
if (props) {
for (const key in props) if (key !== "value" && !isReservedProp(key)) hostPatchProp(el, key, null, props[key], namespace, parentComponent);
if ("value" in props) hostPatchProp(el, "value", null, props.value, namespace);
if (vnodeHook = props.onVnodeBeforeMount) invokeVNodeHook(vnodeHook, parentComponent, vnode);
}
if (dirs) invokeDirectiveHook(vnode, null, parentComponent, "beforeMount");
const needCallTransitionHooks = needTransition(parentSuspense, transition);
if (needCallTransitionHooks) transition.beforeEnter(el);
else if (transition && !transition.persisted) el[deferredEnterKey] = true;
hostInsert(el, container, anchor);
if ((vnodeHook = props && props.onVnodeMounted) || needCallTransitionHooks || dirs) queuePostRenderEffect(() => {
try {
vnodeHook && invokeVNodeHook(vnodeHook, parentComponent, vnode);
needCallTransitionHooks && transition.enter(el);
dirs && invokeDirectiveHook(vnode, null, parentComponent, "mounted");
} finally {}
}, parentSuspense);
};
const setScopeId = (el, vnode, scopeId, slotScopeIds, parentComponent) => {
if (scopeId) hostSetScopeId(el, scopeId);
if (slotScopeIds) for (let i = 0; i < slotScopeIds.length; i++) hostSetScopeId(el, slotScopeIds[i]);
if (parentComponent) {
let subTree = parentComponent.subTree;
if (vnode === subTree || isSuspense(subTree.type) && (subTree.ssContent === vnode || subTree.ssFallback === vnode)) {
const parentVNode = parentComponent.vnode;
setScopeId(el, parentVNode, parentVNode.scopeId, parentVNode.slotScopeIds, parentComponent.parent);
}
}
};
const mountChildren = (children, container, anchor, parentComponent, parentSuspense, namespace, slotScopeIds, optimized, start = 0) => {
for (let i = start; i < children.length; i++) {
const child = children[i] = optimized ? cloneIfMounted(children[i]) : normalizeVNode(children[i]);
patch(null, child, container, anchor, parentComponent, parentSuspense, namespace, slotScopeIds, optimized);
}
};
const patchElement = (n1, n2, parentComponent, parentSuspense, namespace, slotScopeIds, optimized) => {
const el = n2.el = n1.el;
let { patchFlag, dynamicChildren, dirs } = n2;
patchFlag |= n1.patchFlag & 16;
const oldProps = n1.props || EMPTY_OBJ;
const newProps = n2.props || EMPTY_OBJ;
let vnodeHook;
parentComponent && toggleRecurse(parentComponent, false);
if (vnodeHook = newProps.onVnodeBeforeUpdate) invokeVNodeHook(vnodeHook, parentComponent, n2, n1);
if (dirs) invokeDirectiveHook(n2, n1, parentComponent, "beforeUpdate");
parentComponent && toggleRecurse(parentComponent, true);
if (dynamicChildren && (!n1.dynamicChildren || n1.dynamicChildren.length !== dynamicChildren.length)) {
patchFlag = 0;
optimized = false;
dynamicChildren = null;
}
if (oldProps.innerHTML && newProps.innerHTML == null || oldProps.textContent && newProps.textContent == null) hostSetElementText(el, "");
if (dynamicChildren) patchBlockChildren(n1.dynamicChildren, dynamicChildren, el, parentComponent, parentSuspense, resolveChildrenNamespace(n2, namespace), slotScopeIds);
else if (!optimized) patchChildren(n1, n2, el, null, parentComponent, parentSuspense, resolveChildrenNamespace(n2, namespace), slotScopeIds, false);
if (patchFlag > 0) {
if (patchFlag & 16) patchProps(el, oldProps, newProps, parentComponent, namespace);
else {
if (patchFlag & 2) {
if (oldProps.class !== newProps.class) hostPatchProp(el, "class", null, newProps.class, namespace);
}
if (patchFlag & 4) hostPatchProp(el, "style", oldProps.style, newProps.style, namespace);
if (patchFlag & 8) {
const propsToUpdate = n2.dynamicProps;
for (let i = 0; i < propsToUpdate.length; i++) {
const key = propsToUpdate[i];
const prev = oldProps[key];
const next = newProps[key];
if (next !== prev || key === "value") hostPatchProp(el, key, prev, next, namespace, parentComponent);
}
}
}
if (patchFlag & 1) {
if (n1.children !== n2.children) hostSetElementText(el, n2.children);
}
} else if (!optimized && dynamicChildren == null) patchProps(el, oldProps, newProps, parentComponent, namespace);
if ((vnodeHook = newProps.onVnodeUpdated) || dirs) queuePostRenderEffect(() => {
vnodeHook && invokeVNodeHook(vnodeHook, parentComponent, n2, n1);
dirs && invokeDirectiveHook(n2, n1, parentComponent, "updated");
}, parentSuspense);
};
const patchBlockChildren = (oldChildren, newChildren, fallbackContainer, parentComponent, parentSuspense, namespace, slotScopeIds) => {
for (let i = 0; i < newChildren.length; i++) {
const oldVNode = oldChildren[i];
const newVNode = newChildren[i];
const oldEl = oldVNode.el || resolveAsyncComponentPlaceholder(oldVNode);
const container = oldEl && (oldVNode.type === Fragment || !isSameVNodeType(oldVNode, newVNode) || oldVNode.shapeFlag & 198) ? hostParentNode(oldEl) : fallbackContainer;
patch(oldVNode, newVNode, container, null, parentComponent, parentSuspense, namespace, slotScopeIds, true);
}
};
const patchProps = (el, oldProps, newProps, parentComponent, namespace) => {
if (oldProps !== newProps) {
if (oldProps !== EMPTY_OBJ) {
for (const key in oldProps) if (!isReservedProp(key) && !(key in newProps)) hostPatchProp(el, key, oldProps[key], null, namespace, parentComponent);
}
for (const key in newProps) {
if (isReservedProp(key)) continue;
const next = newProps[key];
const prev = oldProps[key];
if (next !== prev && key !== "value") hostPatchProp(el, key, prev, next, namespace, parentComponent);
}
if ("value" in newProps) hostPatchProp(el, "value", oldProps.value, newProps.value, namespace);
}
};
const processFragment = (n1, n2, container, anchor, parentComponent, parentSuspense, namespace, slotScopeIds, optimized) => {
const fragmentStartAnchor = n2.el = n1 ? n1.el : hostCreateText("");
const fragmentEndAnchor = n2.anchor = n1 ? n1.anchor : hostCreateText("");
let { patchFlag, dynamicChildren, slotScopeIds: fragmentSlotScopeIds } = n2;
if (fragmentSlotScopeIds) slotScopeIds = slotScopeIds ? slotScopeIds.concat(fragmentSlotScopeIds) : fragmentSlotScopeIds;
if (n1 == null) {
hostInsert(fragmentStartAnchor, container, anchor);
hostInsert(fragmentEndAnchor, container, anchor);
mountChildren(n2.children || [], container, fragmentEndAnchor, parentComponent, parentSuspense, namespace, slotScopeIds, optimized);
} else if (patchFlag > 0 && patchFlag & 64 && dynamicChildren && n1.dynamicChildren && n1.dynamicChildren.length === dynamicChildren.length) {
patchBlockChildren(n1.dynamicChildren, dynamicChildren, container, parentComponent, parentSuspense, namespace, slotScopeIds);
if (n2.key != null || parentComponent && n2 === parentComponent.subTree) traverseStaticChildren(n1, n2, true);
} else patchChildren(n1, n2, container, fragmentEndAnchor, parentComponent, parentSuspense, namespace, slotScopeIds, optimized);
};
const processComponent = (n1, n2, container, anchor, parentComponent, parentSuspense, namespace, slotScopeIds, optimized) => {
n2.slotScopeIds = slotScopeIds;
if (n1 == null) {
if (n2.shapeFlag & 512) parentComponent.ctx.activate(n2, container, anchor, namespace, optimized);
else mountComponent(n2, container, anchor, parentComponent, parentSuspense, namespace, optimized);
} else updateComponent(n1, n2, optimized);
};
const mountComponent = (initialVNode, container, anchor, parentComponent, parentSuspense, namespace, optimized) => {
const instance = initialVNode.component = createComponentInstance(initialVNode, parentComponent, parentSuspense);
if (isKeepAlive(initialVNode)) instance.ctx.renderer = internals;
setupComponent(instance, false, optimized);
if (instance.asyncDep) {
parentSuspense && parentSuspense.registerDep(instance, setupRenderEffect, optimized, namespace);
if (!initialVNode.el) {
const placeholder = instance.subTree = createVNode(Comment);
processCommentNode(null, placeholder, container, anchor);
initialVNode.placeholder = placeholder.el;
}
} else setupRenderEffect(instance, initialVNode, container, anchor, parentSuspense, namespace, optimized);
};
const updateComponent = (n1, n2, optimized) => {
const instance = n2.component = n1.component;
if (shouldUpdateComponent(n1, n2, optimized)) {
if (instance.asyncDep && !instance.asyncResolved) {
n2.el = n1.el;
n2.placeholder = n1.placeholder;
updateComponentPreRender(instance, n2, optimized);
return;
} else {
instance.next = n2;
instance.update();
}
} else {
n2.el = n1.el;
n2.placeholder = n1.placeholder;
instance.vnode = n2;
}
};
const setupRenderEffect = (instance, initialVNode, container, anchor, parentSuspense, namespace, optimized) => {
const componentUpdateFn = () => {
if (!instance.isMounted) {
let vnodeHook;
const { el, props } = initialVNode;
const { bm, m, parent, root, type } = instance;
const isAsyncWrapperVNode = isAsyncWrapper(initialVNode);
toggleRecurse(instance, false);
if (bm) invokeArrayFns(bm);
if (!isAsyncWrapperVNode && (vnodeHook = props && props.onVnodeBeforeMount)) invokeVNodeHook(vnodeHook, parent, initialVNode);
toggleRecurse(instance, true);
if (el && hydrateNode) {
const hydrateSubTree = () => {
instance.subTree = renderComponentRoot(instance);
hydrateNode(el, instance.subTree, instance, parentSuspense, null);
};
if (isAsyncWrapperVNode && type.__asyncHydrate) type.__asyncHydrate(el, instance, hydrateSubTree);
else hydrateSubTree();
} else {
if (root.ce && root.ce._hasShadowRoot()) root.ce._injectChildStyle(type, instance.parent ? instance.parent.type : void 0);
const subTree = instance.subTree = renderComponentRoot(instance);
patch(null, subTree, container, anchor, instance, parentSuspense, namespace);
initialVNode.el = subTree.el;
}
if (m) queuePostRenderEffect(m, parentSuspense);
if (!isAsyncWrapperVNode && (vnodeHook = props && props.onVnodeMounted)) {
const scopedInitialVNode = initialVNode;
queuePostRenderEffect(() => invokeVNodeHook(vnodeHook, parent, scopedInitialVNode), parentSuspense);
}
if (initialVNode.shapeFlag & 256 || parent && isAsyncWrapper(parent.vnode) && parent.vnode.shapeFlag & 256) instance.a && queuePostRenderEffect(instance.a, parentSuspense);
instance.isMounted = true;
initialVNode = container = anchor = null;
} else {
let { next, bu, u, parent, vnode } = instance;
{
const unresolvedAsyncRoot = locateUnresolvedAsyncRoot(instance);
if (unresolvedAsyncRoot) {
if (next) {
next.el = vnode.el;
updateComponentPreRender(instance, next, optimized);
}
unresolvedAsyncRoot.asyncDep.then(() => {
const retry = () => {
if (instance.job.flags & 8) return;
if (parentSuspense && parentSuspense.pendingBranch) queuePostRenderEffect(retry, parentSuspense);
else update();
};
retry.flags = 48;
queuePostRenderEffect(retry, parentSuspense);
});
return;
}
}
let originNext = next;
let vnodeHook;
toggleRecurse(instance, false);
if (next) {
next.el = vnode.el;
updateComponentPreRender(instance, next, optimized);
} else next = vnode;
if (bu) invokeArrayFns(bu);
if (vnodeHook = next.props && next.props.onVnodeBeforeUpdate) invokeVNodeHook(vnodeHook, parent, next, vnode);
toggleRecurse(instance, true);
const nextTree = renderComponentRoot(instance);
const prevTree = instance.subTree;
instance.subTree = nextTree;
patch(prevTree, nextTree, hostParentNode(prevTree.el || resolveAsyncComponentPlaceholder(prevTree)), getNextHostNode(prevTree), instance, parentSuspense, namespace);
next.el = nextTree.el;
if (originNext === null) updateHOCHostEl(instance, nextTree.el);
if (u) queuePostRenderEffect(u, parentSuspense);
if (vnodeHook = next.props && next.props.onVnodeUpdated) queuePostRenderEffect(() => invokeVNodeHook(vnodeHook, parent, next, vnode), parentSuspense);
}
};
instance.scope.on();
const effect = instance.effect = new ReactiveEffect(componentUpdateFn);
instance.scope.off();
const update = instance.update = effect.run.bind(effect);
const job = instance.job = effect.runIfDirty.bind(effect);
job.i = instance;
job.id = instance.uid;
effect.scheduler = () => queueJob(job);
toggleRecurse(instance, true);
update();
};
const updateComponentPreRender = (instance, nextVNode, optimized) => {
nextVNode.component = instance;
const prevProps = instance.vnode.props;
instance.vnode = nextVNode;
instance.next = null;
updateProps(instance, nextVNode.props, prevProps, optimized);
updateSlots(instance, nextVNode.children, optimized);
pauseTracking();
flushPreFlushCbs(instance);
resetTracking();
};
const patchChildren = (n1, n2, container, anchor, parentComponent, parentSuspense, namespace, slotScopeIds, optimized = false) => {
const c1 = n1 && n1.children;
const prevShapeFlag = n1 ? n1.shapeFlag : 0;
const c2 = n2.children;
const { patchFlag, shapeFlag } = n2;
if (patchFlag > 0) {
if (patchFlag & 128) {
patchKeyedChildren(c1, c2, container, anchor, parentComponent, parentSuspense, namespace, slotScopeIds, optimized);
return;
} else if (patchFlag & 256) {
patchUnkeyedChildren(c1, c2, container, anchor, parentComponent, parentSuspense, namespace, slotScopeIds, optimized);
return;
}
}
if (shapeFlag & 8) {
if (prevShapeFlag & 16) unmountChildren(c1, parentComponent, parentSuspense);
if (c2 !== c1) hostSetElementText(container, c2);
} else if (prevShapeFlag & 16) {
if (shapeFlag & 16) patchKeyedChildren(c1, c2, container, anchor, parentComponent, parentSuspense, namespace, slotScopeIds, optimized);
else unmountChildren(c1, parentComponent, parentSuspense, true);
} else {
if (prevShapeFlag & 8) hostSetElementText(container, "");
if (shapeFlag & 16) mountChildren(c2, container, anchor, parentComponent, parentSuspense, namespace, slotScopeIds, optimized);
}
};
const patchUnkeyedChildren = (c1, c2, container, anchor, parentComponent, parentSuspense, namespace, slotScopeIds, optimized) => {
c1 = c1 || EMPTY_ARR;
c2 = c2 || EMPTY_ARR;
const oldLength = c1.length;
const newLength = c2.length;
const commonLength = Math.min(oldLength, newLength);
let i = 0;
for (; i < commonLength; i++) {
const nextChild = c2[i] = optimized ? cloneIfMounted(c2[i]) : normalizeVNode(c2[i]);
patch(c1[i], nextChild, container, null, parentComponent, parentSuspense, namespace, slotScopeIds, optimized);
}
if (oldLength > newLength) unmountChildren(c1, parentComponent, parentSuspense, true, false, commonLength);
else mountChildren(c2, container, anchor, parentComponent, parentSuspense, namespace, slotScopeIds, optimized, commonLength);
};
const patchKeyedChildren = (c1, c2, container, parentAnchor, parentComponent, parentSuspense, namespace, slotScopeIds, optimized) => {
let i = 0;
const l2 = c2.length;
let e1 = c1.length - 1;
let e2 = l2 - 1;
while (i <= e1 && i <= e2) {
const n1 = c1[i];
const n2 = c2[i] = optimized ? cloneIfMounted(c2[i]) : normalizeVNode(c2[i]);
if (isSameVNodeType(n1, n2)) patch(n1, n2, container, null, parentComponent, parentSuspense, namespace, slotScopeIds, optimized);
else break;
i++;
}
while (i <= e1 && i <= e2) {
const n1 = c1[e1];
const n2 = c2[e2] = optimized ? cloneIfMounted(c2[e2]) : normalizeVNode(c2[e2]);
if (isSameVNodeType(n1, n2)) patch(n1, n2, container, null, parentComponent, parentSuspense, namespace, slotScopeIds, optimized);
else break;
e1--;
e2--;
}
if (i > e1) {
if (i <= e2) {
const nextPos = e2 + 1;
const anchor = nextPos < l2 ? c2[nextPos].el : parentAnchor;
while (i <= e2) {
patch(null, c2[i] = optimized ? cloneIfMounted(c2[i]) : normalizeVNode(c2[i]), container, anchor, parentComponent, parentSuspense, namespace, slotScopeIds, optimized);
i++;
}
}
} else if (i > e2) while (i <= e1) {
unmount(c1[i], parentComponent, parentSuspense, true);
i++;
}
else {
const s1 = i;
const s2 = i;
const keyToNewIndexMap = new Map();
for (i = s2; i <= e2; i++) {
const nextChild = c2[i] = optimized ? cloneIfMounted(c2[i]) : normalizeVNode(c2[i]);
if (nextChild.key != null) keyToNewIndexMap.set(nextChild.key, i);
}
let j;
let patched = 0;
const toBePatched = e2 - s2 + 1;
let moved = false;
let maxNewIndexSoFar = 0;
const newIndexToOldIndexMap = new Array(toBePatched);
for (i = 0; i < toBePatched; i++) newIndexToOldIndexMap[i] = 0;
for (i = s1; i <= e1; i++) {
const prevChild = c1[i];
if (patched >= toBePatched) {
unmount(prevChild, parentComponent, parentSuspense, true);
continue;
}
let newIndex;
if (prevChild.key != null) newIndex = keyToNewIndexMap.get(prevChild.key);
else for (j = s2; j <= e2; j++) if (newIndexToOldIndexMap[j - s2] === 0 && isSameVNodeType(prevChild, c2[j])) {
newIndex = j;
break;
}
if (newIndex === void 0) unmount(prevChild, parentComponent, parentSuspense, true);
else {
newIndexToOldIndexMap[newIndex - s2] = i + 1;
if (newIndex >= maxNewIndexSoFar) maxNewIndexSoFar = newIndex;
else moved = true;
patch(prevChild, c2[newIndex], container, null, parentComponent, parentSuspense, namespace, slotScopeIds, optimized);
patched++;
}
}
const increasingNewIndexSequence = moved ? getSequence(newIndexToOldIndexMap) : EMPTY_ARR;
j = increasingNewIndexSequence.length - 1;
for (i = toBePatched - 1; i >= 0; i--) {
const nextIndex = s2 + i;
const nextChild = c2[nextIndex];
const anchorVNode = c2[nextIndex + 1];
const anchor = nextIndex + 1 < l2 ? anchorVNode.el || resolveAsyncComponentPlaceholder(anchorVNode) : parentAnchor;
if (newIndexToOldIndexMap[i] === 0) patch(null, nextChild, container, anchor, parentComponent, parentSuspense, namespace, slotScopeIds, optimized);
else if (moved) {
if (j < 0 || i !== increasingNewIndexSequence[j]) move(nextChild, container, anchor, 2);
else j--;
}
}
}
};
const move = (vnode, container, anchor, moveType, parentSuspense = null) => {
const { el, type, transition, children, shapeFlag } = vnode;
if (shapeFlag & 6) {
move(vnode.component.subTree, container, anchor, moveType);
return;
}
if (shapeFlag & 128) {
vnode.suspense.move(container, anchor, moveType);
return;
}
if (shapeFlag & 64) {
type.move(vnode, container, anchor, internals);
return;
}
if (type === Fragment) {
hostInsert(el, container, anchor);
for (let i = 0; i < children.length; i++) move(children[i], container, anchor, moveType);
hostInsert(vnode.anchor, container, anchor);
return;
}
if (type === Static) {
moveStaticNode(vnode, container, anchor);
return;
}
if (moveType !== 2 && shapeFlag & 1 && transition) {
if (moveType === 0) {
if (transition.persisted && !el[leaveCbKey]) hostInsert(el, container, anchor);
else {
transition.beforeEnter(el);
hostInsert(el, container, anchor);
queuePostRenderEffect(() => transition.enter(el), parentSuspense);
}
} else {
const { leave, delayLeave, afterLeave } = transition;
const remove2 = () => {
if (vnode.ctx.isUnmounted) hostRemove(el);
else hostInsert(el, container, anchor);
};
const performLeave = () => {
const wasLeaving = el._isLeaving || !!el[leaveCbKey];
if (el._isLeaving) el[leaveCbKey](true);
if (transition.persisted && !wasLeaving) remove2();
else leave(el, () => {
remove2();
afterLeave && afterLeave();
});
};
if (delayLeave) delayLeave(el, remove2, performLeave);
else performLeave();
}
} else hostInsert(el, container, anchor);
};
const unmount = (vnode, parentComponent, parentSuspense, doRemove = false, optimized = false) => {
const { type, props, ref, children, dynamicChildren, shapeFlag, patchFlag, dirs, cacheIndex, memo } = vnode;
if (patchFlag === -2 || dynamicChildren && dynamicChildren.hasOnce) optimized = false;
if (ref != null) {
pauseTracking();
setRef(ref, null, parentSuspense, vnode, true);
resetTracking();
}
if (cacheIndex != null && (!vnode.ctx || vnode.ctx === parentComponent)) parentComponent.renderCache[cacheIndex] = void 0;
if (shapeFlag & 256 && parentComponent.ctx.deactivate(vnode)) return;
const shouldInvokeDirs = shapeFlag & 1 && dirs;
const shouldInvokeVnodeHook = !isAsyncWrapper(vnode);
let vnodeHook;
if (shouldInvokeVnodeHook && (vnodeHook = props && props.onVnodeBeforeUnmount)) invokeVNodeHook(vnodeHook, parentComponent, vnode);
if (shapeFlag & 6) unmountComponent(vnode.component, parentSuspense, doRemove);
else {
if (shapeFlag & 128) {
vnode.suspense.unmount(parentSuspense, doRemove);
return;
}
if (shouldInvokeDirs) invokeDirectiveHook(vnode, null, parentComponent, "beforeUnmount");
if (shapeFlag & 64) vnode.type.remove(vnode, parentComponent, parentSuspense, internals, doRemove);
else if (dynamicChildren && !dynamicChildren.hasOnce && (type !== Fragment || patchFlag > 0 && patchFlag & 64)) unmountChildren(dynamicChildren, parentComponent, parentSuspense, false, true);
else if (type === Fragment && patchFlag & 384 || !optimized && shapeFlag & 16) unmountChildren(children, parentComponent, parentSuspense);
if (doRemove) remove(vnode);
}
const shouldInvalidateMemo = memo != null && cacheIndex == null;
if (shouldInvokeVnodeHook && (vnodeHook = props && props.onVnodeUnmounted) || shouldInvokeDirs || shouldInvalidateMemo) queuePostRenderEffect(() => {
vnodeHook && invokeVNodeHook(vnodeHook, parentComponent, vnode);
shouldInvokeDirs && invokeDirectiveHook(vnode, null, parentComponent, "unmounted");
if (shouldInvalidateMemo) vnode.el = null;
}, parentSuspense);
};
const remove = (vnode) => {
const { type, el, anchor, transition } = vnode;
const isFragment = type === Fragment;
if (isFragment && !transition) {
removeFragment(el, anchor);
return;
}
if (type === Static) {
removeStaticNode(vnode);
if (transition && !transition.persisted && transition.afterLeave) transition.afterLeave();
return;
}
const leavingNode = isFragment ? getTransitionRoot(vnode) : vnode;
const performRemove = () => {
if (isFragment) {
if (hostParentNode(el)) removeFragment(el, anchor);
} else hostRemove(el);
if (transition && !transition.persisted && transition.afterLeave) transition.afterLeave();
};
if (leavingNode && leavingNode.shapeFlag & 1 && transition && !transition.persisted) {
const { leave, delayLeave } = transition;
const leavingEl = leavingNode.el;
const performLeave = () => leave(leavingEl, performRemove);
if (delayLeave) delayLeave(leavingEl, performRemove, performLeave);
else performLeave();
} else performRemove();
};
const removeFragment = (cur, end) => {
let next;
while (cur !== end) {
next = hostNextSibling(cur);
hostRemove(cur);
cur = next;
}
hostRemove(end);
};
const unmountComponent = (instance, parentSuspense, doRemove) => {
const { bum, scope, job, subTree, um, m, a } = instance;
invalidateMount(m);
invalidateMount(a);
if (bum) invokeArrayFns(bum);
scope.stop();
if (job) {
job.flags |= 8;
unmount(subTree, instance, parentSuspense, doRemove);
} else if (subTree) {
subTree.transition = instance.vnode.transition;
unmount(subTree, instance, parentSuspense, doRemove);
}
if (um) queuePostRenderEffect(um, parentSuspense);
const markUnmounted = () => {
instance.isUnmounted = true;
};
markUnmounted.flags = 16;
queuePostRenderEffect(markUnmounted, parentSuspense);
};
const unmountChildren = (children, parentComponent, parentSuspense, doRemove = false, optimized = false, start = 0) => {
for (let i = start; i < children.length; i++) unmount(children[i], parentComponent, parentSuspense, doRemove, optimized);
};
const getNextHostNode = (vnode) => {
if (vnode.shapeFlag & 6) return getNextHostNode(vnode.component.subTree);
if (vnode.shapeFlag & 128) return vnode.suspense.next();
const el = hostNextSibling(vnode.anchor || vnode.el);
const teleportEnd = el && el[TeleportEndKey];
return teleportEnd ? hostNextSibling(teleportEnd) : el;
};
const render = (vnode, container, namespace) => {
flushOnAppMount(() => {
if (vnode == null) {
if (container._vnode) unmount(container._vnode, null, null, true);
} else patch(container._vnode || null, vnode, container, null, null, null, namespace);
container._vnode = vnode;
}, vnode && container._vnode ? void 0 : vnode && vnode.component ? vnode.component.uid : getNextUid());
};
const internals = {
p: patch,
um: unmount,
m: move,
r: remove,
mt: mountComponent,
mc: mountChildren,
pc: patchChildren,
pbc: patchBlockChildren,
n: getNextHostNode,
o: options
};
let hydrate;
let hydrateNode;
if (createHydrationFns) [hydrate, hydrateNode] = createHydrationFns(internals);
return {
render,
hydrate,
createApp: createAppAPI(render, hydrate)
};
}
function resolveChildrenNamespace({ type, props }, currentNamespace) {
return currentNamespace === "svg" && type === "foreignObject" || currentNamespace === "mathml" && type === "annotation-xml" && props && props.encoding && props.encoding.includes("html") ? void 0 : currentNamespace;
}
function toggleRecurse({ effect, job }, allowed) {
if (allowed) {
effect.flags |= 32;
job.flags |= 4;
} else {
effect.flags &= -33;
job.flags &= -5;
}
}
function needTransition(parentSuspense, transition) {
return (!parentSuspense || parentSuspense && !parentSuspense.pendingBranch) && transition && !transition.persisted;
}
function traverseStaticChildren(n1, n2, shallow = false) {
const ch1 = n1.children;
const ch2 = n2.children;
if (isArray$1(ch1) && isArray$1(ch2)) for (let i = 0; i < ch1.length; i++) {
const c1 = ch1[i];
let c2 = ch2[i];
if (c2.shapeFlag & 1 && !c2.dynamicChildren) {
if (c2.patchFlag <= 0 || c2.patchFlag === 32) {
c2 = ch2[i] = cloneIfMounted(ch2[i]);
c2.el = c1.el;
}
if (!shallow && c2.patchFlag !== -2) traverseStaticChildren(c1, c2);
}
if (c2.type === Text) {
if (c2.patchFlag === -1) c2 = ch2[i] = cloneIfMounted(c2);
c2.el = c1.el;
}
if (c2.type === Comment && !c2.el) c2.el = c1.el;
}
}
function getSequence(arr) {
const p = arr.slice();
const result = [0];
let i, j, u, v, c;
const len = arr.length;
for (i = 0; i < len; i++) {
const arrI = arr[i];
if (arrI !== 0) {
j = result[result.length - 1];
if (arr[j] < arrI) {
p[i] = j;
result.push(i);
continue;
}
u = 0;
v = result.length - 1;
while (u < v) {
c = u + v >> 1;
if (arr[result[c]] < arrI) u = c + 1;
else v = c;
}
if (arrI < arr[result[u]]) {
if (u > 0) p[i] = result[u - 1];
result[u] = i;
}
}
}
u = result.length;
v = result[u - 1];
while (u-- > 0) {
result[u] = v;
v = p[v];
}
return result;
}
function locateUnresolvedAsyncRoot(instance) {
const subComponent = instance.subTree.component;
if (subComponent) {
if (subComponent.asyncDep && !subComponent.asyncResolved) return subComponent;
else return locateUnresolvedAsyncRoot(subComponent);
}
}
function invalidateMount(hooks) {
if (hooks) for (let i = 0; i < hooks.length; i++) hooks[i].flags |= 8;
}
function resolveAsyncComponentPlaceholder(anchorVnode) {
if (anchorVnode.placeholder) return anchorVnode.placeholder;
const instance = anchorVnode.component;
if (instance) return resolveAsyncComponentPlaceholder(instance.subTree);
const suspense = anchorVnode.suspense;
if (suspense && suspense.activeBranch) return resolveAsyncComponentPlaceholder(suspense.activeBranch);
return null;
}
var isSuspense = (type) => type.__isSuspense;
var deferredEnterKey = Symbol("_deferredEnter");
function queueEffectWithSuspense(fn, suspense) {
if (suspense && suspense.pendingBranch) {
if (isArray$1(fn)) suspense.effects.push(...fn);
else suspense.effects.push(fn);
} else queuePostFlushCb(fn);
}
var Fragment = Symbol.for("v-fgt");
var Text = Symbol.for("v-txt");
var Comment = Symbol.for("v-cmt");
var Static = Symbol.for("v-stc");
var blockStack = [];
var currentBlock = null;
function openBlock(disableTracking = false) {
blockStack.push(currentBlock = disableTracking ? null : []);
}
function closeBlock() {
blockStack.pop();
currentBlock = blockStack[blockStack.length - 1] || null;
}
var isBlockTreeEnabled = 1;
function setBlockTracking(value, inVOnce = false) {
isBlockTreeEnabled += value;
if (value < 0 && currentBlock && inVOnce) currentBlock.hasOnce = true;
}
function setupBlock(vnode) {
vnode.dynamicChildren = isBlockTreeEnabled > 0 ? currentBlock || EMPTY_ARR : null;
closeBlock();
if (isBlockTreeEnabled > 0 && currentBlock) currentBlock.push(vnode);
return vnode;
}
function createElementBlock(type, props, children, patchFlag, dynamicProps, shapeFlag) {
return setupBlock(createBaseVNode(type, props, children, patchFlag, dynamicProps, shapeFlag, true));
}
function createBlock(type, props, children, patchFlag, dynamicProps) {
return setupBlock(createVNode(type, props, children, patchFlag, dynamicProps, true));
}
function isVNode(value) {
return value ? value.__v_isVNode === true : false;
}
function isSameVNodeType(n1, n2) {
return n1.type === n2.type && n1.key === n2.key;
}
var normalizeKey = ({ key }) => key != null ? key : null;
var normalizeRef = ({ ref, ref_key, ref_for }) => {
if (typeof ref === "number") ref = "" + ref;
return ref != null ? isString$1(ref) || isRef(ref) || isFunction(ref) ? {
i: currentRenderingInstance,
r: ref,
k: ref_key,
f: !!ref_for
} : ref : null;
};
function createBaseVNode(type, props = null, children = null, patchFlag = 0, dynamicProps = null, shapeFlag = type === Fragment ? 0 : 1, isBlockNode = false, needFullChildrenNormalization = false) {
const vnode = {
__v_isVNode: true,
__v_skip: true,
type,
props,
key: props && normalizeKey(props),
ref: props && normalizeRef(props),
scopeId: currentScopeId,
slotScopeIds: null,
children,
component: null,
suspense: null,
ssContent: null,
ssFallback: null,
dirs: null,
transition: null,
el: null,
anchor: null,
target: null,
targetStart: null,
targetAnchor: null,
staticCount: 0,
shapeFlag,
patchFlag,
dynamicProps,
dynamicChildren: null,
appContext: null,
ctx: currentRenderingInstance
};
if (needFullChildrenNormalization) {
normalizeChildren(vnode, children);
if (shapeFlag & 128) type.normalize(vnode);
} else if (children) vnode.shapeFlag |= isString$1(children) ? 8 : 16;
if (isBlockTreeEnabled > 0 && !isBlockNode && currentBlock && (vnode.patchFlag > 0 || shapeFlag & 6) && vnode.patchFlag !== 32) currentBlock.push(vnode);
return vnode;
}
var createVNode = _createVNode;
function _createVNode(type, props = null, children = null, patchFlag = 0, dynamicProps = null, isBlockNode = false) {
if (!type || type === NULL_DYNAMIC_COMPONENT) type = Comment;
if (isVNode(type)) {
const cloned = cloneVNode(type, props, true);
if (children) normalizeChildren(cloned, children);
if (isBlockTreeEnabled > 0 && !isBlockNode && currentBlock) {
if (cloned.shapeFlag & 6) currentBlock[currentBlock.indexOf(type)] = cloned;
else currentBlock.push(cloned);
}
cloned.patchFlag = -2;
return cloned;
}
if (isClassComponent(type)) type = type.__vccOpts;
if (props) {
props = guardReactiveProps(props);
let { class: klass, style } = props;
if (klass && !isString$1(klass)) props.class = normalizeClass(klass);
if (isObject$3(style)) {
if (isProxy(style) && !isArray$1(style)) style = extend({}, style);
props.style = normalizeStyle(style);
}
}
const shapeFlag = isString$1(type) ? 1 : isSuspense(type) ? 128 : isTeleport(type) ? 64 : isObject$3(type) ? 4 : isFunction(type) ? 2 : 0;
return createBaseVNode(type, props, children, patchFlag, dynamicProps, shapeFlag, isBlockNode, true);
}
function guardReactiveProps(props) {
if (!props) return null;
if (isProxy(props)) return extend({}, props);
return isInternalObject(props) ? extend({}, props[rawAttrsKey] || props) : props;
}
function cloneVNode(vnode, extraProps, mergeRef = false, cloneTransition = false) {
const { props, ref, patchFlag, children, transition } = vnode;
const mergedProps = extraProps ? mergeProps(props || {}, extraProps) : props;
const cloned = {
__v_isVNode: true,
__v_skip: true,
type: vnode.type,
props: mergedProps,
key: mergedProps && normalizeKey(mergedProps),
ref: extraProps && extraProps.ref ? mergeRef && ref ? isArray$1(ref) ? ref.concat(normalizeRef(extraProps)) : [ref, normalizeRef(extraProps)] : normalizeRef(extraProps) : ref,
scopeId: vnode.scopeId,
slotScopeIds: vnode.slotScopeIds,
children,
target: vnode.target,
targetStart: vnode.targetStart,
targetAnchor: vnode.targetAnchor,
staticCount: vnode.staticCount,
shapeFlag: vnode.shapeFlag,
patchFlag: extraProps && vnode.type !== Fragment ? patchFlag === -1 ? 16 : patchFlag | 16 : patchFlag,
dynamicProps: vnode.dynamicProps,
dynamicChildren: vnode.dynamicChildren,
appContext: vnode.appContext,
dirs: vnode.dirs,
transition,
component: vnode.component,
suspense: vnode.suspense,
ssContent: vnode.ssContent && cloneVNode(vnode.ssContent),
ssFallback: vnode.ssFallback && cloneVNode(vnode.ssFallback),
placeholder: vnode.placeholder,
el: vnode.el,
anchor: vnode.anchor,
ctx: vnode.ctx,
ce: vnode.ce,
cacheIndex: vnode.cacheIndex
};
if (transition && cloneTransition) setTransitionHooks(cloned, transition.clone(cloned));
return cloned;
}
function createTextVNode(text = " ", flag = 0) {
return createVNode(Text, null, text, flag);
}
function createCommentVNode(text = "", asBlock = false) {
return asBlock ? (openBlock(), createBlock(Comment, null, text)) : createVNode(Comment, null, text);
}
function normalizeVNode(child) {
if (child == null || typeof child === "boolean") return createVNode(Comment);
else if (isArray$1(child)) return createVNode(Fragment, null, child.slice());
else if (isVNode(child)) return cloneIfMounted(child);
else return createVNode(Text, null, String(child));
}
function cloneIfMounted(child) {
return child.el === null && child.patchFlag !== -1 || child.memo ? child : cloneVNode(child);
}
function normalizeChildren(vnode, children) {
let type = 0;
const { shapeFlag } = vnode;
if (children == null) children = null;
else if (isArray$1(children)) type = 16;
else if (typeof children === "object") {
if (shapeFlag & 65) {
const slot = children.default;
if (slot) {
slot._c && (slot._d = false);
normalizeChildren(vnode, slot());
slot._c && (slot._d = true);
}
return;
} else {
type = 32;
const slotFlag = children._;
if (!slotFlag && !isInternalObject(children)) children._ctx = currentRenderingInstance;
else if (slotFlag === 3 && currentRenderingInstance) {
if (currentRenderingInstance.slots._ === 1) children._ = 1;
else {
children._ = 2;
vnode.patchFlag |= 1024;
}
}
}
} else if (isFunction(children)) {
if (shapeFlag & 65) {
normalizeChildren(vnode, { default: children });
return;
}
children = {
default: children,
_ctx: currentRenderingInstance
};
type = 32;
} else {
children = String(children);
if (shapeFlag & 64) {
type = 16;
children = [createTextVNode(children)];
} else type = 8;
}
vnode.children = children;
vnode.shapeFlag |= type;
}
function mergeProps(...args) {
const ret = {};
for (let i = 0; i < args.length; i++) {
const toMerge = args[i];
for (const key in toMerge) if (key === "class") {
if (ret.class !== toMerge.class) ret.class = normalizeClass([ret.class, toMerge.class]);
} else if (key === "style") ret.style = normalizeStyle([ret.style, toMerge.style]);
else if (isOn(key)) {
const existing = ret[key];
const incoming = toMerge[key];
if (incoming && existing !== incoming && !(isArray$1(existing) && existing.includes(incoming))) ret[key] = existing ? [].concat(existing, incoming) : incoming;
else if (incoming == null && existing == null && !isModelListener(key)) ret[key] = incoming;
} else if (key !== "") ret[key] = toMerge[key];
}
return ret;
}
function invokeVNodeHook(hook, instance, vnode, prevVNode = null) {
callWithAsyncErrorHandling(hook, instance, 7, [vnode, prevVNode]);
}
var emptyAppContext = createAppContext();
var uid = 0;
function getNextUid() {
return uid;
}
function createComponentInstance(vnode, parent, suspense) {
const type = vnode.type;
const appContext = (parent ? parent.appContext : vnode.appContext) || emptyAppContext;
const instance = {
uid: uid++,
vnode,
type,
parent,
appContext,
root: null,
next: null,
subTree: null,
effect: null,
update: null,
job: null,
scope: new EffectScope(true),
render: null,
proxy: null,
exposed: null,
exposeProxy: null,
withProxy: null,
provides: parent ? parent.provides : Object.create(appContext.provides),
ids: parent ? parent.ids : [
"",
0,
0
],
accessCache: null,
renderCache: [],
components: null,
directives: null,
propsOptions: normalizePropsOptions(type, appContext),
emitsOptions: normalizeEmitsOptions(type, appContext),
emit: null,
emitted: null,
propsDefaults: EMPTY_OBJ,
inheritAttrs: type.inheritAttrs,
ctx: EMPTY_OBJ,
data: EMPTY_OBJ,
props: EMPTY_OBJ,
attrs: EMPTY_OBJ,
slots: EMPTY_OBJ,
refs: EMPTY_OBJ,
setupState: EMPTY_OBJ,
setupContext: null,
suspense,
suspenseId: suspense ? suspense.pendingId : 0,
asyncDep: null,
asyncResolved: false,
isMounted: false,
isUnmounted: false,
isDeactivated: false,
bc: null,
c: null,
bm: null,
m: null,
bu: null,
u: null,
um: null,
bum: null,
da: null,
a: null,
rtg: null,
rtc: null,
ec: null,
sp: null
};
instance.ctx = { _: instance };
instance.root = parent ? parent.root : instance;
instance.emit = emit.bind(null, instance);
if (vnode.ce) vnode.ce(instance);
return instance;
}
var currentInstance = null;
var getCurrentInstance = () => currentInstance || currentRenderingInstance;
var internalSetCurrentInstance;
var setInSSRSetupState;
{
const g = getGlobalThis();
const registerGlobalSetter = (key, setter) => {
let setters;
if (!(setters = g[key])) setters = g[key] = [];
setters.push(setter);
return (v) => {
if (setters.length > 1) setters.forEach((set) => set(v));
else setters[0](v);
};
};
internalSetCurrentInstance = registerGlobalSetter(`__VUE_INSTANCE_SETTERS__`, (v) => currentInstance = v);
setInSSRSetupState = registerGlobalSetter(`__VUE_SSR_SETTERS__`, (v) => isInSSRComponentSetup = v);
}
var setCurrentInstance = (instance) => {
const prev = currentInstance;
internalSetCurrentInstance(instance);
instance.scope.on();
return () => {
instance.scope.off();
internalSetCurrentInstance(prev);
};
};
var unsetCurrentInstance = () => {
currentInstance && currentInstance.scope.off();
internalSetCurrentInstance(null);
};
function isStatefulComponent(instance) {
return instance.vnode.shapeFlag & 4;
}
var isInSSRComponentSetup = false;
function setupComponent(instance, isSSR = false, optimized = false) {
isSSR && setInSSRSetupState(isSSR);
const { props, children } = instance.vnode;
const isStateful = isStatefulComponent(instance);
initProps(instance, props, isStateful, isSSR);
initSlots(instance, children, optimized || isSSR);
const setupResult = isStateful ? setupStatefulComponent(instance, isSSR) : void 0;
isSSR && setInSSRSetupState(false);
return setupResult;
}
function setupStatefulComponent(instance, isSSR) {
const Component = instance.type;
instance.accessCache = Object.create(null);
instance.proxy = new Proxy(instance.ctx, PublicInstanceProxyHandlers);
const { setup } = Component;
if (setup) {
pauseTracking();
const setupContext = instance.setupContext = setup.length > 1 ? createSetupContext(instance) : null;
const reset = setCurrentInstance(instance);
const setupResult = callWithErrorHandling(setup, instance, 0, [instance.props, setupContext]);
const isAsyncSetup = isPromise(setupResult);
resetTracking();
reset();
if ((isAsyncSetup || instance.sp) && !isAsyncWrapper(instance)) markAsyncBoundary(instance);
if (isAsyncSetup) {
setupResult.then(unsetCurrentInstance, unsetCurrentInstance);
if (isSSR) return setupResult.then((resolvedResult) => {
setInSSRSetupState(true);
try {
handleSetupResult(instance, resolvedResult, isSSR);
} finally {
setInSSRSetupState(false);
}
}).catch((e) => {
handleError(e, instance, 0, void 0, true);
instance.ssrRender = (_, push) => push("<!---->");
});
else instance.asyncDep = setupResult;
} else handleSetupResult(instance, setupResult, isSSR);
} else finishComponentSetup(instance, isSSR);
}
function handleSetupResult(instance, setupResult, isSSR) {
if (isFunction(setupResult)) {
if (instance.type.__ssrInlineRender) instance.ssrRender = setupResult;
else instance.render = setupResult;
} else if (isObject$3(setupResult)) instance.setupState = proxyRefs(setupResult);
finishComponentSetup(instance, isSSR);
}
function finishComponentSetup(instance, isSSR, skipOptions) {
const Component = instance.type;
if (!instance.render) instance.render = Component.render || NOOP;
{
const reset = setCurrentInstance(instance);
pauseTracking();
try {
applyOptions(instance);
} finally {
resetTracking();
reset();
}
}
}
var rawAttrsKey = Symbol();
var attrsProxyHandlers = { get(target, key) {
track(target, "get", "");
return key === rawAttrsKey ? target : target[key];
} };
function createSetupContext(instance) {
const expose = (exposed) => {
instance.exposed = exposed || {};
};
return {
attrs: new Proxy(instance.attrs, attrsProxyHandlers),
slots: instance.slots,
emit: instance.emit,
expose
};
}
function getComponentPublicInstance(instance) {
if (instance.exposed) return instance.exposeProxy || (instance.exposeProxy = new Proxy(proxyRefs(markRaw(instance.exposed)), {
get(target, key) {
if (key in target) return target[key];
else if (key in publicPropertiesMap) return publicPropertiesMap[key](instance);
},
has(target, key) {
return key in target || key in publicPropertiesMap;
}
}));
else return instance.proxy;
}
function getComponentName(Component, includeInferred = true) {
return isFunction(Component) ? Component.displayName || Component.name : Component.name || includeInferred && Component.__name;
}
function isClassComponent(value) {
return isFunction(value) && "__vccOpts" in value;
}
var computed = (getterOrOptions, debugOptions) => {
return computed$1(getterOrOptions, debugOptions, isInSSRComponentSetup);
};
function h(type, propsOrChildren, children) {
try {
setBlockTracking(-1);
const l = arguments.length;
if (l === 2) {
if (isObject$3(propsOrChildren) && !isArray$1(propsOrChildren)) {
if (isVNode(propsOrChildren)) return createVNode(type, null, [propsOrChildren]);
return createVNode(type, propsOrChildren);
} else return createVNode(type, null, propsOrChildren);
} else {
if (l > 3) children = Array.prototype.slice.call(arguments, 2);
else if (l === 3 && isVNode(children)) children = [children];
return createVNode(type, propsOrChildren, children);
}
} finally {
setBlockTracking(1);
}
}
var version = "3.5.45";
var policy = void 0;
var tt = typeof window !== "undefined" && window.trustedTypes;
if (tt) try {
policy = tt.createPolicy("vue", { createHTML: (val) => val });
} catch (e) {}
var unsafeToTrustedHTML = policy ? (val) => policy.createHTML(val) : (val) => val;
var svgNS = "http://www.w3.org/2000/svg";
var mathmlNS = "http://www.w3.org/1998/Math/MathML";
var doc = typeof document !== "undefined" ? document : null;
var templateContainer = doc && doc.createElement("template");
var nodeOps = {
insert: (child, parent, anchor) => {
parent.insertBefore(child, anchor || null);
},
remove: (child) => {
const parent = child.parentNode;
if (parent) parent.removeChild(child);
},
createElement: (tag, namespace, is, props) => {
const el = namespace === "svg" ? doc.createElementNS(svgNS, tag) : namespace === "mathml" ? doc.createElementNS(mathmlNS, tag) : is ? doc.createElement(tag, { is }) : doc.createElement(tag);
if (tag === "select" && props && props.multiple != null) el.setAttribute("multiple", props.multiple);
return el;
},
createText: (text) => doc.createTextNode(text),
createComment: (text) => doc.createComment(text),
setText: (node, text) => {
node.nodeValue = text;
},
setElementText: (el, text) => {
el.textContent = text;
},
parentNode: (node) => node.parentNode,
nextSibling: (node) => node.nextSibling,
querySelector: (selector) => doc.querySelector(selector),
setScopeId(el, id) {
el.setAttribute(id, "");
},
insertStaticContent(content, parent, anchor, namespace, start, end) {
const before = anchor ? anchor.previousSibling : parent.lastChild;
if (start && (start === end || start.nextSibling)) while (true) {
parent.insertBefore(start.cloneNode(true), anchor);
if (start === end || !(start = start.nextSibling)) break;
}
else {
templateContainer.innerHTML = unsafeToTrustedHTML(namespace === "svg" ? `<svg>${content}</svg>` : namespace === "mathml" ? `<math>${content}</math>` : content);
const template = templateContainer.content;
if (namespace === "svg" || namespace === "mathml") {
const wrapper = template.firstChild;
while (wrapper.firstChild) template.appendChild(wrapper.firstChild);
template.removeChild(wrapper);
}
parent.insertBefore(template, anchor);
}
return [before ? before.nextSibling : parent.firstChild, anchor ? anchor.previousSibling : parent.lastChild];
}
};
var TRANSITION = "transition";
var ANIMATION = "animation";
var vtcKey = Symbol("_vtc");
var DOMTransitionPropsValidators = {
name: String,
type: String,
css: {
type: Boolean,
default: true
},
duration: [
String,
Number,
Object
],
enterFromClass: String,
enterActiveClass: String,
enterToClass: String,
appearFromClass: String,
appearActiveClass: String,
appearToClass: String,
leaveFromClass: String,
leaveActiveClass: String,
leaveToClass: String
};
var TransitionPropsValidators = extend({}, BaseTransitionPropsValidators, DOMTransitionPropsValidators);
var decorate$1 = (t) => {
t.displayName = "Transition";
t.props = TransitionPropsValidators;
return t;
};
var Transition = decorate$1((props, { slots }) => h(BaseTransition, resolveTransitionProps(props), slots));
var callHook = (hook, args = []) => {
if (isArray$1(hook)) hook.forEach((h2) => h2(...args));
else if (hook) hook(...args);
};
var hasExplicitCallback = (hook) => {
return hook ? isArray$1(hook) ? hook.some((h2) => h2.length > 1) : hook.length > 1 : false;
};
function resolveTransitionProps(rawProps) {
const baseProps = {};
for (const key in rawProps) if (!(key in DOMTransitionPropsValidators)) baseProps[key] = rawProps[key];
if (rawProps.css === false) return baseProps;
const { name = "v", type, duration, enterFromClass = `${name}-enter-from`, enterActiveClass = `${name}-enter-active`, enterToClass = `${name}-enter-to`, appearFromClass = enterFromClass, appearActiveClass = enterActiveClass, appearToClass = enterToClass, leaveFromClass = `${name}-leave-from`, leaveActiveClass = `${name}-leave-active`, leaveToClass = `${name}-leave-to` } = rawProps;
const durations = normalizeDuration(duration);
const enterDuration = durations && durations[0];
const leaveDuration = durations && durations[1];
const { onBeforeEnter, onEnter, onEnterCancelled, onLeave, onLeaveCancelled, onBeforeAppear = onBeforeEnter, onAppear = onEnter, onAppearCancelled = onEnterCancelled } = baseProps;
const finishEnter = (el, isAppear, done, isCancelled) => {
el._enterCancelled = isCancelled;
removeTransitionClass(el, isAppear ? appearToClass : enterToClass);
removeTransitionClass(el, isAppear ? appearActiveClass : enterActiveClass);
done && done();
};
const finishLeave = (el, done) => {
el._isLeaving = false;
removeTransitionClass(el, leaveFromClass);
removeTransitionClass(el, leaveToClass);
removeTransitionClass(el, leaveActiveClass);
done && done();
};
const makeEnterHook = (isAppear) => {
return (el, done) => {
const hook = isAppear ? onAppear : onEnter;
const resolve = () => finishEnter(el, isAppear, done);
callHook(hook, [el, resolve]);
nextFrame(() => {
removeTransitionClass(el, isAppear ? appearFromClass : enterFromClass);
addTransitionClass(el, isAppear ? appearToClass : enterToClass);
if (!hasExplicitCallback(hook)) whenTransitionEnds(el, type, enterDuration, resolve);
});
};
};
return extend(baseProps, {
onBeforeEnter(el) {
callHook(onBeforeEnter, [el]);
addTransitionClass(el, enterFromClass);
addTransitionClass(el, enterActiveClass);
},
onBeforeAppear(el) {
callHook(onBeforeAppear, [el]);
addTransitionClass(el, appearFromClass);
addTransitionClass(el, appearActiveClass);
},
onEnter: makeEnterHook(false),
onAppear: makeEnterHook(true),
onLeave(el, done) {
el._isLeaving = true;
const resolve = () => finishLeave(el, done);
addTransitionClass(el, leaveFromClass);
if (!el._enterCancelled) {
forceReflow(el);
addTransitionClass(el, leaveActiveClass);
} else {
addTransitionClass(el, leaveActiveClass);
forceReflow(el);
}
nextFrame(() => {
if (!el._isLeaving) return;
removeTransitionClass(el, leaveFromClass);
addTransitionClass(el, leaveToClass);
if (!hasExplicitCallback(onLeave)) whenTransitionEnds(el, type, leaveDuration, resolve);
});
callHook(onLeave, [el, resolve]);
},
onEnterCancelled(el) {
finishEnter(el, false, void 0, true);
callHook(onEnterCancelled, [el]);
},
onAppearCancelled(el) {
finishEnter(el, true, void 0, true);
callHook(onAppearCancelled, [el]);
},
onLeaveCancelled(el) {
finishLeave(el);
callHook(onLeaveCancelled, [el]);
}
});
}
function normalizeDuration(duration) {
if (duration == null) return null;
else if (isObject$3(duration)) return [NumberOf(duration.enter), NumberOf(duration.leave)];
else {
const n = NumberOf(duration);
return [n, n];
}
}
function NumberOf(val) {
return toNumber(val);
}
function addTransitionClass(el, cls) {
cls.split(/\s+/).forEach((c) => c && el.classList.add(c));
(el[vtcKey] || (el[vtcKey] = new Set())).add(cls);
}
function removeTransitionClass(el, cls) {
cls.split(/\s+/).forEach((c) => c && el.classList.remove(c));
const _vtc = el[vtcKey];
if (_vtc) {
_vtc.delete(cls);
if (!_vtc.size) el[vtcKey] = void 0;
}
}
function nextFrame(cb) {
requestAnimationFrame(() => {
requestAnimationFrame(cb);
});
}
var endId = 0;
function whenTransitionEnds(el, expectedType, explicitTimeout, resolve) {
const id = el._endId = ++endId;
const resolveIfNotStale = () => {
if (id === el._endId) resolve();
};
if (explicitTimeout != null) return setTimeout(resolveIfNotStale, explicitTimeout);
const { type, timeout, propCount } = getTransitionInfo(el, expectedType);
if (!type) return resolve();
const endEvent = type + "end";
let ended = 0;
const end = () => {
el.removeEventListener(endEvent, onEnd);
resolveIfNotStale();
};
const onEnd = (e) => {
if (e.target === el && ++ended >= propCount) end();
};
setTimeout(() => {
if (ended < propCount) end();
}, timeout + 1);
el.addEventListener(endEvent, onEnd);
}
function getTransitionInfo(el, expectedType) {
const styles = window.getComputedStyle(el);
const getStyleProperties = (key) => (styles[key] || "").split(", ");
const transitionDelays = getStyleProperties(`${TRANSITION}Delay`);
const transitionDurations = getStyleProperties(`${TRANSITION}Duration`);
const transitionTimeout = getTimeout(transitionDelays, transitionDurations);
const animationDelays = getStyleProperties(`${ANIMATION}Delay`);
const animationDurations = getStyleProperties(`${ANIMATION}Duration`);
const animationTimeout = getTimeout(animationDelays, animationDurations);
let type = null;
let timeout = 0;
let propCount = 0;
if (expectedType === TRANSITION) {
if (transitionTimeout > 0) {
type = TRANSITION;
timeout = transitionTimeout;
propCount = transitionDurations.length;
}
} else if (expectedType === ANIMATION) {
if (animationTimeout > 0) {
type = ANIMATION;
timeout = animationTimeout;
propCount = animationDurations.length;
}
} else {
timeout = Math.max(transitionTimeout, animationTimeout);
type = timeout > 0 ? transitionTimeout > animationTimeout ? TRANSITION : ANIMATION : null;
propCount = type ? type === TRANSITION ? transitionDurations.length : animationDurations.length : 0;
}
const hasTransform = type === TRANSITION && /\b(?:transform|all)(?:,|$)/.test(getStyleProperties(`${TRANSITION}Property`).toString());
return {
type,
timeout,
propCount,
hasTransform
};
}
function getTimeout(delays, durations) {
while (delays.length < durations.length) delays = delays.concat(delays);
return Math.max(...durations.map((d, i) => toMs(d) + toMs(delays[i])));
}
function toMs(s) {
if (s === "auto") return 0;
return Number(s.slice(0, -1).replace(",", ".")) * 1e3;
}
function forceReflow(el) {
return (el ? el.ownerDocument : document).body.offsetHeight;
}
function patchClass(el, value, isSVG) {
const transitionClasses = el[vtcKey];
if (transitionClasses) value = (value ? [value, ...transitionClasses] : [...transitionClasses]).join(" ");
if (value == null) el.removeAttribute("class");
else if (isSVG) el.setAttribute("class", value);
else el.className = value;
}
var vShowOriginalDisplay = Symbol("_vod");
var vShowHidden = Symbol("_vsh");
var vShow = {
name: "show",
beforeMount(el, { value }, { transition }) {
el[vShowOriginalDisplay] = el.style.display === "none" ? "" : el.style.display;
if (transition && value) transition.beforeEnter(el);
else setDisplay(el, value);
},
mounted(el, { value }, { transition }) {
if (transition && value) transition.enter(el);
},
updated(el, { value, oldValue }, { transition }) {
if (!value === !oldValue) return;
if (transition) {
if (value) {
transition.beforeEnter(el);
setDisplay(el, true);
transition.enter(el);
} else transition.leave(el, () => {
setDisplay(el, false);
});
} else setDisplay(el, value);
},
beforeUnmount(el, { value }) {
setDisplay(el, value);
}
};
function setDisplay(el, value) {
el.style.display = value ? el[vShowOriginalDisplay] : "none";
el[vShowHidden] = !value;
}
var CSS_VAR_TEXT = Symbol("");
var displayRE = /(?:^|;)\s*display\s*:/;
function patchStyle(el, prev, next) {
const style = el.style;
const isCssString = isString$1(next);
let hasControlledDisplay = false;
if (next && !isCssString) {
if (prev) {
if (!isString$1(prev)) {
for (const key in prev) if (next[key] == null) setStyle(style, key, "");
} else for (const prevStyle of prev.split(";")) {
const key = prevStyle.slice(0, prevStyle.indexOf(":")).trim();
if (next[key] == null) setStyle(style, key, "");
}
}
for (const key in next) {
if (key === "display") hasControlledDisplay = true;
const value = next[key];
if (value != null) {
if (!shouldPreserveTextareaResizeStyle(el, key, !isString$1(prev) && prev ? prev[key] : void 0, value)) setStyle(style, key, value);
} else setStyle(style, key, "");
}
} else if (isCssString) {
if (prev !== next) {
const cssVarText = style[CSS_VAR_TEXT];
if (cssVarText) next += ";" + cssVarText;
style.cssText = next;
hasControlledDisplay = displayRE.test(next);
}
} else if (prev) el.removeAttribute("style");
if (vShowOriginalDisplay in el) {
if (!isCssString || prev !== next) el[vShowOriginalDisplay] = hasControlledDisplay ? style.display : "";
if (el[vShowHidden]) style.display = "none";
}
}
var importantRE = /\s*!important$/;
function setStyle(style, name, val) {
if (isArray$1(val)) val.forEach((v) => setStyle(style, name, v));
else {
if (val == null) val = "";
if (name.startsWith("--")) {
if (importantRE.test(val)) style.setProperty(name, val.replace(importantRE, ""), "important");
else style.setProperty(name, val);
} else {
const prefixed = autoPrefix(style, name);
if (importantRE.test(val)) style.setProperty(hyphenate$2(prefixed), val.replace(importantRE, ""), "important");
else style[prefixed] = val;
}
}
}
var prefixes = [
"Webkit",
"Moz",
"ms"
];
var prefixCache = {};
function autoPrefix(style, rawName) {
const cached = prefixCache[rawName];
if (cached) return cached;
let name = camelize$2(rawName);
if (name !== "filter" && name in style) return prefixCache[rawName] = name;
name = capitalize(name);
for (let i = 0; i < prefixes.length; i++) {
const prefixed = prefixes[i] + name;
if (prefixed in style) return prefixCache[rawName] = prefixed;
}
return rawName;
}
function shouldPreserveTextareaResizeStyle(el, key, prev, next) {
return el.tagName === "TEXTAREA" && (key === "width" || key === "height") && isString$1(next) && prev === next;
}
var xlinkNS = "http://www.w3.org/1999/xlink";
function patchAttr(el, key, value, isSVG, instance, isBoolean = isSpecialBooleanAttr(key)) {
if (isSVG && key.startsWith("xlink:")) {
if (value == null) el.removeAttributeNS(xlinkNS, key.slice(6, key.length));
else el.setAttributeNS(xlinkNS, key, value);
} else if (value == null || isBoolean && !includeBooleanAttr(value)) el.removeAttribute(key);
else el.setAttribute(key, isBoolean ? "" : isSymbol(value) ? String(value) : value);
}
function patchDOMProp(el, key, value, parentComponent, attrName) {
if (key === "innerHTML" || key === "textContent") {
if (value != null) el[key] = key === "innerHTML" ? unsafeToTrustedHTML(value) : value;
return;
}
const tag = el.tagName;
if (key === "value" && tag !== "PROGRESS" && !tag.includes("-")) {
const oldValue = tag === "OPTION" ? el.getAttribute("value") || "" : el.value;
const newValue = value == null ? el.type === "checkbox" ? "on" : "" : String(value);
if (oldValue !== newValue || !("_value" in el)) el.value = newValue;
if (value == null) el.removeAttribute(key);
el._value = value;
return;
}
let needRemove = false;
if (value === "" || value == null) {
const type = typeof el[key];
if (type === "boolean") value = includeBooleanAttr(value);
else if (value == null && type === "string") {
value = "";
needRemove = true;
} else if (type === "number") {
value = 0;
needRemove = true;
}
}
try {
el[key] = value;
} catch (e) {}
needRemove && el.removeAttribute(attrName || key);
}
function addEventListener(el, event, handler, options) {
el.addEventListener(event, handler, options);
}
function removeEventListener(el, event, handler, options) {
el.removeEventListener(event, handler, options);
}
var veiKey = Symbol("_vei");
function patchEvent(el, rawName, prevValue, nextValue, instance = null) {
const invokers = el[veiKey] || (el[veiKey] = {});
const existingInvoker = invokers[rawName];
if (nextValue && existingInvoker) existingInvoker.value = nextValue;
else {
const [name, options] = parseName(rawName);
if (nextValue) addEventListener(el, name, invokers[rawName] = createInvoker(nextValue, instance), options);
else if (existingInvoker) {
removeEventListener(el, name, existingInvoker, options);
invokers[rawName] = void 0;
}
}
}
var optionsModifierRE = /(Once|Passive|Capture)$/;
var optionsModifierEventRE = /^on:?(?:Once|Passive|Capture)$/;
function parseName(name) {
let options;
let m;
while ((m = name.match(optionsModifierRE)) && !optionsModifierEventRE.test(name)) {
if (!options) options = {};
name = name.slice(0, name.length - m[1].length);
options[m[1].toLowerCase()] = true;
}
return [name[2] === ":" ? name.slice(3) : hyphenate$2(name.slice(2)), options];
}
var cachedNow = 0;
var p = Promise.resolve();
var getNow = () => cachedNow || (p.then(() => cachedNow = 0), cachedNow = Date.now());
function createInvoker(initialValue, instance) {
const invoker = (e) => {
if (!e._vts) e._vts = Date.now();
else if (e._vts <= invoker.attached) return;
const value = invoker.value;
if (isArray$1(value)) {
const originalStop = e.stopImmediatePropagation;
e.stopImmediatePropagation = () => {
originalStop.call(e);
e._stopped = true;
};
const handlers = value.slice();
const args = [e];
for (let i = 0; i < handlers.length; i++) {
if (e._stopped) break;
const handler = handlers[i];
if (handler) callWithAsyncErrorHandling(handler, instance, 5, args);
}
} else callWithAsyncErrorHandling(value, instance, 5, [e]);
};
invoker.value = initialValue;
invoker.attached = getNow();
return invoker;
}
var isNativeOn = (key) => key.charCodeAt(0) === 111 && key.charCodeAt(1) === 110 && key.charCodeAt(2) > 96 && key.charCodeAt(2) < 123;
var patchProp = (el, key, prevValue, nextValue, namespace, parentComponent) => {
const isSVG = namespace === "svg";
if (key === "class") patchClass(el, nextValue, isSVG);
else if (key === "style") patchStyle(el, prevValue, nextValue);
else if (isOn(key)) {
if (!isModelListener(key)) patchEvent(el, key, prevValue, nextValue, parentComponent);
} else if (key[0] === "." ? (key = key.slice(1), true) : key[0] === "^" ? (key = key.slice(1), false) : shouldSetAsProp(el, key, nextValue, isSVG)) {
patchDOMProp(el, key, nextValue);
if (!el.tagName.includes("-") && (key === "value" || key === "checked" || key === "selected")) patchAttr(el, key, nextValue, isSVG, parentComponent, key !== "value");
} else if (el._isVueCE && (shouldSetAsPropForVueCE(el, key) || el._def.__asyncLoader && (/[A-Z]/.test(key) || !isString$1(nextValue)))) patchDOMProp(el, camelize$2(key), nextValue, parentComponent, key);
else {
if (key === "true-value") el._trueValue = nextValue;
else if (key === "false-value") el._falseValue = nextValue;
patchAttr(el, key, nextValue, isSVG);
}
};
function shouldSetAsProp(el, key, value, isSVG) {
if (isSVG) {
if (key === "innerHTML" || key === "textContent") return true;
if (key in el && isNativeOn(key) && isFunction(value)) return true;
return false;
}
if (key === "spellcheck" || key === "draggable" || key === "translate" || key === "autocorrect") return false;
if (key === "sandbox" && el.tagName === "IFRAME") return false;
if (key === "form") return false;
if (key === "list" && el.tagName === "INPUT") return false;
if (key === "type" && el.tagName === "TEXTAREA") return false;
if (key === "width" || key === "height") {
const tag = el.tagName;
if (tag === "IMG" || tag === "VIDEO" || tag === "CANVAS" || tag === "SOURCE") return false;
}
if (isNativeOn(key) && isString$1(value)) return false;
return key in el;
}
function shouldSetAsPropForVueCE(el, key) {
const props = el._def.props;
if (!props) return false;
const camelKey = camelize$2(key);
return Array.isArray(props) ? props.some((prop) => camelize$2(prop) === camelKey) : Object.keys(props).some((prop) => camelize$2(prop) === camelKey);
}
var getModelAssigner = (vnode) => {
const fn = vnode.props["onUpdate:modelValue"] || false;
return isArray$1(fn) ? (value) => invokeArrayFns(fn, value) : fn;
};
function onCompositionStart(e) {
e.target.composing = true;
}
function onCompositionEnd(e) {
const target = e.target;
if (target.composing) {
target.composing = false;
target.dispatchEvent(new Event("input"));
}
}
var assignKey = Symbol("_assign");
var initialValueKey = Symbol("_initialValue");
function castValue(value, trim, number) {
if (trim) value = value.trim();
if (number) value = looseToNumber(value);
return value;
}
var vModelText = {
created(el, { modifiers: { lazy, trim, number } }, vnode) {
if (el.parentNode) {
if (el.type === "text") el[initialValueKey] = el.defaultValue.replace(/[\r\n]/g, "");
else if (el.type === "textarea") el[initialValueKey] = el.defaultValue.replace(/\r\n?/g, "\n");
}
el[assignKey] = getModelAssigner(vnode);
const castToNumber = number || vnode.props && vnode.props.type === "number";
addEventListener(el, lazy ? "change" : "input", (e) => {
if (e.target.composing) return;
el[assignKey](castValue(el.value, trim, castToNumber));
});
if (trim || castToNumber) addEventListener(el, "change", () => {
el.value = castValue(el.value, trim, castToNumber);
});
if (!lazy) {
addEventListener(el, "compositionstart", onCompositionStart);
addEventListener(el, "compositionend", onCompositionEnd);
addEventListener(el, "change", onCompositionEnd);
}
},
mounted(el, { value, modifiers: { trim, number } }) {
const newValue = value == null ? "" : value;
const initialValue = el[initialValueKey];
delete el[initialValueKey];
if (initialValue !== void 0 && (el.type === "text" || el.type === "textarea") && el.value !== initialValue) el[assignKey](castValue(el.value, trim, number));
else el.value = newValue;
},
beforeUpdate(el, { value, oldValue, modifiers: { lazy, trim, number } }, vnode) {
el[assignKey] = getModelAssigner(vnode);
if (el.composing) return;
const elValue = (number || el.type === "number") && !/^0\d/.test(el.value) ? looseToNumber(el.value) : el.value;
const newValue = value == null ? "" : value;
if (elValue === newValue) return;
const rootNode = el.getRootNode();
if ((rootNode instanceof Document || rootNode instanceof ShadowRoot) && rootNode.activeElement === el && el.type !== "range") {
if (lazy && value === oldValue) return;
if (trim && el.value.trim() === newValue) return;
}
el.value = newValue;
}
};
var vModelCheckbox = {
deep: true,
created(el, _, vnode) {
el[assignKey] = getModelAssigner(vnode);
addEventListener(el, "change", () => {
const modelValue = el._modelValue;
const elementValue = getValue(el);
const checked = el.checked;
const assign = el[assignKey];
if (isArray$1(modelValue)) {
const index = looseIndexOf(modelValue, elementValue);
const found = index !== -1;
if (checked && !found) assign(modelValue.concat(elementValue));
else if (!checked && found) {
const filtered = [...modelValue];
filtered.splice(index, 1);
assign(filtered);
}
} else if (isSet(modelValue)) {
const cloned = new Set(modelValue);
if (checked) cloned.add(elementValue);
else cloned.delete(elementValue);
assign(cloned);
} else assign(getCheckboxValue(el, checked));
});
},
mounted: setChecked,
beforeUpdate(el, binding, vnode) {
el[assignKey] = getModelAssigner(vnode);
setChecked(el, binding, vnode);
}
};
function setChecked(el, { value, oldValue }, vnode) {
el._modelValue = value;
let checked;
if (isArray$1(value)) checked = looseIndexOf(value, vnode.props.value) > -1;
else if (isSet(value)) checked = value.has(vnode.props.value);
else {
if (value === oldValue) return;
checked = looseEqual(value, getCheckboxValue(el, true));
}
if (el.checked !== checked) el.checked = checked;
}
var vModelSelect = {
deep: true,
created(el, { value, modifiers: { number } }, vnode) {
el._modelValue = value;
addEventListener(el, "change", () => {
const selectedVal = Array.prototype.filter.call(el.options, (o) => o.selected).map((o) => number ? looseToNumber(getValue(o)) : getValue(o));
const multiple = el.multiple;
const assignedValue = multiple ? isSet(el._modelValue) ? new Set(selectedVal) : selectedVal : selectedVal[0];
const pending = el._pendingValue = [multiple, multiple ? isArray$1(assignedValue) ? selectedVal.slice() : selectedVal : assignedValue];
try {
el[assignKey](assignedValue);
} finally {
nextTick(() => {
if (el._pendingValue === pending) el._pendingValue = void 0;
});
}
});
el[assignKey] = getModelAssigner(vnode);
},
mounted(el, { value, modifiers: { number } }) {
setSelected(el, value, number);
},
beforeUpdate(el, { value }, vnode) {
el._modelValue = value;
el[assignKey] = getModelAssigner(vnode);
},
updated(el, { value, modifiers: { number } }) {
const pending = el._pendingValue;
el._pendingValue = void 0;
if (!pending || pending[0] !== el.multiple || !isSameSelectValue(value, pending[1], pending[0])) setSelected(el, value, number);
}
};
function isSameSelectValue(value, assignedValue, multiple) {
if (!multiple) return looseEqual(value, assignedValue);
if (isArray$1(value)) return looseEqual(value, assignedValue);
if (isSet(value)) {
if (value.size !== assignedValue.length) return false;
for (const item of assignedValue) if (!value.has(item)) return false;
return true;
}
return false;
}
function setSelected(el, value, number = false) {
const isMultiple = el.multiple;
const isArrayValue = isArray$1(value);
if (isMultiple && !isArrayValue && !isSet(value)) return;
for (let i = 0, l = el.options.length; i < l; i++) {
const option = el.options[i];
const optionValue = getValue(option);
if (isMultiple) {
if (isArrayValue) {
const optionType = typeof optionValue;
if (optionType === "string" || optionType === "number") option.selected = value.some((v) => String(v) === String(optionValue));
else option.selected = looseIndexOf(value, optionValue) > -1;
} else option.selected = value.has(optionValue) || number && typeof optionValue === "string" && value.has(looseToNumber(optionValue));
} else if (looseEqual(getValue(option), value)) {
if (el.selectedIndex !== i) el.selectedIndex = i;
return;
}
}
if (!isMultiple && el.selectedIndex !== -1) el.selectedIndex = -1;
}
function getValue(el) {
return "_value" in el ? el._value : el.value;
}
function getCheckboxValue(el, checked) {
const key = checked ? "_trueValue" : "_falseValue";
return key in el ? el[key] : checked;
}
var systemModifiers = [
"ctrl",
"shift",
"alt",
"meta"
];
var modifierGuards = {
stop: (e) => e.stopPropagation(),
prevent: (e) => e.preventDefault(),
self: (e) => e.target !== e.currentTarget,
ctrl: (e) => !e.ctrlKey,
shift: (e) => !e.shiftKey,
alt: (e) => !e.altKey,
meta: (e) => !e.metaKey,
left: (e) => "button" in e && e.button !== 0,
middle: (e) => "button" in e && e.button !== 1,
right: (e) => "button" in e && e.button !== 2,
exact: (e, modifiers) => systemModifiers.some((m) => e[`${m}Key`] && !modifiers.includes(m))
};
var withModifiers = (fn, modifiers) => {
if (!fn) return fn;
const cache = fn._withMods || (fn._withMods = {});
const cacheKey = modifiers.join(".");
return cache[cacheKey] || (cache[cacheKey] = ((event, ...args) => {
for (let i = 0; i < modifiers.length; i++) {
const guard = modifierGuards[modifiers[i]];
if (guard && guard(event, modifiers)) return;
}
return fn(event, ...args);
}));
};
var keyNames = {
esc: "escape",
space: " ",
up: "arrow-up",
left: "arrow-left",
right: "arrow-right",
down: "arrow-down",
delete: "backspace"
};
var withKeys = (fn, modifiers) => {
const cache = fn._withKeys || (fn._withKeys = {});
const cacheKey = modifiers.join(".");
return cache[cacheKey] || (cache[cacheKey] = ((event) => {
if (!("key" in event)) return;
const eventKey = hyphenate$2(event.key);
if (modifiers.some((k) => k === eventKey || keyNames[k] === eventKey)) return fn(event);
}));
};
var rendererOptions = extend({ patchProp }, nodeOps);
var renderer;
function ensureRenderer() {
return renderer || (renderer = createRenderer(rendererOptions));
}
var createApp = ((...args) => {
const app = ensureRenderer().createApp(...args);
const { mount } = app;
app.mount = (containerOrSelector) => {
const container = normalizeContainer(containerOrSelector);
if (!container) return;
const component = app._component;
if (!isFunction(component) && !component.render && !component.template) component.template = container.innerHTML;
if (container.nodeType === 1) container.textContent = "";
const proxy = mount(container, false, resolveRootNamespace(container));
if (container instanceof Element) {
container.removeAttribute("v-cloak");
container.setAttribute("data-v-app", "");
}
return proxy;
};
return app;
});
function resolveRootNamespace(container) {
if (container instanceof SVGElement) return "svg";
if (typeof MathMLElement === "function" && container instanceof MathMLElement) return "mathml";
}
function normalizeContainer(container) {
if (isString$1(container)) return document.querySelector(container);
return container;
}
var IS_CLIENT = typeof window !== "undefined";
var activePinia;
var setActivePinia = (pinia) => activePinia = pinia;
var piniaSymbol = Symbol();
function isPlainObject$1(o) {
return o && typeof o === "object" && Object.prototype.toString.call(o) === "[object Object]" && typeof o.toJSON !== "function";
}
var _global$1 = (() => typeof window === "object" && window.window === window ? window : typeof self === "object" && self.self === self ? self : typeof global === "object" && global.global === global ? global : typeof globalThis === "object" ? globalThis : { HTMLElement: null })();
function bom(blob, { autoBom = false } = {}) {
if (autoBom && /^\s*(?:text\/\S*|application\/xml|\S*\/\S*\+xml)\s*;.*charset\s*=\s*utf-8/i.test(blob.type)) return new Blob([String.fromCharCode(65279), blob], { type: blob.type });
return blob;
}
function download(url, name, opts) {
const xhr = new XMLHttpRequest();
xhr.open("GET", url);
xhr.responseType = "blob";
xhr.onload = function() {
saveAs(xhr.response, name, opts);
};
xhr.onerror = function() {
console.error("could not download file");
};
xhr.send();
}
function corsEnabled(url) {
const xhr = new XMLHttpRequest();
xhr.open("HEAD", url, false);
try {
xhr.send();
} catch (e) {}
return xhr.status >= 200 && xhr.status <= 299;
}
function click(node) {
try {
node.dispatchEvent(new MouseEvent("click"));
} catch (e) {
const evt = new MouseEvent("click", {
bubbles: true,
cancelable: true,
view: window,
detail: 0,
screenX: 80,
screenY: 20,
clientX: 80,
clientY: 20,
ctrlKey: false,
altKey: false,
shiftKey: false,
metaKey: false,
button: 0,
relatedTarget: null
});
node.dispatchEvent(evt);
}
}
var _navigator = typeof navigator === "object" ? navigator : { userAgent: "" };
var isMacOSWebView = (() => /Macintosh/.test(_navigator.userAgent) && /AppleWebKit/.test(_navigator.userAgent) && !/Safari/.test(_navigator.userAgent))();
var saveAs = !IS_CLIENT ? () => {} : typeof HTMLAnchorElement !== "undefined" && "download" in HTMLAnchorElement.prototype && !isMacOSWebView ? downloadSaveAs : "msSaveOrOpenBlob" in _navigator ? msSaveAs : fileSaverSaveAs;
function downloadSaveAs(blob, name = "download", opts) {
const a = document.createElement("a");
a.download = name;
a.rel = "noopener";
if (typeof blob === "string") {
a.href = blob;
if (a.origin !== location.origin) {
if (corsEnabled(a.href)) download(blob, name, opts);
else {
a.target = "_blank";
click(a);
}
} else click(a);
} else {
a.href = URL.createObjectURL(blob);
setTimeout(function() {
URL.revokeObjectURL(a.href);
}, 4e4);
setTimeout(function() {
click(a);
}, 0);
}
}
function msSaveAs(blob, name = "download", opts) {
if (typeof blob === "string") {
if (corsEnabled(blob)) download(blob, name, opts);
else {
const a = document.createElement("a");
a.href = blob;
a.target = "_blank";
setTimeout(function() {
click(a);
});
}
} else navigator.msSaveOrOpenBlob(bom(blob, opts), name);
}
function fileSaverSaveAs(blob, name, opts, popup) {
popup = popup || open("", "_blank");
if (popup) popup.document.title = popup.document.body.innerText = "downloading...";
if (typeof blob === "string") return download(blob, name, opts);
const force = blob.type === "application/octet-stream";
const isSafari = /constructor/i.test(String(_global$1.HTMLElement)) || "safari" in _global$1;
const isChromeIOS = /CriOS\/[\d]+/.test(navigator.userAgent);
if ((isChromeIOS || force && isSafari || isMacOSWebView) && typeof FileReader !== "undefined") {
const reader = new FileReader();
reader.onloadend = function() {
let url = reader.result;
if (typeof url !== "string") {
popup = null;
throw new Error("Wrong reader.result type");
}
url = isChromeIOS ? url : url.replace(/^data:[^;]*;/, "data:attachment/file;");
if (popup) popup.location.href = url;
else location.assign(url);
popup = null;
};
reader.readAsDataURL(blob);
} else {
const url = URL.createObjectURL(blob);
if (popup) popup.location.assign(url);
else location.href = url;
popup = null;
setTimeout(function() {
URL.revokeObjectURL(url);
}, 4e4);
}
}
var { assign: assign$1 } = Object;
function createPinia() {
const scope = effectScope(true);
const state = scope.run(() => ref({}));
let _p = [];
let toBeInstalled = [];
const pinia = markRaw({
install(app) {
setActivePinia(pinia);
pinia._a = app;
app.provide(piniaSymbol, pinia);
app.config.globalProperties.$pinia = pinia;
toBeInstalled.forEach((plugin) => _p.push(plugin));
toBeInstalled = [];
},
use(plugin) {
if (!this._a) toBeInstalled.push(plugin);
else _p.push(plugin);
return this;
},
_p,
_a: null,
_e: scope,
_s: new Map(),
state
});
return pinia;
}
function disposePinia(pinia) {
pinia._e.stop();
pinia._s.clear();
pinia._p.splice(0);
pinia.state.value = {};
pinia._a = null;
}
var noop$2 = () => {};
function addSubscription(subscriptions, callback, detached, onCleanup = noop$2) {
subscriptions.add(callback);
const removeSubscription = () => {
subscriptions.delete(callback) && onCleanup();
};
if (!detached && getCurrentScope()) onScopeDispose(removeSubscription);
return removeSubscription;
}
function triggerSubscriptions(subscriptions, ...args) {
subscriptions.forEach((callback) => {
callback(...args);
});
}
var fallbackRunWithContext = (fn) => fn();
var ACTION_MARKER = Symbol();
var ACTION_NAME = Symbol();
function mergeReactiveObjects(target, patchToApply) {
if (target instanceof Map && patchToApply instanceof Map) patchToApply.forEach((value, key) => target.set(key, value));
else if (target instanceof Set && patchToApply instanceof Set) patchToApply.forEach(target.add, target);
for (const key in patchToApply) {
if (!Object.hasOwn(patchToApply, key)) continue;
const subPatch = patchToApply[key];
const targetValue = target[key];
if (isPlainObject$1(targetValue) && isPlainObject$1(subPatch) && Object.hasOwn(target, key) && !isRef(subPatch) && !isReactive(subPatch)) {
target[key] = mergeReactiveObjects(targetValue, subPatch);
const targetRef = toRaw(target)[key];
if (isRef(targetRef) && isShallow(targetRef)) triggerRef(targetRef);
} else target[key] = subPatch;
}
return target;
}
var skipHydrateSymbol = Symbol();
function shouldHydrate(obj) {
return !obj || typeof obj !== "object" || !Object.hasOwn(obj, skipHydrateSymbol);
}
var { assign } = Object;
function isComputed(o) {
return !!(isRef(o) && o.effect);
}
function createOptionsStore(id, options, pinia, hot) {
const { state, actions, getters } = options;
const initialState = pinia.state.value[id];
let store;
function setup() {
if (!initialState && true) pinia.state.value[id] = state ? state() : {};
return assign(toRefs(pinia.state.value[id]), actions, Object.keys(getters || {}).reduce((computedGetters, name) => {
computedGetters[name] = markRaw(computed(() => {
setActivePinia(pinia);
const store = pinia._s.get(id);
return getters[name].call(store, store);
}));
return computedGetters;
}, {}));
}
store = createSetupStore(id, setup, options, pinia, hot, true);
return store;
}
function createSetupStore($id, setup, options = {}, pinia, hot, isOptionsStore) {
let scope;
const optionsForPlugin = assign({ actions: {} }, options);
const $subscribeOptions = { deep: true };
let isListening;
let isSyncListening;
let subscriptions = new Set();
let actionSubscriptions = new Set();
let debuggerEvents;
const initialState = pinia.state.value[$id];
if (!isOptionsStore && !initialState && true) pinia.state.value[$id] = {};
let activeListener;
function $patch(partialStateOrMutator) {
let subscriptionMutation;
isListening = isSyncListening = false;
if (typeof partialStateOrMutator === "function") {
partialStateOrMutator(pinia.state.value[$id]);
subscriptionMutation = {
type: "patch function",
storeId: $id,
events: debuggerEvents
};
} else {
mergeReactiveObjects(pinia.state.value[$id], partialStateOrMutator);
subscriptionMutation = {
type: "patch object",
payload: partialStateOrMutator,
storeId: $id,
events: debuggerEvents
};
}
const myListenerId = activeListener = Symbol();
nextTick().then(() => {
if (activeListener === myListenerId) isListening = true;
});
isSyncListening = true;
triggerSubscriptions(subscriptions, subscriptionMutation, pinia.state.value[$id]);
}
const $reset = isOptionsStore ? function $reset() {
const { state } = options;
const newState = state ? state() : {};
this.$patch(($state) => {
assign($state, newState);
});
} : noop$2;
function $dispose() {
scope.stop();
subscriptions.clear();
actionSubscriptions.clear();
pinia._s.delete($id);
}
const action = (fn, name = "") => {
if (ACTION_MARKER in fn) {
fn[ACTION_NAME] = name;
return fn;
}
const wrappedAction = function() {
setActivePinia(pinia);
const args = Array.from(arguments);
const afterCallbackSet = new Set();
const onErrorCallbackSet = new Set();
function after(callback) {
afterCallbackSet.add(callback);
}
function onError(callback) {
onErrorCallbackSet.add(callback);
}
triggerSubscriptions(actionSubscriptions, {
args,
name: wrappedAction[ACTION_NAME],
store,
after,
onError
});
let ret;
try {
ret = fn.apply(this && this.$id === $id ? this : store, args);
} catch (error) {
triggerSubscriptions(onErrorCallbackSet, error);
throw error;
}
if (ret instanceof Promise) return ret.then((value) => {
triggerSubscriptions(afterCallbackSet, value);
return value;
}).catch((error) => {
triggerSubscriptions(onErrorCallbackSet, error);
return Promise.reject(error);
});
triggerSubscriptions(afterCallbackSet, ret);
return ret;
};
wrappedAction[ACTION_MARKER] = true;
wrappedAction[ACTION_NAME] = name;
return wrappedAction;
};
const store = reactive({
_p: pinia,
$id,
$onAction: addSubscription.bind(null, actionSubscriptions),
$patch,
$reset,
$subscribe(callback, options = {}) {
if (subscriptions.has(callback)) return noop$2;
const removeSubscription = addSubscription(subscriptions, callback, options.detached, () => stopWatcher());
const stopWatcher = scope.run(() => watch(() => pinia.state.value[$id], (state) => {
if (options.flush === "sync" ? isSyncListening : isListening) callback({
storeId: $id,
type: "direct",
events: debuggerEvents
}, state);
}, assign({}, $subscribeOptions, options)));
return removeSubscription;
},
$dispose
});
pinia._s.set($id, store);
const setupStore = (pinia._a && pinia._a.runWithContext || fallbackRunWithContext)(() => pinia._e.run(() => (scope = effectScope()).run(() => setup({ action }))));
for (const key in setupStore) {
const prop = setupStore[key];
if (isRef(prop) && !isComputed(prop) || isReactive(prop)) {
if (!isOptionsStore) {
if (initialState && shouldHydrate(prop)) {
if (isRef(prop)) prop.value = initialState[key];
else {
if (prop instanceof Set || prop instanceof Map) prop.clear();
mergeReactiveObjects(prop, initialState[key]);
}
}
pinia.state.value[$id][key] = prop;
}
} else if (typeof prop === "function") {
setupStore[key] = action(prop, key);
optionsForPlugin.actions[key] = prop;
}
}
assign(store, setupStore);
assign(toRaw(store), setupStore);
Object.defineProperty(store, "$state", {
get: () => pinia.state.value[$id],
set: (state) => {
$patch(($state) => {
assign($state, state);
});
}
});
pinia._p.forEach((extender) => {
const extensions = scope.run(() => extender({
store,
app: pinia._a,
pinia,
options: optionsForPlugin
}));
assign(store, extensions);
});
if (initialState && isOptionsStore && options.hydrate) options.hydrate(store.$state, initialState);
isListening = true;
isSyncListening = true;
return store;
}
function defineStore(id, setup, setupOptions) {
let options;
const isSetupStore = typeof setup === "function";
options = isSetupStore ? setupOptions : setup;
function useStore(pinia, hot) {
const hasContext = hasInjectionContext();
pinia = pinia || (hasContext ? inject(piniaSymbol, null) : null);
if (pinia) setActivePinia(pinia);
pinia = activePinia;
if (!pinia._s.has(id)) {
if (isSetupStore) createSetupStore(id, setup, options, pinia);
else createOptionsStore(id, options, pinia);
}
return pinia._s.get(id);
}
useStore.$id = id;
return useStore;
}
function storeToRefs(store) {
const rawStore = toRaw(store);
const refs = {};
for (const key in rawStore) {
const value = rawStore[key];
if (value?.effect) refs[key] = computed({
get: () => store[key],
set(value) {
store[key] = value;
}
});
else if (isRef(value) || isReactive(value)) refs[key] = toRef$1(store, key);
}
return refs;
}
function tryOnScopeDispose$1(fn, failSilently) {
if (getCurrentScope()) {
onScopeDispose(fn, failSilently);
return true;
}
return false;
}
var localProvidedStateMap = new WeakMap();
var injectLocal = (...args) => {
var _getCurrentInstance;
const key = args[0];
const instance = (_getCurrentInstance = getCurrentInstance()) === null || _getCurrentInstance === void 0 ? void 0 : _getCurrentInstance.proxy;
const owner = instance !== null && instance !== void 0 ? instance : getCurrentScope();
if (owner == null && !hasInjectionContext()) throw new Error("injectLocal must be called in setup");
if (owner && localProvidedStateMap.has(owner) && key in localProvidedStateMap.get(owner)) return localProvidedStateMap.get(owner)[key];
return inject(...args);
};
var isClient$1 = typeof window !== "undefined" && typeof document !== "undefined";
typeof WorkerGlobalScope !== "undefined" && globalThis instanceof WorkerGlobalScope;
var notNullish$1 = (val) => val != null;
var toString$1 = Object.prototype.toString;
var isObject$2 = (val) => toString$1.call(val) === "[object Object]";
var noop$1 = () => {};
var isIOS = getIsIOS();
function getIsIOS() {
var _window, _window2, _window3;
return isClient$1 && !!((_window = window) === null || _window === void 0 || (_window = _window.navigator) === null || _window === void 0 ? void 0 : _window.userAgent) && (/iP(?:ad|hone|od)/.test(window.navigator.userAgent) || ((_window2 = window) === null || _window2 === void 0 || (_window2 = _window2.navigator) === null || _window2 === void 0 ? void 0 : _window2.maxTouchPoints) > 2 && /iPad|Macintosh/.test((_window3 = window) === null || _window3 === void 0 ? void 0 : _window3.navigator.userAgent));
}
function toRef(...args) {
if (args.length !== 1) return toRef$1(...args);
const r = args[0];
return typeof r === "function" ? readonly(customRef(() => ({
get: r,
set: noop$1
}))) : ref(r);
}
function createFilterWrapper(filter, fn) {
function wrapper(...args) {
return new Promise((resolve, reject) => {
Promise.resolve(filter(() => fn.apply(this, args), {
fn,
thisArg: this,
args
})).then(resolve).catch(reject);
});
}
if ("cancel" in filter) Object.assign(wrapper, {
cancel: filter.cancel,
flush: filter.flush,
isPending: filter.isPending
});
return wrapper;
}
var bypassFilter = (invoke) => {
return invoke();
};
function debounceFilter(ms, options = {}) {
let timer;
let maxTimer;
let lastRejector = noop$1;
let lastResolve = noop$1;
const _pending = shallowRef(false);
const _clearTimeout = (timer) => {
clearTimeout(timer);
lastRejector();
lastRejector = noop$1;
};
let lastInvoker;
const handler = (invoke) => {
const duration = toValue(ms);
const maxDuration = toValue(options.maxWait);
if (timer) _clearTimeout(timer);
if (duration <= 0 || maxDuration !== void 0 && maxDuration <= 0) {
if (maxTimer) {
_clearTimeout(maxTimer);
maxTimer = void 0;
}
_pending.value = false;
return Promise.resolve(invoke());
}
_pending.value = true;
return new Promise((resolve, reject) => {
lastRejector = options.rejectOnCancel ? reject : resolve;
lastResolve = resolve;
lastInvoker = invoke;
if (maxDuration && !maxTimer) maxTimer = setTimeout(() => {
if (timer) _clearTimeout(timer);
maxTimer = void 0;
_pending.value = false;
resolve(lastInvoker());
}, maxDuration);
timer = setTimeout(() => {
if (maxTimer) _clearTimeout(maxTimer);
maxTimer = void 0;
_pending.value = false;
resolve(invoke());
}, duration);
});
};
return Object.assign(handler, {
cancel: () => {
if (timer) {
_clearTimeout(timer);
timer = void 0;
}
if (maxTimer) {
_clearTimeout(maxTimer);
maxTimer = void 0;
}
_pending.value = false;
lastResolve = noop$1;
},
flush: () => {
if (_pending.value) {
if (timer) {
clearTimeout(timer);
timer = void 0;
}
if (maxTimer) {
clearTimeout(maxTimer);
maxTimer = void 0;
}
_pending.value = false;
const resolve = lastResolve;
lastRejector = noop$1;
lastResolve = noop$1;
resolve(lastInvoker());
}
},
isPending: shallowReadonly(_pending)
});
}
function throttleFilter(...args) {
let lastExec = 0;
let timer;
let isLeading = true;
let lastRejector = noop$1;
let lastValue;
let ms;
let trailing;
let leading;
let rejectOnCancel;
if (!isRef(args[0]) && typeof args[0] === "object") ({delay: ms, trailing = true, leading = true, rejectOnCancel = false} = args[0]);
else [ms, trailing = true, leading = true, rejectOnCancel = false] = args;
const clear = () => {
if (timer) {
clearTimeout(timer);
timer = void 0;
lastRejector();
lastRejector = noop$1;
}
};
const filter = (_invoke) => {
const duration = toValue(ms);
const elapsed = Date.now() - lastExec;
const invoke = () => {
return lastValue = _invoke();
};
clear();
if (duration <= 0) {
lastExec = Date.now();
return invoke();
}
if (elapsed > duration) {
lastExec = Date.now();
if (leading || !isLeading) invoke();
} else if (trailing) lastValue = new Promise((resolve, reject) => {
lastRejector = rejectOnCancel ? reject : resolve;
timer = setTimeout(() => {
lastExec = Date.now();
isLeading = true;
resolve(invoke());
clear();
}, Math.max(0, duration - elapsed));
});
if (!leading && !timer) timer = setTimeout(() => isLeading = true, duration);
isLeading = false;
return lastValue;
};
return filter;
}
function pausableFilter(extendFilter = bypassFilter, options = {}) {
const { initialState = "active" } = options;
const isActive = toRef(initialState === "active");
function pause() {
isActive.value = false;
}
function resume() {
isActive.value = true;
}
const eventFilter = (...args) => {
if (isActive.value) extendFilter(...args);
};
return {
isActive: shallowReadonly(isActive),
pause,
resume,
eventFilter
};
}
function pxValue(px) {
return px.endsWith("rem") ? Number.parseFloat(px) * 16 : Number.parseFloat(px);
}
function toArray$1(value) {
return Array.isArray(value) ? value : [value];
}
function getLifeCycleTarget$1(target) {
return target || getCurrentInstance();
}
function useDebounceFn(fn, ms = 200, options = {}) {
return createFilterWrapper(debounceFilter(ms, options), fn);
}
function useThrottleFn(fn, ms = 200, trailing = true, leading = true, rejectOnCancel = false) {
return createFilterWrapper(throttleFilter(ms, trailing, leading, rejectOnCancel), fn);
}
function watchWithFilter(source, cb, options = {}) {
const { eventFilter = bypassFilter, ...watchOptions } = options;
return watch(source, createFilterWrapper(eventFilter, cb), watchOptions);
}
function watchPausable(source, cb, options = {}) {
const { eventFilter: filter, initialState = "active", ...watchOptions } = options;
const { eventFilter, pause, resume, isActive } = pausableFilter(filter, { initialState });
return {
stop: watchWithFilter(source, cb, {
...watchOptions,
eventFilter
}),
pause,
resume,
isActive
};
}
function tryOnMounted(fn, sync = true, target) {
if (getLifeCycleTarget$1(target)) onMounted(fn, target);
else if (sync) fn();
else nextTick(fn);
}
function useTimeoutFn(cb, interval, options = {}) {
const { immediate = true, immediateCallback = false } = options;
const isPending = shallowRef(false);
let timer;
function clear() {
if (timer) {
clearTimeout(timer);
timer = void 0;
}
}
function stop() {
isPending.value = false;
clear();
}
function start(...args) {
if (immediateCallback) cb();
clear();
isPending.value = true;
timer = setTimeout(() => {
isPending.value = false;
timer = void 0;
cb(...args);
}, toValue(interval));
}
if (immediate) {
isPending.value = true;
if (isClient$1) start();
}
tryOnScopeDispose$1(stop);
return {
isPending: shallowReadonly(isPending),
start,
stop
};
}
function watchImmediate$1(source, cb, options) {
return watch(source, cb, {
...options,
immediate: true
});
}
var defaultWindow$1 = isClient$1 ? window : void 0;
isClient$1 && window.document;
isClient$1 && window.navigator;
isClient$1 && window.location;
function unrefElement$1(elRef) {
var _$el;
const plain = toValue(elRef);
return (_$el = plain === null || plain === void 0 ? void 0 : plain.$el) !== null && _$el !== void 0 ? _$el : plain;
}
function useEventListener$1(...args) {
const register = (el, event, listener, options) => {
el.addEventListener(event, listener, options);
return () => el.removeEventListener(event, listener, options);
};
const firstParamTargets = computed(() => {
const test = toArray$1(toValue(args[0])).filter((e) => e != null);
return test.every((e) => typeof e !== "string") ? test : void 0;
});
return watchImmediate$1(() => {
var _firstParamTargets$va, _firstParamTargets$va2;
return [
(_firstParamTargets$va = (_firstParamTargets$va2 = firstParamTargets.value) === null || _firstParamTargets$va2 === void 0 ? void 0 : _firstParamTargets$va2.map((e) => unrefElement$1(e))) !== null && _firstParamTargets$va !== void 0 ? _firstParamTargets$va : [defaultWindow$1].filter((e) => e != null),
toArray$1(toValue(firstParamTargets.value ? args[1] : args[0])),
toArray$1(unref(firstParamTargets.value ? args[2] : args[1])),
toValue(firstParamTargets.value ? args[3] : args[2])
];
}, ([raw_targets, raw_events, raw_listeners, raw_options], _, onCleanup) => {
if (!(raw_targets === null || raw_targets === void 0 ? void 0 : raw_targets.length) || !(raw_events === null || raw_events === void 0 ? void 0 : raw_events.length) || !(raw_listeners === null || raw_listeners === void 0 ? void 0 : raw_listeners.length)) return;
const optionsClone = isObject$2(raw_options) ? { ...raw_options } : raw_options;
const cleanups = raw_targets.flatMap((el) => raw_events.flatMap((event) => raw_listeners.map((listener) => register(el, event, listener, optionsClone))));
onCleanup(() => {
cleanups.forEach((fn) => fn());
});
}, { flush: "post" });
}
var _iOSWorkaround = false;
function onClickOutside(target, handler, options = {}) {
const { window = defaultWindow$1, ignore = [], capture = true, detectIframe = false, controls = false } = options;
if (!window) return controls ? {
stop: noop$1,
cancel: noop$1,
trigger: noop$1
} : noop$1;
if (isIOS && !_iOSWorkaround) {
_iOSWorkaround = true;
const listenerOptions = { passive: true };
Array.from(window.document.body.children).forEach((el) => el.addEventListener("click", noop$1, listenerOptions));
window.document.documentElement.addEventListener("click", noop$1, listenerOptions);
}
let shouldListen = true;
const shouldIgnore = (event) => {
return toValue(ignore).some((target) => {
if (typeof target === "string") return Array.from(window.document.querySelectorAll(target)).some((el) => el === event.target || event.composedPath().includes(el));
else {
const el = unrefElement$1(target);
return el && (event.target === el || event.composedPath().includes(el));
}
});
};
function hasMultipleRoots(target) {
const vm = toValue(target);
return vm && vm.$.subTree.shapeFlag === 16;
}
function checkMultipleRoots(target, event) {
const vm = toValue(target);
const children = vm.$.subTree && vm.$.subTree.children;
if (children == null || !Array.isArray(children)) return false;
return children.some((child) => child.el === event.target || event.composedPath().includes(child.el));
}
const listener = (event) => {
const el = unrefElement$1(target);
if (event.target == null) return;
if (!(el instanceof Element) && hasMultipleRoots(target) && checkMultipleRoots(target, event)) return;
if (!el || el === event.target || event.composedPath().includes(el)) return;
if ("detail" in event && event.detail === 0) shouldListen = !shouldIgnore(event);
if (!shouldListen) {
shouldListen = true;
return;
}
handler(event);
};
let isProcessingClick = false;
const cleanup = [
useEventListener$1(window, "click", (event) => {
if (!isProcessingClick) {
isProcessingClick = true;
setTimeout(() => {
isProcessingClick = false;
}, 0);
listener(event);
}
}, {
passive: true,
capture
}),
useEventListener$1(window, "pointerdown", (e) => {
const el = unrefElement$1(target);
shouldListen = !shouldIgnore(e) && !!(el && !e.composedPath().includes(el));
}, { passive: true }),
detectIframe && useEventListener$1(window, "blur", (event) => {
setTimeout(() => {
const el = unrefElement$1(target);
let activeEl = window.document.activeElement;
while (activeEl === null || activeEl === void 0 ? void 0 : activeEl.shadowRoot) activeEl = activeEl.shadowRoot.activeElement;
if ((activeEl === null || activeEl === void 0 ? void 0 : activeEl.tagName) === "IFRAME" && !(el === null || el === void 0 ? void 0 : el.contains(window.document.activeElement))) handler(event);
}, 0);
}, { passive: true })
].filter(Boolean);
const stop = () => cleanup.forEach((fn) => fn());
if (controls) return {
stop,
cancel: () => {
shouldListen = false;
},
trigger: (event) => {
shouldListen = true;
listener(event);
shouldListen = false;
}
};
return stop;
}
function useMounted$1() {
const isMounted = shallowRef(false);
const instance = getCurrentInstance();
if (instance) onMounted(() => {
isMounted.value = true;
}, instance);
return isMounted;
}
function useSupported$1(callback) {
const isMounted = useMounted$1();
return computed(() => {
isMounted.value;
return Boolean(callback());
});
}
function useMutationObserver(target, callback, options = {}) {
const { window = defaultWindow$1, ...mutationOptions } = options;
let observer;
const isSupported = useSupported$1(() => window && "MutationObserver" in window);
const cleanup = () => {
if (observer) {
observer.disconnect();
observer = void 0;
}
};
const stopWatch = watch(computed(() => {
const items = toArray$1(toValue(target)).map(unrefElement$1).filter(notNullish$1);
return new Set(items);
}), (newTargets) => {
cleanup();
if (isSupported.value && newTargets.size) {
observer = new MutationObserver(callback);
newTargets.forEach((el) => observer.observe(el, mutationOptions));
}
}, {
immediate: true,
flush: "post"
});
const takeRecords = () => {
return observer === null || observer === void 0 ? void 0 : observer.takeRecords();
};
const stop = () => {
stopWatch();
cleanup();
};
tryOnScopeDispose$1(stop);
return {
isSupported,
stop,
takeRecords
};
}
var ssrWidthSymbol = Symbol("vueuse-ssr-width");
function useSSRWidth() {
const ssrWidth = hasInjectionContext() ? injectLocal(ssrWidthSymbol, null) : null;
return typeof ssrWidth === "number" ? ssrWidth : void 0;
}
function useMediaQuery(query, options = {}) {
const { window = defaultWindow$1, ssrWidth = useSSRWidth() } = options;
const isSupported = useSupported$1(() => window && "matchMedia" in window && typeof window.matchMedia === "function");
const ssrSupport = shallowRef(typeof ssrWidth === "number");
const mediaQuery = shallowRef();
const matches = shallowRef(false);
const handler = (event) => {
matches.value = event.matches;
};
watchEffect(() => {
if (ssrSupport.value) {
ssrSupport.value = !isSupported.value;
const queryStrings = toValue(query).split(",");
matches.value = queryStrings.some((queryString) => {
const not = queryString.includes("not all");
const minWidth = queryString.match(/\(\s*min-width:\s*(-?\d+(?:\.\d*)?[a-z]+\s*)\)/);
const maxWidth = queryString.match(/\(\s*max-width:\s*(-?\d+(?:\.\d*)?[a-z]+\s*)\)/);
let res = Boolean(minWidth || maxWidth);
if (minWidth && res) res = ssrWidth >= pxValue(minWidth[1]);
if (maxWidth && res) res = ssrWidth <= pxValue(maxWidth[1]);
return not ? !res : res;
});
return;
}
if (!isSupported.value) return;
mediaQuery.value = window.matchMedia(toValue(query));
matches.value = mediaQuery.value.matches;
});
useEventListener$1(mediaQuery, "change", handler, { passive: true });
return computed(() => matches.value);
}
var _global = typeof globalThis !== "undefined" ? globalThis : typeof window !== "undefined" ? window : typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : {};
var globalKey = "__vueuse_ssr_handlers__";
var handlers = getHandlers();
function getHandlers() {
if (!(globalKey in _global)) _global[globalKey] = _global[globalKey] || {};
return _global[globalKey];
}
function getSSRHandler(key, fallback) {
return handlers[key] || fallback;
}
function usePreferredDark(options) {
return useMediaQuery("(prefers-color-scheme: dark)", options);
}
function guessSerializerType(rawInit) {
return rawInit == null ? "any" : rawInit instanceof Set ? "set" : rawInit instanceof Map ? "map" : rawInit instanceof Date ? "date" : typeof rawInit === "boolean" ? "boolean" : typeof rawInit === "string" ? "string" : typeof rawInit === "object" ? "object" : !Number.isNaN(rawInit) ? "number" : "any";
}
var StorageSerializers = {
boolean: {
read: (v) => v === "true",
write: (v) => String(v)
},
object: {
read: (v) => JSON.parse(v),
write: (v) => JSON.stringify(v)
},
number: {
read: (v) => Number.parseFloat(v),
write: (v) => String(v)
},
any: {
read: (v) => v,
write: (v) => String(v)
},
string: {
read: (v) => v,
write: (v) => String(v)
},
map: {
read: (v) => new Map(JSON.parse(v)),
write: (v) => JSON.stringify(Array.from(v.entries()))
},
set: {
read: (v) => new Set(JSON.parse(v)),
write: (v) => JSON.stringify(Array.from(v))
},
date: {
read: (v) => new Date(v),
write: (v) => v.toISOString()
}
};
var customStorageEventName = "vueuse-storage";
function useStorage(key, defaults, storage, options = {}) {
var _options$serializer;
const { flush = "pre", deep = true, listenToStorageChanges = true, writeDefaults = true, mergeDefaults = false, shallow, window = defaultWindow$1, eventFilter, onError = (e) => {
console.error(e);
}, initOnMounted } = options;
const data = (shallow ? shallowRef : ref)(typeof defaults === "function" ? defaults() : defaults);
const keyComputed = computed(() => toValue(key));
if (!storage) try {
storage = getSSRHandler("getDefaultStorage", () => defaultWindow$1 === null || defaultWindow$1 === void 0 ? void 0 : defaultWindow$1.localStorage)();
} catch (e) {
onError(e);
}
if (!storage) return data;
const rawInit = toValue(defaults);
const type = guessSerializerType(rawInit);
const serializer = (_options$serializer = options.serializer) !== null && _options$serializer !== void 0 ? _options$serializer : StorageSerializers[type];
const { pause: pauseWatch, resume: resumeWatch } = watchPausable(data, (newValue) => write(newValue), {
flush,
deep,
eventFilter
});
watch(keyComputed, () => update(), { flush });
let firstMounted = false;
const onStorageEvent = (ev) => {
if (initOnMounted && !firstMounted) return;
update(ev);
};
const onStorageCustomEvent = (ev) => {
if (initOnMounted && !firstMounted) return;
updateFromCustomEvent(ev);
};
if (window && listenToStorageChanges) {
if (storage instanceof Storage) useEventListener$1(window, "storage", onStorageEvent, { passive: true });
else useEventListener$1(window, customStorageEventName, onStorageCustomEvent);
}
if (initOnMounted) tryOnMounted(() => {
firstMounted = true;
update();
});
else update();
function dispatchWriteEvent(oldValue, newValue) {
if (window) {
const payload = {
key: keyComputed.value,
oldValue,
newValue,
storageArea: storage
};
window.dispatchEvent(storage instanceof Storage ? new StorageEvent("storage", payload) : new CustomEvent(customStorageEventName, { detail: payload }));
}
}
function write(v) {
try {
const oldValue = storage.getItem(keyComputed.value);
if (v == null) {
dispatchWriteEvent(oldValue, null);
storage.removeItem(keyComputed.value);
} else {
const serialized = serializer.write(v);
if (oldValue !== serialized) {
storage.setItem(keyComputed.value, serialized);
dispatchWriteEvent(oldValue, serialized);
}
}
} catch (e) {
onError(e);
}
}
function read(event) {
const rawValue = event ? event.newValue : storage.getItem(keyComputed.value);
if (rawValue == null) {
if (writeDefaults && rawInit != null) storage.setItem(keyComputed.value, serializer.write(rawInit));
return rawInit;
} else if (!event && mergeDefaults) {
const value = serializer.read(rawValue);
if (typeof mergeDefaults === "function") return mergeDefaults(value, rawInit);
else if (type === "object" && !Array.isArray(value)) return {
...rawInit,
...value
};
return value;
} else if (typeof rawValue !== "string") return rawValue;
else return serializer.read(rawValue);
}
function update(event) {
if (event && event.storageArea !== storage) return;
if (event && event.key == null) {
data.value = rawInit;
return;
}
if (event && event.key !== keyComputed.value) return;
pauseWatch();
try {
const serializedData = serializer.write(data.value);
if (event === void 0 || (event === null || event === void 0 ? void 0 : event.newValue) !== serializedData) data.value = read(event);
} catch (e) {
onError(e);
} finally {
if (event) nextTick(resumeWatch);
else resumeWatch();
}
}
function updateFromCustomEvent(event) {
update(event.detail);
}
return data;
}
function useResizeObserver(target, callback, options = {}) {
const { window = defaultWindow$1, ...observerOptions } = options;
let observer;
const isSupported = useSupported$1(() => window && "ResizeObserver" in window);
const cleanup = () => {
if (observer) {
observer.disconnect();
observer = void 0;
}
};
const stopWatch = watch(computed(() => {
const _targets = toValue(target);
return Array.isArray(_targets) ? _targets.map((el) => unrefElement$1(el)) : [unrefElement$1(_targets)];
}), (els) => {
cleanup();
if (isSupported.value && window) {
observer = new ResizeObserver(callback);
for (const _el of els) if (_el instanceof Element) observer.observe(_el, observerOptions);
}
}, {
immediate: true,
flush: "post"
});
const stop = () => {
cleanup();
stopWatch();
};
tryOnScopeDispose$1(stop);
return {
isSupported,
stop
};
}
function useElementSize(target, initialSize = {
width: 0,
height: 0
}, options = {}) {
const { window = defaultWindow$1, box = "content-box" } = options;
const isSVG = computed(() => {
var _unrefElement;
return (_unrefElement = unrefElement$1(target)) === null || _unrefElement === void 0 || (_unrefElement = _unrefElement.namespaceURI) === null || _unrefElement === void 0 ? void 0 : _unrefElement.includes("svg");
});
const width = shallowRef(initialSize.width);
const height = shallowRef(initialSize.height);
const { stop: stop1 } = useResizeObserver(target, ([entry]) => {
const boxSize = box === "border-box" ? entry.borderBoxSize : box === "content-box" ? entry.contentBoxSize : entry.devicePixelContentBoxSize;
if (window && isSVG.value) {
const $elem = unrefElement$1(target);
if ($elem) {
const rect = $elem.getBoundingClientRect();
width.value = rect.width;
height.value = rect.height;
}
} else if (boxSize) {
const formatBoxSize = toArray$1(boxSize);
width.value = formatBoxSize.reduce((acc, { inlineSize }) => acc + inlineSize, 0);
height.value = formatBoxSize.reduce((acc, { blockSize }) => acc + blockSize, 0);
} else {
width.value = entry.contentRect.width;
height.value = entry.contentRect.height;
}
}, options);
tryOnMounted(() => {
const ele = unrefElement$1(target);
if (ele && "offsetWidth" in ele) {
if (box === "content-box" && window) {
const cs = window.getComputedStyle(ele);
const padX = Number.parseFloat(cs.paddingLeft) + Number.parseFloat(cs.paddingRight);
const padY = Number.parseFloat(cs.paddingTop) + Number.parseFloat(cs.paddingBottom);
const bdX = Number.parseFloat(cs.borderLeftWidth) + Number.parseFloat(cs.borderRightWidth);
const bdY = Number.parseFloat(cs.borderTopWidth) + Number.parseFloat(cs.borderBottomWidth);
width.value = ele.offsetWidth - padX - bdX;
height.value = ele.offsetHeight - padY - bdY;
} else {
width.value = ele.offsetWidth;
height.value = ele.offsetHeight;
}
} else if (ele) {
width.value = initialSize.width;
height.value = initialSize.height;
}
});
const stop2 = watch(() => unrefElement$1(target), (ele) => {
width.value = ele ? initialSize.width : 0;
height.value = ele ? initialSize.height : 0;
});
function stop() {
stop1();
stop2();
}
return {
width,
height,
stop
};
}
var ARRIVED_STATE_THRESHOLD_PIXELS = 1;
function useScroll(element, options = {}) {
const { throttle = 0, idle = 200, onStop = noop$1, onScroll = noop$1, offset = {
left: 0,
right: 0,
top: 0,
bottom: 0
}, observe: _observe = { mutation: false }, eventListenerOptions = {
capture: false,
passive: true
}, behavior = "auto", window = defaultWindow$1, onError = (e) => {
console.error(e);
} } = options;
const observe = typeof _observe === "boolean" ? { mutation: _observe } : _observe;
const internalX = shallowRef(0);
const internalY = shallowRef(0);
const x = computed({
get() {
return internalX.value;
},
set(x) {
scrollTo(x, void 0);
}
});
const y = computed({
get() {
return internalY.value;
},
set(y) {
scrollTo(void 0, y);
}
});
function scrollTo(_x, _y) {
var _ref, _toValue, _toValue2, _document;
if (!window) return;
const _element = toValue(element);
if (!_element) return;
(_ref = _element instanceof Document ? window.document.body : _element) === null || _ref === void 0 || _ref.scrollTo({
top: (_toValue = toValue(_y)) !== null && _toValue !== void 0 ? _toValue : y.value,
left: (_toValue2 = toValue(_x)) !== null && _toValue2 !== void 0 ? _toValue2 : x.value,
behavior: toValue(behavior)
});
const scrollContainer = (_element === null || _element === void 0 || (_document = _element.document) === null || _document === void 0 ? void 0 : _document.documentElement) || (_element === null || _element === void 0 ? void 0 : _element.documentElement) || _element;
if (x != null) internalX.value = scrollContainer.scrollLeft;
if (y != null) internalY.value = scrollContainer.scrollTop;
}
const isScrolling = shallowRef(false);
const arrivedState = reactive({
left: true,
right: false,
top: true,
bottom: false
});
const directions = reactive({
left: false,
right: false,
top: false,
bottom: false
});
const onScrollEnd = (e) => {
if (!isScrolling.value) return;
isScrolling.value = false;
directions.left = false;
directions.right = false;
directions.top = false;
directions.bottom = false;
onStop(e);
};
const onScrollEndDebounced = useDebounceFn(onScrollEnd, throttle + idle);
const setArrivedState = (target) => {
var _document2;
if (!window) return;
const el = (target === null || target === void 0 || (_document2 = target.document) === null || _document2 === void 0 ? void 0 : _document2.documentElement) || (target === null || target === void 0 ? void 0 : target.documentElement) || unrefElement$1(target);
const { display, flexDirection, direction } = window.getComputedStyle(el);
const directionMultipler = direction === "rtl" ? -1 : 1;
const scrollLeft = el.scrollLeft;
directions.left = scrollLeft < internalX.value;
directions.right = scrollLeft > internalX.value;
const left = Math.abs(scrollLeft * directionMultipler) <= (offset.left || 0);
const right = Math.abs(scrollLeft * directionMultipler) + el.clientWidth >= el.scrollWidth - (offset.right || 0) - ARRIVED_STATE_THRESHOLD_PIXELS;
if (display === "flex" && flexDirection === "row-reverse") {
arrivedState.left = right;
arrivedState.right = left;
} else {
arrivedState.left = left;
arrivedState.right = right;
}
internalX.value = scrollLeft;
let scrollTop = el.scrollTop;
if (target === window.document && !scrollTop) scrollTop = window.document.body.scrollTop;
directions.top = scrollTop < internalY.value;
directions.bottom = scrollTop > internalY.value;
const top = Math.abs(scrollTop) <= (offset.top || 0);
const bottom = Math.abs(scrollTop) + el.clientHeight >= el.scrollHeight - (offset.bottom || 0) - ARRIVED_STATE_THRESHOLD_PIXELS;
if (display === "flex" && flexDirection === "column-reverse") {
arrivedState.top = bottom;
arrivedState.bottom = top;
} else {
arrivedState.top = top;
arrivedState.bottom = bottom;
}
internalY.value = scrollTop;
};
const onScrollHandler = (e) => {
var _documentElement;
if (!window) return;
const eventTarget = (_documentElement = e.target.documentElement) !== null && _documentElement !== void 0 ? _documentElement : e.target;
setArrivedState(eventTarget);
isScrolling.value = true;
onScrollEndDebounced(e);
onScroll(e);
};
useEventListener$1(element, "scroll", throttle ? useThrottleFn(onScrollHandler, throttle, true, false) : onScrollHandler, eventListenerOptions);
tryOnMounted(() => {
try {
const _element = toValue(element);
if (!_element) return;
setArrivedState(_element);
} catch (e) {
onError(e);
}
});
if ((observe === null || observe === void 0 ? void 0 : observe.mutation) && element != null && element !== window && element !== document) useMutationObserver(element, () => {
const _element = toValue(element);
if (!_element) return;
setArrivedState(_element);
}, {
attributes: true,
childList: true,
subtree: true
});
useEventListener$1(element, "scrollend", onScrollEnd, eventListenerOptions);
return {
x,
y,
isScrolling,
arrivedState,
directions,
measure() {
const _element = toValue(element);
if (window && _element) setArrivedState(_element);
}
};
}
function useLocalStorage(key, initialValue, options = {}) {
const { window = defaultWindow$1 } = options;
return useStorage(key, initialValue, window === null || window === void 0 ? void 0 : window.localStorage, options);
}
function usePreferredReducedMotion(options) {
const isReduced = useMediaQuery("(prefers-reduced-motion: reduce)", options);
return computed(() => {
if (isReduced.value) return "reduce";
return "no-preference";
});
}
var defaultAttributes = {
xmlns: "http://www.w3.org/2000/svg",
width: 24,
height: 24,
viewBox: "0 0 24 24",
fill: "none",
stroke: "currentColor",
"stroke-width": 2,
"stroke-linecap": "round",
"stroke-linejoin": "round"
};
var mergeClasses = (...classes) => {
const tokens = new Set();
for (const cls of classes) {
if (typeof cls !== "string") continue;
for (const token of cls.split(/\s+/)) if (token) tokens.add(token);
}
return [...tokens].join(" ");
};
function isDefined(value) {
return value !== null && value !== void 0;
}
function buildLucideIconNode(icon, params = {}) {
const attributeNames = params.attributeNames ?? {};
const getAttributeName = (attributeName) => attributeNames[attributeName] ?? attributeName;
const viewBoxWidth = icon.size ?? icon.width ?? defaultAttributes["width"];
const viewBoxHeight = icon.size ?? icon.height ?? defaultAttributes["height"];
const aliasClassNames = icon.aliases?.filter((alias) => typeof alias === "string" && alias.trim() !== "").map((alias) => `lucide-${alias}`) ?? [];
const iconClassNames = [...icon.name ? [`lucide-${icon.name}`] : [], ...aliasClassNames];
const classNamesFromClassName = params.className?.split(" ").filter(Boolean) ?? [];
const className = params.includeDefaultClasses === false ? mergeClasses(...classNamesFromClassName) : mergeClasses("lucide", ...iconClassNames, ...classNamesFromClassName);
const calculatedStrokeWidth = params.absoluteStrokeWidth ? Number(params.strokeWidth ?? defaultAttributes["stroke-width"]) * Number(icon.size ?? icon.width ?? defaultAttributes["width"]) / Number(params.size ?? params.width ?? defaultAttributes["width"]) : params.strokeWidth ?? defaultAttributes["stroke-width"];
return [
"svg",
{
...Object.entries(defaultAttributes).reduce((attrs, [attrName, value]) => {
attrs[getAttributeName(attrName)] = value;
return attrs;
}, {}),
..."color" in params && params.color && { [getAttributeName("stroke")]: params.color },
..."size" in params && isDefined(params.size) && {
[getAttributeName("width")]: params.size,
[getAttributeName("height")]: params.size
},
..."width" in params && isDefined(params.width) && { [getAttributeName("width")]: params.width },
..."height" in params && isDefined(params.height) && { [getAttributeName("height")]: params.height },
[getAttributeName("stroke-width")]: calculatedStrokeWidth,
...className && { [getAttributeName("class")]: className },
[getAttributeName("viewBox")]: `0 0 ${viewBoxWidth} ${viewBoxHeight}`,
...params.hasA11yProp === false ? { [getAttributeName("aria-hidden")]: "true" } : {},
..."attributes" in params && params.attributes
},
icon.node.map((child) => {
const [name, attrs, children] = child;
const nextAttrs = params.nonScalingStroke ? {
[getAttributeName("vector-effect")]: "non-scaling-stroke",
...attrs
} : attrs;
return children ? [
name,
nextAttrs,
children
] : [name, nextAttrs];
})
];
}
var hasA11yProp = (props) => {
if (props == null || typeof props !== "object") return false;
for (const prop in props) if (Object.prototype.hasOwnProperty.call(props, prop) && (prop.startsWith("aria-") || prop === "role" || prop === "title") && props[prop] != null) return true;
return false;
};
var isEmptyString = (value) => value === "";
var toKebabCase = (string) => string?.replace(/([a-z0-9])([A-Z])/g, "$1-$2").toLowerCase();
var LUCIDE_CONTEXT = Symbol("lucide-icons");
function useLucideProps() {
return inject(LUCIDE_CONTEXT, {});
}
var Icon = ({ name, iconNode, "icon-node": iconNodeKebabCase, icon = {
name: name && toKebabCase(name),
node: iconNode ?? iconNodeKebabCase ?? [],
size: 24,
aliases: []
}, absoluteStrokeWidth, "absolute-stroke-width": absoluteStrokeWidthKebabCase, nonScalingStroke, "non-scaling-stroke": nonScalingStrokeKebabCase, strokeWidth, "stroke-width": strokeWidthKebabCase, size, width = size, height = size, color, ...props }, { slots }) => {
const { size: contextSize, color: contextColor, strokeWidth: contextStrokeWidth = 2, absoluteStrokeWidth: contextAbsoluteStrokeWidth = false, nonScalingStroke: contextNonScalingStroke = false, class: contextClass = "" } = useLucideProps();
const isAbsoluteStrokeWidth = isEmptyString(absoluteStrokeWidth) || isEmptyString(absoluteStrokeWidthKebabCase) || absoluteStrokeWidth === true || absoluteStrokeWidthKebabCase === true || contextAbsoluteStrokeWidth === true;
const isNonScalingStroke = isEmptyString(nonScalingStroke) || isEmptyString(nonScalingStrokeKebabCase) || nonScalingStroke === true || nonScalingStrokeKebabCase === true || contextNonScalingStroke === true;
delete props.class;
const defaultSlot = slots.default?.();
const [, svgAttributes, builtIconNode = []] = buildLucideIconNode(icon, {
color: color ?? contextColor,
width: width ?? size ?? contextSize,
height: height ?? size ?? contextSize,
strokeWidth: strokeWidth ?? strokeWidthKebabCase ?? contextStrokeWidth,
absoluteStrokeWidth: isAbsoluteStrokeWidth,
nonScalingStroke: isNonScalingStroke,
className: contextClass,
hasA11yProp: defaultSlot != null && defaultSlot.length > 0 || hasA11yProp(props),
attributes: props
});
return h("svg", svgAttributes, [...builtIconNode.map(([tag, attrs]) => h(tag, attrs)), ...defaultSlot ?? []]);
};
function createLucideIcon(iconDataOrName, iconNode = []) {
const icon = typeof iconDataOrName === "string" ? {
name: iconDataOrName,
node: iconNode
} : iconDataOrName;
return (props, { slots }) => h(Icon, {
...props,
icon
}, slots.default ? { default: slots.default } : void 0);
}
var ArrowDown = createLucideIcon({
name: "arrow-down",
size: 24,
node: [["path", {
d: "M12 5v14",
key: "s699le"
}], ["path", {
d: "m19 12-7 7-7-7",
key: "1idqje"
}]]
});
var ArrowLeft = createLucideIcon({
name: "arrow-left",
size: 24,
node: [["path", {
d: "m12 19-7-7 7-7",
key: "1l729n"
}], ["path", {
d: "M19 12H5",
key: "x3x0zl"
}]]
});
var ArrowRight = createLucideIcon({
name: "arrow-right",
size: 24,
node: [["path", {
d: "M5 12h14",
key: "1ays0h"
}], ["path", {
d: "m12 5 7 7-7 7",
key: "xquz4c"
}]]
});
var ArrowUpRight = createLucideIcon({
name: "arrow-up-right",
size: 24,
node: [["path", {
d: "M7 7h10v10",
key: "1tivn9"
}], ["path", {
d: "M7 17 17 7",
key: "1vkiza"
}]]
});
var ArrowUp = createLucideIcon({
name: "arrow-up",
size: 24,
node: [["path", {
d: "m5 12 7-7 7 7",
key: "hav0vg"
}], ["path", {
d: "M12 19V5",
key: "x0mq9r"
}]]
});
var Bookmark = createLucideIcon({
name: "bookmark",
size: 24,
node: [["path", {
d: "M17 3a2 2 0 0 1 2 2v15a1 1 0 0 1-1.496.868l-4.512-2.578a2 2 0 0 0-1.984 0l-4.512 2.578A1 1 0 0 1 5 20V5a2 2 0 0 1 2-2z",
key: "oz39mx"
}]]
});
var Check = createLucideIcon({
name: "check",
size: 24,
node: [["path", {
d: "M20 6 9 17l-5-5",
key: "1gmf2c"
}]]
});
var ChevronDown = createLucideIcon({
name: "chevron-down",
size: 24,
node: [["path", {
d: "m6 9 6 6 6-6",
key: "qrunsl"
}]]
});
var ChevronUp = createLucideIcon({
name: "chevron-up",
size: 24,
node: [["path", {
d: "m18 15-6-6-6 6",
key: "153udz"
}]]
});
var Compass = createLucideIcon({
name: "compass",
size: 24,
node: [["circle", {
cx: "12",
cy: "12",
r: "10",
key: "1mglay"
}], ["path", {
d: "m16.24 7.76-1.804 5.411a2 2 0 0 1-1.265 1.265L7.76 16.24l1.804-5.411a2 2 0 0 1 1.265-1.265z",
key: "9ktpf1"
}]]
});
var Download = createLucideIcon({
name: "download",
size: 24,
node: [
["path", {
d: "M12 15V3",
key: "m9g1x1"
}],
["path", {
d: "M21 15v4a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2v-4",
key: "ih7n3h"
}],
["path", {
d: "m7 10 5 5 5-5",
key: "brsn70"
}]
]
});
var Ellipsis = createLucideIcon({
name: "ellipsis",
size: 24,
node: [
["circle", {
cx: "12",
cy: "12",
r: "1",
key: "41hilf"
}],
["circle", {
cx: "19",
cy: "12",
r: "1",
key: "1wjl8i"
}],
["circle", {
cx: "5",
cy: "12",
r: "1",
key: "1pcz8c"
}]
],
aliases: ["more-horizontal"]
});
var ExternalLink = createLucideIcon({
name: "external-link",
size: 24,
node: [
["path", {
d: "M15 3h6v6",
key: "1q9fwt"
}],
["path", {
d: "M10 14 21 3",
key: "gplh6r"
}],
["path", {
d: "M18 13v6a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2V8a2 2 0 0 1 2-2h6",
key: "a6xqqp"
}]
]
});
var Eye = createLucideIcon({
name: "eye",
size: 24,
node: [["path", {
d: "M2.062 12.348a1 1 0 0 1 0-.696 10.75 10.75 0 0 1 19.876 0 1 1 0 0 1 0 .696 10.75 10.75 0 0 1-19.876 0",
key: "1nclc0"
}], ["circle", {
cx: "12",
cy: "12",
r: "3",
key: "1v7zrd"
}]]
});
var Flame = createLucideIcon({
name: "flame",
size: 24,
node: [["path", {
d: "M12 3q1 4 4 6.5t3 5.5a1 1 0 0 1-14 0 5 5 0 0 1 1-3 1 1 0 0 0 5 0c0-2-1.5-3-1.5-5q0-2 2.5-4",
key: "1slcih"
}]]
});
var Grid2x2 = createLucideIcon({
name: "grid-2x2",
size: 24,
node: [
["path", {
d: "M12 3v18",
key: "108xh3"
}],
["path", {
d: "M3 12h18",
key: "1i2n21"
}],
["rect", {
x: "3",
y: "3",
width: "18",
height: "18",
rx: "2",
key: "h1oib"
}]
],
aliases: ["grid-2-x-2"]
});
var Heart = createLucideIcon({
name: "heart",
size: 24,
node: [["path", {
d: "M2 9.5a5.5 5.5 0 0 1 9.591-3.676.56.56 0 0 0 .818 0A5.49 5.49 0 0 1 22 9.5c0 2.29-1.5 4-3 5.5l-5.492 5.313a2 2 0 0 1-3 .019L5 15c-1.5-1.5-3-3.2-3-5.5",
key: "mvr1a0"
}]]
});
var House = createLucideIcon({
name: "house",
size: 24,
node: [["path", {
d: "M15 21v-8a1 1 0 0 0-1-1h-4a1 1 0 0 0-1 1v8",
key: "5wwlr5"
}], ["path", {
d: "M3 10a2 2 0 0 1 .709-1.528l7-6a2 2 0 0 1 2.582 0l7 6A2 2 0 0 1 21 10v9a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2z",
key: "r6nss1"
}]],
aliases: ["home"]
});
var Image$1 = createLucideIcon({
name: "image",
size: 24,
node: [
["rect", {
width: "18",
height: "18",
x: "3",
y: "3",
rx: "2",
ry: "2",
key: "1m3agn"
}],
["circle", {
cx: "9",
cy: "9",
r: "2",
key: "af1f0g"
}],
["path", {
d: "m21 15-3.086-3.086a2 2 0 0 0-2.828 0L6 21",
key: "1xmnt7"
}]
]
});
var LibraryBig = createLucideIcon({
name: "library-big",
size: 24,
node: [
["rect", {
width: "8",
height: "18",
x: "3",
y: "3",
rx: "1",
key: "oynpb5"
}],
["path", {
d: "M7 3v18",
key: "bbkbws"
}],
["path", {
d: "M20.4 18.9c.2.5-.1 1.1-.6 1.3l-1.9.7c-.5.2-1.1-.1-1.3-.6L11.1 5.1c-.2-.5.1-1.1.6-1.3l1.9-.7c.5-.2 1.1.1 1.3.6Z",
key: "1qboyk"
}]
]
});
var List = createLucideIcon({
name: "list",
size: 24,
node: [
["path", {
d: "M3 5h.01",
key: "18ugdj"
}],
["path", {
d: "M3 12h.01",
key: "nlz23k"
}],
["path", {
d: "M3 19h.01",
key: "noohij"
}],
["path", {
d: "M8 5h13",
key: "1pao27"
}],
["path", {
d: "M8 12h13",
key: "1za7za"
}],
["path", {
d: "M8 19h13",
key: "m83p4d"
}]
]
});
var Menu = createLucideIcon({
name: "menu",
size: 24,
node: [
["path", {
d: "M4 5h16",
key: "1tepv9"
}],
["path", {
d: "M4 12h16",
key: "1lakjw"
}],
["path", {
d: "M4 19h16",
key: "1djgab"
}]
]
});
var MessageSquare = createLucideIcon({
name: "message-square",
size: 24,
node: [["path", {
d: "M22 17a2 2 0 0 1-2 2H6.828a2 2 0 0 0-1.414.586l-2.202 2.202A.71.71 0 0 1 2 21.286V5a2 2 0 0 1 2-2h16a2 2 0 0 1 2 2z",
key: "18887p"
}]]
});
var Moon = createLucideIcon({
name: "moon",
size: 24,
node: [["path", {
d: "M20.985 12.486a9 9 0 1 1-9.473-9.472c.405-.022.617.46.402.803a6 6 0 0 0 8.268 8.268c.344-.215.825-.004.803.401",
key: "kfwtm"
}]]
});
var Pipette = createLucideIcon({
name: "pipette",
size: 24,
node: [
["path", {
d: "m12 9-8.414 8.414A2 2 0 0 0 3 18.828v1.344a2 2 0 0 1-.586 1.414A2 2 0 0 1 3.828 21h1.344a2 2 0 0 0 1.414-.586L15 12",
key: "1y3wsu"
}],
["path", {
d: "m18 9 .4.4a1 1 0 1 1-3 3l-3.8-3.8a1 1 0 1 1 3-3l.4.4 3.4-3.4a1 1 0 1 1 3 3z",
key: "110lr1"
}],
["path", {
d: "m2 22 .414-.414",
key: "jhxm08"
}]
]
});
var Plus = createLucideIcon({
name: "plus",
size: 24,
node: [["path", {
d: "M5 12h14",
key: "1ays0h"
}], ["path", {
d: "M12 5v14",
key: "s699le"
}]]
});
var RefreshCw = createLucideIcon({
name: "refresh-cw",
size: 24,
node: [
["path", {
d: "M3 12a9 9 0 0 1 9-9 9.75 9.75 0 0 1 6.74 2.74L21 8",
key: "v9h5vc"
}],
["path", {
d: "M21 3v5h-5",
key: "1q7to0"
}],
["path", {
d: "M21 12a9 9 0 0 1-9 9 9.75 9.75 0 0 1-6.74-2.74L3 16",
key: "3uifl3"
}],
["path", {
d: "M8 16H3v5",
key: "1cv678"
}]
]
});
var RotateCcwClock = createLucideIcon({
name: "rotate-ccw-clock",
size: 24,
node: [
["path", {
d: "M3 12a9 9 0 1 0 9-9 9.75 9.75 0 0 0-6.74 2.74L3 8",
key: "1357e3"
}],
["path", {
d: "M3 3v5h5",
key: "1xhq8a"
}],
["path", {
d: "M12 7v5l4 2",
key: "1fdv2h"
}]
],
aliases: ["history"]
});
var Search = createLucideIcon({
name: "search",
size: 24,
node: [["path", {
d: "m21 21-4.34-4.34",
key: "14j7rj"
}], ["circle", {
cx: "11",
cy: "11",
r: "8",
key: "4ej97u"
}]]
});
var Settings = createLucideIcon({
name: "settings",
size: 24,
node: [["path", {
d: "M9.671 4.136a2.34 2.34 0 0 1 4.659 0 2.34 2.34 0 0 0 3.319 1.915 2.34 2.34 0 0 1 2.33 4.033 2.34 2.34 0 0 0 0 3.831 2.34 2.34 0 0 1-2.33 4.033 2.34 2.34 0 0 0-3.319 1.915 2.34 2.34 0 0 1-4.659 0 2.34 2.34 0 0 0-3.32-1.915 2.34 2.34 0 0 1-2.33-4.033 2.34 2.34 0 0 0 0-3.831A2.34 2.34 0 0 1 6.35 6.051a2.34 2.34 0 0 0 3.319-1.915",
key: "1i5ecw"
}], ["circle", {
cx: "12",
cy: "12",
r: "3",
key: "1v7zrd"
}]]
});
var Sun = createLucideIcon({
name: "sun",
size: 24,
node: [
["circle", {
cx: "12",
cy: "12",
r: "4",
key: "4exip2"
}],
["path", {
d: "M12 2v2",
key: "tus03m"
}],
["path", {
d: "M12 20v2",
key: "1lh1kg"
}],
["path", {
d: "m4.93 4.93 1.41 1.41",
key: "149t6j"
}],
["path", {
d: "m17.66 17.66 1.41 1.41",
key: "ptbguv"
}],
["path", {
d: "M2 12h2",
key: "1t8f8n"
}],
["path", {
d: "M20 12h2",
key: "1q8mjw"
}],
["path", {
d: "m6.34 17.66-1.41 1.41",
key: "1m8zz5"
}],
["path", {
d: "m19.07 4.93-1.41 1.41",
key: "1shlcs"
}]
]
});
var Tag = createLucideIcon({
name: "tag",
size: 24,
node: [["path", {
d: "M12.586 2.586A2 2 0 0 0 11.172 2H4a2 2 0 0 0-2 2v7.172a2 2 0 0 0 .586 1.414l8.704 8.704a2.426 2.426 0 0 0 3.42 0l6.58-6.58a2.426 2.426 0 0 0 0-3.42z",
key: "vktsd0"
}], ["circle", {
cx: "7.5",
cy: "7.5",
r: ".5",
fill: "currentColor",
key: "kqv944"
}]]
});
var Tags = createLucideIcon({
name: "tags",
size: 24,
node: [
["path", {
d: "M13.172 2a2 2 0 0 1 1.414.586l6.71 6.71a2.4 2.4 0 0 1 0 3.408l-4.592 4.592a2.4 2.4 0 0 1-3.408 0l-6.71-6.71A2 2 0 0 1 6 9.172V3a1 1 0 0 1 1-1z",
key: "16rjxf"
}],
["path", {
d: "M2 7v6.172a2 2 0 0 0 .586 1.414l6.71 6.71a2.4 2.4 0 0 0 3.191.193",
key: "178nd4"
}],
["circle", {
cx: "10.5",
cy: "6.5",
r: ".5",
fill: "currentColor",
key: "12ikhr"
}]
]
});
var Trash = createLucideIcon({
name: "trash",
size: 24,
node: [
["path", {
d: "M10 11v6",
key: "nco0om"
}],
["path", {
d: "M14 11v6",
key: "outv1u"
}],
["path", {
d: "M19 6v14a2 2 0 0 1-2 2H7a2 2 0 0 1-2-2V6",
key: "miytrc"
}],
["path", {
d: "M3 6h18",
key: "d0wm0j"
}],
["path", {
d: "M8 6V4a2 2 0 0 1 2-2h4a2 2 0 0 1 2 2v2",
key: "e791ji"
}]
],
aliases: ["trash-2"]
});
var Upload = createLucideIcon({
name: "upload",
size: 24,
node: [
["path", {
d: "M12 3v12",
key: "1x0j5s"
}],
["path", {
d: "m17 8-5-5-5 5",
key: "7q97r8"
}],
["path", {
d: "M21 15v4a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2v-4",
key: "ih7n3h"
}]
]
});
var X = createLucideIcon({
name: "x",
size: 24,
node: [["path", {
d: "M18 6 6 18",
key: "1bl5f8"
}], ["path", {
d: "m6 6 12 12",
key: "d8bk6v"
}]]
});
var useReadingLibraryStore = defineStore("reading-library", () => {
const library = shallowRef({
history: [],
later: []
});
const loadingLibrary = shallowRef(false);
const savingLibrary = shallowRef(false);
const libraryError = shallowRef("");
const bookmarksBusy = computed(() => loadingLibrary.value || savingLibrary.value);
const historyByGalleryHref = computed(() => new Map(library.value.history.map((entry) => [entry.gallery.href, entry])));
const savedGalleryUrls = computed(() => new Set(library.value.later.map((entry) => entry.gallery.href)));
let repository;
let unsubscribe;
let queue = Promise.resolve();
function initialize(source) {
if (repository) return;
repository = source;
unsubscribe = source.subscribe?.(() => {
enqueue(() => source.read(), "无法读取浏览器中的阅读记录。");
});
readLibrary();
}
function enqueue(read, error) {
const result = queue.then(async () => {
try {
library.value = await read();
return true;
} catch {
libraryError.value = error;
return false;
}
});
queue = result.then(() => void 0);
return result;
}
async function readLibrary() {
const source = repository;
if (!source || loadingLibrary.value) return;
loadingLibrary.value = true;
libraryError.value = "";
try {
await enqueue(() => source.read(), "无法读取浏览器中的阅读记录。");
} finally {
loadingLibrary.value = false;
}
}
async function changeLibrary(change) {
const source = repository;
if (!source) return false;
if (change.type === "visit") return enqueue(() => source.apply(change), "无法保存浏览历史。");
if (savingLibrary.value) return false;
savingLibrary.value = true;
libraryError.value = "";
try {
return await enqueue(() => source.apply(change), "无法保存阅读记录,请检查浏览器存储后重试。");
} finally {
savingLibrary.value = false;
}
}
onScopeDispose(() => {
unsubscribe?.();
unsubscribe = void 0;
repository = void 0;
});
return {
library,
libraryError,
loadingLibrary,
savingLibrary,
bookmarksBusy,
historyByGalleryHref,
savedGalleryUrls,
initialize,
readLibrary,
changeLibrary
};
});
var useTagDirectoryStore = defineStore("tag-directory", () => {
const directory = shallowRef();
const loading = shallowRef(false);
const failed = shallowRef(false);
async function load(adapter) {
if (!adapter.loadTagDirectory || directory.value || loading.value) return;
loading.value = true;
failed.value = false;
try {
directory.value = await adapter.loadTagDirectory();
} catch {
failed.value = true;
} finally {
loading.value = false;
}
}
return {
directory,
loading,
failed,
load,
translate: computed(() => directory.value?.translate)
};
});
var librarySections = {
history: "浏览历史",
later: "稍后阅读"
};
function libraryUrl(home, section) {
const url = new URL(home, location.href);
url.hash = "better-eh-" + section;
return url.href;
}
function libraryPage(url, home) {
for (const section of ["history", "later"]) if (url === libraryUrl(home, section)) return {
kind: "library",
section,
title: librarySections[section]
};
}
var ActionButton_default = defineComponent({
__name: "ActionButton",
props: {
href: {},
variant: {}
},
setup(__props) {
return (_ctx, _cache) => {
return openBlock(), createBlock(resolveDynamicComponent(__props.href ? "a" : "button"), {
href: __props.href,
type: __props.href ? void 0 : "button",
class: normalizeClass(["pill action-button", __props.variant && __props.variant !== "secondary" ? "action-button-" + __props.variant : void 0])
}, {
default: withCtx(() => [renderSlot(_ctx.$slots, "default")]),
_: 3
}, 8, [
"href",
"type",
"class"
]);
};
}
});
var _hoisted_1$33 = [
"aria-busy",
"aria-labelledby",
"aria-describedby"
];
var _hoisted_2$24 = { class: "confirmation-content p-5 wrap-anywhere" };
var _hoisted_3$17 = ["id"];
var _hoisted_4$14 = ["id"];
var _hoisted_5$12 = {
key: 0,
role: "alert"
};
var _hoisted_6$11 = { class: "confirmation-actions mt-[18px] flex flex-wrap justify-end gap-2" };
var ConfirmationDialog_default = defineComponent({
__name: "ConfirmationDialog",
props: {
title: {},
message: {},
confirmLabel: {},
busy: { type: Boolean },
error: {}
},
emits: ["confirm", "cancel"],
setup(__props, { emit: __emit }) {
const emit = __emit;
const dialog = useTemplateRef("dialog");
const id = useId();
onMounted(() => dialog.value?.showModal());
onBeforeUnmount(() => dialog.value?.close());
return (_ctx, _cache) => {
return openBlock(), createElementBlock("dialog", {
ref_key: "dialog",
ref: dialog,
class: "confirmation-dialog",
role: "alertdialog",
"aria-busy": __props.busy,
"aria-labelledby": unref(id) + "-title",
"aria-describedby": unref(id) + "-message",
onCancel: _cache[2] || (_cache[2] = withModifiers(($event) => !__props.busy && emit("cancel"), ["prevent"])),
onClick: _cache[3] || (_cache[3] = withModifiers(($event) => !__props.busy && emit("cancel"), ["self"])),
onTouchmove: _cache[4] || (_cache[4] = withModifiers(() => {}, ["self", "prevent"])),
onWheel: _cache[5] || (_cache[5] = withModifiers(() => {}, ["self", "prevent"]))
}, [createBaseVNode("div", _hoisted_2$24, [
createBaseVNode("h2", { id: unref(id) + "-title" }, toDisplayString(__props.title), 9, _hoisted_3$17),
createBaseVNode("p", { id: unref(id) + "-message" }, toDisplayString(__props.message), 9, _hoisted_4$14),
__props.error ? (openBlock(), createElementBlock("p", _hoisted_5$12, toDisplayString(__props.error), 1)) : createCommentVNode("", true),
createBaseVNode("div", _hoisted_6$11, [createVNode(ActionButton_default, {
autofocus: "",
disabled: __props.busy,
onClick: _cache[0] || (_cache[0] = ($event) => emit("cancel"))
}, {
default: withCtx(() => [..._cache[6] || (_cache[6] = [createTextVNode("取消", -1)])]),
_: 1
}, 8, ["disabled"]), createVNode(ActionButton_default, {
variant: "danger",
disabled: __props.busy,
onClick: _cache[1] || (_cache[1] = ($event) => emit("confirm"))
}, {
default: withCtx(() => [createTextVNode(toDisplayString(__props.confirmLabel), 1)]),
_: 1
}, 8, ["disabled"])])
])], 40, _hoisted_1$33);
};
}
});
var _hoisted_1$32 = ["aria-labelledby"];
var _hoisted_2$23 = { class: "card-action-sheet-panel" };
var _hoisted_3$16 = { class: "card-action-sheet-header" };
var _hoisted_4$13 = ["id"];
var _hoisted_5$11 = ["disabled"];
var GalleryActionSheet_default = defineComponent({
__name: "GalleryActionSheet",
props: {
title: {},
busy: { type: Boolean },
removalSection: {}
},
emits: ["close", "submit"],
setup(__props, { expose: __expose, emit: __emit }) {
const emit = __emit;
const dialog = useTemplateRef("dialog");
const titleId = useId();
onMounted(() => dialog.value?.showModal());
__expose({ closeDialog: () => dialog.value?.close() });
return (_ctx, _cache) => {
return openBlock(), createElementBlock("dialog", {
ref_key: "dialog",
ref: dialog,
class: "card-action-sheet",
"aria-labelledby": unref(titleId),
onCancel: _cache[2] || (_cache[2] = withModifiers(($event) => emit("close"), ["prevent"])),
onClick: _cache[3] || (_cache[3] = withModifiers(($event) => emit("close"), ["self"])),
onTouchmove: _cache[4] || (_cache[4] = withModifiers(() => {}, ["self", "prevent"])),
onWheel: _cache[5] || (_cache[5] = withModifiers(() => {}, ["self", "prevent"]))
}, [createBaseVNode("div", _hoisted_2$23, [createBaseVNode("header", _hoisted_3$16, [createBaseVNode("h2", { id: unref(titleId) }, toDisplayString(__props.title), 9, _hoisted_4$13), createBaseVNode("button", {
class: "icon-button",
type: "button",
"aria-label": "关闭画廊操作",
onClick: _cache[0] || (_cache[0] = ($event) => emit("close"))
}, [createVNode(unref(X), {
size: 20,
"aria-hidden": "true"
})])]), createBaseVNode("button", {
class: normalizeClass(["card-action-sheet-button", { "action-button-danger-subtle": __props.removalSection }]),
type: "button",
autofocus: "",
disabled: __props.busy,
onClick: _cache[1] || (_cache[1] = ($event) => emit("submit", $event))
}, [__props.removalSection ? (openBlock(), createBlock(unref(Trash), {
key: 0,
size: 19,
"aria-hidden": "true"
})) : (openBlock(), createBlock(unref(Bookmark), {
key: 1,
size: 19,
"aria-hidden": "true"
})), createTextVNode(" " + toDisplayString(__props.removalSection ? `从${unref(librarySections)[__props.removalSection]}移除` : "添加到稍后阅读"), 1)], 10, _hoisted_5$11)])], 40, _hoisted_1$32);
};
}
});
var _hoisted_1$31 = { id: "gallery-tag-search-label" };
var TagSearchPopover_default = defineComponent({
__name: "TagSearchPopover",
props: {
anchor: {},
label: {},
href: {},
inSearch: { type: Boolean }
},
emits: [
"toggle",
"search",
"dismiss"
],
setup(__props, { emit: __emit }) {
const props = __props;
const emit = __emit;
const panel = useTemplateRef("panel");
const toggleButton = useTemplateRef("toggleButton");
function place() {
const popup = panel.value;
if (!popup) return false;
const anchor = props.anchor.getBoundingClientRect();
const header = props.anchor.closest(".eh-app")?.querySelector(".masthead");
const { width, height } = popup.getBoundingClientRect();
const gutter = 12;
const gap = 8;
const topEdge = Math.max(gutter, header?.getBoundingClientRect().bottom ?? 0);
const bottomEdge = window.innerHeight - gutter;
if (!props.anchor.isConnected || anchor.bottom <= topEdge || anchor.top >= bottomEdge) {
emit("dismiss", false);
return false;
}
const below = anchor.bottom + gap;
const above = anchor.top - gap - height;
const top = below + height <= bottomEdge ? below : above;
popup.style.left = Math.max(gutter, Math.min(anchor.left, window.innerWidth - width - gutter)) + "px";
popup.style.top = Math.max(topEdge, Math.min(top, bottomEdge - height)) + "px";
return true;
}
function onFocusout(event) {
if (event.relatedTarget instanceof Node && !panel.value?.contains(event.relatedTarget)) emit("dismiss", false);
}
onMounted(() => {
if (place()) toggleButton.value?.focus({ preventScroll: true });
});
onClickOutside(panel, () => emit("dismiss", false), { ignore: [toRef$1(props, "anchor")] });
useEventListener$1(() => props.anchor.closest(".eh-app"), "scroll", place, { passive: true });
useEventListener$1(window, "resize", place);
useResizeObserver(panel, place);
return (_ctx, _cache) => {
return openBlock(), createElementBlock("div", {
id: "gallery-tag-search",
ref_key: "panel",
ref: panel,
class: "tag-search-popover",
role: "dialog",
"aria-labelledby": "gallery-tag-search-label",
onKeydown: _cache[3] || (_cache[3] = withKeys(withModifiers(($event) => emit("dismiss", true), ["stop", "prevent"]), ["esc"])),
onFocusout
}, [createBaseVNode("p", _hoisted_1$31, toDisplayString(__props.label), 1), createBaseVNode("div", {
class: "tag-search-popover-actions flex flex-wrap gap-2",
onMousedown: _cache[2] || (_cache[2] = withModifiers(() => {}, ["prevent"]))
}, [createBaseVNode("button", {
ref_key: "toggleButton",
ref: toggleButton,
class: normalizeClass(["pill action-button", { "action-button-danger-subtle": __props.inSearch }]),
type: "button",
onClick: _cache[0] || (_cache[0] = ($event) => emit("toggle"))
}, toDisplayString(__props.inSearch ? "从搜索框移除" : "添加到搜索框"), 3), createVNode(ActionButton_default, {
variant: "primary",
href: __props.href,
onClick: _cache[1] || (_cache[1] = ($event) => emit("search", $event))
}, {
default: withCtx(() => [..._cache[4] || (_cache[4] = [createTextVNode("直接搜索", -1)])]),
_: 1
}, 8, ["href"])], 32)], 544);
};
}
});
var _hoisted_1$30 = { role: "status" };
var _hoisted_2$22 = ["href"];
var AppGalleryOverlays_default = defineComponent({
__name: "AppGalleryOverlays",
props: {
gallerySearch: {},
library: {},
home: {}
},
emits: ["navigate"],
setup(__props, { emit: __emit }) {
const props = __props;
const emit = __emit;
const { tagSearch, tagInSearch, toggleTagInSearch, runTagSearch, dismissTagSearch } = props.gallerySearch;
const { cardActionSheet, cardRemovalSection, closeCardActionSheet, restoreCardActionFocus, submitCardAction, removalDialog, removalFailed, closeRemoval, confirmRemoval, libraryNotice, stopLibraryNotice, startLibraryNotice } = props.library;
const { libraryError, savingLibrary, bookmarksBusy } = storeToRefs(useReadingLibraryStore());
const tags = useTagDirectoryStore();
return (_ctx, _cache) => {
return openBlock(), createElementBlock(Fragment, null, [
unref(tagSearch) ? (openBlock(), createBlock(TagSearchPopover_default, {
key: unref(tagSearch).href,
anchor: unref(tagSearch).trigger,
label: unref(tagSearch).tag.key && unref(tags).translate?.(unref(tagSearch).tag.key) || unref(tagSearch).tag.label,
href: unref(tagSearch).href,
"in-search": unref(tagInSearch),
onToggle: unref(toggleTagInSearch),
onSearch: unref(runTagSearch),
onDismiss: unref(dismissTagSearch)
}, null, 8, [
"anchor",
"label",
"href",
"in-search",
"onToggle",
"onSearch",
"onDismiss"
])) : createCommentVNode("", true),
createVNode(Transition, {
name: "card-action-sheet",
onAfterLeave: unref(restoreCardActionFocus)
}, {
default: withCtx(() => [unref(cardActionSheet) ? (openBlock(), createBlock(GalleryActionSheet_default, {
key: 0,
ref: __props.library.cardActionDialog,
title: unref(cardActionSheet).gallery.title,
busy: unref(bookmarksBusy),
"removal-section": unref(cardRemovalSection),
onClose: unref(closeCardActionSheet),
onSubmit: unref(submitCardAction)
}, null, 8, [
"title",
"busy",
"removal-section",
"onClose",
"onSubmit"
])) : createCommentVNode("", true)]),
_: 1
}, 8, ["onAfterLeave"]),
unref(removalDialog) ? (openBlock(), createBlock(ConfirmationDialog_default, mergeProps({ key: 1 }, unref(removalDialog), {
busy: unref(savingLibrary),
error: unref(removalFailed) ? unref(libraryError) : "",
onConfirm: unref(confirmRemoval),
onCancel: unref(closeRemoval)
}), null, 16, [
"busy",
"error",
"onConfirm",
"onCancel"
])) : createCommentVNode("", true),
createBaseVNode("span", {
ref: __props.gallerySearch.tagFlightElement,
class: "icon-flight",
"aria-hidden": "true"
}, [createVNode(unref(Tag), { size: 17 })], 512),
createBaseVNode("span", {
ref: __props.library.bookmarkFlightElement,
class: "icon-flight",
"aria-hidden": "true"
}, [createVNode(unref(Bookmark), { size: 17 })], 512),
createVNode(Transition, { name: "bookmark-notice" }, {
default: withCtx(() => [unref(libraryNotice) ? (openBlock(), createElementBlock("div", {
key: 0,
class: "bookmark-notice",
onFocusin: _cache[1] || (_cache[1] = (...args) => unref(stopLibraryNotice) && unref(stopLibraryNotice)(...args)),
onFocusout: _cache[2] || (_cache[2] = (...args) => unref(startLibraryNotice) && unref(startLibraryNotice)(...args))
}, [createBaseVNode("p", _hoisted_1$30, [!unref(libraryNotice).failed ? (openBlock(), createBlock(unref(Check), {
key: 0,
size: 18,
"aria-hidden": "true"
})) : createCommentVNode("", true), createTextVNode(" " + toDisplayString(unref(libraryNotice).text), 1)]), unref(libraryNotice).saved ? (openBlock(), createElementBlock("a", {
key: 0,
ref: __props.library.bookmarkNoticeDestination,
href: unref(libraryUrl)(__props.home, "later"),
onClick: _cache[0] || (_cache[0] = ($event) => emit("navigate", $event, unref(libraryUrl)(__props.home, "later")))
}, " 去看看 ", 8, _hoisted_2$22)) : createCommentVNode("", true)], 32)) : createCommentVNode("", true)]),
_: 1
})
], 64);
};
}
});
function isPrimaryClick(event) {
return event.button === 0 && !event.ctrlKey && !event.metaKey && !event.shiftKey && !event.altKey;
}
var themeStorageKey = "better-eh-theme";
var usePreferencesStore = defineStore("preferences", () => {
const theme = useLocalStorage(themeStorageKey, usePreferredDark().value ? "dark" : "light");
const layout = useLocalStorage("better-eh-layout", "grid");
const desktopReaderFit = useLocalStorage("better-eh-reader-fit", "screen");
const narrowReaderFit = useLocalStorage("better-eh-reader-fit-narrow", "width");
const desktopNavigation = useMediaQuery("(min-width: 960px)");
const readerFit = computed(() => desktopNavigation.value ? desktopReaderFit.value : narrowReaderFit.value);
function toggleTheme() {
theme.value = theme.value === "dark" ? "light" : "dark";
}
function toggleReaderFit() {
const preference = desktopNavigation.value ? desktopReaderFit : narrowReaderFit;
preference.value = preference.value === "screen" ? "width" : "screen";
}
return {
theme,
layout,
desktopReaderFit,
narrowReaderFit,
desktopNavigation,
readerFit,
toggleTheme,
toggleReaderFit
};
});
var _hoisted_1$29 = [
"aria-label",
"aria-pressed",
"aria-haspopup",
"aria-disabled",
"disabled"
];
var _hoisted_2$21 = {
class: "card-hover-action-label",
"aria-hidden": "true"
};
var GalleryCardAction_default = defineComponent({
__name: "GalleryCardAction",
props: {
label: {},
title: {},
busy: { type: Boolean },
destructive: { type: Boolean },
pressed: {
type: Boolean,
default: void 0
}
},
setup(__props) {
return (_ctx, _cache) => {
return openBlock(), createElementBlock("button", {
class: normalizeClass(["card-hover-action", { "action-button-danger-subtle": __props.destructive }]),
type: "button",
"aria-label": __props.label + ":" + __props.title,
"aria-pressed": __props.pressed,
"aria-haspopup": __props.destructive ? "dialog" : void 0,
"aria-disabled": __props.pressed !== void 0 ? __props.busy : void 0,
disabled: __props.pressed === void 0 && __props.busy
}, [__props.destructive ? (openBlock(), createBlock(unref(Trash), {
key: 0,
size: 18,
"aria-hidden": "true"
})) : (openBlock(), createBlock(unref(Bookmark), {
key: 1,
size: 18,
"aria-hidden": "true"
})), createBaseVNode("span", _hoisted_2$21, [renderSlot(_ctx.$slots, "default", {}, () => [createTextVNode(toDisplayString(__props.label), 1)])])], 10, _hoisted_1$29);
};
}
});
var _hoisted_1$28 = [
"aria-label",
"title",
"aria-pressed",
"aria-haspopup",
"disabled"
];
var BookmarkButton_default = defineComponent({
__name: "BookmarkButton",
props: {
saved: { type: Boolean },
busy: { type: Boolean },
compact: { type: Boolean },
catalogTitle: {}
},
emits: ["toggle"],
setup(__props, { emit: __emit }) {
const emit = __emit;
return (_ctx, _cache) => {
return __props.catalogTitle !== void 0 ? (openBlock(), createBlock(GalleryCardAction_default, {
key: 0,
title: __props.catalogTitle,
label: __props.saved ? "从稍后阅读移除" : "稍后阅读",
pressed: __props.saved,
destructive: __props.saved,
busy: __props.busy,
onClick: _cache[0] || (_cache[0] = ($event) => emit("toggle", $event))
}, {
default: withCtx(() => [createTextVNode(toDisplayString(__props.saved ? "从稍后阅读移除" : "添加到稍后阅读"), 1)]),
_: 1
}, 8, [
"title",
"label",
"pressed",
"destructive",
"busy"
])) : __props.compact ? (openBlock(), createElementBlock("button", {
key: 1,
type: "button",
class: normalizeClass(["icon-button", { "action-button-danger-subtle": __props.saved }]),
"aria-label": __props.saved ? "从稍后阅读移除" : "稍后阅读",
title: __props.saved ? "从稍后阅读移除" : "稍后阅读",
"aria-pressed": __props.saved,
"aria-haspopup": __props.saved ? "dialog" : void 0,
disabled: __props.busy,
onClick: _cache[1] || (_cache[1] = ($event) => emit("toggle", $event))
}, [createVNode(unref(Bookmark), {
size: 18,
"aria-hidden": "true"
})], 10, _hoisted_1$28)) : (openBlock(), createBlock(ActionButton_default, {
key: 2,
variant: __props.saved ? "danger-subtle" : "secondary",
"aria-pressed": __props.saved,
"aria-haspopup": __props.saved ? "dialog" : void 0,
disabled: __props.busy,
onClick: _cache[2] || (_cache[2] = ($event) => emit("toggle", $event))
}, {
default: withCtx(() => [createVNode(unref(Bookmark), {
size: 17,
"aria-hidden": "true"
}), createTextVNode(" " + toDisplayString(__props.saved ? "从稍后阅读移除" : "稍后阅读"), 1)]),
_: 1
}, 8, [
"variant",
"aria-pressed",
"aria-haspopup",
"disabled"
]));
};
}
});
var _hoisted_1$27 = {
class: "relative align-middle text-[0]",
"aria-live": "polite",
"aria-busy": "true"
};
var LoadingSpinner_default = defineComponent({
__name: "LoadingSpinner",
props: { size: {} },
setup(__props) {
return (_ctx, _cache) => {
return openBlock(), createElementBlock("div", _hoisted_1$27, [(openBlock(), createElementBlock("svg", {
class: "relative inline-block max-h-full max-w-full align-middle",
style: normalizeStyle({
width: __props.size + "px",
height: __props.size + "px"
}),
viewBox: "25 25 50 50",
"aria-hidden": "true"
}, [..._cache[0] || (_cache[0] = [createBaseVNode("circle", {
cx: "50",
cy: "50",
r: "20",
fill: "none",
stroke: "currentColor",
"stroke-width": "3",
"stroke-linecap": "round",
class: "[stroke-dasharray:28_126] motion-safe:animate-loading-spinner"
}, null, -1)])], 4))]);
};
}
});
var _hoisted_1$26 = {
id: "better-eh-masthead",
class: "masthead"
};
var _hoisted_2$20 = ["inert"];
var _hoisted_3$15 = { class: "header-brand" };
var _hoisted_4$12 = ["aria-expanded"];
var _hoisted_5$10 = ["href"];
var _hoisted_6$10 = { class: "brand-symbol" };
var _hoisted_7$10 = { key: 0 };
var _hoisted_8$9 = [
"href",
"aria-label",
"title"
];
var _hoisted_9$9 = ["aria-controls", "aria-expanded"];
var _hoisted_10$9 = ["title"];
var _hoisted_11$9 = ["aria-controls", "aria-expanded"];
var _hoisted_12$8 = { class: "header-actions flex items-center gap-2" };
var _hoisted_13$8 = { class: "header-tools flex items-center" };
var _hoisted_14$8 = ["disabled"];
var _hoisted_15$5 = ["aria-label"];
var _hoisted_16$5 = ["href", "aria-disabled"];
var _hoisted_17$5 = {
key: 0,
class: "shell reader-controls"
};
var _hoisted_18$4 = { class: "reading-actions" };
var _hoisted_19$3 = {
key: 1,
class: "progress-bar",
role: "progressbar",
"aria-label": "正在加载页面"
};
var AppHeader_default = defineComponent({
__name: "AppHeader",
props: {
home: {},
back: {},
hasNavigation: { type: Boolean },
menuOpen: { type: Boolean },
compactSearch: { type: Boolean },
searchOpen: { type: Boolean },
search: {},
wideReader: { type: Boolean },
smallReaderHeader: { type: Boolean },
isReader: { type: Boolean },
readerTitle: {},
busy: { type: Boolean },
refreshBlocked: { type: Boolean },
refreshingContent: { type: Boolean },
nativeHref: {},
openingNative: { type: Boolean },
canBookmark: { type: Boolean },
savedForLater: { type: Boolean },
bookmarksBusy: { type: Boolean }
},
emits: [
"navigate",
"goBack",
"openSiteMenu",
"openSearch",
"refresh",
"toggleBookmark"
],
setup(__props, { expose: __expose, emit: __emit }) {
const emit = __emit;
const preferences = usePreferencesStore();
const { theme, readerFit } = storeToRefs(preferences);
const searchToggle = useTemplateRef("searchToggle");
const brand = useTemplateRef("brand");
const readerActionsTarget = useTemplateRef("readerActionsTarget");
const readerToolsTarget = useTemplateRef("readerToolsTarget");
__expose({
searchIcon: () => searchToggle.value?.querySelector("svg") ?? void 0,
focusSearchToggle: () => searchToggle.value?.focus({ preventScroll: true }),
focusNavigation: () => (searchToggle.value ?? brand.value)?.focus({ preventScroll: true })
});
return (_ctx, _cache) => {
return openBlock(), createElementBlock("header", _hoisted_1$26, [
createBaseVNode("div", {
class: normalizeClass(["shell header-inner", {
"header-with-back": __props.back,
"header-compact-search": __props.compactSearch,
"reader-header": __props.wideReader,
invisible: !__props.compactSearch && __props.searchOpen
}]),
inert: !__props.compactSearch && __props.searchOpen
}, [
createBaseVNode("div", _hoisted_3$15, [
__props.hasNavigation ? (openBlock(), createElementBlock("button", {
key: 0,
class: "icon-button site-nav-toggle",
type: "button",
"aria-label": "打开站点导航",
"aria-haspopup": "dialog",
"aria-controls": "better-eh-site-menu",
"aria-expanded": __props.menuOpen,
onClick: _cache[0] || (_cache[0] = ($event) => emit("openSiteMenu"))
}, [createVNode(unref(Menu), {
size: 21,
"aria-hidden": "true"
})], 8, _hoisted_4$12)) : createCommentVNode("", true),
createBaseVNode("a", {
ref_key: "brand",
ref: brand,
class: "brand",
href: __props.home,
"aria-label": "Better EH 首页",
onClick: _cache[1] || (_cache[1] = ($event) => emit("navigate", $event, __props.home))
}, [createBaseVNode("span", _hoisted_6$10, [createVNode(unref(LibraryBig), { size: 19 })]), !__props.isReader ? (openBlock(), createElementBlock("strong", _hoisted_7$10, "Better EH")) : createCommentVNode("", true)], 8, _hoisted_5$10),
__props.back ? (openBlock(), createElementBlock("a", {
key: 1,
class: "icon-button header-back",
href: __props.back.href,
"aria-label": __props.back.label,
title: __props.back.label,
onClick: _cache[2] || (_cache[2] = ($event) => emit("goBack", $event))
}, [createVNode(unref(ArrowLeft), {
size: 21,
"aria-hidden": "true"
})], 8, _hoisted_8$9)) : createCommentVNode("", true),
__props.compactSearch && (__props.isReader || __props.back) ? (openBlock(), createElementBlock("button", {
key: 2,
ref_key: "searchToggle",
ref: searchToggle,
class: "icon-button",
type: "button",
"aria-label": "搜索画廊或标签",
title: "搜索画廊或标签",
"aria-haspopup": "dialog",
"aria-controls": __props.searchOpen ? "better-eh-gallery-search" : void 0,
"aria-expanded": __props.searchOpen,
onClick: _cache[3] || (_cache[3] = ($event) => emit("openSearch"))
}, [createVNode(unref(Search), {
size: 20,
"aria-hidden": "true"
})], 8, _hoisted_9$9)) : createCommentVNode("", true),
__props.isReader ? (openBlock(), createElementBlock("p", {
key: 3,
class: "reader-header-title",
title: __props.readerTitle
}, toDisplayString(__props.readerTitle), 9, _hoisted_10$9)) : createCommentVNode("", true)
]),
!__props.compactSearch || !__props.isReader && !__props.back ? (openBlock(), createElementBlock("button", {
key: 0,
ref_key: "searchToggle",
ref: searchToggle,
class: "search-form flex min-h-11 w-full items-center gap-2.5 rounded-xl text-left",
type: "button",
"aria-label": "搜索画廊或标签",
"aria-haspopup": "dialog",
"aria-controls": __props.searchOpen ? "better-eh-gallery-search" : void 0,
"aria-expanded": __props.searchOpen,
onClick: _cache[4] || (_cache[4] = ($event) => emit("openSearch"))
}, [createVNode(unref(Search), {
size: 18,
class: "shrink-0 text-muted",
"aria-hidden": "true"
}), createBaseVNode("span", { class: normalizeClass(["truncate", { "text-muted": !__props.search }]) }, toDisplayString(__props.search || "搜索画廊或标签"), 3)], 8, _hoisted_11$9)) : createCommentVNode("", true),
createBaseVNode("div", _hoisted_12$8, [__props.isReader ? withDirectives((openBlock(), createElementBlock("div", {
key: 0,
ref_key: "readerActionsTarget",
ref: readerActionsTarget,
class: "reader-header-actions"
}, null, 512)), [[vShow, __props.wideReader]]) : createCommentVNode("", true), (openBlock(), createBlock(Teleport, {
to: readerToolsTarget.value,
disabled: !__props.isReader || !__props.smallReaderHeader || !readerToolsTarget.value
}, [createBaseVNode("div", _hoisted_13$8, [
createBaseVNode("button", {
class: "icon-button",
type: "button",
"aria-label": "刷新页面",
title: "刷新页面",
disabled: __props.refreshBlocked,
onClick: _cache[5] || (_cache[5] = ($event) => emit("refresh"))
}, [__props.refreshingContent ? (openBlock(), createBlock(LoadingSpinner_default, {
key: 0,
size: 18,
"aria-hidden": "true"
})) : (openBlock(), createBlock(unref(RefreshCw), {
key: 1,
size: 18,
"aria-hidden": "true"
}))], 8, _hoisted_14$8),
createBaseVNode("button", {
class: "icon-button theme-button",
type: "button",
"aria-label": unref(theme) === "dark" ? "切换白色主题" : "切换黑色主题",
onClick: _cache[6] || (_cache[6] = (...args) => unref(preferences).toggleTheme && unref(preferences).toggleTheme(...args))
}, [unref(theme) !== "dark" ? (openBlock(), createBlock(unref(Moon), {
key: 0,
size: 19
})) : (openBlock(), createBlock(unref(Sun), {
key: 1,
size: 19
}))], 8, _hoisted_15$5),
__props.nativeHref ? (openBlock(), createElementBlock("a", {
key: 0,
class: "icon-button native-button",
href: __props.nativeHref,
"aria-disabled": __props.openingNative || void 0,
"aria-label": "打开原站",
title: "打开原站"
}, [__props.openingNative ? (openBlock(), createBlock(LoadingSpinner_default, {
key: 0,
size: 18,
"aria-hidden": "true"
})) : (openBlock(), createBlock(unref(ExternalLink), {
key: 1,
size: 18,
"aria-hidden": "true"
}))], 8, _hoisted_16$5)) : createCommentVNode("", true)
])], 8, ["to", "disabled"]))])
], 10, _hoisted_2$20),
renderSlot(_ctx.$slots, "default"),
__props.isReader ? withDirectives((openBlock(), createElementBlock("div", _hoisted_17$5, [withDirectives(createBaseVNode("div", {
ref_key: "readerToolsTarget",
ref: readerToolsTarget,
class: "reader-controls-tools"
}, null, 512), [[vShow, __props.smallReaderHeader]]), (openBlock(), createBlock(Teleport, {
to: readerActionsTarget.value,
disabled: !__props.wideReader || !readerActionsTarget.value
}, [createBaseVNode("div", _hoisted_18$4, [__props.canBookmark ? (openBlock(), createBlock(BookmarkButton_default, {
key: 0,
compact: "",
saved: __props.savedForLater,
busy: __props.bookmarksBusy,
onToggle: _cache[7] || (_cache[7] = ($event) => emit("toggleBookmark", $event))
}, null, 8, ["saved", "busy"])) : createCommentVNode("", true), createBaseVNode("button", {
class: "pill library-action",
type: "button",
onClick: _cache[8] || (_cache[8] = (...args) => unref(preferences).toggleReaderFit && unref(preferences).toggleReaderFit(...args))
}, toDisplayString(unref(readerFit) === "screen" ? "适应宽度" : "适应屏幕"), 1)])], 8, ["to", "disabled"]))], 512)), [[vShow, !__props.wideReader]]) : createCommentVNode("", true),
__props.busy ? (openBlock(), createElementBlock("div", _hoisted_19$3)) : createCommentVNode("", true)
]);
};
}
});
var historyLimit$1 = 8;
var storageKey$1 = "better-eh-search-history";
var useSearchHistoryStore = defineStore("search-history", () => {
const stored = useLocalStorage(storageKey$1, [], {
serializer: {
read: JSON.parse,
write: JSON.stringify
},
writeDefaults: false,
flush: "sync"
});
const recent = computed(() => {
if (!Array.isArray(stored.value)) return [];
const terms = stored.value.flatMap((query) => typeof query === "string" && query.trim() ? [query.trim()] : []);
return [...new Set(terms)].slice(0, historyLimit$1);
});
function remember(query) {
const term = query.trim();
if (term) stored.value = [term, ...recent.value.filter((item) => item !== term)].slice(0, historyLimit$1);
}
function clear() {
stored.value = [];
}
return {
recent,
remember,
clear
};
});
var _hoisted_1$25 = { class: "search-editor-row flex items-center gap-2" };
var _hoisted_2$19 = { class: "search-box flex flex-1 items-center" };
var _hoisted_3$14 = [
"placeholder",
"aria-expanded",
"aria-controls",
"aria-activedescendant"
];
var _hoisted_4$11 = ["disabled"];
var _hoisted_5$9 = {
key: 0,
class: "tag-suggestions"
};
var _hoisted_6$9 = { class: "flex items-center justify-between gap-2 px-2.5 text-xs text-muted" };
var _hoisted_7$9 = ["id"];
var _hoisted_8$8 = [
"id",
"aria-selected",
"onClick"
];
var _hoisted_9$8 = { class: "flex items-center gap-2.5" };
var _hoisted_10$8 = ["id"];
var _hoisted_11$8 = [
"id",
"aria-selected",
"onClick"
];
var _hoisted_12$7 = {
key: 2,
class: "tag-suggestions tag-suggestion-status"
};
var _hoisted_13$7 = { role: "status" };
var _hoisted_14$7 = {
key: 3,
class: "px-2.5 pt-5 text-muted"
};
var TagSearchBox_default = defineComponent({
__name: "TagSearchBox",
props: mergeModels({
completeTags: { type: Function },
placeholder: {}
}, {
"modelValue": { required: true },
"modelModifiers": {}
}),
emits: mergeModels([
"add",
"load",
"search",
"selectHistory"
], ["update:modelValue"]),
setup(__props, { expose: __expose, emit: __emit }) {
const { directory, loading, failed } = storeToRefs(useTagDirectoryStore());
const searchHistory = useSearchHistoryStore();
const { recent } = storeToRefs(searchHistory);
const props = __props;
const emit = __emit;
const query = useModel(__props, "modelValue");
const control = useTemplateRef("control");
const list = useTemplateRef("list");
const listId = useId();
const focused = shallowRef(false);
const composing = shallowRef(false);
const dismissed = shallowRef(false);
const confirmClearHistory = shallowRef(false);
const caret = shallowRef(0);
const activeIndex = shallowRef(-1);
const remoteOptions = shallowRef([]);
const remotePending = shallowRef(false);
__expose({ focus: () => control.value?.focus({ preventScroll: true }) });
const canSuggest = computed(() => focused.value && !composing.value && !dismissed.value);
const historyOptions = computed(() => !query.value.trim() && !composing.value ? recent.value : []);
const localOptions = computed(() => canSuggest.value && !historyOptions.value.length ? directory.value?.complete(query.value, caret.value) ?? [] : []);
const suggestions = computed(() => {
if (!canSuggest.value || historyOptions.value.length) return [];
if (localOptions.value.length || !props.completeTags) return localOptions.value;
return remoteOptions.value.map((option) => ({
...option,
label: directory.value?.translate(option.key) ?? option.label
}));
});
watch([
query,
caret,
computed(() => canSuggest.value && Boolean(directory.value) && !historyOptions.value.length && !localOptions.value.length)
], ([text, position, enabled], _, onCleanup) => {
remoteOptions.value = [];
const complete = props.completeTags;
if (!complete || !enabled || !text.trim()) return;
const request = new AbortController();
let timeout;
const timer = setTimeout(async () => {
remotePending.value = true;
timeout = setTimeout(() => {
request.abort();
remotePending.value = false;
}, 8e3);
try {
const options = await complete(text, position, request.signal);
if (!request.signal.aborted) remoteOptions.value = options;
} catch {} finally {
clearTimeout(timeout);
if (!request.signal.aborted) remotePending.value = false;
}
}, 200);
onCleanup(() => {
clearTimeout(timer);
clearTimeout(timeout);
remotePending.value = false;
request.abort();
});
});
const optionCount = computed(() => historyOptions.value.length || suggestions.value.length);
const activeId = computed(() => activeIndex.value >= 0 && activeIndex.value < optionCount.value ? listId + "-" + activeIndex.value : void 0);
watch([historyOptions, suggestions], () => {
activeIndex.value = -1;
});
function readCaret() {
caret.value = control.value?.selectionStart ?? query.value.length;
}
function onFocus() {
focused.value = true;
dismissed.value = false;
readCaret();
emit("load");
}
function retryTags() {
control.value?.focus({ preventScroll: true });
emit("load");
}
function onBlur(event) {
if (event.currentTarget instanceof Element && event.relatedTarget instanceof Node) {
if (event.currentTarget.contains(event.relatedTarget)) return;
}
focused.value = false;
}
function reopenOptions() {
dismissed.value = false;
readCaret();
}
function clearSearch() {
query.value = "";
control.value?.focus({ preventScroll: true });
reopenOptions();
}
async function closeClearHistory() {
confirmClearHistory.value = false;
await nextTick();
control.value?.focus({ preventScroll: true });
}
async function clearHistory() {
searchHistory.clear();
await closeClearHistory();
}
function onKeydown(event) {
if (composing.value || event.isComposing) return;
const count = optionCount.value;
const canDismiss = remotePending.value || suggestions.value.length;
if (event.key === "Escape" && canDismiss) {
event.preventDefault();
dismissed.value = true;
} else if (count && (event.key === "ArrowDown" || event.key === "ArrowUp")) {
event.preventDefault();
const step = event.key === "ArrowDown" ? 1 : -1;
const current = activeIndex.value;
activeIndex.value = current < 0 && step < 0 ? count - 1 : (current + step + count) % count;
list.value?.children[activeIndex.value]?.scrollIntoView({ block: "nearest" });
} else if (event.key === "Enter") {
const term = historyOptions.value[activeIndex.value];
if (term) {
event.preventDefault();
emit("selectHistory", term);
return;
}
const option = suggestions.value[activeIndex.value];
if (option) {
event.preventDefault();
emit("add", option.query);
} else if (!query.value.trim()) {
event.preventDefault();
emit("search");
}
}
}
function submit() {
if (!composing.value && query.value.trim()) emit("add", query.value);
}
return (_ctx, _cache) => {
return openBlock(), createElementBlock("form", {
class: "search-form relative min-w-0",
role: "search",
onFocusout: onBlur,
onSubmit: withModifiers(submit, ["prevent"])
}, [
createBaseVNode("div", _hoisted_1$25, [createBaseVNode("div", _hoisted_2$19, [
withDirectives(createBaseVNode("input", {
ref_key: "control",
ref: control,
"onUpdate:modelValue": _cache[0] || (_cache[0] = ($event) => query.value = $event),
type: "search",
role: "combobox",
placeholder: __props.placeholder,
"aria-label": "搜索画廊或标签",
"aria-autocomplete": "list",
"aria-expanded": optionCount.value > 0,
"aria-controls": optionCount.value ? unref(listId) : void 0,
"aria-activedescendant": activeId.value,
autofocus: "",
autocomplete: "off",
enterkeyhint: "enter",
onFocus,
onInput: reopenOptions,
onClick: reopenOptions,
onSelect: readCaret,
onKeyup: readCaret,
onKeydown,
onCompositionstart: _cache[1] || (_cache[1] = ($event) => composing.value = true),
onCompositionend: _cache[2] || (_cache[2] = ($event) => composing.value = false)
}, null, 40, _hoisted_3$14), [[vModelText, query.value]]),
query.value ? (openBlock(), createElementBlock("button", {
key: 0,
type: "button",
class: "icon-button search-clear",
"aria-label": "清除搜索内容",
title: "清除搜索内容",
onClick: clearSearch
}, [createVNode(unref(X), {
size: 16,
"aria-hidden": "true"
})])) : createCommentVNode("", true),
createBaseVNode("button", {
type: "submit",
class: "icon-button",
"aria-label": "添加条件",
title: "添加条件",
disabled: !query.value.trim(),
onMousedown: _cache[3] || (_cache[3] = withModifiers(() => {}, ["prevent"]))
}, [createVNode(unref(Plus), {
size: 20,
"aria-hidden": "true"
})], 40, _hoisted_4$11)
]), renderSlot(_ctx.$slots, "actions")]),
renderSlot(_ctx.$slots, "default"),
historyOptions.value.length ? (openBlock(), createElementBlock("div", _hoisted_5$9, [createBaseVNode("div", _hoisted_6$9, [_cache[9] || (_cache[9] = createBaseVNode("span", null, "最近搜索", -1)), createBaseVNode("button", {
type: "button",
class: "min-h-11 rounded-md px-2 hover:bg-panel",
"aria-haspopup": "dialog",
onMousedown: _cache[4] || (_cache[4] = withModifiers(() => {}, ["prevent"])),
onClick: _cache[5] || (_cache[5] = ($event) => confirmClearHistory.value = true)
}, " 清空历史 ", 32)]), createBaseVNode("ul", {
id: unref(listId),
ref_key: "list",
ref: list,
class: "m-0 list-none p-0",
role: "listbox",
"aria-label": "最近搜索"
}, [(openBlock(true), createElementBlock(Fragment, null, renderList(historyOptions.value, (term, index) => {
return openBlock(), createElementBlock("li", {
id: unref(listId) + "-" + index,
key: term,
role: "option",
"aria-selected": index === activeIndex.value,
onMousedown: _cache[6] || (_cache[6] = withModifiers(() => {}, ["prevent"])),
onClick: ($event) => emit("selectHistory", term)
}, [createBaseVNode("span", _hoisted_9$8, [createVNode(unref(RotateCcwClock), {
size: 16,
class: "shrink-0 text-muted",
"aria-hidden": "true"
}), createBaseVNode("span", null, toDisplayString(term), 1)])], 40, _hoisted_8$8);
}), 128))], 8, _hoisted_7$9)])) : suggestions.value.length ? (openBlock(), createElementBlock("ul", {
key: 1,
id: unref(listId),
ref_key: "list",
ref: list,
class: "tag-suggestions",
role: "listbox",
"aria-label": "标签联想"
}, [(openBlock(true), createElementBlock(Fragment, null, renderList(suggestions.value, (option, index) => {
return openBlock(), createElementBlock("li", {
id: unref(listId) + "-" + index,
key: option.key,
role: "option",
"aria-selected": index === activeIndex.value,
onMousedown: _cache[7] || (_cache[7] = withModifiers(() => {}, ["prevent"])),
onClick: ($event) => emit("add", option.query)
}, [createBaseVNode("span", null, toDisplayString(option.label), 1), createBaseVNode("small", null, toDisplayString(option.key), 1)], 40, _hoisted_11$8);
}), 128))], 8, _hoisted_10$8)) : canSuggest.value && query.value.trim() && (unref(loading) || unref(failed)) ? (openBlock(), createElementBlock("div", _hoisted_12$7, [createBaseVNode("p", _hoisted_13$7, toDisplayString(unref(loading) ? "正在加载标签词库…" : "标签词库加载失败"), 1), unref(failed) && !unref(loading) ? (openBlock(), createElementBlock("button", {
key: 0,
class: "pill",
type: "button",
onMousedown: _cache[8] || (_cache[8] = withModifiers(() => {}, ["prevent"])),
onClick: retryTags
}, "重试", 32)) : createCommentVNode("", true)])) : !query.value.trim() && !unref(recent).length ? (openBlock(), createElementBlock("p", _hoisted_14$7, "还没有搜索记录")) : createCommentVNode("", true),
confirmClearHistory.value ? (openBlock(), createBlock(ConfirmationDialog_default, {
key: 4,
title: "清空搜索历史?",
message: "将删除所有最近的搜索记录。",
"confirm-label": "清空",
busy: false,
error: "",
onCancel: closeClearHistory,
onConfirm: clearHistory
})) : createCommentVNode("", true)
], 32);
};
}
});
var _hoisted_1$24 = ["aria-label", "aria-labelledby"];
var _hoisted_2$18 = {
key: 0,
class: "sticky top-0 z-3 flex items-center gap-2 border-b border-line bg-surface py-1.5 pt-[max(6px,env(safe-area-inset-top))] pr-[max(16px,env(safe-area-inset-right))] pl-[max(12px,env(safe-area-inset-left))]"
};
var _hoisted_3$13 = {
key: 0,
class: "my-3"
};
var _hoisted_4$10 = { class: "mb-2 flex items-center justify-between gap-2 px-2.5 text-xs text-muted" };
var _hoisted_5$8 = {
class: "m-0 flex list-none flex-wrap gap-2 p-0",
"aria-labelledby": "better-eh-search-conditions"
};
var _hoisted_6$8 = ["aria-label", "onClick"];
var _hoisted_7$8 = { class: "min-w-0 wrap-anywhere" };
var GallerySearchPanel_default = defineComponent({
__name: "GallerySearchPanel",
props: {
query: {},
desktop: { type: Boolean },
completeTags: { type: Function }
},
emits: [
"close",
"loadTags",
"search"
],
setup(__props, { emit: __emit }) {
const props = __props;
const emit = __emit;
const panel = useTemplateRef("panel");
const searchBox = useTemplateRef("searchBox");
const draft = shallowRef("");
const conditions = shallowRef(searchTokens(props.query).map(({ text }) => text));
const canSearch = computed(() => Boolean(conditions.value.length || draft.value.trim() || props.query));
const confirmClear = shallowRef(false);
const viewport = window.visualViewport;
useEventListener$1(viewport, ["resize", "scroll"], fitViewport);
onMounted(() => {
fitViewport();
panel.value?.showModal();
});
onBeforeUnmount(() => panel.value?.close());
function fitViewport() {
const element = panel.value;
if (props.desktop || !element || !viewport) return;
const scale = viewport.scale;
element.style.setProperty("--search-height", `${viewport.height * scale}px`);
element.style.setProperty("--search-top", scale <= 1.01 ? `${viewport.offsetTop}px` : "0px");
}
function addConditions(query) {
const added = searchTokens(query).map(({ text }) => text);
conditions.value = [...conditions.value, ...added];
draft.value = "";
}
function restoreHistory(query) {
conditions.value = searchTokens(query).map(({ text }) => text);
draft.value = "";
}
function removeCondition(index) {
conditions.value = conditions.value.filter((_, position) => position !== index);
}
async function clearConditions() {
confirmClear.value = false;
conditions.value = [];
await nextTick();
searchBox.value?.focus();
}
function search() {
if (!canSearch.value) return;
emit("search", [...conditions.value, draft.value.trim()].filter(Boolean).join(" "));
}
return (_ctx, _cache) => {
return openBlock(), createElementBlock("dialog", {
id: "better-eh-gallery-search",
ref_key: "panel",
ref: panel,
class: normalizeClass(__props.desktop ? "search-panel-desktop" : "search-panel-mobile"),
"aria-label": __props.desktop ? "搜索画廊" : void 0,
"aria-labelledby": __props.desktop ? void 0 : "better-eh-gallery-search-title",
onCancel: _cache[7] || (_cache[7] = withModifiers(($event) => emit("close"), ["self", "prevent"])),
onClick: _cache[8] || (_cache[8] = withModifiers(($event) => __props.desktop && emit("close"), ["self"])),
onTouchmove: _cache[9] || (_cache[9] = withModifiers(() => {}, ["self", "prevent"])),
onWheel: _cache[10] || (_cache[10] = withModifiers(() => {}, ["self", "prevent"]))
}, [createBaseVNode("div", { class: normalizeClass({ "search-panel-mobile-content": !__props.desktop }) }, [!__props.desktop ? (openBlock(), createElementBlock("div", _hoisted_2$18, [
createBaseVNode("button", {
class: "icon-button",
type: "button",
"aria-label": "返回",
onClick: _cache[0] || (_cache[0] = ($event) => emit("close"))
}, [createVNode(unref(ArrowLeft), {
size: 22,
"aria-hidden": "true"
})]),
_cache[12] || (_cache[12] = createBaseVNode("h2", {
id: "better-eh-gallery-search-title",
class: "grow text-[17px] font-[650]"
}, "搜索画廊", -1)),
createVNode(ActionButton_default, {
class: "min-h-11 px-4",
variant: "primary",
disabled: !canSearch.value,
onClick: search
}, {
default: withCtx(() => [..._cache[11] || (_cache[11] = [createTextVNode("搜索", -1)])]),
_: 1
}, 8, ["disabled"])
])) : createCommentVNode("", true), createVNode(TagSearchBox_default, {
ref_key: "searchBox",
ref: searchBox,
modelValue: draft.value,
"onUpdate:modelValue": _cache[4] || (_cache[4] = ($event) => draft.value = $event),
class: normalizeClass(__props.desktop ? "shell pb-4" : "pt-3 pr-[max(16px,env(safe-area-inset-right))] pb-[max(16px,env(safe-area-inset-bottom))] pl-[max(16px,env(safe-area-inset-left))]"),
"complete-tags": __props.completeTags,
placeholder: conditions.value.length ? "添加更多条件" : "输入关键词或标签",
onLoad: _cache[5] || (_cache[5] = ($event) => emit("loadTags")),
onAdd: addConditions,
onSearch: search,
onSelectHistory: restoreHistory
}, createSlots({
default: withCtx(() => [conditions.value.length ? (openBlock(), createElementBlock("div", _hoisted_3$13, [createBaseVNode("div", _hoisted_4$10, [_cache[14] || (_cache[14] = createBaseVNode("h3", {
id: "better-eh-search-conditions",
class: "font-medium"
}, "搜索条件", -1)), createBaseVNode("button", {
class: "min-h-11 rounded-md px-2 hover:bg-panel",
type: "button",
"aria-label": "清空全部搜索条件",
"aria-haspopup": "dialog",
onMousedown: _cache[2] || (_cache[2] = withModifiers(() => {}, ["prevent"])),
onClick: _cache[3] || (_cache[3] = ($event) => confirmClear.value = true)
}, " 清空全部 ", 32)]), createBaseVNode("ul", _hoisted_5$8, [(openBlock(true), createElementBlock(Fragment, null, renderList(conditions.value, (term, index) => {
return openBlock(), createElementBlock("li", {
key: index,
class: "max-w-full min-w-0"
}, [createBaseVNode("button", {
class: "search-condition flex min-h-11 max-w-full touch-manipulation items-center gap-2 rounded-xl text-left text-[13px] font-[550]",
type: "button",
"aria-label": "移除 " + term,
onClick: ($event) => removeCondition(index)
}, [createBaseVNode("span", _hoisted_7$8, toDisplayString(term), 1), createVNode(unref(X), {
size: 16,
class: "shrink-0 text-muted",
"aria-hidden": "true"
})], 8, _hoisted_6$8)]);
}), 128))])])) : createCommentVNode("", true)]),
_: 2
}, [__props.desktop ? {
name: "actions",
fn: withCtx(() => [createVNode(ActionButton_default, {
variant: "primary",
disabled: !canSearch.value,
onClick: search
}, {
default: withCtx(() => [..._cache[13] || (_cache[13] = [createTextVNode(" 搜索 ", -1)])]),
_: 1
}, 8, ["disabled"]), createBaseVNode("button", {
class: "icon-button",
type: "button",
"aria-label": "关闭搜索",
title: "关闭搜索",
onClick: _cache[1] || (_cache[1] = ($event) => emit("close"))
}, [createVNode(unref(X), {
size: 20,
"aria-hidden": "true"
})])]),
key: "0"
} : void 0]), 1032, [
"modelValue",
"class",
"complete-tags",
"placeholder"
])], 2), confirmClear.value ? (openBlock(), createBlock(ConfirmationDialog_default, {
key: 0,
title: "清空全部搜索条件?",
message: "将移除所有已添加的标签。",
"confirm-label": "清空",
busy: false,
error: "",
onCancel: _cache[6] || (_cache[6] = ($event) => confirmClear.value = false),
onConfirm: clearConditions
})) : createCommentVNode("", true)], 42, _hoisted_1$24);
};
}
});
var _hoisted_1$23 = {
class: "site-nav grid gap-1",
"aria-label": "站点导航"
};
var _hoisted_2$17 = [
"data-section",
"href",
"aria-current",
"onClick"
];
var SiteNavLinks_default = defineComponent({
__name: "SiteNavLinks",
props: {
items: {},
currentUrl: {}
},
emits: ["select"],
setup(__props, { emit: __emit }) {
const emit = __emit;
const icons = {
home: House,
watched: Eye,
popular: Flame,
torrents: Download,
favorites: Heart,
settings: Settings,
uploads: Upload,
tags: Tags,
history: RotateCcwClock,
later: Bookmark
};
function isCurrent(href, currentUrl) {
const target = new URL(href);
return target.origin === currentUrl.origin && target.pathname.replace(/\/$/, "") === currentUrl.pathname.replace(/\/$/, "") && Array.from(target.searchParams).every(([key, value]) => (currentUrl.searchParams.get(key) ?? "") === value) && (target.hash.startsWith("#better-eh-") || currentUrl.hash.startsWith("#better-eh-") ? target.hash === currentUrl.hash : true);
}
return (_ctx, _cache) => {
return openBlock(), createElementBlock("nav", _hoisted_1$23, [(openBlock(true), createElementBlock(Fragment, null, renderList(__props.items, (item) => {
return openBlock(), createElementBlock("a", {
key: item.id,
class: "site-nav-link",
"data-section": item.id,
href: item.href,
"aria-current": isCurrent(item.href, __props.currentUrl) ? "page" : void 0,
onClick: ($event) => emit("select", $event, item)
}, [
(openBlock(), createBlock(resolveDynamicComponent(icons[item.id] ?? unref(Compass)), {
size: 18,
"aria-hidden": "true"
})),
createBaseVNode("span", null, toDisplayString(item.label), 1),
item.native ? (openBlock(), createBlock(unref(ArrowUpRight), {
key: 0,
class: "site-nav-native opacity-[.72]",
size: 14,
"aria-hidden": "true"
})) : createCommentVNode("", true)
], 8, _hoisted_2$17);
}), 128))]);
};
}
});
var _hoisted_1$22 = { class: "site-menu-panel" };
var _hoisted_2$16 = { class: "site-menu-header" };
var SiteMenu_default = defineComponent({
__name: "SiteMenu",
props: {
items: {},
currentUrl: {}
},
emits: ["close", "select"],
setup(__props, { expose: __expose, emit: __emit }) {
const emit = __emit;
const dialog = useTemplateRef("dialog");
__expose({ dialog });
return (_ctx, _cache) => {
return openBlock(), createElementBlock("dialog", {
id: "better-eh-site-menu",
ref_key: "dialog",
ref: dialog,
class: "site-menu",
"aria-labelledby": "better-eh-site-menu-title",
onCancel: _cache[2] || (_cache[2] = withModifiers(($event) => emit("close"), ["prevent"])),
onClick: _cache[3] || (_cache[3] = withModifiers(($event) => emit("close"), ["self"]))
}, [createBaseVNode("div", _hoisted_1$22, [createBaseVNode("div", _hoisted_2$16, [_cache[4] || (_cache[4] = createBaseVNode("h2", {
id: "better-eh-site-menu-title",
class: "text-[16px] font-[650]"
}, "站点导航", -1)), createBaseVNode("button", {
class: "icon-button",
type: "button",
"aria-label": "关闭站点导航",
autofocus: "",
onClick: _cache[0] || (_cache[0] = ($event) => emit("close"))
}, [createVNode(unref(X), {
size: 20,
"aria-hidden": "true"
})])]), createVNode(SiteNavLinks_default, {
items: __props.items,
"current-url": __props.currentUrl,
onSelect: _cache[1] || (_cache[1] = (event, item) => emit("select", event, item))
}, null, 8, ["items", "current-url"])])], 544);
};
}
});
var _hoisted_1$21 = {
key: 0,
class: "site-sidebar"
};
var AppNavigation_default = defineComponent({
__name: "AppNavigation",
props: {
routing: {},
searchPanel: {},
completeTags: { type: Function },
visible: { type: Boolean },
desktop: { type: Boolean },
isReader: { type: Boolean },
readerTitle: {},
busy: { type: Boolean },
refreshBlocked: { type: Boolean },
refreshing: { type: Boolean },
openingNative: { type: Boolean },
canBookmark: { type: Boolean },
savedForLater: { type: Boolean },
bookmarksBusy: { type: Boolean }
},
emits: ["navigate", "toggleBookmark"],
setup(__props, { expose: __expose, emit: __emit }) {
const props = __props;
const emit = __emit;
const { search, searchOpen, openSearch, closeSearch, loadTags, submitSearch } = props.searchPanel;
const { home, nativeHref, navigationItems, activeUrl, back, goBack, refreshPage } = props.routing;
const header = useTemplateRef("header");
const siteMenu = useTemplateRef("siteMenu");
const menuOpen = shallowRef(false);
const smallReaderHeader = useMediaQuery("(max-width: 480px)");
const wideReader = computed(() => props.desktop && props.isReader);
const compactSearch = computed(() => !props.desktop);
function openSiteMenu() {
const dialog = siteMenu.value?.dialog;
if (!dialog || dialog.open) return;
dialog.showModal();
menuOpen.value = true;
}
function closeSiteMenu() {
siteMenu.value?.dialog?.close();
menuOpen.value = false;
}
function selectSection(event, item) {
if (!isPrimaryClick(event)) return;
closeSiteMenu();
if (!item.native) emit("navigate", event, item.href);
}
watch(() => props.isReader, (reading) => {
if (reading) closeSiteMenu();
}, { immediate: true });
watch(() => props.desktop, (wide) => {
if (wide) closeSiteMenu();
});
__expose({
searchIcon: () => header.value?.searchIcon(),
focusSearchToggle: () => header.value?.focusSearchToggle(),
focusNavigation: () => header.value?.focusNavigation()
});
return (_ctx, _cache) => {
return openBlock(), createElementBlock(Fragment, null, [
withDirectives(createVNode(AppHeader_default, {
ref_key: "header",
ref: header,
search: unref(search),
"search-open": unref(searchOpen),
home: unref(home),
back: unref(back),
"has-navigation": unref(navigationItems).length > 0,
"menu-open": menuOpen.value,
"compact-search": compactSearch.value,
"wide-reader": wideReader.value,
"small-reader-header": unref(smallReaderHeader),
"is-reader": __props.isReader,
"reader-title": __props.readerTitle,
busy: __props.busy,
"refresh-blocked": __props.refreshBlocked,
"refreshing-content": __props.refreshing,
"native-href": unref(nativeHref),
"opening-native": __props.openingNative,
"can-bookmark": __props.canBookmark,
"saved-for-later": __props.savedForLater,
"bookmarks-busy": __props.bookmarksBusy,
onNavigate: _cache[0] || (_cache[0] = (event, href) => emit("navigate", event, href)),
onGoBack: unref(goBack),
onOpenSiteMenu: openSiteMenu,
onOpenSearch: _cache[1] || (_cache[1] = ($event) => unref(openSearch)()),
onRefresh: unref(refreshPage),
onToggleBookmark: _cache[2] || (_cache[2] = ($event) => emit("toggleBookmark", $event))
}, {
default: withCtx(() => [unref(searchOpen) ? (openBlock(), createBlock(GallerySearchPanel_default, {
key: 0,
query: unref(search),
desktop: !compactSearch.value,
"complete-tags": __props.completeTags,
onClose: unref(closeSearch),
onLoadTags: unref(loadTags),
onSearch: unref(submitSearch)
}, null, 8, [
"query",
"desktop",
"complete-tags",
"onClose",
"onLoadTags",
"onSearch"
])) : createCommentVNode("", true)]),
_: 1
}, 8, [
"search",
"search-open",
"home",
"back",
"has-navigation",
"menu-open",
"compact-search",
"wide-reader",
"small-reader-header",
"is-reader",
"reader-title",
"busy",
"refresh-blocked",
"refreshing-content",
"native-href",
"opening-native",
"can-bookmark",
"saved-for-later",
"bookmarks-busy",
"onGoBack",
"onRefresh"
]), [[vShow, __props.visible]]),
unref(navigationItems).length ? withDirectives((openBlock(), createElementBlock("aside", _hoisted_1$21, [createVNode(SiteNavLinks_default, {
items: unref(navigationItems),
"current-url": unref(activeUrl),
onSelect: selectSection
}, null, 8, ["items", "current-url"])], 512)), [[vShow, __props.visible]]) : createCommentVNode("", true),
unref(navigationItems).length ? (openBlock(), createBlock(SiteMenu_default, {
key: 1,
ref_key: "siteMenu",
ref: siteMenu,
items: unref(navigationItems),
"current-url": unref(activeUrl),
onClose: closeSiteMenu,
onSelect: selectSection
}, null, 8, ["items", "current-url"])) : createCommentVNode("", true)
], 64);
};
}
});
var galleryResizePositionKey = Symbol("gallery resize position");
var galleryViewportKey = Symbol("gallery viewport");
function captureScrollPosition(viewport, source) {
return {
scrollTop: viewport?.scrollTop ?? 0,
anchor: viewport ? captureGalleryAnchor(viewport, source) : void 0
};
}
function captureGalleryAnchor(viewport, source) {
const clicked = source instanceof HTMLElement ? source.closest("[data-gallery-href]") : null;
if (!viewport.scrollTop && !clicked) return;
const bounds = viewport.getBoundingClientRect();
const visibleTop = Math.max(bounds.top, viewport.querySelector(".masthead")?.getBoundingClientRect().bottom ?? 0);
const isVisible = (card) => {
const { top, bottom } = card.getBoundingClientRect();
return bottom > visibleTop && top < bounds.bottom;
};
const card = clicked && viewport.contains(clicked) && isVisible(clicked) ? clicked : Array.from(viewport.querySelectorAll("[data-gallery-href]")).find(isVisible);
const href = card?.dataset.galleryHref;
const group = card?.closest("[data-gallery-group]")?.dataset.galleryGroup;
if (card && href && group) return {
href,
group,
offset: card.getBoundingClientRect().top - bounds.top
};
}
function provideGalleryResizePosition() {
const viewport = inject(galleryViewportKey)?.viewport;
const resizePosition = shallowRef();
provide(galleryResizePositionKey, resizePosition);
useEventListener$1(() => viewport?.value, "scroll", () => {
const scroll = viewport?.value;
const top = resizePosition.value?.scrollTop;
if (!scroll || top === void 0 || Math.abs(scroll.scrollTop - top) <= 1) return;
const clampedTop = Math.min(top, Math.max(0, scroll.scrollHeight - scroll.clientHeight));
if (Math.abs(scroll.scrollTop - clampedTop) > 1) resizePosition.value = void 0;
}, { passive: true });
}
function getMeasurementKey(item) {
return typeof item === "object" ? item.key : item;
}
function createLazyMeasurementsView(cache, flat) {
const count = cache.length;
return new Proxy(cache, { get(target, prop, receiver) {
if (typeof prop === "string") {
const c = prop.charCodeAt(0);
if (c >= 48 && c <= 57) {
const i = +prop;
if (Number.isInteger(i) && i >= 0 && i < count) {
let v = target[i];
if (typeof v !== "object") {
const s = flat[i * 2];
v = target[i] = {
index: i,
key: v,
start: s,
size: flat[i * 2 + 1],
end: s + flat[i * 2 + 1],
lane: 0
};
}
return v;
}
}
if (prop === "length") return count;
}
return Reflect.get(target, prop, receiver);
} });
}
function memo(getDeps, fn, opts) {
let deps = opts.initialDeps ?? [];
let result;
let isInitial = true;
function memoizedFunction() {
const newDeps = getDeps();
if (!(newDeps.length !== deps.length || newDeps.some((dep, index) => deps[index] !== dep))) return result;
deps = newDeps;
result = fn(...newDeps);
if ((opts == null ? void 0 : opts.onChange) && !(isInitial && opts.skipInitialOnChange)) opts.onChange(result);
isInitial = false;
return result;
}
memoizedFunction.updateDeps = (newDeps) => {
deps = newDeps;
};
return memoizedFunction;
}
function notUndefined(value, msg) {
if (value === void 0) throw new Error(`Unexpected undefined${msg ? `: ${msg}` : ""}`);
else return value;
}
var approxEqual = (a, b) => Math.abs(a - b) < 1.01;
var debounce = (targetWindow, fn, ms) => {
let timeoutId;
return Object.assign(function(...args) {
targetWindow.clearTimeout(timeoutId);
timeoutId = targetWindow.setTimeout(() => fn.apply(this, args), ms);
}, { cancel: () => {
targetWindow.clearTimeout(timeoutId);
} });
};
function classifyScrollEvent({ offset, isScrolling, elementMax, holdOffset, scrollOffset, pendingWrite, clampedMaxAtWrite }) {
var _a;
if (isScrolling && pendingWrite === null && offset === scrollOffset) return "spurious";
if (pendingWrite !== null && Math.abs(offset - pendingWrite.target) < 1.5) return "readBack";
if (pendingWrite !== null && !pendingWrite.smooth && elementMax !== null && pendingWrite.target > elementMax + holdOffset + .5 && Math.abs(offset - (elementMax + holdOffset)) < 1.5) return "clampedReadBack";
if (pendingWrite !== null && !pendingWrite.smooth && ((_a = pendingWrite.lowMaxes) == null ? void 0 : _a.some((max) => Math.abs(offset - max) < 1.5))) return "clampedReadBack";
if (clampedMaxAtWrite !== null && Math.abs(offset - clampedMaxAtWrite) < 1.5) return "clampedEcho";
return "external";
}
var isAnimating = (phase) => phase === "smooth" || phase === "smoothFinishing";
function externalRetiresCommand({ kind, offset, command, target }) {
return kind !== "spurious" && kind !== "readBack" && kind !== "clampedReadBack" && (command == null ? void 0 : command.index) != null && command.phase !== "queued" && !isAnimating(command.phase) && !approxEqual(offset, command.lastTargetOffset) && !approxEqual(offset, target()) && kind !== "clampedEcho";
}
var FLING_WINDOW_MS = 40;
function flingSpedUp(samples) {
const last = samples[samples.length - 1];
if (last === void 0) return false;
let j = samples.length - 2;
while (j >= 0 && last.t - samples[j].t < FLING_WINDOW_MS) j--;
if (j < 0) return false;
const mid = samples[j];
let k = j - 1;
while (k >= 0 && mid.t - samples[k].t < FLING_WINDOW_MS) k--;
if (k < 0) return false;
const first = samples[k];
const recent = (last.offset - mid.offset) / (last.t - mid.t);
const before = (mid.offset - first.offset) / (mid.t - first.t);
return recent * before >= 0 && Math.abs(recent) >= 2 * Math.abs(before) && Math.abs(recent) - Math.abs(before) >= .8;
}
function flingCaught(samples) {
const last = samples[samples.length - 1];
if (last === void 0) return false;
let j = samples.length - 2;
while (j >= 0 && last.t - samples[j].t < FLING_WINDOW_MS) j--;
if (j < 0) return false;
const from = samples[j];
return Math.abs(last.offset - from.offset) / (last.t - from.t) >= .05;
}
var _isIOSResult;
var isIOSWebKit = () => {
if (_isIOSResult !== void 0) return _isIOSResult;
if (typeof navigator === "undefined") return _isIOSResult = false;
if (/iP(hone|od|ad)/.test(navigator.userAgent)) return _isIOSResult = true;
const mtp = navigator.maxTouchPoints;
return _isIOSResult = navigator.platform === "MacIntel" && mtp !== void 0 && mtp > 0;
};
var _iosMomentumOverridesWritesResult;
var iosMomentumOverridesWrites = () => {
if (_iosMomentumOverridesWritesResult !== void 0) return _iosMomentumOverridesWritesResult;
return _iosMomentumOverridesWritesResult = isIOSWebKit() && typeof CSS !== "undefined" && typeof CSS.supports === "function" && CSS.supports("overflow-anchor: auto");
};
var momentumOverridesWrites = () => !isIOSWebKit() || iosMomentumOverridesWrites();
var touchListenerOptions = {
capture: true,
passive: true
};
var IosGesture = class {
constructor(host) {
this.host = host;
this._touch = null;
this.inMotion = () => this._touch !== null && this._touch.phase !== "lateFling";
this.dragging = () => {
var _a;
return ((_a = this._touch) == null ? void 0 : _a.phase) === "down" && this._touch.moved;
};
this.tail = () => {
var _a;
return ((_a = this._touch) == null ? void 0 : _a.phase) === "tail" ? this._touch.moved ? "fling" : "tap" : null;
};
this.onScroll = ({ isScrolling, ownReadBack, moved, external }) => {
var _a, _b, _c;
if (isScrolling && ((_a = this._touch) == null ? void 0 : _a.phase) === "tail") this._openTail(this._touch.moved || !ownReadBack, false);
else if (((_b = this._touch) == null ? void 0 : _b.phase) === "lateFling") {
if (this.host.now() > this._touch.until) this._touch = null;
else if (external && isScrolling && moved) this._openTail(true, false);
}
if (!ownReadBack && isScrolling && moved && ((_c = this._touch) == null ? void 0 : _c.phase) === "down") {
this._touch.moved = true;
return true;
}
return false;
};
this.touchStart = () => {
this.end();
this._touch = {
phase: "down",
moved: false
};
};
this.touchEnd = () => {
var _a;
const moved = ((_a = this._touch) == null ? void 0 : _a.phase) === "down" && this._touch.moved;
this.end();
this._openTail(moved, moved);
};
this.end = () => {
var _a;
const win = this.host.getWindow();
if (((_a = this._touch) == null ? void 0 : _a.phase) === "tail" && win != null) win.clearTimeout(this._touch.timerId);
this._touch = null;
};
this.listen = (target) => {
const onTouchStart = () => this.touchStart();
const onTouchEnd = () => this.touchEnd();
target.addEventListener("touchstart", onTouchStart, touchListenerOptions);
target.addEventListener("touchend", onTouchEnd, touchListenerOptions);
target.addEventListener("touchcancel", onTouchEnd, touchListenerOptions);
return () => {
target.removeEventListener("touchstart", onTouchStart, touchListenerOptions);
target.removeEventListener("touchend", onTouchEnd, touchListenerOptions);
target.removeEventListener("touchcancel", onTouchEnd, touchListenerOptions);
this.end();
};
};
this._openTail = (moved, awaitingFling) => {
const win = this.host.getWindow();
if (win == null) return;
this.end();
const tail = {
phase: "tail",
moved,
awaitingFling,
timerId: win.setTimeout(() => {
if (this.host.tailStillMoving()) {
this._openTail(tail.moved, tail.awaitingFling);
return;
}
this._touch = tail.awaitingFling ? {
phase: "lateFling",
until: this.host.now() + 1e3
} : null;
this.host.onTailClosed();
}, 150)
};
this._touch = tail;
};
}
get touch() {
return this._touch;
}
};
var getRect = (element) => {
const { clientWidth, clientHeight } = element;
return {
width: clientWidth,
height: clientHeight
};
};
var createFrameQueue = (targetWindow) => {
const ids = new Set();
return {
schedule: (fn) => {
const id = targetWindow.requestAnimationFrame(() => {
ids.delete(id);
fn();
});
ids.add(id);
},
cancel: () => {
ids.forEach((id) => targetWindow.cancelAnimationFrame(id));
ids.clear();
}
};
};
var defaultKeyExtractor = (index) => index;
var defaultRangeExtractor = (range) => {
const overscan = range.overscan * Math.max(range.lanes ?? 1, 1);
const start = Math.max(range.startIndex - overscan, 0);
const len = Math.min(range.endIndex + overscan, range.count - 1) - start + 1;
const arr = new Array(len);
for (let i = 0; i < len; i++) arr[i] = start + i;
return arr;
};
var observeElementRect = (instance, cb) => {
const element = instance.scrollElement;
if (!element) return;
const targetWindow = instance.targetWindow;
if (!targetWindow) return;
const handler = (rect) => {
const { width, height } = rect;
cb({
width: Math.round(width),
height: Math.round(height)
});
};
handler(getRect(element));
if (!targetWindow.ResizeObserver) return () => {};
const frames = createFrameQueue(targetWindow);
const observer = new targetWindow.ResizeObserver(() => {
const run = () => {
handler(getRect(element));
};
instance.options.useAnimationFrameWithResizeObserver ? frames.schedule(run) : run();
});
observer.observe(element, { box: "content-box" });
return () => {
observer.unobserve(element);
frames.cancel();
};
};
var addEventListenerOptions = { passive: true };
var supportsScrollend = typeof window == "undefined" ? true : "onscrollend" in window;
var observeOffset = (instance, cb, readOffset) => {
const element = instance.scrollElement;
if (!element) return;
const targetWindow = instance.targetWindow;
if (!targetWindow) return;
const registerScrollendEvent = instance.options.useScrollendEvent && supportsScrollend;
let offset = 0;
const fallback = registerScrollendEvent ? null : debounce(targetWindow, () => cb(readOffset(element), false), instance.options.isScrollingResetDelay);
const createHandler = (isScrolling) => () => {
offset = readOffset(element);
fallback?.();
cb(offset, isScrolling);
};
const handler = createHandler(true);
const endHandler = createHandler(false);
element.addEventListener("scroll", handler, addEventListenerOptions);
if (registerScrollendEvent) element.addEventListener("scrollend", endHandler, addEventListenerOptions);
return () => {
element.removeEventListener("scroll", handler);
if (registerScrollendEvent) element.removeEventListener("scrollend", endHandler);
fallback?.cancel();
};
};
var observeElementOffset = (instance, cb) => observeOffset(instance, cb, (el) => {
const { horizontal, isRtl } = instance.options;
return horizontal ? el.scrollLeft * (isRtl && -1 || 1) : el.scrollTop;
});
var measureElement = (element, entry, instance) => {
if (instance.options.useCachedMeasurements) {
const index = instance.indexFromElement(element);
const key = instance.options.getItemKey(index);
return instance.itemSizeCache.get(key) ?? instance.options.estimateSize(index);
}
if (entry == null ? void 0 : entry.borderBoxSize) {
const box = entry.borderBoxSize[0];
if (box) return Math.round(box[instance.options.horizontal ? "inlineSize" : "blockSize"]);
}
if (!entry) {
const index = instance.indexFromElement(element);
const key = instance.options.getItemKey(index);
const cachedSize = instance.itemSizeCache.get(key);
if (cachedSize !== void 0) return cachedSize;
}
return element[instance.options.horizontal ? "offsetWidth" : "offsetHeight"];
};
var scrollWithAdjustments = (offset, { adjustments = 0, behavior }, instance) => {
var _a;
const { scrollElement, options } = instance;
const adjustedOffset = offset + adjustments;
const isRtlElement = options.horizontal && options.isRtl && scrollElement !== null && "ownerDocument" in scrollElement;
(_a = scrollElement == null ? void 0 : scrollElement.scrollTo) == null || _a.call(scrollElement, {
[options.horizontal ? "left" : "top"]: isRtlElement ? -adjustedOffset : adjustedOffset,
behavior
});
};
var elementScroll = scrollWithAdjustments;
var initialScrollPhase = (behavior, atTarget) => behavior === "smooth" ? atTarget ? "smoothLanded" : "smooth" : "instant";
var isSmoothScroll = (state) => (state == null ? void 0 : state.phase) === "smooth" || (state == null ? void 0 : state.phase) === "smoothLanded";
function isAppendWithTrim(prevCount, nextCount, getPreviousKey, getNextKey) {
if (nextCount === 0) return false;
const firstKey = getNextKey(0);
const removedKeys = new Set();
let removedCount = 0;
while (removedCount < prevCount) {
const key = getPreviousKey(removedCount);
if (key === firstKey) break;
removedKeys.add(key);
removedCount++;
}
const retainedCount = prevCount - removedCount;
if (retainedCount === 0 || retainedCount >= nextCount) return false;
for (let i = 0; i < retainedCount; i++) if (getNextKey(i) !== getPreviousKey(removedCount + i)) return false;
for (let i = retainedCount; i < nextCount; i++) if (removedKeys.has(getNextKey(i))) return false;
return true;
}
var Virtualizer = class {
constructor(opts) {
this.unsubs = [];
this.scrollElement = null;
this.targetWindow = null;
this.isScrolling = false;
this.scrollState = null;
this.measurementsCache = [];
this._singleLaneMeasurements = null;
this.itemSizeCache = new Map();
this.itemSizeCacheVersion = 0;
this.laneAssignments = new Map();
this.pendingMin = null;
this.prevLanes = void 0;
this.lanesChangedFlag = false;
this.lanesSettling = false;
this.pendingScrollAnchor = null;
this.scrollRect = null;
this.scrollOffset = null;
this.scrollDirection = null;
this._holdOffset = 0;
this._reportedOverscroll = false;
this._iosGesture = new IosGesture({
getWindow: () => this.targetWindow,
now: () => this.now(),
tailStillMoving: () => {
const state = this.scrollState;
if ((state == null ? void 0 : state.phase) !== "queued" || this.pendingWrite !== null) return false;
const now = this._readElementOffset();
if (now === null || this._lastElementOffset === null || Math.abs(now - this._lastElementOffset) < 1) return false;
this._lastElementOffset = now;
state.samples = [...state.samples ?? [], {
t: this.now(),
offset: now
}];
return true;
},
onTailClosed: () => {
const state = this.scrollState;
if ((state == null ? void 0 : state.phase) === "queued" && flingCaught(state.samples ?? [])) this.scrollState = null;
this._flushHoldIfReady(true);
this._writeAwaitingCommand();
this._retryClampedAdjustment();
}
});
this._lastElementOffset = null;
this.pendingWrite = null;
this._clampedAdjustment = null;
this.elementsCache = new Map();
this._resizeBatch = null;
this.now = () => {
var _a, _b, _c;
return ((_c = (_b = (_a = this.targetWindow) == null ? void 0 : _a.performance) == null ? void 0 : _b.now) == null ? void 0 : _c.call(_b)) ?? Date.now();
};
this.observer = (() => {
let _ro = null;
let _frames = null;
let delivering = false;
let observeQueued = false;
const pendingObservations = new Set();
const get = () => {
if (_ro) return _ro;
const targetWindow = this.targetWindow;
if (!targetWindow || !targetWindow.ResizeObserver) return null;
const frames = _frames = createFrameQueue(targetWindow);
return _ro = new targetWindow.ResizeObserver((entries) => {
const run = () => {
const batch = { sync: false };
this._resizeBatch = batch;
try {
entries.forEach(measureEntry);
} finally {
this._resizeBatch = null;
if (batch.notify) {
this.notify(batch.sync);
this._noteClampMax();
this._flushHoldIfReady(true);
this._retryClampedAdjustment();
this.measureElement(null);
}
}
};
if (this.options.useAnimationFrameWithResizeObserver) frames.schedule(run);
else {
delivering = true;
try {
run();
} finally {
delivering = false;
}
}
});
};
const measureEntry = (entry) => {
const node = entry.target;
const index = this.indexFromElement(node);
if (!node.isConnected) {
this.observer.unobserve(node);
for (const [cacheKey, cachedNode] of this.elementsCache) if (cachedNode === node) {
this.elementsCache.delete(cacheKey);
break;
}
return;
}
if (!this.isIndexInRange(index)) return;
if (this.shouldMeasureDuringScroll(index)) this.resizeItem(index, this.options.measureElement(node, entry, this));
};
return {
disconnect: () => {
var _a;
(_a = get()) == null || _a.disconnect();
_frames?.cancel();
pendingObservations.clear();
observeQueued = false;
_ro = null;
_frames = null;
},
observe: (target) => {
const observer = get();
if (!observer) return;
if (!delivering) {
observer.observe(target, { box: "border-box" });
return;
}
pendingObservations.add(target);
if (!observeQueued) {
observeQueued = true;
_frames?.schedule(() => {
observeQueued = false;
pendingObservations.forEach((node) => {
if (node.isConnected) _ro?.observe(node, { box: "border-box" });
});
pendingObservations.clear();
});
}
},
unobserve: (target) => {
var _a;
pendingObservations.delete(target);
(_a = get()) == null || _a.unobserve(target);
}
};
})();
this.range = null;
this.setOptions = (opts2) => {
var _a;
const merged = {
debug: false,
initialOffset: 0,
overscan: 1,
paddingStart: 0,
paddingEnd: 0,
scrollPaddingStart: 0,
scrollPaddingEnd: 0,
horizontal: false,
getItemKey: defaultKeyExtractor,
rangeExtractor: defaultRangeExtractor,
onChange: () => {},
measureElement,
initialRect: {
width: 0,
height: 0
},
scrollMargin: 0,
gap: 0,
indexAttribute: "data-index",
initialMeasurementsCache: [],
lanes: 1,
anchorTo: "start",
followOnAppend: false,
scrollEndThreshold: 1,
isScrollingResetDelay: 150,
enabled: true,
isRtl: false,
useScrollendEvent: false,
useAnimationFrameWithResizeObserver: false,
laneAssignmentMode: "estimate",
useCachedMeasurements: false
};
for (const key in opts2) {
const v = opts2[key];
if (v !== void 0) merged[key] = v;
}
const prevOptions = this.options;
let anchor = null;
let followOnAppend = null;
let edgeKeysChanged = false;
if (prevOptions !== void 0 && prevOptions.enabled && merged.enabled && merged.anchorTo === "end" && this.scrollElement !== null) {
const prevCount = prevOptions.count;
const nextCount = merged.count;
const measurements = this.getMeasurements();
const previousItems = ((_a = this._singleLaneMeasurements) == null ? void 0 : _a.items) ?? measurements;
const getPreviousKey = (index) => getMeasurementKey(previousItems[index]);
const prevFirstKey = prevCount > 0 ? getPreviousKey(0) : null;
const prevLastKey = prevCount > 0 ? getPreviousKey(prevCount - 1) : null;
if (nextCount !== prevCount || prevCount > 0 && nextCount > 0 && (merged.getItemKey(0) !== prevFirstKey || merged.getItemKey(nextCount - 1) !== prevLastKey)) {
edgeKeysChanged = true;
const item = prevCount > 0 ? this.getVirtualItemForOffset(this.getScrollOffset()) ?? measurements[0] : null;
if (item) anchor = [item.key, this.getScrollOffset() - item.start];
const behavior = merged.followOnAppend === true ? "auto" : merged.followOnAppend || null;
if (behavior && nextCount > 0 && this.isAtEnd(prevOptions.scrollEndThreshold) && (prevCount === 0 || merged.getItemKey(nextCount - 1) !== prevLastKey)) {
if (nextCount > prevCount || isAppendWithTrim(prevCount, nextCount, getPreviousKey, merged.getItemKey)) followOnAppend = behavior;
}
}
}
this.options = merged;
if (edgeKeysChanged) {
this.pendingMin = 0;
this.itemSizeCacheVersion++;
}
let anchorDelta = null;
if (anchor && this.scrollOffset !== null && !this._awaitingCommandReadBack()) {
const [anchorKey, anchorOffset] = anchor;
const newMeasurements = this.getMeasurements();
const { count, getItemKey } = this.options;
let idx = 0;
while (idx < count && getItemKey(idx) !== anchorKey) idx++;
if (idx < count) {
const anchorItem = newMeasurements[idx];
if (anchorItem) {
const newOffset = Math.max(0, anchorItem.start + anchorOffset);
if (!followOnAppend && newOffset !== this.scrollOffset) {
anchorDelta = newOffset - this.scrollOffset;
this.scrollOffset = newOffset;
}
}
}
}
if (followOnAppend) this.pendingScrollAnchor = {
kind: "follow",
behavior: followOnAppend
};
else if (anchorDelta !== null) {
if (this._canWriteScroll()) this.pendingScrollAnchor = {
kind: "anchor",
delta: anchorDelta
};
else {
this._holdOffset += anchorDelta;
this._followOffsetTarget(anchorDelta);
}
}
};
this.notify = (sync) => {
var _a, _b;
(_b = (_a = this.options).onChange) == null || _b.call(_a, this, sync);
};
this.maybeNotify = memo(() => {
this.calculateRange();
return [
this.isScrolling,
this.range ? this.range.startIndex : null,
this.range ? this.range.endIndex : null
];
}, (isScrolling) => {
this.notify(isScrolling);
}, {
key: false,
debug: () => this.options.debug,
initialDeps: [
this.isScrolling,
this.range ? this.range.startIndex : null,
this.range ? this.range.endIndex : null
]
});
this.cleanup = () => {
var _a;
this.unsubs.filter(Boolean).forEach((d) => d());
this.unsubs = [];
this.observer.disconnect();
if (this.rafId != null && this.targetWindow) {
this.targetWindow.cancelAnimationFrame(this.rafId);
this.rafId = null;
}
this.scrollState = null;
(_a = this._momentumStop) == null || _a.restore();
this._momentumStop = null;
this.isScrolling = false;
this.scrollDirection = null;
this._holdOffset = 0;
this._reportedOverscroll = false;
this._clampedAdjustment = null;
this.pendingWrite = null;
this.scrollElement = null;
this.targetWindow = null;
};
this._didMount = () => {
return () => {
this.cleanup();
};
};
this._willUpdate = () => {
var _a;
const scrollElement = this.options.enabled ? this.options.getScrollElement() : null;
if (this.scrollElement !== scrollElement) {
this.cleanup();
if (!scrollElement) {
this.maybeNotify();
return;
}
this.scrollElement = scrollElement;
if (this.scrollElement && "ownerDocument" in this.scrollElement) this.targetWindow = this.scrollElement.ownerDocument.defaultView;
else this.targetWindow = ((_a = this.scrollElement) == null ? void 0 : _a.window) ?? null;
this.elementsCache.forEach((cached) => {
this.observer.observe(cached);
});
this.unsubs.push(this.options.observeElementRect(this, (rect) => {
this.scrollRect = rect;
this.maybeNotify();
}));
this.unsubs.push(this.options.observeElementOffset(this, (offset, isScrolling) => {
var _a2, _b, _c, _d;
const elementMax = isScrolling ? this._elementMaxScrollOffset() : null;
const wasOverscrolled = this._reportedOverscroll;
this._reportedOverscroll = offset < 0 || elementMax !== null && offset > elementMax + 1;
const elementOffset = offset;
this._lastElementOffset = elementOffset;
offset = this._toLayoutOffset(offset);
const kind = this._classifyScrollEvent(offset, isScrolling, elementMax);
if (kind === "spurious") return;
if (kind === "readBack") offset = this.pendingWrite.target;
else if (kind === "clampedReadBack" && ((_a2 = this.scrollState) == null ? void 0 : _a2.index) != null && offset < this.getMaxScrollOffset() - 1.5) this.scrollState.lastTargetOffset = offset;
else if (externalRetiresCommand({
kind,
offset,
command: this.scrollState,
target: () => this.getScrollStateTarget(this.scrollState)
})) this.scrollState = null;
this.pendingWrite = null;
if (this._clampedAdjustment !== null && Math.abs(offset - this._clampedAdjustment.maxAtWrite) >= 1.5) this._clampedAdjustment = null;
const prevOffset = this.getScrollOffset();
const prevDirection = this.scrollDirection;
this.scrollDirection = isScrolling ? prevOffset === offset ? this.scrollDirection : prevOffset < offset ? "forward" : "backward" : null;
this.scrollOffset = offset;
this.isScrolling = isScrolling;
const queued = this.scrollState;
if ((queued == null ? void 0 : queued.phase) === "queued" && kind === "external" && isScrolling) {
if (wasOverscrolled || this._reportedOverscroll) queued.samples = [];
else {
const t = this.now();
queued.samples = [...(queued.samples ?? []).filter((sample) => t - sample.t <= 200), {
t,
offset: elementOffset
}];
if (prevDirection !== null && this.scrollDirection !== prevDirection || flingSpedUp(queued.samples)) this.scrollState = null;
}
}
if (this._iosGesture.onScroll({
isScrolling,
ownReadBack: kind === "readBack",
moved: offset !== prevOffset,
external: kind === "external" && ((_b = this.scrollState) == null ? void 0 : _b.phase) !== "smooth" && ((_c = this.scrollState) == null ? void 0 : _c.phase) !== "smoothFinishing"
}) && ((_d = this.scrollState) == null ? void 0 : _d.phase) === "queued") this.scrollState = null;
this._flushHoldIfReady(true);
if (this.scrollState) this.scheduleScrollReconcile();
this.maybeNotify();
}));
if ("addEventListener" in this.scrollElement) this.unsubs.push(this._iosGesture.listen(this.scrollElement));
this._scrollToOffset(this.getScrollOffset());
}
this._noteClampMax();
const anchor = this.pendingScrollAnchor;
this.pendingScrollAnchor = null;
if (anchor && this.scrollElement && this.options.enabled) {
if (anchor.kind === "anchor") {
if (!this._canWriteScroll()) {
this._holdOffset += anchor.delta;
this._followOffsetTarget(anchor.delta);
this.notify(false);
} else if (isSmoothScroll(this.scrollState) && !approxEqual(this.getScrollOffset() - anchor.delta, this.scrollState.lastTargetOffset));
else {
this._followOffsetTarget(anchor.delta);
this._scrollToOffset(this.getScrollOffset());
}
} else this.scrollToEnd({ behavior: anchor.behavior });
}
this._flushHoldIfReady(false);
this._retryClampedAdjustment();
};
this._classifyScrollEvent = (offset, isScrolling, elementMax) => {
var _a;
return classifyScrollEvent({
offset,
isScrolling,
elementMax,
holdOffset: this._holdOffset,
scrollOffset: this.scrollOffset,
pendingWrite: this.pendingWrite,
clampedMaxAtWrite: ((_a = this._clampedAdjustment) == null ? void 0 : _a.maxAtWrite) ?? null
});
};
this._retryClampedAdjustment = () => {
if (this._clampedAdjustment === null || !this.scrollElement || !this.options.enabled || !this._canWriteScroll()) return;
const { target, maxAtWrite } = this._clampedAdjustment;
const max = this.getMaxScrollOffset();
if (max > maxAtWrite + .5) {
this._clampedAdjustment = target > max + .5 ? {
target,
maxAtWrite: max
} : null;
this._scrollToOffset(target);
}
};
this._writeAwaitingCommand = () => {
const state = this.scrollState;
if (state === null || state.phase !== "queued") return;
const { behavior } = state;
this.getMeasurements();
const offset = this.getScrollStateTarget(state);
state.lastTargetOffset = offset;
this._clampedAdjustment = null;
state.phase = initialScrollPhase(behavior, state.index != null && approxEqual(offset, this.getScrollOffset()));
this._scrollToOffset(offset, { behavior });
this.scheduleScrollReconcile();
};
this._readElementOffset = () => {
const el = this.scrollElement;
if (el == null) return null;
const { horizontal, isRtl } = this.options;
if (typeof el.scrollTop === "number") return horizontal ? el.scrollLeft * (isRtl && -1 || 1) : el.scrollTop;
if (typeof el.scrollY === "number") return horizontal ? el.scrollX : el.scrollY;
return null;
};
this._canWriteScroll = () => !(isIOSWebKit() && this._iosGesture.inMotion()) && !this._reportedOverscroll;
this._flushHoldIfReady = (sync) => {
var _a;
if (this._holdOffset === 0) return;
if (!this.scrollElement || !this.options.enabled) return;
if (!this._canWriteScroll()) return;
if (((_a = this.scrollState) == null ? void 0 : _a.phase) === "smooth") return;
this._holdOffset = 0;
if (this.scrollOffset !== null && this.scrollOffset < 0) this.scrollOffset = 0;
this.notify(sync);
const target = this.getCommandWrittenOffset() ?? this.getScrollOffset();
this._clampedAdjustment = this._clampedBy(target);
this._scrollToOffset(target);
};
this.rafId = null;
this.getSize = () => {
if (!this.options.enabled) {
this.scrollRect = null;
return 0;
}
this.scrollRect = this.scrollRect ?? this.options.initialRect;
return this.scrollRect[this.options.horizontal ? "width" : "height"];
};
this.getScrollOffset = () => {
if (!this.options.enabled) {
this.scrollOffset = null;
return 0;
}
this.scrollOffset = this.scrollOffset ?? (typeof this.options.initialOffset === "function" ? this.options.initialOffset() : this.options.initialOffset);
return this.scrollOffset;
};
this.getMeasurementOptions = memo(() => [
this.options.count,
this.options.paddingStart,
this.options.scrollMargin,
this.options.getItemKey,
this.options.enabled,
this.options.lanes,
this.options.laneAssignmentMode,
this.options.gap
], (count, paddingStart, scrollMargin, getItemKey, enabled, lanes, laneAssignmentMode, gap) => {
if (this.prevLanes !== void 0 && this.prevLanes !== lanes) this.lanesChangedFlag = true;
this.prevLanes = lanes;
this.pendingMin = null;
return {
count,
paddingStart,
scrollMargin,
getItemKey,
enabled,
lanes,
laneAssignmentMode,
gap
};
}, { key: false });
this.isIndexInRange = (index) => index >= 0 && index < this.options.count;
this.getMeasurements = memo(() => [this.getMeasurementOptions(), this.itemSizeCacheVersion], ({ count, paddingStart, scrollMargin, getItemKey, enabled, lanes, laneAssignmentMode, gap }, _itemSizeCacheVersion) => {
var _a;
const itemSizeCache = this.itemSizeCache;
if (!enabled) {
this.measurementsCache = [];
this._singleLaneMeasurements = null;
this.itemSizeCache.clear();
this.laneAssignments.clear();
return [];
}
if (this.laneAssignments.size > count) {
for (const index of this.laneAssignments.keys()) if (index >= count) this.laneAssignments.delete(index);
}
if (this.lanesChangedFlag) {
this.lanesChangedFlag = false;
this.lanesSettling = true;
this.measurementsCache = [];
this._singleLaneMeasurements = null;
this.itemSizeCache.clear();
this.laneAssignments.clear();
this.pendingMin = null;
}
if (this.measurementsCache.length === 0 && !this.lanesSettling) {
this.measurementsCache = this.options.initialMeasurementsCache;
this.measurementsCache.forEach((item) => {
this.itemSizeCache.set(item.key, item.size);
});
}
const min = this.lanesSettling ? 0 : this.pendingMin ?? 0;
this.pendingMin = null;
if (this.lanesSettling && this.measurementsCache.length === count) this.lanesSettling = false;
if (lanes === 1) {
const need = count * 2;
let flat = (_a = this._singleLaneMeasurements) == null ? void 0 : _a.flat;
if (!flat || flat.length < need) {
const next = new Float64Array(need);
if (flat && min > 0) next.set(flat.subarray(0, min * 2));
flat = next;
}
const items = min === 0 ? new Array(count) : this._singleLaneMeasurements.items.slice();
let runningStart;
if (min === 0) runningStart = paddingStart + scrollMargin;
else {
const prevIdx = min - 1;
runningStart = flat[prevIdx * 2] + flat[prevIdx * 2 + 1] + gap;
}
for (let i = min; i < count; i++) {
const key = getItemKey(i);
items[i] = key;
const measuredSize = itemSizeCache.get(key);
const size = typeof measuredSize === "number" ? measuredSize : this.options.estimateSize(i);
flat[i * 2] = runningStart;
flat[i * 2 + 1] = size;
runningStart += size + gap;
}
this._singleLaneMeasurements = {
flat,
items
};
const view = createLazyMeasurementsView(items, flat);
this.measurementsCache = view;
return view;
}
const measurements = this.measurementsCache.slice(0, min);
const laneLastIndex = new Array(lanes).fill(void 0);
const laneEnds = new Float64Array(lanes);
let filledLanes = 0;
for (let m = 0; m < min; m++) {
const item = measurements[m];
if (item) {
if (laneLastIndex[item.lane] === void 0) filledLanes++;
laneLastIndex[item.lane] = m;
laneEnds[item.lane] = item.end;
}
}
for (let i = min; i < count; i++) {
const key = getItemKey(i);
const cachedLane = this.laneAssignments.get(i);
let lane;
let start;
const shouldCacheLane = laneAssignmentMode === "estimate" || itemSizeCache.has(key);
if (cachedLane !== void 0 && this.options.lanes > 1) {
lane = cachedLane;
const prevIndex = laneLastIndex[lane];
const prevInLane = prevIndex !== void 0 ? measurements[prevIndex] : void 0;
start = prevInLane ? prevInLane.end + gap : paddingStart + scrollMargin;
} else if (filledLanes === lanes) {
let bestLane = 0;
let bestEnd = laneEnds[0];
let bestIdx = laneLastIndex[0];
for (let l = 1; l < lanes; l++) {
const e = laneEnds[l];
if (e < bestEnd || e === bestEnd && laneLastIndex[l] < bestIdx) {
bestLane = l;
bestEnd = e;
bestIdx = laneLastIndex[l];
}
}
lane = bestLane;
start = bestEnd + gap;
if (shouldCacheLane) this.laneAssignments.set(i, lane);
} else {
lane = i % this.options.lanes;
start = paddingStart + scrollMargin;
if (shouldCacheLane) this.laneAssignments.set(i, lane);
}
const measuredSize = itemSizeCache.get(key);
const size = typeof measuredSize === "number" ? measuredSize : this.options.estimateSize(i);
const end = start + size;
measurements[i] = {
index: i,
start,
size,
end,
key,
lane
};
if (laneLastIndex[lane] === void 0) filledLanes++;
laneLastIndex[lane] = i;
laneEnds[lane] = end;
}
this.measurementsCache = measurements;
return measurements;
}, {
key: false,
debug: () => this.options.debug
});
this.calculateRange = memo(() => [
this.getMeasurements(),
this.getSize(),
this.getScrollOffset(),
this.options.lanes,
this._getLayoutTotalSize() + this.options.scrollMargin
], (measurements, outerSize, scrollOffset, lanes, listEnd) => {
if (measurements.length === 0 || outerSize === 0) {
this.range = null;
return null;
}
const maxScrollOffset = Math.max(listEnd - outerSize, 0);
this.range = calculateRangeImpl(measurements, outerSize, Math.min(scrollOffset, maxScrollOffset), lanes, lanes === 1 && this._singleLaneMeasurements !== null ? this._singleLaneMeasurements.flat : null);
return this.range;
}, {
key: false,
debug: () => this.options.debug
});
this.getVirtualIndexes = memo(() => {
let startIndex = null;
let endIndex = null;
const range = this.calculateRange();
if (range) {
startIndex = range.startIndex;
endIndex = range.endIndex;
}
this.maybeNotify.updateDeps([
this.isScrolling,
startIndex,
endIndex
]);
return [
this.options.rangeExtractor,
this.options.overscan,
this.options.count,
startIndex,
endIndex,
this.options.lanes
];
}, (rangeExtractor, overscan, count, startIndex, endIndex, lanes) => {
return startIndex === null || endIndex === null ? [] : rangeExtractor({
startIndex,
endIndex,
overscan,
count,
lanes
});
}, {
key: false,
debug: () => this.options.debug
});
this.indexFromElement = (node) => {
const attributeName = this.options.indexAttribute;
const indexStr = node.getAttribute(attributeName);
if (!indexStr) {
console.warn(`Missing attribute name '${attributeName}={index}' on measured element.`);
return -1;
}
return parseInt(indexStr, 10);
};
this.shouldMeasureDuringScroll = (index) => {
var _a;
if (!isSmoothScroll(this.scrollState)) return true;
const scrollIndex = this.scrollState.index ?? ((_a = this.getVirtualItemForOffset(this.scrollState.lastTargetOffset)) == null ? void 0 : _a.index);
if (scrollIndex !== void 0 && this.range) {
const bufferSize = Math.max(this.options.overscan, Math.ceil((this.range.endIndex - this.range.startIndex) / 2));
const minIndex = Math.max(0, scrollIndex - bufferSize);
const maxIndex = Math.min(this.options.count - 1, scrollIndex + bufferSize);
return index >= minIndex && index <= maxIndex;
}
return true;
};
this.measureElement = (node) => {
if (!node) {
this.elementsCache.forEach((cached, key2) => {
if (!cached.isConnected) {
this.observer.unobserve(cached);
this.elementsCache.delete(key2);
}
});
return;
}
const index = this.indexFromElement(node);
if (!this.isIndexInRange(index)) return;
const key = this.options.getItemKey(index);
const prevNode = this.elementsCache.get(key);
if (prevNode !== node) {
if (prevNode) this.observer.unobserve(prevNode);
this.observer.observe(node);
this.elementsCache.set(key, node);
}
if (node.isConnected && (!this.isScrolling || this.scrollState) && this.shouldMeasureDuringScroll(index)) this.resizeItem(index, this.options.measureElement(node, void 0, this));
};
this.resizeItem = (index, size) => {
var _a, _b, _c;
if (!this.isIndexInRange(index)) return;
if ((_a = this._resizeBatch) == null ? void 0 : _a.sync) this.getMeasurements();
let cachedSize;
let itemStart;
let key;
const flat = (_b = this._singleLaneMeasurements) == null ? void 0 : _b.flat;
if (this.options.lanes === 1 && flat != null) {
key = this.options.getItemKey(index);
itemStart = flat[index * 2];
cachedSize = flat[index * 2 + 1];
} else {
const item = this.measurementsCache[index];
if (!item) return;
key = item.key;
itemStart = item.start;
cachedSize = item.size;
}
const itemSize = this.itemSizeCache.get(key) ?? cachedSize;
const delta = size - itemSize;
if (delta !== 0) {
const wasAtEnd = this.options.anchorTo === "end" && !isSmoothScroll(this.scrollState) && this.getVirtualDistanceFromEnd() <= this.options.scrollEndThreshold;
const prevTotalSize = wasAtEnd ? this._getLayoutTotalSize() : 0;
const scrollOffset = this.getScrollOffset();
const defaultShouldAdjust = !this.itemSizeCache.has(key) ? itemStart < scrollOffset : itemStart + itemSize <= scrollOffset && this.scrollDirection !== "backward";
const shouldAdjustScroll = !isSmoothScroll(this.scrollState) && (this.shouldAdjustScrollPositionOnItemSizeChange !== void 0 ? this.shouldAdjustScrollPositionOnItemSizeChange(this.measurementsCache[index] ?? {
index,
key,
start: itemStart,
size: cachedSize,
end: itemStart + cachedSize,
lane: 0
}, delta, this) : defaultShouldAdjust);
if (this.pendingMin === null || index < this.pendingMin) this.pendingMin = index;
this.itemSizeCache.set(key, size);
this.itemSizeCacheVersion++;
let adjustedSync = false;
if (!this._awaitingCommandReadBack()) {
if (wasAtEnd) adjustedSync = this.applyScrollAdjustment(this._getLayoutTotalSize() - prevTotalSize);
else if (shouldAdjustScroll) adjustedSync = this.applyScrollAdjustment(delta);
}
if (this._resizeBatch) {
this._resizeBatch.notify = true;
(_c = this._resizeBatch).sync || (_c.sync = adjustedSync);
return;
}
this.notify(adjustedSync);
this._noteClampMax();
this._flushHoldIfReady(true);
this._retryClampedAdjustment();
}
};
this.getVirtualItems = memo(() => [
this.getVirtualIndexes(),
this.getMeasurements(),
this._holdOffset
], (indexes, measurements, hold) => {
const virtualItems = [];
for (let k = 0, len = indexes.length; k < len; k++) {
const measurement = measurements[indexes[k]];
virtualItems.push(hold === 0 ? measurement : {
...measurement,
start: measurement.start - hold,
end: measurement.end - hold
});
}
return virtualItems;
}, {
key: false,
debug: () => this.options.debug
});
this.getVirtualItemForOffset = (offset) => {
var _a;
const measurements = this.getMeasurements();
if (measurements.length === 0) return;
const flat = (_a = this._singleLaneMeasurements) == null ? void 0 : _a.flat;
const useFlat = this.options.lanes === 1 && flat != null;
return notUndefined(measurements[findNearestBinarySearch(0, measurements.length - 1, useFlat ? (i) => flat[i * 2] : (i) => notUndefined(measurements[i]).start, offset)]);
};
this._noteClampMax = () => {
if (!this._awaitingCommandReadBack()) return;
const elementMax = this._elementMaxScrollOffset();
if (elementMax === null) return;
const write = this.pendingWrite;
const max = Math.max(elementMax, 0) + this._holdOffset;
if (max >= write.target) return;
const lowMaxes = write.lowMaxes ?? (write.lowMaxes = []);
if (lowMaxes[lowMaxes.length - 1] !== max) lowMaxes.push(max);
};
this.getMaxScrollOffset = () => (this._elementMaxScrollOffset() ?? 0) + this._holdOffset;
this._toLayoutOffset = (elementOffset) => {
var _a;
let offset = elementOffset + this._holdOffset;
if (((_a = this.pendingScrollAnchor) == null ? void 0 : _a.kind) === "anchor") offset += this.pendingScrollAnchor.delta;
return offset;
};
this._elementMaxScrollOffset = () => {
const el = this.scrollElement;
if (el === null) return null;
if ("scrollHeight" in el) return this.options.horizontal ? el.scrollWidth - el.clientWidth : el.scrollHeight - el.clientHeight;
if ("document" in el) {
const doc = el.document.documentElement;
return this.options.horizontal ? doc.scrollWidth - el.innerWidth : doc.scrollHeight - el.innerHeight;
}
return null;
};
this._momentumStop = null;
this._stopMomentum = (done) => {
const el = this.scrollElement;
const win = this.targetWindow;
if (el === null || win === null) return;
const scroller = "document" in el ? el.document.scrollingElement : el;
if (!(scroller == null ? void 0 : scroller.style)) return;
if (this._momentumStop) {
this._momentumStop.done = done;
return;
}
const { style } = scroller;
const property = this.options.horizontal ? "overflow-x" : "overflow-y";
const value = style.getPropertyValue(property);
const priority = style.getPropertyPriority(property);
const crossSize = () => this.options.horizontal ? scroller.clientHeight : scroller.clientWidth;
const crossSizeBefore = crossSize();
style.setProperty(property, "hidden", "important");
if (crossSize() !== crossSizeBefore) {
style.setProperty(property, value, priority);
return;
}
const stop = {
restore: () => {
if (style.getPropertyValue(property) !== "hidden" || style.getPropertyPriority(property) !== "important") return false;
style.setProperty(property, value, priority);
return true;
},
done
};
this._momentumStop = stop;
win.requestAnimationFrame(() => win.requestAnimationFrame(() => {
if (this._momentumStop !== stop) return;
this._momentumStop = null;
if (stop.restore()) stop.done();
}));
};
this._clampedBy = (target) => {
const elementMax = this._elementMaxScrollOffset();
if (elementMax === null) return null;
const maxAtWrite = elementMax + this._holdOffset;
return target > maxAtWrite + .5 ? {
target,
maxAtWrite
} : null;
};
this.getVirtualDistanceFromEnd = () => {
return Math.max(this._getLayoutTotalSize() + this.options.scrollMargin - this.getSize() - this.getScrollOffset(), 0);
};
this.getDistanceFromEnd = () => {
return Math.max(this.getMaxScrollOffset() - this.getScrollOffset(), 0);
};
this.isAtEnd = (threshold = this.options.scrollEndThreshold) => {
return this.getDistanceFromEnd() <= threshold;
};
this.getOffsetForAlignment = (toOffset, align, itemSize = 0) => {
if (!this.scrollElement) return 0;
const size = this.getSize();
const scrollOffset = this.getScrollOffset();
if (align === "auto") align = toOffset >= scrollOffset + size ? "end" : "start";
if (align === "center") toOffset += (itemSize - size) / 2;
else if (align === "end") toOffset -= size;
const maxOffset = this.getMaxScrollOffset();
return Math.max(Math.min(maxOffset, toOffset), 0);
};
this.getOffsetForIndex = (index, align = "auto") => {
index = Math.max(0, Math.min(index, this.options.count - 1));
const size = this.getSize();
const scrollOffset = this.getScrollOffset();
const item = this.getMeasurements()[index];
if (!item) return;
if (align === "auto") {
if (item.end >= scrollOffset + size - this.options.scrollPaddingEnd) align = "end";
else if (item.start <= scrollOffset + this.options.scrollPaddingStart) align = "start";
else return [scrollOffset, align];
}
if (align === "end" && index === this.options.count - 1) {
const maxOffset = this.getMaxScrollOffset();
const toOffset2 = maxOffset - this.options.paddingEnd + this.options.scrollPaddingEnd;
return [Math.max(Math.min(toOffset2, maxOffset), 0), align];
}
const toOffset = align === "end" ? item.end + this.options.scrollPaddingEnd : item.start - this.options.scrollPaddingStart;
return [this.getOffsetForAlignment(toOffset, align, item.size), align];
};
this.scrollToOffset = (toOffset, { align = "start", behavior = "auto" } = {}) => {
this._startScroll({
index: null,
align
}, this.getOffsetForAlignment(toOffset, align), behavior, "absolute");
};
this.scrollToIndex = (index, { align: initialAlign = "auto", behavior = "auto" } = {}) => {
index = Math.max(0, Math.min(index, this.options.count - 1));
const offsetInfo = this.getOffsetForIndex(index, initialAlign);
if (!offsetInfo) return;
const [offset, align] = offsetInfo;
this._startScroll({
index,
align
}, offset, behavior, "absolute");
};
this.scrollBy = (delta, { behavior = "auto" } = {}) => {
const offset = this.getOffsetForAlignment((this.getCommandWrittenOffset() ?? this.getScrollOffset()) + delta, "start");
this._startScroll({
index: null,
align: "start"
}, offset, behavior, "relative");
};
this.scrollToEnd = ({ behavior = "auto" } = {}) => {
if (this.options.count > 0) {
this._startScroll({
index: this.options.count - 1,
align: "end",
toEnd: true
}, Math.max(this.getMaxScrollOffset(), 0), behavior, "absolute");
return;
}
this.scrollToOffset(Math.max(this.getTotalSize() - this.getSize(), 0), { behavior });
};
this.cancelScroll = () => {
if (this.rafId != null && this.targetWindow) {
this.targetWindow.cancelAnimationFrame(this.rafId);
this.rafId = null;
}
this.scrollState = null;
};
this.getTotalSize = () => Math.max(this._getLayoutTotalSize() - this._holdOffset, 0);
this._getLayoutTotalSize = () => {
var _a, _b;
const measurements = this.getMeasurements();
let end;
if (measurements.length === 0) end = this.options.paddingStart;
else if (this.options.lanes === 1) {
const lastIdx = measurements.length - 1;
const flat = (_a = this._singleLaneMeasurements) == null ? void 0 : _a.flat;
if (flat != null) end = flat[lastIdx * 2] + flat[lastIdx * 2 + 1];
else end = ((_b = measurements[lastIdx]) == null ? void 0 : _b.end) ?? 0;
} else {
const endByLane = Array(this.options.lanes).fill(null);
let endIndex = measurements.length - 1;
while (endIndex >= 0 && endByLane.some((val) => val === null)) {
const item = measurements[endIndex];
if (endByLane[item.lane] === null) endByLane[item.lane] = item.end;
endIndex--;
}
end = Math.max(...endByLane.filter((val) => val !== null));
}
return Math.max(end - this.options.scrollMargin + this.options.paddingEnd, 0);
};
this.takeSnapshot = () => {
const snapshot = [];
if (this.itemSizeCache.size === 0) return snapshot;
const m = this.getMeasurements();
for (const item of m) if (item && this.itemSizeCache.has(item.key)) snapshot.push({
index: item.index,
key: item.key,
start: item.start,
size: item.size,
end: item.end,
lane: item.lane
});
return snapshot;
};
this._scrollToOffset = (offset, { adjustments, behavior } = {}) => {
const write = {
target: offset + (adjustments ?? 0),
smooth: behavior === "smooth"
};
this.pendingWrite = write;
this.options.scrollToFn(offset - this._holdOffset, {
behavior,
adjustments
}, this);
return write;
};
this.getCommandWrittenOffset = () => this.scrollState !== null && this.pendingWrite !== null && !this.pendingWrite.smooth ? this.pendingWrite.target : null;
this._awaitingCommandReadBack = () => {
const writtenOffset = this.getCommandWrittenOffset();
return !(isIOSWebKit() && this._iosGesture.dragging()) && writtenOffset !== null && !approxEqual(writtenOffset, this.getScrollOffset());
};
this._followOffsetTarget = (delta) => {
if (this.scrollState !== null && this.scrollState.index == null) this.scrollState.lastTargetOffset += delta;
};
this.measure = () => {
this.pendingMin = null;
this.itemSizeCache.clear();
this.laneAssignments.clear();
this.itemSizeCacheVersion++;
this.notify(false);
};
this.setOptions(opts);
}
get scrollAdjustments() {
return 0;
}
applyScrollAdjustment(delta, behavior) {
if (delta === 0) return false;
this._followOffsetTarget(delta);
if (!this._canWriteScroll()) {
this._holdOffset += delta;
if (this.scrollOffset !== null) this.scrollOffset += delta;
return true;
} else {
const offset = this.getScrollOffset();
this._clampedAdjustment = this._clampedBy(offset + delta);
const write = this._scrollToOffset(offset, {
adjustments: delta,
behavior
});
if (this.scrollOffset !== null) {
if (this.pendingWrite === write) this.scrollOffset += delta;
if (this.scrollOffset < 0) this.scrollOffset = 0;
}
return true;
}
}
scheduleScrollReconcile() {
if (!this.targetWindow) {
this.scrollState = null;
return;
}
if (this.rafId != null) return;
this.rafId = this.targetWindow.requestAnimationFrame(() => {
this.rafId = null;
this.reconcileScroll();
});
}
getScrollStateTarget(state) {
const offsetInfo = state.toEnd ? [Math.max(this.getMaxScrollOffset(), 0)] : state.index != null ? this.getOffsetForIndex(state.index, state.align) : void 0;
return offsetInfo ? offsetInfo[0] : state.lastTargetOffset;
}
reconcileScroll() {
if (!this.scrollState) return;
if (!this.scrollElement) return;
if (this.now() - this.scrollState.startedAt > 5e3) {
this.scrollState = null;
return;
}
if (this.scrollState.phase === "queued") {
this.scheduleScrollReconcile();
return;
}
this.getMeasurements();
const targetOffset = this.getScrollStateTarget(this.scrollState);
const STABLE_FRAMES = this.scrollState.index == null ? 1 : this.options.useAnimationFrameWithResizeObserver ? 3 : 2;
const targetChanged = targetOffset !== this.scrollState.lastTargetOffset;
if (!targetChanged && approxEqual(targetOffset, this.getScrollOffset())) {
if (this.scrollState.phase === "smooth") this.scrollState.phase = "smoothLanded";
else if (this.scrollState.phase === "smoothFinishing") this.scrollState.phase = "instant";
this.scrollState.stableFrames++;
if (this.scrollState.stableFrames >= STABLE_FRAMES) {
if (this.getScrollOffset() !== targetOffset) this._scrollToOffset(targetOffset, { behavior: "auto" });
this.scrollState = null;
return;
}
} else {
this.scrollState.stableFrames = 0;
if (targetChanged) {
const viewport = this.getSize() || 600;
const distance = Math.abs(targetOffset - this.getScrollOffset());
const keepSmooth = isSmoothScroll(this.scrollState) && distance > viewport;
this.scrollState.lastTargetOffset = targetOffset;
if (keepSmooth) this.scrollState.phase = "smooth";
else if (this.scrollState.phase === "smooth") this.scrollState.phase = "smoothFinishing";
else if (this.scrollState.phase === "smoothLanded") this.scrollState.phase = "instant";
this._scrollToOffset(targetOffset, { behavior: keepSmooth ? "smooth" : "auto" });
}
}
this.scheduleScrollReconcile();
}
_startScroll(target, offset, behavior, kind) {
this.pendingScrollAnchor = null;
this._clampedAdjustment = null;
const tail = this._iosGesture.tail();
if (kind === "absolute" && tail !== null) {
if (tail === "fling" && momentumOverridesWrites()) {
this._stopMomentum(() => {
const state = this.scrollState;
if ((state == null ? void 0 : state.phase) !== "queued" || this._iosGesture.tail() !== "fling" || this._reportedOverscroll) return;
this._iosGesture.end();
this._flushHoldIfReady(true);
this._writeAwaitingCommand();
});
this.scrollState = {
...target,
startedAt: this.now(),
lastTargetOffset: offset,
stableFrames: 0,
phase: "queued",
behavior,
samples: []
};
this.scheduleScrollReconcile();
return;
}
this._iosGesture.end();
}
this.scrollState = {
...target,
startedAt: this.now(),
lastTargetOffset: offset,
stableFrames: 0,
behavior,
phase: initialScrollPhase(behavior, target.index != null && approxEqual(offset, this.getScrollOffset()))
};
this._scrollToOffset(offset, { behavior });
this.scheduleScrollReconcile();
}
};
var findNearestBinarySearch = (low, high, getCurrentValue, value) => {
while (low <= high) {
const middle = (low + high) / 2 | 0;
const currentValue = getCurrentValue(middle);
if (currentValue < value) low = middle + 1;
else if (currentValue > value) high = middle - 1;
else return middle;
}
if (low > 0) return low - 1;
else return 0;
};
function findNearestBinarySearchFlat(flat, high, value) {
let low = 0;
while (low <= high) {
const middle = (low + high) / 2 | 0;
const currentValue = flat[middle * 2];
if (currentValue < value) low = middle + 1;
else if (currentValue > value) high = middle - 1;
else return middle;
}
return low > 0 ? low - 1 : 0;
}
function calculateRangeImpl(measurements, outerSize, scrollOffset, lanes, flat) {
const lastIndex = measurements.length - 1;
if (measurements.length <= lanes) return {
startIndex: 0,
endIndex: lastIndex
};
if (lanes === 1 && flat !== null) {
const startIndex2 = findNearestBinarySearchFlat(flat, lastIndex, scrollOffset);
let endIndex2 = startIndex2;
const limit = scrollOffset + outerSize;
while (endIndex2 < lastIndex && flat[endIndex2 * 2] + flat[endIndex2 * 2 + 1] < limit) endIndex2++;
return {
startIndex: startIndex2,
endIndex: endIndex2
};
}
const getStart = (index) => measurements[index].start;
let startIndex = findNearestBinarySearch(0, lastIndex, getStart, scrollOffset);
let endIndex = startIndex;
if (lanes === 1) while (endIndex < lastIndex && measurements[endIndex].end < scrollOffset + outerSize) endIndex++;
else if (lanes > 1) {
const endPerLane = Array(lanes).fill(0);
while (endIndex < lastIndex && endPerLane.some((pos) => pos < scrollOffset + outerSize)) {
const item = measurements[endIndex];
endPerLane[item.lane] = item.end;
endIndex++;
}
const startPerLane = Array(lanes).fill(scrollOffset + outerSize);
while (startIndex >= 0 && startPerLane.some((pos) => pos >= scrollOffset)) {
const item = measurements[startIndex];
startPerLane[item.lane] = item.start;
startIndex--;
}
startIndex = Math.max(0, startIndex - startIndex % lanes);
endIndex = Math.min(lastIndex, endIndex + (lanes - 1 - endIndex % lanes));
}
return {
startIndex,
endIndex
};
}
function useVirtualizerBase(options) {
const virtualizer = new Virtualizer(unref(options));
const state = shallowRef(virtualizer);
const cleanup = virtualizer._didMount();
watch(() => unref(options).getScrollElement(), () => {
virtualizer._willUpdate();
}, { immediate: true });
watch(() => unref(options), (options2) => {
virtualizer.setOptions({
...options2,
onChange: (instance, sync) => {
var _a;
triggerRef(state);
(_a = options2.onChange) == null || _a.call(options2, instance, sync);
}
});
virtualizer._willUpdate();
triggerRef(state);
}, { immediate: true });
onScopeDispose(cleanup);
return state;
}
function useVirtualizer(options) {
return useVirtualizerBase(computed(() => ({
observeElementRect,
observeElementOffset,
scrollToFn: elementScroll,
...unref(options)
})));
}
function afterRenderedFrame() {
return new Promise((resolve) => requestAnimationFrame(() => requestAnimationFrame(() => resolve())));
}
var _hoisted_1$20 = ["data-gallery-group"];
var _hoisted_2$15 = ["data-index", "onFocusin"];
var GalleryRows_default = defineComponent({
__name: "GalleryRows",
props: {
items: {},
group: {},
estimateRowSize: { type: Function }
},
setup(__props) {
const props = __props;
const context = inject(galleryViewportKey);
const providedResizePosition = inject(galleryResizePositionKey);
if (!context || !providedResizePosition) throw new Error("GalleryRows needs the parent gallery list and app scroll container.");
const resizePosition = providedResizePosition;
const { viewport, restoration, returningToTop } = context;
const list = useTemplateRef("list");
const geometry = shallowRef({
width: 0,
columns: 1,
gap: 0,
offset: 0,
headerHeight: 0
});
const focusedRow = shallowRef();
const restoringRow = shallowRef();
const resizeAnchor = shallowRef();
const columns = computed(() => geometry.value.columns);
const count = computed(() => Math.ceil(props.items.length / columns.value));
const rowKey = computed(() => {
const { items } = props;
const columnCount = columns.value;
return (index) => items[index * columnCount]?.href ?? index;
});
const rangeExtractor = computed(() => {
const retained = [focusedRow.value, restoringRow.value].filter((index) => index !== void 0);
return (range) => {
const visible = defaultRangeExtractor(range);
for (const index of retained) if (index < range.count && !visible.includes(index)) visible.push(index);
return visible.sort((a, b) => a - b);
};
});
function updateGeometry() {
const node = list.value;
const scroll = viewport.value;
if (!node || !scroll) return;
const bounds = node.getBoundingClientRect();
const { width } = bounds;
if (!width) return;
const style = getComputedStyle(node);
const gap = Number.parseFloat(style.getPropertyValue("--gallery-gap"));
const minWidth = Number.parseFloat(style.getPropertyValue("--gallery-min-column-width"));
const columns = Number(style.getPropertyValue("--gallery-fixed-columns")) || Math.max(1, Math.floor((width + gap) / (minWidth + gap)));
const offset = Math.round(bounds.top - scroll.getBoundingClientRect().top + scroll.scrollTop);
const headerHeight = scroll.querySelector(".masthead")?.getBoundingClientRect().height ?? 0;
const previous = geometry.value;
const resized = width !== previous.width || columns !== previous.columns || gap !== previous.gap;
if (resized && previous.width && !returningToTop.value) {
const anchor = resizePosition.value?.anchor ?? anchorBeforeResize(scroll.scrollTop);
if (anchor?.group === props.group) {
resizePosition.value = { anchor };
resizeAnchor.value = { ...anchor };
}
}
if (resized || offset !== previous.offset || headerHeight !== previous.headerHeight) geometry.value = {
width,
columns,
gap,
offset,
headerHeight
};
}
const virtualizer = useVirtualizer(computed(() => {
const { width, columns, gap, offset } = geometry.value;
const cardWidth = (width - (columns - 1) * gap) / columns;
const { items, estimateRowSize } = props;
return {
count: count.value,
enabled: width > 0,
getScrollElement: () => viewport.value,
getItemKey: rowKey.value,
gap,
scrollMargin: offset,
overscan: 3,
useAnimationFrameWithResizeObserver: true,
rangeExtractor: rangeExtractor.value,
estimateSize: (index) => estimateRowSize(items.slice(index * columns, (index + 1) * columns), cardWidth),
measureElement(element, entry, instance) {
const bounds = entry?.borderBoxSize[0] ?? element.getBoundingClientRect();
const measuredWidth = "inlineSize" in bounds ? bounds.inlineSize : bounds.width;
if (Math.abs(measuredWidth - width) > 1) {
const index = Number(element.dataset.index);
return instance.itemSizeCache.get(instance.options.getItemKey(index)) ?? instance.options.estimateSize(index);
}
return "blockSize" in bounds ? bounds.blockSize : bounds.height;
}
};
}));
const rows = computed(() => virtualizer.value.getVirtualItems().map((row) => ({
index: row.index,
top: row.start - geometry.value.offset,
items: props.items.slice(row.index * columns.value, (row.index + 1) * columns.value)
})));
function anchorBeforeResize(scrollTop) {
const { columns, offset, headerHeight, gap } = geometry.value;
const visibleTop = scrollTop + headerHeight;
const instance = virtualizer.value;
if (scrollTop <= 1 || visibleTop < offset || visibleTop >= offset + instance.getTotalSize()) return;
const row = instance.getVirtualItemForOffset(visibleTop);
const visibleRow = row && row.end <= visibleTop ? instance.getVirtualItemForOffset(row.end + gap + .01) : row;
const href = visibleRow && props.items[visibleRow.index * columns]?.href;
if (visibleRow && href) return {
href,
group: props.group,
offset: visibleRow.start - scrollTop
};
}
watch([returningToTop, resizeAnchor], ([returning, anchor]) => {
virtualizer.value.shouldAdjustScrollPositionOnItemSizeChange = returning || anchor ? () => false : void 0;
}, {
immediate: true,
flush: "sync"
});
watch([
list,
viewport,
() => props.estimateRowSize
], updateGeometry, { flush: "post" });
let geometryFrame = 0;
useResizeObserver(() => [
viewport.value,
viewport.value?.querySelector(".masthead"),
list.value,
list.value?.closest("main")
], () => {
cancelAnimationFrame(geometryFrame);
geometryFrame = requestAnimationFrame(updateGeometry);
});
onScopeDispose(() => {
cancelAnimationFrame(geometryFrame);
if (resizePosition.value?.anchor.group === props.group) resizePosition.value = void 0;
});
function measureRows() {
list.value?.querySelectorAll(".gallery-row").forEach(virtualizer.value.measureElement);
}
function measureRow(element) {
virtualizer.value.measureElement(element instanceof HTMLElement ? element : null);
}
watch([
() => geometry.value.width,
columns,
() => props.estimateRowSize
], async () => {
virtualizer.value.measure();
await nextTick();
measureRows();
}, { flush: "post" });
function restoreRow(node, scroll, index, anchor, resized) {
const row = node.querySelector(`[data-index="${index}"]`);
if (!row) return;
const bounds = row.getBoundingClientRect();
const viewportTop = scroll.getBoundingClientRect().top;
const headerBottom = (scroll.querySelector(".masthead")?.getBoundingClientRect().bottom ?? viewportTop) - viewportTop;
const offset = anchor.offset < scroll.clientHeight && anchor.offset + bounds.height > headerBottom ? anchor.offset : headerBottom;
const top = bounds.top - viewportTop + scroll.scrollTop - offset;
if (resized) {
scroll.scrollTo({
top,
behavior: "instant"
});
resizePosition.value = {
anchor,
scrollTop: scroll.scrollTop
};
} else virtualizer.value.scrollToOffset(top);
return row;
}
watch([
restoration,
resizeAnchor,
list,
returningToTop
], async ([historyAnchor, resized, node, returning], [previousHistory, , previousNode], onCleanup) => {
if (returning) {
resizePosition.value = void 0;
resizeAnchor.value = void 0;
return;
}
const anchor = resized ?? (historyAnchor !== previousHistory || node !== previousNode ? historyAnchor : void 0);
const scroll = viewport.value;
if (!anchor || anchor.group !== props.group || !node || !scroll) return;
const item = props.items.findIndex((item) => item.href === anchor.href);
if (item < 0) {
if (resized) {
resizePosition.value = void 0;
resizeAnchor.value = void 0;
}
return;
}
let cancelled = false;
onCleanup(() => {
cancelled = true;
restoringRow.value = void 0;
});
const index = Math.floor(item / columns.value);
restoringRow.value = index;
await afterRenderedFrame();
if (cancelled) return;
updateGeometry();
measureRows();
await nextTick();
if (cancelled) return;
const row = restoreRow(node, scroll, index, anchor, resized);
requestAnimationFrame(() => {
if (cancelled) return;
restoringRow.value = void 0;
if (resized) {
if (!row) resizePosition.value = void 0;
resizeAnchor.value = void 0;
}
});
}, { flush: "post" });
return (_ctx, _cache) => {
return openBlock(), createElementBlock("div", {
ref_key: "list",
ref: list,
class: "gallery-rows",
style: normalizeStyle({
height: unref(virtualizer).getTotalSize() + "px",
"--gallery-columns": columns.value
}),
"data-gallery-group": __props.group,
role: "list",
onFocusout: _cache[0] || (_cache[0] = ($event) => focusedRow.value = void 0)
}, [(openBlock(true), createElementBlock(Fragment, null, renderList(rows.value, (row) => {
return openBlock(), createElementBlock("div", {
key: row.items[0]?.href ?? row.index,
ref_for: true,
ref: measureRow,
class: "gallery-row",
"data-index": row.index,
style: normalizeStyle({ transform: `translateY(${row.top}px)` }),
role: "presentation",
onFocusin: ($event) => focusedRow.value = row.index
}, [(openBlock(true), createElementBlock(Fragment, null, renderList(row.items, (item, index) => {
return renderSlot(_ctx.$slots, "default", {
item,
position: row.index * columns.value + index + 1
}, void 0, void 0, item.href);
}), 128))], 44, _hoisted_2$15);
}), 128))], 44, _hoisted_1$20);
};
}
});
var _hoisted_1$19 = ["aria-labelledby"];
var _hoisted_2$14 = { class: "catalog-title flex flex-wrap items-end justify-between gap-4" };
var _hoisted_3$12 = ["id"];
var _hoisted_4$9 = {
key: 0,
class: "query"
};
var _hoisted_5$7 = { class: "catalog-controls" };
var _hoisted_6$7 = { class: "count" };
var _hoisted_7$7 = ["disabled"];
var _hoisted_8$7 = { class: "flex min-w-0 items-center gap-2" };
var _hoisted_9$7 = {
class: "view-switch flex",
role: "group",
"aria-label": "浏览布局"
};
var _hoisted_10$7 = ["aria-pressed"];
var _hoisted_11$7 = ["aria-pressed"];
var _hoisted_12$6 = {
key: 0,
class: "gallery-selection-bar",
role: "group",
"aria-label": "批量操作"
};
var _hoisted_13$6 = ["disabled"];
var _hoisted_14$6 = {
class: "count grow",
role: "status"
};
var _hoisted_15$4 = ["id"];
var _hoisted_16$4 = [
"data-gallery-href",
"data-scroll-item",
"aria-posinset",
"aria-setsize"
];
var _hoisted_17$4 = {
key: 0,
class: "card-selector"
};
var _hoisted_18$3 = { class: "card-selector-box" };
var _hoisted_19$2 = [
"aria-label",
"checked",
"disabled",
"onChange"
];
var _hoisted_20$2 = { class: "poster" };
var _hoisted_21$1 = ["src"];
var _hoisted_22$1 = {
key: 2,
class: "page-count"
};
var _hoisted_23$1 = { class: "card-meta" };
var _hoisted_24$1 = {
key: 0,
class: "category"
};
var _hoisted_25$1 = ["datetime"];
var _hoisted_26$1 = {
key: 2,
class: "posted"
};
var _hoisted_27$1 = {
key: 1,
class: "card-quick-action"
};
var _hoisted_28$1 = {
key: 1,
class: "catalog-empty"
};
var GalleryList_default = defineComponent({
__name: "GalleryList",
props: mergeModels({
title: {},
query: {},
items: {},
itemsTitle: {},
featured: {},
listKey: {},
bulkAction: {},
selectionBusy: { type: Boolean }
}, {
"selecting": {
type: Boolean,
required: true
},
"selectingModifiers": {}
}),
emits: mergeModels(["navigate", "applySelection"], ["update:selecting"]),
setup(__props, { emit: __emit }) {
const props = __props;
const { layout } = storeToRefs(usePreferencesStore());
const selecting = useModel(__props, "selecting");
const emit = __emit;
const headingId = useId();
const dateFormat = new Intl.DateTimeFormat("zh-CN", {
dateStyle: "medium",
timeStyle: "short"
});
const selectionStart = useTemplateRef("selectionStart");
const selectionExit = useTemplateRef("selectionExit");
const selectedHrefs = shallowRef(new Set());
provideGalleryResizePosition();
const estimateRowSize = computed(() => {
const listView = layout.value === "list";
return (items, cardWidth) => {
let metaHeight = 68.4;
for (const item of items) {
const lines = Number(Boolean(item.category)) + Number(item.recordedAt !== void 0 || Boolean(item.posted));
metaHeight = Math.max(metaHeight, 68.4 + 16.5 * lines);
}
return 2 + (listView ? Math.max(102.5, metaHeight) : Math.max(0, cardWidth - 2) * 1.25 + metaHeight);
};
});
const groups = computed(() => {
const main = {
id: "main",
title: props.itemsTitle,
items: props.items
};
return props.featured ? [{
id: "featured",
...props.featured
}, main] : [main];
});
const allItems = computed(() => {
if (!props.featured) return props.items;
const unique = new Map(props.featured.items.map((item) => [item.href, item]));
for (const item of props.items) unique.set(item.href, item);
return [...unique.values()];
});
const selectedItems = computed(() => allItems.value.filter((item) => selectedHrefs.value.has(item.href)));
const allSelected = computed(() => allItems.value.length > 0 && selectedItems.value.length === allItems.value.length);
watch(selecting, (active) => {
if (!active) selectedHrefs.value = new Set();
});
async function toggleSelection() {
selecting.value = !selecting.value;
await nextTick();
(selecting.value ? selectionExit.value : selectionStart.value)?.focus();
}
function changeSelection(href, event) {
if (!(event.target instanceof HTMLInputElement)) return;
const next = new Set(selectedHrefs.value);
if (event.target.checked) next.add(href);
else next.delete(href);
selectedHrefs.value = next;
}
function toggleAll() {
selectedHrefs.value = new Set(allSelected.value ? [] : allItems.value.map((item) => item.href));
}
return (_ctx, _cache) => {
return openBlock(), createElementBlock("section", { "aria-labelledby": unref(headingId) }, [
createBaseVNode("div", _hoisted_2$14, [createBaseVNode("div", null, [createBaseVNode("h1", {
id: unref(headingId),
tabindex: "-1"
}, toDisplayString(__props.title), 9, _hoisted_3$12), __props.query ? (openBlock(), createElementBlock("p", _hoisted_4$9, toDisplayString(__props.query), 1)) : createCommentVNode("", true)]), createBaseVNode("div", _hoisted_5$7, [
createBaseVNode("span", _hoisted_6$7, toDisplayString(allItems.value.length) + " 个画廊", 1),
renderSlot(_ctx.$slots, "controls"),
allItems.value.length && !selecting.value ? (openBlock(), createElementBlock("button", {
key: 0,
ref_key: "selectionStart",
ref: selectionStart,
type: "button",
class: "pill action-button",
disabled: __props.selectionBusy,
onClick: toggleSelection
}, " 多选 ", 8, _hoisted_7$7)) : createCommentVNode("", true),
createBaseVNode("div", _hoisted_8$7, [renderSlot(_ctx.$slots, "view-options"), createBaseVNode("div", _hoisted_9$7, [createBaseVNode("button", {
class: "icon-button",
type: "button",
"aria-label": "网格视图",
"aria-pressed": unref(layout) !== "list",
onClick: _cache[0] || (_cache[0] = ($event) => layout.value = "grid")
}, [createVNode(unref(Grid2x2), {
size: 17,
"aria-hidden": "true"
})], 8, _hoisted_10$7), createBaseVNode("button", {
class: "icon-button",
type: "button",
"aria-label": "列表视图",
"aria-pressed": unref(layout) === "list",
onClick: _cache[1] || (_cache[1] = ($event) => layout.value = "list")
}, [createVNode(unref(List), {
size: 18,
"aria-hidden": "true"
})], 8, _hoisted_11$7)])])
])]),
renderSlot(_ctx.$slots, "filters"),
renderSlot(_ctx.$slots, "notice"),
selecting.value ? (openBlock(), createElementBlock("div", _hoisted_12$6, [
createBaseVNode("button", {
ref_key: "selectionExit",
ref: selectionExit,
type: "button",
class: "pill action-button",
disabled: __props.selectionBusy,
onClick: toggleSelection
}, " 退出多选 ", 8, _hoisted_13$6),
createVNode(ActionButton_default, {
disabled: __props.selectionBusy || !allItems.value.length,
onClick: toggleAll
}, {
default: withCtx(() => [createTextVNode(toDisplayString(allSelected.value ? "取消全选" : "全选"), 1)]),
_: 1
}, 8, ["disabled"]),
createBaseVNode("span", _hoisted_14$6, "已选 " + toDisplayString(selectedItems.value.length) + " 项", 1),
createVNode(ActionButton_default, {
variant: __props.bulkAction === "delete" ? "danger-subtle" : "primary",
disabled: __props.selectionBusy || !selectedItems.value.length,
"aria-haspopup": __props.bulkAction === "delete" ? "dialog" : void 0,
onClick: _cache[2] || (_cache[2] = ($event) => emit("applySelection", selectedItems.value, $event))
}, {
default: withCtx(() => [createTextVNode(toDisplayString(__props.bulkAction === "save" ? "批量加入稍后阅读" : "批量删除"), 1)]),
_: 1
}, 8, [
"variant",
"disabled",
"aria-haspopup"
])
])) : createCommentVNode("", true),
(openBlock(true), createElementBlock(Fragment, null, renderList(groups.value, (group) => {
return openBlock(), createElementBlock(Fragment, { key: group.id }, [group.title && group.items.length ? (openBlock(), createElementBlock("h2", {
key: 0,
id: unref(headingId) + "-" + group.id,
class: "mt-8 border-b border-(--line) pb-3 text-xl font-semibold"
}, toDisplayString(group.title), 9, _hoisted_15$4)) : createCommentVNode("", true), group.items.length ? (openBlock(), createBlock(GalleryRows_default, {
key: __props.listKey,
class: normalizeClass(["catalog-grid", { "list-view": unref(layout) === "list" }]),
items: group.items,
group: group.id,
"estimate-row-size": estimateRowSize.value,
"aria-labelledby": group.title ? unref(headingId) + "-" + group.id : unref(headingId)
}, {
default: withCtx(({ item, position }) => [createBaseVNode("article", {
class: normalizeClass(["gallery-card", { "is-selected": selecting.value && selectedHrefs.value.has(item.href) }]),
"data-gallery-href": item.href,
"data-scroll-item": group.id === "main" ? item.href : void 0,
"aria-posinset": position,
"aria-setsize": group.items.length,
role: "listitem"
}, [
selecting.value ? (openBlock(), createElementBlock("label", _hoisted_17$4, [createBaseVNode("span", _hoisted_18$3, [createBaseVNode("input", {
type: "checkbox",
"aria-label": "选择 " + item.title,
checked: selectedHrefs.value.has(item.href),
disabled: __props.selectionBusy,
onChange: ($event) => changeSelection(item.href, $event)
}, null, 40, _hoisted_19$2)])])) : createCommentVNode("", true),
(openBlock(), createBlock(resolveDynamicComponent(selecting.value ? "div" : "a"), {
class: "card-link",
href: selecting.value ? void 0 : item.href,
onClick: ($event) => !selecting.value && emit("navigate", $event, item.href)
}, {
default: withCtx(() => [createBaseVNode("div", _hoisted_20$2, [item.cover ? (openBlock(), createElementBlock("img", {
key: 0,
src: item.cover,
alt: "",
loading: "lazy",
decoding: "async"
}, null, 8, _hoisted_21$1)) : (openBlock(), createBlock(unref(Image$1), {
key: 1,
size: 24,
class: "muted",
"aria-hidden": "true"
})), item.progressIndex || item.pages ? (openBlock(), createElementBlock("span", _hoisted_22$1, [item.progressIndex && item.pages >= item.progressIndex ? (openBlock(), createElementBlock(Fragment, { key: 0 }, [createTextVNode(toDisplayString(item.progressIndex) + "/" + toDisplayString(item.pages) + " 页 ", 1)], 64)) : item.progressIndex ? (openBlock(), createElementBlock(Fragment, { key: 1 }, [createTextVNode("第 " + toDisplayString(item.progressIndex) + " 页", 1)], 64)) : (openBlock(), createElementBlock(Fragment, { key: 2 }, [createTextVNode(toDisplayString(item.pages) + " 页", 1)], 64))])) : createCommentVNode("", true)]), createBaseVNode("div", _hoisted_23$1, [
item.category ? (openBlock(), createElementBlock("p", _hoisted_24$1, toDisplayString(item.category), 1)) : createCommentVNode("", true),
(openBlock(), createBlock(resolveDynamicComponent(group.title ? "h3" : "h2"), { class: "card-title" }, {
default: withCtx(() => [createTextVNode(toDisplayString(item.title), 1)]),
_: 2
}, 1024)),
item.recordedAt !== void 0 ? (openBlock(), createElementBlock("time", {
key: 1,
class: "posted",
datetime: new Date(item.recordedAt).toISOString()
}, toDisplayString(unref(dateFormat).format(item.recordedAt)), 9, _hoisted_25$1)) : item.posted ? (openBlock(), createElementBlock("p", _hoisted_26$1, toDisplayString(item.posted), 1)) : createCommentVNode("", true)
])]),
_: 2
}, 1032, ["href", "onClick"])),
!selecting.value && _ctx.$slots.quickAction ? (openBlock(), createElementBlock("div", _hoisted_27$1, [renderSlot(_ctx.$slots, "quickAction", { item })])) : createCommentVNode("", true)
], 10, _hoisted_16$4)]),
_: 2
}, 1032, [
"class",
"items",
"group",
"estimate-row-size",
"aria-labelledby"
])) : createCommentVNode("", true)], 64);
}), 128)),
!allItems.value.length ? (openBlock(), createElementBlock("div", _hoisted_28$1, [renderSlot(_ctx.$slots, "empty")])) : createCommentVNode("", true)
], 8, _hoisted_1$19);
};
}
});
var _hoisted_1$18 = [
"aria-label",
"aria-expanded",
"aria-disabled"
];
var GalleryMoreButton_default = defineComponent({
__name: "GalleryMoreButton",
props: {
title: {},
expanded: { type: Boolean },
busy: { type: Boolean }
},
setup(__props) {
return (_ctx, _cache) => {
return openBlock(), createElementBlock("button", {
class: "card-more",
type: "button",
"aria-label": "画廊操作:" + __props.title,
"aria-haspopup": "dialog",
"aria-expanded": __props.expanded,
"aria-disabled": __props.busy
}, [createVNode(unref(Ellipsis), {
size: 20,
"aria-hidden": "true"
})], 8, _hoisted_1$18);
};
}
});
var _hoisted_1$17 = ["aria-checked", "aria-busy"];
var _hoisted_2$13 = {
key: 0,
class: "filters flex",
"aria-label": "画廊分类"
};
var _hoisted_3$11 = [
"aria-current",
"href",
"onClick"
];
var _hoisted_4$8 = { class: "empty" };
var CatalogPage_default = defineComponent({
__name: "CatalogPage",
props: mergeModels({
page: {},
items: {},
featured: {},
listKey: {},
savedHrefs: {},
busy: { type: Boolean },
desktop: { type: Boolean },
pendingUrl: {},
openActionHref: {}
}, {
"selecting": {
type: Boolean,
required: true
},
"selectingModifiers": {}
}),
emits: mergeModels([
"navigate",
"changeFilters",
"saveSelected",
"toggleReadLater",
"openActions"
], ["update:selecting"]),
setup(__props, { emit: __emit }) {
const props = __props;
const selecting = useModel(__props, "selecting");
const emit = __emit;
const filtersPending = computed(() => Boolean(props.pendingUrl && props.pendingUrl === props.page.defaultFilters?.href));
const filtersDisabled = computed(() => {
const disabled = props.page.defaultFilters?.disabled ?? false;
return filtersPending.value ? !disabled : disabled;
});
function toggleFilters(event) {
const filters = props.page.defaultFilters;
if (filters) emit("changeFilters", filtersPending.value ? void 0 : filters.href, event.currentTarget);
}
return (_ctx, _cache) => {
return openBlock(), createBlock(GalleryList_default, {
selecting: selecting.value,
"onUpdate:selecting": _cache[0] || (_cache[0] = ($event) => selecting.value = $event),
title: __props.page.title,
query: __props.page.query,
items: __props.items,
"items-title": __props.page.itemsTitle,
featured: __props.featured,
"list-key": __props.listKey,
"bulk-action": "save",
"selection-busy": __props.busy,
onNavigate: _cache[1] || (_cache[1] = (event, href) => emit("navigate", event, href)),
onApplySelection: _cache[2] || (_cache[2] = (items, event) => emit("saveSelected", items, event))
}, {
"view-options": withCtx(() => [__props.page.defaultFilters ? (openBlock(), createElementBlock("button", {
key: 0,
class: "pill action-button filter-switch",
type: "button",
role: "switch",
"aria-checked": filtersDisabled.value,
"aria-busy": filtersPending.value,
onClick: toggleFilters
}, [..._cache[3] || (_cache[3] = [createTextVNode(" 忽略过滤 ", -1), createBaseVNode("span", {
class: "filter-switch-track",
"aria-hidden": "true"
}, null, -1)])], 8, _hoisted_1$17)) : createCommentVNode("", true)]),
filters: withCtx(() => [__props.page.categories.length ? (openBlock(), createElementBlock("nav", _hoisted_2$13, [(openBlock(true), createElementBlock(Fragment, null, renderList(__props.page.categories, (category) => {
return openBlock(), createElementBlock("a", {
key: category.label,
class: "pill",
"aria-current": category.selected ? "true" : void 0,
href: category.href,
onClick: ($event) => emit("navigate", $event, category.href)
}, toDisplayString(category.label), 9, _hoisted_3$11);
}), 128))])) : createCommentVNode("", true)]),
empty: withCtx(() => [createBaseVNode("p", _hoisted_4$8, toDisplayString(__props.page.emptyMessage ?? "没有找到画廊。可以试试其他关键词或分类。"), 1)]),
quickAction: withCtx(({ item }) => [__props.desktop ? (openBlock(), createBlock(BookmarkButton_default, {
key: 0,
"catalog-title": item.title,
saved: __props.savedHrefs.has(item.href),
busy: __props.busy,
onToggle: ($event) => emit("toggleReadLater", $event, item)
}, null, 8, [
"catalog-title",
"saved",
"busy",
"onToggle"
])) : (openBlock(), createBlock(GalleryMoreButton_default, {
key: 1,
title: item.title,
expanded: __props.openActionHref === item.href,
busy: __props.busy,
onClick: ($event) => emit("openActions", $event, item)
}, null, 8, [
"title",
"expanded",
"busy",
"onClick"
]))]),
_: 1
}, 8, [
"selecting",
"title",
"query",
"items",
"items-title",
"featured",
"list-key",
"selection-busy"
]);
};
}
});
function appendUnique(current, incoming, key) {
const seen = new Set(current.map(key));
return current.concat(incoming.filter((item) => {
const itemKey = key(item);
if (seen.has(itemKey)) return false;
seen.add(itemKey);
return true;
}));
}
async function stopScrollMomentum(viewport) {
viewport.classList.add("stop-scroll");
await afterRenderedFrame();
viewport.classList.remove("stop-scroll");
}
var _hoisted_1$16 = [
"aria-label",
"title",
"disabled"
];
var BackToTopButton_default = defineComponent({
inheritAttrs: false,
__name: "BackToTopButton",
props: {
visible: { type: Boolean },
label: { default: "回到顶部" },
title: {},
disabled: { type: Boolean }
},
setup(__props) {
return (_ctx, _cache) => {
return openBlock(), createBlock(Transition, { name: "back-to-top" }, {
default: withCtx(() => [__props.visible ? (openBlock(), createElementBlock("button", mergeProps({ key: 0 }, _ctx.$attrs, {
class: "icon-button back-to-top",
type: "button",
"aria-label": __props.label,
title: __props.title ?? __props.label,
disabled: __props.disabled
}), [createVNode(unref(ArrowUp), {
size: 21,
"aria-hidden": "true"
})], 16, _hoisted_1$16)) : createCommentVNode("", true)]),
_: 1
});
};
}
});
var edgeResistance = .55;
function isAtEdge(element, viewport, bottom, edgeDistance) {
if (edgeDistance(element) > 1) return false;
if (!bottom) return (viewport?.offsetTop ?? 0) <= 1;
return !viewport || viewport.scale <= 1.01 || viewport.offsetTop + viewport.height >= element.getBoundingClientRect().bottom - 1;
}
function acceptsScrollEdgeTarget(target, element) {
if (!(target instanceof Element)) return true;
if (target.closest("dialog") !== element.closest("dialog")) return false;
if (target.closest("select, textarea, [contenteditable], .site-sidebar, .tag-suggestions")) return false;
const input = target.closest("input");
return !input || input.matches(".card-selector input[type='checkbox']");
}
function getFingerPosition(touch, scale, viewport) {
if (!viewport || scale <= 1.01) return {
x: touch.clientX,
y: touch.clientY
};
return {
x: (touch.pageX - viewport.pageLeft) * scale,
y: (touch.pageY - viewport.pageTop) * scale
};
}
function applyEdgeResistance(raw, maxDistance) {
const resisted = Math.max(0, raw) * edgeResistance;
return maxDistance * resisted / (maxDistance + resisted);
}
function removeEdgeResistance(displacement, maxDistance) {
return displacement * maxDistance / (edgeResistance * (maxDistance - displacement));
}
var momentumGap = 120;
var firstMomentumGap = 250;
function createEdgeMomentum(options) {
const { direction } = options;
let momentum;
function track(element, event) {
const { getPull, blocked, atEdge, edgeDistance, enterNativeEdge, rebound } = options;
const top = element.scrollTop;
const current = getPull();
const previous = current?.nativeSample ?? momentum;
if (!previous) return;
const elapsed = event.timeStamp - previous.time;
const advance = direction * (previous.top - top);
const viewport = window.visualViewport;
if (current) {
if (!current.nativeScroll || current.rawOffset !== void 0 || !advance) return;
const boundary = atEdge(element, viewport);
let speed;
if (advance > 0 && elapsed <= momentumGap) speed = boundary && previous.speed || advance * 1e3 / Math.max(8, elapsed);
current.nativeSample = {
top,
time: event.timeStamp,
speed
};
if (advance > 0 && boundary && !blocked() && current.crossing && current.scale <= 1.01) enterNativeEdge(current, current.crossing, viewport, Math.max(8, elapsed));
return;
}
const fling = momentum;
if (!fling) return;
const gap = fling.first ? firstMomentumGap : momentumGap;
if (blocked() || elapsed > gap || advance < 0 || (viewport?.scale ?? 1) > 1.01) {
momentum = void 0;
return;
}
if (atEdge(element, viewport) && advance > 0) {
momentum = void 0;
const distanceToEdge = advance + Math.min(0, edgeDistance(element));
const impactAge = fling.first ? 0 : Math.max(0, elapsed - distanceToEdge * 1e3 / fling.speed);
rebound(fling.speed, impactAge);
} else {
if (!advance) return;
const speed = advance * 1e3 / Math.max(8, elapsed);
momentum = {
top,
time: event.timeStamp,
speed,
first: false
};
}
}
function clear() {
momentum = void 0;
}
function finishScroll() {
if (!momentum?.first) clear();
}
function begin(top, time, speed) {
momentum = {
top,
time,
speed,
first: true
};
}
return {
track,
clear,
finishScroll,
begin
};
}
var holdDistance = 52;
function useScrollEdgeGesture(surface, indicatorEnabled, reducedMotion, options, stretch, handoff) {
const { bottom, direction, blocked, dragging, indicator, distance, scrollFromEdge, atEdge, edgeDistance, leaveEdge, paintPull, beginPull, reversePull, rebound, settle, stopMotion, resetStretch, mergeCarriedOffset } = stretch;
const { totalOffset, ready } = stretch.feedback;
const { releaseCarriedOffset } = handoff;
let pull;
const momentum = createEdgeMomentum({
direction,
getPull: () => pull,
blocked: () => blocked.value,
atEdge,
edgeDistance,
enterNativeEdge,
rebound
});
function viewportAtEdge(current, viewport) {
const element = surface.value;
return !!element && atEdge(element, viewport) && (!current.edge || Math.abs((viewport?.offsetLeft ?? 0) - current.edge.viewportLeft) * current.scale <= 6) && Math.abs((viewport?.scale ?? 1) - current.scale) <= .01;
}
function detach() {
const current = pull;
current?.listeners.abort();
pull = void 0;
dragging.value = false;
return current;
}
function cancel() {
momentum.clear();
const current = detach();
if (current && !releaseCarriedOffset(0) && (current.rawOffset !== void 0 || current.holdingSpring)) settle(0);
}
function enterNativeEdge(current, crossing, viewport, elapsed) {
current.crossing = void 0;
current.lastEdgeDistance = 0;
current.edge = {
x: crossing.x,
y: crossing.y - direction * (crossing.excess + 6),
viewportLeft: viewport?.offsetLeft ?? 0
};
if (crossing.excess > 0) {
beginPull(current);
paintPull(current, (current.rawOffset ?? 0) + crossing.excess, elapsed);
}
}
function trackMomentum(event) {
const element = surface.value;
if (!element) return;
if (!bottom || totalOffset.value) scrollFromEdge.value = Math.max(0, edgeDistance(element));
momentum.track(element, event);
}
function recognizeVerticalPull(current, finger) {
if (current.vertical) return true;
const dx = Math.abs(finger.x - current.start.x);
const dy = Math.abs(finger.y - current.start.y);
if (Math.max(dx, dy) < 6) return false;
if (dx >= dy) {
cancel();
return false;
}
current.vertical = true;
return true;
}
function reachPullEdge(current, finger, viewport, travel, elapsed, previousEdgeDistance) {
if (!viewportAtEdge(current, viewport)) {
leaveEdge(current, true);
if (current.scale <= 1.01) {
current.nativeScroll = true;
current.crossing = travel > 0 ? {
...finger,
excess: Math.max(0, travel - current.lastEdgeDistance * current.scale)
} : void 0;
}
return false;
}
if (!current.edge) {
if (travel <= 0) return false;
if (current.nativeScroll && current.scale <= 1.01) {
const excess = current.crossing ? current.crossing.excess + travel : Math.max(0, travel - previousEdgeDistance * current.scale);
enterNativeEdge(current, {
...finger,
excess
}, viewport, elapsed);
return false;
}
const overshoot = current.scale <= 1.01 ? Math.max(0, travel - previousEdgeDistance) : 0;
current.edge = {
x: finger.x,
y: finger.y - direction * overshoot,
viewportLeft: viewport?.offsetLeft ?? 0
};
}
return true;
}
function sampleTouch(current, element, y, travel, time) {
if (travel && !totalOffset.value) {
current.loadingHandoff = false;
current.layoutAnchor = void 0;
}
const elapsed = Math.max(8, time - current.time);
current.velocity = travel * 1e3 / elapsed;
current.lastFingerY = y;
current.lastEdgeDistance = Math.max(0, edgeDistance(element));
scrollFromEdge.value = current.lastEdgeDistance;
current.time = time;
return elapsed;
}
function move(event) {
const current = pull;
if (!current) return;
const element = surface.value;
const viewport = window.visualViewport;
const touch = event.touches[0];
if (!element || !touch || event.touches.length !== 1 || touch.identifier !== current.id || blocked.value || Math.abs((viewport?.scale ?? 1) - current.scale) > .01) {
cancel();
return;
}
const finger = getFingerPosition(touch, current.scale, viewport);
if (!recognizeVerticalPull(current, finger)) return;
const previousEdgeDistance = current.lastEdgeDistance;
const travel = direction * (finger.y - current.lastFingerY);
const elapsed = sampleTouch(current, element, finger.y, travel, event.timeStamp);
if (!reachPullEdge(current, finger, viewport, travel, elapsed, previousEdgeDistance) || !current.edge) return;
if (travel < 0 && current.rawOffset !== void 0) {
reversePull(current, element, event, travel, elapsed);
return;
}
const dy = direction * (finger.y - current.edge.y);
if (travel < 0 && (current.rawOffset ?? 0) + dy <= 6) {
leaveEdge(current);
return;
}
if (current.rawOffset === void 0) {
const dx = Math.abs(finger.x - current.edge.x);
if (dy <= 6 || !current.nativeScroll && dy <= dx) return;
beginPull(current);
}
if (indicator.value && event.cancelable && current.scale <= 1.01) event.preventDefault();
paintPull(current, (current.rawOffset ?? 0) + dy - 6, elapsed);
}
function start(event) {
cancel();
const element = surface.value;
const touch = event.touches[0];
const target = event.target;
if (blocked.value || !element || !touch || event.touches.length !== 1 || !acceptsScrollEdgeTarget(target, element)) return;
const viewport = window.visualViewport;
const zoom = viewport?.scale ?? 1;
const atBoundary = atEdge(element, viewport);
const holdingSpring = atBoundary && distance.value > 0;
if (holdingSpring) stopMotion();
const start = getFingerPosition(touch, zoom, viewport);
const listeners = new AbortController();
const top = element.scrollTop;
scrollFromEdge.value = Math.max(0, edgeDistance(element));
pull = {
listeners,
id: touch.identifier,
start,
startScrollTop: top,
scale: zoom,
holdingSpring,
edge: atBoundary ? {
...start,
viewportLeft: viewport?.offsetLeft ?? 0
} : void 0,
nativeScroll: !atBoundary && zoom <= 1.01,
nativeSample: {
top,
time: event.timeStamp
},
lastFingerY: start.y,
lastEdgeDistance: Math.max(0, edgeDistance(element)),
time: event.timeStamp,
velocity: 0
};
const source = target ?? element;
const { signal } = listeners;
const onMove = (event) => move(event);
const onEnd = (event) => void end(event);
source.addEventListener("touchmove", onMove, {
capture: true,
passive: false,
signal
});
source.addEventListener("touchend", onEnd, {
passive: true,
signal
});
source.addEventListener("touchcancel", onEnd, {
passive: true,
signal
});
}
function releaseNativeMomentum(current, event, velocity, cancelled) {
const element = surface.value;
const sample = current.nativeSample;
const nativeSpeed = event.timeStamp - sample.time <= 80 ? sample.speed : void 0;
const speed = nativeSpeed ?? velocity;
if (current.nativeScroll && !blocked.value && element && !reducedMotion.value && velocity >= 0 && speed > 0 && !event.touches.length) {
const top = element.scrollTop;
if (!cancelled || nativeSpeed !== void 0 || direction * (current.startScrollTop - top) > 1) {
if (atEdge(element, window.visualViewport)) rebound(speed);
else momentum.begin(top, event.timeStamp, speed);
}
}
}
async function end(event) {
const readyToRefresh = ready.value;
const current = detach();
if (!current) return;
const cancelled = event.type === "touchcancel";
const velocity = event.timeStamp - current.time < 80 ? current.velocity : 0;
if (options.edge === "top" && !cancelled && readyToRefresh && event.touches.length === 0 && indicatorEnabled.value && viewportAtEdge(current, window.visualViewport)) {
mergeCarriedOffset();
settle(holdDistance, velocity);
try {
await options.refresh();
} finally {
settle(0);
}
return;
}
if (releaseCarriedOffset(velocity)) return;
if (current.holdingSpring) {
settle(0);
return;
}
if (current.rawOffset === void 0) {
releaseNativeMomentum(current, event, velocity, cancelled);
return;
}
settle(0, velocity);
}
function observePull() {
const target = computed(() => bottom && blocked.value ? null : surface.value);
useEventListener$1(target, "touchstart", start, { passive: true });
useEventListener$1(target, "scroll", trackMomentum, { passive: true });
useEventListener$1(target, [
"pointerdown",
"wheel",
"keydown"
], momentum.clear, { passive: true });
useEventListener$1(target, "scrollend", momentum.finishScroll, { passive: true });
watch(blocked, (value) => {
if (!value) return;
cancel();
if (bottom) resetStretch();
});
onScopeDispose(detach);
}
observePull();
return {
captureLoad: () => handoff.captureLoad(() => pull),
reconcileEdge: () => handoff.reconcileEdge(pull)
};
}
function useScrollEdgeHandoff(surface, stretch) {
const { direction, dragging, indicator, scrollFromEdge, edgeDistance, atEdge, leaveEdge, settleCarriedOffset } = stretch;
const { carriedOffset, totalOffset } = stretch.feedback;
function absorbOffset(element, pixels) {
const before = element.scrollTop;
element.scrollTo({
top: before - direction * pixels,
behavior: "instant"
});
scrollFromEdge.value = Math.max(0, edgeDistance(element));
const remaining = pixels + direction * (element.scrollTop - before);
carriedOffset.value = remaining > 1 ? remaining : 0;
}
function releaseCarriedOffset(velocity) {
if (!carriedOffset.value) return false;
const element = surface.value;
if (element && edgeDistance(element) > 1) absorbOffset(element, carriedOffset.value);
if (!carriedOffset.value) return false;
settleCarriedOffset(velocity);
return true;
}
function captureLoad(getPull) {
const current = getPull();
const element = surface.value;
if (!current || !element || indicator.value === "refresh") return;
if (!current.loadingHandoff && (indicator.value || !totalOffset.value || !dragging.value && !current.holdingSpring)) return;
return {
anchor: current.layoutAnchor,
restore(anchor, shift) {
if (getPull() !== current || surface.value !== element) return false;
const pixels = totalOffset.value - direction * shift;
leaveEdge(current);
absorbOffset(element, pixels);
current.loadingHandoff = true;
current.layoutAnchor = anchor;
current.lastEdgeDistance = Math.max(0, edgeDistance(element));
current.velocity = 0;
return true;
}
};
}
function reconcileEdge(current) {
const element = surface.value;
if (element) scrollFromEdge.value = Math.max(0, edgeDistance(element));
if (!current || !element || atEdge(element, window.visualViewport)) return;
if (carriedOffset.value && edgeDistance(element) > 1) absorbOffset(element, carriedOffset.value);
if (current.edge && !atEdge(element, window.visualViewport)) {
leaveEdge(current, true);
if (current.scale <= 1.01) current.nativeScroll = true;
}
}
return {
captureLoad,
reconcileEdge,
releaseCarriedOffset
};
}
var isClient = typeof window !== "undefined" && typeof document !== "undefined";
typeof WorkerGlobalScope !== "undefined" && globalThis instanceof WorkerGlobalScope;
function getLifeCycleTarget(target) {
return target || getCurrentInstance();
}
function tryOnUnmounted(fn, target) {
if (getLifeCycleTarget(target)) onUnmounted(fn, target);
}
isClient && window.document;
isClient && window.navigator;
isClient && window.location;
var defaultTimestep = 1 / 60 * 1e3;
var getCurrentTime = typeof performance !== "undefined" ? () => performance.now() : () => Date.now();
var onNextFrame = typeof window !== "undefined" ? (callback) => window.requestAnimationFrame(callback) : (callback) => setTimeout(() => callback(getCurrentTime()), defaultTimestep);
function createRenderStep(runNextFrame) {
let toRun = [];
let toRunNextFrame = [];
let numToRun = 0;
let isProcessing = false;
let flushNextFrame = false;
const toKeepAlive = new WeakSet();
const step = {
schedule: (callback, keepAlive = false, immediate = false) => {
const addToCurrentFrame = immediate && isProcessing;
const buffer = addToCurrentFrame ? toRun : toRunNextFrame;
if (keepAlive) toKeepAlive.add(callback);
if (buffer.indexOf(callback) === -1) {
buffer.push(callback);
if (addToCurrentFrame && isProcessing) numToRun = toRun.length;
}
return callback;
},
cancel: (callback) => {
const index = toRunNextFrame.indexOf(callback);
if (index !== -1) toRunNextFrame.splice(index, 1);
toKeepAlive.delete(callback);
},
process: (frameData) => {
if (isProcessing) {
flushNextFrame = true;
return;
}
isProcessing = true;
[toRun, toRunNextFrame] = [toRunNextFrame, toRun];
toRunNextFrame.length = 0;
numToRun = toRun.length;
if (numToRun) for (let i = 0; i < numToRun; i++) {
const callback = toRun[i];
callback(frameData);
if (toKeepAlive.has(callback)) {
step.schedule(callback);
runNextFrame();
}
}
isProcessing = false;
if (flushNextFrame) {
flushNextFrame = false;
step.process(frameData);
}
}
};
return step;
}
var maxElapsed = 40;
var useDefaultElapsed = true;
var runNextFrame = false;
var isProcessing = false;
var frame = {
delta: 0,
timestamp: 0
};
var stepsOrder = [
"read",
"update",
"preRender",
"render",
"postRender"
];
var steps = stepsOrder.reduce((acc, key) => {
acc[key] = createRenderStep(() => runNextFrame = true);
return acc;
}, {});
var sync = stepsOrder.reduce((acc, key) => {
const step = steps[key];
acc[key] = (process, keepAlive = false, immediate = false) => {
if (!runNextFrame) startLoop();
return step.schedule(process, keepAlive, immediate);
};
return acc;
}, {});
var cancelSync = stepsOrder.reduce((acc, key) => {
acc[key] = steps[key].cancel;
return acc;
}, {});
stepsOrder.reduce((acc, key) => {
acc[key] = () => steps[key].process(frame);
return acc;
}, {});
var processStep = (stepId) => steps[stepId].process(frame);
var processFrame = (timestamp) => {
runNextFrame = false;
frame.delta = useDefaultElapsed ? defaultTimestep : Math.max(Math.min(timestamp - frame.timestamp, maxElapsed), 1);
frame.timestamp = timestamp;
isProcessing = true;
stepsOrder.forEach(processStep);
isProcessing = false;
if (runNextFrame) {
useDefaultElapsed = false;
onNextFrame(processFrame);
}
};
var startLoop = () => {
runNextFrame = true;
useDefaultElapsed = true;
if (!isProcessing) onNextFrame(processFrame);
};
var getFrameData = () => frame;
function __rest(s, e) {
var t = {};
for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p) && e.indexOf(p) < 0) t[p] = s[p];
if (s != null && typeof Object.getOwnPropertySymbols === "function") {
for (var i = 0, p = Object.getOwnPropertySymbols(s); i < p.length; i++) if (e.indexOf(p[i]) < 0 && Object.prototype.propertyIsEnumerable.call(s, p[i])) t[p[i]] = s[p[i]];
}
return t;
}
var clamp$1 = (min, max, v) => Math.min(Math.max(v, min), max);
var safeMin = .001;
var minDuration = .01;
var minDamping = .05;
function findSpring({ duration = 800, bounce = .25, velocity = 0, mass = 1 }) {
let envelope;
let derivative;
let dampingRatio = 1 - bounce;
dampingRatio = clamp$1(minDamping, 1, dampingRatio);
duration = clamp$1(minDuration, 10, duration / 1e3);
if (dampingRatio < 1) {
envelope = (undampedFreq) => {
const exponentialDecay = undampedFreq * dampingRatio;
const delta = exponentialDecay * duration;
const a = exponentialDecay - velocity;
const b = calcAngularFreq(undampedFreq, dampingRatio);
const c = Math.exp(-delta);
return safeMin - a / b * c;
};
derivative = (undampedFreq) => {
const delta = undampedFreq * dampingRatio * duration;
const d = delta * velocity + velocity;
const e = Math.pow(dampingRatio, 2) * Math.pow(undampedFreq, 2) * duration;
const f = Math.exp(-delta);
const g = calcAngularFreq(Math.pow(undampedFreq, 2), dampingRatio);
return (-envelope(undampedFreq) + safeMin > 0 ? -1 : 1) * ((d - e) * f) / g;
};
} else {
envelope = (undampedFreq) => {
return -.001 + Math.exp(-undampedFreq * duration) * ((undampedFreq - velocity) * duration + 1);
};
derivative = (undampedFreq) => {
return Math.exp(-undampedFreq * duration) * ((velocity - undampedFreq) * (duration * duration));
};
}
const initialGuess = 5 / duration;
const undampedFreq = approximateRoot(envelope, derivative, initialGuess);
duration = duration * 1e3;
if (isNaN(undampedFreq)) return {
stiffness: 100,
damping: 10,
duration
};
else {
const stiffness = Math.pow(undampedFreq, 2) * mass;
return {
stiffness,
damping: dampingRatio * 2 * Math.sqrt(mass * stiffness),
duration
};
}
}
var rootIterations = 12;
function approximateRoot(envelope, derivative, initialGuess) {
let result = initialGuess;
for (let i = 1; i < rootIterations; i++) result = result - envelope(result) / derivative(result);
return result;
}
function calcAngularFreq(undampedFreq, dampingRatio) {
return undampedFreq * Math.sqrt(1 - dampingRatio * dampingRatio);
}
var durationKeys = ["duration", "bounce"];
var physicsKeys = [
"stiffness",
"damping",
"mass"
];
function isSpringType(options, keys) {
return keys.some((key) => options[key] !== void 0);
}
function getSpringOptions(options) {
let springOptions = Object.assign({
velocity: 0,
stiffness: 100,
damping: 10,
mass: 1,
isResolvedFromDuration: false
}, options);
if (!isSpringType(options, physicsKeys) && isSpringType(options, durationKeys)) {
const derived = findSpring(options);
springOptions = Object.assign(Object.assign(Object.assign({}, springOptions), derived), {
velocity: 0,
mass: 1
});
springOptions.isResolvedFromDuration = true;
}
return springOptions;
}
function spring(_a) {
var { from = 0, to = 1, restSpeed = 2, restDelta } = _a, options = __rest(_a, [
"from",
"to",
"restSpeed",
"restDelta"
]);
const state = {
done: false,
value: from
};
let { stiffness, damping, mass, velocity, duration, isResolvedFromDuration } = getSpringOptions(options);
let resolveSpring = zero;
let resolveVelocity = zero;
function createSpring() {
const initialVelocity = velocity ? -(velocity / 1e3) : 0;
const initialDelta = to - from;
const dampingRatio = damping / (2 * Math.sqrt(stiffness * mass));
const undampedAngularFreq = Math.sqrt(stiffness / mass) / 1e3;
if (restDelta === void 0) restDelta = Math.min(Math.abs(to - from) / 100, .4);
if (dampingRatio < 1) {
const angularFreq = calcAngularFreq(undampedAngularFreq, dampingRatio);
resolveSpring = (t) => {
const envelope = Math.exp(-dampingRatio * undampedAngularFreq * t);
return to - envelope * ((initialVelocity + dampingRatio * undampedAngularFreq * initialDelta) / angularFreq * Math.sin(angularFreq * t) + initialDelta * Math.cos(angularFreq * t));
};
resolveVelocity = (t) => {
const envelope = Math.exp(-dampingRatio * undampedAngularFreq * t);
return dampingRatio * undampedAngularFreq * envelope * (Math.sin(angularFreq * t) * (initialVelocity + dampingRatio * undampedAngularFreq * initialDelta) / angularFreq + initialDelta * Math.cos(angularFreq * t)) - envelope * (Math.cos(angularFreq * t) * (initialVelocity + dampingRatio * undampedAngularFreq * initialDelta) - angularFreq * initialDelta * Math.sin(angularFreq * t));
};
} else if (dampingRatio === 1) resolveSpring = (t) => to - Math.exp(-undampedAngularFreq * t) * (initialDelta + (initialVelocity + undampedAngularFreq * initialDelta) * t);
else {
const dampedAngularFreq = undampedAngularFreq * Math.sqrt(dampingRatio * dampingRatio - 1);
resolveSpring = (t) => {
const envelope = Math.exp(-dampingRatio * undampedAngularFreq * t);
const freqForT = Math.min(dampedAngularFreq * t, 300);
return to - envelope * ((initialVelocity + dampingRatio * undampedAngularFreq * initialDelta) * Math.sinh(freqForT) + dampedAngularFreq * initialDelta * Math.cosh(freqForT)) / dampedAngularFreq;
};
}
}
createSpring();
return {
next: (t) => {
const current = resolveSpring(t);
if (!isResolvedFromDuration) {
const currentVelocity = resolveVelocity(t) * 1e3;
const isBelowVelocityThreshold = Math.abs(currentVelocity) <= restSpeed;
const isBelowDisplacementThreshold = Math.abs(to - current) <= restDelta;
state.done = isBelowVelocityThreshold && isBelowDisplacementThreshold;
} else state.done = t >= duration;
state.value = state.done ? to : current;
return state;
},
flipTarget: () => {
velocity = -velocity;
[from, to] = [to, from];
createSpring();
}
};
}
spring.needsInterpolation = (a, b) => typeof a === "string" || typeof b === "string";
var zero = (_t) => 0;
var progress = (from, to, value) => {
const toFromDifference = to - from;
return toFromDifference === 0 ? 1 : (value - from) / toFromDifference;
};
var mix = (from, to, progress) => -progress * from + progress * to + from;
var clamp = (min, max) => (v) => Math.max(Math.min(v, max), min);
var sanitize = (v) => v % 1 ? Number(v.toFixed(5)) : v;
var floatRegex = /(-)?([\d]*\.?[\d])+/g;
var colorRegex = /(#[0-9a-f]{6}|#[0-9a-f]{3}|#(?:[0-9a-f]{2}){2,4}|(rgb|hsl)a?\((-?[\d\.]+%?[,\s]+){2}(-?[\d\.]+%?)\s*[\,\/]?\s*[\d\.]*%?\))/gi;
var singleColorRegex = /^(#[0-9a-f]{3}|#(?:[0-9a-f]{2}){2,4}|(rgb|hsl)a?\((-?[\d\.]+%?[,\s]+){2}(-?[\d\.]+%?)\s*[\,\/]?\s*[\d\.]*%?\))$/i;
function isString(v) {
return typeof v === "string";
}
var number = {
test: (v) => typeof v === "number",
parse: parseFloat,
transform: (v) => v
};
var alpha = Object.assign(Object.assign({}, number), { transform: clamp(0, 1) });
Object.assign(Object.assign({}, number), { default: 1 });
var createUnitType = (unit) => ({
test: (v) => isString(v) && v.endsWith(unit) && v.split(" ").length === 1,
parse: parseFloat,
transform: (v) => `${v}${unit}`
});
var percent = createUnitType("%");
Object.assign(Object.assign({}, percent), {
parse: (v) => percent.parse(v) / 100,
transform: (v) => percent.transform(v * 100)
});
var isColorString = (type, testProp) => (v) => {
return Boolean(isString(v) && singleColorRegex.test(v) && v.startsWith(type) || testProp && Object.prototype.hasOwnProperty.call(v, testProp));
};
var splitColor = (aName, bName, cName) => (v) => {
if (!isString(v)) return v;
const [a, b, c, alpha] = v.match(floatRegex);
return {
[aName]: parseFloat(a),
[bName]: parseFloat(b),
[cName]: parseFloat(c),
alpha: alpha !== void 0 ? parseFloat(alpha) : 1
};
};
var hsla = {
test: isColorString("hsl", "hue"),
parse: splitColor("hue", "saturation", "lightness"),
transform: ({ hue, saturation, lightness, alpha: alpha$1 = 1 }) => {
return "hsla(" + Math.round(hue) + ", " + percent.transform(sanitize(saturation)) + ", " + percent.transform(sanitize(lightness)) + ", " + sanitize(alpha.transform(alpha$1)) + ")";
}
};
var clampRgbUnit = clamp(0, 255);
var rgbUnit = Object.assign(Object.assign({}, number), { transform: (v) => Math.round(clampRgbUnit(v)) });
var rgba = {
test: isColorString("rgb", "red"),
parse: splitColor("red", "green", "blue"),
transform: ({ red, green, blue, alpha: alpha$1 = 1 }) => "rgba(" + rgbUnit.transform(red) + ", " + rgbUnit.transform(green) + ", " + rgbUnit.transform(blue) + ", " + sanitize(alpha.transform(alpha$1)) + ")"
};
function parseHex(v) {
let r = "";
let g = "";
let b = "";
let a = "";
if (v.length > 5) {
r = v.substr(1, 2);
g = v.substr(3, 2);
b = v.substr(5, 2);
a = v.substr(7, 2);
} else {
r = v.substr(1, 1);
g = v.substr(2, 1);
b = v.substr(3, 1);
a = v.substr(4, 1);
r += r;
g += g;
b += b;
a += a;
}
return {
red: parseInt(r, 16),
green: parseInt(g, 16),
blue: parseInt(b, 16),
alpha: a ? parseInt(a, 16) / 255 : 1
};
}
var hex = {
test: isColorString("#"),
parse: parseHex,
transform: rgba.transform
};
var color = {
test: (v) => rgba.test(v) || hex.test(v) || hsla.test(v),
parse: (v) => {
if (rgba.test(v)) return rgba.parse(v);
else if (hsla.test(v)) return hsla.parse(v);
else return hex.parse(v);
},
transform: (v) => {
return isString(v) ? v : v.hasOwnProperty("red") ? rgba.transform(v) : hsla.transform(v);
}
};
var colorToken = "${c}";
var numberToken = "${n}";
function test(v) {
var _a, _b, _c, _d;
return isNaN(v) && isString(v) && ((_b = (_a = v.match(floatRegex)) === null || _a === void 0 ? void 0 : _a.length) !== null && _b !== void 0 ? _b : 0) + ((_d = (_c = v.match(colorRegex)) === null || _c === void 0 ? void 0 : _c.length) !== null && _d !== void 0 ? _d : 0) > 0;
}
function analyse$1(v) {
if (typeof v === "number") v = `${v}`;
const values = [];
let numColors = 0;
const colors = v.match(colorRegex);
if (colors) {
numColors = colors.length;
v = v.replace(colorRegex, colorToken);
values.push(...colors.map(color.parse));
}
const numbers = v.match(floatRegex);
if (numbers) {
v = v.replace(floatRegex, numberToken);
values.push(...numbers.map(number.parse));
}
return {
values,
numColors,
tokenised: v
};
}
function parse(v) {
return analyse$1(v).values;
}
function createTransformer(v) {
const { values, numColors, tokenised } = analyse$1(v);
const numValues = values.length;
return (v) => {
let output = tokenised;
for (let i = 0; i < numValues; i++) output = output.replace(i < numColors ? colorToken : numberToken, i < numColors ? color.transform(v[i]) : sanitize(v[i]));
return output;
};
}
var convertNumbersToZero = (v) => typeof v === "number" ? 0 : v;
function getAnimatableNone$1(v) {
const parsed = parse(v);
return createTransformer(v)(parsed.map(convertNumbersToZero));
}
var complex = {
test,
parse,
createTransformer,
getAnimatableNone: getAnimatableNone$1
};
var maxDefaults = new Set([
"brightness",
"contrast",
"saturate",
"opacity"
]);
function applyDefaultFilter(v) {
let [name, value] = v.slice(0, -1).split("(");
if (name === "drop-shadow") return v;
const [number] = value.match(floatRegex) || [];
if (!number) return v;
const unit = value.replace(number, "");
let defaultValue = maxDefaults.has(name) ? 1 : 0;
if (number !== value) defaultValue *= 100;
return name + "(" + defaultValue + unit + ")";
}
var functionRegex = /([a-z-]*)\(.*?\)/g;
Object.assign(Object.assign({}, complex), { getAnimatableNone: (v) => {
const functions = v.match(functionRegex);
return functions ? functions.map(applyDefaultFilter).join(" ") : v;
} });
function hueToRgb(p, q, t) {
if (t < 0) t += 1;
if (t > 1) t -= 1;
if (t < 1 / 6) return p + (q - p) * 6 * t;
if (t < 1 / 2) return q;
if (t < 2 / 3) return p + (q - p) * (2 / 3 - t) * 6;
return p;
}
function hslaToRgba({ hue, saturation, lightness, alpha }) {
hue /= 360;
saturation /= 100;
lightness /= 100;
let red = 0;
let green = 0;
let blue = 0;
if (!saturation) red = green = blue = lightness;
else {
const q = lightness < .5 ? lightness * (1 + saturation) : lightness + saturation - lightness * saturation;
const p = 2 * lightness - q;
red = hueToRgb(p, q, hue + 1 / 3);
green = hueToRgb(p, q, hue);
blue = hueToRgb(p, q, hue - 1 / 3);
}
return {
red: Math.round(red * 255),
green: Math.round(green * 255),
blue: Math.round(blue * 255),
alpha
};
}
var mixLinearColor = (from, to, v) => {
const fromExpo = from * from;
const toExpo = to * to;
return Math.sqrt(Math.max(0, v * (toExpo - fromExpo) + fromExpo));
};
var colorTypes = [
hex,
rgba,
hsla
];
var getColorType = (v) => colorTypes.find((type) => type.test(v));
var notAnimatable = (color) => `'${color}' is not an animatable color. Use the equivalent color code instead.`;
var mixColor = (from, to) => {
let fromColorType = getColorType(from);
let toColorType = getColorType(to);
notAnimatable(from);
notAnimatable(to);
let fromColor = fromColorType.parse(from);
let toColor = toColorType.parse(to);
if (fromColorType === hsla) {
fromColor = hslaToRgba(fromColor);
fromColorType = rgba;
}
if (toColorType === hsla) {
toColor = hslaToRgba(toColor);
toColorType = rgba;
}
const blended = Object.assign({}, fromColor);
return (v) => {
for (const key in blended) if (key !== "alpha") blended[key] = mixLinearColor(fromColor[key], toColor[key], v);
blended.alpha = mix(fromColor.alpha, toColor.alpha, v);
return fromColorType.transform(blended);
};
};
var isNum = (v) => typeof v === "number";
var combineFunctions = (a, b) => (v) => b(a(v));
var pipe = (...transformers) => transformers.reduce(combineFunctions);
function getMixer(origin, target) {
if (isNum(origin)) return (v) => mix(origin, target, v);
else if (color.test(origin)) return mixColor(origin, target);
else return mixComplex(origin, target);
}
var mixArray = (from, to) => {
const output = [...from];
const numValues = output.length;
const blendValue = from.map((fromThis, i) => getMixer(fromThis, to[i]));
return (v) => {
for (let i = 0; i < numValues; i++) output[i] = blendValue[i](v);
return output;
};
};
var mixObject = (origin, target) => {
const output = Object.assign(Object.assign({}, origin), target);
const blendValue = {};
for (const key in output) if (origin[key] !== void 0 && target[key] !== void 0) blendValue[key] = getMixer(origin[key], target[key]);
return (v) => {
for (const key in blendValue) output[key] = blendValue[key](v);
return output;
};
};
function analyse(value) {
const parsed = complex.parse(value);
const numValues = parsed.length;
let numNumbers = 0;
let numRGB = 0;
let numHSL = 0;
for (let i = 0; i < numValues; i++) if (numNumbers || typeof parsed[i] === "number") numNumbers++;
else if (parsed[i].hue !== void 0) numHSL++;
else numRGB++;
return {
parsed,
numNumbers,
numRGB,
numHSL
};
}
var mixComplex = (origin, target) => {
const template = complex.createTransformer(target);
const originStats = analyse(origin);
const targetStats = analyse(target);
if (originStats.numHSL === targetStats.numHSL && originStats.numRGB === targetStats.numRGB && originStats.numNumbers >= targetStats.numNumbers) return pipe(mixArray(originStats.parsed, targetStats.parsed), template);
else {
`${origin}${target}`;
return (p) => `${p > 0 ? target : origin}`;
}
};
var mixNumber = (from, to) => (p) => mix(from, to, p);
function detectMixerFactory(v) {
if (typeof v === "number") return mixNumber;
else if (typeof v === "string") {
if (color.test(v)) return mixColor;
else return mixComplex;
} else if (Array.isArray(v)) return mixArray;
else if (typeof v === "object") return mixObject;
}
function createMixers(output, ease, customMixer) {
const mixers = [];
const mixerFactory = customMixer || detectMixerFactory(output[0]);
const numMixers = output.length - 1;
for (let i = 0; i < numMixers; i++) {
let mixer = mixerFactory(output[i], output[i + 1]);
if (ease) mixer = pipe(Array.isArray(ease) ? ease[i] : ease, mixer);
mixers.push(mixer);
}
return mixers;
}
function fastInterpolate([from, to], [mixer]) {
return (v) => mixer(progress(from, to, v));
}
function slowInterpolate(input, mixers) {
const inputLength = input.length;
const lastInputIndex = inputLength - 1;
return (v) => {
let mixerIndex = 0;
let foundMixerIndex = false;
if (v <= input[0]) foundMixerIndex = true;
else if (v >= input[lastInputIndex]) {
mixerIndex = lastInputIndex - 1;
foundMixerIndex = true;
}
if (!foundMixerIndex) {
let i = 1;
for (; i < inputLength; i++) if (input[i] > v || i === lastInputIndex) break;
mixerIndex = i - 1;
}
const progressInRange = progress(input[mixerIndex], input[mixerIndex + 1], v);
return mixers[mixerIndex](progressInRange);
};
}
function interpolate(input, output, { clamp: isClamp = true, ease, mixer } = {}) {
const inputLength = input.length;
output.length;
!ease || !Array.isArray(ease) || (ease.length, inputLength - 1);
if (input[0] > input[inputLength - 1]) {
input = [].concat(input);
output = [].concat(output);
input.reverse();
output.reverse();
}
const mixers = createMixers(output, ease, mixer);
const interpolator = inputLength === 2 ? fastInterpolate(input, mixers) : slowInterpolate(input, mixers);
return isClamp ? (v) => interpolator(clamp$1(input[0], input[inputLength - 1], v)) : interpolator;
}
var mirrorEasing = (easing) => (p) => p <= .5 ? easing(2 * p) / 2 : (2 - easing(2 * (1 - p))) / 2;
var createExpoIn = (power) => (p) => Math.pow(p, power);
var createBackIn = (power) => (p) => p * p * ((power + 1) * p - power);
var createAnticipate = (power) => {
const backEasing = createBackIn(power);
return (p) => (p *= 2) < 1 ? .5 * backEasing(p) : .5 * (2 - Math.pow(2, -10 * (p - 1)));
};
var DEFAULT_OVERSHOOT_STRENGTH = 1.525;
var easeInOut = mirrorEasing(createExpoIn(2));
createAnticipate(DEFAULT_OVERSHOOT_STRENGTH);
function defaultEasing(values, easing) {
return values.map(() => easing || easeInOut).splice(0, values.length - 1);
}
function defaultOffset(values) {
const numValues = values.length;
return values.map((_value, i) => i !== 0 ? i / (numValues - 1) : 0);
}
function convertOffsetToTimes(offset, duration) {
return offset.map((o) => o * duration);
}
function keyframes$1({ from = 0, to = 1, ease, offset, duration = 300 }) {
const state = {
done: false,
value: from
};
const values = Array.isArray(to) ? to : [from, to];
const times = convertOffsetToTimes(offset && offset.length === values.length ? offset : defaultOffset(values), duration);
function createInterpolator() {
return interpolate(times, values, { ease: Array.isArray(ease) ? ease : defaultEasing(values, ease) });
}
let interpolator = createInterpolator();
return {
next: (t) => {
state.value = interpolator(t);
state.done = t >= duration;
return state;
},
flipTarget: () => {
values.reverse();
interpolator = createInterpolator();
}
};
}
function decay({ velocity = 0, from = 0, power = .8, timeConstant = 350, restDelta = .5, modifyTarget }) {
const state = {
done: false,
value: from
};
let amplitude = power * velocity;
const ideal = from + amplitude;
const target = modifyTarget === void 0 ? ideal : modifyTarget(ideal);
if (target !== ideal) amplitude = target - from;
return {
next: (t) => {
const delta = -amplitude * Math.exp(-t / timeConstant);
state.done = !(delta > restDelta || delta < -restDelta);
state.value = state.done ? target : target + delta;
return state;
},
flipTarget: () => {}
};
}
var types = {
keyframes: keyframes$1,
spring,
decay
};
function detectAnimationFromOptions(config) {
if (Array.isArray(config.to)) return keyframes$1;
else if (types[config.type]) return types[config.type];
const keys = new Set(Object.keys(config));
if (keys.has("ease") || keys.has("duration") && !keys.has("dampingRatio")) return keyframes$1;
else if (keys.has("dampingRatio") || keys.has("stiffness") || keys.has("mass") || keys.has("damping") || keys.has("restSpeed") || keys.has("restDelta")) return spring;
return keyframes$1;
}
function loopElapsed(elapsed, duration, delay = 0) {
return elapsed - duration - delay;
}
function reverseElapsed(elapsed, duration, delay = 0, isForwardPlayback = true) {
return isForwardPlayback ? loopElapsed(duration + -elapsed, duration, delay) : duration - (elapsed - duration) + delay;
}
function hasRepeatDelayElapsed(elapsed, duration, delay, isForwardPlayback) {
return isForwardPlayback ? elapsed >= duration + delay : elapsed <= -delay;
}
var framesync = (update) => {
const passTimestamp = ({ delta }) => update(delta);
return {
start: () => sync.update(passTimestamp, true),
stop: () => cancelSync.update(passTimestamp)
};
};
function animate(_a) {
var _b, _c;
var { from, autoplay = true, driver = framesync, elapsed = 0, repeat: repeatMax = 0, repeatType = "loop", repeatDelay = 0, onPlay, onStop, onComplete, onRepeat, onUpdate } = _a, options = __rest(_a, [
"from",
"autoplay",
"driver",
"elapsed",
"repeat",
"repeatType",
"repeatDelay",
"onPlay",
"onStop",
"onComplete",
"onRepeat",
"onUpdate"
]);
let { to } = options;
let driverControls;
let repeatCount = 0;
let computedDuration = options.duration;
let latest;
let isComplete = false;
let isForwardPlayback = true;
let interpolateFromNumber;
const animator = detectAnimationFromOptions(options);
if ((_c = (_b = animator).needsInterpolation) === null || _c === void 0 ? void 0 : _c.call(_b, from, to)) {
interpolateFromNumber = interpolate([0, 100], [from, to], { clamp: false });
from = 0;
to = 100;
}
const animation = animator(Object.assign(Object.assign({}, options), {
from,
to
}));
function repeat() {
repeatCount++;
if (repeatType === "reverse") {
isForwardPlayback = repeatCount % 2 === 0;
elapsed = reverseElapsed(elapsed, computedDuration, repeatDelay, isForwardPlayback);
} else {
elapsed = loopElapsed(elapsed, computedDuration, repeatDelay);
if (repeatType === "mirror") animation.flipTarget();
}
isComplete = false;
onRepeat && onRepeat();
}
function complete() {
driverControls.stop();
onComplete && onComplete();
}
function update(delta) {
if (!isForwardPlayback) delta = -delta;
elapsed += delta;
if (!isComplete) {
const state = animation.next(Math.max(0, elapsed));
latest = state.value;
if (interpolateFromNumber) latest = interpolateFromNumber(latest);
isComplete = isForwardPlayback ? state.done : elapsed <= 0;
}
onUpdate === null || onUpdate === void 0 || onUpdate(latest);
if (isComplete) {
if (repeatCount === 0) computedDuration !== null && computedDuration !== void 0 || (computedDuration = elapsed);
if (repeatCount < repeatMax) hasRepeatDelayElapsed(elapsed, computedDuration, repeatDelay, isForwardPlayback) && repeat();
else complete();
}
}
function play() {
onPlay === null || onPlay === void 0 || onPlay();
driverControls = driver(update);
driverControls.start();
}
autoplay && play();
return { stop: () => {
onStop === null || onStop === void 0 || onStop();
driverControls.stop();
} };
}
function velocityPerSecond(velocity, frameDuration) {
return frameDuration ? velocity * (1e3 / frameDuration) : 0;
}
var SubscriptionManager = class {
subscriptions = new Set();
add(handler) {
this.subscriptions.add(handler);
return () => this.subscriptions.delete(handler);
}
notify(a, b, c) {
if (!this.subscriptions.size) return;
for (const handler of this.subscriptions) handler(a, b, c);
}
clear() {
this.subscriptions.clear();
}
};
function isFloat(value) {
return !Number.isNaN(Number.parseFloat(value));
}
var MotionValue = class {
current;
prev;
timeDelta = 0;
lastUpdated = 0;
updateSubscribers = new SubscriptionManager();
stopAnimation;
canTrackVelocity = false;
constructor(init) {
this.prev = this.current = init;
this.canTrackVelocity = isFloat(this.current);
}
onChange(subscription) {
return this.updateSubscribers.add(subscription);
}
clearListeners() {
this.updateSubscribers.clear();
}
set(v) {
this.updateAndNotify(v);
}
updateAndNotify = (v) => {
this.prev = this.current;
this.current = v;
const { delta, timestamp } = getFrameData();
if (this.lastUpdated !== timestamp) {
this.timeDelta = delta;
this.lastUpdated = timestamp;
}
sync.postRender(this.scheduleVelocityCheck);
this.updateSubscribers.notify(this.current);
};
get() {
return this.current;
}
getPrevious() {
return this.prev;
}
getVelocity() {
return this.canTrackVelocity ? velocityPerSecond(Number.parseFloat(this.current) - Number.parseFloat(this.prev), this.timeDelta) : 0;
}
scheduleVelocityCheck = () => sync.postRender(this.velocityCheck);
velocityCheck = ({ timestamp }) => {
if (!this.canTrackVelocity) this.canTrackVelocity = isFloat(this.current);
if (timestamp !== this.lastUpdated) this.prev = this.current;
};
start(animation) {
this.stop();
return new Promise((resolve) => {
const { stop } = animation(resolve);
this.stopAnimation = stop;
}).then(() => this.clearAnimation());
}
stop() {
if (this.stopAnimation) this.stopAnimation();
this.clearAnimation();
}
isAnimating() {
return !!this.stopAnimation;
}
clearAnimation() {
this.stopAnimation = null;
}
destroy() {
this.updateSubscribers.clear();
this.stop();
}
};
function getMotionValue(init) {
return new MotionValue(init);
}
var { isArray } = Array;
function useMotionValues() {
const motionValues = ref({});
const stop = (keys) => {
const destroyKey = (key) => {
if (!motionValues.value[key]) return;
motionValues.value[key].stop();
motionValues.value[key].destroy();
delete motionValues.value[key];
};
if (keys) {
if (isArray(keys)) keys.forEach(destroyKey);
else destroyKey(keys);
} else Object.keys(motionValues.value).forEach(destroyKey);
};
const get = (key, from, target) => {
if (motionValues.value[key]) return motionValues.value[key];
const motionValue = getMotionValue(from);
motionValue.onChange((v) => target[key] = v);
motionValues.value[key] = motionValue;
return motionValue;
};
tryOnUnmounted(stop);
return {
motionValues,
get,
stop
};
}
function isKeyframesTarget(v) {
return Array.isArray(v);
}
function underDampedSpring() {
return {
type: "spring",
stiffness: 500,
damping: 25,
restDelta: .5,
restSpeed: 10
};
}
function criticallyDampedSpring(to) {
return {
type: "spring",
stiffness: 550,
damping: to === 0 ? 2 * Math.sqrt(550) : 30,
restDelta: .01,
restSpeed: 10
};
}
function overDampedSpring(to) {
return {
type: "spring",
stiffness: 550,
damping: to === 0 ? 100 : 30,
restDelta: .01,
restSpeed: 10
};
}
function linearTween() {
return {
type: "keyframes",
ease: "linear",
duration: 300
};
}
function keyframes(values) {
return {
type: "keyframes",
duration: 800,
values
};
}
var defaultTransitions = {
default: overDampedSpring,
x: underDampedSpring,
y: underDampedSpring,
z: underDampedSpring,
rotate: underDampedSpring,
rotateX: underDampedSpring,
rotateY: underDampedSpring,
rotateZ: underDampedSpring,
scaleX: criticallyDampedSpring,
scaleY: criticallyDampedSpring,
scale: criticallyDampedSpring,
backgroundColor: linearTween,
color: linearTween,
opacity: linearTween
};
function getDefaultTransition(valueKey, to) {
let transitionFactory;
if (isKeyframesTarget(to)) transitionFactory = keyframes;
else transitionFactory = defaultTransitions[valueKey] || defaultTransitions.default;
return {
to,
...transitionFactory(to)
};
}
({ ...number });
var transformAxes = [
"",
"X",
"Y",
"Z"
];
var order = [
"perspective",
"translate",
"scale",
"rotate",
"skew"
];
var transformProps = [
"transformPerspective",
"x",
"y",
"z"
];
order.forEach((operationKey) => {
transformAxes.forEach((axesKey) => {
const key = operationKey + axesKey;
transformProps.push(key);
});
});
new Set(transformProps);
var MotionComponentProps = {
preset: {
type: String,
required: false
},
instance: {
type: Object,
required: false
},
variants: {
type: Object,
required: false
},
initial: {
type: Object,
required: false
},
enter: {
type: Object,
required: false
},
leave: {
type: Object,
required: false
},
visible: {
type: Object,
required: false
},
visibleOnce: {
type: Object,
required: false
},
hovered: {
type: Object,
required: false
},
tapped: {
type: Object,
required: false
},
focused: {
type: Object,
required: false
},
delay: {
type: [Number, String],
required: false
},
duration: {
type: [Number, String],
required: false
}
};
({ ...MotionComponentProps });
({ ...MotionComponentProps });
function useSpring(values, spring) {
const { stop, get } = useMotionValues();
return {
values,
stop,
set: (properties) => Promise.all(Object.entries(properties).map(([key, value]) => {
const motionValue = get(key, values[key], values);
return motionValue.start((onComplete) => {
const options = {
type: "spring",
...spring || getDefaultTransition(key, value)
};
return animate({
from: motionValue.get(),
to: value,
velocity: motionValue.getVelocity(),
onUpdate: (v) => motionValue.set(v),
onComplete,
...options
});
});
}))
};
}
var minReboundSpeed = 60;
var maxReboundDistance = 40;
var maxImpactAge = 1e3 / 60;
function useScrollEdgeMotion(reducedMotion) {
const position = reactive({ y: 0 });
const spring = {
stiffness: 340,
damping: 37,
restDelta: .15,
restSpeed: 3,
velocity: 0
};
const { set, stop: stopSpring } = useSpring(position, spring);
let reboundFrame = 0;
function stop() {
cancelAnimationFrame(reboundFrame);
stopSpring();
}
function settle(target, velocity = 0) {
stop();
if (reducedMotion.value) position.y = target;
else {
spring.velocity = velocity;
set({ y: target });
}
}
function rebound(speed, impactAge = 0) {
if (reducedMotion.value || speed < minReboundSpeed) return false;
stop();
const decay = Math.max(spring.damping / 2, speed / (Math.E * maxReboundDistance));
const started = performance.now() - Math.min(maxImpactAge, impactAge);
const frame = (now) => {
const seconds = Math.max(0, now - started) / 1e3;
const stretch = speed * seconds * Math.exp(-decay * seconds);
if (seconds > 1 / decay && stretch < spring.restDelta) {
position.y = 0;
return;
}
position.y = stretch;
reboundFrame = requestAnimationFrame(frame);
};
frame(performance.now());
return true;
}
onScopeDispose(stop);
return {
position,
settle,
rebound,
stop
};
}
var triggerDistance = 56;
var maxDistance = 150;
function useScrollEdgeStretch(edge, indicatorEnabled, bounceAtLoadingEdge, reducedMotion) {
const bottom = edge === "bottom";
const edgeIndicator = bottom ? "limit" : "refresh";
const blocked = computed(() => !indicatorEnabled.value && !bounceAtLoadingEdge.value);
const direction = bottom ? -1 : 1;
const { position, settle, rebound: playRebound, stop: stopMotion } = useScrollEdgeMotion(reducedMotion);
const dragging = shallowRef(false);
const indicator = shallowRef();
const scale = shallowRef(1);
const distance = computed(() => Math.max(0, position.y));
const offset = computed(() => distance.value / scale.value);
const carriedOffset = shallowRef(0);
const totalOffset = computed(() => offset.value + carriedOffset.value);
const scrollFromEdge = shallowRef(0);
const exposedOffset = computed(() => Math.max(0, totalOffset.value - scrollFromEdge.value));
const feedback = createFeedback();
function createFeedback() {
const ready = computed(() => indicator.value === "refresh" && dragging.value && scrollFromEdge.value <= 1 && exposedOffset.value * scale.value >= triggerDistance);
const needsMore = computed(() => bounceAtLoadingEdge.value && (dragging.value || carriedOffset.value > 0));
const revealOffset = computed(() => Math.min(maxDistance / scale.value, exposedOffset.value));
const refreshOffset = computed(() => !bottom && (indicator.value === "refresh" || indicatorEnabled.value && carriedOffset.value) ? revealOffset.value : 0);
const limitOffset = computed(() => bottom && indicatorEnabled.value && (indicator.value === "limit" || carriedOffset.value) ? revealOffset.value : 0);
return {
totalOffset,
carriedOffset,
ready,
refreshOffset,
limitOffset,
needsMore
};
}
function edgeDistance(element) {
return bottom ? element.scrollHeight - element.clientHeight - element.scrollTop : element.scrollTop;
}
function atEdge(element, viewport) {
return isAtEdge(element, viewport, bottom, edgeDistance);
}
function leaveEdge(current, edgeMoved = false) {
current.edge = void 0;
if (current.rawOffset === void 0 && !current.holdingSpring) return;
current.rawOffset = void 0;
current.holdingSpring = false;
dragging.value = false;
if (!edgeMoved) {
position.y = 0;
return;
}
indicator.value = void 0;
settle(0);
}
function mergeCarriedOffset() {
position.y += carriedOffset.value * scale.value;
carriedOffset.value = 0;
}
function settleCarriedOffset(velocity) {
mergeCarriedOffset();
indicator.value = indicatorEnabled.value ? edgeIndicator : void 0;
settle(0, velocity);
}
function resetStretch() {
carriedOffset.value = 0;
stopMotion();
position.y = 0;
}
function rebound(speed, impactAge = 0) {
if (!playRebound(speed, impactAge)) return;
indicator.value = void 0;
scale.value = 1;
}
function paintPull(current, raw, elapsed) {
const next = applyEdgeResistance(raw, maxDistance);
current.velocity = Math.max(-600, Math.min(600, (next - distance.value) * 1e3 / elapsed));
position.y = next;
}
function beginPull(current) {
stopMotion();
const stretch = offset.value * current.scale;
const rest = Math.min(stretch, 149);
carriedOffset.value += (stretch - rest) / current.scale;
position.y = rest;
current.rawOffset = removeEdgeResistance(rest, maxDistance);
current.holdingSpring = false;
scale.value = current.scale;
indicator.value = indicatorEnabled.value ? edgeIndicator : void 0;
dragging.value = true;
}
function reversePull(current, element, event, travel, elapsed) {
const remaining = distance.value + carriedOffset.value * current.scale + travel;
const controlsScroll = indicator.value && event.cancelable && current.scale <= 1.01;
if (controlsScroll) event.preventDefault();
if (remaining <= 0) {
carriedOffset.value = 0;
leaveEdge(current);
if (controlsScroll) {
element.scrollTo({
top: element.scrollTop + direction * (-remaining / current.scale),
behavior: "instant"
});
current.lastEdgeDistance = Math.max(0, edgeDistance(element));
current.nativeScroll = true;
}
return;
}
const next = Math.max(0, distance.value + travel);
carriedOffset.value = Math.max(0, remaining - next) / current.scale;
position.y = next;
current.rawOffset = removeEdgeResistance(next, maxDistance);
if (current.edge) current.edge.y = current.lastFingerY - direction * 6;
current.velocity = Math.max(-600, travel * 1e3 / elapsed);
}
return {
feedback,
bottom,
direction,
blocked,
dragging,
indicator,
distance,
scrollFromEdge,
settle,
stopMotion,
resetStretch,
edgeDistance,
atEdge,
leaveEdge,
mergeCarriedOffset,
settleCarriedOffset,
rebound,
paintPull,
beginPull,
reversePull
};
}
function useScrollEdgePull(surface, indicatorEnabled, bounceAtLoadingEdge, reducedMotion, options) {
const stretch = useScrollEdgeStretch(options.edge, indicatorEnabled, bounceAtLoadingEdge, reducedMotion);
const gesture = useScrollEdgeGesture(surface, indicatorEnabled, reducedMotion, options, stretch, useScrollEdgeHandoff(surface, stretch));
return {
...stretch.feedback,
...gesture
};
}
function useScrollEdgeFeedback(surface, content, reducedMotion, refreshBlocked, refresh, reachedEnd, loadingEdges) {
const top = useScrollEdgePull(surface, computed(() => !refreshBlocked.value), computed(() => loadingEdges.value.top), reducedMotion, {
edge: "top",
refresh
});
const bottom = useScrollEdgePull(surface, reachedEnd, computed(() => loadingEdges.value.bottom), reducedMotion, { edge: "bottom" });
useResizeObserver(() => [surface.value, content.value], () => {
top.reconcileEdge();
bottom.reconcileEdge();
});
const contentOffset = computed(() => top.totalOffset.value - bottom.totalOffset.value);
const edgePreload = computed(() => top.needsMore.value ? "previous" : bottom.needsMore.value ? "next" : void 0);
return {
pullReady: top.ready,
refreshOffset: top.refreshOffset,
endOffset: bottom.limitOffset,
contentOffset,
edgePreload,
captureLoad: (direction) => direction ? (direction === "previous" ? top : bottom).captureLoad() : top.captureLoad() ?? bottom.captureLoad(),
clearHandoff: () => {
top.carriedOffset.value = 0;
bottom.carriedOffset.value = 0;
}
};
}
var _hoisted_1$15 = {
class: "infinite-sentinel grid min-h-[94px] place-items-center pt-6 pb-[38px]",
"aria-live": "polite"
};
var _hoisted_2$12 = {
key: 1,
class: "infinite-error"
};
var LoadMoreIndicator_default = defineComponent({
__name: "LoadMoreIndicator",
props: {
loading: { type: Boolean },
error: {},
showHint: { type: Boolean }
},
emits: ["load", "retry"],
setup(__props, { emit: __emit }) {
const emit = __emit;
return (_ctx, _cache) => {
return openBlock(), createElementBlock("div", _hoisted_1$15, [createBaseVNode("div", { class: normalizeClass(["infinite-sentinel-inner", { "is-loading": __props.loading }]) }, [__props.loading ? (openBlock(), createBlock(LoadingSpinner_default, {
key: 0,
size: 18
})) : __props.error ? (openBlock(), createElementBlock("span", _hoisted_2$12, [createBaseVNode("span", null, toDisplayString(__props.error), 1), createBaseVNode("button", {
class: "pill",
type: "button",
onClick: _cache[0] || (_cache[0] = ($event) => emit("retry"))
}, "重试")])) : __props.showHint ? (openBlock(), createElementBlock("button", {
key: 2,
class: "infinite-hint min-h-9 rounded-[9px] px-3 py-1.5 text-[12px] text-muted [border:1px_solid_var(--line)] active:[transform:scale(.97)]",
type: "button",
onClick: _cache[1] || (_cache[1] = ($event) => emit("load"))
}, " 继续下滑加载更多 ")) : createCommentVNode("", true)], 2)]);
};
}
});
var _hoisted_1$14 = ["aria-hidden", "role"];
var _hoisted_2$11 = {
key: 0,
class: "scroll-edge-chip"
};
var _hoisted_3$10 = {
key: 1,
class: "scroll-edge-chip pull-refresh-chip"
};
var ScrollEdgeIndicator_default = defineComponent({
__name: "ScrollEdgeIndicator",
props: {
offset: {},
ready: { type: Boolean },
refreshing: { type: Boolean },
edge: {}
},
setup(__props) {
const reveal = useTemplateRef("reveal");
const visual = window.visualViewport;
function positionChip() {
const element = reveal.value;
if (!element || !visual) return;
if (visual.scale <= 1.01) {
element.style.removeProperty("--scroll-edge-center");
element.style.removeProperty("--scroll-edge-scale");
return;
}
const bounds = element.getBoundingClientRect();
const left = Math.max(bounds.left, visual.offsetLeft);
const right = Math.min(bounds.right, visual.offsetLeft + visual.width);
element.style.setProperty("--scroll-edge-center", (left + right) / 2 - bounds.left + "px");
element.style.setProperty("--scroll-edge-scale", String(1 / visual.scale));
}
watch(reveal, positionChip, { flush: "post" });
useEventListener$1(() => reveal.value ? visual : null, ["resize", "scroll"], positionChip, { passive: true });
return (_ctx, _cache) => {
return __props.offset > 0 ? (openBlock(), createElementBlock("div", {
key: 0,
ref_key: "reveal",
ref: reveal,
class: "scroll-edge-reveal",
style: normalizeStyle({ height: __props.offset + "px" }),
"aria-hidden": __props.edge ? void 0 : true,
role: __props.edge ? "status" : void 0
}, [__props.edge === "bottom" ? (openBlock(), createElementBlock("span", _hoisted_2$11, "已经到底了")) : (openBlock(), createElementBlock("span", _hoisted_3$10, [__props.refreshing ? (openBlock(), createBlock(LoadingSpinner_default, {
key: 0,
size: 16
})) : (openBlock(), createBlock(unref(ArrowDown), {
key: 1,
size: 16,
class: normalizeClass({ "pull-refresh-ready": __props.ready })
}, null, 8, ["class"])), createTextVNode(" " + toDisplayString(__props.refreshing ? "正在刷新" : __props.ready ? "松手刷新" : "下拉刷新"), 1)]))], 12, _hoisted_1$14)) : createCommentVNode("", true);
};
}
});
var _hoisted_1$13 = { class: "infinite-scroll-overlay" };
var InfiniteScroll_default = defineComponent({
__name: "InfiniteScroll",
props: {
refresh: {},
loadMore: {},
retryLoadMore: {},
hasMore: { type: Boolean },
reachedEnd: { type: Boolean },
hasPrevious: { type: Boolean },
loading: { type: Boolean },
error: {},
previousError: {},
refreshing: { type: Boolean },
refreshBlocked: { type: Boolean },
loadingBlocked: { type: Boolean },
active: {
type: Boolean,
default: true
},
showLoadHint: { type: Boolean },
preloadDistance: {},
loadInterval: {},
canPreload: {
type: Boolean,
default: true
},
preloadDirection: {},
virtual: { type: Boolean },
contentAs: {},
contentAttrs: {},
endIndicatorClass: {},
itemKeys: {}
},
setup(__props, { expose: __expose }) {
const props = __props;
const viewport = useTemplateRef("viewport");
const content = useTemplateRef("content");
const motion = usePreferredReducedMotion();
const visual = window.visualViewport;
const zoomed = shallowRef((visual?.scale ?? 1) > 1.01);
useEventListener$1(visual, "resize", () => {
zoomed.value = (visual?.scale ?? 1) > 1.01;
});
useResizeObserver(() => viewport.value?.querySelector(":scope > header"), ([entry]) => {
if (entry) {
const height = entry.target.getBoundingClientRect().height + "px";
viewport.value?.style.setProperty("--masthead-height", height);
}
});
const refreshingPull = shallowRef(false);
async function refreshFromEdge() {
refreshingPull.value = true;
try {
await props.refresh();
} finally {
refreshingPull.value = false;
}
}
const { pullReady, refreshOffset, endOffset, contentOffset, edgePreload, captureLoad, clearHandoff } = useScrollEdgeFeedback(viewport, content, computed(() => motion.value === "reduce"), computed(() => !props.active || Boolean(props.refreshBlocked || props.refreshing || refreshingPull.value)), refreshFromEdge, computed(() => props.active && props.reachedEnd && !props.refreshing && !refreshingPull.value), computed(() => {
const active = props.active && !props.refreshing && !refreshingPull.value;
return {
top: active && Boolean(props.hasPrevious),
bottom: active && (props.hasMore || Boolean(props.loading))
};
}));
const contentStyle = computed(() => contentOffset.value ? { transform: `translateY(${contentOffset.value}px)` } : void 0);
async function preserveEdgePosition(direction) {
const handoff = captureLoad(direction);
const element = viewport.value;
const container = content.value;
if (!handoff || !element || !container) return false;
let anchor = handoff.anchor;
if (!anchor || !container.contains(anchor)) {
anchor = void 0;
const bounds = element.getBoundingClientRect();
for (const item of container.querySelectorAll("[data-scroll-item]")) {
const position = item.getBoundingClientRect();
anchor = item;
if (position.bottom > bounds.top && position.top < bounds.bottom) break;
}
}
const anchorTop = anchor?.getBoundingClientRect().top ?? 0;
await nextTick();
await nextTick();
if (content.value !== container) return false;
const shift = anchor && container.contains(anchor) ? anchor.getBoundingClientRect().top - anchorTop : 0;
return handoff.restore(anchor, shift);
}
watch(() => props.itemKeys, async (items, previous) => {
const first = previous?.[0];
if (!previous || first === void 0) return;
if (!items?.includes(first)) clearHandoff();
if (!items || items.length <= previous.length) return;
const count = items.length - previous.length;
const last = previous.at(-1);
const append = items[0] === first && items[previous.length - 1] === last;
const prepend = items[count] === first && items.at(-1) === last;
if (!append && !prepend) return;
const container = content.value;
if (!container || !await preserveEdgePosition(append ? "next" : "previous")) return;
if (content.value !== container || props.itemKeys !== items || motion.value === "reduce") return;
const added = new Set(append ? items.slice(previous.length) : items.slice(0, count));
for (const item of container.querySelectorAll("[data-scroll-item]")) if (added.has(item.dataset.scrollItem ?? "")) item.animate({ opacity: [0, 1] }, {
duration: 180,
easing: "ease-out"
});
});
const canLoad = computed(() => props.active && !props.loadingBlocked && !props.refreshing && !refreshingPull.value && !refreshOffset.value);
const showFooter = computed(() => props.hasMore || props.loading || props.error);
const loadingPage = shallowRef(false);
const preloadTimer = useTimeoutFn(checkPreload, () => props.loadInterval ?? 100, { immediate: false });
let disposed = false;
onScopeDispose(() => {
disposed = true;
});
async function requestMore(direction = "next", retry = false) {
if (!canLoad.value || props.loading || loadingPage.value) return;
loadingPage.value = true;
try {
await (retry ? props.retryLoadMore ?? props.loadMore : props.loadMore)(direction);
} finally {
loadingPage.value = false;
if (!disposed) preloadTimer.start();
}
}
function checkPreload() {
const element = viewport.value;
if (!element?.clientHeight || !canLoad.value || props.loading || loadingPage.value) return;
const pulling = edgePreload.value;
const direction = pulling === "previous" && props.hasPrevious && !props.previousError ? pulling : pulling === "next" && props.hasMore && !props.error ? pulling : props.preloadDirection;
if (direction) requestMore(direction);
else if (!preloadTimer.isPending.value && props.canPreload && props.hasMore && !props.error && element.scrollHeight - element.clientHeight - element.scrollTop <= props.preloadDistance + 1) requestMore();
}
useEventListener$1(viewport, "scroll", checkPreload, { passive: true });
useResizeObserver(() => [viewport.value, content.value], checkPreload);
watch(() => [
canLoad.value,
props.hasMore,
props.hasPrevious,
props.loading,
props.error,
props.previousError,
props.canPreload,
props.preloadDirection,
edgePreload.value
], checkPreload, { flush: "post" });
__expose({
viewport,
content
});
return (_ctx, _cache) => {
return openBlock(), createElementBlock("div", {
ref_key: "viewport",
ref: viewport,
class: normalizeClass(["infinite-scroll", { "is-zoomed": zoomed.value }])
}, [
renderSlot(_ctx.$slots, "header"),
(openBlock(), createBlock(resolveDynamicComponent(__props.contentAs ?? "div"), mergeProps({
ref_key: "content",
ref: content,
class: "transition-none"
}, __props.contentAttrs ?? {}, { style: contentStyle.value }), {
default: withCtx(() => [
__props.virtual && _ctx.$slots.virtual ? renderSlot(_ctx.$slots, "virtual", {
viewport: viewport.value,
preserveEdgePosition
}, void 0, void 0, 0) : renderSlot(_ctx.$slots, "default", {
viewport: viewport.value,
preserveEdgePosition
}, void 0, void 0, 1),
showFooter.value ? (openBlock(), createBlock(LoadMoreIndicator_default, {
key: 2,
loading: Boolean(__props.loading),
error: __props.error,
"show-hint": Boolean(__props.showLoadHint),
onLoad: _cache[0] || (_cache[0] = ($event) => requestMore()),
onRetry: _cache[1] || (_cache[1] = ($event) => requestMore("next", true))
}, null, 8, [
"loading",
"error",
"show-hint"
])) : createCommentVNode("", true),
renderSlot(_ctx.$slots, "after-content")
]),
_: 3
}, 16, ["style"])),
createBaseVNode("div", _hoisted_1$13, [createVNode(ScrollEdgeIndicator_default, {
class: "infinite-scroll-refresh",
offset: unref(refreshOffset),
ready: unref(pullReady),
refreshing: __props.refreshing || refreshingPull.value
}, null, 8, [
"offset",
"ready",
"refreshing"
]), createVNode(ScrollEdgeIndicator_default, {
class: normalizeClass(["infinite-scroll-end", __props.endIndicatorClass]),
offset: unref(endOffset),
edge: "bottom"
}, null, 8, ["class", "offset"])]),
renderSlot(_ctx.$slots, "after", { pullOffset: unref(refreshOffset) })
], 2);
};
}
});
var _hoisted_1$12 = {
key: 0,
class: "tabular-nums"
};
var _hoisted_2$10 = ["aria-labelledby"];
var _hoisted_3$9 = { class: "gallery-comments-header flex items-center justify-between gap-3 border-b border-solid border-line" };
var _hoisted_4$7 = ["id"];
var _hoisted_5$6 = {
key: 0,
class: "text-[13px] font-normal text-muted tabular-nums"
};
var _hoisted_6$6 = { class: "flex items-center gap-1" };
var _hoisted_7$6 = ["disabled"];
var _hoisted_8$6 = {
key: 0,
class: "py-3 text-muted",
role: "status"
};
var _hoisted_9$6 = {
key: 1,
role: "list",
class: "m-0 list-none divide-y divide-solid divide-line p-0"
};
var _hoisted_10$6 = ["data-scroll-item"];
var _hoisted_11$6 = { class: "flex flex-wrap items-baseline gap-x-2.5 gap-y-0.5" };
var _hoisted_12$5 = { class: "font-semibold" };
var _hoisted_13$5 = {
key: 0,
class: "text-[12px] text-muted"
};
var _hoisted_14$5 = {
key: 1,
class: "ml-auto text-[12px] whitespace-nowrap text-muted tabular-nums"
};
var _hoisted_15$3 = { class: "mt-1.5 leading-relaxed whitespace-pre-wrap" };
var _hoisted_16$3 = ["href", "onClick"];
var _hoisted_17$3 = {
key: 2,
class: "py-5 text-muted"
};
var GalleryComments_default = defineComponent({
__name: "GalleryComments",
props: {
galleryHref: {},
comments: {},
active: { type: Boolean },
loadComments: { type: Function },
refreshComments: { type: Function },
loadCommentTotal: { type: Function }
},
emits: ["navigate"],
setup(__props, { emit: __emit }) {
const props = __props;
const emit = __emit;
const titleId = useId();
const dialog = useTemplateRef("dialog");
const scroll = useTemplateRef("scroll");
const viewport = computed(() => scroll.value?.viewport ?? null);
const trigger = useTemplateRef("trigger");
const open = shallowRef(false);
const loaded = shallowRef();
const comments = computed(() => loaded.value ?? props.comments);
const fetchedTotal = shallowRef();
const total = computed(() => comments.value?.total ?? fetchedTotal.value);
const scrollItemKeys = computed(() => comments.value?.items.map((comment) => String(comment.id)));
const loading = shallowRef(false);
const failed = shallowRef(false);
const refreshing = shallowRef(false);
const refreshFailed = shallowRef(false);
const motion = usePreferredReducedMotion();
const reducedMotion = computed(() => motion.value === "reduce");
const pullBlocked = computed(() => !open.value || !props.active || refreshing.value);
const reachedEnd = computed(() => Boolean(comments.value?.items.length && !comments.value.moreHref && !loading.value && !failed.value));
const { y: scrollY, isScrolling, measure } = useScroll(viewport);
const closeButton = useTemplateRef("closeButton");
let stoppingScroll = false;
let request;
const scrollPositions = new Map();
watch([
() => props.active,
() => props.galleryHref,
total
], async ([active, href, count], _, onCleanup) => {
if (!active || count !== void 0 || !props.loadCommentTotal) return;
const controller = new AbortController();
onCleanup(() => controller.abort());
try {
const result = await props.loadCommentTotal(href, controller.signal);
if (!controller.signal.aborted) fetchedTotal.value = result;
} catch {}
}, { immediate: true });
function saveScrollPosition() {
if (viewport.value) scrollPositions.set(props.galleryHref, viewport.value.scrollTop);
}
function cancelRequest() {
request?.abort();
request = void 0;
loading.value = false;
failed.value = false;
refreshing.value = false;
refreshFailed.value = false;
}
function close() {
saveScrollPosition();
open.value = false;
cancelRequest();
}
function openLink(event, href) {
emit("navigate", event, href);
if (event.defaultPrevented) close();
}
async function loadMore() {
const current = comments.value;
if (!open.value || !current?.moreHref || request) return;
const controller = new AbortController();
request = controller;
const refresh = failed.value;
loading.value = true;
failed.value = false;
try {
const result = await props.loadComments(current.moreHref, controller.signal, refresh);
if (!controller.signal.aborted) loaded.value = {
items: appendUnique(current.items, result.items, (comment) => comment.id),
total: result.total ?? current.total,
moreHref: result.moreHref
};
} catch {
if (!controller.signal.aborted) failed.value = true;
} finally {
if (request === controller) {
request = void 0;
loading.value = false;
}
}
}
async function refresh() {
if (pullBlocked.value) return;
request?.abort();
const controller = new AbortController();
request = controller;
loading.value = false;
refreshing.value = true;
refreshFailed.value = false;
try {
const result = await props.refreshComments(props.galleryHref, controller.signal);
if (controller.signal.aborted) return;
loaded.value = result;
failed.value = false;
viewport.value?.scrollTo({
top: 0,
behavior: "instant"
});
} catch {
if (!controller.signal.aborted) refreshFailed.value = true;
} finally {
if (request === controller) {
request = void 0;
refreshing.value = false;
}
}
}
async function backToTop() {
const element = viewport.value;
if (!element || stoppingScroll) return;
if (isScrolling.value) {
stoppingScroll = true;
await stopScrollMomentum(element);
stoppingScroll = false;
if (!open.value || viewport.value !== element) return;
}
closeButton.value?.focus({ preventScroll: true });
element.scrollTo({
top: 0,
behavior: reducedMotion.value ? "instant" : "smooth"
});
}
watch(dialog, (element) => {
if (!element) return;
element.showModal();
measure();
const top = scrollPositions.get(props.galleryHref);
if (top !== void 0) requestAnimationFrame(() => viewport.value?.scrollTo({
top,
behavior: "instant"
}));
}, { flush: "post" });
watch(() => props.comments, () => {
cancelRequest();
loaded.value = void 0;
fetchedTotal.value = void 0;
});
watch(() => props.active, (active) => {
if (!active) {
dialog.value?.close();
close();
}
}, { flush: "sync" });
onBeforeUnmount(() => {
dialog.value?.close();
cancelRequest();
});
function restoreFocus() {
if (!open.value && props.active) trigger.value?.focus({ preventScroll: true });
}
return (_ctx, _cache) => {
return openBlock(), createElementBlock(Fragment, null, [createBaseVNode("button", {
ref_key: "trigger",
ref: trigger,
class: "pill shrink-0 whitespace-nowrap max-[960px]:min-h-[44px]!",
type: "button",
"aria-haspopup": "dialog",
onClick: _cache[0] || (_cache[0] = ($event) => open.value = true)
}, [
createVNode(unref(MessageSquare), {
size: 15,
"aria-hidden": "true"
}),
_cache[3] || (_cache[3] = createTextVNode(" 评论", -1)),
total.value !== void 0 ? (openBlock(), createElementBlock("span", _hoisted_1$12, toDisplayString(total.value), 1)) : createCommentVNode("", true)
], 512), createVNode(Transition, {
name: "gallery-comments-drawer",
onAfterLeave: restoreFocus
}, {
default: withCtx(() => [open.value ? (openBlock(), createElementBlock("dialog", {
key: 0,
ref_key: "dialog",
ref: dialog,
class: "gallery-comments-drawer",
"aria-labelledby": unref(titleId),
onCancel: withModifiers(close, ["prevent"]),
onClick: withModifiers(close, ["self"]),
onWheel: _cache[1] || (_cache[1] = withModifiers(() => {}, ["self", "prevent"])),
onTouchmove: _cache[2] || (_cache[2] = withModifiers(() => {}, ["self", "prevent"]))
}, [createVNode(InfiniteScroll_default, {
ref_key: "scroll",
ref: scroll,
class: "gallery-comments-panel gallery-comments-viewport",
"content-attrs": { class: "px-5 pb-[env(safe-area-inset-bottom)]" },
"item-keys": scrollItemKeys.value,
refresh,
"refresh-blocked": pullBlocked.value,
refreshing: refreshing.value,
"load-more": loadMore,
loading: loading.value,
"has-more": Boolean(comments.value?.moreHref),
error: failed.value ? "评论加载失败。" : void 0,
"reached-end": reachedEnd.value,
active: open.value && __props.active,
"preload-distance": 140,
"aria-busy": loading.value || refreshing.value
}, {
header: withCtx(() => [createBaseVNode("header", _hoisted_3$9, [createBaseVNode("h2", {
id: unref(titleId),
class: "flex items-baseline gap-2 text-[18px] font-bold"
}, [_cache[4] || (_cache[4] = createTextVNode(" 评论 ", -1)), total.value !== void 0 ? (openBlock(), createElementBlock("span", _hoisted_5$6, toDisplayString(total.value), 1)) : createCommentVNode("", true)], 8, _hoisted_4$7), createBaseVNode("div", _hoisted_6$6, [createBaseVNode("button", {
class: "icon-button",
type: "button",
"aria-label": "刷新评论",
title: "刷新评论",
disabled: refreshing.value,
onClick: refresh
}, [refreshing.value ? (openBlock(), createBlock(LoadingSpinner_default, {
key: 0,
size: 18
})) : (openBlock(), createBlock(unref(RefreshCw), {
key: 1,
size: 18,
"aria-hidden": "true"
}))], 8, _hoisted_7$6), createBaseVNode("button", {
ref_key: "closeButton",
ref: closeButton,
class: "icon-button",
type: "button",
"aria-label": "关闭评论",
autofocus: "",
onClick: close
}, [createVNode(unref(X), {
size: 20,
"aria-hidden": "true"
})], 512)])])]),
default: withCtx(() => [refreshFailed.value ? (openBlock(), createElementBlock("p", _hoisted_8$6, "刷新评论失败,可点击刷新按钮重试。")) : createCommentVNode("", true), comments.value?.items.length ? (openBlock(), createElementBlock("ul", _hoisted_9$6, [(openBlock(true), createElementBlock(Fragment, null, renderList(comments.value.items, (comment) => {
return openBlock(), createElementBlock("li", {
key: comment.id,
class: "py-4 wrap-anywhere",
"data-scroll-item": comment.id
}, [createBaseVNode("div", _hoisted_11$6, [
createBaseVNode("span", _hoisted_12$5, toDisplayString(comment.author || "未知作者"), 1),
comment.posted ? (openBlock(), createElementBlock("span", _hoisted_13$5, toDisplayString(comment.posted), 1)) : createCommentVNode("", true),
comment.score !== void 0 ? (openBlock(), createElementBlock("span", _hoisted_14$5, " 评分 " + toDisplayString(comment.score), 1)) : createCommentVNode("", true)
]), createBaseVNode("p", _hoisted_15$3, [(openBlock(true), createElementBlock(Fragment, null, renderList(comment.body, (part, index) => {
return openBlock(), createElementBlock(Fragment, { key: index }, [part.href ? (openBlock(), createElementBlock("a", {
key: 0,
class: "gallery-comment-link",
href: part.href,
onClick: ($event) => openLink($event, part.href)
}, toDisplayString(part.text), 9, _hoisted_16$3)) : (openBlock(), createElementBlock(Fragment, { key: 1 }, [createTextVNode(toDisplayString(part.text), 1)], 64))], 64);
}), 128))])], 8, _hoisted_10$6);
}), 128))])) : !comments.value?.moreHref ? (openBlock(), createElementBlock("p", _hoisted_17$3, toDisplayString(comments.value ? "暂无评论" : "无法读取评论。"), 1)) : createCommentVNode("", true)]),
after: withCtx(() => [createVNode(BackToTopButton_default, {
visible: unref(scrollY) > 1,
label: "回到评论顶部",
onClick: backToTop
}, null, 8, ["visible"])]),
_: 1
}, 8, [
"item-keys",
"refresh-blocked",
"refreshing",
"loading",
"has-more",
"error",
"reached-end",
"active",
"aria-busy"
])], 40, _hoisted_2$10)) : createCommentVNode("", true)]),
_: 1
})], 64);
};
}
});
var _hoisted_1$11 = {
key: 0,
class: "col-span-full basis-full text-[13px] text-muted",
role: "status"
};
var GalleryFavoriteButton_default = defineComponent({
__name: "GalleryFavoriteButton",
props: {
page: {},
favorite: {},
updateFavorite: { type: Function }
},
setup(__props) {
const props = __props;
const busy = shallowRef(false);
const message = shallowRef("");
async function changeFavorite(event) {
if (!isPrimaryClick(event)) return;
if (busy.value) {
event.preventDefault();
return;
}
const { page, favorite } = props;
message.value = "";
busy.value = true;
try {
if ("href" in favorite) {
const popup = window.open(favorite.href, "_blank", "popup,width=675,height=415");
if (!popup) return;
event.preventDefault();
await new Promise((resolve) => {
const timer = window.setInterval(() => {
if (!popup.closed) return;
window.clearInterval(timer);
resolve();
}, 400);
});
}
const updated = await props.updateFavorite(page);
if (updated.saved !== favorite.saved) message.value = updated.saved ? "已加入收藏夹" : "已取消收藏";
else if ("submit" in favorite) message.value = "站点未更新收藏状态,请重试。";
} catch (error) {
message.value = error instanceof Error ? error.message : "收藏操作失败,请重试。";
} finally {
busy.value = false;
}
}
return (_ctx, _cache) => {
return openBlock(), createElementBlock(Fragment, null, [createVNode(ActionButton_default, {
class: "favorite-button",
href: "href" in __props.favorite ? __props.favorite.href : void 0,
target: "href" in __props.favorite ? "_blank" : void 0,
rel: "href" in __props.favorite ? "noopener" : void 0,
disabled: "submit" in __props.favorite && busy.value ? true : void 0,
"aria-busy": busy.value,
title: __props.favorite.saved ? "href" in __props.favorite ? "管理收藏" : "取消收藏" : void 0,
onClick: changeFavorite
}, {
default: withCtx(() => [busy.value ? (openBlock(), createBlock(LoadingSpinner_default, {
key: 0,
size: 17,
"aria-hidden": "true"
})) : (openBlock(), createBlock(unref(Heart), {
key: 1,
size: 17,
fill: __props.favorite.saved ? "currentColor" : "none",
"aria-hidden": "true"
}, null, 8, ["fill"])), createTextVNode(" " + toDisplayString(__props.favorite.saved ? "href" in __props.favorite ? "已收藏" : "取消收藏" : "加入收藏"), 1)]),
_: 1
}, 8, [
"href",
"target",
"rel",
"disabled",
"aria-busy",
"title"
]), message.value ? (openBlock(), createElementBlock("p", _hoisted_1$11, toDisplayString(message.value), 1)) : createCommentVNode("", true)], 64);
};
}
});
var _hoisted_1$10 = ["src", "loading"];
var _hoisted_2$9 = {
key: 2,
class: "muted grid h-full place-items-center"
};
var ThumbnailTile_default = defineComponent({
__name: "ThumbnailTile",
props: {
thumb: {},
fill: { type: Boolean }
},
setup(__props) {
const props = __props;
const tile = useTemplateRef("tile");
const { width, height } = useElementSize(tile);
const crop = computed(() => {
const sprite = props.thumb.sprite;
if (!sprite) return;
const scale = Math.min(width.value / sprite.width, height.value / sprite.height);
return {
width: sprite.width + "px",
height: sprite.height + "px",
left: (width.value - sprite.width * scale) / 2 + "px",
top: (height.value - sprite.height * scale) / 2 + "px",
transform: "scale(" + scale + ")",
backgroundImage: `url("${props.thumb.image}")`,
backgroundPosition: sprite.x + "px " + sprite.y + "px"
};
});
return (_ctx, _cache) => {
return openBlock(), createElementBlock("div", {
ref_key: "tile",
ref: tile,
class: normalizeClass(["thumbnail-image relative overflow-hidden bg-panel", __props.fill ? "size-full" : "aspect-[4/5]"])
}, [crop.value ? (openBlock(), createElementBlock("span", {
key: 0,
class: "thumbnail-sprite absolute origin-top-left bg-no-repeat",
style: normalizeStyle(crop.value)
}, null, 4)) : __props.thumb.image ? (openBlock(), createElementBlock("img", {
key: 1,
class: "size-full object-contain",
src: __props.thumb.image,
alt: "",
loading: __props.fill ? "eager" : "lazy",
decoding: "async"
}, null, 8, _hoisted_1$10)) : (openBlock(), createElementBlock("span", _hoisted_2$9, toDisplayString(__props.thumb.index), 1))], 2);
};
}
});
var _hoisted_1$9 = { class: "detail-copy" };
var _hoisted_2$8 = { class: "category" };
var _hoisted_3$8 = { key: 0 };
var _hoisted_4$6 = {
key: 0,
class: "subtitle"
};
var _hoisted_5$5 = {
key: 1,
class: "details-grid"
};
var _hoisted_6$5 = { class: "detail-media" };
var _hoisted_7$5 = {
key: 0,
class: "detail-cover"
};
var _hoisted_8$5 = ["src"];
var _hoisted_9$5 = { class: "reading-actions detail-actions" };
var _hoisted_10$5 = {
key: 0,
class: "detail-tag-groups",
"aria-label": "画廊标签"
};
var _hoisted_11$5 = { class: "section-title flex items-center justify-between gap-2" };
var _hoisted_12$4 = { class: "flex flex-wrap items-baseline gap-x-2 gap-y-0.5" };
var _hoisted_13$4 = ["id"];
var _hoisted_14$4 = {
key: 0,
class: "count whitespace-nowrap"
};
var _hoisted_15$2 = [
"aria-posinset",
"aria-setsize",
"data-gallery-href",
"data-scroll-item"
];
var _hoisted_16$2 = [
"href",
"aria-label",
"onClick"
];
var _hoisted_17$2 = { class: "thumbnail-number block p-1 text-[12px] tabular-nums" };
var _hoisted_18$2 = {
key: 1,
class: "empty"
};
var GalleryDetail_default = defineComponent({
__name: "GalleryDetail",
props: {
page: {},
galleryProgress: {},
galleryReadHref: {},
savedForLater: { type: Boolean },
bookmarksBusy: { type: Boolean },
activeTag: {},
active: { type: Boolean },
updateFavorite: { type: Function },
loadComments: { type: Function },
refreshComments: { type: Function },
loadCommentTotal: { type: Function }
},
emits: [
"navigate",
"openCommentLink",
"startReading",
"toggleBookmark",
"tag"
],
setup(__props, { emit: __emit }) {
const props = __props;
const tags = useTagDirectoryStore();
const thumbnailsHeading = useId();
provideGalleryResizePosition();
function estimateThumbnailRowSize(_items, width) {
return Math.max(0, width - 2) * 1.25 + 28;
}
const emit = __emit;
const metadata = computed(() => {
const gallery = props.page;
return [
{
label: "语言",
value: gallery.language
},
{
label: "上传者",
value: gallery.uploader
},
{
label: "评分",
value: gallery.rating
},
{
label: "发布日期",
value: gallery.posted
}
].filter((item) => item.value);
});
const tagGroupLabels = new Map([
["language", "语言"],
["parody", "原作"],
["character", "角色"],
["group", "社团"],
["artist", "画师"],
["category", "分类"],
["tag", "标签"],
["cosplayer", "角色扮演者"],
["female", "女性"],
["male", "男性"],
["mixed", "混合"],
["other", "其他"],
["location", "地点"],
["reclass", "重新分类"],
["misc", "杂项"]
]);
const galleryTagGroups = computed(() => {
const gallery = props.page;
const groups = new Map();
for (const tag of gallery.tags) {
const tags = groups.get(tag.namespace);
if (tags) tags.push(tag);
else groups.set(tag.namespace, [tag]);
}
return Array.from(groups, ([namespace, tags]) => ({
namespace,
label: namespace ? tagGroupLabels.get(namespace) ?? namespace : "未分类",
tags
}));
});
return (_ctx, _cache) => {
return openBlock(), createElementBlock(Fragment, null, [
createBaseVNode("section", { class: normalizeClass(["detail", { "detail-with-cover": __props.page.cover }]) }, [
createBaseVNode("div", _hoisted_1$9, [
createBaseVNode("p", _hoisted_2$8, [createTextVNode(toDisplayString(__props.page.category), 1), __props.page.pages ? (openBlock(), createElementBlock("span", _hoisted_3$8, " / " + toDisplayString(__props.page.pages) + " 页", 1)) : createCommentVNode("", true)]),
createBaseVNode("h1", null, toDisplayString(__props.page.title), 1),
__props.page.subtitle && __props.page.subtitle !== __props.page.title ? (openBlock(), createElementBlock("p", _hoisted_4$6, toDisplayString(__props.page.subtitle), 1)) : createCommentVNode("", true),
metadata.value.length ? (openBlock(), createElementBlock("dl", _hoisted_5$5, [(openBlock(true), createElementBlock(Fragment, null, renderList(metadata.value, (item) => {
return openBlock(), createElementBlock("div", { key: item.label }, [createBaseVNode("dt", null, toDisplayString(item.label), 1), createBaseVNode("dd", null, toDisplayString(item.value), 1)]);
}), 128))])) : createCommentVNode("", true)
]),
createBaseVNode("div", _hoisted_6$5, [__props.page.cover ? (openBlock(), createElementBlock("div", _hoisted_7$5, [createBaseVNode("img", {
src: __props.page.cover,
alt: "",
decoding: "async"
}, null, 8, _hoisted_8$5)])) : createCommentVNode("", true), createBaseVNode("div", _hoisted_9$5, [
__props.galleryProgress ? (openBlock(), createBlock(ActionButton_default, {
key: 0,
variant: "primary",
href: __props.galleryProgress.href,
onClick: _cache[0] || (_cache[0] = ($event) => emit("navigate", $event, __props.galleryProgress.href))
}, {
default: withCtx(() => [createTextVNode(" 从第 " + toDisplayString(__props.galleryProgress.index) + " 页开始阅读 ", 1), createVNode(unref(ArrowRight), {
size: 17,
"aria-hidden": "true"
})]),
_: 1
}, 8, ["href"])) : createCommentVNode("", true),
__props.galleryReadHref || __props.galleryProgress ? (openBlock(), createBlock(ActionButton_default, {
key: 1,
variant: __props.galleryProgress ? "secondary" : "primary",
href: __props.galleryReadHref,
onClick: _cache[1] || (_cache[1] = ($event) => emit("startReading", $event))
}, {
default: withCtx(() => [createTextVNode(toDisplayString(__props.galleryProgress ? "从头开始阅读" : "进入阅读") + " ", 1), createVNode(unref(ArrowRight), {
size: 17,
"aria-hidden": "true"
})]),
_: 1
}, 8, ["variant", "href"])) : createCommentVNode("", true),
createVNode(BookmarkButton_default, {
saved: __props.savedForLater,
busy: __props.bookmarksBusy,
onToggle: _cache[2] || (_cache[2] = ($event) => emit("toggleBookmark", $event))
}, null, 8, ["saved", "busy"]),
__props.page.favorite ? (openBlock(), createBlock(GalleryFavoriteButton_default, {
key: __props.page.href,
page: __props.page,
favorite: __props.page.favorite,
"update-favorite": __props.updateFavorite
}, null, 8, [
"page",
"favorite",
"update-favorite"
])) : createCommentVNode("", true)
])]),
galleryTagGroups.value.length ? (openBlock(), createElementBlock("dl", _hoisted_10$5, [(openBlock(true), createElementBlock(Fragment, null, renderList(galleryTagGroups.value, (group) => {
return openBlock(), createElementBlock("div", {
key: group.namespace ?? "",
class: "detail-tag-group"
}, [createBaseVNode("dt", null, toDisplayString(group.label), 1), createBaseVNode("dd", null, [(openBlock(true), createElementBlock(Fragment, null, renderList(group.tags, (tag) => {
return openBlock(), createBlock(resolveDynamicComponent(tag.href ? "a" : "span"), {
key: tag.key ?? tag.href ?? tag.label,
class: "pill",
href: tag.href,
title: tag.key ?? tag.label,
"aria-haspopup": tag.href && tag.searchTerm ? "dialog" : void 0,
"aria-expanded": tag.href && tag.searchTerm ? __props.activeTag === tag : void 0,
"aria-controls": __props.activeTag === tag ? "gallery-tag-search" : void 0,
onClick: ($event) => emit("tag", $event, tag)
}, {
default: withCtx(() => [createTextVNode(toDisplayString(tag.key && unref(tags).translate?.(tag.key) || tag.label), 1)]),
_: 2
}, 1032, [
"href",
"title",
"aria-haspopup",
"aria-expanded",
"aria-controls",
"onClick"
]);
}), 128))])]);
}), 128))])) : createCommentVNode("", true)
], 2),
createBaseVNode("div", _hoisted_11$5, [createBaseVNode("div", _hoisted_12$4, [createBaseVNode("h2", { id: unref(thumbnailsHeading) }, "页面缩略图", 8, _hoisted_13$4), __props.page.thumbnails.length ? (openBlock(), createElementBlock("span", _hoisted_14$4, toDisplayString(__props.page.thumbnails[0]?.index) + "–" + toDisplayString(__props.page.thumbnails.at(-1)?.index) + " 页 ", 1)) : createCommentVNode("", true)]), (openBlock(), createBlock(GalleryComments_default, {
key: __props.page.href,
"gallery-href": __props.page.href,
comments: __props.page.comments,
active: __props.active,
"load-comments": __props.loadComments,
"refresh-comments": __props.refreshComments,
"load-comment-total": __props.loadCommentTotal,
onNavigate: _cache[3] || (_cache[3] = (event, href) => emit("openCommentLink", event, href))
}, null, 8, [
"gallery-href",
"comments",
"active",
"load-comments",
"refresh-comments",
"load-comment-total"
]))]),
__props.page.thumbnails.length ? (openBlock(), createBlock(GalleryRows_default, {
key: __props.page.href,
class: "thumbnails",
group: "thumbnails",
"aria-labelledby": unref(thumbnailsHeading),
items: __props.page.thumbnails,
"estimate-row-size": estimateThumbnailRowSize
}, {
default: withCtx(({ item: thumb, position }) => [createBaseVNode("div", {
role: "listitem",
"aria-posinset": position,
"aria-setsize": __props.page.thumbnails.length,
"data-gallery-href": thumb.href,
"data-scroll-item": thumb.href
}, [createBaseVNode("a", {
href: thumb.href,
class: "thumbnail",
"aria-label": "阅读第 " + thumb.index + " 页",
onClick: ($event) => emit("navigate", $event, thumb.href)
}, [createVNode(ThumbnailTile_default, { thumb }, null, 8, ["thumb"]), createBaseVNode("span", _hoisted_17$2, toDisplayString(thumb.index), 1)], 8, _hoisted_16$2)], 8, _hoisted_15$2)]),
_: 1
}, 8, ["aria-labelledby", "items"])) : (openBlock(), createElementBlock("p", _hoisted_18$2, "没有可用的页面缩略图。"))
], 64);
};
}
});
function useReaderPreviews(frames, visible, loadThumbnails) {
const previews = shallowReactive(new Map());
const loadedImages = shallowReactive(new Map());
const attempted = new Set();
let request;
const { start: schedule, stop } = useTimeoutFn(loadNext, 120, { immediate: false });
function isLoaded(frame) {
return loadedImages.get(frame.href) === frame.image;
}
function previewFor(frame) {
if (isLoaded(frame)) return;
return previews.get(frame.chapter)?.get(frame.index);
}
function markLoaded(frame) {
loadedImages.set(frame.href, frame.image);
}
function markFailed(frame) {
loadedImages.delete(frame.href);
schedule();
}
async function loadNext() {
if (!visible.value || request) return;
const frame = frames.value.find((frame) => !isLoaded(frame) && !previews.get(frame.chapter)?.has(frame.index) && !attempted.has(frame.href));
if (!frame) return;
const controller = new AbortController();
request = controller;
try {
const items = await loadThumbnails(frame.chapter, frame.index, controller.signal);
if (!controller.signal.aborted) {
const batch = new Map(previews.get(frame.chapter));
for (const item of items) if (item.image) batch.set(item.index, item);
previews.set(frame.chapter, batch);
attempted.add(frame.href);
}
} catch {
if (!controller.signal.aborted) {
for (const candidate of frames.value) if (candidate.chapter === frame.chapter) attempted.add(candidate.href);
attempted.add(frame.href);
}
} finally {
if (request === controller) {
request = void 0;
if (visible.value) schedule();
}
}
}
function cancel() {
stop();
request?.abort();
request = void 0;
}
watch([frames, visible], ([, active]) => {
if (active) schedule();
else cancel();
}, {
immediate: true,
flush: "post"
});
onScopeDispose(cancel);
return {
isLoaded,
previewFor,
markLoaded,
markFailed
};
}
function useReaderScrollPosition(props, framesElement, viewportState, layout, updateGeometry, showPage) {
const { endSpace, seekingPage, restoringPage, edgeTranslation } = viewportState;
const { slots, virtualizer, rendered } = layout;
function findPage(container, chapter, index) {
return container.querySelector(`[data-reader-chapter="${chapter}"][data-reader-index="${index}"]`);
}
function captureHistoryAnchor(chapter, index) {
const viewport = props.viewport;
const container = framesElement.value;
const frame = props.frames.find((frame) => frame.chapter === chapter && frame.index === index);
if (!viewport || !container || !frame) return;
const bounds = findPage(container, chapter, index)?.getBoundingClientRect();
const line = viewport.getBoundingClientRect().top + Math.floor(viewport.clientHeight / 3);
return {
chapter,
index,
href: frame.href,
atStart: viewport.scrollTop <= 1,
progress: bounds?.height ? (line - bounds.top + edgeTranslation(container)) / bounds.height : void 0,
imageSizes: layout.snapshotImageSizes()
};
}
function targetScrollTop(target, viewport, container, anchor) {
const bounds = target.getBoundingClientRect();
const viewportBounds = viewport.getBoundingClientRect();
const line = Math.floor(viewport.clientHeight / 3);
const headerHeight = viewport.querySelector(".masthead")?.offsetHeight ?? 0;
const offset = anchor?.progress === void 0 ? Math.min(line, Math.max(headerHeight + 8, line - bounds.height / 2)) : line - bounds.height * anchor.progress;
const position = bounds.top - viewportBounds.top + viewport.scrollTop - (anchor ? edgeTranslation(container) : 0);
return anchor?.atStart ? 0 : Math.max(0, Math.round(position - offset));
}
async function waitForPage(container, chapter, index, signal, anchor) {
if (anchor) updateGeometry();
await nextTick();
let target = findPage(container, chapter, index);
if (anchor && !target && !signal.aborted) {
await afterRenderedFrame();
target = findPage(container, chapter, index);
}
return target;
}
async function scrollToPage(chapter, index, signal, anchor) {
const viewport = props.viewport;
const container = framesElement.value;
const frame = props.frames.find((frame) => frame.chapter === chapter && frame.index === index && (!anchor || anchor.href === frame.href));
if (!viewport || !container || !frame || signal.aborted) return false;
const request = { href: frame.href };
seekingPage.value = request;
restoringPage.value = void 0;
try {
const target = await waitForPage(container, chapter, index, signal, anchor);
if (!target || signal.aborted) return false;
const top = targetScrollTop(target, viewport, container, anchor);
const extra = Math.ceil(top - (viewport.scrollHeight - viewport.clientHeight));
if (extra > 0) {
endSpace.value += extra;
await nextTick();
}
if (signal.aborted) return false;
if (anchor) {
viewportState.invalidateScrollWrites();
viewport.scrollTo({
top,
behavior: "instant"
});
} else virtualizer.value.scrollToOffset(top, { behavior: "instant" });
return true;
} finally {
if (seekingPage.value === request) seekingPage.value = void 0;
}
}
function restoreHistoryAnchor(anchor, signal) {
if (!signal.aborted && anchor.imageSizes.size) layout.restoreImageSizes(anchor.imageSizes);
return scrollToPage(anchor.chapter, anchor.index, signal, anchor);
}
watch([
() => props.scrollTop,
() => props.trackPosition,
rendered
], () => {
const viewport = props.viewport;
if (!viewport || !props.trackPosition || seekingPage.value || restoringPage.value) return;
const line = Math.floor(viewport.clientHeight / 3) + viewport.scrollTop;
const item = virtualizer.value.getVirtualItems().find(({ start, end }) => end > line && start < line + 24);
const slot = item && slots.value[item.index];
const frame = slot && "frame" in slot ? slot.frame : void 0;
if (frame) showPage(frame.chapter, frame.index);
}, { flush: "post" });
return {
scrollToPage,
captureHistoryAnchor,
restoreHistoryAnchor
};
}
function useReaderViewport(props, framesElement, heightProbe, fitWidth) {
const geometry = shallowRef({
width: 0,
maxHeight: 0,
viewportHeight: 0,
offset: 0,
widthMode: false
});
const endSpace = shallowRef(0);
const seekingPage = shallowRef();
const restoringPage = shallowRef();
const prepending = shallowRef(false);
let scrollWrite = 0;
let savedResize;
function invalidateScrollWrites() {
scrollWrite += 1;
}
function edgeTranslation(container) {
const transform = container.closest("main")?.style.transform;
return transform ? new DOMMatrixReadOnly(transform).m42 : 0;
}
const writeScroll = (offset, options, instance) => {
const viewport = instance.scrollElement;
if (!viewport) return;
const write = ++scrollWrite;
const apply = () => {
if (write !== scrollWrite || props.viewport !== viewport) return;
const before = viewport.scrollTop;
elementScroll(offset, options, instance);
if (savedResize && Math.abs(before - savedResize.scrollTop) <= 1) savedResize.scrollTop = viewport.scrollTop;
};
if (options.behavior === void 0 || options.adjustments !== void 0) queueMicrotask(() => void nextTick(apply));
else apply();
};
function observe(layout) {
const { slots, virtualizer } = layout;
const restoreAfterResize = useDebounceFn(restorePosition, 80);
restoreOnPrepend();
useEventListener$1(() => props.viewport, "scroll", () => {
const viewport = props.viewport;
if (!viewport || !savedResize || restoringPage.value) return;
const lastTop = savedResize.scrollTop;
const clampedTop = Math.min(lastTop, Math.max(0, viewport.scrollHeight - viewport.clientHeight));
if (Math.abs(viewport.scrollTop - lastTop) > 1 && Math.abs(viewport.scrollTop - clampedTop) > 1) savedResize = void 0;
}, { passive: true });
watch([
() => props.returningToTop,
seekingPage,
restoringPage
], ([returning, seeking, restoring]) => {
if (returning || seeking) savedResize = void 0;
virtualizer.value.shouldAdjustScrollPositionOnItemSizeChange = returning || seeking || restoring ? () => false : void 0;
}, {
immediate: true,
flush: "sync"
});
watch([
framesElement,
() => props.viewport,
() => props.loadPreviousFailure,
fitWidth
], updateGeometry, { flush: "post" });
let resizeFrame = 0;
useResizeObserver(() => [
props.viewport,
framesElement.value,
framesElement.value?.closest("main")
], () => {
cancelAnimationFrame(resizeFrame);
resizeFrame = requestAnimationFrame(updateGeometry);
});
onScopeDispose(() => {
invalidateScrollWrites();
cancelAnimationFrame(resizeFrame);
restoringPage.value = void 0;
});
watch([
() => geometry.value.width,
() => geometry.value.maxHeight,
() => geometry.value.widthMode
], () => {
virtualizer.value.measure();
}, { flush: "post" });
function updateGeometry() {
const container = framesElement.value;
const viewport = props.viewport;
const probe = heightProbe.value;
if (!container || !viewport || !probe || !container.clientWidth) return;
const bounds = container.getBoundingClientRect();
const width = bounds.width;
const viewportHeight = viewport.clientHeight;
const maxHeight = Number.parseFloat(getComputedStyle(probe).maxHeight) || Math.max(360, viewportHeight * .69);
const offset = bounds.top - viewport.getBoundingClientRect().top + viewport.scrollTop - edgeTranslation(container);
const widthMode = fitWidth.value;
const previous = geometry.value;
const reflow = width !== previous.width || maxHeight !== previous.maxHeight || viewportHeight !== previous.viewportHeight || widthMode !== previous.widthMode;
const restoring = restoringPage.value;
const anchor = reflow && previous.width && props.trackPosition && !props.returningToTop && !seekingPage.value ? restoring ?? savedResize?.anchor ?? captureResizeAnchor(viewport) : void 0;
const request = anchor && { ...anchor };
if (request) restoringPage.value = request;
if (reflow || Math.abs(offset - previous.offset) > .5) geometry.value = {
width,
maxHeight,
viewportHeight,
offset,
widthMode
};
if (request) restoreAfterResize(viewport, container, request);
}
function captureResizeAnchor(viewport) {
if (viewport.scrollTop <= 1) return;
const line = viewport.scrollTop + Math.floor(geometry.value.viewportHeight / 3);
const row = virtualizer.value.getVirtualItemForOffset(line);
const slot = row && slots.value[row.index];
const frame = slot && "frame" in slot ? slot.frame : void 0;
if (row && frame) return {
href: frame.href,
progress: Math.max(0, Math.min(1, (line - row.start) / row.size))
};
}
function restoreOnPrepend() {
watch(() => slots.value[0]?.key, (first, previous) => {
if (!previous || !first || !slots.value.some((slot) => slot.key === previous)) return;
const viewport = props.viewport;
const container = framesElement.value;
const main = container?.closest("main");
if (viewport && container && main) {
const bottom = container.getBoundingClientRect().bottom - edgeTranslation(container) + endSpace.value + parseFloat(getComputedStyle(main).paddingBottom);
const unused = viewport.getBoundingClientRect().bottom - bottom;
if (unused > 0) endSpace.value += Math.ceil(unused);
}
prepending.value = true;
nextTick(() => prepending.value = false);
}, { flush: "sync" });
}
async function restorePosition(viewport, container, request) {
await afterRenderedFrame();
if (restoringPage.value !== request) return;
const index = props.frames.findIndex((frame) => frame.href === request.href);
const target = container.querySelector(`[data-index="${index}"]`);
if (target && props.trackPosition && !props.returningToTop && !seekingPage.value) {
const bounds = target.getBoundingClientRect();
const offset = Math.floor(viewport.clientHeight / 3) - Math.min(Math.max(0, bounds.height - 1), bounds.height * request.progress);
const top = bounds.top - viewport.getBoundingClientRect().top + viewport.scrollTop - offset;
viewport.scrollTo({
top: Math.round(top),
behavior: "instant"
});
savedResize = {
anchor: request,
scrollTop: viewport.scrollTop
};
}
restoringPage.value = void 0;
}
return { updateGeometry };
}
return {
geometry,
endSpace,
seekingPage,
restoringPage,
prepending,
writeScroll,
invalidateScrollWrites,
edgeTranslation,
observe
};
}
function useReaderVirtualLayout(props, viewport) {
const { geometry, seekingPage, restoringPage, prepending, writeScroll } = viewport;
const gap = 18;
const minHeight = 180;
const focusedPage = shallowRef();
const imageSizes = shallowReactive(new Map());
const entryPage = props.frames[0]?.href;
const headBuffer = computed(() => props.frames[0]?.href !== entryPage ? props.buffer.head : []);
const slots = computed(() => [
...headBuffer.value.map((key) => ({ key })),
...props.frames.map((frame, position) => ({
key: `${frame.chapter}:${frame.index}`,
frame,
position
})),
...props.buffer.tail.map((key) => ({ key }))
]);
function dimensions(frame) {
return imageSizes.get(frame.image) ?? frame;
}
function estimateHeight(frame, width, maxHeight, widthMode) {
const size = dimensions(frame);
const ratio = size.width && size.height ? size.height / size.width : 1.4;
const scaled = widthMode ? width * ratio : Math.min(maxHeight, Math.min(width, size.width || width) * ratio);
return Math.max(minHeight, scaled);
}
const virtualizer = createVirtualizer();
const totalHeight = computed(() => virtualizer.value.getTotalSize());
const rendered = computed(() => {
const { offset } = geometry.value;
return virtualizer.value.getVirtualItems().flatMap((item) => {
const slot = slots.value[item.index];
if (!slot || !("frame" in slot)) return [];
const { frame, position } = slot;
const size = dimensions(frame);
return [{
frame,
position,
top: item.start - offset,
width: size.width,
height: size.height,
pageHeight: item.size
}];
});
});
const renderedBuffer = computed(() => virtualizer.value.getVirtualItems().flatMap((item) => {
const slot = slots.value[item.index];
if (!slot || "frame" in slot) return [];
return [{
key: slot.key,
top: item.start - geometry.value.offset,
height: item.size
}];
}));
function createVirtualizer() {
const rangeExtractor = computed(() => {
const retained = [focusedPage.value, (seekingPage.value ?? restoringPage.value)?.href].filter(Boolean).map((href) => slots.value.findIndex((slot) => "frame" in slot && slot.frame.href === href));
const pagesBehind = props.preloadPaused ? 0 : props.pagesBehind;
const pagesAhead = props.preloadPaused ? 0 : props.pagesAhead;
return ({ startIndex, endIndex, count }) => {
const start = Math.max(0, startIndex - pagesBehind);
const end = Math.min(count - 1, endIndex + pagesAhead);
const range = Array.from({ length: end - start + 1 }, (_, index) => start + index);
for (const index of retained) if (index >= 0 && (index < start || index > end) && !range.includes(index)) range.push(index);
return range.sort((a, b) => a - b);
};
});
return useVirtualizer(computed(() => {
const rows = slots.value;
const { width, maxHeight, offset, widthMode, viewportHeight } = geometry.value;
return {
count: rows.length,
enabled: width > 0,
anchorTo: prepending.value ? "end" : "start",
getScrollElement: () => props.viewport,
getItemKey: (position) => rows[position]?.key ?? position,
estimateSize: (position) => {
const row = rows[position];
return row && "frame" in row ? estimateHeight(row.frame, width, maxHeight, widthMode) : Math.max(minHeight, maxHeight / 2, viewportHeight / 2);
},
gap,
paddingEnd: gap,
scrollMargin: offset,
scrollToFn: writeScroll,
rangeExtractor: rangeExtractor.value,
useAnimationFrameWithResizeObserver: true
};
}));
}
function recordImageSize(position, url, event) {
const image = event.target;
if (!(image instanceof HTMLImageElement) || !image.naturalWidth || !image.naturalHeight) return;
const frame = props.frames[position];
if (frame?.image !== url) return;
const previous = dimensions(frame);
if (previous.width === image.naturalWidth && previous.height === image.naturalHeight) return;
props.preserveEdgePosition();
imageSizes.set(url, {
width: image.naturalWidth,
height: image.naturalHeight
});
const { width, maxHeight, widthMode } = geometry.value;
virtualizer.value.resizeItem(position + headBuffer.value.length, estimateHeight(frame, width, maxHeight, widthMode));
}
function snapshotImageSizes() {
return new Map(imageSizes);
}
function restoreImageSizes(sizes) {
for (const [url, size] of sizes) imageSizes.set(url, size);
virtualizer.value.measure();
}
return {
slots,
virtualizer,
rendered,
renderedBuffer,
totalHeight,
focusedPage,
recordImageSize,
snapshotImageSizes,
restoreImageSizes
};
}
function useReaderVirtualizer(props, framesElement, heightProbe, fitWidth, showPage) {
const viewport = useReaderViewport(props, framesElement, heightProbe, fitWidth);
const layout = useReaderVirtualLayout(props, viewport);
const { updateGeometry } = viewport.observe(layout);
const position = useReaderScrollPosition(props, framesElement, viewport, layout, updateGeometry, showPage);
return {
rendered: layout.rendered,
renderedBuffer: layout.renderedBuffer,
totalHeight: layout.totalHeight,
focusedPage: layout.focusedPage,
recordImageSize: layout.recordImageSize,
endSpace: viewport.endSpace,
...position
};
}
var _hoisted_1$8 = { class: "sr-only" };
var _hoisted_2$7 = {
key: 0,
class: "reader-previous-error infinite-error",
role: "status"
};
var _hoisted_3$7 = ["disabled"];
var _hoisted_4$5 = [
"data-index",
"data-reader-href",
"data-scroll-item",
"data-reader-chapter",
"data-reader-index",
"onFocusin"
];
var _hoisted_5$4 = [
"src",
"width",
"height",
"alt",
"onLoad",
"onError"
];
var _hoisted_6$4 = {
key: 2,
class: "empty frame-error relative mx-4 mt-4 self-start"
};
var _hoisted_7$4 = { role: "status" };
var _hoisted_8$4 = { class: "flex flex-wrap gap-x-2" };
var _hoisted_9$4 = ["onClick"];
var _hoisted_10$4 = ["onClick"];
var _hoisted_11$4 = ["href"];
var _hoisted_12$3 = {
key: 3,
class: "pointer-events-none absolute top-2.5 right-2.5 grid size-8 place-items-center rounded-full bg-surface text-ink shadow-sm",
role: "status"
};
var _hoisted_13$3 = { class: "sr-only" };
var _hoisted_14$3 = { class: "reader-page-label absolute right-2.5 bottom-2.5 rounded-md bg-[#101010d9] px-[7px] py-[3px] text-[11px] text-white tabular-nums" };
var ReaderPages_default = defineComponent({
__name: "ReaderPages",
props: {
viewport: {},
preserveEdgePosition: { type: Function },
frames: {},
pagesAhead: {},
pagesBehind: {},
preloadPaused: { type: Boolean },
buffer: {},
scrollTop: {},
trackPosition: { type: Boolean },
returningToTop: { type: Boolean },
brokenImages: {},
loadPreviousFailure: {},
title: {},
busy: { type: Boolean },
active: { type: Boolean },
nativeLink: { type: Function },
loadThumbnails: { type: Function },
imageRetryErrors: {},
retryingImages: {}
},
emits: [
"retryPrevious",
"imageError",
"imageLoad",
"retryImage",
"loadOriginalImage",
"showPage"
],
setup(__props, { expose: __expose, emit: __emit }) {
const props = __props;
const emit = __emit;
const preferences = usePreferencesStore();
const framesElement = useTemplateRef("framesElement");
const heightProbe = useTemplateRef("heightProbe");
const fitWidth = computed(() => preferences.readerFit === "width");
const { rendered, renderedBuffer, totalHeight, endSpace, focusedPage, recordImageSize, scrollToPage, captureHistoryAnchor, restoreHistoryAnchor } = useReaderVirtualizer(props, framesElement, heightProbe, fitWidth, (chapter, index) => emit("showPage", chapter, index));
const { isLoaded, previewFor, markLoaded, markFailed } = useReaderPreviews(computed(() => rendered.value.map(({ frame }) => frame)), computed(() => props.active && props.trackPosition && !props.preloadPaused), props.loadThumbnails);
const renderedPages = computed(() => rendered.value.map((page) => {
const { frame } = page;
const broken = props.brokenImages.has(frame.href);
const loading = props.retryingImages.has(frame.href) || !broken && !isLoaded(frame);
return {
...page,
broken,
loading,
preview: previewFor(frame)
};
}));
function imageLoaded(frame, position, event) {
const image = event.currentTarget;
if (!(image instanceof HTMLImageElement) || !image.naturalWidth || !image.naturalHeight) return;
markLoaded(frame);
recordImageSize(position, frame.image, event);
emit("imageLoad", frame, {
width: image.naturalWidth,
height: image.naturalHeight
});
}
__expose({
scrollToPage,
captureHistoryAnchor,
restoreHistoryAnchor
});
return (_ctx, _cache) => {
return openBlock(), createElementBlock(Fragment, null, [createBaseVNode("h1", _hoisted_1$8, toDisplayString(__props.title), 1), createBaseVNode("div", { class: normalizeClass(["reader-surface mx-auto block w-[min(100%,1000px)] overflow-visible bg-transparent", { "fit-width": fitWidth.value }]) }, [
__props.loadPreviousFailure ? (openBlock(), createElementBlock("div", _hoisted_2$7, [createBaseVNode("span", null, toDisplayString(__props.loadPreviousFailure), 1), createBaseVNode("button", {
class: "pill",
type: "button",
disabled: __props.busy,
onClick: _cache[0] || (_cache[0] = ($event) => emit("retryPrevious"))
}, "重试加载前一张", 8, _hoisted_3$7)])) : createCommentVNode("", true),
createBaseVNode("div", {
ref_key: "framesElement",
ref: framesElement,
class: "reader-frames relative",
style: normalizeStyle({ height: unref(totalHeight) + "px" }),
onFocusout: _cache[1] || (_cache[1] = ($event) => focusedPage.value = void 0)
}, [
createBaseVNode("span", {
ref_key: "heightProbe",
ref: heightProbe,
class: "reader-height-probe",
"aria-hidden": "true"
}, null, 512),
(openBlock(true), createElementBlock(Fragment, null, renderList(unref(renderedBuffer), ({ key, top, height }) => {
return openBlock(), createElementBlock("div", {
key,
class: "reader-buffer absolute inset-x-0 top-0",
style: normalizeStyle({
transform: "translateY(" + top + "px)",
height: height + "px"
}),
"aria-hidden": "true"
}, [createVNode(LoadingSpinner_default, { size: 24 })], 4);
}), 128)),
(openBlock(true), createElementBlock(Fragment, null, renderList(renderedPages.value, ({ frame, position, top, width, height, pageHeight, preview, broken, loading }) => {
return openBlock(), createElementBlock("article", {
key: frame.href,
class: "reader-frame absolute inset-x-0 top-0",
style: normalizeStyle({
transform: "translateY(" + top + "px)",
height: pageHeight + "px"
}),
"data-index": position,
"data-reader-href": frame.href,
"data-scroll-item": frame.href,
"data-reader-chapter": frame.chapter,
"data-reader-index": frame.index,
onFocusin: ($event) => focusedPage.value = frame.href
}, [
preview ? (openBlock(), createBlock(ThumbnailTile_default, {
key: 0,
thumb: preview,
class: "reader-frame-preview pointer-events-none absolute inset-0 opacity-70",
fill: "",
"aria-hidden": "true"
}, null, 8, ["thumb"])) : createCommentVNode("", true),
!broken ? (openBlock(), createElementBlock("img", {
key: frame.image,
class: "reader-page-image relative",
src: frame.image,
width,
height,
style: normalizeStyle(width && height ? {
"--reader-image-width": width + "px",
"--reader-image-ratio": width / height
} : void 0),
alt: "第 " + frame.index + " 页",
loading: "eager",
decoding: "async",
draggable: "false",
onLoad: ($event) => imageLoaded(frame, position, $event),
onError: () => {
unref(markFailed)(frame);
emit("imageError", frame);
}
}, null, 44, _hoisted_5$4)) : !loading ? (openBlock(), createElementBlock("div", _hoisted_6$4, [createBaseVNode("p", _hoisted_7$4, toDisplayString(__props.imageRetryErrors.get(frame.href) ?? "图片加载失败。"), 1), createBaseVNode("div", _hoisted_8$4, [
createBaseVNode("button", {
class: "pill",
type: "button",
onClick: ($event) => emit("retryImage", frame)
}, "重试图片", 8, _hoisted_9$4),
frame.originalHref ? (openBlock(), createElementBlock("button", {
key: 0,
class: "pill",
type: "button",
onClick: ($event) => emit("loadOriginalImage", frame)
}, " 加载原图 ", 8, _hoisted_10$4)) : createCommentVNode("", true),
__props.nativeLink ? (openBlock(), createElementBlock("a", {
key: 1,
class: "pill",
href: __props.nativeLink(frame.href)
}, "打开原站", 8, _hoisted_11$4)) : createCommentVNode("", true)
])])) : createCommentVNode("", true),
__props.active && loading ? (openBlock(), createElementBlock("div", _hoisted_12$3, [createVNode(LoadingSpinner_default, {
size: 20,
"aria-hidden": "true"
}), createBaseVNode("span", _hoisted_13$3, "正在加载第 " + toDisplayString(frame.index) + " 页图片", 1)])) : createCommentVNode("", true),
createBaseVNode("span", _hoisted_14$3, toDisplayString(frame.index), 1)
], 44, _hoisted_4$5);
}), 128))
], 36),
unref(endSpace) ? (openBlock(), createElementBlock("div", {
key: 1,
style: normalizeStyle({ height: unref(endSpace) + "px" }),
"aria-hidden": "true"
}, null, 4)) : createCommentVNode("", true)
], 2)], 64);
};
}
});
var _hoisted_1$7 = {
key: 0,
class: "notice library-notice",
role: "status"
};
var _hoisted_2$6 = {
key: 0,
class: "empty",
role: "status"
};
var _hoisted_3$6 = {
key: 1,
class: "empty"
};
var ReadingLibraryPage_default = defineComponent({
__name: "ReadingLibraryPage",
props: mergeModels({
section: {},
startingReading: { type: Boolean },
desktop: { type: Boolean },
openActionHref: {}
}, {
"selecting": {
type: Boolean,
required: true
},
"selectingModifiers": {}
}),
emits: mergeModels([
"navigate",
"remove",
"openActions",
"readAll"
], ["update:selecting"]),
setup(__props, { emit: __emit }) {
const props = __props;
const emit = __emit;
const readingLibrary = useReadingLibraryStore();
const { library, historyByGalleryHref, loadingLibrary: loading, savingLibrary: saving, libraryError: error } = storeToRefs(readingLibrary);
const selecting = useModel(__props, "selecting");
const rows = computed(() => {
if (props.section === "history") return library.value.history.map((entry) => ({
...entry.gallery,
recordedAt: entry.visitedAt,
progressIndex: entry.progress?.index
}));
return library.value.later.map((entry) => {
const history = historyByGalleryHref.value.get(entry.gallery.href);
return {
...entry.gallery,
pages: history?.gallery.pages || entry.gallery.pages,
recordedAt: entry.savedAt,
progressIndex: history?.progress?.index
};
});
});
const removalType = computed(() => props.section === "history" ? "remove-from-history" : "remove-from-later");
const removalLabel = computed(() => `从${librarySections[props.section]}移除`);
function removeSelected(items, event) {
emit("remove", {
type: "remove-many",
section: props.section,
hrefs: items.map((item) => item.href)
}, event);
}
return (_ctx, _cache) => {
return openBlock(), createBlock(GalleryList_default, {
selecting: selecting.value,
"onUpdate:selecting": _cache[1] || (_cache[1] = ($event) => selecting.value = $event),
title: unref(librarySections)[__props.section],
items: rows.value,
"list-key": __props.section,
"bulk-action": "delete",
"selection-busy": unref(loading) || unref(saving),
onNavigate: _cache[2] || (_cache[2] = (event, href) => emit("navigate", event, href)),
onApplySelection: removeSelected
}, {
controls: withCtx(() => [__props.section === "later" && rows.value.length && !selecting.value ? (openBlock(), createBlock(ActionButton_default, {
key: 0,
variant: "primary",
disabled: unref(loading) || unref(saving) || __props.startingReading,
onClick: _cache[0] || (_cache[0] = ($event) => emit("readAll"))
}, {
default: withCtx(() => [createTextVNode(toDisplayString(__props.startingReading ? "正在打开…" : "全部阅读"), 1)]),
_: 1
}, 8, ["disabled"])) : createCommentVNode("", true)]),
notice: withCtx(() => [unref(error) ? (openBlock(), createElementBlock("div", _hoisted_1$7, [createBaseVNode("p", null, toDisplayString(unref(error)), 1), createVNode(ActionButton_default, {
disabled: unref(loading),
onClick: unref(readingLibrary).readLibrary
}, {
default: withCtx(() => [..._cache[3] || (_cache[3] = [createTextVNode("重新读取", -1)])]),
_: 1
}, 8, ["disabled", "onClick"])])) : createCommentVNode("", true)]),
empty: withCtx(() => [unref(loading) ? (openBlock(), createElementBlock("p", _hoisted_2$6, "正在读取阅读记录…")) : !unref(error) ? (openBlock(), createElementBlock("p", _hoisted_3$6, toDisplayString(__props.section === "history" ? "浏览过的画廊会出现在这里。" : "可从画廊详情或阅读页添加稍后阅读。"), 1)) : createCommentVNode("", true)]),
quickAction: withCtx(({ item }) => [__props.desktop ? (openBlock(), createBlock(GalleryCardAction_default, {
key: 0,
destructive: "",
label: removalLabel.value,
title: item.title,
busy: unref(loading) || unref(saving),
onClick: ($event) => emit("remove", {
type: removalType.value,
href: item.href
}, $event, item.title)
}, null, 8, [
"label",
"title",
"busy",
"onClick"
])) : (openBlock(), createBlock(GalleryMoreButton_default, {
key: 1,
title: item.title,
expanded: __props.openActionHref === item.href,
busy: unref(loading) || unref(saving),
onClick: ($event) => emit("openActions", $event, item, __props.section)
}, null, 8, [
"title",
"expanded",
"busy",
"onClick"
]))]),
_: 1
}, 8, [
"selecting",
"title",
"items",
"list-key",
"selection-busy"
]);
};
}
});
var _hoisted_1$6 = { class: "tags-field" };
var _hoisted_2$5 = ["aria-label", "aria-controls"];
var _hoisted_3$5 = ["id", "aria-labelledby"];
var _hoisted_4$4 = { class: "tag-color-panel" };
var _hoisted_5$3 = { class: "tag-color-header" };
var _hoisted_6$3 = ["id"];
var _hoisted_7$3 = { class: "tag-color-content" };
var _hoisted_8$3 = { class: "tag-color-presets" };
var _hoisted_9$3 = { class: "tag-color-swatches" };
var _hoisted_10$3 = ["title"];
var _hoisted_11$3 = [
"name",
"value",
"checked",
"aria-label",
"onChange"
];
var _hoisted_12$2 = { class: "tag-color-check" };
var _hoisted_13$2 = { class: "tag-color-native" };
var _hoisted_14$2 = ["value"];
var _hoisted_15$1 = { class: "tag-color-custom" };
var _hoisted_16$1 = { class: "tag-color-hex" };
var _hoisted_17$1 = [
"aria-invalid",
"aria-describedby",
"onKeydown"
];
var _hoisted_18$1 = ["id"];
var _hoisted_19$1 = { class: "tag-color-footer" };
var _hoisted_20$1 = ["disabled"];
var TagColorPicker_default = defineComponent({
__name: "TagColorPicker",
props: mergeModels({ defaultColor: {} }, {
"modelValue": { required: true },
"modelModifiers": {}
}),
emits: ["update:modelValue"],
setup(__props) {
const swatches = [
{
name: "红色",
value: "#cc3d46"
},
{
name: "橙色",
value: "#dc6a3a"
},
{
name: "金黄",
value: "#d9a023"
},
{
name: "橄榄绿",
value: "#79a13b"
},
{
name: "翠绿",
value: "#2b9461"
},
{
name: "青绿",
value: "#229e99"
},
{
name: "天蓝",
value: "#368ebf"
},
{
name: "靛蓝",
value: "#4168cb"
},
{
name: "紫色",
value: "#7956c5"
},
{
name: "玫瑰粉",
value: "#c4558e"
},
{
name: "棕色",
value: "#916749"
},
{
name: "蓝灰",
value: "#697485"
}
];
const props = __props;
const color = useModel(__props, "modelValue");
const dialogId = useId();
const dialog = useTemplateRef("dialog");
const trigger = useTemplateRef("trigger");
const draft = shallowRef("");
function normalize(value) {
const hex = value.trim().toLowerCase().replace(/^#/, "");
if (!value.trim()) return "";
if (/^[0-9a-f]{6}$/.test(hex)) return "#" + hex;
if (/^[0-9a-f]{3}$/.test(hex)) return "#" + [...hex].map((digit) => digit.repeat(2)).join("");
}
const normalized = computed(() => normalize(draft.value));
const invalid = computed(() => normalized.value === void 0 && draft.value !== color.value);
const previewColor = computed(() => normalized.value || (invalid.value ? color.value : draft.value) || props.defaultColor);
const nativeColor = computed(() => normalize(previewColor.value) || "#000000");
function open() {
draft.value = color.value;
dialog.value?.showModal();
}
function close() {
dialog.value?.close();
trigger.value?.focus({ preventScroll: true });
}
function confirm() {
if (invalid.value) return;
if (draft.value !== color.value && normalized.value !== void 0) color.value = normalized.value;
close();
}
function pickNative(event) {
if (event.target instanceof HTMLInputElement) draft.value = event.target.value;
}
return (_ctx, _cache) => {
return openBlock(), createElementBlock(Fragment, null, [createBaseVNode("div", _hoisted_1$6, [_cache[4] || (_cache[4] = createBaseVNode("span", null, "颜色", -1)), createBaseVNode("button", {
ref_key: "trigger",
ref: trigger,
class: "tag-color-trigger",
type: "button",
"aria-label": "选择标签颜色,当前:" + (color.value || "默认颜色"),
"aria-haspopup": "dialog",
"aria-controls": unref(dialogId),
onClick: open
}, [
createBaseVNode("span", {
class: "tag-color",
style: normalizeStyle({ backgroundColor: color.value || __props.defaultColor }),
"aria-hidden": "true"
}, null, 4),
createBaseVNode("span", null, toDisplayString(color.value || "默认颜色"), 1),
createVNode(unref(ChevronDown), {
size: 15,
"aria-hidden": "true"
})
], 8, _hoisted_2$5)]), createBaseVNode("dialog", {
id: unref(dialogId),
ref_key: "dialog",
ref: dialog,
class: "tag-color-dialog",
"aria-labelledby": unref(dialogId) + "-title",
onClick: withModifiers(close, ["self"]),
onCancel: withModifiers(close, ["prevent"]),
onTouchmove: _cache[2] || (_cache[2] = withModifiers(() => {}, ["self", "prevent"])),
onWheel: _cache[3] || (_cache[3] = withModifiers(() => {}, ["self", "prevent"]))
}, [createBaseVNode("div", _hoisted_4$4, [
createBaseVNode("header", _hoisted_5$3, [createBaseVNode("h3", { id: unref(dialogId) + "-title" }, "选择标签颜色", 8, _hoisted_6$3), createBaseVNode("button", {
class: "icon-button",
type: "button",
autofocus: "",
"aria-label": "关闭颜色面板",
onClick: close
}, [createVNode(unref(X), {
size: 20,
"aria-hidden": "true"
})])]),
createBaseVNode("div", _hoisted_7$3, [
createBaseVNode("fieldset", _hoisted_8$3, [_cache[5] || (_cache[5] = createBaseVNode("legend", null, "预设颜色", -1)), createBaseVNode("div", _hoisted_9$3, [(openBlock(), createElementBlock(Fragment, null, renderList(swatches, (swatch) => {
return createBaseVNode("label", {
key: swatch.value,
class: "tag-color-swatch",
title: swatch.name
}, [createBaseVNode("input", {
type: "radio",
name: unref(dialogId) + "-preset",
value: swatch.value,
checked: normalized.value === swatch.value,
"aria-label": swatch.name,
onChange: ($event) => draft.value = swatch.value
}, null, 40, _hoisted_11$3), createBaseVNode("span", {
class: "tag-color-chip",
style: normalizeStyle({ backgroundColor: swatch.value }),
"aria-hidden": "true"
}, [createBaseVNode("span", _hoisted_12$2, [createVNode(unref(Check), { size: 14 })])], 4)], 8, _hoisted_10$3);
}), 64))])]),
createBaseVNode("label", _hoisted_13$2, [
createBaseVNode("span", {
class: "tag-color-preview",
style: normalizeStyle({ backgroundColor: previewColor.value }),
"aria-hidden": "true"
}, null, 4),
_cache[6] || (_cache[6] = createBaseVNode("span", null, "打开系统取色器", -1)),
createVNode(unref(Pipette), {
size: 18,
"aria-hidden": "true"
}),
createBaseVNode("input", {
value: nativeColor.value,
type: "color",
onInput: pickNative,
onChange: pickNative
}, null, 40, _hoisted_14$2)
]),
createBaseVNode("div", _hoisted_15$1, [createBaseVNode("label", _hoisted_16$1, [_cache[7] || (_cache[7] = createBaseVNode("span", null, "色值", -1)), withDirectives(createBaseVNode("input", {
"onUpdate:modelValue": _cache[0] || (_cache[0] = ($event) => draft.value = $event),
type: "text",
placeholder: "#RRGGBB",
spellcheck: "false",
autocapitalize: "off",
"aria-invalid": invalid.value || void 0,
"aria-describedby": invalid.value ? unref(dialogId) + "-error" : void 0,
onKeydown: withKeys(withModifiers(confirm, ["prevent"]), ["enter"])
}, null, 40, _hoisted_17$1), [[vModelText, draft.value]])]), createBaseVNode("button", {
class: "pill",
type: "button",
onClick: _cache[1] || (_cache[1] = ($event) => draft.value = "")
}, "恢复默认")]),
invalid.value ? (openBlock(), createElementBlock("p", {
key: 0,
id: unref(dialogId) + "-error",
class: "tag-color-error",
role: "status"
}, " 输入 3 位或 6 位十六进制色值。 ", 8, _hoisted_18$1)) : createCommentVNode("", true)
]),
createBaseVNode("footer", _hoisted_19$1, [createBaseVNode("button", {
class: "pill",
type: "button",
onClick: close
}, "取消"), createBaseVNode("button", {
class: "pill tags-primary",
type: "button",
disabled: invalid.value,
onClick: confirm
}, "应用颜色", 8, _hoisted_20$1)])
])], 40, _hoisted_3$5)], 64);
};
}
});
var _hoisted_1$5 = ["aria-label"];
var _hoisted_2$4 = { key: 0 };
var _hoisted_3$4 = ["disabled"];
var _hoisted_4$3 = {
key: 0,
class: "tags-field"
};
var _hoisted_5$2 = { class: "tags-field" };
var _hoisted_6$2 = { class: "tags-check" };
var _hoisted_7$2 = { class: "tags-check" };
var _hoisted_8$2 = {
key: 1,
class: "notice",
role: "alert"
};
var _hoisted_9$2 = { class: "flex flex-wrap gap-2" };
var _hoisted_10$2 = ["disabled"];
var _hoisted_11$2 = ["disabled"];
var TagEditor_default = defineComponent({
__name: "TagEditor",
props: {
tag: {},
defaultColor: {},
saving: { type: Boolean },
error: {}
},
emits: ["save", "cancel"],
setup(__props, { emit: __emit }) {
const props = __props;
const emit = __emit;
const form = useTemplateRef("form");
const name = ref("");
const preferences = reactive({
color: props.tag?.color ?? "",
weight: props.tag?.weight ?? 10,
watched: props.tag?.watched ?? false,
hidden: props.tag?.hidden ?? false
});
onMounted(() => {
if (!props.tag) form.value?.focus();
});
function submit() {
if (props.saving || typeof preferences.weight !== "number" || !Number.isInteger(preferences.weight)) return;
if (props.tag) emit("save", {
kind: "edit",
id: props.tag.id,
...preferences
});
else if (name.value.trim()) emit("save", {
kind: "add",
name: name.value.trim(),
...preferences
});
}
return (_ctx, _cache) => {
return openBlock(), createElementBlock("form", {
ref_key: "form",
ref: form,
class: "tags-editor",
"aria-label": __props.tag ? "编辑标签 " + __props.tag.name : "添加标签",
tabindex: "-1",
onSubmit: withModifiers(submit, ["prevent"])
}, [
!__props.tag ? (openBlock(), createElementBlock("h2", _hoisted_2$4, "添加标签")) : createCommentVNode("", true),
createBaseVNode("fieldset", {
class: "tags-fields",
disabled: __props.saving
}, [
!__props.tag ? (openBlock(), createElementBlock("label", _hoisted_4$3, [_cache[6] || (_cache[6] = createTextVNode(" 标签名称 ", -1)), withDirectives(createBaseVNode("input", {
"onUpdate:modelValue": _cache[0] || (_cache[0] = ($event) => name.value = $event),
placeholder: "namespace:tag",
required: ""
}, null, 512), [[vModelText, name.value]])])) : createCommentVNode("", true),
createVNode(TagColorPicker_default, {
modelValue: preferences.color,
"onUpdate:modelValue": _cache[1] || (_cache[1] = ($event) => preferences.color = $event),
"default-color": __props.defaultColor
}, null, 8, ["modelValue", "default-color"]),
createBaseVNode("label", _hoisted_5$2, [_cache[7] || (_cache[7] = createTextVNode(" 权重 ", -1)), withDirectives(createBaseVNode("input", {
"onUpdate:modelValue": _cache[2] || (_cache[2] = ($event) => preferences.weight = $event),
type: "number",
min: "-99",
max: "99",
step: "1",
required: ""
}, null, 512), [[
vModelText,
preferences.weight,
void 0,
{ number: true }
]])]),
createBaseVNode("label", _hoisted_6$2, [withDirectives(createBaseVNode("input", {
"onUpdate:modelValue": _cache[3] || (_cache[3] = ($event) => preferences.watched = $event),
type: "checkbox"
}, null, 512), [[vModelCheckbox, preferences.watched]]), _cache[8] || (_cache[8] = createTextVNode(" 关注", -1))]),
createBaseVNode("label", _hoisted_7$2, [withDirectives(createBaseVNode("input", {
"onUpdate:modelValue": _cache[4] || (_cache[4] = ($event) => preferences.hidden = $event),
type: "checkbox"
}, null, 512), [[vModelCheckbox, preferences.hidden]]), _cache[9] || (_cache[9] = createTextVNode(" 隐藏", -1))])
], 8, _hoisted_3$4),
__props.error ? (openBlock(), createElementBlock("p", _hoisted_8$2, toDisplayString(__props.error), 1)) : createCommentVNode("", true),
createBaseVNode("div", _hoisted_9$2, [createBaseVNode("button", {
class: "pill tags-primary",
type: "submit",
disabled: __props.saving
}, toDisplayString(__props.saving ? "保存中…" : "保存"), 9, _hoisted_10$2), createBaseVNode("button", {
class: "pill",
type: "button",
disabled: __props.saving,
onClick: _cache[5] || (_cache[5] = ($event) => emit("cancel"))
}, "取消", 8, _hoisted_11$2)])
], 40, _hoisted_1$5);
};
}
});
var _hoisted_1$4 = ["aria-busy"];
var _hoisted_2$3 = { class: "tags-heading flex flex-wrap items-center justify-between gap-3" };
var _hoisted_3$3 = { id: "tags-title" };
var _hoisted_4$2 = ["aria-expanded", "disabled"];
var _hoisted_5$1 = {
key: 0,
class: "tags-groups my-5 flex flex-wrap gap-2",
"aria-label": "标签组"
};
var _hoisted_6$1 = [
"aria-current",
"href",
"onClick"
];
var _hoisted_7$1 = { class: "tags-tools flex flex-wrap items-center justify-between gap-3" };
var _hoisted_8$1 = { class: "tags-filter" };
var _hoisted_9$1 = { class: "count" };
var _hoisted_10$1 = { key: 0 };
var _hoisted_11$1 = {
key: 0,
class: "notice",
role: "alert"
};
var _hoisted_12$1 = {
key: 1,
class: "tags-status my-3 text-muted",
role: "status"
};
var _hoisted_13$1 = {
key: 3,
class: "tags-bulk flex flex-wrap items-center gap-2"
};
var _hoisted_14$1 = { class: "count" };
var _hoisted_15 = ["disabled"];
var _hoisted_16 = ["disabled"];
var _hoisted_17 = ["disabled"];
var _hoisted_18 = ["value"];
var _hoisted_19 = ["disabled"];
var _hoisted_20 = ["disabled"];
var _hoisted_21 = ["disabled"];
var _hoisted_22 = {
key: 4,
class: "tags-list",
"aria-label": "当前组的标签"
};
var _hoisted_23 = { class: "tags-row-header" };
var _hoisted_24 = { class: "tags-check" };
var _hoisted_25 = [
"value",
"aria-label",
"disabled"
];
var _hoisted_26 = { class: "tag-info flex flex-wrap items-center gap-x-2.5 gap-y-1" };
var _hoisted_27 = ["title"];
var _hoisted_28 = {
key: 0,
class: "tag-state"
};
var _hoisted_29 = {
key: 1,
class: "tag-state"
};
var _hoisted_30 = { class: "tag-weight" };
var _hoisted_31 = [
"aria-label",
"aria-expanded",
"aria-controls",
"disabled",
"onClick"
];
var _hoisted_32 = ["id"];
var _hoisted_33 = {
key: 0,
class: "tag-edit-status",
role: "status"
};
var _hoisted_34 = {
key: 5,
class: "empty"
};
var TagsPanel_default = defineComponent({
__name: "TagsPanel",
props: {
page: {},
commit: { type: Function }
},
emits: ["navigate"],
setup(__props, { emit: __emit }) {
const props = __props;
const emit = __emit;
const tags = useTagDirectoryStore();
const filter = ref("");
const editor = shallowRef();
const editorId = useId();
const selected = ref([]);
const target = ref("");
const confirmRemove = ref(false);
const saving = ref(false);
const feedback = shallowRef();
const groups = computed(() => props.page.groups.filter((group) => group.id !== props.page.activeGroup));
const rows = computed(() => {
const query = filter.value.trim().toLowerCase();
const visible = props.page.tags.filter((tag) => tag.name.toLowerCase().includes(query) || tags.translate?.(tag.name)?.toLowerCase().includes(query));
const editedId = editor.value?.tagId;
const edited = editedId === void 0 ? void 0 : props.page.tags.find((tag) => tag.id === editedId);
if (edited && !visible.includes(edited)) return {
tags: [...visible, edited],
hiddenId: edited.id,
count: visible.length
};
return {
tags: visible,
hiddenId: void 0,
count: visible.length
};
});
watch(selected, () => {
confirmRemove.value = false;
}, { deep: true });
async function closeEditor() {
const trigger = editor.value?.trigger;
editor.value = void 0;
await nextTick();
trigger?.focus({ preventScroll: true });
}
function toggleEditor(event, tagId) {
const trigger = event.currentTarget;
if (!(trigger instanceof HTMLButtonElement)) return;
if (feedback.value?.type === "error") feedback.value = void 0;
if (editor.value?.trigger === trigger) closeEditor();
else editor.value = {
trigger,
tagId
};
}
function makeInert(element) {
element.setAttribute("inert", "");
}
async function apply(change, message) {
if (saving.value) return false;
saving.value = true;
feedback.value = void 0;
const tagId = change.kind === "edit" ? change.id : void 0;
try {
await props.commit(change);
feedback.value = {
type: "status",
tagId,
text: message
};
return true;
} catch (reason) {
feedback.value = {
type: "error",
tagId,
text: reason instanceof Error ? reason.message : "标签操作失败。"
};
return false;
} finally {
saving.value = false;
}
}
async function save(change) {
if (await apply(change, change.kind === "edit" ? "已保存标签。" : "已添加标签。")) await closeEditor();
}
async function move() {
const ids = [...selected.value];
if (target.value && await apply({
kind: "move",
ids,
target: target.value
}, "已移动所选标签。")) selected.value = [];
}
async function remove() {
if (await apply({
kind: "remove",
ids: [...selected.value]
}, "已删除所选标签。")) selected.value = [];
}
return (_ctx, _cache) => {
return openBlock(), createElementBlock("section", {
"aria-labelledby": "tags-title",
"aria-busy": saving.value
}, [
createBaseVNode("div", _hoisted_2$3, [createBaseVNode("h1", _hoisted_3$3, toDisplayString(__props.page.title), 1), __props.page.canAdd ? (openBlock(), createElementBlock("button", {
key: 0,
class: "pill tags-primary",
type: "button",
"aria-expanded": Boolean(editor.value && editor.value.tagId === void 0),
disabled: saving.value,
onClick: toggleEditor
}, [createVNode(unref(Plus), {
size: 17,
"aria-hidden": "true"
}), _cache[6] || (_cache[6] = createTextVNode(" 添加标签 ", -1))], 8, _hoisted_4$2)) : createCommentVNode("", true)]),
__props.page.groups.length ? (openBlock(), createElementBlock("nav", _hoisted_5$1, [(openBlock(true), createElementBlock(Fragment, null, renderList(__props.page.groups, (group) => {
return openBlock(), createElementBlock("a", {
key: group.id,
class: "pill",
"aria-current": group.id === __props.page.activeGroup ? "true" : void 0,
href: group.href,
onClick: ($event) => emit("navigate", $event, group.href)
}, toDisplayString(group.label), 9, _hoisted_6$1);
}), 128))])) : createCommentVNode("", true),
createBaseVNode("div", _hoisted_7$1, [createBaseVNode("label", _hoisted_8$1, [createVNode(unref(Search), {
size: 17,
"aria-hidden": "true"
}), withDirectives(createBaseVNode("input", {
"onUpdate:modelValue": _cache[0] || (_cache[0] = ($event) => filter.value = $event),
type: "search",
"aria-label": "筛选标签",
placeholder: "筛选标签"
}, null, 512), [[vModelText, filter.value]])]), createBaseVNode("span", _hoisted_9$1, [createTextVNode(toDisplayString(rows.value.count) + " / " + toDisplayString(__props.page.tags.length) + " 个标签", 1), !__props.page.groupEnabled ? (openBlock(), createElementBlock("span", _hoisted_10$1, " · 组已停用")) : createCommentVNode("", true)])]),
feedback.value && feedback.value.tagId === void 0 ? (openBlock(), createElementBlock(Fragment, { key: 1 }, [feedback.value.type === "error" ? (openBlock(), createElementBlock("p", _hoisted_11$1, toDisplayString(feedback.value.text), 1)) : (openBlock(), createElementBlock("p", _hoisted_12$1, toDisplayString(feedback.value.text), 1))], 64)) : createCommentVNode("", true),
editor.value && editor.value.tagId === void 0 ? (openBlock(), createBlock(TagEditor_default, {
key: 2,
"default-color": __props.page.defaultColor,
saving: saving.value,
onSave: save,
onCancel: closeEditor
}, null, 8, ["default-color", "saving"])) : createCommentVNode("", true),
selected.value.length ? (openBlock(), createElementBlock("div", _hoisted_13$1, [createBaseVNode("span", _hoisted_14$1, "已选 " + toDisplayString(selected.value.length) + " 个", 1), confirmRemove.value ? (openBlock(), createElementBlock(Fragment, { key: 0 }, [createBaseVNode("button", {
class: "pill action-button-danger",
type: "button",
disabled: saving.value,
onClick: remove
}, " 确认删除所选标签 ", 8, _hoisted_15), createBaseVNode("button", {
class: "pill",
type: "button",
disabled: saving.value,
onClick: _cache[1] || (_cache[1] = ($event) => confirmRemove.value = false)
}, "取消", 8, _hoisted_16)], 64)) : (openBlock(), createElementBlock(Fragment, { key: 1 }, [
groups.value.length ? withDirectives((openBlock(), createElementBlock("select", {
key: 0,
"onUpdate:modelValue": _cache[2] || (_cache[2] = ($event) => target.value = $event),
class: "tags-select",
"aria-label": "移动目标标签组",
disabled: saving.value
}, [_cache[7] || (_cache[7] = createBaseVNode("option", { value: "" }, "选择目标组", -1)), (openBlock(true), createElementBlock(Fragment, null, renderList(groups.value, (group) => {
return openBlock(), createElementBlock("option", {
key: group.id,
value: group.id
}, toDisplayString(group.label), 9, _hoisted_18);
}), 128))], 8, _hoisted_17)), [[vModelSelect, target.value]]) : createCommentVNode("", true),
groups.value.length ? (openBlock(), createElementBlock("button", {
key: 1,
class: "pill",
type: "button",
disabled: saving.value || !target.value,
onClick: move
}, " 移动 ", 8, _hoisted_19)) : createCommentVNode("", true),
createBaseVNode("button", {
class: "pill action-button-danger-subtle",
type: "button",
disabled: saving.value,
onClick: _cache[3] || (_cache[3] = ($event) => confirmRemove.value = true)
}, " 删除 ", 8, _hoisted_20),
createBaseVNode("button", {
class: "pill",
type: "button",
disabled: saving.value,
onClick: _cache[4] || (_cache[4] = ($event) => selected.value = [])
}, "清除选择", 8, _hoisted_21)
], 64))])) : createCommentVNode("", true),
rows.value.tags.length ? withDirectives((openBlock(), createElementBlock("ul", _hoisted_22, [(openBlock(true), createElementBlock(Fragment, null, renderList(rows.value.tags, (tag) => {
return withDirectives((openBlock(), createElementBlock("li", {
key: tag.id,
class: "tags-row [border-bottom:1px_solid_var(--line)]"
}, [
createBaseVNode("div", _hoisted_23, [
createBaseVNode("label", _hoisted_24, [withDirectives(createBaseVNode("input", {
"onUpdate:modelValue": _cache[5] || (_cache[5] = ($event) => selected.value = $event),
type: "checkbox",
value: tag.id,
"aria-label": "选择 " + tag.name,
disabled: saving.value
}, null, 8, _hoisted_25), [[vModelCheckbox, selected.value]])]),
createBaseVNode("div", _hoisted_26, [
createBaseVNode("span", {
class: "tag-color",
style: normalizeStyle({ backgroundColor: tag.color || __props.page.defaultColor }),
"aria-hidden": "true"
}, null, 4),
createBaseVNode("strong", {
class: "tag-name wrap-anywhere",
title: tag.name
}, toDisplayString(unref(tags).translate?.(tag.name) || tag.name), 9, _hoisted_27),
tag.watched ? (openBlock(), createElementBlock("span", _hoisted_28, "关注")) : createCommentVNode("", true),
tag.hidden ? (openBlock(), createElementBlock("span", _hoisted_29, "隐藏")) : createCommentVNode("", true),
createBaseVNode("span", _hoisted_30, "权重 " + toDisplayString(tag.weight), 1)
]),
__props.page.canEdit ? (openBlock(), createElementBlock("button", {
key: 0,
class: "pill",
type: "button",
"aria-label": (editor.value?.tagId === tag.id ? "收起 " : "编辑 ") + tag.name,
"aria-expanded": editor.value?.tagId === tag.id,
"aria-controls": editor.value?.tagId === tag.id ? unref(editorId) + "-" + tag.id : void 0,
disabled: saving.value,
onClick: ($event) => toggleEditor($event, tag.id)
}, toDisplayString(editor.value?.tagId === tag.id ? "收起" : "编辑"), 9, _hoisted_31)) : createCommentVNode("", true)
]),
createVNode(Transition, {
name: "tag-expand",
onBeforeLeave: makeInert
}, {
default: withCtx(() => [editor.value?.tagId === tag.id ? (openBlock(), createElementBlock("div", {
key: 0,
id: unref(editorId) + "-" + tag.id,
class: "tags-row-editor"
}, [createBaseVNode("div", null, [createVNode(TagEditor_default, {
tag,
"default-color": __props.page.defaultColor,
saving: saving.value,
error: feedback.value?.type === "error" && feedback.value.tagId === tag.id ? feedback.value.text : void 0,
onSave: save,
onCancel: closeEditor
}, null, 8, [
"tag",
"default-color",
"saving",
"error"
])])], 8, _hoisted_32)) : createCommentVNode("", true)]),
_: 2
}, 1024),
feedback.value?.type === "status" && feedback.value.tagId === tag.id ? (openBlock(), createElementBlock("p", _hoisted_33, toDisplayString(feedback.value.text), 1)) : createCommentVNode("", true)
])), [[vShow, tag.id !== rows.value.hiddenId]]);
}), 128))], 512)), [[vShow, rows.value.count > 0]]) : createCommentVNode("", true),
!rows.value.count ? (openBlock(), createElementBlock("p", _hoisted_34, toDisplayString(filter.value.trim() ? "没有匹配的标签。" : "此组还没有标签。"), 1)) : createCommentVNode("", true)
], 8, _hoisted_1$4);
};
}
});
var _hoisted_1$3 = {
key: 0,
class: "notice flex flex-wrap items-center gap-3",
role: "alert"
};
var _hoisted_2$2 = { class: "grow" };
var _hoisted_3$2 = ["href"];
var _hoisted_4$1 = {
key: 1,
class: "notice",
role: "status"
};
var AppPageContent_default = defineComponent({
__name: "AppPageContent",
props: {
navigation: {},
routing: {},
library: {},
readerUi: {},
gallerySearch: {},
viewport: {},
preserveEdgePosition: { type: Function },
nativeLink: { type: Function },
active: { type: Boolean },
desktop: { type: Boolean },
busy: { type: Boolean }
},
emits: ["navigate"],
setup(__props, { emit: __emit }) {
const props = __props;
const emit = __emit;
const { page, navigate, currentUrl, pending, failure, restoringReader, activeReader: reader, loadPreviousFailure, readerRevision, retryNavigation, retryLoadMore, commitTagChange } = props.navigation;
const { galleryReadHref, openCommentLink, startGalleryReading } = props.routing;
const { selectingGalleries, readingGallery, galleryProgress, savedForLater, catalogLists, savedCatalogHrefs, cardActionSheet, openCardActionSheet, toggleReadLater, saveSelectedForLater, requestRemoval, readAll } = props.library;
const { readerSeekFailure, readerFrames, scrollY, returningToTop, readerPagesAhead, readerPagesBehind, readerProgressDragging, readerBuffer, brokenImages, imageRetryErrors, retryingImages, markBroken, rememberImage, retryImage, loadOriginalImage } = props.readerUi;
const { tagSearch, openTagSearch } = props.gallerySearch;
const { libraryError, bookmarksBusy } = storeToRefs(useReadingLibraryStore());
return (_ctx, _cache) => {
return openBlock(), createElementBlock(Fragment, null, [
unref(failure) && !unref(readerSeekFailure) ? (openBlock(), createElementBlock("div", _hoisted_1$3, [
createBaseVNode("span", _hoisted_2$2, toDisplayString(unref(failure).message), 1),
createBaseVNode("button", {
type: "button",
class: "pill",
onClick: _cache[0] || (_cache[0] = (...args) => unref(retryNavigation) && unref(retryNavigation)(...args))
}, "重试"),
__props.nativeLink ? (openBlock(), createElementBlock("a", {
key: 0,
class: "pill",
href: __props.nativeLink(unref(failure).url)
}, "打开原站", 8, _hoisted_3$2)) : createCommentVNode("", true)
])) : createCommentVNode("", true),
(unref(page).kind === "catalog" || unref(readingGallery)) && unref(libraryError) ? (openBlock(), createElementBlock("p", _hoisted_4$1, toDisplayString(unref(libraryError)), 1)) : createCommentVNode("", true),
unref(page).kind === "catalog" ? (openBlock(), createBlock(CatalogPage_default, {
key: 2,
selecting: unref(selectingGalleries),
"onUpdate:selecting": _cache[1] || (_cache[1] = ($event) => isRef(selectingGalleries) ? selectingGalleries.value = $event : null),
page: unref(page),
items: unref(catalogLists).items,
featured: unref(catalogLists).featured,
"list-key": unref(currentUrl),
"saved-hrefs": unref(savedCatalogHrefs),
busy: unref(bookmarksBusy),
desktop: __props.desktop,
"pending-url": unref(pending),
"open-action-href": unref(cardActionSheet)?.gallery.href,
onNavigate: _cache[2] || (_cache[2] = (event, href) => emit("navigate", event, href)),
onChangeFilters: _cache[3] || (_cache[3] = (href, source) => unref(navigate)(href ?? unref(currentUrl), "push", void 0, void 0, source)),
onSaveSelected: unref(saveSelectedForLater),
onToggleReadLater: _cache[4] || (_cache[4] = (event, gallery) => unref(toggleReadLater)(event.currentTarget, gallery)),
onOpenActions: unref(openCardActionSheet)
}, null, 8, [
"selecting",
"page",
"items",
"featured",
"list-key",
"saved-hrefs",
"busy",
"desktop",
"pending-url",
"open-action-href",
"onSaveSelected",
"onOpenActions"
])) : unref(page).kind === "gallery" ? (openBlock(), createBlock(GalleryDetail_default, {
key: 3,
page: unref(page),
"gallery-progress": unref(galleryProgress),
"gallery-read-href": unref(galleryReadHref),
"saved-for-later": unref(savedForLater),
"bookmarks-busy": unref(bookmarksBusy),
"active-tag": unref(tagSearch)?.tag,
active: __props.active,
"update-favorite": __props.navigation.updateGalleryFavorite,
"load-comments": __props.navigation.loadGalleryComments,
"refresh-comments": __props.navigation.refreshGalleryComments,
"load-comment-total": __props.navigation.loadGalleryCommentTotal,
onNavigate: _cache[5] || (_cache[5] = (event, href) => emit("navigate", event, href)),
onOpenCommentLink: unref(openCommentLink),
onStartReading: unref(startGalleryReading),
onToggleBookmark: _cache[6] || (_cache[6] = ($event) => unref(toggleReadLater)($event.currentTarget, unref(readingGallery))),
onTag: unref(openTagSearch)
}, null, 8, [
"page",
"gallery-progress",
"gallery-read-href",
"saved-for-later",
"bookmarks-busy",
"active-tag",
"active",
"update-favorite",
"load-comments",
"refresh-comments",
"load-comment-total",
"onOpenCommentLink",
"onStartReading",
"onTag"
])) : unref(page).kind === "tags" ? (openBlock(), createBlock(TagsPanel_default, {
key: unref(currentUrl),
page: unref(page),
commit: unref(commitTagChange),
onNavigate: _cache[7] || (_cache[7] = (event, href) => emit("navigate", event, href))
}, null, 8, ["page", "commit"])) : unref(page).kind === "library" ? (openBlock(), createBlock(ReadingLibraryPage_default, {
key: unref(page).section,
selecting: unref(selectingGalleries),
"onUpdate:selecting": _cache[8] || (_cache[8] = ($event) => isRef(selectingGalleries) ? selectingGalleries.value = $event : null),
section: unref(page).section,
"starting-reading": Boolean(unref(pending)),
desktop: __props.desktop,
"open-action-href": unref(cardActionSheet)?.gallery.href,
onNavigate: _cache[9] || (_cache[9] = (event, href) => emit("navigate", event, href)),
onOpenActions: unref(openCardActionSheet),
onRemove: _cache[10] || (_cache[10] = (change, event, title) => unref(requestRemoval)(change, event.currentTarget, title)),
onReadAll: unref(readAll)
}, null, 8, [
"selecting",
"section",
"starting-reading",
"desktop",
"open-action-href",
"onOpenActions",
"onReadAll"
])) : (openBlock(), createBlock(ReaderPages_default, {
key: unref(readerRevision),
ref: __props.navigation.readerPages,
title: unref(reader)?.title,
frames: unref(readerFrames),
viewport: __props.viewport,
"preserve-edge-position": __props.preserveEdgePosition,
active: __props.active,
"load-thumbnails": __props.navigation.loadReaderThumbnails,
"scroll-top": unref(scrollY),
"track-position": !unref(pending) && !unref(restoringReader),
"returning-to-top": unref(returningToTop),
"pages-ahead": unref(readerPagesAhead),
"pages-behind": unref(readerPagesBehind),
"preload-paused": unref(readerProgressDragging),
buffer: unref(readerBuffer),
busy: __props.busy,
"broken-images": unref(brokenImages),
"image-retry-errors": unref(imageRetryErrors),
"retrying-images": unref(retryingImages),
"load-previous-failure": unref(loadPreviousFailure),
"native-link": __props.nativeLink,
onRetryPrevious: _cache[11] || (_cache[11] = ($event) => unref(retryLoadMore)("previous")),
onImageError: unref(markBroken),
onImageLoad: unref(rememberImage),
onRetryImage: unref(retryImage),
onLoadOriginalImage: unref(loadOriginalImage),
onShowPage: __props.navigation.showReaderFrame
}, null, 8, [
"title",
"frames",
"viewport",
"preserve-edge-position",
"active",
"load-thumbnails",
"scroll-top",
"track-position",
"returning-to-top",
"pages-ahead",
"pages-behind",
"preload-paused",
"buffer",
"busy",
"broken-images",
"image-retry-errors",
"retrying-images",
"load-previous-failure",
"native-link",
"onImageError",
"onImageLoad",
"onRetryImage",
"onLoadOriginalImage",
"onShowPage"
]))
], 64);
};
}
});
var _hoisted_1$2 = {
id: "better-eh-reader-progress",
class: "reader-progress"
};
var _hoisted_2$1 = {
key: 0,
class: "reader-progress-error",
role: "alert"
};
var _hoisted_3$1 = ["onKeydown"];
var _hoisted_4 = { class: "reader-chapters-header" };
var _hoisted_5 = [
"aria-current",
"disabled",
"onClick"
];
var _hoisted_6 = { class: "reader-chapter-number" };
var _hoisted_7 = { class: "reader-progress-bar" };
var _hoisted_8 = {
key: 0,
class: "reader-progress-preview pointer-events-none absolute bottom-[calc(100%+16px)] z-1 w-[108px] overflow-hidden rounded-ui border border-solid border-line bg-surface shadow-lg",
"aria-hidden": "true"
};
var _hoisted_9 = { class: "grid h-[min(132px,28dvh)] place-items-center bg-panel text-muted" };
var _hoisted_10 = {
key: 1,
class: "text-xs"
};
var _hoisted_11 = { class: "px-2 py-1 text-center text-xs font-semibold tabular-nums" };
var _hoisted_12 = [
"max",
"value",
"disabled",
"aria-valuetext"
];
var _hoisted_13 = { class: "reader-count min-w-[58px] text-center font-[650] whitespace-nowrap tabular-nums" };
var _hoisted_14 = ["aria-label", "aria-expanded"];
var ReaderProgress_default = defineComponent({
__name: "ReaderProgress",
props: mergeModels({
chapters: {},
activeChapter: {},
currentPage: {},
totalPages: {},
visible: { type: Boolean },
galleryHref: {},
pending: { type: Boolean },
seekingReader: { type: Boolean },
error: {},
openChapter: { type: Function },
loadThumbnails: { type: Function }
}, {
"chaptersOpen": {
type: Boolean,
required: true
},
"chaptersOpenModifiers": {},
"dragging": {
type: Boolean,
required: true
},
"draggingModifiers": {}
}),
emits: mergeModels([
"retry",
"preview",
"cancelPreview"
], ["update:chaptersOpen", "update:dragging"]),
setup(__props, { emit: __emit }) {
const props = __props;
const emit = __emit;
const chaptersOpen = useModel(__props, "chaptersOpen");
const dragging = useModel(__props, "dragging");
const chapterToggle = useTemplateRef("chapterToggle");
const chapterList = useTemplateRef("chapterList");
const pointer = shallowRef();
const disabled = computed(() => props.totalPages < 2 || props.pending && !props.seekingReader);
const previewPage = computed(() => props.visible && !disabled.value && pointer.value !== void 0 ? props.currentPage : void 0);
const progress = computed(() => props.totalPages > 1 ? (props.currentPage - 1) / (props.totalPages - 1) : 0);
const thumbnails = shallowReactive(new Map());
const thumbnail = computed(() => previewPage.value === void 0 ? void 0 : thumbnails.get(previewPage.value));
const failedPage = shallowRef();
const { start: scheduleThumbnail, stop: stopThumbnail } = useTimeoutFn(loadThumbnail, 100, { immediate: false });
let request;
async function loadThumbnail() {
const index = previewPage.value;
if (index === void 0 || thumbnails.has(index) || failedPage.value === index || request) return;
const controller = new AbortController();
request = controller;
try {
const items = await props.loadThumbnails(props.activeChapter, index, controller.signal);
if (controller.signal.aborted) return;
for (const item of items) if (item.image) thumbnails.set(item.index, item);
if (!thumbnails.has(index)) thumbnails.set(index, void 0);
} catch {
if (!controller.signal.aborted) failedPage.value = index;
} finally {
if (request === controller) {
request = void 0;
if (previewPage.value !== void 0 && previewPage.value !== index) scheduleThumbnail();
}
}
}
function startDrag(event) {
if (disabled.value || !event.isPrimary || event.button !== 0) return;
chaptersOpen.value = false;
failedPage.value = void 0;
pointer.value = event.pointerId;
dragging.value = true;
}
function stopDrag() {
pointer.value = void 0;
dragging.value = false;
stopThumbnail();
}
useEventListener$1(window, ["pointerup", "pointercancel"], (event) => {
if (event.pointerId === pointer.value) stopDrag();
});
useEventListener$1(window, "blur", stopDrag);
watch(previewPage, (index) => {
if (index !== void 0) scheduleThumbnail();
else stopThumbnail();
});
watch([() => props.visible, disabled], ([visible, blocked]) => {
if (!visible || blocked) stopDrag();
});
watch(() => props.galleryHref, () => {
stopDrag();
request?.abort();
request = void 0;
thumbnails.clear();
});
onScopeDispose(() => {
stopDrag();
request?.abort();
});
async function toggleChapterList() {
chaptersOpen.value = !chaptersOpen.value;
await nextTick();
if (chaptersOpen.value) {
const list = chapterList.value;
const active = list?.querySelector("[aria-current='true']");
if (active) list?.scrollTo({
top: active.offsetTop,
behavior: "instant"
});
} else chapterToggle.value?.focus({ preventScroll: true });
}
async function selectReaderChapter(chapter) {
if (await props.openChapter(chapter) && chaptersOpen.value) await toggleChapterList();
}
return (_ctx, _cache) => {
return openBlock(), createElementBlock("div", _hoisted_1$2, [
__props.error ? (openBlock(), createElementBlock("div", _hoisted_2$1, [createBaseVNode("span", null, toDisplayString(__props.error), 1), createBaseVNode("button", {
type: "button",
class: "pill",
onClick: _cache[0] || (_cache[0] = ($event) => emit("retry"))
}, "重试")])) : createCommentVNode("", true),
__props.chapters ? withDirectives((openBlock(), createElementBlock("section", {
key: 1,
id: "better-eh-reader-chapters",
class: "reader-chapters",
"aria-labelledby": "better-eh-reader-chapters-title",
onKeydown: withKeys(withModifiers(toggleChapterList, ["stop"]), ["esc"])
}, [createBaseVNode("header", _hoisted_4, [_cache[3] || (_cache[3] = createBaseVNode("h2", { id: "better-eh-reader-chapters-title" }, "章节", -1)), createBaseVNode("button", {
class: "icon-button",
type: "button",
"aria-label": "收起章节列表",
"aria-controls": "better-eh-reader-chapters",
onClick: toggleChapterList
}, [createVNode(unref(ChevronDown), {
size: 20,
"aria-hidden": "true"
})])]), createBaseVNode("ol", {
ref_key: "chapterList",
ref: chapterList,
class: "reader-chapter-list"
}, [(openBlock(true), createElementBlock(Fragment, null, renderList(__props.chapters, (chapter, index) => {
return openBlock(), createElementBlock("li", { key: chapter.href }, [createBaseVNode("button", {
type: "button",
"aria-current": index === __props.activeChapter ? "true" : void 0,
disabled: __props.pending,
onClick: ($event) => selectReaderChapter(index)
}, [createBaseVNode("span", _hoisted_6, toDisplayString(index + 1), 1), createBaseVNode("span", null, toDisplayString(chapter.title), 1)], 8, _hoisted_5)]);
}), 128))], 512)], 40, _hoisted_3$1)), [[vShow, chaptersOpen.value]]) : createCommentVNode("", true),
createBaseVNode("div", _hoisted_7, [
createBaseVNode("div", {
class: "relative flex min-w-0 flex-1",
style: normalizeStyle({ "--reader-progress-ratio": progress.value })
}, [previewPage.value !== void 0 ? (openBlock(), createElementBlock("div", _hoisted_8, [createBaseVNode("div", _hoisted_9, [thumbnail.value ? (openBlock(), createBlock(ThumbnailTile_default, {
key: 0,
thumb: thumbnail.value,
fill: ""
}, null, 8, ["thumb"])) : failedPage.value === previewPage.value || unref(thumbnails).has(previewPage.value) ? (openBlock(), createElementBlock("span", _hoisted_10, "暂无缩略图")) : (openBlock(), createBlock(LoadingSpinner_default, {
key: 2,
size: 20
}))]), createBaseVNode("div", _hoisted_11, toDisplayString(previewPage.value) + " / " + toDisplayString(__props.totalPages) + " 页 ", 1)])) : createCommentVNode("", true), createBaseVNode("input", {
type: "range",
min: "1",
max: Math.max(1, __props.totalPages),
value: __props.currentPage,
disabled: disabled.value,
"aria-label": "阅读进度",
"aria-valuetext": `第 ${__props.currentPage} 页${__props.totalPages ? `,共 ${__props.totalPages} 页` : ""}`,
onInput: _cache[1] || (_cache[1] = ($event) => emit("preview", $event)),
onPointerdown: startDrag,
onPointercancel: _cache[2] || (_cache[2] = ($event) => emit("cancelPreview"))
}, null, 40, _hoisted_12)], 4),
createBaseVNode("output", _hoisted_13, toDisplayString(__props.currentPage) + " / " + toDisplayString(__props.totalPages || "—") + " 页", 1),
__props.chapters ? (openBlock(), createElementBlock("button", {
key: 0,
ref_key: "chapterToggle",
ref: chapterToggle,
type: "button",
class: "icon-button",
"aria-label": chaptersOpen.value ? "收起章节列表" : "展开章节列表",
"aria-expanded": chaptersOpen.value,
"aria-controls": "better-eh-reader-chapters",
onClick: toggleChapterList
}, [chaptersOpen.value ? (openBlock(), createBlock(unref(ChevronDown), {
key: 0,
size: 20,
"aria-hidden": "true"
})) : (openBlock(), createBlock(unref(ChevronUp), {
key: 1,
size: 20,
"aria-hidden": "true"
}))], 8, _hoisted_14)) : createCommentVNode("", true)
])
]);
};
}
});
var _hoisted_1$1 = ["aria-label", "aria-expanded"];
var AppReaderControls_default = defineComponent({
__name: "AppReaderControls",
props: {
navigation: {},
readerUi: {},
readerTotal: {},
desktop: { type: Boolean },
active: { type: Boolean }
},
setup(__props) {
const props = __props;
const { activeReader: reader, readingQueue, readerChapter, currentUrl, pending, seekingReader, retryNavigation } = props.navigation;
const { readerChrome, chromeVisible, chaptersOpen, readerProgressDragging, readerDisplayIndex, readerSeekFailure, toggleReaderChrome, selectReaderChapter, previewReaderPage, clearReaderPreview } = props.readerUi;
return (_ctx, _cache) => {
return openBlock(), createElementBlock(Fragment, null, [unref(reader) && __props.desktop ? (openBlock(), createElementBlock("button", {
key: 0,
class: "icon-button reader-menu-toggle",
type: "button",
"aria-label": unref(readerChrome) ? "隐藏阅读菜单" : "显示阅读菜单",
"aria-expanded": unref(readerChrome),
"aria-controls": "better-eh-masthead better-eh-reader-progress",
onClick: _cache[0] || (_cache[0] = (...args) => unref(toggleReaderChrome) && unref(toggleReaderChrome)(...args))
}, [unref(readerChrome) ? (openBlock(), createBlock(unref(X), {
key: 0,
size: 21,
"aria-hidden": "true"
})) : (openBlock(), createBlock(unref(Menu), {
key: 1,
size: 21,
"aria-hidden": "true"
}))], 8, _hoisted_1$1)) : createCommentVNode("", true), unref(reader) ? withDirectives((openBlock(), createBlock(ReaderProgress_default, {
key: 1,
"chapters-open": unref(chaptersOpen),
"onUpdate:chaptersOpen": _cache[1] || (_cache[1] = ($event) => isRef(chaptersOpen) ? chaptersOpen.value = $event : null),
dragging: unref(readerProgressDragging),
"onUpdate:dragging": _cache[2] || (_cache[2] = ($event) => isRef(readerProgressDragging) ? readerProgressDragging.value = $event : null),
chapters: unref(readingQueue),
"active-chapter": unref(readerChapter),
"current-page": unref(readerDisplayIndex),
"total-pages": __props.readerTotal,
visible: unref(chromeVisible) && __props.active,
"gallery-href": __props.navigation.readerGalleryUrl(unref(reader)) ?? unref(currentUrl),
pending: Boolean(unref(pending)),
"seeking-reader": unref(seekingReader),
error: unref(readerSeekFailure)?.message,
"open-chapter": unref(selectReaderChapter),
"load-thumbnails": __props.navigation.loadReaderThumbnails,
onRetry: unref(retryNavigation),
onPreview: unref(previewReaderPage),
onCancelPreview: unref(clearReaderPreview)
}, null, 8, [
"chapters-open",
"dragging",
"chapters",
"active-chapter",
"current-page",
"total-pages",
"visible",
"gallery-href",
"pending",
"seeking-reader",
"error",
"open-chapter",
"load-thumbnails",
"onRetry",
"onPreview",
"onCancelPreview"
])), [[vShow, unref(chromeVisible)]]) : createCommentVNode("", true)], 64);
};
}
});
var _hoisted_1 = {
class: "pagination",
"aria-label": "分页"
};
var _hoisted_2 = ["href"];
var _hoisted_3 = ["href"];
var PageLinks_default = defineComponent({
__name: "PageLinks",
props: {
previous: {},
next: {}
},
emits: ["navigate"],
setup(__props, { emit: __emit }) {
const emit = __emit;
return (_ctx, _cache) => {
return openBlock(), createElementBlock("nav", _hoisted_1, [__props.previous ? (openBlock(), createElementBlock("a", {
key: 0,
class: "pill",
href: __props.previous,
onClick: _cache[0] || (_cache[0] = ($event) => emit("navigate", $event, __props.previous))
}, [createVNode(unref(ArrowLeft), {
size: 16,
"aria-hidden": "true"
}), _cache[2] || (_cache[2] = createTextVNode(" 上一页 ", -1))], 8, _hoisted_2)) : createCommentVNode("", true), __props.next ? (openBlock(), createElementBlock("a", {
key: 1,
class: "pill next",
href: __props.next,
onClick: _cache[1] || (_cache[1] = ($event) => emit("navigate", $event, __props.next))
}, [_cache[3] || (_cache[3] = createTextVNode(" 下一页 ", -1)), createVNode(unref(ArrowRight), {
size: 16,
"aria-hidden": "true"
})], 8, _hoisted_3)) : createCommentVNode("", true)]);
};
}
});
function useAppRouting(navigation, readerUi, library, adapter, getNativeLink, readLibrary, activate) {
const { page, currentUrl, readNavigationState, readingQueue, navigate, activeReader: reader } = navigation;
const { readerFrames, activeFramePosition } = readerUi;
const { galleryProgress, readingGallery } = library;
const links = createLinks();
function createLinks() {
const activeUrl = computed(() => new URL(currentUrl.value));
const home = computed(() => adapter.home(activeUrl.value));
return {
activeUrl,
home,
nativeHref: computed(() => page.value.kind === "library" ? void 0 : getNativeLink()?.(readerFrames.value[activeFramePosition.value]?.href ?? currentUrl.value)),
navigationItems: computed(() => {
const nativeLink = getNativeLink();
return [
...(adapter.navigation?.(activeUrl.value) ?? []).map((item) => item.native && nativeLink && new URL(item.href).origin === activeUrl.value.origin ? {
...item,
href: nativeLink(item.href)
} : item),
{
id: "history",
label: librarySections.history,
href: libraryUrl(home.value, "history")
},
{
id: "later",
label: librarySections.later,
href: libraryUrl(home.value, "later")
}
];
}),
galleryReadHref: computed(() => {
const current = page.value;
if (current.kind !== "gallery") return;
const thumbnails = current.thumbnails;
return adapter.readerPageUrl?.(new URL(current.href), 1) ?? (galleryProgress.value ? thumbnails.find((thumb) => thumb.index === 1)?.href : thumbnails[0]?.href);
}),
back: computed(() => {
const current = page.value;
if (current.kind !== "reader" && current.kind !== "gallery") return;
const state = readNavigationState();
const previous = state?.previousUrl;
if (current.kind === "gallery") return {
href: previous ?? home.value,
label: "返回",
useHistory: Boolean(state?.betterEh)
};
if (readingQueue.value) return {
href: libraryUrl(home.value, "later"),
label: "返回稍后阅读",
useHistory: state?.previousKind === "library"
};
const gallery = reader.value?.gallery;
if (previous && state?.previousKind === "gallery") {
const previousGallery = new URL(previous);
const galleryUrl = gallery && new URL(gallery);
if (!galleryUrl || previousGallery.origin === galleryUrl.origin && previousGallery.pathname.replace(/\/$/, "") === galleryUrl.pathname.replace(/\/$/, "")) return {
href: previous,
label: "返回画廊",
useHistory: true
};
}
return {
href: gallery ?? home.value,
label: gallery ? "返回画廊" : "返回首页",
useHistory: false
};
})
};
}
function refreshPage() {
if (page.value.kind === "library") return readLibrary();
return navigate(currentUrl.value, "refresh");
}
function refreshFromTop() {
const first = readerFrames.value[0];
if (!reader.value || !first) return refreshPage();
const chapters = readingQueue.value;
return navigate(first.href, "refresh", void 0, chapters && {
chapters,
chapter: first.chapter
});
}
function openCommentLink(event, href) {
const url = new URL(href);
const { kind } = adapter.pageCacheGroup(url);
if (!url.hash && (kind === "gallery" || kind === "reader")) activate(event, href);
}
function startGalleryReading(event) {
if (links.galleryReadHref.value) activate(event, links.galleryReadHref.value);
else navigate(readingGallery.value?.href, "gallery-start");
}
function goBack(event) {
const destination = links.back.value;
if (!destination || !isPrimaryClick(event)) return;
event.preventDefault();
if (location.href !== currentUrl.value) return;
if (destination.useHistory) history.back();
else navigate(destination.href, "replace");
}
return {
...links,
refreshPage,
refreshFromTop,
openCommentLink,
startGalleryReading,
goBack
};
}
function useAppScroll({ pending, savingTags, hasPrevious, loadingPrevious, page, activeReader: reader }, { readerFrames, tapReader, toggleReaderChrome }, desktopNavigation, busy) {
const refreshBlocked = computed(() => Boolean(pending.value || savingTags.value));
return {
refreshBlocked,
pullRefreshBlocked: computed(() => refreshBlocked.value || hasPrevious.value || loadingPrevious.value),
virtual: computed(() => page.value.kind !== "tags"),
scrollItemKeys: computed(() => {
const current = page.value;
if (current.kind === "catalog") return current.items.map((item) => item.href);
if (current.kind === "gallery") return current.thumbnails.map((item) => item.href);
if (current.kind === "reader") return readerFrames.value.map((frame) => frame.href);
}),
contentAttrs: computed(() => ({
class: {
"shell main": true,
"reader-main": Boolean(reader.value)
},
"aria-busy": busy.value,
tabindex: reader.value && !desktopNavigation.value ? 0 : void 0,
"aria-label": reader.value && !desktopNavigation.value ? "阅读内容,按回车切换菜单" : void 0,
onClick: tapReader,
onKeydown: (event) => {
if (event.key === "Enter" && event.target === event.currentTarget && reader.value && !desktopNavigation.value) toggleReaderChrome();
}
}))
};
}
function getFlightCenter(element) {
const bounds = element.getBoundingClientRect();
if (!bounds.width || !bounds.height) return;
const x = bounds.left + bounds.width / 2;
const y = bounds.top + bounds.height / 2;
return x >= 0 && x <= innerWidth && y >= 0 && y <= innerHeight ? {
x,
y
} : void 0;
}
function getBookmarkOrigin(source) {
if (source instanceof HTMLElement) return getFlightCenter(source.querySelector("svg") ?? source);
}
function readerFrame(page, href) {
return {
href,
image: page.image,
width: page.width,
height: page.height,
index: page.index
};
}
function readerPageFrames(page, href) {
return page.frames ?? [readerFrame(page, href)];
}
function readerHasNext(page) {
const last = page.frames?.at(-1)?.index ?? page.index;
return Boolean(page.next && (!page.total || last < page.total));
}
function firstReaderIndex(page) {
return page.frames?.[0]?.index ?? page.index;
}
function queuedReaderPage(page, gallery) {
return gallery ? {
...page,
gallery: page.gallery ?? gallery.href,
total: page.total || gallery.pages
} : page;
}
function useIconFlight(token, reducedMotion) {
let flight;
let arrival;
function cancel() {
flight?.cancel();
arrival?.cancel();
}
function fly(start, destination) {
if (!start || !destination || !token.value || reducedMotion.value) return false;
const end = getFlightCenter(destination);
if (!end) return false;
cancel();
const arcHeight = Math.min(160, Math.hypot(end.x - start.x, end.y - start.y) * .35);
const frames = Array.from({ length: 9 }, (_, step) => {
const progress = step / 8;
return {
transform: `translate(${start.x + (end.x - start.x) * progress}px, ${start.y + (end.y - start.y) * progress - arcHeight * progress * (1 - progress)}px) translate(-50%, -50%) scale(${1 - .45 * progress})`,
opacity: 1 - .8 * progress ** 4
};
});
flight = token.value.animate(frames, {
duration: 440,
easing: "cubic-bezier(.25, .75, .35, 1)"
});
flight.onfinish = () => {
if (!destination.isConnected || reducedMotion.value) return;
arrival = destination.animate([
{ scale: "1" },
{
scale: "1.23",
offset: .42
},
{ scale: "1" }
], {
duration: 220,
easing: "ease-out"
});
};
return true;
}
onScopeDispose(cancel);
return {
cancel,
fly
};
}
function useBookmarkFlight(app, reducedMotion) {
const token = shallowRef(null);
const noticeDestination = shallowRef(null);
const { cancel, fly } = useIconFlight(token, reducedMotion);
function sidebarDestination() {
const sidebar = app.value?.querySelector(".site-sidebar");
const icon = sidebar?.querySelector("[data-section='later'] svg");
if (!sidebar || !icon) return;
const point = getFlightCenter(icon);
const { top, bottom } = sidebar.getBoundingClientRect();
if (point && point.y >= top && point.y <= bottom) return icon;
}
function flyToNotice(start) {
return fly(start, noticeDestination.value ?? void 0);
}
return {
cancel,
fly,
flyToNotice,
sidebarDestination,
token,
noticeDestination
};
}
var removalMessages = {
"remove-from-later": "已从稍后阅读移除",
"remove-from-history": "已删除这条浏览历史",
"remove-many": "已删除所选记录"
};
function useGalleryLibrary({ adapter, navigation, app, desktop, reducedMotion }) {
const { activeReader: reader, currentUrl, readerGalleryUrl, page, readerChapter, readerIndex, readerSections, readingQueue, startReadingQueue } = navigation;
const readingLibrary = useReadingLibraryStore();
const { library, savingLibrary, bookmarksBusy, historyByGalleryHref, savedGalleryUrls } = storeToRefs(readingLibrary);
const { changeLibrary } = readingLibrary;
const selectingGalleries = shallowRef(false);
const cardActionSheet = shallowRef();
const cardActionDialog = shallowRef(null);
let cardActionTrigger;
const libraryNotice = shallowRef();
const { start: startLibraryNotice, stop: stopLibraryNotice } = useTimeoutFn(() => libraryNotice.value = void 0, 4800, { immediate: false });
const bookmarkFlight = useBookmarkFlight(app, reducedMotion);
const pendingRemoval = shallowRef();
const removalFailed = shallowRef(false);
const removalDialog = computed(() => {
const request = pendingRemoval.value;
if (!request) return;
if (request.change.type === "remove-many") {
const section = librarySections[request.change.section];
return {
title: `从${section}批量删除?`,
message: `将从${section}移除所选的 ${request.change.hrefs.length} 条记录。`,
confirmLabel: "确认删除"
};
}
const section = request.change.type === "remove-from-history" ? librarySections.history : librarySections.later;
return {
title: `从${section}移除?`,
message: `将从${section}移除《${request.title}》。`,
confirmLabel: "确认删除"
};
});
const derived = createGalleryLists();
const { readingGallery, cardRemovalSection } = derived;
function watchLibrary() {
watch(currentUrl, () => {
selectingGalleries.value = false;
pendingRemoval.value = void 0;
cardActionSheet.value = void 0;
cardActionTrigger = void 0;
libraryNotice.value = void 0;
stopLibraryNotice();
bookmarkFlight.cancel();
});
watch([
currentUrl,
readerIndex,
navigation.restoringReader
], () => {
if (navigation.restoringReader.value) return;
const gallery = readingGallery.value;
if (!gallery) return;
const section = readerSections.value.find(({ chapter }) => chapter === readerChapter.value);
const frame = (section && readerPageFrames(section.page, section.url))?.find(({ index }) => index === readerIndex.value);
const progress = frame ? {
href: frame.href,
index: frame.index
} : void 0;
changeLibrary({
type: "visit",
gallery,
progress
});
}, {
immediate: true,
flush: "post"
});
watch(desktop, (wide) => {
if (wide) closeCardActionSheet();
});
}
function createGalleryLists() {
const readingGallery = computed(() => {
const current = page.value;
if (current.kind === "gallery") {
const { href, cover, pages, title } = current;
return {
href: galleryKey(href),
cover,
pages,
title
};
}
if (reader.value) {
const queued = readingQueue.value?.[readerChapter.value];
if (queued) return {
...queued,
pages: reader.value.total || queued.pages
};
const href = readerGalleryUrl(reader.value);
if (href) return {
href: galleryKey(href),
title: reader.value.title,
pages: reader.value.total
};
}
});
const galleryProgress = computed(() => {
if (page.value.kind !== "gallery" || !readingGallery.value) return;
const progress = historyByGalleryHref.value.get(readingGallery.value.href)?.progress;
return progress && progress.index > 1 ? progress : void 0;
});
const savedForLater = computed(() => savedGalleryUrls.value.has(readingGallery.value?.href ?? ""));
const cardRemovalSection = computed(() => {
const sheet = cardActionSheet.value;
if (!sheet) return;
return sheet.section ?? (savedGalleryUrls.value.has(galleryKey(sheet.gallery.href)) ? "later" : void 0);
});
const catalogLists = computed(() => {
const current = page.value;
if (current.kind !== "catalog") return { items: [] };
const historyByHref = historyByGalleryHref.value;
const withProgress = (items) => {
if (!historyByHref.size) return items;
return items.map((item) => {
const history = historyByHref.get(galleryKey(item.href));
if (!history?.progress) return item;
return {
...item,
pages: item.pages || history.gallery.pages,
progressIndex: history.progress.index
};
});
};
const featured = current.featured;
return {
items: withProgress(current.items),
featured: featured && {
...featured,
items: withProgress(featured.items)
}
};
});
const savedCatalogHrefs = computed(() => {
const saved = savedGalleryUrls.value;
if (!saved.size) return new Set();
const { items, featured } = catalogLists.value;
const galleries = featured ? [...featured.items, ...items] : items;
return new Set(galleries.filter((item) => saved.has(galleryKey(item.href))).map((item) => item.href));
});
return {
readingGallery,
readerTotal: computed(() => {
if (!reader.value) return 0;
const href = readingGallery.value?.href;
return reader.value.total || readingGallery.value?.pages || href && historyByGalleryHref.value.get(href)?.gallery.pages || 0;
}),
galleryProgress,
savedForLater,
cardRemovalSection,
catalogLists,
savedCatalogHrefs
};
}
function galleryKey(href) {
const url = new URL(href);
return adapter.canonicalGalleryUrl?.(url) ?? url.href;
}
function requestRemoval(change, source, title) {
if (savingLibrary.value || pendingRemoval.value) return;
const trigger = source instanceof HTMLElement ? source : void 0;
libraryNotice.value = void 0;
stopLibraryNotice();
removalFailed.value = false;
pendingRemoval.value = {
change,
trigger,
title
};
}
async function closeRemoval() {
const trigger = pendingRemoval.value?.trigger;
const url = currentUrl.value;
pendingRemoval.value = void 0;
await nextTick();
if (url !== currentUrl.value) return;
(trigger?.isConnected ? trigger : app.value?.querySelector(".catalog-title h1"))?.focus({ preventScroll: true });
}
async function confirmRemoval() {
const request = pendingRemoval.value;
if (!request || savingLibrary.value) return;
removalFailed.value = false;
const saved = await changeLibrary(request.change);
if (pendingRemoval.value !== request) return;
if (!saved) {
removalFailed.value = true;
return;
}
const url = currentUrl.value;
if (request.change.type === "remove-many") selectingGalleries.value = false;
await closeRemoval();
if (currentUrl.value !== url) return;
libraryNotice.value = { text: removalMessages[request.change.type] };
startLibraryNotice();
}
function openCardActionSheet(event, gallery, section) {
if (bookmarksBusy.value || !(event.currentTarget instanceof HTMLElement)) return;
cardActionTrigger = event.currentTarget;
cardActionSheet.value = {
gallery,
trigger: cardActionTrigger,
section
};
}
function closeCardActionSheet() {
cardActionSheet.value = void 0;
}
function restoreCardActionFocus() {
if (cardActionSheet.value) return;
if (!pendingRemoval.value) cardActionTrigger?.focus({ preventScroll: true });
cardActionTrigger = void 0;
}
function submitCardAction(event) {
const selection = cardActionSheet.value;
if (!selection) return;
const section = cardRemovalSection.value;
closeCardActionSheet();
if (section) {
cardActionDialog.value?.closeDialog();
requestRemoval({
type: section === "history" ? "remove-from-history" : "remove-from-later",
href: selection.section ? selection.gallery.href : galleryKey(selection.gallery.href)
}, selection.trigger, selection.gallery.title);
return;
}
const start = getBookmarkOrigin(event.currentTarget);
cardActionDialog.value?.closeDialog();
toggleReadLater(selection.trigger, selection.gallery, start);
}
async function showBookmarkResult(saved, start, options = {}) {
const { batch, added = saved } = options;
const flewToSidebar = added && bookmarkFlight.fly(start, bookmarkFlight.sidebarDestination());
if (flewToSidebar && !batch) return;
libraryNotice.value = saved ? {
text: batch ? "所选画廊已在稍后阅读" : "已加入稍后阅读",
saved: true
} : {
text: "保存失败,请重试",
failed: true
};
const notice = libraryNotice.value;
startLibraryNotice();
if (!added || flewToSidebar) return;
await nextTick();
if (libraryNotice.value === notice) bookmarkFlight.flyToNotice(start);
}
async function toggleReadLater(source, gallery, start = getBookmarkOrigin(source)) {
if (!gallery || bookmarksBusy.value) return;
const { title, cover, pages } = gallery;
const href = galleryKey(gallery.href);
if (savedGalleryUrls.value.has(href)) {
requestRemoval({
type: "remove-from-later",
href
}, source, title);
return;
}
libraryNotice.value = void 0;
stopLibraryNotice();
bookmarkFlight.cancel();
const url = currentUrl.value;
const saved = await changeLibrary({
type: "save-for-later",
gallery: {
href,
title,
cover,
pages
}
});
if (url === currentUrl.value) await showBookmarkResult(saved, start);
}
async function saveSelectedForLater(items, event) {
if (bookmarksBusy.value || !items.length) return;
const start = getBookmarkOrigin(event.currentTarget);
const url = currentUrl.value;
libraryNotice.value = void 0;
stopLibraryNotice();
bookmarkFlight.cancel();
const galleries = items.map(({ href, title, cover, pages }) => ({
href: galleryKey(href),
title,
cover,
pages
}));
const hasNewGallery = galleries.some(({ href }) => !savedGalleryUrls.value.has(href));
const saved = await changeLibrary({
type: "save-many-for-later",
galleries
});
if (url !== currentUrl.value) return;
if (saved) {
selectingGalleries.value = false;
await nextTick();
if (url !== currentUrl.value) return;
app.value?.querySelector(".catalog-title h1")?.focus({ preventScroll: true });
}
await showBookmarkResult(saved, start, {
batch: true,
added: saved && hasNewGallery
});
}
function readAll() {
const chapters = new Map();
for (const { gallery } of library.value.later) {
const href = galleryKey(gallery.href);
if (!chapters.has(href)) chapters.set(href, {
...gallery,
href
});
}
startReadingQueue([...chapters.values()]);
}
watchLibrary();
function dialogActions() {
return {
openCardActionSheet,
removalDialog,
removalFailed,
requestRemoval,
closeRemoval,
confirmRemoval,
cardActionDialog,
bookmarkFlightElement: bookmarkFlight.token,
bookmarkNoticeDestination: bookmarkFlight.noticeDestination
};
}
return {
...derived,
selectingGalleries,
cardActionSheet,
closeCardActionSheet,
restoreCardActionFocus,
submitCardAction,
...dialogActions(),
libraryNotice,
stopLibraryNotice,
startLibraryNotice,
toggleReadLater,
saveSelectedForLater,
readAll
};
}
function useGallerySearch(adapter, navigation, header, compactSearch, reducedMotion, activate) {
const { currentUrl, page, navigate } = navigation;
const searchOpen = shallowRef(false);
const tagFlightElement = shallowRef(null);
const tagFlight = useIconFlight(tagFlightElement, reducedMotion);
const search = shallowRef(page.value.kind === "catalog" ? page.value.query : "");
const tagSearch = shallowRef();
const remainingTerms = computed(() => {
const selected = tagSearch.value?.term.toLowerCase();
if (!selected) return;
const terms = searchTokens(search.value);
const remaining = terms.filter(({ text }) => text.toLowerCase() !== selected);
if (remaining.length !== terms.length) return remaining;
});
const tagInSearch = computed(() => remainingTerms.value !== void 0);
const tags = useTagDirectoryStore();
const { remember } = useSearchHistoryStore();
function watchSearchContext() {
watch(currentUrl, () => {
tagFlight.cancel();
searchOpen.value = false;
tagSearch.value = void 0;
if (page.value.kind === "catalog") search.value = page.value.query;
});
watch(compactSearch, () => {
tagFlight.cancel();
searchOpen.value = false;
});
watch(() => page.value.kind, (kind) => {
if (kind === "gallery" || kind === "tags") loadTags();
}, { immediate: true });
}
function loadTags() {
return tags.load(adapter);
}
function submitSearch(value = search.value) {
searchOpen.value = false;
const query = value.trim();
search.value = query;
remember(query);
navigate(adapter.search(new URL(currentUrl.value), query));
}
function openTagSearch(event, tag) {
if (!isPrimaryClick(event) || !tag.href) return;
if (!tag.searchTerm || !(event.currentTarget instanceof HTMLElement)) {
activate(event, tag.href);
return;
}
event.preventDefault();
const trigger = event.currentTarget;
tagSearch.value = tagSearch.value?.trigger === trigger ? void 0 : {
tag,
trigger,
href: tag.href,
term: tag.searchTerm
};
}
function dismissTagSearch(restoreFocus) {
const trigger = tagSearch.value?.trigger;
tagSearch.value = void 0;
if (restoreFocus) trigger?.focus({ preventScroll: true });
}
async function toggleTagInSearch() {
const selection = tagSearch.value;
if (!selection) return;
const { term, trigger } = selection;
const remaining = remainingTerms.value;
const start = remaining ? void 0 : getFlightCenter(trigger);
dismissTagSearch(true);
search.value = remaining ? remaining.map(({ text }) => text).join(" ") : [search.value.trimEnd(), term].filter(Boolean).join(" ");
await nextTick();
if (start) tagFlight.fly(start, header.value?.searchIcon());
}
function runTagSearch(event) {
if (!isPrimaryClick(event)) return;
const selection = tagSearch.value;
dismissTagSearch(true);
if (!selection) return;
remember(selection.term);
activate(event, selection.href);
}
function openSearch() {
searchOpen.value = true;
}
async function closeSearch(restoreFocus = true) {
if (!searchOpen.value) return;
searchOpen.value = false;
await nextTick();
if (restoreFocus) header.value?.focusSearchToggle();
}
watchSearchContext();
return {
search,
searchOpen,
tagSearch,
tagFlightElement,
tagInSearch,
loadTags,
submitSearch,
openTagSearch,
dismissTagSearch,
toggleTagInSearch,
runTagSearch,
openSearch,
closeSearch
};
}
var pageLimit = 48;
var groupLimit = 12;
var readerImageLimit = 576;
function touch(map, key, value) {
map.delete(key);
map.set(key, value);
}
function trim(map, limit) {
if (map.size <= limit) return;
const oldest = map.keys().next();
if (!oldest.done) map.delete(oldest.value);
}
function readerImageKey(href) {
const url = new URL(href);
return url.origin + url.pathname.replace(/\/$/, "");
}
var usePageCacheStore = defineStore("page-cache", () => {
const groupsByKind = shallowRef(new Map());
const readerImages = shallowReactive(new Map());
const get = ({ kind, key }, href) => {
const groups = groupsByKind.value.get(kind);
const pages = groups?.get(key);
const entry = pages?.get(href);
if (groups && pages && entry) {
touch(groups, key, pages);
touch(pages, href, entry);
}
return entry;
};
const set = ({ kind, key }, href, entry) => {
const groups = groupsByKind.value.get(kind) ?? new Map();
const pages = groups.get(key) ?? new Map();
touch(pages, href, entry);
trim(pages, pageLimit);
touch(groups, key, pages);
trim(groups, groupLimit);
groupsByKind.value.set(kind, groups);
triggerRef(groupsByKind);
};
const update = (kind, updateEntry) => {
const groups = groupsByKind.value.get(kind);
if (!groups) return;
for (const [key, pages] of groups) {
for (const [href, entry] of pages) {
const updated = updateEntry(entry);
if (updated) pages.set(href, updated);
else pages.delete(href);
}
if (!pages.size) groups.delete(key);
}
if (!groups.size) groupsByKind.value.delete(kind);
triggerRef(groupsByKind);
};
function getReaderImage(href) {
return readerImages.get(readerImageKey(href));
}
function setReaderImage(frame) {
touch(readerImages, readerImageKey(frame.href), frame);
trim(readerImages, readerImageLimit);
}
function forgetReaderImage(href, image) {
const key = readerImageKey(href);
return readerImages.get(key)?.image === image && readerImages.delete(key);
}
return {
groupsByKind,
get,
set,
update,
readerImages,
getReaderImage,
setReaderImage,
forgetReaderImage
};
});
function readNavigationState() {
return history.state;
}
function createNavigationPager({ route, reader }, pagination, loader, { firstReaderPage, lastReaderPage, readerTargetUrl }, viewActive) {
let appendController;
function cancelLoadMore() {
appendController?.abort();
}
function nextLoad(direction) {
if (viewActive?.value === false || route.pending.value || appendController || !route.currentUrl.value) return;
const prepend = direction === "previous";
const routePage = route.page.value;
const leading = prepend ? reader.firstSection.value : void 0;
const current = leading?.page ?? routePage;
if (current.kind === "tags" || current.kind === "library" || prepend && current.kind !== "reader") return;
const chapter = prepend ? reader.previousChapter.value : current.kind === "reader" && !readerHasNext(current) ? reader.nextChapter.value : void 0;
if (current.kind === "reader" && (prepend ? !pagination.hasPrevious.value : !pagination.canLoadNextPage.value && !pagination.canLoadNextChapter.value)) return;
return {
prepend,
routePage,
leading,
current,
chapter,
routeUrl: leading?.url ?? reader.tailUrl.value,
loading: prepend ? pagination.loadingPrevious : pagination.loadingMore,
errorMessage: prepend ? pagination.loadPreviousFailure : pagination.loadMoreFailure
};
}
async function appendChapter(load, entry, signal) {
const { leading, chapter, routePage } = load;
if (!chapter) return false;
if (leading && entry.page.kind === "reader") {
reader.earlierSections.value = [{
chapter: leading.chapter - 1,
url: entry.url,
page: queuedReaderPage(entry.page, chapter)
}, ...reader.earlierSections.value];
return true;
}
const next = await firstReaderPage(entry, signal);
if (signal.aborted || route.page.value !== routePage) return false;
reader.earlierSections.value = reader.readerSections.value;
reader.tailChapter.value += 1;
reader.tailUrl.value = next.url;
route.page.value = queuedReaderPage(next.page, chapter);
return true;
}
function appendPage(load, entry, direction, targetUrl) {
const { current, leading, routeUrl } = load;
if (current.kind === "catalog" && entry.page.kind === "catalog") {
route.page.value = {
...current,
items: appendUnique(current.items, entry.page.items, (item) => item.href),
next: entry.page.next === targetUrl ? void 0 : entry.page.next
};
return;
}
if (current.kind === "gallery" && entry.page.kind === "gallery") {
route.page.value = {
...current,
thumbnails: appendUnique(current.thumbnails, entry.page.thumbnails, (item) => item.href),
next: entry.page.next === targetUrl ? void 0 : entry.page.next
};
return;
}
if (current.kind !== "reader" || entry.page.kind !== "reader") return;
const nextPage = mergeFrames(current, entry.page, routeUrl, entry.url, targetUrl, direction, Boolean(reader.readingQueue.value));
if (leading && reader.earlierSections.value.length) {
reader.earlierSections.value = [{
...leading,
page: nextPage
}, ...reader.earlierSections.value.slice(1)];
return;
}
route.page.value = nextPage;
}
async function loadMore(direction = "next") {
const load = nextLoad(direction);
if (!load) return;
const { prepend, routePage, leading, current, chapter, loading, errorMessage } = load;
const request = new AbortController();
appendController = request;
loading.value = true;
try {
const targetUrl = chapter?.href ?? current[direction] ?? (prepend && current.kind === "reader" ? await readerTargetUrl(current, firstReaderIndex(current) - 1, request.signal) : void 0);
if (!targetUrl) return;
const entry = prepend && chapter ? await lastReaderPage(chapter, request.signal) : await loader.load(targetUrl, request.signal);
if (request.signal.aborted || route.page.value !== routePage) return;
if (leading && entry.page.kind !== "reader") throw new Error("无法加载上一页。");
if (chapter) {
if (!await appendChapter(load, entry, request.signal)) return;
} else appendPage(load, entry, direction, targetUrl);
errorMessage.value = void 0;
} catch (error) {
if (!request.signal.aborted) errorMessage.value = error instanceof Error ? error.message : "加载更多失败。";
} finally {
if (appendController === request) {
appendController = void 0;
loading.value = false;
}
}
}
async function retryLoadMore(direction = "next") {
if (route.pending.value || appendController) return;
if (direction === "next") pagination.loadMoreFailure.value = void 0;
await loadMore(direction);
}
return {
loadMore,
cancelLoadMore,
retryLoadMore
};
}
function mergeFrames(current, nextPage, routeUrl, nextUrl, targetUrl, direction, hasQueue) {
const prepend = direction === "previous";
const oldFrames = readerPageFrames(current, routeUrl);
const incoming = readerPageFrames(nextPage, nextUrl);
const firstIndex = firstReaderIndex(current);
const lastIndex = oldFrames.at(-1)?.index ?? current.index;
const adjacentFrames = incoming.filter((frame) => prepend ? frame.index < firstIndex : frame.index > lastIndex);
if (prepend && hasQueue && !adjacentFrames.some((frame) => frame.index === firstIndex - 1)) throw new Error(`找不到第 ${firstIndex - 1} 页。`);
const frames = prepend ? appendUnique(adjacentFrames, oldFrames, (item) => item.href) : appendUnique(oldFrames, adjacentFrames, (item) => item.href);
const nextLink = nextPage[direction];
const boundary = nextLink === targetUrl || frames.length === oldFrames.length ? void 0 : nextLink;
return {
...current,
[direction]: boundary,
frames
};
}
function createNavigationState(adapter, initialPage, initialUrl) {
const currentUrl = ref(initialUrl);
const localPage = (url) => libraryPage(url, adapter.home(new URL(url)));
const initialQueue = initialPage.kind === "reader" ? readNavigationState()?.readingQueue : void 0;
const initialChapter = initialQueue?.chapters[initialQueue.chapter];
const page = shallowRef(localPage(initialUrl) ?? (initialPage.kind === "reader" ? queuedReaderPage(initialPage, initialChapter) : initialPage));
return {
route: {
currentUrl,
page,
pending: ref(),
failure: shallowRef(),
refreshing: ref(false),
returningToStart: ref(false),
seekingReader: ref(false),
restoringReader: ref(false),
savingTags: ref(false),
galleryRestoration: shallowRef()
},
reader: createReaderState(page, initialPage, initialUrl, initialQueue),
localPage
};
}
function createReaderState(page, initialPage, initialUrl, initialQueue) {
const readingQueue = shallowRef(initialQueue?.chapters);
const readerChapter = ref(initialQueue?.chapter ?? 0);
const tailChapter = ref(readerChapter.value);
const tailUrl = ref(initialUrl);
const earlierSections = shallowRef([]);
const readerSections = computed(() => page.value.kind === "reader" ? [...earlierSections.value, {
chapter: tailChapter.value,
url: tailUrl.value,
page: page.value
}] : []);
const activeReader = computed(() => readerSections.value.find((section) => section.chapter === readerChapter.value)?.page);
const firstSection = computed(() => readerSections.value[0]);
const previousChapter = computed(() => {
const first = firstSection.value;
return first && firstReaderIndex(first.page) === 1 ? readingQueue.value?.[first.chapter - 1] : void 0;
});
const nextChapter = computed(() => readingQueue.value?.[tailChapter.value + 1]);
return {
readerIndex: ref(initialPage.kind === "reader" ? initialPage.index : 0),
readerRevision: ref(0),
readerPages: shallowRef(null),
readingQueue,
readerChapter,
tailChapter,
tailUrl,
earlierSections,
readerSections,
activeReader,
firstSection,
previousChapter,
nextChapter
};
}
function createPaginationState({ route, reader }, viewActive) {
const loadingMore = ref(false);
const loadMoreFailure = shallowRef();
const loadingPrevious = ref(false);
const loadPreviousFailure = shallowRef();
const hasMore = computed(() => {
const current = route.page.value;
if (current.kind === "reader") return readerHasNext(current) || Boolean(reader.nextChapter.value);
return "next" in current && Boolean(current.next);
});
const reachedEnd = computed(() => {
if (viewActive?.value === false || hasMore.value || route.pending.value || route.failure.value || loadMoreFailure.value) return false;
if (loadingMore.value || loadingPrevious.value) return false;
const current = route.page.value;
if (current.kind === "catalog") return Boolean(current.items.length || current.featured?.items.length);
if (current.kind === "gallery") return current.thumbnails.length > 0;
return current.kind === "reader" && (!current.total || (current.frames?.at(-1)?.index ?? current.index) >= current.total);
});
const canLoadNextPage = computed(() => {
const current = route.page.value;
return current.kind === "reader" ? readerHasNext(current) : hasMore.value;
});
return {
loadingMore,
loadMoreFailure,
loadingPrevious,
loadPreviousFailure,
hasMore,
reachedEnd,
canLoadNextPage,
canLoadNextChapter: computed(() => Boolean(reader.nextChapter.value) && !canLoadNextPage.value && reader.readerChapter.value === reader.tailChapter.value),
hasPrevious: computed(() => {
const first = reader.firstSection.value;
if (!first) return false;
return Boolean(reader.previousChapter.value || firstReaderIndex(first.page) > 1 && (first.page.previous || reader.readingQueue.value && first.page.gallery));
})
};
}
var snapshotLimit = 12;
var usePagedHistoryStore = defineStore("paged-history", () => {
const snapshots = shallowRef({
catalog: new Map(),
gallery: new Map(),
reader: new Map()
});
function remember(id, snapshot, entries) {
const { catalog, gallery, reader } = snapshots.value;
catalog.delete(id);
gallery.delete(id);
reader.delete(id);
entries.set(id, snapshot);
if (entries.size > snapshotLimit) {
const oldest = entries.keys().next();
if (!oldest.done) entries.delete(oldest.value);
}
triggerRef(snapshots);
}
function save(id, snapshot) {
remember(id, snapshot, snapshots.value[snapshot.page.kind]);
}
function saveReader(id, snapshot) {
remember(id, snapshot, snapshots.value.reader);
}
function restore(id, url) {
const { catalog, gallery } = snapshots.value;
const snapshot = id && (catalog.get(id) ?? gallery.get(id));
if (snapshot && snapshot.url === url) return snapshot;
}
function restoreReader(id, url) {
const snapshot = id && snapshots.value.reader.get(id);
if (snapshot && snapshot.url === url) return snapshot;
}
function clearCatalogs(matches) {
const { catalog } = snapshots.value;
if (!matches) catalog.clear();
else for (const [id, snapshot] of catalog) if (matches(snapshot.url)) catalog.delete(id);
triggerRef(snapshots);
}
function updateGalleryFavorite(matches, favorite) {
for (const snapshot of snapshots.value.gallery.values()) if (snapshot.page.kind === "gallery" && matches(snapshot.url)) snapshot.page = {
...snapshot.page,
favorite
};
}
return {
snapshots,
save,
restore,
saveReader,
restoreReader,
clearCatalogs,
updateGalleryFavorite
};
});
function newHistoryId() {
return Array.from(crypto.getRandomValues(new Uint32Array(2))).join("-");
}
function useNavigationHistory() {
const pagedHistory = usePagedHistoryStore();
const scrollPositions = new Map();
let entryId = readNavigationState()?.entryId ?? newHistoryId();
if (!readNavigationState()?.entryId) history.replaceState({
...readNavigationState(),
entryId
}, "");
function isCurrentEntry() {
return readNavigationState()?.entryId === entryId;
}
function remember(url, page, viewport, source, reader) {
if (page.kind === "reader") {
if (reader) pagedHistory.saveReader(entryId, {
url,
...reader
});
return;
}
const position = captureScrollPosition(viewport, source);
if (page.kind === "catalog" || page.kind === "gallery") pagedHistory.save(entryId, {
url,
page,
...position
});
else scrollPositions.set(url, position);
}
function commit(url, previousUrl, previousKind, readingQueue, push) {
const previous = readNavigationState();
const nextId = push ? newHistoryId() : previous?.entryId ?? newHistoryId();
const state = {
...previous,
entryId: nextId,
readingQueue
};
if (push) history.pushState({
entryId: nextId,
betterEh: true,
previousUrl,
previousKind,
readingQueue
}, "", url);
else if (url !== location.href || state.readingQueue || previous?.readingQueue || !previous?.entryId) history.replaceState(state, "", url);
entryId = nextId;
}
function replaceReadingChapter(url, readingQueue) {
history.replaceState({
...readNavigationState(),
readingQueue
}, "", url);
}
return {
remember,
commit,
replaceReadingChapter,
isCurrentEntry,
restorePage: pagedHistory.restore,
restoreReader: pagedHistory.restoreReader,
restoreScrollPosition: (url) => scrollPositions.get(url),
clearCatalogs: pagedHistory.clearCatalogs,
updateGalleryFavorite: pagedHistory.updateGalleryFavorite
};
}
function createReaderPageResolver(adapter, loader, readerGalleryUrl) {
async function firstReaderPage(entry, signal) {
const gallery = entry.page.kind === "gallery" ? entry.page : void 0;
const first = gallery && (adapter.readerPageUrl?.(new URL(gallery.href), 1) ?? gallery.thumbnails.find((thumbnail) => thumbnail.index === 1)?.href);
const result = first ? await loader.load(first, signal) : entry;
if (result.page.kind !== "reader" || result.page.index !== 1) throw new Error("找不到第 1 页。");
return {
url: result.url,
page: result.page
};
}
async function readerTargetUrl(current, index, signal) {
const first = firstReaderIndex(current);
const last = current.frames?.at(-1)?.index ?? current.index;
const known = current.frames?.find((frame) => frame.index === index)?.href ?? (index === first - 1 ? current.previous : index === last + 1 ? current.next : void 0) ?? (index === 1 ? current.first : void 0);
if (known) return known;
const href = readerGalleryUrl(current);
if (!href) throw new Error(`找不到第 ${index} 页。`);
return galleryReaderUrl(new URL(href), index, signal);
}
async function galleryReaderUrl(gallery, index, signal, firstPage) {
const direct = adapter.readerPageUrl?.(gallery, index);
if (direct) return direct;
const target = (await galleryThumbnails(gallery, index, signal, firstPage)).find((thumbnail) => thumbnail.index === index);
if (!target) throw new Error(`找不到第 ${index} 页。`);
return target.href;
}
async function galleryThumbnails(gallery, index, signal, firstPage) {
const batchUrl = adapter.galleryThumbnailPageUrl;
const page = firstPage ?? (await loader.load(batchUrl?.(gallery, 0) ?? gallery.href, signal)).page;
if (page.kind !== "gallery") return [];
const thumbnails = page.thumbnails;
if (thumbnails.some((thumbnail) => thumbnail.index === index)) return thumbnails;
const pageSize = thumbnails.at(-1)?.index ?? 0;
if (!batchUrl || !pageSize || thumbnails[0]?.index !== 1 || index <= pageSize) return [];
const batch = await loader.load(batchUrl(gallery, Math.floor((index - 1) / pageSize)), signal);
return batch.page.kind === "gallery" ? batch.page.thumbnails : [];
}
async function lastReaderPage(gallery, signal) {
const url = new URL(gallery.href);
const entry = await loader.load(adapter.galleryThumbnailPageUrl?.(url, 0) ?? url.href, signal);
if (entry.page.kind !== "gallery") throw new Error("无法打开上一章。");
let total = entry.page.pages || gallery.pages;
if (!total) {
const first = await firstReaderPage(entry, signal);
if (first.page.total === 1 || !first.page.total && !first.page.next) return first;
total = first.page.total;
}
if (!total) throw new Error("找不到上一章的最后一页。");
const href = await galleryReaderUrl(url, total, signal, entry.page);
const last = await loader.load(href, signal);
if (last.page.kind !== "reader" || last.page.index !== total) throw new Error("找不到上一章的最后一页。");
return {
url: last.url,
page: last.page
};
}
return {
firstReaderPage,
readerTargetUrl,
lastReaderPage,
galleryThumbnails
};
}
function useReaderNavigation(state, adapter, loader, pageHistory, viewActive) {
const { route, reader } = state;
const resolver = createReaderPageResolver(adapter, loader, readerGalleryUrl);
const { galleryThumbnails } = resolver;
function showReaderFrame(chapter, index) {
if (viewActive?.value === false || !pageHistory.isCurrentEntry()) return;
const chapters = reader.readingQueue.value;
if (chapter !== reader.readerChapter.value && chapters) {
const section = reader.readerSections.value.find((item) => item.chapter === chapter);
if (!section) return;
const url = section.page.frames?.find((frame) => frame.index === index)?.href ?? section.url;
pageHistory.replaceReadingChapter(url, {
chapters,
chapter
});
route.currentUrl.value = url;
reader.readerChapter.value = chapter;
document.title = section.page.title + " · Better EH";
}
reader.readerIndex.value = index;
}
function readerGalleryUrl(current) {
const state = readNavigationState();
return current.gallery ?? (state?.previousKind === "gallery" ? state.previousUrl : void 0);
}
async function scrollToReaderFrame(chapter, index, signal, onPositioned) {
if (!await reader.readerPages.value?.scrollToPage(chapter, index, signal)) return false;
if (!signal.aborted) {
route.restoringReader.value = false;
showReaderFrame(chapter, index);
onPositioned();
}
return true;
}
async function restoreReaderPosition(snapshot, title, signal) {
const positioned = await reader.readerPages.value?.restoreHistoryAnchor(snapshot.anchor, signal);
if (signal.aborted) return;
if (!positioned) throw new Error("无法恢复阅读位置。");
document.title = (reader.activeReader.value?.title ?? title) + " · Better EH";
route.restoringReader.value = false;
}
function captureSnapshot() {
const tail = reader.readerSections.value.at(-1);
const anchor = tail && reader.readerPages.value?.captureHistoryAnchor(reader.readerChapter.value, reader.readerIndex.value);
return tail && anchor ? {
anchor,
tail,
earlier: reader.earlierSections.value
} : void 0;
}
function syncReaderOnNavigation(entry, readerQueue, readerSnapshot) {
const savedTail = readerSnapshot?.tail;
reader.readerRevision.value += 1;
reader.readingQueue.value = readerQueue?.chapters;
reader.readerChapter.value = readerSnapshot?.anchor.chapter ?? readerQueue?.chapter ?? 0;
reader.tailChapter.value = savedTail?.chapter ?? reader.readerChapter.value;
reader.tailUrl.value = savedTail?.url ?? entry.url;
reader.earlierSections.value = readerSnapshot?.earlier ?? [];
reader.readerIndex.value = readerSnapshot?.anchor.index ?? (entry.page.kind === "reader" ? entry.page.index : 0);
return entry.page.kind === "reader" && readerQueue && !readerSnapshot ? queuedReaderPage(entry.page, readerQueue.chapters[readerQueue.chapter]) : entry.page;
}
async function loadReaderImage(frame, signal) {
const entry = await loader.load(frame.reloadHref ?? frame.href, signal, true);
if (entry.page.kind !== "reader" || entry.page.index !== frame.index || adapter.pageCacheGroup(new URL(entry.url)).key !== adapter.pageCacheGroup(new URL(frame.href)).key) throw new Error("原站没有返回这一页的图片。");
return entry.page.frames?.find((item) => item.index === frame.index) ?? readerFrame(entry.page, entry.url);
}
async function loadReaderThumbnails(chapter, index, signal) {
const section = reader.readerSections.value.find((section) => section.chapter === chapter);
const href = section && readerGalleryUrl(section.page);
return href ? galleryThumbnails(new URL(href), index, signal) : [];
}
function controls(navigate) {
function returnToReaderStart(chapter = reader.readerChapter.value, index = reader.readerIndex.value) {
const current = reader.activeReader.value;
if (!current) return Promise.resolve();
if (reader.readingQueue.value) {
if (index === 1) return openReaderChapter(chapter - 1);
if (chapter !== reader.readerChapter.value) return openReaderChapter(chapter);
return navigate(route.currentUrl.value, "reader-seek", 1);
}
return navigate(current.first ?? (current.index === 2 ? current.previous : void 0) ?? readerGalleryUrl(current) ?? route.currentUrl.value, "reader-start");
}
function startReadingQueue(chapters) {
return navigate(chapters[0]?.href, "queue-start", void 0, {
chapters,
chapter: 0
});
}
function openReaderChapter(chapter) {
const chapters = reader.readingQueue.value;
const gallery = chapters?.[chapter];
if (!chapters || !gallery) return Promise.resolve();
return navigate(gallery.href, "queue-chapter", void 0, {
chapters,
chapter
});
}
return {
readerIndex: reader.readerIndex,
readerChapter: reader.readerChapter,
readerSections: reader.readerSections,
activeReader: reader.activeReader,
readingQueue: reader.readingQueue,
readerRevision: reader.readerRevision,
readerPages: reader.readerPages,
returnToReaderStart,
startReadingQueue,
openReaderChapter,
showReaderFrame,
readerGalleryUrl,
loadReaderImage,
loadReaderThumbnails
};
}
return {
resolver,
captureSnapshot,
syncReaderOnNavigation,
restoreReaderPosition,
scrollToReaderFrame,
controls
};
}
function useRouteNavigation(state, pagination, cancelLoadMore, loader, pageHistory, readerNavigation, view) {
const { route, reader, localPage } = state;
const { viewport, pageContent, viewActive } = view;
const { syncReaderOnNavigation, captureSnapshot, restoreReaderPosition, scrollToReaderFrame, resolver } = readerNavigation;
const { firstReaderPage, readerTargetUrl } = resolver;
let active;
let pageEntrance;
function showPageEntrance() {
pageEntrance?.cancel();
if (viewActive?.value === false || window.matchMedia("(prefers-reduced-motion: reduce)").matches) return;
pageEntrance = pageContent.value?.animate([{ opacity: 0 }, { opacity: 1 }], {
duration: 230,
easing: "ease-in-out"
});
}
function cancelReaderSeek() {
if (!route.seekingReader.value) return;
active?.abort();
active = void 0;
route.seekingReader.value = false;
route.pending.value = void 0;
}
function describeNavigation(mode, queue) {
const reload = mode === "refresh";
const readerStart = mode === "reader-start";
const galleryStart = mode === "gallery-start";
const readerSeek = mode === "reader-seek";
const queueChapter = mode === "queue-chapter";
const queueStart = mode === "queue-start";
const fromStart = readerStart || galleryStart || queueStart || queueChapter;
const push = mode === "push" || galleryStart || queueStart;
const current = reader.activeReader.value;
const chapters = reader.readingQueue.value;
return {
reload,
readerStart,
readerSeek,
queueChapter,
fromStart,
push,
current,
nextQueue: queue ?? (mode === "pop" ? readNavigationState()?.readingQueue : (readerSeek || reload || readerStart) && chapters ? {
chapters,
chapter: reader.readerChapter.value
} : void 0)
};
}
function beginNavigation(url, mode, plan, index) {
const { reload, readerStart, readerSeek, fromStart, current } = plan;
if (readerSeek && (!current || !index || !Number.isSafeInteger(index) || index < 1)) return;
if ((reload || readerStart) && (route.pending.value || route.savingTags.value)) return;
active?.abort();
cancelLoadMore();
pagination.loadMoreFailure.value = void 0;
pagination.loadPreviousFailure.value = void 0;
route.refreshing.value = reload;
route.returningToStart.value = readerStart;
route.seekingReader.value = readerSeek;
const keepReader = mode === "pop" && route.page.value.kind === "reader" && pageHistory.isCurrentEntry();
if (url === route.currentUrl.value && !reload && !fromStart && !readerSeek && (mode !== "pop" || keepReader) && !route.restoringReader.value) {
active = void 0;
route.pending.value = void 0;
route.failure.value = void 0;
return;
}
const request = new AbortController();
active = request;
route.pending.value = url;
route.failure.value = void 0;
return request;
}
async function resolveTarget(url, plan, signal, index, queue) {
if (plan.queueChapter && queue && await scrollToReaderFrame(queue.chapter, 1, signal, showPageEntrance)) return;
if (!plan.readerSeek || !plan.current || !index) return url;
if (await scrollToReaderFrame(reader.readerChapter.value, index, signal, showPageEntrance)) return;
return readerTargetUrl(plan.current, index, signal);
}
async function loadEntry(target, mode, plan, signal, index) {
const { reload, readerSeek, fromStart, push } = plan;
const local = localPage(target);
const historyId = mode === "pop" ? readNavigationState()?.entryId : void 0;
const restored = pageHistory.restorePage(historyId, target);
const readerSnapshot = pageHistory.restoreReader(historyId, target);
const savedTail = readerSnapshot?.tail;
let entry = local ? {
url: target,
page: local
} : restored ?? (savedTail ? {
url: target,
page: savedTail.page
} : await loader.load(target, signal, reload));
if (signal.aborted) return;
if (readerSeek && (entry.page.kind !== "reader" || entry.page.index !== index)) throw new Error(`找不到第 ${index} 页。`);
if (fromStart) entry = await firstReaderPage(entry, signal);
if (signal.aborted) return;
if (push && entry.url === route.currentUrl.value) return;
return {
entry,
restored,
readerSnapshot
};
}
async function commitEntry(loaded, mode, plan, signal, source) {
const { entry, restored, readerSnapshot } = loaded;
const { nextQueue, reload, push } = plan;
const readerQueue = entry.page.kind === "reader" ? nextQueue : void 0;
if (!reload && !route.restoringReader.value) pageHistory.remember(route.currentUrl.value, route.page.value, viewport.value, source, captureSnapshot());
pageHistory.commit(entry.url, route.currentUrl.value, route.page.value.kind, readerQueue, push);
route.restoringReader.value = Boolean(readerSnapshot);
route.galleryRestoration.value = void 0;
route.currentUrl.value = entry.url;
route.page.value = syncReaderOnNavigation(entry, readerQueue, readerSnapshot);
document.title = entry.page.title + " · Better EH";
await nextTick();
if (signal.aborted) return;
if (readerSnapshot) {
await restoreReaderPosition(readerSnapshot, entry.page.title, signal);
if (signal.aborted) return;
} else {
const position = restored ?? (mode === "pop" ? pageHistory.restoreScrollPosition(entry.url) : void 0);
viewport.value?.scrollTo({
top: position?.scrollTop ?? 0,
behavior: "instant"
});
route.galleryRestoration.value = position?.anchor;
}
if (!reload) showPageEntrance();
}
async function navigate(url, mode = "push", index, queue, source) {
if (!url) return;
const plan = describeNavigation(mode, queue);
const request = beginNavigation(url, mode, plan, index);
if (!request) return;
try {
const target = await resolveTarget(url, plan, request.signal, index, queue);
if (!target) return;
const loaded = await loadEntry(target, mode, plan, request.signal, index);
if (!loaded || request.signal.aborted) return;
await commitEntry(loaded, mode, plan, request.signal, source);
} catch (error) {
if (!request.signal.aborted) route.failure.value = {
url,
mode,
index,
queue,
message: error instanceof Error ? error.message : "页面加载失败。"
};
} finally {
if (active === request) {
active = void 0;
route.pending.value = void 0;
route.refreshing.value = false;
route.returningToStart.value = false;
route.seekingReader.value = false;
}
}
}
function retryNavigation() {
const request = route.failure.value;
if (request) navigate(request.url, request.mode, request.index, request.queue);
}
function connectLifecycle() {
const stopNavigation = () => {
active?.abort();
cancelLoadMore();
pageEntrance?.cancel();
};
onMounted(showPageEntrance);
onScopeDispose(stopNavigation);
if (viewActive) watch(viewActive, (visible) => {
if (!visible) stopNavigation();
});
history.scrollRestoration = "manual";
useEventListener$1(window, "popstate", () => {
if (history.state?.["better-eh-native"] !== true) navigate(location.href, "pop");
});
}
connectLifecycle();
return {
navigate,
retryNavigation,
cancelReaderSeek
};
}
function useSitePageActions(adapter, route, loader, pageCache, pageHistory) {
async function updateGalleryFavorite(gallery) {
const favorite = await loader.updateGalleryFavorite(gallery);
const url = new URL(gallery.href);
const group = adapter.pageCacheGroup(url).key;
const matchesGallery = (href) => adapter.pageCacheGroup(new URL(href)).key === group;
pageCache.update("gallery", (entry) => entry.page.kind === "gallery" && matchesGallery(entry.url) ? {
...entry,
page: {
...entry.page,
favorite
}
} : entry);
pageHistory.updateGalleryFavorite(matchesGallery, favorite);
if (route.page.value.kind === "gallery" && matchesGallery(route.page.value.href)) route.page.value = {
...route.page.value,
favorite
};
const href = adapter.navigation?.(url).find((item) => item.id === "favorites")?.href;
if (href) {
const favorites = new URL(href);
const matchesFavorites = (href) => {
const candidate = new URL(href);
return candidate.origin === favorites.origin && candidate.pathname.replace(/\/$/, "") === favorites.pathname.replace(/\/$/, "");
};
pageCache.update("catalog", (entry) => matchesFavorites(entry.url) ? void 0 : entry);
pageHistory.clearCatalogs(matchesFavorites);
}
return favorite;
}
async function commitTagChange(change) {
const current = route.page.value;
if (current.kind !== "tags") return;
if (route.refreshing.value || route.savingTags.value) throw new Error("请等当前操作完成后再试。");
route.savingTags.value = true;
try {
const updated = await loader.submitTagChange(route.currentUrl.value, current, change);
pageHistory.clearCatalogs();
if (route.page.value.kind === "tags" && route.page.value.activeGroup === updated.activeGroup) route.page.value = updated;
} finally {
route.savingTags.value = false;
}
}
return {
updateGalleryFavorite,
commitTagChange,
loadGalleryComments: loader.loadComments,
refreshGalleryComments: loader.refreshGalleryComments,
loadGalleryCommentTotal: adapter.galleryCommentsUrl ? loader.loadGalleryCommentTotal : void 0
};
}
function useNavigation(adapter, initialPage, initialUrl, viewport, pageContent, viewActive) {
const state = createNavigationState(adapter, initialPage, initialUrl);
const { route } = state;
const pagination = createPaginationState(state, viewActive);
const pageCache = usePageCacheStore();
const loader = createPageLoader(adapter, route.page.value.kind === "library" ? adapter.home(new URL(initialUrl)) : initialUrl, initialPage, pageCache);
const pageHistory = useNavigationHistory();
const readerNavigation = useReaderNavigation(state, adapter, loader, pageHistory, viewActive);
const pager = createNavigationPager(state, pagination, loader, readerNavigation.resolver, viewActive);
const router = useRouteNavigation(state, pagination, pager.cancelLoadMore, loader, pageHistory, readerNavigation, {
viewport,
pageContent,
viewActive
});
const siteActions = useSitePageActions(adapter, route, loader, pageCache, pageHistory);
return {
...route,
...pagination,
...pager,
...router,
...readerNavigation.controls(router.navigate),
...siteActions,
readNavigationState
};
}
function useReaderImages(frames, revision, loadImage, viewActive) {
const cache = usePageCacheStore();
const brokenImages = shallowReactive(new Set());
const imageRetryErrors = shallowReactive(new Map());
const requests = shallowReactive(new Map());
const replacements = shallowReactive(new Map());
const readerFrames = computed(() => frames.value.map((frame) => {
const replacement = replacements.get(frame.href) ?? cache.getReaderImage(frame.href);
return replacement ? {
...frame,
...replacement,
href: frame.href,
originalHref: replacement.originalHref ?? frame.originalHref
} : frame;
}));
function cancelRetries() {
for (const request of requests.values()) request.abort();
requests.clear();
}
watch(revision, () => {
cancelRetries();
brokenImages.clear();
imageRetryErrors.clear();
replacements.clear();
}, { flush: "sync" });
if (viewActive) watch(viewActive, (active) => {
if (!active) cancelRetries();
});
onScopeDispose(cancelRetries);
function markBroken(frame) {
const { href, image } = frame;
const initial = frames.value.find((item) => item.href === href);
const replaced = replacements.get(href);
const cached = cache.getReaderImage(href);
if (!initial || (replaced ?? cached ?? initial).image !== image) return;
if (cache.forgetReaderImage(href, image) && !replaced && initial.image !== image) return;
brokenImages.add(href);
}
function rememberImage(frame, size) {
if (replacements.get(frame.href)?.image !== frame.image) return;
const initial = frames.value.find((item) => item.href === frame.href);
if (initial && initial.image !== frame.image) cache.setReaderImage({
...frame,
...size
});
}
function canRetry(href) {
return brokenImages.has(href) && !requests.has(href) && viewActive?.value !== false;
}
function loadOriginalImage(frame) {
const { href, originalHref } = frame;
if (!originalHref || !canRetry(href)) return;
replacements.set(href, {
...frame,
image: originalHref
});
imageRetryErrors.delete(href);
brokenImages.delete(href);
}
async function retryImage(frame) {
const { href } = frame;
if (!canRetry(href)) return;
imageRetryErrors.delete(href);
if (!frame.reloadHref) {
if (frame.image === frame.originalHref) replacements.delete(href);
brokenImages.delete(href);
return;
}
const request = new AbortController();
requests.set(href, request);
try {
const replacement = await loadImage(frame, request.signal);
if (request.signal.aborted) return;
replacements.set(href, replacement);
brokenImages.delete(href);
} catch (error) {
if (!request.signal.aborted) imageRetryErrors.set(href, error instanceof Error ? error.message : "无法重新加载图片。");
} finally {
if (requests.get(href) === request) requests.delete(href);
}
}
return {
readerFrames,
brokenImages,
imageRetryErrors,
retryingImages: requests,
markBroken,
rememberImage,
retryImage,
loadOriginalImage
};
}
function useReaderControls({ desktopNavigation, navigation }) {
const { activeReader: reader, page, pending, failure, seekingReader, readerIndex, readerChapter, readingQueue, currentUrl, navigate, cancelReaderSeek, openReaderChapter } = navigation;
const readerChrome = shallowRef(false);
const chaptersOpen = shallowRef(false);
const readerProgressDragging = shallowRef(false);
watch(readerProgressDragging, (dragging) => {
if (dragging) navigation.cancelLoadMore();
}, { flush: "sync" });
const chromeVisible = computed(() => !reader.value || readerChrome.value);
const readerPreview = shallowRef();
let readerSeekVersion = 0;
const { start: scheduleReaderSeek, stop: stopReaderSeek } = useTimeoutFn(commitReaderSeek, 350, { immediate: false });
const readerDisplayIndex = computed(() => readerPreview.value ?? readerIndex.value);
const readerSeekFailure = computed(() => failure.value?.mode === "reader-seek" || failure.value?.mode === "queue-chapter" ? failure.value : void 0);
function watchNavigation() {
watch(currentUrl, () => {
if (!seekingReader.value) clearReaderPreview();
});
watch(readingQueue, () => {
chaptersOpen.value = false;
});
watch(() => page.value.kind, (kind) => {
if (kind !== "reader") {
readerChrome.value = false;
clearReaderPreview();
}
}, { immediate: true });
}
function clearReaderPreview() {
readerSeekVersion += 1;
stopReaderSeek();
readerPreview.value = void 0;
}
function previewReaderPage(event) {
if (!(event.target instanceof HTMLInputElement)) return;
readerSeekVersion += 1;
readerPreview.value = event.target.valueAsNumber;
if (readerSeekFailure.value) failure.value = void 0;
cancelReaderSeek();
scheduleReaderSeek();
}
async function commitReaderSeek() {
const index = readerPreview.value;
const version = readerSeekVersion;
if (reader.value && index && index !== readerIndex.value && !pending.value) await navigate(currentUrl.value, "reader-seek", index);
if (version === readerSeekVersion) readerPreview.value = void 0;
}
function toggleReaderChrome() {
readerChrome.value = !readerChrome.value;
if (!readerChrome.value) chaptersOpen.value = false;
}
async function selectReaderChapter(chapter) {
if (chapter === readerChapter.value) return false;
clearReaderPreview();
await openReaderChapter(chapter);
return chapter === readerChapter.value;
}
function tapReader(event) {
if (!reader.value || desktopNavigation.value || !isPrimaryClick(event)) return;
if (event.target instanceof Element && !event.target.closest("a, button, input, [role='alert']")) toggleReaderChrome();
}
watchNavigation();
return {
readerChrome,
chromeVisible,
chaptersOpen,
readerProgressDragging,
readerPreview,
readerDisplayIndex,
readerSeekFailure,
clearReaderPreview,
previewReaderPage,
toggleReaderChrome,
selectReaderChapter,
tapReader
};
}
function useReaderScroll({ app, navigation, reducedMotion, focusNavigation }, controls) {
const { activeReader: reader, pending, readerIndex, readerChapter, readingQueue, currentUrl, returnToReaderStart } = navigation;
const { chromeVisible, clearReaderPreview } = controls;
const returningToTop = shallowRef(false);
const { start: scheduleReturnToTopEnd } = useTimeoutFn(() => returningToTop.value = false, 200, { immediate: false });
const { y: scrollY, isScrolling } = useScroll(app, { onScroll: () => {
if (returningToTop.value) scheduleReturnToTopEnd();
} });
let stoppingScroll = false;
const readerStartsLater = computed(() => (reader.value?.frames?.[0]?.index ?? reader.value?.index ?? 1) > 1);
const showBackToTop = computed(() => chromeVisible.value && (readingQueue.value ? readerChapter.value > 0 || readerIndex.value > 1 : scrollY.value > 1 || readerStartsLater.value));
const backToTopTitle = computed(() => {
if (!reader.value) return "回到顶部";
if (!readingQueue.value) return "回到第 1 页";
return readerIndex.value === 1 ? "回到上一章第 1 页" : "回到当前章第 1 页";
});
watch(currentUrl, () => returningToTop.value = false);
async function backToTop() {
const viewport = app.value;
if (!viewport || pending.value || stoppingScroll) return;
const url = currentUrl.value;
const queue = readingQueue.value;
const chapter = readerChapter.value;
const index = readerIndex.value;
if (queue) clearReaderPreview();
if (isScrolling.value) {
stoppingScroll = true;
await stopScrollMomentum(viewport);
stoppingScroll = false;
if (app.value !== viewport || pending.value || (queue ? readingQueue.value !== queue : currentUrl.value !== url)) return;
}
if (queue) {
returnToReaderStart(chapter, index);
return;
}
focusNavigation();
if (readerStartsLater.value) {
returnToReaderStart();
return;
}
if (!reducedMotion.value) {
returningToTop.value = true;
scheduleReturnToTopEnd();
}
viewport.scrollTo({
top: 0,
behavior: reducedMotion.value ? "instant" : "smooth"
});
}
return {
scrollY,
showBackToTop,
returningToTop,
backToTopTitle,
backToTop
};
}
function useReaderBuffer({ navigation, viewActive }) {
const images = createReaderImages(navigation, viewActive);
return {
...images,
...createReaderPreload(navigation, images.readerFrames)
};
}
function createReaderImages(navigation, viewActive) {
const { readerSections } = navigation;
return useReaderImages(computed(() => readerSections.value.flatMap(({ chapter, url, page }) => readerPageFrames(page, url).map((frame) => ({
...frame,
chapter
})))), navigation.readerRevision, navigation.loadReaderImage, viewActive);
}
function createReaderPreload(navigation, readerFrames) {
const { readerChapter, readerIndex, readerSections, readingQueue, hasPrevious, hasMore, loadPreviousFailure, loadMoreFailure, canLoadNextPage } = navigation;
const readerPagesAhead = 5;
const readerPagesBehind = 3;
const activeFramePosition = computed(() => readerFrames.value.findIndex((frame) => frame.chapter === readerChapter.value && frame.index === readerIndex.value));
const scrollDirection = shallowRef();
watch(navigation.readerRevision, () => scrollDirection.value = void 0, { flush: "post" });
watch([readerChapter, readerIndex], ([chapter, index], [previousChapter, previousIndex]) => {
if (chapter !== previousChapter) scrollDirection.value = chapter < previousChapter ? "previous" : "next";
else if (index !== previousIndex) scrollDirection.value = index < previousIndex ? "previous" : "next";
});
return {
activeFramePosition,
readerPagesAhead,
readerPagesBehind,
readerBuffer: computed(() => {
const first = readerFrames.value[0];
const last = readerFrames.value.at(-1);
const chapters = readingQueue.value;
const head = [];
const tail = [];
if (first && hasPrevious.value && !loadPreviousFailure.value) {
const chapter = first.index > 1 ? first.chapter : first.chapter - 1;
const index = first.index > 1 ? first.index - 1 : chapters?.[chapter]?.pages || 0;
head.push(`${chapter}:${index}`);
if (index > 1) head.unshift(`${chapter}:${index - 1}`);
}
if (last && hasMore.value && !loadMoreFailure.value) {
if (canLoadNextPage.value) {
const total = readerSections.value.at(-1)?.page.total;
tail.push(`${last.chapter}:${last.index + 1}`);
if (!total || last.index + 2 <= total) tail.push(`${last.chapter}:${last.index + 2}`);
} else tail.push(`${last.chapter + 1}:1`);
}
return {
head,
tail
};
}),
scrollDirection
};
}
function useReaderPreloadDirection(navigation, { readerPreview }, { activeFramePosition, readerFrames, readerPagesAhead, readerPagesBehind, scrollDirection }) {
const { activeReader: reader, pending, loadingMore, loadingPrevious, hasPrevious, loadPreviousFailure, loadMoreFailure, canLoadNextPage, canLoadNextChapter } = navigation;
return {
readerPreloadDirection: computed(() => {
const position = activeFramePosition.value;
if (position < 0 || readerPreview.value || pending.value || loadingMore.value || loadingPrevious.value) return;
const ahead = readerFrames.value.length - 1 - position;
const needPrevious = position < readerPagesBehind && hasPrevious.value && !loadPreviousFailure.value;
const needNext = !loadMoreFailure.value && (canLoadNextPage.value && ahead < readerPagesAhead || canLoadNextChapter.value && ahead === 0);
if (needPrevious && needNext && scrollDirection.value) return scrollDirection.value;
if (needPrevious && (!needNext || position < ahead)) return "previous";
return needNext ? "next" : void 0;
}),
canPreloadAtBottom: computed(() => !reader.value || canLoadNextChapter.value && !readerPreview.value && !loadingPrevious.value)
};
}
function useReader(options) {
const { app, navigation } = options;
const controls = useReaderControls(options);
const scroll = useReaderScroll(options, controls);
const buffer = useReaderBuffer(options);
const preloads = useReaderPreloadDirection(navigation, controls, buffer);
onMounted(async () => {
await nextTick();
if (document.activeElement === document.body) app.value?.focus({ preventScroll: true });
});
return {
...controls,
...scroll,
...buffer,
...preloads
};
}
var BetterEhApp_default = defineComponent({
__name: "BetterEhApp",
props: {
adapter: {},
initialPage: {},
initialUrl: {},
nativeLink: { type: Function },
viewActive: {},
openingNative: {},
readingLibraryRepository: {}
},
setup(__props) {
const props = __props;
const scroll = useTemplateRef("scroll");
const app = computed(() => scroll.value?.viewport ?? null);
const header = useTemplateRef("header");
const navigation = useNavigation(props.adapter, props.initialPage, props.initialUrl, app, computed(() => scroll.value?.content ?? null), props.viewActive);
const { page, navigate, pending, refreshing, returningToStart, seekingReader, activeReader: reader, loadingMore, loadMoreFailure, loadingPrevious, loadPreviousFailure, hasMore, reachedEnd, hasPrevious, loadMore, retryLoadMore } = navigation;
const { theme, desktopNavigation } = storeToRefs(usePreferencesStore());
const readingLibrary = useReadingLibraryStore();
readingLibrary.initialize(props.readingLibraryRepository);
const { loadingLibrary, bookmarksBusy } = storeToRefs(readingLibrary);
const { readLibrary } = readingLibrary;
const motion = usePreferredReducedMotion();
const reducedMotion = computed(() => motion.value === "reduce");
const compactSearch = computed(() => !desktopNavigation.value);
const busy = computed(() => Boolean(pending.value || loadingMore.value || loadingPrevious.value));
const galleryLibrary = useGalleryLibrary({
adapter: props.adapter,
navigation,
app,
desktop: desktopNavigation,
reducedMotion
});
const { readingGallery, readerTotal, savedForLater, toggleReadLater } = galleryLibrary;
const gallerySearch = useGallerySearch(props.adapter, navigation, header, compactSearch, reducedMotion, activate);
const { searchOpen, closeSearch } = gallerySearch;
const readerUi = useReader({
app,
navigation,
viewActive: props.viewActive,
desktopNavigation,
reducedMotion,
focusNavigation: () => header.value?.focusNavigation()
});
const { chromeVisible, readerProgressDragging, readerPreloadDirection, canPreloadAtBottom, showBackToTop, returningToTop, backToTopTitle, backToTop } = readerUi;
watch([chromeVisible, () => props.viewActive?.value], ([visible, active]) => {
if (!visible || active === false) closeSearch(false);
});
provide(galleryViewportKey, {
viewport: app,
restoration: navigation.galleryRestoration,
returningToTop
});
const { refreshBlocked, pullRefreshBlocked, virtual, scrollItemKeys, contentAttrs } = useAppScroll(navigation, readerUi, desktopNavigation, busy);
const routing = useAppRouting(navigation, readerUi, galleryLibrary, props.adapter, () => props.nativeLink, readLibrary, activate);
const { home, navigationItems, refreshFromTop } = routing;
const libraryRefreshing = computed(() => page.value.kind === "library" && loadingLibrary.value);
function activate(event, url) {
if (!url || !isPrimaryClick(event)) return;
event.preventDefault();
navigate(url, "push", void 0, void 0, event.currentTarget);
}
return (_ctx, _cache) => {
return openBlock(), createElementBlock(Fragment, null, [createVNode(InfiniteScroll_default, {
ref_key: "scroll",
ref: scroll,
class: normalizeClass(["eh-app", {
"has-site-nav": !unref(reader) && unref(navigationItems).length,
"is-reader": unref(reader)
}]),
"content-attrs": unref(contentAttrs),
"item-keys": unref(scrollItemKeys),
"content-as": "main",
virtual: unref(virtual),
refresh: unref(refreshFromTop),
"refresh-blocked": unref(searchOpen) || unref(pullRefreshBlocked) || libraryRefreshing.value,
refreshing: unref(refreshing) || libraryRefreshing.value,
"load-more": unref(loadMore),
"retry-load-more": unref(retryLoadMore),
"loading-blocked": Boolean(unref(pending) || unref(loadingPrevious) || unref(readerProgressDragging)),
loading: unref(loadingMore),
"has-more": unref(hasMore),
error: unref(loadMoreFailure),
"previous-error": unref(loadPreviousFailure),
"reached-end": unref(reachedEnd),
"has-previous": unref(hasPrevious) || unref(loadingPrevious),
active: __props.viewActive?.value !== false,
"show-load-hint": unref(page).kind !== "reader",
"preload-distance": unref(reader) ? 180 : 760,
"load-interval": 900,
"can-preload": unref(canPreloadAtBottom),
"preload-direction": unref(readerPreloadDirection),
"end-indicator-class": { "reader-end-reveal": Boolean(unref(reader) && unref(chromeVisible)) },
"data-theme": unref(theme),
lang: "zh-CN",
role: "region",
"aria-label": "Better EH",
tabindex: "0"
}, {
header: withCtx(() => [createVNode(AppNavigation_default, {
ref_key: "header",
ref: header,
routing: unref(routing),
"search-panel": unref(gallerySearch),
"complete-tags": __props.adapter.completeTags,
visible: unref(chromeVisible),
desktop: unref(desktopNavigation),
"is-reader": Boolean(unref(reader)),
"reader-title": unref(reader)?.title,
busy: busy.value,
"refresh-blocked": unref(refreshBlocked) || libraryRefreshing.value,
refreshing: unref(refreshing) || libraryRefreshing.value,
"opening-native": __props.openingNative?.value,
"can-bookmark": Boolean(unref(readingGallery)),
"saved-for-later": unref(savedForLater),
"bookmarks-busy": unref(bookmarksBusy),
onNavigate: activate,
onToggleBookmark: _cache[0] || (_cache[0] = ($event) => unref(toggleReadLater)($event.currentTarget, unref(readingGallery)))
}, null, 8, [
"routing",
"search-panel",
"complete-tags",
"visible",
"desktop",
"is-reader",
"reader-title",
"busy",
"refresh-blocked",
"refreshing",
"opening-native",
"can-bookmark",
"saved-for-later",
"bookmarks-busy"
])]),
[unref(virtual) ? "virtual" : "default"]: withCtx(({ viewport, preserveEdgePosition }) => [createVNode(AppPageContent_default, {
navigation: unref(navigation),
routing: unref(routing),
library: unref(galleryLibrary),
"reader-ui": unref(readerUi),
"gallery-search": unref(gallerySearch),
viewport,
"preserve-edge-position": preserveEdgePosition,
"native-link": __props.nativeLink,
active: __props.viewActive?.value !== false,
desktop: unref(desktopNavigation),
busy: busy.value,
onNavigate: activate
}, null, 8, [
"navigation",
"routing",
"library",
"reader-ui",
"gallery-search",
"viewport",
"preserve-edge-position",
"native-link",
"active",
"desktop",
"busy"
])]),
"after-content": withCtx(() => [(unref(page).kind === "catalog" || unref(page).kind === "gallery") && (unref(page).previous || unref(page).next) ? (openBlock(), createBlock(PageLinks_default, {
key: 0,
previous: unref(page).previous,
next: unref(page).next,
onNavigate: activate
}, null, 8, ["previous", "next"])) : createCommentVNode("", true)]),
after: withCtx(({ pullOffset }) => [
createVNode(AppReaderControls_default, {
navigation: unref(navigation),
"reader-ui": unref(readerUi),
"reader-total": unref(readerTotal),
desktop: unref(desktopNavigation),
active: __props.viewActive?.value !== false
}, null, 8, [
"navigation",
"reader-ui",
"reader-total",
"desktop",
"active"
]),
createVNode(AppGalleryOverlays_default, {
"gallery-search": unref(gallerySearch),
library: unref(galleryLibrary),
home: unref(home),
onNavigate: activate
}, null, 8, [
"gallery-search",
"library",
"home"
]),
__props.openingNative?.value || unref(pending) ? (openBlock(), createElementBlock("div", {
key: 0,
class: normalizeClass(!__props.openingNative?.value && unref(refreshing) && pullOffset > 0 ? "sr-only" : "loading-note"),
role: "status"
}, [createVNode(LoadingSpinner_default, {
size: 17,
"aria-hidden": "true"
}), createTextVNode(" " + toDisplayString(__props.openingNative?.value ? "正在打开原站…" : unref(seekingReader) ? "正在跳页" : unref(returningToStart) ? "正在返回第 1 页" : unref(refreshing) ? "正在刷新" : "正在加载"), 1)], 2)) : createCommentVNode("", true)
]),
_: 2
}, 1032, [
"class",
"content-attrs",
"item-keys",
"virtual",
"refresh",
"refresh-blocked",
"refreshing",
"load-more",
"retry-load-more",
"loading-blocked",
"loading",
"has-more",
"error",
"previous-error",
"reached-end",
"has-previous",
"active",
"show-load-hint",
"preload-distance",
"can-preload",
"preload-direction",
"end-indicator-class",
"data-theme"
]), createVNode(BackToTopButton_default, {
visible: unref(showBackToTop),
class: normalizeClass({ "is-reader": unref(reader) }),
"data-theme": unref(theme),
lang: "zh-CN",
title: unref(backToTopTitle),
disabled: Boolean(unref(pending)),
onClick: unref(backToTop)
}, null, 8, [
"visible",
"class",
"data-theme",
"title",
"disabled",
"onClick"
])], 64);
};
}
});
var storageKey = "better-eh-reading-library-v1";
var historyLimit = 500;
function isRecord(value) {
return typeof value === "object" && value !== null && !Array.isArray(value);
}
function isUrl(value, origin) {
if (typeof value !== "string") return false;
try {
const url = new URL(value);
return /^https?:$/.test(url.protocol) && (!origin || url.origin === origin);
} catch {
return false;
}
}
function isDate(value) {
return typeof value === "number" && Number.isFinite(new Date(value).getTime());
}
function isGallery(value, origin) {
return isRecord(value) && isUrl(value.href, origin) && typeof value.title === "string" && typeof value.pages === "number" && Number.isSafeInteger(value.pages) && value.pages >= 0 && (value.cover === void 0 || isUrl(value.cover));
}
function isProgress(value, origin) {
return isRecord(value) && isUrl(value.href, origin) && typeof value.index === "number" && Number.isSafeInteger(value.index) && value.index > 0;
}
function mergeGallery(gallery, previous) {
return {
...gallery,
cover: gallery.cover ?? previous?.cover,
pages: gallery.pages || previous?.pages || 0
};
}
function applyChange(library, change) {
switch (change.type) {
case "visit": {
const href = change.gallery.href;
const old = library.history.find((entry) => entry.gallery.href === href);
const recent = {
gallery: mergeGallery(change.gallery, old?.gallery),
visitedAt: Date.now(),
progress: change.progress ?? old?.progress
};
return {
...library,
history: [recent, ...library.history.filter((entry) => entry.gallery.href !== href)].slice(0, historyLimit)
};
}
case "save-for-later":
case "save-many-for-later": {
const galleries = change.type === "save-for-later" ? [change.gallery] : change.galleries;
const savedHrefs = new Set(library.later.map((entry) => entry.gallery.href));
const historyByHref = new Map(library.history.map((entry) => [entry.gallery.href, entry.gallery]));
const savedAt = Date.now();
const added = [];
for (const gallery of galleries) {
if (savedHrefs.has(gallery.href)) continue;
savedHrefs.add(gallery.href);
added.push({
gallery: mergeGallery(gallery, historyByHref.get(gallery.href)),
savedAt
});
}
return added.length ? {
...library,
later: added.concat(library.later)
} : library;
}
case "remove-from-later":
case "remove-from-history":
case "remove-many": {
const section = change.type === "remove-many" ? change.section : change.type === "remove-from-history" ? "history" : "later";
const hrefs = new Set(change.type === "remove-many" ? change.hrefs : [change.href]);
return {
...library,
[section]: library[section].filter((entry) => !hrefs.has(entry.gallery.href))
};
}
}
}
function createBrowserReadingLibrary(browser) {
function read() {
const stored = browser.localStorage.getItem(storageKey);
if (stored === null) return {
history: [],
later: []
};
const value = JSON.parse(stored);
if (!isRecord(value) || !Array.isArray(value.history) || !Array.isArray(value.later)) throw new Error("阅读记录格式有误。");
const origin = browser.location.origin;
return {
history: value.history.filter((entry) => isRecord(entry) && isGallery(entry.gallery, origin) && isDate(entry.visitedAt) && (entry.progress === void 0 || isProgress(entry.progress, origin))),
later: value.later.filter((entry) => isRecord(entry) && isGallery(entry.gallery, origin) && isDate(entry.savedAt))
};
}
return {
async read() {
return read();
},
async apply(change) {
function mutate() {
const library = read();
const updated = applyChange(library, change);
if (updated !== library) browser.localStorage.setItem(storageKey, JSON.stringify(updated));
return updated;
}
return browser.navigator.locks ? browser.navigator.locks.request(storageKey, mutate) : mutate();
},
subscribe(onChange) {
const listener = (event) => {
if (event.key === storageKey || event.key === null) onChange();
};
browser.addEventListener("storage", listener);
return () => browser.removeEventListener("storage", listener);
}
};
}
var style_default = "/*! tailwindcss v4.3.5 | MIT License | https://tailwindcss.com */\n@layer properties {\n @supports (((-webkit-hyphens: none)) and (not (margin-trim: block))) or ((-moz-orient: inline) and (not (color: rgb(from red r g b)))) {\n *, :before, :after, ::backdrop {\n --tw-rotate-x: initial;\n --tw-rotate-y: initial;\n --tw-rotate-z: initial;\n --tw-skew-x: initial;\n --tw-skew-y: initial;\n --tw-divide-y-reverse: 0;\n --tw-border-style: solid;\n --tw-leading: initial;\n --tw-font-weight: initial;\n --tw-ordinal: initial;\n --tw-slashed-zero: initial;\n --tw-numeric-figure: initial;\n --tw-numeric-spacing: initial;\n --tw-numeric-fraction: initial;\n --tw-shadow: 0 0 #0000;\n --tw-shadow-color: initial;\n --tw-shadow-alpha: 100%;\n --tw-inset-shadow: 0 0 #0000;\n --tw-inset-shadow-color: initial;\n --tw-inset-shadow-alpha: 100%;\n --tw-ring-color: initial;\n --tw-ring-shadow: 0 0 #0000;\n --tw-inset-ring-color: initial;\n --tw-inset-ring-shadow: 0 0 #0000;\n --tw-ring-inset: initial;\n --tw-ring-offset-width: 0px;\n --tw-ring-offset-color: #fff;\n --tw-ring-offset-shadow: 0 0 #0000;\n --tw-blur: initial;\n --tw-brightness: initial;\n --tw-contrast: initial;\n --tw-grayscale: initial;\n --tw-hue-rotate: initial;\n --tw-invert: initial;\n --tw-opacity: initial;\n --tw-saturate: initial;\n --tw-sepia: initial;\n --tw-drop-shadow: initial;\n --tw-drop-shadow-color: initial;\n --tw-drop-shadow-alpha: 100%;\n --tw-drop-shadow-size: initial;\n --tw-ease: initial;\n }\n }\n}\n\n@layer theme {\n :root, :host {\n --font-sans: -apple-system, BlinkMacSystemFont, \"Segoe UI\", Roboto, \"Helvetica Neue\",\n \"Noto Sans\", Arial, sans-serif, \"Apple Color Emoji\", \"Segoe UI Emoji\",\n \"Segoe UI Symbol\", \"Noto Color Emoji\";\n --font-mono: ui-monospace, SFMono-Regular, Menlo, Monaco, Consolas, \"Liberation Mono\",\n \"Courier New\", monospace;\n --color-white: #fff;\n --spacing: .25rem;\n --text-xs: .75rem;\n --text-xs--line-height: calc(1 / .75);\n --text-xl: 1.25rem;\n --text-xl--line-height: calc(1.75 / 1.25);\n --font-weight-normal: 400;\n --font-weight-medium: 500;\n --font-weight-semibold: 600;\n --font-weight-bold: 700;\n --leading-relaxed: 1.625;\n --radius-sm: .25rem;\n --radius-md: .375rem;\n --radius-lg: .5rem;\n --radius-xl: .75rem;\n --radius-2xl: 1rem;\n --ease-out: cubic-bezier(0, 0, .2, 1);\n --default-font-family: var(--font-sans);\n --default-mono-font-family: var(--font-mono);\n --animate-loading-spinner: loading-dash 1.5s ease-in-out infinite;\n }\n}\n\n@layer base {\n *, :after, :before, ::backdrop {\n box-sizing: border-box;\n border: 0 solid;\n margin: 0;\n padding: 0;\n }\n\n ::file-selector-button {\n box-sizing: border-box;\n border: 0 solid;\n margin: 0;\n padding: 0;\n }\n\n html, :host {\n -webkit-text-size-adjust: 100%;\n tab-size: 4;\n line-height: 1.5;\n font-family: var(--default-font-family, -apple-system, BlinkMacSystemFont, \"Segoe UI\", Roboto, \"Helvetica Neue\", \"Noto Sans\", Arial, sans-serif, \"Apple Color Emoji\", \"Segoe UI Emoji\", \"Segoe UI Symbol\", \"Noto Color Emoji\");\n font-feature-settings: var(--default-font-feature-settings, normal);\n font-variation-settings: var(--default-font-variation-settings, normal);\n -webkit-tap-highlight-color: transparent;\n }\n\n hr {\n height: 0;\n color: inherit;\n border-top-width: 1px;\n }\n\n abbr:where([title]) {\n -webkit-text-decoration: underline dotted;\n text-decoration: underline dotted;\n }\n\n h1, h2, h3, h4, h5, h6 {\n font-size: inherit;\n font-weight: inherit;\n }\n\n a {\n color: inherit;\n -webkit-text-decoration: inherit;\n -webkit-text-decoration: inherit;\n -webkit-text-decoration: inherit;\n text-decoration: inherit;\n }\n\n b, strong {\n font-weight: bolder;\n }\n\n code, kbd, samp, pre {\n font-family: var(--default-mono-font-family, ui-monospace, SFMono-Regular, Menlo, Monaco, Consolas, \"Liberation Mono\", \"Courier New\", monospace);\n font-feature-settings: var(--default-mono-font-feature-settings, normal);\n font-variation-settings: var(--default-mono-font-variation-settings, normal);\n font-size: 1em;\n }\n\n small {\n font-size: 80%;\n }\n\n sub, sup {\n vertical-align: baseline;\n font-size: 75%;\n line-height: 0;\n position: relative;\n }\n\n sub {\n bottom: -.25em;\n }\n\n sup {\n top: -.5em;\n }\n\n table {\n text-indent: 0;\n border-color: inherit;\n border-collapse: collapse;\n }\n\n :-moz-focusring:where(:not(iframe)) {\n outline: auto;\n }\n\n progress {\n vertical-align: baseline;\n }\n\n summary {\n display: list-item;\n }\n\n ol, ul, menu {\n list-style: none;\n }\n\n img, svg, video, canvas, audio, iframe, embed, object {\n vertical-align: middle;\n display: block;\n }\n\n img, video {\n max-width: 100%;\n height: auto;\n }\n\n button, input, select, optgroup, textarea {\n font: inherit;\n font-feature-settings: inherit;\n font-variation-settings: inherit;\n letter-spacing: inherit;\n color: inherit;\n opacity: 1;\n background-color: #0000;\n border-radius: 0;\n }\n\n ::file-selector-button {\n font: inherit;\n font-feature-settings: inherit;\n font-variation-settings: inherit;\n letter-spacing: inherit;\n color: inherit;\n opacity: 1;\n background-color: #0000;\n border-radius: 0;\n }\n\n :where(select:is([multiple], [size])) optgroup {\n font-weight: bolder;\n }\n\n :where(select:is([multiple], [size])) optgroup option {\n padding-inline-start: 20px;\n }\n\n ::file-selector-button {\n margin-inline-end: 4px;\n }\n\n ::placeholder {\n opacity: 1;\n }\n\n @supports (not ((-webkit-appearance: -apple-pay-button))) or (contain-intrinsic-size: 1px) {\n ::placeholder {\n color: currentColor;\n }\n\n @supports (color: color-mix(in lab, red, red)) {\n ::placeholder {\n color: color-mix(in oklab, currentcolor 50%, transparent);\n }\n }\n }\n\n textarea {\n resize: vertical;\n }\n\n ::-webkit-search-decoration {\n -webkit-appearance: none;\n }\n\n ::-webkit-date-and-time-value {\n min-height: 1lh;\n text-align: inherit;\n }\n\n ::-webkit-datetime-edit {\n display: inline-flex;\n }\n\n ::-webkit-datetime-edit-fields-wrapper {\n padding: 0;\n }\n\n ::-webkit-datetime-edit {\n padding-block: 0;\n }\n\n ::-webkit-datetime-edit-year-field {\n padding-block: 0;\n }\n\n ::-webkit-datetime-edit-month-field {\n padding-block: 0;\n }\n\n ::-webkit-datetime-edit-day-field {\n padding-block: 0;\n }\n\n ::-webkit-datetime-edit-hour-field {\n padding-block: 0;\n }\n\n ::-webkit-datetime-edit-minute-field {\n padding-block: 0;\n }\n\n ::-webkit-datetime-edit-second-field {\n padding-block: 0;\n }\n\n ::-webkit-datetime-edit-millisecond-field {\n padding-block: 0;\n }\n\n ::-webkit-datetime-edit-meridiem-field {\n padding-block: 0;\n }\n\n ::-webkit-calendar-picker-indicator {\n line-height: 1;\n }\n\n :-moz-ui-invalid {\n box-shadow: none;\n }\n\n button, input:where([type=\"button\"], [type=\"reset\"], [type=\"submit\"]) {\n appearance: button;\n }\n\n ::file-selector-button {\n appearance: button;\n }\n\n ::-webkit-inner-spin-button {\n height: auto;\n }\n\n ::-webkit-outer-spin-button {\n height: auto;\n }\n\n [hidden]:where(:not([hidden=\"until-found\"])) {\n display: none !important;\n }\n}\n\n@layer components;\n\n@layer utilities {\n .pointer-events-none {\n pointer-events: none;\n }\n\n .invisible {\n visibility: hidden;\n }\n\n .visible {\n visibility: visible;\n }\n\n .sr-only {\n clip-path: inset(50%);\n white-space: nowrap;\n border-width: 0;\n width: 1px;\n height: 1px;\n margin: -1px;\n padding: 0;\n position: absolute;\n overflow: hidden;\n }\n\n .absolute {\n position: absolute;\n }\n\n .relative {\n position: relative;\n }\n\n .sticky {\n position: sticky;\n }\n\n .inset-0 {\n inset: 0;\n }\n\n .inset-x-0 {\n inset-inline: 0;\n }\n\n .top-0 {\n top: 0;\n }\n\n .top-2\\.5 {\n top: calc(var(--spacing) * 2.5);\n }\n\n .right-2\\.5 {\n right: calc(var(--spacing) * 2.5);\n }\n\n .bottom-2\\.5 {\n bottom: calc(var(--spacing) * 2.5);\n }\n\n .bottom-\\[calc\\(100\\%\\+16px\\)\\] {\n bottom: calc(100% + 16px);\n }\n\n .z-1 {\n z-index: 1;\n }\n\n .z-3 {\n z-index: 3;\n }\n\n .col-span-full {\n grid-column: 1 / -1;\n }\n\n .container {\n width: 100%;\n }\n\n @media (min-width: 40rem) {\n .container {\n max-width: 40rem;\n }\n }\n\n @media (min-width: 48rem) {\n .container {\n max-width: 48rem;\n }\n }\n\n @media (min-width: 64rem) {\n .container {\n max-width: 64rem;\n }\n }\n\n @media (min-width: 80rem) {\n .container {\n max-width: 80rem;\n }\n }\n\n @media (min-width: 96rem) {\n .container {\n max-width: 96rem;\n }\n }\n\n .m-0 {\n margin: 0;\n }\n\n .mx-4 {\n margin-inline: calc(var(--spacing) * 4);\n }\n\n .mx-auto {\n margin-inline: auto;\n }\n\n .my-3 {\n margin-block: calc(var(--spacing) * 3);\n }\n\n .my-5 {\n margin-block: calc(var(--spacing) * 5);\n }\n\n .mt-1\\.5 {\n margin-top: calc(var(--spacing) * 1.5);\n }\n\n .mt-4 {\n margin-top: calc(var(--spacing) * 4);\n }\n\n .mt-8 {\n margin-top: calc(var(--spacing) * 8);\n }\n\n .mt-\\[18px\\] {\n margin-top: 18px;\n }\n\n .mb-2 {\n margin-bottom: calc(var(--spacing) * 2);\n }\n\n .ml-auto {\n margin-left: auto;\n }\n\n .block {\n display: block;\n }\n\n .flex {\n display: flex;\n }\n\n .grid {\n display: grid;\n }\n\n .hidden {\n display: none;\n }\n\n .inline-block {\n display: inline-block;\n }\n\n .aspect-\\[4\\/5\\] {\n aspect-ratio: 4 / 5;\n }\n\n .size-8 {\n width: calc(var(--spacing) * 8);\n height: calc(var(--spacing) * 8);\n }\n\n .size-full {\n width: 100%;\n height: 100%;\n }\n\n .h-\\[min\\(132px\\,28dvh\\)\\] {\n height: min(132px, 28dvh);\n }\n\n .h-full {\n height: 100%;\n }\n\n .max-h-full {\n max-height: 100%;\n }\n\n .min-h-9 {\n min-height: calc(var(--spacing) * 9);\n }\n\n .min-h-11 {\n min-height: calc(var(--spacing) * 11);\n }\n\n .min-h-\\[94px\\] {\n min-height: 94px;\n }\n\n .w-\\[108px\\] {\n width: 108px;\n }\n\n .w-\\[min\\(100\\%\\,1000px\\)\\] {\n width: min(100%, 1000px);\n }\n\n .w-full {\n width: 100%;\n }\n\n .max-w-full {\n max-width: 100%;\n }\n\n .min-w-0 {\n min-width: 0;\n }\n\n .min-w-\\[58px\\] {\n min-width: 58px;\n }\n\n .flex-1 {\n flex: 1;\n }\n\n .shrink-0 {\n flex-shrink: 0;\n }\n\n .grow {\n flex-grow: 1;\n }\n\n .basis-full {\n flex-basis: 100%;\n }\n\n .origin-top-left {\n transform-origin: 0 0;\n }\n\n .transform {\n transform: var(--tw-rotate-x, ) var(--tw-rotate-y, ) var(--tw-rotate-z, ) var(--tw-skew-x, ) var(--tw-skew-y, );\n }\n\n .touch-manipulation {\n touch-action: manipulation;\n }\n\n .resize {\n resize: both;\n }\n\n .list-none {\n list-style-type: none;\n }\n\n .flex-wrap {\n flex-wrap: wrap;\n }\n\n .place-items-center {\n place-items: center;\n }\n\n .items-baseline {\n align-items: baseline;\n }\n\n .items-center {\n align-items: center;\n }\n\n .items-end {\n align-items: flex-end;\n }\n\n .justify-between {\n justify-content: space-between;\n }\n\n .justify-end {\n justify-content: flex-end;\n }\n\n .gap-1 {\n gap: var(--spacing);\n }\n\n .gap-2 {\n gap: calc(var(--spacing) * 2);\n }\n\n .gap-2\\.5 {\n gap: calc(var(--spacing) * 2.5);\n }\n\n .gap-3 {\n gap: calc(var(--spacing) * 3);\n }\n\n .gap-4 {\n gap: calc(var(--spacing) * 4);\n }\n\n .gap-x-2 {\n column-gap: calc(var(--spacing) * 2);\n }\n\n .gap-x-2\\.5 {\n column-gap: calc(var(--spacing) * 2.5);\n }\n\n .gap-y-0\\.5 {\n row-gap: calc(var(--spacing) * .5);\n }\n\n .gap-y-1 {\n row-gap: var(--spacing);\n }\n\n :where(.divide-y > :not(:last-child)) {\n --tw-divide-y-reverse: 0;\n border-bottom-style: var(--tw-border-style);\n border-top-style: var(--tw-border-style);\n border-top-width: calc(1px * var(--tw-divide-y-reverse));\n border-bottom-width: calc(1px * calc(1 - var(--tw-divide-y-reverse)));\n }\n\n :where(.divide-solid > :not(:last-child)) {\n --tw-border-style: solid;\n border-style: solid;\n }\n\n :where(.divide-line > :not(:last-child)) {\n border-color: var(--line);\n }\n\n .self-start {\n align-self: flex-start;\n }\n\n .truncate {\n text-overflow: ellipsis;\n white-space: nowrap;\n overflow: hidden;\n }\n\n .overflow-hidden {\n overflow: hidden;\n }\n\n .overflow-visible {\n overflow: visible;\n }\n\n .rounded-\\[9px\\] {\n border-radius: 9px;\n }\n\n .rounded-full {\n border-radius: 2147483647px;\n }\n\n .rounded-md {\n border-radius: var(--radius-md);\n }\n\n .rounded-ui {\n border-radius: var(--radius);\n }\n\n .rounded-xl {\n border-radius: var(--radius-xl);\n }\n\n .border {\n border-style: var(--tw-border-style);\n border-width: 1px;\n }\n\n .border-b {\n border-bottom-style: var(--tw-border-style);\n border-bottom-width: 1px;\n }\n\n .border-solid {\n --tw-border-style: solid;\n border-style: solid;\n }\n\n .border-\\(--line\\), .border-line {\n border-color: var(--line);\n }\n\n .bg-\\[\\#101010d9\\] {\n background-color: #101010d9;\n }\n\n .bg-panel {\n background-color: var(--panel);\n }\n\n .bg-surface {\n background-color: var(--surface);\n }\n\n .bg-transparent {\n background-color: #0000;\n }\n\n .bg-no-repeat {\n background-repeat: no-repeat;\n }\n\n .object-contain {\n object-fit: contain;\n }\n\n .p-0 {\n padding: 0;\n }\n\n .p-1 {\n padding: var(--spacing);\n }\n\n .p-5 {\n padding: calc(var(--spacing) * 5);\n }\n\n .px-2 {\n padding-inline: calc(var(--spacing) * 2);\n }\n\n .px-2\\.5 {\n padding-inline: calc(var(--spacing) * 2.5);\n }\n\n .px-3 {\n padding-inline: calc(var(--spacing) * 3);\n }\n\n .px-4 {\n padding-inline: calc(var(--spacing) * 4);\n }\n\n .px-5 {\n padding-inline: calc(var(--spacing) * 5);\n }\n\n .px-\\[7px\\] {\n padding-inline: 7px;\n }\n\n .py-1 {\n padding-block: var(--spacing);\n }\n\n .py-1\\.5 {\n padding-block: calc(var(--spacing) * 1.5);\n }\n\n .py-3 {\n padding-block: calc(var(--spacing) * 3);\n }\n\n .py-4 {\n padding-block: calc(var(--spacing) * 4);\n }\n\n .py-5 {\n padding-block: calc(var(--spacing) * 5);\n }\n\n .py-\\[3px\\] {\n padding-block: 3px;\n }\n\n .pt-3 {\n padding-top: calc(var(--spacing) * 3);\n }\n\n .pt-5 {\n padding-top: calc(var(--spacing) * 5);\n }\n\n .pt-6 {\n padding-top: calc(var(--spacing) * 6);\n }\n\n .pt-\\[max\\(6px\\,env\\(safe-area-inset-top\\)\\)\\] {\n padding-top: max(6px, env(safe-area-inset-top));\n }\n\n .pr-\\[max\\(16px\\,env\\(safe-area-inset-right\\)\\)\\] {\n padding-right: max(16px, env(safe-area-inset-right));\n }\n\n .pb-3 {\n padding-bottom: calc(var(--spacing) * 3);\n }\n\n .pb-4 {\n padding-bottom: calc(var(--spacing) * 4);\n }\n\n .pb-\\[38px\\] {\n padding-bottom: 38px;\n }\n\n .pb-\\[env\\(safe-area-inset-bottom\\)\\] {\n padding-bottom: env(safe-area-inset-bottom);\n }\n\n .pb-\\[max\\(16px\\,env\\(safe-area-inset-bottom\\)\\)\\] {\n padding-bottom: max(16px, env(safe-area-inset-bottom));\n }\n\n .pl-\\[max\\(12px\\,env\\(safe-area-inset-left\\)\\)\\] {\n padding-left: max(12px, env(safe-area-inset-left));\n }\n\n .pl-\\[max\\(16px\\,env\\(safe-area-inset-left\\)\\)\\] {\n padding-left: max(16px, env(safe-area-inset-left));\n }\n\n .text-center {\n text-align: center;\n }\n\n .text-left {\n text-align: left;\n }\n\n .align-middle {\n vertical-align: middle;\n }\n\n .text-xl {\n font-size: var(--text-xl);\n line-height: var(--tw-leading, var(--text-xl--line-height));\n }\n\n .text-xs {\n font-size: var(--text-xs);\n line-height: var(--tw-leading, var(--text-xs--line-height));\n }\n\n .text-\\[11px\\] {\n font-size: 11px;\n }\n\n .text-\\[12px\\] {\n font-size: 12px;\n }\n\n .text-\\[13px\\] {\n font-size: 13px;\n }\n\n .text-\\[16px\\] {\n font-size: 16px;\n }\n\n .text-\\[17px\\] {\n font-size: 17px;\n }\n\n .text-\\[18px\\] {\n font-size: 18px;\n }\n\n .leading-relaxed {\n --tw-leading: var(--leading-relaxed);\n line-height: var(--leading-relaxed);\n }\n\n .font-\\[550\\] {\n --tw-font-weight: 550;\n font-weight: 550;\n }\n\n .font-\\[650\\] {\n --tw-font-weight: 650;\n font-weight: 650;\n }\n\n .font-bold {\n --tw-font-weight: var(--font-weight-bold);\n font-weight: var(--font-weight-bold);\n }\n\n .font-medium {\n --tw-font-weight: var(--font-weight-medium);\n font-weight: var(--font-weight-medium);\n }\n\n .font-normal {\n --tw-font-weight: var(--font-weight-normal);\n font-weight: var(--font-weight-normal);\n }\n\n .font-semibold {\n --tw-font-weight: var(--font-weight-semibold);\n font-weight: var(--font-weight-semibold);\n }\n\n .wrap-anywhere {\n overflow-wrap: anywhere;\n }\n\n .whitespace-nowrap {\n white-space: nowrap;\n }\n\n .whitespace-pre-wrap {\n white-space: pre-wrap;\n }\n\n .text-\\[0\\] {\n color: 0;\n }\n\n .text-ink {\n color: var(--ink);\n }\n\n .text-muted {\n color: var(--muted);\n }\n\n .text-white {\n color: var(--color-white);\n }\n\n .tabular-nums {\n --tw-numeric-spacing: tabular-nums;\n font-variant-numeric: var(--tw-ordinal, ) var(--tw-slashed-zero, ) var(--tw-numeric-figure, ) var(--tw-numeric-spacing, ) var(--tw-numeric-fraction, );\n }\n\n .opacity-70 {\n opacity: .7;\n }\n\n .opacity-\\[\\.72\\] {\n opacity: .72;\n }\n\n .shadow-lg {\n --tw-shadow: 0 10px 15px -3px var(--tw-shadow-color, #0000001a), 0 4px 6px -4px var(--tw-shadow-color, #0000001a);\n box-shadow: var(--tw-inset-shadow), var(--tw-inset-ring-shadow), var(--tw-ring-offset-shadow), var(--tw-ring-shadow), var(--tw-shadow);\n }\n\n .shadow-sm {\n --tw-shadow: 0 1px 3px 0 var(--tw-shadow-color, #0000001a), 0 1px 2px -1px var(--tw-shadow-color, #0000001a);\n box-shadow: var(--tw-inset-shadow), var(--tw-inset-ring-shadow), var(--tw-ring-offset-shadow), var(--tw-ring-shadow), var(--tw-shadow);\n }\n\n .blur {\n --tw-blur: blur(8px);\n filter: var(--tw-blur, ) var(--tw-brightness, ) var(--tw-contrast, ) var(--tw-grayscale, ) var(--tw-hue-rotate, ) var(--tw-invert, ) var(--tw-saturate, ) var(--tw-sepia, ) var(--tw-drop-shadow, );\n }\n\n .filter {\n filter: var(--tw-blur, ) var(--tw-brightness, ) var(--tw-contrast, ) var(--tw-grayscale, ) var(--tw-hue-rotate, ) var(--tw-invert, ) var(--tw-saturate, ) var(--tw-sepia, ) var(--tw-drop-shadow, );\n }\n\n .transition-none {\n transition-property: none;\n }\n\n .ease-out {\n --tw-ease: var(--ease-out);\n transition-timing-function: var(--ease-out);\n }\n\n .\\[border-bottom\\:1px_solid_var\\(--line\\)\\] {\n border-bottom: 1px solid var(--line);\n }\n\n .\\[border\\:1px_solid_var\\(--line\\)\\] {\n border: 1px solid var(--line);\n }\n\n .\\[stroke-dasharray\\:28_126\\] {\n stroke-dasharray: 28 126;\n }\n\n @media (hover: hover) {\n .hover\\:bg-panel:hover {\n background-color: var(--panel);\n }\n }\n\n .active\\:\\[transform\\:scale\\(\\.97\\)\\]:active {\n transform: scale(.97);\n }\n\n @media (prefers-reduced-motion: no-preference) {\n .motion-safe\\:animate-loading-spinner {\n animation: var(--animate-loading-spinner);\n }\n }\n\n @media not all and (min-width: 960px) {\n .max-\\[960px\\]\\:min-h-\\[44px\\]\\! {\n min-height: 44px !important;\n }\n }\n}\n\n[data-theme] {\n --paper: #fafafa;\n --surface: #fff;\n --panel: #f0f0f0;\n --ink: #161616;\n --muted: #626262;\n --line: #e1e1e1;\n --link-text: #1859b6;\n --danger-bg: #b42318;\n --danger-text: #fff;\n --danger-hover: #912018;\n --danger-subtle-bg: #fef3f2;\n --danger-subtle-text: #b42318;\n --danger-subtle-hover: #fee4e2;\n --radius: 12px;\n color-scheme: light;\n}\n\n[data-theme=\"dark\"] {\n --paper: #101010;\n --surface: #171717;\n --panel: #212121;\n --ink: #f4f4f4;\n --muted: #a6a6a6;\n --line: #303030;\n --link-text: #8cbaff;\n --danger-bg: #f97066;\n --danger-text: #280b08;\n --danger-hover: #fda29b;\n --danger-subtle-bg: #3b1518;\n --danger-subtle-text: #fda29b;\n --danger-subtle-hover: #511c20;\n color-scheme: dark;\n}\n\n:host {\n all: initial;\n touch-action: manipulation;\n display: block;\n position: fixed;\n inset: 0;\n}\n\n:host([hidden]) {\n display: none;\n}\n\n*, :before, :after {\n box-sizing: border-box;\n}\n\nh1, h2, p, dl, dd {\n margin: 0;\n}\n\na, button {\n color: inherit;\n}\n\na {\n text-decoration: none;\n}\n\nbutton, input {\n font: inherit;\n}\n\nbutton {\n cursor: pointer;\n background: none;\n border: 0;\n padding: 0;\n}\n\nbutton:disabled {\n cursor: default;\n opacity: .35;\n}\n\nimg, svg {\n display: block;\n}\n\n:focus-visible {\n outline: 2px solid var(--ink);\n outline-offset: 3px;\n}\n\n.infinite-scroll {\n overscroll-behavior-y: none;\n -webkit-overflow-scrolling: touch;\n overflow: hidden auto;\n}\n\n.infinite-scroll.is-zoomed {\n overscroll-behavior-y: auto;\n}\n\n.eh-app {\n background-color: var(--paper);\n height: 100dvh;\n color: var(--ink);\n text-align: left;\n overflow-anchor: auto;\n font: 400 14px / 1.5 Inter, system-ui, sans-serif;\n}\n\n.eh-app:not(.is-reader) {\n scrollbar-gutter: stable;\n}\n\n.stop-scroll {\n overflow-y: hidden;\n}\n\n.shell {\n --shell-width: 1440px;\n width: min(var(--shell-width), 100%);\n padding-inline: max(38px, env(safe-area-inset-left)) max(38px, env(safe-area-inset-right));\n margin-inline: auto;\n}\n\n@media (prefers-reduced-motion: reduce) {\n *, :before, :after {\n scroll-behavior: auto !important;\n transition-duration: .01ms !important;\n animation-duration: .01ms !important;\n }\n}\n\n.masthead {\n z-index: 10;\n border-bottom: 1px solid var(--line);\n background-color: var(--surface);\n padding-top: env(safe-area-inset-top);\n position: sticky;\n top: 0;\n}\n\n.pull-refresh-chip svg {\n transition: transform .16s;\n}\n\n.pull-refresh-ready {\n transform: rotate(180deg);\n}\n\n.header-inner {\n grid-template-columns: minmax(0, 1fr) clamp(440px, 54%, 720px) minmax(0, 1fr);\n align-items: center;\n gap: 18px;\n min-height: 70px;\n display: grid;\n}\n\n.header-with-back {\n width: auto;\n margin-inline: 0 max(0px, calc((100% - var(--shell-width)) / 2));\n padding-inline-start: max(12px, env(safe-area-inset-left));\n}\n\n.header-inner.header-compact-search {\n grid-template-columns: minmax(0, 1fr) auto;\n position: relative;\n}\n\n.header-inner.header-compact-search:has( > .search-form) {\n row-gap: calc(var(--spacing) * 2);\n padding-block: calc(var(--spacing) * 2);\n}\n\n.header-actions {\n --header-tools-gap: 8px;\n justify-self: flex-end;\n}\n\n.header-tools {\n gap: var(--header-tools-gap, 4px);\n}\n\n.header-brand {\n align-items: center;\n gap: 4px;\n display: flex;\n}\n\n.brand {\n letter-spacing: -.04em;\n white-space: nowrap;\n align-items: center;\n gap: 10px;\n width: fit-content;\n font-size: 18px;\n display: inline-flex;\n}\n\n.brand-symbol {\n background-color: var(--ink);\n width: 35px;\n height: 35px;\n color: var(--surface);\n border-radius: 9px;\n place-items: center;\n display: grid;\n}\n\n.search-box {\n border-radius: var(--radius-xl);\n background-color: var(--panel);\n min-width: 0;\n padding: 0 5px 0 14px;\n position: relative;\n}\n\n.header-inner > button.search-form {\n background-color: var(--panel);\n padding-inline: calc(var(--spacing) * 3.5);\n}\n\n@media (hover: hover) {\n .header-inner > button.search-form:hover {\n background-color: var(--line);\n }\n}\n\n.header-inner > button.search-form:active {\n background-color: var(--line);\n}\n\n.header-compact-search > button.search-form {\n grid-column: 1 / -1;\n grid-row-start: 2;\n}\n\n.search-panel-desktop {\n overscroll-behavior: contain;\n border-style: var(--tw-border-style);\n border-width: 0;\n border-bottom-style: var(--tw-border-style);\n border-bottom-width: 1px;\n border-color: var(--line);\n background-color: var(--surface);\n width: 100%;\n max-width: none;\n color: var(--ink);\n --tw-shadow: 0 10px 15px -3px var(--tw-shadow-color, #0000001a), 0 4px 6px -4px var(--tw-shadow-color, #0000001a);\n box-shadow: var(--tw-inset-shadow), var(--tw-inset-ring-shadow), var(--tw-ring-offset-shadow), var(--tw-ring-shadow), var(--tw-shadow);\n padding: 0;\n padding-top: env(safe-area-inset-top);\n inset-inline: 0;\n max-height: min(540px, 76dvh);\n margin: 0;\n position: fixed;\n top: 0;\n overflow-y: auto;\n}\n\n.search-panel-desktop::backdrop {\n background: #0006;\n}\n\n.search-panel-desktop .search-editor-row {\n z-index: 1;\n background-color: var(--surface);\n min-height: 70px;\n position: sticky;\n top: 0;\n}\n\n.search-panel-mobile {\n border-style: var(--tw-border-style);\n background-color: var(--surface);\n width: 100%;\n max-width: none;\n height: 100%;\n max-height: none;\n color: var(--ink);\n border-width: 0;\n margin: 0;\n padding: 0;\n position: fixed;\n inset: 0;\n overflow: hidden;\n}\n\n.search-panel-mobile::backdrop {\n background: var(--surface);\n}\n\n.search-panel-mobile-content {\n overscroll-behavior: contain;\n top: var(--search-top, 0px);\n height: var(--search-height, 100%);\n max-height: calc(100% - var(--search-top, 0px));\n position: relative;\n overflow-y: auto;\n}\n\n.search-box:has( > input:focus) {\n outline: 1px solid var(--muted);\n}\n\n.search-box input {\n width: 100%;\n min-width: 0;\n color: var(--ink);\n background: none;\n border: 0;\n outline: 0;\n font-size: 16px;\n}\n\n.search-box input::placeholder {\n color: var(--muted);\n}\n\n.search-box input::-webkit-search-cancel-button {\n display: none;\n}\n\n.search-box > .search-clear {\n color: var(--muted);\n}\n\n.search-box > .icon-button {\n border-radius: var(--radius-xl);\n touch-action: manipulation;\n background-clip: content-box;\n padding: 4px;\n}\n\n.search-box > .icon-button:hover:not(:disabled), .search-box > .icon-button:active {\n background-color: var(--line);\n}\n\n.search-box > .icon-button:focus-visible {\n outline-offset: -3px;\n}\n\n.tag-suggestions {\n margin-top: calc(var(--spacing) * 3);\n list-style-type: none;\n}\n\n.tag-suggestions [role=\"option\"] {\n min-height: calc(var(--spacing) * 12);\n cursor: pointer;\n overflow-wrap: anywhere;\n border-radius: 7px;\n align-content: center;\n padding: 5px 10px;\n display: grid;\n}\n\n.tag-suggestions [role=\"option\"][aria-selected=\"true\"], .tag-suggestions [role=\"option\"]:active {\n background-color: var(--panel);\n}\n\n@media (hover: hover) {\n .tag-suggestions [role=\"option\"]:hover {\n background-color: var(--panel);\n }\n}\n\n.tag-suggestions small, .tag-suggestion-status {\n color: var(--muted);\n font-size: 12px;\n}\n\n.tag-suggestion-status {\n justify-content: space-between;\n align-items: center;\n gap: 8px;\n min-height: 44px;\n padding: 6px 10px;\n display: flex;\n}\n\n.tag-suggestion-status button {\n min-height: 36px;\n}\n\n.search-condition {\n border-style: var(--tw-border-style);\n border-width: 1px;\n border-color: var(--line);\n background-color: var(--panel);\n padding-inline: calc(var(--spacing) * 3);\n}\n\n.search-condition:active {\n background-color: var(--line);\n}\n\n.icon-button {\n border-radius: 9px;\n flex: none;\n place-items: center;\n width: 44px;\n height: 44px;\n display: inline-grid;\n}\n\n.icon-button:hover:not(:disabled), .header-back:active {\n background-color: var(--panel);\n}\n\n.header-back {\n touch-action: manipulation;\n}\n\n.site-sidebar {\n display: none;\n}\n\n.site-nav-toggle {\n -webkit-tap-highlight-color: transparent;\n}\n\n.site-nav-toggle:active {\n background-color: var(--panel);\n}\n\n.site-nav-link {\n touch-action: manipulation;\n border-radius: var(--radius-lg);\n --tw-font-weight: 550;\n min-height: 44px;\n color: var(--muted);\n border: 1px solid #0000;\n grid-template-columns: 18px minmax(0, 1fr) auto;\n align-items: center;\n gap: 12px;\n padding: 8px 12px;\n font-size: 14px;\n font-weight: 550;\n transition: background-color .13s, color .13s;\n display: grid;\n}\n\n.site-nav-link:hover, .site-nav-link:active, .site-nav-link[aria-current=\"page\"] {\n background-color: var(--panel);\n color: var(--ink);\n}\n\n.site-nav-link[aria-current=\"page\"] {\n border-color: var(--line);\n --tw-font-weight: 650;\n font-weight: 650;\n}\n\n.site-menu {\n overscroll-behavior: contain;\n width: 100%;\n max-width: none;\n height: 100%;\n max-height: none;\n color: var(--ink);\n background: none;\n border: 0;\n margin: 0;\n padding: 0;\n position: fixed;\n inset: 0;\n overflow: hidden;\n}\n\n.site-menu::backdrop {\n background: #0007;\n}\n\n.site-menu-panel {\n overscroll-behavior-y: contain;\n width: min(300px, 100% - 48px);\n height: 100%;\n padding: max(12px, env(safe-area-inset-top)) 12px max(16px, env(safe-area-inset-bottom)) max(12px, env(safe-area-inset-left));\n background-color: var(--surface);\n border-inline-end: 1px solid var(--line);\n overflow-y: auto;\n}\n\n.site-menu[open] .site-menu-panel {\n animation: .22s cubic-bezier(.22, 1, .36, 1) site-menu-enter;\n}\n\n.site-menu-header {\n justify-content: space-between;\n align-items: center;\n padding: 2px 0 8px 12px;\n display: flex;\n}\n\n@keyframes site-menu-enter {\n from {\n transform: translateX(-100%);\n }\n\n to {\n transform: translateX(0);\n }\n}\n\n@media (min-width: 960px) {\n .has-site-nav {\n grid-template-rows: auto 1fr;\n grid-template-columns: 216px minmax(0, 1fr);\n display: grid;\n }\n\n .has-site-nav .masthead {\n grid-column: 1 / -1;\n }\n\n .site-sidebar {\n top: calc(71px + env(safe-area-inset-top));\n height: calc(100vh - 71px - env(safe-area-inset-top));\n height: calc(100dvh - 71px - env(safe-area-inset-top));\n overscroll-behavior-y: contain;\n padding: 22px 12px max(16px, env(safe-area-inset-bottom)) max(12px, env(safe-area-inset-left));\n border-inline-end: 1px solid var(--line);\n background-color: var(--surface);\n align-self: flex-start;\n display: block;\n position: sticky;\n overflow-y: auto;\n }\n\n .site-nav-toggle {\n display: none;\n }\n}\n\n.progress-bar {\n background-color: var(--line);\n width: 100%;\n height: 2px;\n position: absolute;\n bottom: -1px;\n left: 0;\n overflow: hidden;\n}\n\n.progress-bar:after {\n content: \"\";\n background-color: var(--ink);\n width: 27%;\n height: 2px;\n animation: 1.2s ease-in-out infinite loading;\n display: block;\n}\n\n@keyframes loading {\n from {\n transform: translateX(-100%);\n }\n\n to {\n transform: translateX(370%);\n }\n}\n\n.is-reader .masthead {\n position: fixed;\n inset-inline: 0;\n}\n\n.is-reader .header-brand {\n min-width: 0;\n}\n\n.is-reader .header-brand .brand {\n flex: none;\n display: inline-flex;\n}\n\n.is-reader .brand-symbol {\n display: grid;\n}\n\n.reader-header-title {\n --tw-font-weight: 650;\n text-overflow: ellipsis;\n white-space: nowrap;\n min-width: 0;\n margin-inline-start: 8px;\n font-size: 16px;\n font-weight: 650;\n overflow: hidden;\n}\n\n@media (min-width: 651px) and (max-width: 959px) {\n .is-reader .header-inner:not(.header-compact-search) {\n grid-template-columns: minmax(0, 1fr) minmax(144px, 30%) auto;\n gap: 12px;\n }\n}\n\n@media (min-width: 960px) {\n .header-inner > button.search-form {\n min-height: calc(var(--spacing) * 12);\n font-size: 15px;\n }\n\n .reader-header {\n grid-template-columns: minmax(0, 1fr) clamp(160px, 100% - 800px, 440px) minmax(0, 1fr);\n gap: 16px;\n width: 100%;\n margin-inline: 0;\n padding-inline: 0;\n }\n\n .reader-header .header-brand {\n padding-inline-start: max(12px, env(safe-area-inset-left));\n }\n\n .reader-header .header-actions {\n margin-inline-end: max(78px, calc(env(safe-area-inset-right) + 62px));\n }\n\n .reader-header-actions {\n border-inline-end: 1px solid var(--line);\n padding-inline-end: 12px;\n }\n\n .reader-header-actions .reading-actions {\n flex-wrap: nowrap;\n }\n\n .is-reader .site-sidebar {\n inset: var(--masthead-height, 71px) auto 0 0;\n z-index: 9;\n width: 216px;\n height: auto;\n position: fixed;\n }\n}\n\n.icon-button.reader-menu-toggle {\n top: max(12px, calc(env(safe-area-inset-top) + 12px));\n right: max(14px, env(safe-area-inset-right));\n z-index: 12;\n border: 1px solid var(--line);\n background-color: var(--surface);\n touch-action: manipulation;\n position: fixed;\n box-shadow: 0 4px 18px #0002;\n}\n\n@media (max-width: 650px) {\n .header-inner {\n grid-template-columns: 1fr auto;\n gap: 5px;\n padding-block: 8px;\n }\n\n .header-inner > .search-form {\n grid-area: 2 / 1 / 3 / 3;\n }\n}\n\n@media (max-width: 420px) {\n .header-with-back .header-brand {\n gap: 2px;\n }\n\n .header-with-back .header-actions {\n --header-tools-gap: 4px;\n gap: 4px;\n }\n\n .header-with-back .brand {\n border-radius: 9px;\n flex: none;\n justify-content: center;\n width: 44px;\n height: 44px;\n }\n\n .header-with-back .brand strong {\n display: none;\n }\n\n .header-with-back .brand-symbol {\n display: grid;\n }\n\n .eh-app:not(.is-reader) .header-compact-search :is(.header-brand, .header-tools) > :is(.icon-button, .brand) {\n width: clamp(32px, 11.875vw, 44px);\n }\n}\n\n@media (max-width: 480px) {\n .is-reader .header-inner.header-compact-search {\n grid-template-columns: minmax(0, 1fr);\n }\n\n .is-reader .header-actions {\n display: none;\n }\n\n .reader-header-title {\n margin-inline-start: 4px;\n font-size: 14px;\n }\n}\n\n@media (min-width: 421px) and (max-width: 480px) {\n .header-compact-search .brand strong {\n display: none;\n }\n}\n\n@media (max-width: 360px) {\n .brand-symbol {\n display: none;\n }\n}\n\n.tag-color-trigger {\n border: 1px solid var(--line);\n touch-action: manipulation;\n border-radius: var(--radius-lg);\n background-color: var(--paper);\n text-align: left;\n min-width: 164px;\n min-height: 38px;\n color: var(--ink);\n align-items: center;\n gap: 8px;\n padding: 6px 10px;\n display: inline-flex;\n}\n\n.tag-color-trigger > span:nth-child(2) {\n --tw-numeric-spacing: tabular-nums;\n font-variant-numeric: var(--tw-ordinal, ) var(--tw-slashed-zero, ) var(--tw-numeric-figure, ) var(--tw-numeric-spacing, ) var(--tw-numeric-fraction, );\n flex: 1;\n}\n\n.tag-color-dialog {\n border: 1px solid var(--line);\n overscroll-behavior: contain;\n border-radius: var(--radius-2xl);\n background-color: var(--surface);\n width: min(440px, 100vw - 32px);\n max-width: none;\n max-height: calc(100dvh - 32px);\n color: var(--ink);\n margin: auto;\n padding: 0;\n position: fixed;\n inset: 0;\n box-shadow: 0 20px 60px #0004;\n}\n\n.tag-color-dialog::backdrop {\n background: #0007;\n}\n\n.tag-color-panel {\n grid-template-rows: auto minmax(0, 1fr) auto;\n max-height: min(620px, 100dvh - 32px);\n display: grid;\n}\n\n.tag-color-header, .tag-color-footer {\n justify-content: space-between;\n align-items: center;\n gap: 12px;\n padding: 12px 16px;\n display: flex;\n}\n\n.tag-color-header {\n border-bottom: 1px solid var(--line);\n}\n\n.tag-color-header h3 {\n --tw-font-weight: 650;\n font-size: 17px;\n font-weight: 650;\n}\n\n.tag-color-content {\n overscroll-behavior: contain;\n padding: 16px;\n overflow-y: auto;\n}\n\n.tag-color-presets {\n border: 0;\n min-width: 0;\n margin: 0 0 16px;\n padding: 0;\n}\n\n.tag-color-presets legend {\n color: var(--muted);\n margin-bottom: 8px;\n padding: 0;\n font-size: 13px;\n}\n\n.tag-color-swatches {\n grid-template-columns: repeat(6, minmax(0, 1fr));\n gap: 8px;\n display: grid;\n}\n\n.tag-color-swatch {\n touch-action: manipulation;\n min-height: 44px;\n display: block;\n position: relative;\n}\n\n.tag-color-swatch input {\n z-index: 1;\n cursor: pointer;\n opacity: 0;\n width: 100%;\n height: 100%;\n margin: 0;\n position: absolute;\n inset: 0;\n}\n\n.tag-color-chip {\n border-radius: var(--radius-lg);\n place-items: center;\n min-height: 44px;\n transition: filter .12s;\n display: grid;\n box-shadow: inset 0 0 0 1px #0002;\n}\n\n.tag-color-swatch:active .tag-color-chip {\n filter: brightness(.86);\n}\n\n.tag-color-swatch input:focus-visible + .tag-color-chip {\n outline: 2px solid var(--ink);\n outline-offset: 2px;\n}\n\n.tag-color-check {\n color: #fff;\n opacity: 0;\n background: #161616;\n border: 1px solid #fff;\n border-radius: 50%;\n place-items: center;\n width: 22px;\n height: 22px;\n transition: opacity .12s;\n display: grid;\n}\n\n.tag-color-swatch input:checked + .tag-color-chip .tag-color-check {\n opacity: 1;\n}\n\n.tag-color-custom {\n align-items: flex-end;\n gap: 8px;\n margin-top: 18px;\n display: flex;\n}\n\n.tag-color-hex {\n min-width: 0;\n color: var(--muted);\n flex: 1;\n gap: 4px;\n font-size: 12px;\n display: grid;\n}\n\n.tag-color-hex input {\n border: 1px solid var(--line);\n border-radius: var(--radius-lg);\n background-color: var(--paper);\n min-width: 0;\n min-height: 38px;\n color: var(--ink);\n --tw-numeric-spacing: tabular-nums;\n font-variant-numeric: var(--tw-ordinal, ) var(--tw-slashed-zero, ) var(--tw-numeric-figure, ) var(--tw-numeric-spacing, ) var(--tw-numeric-fraction, );\n padding: 6px 10px;\n font-size: 16px;\n}\n\n.tag-color-hex input[aria-invalid=\"true\"] {\n border-color: #c00;\n}\n\n.tag-color-native {\n border: 1px solid var(--line);\n touch-action: manipulation;\n background-color: var(--paper);\n border-radius: 10px;\n grid-template-columns: 48px minmax(0, 1fr) auto;\n align-items: center;\n gap: 12px;\n min-height: 64px;\n padding: 8px 12px 8px 8px;\n display: grid;\n position: relative;\n}\n\n.tag-color-native:hover {\n border-color: var(--muted);\n}\n\n.tag-color-preview {\n border: 1px solid var(--line);\n border-radius: var(--radius-md);\n background-color: var(--panel);\n width: 48px;\n height: 46px;\n}\n\n.tag-color-native input {\n cursor: pointer;\n opacity: 0;\n width: 100%;\n height: 100%;\n position: absolute;\n inset: 0;\n}\n\n.tag-color-native:has(input:focus-visible) {\n outline: 2px solid var(--ink);\n outline-offset: 3px;\n}\n\n.tag-color-error {\n color: #c00;\n margin-top: 8px;\n font-size: 12px;\n}\n\n.tag-color-footer {\n border-top: 1px solid var(--line);\n justify-content: flex-end;\n}\n\n@media (prefers-reduced-motion: no-preference) {\n .tag-color-dialog[open] {\n animation: .18s cubic-bezier(.22, 1, .36, 1) color-panel-enter;\n }\n}\n\n@keyframes color-panel-enter {\n from {\n opacity: 0;\n transform: translateY(16px);\n }\n}\n\n@media (max-width: 650px) {\n .tag-color-header, .tag-color-content, .tag-color-footer {\n padding-inline: max(14px, env(safe-area-inset-left)) max(14px, env(safe-area-inset-right));\n }\n\n .tag-color-dialog {\n border-inline: 0;\n border-bottom: 0;\n border-radius: 16px 16px 0 0;\n width: 100%;\n max-height: none;\n margin: auto 0 0;\n }\n\n .tag-color-panel {\n max-height: min(640px, 88dvh);\n }\n\n .tag-color-footer {\n padding-bottom: max(12px, env(safe-area-inset-bottom));\n }\n\n .tag-color-custom .pill, .tag-color-footer .pill {\n min-height: 44px;\n }\n}\n\n@media (max-width: 420px) {\n .tag-color-swatches {\n grid-template-columns: repeat(4, minmax(0, 1fr));\n }\n}\n\n.tags-heading h1 {\n letter-spacing: -.04em;\n font-size: clamp(30px, 4vw, 48px);\n line-height: 1.15;\n}\n\n.pill.tags-primary {\n border-color: var(--ink);\n background-color: var(--ink);\n color: var(--surface);\n}\n\n.tags-tools, .tags-bulk {\n margin-block: 16px;\n}\n\n.tags-filter {\n border: 1px solid var(--line);\n border-radius: var(--radius-lg);\n background-color: var(--surface);\n min-height: 42px;\n color: var(--muted);\n align-items: center;\n gap: 8px;\n padding-inline: 12px;\n display: flex;\n}\n\n.tags-filter input {\n width: min(210px, 58vw);\n color: var(--ink);\n background: none;\n font-size: 16px;\n}\n\n.tags-editor {\n border: 1px solid var(--line);\n border-radius: var(--radius);\n background-color: var(--surface);\n gap: 12px;\n margin-block: 16px;\n padding: 16px;\n display: grid;\n}\n\n.tags-editor h2 {\n --tw-font-weight: 650;\n font-size: 18px;\n font-weight: 650;\n}\n\n.tags-fields {\n flex-wrap: wrap;\n align-items: flex-end;\n gap: 12px;\n min-width: 0;\n display: flex;\n}\n\n.tags-field {\n max-width: 100%;\n color: var(--muted);\n gap: 4px;\n font-size: 13px;\n display: grid;\n}\n\n.tags-field input, .tags-select {\n border: 1px solid var(--line);\n border-radius: var(--radius-lg);\n background-color: var(--paper);\n max-width: 100%;\n min-height: 38px;\n color: var(--ink);\n padding: 6px 10px;\n font-size: 16px;\n}\n\n.tags-field input[type=\"number\"] {\n width: 86px;\n}\n\n.tags-check {\n cursor: pointer;\n align-items: center;\n gap: 6px;\n min-height: 38px;\n display: inline-flex;\n}\n\n.tags-row-header > .tags-check {\n justify-content: center;\n}\n\n.tags-check input {\n width: 16px;\n height: 16px;\n accent-color: var(--ink);\n}\n\n.tags-list {\n border-top: 1px solid var(--line);\n margin: 0;\n padding: 0;\n list-style-type: none;\n}\n\n.tags-row-header {\n grid-template-columns: 38px minmax(0, 1fr) auto;\n align-items: center;\n gap: 8px;\n min-height: 59px;\n padding-block: 6px;\n display: grid;\n}\n\n.tag-color {\n border: 1px solid var(--line);\n border-radius: 50%;\n flex: none;\n width: 10px;\n height: 10px;\n}\n\n.tag-state, .tag-weight {\n color: var(--muted);\n font-size: 12px;\n}\n\n.tag-state {\n border-radius: var(--radius-sm);\n background-color: var(--panel);\n padding: 1px 5px;\n}\n\n.tags-row-header > .pill {\n grid-column: 3;\n}\n\n.tags-row-header > .pill[aria-expanded=\"true\"] {\n background-color: var(--panel);\n}\n\n.tags-row-editor {\n grid-template-rows: 1fr;\n display: grid;\n}\n\n.tags-row-editor > div {\n min-width: 0;\n min-height: 0;\n}\n\n.tags-row-editor .tags-editor {\n margin: 0 0 8px;\n padding: 12px;\n}\n\n.tags-row-editor .notice {\n margin: 0;\n}\n\n.tag-edit-status {\n color: var(--muted);\n margin: 0 0 8px;\n font-size: 13px;\n}\n\n@media (prefers-reduced-motion: no-preference) {\n .tag-expand-enter-active, .tag-expand-leave-active {\n transition: grid-template-rows .18s cubic-bezier(.22, 1, .36, 1), opacity .12s;\n overflow: clip;\n }\n\n .tag-expand-enter-from, .tag-expand-leave-to {\n opacity: 0;\n grid-template-rows: 0fr;\n }\n}\n\n@media (pointer: coarse) {\n .tags-row-header > .pill, .tags-row-editor .pill, .tags-row-editor .tags-check, .tags-row-editor .tags-field input, .tags-row-editor .tag-color-trigger {\n min-height: 44px;\n }\n\n .tags-row-header > .pill {\n min-width: 44px;\n }\n}\n\n.main {\n padding-top: clamp(30px, 4.3vw, 58px);\n padding-bottom: max(40px, env(safe-area-inset-bottom));\n}\n\n.reader-main {\n min-height: 100%;\n padding-top: max(12px, env(safe-area-inset-top));\n padding-bottom: calc(var(--reader-progress-bottom) + var(--reader-progress-height) + 16px);\n}\n\n.is-reader {\n --reader-progress-bottom: max(12px, calc(env(safe-area-inset-bottom) + 6px));\n --reader-progress-height: 58px;\n}\n\n@media (max-width: 650px) {\n .shell {\n padding-inline: max(14px, env(safe-area-inset-left)) max(14px, env(safe-area-inset-right));\n }\n}\n\n.catalog-title h1 {\n letter-spacing: -.065em;\n font-size: clamp(40px, 5vw, 66px);\n font-weight: 750;\n line-height: 1.09;\n}\n\n.catalog-controls {\n flex-wrap: wrap;\n justify-content: flex-end;\n align-items: center;\n gap: 8px;\n margin-inline-start: auto;\n display: flex;\n}\n\n.query {\n overflow-wrap: anywhere;\n color: var(--muted);\n margin-top: 7px;\n}\n\n.count, .muted {\n color: var(--muted);\n}\n\n.count {\n white-space: nowrap;\n font-size: 13px;\n}\n\n.view-switch {\n border: 1px solid var(--line);\n border-radius: 11px;\n padding: 3px;\n}\n\n.view-switch .icon-button {\n width: 35px;\n height: 33px;\n color: var(--muted);\n border-radius: 7px;\n}\n\n.view-switch [aria-pressed=\"true\"] {\n background-color: var(--panel);\n color: var(--ink);\n}\n\n.filter-switch {\n flex-shrink: 0;\n}\n\n.filter-switch-track {\n --thumb-size: 12px;\n --thumb-inset: 2px;\n background-color: var(--panel);\n border: 1px solid var(--line);\n border-radius: 2147483647px;\n width: 32px;\n height: 18px;\n position: relative;\n}\n\n.filter-switch-track:before {\n content: \"\";\n background-color: var(--muted);\n width: var(--thumb-size);\n height: var(--thumb-size);\n border-radius: 2147483647px;\n margin-block: auto;\n transition: inset-inline-start .12s;\n position: absolute;\n inset-block: 0;\n inset-inline-start: var(--thumb-inset);\n}\n\n.filter-switch[aria-checked=\"true\"] .filter-switch-track {\n background-color: var(--ink);\n border-color: var(--ink);\n}\n\n.filter-switch[aria-checked=\"true\"] .filter-switch-track:before {\n background-color: var(--surface);\n inset-inline-start: calc(100% - var(--thumb-size) - var(--thumb-inset));\n}\n\n@media (pointer: coarse) {\n .view-switch .icon-button {\n width: 44px;\n height: 44px;\n }\n}\n\n.filters {\n scrollbar-width: thin;\n overscroll-behavior-x: contain;\n -webkit-overflow-scrolling: touch;\n gap: 7px;\n margin-block: 24px 22px;\n padding: 4px 3px 8px;\n overflow-x: auto;\n}\n\n.pill {\n white-space: nowrap;\n border: 1px solid var(--line);\n background-color: var(--surface);\n border-radius: 9px;\n justify-content: center;\n align-items: center;\n gap: 6px;\n min-height: 36px;\n padding: 6px 13px;\n font-size: 13px;\n display: inline-flex;\n}\n\n.pill:hover:not(:disabled) {\n border-color: var(--muted);\n}\n\n.pill[aria-current=\"true\"], .pill.action-button-primary {\n border-color: var(--ink);\n background-color: var(--ink);\n color: var(--surface);\n}\n\n.pill.action-button {\n touch-action: manipulation;\n --tw-font-weight: var(--font-weight-semibold);\n min-height: 44px;\n font-weight: var(--font-weight-semibold);\n padding: 8px 12px;\n}\n\n.pill.action-button-primary:hover {\n opacity: .85;\n}\n\n.eh-app:has(.gallery-rows) {\n overflow-anchor: none;\n}\n\n.gallery-rows {\n --gallery-fixed-columns: 0;\n position: relative;\n}\n\n.catalog-grid {\n --gallery-min-column-width: 192px;\n --gallery-gap: 18px;\n margin-top: 18px;\n}\n\n.gallery-row {\n grid-template-columns: repeat(var(--gallery-columns), minmax(0, 1fr));\n column-gap: var(--gallery-gap);\n inset-inline: 0;\n display: grid;\n position: absolute;\n top: 0;\n}\n\n.catalog-empty, .library-notice {\n margin-top: 18px;\n}\n\n.library-notice {\n flex-wrap: wrap;\n justify-content: space-between;\n align-items: center;\n gap: 8px;\n display: flex;\n}\n\n.gallery-selection-bar {\n top: calc(var(--masthead-height, 71px) + 8px);\n z-index: 3;\n border: 1px solid var(--line);\n border-radius: var(--radius);\n background-color: var(--surface);\n flex-wrap: wrap;\n align-items: center;\n gap: 8px;\n margin-top: 12px;\n padding: 8px;\n display: flex;\n position: sticky;\n}\n\n.gallery-selection-bar > :is(.action-button-primary, .action-button-danger-subtle) {\n margin-inline-start: auto;\n}\n\n.gallery-card {\n border: 1px solid var(--line);\n border-radius: var(--radius);\n background-color: var(--surface);\n flex-direction: column;\n min-width: 0;\n transition: border-color .18s;\n display: flex;\n position: relative;\n}\n\n.card-link {\n border-radius: inherit;\n flex-direction: column;\n flex: 1;\n display: flex;\n overflow: hidden;\n}\n\n.gallery-card:hover {\n border-color: var(--muted);\n}\n\n.gallery-card.is-selected {\n border-color: var(--ink);\n box-shadow: 0 0 0 1px var(--ink);\n}\n\n.card-selector {\n z-index: 1;\n border-radius: inherit;\n cursor: pointer;\n padding: 5px;\n position: absolute;\n inset: 0;\n}\n\n.card-selector-box {\n border: 1px solid var(--line);\n border-radius: var(--radius-lg);\n background-color: var(--surface);\n place-items: center;\n width: 44px;\n height: 44px;\n display: grid;\n}\n\n.card-selector input {\n width: 20px;\n height: 20px;\n accent-color: var(--ink);\n cursor: inherit;\n}\n\n.card-quick-action {\n pointer-events: none;\n position: absolute;\n inset-block-start: 5px;\n inset-inline-end: 5px;\n}\n\n.card-quick-action > button {\n border-radius: var(--radius-lg);\n color: #fff;\n touch-action: manipulation;\n -webkit-tap-highlight-color: transparent;\n background: #161616e8;\n place-items: center;\n width: 44px;\n height: 44px;\n display: grid;\n position: relative;\n}\n\n.card-quick-action > button:focus-visible {\n outline-offset: -4px;\n outline: 2px solid #fff;\n}\n\n.card-quick-action > button:active {\n background: #333;\n}\n\n.card-quick-action > button[aria-disabled=\"true\"] {\n cursor: wait;\n}\n\n.card-quick-action > .card-more {\n pointer-events: auto;\n}\n\n.card-hover-action {\n opacity: 0;\n transition: opacity .14s ease-out;\n}\n\n.gallery-card:hover .card-hover-action, .gallery-card:focus-within .card-hover-action {\n pointer-events: auto;\n opacity: 1;\n transition-duration: 0s;\n}\n\n.card-hover-action-label {\n background: inherit;\n pointer-events: none;\n --tw-font-weight: 650;\n white-space: nowrap;\n opacity: 0;\n border-radius: 8px 0 0 8px;\n align-items: center;\n padding-inline: 10px 0;\n font-size: 13px;\n font-weight: 650;\n transition: opacity .13s ease-out;\n display: flex;\n position: absolute;\n inset: 0 100% 0 auto;\n}\n\n.card-hover-action:hover, .card-hover-action:focus-visible {\n border-start-start-radius: 0;\n border-end-start-radius: 0;\n}\n\n.card-hover-action:hover .card-hover-action-label, .card-hover-action:focus-visible .card-hover-action-label {\n pointer-events: auto;\n opacity: 1;\n}\n\n.list-view .gallery-card:has( > .card-quick-action) .card-meta {\n padding-inline-end: 54px;\n}\n\n.poster {\n aspect-ratio: 4 / 5;\n background-color: var(--panel);\n place-items: center;\n display: grid;\n position: relative;\n overflow: hidden;\n}\n\n.poster img {\n object-fit: cover;\n width: 100%;\n height: 100%;\n transition: transform .25s;\n}\n\n@media (hover: hover) {\n .card-link:hover .poster img {\n transform: scale(1.035);\n }\n}\n\n.page-count {\n color: #fff;\n --tw-numeric-spacing: tabular-nums;\n font-variant-numeric: var(--tw-ordinal, ) var(--tw-slashed-zero, ) var(--tw-numeric-figure, ) var(--tw-numeric-spacing, ) var(--tw-numeric-fraction, );\n background: #101010d9;\n border-radius: 5px;\n padding: 3px 6px;\n font-size: 11px;\n position: absolute;\n bottom: 8px;\n right: 8px;\n}\n\n.card-meta {\n min-width: 0;\n padding: 11px 12px 13px;\n}\n\n.category, .posted {\n color: var(--muted);\n font-size: 11px;\n}\n\n.card-meta .card-title {\n -webkit-line-clamp: 2;\n --tw-font-weight: 650;\n overflow-wrap: anywhere;\n -webkit-box-orient: vertical;\n min-height: 2.6em;\n margin: 4px 0;\n font-size: 14px;\n font-weight: 650;\n line-height: 1.3;\n display: -webkit-box;\n overflow: hidden;\n}\n\n.posted {\n --tw-numeric-spacing: tabular-nums;\n font-variant-numeric: var(--tw-ordinal, ) var(--tw-slashed-zero, ) var(--tw-numeric-figure, ) var(--tw-numeric-spacing, ) var(--tw-numeric-fraction, );\n}\n\n.list-view {\n --gallery-min-column-width: 360px;\n --gallery-gap: 10px;\n}\n\n.list-view .card-link {\n flex-direction: row;\n align-items: center;\n}\n\n.list-view .poster {\n flex-shrink: 0;\n width: 82px;\n}\n\n.list-view .page-count {\n bottom: 4px;\n right: 4px;\n}\n\n.detail {\n grid-template-columns: minmax(0, 1fr);\n grid-template-areas: \"copy\"\n \"media\"\n \"tags\";\n align-items: flex-start;\n margin-bottom: 36px;\n display: grid;\n}\n\n.detail-with-cover {\n grid-template: \"media copy\"\n \"media tags\" 1fr\n / minmax(135px, 250px) minmax(0, 1fr);\n column-gap: clamp(14px, 4vw, 48px);\n}\n\n.detail-copy {\n grid-area: copy;\n}\n\n.detail-media {\n grid-area: media;\n}\n\n.detail-cover {\n border-radius: var(--radius);\n border: 1px solid var(--line);\n background-color: var(--panel);\n grid-area: cover;\n overflow: hidden;\n}\n\n.detail-cover img {\n object-fit: contain;\n width: 100%;\n height: auto;\n max-height: min(420px, 46svh);\n}\n\n.detail h1 {\n letter-spacing: -.04em;\n overflow-wrap: anywhere;\n margin-block: 5px 8px;\n font-size: clamp(23px, 3.3vw, 45px);\n font-weight: 690;\n line-height: 1.12;\n}\n\n.subtitle {\n overflow-wrap: anywhere;\n color: var(--muted);\n}\n\n.details-grid {\n border-block: 1px solid var(--line);\n flex-wrap: wrap;\n gap: 10px 24px;\n margin-top: 16px;\n padding-block: 12px;\n display: flex;\n}\n\n.details-grid dt {\n color: var(--muted);\n font-size: 11px;\n}\n\n.details-grid dd {\n overflow-wrap: anywhere;\n margin-top: 3px;\n}\n\n.detail-tag-groups {\n grid-area: tags;\n gap: 10px;\n margin-top: 16px;\n display: grid;\n}\n\n.detail-tag-group {\n grid-template-columns: 5.25rem minmax(0, 1fr);\n align-items: flex-start;\n gap: 8px;\n display: grid;\n}\n\n.detail-tag-group dt {\n --tw-font-weight: var(--font-weight-semibold);\n font-size: 13px;\n font-weight: var(--font-weight-semibold);\n overflow-wrap: anywhere;\n color: var(--muted);\n padding-block: 8px;\n}\n\n.detail-tag-group dd {\n flex-wrap: wrap;\n gap: 6px;\n display: flex;\n}\n\n.detail-tag-group .pill {\n overflow-wrap: anywhere;\n white-space: normal;\n max-inline-size: 100%;\n}\n\n.detail-tag-group [aria-expanded=\"true\"] {\n border-color: var(--muted);\n background-color: var(--panel);\n}\n\n.tag-search-popover {\n z-index: 11;\n border: 1px solid var(--line);\n border-radius: var(--radius);\n background-color: var(--surface);\n inline-size: max-content;\n max-inline-size: min(320px, 100vw - 24px);\n padding: 10px;\n position: fixed;\n inset: 0 auto auto 0;\n box-shadow: 0 8px 24px #0003;\n}\n\n.tag-search-popover p {\n --tw-font-weight: 650;\n overflow-wrap: anywhere;\n margin: 0 2px 8px;\n font-weight: 650;\n}\n\n.section-title {\n border-top: 1px solid var(--line);\n padding-block: 15px;\n}\n\n.section-title h2 {\n font-size: 18px;\n}\n\n.thumbnails {\n --gallery-min-column-width: 95px;\n --gallery-gap: 9px;\n}\n\n.thumbnail {\n border: 1px solid var(--line);\n border-radius: var(--radius-lg);\n background-color: var(--surface);\n text-align: center;\n transition: border-color .18s;\n display: block;\n overflow: hidden;\n}\n\n.thumbnail:hover {\n border-color: var(--muted);\n}\n\n.pagination {\n border-top: 1px solid var(--line);\n grid-template-columns: 1fr 1fr;\n gap: 8px;\n margin-top: 22px;\n padding-top: 14px;\n display: grid;\n}\n\n.pagination a {\n justify-self: flex-start;\n}\n\n.pagination .next {\n grid-column: 2;\n justify-self: flex-end;\n}\n\n.empty, .notice {\n border: 1px solid var(--line);\n border-radius: var(--radius);\n background-color: var(--surface);\n color: var(--muted);\n padding: 18px;\n}\n\n.notice {\n margin-bottom: 20px;\n}\n\n.empty .pill {\n margin-top: 8px;\n}\n\n@media (max-width: 650px) {\n .catalog-title {\n row-gap: 10px;\n }\n\n .filters {\n margin-block: 14px 10px;\n }\n\n .catalog-grid {\n --gallery-fixed-columns: 2;\n --gallery-gap: 10px;\n }\n\n .list-view {\n --gallery-fixed-columns: 1;\n }\n\n .thumbnails {\n --gallery-fixed-columns: 4;\n }\n\n .detail-with-cover {\n grid-template: \"cover copy\"\n \"actions actions\"\n \"tags tags\"\n / minmax(87px, 29%) minmax(0, 1fr);\n }\n\n .detail-with-cover .detail-media {\n display: contents;\n }\n\n .detail-cover img {\n max-height: min(220px, 38svh);\n }\n\n .detail-tag-group {\n grid-template-columns: minmax(0, 1fr);\n gap: 4px;\n }\n\n .detail-tag-group dt {\n padding-block: 0;\n }\n\n .card-meta {\n padding-inline: 9px;\n }\n}\n\n.eh-app:has(.gallery-comments-drawer[open]) {\n overflow-y: hidden;\n}\n\n.gallery-comments-drawer {\n border-style: var(--tw-border-style);\n background-color: var(--surface);\n width: 100%;\n max-width: none;\n height: 100dvh;\n max-height: none;\n color: var(--ink);\n --drawer-offset: translateY(100%);\n border-width: 0;\n margin: 0;\n padding: 0;\n position: fixed;\n inset: 0 0 auto auto;\n overflow: hidden;\n}\n\n.gallery-comments-drawer::backdrop {\n background: #0007;\n}\n\n.gallery-comments-panel {\n height: 100%;\n padding-inline: env(safe-area-inset-left) env(safe-area-inset-right);\n}\n\n.gallery-comments-header {\n z-index: 1;\n background-color: var(--surface);\n min-height: 62px;\n padding-inline: calc(var(--spacing) * 5);\n padding-bottom: calc(var(--spacing) * 2);\n padding-top: max(8px, env(safe-area-inset-top));\n position: sticky;\n top: 0;\n}\n\n.gallery-comments-panel .icon-button.back-to-top {\n position: absolute;\n}\n\n.gallery-comment-link {\n color: var(--link-text);\n text-underline-offset: 2px;\n text-decoration-line: underline;\n}\n\n.gallery-comments-drawer-enter-active, .gallery-comments-drawer-leave-active {\n transition: transform .19s cubic-bezier(.25, 1, .5, 1);\n}\n\n.gallery-comments-drawer-enter-active::backdrop, .gallery-comments-drawer-leave-active::backdrop {\n transition: opacity .19s;\n}\n\n.gallery-comments-drawer-enter-from, .gallery-comments-drawer-leave-to {\n transform: var(--drawer-offset);\n}\n\n.gallery-comments-drawer-enter-from::backdrop, .gallery-comments-drawer-leave-to::backdrop {\n opacity: 0;\n}\n\n@media (min-width: 960px) {\n .gallery-comments-drawer {\n border-left-style: var(--tw-border-style);\n --tw-border-style: solid;\n border-style: solid;\n border-left-width: 1px;\n border-color: var(--line);\n --drawer-offset: translateX(100%);\n width: 440px;\n }\n}\n\n.icon-button.back-to-top {\n right: max(16px, calc(env(safe-area-inset-right) + 8px));\n bottom: max(16px, calc(env(safe-area-inset-bottom) + 8px));\n z-index: 12;\n border: 1px solid var(--line);\n background-color: var(--surface);\n width: 48px;\n height: 48px;\n color: var(--ink);\n touch-action: manipulation;\n border-radius: 50%;\n position: fixed;\n box-shadow: 0 4px 18px #0002;\n}\n\n.icon-button.back-to-top:active {\n background-color: var(--panel);\n}\n\n.back-to-top-enter-active, .back-to-top-leave-active {\n transition: opacity .15s, transform .18s cubic-bezier(.22, 1, .36, 1);\n}\n\n.back-to-top-enter-from, .back-to-top-leave-to {\n opacity: 0;\n transform: translateY(6px);\n}\n\n.back-to-top-leave-active {\n pointer-events: none;\n}\n\n.loading-note {\n right: max(16px, calc(env(safe-area-inset-right) + 8px));\n bottom: max(16px, calc(env(safe-area-inset-bottom) + 8px));\n z-index: 12;\n background-color: var(--ink);\n color: var(--surface);\n border-radius: 9px;\n align-items: center;\n gap: 8px;\n padding: 8px 14px;\n font-size: 12px;\n display: flex;\n position: fixed;\n}\n\n.eh-app:has( + .back-to-top) .loading-note {\n bottom: calc(max(16px, calc(env(safe-area-inset-bottom) + 8px)) + 56px);\n}\n\n.back-to-top.is-reader, .is-reader .loading-note {\n bottom: calc(var(--reader-progress-bottom) + var(--reader-progress-height) + 8px);\n}\n\n.is-reader:has( + .back-to-top) .loading-note {\n bottom: calc(var(--reader-progress-bottom) + var(--reader-progress-height) + 64px);\n}\n\n.card-action-sheet {\n overscroll-behavior: contain;\n border: 1px solid var(--line);\n background-color: var(--surface);\n width: min(100%, 480px);\n max-width: none;\n max-height: 80dvh;\n color: var(--ink);\n border-bottom: 0;\n border-radius: 18px 18px 0 0;\n margin: 0 auto;\n padding: 0;\n position: fixed;\n inset: auto 0 0;\n overflow-y: auto;\n}\n\n.card-action-sheet::backdrop {\n background: #0007;\n}\n\n.card-action-sheet-panel {\n padding: 8px max(14px, env(safe-area-inset-right)) max(14px, env(safe-area-inset-bottom)) max(14px, env(safe-area-inset-left));\n grid-template-columns: minmax(0, 1fr);\n gap: 8px;\n display: grid;\n}\n\n.card-action-sheet-header {\n justify-content: space-between;\n align-items: center;\n gap: 8px;\n display: flex;\n}\n\n.card-action-sheet-header h2 {\n --tw-font-weight: 650;\n text-overflow: ellipsis;\n white-space: nowrap;\n font-size: 14px;\n font-weight: 650;\n overflow: hidden;\n}\n\n.card-action-sheet-button {\n background-color: var(--panel);\n --tw-font-weight: var(--font-weight-semibold);\n min-height: 50px;\n font-weight: var(--font-weight-semibold);\n touch-action: manipulation;\n border-radius: 10px;\n align-items: center;\n gap: 12px;\n padding-inline: 14px;\n display: flex;\n}\n\n.card-action-sheet-button:active:not(:disabled) {\n background-color: var(--line);\n}\n\n.card-action-sheet-enter-active, .card-action-sheet-leave-active {\n transition: transform .19s cubic-bezier(.25, 1, .5, 1);\n}\n\n.card-action-sheet-enter-active::backdrop, .card-action-sheet-leave-active::backdrop {\n transition: opacity .19s cubic-bezier(.25, 1, .5, 1);\n}\n\n.card-action-sheet-enter-from, .card-action-sheet-leave-to {\n transform: translateY(100%);\n}\n\n.card-action-sheet-enter-from::backdrop, .card-action-sheet-leave-to::backdrop {\n opacity: 0;\n}\n\n.card-action-sheet-leave-active {\n pointer-events: none;\n}\n\n.icon-flight {\n z-index: 20;\n border: 1px solid var(--line);\n background-color: var(--ink);\n width: 34px;\n height: 34px;\n color: var(--surface);\n pointer-events: none;\n opacity: 0;\n border-radius: 9px;\n place-items: center;\n display: grid;\n position: fixed;\n inset: 0 auto auto 0;\n box-shadow: 0 4px 14px #0003;\n}\n\n.bookmark-notice {\n z-index: 13;\n inset-inline: max(14px, env(safe-area-inset-left)) max(14px, env(safe-area-inset-right));\n bottom: max(14px, calc(env(safe-area-inset-bottom) + 6px));\n background-color: var(--ink);\n width: min(420px, 100% - 32px);\n min-height: 52px;\n color: var(--surface);\n border-radius: 11px;\n justify-content: space-between;\n align-items: center;\n gap: 12px;\n margin-inline: auto;\n padding: 4px 12px;\n display: flex;\n position: fixed;\n box-shadow: 0 4px 18px #0003;\n}\n\n.eh-app:has( + .back-to-top) .bookmark-notice {\n bottom: calc(max(16px, calc(env(safe-area-inset-bottom) + 8px)) + 56px);\n}\n\n.eh-app.is-reader .bookmark-notice {\n bottom: calc(var(--reader-progress-bottom) + var(--reader-progress-height) + 8px);\n}\n\n.eh-app.is-reader:has( + .back-to-top) .bookmark-notice {\n bottom: calc(var(--reader-progress-bottom) + var(--reader-progress-height) + 64px);\n}\n\n.bookmark-notice p, .bookmark-notice a {\n align-items: center;\n gap: 8px;\n display: flex;\n}\n\n.bookmark-notice a {\n --tw-font-weight: 650;\n white-space: nowrap;\n min-height: 44px;\n padding-inline: 4px;\n font-weight: 650;\n}\n\n.bookmark-notice a:focus-visible {\n outline-color: var(--surface);\n}\n\n.bookmark-notice-enter-active, .bookmark-notice-leave-active {\n transition: opacity .16s ease-out, transform .16s cubic-bezier(.25, 1, .5, 1);\n}\n\n.bookmark-notice-enter-from, .bookmark-notice-leave-to {\n opacity: 0;\n transform: translateY(8px);\n}\n\n.bookmark-notice-leave-active {\n pointer-events: none;\n}\n\n.scroll-edge-reveal {\n pointer-events: none;\n overflow: clip;\n}\n\n.scroll-edge-chip {\n align-items: center;\n gap: calc(var(--spacing) * 2);\n border-style: var(--tw-border-style);\n --tw-border-style: solid;\n border-style: solid;\n border-width: 1px;\n border-color: var(--line);\n background-color: var(--surface);\n min-height: 34px;\n padding-inline: calc(var(--spacing) * 3);\n font-size: var(--text-xs);\n line-height: var(--tw-leading, var(--text-xs--line-height));\n white-space: nowrap;\n color: var(--ink);\n top: 50%;\n left: var(--scroll-edge-center, 50%);\n transform: translate(-50%, -50%) scale(var(--scroll-edge-scale, 1));\n border-radius: 2147483647px;\n display: flex;\n position: absolute;\n}\n\n.infinite-scroll-overlay {\n pointer-events: none;\n position: absolute;\n inset: 0;\n}\n\n.eh-app > .infinite-scroll-overlay {\n position: fixed;\n}\n\n.infinite-scroll-refresh {\n z-index: 10;\n inset-inline: 0;\n top: max(var(--masthead-height, 0px), env(safe-area-inset-top));\n position: absolute;\n}\n\n.infinite-scroll-end {\n inset-inline: 0;\n position: absolute;\n bottom: 0;\n}\n\n.infinite-scroll-end.reader-end-reveal {\n bottom: calc(var(--reader-progress-bottom) + var(--reader-progress-height) + 4px);\n}\n\n.infinite-sentinel-inner {\n min-height: 38px;\n color: var(--muted);\n opacity: .92;\n justify-content: center;\n align-items: center;\n gap: 10px;\n transition: transform .36s cubic-bezier(.32, .72, 0, 1), opacity .22s;\n display: flex;\n transform: translateY(0);\n}\n\n.infinite-sentinel-inner.is-loading {\n transform: translateY(-3px);\n}\n\n.infinite-error {\n color: var(--muted);\n align-items: center;\n gap: 10px;\n font-size: 12px;\n display: inline-flex;\n}\n\n.native-frame-notice {\n z-index: 20;\n align-items: center;\n gap: calc(var(--spacing) * 2);\n max-width: calc(100% - 24px);\n padding-block: calc(var(--spacing) * 2);\n padding-right: calc(var(--spacing) * 3);\n padding-left: calc(var(--spacing) * 2);\n inset: max(12px, env(safe-area-inset-top)) max(12px, env(safe-area-inset-right)) auto auto;\n color: #fff;\n background: #161616;\n border-radius: 9px;\n margin: 0;\n font-size: 13px;\n display: flex;\n position: fixed;\n}\n\n.native-frame-notice a {\n --tw-font-weight: var(--font-weight-semibold);\n font-weight: var(--font-weight-semibold);\n text-underline-offset: 2px;\n text-decoration-line: underline;\n}\n\n.notice-dismiss {\n width: calc(var(--spacing) * 9);\n height: calc(var(--spacing) * 9);\n border-radius: var(--radius-md);\n font-size: var(--text-xl);\n line-height: var(--tw-leading, var(--text-xl--line-height));\n flex-shrink: 0;\n place-items: center;\n display: grid;\n}\n\n@media (hover: hover) {\n .notice-dismiss:hover {\n background-color: currentColor;\n }\n\n @supports (color: color-mix(in lab, red, red)) {\n .notice-dismiss:hover {\n background-color: color-mix(in oklab, currentcolor 15%, transparent);\n }\n }\n}\n\n.notice-dismiss:active {\n background-color: currentColor;\n}\n\n@supports (color: color-mix(in lab, red, red)) {\n .notice-dismiss:active {\n background-color: color-mix(in oklab, currentcolor 20%, transparent);\n }\n}\n\n.native-frame-notice a:focus-visible, .notice-dismiss:focus-visible {\n outline-color: currentColor;\n}\n\n.reader-controls {\n flex-wrap: wrap;\n justify-content: flex-end;\n align-items: center;\n gap: 4px 8px;\n padding-block: 4px 8px;\n display: flex;\n}\n\n.reader-controls-tools {\n margin-inline-end: auto;\n}\n\n.reader-controls .reading-actions {\n flex: none;\n}\n\n.reader-progress {\n inset-inline: max(14px, env(safe-area-inset-left)) max(14px, env(safe-area-inset-right));\n bottom: var(--reader-progress-bottom);\n z-index: 11;\n width: min(460px, calc(100% - max(28px, env(safe-area-inset-left) + env(safe-area-inset-right))));\n gap: 8px;\n margin-inline: auto;\n display: grid;\n position: fixed;\n}\n\n.reader-progress-bar {\n min-height: var(--reader-progress-height);\n border: 1px solid var(--line);\n border-radius: var(--radius);\n background-color: var(--surface);\n align-items: center;\n gap: 12px;\n padding-inline: 14px;\n display: flex;\n box-shadow: 0 4px 18px #0002;\n}\n\n.reader-progress-error {\n border: 1px solid var(--line);\n border-radius: var(--radius);\n background-color: var(--surface);\n color: var(--danger-subtle-text);\n justify-content: space-between;\n align-items: center;\n gap: 8px;\n padding: 8px;\n display: flex;\n}\n\n.reader-previous-error {\n top: max(calc(env(safe-area-inset-top) + 12px), calc(var(--masthead-height, 0px) + 8px));\n z-index: 11;\n border: 1px solid var(--line);\n border-radius: var(--radius);\n background-color: var(--surface);\n width: fit-content;\n max-width: calc(100% - 32px);\n margin-inline: auto;\n padding: 8px 12px;\n position: fixed;\n inset-inline: 16px;\n box-shadow: 0 4px 18px #0002;\n}\n\n.reader-chapters {\n border: 1px solid var(--line);\n border-radius: var(--radius);\n background-color: var(--surface);\n padding: 4px 8px 8px;\n display: grid;\n box-shadow: 0 4px 18px #0002;\n}\n\n.reader-chapters-header {\n --tw-font-weight: 650;\n justify-content: space-between;\n align-items: center;\n padding-inline-start: 8px;\n font-size: 14px;\n font-weight: 650;\n display: flex;\n}\n\n.reader-chapter-list {\n overscroll-behavior-y: contain;\n max-height: min(300px, 40dvh);\n margin: 0;\n padding: 4px;\n list-style-type: none;\n position: relative;\n overflow-y: auto;\n}\n\n.reader-chapter-list button {\n border-radius: var(--radius-lg);\n text-align: start;\n overflow-wrap: anywhere;\n align-items: baseline;\n gap: 10px;\n width: 100%;\n min-height: 44px;\n padding: 9px 8px;\n display: flex;\n}\n\n.reader-chapter-list button:hover:not(:disabled), .reader-chapter-list [aria-current=\"true\"] {\n background-color: var(--panel);\n}\n\n.reader-chapter-list [aria-current=\"true\"] {\n --tw-font-weight: 650;\n font-weight: 650;\n}\n\n.reader-chapter-number {\n min-width: 2ch;\n color: var(--muted);\n --tw-numeric-spacing: tabular-nums;\n font-variant-numeric: var(--tw-ordinal, ) var(--tw-slashed-zero, ) var(--tw-numeric-figure, ) var(--tw-numeric-spacing, ) var(--tw-numeric-fraction, );\n flex: none;\n}\n\n.reader-progress-preview {\n left: clamp(39px, calc(8px + (100% - 16px) * var(--reader-progress-ratio)), calc(100% - 39px));\n transform: translateX(-50%);\n}\n\n.reader-progress input {\n --reader-progress-value: calc(var(--reader-progress-ratio) * 100%);\n --reader-track: linear-gradient(to right, var(--ink) var(--reader-progress-value), var(--muted) 0);\n appearance: none;\n cursor: pointer;\n touch-action: none;\n background: none;\n flex: 1;\n min-width: 0;\n height: 44px;\n}\n\n.reader-progress input:disabled {\n cursor: default;\n opacity: .45;\n}\n\n.reader-progress input::-webkit-slider-runnable-track {\n border-radius: var(--radius-sm);\n background: var(--reader-track);\n height: 4px;\n}\n\n.reader-progress input::-moz-range-track {\n border-radius: var(--radius-sm);\n background: var(--reader-track);\n height: 4px;\n}\n\n.reader-progress input::-webkit-slider-thumb {\n appearance: none;\n background-color: var(--ink);\n border-radius: 50%;\n width: 16px;\n height: 16px;\n margin-top: -6px;\n}\n\n.reader-progress input::-moz-range-thumb {\n background-color: var(--ink);\n border: 0;\n border-radius: 50%;\n width: 16px;\n height: 16px;\n}\n\n.reading-actions {\n flex-wrap: wrap;\n align-items: center;\n gap: 8px;\n display: flex;\n}\n\n.library-action {\n min-height: 44px;\n}\n\n.detail-actions {\n grid-area: actions;\n margin-top: 12px;\n}\n\n.detail-with-cover .detail-actions {\n grid-template-columns: minmax(0, 1fr);\n display: grid;\n}\n\n@media (max-width: 650px) {\n .detail-with-cover .detail-actions {\n display: flex;\n }\n}\n\n.detail-actions .action-button {\n overflow-wrap: anywhere;\n white-space: normal;\n min-inline-size: min(112px, 100%);\n max-inline-size: 100%;\n}\n\n.detail-actions .favorite-button {\n min-inline-size: 0;\n}\n\n.detail-actions svg {\n flex: none;\n}\n\n.reading-actions [aria-pressed=\"true\"] {\n background-color: var(--panel);\n}\n\n.reading-actions [aria-pressed=\"true\"] svg {\n fill: currentColor;\n}\n\n.confirmation-dialog {\n border: 1px solid var(--line);\n border-radius: var(--radius);\n background-color: var(--surface);\n width: min(420px, 100% - 32px);\n max-height: calc(100% - 32px);\n color: var(--ink);\n overscroll-behavior: contain;\n margin: auto;\n padding: 0;\n position: fixed;\n inset: 0;\n box-shadow: 0 12px 40px #0004;\n}\n\n.confirmation-dialog::backdrop {\n background: #0008;\n}\n\n.confirmation-content h2 {\n --tw-font-weight: var(--font-weight-bold);\n font-size: 18px;\n font-weight: var(--font-weight-bold);\n}\n\n.confirmation-content p {\n color: var(--muted);\n margin-top: 8px;\n}\n\n.action-button-danger {\n --delete-bg: var(--danger-bg);\n --delete-text: var(--danger-text);\n --delete-hover: var(--danger-hover);\n}\n\n.action-button-danger-subtle {\n --delete-bg: var(--danger-subtle-bg);\n --delete-text: var(--danger-subtle-text);\n --delete-hover: var(--danger-subtle-hover);\n}\n\n.eh-app :is(button, a):is(.action-button-danger, .action-button-danger-subtle) {\n border-color: var(--delete-bg);\n background: var(--delete-bg);\n color: var(--delete-text);\n}\n\n.eh-app :is(button, a):is(.action-button-danger, .action-button-danger-subtle):is(:hover, :active):not(:disabled, [aria-disabled=\"true\"]) {\n border-color: var(--delete-hover);\n background: var(--delete-hover);\n}\n\n.card-quick-action > .action-button-danger-subtle:focus-visible {\n outline-color: var(--delete-text);\n}\n\n.reader-frames, .reader-buffer, .reader-frame {\n transition-property: none;\n}\n\n.reader-frame, .reader-buffer {\n border-radius: var(--radius);\n background-color: var(--panel);\n place-items: center;\n min-height: 180px;\n display: grid;\n overflow: hidden;\n}\n\n.eh-app.is-reader {\n overflow-anchor: none;\n}\n\n.reader-surface {\n --reader-image-max-height: max(360px, 69svh);\n}\n\n.reader-height-probe {\n pointer-events: none;\n visibility: hidden;\n width: 0;\n height: 0;\n max-height: var(--reader-image-max-height);\n position: absolute;\n}\n\n.reader-frame-preview.thumbnail-image {\n position: absolute;\n inset: 0;\n}\n\n.reader-page-image {\n max-width: 100%;\n max-height: var(--reader-image-max-height);\n object-fit: contain;\n -webkit-user-select: none;\n user-select: none;\n width: auto;\n height: auto;\n}\n\n.reader-page-image[width][height] {\n width: min(100%, var(--reader-image-width), calc(var(--reader-image-max-height) * var(--reader-image-ratio)));\n aspect-ratio: auto var(--reader-image-ratio);\n}\n\n.reader-surface.fit-width .reader-page-image {\n width: 100%;\n max-height: none;\n}\n\n@media (max-width: 959px) {\n .reader-main.shell {\n padding-inline: env(safe-area-inset-left) env(safe-area-inset-right);\n }\n\n .reader-frame, .reader-buffer {\n border-radius: 0;\n }\n}\n\n@property --tw-rotate-x {\n syntax: \"*\";\n inherits: false\n}\n\n@property --tw-rotate-y {\n syntax: \"*\";\n inherits: false\n}\n\n@property --tw-rotate-z {\n syntax: \"*\";\n inherits: false\n}\n\n@property --tw-skew-x {\n syntax: \"*\";\n inherits: false\n}\n\n@property --tw-skew-y {\n syntax: \"*\";\n inherits: false\n}\n\n@property --tw-divide-y-reverse {\n syntax: \"*\";\n inherits: false;\n initial-value: 0;\n}\n\n@property --tw-border-style {\n syntax: \"*\";\n inherits: false;\n initial-value: solid;\n}\n\n@property --tw-leading {\n syntax: \"*\";\n inherits: false\n}\n\n@property --tw-font-weight {\n syntax: \"*\";\n inherits: false\n}\n\n@property --tw-ordinal {\n syntax: \"*\";\n inherits: false\n}\n\n@property --tw-slashed-zero {\n syntax: \"*\";\n inherits: false\n}\n\n@property --tw-numeric-figure {\n syntax: \"*\";\n inherits: false\n}\n\n@property --tw-numeric-spacing {\n syntax: \"*\";\n inherits: false\n}\n\n@property --tw-numeric-fraction {\n syntax: \"*\";\n inherits: false\n}\n\n@property --tw-shadow {\n syntax: \"*\";\n inherits: false;\n initial-value: 0 0 #0000;\n}\n\n@property --tw-shadow-color {\n syntax: \"*\";\n inherits: false\n}\n\n@property --tw-shadow-alpha {\n syntax: \"<percentage>\";\n inherits: false;\n initial-value: 100%;\n}\n\n@property --tw-inset-shadow {\n syntax: \"*\";\n inherits: false;\n initial-value: 0 0 #0000;\n}\n\n@property --tw-inset-shadow-color {\n syntax: \"*\";\n inherits: false\n}\n\n@property --tw-inset-shadow-alpha {\n syntax: \"<percentage>\";\n inherits: false;\n initial-value: 100%;\n}\n\n@property --tw-ring-color {\n syntax: \"*\";\n inherits: false\n}\n\n@property --tw-ring-shadow {\n syntax: \"*\";\n inherits: false;\n initial-value: 0 0 #0000;\n}\n\n@property --tw-inset-ring-color {\n syntax: \"*\";\n inherits: false\n}\n\n@property --tw-inset-ring-shadow {\n syntax: \"*\";\n inherits: false;\n initial-value: 0 0 #0000;\n}\n\n@property --tw-ring-inset {\n syntax: \"*\";\n inherits: false\n}\n\n@property --tw-ring-offset-width {\n syntax: \"<length>\";\n inherits: false;\n initial-value: 0;\n}\n\n@property --tw-ring-offset-color {\n syntax: \"*\";\n inherits: false;\n initial-value: #fff;\n}\n\n@property --tw-ring-offset-shadow {\n syntax: \"*\";\n inherits: false;\n initial-value: 0 0 #0000;\n}\n\n@property --tw-blur {\n syntax: \"*\";\n inherits: false\n}\n\n@property --tw-brightness {\n syntax: \"*\";\n inherits: false\n}\n\n@property --tw-contrast {\n syntax: \"*\";\n inherits: false\n}\n\n@property --tw-grayscale {\n syntax: \"*\";\n inherits: false\n}\n\n@property --tw-hue-rotate {\n syntax: \"*\";\n inherits: false\n}\n\n@property --tw-invert {\n syntax: \"*\";\n inherits: false\n}\n\n@property --tw-opacity {\n syntax: \"*\";\n inherits: false\n}\n\n@property --tw-saturate {\n syntax: \"*\";\n inherits: false\n}\n\n@property --tw-sepia {\n syntax: \"*\";\n inherits: false\n}\n\n@property --tw-drop-shadow {\n syntax: \"*\";\n inherits: false\n}\n\n@property --tw-drop-shadow-color {\n syntax: \"*\";\n inherits: false\n}\n\n@property --tw-drop-shadow-alpha {\n syntax: \"<percentage>\";\n inherits: false;\n initial-value: 100%;\n}\n\n@property --tw-drop-shadow-size {\n syntax: \"*\";\n inherits: false\n}\n\n@property --tw-ease {\n syntax: \"*\";\n inherits: false\n}\n\n@keyframes loading-dash {\n 0% {\n stroke-dasharray: 1 200;\n stroke-dashoffset: 0;\n }\n\n 50% {\n stroke-dasharray: 90 150;\n stroke-dashoffset: -40px;\n }\n\n 100% {\n stroke-dasharray: 90 150;\n stroke-dashoffset: -120px;\n }\n}\n";
function mount(host, adapter, initialPage, url, nativeLink) {
const viewActive = shallowRef(true);
const openingNative = shallowRef(false);
const shadow = host.attachShadow({ mode: "open" });
const style = document.createElement("style");
style.textContent = style_default;
const root = document.createElement("div");
shadow.append(style, root);
const app = createApp(BetterEhApp_default, {
adapter,
initialPage,
initialUrl: url.href,
nativeLink,
viewActive,
openingNative,
readingLibraryRepository: createBrowserReadingLibrary(window)
});
const pinia = createPinia();
app.use(pinia);
app.onUnmount(() => disposePinia(pinia));
app.mount(root);
return {
setActive(active) {
viewActive.value = active;
},
setOpeningNative(opening) {
openingNative.value = opening;
},
unmount: () => app.unmount()
};
}
var native_pull_default = "[data-theme] {\n --paper: #fafafa;\n --surface: #fff;\n --panel: #f0f0f0;\n --ink: #161616;\n --muted: #626262;\n --line: #e1e1e1;\n --link-text: #1859b6;\n --danger-bg: #b42318;\n --danger-text: #fff;\n --danger-hover: #912018;\n --danger-subtle-bg: #fef3f2;\n --danger-subtle-text: #b42318;\n --danger-subtle-hover: #fee4e2;\n --radius: 12px;\n color-scheme: light;\n}\n\n[data-theme=\"dark\"] {\n --paper: #101010;\n --surface: #171717;\n --panel: #212121;\n --ink: #f4f4f4;\n --muted: #a6a6a6;\n --line: #303030;\n --link-text: #8cbaff;\n --danger-bg: #f97066;\n --danger-text: #280b08;\n --danger-hover: #fda29b;\n --danger-subtle-bg: #3b1518;\n --danger-subtle-text: #fda29b;\n --danger-subtle-hover: #511c20;\n color-scheme: dark;\n}\n\n:host {\n all: initial;\n position: fixed;\n z-index: 2147483647;\n top: 0;\n right: max(12px, env(safe-area-inset-right));\n display: block;\n pointer-events: none;\n}\n\nbutton {\n position: relative;\n top: calc(35px + env(safe-area-inset-top));\n display: block;\n width: 48px;\n height: 44px;\n padding: 0;\n border: 0;\n background: none;\n cursor: pointer;\n pointer-events: auto;\n touch-action: manipulation;\n -webkit-tap-highlight-color: transparent;\n}\n\n.cord {\n position: absolute;\n top: calc(-35px - env(safe-area-inset-top));\n left: 23px;\n width: 2px;\n height: calc(51px + env(safe-area-inset-top));\n background: var(--ink);\n transform-origin: center top;\n pointer-events: none;\n}\n\n.handle {\n position: absolute;\n top: 5px;\n left: 7px;\n display: grid;\n width: 34px;\n height: 34px;\n box-sizing: border-box;\n place-items: center;\n border-radius: 50%;\n color: var(--surface);\n background: var(--ink);\n box-shadow: 0 2px 6px #0005;\n}\n\n.handle::after {\n content: \"\";\n width: 7px;\n height: 7px;\n margin-top: -3px;\n border: solid currentColor;\n border-width: 0 2px 2px 0;\n rotate: 45deg;\n}\n\nbutton:focus-visible {\n outline: none;\n}\n\nbutton:focus-visible .handle {\n outline: 2px solid var(--ink);\n outline-offset: 2px;\n box-shadow: 0 0 0 2px var(--surface);\n}\n\n@media (hover: hover) {\n button:hover .handle {\n background: var(--muted);\n }\n}\n";
function prefersReducedMotion() {
return window.matchMedia("(prefers-reduced-motion: reduce)").matches;
}
function pullTheme() {
try {
const saved = localStorage.getItem(themeStorageKey);
if (saved === "light" || saved === "dark") return saved;
} catch {}
return window.matchMedia("(prefers-color-scheme: dark)").matches ? "dark" : "light";
}
function createNativePull(id, resume) {
const host = document.createElement("div");
host.id = id;
const shadow = host.attachShadow({ mode: "open" });
const style = document.createElement("style");
style.textContent = native_pull_default;
const button = document.createElement("button");
button.type = "button";
button.setAttribute("aria-label", "切回 Better EH");
button.title = "切回 Better EH";
const cord = document.createElement("span");
cord.className = "cord";
const handle = document.createElement("span");
handle.className = "handle";
button.append(cord, handle);
shadow.append(style, button);
const stowed = "translateY(calc(-100% - 48px - env(safe-area-inset-top)))";
const resting = "translateY(0)";
button.addEventListener("click", async () => {
button.disabled = true;
let pull = [];
if (!prefersReducedMotion()) {
const timing = {
duration: 140,
easing: "cubic-bezier(0.25, 0.46, 0.45, 0.94)",
fill: "forwards"
};
const stretch = 1 + 17 / cord.offsetHeight;
pull = [cord.animate({ transform: ["scaleY(1)", `scaleY(${stretch})`] }, timing), handle.animate({ transform: ["translateY(0)", "translateY(17px)"] }, timing)];
await Promise.allSettled(pull.map((animation) => animation.finished));
}
try {
await resume();
} finally {
pull.forEach((animation) => animation.cancel());
button.disabled = false;
}
});
async function show(animate) {
button.dataset.theme = pullTheme();
button.disabled = true;
document.body.append(host);
await move(resting, animate, 70);
button.disabled = false;
}
async function hide(animate) {
await move(stowed, animate);
host.remove();
}
async function move(to, animate, delay = 0) {
const from = to === stowed ? resting : stowed;
host.style.transform = to;
if (!animate || prefersReducedMotion()) return;
await host.animate({ transform: [from, to] }, {
duration: 260,
delay,
easing: "cubic-bezier(0.22, 1, 0.36, 1)",
fill: "backwards"
}).finished.catch(() => void 0);
}
return {
show,
hide,
focus: () => button.focus({ preventScroll: true })
};
}
var lockStyles = `
html { overscroll-behavior-y: none !important; }
html, body {
overflow: hidden !important;
margin: 0 !important;
padding: 0 !important;
width: auto !important;
min-width: 0 !important;
max-width: none !important;
}
`;
function createDocumentLock(interfaceIds) {
const style = document.createElement("style");
style.textContent = lockStyles;
const originalViewport = document.querySelector("meta[name='viewport']");
const originalContent = originalViewport?.getAttribute("content");
const viewport = originalViewport ?? document.createElement("meta");
const disabled = new Set();
let previousScroll;
function disableOriginal() {
for (const element of document.body.children) {
if (interfaceIds.has(element.id) || element.hasAttribute("inert")) continue;
element.setAttribute("inert", "");
disabled.add(element);
}
}
function set(locked, framed = false) {
if (locked || framed) disableOriginal();
else {
for (const element of disabled) element.removeAttribute("inert");
disabled.clear();
}
if (locked || framed) {
if (!style.isConnected) {
previousScroll = [window.scrollX, window.scrollY];
document.head.append(style);
}
viewport.name = "viewport";
viewport.content = "width=device-width, initial-scale=1, viewport-fit=cover";
if (!viewport.isConnected) document.head.append(viewport);
} else {
style.remove();
if (!originalViewport) viewport.remove();
else if (originalContent === null || originalContent === void 0) viewport.removeAttribute("content");
else viewport.content = originalContent;
if (previousScroll) window.scrollTo(...previousScroll);
previousScroll = void 0;
}
}
return { set };
}
function createNativeFrame(id) {
let frame;
function current() {
try {
const doc = frame?.contentDocument;
if (!doc || doc.URL === "about:blank") return;
return {
doc,
url: new URL(doc.URL)
};
} catch {
return;
}
}
function setVisible(visible) {
if (!frame) return;
frame.style.visibility = visible ? "visible" : "hidden";
frame.inert = !visible;
}
async function load(url) {
if (current()?.url.href === url.href) return true;
frame?.remove();
const next = document.createElement("iframe");
next.id = id;
next.title = "原站页面";
next.style.cssText = "position:fixed;inset:0;z-index:2147483645;width:100%;height:100%;border:0;background:white;visibility:hidden";
next.inert = true;
frame = next;
const loaded = await new Promise((resolve) => {
const timer = window.setTimeout(() => finish(false), 8e3);
function finish(success) {
clearTimeout(timer);
next.removeEventListener("load", onLoad);
resolve(success);
}
function onLoad() {
const loaded = current();
finish(Boolean(loaded));
}
document.body.append(next);
next.contentWindow?.location.replace(url.href);
next.addEventListener("load", onLoad);
});
if (!loaded) {
next.remove();
if (frame === next) frame = void 0;
}
return loaded;
}
return {
current,
setVisible,
load
};
}
var rootId = "better-eh-root";
var pullId = "better-eh-native-pull";
var frameId = "better-eh-native-frame";
var revealFlag = "better-eh-reveal";
var adapters = new Map([
["e-hentai.org", ehAdapter],
["exhentai.org", ehAdapter],
["nhentai.net", nhAdapter]
]);
function nativeLink(href) {
const url = new URL(href);
url.searchParams.set(nativePageFlag, "1");
return url.href;
}
function cleanUrl(input) {
const url = new URL(input);
url.searchParams.delete(nativePageFlag);
url.searchParams.delete(revealFlag);
return url;
}
function nativeMode(enabled) {
try {
if (enabled === true) sessionStorage.setItem(nativePageFlag, "1");
else if (enabled === false) sessionStorage.removeItem(nativePageFlag);
return sessionStorage.getItem(nativePageFlag) === "1";
} catch {
return false;
}
}
function homeFromUploads() {
return document.referrer.startsWith("https://exhentai.org/") ? "https://exhentai.org/" : "https://e-hentai.org/";
}
function install() {
const initial = new URL(location.href);
const adapter = adapters.get(initial.hostname);
if (window.top !== window.self || !adapter && initial.hostname !== "upld.e-hentai.org") return;
if (document.getElementById(rootId) || document.getElementById(pullId)) return;
let originalUrl = cleanUrl(initial);
const lock = createDocumentLock(new Set([
rootId,
pullId,
frameId
]));
const nativeFrame = createNativeFrame(frameId);
let root;
let mounted;
let framed = false;
let busy = false;
let enhancedUrl;
let openedNativeUrl;
let frameNotice;
let enhancedState;
let enhancedTitle = "";
let enhancedFocus;
const originalTitle = document.title;
const originalScrollRestoration = history.scrollRestoration;
const pull = createNativePull(pullId, resume);
function rememberMode(original, url) {
const state = { ...history.state };
if (original) state[nativePageFlag] = true;
else delete state[nativePageFlag];
nativeMode(original);
history.replaceState(state, "", url?.href);
}
function focusEnhanced() {
if (enhancedFocus?.getClientRects().length) enhancedFocus.focus({ preventScroll: true });
else root?.shadowRoot?.querySelector(".eh-app")?.focus({ preventScroll: true });
}
function showFrameNotice(surface, target) {
const shadow = surface.shadowRoot;
if (!shadow) return;
const previousFocus = shadow.activeElement;
const notice = document.createElement("div");
notice.className = "native-frame-notice";
notice.setAttribute("role", "status");
const link = document.createElement("a");
link.href = nativeLink(target.href);
link.target = "_blank";
link.rel = "noopener";
link.textContent = "在新标签页打开原站";
const message = document.createElement("span");
message.append("原站页面无法在这里载入。 ", link);
const close = document.createElement("button");
close.className = "notice-dismiss";
close.type = "button";
close.textContent = "×";
close.title = "关闭原站提示";
close.setAttribute("aria-label", close.title);
close.addEventListener("click", () => {
notice.remove();
frameNotice = void 0;
(previousFocus instanceof HTMLElement && previousFocus.getClientRects().length ? previousFocus : shadow.querySelector(".eh-app"))?.focus({ preventScroll: true });
});
notice.append(close, message);
frameNotice?.remove();
shadow.append(notice);
frameNotice = notice;
close.focus({ preventScroll: true });
}
async function showEnhanced(site, page, url, animate) {
const previousRoot = root;
if (!root || enhancedUrl?.href !== url.href) {
mounted?.unmount();
root?.remove();
root = document.createElement("div");
root.id = rootId;
root.style.zIndex = "2147483646";
root.addEventListener("click", openOriginal);
document.body.append(root);
if (previousRoot || cleanUrl(new URL(location.href)).href !== url.href) history.replaceState({}, "", url.href);
rememberMode(false, url);
mounted = mount(root, site, page, url, nativeLink);
enhancedFocus = void 0;
} else {
history.replaceState(enhancedState, "", url.href);
rememberMode(false);
root.hidden = false;
document.title = enhancedTitle;
history.scrollRestoration = "manual";
}
const surface = root;
mounted?.setActive(true);
surface.inert = false;
lock.set(true, framed);
focusEnhanced();
await Promise.all([animateCurtain(surface, true, animate), pull.hide(animate)]);
nativeFrame.setVisible(false);
framed = false;
}
async function resume() {
if (busy) return;
busy = true;
try {
const current = framed ? nativeFrame.current() : {
doc: document,
url: new URL(location.href)
};
if (current) {
const url = cleanUrl(current.url);
const resumeUrl = url.href === openedNativeUrl ? enhancedUrl ?? url : url;
const page = adapter?.parse(current.doc, url);
if (adapter && page) {
if (!framed) originalUrl = url;
await showEnhanced(adapter, page, resumeUrl, true);
return;
}
}
const home = new URL(adapter?.home(originalUrl) ?? homeFromUploads());
home.searchParams.set(revealFlag, "1");
nativeMode(false);
await pull.hide(true);
location.assign(home.href);
} finally {
busy = false;
}
}
function openOriginal(event) {
if (event.defaultPrevented || event.button !== 0 || event.metaKey || event.ctrlKey || event.shiftKey || event.altKey) return;
const link = event.composedPath().find((node) => node instanceof HTMLAnchorElement);
if (!link?.hasAttribute("href") || link.target && link.target !== "_self") return;
const destination = new URL(link.href);
if (destination.origin !== location.origin || !destination.searchParams.has("better-eh-native")) return;
event.preventDefault();
if (!busy) hideEnhanced(cleanUrl(destination)).catch(() => {
if (root && !root.hidden) showFrameNotice(root, cleanUrl(destination));
});
}
async function hideEnhanced(target) {
const surface = root;
const currentApp = mounted;
if (!surface || !currentApp) return;
frameNotice?.remove();
busy = true;
const startingUrl = location.href;
try {
const needsFrame = target.href !== originalUrl.href;
if (needsFrame) {
currentApp.setOpeningNative(true);
if (!await nativeFrame.load(target).finally(() => currentApp.setOpeningNative(false))) {
if (location.href === startingUrl) showFrameNotice(surface, target);
return;
}
}
if (location.href !== startingUrl) return;
enhancedUrl = cleanUrl(new URL(location.href));
enhancedState = history.state;
enhancedTitle = document.title;
enhancedFocus = surface.shadowRoot?.activeElement instanceof HTMLElement ? surface.shadowRoot.activeElement : void 0;
framed = needsFrame;
const native = framed ? nativeFrame.current() : void 0;
const shownUrl = cleanUrl(native?.url ?? target);
openedNativeUrl = target.href;
rememberMode(true, shownUrl);
document.title = native?.doc.title ?? originalTitle;
surface.inert = true;
mounted?.setActive(false);
nativeFrame.setVisible(framed);
lock.set(false, framed);
history.scrollRestoration = originalScrollRestoration;
await Promise.all([animateCurtain(surface, false, true), pull.show(true)]);
surface.hidden = true;
pull.focus();
} finally {
busy = false;
}
}
function showInitialView() {
const reveal = initial.searchParams.has(revealFlag);
const original = !reveal && (initial.searchParams.has("better-eh-native") || history.state?.["better-eh-native"] === true || !history.state?.entryId && nativeMode());
const page = original ? void 0 : adapter?.parse(document, originalUrl);
if (adapter && page) showEnhanced(adapter, page, originalUrl, reveal);
else {
rememberMode(original, originalUrl);
pull.show(false);
}
}
showInitialView();
window.addEventListener("popstate", () => {
const native = history.state?.[nativePageFlag] === true;
nativeMode(native);
if (native && root && !root.hidden) {
enhancedUrl = void 0;
mounted?.setActive(false);
root.hidden = true;
root.inert = true;
const target = cleanUrl(new URL(location.href));
framed = target.href !== originalUrl.href && nativeFrame.current()?.url.href === target.href;
nativeFrame.setVisible(framed);
lock.set(false, framed);
history.scrollRestoration = originalScrollRestoration;
pull.show(false);
} else if (!native && root?.hidden) {
enhancedUrl = void 0;
mounted?.setActive(true);
root.hidden = false;
root.inert = false;
lock.set(true);
nativeFrame.setVisible(false);
framed = false;
history.scrollRestoration = "manual";
pull.hide(false);
}
}, { capture: true });
window.addEventListener("pageshow", (event) => {
if (event.persisted) nativeMode(history.state?.[nativePageFlag] === true);
});
}
async function animateCurtain(surface, reveal, animate) {
if (!animate || prefersReducedMotion()) return;
const closed = "inset(0 0 100% 0)";
const open = "inset(0 0 0 0)";
const motion = surface.animate({ clipPath: reveal ? [closed, open] : [open, closed] }, {
duration: reveal ? 360 : 300,
easing: "cubic-bezier(0.22, 1, 0.36, 1)",
fill: "forwards"
});
await motion.finished.catch(() => void 0);
if (!reveal) surface.hidden = true;
motion.cancel();
}
if (document.readyState === "loading") document.addEventListener("DOMContentLoaded", install, { once: true });
else install();
})();