页内目录

页内目录和标题永久链接依赖当前文档的标题大纲。Tola 在 @tola/document:0.0.0 中提供 headings(),只返回当前 document(...) 内的标题,避免在多页 Bundle 中误查到其他页面。

嵌套目录

导入 @tola/document 时只引入所需符号(或用 as doc 起别名),避免遮蔽内置的 document(...) 函数。调用 headings(depth: 2) 获取大纲深度不超过 2 的标题,并过滤掉 outlined: false 的标题:

typst
#import "@tola/document:0.0.0": headings

#let group-headings(items) = {
  let groups = ()
  for item in items {
    if item.nesting == 1 or groups.len() == 0 {
      groups.push((heading: item, children: ()))
    } else {
      groups.last().children.push(item)
    }
  }
  groups
}

#let page-toc(title: "本页目录") = context {
  let items = headings(depth: 2).filter(h => h.outlined)
  if items.len() == 0 { return }

  html.aside(class: "toc")[
    #html.nav(aria-label: title)[
      #html.h2(title)
      #html.ul[
        #for group in group-headings(items) {
          html.li[
            #link(group.heading.location, group.heading.text)
            #if group.children.len() > 0 {
              html.ul[
                #for sub in group.children {
                  html.li(link(sub.location, sub.text))
                }
              ]
            }
          ]
        }
      ]
    ]
  ]
}

headings() 返回的每条记录包含以下常用字段:

字段说明
level计入 heading.offset 后的实际层级。
nesting在大纲中的嵌套深度(从 1 开始);outlined: false 时为 none。
text / bodyshow rule 生效前的纯文本标题与富文本内容。
label标题显式附带的 <label>,未声明时为 none。
location标题的 Typst 位置,传给 link(h.location, ...) 会生成对应的 #anchor 链接。
outlined是否参与大纲,等价于 Typst outline() 的筛选规则。

稳定锚点

在中文文档中,如果标题没有显式 <label>,依赖自动生成的锚点会在修改措辞时失效,或者带有百分比编码。推荐在写作时给每个标题附一个简短的英文 <label>:

typst
= 静态资源 <static-assets>
== 目录树映射 <asset-trees>

在自定义标题 show 规则中,优先使用 section.label 作为 HTML id;缺少显式标签时,再退回到 slugify(section.text, mode: "ascii") 并为重名标题自动追加 -2、-3 后缀:

typst
#import "@tola/address:0.0.0": slugify
#import "@tola/document:0.0.0": headings

#let resolve-heading-ids(sections) = {
  let used = (:)
  for s in sections {
    if s.label != none { used.insert(str(s.label), true) }
  }

  let ids = ()
  for s in sections {
    if not s.outlined or s.level > 5 {
      ids.push(none)
      continue
    }
    if s.label != none {
      ids.push(str(s.label))
      continue
    }
    let base = if s.text.contains(regex("[\\p{L}\\p{N}]")) {
      slugify(s.text, mode: "ascii")
    } else { "section" }
    let id = base
    let n = 2
    while id in used {
      id = base + "-" + str(n)
      n += 1
    }
    used.insert(id, true)
    ids.push(id)
  }
  ids
}

在正文作用域的 show heading 中,通过 source.location() 找到当前标题在 headings() 中的记录,输出带 id 的 <h2> <h6> 元素和指向自身的锚点链接:

typst
#let heading-with-anchor(source) = context {
  if target() != "html" or not source.outlined or source.level > 5 {
    return source
  }

  let sections = headings()
  let index = sections.position(s => s.location == source.location())
  let section = sections.at(index)
  let id = if section.label != none {
    str(section.label)
  } else {
    resolve-heading-ids(sections).at(index)
  }

  let tag = "h" + str(section.level + 1)
  let body = if section.number != none { section.number + [ ] + source.body } else { source.body }
  let anchor = html.a(href: "#" + id, class: "heading-anchor", aria-label: "锚点:" + section.text)[]

  html.elem(tag, attrs: (id: id), body + anchor)
}

性能

如果每渲染一个标题都重新计算整页所有标题的 slug,标题数量上百的参考页会有明显开销。对已经带有显式 section.label 的标题走快速路径(直接 str(section.label)),只在 section.label == none 时调用 resolve-heading-ids(sections),可以省去大部分重复计算。完整实现见本仓库的 theme/components/content/heading.typ。

站内搜索

可以用上下方向键选择结果。

输入关键词开始搜索。