Skip to content

Commit

Permalink
feat: add Algolia Search support (#329)
Browse files Browse the repository at this point in the history
updates #222

Co-authored-by: reuixiy <[email protected]>
  • Loading branch information
rxrw and reuixiy authored May 23, 2021
1 parent 97cb67e commit 2dc1f8b
Show file tree
Hide file tree
Showing 20 changed files with 211 additions and 94 deletions.
1 change: 1 addition & 0 deletions .gitignore
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
.DS_Store
109 changes: 109 additions & 0 deletions assets/js/algolia-search.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,109 @@
window.addEventListener("DOMContentLoaded", event => {
let origContent = null;

const search = instantsearch({
appId: "{{ .Site.Params.algoliaAppId }}",
apiKey: "{{ .Site.Params.algoliaApiKey }}",
indexName: "{{ .Site.Params.algoliaIndexName }}",
});

search.addWidget({
init: function (opts) {
const helper = opts.helper;
const input = document.getElementById("search-input");

input.addEventListener("input", function (e) {
helper
.setQuery(e.currentTarget.value) // update the parameters
.search(); // launch the query
});
},
});

search.addWidget({
render: function (opts) {
let term = opts.state.query
if (!term) {
return
}

const results = opts.results.hits;

let target = document.querySelector(".main-inner") || document.querySelector("main.home");
let replaced = [];

while (target.firstChild) {
replaced.push(target.firstChild);
target.removeChild(target.firstChild);
}

if (!origContent) {
origContent = replaced;
}

let title = document.createElement("h1");

title.id = "search-results";
title.className = "list-title";

if (results.length == 0) {
title.textContent = "{{ i18n "searchResultsNone" (dict "Term" "{}") }}".replace("{}", term);
} else if (results.length == 1) {
title.textContent = "{{ i18n "searchResultsTitle" (dict "Count" 1 "Term" "{}") }}".replace("{}", term);
} else {
title.textContent = "{{ i18n "searchResultsTitle" (dict "Count" 13579 "Term" "{}") }}".replace("{}", term).replace("13579", results.length);
}

target.appendChild(title);
document.title = title.textContent;

let template = document.getElementById("search-result");
for (let result of results) {
let element = template.content.cloneNode(true);
element.querySelector(".summary-title-link").href = element.querySelector(".read-more-link").href = result.url;
element.querySelector(".summary-title-link").textContent = result.title;
element.querySelector(".summary").textContent = truncateToEndOfSentence(result.summary, 70);
target.appendChild(element);
}
title.scrollIntoView(true);

{{ if .Site.Params.enableNavToggle }}
let navToggleLabel = document.querySelector('.nav-toggle');
if (navToggleLabel && navToggleLabel.classList.contains("open")) {
document.getElementById(navToggleLabel.getAttribute("for")).click();
}
{{ end }}
},
});

search.start();

// This matches Hugo's own summary logic:
// https://github.com/gohugoio/hugo/blob/b5f39d23b86f9cb83c51da9fe4abb4c19c01c3b7/helpers/content.go#L543
function truncateToEndOfSentence(text, minWords)
{
let match;
let result = "";
let wordCount = 0;
let regexp = /(\S+)(\s*)/g;
while (match = regexp.exec(text)) {
wordCount++;
if (wordCount <= minWords) {
result += match[0];
}
else
{
let char1 = match[1][match[1].length - 1];
let char2 = match[2][0];
if (/[.?!"]/.test(char1) || char2 == "\n") {
result += match[1];
break;
}
else {
result += match[0];
}
}
}
return result;
}
}, {once: true});
2 changes: 1 addition & 1 deletion assets/js/lunr-search.js
Original file line number Diff line number Diff line change
Expand Up @@ -114,7 +114,7 @@ window.addEventListener("DOMContentLoaded", event => {
try {
let results = index.search(term);

let target = document.querySelector(".main-inner");
let target = document.querySelector(".main-inner") || document.querySelector("main.home");
let replaced = [];
while (target.firstChild) {
replaced.push(target.firstChild);
Expand Down
2 changes: 1 addition & 1 deletion assets/scss/base/_responsive.scss
Original file line number Diff line number Diff line change
Expand Up @@ -128,7 +128,7 @@
#langs li {
width: auto;
}
@if ($enableLunrSearch) {
@if ($enableSearch) {
.search-item {
grid-column: 1 / -1;
}
Expand Down
6 changes: 3 additions & 3 deletions assets/scss/main.scss
Original file line number Diff line number Diff line change
Expand Up @@ -449,11 +449,11 @@ $fofPoster: url({{ $fofPoster }});

// Lunr search

{{ if and (eq .Site.Params.headerLayout "flex") .Site.Params.enableLunrSearch }}
$enableLunrSearch: true;
{{ if and (eq .Site.Params.headerLayout "flex") (or .Site.Params.enableLunrSearch .Site.Params.enableAlgoliaSearch) }}
$enableSearch: true;
@import "components/search";
{{ else }}
$enableLunrSearch: false;
$enableSearch: false;
{{ end }}


Expand Down
28 changes: 27 additions & 1 deletion config-examples/en/config.toml
Original file line number Diff line number Diff line change
Expand Up @@ -141,9 +141,17 @@ uglyURLs = false
mediaType = "application/json"
baseName = "search"

# Search index for Algolia
[outputFormats.Algolia]
mediaType = "application/json"
baseName = "algolia"
isPlainText = true
notAlternative = true

# Hugo’s output control
[outputs]
page = ["HTML"]
# home = ["HTML", "SectionsAtom", "SectionsRSS", "SearchIndex", "Algolia"]
home = ["HTML", "SectionsAtom", "SectionsRSS", "SearchIndex"]
section = ["HTML"]
taxonomy = ["HTML"]
Expand Down Expand Up @@ -1360,12 +1368,30 @@ uglyURLs = false
# Lunr search

# Note: This requires SearchIndex
# output to be enabled.
# output to be enabled.

enableLunrSearch = true
# Note: https://lunrjs.com/


######################################
# Algolia search

# Note: This requires Algolia
# output to be enabled.
# And you need to upload the
# generated algolia.json to
# Algolia every time you rebuild
# your site.

enableAlgoliaSearch = false

algoliaAppId = ""
algoliaApiKey = ""
algoliaIndexName = ""
# Note: https://www.algolia.com/


######################################
# 404 Page

Expand Down
30 changes: 26 additions & 4 deletions config-examples/zh-cn/config.toml
Original file line number Diff line number Diff line change
Expand Up @@ -135,14 +135,21 @@ uglyURLs = false
baseName = "rss"

# lunr.js 的搜索索引
# [outputFormats.SearchIndex]
# mediaType = "application/json"
# baseName = "search"
[outputFormats.SearchIndex]
mediaType = "application/json"
baseName = "search"

# Algolia 的搜索索引
[outputFormats.Algolia]
mediaType = "application/json"
baseName = "algolia"
isPlainText = true
notAlternative = true

# Hugo 的输出控制
[outputs]
page = ["HTML"]
# home = ["HTML", "SectionsAtom", "SectionsRSS", "SearchIndex"]
# home = ["HTML", "SectionsAtom", "SectionsRSS", "SearchIndex", "Algolia"]
home = ["HTML", "SectionsAtom", "SectionsRSS"]
section = ["HTML"]
taxonomy = ["HTML"]
Expand Down Expand Up @@ -1338,6 +1345,21 @@ uglyURLs = false
# 说明:https://lunrjs.com/


######################################
# Algolia search

# 说明:需要开启 `Algolia` 的输出,且需要每
# 次将生成的 algolia.json 文件上传到
# Algolia

enableAlgoliaSearch = false

algoliaAppId = ""
algoliaApiKey = ""
algoliaIndexName = ""
# 说明:https://www.algolia.com/


######################################
# 404 页面

Expand Down
30 changes: 26 additions & 4 deletions config-examples/zh-tw/config.toml
Original file line number Diff line number Diff line change
Expand Up @@ -135,14 +135,21 @@ uglyURLs = false
baseName = "rss"

# lunr.js 的搜尋索引
# [outputFormats.SearchIndex]
# mediaType = "application/json"
# baseName = "search"
[outputFormats.SearchIndex]
mediaType = "application/json"
baseName = "search"

# Algolia 的搜尋索引
[outputFormats.Algolia]
mediaType = "application/json"
baseName = "algolia"
isPlainText = true
notAlternative = true

# Hugo 的輸出控制
[outputs]
page = ["HTML"]
# home = ["HTML", "SectionsAtom", "SectionsRSS", "SearchIndex"]
# home = ["HTML", "SectionsAtom", "SectionsRSS", "SearchIndex", "Algolia"]
home = ["HTML", "SectionsAtom", "SectionsRSS"]
section = ["HTML"]
taxonomy = ["HTML"]
Expand Down Expand Up @@ -1338,6 +1345,21 @@ uglyURLs = false
# 說明:https://lunrjs.com/


######################################
# Algolia 搜尋

# 說明:需要開啟 `Algolia` 的輸出,且需要每
# 次將生成的 algolia.json 文件上傳到
# Algolia

enableAlgoliaSearch = false

algoliaAppId = ""
algoliaApiKey = ""
algoliaIndexName = ""
# 說明:https://www.algolia.com/


######################################
# 404 頁面

Expand Down
Binary file modified images/screenshot.png
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
Binary file modified images/tn.png
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
5 changes: 5 additions & 0 deletions layouts/index.algolia.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
{{- $.Scratch.Add "index" slice -}}
{{- range (where .Site.RegularPages "Section" "in" .Site.Params.mainSections) -}}
{{- $.Scratch.Add "index" (dict "objectID" .File.UniqueID "date" .Date.UTC.Unix "description" .Description "fuzzywordcount" .FuzzyWordCount "kind" .Kind "lang" .Lang "lastmod" .Lastmod.UTC.Unix "publishdate" .PublishDate.UTC.Unix "relpermalink" .RelPermalink "summary" .Summary "title" .Title "url" .Permalink "wordcount" .WordCount "section" .Section "tags" .Params.tags "categories" .Section "content" .Content)}}
{{- end -}}
{{- $.Scratch.Get "index" | jsonify -}}
2 changes: 1 addition & 1 deletion layouts/index.searchindex.json
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
[
{{- range $index, $page := where .Site.Pages "Content" "ne" ("" | safeHTML) -}}
{{- range $index, $page := where .Site.RegularPages "Section" "in" .Site.Params.mainSections -}}
{{- if gt $index 0 -}}
,
{{- end -}}
Expand Down
2 changes: 1 addition & 1 deletion layouts/partials/menu.html
Original file line number Diff line number Diff line change
Expand Up @@ -29,7 +29,7 @@
{{ end }}
{{ end }}
{{ else if eq .Identifier "search" }}
{{ if and $.Site.Params.enableLunrSearch (eq $.Site.Params.headerLayout "flex") }}
{{ if and (eq $.Site.Params.headerLayout "flex") (or $.Site.Params.enableLunrSearch $.Site.Params.enableAlgoliaSearch) }}
{{- $iconName := (string .Post) -}}
<li class="menu-item search-item">
{{ partial "components/search.html" (dict "$" $ctx "iconName" $iconName) }}
Expand Down
2 changes: 1 addition & 1 deletion layouts/partials/pages/post.html
Original file line number Diff line number Diff line change
Expand Up @@ -35,7 +35,7 @@ <h1 class="post-title p-name">{{ (partial "utils/title.html" (dict "$" $ "title"
{{- end -}}

<div class="post-body e-content">
{{ partial "utils/content.html" . }}
{{ partial "utils/content.html" . }}
</div>

{{ partial "components/post-copyright.html" . }}
Expand Down
4 changes: 4 additions & 0 deletions layouts/partials/script.html
Original file line number Diff line number Diff line change
Expand Up @@ -36,6 +36,10 @@
{{- $scripts = union $scripts (partial "third-party/lunr-search.html" .) -}}
{{- end -}}

{{- if .Site.Params.enableAlgoliaSearch -}}
{{- $scripts = union $scripts (partial "third-party/algolia-search.html" .) -}}
{{- end -}}

{{- $scripts = union $scripts (slice "js/custom.js") -}}

{{- $processedScripts := slice ("" | resources.FromString "dummy.js") -}}
Expand Down
4 changes: 4 additions & 0 deletions layouts/partials/third-party/algolia-search.html
Original file line number Diff line number Diff line change
@@ -0,0 +1,4 @@
{{- $scripts := slice "https://cdn.jsdelivr.net/npm/instantsearch.js@2/dist/instantsearch.min.js" -}}

{{- $scripts = union $scripts (slice "js/algolia-search.js") -}}
{{- return $scripts -}}
Binary file modified static/icons/android-chrome-512x512.png
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
Binary file modified static/icons/apple-touch-icon.png
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
Binary file modified static/icons/mstile-150x150.png
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
Loading

0 comments on commit 2dc1f8b

Please sign in to comment.