Skip to content

Commit f067474

Browse files
authored
Merge pull request #49724 from SayakMukhopadhyay/search-script-rework
Rework the search scripts and layouts to make it closer to docsy
2 parents f90edec + 8af9731 commit f067474

File tree

8 files changed

+241
-246
lines changed

8 files changed

+241
-246
lines changed

assets/js/custom-search.js

+139
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,139 @@
1+
document.querySelector('html').classList.add('search');
2+
3+
document.addEventListener('DOMContentLoaded', function() {
4+
let searchTerm = new URLSearchParams(window.location.search).get('q');
5+
let fetchingElem = document.getElementById('bing-results-container');
6+
7+
if (!searchTerm) {
8+
if (fetchingElem) fetchingElem.style.display = 'none';
9+
}
10+
});
11+
12+
window.renderGoogleSearchResults = () => {
13+
const cx = '013288817511911618469:elfqqbqldzg';
14+
const gcse = document.createElement('script');
15+
gcse.type = 'text/javascript';
16+
gcse.async = true;
17+
gcse.src = (document.location.protocol === 'https:' ? 'https:' : 'http:') + '//cse.google.com/cse.js?cx=' + cx;
18+
const s = document.getElementsByTagName('script')[0];
19+
s.parentNode.insertBefore(gcse, s);
20+
}
21+
22+
window.renderPageFindSearchResults = () => {
23+
let urlParams = new URLSearchParams(window.location.search);
24+
let searchTerm = urlParams.get("q") || "";
25+
let sidebarSearch = document.querySelector('#search-results-search');
26+
if (sidebarSearch) {
27+
sidebarSearch.remove();
28+
}
29+
document.getElementById('search').style.display = 'block';
30+
let pagefind = new PagefindUI({ element: "#search", showImages: false });
31+
if (searchTerm) {
32+
pagefind.triggerSearch(searchTerm);
33+
}
34+
35+
document.querySelector("#search input").addEventListener("input", function() {
36+
const inputValue = this.value;
37+
const queryStringVar = "q";
38+
updateQueryString(queryStringVar, inputValue);
39+
});
40+
}
41+
42+
function updateQueryString(key, value) {
43+
const baseUrl = window.location.href.split("?")[0];
44+
const queryString = window.location.search.slice(1);
45+
const urlParams = new URLSearchParams(queryString);
46+
47+
if (urlParams.has(key)) {
48+
urlParams.set(key, value);
49+
} else {
50+
urlParams.append(key, value);
51+
}
52+
53+
const newUrl = baseUrl + "?" + urlParams.toString();
54+
// Update the browser history (optional)
55+
history.replaceState(null, '', newUrl);
56+
}
57+
58+
// China Verification.
59+
const path = "path=/;";
60+
let d = new Date()
61+
d.setTime(d.getTime() + (7 * 24 * 60 * 60 * 1000))
62+
let expires = "expires=" + d.toUTCString()
63+
64+
function getCookie(name) {
65+
const value = "; " + document.cookie;
66+
const parts = value.split("; " + name + "=");
67+
if (parts.length === 2) return parts.pop().split(";").shift();
68+
else return "";
69+
}
70+
71+
async function checkBlockedSite(url) {
72+
const controller = new AbortController();
73+
const timeout = setTimeout(() => {
74+
controller.abort();
75+
}, 5000); // Timeout set to 5000ms (5 seconds)
76+
77+
try {
78+
const response = await fetch(url, { method: 'HEAD', mode: 'no-cors', signal: controller.signal });
79+
// If we reach this point, the site is accessible (since mode: 'no-cors' doesn't allow us to check response.ok)
80+
clearTimeout(timeout);
81+
return false;
82+
} catch (error) {
83+
// If an error occurs, it's likely the site is blocked
84+
return true;
85+
}
86+
}
87+
88+
async function loadSearch() {
89+
if (getCookie("can_google") === "") {
90+
const isGoogleBlocked = await checkBlockedSite("https://www.google.com/favicon.ico");
91+
if ( isGoogleBlocked ) {
92+
// Google is blocked.
93+
document.cookie = "can_google=false;" + path + expires
94+
window.renderPageFindSearchResults()
95+
} else {
96+
// Google is not blocked.
97+
document.cookie = "can_google=true;" + path + expires
98+
window.renderGoogleSearchResults()
99+
}
100+
} else if (getCookie("can_google") === "false") {
101+
window.renderPageFindSearchResults()
102+
} else {
103+
window.renderGoogleSearchResults()
104+
}
105+
}
106+
107+
(function ($) {
108+
"use strict";
109+
110+
const Search = {
111+
init: function () {
112+
$(document).ready(function () {
113+
// Fill the search input form with the current search keywords
114+
const searchKeywords = new URLSearchParams(location.search).get('q');
115+
if (searchKeywords !== null && searchKeywords !== '') {
116+
const searchInput = document.querySelector('.td-search-input');
117+
searchInput.focus();
118+
searchInput.value = searchKeywords;
119+
}
120+
121+
// Set a keydown event
122+
$(document).on("keypress", ".td-search-input", function (e) {
123+
if (e.keyCode !== 13) {
124+
return;
125+
}
126+
127+
const query = $(this).val();
128+
document.location = $(this).data('search-page') + "?q=" + query;
129+
130+
return false;
131+
});
132+
});
133+
},
134+
};
135+
136+
Search.init();
137+
})(jQuery);
138+
139+
window.onload = loadSearch;

assets/js/search.js

-45
This file was deleted.

hugo.toml

+1-1
Original file line numberDiff line numberDiff line change
@@ -151,7 +151,7 @@ githubWebsiteRaw = "raw.githubusercontent.com/kubernetes/website"
151151
github_repo = "https://github.com/kubernetes/website"
152152

153153
# Searching
154-
k8s_search = true
154+
customSearch = true
155155

156156
# The following search parameters are specific to Docsy's implementation. Kubernetes implementes its own search-related partials and scripts.
157157

layouts/_default/search.html

+42-54
Original file line numberDiff line numberDiff line change
@@ -1,54 +1,42 @@
1-
<!doctype html>
2-
<html lang="{{ .Site.Language.Lang }}" class="{{.Params.class}} no-js">
3-
<head>
4-
{{ partial "head.html" . }}
5-
</head>
6-
<body class="td-search {{- if ne (lower .Params.cid) "" -}}{{- printf " cid-%s" (lower .Params.cid) -}}{{- end -}}">
7-
<header>
8-
{{ partial "navbar.html" . }}
9-
{{ block "announcement" . }}
10-
{{ partial "announcement.html" . }}
11-
{{ end }}
12-
{{ block "hero" . }}
13-
<section class="header-hero filler">
14-
</section>
15-
{{ block "hero-more" . }}{{ end }}
16-
{{ end }}
17-
</header>
18-
<div class="td-outer">
19-
<main role="main" class="td-main">
20-
<section class="row td-search-result">
21-
<div class="col-12 col-md-4 offset-md-2">
22-
<form class="td-sidebar__search d-flex align-items-center">
23-
{{ partial "search-input.html" . }}
24-
</form>
25-
</div>
26-
<div class="col-12 col-md-8 offset-md-2">
27-
{{ if .Site.Params.gcs_engine_id }}
28-
<script>
29-
(function() {
30-
var cx = '{{ . }}';
31-
var gcse = document.createElement('script');
32-
gcse.type = 'text/javascript';
33-
gcse.async = true;
34-
gcse.src = 'https://cse.google.com/cse.js?cx=' + cx;
35-
var s = document.getElementsByTagName('script')[0];
36-
s.parentNode.insertBefore(gcse, s);
37-
})();
38-
</script>
39-
<gcse:searchresults-only></gcse:searchresults-only>
40-
{{ else if .Site.Params.k8s_search }}
41-
<script src="{{ "js/search.js" | relURL }}"></script>
42-
<script src="/pagefind/pagefind-ui.js"></script>
43-
<gcse:searchresults-only linktarget="_parent">
44-
<div id="search" style="display:none"></div>
45-
</gcse:searchresults-only>
46-
{{ end }}
47-
</div>
48-
</section>
49-
</main>
50-
</div>
51-
{{ partial "footer.html" . }}
52-
{{ partialCached "scripts.html" . }}
53-
</body>
54-
</html>
1+
{{/*
2+
Copied from Docsy with the addition of the search-input and the customSearch block.
3+
Revisit this if / when either of https://github.com/google/docsy/issues/2194 and https://github.com/google/docsy/pull/1512 are closed
4+
*/}}
5+
{{ define "main" }}
6+
7+
{{/*
8+
Do not use the `search-results-search` id elsewhere as it is used
9+
delete this element for pagefind/China users
10+
*/}}
11+
12+
{{/* From shortcodes/site-searchbar.html which is used in the home page */}}
13+
<div id="search-results-search" class="col-sm-6 col-md-6 col-lg-6 mx-auto py-3">
14+
{{partial "search-input" .}}
15+
</div>
16+
<section class="row td-search-result">
17+
<div class="col-12 col-md-8 offset-md-2">
18+
<h2 class="ml-4">{{ .Title }}</h2>
19+
{{ with .Site.Params.gcs_engine_id }}
20+
<script>
21+
(function() {
22+
var cx = '{{ . }}';
23+
var gcse = document.createElement('script');
24+
gcse.type = 'text/javascript';
25+
gcse.async = true;
26+
gcse.src = 'https://cse.google.com/cse.js?cx=' + cx;
27+
var s = document.getElementsByTagName('script')[0];
28+
s.parentNode.insertBefore(gcse, s);
29+
})();
30+
</script>
31+
<gcse:searchresults-only></gcse:searchresults-only>
32+
{{ end }}
33+
{{ if .Site.Params.customSearch }}
34+
<script src="/pagefind/pagefind-ui.js"></script>
35+
<gcse:searchresults-only linktarget="_parent">
36+
<div id="search" style="display:none"></div>
37+
</gcse:searchresults-only>
38+
{{ end }}
39+
</div>
40+
</section>
41+
42+
{{ end }}

layouts/partials/scripts.html

+3
Original file line numberDiff line numberDiff line change
@@ -33,6 +33,9 @@
3333
{{ $jsSearch := resources.Get "js/search.js" | resources.ExecuteAsTemplate "js/search.js" .Site.Home }}
3434
{{ if .Site.Params.offlineSearch }}
3535
{{ $jsSearch = resources.Get "js/offline-search.js" }}
36+
{{/* Revisit this if / when either of https://github.com/google/docsy/issues/2194 and https://github.com/google/docsy/pull/1512 are closed */}}
37+
{{ else if .Site.Params.customSearch }}
38+
{{ $jsSearch = resources.Get "js/custom-search.js" }}
3639
{{ end }}
3740
{{ $js := (slice $jsBs $jsBase $jsAnchor $jsSearch) | resources.Concat "js/main.js" -}}
3841
{{ if hugo.IsProduction -}}
+20
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,20 @@
1+
{{/* Revisit this if / when either of https://github.com/google/docsy/issues/2194 and https://github.com/google/docsy/pull/1512 are closed */}}
2+
{{ $lang := .Site.Language.Lang }}
3+
{{ $searchFile := printf "content/%s/search.md" $lang }}
4+
5+
<div class="search-bar">
6+
<i class="search-icon fa-solid fa-search"></i>
7+
<input
8+
type="search"
9+
name="q"
10+
{{ if fileExists $searchFile }}
11+
data-search-page="{{ "search/" | relLangURL }}"
12+
{{ else }}
13+
data-search-page="{{ "search/" | relURL }}"
14+
{{ end }}
15+
class="search-input td-search-input"
16+
placeholder="{{ T "ui_search_placeholder" }}"
17+
aria-label="{{ T "ui_search_placeholder" }}"
18+
autocomplete="off"
19+
>
20+
</div>

0 commit comments

Comments
 (0)