Skip to content

page-level themes, specified in the front-matter #443

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Closed
wants to merge 1 commit into from
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
15 changes: 10 additions & 5 deletions src/build.ts
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,7 @@ import {createImportResolver, rewriteModule} from "./javascript/imports.js";
import type {Logger, Writer} from "./logger.js";
import {renderServerless} from "./render.js";
import {bundleStyles, getClientPath, rollupClient} from "./rollup.js";
import {styleHash} from "./theme.js";
import {faint} from "./tty.js";
import {resolvePath} from "./url.js";

Expand Down Expand Up @@ -71,6 +72,7 @@ export async function build(
// Render .md files, building a list of file attachments as we go.
const files: string[] = [];
const imports: string[] = [];
const styles = new Set<string | null>([null]);
for await (const sourceFile of visitMarkdownFiles(root)) {
const sourcePath = join(root, sourceFile);
const outputPath = join(dirname(sourceFile), basename(sourceFile, ".md") + ".html");
Expand All @@ -80,6 +82,7 @@ export async function build(
const resolveFile = ({name}) => resolvePath(sourceFile, name);
files.push(...render.files.map(resolveFile));
imports.push(...render.imports.filter((i) => i.type === "local").map(resolveFile));
if (render.theme) styles.add(render.theme);
await effects.writeFile(outputPath, render.html);
}

Expand All @@ -92,11 +95,13 @@ export async function build(
const code = await rollupClient(clientPath, {minify: true});
await effects.writeFile(outputPath, code);
}
// Generate the style bundle.
const outputPath = join("_observablehq", "style.css");
effects.output.write(`${faint("bundle")} config.style ${faint("→")} `);
const code = await bundleStyles(config);
await effects.writeFile(outputPath, code);
// Generate the page style bundles.
for (const theme of styles) {
const outputPath = join("_observablehq", `${theme === null ? "style" : `style-${styleHash(theme)}`}.css`);
effects.output.write(`${faint("bundle")} config.style ${faint("→")} `);
const code = await bundleStyles(theme === null ? config : {...config, theme: theme.split(",")});
await effects.writeFile(outputPath, code);
}
}

// Copy over the referenced files.
Expand Down
5 changes: 4 additions & 1 deletion src/markdown.ts
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,7 @@ import {parseInfo} from "./info.js";
import type {FileReference, ImportReference, PendingTranspile, Transpile} from "./javascript.js";
import {transpileJavaScript} from "./javascript.js";
import {transpileTag} from "./tag.js";
import {normalizeTheme} from "./theme.js";
import {resolvePath} from "./url.js";

export interface ReadMarkdownResult {
Expand Down Expand Up @@ -47,6 +48,7 @@ export interface ParseResult {
pieces: HtmlPiece[];
cells: CellPiece[];
hash: string;
theme?: string;
}

interface RenderPiece {
Expand Down Expand Up @@ -439,7 +441,8 @@ export async function parseMarkdown(source: string, root: string, sourcePath: st
imports: context.imports,
pieces: toParsePieces(context.pieces),
cells: await toParseCells(context.pieces),
hash: await computeMarkdownHash(source, root, sourcePath, context.imports)
hash: await computeMarkdownHash(source, root, sourcePath, context.imports),
theme: normalizeTheme(parts.data.theme)
};
}

Expand Down
8 changes: 7 additions & 1 deletion src/preview.ts
Original file line number Diff line number Diff line change
Expand Up @@ -20,6 +20,7 @@ import {diffMarkdown, readMarkdown} from "./markdown.js";
import type {ParseResult, ReadMarkdownResult} from "./markdown.js";
import {renderPreview} from "./render.js";
import {bundleStyles, getClientPath, rollupClient} from "./rollup.js";
import {styleHash} from "./theme.js";
import {bold, faint, green, underline} from "./tty.js";

const publicRoot = join(dirname(fileURLToPath(import.meta.url)), "..", "public");
Expand Down Expand Up @@ -93,7 +94,12 @@ export class PreviewServer {
} else if (pathname === "/_observablehq/style.css") {
end(req, res, await bundleStyles(config), "text/css");
} else if (pathname.startsWith("/_observablehq/")) {
send(req, pathname.slice("/_observablehq".length), {root: publicRoot}).pipe(res);
const style = pathname.slice("/_observablehq/".length).match(/^style-([0-9a-f]+)\.css$/);
if (style) {
const theme = decodeURIComponent(url.search.slice(1));
if (styleHash(theme) !== style[1]) throw new Error(`unexpected style signature ${style[1]}`);
end(req, res, await bundleStyles({...config, theme: theme.split(",")}), "text/css");
} else send(req, pathname.slice("/_observablehq".length), {root: publicRoot}).pipe(res);
} else if (pathname.startsWith("/_import/")) {
const file = pathname.slice("/_import".length);
let js: string;
Expand Down
32 changes: 19 additions & 13 deletions src/render.ts
Original file line number Diff line number Diff line change
Expand Up @@ -8,12 +8,14 @@ import {addImplicitSpecifiers, addImplicitStylesheets} from "./libraries.js";
import {type ParseResult, parseMarkdown} from "./markdown.js";
import {type PageLink, findLink, normalizePath} from "./pager.js";
import {getClientPath, rollupClient} from "./rollup.js";
import {styleUrl} from "./theme.js";
import {relativeUrl} from "./url.js";

export interface Render {
html: string;
files: FileReference[];
imports: ImportReference[];
theme?: string;
}

export interface RenderOptions extends Config {
Expand All @@ -23,20 +25,16 @@ export interface RenderOptions extends Config {

export async function renderPreview(source: string, options: RenderOptions): Promise<Render> {
const parseResult = await parseMarkdown(source, options.root, options.path);
return {
html: await render(parseResult, {...options, preview: true}),
files: parseResult.files,
imports: parseResult.imports
};
const {files, imports} = parseResult;
const html = await render(parseResult, {...options, preview: true});
return {html, files, imports};
}

export async function renderServerless(source: string, options: RenderOptions): Promise<Render> {
const parseResult = await parseMarkdown(source, options.root, options.path);
return {
html: await render(parseResult, options),
files: parseResult.files,
imports: parseResult.imports
};
const {files, imports, theme} = parseResult;
const html = await render(parseResult, options);
return {html, files, imports, theme};
}

export function renderDefineCell(cell: Transpile): string {
Expand All @@ -63,7 +61,7 @@ ${
.filter((title): title is string => !!title)
.join(" | ")}</title>\n`
: ""
}${await renderLinks(parseResult, path, createImportResolver(root, "_import"))}${
}${await renderLinks(parseResult, path, createImportResolver(root, "_import"), options.preview)}${
path === "/404"
? html.unsafe(`\n<script type="module">

Expand Down Expand Up @@ -169,8 +167,16 @@ function prettyPath(path: string): string {
return path.replace(/\/index$/, "/") || "/";
}

async function renderLinks(parseResult: ParseResult, path: string, resolver: ImportResolver): Promise<Html> {
const stylesheets = new Set<string>([relativeUrl(path, "/_observablehq/style.css"), "https://fonts.googleapis.com/css2?family=Source+Serif+Pro:ital,wght@0,400;0,600;0,700;1,400;1,600;1,700&display=swap"]); // prettier-ignore
async function renderLinks(
parseResult: ParseResult,
path: string,
resolver: ImportResolver,
preview?: boolean
): Promise<Html> {
const stylesheets = new Set<string>([
styleUrl(path, parseResult.theme, preview),
"https://fonts.googleapis.com/css2?family=Source+Serif+Pro:ital,wght@0,400;0,600;0,700;1,400;1,600;1,700&display=swap"
]); // prettier-ignore
const specifiers = new Set<string>(["npm:@observablehq/runtime", "npm:@observablehq/stdlib"]);
for (const {name} of parseResult.imports) specifiers.add(name);
const inputs = new Set(parseResult.cells.flatMap((cell) => cell.inputs ?? []));
Expand Down
23 changes: 23 additions & 0 deletions src/theme.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,23 @@
import {createHash} from "node:crypto";
import type {ParseResult} from "./markdown.js";
import {relativeUrl} from "./url.js";

export function styleUrl(path: string, theme?: string, preview?: boolean): string {
const [name, query] =
theme !== undefined ? ["style-" + styleHash(theme), preview ? `?${encodeURIComponent(theme)}` : ""] : ["style", ""];
return relativeUrl(path, `/_observablehq/${name}.css${query}`);
}

export function styleHash(str: string): string {
return createHash("sha256").update(str).digest("hex").slice(0, 16);
}

export function normalizeTheme(theme: any): ParseResult["theme"] {
return theme ? (typeof theme === "string" ? validate(theme) : Array.from(theme, validate).join(",")) : undefined;
}

function validate(theme: any): string {
theme = String(theme);
if (theme.match(/[^\w-]/)) throw new Error(`unsupported theme name ${theme}`);
return theme;
}