Skip to content
Open
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
1 change: 1 addition & 0 deletions docs/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@ This directory explains how the site behaves and how to work in it. It is writte
- **`views/`** — one file per page describing its behavior; maps to `src/web/pages/` and `tests/views/`.
- **`catalog.md`** — what the catalog is, how it's assembled, and how to change it.
- **`content.md`** — how to author prose: hero, commitment, about, per-repo overlays.
- **`content-collections.md`** — the generic loader for folders of markdown items (`content/<name>/*.md`).
- **`stewardship.md`** — tier definitions and how the health checks are evaluated.
- **`deployment.md`** — branch previews, production, the gh-pages layout, and the CNAME.
- **`testing.md`** — the TDD strategy, where tests live, and how to run each suite.
Expand Down
59 changes: 59 additions & 0 deletions docs/content-collections.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,59 @@
# Content collections

A content collection is a folder of markdown files, `content/<name>/<slug>.md`, each with YAML front-matter and an
optional markdown body. `src/build/collections.ts` loads and validates them so that a new kind of page (a project, a
note, an area) needs only a small schema and a page template, not another bespoke loader.

## Loading

```ts
import { loadCollection, type Fields } from './collections'

type Project = { title: string; stage: 'experiment' | 'supported'; people: string[] }

const parseProject = (f: Fields): Project => ({
title: f.string('title'),
stage: f.oneOf('stage', ['experiment', 'supported'] as const),
people: f.stringList('people'),
})

const projects = await loadCollection(rootDir, 'projects', parseProject)
// [{ slug: 'iml', data: { title, stage, people }, body: '…markdown…' }, …]
```

- **Slugs** are the file name without `.md`: lowercase letters, digits and hyphens. They become URLs, so treat them as
permanent.
- **A missing folder** is an empty collection, so a page type can ship before any content exists.
- **Items are sorted by slug.** Sort again by a field such as `order` or a date where the page needs it.
- **The body** is returned as markdown; the page renders it (for example with `marked`, as `ContentPage` does).

## Validation

`Fields` reads one item's front-matter. Each reader throws an error naming the file and the field, which fails the
build:

| Reader | Accepts |
|---|---|
| `string(f)` / `optionalString(f)` | a non-empty string / a string or nothing |
| `number(f, fallback?)` | a number |
| `boolean(f, fallback)` | `true` or `false` |
| `oneOf(f, values, fallback?)` | one of a fixed set of strings |
| `date(f)` / `optionalDate(f)` | a date written `YYYY-MM-DD` |
| `stringList(f)` | a list of strings (missing means empty) |
| `list(f, parse)` | a list of mappings, each parsed with its own `Fields` |

## References between items

When one item names another (a note naming its project, a project naming its area), check the names at build time:

```ts
import { assertRefs, refsOf } from './collections'

assertRefs(refsOf('notes', notes, 'project', (d) => d.project), projects.map((p) => p.slug), 'project')
```

`assertRefs` lists every broken reference in one error, so a single build run shows them all.

## Tests

`tests/build/collections.test.ts`, with fixtures in `tests/fixtures/collections/`.
11 changes: 11 additions & 0 deletions docs/deployment.md
Original file line number Diff line number Diff line change
Expand Up @@ -36,6 +36,17 @@ The environment entry itself persists in the Deployments sidebar. Deleting envir

`CNAME` at the source repo root contains `labs.flexion.us`. The build driver (`src/build/entry.tsx`) copies it into `dist/` on production builds only — preview subdirectories must not carry a CNAME.

## Preview builds are marked

Any build whose base path is not `/` is a branch preview (`isPreview` in `src/build/config.ts`). Every page of a
preview carries:

- `<meta name="robots" content="noindex, nofollow">`, so search engines don't index drafts, and
- a banner saying the page is a preview of proposed changes, linking to the live site (`src/design/components/preview-banner/`).

Production builds have neither. Previews are still public: anyone with the URL can open them, and the branch is
visible in this public repository.

## Base path

`SITE_BASE_URL` is the single knob that changes how internal links and asset URLs are emitted. The default is `/`. Any non-root value is normalized to `/path/`.
157 changes: 157 additions & 0 deletions src/build/collections.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,157 @@
import { parse as parseYaml } from 'yaml'
import { readdir } from 'node:fs/promises'
import { join } from 'node:path'

// A content collection is a folder of markdown files, content/<name>/<slug>.md,
// each with YAML front-matter. See docs/content-collections.md.

export type CollectionItem<T> = {
slug: string // file name without .md; stable, used in URLs
data: T // validated front-matter
body: string // markdown after the front-matter, trimmed
}

const FRONTMATTER_RE = /^---\n([\s\S]*?)\n---\n?/
const SLUG_RE = /^[a-z0-9][a-z0-9-]*$/

// Loads and validates every item in content/<name>/. A missing folder is an
// empty collection. Items are sorted by slug; callers re-sort as needed.
export async function loadCollection<T>(
rootDir: string,
name: string,
parse: (fields: Fields) => T,
): Promise<CollectionItem<T>[]> {
const dir = join(rootDir, 'content', name)
let files: string[]
try {
files = await readdir(dir)
} catch {
return []
}

const items: CollectionItem<T>[] = []
for (const file of files.sort()) {
if (!file.endsWith('.md')) continue
const slug = file.slice(0, -'.md'.length)
const where = `content/${name}/${file}`
if (!SLUG_RE.test(slug)) {
throw new Error(`${where}: file name must be lowercase letters, digits and hyphens`)
}
const raw = await Bun.file(join(dir, file)).text()
const match = raw.match(FRONTMATTER_RE)
if (!match) throw new Error(`${where}: missing YAML front-matter`)
const parsed = parseYaml(match[1]) ?? {}
if (typeof parsed !== 'object' || Array.isArray(parsed)) {
throw new Error(`${where}: front-matter must be a mapping`)
}
const data = parse(new Fields(where, parsed as Record<string, unknown>))
items.push({ slug, data, body: raw.slice(match[0].length).trim() })
}
return items
}

// Typed, error-reporting access to one item's front-matter.
export class Fields {
constructor(
readonly where: string,
readonly raw: Record<string, unknown>,
) {}

fail(field: string, message: string): never {
throw new Error(`${this.where}: "${field}" ${message}`)
}

string(field: string): string {
const v = this.raw[field]
if (typeof v !== 'string' || v.trim() === '') this.fail(field, 'is required and must be a string')
return v
}

optionalString(field: string): string | undefined {
const v = this.raw[field]
if (v === undefined || v === null) return undefined
if (typeof v !== 'string') this.fail(field, 'must be a string')
return v
}

number(field: string, fallback?: number): number {
const v = this.raw[field]
if (v === undefined && fallback !== undefined) return fallback
if (typeof v !== 'number') this.fail(field, 'is required and must be a number')
return v
}

boolean(field: string, fallback: boolean): boolean {
const v = this.raw[field]
if (v === undefined) return fallback
if (typeof v !== 'boolean') this.fail(field, 'must be true or false')
return v
}

oneOf<const V extends string>(field: string, values: readonly V[], fallback?: V): V {
const v = this.raw[field]
if (v === undefined && fallback !== undefined) return fallback
if (typeof v !== 'string' || !values.includes(v as V)) {
this.fail(field, `must be one of ${values.join(', ')}`)
}
return v as V
}

// A date written YYYY-MM-DD (the yaml package's default schema keeps it a string).
date(field: string): string {
const v = this.string(field)
if (!/^\d{4}-\d{2}-\d{2}$/.test(v)) this.fail(field, 'must be a date written YYYY-MM-DD')
return v
}

optionalDate(field: string): string | undefined {
return this.raw[field] === undefined ? undefined : this.date(field)
}

stringList(field: string): string[] {
const v = this.raw[field]
if (v === undefined || v === null) return []
if (!Array.isArray(v) || v.some((s) => typeof s !== 'string' || s === '')) {
this.fail(field, 'must be a list of strings')
}
return v as string[]
}

list<T>(field: string, parse: (item: Fields, index: number) => T): T[] {
const v = this.raw[field]
if (v === undefined || v === null) return []
if (!Array.isArray(v)) this.fail(field, 'must be a list')
return v.map((item, i) => {
if (!item || typeof item !== 'object' || Array.isArray(item)) {
this.fail(`${field}[${i}]`, 'must be a mapping')
}
return parse(new Fields(`${this.where} ${field}[${i}]`, item as Record<string, unknown>), i)
})
}
}

export type Ref = { from: string; field: string; to: string }

// Fails the build if any reference names an item that does not exist. Lists
// every broken reference at once so one build run shows them all.
export function assertRefs(refs: Ref[], known: Iterable<string>, targetLabel: string): void {
const names = new Set(known)
const broken = refs.filter((r) => !names.has(r.to))
if (broken.length === 0) return
const lines = broken.map((r) => ` ${r.from}: "${r.field}" names unknown ${targetLabel} "${r.to}"`)
throw new Error(`Broken references:\n${lines.join('\n')}`)
}

// Collects refs from every item of a collection.
export function refsOf<T>(
name: string,
items: CollectionItem<T>[],
field: string,
get: (data: T) => string[] | string | undefined,
): Ref[] {
return items.flatMap((item) => {
const v = get(item.data)
const targets = v === undefined ? [] : Array.isArray(v) ? v : [v]
return targets.map((to) => ({ from: `content/${name}/${item.slug}.md`, field, to }))
})
}
5 changes: 5 additions & 0 deletions src/build/config.ts
Original file line number Diff line number Diff line change
Expand Up @@ -20,3 +20,8 @@ export function createConfig(env: NodeJS.ProcessEnv = process.env): SiteConfig {
buildTime: new Date().toISOString(),
}
}

// A branch preview is any build served below the site root (see docs/deployment.md).
export function isPreview(config: Pick<SiteConfig, 'basePath'>): boolean {
return config.basePath !== '/'
}
6 changes: 5 additions & 1 deletion src/design/common/layout.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,8 @@ import type { Child } from 'hono/jsx'
import { raw } from 'hono/html'
import { Header } from '../components/header'
import { Footer } from '../components/footer'
import { url } from '../../build/config'
import { PreviewBanner } from '../components/preview-banner'
import { url, isPreview } from '../../build/config'
import type { SiteConfig } from '../../build/config'

export function Layout({
Expand All @@ -15,12 +16,14 @@ export function Layout({
children: Child
}) {
const documentTitle = title ? `${title} — Flexion Labs` : 'Flexion Labs'
const preview = isPreview(config)
return (
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1" />
<title>{documentTitle}</title>
{preview ? <meta name="robots" content="noindex, nofollow" /> : null}
<link rel="stylesheet" href={url('/design/index.css', config.basePath)} />
<link rel="icon" href={url('/assets/favicon-32x32.png', config.basePath)} sizes="32x32" type="image/png" />
<link rel="icon" href={url('/assets/favicon-192x192.png', config.basePath)} sizes="192x192" type="image/png" />
Expand All @@ -31,6 +34,7 @@ export function Layout({
</head>
<body>
<a href="#main" class="skip-link">Skip to main content</a>
{preview ? <PreviewBanner /> : null}
<Header config={config} />
<main id="main">{children}</main>
<Footer config={config} />
Expand Down
15 changes: 15 additions & 0 deletions src/design/components/preview-banner/examples.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,15 @@
import { PreviewBanner } from './index'

export function PreviewBannerExamples() {
return (
<section id="preview-banner">
<h2>Preview banner</h2>
<p>
Rendered by the layout at the top of every page when the build is a branch preview (any base path other
than <code>/</code>). Production never shows it. Preview builds also carry
<code>&lt;meta name="robots" content="noindex, nofollow"&gt;</code>.
</p>
<PreviewBanner />
</section>
)
}
11 changes: 11 additions & 0 deletions src/design/components/preview-banner/index.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,11 @@
// Shown at the top of every page on a branch preview build (see isPreview in
// src/build/config.ts). Production never renders it.
export function PreviewBanner() {
return (
<aside class="preview-banner" aria-label="Preview notice">
<p>
This is a preview of proposed changes, not the <a href="https://labs.flexion.us/">live site</a>.
</p>
</aside>
)
}
16 changes: 16 additions & 0 deletions src/design/components/preview-banner/styles.css
Original file line number Diff line number Diff line change
@@ -0,0 +1,16 @@
.preview-banner {
background: var(--color-butter);
color: var(--color-midnight);
padding: var(--space-2) var(--space-4);
font-size: var(--step--1);
text-align: center;

& p {
margin: 0;
max-inline-size: none;
}

& a {
color: var(--color-midnight);
}
}
1 change: 1 addition & 0 deletions src/design/index.css
Original file line number Diff line number Diff line change
Expand Up @@ -21,5 +21,6 @@
@import url("./components/sortable-table/styles.css") layer(components);
@import url("./components/copy-button/styles.css") layer(components);
@import url("./components/side-nav/styles.css") layer(components);
@import url("./components/preview-banner/styles.css") layer(components);
@import url("./common/content-page.css") layer(components);
@import url("./utilities.css") layer(utilities);
4 changes: 4 additions & 0 deletions src/design/layout.css
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,10 @@
grid-template-rows: auto auto 1fr auto;
min-block-size: 100vh;
}
/* Preview builds add a banner above the header; keep <main> on the growing row. */
body:has(> .preview-banner) {
grid-template-rows: auto auto auto 1fr auto;
}
body::before {
content: '';
display: block;
Expand Down
3 changes: 3 additions & 0 deletions src/pages/design-system.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,7 @@ import { SideNavExamples } from '../design/components/side-nav/examples'
import { CatalogFilterExamples } from '../design/components/catalog-filter/examples'
import { SortableTableExamples } from '../design/components/sortable-table/examples'
import { CopyButtonExamples } from '../design/components/copy-button/examples'
import { PreviewBannerExamples } from '../design/components/preview-banner/examples'

declare module 'hono/jsx' {
namespace JSX {
Expand Down Expand Up @@ -42,6 +43,7 @@ const NAV_ITEMS = [
{ href: '#catalog-filter', label: 'Catalog filter' },
{ href: '#sortable-table', label: 'Sortable table' },
{ href: '#copy-button', label: 'Copy button' },
{ href: '#preview-banner', label: 'Preview banner' },
]

export function DesignSystem({ config }: { config: SiteConfig }) {
Expand Down Expand Up @@ -81,6 +83,7 @@ export function DesignSystem({ config }: { config: SiteConfig }) {
<CatalogFilterExamples />
<SortableTableExamples />
<CopyButtonExamples />
<PreviewBannerExamples />
</div>
</div>
</Layout>
Expand Down
Loading
Loading