From 3b391cd9c74af3a6d0650549a8e346eecf02a1ec Mon Sep 17 00:00:00 2001 From: razonyang Date: Fri, 6 Sep 2024 13:44:37 +0800 Subject: [PATCH] fix: show ancestors of headings Closes #249 --- assets/search/js/renderer.ts | 17 +++++++++++++++-- .../search/functions/parse-headings.html | 7 +------ .../search/functions/walk-headings.html | 16 ++++++++++++++++ 3 files changed, 32 insertions(+), 8 deletions(-) create mode 100644 layouts/partials/search/functions/walk-headings.html diff --git a/assets/search/js/renderer.ts b/assets/search/js/renderer.ts index 8b296dbdab9..b7ff0873c68 100644 --- a/assets/search/js/renderer.ts +++ b/assets/search/js/renderer.ts @@ -345,11 +345,15 @@ export default class Renderer { continue } - headings += ` + let ancestors = this.headingAncestors(result.item.headings, heading.pid) + ancestors = ancestors.concat(result.item.title) + const subtitle = ancestors.join(' ยท ') + + headings += `
${params.icons['heading']}
${this.highlight(heading.title, [matches[j]])}
-
${result.item.title}
+
${subtitle}
` break // avoid match same heading multiple times. @@ -358,4 +362,13 @@ export default class Renderer { return headings } + + headingAncestors(headings, pid): Array { + let v :Array = [] + if (pid >= 0) { + v.push(headings[pid].title) + v = v.concat(this.headingAncestors(headings, headings[pid].pid)) + } + return v + } } diff --git a/layouts/partials/search/functions/parse-headings.html b/layouts/partials/search/functions/parse-headings.html index db48e09abee..46a8a52c08c 100644 --- a/layouts/partials/search/functions/parse-headings.html +++ b/layouts/partials/search/functions/parse-headings.html @@ -1,10 +1,5 @@ {{- $headings := slice }} {{- with .Fragments }} - {{- range .HeadingsMap }} - {{- $headings = $headings | append (dict - "anchor" .ID - "title" (.Title | plainify)) - }} - {{- end }} + {{- $headings = partial "search/functions/walk-headings" (dict "Headings" .Headings "PID" -1) }} {{- end }} {{- return $headings -}} diff --git a/layouts/partials/search/functions/walk-headings.html b/layouts/partials/search/functions/walk-headings.html new file mode 100644 index 00000000000..59aa6117c60 --- /dev/null +++ b/layouts/partials/search/functions/walk-headings.html @@ -0,0 +1,16 @@ +{{- $v := slice }} +{{- $pid := .PID }} +{{- range .Headings }} + {{- if ne .Title "" }} + {{- $v = $v | append (dict + "pid" $pid + "anchor" .ID + "title" (.Title | plainify)) + }} + {{- end }} + {{- $v = $v | append (partial "search/functions/walk-headings" (dict + "Headings" .Headings + "PID" (add $pid (len $v)))) + }} +{{- end }} +{{- return $v }}