A local-first multi-agent app development platform, built on PenguinHarness
fix(landing): blog links to a Chinese heading anchor land on the heading (#772)
Yaowei Zheng8044a0a25d2f
diff --git a/changelog/unreleased/2026-09-17-blog-cjk-heading-anchors.md b/changelog/unreleased/2026-09-17-blog-cjk-heading-anchors.mdnew file mode 100644index 00000000..c23b1e52--- /dev/null+++ b/changelog/unreleased/2026-09-17-blog-cjk-heading-anchors.md@@ -0,0 +1,17 @@+# Blog links to a Chinese heading anchor scroll to the heading++- **Date:** 2026-09-17+- **Type:** fix+- **Scope:** `landing`, `docs`+- **PR:** [#772](https://github.com/Prism-Shadow/penguin-harness/pull/772)++[中文版](2026-09-17-blog-cjk-heading-anchors.zh.md)++The landing site's router looked up the element for a URL hash without decoding the hash first. Browsers report the fragment percent-encoded, so a link to a Chinese heading such as `#升级须知` arrived as `#%E5%8D%87…` and matched no element, and the page scrolled to the top instead. The router now decodes the hash before the lookup. A shared deep link, an in-post `[…](#…)` link (which opens in a new tab) and a table-of-contents click all scroll to the Chinese heading, as links to English headings already did.++## Details++- Each site gained a `hashTargetId` helper that turns a hash into an element id. It decodes the hash with `decodeURIComponent` and falls back to the raw fragment when an escape is malformed.+- The landing router's scroll-to-hash effect uses the helper. Before, clicking a Chinese table-of-contents entry in a post opened from the blog list pulled the page back to the top.+- The docs site already decoded the hash, but had no fallback. A malformed escape such as `#100%` threw inside its effects and blanked the whole page. Its router and the doc page's table-of-contents highlight now use the same helper.+- A landing test renders every blog post and fails when an in-page link or a table-of-contents entry names no rendered heading.diff --git a/changelog/unreleased/2026-09-17-blog-cjk-heading-anchors.zh.md b/changelog/unreleased/2026-09-17-blog-cjk-heading-anchors.zh.mdnew file mode 100644index 00000000..b72e920d--- /dev/null+++ b/changelog/unreleased/2026-09-17-blog-cjk-heading-anchors.zh.md@@ -0,0 +1,17 @@+# 博客中指向中文标题锚点的链接会滚动到该标题++- **Date:** 2026-09-17+- **Type:** fix+- **Scope:** `landing`, `docs`+- **PR:** [#772](https://github.com/Prism-Shadow/penguin-harness/pull/772)++[English](2026-09-17-blog-cjk-heading-anchors.md)++落地页路由按 URL hash 查找元素时,没有先解码 hash。浏览器给出的 fragment 是百分号编码的,指向中文标题的链接(如 `#升级须知`)到达时变成 `#%E5%8D%87…`,找不到任何元素,页面于是滚回顶部。现在路由先解码 hash 再查找。分享出去的深链接、文章内的 `[…](#…)` 链接(在新标签页打开)和目录点击,都会像指向英文标题的链接一样滚动到中文标题。++## 细节++- 两个站点各新增一个 `hashTargetId` 辅助函数,把 hash 转成元素 id。它用 `decodeURIComponent` 解码 hash,遇到格式错误的转义时退回原始 fragment。+- 落地页路由的滚动定位 effect 改用这个函数。此前从博客列表打开文章后,点击目录中的中文标题会把页面拉回顶部。+- 文档站原本就会解码 hash,但没有退回处理:`#100%` 这类格式错误的转义会在 effect 中抛错,整个页面变成空白。文档站的路由和文档页的目录高亮现在也改用同一个函数。+- 落地页新增一项测试:逐篇渲染博客文章,页内链接或目录条目对应不到任何渲染出的标题时,测试失败。diff --git a/packages/docs/src/lib/hash.ts b/packages/docs/src/lib/hash.tsnew file mode 100644index 00000000..2204f28c--- /dev/null+++ b/packages/docs/src/lib/hash.ts@@ -0,0 +1,21 @@+/**+ * URL hash -> the id of the element it targets. Pure and unit-testable.+ *+ * `location.hash` carries the fragment percent-encoded: a link to the CJK heading+ * `## 安装参考` arrives as `#%E5%AE%89%E8%A3%85%E5%8F%82%E8%80%83`, while the heading's id+ * (slugifyHeading in toc.ts) holds the decoded text, so the fragment is decoded before+ * any lookup. A malformed escape (`#100%`) cannot be decoded and falls back to the raw+ * fragment instead of throwing — a throw inside a React effect would unmount the page.+ * The leading `#` is optional, and a fragment without escapes comes back unchanged.+ *+ * The landing site carries the same helper (packages/landing/src/lib/hash.ts); the two+ * sites share no package, so keep them aligned.+ */+export function hashTargetId(hash: string): string {+ const fragment = hash.startsWith("#") ? hash.slice(1) : hash;+ try {+ return decodeURIComponent(fragment);+ } catch {+ return fragment;+ }+}diff --git a/packages/docs/src/pages/doc-page.tsx b/packages/docs/src/pages/doc-page.tsxindex 7c979509..cb163598 100644--- a/packages/docs/src/pages/doc-page.tsx+++ b/packages/docs/src/pages/doc-page.tsx@@ -21,6 +21,7 @@ import { useLocale } from "../state/locale";import { docMarkdown, docTitle, getDoc } from "../lib/docs";import { HOME_SLUG, pagerFor, sectionOf } from "../lib/nav";import { extractToc, slugifyHeading } from "../lib/toc";+import { hashTargetId } from "../lib/hash";import { remarkCallout } from "../lib/remark-callout";import { remarkTabs } from "../lib/remark-tabs";import { CopyMarkdownButton } from "../components/copy-markdown-button";@@ -189,7 +190,7 @@ export function DocPage() {useEffect(() => {if (toc.length < 2) return;// Deep links carry the anchor percent-encoded (CJK headings); pin it if it is ours.- const initialHash = decodeURIComponent(window.location.hash.slice(1));+ const initialHash = hashTargetId(window.location.hash);pinnedId.current = toc.some((entry) => entry.id === initialHash) ? initialHash : null;let raf = 0;const update = () => {@@ -227,7 +228,7 @@ export function DocPage() {// Same-page hash navigation (address bar / in-content anchors) re-runs no effect,// so re-evaluate the pin whenever the hash changes.const onHashChange = () => {- const hash = decodeURIComponent(window.location.hash.slice(1));+ const hash = hashTargetId(window.location.hash);if (toc.some((entry) => entry.id === hash)) {pinnedId.current = hash;setActiveId(hash);diff --git a/packages/docs/src/router.tsx b/packages/docs/src/router.tsxindex abedaf7f..1a0dd840 100644--- a/packages/docs/src/router.tsx+++ b/packages/docs/src/router.tsx@@ -10,6 +10,7 @@ import { Nav } from "./components/nav";import { Sidebar } from "./components/sidebar";import { Footer } from "./components/footer";import { DocSearchDialog } from "./components/doc-search-dialog";+import { hashTargetId } from "./lib/hash";import { DocPage } from "./pages/doc-page";/**@@ -62,7 +63,7 @@ function Layout() {handledLocationKey = key;if (hash) {// Anchors of CJK headings arrive percent-encoded in the URL hash.- const el = document.getElementById(decodeURIComponent(hash.slice(1)));+ const el = document.getElementById(hashTargetId(hash));if (el) {el.scrollIntoView();return;diff --git a/packages/docs/test/content.test.ts b/packages/docs/test/content.test.tsindex 5fbfe0a0..6df12f69 100644--- a/packages/docs/test/content.test.ts+++ b/packages/docs/test/content.test.ts@@ -15,14 +15,15 @@ import { join } from "node:path";import { describe, expect, it } from "vitest";import { DOCS_NAV, DOC_SLUGS, pagerFor } from "../src/lib/nav";import { parseFrontmatter } from "../src/lib/frontmatter";+import { hashTargetId } from "../src/lib/hash";import { extractToc } from "../src/lib/toc";const contentDir = join(__dirname, "..", "content");const files = readdirSync(contentDir).filter((f) => f.endsWith(".md"));-/** In-page targets of Markdown links, i.e. "[label](#anchor)" (percent-decoded). */+/** In-page targets of Markdown links, i.e. "[label](#anchor)", resolved as the router does. */function inPageAnchors(body: string): string[] {- return [...body.matchAll(/\]\(#([^)\s]+)\)/g)].map((match) => decodeURIComponent(match[1]!));+ return [...body.matchAll(/\]\(#([^)\s]+)\)/g)].map((match) => hashTargetId(match[1]!));}/** Slugs of absolute doc links, i.e. "[label](/slug)" or "[label](/slug#anchor)". */diff --git a/packages/docs/test/hash.test.ts b/packages/docs/test/hash.test.tsnew file mode 100644index 00000000..89eb2675--- /dev/null+++ b/packages/docs/test/hash.test.ts@@ -0,0 +1,57 @@+/**+ * hashTargetId: the URL hash -> element id step behind the router's scroll-to-hash effect and+ * the page's TOC pin. A browser reports a CJK fragment percent-encoded in location.hash, so+ * the heading id only matches once the hash is decoded; a malformed escape must fall back+ * instead of throwing, which inside an effect blanked the whole page.+ */+import { describe, expect, it } from "vitest";+import { hashTargetId } from "../src/lib/hash";+import { slugifyHeading } from "../src/lib/toc";++/** The hash a browser reports after following a link to `#<fragment>` (WHATWG URL parsing). */+const locationHash = (fragment: string) =>+ new URL(`#${fragment}`, "https://example.test/docs/quickstart-cli").hash;++describe("hashTargetId", () => {+ it("decodes a percent-encoded Chinese hash", () => {+ expect(hashTargetId("#%E5%AE%89%E8%A3%85%E5%8F%82%E8%80%83")).toBe("安装参考");+ });++ it("passes a raw Chinese hash through unchanged", () => {+ expect(hashTargetId("#安装参考")).toBe("安装参考");+ expect(hashTargetId("#钩子包")).toBe("钩子包");+ });++ it("accepts a fragment without the leading #", () => {+ expect(hashTargetId("%E5%AE%89%E8%A3%85%E5%8F%82%E8%80%83")).toBe("安装参考");+ expect(hashTargetId("安装参考")).toBe("安装参考");+ });++ it("falls back to the raw fragment when an escape is malformed", () => {+ expect(hashTargetId("#100%")).toBe("100%");+ expect(hashTargetId("#%zz")).toBe("%zz");+ expect(hashTargetId("#安装%参考")).toBe("安装%参考");+ // A truncated UTF-8 sequence is malformed too.+ expect(hashTargetId("#%E5%AE")).toBe("%E5%AE");+ });++ it("returns an empty id for an empty hash", () => {+ expect(hashTargetId("")).toBe("");+ expect(hashTargetId("#")).toBe("");+ });++ it("leaves an ASCII hash unchanged", () => {+ expect(hashTargetId("#stop-hooks")).toBe("stop-hooks");+ expect(hashTargetId("#command-policy")).toBe("command-policy");+ expect(hashTargetId("vault")).toBe("vault");+ });++ it("maps the hash of a CJK heading's anchor back to the heading's slug id", () => {+ for (const heading of ["安装参考", "User Prompt Hook 钩子", "第一步:配置模型(可选)"]) {+ const id = slugifyHeading(heading);+ const hash = locationHash(id);+ expect(hash, `location.hash for ${heading}`).not.toBe(`#${id}`);+ expect(hashTargetId(hash), `id for ${heading}`).toBe(id);+ }+ });+});diff --git a/packages/landing/src/lib/hash.ts b/packages/landing/src/lib/hash.tsnew file mode 100644index 00000000..f0a34c5b--- /dev/null+++ b/packages/landing/src/lib/hash.ts@@ -0,0 +1,21 @@+/**+ * URL hash -> the id of the element it targets. Pure and unit-testable.+ *+ * `location.hash` carries the fragment percent-encoded: a link to the CJK heading+ * `## 升级须知` arrives as `#%E5%8D%87%E7%BA%A7%E9%A1%BB%E7%9F%A5`, while the heading's id+ * (slugifyHeading in toc.ts) holds the decoded text, so the fragment is decoded before+ * any lookup. A malformed escape (`#100%`) cannot be decoded and falls back to the raw+ * fragment instead of throwing — a throw inside a React effect would unmount the page.+ * The leading `#` is optional, and a fragment without escapes comes back unchanged.+ *+ * The docs site carries the same helper (packages/docs/src/lib/hash.ts); the two sites+ * share no package, so keep them aligned.+ */+export function hashTargetId(hash: string): string {+ const fragment = hash.startsWith("#") ? hash.slice(1) : hash;+ try {+ return decodeURIComponent(fragment);+ } catch {+ return fragment;+ }+}diff --git a/packages/landing/src/pages/blog-post.tsx b/packages/landing/src/pages/blog-post.tsxindex b54ac736..6995bae1 100644--- a/packages/landing/src/pages/blog-post.tsx+++ b/packages/landing/src/pages/blog-post.tsx@@ -83,7 +83,7 @@ export function MdImage({* that subtree instead of updating it. None of these adapters closes over render state, so a single* frozen map is enough.*/-const MD_COMPONENTS: Components = {+export const MD_COMPONENTS: Components = {h2: ({ children }) => (<h2 id={slugifyHeading(nodeText(children))} className="scroll-mt-20">{children}diff --git a/packages/landing/src/router.tsx b/packages/landing/src/router.tsxindex 1d9ef878..30be28af 100644--- a/packages/landing/src/router.tsx+++ b/packages/landing/src/router.tsx@@ -6,6 +6,7 @@import { useEffect } from "react";import { BrowserRouter, Navigate, Outlet, Route, Routes, useLocation } from "react-router";import { DOCS_URL } from "./lib/links";+import { hashTargetId } from "./lib/hash";import { AnnouncementBar } from "./components/announcement-bar";import { Nav } from "./components/nav";import { Footer } from "./components/footer";@@ -41,12 +42,14 @@ let handledLocationKey = "";function Layout() {const { pathname, hash, key } = useLocation();// Genuine route change: jump to top; with a hash (e.g. /#quickstart after leaving- // the blog) scroll to the target once the section is in the DOM.+ // the blog) scroll to the target once the section is in the DOM. A native #anchor+ // click (a blog TOC entry) also lands here, through popstate. The hash is decoded+ // first: an anchor to a CJK heading arrives percent-encoded.useEffect(() => {if (key === handledLocationKey) return;handledLocationKey = key;if (hash) {- const el = document.getElementById(hash.slice(1));+ const el = document.getElementById(hashTargetId(hash));if (el) {el.scrollIntoView();return;diff --git a/packages/landing/test/blog-post-anchors.test.ts b/packages/landing/test/blog-post-anchors.test.tsnew file mode 100644index 00000000..117d4db4--- /dev/null+++ b/packages/landing/test/blog-post-anchors.test.ts@@ -0,0 +1,80 @@+/**+ * In-page anchors of a blog post, through the page's own render pipeline (react-dom/server+ * static markup, node env): a hand-written "[label](#anchor)" link and a TOC entry must both+ * resolve — via the hash a browser reports for them, then hashTargetId — to the id of a+ * rendered heading. CJK headings are the case that matters: their anchors reach+ * location.hash percent-encoded. Checked on a fixture and on every post file on disk (read+ * via fs, both languages).+ */+import { readdirSync, readFileSync } from "node:fs";+import { join } from "node:path";+import { createElement } from "react";+import { renderToStaticMarkup } from "react-dom/server";+import Markdown from "react-markdown";+import { describe, expect, it } from "vitest";+import { MD_COMPONENTS, REHYPE_PLUGINS, REMARK_PLUGINS } from "../src/pages/blog-post";+import { parseFrontmatter } from "../src/lib/frontmatter";+import { hashTargetId } from "../src/lib/hash";+import { extractToc } from "../src/lib/toc";++const contentDir = join(__dirname, "..", "content", "blog");+const files = readdirSync(contentDir).filter((f) => f.endsWith(".md"));++const render = (body: string) =>+ renderToStaticMarkup(+ createElement(+ Markdown,+ { remarkPlugins: REMARK_PLUGINS, rehypePlugins: REHYPE_PLUGINS, components: MD_COMPONENTS },+ body,+ ),+ );++/** Ids of the rendered h2/h3 headings, in document order. */+const headingIds = (html: string) =>+ [...html.matchAll(/<h[23] id="([^"]*)"/g)].map((match) => match[1]!);++/** Hrefs of the rendered in-page links ("#..."), in document order. */+const inPageHrefs = (html: string) =>+ [...html.matchAll(/<a\b[^>]*\bhref="(#[^"]*)"/g)].map((match) => match[1]!);++/** The element id a click on `href` targets: the hash the browser reports, then hashTargetId. */+const targetOf = (href: string) =>+ hashTargetId(new URL(href, "https://example.test/blog/post").hash);++describe("blog post in-page anchors", () => {+ it("resolves a hand-written link and a TOC entry to a CJK heading", () => {+ const body = [+ "## 升级须知",+ "",+ "见下方[升级须知](#升级须知)。",+ "",+ "### 为什么是 PenguinHarness",+ "",+ "详见[这一节](#为什么是-penguinharness)。",+ ].join("\n");+ const html = render(body);+ const ids = headingIds(html);+ expect(ids).toEqual(["升级须知", "为什么是-penguinharness"]);+ const hrefs = inPageHrefs(html);+ // The renderer emits the link percent-encoded, which is also what location.hash reports.+ expect(hrefs[0]).toBe("#%E5%8D%87%E7%BA%A7%E9%A1%BB%E7%9F%A5");+ expect(hrefs.map(targetOf)).toEqual(ids);+ // A TOC entry links to `#${entry.id}`.+ expect(extractToc(body).map((entry) => targetOf(`#${entry.id}`))).toEqual(ids);+ });++ it("resolves every post's in-page links and TOC entries to a rendered heading", () => {+ expect(files.length).toBeGreaterThan(0);+ for (const file of files) {+ const { body } = parseFrontmatter(readFileSync(join(contentDir, file), "utf8"));+ const html = render(body);+ const ids = new Set(headingIds(html));+ const tocMisses = extractToc(body)+ .map((entry) => `#${entry.id}`)+ .filter((href) => !ids.has(targetOf(href)));+ expect(tocMisses, `TOC entries naming no rendered heading in ${file}`).toEqual([]);+ const dangling = inPageHrefs(html).filter((href) => !ids.has(targetOf(href)));+ expect(dangling, `dangling in-page anchors in ${file}`).toEqual([]);+ }+ });+});diff --git a/packages/landing/test/hash.test.ts b/packages/landing/test/hash.test.tsnew file mode 100644index 00000000..477b0781--- /dev/null+++ b/packages/landing/test/hash.test.ts@@ -0,0 +1,61 @@+/**+ * hashTargetId: the URL hash -> element id step behind the router's scroll-to-hash effect.+ * A browser reports a CJK fragment percent-encoded in location.hash, so the heading id only+ * matches once the hash is decoded; a malformed escape must fall back instead of throwing.+ */+import { describe, expect, it } from "vitest";+import { hashTargetId } from "../src/lib/hash";+import { slugifyHeading } from "../src/lib/toc";++/** The hash a browser reports after following a link to `#<fragment>` (WHATWG URL parsing). */+const locationHash = (fragment: string) =>+ new URL(`#${fragment}`, "https://example.test/blog/post").hash;++describe("hashTargetId", () => {+ it("decodes a percent-encoded Chinese hash", () => {+ expect(hashTargetId("#%E5%8D%87%E7%BA%A7%E9%A1%BB%E7%9F%A5")).toBe("升级须知");+ });++ it("passes a raw Chinese hash through unchanged", () => {+ expect(hashTargetId("#升级须知")).toBe("升级须知");+ expect(hashTargetId("#为什么是-penguinharness")).toBe("为什么是-penguinharness");+ });++ it("accepts a fragment without the leading #", () => {+ expect(hashTargetId("%E5%8D%87%E7%BA%A7%E9%A1%BB%E7%9F%A5")).toBe("升级须知");+ expect(hashTargetId("升级须知")).toBe("升级须知");+ });++ it("falls back to the raw fragment when an escape is malformed", () => {+ expect(hashTargetId("#100%")).toBe("100%");+ expect(hashTargetId("#%zz")).toBe("%zz");+ expect(hashTargetId("#升级%须知")).toBe("升级%须知");+ // A truncated UTF-8 sequence is malformed too.+ expect(hashTargetId("#%E5%8D")).toBe("%E5%8D");+ });++ it("returns an empty id for an empty hash", () => {+ expect(hashTargetId("")).toBe("");+ expect(hashTargetId("#")).toBe("");+ });++ it("leaves an ASCII hash unchanged", () => {+ expect(hashTargetId("#quickstart")).toBe("quickstart");+ expect(hashTargetId("#self-improvement")).toBe("self-improvement");+ expect(hashTargetId("upgrading")).toBe("upgrading");+ });++ it("maps the hash of a CJK heading's anchor back to the heading's slug id", () => {+ for (const heading of [+ "升级须知",+ "为什么是 PenguinHarness",+ "第一步:安装(Linux)",+ "0.2.4 的变化",+ ]) {+ const id = slugifyHeading(heading);+ const hash = locationHash(id);+ expect(hash, `location.hash for ${heading}`).not.toBe(`#${id}`);+ expect(hashTargetId(hash), `id for ${heading}`).toBe(id);+ }+ });+});