Skip to content

Commit 37f1541

Browse files
authored
feat: search box in 404 page (#1081)
1 parent f4eb5d3 commit 37f1541

File tree

2 files changed

+46
-1
lines changed

2 files changed

+46
-1
lines changed

assets/ts/search.tsx

Lines changed: 8 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -53,7 +53,14 @@ class Search {
5353
this.resultTitle = resultTitle;
5454
this.resultTitleTemplate = resultTitleTemplate;
5555

56-
this.handleQueryString();
56+
/// Check if there's already value in the search input
57+
if (this.input.value.trim() !== '') {
58+
this.doSearch(this.input.value.split(' '));
59+
}
60+
else {
61+
this.handleQueryString();
62+
}
63+
5764
this.bindQueryStringChange();
5865
this.bindSearchForm();
5966
}

layouts/404.html

Lines changed: 38 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -3,5 +3,43 @@
33
<h1 class="article-title">{{ T "notFound.title" }}</h1>
44
<h2 class="article-subtitle">{{ T "notFound.subtitle" }}</h2>
55
</div>
6+
7+
{{- $query := first 1 (where .Site.Pages "Layout" "==" "search") -}}
8+
{{- $searchPage := index $query 0 -}}
9+
10+
{{- with $searchPage -}}
11+
<form action="{{ $searchPage.RelPermalink }}" class="search-form widget" {{ with .OutputFormats.Get "json" -}}data-json="{{ .Permalink }}" {{- end }}>
12+
<p>
13+
<label>{{ T "search.title" }}</label>
14+
<input id="searchInput" name="keyword" required placeholder="{{ T `search.placeholder` }}" />
15+
16+
<button title="{{ T `search.title` }}">
17+
{{ partial "helper/icon" "search" }}
18+
</button>
19+
</p>
20+
</form>
21+
22+
<div class="search-result">
23+
<h3 class="search-result--title section-title"></h3>
24+
<div class="search-result--list article-list--compact"></div>
25+
</div>
26+
27+
<script>
28+
window.searchResultTitleTemplate = "{{ T `search.resultTitle` }}"
29+
</script>
30+
31+
{{- $opts := dict "minify" hugo.IsProduction "JSXFactory" "createElement" -}}
32+
{{- $searchScript := resources.Get "ts/search.tsx" | js.Build $opts -}}
33+
<script type="text/javascript" src="{{ $searchScript.RelPermalink }}" defer></script>
34+
35+
<script>
36+
const wrongUrl = new URL(window.location.href);
37+
38+
/// Get the search keyword from the wrong URL by removing all slashes and dashes
39+
const searchKeyword = wrongUrl.pathname.split(/[/|-]/).join(' ').trim();
40+
41+
document.getElementById('searchInput').setAttribute('value', searchKeyword);
42+
</script>
43+
{{- end -}}
644
{{ partialCached "footer/footer" . }}
745
{{ end }}

0 commit comments

Comments
 (0)