Loading...

Loading...

This article is both a complete usage tutorial for the matery theme’s layout and page features and an automated testing playground.
Coverage: post layout features, sidebar widgets, responsive breakpoints, galleries, search, comments, dark mode, encryption, RSS/sitemap, PWA.
Automated tests (tools/tests/release-test.sh) assert the rendering markers labeled below.

How to read: every feature shows Effect first (real rendering or behavior), then Corresponding config (the minimal snippet that produces it). When you need a parameter, jump straight to that section’s “All tunable keys” table. Config snippets come from the theme config userConfig/_config.tmp.yml (injected into themes/matery/_config.yml at build time).


1. Post Layout Features

1.1 Prev/Next Navigation

Effect: Two cards at the end of the post, left and right, each showing the adjacent post’s cover + title + excerpt, with a gradient background on hover; when one side has no post, the opposite card’s placeholder is rendered (left-badge / right-badge markers).

Corresponding config: There is no switch — post-detail.ejs:171 unconditionally renders _partial/post/prev-next.ejs.

# The config file contains post.prev_next.enable: true, but the template never reads that key;
# renaming or disabling it won't make the navigation disappear. What actually affects it is front-matter:
#   hide: true   → prev_post()/next_post() recursively skip this post, so navigation never points at it

⚠️ Historical misremembering: older versions of this article documented prenext.enable, which is not a config key; prenext-posts is merely the rendered DOM id.

Test assertion: The post page contains the #prenext-posts container.

Effect: A license card at the bottom of the post — title, author, original link, publish date, CC icon + license name (e.g. CC BY-NC-SA 4.0); with update_date enabled it adds an “Updated on” row.

Corresponding config:

post:
  copyright:
    enable: true            # master switch
    license: 'cc_by_nc_sa'  # default license
    author:
      enable: true          # show author
    post_date:
      enable: true          # show publish date
      format: "LL"
    update_date:
      enable: false         # show update date
      format: "LL"

Common options:

① Change the license (8 licenses + 2 special)

Effect: The CC icon and name at the bottom-right of the card change accordingly; noreprint shows “no reprint allowed”, pay shows “paid reprint”.

Corresponding config (license allowed values, mapping table in copyright.ejs):

post:
  copyright:
    license: 'cc_by_nc_sa'
    # cc_by | cc_by_nd | cc_by_sa | cc_by_nc | cc_by_nc_nd | cc_by_nc_sa
    # cc0 | noreprint | pay

② Disable / override per post

Effect: copyright: false removes the license card for that post; reprintPolicy changes only that post’s license while other posts keep the global license.

Corresponding config (in the post front-matter):

---
copyright: false          # no copyright card for this post
# or
reprintPolicy: cc_by      # this post uses CC BY
---

Test assertion: The post page contains a copyright container (#reprint-statement / .license-box).

1.3 Outdated Content Notice

Effect: A note is inserted at the top of the post: older than warning_day days uses the warning style, older than error_day days upgrades to danger/error style. This site currently has it disabled, so this post shows no such notice.

Corresponding config:

post:
  outdate:
    enable: false      # disabled on this site; set true to apply site-wide
    warning_day: 365   # over 365 days → warning style
    error_day: 3650    # over 3650 days → error style

Common options:

① Keep only “outdated”, never escalate

Effect: Every outdated post stays at the warning style instead of suddenly turning into a glaring red block.

Corresponding config: set error_day larger than the site’s age (e.g. 36500).

② Per-post exemption

Effect: Evergreen articles (such as this tutorial series) show no outdated notice.

Corresponding config: put outdate: false in front-matter (that post gets no notice bar).

Test assertion: When enabled, the post page contains an outdated-notice element (outdate-related class); under the current config it is not asserted.

1.4 TOC

Effect: On desktop, a floating TOC tree on the right that highlights the current heading as you scroll; on mobile it collapses into the sidebar.

Corresponding config (theme _config.yml top-level toc, shared by every page with a TOC: post / wiki / msg / bb):

toc:
  enable: true
  headingSelector: "h2,h3,h4,h5,h6"   # heading levels included in the TOC
  collapseDepth: 0                    # collapse depth (0 = all collapsed)

Common options:

① Collect only h2/h3

Effect: A two-level TOC, a shorter sidebar, and fewer highlight jumps while scrolling long articles (h4 and below no longer interrupt).

Corresponding config:

toc:
  headingSelector: "h2,h3"

② Default expansion level

Effect: With collapseDepth: 1, level-one headings expand their children by default, so readers don’t have to open each level manually.

Corresponding config:

toc:
  collapseDepth: 1   # greater than 0: expand by default when child headings exist

2026-09-25 update: the config moved from post.toc to top-level toc, and the wiki page now shares the same config as the post page (previously wiki hardcoded h1, h2, h3 and ignored the config entirely). The misleading showToggleBtn (it only gated whether the button’s click handler was registered — not a visibility switch) and the unimplemented placement (dead config) were removed.

Test assertion: The post page contains the #toc-content TOC container.

1.5 Advertisement Slots (below the TOC)

Effect: A group of colored ad cards (.tgCard) appears below the post TOC, either full-width or two columns (decided by colspan); when no entry has enable: true the whole block is not rendered (not an empty shell).

Corresponding config:

post:
  advertisements:
    - id: "ad-1"
      text: "Ad copy"
      link: "https://example.com"
      enable: true

Field reference: see §2.10 (placement here, full parameter table there).

Test assertion: The post page contains the .tgCard ad container.

1.6 Word Count & Reading Time

Effect: The post header article-info shows “word count · reading time” (e.g. 4.2k words · 14 min); the footer shows the site-wide total.

Corresponding config (visibility switches live in postInfo, calculation coefficients in post.min2read):

postInfo:
  wordCount: true     # show per-post word count
  min2read: true      # show reading time

post:
  min2read:
    awl: 1            # average word length: 1 CJK char = 1 character → 1
    wpm: 300          # words per minute: 250-350 suits CJK technical content

Implementation (themes/matery/scripts/helpers/wordcount.js): three built-in helpers replace the former hexo-wordcount plugin — same names and signatures, so no template changed:

HelperPurpose
wordcount(page)per-post count (CJK characters + English words)
min2read(page)reading time in minutes = floor(count / (awl × wpm)) + 1
totalcount(site)site-wide total (posts + wiki pages; i18n duplicates de-duplicated; encrypted posts counted by plaintext post.origin)

Common options:

① Show word count only, no reading time

Effect: article-info loses one item and the header becomes more compact.

Corresponding config:

postInfo:
  wordCount: true
  min2read: false

② Calculate at English reading speed

Effect: With awl: 2 / wpm: 60 (equivalent to 120 chars/min), a 520-character post shows 5 min — the old, wrong default.

Corresponding config:

post:
  min2read:
    awl: 2
    wpm: 60

⚠️ Historical bug (fixed 2026-09-22): the old default awl: 2 / wpm: 60 equals 120 chars/min — tuned for English — so a 520-character Chinese post showed 5 min; with the new awl: 1 / wpm: 300 the same post shows 2 min.

Test assertion: posts expose the article-info word-count / reading-time markers; the three helpers’ behaviour is covered by tools/tests/unit/helpers.test.js.

1.7 Update Time (“Updated on”)

Effect: The post header shows “Updated on September 26, 2026 AM” (different per post); posts that were never edited do not show this line — guarded by compare_date(page.date, page.updated): when the two timestamps are equal, the row is not rendered.

Data source (fixed 2026-09-26): the source file’s git last-commit time — neither the file mtime nor the publish date.

CandidateWhy not
file mtimereset by git checkout/clone or bulk scripts (measured: all 142 _posts mtimes fell in the same second) → every post shows the same day
date (publish time)cannot reflect edits; yields “Updated on == Published on”
git commit time ✅frozen at commit time, immune to any working-tree operation

Corresponding config:

postInfo:
  update: true        # switch for the "Updated on" line (this is the key the template reads)

post:
  updated:
    enable: false     # compatibility slot: post-detail never reads it, changing it has no effect
    date_format: "LL a"   # date format
    relative: false       # true → show "3 days ago"
    note_class: info      # note style: default|primary|info|success|warning|danger|light

updated_option: 'date'    # fallback only — 'empty' makes the third-party sitemap template crash on post.updated.toDate()

Common options:

① Relative time

Effect: “Updated 3 days ago” instead of “Updated on September 26, 2026 AM”.

Corresponding config:

post:
  updated:
    relative: true

② Author-specified value

Effect: That post shows the date written in front-matter instead of the git time.

Corresponding config (front-matter):

---
updated: 2026-10-01 09:00:00
---

Implementation: scripts/filters/post-updated.js overwrites post.updated in before_generate (before every generator) using the git time from scripts/utils/git-time.js; an explicit updated: in front-matter takes precedence.

Test assertion: tools/tests/unit/unit-updated.test.js (4 cases: CJK path hits / missing returns null / overwritten as moment / author value preserved); the post page contains datetime="…" update.


2. Sidebar Widgets

The 10 widgets in this section fall into two groups: page-level auto-rendered (no config key — present whenever the page exists) and config-driven (keys in the theme _config.yml). Each item notes who renders it and which key controls it.

2.1 Category Radar

Effect: A canvas radar chart at the top of the /categories/ page, one dimension per category, axis length ∝ that category’s post count; it redraws on light/dark switch.

Corresponding config: No config key — categories.ejs:11 unconditionally renders _partial/widget/category-radar.ejs, with data taken from post categories. To get it you only need a categories page:

---
title: categories
type: "categories"
layout: "categories"
---

The menu entry is a separate matter (menu.<any-name> with url + icon), unrelated to whether the widget renders.

Test assertion: /categories/ contains a <canvas> element.

2.2 Tag Cloud

Effect: A row of colorful rounded chips at the bottom of the /tags/ page, with randomized font sizes (visual hierarchy); clicking jumps to the corresponding tag page.

Corresponding config: No config key — tags.ejs:13 renders tag-cloud.ejs, with data taken from all post tags.

Test assertion: /tags/ contains .tag-chips .chip.

2.3 Word Cloud

Effect: An ECharts word cloud on the /tags/ page (2026-09-05 custom spiral → echarts-wordcloud@2, fixing a 30s timeout); font size is continuous over sizeRange [14,56] ∝ post count; container height is auto max(minHeight, word count × heightPerWord) — many words are not clipped, few words leave no large blank area.

Corresponding config:

wordcloud:
  minHeight: 500         # minimum word-cloud height (px), fallback for few words
  heightPerWord: 2.2     # height increment per word (px/word), expands for many words to prevent clipping

Common options:

① Taller when there are many words

Effect: With 500 tags the container height = max(500, 500×2.2) = 1100px, so words are not squeezed together.

Corresponding config:

wordcloud:
  heightPerWord: 3      # 3px per word, taller container for many words

The title Tag Word Cloud goes through i18n; light/dark switching goes through Matery.echarts.init automatically (no extra config).

Test assertion: /tags/ contains the #tag-wordcloud container + echarts loaded exactly once + light/dark switch dispose→reinit (tools/tests/wordcloud.test.js L2g).

2.4 Archive Timeline

Effect: The /archives/ page arranges all posts in a vertical year/month timeline, with dots + collapsible years and fade-in on scroll.

Corresponding config: No config key — built into archive.ejs (#cd-timeline), with the post list taken directly from site.posts.

Test assertion: /archives/ contains #cd-timeline.

2.5 About Page Statistics (postCharts)

Effect: Three ECharts charts on the /about/ page: post publication trend (#posts-chart), category distribution (#categories-chart), tag distribution (#tags-chart), adapting to light/dark automatically.

Corresponding config: No config key — about.ejs:48 unconditionally renders post-charts.ejs; you need an /about/ page (layout: about).

Test assertion: /about/ contains the #postCharts container + multiple <canvas> elements.

2.6 ArtiTalk (Optional, Disabled by Default)

Effect: An ArtiTalk status wall (LeanCloud backend) is embedded at the bottom of the /about/ page for posting short updates. Disabled by default, so this site’s about page doesn’t show it.

Corresponding config:

artitalk:
  enable: false    # disabled by default; set true to render
  appId:           # LeanCloud App ID
  appKey:          # LeanCloud App Key

Common options:

① Enable the status wall

Effect: The #artitalk_main container appears and loads the artitalk script from jsDelivr; once appId/appKey are filled in you can read and write real updates.

Corresponding config:

artitalk:
  enable: true
  appId: "{{LEANCLOUD_APP_ID}}"
  appKey: "{{LEANCLOUD_APP_KEY}}"

Without enable the template skips the whole block (the if guard at about.ejs:62), so the default state is not asserted.

Test assertion: Not rendered in the default state.

2.7 My Projects (myProjects)

Effect: Three columns of project cards on the /about/ page, each with a Font Awesome icon + gradient background + project name + one-line description, linking out on click.

Corresponding config:

myProjects:
  enable: true
  data:
    LinuxPTTools:                                  # project name (card title)
      icon: fab fa-linux                           # Font Awesome class name
      iconBackground: 'linear-gradient(to bottom right, #66BB6A 0%, #81C784 100%)'
      url: https://github.com/appotry/PTtool       # click target
      desc: Designed for PT users, scrape and seed at the same time.   # one-line description

Common options:

① Turn off the whole block

Effect: The about page no longer renders the .my-projects card area (other blocks are unaffected).

Corresponding config:

myProjects:
  enable: false

② Add a project

Effect: One more card, with its own icon/gradient/link/description.

Corresponding config: append another entry under data: at the same level (the key name is the title and may contain a colon, e.g. Docker:hexo).

Test assertion: /about/ contains the .my-projects container.

2.8 My Skills (mySkills)

Effect: Two columns of skill bars on the /about/ page, with colorful gradient fills + percentage numbers, rendered at the width given by percent.

Corresponding config:

mySkills:
  enable: true
  data:
    C:
      background: 'linear-gradient(to right, #2196F3 0%, #42A5F5 100%)'
      percent: 90%

Common options:

① Adjust proficiency

Effect: The progress-bar fill width follows percent; 90% and 45% side by side are visibly different in length.

Corresponding config:

mySkills:
  data:
    C:
      percent: 45%

② Group by color

Effect: Skills in the same color family read as one visual group (this site groups into five families: blue/pink/purple/cyan/green).

Corresponding config: give skills in the same group the same background value.

Test assertion: /about/ contains the .my-skills container.

2.9 Archive Calendar (postCalendar)

Effect: A calendar heatmap (#post-calendar) at the top of the /archives/ page, where cell color intensity represents that month’s post count.

Corresponding config (note: this is a boolean root key, not a map):

postCalendar: true    # show post calendar widget on the archives page

Common options:

① Turn the calendar off

Effect: The archives page starts directly with the timeline, with no calendar card.

Corresponding config:

postCalendar: false

Test assertion: /archives/ contains the #post-calendar container.

2.10 Sidebar Advertisement (advertisement)

Effect: A group of ad cards below the post TOC; with image the image is shown, otherwise text; colspan: 2 takes the whole row, colspan: 1 takes half; dark mode automatically switches to background_dark.

Corresponding config:

post:
  advertisements:
    - id: "ad-1"                          # unique identifier (data-tg-id)
      text: "Ad copy"                     # text shown when there is no image
      link: "https://example.com"          # click target
      background: "#ff6666"                # light background
      background_dark: "#8b3a3a"           # dark background (falls back to light when absent)
      colspan: 1                           # 1=half row, 2=full row
      enable: true                         # only true entries are rendered

Common options:

① Image ad

Effect: The card holds an image (the image replaces the text), with the text used only as alt.

Corresponding config:

post:
  advertisements:
    - id: "ad-aliHongBao"
      text: "Scan with Alipay for a red packet"
      link: "/msg/"
      background: "var(--card-bg-color)"
      colspan: 1
      image: "/medias_webp/misc/hongbao.webp"
      enable: true

② Full-row card + disable one entry

Effect: The colspan: 2 ad occupies a full row; an entry with enable: false is neither rendered nor reserved.

Corresponding config:

post:
  advertisements:
    - id: "ad-3"
      text: "Ad space for rent"
      link: "mailto:admin@example.com"
      background: "#66ff66"
      background_dark: "#3a8b3a"
      colspan: 2
      enable: false

With no enabled ads the output is empty (advertisement.ejs first checks some(ad => ad.enable)).

Test assertion: The post page contains the .tgCard ad container.

Effect: A row of thumbnail cards at the bottom of the /about/ page (the /medias_webp/featureimages/ series); clicking opens the lightbox.

Corresponding config:

myGallery:
  enable: true
  data:
    - /medias_webp/featureimages/0.webp
    - /medias_webp/featureimages/1.webp
    - /medias_webp/featureimages/2.webp

Common options:

① Change the image set

Effect: The number of cards maps one-to-one to the images, in the same order.

Corresponding config: add or remove paths line by line under data:; there is no limit (extra items wrap to a new row).

This is not the same as the standalone /galleries/ album pages in §7: here it is only an image wall on the about page, with no cover/description/encryption.

Test assertion: /about/ contains the .my-gallery container.


3. Responsive Breakpoints

Purpose: Four Stylus variables cut the viewport width into four segments, deciding nav collapse, sidebar visibility, TOC placement, and effects on/off.

Learning path: which variable to change → common tweaks → full parameter table → boundaries & conflicts

3.1 How to enable

Effect: Four segments by default — <768px nav collapses to a hamburger menu with single-column content; 768–992px tablet layout with the sidebar collapsed; >992px desktop three columns (content + sidebar + TOC); >1400px sakura/ripple effects enabled.

Corresponding config (themes/matery/source/css/_variables/base.styl):

$breakpoint-sm: 368px   // Extra small (phone portrait)
$breakpoint-md: 768px   // Tablet / phone landscape
$breakpoint-lg: 992px   // Desktop
$breakpoint-fun: 1400px // Effects enable threshold (large screens)

3.2 Common options

① Enter desktop three columns earlier

Effect: A 1280px-wide laptop shows the sidebar + TOC without waiting for a 1400px screen.

Corresponding config:

$breakpoint-lg: 1200px

② Delay the effects

Effect: Below 1400px, sakura/ripple animations are not loaded at all, so scrolling is smoother on low-end machines.

Corresponding config:

$breakpoint-fun: 1600px

3.3 All tunable keys

KeyTypeDefaultAllowed values / rangePurpose
$breakpoint-smlength368pxany CSS lengthExtra small (phone portrait)
$breakpoint-mdlength768pxany CSS lengthTablet / phone landscape
$breakpoint-lglength992pxany CSS lengthDesktop three columns
$breakpoint-funlength1400pxany CSS lengthEffects enable threshold (large screens)

3.4 Boundaries & conflicts

  • Defined in the Stylus variable file, not _config.yml: after changing it you must recompile (clean build); reading the source alone has no effect.
  • The four values together cut the width into four segments; changing any one moves the boundary of its two neighbours (the interval table below is the result, not independent config).
  • Orthogonal to §4 content-width steps: breakpoints decide layout shape, max-width decides column width caps.

3.5 Summary

BreakpointLayout
<768pxNav collapses to hamburger menu, content single column
768–992pxTablet layout, sidebar collapsed
>992pxDesktop three-column (content + sidebar + TOC)
>1400pxEffects enabled (sakura/ripples, etc.)

Effect summary: Bootstrap/Materialize grid auto-adapts; the sidebar auto-hides on narrow screens; the TOC collapses on mobile.

Test assertion: <768px nav collapses; >992px desktop three-column; >1400px effects enabled.


4. Content Width Unification (Added 2026-09-07)

Purpose: Make the content column fill the screen without becoming too wide to read.

Learning path: why “ratio + cap” → single vs multi column → width step table → boundaries

4.1 How to enable

Effect: On a 4K screen the content column caps at 1525px (single-column) / 2250px (multi-column), instead of stretching into a 3456px-wide line of text; on FHD it is 1125px / 1250px.

Corresponding config (_variables/base.styl, mixin content-container(wide)):

// Single-column: content without sidebar
.content-container()      // → standard width steps

// Multi-column: content + sidebar/TOC
content-container(true)   // → wide width steps

Design principle: “ratio + cap” — content area width: 90% (relative to the screen) + max-width steps (readability cap). Do not use a pure 90% — at 4K, 90% = 3456px is unreadable.

4.2 Common options

① Standard width for single-column pages

Effect: A single-column wiki page is 1125px on FHD, 1525px on 2K, and still 1525px on 4K (capped).

Corresponding config:

.content-container()      // no argument = single-column

② Wide width for multi-column pages

Effect: A multi-column wiki page’s content column goes from 899px → 1500px at 4K (+67%), on the same step ladder as post-container.

Corresponding config:

.content-container(true)  // pass true = multi-column

Selection rules:

  • Single-column (content without sidebar): content-container() → standard width
  • Multi-column (content + sidebar/TOC): content-container(true) → wide width
  • No hand-written max-width in layouts (always go through the mixin)

4.3 All tunable keys

BreakpointStandard (single-column)Wide (multi-column)
FHD 993-1920px1125px1250px
2K 1921-2560px1525px1750px
4K 2561px+1525px (capped)2250px

4.4 Boundaries & conflicts

  • The step values are hard-coded in the mixin; changing one affects every caller, and an exception for a single page breaks the site-wide visual consistency.
  • Orthogonal to §3 breakpoints: breakpoints decide “how many columns”, this decides “how wide each column is”.
  • The 1525px single-column cap at 4K is deliberate — anything wider makes the eye’s return sweep too long while reading.

4.5 Summary

  • The default single-column is enough: one line, content-container()
  • With sidebar/TOC: content-container(true)
  • Don’t hand-write max-width: layout pages will stop aligning with each other
  • Verification: tools/tests/content-width.test.js (L2m) covers W1 4K wiki==post-container / W3 FHD / W4 2K / W5 single-column capped at 1525px.

4.6 FA Resource Version Stamp ({urlVersion})

Effect: After a release, browsers/CDN fetch the new resources (URL carries ?v=13.13) and the old cache is invalidated automatically; local preview has no version suffix and functionality is unaffected.

Corresponding config (userConfig/_config.tmp.yml, static_prefix.libs section):

static_prefix:
  libs:
    faSolid: /libs/awesome/webfonts/fa-solid-900.woff2{urlVersion}
    matery:
      mycss:
        main: /css/main.css{urlVersion}
    highlight:
      highlight: /css/highlight.css{urlVersion}

Mechanism: Resource URLs carry the version-stamp placeholder {urlVersion}, which tools/cicd.sh replaces at build time via sed with the actual version number (read from tools/.VERSION).

Affected resources:

ResourceConfig keyExample
FA WebFontfaBrands/faRegular/faSolid/libs/awesome/webfonts/fa-solid-900.woff2{urlVersion}
Theme CSSmatery/mycss/main/css/main.css{urlVersion}
Highlight CSShighlight/highlightDark/css/highlight.css{urlVersion}

No manual action required: the version number is injected by CI automatically.

⚠️ Do not manually edit the {urlVersion} placeholders in themes/matery/_config.yml — that file is a build artifact overwritten by userConfig/_config.tmp.yml during CI.


5. Multilingual Fallback Mechanism (Added 2026-09-08, Revised 2026-09-10)

Purpose: One set of content is output as multiple pages per language prefix; when a translation is missing it falls back along a fixed chain instead of 404ing.

Learning path: which languages to enable → fallback order → where translation files go → full parameters → boundaries

5.1 How to enable

Effect: Only languages with enabled: true generate pages and appear in the language dropdown; de/eo/es/ja/ru etc. are disabled by default, so visiting /de/... falls back to en.

Corresponding config (the preference section of theme _config.yml):

preference:
  default_lang: zh-cn         # default language (no prefix path)
  fallback_lang: en           # fallback intermediate layer (must be enabled in lang_meta)
  lang_meta:
    zh-cn:
      name: 简体中文
      flag: 🇨🇳
      enabled: true
    en:
      name: English
      flag: 🇬🇧
      enabled: true
    de:
      name: Deutsch
      flag: 🇩🇪
      enabled: false          # disabled → no pages generated, absent from dropdown

Fallback chain (three layers):

Requested language exists? → Use it
→ Doesn't exist → fallback_lang exists? → Fall back to fallback_lang
→ Doesn't exist → default_lang exists? → Fall back to default_lang
→ Doesn't exist → Any available language

5.2 Common options

① Chinese/English only

Effect: The build output is only / and /en/; no more empty de/eo/es/ja/ru pages.

Corresponding config: keep default_lang: zh-cn + fallback_lang: en + both enabled: true, and set the rest to false.

② Add a language

Effect: The panel dropdown gains one option, /{lang}/ and /{lang}/page/N/ appear, and missing translations still resolve through the fallback chain.

Corresponding config: set that language’s enabled to true and add translation files under source/{lang}/.

③ Real translation mapping (post / wiki)

Effect: With a real translation, a /{lang}/posts/{abbrlink}/ page with real content is generated; without one, the fallback chain generates it.

Corresponding config: Translation files share the same filename as the default language, placed in the language subdirectory:

TypeTranslation source pathfront-matter
Postsource/{lang}/_posts/{same-name}.mdKeep the same abbrlink + add lang: en
Wikisource/{lang}/docs/{same-name}.mdSame (wiki pages have no abbrlink, mapped by same-name path)

Chinese-English association has two modes: with abbrlink plugin → same abbrlink associates; without plugin → same-name file association (with filesystem fallback check).

Note: Hexo natively only recognizes source/_posts/ (en/_posts/ is ignored); article translations are generated by the theme’s i18n-post-generator.js.

5.3 All tunable keys

KeyTypeDefaultAllowed values / rangePurpose
preference.default_langstringzh-cnlanguage codeDefault language, no path prefix
preference.fallback_langstringenlanguage code (must be enabled)Fallback intermediate layer
preference.lang_meta.<code>.namestring—any stringDropdown/panel display name
preference.lang_meta.<code>.flagstring—emojiDropdown flag
preference.lang_meta.<code>.enabledboolfalse (en/zh-cn are true in the example)true / falseWhether to generate that language’s pages + include it in the dropdown

5.4 Boundaries & conflicts

Behavior by page type (revised 2026-09-10):

Page typeMultilingual versionNotice banner
Post✅ Use the translation if it exists, otherwise generate via fallback chain✅ Show “xx doesn’t exist, displaying yy language version”
Wiki page✅ Same as above✅ Same as above
Aggregation page (tag/category/archive)✅ Generate per enabled languages❌ Generate only, no notice
Standalone page (about/musics/movies/friends/msg/bb/galleries etc.)✅ Generates /{lang}/{page}/ (UI text goes through languages/{lang}.yml i18n)❌ None
Homepage✅ /en/, /en/page/N/❌ None

Standalone pages (including gallery sub-pages and historical pages with layout:'post' in the pages collection, such as dash) are generated by standalone-page-generator.js using an exclusion method (layout ∉ {wiki, tags, categories, 404} → generate; new standalone pages are automatically covered without registering to a list).

Client-side language strategy (Scheme A: site-wide follow, 2026-09-10):

ScenarioBehavior
First visitNo local preference and browser language matches an enabled language → popup asking to switch; if accepted, remember and redirect; if rejected, remember the default language (won’t ask again)
Panel switchLanguage dropdown selection → write local preference + redirect to the corresponding language version
Page load / refreshHas local preference → load that language version directly (head.ejs inline redirect, before render with no flash); crawlers skipped (SEO); paths without a multilingual version skipped (prevent 404)
Panel displayLanguage dropdown shows the local preference (localStorage.wiki_lang)

Language prefix rules (url_for_lang): Resources (css/js/libs/medias/images/fonts etc.) and static files (xml/txt/json etc.) do not get language prefixes; all other content paths always get the prefix. Exemption rules come from a single source, scripts/utils/url-lang-blacklist.js. Standalone page navigation therefore carries the /en/ prefix pointing to the corresponding language version.

Title i18n (page_title_i18n, 2026-09-10): <title> and the cover headline (bg-cover-content.ejs) share page_title_i18n from scripts/helpers/page-title.js: tags/categories/about map by title, the rest map by layout to i18n keys; when it returns null the caller falls back to the original title.

2026-09-27 addendum (i18n batch):

ItemChange
404 pageSwitched to client-side language detection (single file) — copy is chosen dynamically from the browser language / local preference; no longer statically generated per path (/en/404.html etc. retired)
archives aggregate pageUnified pagination across all languages — no longer diverges per language
Encrypted page languageEncryption prompt / button copy follows the page language (hbe-bundle fallback copy goes through MATERY_I18N, E7)
Runtime copySearch / dialog / codeLang runtime copy is i18n-ised (P0/P1)
In-content linksPost internal links (url_for_lang) point to the matching language version (E2)

5.5 Summary

Effect summary: Visiting /de/docs/setup/ (de disabled) → content uses zh-cn with a notice banner; visitors whose browser language is en are asked on first visit whether to switch to the English version.

  • Two languages only: enabled is the only switch, no files to delete
  • Missing translation is not an error: the fallback chain covers it, the page still returns 200
  • Resources get no prefix: url-lang-blacklist.js is the single exemption list
  • Testing: tools/tests/lang-fallback.test.js (L13, fallback chain 4 levels + config compatibility/filtering/validation, 13 assertions); tools/tests/release-test.sh L2x (MATERY_LANG injection / fallback pages / 9 standalone pages 200); tools/tests/unit-standalone.test.js (L13, 22 assertions); tools/tests/lang-client-strategy.test.js (L11, 7 assertions).

6. Wiki Multilingual (docs/api/tutorial sub-sites, revised 2026-09-10)

Purpose: Wiki documentation sub-sites (docs/api/tutorial) with three-column layout + Chinese/English bilingual + fallback mechanism, sharing the same multilingual system as blog posts.

Learning path: minimal front-matter → sidebar & encryption → full parameters → boundaries (style/width traps)

6.1 How to enable

Effect: A page with these two keys renders in a three-column layout (left sidebar + content + right TOC); missing layout degrades it to a normal page, missing wiki leaves it without a sidebar.

Corresponding config (required front-matter):

---
layout: wiki        # required, otherwise the three-column layout is not rendered
wiki: tutorial      # required, sub-site name (docs/api/tutorial)
lang: en            # required for English pages (Pitfall 3)
---

Directory structure:

LanguagePath
Chinese (default)source/{wiki}/ (no prefix)
Englishsource/en/{wiki}/ (/en/ prefix)

Fallback mechanism: No English version → /en/... falls back to showing Chinese + top notice banner (“no en version”) + noindex.

6.2 Common options

① Configure the sidebar

Effect: A grouped navigation appears on the left (writing and others under guide), and the item copy follows the language switch.

Corresponding config (source/_data/{wiki}-sidebar.yml):

# source/_data/docs-sidebar.yml
structure:
  docs:
    - key: guide
      children:
        - key: writing
          title: Writing Guide
  • Entry keys are English snake_case; display text goes through languages/*.yml translations

② Encrypt the whole wiki

Effect: Every page of that wiki requires a password before rendering; after entering it once, other pages of the same wiki auto-decrypt without re-entry (the derived key is stored in localStorage under wiki.<wiki name>, TTL 1 day).

Corresponding config:

# source/_data/docs-sidebar.yml top level
encrypt_password: "{{WIKI_PASSWORD}}"
encrypt_message: "Please enter the access password"
encrypt_placeholder: "Password"
encrypt_button_text: "Enter"

encrypt_-prefixed metadata keys exist only at the top level of the data file (outside the structure section), so they never participate in sidebar navigation rendering.

The encrypt_ family has 4 keys total: encrypt_password (required) + encrypt_message / encrypt_placeholder / encrypt_button_text (optional, fall back to the built-in copy).

③ Internal links

Effect: Absolute paths + .html links automatically become /en/tutorial/... on English pages, so they don’t drop back to the Chinese page.

Corresponding config:

[topic](/tutorial/guide/writing.html)

④ Section numbering

Effect: Wiki pages with hand-written numbering no longer show “1. 1. Overview”.

Corresponding config (same as the blog):

closeAutoTocNum: true

⑤ Adding a new wiki page

Effect: The new page appears in the sidebar, one copy each in Chinese and English, with all 9 language keys present.

Corresponding config (5 steps):

  1. Write the Chinese source/{wiki}/xxx.md (front-matter layout: wiki + wiki: <sub-site>)
  2. Add the English source/en/{wiki}/xxx.md
  3. Update source/_data/{wiki}-sidebar.yml
  4. Add the 9 language translation keys (languages/*.yml)
  5. hexo clean rebuild

6.3 All tunable keys

KeyTypeDefaultAllowed values / rangePurpose
layoutstring—wikiEnable the three-column wiki layout (required)
wikistring—docs / api / tutorialSub-site name, decides the sidebar data file
langstringdefault_langlanguage codeSidebar link language prefix (required for English pages)
closeAutoTocNumbool—trueDisable CSS auto-numbering (for hand-written numbering)
encrypt_passwordstring—any stringSidebar top level: encrypt the whole wiki
encrypt_messagestring—any stringEncryption prompt body
encrypt_placeholderstring—any stringPassword field placeholder
encrypt_button_textstring—any stringDecrypt button copy

6.4 Boundaries & conflicts

Wiki page tag-component styles and layout width — two real traps already hit:

  • Style scoping: Tag component CSS is entirely scoped under .post-container descendant selectors. The wiki <main> must carry both post-container and wiki-main classes for components to receive styles. If new tag component CSS is added without a .post-container prefix, it will be invisible on wiki pages.
  • Layout width: The wiki <main> needs an explicit width: 100% (.wiki-main { width: 100% } in _tags/_base/media.styl), otherwise the flex item’s auto margin triggers shrink-to-fit, making width vary with content amount (pages with less content become narrower). max-width is controlled by the global .post-container rule, keeping all wiki pages at uniform width.

English pages missing lang: en → sidebar links point to /docs/ instead of /en/docs/ (see Pitfall 3 under “Known Pitfalls”).

6.5 Summary

Effect summary: /en/docs/setup/ without an English version shows Chinese content + notice banner + noindex; with an English version it shows English.

  • Two required keys: layout: wiki + wiki: <sub-site>
  • English page trio: don’t forget lang: en
  • Whole-wiki encryption: one line, encrypt_password; encrypt_* never leaks into the sidebar
  • Testing: release-test.sh L2b (en page 200 + fallback notice banner + comment path normalization + default language has no prefix); L2y (wiki encrypted page decryption + sidebar has no structure/i18n/encrypt_ leakage); readmode-integration.test.js asserts <main> contains post-container and .wiki-layout width is consistent across pages.

Purpose: A /galleries/ list + per-album lightbox browsing, with encrypted album support.

Learning path: minimal album → three image forms → full parameters → boundaries

7.1 How to enable

Effect: /galleries/ shows album cards (cover + name + description); clicking opens the lightbox page (thumbnail grid, click for fullscreen, caption shows title/description).

Corresponding config (source/_data/galleries.yml top level + the album page route):

galleries:
  - name: 2020
    cover: /medias_webp/images/01.webp
    description: "My image host"
    photos:
      - /medias_webp/images/02.webp

Companion page (created by hexo new gallery 2020; without it the list card leads to a 404):

---
title: 2020
layout: gallery
---

7.2 Common options

① Single image (full information)

Effect: That image shows its own title and description in the lightbox instead of falling back to the album description.

Corresponding config:

photos:
  - url: /medias_webp/images/01.webp   # image path (required)
    title: "2020 New Year"             # image title (optional, falls back to album description)
    desc: "Shot at the Bund, Shanghai" # image detail (optional, hidden when empty)

② Single image (shorthand)

Effect: Only the path is given; the lightbox title falls back to the album description.

Corresponding config:

photos:
  - /medias_webp/images/02.webp

③ Whole-directory auto scan

Effect: All images in the directory (webp/jpg/jpeg/png/gif/svg/avif) are added automatically, titled “Image 1, Image 2…”, with natural filename ordering (01 < 02 < 10).

Corresponding config:

photos:
  - dir: /medias_webp/featureimages/   # directory path (relative to source/, required)
    title_prefix: "Image"              # title prefix (optional)
    desc: "featureimages series"       # unified directory description (optional)
    sort: asc                          # asc=filename ascending (default) / desc=descending

④ Encrypted album

Effect: The album page asks for a password first; the lightbox is browsable only after decryption.

Corresponding config (album page front-matter):

---
title: private
layout: gallery
password: "{{GALLERY_PASSWORD}}"
---

7.3 All tunable keys

KeyTypeDefaultAllowed values / rangePurpose
galleries[].namestring—any string (must match index.md’s title)Album name
galleries[].coverstring—image pathList page cover
galleries[].descriptionstring—any stringAlbum description (falls back when the lightbox has no title)
photos[].urlstring—image pathSingle image (full form)
photos[].titlestring—any stringSingle image title
photos[].descstring—any stringSingle image description
photos[] (string)string—image pathSingle image shorthand
photos[].dirstring—directory path (relative to source/)Directory scan form
photos[].title_prefixstring—any stringDirectory form title prefix
photos[].sortstringascasc / descDirectory form ordering
password (page front-matter)string—any stringEncrypted album

7.4 Boundaries & conflicts

  • The three photos forms can be mixed, ordered by array position; multiple directories are not interleaved (each directory sorts internally).
  • name must match the title of source/galleries/<name>/index.md, otherwise the list card leads to a 404.
  • After decryption the lightbox goes through the unified initGallery() (hbe-bundle onSuccess), see §11.4.

7.5 Summary

Effect summary: List cards + inner-page lightGallery lightbox browsing; encrypted albums appear after decryption.

  • Easiest: one dir: line scans a whole directory
  • Need captions: use url + title + desc, three lines
  • Need privacy: add password to the page front-matter
  • Testing: /galleries/ list, /galleries/2020/ lightbox + caption, /galleries/private/ encryption/decryption UI.

8. Search Feature

Purpose: A navbar search box + popup with live results, three switchable engines.

Learning path: default engine → change engine / shrink the index → full parameters → boundaries

8.1 How to enable

Effect: A search input (#searchInput) appears in the navbar; clicking it or pressing Ctrl+K (Mac ⌘+K) opens the search overlay, and results appear as you type (auto trigger).

Corresponding config (the search block of theme _config.yml):

search:
  default: "algolia"     # default engine: local | algolia | pagefind
  algolia:
    enable: true         # master switch
  local:
    enable: true
    path: /search.json   # local index output path (theme generator local-search.js)
  pagefind:
    enable: true         # after build, npx pagefind scans public/ for a static index

Three engines: local (local search.json) + algolia (Algolia API) + pagefind (Pagefind index).

8.2 Common options

① Fully local, no external service

Effect: Search only fetches /search.json with no external requests; the cost is an index that grows with the post count (a large site’s first open is a bit slower).

Corresponding config:

search:
  default: "local"
  algolia:
    enable: false
  pagefind:
    enable: false

If the engine pointed to by default has enable: false, it automatically degrades to the first enabled engine and logs a warning.

② Shrink the index scope

Effect: Only post titles are indexed (content: false), so search.json shrinks a lot — at the cost of only matching by title.

Corresponding config:

search:
  local:
    enable: true
    field: [post]          # post | page | wiki | all | array combinations
    content: false         # false = match titles only

③ Search only on Enter

Effect: No requests while typing; search runs on Enter or button click (saves bandwidth on large indexes).

Corresponding config:

search:
  local:
    trigger: manual        # auto (search while typing) | manual (Enter/button)

④ Algolia record size

Effect: With content_length: 2500 each Chinese record is about 7.5KB, so 1000 records ≈ 7.5MB (Algolia recommends ≤10MB per batch); setting 25000 exceeds the 10KB-per-record limit and the push fails with a 400.

Corresponding config:

search:
  algolia:
    content_length: 2500   # plain-text body truncation (2000-2500 recommended for Chinese)
    excerpt_length: 300    # excerpt truncation
    batch_size: 1000       # records pushed per batch

8.3 All tunable keys

KeyTypeDefaultAllowed values / rangePurpose
search.defaultstringalgolialocal / algolia / pagefindDefault engine (auto-degrades when disabled)
search.algolia.enablebooltruetrue / falseAlgolia engine switch
search.algolia.indexNamestringblogany index nameAlgolia index
search.algolia.content_lengthint25002000-2500 (recommended for Chinese)Body truncation length
search.algolia.excerpt_lengthint300150-300Excerpt truncation length
search.algolia.batch_sizeint1000whole batch ≤10MBRecords pushed per batch
search.local.enablebooltruetrue / falseLocal engine switch
search.local.pathstring/search.jsonoutput pathIndex file location
search.local.fieldarray[post, wiki]post / page / wiki / all / array combinationsSearch scope
search.local.contentbooltruetrue / falseWhether to scan the body
search.local.formatstringstriptagsstriptags / rawIndexed body format
search.local.triggerstringautoauto / manualTrigger mode
search.local.top_n_per_articleint1-1 shows allMatched snippets per post
search.pagefind.enablebooltruetrue / falsePagefind engine switch
search.pagefind.output_subdirstringpagefindsubdirectory relative to public/ (don’t start with _)Index output directory

search.local.unescape / preload exist in the config, but the comments explicitly say “not wired into the current implementation, planned” — changing them has no effect, and other values are unverified.

8.4 Boundaries & conflicts

  • /search.json is a build artifact of the theme generator; hand edits are overwritten by the next build.
  • All three engines inherit the same base class and share _highlight / _escapeHtml; a new engine that doesn’t inherit it will highlight and escape differently from the other two.
  • #searchInput comes from the navbar template and is unrelated to the search config — the input remains even if every engine is off.
  • Encrypted posts are automatically excluded from the Pagefind index via the conditional data-pagefind-body rendering in post-detail.ejs.

Interaction:

  • Popup: Opens on click/focus of the navbar search box; Ctrl+K (Mac ⌘+K) shortcut opens it
  • Engine switching: Dropdown inside the popup switches between local / Algolia / Pagefind
  • Multi-language filtering: Filters by language prefix + de-duplicates via fallback (applyLangFilter)
  • Unified highlighting: All three engines inherit the same base class, sharing _highlight/_escapeHtml (consistent result highlighting)

8.5 Summary

Effect summary: #searchInput is visible; the popup opens; /search.json is accessible.

  • Most worry-free: local.enable: true + field: [post], zero external dependencies
  • Search the whole site: field: [post, wiki], the index grows
  • Index blew up: try content: false first, then consider trigger: manual
  • Testing: page contains #searchInput; /search.json is accessible; the popup opens.

9. Comment System

Purpose: A comment box at the bottom of post / message / friends / status pages.

Learning path: pick an engine → common appearance options → full parameters → boundaries (Valine is deprecated)

9.1 How to enable

Effect: A Waline comment box appears at the bottom of the page (with Markdown editing, Emoji, likes), following dark mode automatically.

Corresponding config (the post.comments section of theme _config.yml):

post:
  comments:
    enable: true
    type: waline        # utterances|disqus|gitalk|gitment|valine|waline|changyan|livere|remark42|twikoo|cusdis|giscus|discuss

Per-page override (front-matter; comments is the switch, comment selects the tool — writing them in the wrong place has no effect):

---
comments: true        # switch (false = comments off for this post)
comment: waline       # tool selection (string)
---

9.2 Common options

① Change avatar and language

Effect: Comment avatars switch away from the Gravatar style; UI copy follows lang.

Corresponding config:

waline:
  serverURL: 'https://waline.17lai.site'
  avatar: 'mp'        # ''/mp/identicon/monsterid/wavatar/retro/hide
  lang: zh-CN

② Dark-mode adaptation

Effect: When the site switches to dark, the comment box re-skins in sync, with no glaring white area.

Corresponding config:

waline:
  dark: 'html[data-user-color-scheme="dark"]'

③ Length limit and pagination

Effect: Comments over wordLimit cannot be submitted; the list shows pageSize entries per page.

Corresponding config:

waline:
  wordLimit: 1000     # 0 = unlimited
  pageSize: 10

④ Disable comments for one post

Effect: That post renders no comment area at the bottom (#comments does not appear).

Corresponding config:

---
comments: false
---

9.3 All tunable keys

KeyTypeDefaultAllowed values / rangePurpose
post.comments.enablebooltruetrue / falseMaster switch for post comments
post.comments.typestringwalinesee the enum aboveGlobal comment engine
waline.enablebooltruetrue / falseWaline client switch
waline.serverURLstring—Waline server URLComment backend address
waline.avatarstringmp'' / mp / identicon / monsterid / wavatar / retro / hideAvatar style
waline.langstringzh-CNlanguage codeUI language
waline.darkstringhtml[data-user-color-scheme="dark"]CSS selectorDark-mode hook
waline.loginstringenableenable / force / disableLogin mode
waline.wordLimitint10000 = unlimitedComment length limit
waline.pageSizeint10any positive integerList pagination size
waline.highlighterstringhanabihighlighter nameCode highlighting inside comments
waline.highlight.enableboolfalsetrue / falseDisable the original highlighter
front-matter commentsbool—true / falsePer-page switch
front-matter commentstring—waline etc.Per-page engine override

9.4 Boundaries & conflicts

  • valine.enable: false is the disabled state; the valine.* section remains only as a historical leftover. The actual engine is Waline.
  • Without comment in front-matter, the global post.comments.type applies; comments is the switch and comment selects the tool — don’t mix the two keys (post-filter.js processes defaults on this convention).
  • The comment area depends on the #comments container; when a page doesn’t inject it the script never initializes — the symptom is a blank area, not an error.

Deprecated: Valine (valine.enable: false) is retired; the actual comment engine is Waline.

9.5 Summary

Effect summary: Waline comment box (Markdown/Emoji/likes/admin backend).

  • Minimum viable: post.comments.enable + waline.serverURL, two items
  • Turn off for one post: front-matter comments: false
  • Switch engine: change post.comments.type (other engines’ parameters are not expanded here; other values unverified)
  • Testing: post/msg/friends/bb pages contain #comments; the waline init script exists.

10. Dark Mode

Purpose: Site-wide light/dark switching, following the system or local time.

Learning path: switch + default → the ordering auto follows → full parameters → boundaries

10.1 How to enable

Effect: A light/dark toggle button appears in the navbar; under auto the site uses dark if the system is dark, and enters dark by local time 18:00–6:00 when the system has no preference; a manual choice from the toggle/floating panel overrides the default.

Corresponding config (theme _config.yml):

dark_mode:
  enable: true
  default: auto   # auto | light | dark

10.2 Common options

① Force light (don’t follow the system)

Effect: First visit is light regardless of system/time; readers can still switch to dark manually.

Corresponding config:

dark_mode:
  default: light

② Force dark

Effect: Dark on first visit (suits night-oriented content sites).

Corresponding config:

dark_mode:
  default: dark

10.3 All tunable keys

KeyTypeDefaultAllowed values / rangePurpose
dark_mode.enablebooltruetrue / falseMaster switch for dark mode
dark_mode.defaultstringautoauto / light / darkInitial mode

10.4 Boundaries & conflicts

  • The auto ordering is fixed: the system prefers-color-scheme first; only when the system has no clear preference does it use local time 18:00–6:00.
  • Manual switching (button or floating panel) writes a local preference that overrides default; clearing local storage falls back to default.
  • Attribute-driven: [data-user-color-scheme="dark"] swaps a whole set of CSS variables, so components with hard-coded colors won’t follow (see docs/dark-mode-principles.md).
  • Turning enable off removes the button, but historical local preferences remain — readers who stored dark locally need to clear localStorage to get back to light.

10.5 Summary

Effect summary: The [data-user-color-scheme="dark"] attribute drives a full set of CSS variable switches; images/charts adapt automatically.

  • The default is fine: enable: true + default: auto
  • Change the default: change the one default value
  • New components don’t follow: use var(--*), never hard-code colors (see §15)
  • Testing: CSS contains [data-user-color-scheme="dark"] rules; the toggle button switches light/dark.

11. Encrypted Posts

Purpose: Batch-encrypt posts by tag; readers enter a password to decrypt. Also supports whole-post / whole-wiki encryption.

Learning path: tag encryption → copy & key caching → full parameters → boundaries + refresh after decryption

11.1 How to enable

Effect: A post carrying the encryption tag shows only the decryption UI (#hbePass + password field); the body renders only after the correct password.

Corresponding config (the encrypt section of root _config.yml):

encrypt:
  enable: true
  abstract: Something is encrypted here, please enter the password to view.
  message: Hello, a password is required here.
  tags:
    - {name: private, password: "{{TAG_PASSWORD}}" }
  wrong_pass_message: Sorry, that password doesn't look right, please try again.

Common options:

① Encrypt by tag

Effect: Every post with tags: [private] is encrypted automatically, no per-post configuration; after removing the tag a rebuild is needed to restore plaintext.

Corresponding config:

encrypt:
  tags:
    - {name: private, password: "{{PWD_1}}"}
    - {name: mywork, password: "{{PWD_2}}"}

② Per-post password

Effect: That post uses its own password, unaffected by tag rules; password: "" keeps a post unencrypted even under a tag.

Corresponding config (front-matter):

---
tags:
  - private
password: "{{POST_PASSWORD}}"
default_abstract: 本文已加密      # encryption prompt copy (optional)
---

③ No re-entry after decryption

Effect: Refreshing the page skips the password field (the AES key is cached in localStorage under hbe.v4.<post-permalink-hash>).

Corresponding config:

encrypt:
  autoSave: true       # enable globally; can also be set per post in front-matter

④ Stable salt (static hosting platforms)

Effect: The salt stays the same across clean builds, so readers’ local caches don’t break on every redeploy; the AES-GCM nonce is still random each time (avoiding nonce reuse).

Corresponding config:

encrypt:
  stableSalt: true
  kdf:
    iterations: 600000   # default 250000; floor 100000, recommend ≥600000 (OWASP 2023)

11.2 All tunable keys

KeyTypeDefaultAllowed values / rangePurpose
encrypt.enablebooltruetrue / falseMaster switch for encryption
encrypt.abstractstringSomething is encrypted here, please enter the password to view.any stringAbstract-area hint
encrypt.messagestringHello, a password is required here.any stringDecryption-box hint
encrypt.tagsarray—array of {name, password} objectsPosts matching these tags are encrypted automatically
encrypt.wrong_pass_messagestringSorry, that password doesn't look right, please try again.any stringWrong-password hint
encrypt.autoSavebooltrue (this site’s value)true / falseCache the derived key in localStorage
encrypt.stableSaltboolfalsetrue / falseStable PBKDF2 salt across clean builds
encrypt.kdf.iterationsint250000≥100000, recommend ≥600000PBKDF2 iterations
front-matter passwordstring—any string ("" = no encryption)Per-post password
front-matter autoSavebool—true / falsePer-post key-cache override

11.3 Boundaries & conflicts

  • It works by tag matching, not a per-post switch: adding the tag encrypts, and removing it requires a rebuild to restore plaintext.
  • Not showing the TOC in the encrypted state is by design (see Pitfall 2 under “Known Pitfalls”); tests must not hard-code “TOC must exist”.
  • After decryption you must go through the unified hbe-bundle onSuccess refresh, otherwise code blocks/lightboxes/Mermaid in the body never initialize.
  • Setting kdf.iterations below the recommended value prints a warning at build (not an error; the build still succeeds).

11.4 Unified Refresh After Decryption (Added 2026-09-09)

Effect: The moment decryption succeeds, the code-block toolbars, image lightbox, Mermaid diagrams, and masonry layout in the body all fall into place at once (before decryption these elements don’t exist in the DOM at all).

Corresponding mechanism (no config key, triggered uniformly by hbe-bundle onSuccess):

ComponentAction after decryption
Code blocks (code-area)codeWidget() scans new pre elements to generate toolbar (language label/copy/collapse/fullscreen)
Image lightboxarticleInit() wraps img → .img-item + lightGallery binding (shared for post/wiki)
Mermaid diagramsevents.refresh() triggers the refresh callback to re-render (data-processed idempotent)
Layout (AOS/Masonry)boot.refresh() → refreshLayout re-arranges

Unified trigger point: hbe-bundle onSuccess (all encryption scenarios: post/gallery/wiki/snippet shared). Each listener retains only its unique handling:

  • post: tocbot reinit (post TOC)
  • wiki: TOC encryption-state removal + tocbot reinit
  • gallery: initGallery()

Idempotent protection: codeWidget data-code-processed, mermaid data-processed, articleInit destroys the old instance and rebuilds — repeated calls don’t produce duplicate elements.

11.5 Summary

Effect summary: The post page shows the decryption UI (#hbePass); the body renders after the correct password.

  • Minimum viable: enable: true + tags: [{name, password}]
  • Never use plaintext passwords: passwords in config should go through placeholders/private config, never a public repo
  • Readers find it annoying: autoSave: true
  • Vercel/CF Pages: stableSalt: true, otherwise every deploy invalidates all caches
  • Testing: tag-encrypted posts contain #hbePass; after decryption .code-toolbar count = .code-area count; image wrapping .img-item + container lg-uid attribute exist.

12. RSS / Sitemap

Purpose: Output subscription feeds (RSS/Atom/JSON Feed) and sitemaps for search engine crawling.

Learning path: minimal config → turn off a format → full parameters → boundaries

12.1 How to enable

Effect: The site root gains /rss.xml, /atom.xml, /feed.json (feeds) and /sitemap.xml, /baidusitemap.xml (for crawling).

Corresponding config (root _config.yml):

feed:
  limit: 10
  order_by: "-date"
  tag_dir: false
  category_dir: "categories"
  rss:
    enable: true
    output: "rss.xml"
  atom:
    enable: true
    output: "atom.xml"
  jsonFeed:
    enable: true
    output: "feed.json"

sitemap:
  path: sitemap.xml

baidusitemap:
  path: baidusitemap.xml

12.2 Common options

① Atom only

Effect: /rss.xml and /feed.json are no longer generated; only /atom.xml remains (modern readers all handle Atom).

Corresponding config:

feed:
  rss:
    enable: false
  atom:
    enable: true
  jsonFeed:
    enable: false

② Export only the latest 20 posts

Effect: At most 20 entries in the feed; old posts stay out of the feed (new readers aren’t flooded with history).

Corresponding config:

feed:
  limit: 20
  order_by: "-date"

③ Change the output path

Effect: Feeds move to custom filenames; after changing you must clean-build, otherwise the old atom.xml / sitemap.xml stay in public/.

Corresponding config:

sitemap:
  path: sitemap-custom.xml

12.3 All tunable keys

KeyTypeDefaultAllowed values / rangePurpose
feed.limitint10any positive integerPosts included in each feed
feed.order_bystring-dateany field (prefix - for descending)Ordering
feed.tag_dirboolfalsetrue / falseWhether to output per-tag feeds
feed.category_dirstringcategoriesdirectory nameCategory feed directory
feed.rss.enablebooltruetrue / falseRSS output switch
feed.rss.outputstringrss.xmloutput filenameRSS path
feed.atom.enablebooltruetrue / falseAtom output switch
feed.atom.outputstringatom.xmloutput filenameAtom path
feed.jsonFeed.enablebooltruetrue / falseJSON Feed output switch
feed.jsonFeed.outputstringfeed.jsonoutput filenameJSON Feed path
sitemap.pathstringsitemap.xmloutput filenameGeneral sitemap
baidusitemap.pathstringbaidusitemap.xmloutput filenameBaidu sitemap

12.4 Boundaries & conflicts

  • feed.*.output controls only its own file; the three are independent, and disabling one doesn’t affect the other two.
  • The Baidu sitemap is the product of another plugin (baidusitemap), unrelated to sitemap.path.
  • After changing path / output a clean build is required, otherwise the old files stay in public/.
  • The theme-side RSS template is themes/matery/layout/_partial/rss.ejs (a custom template); style changes live in the template, not the config.

12.5 Summary

Effect summary: /rss.xml, /atom.xml, /feed.json, /sitemap.xml are all accessible.

  • The default is fine: all three feed formats on, best compatibility
  • Fewer artifacts: turn off rss/jsonFeed as you like
  • Changes don’t apply: clean (Pitfall 5)
  • Testing: /rss.xml, /atom.xml, /feed.json, /sitemap.xml are all accessible.

13. PWA

Purpose: Installable + offline cache + auto-refresh on version update.

Learning path: master switch → cache list → full parameters → boundaries (localhost exemption)

13.1 How to enable

Effect: An install button appears in Chrome’s address bar, and the installed app runs in its own window; cached pages still open offline; after a new release the first visit auto-refreshes once.

Corresponding config (theme _config.yml):

pwa:
  enable: true

13.2 Common options

① Change the cache list

Effect: Resources in the list are pre-cached on first visit (/css/main.css, js/boot.js etc.) and available offline; anything not listed is cached on demand.

Corresponding config (userConfig/sw.tmp.js):

var cacheList = [
  '/css/main.css{urlVersion}',
  '/css/highlight.css{urlVersion}',
  '{cdnUrl}/js/boot.js{urlVersion}',
  '{cdnUrl}/js/events.js{urlVersion}'
];

② Cache version key

Effect: {uniqueIdentifier} is replaced by CI with the build timestamp (17lai-cache-{timestamp}); as soon as the key changes it counts as a new version, triggering one auto-refresh and clearing old 17lai-cache-*.

Corresponding config:

const cacheStorageKeyPrefix = '17lai-cache-';
const cacheStorageKey = `17lai-cache-{uniqueIdentifier}`;

13.3 All tunable keys

KeyTypeDefaultAllowed values / rangePurpose
pwa.enablebooltruetrue / falsePWA master switch
userConfig/sw.tmp.jstemplate—CI injects {uniqueIdentifier} then generates source/sw.jsService Worker template
cacheListarraysee templatearray of resource pathsPre-cache list
cacheStorageKeystring17lai-cache-{uniqueIdentifier}prefix + identifierCache key (change = new version)

The pwa section’s manifest (name/icons/theme color) is injected at build time; the exact key names are not expanded here, and other values are unverified.

13.4 Boundaries & conflicts

  • source/sw.js is a build artifact; hand edits are overwritten by CI — change sw.tmp.js to change the logic.
  • localhost exempts SW registration (for testing); verifying offline capability requires a domain (e.g. the test domain).
  • A change to the cache key counts as a new version and triggers one auto-refresh; skipWaiting + clients.claim() let the new SW take over immediately and clear old 17lai-cache-*.
  • Changing cacheList without changing the version key (non-CI build) means browsers never notice the update.

13.5 Summary

Effect summary: Installable (manifest), offline caching of static assets, auto-refresh on version update.

SW version comparison & auto-refresh: When registering the SW, updatefound (new SW installed) and controllerchange are monitored; the old and new cacheStorageKey are compared — if changed, the page auto-refreshes once (no prompt, the user doesn’t need to refresh manually).

  • The default is fine: pwa.enable: true, leave the rest to CI
  • Add pre-caching: append paths to cacheList, remember {urlVersion}
  • Can’t test locally: localhost is exempt, use the test domain
  • Testing: /sw.js is accessible, SW registration works (localhost exempted).

14. SEO Structured Data (JSON-LD + Open Graph)

Purpose: Provide structured metadata for search engines and social platforms: JSON-LD rich results + Open Graph / Twitter Card share previews.

Learning path: what it outputs automatically → entities and @id → full parameters → boundaries (no switch)

14.1 How to enable

Effect: Every page’s <head> carries a <script type="application/ld+json"> (@graph in a single script: WebSite + Person + Organization, with BlogPosting appended on post pages), plus og:type/title/url/site_name/description/image and twitter:card=summary_large_image. Sharing to social platforms shows a title/description/cover card.

Corresponding config: No standalone toggle — output unconditionally by head.ejs.

layout/_partial/common/structured-data.ejs   # JSON-LD (@graph)
layout/_partial/common/head.ejs              # OG / Twitter Card

14.2 Common options

① Site search box rich result

Effect: Google results may show a Sitelinks Searchbox that jumps straight into the site search.

Corresponding config: Carried by the SearchAction inside the WebSite entity, pointing at the site search URL (fixed in the template, no standalone key).

② Author/publisher association

Effect: BlogPosting.author points to #person, publisher to #organization, so rich-result validation reports no “missing entity”.

Corresponding config: @id cross-references (changing an @id requires updating the referring side too).

14.3 All tunable keys

KeyTypeDefaultAllowed values / rangePurpose
Switch——none (output unconditionally by head.ejs)No standalone config item
@graph entities——WebSite (with SearchAction), Person, Organization; BlogPosting appended on post pagesStructured data
Description truncation—210 characters—Truncation length after strip_html

14.4 Boundaries & conflicts

  • No switch: to turn it off you can only edit the structured-data.ejs / head.ejs templates.
  • @id values cross-reference each other (publisher→#organization, author→#person); changing an @id requires updating the referring side, otherwise rich-result validation fails.
  • JSON-LD and OG/Twitter are two independent outputs; missing one doesn’t affect the other.
  • Descriptions are truncated at 210 characters after strip_html — changing the truncation length means editing the template, not the config.

14.5 Summary

Effect summary: Pages contain application/ld+json; post pages contain BlogPosting; og:type / twitter:card markers are present.

  • Zero config: on by default, nothing to enable
  • Change the content: edit structured-data.ejs, mind the bidirectional @id references
  • No image when sharing: check the post’s img / cover, not JSON-LD
  • Testing: pages contain application/ld+json; post pages contain BlogPosting; og:type / twitter:card markers are present.

15. Design Tokens & CSS Variable Architecture

Purpose: Unify design tokens (border-radius/shadow/transition/spacing/font-size) and deliver them through a three-layer chain to CSS custom properties for site-wide reference, avoiding hardcoded values.

Learning path: where tokens are defined → change one place, site-wide effect → full parameters → boundaries (three-layer chain)

15.1 How to enable

Effect: Card corners are uniformly 8px, buttons 3px, modals 12px; cards default to shadow_md, hover to shadow_lg; spacing increments by 4px; body font size scales proportionally with the preference panel’s --font-scale.

Corresponding config (the design section of theme _config.yml):

design:
  radius_sm: 3px          # Buttons / small labels
  radius_md: 8px          # Cards / notes
  radius_lg: 12px         # Modals
  shadow_md: "0 2px 5px 0 rgba(0,0,0,0.16)"
  shadow_lg: "0 5px 11px 0 rgba(0,0,0,0.18)"
  transition_fast: 0.2s
  space_1: 4px            # 4px base increment
  font_size_md: 1.125rem  # rem-based, scales with --font-scale

Three-layer delivery chain:

_config.yml design.* → theme-config() → Stylus variables → :root CSS custom properties → components var(--*)
  • Scheme layer: source/css/_schemes/matery.styl (aligned with NexT _schemes/ mechanism, extensible for future schemes)
  • Font size: root font size calc(var(--font-size-base) * var(--font-scale)), preference panel adjusts --font-scale for site-wide rem proportional scaling

15.2 Common options

① Change the corner style

Effect: Shrinking all three radius steps together makes cards/buttons/modals look “squarer” in sync; changing only radius_md leaves buttons and cards stylistically inconsistent.

Corresponding config:

design:
  radius_sm: 2px
  radius_md: 4px
  radius_lg: 6px

② Tune dark-mode shadows

Effect: Shadows don’t look dirty in dark mode (light shadows turn grey on a dark background), while the card’s lifted feel is preserved.

Corresponding config:

design:
  shadow_md: "0 2px 5px 0 rgba(0,0,0,0.16)"
  shadow_md_dark: "0 2px 5px 0 rgba(0,0,0,0.45)"

15.3 All tunable keys

KeyTypeDefaultAllowed values / rangePurpose
design.radius_smlength3pxany CSS lengthButton / small label corners
design.radius_mdlength8pxany CSS lengthCard / note corners
design.radius_lglength12pxany CSS lengthModal corners
design.radius_pilllength999pxany CSS lengthPill corners
design.radius_fulllength50%any CSS lengthCircle
design.shadow_smstring"0 1px 3px 0 rgba(0,0,0,0.12)"valid box-shadowSubtle floating shadow
design.shadow_mdstring"0 2px 5px 0 rgba(0,0,0,0.16)"valid box-shadowCard default
design.shadow_lgstring"0 5px 11px 0 rgba(0,0,0,0.18)"valid box-shadowCard hover
design.shadow_xlstring"0 10px 30px 0 rgba(0,0,0,0.2)"valid box-shadowModal / overlay
design.shadow_*_darkstring0 1px 3px …0.4 etc.valid box-shadowDark-mode counterpart shadows
design.transition_fasttime0.2sany CSS timeHover feedback
design.transition_normaltime0.3sany CSS timePanels / modals
design.gradient_primarystringlinear-gradient(to right, #4facfe, #00f2fe)valid linear-gradientNav / button gradient
design.gradient_accentstringlinear-gradient(135deg, #667eea, #764ba2)valid linear-gradientCard decorative gradient
design.space_1length4pxany CSS lengthSpacing base
design.space_2length8pxany CSS lengthSpacing step
design.space_3length12pxany CSS lengthSpacing step
design.space_4length16pxany CSS lengthSpacing step
design.space_5length24pxany CSS lengthSpacing step
design.font_size_xslength0.75remrem valueFont-size step
design.font_size_smlength0.875remrem valueFont-size step
design.font_size_mdlength1.125remrem valueBody size (scales with --font-scale)
design.font_size_lglength1.25remrem valueFont-size step
design.font_size_xllength1.5remrem valueFont-size step
design.font_size_2xllength2remrem valueFont-size step

15.4 Boundaries & conflicts

  • Tokens land on :root custom properties through the three-layer chain; components must use var(--*) to follow — hardcoded values never change.
  • font_size_md is rem-based: changing it changes the site-wide size basis, and the preference panel’s --font-scale multiplies on top of it.
  • The mapping lives in the scheme layer source/css/_schemes/matery.styl; renaming a token requires updating the scheme too, otherwise the variable dangles and components get no value.
  • Dark-mode shadows must use the *_dark set; reusing light shadows directly makes them nearly invisible on a dark background.

15.5 Summary

Effect summary: Components reference tokens uniformly (consistent corners/shadows/spacing); changing one place in the design section applies site-wide.

  • Change corners/shadows/spacing: edit the design section, not the components
  • Dark mode needs its own values: *_dark is not optional
  • New components: use var(--*); hardcoding means it won’t follow the theme
  • Testing: CSS contains --font-scale rules and the root font size calc(... * var(--font-scale)).

⚠️ Known Pitfalls

Pitfall 1: Double Section Numbering

Symptom: Headings render as “1. 1. Overview” (two numbers).

Cause: Theme CSS auto-adds numbers to h2–h6 by default; hand-written numbers (e.g. ## 1. Overview) stack on top.

Fix: Pages with hand-written numbering add closeAutoTocNum: true in front-matter; pages without hand-written numbering must not add this field.

This article already correctly sets closeAutoTocNum: true (front-matter line 19).

Pitfall 2: Encryption ↔ TOC Conflict

Symptom: When a wiki is encrypted as a whole, the TOC is hidden by design.

Cause: In encryption mode the TOC component is skipped (intended behavior).

Fix: Test assertions must not hard-code “TOC must exist”. Encrypted wiki pages not showing TOC is normal behavior, not a bug.

Pitfall 3: Wiki English Pages Missing lang: en

Symptom: Sidebar links point to /docs/ instead of /en/docs/.

Cause: wiki_sidebar uses page.lang || default_lang; omitting lang: en falls back to the default language path.

Fix: All pages under source/en/tutorial/ must include lang: en. Verify: for f in source/en/tutorial/**/*.md; do grep -L 'lang: en' "$f"; done.

Pitfall 4: _config.tmp.yml Comment Lines Must Be Preserved

Symptom: Attempted to delete comment lines to slim the file, was vetoed and fully reverted.

Cause: User explicitly declared comment lines are useful reserves (may be restored in the future).

Fix: Never delete or modify comment lines in userConfig/_config.tmp.yml.

Pitfall 5: Config Changes Require Clean Build

Symptom: Changed configuration but the page didn’t update.

Cause: Hexo’s caching mechanism doesn’t auto-detect configuration changes.

Fix: After changing config or source/_data/*, you must run npm run clean && npm run build. Build logs showing INFO Deleted database. and INFO Deleted public folder. confirm clean ran successfully.

Pitfall 6: source/_data/* Incremental Cache Misjudgment

Symptom: After modifying source/_data/friends.yml and other data files, the page is blank or data doesn’t update.

Cause: Hexo’s incremental cache incorrectly judges “cached, unchanged” (Cache hash updated but Data model not written).

Fix:

  • Local: rm -f db.json && npm run build
  • Container: tools/cicd.sh -d (includes clean + generate + config injection)
  • In-container pm2 restart is not enough: pm2 caches old db.json content in memory

Appendix: Layout Feature Quick Reference

FeaturePage / LocationKey ConfigurationAutomated Assertion Marker
Prev/nextPost bottomno key (post.prev_next.enable is never read)#prenext-posts
CopyrightPost bottompost.copyright.enable / license#reprint-statement
Outdated noticePost toppost.outdateoutdate
TOCRight side / sidebartoc (top-level)#toc-content
Ad slotBelow TOCpost.advertisements.tgCard
Category radar/categories/no key (categories.ejs)canvas (Matery.echarts light/dark switch)
Tag cloud / word cloud/tags/wordcloud.minHeight / heightPerWord.tag-chips / #tag-wordcloud
ArtiTalk/about/artitalk.enable: false (disabled by default)LeanCloud backend
My Projects/about/myProjects.enable: true.my-projects
My Skills/about/mySkills.enable: true.my-skills
About page gallery/about/myGallery.enable: true.my-gallery
Archive calendar/archives/postCalendar: true#post-calendar
Online music/musics/musics + failover.aplayer (tools/tests/musics-integration.test.js L2i)
Archive timeline/archives/no key (archive.ejs)#cd-timeline
About page charts/about/no key (about.ejs)canvas
Galleries/galleries/galleries.ymlLightbox + encryption UI
SearchNavbarsearch#searchInput / search.json
CommentsPost/msg etc.post.comments#comments
Dark modeGlobaldark_modedata-user-color-scheme
EncryptionTag-drivenencrypt.tags#hbePass
RSS/SitemapRoot pathsfeed / sitemap/rss.xml etc.
PWAGlobalpwa + sw.tmp.js/sw.js
SEO<head>structured-data.ejs + head.ejsapplication/ld+json / og:type
Design tokensGlobaldesign section + _schemes/--font-scale

References

系列教程

全部文章RSS订阅

Hexo 主题功能测试系列


Hexo Theme Feature Test - Layout & Pages
Posted on
August 7, 2026
reprint policy. If reproduced, please indicate source
Support
Comments
Data Loading...
 Previous

Read More

Hexo Theme Feature Test - Markdown Syntax
Hexo Theme Feature Test - Markdown Syntax Hexo Theme Feature Test - Markdown Syntax
A complete Markdown syntax tutorial and test for the theme: full coverage of 16 markdown-it plugins (emoji/abbr/footnote
2026-08-08
Next 

Read More

Hexo Theme Feature Test - Interaction & Visual
Hexo Theme Feature Test - Interaction & Visual Hexo Theme Feature Test - Interaction & Visual
Complete tutorial and test for matery theme interaction & visual features: code block enhancements, image lightbox, type
2026-08-07