-
Notifications
You must be signed in to change notification settings - Fork 12.9k
Expand file tree
/
Copy pathSidebar.astro
More file actions
375 lines (328 loc) · 11.8 KB
/
Sidebar.astro
File metadata and controls
375 lines (328 loc) · 11.8 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
---
import Default from "@astrojs/starlight/components/Sidebar.astro";
import { Icon as AstroIcon } from "astro-icon/components";
import { lookupProductTitle } from "~/util/sidebar";
const [product, module] = Astro.url.pathname.split("/").filter(Boolean);
---
<div
class="sticky top-0 z-[1] flex flex-col gap-2 bg-[var(--sl-color-black)] py-3.5 min-[50rem]:bg-[var(--sl-color-bg-sidebar)]"
>
<div class="sidebar-product-title px-1">
<a href={"/" + product + "/"} class="flex items-center gap-2 no-underline">
<AstroIcon name={product} size="32px" class="text-cl1-brand-orange" />
<span class="text-xl text-black">
<strong>
{lookupProductTitle(product, module)}
</strong>
</span>
</a>
</div>
<!-- Search Input -->
<div class="relative">
<input
type="search"
id="sidebar-search"
placeholder="Search sidebar..."
aria-label="Search sidebar navigation"
autocomplete="off"
spellcheck="false"
class="box-border min-h-[2.125rem] w-full rounded-lg border border-neutral-200 bg-transparent px-3 pr-10 text-sm text-neutral-950 placeholder-[var(--color-cl1-gray-4)] outline-2 outline-offset-2 outline-transparent transition-colors duration-150 focus-visible:outline-blue-500 dark:border-neutral-700 dark:text-neutral-100 dark:placeholder-[var(--color-cl1-gray-6)] dark:focus-visible:outline-blue-400"
/>
<div class="sidebar-search-icon"></div>
</div>
<!-- No Results Message -->
<div
id="sidebar-no-results"
class="hidden p-4 text-center text-sm text-gray-500 dark:text-gray-400"
>
No results found. Try a different search term, or use our <button
id="global-search-link"
class="font-inherit cursor-pointer border-none bg-transparent p-0 text-blue-500 underline hover:no-underline dark:text-orange-500"
>global search</button
>.
</div>
</div>
<Default><slot /></Default>
<script>
import { track } from "~/util/zaraz";
import { openGlobalSearch } from "~/util/search";
function initSidebarSearch() {
const searchInput = document.getElementById(
"sidebar-search",
) as HTMLInputElement;
const noResultsMessage = document.getElementById(
"sidebar-no-results",
) as HTMLElement;
const globalSearchLink = document.getElementById(
"global-search-link",
) as HTMLButtonElement;
const sidebarContent = document.querySelector(".sidebar-content");
if (
!searchInput ||
!sidebarContent ||
!noResultsMessage ||
!globalSearchLink
)
return;
// Attach an event listener so that we ONLY animate details that are explicitly toggled
// by the user clicking them, preventing CSS animations from flickering on page load
sidebarContent.addEventListener("click", (e) => {
const target = e.target as HTMLElement;
const summary = target.closest("summary");
if (!summary) return;
const details = summary.parentElement;
if (details && details.tagName === "DETAILS") {
details.classList.add("is-user-toggled");
}
});
(sidebarContent as HTMLElement).addEventListener(
"transitionend",
(e: TransitionEvent) => {
const target = e.target as HTMLElement;
if (
target.classList.contains("sidebar-accordion") &&
e.propertyName === "grid-template-rows"
) {
const details = target.closest("details");
if (details) details.classList.remove("is-user-toggled");
}
},
);
// Failsafe: strip the class before any page transition DOM swap
document.addEventListener("astro:before-swap", () => {
document
.querySelectorAll(".sidebar-content details.is-user-toggled")
.forEach((d) => {
d.classList.remove("is-user-toggled");
});
});
const originalState: Map<Element, boolean> = new Map();
// Store original state of details elements
function storeOriginalState() {
if (originalState.size === 0) {
const detailsElements = sidebarContent!.querySelectorAll("details");
detailsElements.forEach((details) => {
originalState.set(details, details.open);
});
}
}
// Check if text matches all search terms (for multi-word searches)
function matchesAllTerms(text: string, searchTerms: string[]): boolean {
const lowerText = text.toLowerCase();
return searchTerms.every((term) => lowerText.includes(term));
}
// Show only direct children of a folder (not recursive)
function showDirectChildren(details: HTMLDetailsElement) {
details.open = true;
const directList = details.querySelector(
":scope > .sidebar-accordion > .sidebar-accordion-inner > ul",
);
if (directList) {
const directChildren = directList.querySelectorAll(":scope > li");
directChildren.forEach((child) => {
(child as HTMLElement).style.display = "";
});
}
}
// Show parent chain for a specific item
function showParentChain(element: Element) {
let parent = element.parentElement;
while (parent && parent !== sidebarContent) {
if (parent.tagName === "LI") {
(parent as HTMLElement).style.display = "";
}
if (parent.tagName === "DETAILS") {
(parent as HTMLDetailsElement).open = true;
}
parent = parent.parentElement;
}
}
// Filter sidebar items based on search query
function filterSidebarItems(query: string) {
const items = sidebarContent!.querySelectorAll("li");
const detailsElements = sidebarContent!.querySelectorAll("details");
track("use sidebar search", { query: query });
if (!query.trim()) {
// Reset to original state
items.forEach((item) => {
(item as HTMLElement).style.display = "";
});
// Restore original details state
detailsElements.forEach((details) => {
const originalOpen = originalState.get(details);
if (originalOpen !== undefined) {
(details as HTMLDetailsElement).open = originalOpen;
}
});
// Hide no results message
noResultsMessage.classList.add("hidden");
return;
}
// Split search query into terms for more precise matching
const searchTerms = query
.toLowerCase()
.split(/\s+/)
.filter((term) => term.length > 0);
// First, hide all items and close all details
items.forEach((item) => {
(item as HTMLElement).style.display = "none";
});
detailsElements.forEach((details) => {
(details as HTMLDetailsElement).open = false;
});
// Track what we've matched to avoid duplicates
const matchedItems = new Set<Element>();
// 1. Check for folder/subfolder matches first (highest priority)
detailsElements.forEach((details) => {
const summary = details.querySelector("summary");
if (summary) {
const summaryText = summary.textContent || "";
if (matchesAllTerms(summaryText, searchTerms)) {
// This is a folder match - show the folder and its direct children
const parentLi = details.closest("li");
if (parentLi && !matchedItems.has(parentLi)) {
(parentLi as HTMLElement).style.display = "";
showDirectChildren(details);
showParentChain(parentLi);
matchedItems.add(parentLi);
}
}
}
});
// 2. Check for specific page matches (show page + parent chain)
items.forEach((item) => {
if (matchedItems.has(item)) return; // Skip if already matched as folder
const link = item.querySelector("a");
const summary = item.querySelector("summary");
// Skip if this is a folder (has summary) - those are handled above
if (summary) return;
if (link) {
const linkText = link.textContent || "";
if (matchesAllTerms(linkText, searchTerms)) {
// This is a specific page match - show page + parent chain
(item as HTMLElement).style.display = "";
showParentChain(item);
matchedItems.add(item);
}
}
});
// 3. Fallback: if no exact matches, show partial matches (less specific)
if (matchedItems.size === 0) {
items.forEach((item) => {
const textContent = item.textContent?.toLowerCase() || "";
const link = item.querySelector("a");
const linkText = link?.textContent?.toLowerCase() || "";
const summary = item.querySelector("summary");
const summaryText = summary?.textContent?.toLowerCase() || "";
// Check if any search term is found (partial matching)
const hasPartialMatch = searchTerms.some(
(term) =>
textContent.includes(term) ||
linkText.includes(term) ||
summaryText.includes(term),
);
if (hasPartialMatch) {
(item as HTMLElement).style.display = "";
// If it's a folder, show direct children only
if (summary) {
const details = item.querySelector("details");
if (details) {
showDirectChildren(details);
}
}
showParentChain(item);
matchedItems.add(item);
}
});
}
// Show/hide no results message based on matches
if (matchedItems.size === 0) {
noResultsMessage.classList.remove("hidden");
} else {
noResultsMessage.classList.add("hidden");
}
}
// Event listeners
searchInput.addEventListener("input", (e) => {
storeOriginalState();
const query = (e.target as HTMLInputElement).value;
filterSidebarItems(query);
});
// Clear search on Escape key
searchInput.addEventListener("keydown", (e) => {
if (e.key === "Escape") {
searchInput.value = "";
filterSidebarItems("");
}
});
// Global search link click handler
globalSearchLink.addEventListener("click", () => {
const currentQuery = searchInput.value.trim();
if (currentQuery) {
openGlobalSearch(currentQuery);
}
});
// On link click during search, clear persisted open[] so the next page
// uses its server-rendered state instead of the search-modified state.
sidebarContent.addEventListener("click", (e) => {
if (!searchInput.value) return;
if (!(e.target instanceof Element)) return;
if (!e.target.closest("a")) return;
try {
// try/catch guards against sessionStorage being blocked (e.g. private browsing)
const storageKey = "sl-sidebar-state";
const raw = sessionStorage.getItem(storageKey);
const state = JSON.parse(raw || "{}");
state.open = [];
sessionStorage.setItem(storageKey, JSON.stringify(state));
} catch (_) {} // eslint-disable-line no-empty
});
document.addEventListener(
"keydown",
(keyboardEvent) => {
const target = keyboardEvent.target;
const isInput =
target instanceof EventTarget &&
(("tagName" in target &&
(target.tagName === "INPUT" ||
target.tagName === "TEXTAREA" ||
target.tagName === "SELECT")) ||
("isContentEditable" in target && target.isContentEditable));
if (keyboardEvent.key === "/" && !isInput) {
keyboardEvent.preventDefault();
keyboardEvent.stopPropagation();
searchInput.focus();
}
},
{
capture: true,
},
);
}
// Initialize when DOM is loaded
if (document.readyState === "loading") {
document.addEventListener("DOMContentLoaded", initSidebarSearch);
} else {
initSidebarSearch();
}
</script>
<style is:global>
.sidebar-search-icon {
position: absolute;
right: 12px;
top: 50%;
transform: translateY(-50%);
width: 1em;
height: 1em;
-webkit-mask-image: url("data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' viewBox='0 0 24 24'%3E%3Cpath d='M17 2H7a5 5 0 0 0-5 5v10a5 5 0 0 0 5 5h10a5 5 0 0 0 5-5V7a5 5 0 0 0-5-5Zm3 15a3 3 0 0 1-3 3H7a3 3 0 0 1-3-3V7a3 3 0 0 1 3-3h10a3 3 0 0 1 3 3v10Z'%3E%3C/path%3E%3Cpath d='M15.293 6.707a1 1 0 1 1 1.414 1.414l-8.485 8.486a1 1 0 0 1-1.414-1.415l8.485-8.485Z'%3E%3C/path%3E%3C/svg%3E");
mask-image: url("data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' viewBox='0 0 24 24'%3E%3Cpath d='M17 2H7a5 5 0 0 0-5 5v10a5 5 0 0 0 5 5h10a5 5 0 0 0 5-5V7a5 5 0 0 0-5-5Zm3 15a3 3 0 0 1-3 3H7a3 3 0 0 1-3-3V7a3 3 0 0 1 3-3h10a3 3 0 0 1 3 3v10Z'%3E%3C/path%3E%3Cpath d='M15.293 6.707a1 1 0 1 1 1.414 1.414l-8.485 8.486a1 1 0 0 1-1.414-1.415l8.485-8.485Z'%3E%3C/path%3E%3C/svg%3E");
-webkit-mask-size: 100%;
mask-size: 100%;
background-color: currentColor;
pointer-events: none;
}
.sidebar-content {
height: auto !important;
min-height: 0 !important;
}
</style>