Initial Commit

This commit is contained in:
2026-07-15 05:49:11 +08:00
parent b978f92d03
commit 0505d2586c
392 changed files with 64138 additions and 7379 deletions
Binary file not shown.

Before

Width:  |  Height:  |  Size: 31 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 32 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 28 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 38 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 34 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 21 KiB

Binary file not shown.
Binary file not shown.
Binary file not shown.

After

Width:  |  Height:  |  Size: 72 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 96 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 100 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 73 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 50 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 65 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 300 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 295 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 240 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 246 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 250 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 238 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 28 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 79 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 27 KiB

-52
View File
@@ -1,52 +0,0 @@
---
// Import the global.css file here so that it is included on
// all pages through the use of the <BaseHead /> component.
import '../styles/global.css';
import type { ImageMetadata } from 'astro';
import FallbackImage from '../assets/blog-placeholder-1.jpg';
import { SITE_TITLE } from '../consts';
import { Font } from 'astro:assets';
interface Props {
title: string;
description: string;
image?: ImageMetadata;
}
const canonicalURL = new URL(Astro.url.pathname, Astro.site);
const { title, description, image = FallbackImage } = Astro.props;
---
<!-- Global Metadata -->
<meta charset="utf-8" />
<meta name="viewport" content="width=device-width,initial-scale=1" />
<link rel="icon" type="image/svg+xml" href="/favicon.svg" />
<link rel="icon" href="/favicon.ico" />
<link rel="sitemap" href="/sitemap-index.xml" />
<link
rel="alternate"
type="application/rss+xml"
title={SITE_TITLE}
href={new URL('rss.xml', Astro.site)}
/>
<meta name="generator" content={Astro.generator} />
<Font cssVariable="--font-atkinson" preload />
<!-- Canonical URL -->
<link rel="canonical" href={canonicalURL} />
<!-- Primary Meta Tags -->
<title>{title}</title>
<meta name="description" content={description} />
<!-- Open Graph / Facebook -->
<meta property="og:type" content="website" />
<meta property="og:url" content={Astro.url} />
<meta property="og:title" content={title} />
<meta property="og:description" content={description} />
<meta property="og:image" content={new URL(image.src, Astro.url)} />
<!-- Twitter -->
<meta name="twitter:card" content="summary_large_image" />
-62
View File
@@ -1,62 +0,0 @@
---
const today = new Date();
---
<footer>
&copy; {today.getFullYear()} Your name here. All rights reserved.
<div class="social-links">
<a href="https://m.webtoo.ls/@astro" target="_blank">
<span class="sr-only">Follow Astro on Mastodon</span>
<svg
viewBox="0 0 16 16"
aria-hidden="true"
width="32"
height="32"
astro-icon="social/mastodon"
><path
fill="currentColor"
d="M11.19 12.195c2.016-.24 3.77-1.475 3.99-2.603.348-1.778.32-4.339.32-4.339 0-3.47-2.286-4.488-2.286-4.488C12.062.238 10.083.017 8.027 0h-.05C5.92.017 3.942.238 2.79.765c0 0-2.285 1.017-2.285 4.488l-.002.662c-.004.64-.007 1.35.011 2.091.083 3.394.626 6.74 3.78 7.57 1.454.383 2.703.463 3.709.408 1.823-.1 2.847-.647 2.847-.647l-.06-1.317s-1.303.41-2.767.36c-1.45-.05-2.98-.156-3.215-1.928a3.614 3.614 0 0 1-.033-.496s1.424.346 3.228.428c1.103.05 2.137-.064 3.188-.189zm1.613-2.47H11.13v-4.08c0-.859-.364-1.295-1.091-1.295-.804 0-1.207.517-1.207 1.541v2.233H7.168V5.89c0-1.024-.403-1.541-1.207-1.541-.727 0-1.091.436-1.091 1.296v4.079H3.197V5.522c0-.859.22-1.541.66-2.046.456-.505 1.052-.764 1.793-.764.856 0 1.504.328 1.933.983L8 4.39l.417-.695c.429-.655 1.077-.983 1.934-.983.74 0 1.336.259 1.791.764.442.505.661 1.187.661 2.046v4.203z"
></path></svg
>
</a>
<a href="https://twitter.com/astrodotbuild" target="_blank">
<span class="sr-only">Follow Astro on Twitter</span>
<svg viewBox="0 0 16 16" aria-hidden="true" width="32" height="32" astro-icon="social/twitter"
><path
fill="currentColor"
d="M5.026 15c6.038 0 9.341-5.003 9.341-9.334 0-.14 0-.282-.006-.422A6.685 6.685 0 0 0 16 3.542a6.658 6.658 0 0 1-1.889.518 3.301 3.301 0 0 0 1.447-1.817 6.533 6.533 0 0 1-2.087.793A3.286 3.286 0 0 0 7.875 6.03a9.325 9.325 0 0 1-6.767-3.429 3.289 3.289 0 0 0 1.018 4.382A3.323 3.323 0 0 1 .64 6.575v.045a3.288 3.288 0 0 0 2.632 3.218 3.203 3.203 0 0 1-.865.115 3.23 3.23 0 0 1-.614-.057 3.283 3.283 0 0 0 3.067 2.277A6.588 6.588 0 0 1 .78 13.58a6.32 6.32 0 0 1-.78-.045A9.344 9.344 0 0 0 5.026 15z"
></path></svg
>
</a>
<a href="https://github.com/withastro/astro" target="_blank">
<span class="sr-only">Go to Astro's GitHub repo</span>
<svg viewBox="0 0 16 16" aria-hidden="true" width="32" height="32" astro-icon="social/github"
><path
fill="currentColor"
d="M8 0C3.58 0 0 3.58 0 8c0 3.54 2.29 6.53 5.47 7.59.4.07.55-.17.55-.38 0-.19-.01-.82-.01-1.49-2.01.37-2.53-.49-2.69-.94-.09-.23-.48-.94-.82-1.13-.28-.15-.68-.52-.01-.53.63-.01 1.08.58 1.23.82.72 1.21 1.87.87 2.33.66.07-.52.28-.87.51-1.07-1.78-.2-3.64-.89-3.64-3.95 0-.87.31-1.59.82-2.15-.08-.2-.36-1.02.08-2.12 0 0 .67-.21 2.2.82.64-.18 1.32-.27 2-.27.68 0 1.36.09 2 .27 1.53-1.04 2.2-.82 2.2-.82.44 1.1.16 1.92.08 2.12.51.56.82 1.27.82 2.15 0 3.07-1.87 3.75-3.65 3.95.29.25.54.73.54 1.48 0 1.07-.01 1.93-.01 2.2 0 .21.15.46.55.38A8.012 8.012 0 0 0 16 8c0-4.42-3.58-8-8-8z"
></path></svg
>
</a>
</div>
</footer>
<style>
footer {
padding: 2em 1em 6em 1em;
background: linear-gradient(var(--gray-gradient)) no-repeat;
color: rgb(var(--gray));
text-align: center;
}
.social-links {
display: flex;
justify-content: center;
gap: 1em;
margin-top: 1em;
}
.social-links a {
text-decoration: none;
color: rgb(var(--gray));
}
.social-links a:hover {
color: rgb(var(--gray-dark));
}
</style>
-17
View File
@@ -1,17 +0,0 @@
---
interface Props {
date: Date;
}
const { date } = Astro.props;
---
<time datetime={date.toISOString()}>
{
date.toLocaleDateString('en-us', {
year: 'numeric',
month: 'short',
day: 'numeric',
})
}
</time>
-85
View File
@@ -1,85 +0,0 @@
---
import { SITE_TITLE } from '../consts';
import HeaderLink from './HeaderLink.astro';
---
<header>
<nav>
<h2><a href="/">{SITE_TITLE}</a></h2>
<div class="internal-links">
<HeaderLink href="/">Home</HeaderLink>
<HeaderLink href="/blog">Blog</HeaderLink>
<HeaderLink href="/about">About</HeaderLink>
</div>
<div class="social-links">
<a href="https://m.webtoo.ls/@astro" target="_blank">
<span class="sr-only">Follow Astro on Mastodon</span>
<svg viewBox="0 0 16 16" aria-hidden="true" width="32" height="32"
><path
fill="currentColor"
d="M11.19 12.195c2.016-.24 3.77-1.475 3.99-2.603.348-1.778.32-4.339.32-4.339 0-3.47-2.286-4.488-2.286-4.488C12.062.238 10.083.017 8.027 0h-.05C5.92.017 3.942.238 2.79.765c0 0-2.285 1.017-2.285 4.488l-.002.662c-.004.64-.007 1.35.011 2.091.083 3.394.626 6.74 3.78 7.57 1.454.383 2.703.463 3.709.408 1.823-.1 2.847-.647 2.847-.647l-.06-1.317s-1.303.41-2.767.36c-1.45-.05-2.98-.156-3.215-1.928a3.614 3.614 0 0 1-.033-.496s1.424.346 3.228.428c1.103.05 2.137-.064 3.188-.189zm1.613-2.47H11.13v-4.08c0-.859-.364-1.295-1.091-1.295-.804 0-1.207.517-1.207 1.541v2.233H7.168V5.89c0-1.024-.403-1.541-1.207-1.541-.727 0-1.091.436-1.091 1.296v4.079H3.197V5.522c0-.859.22-1.541.66-2.046.456-.505 1.052-.764 1.793-.764.856 0 1.504.328 1.933.983L8 4.39l.417-.695c.429-.655 1.077-.983 1.934-.983.74 0 1.336.259 1.791.764.442.505.661 1.187.661 2.046v4.203z"
></path></svg
>
</a>
<a href="https://twitter.com/astrodotbuild" target="_blank">
<span class="sr-only">Follow Astro on Twitter</span>
<svg viewBox="0 0 16 16" aria-hidden="true" width="32" height="32"
><path
fill="currentColor"
d="M5.026 15c6.038 0 9.341-5.003 9.341-9.334 0-.14 0-.282-.006-.422A6.685 6.685 0 0 0 16 3.542a6.658 6.658 0 0 1-1.889.518 3.301 3.301 0 0 0 1.447-1.817 6.533 6.533 0 0 1-2.087.793A3.286 3.286 0 0 0 7.875 6.03a9.325 9.325 0 0 1-6.767-3.429 3.289 3.289 0 0 0 1.018 4.382A3.323 3.323 0 0 1 .64 6.575v.045a3.288 3.288 0 0 0 2.632 3.218 3.203 3.203 0 0 1-.865.115 3.23 3.23 0 0 1-.614-.057 3.283 3.283 0 0 0 3.067 2.277A6.588 6.588 0 0 1 .78 13.58a6.32 6.32 0 0 1-.78-.045A9.344 9.344 0 0 0 5.026 15z"
></path></svg
>
</a>
<a href="https://github.com/withastro/astro" target="_blank">
<span class="sr-only">Go to Astro's GitHub repo</span>
<svg viewBox="0 0 16 16" aria-hidden="true" width="32" height="32"
><path
fill="currentColor"
d="M8 0C3.58 0 0 3.58 0 8c0 3.54 2.29 6.53 5.47 7.59.4.07.55-.17.55-.38 0-.19-.01-.82-.01-1.49-2.01.37-2.53-.49-2.69-.94-.09-.23-.48-.94-.82-1.13-.28-.15-.68-.52-.01-.53.63-.01 1.08.58 1.23.82.72 1.21 1.87.87 2.33.66.07-.52.28-.87.51-1.07-1.78-.2-3.64-.89-3.64-3.95 0-.87.31-1.59.82-2.15-.08-.2-.36-1.02.08-2.12 0 0 .67-.21 2.2.82.64-.18 1.32-.27 2-.27.68 0 1.36.09 2 .27 1.53-1.04 2.2-.82 2.2-.82.44 1.1.16 1.92.08 2.12.51.56.82 1.27.82 2.15 0 3.07-1.87 3.75-3.65 3.95.29.25.54.73.54 1.48 0 1.07-.01 1.93-.01 2.2 0 .21.15.46.55.38A8.012 8.012 0 0 0 16 8c0-4.42-3.58-8-8-8z"
></path></svg
>
</a>
</div>
</nav>
</header>
<style>
header {
margin: 0;
padding: 0 1em;
background: white;
box-shadow: 0 2px 8px rgba(var(--black), 5%);
}
h2 {
margin: 0;
font-size: 1em;
}
h2 a,
h2 a.active {
text-decoration: none;
}
nav {
display: flex;
align-items: center;
justify-content: space-between;
}
nav a {
padding: 1em 0.5em;
color: var(--black);
border-bottom: 4px solid transparent;
text-decoration: none;
}
nav a.active {
text-decoration: none;
border-bottom-color: var(--accent);
}
.social-links,
.social-links a {
display: flex;
}
@media (max-width: 720px) {
.social-links {
display: none;
}
}
</style>
-24
View File
@@ -1,24 +0,0 @@
---
import type { HTMLAttributes } from 'astro/types';
type Props = HTMLAttributes<'a'>;
const { href, class: className, ...props } = Astro.props;
const pathname = Astro.url.pathname.replace(import.meta.env.BASE_URL, '');
const subpath = pathname.match(/[^\/]+/g);
const isActive = href === pathname || href === '/' + (subpath?.[0] || '');
---
<a href={href} class:list={[className, { active: isActive }]} {...props}>
<slot />
</a>
<style>
a {
display: inline-block;
text-decoration: none;
}
a.active {
font-weight: bolder;
text-decoration: underline;
}
</style>
+160
View File
@@ -0,0 +1,160 @@
# 📦 Components 组件目录
Firefly 项目中所有可复用组件的集中管理。组件按照功能和职责进行分类,提供清晰的架构和易于维护的代码组织。
## 📁 目录结构
### 🏗️ layout/ - 页面布局组件
负责整体页面框架和布局结构的组件。
- `CategoryBar.astro` - 分类栏组件
- `ConfigCarrier.astro` - 配置载体组件
- `DropdownMenu.astro` - 下拉菜单组件
- `Footer.astro` - 页脚组件
- `Navbar.astro` - 导航栏组件
- `NavMenuPanel.astro` - 导航菜单面板
- `PostCard.astro` - 文章卡片组件
- `PostMeta.astro` - 文章元数据组件
- `PostPage.astro` - 文章页面布局组件
- `SideBar.astro` - 侧边栏组件
### 🎮 controls/ - 导航和交互控件
页面导航和用户交互功能组件。
**导航控件**
- `BackToComment.astro` - 返回评论区按钮
- `BackToHome.astro` - 返回主页按钮
- `BackToTop.astro` - 返回顶部按钮
- `FloatingControls.astro` - 右下角悬浮控件容器
- `FloatingTOC.astro` - 浮动目录组件
- `ScrollDownIndicator.astro` - 向下滚动指示器
- `ArchivePanel.astro` - 归档面板组件(服务端渲染 + 客户端筛选/折叠)
**交互组件**
- `DisplaySettings.svelte` - 显示设置组件
- `DisplaySettingsIntegrated.svelte` - 集成显示设置组件
- `LayoutSwitchButton.svelte` - 布局切换按钮
- `LightDarkSwitch.svelte` - 主题切换组件
- `Search.svelte` - 搜索功能组件
- `WallpaperSwitch.svelte` - 壁纸模式切换组件
### 🔧 common/ - 公共可复用组件
通用的 UI 组件和工具组件,支持跨项目复用。
**基础 UI 组件**
- `ButtonLink.astro` - 链接按钮
- `ButtonTag.astro` - 标签按钮
- `DropdownItem.astro` / `.svelte` - 下拉选项
- `DropdownPanel.astro` / `.svelte` - 下拉面板容器
- `FloatingButton.astro` - 悬浮按钮基础组件
- `Icon.svelte` - 图标组件(带加载状态和错误处理)
- `WidgetLayout.astro` - 小部件布局容器
**内容和展示组件**
- `CoverImage.astro` - 封面图组件(支持本地图片和随机图API)
- `ImageWrapper.astro` - 图片包装器(支持本地和远程图片)
- `Markdown.astro` - Markdown 内容样式包装器
- `PioMessageBox.astro` - 消息框组件(Live2D/Spine 消息显示)
**分页组件**
- `ClientPagination.svelte` - 客户端分页(JavaScript 控制)
- `Pagination.astro` - 静态路由分页(Astro 原生)
### 🧩 widget/ - 小部件
侧边栏中使用的各种功能小部件。
- `Advertisement.astro` - 广告组件
- `Announcement.astro` - 公告组件
- `Calendar.astro` - 日历组件
- `Categories.astro` - 分类组件
- `Music.astro` - 音乐播放器小部件
- `Profile.astro` - 个人信息/社交链接小部件
- `SidebarTOC.astro` - 侧边栏目录组件
- `SiteInfo.astro` - 站点信息组件
- `SiteStats.astro` - 站点统计组件
- `SpineModel.astro` - Spine 看板娘组件
- `Tags.astro` - 标签组件
### ✨ features/ - 全局功能特效组件
全局加载的功能增强和特效组件。
**管理器(初始化和管理功能)**
- `FancyboxManager.astro` - Fancybox 图片查看器管理
- `FontSetup.astro` - 字体加载和管理(基于 Astro Font API)
- `KatexManager.astro` - Katex 数学公式渲染管理
- `MusicManager.astro` - 全局音乐播放管理器(单例,管理唯一 audio 元素和播放状态,通过 CustomEvent 同步所有 MusicPlayer 视图实例)
**功能组件**
- `EncryptedContent.astro` - 加密内容组件
- `EncryptedPost.astro` - 加密文章组件
- `Live2DWidget.astro` - Live2D 看板娘组件
- `MusicPlayer.astro` - 音乐播放器 UI 视图控制器(纯 UI,委托 MusicManager 进行播放控制)
- `SakuraEffect.astro` - 樱花飘落特效
- `SpineModel.astro` - Spine 看板娘组件
- `TypewriterText.astro` - 打字机动画效果
### 📃 pages/ - 页面特定组件
特定页面使用的组件,不用于其他页面。
- `AdvancedSearch.svelte` - 高级搜索组件
**pages/bangumi/** - 番组计划页面组件
- `BangumiGrid.svelte` - 番组网格布局组件
- `BangumiSection.astro` - 番组分类展示组件
- `Card.svelte` - 番组卡片组件
- `FilterControls.svelte` - 筛选控制组件
- `TabNav.svelte` - 标签导航组件
**pages/gallery/** - 相册页面组件
- `AlbumCard.astro` - 相册卡片组件
- `PhotoCard.astro` - 照片卡片组件
### 💬 comment/ - 评论系统组件
第三方评论系统集成组件。
- `index.astro` - 评论主组件
- `Artalk.astro` - Artalk 评论集成
- `Disqus.astro` - Disqus 评论集成
- `Giscus.astro` - Giscus 评论集成(GitHub 讨论)
- `Twikoo.astro` - Twikoo 评论集成
- `Waline.astro` - Waline 评论集成
### 📊 analytics/ - 数据统计组件
网站分析和统计集成组件。
- `GoogleAnalytics.astro` - Google Analytics
- `La51Analytics.astro` - 51la 统计
- `MicrosoftClarity.astro` - Microsoft Clarity
- `UmamiAnalytics.astro` - Umami 统计
### 🔧 misc/ - 杂项工具组件
其他辅助和工具类组件。
- `License.astro` - 许可证信息显示
- `RecommendedPost.astro` - 推荐文章组件
- `SharePoster.svelte` - 分享海报生成
---
## 🗂️ 分类原则
| 分类 | 用途 | 特点 |
|------|------|------|
| **layout/** | 页面布局和结构 | 决定整体页面框架 |
| **controls/** | 导航和交互 | 用户交互功能 |
| **common/** | 通用可复用组件 | 跨多个页面/组件使用 |
| **widget/** | 侧边栏小部件 | 侧边栏特定组件 |
| **features/** | 全局功能特效 | 全局加载的增强功能 |
| **pages/** | 页面特定组件 | 仅在特定页面使用 |
| **comment/** | 评论系统 | 第三方服务集成 |
| **analytics/** | 数据统计 | 分析和统计服务 |
| **misc/** | 工具和辅助 | 其他杂项功能 |
@@ -0,0 +1,19 @@
---
interface Props {
analyticsId: string;
}
const { analyticsId } = Astro.props;
---
<!-- Google tag (gtag.js) -->
<script is:inline data-swup-ignore-script async src={`https://www.googletagmanager.com/gtag/js?id=${analyticsId}`}></script>
<script is:inline data-swup-ignore-script define:vars={{analyticsId}}>window.dataLayer = window.dataLayer || [];
function gtag() {
dataLayer.push(arguments);
}
gtag('js', new Date());
gtag('config', analyticsId);
</script>
@@ -0,0 +1,49 @@
---
interface Props {
analyticsId: string;
sdkUrl?: string;
ck?: string;
autoTrack?: boolean;
hashMode?: boolean;
screenRecord?: boolean;
}
const {
analyticsId,
sdkUrl,
ck,
autoTrack = true,
hashMode = false,
screenRecord = true,
} = Astro.props;
---
<script is:inline data-swup-ignore-script define:vars={{ analyticsId, sdkUrl, ck, autoTrack, hashMode, screenRecord }}>
!(function (p) {
"use strict";
!(function () {
var s = window,
e = document,
i = p,
c = sdkUrl || "".concat(
"https:" === e.location.protocol ? "https://" : "http://",
"sdk.51.la/js-sdk-pro.min.js"
),
n = e.createElement("script"),
r = e.getElementsByTagName("script")[0];
(n.type = "text/javascript"),
n.setAttribute("charset", "UTF-8"),
(n.async = !0),
(n.src = c),
(n.id = "LA_COLLECT"),
(i.d = n);
var o = function () {
s.LA.ids.push(i);
};
s.LA
? s.LA.ids && o()
: ((s.LA = p), (s.LA.ids = []), o()),
r.parentNode.insertBefore(n, r);
})();
})({ id: analyticsId, ck: ck || analyticsId, autoTrack: autoTrack, hashMode: hashMode, screenRecord: screenRecord });
</script>
@@ -0,0 +1,15 @@
---
interface Props {
clarityId: string;
}
const { clarityId } = Astro.props;
---
<script is:inline data-swup-ignore-script define:vars={{ clarityId }}>
(function(c,l,a,r,i,t,y){
c[a]=c[a]||function(){(c[a].q=c[a].q||[]).push(arguments)};
t=l.createElement(r);t.async=1;t.src="https://www.clarity.ms/tag/"+i;
y=l.getElementsByTagName(r)[0];y.parentNode.insertBefore(t,y);
})(window, document, "clarity", "script", clarityId);
</script>
@@ -0,0 +1,88 @@
---
interface Props {
websiteId: string;
scriptUrl?: string;
replaysScriptUrl?: string;
trackOutboundLinks?: boolean;
collectWebVitals?: boolean;
replays?: {
enabled?: boolean;
sampleRate?: number;
maskLevel?: "moderate" | "strict";
maxDuration?: number;
blockSelector?: string;
};
}
const {
websiteId,
scriptUrl,
replaysScriptUrl,
trackOutboundLinks = true,
collectWebVitals = false,
replays,
} = Astro.props;
const replaysEnabled = replays?.enabled ?? false;
const replaysSampleRate = replays?.sampleRate ?? 0.15;
const replaysMaskLevel = replays?.maskLevel ?? "moderate";
const replaysMaxDuration = replays?.maxDuration ?? 300000;
const replaysBlockSelector = replays?.blockSelector?.trim();
---
<script
is:inline
data-swup-ignore-script
defer
src={scriptUrl}
data-website-id={websiteId}
data-performance={collectWebVitals ? "true" : undefined}
></script>
{
replaysEnabled && (
<script
is:inline
data-swup-ignore-script
defer
src={replaysScriptUrl}
data-website-id={websiteId}
data-sample-rate={String(replaysSampleRate)}
data-mask-level={replaysMaskLevel}
data-max-duration={String(replaysMaxDuration)}
data-block-selector={replaysBlockSelector || undefined}
/>
)
}
{
trackOutboundLinks && (
<script is:inline data-swup-ignore-script>
;(() => {
const name = 'outbound-link-click'
const applyOutboundTracking = () => {
document.querySelectorAll('a').forEach((a) => {
if (
a.host !== window.location.host &&
!a.getAttribute('data-umami-event')
) {
a.setAttribute('data-umami-event', name)
a.setAttribute('data-umami-event-url', a.href)
}
})
}
if (document.readyState === 'loading') {
document.addEventListener('DOMContentLoaded', applyOutboundTracking, {
once: true,
})
} else {
applyOutboundTracking()
}
document.addEventListener('astro:page-load', applyOutboundTracking)
})()
</script>
)
}
+50
View File
@@ -0,0 +1,50 @@
---
import { commentConfig, siteConfig } from "@/config";
interface Props {
path: string;
}
const config = {
...commentConfig.artalk,
el: "#artalk",
site: siteConfig.title,
pageKey: Astro.props.path,
dark: "html.dark",
pageTitle: "",
...(commentConfig.artalk?.visitorCount ? { pageview: true } : {}),
};
---
<!-- Artalk -->
<div class="relative w-full">
<!-- 挂载点 -->
<div id="artalk" style="--at-color-main: var(--primary); --at-color-bg: var(--card-bg); --at-color-border: var(--line-divider);"></div>
<!-- 引入 Artalk 样式 -->
<link rel="stylesheet" href="https://unpkg.com/artalk/dist/Artalk.css"/>
<!-- 脚本逻辑 -->
<script type="module" is:inline define:vars={{config}}>
import Artalk from 'https://unpkg.com/artalk/dist/Artalk.mjs';
// 初始化 Artalk
const artalk = Artalk.init(config);
// 深色模式
function updateTheme() {
const isDark = document.documentElement.classList.contains('dark');
artalk.setDarkMode(isDark);
}
updateTheme();
const observer = new MutationObserver((_mutations) => {
updateTheme();
});
observer.observe(document.documentElement, {
attributes: true,
attributeFilter: ['class'],
});
</script>
</div>
+37
View File
@@ -0,0 +1,37 @@
---
import { commentConfig } from "@/config";
interface Props {
identifier: string;
url: string;
title: string;
}
const { identifier, url, title } = Astro.props;
if (!commentConfig?.disqus) {
throw new Error("Disqus comments are not configured");
}
const shortname = commentConfig.disqus.shortname;
---
<div id="disqus_thread"></div>
<script is:inline define:vars={{ shortname, identifier, url, title }}>
// @ts-ignore
window.disqus_config = function () {
this.page.url = url
this.page.identifier = identifier
this.page.title = title
}
;(function () {
var d = document,
s = d.createElement('script')
s.src = 'https://' + shortname + '.disqus.com/embed.js'
s.setAttribute('data-timestamp', new Date().toString())
;(d.head || d.body).appendChild(s)
})()
</script>
<noscript>Please enable JavaScript to view the <a href="https://disqus.com/?ref_noscript">comments powered by Disqus.</a></noscript>
<style is:global></style>
+63
View File
@@ -0,0 +1,63 @@
---
import { commentConfig } from "@/config";
if (!commentConfig?.giscus) {
throw new Error("Giscus comments are not configured");
}
const giscus = commentConfig.giscus;
const lightTheme = "light";
const darkTheme = "dark";
---
<script is:inline type="module" src="https://esm.sh/giscus"></script>
<!--
Giscus 官方Web Component用法,兼容Astro静态输出,无需import包,无需NPM依赖!
参考:https://giscus.app/ 详情配置说明
-->
<giscus-widget
id="comments"
repo={giscus.repo}
repoId={giscus.repoId}
category={giscus.category}
categoryId={giscus.categoryId}
mapping={giscus.mapping}
strict={giscus.strict}
reactionsEnabled={giscus.reactionsEnabled}
emitMetadata={giscus.emitMetadata}
inputPosition={giscus.inputPosition}
theme={lightTheme}
lang={giscus.lang}
loading={giscus.loading}
/>
<script is:inline define:vars={{ lightTheme, darkTheme }}>
function updateGiscusTheme() {
const isDark = document.documentElement.classList.contains('dark');
const theme = isDark ? darkTheme : lightTheme;
const widget = document.querySelector('giscus-widget');
if (widget) {
widget.setAttribute('theme', theme);
}
}
// Initial update
updateGiscusTheme();
// Clean up previous observer if exists
if (window.giscusThemeObserver) {
window.giscusThemeObserver.disconnect();
}
// Create new observer
window.giscusThemeObserver = new MutationObserver((mutations) => {
mutations.forEach((mutation) => {
if (mutation.type === 'attributes' && mutation.attributeName === 'class') {
updateGiscusTheme();
}
});
});
window.giscusThemeObserver.observe(document.documentElement, { attributes: true });
</script>
+93
View File
@@ -0,0 +1,93 @@
---
import { commentConfig } from "@/config/commentConfig";
import { url } from "@/utils/url-utils";
interface Props {
path: string;
}
const twikooConfig = commentConfig.twikoo ?? { envId: "" };
const jsUrl =
twikooConfig.jsUrl ||
"https://registry.npmmirror.com/twikoo/1.7.13/files/dist/twikoo.min.js";
const cssUrl = twikooConfig.cssUrl;
const config = {
...twikooConfig,
el: "#tcomment",
path: Astro.props.path,
};
---
<div id="tcomment"></div>
<script is:inline src={jsUrl}></script>
{cssUrl && <link rel="stylesheet" href={cssUrl.startsWith("http") ? cssUrl : url(cssUrl)} />}
<script is:inline define:vars={{ config }}>
// 获取当前页面路径
function getCurrentPath() {
const pathname = window.location.pathname;
return pathname.endsWith("/") && pathname.length > 1
? pathname.slice(0, -1)
: pathname;
}
// 动态创建配置对象
function createTwikooConfig() {
return {
...config,
path: getCurrentPath(),
el: "#tcomment",
};
}
// 初始化 Twikoo
function initTwikoo() {
if (typeof twikoo !== "undefined") {
const commentEl = document.getElementById("tcomment");
if (commentEl) {
commentEl.innerHTML = "";
const dynamicConfig = createTwikooConfig();
console.log("[Twikoo] 初始化配置:", dynamicConfig);
twikoo
.init(dynamicConfig)
.then(() => {
console.log("[Twikoo] 初始化完成");
})
.catch((error) => {
console.error("[Twikoo] 初始化失败:", error);
});
}
} else {
// 如果 Twikoo 未加载,稍后重试
setTimeout(initTwikoo, 500);
}
}
// 页面加载时初始化
document.addEventListener("DOMContentLoaded", initTwikoo);
// Swup 页面切换后重新初始化
if (window.swup && window.swup.hooks) {
window.swup.hooks.on("content:replace", function () {
setTimeout(initTwikoo, 200);
});
} else {
document.addEventListener("swup:enable", function () {
if (window.swup && window.swup.hooks) {
window.swup.hooks.on("content:replace", function () {
setTimeout(initTwikoo, 200);
});
}
});
}
// 自定义事件监听
document.addEventListener("firefly:page:loaded", function () {
const commentEl = document.getElementById("tcomment");
if (commentEl) {
console.log("[Twikoo] 通过自定义事件重新初始化");
initTwikoo();
}
});
</script>
+25
View File
@@ -0,0 +1,25 @@
---
import { commentConfig } from "@/config";
interface Props {
path: string;
}
const config = {
...commentConfig.waline,
el: "#waline",
path: Astro.props.path,
dark: "html.dark",
wordLimit: ["2", "300"],
...(commentConfig.waline?.visitorCount ? { pageview: true } : {}),
};
---
<!-- Waline -->
<div class="relative w-full">
<div id="waline"></div>
<link rel="stylesheet" href="https://unpkg.com/@waline/client@v3/dist/waline.css" />
<script type="module" is:inline define:vars={{ config }}>
import { init } from 'https://unpkg.com/@waline/client@v3/dist/waline.js';
init(config);
</script>
</div>
+77
View File
@@ -0,0 +1,77 @@
---
import type { CollectionEntry } from "astro:content";
import { commentConfig } from "@/config/commentConfig";
import Key from "@/i18n/i18nKey";
import { i18n } from "@/i18n/translation";
import { removeFileExtension } from "@/utils/url-utils";
import Artalk from "./Artalk.astro";
import Disqus from "./Disqus.astro";
import Giscus from "./Giscus.astro";
import Twikoo from "./Twikoo.astro";
import Waline from "./Waline.astro";
interface Props {
post?: CollectionEntry<"posts"> | CollectionEntry<"spec">;
customPath?: string;
title?: string;
}
const { post, customPath, title: customTitle } = Astro.props as Props;
// 根据页面类型确定路径
const slugFromPath = (customPath || "/").replace(/^\/+|\/+$/g, "") || "index";
const slug = post ? removeFileExtension(post.id) : slugFromPath;
const path = customPath
? customPath
: post
? post.collection === "posts"
? `/posts/${slug}`
: `/${slug}`
: `/${slug}`;
const url = `${Astro.site?.href}${path}`;
const postTitle = post && "title" in post.data ? post.data.title : undefined;
// 强制commentService类型为string,避免类型不兼容警告
let commentService: string = commentConfig?.type || "none";
---
{
commentService !== "none" && (
<div id="post-comments" class="card-base p-8 mb-6 relative overflow-hidden">
<!-- 评论区装饰性背景 -->
<div class="absolute top-0 right-0 w-32 h-32 opacity-5 pointer-events-none">
<svg viewBox="0 0 100 100" class="w-full h-full">
<circle cx="50" cy="50" r="40" fill="currentColor" class="text-(--primary)" />
<circle cx="50" cy="50" r="25" fill="none" stroke="currentColor" stroke-width="2" class="text-(--primary)" />
<circle cx="50" cy="50" r="10" fill="currentColor" class="text-(--primary)" />
</svg>
</div>
<!-- 评论区标题 -->
<div class="relative z-10 mb-6">
<div class="flex items-center gap-3 mb-2">
<div class="w-1 h-6 bg-linear-to-b from-(--primary) to-transparent rounded-full"></div>
<h3 class="text-xl font-bold text-(--btn-content)">{i18n(Key.commentSection)}</h3>
</div>
<p class="text-sm text-(--content-meta) ml-4">{i18n(Key.commentSubtitle)}</p>
</div>
<!-- 评论内容区域 -->
<div class="relative z-10 pl-2 pr-2">
{commentService === "twikoo" && <Twikoo path={path} />}
{commentService === "waline" && <Waline path={path} />}
{commentService === "giscus" && <Giscus />}
{commentService === "disqus" && <Disqus identifier={slug} url={url} title={customTitle || postTitle || slug} />}
{commentService === "artalk" && <Artalk path={path} />}
{commentService === "none" && (
<div class="text-center py-8 text-(--content-meta)">
<div class="w-16 h-16 mx-auto mb-4 rounded-full bg-(--btn-regular-bg) flex items-center justify-center">
<svg class="w-8 h-8 text-(--primary)" fill="none" stroke="currentColor" viewBox="0 0 24 24">
<path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M8 12h.01M12 12h.01M16 12h.01M21 12c0 4.418-4.03 8-9 8a9.863 9.863 0 01-4.255-.949L3 20l1.395-3.72C3.512 15.042 3 13.574 3 12c0-4.418 4.03-8 9-8s9 3.582 9 8z"></path>
</svg>
</div>
<p>{i18n(Key.commentNotConfigured)}</p>
</div>
)}
</div>
</div>
)
}
+43
View File
@@ -0,0 +1,43 @@
---
interface Props {
badge?: string;
url?: string;
label?: string;
}
const { badge, url, label } = Astro.props;
---
<a href={url} aria-label={label}>
<button
class:list={`
w-full
h-10
rounded-lg
bg-none
hover:bg-(--btn-plain-bg-hover)
active:bg-(--btn-plain-bg-active)
transition-all
pl-2
hover:pl-3
text-neutral-700
hover:text-(--primary)
dark:text-neutral-300
dark:hover:text-(--primary)
`
}
>
<div class="flex items-center justify-between relative mr-2">
<div class="overflow-hidden text-left whitespace-nowrap text-ellipsis ">
<slot></slot>
</div>
{ badge !== undefined && badge !== null && badge !== '' &&
<div class="transition px-2 h-7 ml-4 min-w-8 rounded-lg text-sm font-bold
text-(--btn-content) dark:text-(--deep-text)
bg-[oklch(0.95_0.025_var(--hue))] dark:bg-(--primary)
flex items-center justify-center">
{ badge }
</div>
}
</div>
</button>
</a>
+15
View File
@@ -0,0 +1,15 @@
---
interface Props {
size?: string;
dot?: boolean;
href?: string;
label?: string;
}
const { dot, href, label }: Props = Astro.props;
---
<a href={href} aria-label={label} class="transition text-sm font-medium px-3 py-1.5 rounded-full
bg-black/5 dark:bg-white/10 text-neutral-500 dark:text-neutral-400
hover:bg-(--btn-regular-bg) hover:text-(--btn-content)">
{dot && <div class="h-1 w-1 bg-(--btn-content) dark:bg-(--card-bg) transition rounded-md mr-2"></div>}
<slot></slot>
</a>
@@ -0,0 +1,186 @@
<script lang="ts">
interface Props {
totalItems: number;
itemsPerPage: number;
currentPage: number;
onPageChange: (page: number) => void;
}
const { totalItems, itemsPerPage, currentPage, onPageChange }: Props = $props();
const totalPages = $derived(Math.ceil(totalItems / itemsPerPage));
function generatePageNumbers(
current: number,
total: number,
): (number | string)[] {
if (total <= 7) {
return Array.from({ length: total }, (_, i) => i + 1);
}
const delta = 2;
const left = Math.max(2, current - delta);
const right = Math.min(total - 1, current + delta);
const pages: (number | string)[] = [1];
if (left > 2) pages.push("...");
for (let i = left; i <= right; i++) pages.push(i);
if (right < total - 1) pages.push("...");
if (total > 1) pages.push(total);
return pages;
}
const pageNumbers = $derived(generatePageNumbers(currentPage, totalPages));
function goToPage(page: number) {
if (page >= 1 && page <= totalPages && page !== currentPage) {
onPageChange(page);
}
}
</script>
{#if totalPages > 1}
<div class="responsive-pagination flex justify-center items-center mt-8">
<!-- 移动端简化版分页 -->
<div class="mobile-pagination items-center gap-3">
<button
type="button"
class="btn-card overflow-hidden rounded-lg text-(--primary) w-11 h-11 disabled:opacity-50 disabled:cursor-not-allowed"
onclick={() => goToPage(currentPage - 1)}
disabled={currentPage === 1}
aria-label="上一页"
>
<svg class="w-7 h-7" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><path d="M15 18l-6-6 6-6"/></svg>
</button>
<div class="btn-card flex items-center rounded-lg px-4 h-11 gap-1.5">
<span class="text-base font-bold text-(--primary)">{currentPage}</span>
<span class="text-sm text-neutral-500 dark:text-neutral-500">/</span>
<span class="text-base font-bold text-neutral-700 dark:text-neutral-300">{totalPages}</span>
</div>
<button
type="button"
class="btn-card overflow-hidden rounded-lg text-(--primary) w-11 h-11 disabled:opacity-50 disabled:cursor-not-allowed"
onclick={() => goToPage(currentPage + 1)}
disabled={currentPage === totalPages}
aria-label="下一页"
>
<svg class="w-7 h-7" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><path d="M9 18l6-6-6-6"/></svg>
</button>
</div>
<!-- 桌面端完整版分页 -->
<div class="desktop-pagination items-center gap-3">
<button
type="button"
class="btn-card overflow-hidden rounded-lg text-(--primary) w-11 h-11 disabled:opacity-50 disabled:cursor-not-allowed"
onclick={() => goToPage(currentPage - 1)}
disabled={currentPage === 1}
aria-label="上一页"
>
<svg class="w-7 h-7" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><path d="M15 18l-6-6 6-6"/></svg>
</button>
{#each pageNumbers as pageItem}
{#if pageItem === "..."}
<svg class="w-11 h-11 flex items-center justify-center text-neutral-700 dark:text-neutral-300" width="24" height="24" viewBox="0 0 24 24"><path fill="currentColor" d="M6 10c-1.1 0-2 .9-2 2s.9 2 2 2 2-.9 2-2-.9-2-2-2zm12 0c-1.1 0-2 .9-2 2s.9 2 2 2 2-.9 2-2-.9-2-2-2zm-6 0c-1.1 0-2 .9-2 2s.9 2 2 2 2-.9 2-2-.9-2-2-2z"/></svg>
{:else}
<button
type="button"
class="rounded-lg overflow-hidden w-11 h-11 flex items-center justify-center font-bold {pageItem === currentPage
? 'bg-(--primary) text-white dark:text-black/70'
: 'btn-card active:scale-[0.85] text-neutral-700 dark:text-neutral-300'}"
onclick={() => goToPage(pageItem as number)}
aria-label="{String(pageItem)}"
aria-current={pageItem === currentPage ? 'page' : undefined}
>
{pageItem}
</button>
{/if}
{/each}
<button
type="button"
class="btn-card overflow-hidden rounded-lg text-(--primary) w-11 h-11 disabled:opacity-50 disabled:cursor-not-allowed"
onclick={() => goToPage(currentPage + 1)}
disabled={currentPage === totalPages}
aria-label="下一页"
>
<svg class="w-7 h-7" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><path d="M9 18l6-6-6-6"/></svg>
</button>
</div>
</div>
{/if}
<style>
.responsive-pagination {
max-width: 100%;
overflow-x: auto;
-webkit-overflow-scrolling: touch;
}
.mobile-pagination {
display: flex;
padding: 0 1rem;
}
.desktop-pagination {
display: none;
}
@media (min-width: 1024px) {
.mobile-pagination {
display: none;
}
.desktop-pagination {
display: flex;
}
}
@media (max-width: 640px) {
.mobile-pagination {
padding: 0 0.5rem;
}
}
@media (max-width: 480px) {
.mobile-pagination {
padding: 0 0.25rem;
}
}
.responsive-pagination button {
transition: all 0.2s ease-in-out;
}
@media (prefers-contrast: high) {
.responsive-pagination button {
border: 1px solid currentColor;
}
}
@media (prefers-reduced-motion: reduce) {
.responsive-pagination button {
transition: none;
}
}
@media (hover: none) and (pointer: coarse) {
.responsive-pagination button {
min-height: 44px;
min-width: 44px;
}
.mobile-pagination button {
min-height: 40px;
min-width: 40px;
}
}
@media (max-width: 1024px) and (orientation: landscape) {
.mobile-pagination {
padding: 0 0.5rem;
}
}
</style>
+353
View File
@@ -0,0 +1,353 @@
---
import { Picture } from "astro:assets";
import * as path from "node:path";
import type { ImageMetadata } from "astro";
import { coverImageConfig } from "@/config";
import type { ImageFormat, ResponsiveImageLayout } from "@/types/config";
import {
getFallbackFormat,
getImageFormats,
getImageQuality,
shouldAddNoReferrer,
} from "@/utils/image-utils";
import { getLqipProps } from "@/utils/lqip-utils";
import { url } from "@/utils/url-utils";
interface Props {
id?: string;
src: string;
class?: string;
alt?: string;
position?: string;
basePath?: string;
preview?: boolean;
layout?: ResponsiveImageLayout;
formats?: ImageFormat[];
loading?: "lazy" | "eager";
apiUrls?: string[];
}
const {
id,
src,
alt,
position = "center",
basePath = "/",
preview = false,
layout = "constrained",
formats = getImageFormats(),
loading = "lazy",
apiUrls = [],
} = Astro.props;
const configQuality = getImageQuality();
const fallbackFormat = getFallbackFormat();
const className = Astro.props.class;
// 判断图片类型
const isLocal = !(
src.startsWith("/") ||
src.startsWith("http") ||
src.startsWith("https") ||
src.startsWith("data:")
);
const isPublic = src.startsWith("/");
// 动态导入本地图片
let img: ImageMetadata | null = null;
if (isLocal) {
const files = import.meta.glob<ImageMetadata>(
"../../**/*.{png,jpg,jpeg,webp,avif}",
{
import: "default",
},
);
const normalizedPath = path
.normalize(path.join("../../", basePath, src))
.replace(/\\/g, "/");
const file = files[normalizedPath];
if (file) {
img = await file();
} else {
console.error(
`[ERROR] Image not found: ${normalizedPath.replace("../../", "src/")}`,
);
}
}
// 加载回退图片
let fallbackImg: ImageMetadata | null = null;
const fallbackPath = coverImageConfig.randomCoverImage.fallback;
const isFallbackPublic = fallbackPath?.startsWith("/");
if (fallbackPath && !isLocal && !isFallbackPublic) {
const files = import.meta.glob<ImageMetadata>(
"../../**/*.{png,jpg,jpeg,webp,avif}",
{
import: "default",
},
);
const normalizedFallbackPath = path
.normalize(path.join("../../", fallbackPath))
.replace(/\\/g, "/");
const file = files[normalizedFallbackPath];
if (file) {
fallbackImg = await file();
}
}
// 图片样式
const imageClass =
"w-full h-full object-cover opacity-0 transition-opacity duration-500 ease-out";
const imageStyle = `object-position: ${position};`;
// LQIP 渐变占位
const lqipProps = isLocal
? getLqipProps(src, basePath)
: isPublic
? getLqipProps(src, basePath, true)
: getLqipProps(src);
// 响应式配置
const widths = preview ? [320, 480, 640, 960] : [800, 1200, 1600, 2000];
const sizes = preview
? "(max-width: 640px) 100vw, (max-width: 1024px) 50vw, 320px"
: "(max-width: 768px) 100vw, (max-width: 1200px) 90vw, 1200px";
const quality = preview ? Math.round(configQuality * 0.9) : configQuality;
const getPictureSizeProps = (image: ImageMetadata) => {
if (preview) {
return { width: 400, height: 300, widths, sizes };
}
const baseHeight = Math.round(1200 / (image.width / image.height));
return { width: 1200, height: baseHeight, widths, sizes };
};
// 是否显示加载动画
const showLoading = coverImageConfig.randomCoverImage.showLoading ?? true;
// 检查回退图片是否需要 referrerpolicy
const fallbackReferrerPolicy =
isFallbackPublic && fallbackPath && shouldAddNoReferrer(url(fallbackPath))
? "no-referrer"
: undefined;
// 检查远程图片是否需要 referrerpolicy
const remoteReferrerPolicy =
!isLocal && shouldAddNoReferrer(isPublic ? url(src) : src)
? "no-referrer"
: undefined;
---
<div
id={id}
class:list={[className, "cover-image-container overflow-hidden relative"]}
data-loading={showLoading ? "true" : "false"}
data-api-urls={apiUrls.length > 0 ? JSON.stringify(apiUrls) : undefined}
>
<!-- LQIP 渐变占位 -->
<div class="lqip-placeholder absolute inset-0 pointer-events-none" style={lqipProps.style} aria-hidden="true"></div>
<!-- 加载动画 -->
{showLoading && (
<div class="loading-spinner absolute inset-0 flex items-center justify-center z-10" style="background-color: var(--card-bg);">
<div class="spinner"></div>
</div>
)}
<!-- 错误提示(覆盖在回退图片上) -->
<div class="error-message absolute inset-0 items-center justify-center z-20 hidden pointer-events-none">
<span class="text-white text-sm px-3 py-1 rounded-sm bg-black/50">Image API Error</span>
</div>
<!-- 回退图片(错误时显示) -->
{fallbackImg && (
<div class="fallback-image absolute inset-0 hidden">
<Picture
src={fallbackImg}
alt="Fallback cover"
class={imageClass}
style={imageStyle}
loading="lazy"
formats={formats}
fallbackFormat={fallbackFormat}
quality={quality}
layout={layout}
{...getPictureSizeProps(fallbackImg)}
/>
</div>
)}
{!fallbackImg && isFallbackPublic && fallbackPath && (
<div class="fallback-image absolute inset-0 hidden">
<img
src={url(fallbackPath)}
alt="Fallback cover"
class={imageClass}
style={imageStyle}
loading="lazy"
decoding="async"
referrerpolicy={fallbackReferrerPolicy}
/>
</div>
)}
<!-- 本地图片 -->
{isLocal && img && (
<Picture
src={img}
alt={alt || ""}
class={imageClass}
style={imageStyle}
loading={loading}
formats={formats}
fallbackFormat={fallbackFormat}
quality={quality}
layout={layout}
{...getPictureSizeProps(img)}
data-cover-img
/>
)}
<!-- 远程图片 -->
{!isLocal && (
<img
src={isPublic ? url(src) : src}
alt={alt || ""}
class={imageClass}
style={imageStyle}
loading={loading}
decoding="async"
data-cover-img
data-remote="true"
referrerpolicy={remoteReferrerPolicy}
/>
)}
</div>
<style>
.cover-image-container {
min-height: 150px;
}
@media (min-width: 768px) {
.cover-image-container {
min-height: 0;
}
}
/* 加载动画容器 */
.loading-spinner {
transition: opacity 0.3s ease-out;
}
/* 加载完成后隐藏 */
.cover-image-container[data-loading="false"] .loading-spinner {
opacity: 0;
pointer-events: none;
}
/* 错误状态隐藏加载动画 */
.cover-image-container[data-error="true"] .loading-spinner {
display: none;
}
/* 错误状态显示错误信息和回退图片 */
.cover-image-container[data-error="true"] .error-message {
display: flex;
}
.cover-image-container[data-error="true"] .fallback-image {
display: block;
}
/* 错误状态隐藏失败的远程图片 */
.cover-image-container[data-error="true"] img[data-remote="true"] {
display: none;
}
/* 旋转加载动画 */
.spinner {
width: 40px;
height: 40px;
border: 3px solid oklch(0.9 0.05 var(--hue));
border-top-color: oklch(0.6 0.15 var(--hue));
border-radius: 50%;
animation: spin 0.8s linear infinite;
}
@keyframes spin {
to {
transform: rotate(360deg);
}
}
/* 图片样式 */
.cover-image-container img {
width: 100%;
height: 100%;
object-fit: cover;
}
</style>
<script>
function initCoverImages() {
const containers = document.querySelectorAll('.cover-image-container');
containers.forEach((container) => {
if (container.hasAttribute('data-initialized')) return;
container.setAttribute('data-initialized', 'true');
const img = container.querySelector('img[data-cover-img]') as HTMLImageElement | null;
if (!img) return;
// 解析API URL列表,用于按顺序重试
let apiUrls: string[] = [];
let currentApiIndex = 1; // 0号已由服务端设为img.src
const apiUrlsAttr = container.getAttribute('data-api-urls');
if (apiUrlsAttr) {
try { apiUrls = JSON.parse(apiUrlsAttr); } catch (_e) { /* ignore */ }
}
const hideLoading = () => {
container.setAttribute('data-loading', 'false');
img.style.opacity = '1';
const placeholder = container.querySelector('.lqip-placeholder') as HTMLElement | null;
if (placeholder) placeholder.classList.add('loaded');
};
const showError = () => {
container.setAttribute('data-loading', 'false');
container.setAttribute('data-error', 'true');
const placeholder = container.querySelector('.lqip-placeholder') as HTMLElement | null;
if (placeholder) placeholder.classList.add('loaded');
};
// 统一的错误处理:尝试下一个API或显示回退
const onError = () => {
if (img.dataset.remote !== 'true') return;
if (currentApiIndex < apiUrls.length) {
// 先绑定好事件,再更换src
img.addEventListener('load', hideLoading, { once: true });
img.addEventListener('error', onError, { once: true });
img.src = apiUrls[currentApiIndex];
currentApiIndex++;
} else {
showError();
}
};
if (img.complete) {
if (img.naturalWidth > 0) {
hideLoading();
} else {
onError();
}
} else {
img.addEventListener('load', hideLoading, { once: true });
img.addEventListener('error', onError, { once: true });
}
});
}
initCoverImages();
document.addEventListener('astro:page-load', initCoverImages);
</script>
+41
View File
@@ -0,0 +1,41 @@
---
/**
* 公共下拉面板选项组件
* 用于下拉面板中的选项项
*/
interface Props {
href?: string;
target?: string;
isActive?: boolean;
isLast?: boolean;
class?: string;
onclick?: string;
}
const {
href,
target,
isActive = false,
isLast = false,
class: className,
onclick,
} = Astro.props;
const baseClasses =
"flex transition whitespace-nowrap items-center justify-start! w-full btn-plain scale-animation rounded-lg h-9 px-3 font-medium active:scale-95";
const spacingClass = isLast ? "" : "mb-0.5";
const activeClass = isActive ? "current-theme-btn" : "";
const allClasses =
`${baseClasses} ${spacingClass} ${activeClass} ${className || ""}`.trim();
const Tag = href ? "a" : "button";
---
<Tag
href={href}
target={target}
class={allClasses}
onclick={onclick}
>
<slot />
</Tag>
+47
View File
@@ -0,0 +1,47 @@
<script lang="ts">
/**
* 公共下拉面板选项组件 (Svelte 5 版本)
* 用于下拉面板中的选项项
*/
import type { Snippet } from "svelte";
interface Props {
isActive?: boolean;
isLast?: boolean;
class?: string;
onclick?: (event: MouseEvent) => void;
role?: string;
children?: Snippet;
}
let {
isActive = false,
isLast = false,
class: className = "",
onclick,
role,
children,
...restProps
}: Props = $props();
const baseClasses =
"flex transition whitespace-nowrap items-center justify-start! w-full btn-plain scale-animation rounded-lg h-9 px-3 font-medium active:scale-95";
// 使用 $derived 使类名响应式
const allClasses = $derived.by(() => {
const spacingClass = isLast ? "" : "mb-0.5";
const activeClass = isActive ? "current-theme-btn" : "";
return `${baseClasses} ${spacingClass} ${activeClass} ${className}`.trim();
});
</script>
<button
class={allClasses}
{onclick}
{role}
{...restProps}
>
{#if children}
{@render children()}
{/if}
</button>
+15
View File
@@ -0,0 +1,15 @@
---
/**
* 公共下拉面板组件
* 用于壁纸切换、亮暗色切换、导航栏菜单等下拉面板
*/
interface Props {
class?: string;
}
const { class: className } = Astro.props;
---
<div class:list={["float-panel p-2", className]} role="none">
<slot />
</div>
@@ -0,0 +1,20 @@
<script lang="ts">
/**
* 公共下拉面板组件 (Svelte 5 版本)
* 用于壁纸切换、亮暗色切换等下拉面板
*/
import type { Snippet } from "svelte";
interface Props {
class?: string;
children?: Snippet;
}
let { class: className = "", children, ...restProps }: Props = $props();
</script>
<div class={`float-panel p-2 ${className}`.trim()} role="none" {...restProps}>
{#if children}
{@render children()}
{/if}
</div>
+189
View File
@@ -0,0 +1,189 @@
---
import { Icon } from "astro-icon/components";
/****
* FloatingButton 组件
* 用于创建一个悬浮按钮,支持图标、点击事件和可选的辅助标签。
*/
interface Props {
id: string;
icon: string;
/** 可选的第二图标:提供后,按钮加上 .toggled 类时显示此图标、隐藏默认图标 */
toggleIcon?: string;
ariaLabel?: string;
onclick?: string;
class?: string;
}
const {
id,
icon,
toggleIcon,
ariaLabel,
onclick,
class: className = "",
} = Astro.props;
---
<div
id={id}
class:list={["floating-btn", className, "card-base flex items-center rounded-2xl overflow-hidden transition"]}
onclick={onclick}
>
<button
aria-label={ariaLabel}
class:list={["h-full w-full rounded-2xl", toggleIcon && "has-toggle-icon"]}
>
<Icon is:inline name={icon} class:list={["mx-auto", toggleIcon && "icon-default"]} />
{toggleIcon && <Icon is:inline name={toggleIcon} class="icon-toggled" />}
</button>
</div>
<style lang="stylus">
.floating-btn
color: var(--primary)
font-size: 1.5rem
font-weight: bold
width: 3rem
height: 3rem
opacity: 1
cursor: pointer
pointer-events: auto
/* 默认状态(显示):各属性平滑过渡 */
transition: all 0.3s cubic-bezier(0.4, 0, 0.2, 1)
border-radius: 1rem
backdrop-filter: blur(12px)
background-color: var(--card-bg)
border: 1px solid rgba(0, 0, 0, 0.1)
flex-shrink: 0
overflow: hidden
/* 图标样式 */
:global(svg)
font-size: 1.6rem
opacity: 1
transition: opacity 0.2s ease 0.1s /* 显示时:延迟出现,通过 delay 避免"先出现icon" */
/* 双图标切换:两个图标叠放在按钮正中(grid 同格),靠 .toggled 切换显隐 */
button.has-toggle-icon
display: grid
place-items: center
:global(svg)
grid-area: 1 / 1
:global(svg.icon-toggled)
display: none
&.toggled
/* 面板展开时的选中态背景 */
background-color: var(--btn-regular-bg)
:global(svg.icon-default)
display: none
:global(svg.icon-toggled)
display: block
&:hover
background-color: var(--btn-regular-bg-hover)
&.hide
/* 隐藏状态:缩小并收起布局 */
transform: scale(0.5)
opacity: 0
pointer-events: none
/* 强制收缩布局占用 */
height: 0 !important
width: 0 !important
margin: 0 !important
border-width: 0 !important
padding: 0 !important
/* 隐藏时:不需要 delay,与布局同时(或稍快)消失 */
/* 由于 width/height 也在变,all cover全部。关键是 inner element 必须快 */
:global(svg)
opacity: 0
transition: opacity 0.1s ease /* 隐藏时:立即消失,解决"icon最后消失" */
&:active
transform: scale(0.9)
&:hover
background-color: var(--btn-card-bg-hover)
color: var(--primary)
box-shadow: var(--shadow-button)
/* 暗色主题样式 */
:global(.dark) .floating-btn
background-color: var(--card-bg)
border: 1px solid rgba(255, 255, 255, 0.15)
color: var(--primary, #60a5fa)
&:hover
background-color: var(--btn-card-bg-hover)
color: var(--primary)
box-shadow: var(--shadow-button-dark)
&.toggled
background-color: var(--btn-regular-bg)
&:hover
background-color: var(--btn-regular-bg-hover)
/* 响应式调整 */
@media (max-width: 768px)
.floating-btn
width: 3rem
height: 3rem
font-size: 1.5rem
border-radius: 0.75rem
:global(svg)
font-size: 1.5rem
@media (max-width: 480px)
.floating-btn
width: 2.5rem
height: 2.5rem
font-size: 1.25rem
border-radius: 0.5rem
:global(svg)
font-size: 1.2rem
@media (max-width: 360px)
.floating-btn
width: 2rem
height: 2rem
font-size: 1rem
border-radius: 0.375rem
:global(svg)
font-size: 1rem
@media (max-width: 320px)
.floating-btn
width: 1.75rem
height: 1.75rem
font-size: 0.875rem
border-radius: 0.25rem
:global(svg)
font-size: 0.875rem
/* 确保按钮始终在可视区域内 */
.floating-btn
min-width: 0
min-height: 0
padding: 0.25rem
border-radius: 1rem !important
&.hide
padding: 0
/* 高DPI屏幕优化 */
@media (-webkit-min-device-pixel-ratio: 2), (min-resolution: 192dpi)
.floating-btn
image-rendering: -webkit-optimize-contrast
image-rendering: crisp-edges
</style>
+80
View File
@@ -0,0 +1,80 @@
<script lang="ts">
/**
* 统一的图标组件 - 构建时内联 SVG
* 用于 Svelte 组件
*
* 图标在构建时由 scripts/generate-icons.js 自动扫描并内联
* 无需运行时 API 请求,零延迟加载
*
* 因为如果使用@iconify/svelte搭配unplugin-icons的方式会导致使用方法繁琐了,所以改为这种预构建内联SVG的方式。
*/
import { getIconSvg, hasIcon } from "@/constants/icons";
interface Props {
icon: string;
class?: string;
style?: string;
size?: "xs" | "sm" | "md" | "lg" | "xl" | "2xl";
color?: string;
}
let {
icon,
class: className = "",
style = "",
size = "md",
color,
}: Props = $props();
// 尺寸映射
const sizeClasses: Record<string, string> = {
xs: "text-xs",
sm: "text-sm",
md: "text-base",
lg: "text-lg",
xl: "text-xl",
"2xl": "text-2xl",
};
const sizeClass = $derived(sizeClasses[size] || sizeClasses.md);
const colorStyle = $derived(color ? `color: ${color};` : "");
const combinedStyle = $derived(`${colorStyle}${style}`);
const combinedClass = $derived(`${sizeClass} ${className}`.trim());
// 获取内联 SVG
const svgContent = $derived(getIconSvg(icon));
const iconExists = $derived(hasIcon(icon));
</script>
{#if iconExists && svgContent}
<!-- 使用预加载的内联 SVG -->
<span
class="inline-icon inline-flex items-center justify-center {combinedClass}"
style={combinedStyle}
aria-hidden="true"
>
{@html svgContent}
</span>
{:else}
<!-- 回退:图标未找到时显示占位符 -->
<span
class="inline-icon inline-flex items-center justify-center {combinedClass}"
style={combinedStyle}
aria-hidden="true"
title="Icon not found: {icon}"
>
<svg xmlns="http://www.w3.org/2000/svg" width="1em" height="1em" viewBox="0 0 24 24">
<circle cx="12" cy="12" r="10" fill="none" stroke="currentColor" stroke-width="2" opacity="0.3"/>
</svg>
</span>
{/if}
<style>
.inline-icon :global(svg) {
width: 1em;
height: 1em;
display: inline-block;
vertical-align: middle;
fill: currentColor;
}
</style>
+135
View File
@@ -0,0 +1,135 @@
---
import { Image, Picture } from "astro:assets";
import * as path from "node:path";
import type { ImageMetadata } from "astro";
import type { ImageFormat, ResponsiveImageLayout } from "@/types/config";
import {
getFallbackFormat,
getImageFormats,
getImageQuality,
shouldAddNoReferrer,
} from "@/utils/image-utils";
import { getLqipProps } from "@/utils/lqip-utils";
import { url } from "@/utils/url-utils";
interface Props {
id?: string;
src: string;
class?: string;
alt?: string;
position?: string;
basePath?: string;
loading?: "lazy" | "eager";
fetchpriority?: "high" | "low" | "auto";
// 响应式图像属性
layout?: ResponsiveImageLayout;
usePicture?: boolean;
formats?: ImageFormat[];
widths?: number[];
sizes?: string;
quality?: number;
}
const {
id,
src,
alt,
position = "center",
basePath = "/",
loading = "lazy",
fetchpriority = "auto",
layout = "constrained",
usePicture = true,
formats = getImageFormats(),
widths,
sizes,
quality = getImageQuality(),
} = Astro.props;
const fallbackFormat = getFallbackFormat();
const className = Astro.props.class;
const isLocal = !(
src.startsWith("/") ||
src.startsWith("http") ||
src.startsWith("https") ||
src.startsWith("data:")
);
const isPublic = src.startsWith("/");
// TODO temporary workaround for images dynamic import
// https://github.com/withastro/astro/issues/3373
let img: ImageMetadata | null = null;
if (isLocal) {
const files = import.meta.glob<ImageMetadata>(
"../../**/*.{png,jpg,jpeg,webp,avif}",
{
import: "default",
},
);
let normalizedPath = path
.normalize(path.join("../../", basePath, src))
.replace(/\\/g, "/");
const file = files[normalizedPath];
if (!file) {
console.error(
`\n[ERROR] Image file not found: ${normalizedPath.replace("../../", "src/")}`,
);
} else {
img = await file();
}
}
const imageClass =
"w-full h-full object-cover opacity-0 transition-opacity duration-500 ease-out";
const imageStyle = `object-position: ${position}`;
// 检查是否需要添加 referrerpolicy(仅对非本地图片)
const fullSrc = isPublic ? url(src) : src;
const referrerPolicy =
!isLocal && shouldAddNoReferrer(fullSrc) ? "no-referrer" : undefined;
// 构建响应式图像属性
const responsiveProps = {
...(layout && { layout }),
...(widths && { widths }),
...(sizes && { sizes }),
...(quality && { quality }),
};
// LQIP 渐变占位
const lqipProps = isLocal
? getLqipProps(src, basePath)
: isPublic
? getLqipProps(src, basePath, true)
: getLqipProps(src);
---
<div id={id} class:list={[className, 'overflow-hidden relative']}>
<div class="lqip-placeholder absolute inset-0 pointer-events-none" style={lqipProps.style} aria-hidden="true"></div>
<div class="transition absolute inset-0 dark:bg-black/10 pointer-events-none"></div>
{isLocal && img && usePicture && (
<Picture
src={img}
alt={alt || ""}
class={imageClass}
style={imageStyle}
loading={loading}
fetchpriority={fetchpriority}
formats={formats}
fallbackFormat={fallbackFormat}
{...responsiveProps}
/>
)}
{isLocal && img && !usePicture && (
<Image
src={img}
alt={alt || ""}
class={imageClass}
style={imageStyle}
loading={loading}
fetchpriority={fetchpriority}
{...responsiveProps}
/>
)}
{!isLocal && <img src={isPublic ? url(src) : src} alt={alt || ""} class={imageClass} style={imageStyle} loading={loading} fetchpriority={fetchpriority} referrerpolicy={referrerPolicy} />}
</div>
+9
View File
@@ -0,0 +1,9 @@
---
interface Props {
class: string;
}
const className = Astro.props.class;
---
<div data-pagefind-body class={`prose dark:prose-invert prose-base max-w-none! custom-md ${className}`}>
<slot/>
</div>
+207
View File
@@ -0,0 +1,207 @@
---
import type { Page } from "astro";
import { Icon } from "astro-icon/components";
import I18nKey from "@/i18n/i18nKey";
import { i18n } from "@/i18n/translation";
import { url } from "@/utils/url-utils";
interface Props {
page: Page;
class?: string;
style?: string;
}
const { page, style } = Astro.props;
const HIDDEN = -1;
const className = Astro.props.class;
const ADJ_DIST = 2;
const VISIBLE = ADJ_DIST * 2 + 1;
// for test
let count = 1;
let l = page.currentPage;
let r = page.currentPage;
while (0 < l - 1 && r + 1 <= page.lastPage && count + 2 <= VISIBLE) {
count += 2;
l--;
r++;
}
while (0 < l - 1 && count < VISIBLE) {
count++;
l--;
}
while (r + 1 <= page.lastPage && count < VISIBLE) {
count++;
r++;
}
let pages: number[] = [];
if (l > 1) pages.push(1);
if (l === 3) pages.push(2);
if (l > 3) pages.push(HIDDEN);
for (let i = l; i <= r; i++) pages.push(i);
if (r < page.lastPage - 2) pages.push(HIDDEN);
if (r === page.lastPage - 2) pages.push(page.lastPage - 1);
if (r < page.lastPage) pages.push(page.lastPage);
const getPageUrl = (p: number) => {
if (p === 1) return "/";
return `/${p}/`;
};
---
<div class:list={[className, "pagination-wrapper flex flex-col gap-4 items-center"]} style={style}>
<!-- 分页控件 -->
<div class="flex flex-row gap-3 justify-center" role="navigation" aria-label={i18n(I18nKey.postList)}>
<!-- 移动端简化版分页 -->
<div class="mobile-pagination flex items-center gap-3">
<a
href={page.url.prev || "#"}
aria-label={i18n(I18nKey.paginationPrev)}
aria-disabled={page.url.prev === undefined ? "true" : "false"}
tabindex={page.url.prev === undefined ? "-1" : "0"}
class:list={[
"btn-card overflow-hidden rounded-lg text-(--primary) w-11 h-11",
{ disabled: page.url.prev == undefined },
]}
>
<Icon is:inline
name="material-symbols:chevron-left-rounded"
class="text-[1.75rem]"
aria-hidden="true"
/>
</a>
<div class="btn-card flex items-center rounded-lg px-4 h-11 gap-1.5">
<span class="text-base font-bold text-(--primary)">{page.currentPage}</span>
<span class="text-sm text-neutral-500 dark:text-neutral-500">/</span>
<span class="text-base font-bold text-neutral-700 dark:text-neutral-300">{page.lastPage}</span>
</div>
<a
href={page.url.next || "#"}
aria-label={i18n(I18nKey.paginationNext)}
aria-disabled={page.url.next === undefined ? "true" : "false"}
tabindex={page.url.next === undefined ? "-1" : "0"}
class:list={[
"btn-card overflow-hidden rounded-lg text-(--primary) w-11 h-11",
{ disabled: page.url.next == undefined },
]}
>
<Icon is:inline
name="material-symbols:chevron-right-rounded"
class="text-[1.75rem]"
aria-hidden="true"
/>
</a>
</div>
<!-- 桌面端完整版分页 -->
<div class="desktop-pagination flex items-center gap-3">
<a
href={page.url.prev || "#"}
aria-label={i18n(I18nKey.paginationPrev)}
aria-disabled={page.url.prev === undefined ? "true" : "false"}
tabindex={page.url.prev === undefined ? "-1" : "0"}
class:list={[
"btn-card overflow-hidden rounded-lg text-(--primary) w-11 h-11",
{ disabled: page.url.prev == undefined },
]}
>
<Icon is:inline
name="material-symbols:chevron-left-rounded"
class="text-[1.75rem]"
aria-hidden="true"
/>
</a>
{
pages.map((p) => {
if (p == HIDDEN)
return <Icon is:inline name="material-symbols:more-horiz" class="w-11 h-11 flex items-center justify-center text-neutral-700 dark:text-neutral-300" aria-hidden="true" />;
if (p == page.currentPage)
return (
<div
class="h-11 w-11 rounded-lg bg-(--primary) flex items-center justify-center
font-bold text-white dark:text-black/70"
aria-current="page"
>
{p}
</div>
);
return (
<a
href={url(getPageUrl(p))}
aria-label={`${i18n(I18nKey.paginationPage)} ${p}`}
class="btn-card w-11 h-11 rounded-lg overflow-hidden active:scale-[0.85] text-neutral-700 dark:text-neutral-300"
>
{p}
</a>
);
})
}
<a
href={page.url.next || "#"}
aria-label={i18n(I18nKey.paginationNext)}
aria-disabled={page.url.next === undefined ? "true" : "false"}
tabindex={page.url.next === undefined ? "-1" : "0"}
class:list={[
"btn-card overflow-hidden rounded-lg text-(--primary) w-11 h-11",
{ disabled: page.url.next == undefined },
]}
>
<Icon is:inline
name="material-symbols:chevron-right-rounded"
class="text-[1.75rem]"
aria-hidden="true"
/>
</a>
</div>
</div>
</div>
<style>
.pagination-wrapper {
max-width: 100%;
}
.mobile-pagination {
display: flex;
padding: 0 1rem;
}
.desktop-pagination {
display: none;
}
@media (min-width: 1024px) {
.mobile-pagination {
display: none;
}
.desktop-pagination {
display: flex;
}
}
@media (max-width: 640px) {
.mobile-pagination {
padding: 0 0.5rem;
}
}
@media (max-width: 480px) {
.mobile-pagination {
padding: 0 0.25rem;
}
}
@media (hover: none) and (pointer: coarse) {
.mobile-pagination a,
.mobile-pagination div {
min-height: 44px;
min-width: 44px;
}
}
</style>
+309
View File
@@ -0,0 +1,309 @@
---
// 消息框公共组件
// 用于Live2D和Spine模型的消息显示
---
<script>
// 全局变量,跟踪当前显示的消息容器和隐藏定时器
let currentMessageContainer: HTMLDivElement | null = null;
let hideMessageTimer: number | null = null;
// 消息显示函数
export function showMessage(message: string, options: { containerId?: string; displayTime?: number } = {}) {
// 防止空消息或重复调用
if (!message || !message.trim()) {
return;
}
// 立即清除之前的消息
if (currentMessageContainer) {
if (hideMessageTimer !== null) {
clearTimeout(hideMessageTimer);
}
if (currentMessageContainer.parentNode) {
currentMessageContainer.parentNode.removeChild(currentMessageContainer);
}
currentMessageContainer = null;
}
// 确保DOM中没有残留的消息容器
const existingMessages = document.querySelectorAll(
".model-message-container"
);
existingMessages.forEach((msg) => {
if (msg.parentNode) {
msg.parentNode.removeChild(msg);
}
});
// 检测暗色主题
const isDarkMode =
document.documentElement.classList.contains("dark") ||
window.matchMedia("(prefers-color-scheme: dark)").matches;
// 创建消息容器
const messageContainer = document.createElement("div");
messageContainer.className = "model-message-container";
// 创建消息元素
const messageEl = document.createElement("div");
messageEl.className = "model-message";
messageEl.textContent = message;
// 创建箭头元素
const arrowEl = document.createElement("div");
arrowEl.className = "model-message-arrow";
// 设置容器样式
Object.assign(messageContainer.style, {
position: "fixed",
zIndex: "1001",
pointerEvents: "none",
opacity: "0",
transform: "translateY(15px) translateX(-50%) scale(0.9)",
transition: "all 0.4s cubic-bezier(0.34, 1.56, 0.64, 1)",
});
// 设置消息框美化样式(支持暗色主题)
const messageStyles = {
position: "relative",
background: isDarkMode
? "linear-gradient(135deg, rgba(45, 55, 72, 0.95), rgba(26, 32, 44, 0.9))"
: "linear-gradient(135deg, rgba(255, 255, 255, 0.95), rgba(240, 248, 255, 0.9))",
color: isDarkMode ? "#e2e8f0" : "#2c3e50",
padding: "12px 16px",
borderRadius: "16px",
fontSize: "14px",
fontWeight: "500",
fontFamily:
'-apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, sans-serif',
maxWidth: "240px",
minWidth: "100px",
wordWrap: "break-word",
textAlign: "center",
whiteSpace: "pre-wrap",
boxShadow: isDarkMode
? "0 8px 32px rgba(0, 0, 0, 0.3), 0 2px 8px rgba(0, 0, 0, 0.2)"
: "0 8px 32px rgba(0, 0, 0, 0.12), 0 2px 8px rgba(0, 0, 0, 0.08)",
border: isDarkMode
? "1px solid rgba(255, 255, 255, 0.1)"
: "1px solid rgba(255, 255, 255, 0.6)",
backdropFilter: "blur(12px)",
letterSpacing: "0.3px",
lineHeight: "1.4",
};
Object.assign(messageEl.style, messageStyles);
// 设置箭头样式(居中显示)
Object.assign(arrowEl.style, {
position: "absolute",
top: "100%",
left: "50%",
transform: "translateX(-50%)", // 箭头居中
width: "0",
height: "0",
borderLeft: "8px solid transparent",
borderRight: "8px solid transparent",
borderTop: isDarkMode
? "8px solid rgba(45, 55, 72, 0.95)"
: "8px solid rgba(255, 255, 255, 0.95)",
filter: "drop-shadow(0 2px 4px rgba(0, 0, 0, 0.1))",
});
// 组装消息框元素
messageEl.appendChild(arrowEl);
messageContainer.appendChild(messageEl);
// 添加到页面并保存引用
document.body.appendChild(messageContainer);
currentMessageContainer = messageContainer;
// 将消息显示在模型头顶居中
const container = document.getElementById(options.containerId || "model-container");
if (container) {
const rect = container.getBoundingClientRect();
// 消息框居中显示在模型上方
const containerCenterX = rect.left + rect.width / 2;
// 使用估算的消息框尺寸进行初步定位
const estimatedMessageWidth = 240; // 使用maxWidth作为估算
const estimatedMessageHeight = 60; // 估算高度
const screenPadding = 10; // 距离屏幕边缘的最小距离
// 计算消息框的实际位置(考虑translateX(-50%)的影响)
let messageX = containerCenterX;
let messageY = rect.top - estimatedMessageHeight - 25; // 距离模型顶部25px
// 屏幕边界检查 - 水平方向
const minX = screenPadding + estimatedMessageWidth / 2; // 考虑translateX(-50%)
const maxX =
window.innerWidth - screenPadding - estimatedMessageWidth / 2;
if (messageX < minX) {
messageX = minX;
} else if (messageX > maxX) {
messageX = maxX;
}
// 屏幕边界检查 - 垂直方向
const minY = screenPadding;
const maxY = window.innerHeight - estimatedMessageHeight - screenPadding;
if (messageY < minY) {
// 如果上方空间不够,显示在模型下方
messageY = rect.bottom + 25;
// 调整箭头方向(显示在下方)
arrowEl.style.top = "0";
arrowEl.style.bottom = "auto";
arrowEl.style.borderTop = "none";
arrowEl.style.borderBottom = isDarkMode
? "8px solid rgba(45, 55, 72, 0.95)"
: "8px solid rgba(255, 255, 255, 0.95)";
} else if (messageY > maxY) {
messageY = maxY;
}
// 设置位置
messageContainer.style.left = messageX + "px";
messageContainer.style.top = messageY + "px";
// 在消息框渲染后,进行精确的边界调整
setTimeout(() => {
const actualMessageRect = messageContainer.getBoundingClientRect();
const actualWidth = actualMessageRect.width;
const actualHeight = actualMessageRect.height;
// 重新计算水平位置
let adjustedX = containerCenterX;
const actualMinX = screenPadding + actualWidth / 2;
const actualMaxX = window.innerWidth - screenPadding - actualWidth / 2;
if (adjustedX < actualMinX) {
adjustedX = actualMinX;
} else if (adjustedX > actualMaxX) {
adjustedX = actualMaxX;
}
// 重新计算垂直位置
let adjustedY = rect.top - actualHeight - 25;
const actualMinY = screenPadding;
const actualMaxY = window.innerHeight - actualHeight - screenPadding;
let isAboveModel = true; // 标记消息框是否在模型上方
if (adjustedY < actualMinY) {
adjustedY = rect.bottom + 25;
isAboveModel = false;
} else if (adjustedY > actualMaxY) {
adjustedY = actualMaxY;
}
// 计算箭头应该指向的位置(模型中心)
const modelCenterX = rect.left + rect.width / 2;
const messageCenterX = adjustedX; // 消息框中心位置
const arrowOffsetX = modelCenterX - messageCenterX; // 箭头相对于消息框中心的偏移
// 限制箭头偏移范围,避免超出消息框边界
const maxOffset = actualWidth / 2 - 20; // 留出20px边距
const clampedOffsetX = Math.max(
-maxOffset,
Math.min(maxOffset, arrowOffsetX)
);
// 根据最终位置调整箭头方向和位置
if (isAboveModel) {
// 消息框在模型上方,箭头向下
Object.assign(arrowEl.style, {
position: "absolute",
top: "100%",
left: "50%",
bottom: "auto",
transform: `translateX(calc(-50% + ${clampedOffsetX}px))`,
width: "0",
height: "0",
borderLeft: "8px solid transparent",
borderRight: "8px solid transparent",
borderTop: isDarkMode
? "8px solid rgba(45, 55, 72, 0.95)"
: "8px solid rgba(255, 255, 255, 0.95)",
borderBottom: "none",
filter: "drop-shadow(0 2px 4px rgba(0, 0, 0, 0.1))",
});
} else {
// 消息框在模型下方,箭头向上
Object.assign(arrowEl.style, {
position: "absolute",
top: "0",
left: "50%",
bottom: "auto",
transform: `translateX(calc(-50% + ${clampedOffsetX}px))`,
width: "0",
height: "0",
borderLeft: "8px solid transparent",
borderRight: "8px solid transparent",
borderTop: "none",
borderBottom: isDarkMode
? "8px solid rgba(45, 55, 72, 0.95)"
: "8px solid rgba(255, 255, 255, 0.95)",
filter: "drop-shadow(0 2px 4px rgba(0, 0, 0, 0.1))",
});
}
// 应用调整后的位置
messageContainer.style.left = adjustedX + "px";
messageContainer.style.top = adjustedY + "px";
}, 50); // 增加延迟确保消息框完全渲染
}
// 显示动画
setTimeout(() => {
messageContainer.style.opacity = "1";
messageContainer.style.transform =
"translateY(0) translateX(-50%) scale(1)";
}, 100); // 延迟到边界调整完成后
// 自动隐藏
const displayTime = options.displayTime || 3000;
hideMessageTimer = window.setTimeout(() => {
messageContainer.style.opacity = "0";
messageContainer.style.transform =
"translateY(-15px) translateX(-50%) scale(0.95)";
setTimeout(() => {
if (messageContainer.parentNode) {
messageContainer.parentNode.removeChild(messageContainer);
}
// 清除引用
if (currentMessageContainer === messageContainer) {
currentMessageContainer = null;
}
}, 400);
}, displayTime);
}
// 清理消息函数
export function clearMessage() {
if (currentMessageContainer) {
if (hideMessageTimer !== null) {
clearTimeout(hideMessageTimer);
}
if (currentMessageContainer.parentNode) {
currentMessageContainer.parentNode.removeChild(currentMessageContainer);
}
currentMessageContainer = null;
}
// 清理所有消息容器
const existingMessages = document.querySelectorAll(
".model-message-container"
);
existingMessages.forEach((msg) => {
if (msg.parentNode) {
msg.parentNode.removeChild(msg);
}
});
}
// 将函数暴露到全局作用域
(window as any).showModelMessage = showMessage;
(window as any).clearModelMessage = clearMessage;
</script>
+136
View File
@@ -0,0 +1,136 @@
---
import { Icon } from "astro-icon/components";
import I18nKey from "@/i18n/i18nKey";
import { i18n } from "@/i18n/translation";
interface Props {
id: string;
name?: string;
showTitle?: boolean;
isCollapsed?: boolean;
collapsedHeight?: string;
useExpandedButtonSpacing?: boolean;
contentPadding?: boolean;
moreUrl?: string;
class?: string;
style?: string;
}
const {
id,
name,
showTitle = true,
isCollapsed,
collapsedHeight,
useExpandedButtonSpacing = false,
contentPadding = true,
moreUrl,
style,
} = Astro.props;
const className = Astro.props.class;
---
<widget-layout
data-id={id}
data-is-collapsed={String(isCollapsed)}
data-use-expanded-button-spacing={String(useExpandedButtonSpacing)}
class:list={["card-base", {"pb-4": contentPadding}, className]}
style={style}
>
{name && showTitle && (
<div class="widget-title font-bold transition text-lg text-neutral-900 dark:text-neutral-100 relative ml-8 mt-4 mb-2
before:w-1 before:h-4 before:rounded-md before:bg-(--primary)
before:absolute before:left-[-16px] before:top-[5.5px] flex items-center justify-between">
<span class="widget-name">{name}</span>
<slot name="title-icon" />
</div>
)}
<div id={id} class:list={["collapse-wrapper overflow-hidden", {"px-4": contentPadding, "collapsed": isCollapsed, "pt-4": contentPadding && (!name || !showTitle)}]}>
<slot></slot>
</div>
{isCollapsed && <div class="expand-btn px-4 -mb-2">
{moreUrl ? (
<a
href={moreUrl}
class="btn-plain rounded-lg w-full h-9 flex items-center justify-center"
title={i18n(I18nKey.more)}
>
<div class="text-(--primary) flex items-center justify-center gap-2 -translate-x-2">
<Icon is:inline name="material-symbols:more-horiz" class="text-[1.75rem]" aria-hidden="true"></Icon>
<span>{i18n(I18nKey.more)}</span>
</div>
</a>
) : (
<button
class="btn-plain rounded-lg w-full h-9"
title={i18n(I18nKey.more)}
aria-label={i18n(I18nKey.more)}
data-show-more={i18n(I18nKey.more)}
data-show-less={i18n(I18nKey.collapse)}
data-expanded="false"
>
<div class="text-(--primary) flex items-center justify-center gap-2 -translate-x-2">
<Icon is:inline name="material-symbols:more-horiz" class="toggle-icon-more text-[1.75rem]" aria-hidden="true"></Icon>
<Icon is:inline name="material-symbols:keyboard-arrow-up-rounded" class="toggle-icon-less hidden text-[1.75rem]" aria-hidden="true"></Icon>
<span class="toggle-text">{i18n(I18nKey.more)}</span>
</div>
</button>
)}
</div>}
</widget-layout>
<style define:vars={{ collapsedHeight }}>
.collapsed {
height: var(--collapsedHeight);
}
widget-layout[data-is-collapsed="true"][data-expanded="true"][data-use-expanded-button-spacing="true"] .expand-btn {
padding-top: 0.5rem;
}
</style>
<script>
class WidgetLayout extends HTMLElement {
constructor() {
super();
if (this.dataset.isCollapsed !== "true")
return;
this.dataset.expanded = 'false';
const id = this.dataset.id;
const btn = this.querySelector('.expand-btn button') as HTMLButtonElement | null;
const wrapper = this.querySelector(`#${id}`)
if (!btn || !wrapper)
return;
const text = btn.querySelector('.toggle-text');
const moreIcon = btn.querySelector('.toggle-icon-more');
const lessIcon = btn.querySelector('.toggle-icon-less');
const updateButtonState = (expanded: boolean) => {
const label = expanded
? btn.dataset.showLess || ''
: btn.dataset.showMore || '';
btn.dataset.expanded = String(expanded);
this.dataset.expanded = String(expanded);
btn.title = label;
btn.setAttribute('aria-label', label);
if (text)
text.textContent = label;
moreIcon?.classList.toggle('hidden', expanded);
lessIcon?.classList.toggle('hidden', !expanded);
};
btn.addEventListener('click', () => {
const expanded = btn.dataset.expanded === 'true';
wrapper.classList.toggle('collapsed', expanded);
updateButtonState(!expanded);
});
}
}
if (!customElements.get("widget-layout")) {
customElements.define("widget-layout", WidgetLayout);
}
</script>
+370
View File
@@ -0,0 +1,370 @@
---
import { siteConfig } from "@/config";
import I18nKey from "@/i18n/i18nKey";
import { i18n } from "@/i18n/translation";
import { getSortedPostsList } from "@/utils/content-utils";
import { getPostUrlBySlug, url } from "@/utils/url-utils";
// 归档列表:全量按年分组,服务端渲染。筛选(?tag=/?category=/?uncategorized)
// 与年份折叠由客户端脚本处理——数据本身在构建期已全部就绪。
const sortedPostsList = await getSortedPostsList();
// 严格按发布时间倒序(不受置顶影响),镜像原 Svelte 版行为
const posts = sortedPostsList
.slice()
.sort((a, b) => b.data.published.getTime() - a.data.published.getTime());
// 按年份分组
const grouped = new Map<number, typeof posts>();
for (const post of posts) {
const year = post.data.published.getFullYear();
if (!grouped.has(year)) grouped.set(year, []);
grouped.get(year)?.push(post);
}
const groups = Array.from(grouped.entries())
.map(([year, yearPosts]) => ({ year, posts: yearPosts }))
.sort((a, b) => b.year - a.year);
// 初始折叠规则:foldArticle 非 false 且多于一年时,除首年外全部折叠
const foldArticle = siteConfig.foldArticle !== false;
const collapseAllButFirst = foldArticle && groups.length > 1;
function formatDate(date: Date) {
const month = (date.getMonth() + 1).toString().padStart(2, "0");
const day = date.getDate().toString().padStart(2, "0");
return `${month}-${day}`;
}
function formatTag(tagList: string[]) {
return tagList.map((t) => `#${t}`).join(" ");
}
// 传给客户端脚本的 i18n 文案与配置
const i18nStrings = {
categories: i18n(I18nKey.categories),
tags: i18n(I18nKey.tags),
uncategorized: i18n(I18nKey.uncategorized),
postCount: i18n(I18nKey.postCount),
postsCount: i18n(I18nKey.postsCount),
};
const tagsBaseUrl = url("/tags/");
const categoriesBaseUrl = url("/categories/");
const foldOnFilter = collapseAllButFirst;
---
<archive-panel
class="card-base px-8 py-6"
data-fold={foldOnFilter ? "true" : "false"}
>
{/* 筛选头部:默认隐藏,客户端在有筛选时填充并显示 */}
<div id="archive-filter-header" class="mb-5 hidden">
<div class="flex flex-wrap items-center justify-between gap-x-4 gap-y-1">
<div class="min-w-0 text-sm text-75">
<a id="archive-filter-link" href={tagsBaseUrl} class="text-50 hover:text-(--primary) transition-colors"></a>
<span class="mx-2 text-30">/</span>
<span id="archive-filter-values" class="font-semibold text-(--primary)"></span>
<span id="archive-filter-secondary" class="ml-2 text-50 hidden"></span>
</div>
<div class="shrink-0 text-xs text-50">
<span id="archive-filter-count"></span> <span id="archive-filter-count-label"></span>
</div>
</div>
</div>
{groups.map((group, groupIndex) => {
const collapsed = collapseAllButFirst && groupIndex > 0;
return (
<div class="archive-year-block" data-year={group.year} data-count={group.posts.length}>
<button
class="archive-year-toggle flex flex-row w-full items-center h-15 cursor-pointer rounded-lg
hover:bg-(--btn-plain-bg-hover) transition-colors group/yr"
aria-expanded={collapsed ? "false" : "true"}
>
<div class="w-[15%] md:w-[10%] transition text-2xl font-bold text-right text-75
group-hover/yr:text-(--primary)">
{group.year}
</div>
<div class="w-[15%] md:w-[10%]">
<div class="h-3 w-3 bg-none rounded-full outline-(--primary) mx-auto
-outline-offset-2 z-50 outline-3"></div>
</div>
<div class="w-[70%] md:w-[80%] transition text-left text-50 flex items-center gap-2
group-hover/yr:text-(--primary)">
<span class="archive-year-count">{group.posts.length}</span>
{" "}
<span class="archive-year-count-label">{i18n(group.posts.length === 1 ? I18nKey.postCount : I18nKey.postsCount)}</span>
<span class="archive-arrow" style={collapsed ? "transform: rotate(-90deg)" : ""}>
<svg class="w-4 h-4" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="3">
<path d="M6 9l6 6 6-6" stroke-linecap="round" stroke-linejoin="round" />
</svg>
</span>
</div>
</button>
<div class="archive-year-content" hidden={collapsed}>
{group.posts.map((post) => (
<a
href={getPostUrlBySlug(post.id)}
aria-label={post.data.title}
class="archive-post group btn-plain block! h-10 w-full rounded-lg hover:text-[initial]"
data-tags={JSON.stringify(post.data.tags || [])}
data-category={post.data.category || ""}
>
<div class="flex flex-row justify-start items-center h-full">
{/* date */}
<div class="w-[15%] md:w-[10%] transition text-sm text-right text-50">
{formatDate(post.data.published)}
</div>
{/* dot and line */}
<div class="w-[15%] md:w-[10%] relative dash-line h-full flex items-center">
<div class="transition-all mx-auto w-1 h-1 rounded-sm group-hover:h-5
bg-[oklch(0.5_0.05_var(--hue))] group-hover:bg-(--primary)
outline-4 z-50 outline-(--card-bg)
group-hover:outline-(--btn-plain-bg-hover)
group-active:outline-(--btn-plain-bg-active)"></div>
</div>
{/* post title */}
<div class="w-[70%] md:max-w-[65%] md:w-[65%] text-left font-bold
group-hover:translate-x-1 transition-all group-hover:text-(--primary)
text-75 pr-8 whitespace-nowrap text-ellipsis overflow-hidden flex items-center gap-2">
{post.data.category && (
<span class="shrink-0 inline-block text-xs font-medium px-1.5 py-0.5 rounded-sm
bg-[oklch(0.95_0.025_var(--hue))] dark:bg-[oklch(0.25_0.025_var(--hue))]
text-(--primary) group-hover:bg-(--primary) group-hover:text-white!
transition-colors">
{post.data.category}
</span>
)}
<span class="truncate">{post.data.title}</span>
</div>
{/* tag list */}
<div class="hidden md:block md:w-[15%] text-left text-sm transition
whitespace-nowrap text-ellipsis overflow-hidden text-30">
{formatTag(post.data.tags || [])}
</div>
</div>
</a>
))}
</div>
</div>
);
})}
</archive-panel>
<style>
archive-panel {
display: block;
}
.archive-arrow {
display: inline-flex;
}
</style>
<script is:inline define:vars={{ i18nStrings, tagsBaseUrl, categoriesBaseUrl }}>
class ArchivePanel extends HTMLElement {
constructor() {
super();
// 避免 swup 重复初始化
if (this.dataset.initialized === "true") return;
this.dataset.initialized = "true";
this.init();
}
init() {
const params = new URLSearchParams(window.location.search);
const tags = params.has("tag") ? params.getAll("tag") : [];
const categories = params.has("category") ? params.getAll("category") : [];
const uncategorized = params.get("uncategorized");
const hasFilter = tags.length > 0 || categories.length > 0 || !!uncategorized;
if (hasFilter) {
this.applyFilter(tags, categories, !!uncategorized);
this.updateBannerTitle(tags, categories, !!uncategorized);
}
this.bindYearToggles();
}
// 按筛选条件隐藏不匹配的文章行,重算每年计数,隐藏空年份,重新折叠
applyFilter(tags, categories, uncategorized) {
const foldOnFilter = this.dataset.fold === "true";
const blocks = Array.from(this.querySelectorAll(".archive-year-block"));
let totalVisible = 0;
const visibleBlocks = [];
for (const block of blocks) {
const rows = Array.from(block.querySelectorAll(".archive-post"));
let visibleCount = 0;
for (const row of rows) {
let rowTags = [];
try {
rowTags = JSON.parse(row.dataset.tags || "[]");
} catch {
rowTags = [];
}
const rowCategory = row.dataset.category || "";
let match = true;
if (tags.length > 0) {
match = match && rowTags.some((t) => tags.includes(t));
}
if (categories.length > 0) {
match = match && !!rowCategory && categories.includes(rowCategory);
}
if (uncategorized) {
match = match && !rowCategory;
}
row.hidden = !match;
if (match) visibleCount++;
}
// 更新每年计数显示
const countEl = block.querySelector(".archive-year-count");
const labelEl = block.querySelector(".archive-year-count-label");
if (countEl) countEl.textContent = String(visibleCount);
if (labelEl) {
labelEl.textContent =
visibleCount === 1 ? i18nStrings.postCount : i18nStrings.postsCount;
}
// 隐藏没有可见文章的年份块
block.hidden = visibleCount === 0;
if (visibleCount > 0) {
visibleBlocks.push(block);
totalVisible += visibleCount;
}
}
// 重新应用折叠:首个可见年份展开,其余折叠
visibleBlocks.forEach((block, index) => {
const shouldCollapse = foldOnFilter && index > 0;
this.setBlockCollapsed(block, shouldCollapse);
});
// 填充并显示筛选头部
this.renderFilterHeader(tags, categories, uncategorized, totalVisible);
}
setBlockCollapsed(block, collapsed) {
const content = block.querySelector(".archive-year-content");
const toggle = block.querySelector(".archive-year-toggle");
const arrow = block.querySelector(".archive-arrow");
if (content) content.hidden = collapsed;
if (toggle) toggle.setAttribute("aria-expanded", collapsed ? "false" : "true");
if (arrow) {
arrow.style.transform = collapsed ? "rotate(-90deg)" : "";
}
}
renderFilterHeader(tags, categories, uncategorized, count) {
const header = this.querySelector("#archive-filter-header");
if (!header) return;
// 构造筛选项(tag 优先作为主筛选,镜像原逻辑)
const filters = [];
if (categories.length > 0)
filters.push({ label: i18nStrings.categories, values: categories, isTag: false });
if (uncategorized)
filters.push({ label: i18nStrings.categories, values: [i18nStrings.uncategorized], isTag: false });
if (tags.length > 0)
filters.push({ label: i18nStrings.tags, values: tags, isTag: true });
const primary =
filters.find((f) => f.isTag) || filters[0] || null;
if (!primary) return;
const secondary = filters.filter((f) => f !== primary);
const linkEl = header.querySelector("#archive-filter-link");
const valuesEl = header.querySelector("#archive-filter-values");
const secondaryEl = header.querySelector("#archive-filter-secondary");
const countEl = header.querySelector("#archive-filter-count");
const countLabelEl = header.querySelector("#archive-filter-count-label");
const fmtValues = (f) => {
const prefix = f.isTag ? "#" : "";
return f.values.map((v) => `${prefix}${v}`).join(" / ");
};
if (linkEl) {
linkEl.textContent = primary.label;
linkEl.setAttribute("href", primary.isTag ? tagsBaseUrl : categoriesBaseUrl);
}
if (valuesEl) valuesEl.textContent = fmtValues(primary);
if (secondaryEl) {
if (secondary.length > 0) {
const summary = secondary
.map((f) => `${f.label}: ${fmtValues(f)}`)
.join(" · ");
secondaryEl.textContent = `· ${summary}`;
secondaryEl.classList.remove("hidden");
} else {
secondaryEl.classList.add("hidden");
}
}
if (countEl) countEl.textContent = String(count);
if (countLabelEl) {
countLabelEl.textContent =
count === 1 ? i18nStrings.postCount : i18nStrings.postsCount;
}
header.classList.remove("hidden");
}
updateBannerTitle(tags, categories, uncategorized) {
const bannerTitle = document.querySelector(".banner-page-title-text");
if (!bannerTitle) return;
let newTitle = "";
if (categories.length > 0) {
newTitle = categories.join(" / ");
} else if (uncategorized) {
newTitle = i18nStrings.uncategorized;
} else if (tags.length > 0) {
newTitle = tags.map((t) => `#${t}`).join(" / ");
}
// 直接设置(自定义元素在解析阶段升级、首帧前执行),避免默认标题闪烁
if (newTitle && bannerTitle.textContent !== newTitle) {
bannerTitle.textContent = newTitle;
}
}
bindYearToggles() {
const blocks = Array.from(this.querySelectorAll(".archive-year-block"));
for (const block of blocks) {
const toggle = block.querySelector(".archive-year-toggle");
const content = block.querySelector(".archive-year-content");
const arrow = block.querySelector(".archive-arrow");
if (!toggle || !content) continue;
toggle.addEventListener("click", () => {
const willCollapse = !content.hidden;
content.hidden = willCollapse;
toggle.setAttribute("aria-expanded", willCollapse ? "false" : "true");
// 用 Web Animations API 做旋转动画,绕开 Swup 对 CSS transition 的干扰
if (arrow) {
requestAnimationFrame(() => {
arrow.animate(
[
{ transform: willCollapse ? "rotate(0deg)" : "rotate(-90deg)" },
{ transform: willCollapse ? "rotate(-90deg)" : "rotate(0deg)" },
],
{ duration: 200, easing: "ease", fill: "forwards" },
);
});
}
});
}
}
}
if (!customElements.get("archive-panel")) {
customElements.define("archive-panel", ArchivePanel);
}
</script>
@@ -0,0 +1,47 @@
---
import FloatingButton from "@/components/common/FloatingButton.astro";
---
<FloatingButton
id="back-to-comment-btn"
icon="mingcute:comment-line"
ariaLabel="Scroll to comments"
onclick="scrollToCommentSection()"
class="hide"
/>
<script is:inline>
window.scrollToCommentSection = function () {
const commentSection = document.getElementById("post-comments");
if (!commentSection) return;
commentSection.scrollIntoView({
behavior: "smooth",
block: "start",
});
};
function updateCommentButtonVisibility() {
const btn = document.getElementById("back-to-comment-btn");
const commentSection = document.getElementById("post-comments");
if (!btn) return;
// No comment section on current page: keep hidden.
if (!commentSection) {
btn.style.display = "none";
btn.classList.add("hide");
return;
}
btn.style.display = "";
btn.classList.remove("hide");
}
updateCommentButtonVisibility();
setTimeout(updateCommentButtonVisibility, 0);
requestAnimationFrame(updateCommentButtonVisibility);
document.addEventListener("astro:page-load", updateCommentButtonVisibility);
document.addEventListener("swup:contentReplaced", updateCommentButtonVisibility);
document.addEventListener("swup:enable", updateCommentButtonVisibility);
</script>
+50
View File
@@ -0,0 +1,50 @@
---
import FloatingButton from "@/components/common/FloatingButton.astro";
import I18nKey from "@/i18n/i18nKey";
import { i18n } from "@/i18n/translation";
import { url } from "@/utils/url-utils";
---
<FloatingButton
id="back-to-home-btn"
icon="material-symbols:home-outline-rounded"
ariaLabel={i18n(I18nKey.home)}
onclick="backToHome()"
class="hide"
/>
<script is:raw is:inline define:vars={{ homeUrl: url("/")}}>
window.backToHome = function() {
const url = homeUrl;
if (window.swup) {
window.swup.navigate(url);
} else {
window.location.href = url;
}
};
</script>
<script is:inline define:vars={{ homeUrl: url("/") }}>
function updateBackToHomeVisibility() {
const btn = document.getElementById("back-to-home-btn");
if (!btn) return;
const path = window.location.pathname.replace(/\/$/, "") || "/";
const homePath = homeUrl.replace(/\/$/, "") || "/";
if (path === homePath) {
btn.classList.add("hide");
} else {
btn.classList.remove("hide");
}
}
// Initial check
updateBackToHomeVisibility();
// Re-check on view transitions or swup navigation
document.addEventListener("astro:page-load", updateBackToHomeVisibility);
document.addEventListener("swup:contentReplaced", updateBackToHomeVisibility);
</script>
+65
View File
@@ -0,0 +1,65 @@
---
import FloatingButton from "@/components/common/FloatingButton.astro";
---
<!-- There can't be a filter on parent element, or it will break `fixed` -->
<FloatingButton
id="back-to-top-btn"
icon="material-symbols:keyboard-arrow-up-rounded"
ariaLabel="Back to Top"
onclick="backToTop()"
class="hide"
/>
<script is:raw is:inline>
function backToTop() {
// 直接使用原生滚动,避免OverlayScrollbars冲突
window.scroll({ top: 0, behavior: "smooth" });
}
// 响应式返回顶部按钮管理器
if (typeof window.BackToTopManager === "undefined") {
window.BackToTopManager = class BackToTopManager {
constructor() {
this.button = document.getElementById("back-to-top-btn");
this.init();
}
init() {
if (!this.button) return; // wrapper checks removed as it is now flexible
this.setupScrollListener();
}
setupScrollListener() {
const updateVisibility = () => {
const scrollTop =
window.pageYOffset || document.documentElement.scrollTop;
// 当滚动超过200px时显示按钮
if (scrollTop > 200) {
this.button.classList.remove("hide");
} else {
this.button.classList.add("hide");
}
};
window.addEventListener("scroll", updateVisibility, { passive: true });
}
};
}
// ... existing initialization logic ...
// 页面加载完成后初始化
document.addEventListener("DOMContentLoaded", () => {
new BackToTopManager();
});
// 如果页面已经加载完成,立即初始化
if (document.readyState === "loading") {
document.addEventListener("DOMContentLoaded", () => {
new BackToTopManager();
});
} else {
new BackToTopManager();
}
</script>
@@ -0,0 +1,98 @@
<script lang="ts">
import I18nKey from "@i18n/i18nKey";
import { i18n } from "@i18n/translation";
import { getDefaultHue, getHue, setHue } from "@utils/setting-utils";
import Icon from "@/components/common/Icon.svelte";
/**
* 主题色设置面板
* 目前已弃用,已集成至DisplaySettingsIntegrated.svelte,当前文件保留以备将来可能的单独使用
*/
let hue = getHue();
const defaultHue = getDefaultHue();
function resetHue() {
hue = getDefaultHue();
}
$: if (hue || hue === 0) {
setHue(hue);
}
</script>
<div id="display-setting" class="float-panel float-panel-closed absolute transition-all w-80 right-4 px-4 py-4">
<div class="flex flex-row gap-2 mb-3 items-center justify-between">
<div class="flex gap-2 font-bold text-lg text-neutral-900 dark:text-neutral-100 transition relative ml-3
before:w-1 before:h-4 before:rounded-md before:bg-(--primary)
before:absolute before:-left-3 before:top-[0.33rem]"
>
{i18n(I18nKey.themeColor)}
<button aria-label="Reset to Default" class="btn-regular w-7 h-7 rounded-md active:scale-90"
class:opacity-0={hue === defaultHue} class:pointer-events-none={hue === defaultHue} on:click={resetHue}>
<div class="text-(--btn-content)">
<Icon icon="fa7-solid:arrow-rotate-left" class="text-[0.875rem]"></Icon>
</div>
</button>
</div>
<div class="flex gap-1">
<div id="hueValue" class="transition bg-(--btn-regular-bg) w-10 h-7 rounded-md flex justify-center
font-bold text-sm items-center text-(--btn-content)">
{hue}
</div>
</div>
</div>
<div class="w-full h-6 px-1 bg-[oklch(0.80_0.10_0)] dark:bg-[oklch(0.70_0.10_0)] rounded-sm select-none">
<input aria-label={i18n(I18nKey.themeColor)} type="range" min="0" max="360" bind:value={hue}
class="slider" id="colorSlider" step="5" style="width: 100%">
</div>
</div>
<style lang="stylus">
#display-setting
input[type="range"]
-webkit-appearance none
height 1.5rem
background-image var(--color-selection-bar)
transition background-image 0.15s ease-in-out
/* Input Thumb */
&::-webkit-slider-thumb
-webkit-appearance none
height 1rem
width 0.5rem
border-radius 0.125rem
background rgba(255, 255, 255, 0.7)
box-shadow none
&:hover
background rgba(255, 255, 255, 0.8)
&:active
background rgba(255, 255, 255, 0.6)
&::-moz-range-thumb
-webkit-appearance none
height 1rem
width 0.5rem
border-radius 0.125rem
border-width 0
background rgba(255, 255, 255, 0.7)
box-shadow none
&:hover
background rgba(255, 255, 255, 0.8)
&:active
background rgba(255, 255, 255, 0.6)
&::-ms-thumb
-webkit-appearance none
height 1rem
width 0.5rem
border-radius 0.125rem
background rgba(255, 255, 255, 0.7)
box-shadow none
&:hover
background rgba(255, 255, 255, 0.8)
&:active
background rgba(255, 255, 255, 0.6)
</style>
@@ -0,0 +1,886 @@
<script lang="ts">
import {
WALLPAPER_BANNER,
WALLPAPER_FULLSCREEN,
WALLPAPER_NONE,
WALLPAPER_OVERLAY,
} from "@constants/constants";
import I18nKey from "@i18n/i18nKey";
import { i18n } from "@i18n/translation";
import {
getDefaultBannerCarouselEnabled,
getDefaultBannerTitleEnabled,
getDefaultGradientEnabled,
getDefaultHue,
getDefaultOverlayBlur,
getDefaultOverlayCardOpacity,
getDefaultOverlayOpacity,
getDefaultSakuraEnabled,
getDefaultWavesEnabled,
getHue,
getStoredBannerCarouselEnabled,
getStoredBannerTitleEnabled,
getStoredGradientEnabled,
getStoredOverlayBlur,
getStoredOverlayCardOpacity,
getStoredOverlayOpacity,
getStoredSakuraEnabled,
getStoredWallpaperMode,
getStoredWavesEnabled,
setBannerCarouselEnabled,
setBannerTitleEnabled,
setGradientEnabled,
setHue,
setOverlayBlur,
setOverlayCardOpacity,
setOverlayOpacity,
setSakuraEnabled,
setWallpaperMode,
setWavesEnabled,
} from "@utils/setting-utils";
import { onMount } from "svelte";
import Icon from "@/components/common/Icon.svelte";
import { backgroundWallpaper, sakuraConfig, siteConfig } from "@/config";
import type { WALLPAPER_MODE } from "@/types/config";
type OverlaySliderItem = {
key: "opacity" | "blur" | "cardOpacity";
enabled: boolean;
label: string;
displayValue: string;
ariaLabel: string;
min: number;
max: number;
step: number;
value: number;
onValueChange: (value: number) => void;
};
let hue = $state(getHue());
const defaultHue = getDefaultHue();
let wallpaperMode: WALLPAPER_MODE = $state(backgroundWallpaper.mode);
const defaultWallpaperMode = backgroundWallpaper.mode;
let currentLayout: "list" | "grid" = $state("list");
const defaultLayout = siteConfig.postListLayout.defaultMode;
const mobileDefaultLayout =
siteConfig.postListLayout.mobileDefaultMode || defaultLayout;
let mounted = $state(false);
let isSmallScreen = $state(
typeof window !== "undefined" ? window.innerWidth < 1200 : false,
);
let isMobileWidth = $state(
typeof window !== "undefined" ? window.innerWidth < 780 : false,
);
let isSwitching = $state(false);
let wavesEnabled = $state(true);
const defaultWavesEnabled = getDefaultWavesEnabled();
let gradientEnabled = $state(true);
const defaultGradientEnabled = getDefaultGradientEnabled();
let bannerTitleEnabled = $state(true);
const defaultBannerTitleEnabled = getDefaultBannerTitleEnabled();
let bannerCarouselEnabled = $state(true);
const defaultBannerCarouselEnabled = getDefaultBannerCarouselEnabled();
let sakuraEnabled = $state(true);
const defaultSakuraEnabled = getDefaultSakuraEnabled();
let overlayOpacity = $state(getDefaultOverlayOpacity());
const defaultOverlayOpacity = getDefaultOverlayOpacity();
let overlayBlur = $state(getDefaultOverlayBlur());
const defaultOverlayBlur = getDefaultOverlayBlur();
let overlayCardOpacity = $state(getDefaultOverlayCardOpacity());
const defaultOverlayCardOpacity = getDefaultOverlayCardOpacity();
const isWallpaperSwitchable = backgroundWallpaper.switchable ?? true;
const allowLayoutSwitch = siteConfig.postListLayout.allowSwitch;
let effectiveDefaultLayout = $derived(
isMobileWidth ? mobileDefaultLayout : defaultLayout,
);
const showThemeColor = !siteConfig.themeColor.fixed;
// 是否允许用户切换水波纹动画(只看 switchable 配置)
const isWavesSwitchable =
backgroundWallpaper.common?.waves?.switchable ?? false;
// 是否允许用户切换渐变过渡(只看 switchable 配置)
const isGradientSwitchable =
backgroundWallpaper.common?.gradient?.switchable ?? false;
// 检查是否启用横幅标题配置
const isBannerTitleEnabled =
backgroundWallpaper.common?.homeText?.enable ?? false;
// 是否允许用户切换横幅标题
const isBannerTitleSwitchable =
isBannerTitleEnabled &&
(backgroundWallpaper.common?.homeText?.switchable ?? false);
// 是否允许用户切换横幅轮播
const isBannerCarouselSwitchable =
backgroundWallpaper.common?.carousel?.switchable ?? false;
// 是否允许用户切换樱花特效
const isSakuraSwitchable = sakuraConfig?.switchable ?? false;
// 是否有任何横幅设置可显示(后续添加新设置时在此处添加条件)
const hasBannerSettings =
isWavesSwitchable ||
isGradientSwitchable ||
isBannerTitleSwitchable ||
isBannerCarouselSwitchable;
const overlaySwitchableConfig =
backgroundWallpaper.overlay?.switchable ?? false;
const isOverlaySettingsSwitchable =
typeof overlaySwitchableConfig === "boolean" ? overlaySwitchableConfig : true;
const isOverlayOpacitySwitchable =
typeof overlaySwitchableConfig === "boolean"
? overlaySwitchableConfig
: (overlaySwitchableConfig.opacity ?? false);
const isOverlayBlurSwitchable =
typeof overlaySwitchableConfig === "boolean"
? overlaySwitchableConfig
: (overlaySwitchableConfig.blur ?? false);
const isOverlayCardOpacitySwitchable =
typeof overlaySwitchableConfig === "boolean"
? overlaySwitchableConfig
: (overlaySwitchableConfig.cardOpacity ?? false);
const hasOverlaySettings =
isOverlaySettingsSwitchable &&
(isOverlayOpacitySwitchable ||
isOverlayBlurSwitchable ||
isOverlayCardOpacitySwitchable);
let overlaySettingsIsDefault = $derived(
(!isOverlayOpacitySwitchable || overlayOpacity === defaultOverlayOpacity) &&
(!isOverlayBlurSwitchable || overlayBlur === defaultOverlayBlur) &&
(!isOverlayCardOpacitySwitchable ||
overlayCardOpacity === defaultOverlayCardOpacity),
);
// 横幅设置是否全部为默认值(用于控制恢复默认按钮的显隐)
let bannerSettingsIsDefault = $derived(
(!isBannerTitleSwitchable ||
bannerTitleEnabled === defaultBannerTitleEnabled) &&
(!isWavesSwitchable || wavesEnabled === defaultWavesEnabled) &&
(!isGradientSwitchable || gradientEnabled === defaultGradientEnabled) &&
(!isBannerCarouselSwitchable ||
bannerCarouselEnabled === defaultBannerCarouselEnabled),
);
const hasAnyContent =
showThemeColor ||
isWallpaperSwitchable ||
allowLayoutSwitch ||
hasBannerSettings ||
hasOverlaySettings ||
isSakuraSwitchable;
let overlaySliderItems = $derived<OverlaySliderItem[]>([
{
key: "opacity",
enabled: isOverlayOpacitySwitchable,
label: i18n(I18nKey.overlayOpacity),
displayValue: `${Math.round(overlayOpacity * 100)}%`,
ariaLabel: i18n(I18nKey.overlayOpacity),
min: 20,
max: 100,
step: 1,
value: Math.round(overlayOpacity * 100),
onValueChange: (value) => {
overlayOpacity = value / 100;
},
},
{
key: "blur",
enabled: isOverlayBlurSwitchable,
label: i18n(I18nKey.overlayBlur),
displayValue: `${overlayBlur.toFixed(1)}px`,
ariaLabel: i18n(I18nKey.overlayBlur),
min: 0,
max: 20,
step: 0.5,
value: overlayBlur,
onValueChange: (value) => {
overlayBlur = value;
},
},
{
key: "cardOpacity",
enabled: isOverlayCardOpacitySwitchable,
label: i18n(I18nKey.overlayCardOpacity),
displayValue: `${Math.round(overlayCardOpacity * 100)}%`,
ariaLabel: i18n(I18nKey.overlayCardOpacity),
min: 20,
max: 100,
step: 1,
value: Math.round(overlayCardOpacity * 100),
onValueChange: (value) => {
overlayCardOpacity = value / 100;
},
},
]);
function resetHue() {
hue = getDefaultHue();
requestAnimationFrame(refreshAllRangeProgress);
}
function resetWallpaperMode() {
wallpaperMode = defaultWallpaperMode;
setWallpaperMode(defaultWallpaperMode);
}
function resetLayout() {
currentLayout = effectiveDefaultLayout;
localStorage.removeItem("postListLayout");
// 触发自定义事件,通知页面布局已改变
const event = new CustomEvent("layoutChange", {
detail: { layout: effectiveDefaultLayout },
});
window.dispatchEvent(event);
}
function resetWavesEnabled() {
wavesEnabled = defaultWavesEnabled;
setWavesEnabled(defaultWavesEnabled);
}
function resetGradientEnabled() {
gradientEnabled = defaultGradientEnabled;
setGradientEnabled(defaultGradientEnabled);
}
function resetBannerSettings() {
if (
isBannerTitleSwitchable &&
bannerTitleEnabled !== defaultBannerTitleEnabled
) {
bannerTitleEnabled = defaultBannerTitleEnabled;
setBannerTitleEnabled(defaultBannerTitleEnabled);
}
if (isWavesSwitchable && wavesEnabled !== defaultWavesEnabled) {
wavesEnabled = defaultWavesEnabled;
setWavesEnabled(defaultWavesEnabled);
}
if (isGradientSwitchable && gradientEnabled !== defaultGradientEnabled) {
gradientEnabled = defaultGradientEnabled;
setGradientEnabled(defaultGradientEnabled);
}
if (
isBannerCarouselSwitchable &&
bannerCarouselEnabled !== defaultBannerCarouselEnabled
) {
bannerCarouselEnabled = defaultBannerCarouselEnabled;
setBannerCarouselEnabled(defaultBannerCarouselEnabled);
}
}
function resetOverlaySettings() {
if (isOverlayOpacitySwitchable && overlayOpacity !== defaultOverlayOpacity) {
overlayOpacity = defaultOverlayOpacity;
setOverlayOpacity(defaultOverlayOpacity);
}
if (isOverlayBlurSwitchable && overlayBlur !== defaultOverlayBlur) {
overlayBlur = defaultOverlayBlur;
setOverlayBlur(defaultOverlayBlur);
}
if (
isOverlayCardOpacitySwitchable &&
overlayCardOpacity !== defaultOverlayCardOpacity
) {
overlayCardOpacity = defaultOverlayCardOpacity;
setOverlayCardOpacity(defaultOverlayCardOpacity);
}
requestAnimationFrame(refreshAllRangeProgress);
}
function toggleWavesEnabled() {
wavesEnabled = !wavesEnabled;
setWavesEnabled(wavesEnabled);
}
function toggleGradientEnabled() {
gradientEnabled = !gradientEnabled;
setGradientEnabled(gradientEnabled);
}
function toggleBannerTitleEnabled() {
bannerTitleEnabled = !bannerTitleEnabled;
setBannerTitleEnabled(bannerTitleEnabled);
}
function toggleBannerCarouselEnabled() {
bannerCarouselEnabled = !bannerCarouselEnabled;
setBannerCarouselEnabled(bannerCarouselEnabled);
}
function toggleSakuraEnabled() {
sakuraEnabled = !sakuraEnabled;
setSakuraEnabled(sakuraEnabled);
}
function switchWallpaperMode(newMode: WALLPAPER_MODE) {
wallpaperMode = newMode;
setWallpaperMode(newMode);
window.scrollTo({ top: 0 });
if (newMode === WALLPAPER_OVERLAY) {
requestAnimationFrame(refreshAllRangeProgress);
}
}
function checkScreenSize() {
isSmallScreen = window.innerWidth < 1200;
isMobileWidth = window.innerWidth < 780;
// 低于380px强制网格模式
if (window.innerWidth < 380 && currentLayout === "list") {
currentLayout = "grid";
const event = new CustomEvent("layoutChange", {
detail: { layout: "grid" },
});
window.dispatchEvent(event);
}
}
function updateRangeProgress(input: HTMLInputElement) {
const min = Number(input.min || 0);
const max = Number(input.max || 100);
const value = Number(input.value || 0);
const progress = ((value - min) * 100) / (max - min || 1);
input.style.setProperty(
"--range-progress",
`${Math.min(100, Math.max(0, progress))}%`,
);
}
function refreshAllRangeProgress() {
const panel = document.getElementById("display-setting");
if (!panel) return;
const rangeInputs = Array.from(
panel.querySelectorAll('input[type="range"]'),
) as HTMLInputElement[];
rangeInputs.forEach((input) => {
updateRangeProgress(input);
});
}
function switchLayout() {
if (!mounted || isSwitching) return;
isSwitching = true;
currentLayout = currentLayout === "list" ? "grid" : "list";
localStorage.setItem("postListLayout", currentLayout);
// 触发自定义事件,通知页面布局已改变
const event = new CustomEvent("layoutChange", {
detail: { layout: currentLayout },
});
window.dispatchEvent(event);
// 动画完成后重置状态
setTimeout(() => {
isSwitching = false;
}, 500);
}
onMount(() => {
mounted = true;
checkScreenSize();
// 从localStorage读取保存的壁纸模式
wallpaperMode = getStoredWallpaperMode();
// 从localStorage读取水波纹动画状态
wavesEnabled = getStoredWavesEnabled();
// 从localStorage读取渐变过渡状态
gradientEnabled = getStoredGradientEnabled();
// 从localStorage读取横幅标题状态
bannerTitleEnabled = getStoredBannerTitleEnabled();
// 从localStorage读取横幅轮播状态
bannerCarouselEnabled = getStoredBannerCarouselEnabled();
// 从localStorage读取樱花特效状态
sakuraEnabled = getStoredSakuraEnabled();
// 从localStorage读取全屏透明设置状态
overlayOpacity = getStoredOverlayOpacity();
overlayBlur = getStoredOverlayBlur();
overlayCardOpacity = getStoredOverlayCardOpacity();
// 从localStorage读取用户偏好布局
const savedLayout = localStorage.getItem("postListLayout");
if (savedLayout && (savedLayout === "list" || savedLayout === "grid")) {
currentLayout = savedLayout;
} else {
currentLayout =
window.innerWidth < 780 ? mobileDefaultLayout : defaultLayout;
}
// 监听窗口大小变化
window.addEventListener("resize", checkScreenSize);
return () => {
window.removeEventListener("resize", checkScreenSize);
};
});
// 监听布局变化事件
onMount(() => {
const handleCustomEvent = (event: Event) => {
const customEvent = event as CustomEvent<{ layout: "list" | "grid" }>;
currentLayout = customEvent.detail.layout;
};
window.addEventListener("layoutChange", handleCustomEvent);
return () => {
window.removeEventListener("layoutChange", handleCustomEvent);
};
});
onMount(() => {
const panel = document.getElementById("display-setting");
if (!panel) return;
const handleRangeInput = (event: Event) => {
const target = event.target;
if (target instanceof HTMLInputElement && target.type === "range") {
updateRangeProgress(target);
}
};
refreshAllRangeProgress();
panel.addEventListener("input", handleRangeInput);
return () => {
panel.removeEventListener("input", handleRangeInput);
};
});
onMount(() => {
const handleWallpaperModeChange = (event: Event) => {
const customEvent = event as CustomEvent<{ mode: WALLPAPER_MODE }>;
wallpaperMode = customEvent.detail.mode;
};
window.addEventListener("wallpaperModeChange", handleWallpaperModeChange);
return () => {
window.removeEventListener(
"wallpaperModeChange",
handleWallpaperModeChange,
);
};
});
$effect(() => {
if (hue || hue === 0) {
setHue(hue);
}
});
$effect(() => {
if (wallpaperMode === WALLPAPER_OVERLAY) {
if (isOverlayOpacitySwitchable) {
setOverlayOpacity(overlayOpacity);
}
if (isOverlayBlurSwitchable) {
setOverlayBlur(overlayBlur);
}
if (isOverlayCardOpacitySwitchable) {
setOverlayCardOpacity(overlayCardOpacity);
}
}
});
</script>
{#if hasAnyContent}
<div id="display-setting" class="float-panel float-panel-closed absolute transition-all w-80 right-4 px-4 py-2">
<!-- Theme Color Section -->
{#if showThemeColor}
<div class="mt-2 mb-2">
<div class="flex flex-row gap-2 mb-2 items-center justify-between">
<div class="flex gap-2 font-bold text-lg text-neutral-900 dark:text-neutral-100 transition relative ml-3
before:w-1 before:h-4 before:rounded-md before:bg-(--primary)
before:absolute before:-left-3 before:top-1/2 before:-translate-y-1/2"
>
{i18n(I18nKey.themeColor)}
<button aria-label="Reset to Default" class="btn-regular w-7 h-7 rounded-md active:scale-90"
class:opacity-0={hue === defaultHue} class:pointer-events-none={hue === defaultHue} onclick={resetHue}>
<div class="text-(--btn-content)">
<Icon icon="fa7-solid:arrow-rotate-left" class="text-[0.875rem]"></Icon>
</div>
</button>
</div>
<div class="flex gap-1">
<div id="hueValue" class="transition bg-(--btn-regular-bg) w-10 h-7 rounded-md flex justify-center
font-bold text-sm items-center text-(--btn-content)">
{hue}
</div>
</div>
</div>
<div class="w-full h-6 px-1 bg-[oklch(0.80_0.10_0)] dark:bg-[oklch(0.70_0.10_0)] rounded-sm select-none">
<input aria-label={i18n(I18nKey.themeColor)} type="range" min="0" max="360" bind:value={hue}
class="slider" id="colorSlider" step="5" style="width: 100%">
</div>
</div>
{/if}
<!-- Wallpaper Mode Section -->
{#if isWallpaperSwitchable}
<div class="mt-2 mb-2">
<div class="flex gap-2 font-bold text-lg text-neutral-900 dark:text-neutral-100 transition relative ml-3 mb-2
before:w-1 before:h-4 before:rounded-md before:bg-(--primary)
before:absolute before:-left-3 before:top-1/2 before:-translate-y-1/2"
>
{i18n(I18nKey.wallpaperMode)}
<button aria-label="Reset to Default" class="btn-regular w-7 h-7 rounded-md active:scale-90"
class:opacity-0={wallpaperMode === defaultWallpaperMode} class:pointer-events-none={wallpaperMode === defaultWallpaperMode} onclick={resetWallpaperMode}>
<div class="text-(--btn-content)">
<Icon icon="fa7-solid:arrow-rotate-left" class="text-[0.875rem]"></Icon>
</div>
</button>
</div>
<div class="flex gap-2">
<button
class="flex-1 btn-regular rounded-md py-2 px-3 flex items-center justify-center gap-2 active:scale-95 transition-all relative overflow-hidden"
class:opacity-60={wallpaperMode !== WALLPAPER_BANNER}
class:bg-(--btn-regular-bg-hover)={wallpaperMode === WALLPAPER_BANNER}
onclick={() => switchWallpaperMode(WALLPAPER_BANNER)}
>
<Icon icon="material-symbols:image-outline" class="text-[1.25rem] shrink-0"></Icon>
<span class="text-xs font-medium">{i18n(I18nKey.wallpaperBannerMode)}</span>
</button>
<button
class="flex-1 btn-regular rounded-md py-2 px-3 flex items-center justify-center gap-2 active:scale-95 transition-all relative overflow-hidden"
class:opacity-60={wallpaperMode !== WALLPAPER_FULLSCREEN}
class:bg-(--btn-regular-bg-hover)={wallpaperMode === WALLPAPER_FULLSCREEN}
onclick={() => switchWallpaperMode(WALLPAPER_FULLSCREEN)}
>
<Icon icon="material-symbols:wallpaper" class="text-[1.25rem] shrink-0"></Icon>
<span class="text-xs font-medium">{i18n(I18nKey.wallpaperFullscreenMode)}</span>
</button>
</div>
<div class="flex gap-2 mt-2">
<button
class="flex-1 btn-regular rounded-md py-2 px-3 flex items-center justify-center gap-2 active:scale-95 transition-all relative overflow-hidden"
class:opacity-60={wallpaperMode !== WALLPAPER_OVERLAY}
class:bg-(--btn-regular-bg-hover)={wallpaperMode === WALLPAPER_OVERLAY}
onclick={() => switchWallpaperMode(WALLPAPER_OVERLAY)}
>
<Icon icon="material-symbols:full-coverage-outline-rounded" class="text-[1.25rem] shrink-0"></Icon>
<span class="text-xs font-medium">{i18n(I18nKey.wallpaperOverlayMode)}</span>
</button>
<button
class="flex-1 btn-regular rounded-md py-2 px-3 flex items-center justify-center gap-2 active:scale-95 transition-all relative overflow-hidden"
class:opacity-60={wallpaperMode !== WALLPAPER_NONE}
class:bg-(--btn-regular-bg-hover)={wallpaperMode === WALLPAPER_NONE}
onclick={() => switchWallpaperMode(WALLPAPER_NONE)}
>
<Icon icon="material-symbols:hide-image-outline" class="text-[1.25rem] shrink-0"></Icon>
<span class="text-xs font-medium">{i18n(I18nKey.wallpaperNoneMode)}</span>
</button>
</div>
</div>
{/if}
<!-- Overlay Settings Section -->
{#if wallpaperMode === WALLPAPER_OVERLAY && hasOverlaySettings}
<div class="mt-2 mb-2">
<div class="flex gap-2 font-bold text-lg text-neutral-900 dark:text-neutral-100 transition relative ml-3 mb-2
before:w-1 before:h-4 before:rounded-md before:bg-(--primary)
before:absolute before:-left-3 before:top-1/2 before:-translate-y-1/2"
>
{i18n(I18nKey.overlaySettings)}
<button aria-label="Reset to Default" class="btn-regular w-7 h-7 rounded-md active:scale-90"
class:opacity-0={overlaySettingsIsDefault} class:pointer-events-none={overlaySettingsIsDefault} onclick={resetOverlaySettings}>
<div class="text-(--btn-content)">
<Icon icon="fa7-solid:arrow-rotate-left" class="text-[0.875rem]"></Icon>
</div>
</button>
</div>
<div class="space-y-2">
{#each overlaySliderItems as item (item.key)}
{#if item.enabled}
<div class="rounded-md bg-(--btn-regular-bg) p-2">
<div class="flex items-center justify-between mb-1">
<span class="text-sm font-medium text-(--btn-content) opacity-80">{item.label}</span>
<span class="text-xs text-(--btn-content)">{item.displayValue}</span>
</div>
<input
aria-label={item.ariaLabel}
type="range"
min={item.min}
max={item.max}
step={item.step}
value={item.value}
oninput={(e) => item.onValueChange(Number((e.currentTarget as HTMLInputElement).value))}
class="slider w-full overlay-slider"
/>
</div>
{/if}
{/each}
</div>
</div>
{/if}
<!-- Banner Settings Section -->
{#if (wallpaperMode === WALLPAPER_BANNER || wallpaperMode === WALLPAPER_FULLSCREEN) && hasBannerSettings}
<div class="mt-2 mb-2">
<div class="flex gap-2 font-bold text-lg text-neutral-900 dark:text-neutral-100 transition relative ml-3 mb-2
before:w-1 before:h-4 before:rounded-md before:bg-(--primary)
before:absolute before:-left-3 before:top-1/2 before:-translate-y-1/2"
>
{i18n(I18nKey.wallpaperSettings)}
<button aria-label="Reset to Default" class="btn-regular w-7 h-7 rounded-md active:scale-90"
class:opacity-0={bannerSettingsIsDefault} class:pointer-events-none={bannerSettingsIsDefault} onclick={resetBannerSettings}>
<div class="text-(--btn-content)">
<Icon icon="fa7-solid:arrow-rotate-left" class="text-[0.875rem]"></Icon>
</div>
</button>
</div>
<div class="space-y-1">
<!-- Banner Title Switch -->
{#if isBannerTitleSwitchable}
<button
class="w-full btn-regular rounded-md py-2 px-3 flex items-center gap-3 text-left active:scale-95 transition-all relative overflow-hidden"
class:bg-(--btn-regular-bg-hover)={bannerTitleEnabled}
onclick={toggleBannerTitleEnabled}
>
<Icon icon="material-symbols:titlecase-rounded" class="text-[1.25rem] shrink-0"></Icon>
<span class="text-sm flex-1">{i18n(I18nKey.wallpaperTitle)}</span>
<div class="w-10 h-5 rounded-full transition-all duration-200 relative"
class:bg-(--primary)={bannerTitleEnabled}
class:bg-(--btn-regular-bg-active)={!bannerTitleEnabled}>
<div class="absolute top-0.5 w-4 h-4 bg-white rounded-full shadow transition-all duration-200"
class:left-0.5={!bannerTitleEnabled}
class:left-5={bannerTitleEnabled}></div>
</div>
</button>
{/if}
<!-- Banner Carousel Switch -->
{#if isBannerCarouselSwitchable}
<button
class="w-full btn-regular rounded-md py-2 px-3 flex items-center gap-3 text-left active:scale-95 transition-all relative overflow-hidden"
class:bg-(--btn-regular-bg-hover)={bannerCarouselEnabled}
onclick={toggleBannerCarouselEnabled}
>
<Icon icon="material-symbols:view-carousel-outline" class="text-[1.25rem] shrink-0"></Icon>
<span class="text-sm flex-1">{i18n(I18nKey.wallpaperCarousel)}</span>
<div class="w-10 h-5 rounded-full transition-all duration-200 relative"
class:bg-(--primary)={bannerCarouselEnabled}
class:bg-(--btn-regular-bg-active)={!bannerCarouselEnabled}>
<div class="absolute top-0.5 w-4 h-4 bg-white rounded-full shadow transition-all duration-200"
class:left-0.5={!bannerCarouselEnabled}
class:left-5={bannerCarouselEnabled}></div>
</div>
</button>
{/if}
<!-- Waves Animation Switch -->
{#if isWavesSwitchable}
<button
class="w-full btn-regular rounded-md py-2 px-3 flex items-center gap-3 text-left active:scale-95 transition-all relative overflow-hidden"
class:bg-(--btn-regular-bg-hover)={wavesEnabled}
onclick={toggleWavesEnabled}
>
<Icon icon="material-symbols:airwave-rounded" class="text-[1.25rem] shrink-0"></Icon>
<span class="text-sm flex-1">{i18n(I18nKey.wavesAnimation)}</span>
<div class="w-10 h-5 rounded-full transition-all duration-200 relative"
class:bg-(--primary)={wavesEnabled}
class:bg-(--btn-regular-bg-active)={!wavesEnabled}>
<div class="absolute top-0.5 w-4 h-4 bg-white rounded-full shadow transition-all duration-200"
class:left-0.5={!wavesEnabled}
class:left-5={wavesEnabled}></div>
</div>
</button>
{/if}
<!-- Gradient Transition Switch -->
{#if isGradientSwitchable}
<button
class="w-full btn-regular rounded-md py-2 px-3 flex items-center gap-3 text-left active:scale-95 transition-all relative overflow-hidden"
class:bg-(--btn-regular-bg-hover)={gradientEnabled}
onclick={toggleGradientEnabled}
>
<Icon icon="material-symbols:gradient" class="text-[1.25rem] shrink-0"></Icon>
<span class="text-sm flex-1">{i18n(I18nKey.gradientTransition)}</span>
<div class="w-10 h-5 rounded-full transition-all duration-200 relative"
class:bg-(--primary)={gradientEnabled}
class:bg-(--btn-regular-bg-active)={!gradientEnabled}>
<div class="absolute top-0.5 w-4 h-4 bg-white rounded-full shadow transition-all duration-200"
class:left-0.5={!gradientEnabled}
class:left-5={gradientEnabled}></div>
</div>
</button>
{/if}
</div>
</div>
{/if}
<!-- Effects Settings Section -->
{#if isSakuraSwitchable}
<div class="mt-2 mb-2">
<div class="flex gap-2 font-bold text-lg text-neutral-900 dark:text-neutral-100 transition relative ml-3 mb-2
before:w-1 before:h-4 before:rounded-md before:bg-(--primary)
before:absolute before:-left-3 before:top-1/2 before:-translate-y-1/2"
>
{i18n(I18nKey.effectsSettings)}
<button aria-label="Reset to Default" class="btn-regular w-7 h-7 rounded-md active:scale-90"
class:opacity-0={sakuraEnabled === defaultSakuraEnabled} class:pointer-events-none={sakuraEnabled === defaultSakuraEnabled} onclick={() => { sakuraEnabled = defaultSakuraEnabled; setSakuraEnabled(defaultSakuraEnabled); }}>
<div class="text-(--btn-content)">
<Icon icon="fa7-solid:arrow-rotate-left" class="text-[0.875rem]"></Icon>
</div>
</button>
</div>
<div class="space-y-1">
<button
class="w-full btn-regular rounded-md py-2 px-3 flex items-center gap-3 text-left active:scale-95 transition-all relative overflow-hidden"
class:bg-(--btn-regular-bg-hover)={sakuraEnabled}
onclick={toggleSakuraEnabled}
>
<Icon icon="mdi:flower-poppy" class="text-[1.25rem] shrink-0"></Icon>
<span class="text-sm flex-1">{i18n(I18nKey.sakuraEffect)}</span>
<div class="w-10 h-5 rounded-full transition-all duration-200 relative"
class:bg-(--primary)={sakuraEnabled}
class:bg-(--btn-regular-bg-active)={!sakuraEnabled}>
<div class="absolute top-0.5 w-4 h-4 bg-white rounded-full shadow transition-all duration-200"
class:left-0.5={!sakuraEnabled}
class:left-5={sakuraEnabled}></div>
</div>
</button>
</div>
</div>
{/if}
<!-- Layout Switch Section -->
{#if allowLayoutSwitch}
<div class="mt-2 mb-2">
<div class="flex gap-2 font-bold text-lg text-neutral-900 dark:text-neutral-100 transition relative ml-3 mb-2
before:w-1 before:h-4 before:rounded-md before:bg-(--primary)
before:absolute before:-left-3 before:top-1/2 before:-translate-y-1/2"
>
{i18n(I18nKey.postListLayout)}
<button aria-label="Reset to Default" class="btn-regular w-7 h-7 rounded-md active:scale-90"
class:opacity-0={currentLayout === effectiveDefaultLayout} class:pointer-events-none={currentLayout === effectiveDefaultLayout} onclick={resetLayout}>
<div class="text-(--btn-content)">
<Icon icon="fa7-solid:arrow-rotate-left" class="text-[0.875rem]"></Icon>
</div>
</button>
</div>
<div class="flex gap-2">
<button
aria-label={i18n(I18nKey.postListLayoutList)}
class="flex-1 btn-regular rounded-md py-2 px-3 flex items-center justify-center gap-2 active:scale-95 transition-all relative overflow-hidden"
class:opacity-60={currentLayout !== 'list'}
class:bg-(--btn-regular-bg-hover)={currentLayout === 'list'}
disabled={isSwitching}
onclick={switchLayout}
title={i18n(I18nKey.postListLayoutList)}
>
<svg class="w-4 h-4" fill="currentColor" viewBox="0 0 24 24">
<path d="M4 6h16v2H4zm0 5h16v2H4zm0 5h16v2H4z"/>
</svg>
<span class="text-xs font-medium">{i18n(I18nKey.postListLayoutList)}</span>
</button>
<button
aria-label={i18n(I18nKey.postListLayoutGrid)}
class="flex-1 btn-regular rounded-md py-2 px-3 flex items-center justify-center gap-2 active:scale-95 transition-all relative overflow-hidden"
class:opacity-60={currentLayout !== 'grid'}
class:bg-(--btn-regular-bg-hover)={currentLayout === 'grid'}
disabled={isSwitching}
onclick={switchLayout}
title={i18n(I18nKey.postListLayoutGrid)}
>
<svg class="w-4 h-4" fill="currentColor" viewBox="0 0 24 24">
<path d="M3 3h7v7H3V3zm0 11h7v7H3v-7zm11-11h7v7h-7V3zm0 11h7v7h-7v-7z"/>
</svg>
<span class="text-xs font-medium">{i18n(I18nKey.postListLayoutGrid)}</span>
</button>
</div>
</div>
{/if}
</div>
{/if}
<style lang="stylus">
#display-setting
input[type="range"]
-webkit-appearance none
height 1.5rem
border-radius 999px
background-image unquote("linear-gradient(90deg, var(--primary) 0 var(--range-progress, 50%), hsla(var(--hue), 22%, 28%, 0.18) var(--range-progress, 50%) 100%)")
transition background-image 0.15s ease-in-out
input[type="range"].overlay-slider
height 0.85rem
/* Input Thumb */
&::-webkit-slider-thumb
-webkit-appearance none
height 0
width 0
border 0
border-radius 0
background transparent
box-shadow none
&::-moz-range-thumb
height 0
width 0
border 0
border-radius 0
background transparent
box-shadow none
&::-ms-thumb
-webkit-appearance none
height 0
width 0
border 0
border-radius 0
background transparent
box-shadow none
#colorSlider
background-image var(--color-selection-bar)
transition background-image 0.15s ease-in-out
&::-webkit-slider-thumb
-webkit-appearance none
height 1rem
width 0.5rem
border-radius 0.125rem
background rgba(255, 255, 255, 0.7)
box-shadow none
&:hover
background rgba(255, 255, 255, 0.8)
&:active
background rgba(255, 255, 255, 0.6)
&::-moz-range-thumb
-webkit-appearance none
height 1rem
width 0.5rem
border-radius 0.125rem
border-width 0
background rgba(255, 255, 255, 0.7)
box-shadow none
&:hover
background rgba(255, 255, 255, 0.8)
&:active
background rgba(255, 255, 255, 0.6)
&::-ms-thumb
-webkit-appearance none
height 1rem
width 0.5rem
border-radius 0.125rem
background rgba(255, 255, 255, 0.7)
box-shadow none
&:hover
background rgba(255, 255, 255, 0.8)
&:active
background rgba(255, 255, 255, 0.6)
</style>
@@ -0,0 +1,83 @@
---
import type { MarkdownHeading } from "astro";
import BackToComment from "./BackToComment.astro";
import BackToHome from "./BackToHome.astro";
import BackToTop from "./BackToTop.astro";
import FloatingTOC from "./FloatingTOC.astro";
interface Props {
headings?: MarkdownHeading[];
encrypted?: boolean;
}
const { headings, encrypted } = Astro.props;
---
<div class="floating-controls-container">
<FloatingTOC headings={headings ?? []} encrypted={encrypted} />
<BackToComment />
<BackToHome />
<BackToTop />
</div>
<style>
.floating-controls-container {
position: fixed;
z-index: 1000;
display: flex;
flex-direction: column;
gap: 0.5rem;
align-items: flex-end; /* 右对齐 */
pointer-events: none; /* 容器不阻挡点击 */
/* 默认桌面端位置 - 对应 BackToTop 的位置 */
right: 1rem;
bottom: 4rem;
}
/* 响应式调整 - 保持原有的位置逻辑 */
@media (max-width: 1024px) {
.floating-controls-container {
right: 1rem;
bottom: 4rem;
}
}
@media (max-width: 768px) {
.floating-controls-container {
right: 0.75rem;
bottom: 4rem;
gap: 0.5rem;
}
}
@media (max-width: 480px) {
.floating-controls-container {
right: 0.5rem;
bottom: 4rem;
}
}
/* 高缩放比例适配 */
@media (min-resolution: 2dppx) {
.floating-controls-container {
right: max(0.5rem, 2rem - 2vw);
bottom: max(3rem, 4rem - 5vh);
}
}
/* 横屏模式适配 */
@media (orientation: landscape) and (max-height: 500px) {
.floating-controls-container {
bottom: 4rem;
}
}
/* 极低分辨率适配 */
@media (max-width: 320px) {
.floating-controls-container {
right: 0.125rem;
bottom: 4rem;
}
}
</style>
+381
View File
@@ -0,0 +1,381 @@
---
import type { MarkdownHeading } from "astro";
import FloatingButton from "@/components/common/FloatingButton.astro";
import { sidebarLayoutConfig } from "@/config/sidebarConfig";
import I18nKey from "@/i18n/i18nKey";
import { i18n } from "@/i18n/translation";
import "@/styles/toc.css";
import { computeTocItems } from "@/utils/toc-shared";
interface Props {
headings: MarkdownHeading[];
encrypted?: boolean;
}
const { headings = [], encrypted = false } = Astro.props;
// 加密文章不在服务端渲染目录(避免标题泄露),交由客户端解密后生成
const items = encrypted ? [] : computeTocItems(headings, { maxLevel: 3 });
// 检查侧边栏目录组件是否启用
const sidebarTocComponent = sidebarLayoutConfig.rightComponents?.find(
(c) => c.type === "sidebarToc",
);
const isSidebarTocEnabled = sidebarTocComponent?.enable ?? false;
const sidebarPosition = sidebarLayoutConfig.position;
const hideSidebarOnPostPage =
sidebarLayoutConfig.hideSidebarOnPostPage === true;
---
<!-- 悬浮TOC按钮 -->
<div id="floating-toc-wrapper" class="floating-toc-wrapper" data-is-sidebar-toc-enabled={String(isSidebarTocEnabled)} data-sidebar-position={sidebarPosition} data-show-both-sidebars-on-post={String(sidebarLayoutConfig.showBothSidebarsOnPostPage ?? false)} data-hide-sidebar-on-post={String(hideSidebarOnPostPage)}>
<FloatingButton
id="floating-toc-btn"
icon="material-symbols:format-list-bulleted"
toggleIcon="material-symbols:close"
ariaLabel="Table of Contents"
onclick="window.toggleFloatingTOC()"
class="hide"
/>
<!-- 悬浮TOC面板 - 移到 Wrapper 内部以便相对定位 -->
<div
id="floating-toc-panel"
class="floating-toc-panel hide overflow-hidden rounded-2xl shadow-2xl backdrop-blur-lg border border-white/20 dark:border-white/10 md:w-80 w-[calc(100vw-2rem)] md:max-h-96 max-h-[calc(100vh-8rem)] py-3"
style="background-color: var(--card-bg-transparent);"
>
<div class="toc-scroll-container px-3">
<div
class="toc-content"
id="floating-toc-content"
style="width: 100%; max-width: 100%;"
>
{!encrypted && items.length > 0 && (
<>
{items.map((item) => (
<a
href={item.href}
class={`toc-item toc-level-${item.depthLevel}`}
data-heading-id={item.headingId}
aria-label={item.text}
title={item.text}
>
<div class={`toc-badge ${item.badgeKind === "index" ? "toc-badge-index" : ""}`}>
{item.badgeKind === "index" ? (
item.badgeIndex
) : item.badgeKind === "dot" ? (
<span class="toc-badge-dot"></span>
) : (
<span class="toc-badge-dot toc-badge-dot-sm"></span>
)}
</div>
<div class={`toc-label ${item.labelPrimary ? "toc-label-primary" : "toc-label-secondary"}`}>
{item.text}
</div>
</a>
))}
<div id="floating-active-indicator" class="toc-active-indicator" style="opacity: 0;"></div>
</>
)}
{!encrypted && items.length === 0 && (
<div class="text-center py-8 text-gray-500 dark:text-gray-400">
<p>{i18n(I18nKey.tocEmpty)}</p>
</div>
)}
{/* 加密文章:留空,客户端解密后由 TOCManager 填充 */}
</div>
</div>
</div>
</div>
<style lang="stylus">
.floating-toc-wrapper
position: relative
z-index: 999
overflow: visible
.floating-toc-panel
position: absolute
bottom: calc(100% + 1rem)
right: 0
transition: all 0.3s ease
transform: translateY(20px)
opacity: 0
pointer-events: none
overflow: hidden
box-sizing: border-box
backdrop-filter: blur(20px)
-webkit-backdrop-filter: blur(20px)
z-index: 1001
&.show
transform: translateY(0)
opacity: 1
pointer-events: auto
&.hide
transform: translateY(20px)
opacity: 0
pointer-events: none
visibility: hidden
.toc-scroll-container
/* 面板 max-height 24rem 减去面板自身 py-3 上下共 1.5rem */
max-height: calc(24rem - 1.5rem)
@media (max-width: 768px)
max-height: calc(24rem - 1.5rem)
/* 响应式调整 - 仅保留 Panel 尺寸调整 */
@media (max-width: 1024px)
.floating-toc-panel
width: calc(100vw - 2rem)
max-width: 20rem
max-height: 20rem
@media (max-width: 768px)
.floating-toc-panel
width: calc(100vw - 1.5rem)
max-width: 20rem
max-height: 28rem
bottom: calc(100% + 1rem)
/* 暗色主题半透明效果 */
:global(.dark) .floating-toc-panel
backdrop-filter: blur(20px)
-webkit-backdrop-filter: blur(20px)
</style>
<script>
import { TOCManager, isPostPage } from "@/utils/toc-utils";
// 从 data 属性读取配置
const wrapper = document.querySelector('.floating-toc-wrapper');
const isSidebarTocEnabled = wrapper?.getAttribute('data-is-sidebar-toc-enabled') === 'true';
if (typeof window.FloatingTOC === "undefined") {
window.FloatingTOC = {
btn: null,
panel: null,
manager: null,
isPostPage: isPostPage // 使用导入的工具函数
};
}
// 切换 TOC 面板(按钮图标随开关在 列表/X 之间切换)
window.toggleFloatingTOC = function () {
const panel = window.FloatingTOC.panel;
const btn = window.FloatingTOC.btn;
if (!panel) return;
const isHidden = panel.classList.contains("hide");
if (isHidden) {
panel.classList.remove("hide");
panel.classList.add("show");
btn?.classList.add("toggled");
} else {
panel.classList.remove("show");
panel.classList.add("hide");
btn?.classList.remove("toggled");
}
};
// 关闭 TOC 面板
function closeTOC() {
const panel = window.FloatingTOC.panel;
const btn = window.FloatingTOC.btn;
if (panel && !panel.classList.contains("hide")) {
panel.classList.add("hide");
panel.classList.remove("show");
}
btn?.classList.remove("toggled");
}
// 设置自动关闭功能
function setupAutoClose() {
// 监听页面卸载和隐藏
window.addEventListener("beforeunload", closeTOC);
window.addEventListener("pagehide", closeTOC);
window.addEventListener("popstate", closeTOC);
document.addEventListener("visibilitychange", () => {
if (document.hidden) closeTOC();
});
// 监听 Astro 页面切换
document.addEventListener("astro:page-load", closeTOC);
document.addEventListener("astro:before-preparation", closeTOC);
// 监听 hashchange(排除TOC内部导航)
window.addEventListener("hashchange", () => {
if (!window.tocInternalNavigation) {
closeTOC();
}
window.tocInternalNavigation = false;
});
// 监听外部链接点击
document.addEventListener("click", (e) => {
const target = e.target as Element | null;
const link = target?.closest("a");
if (!link || !link.href) return;
const href = link.getAttribute("href");
const isExternalLink = href && !href.startsWith("#") && !href.startsWith("javascript:");
if (isExternalLink && !window.tocInternalNavigation) {
const tocPanel = document.getElementById("floating-toc-panel");
if (!tocPanel || !tocPanel.contains(link)) {
closeTOC();
}
}
});
// 拦截 history API
const originalPushState = history.pushState;
const originalReplaceState = history.replaceState;
history.pushState = function (...args) {
closeTOC();
return originalPushState.apply(this, args);
};
history.replaceState = function (...args) {
closeTOC();
return originalReplaceState.apply(this, args);
};
}
// 检查是否应该显示悬浮目录
function shouldShowFloatingTOC() {
// 检查是否为文章页面
if (!window.FloatingTOC.isPostPage()) {
return false;
}
const wrapper = document.querySelector('.floating-toc-wrapper');
const sidebarPosition = wrapper?.getAttribute('data-sidebar-position') || 'left';
const showBothSidebarsOnPost = wrapper?.getAttribute('data-show-both-sidebars-on-post') === 'true';
const hideSidebarOnPost = wrapper?.getAttribute('data-hide-sidebar-on-post') === 'true';
// 侧边栏在文章页隐藏时,始终显示悬浮目录
if (hideSidebarOnPost) {
return true;
}
// 双侧边栏模式(含文章页临时双侧栏):小屏幕或侧边栏目录未启用时显示悬浮目录
const effectiveIsBothSidebars = sidebarPosition === 'both' || showBothSidebarsOnPost;
if (effectiveIsBothSidebars) {
const isSmallScreen = window.innerWidth < 1280;
return isSmallScreen || !isSidebarTocEnabled;
}
// 单侧边栏模式(left或right),对侧没有侧边栏目录,始终显示悬浮目录
return true;
}
// 更新悬浮目录的显示状态
function updateFloatingTOCVisibility() {
const btn = window.FloatingTOC.btn;
if (!btn) return;
if (shouldShowFloatingTOC()) {
btn.classList.remove("hide");
} else {
btn.classList.add("hide");
// 同时关闭面板
closeTOC();
}
}
// 初始化 FloatingTOC
async function initFloatingTOC() {
window.FloatingTOC.btn = document.getElementById("floating-toc-btn");
window.FloatingTOC.panel = document.getElementById("floating-toc-panel");
if (!window.FloatingTOC.btn || !window.FloatingTOC.panel) {
return;
}
// 更新显示状态
updateFloatingTOCVisibility();
try {
// 清理旧实例
if (window.FloatingTOC.manager) {
window.FloatingTOC.manager.cleanup();
}
// 创建新实例
window.FloatingTOC.manager = new TOCManager({
contentId: "floating-toc-content",
indicatorId: "floating-active-indicator",
maxLevel: 3,
scrollOffset: 80,
});
// attach() 自校正:SSR 锚点与当前正文一致则直接附着;
// 缺失或过时(加密未解密/异常情况)则自动回退 DOM 遍历重建。
window.FloatingTOC.manager.attach();
// 设置点击事件 - 标记为 TOC 内部导航
const tocContent = document.getElementById("floating-toc-content");
if (tocContent) {
tocContent.addEventListener("click", (e) => {
const target = e.target as Element | null;
const anchor = target?.closest('a[href^="#"]');
if (anchor) {
window.tocInternalNavigation = true;
}
}, { capture: true });
}
// 设置自动关闭
setupAutoClose();
} catch (error) {
console.error("Failed to load TOCManager:", error);
}
}
// 初始化
initFloatingTOC();
// 监听页面切换事件
if (typeof window !== "undefined" && !window.floatingTOCListenersInitialized) {
window.floatingTOCListenersInitialized = true;
// Swup 路由切换
document.addEventListener("swup:contentReplaced", () => {
setTimeout(initFloatingTOC, 100);
});
// Astro 页面切换事件
document.addEventListener("astro:page-load", () => {
setTimeout(initFloatingTOC, 100);
});
// 浏览器导航事件
window.addEventListener("popstate", () => {
setTimeout(initFloatingTOC, 200);
});
// 监听布局模式切换(通过自定义事件)
window.addEventListener('layoutChange', () => {
updateFloatingTOCVisibility();
});
// 密码解密后重新初始化 TOC
document.addEventListener("password:decrypted", () => {
setTimeout(initFloatingTOC, 200);
});
// 监听窗口大小变化
let resizeTimeout: ReturnType<typeof setTimeout>;
window.addEventListener('resize', () => {
clearTimeout(resizeTimeout);
resizeTimeout = setTimeout(() => {
updateFloatingTOCVisibility();
}, 300);
});
}
</script>
@@ -0,0 +1,170 @@
<script lang="ts">
import { onMount } from "svelte";
import { siteConfig } from "@/config";
export let currentLayout: "list" | "grid" = "list";
/**
* 文章列表布局切换按钮
* 目前已弃用,已集成至DisplaySettingsIntegrated.svelte,当前文件保留以备将来可能的单独使用
*/
let mounted = false;
let isSmallScreen = false;
let isSwitching = false;
function checkScreenSize() {
isSmallScreen = window.innerWidth < 1200;
if (isSmallScreen) {
currentLayout = "list";
}
}
onMount(() => {
mounted = true;
checkScreenSize();
// 从localStorage读取用户偏好,如果没有则使用传入的默认值
const savedLayout = localStorage.getItem("postListLayout");
if (savedLayout && (savedLayout === "list" || savedLayout === "grid")) {
currentLayout = savedLayout;
} else {
// 如果没有保存的偏好,根据视口宽度使用对应的默认布局
const mobileDefault =
siteConfig.postListLayout.mobileDefaultMode ||
siteConfig.postListLayout.defaultMode;
currentLayout =
window.innerWidth < 780
? mobileDefault
: currentLayout || siteConfig.postListLayout.defaultMode;
}
// 监听窗口大小变化
window.addEventListener("resize", checkScreenSize);
return () => {
window.removeEventListener("resize", checkScreenSize);
};
});
function switchLayout() {
if (!mounted || isSmallScreen || isSwitching) return;
isSwitching = true;
currentLayout = currentLayout === "list" ? "grid" : "list";
localStorage.setItem("postListLayout", currentLayout);
// 触发自定义事件,通知父组件布局已改变
const event = new CustomEvent("layoutChange", {
detail: { layout: currentLayout },
});
window.dispatchEvent(event);
// 动画完成后重置状态
setTimeout(() => {
isSwitching = false;
}, 500);
}
// 监听布局变化事件
onMount(() => {
const handleCustomEvent = (event: Event) => {
const customEvent = event as CustomEvent<{ layout: "list" | "grid" }>;
currentLayout = customEvent.detail.layout;
};
window.addEventListener("layoutChange", handleCustomEvent);
return () => {
window.removeEventListener("layoutChange", handleCustomEvent);
};
});
// 监听PostPage的布局初始化事件
onMount(() => {
const handleLayoutInit = () => {
// 从PostPage获取当前布局状态
const postListContainer = document.getElementById("post-list-container");
if (postListContainer) {
const isGridMode = postListContainer.classList.contains("grid-mode");
currentLayout = isGridMode ? "grid" : "list";
}
};
// 延迟执行,确保PostPage已经初始化
setTimeout(handleLayoutInit, 100);
return () => {
// 清理函数
};
});
</script>
{#if mounted && siteConfig.postListLayout.allowSwitch && !isSmallScreen}
<button
aria-label="切换文章列表布局"
class="btn-plain scale-animation rounded-lg h-11 w-11 active:scale-90 flex items-center justify-center theme-switch-btn {isSwitching ? 'switching' : ''}"
on:click={switchLayout}
disabled={isSwitching}
title={currentLayout === 'list' ? '切换到网格模式' : '切换到列表模式'}
>
{#if currentLayout === 'list'}
<!-- 列表图标 -->
<svg class="w-5 h-5 icon-transition" fill="currentColor" viewBox="0 0 24 24">
<path d="M4 6h16v2H4zm0 5h16v2H4zm0 5h16v2H4z"/>
</svg>
{:else}
<!-- 网格图标 -->
<svg class="w-5 h-5 icon-transition" fill="currentColor" viewBox="0 0 24 24">
<path d="M3 3h7v7H3V3zm0 11h7v7H3v-7zm11-11h7v7h-7V3zm0 11h7v7h-7v-7z"/>
</svg>
{/if}
</button>
{/if}
<style>
/* 确保主题切换按钮的背景色即时更新 */
.theme-switch-btn::before {
transition: transform 75ms ease-out, background-color 0ms !important;
}
/* 图标过渡动画 */
.icon-transition {
transition: transform 0.3s cubic-bezier(0.4, 0, 0.2, 1), opacity 0.3s ease;
}
/* 切换中的按钮动画 */
.switching {
pointer-events: none;
}
.switching .icon-transition {
animation: iconRotate 0.5s cubic-bezier(0.4, 0, 0.2, 1);
}
@keyframes iconRotate {
0% {
transform: rotate(0deg) scale(1);
opacity: 1;
}
50% {
transform: rotate(180deg) scale(0.8);
opacity: 0.5;
}
100% {
transform: rotate(360deg) scale(1);
opacity: 1;
}
}
/* 悬停效果增强 */
.theme-switch-btn:not(.switching):hover .icon-transition {
transform: scale(1.1);
}
/* 按钮禁用状态 */
.theme-switch-btn:disabled {
cursor: not-allowed;
opacity: 0.7;
}
</style>
@@ -0,0 +1,158 @@
<script lang="ts">
import I18nKey from "@i18n/i18nKey";
import { i18n } from "@i18n/translation";
import { onMount } from "svelte";
import DropdownItem from "@/components/common/DropdownItem.svelte";
import DropdownPanel from "@/components/common/DropdownPanel.svelte";
import Icon from "@/components/common/Icon.svelte";
import { DARK_MODE, LIGHT_MODE, SYSTEM_MODE } from "@/constants/constants";
import type { LIGHT_DARK_MODE } from "@/types/config.ts";
import {
applyThemeToDocument,
getStoredTheme,
setTheme,
} from "@/utils/setting-utils";
// Define Swup type for window object
interface SwupHooks {
on(event: string, callback: () => void): void;
}
interface SwupInstance {
hooks?: SwupHooks;
}
type WindowWithSwup = Window & { swup?: SwupInstance };
let mode: LIGHT_DARK_MODE = $state(LIGHT_MODE);
let displayedMode: LIGHT_DARK_MODE = $state(LIGHT_MODE); // 显示的实际主题(在system模式下会随系统变化)
function switchScheme(newMode: LIGHT_DARK_MODE) {
mode = newMode;
setTheme(newMode);
updateDisplayedMode();
}
// 更新显示的主题(用于显示当前实际主题)
function updateDisplayedMode() {
if (mode === SYSTEM_MODE) {
// 如果是system模式,显示实际的系统主题
const isSystemDark = window.matchMedia(
"(prefers-color-scheme: dark)",
).matches;
displayedMode = isSystemDark ? DARK_MODE : LIGHT_MODE;
} else {
displayedMode = mode;
}
}
// 使用onMount确保在组件挂载后正确初始化
onMount(() => {
// 立即获取并设置正确的主题
const storedTheme = getStoredTheme();
mode = storedTheme;
updateDisplayedMode();
// 确保DOM状态与存储的主题一致(只对非system模式检查)
if (storedTheme !== SYSTEM_MODE) {
const currentTheme = document.documentElement.classList.contains("dark")
? DARK_MODE
: LIGHT_MODE;
if (storedTheme !== currentTheme) {
applyThemeToDocument(storedTheme);
}
}
// 如果是system模式,监听系统主题变化
if (storedTheme === SYSTEM_MODE) {
const mediaQuery = window.matchMedia("(prefers-color-scheme: dark)");
const handleSystemChange = () => {
updateDisplayedMode();
};
mediaQuery.addEventListener("change", handleSystemChange);
}
// 添加Swup监听
const handleContentReplace = () => {
const newTheme = getStoredTheme();
mode = newTheme;
updateDisplayedMode();
};
// 检查Swup是否已经加载
const win = window as WindowWithSwup;
if (win.swup?.hooks) {
win.swup.hooks.on("content:replace", handleContentReplace);
} else {
document.addEventListener("swup:enable", () => {
const w = window as WindowWithSwup;
if (w.swup?.hooks) {
w.swup.hooks.on("content:replace", handleContentReplace);
}
});
}
// 监听主题变化事件
const handleThemeChange = () => {
// 只有当mode不是system模式时才更新mode
// system模式下,mode应该保持为SYSTEM_MODE,displayedMode会自动更新
if (mode !== SYSTEM_MODE) {
const newTheme = getStoredTheme();
mode = newTheme;
updateDisplayedMode();
} else {
// system模式下只需要更新displayedMode
updateDisplayedMode();
}
};
window.addEventListener("theme-change", handleThemeChange);
// 清理函数
return () => {
window.removeEventListener("theme-change", handleThemeChange);
};
});
</script>
<div class="relative z-50">
<button aria-label="Light/Dark Mode" aria-haspopup="menu" class="relative btn-plain scale-animation rounded-lg h-9 w-9 md:h-11 md:w-11 active:scale-90" id="scheme-switch">
<div class="absolute inset-0 flex items-center justify-center" class:opacity-0={displayedMode !== LIGHT_MODE}>
<Icon icon="material-symbols:wb-sunny-outline-rounded" class="text-[1.25rem]"></Icon>
</div>
<div class="absolute inset-0 flex items-center justify-center" class:opacity-0={displayedMode !== DARK_MODE}>
<Icon icon="material-symbols:dark-mode-outline-rounded" class="text-[1.25rem]"></Icon>
</div>
</button>
<div id="theme-mode-panel" class="absolute transition float-panel-closed top-11 -right-2 pt-5 z-50" role="menu" aria-labelledby="scheme-switch">
<DropdownPanel>
<DropdownItem
role="menuitem"
isActive={mode === LIGHT_MODE}
isLast={false}
onclick={() => switchScheme(LIGHT_MODE)}
>
<Icon icon="material-symbols:wb-sunny-outline-rounded" class="text-[1.25rem] mr-3"></Icon>
{i18n(I18nKey.lightMode)}
</DropdownItem>
<DropdownItem
role="menuitem"
isActive={mode === DARK_MODE}
isLast={false}
onclick={() => switchScheme(DARK_MODE)}
>
<Icon icon="material-symbols:dark-mode-outline-rounded" class="text-[1.25rem] mr-3"></Icon>
{i18n(I18nKey.darkMode)}
</DropdownItem>
<DropdownItem
role="menuitem"
isActive={mode === SYSTEM_MODE}
isLast={true}
onclick={() => switchScheme(SYSTEM_MODE)}
>
<Icon icon="material-symbols:brightness-auto-outline-rounded" class="text-[1.25rem] mr-3"></Icon>
{i18n(I18nKey.systemMode)}
</DropdownItem>
</DropdownPanel>
</div>
</div>
@@ -0,0 +1,33 @@
---
import { Icon } from "astro-icon/components";
---
<div
id="scroll-down-indicator"
class="scroll-down-indicator"
onclick="document.getElementById('main-grid')?.scrollIntoView({ behavior: 'smooth' })"
>
<Icon is:inline name="material-symbols:keyboard-arrow-down-rounded" class="scroll-down-icon" />
</div>
<script is:inline>
(function () {
// 防止重复初始化(Swup 页面切换时可能重复执行)
if (window.__scrollDownIndicatorInit) return;
window.__scrollDownIndicatorInit = true;
function updateVisibility() {
var indicator = document.getElementById("scroll-down-indicator");
if (!indicator) return;
var scrollTop = window.pageYOffset || document.documentElement.scrollTop;
if (scrollTop > 100) {
indicator.classList.add("hide");
} else {
indicator.classList.remove("hide");
}
}
window.addEventListener("scroll", updateVisibility, { passive: true });
updateVisibility();
})();
</script>
+243
View File
@@ -0,0 +1,243 @@
<script lang="ts">
import I18nKey from "@i18n/i18nKey";
import { i18n } from "@i18n/translation";
import { navigateToPage } from "@utils/navigation-utils";
import { onMount } from "svelte";
import Icon from "@/components/common/Icon.svelte";
import type { SearchResult } from "@/global";
import { url as formatUrl, getSearchUrl } from "@/utils/url-utils";
// --- State ---
let keywordDesktop = "";
let keywordMobile = "";
let result: SearchResult[] = [];
let isSearching = false;
let initialized = false;
let debounceTimer: NodeJS.Timeout;
// --- Mocks for Dev Mode ---
const fakeResult: SearchResult[] = [
{
url: formatUrl("/"),
meta: { title: "This Is a Fake Search Result" },
excerpt:
"Because Pagefind cannot work in the <mark>dev</mark> environment.",
},
{
url: formatUrl("/"),
meta: { title: "If You Want to Test the Search" },
excerpt: "Try running <mark>npm build && npm preview</mark> instead.",
},
];
// --- UI Logic ---
const togglePanel = () => {
document
.getElementById("search-panel")
?.classList.toggle("float-panel-closed");
};
const setPanelVisibility = (show: boolean, isDesktop: boolean): void => {
const panel = document.getElementById("search-panel");
if (
!panel ||
(isDesktop && !keywordDesktop) ||
(!isDesktop && !keywordMobile)
)
return;
show
? panel.classList.remove("float-panel-closed")
: panel.classList.add("float-panel-closed");
};
const closeSearchPanel = (): void => {
document.getElementById("search-panel")?.classList.add("float-panel-closed");
keywordDesktop = "";
keywordMobile = "";
result = [];
};
const handleResultClick = (event: Event, url: string): void => {
event.preventDefault();
closeSearchPanel();
navigateToPage(url);
};
// --- Core Search Logic ---
const search = async (keyword: string, isDesktop: boolean): Promise<void> => {
if (!keyword) {
setPanelVisibility(false, isDesktop);
result = [];
return;
}
if (!initialized) return;
isSearching = true;
clearTimeout(debounceTimer);
debounceTimer = setTimeout(async () => {
try {
let searchResults: SearchResult[] = [];
if (import.meta.env.PROD && window.pagefind) {
const response = await window.pagefind.search(keyword);
searchResults = await Promise.all(
response.results.map((item) => item.data()),
);
} else if (import.meta.env.DEV) {
searchResults = fakeResult;
}
result = searchResults;
setPanelVisibility(true, isDesktop);
} catch (error) {
console.error("Search error:", error);
result = [];
setPanelVisibility(false, isDesktop);
} finally {
isSearching = false;
}
}, 300); // 300ms debounce
};
// --- Initialization onMount ---
onMount(() => {
const initializePagefind = () => {
initialized = true;
if (keywordDesktop) search(keywordDesktop, true);
if (keywordMobile) search(keywordMobile, false);
};
if (import.meta.env.DEV) {
console.log("Pagefind mock enabled in development mode.");
initializePagefind();
} else {
if (window.pagefind) {
// If script already loaded
initializePagefind();
} else {
// Listen for the event
document.addEventListener("pagefindready", initializePagefind, {
once: true,
});
document.addEventListener("pagefindloaderror", initializePagefind, {
once: true,
});
}
}
});
// --- Reactive Statements ---
$: if (initialized && (keywordDesktop || keywordDesktop === "")) {
search(keywordDesktop, true);
}
$: if (initialized && (keywordMobile || keywordMobile === "")) {
search(keywordMobile, false);
}
</script>
<!-- search bar for desktop view -->
<div id="search-bar" class="hidden lg:flex transition-all items-center h-11 mr-2 rounded-lg
bg-black/4 hover:bg-black/6 focus-within:bg-black/6
dark:bg-white/5 dark:hover:bg-white/10 dark:focus-within:bg-white/10
">
<Icon icon="material-symbols:search"
class="absolute text-[1.25rem] pointer-events-none ml-3 transition my-auto text-black/30 dark:text-white/30"></Icon>
<input placeholder="{i18n(I18nKey.search)}" bind:value={keywordDesktop}
on:focus={() => search(keywordDesktop, true)}
class="transition-all pl-10 text-sm bg-transparent outline-0
h-full w-40 active:w-60 focus:w-60 text-black/50 dark:text-white/50"
>
</div>
<!-- toggle btn for phone/tablet view -->
<button on:click={togglePanel} aria-label="Search Panel" id="search-switch"
class="btn-plain scale-animation lg:hidden! rounded-lg w-9 h-9 md:w-11 md:h-11 active:scale-90">
<Icon icon="material-symbols:search" class="text-[1.25rem]"></Icon>
</button>
<!-- search panel -->
<div id="search-panel" class="float-panel float-panel-closed search-panel absolute md:w-120
top-20 left-4 md:left-[unset] right-4 shadow-2xl rounded-2xl p-2">
<!-- search bar inside panel for phone/tablet -->
<div id="search-bar-inside" class="flex relative lg:hidden transition-all items-center h-11 rounded-xl
bg-black/4 hover:bg-black/6 focus-within:bg-black/6
dark:bg-white/5 dark:hover:bg-white/10 dark:focus-within:bg-white/10
">
<Icon icon="material-symbols:search"
class="absolute text-[1.25rem] pointer-events-none ml-3 transition my-auto text-black/30 dark:text-white/30"></Icon>
<input placeholder={i18n(I18nKey.search)} bind:value={keywordMobile}
class="pl-10 absolute inset-0 text-sm bg-transparent outline-0
focus:w-60 text-black/50 dark:text-white/50"
>
</div>
<!-- search results -->
{#if isSearching}
<div class="transition first-of-type:mt-2 lg:first-of-type:mt-0 block rounded-xl text-lg px-3 py-2 text-50">
{i18n(I18nKey.searchLoading)}
</div>
{:else if result.length > 0}
{#each result.slice(0, 5) as item}
<a href={item.url}
on:click={(e) => handleResultClick(e, item.url)}
class="transition first-of-type:mt-2 lg:first-of-type:mt-0 group block
rounded-xl text-lg px-3 py-2 hover:bg-(--btn-plain-bg-hover) active:bg-(--btn-plain-bg-active)">
<div class="transition text-90 inline-flex font-bold group-hover:text-(--primary)">
{@html item.meta.title}
<Icon icon="fa7-solid:chevron-right"
class="transition text-[0.75rem] translate-x-1 my-auto text-(--primary)"></Icon>
</div>
{#if item.excerpt.includes('<mark>')}
<div class="transition text-sm text-50" style="display: flex; align-items: flex-start; margin-top: 0.1rem">
<div>
{@html item.excerpt}
</div>
</div>
{/if}
{#if item.content && item.content.includes('<mark>')}
<div class="transition text-sm text-30" style="display: flex; align-items: flex-start; margin-top: 0.1rem">
<span style="display: inline-block; background-color: var(--btn-plain-bg-active); color: var(--primary); padding: 0.1em 0.4em; border-radius: 5px; font-size: 0.75em; font-weight: 600; margin-right: 0.5em; shrink: 0;">
{i18n(I18nKey.searchContent)}
</span>
<div>
{@html item.content}
</div>
</div>
{/if}
</a>
{/each}
{#if result.length > 5}
<a href={getSearchUrl(keywordDesktop || keywordMobile)}
on:click={(e) => handleResultClick(e, getSearchUrl(keywordDesktop || keywordMobile))}
class="transition first-of-type:mt-2 lg:first-of-type:mt-0 group block rounded-xl text-lg px-3 py-2 hover:bg-(--btn-plain-bg-hover) active:bg-(--btn-plain-bg-active) text-(--primary) font-bold text-center">
<span class="inline-flex items-center">
{i18n(I18nKey.searchViewMore).replace('{count}', (result.length - 5).toString())}
<Icon icon="fa7-solid:arrow-right" class="transition text-[0.75rem] ml-1"></Icon>
</span>
</a>
{/if}
{:else if result.length === 0}
<div class="transition first-of-type:mt-2 lg:first-of-type:mt-0 block rounded-xl text-lg px-3 py-2 text-50">
{i18n(I18nKey.searchNoResults)}
</div>
{:else if keywordDesktop || keywordMobile}
<div class="transition first-of-type:mt-2 lg:first-of-type:mt-0 block rounded-xl text-lg px-3 py-2 text-50">
{i18n(I18nKey.searchTypeSomething)}
</div>
{/if}
</div>
<style>
input:focus {
outline: 0;
}
.search-panel {
max-height: calc(100vh - 100px);
overflow-y: auto;
}
</style>
@@ -0,0 +1,79 @@
<script lang="ts">
import {
WALLPAPER_BANNER,
WALLPAPER_NONE,
WALLPAPER_OVERLAY,
} from "@constants/constants";
import I18nKey from "@i18n/i18nKey";
import { i18n } from "@i18n/translation";
import { getStoredWallpaperMode, setWallpaperMode } from "@utils/setting-utils";
import { onMount } from "svelte";
import DropdownItem from "@/components/common/DropdownItem.svelte";
import DropdownPanel from "@/components/common/DropdownPanel.svelte";
import Icon from "@/components/common/Icon.svelte";
import { backgroundWallpaper } from "@/config";
import type { WALLPAPER_MODE } from "@/types/config";
/**
* 壁纸模式切换按钮
* 目前已弃用,已集成至DisplaySettingsIntegrated.svelte,当前文件保留以备将来可能的单独使用
*/
let mode: WALLPAPER_MODE = $state(backgroundWallpaper.mode);
// 在组件挂载时从localStorage读取保存的模式
onMount(() => {
mode = getStoredWallpaperMode();
});
function switchWallpaperMode(newMode: WALLPAPER_MODE) {
mode = newMode;
setWallpaperMode(newMode);
}
</script>
<!-- z-50 make the panel higher than other float panels -->
<div class="relative z-50">
<button aria-label="Wallpaper Mode" aria-haspopup="menu" class="relative btn-plain scale-animation rounded-lg h-11 w-11 active:scale-90" id="wallpaper-mode-switch">
<div class="absolute inset-0 flex items-center justify-center" class:opacity-0={mode !== WALLPAPER_BANNER}>
<Icon icon="material-symbols:image-outline" class="text-[1.25rem]"></Icon>
</div>
<div class="absolute inset-0 flex items-center justify-center" class:opacity-0={mode !== WALLPAPER_OVERLAY}>
<Icon icon="material-symbols:wallpaper" class="text-[1.25rem]"></Icon>
</div>
<div class="absolute inset-0 flex items-center justify-center" class:opacity-0={mode !== WALLPAPER_NONE}>
<Icon icon="material-symbols:hide-image-outline" class="text-[1.25rem]"></Icon>
</div>
</button>
<div id="wallpaper-mode-panel" class="absolute transition float-panel-closed top-11 -right-2 pt-5 z-50" role="menu" aria-labelledby="wallpaper-mode-switch">
<DropdownPanel>
<DropdownItem
role="menuitem"
isActive={mode === WALLPAPER_BANNER}
isLast={false}
onclick={() => switchWallpaperMode(WALLPAPER_BANNER)}
>
<Icon icon="material-symbols:image-outline" class="text-[1.25rem] mr-3"></Icon>
{i18n(I18nKey.wallpaperBannerMode)}
</DropdownItem>
<DropdownItem
role="menuitem"
isActive={mode === WALLPAPER_OVERLAY}
isLast={false}
onclick={() => switchWallpaperMode(WALLPAPER_OVERLAY)}
>
<Icon icon="material-symbols:wallpaper" class="text-[1.25rem] mr-3"></Icon>
{i18n(I18nKey.wallpaperOverlayMode)}
</DropdownItem>
<DropdownItem
role="menuitem"
isActive={mode === WALLPAPER_NONE}
isLast={true}
onclick={() => switchWallpaperMode(WALLPAPER_NONE)}
>
<Icon icon="material-symbols:hide-image-outline" class="text-[1.25rem] mr-3"></Icon>
{i18n(I18nKey.wallpaperNoneMode)}
</DropdownItem>
</DropdownPanel>
</div>
</div>
@@ -0,0 +1,227 @@
---
import { Icon } from "astro-icon/components";
import I18nKey from "@/i18n/i18nKey";
import { i18n } from "@/i18n/translation";
export interface Props {
playerUrl: string | string[];
playerMode?: "order" | "random";
}
const { playerUrl, playerMode = "order" } = Astro.props;
const urls = Array.isArray(playerUrl) ? playerUrl : [playerUrl];
const hasMultiple = urls.length > 1;
const urlsJson = JSON.stringify(urls);
const tPrev = i18n(I18nKey.videoPrev);
const tNext = i18n(I18nKey.videoNext);
const tLoadError = i18n(I18nKey.videoLoadError);
---
{
urls.length > 0 && (
<div id="bg-player">
<div
id="bg-player-overlay"
class="absolute inset-0 z-15 overflow-hidden pointer-events-none transition-opacity duration-500 ease-in-out opacity-0"
>
<video id="bg-player-video" preload="auto" playsinline class="size-full object-cover"></video>
</div>
<div id="bg-player-controls" class="absolute bottom-4 left-4 z-30 flex items-center gap-1.5 group">
{hasMultiple && (
<button
id="bg-prev-btn"
class="w-11 h-11 flex items-center justify-center rounded-full border border-white/30 bg-black/35 text-white/50 backdrop-blur-sm cursor-pointer transition-all duration-200 opacity-0 scale-90 group-hover:opacity-50 group-hover:scale-100 hover:opacity-80! hover:scale-100!"
title={tPrev}
aria-label={tPrev}
>
<Icon is:inline name="material-symbols:skip-previous-rounded" class="text-[1rem]" />
</button>
)}
{hasMultiple && (
<button
id="bg-next-btn"
class="w-11 h-11 flex items-center justify-center rounded-full border border-white/30 bg-black/35 text-white/50 backdrop-blur-sm cursor-pointer transition-all duration-200 opacity-0 scale-90 group-hover:opacity-50 group-hover:scale-100 hover:opacity-80! hover:scale-100!"
title={tNext}
aria-label={tNext}
>
<Icon is:inline name="material-symbols:skip-next-rounded" class="text-[1rem]" />
</button>
)}
</div>
<div
id="bg-player-toast"
class="fixed bottom-20 left-1/2 -translate-x-1/2 z-100 px-4 py-2 rounded-lg bg-black/70 text-white text-sm backdrop-blur-sm opacity-0 transition-opacity duration-300 pointer-events-none"
>
{tLoadError}
</div>
</div>
)
}
<script is:inline define:vars={{ urls: urlsJson, playerMode, hasMultiple }}>
(() => {
var urlList = JSON.parse(urls);
if (!urlList.length) return;
var isMultiple = urlList.length > 1;
var overlay = document.getElementById("bg-player-overlay");
var video = document.getElementById("bg-player-video");
var prevBtn = document.getElementById("bg-prev-btn");
var nextBtn = document.getElementById("bg-next-btn");
var toast = document.getElementById("bg-player-toast");
if (!video) return;
// 防止 is:inline 脚本重复注册监听器(Swup 导航会重新执行脚本)
if (video.getAttribute("data-player-init")) return;
video.setAttribute("data-player-init", "true");
var isPlaying = false;
var currentIndex = 0;
var errorCount = 0;
var toastTimer = null;
function showToast() {
if (!toast) return;
toast.classList.remove("opacity-0");
toast.classList.add("opacity-100");
if (toastTimer) clearTimeout(toastTimer);
toastTimer = setTimeout(function () {
toast.classList.remove("opacity-100");
toast.classList.add("opacity-0");
}, 3000);
}
function pickIndex(except) {
if (urlList.length <= 1) return 0;
if (playerMode === "random") {
var n;
do { n = Math.floor(Math.random() * urlList.length); } while (n === except);
return n;
}
return (except + 1) % urlList.length;
}
function prevIndex() {
if (urlList.length <= 1) return 0;
if (playerMode === "random") return pickIndex(currentIndex);
return (currentIndex - 1 + urlList.length) % urlList.length;
}
function syncAttr() {
document.body.toggleAttribute("data-bg-video-playing", isPlaying);
document.documentElement.toggleAttribute("data-bg-video-playing", isPlaying);
window.dispatchEvent(new CustomEvent("bg-player-state-change", { detail: { playing: isPlaying } }));
}
function doPlay() {
video.src = urlList[currentIndex];
video.muted = true;
video.play()
.then(function () { setTimeout(function () { if (video) video.muted = false; }, 100); })
.catch(function () { isPlaying = false; syncAttr(); });
}
function switchTrack(index) {
if (index < 0 || index >= urlList.length) return;
currentIndex = index;
if (isPlaying) {
doPlay();
} else {
video.src = urlList[currentIndex];
video.load();
}
}
function toggle() {
isPlaying = !isPlaying;
if (isPlaying) {
if (currentIndex >= urlList.length) currentIndex = 0;
syncAttr();
if (overlay) { overlay.classList.remove("opacity-0"); overlay.classList.add("opacity-100"); }
requestAnimationFrame(function () { doPlay(); });
} else {
video.pause();
if (overlay) { overlay.classList.remove("opacity-100"); overlay.classList.add("opacity-0"); }
syncAttr();
}
}
function onEnded() {
if (isMultiple) {
currentIndex = pickIndex(currentIndex);
doPlay();
} else {
isPlaying = false;
if (overlay) { overlay.classList.remove("opacity-100"); overlay.classList.add("opacity-0"); }
syncAttr();
}
}
function onError() {
errorCount++;
if (isMultiple && errorCount < urlList.length) {
// 多视频模式下自动尝试下一个
currentIndex = pickIndex(currentIndex);
video.src = urlList[currentIndex];
video.load();
} else {
// 所有视频都失败或只有单个视频
isPlaying = false;
if (overlay) { overlay.classList.remove("opacity-100"); overlay.classList.add("opacity-0"); }
syncAttr();
showToast();
}
}
// 监听导航栏播放按钮事件
window.addEventListener("bg-player-toggle", toggle);
video.addEventListener("ended", onEnded);
video.addEventListener("error", onError);
// 播放成功时重置错误计数
video.addEventListener("playing", function () { errorCount = 0; });
if (prevBtn) prevBtn.addEventListener("click", function () { switchTrack(prevIndex()); });
if (nextBtn) nextBtn.addEventListener("click", function () { switchTrack(pickIndex(currentIndex)); });
// 切换壁纸模式时停止播放
window.addEventListener("wallpaperModeChange", function (e) {
if (e.detail && e.detail.mode === "none" && isPlaying) {
isPlaying = false;
video.pause();
if (overlay) { overlay.classList.remove("opacity-100"); overlay.classList.add("opacity-0"); }
syncAttr();
}
});
// 动态控制 prev/next 按钮显示
if (!isMultiple) {
if (prevBtn) prevBtn.style.display = "none";
if (nextBtn) nextBtn.style.display = "none";
}
function cleanup() {
// 视频仍在播放时保留属性,供 Navbar 同步按钮状态
if (!isPlaying) {
document.body.removeAttribute("data-bg-video-playing");
document.documentElement.removeAttribute("data-bg-video-playing");
}
}
document.addEventListener("astro:before-swap", cleanup);
})();
</script>
<style>
:global([data-bg-video-playing] #banner-images-container),
:global([data-bg-video-playing] #banner-dim-container),
:global([data-bg-video-playing] #banner-overlay-container),
:global([data-bg-video-playing] #header-waves),
:global([data-bg-video-playing] #wallpaper-gradient) {
opacity: 0 !important;
transition: opacity 0.5s ease;
}
</style>
@@ -0,0 +1,205 @@
---
import I18nKey from "@i18n/i18nKey";
import { i18n } from "@i18n/translation";
import { encryptContent } from "@utils/crypto-utils";
import { Icon } from "astro-icon/components";
interface Props {
password: string;
slug: string;
hint?: string;
}
const { password, slug, hint = "" } = Astro.props;
const rawHtml = await Astro.slots.render("default");
const encryptedData = encryptContent(rawHtml, password, slug);
const labels = {
protected: i18n(I18nKey.passwordProtected),
desc: i18n(I18nKey.passwordProtectedDesc),
hint: i18n(I18nKey.passwordHint),
placeholder: i18n(I18nKey.passwordPlaceholder),
submit: i18n(I18nKey.passwordSubmit),
error: i18n(I18nKey.passwordError),
};
---
<div
id="encrypted-container"
data-encrypted={encryptedData}
data-slug={slug}
>
<!-- Lock UI -->
<div id="password-ui" class="flex justify-center py-16 px-4">
<div class="card-base flex flex-col items-center gap-3 max-w-100 w-full p-8">
<Icon is:inline name="material-symbols:shield-lock" class="text-8xl text-(--primary)" />
<h2 class="text-lg font-bold text-black/80 dark:text-white/80 m-0">{labels.protected}</h2>
<p class="text-sm text-black/40 dark:text-white/40 text-center m-0">{labels.desc}</p>
{hint && (
<p class="text-xs text-black/30 dark:text-white/30 text-center m-0">{labels.hint}: {hint}</p>
)}
<form id="password-form" class="w-full mt-2 space-y-2">
<input
id="password-input"
name="password"
type="password"
placeholder={labels.placeholder}
autocomplete="off"
class="w-full px-3 py-2 rounded-lg text-sm bg-black/5 dark:bg-white/10
border border-black/8 dark:border-white/8
text-black/80 dark:text-white/80 placeholder-black/25 dark:placeholder-white/25
outline-hidden focus:border-(--primary) transition"
/>
<button
type="submit"
class="w-full py-2 rounded-lg text-sm font-medium bg-(--primary) text-white dark:text-black/70
hover:opacity-85 active:scale-[0.98] transition-all"
>
{labels.submit}
</button>
</form>
<p id="password-error" class="text-xs text-red-500 dark:text-red-400 m-0 hidden">{labels.error}</p>
</div>
</div>
<!-- Decrypted content injected here -->
<div id="decrypted-content" class="hidden"></div>
</div>
<script is:inline>
(function() {
var ITERATIONS = 100000;
var SALT_LEN = 16;
var IV_LEN = 12;
var TAG_LEN = 16;
var container = document.getElementById('encrypted-container');
if (!container) return;
var encryptedData = container.getAttribute('data-encrypted');
var slug = container.getAttribute('data-slug');
var cacheKey = 'pw:' + slug;
var ui = document.getElementById('password-ui');
var form = document.getElementById('password-form');
var input = document.getElementById('password-input');
var errorEl = document.getElementById('password-error');
var contentEl = document.getElementById('decrypted-content');
function showContent(html) {
contentEl.innerHTML = html;
contentEl.classList.remove('hidden');
ui.classList.add('hidden');
// Scripts injected via innerHTML are inert — re-create them so they execute
var scripts = contentEl.querySelectorAll('script');
for (var i = 0; i < scripts.length; i++) {
var old = scripts[i];
var ns = document.createElement('script');
for (var j = 0; j < old.attributes.length; j++) {
ns.setAttribute(old.attributes[j].name, old.attributes[j].value);
}
ns.textContent = old.textContent;
old.parentNode.replaceChild(ns, old);
}
// Re-init components after content is in DOM
setTimeout(function() {
document.dispatchEvent(new CustomEvent('password:decrypted'));
}, 100);
// 初始化解密内容中图片的 LQIP 淡入
var placeholders = contentEl.querySelectorAll('.lqip-placeholder');
for (var i = 0; i < placeholders.length; i++) {
(function(placeholder) {
var container = placeholder.parentElement;
if (!container) return;
var img = container.querySelector('img');
if (!img) return;
if (img.complete && img.naturalWidth > 0) {
img.style.opacity = '1';
placeholder.classList.add('loaded');
} else {
img.addEventListener('load', function() {
img.style.opacity = '1';
placeholder.classList.add('loaded');
}, { once: true });
img.addEventListener('error', function() {
placeholder.classList.add('loaded');
}, { once: true });
}
})(placeholders[i]);
}
}
function showError() {
errorEl.classList.remove('hidden');
}
function hideError() {
errorEl.classList.add('hidden');
}
function base64ToBytes(b64) {
var bin = atob(b64);
var bytes = new Uint8Array(bin.length);
for (var i = 0; i < bin.length; i++) {
bytes[i] = bin.charCodeAt(i);
}
return bytes;
}
async function decrypt(pwd) {
var raw = base64ToBytes(encryptedData);
var salt = raw.slice(0, SALT_LEN);
var iv = raw.slice(SALT_LEN, SALT_LEN + IV_LEN);
var authTag = raw.slice(SALT_LEN + IV_LEN, SALT_LEN + IV_LEN + TAG_LEN);
var ciphertext = raw.slice(SALT_LEN + IV_LEN + TAG_LEN);
var combined = new Uint8Array(ciphertext.length + TAG_LEN);
combined.set(ciphertext);
combined.set(authTag, ciphertext.length);
var enc = new TextEncoder();
var keyMaterial = await crypto.subtle.importKey(
'raw', enc.encode(pwd), 'PBKDF2', false, ['deriveBits', 'deriveKey']
);
var key = await crypto.subtle.deriveKey(
{ name: 'PBKDF2', salt: salt, iterations: ITERATIONS, hash: 'SHA-256' },
keyMaterial,
{ name: 'AES-GCM', length: 256 },
false,
['decrypt']
);
var decrypted = await crypto.subtle.decrypt({ name: 'AES-GCM', iv: iv }, key, combined);
return new TextDecoder().decode(decrypted);
}
// Handle form submit
form.addEventListener('submit', function(e) {
e.preventDefault();
var pwd = input.value.trim();
if (!pwd) return;
hideError();
decrypt(pwd).then(function(html) {
sessionStorage.setItem(cacheKey, pwd);
showContent(html);
}).catch(function() {
showError();
});
});
// Try cached password
var cached = sessionStorage.getItem(cacheKey);
if (cached) {
decrypt(cached).then(function(html) {
showContent(html);
}).catch(function() {
sessionStorage.removeItem(cacheKey);
});
}
})();
</script>
@@ -0,0 +1,13 @@
---
import EncryptedContent from "./EncryptedContent.astro";
interface Props {
password: string;
slug: string;
hint?: string;
}
---
<EncryptedContent {...Astro.props}>
<slot />
</EncryptedContent>
@@ -0,0 +1,199 @@
---
import "@fancyapps/ui/dist/fancybox/fancybox.css";
import "@/styles/fancybox-custom.css";
// Fancybox 管理器组件
---
<script>
let Fancybox: any;
const IMG_SELECTOR = ".custom-md img, #post-cover img, .moment-images img";
const LINK_SELECTOR = ".moment-images a[data-fancybox], [data-fancybox]:not(.moment-images a)";
const svgBlobUrlCache = new Map<string, string>();
function isSvgSrc(src: string): boolean {
if (!src) return false;
try {
const url = new URL(src, location.href);
if (url.pathname.toLowerCase().endsWith(".svg")) return true;
if (url.searchParams.get("f")?.toLowerCase() === "svg") return true;
} catch { return false; }
return false;
}
function revokeAllSvgBlobUrls() {
for (const url of svgBlobUrlCache.values()) URL.revokeObjectURL(url);
svgBlobUrlCache.clear();
}
async function getSvgBlobUrl(src: string, fallbackW: number, fallbackH: number): Promise<string | null> {
const cached = svgBlobUrlCache.get(src);
if (cached) return cached;
try {
const resp = await fetch(src);
if (!resp.ok) { console.debug("[Fancybox] SVG fetch failed:", resp.status, src); return null; }
const svgText = await resp.text();
const parser = new DOMParser();
const doc = parser.parseFromString(svgText, "image/svg+xml");
if (doc.querySelector("parsererror")) { console.debug("[Fancybox] SVG parse error:", src); return null; }
const svgEl = doc.querySelector("svg");
if (!svgEl) { console.debug("[Fancybox] No <svg> element:", src); return null; }
if (!svgEl.getAttribute("width") || !svgEl.getAttribute("height")) {
const vb = svgEl.getAttribute("viewBox");
let w = String(fallbackW), h = String(fallbackH);
if (vb) {
const parts = vb.split(/[\s,]+/);
if (parts.length >= 4 && Number(parts[2]) > 0 && Number(parts[3]) > 0) {
w = parts[2]; h = parts[3];
}
}
if (!svgEl.getAttribute("width")) svgEl.setAttribute("width", w);
if (!svgEl.getAttribute("height")) svgEl.setAttribute("height", h);
}
const blob = new Blob([new XMLSerializer().serializeToString(svgEl)], { type: "image/svg+xml" });
const blobUrl = URL.createObjectURL(blob);
svgBlobUrlCache.set(src, blobUrl);
return blobUrl;
} catch (err) { console.debug("[Fancybox] SVG preprocess error:", src, err); return null; }
}
function getCommonOptions() {
return {
Thumbs: {
autoStart: true,
showOnStart: "yes",
},
Toolbar: {
display: {
left: ["infobar"],
middle: [
"zoomIn",
"zoomOut",
"toggle1to1",
"rotateCCW",
"rotateCW",
"flipX",
"flipY",
],
right: ["slideshow", "thumbs", "close"],
},
},
animated: true,
dragToClose: true,
keyboard: {
Escape: "close",
Delete: "close",
Backspace: "close",
PageUp: "next",
PageDown: "prev",
ArrowUp: "next",
ArrowDown: "prev",
ArrowRight: "next",
ArrowLeft: "prev",
},
fitToView: true,
preload: 3,
infinite: true,
Panzoom: {
maxScale: 3,
minScale: 1,
},
caption: false,
};
}
async function preprocessSvgImages() {
const promises: Promise<void>[] = [];
document.querySelectorAll<HTMLImageElement>(IMG_SELECTOR).forEach((img) => {
if (img.dataset.svgFixed) return;
const src = img.getAttribute("src") || "";
if (!isSvgSrc(src)) return;
const fallbackW = img.naturalWidth || img.clientWidth || 1600;
const fallbackH = img.naturalHeight || img.clientHeight || 900;
promises.push(
getSvgBlobUrl(src, fallbackW, fallbackH).then((blobUrl) => {
if (blobUrl) {
img.dataset.originalSrc = src;
img.src = blobUrl;
img.dataset.svgFixed = "true";
}
})
);
});
document.querySelectorAll<HTMLElement>(LINK_SELECTOR).forEach((el) => {
if (el.dataset.svgFixed) return;
const attr = el.hasAttribute("data-src") ? "data-src" : "href";
const svgSrc = el.getAttribute(attr) || "";
if (!isSvgSrc(svgSrc)) return;
promises.push(
getSvgBlobUrl(svgSrc, 1600, 900).then((blobUrl) => {
if (blobUrl) {
el.dataset.originalSrc = svgSrc;
el.setAttribute(attr, blobUrl);
el.dataset.svgFixed = "true";
}
})
);
});
await Promise.allSettled(promises);
}
async function setup() {
if (!document.querySelector(IMG_SELECTOR) && !document.querySelector(LINK_SELECTOR)) return;
if (!Fancybox) {
const mod = await import("@fancyapps/ui");
Fancybox = mod.Fancybox;
}
const commonOptions = getCommonOptions();
await preprocessSvgImages();
Fancybox.bind(IMG_SELECTOR, {
...commonOptions,
groupAll: true,
Carousel: {
transition: "slide",
preload: 2,
},
});
Fancybox.bind(LINK_SELECTOR, {
...commonOptions,
source: (el: any) => el.getAttribute("data-src") || el.getAttribute("href"),
});
}
function cleanupFancybox() {
if (Fancybox) {
Fancybox.close();
Fancybox.unbind(document.body);
}
// 恢复原始 URL 并清除标记,避免 blob URL 被 revoke 后图片损坏
document.querySelectorAll<HTMLElement>("[data-svg-fixed]").forEach((el) => {
const original = el.dataset.originalSrc;
if (!original) return;
if (el instanceof HTMLImageElement) el.src = original;
else if (el.hasAttribute("data-src")) el.setAttribute("data-src", original);
else if (el.hasAttribute("href")) el.setAttribute("href", original);
delete el.dataset.svgFixed;
delete el.dataset.originalSrc;
});
revokeAllSvgBlobUrls();
}
// 初始化
setup();
// Swup 生命周期整合
document.addEventListener("swup:content:replace", setup);
document.addEventListener("swup:visit:start", cleanupFancybox);
// 加密文章解密后重新绑定灯箱
document.addEventListener("password:decrypted", () => {
setTimeout(setup, 200);
});
</script>
+90
View File
@@ -0,0 +1,90 @@
---
/**
* FontSetup.astro
*
* 使用 Astro Font API(<Font /> 组件)统一管理字体加载。
* 字体定义在 fontConfig.ts 的 fonts 数组中配置,
* 本组件负责渲染 <Font /> 标签并设置 body 字体和区域覆盖 CSS 变量。
*
* 字体的 fallback 由各字体定义中的 fallbacks 字段控制(Astro Font API 处理),
*/
import { Font } from "astro:assets";
import { fontConfig } from "@/config";
import { collectUsedFontCssVars } from "@/utils/fontHelper";
// 使用共享的工具函数收集所有需要加载的 CSS 变量名(selected + 各区域字体,去重)
// enable=false 时返回空集,不会加载任何字体
const allCssVars = fontConfig.enable
? collectUsedFontCssVars(fontConfig)
: new Set<string>();
// 统一解析 selected 为数组(用于后续 body font-family 和 preload 判断)
const selectedIds: string[] =
fontConfig.enable && fontConfig.selected
? Array.isArray(fontConfig.selected)
? fontConfig.selected
: [fontConfig.selected]
: [];
// 生成 body 的 font-family 值
// 每个字体的 fallback 由其在 fonts 中的 fallbacks 字段控制
// 这里只拼接 CSS 变量引用,末尾加系统字体作为最终保底
const SYSTEM_FONT_STACK =
"system-ui, -apple-system, BlinkMacSystemFont, Segoe UI, Roboto, sans-serif";
const selectedFontVars = selectedIds.filter((v) => v !== "system");
const bodyFontFamily =
selectedFontVars.length > 0
? [...selectedFontVars.map((v) => `var(${v})`), SYSTEM_FONT_STACK].join(
", ",
)
: SYSTEM_FONT_STACK;
// 各区域字体 CSS 变量值
const bannerTitleFontVar = fontConfig.enable
? fontConfig.bannerTitleFont || ""
: "";
const bannerSubtitleFontVar = fontConfig.enable
? fontConfig.bannerSubtitleFont || ""
: "";
const navbarTitleFontVar = fontConfig.enable
? fontConfig.navbarTitleFont || ""
: "";
---
<!-- Astro Font API: 自动下载、缓存并生成优化的 @font-face -->
{Array.from(allCssVars).map((cssVar) => (
<Font
cssVariable={cssVar as any}
preload={selectedFontVars.includes(cssVar)}
/>
))}
<!-- 区域字体 CSS 变量 + body 字体 -->
{fontConfig.enable && (bannerTitleFontVar || bannerSubtitleFontVar || navbarTitleFontVar || selectedFontVars.length > 0) && (
<style
set:html={`
${bannerTitleFontVar || bannerSubtitleFontVar || navbarTitleFontVar ? `:root {
${bannerTitleFontVar ? `--font-banner-title: var(${bannerTitleFontVar}, inherit);` : ""}
${bannerSubtitleFontVar ? `--font-banner-subtitle: var(${bannerSubtitleFontVar}, inherit);` : ""}
${navbarTitleFontVar ? `--font-navbar-title: var(${navbarTitleFontVar}, inherit);` : ""}
}` : ""}
body {
font-family: ${bodyFontFamily};
}
`}
/>
)}
<script>
// 字体加载完成事件
if (document.fonts && typeof document.fonts.ready !== "undefined") {
document.fonts.ready
.then(() => {
document.dispatchEvent(new CustomEvent("fontsLoaded"));
})
.catch((error) => {
console.warn("Font loading failed:", error);
});
}
</script>
@@ -0,0 +1,4 @@
---
// KaTeX CSS - 直接在文章页加载
import "katex/dist/katex.min.css";
---
+258
View File
@@ -0,0 +1,258 @@
---
import { url } from "@/utils/url-utils";
interface MenuItem {
icon?: string;
label: string;
action: string;
}
interface Props {
config: {
enable: boolean;
model:
| {
path: string;
volume?: number;
scale?: number;
x?: number;
y?: number;
}
| {
path: string;
volume?: number;
scale?: number;
x?: number;
y?: number;
}[];
position?: "bottom-left" | "bottom-right";
size?: number | { width: number; height: number };
primaryColor?: string;
transitionDuration?: number;
transitionType?: "slide" | "fade";
menus?: {
items?: MenuItem[];
extraItems?: MenuItem[];
align?: "left" | "right";
};
tips?: {
enable?: boolean;
welcomeMessage?: string[];
messages?: string[];
duration?: number;
interval?: number;
offset?: { x?: number; y?: number };
typing?: {
param?: string;
speed?: number;
minValue?: number;
maxValue?: number;
};
};
responsive?: {
hideOnMobile?: boolean;
mobileBreakpoint?: number;
};
};
}
const { config } = Astro.props;
// 构建模型配置
const models = Array.isArray(config.model) ? config.model : [config.model];
const resolvePath = (p: string) => (/^https?:\/\//.test(p) ? p : url(p));
const modelConfigs = models.map((m) => ({
path: resolvePath(m.path),
...(m.volume !== undefined && { volume: m.volume }),
...(m.scale !== undefined && { scale: m.scale }),
...((m.x !== undefined || m.y !== undefined) && {
offset: [m.x ?? 0, m.y ?? 0],
}),
}));
// 序列化菜单配置(只保留 icon, label, action)
function serializeMenus(menus: Props["config"]["menus"]) {
if (!menus) return {};
const serialize = (items: MenuItem[]) =>
items.map(({ icon, label, action }) => ({ icon, label, action }));
const result: {
items?: ReturnType<typeof serialize>;
extraItems?: ReturnType<typeof serialize>;
align?: string;
} = {};
if (menus.items) result.items = serialize(menus.items);
if (menus.extraItems) result.extraItems = serialize(menus.extraItems);
if (menus.align) result.align = menus.align;
return result;
}
---
<div
id="l2d-widget-container"
style="position: fixed; z-index: 999;"
data-models={JSON.stringify(modelConfigs)}
data-position={config.position || "bottom-left"}
data-size={JSON.stringify(config.size || 300)}
data-primary-color={config.primaryColor || ""}
data-transition-duration={config.transitionDuration?.toString() || ""}
data-transition-type={config.transitionType || ""}
data-menus={JSON.stringify(serializeMenus(config.menus))}
data-tips={JSON.stringify(config.tips || {})}
data-responsive={JSON.stringify(config.responsive || {})}
>
</div>
<script>
import { createWidget } from "l2d-widget";
// 修复 l2d-widget 气泡 不会自动换行
// l2d-widget 使用行内样式,CSS 无法覆盖,需用 JS 修改
function patchTipBubble(el: HTMLElement) {
if (el.style.whiteSpace === "nowrap") {
el.style.whiteSpace = "normal";
el.style.width = "190px";
}
}
const tipObserver = new MutationObserver((mutations) => {
for (const m of mutations) {
for (const node of m.addedNodes) {
if (node instanceof HTMLElement) {
if (node.style.whiteSpace === "nowrap") patchTipBubble(node);
node.querySelectorAll<HTMLElement>('*').forEach(patchTipBubble);
}
}
}
});
tipObserver.observe(document.body, { childList: true, subtree: true });
// 菜单动作映射
let currentModelIndex = 0;
const menuActions: Record<string, (widget: any) => void> = {
home: () => (window.location.href = "/"),
scrollToTop: () => window.scrollTo({ top: 0, behavior: "smooth" }),
sleep: (widget) => widget.sleep(),
github: () => window.open("https://github.com/CuteLeaf/Firefly", "_blank"),
switchModel: (widget) => {
const container = document.getElementById("l2d-widget-container");
const models = JSON.parse(container?.dataset.models || "[]");
currentModelIndex = (currentModelIndex + 1) % models.length;
widget.switchModel(currentModelIndex);
},
};
function initWidget() {
const container = document.getElementById("l2d-widget-container");
if (!container) return;
try {
const models = JSON.parse(container.dataset.models || "[]");
const position = container.dataset.position || "bottom-left";
const size = JSON.parse(container.dataset.size || "300");
const primaryColor = container.dataset.primaryColor || undefined;
const transitionDuration = container.dataset.transitionDuration
? parseInt(container.dataset.transitionDuration)
: undefined;
const transitionType = container.dataset.transitionType || undefined;
const menus = JSON.parse(container.dataset.menus || "{}");
const tips = JSON.parse(container.dataset.tips || "{}");
const responsive = JSON.parse(container.dataset.responsive || "{}");
// 响应式检查:移动端隐藏
if (responsive.hideOnMobile) {
const breakpoint = responsive.mobileBreakpoint || 768;
if (window.innerWidth <= breakpoint) {
container.style.display = "none";
return;
}
}
if (models.length === 0) {
console.warn("No Live2D models configured");
return;
}
const options: any = {
model: models.length === 1 ? models[0] : models,
position: position,
size: size,
};
if (primaryColor) options.primaryColor = primaryColor;
if (transitionDuration) options.transitionDuration = transitionDuration;
if (transitionType) options.transitionType = transitionType;
// 菜单配置 - 将 action 字符串映射为实际函数
if (menus.items || (menus.extraItems && menus.extraItems.length > 0)) {
options.menus = {};
if (menus.items) {
options.menus.items = menus.items.map((item: any) => ({
icon: item.icon,
label: item.label,
onClick: menuActions[item.action] || (() => {}),
}));
}
if (menus.extraItems) {
options.menus.extraItems = menus.extraItems.map((item: any) => ({
icon: item.icon,
label: item.label,
onClick: menuActions[item.action] || (() => {}),
}));
}
if (menus.align) {
options.menus.align = menus.align;
}
}
// 提示配置
if (tips) {
const tipsConfig = tips.enable === false ? false : {
...(tips.welcomeMessage && { welcomeMessage: tips.welcomeMessage }),
...(tips.messages && { messages: tips.messages }),
...(tips.duration !== undefined && { duration: tips.duration }),
...(tips.interval !== undefined && { interval: tips.interval }),
...(tips.offset && { offset: tips.offset }),
...(tips.typing && { typing: tips.typing }),
};
if (tipsConfig === false || Object.keys(tipsConfig).length > 0) {
if (Array.isArray(options.model)) {
options.model.forEach((m: any) => m.tips = tipsConfig);
} else {
options.model.tips = tipsConfig;
}
}
}
createWidget(options);
} catch (e) {
console.error("Failed to initialize Live2D widget:", e);
}
}
// 确保只初始化一次
if (document.readyState === "loading") {
document.addEventListener("DOMContentLoaded", initWidget);
} else {
initWidget();
}
// 响应式处理:窗口大小变化时显示/隐藏
function handleResponsive() {
const container = document.getElementById("l2d-widget-container");
if (!container) return;
const responsive = JSON.parse(container.dataset.responsive || "{}");
if (responsive.hideOnMobile) {
const breakpoint = responsive.mobileBreakpoint || 768;
if (window.innerWidth <= breakpoint) {
container.style.display = "none";
} else {
container.style.display = "";
}
}
}
window.addEventListener("resize", handleResponsive);
</script>
+445
View File
@@ -0,0 +1,445 @@
---
import { musicPlayerConfig } from "@/config/musicConfig";
import I18nKey from "@/i18n/i18nKey";
import { i18n } from "@/i18n/translation";
import { url } from "@/utils/url-utils";
const config = musicPlayerConfig;
const localPlaylist =
config.mode === "local" && config.local?.playlist
? config.local.playlist.map((song) => {
const isFullUrl = (path: string) => /^https?:\/\//.test(path);
return {
name: song.name,
artist: song.artist,
url: isFullUrl(song.url) ? song.url : url(song.url),
pic: song.cover
? isFullUrl(song.cover)
? song.cover
: url(song.cover)
: undefined,
lrc: song.lrc
? isFullUrl(song.lrc)
? song.lrc
: url(song.lrc)
: undefined,
};
})
: [];
const managerConfigStr = JSON.stringify({
mode: config.mode,
meting: config.meting,
localPlaylist: localPlaylist,
volume: config.volume ?? 0.7,
playMode: config.playMode ?? "list",
showLyrics: config.showLyrics ?? true,
i18n: {
noPlaying: i18n(I18nKey.musicNoPlaying),
lyrics: i18n(I18nKey.musicLyrics),
volume: i18n(I18nKey.musicVolume),
playMode: i18n(I18nKey.musicPlayMode),
prev: i18n(I18nKey.musicPrev),
next: i18n(I18nKey.musicNext),
playlist: i18n(I18nKey.musicPlaylist),
noLyrics: i18n(I18nKey.musicNoLyrics),
loadingLyrics: i18n(I18nKey.musicLoadingLyrics),
failedLyrics: i18n(I18nKey.musicFailedLyrics),
noSongs: i18n(I18nKey.musicNoSongs),
error: i18n(I18nKey.musicError),
play: i18n(I18nKey.musicPlay),
pause: i18n(I18nKey.musicPause),
progress: i18n(I18nKey.musicProgress),
noCover: i18n(I18nKey.musicNoCover),
},
});
---
<script is:inline data-swup-ignore-script define:vars={{ managerConfigStr }}>
(function () {
// Singleton guard – only create once
if (window.__fireflyMusic) return;
var config = JSON.parse(managerConfigStr);
// ── Helpers ──────────────────────────────────────────────
function formatTime(seconds) {
if (!seconds || isNaN(seconds)) return '0:00';
var min = Math.floor(seconds / 60);
var sec = Math.floor(seconds % 60);
return min + ':' + (sec < 10 ? '0' : '') + sec;
}
function parseLRC(lrc) {
if (!lrc) return [];
var lines = lrc.split('\n');
var result = [];
var timeReg = /\[(\d{2}):(\d{2})\.(\d{2,3})\]/g;
lines.forEach(function (line) {
var matches = Array.from(line.matchAll(timeReg));
if (matches.length > 0) {
var text = line.replace(timeReg, '').trim();
if (text) {
matches.forEach(function (match) {
var m = parseInt(match[1]);
var s = parseInt(match[2]);
var ms = parseInt(match[3]);
var time = m * 60 + s + ms / (match[3].length === 3 ? 1000 : 100);
result.push({ time: time, text: text });
});
}
}
});
return result.sort(function (a, b) { return a.time - b.time; });
}
// ── Audio element (persistent, attached to body) ────────
var audio = document.createElement('audio');
audio.crossOrigin = 'anonymous';
audio.style.display = 'none';
document.body.appendChild(audio);
// ── State ────────────────────────────────────────────────
var loadVersion = 0; // incremented on each loadTrack to discard stale play() results
var state = {
playlist: [],
currentIndex: 0,
isPlaying: false,
playMode: 0, // 0: list, 1: one, 2: random
volume: localStorage.getItem('music-player-volume') !== null
? parseFloat(localStorage.getItem('music-player-volume'))
: (config.volume || 0.7),
isMuted: false,
lyrics: [],
currentLrcIndex: -1,
initialized: false,
initializing: false,
error: null
};
// Map config playMode string to number
if (config.playMode === 'random') state.playMode = 2;
else if (config.playMode === 'one') state.playMode = 1;
else state.playMode = 0;
// ── Event helpers ────────────────────────────────────────
function emit(name, detail) {
window.dispatchEvent(new CustomEvent(name, { detail: detail || {} }));
}
// ── Meting fetch ─────────────────────────────────────────
async function fetchMetingData() {
if (!config.meting) return;
var m = config.meting;
var apis = [m.api].concat(m.fallbackApis || []);
for (var i = 0; i < apis.length; i++) {
var baseApi = apis[i];
if (!baseApi) continue;
try {
var fetchUrl = baseApi
.replace(':server', m.server)
.replace(':type', m.type)
.replace(':id', m.id)
.replace(':r', Math.random());
if (m.auth) fetchUrl += '&auth=' + m.auth;
var res = await fetch(fetchUrl);
if (!res.ok) throw new Error('HTTP ' + res.status);
var data = await res.json();
if (Array.isArray(data) && data.length > 0) {
state.playlist = data.map(function (item) {
return {
name: item.title || item.name || 'Unknown',
artist: item.author || item.artist || 'Unknown',
url: item.url,
pic: item.pic || item.cover || '',
lrc: item.lrc
};
});
return;
}
} catch (e) {
console.warn('Meting API failed for ' + baseApi, e);
}
}
throw new Error('All Meting APIs failed');
}
// ── Lyrics ───────────────────────────────────────────────
function loadLyrics(track) {
state.lyrics = [];
state.currentLrcIndex = -1;
if (!track.lrc) {
emit('fm:lyrics', { lyrics: [], status: 'none' });
return;
}
var isLrcUrl = /^(https?:)?\/\//.test(track.lrc)
|| track.lrc.startsWith('/')
|| /\.(lrc|txt)(\?|#|$)/i.test(track.lrc);
if (isLrcUrl) {
emit('fm:lyrics', { lyrics: [], status: 'loading' });
fetch(track.lrc)
.then(function (r) { return r.text(); })
.then(function (text) {
state.lyrics = parseLRC(text);
emit('fm:lyrics', { lyrics: state.lyrics, status: 'loaded' });
})
.catch(function () {
state.lyrics = [];
emit('fm:lyrics', { lyrics: [], status: 'failed' });
});
} else {
state.lyrics = parseLRC(track.lrc);
emit('fm:lyrics', { lyrics: state.lyrics, status: state.lyrics.length > 0 ? 'loaded' : 'none' });
}
}
// ── Track loading ────────────────────────────────────────
function loadTrack(index, autoPlay) {
if (index < 0 || index >= state.playlist.length) return;
state.currentIndex = index;
var track = state.playlist[index];
var ver = ++loadVersion;
audio.src = track.url;
loadLyrics(track);
emit('fm:track', { index: index, track: track, autoPlay: !!autoPlay });
if (autoPlay) {
audio.play().then(function () {
if (ver !== loadVersion) return; // stale, discard
state.isPlaying = true;
emit('fm:play-state', { isPlaying: true });
}).catch(function (e) {
if (ver !== loadVersion) return; // stale, discard
if (e.name === 'AbortError') return; // interrupted by new load
console.warn('Autoplay blocked:', e);
});
} else {
state.isPlaying = false;
emit('fm:play-state', { isPlaying: false });
}
}
// ── Playback controls ────────────────────────────────────
function togglePlay() {
if (audio.paused) {
audio.play().then(function () {
state.isPlaying = true;
emit('fm:play-state', { isPlaying: true });
});
} else {
audio.pause();
state.isPlaying = false;
emit('fm:play-state', { isPlaying: false });
}
}
function playNext(auto) {
if (state.playMode === 1 && auto) {
audio.currentTime = 0;
audio.play();
return;
}
var nextIndex;
if (state.playMode === 2) {
nextIndex = Math.floor(Math.random() * state.playlist.length);
} else {
nextIndex = (state.currentIndex + 1) % state.playlist.length;
}
loadTrack(nextIndex, true);
}
function playPrev() {
var prevIndex;
if (state.playMode === 2) {
prevIndex = Math.floor(Math.random() * state.playlist.length);
} else {
prevIndex = (state.currentIndex - 1 + state.playlist.length) % state.playlist.length;
}
loadTrack(prevIndex, true);
}
function setPlayMode(mode) {
state.playMode = mode;
emit('fm:mode', { playMode: mode });
}
function cyclePlayMode() {
setPlayMode((state.playMode + 1) % 3);
}
function setVolume(val) {
val = Math.max(0, Math.min(1, val));
state.volume = val;
state.isMuted = false;
audio.volume = val;
audio.muted = false;
localStorage.setItem('music-player-volume', val.toString());
emit('fm:volume', { volume: val, isMuted: false });
}
function toggleMute() {
state.isMuted = !state.isMuted;
audio.muted = state.isMuted;
emit('fm:volume', { volume: state.volume, isMuted: state.isMuted });
}
function seek(percent) {
if (!audio.duration) return;
audio.currentTime = Math.max(0, Math.min(1, percent)) * audio.duration;
}
function seekToTime(time) {
if (!audio.duration) return;
audio.currentTime = Math.max(0, Math.min(time, audio.duration));
}
function playTrackByIndex(index) {
if (index === state.currentIndex && !audio.paused) {
togglePlay();
} else {
loadTrack(index, true);
}
}
// ── Audio events → broadcast ─────────────────────────────
audio.addEventListener('timeupdate', function () {
if (isNaN(audio.duration)) return;
var ct = audio.currentTime;
var dur = audio.duration;
var pct = (ct / dur) * 100;
emit('fm:time', {
currentTime: ct,
duration: dur,
progress: pct,
currentTimeStr: formatTime(ct),
durationStr: formatTime(dur)
});
// Lyrics sync
if (state.lyrics.length > 0) {
var idx = -1;
for (var i = 0; i < state.lyrics.length; i++) {
if (ct >= state.lyrics[i].time) idx = i;
else break;
}
if (idx !== state.currentLrcIndex) {
state.currentLrcIndex = idx;
emit('fm:lrc-index', { index: idx });
}
}
});
audio.addEventListener('ended', function () {
playNext(true);
});
audio.addEventListener('error', function () {
state.error = 'Audio playback error';
emit('fm:error', { message: state.error });
});
// ── Init (idempotent) ────────────────────────────────────
async function init() {
if (state.initialized || state.initializing) return;
state.initializing = true;
try {
if (config.mode === 'meting' && config.meting) {
await fetchMetingData();
} else if (config.mode === 'local') {
state.playlist = config.localPlaylist || [];
}
if (state.playlist.length > 0) {
// Apply volume
audio.volume = state.volume;
var startIndex = 0;
if (state.playMode === 2) {
startIndex = Math.floor(Math.random() * state.playlist.length);
}
state.initialized = true;
emit('fm:init', {
playlist: state.playlist,
playMode: state.playMode,
volume: state.volume,
isMuted: state.isMuted
});
loadTrack(startIndex, false);
} else {
state.initialized = true;
emit('fm:init', {
playlist: [],
playMode: state.playMode,
volume: state.volume,
isMuted: state.isMuted
});
emit('fm:error', { message: config.i18n.noSongs });
}
} catch (e) {
console.error('Music Manager init error:', e);
state.initialized = true;
emit('fm:init', {
playlist: [],
playMode: state.playMode,
volume: state.volume,
isMuted: state.isMuted
});
emit('fm:error', { message: config.i18n.error });
} finally {
state.initializing = false;
}
}
// ── Public API ───────────────────────────────────────────
window.__fireflyMusic = {
init: init,
getState: function () {
var track = state.playlist[state.currentIndex] || null;
return {
playlist: state.playlist,
currentIndex: state.currentIndex,
track: track,
isPlaying: state.isPlaying,
playMode: state.playMode,
volume: state.volume,
isMuted: state.isMuted,
currentTime: audio.currentTime,
duration: audio.duration || 0,
progress: audio.duration ? (audio.currentTime / audio.duration) * 100 : 0,
currentTimeStr: formatTime(audio.currentTime),
durationStr: formatTime(audio.duration),
lyrics: state.lyrics,
currentLrcIndex: state.currentLrcIndex,
initialized: state.initialized,
error: state.error,
config: config
};
},
togglePlay: togglePlay,
playNext: function () { playNext(false); },
playPrev: playPrev,
cyclePlayMode: cyclePlayMode,
setVolume: setVolume,
toggleMute: toggleMute,
seek: seek,
seekToTime: seekToTime,
playTrackByIndex: playTrackByIndex,
loadTrack: loadTrack
};
})();
</script>
+872
View File
@@ -0,0 +1,872 @@
---
import { Icon } from "astro-icon/components";
import { musicPlayerConfig } from "@/config/musicConfig";
import I18nKey from "@/i18n/i18nKey";
import { i18n } from "@/i18n/translation";
interface Props {
class?: string;
style?: string;
id?: string;
}
const { class: className, style, id } = Astro.props;
const config = musicPlayerConfig;
const viewConfigStr = JSON.stringify({
showLyrics: config.showLyrics ?? true,
i18n: {
noPlaying: i18n(I18nKey.musicNoPlaying),
lyrics: i18n(I18nKey.musicLyrics),
noLyrics: i18n(I18nKey.musicNoLyrics),
loadingLyrics: i18n(I18nKey.musicLoadingLyrics),
failedLyrics: i18n(I18nKey.musicFailedLyrics),
noSongs: i18n(I18nKey.musicNoSongs),
error: i18n(I18nKey.musicError),
play: i18n(I18nKey.musicPlay),
pause: i18n(I18nKey.musicPause),
noCover: i18n(I18nKey.musicNoCover),
music: i18n(I18nKey.music),
},
});
const widgetId =
id || `music-widget-${Math.random().toString(36).substring(2, 9)}`;
---
<div id={widgetId} class:list={["music-player-widget w-full relative transition-all duration-300", className]} style={style} role="region" aria-label={i18n(I18nKey.music)}>
<!-- Top Row: Cover & Info -->
<div class="flex items-center gap-2 mb-2 px-1">
<!-- Circular Cover -->
<div class="relative shrink-0 w-14 h-14 group">
<div class="w-full h-full rounded-full overflow-hidden shadow-lg border-2 border-white dark:border-neutral-700 relative z-10 bg-(--primary)/10 flex items-center justify-center">
<Icon is:inline name="material-symbols:music-note-rounded" class="text-2xl text-(--primary) opacity-40 absolute" aria-hidden="true" />
<img class="music-cover w-full h-full object-cover animate-spin-slow relative z-10 opacity-0 transition-opacity duration-300" src="" alt={i18n(I18nKey.musicCover)} style="animation-play-state: paused;" />
</div>
</div>
<!-- Info Section -->
<div class="flex-1 min-w-0 flex flex-col overflow-hidden">
<div class="flex items-center justify-between overflow-hidden gap-2">
<div class="flex-1 min-w-0 overflow-hidden relative">
<h3 class="music-title font-bold text-base text-neutral-800 dark:text-neutral-100 leading-tight truncate">
{i18n(I18nKey.music)}
</h3>
</div>
<!-- Top Right: Lyric Toggle -->
<button class={`btn-lrc-toggle hover:text-(--primary) transition-all duration-300 p-0.5 pr-2 transform active:scale-95 text-neutral-400 shrink-0 ${!config.showLyrics ? 'hidden' : ''}`} title={i18n(I18nKey.musicLyrics)} aria-label={i18n(I18nKey.musicLyrics)}>
<Icon is:inline name="material-symbols:subtitles-off-outline-rounded" class="icon-lrc-off text-xl" aria-hidden="true" />
<Icon is:inline name="material-symbols:subtitles-outline-rounded" class="icon-lrc-on text-xl hidden" aria-hidden="true" />
</button>
</div>
<div class="min-w-0 overflow-hidden">
<p class="music-artist text-xs font-medium text-neutral-500 dark:text-neutral-400 truncate">
{i18n(I18nKey.musicNoPlaying)}
</p>
</div>
<!-- Time Display & Volume -->
<div class="flex items-center gap-3 text-neutral-400 h-5">
<div class="text-[10px] font-mono flex items-center gap-1 shrink-0 h-full" aria-live="polite">
<span class="current-time">0:00</span>
<span class="opacity-50" aria-hidden="true">/</span>
<span class="total-time">0:00</span>
</div>
<!-- Volume (Always visible) -->
<div class="flex items-center gap-1 bg-transparent h-full ml-auto">
<button class="btn-mute hover:text-(--primary) transition-colors p-0.5 rounded-md flex items-center" title={i18n(I18nKey.musicVolume)} aria-label={i18n(I18nKey.musicVolume)}>
<Icon is:inline name="material-symbols:volume-up-rounded" class=" icon-vol-high text-lg" aria-hidden="true" />
<Icon is:inline name="material-symbols:volume-off-rounded" class="icon-vol-mute text-lg hidden" aria-hidden="true" />
</button>
<div class="w-16 transition-all duration-300 ease-out flex items-center">
<div class="vol-container h-1 w-16 bg-neutral-300/50 dark:bg-neutral-500/40 rounded-full cursor-pointer relative ml-1" role="slider" aria-label={i18n(I18nKey.musicVolume)} aria-valuemin="0" aria-valuemax="100" aria-valuenow="70">
<div class="vol-bar absolute left-0 top-0 h-full bg-(--primary) rounded-full w-[70%]"></div>
</div>
</div>
</div>
</div>
</div>
</div>
<!-- Progress Bar (Slim) -->
<div class="px-1">
<div class="progress-container relative w-full h-1 bg-neutral-300/60 dark:bg-neutral-500/40 rounded-full cursor-pointer touch-none mb-2 group mt-2" role="slider" aria-label={i18n(I18nKey.musicProgress)} aria-valuemin="0" aria-valuemax="100" aria-valuenow="0">
<div class="progress-bar absolute left-0 top-0 h-full bg-(--primary) rounded-full w-0 transition-[width] duration-100"></div>
<!-- Hover Thumb -->
<div class="progress-thumb absolute top-1/2 -mt-1.5 -ml-1.5 w-3 h-3 bg-(--primary) ring-2 ring-white dark:ring-neutral-800 rounded-full shadow-sm scale-0 group-hover:scale-100 transition-transform duration-200"></div>
</div>
</div>
<!-- Controls Row -->
<div class="flex items-center justify-between px-1 select-none">
<!-- Repeat Mode -->
<button class="btn-repeat text-neutral-300 dark:text-neutral-600 hover:text-(--primary) transition-colors p-2 active:scale-95" title={i18n(I18nKey.musicPlayMode)} aria-label={i18n(I18nKey.musicPlayMode)}>
<Icon is:inline name="material-symbols:repeat-rounded" class="icon-repeat text-xl" aria-hidden="true" />
<Icon is:inline name="material-symbols:repeat-one-rounded" class="icon-repeat-one text-xl hidden" aria-hidden="true" />
<Icon is:inline name="material-symbols:shuffle-rounded" class="icon-shuffle text-xl hidden" aria-hidden="true" />
</button>
<!-- Prev -->
<button class="btn-prev text-neutral-600 dark:text-neutral-300 hover:text-(--primary) transition-colors p-2 active:scale-95" title={i18n(I18nKey.musicPrev)} aria-label={i18n(I18nKey.musicPrev)}>
<Icon is:inline name="material-symbols:skip-previous-rounded" class="text-3xl" aria-hidden="true" />
</button>
<!-- Play/Pause (Feature) -->
<button class="btn-play w-12 h-12 bg-(--btn-regular-bg) hover:bg-(--btn-regular-bg-hover) active:bg-(--btn-regular-bg-active) text-(--primary) rounded-full flex items-center justify-center transition-all duration-300" title={i18n(I18nKey.musicPlay)} aria-label={i18n(I18nKey.musicPlay)}>
<Icon is:inline name="material-symbols:play-arrow-rounded" class="icon-play text-3xl ml-0.5" aria-hidden="true" />
<Icon is:inline name="material-symbols:pause-rounded" class="icon-pause text-3xl hidden" aria-hidden="true" />
</button>
<!-- Next -->
<button class="btn-next text-neutral-600 dark:text-neutral-300 hover:text-(--primary) transition-colors p-2 active:scale-95" title={i18n(I18nKey.musicNext)} aria-label={i18n(I18nKey.musicNext)}>
<Icon is:inline name="material-symbols:skip-next-rounded" class="text-3xl" aria-hidden="true" />
</button>
<!-- Playlist Toggle Arrow -->
<button class="btn-drawer-toggle text-neutral-400 hover:text-(--primary) transition-all duration-300 p-2 transform active:scale-95" title={i18n(I18nKey.musicPlaylist)} aria-label={i18n(I18nKey.musicPlaylist)}>
<Icon is:inline name="mdi:playlist-music" class="text-xl" aria-hidden="true" />
</button>
</div>
<!-- Lyrics Drawer -->
<div class="lrc-drawer grid transition-all duration-300 ease-[cubic-bezier(0.4,0,0.2,1)] grid-rows-[0fr] opacity-0">
<div class="overflow-hidden min-h-0">
<div class="mt-2 pt-2 border-t border-neutral-100 dark:border-white/5 mx-1">
<div class="lrc-container h-48 overflow-y-auto custom-scrollbar flex flex-col items-center gap-2 p-4 py-24 text-center relative scroll-smooth" role="listbox" aria-label={i18n(I18nKey.musicLyrics)}>
<div class="text-neutral-400 text-sm py-10" role="option">{i18n(I18nKey.musicNoLyrics)}</div>
</div>
</div>
</div>
</div>
<!-- Playlist Drawer (Accordion) -->
<div class="playlist-drawer grid transition-all duration-300 ease-[cubic-bezier(0.4,0,0.2,1)] grid-rows-[0fr] opacity-0">
<div class="overflow-hidden min-h-0">
<div class="mt-2 pt-2 border-t border-neutral-100 dark:border-white/5 mx-1">
<div class="playlist-container max-h-48 overflow-y-auto custom-scrollbar pr-1 pb-1 relative" role="listbox" aria-label={i18n(I18nKey.musicPlaylist)}>
<!-- Items -->
</div>
</div>
</div>
</div>
<!-- Loading Overlay -->
<div class="music-loading absolute inset-0 z-20 flex flex-col items-center justify-center bg-white/60 dark:bg-[#1e1e1e]/60 backdrop-blur-[2px] transition-opacity duration-300 opacity-0 pointer-events-none rounded-xl" aria-busy="true" aria-hidden="true">
<div class="w-8 h-8 text-(--primary) animate-spin">
<Icon is:inline name="material-symbols:sync-rounded" class="text-3xl" aria-hidden="true" />
</div>
</div>
</div>
<template id={`playlist-item-template-${widgetId}`}>
<div class="playlist-item flex items-center gap-3 p-2 rounded-lg cursor-pointer hover:bg-neutral-50 dark:hover:bg-white/5 transition-colors group">
<div class="w-8 h-8 rounded-md overflow-hidden shrink-0 relative bg-neutral-200 dark:bg-neutral-700">
<img src="" class="item-cover w-full h-full object-cover" loading="lazy" alt="" />
<!-- Active Indicator overlay with animated equalizer / play icon -->
<div class="item-active-overlay absolute inset-0 bg-(--primary)/20 hidden items-center justify-center">
<div class="eq-bars flex items-end gap-[2px] h-3.5">
<span class="eq-bar w-[3px] bg-(--primary) rounded-sm"></span>
<span class="eq-bar w-[3px] bg-(--primary) rounded-sm"></span>
<span class="eq-bar w-[3px] bg-(--primary) rounded-sm"></span>
</div>
<svg class="eq-play-icon text-(--primary) hidden" width="14" height="14" viewBox="0 0 24 24" fill="currentColor"><path d="M8 5v14l11-7z"/></svg>
</div>
</div>
<div class="flex-1 min-w-0">
<div class="item-title text-xs font-bold text-neutral-700 dark:text-neutral-200 truncate group-hover:text-(--primary) transition-colors"></div>
<div class="item-artist text-[10px] text-neutral-400 truncate"></div>
</div>
</div>
</template>
<script define:vars={{ viewConfigStr, widgetId }} is:inline>
(function () {
var cfg = JSON.parse(viewConfigStr);
var widget = document.getElementById(widgetId);
if (!widget) return;
var mgr = window.__fireflyMusic;
if (!mgr) return;
// ── UI element refs ──────────────────────────────────────
var ui = {
widget: widget,
loading: widget.querySelector('.music-loading'),
cover: widget.querySelector('.music-cover'),
title: widget.querySelector('.music-title'),
artist: widget.querySelector('.music-artist'),
progressBar: widget.querySelector('.progress-bar'),
progressThumb: widget.querySelector('.progress-thumb'),
progressContainer: widget.querySelector('.progress-container'),
currentTime: widget.querySelector('.current-time'),
totalTime: widget.querySelector('.total-time'),
btnPlay: widget.querySelector('.btn-play'),
iconPlay: widget.querySelector('.icon-play'),
iconPause: widget.querySelector('.icon-pause'),
btnPrev: widget.querySelector('.btn-prev'),
btnNext: widget.querySelector('.btn-next'),
btnRepeat: widget.querySelector('.btn-repeat'),
iconRepeat: widget.querySelector('.icon-repeat'),
iconRepeatOne: widget.querySelector('.icon-repeat-one'),
iconShuffle: widget.querySelector('.icon-shuffle'),
btnMute: widget.querySelector('.btn-mute'),
iconVolHigh: widget.querySelector('.icon-vol-high'),
iconVolMute: widget.querySelector('.icon-vol-mute'),
volContainer: widget.querySelector('.vol-container'),
volBar: widget.querySelector('.vol-bar'),
btnLrc: widget.querySelector('.btn-lrc-toggle'),
iconLrcOn: widget.querySelector('.icon-lrc-on'),
iconLrcOff: widget.querySelector('.icon-lrc-off'),
lrcDrawer: widget.querySelector('.lrc-drawer'),
lrcContainer: widget.querySelector('.lrc-container'),
btnDrawer: widget.querySelector('.btn-drawer-toggle'),
playlistDrawer: widget.querySelector('.playlist-drawer'),
playlistContainer: widget.querySelector('.playlist-container'),
itemTemplate: document.getElementById('playlist-item-template-' + widgetId)
};
// Verify critical elements
var _critical = [ui.btnPlay, ui.btnRepeat, ui.btnMute, ui.volContainer,
ui.btnDrawer, ui.btnLrc, ui.lrcDrawer, ui.lrcContainer,
ui.progressContainer, ui.btnNext, ui.btnPrev, ui.loading,
ui.cover, ui.title, ui.artist, ui.playlistContainer, ui.itemTemplate];
if (_critical.some(function(el) { return !el; })) return;
// ── Local state (drawers, user scrolling, virtual scroll) ──
var ITEM_H = 42;
var OVERSCAN = 8;
var local = {
isUserScrolling: false,
scrollTimeout: null,
currentLrcIndex: -1,
vs: {
playlist: [],
currentIndex: -1,
renderedStart: -1,
renderedEnd: -1,
renderedEls: {},
scrollRaf: 0,
drawerOpen: false
}
};
// ── UI update functions ──────────────────────────────────
function setLoading(bool) {
if (bool) {
ui.loading.classList.remove('opacity-0', 'pointer-events-none');
} else {
ui.loading.classList.add('opacity-0', 'pointer-events-none');
}
}
function updatePlayStateUI(isPlaying) {
if (isPlaying) {
ui.btnPlay.classList.add('bg-(--primary)', 'text-white', 'hover:brightness-110');
ui.btnPlay.classList.remove('bg-(--btn-regular-bg)', 'hover:bg-(--btn-regular-bg-hover)', 'active:bg-(--btn-regular-bg-active)', 'text-(--primary)');
ui.iconPlay.classList.add('hidden');
ui.iconPause.classList.remove('hidden');
ui.cover.style.animationPlayState = 'running';
ui.btnPlay.setAttribute('aria-label', cfg.i18n.pause);
ui.btnPlay.title = cfg.i18n.pause;
} else {
ui.btnPlay.classList.remove('bg-(--primary)', 'text-white', 'hover:brightness-110');
ui.btnPlay.classList.add('bg-(--btn-regular-bg)', 'hover:bg-(--btn-regular-bg-hover)', 'active:bg-(--btn-regular-bg-active)', 'text-(--primary)');
ui.iconPlay.classList.remove('hidden');
ui.iconPause.classList.add('hidden');
ui.cover.style.animationPlayState = 'paused';
ui.btnPlay.setAttribute('aria-label', cfg.i18n.play);
ui.btnPlay.title = cfg.i18n.play;
}
// Toggle eq-bars / play icon in playlist
var activeItems = ui.playlistContainer.querySelectorAll('.playlist-item[aria-current="true"]');
activeItems.forEach(function (item) {
var eqBars = item.querySelector('.eq-bars');
var playIcon = item.querySelector('.eq-play-icon');
if (isPlaying) {
eqBars.classList.remove('hidden');
eqBars.classList.add('flex');
playIcon.classList.add('hidden');
} else {
eqBars.classList.add('hidden');
eqBars.classList.remove('flex');
playIcon.classList.remove('hidden');
}
});
}
function updateModeUI(playMode) {
var primaryColor = 'text-(--primary)';
if (playMode === 0) {
ui.btnRepeat.className = 'p-2 active:scale-95 transition-colors text-neutral-300 dark:text-neutral-600 hover:text-(--primary)';
ui.iconRepeat.classList.remove('hidden');
ui.iconRepeatOne.classList.add('hidden');
ui.iconShuffle.classList.add('hidden');
} else if (playMode === 1) {
ui.btnRepeat.className = 'p-2 active:scale-95 transition-colors ' + primaryColor;
ui.iconRepeat.classList.add('hidden');
ui.iconRepeatOne.classList.remove('hidden');
ui.iconShuffle.classList.add('hidden');
} else {
ui.btnRepeat.className = 'p-2 active:scale-95 transition-colors ' + primaryColor;
ui.iconRepeat.classList.add('hidden');
ui.iconRepeatOne.classList.add('hidden');
ui.iconShuffle.classList.remove('hidden');
}
}
function updateVolumeUI(volume, isMuted) {
var pct = isMuted ? 0 : volume * 100;
ui.volBar.style.width = pct + '%';
ui.volContainer.setAttribute('aria-valuenow', Math.round(pct).toString());
if (isMuted || volume === 0) {
ui.iconVolHigh.classList.add('hidden');
ui.iconVolMute.classList.remove('hidden');
} else {
ui.iconVolHigh.classList.remove('hidden');
ui.iconVolMute.classList.add('hidden');
}
}
function updateTrackUI(track) {
if (!track) return;
ui.title.innerText = track.name;
ui.title.title = track.name;
ui.artist.innerText = track.artist;
ui.artist.title = track.artist;
if (track.pic) {
ui.cover.classList.add('opacity-0');
ui.cover.src = track.pic;
ui.cover.alt = track.name + ' - ' + track.artist;
} else {
ui.cover.src = '';
ui.cover.classList.add('opacity-0');
ui.cover.alt = cfg.i18n.noCover;
}
// Reset cover rotation
ui.cover.classList.remove('animate-spin-slow');
void ui.cover.offsetWidth;
ui.cover.classList.add('animate-spin-slow');
ui.cover.style.animationPlayState = 'paused';
// Reset progress
ui.progressBar.style.width = '0%';
ui.progressThumb.style.left = '0%';
ui.progressContainer.setAttribute('aria-valuenow', '0');
ui.currentTime.innerText = '0:00';
ui.totalTime.innerText = '0:00';
}
// ── Virtual scroll helpers (absolute-position based) ──────
var PRIMARY_COLOR = getComputedStyle(document.documentElement).getPropertyValue('--primary').trim() || '#6366f1';
function vsApplyActiveStyle(el, isActive) {
var overlay = el.querySelector('.item-active-overlay');
var title = el.querySelector('.item-title');
var eqBars = el.querySelector('.eq-bars');
var playIcon = el.querySelector('.eq-play-icon');
var isPlaying = mgr.getState().isPlaying;
if (isActive) {
el.classList.add('bg-neutral-100', 'dark:bg-white/10');
el.setAttribute('aria-current', 'true');
overlay.classList.remove('hidden');
overlay.classList.add('flex');
title.style.color = PRIMARY_COLOR;
if (isPlaying) {
eqBars.classList.remove('hidden');
eqBars.classList.add('flex');
playIcon.classList.add('hidden');
} else {
eqBars.classList.add('hidden');
eqBars.classList.remove('flex');
playIcon.classList.remove('hidden');
}
} else {
el.classList.remove('bg-neutral-100', 'dark:bg-white/10');
el.removeAttribute('aria-current');
overlay.classList.add('hidden');
overlay.classList.remove('flex');
title.style.color = '';
}
}
function vsCreateItemEl(idx) {
var vs = local.vs;
var track = vs.playlist[idx];
var clone = ui.itemTemplate.content.cloneNode(true);
var itemEl = clone.querySelector('.playlist-item');
var img = clone.querySelector('.item-cover');
var title = clone.querySelector('.item-title');
var artist = clone.querySelector('.item-artist');
img.src = track.pic || '';
img.alt = track.name + ' - ' + track.artist;
title.innerText = track.name;
artist.innerText = track.artist;
itemEl.dataset.index = idx;
itemEl.setAttribute('role', 'option');
itemEl.setAttribute('aria-label', track.name + ' - ' + track.artist);
itemEl.onclick = function () { mgr.playTrackByIndex(idx); };
// Absolute positioning for virtual scroll
itemEl.style.position = 'absolute';
itemEl.style.left = '0';
itemEl.style.right = '0';
itemEl.style.top = (idx * ITEM_H) + 'px';
itemEl.style.height = ITEM_H + 'px';
if (idx === vs.currentIndex) {
vsApplyActiveStyle(itemEl, true);
}
return clone;
}
function vsCommitRange() {
var vs = local.vs;
if (vs.playlist.length === 0 || !vs.drawerOpen) return;
var container = ui.playlistContainer;
var scrollTop = container.scrollTop;
var viewHeight = container.clientHeight;
var start = Math.max(0, Math.floor(scrollTop / ITEM_H) - OVERSCAN);
var end = Math.min(vs.playlist.length, Math.ceil((scrollTop + viewHeight) / ITEM_H) + OVERSCAN);
if (start === vs.renderedStart && end === vs.renderedEnd) return;
if (vs.renderedStart === -1) {
// First render: batch via fragment
var frag = document.createDocumentFragment();
for (var i = start; i < end; i++) {
frag.appendChild(vsCreateItemEl(i));
}
container.appendChild(frag);
} else {
// Incremental: remove out-of-range, add new items
var oldEls = vs.renderedEls;
for (var ri = vs.renderedStart; ri < vs.renderedEnd; ri++) {
if (ri < start || ri >= end) {
if (oldEls[ri]) { oldEls[ri].remove(); delete oldEls[ri]; }
}
}
for (var ai = start; ai < end; ai++) {
if (!oldEls[ai]) {
var newEl = vsCreateItemEl(ai);
var inserted = false;
for (var ni = ai + 1; ni < end; ni++) {
if (oldEls[ni]) {
container.insertBefore(newEl, oldEls[ni]);
inserted = true;
break;
}
}
if (!inserted) container.appendChild(newEl);
oldEls[ai] = newEl;
}
}
}
// Rebuild reference map
vs.renderedEls = {};
var children = container.children;
for (var ci = 0; ci < children.length; ci++) {
var idx = parseInt(children[ci].dataset.index);
if (!isNaN(idx)) vs.renderedEls[idx] = children[ci];
}
vs.renderedStart = start;
vs.renderedEnd = end;
}
function vsRequestUpdate() {
var vs = local.vs;
if (vs.scrollRaf) return;
vs.scrollRaf = requestAnimationFrame(function () {
vs.scrollRaf = 0;
vsCommitRange();
});
}
function vsSetContainerHeight() {
ui.playlistContainer.style.height = (local.vs.playlist.length * ITEM_H) + 'px';
}
function renderPlaylist(playlist, currentIndex) {
var vs = local.vs;
vs.playlist = playlist;
vs.currentIndex = currentIndex;
vs.renderedStart = -1;
vs.renderedEnd = -1;
vs.renderedEls = {};
vs.drawerOpen = ui.playlistDrawer.style.gridTemplateRows === '1fr';
ui.playlistContainer.innerHTML = '';
if (vs.drawerOpen) {
vsSetContainerHeight();
vsCommitRange();
}
}
function updatePlaylistActiveUI(currentIndex) {
var vs = local.vs;
var oldIndex = vs.currentIndex;
vs.currentIndex = currentIndex;
if (vs.renderedEls[oldIndex]) {
vsApplyActiveStyle(vs.renderedEls[oldIndex], false);
}
if (currentIndex >= 0 && currentIndex < vs.playlist.length) {
if (currentIndex < vs.renderedStart || currentIndex >= vs.renderedEnd) {
ui.playlistContainer.scrollTop = currentIndex * ITEM_H;
vsCommitRange();
}
if (vs.renderedEls[currentIndex]) {
vsApplyActiveStyle(vs.renderedEls[currentIndex], true);
}
}
}
function renderLyricsUI(lyrics, status) {
local.currentLrcIndex = -1;
ui.lrcContainer.innerHTML = '';
if (status === 'loading') {
ui.lrcContainer.innerHTML = '<div class="text-neutral-400 text-sm py-10">' + cfg.i18n.loadingLyrics + '</div>';
return;
}
if (status === 'failed') {
ui.lrcContainer.innerHTML = '<div class="text-neutral-400 text-sm py-10">' + cfg.i18n.failedLyrics + '</div>';
return;
}
if (!lyrics || lyrics.length === 0) {
ui.lrcContainer.innerHTML = '<div class="text-neutral-400 text-sm py-10" role="option">' + cfg.i18n.noLyrics + '</div>';
return;
}
lyrics.forEach(function (line, index) {
var lineEl = document.createElement('div');
lineEl.className = 'lrc-line transition-all duration-300 text-sm text-neutral-400 py-1 cursor-pointer hover:text-(--primary)';
lineEl.innerText = line.text;
lineEl.dataset.index = index;
lineEl.setAttribute('role', 'option');
lineEl.setAttribute('aria-label', line.text);
lineEl.onclick = function () {
mgr.seekToTime(line.time);
};
ui.lrcContainer.appendChild(lineEl);
});
}
function updateLrcHighlight(index) {
if (index === local.currentLrcIndex) return;
local.currentLrcIndex = index;
var lines = ui.lrcContainer.querySelectorAll('.lrc-line');
lines.forEach(function (line, i) {
if (i === index) {
line.classList.add('text-(--primary)', 'font-bold', 'text-base');
line.classList.remove('text-neutral-400', 'text-sm');
} else {
line.classList.remove('text-(--primary)', 'font-bold', 'text-base');
line.classList.add('text-neutral-400', 'text-sm');
}
});
// Auto-scroll unless user is scrolling
if (index !== -1 && !local.isUserScrolling) {
var line = ui.lrcContainer.querySelector('.lrc-line[data-index="' + index + '"]');
if (line) {
var containerHeight = ui.lrcContainer.clientHeight;
var lineOffset = line.offsetTop;
var lineHeight = line.offsetHeight;
var targetScroll = lineOffset - (containerHeight / 2) + (lineHeight / 2);
ui.lrcContainer.scrollTo({ top: targetScroll, behavior: 'smooth' });
}
}
}
// ── Full sync from manager state (for late-mount) ────────
function syncAll() {
var s = mgr.getState();
if (!s.initialized) return;
// Loading off
setLoading(false);
if (s.playlist.length === 0) {
ui.title.innerText = s.error || cfg.i18n.noSongs;
return;
}
renderPlaylist(s.playlist, s.currentIndex);
if (s.track) updateTrackUI(s.track);
updatePlayStateUI(s.isPlaying);
updateModeUI(s.playMode);
updateVolumeUI(s.volume, s.isMuted);
// Progress
if (s.duration > 0) {
ui.progressBar.style.width = s.progress + '%';
ui.progressThumb.style.left = s.progress + '%';
ui.progressContainer.setAttribute('aria-valuenow', Math.round(s.progress).toString());
ui.currentTime.innerText = s.currentTimeStr;
ui.totalTime.innerText = s.durationStr;
}
// Lyrics
renderLyricsUI(s.lyrics, s.lyrics.length > 0 ? 'loaded' : 'none');
if (s.currentLrcIndex >= 0) updateLrcHighlight(s.currentLrcIndex);
// Cover image: if already set, show it
if (s.track && s.track.pic && ui.cover.src && ui.cover.complete && ui.cover.naturalWidth > 0) {
ui.cover.classList.remove('opacity-0');
}
// Update cover animation state to match play state
ui.cover.style.animationPlayState = s.isPlaying ? 'running' : 'paused';
}
// ── Event listeners (fm:* from manager) ──────────────────
var handlers = {};
function on(name, fn) {
handlers[name] = fn;
window.addEventListener(name, fn);
}
on('fm:init', function (e) {
var d = e.detail;
setLoading(false);
if (d.playlist.length > 0) {
renderPlaylist(d.playlist, 0);
updateModeUI(d.playMode);
updateVolumeUI(d.volume, d.isMuted);
} else {
ui.title.innerText = cfg.i18n.noSongs;
}
});
on('fm:track', function (e) {
var d = e.detail;
updateTrackUI(d.track);
updatePlaylistActiveUI(d.index);
});
on('fm:play-state', function (e) {
updatePlayStateUI(e.detail.isPlaying);
});
on('fm:time', function (e) {
var d = e.detail;
ui.progressBar.style.width = d.progress + '%';
ui.progressThumb.style.left = d.progress + '%';
ui.progressContainer.setAttribute('aria-valuenow', Math.round(d.progress).toString());
ui.currentTime.innerText = d.currentTimeStr;
ui.totalTime.innerText = d.durationStr;
});
on('fm:volume', function (e) {
updateVolumeUI(e.detail.volume, e.detail.isMuted);
});
on('fm:mode', function (e) {
updateModeUI(e.detail.playMode);
});
on('fm:lyrics', function (e) {
renderLyricsUI(e.detail.lyrics, e.detail.status);
});
on('fm:lrc-index', function (e) {
updateLrcHighlight(e.detail.index);
});
on('fm:error', function (e) {
ui.title.innerText = e.detail.message || cfg.i18n.error;
});
// ── Button click delegates ───────────────────────────────
ui.btnPlay.addEventListener('click', function () { mgr.togglePlay(); });
ui.btnNext.addEventListener('click', function () { mgr.playNext(); });
ui.btnPrev.addEventListener('click', function () { mgr.playPrev(); });
ui.btnRepeat.addEventListener('click', function () { mgr.cyclePlayMode(); });
ui.btnMute.addEventListener('click', function () { mgr.toggleMute(); });
ui.volContainer.addEventListener('click', function (e) {
var rect = ui.volContainer.getBoundingClientRect();
var x = e.clientX - rect.left;
var val = Math.max(0, Math.min(1, x / rect.width));
mgr.setVolume(val);
});
ui.progressContainer.addEventListener('click', function (e) {
var rect = ui.progressContainer.getBoundingClientRect();
var clickX = e.clientX - rect.left;
var percent = Math.min(Math.max(clickX / rect.width, 0), 1);
mgr.seek(percent);
});
// ── Drawer logic (local state) ───────────────────────────
ui.btnLrc.addEventListener('click', function () {
var isOpen = ui.lrcDrawer.style.gridTemplateRows === '1fr';
if (isOpen) {
ui.lrcDrawer.style.gridTemplateRows = '0fr';
ui.lrcDrawer.classList.remove('opacity-100');
ui.lrcDrawer.classList.add('opacity-0');
ui.btnLrc.classList.remove('text-(--primary)');
ui.btnLrc.classList.add('text-neutral-400');
ui.iconLrcOn.classList.add('hidden');
ui.iconLrcOff.classList.remove('hidden');
} else {
// Close playlist if open
ui.playlistDrawer.style.gridTemplateRows = '0fr';
ui.playlistDrawer.classList.remove('opacity-100');
ui.playlistDrawer.classList.add('opacity-0');
ui.btnDrawer.classList.remove('text-(--primary)');
ui.btnDrawer.classList.add('text-neutral-400');
ui.lrcDrawer.style.gridTemplateRows = '1fr';
ui.lrcDrawer.classList.add('opacity-100');
ui.lrcDrawer.classList.remove('opacity-0');
ui.btnLrc.classList.add('text-(--primary)');
ui.btnLrc.classList.remove('text-neutral-400');
ui.iconLrcOn.classList.remove('hidden');
ui.iconLrcOff.classList.add('hidden');
}
});
ui.btnDrawer.addEventListener('click', function () {
var isOpen = ui.playlistDrawer.style.gridTemplateRows === '1fr';
if (isOpen) {
ui.playlistDrawer.style.gridTemplateRows = '0fr';
ui.playlistDrawer.classList.remove('opacity-100');
ui.playlistDrawer.classList.add('opacity-0');
ui.btnDrawer.classList.add('text-neutral-400');
ui.btnDrawer.classList.remove('text-(--primary)');
local.vs.drawerOpen = false;
} else {
// Close lyrics if open
ui.lrcDrawer.style.gridTemplateRows = '0fr';
ui.lrcDrawer.classList.remove('opacity-100');
ui.lrcDrawer.classList.add('opacity-0');
ui.btnLrc.classList.remove('text-(--primary)');
ui.btnLrc.classList.add('text-neutral-400');
ui.iconLrcOn.classList.add('hidden');
ui.iconLrcOff.classList.remove('hidden');
ui.playlistDrawer.style.gridTemplateRows = '1fr';
ui.playlistDrawer.classList.add('opacity-100');
ui.playlistDrawer.classList.remove('opacity-0');
ui.btnDrawer.classList.remove('text-neutral-400');
ui.btnDrawer.classList.add('text-(--primary)');
local.vs.drawerOpen = true;
// Render playlist after drawer transition settles
if (local.vs.playlist.length > 0) {
requestAnimationFrame(function () {
vsSetContainerHeight();
vsCommitRange();
});
}
}
});
// ── Playlist virtual scroll listener ──────────────────────
ui.playlistContainer.addEventListener('scroll', function () {
vsRequestUpdate();
});
// ── Lyrics user scroll detection ─────────────────────────
function resetScrollTimeout() {
clearTimeout(local.scrollTimeout);
local.scrollTimeout = setTimeout(function () {
local.isUserScrolling = false;
// Snap back to current lyric
var s = mgr.getState();
if (s.currentLrcIndex >= 0) {
var line = ui.lrcContainer.querySelector('.lrc-line[data-index="' + s.currentLrcIndex + '"]');
if (line) {
var containerHeight = ui.lrcContainer.clientHeight;
var lineOffset = line.offsetTop;
var lineHeight = line.offsetHeight;
var targetScroll = lineOffset - (containerHeight / 2) + (lineHeight / 2);
ui.lrcContainer.scrollTo({ top: targetScroll, behavior: 'auto' });
}
}
}, 3000);
}
ui.lrcContainer.addEventListener('wheel', function () {
local.isUserScrolling = true;
resetScrollTimeout();
});
ui.lrcContainer.addEventListener('touchstart', function () {
local.isUserScrolling = true;
resetScrollTimeout();
});
// ── Cover image events ───────────────────────────────────
ui.cover.addEventListener('load', function () {
ui.cover.classList.remove('opacity-0');
});
ui.cover.addEventListener('error', function () {
ui.cover.classList.add('opacity-0');
});
// ── Cleanup on DOM removal ───────────────────────────────
var observer = new MutationObserver(function (mutations) {
for (var i = 0; i < mutations.length; i++) {
var removed = mutations[i].removedNodes;
for (var j = 0; j < removed.length; j++) {
if (removed[j] === widget || (removed[j].contains && removed[j].contains(widget))) {
// Widget removed from DOM – clean up event listeners
Object.keys(handlers).forEach(function (name) {
window.removeEventListener(name, handlers[name]);
});
observer.disconnect();
clearTimeout(local.scrollTimeout);
return;
}
}
}
});
if (widget.parentNode) {
observer.observe(widget.parentNode, { childList: true });
}
// ── Init: either sync existing state or trigger init ─────
var currentState = mgr.getState();
if (currentState.initialized) {
// Manager already initialized (late mount) – sync all UI
syncAll();
} else {
// First widget to mount – show loading and trigger init
setLoading(true);
mgr.init();
}
})();
</script>
<style>
@keyframes spin-slow {
from { transform: rotate(0deg); }
to { transform: rotate(360deg); }
}
.animate-spin-slow {
animation: spin-slow 10s linear infinite;
}
/* Now-playing equalizer bars */
.eq-bars .eq-bar {
animation: eq-bounce 1.2s ease-in-out infinite;
}
.eq-bars .eq-bar:nth-child(1) { animation-duration: 0.8s; }
.eq-bars .eq-bar:nth-child(2) { animation-duration: 0.6s; animation-delay: 0.15s; }
.eq-bars .eq-bar:nth-child(3) { animation-duration: 1.0s; animation-delay: 0.3s; }
@keyframes eq-bounce {
0%, 100% { height: 4px; }
50% { height: 14px; }
}
</style>
+378
View File
@@ -0,0 +1,378 @@
---
import { sakuraConfig } from "@/config";
const config = sakuraConfig;
---
<script is:inline define:vars={{ sakuraConfig: config }}>
let windowWidth = window.innerWidth;
let windowHeight = window.innerHeight;
// 樱花对象类
class Sakura {
constructor(x, y, s, r, a, fn, idx, img, limitArray, config) {
this.x = x;
this.y = y;
this.s = s;
this.r = r;
this.a = a;
this.fn = fn;
this.idx = idx;
this.img = img;
this.limitArray = limitArray;
this.config = config;
}
draw(cxt) {
cxt.save();
cxt.translate(this.x, this.y);
cxt.rotate(this.r);
cxt.globalAlpha = this.a;
cxt.drawImage(this.img, 0, 0, 40 * this.s, 40 * this.s);
cxt.restore();
}
update() {
this.x = this.fn.x(this.x, this.y);
this.y = this.fn.y(this.y, this.y);
this.r = this.fn.r(this.r);
this.a = this.fn.a(this.a);
// 如果樱花越界,重新调整位置
if (
this.x > windowWidth ||
this.x < 0 ||
this.y > windowHeight ||
this.y < 0 ||
this.a <= 0
) {
// 如果樱花不做限制
if (this.limitArray[this.idx] === -1) {
this.resetPosition();
}
// 否则樱花有限制
else {
if (this.limitArray[this.idx] > 0) {
this.resetPosition();
this.limitArray[this.idx]--;
}
}
}
}
resetPosition() {
this.r = getRandom('fnr', this.config);
if (Math.random() > 0.4) {
this.x = getRandom('x', this.config);
this.y = 0;
this.s = getRandom('s', this.config);
this.r = getRandom('r', this.config);
this.a = getRandom('a', this.config);
} else {
this.x = windowWidth;
this.y = getRandom('y', this.config);
this.s = getRandom('s', this.config);
this.r = getRandom('r', this.config);
this.a = getRandom('a', this.config);
}
}
}
// 樱花列表类
class SakuraList {
constructor() {
this.list = [];
}
push(sakura) {
this.list.push(sakura);
}
update() {
for (let i = 0, len = this.list.length; i < len; i++) {
this.list[i].update();
}
}
draw(cxt) {
for (let i = 0, len = this.list.length; i < len; i++) {
this.list[i].draw(cxt);
}
}
get(i) {
return this.list[i];
}
size() {
return this.list.length;
}
}
// 获取随机值的函数
function getRandom(option, config) {
let ret;
let random;
switch (option) {
case 'x':
ret = Math.random() * windowWidth;
break;
case 'y':
ret = Math.random() * windowHeight;
break;
case 's':
ret = config.size.min + Math.random() * (config.size.max - config.size.min);
break;
case 'r':
ret = Math.random() * 6;
break;
case 'a':
ret = config.opacity.min + Math.random() * (config.opacity.max - config.opacity.min);
break;
case 'fnx':
random = config.speed.horizontal.min + Math.random() * (config.speed.horizontal.max - config.speed.horizontal.min);
ret = function (x, _y) {
return x + random;
};
break;
case 'fny':
random = config.speed.vertical.min + Math.random() * (config.speed.vertical.max - config.speed.vertical.min);
ret = function (_x, y) {
return y + random;
};
break;
case 'fnr':
ret = function (r) {
return r + config.speed.rotation;
};
break;
case 'fna':
ret = function (alpha) {
return alpha - config.speed.fadeSpeed * 0.01;
};
break;
}
return ret;
}
// 樱花管理器类
class SakuraManager {
constructor(config) {
this.config = config;
this.canvas = null;
this.ctx = null;
this.sakuraList = null;
this.animationId = null;
this.img = null;
this.isRunning = false;
}
// 初始化樱花特效
async init() {
if (!this.config.enable || this.isRunning) {
return;
}
// 创建图片对象
this.img = new Image();
this.img.src = '/assets/images/effects/sakura.png'; // 使用樱花图片
// 等待图片加载完成
await new Promise((resolve, reject) => {
if (this.img) {
this.img.onload = () => resolve();
this.img.onerror = () => reject(new Error('Failed to load sakura image'));
}
});
this.createCanvas();
this.createSakuraList();
this.startAnimation();
this.isRunning = true;
}
// 创建画布
createCanvas() {
this.canvas = document.createElement('canvas');
this.canvas.height = windowHeight;
this.canvas.width = windowWidth;
this.canvas.setAttribute('style', `position: fixed; left: 0; top: 0; pointer-events: none; z-index: ${this.config.zIndex}; transform: translateZ(0);`);
this.canvas.setAttribute('id', 'canvas_sakura');
document.body.appendChild(this.canvas);
this.ctx = this.canvas.getContext('2d');
// 监听窗口大小变化
this._boundHandleResize = this.handleResize.bind(this);
window.addEventListener('resize', this._boundHandleResize);
}
// 创建樱花列表
createSakuraList() {
if (!this.img || !this.ctx) return;
this.sakuraList = new SakuraList();
const limitArray = new Array(this.config.sakuraNum).fill(this.config.limitTimes);
for (let i = 0; i < this.config.sakuraNum; i++) {
const randomX = getRandom('x', this.config);
const randomY = getRandom('y', this.config);
const randomS = getRandom('s', this.config);
const randomR = getRandom('r', this.config);
const randomA = getRandom('a', this.config);
const randomFnx = getRandom('fnx', this.config);
const randomFny = getRandom('fny', this.config);
const randomFnR = getRandom('fnr', this.config);
const randomFnA = getRandom('fna', this.config);
const sakura = new Sakura(
randomX,
randomY,
randomS,
randomR,
randomA,
{
x: randomFnx,
y: randomFny,
r: randomFnR,
a: randomFnA,
},
i,
this.img,
limitArray,
this.config
);
sakura.draw(this.ctx);
this.sakuraList.push(sakura);
}
}
// 开始动画
startAnimation() {
if (!this.ctx || !this.canvas || !this.sakuraList) return;
const animate = () => {
if (!this.ctx || !this.canvas || !this.sakuraList) return;
this.ctx.clearRect(0, 0, this.canvas.width, this.canvas.height);
this.sakuraList.update();
this.sakuraList.draw(this.ctx);
this.animationId = requestAnimationFrame(animate);
};
this.animationId = requestAnimationFrame(animate);
}
// 处理窗口大小变化
handleResize() {
windowWidth = window.innerWidth;
windowHeight = window.innerHeight;
if (this.canvas) {
this.canvas.width = windowWidth;
this.canvas.height = windowHeight;
}
}
// 停止樱花特效
stop() {
if (this.animationId) {
cancelAnimationFrame(this.animationId);
this.animationId = null;
}
if (this.canvas) {
document.body.removeChild(this.canvas);
this.canvas = null;
}
if (this._boundHandleResize) {
window.removeEventListener('resize', this._boundHandleResize);
this._boundHandleResize = null;
}
this.isRunning = false;
}
// 切换樱花特效
toggle() {
if (this.isRunning) {
this.stop();
} else {
this.init();
}
}
// 更新配置
updateConfig(newConfig) {
const wasRunning = this.isRunning;
if (wasRunning) {
this.stop();
}
this.config = newConfig;
if (wasRunning && newConfig.enable) {
this.init();
}
}
// 获取运行状态
getIsRunning() {
return this.isRunning;
}
}
// 创建全局樱花管理器实例
let globalSakuraManager = null;
window.sakuraManager = null;
// 初始化樱花特效
function initSakura(config) {
if (globalSakuraManager) {
globalSakuraManager.updateConfig(config);
} else {
globalSakuraManager = new SakuraManager(config);
window.sakuraManager = globalSakuraManager;
if (config.enable) {
globalSakuraManager.init();
}
}
}
// 樱花特效初始化
(function() {
// 全局标记,确保樱花特效只初始化一次
if (window.sakuraInitialized) {
return;
}
// 初始化樱花特效的函数
const setupSakura = () => {
if (window.sakuraInitialized) return;
// 检查用户是否在设置中关闭了樱花特效
var storedEnabled = localStorage.getItem("sakuraEnabled");
var isEnabled = storedEnabled !== null ? storedEnabled === "true" : sakuraConfig.enable;
// 创建管理器并根据用户偏好决定是否启动
var cfg = Object.assign({}, sakuraConfig, { enable: isEnabled });
initSakura(cfg);
window.sakuraInitialized = true;
};
// 页面加载完成后初始化樱花特效
if (document.readyState === 'loading') {
document.addEventListener('DOMContentLoaded', setupSakura);
} else {
setupSakura();
}
})();
// 监听设置面板的樱花特效切换事件
window.addEventListener('sakuraToggle', function(e) {
var enabled = e.detail.enabled;
var mgr = window.sakuraManager;
if (!mgr) return;
if (enabled && !mgr.getIsRunning()) {
mgr.config.enable = true;
mgr.init();
} else if (!enabled && mgr.getIsRunning()) {
mgr.stop();
}
});
</script>
+450
View File
@@ -0,0 +1,450 @@
---
import MessageBox from "@/components/common/PioMessageBox.astro";
import { spineModelConfig } from "@/config/pioConfig";
import { url } from "@/utils/url-utils";
---
<!-- Spine Web Player CSS 将在 script 中动态加载 -->{
spineModelConfig.enable && (
<div
id="spine-model-container"
style={`
position: fixed;
${spineModelConfig.position.corner.includes("right") ? "right" : "left"}: ${spineModelConfig.position.offsetX}px;
${spineModelConfig.position.corner.includes("top") ? "top" : "bottom"}: ${spineModelConfig.position.offsetY}px;
width: ${spineModelConfig.size.width}px;
height: ${spineModelConfig.size.height}px;
pointer-events: auto;
z-index: 1000;
`}
>
<div id="spine-player-container" style="width: 100%; height: 100%;" />
<div id="spine-error" style="display: none;" />
</div>
)
}
<!-- 引入消息框组件 -->
<MessageBox />
<script is:inline define:vars={{ spineModelConfig, modelPath: url(spineModelConfig.model.path), atlasPath: url(spineModelConfig.model.path.replace(".json", ".atlas")), cssPath: url("/pio/static/spine-player.min.css"), jsPath: url("/pio/static/spine-player.min.js") }}>
// 动态加载 Spine CSS(带本地备用)
function loadSpineCSS() {
if (!spineModelConfig.enable) return;
// 检查是否已经加载
const existingLink = document.querySelector('link[href*="spine-player"]');
if (existingLink) return;
// 首先尝试加载 CDN CSS
const cdnLink = document.createElement("link");
cdnLink.rel = "stylesheet";
cdnLink.href =
"https://unpkg.com/@esotericsoftware/spine-player@4.2.*/dist/spine-player.min.css";
// 监听加载失败事件,自动回退到本地文件
cdnLink.onerror = function () {
console.warn("⚠️ Spine CSS CDN failed, trying local fallback...");
// 移除失败的 CDN link
if (cdnLink.parentNode) {
cdnLink.parentNode.removeChild(cdnLink);
}
// 创建本地备用 CSS link
const localLink = document.createElement("link");
localLink.rel = "stylesheet";
localLink.href = cssPath;
localLink.onerror = function () {
console.error("❌ Failed to load Spine CSS");
};
document.head.appendChild(localLink);
};
document.head.appendChild(cdnLink);
}
// 消息框功能已移至公共组件 MessageBox.astro
let isClickProcessing = false; // 防止重复点击的标志
let lastClickTime = 0; // 记录最后一次点击时间
// 全局变量,防止重复初始化
window.spineModelInitialized = window.spineModelInitialized || false;
window.spinePlayerInstance = window.spinePlayerInstance || null;
// 消息显示函数 - 使用公共消息框组件
function showMessage(message) {
// 使用公共消息框组件
if (window.showModelMessage) {
window.showModelMessage(message, {
containerId: "spine-model-container",
displayTime: spineModelConfig.interactive.messageDisplayTime || 3000
});
}
}
// 更新响应式显示
function updateResponsiveDisplay() {
if (!spineModelConfig.enable) return;
const container = document.getElementById("spine-model-container");
if (!container) return;
// 检查移动端显示设置
if (
spineModelConfig.responsive.hideOnMobile &&
window.innerWidth <= spineModelConfig.responsive.mobileBreakpoint
) {
container.style.display = "none";
} else {
container.style.display = "block";
}
}
// 清理函数
function cleanupSpineModel() {
console.log("🧹 Cleaning up existing Spine model...");
// 清理消息显示(使用公共组件)
if (window.clearModelMessage) {
window.clearModelMessage();
}
// 清理现有的播放器实例
if (window.spinePlayerInstance) {
try {
if (window.spinePlayerInstance.dispose) {
window.spinePlayerInstance.dispose();
}
} catch (e) {
console.warn("Error disposing spine player:", e);
}
window.spinePlayerInstance = null;
}
// 清理容器内容
const playerContainer = document.getElementById("spine-player-container");
if (playerContainer) {
playerContainer.innerHTML = "";
}
// 重置初始化标志
window.spineModelInitialized = false;
}
async function initSpineModel() {
if (!spineModelConfig.enable) return;
// 检查移动端显示设置,如果隐藏则不加载运行时
if (
spineModelConfig.responsive.hideOnMobile &&
window.innerWidth <= spineModelConfig.responsive.mobileBreakpoint
) {
console.log("📱 Mobile device detected, skipping Spine model initialization");
const container = document.getElementById("spine-model-container");
if (container) container.style.display = "none";
return;
}
// 检查是否已经初始化
if (window.spineModelInitialized) {
console.log("⏭️ Spine model already initialized, skipping...");
return;
}
console.log("🎯 Initializing Spine Model...");
// 先清理可能存在的旧实例
cleanupSpineModel();
// 首先加载 CSS
loadSpineCSS();
// 加载 Spine Web Player 运行时
const loadSpineRuntime = () => {
return new Promise((resolve, reject) => {
if (typeof window.spine !== "undefined") {
console.log("✅ Spine runtime already loaded");
resolve();
return;
}
console.log("📦 Loading Spine runtime...");
const script = document.createElement("script");
script.src =
"https://unpkg.com/@esotericsoftware/spine-player@4.2.*/dist/iife/spine-player.min.js";
script.onload = () => {
console.log("✅ Spine runtime loaded from CDN");
resolve();
};
script.onerror = (_error) => {
console.warn("⚠️ CDN failed, trying local fallback...");
// 尝试本地回退
const fallbackScript = document.createElement("script");
fallbackScript.src = jsPath;
fallbackScript.onload = () => {
console.log("✅ Spine runtime loaded from local fallback");
resolve();
};
fallbackScript.onerror = () => {
reject(new Error("Failed to load Spine runtime"));
};
document.head.appendChild(fallbackScript);
};
document.head.appendChild(script);
});
};
// 等待 Spine 库加载
const waitForSpine = () => {
return new Promise((resolve, reject) => {
let attempts = 0;
const maxAttempts = 50;
const check = () => {
attempts++;
if (typeof window.spine !== "undefined" && window.spine.SpinePlayer) {
console.log("✅ Spine runtime loaded");
resolve();
} else if (attempts >= maxAttempts) {
reject(new Error("Spine runtime loading timeout"));
} else {
setTimeout(check, 100);
}
};
check();
});
};
try {
// 首先加载 Spine 运行时
await loadSpineRuntime();
// 然后等待 Spine 对象可用
await waitForSpine();
// 标记为已初始化
window.spineModelInitialized = true;
// 创建 SpinePlayer
new window.spine.SpinePlayer("spine-player-container", {
skeleton: modelPath,
atlas: atlasPath,
animation: "idle",
backgroundColor: "#00000000", // 透明背景
showControls: false, // 隐藏控件
alpha: true,
premultipliedAlpha: false,
success: (player) => {
console.log("🎉 Spine model loaded successfully!");
// 保存播放器实例引用
window.spinePlayerInstance = player;
// 构建可用动画索引,避免播放不存在的动画导致报错
const availableAnimations = new Set(
(player.skeleton?.data?.animations || [])
.map((anim) => anim?.name)
.filter(Boolean)
);
const pickRandom = (list) =>
list[Math.floor(Math.random() * list.length)];
const configuredClickAnims =
spineModelConfig.interactive.clickAnimations ||
(spineModelConfig.interactive.clickAnimation
? [spineModelConfig.interactive.clickAnimation]
: []);
const configuredIdleAnims =
spineModelConfig.interactive.idleAnimations || ["idle"];
const validClickAnims = configuredClickAnims.filter((name) =>
availableAnimations.has(name)
);
const validIdleAnims = configuredIdleAnims.filter((name) =>
availableAnimations.has(name)
);
const fallbackIdleAnim =
(availableAnimations.has("idle") && "idle") ||
validIdleAnims[0] ||
configuredIdleAnims[0] ||
configuredClickAnims[0] ||
Array.from(availableAnimations)[0];
const safeSetAnimation = (name, loop) => {
if (!name || !availableAnimations.has(name)) {
return false;
}
try {
player.setAnimation(name, loop);
return true;
} catch (e) {
console.warn(`Failed to play animation: ${name}`, e);
return false;
}
};
// 初始动画兜底,防止默认 idle 不存在
if (!safeSetAnimation("idle", true) && fallbackIdleAnim) {
safeSetAnimation(fallbackIdleAnim, true);
}
// 输出一次配置校验信息,便于排查模型与配置不一致
const missingClickAnims = configuredClickAnims.filter(
(name) => !availableAnimations.has(name)
);
if (missingClickAnims.length > 0) {
console.warn(
"Spine click animations not found in model:",
missingClickAnims
);
}
// 初始化完成后设置默认姿态
setTimeout(() => {
if (player.skeleton) {
try {
player.skeleton.setToSetupPose();
const physicsMode =
window.spine?.Physics?.update ??
window.spine?.Physics?.pose ??
window.spine?.Physics?.none ??
0;
player.skeleton.updateWorldTransform(physicsMode);
} catch (e) {
console.warn("Error positioning skeleton:", e);
}
}
}, 500);
// 设置交互功能
if (spineModelConfig.interactive.enabled) {
const canvas = document.querySelector(
"#spine-player-container canvas"
);
if (canvas) {
canvas.addEventListener("click", () => {
// 防抖处理:防止重复点击
const currentTime = Date.now();
if (isClickProcessing || currentTime - lastClickTime < 500) {
return; // 500ms 内重复点击忽略
}
isClickProcessing = true;
lastClickTime = currentTime;
// 随机播放点击动画(仅在动画存在时)
if (validClickAnims.length > 0) {
const randomClickAnim = pickRandom(validClickAnims);
safeSetAnimation(randomClickAnim, false);
// 动画播放完成后回到待机状态
setTimeout(() => {
const randomIdle =
validIdleAnims.length > 0
? pickRandom(validIdleAnims)
: fallbackIdleAnim;
safeSetAnimation(randomIdle, true);
}, 2000);
} else if (fallbackIdleAnim) {
safeSetAnimation(fallbackIdleAnim, true);
}
// 显示随机消息
const messages = spineModelConfig.interactive.clickMessages;
if (messages && messages.length > 0) {
const randomMessage =
messages[Math.floor(Math.random() * messages.length)];
showMessage(randomMessage);
}
// 500ms 后重置防抖标志
setTimeout(() => {
isClickProcessing = false;
}, 500);
});
// 设置待机动画循环(仅在至少两个有效待机动画时启用)
if (validIdleAnims.length > 1) {
setInterval(() => {
const randomIdle = pickRandom(validIdleAnims);
safeSetAnimation(randomIdle, true);
}, spineModelConfig.interactive.idleInterval);
}
}
}
console.log("✅ Spine model setup complete!");
},
error: (_player, reason) => {
console.error("❌ Spine model loading error:", reason);
const errorDiv = document.getElementById("spine-error");
if (errorDiv) {
errorDiv.style.display = "block";
errorDiv.innerHTML = `
<div style="color: #ff4444; padding: 20px; text-align: center; font-size: 14px;">
<div>⚠️ Spine 模型加载失败</div>
<div style="font-size: 12px; margin-top: 8px; color: #888;">${reason}</div>
</div>
`;
}
const canvas = document.getElementById("spine-canvas");
if (canvas) canvas.style.display = "none";
},
});
} catch (error) {
console.error("Spine model initialization error:", error);
// 重置初始化标志,允许重试
window.spineModelInitialized = false;
const errorDiv = document.getElementById("spine-error");
if (errorDiv) {
errorDiv.style.display = "block";
errorDiv.innerHTML = `
<div style="color: #ff4444; padding: 20px; text-align: center; font-size: 14px;">
<div>⚠️ Spine 运行时加载失败</div>
<div style="font-size: 12px; margin-top: 8px; color: #888;">${error instanceof Error ? error.message : "未知错误"}</div>
</div>
`;
}
}
}
// 监听页面卸载事件,清理资源
window.addEventListener("beforeunload", cleanupSpineModel);
// 监听 Swup 页面切换事件(如果使用了 Swup)
if (typeof window.swup !== "undefined" && window.swup.hooks) {
window.swup.hooks.on("content:replace", () => {
// 只更新响应式显示,不重新创建模型
setTimeout(() => {
updateResponsiveDisplay();
}, 100);
});
}
// 监听 popstate 事件(浏览器前进后退)
window.addEventListener("popstate", () => {
setTimeout(() => {
updateResponsiveDisplay();
}, 100);
});
// 监听窗口大小变化
window.addEventListener("resize", updateResponsiveDisplay);
// 页面加载完成后初始化(只初始化一次)
if (document.readyState === "loading") {
document.addEventListener("DOMContentLoaded", initSpineModel);
} else {
initSpineModel();
}
</script>
@@ -0,0 +1,202 @@
---
export interface Props {
text: string | string[];
speed?: number;
deleteSpeed?: number;
pauseTime?: number;
class?: string;
}
const {
text,
speed = 100,
deleteSpeed = 50,
pauseTime = 2000,
class: className = "",
} = Astro.props;
const textData = Array.isArray(text) ? JSON.stringify(text) : text;
---
<span
class={`typewriter ${className}`}
data-text={textData}
data-speed={speed}
data-delete-speed={deleteSpeed}
data-pause-time={pauseTime}></span>
<script>
class TypewriterEffect {
private element: HTMLElement;
private texts: string[];
private currentTextIndex: number = 0;
private speed: number;
private deleteSpeed: number;
private pauseTime: number;
private currentIndex: number = 0;
private isDeleting: boolean = false;
private timeoutId: number | null = null;
constructor(element: HTMLElement) {
this.element = element;
const textData = element.dataset.text || "";
// 尝试解析为JSON数组,如果失败则作为单个字符串处理
try {
const parsed = JSON.parse(textData);
this.texts = Array.isArray(parsed) ? parsed : [textData];
} catch {
this.texts = [textData];
}
this.speed = parseInt(element.dataset.speed || "100");
this.deleteSpeed = parseInt(element.dataset.deleteSpeed || "50");
this.pauseTime = parseInt(element.dataset.pauseTime || "2000");
// 如果有多条文本且未启用打字机效果,随机显示一条
if (this.texts.length > 1 && !this.isTypewriterEnabled()) {
this.showRandomText();
} else {
this.start();
}
}
private isTypewriterEnabled(): boolean {
// 检查是否有打字机相关的数据属性
return (
this.element.dataset.speed !== undefined ||
this.element.dataset.deleteSpeed !== undefined ||
this.element.dataset.pauseTime !== undefined
);
}
private showRandomText() {
const randomIndex = Math.floor(Math.random() * this.texts.length);
this.element.textContent = this.texts[randomIndex];
}
private start() {
if (this.texts.length === 0) return;
this.type();
}
private getCurrentText(): string {
return this.texts[this.currentTextIndex] || "";
}
private type() {
const currentText = this.getCurrentText();
const segments = this.segmentText(currentText);
if (this.isDeleting) {
// 删除字符
if (this.currentIndex > 0) {
this.currentIndex--;
this.element.textContent = segments
.slice(0, this.currentIndex)
.join("");
this.timeoutId = window.setTimeout(
() => this.type(),
this.deleteSpeed
);
} else {
// 删除完成,切换到下一条文本
this.isDeleting = false;
this.currentTextIndex =
(this.currentTextIndex + 1) % this.texts.length;
this.timeoutId = window.setTimeout(() => this.type(), this.speed);
}
} else {
if (this.currentIndex < segments.length) {
this.currentIndex++;
this.element.textContent = segments
.slice(0, this.currentIndex)
.join("");
this.timeoutId = window.setTimeout(() => this.type(), this.speed);
} else {
// 打字完成,暂停后开始删除(如果有多条文本)
if (this.texts.length > 1) {
this.isDeleting = true;
this.timeoutId = window.setTimeout(
() => this.type(),
this.pauseTime
);
}
// 如果只有一条文本,保持显示不删除
}
}
}
public destroy() {
if (this.timeoutId) {
clearTimeout(this.timeoutId);
}
}
private segmentText(text: string): string[] {
const segmenter = new Intl.Segmenter(undefined, { granularity: "grapheme" });
return Array.from(segmenter.segment(text), s => s.segment);
}
}
function initTypewriterElements() {
const typewriterElements = document.querySelectorAll(".typewriter");
typewriterElements.forEach((element) => {
const el = element as HTMLElement & { __typewriterInstance?: TypewriterEffect };
if (el.__typewriterInstance) {
el.__typewriterInstance.destroy();
}
el.textContent = "";
el.__typewriterInstance = new TypewriterEffect(el);
});
}
// 初始化所有打字机效果
function runInitWithDelay() {
initTypewriterElements();
// 兼容 banner 显隐晚于内容替换的场景
setTimeout(initTypewriterElements, 220);
}
if (document.readyState === "loading") {
document.addEventListener("DOMContentLoaded", runInitWithDelay);
} else {
runInitWithDelay();
}
// 支持页面切换时重新初始化(兼容不同 swup 事件名)
document.addEventListener("swup:contentReplaced", runInitWithDelay);
document.addEventListener("swup:content:replace", runInitWithDelay);
document.addEventListener("swup:page:view", runInitWithDelay);
// swup hooks(若可用)
if (typeof window !== "undefined" && window.swup?.hooks) {
window.swup.hooks.on("content:replace", runInitWithDelay);
window.swup.hooks.on("page:view", runInitWithDelay);
}
</script>
<style>
.typewriter {
position: relative;
}
.typewriter::after {
content: "|";
animation: blink 1s infinite;
margin-left: 2px;
}
@keyframes blink {
0%,
50% {
opacity: 1;
}
51%,
100% {
opacity: 0;
}
}
</style>
+420
View File
@@ -0,0 +1,420 @@
---
import I18nKey from "@i18n/i18nKey";
import { i18n } from "@i18n/translation";
import { Icon } from "astro-icon/components";
import { getCategoryList, getSortedPostsList } from "@/utils/content-utils";
import { url } from "@/utils/url-utils";
interface Props {
currentPostCategory?: string;
}
const { currentPostCategory } = Astro.props as Props;
const categories = await getCategoryList();
const totalPosts = (await getSortedPostsList()).length;
const homeUrl = url("/");
const archiveUrl = url("/archive/");
// 服务端计算初始高亮 pill(首屏无需等 JS)。
// 查询串筛选(?category=/?tag=/?uncategorized)在静态页构建期不可知,
// 交由客户端脚本在加载/导航时同步;此处只处理路径可确定的情况。
const pathname = Astro.url.pathname.replace(/\/$/, "");
const homePath = homeUrl.replace(/\/$/, "");
const archivePath = archiveUrl.replace(/\/$/, "");
const isHome = pathname === homePath || pathname === "" || pathname === "/";
const isCategories = pathname === "/categories";
const isArchive = pathname === archivePath;
const postCategory = (currentPostCategory || "").trim();
// 返回某个 pill 的初始高亮属性:active(强)或 soft-active(弱,文章页所属分类)
function initialActive(categoryName: string): {
active?: boolean;
soft?: boolean;
} {
if (isHome) return categoryName === "" ? { active: true } : {};
if (isCategories)
return categoryName === "__categories__" ? { active: true } : {};
if (isArchive) return categoryName === "__archive__" ? { active: true } : {};
if (postCategory && categoryName === postCategory) return { soft: true };
return {};
}
---
<div
class="card-base category-bar p-3 onload-animation"
id="category-bar"
data-home-path={homeUrl}
data-archive-path={archiveUrl}
data-current-post-category={currentPostCategory || ""}
>
<div class="category-bar-inner flex gap-2">
<a
href={homeUrl}
class="category-pill text-sm px-3 py-1.5 rounded-full shrink-0
transition-colors duration-150 ease-out flex items-center justify-center"
data-category-name=""
data-active={initialActive("").active ? "" : undefined}
aria-label={i18n(I18nKey.home)}
>
<Icon is:inline name="material-symbols:home" class="text-lg" />
</a>
<a
href={archiveUrl}
class="category-pill text-sm px-4 py-1.5 rounded-full whitespace-nowrap shrink-0
transition-colors duration-150 ease-out flex items-center justify-center"
data-category-name="__archive__"
data-active={initialActive("__archive__").active ? "" : undefined}
>
{i18n(I18nKey.archive)}
<span class="pill-count">{totalPosts}</span>
</a>
<div class="category-divider shrink-0"></div>
<div class="scroll-area relative">
<div class="scroll-fade scroll-fade-left" aria-hidden="true"></div>
<div class="category-scroll flex gap-2 overflow-x-auto">
{
categories.map((cat) => {
const active = initialActive(cat.name);
return (
<a
href={cat.url}
class="category-pill text-sm px-4 py-1.5 rounded-full whitespace-nowrap
transition-colors duration-150 ease-out flex items-center justify-center"
data-category-name={cat.name}
data-active={active.active ? "" : undefined}
data-soft-active={active.soft ? "" : undefined}
>
{cat.name}
<span class="pill-count">{cat.count}</span>
</a>
);
})
}
</div>
<div class="scroll-fade scroll-fade-right" aria-hidden="true"></div>
</div>
<div class="category-divider shrink-0 more-divider" aria-hidden="true"></div>
<a
href={url("/categories/")}
class="category-pill text-sm px-3 py-1.5 rounded-full shrink-0
transition-colors duration-150 ease-out flex items-center justify-center gap-1"
data-category-name="__categories__"
data-active={initialActive("__categories__").active ? "" : undefined}
aria-label={i18n(I18nKey.more)}
>
<span>{i18n(I18nKey.more)}</span>
<Icon is:inline name="fa7-solid:chevron-right" class="text-sm" />
</a>
</div>
</div>
<style>
.category-bar .category-pill {
border: none;
}
.category-bar {
margin-bottom: 1rem;
}
.category-divider {
width: 1px;
align-self: stretch;
background: var(--line-divider);
opacity: 0.5;
}
.more-divider {
opacity: 0;
transition: opacity 300ms ease-in-out;
}
.more-divider[data-visible] {
opacity: 0.5;
}
.scroll-area {
flex: 1;
min-width: 0;
position: relative;
}
.scroll-fade {
position: absolute;
top: 0;
bottom: 0;
width: 2.5rem;
pointer-events: none;
opacity: 0;
transition: opacity 300ms ease-in-out;
z-index: 1;
}
.scroll-fade[data-visible] {
opacity: 1;
}
.scroll-fade-left {
left: 0;
background: linear-gradient(to left, transparent, var(--card-bg));
}
.scroll-fade-right {
right: 0;
background: linear-gradient(to right, transparent, var(--card-bg));
}
:global(body.wallpaper-transparent) .scroll-fade {
display: none;
}
.category-scroll {
scrollbar-width: none;
-ms-overflow-style: none;
scroll-behavior: smooth;
}
.category-scroll::-webkit-scrollbar {
display: none;
}
</style>
<script>
let delayedCategoryBarScrollTimer: number | undefined;
function getCategoryBarState(bar: HTMLElement, currentUrl: URL) {
const pathname = currentUrl.pathname.replace(/\/$/, "");
const homePath = (bar.getAttribute("data-home-path") || "/").replace(/\/$/, "");
const archivePath = (bar.getAttribute("data-archive-path") || "/archive").replace(/\/$/, "");
const isHome = pathname === homePath || pathname === "" || pathname === "/";
const isArchive = pathname === archivePath;
const isCategories = pathname === "/categories";
return {
isHome,
isArchive,
isCategories,
activeCategory: currentUrl.searchParams.get("category") || "",
hasTag: currentUrl.searchParams.has("tag"),
hasUncategorized: currentUrl.searchParams.has("uncategorized"),
};
}
function setActiveCategory(bar: HTMLElement, currentUrl: URL) {
const { isHome, isArchive, isCategories, activeCategory, hasTag, hasUncategorized } =
getCategoryBarState(bar, currentUrl);
const postCategory = (bar.getAttribute("data-current-post-category") || "").trim();
const pills = bar.querySelectorAll<HTMLAnchorElement>(".category-pill");
pills.forEach((pill) => {
pill.removeAttribute("data-active");
pill.removeAttribute("data-soft-active");
});
if (isHome) {
bar.querySelector<HTMLAnchorElement>('.category-pill[data-category-name=""]')
?.setAttribute("data-active", "");
return;
}
if (isCategories) {
bar.querySelector<HTMLAnchorElement>('.category-pill[data-category-name="__categories__"]')
?.setAttribute("data-active", "");
return;
}
if (activeCategory) {
pills.forEach((pill) => {
if (pill.getAttribute("data-category-name") === activeCategory) {
pill.setAttribute("data-active", "");
}
});
return;
}
if (isArchive && !hasTag && !hasUncategorized) {
bar.querySelector<HTMLAnchorElement>('.category-pill[data-category-name="__archive__"]')
?.setAttribute("data-active", "");
return;
}
if (postCategory) {
pills.forEach((pill) => {
if (pill.getAttribute("data-category-name") === postCategory) {
pill.setAttribute("data-soft-active", "");
}
});
}
}
function scrollActiveCategoryIntoView(bar: HTMLElement, behavior: ScrollBehavior = "smooth") {
const activePill =
bar.querySelector<HTMLAnchorElement>('.category-pill[data-active]') ||
bar.querySelector<HTMLAnchorElement>('.category-pill[data-soft-active]');
const scroll = bar.querySelector<HTMLElement>(".category-scroll");
if (!activePill || !scroll) return;
const scrollLeft = activePill.offsetLeft - scroll.offsetLeft - (scroll.clientWidth - activePill.offsetWidth) / 2;
scroll.scrollTo({ left: Math.max(0, scrollLeft), behavior });
}
function shouldDeferCategoryScroll(bar: HTMLElement, currentUrl: URL) {
const { isHome } = getCategoryBarState(bar, currentUrl);
const isMobile = window.innerWidth < 1024;
const isBannerMode = document.body.classList.contains("enable-banner");
return isMobile && isBannerMode && !isHome;
}
function updateCategoryBar(
currentUrl = new URL(window.location.href),
options: { scrollBehavior?: ScrollBehavior; deferScroll?: boolean } = {},
) {
const bar = document.getElementById("category-bar");
if (!bar) return;
const swupContainer = document.getElementById("swup-container");
if (swupContainer) {
const currentPostCategory = swupContainer.getAttribute("data-current-post-category") || "";
bar.setAttribute("data-current-post-category", currentPostCategory);
}
setActiveCategory(bar, currentUrl);
const deferScroll = options.deferScroll ?? shouldDeferCategoryScroll(bar, currentUrl);
const scrollBehavior = options.scrollBehavior ?? (deferScroll ? "auto" : "smooth");
if (delayedCategoryBarScrollTimer) {
window.clearTimeout(delayedCategoryBarScrollTimer);
delayedCategoryBarScrollTimer = undefined;
}
if (deferScroll) {
// 等主内容上移完成后再定位分类,避免出现“先横向滚动后上移”的卡顿观感。
delayedCategoryBarScrollTimer = window.setTimeout(() => {
requestAnimationFrame(() => {
requestAnimationFrame(() => {
scrollActiveCategoryIntoView(bar, scrollBehavior);
updateScrollHint();
});
});
}, 220);
return;
}
scrollActiveCategoryIntoView(bar, scrollBehavior);
updateScrollHint();
}
function initCategoryBarInteractions() {
const bar = document.getElementById("category-bar");
if (!bar || bar.dataset.clickBound === "true") return;
bar.dataset.clickBound = "true";
bar.addEventListener("click", (event) => {
if (!(event.target instanceof Element)) return;
const pill = event.target.closest<HTMLAnchorElement>(".category-pill");
if (!pill) return;
if (
event.defaultPrevented ||
event.button !== 0 ||
event.metaKey ||
event.ctrlKey ||
event.shiftKey ||
event.altKey
) {
return;
}
if (pill.target && pill.target !== "_self") return;
const targetUrl = new URL(pill.href, window.location.href);
if (targetUrl.origin !== window.location.origin) return;
setActiveCategory(bar, targetUrl);
scrollActiveCategoryIntoView(bar, "auto");
});
}
function initScrollFeatures() {
const bar = document.getElementById("category-bar");
if (!bar) return;
const scroll = bar.querySelector<HTMLElement>(".category-scroll");
if (!scroll) return;
if (scroll.dataset.featuresBound === "true") {
updateScrollHint();
return;
}
scroll.dataset.featuresBound = "true";
// 鼠标滚轮横向滚动
scroll.addEventListener("wheel", (e) => {
if (scroll.scrollWidth <= scroll.clientWidth) return;
e.preventDefault();
scroll.scrollLeft += e.deltaY;
}, { passive: false });
// 监听滚动更新提示图标
scroll.addEventListener("scroll", updateScrollHint);
window.addEventListener("resize", updateScrollHint);
updateScrollHint();
}
function updateScrollHint() {
const bar = document.getElementById("category-bar");
if (!bar) return;
const scroll = bar.querySelector<HTMLElement>(".category-scroll");
const fadeLeft = bar.querySelector<HTMLElement>(".scroll-fade-left");
const fadeRight = bar.querySelector<HTMLElement>(".scroll-fade-right");
if (!scroll || !fadeLeft || !fadeRight) return;
const hasOverflow = scroll.scrollWidth > scroll.clientWidth + 1;
const atStart = scroll.scrollLeft <= 1;
const atEnd = scroll.scrollLeft + scroll.clientWidth >= scroll.scrollWidth - 1;
if (hasOverflow && !atStart) {
fadeLeft.setAttribute("data-visible", "");
} else {
fadeLeft.removeAttribute("data-visible");
}
if (hasOverflow && !atEnd) {
fadeRight.setAttribute("data-visible", "");
} else {
fadeRight.removeAttribute("data-visible");
}
// 分类溢出时显示"更多"按钮前的分割线
const moreDivider = bar.querySelector<HTMLElement>(".more-divider");
if (moreDivider) {
if (hasOverflow) {
moreDivider.setAttribute("data-visible", "");
} else {
moreDivider.removeAttribute("data-visible");
}
}
}
updateCategoryBar();
initCategoryBarInteractions();
initScrollFeatures();
document.addEventListener("astro:page-load", () => {
updateCategoryBar();
initScrollFeatures();
});
document.addEventListener("swup:contentReplaced", () => {
updateCategoryBar();
// 某些 swup 生命周期下 URL/DOM 状态同步稍晚,下一帧再校正一次避免状态残留
requestAnimationFrame(() => {
updateCategoryBar();
});
});
// 在 Swup 导航时提前更新状态,避免切换期间激活态闪烁
function setupSwupEarlyUpdate() {
if (!window.swup?.hooks) return;
window.swup.hooks.on("visit:start", (visit: any) => {
const bar = document.getElementById("category-bar");
if (!bar) return;
const targetUrl = new URL(visit.to.url, window.location.href);
setActiveCategory(bar, targetUrl);
});
}
if (window.swup?.hooks) {
setupSwupEarlyUpdate();
} else {
document.addEventListener("swup:enable", setupSwupEarlyUpdate);
}
</script>
+11
View File
@@ -0,0 +1,11 @@
---
import { backgroundWallpaper, siteConfig } from "@/config";
---
<!-- 全局配置载体 -->
<div
id="config-carrier"
data-hue={siteConfig.themeColor.hue}
data-wallpaper-mode={backgroundWallpaper.mode}
>
</div>
+187
View File
@@ -0,0 +1,187 @@
---
import { Icon } from "astro-icon/components";
import DropdownItem from "@/components/common/DropdownItem.astro";
import DropdownPanel from "@/components/common/DropdownPanel.astro";
import type { NavBarLink } from "@/types/config";
import { url } from "@/utils/url-utils";
interface Props {
link: NavBarLink;
class?: string;
}
const { link, class: className } = Astro.props;
// 检查 link 是否存在
if (!link) {
return null;
}
const processedLink = link;
const hasChildren = processedLink.children && processedLink.children.length > 0;
---
<div class:list={["dropdown-container", className]} data-dropdown>
{hasChildren ? (
<button
class="btn-plain scale-animation rounded-lg h-10 font-bold px-4 pr-8 active:scale-95 dropdown-trigger relative"
aria-expanded="false"
aria-haspopup="true"
data-dropdown-trigger
>
<div class="flex items-center gap-1.5">
{processedLink.icon && <Icon is:inline name={processedLink.icon} class="text-[1.1rem] mr-1.5 navbar-icon" />}
{processedLink.name}
</div>
<Icon is:inline name="material-symbols:keyboard-arrow-down-rounded" class="text-[1.2rem] transition-transform duration-200 dropdown-arrow absolute right-2.5 top-1/2 -translate-y-1/2" />
</button>
<div class="dropdown-menu" data-dropdown-menu>
<DropdownPanel class="dropdown-content">
{processedLink.children?.map((child, index) => (
<DropdownItem
href={child.external ? child.url : url(child.url)}
target={child.external ? "_blank" : undefined}
isLast={index === (processedLink.children?.length || 0) - 1}
class="dropdown-item h-10"
>
{child.icon && <Icon is:inline name={child.icon} class="text-[1.25rem] mr-3 navbar-icon" />}
<span>{child.name}</span>
{child.external && (
<Icon is:inline name="fa7-solid:arrow-up-right-from-square" class="text-[0.75rem] text-black/25 dark:text-white/25 ml-auto" />
)}
</DropdownItem>
))}
</DropdownPanel>
</div>
) : (
<a
aria-label={processedLink.name}
href={processedLink.external ? processedLink.url : url(processedLink.url)}
target={processedLink.external ? "_blank" : null}
class="btn-plain scale-animation rounded-lg h-10 font-bold px-4 active:scale-95"
>
<div class="flex items-center gap-1.5">
{processedLink.icon && <Icon is:inline name={processedLink.icon} class="text-[1.1rem] mr-1.5 navbar-icon" />}
{processedLink.name}
{processedLink.external && <Icon is:inline name="fa7-solid:arrow-up-right-from-square" class="text-[0.875rem] transition -translate-y-px ml-1 text-black/20 dark:text-white/20" />}
</div>
</a>
)}
</div>
<style>
@reference "../../styles/main.css";
.dropdown-container {
@apply relative;
}
.dropdown-menu {
@apply absolute top-full left-0 pt-2 opacity-0 invisible pointer-events-none transition-all duration-200 ease-out transform translate-y-[-8px] z-50;
}
.dropdown-container:hover .dropdown-menu,
.dropdown-container:focus-within .dropdown-menu {
@apply opacity-100 visible pointer-events-auto translate-y-0;
}
.dropdown-container:hover .dropdown-arrow,
.dropdown-container:focus-within .dropdown-arrow {
@apply rotate-180;
}
.dropdown-content {
@apply min-w-[12rem];
}
/* 移动端隐藏下拉菜单 */
@media (max-width: 768px) {
.dropdown-container {
@apply hidden;
}
}
</style>
<script>
// 键盘导航支持
document.addEventListener('DOMContentLoaded', function() {
const dropdowns = document.querySelectorAll('[data-dropdown]');
dropdowns.forEach(dropdown => {
const trigger = dropdown.querySelector('[data-dropdown-trigger]') as HTMLElement | null;
const menu = dropdown.querySelector('[data-dropdown-menu]');
const items = dropdown.querySelectorAll('.dropdown-item') as NodeListOf<HTMLElement>;
if (!trigger || !menu) return;
// 键盘事件处理
trigger.addEventListener('keydown', function(e: KeyboardEvent) {
if (e.key === 'Enter' || e.key === ' ') {
e.preventDefault();
toggleDropdown(dropdown, trigger, menu);
} else if (e.key === 'ArrowDown') {
e.preventDefault();
openDropdown(dropdown, trigger, menu);
if (items.length > 0) {
items[0].focus();
}
} else if (e.key === 'Escape') {
closeDropdown(dropdown, trigger, menu);
}
});
// 菜单项键盘导航
items.forEach((item, index) => {
item.addEventListener('keydown', function(e: KeyboardEvent) {
if (e.key === 'ArrowDown') {
e.preventDefault();
const nextIndex = (index + 1) % items.length;
items[nextIndex].focus();
} else if (e.key === 'ArrowUp') {
e.preventDefault();
const prevIndex = (index - 1 + items.length) % items.length;
items[prevIndex].focus();
} else if (e.key === 'Escape') {
closeDropdown(dropdown, trigger, menu);
trigger.focus();
}
});
});
});
// 点击外部关闭下拉菜单
document.addEventListener('click', function(e) {
dropdowns.forEach(dropdown => {
if (!dropdown.contains(e.target as Node)) {
const trigger = dropdown.querySelector('[data-dropdown-trigger]');
const menu = dropdown.querySelector('[data-dropdown-menu]');
if (trigger && menu) {
closeDropdown(dropdown, trigger, menu);
}
}
});
});
});
function toggleDropdown(_dropdown: Element, trigger: Element, menu: Element) {
const isOpen = trigger.getAttribute('aria-expanded') === 'true';
if (isOpen) {
closeDropdown(_dropdown, trigger, menu);
} else {
openDropdown(_dropdown, trigger, menu);
}
}
function openDropdown(_dropdown: Element, trigger: Element, menu: Element) {
trigger.setAttribute('aria-expanded', 'true');
menu.classList.remove('opacity-0', 'invisible', 'pointer-events-none', 'translate-y-[-8px]');
menu.classList.add('opacity-100', 'visible', 'pointer-events-auto', 'translate-y-0');
}
function closeDropdown(_dropdown: Element, trigger: Element, menu: Element) {
trigger.setAttribute('aria-expanded', 'false');
menu.classList.add('opacity-0', 'invisible', 'pointer-events-none', 'translate-y-[-8px]');
menu.classList.remove('opacity-100', 'visible', 'pointer-events-auto', 'translate-y-0');
}
</script>
+80
View File
@@ -0,0 +1,80 @@
---
import fs from "node:fs";
import path from "node:path";
import { footerConfig, profileConfig } from "@/config";
import { url } from "@/utils/url-utils";
const currentYear = new Date().getFullYear();
// 读取FooterConfig.html文件内容
let customFooterHtml = "";
if (footerConfig.enable) {
try {
const footerConfigPath = path.join(
process.cwd(),
"src",
"config",
"FooterConfig.html",
);
customFooterHtml = fs.readFileSync(footerConfigPath, "utf-8");
// 移除HTML注释
customFooterHtml = customFooterHtml.replace(/<!--[\s\S]*?-->/g, "").trim();
} catch (error) {
console.warn(
"FooterConfig.html文件读取失败:",
error instanceof Error ? error.message : String(error),
);
}
}
---
<div
class="transition border-t border-black/10 dark:border-white/15 my-10 border-dashed mx-32"
>
</div>
<div
class="transition border-dashed border-[oklch(85%_0.01_var(--hue))] dark:border-white/15 rounded-2xl mb-12 flex flex-col items-center justify-center px-6"
>
<div class="transition text-50 text-sm text-center wrap">
<div class="mb-2">
{customFooterHtml && <div set:html={customFooterHtml} />}
</div>
<div class="m-0.5 flex gap-2 justify-center flex-wrap">
&copy; <span id="copyright-year">{currentYear}</span>
{profileConfig.name}. All Rights Reserved.
<span aria-hidden="true">/</span>
<a
class="transition link text-(--primary) font-medium"
target="_blank"
href={url("rss.xml")}>RSS</a
>
<span aria-hidden="true">/</span>
<a
class="transition link text-(--primary) font-medium"
target="_blank"
href={url("sitemap-index.xml")}>Sitemap</a
>
</div>
<div class="m-0.5 flex gap-2 justify-center flex-wrap">
<span>Powered by</span>
<a
class="transition link text-(--primary) font-medium"
target="_blank"
href="https://astro.build">Astro</a
>
<span aria-hidden="true">&</span>
<a
class="transition link text-(--primary) font-medium"
target="_blank"
href="https://github.com/CuteLeaf/Firefly">Firefly</a
>
</div>
<!--
注意:请勿随意修改或删除 "Powered by Astro & Firefly" 部分,这是对开源项目的尊重和支持。
如果您需要在底部增加内容,请在src/config/footerConfig.ts中修改enable属性为true,然后编辑src/config/FooterConfig.html文件。
您可以随意在src/config/FooterConfig.html中随意添加自定义内容,不需要修改Footer.astro文件。
-->
</div>
</div>
+121
View File
@@ -0,0 +1,121 @@
---
import { Icon } from "astro-icon/components";
import type { NavBarLink } from "@/types/config";
import { url } from "@/utils/url-utils";
interface Props {
links: NavBarLink[];
}
const processedLinks = Astro.props.links;
---
<div id="nav-menu-panel" class:list={["float-panel float-panel-closed transition-all fixed right-4 px-2 py-2 max-h-[80vh] overflow-y-auto"]}>
{processedLinks.map((link) => (
<div class="mobile-menu-item">
{link.children && link.children.length > 0 ? (
/* 有子菜单的项目 */
<div class="mobile-dropdown" data-mobile-dropdown>
<button
class="group flex justify-between items-center py-2 pl-3 pr-1 rounded-lg gap-8 w-full text-left
hover:bg-(--btn-plain-bg-hover) active:bg-(--btn-plain-bg-active) transition"
data-mobile-dropdown-trigger
aria-expanded="false"
>
<div class="flex items-center transition text-black/75 dark:text-white/75 font-bold group-hover:text-(--primary) group-active:text-(--primary)">
{link.icon && <Icon is:inline name={link.icon} class="text-[1.1rem] mr-2" />}
{link.name}
</div>
<Icon is:inline name="material-symbols:keyboard-arrow-down-rounded"
class="transition text-[1.25rem] text-(--primary) mobile-dropdown-arrow duration-200"
/>
</button>
<div class="mobile-submenu" data-mobile-submenu>
{link.children.map((child) => (
<a href={child.external ? child.url : url(child.url)}
class="group flex justify-between items-center py-2 pl-6 pr-1 rounded-lg gap-8
hover:bg-(--btn-plain-bg-hover) active:bg-(--btn-plain-bg-active) transition"
target={child.external ? "_blank" : null}
>
<div class="flex items-center transition text-black/60 dark:text-white/60 font-medium group-hover:text-(--primary) group-active:text-(--primary)">
{child.icon && <Icon is:inline name={child.icon} class="text-[1.1rem] mr-2" />}
{child.name}
</div>
{child.external && <Icon is:inline name="fa7-solid:arrow-up-right-from-square"
class="transition text-[0.75rem] text-black/25 dark:text-white/25 -translate-x-1"
/>}
</a>
))}
</div>
</div>
) : (
/* 普通链接项目 */
<a href={link.external ? link.url : url(link.url)} class="group flex justify-between items-center py-2 pl-3 pr-1 rounded-lg gap-8
hover:bg-(--btn-plain-bg-hover) active:bg-(--btn-plain-bg-active) transition
"
target={link.external ? "_blank" : null}
>
<div class="flex items-center transition text-black/75 dark:text-white/75 font-bold group-hover:text-(--primary) group-active:text-(--primary)">
{link.icon && <Icon is:inline name={link.icon} class="text-[1.1rem] mr-2" />}
{link.name}
</div>
{!link.external && <Icon is:inline name="material-symbols:chevron-right-rounded"
class="transition text-[1.25rem] text-(--primary)"
/>}
{link.external && <Icon is:inline name="fa7-solid:arrow-up-right-from-square"
class="transition text-[0.75rem] text-black/25 dark:text-white/25 -translate-x-1"
/>}
</a>
)}
</div>
))}
</div>
<style>
@reference "../../styles/main.css";
.mobile-submenu {
@apply max-h-0 overflow-hidden transition-all duration-300 ease-in-out;
}
.mobile-dropdown[data-expanded="true"] .mobile-submenu {
@apply max-h-96;
}
.mobile-dropdown[data-expanded="true"] .mobile-dropdown-arrow {
@apply rotate-180;
}
</style>
<script>
document.addEventListener('DOMContentLoaded', function() {
const mobileDropdowns = document.querySelectorAll('[data-mobile-dropdown]');
mobileDropdowns.forEach(dropdown => {
const trigger = dropdown.querySelector('[data-mobile-dropdown-trigger]');
const submenu = dropdown.querySelector('[data-mobile-submenu]');
if (!trigger || !submenu) return;
trigger.addEventListener('click', function(e) {
e.preventDefault();
const isExpanded = dropdown.getAttribute('data-expanded') === 'true';
// 关闭其他打开的下拉菜单
mobileDropdowns.forEach(otherDropdown => {
if (otherDropdown !== dropdown) {
otherDropdown.setAttribute('data-expanded', 'false');
const otherTrigger = otherDropdown.querySelector('[data-mobile-dropdown-trigger]');
if (otherTrigger) {
otherTrigger.setAttribute('aria-expanded', 'false');
}
}
});
// 切换当前下拉菜单
const newState = !isExpanded;
dropdown.setAttribute('data-expanded', newState.toString());
trigger.setAttribute('aria-expanded', newState.toString());
});
});
});
</script>
+405
View File
@@ -0,0 +1,405 @@
---
import { Picture } from "astro:assets";
import * as path from "node:path";
import type { ImageMetadata } from "astro";
import { Icon } from "astro-icon/components";
import DisplaySettings from "@/components/controls/DisplaySettingsIntegrated.svelte";
import LightDarkSwitch from "@/components/controls/LightDarkSwitch.svelte";
import Search from "@/components/controls/Search.svelte";
import MusicPlayer from "@/components/features/MusicPlayer.astro";
import { backgroundWallpaper, navBarConfig, siteConfig } from "@/config";
import { musicPlayerConfig } from "@/config/musicConfig";
import I18nKey from "@/i18n/i18nKey";
import { i18n } from "@/i18n/translation";
import type { NavBarLink } from "@/types/config";
import { getFallbackFormat, getImageFormats } from "@/utils/image-utils";
import { isHomePage } from "@/utils/layout-utils";
import { url } from "@/utils/url-utils";
import DropdownMenu from "./DropdownMenu.astro";
import NavMenuPanel from "./NavMenuPanel.astro";
const className = Astro.props.class;
// 获取导航栏透明模式配置
const navbarTransparentMode =
backgroundWallpaper.mode === "banner"
? backgroundWallpaper.common?.navbar?.transparentMode || "semi"
: "semi";
// 获取导航栏毛玻璃效果配置
const navbarEnableBlur =
backgroundWallpaper.mode === "banner"
? (backgroundWallpaper.common?.navbar?.enableBlur ?? true)
: false;
// 获取导航栏模糊度
const navbarBlur =
backgroundWallpaper.mode === "banner"
? (backgroundWallpaper.common?.navbar?.blur ?? 20)
: 0;
// 获取导航栏标题,如果没有设置则使用 siteConfig.title
const navbarTitle = siteConfig.navbar.title || siteConfig.title;
// 获取导航栏宽度配置
const navbarWidthFull = siteConfig.navbar.widthFull ?? false;
const navbarMenuAlign = siteConfig.navbar.menuAlign ?? "center";
const isNavbarMenuCentered = navbarMenuAlign === "center";
// 检查是否为首页
const isHomePageCheck = isHomePage(Astro.url.pathname);
// 检查是否有任何显示设置可用
const showThemeColor = !siteConfig.themeColor.fixed;
const isWallpaperSwitchable = backgroundWallpaper.switchable ?? true;
const allowLayoutSwitch = siteConfig.postListLayout.allowSwitch;
const hasDisplaySettings =
showThemeColor || isWallpaperSwitchable || allowLayoutSwitch;
// 根据 siteConfig.pages 过滤导航栏链接
const pages = siteConfig.pages;
function isPageEnabled(link: NavBarLink): boolean {
if (!link.pageKey) return true;
return pages[link.pageKey as keyof typeof pages] !== false;
}
function filterLinks(link: NavBarLink): NavBarLink | null {
if (!link.children) {
return isPageEnabled(link) ? link : null;
}
const filteredChildren = link.children.filter(isPageEnabled);
if (filteredChildren.length === 0) return null;
if (filteredChildren.length === 1) return filteredChildren[0];
return { ...link, children: filteredChildren };
}
let links: NavBarLink[] = navBarConfig.links
.map(filterLinks)
.filter((link): link is NavBarLink => link !== null);
// 处理导航栏 Logo 图片
const logoValue = siteConfig.navbar.logo?.value || "";
const isLocalSrcLogo =
siteConfig.navbar.logo?.type === "image" &&
logoValue &&
!logoValue.startsWith("/") &&
!logoValue.startsWith("http");
let logoImg: ImageMetadata | null = null;
if (isLocalSrcLogo) {
const files = import.meta.glob<ImageMetadata>(
"../../**/*.{png,jpg,jpeg,webp,avif,gif,svg}",
{ import: "default" },
);
const normalizedPath = path
.normalize(path.join("../../", logoValue))
.replace(/\\/g, "/");
const file = files[normalizedPath];
if (file) {
logoImg = await file();
}
}
---
<div id="navbar" class="z-50" style={`--navbar-glass-blur: ${navbarBlur}px;`} data-transparent-mode={navbarTransparentMode} data-enable-blur={String(navbarEnableBlur)} data-is-home={isHomePageCheck} data-full-width={navbarWidthFull}>
<div class:list={[
className,
"overflow-visible! h-18 px-4"
]}>
<div class="mx-auto h-full w-full max-w-(--page-width) grid grid-cols-[auto_minmax(0,1fr)_auto] items-center">
<a href={url('/')} class="btn-plain scale-animation rounded-lg h-13 px-3 md:px-5 font-bold active:scale-95">
<div class:list={[
"flex flex-row items-center text-md",
siteConfig.navbar.followTheme ? "text-(--primary)" : "dark:text-white text-black"
]} style="font-family: var(--font-navbar-title, inherit)">
{siteConfig.navbar.logo?.type === "icon" ? (
<Icon is:inline name={siteConfig.navbar.logo.value || "material-symbols:home-pin-outline"} class="text-[1.75rem] mb-1 mr-2" />
) : siteConfig.navbar.logo?.type === "image" && logoImg ? (
<Picture
src={logoImg}
alt={siteConfig.navbar.logo.alt || siteConfig.title}
class="h-7 w-7 mb-1 mr-2 object-contain"
formats={getImageFormats()}
fallbackFormat={getFallbackFormat()}
widths={[28, 56]}
loading="eager"
fetchpriority="high"
/>
) : siteConfig.navbar.logo?.type === "image" ? (
<img src={url(siteConfig.navbar.logo.value)} alt={siteConfig.navbar.logo.alt || siteConfig.title} class="h-7 w-7 mb-1 mr-2 object-contain" fetchpriority="high" />
) : siteConfig.navbar.logo?.type === "url" ? (
<img src={siteConfig.navbar.logo.value} alt={siteConfig.navbar.logo.alt || siteConfig.title} class="h-7 w-7 mb-1 mr-2 object-contain" fetchpriority="high" />
) : (
<Icon is:inline name="material-symbols:home-pin-outline" class="text-[1.75rem] mb-1 mr-2" />
)}
{navbarTitle}
</div>
</a>
<div class:list={[
"hidden lg:flex items-center space-x-1 col-start-2",
isNavbarMenuCentered
? "justify-center"
: "justify-start pl-2"
]}>
{links.map((l) => {
return <DropdownMenu link={l} />;
})}
</div>
<div class="flex col-start-3 justify-self-end">
<!--<SearchPanel client:load>-->
<Search
client:load
/>
{musicPlayerConfig.showInNavbar && (
<button aria-label={i18n(I18nKey.music)} class="btn-plain scale-animation rounded-lg h-9 w-9 md:h-11 md:w-11 active:scale-90" id="music-player-switch">
<Icon is:inline name="material-symbols:music-note-rounded" class="text-[1.25rem]"></Icon>
</button>
)}
{backgroundWallpaper.playerEnable && backgroundWallpaper.mode !== "none" && (
<button
aria-label={i18n(I18nKey.videoPlay)}
class="btn-plain scale-animation rounded-lg h-9 w-9 md:h-11 md:w-11 active:scale-90"
id="bg-player-toggle"
data-i18n-play={i18n(I18nKey.videoPlay)}
data-i18n-pause={i18n(I18nKey.videoPause)}
>
<span class="bg-player-icon-play"><Icon is:inline name="material-symbols:play-arrow-rounded" class="text-[1.5rem]" /></span>
<span class="bg-player-icon-pause hidden"><Icon is:inline name="material-symbols:pause-rounded" class="text-[1.5rem]" /></span>
</button>
)}
{hasDisplaySettings && (
<button aria-label="Display Settings" class="btn-plain scale-animation rounded-lg h-9 w-9 md:h-11 md:w-11 active:scale-90" id="display-settings-switch">
<Icon is:inline name="material-symbols:palette-outline" class="text-[1.25rem]"></Icon>
</button>
)}
{/* @ts-ignore */}
<LightDarkSwitch client:load></LightDarkSwitch>
<button aria-label="Menu" name="Nav Menu" class="btn-plain scale-animation rounded-lg w-9 h-9 md:w-11 md:h-11 active:scale-90 lg:hidden!" id="nav-menu-switch">
<Icon is:inline name="material-symbols:menu-rounded" class="text-[1.25rem]"></Icon>
</button>
</div>
</div>
{musicPlayerConfig.showInNavbar && (
<div id="music-nav-panel" class="float-panel float-panel-closed absolute transition-all right-16 p-2 pt-4.5 w-80 z-50">
<MusicPlayer />
</div>
)}
<NavMenuPanel links={links}></NavMenuPanel>
<DisplaySettings client:load></DisplaySettings>
</div>
</div>
<script>
function loadButtonScript() {
let settingBtn = document.getElementById("display-settings-switch");
if (settingBtn) {
settingBtn.onclick = function () {
let settingPanel = document.getElementById("display-setting");
if (settingPanel) {
settingPanel.classList.toggle("float-panel-closed");
}
};
}
let menuBtn = document.getElementById("nav-menu-switch");
if (menuBtn) {
menuBtn.onclick = function () {
let menuPanel = document.getElementById("nav-menu-panel");
if (menuPanel) {
menuPanel.classList.toggle("float-panel-closed");
}
};
}
let musicBtn = document.getElementById("music-player-switch");
if (musicBtn) {
musicBtn.onclick = function () {
let musicPanel = document.getElementById("music-nav-panel");
if (musicPanel) {
musicPanel.classList.toggle("float-panel-closed");
}
};
}
// 背景视频播放器控制按钮
let bgPlayerBtn = document.getElementById("bg-player-toggle");
if (bgPlayerBtn) {
bgPlayerBtn.onclick = function () {
window.dispatchEvent(new CustomEvent("bg-player-toggle"));
};
function toggleBgPlayerIcon(playing: boolean) {
var playIcon = bgPlayerBtn!.querySelector(".bg-player-icon-play");
var pauseIcon = bgPlayerBtn!.querySelector(".bg-player-icon-pause");
if (playIcon && pauseIcon) {
playIcon.classList.toggle("hidden", playing);
pauseIcon.classList.toggle("hidden", !playing);
}
var i18nPlay = bgPlayerBtn!.getAttribute("data-i18n-play") ?? "";
var i18nPause = bgPlayerBtn!.getAttribute("data-i18n-pause") ?? "";
var label = playing ? i18nPause : i18nPlay;
bgPlayerBtn!.setAttribute("title", label);
bgPlayerBtn!.setAttribute("aria-label", label);
}
window.addEventListener("bg-player-state-change", function (e) {
var ce = e as CustomEvent;
var playing = ce.detail && ce.detail.playing;
toggleBgPlayerIcon(playing);
});
// 切换壁纸模式时隐藏/显示播放按钮
window.addEventListener("wallpaperModeChange", function (e) {
var ce = e as CustomEvent;
var mode = ce.detail && ce.detail.mode;
bgPlayerBtn!.style.display = mode === "none" ? "none" : "";
});
// Swup 导航时同步播放按钮状态(BackgroundPlayer 可能被重建,也可能持久存在)
function syncBgPlayerBtn() {
var playing = document.documentElement.hasAttribute("data-bg-video-playing");
toggleBgPlayerIcon(playing);
}
if (window.swup && window.swup.hooks) {
window.swup.hooks.on("content:replace", syncBgPlayerBtn);
} else {
document.addEventListener("swup:enable", function () {
window.swup.hooks.on("content:replace", syncBgPlayerBtn);
});
}
}
let themeSwitchBtn = document.getElementById("scheme-switch");
if (themeSwitchBtn) {
themeSwitchBtn.onclick = function () {
let themePanel = document.getElementById("theme-mode-panel");
if (themePanel) {
themePanel.classList.toggle("float-panel-closed");
}
};
}
document.addEventListener("click", function(event) {
const panels = ["display-setting", "nav-menu-panel", "music-nav-panel", "theme-mode-panel"];
const buttons = ["display-settings-switch", "nav-menu-switch", "music-player-switch", "scheme-switch"];
panels.forEach((id, index) => {
const panel = document.getElementById(id);
const button = document.getElementById(buttons[index]);
if (panel && button && !panel.classList.contains("float-panel-closed")) {
if (event.target instanceof Node && !panel.contains(event.target) && !button.contains(event.target)) {
panel.classList.add("float-panel-closed");
}
}
});
});
}
loadButtonScript();
// 为semifull模式添加滚动检测逻辑
function initSemifullScrollDetection() {
const navbar = document.getElementById('navbar');
if (!navbar) return;
const transparentMode = navbar.getAttribute('data-transparent-mode');
if (transparentMode !== 'semifull') return;
// 无论首页/非首页,semifull 都由滚动位置决定是否进入 scrolled 状态
// 先移除之前的滚动监听器,避免重复绑定
if (window.semifullScrollHandler) {
window.removeEventListener('scroll', window.semifullScrollHandler as () => void);
window.semifullScrollHandler = undefined;
}
// 初始状态不强制加 scrolled,保持透明;滚动后再切换
navbar.classList.remove('scrolled');
let ticking = false;
function updateNavbarState() {
if (document.documentElement.classList.contains('is-page-transitioning')) {
navbar!.classList.remove('scrolled');
ticking = false;
return;
}
const scrollTop = window.pageYOffset || document.documentElement.scrollTop;
const threshold = 50; // 滚动阈值,可以根据需要调整
// 使用批量DOM操作优化性能
if (scrollTop > threshold) {
navbar!.classList.add('scrolled');
} else {
navbar!.classList.remove('scrolled');
}
ticking = false;
}
function requestTick() {
if (!ticking) {
requestAnimationFrame(updateNavbarState);
ticking = true;
}
}
// 移除之前的滚动事件监听器(如果存在)
if (window.semifullScrollHandler) {
window.removeEventListener('scroll', window.semifullScrollHandler as () => void);
}
// 保存新的事件处理器引用
window.semifullScrollHandler = requestTick as unknown as (() => void);
// 监听滚动事件
window.addEventListener('scroll', requestTick, { passive: true });
// 初始化状态
updateNavbarState();
}
// 将函数暴露到全局对象,供页面切换时调用
window.initSemifullScrollDetection = initSemifullScrollDetection;
// 页面加载完成后初始化滚动检测
if (document.readyState === 'loading') {
document.addEventListener('DOMContentLoaded', initSemifullScrollDetection);
} else {
initSemifullScrollDetection();
}
</script>
{
import.meta.env.PROD && (
<script is:inline data-swup-ignore-script define:vars={{ scriptUrl: url('/pagefind/pagefind.js') }}>
{/* 你的 loadPagefind 函数的完整内容放在这里 */}
async function loadPagefind() {
try {
const response = await fetch(scriptUrl, { method: 'HEAD' });
if (!response.ok) {
throw new Error(`Pagefind script not found: ${response.status}`);
}
const pagefind = await import(scriptUrl);
await pagefind.options({
excerptLength: 20
});
window.pagefind = pagefind;
document.dispatchEvent(new CustomEvent('pagefindready'));
console.log('Pagefind loaded and initialized successfully, event dispatched.');
} catch (error) {
console.error('Failed to load Pagefind:', error);
window.pagefind = {
search: () => Promise.resolve({ results: [] }),
options: () => Promise.resolve(),
};
document.dispatchEvent(new CustomEvent('pagefindloaderror'));
console.log('Pagefind load error, event dispatched.');
}
}
if (document.readyState === 'loading') {
document.addEventListener('DOMContentLoaded', loadPagefind);
} else {
loadPagefind();
}
</script>
)
}
+409
View File
@@ -0,0 +1,409 @@
---
import type { CollectionEntry } from "astro:content";
import { render } from "astro:content";
import { Icon } from "astro-icon/components";
import CoverImage from "@/components/common/CoverImage.astro";
import PostMetadata from "@/components/layout/PostMeta.astro";
import PostStats from "@/components/layout/PostStats.astro";
import { siteConfig } from "@/config";
import { getApiUrlList, processCoverImageSync } from "@/utils/image-utils";
import { getFileDirFromPath, getTagUrl } from "@/utils/url-utils";
interface Props {
class?: string;
entry: CollectionEntry<"posts">;
title: string;
url: string;
published: Date;
updated?: Date;
tags: string[];
category: string | null;
image: string;
description: string;
draft: boolean;
pinned?: boolean;
password?: boolean;
style: string;
loading?: "lazy" | "eager";
}
const {
entry,
title,
url,
published,
tags,
category,
image,
description,
pinned,
password,
style,
loading = "lazy",
} = Astro.props;
const className = Astro.props.class;
// 处理随机图:如果image为"api",则从配置的API获取随机图
const processedImage = processCoverImageSync(image, entry.id);
const apiUrls = getApiUrlList(image, entry.id);
const hasCover =
processedImage !== undefined &&
processedImage !== null &&
processedImage !== "";
const coverWidth = "30%";
const descriptionLines = Math.max(
0,
Math.trunc(siteConfig.postListLayout.descriptionLines ?? 2),
);
// PostMeta 配置
const metaConfig = siteConfig.postListLayout.meta ?? {};
const showCategory = metaConfig.showCategory ?? true;
const metaShowTags = metaConfig.showTags ?? true;
const metaTagCount =
metaConfig.tagCount !== undefined
? Math.max(0, Math.trunc(metaConfig.tagCount))
: 1;
const metaShowWords = metaConfig.showWords ?? true;
const metaShowReadingTime = metaConfig.showReadingTime ?? true;
const metaShowPublished = metaConfig.showPublished ?? true;
// PostStats 配置
const statsConfig = siteConfig.postListLayout.stats ?? {};
const statsShowPublished = statsConfig.showPublished ?? true;
const statsShowWords = statsConfig.showWords ?? true;
const statsShowReadingTime = statsConfig.showReadingTime ?? true;
// 标签显示位置
const tagsPosition = siteConfig.postListLayout.tagsPosition ?? "meta";
const showTagsInMeta = metaShowTags && tagsPosition === "meta";
const showTagsAtBottom = metaShowTags && tagsPosition === "bottom";
const descriptionClampLines = String(descriptionLines);
const shouldClampDescription = descriptionLines > 0;
const { remarkPluginFrontmatter } = await render(entry);
const descriptionText = description || remarkPluginFrontmatter.excerpt || "";
const words = remarkPluginFrontmatter.words;
const minutes = remarkPluginFrontmatter.minutes;
---
<div
class:list={[
"post-card-wrapper",
hasCover ? "has-cover" : "no-cover",
pinned ? "pinned" : "",
"card-base flex flex-col-reverse w-full rounded-(--radius-large) overflow-hidden relative",
className,
]}
style={style}
>
<!-- pinned icon -->
<div
class:list={[
"post-card-content",
"pl-4 md:pl-9 pr-4 md:pr-2 pt-4 md:pt-7 pb-4 md:pb-7 relative flex flex-col h-full",
{
"w-full md:w-[calc(100%-52px-12px)]": !hasCover,
"w-full md:w-[calc(100%-var(--coverWidth)-1.5rem)]": hasCover,
},
]}
>
<a
href={url}
class="post-card-title transition group w-full block font-bold mb-3 text-3xl text-90
hover:text-(--primary) dark:hover:text-(--primary)
active:text-(--title-active) dark:active:text-(--title-active)
before:w-1 before:h-5 before:rounded-md before:bg-(--primary)
before:absolute before:top-[35px] before:left-[18px] before:hidden md:before:block"
>
{title}
{
password && (
<Icon
is:inline
name="material-symbols:lock-outline"
class="inline text-2xl align-middle -translate-y-px"
/>
)
}
</a>
<!-- metadata -->
<PostMetadata
published={published}
tags={tags}
showPublished={metaShowPublished}
showCategory={showCategory}
showTags={showTagsInMeta}
maxTags={metaTagCount > 0 ? metaTagCount : undefined}
showNoTags={true}
hideUpdateDate={true}
category={category || undefined}
pinned={pinned}
password={password}
words={words}
minutes={minutes}
showWords={metaShowWords}
showReadingTime={metaShowReadingTime}
className="mb-4 post-meta card-header-meta"
/>
<!-- description -->
<div
class:list={[
"transition text-75 md:pr-4 description grow",
{ "description-clamped": shouldClampDescription },
]}
title={descriptionText}
>
{descriptionText}
</div>
<!-- bottom tags(与 stats 二选一) -->
{showTagsAtBottom && tags && tags.length > 0 && (
<div class="post-card-bottom-tags flex flex-wrap items-center gap-1.5 mt-auto pt-3">
{(metaTagCount > 0 ? tags.slice(0, metaTagCount) : tags).map((tag) => (
<a
href={getTagUrl(tag)}
aria-label={`View all posts with the ${tag.trim()} tag`}
class="transition text-xs font-medium px-2.5 py-1 rounded-full
bg-black/5 dark:bg-white/10 text-neutral-500 dark:text-neutral-400
hover:bg-(--btn-regular-bg) hover:text-(--btn-content)"
>
#{tag.trim()}
</a>
))}
</div>
)}
<!-- stats(与底部标签二选一) -->
{!showTagsAtBottom && (
<PostStats
published={published}
words={words}
minutes={minutes}
showPublished={statsShowPublished}
showWords={statsShowWords}
showReadingTime={statsShowReadingTime}
showIcons={siteConfig.postListLayout.showStatsIcons}
className="stats mt-auto pt-3 text-black/30 dark:text-white/30 gap-x-2"
/>
)}
</div>
{
hasCover && (
<a
href={url}
aria-label={title}
class:list={[
"post-card-image",
"group",
"w-full md:w-(--coverWidth)",
"aspect-2/1 md:aspect-auto",
"relative md:absolute md:top-4 md:bottom-4 md:right-4",
"rounded-(--radius-large) md:rounded-xl overflow-hidden",
]}
>
<div class="absolute pointer-events-none z-10 w-full h-full group-hover:bg-black/30 group-active:bg-black/50 transition" />
<div class="absolute pointer-events-none z-20 w-full h-full flex items-center justify-center ">
<Icon
is:inline
name="material-symbols:chevron-right-rounded"
class="transition opacity-0 group-hover:opacity-100 scale-50 group-hover:scale-100 text-white text-5xl"
/>
</div>
<CoverImage
src={processedImage}
basePath={getFileDirFromPath(entry.filePath || "")}
alt="Cover Image of the Post"
class="w-full h-full transition-transform duration-300 group-hover:scale-110 group-active:scale-115"
preview={true}
loading={loading}
apiUrls={apiUrls}
/>
</a>
)
}
{
!hasCover && (
<a
href={url}
aria-label={title}
class:list={[
"post-card-enter-btn",
"flex btn-regular w-13",
"absolute right-3 top-3 bottom-3 rounded-xl bg-(--enter-btn-bg)",
"hover:bg-(--enter-btn-bg-hover) active:bg-(--enter-btn-bg-active) active:scale-95",
]}
>
<Icon
is:inline
name="material-symbols:chevron-right-rounded"
class="transition text-(--primary) text-4xl mx-auto"
/>
</a>
)
}
</div>
<style define:vars={{ coverWidth, descriptionClampLines }}>
.description-clamped {
display: -webkit-box;
-webkit-box-orient: vertical;
overflow: hidden;
-webkit-line-clamp: var(--descriptionClampLines);
line-clamp: var(--descriptionClampLines);
}
/* === List Mode Mobile Styles === */
/* 移动端列表模式:封面在右侧,内容缩小 */
:global(.list-mode) .post-card-wrapper {
flex-direction: row !important;
}
:global(.list-mode) .has-cover .post-card-content {
width: calc(100% - 9rem - 0.75rem) !important;
padding: 0.75rem 0.5rem 0.75rem 0.75rem !important;
}
:global(.list-mode) .has-cover .post-card-image {
position: absolute !important;
top: 0.5rem !important;
bottom: 0.5rem !important;
right: 0.5rem !important;
width: 9rem !important;
aspect-ratio: auto !important;
border-radius: 0.75rem !important;
}
:global(.list-mode) .post-card-title {
font-size: 1.125rem !important;
line-height: 1.75rem !important;
margin-bottom: 0.5rem !important;
}
:global(.list-mode) .post-card-title::before {
display: none !important;
}
:global(.list-mode) .stats {
gap: 0.25rem !important;
}
:global(.list-mode) .no-cover .post-card-content {
width: calc(100% - 52px - 12px) !important;
}
:global(.list-mode) .post-card-enter-btn {
display: flex !important;
}
/* 移动端列表模式 - 隐藏tags,只在有空间时显示 */
:global(.list-mode) .stats a {
font-size: 0.65rem !important;
padding: 0.125rem 0.375rem !important;
height: 1.25rem !important;
}
/* === Desktop List Mode overrides === */
@media (min-width: 768px) {
:global(.list-mode) .post-card-wrapper {
flex-direction: row !important;
}
:global(.list-mode) .has-cover .post-card-content {
width: calc(100% - var(--coverWidth) - 1.5rem) !important;
padding: 1.75rem 0.5rem 1.75rem 2.25rem !important;
}
:global(.list-mode) .has-cover .post-card-image {
top: 1rem !important;
bottom: 1rem !important;
right: 1rem !important;
width: var(--coverWidth) !important;
border-radius: 0.75rem !important;
}
:global(.list-mode) .post-card-title {
font-size: 1.5rem !important;
line-height: 2rem !important;
margin-bottom: 0.75rem !important;
}
:global(.list-mode) .post-card-title::before {
display: block !important;
top: 2.25rem !important;
height: 1rem !important;
}
:global(.list-mode) .description {
font-size: inherit !important;
}
:global(.list-mode) .stats a {
font-size: 0.75rem !important;
padding: 0.25rem 0.5rem !important;
height: 1.5rem !important;
}
:global(.list-mode) .no-cover .post-card-content {
width: calc(100% - 52px - 12px) !important;
}
:global(.list-mode) .post-card-enter-btn {
display: flex !important;
}
}
/* === Grid Mode Styles === */
/* 网格模式:封面在顶部(移动端和桌面端一致) */
:global(.grid-mode) .post-card-wrapper {
flex-direction: column-reverse !important;
height: 100% !important;
justify-content: flex-end !important;
}
:global(.grid-mode) .post-card-content {
width: 100% !important;
height: auto !important;
flex-grow: 1 !important;
}
:global(.grid-mode) .post-card-image {
position: relative !important;
top: auto !important;
bottom: auto !important;
right: auto !important;
width: 100% !important;
margin: 0 !important;
border-radius: var(--radius-large) var(--radius-large) 0 0 !important;
max-height: none !important;
aspect-ratio: 2/1 !important;
}
:global(.grid-mode) .description {
flex-grow: 0 !important;
}
:global(.grid-mode) .stats {
margin-top: auto !important;
}
:global(.grid-mode) .has-cover .post-card-content {
padding-top: 0.8rem !important;
}
:global(.grid-mode) .has-cover .post-card-title::before {
top: 1.3rem !important;
}
:global(.grid-mode) .no-cover .post-card-content {
width: calc(100% - 52px - 12px) !important;
}
:global(.grid-mode) .post-card-enter-btn {
display: flex !important;
}
</style>
+277
View File
@@ -0,0 +1,277 @@
---
import { Icon } from "astro-icon/components";
import { commentConfig } from "@/config";
import I18nKey from "@/i18n/i18nKey";
import { i18n } from "@/i18n/translation";
import { formatDateToYYYYMMDD } from "@/utils/date-utils";
import { getCategoryUrl, getTagUrl } from "@/utils/url-utils";
export interface Props {
published: Date;
updated?: Date;
category?: string;
tags?: string[];
hideUpdateDate?: boolean;
hideTagsForMobile?: boolean;
isHome?: boolean;
className?: string;
id?: string;
showPublished?: boolean;
showCategory?: boolean;
showTags?: boolean;
maxTags?: number;
showNoTags?: boolean;
customPath?: string;
pinned?: boolean;
password?: boolean;
words?: number;
minutes?: number;
showWords?: boolean;
showReadingTime?: boolean;
}
const {
published,
updated,
category,
tags,
hideUpdateDate,
hideTagsForMobile,
isHome,
className = "",
id,
showPublished = true,
showCategory = true,
showTags = true,
maxTags,
showNoTags = true,
customPath,
pinned,
words,
minutes,
showWords = false,
showReadingTime = false,
} = Astro.props;
const path = customPath || (id ? `/posts/${id}` : "");
const visibleTags =
typeof maxTags === "number" ? tags?.slice(0, maxTags) : tags;
---
<div
class:list={[
"post-meta-root flex flex-wrap text-neutral-500 dark:text-neutral-400 items-center gap-4 gap-x-4 gap-y-2",
className,
]}
>
{
pinned && (
<div class="pinned-btn flex items-center gap-1 bg-(--btn-regular-bg) text-(--btn-content) rounded-md px-2 py-1.5 font-bold">
<Icon is:inline name="material-symbols:pinboard" class="text-xl" />
<span class="text-sm">{i18n(I18nKey.pinned)}</span>
</div>
)
}
{
showPublished && (
<div class="flex items-center">
<div class="meta-icon">
<Icon
is:inline
name="material-symbols:calendar-today-outline-rounded"
class="text-xl"
/>
</div>
<span class="text-50 text-sm font-medium">
{formatDateToYYYYMMDD(published)}
</span>
</div>
)
}
{
showPublished &&
!hideUpdateDate &&
updated &&
updated.getTime() !== published.getTime() && (
<div class="flex items-center">
<div class="meta-icon">
<Icon
is:inline
name="material-symbols:edit-calendar-outline-rounded"
class="text-xl"
/>
</div>
<span class="text-50 text-sm font-medium">
{formatDateToYYYYMMDD(updated)}
</span>
</div>
)
}
{
showCategory && (
<div class="flex items-center">
<div class="meta-icon">
<Icon is:inline name="material-symbols:book-2-outline-rounded" class="text-xl" />
</div>
<div class="flex flex-row flex-nowrap items-center">
<a
href={getCategoryUrl(category || "")}
aria-label={`View all posts in the ${category} category`}
class="link-lg transition text-50 text-sm font-medium
hover:text-(--primary) dark:hover:text-(--primary) whitespace-nowrap"
>
{category || i18n(I18nKey.uncategorized)}
</a>
</div>
</div>
)
}
{
showTags && (
<div
class:list={[
"items-center",
{ flex: !hideTagsForMobile, "hidden md:flex": hideTagsForMobile },
]}
>
<div class="meta-icon">
<Icon is:inline name="material-symbols:tag-rounded" class="text-xl" />
</div>
<div class="flex flex-row flex-nowrap items-center">
{visibleTags &&
visibleTags.length > 0 &&
visibleTags.map((tag, i) => (
<>
<div
class:list={[
{ hidden: i === 0 },
"mx-1.5 text-(--meta-divider) text-sm",
]}
>
/
</div>
<a
href={getTagUrl(tag)}
aria-label={`View all posts with the ${tag.trim()} tag`}
class="link-lg transition text-50 text-sm font-medium
hover:text-(--primary) dark:hover:text-(--primary) whitespace-nowrap"
>
{tag.trim()}
</a>
</>
))}
{showNoTags && !(visibleTags && visibleTags.length > 0) && (
<div class="transition text-50 text-sm font-medium">
{i18n(I18nKey.noTags)}
</div>
)}
</div>
</div>
)
}
{
!isHome &&
commentConfig.type === "twikoo" &&
commentConfig.twikoo?.visitorCount &&
id && (
<div class="flex items-center">
<div class="meta-icon">
<Icon
is:inline
name="material-symbols:visibility-outline-rounded"
class="text-xl"
/>
</div>
<span class="text-50 text-sm font-medium mr-1">
{i18n(I18nKey.pageViews)}
</span>
<span class="text-50 text-sm font-medium" id="twikoo_visitors">
{i18n(I18nKey.pageViewsLoading)}
</span>
</div>
)
}
{
!isHome &&
commentConfig.type === "waline" &&
commentConfig.waline?.visitorCount &&
id && (
<div class="flex items-center">
<div class="meta-icon">
<Icon
is:inline
name="material-symbols:visibility-outline-rounded"
class="text-xl"
/>
</div>
<span class="text-50 text-sm font-medium mr-1">
{i18n(I18nKey.pageViews)}
</span>
<span
class="text-50 text-sm font-medium waline-pageview-count"
data-path={path}
>
{i18n(I18nKey.pageViewsLoading)}
</span>
</div>
)
}
{
!isHome &&
commentConfig.type === "artalk" &&
commentConfig.artalk?.visitorCount &&
id && (
<div class="flex items-center">
<div class="meta-icon">
<Icon
is:inline
name="material-symbols:visibility-outline-rounded"
class="text-xl"
/>
</div>
<span class="text-50 text-sm font-medium mr-1">
{i18n(I18nKey.pageViews)}
</span>
<span
class="text-50 text-sm font-medium artalk-pv-count"
data-path={path}
>
{i18n(I18nKey.pageViewsLoading)}
</span>
</div>
)
}
{
showWords && typeof words === "number" && (
<div class="flex items-center">
<div class="meta-icon">
<Icon is:inline name="material-symbols:notes-rounded" class="text-xl" />
</div>
<span class="text-50 text-sm font-medium">
{words} {i18n(words === 1 ? I18nKey.wordCount : I18nKey.wordsCount)}
</span>
</div>
)
}
{
showReadingTime && typeof minutes === "number" && (
<div class="flex items-center">
<div class="meta-icon">
<Icon is:inline name="material-symbols:schedule-outline-rounded" class="text-xl" />
</div>
<span class="text-50 text-sm font-medium">
{minutes} {i18n(minutes === 1 ? I18nKey.minuteCount : I18nKey.minutesCount)}
</span>
</div>
)
}
</div>
+464
View File
@@ -0,0 +1,464 @@
---
import type { CollectionEntry } from "astro:content";
import { getPostUrlBySlug } from "@utils/url-utils";
import PostCard from "@/components/layout/PostCard.astro";
import { siteConfig } from "@/config";
const { page } = Astro.props;
let delay = 0;
const interval = 50;
// 类型别名避免Fragment语法问题
type PostEntry = CollectionEntry<"posts">;
const masonryEnabled = siteConfig.postListLayout.grid.masonry;
const columnWidth = siteConfig.postListLayout.grid.columnWidth || 280;
// 根据配置设置初始布局模式,避免闪烁
const defaultLayout = siteConfig.postListLayout.defaultMode || "list";
const mobileDefaultLayout =
siteConfig.postListLayout.mobileDefaultMode || defaultLayout;
const initialLayoutClass =
defaultLayout === "grid"
? "post-grid-auto grid-mode"
: "flex flex-col gap-4 md:gap-4 list-mode";
---
<div
id="post-list-container"
class={`transition-all duration-500 ease-in-out mb-4 ${initialLayoutClass}`}
data-default-layout={defaultLayout}
data-mobile-default-layout={mobileDefaultLayout}
data-masonry-enabled={masonryEnabled}
data-column-width={columnWidth}
style={`--post-card-min-width: ${columnWidth}px;`}
>
{
page.data.map((entry: PostEntry, index: number) => (
<PostCard
entry={entry}
title={entry.data.title}
tags={entry.data.tags}
category={entry.data.category}
published={entry.data.published}
updated={entry.data.updated}
url={getPostUrlBySlug(entry.id)}
image={entry.data.image}
description={entry.data.description}
draft={entry.data.draft}
pinned={entry.data.pinned}
password={!!entry.data.password}
loading={index < 2 ? "eager" : "lazy"}
class:list="onload-animation post-card-item"
style={`animation-delay: calc(var(--content-delay) + ${delay++ * interval}ms);`}
/>
))
}
</div>
<!-- 立即执行脚本:防止刷新时的布局闪烁 -->
<script is:inline define:vars={{ defaultLayout, mobileDefaultLayout, columnWidth }}>
(function() {
const savedLayout = localStorage.getItem('postListLayout');
// 根据视口宽度确定有效的默认布局
const effectiveDefault = window.innerWidth < 780 ? mobileDefaultLayout : defaultLayout;
// 低于380px强制网格模式
const effectiveLayout = window.innerWidth < 380 ? 'grid' : (savedLayout || effectiveDefault);
if (effectiveLayout !== defaultLayout) {
const container = document.getElementById('post-list-container');
if (container) {
// 禁用过渡动画
container.style.transition = 'none';
// 移除所有布局类
container.classList.remove('list-mode', 'grid-mode', 'post-grid-auto', 'flex', 'flex-col', 'gap-4', 'md:gap-4');
if (effectiveLayout === 'grid') {
container.classList.add('grid-mode', 'post-grid-auto');
} else {
container.classList.add('list-mode', 'flex', 'flex-col', 'gap-4', 'md:gap-4');
}
// 强制重排后恢复过渡动画
container.offsetHeight;
container.style.transition = '';
}
}
})();
</script>
<script>
// 动态布局切换脚本
function initLayout() {
const postListContainer = document.getElementById("post-list-container");
if (!postListContainer) return;
// 从localStorage读取用户偏好
const savedLayout = localStorage.getItem("postListLayout");
const defaultLayout =
postListContainer.getAttribute("data-default-layout") || "list";
const mobileDefaultLayout =
postListContainer.getAttribute("data-mobile-default-layout") || defaultLayout;
// 根据视口宽度确定有效的默认布局
const effectiveDefault = window.innerWidth < 780 ? mobileDefaultLayout : defaultLayout;
let currentLayout = savedLayout || effectiveDefault;
// 低于380px强制网格模式
if (window.innerWidth < 380) {
currentLayout = "grid";
}
// 应用布局
updatePostListLayout(currentLayout);
}
function updatePostListLayout(layout: string) {
const postListContainer = document.getElementById("post-list-container");
if (!postListContainer) return;
// Check current layout state
const isCurrentGrid = postListContainer.classList.contains("grid-mode");
const isCurrentList = postListContainer.classList.contains("list-mode");
const currentLayout = isCurrentGrid ? "grid" : (isCurrentList ? "list" : null);
// Common logic vars
const masonryEnabled = postListContainer.getAttribute("data-masonry-enabled") === "true";
// Helper to apply layout classes (Pure logic, no animation)
const applyClasses = () => {
postListContainer.classList.remove("list-mode", "grid-mode", "post-grid-auto");
if (layout === "grid") {
postListContainer.classList.add("grid-mode");
postListContainer.classList.remove("flex", "flex-col");
if (masonryEnabled) {
postListContainer.classList.remove("post-grid-auto");
applyMasonryLayout();
} else {
postListContainer.classList.add("post-grid-auto");
resetMasonryLayout();
}
} else {
postListContainer.classList.add("list-mode");
postListContainer.classList.add("flex", "flex-col", "gap-4", "md:gap-4");
postListContainer.classList.remove("post-grid-auto");
resetMasonryLayout();
}
};
// Case 1: First run (Initialization) - No animation
if (!currentLayout) {
applyClasses();
return;
}
// Case 2: Same layout (e.g. Resize) - No animation, just refresh masonry
if (currentLayout === layout) {
if (layout === "grid" && masonryEnabled) {
applyMasonryLayout();
}
return;
}
// Case 3: Layout Change - Smooth Animation
// 1. Fade OUT
postListContainer.classList.add("layout-switching");
// 2. Change Layout after fade out (200ms match CSS)
setTimeout(() => {
applyClasses();
// 3. Fade IN (Short delay to ensure DOM update)
requestAnimationFrame(() => {
postListContainer.classList.remove("layout-switching");
});
}, 200);
}
function resetMasonryLayout() {
const container = document.getElementById("post-list-container");
if (!container) return;
container.style.height = "";
container.style.position = "";
container.style.display = "";
const items = container.querySelectorAll(".post-card-item");
items.forEach((item) => {
// @ts-ignore
item.style.position = "";
// @ts-ignore
item.style.top = "";
// @ts-ignore
item.style.left = "";
// @ts-ignore
item.style.width = "";
});
}
function applyMasonryLayout() {
const container = document.getElementById("post-list-container");
if (!container) return;
const masonryEnabled = container.getAttribute("data-masonry-enabled") === "true";
if (!masonryEnabled) return;
// 仅在 grid 模式下应用
if (!container.classList.contains("grid-mode")) return;
const items = Array.from(container.querySelectorAll(".post-card-item"));
if (items.length === 0) return;
// 瀑布流配置
const gap = 16; // 1rem = 16px
const columnWidth = parseInt(container.getAttribute("data-column-width") || "280");
// 重置容器样式以允许绝对定位
container.style.position = "relative";
container.style.display = "block"; // 覆盖 grid display
// 使用 offsetWidth 避免 transform: scale 的影响
const containerWidth = container.offsetWidth;
// 根据容器宽度和最小列宽动态计算列数
const colCount = Math.max(1, Math.floor((containerWidth + gap) / (columnWidth + gap)));
const itemWidth = (containerWidth - (colCount - 1) * gap) / colCount;
const colHeights = new Array(colCount).fill(0);
items.forEach((item) => {
// 找到最短的列放置
const colIndex = colHeights.indexOf(Math.min(...colHeights));
// @ts-ignore
item.style.position = "absolute";
// @ts-ignore
item.style.width = `${itemWidth}px`;
// @ts-ignore
item.style.setProperty('height', 'auto', 'important');
// 获取高度,优先使用 offsetHeight 避免 transform 影响
// @ts-ignore
const height = item.offsetHeight;
const top = colHeights[colIndex];
const left = colIndex * (itemWidth + gap);
// @ts-ignore
item.style.top = `${top}px`;
// @ts-ignore
item.style.left = `${left}px`;
colHeights[colIndex] += height + gap;
});
container.style.height = `${Math.max(...colHeights)}px`;
}
// 页面加载时初始化布局
document.addEventListener("DOMContentLoaded", function () {
// 延迟一点确保DOM完全加载
setTimeout(initLayout, 50);
// 监听图片加载以重新计算布局
const imgs = document.querySelectorAll('#post-list-container img');
imgs.forEach(img => {
// @ts-ignore
if(img.complete) return;
img.addEventListener('load', () => {
applyMasonryLayout();
});
});
});
// 页面显示时也初始化布局(处理页面切换)
document.addEventListener("visibilitychange", function () {
if (!document.hidden) {
setTimeout(initLayout, 100);
}
});
// 监听布局变化事件
window.addEventListener("layoutChange", function (event) {
// @ts-ignore
const newLayout = event.detail.layout;
const postListContainer = document.getElementById("post-list-container");
if (!postListContainer) return;
updatePostListLayout(newLayout);
});
// 监听窗口大小变化
let resizeTimeout: any;
window.addEventListener("resize", function () {
clearTimeout(resizeTimeout);
resizeTimeout = setTimeout(function () {
initLayout();
}, 250);
});
// 监听页面导航事件(Astro的客户端路由)
document.addEventListener("astro:page-load", function () {
setTimeout(initLayout, 50);
// 监听图片加载
const imgs = document.querySelectorAll('#post-list-container img');
imgs.forEach(img => {
// @ts-ignore
if(img.complete) return;
img.addEventListener('load', () => {
applyMasonryLayout();
});
});
});
document.addEventListener("astro:after-swap", function () {
setTimeout(initLayout, 50);
});
// 立即执行一次(处理页面刷新)
setTimeout(initLayout, 0);
</script>
<style is:global>
.post-grid-auto {
display: grid;
grid-template-columns: repeat(auto-fill, minmax(var(--post-card-min-width, 320px), 1fr));
gap: 1rem;
}
/* 移动端列表模式下缩小元数据 */
@media (max-width: 767px) {
.list-mode .post-meta-root {
transform: scale(0.72) !important;
transform-origin: top left !important;
margin-bottom: 0.25rem !important;
width: 139% !important;
}
.list-mode .post-meta.card-header-meta {
transform: scale(0.9) !important;
width: 111% !important;
margin-bottom: 0.5rem !important;
gap: 0.5rem !important;
}
.list-mode :global(.post-meta) {
margin-bottom: 0.25rem !important;
gap: 0.25rem !important;
}
}
</style>
<style>
/* 布局切换动画 */
#post-list-container {
/* 限制过渡属性为 opacity 和 transform,避免响应父元素位置变化 */
transition: opacity 0.5s cubic-bezier(0.4, 0, 0.2, 1),
transform 0.5s cubic-bezier(0.4, 0, 0.2, 1);
}
/* 文章卡片的过渡动画 */
#post-list-container > :global(*) {
transition: opacity 0.4s cubic-bezier(0.4, 0, 0.2, 1),
transform 0.4s cubic-bezier(0.4, 0, 0.2, 1);
}
/* 布局切换时的动画效果 */
#post-list-container {
transition: opacity 0.2s ease-out, transform 0.2s ease-out;
}
#post-list-container.layout-switching {
opacity: 0;
transform: translateY(10px);
}
/* Grid Mode Customization */
#post-list-container.grid-mode :global(.post-card-wrapper) {
flex-direction: column-reverse !important;
}
#post-list-container.grid-mode :global(.post-card-image) {
width: 100% !important;
position: relative !important;
top: auto !important;
right: auto !important;
bottom: auto !important;
border-radius: var(--radius-large) var(--radius-large) 0 0 !important;
/*aspect-ratio: 16/9 !important;*/
}
#post-list-container.grid-mode :global(.post-card-content) {
width: 100% !important;
padding: 1rem !important;
}
#post-list-container.grid-mode :global(.no-cover .post-card-content) {
padding-right: 4.5rem !important;
}
#post-list-container.grid-mode :global(.post-card-title) {
font-size: 1.35rem !important;
line-height: 1.75rem !important;
margin-bottom: 0.5rem !important;
}
#post-list-container.grid-mode :global(.post-card-title::before) {
display: none !important;
}
#post-list-container.grid-mode :global(.post-meta) {
margin-bottom: 0.5rem !important;
gap: 0.5rem !important;
}
#post-list-container.grid-mode :global(.post-meta .text-xl) {
font-size: 1rem !important;
line-height: 1.25rem !important;
}
#post-list-container.grid-mode :global(.meta-icon) {
width: 1.5rem !important;
height: 1.5rem !important;
margin-right: 0.25rem !important;
}
#post-list-container.grid-mode :global(.post-meta .text-sm) {
font-size: 0.75rem !important;
line-height: 1rem !important;
}
#post-list-container.grid-mode :global(.card-header-meta .text-sm) {
font-size: 0.875rem !important;
line-height: 1.25rem !important;
}
#post-list-container.grid-mode :global(.card-header-meta .meta-icon) {
width: 2rem !important;
height: 2rem !important;
margin-right: 0.5rem !important;
}
#post-list-container.grid-mode :global(.card-header-meta .text-xl) {
font-size: 1.25rem !important;
line-height: 1.75rem !important;
}
#post-list-container.grid-mode :global(.post-meta .pinned-btn) {
height: 2rem !important;
padding: 0 0.5rem !important;
gap: 0.25rem !important;
}
#post-list-container.grid-mode :global(.post-meta .pinned-btn .text-xl) {
font-size: 1.25rem !important;
line-height: 1.75rem !important;
}
#post-list-container.grid-mode :global(.post-meta .pinned-btn .text-sm) {
font-size: 0.875rem !important;
line-height: 1.25rem !important;
}
</style>
+82
View File
@@ -0,0 +1,82 @@
---
import { Icon } from "astro-icon/components";
import I18nKey from "@/i18n/i18nKey";
import { i18n } from "@/i18n/translation";
import { formatDateToYYYYMMDD } from "@/utils/date-utils";
export interface Props {
published: Date;
words?: number;
minutes?: number;
showPublished?: boolean;
showWords?: boolean;
showReadingTime?: boolean;
showIcons?: boolean;
className?: string;
}
const {
published,
words,
minutes,
showPublished = true,
showWords = true,
showReadingTime = true,
showIcons = false,
className = "",
} = Astro.props;
const hasPublished = showPublished;
const hasWords = showWords && typeof words === "number";
const hasMinutes = showReadingTime && typeof minutes === "number";
const textClass = "text-xs font-medium";
const dividerClass = "text-xs font-medium text-black/20 dark:text-white/20";
const iconWrapperClass =
"transition h-5 w-5 rounded-md bg-black/5 dark:bg-white/10 text-black/50 dark:text-white/50 flex items-center justify-center mr-1.5";
const iconClass = "text-sm";
---
<div class:list={["flex flex-wrap items-center gap-2", className]}>
{hasPublished && (
<div class="flex items-center">
{showIcons && (
<div class={iconWrapperClass}>
<Icon is:inline name="material-symbols:calendar-today-outline-rounded" class={iconClass} />
</div>
)}
<span class={textClass}>
{!showIcons && `${i18n(I18nKey.publishedAt)} `}{formatDateToYYYYMMDD(published)}
</span>
</div>
)}
{hasPublished && hasWords && <span class={dividerClass}>|</span>}
{hasWords && (
<div class="flex items-center">
{showIcons && (
<div class={iconWrapperClass}>
<Icon is:inline name="material-symbols:notes-rounded" class={iconClass} />
</div>
)}
<span class={textClass}>
{words} {i18n(words === 1 ? I18nKey.wordCount : I18nKey.wordsCount)}
</span>
</div>
)}
{(hasPublished || hasWords) && hasMinutes && <span class={dividerClass}>|</span>}
{hasMinutes && (
<div class="flex items-center">
{showIcons && (
<div class={iconWrapperClass}>
<Icon is:inline name="material-symbols:schedule-outline-rounded" class={iconClass} />
</div>
)}
<span class={textClass}>
{minutes} {i18n(minutes === 1 ? I18nKey.minuteCount : I18nKey.minutesCount)}
</span>
</div>
)}
</div>
+237
View File
@@ -0,0 +1,237 @@
---
import type { MarkdownHeading } from "astro";
import Advertisement from "@/components/widget/Advertisement.astro";
import Announcement from "@/components/widget/Announcement.astro";
import Calendar from "@/components/widget/Calendar.astro";
import Categories from "@/components/widget/Categories.astro";
import Music from "@/components/widget/Music.astro";
import Profile from "@/components/widget/Profile.astro";
import SidebarTOC from "@/components/widget/SidebarTOC.astro";
import SiteInfo from "@/components/widget/SiteInfo.astro";
import SiteStats from "@/components/widget/SiteStats.astro";
import Tags from "@/components/widget/Tags.astro";
import { sidebarLayoutConfig } from "@/config";
import type {
MobileBottomComponentConfig,
WidgetComponentConfig,
} from "@/types/config";
interface Props {
class?: string;
headings?: MarkdownHeading[];
encrypted?: boolean;
side?: "left" | "right" | "bottom";
}
// 侧边栏位置常量
const SIDEBAR_SIDE = {
LEFT: "left",
RIGHT: "right",
BOTTOM: "bottom",
} as const;
// 组件位置常量
const COMPONENT_POSITION = {
TOP: "top",
STICKY: "sticky",
} as const;
// 动画延迟配置
const ANIMATION_DELAY_UNIT = 50; // ms
// 组件映射表
const componentMap = {
profile: Profile,
announcement: Announcement,
categories: Categories,
tags: Tags,
sidebarToc: SidebarTOC,
advertisement: Advertisement,
stats: SiteStats,
calendar: Calendar,
music: Music,
siteInfo: SiteInfo,
};
// 获取侧边栏位置
const side = (Astro.props.side ||
SIDEBAR_SIDE.LEFT) as (typeof SIDEBAR_SIDE)[keyof typeof SIDEBAR_SIDE];
const className = Astro.props.class;
// 根据 side 属性获取对应的组件列表
const getComponents = (): (
| WidgetComponentConfig
| MobileBottomComponentConfig
)[] => {
if (side === SIDEBAR_SIDE.LEFT) {
return sidebarLayoutConfig.leftComponents;
}
if (side === SIDEBAR_SIDE.RIGHT) {
return sidebarLayoutConfig.rightComponents;
}
if (side === SIDEBAR_SIDE.BOTTOM) {
return sidebarLayoutConfig.mobileBottomComponents;
}
return [];
};
// 过滤并排序组件(不再进行 showOnPostPage 过滤,交由客户端处理)
const filterAndSortComponents = (
components: (WidgetComponentConfig | MobileBottomComponentConfig)[],
) => {
return components.filter((comp) => comp.enable);
};
// 分离 top 和 sticky 位置的组件(保持原始数组顺序)
const getComponentsByPosition = (
components: (WidgetComponentConfig | MobileBottomComponentConfig)[],
) => {
const topComponents = components.filter(
(c) => "position" in c && c.position === COMPONENT_POSITION.TOP,
) as WidgetComponentConfig[];
const stickyComponents = components.filter(
(c) => "position" in c && c.position === COMPONENT_POSITION.STICKY,
) as WidgetComponentConfig[];
return { topComponents, stickyComponents };
};
// 获取动画延迟(硬编码)
const getAnimationDelay = (index: number): string => {
return `${index * ANIMATION_DELAY_UNIT}ms`;
};
// 判断当前页面是否为文章页面(服务端渲染时确定)
const isPostPage = Astro.url.pathname.includes("/posts/");
// 判断组件在当前页面首屏是否可见(用于计算布局间距,避免隐藏组件占位)
const isComponentInitiallyVisible = (
config: WidgetComponentConfig | MobileBottomComponentConfig,
): boolean => {
if (
"showOnPostPage" in config &&
config.showOnPostPage === false &&
isPostPage
) {
return false;
}
if (
"hideOnNonPostPage" in config &&
config.hideOnNonPostPage === true &&
!isPostPage
) {
return false;
}
return true;
};
// 动态构建组件 props
const getComponentProps = (
config: WidgetComponentConfig | MobileBottomComponentConfig,
index: number,
): Record<string, unknown> => {
const baseProps: Record<string, unknown> = {
class: "onload-animation",
style: `animation-delay: ${getAnimationDelay(index)}`,
widgetConfig: config,
};
// 添加 showOnPostPage 和 hideOnNonPostPage 标记class(仅WidgetComponentConfig有这些属性)
// 同时根据当前页面类型在服务端渲染时设置初始 hidden 状态,避免页面加载时闪烁
if ("showOnPostPage" in config && config.showOnPostPage === false) {
baseProps.class = `${baseProps.class} widget-hide-on-post`;
if (isPostPage) {
baseProps.class = `${baseProps.class} hidden`;
}
}
if ("hideOnNonPostPage" in config && config.hideOnNonPostPage === true) {
baseProps.class = `${baseProps.class} widget-hide-on-non-post`;
if (!isPostPage) {
baseProps.class = `${baseProps.class} hidden`;
}
}
// 特殊处理 SidebarTOC 组件
if (config.type === "sidebarToc") {
return {
...baseProps,
headings: Astro.props.headings || [],
encrypted: Astro.props.encrypted || false,
};
}
return baseProps;
};
// 获取所有需要渲染的组件
const allComponents = getComponents();
const filteredComponents = filterAndSortComponents(allComponents);
// 对于移动端底部组件,直接使用所有组件,不进行position分组
const isMobileBottom = side === SIDEBAR_SIDE.BOTTOM;
const { topComponents, stickyComponents } = !isMobileBottom
? getComponentsByPosition(filteredComponents)
: { topComponents: [], stickyComponents: [] };
const bottomComponents = isMobileBottom ? filteredComponents : [];
const hasInitiallyVisibleTopComponents = topComponents.some(
isComponentInitiallyVisible,
);
---
{
(topComponents.length > 0 || stickyComponents.length > 0 || bottomComponents.length > 0) && (
<div id={`${side}-sidebar`} class:list={[className, "flex flex-col w-full pt-0"]}>
{/* Mobile bottom components - 直接渲染所有组件,不分组 */}
{isMobileBottom ? (
<div class="flex flex-col w-full gap-4">
{bottomComponents.map((comp, index) => {
const Component = componentMap[comp.type];
if (!Component) return null;
const props = getComponentProps(comp, index) as any;
return <Component {...props} />;
})}
</div>
) : (
<>
{/* Top components */}
{topComponents.length > 0 && (
<div
class:list={[
"flex flex-col w-full gap-4",
hasInitiallyVisibleTopComponents && "mb-4",
]}
>
{topComponents.map((comp, index) => {
const Component = componentMap[comp.type];
if (!Component) return null;
const props = getComponentProps(comp, index) as any;
return <Component {...props} />;
})}
</div>
)}
{/* Sticky components */}
{stickyComponents.length > 0 && (
<div
id={`${side}-sidebar-sticky`}
class:list={[
"flex flex-col w-full mt-0 gap-4",
"sticky",
hasInitiallyVisibleTopComponents ? "top-4" : "top-0",
]}
>
{stickyComponents.map((comp, index) => {
const Component = componentMap[comp.type];
if (!Component) return null;
const props = getComponentProps(
comp,
topComponents.length + index
) as any;
return <Component {...props} />;
})}
</div>
)}
</>
)}
</div>
)
}
+93
View File
@@ -0,0 +1,93 @@
---
import { Icon } from "astro-icon/components";
import { licenseConfig } from "@/config/licenseConfig";
import { profileConfig } from "@/config/profileConfig";
import I18nKey from "@/i18n/i18nKey";
import { i18n } from "@/i18n/translation";
import { formatDateToYYYYMMDD } from "@/utils/date-utils";
interface Props {
title: string;
id: string;
pubDate: Date;
class: string;
author: string;
sourceLink: string;
licenseName: string;
licenseUrl: string;
}
const { title, pubDate, author, sourceLink, licenseName, licenseUrl } =
Astro.props;
const className = Astro.props.class;
const profileConf = profileConfig;
const licenseConf = licenseConfig;
const postUrl = sourceLink || decodeURIComponent(Astro.url.toString());
// 根据许可证名称匹配对应图标
function getLicenseIcon(name: string): string {
const n = name.toLowerCase();
if (/cc0|creative commons zero/.test(n)) {
return "fa7-brands:creative-commons-zero";
}
if (/public domain|公共领域/.test(n)) {
return "fa7-brands:creative-commons-pd";
}
if (/^cc($|[\s-])|creative commons|知识共享/.test(n)) {
return "fa7-brands:creative-commons";
}
if (/\b(mit|apache|bsd|isc|mulan|unlicense)\b|gpl|mpl\b/.test(n)) {
return "fa7-brands:osi";
}
return "fa7-regular:copyright";
}
// 文章单独指定的许可证按名称自动匹配;站点默认许可证优先使用配置中的自定义图标
const licenseIcon = licenseName
? getLicenseIcon(licenseName)
: licenseConf.icon || getLicenseIcon(licenseConf.name);
---
<div
class={`relative transition overflow-hidden bg-(--license-block-bg) py-5 px-6 ${className}`}
>
<div class="transition font-bold text-black/75 dark:text-white/75">
{title}
</div>
<a href={postUrl} class="link text-(--primary) break-all">
{postUrl}
</a>
<div class="flex flex-col sm:flex-row gap-3 sm:gap-6 mt-2">
<div>
<div class="transition text-black/30 dark:text-white/30 text-sm">
{i18n(I18nKey.author)}
</div>
<div class="transition text-black/75 dark:text-white/75 line-clamp-2">
{author || profileConf.name}
</div>
</div>
<div>
<div class="transition text-black/30 dark:text-white/30 text-sm">
{i18n(I18nKey.publishedAt)}
</div>
<div class="transition text-black/75 dark:text-white/75 line-clamp-2">
{formatDateToYYYYMMDD(pubDate)}
</div>
</div>
<div>
<div class="transition text-black/30 dark:text-white/30 text-sm">
{i18n(I18nKey.license)}
</div>
<a
href={licenseName ? licenseUrl || undefined : licenseConf.url}
target="_blank"
class="link text-(--primary) line-clamp-2"
>{licenseName || licenseConf.name}</a
>
</div>
</div>
<Icon is:inline
name={licenseIcon}
class="transition text-[15rem] absolute pointer-events-none right-6 top-1/2 -translate-y-1/2 text-black/5 dark:text-white/5"
/>
</div>
+220
View File
@@ -0,0 +1,220 @@
---
import { Icon } from "astro-icon/components";
import I18nKey from "@/i18n/i18nKey";
import { i18n } from "@/i18n/translation";
import type { PostForList } from "@/utils/content-utils";
import { formatDateToYYYYMMDD } from "@/utils/date-utils";
import { getPostUrlBySlug, url } from "@/utils/url-utils";
interface Props {
relatedPosts: PostForList[];
currentPostId: string;
}
const { relatedPosts, currentPostId } = Astro.props;
const apiUrl = url("/api/allPostMeta.json");
const relatedIds = JSON.stringify(relatedPosts.map((p) => p.id));
const noRelatedPostsText = i18n(I18nKey.noRelatedPosts);
const noRandomPostsText = i18n(I18nKey.noRandomPosts);
---
<div class="grid grid-cols-1 md:grid-cols-2 gap-4 mb-4">
{/* 左栏:相关文章(静态) */}
<div class="card-base p-5 md:p-6 flex flex-col">
<div class="flex items-center gap-2 pb-3 mb-1 border-b border-(--line-divider)">
<Icon is:inline
name="material-symbols:signpost"
class="text-xl text-(--primary)"
/>
<span class="text-base font-bold text-black/75 dark:text-white/75 transition">
{i18n(I18nKey.relatedPosts)}
</span>
<span class="ml-auto text-xs px-2 py-0.5 rounded-full bg-(--btn-regular-bg) text-(--btn-content) transition">
{i18n(I18nKey.smartRecommend)}
</span>
</div>
{relatedPosts.length > 0 ? (
relatedPosts.map((post, idx) => (
<a
href={getPostUrlBySlug(post.id)}
class:list={[
"group flex items-center gap-3 px-3 py-3 -mx-1 rounded-lg",
"transition-all hover:bg-black/5 dark:hover:bg-white/5 active:scale-[0.98]",
idx < relatedPosts.length - 1 && "border-b border-dashed border-(--line-divider)",
]}
>
<div class="shrink-0 w-6 h-6 rounded-md bg-(--enter-btn-bg) text-(--primary) flex items-center justify-center text-sm font-bold transition">
{idx + 1}
</div>
<div class="flex-1 min-w-0">
<div class="font-bold text-sm text-black/75 dark:text-white/75 truncate transition group-hover:text-(--primary)">
{post.data.title}
</div>
<div class="flex items-center gap-1.5 text-xs text-black/30 dark:text-white/30 transition mt-0.5">
{post.data.category && (
<span class="shrink-0 px-1.5 py-0.5 rounded-sm bg-black/5 dark:bg-white/10 text-black/40 dark:text-white/40">
{post.data.category}
</span>
)}
<span class="truncate">{post.data.description || formatDateToYYYYMMDD(post.data.published)}</span>
</div>
</div>
<Icon is:inline
name="material-symbols:chevron-right-rounded"
class="shrink-0 text-xl text-black/15 dark:text-white/15 transition group-hover:text-(--primary) group-hover:translate-x-0.5"
/>
</a>
))
) : (
<div class="flex-1 flex flex-col items-center justify-center min-h-40 text-black/30 dark:text-white/30 transition">
<Icon is:inline name="material-symbols:article-outline" class="text-4xl mb-3 opacity-50" />
<span class="text-sm">{noRelatedPostsText}</span>
</div>
)}
</div>
{/* 右栏:随机文章(客户端 fetch 渲染) */}
<div class="card-base p-5 md:p-6 flex flex-col">
<div class="flex items-center gap-2 pb-3 mb-1 border-b border-(--line-divider)">
<Icon is:inline
name="material-symbols:recommend"
class="text-xl text-(--primary)"
/>
<span class="text-base font-bold text-black/75 dark:text-white/75 transition">
{i18n(I18nKey.randomPosts)}
</span>
<span class="ml-auto text-xs px-2 py-0.5 rounded-full bg-(--btn-regular-bg) text-(--btn-content) transition">
{i18n(I18nKey.randomRecommend)}
</span>
</div>
<div
id="random-posts-list"
class="flex-1 flex items-center justify-center"
data-api-url={apiUrl}
data-current-id={currentPostId}
data-related-ids={relatedIds}
>
<div id="random-posts-empty" style="display:none" class="flex flex-col items-center text-black/30 dark:text-white/30 transition">
<Icon is:inline name="material-symbols:article-outline" class="text-4xl mb-3 opacity-50" />
<span class="text-sm">{noRandomPostsText}</span>
</div>
</div>
</div>
</div>
<script is:inline>
function renderRandomPosts() {
var container = document.getElementById('random-posts-list');
if (!container) return;
var apiUrl = container.dataset.apiUrl;
var currentId = container.dataset.currentId;
var relatedIds = JSON.parse(container.dataset.relatedIds || '[]');
var excludeSet = {};
excludeSet[currentId] = true;
for (var i = 0; i < relatedIds.length; i++) excludeSet[relatedIds[i]] = true;
function render(allPosts) {
var emptyTemplate = document.getElementById('random-posts-empty');
container.innerHTML = '';
var candidates = allPosts.filter(function(p) {
return !excludeSet[p.id] && !p.password;
});
// Fisher-Yates shuffle
for (var i = candidates.length - 1; i > 0; i--) {
var j = Math.floor(Math.random() * (i + 1));
var tmp = candidates[i];
candidates[i] = candidates[j];
candidates[j] = tmp;
}
var picked = candidates.slice(0, 5);
if (picked.length === 0) {
container.className = 'flex-1 flex items-center justify-center';
if (emptyTemplate) {
var emptyEl = emptyTemplate.cloneNode(true);
emptyEl.style.display = '';
container.appendChild(emptyEl);
}
return;
}
container.className = 'flex-1';
var fragment = document.createDocumentFragment();
var base = apiUrl.replace(/\/api\/allPostMeta\.json$/, '');
picked.forEach(function(post, idx) {
var href = base + '/posts/' + post.id + '/';
var a = document.createElement('a');
a.href = href;
a.className = 'group flex items-center gap-3 px-3 py-3 -mx-1 rounded-lg transition-all hover:bg-black/5 dark:hover:bg-white/5 active:scale-[0.98]'
+ (idx < picked.length - 1 ? ' border-b border-dashed border-(--line-divider)' : '');
var num = document.createElement('div');
num.className = 'shrink-0 w-6 h-6 rounded-md bg-(--enter-btn-bg) text-(--primary) flex items-center justify-center text-sm font-bold transition';
num.textContent = String(idx + 1);
var content = document.createElement('div');
content.className = 'flex-1 min-w-0';
var title = document.createElement('div');
title.className = 'font-bold text-sm text-black/75 dark:text-white/75 truncate transition group-hover:text-(--primary)';
title.textContent = post.title;
var meta = document.createElement('div');
meta.className = 'flex items-center gap-1.5 text-xs text-black/30 dark:text-white/30 transition mt-0.5';
if (post.category) {
var cat = document.createElement('span');
cat.className = 'shrink-0 px-1.5 py-0.5 rounded-sm bg-black/5 dark:bg-white/10 text-black/40 dark:text-white/40';
cat.textContent = post.category;
meta.appendChild(cat);
}
var desc = document.createElement('span');
desc.className = 'truncate';
desc.textContent = post.description || new Date(post.published).toISOString().substring(0, 10);
meta.appendChild(desc);
content.appendChild(title);
content.appendChild(meta);
var svg = document.createElementNS('http://www.w3.org/2000/svg', 'svg');
svg.setAttribute('width', '24');
svg.setAttribute('height', '24');
svg.setAttribute('viewBox', '0 0 24 24');
svg.setAttribute('class', 'shrink-0 text-xl text-black/15 dark:text-white/15 transition group-hover:text-(--primary) group-hover:translate-x-0.5');
var path = document.createElementNS('http://www.w3.org/2000/svg', 'path');
path.setAttribute('fill', 'currentColor');
path.setAttribute('d', 'M9.29 6.71a1 1 0 0 0 0 1.41L13.17 12l-3.88 3.88a1 1 0 1 0 1.41 1.41l4.59-4.59a1 1 0 0 0 0-1.41L10.7 6.7a1 1 0 0 0-1.41.01z');
svg.appendChild(path);
a.appendChild(num);
a.appendChild(content);
a.appendChild(svg);
fragment.appendChild(a);
});
container.appendChild(fragment);
}
// 使用缓存避免 swup 导航时重复请求
if (window.__allPostMetaCache) {
render(window.__allPostMetaCache);
} else {
fetch(apiUrl)
.then(function(r) { return r.json(); })
.then(function(data) {
window.__allPostMetaCache = data;
render(data);
});
}
}
renderRandomPosts();
document.addEventListener('swup:contentReplaced', renderRandomPosts);
</script>
+536
View File
@@ -0,0 +1,536 @@
<script lang="ts">
import QRCode from "qrcode";
import { onMount } from "svelte";
import Icon from "@/components/common/Icon.svelte";
import I18nKey from "../../i18n/i18nKey";
import { i18n } from "../../i18n/translation";
export let title: string;
export let author: string;
export let description = "";
export let pubDate: string;
export let coverImage: string | null = null;
export let url: string;
export let siteTitle: string;
export let avatar: string | null = null;
let showModal = false;
let posterImage: string | null = null;
let generating = false;
let themeColor = "#558e88"; // Default blue
onMount(() => {
// Get theme color from CSS variable
const temp = document.createElement("div");
temp.style.color = "var(--primary)";
temp.style.display = "none";
document.body.appendChild(temp);
const computedColor = getComputedStyle(temp).color;
document.body.removeChild(temp);
if (computedColor) {
themeColor = computedColor;
}
});
function loadImage(src: string): Promise<HTMLImageElement | null> {
return new Promise((resolve) => {
const img = new Image();
img.crossOrigin = "anonymous";
img.onload = () => resolve(img);
img.onerror = () => {
if (!src.includes("images.weserv.nl")) {
const proxyUrl = `https://images.weserv.nl/?url=${encodeURIComponent(src)}&output=png`;
const proxyImg = new Image();
proxyImg.crossOrigin = "anonymous";
proxyImg.onload = () => resolve(proxyImg);
proxyImg.onerror = () => {
resolve(null);
};
proxyImg.src = proxyUrl;
} else {
resolve(null);
}
};
img.src = src;
});
}
function getLines(
ctx: CanvasRenderingContext2D,
text: string,
maxWidth: number,
): string[] {
const chars = text.split("");
const lines: string[] = [];
let currentLine = "";
for (let i = 0; i < chars.length; i++) {
const char = chars[i];
const width = ctx.measureText(currentLine + char).width;
if (width < maxWidth) {
currentLine += char;
} else {
lines.push(currentLine);
currentLine = char;
}
}
if (currentLine) {
lines.push(currentLine);
}
return lines;
}
function drawRoundedRect(
ctx: CanvasRenderingContext2D,
x: number,
y: number,
width: number,
height: number,
radius: number,
) {
ctx.beginPath();
ctx.moveTo(x + radius, y);
ctx.lineTo(x + width - radius, y);
ctx.quadraticCurveTo(x + width, y, x + width, y + radius);
ctx.lineTo(x + width, y + height - radius);
ctx.quadraticCurveTo(x + width, y + height, x + width - radius, y + height);
ctx.lineTo(x + radius, y + height);
ctx.quadraticCurveTo(x, y + height, x, y + height - radius);
ctx.lineTo(x, y + radius);
ctx.quadraticCurveTo(x, y, x + radius, y);
ctx.closePath();
}
async function generatePoster() {
showModal = true;
if (posterImage) return;
generating = true;
try {
const scale = 2;
const width = 425 * scale;
const padding = 24 * scale;
// 1. Prepare resources
const qrCodeUrl = await QRCode.toDataURL(url, {
margin: 1,
width: 100 * scale,
color: { dark: "#000000", light: "#ffffff" },
});
const [qrImg, coverImg, avatarImg] = await Promise.all([
loadImage(qrCodeUrl),
coverImage ? loadImage(coverImage) : Promise.resolve(null),
avatar ? loadImage(avatar) : Promise.resolve(null),
]);
// 2. Setup Canvas for measuring
const canvas = document.createElement("canvas");
const ctx = canvas.getContext("2d");
if (!ctx) throw new Error("Canvas context not available");
canvas.width = width;
// Initial height estimation, will be adjusted
canvas.height = 1000 * scale;
// 3. Layout Calculation
const contentWidth = width - padding * 2;
let currentY = 0;
// Cover
const coverHeight = (coverImage ? 200 : 120) * scale;
currentY += coverHeight;
currentY += padding; // Gap after cover
// Meta (Date on Cover) - No extra height needed
// Title
ctx.font = `700 ${24 * scale}px 'Roboto', sans-serif`;
const titleLines = getLines(ctx, title, contentWidth);
const titleLineHeight = 30 * scale;
const titleHeight = titleLines.length * titleLineHeight;
currentY += titleHeight;
currentY += 16 * scale; // Gap
// Description
let descHeight = 0;
if (description) {
ctx.font = `${14 * scale}px 'Roboto', sans-serif`;
const descLines = getLines(ctx, description, contentWidth - 16 * scale); // minus border width and gap
// Limit to 6 lines
const maxDescLines = 6;
const displayDescLines = descLines.slice(0, maxDescLines);
const descLineHeight = 25 * scale; // 1.8 line-height approx
descHeight = displayDescLines.length * descLineHeight;
currentY += descHeight;
// currentY += 24 * scale; // Gap to footer (Removed to reduce whitespace)
} else {
currentY += 8 * scale; // Smaller gap if no desc
}
// Footer (Author + QR)
// Footer top border + padding
currentY += 24 * scale;
const footerHeight = 64 * scale; // Avatar/QR height
currentY += footerHeight;
currentY += padding; // Bottom padding
// 4. Resize Canvas to fit content
canvas.height = currentY;
// 5. Draw Content
// Fill Background
ctx.fillStyle = "#ffffff";
ctx.fillRect(0, 0, canvas.width, canvas.height);
// Draw Decorative Circles
ctx.save();
ctx.globalAlpha = 0.1;
ctx.fillStyle = themeColor;
// Top Right Circle
// CSS: top: -50px, right: -50px, width: 150px, height: 150px
// Radius = 75px
// Center X = width + 50 - 75 = width - 25
// Center Y = -50 + 75 = 25
ctx.beginPath();
ctx.arc(width - 25 * scale, 25 * scale, 75 * scale, 0, Math.PI * 2);
ctx.fill();
// Bottom Left Circle
// Adjusted to cover the avatar
ctx.beginPath();
ctx.arc(10 * scale, canvas.height - 10 * scale, 50 * scale, 0, Math.PI * 2);
ctx.fill();
ctx.restore();
// Parse Date
let dateObj: { day: string; month: string; year: string } | null = null;
try {
const d = new Date(pubDate);
if (!Number.isNaN(d.getTime())) {
dateObj = {
day: d.getDate().toString().padStart(2, "0"),
month: (d.getMonth() + 1).toString().padStart(2, "0"),
year: d.getFullYear().toString(),
};
}
} catch (e) {}
// Draw Cover
if (coverImg) {
// Object-fit: cover implementation
const imgRatio = coverImg.width / coverImg.height;
const targetRatio = width / coverHeight;
let sx: number;
let sy: number;
let sWidth: number;
let sHeight: number;
if (imgRatio > targetRatio) {
sHeight = coverImg.height;
sWidth = sHeight * targetRatio;
sx = (coverImg.width - sWidth) / 2;
sy = 0;
} else {
sWidth = coverImg.width;
sHeight = sWidth / targetRatio;
sx = 0;
sy = (coverImg.height - sHeight) / 2;
}
ctx.drawImage(
coverImg,
sx,
sy,
sWidth,
sHeight,
0,
0,
width,
coverHeight,
);
} else {
ctx.save();
ctx.fillStyle = themeColor;
ctx.globalAlpha = 0.2;
ctx.fillRect(0, 0, width, coverHeight);
ctx.restore();
}
// Draw Date Overlay
if (dateObj) {
const dateBoxW = 60 * scale;
const dateBoxH = 60 * scale;
const dateBoxX = padding;
const dateBoxY = coverHeight - dateBoxH;
// Background (Semi-transparent black)
ctx.fillStyle = "rgba(0, 0, 0, 0.3)";
drawRoundedRect(ctx, dateBoxX, dateBoxY, dateBoxW, dateBoxH, 4 * scale);
ctx.fill();
// Day
ctx.fillStyle = "#ffffff";
ctx.textAlign = "center";
ctx.textBaseline = "middle";
ctx.font = `700 ${30 * scale}px 'Roboto', sans-serif`;
ctx.fillText(dateObj.day, dateBoxX + dateBoxW / 2, dateBoxY + 24 * scale);
// Line
ctx.beginPath();
ctx.strokeStyle = "rgba(255, 255, 255, 0.6)";
ctx.lineWidth = 1 * scale;
ctx.moveTo(dateBoxX + 10 * scale, dateBoxY + 42 * scale);
ctx.lineTo(dateBoxX + dateBoxW - 10 * scale, dateBoxY + 42 * scale);
ctx.stroke();
// Year Month
ctx.font = `${10 * scale}px 'Roboto', sans-serif`;
ctx.fillText(
`${dateObj.year} ${dateObj.month}`,
dateBoxX + dateBoxW / 2,
dateBoxY + 51 * scale,
);
}
// Reset Y for drawing
let drawY = coverHeight + padding;
// Draw Title
ctx.textBaseline = "top";
ctx.textAlign = "left";
ctx.font = `700 ${24 * scale}px 'Roboto', sans-serif`;
ctx.fillStyle = "#111827";
titleLines.forEach((line) => {
ctx.fillText(line, padding, drawY);
drawY += titleLineHeight;
});
drawY += 16 * scale - (titleLineHeight - 24 * scale); // Adjust for line-height diff
// Draw Description
if (description) {
// Draw vertical line
ctx.fillStyle = "#e5e7eb";
const descLineH = descHeight; // Approximate
// Extend the line slightly above and below the text
drawRoundedRect(
ctx,
padding,
drawY - 8 * scale,
4 * scale,
descLineH + 8 * scale,
2 * scale,
);
ctx.fill();
ctx.font = `${14 * scale}px 'Roboto', sans-serif`;
ctx.fillStyle = "#4b5563";
const descLines = getLines(ctx, description, contentWidth - 16 * scale);
const maxDescLines = 6;
descLines.slice(0, maxDescLines).forEach((line) => {
ctx.fillText(line, padding + 16 * scale, drawY);
drawY += 25 * scale; // line height
});
// drawY += 24 * scale; // Removed to reduce whitespace
} else {
drawY += 8 * scale;
}
// Draw Footer Divider
drawY += 24 * scale; // Spacing before line
ctx.beginPath();
ctx.strokeStyle = "#f3f4f6";
ctx.lineWidth = 1 * scale;
ctx.moveTo(padding, drawY);
ctx.lineTo(width - padding, drawY);
ctx.stroke();
drawY += 24 * scale; // Spacing after line
// Draw Footer Content
const footerY = drawY;
// Left: Author
if (avatarImg) {
ctx.save();
const avatarSize = 64 * scale;
const avatarX = padding;
// Circle clip
ctx.beginPath();
ctx.arc(
avatarX + avatarSize / 2,
footerY + avatarSize / 2,
avatarSize / 2,
0,
Math.PI * 2,
);
ctx.closePath();
ctx.clip();
ctx.drawImage(avatarImg, avatarX, footerY, avatarSize, avatarSize);
ctx.restore();
// Border for avatar
ctx.beginPath();
ctx.arc(
avatarX + (64 * scale) / 2,
footerY + (64 * scale) / 2,
(64 * scale) / 2,
0,
Math.PI * 2,
);
ctx.strokeStyle = "#ffffff";
ctx.lineWidth = 2 * scale;
ctx.stroke();
}
const authorTextX = padding + (avatar ? 64 * scale + 16 * scale : 0);
const textCenterY = footerY + 32 * scale;
ctx.fillStyle = "#9ca3af";
ctx.font = `${12 * scale}px 'Roboto', sans-serif`;
ctx.fillText(i18n(I18nKey.author), authorTextX, textCenterY - 20 * scale);
ctx.fillStyle = "#1f2937";
ctx.font = `700 ${20 * scale}px 'Roboto', sans-serif`;
ctx.fillText(author, authorTextX, textCenterY + 4 * scale);
// Right: QR Code
const qrSize = 64 * scale;
const qrX = width - padding - qrSize;
// QR Background/Shadow effect (simplified as border)
ctx.fillStyle = "#ffffff";
// Shadow simulation
ctx.shadowColor = "rgba(0, 0, 0, 0.05)";
ctx.shadowBlur = 4 * scale;
ctx.shadowOffsetY = 2 * scale;
drawRoundedRect(ctx, qrX, footerY, qrSize, qrSize, 4 * scale);
ctx.fill();
ctx.shadowColor = "transparent"; // Reset shadow
// Draw QR
const qrInnerSize = 56 * scale;
const qrPadding = (qrSize - qrInnerSize) / 2;
if (qrImg) {
ctx.drawImage(
qrImg,
qrX + qrPadding,
footerY + qrPadding,
qrInnerSize,
qrInnerSize,
);
}
// Site Info (Left of QR)
const siteInfoX = qrX - 16 * scale;
ctx.textAlign = "right";
ctx.fillStyle = "#9ca3af";
ctx.font = `${12 * scale}px 'Roboto', sans-serif`;
ctx.fillText(i18n(I18nKey.scanToRead), siteInfoX, textCenterY - 20 * scale);
ctx.fillStyle = "#1f2937";
ctx.font = `700 ${20 * scale}px 'Roboto', sans-serif`;
ctx.fillText(siteTitle, siteInfoX, textCenterY + 4 * scale);
// Finalize
posterImage = canvas.toDataURL("image/png");
generating = false;
} catch (error) {
console.error("Failed to generate poster:", error);
generating = false;
}
}
function downloadPoster() {
if (posterImage) {
const a = document.createElement("a");
a.href = posterImage;
a.download = `poster-${title.replace(/\s+/g, "-")}.png`;
a.click();
}
}
function closeModal() {
showModal = false;
}
let copied = false;
function copyLink() {
navigator.clipboard.writeText(url);
copied = true;
setTimeout(() => {
copied = false;
}, 2000);
}
function portal(node: HTMLElement) {
document.body.appendChild(node);
return {
destroy() {
if (node.parentNode) {
node.parentNode.removeChild(node);
}
},
};
}
</script>
<!-- Trigger Button -->
<button
class="btn-regular rounded-lg h-12 px-6 gap-2 hover:scale-105 active:scale-95 whitespace-nowrap"
on:click={generatePoster}
aria-label="Generate Share Poster"
>
<Icon icon="material-symbols:share" size="md" />
<span>{i18n(I18nKey.shareArticle)}</span>
</button>
<!-- Modal -->
{#if showModal}
<!-- svelte-ignore a11y-click-events-have-key-events -->
<!-- svelte-ignore a11y-no-static-element-interactions -->
<div use:portal class="fixed inset-0 z-9999 flex items-center justify-center bg-black/60 backdrop-blur-xs p-4 transition-opacity" on:click={closeModal}>
<div class="bg-white dark:bg-gray-800 rounded-2xl max-w-[440px] w-full max-h-[90vh] overflow-y-auto flex flex-col shadow-2xl transform transition-all" on:click={(e) => e.stopPropagation()}>
<div class="p-6 flex justify-center bg-gray-50 dark:bg-gray-900 min-h-[200px] items-center">
{#if posterImage}
<img src={posterImage} alt="Poster" class="max-w-full h-auto shadow-lg rounded-lg" />
{:else}
<div class="flex flex-col items-center gap-3">
<div class="w-8 h-8 border-2 border-gray-200 rounded-full animate-spin" style="border-top-color: {themeColor}"></div>
<span class="text-sm text-gray-500">{i18n(I18nKey.generatingPoster)}</span>
</div>
{/if}
</div>
<div class="p-4 border-t border-gray-100 dark:border-gray-700 grid grid-cols-2 gap-3">
<button
class="py-3 bg-gray-100 dark:bg-gray-700 text-gray-700 dark:text-gray-200 rounded-xl font-medium hover:bg-gray-200 dark:hover:bg-gray-600 active:scale-[0.98] transition-all flex items-center justify-center gap-2"
on:click={copyLink}
>
{#if copied}
<Icon icon="material-symbols:check" size="md" />
<span>{i18n(I18nKey.copied)}</span>
{:else}
<Icon icon="material-symbols:link" size="md" />
<span>{i18n(I18nKey.copyLink)}</span>
{/if}
</button>
<button
class="py-3 text-white rounded-xl font-medium active:scale-[0.98] transition-all flex items-center justify-center gap-2 shadow-lg disabled:opacity-50 disabled:cursor-not-allowed hover:brightness-90"
style="background-color: {themeColor};"
on:click={downloadPoster}
disabled={!posterImage}
>
<Icon icon="material-symbols:download" size="md" />
{i18n(I18nKey.savePoster)}
</button>
</div>
</div>
</div>
{/if}
+191
View File
@@ -0,0 +1,191 @@
<script lang="ts">
import I18nKey from "@i18n/i18nKey";
import { i18n } from "@i18n/translation";
import { onMount } from "svelte";
import Icon from "@/components/common/Icon.svelte";
import type { SearchResult } from "@/global";
import { url as formatUrl } from "@/utils/url-utils";
// --- Props ---
export let title = i18n(I18nKey.search);
export let description = "";
// --- State ---
let keyword = "";
let results: SearchResult[] = [];
let isSearching = false;
let initialized = false;
// 在客户端获取 URL 参数
const getInitialKeyword = (): string => {
if (typeof window !== "undefined") {
const searchParams = new URLSearchParams(window.location.search);
return searchParams.get("q") || "";
}
return "";
};
// --- Mocks for Dev Mode ---
const fakeResult: SearchResult[] = [
{
url: formatUrl("/"),
meta: { title: "Dev Mode Search Result 1" },
excerpt: "This is a <mark>mock</mark> result for development.",
},
{
url: formatUrl("/"),
meta: { title: "Dev Mode Search Result 2" },
excerpt: "Pagefind only works in <mark>production</mark> build.",
},
];
// --- Core Search Logic ---
const search = async () => {
if (!initialized || !keyword.trim()) {
results = [];
return;
}
isSearching = true;
try {
if (import.meta.env.PROD && window.pagefind) {
const response = await window.pagefind.search(keyword);
const rawResults = await Promise.all(
response.results.map((item) => item.data()),
);
results = rawResults;
} else if (import.meta.env.DEV) {
// 开发模式下的模拟结果
results = fakeResult.filter(
(item) =>
item.excerpt.toLowerCase().includes(keyword.toLowerCase()) ||
item.meta.title.toLowerCase().includes(keyword.toLowerCase()),
);
}
} catch (error) {
console.error("Search error:", error);
results = [];
} finally {
isSearching = false;
}
};
// --- Initialization onMount ---
onMount(() => {
const initialize = async () => {
initialized = true;
// 从 URL 获取初始关键词
const initialKeyword = getInitialKeyword();
if (initialKeyword) {
keyword = initialKeyword;
}
// 如果有关键词,自动执行搜索
if (keyword.trim()) {
await search();
}
};
// 开发环境直接初始化
if (import.meta.env.DEV) {
initialize();
} else {
// 生产环境等待 Pagefind 加载
if (window.pagefind) {
initialize();
} else {
document.addEventListener("pagefindready", initialize, {
once: true,
});
}
}
});
let debounceTimer: NodeJS.Timeout;
const handleInput = () => {
clearTimeout(debounceTimer);
debounceTimer = setTimeout(() => {
search();
}, 300);
};
</script>
<div class="card-base px-6 py-6 md:px-9 md:py-6 mb-4 rounded-(--radius-large)">
<!-- Title Section -->
<div class="mb-4">
<div class="flex items-center gap-3 mb-3">
<div class="h-8 w-8 rounded-lg bg-(--primary) flex items-center justify-center text-white dark:text-black/70">
<Icon icon="material-symbols:search" class="text-[1.5rem]"></Icon>
</div>
<div class="text-3xl font-bold text-90">
{title}
</div>
</div>
{#if description}
<p class="text-base text-50 leading-relaxed">
{description}
</p>
{/if}
</div>
<!-- Search Bar -->
<div class="relative flex">
<div class="relative flex-1">
<div class="absolute inset-y-0 left-0 flex items-center pl-3 pointer-events-none">
<Icon icon="material-symbols:search" class="text-2xl text-50" />
</div>
<input
type="text"
class="block w-full p-4 pl-10 text-sm bg-transparent border border-black/10 dark:border-white/10 rounded-lg focus:ring-2 focus:ring-(--primary) focus:border-(--primary) hover:border-black/20 dark:hover:border-white/20 text-75 placeholder:opacity-50 transition-colors outline-hidden"
placeholder={i18n(I18nKey.search)}
bind:value={keyword}
on:input={handleInput}
>
</div>
</div>
</div>
<div class="grid grid-cols-1 gap-4">
<!-- Results Area -->
<div>
{#if isSearching}
<div class="flex justify-center py-10">
<Icon icon="svg-spinners:ring-resize" class="text-4xl text-(--primary)" />
</div>
{:else if results.length > 0}
<div class="space-y-4">
{#each results as result}
<div class="card-base p-6 block rounded-(--radius-large)">
<a href={result.url} class="block group">
<h5 class="mb-2 text-2xl font-bold tracking-tight text-90 group-hover:text-(--primary) transition-colors">
{@html result.meta.title}
</h5>
<p class="font-normal text-75">
{@html result.excerpt}
</p>
</a>
</div>
{/each}
</div>
{:else if keyword}
<div class="card-base p-10 text-center text-50 rounded-(--radius-large)">
{i18n(I18nKey.searchNoResults)}
</div>
{:else}
<div class="card-base p-10 text-center text-50 rounded-(--radius-large)">
{i18n(I18nKey.searchTypeSomething)}
</div>
{/if}
</div>
</div>
<style>
/* 关键字高亮效果 - 主题色 */
:global(mark) {
background: transparent;
color: var(--primary);
font-weight: 600;
padding: 0 0.1em;
}
</style>
+143
View File
@@ -0,0 +1,143 @@
<script lang="ts">
import I18nKey from "@/i18n/i18nKey";
import { i18n } from "@/i18n/translation";
import type { StandardizedAnime } from "@/types/anime";
interface Props {
anime: StandardizedAnime;
onclick?: (anime: StandardizedAnime) => void;
}
let { anime, onclick }: Props = $props();
function handleLoad(e: Event) {
const img = e.currentTarget as HTMLImageElement;
img.style.opacity = "1";
const ph = img.parentElement?.querySelector(".lqip-placeholder");
if (ph) ph.classList.add("loaded");
}
function handleClick() {
onclick?.(anime);
}
const SEASON_TYPE_I18N: Record<number, I18nKey> = {
1: I18nKey.animeTypeAnime,
2: I18nKey.animeTypeMovie,
3: I18nKey.animeTypeDocumentary,
4: I18nKey.animeTypeChinese,
5: I18nKey.animeTypeDrama,
7: I18nKey.animeTypeConcert,
};
const SEASON_TYPE_COLORS: Record<number, string> = {
1: "bg-blue-500",
2: "bg-purple-500",
3: "bg-emerald-500",
4: "bg-orange-500",
5: "bg-pink-500",
7: "bg-yellow-500",
};
function getTypeLabel(seasonType: number): string {
return i18n(SEASON_TYPE_I18N[seasonType] || I18nKey.animeTypeAnime);
}
function getTypeColor(seasonType: number): string {
return SEASON_TYPE_COLORS[seasonType] || "bg-gray-500";
}
</script>
<div
class="anime-card group relative overflow-hidden rounded-xl border border-(--line-divider) bg-(--card-bg) cursor-pointer transition-all duration-300 hover:shadow-lg hover:border-(--primary)/30 hover:-translate-y-1"
onclick={handleClick}
onkeydown={(e) => e.key === "Enter" && handleClick()}
role="button"
tabindex="0"
>
<!-- 海报 -->
<div class="relative aspect-2/3 overflow-hidden bg-neutral-100 dark:bg-neutral-800">
{#if anime.poster}
<div class="lqip-placeholder absolute inset-0 pointer-events-none" style="background: var(--muted)" aria-hidden="true"></div>
<img
src={anime.poster}
alt={anime.title}
class="h-full w-full object-cover transition-all duration-500 group-hover:scale-110 opacity-0"
loading="eager"
decoding="async"
referrerpolicy="no-referrer"
crossorigin="anonymous"
onload={handleLoad}
/>
{:else}
<div class="flex h-full w-full items-center justify-center">
<svg class="h-12 w-12 text-neutral-300 dark:text-neutral-600" fill="none" viewBox="0 0 24 24" stroke="currentColor">
<path stroke-linecap="round" stroke-linejoin="round" stroke-width="1.5" d="m2.25 15.75 5.159-5.159a2.25 2.25 0 0 1 3.182 0l5.159 5.159m-1.5-1.5 1.409-1.409a2.25 2.25 0 0 1 3.182 0l2.909 2.909M3.75 21h16.5A2.25 2.25 0 0 0 22.5 18.75V5.25A2.25 2.25 0 0 0 20.25 3H3.75A2.25 2.25 0 0 0 1.5 5.25v13.5A2.25 2.25 0 0 0 3.75 21Z" />
</svg>
</div>
{/if}
<!-- 评分角标(右上) -->
{#if anime.rating > 0}
<div class="absolute top-2 right-2 flex items-center gap-1 rounded-lg bg-black/70 backdrop-blur-sm px-2 py-1 text-xs font-bold text-white">
<svg class="h-3 w-3 text-yellow-400" fill="currentColor" viewBox="0 0 20 20">
<path d="M9.049 2.927c.3-.921 1.603-.921 1.902 0l1.07 3.292a1 1 0 00.95.69h3.462c.969 0 1.371 1.24.588 1.81l-2.8 2.034a1 1 0 00-.364 1.118l1.07 3.292c.3.921-.755 1.688-1.54 1.118l-2.8-2.034a1 1 0 00-1.175 0l-2.8 2.034c-.784.57-1.838-.197-1.539-1.118l1.07-3.292a1 1 0 00-.364-1.118L2.98 8.72c-.783-.57-.38-1.81.588-1.81h3.461a1 1 0 00.951-.69l1.07-3.292z" />
</svg>
{anime.rating.toFixed(1)}
</div>
{/if}
<!-- 类型角标(左上) -->
<div class="absolute top-2 left-2 rounded-lg {getTypeColor(anime.season_type)} px-2 py-1 text-xs font-bold text-white backdrop-blur-sm">
{getTypeLabel(anime.season_type)}
</div>
<!-- 来源标签 -->
<div class="absolute bottom-2 left-2 rounded-md {anime.source === 'bilibili' ? 'bg-pink-500/80' : 'bg-emerald-500/80'} px-2 py-0.5 text-[10px] font-medium text-white backdrop-blur-sm">
{anime.source === 'bilibili' ? 'Bilibili' : 'TMDB'}
</div>
<!-- 悬停遮罩 -->
<div class="absolute inset-0 flex flex-col justify-end bg-linear-to-t from-black/80 via-black/40 to-transparent opacity-0 transition-opacity duration-300 group-hover:opacity-100">
<div class="p-3">
<p class="mb-2 line-clamp-3 text-xs text-white/90 leading-relaxed">{anime.overview || i18n(I18nKey.animeNoOverview)}</p>
<button class="w-full rounded-lg bg-(--primary) px-3 py-1.5 text-xs font-medium text-white transition-colors hover:bg-(--primary)/80">
{i18n(I18nKey.animeViewDetails)}
</button>
</div>
</div>
</div>
<!-- 底部信息 -->
<div class="p-3">
<!-- 标题 -->
<h3 class="mb-1 line-clamp-1 text-sm font-semibold text-neutral-900 dark:text-neutral-100" title={anime.title}>
{anime.title}
</h3>
<!-- 原文标题 -->
{#if anime.originalTitle && anime.originalTitle !== anime.title}
<p class="mb-2 line-clamp-1 text-xs text-neutral-500 dark:text-neutral-400" title={anime.originalTitle}>
{anime.originalTitle}
</p>
{/if}
<!-- 底部信息行 -->
<div class="flex items-center justify-between text-xs text-neutral-500 dark:text-neutral-400">
<span>{anime.epStatus || anime.date?.slice(0, 4) || ""}</span>
</div>
</div>
</div>
<style>
.line-clamp-1 {
display: -webkit-box;
line-clamp: 1;
-webkit-box-orient: vertical;
overflow: hidden;
}
.line-clamp-3 {
display: -webkit-box;
line-clamp: 3;
-webkit-box-orient: vertical;
overflow: hidden;
}
</style>
@@ -0,0 +1,199 @@
<script lang="ts">
import I18nKey from "@/i18n/i18nKey";
import { i18n } from "@/i18n/translation";
import type { StandardizedAnime } from "@/types/anime";
interface Props {
anime: StandardizedAnime | null;
onclose: () => void;
}
let { anime, onclose }: Props = $props();
/** 将元素挂载到 body,脱离 overflow:hidden 容器 */
function portal(node: HTMLElement) {
document.body.appendChild(node);
return {
destroy() {
node.remove();
},
};
}
function handleBackdropClick(e: MouseEvent) {
if (e.target === e.currentTarget) {
onclose();
}
}
function handleKeydown(e: KeyboardEvent) {
if (e.key === "Escape") {
onclose();
}
}
const SEASON_TYPE_I18N: Record<number, I18nKey> = {
1: I18nKey.animeTypeAnime,
2: I18nKey.animeTypeMovie,
3: I18nKey.animeTypeDocumentary,
4: I18nKey.animeTypeChinese,
5: I18nKey.animeTypeDrama,
7: I18nKey.animeTypeConcert,
};
const SEASON_TYPE_COLORS: Record<number, string> = {
1: "bg-blue-500",
2: "bg-purple-500",
3: "bg-emerald-500",
4: "bg-orange-500",
5: "bg-pink-500",
7: "bg-yellow-500",
};
function getTypeLabel(seasonType: number): string {
return i18n(SEASON_TYPE_I18N[seasonType] || I18nKey.animeTypeAnime);
}
function getTypeColor(seasonType: number): string {
return SEASON_TYPE_COLORS[seasonType] || "bg-gray-500";
}
</script>
<svelte:window onkeydown={handleKeydown} />
{#if anime}
<div
use:portal
class="fixed inset-0 z-50 flex items-center justify-center bg-black/60 backdrop-blur-sm p-4"
onclick={handleBackdropClick}
onkeydown={handleKeydown}
role="dialog"
aria-modal="true"
tabindex="-1"
>
<div class="relative w-full max-w-lg max-h-[90vh] overflow-hidden rounded-xl sm:rounded-2xl bg-(--card-bg) border border-(--line-divider) shadow-2xl animate-in scale-90 sm:scale-100">
<!-- 关闭按钮 -->
<button
class="absolute top-4 right-4 z-10 flex h-8 w-8 items-center justify-center rounded-full bg-black/50 text-white backdrop-blur-sm transition-colors hover:bg-black/70"
onclick={onclose}
aria-label={i18n(I18nKey.animeClose)}
>
<svg class="h-4 w-4" fill="none" viewBox="0 0 24 24" stroke="currentColor">
<path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M6 18L18 6M6 6l12 12" />
</svg>
</button>
<!-- 内容区域 -->
<div class="flex flex-col md:flex-row">
<!-- 海报 -->
<div class="relative w-full md:w-64 lg:w-72 shrink-0 h-48 sm:h-64 md:aspect-auto md:h-auto bg-neutral-100 dark:bg-neutral-800 overflow-hidden">
{#if anime.poster}
<div class="lqip-placeholder absolute inset-0 pointer-events-none" style="background: var(--muted)" aria-hidden="true"></div>
<img
src={anime.poster}
alt={anime.title}
class="h-full w-full object-cover opacity-0 transition-opacity duration-500"
referrerpolicy="no-referrer"
crossorigin="anonymous"
onload={(e) => {
const img = e.currentTarget as HTMLElement;
img.style.opacity = '1';
const ph = img.parentElement?.querySelector('.lqip-placeholder');
if (ph) ph.classList.add('loaded');
}}
/>
{:else}
<div class="flex h-full min-h-[300px] items-center justify-center">
<svg class="h-16 w-16 text-neutral-300 dark:text-neutral-600" fill="none" viewBox="0 0 24 24" stroke="currentColor">
<path stroke-linecap="round" stroke-linejoin="round" stroke-width="1.5" d="m2.25 15.75 5.159-5.159a2.25 2.25 0 0 1 3.182 0l5.159 5.159m-1.5-1.5 1.409-1.409a2.25 2.25 0 0 1 3.182 0l2.909 2.909M3.75 21h16.5A2.25 2.25 0 0 0 22.5 18.75V5.25A2.25 2.25 0 0 0 20.25 3H3.75A2.25 2.25 0 0 0 1.5 5.25v13.5A2.25 2.25 0 0 0 3.75 21Z" />
</svg>
</div>
{/if}
</div>
<!-- 详情 -->
<div class="flex-1 p-4 sm:p-6 overflow-y-auto max-h-[60vh] md:max-h-none">
<!-- 标题 -->
<h2 class="mb-1 text-xl sm:text-2xl font-bold text-neutral-900 dark:text-neutral-100">
{anime.title}
</h2>
{#if anime.originalTitle && anime.originalTitle !== anime.title}
<p class="mb-4 text-sm text-neutral-500 dark:text-neutral-400">
{anime.originalTitle}
</p>
{/if}
<!-- 徽章 -->
<div class="mb-4 flex flex-wrap gap-2">
<span class="inline-flex items-center gap-1 rounded-lg {getTypeColor(anime.season_type)} px-3 py-1 text-xs font-bold text-white">
{getTypeLabel(anime.season_type)}
</span>
{#if anime.rating > 0}
<span class="inline-flex items-center gap-1 rounded-lg bg-yellow-500/10 border border-yellow-500/20 px-3 py-1 text-xs font-bold text-yellow-600 dark:text-yellow-400">
<svg class="h-3 w-3" fill="currentColor" viewBox="0 0 20 20">
<path d="M9.049 2.927c.3-.921 1.603-.921 1.902 0l1.07 3.292a1 1 0 00.95.69h3.462c.969 0 1.371 1.24.588 1.81l-2.8 2.034a1 1 0 00-.364 1.118l1.07 3.292c.3.921-.755 1.688-1.54 1.118l-2.8-2.034a1 1 0 00-1.175 0l-2.8 2.034c-.784.57-1.838-.197-1.539-1.118l1.07-3.292a1 1 0 00-.364-1.118L2.98 8.72c-.783-.57-.38-1.81.588-1.81h3.461a1 1 0 00.951-.69l1.07-3.292z" />
</svg>
{anime.rating.toFixed(1)}
</span>
{/if}
{#if anime.epStatus}
<span class="inline-flex items-center rounded-lg bg-blue-500/10 border border-blue-500/20 px-3 py-1 text-xs font-bold text-blue-600 dark:text-blue-400">
{anime.epStatus}
</span>
{/if}
<span class="inline-flex items-center rounded-lg {anime.source === 'bilibili' ? 'bg-pink-500/10 border-pink-500/20 text-pink-600 dark:text-pink-400' : 'bg-emerald-500/10 border-emerald-500/20 text-emerald-600 dark:text-emerald-400'} border px-3 py-1 text-xs font-bold">
{anime.source === 'bilibili' ? 'Bilibili' : 'TMDB'}
</span>
</div>
<!-- 简介 -->
{#if anime.overview}
<div class="mb-6">
<h3 class="mb-2 text-sm font-semibold text-neutral-700 dark:text-neutral-300">{i18n(I18nKey.animeSynopsis)}</h3>
<p class="text-sm text-neutral-600 dark:text-neutral-400 leading-relaxed max-h-40 overflow-y-auto">
{anime.overview}
</p>
</div>
{/if}
<!-- 跳转按钮 -->
<a
href={anime.link}
target="_blank"
rel="noopener noreferrer"
class="inline-flex w-full items-center justify-center gap-2 rounded-xl bg-(--primary) px-6 py-3 text-sm font-semibold text-white transition-all hover:bg-(--primary)/90 hover:shadow-lg"
>
{#if anime.source === 'bilibili'}
<svg class="h-4 w-4" fill="none" viewBox="0 0 24 24" stroke="currentColor">
<path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M14.752 11.168l-3.197-2.132A1 1 0 0010 9.87v4.263a1 1 0 001.555.832l3.197-2.132a1 1 0 000-1.664z" />
<path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M21 12a9 9 0 11-18 0 9 9 0 0118 0z" />
</svg>
{i18n(I18nKey.animeWatchNow)}
{:else}
<svg class="h-4 w-4" fill="none" viewBox="0 0 24 24" stroke="currentColor">
<path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M10 6H6a2 2 0 00-2 2v10a2 2 0 002 2h10a2 2 0 002-2v-4M14 4h6m0 0v6m0-6L10 14" />
</svg>
{i18n(I18nKey.animeViewTmdb)}
{/if}
</a>
</div>
</div>
</div>
</div>
{/if}
<style>
@keyframes animate-in {
from {
opacity: 0;
transform: translateY(10px);
}
to {
opacity: 1;
transform: translateY(0);
}
}
.animate-in {
animation: animate-in 0.2s ease-out;
}
</style>
+205
View File
@@ -0,0 +1,205 @@
<script lang="ts">
import ClientPagination from "@components/common/ClientPagination.svelte";
import { untrack } from "svelte";
import I18nKey from "@/i18n/i18nKey";
import { i18n } from "@/i18n/translation";
import type { StandardizedAnime } from "@/types/anime";
import TabNav from "../bangumi/TabNav.svelte";
import AnimeCard from "./AnimeCard.svelte";
import AnimeDetailModal from "./AnimeDetailModal.svelte";
interface Props {
items: StandardizedAnime[];
bilibiliAverageRating?: string;
itemsPerPage?: number;
}
let { items, bilibiliAverageRating, itemsPerPage = 24 }: Props = $props();
// 状态
let searchQuery = $state("");
let activeFilter = $state(
untrack(() =>
String(
[...new Set(items.map((i) => i.season_type || 1))].sort(
(a, b) => a - b,
)[0] || "",
),
),
);
let sortBy = $state<"rating-desc" | "rating-asc" | "date-desc" | "date-asc">(
"rating-desc",
);
let currentPage = $state(1);
let selectedAnime = $state<StandardizedAnime | null>(null);
// season_type 到 i18n key 的映射
const SEASON_TYPE_I18N: Record<number, I18nKey> = {
1: I18nKey.animeTypeAnime,
2: I18nKey.animeTypeMovie,
3: I18nKey.animeTypeDocumentary,
4: I18nKey.animeTypeChinese,
5: I18nKey.animeTypeDrama,
7: I18nKey.animeTypeConcert,
};
// 动态生成筛选项:从数据中提取实际存在的 season_type
let filterOptions = $derived(() => {
const typeMap = new Map<number, number>();
for (const item of items) {
const st = item.season_type || 1;
typeMap.set(st, (typeMap.get(st) || 0) + 1);
}
// 按 season_type 排序
return Array.from(typeMap.entries())
.sort(([a], [b]) => a - b)
.map(([type, count]) => ({
value: String(type),
label: i18n(SEASON_TYPE_I18N[type] || I18nKey.animeTypeAnime),
count,
}));
});
// 筛选和排序后的数据
let filteredItems = $derived(() => {
let result = [...items];
// 搜索过滤
if (searchQuery.trim()) {
const query = searchQuery.toLowerCase().trim();
result = result.filter(
(item) =>
item.title.toLowerCase().includes(query) ||
item.originalTitle.toLowerCase().includes(query),
);
}
// 类型过滤
if (activeFilter) {
const filterType = Number(activeFilter);
result = result.filter((item) => (item.season_type || 1) === filterType);
}
// 排序
switch (sortBy) {
case "rating-desc":
result.sort((a, b) => b.rating - a.rating);
break;
case "rating-asc":
result.sort((a, b) => a.rating - b.rating);
break;
case "date-desc":
result.sort((a, b) => (b.date || "").localeCompare(a.date || ""));
break;
case "date-asc":
result.sort((a, b) => (a.date || "").localeCompare(b.date || ""));
break;
}
return result;
});
// 分页
let pagedItems = $derived(() => {
const start = (currentPage - 1) * itemsPerPage;
return filteredItems().slice(start, start + itemsPerPage);
});
// 筛选/搜索变化时重置到第一页
function resetPage() {
currentPage = 1;
}
function handleSearch(e: Event) {
searchQuery = (e.target as HTMLInputElement).value;
resetPage();
}
function setFilter(filter: string) {
activeFilter = activeFilter === filter ? "" : filter;
resetPage();
}
function setSort(sort: typeof sortBy) {
sortBy = sort;
resetPage();
}
function goToPage(page: number) {
currentPage = page;
}
function openDetail(anime: StandardizedAnime) {
selectedAnime = anime;
}
function closeDetail() {
selectedAnime = null;
}
</script>
<div class="anime-grid">
<!-- 工具栏 -->
<div class="mb-6 flex flex-col gap-3">
<!-- 搜索和排序 -->
<div class="flex gap-2">
<div class="relative flex-1">
<svg class="absolute left-3 top-1/2 h-4 w-4 -translate-y-1/2 text-neutral-400" fill="none" viewBox="0 0 24 24" stroke="currentColor">
<path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M21 21l-6-6m2-5a7 7 0 11-14 0 7 7 0 0114 0z" />
</svg>
<input
type="text"
placeholder={i18n(I18nKey.animeSearch)}
value={searchQuery}
oninput={handleSearch}
class="w-full rounded-xl border border-(--line-divider) bg-(--card-bg) py-2.5 pl-10 pr-4 text-sm text-neutral-900 dark:text-neutral-100 placeholder-neutral-400 outline-none transition-colors focus:border-(--primary)"
/>
</div>
<select
value={sortBy}
onchange={(e) => setSort((e.target as HTMLSelectElement).value as typeof sortBy)}
class="rounded-xl border border-(--line-divider) bg-(--card-bg) px-3 text-sm text-neutral-600 dark:text-neutral-400 outline-none cursor-pointer shrink-0"
>
<option value="rating-desc">{i18n(I18nKey.animeRatingDesc)}</option>
<option value="rating-asc">{i18n(I18nKey.animeRatingAsc)}</option>
<option value="date-desc">{i18n(I18nKey.animeDateDesc)}</option>
<option value="date-asc">{i18n(I18nKey.animeDateAsc)}</option>
</select>
</div>
<!-- 类型筛选 -->
<TabNav
tabs={filterOptions().map(opt => ({ id: opt.value, name: opt.label, count: opt.count }))}
activeTab={activeFilter}
onTabChange={setFilter}
/>
</div>
<!-- 卡片网格 -->
{#if pagedItems().length > 0}
<div class="anime-card-grid grid grid-cols-2 sm:grid-cols-3 lg:grid-cols-4 xl:grid-cols-5 gap-4">
{#each pagedItems() as anime (anime.id)}
<AnimeCard {anime} onclick={openDetail} />
{/each}
</div>
{:else}
<div class="py-16 text-center">
<svg class="mx-auto h-12 w-12 text-neutral-300 dark:text-neutral-600 mb-4" fill="none" viewBox="0 0 24 24" stroke="currentColor">
<path stroke-linecap="round" stroke-linejoin="round" stroke-width="1.5" d="M21 21l-6-6m2-5a7 7 0 11-14 0 7 7 0 0114 0z" />
</svg>
<p class="text-neutral-500 dark:text-neutral-400">{i18n(I18nKey.animeNoResults)}</p>
</div>
{/if}
<!-- 分页 -->
<ClientPagination
totalItems={filteredItems().length}
{itemsPerPage}
{currentPage}
onPageChange={goToPage}
/>
</div>
<!-- 详情弹窗 -->
<AnimeDetailModal anime={selectedAnime} onclose={closeDetail} />
@@ -0,0 +1,241 @@
<script lang="ts">
import { onMount } from "svelte";
import I18nKey from "@/i18n/i18nKey";
import { i18n } from "@/i18n/translation";
import type { UserSubjectCollection } from "@/types/bangumi";
import BangumiSection from "./BangumiSection.svelte";
import TabNav from "./TabNav.svelte";
interface Props {
// 静态模式:直接传入数据
tabs?: Array<{ id: string; name: string; count: number }>;
initialActiveTab?: string;
bangumiData?: Record<string, UserSubjectCollection[]>;
subjectBaseUrl?: string;
// 动态模式:传入获取配置
fetchConfig?: {
username: string;
apiUrl: string;
categories: Record<string, boolean>;
categoryOrder: string[];
pagination: { limit: number; delay: number; maxTotal: number };
};
}
const {
tabs: staticTabs,
initialActiveTab,
bangumiData: staticData,
subjectBaseUrl,
fetchConfig,
}: Props = $props();
const isDynamic = $derived(!!fetchConfig);
// 状态
let activeTab = $state("");
let fetchLoading = $state(false);
const loading = $derived(isDynamic && fetchLoading);
let error = $state(false);
// 初始化 activeTab / 当 fetchConfig 变化时重置状态
$effect(() => {
if (initialActiveTab) {
activeTab = initialActiveTab;
}
if (fetchConfig) {
fetchLoading = true;
error = false;
}
});
let errorTitle = $state("");
let errorDesc = $state("");
let updateTimestamp = $state("");
// 动态模式的数据
let dynamicTabs = $state<Array<{ id: string; name: string; count: number }>>(
[],
);
let dynamicData = $state<Record<string, UserSubjectCollection[]>>({});
// 合并后的数据
const tabs = $derived(staticTabs || dynamicTabs);
const bangumiData = $derived(staticData || dynamicData);
const categoryMap: Record<string, { name: string; subjectType: number }> = {
book: { name: i18n(I18nKey.bangumiCategoryBook), subjectType: 1 },
anime: { name: i18n(I18nKey.bangumiCategoryAnime), subjectType: 2 },
music: { name: i18n(I18nKey.bangumiCategoryMusic), subjectType: 3 },
game: { name: i18n(I18nKey.bangumiCategoryGame), subjectType: 4 },
real: { name: i18n(I18nKey.bangumiCategoryReal), subjectType: 6 },
};
function handleTabChange(tabId: string) {
activeTab = tabId;
}
async function fetchCategory(
apiUrl: string,
username: string,
subjectType: number,
pagination: { limit: number; delay: number; maxTotal: number },
): Promise<UserSubjectCollection[]> {
const { limit, delay, maxTotal } = pagination;
let offset = 0;
const allItems: UserSubjectCollection[] = [];
while (true) {
if (maxTotal > 0 && allItems.length >= maxTotal) break;
const url = `${apiUrl}/v0/users/${username}/collections?subject_type=${subjectType}&limit=${limit}&offset=${offset}`;
const resp = await fetch(url, { headers: { Accept: "application/json" } });
if (!resp.ok) throw new Error(`HTTP ${resp.status}`);
const data = await resp.json();
const batch: UserSubjectCollection[] = data.data || [];
if (batch.length > 0) {
allItems.push(...batch);
offset += limit;
if (batch.length < limit) break;
await new Promise((r) => setTimeout(r, delay));
} else {
break;
}
}
return allItems;
}
async function loadDynamicData() {
if (!fetchConfig) return;
const { username, apiUrl, categories, categoryOrder, pagination } =
fetchConfig;
const enabled: string[] = [];
for (const [k, v] of Object.entries(categories)) {
if (v) enabled.push(k);
}
if (categoryOrder.length > 0) {
enabled.sort((a, b) => {
const ai = categoryOrder.indexOf(a);
const bi = categoryOrder.indexOf(b);
if (ai === -1 && bi === -1) return 0;
if (ai === -1) return 1;
if (bi === -1) return -1;
return ai - bi;
});
}
const newTabs: Array<{ id: string; name: string; count: number }> = [];
const newData: Record<string, UserSubjectCollection[]> = {};
for (const catKey of enabled) {
const info = categoryMap[catKey];
if (!info) continue;
try {
const data = await fetchCategory(
apiUrl,
username,
info.subjectType,
pagination,
);
newData[catKey] = data;
newTabs.push({ id: catKey, name: info.name, count: data.length });
} catch (e) {
console.error(`[Bangumi] 获取 ${catKey} 数据失败:`, e);
fetchLoading = false;
error = true;
errorTitle = i18n(I18nKey.bangumiFetchError);
errorDesc = i18n(I18nKey.bangumiFetchErrorDesc);
return;
}
}
if (newTabs.length === 0 || newTabs.every((t) => t.count === 0)) {
fetchLoading = false;
error = true;
errorTitle = i18n(I18nKey.bangumiNoData);
errorDesc = i18n(I18nKey.bangumiNoDataDescription);
return;
}
dynamicTabs = newTabs;
dynamicData = newData;
activeTab = newTabs[0].id;
fetchLoading = false;
const now = new Date();
const pad = (n: number) => (n < 10 ? `0${n}` : String(n));
updateTimestamp = `${now.getFullYear()}-${pad(now.getMonth() + 1)}-${pad(now.getDate())} ${pad(now.getHours())}:${pad(now.getMinutes())}`;
}
// 从 URL hash 恢复 tab
function restoreTabFromHash() {
if (!isDynamic) {
const hash = window.location.hash.replace(/^#/, "");
if (hash) {
try {
const decoded = decodeURIComponent(hash);
if (tabs.some((t) => t.id === decoded)) {
activeTab = decoded;
}
} catch {}
}
}
}
onMount(async () => {
restoreTabFromHash();
if (isDynamic) {
await loadDynamicData();
}
});
</script>
{#if isDynamic && loading}
<!-- Tab 骨架 -->
<div class="border-b border-(--line-divider) mb-3">
<div class="flex min-w-max space-x-8">
{#each [1, 2, 3, 4] as _}
<div class="h-10 w-20 bg-(--btn-regular-bg) rounded animate-pulse"></div>
{/each}
</div>
</div>
<!-- 筛选骨架 -->
<div class="flex flex-wrap gap-1.5 mb-4">
{#each [1, 2, 3, 4] as _}
<div class="h-7 w-16 bg-(--btn-regular-bg) rounded-full animate-pulse"></div>
{/each}
</div>
<!-- 卡片网格骨架 -->
<div class="bangumi-masonry grid grid-cols-2 sm:grid-cols-3 lg:grid-cols-4 xl:grid-cols-5 gap-3">
{#each [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12] as _}
<div class="rounded-xl overflow-hidden">
<div class="aspect-2/3 bg-(--btn-regular-bg) animate-pulse"></div>
</div>
{/each}
</div>
<!-- 分页骨架 -->
<div class="mt-6 flex items-center justify-center gap-3">
<div class="w-11 h-11 bg-(--btn-regular-bg) rounded-lg animate-pulse"></div>
<div class="w-16 h-8 bg-(--btn-regular-bg) rounded animate-pulse"></div>
<div class="w-11 h-11 bg-(--btn-regular-bg) rounded-lg animate-pulse"></div>
</div>
{:else if isDynamic && error}
<div class="text-center py-16">
<div class="inline-flex items-center justify-center w-16 h-16 bg-(--btn-regular-bg) rounded-full mb-6 border border-(--line-divider)">
<span class="text-[2rem] text-red-500">⚠</span>
</div>
<h2 class="text-xl font-semibold text-black/80 dark:text-white/80 mb-3">{errorTitle}</h2>
<p class="text-black/60 dark:text-white/60 mb-4 max-w-md mx-auto">{errorDesc}</p>
</div>
{:else if tabs.length > 0}
<TabNav {tabs} {activeTab} onTabChange={handleTabChange} />
{#each tabs as tab (tab.id)}
<BangumiSection
sectionId={tab.id}
items={bangumiData[tab.id] || []}
isActive={tab.id === activeTab}
itemsPerPage={24}
{subjectBaseUrl}
/>
{/each}
{/if}
@@ -0,0 +1,189 @@
<script lang="ts">
import ClientPagination from "@/components/common/ClientPagination.svelte";
import I18nKey from "@/i18n/i18nKey";
import { i18n } from "@/i18n/translation";
import type { UserSubjectCollection } from "@/types/bangumi";
import Card from "./Card.svelte";
import FilterControls from "./FilterControls.svelte";
interface Props {
sectionId: string;
items: UserSubjectCollection[];
isActive: boolean;
itemsPerPage?: number;
subjectBaseUrl?: string;
}
const {
sectionId,
items,
isActive,
itemsPerPage = 24,
subjectBaseUrl,
}: Props = $props();
const STATUS_MAP: Record<number, string> = {
1: "wish",
2: "collect",
3: "doing",
4: "on_hold",
5: "dropped",
};
const isGame = $derived(sectionId === "game");
const isBook = $derived(sectionId === "book");
const isMusic = $derived(sectionId === "music");
function getFilterLabel(type: "collect" | "doing" | "wish"): string {
if (isGame) {
switch (type) {
case "collect":
return i18n(I18nKey.bangumiFilterGamePlayed);
case "doing":
return i18n(I18nKey.bangumiFilterGamePlaying);
case "wish":
return i18n(I18nKey.bangumiFilterGameWish);
}
}
if (isBook) {
switch (type) {
case "collect":
return i18n(I18nKey.bangumiFilterBookRead);
case "doing":
return i18n(I18nKey.bangumiFilterBookReading);
case "wish":
return i18n(I18nKey.bangumiFilterBookWish);
}
}
if (isMusic) {
switch (type) {
case "collect":
return i18n(I18nKey.bangumiFilterMusicListened);
case "doing":
return i18n(I18nKey.bangumiFilterMusicListening);
case "wish":
return i18n(I18nKey.bangumiFilterMusicWish);
}
}
switch (type) {
case "collect":
return i18n(I18nKey.bangumiFilterWatched);
case "doing":
return i18n(I18nKey.bangumiFilterWatching);
case "wish":
return i18n(I18nKey.bangumiFilterWish);
}
}
const statusCounts = $derived(() => {
const counts: Record<string, number> = {};
for (const item of items) {
const status =
STATUS_MAP[item.type as keyof typeof STATUS_MAP] || "unknown";
counts[status] = (counts[status] || 0) + 1;
}
return counts;
});
const filters = $derived(() => {
const counts = statusCounts();
return [
{
value: "all",
label: i18n(I18nKey.bangumiFilterAll),
count: items.length,
},
{
value: "collect",
label: getFilterLabel("collect"),
count: counts.collect || 0,
},
{
value: "doing",
label: getFilterLabel("doing"),
count: counts.doing || 0,
},
{ value: "wish", label: getFilterLabel("wish"), count: counts.wish || 0 },
{
value: "on_hold",
label: i18n(I18nKey.bangumiFilterOnHold),
count: counts.on_hold || 0,
},
{
value: "dropped",
label: i18n(I18nKey.bangumiFilterDropped),
count: counts.dropped || 0,
},
].filter((f) => f.value === "all" || f.count > 0);
});
let activeFilter = $state("all");
let currentPage = $state(1);
const filteredItems = $derived(
activeFilter === "all"
? items
: items.filter(
(item) =>
(STATUS_MAP[item.type as keyof typeof STATUS_MAP] || "unknown") ===
activeFilter,
),
);
const totalPages = $derived(
Math.max(1, Math.ceil(filteredItems.length / itemsPerPage)),
);
const pagedItems = $derived(
filteredItems.slice(
(currentPage - 1) * itemsPerPage,
currentPage * itemsPerPage,
),
);
function handleFilterChange(filter: string) {
activeFilter = filter;
currentPage = 1;
}
function goToPage(page: number) {
if (page >= 1 && page <= totalPages) {
currentPage = page;
}
}
</script>
<div class="bangumi-section" class:hidden={!isActive} data-section={sectionId}>
{#if items.length > 0}
<FilterControls
filters={filters()}
activeFilter={activeFilter}
onFilterChange={handleFilterChange}
/>
<div class="bangumi-masonry grid grid-cols-2 sm:grid-cols-3 lg:grid-cols-4 xl:grid-cols-5 gap-3">
{#each pagedItems as item (item.subject_id)}
<div
class="bangumi-item"
data-item-section={sectionId}
data-item-status={STATUS_MAP[item.type as keyof typeof STATUS_MAP] || "unknown"}
>
<Card item={item} loadImage={isActive} {subjectBaseUrl} />
</div>
{/each}
</div>
<ClientPagination
totalItems={filteredItems.length}
itemsPerPage={itemsPerPage}
currentPage={currentPage}
onPageChange={goToPage}
/>
{:else}
<div class="text-center py-12">
<h3 class="text-xl font-medium text-gray-600 dark:text-gray-400 mb-2">{i18n(I18nKey.bangumiNoData)}</h3>
<p class="text-gray-500 dark:text-gray-500">{i18n(I18nKey.bangumiNoDataDescription)}</p>
</div>
{/if}
</div>
+151
View File
@@ -0,0 +1,151 @@
<script lang="ts">
import I18nKey from "@/i18n/i18nKey";
import { i18n } from "@/i18n/translation";
import type { UserSubjectCollection } from "@/types/bangumi";
interface Props {
item: UserSubjectCollection;
loadImage?: boolean;
subjectBaseUrl?: string;
}
const {
item,
loadImage = false,
subjectBaseUrl = "https://bangumi.one/subject/",
}: Props = $props();
const STATUS_COLORS: Record<number, string> = {
1: "bg-blue-500",
2: "bg-green-500",
3: "bg-yellow-500",
4: "bg-orange-500",
5: "bg-red-500",
};
function getStatusText(type: number): string {
const subjectType = item.subject?.type;
switch (type) {
case 1:
if (subjectType === 1) return i18n(I18nKey.bangumiStatusBookWish);
if (subjectType === 3) return i18n(I18nKey.bangumiStatusMusicWish);
if (subjectType === 4) return i18n(I18nKey.bangumiStatusGameWish);
return i18n(I18nKey.bangumiStatusWish);
case 2:
if (subjectType === 1) return i18n(I18nKey.bangumiStatusBookRead);
if (subjectType === 3) return i18n(I18nKey.bangumiStatusMusicListened);
if (subjectType === 4) return i18n(I18nKey.bangumiStatusGamePlayed);
return i18n(I18nKey.bangumiStatusWatched);
case 3:
if (subjectType === 1) return i18n(I18nKey.bangumiStatusBookReading);
if (subjectType === 3) return i18n(I18nKey.bangumiStatusMusicListening);
if (subjectType === 4) return i18n(I18nKey.bangumiStatusGamePlaying);
return i18n(I18nKey.bangumiStatusWatching);
case 4:
return i18n(I18nKey.bangumiStatusOnHold);
case 5:
return i18n(I18nKey.bangumiStatusDropped);
default:
return i18n(I18nKey.bangumiStatusUnknown);
}
}
const tags = $derived(
item.tags && item.tags.length > 0
? item.tags
: (item.subject?.tags || []).map((t) => t.name).slice(0, 5),
);
const visibleTags = $derived(tags.slice(0, 3));
const hiddenTagCount = $derived(Math.max(tags.length - visibleTags.length, 0));
const coverSrc = $derived(item.subject?.images?.medium || "");
const title = $derived(item.subject?.name_cn || item.subject?.name || "");
const year = $derived(
item.subject?.date ? item.subject.date.substring(0, 4) : "",
);
const statusColor = $derived(STATUS_COLORS[item.type] || "bg-gray-500");
const score = $derived(item.subject?.score || 0);
function handleLoad(e: Event) {
const img = e.currentTarget as HTMLImageElement;
img.style.opacity = "1";
const ph = img.parentElement?.querySelector(".lqip-placeholder");
if (ph) ph.classList.add("loaded");
}
</script>
<a
href="{subjectBaseUrl}{item.subject?.id}"
target="_blank"
rel="noopener noreferrer nofollow"
class="group relative overflow-hidden rounded-xl transition-all duration-300 hover:shadow-lg hover:scale-[1.02] block"
>
<div class="aspect-2/3 relative overflow-hidden">
{#if coverSrc}
<div class="lqip-placeholder absolute inset-0 pointer-events-none" style="background: var(--muted)" aria-hidden="true"></div>
<img
src={loadImage ? coverSrc : undefined}
data-src={loadImage ? undefined : coverSrc}
alt={title}
class="w-full h-full object-cover pointer-events-none opacity-0 transition-all duration-500 ease-out group-hover:scale-105"
loading="lazy"
decoding="async"
onload={handleLoad}
/>
{:else}
<div class="w-full h-full bg-gray-200 dark:bg-gray-700 flex items-center justify-center">
<div class="text-gray-400 text-4xl">📖</div>
</div>
{/if}
<!-- Status badge -->
<div class="absolute top-2 left-2 px-2 py-1 rounded-full text-xs text-white font-medium {statusColor}">
{getStatusText(item.type)}
</div>
<!-- Score badge -->
{#if score}
<div class="absolute top-2 right-2 px-2 py-1 rounded-full text-xs text-white font-medium bg-black/50 backdrop-blur-sm flex items-center gap-1">
<span class="text-yellow-400">⭐</span>
{score}
</div>
{/if}
<!-- Gradient overlay + info -->
<div class="absolute inset-0 bg-linear-to-t from-black/70 via-black/20 to-transparent"></div>
<div class="absolute bottom-0 left-0 right-0 p-3">
<h3 class="font-bold text-sm text-white line-clamp-2 drop-shadow-lg">{title}</h3>
{#if year}
<p class="text-xs text-white/60 mt-1">{year}</p>
{/if}
{#if item.comment}
<p class="text-xs text-white/75 line-clamp-1 mt-1 leading-relaxed" title={item.comment}>{item.comment}</p>
{/if}
{#if visibleTags.length > 0}
<div class="flex flex-wrap gap-1 mt-1.5">
{#each visibleTags as tag}
<span class="text-[0.6rem] px-1.5 py-0.5 rounded bg-white/20 text-white/90 backdrop-blur-sm">{tag}</span>
{/each}
{#if hiddenTagCount > 0}
<span class="text-[0.6rem] px-1.5 py-0.5 rounded bg-white/20 text-white/60 backdrop-blur-sm">+{hiddenTagCount}</span>
{/if}
</div>
{/if}
</div>
</div>
</a>
<style>
.line-clamp-2 {
display: -webkit-box;
line-clamp: 2;
-webkit-box-orient: vertical;
overflow: hidden;
}
.line-clamp-1 {
display: -webkit-box;
line-clamp: 1;
-webkit-box-orient: vertical;
overflow: hidden;
}
</style>

Some files were not shown because too many files have changed in this diff Show More