-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathmiddleware.tsx
More file actions
52 lines (44 loc) · 1.23 KB
/
Copy pathmiddleware.tsx
File metadata and controls
52 lines (44 loc) · 1.23 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
/** @jsxImportSource microjsx */
import { renderAsync, type ElementMiddleware, type PropsWithChildren } from "microjsx";
function Document({ children }: PropsWithChildren) {
return (
<html lang="en">
<head>
<meta charset="utf-8" />
<title>microjsx middleware</title>
</head>
<body>{children}</body>
</html>
);
}
const externalLinks: ElementMiddleware = ({ tag, props }) => {
if (tag !== "a" || typeof props["href"] !== "string") return;
if (!props["href"].startsWith("https://")) return;
return { ...props, target: "_blank", rel: "noreferrer" };
};
const imageMetadata: ElementMiddleware = async ({ tag, props }) => {
if (tag !== "img" || typeof props["src"] !== "string") return;
const size = await getImageSize(props["src"]);
return {
...props,
loading: props["loading"] ?? "lazy",
width: size.width,
height: size.height,
};
};
async function getImageSize(_src: string) {
return { width: 1200, height: 800 };
}
const html = await renderAsync(
<Document>
<main>
<h1>Element middleware</h1>
<a href="https://example.com">External link</a>
<img src="/photo.jpg" alt="A mountain lake" />
</main>
</Document>,
{
element: [externalLinks, imageMetadata],
},
);
console.log(`<!doctype html>${html}`);