Skip to content

Commit 1ce03c8

Browse files
committed
switch 404 to use client-side JS
1 parent 8543a0a commit 1ce03c8

File tree

1 file changed

+32
-28
lines changed

1 file changed

+32
-28
lines changed

src/pages/404.astro

Lines changed: 32 additions & 28 deletions
Original file line numberDiff line numberDiff line change
@@ -1,45 +1,49 @@
11
---
22
import Layout from "../layouts/BaseLayout.astro";
3-
4-
/**
5-
* Returns the last (non-empty) segment from the slash-separated path, or ""
6-
*
7-
* Discards any hash part of the URL before splitting it.
8-
*
9-
* @param path string to extract the last part of
10-
* @returns the last non-empty segment or an empty string
11-
*
12-
* @example
13-
* An input of `/reference/p5/basematerialshader/` will return `basematerialshader`
14-
* An input of `/reference/p5.Vector/dist/#Examples` will return `dist`
15-
*/
16-
function getLastPathElementOrEmptyString(path: string): string {
17-
//Get the part of the path before the (first) hash
18-
const preHashPath = path.split("#")[0] ?? "";
19-
//Then get the last non-empty slash-separated segment from that
20-
return preHashPath.split("/").filter(Boolean).pop() ?? "";
21-
}
22-
23-
const currentPath = Astro.url.pathname;
24-
const finalTerm = getLastPathElementOrEmptyString(currentPath);
253
---
264

275
<Layout title="404: Page Not Found">
286
<main class="flex flex-col items-start gap-8 py-8 px-2 prose max-w-none">
297
<p>
308
Sorry, we couldn't find your exact page
31-
<code>{currentPath}</code>.
9+
<code id="display-path"></code>.
3210

3311
<div class="flex flex-col gap-4">
34-
<a
35-
href={`https://beta.p5js.org/search/?term=${finalTerm}`}
36-
class="btn"
37-
>
38-
Search here for <code>{finalTerm}</code>
12+
<a id="search-link" href="/search/" class="btn">
13+
Search here for <code id="display-search-term"></code>
3914
</a>
4015
or
4116
<a href="/" class="btn secondary">go home</a>
4217
</div>
4318
</p>
4419
</main>
20+
<script is:inline>
21+
(function update404PageDetails() {
22+
function getLastPathSegment(path) {
23+
return path.split("/").filter(Boolean).pop() ?? "";
24+
}
25+
26+
// 1. Get the last meaningful segment from the URL path, excluding hash part
27+
// 2. Use that in the link href to the search
28+
// 3. Also display it and the failed path
29+
30+
//(This .pathname already strips away any hash part)
31+
const realPath = window.location.pathname;
32+
const term = getLastPathSegment(realPath);
33+
34+
const displayPathEl = document.getElementById("display-path");
35+
const searchLinkEl = document.getElementById("search-link");
36+
const displaySearchTermEl = document.getElementById("display-search-term");
37+
38+
if (displayPathEl) {
39+
displayPathEl.textContent = realPath;
40+
}
41+
if (displaySearchTermEl) {
42+
displaySearchTermEl.textContent = term;
43+
}
44+
if (searchLinkEl) {
45+
searchLinkEl.href = `/search/?term=${encodeURIComponent(term)}`;
46+
}
47+
})();
48+
</script>
4549
</Layout>

0 commit comments

Comments
 (0)