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
import { set } from "https://esm.town/v/std/set?v=11";
let { selfEditingWebsiteBody } = await import("https://esm.town/v/maxm/selfEditingWebsiteBody");
export const selfEditingWebsite = async (request: Request) => {
if (request == null) {
return "not invoked correctly";
}
// Otherwise, someone has submitted a form so let's handle that
if (selfEditingWebsiteBody === undefined) {
let defaultBody = `<h1>Edit Me!</h1>`;
selfEditingWebsiteBody = defaultBody;
}
if (request.method == "POST") {
let formData = await request.formData();
if (formData.get("source") !== undefined) {
selfEditingWebsiteBody = formData.get("source").toString();
await set("selfEditingWebsiteBody", selfEditingWebsiteBody);
}
}
let body = selfEditingWebsiteBody;
const form = `
<div style="border: 1px solid #999;">
<form action="" method="POST">
<label for="source">Edit the source of this web page:</label>
<textarea id="source" name="source" required>${body}</textarea>
<br>
<input type="submit" value="Submit">
</form>
</div>`;
return new Response(
`<!DOCTYPE html>
<html>
<head>
<title>I am a self-editing website!</title>
<script src="https://cdnjs.cloudflare.com/ajax/libs/codemirror/5.65.15/codemirror.min.js" integrity="sha512-2359y3bpxFfJ9xZw1r2IHM0WlZjZLI8gjLuhTGOVtRPzro3dOFy4AyEEl9ECwVbQ/riLXMeCNy0h6HMt2WUtYw==" crossorigin="anonymous" referrerpolicy="no-referrer"></s
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/codemirror/5.65.15/codemirror.min.css" integrity="sha512-uf06llspW44/LZpHzHT6qBOIVODjWtv4MxCricRxkzvopAlSWnTf6hpZTFxuuZcuNE9CBQhqE0Seu1CoRk84nQ==" crossorigin="anonymous" referrerpolicy=
</head>
<body>
${body}
${form}
<script>
var editor = CodeMirror.fromTextArea(document.getElementById('source'), {
mode: "html",
lineNumbers: true,
});
editor.save();
</script>
</body>
</html>`,
{ headers: { "Content-Type": "text/html" } },
);
};