From a8fe4d10628e535fec106675dabb47dd505c9595 Mon Sep 17 00:00:00 2001 From: Abdullah Hashim Date: Thu, 24 Sep 2026 09:43:26 -0400 Subject: [PATCH] Add bin/dev for previewing the theme in a browser Serves the test/fixtures site through bridgetown start with a standard esbuild + Tailwind v4 frontend, so asset_path resolves to real bundles and edits to layouts/ and frontend/styles/ live-reload. Also fixes the README Tailwind snippet, which placed @source between the two @import rules and caused the theme import to be silently dropped. --- .gitignore | 2 + CHANGELOG.md | 6 +- Gemfile | 4 + README.md | 7 +- bin/dev | 19 ++ bridgetown-stoa.gemspec | 2 +- test/fixtures/Rakefile | 21 ++ test/fixtures/config/esbuild.defaults.js | 361 +++++++++++++++++++++ test/fixtures/config/initializers.rb | 11 + test/fixtures/esbuild.config.js | 44 +++ test/fixtures/frontend/javascript/index.js | 1 + test/fixtures/frontend/styles/index.css | 6 + test/fixtures/package.json | 21 ++ test/fixtures/postcss.config.js | 5 + 14 files changed, 506 insertions(+), 4 deletions(-) create mode 100755 bin/dev create mode 100644 test/fixtures/Rakefile create mode 100644 test/fixtures/config/esbuild.defaults.js create mode 100644 test/fixtures/esbuild.config.js create mode 100644 test/fixtures/frontend/javascript/index.js create mode 100644 test/fixtures/frontend/styles/index.css create mode 100644 test/fixtures/package.json create mode 100644 test/fixtures/postcss.config.js diff --git a/.gitignore b/.gitignore index 4307bb4..7246043 100644 --- a/.gitignore +++ b/.gitignore @@ -38,3 +38,5 @@ test/dest /.ruby-lsp/ /Gemfile.lock +test/fixtures/output +test/fixtures/tmp diff --git a/CHANGELOG.md b/CHANGELOG.md index 964ce63..cae2866 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -7,7 +7,11 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0 ## [Unreleased] -- ... +### Added +- `bin/dev` serves the `test/fixtures` site with the theme applied for browser previews. The fixture now carries a standard Bridgetown esbuild + Tailwind v4 (`@tailwindcss/postcss`) frontend, so `asset_path :css` / `:js` resolve to real bundles, and it watches the gem's `layouts/` directory so theme edits live-reload. + +### Fixed +- README's Tailwind setup snippet placed `@source` between the two `@import` rules, which made Tailwind and postcss-import silently drop `@import "bridgetown-stoa"`. The imports now come first. ## [0.3.0] - 2026-05-22 diff --git a/Gemfile b/Gemfile index 8821275..05cc278 100644 --- a/Gemfile +++ b/Gemfile @@ -5,6 +5,10 @@ gemspec gem "bridgetown", ENV["BRIDGETOWN_VERSION"] if ENV["BRIDGETOWN_VERSION"] +group :development do + gem "puma" # Rack server for bin/dev +end + group :test do gem "minitest" gem "minitest-profile" diff --git a/README.md b/README.md index 91dc45e..4ec5917 100644 --- a/README.md +++ b/README.md @@ -34,12 +34,12 @@ Then in `frontend/styles/index.css`, after `@import "tailwindcss";`, add two lin ```css @import "tailwindcss"; -@source "../../node_modules/bridgetown-stoa/layouts/**/*.serb"; @import "bridgetown-stoa"; +@source "../../node_modules/bridgetown-stoa/layouts/**/*.serb"; ``` +- `@import "bridgetown-stoa"` pulls in the `@theme` tokens (`--color-stoa-*`, `--font-stoa-*`) and a small `@layer base` that styles `html` with the theme colors. Keep it directly after the Tailwind import: CSS requires all `@import` rules to come before any other rule, and an `@import` placed after `@source` is silently dropped. - `@source` tells Tailwind to scan Stoa's layouts for utility-class usage. -- `@import "bridgetown-stoa"` pulls in the `@theme` tokens (`--color-stoa-*`, `--font-stoa-*`) and a small `@layer base` that styles `html` with the theme colors. Override any token by redeclaring it in your own `@theme` block after the import. @@ -77,8 +77,11 @@ Requires Ruby ≥ 3.2 and Bridgetown ≥ 2.0. ```shell bundle install script/cibuild # rubocop + minitest +bin/dev # preview the theme at http://localhost:4000 ``` +`bin/dev` serves the site in `test/fixtures` with the theme applied, using a standard Bridgetown esbuild + Tailwind pipeline (it runs `bundle install` and `npm install` for you when needed). Edits to `layouts/` and `frontend/styles/` rebuild and live-reload. Extra arguments go to `bridgetown start`, e.g. `bin/dev -P 4001`. + Templates use [Serbea](https://www.bridgetownrb.com/docs/template-engines/erb-and-beyond), Bridgetown's ERB-with-Liquid-like-sugar engine. Stoa is **inspired by** just-the-docs, not a port of it — layouts are written idiomatically for Bridgetown rather than translated from upstream. ## License diff --git a/bin/dev b/bin/dev new file mode 100755 index 0000000..a4d10dd --- /dev/null +++ b/bin/dev @@ -0,0 +1,19 @@ +#!/usr/bin/env bash +# Serve the test fixture site with the theme applied, for previewing changes +# to layouts and styles in a browser. Extra arguments are passed through to +# `bridgetown start` (e.g. `bin/dev -P 4001`). +set -euo pipefail + +cd "$(dirname "$0")/.." + +if ! bundle check >/dev/null 2>&1; then + bundle install +fi + +cd test/fixtures + +if [ ! -f node_modules/.package-lock.json ] || [ package.json -nt node_modules/.package-lock.json ]; then + npm install +fi + +exec bundle exec bridgetown start "$@" diff --git a/bridgetown-stoa.gemspec b/bridgetown-stoa.gemspec index ff1bb8a..23f8d58 100644 --- a/bridgetown-stoa.gemspec +++ b/bridgetown-stoa.gemspec @@ -11,7 +11,7 @@ Gem::Specification.new do |spec| spec.homepage = "https://github.com/Guided-Rails/bridgetown-stoa" spec.license = "MIT" - spec.files = `git ls-files -z`.split("\x0").reject { |f| f.match(%r!^(test|script|spec|features|frontend)/!) } + spec.files = `git ls-files -z`.split("\x0").reject { |f| f.match(%r!^(test|script|bin|spec|features|frontend)/!) } spec.test_files = spec.files.grep(%r!^test/!) spec.require_paths = ["lib"] spec.metadata = { diff --git a/test/fixtures/Rakefile b/test/fixtures/Rakefile new file mode 100644 index 0000000..4f712c7 --- /dev/null +++ b/test/fixtures/Rakefile @@ -0,0 +1,21 @@ +# frozen_string_literal: true + +# Minimal Bridgetown site Rakefile: gives `bridgetown start` (via bin/dev) +# a `frontend:dev` task so it can run esbuild alongside the site watcher. + +require "bridgetown" + +Bridgetown.load_tasks + +namespace :frontend do + desc "Build the frontend with esbuild for deployment" + task :build do + sh "npm run esbuild" + end + + desc "Watch the frontend with esbuild during development" + task :dev do + sh "npm run esbuild-dev" + rescue Interrupt + end +end diff --git a/test/fixtures/config/esbuild.defaults.js b/test/fixtures/config/esbuild.defaults.js new file mode 100644 index 0000000..b1626ef --- /dev/null +++ b/test/fixtures/config/esbuild.defaults.js @@ -0,0 +1,361 @@ +// This file is created and managed by Bridgetown. +// Instead of editing this file, add your overrides to `esbuild.config.js` +// +// To update this file to the latest version provided by Bridgetown, +// run `bridgetown esbuild update`. Any changes to this file will be overwritten +// when an update is applied hence we strongly recommend adding overrides to +// `esbuild.config.js` instead of editing this file. +// +// Shipped with Bridgetown v2.1.2 + +// DO NOT MANUALLY EDIT THIS CONFIGURATION: +const autogeneratedBridgetownConfig = { + "source": "src", + "destination": "output", + "componentsDir": "_components", + "islandsDir": "_islands" +} + +import path from "path" +import fsLib from "fs" +const fs = fsLib.promises +import { pathToFileURL, fileURLToPath } from "url" +import { glob } from "glob" +import postcss from "postcss" +import postCssImport from "postcss-import" +import readCache from "read-cache" + +// Detect if an NPM package is available +const moduleAvailable = name => { + try { + import.meta.resolve(name) + return true + } catch (e) { } + return false +} + +// Generate a Source Map URL (used by the Sass plugin) +const generateSourceMappingURL = sourceMap => { + const data = Buffer.from(JSON.stringify(sourceMap), "utf-8").toString("base64") + return `/*# sourceMappingURL=data:application/json;charset=utf-8;base64,${data} */` +} + +// Import Sass if available +let sass +if (moduleAvailable("sass")) { + sass = await import("sass") +} + +// Glob plugin derived from: +// https://github.com/thomaschaaf/esbuild-plugin-import-glob +// https://github.com/xiaohui-zhangxh/jsbundling-rails/commit/b15025dcc20f664b2b0eb238915991afdbc7cb58 +const importGlobPlugin = (options, bridgetownConfig) => ({ + name: "import-glob", + setup: (build) => { + build.onResolve({ filter: /\*/ }, async (args) => { + if (args.resolveDir === "") { + return; // Ignore unresolvable paths + } + + const adjustedPath = args.path + .replace(/^\$components\/\*\*/, `../../${bridgetownConfig.source}/${bridgetownConfig.componentsDir}/**`) + .replace(/^bridgetownComponents\//, `../../${bridgetownConfig.source}/${bridgetownConfig.componentsDir}/`) // legacy + + return { + path: adjustedPath, + namespace: "import-glob", + pluginData: { + path: adjustedPath, + resolveDir: args.resolveDir, + }, + } + }) + + build.onLoad({ filter: /.*/, namespace: "import-glob" }, async (args) => { + const files = glob.sync(args.pluginData.path, { + cwd: args.pluginData.resolveDir, + }) + .filter(module => options.excludeFilter ? !options.excludeFilter.test(module) : true) + .sort() + .map(module => module.replace(`../../${bridgetownConfig.source}/${bridgetownConfig.componentsDir}/`, "$components/")) + .map(module => module.match(/^[a-zA-Z0-9]/) ? `./${module}` : module) + + const importerCode = ` + ${files + .map((module, index) => `import * as module${index} from '${module}'`) + .join(';')} + const modules = {${files + .map((module, index) => ` + "${module.replace("$components/", "")}": module${index},`) + .join("")} + }; + export default modules; + ` + + return { contents: importerCode, resolveDir: args.pluginData.resolveDir } + }) + }, +}) + +// Plugin for PostCSS +const importPostCssPlugin = (options, configuration) => ({ + name: "postcss", + async setup(build) { + // Process .css files with PostCSS + build.onLoad({ filter: (configuration.filter || /\.css$/) }, async (args) => { + if (args.path.endsWith(".lit.css")) return; + + const additionalFilePaths = [] + const css = await fs.readFile(args.path, "utf8") + + // Configure import plugin so PostCSS can properly resolve `@import`ed CSS files + const importPlugin = postCssImport({ + filter: itemPath => !itemPath.startsWith("/"), // ensure it doesn't try to import source-relative paths + load: async filename => { + let contents = await readCache(filename, "utf-8") + const filedir = path.dirname(filename) + // We'll want to track any imports later when in watch mode: + additionalFilePaths.push(filename) + + // We need to transform `url(...)` in imported CSS so the filepaths are properly + // relative to the entrypoint. Seems icky to have to hack this! C'est la vie... + contents = contents.replace(/url\(['"]?\.\/(.*?)['"]?\)/g, (_match, p1) => { + const relpath = path.relative(args.path, path.resolve(filedir, p1)).replace(/^\.\.\//, "") + return `url("${relpath}")` + }) + return contents + } + }) + + // Process the file through PostCSS + let outputCSS = "" + try { + const result = await postcss([importPlugin, ...options.plugins]).process(css, { + map: true, + ...options.options, + from: args.path, + }) + outputCSS = result.css + } catch(err) { + console.error(`\nerror: "${err.reason}" while processing CSS file:\n${err.file}:${err.line}:${err.column}\n`) + } + return { + contents: outputCSS, + loader: "css", + watchFiles: [args.path, ...additionalFilePaths], + } + }) + }, +}) + +// Plugin for Sass +const sassPlugin = (options) => ({ + name: "sass", + async setup(build) { + // Process .scss and .sass files with Sass + build.onLoad({ filter: /\.(sass|scss)$/ }, async (args) => { + if (!sass) { + console.error("error: Sass is not installed. Try running `npm i sass -D` and then building again.") + return + } + + const modulesFolder = pathToFileURL("node_modules/") + + const localOptions = { + importers: [{ + // An importer that redirects relative URLs starting with "~" to + // `node_modules`. + findFileUrl(url) { + if (!url.startsWith('~')) return null + return new URL(url.substring(1), modulesFolder) + } + }], + sourceMap: true, + ...options + } + const result = sass.compile(args.path, localOptions) + + const watchPaths = result.loadedUrls + .filter((x) => x.protocol === "file:" && !x.pathname.startsWith(modulesFolder.pathname)) + .map((x) => x.pathname) + + let cssOutput = result.css.toString() + + if (result.sourceMap) { + const basedir = process.cwd() + const sourceMap = result.sourceMap + + const promises = sourceMap.sources.map(async source => { + const sourceFile = await fs.readFile(fileURLToPath(source), "utf8") + return sourceFile + }) + sourceMap.sourcesContent = await Promise.all(promises) + + sourceMap.sources = sourceMap.sources.map(source => { + return path.relative(basedir, fileURLToPath(source)) + }) + + cssOutput += '\n' + generateSourceMappingURL(sourceMap) + } + + return { + contents: cssOutput, + loader: "css", + watchFiles: [args.path, ...watchPaths], + } + }) + }, +}) + +// Set up defaults and generate frontend bundling manifest file +const bridgetownPreset = (bridgetownConfig) => ({ + name: "bridgetownPreset", + async setup(build) { + // Ensure any imports anywhere starting with `/` are left verbatim + // so they can be used in-browser for actual `src` repo files + build.onResolve({ filter: /^\// }, args => { + return { path: args.path, external: true } + }) + + build.onStart(() => { + console.log("esbuild: frontend bundling started...") + }) + + // Generate the final output manifest + build.onEnd(async (result) => { + if (!result.metafile) { + console.warn("esbuild: build process error, cannot write manifest") + return + } + + const manifest = {} + const entrypoints = [] + + // Clean up entrypoint naming + const stripPrefix = (str) => str + .replace(/^frontend\//, "") + .replace(RegExp(String.raw`^${bridgetownConfig.source}\/${bridgetownConfig.islandsDir}\/`), "islands/") + + // For calculating the file size of bundle output + const fileSize = (path) => { + const { size } = fsLib.statSync(path) + const i = Math.floor(Math.log(size) / Math.log(1024)) + return (size / Math.pow(1024, i)).toFixed(2) * 1 + ['B', 'KB', 'MB', 'GB', 'TB'][i] + } + + const pathShortener = new RegExp(String.raw`^${bridgetownConfig.destination}\/_bridgetown\/static\/`, "g") + + // Let's loop through all the various outputs + for (const key in result.metafile.outputs) { + const value = result.metafile.outputs[key] + const inputs = Object.keys(value.inputs) + const outputPath = key.replace(pathShortener, "") + + if (value.entryPoint) { + // We have an entrypoint! + manifest[stripPrefix(value.entryPoint)] = outputPath + entrypoints.push([outputPath, fileSize(key)]) + } else if (key.match(/index(\.js)?\.[^-.]*\.css/) && inputs.find(item => item.match(/frontend.*\.(s?css|sass)$/))) { + // Special treatment for index.css + const input = inputs.find(item => item.match(/frontend.*\.(s?css|sass)$/)) + manifest[stripPrefix(input)] = outputPath + entrypoints.push([outputPath, fileSize(key)]) + } else if (inputs.length > 0) { + // Naive implementation, we'll just grab the first input and hope it's accurate + manifest[stripPrefix(inputs[0])] = outputPath + } + } + + const manifestFolder = path.join(process.cwd(), ".bridgetown-cache", "frontend-bundling") + await fs.mkdir(manifestFolder, { recursive: true }) + await fs.writeFile(path.join(manifestFolder, "manifest.json"), JSON.stringify(manifest)) + + console.log("esbuild: frontend bundling complete!") + console.log("esbuild: entrypoints processed:") + entrypoints.forEach(entrypoint => { + const [entrypointName, entrypointSize] = entrypoint + console.log(` - ${entrypointName}: ${entrypointSize}`) + }) + }) + } +}) + +const bridgetownConfigured = (bridgetownConfig, outputFolder) => { + bridgetownConfig = {...autogeneratedBridgetownConfig, ...bridgetownConfig} + if (outputFolder) bridgetownConfig.destination = outputFolder + + return bridgetownConfig +} + +// Load the PostCSS config from postcss.config.js or whatever else is a supported location/format +const postcssrc = (await import("postcss-load-config")).default + +export default async (esbuildOptions, ...args) => { + let outputFolder; + if (typeof esbuildOptions === "string") { // legacy syntax where first argument is output folder + outputFolder = esbuildOptions + esbuildOptions = args[0] + } + const bridgetownConfig = bridgetownConfigured(esbuildOptions.bridgetownConfig, outputFolder) + + esbuildOptions.plugins = esbuildOptions.plugins || [] + // Add the PostCSS & glob plugins to the top of the plugin stack + const postCssConfig = await postcssrc() + esbuildOptions.plugins.unshift(importPostCssPlugin(postCssConfig, esbuildOptions.postCssPluginConfig || {})) + if (esbuildOptions.postCssPluginConfig) delete esbuildOptions.postCssPluginConfig + // Add the Glob plugin + esbuildOptions.plugins.unshift(importGlobPlugin(esbuildOptions.globOptions || {}, bridgetownConfig)) + if (esbuildOptions.globOptions) delete esbuildOptions.globOptions + // Add the Sass plugin + esbuildOptions.plugins.push(sassPlugin(esbuildOptions.sassOptions || {})) + if (esbuildOptions.sassOptions) delete esbuildOptions.sassOptions + // Add the Bridgetown preset + esbuildOptions.plugins.push(bridgetownPreset(bridgetownConfig)) + if (esbuildOptions.bridgetownConfig) delete esbuildOptions.bridgetownConfig + + const esbuild = (await import("esbuild")).default + const entryPoints = esbuildOptions.entryPoints || ["./frontend/javascript/index.js"] + if (esbuildOptions.entryPoints) delete esbuildOptions.entryPoints + + const islands = glob.sync(`./${bridgetownConfig.source}/${bridgetownConfig.islandsDir}/*.{js,js.rb}`).map(item => `./${item}`) + const islandsAsObject = islands.reduce((obj, str) => obj[str] = str, {}) + + esbuild.context({ + bundle: true, + loader: { + ".jpg": "file", + ".jpeg": "file", + ".png": "file", + ".gif": "file", + ".svg": "file", + ".avif": "file", + ".jxl": "file", + ".webp": "file", + ".woff": "file", + ".woff2": "file", + ".ttf": "file", + ".eot": "file", + }, + resolveExtensions: [".tsx", ".ts", ".jsx", ".js", ".css", ".scss", ".sass", ".json", ".js.rb"], + minify: process.argv.includes("--minify"), + sourcemap: true, + target: "es2020", + entryPoints: Array.isArray(entryPoints) ? [...entryPoints, ...islands] : {...entryPoints, ...islandsAsObject}, + entryNames: "[dir]/[name].[hash]", + outdir: path.join(process.cwd(), `${bridgetownConfig.destination}/_bridgetown/static`), + publicPath: "/_bridgetown/static", + metafile: true, + ...esbuildOptions, + }).then(context => { + if (process.argv.includes("--watch")) { + // Enable watch mode + context.watch() + } else { + // Build once and exit if not in watch mode + context.rebuild().then(result => { + context.dispose() + }) + } + process.on('SIGINT', () => process.exit()) + }).catch(() => process.exit(1)) +} diff --git a/test/fixtures/config/initializers.rb b/test/fixtures/config/initializers.rb index 8110ad2..f61f3ed 100644 --- a/test/fixtures/config/initializers.rb +++ b/test/fixtures/config/initializers.rb @@ -1,5 +1,16 @@ # frozen_string_literal: true +# The test suite loads the gem from test/helper.rb; bin/dev boots this site +# through the bridgetown CLI, so make sure the working-tree copy is loaded. +require_relative "../../../lib/bridgetown-stoa" + Bridgetown.configure do |config| init :"bridgetown-stoa", require_gem: false + + # Rebuild under bin/dev when the theme's own layouts change (they live + # outside this site's src/, so the watcher wouldn't see them otherwise). + # Fast refresh assumes changed paths are inside src/, so turn it off and + # let every change do a full (still instant) rebuild. + config.additional_watch_paths << File.expand_path("../../../layouts", __dir__) + config.fast_refresh = false end diff --git a/test/fixtures/esbuild.config.js b/test/fixtures/esbuild.config.js new file mode 100644 index 0000000..d45d834 --- /dev/null +++ b/test/fixtures/esbuild.config.js @@ -0,0 +1,44 @@ +import build from "./config/esbuild.defaults.js" + +// You can customize this as you wish, perhaps to add new esbuild plugins. +// +// ``` +// import { copy } from 'esbuild-plugin-copy' +// +// const esbuildOptions = { +// plugins: [ +// copy({ +// resolveFrom: 'cwd', +// assets: { +// from: ['./node_modules/somepackage/files/*')], +// to: ['./output/_bridgetown/somepackage/files')], +// }, +// verbose: false +// }), +// ] +// } +// ``` +// +// You can also support custom base_path deployments via changing `publicPath`. +// +// ``` +// const esbuildOptions = { +// publicPath: "/my_subfolder/_bridgetown/static", +// ... +// } +// ``` + +/** + * @typedef { import("esbuild").BuildOptions } BuildOptions + * @type {BuildOptions} + */ +const esbuildOptions = { + plugins: [ + // add new plugins here... + ], + globOptions: { + excludeFilter: /\.(dsd|lit)\.css$/ + } +} + +build(esbuildOptions) diff --git a/test/fixtures/frontend/javascript/index.js b/test/fixtures/frontend/javascript/index.js new file mode 100644 index 0000000..575e63f --- /dev/null +++ b/test/fixtures/frontend/javascript/index.js @@ -0,0 +1 @@ +import "../styles/index.css" diff --git a/test/fixtures/frontend/styles/index.css b/test/fixtures/frontend/styles/index.css new file mode 100644 index 0000000..bafc36b --- /dev/null +++ b/test/fixtures/frontend/styles/index.css @@ -0,0 +1,6 @@ +/* Mirrors what a host site's frontend/styles/index.css looks like per the + README, except the theme partial is pulled from this repo's working tree + instead of node_modules so edits show up live under bin/dev. */ +@import "tailwindcss"; +@import "../../../../frontend/styles/bridgetown-stoa.css"; +@source "../../../../layouts/**/*.serb"; diff --git a/test/fixtures/package.json b/test/fixtures/package.json new file mode 100644 index 0000000..25ab1b4 --- /dev/null +++ b/test/fixtures/package.json @@ -0,0 +1,21 @@ +{ + "name": "bridgetown-stoa-fixture", + "version": "0.0.0", + "type": "module", + "private": true, + "description": "Host site used by the test suite and by bin/dev to preview the theme.", + "scripts": { + "esbuild": "node esbuild.config.js --minify", + "esbuild-dev": "node esbuild.config.js --watch" + }, + "devDependencies": { + "@tailwindcss/postcss": "^4.0.0", + "esbuild": "^0.25.11", + "glob": "^11.0.3", + "postcss": "^8.5.6", + "postcss-import": "^16.1.0", + "postcss-load-config": "^6.0.1", + "read-cache": "^1.0.0", + "tailwindcss": "^4.0.0" + } +} diff --git a/test/fixtures/postcss.config.js b/test/fixtures/postcss.config.js new file mode 100644 index 0000000..e627111 --- /dev/null +++ b/test/fixtures/postcss.config.js @@ -0,0 +1,5 @@ +export default { + plugins: { + "@tailwindcss/postcss": {} + } +}