Skip to content

Custom 404.md #205

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 6 commits into from
Nov 19, 2023
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
73 changes: 73 additions & 0 deletions docs/404.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,73 @@
<script type="module">

if (location.pathname.endsWith("/")) {
location.replace(`${location.pathname.slice(0, -1)}.html${location.search}${location.hash}`);
}

</script>

# Page not found

Sorry, but we can’t find the page you requested.

Here’s something inspired by [Bridget Riley](https://en.wikipedia.org/wiki/Bridget_Riley) instead.

```js
import * as d3 from "npm:d3";

const height = Math.min(640, width);
const point = (cx, cy, r, a) => [cx + r * Math.cos(a), cy + r * Math.sin(a)];
const circles = [];
const random = d3.randomLcg(42);
const n = 80;
let a = 0.2;
let x = width / 2;
let y = height / 2;
let r = Math.hypot(width, height) / 2;
let dr = r / 6.5;

while (r > 0) {
circles.push({x, y, r, a});
const t = random() * 2 * Math.PI;
const s = Math.sqrt((random() * dr * dr) / 4);
x += Math.cos(t) * s;
y += Math.sin(t) * s;
r -= dr;
a = -a;
}

const canvas = display(document.createElement("canvas"));
canvas.width = width * devicePixelRatio;
canvas.height = height * devicePixelRatio;
canvas.style.width = `${width}px`;

const context = canvas.getContext("2d");
context.scale(devicePixelRatio, devicePixelRatio);

(function frame(elapsed) {
context.save();
context.clearRect(0, 0, width, height);
context.translate(width / 2, height / 2);
context.rotate(Math.sin(elapsed / 50000));
context.translate(-width / 2, -height / 2);
context.beginPath();
for (let i = 0; i < n; ++i) {
let move = true;
d3.pairs(circles, ({x: x1, y: y1, r: r1, a: a1}, {x: x2, y: y2, r: r2, a: a2}) => {
const ai = ((i * 2) / n) * Math.PI;
context[move ? ((move = false), "moveTo") : "lineTo"](...point(x1, y1, r1, a1 + ai));
context.lineTo(...point(x2, y2, r2, a2 + ai));
});
d3.pairs(circles.slice().reverse(), ({x: x1, y: y1, r: r1, a: a1}, {x: x2, y: y2, r: r2, a: a2}) => {
const ai = ((i * 2 + 1) / n) * Math.PI;
context.lineTo(...point(x1, y1, r1, a1 + ai));
context.lineTo(...point(x2, y2, r2, a2 + ai));
});
context.closePath();
}
context.fillStyle = getComputedStyle(canvas).getPropertyValue("color");
context.fill();
context.restore();
if (canvas.isConnected) requestAnimationFrame(frame);
})();
```
2 changes: 1 addition & 1 deletion src/navigation.ts
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,7 @@ export async function readPages(root: string): Promise<NonNullable<RenderOptions
if (config?.pages) return config?.pages;
const pages: RenderOptions["pages"] = [];
for await (const file of visitFiles(root)) {
if (extname(file) !== ".md") continue;
if (file === "404.md" || extname(file) !== ".md") continue;
let parsed: ParseResult;
try {
parsed = parseMarkdown(await readFile(join(root, file), "utf-8"), root, file);
Expand Down
17 changes: 16 additions & 1 deletion src/preview.ts
Original file line number Diff line number Diff line change
Expand Up @@ -47,6 +47,7 @@ class Server {

_handleRequest: RequestListener = async (req, res) => {
console.log(req.method, req.url);
let pages;
try {
const url = new URL(req.url!, "http://localhost");
let {pathname} = url;
Expand Down Expand Up @@ -124,7 +125,7 @@ class Server {
// Otherwise, serve the corresponding Markdown file, if it exists.
// Anything else should 404; static files should be matched above.
try {
const pages = await readPages(this.root); // TODO cache? watcher?
pages = await readPages(this.root); // TODO cache? watcher?
const {html} = await renderPreview(await readFile(path + ".md", "utf-8"), {
root: this.root,
path: pathname,
Expand All @@ -141,6 +142,20 @@ class Server {
} catch (error) {
console.error(error);
res.statusCode = isHttpError(error) ? error.statusCode : 500;
if (req.method === "GET" && res.statusCode === 404) {
try {
const {html} = await renderPreview(await readFile(join(this.root, "404.md"), "utf-8"), {
root: this.root,
path: "/404",
pages,
resolver: this._resolver!
});
end(req, res, html, "text/html");
return;
} catch {
// ignore secondary error (e.g., no 404.md); show the original 404
}
}
res.setHeader("Content-Type", "text/plain; charset=utf-8");
res.end(error instanceof Error ? error.message : "Oops, an error occurred");
}
Expand Down
2 changes: 1 addition & 1 deletion src/render.ts
Original file line number Diff line number Diff line change
Expand Up @@ -55,7 +55,7 @@ function render(
{path, pages, title, preview, hash, resolver}: RenderOptions & RenderInternalOptions
): string {
return `<!DOCTYPE html>
<meta charset="utf-8">
<meta charset="utf-8">${path === "/404" ? `\n<base href="/">` : ""}
<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1">
${
parseResult.title || title
Expand Down