/** * HTML rendering for the browse pages. * * Pure string building: the router reads the filesystem and hands these * renderers plain view models. Everything user-controlled is escaped, links are * percent-encoded per segment, and the only script is the same-origin * `/app.js`. The shared Bytefly shell and components come from `lib/web`, and * the page-only `browse-*` rules from `styles.ts`. */ import { appHead, baseAttribute, docHead, type KeyHint, keysSheet, pageFooter, tabTitle, } from "../../../lib/web/index.ts"; import { escapeHtml } from "../../../lib/escape.ts"; import { renderChanges, renderGit, renderLiveChrome, type LivePage } from "./chrome.ts"; import { type DirEntry, type FileView, type Listing, type TreeNode } from "../files/files.ts"; import { formatSize } from "../../../lib/format.ts"; import { lastSegment } from "../../../lib/path.ts"; import type { GitStatus } from "../git/git.ts"; import type { ChangeIndex } from "../live/live.ts"; import { detectLanguage, highlightLines, type HighlightLanguage } from "../../../lib/highlight.ts"; import { FOLDER_ICON, iconHref, languageOf, SPRITE, type IconSpec } from "./icons.ts"; import { renderMarkdown } from "./markdown.ts"; import { encodePath } from "../files/paths.ts"; import { BROWSE_CSS } from "./styles.ts"; const MONTHS = ["Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"]; /** A short local date like `Oct 8 20:31`. */ export function formatDate(ms: number): string { const date = new Date(ms); if (Number.isNaN(date.getTime())) return "—"; const hh = String(date.getHours()).padStart(2, "0"); const mm = String(date.getMinutes()).padStart(2, "0"); return `${MONTHS[date.getMonth()]} ${date.getDate()} ${hh}:${mm}`; } function iconMarkup(spec: IconSpec, hidden = false): string { return ``; } /** * The changed-path index for markers, plus the totals shown in the chip. It is * the same index the live status feed sends, so the page and its updates agree * on what "changed" means. */ export type ChangeSummary = ChangeIndex; /** Whether a path carries a change marker: a changed file, or a directory above one. */ function isChanged(summary: ChangeSummary | undefined, rel: string, isDir: boolean): boolean { if (!summary || !rel) return false; return isDir ? summary.dirs.has(rel) : summary.files.has(rel); } /** A small dot marking a changed file or a directory that contains one. */ function changeMark(summary: ChangeSummary | undefined, rel: string, isDir: boolean): string { return isChanged(summary, rel, isDir) ? `●` : ""; } /** * The URL one tree or table entry links to, written under the page's `base`. * * Exported because the JSON `/api/tree` route answers with the same hrefs, so the rendered * tree and the client's refresh cannot disagree about where an entry lives. */ export function hrefFor(entry: { rel: string; isDir: boolean }, base: string): string { return entry.isDir ? `${base}/browse/${encodePath(entry.rel)}` : `${base}/view/${encodePath(entry.rel)}`; } interface Layout { /** The mount prefix this page answers under, e.g. `/files`; `""` for the origin's root. */ base: string; title: string; rootLabel: string; tree: TreeNode; currentRel: string; breadcrumbs: string; main: string; footerNote: string; /** Extra classes on `main`, for page-scoped rules. */ mainClass?: string; /** Rows for the `?` keyboard sheet; omitted when the page has no shortcuts. */ keys?: KeyHint[]; git?: GitStatus; /** Changed-path index for the header chip and the tree markers; omitted when clean. */ summary?: ChangeSummary; /** Live status chrome; omitted when the channel is off. */ live?: LivePage; } /** A full two-pane page. */ function renderLayout(layout: Layout): string { return `
${docHead({ title: layout.title, css: BROWSE_CSS, base: layout.base })} Skip to content ${SPRITE} ${appHead({ product: "browse", subject: { label: layout.rootLabel, title: layout.rootLabel }, facts: `${renderGit(layout.git)} ${renderChanges(layout.summary, layout.live)} ${renderLiveChrome(layout.live)}`, })}Showing the first ${page.listing.entries.length} of ${page.listing.total} entries.
`; return renderLayout({ base: page.base, title: tabTitle("browse", page.rel || folderName), rootLabel: page.rootLabel, tree: page.tree, currentRel: page.rel, breadcrumbs: renderBreadcrumbs(page.rel, page.base), keys: pageKeys(), main: ` ${heading}\n ${body}`, footerNote: `${page.listing.total} entr${page.listing.total === 1 ? "y" : "ies"}`, git: page.git, summary: page.summary, live: page.live, }); } export interface FilePage { base: string; rootLabel: string; rel: string; file: FileView; tree: TreeNode; maxFileBytes: number; git?: GitStatus; /** Show the Markdown source instead of the rendered HTML. */ markdownRaw?: boolean; /** Re-emit sanitized raw HTML in rendered Markdown; `false` escapes it as text. */ markdownHtml?: boolean; /** Changed-path index for the header chip and the tree markers. */ summary?: ChangeSummary; /** Live status chrome; omitted when the channel is off. */ live?: LivePage; } /** The root-relative directory of a file, for resolving its Markdown links. */ function markdownBaseDir(rel: string): string { const slash = rel.lastIndexOf("/"); return slash === -1 ? "" : rel.slice(0, slash); } function renderCodeLines(lines: string[], language?: HighlightLanguage): string { const rendered = language ? highlightLines(lines, language) : lines.map((line) => escapeHtml(line)); return rendered.map((html) => `${html.length > 0 ? html : " "}`).join(""); } /** The shortcuts every page shares, plus whatever the page adds. */ function pageKeys(...extra: KeyHint[]): KeyHint[] { return [ { keys: "/ ⌘K", label: "Quick open a file" }, { keys: "-", label: "Fold or expand every folder" }, ...extra, { keys: "?", label: "This sheet" }, ]; } /** Whether the page renders lines with a number beside them: plain text, or raw Markdown. */ function numberedLines(page: FilePage): boolean { return page.file.kind === "text" || (page.file.kind === "markdown" && page.markdownRaw === true); } /** The card-head controls: Markdown mode, line wrapping, and the copy actions, * plus the download it keeps in the same group. */ function renderFileActions(page: FilePage, download: string): string { const isMarkdown = page.file.kind === "markdown"; const rawHref = `${page.base}/raw/${encodePath(page.rel)}`; const viewHref = `${page.base}/view/${encodePath(page.rel)}`; const groups: string[] = []; if (isMarkdown) { const rendered = page.markdownRaw ? `rendered` : `rendered`; const raw = page.markdownRaw ? `raw` : `raw`; groups.push(`${rendered}${raw}`); } if (numberedLines(page)) { groups.push( ``, ); } if (page.file.kind === "text" || isMarkdown) { groups.push( ``, ); } groups.push( ``, ); if (numberedLines(page)) { groups.push( ``, ); } return `${groups.join("")}${download}`; } /** Render a file page (text, Markdown, image, binary, or over-size). */ export function renderFilePage(page: FilePage): string { const name = page.rel.slice(page.rel.lastIndexOf("/") + 1); const spec = languageOf(name); const language = page.file.kind === "text" ? detectLanguage(name) : undefined; // Text is always served as octet-stream, so the response type says nothing // about the file; the language label, size, and date are the useful metadata. const meta = `${spec.label} · ${formatSize(page.file.size)} · ${formatDate(page.file.mtimeMs)}`; const download = `download`; const head = `${renderCodeLines(page.file.lines, language)}`;
}
if (page.file.truncated)
note = `Showing the first ${page.file.lines.length} of ${page.file.totalLines} lines.
`; } else if (page.file.kind === "image") { content = `File is ${escapeHtml(formatSize(page.file.size))}.
Larger than the ${escapeHtml(formatSize(page.maxFileBytes))} inline limit.
${download}Looks like a binary file.
${escapeHtml(formatSize(page.file.size))} · ${escapeHtml(page.file.mime)}
${download}