其他版本

点我跳转新版本

主题骨架和模板

这是一篇主题制作过程记录,不是完整主题代码。

本文所有效果可以直接在本站查看(博客主页)

效果

- 奶油色背景

- 粉色和淡紫色强调

- 标签纸、纸胶带、手账感

- 首页以笔记(碎碎念)为主

- 文章页保留封面、分类和标签

- 评论、搜索、RSS、背景音乐不会因为换主题而失效

结构

```text
theme-momo/
├─ theme.yaml
├─ settings.yaml
└─ templates/
   ├─ modules/
   │  ├─ layout.html
   │  ├─ post-list.html
   │  └─ pagination.html
   ├─ index.html
   ├─ archives.html
   ├─ post.html
   ├─ page.html
   ├─ category.html
   ├─ tag.html
   ├─ categories.html
   ├─ tags.html
   └─ assets/
      ├─ css/style.css
      └─ js/pjax.js
```

theme.yaml 告诉 Halo 这是什么主题settings.yaml 负责后台设置layout.html 负责全站布局,其他模板只负责各自页面。

theme.yaml

```yaml
apiVersion: theme.halo.run/v1alpha1
kind: Theme
metadata:
  name: theme-momo
spec:
  displayName: Momo
  author:
    name: RyoVv
    website: https://www.ryozzz.top
  description: 一款奶油色、简洁、标签纸风格的 Halo 主题
  version: 1.0.51
  requires: "2.20.0"
  settingName: theme-momo-setting
  configMapName: theme-momo-config
  license:
    - name: MIT
      url: https://opensource.org/licenses/MIT
```

metadata.namesettingNameconfigMapName 不要每发一个版本就改。它们一旦变化,Halo 会把新版本当成新主题,主题设置会回到默认值。

```text
metadata.name       保持不变
settingName         保持不变
configMapName       保持不变
displayName         可以改
version             每次升级递增
```

settings.yaml

Momo 的设置分为内容、品牌、首页、导航和页脚。一个最小的内容设置:

```yaml
apiVersion: v1alpha1
kind: Setting
metadata:
  name: theme-momo-setting
spec:
  forms:
    - group: content
      label: 内容
      formSchema:
        - $formkit: text
          name: diaryCategory
          label: 日记分类名称
          value: "碎碎念"
          help: 首页只展示这个分类下的文章,文章页会排除它
        - $formkit: date
          name: siteStartDate
          label: 建站日期
          value: "2026-02-27"
```

模板里读取:

```html
<div th:with="diaryCategory=${theme.config.content?.diaryCategory ?: '碎碎念'}">
  <!-- ... -->
</div>
```

layout 和页面模板

layout.html 负责 head、导航、主内容、页脚和插件注入点。页面模板通过 fragment 复用:

```html
<html xmlns:th="http://www.thymeleaf.org"
      th:replace="~{modules/layout :: layout(title = ${site.title}, content = ~{::content})}">
  <th:block th:fragment="content">
    <!-- 页面内容 -->
  </th:block>
</html>
```

布局里保留 Halo 扩展点:

```html
<halo:footer />
```

评论也使用 Halo 的标签,不自己重写:

```html
<halo:comment
  group="content.halo.run"
  kind="Post"
  th:attr="name=${post.metadata.name}" />
```

常用 Finder

```html
<!-- 文章 -->
<div th:with="posts=${postFinder.listAll()}"></div>

<!-- 分类 -->
<a th:each="category : ${categoryFinder.listAll()}"
   th:href="@{${category.status.permalink}}"
   th:text="${category.spec.displayName}">分类</a>

<!-- 站点统计 -->
<div th:with="stats=${siteStatsFinder.getStats()}">
  <span th:text="${stats.post}">0</span>
  <span th:text="${stats.visit}">0</span>
</div>

<!-- 当前登录用户资料 -->
<div th:with="currentUser=${contributorFinder.getContributor(#authentication.name)}">
  <img th:if="${not #strings.isEmpty(currentUser.avatar)}"
       th:src="${currentUser.avatar}" alt="">
  <span th:text="${currentUser.displayName}">用户</span>
</div>
```

Finder 很方便,但 listAll() 在文章很多时会有额外开销。个人博客通常够用,数量上来后应改成分页查询。

标签纸视觉与手账文章

视觉 token

先把颜色集中成变量,避免每个组件各写一套:

```css
:root {
  --bg: #f8f3ea;
  --paper: #fffaf2;
  --pink: #fa9ebc;
  --pink-soft: #ffe5ee;
  --lilac: #c9b6ff;
  --lilac-soft: #f0eaff;
  --blue: #3a0ca3;
  --ink: #3e4056;
  --muted: #8b8ca6;
  --line: rgba(250, 158, 188, .62);
}
```

夜间模式只替换同一组变量,再补少量组件覆盖:

```css
html[data-theme="dark"] {
  --bg: #0b0a18;
  --paper: #17142a;
  --pink: #ff9fc4;
  --pink-soft: #321b39;
  --lilac: #c79bff;
  --lilac-soft: #211a3d;
  --blue: #f2eaff;
  --ink: #e7e0f4;
  --muted: #a39ab8;
}
```

标签纸卡片

标签纸的核心不是圆角,而是奶油纸色、粉色虚线边和顶部纸胶带。

```css
.diary-tile {
  position: relative;
  background: rgba(255, 250, 242, .96);
  border: 1px solid rgba(250, 158, 188, .42);
  border-radius: 16px;
  box-shadow:
    0 5px 0 rgba(250, 158, 188, .12),
    0 14px 24px rgba(93, 122, 138, .08);
  transform: rotate(-.45deg);
  transition: transform .22s ease, box-shadow .22s ease;
}
```

纸胶带用伪元素:

```css
.diary-tile::before {
  content: "";
  position: absolute;
  top: -8px;
  left: 24px;
  width: 58px;
  height: 16px;
  background: rgba(201, 182, 255, .72);
  border-radius: 2px;
  transform: rotate(-4deg);
  z-index: 2;
}
```

不同卡片稍微改变胶带颜色和旋转角:

```css
.diary-tile:nth-child(2n) {
  background: #fff8fb;
  transform: rotate(.35deg);
}

.diary-tile:nth-child(2n)::before {
  left: auto;
  right: 24px;
  background: rgba(189, 224, 214, .78);
  transform: rotate(3deg);
}

hover 时整张纸上提,但入场动画不要再占用 transform:

```css
.diary-tile {
  animation: diaryFadeIn .28s ease both;
}

.diary-tile:hover {
  transform: translateY(-8px) rotate(0);
  box-shadow:
    0 13px 0 rgba(250, 158, 188, .14),
    0 26px 38px rgba(93, 122, 138, .18);
}

@keyframes diaryFadeIn {
  from { opacity: 0; }
  to { opacity: 1; }
}
```

如果入场动画用 transform 且 animation-fill-mode: both,动画结束后会一直覆盖 hover 的 transform,看起来就像 hover 没效果。这是我踩过的坑。

首页只显示笔记(碎碎念)

首页不是 Moments 插件,而是普通 Halo 文章按分类显示名过滤:

```html
<div class="diary-grid" th:with="diaryPosts=${postFinder.listAll()}">
  <article class="diary-tile"
           th:each="post : ${diaryPosts}"
           th:if="${#lists.contains(post.categories.![spec.displayName], diaryCategory)}">
    <a class="diary-tile-link" th:href="@{${post.status.permalink}}">
      <div class="diary-kicker">
        <time th:text="${#dates.format(post.spec.publishTime, 'yyyy.MM.dd')}">2026.01.01</time>
        <span class="diary-sticker">记录</span>
      </div>
      <h3 th:text="${post.spec.title}">日记标题</h3>
      <p th:text="${post.status.excerpt}">日记摘要</p>
    </a>
  </article>
</div>
```

空状态不能直接判断全部文章列表:

```javascript
const empty = document.querySelector('.diary-empty');
if (empty) {
  empty.hidden = Boolean(document.querySelector('.diary-tile'));
}
```

文章页分类

文章页分类栏用公共 fragment:

```html
<div th:replace="~{modules/category-tabs :: category-tabs(
  currentCategory = '',
  diaryCategory = ${theme.config.content?.diaryCategory ?: '碎碎念'})}">
</div>
```

实际渲染时排除默认分类和当前分类:

```html
<a class="category-tab"
   th:each="category : ${categoryFinder.listAll()}"
   th:if="${category.spec.displayName != diaryCategory
            and category.spec.displayName != '默认分类'
            and category.metadata.name != currentCategory}"
   th:href="@{${category.status.permalink}}"
   th:text="${category.spec.displayName}">
  分类
</a>
```

手账文章分组

只有碎碎念分类启用手账布局,普通文章保持普通排版:

```html
<th:block th:fragment="content"
  th:with="
    diaryCategory=${theme.config.content?.diaryCategory ?: '碎碎念'},
    isDiaryPost=${#lists.contains(post.categories.![spec.displayName],
      theme.config.content?.diaryCategory ?: '碎碎念')}">
  <article class="article" th:classappend="${isDiaryPost} ? ' scrapbook-post' : ''">
```

然后用 JavaScript 按 H1/H2 把正文拆成纸卡:

```javascript
const post = document.querySelector('.scrapbook-post');
if (!post) return;

const content = post.querySelector('.post-content');
const nodes = Array.from(content.childNodes);
const cards = [];
let current = null;

const newCard = () => {
  const card = document.createElement('section');
  card.className = 'scrapbook-card';
  cards.push(card);
  current = card;
  return card;
};

nodes.forEach((node) => {
  if (node.nodeType === 1 && (node.tagName === 'STYLE' || node.tagName === 'SCRIPT')) return;
  if (node.nodeType === 3 && !node.textContent.trim()) return;

  if (node.nodeType === 1 && (node.tagName === 'H1' || node.tagName === 'H2')) {
    newCard().appendChild(node);
    return;
  }

  if (!current) newCard();
  current.appendChild(node);
});

if (cards.length) content.replaceChildren(...cards);
```

这段代码最容易忽略的是:

- 只处理 H2,结果文章里用的是 H1

- 没有跳过 style,导致多出一张空白纸卡

- 在 DOM 还没有稳定时执行

手账卡片的核心是交错和轻微旋转:

```css
.scrapbook-post .scrapbook-card {
  width: 700px;
  max-width: calc(100% - 28px);
  margin: 30px auto 38px;
  padding: 18px 30px 26px;
  background: #fffaf2;
  border: 2px dashed rgba(250, 158, 188, .62);
  border-radius: 20px;
  transform: rotate(-.45deg);
}

.scrapbook-post .scrapbook-card:nth-child(2n) {
  margin-left: 4%;
  margin-right: auto;
  transform: rotate(.55deg);
}
```

整张卡片可点击

不能只让标题和封面可点击。用拉伸标题链让整张卡片成为热区:

```css
.post-card {
  position: relative;
  cursor: pointer;
}

.post-title a::after {
  content: "";
  position: absolute;
  inset: 0;
  z-index: 2;
}

.post-card .post-kicker,
.post-card .post-meta,
.post-card .post-cover {
  position: relative;
  z-index: 3;
}
```

标题里的伪元素覆盖整张卡片,分类、标签和封面在更高层级上,不会被误触。

PJAX、音乐和暗色模式

为什么需要 PJAX

Halo 默认整页刷新。整页刷新会销毁当前文档里的 <audio>,所以背景音乐每次切页都会从头播放。

PJAX 的核心思路:

1. 拦截站内链接

2. fetch 目标页面

3. 只替换 .site-main

4. 更新标题和 URL

5. 重新初始化页面脚本

背景音乐对象留在当前文档里,所以不需要重新播放。

核心替换逻辑

```javascript
const mainSelector = '.site-main';

const navigate = async (url, push = true) => {
  const response = await fetch(url, {
    credentials: 'same-origin',
    headers: { 'X-Requested-With': 'pjax' }
  });

  if (!response.ok) throw new Error('pjax response failed');

  const html = await response.text();
  const doc = new DOMParser().parseFromString(html, 'text/html');
  const nextMain = doc.querySelector(mainSelector);
  const currentMain = document.querySelector(mainSelector);

  if (!nextMain || !currentMain) throw new Error('pjax main not found');

  currentMain.innerHTML = nextMain.innerHTML;
  document.title = doc.title || document.title;

  if (push) history.pushState({ pjax: true }, '', url);
  window.scrollTo({ top: 0, behavior: 'instant' });

  currentMain.querySelectorAll('script').forEach((old) => {
    const script = document.createElement('script');
    [...old.attributes].forEach((attr) => script.setAttribute(attr.name, attr.value));
    script.text = old.textContent || '';
    old.replaceWith(script);
  });
};
```

实际实现还要处理:

- 外链不拦截

- target="_blank" 不拦截

- 登录、控制台、API、插件路径不拦截

- 同页链接只滚回顶部,不重新加载

- 预览模式的 preview-theme 参数要保留

- 脚本重初始化失败时不要直接退回整页刷新

背景音乐开关

Momo 的音乐开关读取全局音乐脚本创建的 window.__singleBgm,并把用户选择保存到 localStorage:

```javascript
const KEY = 'momo-bgm-enabled';
let enabled = localStorage.getItem(KEY) !== 'false';

const audio = window.__singleBgm;

if (!enabled && audio) {
  audio.pause();
}

document.querySelector('.music-toggle').addEventListener('click', () => {
  const audio = window.__singleBgm;
  enabled = !enabled;
  localStorage.setItem(KEY, enabled ? 'true' : 'false');

  if (audio) {
    if (enabled) {
      audio.play().catch(() => {});
    } else {
      audio.pause();
    }
  }
});
```

浏览器规定带声音的自动播放通常需要用户交互。代码可以先调用 play(),但不能保证所有访客一进页面就能听到声音。

暗色模式

主题在 <html> 上设置 data-theme:

```javascript
const key = 'momo-color-scheme';
const root = document.documentElement;

const saved = localStorage.getItem(key) === 'dark' ? 'dark' : 'light';
root.dataset.theme = saved;

document.querySelector('.scheme-toggle').addEventListener('click', () => {
  const next = root.dataset.theme === 'dark' ? 'light' : 'dark';
  root.dataset.theme = next;
  localStorage.setItem(key, next);
});
```

为了避免页面先亮后暗,主题初始化脚本要尽量放在 <head> 里。

评论组件的 Shadow DOM

Halo 评论组件是自定义元素,内部使用 Shadow DOM。主题的普通 CSS 无法直接选中里面的评论文字。

评论插件的夜间变量依赖宿主元素上的 data-color-scheme:

```javascript
const syncComments = () => {
  const dark = document.documentElement.dataset.theme === 'dark';
  document.querySelectorAll('comment-widget').forEach((widget) => {
    widget.dataset.colorScheme = dark ? 'dark' : 'light';
    widget.classList.toggle('dark', dark);
  });
};

const observer = new MutationObserver(syncComments);
observer.observe(document.body, { childList: true, subtree: true });
```

同时可以给 comment-widget 补上插件使用的 CSS 变量:

```css
html[data-theme="dark"] comment-widget {
  --halo-cw-text-1-color: #f9fafb;
  --halo-cw-text-2-color: #e5dff1;
  --halo-cw-text-3-color: #b2a7c5;
  --halo-cw-muted-1-color: #8d7fa5;
  --halo-cw-muted-2-color: #6f6285;
  --halo-cw-muted-3-color: #4c405e;
}
```

这是夜间模式里最容易漏掉的一块。

背景动画性能优化与发布

背景的三次改版

Momo 的背景经历过几次方向变化:

1. 最初是几颗小气泡,飘浮在页面两侧

2. 后来换成粉色的粗波浪

3. 中间尝试过切页全屏转场,但发现容易卡顿、遮挡内容、结束回位不自然

4. 最终决定保留背景本身的动态,不做切页转场

不是所有视觉效果都值得加到页面切换流程里。背景漂浮是常态装饰,切页转场则会影响导航性能和阅读节奏。

最终背景

背景层只保留:

- 右下角实心淡粉圆

- 三条粗波浪边框

- 两条半透明填充波浪

- 缓慢的漂浮和旋转动画

结构:

```html
<div class="bg-effects" aria-hidden="true">
  <div class="p3r-wave-layer">
    <span class="p3r-wave wave-1"></span>
    <span class="p3r-wave wave-2"></span>
    <span class="p3r-wave wave-3"></span>
    <span class="p3r-wave-fill fill-1"></span>
    <span class="p3r-wave-fill fill-2"></span>
  </div>
  <span class="p3r-disc"></span>
</div>
```

动画只影响背景层,不影响正文:

```css
.bg-effects {
  position: fixed;
  inset: 0;
  z-index: 0;
  overflow: hidden;
  pointer-events: none;
}

.site-header,
.site-main,
.site-footer {
  position: relative;
  z-index: 1;
}
```

为什么不要给多个巨型 DOM 做动画

粗波浪看起来简单,实际上是多个超大尺寸的 border-radius 圆环。如果同时缩放多个巨型 DOM,浏览器需要反复重绘,尤其是低性能设备上容易掉帧。

最后的经验:

- 背景动画只做缓慢的 transform 和 opacity

- 不要在切页时同时改变多个大元素的尺寸

- 不要给同一个元素叠加多套动画

- 能用一张纹理解决的效果,不要用十几个 DOM 模拟

- 动画结束状态要和静止状态一致,否则会闪回

主题设置不要重置

主题升级时设置重置,通常是因为 metadata.name、settingName、configMapName 变了。

正确做法:metadata.name 固定,settingName 固定,configMapName 固定,version 递增,displayName 可以改。上传新版时选择升级,不要把它当成全新主题安装。

CSS 缓存

主题 ID 和 CSS 路径不变时,浏览器可能继续使用旧 CSS。给静态资源带版本参数即可解决:

```html
<link rel="stylesheet" th:href="@{/themes/theme-momo/assets/css/style.css(v=${theme.spec.version})}">
<script defer th:src="@{/themes/theme-momo/assets/js/pjax.js(v=${theme.spec.version})}"></script>
```

总结

Momo 的制作过程里,真正花时间的不是写出一个卡片,而是处理主题和 Halo 之间的边界:

- 哪些内容交给 Halo Finder

- 哪些交互交给原生 JavaScript

- 哪些插件能力必须保留

- 哪些视觉效果应该舍弃

最后留下来的版本没有复杂的切页转场,只有稳定的布局、标签纸手账、可控的音乐与夜间模式,以及一层安静的粉色背景。