Skip to content

tailwind #1762

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

Draft
wants to merge 10 commits into
base: main
Choose a base branch
from
Draft
Show file tree
Hide file tree
Changes from 6 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
1 change: 1 addition & 0 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -119,6 +119,7 @@
"cross-env": "^7.0.3",
"d3-dsv": "^3.0.1",
"d3-format": "^3.1.0",
"esbuild-plugin-tailwindcss": "^1.2.1",
"eslint": "^8.50.0",
"eslint-config-prettier": "^9.1.0",
"eslint-import-resolver-typescript": "^3.6.1",
Expand Down
6 changes: 3 additions & 3 deletions src/build.ts
Original file line number Diff line number Diff line change
Expand Up @@ -164,10 +164,10 @@ export async function build(
effects.output.write(`${faint("build")} ${path} ${faint("→")} `);
if (specifier.startsWith("observablehq:theme-")) {
const match = /^observablehq:theme-(?<theme>[\w-]+(,[\w-]+)*)?\.css$/.exec(specifier);
contents = await bundleStyles({theme: match!.groups!.theme?.split(",") ?? [], minify: true});
contents = await bundleStyles({theme: match!.groups!.theme?.split(",") ?? [], minify: true, root});
} else {
const clientPath = getClientPath(path.slice("/_observablehq/".length));
contents = await bundleStyles({path: clientPath, minify: true});
contents = await bundleStyles({path: clientPath, minify: true, root});
}
const hash = createHash("sha256").update(contents).digest("hex").slice(0, 8);
const alias = applyHash(path, hash);
Expand All @@ -181,7 +181,7 @@ export async function build(
} else if (!/^\w+:/.test(specifier)) {
const sourcePath = join(root, specifier);
effects.output.write(`${faint("build")} ${sourcePath} ${faint("→")} `);
const contents = await bundleStyles({path: sourcePath, minify: true});
const contents = await bundleStyles({path: sourcePath, minify: true, root});
const hash = createHash("sha256").update(contents).digest("hex").slice(0, 8);
const alias = applyHash(join("/_import", specifier), hash);
aliases.set(resolveStylesheetPath(root, specifier), alias);
Expand Down
2 changes: 2 additions & 0 deletions src/client/preview.js
Original file line number Diff line number Diff line change
Expand Up @@ -155,6 +155,8 @@ export function open({hash, eval: compile} = {}) {
for (const href of message.stylesheets.removed) {
document.head.querySelector(`link[rel="stylesheet"][href="${href}"]`)?.remove();
}
const tw = document.head.querySelector('link[rel="stylesheet"][href$="_observablehq/tailwind.css"]');
if (tw) tw.href = "" + tw.href; // reload tailwind.css
}
enableCopyButtons();
break;
Expand Down
3 changes: 3 additions & 0 deletions src/client/tailwind.css
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
@import "tailwindcss/base";
@import "tailwindcss/components";
@import "tailwindcss/utilities";
6 changes: 3 additions & 3 deletions src/preview.ts
Original file line number Diff line number Diff line change
Expand Up @@ -132,13 +132,13 @@ export class PreviewServer {
} else if (pathname === "/_observablehq/minisearch.json") {
end(req, res, await searchIndex(config), "application/json");
} else if ((match = /^\/_observablehq\/theme-(?<theme>[\w-]+(,[\w-]+)*)?\.css$/.exec(pathname))) {
end(req, res, await bundleStyles({theme: match.groups!.theme?.split(",") ?? []}), "text/css");
end(req, res, await bundleStyles({theme: match.groups!.theme?.split(",") ?? [], root}), "text/css");
} else if (pathname.startsWith("/_observablehq/") && pathname.endsWith(".js")) {
const path = getClientPath(pathname.slice("/_observablehq/".length));
end(req, res, await rollupClient(path, root, pathname), "text/javascript");
} else if (pathname.startsWith("/_observablehq/") && pathname.endsWith(".css")) {
const path = getClientPath(pathname.slice("/_observablehq/".length));
end(req, res, await bundleStyles({path}), "text/css");
end(req, res, await bundleStyles({path, root}), "text/css");
} else if (pathname.startsWith("/_node/") || pathname.startsWith("/_jsr/")) {
send(req, pathname, {root: join(root, ".observablehq", "cache")}).pipe(res);
} else if (pathname.startsWith("/_npm/")) {
Expand All @@ -151,7 +151,7 @@ export class PreviewServer {
if (module) {
const sourcePath = join(root, path);
await access(sourcePath, constants.R_OK);
end(req, res, await bundleStyles({path: sourcePath}), "text/css");
end(req, res, await bundleStyles({path: sourcePath, root}), "text/css");
return;
}
} else if (pathname.endsWith(".js")) {
Expand Down
1 change: 1 addition & 0 deletions src/resolvers.ts
Original file line number Diff line number Diff line change
Expand Up @@ -348,6 +348,7 @@ async function resolveResolvers(
}

// Add implicit stylesheets.
stylesheets.add("observablehq:tailwind.css");
for (const specifier of getImplicitStylesheets(staticImports)) {
stylesheets.add(specifier);
if (specifier.startsWith("npm:")) {
Expand Down
53 changes: 50 additions & 3 deletions src/rollup.ts
Original file line number Diff line number Diff line change
@@ -1,11 +1,14 @@
import {extname, resolve} from "node:path/posix";
import {writeFile} from "node:fs/promises";
import {extname, join, resolve} from "node:path/posix";
import {nodeResolve} from "@rollup/plugin-node-resolve";
import {simple} from "acorn-walk";
import {build} from "esbuild";
import type {Plugin as ESBuildPlugin} from "esbuild";
import {tailwindPlugin} from "esbuild-plugin-tailwindcss";
import type {AstNode, OutputChunk, Plugin, ResolveIdResult} from "rollup";
import {rollup} from "rollup";
import esbuild from "rollup-plugin-esbuild";
import {getClientPath, getStylePath} from "./files.js";
import {getClientPath, getStylePath, maybeStat, prepareOutput} from "./files.js";
import type {StringLiteral} from "./javascript/source.js";
import {getStringLiteralValue, isStringLiteral} from "./javascript/source.js";
import {resolveNpmImport} from "./npm.js";
Expand All @@ -17,6 +20,7 @@ import {THEMES, renderTheme} from "./theme.js";

const STYLE_MODULES = {
"observablehq:default.css": getStylePath("default.css"),
"observablehq:tailwind.css": getStylePath("tailwind.css"),
...Object.fromEntries(THEMES.map(({name, path}) => [`observablehq:theme-${name}.css`, path]))
};

Expand All @@ -36,21 +40,30 @@ function rewriteInputsNamespace(code: string) {
export async function bundleStyles({
minify = false,
path,
theme
theme,
root
}: {
minify?: boolean;
path?: string;
theme?: string[];
root: string;
}): Promise<string> {
const plugins = path === getClientPath("tailwind.css") ? [await tailwindConfig(root)] : undefined;
const result = await build({
bundle: true,
...(path ? {entryPoints: [path]} : {stdin: {contents: renderTheme(theme!), loader: "css"}}),
write: false,
minify,
plugins,
alias: STYLE_MODULES
});
let text = result.outputFiles[0].text;
if (path === getClientPath("stdlib/inputs.css")) text = rewriteInputsNamespace(text);
// dirty patch for tailwind: remove margin:0 and styles resets for headers
// etc. It should probably be a tailwind plugin instead.
if (path === getClientPath("tailwind.css"))
text = text.replaceAll(/}[^{]*h1,\n*h2,\n*h3,\n*h4,\n*h5,\n*h6[^}]+}\s*/g, "}");

Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

You want the typography plugin and prose class.

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Maybe, but there are other resets that wreck our page, and we might want to find a way to remove the resets independently of adding /prose/ (this works already, anyway). I was thinking maybe a custom plugin we'd inline.

Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

We may need to commit to Tailwind and rewrite any of our own styles accordingly.

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Yes that's a good possibility. For now I'm merely taking stock of the things that change.

The other big change I've noticed are the grid-cols-* classes, which I have to block for now because they are quite different. Ours is responsive to width, tailwind's responsiveness is based on a breakpoint modifier (e.g. lg:grid-cols-3).

blocklist: ["grid", "grid-cols-2", "grid-cols-3", "grid-cols-4"],

return text;
}

Expand Down Expand Up @@ -184,3 +197,37 @@ function importMetaResolve(path: string, resolveImport: ImportResolver): Plugin
}
};
}

// Create a tailwind plugin, configured to reference as content the project
// files that might contain tailwind class names, and the 'tw-' prefix. If a
// tailwind.config.js is present in the project root, we import and merge it.
async function tailwindConfig(root: string): Promise<ESBuildPlugin> {
const twconfig = "tailwind.config.js";
const configPath = join(root, ".observablehq", "cache", twconfig);
const s = await maybeStat(join(root, twconfig));
const m = await maybeStat(configPath);
if (!m || !s || !(m.mtimeMs > s.mtimeMs)) {
await prepareOutput(configPath);
await writeFile(
configPath,
`
// File generated by rollup.ts; to configure tailwind, edit ${root}/tailwind.config.js
${s ? `import config from "../../${twconfig}"` : "const config = {}"};
export default {
content: {
files: [
"${root}/**/*.{js,md}" /* pages and components */,
"${root}/.observablehq/cache/**/*.md" /* page loaders */,
"${root}/.observablehq/cache/_import/**/*.js" /* transpiled components */
]
},
darkMode: ["variant", "&:where([class~=dark], [class~=dark] *)"],
blocklist: ["grid", "grid-cols-2", "grid-cols-3", "grid-cols-4"],
prefix: "",
...config
};
`
);
}
return tailwindPlugin({configPath});
}
Loading
Loading