-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmain.tsx
More file actions
108 lines (91 loc) · 2.73 KB
/
main.tsx
File metadata and controls
108 lines (91 loc) · 2.73 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
/** @jsxImportSource react */
import { useEffect, useState } from "react";
import { createRoot } from "react-dom/client";
import { fetchReadmeHTML, fetchSourceHTML } from "./utils.js";
const sources = {
"./index.html": { lang: "html" },
"./main.tsx": { lang: "tsx" },
"./utils.js": { lang: "javascript" },
} as const satisfies { [url: string]: { lang: string } };
function useSourceHTML(url: keyof typeof sources) {
const [sourceHTML, setSourceHTML] = useState<string | undefined>(undefined);
const [loading, setLoading] = useState(false);
useEffect(function updateSourceHTML() {
const ctrl = new AbortController();
setLoading(true);
fetchSourceHTML(url, sources[url].lang, ctrl.signal)
.then(setSourceHTML, (error) => {
if (!ctrl.signal.aborted) throw error;
})
.finally(() => {
if (!ctrl.signal.aborted) setLoading(false);
});
return () => ctrl.abort();
}, [url]);
return [sourceHTML, { loading }] as const;
}
function useReadmeHTML() {
const [readmeHTML, setReadmeHTML] = useState<string | undefined>(undefined);
useEffect(function updateReadmeHTML() {
const ctrl = new AbortController();
fetchReadmeHTML(ctrl.signal)
.then(setReadmeHTML, (error) => {
if (!ctrl.signal.aborted) throw error;
});
return () => ctrl.abort();
}, []);
return [readmeHTML] as const;
}
function SourceView(props: {
url: keyof typeof sources;
onLoadingChange?: (loading: boolean) => void;
}) {
const [sourceHTML, { loading }] = useSourceHTML(props.url);
useEffect(() => {
props.onLoadingChange?.(loading);
}, [loading, props.onLoadingChange]);
return <div dangerouslySetInnerHTML={{ __html: sourceHTML ?? "" }}></div>;
}
function SourcesView() {
const [selectedSourceUrl, setSelectedSourceUrl] = useState<
keyof typeof sources
>("./index.html");
const [loading, setLoading] = useState(false);
return (
<>
<label>
Source:
<select
onChange={function handleChange(event) {
setSelectedSourceUrl(
(event.currentTarget as HTMLSelectElement)
.value as keyof typeof sources,
);
}}
>
{Object.keys(sources).map((url) => (
<option key={url} value={url}>{url}</option>
))}
</select>
</label>
{loading && <progress />}
<SourceView
url={selectedSourceUrl}
onLoadingChange={setLoading}
/>
</>
);
}
function ReadmeView() {
const [readmeHTML] = useReadmeHTML();
return <div dangerouslySetInnerHTML={{ __html: readmeHTML ?? "" }}></div>;
}
function App() {
return (
<>
<ReadmeView />
<SourcesView />
</>
);
}
createRoot(document.body).render(<App />);