Skip to content

Commit b0c6a5c

Browse files
committed
switch to regex/DOM ToC parsing for subheadings
1 parent 092f747 commit b0c6a5c

3 files changed

Lines changed: 19 additions & 13 deletions

File tree

README.md

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -34,7 +34,7 @@ Submodule path 'themes/srcf-hugo-theme': checked out 'f6c43f8ca31241acb44c4a7493
3434

3535
### TODO
3636

37-
* add search
37+
* refine search
3838
* vendor static assets centrally
3939

4040
## Credits

layouts/index.json

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,8 @@
11
{{- $index := slice -}}
22
{{- range .Site.RegularPages -}}
33
{{- $cleanContents := .Plain | htmlUnescape -}}
4+
{{- $headingTags := findRE "<a.*? href=\"#.*?\".*?>.*?</a>" .TableOfContents -}}
45

5-
{{- $index = $index | append (dict "title" .Title "contents" $cleanContents "headings" .Fragments.Headings "permalink" .Permalink) -}}
6+
{{- $index = $index | append (dict "title" .Title "contents" $cleanContents "headingTags" $headingTags "permalink" .Permalink) -}}
67
{{- end -}}
78
{{- $index | jsonify -}}

static/js/search.js

Lines changed: 16 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -12,7 +12,7 @@ window.addEventListener("DOMContentLoaded", function() {
1212
fuseFetcher = fetch("/index.json")
1313
.then(response => response.json())
1414
.then(searchIndex => {
15-
flattenIndex(searchIndex);
15+
fixupIndex(searchIndex);
1616

1717
fuse = new Fuse(searchIndex, {
1818
keys: [
@@ -95,18 +95,23 @@ window.addEventListener("DOMContentLoaded", function() {
9595
}
9696
}
9797

98-
function flattenIndex(index) {
99-
function flattenHeadings(headings, result = []) {
100-
for (const heading of headings) {
101-
result.push({ id: heading.ID, title: heading.Title });
102-
if (heading.Headings) {
103-
flattenHeadings(heading.Headings, result);
104-
}
98+
function fixupIndex(index) {
99+
const parser = new DOMParser();
100+
101+
index.forEach(item => {
102+
if (!item.headingTags) {
103+
item.headings = [];
104+
return;
105105
}
106-
return result;
107-
}
108106

109-
index.forEach(item => item.headings = flattenHeadings(item.headings));
107+
item.headings = item.headingTags.map(tag => {
108+
const element = parser.parseFromString(tag, "text/html").body.firstChild
109+
return {
110+
id: element.getAttribute("href").slice(1),
111+
title: element.textContent
112+
};
113+
});
114+
});
110115
}
111116

112117
function executeSearch(searchQuery) {

0 commit comments

Comments
 (0)