Skip to content

Commit b087765

Browse files
committed
feat: preview readme
1 parent 7d687d3 commit b087765

1 file changed

Lines changed: 44 additions & 1 deletion

File tree

routes/std/[...path].tsx

Lines changed: 44 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -31,7 +31,10 @@ async function fetchGitHubPath(path: string) {
3131
}`;
3232
const res = await fetch(apiUrl, {
3333
headers: {
34-
Accept: "application/vnd.github.v3+json",
34+
"Authorization": Deno.env.get("GITHUB_TOKEN")
35+
? `token ${Deno.env.get("GITHUB_TOKEN")}`
36+
: "",
37+
"Accept": "application/vnd.github.v3+json",
3538
},
3639
});
3740
if (!res.ok) {
@@ -64,6 +67,7 @@ export default async function StdPage(props: PageProps<never>) {
6467

6568
let items: TreeItem[] | undefined;
6669
let content: string | undefined;
70+
let readmePreview: { path: string; content: string } | undefined;
6771
let isFile = false;
6872
let error: string | undefined;
6973

@@ -80,6 +84,33 @@ export default async function StdPage(props: PageProps<never>) {
8084
});
8185
items = json as TreeItem[];
8286
isFile = false;
87+
try {
88+
const readmeItem = items.find((it) =>
89+
it.type === "file" && /readme\.md$/i.test(it.name)
90+
);
91+
if (readmeItem && readmeItem.path) {
92+
const r = await fetchGitHubPath(readmeItem.path);
93+
if (r.ok && r.json && r.json.content) {
94+
const raw = r.json;
95+
let readmeContent = "";
96+
if (raw.encoding === "base64" && raw.content) {
97+
readmeContent = atob(raw.content.replace(/\n/g, ""));
98+
} else if (raw.content) {
99+
readmeContent = raw.content;
100+
} else if (raw.download_url) {
101+
const rr = await fetch(raw.download_url);
102+
readmeContent = await rr.text();
103+
}
104+
if (readmeContent) {
105+
// limit preview to first ~800 characters to keep layout sane
106+
const preview = readmeContent.slice(0, 800);
107+
readmePreview = { path: readmeItem.path, content: preview };
108+
}
109+
}
110+
}
111+
} catch (_e) {
112+
// non-fatal; just don't show preview
113+
}
83114
} else if (json && json.type === "file") {
84115
isFile = true;
85116
if (json.encoding === "base64" && json.content) {
@@ -238,6 +269,18 @@ export default async function StdPage(props: PageProps<never>) {
238269
</div>
239270
)}
240271

272+
{/* README preview for directories */}
273+
{!isFile && items && readmePreview && (
274+
<div class="mt-6 rounded-lg border border-surface1 p-6 bg-surface">
275+
<div class="prose max-w-none">
276+
<MarkdownContent
277+
markdown={readmePreview.content}
278+
baseUrl={`https://raw.githubusercontent.com/${OWNER}/${REPO}/${BRANCH}/${readmePreview.path}`}
279+
/>
280+
</div>
281+
</div>
282+
)}
283+
241284
{isFile && (
242285
<div class="mt-6">
243286
<div class="flex items-center justify-between mb-3">

0 commit comments

Comments
 (0)