From a29f4b0cbcf278f43ee4b9715be05473d902ae98 Mon Sep 17 00:00:00 2001 From: bailey <74082460+bmjcoding@users.noreply.github.com> Date: Mon, 23 Nov 2026 15:29:32 -0600 Subject: [PATCH 01/23] The changelog tool: entry files, the freeze, the records and every output (DECISIONS 320, 3) tools/changelog reads changelog.config.json and .changes/.md (the only place a ticket id is read from), freezes a release into changelog/releases/.json after checking the version against its line and the highest bump among the entries, and generates CHANGELOG.md, the page's ReleaseRecord[] and a GitHub Release body from the records alone. audit.mjs runs the release-words audit's marked lines. Fixtures are two made-up projects, Slate and Harbor, built by running the tool over their histories. No dependency; nothing publishes a version of Basalt. Co-Authored-By: Claude Opus 5.5 --- package.json | 1 + scripts/test-all.mjs | 1 + tools/changelog/README.md | 142 +++++++ tools/changelog/audit.mjs | 151 ++++++++ tools/changelog/build.mjs | 97 +++++ tools/changelog/config.mjs | 127 +++++++ tools/changelog/entries.mjs | 197 ++++++++++ tools/changelog/fixtures/harbor/CHANGELOG.md | 89 +++++ .../fixtures/harbor/changelog.config.json | 16 + .../harbor/changelog/releases/1.3.0.json | 47 +++ .../harbor/changelog/releases/1.3.1.json | 68 ++++ .../harbor/changelog/releases/1.4.0.json | 121 ++++++ .../harbor/changelog/releases/1.4.1.json | 22 ++ .../harbor/changelog/releases/2.0.0-rc.1.json | 64 ++++ .../harbor/changelog/releases/2.0.0-rc.2.json | 31 ++ .../harbor/changelog/releases/2.0.0.json | 100 +++++ tools/changelog/fixtures/harbor/releases.json | 356 ++++++++++++++++++ tools/changelog/fixtures/make.mjs | 273 ++++++++++++++ .../fixtures/slate/.changes/pr53-1.md | 7 + .../fixtures/slate/.changes/pr54-1.md | 6 + tools/changelog/fixtures/slate/CHANGELOG.md | 58 +++ .../fixtures/slate/changelog.config.json | 33 ++ .../slate/changelog/releases/0.1.0.json | 6 + .../slate/changelog/releases/0.2.0.json | 307 +++++++++++++++ .../slate/changelog/releases/0.2.1.json | 22 ++ tools/changelog/fixtures/slate/releases.json | 341 +++++++++++++++++ tools/changelog/outputs.mjs | 87 +++++ tools/changelog/records.mjs | 153 ++++++++ tools/changelog/release.mjs | 167 ++++++++ tools/changelog/semver.mjs | 98 +++++ tools/changelog/test/audit.test.mjs | 97 +++++ tools/changelog/test/config.test.mjs | 81 ++++ tools/changelog/test/entries.test.mjs | 134 +++++++ tools/changelog/test/outputs.test.mjs | 138 +++++++ tools/changelog/test/release.test.mjs | 247 ++++++++++++ tools/changelog/test/support.mjs | 87 +++++ 36 files changed, 3972 insertions(+) create mode 100644 tools/changelog/README.md create mode 100644 tools/changelog/audit.mjs create mode 100644 tools/changelog/build.mjs create mode 100644 tools/changelog/config.mjs create mode 100644 tools/changelog/entries.mjs create mode 100644 tools/changelog/fixtures/harbor/CHANGELOG.md create mode 100644 tools/changelog/fixtures/harbor/changelog.config.json create mode 100644 tools/changelog/fixtures/harbor/changelog/releases/1.3.0.json create mode 100644 tools/changelog/fixtures/harbor/changelog/releases/1.3.1.json create mode 100644 tools/changelog/fixtures/harbor/changelog/releases/1.4.0.json create mode 100644 tools/changelog/fixtures/harbor/changelog/releases/1.4.1.json create mode 100644 tools/changelog/fixtures/harbor/changelog/releases/2.0.0-rc.1.json create mode 100644 tools/changelog/fixtures/harbor/changelog/releases/2.0.0-rc.2.json create mode 100644 tools/changelog/fixtures/harbor/changelog/releases/2.0.0.json create mode 100644 tools/changelog/fixtures/harbor/releases.json create mode 100644 tools/changelog/fixtures/make.mjs create mode 100644 tools/changelog/fixtures/slate/.changes/pr53-1.md create mode 100644 tools/changelog/fixtures/slate/.changes/pr54-1.md create mode 100644 tools/changelog/fixtures/slate/CHANGELOG.md create mode 100644 tools/changelog/fixtures/slate/changelog.config.json create mode 100644 tools/changelog/fixtures/slate/changelog/releases/0.1.0.json create mode 100644 tools/changelog/fixtures/slate/changelog/releases/0.2.0.json create mode 100644 tools/changelog/fixtures/slate/changelog/releases/0.2.1.json create mode 100644 tools/changelog/fixtures/slate/releases.json create mode 100644 tools/changelog/outputs.mjs create mode 100644 tools/changelog/records.mjs create mode 100644 tools/changelog/release.mjs create mode 100644 tools/changelog/semver.mjs create mode 100644 tools/changelog/test/audit.test.mjs create mode 100644 tools/changelog/test/config.test.mjs create mode 100644 tools/changelog/test/entries.test.mjs create mode 100644 tools/changelog/test/outputs.test.mjs create mode 100644 tools/changelog/test/release.test.mjs create mode 100644 tools/changelog/test/support.mjs diff --git a/package.json b/package.json index d2333be6..88640363 100644 --- a/package.json +++ b/package.json @@ -19,6 +19,7 @@ "ci:local": "node scripts/ci-local.mjs", "test:brand": "npm run build -w packages/tokens && node --test --test-timeout=120000 brand/test/*.test.mjs", "test:html-skill": "node --test --test-timeout=120000 tools/html-skill/test/*.test.mjs", + "test:changelog": "node --test --test-timeout=120000 tools/changelog/test/*.test.mjs", "test:sites": "node --test --test-timeout=120000 sites/test/*.test.mjs", "html-skill:shots": "node tools/html-skill/shoot.mjs" }, diff --git a/scripts/test-all.mjs b/scripts/test-all.mjs index 0f21b45e..8442020c 100644 --- a/scripts/test-all.mjs +++ b/scripts/test-all.mjs @@ -8,6 +8,7 @@ export const SUITES = [ { label: "html skill", command: "npm run test:html-skill" }, { label: "brand", command: "npm run test:brand" }, { label: "sites", command: "npm run test:sites" }, + { label: "changelog tool", command: "npm run test:changelog" }, ]; if (isMain(import.meta.url)) await runSteps(SUITES, { title: "npm test" }); diff --git a/tools/changelog/README.md b/tools/changelog/README.md new file mode 100644 index 00000000..6549814c --- /dev/null +++ b/tools/changelog/README.md @@ -0,0 +1,142 @@ +# The changelog tool + +Versions, changelogs and release notes for Basalt and for each of the owner's products (DECISIONS 320). One small file per change, written in +the pull request that makes it, frozen into a record when a release is cut, and generated into every output: `CHANGELOG.md`, the page's data +(the `ReleaseRecord[]` that `ReleaseNotes` takes), a GitHub Release's body and a page for the HTML skill. Node only, with no dependency. + +The words follow `.agent/skills/release-words/SKILL.md`. The page's parts are `VersionLink`, `ReleaseNotes` and `ReleaseIndex` in +`@srasyndicate/basalt`, and the `release` module in the HTML skill. + +Nothing here publishes a version of Basalt. Basalt's first release is the owner's to cut (DECISIONS 320, backlog 1); until then the repository +has no `changelog.config.json`, no `.changes` and no records. `fixtures/` holds two made-up projects, Slate (a package) and Harbor (a product). + +## Versions + +SemVer 2.0.0, shown with the ship date: `1.4.0 · Nov 23, 2026` on a page, `## 1.4.0 - 2026-11-23` in Markdown, `v1.4.0` as a tag and +`#v1.4.0` as a release's address. Build metadata (`1.4.0+9f3c1e2`) is never part of a release's version; the running build is the app's to +show (Build details). + +| Bump | A package | A product | +|---|---|---| +| Major | Removing or renaming a token, component, prop, CSS variable or documented data attribute; changing a token's `$type` or a prop's type; making an optional prop required; raising the minimum React, Node or browser; changing a default that alters behavior | It takes away or reshapes something people rely on, or they must act for it to keep working | +| Minor | New tokens, components, props or variants; deprecations; a token's value changing while its role holds | Something a person can newly do; a dated notice that something will go | +| Patch | Fixes; accessibility fixes that restore documented behavior; docs and types that were wrong | Fixes and improvements to what exists | + +**In 0.x the numbers move one place right:** a breaking change raises the minor, and everything else raises the patch. A caret range +(`^0.2.0`) then takes additions and fixes and never a break. Basalt stays in 0.x until its public API is written down; 1.0.0 is the owner's +call. The two packages share one version number. + +**A line** is the versions that share their breaking number: the major, or in 0.x the minor. A new version must be higher than every release +in its line; one that opens a line must be higher than every release there is. A fix to a maintained older line (1.4.1 after 2.0.0) is frozen +on that line's branch (`release/1.x`) and its record is then added to the default branch by a pull request, because the page is built there. + +**Pre-releases** are `-beta.N` and `-rc.N`, each frozen with its own record holding what no earlier pre-release of that version holds. Freezing +one removes nothing. The stable version takes every pending file, names the pre-releases it `replaces`, and from then they are drawn in no +output and their addresses open the stable release. A canary (`1.5.0-canary.20261123.1`) is a build from the default branch with no freeze +and no record. + +## An entry + +One file per change, `.changes/.md`, added by the pull request that makes the change: + +```md +--- +type: changed +area: FormGrid +pr: 120 +author: bailey +tickets: [ENG-398, PROJ-88] +bump: major +action: true +migration: docs/migrating.md#formgrid-frame +--- +Changed the parent layout item for `FormGrid` to `.basalt-form-grid-frame`, where existing sizing rules must move +``` + +- **The id** is the file's name, set once and never changed or reused: `pr120-1` (the pull request and the entry's number in it), or any + `a-z0-9-` slug for a change with no pull request. `pr120-1.md` must say `pr: 120`. `unreleased` and anything starting `v` and a digit are + reserved. A backport is its own pull request and its own entry. +- **The head** is `key: value` lines between two `---`. It is not YAML. An unknown key, a key written twice or a line that is not `key: value` + stops the tool, naming the file and the line. + +| Key | Value | +|---|---| +| `type` | `security`, `deprecated`, `removed`, `added`, `changed` or `fixed`. Required | +| `area` | The component, `Tokens`, or a product's page (`Home`), drawn before the sentence. On every entry when a project has more than one surface | +| `pr` | The pull request's number | +| `author` | A key of the config's `people`: the person who wrote the entry's words, or who has said they take authorship of them. Optional. Never who asked for the change, approved it or merged it | +| `tickets` | A list in square brackets, in the order written. **The only place a ticket id is read from**: never a pull request's body, a commit's trailer, a branch name, a title or a sentence | +| `bump` | `major`, `minor` or `patch`. Required for `changed`; otherwise only to raise the type's floor, never to lower it | +| `action` | `true` when a reader must do something: it stands under "Action needed". It raises no number. A `major` entry is always `action` | +| `migration` | The migration note: a file in the repository (opened at the release's tag), a path from the site's root, or an `https` address. Drawn as "How to migrate" | + +Each type's least bump: Removed is major; Added and Deprecated are minor; Fixed and Security are patch; Changed states its own. + +**Release notes** are one more file, `.changes/release.md`, when a release has them: a head with `title` and `summary`, then a paragraph for +everyone with no heading and a `## For admins` heading for each audience, each paragraph opening with a `covers:` line naming the entries it +is about. A paragraph that covers none, or names an entry the release does not hold, stops the tool. + +```md +--- +title: A monitor can open an incident room +summary: Monitors can open incident rooms through a webhook, and Home marks the incidents they open. +--- +covers: [pr131-1] +A monitor that can send a webhook can now open an incident room when its alarm fires. + +## For admins +covers: [pr131-1] +In Settings, open Integrations and add a webhook. Paste its address into your monitor. +``` + +A release with no entries must have a summary, and so must one of more than three changes, unless paragraphs lead it. + +## The config + +`changelog.config.json`, at the repository's root: + +```json +{ + "product": "Basalt", + "repository": "https://github.com/example/basalt", + "trackers": [ + { "name": "Linear", "pattern": "(?:ENG|DES)-[1-9][0-9]*", "url": "https://linear.app/example/issue/{id}" }, + { "name": "Jira", "pattern": "PROJ-[1-9][0-9]*", "url": "https://example.atlassian.net/browse/{id}", "show": "text" }, + { "name": "GitHub", "pattern": "basalt#(?[1-9][0-9]*)", "url": "https://github.com/example/basalt/issues/{n}", "label": "issue #{n}" } + ], + "people": { "bailey": { "name": "Bailey Jones" } } +} +``` + +- `name` is the word shown, and is unique. `pattern` is matched against the whole id: write it without `^` and `$`, name team keys and never + a catch-all, and write a number as `[1-9][0-9]*`. +- `url` and `label` may use `{id}` and the pattern's named groups; any other variable is refused. Each value is percent-encoded into the URL, + which must be `https` with no variable in its host. +- `show` is `link` (the default), `text` (shown, not linked) or `none` (recorded, never published). +- A GitHub issue is written `repo#45`, never `#45`, which is a pull request. +- Whether a ticket exists in its tracker is not checked here; a project may check it in CI. + +## Commands + +| Command | What it does | +|---|---| +| `node tools/changelog/release.mjs --date ` | Freezes a release on the branch it is cut from. Checks every pending file, the version against its line and the highest bump among the entries, and each entry's commit (the first-parent commit that added its file; a shallow clone is refused). Writes `changelog/releases/.json` once; for a stable version removes the pending files and `release.md`. Regenerates `CHANGELOG.md` | +| `node tools/changelog/build.mjs` | Regenerates `CHANGELOG.md` from the records and the pending files (the Unreleased section is what no pre-release holds) | +| `node tools/changelog/build.mjs --json ` | Writes the page's data | +| `node tools/changelog/build.mjs --github ` | Prints a GitHub Release's body | +| `node tools/changelog/build.mjs --check` | Fails when `CHANGELOG.md` is not what the records give, or a tagged record differs from its tag's copy | +| `node tools/changelog/audit.mjs` | Runs the lines of the release-words audit marked (m). It flags and a person decides | +| `node tools/changelog/fixtures/make.mjs` | Rebuilds the two made-up fixtures by running the tool over their histories | +| `node tools/changelog/skill-body.mjs --form ` | Writes a body for the HTML skill's `release` module from the records | + +Every option takes `--root `; the default is the working directory. Every output is generated from the records and the pending +files and nothing else: a rebuild needs no git and no network, and a later config change cannot re-point a frozen release. + +## Why not changesets + +The owner's standard names changesets (S 4.1). The idea it wants from them is kept: one small file per change, written in the pull request, +generated into every output. The format is not. A changeset's head maps package names to a bump (`"@scope/pkg": minor`); its generated +`CHANGELOG.md` is headed by bump (`### Major Changes`, `### Minor Changes`, `### Patch Changes`), not by type. The GitHub changelog formatter +(`@changesets/changelog-github`) accepts overrides for `pr`, `commit` and `author` under a `_:` key, but there is no field for a type, tickets, +`action` or a permanent id, and an author there is a GitHub login. Checked against `docs/guide/writing-changesets.md` and +`packages/apply-release-plan/src/get-changelog-entry.ts` in `changesets/changesets` on Nov 23, 2026. diff --git a/tools/changelog/audit.mjs b/tools/changelog/audit.mjs new file mode 100644 index 00000000..deca44ad --- /dev/null +++ b/tools/changelog/audit.mjs @@ -0,0 +1,151 @@ +// The audit's marked lines (DECISIONS 320, 4; `.agent/skills/release-words/SKILL.md`, "The audit"): node tools/changelog/audit.mjs [--root ] +// It flags, and a person decides: the check showed that neither accepting nor dismissing every flag is right. Each flag is a rule id, the +// quoted line and what is wrong. The lines the skill does not mark are read by a person. +import fs from "node:fs"; +import path from "node:path"; + +import { taggedDifferences } from "./build.mjs"; +import { loadConfig } from "./config.mjs"; +import { CHANGES_DIR, FLOOR, NOTES_FILE, readEntry, readNotes, TYPES } from "./entries.mjs"; +import { changelogMarkdown } from "./outputs.mjs"; +import { pageReleases, readRecords } from "./records.mjs"; +import { atLeast, carries, higher, must } from "./semver.mjs"; + +export const VERBS = ["Added", "Changed", "Improved", "Deprecated", "Removed", "Fixed", "Reverted"]; +export const MAX_WORDS = 30; + +// R9: stock phrases that say nothing a reader can check. +const STOCK = [/\bbug fixes\b/i, /\bperformance improvements\b/i, /\bvarious (?:fixes|improvements)\b/i, /\bminor (?:fixes|improvements)\b/i, /\bgeneral improvements\b/i, /\bstability improvements\b/i]; +// R10: marketing words. +const BANNED = ["seamless", "seamlessly", "powerful", "robust", "effortless", "effortlessly", "blazing", "revolutionary", "game-changing", "cutting-edge", "best-in-class", "world-class", "delightful", "beautiful", "stunning", "magical", "supercharge", "supercharged"]; +// R15: British spellings, in prose (an identifier is spelled as it is exported). +const BRITISH = /\b(?:(?:multi-?)?colour(?:s|ed|ing|ful)?|centre(?:s|d)?|behaviour(?:s|al)?|cancell(?:ed|ing)|favour(?:s|ed|ite|ites)?|honour(?:s|ed)?|neighbour(?:s|ing)?|labour|organis(?:e|ed|es|ing|ation)|recognis(?:e|ed|es|ing)|optimis(?:e|ed|es|ing|ation)|customis(?:e|ed|es|ing|ation)|initialis(?:e|ed|es|ing|ation)|normalis(?:e|ed|es|ing|ation)|serialis(?:e|ed|es|ing|ation)|summaris(?:e|ed|es|ing)|licence|catalogue|dialogue|analys(?:e|ed|es|ing)|grey|programme|travell(?:ed|ing)|modell(?:ed|ing)|labell(?:ed|ing)|fulfil)\b/i; +const FUTURE = /\b(?:will|shall|going to|won't)\b/i; + +/** The sentence's prose: code spans taken out, since an identifier is written as it is exported. */ +const prose = (text) => text.replace(/`[^`]*`/g, "`code`"); + +/** + * Flags for one entry's words and fields. `config` gives the trackers and the people, so an id or a name in the words is caught. + * Each flag is `{ rule, message }`. + */ +export function auditEntry(entry, config) { + const flags = []; + const flag = (rule, message) => flags.push({ rule, message }); + const text = entry.text; + const words = prose(text); + + const [first] = text.split(/\s+/); + if (!VERBS.includes(first)) flag("R1", `starts with "${first}", not a verb of R1 (${VERBS.join(", ")})`); + const count = text.trim().split(/\s+/).length; + if (count > MAX_WORDS) flag("R3", `${count} words; at most ${MAX_WORDS}`); + if (/[.]$/.test(text.trim())) flag("R3", "ends with a period"); + for (const pattern of STOCK) if (pattern.test(words)) flag("R9", `a stock phrase ("${words.match(pattern)[0]}")`); + for (const word of BANNED) if (new RegExp(`\\b${word}\\b`, "i").test(words)) flag("R10", `a marketing word ("${word}")`); + if (words.includes("!")) flag("R10", "an exclamation mark"); + if (words.includes("—")) flag("R15", "an em dash"); + if (words.includes(";")) flag("R15", "a semicolon"); + if (/\p{Extended_Pictographic}/u.test(words)) flag("R15", "an emoji"); + const british = words.match(BRITISH); + if (british) flag("R15", `a British spelling ("${british[0]}")`); + // A dated removal is the one place for the future tense: a deprecation or removal that names a year. + const datedRemoval = ["deprecated", "removed"].includes(entry.type) && /\b20[0-9]{2}\b/.test(text); + if (FUTURE.test(words) && !datedRemoval) flag("R11", `the future tense ("${words.match(FUTURE)[0]}") outside a dated removal`); + if (/(?:^|[^\w`])#[0-9]+\b/.test(text) || /\b(?:PR|pull request)\s*#?[0-9]+\b/i.test(text)) flag("R14", "a pull request number in the words"); + for (const tracker of config?.trackers ?? []) { + const anywhere = new RegExp(`(? flags.push({ rule, message }); + const version = must(record.version); + if (version.pre.length && !["canary", "beta", "rc"].includes(version.pre[0])) flag("Version", `the pre-release "${record.version}" is not -canary, -beta or -rc`); + if (record.previous) { + const needed = record.entries.reduce((most, entry) => higher(most, entry.bump ?? "patch"), "patch"); + const carried = carries(record.previous, version.core); + if (record.entries.length && (!carried || !atLeast(carried, needed))) flag("Version", `${record.version} from ${record.previous} does not carry the ${needed} its entries need`); + } + for (const replaced of record.replaces ?? []) { + const candidate = records.find((other) => other.version === replaced); + if (!candidate) { + flag("Version", `replaces ${replaced}, which has no record`); + continue; + } + const ids = new Set(record.entries.map((entry) => entry.id)); + for (const entry of candidate.entries) if (!ids.has(entry.id)) flag("Version", `${replaced} held "${entry.id}", which ${record.version} does not: was it taken out on purpose?`); + } + for (const audience of record.audiences ?? []) if (!audience.covers?.length) flag("R18", `a paragraph covers no entry: "${audience.text}"`); + return flags; +} + +/** Every flag in a repository: the pending files, the records, CHANGELOG.md and the tags. Each is `{ where, rule, line, message }`. */ +export function audit(root) { + const flags = []; + const config = loadConfig(root); + const records = readRecords(root); + const pending = []; + const dir = path.join(root, CHANGES_DIR); + const names = fs.existsSync(dir) ? fs.readdirSync(dir).filter((name) => name.endsWith(".md") && name !== NOTES_FILE && name !== "README.md").sort() : []; + for (const name of names) { + const file = path.join(CHANGES_DIR, name); + try { + pending.push({ file, entry: readEntry(fs.readFileSync(path.join(root, file), "utf8"), file, config) }); + } catch (error) { + flags.push({ where: file, rule: "Each entry", line: "", message: error.message }); + } + } + const notesFile = path.join(dir, NOTES_FILE); + if (fs.existsSync(notesFile)) { + try { + readNotes(fs.readFileSync(notesFile, "utf8"), path.join(CHANGES_DIR, NOTES_FILE), new Set(pending.map(({ entry }) => entry.id))); + } catch (error) { + flags.push({ where: path.join(CHANGES_DIR, NOTES_FILE), rule: "R18", line: "", message: error.message }); + } + } + const all = [...pending.map(({ file, entry }) => ({ where: file, entry })), ...records.flatMap((record) => record.entries.map((entry) => ({ where: `${record.version} ${entry.id}`, entry })))]; + for (const { where, entry } of all) for (const found of auditEntry(entry, config)) flags.push({ where, line: entry.text, ...found }); + // An area on every entry when the package or product has more than one surface: when any entry has one, every entry does. + if (all.some(({ entry }) => entry.area)) for (const { where, entry } of all) if (!entry.area) flags.push({ where, rule: "Structure", line: entry.text, message: "no area, where other entries have one" }); + for (const record of records) for (const found of auditRecord(record, records)) flags.push({ where: record.version, line: "", ...found }); + for (const entry of all) if (!TYPES.includes(entry.entry.type)) flags.push({ where: entry.where, rule: "Structure", line: entry.entry.text, message: `type "${entry.entry.type}"` }); + const changelog = path.join(root, "CHANGELOG.md"); + if (fs.existsSync(changelog) && records.length) { + const expected = changelogMarkdown(pageReleases(root, { config, records, pending: pending.map(({ entry }) => entry) }), { product: config.product }); + if (fs.readFileSync(changelog, "utf8") !== expected) flags.push({ where: "CHANGELOG.md", rule: "Structure", line: "", message: "is not what the records give: run node tools/changelog/build.mjs" }); + } + for (const difference of taggedDifferences(root)) flags.push({ where: "records", rule: "Version", line: "", message: difference }); + return flags; +} + +/** A flag as the skill logs it: rule id, quoted line, what to look at. */ +export const formatFlag = (flag) => `${flag.rule}, ${flag.where}${flag.line ? `, "${flag.line}"` : ""}: ${flag.message}`; + +const { isMain } = await import("../../scripts/is-main.mjs"); +if (isMain(import.meta.url)) { + const args = process.argv.slice(2); + const at = args.indexOf("--root"); + const root = path.resolve(at >= 0 ? args[at + 1] : process.cwd()); + try { + const flags = audit(root); + for (const flag of flags) process.stdout.write(`${formatFlag(flag)}\n`); + process.stdout.write(flags.length ? `${flags.length} ${flags.length === 1 ? "flag" : "flags"}: a person decides each.\n` : "No flags.\n"); + process.exit(flags.length ? 1 : 0); + } catch (error) { + process.stderr.write(`${error.message}\n`); + process.exit(1); + } +} diff --git a/tools/changelog/build.mjs b/tools/changelog/build.mjs new file mode 100644 index 00000000..9d70c1bd --- /dev/null +++ b/tools/changelog/build.mjs @@ -0,0 +1,97 @@ +// The outputs, from the records and the pending files alone (DECISIONS 320, 3.4): +// node tools/changelog/build.mjs regenerate CHANGELOG.md +// node tools/changelog/build.mjs --json the page's data, the ReleaseRecord[] that ReleaseNotes takes +// node tools/changelog/build.mjs --github a GitHub Release's body, on stdout +// node tools/changelog/build.mjs --check CHANGELOG.md is what the records give, and every tagged record matches its tag +// Option: --root (default the working directory). +// No network and no git, except --check reading the tags. +import { execFileSync } from "node:child_process"; +import fs from "node:fs"; +import path from "node:path"; + +import { loadConfig } from "./config.mjs"; +import { changelogMarkdown, githubBody } from "./outputs.mjs"; +import { pageReleases, readRecords, RECORDS_DIR } from "./records.mjs"; + +/** Every output for a repository, as strings, from its records and pending files. */ +export function outputs(root) { + const config = loadConfig(root); + const releases = pageReleases(root, { config }); + return { + config, + releases, + changelog: changelogMarkdown(releases, { product: config.product }), + json: `${JSON.stringify(releases, null, 2)}\n`, + github: (version) => { + const release = releases.find((candidate) => candidate.version === version); + if (!release) throw new Error(`${version} is not a drawn release`); + return githubBody(release, { repository: config.repository }); + }, + }; +} + +/** + * A published version is never edited (S 3.2.10): every record whose tag exists must equal the tag's copy, byte for byte. Returns the + * differences, each a sentence; empty when every tagged record matches. + */ +export function taggedDifferences(root) { + const differences = []; + for (const record of readRecords(root)) { + const tag = `v${record.version}`; + const file = `${RECORDS_DIR.split(path.sep).join("/")}/${record.version}.json`; + let tagged; + try { + execFileSync("git", ["rev-parse", "--verify", "--quiet", `refs/tags/${tag}`], { cwd: root, stdio: "ignore" }); + } catch { + continue; + } + try { + tagged = execFileSync("git", ["show", `${tag}:${file}`], { cwd: root, encoding: "utf8", stdio: ["ignore", "pipe", "ignore"] }); + } catch { + differences.push(`${file}: the tag ${tag} holds no record`); + continue; + } + if (tagged !== fs.readFileSync(path.join(root, file), "utf8")) differences.push(`${file} differs from the copy tagged ${tag}; a published version is never edited`); + } + return differences; +} + +function main(argv) { + const args = [...argv]; + const take = (flag, hasValue = true) => { + const at = args.indexOf(flag); + if (at < 0) return undefined; + return hasValue ? args.splice(at, 2)[1] : (args.splice(at, 1), true); + }; + const root = path.resolve(take("--root") ?? process.cwd()); + const json = take("--json"); + const github = take("--github"); + const check = take("--check", false); + const out = outputs(root); + if (check) { + const problems = taggedDifferences(root); + const file = path.join(root, "CHANGELOG.md"); + if (!fs.existsSync(file) || fs.readFileSync(file, "utf8") !== out.changelog) problems.push("CHANGELOG.md is not what the records give: run node tools/changelog/build.mjs"); + for (const problem of problems) process.stderr.write(`${problem}\n`); + process.exit(problems.length ? 1 : 0); + } + if (github) { + process.stdout.write(out.github(github)); + return; + } + if (json) { + fs.writeFileSync(path.resolve(json), out.json); + return; + } + fs.writeFileSync(path.join(root, "CHANGELOG.md"), out.changelog); +} + +const { isMain } = await import("../../scripts/is-main.mjs"); +if (isMain(import.meta.url)) { + try { + main(process.argv.slice(2)); + } catch (error) { + process.stderr.write(`${error.message}\n`); + process.exit(1); + } +} diff --git a/tools/changelog/config.mjs b/tools/changelog/config.mjs new file mode 100644 index 00000000..ff9e88d4 --- /dev/null +++ b/tools/changelog/config.mjs @@ -0,0 +1,127 @@ +// `changelog.config.json`: the product, its repository, its trackers and its people (DECISIONS 320, 3.2). Read and checked before any entry. +import fs from "node:fs"; +import path from "node:path"; + +export const CONFIG_FILE = "changelog.config.json"; + +const VARIABLE = /\{([A-Za-z][A-Za-z0-9]*)\}/g; +const TRACKER_KEYS = ["name", "pattern", "url", "label", "show"]; +const TOP_KEYS = ["product", "repository", "trackers", "people"]; +const PERSON_KEYS = ["name"]; +export const SHOWS = ["link", "text", "none"]; + +const fail = (where, message) => { throw new Error(`${CONFIG_FILE}: ${where}: ${message}`); }; + +function checkHttps(where, url) { + if (!/^https:\/\//.test(url)) fail(where, `"${url}" must be https`); + // The variables go after the host only: in the path, the query or the fragment. + if (!/^https:\/\/[^/?#{}]+(?:[/?#]|$)/.test(url)) fail(where, `"${url}" holds a variable in its host`); + try { + new URL(url.replace(VARIABLE, "x")); + } catch { + fail(where, `"${url}" is not a URL`); + } +} + +/** + * Check a parsed config and return it ready to use: each tracker's pattern compiled to match the whole id. Stops on the first fault, naming it. + */ +export function readConfig(raw) { + if (!raw || typeof raw !== "object" || Array.isArray(raw)) fail("the file", "is not a JSON object"); + for (const key of Object.keys(raw)) if (!TOP_KEYS.includes(key)) fail("the file", `unknown key "${key}"`); + if (typeof raw.product !== "string" || !raw.product.trim()) fail("product", "is the product's name, and is required"); + if (typeof raw.repository !== "string") fail("repository", "is the repository's https address, and is required"); + if (/[{}]/.test(raw.repository)) fail("repository", "holds no variable"); + checkHttps("repository", raw.repository); + const repository = raw.repository.replace(/\/+$/, ""); + + const names = new Set(); + const trackers = (raw.trackers ?? []).map((tracker, index) => { + const at = `trackers[${index}]`; + if (!tracker || typeof tracker !== "object") fail(at, "is not an object"); + for (const key of Object.keys(tracker)) if (!TRACKER_KEYS.includes(key)) fail(at, `unknown key "${key}"`); + const { name, pattern, url, label } = tracker; + const show = tracker.show ?? "link"; + if (typeof name !== "string" || !name.trim()) fail(at, `"name" is the word shown, and is required`); + if (names.has(name)) fail(at, `the name "${name}" is used twice`); + names.add(name); + const where = `${at} (${name})`; + if (typeof pattern !== "string" || !pattern) fail(where, `"pattern" is required`); + if (pattern.startsWith("^") || pattern.endsWith("$")) fail(where, `write the pattern without ^ and $: it is matched against the whole id`); + let regexp; + try { + regexp = new RegExp(`^(?:${pattern})$`, "u"); + } catch (error) { + fail(where, `the pattern does not compile: ${error.message}`); + } + const groups = new Set([...pattern.matchAll(/\(\?<([A-Za-z][A-Za-z0-9]*)>/g)].map((match) => match[1])); + for (const [field, template] of [["url", url], ["label", label]]) { + if (template === undefined) continue; + if (typeof template !== "string") fail(where, `"${field}" is a string`); + for (const [, variable] of template.matchAll(VARIABLE)) { + if (variable !== "id" && !groups.has(variable)) fail(where, `"{${variable}}" in "${field}" is neither {id} nor a named group of the pattern`); + } + if (/[{}]/.test(template.replace(VARIABLE, ""))) fail(where, `"${field}" holds a brace that is not a variable`); + } + if (!SHOWS.includes(show)) fail(where, `"show" is link, text or none`); + if (show === "link" && url === undefined) fail(where, `a linked tracker needs "url"`); + if (url !== undefined) checkHttps(where, url); + return { name, pattern, regexp, url: url ?? null, label: label ?? null, show }; + }); + + const people = {}; + for (const [key, person] of Object.entries(raw.people ?? {})) { + if (!/^[a-z0-9][a-z0-9-]*$/.test(key)) fail(`people.${key}`, "a person's key is lowercase letters, digits and hyphens"); + if (!person || typeof person !== "object") fail(`people.${key}`, "is not an object"); + for (const field of Object.keys(person)) if (!PERSON_KEYS.includes(field)) fail(`people.${key}`, `unknown key "${field}"`); + if (typeof person.name !== "string" || !person.name.trim()) fail(`people.${key}`, `"name" is required`); + people[key] = { name: person.name }; + } + + return { product: raw.product, repository, trackers, people }; +} + +/** Read and check the config at a repository's root. */ +export function loadConfig(root) { + const file = path.join(root, CONFIG_FILE); + let text; + try { + text = fs.readFileSync(file, "utf8"); + } catch { + throw new Error(`${CONFIG_FILE}: not found at ${root}`); + } + let raw; + try { + raw = JSON.parse(text); + } catch (error) { + throw new Error(`${CONFIG_FILE}: not JSON: ${error.message}`); + } + return readConfig(raw); +} + +/** + * One ticket id, resolved against every tracker: exactly one must match the whole id. `where` names the file. The result is what a frozen + * release keeps, so a later config change cannot re-point it. + */ +export function resolveTicket(id, config, where) { + const hits = config.trackers.map((tracker) => ({ tracker, match: tracker.regexp.exec(id) })).filter((hit) => hit.match); + const names = config.trackers.map((tracker) => tracker.name).join(", ") || "none configured"; + if (hits.length === 0) throw new Error(`${where}: ticket "${id}" matches no tracker (${names})`); + if (hits.length > 1) throw new Error(`${where}: ticket "${id}" matches ${hits.length} trackers (${hits.map((hit) => hit.tracker.name).join(", ")})`); + const [{ tracker, match }] = hits; + const values = { id, ...(match.groups ?? {}) }; + const fill = (template, encode) => template.replace(VARIABLE, (_, name) => (encode ? encodeURIComponent(values[name]) : values[name])); + const ticket = { tracker: tracker.name, id, label: tracker.label ? fill(tracker.label, false) : id, show: tracker.show }; + if (tracker.show === "link") ticket.href = fill(tracker.url, true); + return ticket; +} + +/** A person's name from their key, or a stop naming the file. */ +export function resolvePerson(key, config, where) { + const person = config.people[key]; + if (!person) throw new Error(`${where}: author "${key}" is not a key of the config's "people" (${Object.keys(config.people).join(", ") || "none"})`); + return person.name; +} + +export const pullHref = (config, number) => `${config.repository}/pull/${number}`; +export const commitHref = (config, sha) => `${config.repository}/commit/${sha}`; diff --git a/tools/changelog/entries.mjs b/tools/changelog/entries.mjs new file mode 100644 index 00000000..5b238373 --- /dev/null +++ b/tools/changelog/entries.mjs @@ -0,0 +1,197 @@ +// The entry files (DECISIONS 320, 3.3 and 3.4): `.changes/.md`, one per change, added by the pull request that makes it. The head is +// `key: value` lines between two `---`, read here and nowhere else: a ticket id is read only from the `tickets` field of the entry's own file, +// never from a pull request's body, a commit's trailer, a branch name, a title or a sentence. It is not YAML, and no parser is added. +import fs from "node:fs"; +import path from "node:path"; + +import { resolvePerson, resolveTicket } from "./config.mjs"; +import { atLeast, BUMPS } from "./semver.mjs"; + +export const CHANGES_DIR = ".changes"; +export const NOTES_FILE = "release.md"; + +/** The sections, in the order every output draws them (2.7). "Action needed" stands above them all and is not a type. */ +export const TYPES = ["security", "deprecated", "removed", "added", "changed", "fixed"]; + +/** The least bump of each type; Changed has none and states its own (1.1). */ +export const FLOOR = { removed: "major", added: "minor", deprecated: "minor", fixed: "patch", security: "patch", changed: null }; + +const KEYS = ["type", "area", "pr", "author", "tickets", "bump", "action", "migration"]; +const ID = /^[a-z0-9][a-z0-9-]*$/; + +/** Whether an id is reserved for a release's address: "unreleased", and anything that starts with a v and a digit (2.10). */ +export const reservedId = (id) => id === "unreleased" || /^v[0-9]/.test(id); + +/** The `key: value` lines between two `---` at the top of a file. Returns the head (with each key's line number) and the body's lines. */ +export function readHead(source, file, keys) { + const lines = source.replace(/\r\n?/g, "\n").split("\n"); + if (lines[0] !== "---") throw new Error(`${file}:1: the file starts with "---"`); + const end = lines.indexOf("---", 1); + if (end < 0) throw new Error(`${file}: the head is not closed with "---"`); + const head = {}; + const at = {}; + for (let index = 1; index < end; index++) { + const line = lines[index]; + const match = /^([a-z]+): ?(.*)$/.exec(line); + if (!match) throw new Error(`${file}:${index + 1}: not a "key: value" line: ${JSON.stringify(line)}`); + const [, key, value] = match; + if (!keys.includes(key)) throw new Error(`${file}:${index + 1}: unknown key "${key}" (the keys are ${keys.join(", ")})`); + if (key in head) throw new Error(`${file}:${index + 1}: "${key}" is written twice`); + head[key] = value.trim(); + at[key] = index + 1; + } + return { head, at, body: lines.slice(end + 1), bodyLine: end + 2 }; +} + +/** A list in square brackets: `[ENG-398, PROJ-88]`. Items are trimmed; an empty item, a space inside one or an item listed twice stops. */ +export function readList(value, where, what) { + const list = /^\[(.*)\]$/.exec(value); + if (!list) throw new Error(`${where}: "${what}" is a list in square brackets, such as [ENG-398, PROJ-88]`); + if (list[1].trim() === "") return []; + const items = list[1].split(",").map((item) => item.trim()); + const seen = new Set(); + for (const item of items) { + if (item === "") throw new Error(`${where}: "${what}" has an empty item (a comma with nothing after it)`); + if (/\s/.test(item)) throw new Error(`${where}: "${item}" in "${what}" holds a space`); + if (seen.has(item)) throw new Error(`${where}: "${item}" is listed twice in "${what}"`); + seen.add(item); + } + return items; +} + +/** + * Read one entry file. `file` is its path as shown in messages; its base name, less `.md`, is the entry's id. Returns the entry as the + * record keeps it, less its commit (the freeze resolves that). + */ +export function readEntry(source, file, config) { + const id = path.basename(file).replace(/\.md$/, ""); + if (!file.endsWith(".md")) throw new Error(`${file}: an entry is a .md file`); + if (!ID.test(id)) throw new Error(`${file}: the id "${id}" is lowercase letters, digits and hyphens`); + if (reservedId(id)) throw new Error(`${file}: the id "${id}" is reserved for a release's address`); + const { head, at, body } = readHead(source, file, KEYS); + const line = (key) => `${file}:${at[key]}`; + + if (!("type" in head)) throw new Error(`${file}: "type" is required (${TYPES.join(", ")})`); + const type = head.type; + if (!TYPES.includes(type)) throw new Error(`${line("type")}: type "${type}" is one of ${TYPES.join(", ")}`); + + let pr; + if ("pr" in head) { + if (!/^[1-9][0-9]*$/.test(head.pr)) throw new Error(`${line("pr")}: "pr" is the pull request's number, such as 120`); + pr = Number(head.pr); + } + const fromPr = /^pr([1-9][0-9]*)-[1-9][0-9]*$/.exec(id); + if (fromPr && pr !== Number(fromPr[1])) throw new Error(`${file}: the file is named for pull request ${fromPr[1]}, so it says "pr: ${fromPr[1]}"${pr ? `, not ${pr}` : ""}`); + + let action = false; + if ("action" in head) { + if (head.action !== "true" && head.action !== "false") throw new Error(`${line("action")}: "action" is true or false`); + action = head.action === "true"; + } + + const floor = FLOOR[type]; + let bump = floor; + if ("bump" in head) { + if (!BUMPS.includes(head.bump)) throw new Error(`${line("bump")}: "bump" is major, minor or patch`); + if (floor && !atLeast(head.bump, floor)) throw new Error(`${line("bump")}: a ${type} entry needs at least a ${floor}; "bump" may raise it and never lower it`); + bump = head.bump; + } + if (!bump) throw new Error(`${file}: a changed entry states its bump ("bump: major", "minor" or "patch"): a default that alters behavior is major, a token's value minor, an improvement patch`); + if (bump === "major" && !action) throw new Error(`${file}: a major entry is always "action: true": what breaks is what a reader checks before upgrading`); + + let area; + if ("area" in head) { + if (!head.area) throw new Error(`${line("area")}: "area" is empty`); + area = head.area; + } + + let tickets = []; + if ("tickets" in head) tickets = readList(head.tickets, line("tickets"), "tickets").map((ticket) => resolveTicket(ticket, config, file)); + + let authors; + if ("author" in head) { + if (!head.author) throw new Error(`${line("author")}: "author" is empty; leave the key out when nobody has claimed the words`); + authors = [resolvePerson(head.author, config, line("author"))]; + } + + let migration; + if ("migration" in head) { + if (!head.migration) throw new Error(`${line("migration")}: "migration" is empty`); + migration = head.migration; + } + + const text = body.join("\n").trim().replace(/\s*\n\s*/g, " "); + if (!text) throw new Error(`${file}: the entry's sentence is missing under the head`); + + const entry = { id, type, bump, text }; + if (area) entry.area = area; + if (action) entry.action = true; + if (migration) entry.migration = migration; + if (pr) entry.pr = pr; + if (tickets.length) entry.tickets = tickets; + if (authors) entry.authors = authors; + return entry; +} + +const NOTES_KEYS = ["title", "summary"]; + +/** + * `.changes/release.md`: a release's notes. A head with `title` and `summary`; then a paragraph for everyone (no heading) and a `## For admins` + * heading for each audience, each block opening with a `covers: [ids]` line. `ids` is every entry id the paragraph may name. + */ +export function readNotes(source, file, ids) { + const { head, body, bodyLine } = readHead(source, file, NOTES_KEYS); + const notes = {}; + if (head.title) notes.title = head.title; + if (head.summary) notes.summary = head.summary; + const blocks = []; + let block = { for: undefined, line: bodyLine, lines: [] }; + body.forEach((text, index) => { + const heading = /^## (.+)$/.exec(text); + if (heading) { + blocks.push(block); + block = { for: heading[1].trim(), line: bodyLine + index, lines: [] }; + } else { + block.lines.push({ text, line: bodyLine + index }); + } + }); + blocks.push(block); + const audiences = []; + for (const { for: group, line, lines } of blocks) { + const filled = lines.filter((entry) => entry.text.trim() !== ""); + if (!filled.length) { + if (group) throw new Error(`${file}:${line}: "${group}" has no paragraph`); + continue; + } + const [first, ...rest] = filled; + const covers = /^covers: ?(.*)$/.exec(first.text.trim()); + if (!covers) throw new Error(`${file}:${first.line}: a paragraph opens with a "covers: [ids]" line naming the entries it is about`); + const list = readList(covers[1].trim(), `${file}:${first.line}`, "covers"); + if (!list.length) throw new Error(`${file}:${first.line}: the paragraph covers no entry: a claim with no entry gets an entry or goes (R18)`); + for (const id of list) if (!ids.has(id)) throw new Error(`${file}:${first.line}: covers "${id}", which is no entry of this release`); + const text = rest.map((entry) => entry.text.trim()).join(" ").trim(); + if (!text) throw new Error(`${file}:${first.line}: the paragraph is missing under its "covers" line`); + const audience = { text, covers: list }; + if (group) audience.for = group; + audiences.push(audience); + } + if (audiences.length) notes.audiences = audiences; + return notes; +} + +/** Every pending entry file in a repository's `.changes`, read and checked, sorted by id. */ +export function readPending(root, config) { + const dir = path.join(root, CHANGES_DIR); + if (!fs.existsSync(dir)) return []; + return fs.readdirSync(dir) + .filter((name) => name.endsWith(".md") && name !== NOTES_FILE && name !== "README.md") + .sort() + .map((name) => readEntry(fs.readFileSync(path.join(dir, name), "utf8"), path.join(CHANGES_DIR, name), config)); +} + +/** The pending release notes, or null. */ +export function readPendingNotes(root, ids) { + const file = path.join(root, CHANGES_DIR, NOTES_FILE); + if (!fs.existsSync(file)) return null; + return readNotes(fs.readFileSync(file, "utf8"), path.join(CHANGES_DIR, NOTES_FILE), ids); +} diff --git a/tools/changelog/fixtures/harbor/CHANGELOG.md b/tools/changelog/fixtures/harbor/CHANGELOG.md new file mode 100644 index 00000000..0c960fe9 --- /dev/null +++ b/tools/changelog/fixtures/harbor/CHANGELOG.md @@ -0,0 +1,89 @@ +# Changelog + +Every version of Harbor. This file is generated by `tools/changelog` from `changelog/releases` and `.changes`. Edit those, never this file. + +## 2.0.0 - 2026-12-07 + +**Responders sign in with their own account** + +Each responder now signs in with their own account, through your company's identity provider. + +### For admins + +In Settings, open Sign-in and connect your identity provider. Shared room codes stop working on Jan 15, 2027. + +Single sign-on replaces shared room codes, with a sign-in page for your company's identity provider. + +### Action needed + +- Sign-in: Removed sign-in with a shared room code, so each responder signs in with their own account before Jan 15, 2027 ([#140](https://github.com/example/harbor/pull/140)) + +### Added + +- Sign-in: Added single sign-on through your company's identity provider ([#141](https://github.com/example/harbor/pull/141), Linear [OPS-230](https://linear.app/example/issue/OPS-230)) +- Sign-in: Added a sign-in page that names your company's identity provider ([#142](https://github.com/example/harbor/pull/142)) + +### Fixed + +- Rooms: Fixed the room list scrolling to the top when a new room opened ([#143](https://github.com/example/harbor/pull/143)) + +## 1.4.1 - 2026-12-08 + +### Fixed + +- Rooms: Fixed the room timer showing 0:00 after a reload in a second tab ([#145](https://github.com/example/harbor/pull/145)) + +## 1.4.0 - 2026-11-23 + +**A monitor can open an incident room** + +A monitor that can send a webhook can now open an incident room when its alarm fires. The room shows the alarm, the service it names and the checks already run. + +### For responders + +On Home, open an incident marked "Opened by a monitor". The first message in the room is the alarm, with a link to the monitor. + +### For admins + +In Settings, open Integrations and add a webhook. Paste its address into your monitor. + +Monitors can open incident rooms through a webhook, and Home marks the incidents they open. The open incident list keeps its place, and two fixes cover the lobby and search. + +### Added + +- Home: Added an "Opened by a monitor" mark to incidents that a webhook declared ([#131](https://github.com/example/harbor/pull/131)) +- Integrations: Added webhook declarations so a monitor can open an incident room when its alarm fires ([#131](https://github.com/example/harbor/pull/131), Linear [OPS-204](https://linear.app/example/issue/OPS-204)) + +### Changed + +- Home: Improved the open incident list so your scroll position stays fixed when an incident arrives above it ([#132](https://github.com/example/harbor/pull/132)) + +### Fixed + +- Lobby: Fixed "Waiting to be admitted" staying on screen after the commander had admitted you, until you reloaded the page ([#133](https://github.com/example/harbor/pull/133)) +- Past incidents: Fixed search missing an update the commander had published in the last minute ([#134](https://github.com/example/harbor/pull/134)) + +## 1.3.1 - 2026-11-23 + +Fixes to the recap, the room timer, the directory and sign-in. + +### Fixed + +- Directory: Fixed a vendor's support line showing the previous vendor's number after you switched rows quickly ([#130](https://github.com/example/harbor/pull/130)) +- Rooms: Fixed the recap starting from the room's first message when you had been away for under a minute ([#129](https://github.com/example/harbor/pull/129)) +- Rooms: Fixed the room timer showing 0:00 after a reload ([#135](https://github.com/example/harbor/pull/135)) +- Sign-in: Fixed the code field clearing when you pasted a code ([#136](https://github.com/example/harbor/pull/136)) + +## 1.3.0 - 2026-11-20 + +**Updates need a second approval** + +An update to people outside the room now needs a second commander's approval before it is published. + +### Action needed + +- Updates: Changed published updates to require approval from a second commander, so name a second commander for each room before Dec 1, 2026 ([#126](https://github.com/example/harbor/pull/126)) + +### Added + +- Updates: Added an approval request that a second commander can grant or return with a note ([#126](https://github.com/example/harbor/pull/126)) diff --git a/tools/changelog/fixtures/harbor/changelog.config.json b/tools/changelog/fixtures/harbor/changelog.config.json new file mode 100644 index 00000000..21e3d12b --- /dev/null +++ b/tools/changelog/fixtures/harbor/changelog.config.json @@ -0,0 +1,16 @@ +{ + "product": "Harbor", + "repository": "https://github.com/example/harbor", + "trackers": [ + { + "name": "Linear", + "pattern": "OPS-[1-9][0-9]*", + "url": "https://linear.app/example/issue/{id}" + } + ], + "people": { + "ada": { + "name": "Ada Okoye" + } + } +} diff --git a/tools/changelog/fixtures/harbor/changelog/releases/1.3.0.json b/tools/changelog/fixtures/harbor/changelog/releases/1.3.0.json new file mode 100644 index 00000000..3ec46dcb --- /dev/null +++ b/tools/changelog/fixtures/harbor/changelog/releases/1.3.0.json @@ -0,0 +1,47 @@ +{ + "version": "1.3.0", + "date": "2026-11-20", + "title": "Updates need a second approval", + "audiences": [ + { + "text": "An update to people outside the room now needs a second commander's approval before it is published.", + "covers": [ + "pr126-1", + "pr126-2" + ] + } + ], + "entries": [ + { + "id": "pr126-1", + "type": "changed", + "bump": "minor", + "area": "Updates", + "text": "Changed published updates to require approval from a second commander, so name a second commander for each room before Dec 1, 2026", + "action": true, + "pr": { + "number": 126, + "href": "https://github.com/example/harbor/pull/126" + }, + "commit": { + "sha": "879654ad138e381be9af010c62d1868ff7600c9d", + "href": "https://github.com/example/harbor/commit/879654ad138e381be9af010c62d1868ff7600c9d" + } + }, + { + "id": "pr126-2", + "type": "added", + "bump": "minor", + "area": "Updates", + "text": "Added an approval request that a second commander can grant or return with a note", + "pr": { + "number": 126, + "href": "https://github.com/example/harbor/pull/126" + }, + "commit": { + "sha": "c8476fd49935f1b91a266a5077c687982941d2f5", + "href": "https://github.com/example/harbor/commit/c8476fd49935f1b91a266a5077c687982941d2f5" + } + } + ] +} diff --git a/tools/changelog/fixtures/harbor/changelog/releases/1.3.1.json b/tools/changelog/fixtures/harbor/changelog/releases/1.3.1.json new file mode 100644 index 00000000..1825d156 --- /dev/null +++ b/tools/changelog/fixtures/harbor/changelog/releases/1.3.1.json @@ -0,0 +1,68 @@ +{ + "version": "1.3.1", + "date": "2026-11-23", + "previous": "1.3.0", + "summary": "Fixes to the recap, the room timer, the directory and sign-in.", + "entries": [ + { + "id": "pr130-1", + "type": "fixed", + "bump": "patch", + "area": "Directory", + "text": "Fixed a vendor's support line showing the previous vendor's number after you switched rows quickly", + "pr": { + "number": 130, + "href": "https://github.com/example/harbor/pull/130" + }, + "commit": { + "sha": "e4f9b9f23e31054ee7fcabb9d081b7ba207789f9", + "href": "https://github.com/example/harbor/commit/e4f9b9f23e31054ee7fcabb9d081b7ba207789f9" + } + }, + { + "id": "pr129-1", + "type": "fixed", + "bump": "patch", + "area": "Rooms", + "text": "Fixed the recap starting from the room's first message when you had been away for under a minute", + "pr": { + "number": 129, + "href": "https://github.com/example/harbor/pull/129" + }, + "commit": { + "sha": "b066b10badd591b2380af2aedb4771207f5137af", + "href": "https://github.com/example/harbor/commit/b066b10badd591b2380af2aedb4771207f5137af" + } + }, + { + "id": "pr135-1", + "type": "fixed", + "bump": "patch", + "area": "Rooms", + "text": "Fixed the room timer showing 0:00 after a reload", + "pr": { + "number": 135, + "href": "https://github.com/example/harbor/pull/135" + }, + "commit": { + "sha": "73aa7ad5925fe59e1eefd7f19f7b5dceeba3574f", + "href": "https://github.com/example/harbor/commit/73aa7ad5925fe59e1eefd7f19f7b5dceeba3574f" + } + }, + { + "id": "pr136-1", + "type": "fixed", + "bump": "patch", + "area": "Sign-in", + "text": "Fixed the code field clearing when you pasted a code", + "pr": { + "number": 136, + "href": "https://github.com/example/harbor/pull/136" + }, + "commit": { + "sha": "f51c9f452aa51fa3eac4366b4d3dbde7c45a53a9", + "href": "https://github.com/example/harbor/commit/f51c9f452aa51fa3eac4366b4d3dbde7c45a53a9" + } + } + ] +} diff --git a/tools/changelog/fixtures/harbor/changelog/releases/1.4.0.json b/tools/changelog/fixtures/harbor/changelog/releases/1.4.0.json new file mode 100644 index 00000000..5d5b1b7e --- /dev/null +++ b/tools/changelog/fixtures/harbor/changelog/releases/1.4.0.json @@ -0,0 +1,121 @@ +{ + "version": "1.4.0", + "date": "2026-11-23", + "previous": "1.3.1", + "title": "A monitor can open an incident room", + "summary": "Monitors can open incident rooms through a webhook, and Home marks the incidents they open. The open incident list keeps its place, and two fixes cover the lobby and search.", + "audiences": [ + { + "text": "A monitor that can send a webhook can now open an incident room when its alarm fires. The room shows the alarm, the service it names and the checks already run.", + "covers": [ + "pr131-1" + ] + }, + { + "text": "On Home, open an incident marked \"Opened by a monitor\". The first message in the room is the alarm, with a link to the monitor.", + "covers": [ + "pr131-2" + ], + "for": "For responders" + }, + { + "text": "In Settings, open Integrations and add a webhook. Paste its address into your monitor.", + "covers": [ + "pr131-1" + ], + "for": "For admins" + } + ], + "entries": [ + { + "id": "pr131-2", + "type": "added", + "bump": "minor", + "area": "Home", + "text": "Added an \"Opened by a monitor\" mark to incidents that a webhook declared", + "pr": { + "number": 131, + "href": "https://github.com/example/harbor/pull/131" + }, + "commit": { + "sha": "df4cb3713024be1fef5e811e8d2bfd8063513935", + "href": "https://github.com/example/harbor/commit/df4cb3713024be1fef5e811e8d2bfd8063513935" + }, + "authors": [ + "Ada Okoye" + ] + }, + { + "id": "pr131-1", + "type": "added", + "bump": "minor", + "area": "Integrations", + "text": "Added webhook declarations so a monitor can open an incident room when its alarm fires", + "pr": { + "number": 131, + "href": "https://github.com/example/harbor/pull/131" + }, + "commit": { + "sha": "ba23aba5af21c20ad6fbbc4e15b596a01880026d", + "href": "https://github.com/example/harbor/commit/ba23aba5af21c20ad6fbbc4e15b596a01880026d" + }, + "tickets": [ + { + "tracker": "Linear", + "id": "OPS-204", + "label": "OPS-204", + "show": "link", + "href": "https://linear.app/example/issue/OPS-204" + } + ], + "authors": [ + "Ada Okoye" + ] + }, + { + "id": "pr132-1", + "type": "changed", + "bump": "patch", + "area": "Home", + "text": "Improved the open incident list so your scroll position stays fixed when an incident arrives above it", + "pr": { + "number": 132, + "href": "https://github.com/example/harbor/pull/132" + }, + "commit": { + "sha": "ceb39214c38800084176cfb676c70c26876d1d5e", + "href": "https://github.com/example/harbor/commit/ceb39214c38800084176cfb676c70c26876d1d5e" + } + }, + { + "id": "pr133-1", + "type": "fixed", + "bump": "patch", + "area": "Lobby", + "text": "Fixed \"Waiting to be admitted\" staying on screen after the commander had admitted you, until you reloaded the page", + "pr": { + "number": 133, + "href": "https://github.com/example/harbor/pull/133" + }, + "commit": { + "sha": "2808edaebcb0058ec82faacd8aecac2842bb269e", + "href": "https://github.com/example/harbor/commit/2808edaebcb0058ec82faacd8aecac2842bb269e" + } + }, + { + "id": "pr134-1", + "type": "fixed", + "bump": "patch", + "area": "Past incidents", + "text": "Fixed search missing an update the commander had published in the last minute", + "pr": { + "number": 134, + "href": "https://github.com/example/harbor/pull/134" + }, + "commit": { + "sha": "342fe80e1e928871370d38fcbea88459f8c6d602", + "href": "https://github.com/example/harbor/commit/342fe80e1e928871370d38fcbea88459f8c6d602" + } + } + ] +} diff --git a/tools/changelog/fixtures/harbor/changelog/releases/1.4.1.json b/tools/changelog/fixtures/harbor/changelog/releases/1.4.1.json new file mode 100644 index 00000000..948d6470 --- /dev/null +++ b/tools/changelog/fixtures/harbor/changelog/releases/1.4.1.json @@ -0,0 +1,22 @@ +{ + "version": "1.4.1", + "date": "2026-12-08", + "previous": "1.4.0", + "entries": [ + { + "id": "pr145-1", + "type": "fixed", + "bump": "patch", + "area": "Rooms", + "text": "Fixed the room timer showing 0:00 after a reload in a second tab", + "pr": { + "number": 145, + "href": "https://github.com/example/harbor/pull/145" + }, + "commit": { + "sha": "2685abd5d6cd57ddf42ceb062093b713aaaf0095", + "href": "https://github.com/example/harbor/commit/2685abd5d6cd57ddf42ceb062093b713aaaf0095" + } + } + ] +} diff --git a/tools/changelog/fixtures/harbor/changelog/releases/2.0.0-rc.1.json b/tools/changelog/fixtures/harbor/changelog/releases/2.0.0-rc.1.json new file mode 100644 index 00000000..f555b00b --- /dev/null +++ b/tools/changelog/fixtures/harbor/changelog/releases/2.0.0-rc.1.json @@ -0,0 +1,64 @@ +{ + "version": "2.0.0-rc.1", + "date": "2026-12-01", + "previous": "1.4.0", + "title": "Responders sign in with their own account", + "audiences": [ + { + "text": "Each responder now signs in with their own account, through your company's identity provider.", + "covers": [ + "pr141-1" + ] + }, + { + "text": "In Settings, open Sign-in and connect your identity provider. Shared room codes stop working on Jan 15, 2027.", + "covers": [ + "pr140-1", + "pr141-1" + ], + "for": "For admins" + } + ], + "entries": [ + { + "id": "pr140-1", + "type": "removed", + "bump": "major", + "area": "Sign-in", + "text": "Removed sign-in with a shared room code, so each responder signs in with their own account before Jan 15, 2027", + "action": true, + "pr": { + "number": 140, + "href": "https://github.com/example/harbor/pull/140" + }, + "commit": { + "sha": "a8304b10a2ecf43758b15ddec4253ca7cd8c1ea0", + "href": "https://github.com/example/harbor/commit/a8304b10a2ecf43758b15ddec4253ca7cd8c1ea0" + } + }, + { + "id": "pr141-1", + "type": "added", + "bump": "minor", + "area": "Sign-in", + "text": "Added single sign-on through your company's identity provider", + "pr": { + "number": 141, + "href": "https://github.com/example/harbor/pull/141" + }, + "commit": { + "sha": "3552f8a84ab38591bc0b0ddd1e3dd2a9d4b8a0be", + "href": "https://github.com/example/harbor/commit/3552f8a84ab38591bc0b0ddd1e3dd2a9d4b8a0be" + }, + "tickets": [ + { + "tracker": "Linear", + "id": "OPS-230", + "label": "OPS-230", + "show": "link", + "href": "https://linear.app/example/issue/OPS-230" + } + ] + } + ] +} diff --git a/tools/changelog/fixtures/harbor/changelog/releases/2.0.0-rc.2.json b/tools/changelog/fixtures/harbor/changelog/releases/2.0.0-rc.2.json new file mode 100644 index 00000000..8d31d8da --- /dev/null +++ b/tools/changelog/fixtures/harbor/changelog/releases/2.0.0-rc.2.json @@ -0,0 +1,31 @@ +{ + "version": "2.0.0-rc.2", + "date": "2026-12-03", + "previous": "1.4.0", + "title": "A sign-in page names your identity provider", + "audiences": [ + { + "text": "The sign-in page now names your company's identity provider, so responders know which account to use.", + "covers": [ + "pr142-1" + ] + } + ], + "entries": [ + { + "id": "pr142-1", + "type": "added", + "bump": "minor", + "area": "Sign-in", + "text": "Added a sign-in page that names your company's identity provider", + "pr": { + "number": 142, + "href": "https://github.com/example/harbor/pull/142" + }, + "commit": { + "sha": "742f0bea9adf73118c34597c5a0b6b7acf89bcb4", + "href": "https://github.com/example/harbor/commit/742f0bea9adf73118c34597c5a0b6b7acf89bcb4" + } + } + ] +} diff --git a/tools/changelog/fixtures/harbor/changelog/releases/2.0.0.json b/tools/changelog/fixtures/harbor/changelog/releases/2.0.0.json new file mode 100644 index 00000000..62d25977 --- /dev/null +++ b/tools/changelog/fixtures/harbor/changelog/releases/2.0.0.json @@ -0,0 +1,100 @@ +{ + "version": "2.0.0", + "date": "2026-12-07", + "previous": "1.4.0", + "replaces": [ + "2.0.0-rc.1", + "2.0.0-rc.2" + ], + "title": "Responders sign in with their own account", + "summary": "Single sign-on replaces shared room codes, with a sign-in page for your company's identity provider.", + "audiences": [ + { + "text": "Each responder now signs in with their own account, through your company's identity provider.", + "covers": [ + "pr141-1", + "pr142-1" + ] + }, + { + "text": "In Settings, open Sign-in and connect your identity provider. Shared room codes stop working on Jan 15, 2027.", + "covers": [ + "pr140-1", + "pr141-1" + ], + "for": "For admins" + } + ], + "entries": [ + { + "id": "pr140-1", + "type": "removed", + "bump": "major", + "area": "Sign-in", + "text": "Removed sign-in with a shared room code, so each responder signs in with their own account before Jan 15, 2027", + "action": true, + "pr": { + "number": 140, + "href": "https://github.com/example/harbor/pull/140" + }, + "commit": { + "sha": "a8304b10a2ecf43758b15ddec4253ca7cd8c1ea0", + "href": "https://github.com/example/harbor/commit/a8304b10a2ecf43758b15ddec4253ca7cd8c1ea0" + } + }, + { + "id": "pr141-1", + "type": "added", + "bump": "minor", + "area": "Sign-in", + "text": "Added single sign-on through your company's identity provider", + "pr": { + "number": 141, + "href": "https://github.com/example/harbor/pull/141" + }, + "commit": { + "sha": "3552f8a84ab38591bc0b0ddd1e3dd2a9d4b8a0be", + "href": "https://github.com/example/harbor/commit/3552f8a84ab38591bc0b0ddd1e3dd2a9d4b8a0be" + }, + "tickets": [ + { + "tracker": "Linear", + "id": "OPS-230", + "label": "OPS-230", + "show": "link", + "href": "https://linear.app/example/issue/OPS-230" + } + ] + }, + { + "id": "pr142-1", + "type": "added", + "bump": "minor", + "area": "Sign-in", + "text": "Added a sign-in page that names your company's identity provider", + "pr": { + "number": 142, + "href": "https://github.com/example/harbor/pull/142" + }, + "commit": { + "sha": "742f0bea9adf73118c34597c5a0b6b7acf89bcb4", + "href": "https://github.com/example/harbor/commit/742f0bea9adf73118c34597c5a0b6b7acf89bcb4" + } + }, + { + "id": "pr143-1", + "type": "fixed", + "bump": "patch", + "area": "Rooms", + "text": "Fixed the room list scrolling to the top when a new room opened", + "pr": { + "number": 143, + "href": "https://github.com/example/harbor/pull/143" + }, + "commit": { + "sha": "1d6845348292ea8e2876f0c9667cc4fc2867346a", + "href": "https://github.com/example/harbor/commit/1d6845348292ea8e2876f0c9667cc4fc2867346a" + } + } + ] +} diff --git a/tools/changelog/fixtures/harbor/releases.json b/tools/changelog/fixtures/harbor/releases.json new file mode 100644 index 00000000..0d44977b --- /dev/null +++ b/tools/changelog/fixtures/harbor/releases.json @@ -0,0 +1,356 @@ +[ + { + "version": "2.0.0", + "date": "2026-12-07", + "previous": "1.4.0", + "replaces": [ + "2.0.0-rc.1", + "2.0.0-rc.2" + ], + "title": "Responders sign in with their own account", + "summary": "Single sign-on replaces shared room codes, with a sign-in page for your company's identity provider.", + "audiences": [ + { + "text": "Each responder now signs in with their own account, through your company's identity provider.", + "covers": [ + "pr141-1", + "pr142-1" + ] + }, + { + "text": "In Settings, open Sign-in and connect your identity provider. Shared room codes stop working on Jan 15, 2027.", + "covers": [ + "pr140-1", + "pr141-1" + ], + "for": "For admins" + } + ], + "entries": [ + { + "id": "pr140-1", + "type": "removed", + "bump": "major", + "area": "Sign-in", + "text": "Removed sign-in with a shared room code, so each responder signs in with their own account before Jan 15, 2027", + "action": true, + "pr": { + "number": 140, + "href": "https://github.com/example/harbor/pull/140" + }, + "commit": { + "sha": "a8304b10a2ecf43758b15ddec4253ca7cd8c1ea0", + "href": "https://github.com/example/harbor/commit/a8304b10a2ecf43758b15ddec4253ca7cd8c1ea0" + } + }, + { + "id": "pr141-1", + "type": "added", + "bump": "minor", + "area": "Sign-in", + "text": "Added single sign-on through your company's identity provider", + "pr": { + "number": 141, + "href": "https://github.com/example/harbor/pull/141" + }, + "commit": { + "sha": "3552f8a84ab38591bc0b0ddd1e3dd2a9d4b8a0be", + "href": "https://github.com/example/harbor/commit/3552f8a84ab38591bc0b0ddd1e3dd2a9d4b8a0be" + }, + "tickets": [ + { + "tracker": "Linear", + "label": "OPS-230", + "href": "https://linear.app/example/issue/OPS-230" + } + ] + }, + { + "id": "pr142-1", + "type": "added", + "bump": "minor", + "area": "Sign-in", + "text": "Added a sign-in page that names your company's identity provider", + "pr": { + "number": 142, + "href": "https://github.com/example/harbor/pull/142" + }, + "commit": { + "sha": "742f0bea9adf73118c34597c5a0b6b7acf89bcb4", + "href": "https://github.com/example/harbor/commit/742f0bea9adf73118c34597c5a0b6b7acf89bcb4" + } + }, + { + "id": "pr143-1", + "type": "fixed", + "bump": "patch", + "area": "Rooms", + "text": "Fixed the room list scrolling to the top when a new room opened", + "pr": { + "number": 143, + "href": "https://github.com/example/harbor/pull/143" + }, + "commit": { + "sha": "1d6845348292ea8e2876f0c9667cc4fc2867346a", + "href": "https://github.com/example/harbor/commit/1d6845348292ea8e2876f0c9667cc4fc2867346a" + } + } + ] + }, + { + "version": "1.4.1", + "date": "2026-12-08", + "previous": "1.4.0", + "entries": [ + { + "id": "pr145-1", + "type": "fixed", + "bump": "patch", + "area": "Rooms", + "text": "Fixed the room timer showing 0:00 after a reload in a second tab", + "pr": { + "number": 145, + "href": "https://github.com/example/harbor/pull/145" + }, + "commit": { + "sha": "2685abd5d6cd57ddf42ceb062093b713aaaf0095", + "href": "https://github.com/example/harbor/commit/2685abd5d6cd57ddf42ceb062093b713aaaf0095" + } + } + ] + }, + { + "version": "1.4.0", + "date": "2026-11-23", + "previous": "1.3.1", + "title": "A monitor can open an incident room", + "summary": "Monitors can open incident rooms through a webhook, and Home marks the incidents they open. The open incident list keeps its place, and two fixes cover the lobby and search.", + "audiences": [ + { + "text": "A monitor that can send a webhook can now open an incident room when its alarm fires. The room shows the alarm, the service it names and the checks already run.", + "covers": [ + "pr131-1" + ] + }, + { + "text": "On Home, open an incident marked \"Opened by a monitor\". The first message in the room is the alarm, with a link to the monitor.", + "covers": [ + "pr131-2" + ], + "for": "For responders" + }, + { + "text": "In Settings, open Integrations and add a webhook. Paste its address into your monitor.", + "covers": [ + "pr131-1" + ], + "for": "For admins" + } + ], + "entries": [ + { + "id": "pr131-2", + "type": "added", + "bump": "minor", + "area": "Home", + "text": "Added an \"Opened by a monitor\" mark to incidents that a webhook declared", + "pr": { + "number": 131, + "href": "https://github.com/example/harbor/pull/131" + }, + "commit": { + "sha": "df4cb3713024be1fef5e811e8d2bfd8063513935", + "href": "https://github.com/example/harbor/commit/df4cb3713024be1fef5e811e8d2bfd8063513935" + }, + "authors": [ + "Ada Okoye" + ] + }, + { + "id": "pr131-1", + "type": "added", + "bump": "minor", + "area": "Integrations", + "text": "Added webhook declarations so a monitor can open an incident room when its alarm fires", + "pr": { + "number": 131, + "href": "https://github.com/example/harbor/pull/131" + }, + "commit": { + "sha": "ba23aba5af21c20ad6fbbc4e15b596a01880026d", + "href": "https://github.com/example/harbor/commit/ba23aba5af21c20ad6fbbc4e15b596a01880026d" + }, + "tickets": [ + { + "tracker": "Linear", + "label": "OPS-204", + "href": "https://linear.app/example/issue/OPS-204" + } + ], + "authors": [ + "Ada Okoye" + ] + }, + { + "id": "pr132-1", + "type": "changed", + "bump": "patch", + "area": "Home", + "text": "Improved the open incident list so your scroll position stays fixed when an incident arrives above it", + "pr": { + "number": 132, + "href": "https://github.com/example/harbor/pull/132" + }, + "commit": { + "sha": "ceb39214c38800084176cfb676c70c26876d1d5e", + "href": "https://github.com/example/harbor/commit/ceb39214c38800084176cfb676c70c26876d1d5e" + } + }, + { + "id": "pr133-1", + "type": "fixed", + "bump": "patch", + "area": "Lobby", + "text": "Fixed \"Waiting to be admitted\" staying on screen after the commander had admitted you, until you reloaded the page", + "pr": { + "number": 133, + "href": "https://github.com/example/harbor/pull/133" + }, + "commit": { + "sha": "2808edaebcb0058ec82faacd8aecac2842bb269e", + "href": "https://github.com/example/harbor/commit/2808edaebcb0058ec82faacd8aecac2842bb269e" + } + }, + { + "id": "pr134-1", + "type": "fixed", + "bump": "patch", + "area": "Past incidents", + "text": "Fixed search missing an update the commander had published in the last minute", + "pr": { + "number": 134, + "href": "https://github.com/example/harbor/pull/134" + }, + "commit": { + "sha": "342fe80e1e928871370d38fcbea88459f8c6d602", + "href": "https://github.com/example/harbor/commit/342fe80e1e928871370d38fcbea88459f8c6d602" + } + } + ] + }, + { + "version": "1.3.1", + "date": "2026-11-23", + "previous": "1.3.0", + "summary": "Fixes to the recap, the room timer, the directory and sign-in.", + "entries": [ + { + "id": "pr130-1", + "type": "fixed", + "bump": "patch", + "area": "Directory", + "text": "Fixed a vendor's support line showing the previous vendor's number after you switched rows quickly", + "pr": { + "number": 130, + "href": "https://github.com/example/harbor/pull/130" + }, + "commit": { + "sha": "e4f9b9f23e31054ee7fcabb9d081b7ba207789f9", + "href": "https://github.com/example/harbor/commit/e4f9b9f23e31054ee7fcabb9d081b7ba207789f9" + } + }, + { + "id": "pr129-1", + "type": "fixed", + "bump": "patch", + "area": "Rooms", + "text": "Fixed the recap starting from the room's first message when you had been away for under a minute", + "pr": { + "number": 129, + "href": "https://github.com/example/harbor/pull/129" + }, + "commit": { + "sha": "b066b10badd591b2380af2aedb4771207f5137af", + "href": "https://github.com/example/harbor/commit/b066b10badd591b2380af2aedb4771207f5137af" + } + }, + { + "id": "pr135-1", + "type": "fixed", + "bump": "patch", + "area": "Rooms", + "text": "Fixed the room timer showing 0:00 after a reload", + "pr": { + "number": 135, + "href": "https://github.com/example/harbor/pull/135" + }, + "commit": { + "sha": "73aa7ad5925fe59e1eefd7f19f7b5dceeba3574f", + "href": "https://github.com/example/harbor/commit/73aa7ad5925fe59e1eefd7f19f7b5dceeba3574f" + } + }, + { + "id": "pr136-1", + "type": "fixed", + "bump": "patch", + "area": "Sign-in", + "text": "Fixed the code field clearing when you pasted a code", + "pr": { + "number": 136, + "href": "https://github.com/example/harbor/pull/136" + }, + "commit": { + "sha": "f51c9f452aa51fa3eac4366b4d3dbde7c45a53a9", + "href": "https://github.com/example/harbor/commit/f51c9f452aa51fa3eac4366b4d3dbde7c45a53a9" + } + } + ] + }, + { + "version": "1.3.0", + "date": "2026-11-20", + "title": "Updates need a second approval", + "audiences": [ + { + "text": "An update to people outside the room now needs a second commander's approval before it is published.", + "covers": [ + "pr126-1", + "pr126-2" + ] + } + ], + "entries": [ + { + "id": "pr126-1", + "type": "changed", + "bump": "minor", + "area": "Updates", + "text": "Changed published updates to require approval from a second commander, so name a second commander for each room before Dec 1, 2026", + "action": true, + "pr": { + "number": 126, + "href": "https://github.com/example/harbor/pull/126" + }, + "commit": { + "sha": "879654ad138e381be9af010c62d1868ff7600c9d", + "href": "https://github.com/example/harbor/commit/879654ad138e381be9af010c62d1868ff7600c9d" + } + }, + { + "id": "pr126-2", + "type": "added", + "bump": "minor", + "area": "Updates", + "text": "Added an approval request that a second commander can grant or return with a note", + "pr": { + "number": 126, + "href": "https://github.com/example/harbor/pull/126" + }, + "commit": { + "sha": "c8476fd49935f1b91a266a5077c687982941d2f5", + "href": "https://github.com/example/harbor/commit/c8476fd49935f1b91a266a5077c687982941d2f5" + } + } + ] + } +] diff --git a/tools/changelog/fixtures/make.mjs b/tools/changelog/fixtures/make.mjs new file mode 100644 index 00000000..73d9960a --- /dev/null +++ b/tools/changelog/fixtures/make.mjs @@ -0,0 +1,273 @@ +// The fixtures (DECISIONS 320, 6.1): two made-up projects, "Slate" (a package) and "Harbor" (a product), built by running the real tool. +// Every fact in them is invented: the products, versions, dates, pull requests, tickets, people and commits. Nothing is Basalt's or CIMIP's. +// node tools/changelog/fixtures/make.mjs +// It builds each project's history in a temporary git repository (each entry file committed as its own squashed pull request, the notes +// written, then `freeze` run, as a person cutting the release would) with fixed authors and dates, so the commits and every byte written are +// the same on every run. It then copies the config, the records, the pending files, CHANGELOG.md and the page's data (`releases.json`) here. +import { execFileSync } from "node:child_process"; +import fs from "node:fs"; +import os from "node:os"; +import path from "node:path"; +import { fileURLToPath } from "node:url"; + +import { freeze } from "../release.mjs"; +import { loadConfig } from "../config.mjs"; +import { pageReleases } from "../records.mjs"; + +const HERE = path.dirname(fileURLToPath(import.meta.url)); + +// ---------- Slate: a package, in 0.x ---------- + +export const SLATE = { + name: "slate", + config: { + product: "Slate", + repository: "https://github.com/example/slate", + trackers: [ + { name: "Linear", pattern: "(?:SL|DS)-[1-9][0-9]*", url: "https://linear.app/example/issue/{id}" }, + { name: "Jira", pattern: "PRJ-[1-9][0-9]*", url: "https://example.atlassian.net/browse/{id}", show: "text" }, + { name: "GitHub", pattern: "slate#(?[1-9][0-9]*)", url: "https://github.com/example/slate/issues/{n}", label: "issue #{n}" }, + { name: "Support", pattern: "SUP-[1-9][0-9]*", show: "none" }, + ], + people: { sam: { name: "Sam Rivera" } }, + }, + steps: [ + { notes: { summary: "The first version in this changelog. Earlier work is in the repository's history." }, version: "0.1.0", date: "2026-11-02" }, + { + entries: [ + { id: "pr41-1", pr: 41, type: "changed", area: "Grid", bump: "major", action: true, author: "sam", tickets: ["SL-112", "PRJ-88"], migration: "docs/migrating.md#grid-frame", text: "Changed the parent layout item for `Grid` to `.slate-grid-frame`, where existing sizing rules must move" }, + { id: "pr41-2", pr: 41, type: "changed", area: "storedCount", bump: "major", action: true, migration: "docs/migrating.md#stored-counts", text: "Changed stored counts to require an explicit store, so pass `() => localStorage` when reading, writing or clearing old counts" }, + { id: "pr42-1", pr: 42, type: "changed", area: "fillForm", bump: "major", action: true, text: "Changed `fillForm` to keep null fields empty, so omit unknown fields or pass `undefined`" }, + { id: "pr43-1", pr: 43, type: "changed", area: "TableHeader", bump: "major", action: true, text: "Changed fixed `TableHeader` cells to show a supplied `hint`, so remove that prop where a header should stay plain" }, + { id: "pr44-1", pr: 44, type: "deprecated", area: "Banner", text: "Deprecated `Banner` in favor of `Notice`, which takes the same props, removed in 1.0.0 no earlier than Mar 1, 2027" }, + { id: "pr45-1", pr: 45, type: "added", area: "Composer", author: "sam", tickets: ["SL-120"], text: "Added `Composer`, a message field that grows from 2 to 8 rows, with Send last and a status line under it" }, + { id: "pr45-2", pr: 45, type: "added", area: "Mention", text: "Added `Mention` to show a name after @ and mark a mention of the reader when `you` is set" }, + { id: "pr46-1", pr: 46, type: "added", area: "Tokens", tickets: ["DS-27", "DS-31", "PRJ-90", "slate#45", "SL-131", "SUP-7"], text: "Added `--slate-plate` for a highlighted row's solid fill on its current surface level" }, + { id: "pr47-1", pr: 47, type: "changed", area: "Toast", bump: "minor", text: "Changed toasts on phones to sit 8px below the top bar instead of above the bottom tabs" }, + { id: "pr48-1", pr: 48, type: "fixed", area: "Checkbox", tickets: ["slate#45"], text: "Fixed scrolling checkbox lists adding empty space below the page inside a sticky container" }, + { id: "pr49-1", pr: 49, type: "fixed", area: "SelectList", text: "Fixed keyboard focus leaving `SelectList` when the focused row was removed" }, + { id: "pr49-2", pr: 49, type: "fixed", area: "Sheet", text: "Fixed clipped focus rings at the top and bottom of a sheet's scrolling body" }, + { id: "pr50-1", pr: 50, type: "fixed", area: "Sidebar", text: "Fixed the brand mark sitting off center when the sidebar collapsed to its rail" }, + { id: "docs-contrast-note", type: "fixed", area: "Docs", text: "Fixed the contrast table listing secondary ink on the sunken band at 4.1:1, where it measures 4.6:1" }, + ], + notes: { summary: "Slate 0.2.0 adds a composer with mentions and a plate token for highlighted rows. Four changes to layout and stored data need a look before upgrading." }, + version: "0.2.0", + date: "2026-11-16", + }, + { entries: [{ id: "pr52-1", pr: 52, type: "fixed", area: "Composer", text: "Fixed `Composer` losing its draft when the window lost focus" }], version: "0.2.1", date: "2026-11-16" }, + { + entries: [ + { id: "pr53-1", pr: 53, type: "changed", area: "Chart", bump: "patch", text: "Changed production builds to leave out development checks, so the minified `Chart` module is 3,227 bytes smaller" }, + { id: "pr54-1", pr: 54, type: "fixed", area: "Chart", text: "Fixed blurry labels on 1px chart lines when a label fell between whole pixels" }, + ], + }, + ], +}; + +// ---------- Harbor: a product, from 1.x, with a maintained older line ---------- + +export const HARBOR = { + name: "harbor", + config: { + product: "Harbor", + repository: "https://github.com/example/harbor", + trackers: [{ name: "Linear", pattern: "OPS-[1-9][0-9]*", url: "https://linear.app/example/issue/{id}" }], + people: { ada: { name: "Ada Okoye" } }, + }, + steps: [ + { + entries: [ + { id: "pr126-1", pr: 126, type: "changed", area: "Updates", bump: "minor", action: true, text: "Changed published updates to require approval from a second commander, so name a second commander for each room before Dec 1, 2026" }, + { id: "pr126-2", pr: 126, type: "added", area: "Updates", text: "Added an approval request that a second commander can grant or return with a note" }, + ], + notes: { title: "Updates need a second approval", audiences: [{ covers: ["pr126-1", "pr126-2"], text: "An update to people outside the room now needs a second commander's approval before it is published." }] }, + version: "1.3.0", + date: "2026-11-20", + }, + { + entries: [ + { id: "pr129-1", pr: 129, type: "fixed", area: "Rooms", text: "Fixed the recap starting from the room's first message when you had been away for under a minute" }, + { id: "pr130-1", pr: 130, type: "fixed", area: "Directory", text: "Fixed a vendor's support line showing the previous vendor's number after you switched rows quickly" }, + { id: "pr135-1", pr: 135, type: "fixed", area: "Rooms", text: "Fixed the room timer showing 0:00 after a reload" }, + { id: "pr136-1", pr: 136, type: "fixed", area: "Sign-in", text: "Fixed the code field clearing when you pasted a code" }, + ], + notes: { summary: "Fixes to the recap, the room timer, the directory and sign-in." }, + version: "1.3.1", + date: "2026-11-23", + }, + { + entries: [ + { id: "pr131-1", pr: 131, type: "added", area: "Integrations", author: "ada", tickets: ["OPS-204"], text: "Added webhook declarations so a monitor can open an incident room when its alarm fires" }, + { id: "pr131-2", pr: 131, type: "added", area: "Home", author: "ada", text: "Added an \"Opened by a monitor\" mark to incidents that a webhook declared" }, + { id: "pr132-1", pr: 132, type: "changed", area: "Home", bump: "patch", text: "Improved the open incident list so your scroll position stays fixed when an incident arrives above it" }, + { id: "pr133-1", pr: 133, type: "fixed", area: "Lobby", text: "Fixed \"Waiting to be admitted\" staying on screen after the commander had admitted you, until you reloaded the page" }, + { id: "pr134-1", pr: 134, type: "fixed", area: "Past incidents", text: "Fixed search missing an update the commander had published in the last minute" }, + ], + notes: { + title: "A monitor can open an incident room", + summary: "Monitors can open incident rooms through a webhook, and Home marks the incidents they open. The open incident list keeps its place, and two fixes cover the lobby and search.", + audiences: [ + { covers: ["pr131-1"], text: "A monitor that can send a webhook can now open an incident room when its alarm fires. The room shows the alarm, the service it names and the checks already run." }, + { for: "For responders", covers: ["pr131-2"], text: "On Home, open an incident marked \"Opened by a monitor\". The first message in the room is the alarm, with a link to the monitor." }, + { for: "For admins", covers: ["pr131-1"], text: "In Settings, open Integrations and add a webhook. Paste its address into your monitor." }, + ], + }, + version: "1.4.0", + date: "2026-11-23", + }, + { branch: "release/1.x", from: "1.4.0" }, + { + entries: [ + { id: "pr140-1", pr: 140, type: "removed", area: "Sign-in", action: true, text: "Removed sign-in with a shared room code, so each responder signs in with their own account before Jan 15, 2027" }, + { id: "pr141-1", pr: 141, type: "added", area: "Sign-in", tickets: ["OPS-230"], text: "Added single sign-on through your company's identity provider" }, + ], + notes: { + title: "Responders sign in with their own account", + audiences: [ + { covers: ["pr141-1"], text: "Each responder now signs in with their own account, through your company's identity provider." }, + { for: "For admins", covers: ["pr140-1", "pr141-1"], text: "In Settings, open Sign-in and connect your identity provider. Shared room codes stop working on Jan 15, 2027." }, + ], + }, + version: "2.0.0-rc.1", + date: "2026-12-01", + }, + { + entries: [{ id: "pr142-1", pr: 142, type: "added", area: "Sign-in", text: "Added a sign-in page that names your company's identity provider" }], + notes: { + title: "A sign-in page names your identity provider", + audiences: [{ covers: ["pr142-1"], text: "The sign-in page now names your company's identity provider, so responders know which account to use." }], + }, + version: "2.0.0-rc.2", + date: "2026-12-03", + }, + { + entries: [{ id: "pr143-1", pr: 143, type: "fixed", area: "Rooms", text: "Fixed the room list scrolling to the top when a new room opened" }], + notes: { + title: "Responders sign in with their own account", + summary: "Single sign-on replaces shared room codes, with a sign-in page for your company's identity provider.", + audiences: [ + { covers: ["pr141-1", "pr142-1"], text: "Each responder now signs in with their own account, through your company's identity provider." }, + { for: "For admins", covers: ["pr140-1", "pr141-1"], text: "In Settings, open Sign-in and connect your identity provider. Shared room codes stop working on Jan 15, 2027." }, + ], + }, + version: "2.0.0", + date: "2026-12-07", + }, + { + branch: "release/1.x", + entries: [{ id: "pr145-1", pr: 145, type: "fixed", area: "Rooms", text: "Fixed the room timer showing 0:00 after a reload in a second tab" }], + version: "1.4.1", + date: "2026-12-08", + // A maintained line's record is added to the default branch by a pull request, because the page is built there. + backTo: "main", + }, + ], +}; + +// ---------- the build ---------- + +const entryFile = (entry) => { + const head = ["---", `type: ${entry.type}`]; + if (entry.area) head.push(`area: ${entry.area}`); + if (entry.pr) head.push(`pr: ${entry.pr}`); + if (entry.author) head.push(`author: ${entry.author}`); + if (entry.tickets) head.push(`tickets: [${entry.tickets.join(", ")}]`); + if (entry.bump) head.push(`bump: ${entry.bump}`); + if (entry.action) head.push("action: true"); + if (entry.migration) head.push(`migration: ${entry.migration}`); + return `${head.join("\n")}\n---\n${entry.text}\n`; +}; + +const notesFile = (notes) => { + const head = ["---"]; + if (notes.title) head.push(`title: ${notes.title}`); + if (notes.summary) head.push(`summary: ${notes.summary}`); + head.push("---"); + const blocks = (notes.audiences ?? []).map((audience) => `${audience.for ? `## ${audience.for}\n` : ""}covers: [${audience.covers.join(", ")}]\n${audience.text}\n`); + return `${head.join("\n")}\n${blocks.join("\n")}`; +}; + +/** Build one project's history in a fresh repository and return its path. */ +export function buildRepository(project, dir = fs.mkdtempSync(path.join(os.tmpdir(), `changelog-${project.name}-`))) { + let clock = Date.UTC(2026, 9, 1, 12); + const env = () => { + clock += 60_000; + const when = new Date(clock).toISOString(); + return { ...process.env, GIT_AUTHOR_NAME: "Example", GIT_AUTHOR_EMAIL: "example@example.com", GIT_COMMITTER_NAME: "Example", GIT_COMMITTER_EMAIL: "example@example.com", GIT_AUTHOR_DATE: when, GIT_COMMITTER_DATE: when }; + }; + const git = (...args) => execFileSync("git", args, { cwd: dir, env: env(), encoding: "utf8", stdio: ["ignore", "pipe", "pipe"] }).trim(); + git("init", "-q", "-b", "main"); + git("config", "commit.gpgsign", "false"); + fs.writeFileSync(path.join(dir, "changelog.config.json"), `${JSON.stringify(project.config, null, 2)}\n`); + git("add", "-A"); + git("commit", "-q", "-m", "Start"); + for (const step of project.steps) { + if (step.from) { + git("branch", step.branch, `v${step.from}`); + continue; + } + if (step.branch) git("checkout", "-q", step.branch); + for (const entry of step.entries ?? []) { + fs.mkdirSync(path.join(dir, ".changes"), { recursive: true }); + fs.writeFileSync(path.join(dir, ".changes", `${entry.id}.md`), entryFile(entry)); + git("add", "-A"); + git("commit", "-q", "-m", entry.pr ? `${entry.area}: ${entry.text.split(" ").slice(0, 6).join(" ")} (#${entry.pr})` : `${entry.area}: ${entry.text.split(" ").slice(0, 6).join(" ")}`); + } + if (!step.version) continue; + const notes = path.join(dir, ".changes", "release.md"); + if (step.notes) { + fs.mkdirSync(path.dirname(notes), { recursive: true }); + fs.writeFileSync(notes, notesFile(step.notes)); + git("add", "-A"); + git("commit", "-q", "-m", `Release notes for ${step.version}`); + } + freeze({ root: dir, version: step.version, date: step.date }); + git("add", "-A"); + git("commit", "-q", "-m", `Release ${step.version}`); + git("tag", `v${step.version}`); + if (step.backTo) { + const record = fs.readFileSync(path.join(dir, "changelog", "releases", `${step.version}.json`), "utf8"); + git("checkout", "-q", step.backTo); + fs.writeFileSync(path.join(dir, "changelog", "releases", `${step.version}.json`), record); + // The default branch's CHANGELOG.md is regenerated with the record in it. + const { changelogMarkdown } = OUTPUTS; + const config = loadConfig(dir); + fs.writeFileSync(path.join(dir, "CHANGELOG.md"), changelogMarkdown(pageReleases(dir, { config }), { product: config.product })); + git("add", "-A"); + git("commit", "-q", "-m", `Add the ${step.version} record (#146)`); + } else if (step.branch) { + git("checkout", "-q", "main"); + } + } + return dir; +} + +const OUTPUTS = await import("../outputs.mjs"); + +/** Copy what a project's repository holds into its fixture folder (or `out`). */ +export function copyOut(project, dir, out = path.join(HERE, project.name)) { + fs.rmSync(out, { recursive: true, force: true }); + fs.mkdirSync(path.join(out, "changelog", "releases"), { recursive: true }); + fs.copyFileSync(path.join(dir, "changelog.config.json"), path.join(out, "changelog.config.json")); + for (const name of fs.readdirSync(path.join(dir, "changelog", "releases"))) fs.copyFileSync(path.join(dir, "changelog", "releases", name), path.join(out, "changelog", "releases", name)); + const changes = path.join(dir, ".changes"); + if (fs.existsSync(changes) && fs.readdirSync(changes).length) { + fs.mkdirSync(path.join(out, ".changes")); + for (const name of fs.readdirSync(changes)) fs.copyFileSync(path.join(changes, name), path.join(out, ".changes", name)); + } + // Entries merged since the last release are in CHANGELOG.md's Unreleased section, as `node tools/changelog/build.mjs` writes it. + const config = loadConfig(out); + const releases = pageReleases(out, { config }); + fs.writeFileSync(path.join(out, "CHANGELOG.md"), OUTPUTS.changelogMarkdown(releases, { product: config.product })); + fs.writeFileSync(path.join(out, "releases.json"), `${JSON.stringify(releases, null, 2)}\n`); +} + +const { isMain } = await import("../../../scripts/is-main.mjs"); +if (isMain(import.meta.url)) { + for (const project of [SLATE, HARBOR]) { + const dir = buildRepository(project); + copyOut(project, dir); + fs.rmSync(dir, { recursive: true, force: true }); + process.stdout.write(`Wrote tools/changelog/fixtures/${project.name}\n`); + } +} diff --git a/tools/changelog/fixtures/slate/.changes/pr53-1.md b/tools/changelog/fixtures/slate/.changes/pr53-1.md new file mode 100644 index 00000000..170c9b52 --- /dev/null +++ b/tools/changelog/fixtures/slate/.changes/pr53-1.md @@ -0,0 +1,7 @@ +--- +type: changed +area: Chart +pr: 53 +bump: patch +--- +Changed production builds to leave out development checks, so the minified `Chart` module is 3,227 bytes smaller diff --git a/tools/changelog/fixtures/slate/.changes/pr54-1.md b/tools/changelog/fixtures/slate/.changes/pr54-1.md new file mode 100644 index 00000000..d117f114 --- /dev/null +++ b/tools/changelog/fixtures/slate/.changes/pr54-1.md @@ -0,0 +1,6 @@ +--- +type: fixed +area: Chart +pr: 54 +--- +Fixed blurry labels on 1px chart lines when a label fell between whole pixels diff --git a/tools/changelog/fixtures/slate/CHANGELOG.md b/tools/changelog/fixtures/slate/CHANGELOG.md new file mode 100644 index 00000000..e22782f1 --- /dev/null +++ b/tools/changelog/fixtures/slate/CHANGELOG.md @@ -0,0 +1,58 @@ +# Changelog + +Every version of Slate. This file is generated by `tools/changelog` from `changelog/releases` and `.changes`. Edit those, never this file. + +## Unreleased + +### Changed + +- Chart: Changed production builds to leave out development checks, so the minified `Chart` module is 3,227 bytes smaller ([#53](https://github.com/example/slate/pull/53)) + +### Fixed + +- Chart: Fixed blurry labels on 1px chart lines when a label fell between whole pixels ([#54](https://github.com/example/slate/pull/54)) + +## 0.2.1 - 2026-11-16 + +### Fixed + +- Composer: Fixed `Composer` losing its draft when the window lost focus ([#52](https://github.com/example/slate/pull/52)) + +## 0.2.0 - 2026-11-16 + +Slate 0.2.0 adds a composer with mentions and a plate token for highlighted rows. Four changes to layout and stored data need a look before upgrading. + +### Action needed + +Before upgrading from 0.1.0, check these 4 changes. + +- fillForm: Changed `fillForm` to keep null fields empty, so omit unknown fields or pass `undefined` ([#42](https://github.com/example/slate/pull/42)) +- Grid: Changed the parent layout item for `Grid` to `.slate-grid-frame`, where existing sizing rules must move [How to migrate](https://github.com/example/slate/blob/v0.2.0/docs/migrating.md#grid-frame) ([#41](https://github.com/example/slate/pull/41), Linear [SL-112](https://linear.app/example/issue/SL-112), Jira PRJ-88) +- storedCount: Changed stored counts to require an explicit store, so pass `() => localStorage` when reading, writing or clearing old counts [How to migrate](https://github.com/example/slate/blob/v0.2.0/docs/migrating.md#stored-counts) ([#41](https://github.com/example/slate/pull/41)) +- TableHeader: Changed fixed `TableHeader` cells to show a supplied `hint`, so remove that prop where a header should stay plain ([#43](https://github.com/example/slate/pull/43)) + +### Deprecated + +- Banner: Deprecated `Banner` in favor of `Notice`, which takes the same props, removed in 1.0.0 no earlier than Mar 1, 2027 ([#44](https://github.com/example/slate/pull/44)) + +### Added + +- Composer: Added `Composer`, a message field that grows from 2 to 8 rows, with Send last and a status line under it ([#45](https://github.com/example/slate/pull/45), Linear [SL-120](https://linear.app/example/issue/SL-120)) +- Mention: Added `Mention` to show a name after @ and mark a mention of the reader when `you` is set ([#45](https://github.com/example/slate/pull/45)) +- Tokens: Added `--slate-plate` for a highlighted row's solid fill on its current surface level ([#46](https://github.com/example/slate/pull/46), Linear [DS-27](https://linear.app/example/issue/DS-27), Linear [DS-31](https://linear.app/example/issue/DS-31), Jira PRJ-90, GitHub [issue #45](https://github.com/example/slate/issues/45), Linear [SL-131](https://linear.app/example/issue/SL-131)) + +### Changed + +- Toast: Changed toasts on phones to sit 8px below the top bar instead of above the bottom tabs ([#47](https://github.com/example/slate/pull/47)) + +### Fixed + +- Checkbox: Fixed scrolling checkbox lists adding empty space below the page inside a sticky container ([#48](https://github.com/example/slate/pull/48), GitHub [issue #45](https://github.com/example/slate/issues/45)) +- Docs: Fixed the contrast table listing secondary ink on the sunken band at 4.1:1, where it measures 4.6:1 ([52ead666](https://github.com/example/slate/commit/52ead666ac257d2f3725d452ae5ddf9e2aed3e3a)) +- SelectList: Fixed keyboard focus leaving `SelectList` when the focused row was removed ([#49](https://github.com/example/slate/pull/49)) +- Sheet: Fixed clipped focus rings at the top and bottom of a sheet's scrolling body ([#49](https://github.com/example/slate/pull/49)) +- Sidebar: Fixed the brand mark sitting off center when the sidebar collapsed to its rail ([#50](https://github.com/example/slate/pull/50)) + +## 0.1.0 - 2026-11-02 + +The first version in this changelog. Earlier work is in the repository's history. diff --git a/tools/changelog/fixtures/slate/changelog.config.json b/tools/changelog/fixtures/slate/changelog.config.json new file mode 100644 index 00000000..22c0931b --- /dev/null +++ b/tools/changelog/fixtures/slate/changelog.config.json @@ -0,0 +1,33 @@ +{ + "product": "Slate", + "repository": "https://github.com/example/slate", + "trackers": [ + { + "name": "Linear", + "pattern": "(?:SL|DS)-[1-9][0-9]*", + "url": "https://linear.app/example/issue/{id}" + }, + { + "name": "Jira", + "pattern": "PRJ-[1-9][0-9]*", + "url": "https://example.atlassian.net/browse/{id}", + "show": "text" + }, + { + "name": "GitHub", + "pattern": "slate#(?[1-9][0-9]*)", + "url": "https://github.com/example/slate/issues/{n}", + "label": "issue #{n}" + }, + { + "name": "Support", + "pattern": "SUP-[1-9][0-9]*", + "show": "none" + } + ], + "people": { + "sam": { + "name": "Sam Rivera" + } + } +} diff --git a/tools/changelog/fixtures/slate/changelog/releases/0.1.0.json b/tools/changelog/fixtures/slate/changelog/releases/0.1.0.json new file mode 100644 index 00000000..55660d3a --- /dev/null +++ b/tools/changelog/fixtures/slate/changelog/releases/0.1.0.json @@ -0,0 +1,6 @@ +{ + "version": "0.1.0", + "date": "2026-11-02", + "summary": "The first version in this changelog. Earlier work is in the repository's history.", + "entries": [] +} diff --git a/tools/changelog/fixtures/slate/changelog/releases/0.2.0.json b/tools/changelog/fixtures/slate/changelog/releases/0.2.0.json new file mode 100644 index 00000000..56b93124 --- /dev/null +++ b/tools/changelog/fixtures/slate/changelog/releases/0.2.0.json @@ -0,0 +1,307 @@ +{ + "version": "0.2.0", + "date": "2026-11-16", + "previous": "0.1.0", + "summary": "Slate 0.2.0 adds a composer with mentions and a plate token for highlighted rows. Four changes to layout and stored data need a look before upgrading.", + "entries": [ + { + "id": "pr42-1", + "type": "changed", + "bump": "major", + "area": "fillForm", + "text": "Changed `fillForm` to keep null fields empty, so omit unknown fields or pass `undefined`", + "action": true, + "pr": { + "number": 42, + "href": "https://github.com/example/slate/pull/42" + }, + "commit": { + "sha": "c3b9399994e9c5bd188419bd1ffd5690aad75589", + "href": "https://github.com/example/slate/commit/c3b9399994e9c5bd188419bd1ffd5690aad75589" + } + }, + { + "id": "pr41-1", + "type": "changed", + "bump": "major", + "area": "Grid", + "text": "Changed the parent layout item for `Grid` to `.slate-grid-frame`, where existing sizing rules must move", + "action": true, + "link": { + "label": "How to migrate", + "href": "https://github.com/example/slate/blob/v0.2.0/docs/migrating.md#grid-frame" + }, + "pr": { + "number": 41, + "href": "https://github.com/example/slate/pull/41" + }, + "commit": { + "sha": "1b1a1576308eb1076a5aa2eb43ad7e7969a0f9de", + "href": "https://github.com/example/slate/commit/1b1a1576308eb1076a5aa2eb43ad7e7969a0f9de" + }, + "tickets": [ + { + "tracker": "Linear", + "id": "SL-112", + "label": "SL-112", + "show": "link", + "href": "https://linear.app/example/issue/SL-112" + }, + { + "tracker": "Jira", + "id": "PRJ-88", + "label": "PRJ-88", + "show": "text" + } + ], + "authors": [ + "Sam Rivera" + ] + }, + { + "id": "pr41-2", + "type": "changed", + "bump": "major", + "area": "storedCount", + "text": "Changed stored counts to require an explicit store, so pass `() => localStorage` when reading, writing or clearing old counts", + "action": true, + "link": { + "label": "How to migrate", + "href": "https://github.com/example/slate/blob/v0.2.0/docs/migrating.md#stored-counts" + }, + "pr": { + "number": 41, + "href": "https://github.com/example/slate/pull/41" + }, + "commit": { + "sha": "aec1f736bd0b0969da984872f8793217968b7694", + "href": "https://github.com/example/slate/commit/aec1f736bd0b0969da984872f8793217968b7694" + } + }, + { + "id": "pr43-1", + "type": "changed", + "bump": "major", + "area": "TableHeader", + "text": "Changed fixed `TableHeader` cells to show a supplied `hint`, so remove that prop where a header should stay plain", + "action": true, + "pr": { + "number": 43, + "href": "https://github.com/example/slate/pull/43" + }, + "commit": { + "sha": "fc0148481a9c5ba95e0b5d2dabd873cfa73532df", + "href": "https://github.com/example/slate/commit/fc0148481a9c5ba95e0b5d2dabd873cfa73532df" + } + }, + { + "id": "pr44-1", + "type": "deprecated", + "bump": "minor", + "area": "Banner", + "text": "Deprecated `Banner` in favor of `Notice`, which takes the same props, removed in 1.0.0 no earlier than Mar 1, 2027", + "pr": { + "number": 44, + "href": "https://github.com/example/slate/pull/44" + }, + "commit": { + "sha": "eca071c45b6c0141f05fb8b419af7e67857962d6", + "href": "https://github.com/example/slate/commit/eca071c45b6c0141f05fb8b419af7e67857962d6" + } + }, + { + "id": "pr45-1", + "type": "added", + "bump": "minor", + "area": "Composer", + "text": "Added `Composer`, a message field that grows from 2 to 8 rows, with Send last and a status line under it", + "pr": { + "number": 45, + "href": "https://github.com/example/slate/pull/45" + }, + "commit": { + "sha": "e641f77b510ba8971aef844024dcd41cfb833e02", + "href": "https://github.com/example/slate/commit/e641f77b510ba8971aef844024dcd41cfb833e02" + }, + "tickets": [ + { + "tracker": "Linear", + "id": "SL-120", + "label": "SL-120", + "show": "link", + "href": "https://linear.app/example/issue/SL-120" + } + ], + "authors": [ + "Sam Rivera" + ] + }, + { + "id": "pr45-2", + "type": "added", + "bump": "minor", + "area": "Mention", + "text": "Added `Mention` to show a name after @ and mark a mention of the reader when `you` is set", + "pr": { + "number": 45, + "href": "https://github.com/example/slate/pull/45" + }, + "commit": { + "sha": "5e1f6f1d3ed82af99639612755ac4c874d01f113", + "href": "https://github.com/example/slate/commit/5e1f6f1d3ed82af99639612755ac4c874d01f113" + } + }, + { + "id": "pr47-1", + "type": "changed", + "bump": "minor", + "area": "Toast", + "text": "Changed toasts on phones to sit 8px below the top bar instead of above the bottom tabs", + "pr": { + "number": 47, + "href": "https://github.com/example/slate/pull/47" + }, + "commit": { + "sha": "cf88219bf09469ab4ee79ff13f01b450d81ff3d5", + "href": "https://github.com/example/slate/commit/cf88219bf09469ab4ee79ff13f01b450d81ff3d5" + } + }, + { + "id": "pr46-1", + "type": "added", + "bump": "minor", + "area": "Tokens", + "text": "Added `--slate-plate` for a highlighted row's solid fill on its current surface level", + "pr": { + "number": 46, + "href": "https://github.com/example/slate/pull/46" + }, + "commit": { + "sha": "f56c4cb85c0d47be47322a741b7e25d16e7c8352", + "href": "https://github.com/example/slate/commit/f56c4cb85c0d47be47322a741b7e25d16e7c8352" + }, + "tickets": [ + { + "tracker": "Linear", + "id": "DS-27", + "label": "DS-27", + "show": "link", + "href": "https://linear.app/example/issue/DS-27" + }, + { + "tracker": "Linear", + "id": "DS-31", + "label": "DS-31", + "show": "link", + "href": "https://linear.app/example/issue/DS-31" + }, + { + "tracker": "Jira", + "id": "PRJ-90", + "label": "PRJ-90", + "show": "text" + }, + { + "tracker": "GitHub", + "id": "slate#45", + "label": "issue #45", + "show": "link", + "href": "https://github.com/example/slate/issues/45" + }, + { + "tracker": "Linear", + "id": "SL-131", + "label": "SL-131", + "show": "link", + "href": "https://linear.app/example/issue/SL-131" + }, + { + "tracker": "Support", + "id": "SUP-7", + "label": "SUP-7", + "show": "none" + } + ] + }, + { + "id": "pr48-1", + "type": "fixed", + "bump": "patch", + "area": "Checkbox", + "text": "Fixed scrolling checkbox lists adding empty space below the page inside a sticky container", + "pr": { + "number": 48, + "href": "https://github.com/example/slate/pull/48" + }, + "commit": { + "sha": "0dcee7ffc7519acff066200cf79fb6b0f3317114", + "href": "https://github.com/example/slate/commit/0dcee7ffc7519acff066200cf79fb6b0f3317114" + }, + "tickets": [ + { + "tracker": "GitHub", + "id": "slate#45", + "label": "issue #45", + "show": "link", + "href": "https://github.com/example/slate/issues/45" + } + ] + }, + { + "id": "docs-contrast-note", + "type": "fixed", + "bump": "patch", + "area": "Docs", + "text": "Fixed the contrast table listing secondary ink on the sunken band at 4.1:1, where it measures 4.6:1", + "commit": { + "sha": "52ead666ac257d2f3725d452ae5ddf9e2aed3e3a", + "href": "https://github.com/example/slate/commit/52ead666ac257d2f3725d452ae5ddf9e2aed3e3a" + } + }, + { + "id": "pr49-1", + "type": "fixed", + "bump": "patch", + "area": "SelectList", + "text": "Fixed keyboard focus leaving `SelectList` when the focused row was removed", + "pr": { + "number": 49, + "href": "https://github.com/example/slate/pull/49" + }, + "commit": { + "sha": "b10bb6bd1c92af9c6581dfefaacfe71376d3b4f3", + "href": "https://github.com/example/slate/commit/b10bb6bd1c92af9c6581dfefaacfe71376d3b4f3" + } + }, + { + "id": "pr49-2", + "type": "fixed", + "bump": "patch", + "area": "Sheet", + "text": "Fixed clipped focus rings at the top and bottom of a sheet's scrolling body", + "pr": { + "number": 49, + "href": "https://github.com/example/slate/pull/49" + }, + "commit": { + "sha": "7b6478fd517c65c3b8395d06ba590f93f1160c75", + "href": "https://github.com/example/slate/commit/7b6478fd517c65c3b8395d06ba590f93f1160c75" + } + }, + { + "id": "pr50-1", + "type": "fixed", + "bump": "patch", + "area": "Sidebar", + "text": "Fixed the brand mark sitting off center when the sidebar collapsed to its rail", + "pr": { + "number": 50, + "href": "https://github.com/example/slate/pull/50" + }, + "commit": { + "sha": "cc6365db1aa8887f71b6c00384ccdd013c51d664", + "href": "https://github.com/example/slate/commit/cc6365db1aa8887f71b6c00384ccdd013c51d664" + } + } + ] +} diff --git a/tools/changelog/fixtures/slate/changelog/releases/0.2.1.json b/tools/changelog/fixtures/slate/changelog/releases/0.2.1.json new file mode 100644 index 00000000..d4b4b957 --- /dev/null +++ b/tools/changelog/fixtures/slate/changelog/releases/0.2.1.json @@ -0,0 +1,22 @@ +{ + "version": "0.2.1", + "date": "2026-11-16", + "previous": "0.2.0", + "entries": [ + { + "id": "pr52-1", + "type": "fixed", + "bump": "patch", + "area": "Composer", + "text": "Fixed `Composer` losing its draft when the window lost focus", + "pr": { + "number": 52, + "href": "https://github.com/example/slate/pull/52" + }, + "commit": { + "sha": "8dd53e0a84b90794230c39970fb0b39b293a110f", + "href": "https://github.com/example/slate/commit/8dd53e0a84b90794230c39970fb0b39b293a110f" + } + } + ] +} diff --git a/tools/changelog/fixtures/slate/releases.json b/tools/changelog/fixtures/slate/releases.json new file mode 100644 index 00000000..c3d5e496 --- /dev/null +++ b/tools/changelog/fixtures/slate/releases.json @@ -0,0 +1,341 @@ +[ + { + "version": "Unreleased", + "unreleased": true, + "entries": [ + { + "id": "pr53-1", + "type": "changed", + "bump": "patch", + "area": "Chart", + "text": "Changed production builds to leave out development checks, so the minified `Chart` module is 3,227 bytes smaller", + "pr": { + "number": 53, + "href": "https://github.com/example/slate/pull/53" + } + }, + { + "id": "pr54-1", + "type": "fixed", + "bump": "patch", + "area": "Chart", + "text": "Fixed blurry labels on 1px chart lines when a label fell between whole pixels", + "pr": { + "number": 54, + "href": "https://github.com/example/slate/pull/54" + } + } + ] + }, + { + "version": "0.2.1", + "date": "2026-11-16", + "previous": "0.2.0", + "entries": [ + { + "id": "pr52-1", + "type": "fixed", + "bump": "patch", + "area": "Composer", + "text": "Fixed `Composer` losing its draft when the window lost focus", + "pr": { + "number": 52, + "href": "https://github.com/example/slate/pull/52" + }, + "commit": { + "sha": "8dd53e0a84b90794230c39970fb0b39b293a110f", + "href": "https://github.com/example/slate/commit/8dd53e0a84b90794230c39970fb0b39b293a110f" + } + } + ] + }, + { + "version": "0.2.0", + "date": "2026-11-16", + "previous": "0.1.0", + "summary": "Slate 0.2.0 adds a composer with mentions and a plate token for highlighted rows. Four changes to layout and stored data need a look before upgrading.", + "entries": [ + { + "id": "pr42-1", + "type": "changed", + "bump": "major", + "area": "fillForm", + "text": "Changed `fillForm` to keep null fields empty, so omit unknown fields or pass `undefined`", + "action": true, + "pr": { + "number": 42, + "href": "https://github.com/example/slate/pull/42" + }, + "commit": { + "sha": "c3b9399994e9c5bd188419bd1ffd5690aad75589", + "href": "https://github.com/example/slate/commit/c3b9399994e9c5bd188419bd1ffd5690aad75589" + } + }, + { + "id": "pr41-1", + "type": "changed", + "bump": "major", + "area": "Grid", + "text": "Changed the parent layout item for `Grid` to `.slate-grid-frame`, where existing sizing rules must move", + "action": true, + "link": { + "label": "How to migrate", + "href": "https://github.com/example/slate/blob/v0.2.0/docs/migrating.md#grid-frame" + }, + "pr": { + "number": 41, + "href": "https://github.com/example/slate/pull/41" + }, + "commit": { + "sha": "1b1a1576308eb1076a5aa2eb43ad7e7969a0f9de", + "href": "https://github.com/example/slate/commit/1b1a1576308eb1076a5aa2eb43ad7e7969a0f9de" + }, + "tickets": [ + { + "tracker": "Linear", + "label": "SL-112", + "href": "https://linear.app/example/issue/SL-112" + }, + { + "tracker": "Jira", + "label": "PRJ-88" + } + ], + "authors": [ + "Sam Rivera" + ] + }, + { + "id": "pr41-2", + "type": "changed", + "bump": "major", + "area": "storedCount", + "text": "Changed stored counts to require an explicit store, so pass `() => localStorage` when reading, writing or clearing old counts", + "action": true, + "link": { + "label": "How to migrate", + "href": "https://github.com/example/slate/blob/v0.2.0/docs/migrating.md#stored-counts" + }, + "pr": { + "number": 41, + "href": "https://github.com/example/slate/pull/41" + }, + "commit": { + "sha": "aec1f736bd0b0969da984872f8793217968b7694", + "href": "https://github.com/example/slate/commit/aec1f736bd0b0969da984872f8793217968b7694" + } + }, + { + "id": "pr43-1", + "type": "changed", + "bump": "major", + "area": "TableHeader", + "text": "Changed fixed `TableHeader` cells to show a supplied `hint`, so remove that prop where a header should stay plain", + "action": true, + "pr": { + "number": 43, + "href": "https://github.com/example/slate/pull/43" + }, + "commit": { + "sha": "fc0148481a9c5ba95e0b5d2dabd873cfa73532df", + "href": "https://github.com/example/slate/commit/fc0148481a9c5ba95e0b5d2dabd873cfa73532df" + } + }, + { + "id": "pr44-1", + "type": "deprecated", + "bump": "minor", + "area": "Banner", + "text": "Deprecated `Banner` in favor of `Notice`, which takes the same props, removed in 1.0.0 no earlier than Mar 1, 2027", + "pr": { + "number": 44, + "href": "https://github.com/example/slate/pull/44" + }, + "commit": { + "sha": "eca071c45b6c0141f05fb8b419af7e67857962d6", + "href": "https://github.com/example/slate/commit/eca071c45b6c0141f05fb8b419af7e67857962d6" + } + }, + { + "id": "pr45-1", + "type": "added", + "bump": "minor", + "area": "Composer", + "text": "Added `Composer`, a message field that grows from 2 to 8 rows, with Send last and a status line under it", + "pr": { + "number": 45, + "href": "https://github.com/example/slate/pull/45" + }, + "commit": { + "sha": "e641f77b510ba8971aef844024dcd41cfb833e02", + "href": "https://github.com/example/slate/commit/e641f77b510ba8971aef844024dcd41cfb833e02" + }, + "tickets": [ + { + "tracker": "Linear", + "label": "SL-120", + "href": "https://linear.app/example/issue/SL-120" + } + ], + "authors": [ + "Sam Rivera" + ] + }, + { + "id": "pr45-2", + "type": "added", + "bump": "minor", + "area": "Mention", + "text": "Added `Mention` to show a name after @ and mark a mention of the reader when `you` is set", + "pr": { + "number": 45, + "href": "https://github.com/example/slate/pull/45" + }, + "commit": { + "sha": "5e1f6f1d3ed82af99639612755ac4c874d01f113", + "href": "https://github.com/example/slate/commit/5e1f6f1d3ed82af99639612755ac4c874d01f113" + } + }, + { + "id": "pr47-1", + "type": "changed", + "bump": "minor", + "area": "Toast", + "text": "Changed toasts on phones to sit 8px below the top bar instead of above the bottom tabs", + "pr": { + "number": 47, + "href": "https://github.com/example/slate/pull/47" + }, + "commit": { + "sha": "cf88219bf09469ab4ee79ff13f01b450d81ff3d5", + "href": "https://github.com/example/slate/commit/cf88219bf09469ab4ee79ff13f01b450d81ff3d5" + } + }, + { + "id": "pr46-1", + "type": "added", + "bump": "minor", + "area": "Tokens", + "text": "Added `--slate-plate` for a highlighted row's solid fill on its current surface level", + "pr": { + "number": 46, + "href": "https://github.com/example/slate/pull/46" + }, + "commit": { + "sha": "f56c4cb85c0d47be47322a741b7e25d16e7c8352", + "href": "https://github.com/example/slate/commit/f56c4cb85c0d47be47322a741b7e25d16e7c8352" + }, + "tickets": [ + { + "tracker": "Linear", + "label": "DS-27", + "href": "https://linear.app/example/issue/DS-27" + }, + { + "tracker": "Linear", + "label": "DS-31", + "href": "https://linear.app/example/issue/DS-31" + }, + { + "tracker": "Jira", + "label": "PRJ-90" + }, + { + "tracker": "GitHub", + "label": "issue #45", + "href": "https://github.com/example/slate/issues/45" + }, + { + "tracker": "Linear", + "label": "SL-131", + "href": "https://linear.app/example/issue/SL-131" + } + ] + }, + { + "id": "pr48-1", + "type": "fixed", + "bump": "patch", + "area": "Checkbox", + "text": "Fixed scrolling checkbox lists adding empty space below the page inside a sticky container", + "pr": { + "number": 48, + "href": "https://github.com/example/slate/pull/48" + }, + "commit": { + "sha": "0dcee7ffc7519acff066200cf79fb6b0f3317114", + "href": "https://github.com/example/slate/commit/0dcee7ffc7519acff066200cf79fb6b0f3317114" + }, + "tickets": [ + { + "tracker": "GitHub", + "label": "issue #45", + "href": "https://github.com/example/slate/issues/45" + } + ] + }, + { + "id": "docs-contrast-note", + "type": "fixed", + "bump": "patch", + "area": "Docs", + "text": "Fixed the contrast table listing secondary ink on the sunken band at 4.1:1, where it measures 4.6:1", + "commit": { + "sha": "52ead666ac257d2f3725d452ae5ddf9e2aed3e3a", + "href": "https://github.com/example/slate/commit/52ead666ac257d2f3725d452ae5ddf9e2aed3e3a" + } + }, + { + "id": "pr49-1", + "type": "fixed", + "bump": "patch", + "area": "SelectList", + "text": "Fixed keyboard focus leaving `SelectList` when the focused row was removed", + "pr": { + "number": 49, + "href": "https://github.com/example/slate/pull/49" + }, + "commit": { + "sha": "b10bb6bd1c92af9c6581dfefaacfe71376d3b4f3", + "href": "https://github.com/example/slate/commit/b10bb6bd1c92af9c6581dfefaacfe71376d3b4f3" + } + }, + { + "id": "pr49-2", + "type": "fixed", + "bump": "patch", + "area": "Sheet", + "text": "Fixed clipped focus rings at the top and bottom of a sheet's scrolling body", + "pr": { + "number": 49, + "href": "https://github.com/example/slate/pull/49" + }, + "commit": { + "sha": "7b6478fd517c65c3b8395d06ba590f93f1160c75", + "href": "https://github.com/example/slate/commit/7b6478fd517c65c3b8395d06ba590f93f1160c75" + } + }, + { + "id": "pr50-1", + "type": "fixed", + "bump": "patch", + "area": "Sidebar", + "text": "Fixed the brand mark sitting off center when the sidebar collapsed to its rail", + "pr": { + "number": 50, + "href": "https://github.com/example/slate/pull/50" + }, + "commit": { + "sha": "cc6365db1aa8887f71b6c00384ccdd013c51d664", + "href": "https://github.com/example/slate/commit/cc6365db1aa8887f71b6c00384ccdd013c51d664" + } + } + ] + }, + { + "version": "0.1.0", + "date": "2026-11-02", + "summary": "The first version in this changelog. Earlier work is in the repository's history.", + "entries": [] + } +] diff --git a/tools/changelog/outputs.mjs b/tools/changelog/outputs.mjs new file mode 100644 index 00000000..b2fdd337 --- /dev/null +++ b/tools/changelog/outputs.mjs @@ -0,0 +1,87 @@ +// The outputs (DECISIONS 320, 3.4): CHANGELOG.md, the page's data and a GitHub Release's body, each generated from the records and the pending +// files and nothing else, with the same entries in the same order (2.7): Action needed, Security, Deprecated, Removed, Added, Changed, Fixed. +import { TYPES } from "./entries.mjs"; +import { byImpact } from "./records.mjs"; + +export const SECTION_NAMES = { action: "Action needed", security: "Security", deprecated: "Deprecated", removed: "Removed", added: "Added", changed: "Changed", fixed: "Fixed" }; + +/** A release's sections in order, each non-empty: the action entries first, then the rest by type. An action entry stands there and nowhere else. */ +export function sectionsOf(release) { + const out = []; + const action = release.entries.filter((entry) => entry.action).sort(byImpact); + if (action.length) out.push({ key: "action", entries: action }); + for (const type of TYPES) { + const entries = release.entries.filter((entry) => !entry.action && entry.type === type).sort(byImpact); + if (entries.length) out.push({ key: type, entries }); + } + return out; +} + +/** "Before upgrading from 0.1.0, check these 4 changes.": a package's callout opens with it, computed from the record. */ +export function upgradeLine(release) { + const count = release.entries.filter((entry) => entry.action).length; + if (!count || !release.previous) return null; + return `Before upgrading from ${release.previous}, check ${count === 1 ? "this change" : `these ${count} changes`}.`; +} + +const sources = (entry) => { + const parts = []; + if (entry.pr) parts.push(`[#${entry.pr.number}](${entry.pr.href})`); + for (const ticket of entry.tickets ?? []) parts.push(ticket.href ? `${ticket.tracker} [${ticket.label}](${ticket.href})` : `${ticket.tracker} ${ticket.label}`); + if (!parts.length && entry.commit) parts.push(`[${entry.commit.sha.slice(0, 8)}](${entry.commit.href})`); + return parts.length ? ` (${parts.join(", ")})` : ""; +}; + +/** One entry as a Markdown list item: the area, the sentence, the migration link, then its sources. */ +export function entryLine(entry) { + const area = entry.area ? `${entry.area}: ` : ""; + const link = entry.link ? ` [${entry.link.label}](${entry.link.href})` : ""; + return `- ${area}${entry.text}${link}${sources(entry)}`; +} + +/** + * A release's body in Markdown, as blocks. A release with a headline is a product's release notes: the headline and its paragraphs lead, then + * the summary, then the list. Any other is a package's: the summary, then the list. The list is always in the order of 2.7, Action needed + * first; a package's Action needed opens with the upgrade line. (On the page Action needed stands above a product's paragraphs; in Markdown a + * paragraph with no heading after it would read as part of that section, so the notes come first and the list keeps its order.) + */ +function releaseBody(release) { + const blocks = []; + const notes = Boolean(release.title); + if (release.title) blocks.push({ kind: "notes", text: `**${release.title}**` }); + for (const audience of release.audiences ?? []) blocks.push({ kind: "notes", text: audience.for ? `### ${audience.for}\n\n${audience.text}` : audience.text }); + if (release.summary) blocks.push({ kind: "notes", text: release.summary }); + for (const section of sectionsOf(release)) { + const opening = section.key === "action" && !notes ? upgradeLine(release) : null; + blocks.push({ kind: section.key, text: [`### ${SECTION_NAMES[section.key]}`, ...(opening ? ["", opening] : []), "", ...section.entries.map(entryLine)].join("\n") }); + } + return blocks; +} + +/** `CHANGELOG.md`: every drawn release, highest first, headed `## 1.4.0 - 2026-11-23` (S 4.2). */ +export function changelogMarkdown(releases, { product } = {}) { + const blocks = [`# Changelog`]; + if (product) blocks.push(`Every version of ${product}. This file is generated by \`tools/changelog\` from \`changelog/releases\` and \`.changes\`. Edit those, never this file.`); + for (const release of releases) { + blocks.push(release.unreleased ? "## Unreleased" : `## ${release.version} - ${release.date}`); + blocks.push(...releaseBody(release).map((block) => block.text)); + } + return `${blocks.join("\n\n")}\n`; +} + +/** A GitHub Release's body for one release: the notes, Action needed at the second level, then every other section under "Changes" (S 7.3). */ +export function githubBody(release, { repository } = {}) { + const blocks = []; + let changes = false; + for (const block of releaseBody(release)) { + if (block.kind === "action") blocks.push(block.text.replace(/^### /, "## ")); + else if (block.kind === "notes") blocks.push(block.text.replace(/^### /, "## ")); + else { + if (!changes) blocks.push("## Changes"); + changes = true; + blocks.push(block.text); + } + } + if (repository && release.previous) blocks.push(`Full diff: [v${release.previous}...v${release.version}](${repository}/compare/v${release.previous}...v${release.version})`); + return `${blocks.join("\n\n")}\n`; +} diff --git a/tools/changelog/records.mjs b/tools/changelog/records.mjs new file mode 100644 index 00000000..7de48439 --- /dev/null +++ b/tools/changelog/records.mjs @@ -0,0 +1,153 @@ +// The frozen records (DECISIONS 320, 3.4): `changelog/releases/.json`, one per release, written once by the freeze and never edited. +// Every output (CHANGELOG.md, the page's data, a GitHub Release's body) is generated from these and the pending files, and nothing else. +import fs from "node:fs"; +import path from "node:path"; + +import { commitHref, pullHref } from "./config.mjs"; +import { FLOOR, readPending, TYPES } from "./entries.mjs"; +import { atLeast, descending, must } from "./semver.mjs"; + +export const RECORDS_DIR = path.join("changelog", "releases"); +export const HOW_TO_MIGRATE = "How to migrate"; + +const RANK = { major: 0, minor: 1, patch: 2 }; + +/** Inside a section, entries stand by impact (the bump), then by area, then by id (S 4.4). */ +export function byImpact(a, b) { + return RANK[a.bump] - RANK[b.bump] || (a.area ?? "").localeCompare(b.area ?? "", "en") || a.id.localeCompare(b.id, "en"); +} + +/** Whether a string is a real calendar date written `YYYY-MM-DD`. */ +export function isDate(value) { + const match = /^([0-9]{4})-([0-9]{2})-([0-9]{2})$/.exec(String(value)); + if (!match) return false; + const [, y, m, d] = match.map(Number); + const day = new Date(Date.UTC(y, m - 1, d)); + return day.getUTCFullYear() === y && day.getUTCMonth() === m - 1 && day.getUTCDate() === d; +} + +/** + * Where an entry's migration note opens. An https address stays; a path from the site's root ("/docs/…") stays; any other is a file in the + * repository, opened at the release's tag (or the default branch's head while unreleased). + */ +export function migrationHref(migration, config, version) { + if (/^https:\/\//.test(migration) || migration.startsWith("/") || migration.startsWith("#")) return migration; + if (/^[a-z][a-z0-9+.-]*:/i.test(migration)) throw new Error(`migration "${migration}" is an https address, a path from the site's root, or a file in the repository`); + return `${config.repository}/blob/${version ? `v${version}` : "HEAD"}/${migration}`; +} + +/** An entry as a record holds it: the file's fields, with every address resolved, so the record alone rebuilds it. */ +export function recordEntry(entry, config, { version, commit } = {}) { + const out = { id: entry.id, type: entry.type, bump: entry.bump }; + if (entry.area) out.area = entry.area; + out.text = entry.text; + if (entry.action) out.action = true; + if (entry.migration) out.link = { label: HOW_TO_MIGRATE, href: migrationHref(entry.migration, config, version) }; + if (entry.pr) out.pr = { number: entry.pr, href: pullHref(config, entry.pr) }; + if (commit) out.commit = { sha: commit, href: commitHref(config, commit) }; + if (entry.tickets?.length) out.tickets = entry.tickets.map((ticket) => ({ ...ticket })); + if (entry.authors?.length) out.authors = [...entry.authors]; + return out; +} + +function checkRecord(record, file) { + const fail = (message) => { throw new Error(`${file}: ${message}`); }; + must(record.version, file); + if (path.basename(file) !== `${record.version}.json`) fail(`the file is named for its version, ${record.version}.json`); + if (!isDate(record.date)) fail(`"date" is a calendar date, YYYY-MM-DD`); + if (!Array.isArray(record.entries)) fail(`"entries" is a list`); + const ids = new Set(); + for (const entry of record.entries) { + if (ids.has(entry.id)) fail(`the entry id "${entry.id}" is used twice`); + ids.add(entry.id); + if (!TYPES.includes(entry.type)) fail(`entry "${entry.id}": type "${entry.type}"`); + const floor = FLOOR[entry.type]; + if (!entry.bump || (floor && !atLeast(entry.bump, floor))) fail(`entry "${entry.id}": the bump "${entry.bump}" is below its type's floor`); + } + for (const audience of record.audiences ?? []) { + if (!audience.covers?.length) fail(`a paragraph covers no entry`); + for (const id of audience.covers) if (!ids.has(id)) fail(`a paragraph covers "${id}", which is no entry of this release`); + } + return record; +} + +/** Every record in a repository, read and checked. */ +export function readRecords(root) { + const dir = path.join(root, RECORDS_DIR); + if (!fs.existsSync(dir)) return []; + const records = fs.readdirSync(dir) + .filter((name) => name.endsWith(".json")) + .map((name) => { + const file = path.join(RECORDS_DIR, name); + let record; + try { + record = JSON.parse(fs.readFileSync(path.join(root, file), "utf8")); + } catch (error) { + throw new Error(`${file}: not JSON: ${error.message}`); + } + return checkRecord(record, file); + }); + checkIds(records); + return records.sort((a, b) => descending(a.version, b.version)); +} + +/** Stop on an entry id held by two records, unless one of them replaces the other (a candidate and its stable release). */ +export function checkIds(records) { + const holder = new Map(); + for (const record of records) { + for (const entry of record.entries) { + const other = holder.get(entry.id); + if (other) { + const related = (other.replaces ?? []).includes(record.version) || (record.replaces ?? []).includes(other.version); + if (!related) throw new Error(`the entry id "${entry.id}" is held by ${other.version} and ${record.version}; an id is never used twice (a backport writes its own entry)`); + } + holder.set(entry.id, record); + } + } +} + +/** The versions a drawn release stands in for: the pre-releases its record replaces. */ +export function replacedVersions(records) { + return new Set(records.flatMap((record) => record.replaces ?? [])); +} + +/** A ticket as the page shows it: a hidden tracker's tickets are recorded and never published, and a text tracker's are not linked. */ +function pageTickets(tickets) { + const shown = (tickets ?? []).filter((ticket) => ticket.show !== "none"); + return shown.length ? shown.map((ticket) => (ticket.show === "link" && ticket.href ? { tracker: ticket.tracker, label: ticket.label, href: ticket.href } : { tracker: ticket.tracker, label: ticket.label })) : undefined; +} + +function pageEntry(entry) { + const out = { ...entry }; + const tickets = pageTickets(entry.tickets); + if (tickets) out.tickets = tickets; + else delete out.tickets; + return out; +} + +/** + * The page's data: the `ReleaseRecord[]` that `ReleaseNotes` takes, highest first, with the Unreleased section (the pending files that no + * pre-release record holds) on top when there is one. A pre-release whose stable version has shipped is not drawn: its address opens the + * stable release (`replaces`). `config` is read only for the pending files; a frozen release is drawn from its record alone. + */ +export function pageReleases(root, { config, records = readRecords(root), pending } = {}) { + const replaced = replacedVersions(records); + const drawn = records.filter((record) => !replaced.has(record.version)); + const out = []; + const held = new Set(records.filter((record) => must(record.version).pre.length).flatMap((record) => record.entries.map((entry) => entry.id))); + const waiting = (pending ?? (config ? readPending(root, config) : [])).filter((entry) => !held.has(entry.id)); + if (waiting.length) { + out.push({ version: "Unreleased", unreleased: true, entries: waiting.map((entry) => pageEntry(recordEntry(entry, config))).sort(byImpact) }); + } + for (const record of drawn) { + const release = { version: record.version, date: record.date }; + if (record.previous) release.previous = record.previous; + if (record.replaces?.length) release.replaces = [...record.replaces]; + if (record.title) release.title = record.title; + if (record.summary) release.summary = record.summary; + if (record.audiences?.length) release.audiences = record.audiences.map((audience) => ({ ...audience, covers: [...audience.covers] })); + release.entries = record.entries.map(pageEntry); + out.push(release); + } + return out; +} diff --git a/tools/changelog/release.mjs b/tools/changelog/release.mjs new file mode 100644 index 00000000..06afa189 --- /dev/null +++ b/tools/changelog/release.mjs @@ -0,0 +1,167 @@ +// Freezing a release (DECISIONS 320, 3.4): node tools/changelog/release.mjs --date +// Run on the branch the release is cut from: the default branch, or a maintained line's own (release/1.x). It reads the config and every pending +// file, checks the version against the entries and the releases in its line, resolves each entry's commit, writes the record once and, for a +// stable version, removes the pending files and regenerates CHANGELOG.md. The version is the owner's to give; the tool refuses one that +// understates the release. +import { execFileSync } from "node:child_process"; +import fs from "node:fs"; +import path from "node:path"; + +import { loadConfig } from "./config.mjs"; +import { CHANGES_DIR, NOTES_FILE, readPending, readPendingNotes } from "./entries.mjs"; +import { changelogMarkdown } from "./outputs.mjs"; +import { byImpact, isDate, pageReleases, readRecords, recordEntry, RECORDS_DIR } from "./records.mjs"; +import { atLeast, carries, compare, higher, least, line, must } from "./semver.mjs"; + +const RANK_WORD = { major: "a major", minor: "a minor", patch: "a patch" }; + +/** git in the repository, its output trimmed. */ +function git(root, args) { + return execFileSync("git", args, { cwd: root, encoding: "utf8", stdio: ["ignore", "pipe", "pipe"] }).trim(); +} + +/** + * The commit that put an entry on this branch: the first-parent commit that added its file. A merge counts as the commit that added it (its + * diff against its first parent), a squash or a rebased commit as itself. If that commit's subject names a different pull request, stop. + */ +export function entryCommit(root, entry) { + const file = `${CHANGES_DIR}/${entry.id}.md`; + const log = git(root, ["log", "--first-parent", "--full-history", "--diff-merges=first-parent", "--diff-filter=A", "--format=%H%x09%s", "--", file]); + const [first] = log.split("\n").filter(Boolean); + if (!first) throw new Error(`${file}: no commit on this branch added it; commit it first`); + const [sha, subject = ""] = first.split("\t"); + const named = /^Merge pull request #([0-9]+)\b/.exec(subject) ?? /\(#([0-9]+)\)\s*$/.exec(subject); + if (named && entry.pr && Number(named[1]) !== entry.pr) { + throw new Error(`${file}: says pull request ${entry.pr}, and the commit that added it (${sha.slice(0, 8)}) is "${subject}"`); + } + return sha; +} + +/** Check the version against the records and the entries (1.1). Returns the base it is measured from, or null for the first release. */ +export function checkVersion(version, records, entries) { + const next = must(version, "the version"); + if (next.pre.length) { + const kind = next.pre[0]; + if (kind === "canary") throw new Error(`${version}: a canary is a build from the default branch, with no freeze and no record`); + if (!(["beta", "rc"].includes(kind) && next.pre.length === 2 && /^[1-9][0-9]*$/.test(next.pre[1]))) { + throw new Error(`${version}: a frozen pre-release is -beta.N or -rc.N`); + } + } + if (records.some((record) => compare(record.version, version) === 0)) throw new Error(`${version} is published, and a published version is never edited`); + const ownLine = line(next); + const inLine = records.filter((record) => line(record.version) === ownLine); + const against = inLine.length ? inLine : records; + const above = against.filter((record) => compare(record.version, version) > 0).sort((a, b) => compare(b.version, a.version)); + if (above.length) { + throw new Error(inLine.length + ? `${version} is not higher than ${above[0].version}, released in its line (${ownLine}${ownLine.includes(".") ? ".x" : ".x.x"})` + : `${version} opens a line, so it must be higher than every release; ${above[0].version} is higher`); + } + const core = must(next.core); + const stableBelow = (list) => list.filter((record) => !must(record.version).pre.length && compare(record.version, core) < 0).sort((a, b) => compare(b.version, a.version))[0]; + const base = stableBelow(inLine) ?? stableBelow(records) ?? null; + if (!base) return null; + const needed = entries.reduce((most, entry) => higher(most, entry.bump), "patch"); + const carried = carries(base.version, core); + if (!entries.length) { + if (!carried) throw new Error(`${version} is not higher than ${base.version}`); + return base; + } + if (!carried || !atLeast(carried, needed)) { + const why = entries.filter((entry) => entry.bump === needed).map((entry) => entry.id).slice(0, 3).join(", "); + throw new Error(`${version} understates the release: from ${base.version} it needs ${RANK_WORD[needed]} (${why})${core.major === 0 ? ", one place right in 0.x" : ""}, so at least ${least(base.version, needed)}`); + } + return base; +} + +/** + * Freeze `version`, shipped on `date`. `root` is the repository. Returns what it wrote. Nothing is written until every check has passed. + */ +export function freeze({ root, version, date }) { + if (!isDate(date)) throw new Error(`--date "${date}" is a calendar date, YYYY-MM-DD`); + const config = loadConfig(root); + const records = readRecords(root); + const pending = readPending(root, config); + const ids = new Set(pending.map((entry) => entry.id)); + const notes = readPendingNotes(root, ids); + const next = must(version, "the version"); + const pre = next.pre.length > 0; + + // A pre-release takes what no earlier pre-release of its version holds; a stable version takes every pending file and replaces them. + const candidates = records.filter((record) => { const v = must(record.version); return v.pre.length && v.core === next.core; }); + const heldByCandidates = new Set(candidates.flatMap((record) => record.entries.map((entry) => entry.id))); + const taken = pre ? pending.filter((entry) => !heldByCandidates.has(entry.id)) : pending; + + const base = checkVersion(version, records, pending); + + // An id is never used twice: only a candidate that this stable release replaces may hold one of its entries. + const takenIds = new Set(taken.map((entry) => entry.id)); + for (const record of records) { + if (!pre && candidates.includes(record)) continue; + const clash = record.entries.find((entry) => takenIds.has(entry.id)); + if (clash) throw new Error(`${CHANGES_DIR}/${clash.id}.md: the id is already held by ${record.version}; a backport writes its own entry`); + } + + if (!taken.length && !notes?.summary) throw new Error(`${version} has no entries, so it needs a summary in ${CHANGES_DIR}/${NOTES_FILE} (no release is a heading over nothing)`); + if (taken.length > 3 && !notes?.summary && !notes?.audiences?.length) throw new Error(`${version} has ${taken.length} changes, so it needs a summary in ${CHANGES_DIR}/${NOTES_FILE}`); + + if (git(root, ["rev-parse", "--is-shallow-repository"]) === "true") throw new Error("this clone is shallow: fetch the whole history (git fetch --unshallow) so each entry's commit can be found"); + const entries = taken.map((entry) => recordEntry(entry, config, { version, commit: entryCommit(root, entry) })).sort(byImpact); + + const record = { version, date }; + if (base) record.previous = base.version; + if (!pre && candidates.length) record.replaces = candidates.map((candidate) => candidate.version).sort(compare); + if (notes?.title) record.title = notes.title; + if (notes?.summary) record.summary = notes.summary; + if (notes?.audiences) { + // A paragraph covers only what this release's own list holds (R18): a candidate is drawn with what it added, until its stable version ships. + const own = new Set(taken.map((entry) => entry.id)); + for (const audience of notes.audiences) for (const id of audience.covers) if (!own.has(id)) throw new Error(`${CHANGES_DIR}/${NOTES_FILE}: covers "${id}", which ${version} does not hold`); + record.audiences = notes.audiences; + } + record.entries = entries; + + const file = path.join(root, RECORDS_DIR, `${version}.json`); + if (fs.existsSync(file)) throw new Error(`${path.join(RECORDS_DIR, `${version}.json`)} exists; a record is written once and never overwritten`); + fs.mkdirSync(path.dirname(file), { recursive: true }); + fs.writeFileSync(file, `${JSON.stringify(record, null, 2)}\n`, { flag: "wx" }); + + const removed = []; + if (!pre) { + for (const entry of pending) { + fs.unlinkSync(path.join(root, CHANGES_DIR, `${entry.id}.md`)); + removed.push(`${CHANGES_DIR}/${entry.id}.md`); + } + if (notes) { + fs.unlinkSync(path.join(root, CHANGES_DIR, NOTES_FILE)); + removed.push(`${CHANGES_DIR}/${NOTES_FILE}`); + } + } + const releases = pageReleases(root, { config }); + fs.writeFileSync(path.join(root, "CHANGELOG.md"), changelogMarkdown(releases, { product: config.product })); + return { record, file, removed }; +} + +function main(argv) { + const args = [...argv]; + const at = args.indexOf("--date"); + const date = at >= 0 ? args.splice(at, 2)[1] : undefined; + const rootAt = args.indexOf("--root"); + const root = rootAt >= 0 ? path.resolve(args.splice(rootAt, 2)[1]) : process.cwd(); + const [version] = args; + if (!version || !date) { + process.stderr.write("usage: node tools/changelog/release.mjs --date [--root ]\n"); + process.exit(2); + } + try { + const { record, removed } = freeze({ root, version, date }); + process.stdout.write(`Wrote ${RECORDS_DIR}/${version}.json: ${record.entries.length} ${record.entries.length === 1 ? "entry" : "entries"}${record.previous ? `, from ${record.previous}` : ""}${record.replaces ? `, replacing ${record.replaces.join(", ")}` : ""}.\n`); + if (removed.length) process.stdout.write(`Removed ${removed.length} pending ${removed.length === 1 ? "file" : "files"} and regenerated CHANGELOG.md.\n`); + } catch (error) { + process.stderr.write(`${error.message}\n`); + process.exit(1); + } +} + +const { isMain } = await import("../../scripts/is-main.mjs"); +if (isMain(import.meta.url)) main(process.argv.slice(2)); diff --git a/tools/changelog/semver.mjs b/tools/changelog/semver.mjs new file mode 100644 index 00000000..f5e81123 --- /dev/null +++ b/tools/changelog/semver.mjs @@ -0,0 +1,98 @@ +// SemVer 2.0.0, as far as the changelog needs it: parsing, precedence, lines and bumps (DECISIONS 320, 1.1). No dependency. + +const NUMBER = "(0|[1-9][0-9]*)"; +const IDENT = "(?:0|[1-9][0-9]*|[0-9]*[A-Za-z-][0-9A-Za-z-]*)"; +const PATTERN = new RegExp(`^${NUMBER}\\.${NUMBER}\\.${NUMBER}(?:-(${IDENT}(?:\\.${IDENT})*))?(?:\\+([0-9A-Za-z-]+(?:\\.[0-9A-Za-z-]+)*))?$`); + +/** A parsed version, or null when the string is not SemVer 2.0.0. */ +export function parse(version) { + const match = PATTERN.exec(String(version)); + if (!match) return null; + const [, major, minor, patch, pre, build] = match; + return { + version: String(version), + major: Number(major), + minor: Number(minor), + patch: Number(patch), + pre: pre ? pre.split(".") : [], + build: build ?? null, + core: `${major}.${minor}.${patch}`, + }; +} + +/** Parse or stop with the reason. */ +export function must(version, where = "version") { + const parsed = parse(version); + if (!parsed) throw new Error(`${where}: "${version}" is not a SemVer version (MAJOR.MINOR.PATCH, a pre-release after a hyphen)`); + if (parsed.build) throw new Error(`${where}: "${version}" holds build metadata; a release's version never does`); + return parsed; +} + +const numeric = (id) => /^[0-9]+$/.test(id); + +/** SemVer precedence: negative when a is lower. Build metadata is ignored, so two builds of one version compare equal. */ +export function compare(a, b) { + const x = typeof a === "string" ? must(a) : a; + const y = typeof b === "string" ? must(b) : b; + for (const key of ["major", "minor", "patch"]) if (x[key] !== y[key]) return x[key] - y[key]; + if (!x.pre.length || !y.pre.length) return (y.pre.length ? 1 : 0) - (x.pre.length ? 1 : 0); + for (let index = 0; index < Math.max(x.pre.length, y.pre.length); index++) { + const p = x.pre[index]; + const q = y.pre[index]; + if (p === undefined) return -1; + if (q === undefined) return 1; + if (p === q) continue; + if (numeric(p) && numeric(q)) return Number(p) - Number(q); + if (numeric(p)) return -1; + if (numeric(q)) return 1; + return p < q ? -1 : 1; + } + return 0; +} + +/** Highest first. */ +export const descending = (a, b) => compare(b, a); + +/** + * A version's line: the versions that share their breaking number, the major, or in 0.x the minor (1.1). "1", "0.2". + */ +export function line(version) { + const v = typeof version === "string" ? must(version) : version; + return v.major === 0 ? `0.${v.minor}` : String(v.major); +} + +export const BUMPS = ["patch", "minor", "major"]; +const RANK = { patch: 1, minor: 2, major: 3 }; + +/** The higher of two bumps. */ +export const higher = (a, b) => (RANK[a] >= RANK[b] ? a : b); + +/** Whether `bump` is at least `floor`. */ +export const atLeast = (bump, floor) => RANK[bump] >= RANK[floor]; + +/** + * What moving from `base` to `next` (cores only) says, as the bump it can carry. From 1.0, the number that moved. In 0.x the numbers move one + * place right: the minor is the breaking number and the patch carries everything else, so a patch there may carry a minor's entries. + */ +export function carries(base, next) { + const from = typeof base === "string" ? must(base) : base; + const to = typeof next === "string" ? must(next) : next; + if (to.major !== from.major) return to.major > from.major ? "major" : null; + if (to.minor !== from.minor) { + if (to.minor < from.minor) return null; + return to.major === 0 ? "major" : "minor"; + } + if (to.patch > from.patch) return to.major === 0 ? "minor" : "patch"; + return null; +} + +/** The smallest version after `base` that carries `bump`: what the tool suggests when it refuses a version. */ +export function least(base, bump) { + const from = typeof base === "string" ? must(base) : base; + if (from.major === 0) { + return bump === "major" ? `0.${from.minor + 1}.0` : `0.${from.minor}.${from.patch + 1}`; + } + if (bump === "major") return `${from.major + 1}.0.0`; + if (bump === "minor") return `${from.major}.${from.minor + 1}.0`; + return `${from.major}.${from.minor}.${from.patch + 1}`; +} diff --git a/tools/changelog/test/audit.test.mjs b/tools/changelog/test/audit.test.mjs new file mode 100644 index 00000000..d8e0cca3 --- /dev/null +++ b/tools/changelog/test/audit.test.mjs @@ -0,0 +1,97 @@ +// DECISIONS 320, 4: the audit runs the lines the skill marks (m). It flags and a person decides. The check's false positives must not flag; its +// true ones must. +import assert from "node:assert/strict"; +import fs from "node:fs"; +import path from "node:path"; +import { test } from "node:test"; +import { fileURLToPath } from "node:url"; + +import { audit, auditEntry, auditRecord } from "../audit.mjs"; +import { readConfig } from "../config.mjs"; +import { CONFIG, repository, tempDir, writeRecord } from "./support.mjs"; + +const config = readConfig(CONFIG); +const FIXTURES = path.join(path.dirname(fileURLToPath(import.meta.url)), "..", "fixtures"); +const rules = (text, more = {}) => auditEntry({ id: "x", type: "fixed", bump: "patch", text, ...more }, config).map((flag) => flag.rule); + +test("the check's false positives do not flag", () => { + // R6 accepts old and new in any wording: "which before" is not a flag. + assert.deepEqual(rules("Changed the default gap to 12px, which before was 8px", { type: "changed", bump: "minor" }), []); + // An entry with nothing that has an identifier needs no code formatting. + assert.deepEqual(rules("Fixed the brand mark sitting off center when the sidebar collapsed to its rail"), []); + // Under 12 words is a prompt to look, not a failure. + assert.deepEqual(rules("Fixed `/hooks` losing your place when going back"), []); + // A spelling inside code is the identifier as exported. + assert.deepEqual(rules("Added `NotificationCenter` as the US spelling of `NotificationCentre`", { type: "added", bump: "minor" }), []); + // A dated removal may use the future tense. + assert.deepEqual(rules("Deprecated `Banner` in favor of `Notice`, which will be removed in 2.0.0 no earlier than Mar 1, 2027", { type: "deprecated", bump: "minor" }), []); + // A product's quoted label and a GitHub issue written as repo#45 in a sentence are not pull request numbers. + assert.deepEqual(rules("Fixed \"Waiting to be admitted\" staying on screen after the commander had admitted you"), []); +}); + +test("the check's true positives flag, each with its rule", () => { + assert.deepEqual(rules("Bug fixes and performance improvements"), ["R1", "R9", "R9"]); + assert.deepEqual(rules("Fixed the list losing its place when a row was removed (ENG-398)"), ["R14"]); + assert.deepEqual(rules("Fixed the list losing its place when a row was removed."), ["R3"]); + const thirtyOne = `Fixed ${Array.from({ length: 30 }, (_, index) => `word${index}`).join(" ")}`; + assert.deepEqual(rules(thirtyOne), ["R3"]); + const thirty = `Fixed ${Array.from({ length: 29 }, (_, index) => `word${index}`).join(" ")}`; + assert.deepEqual(rules(thirty), []); +}); + +test("the other marked lines: banned words, punctuation, emoji, British spelling, future tense, numbers and names in the words", () => { + assert.deepEqual(rules("Added a seamless, powerful composer", { type: "added", bump: "minor" }), ["R10", "R10"]); + assert.deepEqual(rules("Fixed the composer!"), ["R10"]); + assert.deepEqual(rules("Fixed the composer — it lost drafts"), ["R15"]); + assert.deepEqual(rules("Fixed the composer; it lost drafts"), ["R15"]); + assert.deepEqual(rules("Fixed the composer losing drafts 🎉"), ["R15"]); + assert.deepEqual(rules("Fixed the colour of a cancelled run"), ["R15"]); + assert.deepEqual(rules("Fixed the list, which will now keep its place"), ["R11"]); + assert.deepEqual(rules("Fixed the list losing its place, from #120"), ["R14"]); + assert.deepEqual(rules("Fixed the list losing its place, reported in PR 120"), ["R14"]); + assert.deepEqual(rules("Fixed the list losing its place, reported by Sam Rivera"), ["R14"]); + assert.deepEqual(rules("Fixed the list losing its place, see repo#45"), ["R14"]); + assert.deepEqual(rules("The list now keeps its place"), ["R1"]); +}); + +test("the version lines: a bump below the floor, a Changed entry with none, a major entry that is not action", () => { + assert.deepEqual(rules("Changed the toast's place", { type: "changed", bump: undefined }), ["Version"]); + assert.deepEqual(rules("Added `Stepper`", { type: "added", bump: "patch" }), ["Version"]); + assert.deepEqual(rules("Changed the default gap to 12px instead of 8px", { type: "changed", bump: "major" }), ["Version"]); +}); + +test("a release: the bump it carries, the pre-release's form and a stable release holding its candidates' entries", () => { + const entry = (id, bump) => ({ id, type: bump === "minor" ? "added" : "fixed", bump, text: "Fixed it" }); + assert.deepEqual(auditRecord({ version: "1.4.1", date: "2026-11-23", previous: "1.4.0", entries: [entry("a", "minor")] }, []).map((flag) => flag.message), ["1.4.1 from 1.4.0 does not carry the minor its entries need"]); + assert.deepEqual(auditRecord({ version: "0.2.1", date: "2026-11-23", previous: "0.2.0", entries: [entry("a", "minor")] }, []), []); + assert.deepEqual(auditRecord({ version: "2.0.0-alpha.1", date: "2026-11-23", entries: [] }, []).map((flag) => flag.rule), ["Version"]); + const rc = { version: "2.0.0-rc.1", date: "2026-12-01", entries: [entry("a", "patch"), entry("b", "patch")] }; + const stable = { version: "2.0.0", date: "2026-12-07", previous: "1.4.0", replaces: ["2.0.0-rc.1"], entries: [entry("a", "patch")] }; + assert.deepEqual(auditRecord(stable, [rc, stable]).map((flag) => flag.message), ['2.0.0-rc.1 held "b", which 2.0.0 does not: was it taken out on purpose?']); +}); + +test("the fixtures pass the audit, and a repository's flags name where they are", () => { + assert.deepEqual(audit(path.join(FIXTURES, "slate")), []); + assert.deepEqual(audit(path.join(FIXTURES, "harbor")), []); + const copy = path.join(tempDir(), "slate"); + fs.cpSync(path.join(FIXTURES, "slate"), copy, { recursive: true }); + fs.writeFileSync(path.join(copy, ".changes", "pr55-1.md"), "---\ntype: fixed\narea: Chart\npr: 55\n---\nFixed the chart.\n"); + fs.writeFileSync(path.join(copy, ".changes", "pr56-1.md"), "---\ntype: fixed\npr: 56\ntickets: [XX-1]\n---\nFixed the chart\n"); + const flags = audit(copy); + assert.deepEqual(flags.map((flag) => [flag.where, flag.rule]), [ + [".changes/pr56-1.md", "Each entry"], + [".changes/pr55-1.md", "R3"], + ["CHANGELOG.md", "Structure"], + ]); + assert.match(flags[0].message, /ticket "XX-1" matches no tracker/); +}); + +test("an area on every entry when any has one, and a tagged record that changed", () => { + const repo = repository(); + writeRecord(repo.dir, { version: "1.0.0", date: "2026-11-20", entries: [{ id: "a", type: "fixed", bump: "patch", area: "List", text: "Fixed the list losing its place" }, { id: "b", type: "fixed", bump: "patch", text: "Fixed the sheet losing its place" }] }); + repo.commitAll("Release 1.0.0"); + repo.git("tag", "v1.0.0"); + writeRecord(repo.dir, { version: "1.0.0", date: "2026-11-21", entries: [{ id: "a", type: "fixed", bump: "patch", area: "List", text: "Fixed the list losing its place" }, { id: "b", type: "fixed", bump: "patch", text: "Fixed the sheet losing its place" }] }); + const flags = audit(repo.dir); + assert.deepEqual(flags.map((flag) => [flag.where, flag.rule]), [["1.0.0 b", "Structure"], ["records", "Version"]]); +}); diff --git a/tools/changelog/test/config.test.mjs b/tools/changelog/test/config.test.mjs new file mode 100644 index 00000000..fbe7722b --- /dev/null +++ b/tools/changelog/test/config.test.mjs @@ -0,0 +1,81 @@ +// DECISIONS 320, 3.2: the tracker config is read and checked before any entry. +import assert from "node:assert/strict"; +import { test } from "node:test"; + +import { readConfig, resolveTicket } from "../config.mjs"; +import { CONFIG, stops } from "./support.mjs"; + +const one = (tracker) => readConfig({ product: "Example", repository: "https://github.com/example/repo", trackers: [tracker] }); + +test("a pattern written with ^ or $ is refused: the tool matches the whole id", () => { + assert.match(stops(() => one({ name: "Tracker", pattern: "^T-[1-9][0-9]*", url: "https://t.example/{id}" })), /without \^ and \$/); + assert.match(stops(() => one({ name: "Tracker", pattern: "T-[1-9][0-9]*$", url: "https://t.example/{id}" })), /without \^ and \$/); +}); + +test("the whole id is matched, so a pattern never matches part of one", () => { + const config = one({ name: "Tracker", pattern: "T-[1-9][0-9]*", url: "https://t.example/{id}" }); + assert.equal(resolveTicket("T-7", config, "f").id, "T-7"); + assert.match(stops(() => resolveTicket("XT-7", config, "f")), /matches no tracker/); + assert.match(stops(() => resolveTicket("T-7x", config, "f")), /matches no tracker/); +}); + +test("a variable that is neither {id} nor a named group is refused when the config is read", () => { + const message = stops(() => one({ name: "Tracker", pattern: "T-[0-9]+", url: "https://t.example/{n}" })); + assert.match(message, /"\{n\}".*neither \{id\} nor a named group/); + assert.match(stops(() => one({ name: "Tracker", pattern: "T-[0-9]+", url: "https://t.example/{id}", label: "T {num}" })), /"\{num\}" in "label"/); +}); + +test("a variable in the host, http and a non-web scheme are refused", () => { + assert.match(stops(() => one({ name: "Tracker", pattern: "(?[a-z]+)-[0-9]+", url: "https://{team}.example/{id}" })), /variable in its host/); + assert.match(stops(() => one({ name: "Tracker", pattern: "T-[0-9]+", url: "http://t.example/{id}" })), /must be https/); + assert.match(stops(() => one({ name: "Tracker", pattern: "T-[0-9]+", url: "javascript:alert({id})" })), /must be https/); + assert.match(stops(() => readConfig({ product: "Example", repository: "http://github.com/example/repo" })), /must be https/); +}); + +test("a name used twice is refused", () => { + const message = stops(() => readConfig({ product: "Example", repository: "https://github.com/example/repo", trackers: [ + { name: "Linear", pattern: "ENG-[1-9][0-9]*", url: "https://a.example/{id}" }, + { name: "Linear", pattern: "DES-[1-9][0-9]*", url: "https://b.example/{id}" }, + ] })); + assert.match(message, /"Linear" is used twice/); +}); + +test("an unknown key, a pattern that does not compile and a linked tracker with no url are refused", () => { + assert.match(stops(() => one({ name: "Tracker", pattern: "T-[0-9]+", url: "https://t.example/{id}", colour: "red" })), /unknown key "colour"/); + assert.match(stops(() => one({ name: "Tracker", pattern: "T-[0-9+", url: "https://t.example/{id}" })), /does not compile/); + assert.match(stops(() => one({ name: "Tracker", pattern: "T-[0-9]+" })), /needs "url"/); + assert.match(stops(() => readConfig({ product: "Example", repository: "https://github.com/example/repo", extra: 1 })), /unknown key "extra"/); +}); + +test("{id} is replaced at every occurrence, and percent-encoded in the URL", () => { + const config = one({ name: "Tracker", pattern: "T-[1-9][0-9]*", url: "https://t.example/{id}/view?key={id}" }); + assert.equal(resolveTicket("T-7", config, "f").href, "https://t.example/T-7/view?key=T-7"); + const loose = one({ name: "Loose", pattern: "[a-z/?#]+", url: "https://t.example/browse/{id}" }); + assert.equal(resolveTicket("a/b?c#d", loose, "f").href, "https://t.example/browse/a%2Fb%3Fc%23d"); +}); + +test("a named group fills the url and the label", () => { + const config = readConfig(CONFIG); + const ticket = resolveTicket("repo#45", config, "f"); + assert.deepEqual(ticket, { tracker: "GitHub", id: "repo#45", label: "issue #45", show: "link", href: "https://github.com/example/repo/issues/45" }); +}); + +test("show: link (the default) links the id, text shows it unlinked, none records it and is not published", () => { + const config = readConfig({ product: "Example", repository: "https://github.com/example/repo", trackers: [ + { name: "Linear", pattern: "ENG-[1-9][0-9]*", url: "https://linear.app/example/issue/{id}" }, + { name: "Jira", pattern: "PROJ-[1-9][0-9]*", url: "https://example.atlassian.net/browse/{id}", show: "text" }, + { name: "Support", pattern: "SUP-[1-9][0-9]*", show: "none" }, + ] }); + assert.equal(resolveTicket("ENG-1", config, "f").href, "https://linear.app/example/issue/ENG-1"); + assert.equal(resolveTicket("PROJ-2", config, "f").href, undefined); + assert.equal(resolveTicket("PROJ-2", config, "f").show, "text"); + assert.equal(resolveTicket("SUP-3", config, "f").show, "none"); + assert.match(stops(() => one({ name: "Tracker", pattern: "T-[0-9]+", url: "https://t.example/{id}", show: "hidden" })), /link, text or none/); +}); + +test("people are keys with a name; the config needs a product and a repository", () => { + assert.match(stops(() => readConfig({ repository: "https://github.com/example/repo" })), /product/); + assert.match(stops(() => readConfig({ product: "Example" })), /repository/); + assert.match(stops(() => readConfig({ product: "Example", repository: "https://github.com/example/repo", people: { Sam: { name: "Sam" } } })), /lowercase/); + assert.match(stops(() => readConfig({ product: "Example", repository: "https://github.com/example/repo", people: { sam: {} } })), /"name" is required/); +}); diff --git a/tools/changelog/test/entries.test.mjs b/tools/changelog/test/entries.test.mjs new file mode 100644 index 00000000..ff1d338a --- /dev/null +++ b/tools/changelog/test/entries.test.mjs @@ -0,0 +1,134 @@ +// DECISIONS 320, 3.3 and 3.4: an id is read from one place, the `tickets` field of the entry's own file. Every row of 3.3's table, by its input and +// its message; the head's grammar; the id against the file's name; the bump and the author. +import assert from "node:assert/strict"; +import { test } from "node:test"; + +import { readConfig } from "../config.mjs"; +import { readEntry, readNotes } from "../entries.mjs"; +import { CONFIG, entryText, stops } from "./support.mjs"; + +const config = readConfig(CONFIG); +const FILE = ".changes/pr120-1.md"; +const head = (tickets, more = {}) => ({ type: "changed", area: "FormGrid", pr: 120, bump: "major", action: true, ...(tickets === null ? {} : { tickets }), ...more }); +const SENTENCE = "Changed the parent layout item for `FormGrid` to `.basalt-form-grid-frame`, where existing sizing rules must move"; +const read = (source, file = FILE) => readEntry(source, file, config); +const ids = (source, file) => (read(source, file).tickets ?? []).map((ticket) => ticket.id); + +test("the entry says ENG-398, the pull request's body PROJ-88 and a trailer DES-27: only the entry's field is read", () => { + // The body and the trailer are not inputs at all: the reader takes the file and nothing else. Words that look like them are words. + const source = entryText(head("[ENG-398]"), `${SENTENCE}\n\nTickets: PROJ-88\nRefs: DES-27`); + assert.deepEqual(ids(source), ["ENG-398"]); +}); + +test("an empty list and an absent field are the same: no tickets, and nothing to fall back to", () => { + assert.deepEqual(ids(entryText(head("[]"), SENTENCE)), []); + assert.deepEqual(ids(entryText(head(null), SENTENCE)), []); + assert.equal(read(entryText(head(null), SENTENCE)).tickets, undefined); +}); + +test("two entries in one pull request each keep their own list", () => { + assert.deepEqual(ids(entryText(head("[ENG-398]"), SENTENCE), ".changes/pr120-1.md"), ["ENG-398"]); + assert.deepEqual(ids(entryText(head(null), SENTENCE), ".changes/pr120-2.md"), []); +}); + +test("a quoted Tickets: example and a fenced template in the words are words: only the head is read", () => { + const source = `${entryText(head("[PROJ-88]"), SENTENCE)}\nWrite \`Tickets: ENG-1\` in the body.\n\n\`\`\`\ntickets: [ENG-2]\n\`\`\`\n`; + assert.deepEqual(ids(source), ["PROJ-88"]); +}); + +test("two tickets fields stop, naming the file and the line", () => { + const source = `---\ntype: fixed\npr: 120\ntickets: [ENG-398]\ntickets: [PROJ-88]\n---\nFixed the list\n`; + assert.equal(stops(() => read(source)), `${FILE}:5: "tickets" is written twice`); +}); + +test("eng-398, an en dash, #45 and other#45 match no tracker: the message names the file, the id and the trackers", () => { + for (const id of ["eng-398", "ENG–398", "#45", "other#45"]) { + assert.equal(stops(() => read(entryText(head(`[${id}]`), SENTENCE))), `${FILE}: ticket "${id}" matches no tracker (Linear, Jira, GitHub)`); + } +}); + +test("a trailing comma is an empty item, and a duplicate is listed twice", () => { + assert.match(stops(() => read(entryText(head("[ENG-398,]"), SENTENCE))), /^\.changes\/pr120-1\.md:\d+: "tickets" has an empty item/); + assert.match(stops(() => read(entryText(head("[ENG-398, ENG-398]"), SENTENCE))), /"ENG-398" is listed twice in "tickets"/); +}); + +test("spaces around an id are trimmed; a space inside one stops", () => { + assert.deepEqual(ids(entryText(head("[ ENG-398 , PROJ-88 ]"), SENTENCE)), ["ENG-398", "PROJ-88"]); + assert.match(stops(() => read(entryText(head("[ENG 398]"), SENTENCE))), /"ENG 398" in "tickets" holds a space/); +}); + +test("ENG-0398 and ENG-0 stop under the documented number pattern", () => { + for (const id of ["ENG-0398", "ENG-0"]) assert.match(stops(() => read(entryText(head(`[${id}]`), SENTENCE))), new RegExp(`ticket "${id}" matches no tracker`)); +}); + +test("a second tracker that also claims ENG- ids stops, naming both", () => { + const two = readConfig({ ...CONFIG, trackers: [CONFIG.trackers[0], { name: "Tracker 2", pattern: "ENG-[0-9]+", url: "https://t2.example/{id}" }] }); + assert.equal(stops(() => readEntry(entryText(head("[ENG-398]"), SENTENCE), FILE, two)), `${FILE}: ticket "ENG-398" matches 2 trackers (Linear, Tracker 2)`); +}); + +test("tickets keep the order written, each resolved to its tracker, label and address", () => { + const entry = read(entryText(head("[PROJ-88, repo#45, ENG-398]"), SENTENCE)); + assert.deepEqual(entry.tickets, [ + { tracker: "Jira", id: "PROJ-88", label: "PROJ-88", show: "text" }, + { tracker: "GitHub", id: "repo#45", label: "issue #45", show: "link", href: "https://github.com/example/repo/issues/45" }, + { tracker: "Linear", id: "ENG-398", label: "ENG-398", show: "link", href: "https://linear.app/example/issue/ENG-398" }, + ]); +}); + +test("the head's grammar: --- first, closed, key: value lines, known keys only, a list in brackets", () => { + assert.equal(stops(() => read("type: fixed\n---\nFixed it\n")), `${FILE}:1: the file starts with "---"`); + assert.equal(stops(() => read("---\ntype: fixed\nFixed it\n")), `${FILE}: the head is not closed with "---"`); + assert.match(stops(() => read("---\ntype fixed\n---\nFixed it\n")), /pr120-1\.md:2: not a "key: value" line/); + assert.match(stops(() => read("---\ntype: fixed\npr: 120\nTickets: [ENG-1]\n---\nFixed it\n")), /:4: not a "key: value" line/); + assert.match(stops(() => read("---\ntype: fixed\npr: 120\nreviewer: sam\n---\nFixed it\n")), /:4: unknown key "reviewer"/); + assert.match(stops(() => read(entryText(head("ENG-398"), SENTENCE))), /"tickets" is a list in square brackets/); + assert.match(stops(() => read("---\ntype: fixed\npr: 120\n---\n\n")), /the entry's sentence is missing/); + assert.match(stops(() => read("---\ntype: improved\npr: 120\n---\nImproved it\n")), /type "improved" is one of security, deprecated, removed, added, changed, fixed/); +}); + +test("the id is the file's name: pr120-1.md says pr: 120; a slug is lowercase; unreleased and v-digit ids are reserved", () => { + assert.equal(stops(() => read(entryText({ type: "fixed", pr: 121 }), FILE)), `${FILE}: the file is named for pull request 120, so it says "pr: 120", not 121`); + assert.match(stops(() => read(entryText({ type: "fixed" }), FILE)), /so it says "pr: 120"$/); + assert.equal(read(entryText({ type: "fixed" }), ".changes/docs-contrast-note.md").id, "docs-contrast-note"); + assert.match(stops(() => read(entryText({ type: "fixed" }), ".changes/Docs_Note.md")), /lowercase letters, digits and hyphens/); + assert.match(stops(() => read(entryText({ type: "fixed" }), ".changes/unreleased.md")), /reserved/); + assert.match(stops(() => read(entryText({ type: "fixed" }), ".changes/v1-fix.md")), /reserved/); + assert.match(stops(() => read(entryText({ type: "fixed", pr: "12a" }), ".changes/fix-12.md")), /"pr" is the pull request's number/); +}); + +test("the bump: each type's floor, a Changed entry states its own, and a major entry is action", () => { + assert.equal(read(entryText({ type: "added", pr: 120 })).bump, "minor"); + assert.equal(read(entryText({ type: "deprecated", pr: 120 })).bump, "minor"); + assert.equal(read(entryText({ type: "fixed", pr: 120 })).bump, "patch"); + assert.equal(read(entryText({ type: "security", pr: 120 })).bump, "patch"); + assert.equal(read(entryText({ type: "removed", pr: 120, action: true })).bump, "major"); + assert.equal(read(entryText({ type: "fixed", pr: 120, bump: "minor" })).bump, "minor"); + assert.match(stops(() => read(entryText({ type: "changed", pr: 120 }))), /a changed entry states its bump/); + assert.match(stops(() => read(entryText({ type: "added", pr: 120, bump: "patch" }))), /an? added entry needs at least a minor/); + assert.match(stops(() => read(entryText({ type: "removed", pr: 120 }))), /a major entry is always "action: true"/); + assert.match(stops(() => read(entryText({ type: "changed", pr: 120, bump: "major" }))), /a major entry is always "action: true"/); + assert.match(stops(() => read(entryText({ type: "fixed", pr: 120, action: "yes" }))), /"action" is true or false/); + // A deprecation marked action is a minor: action raises nothing. + const deprecation = read(entryText({ type: "deprecated", pr: 120, action: true })); + assert.equal(deprecation.bump, "minor"); + assert.equal(deprecation.action, true); +}); + +test("the author is a key of the config's people, optional; an unknown key stops", () => { + assert.deepEqual(read(entryText({ type: "fixed", pr: 120, author: "sam" })).authors, ["Sam Rivera"]); + assert.equal(read(entryText({ type: "fixed", pr: 120 })).authors, undefined); + assert.match(stops(() => read(entryText({ type: "fixed", pr: 120, author: "octocat" }))), /author "octocat" is not a key of the config's "people" \(sam\)/); +}); + +test("the release notes: each paragraph opens with covers, names entries that exist, and covers at least one", () => { + const entries = new Set(["pr131-1", "pr131-2"]); + const notes = readNotes("---\ntitle: A monitor can open an incident room\n---\ncovers: [pr131-1]\nA monitor can open a room.\n\n## For admins\ncovers: [pr131-1, pr131-2]\nIn Settings, open Integrations.\n", ".changes/release.md", entries); + assert.deepEqual(notes, { title: "A monitor can open an incident room", audiences: [ + { text: "A monitor can open a room.", covers: ["pr131-1"] }, + { for: "For admins", text: "In Settings, open Integrations.", covers: ["pr131-1", "pr131-2"] }, + ] }); + assert.match(stops(() => readNotes("---\n---\ncovers: []\nA claim.\n", ".changes/release.md", entries)), /covers no entry/); + assert.match(stops(() => readNotes("---\n---\ncovers: [pr999-1]\nA claim.\n", ".changes/release.md", entries)), /covers "pr999-1", which is no entry/); + assert.match(stops(() => readNotes("---\n---\nA claim with no covers line.\n", ".changes/release.md", entries)), /opens with a "covers: \[ids\]" line/); + assert.match(stops(() => readNotes("---\n---\n## For admins\n\n", ".changes/release.md", entries)), /"For admins" has no paragraph/); +}); diff --git a/tools/changelog/test/outputs.test.mjs b/tools/changelog/test/outputs.test.mjs new file mode 100644 index 00000000..6d9ab60c --- /dev/null +++ b/tools/changelog/test/outputs.test.mjs @@ -0,0 +1,138 @@ +// DECISIONS 320, 3.4: every output is generated from the records and nothing else. CHANGELOG.md, the page's data and a GitHub Release's body +// hold the same entries in the order of 2.7; a replaced pre-release is in none of them; Unreleased leaves out what a candidate holds; a rebuild +// needs no git and no network; a changed config does not change a frozen release. The fixtures are what the tool writes. +import assert from "node:assert/strict"; +import { execFileSync } from "node:child_process"; +import fs from "node:fs"; +import path from "node:path"; +import { test } from "node:test"; +import { fileURLToPath } from "node:url"; + +import { outputs, taggedDifferences } from "../build.mjs"; +import { loadConfig } from "../config.mjs"; +import { readEntry } from "../entries.mjs"; +import { buildRepository, copyOut, HARBOR, SLATE } from "../fixtures/make.mjs"; +import { sectionsOf, SECTION_NAMES } from "../outputs.mjs"; +import { pageReleases, readRecords } from "../records.mjs"; +import { repository, tempDir, writeRecord } from "./support.mjs"; + +const HERE = path.dirname(fileURLToPath(import.meta.url)); +const FIXTURES = path.join(HERE, "..", "fixtures"); +const BUILD = path.join(HERE, "..", "build.mjs"); + +/** The pull request numbers in a Markdown block, in order: the order the entries stand in. */ +const prsIn = (markdown) => [...markdown.matchAll(/\[#([0-9]+)\]/g)].map((match) => Number(match[1])); +const section = (markdown, start, end) => markdown.slice(markdown.indexOf(start), end ? markdown.indexOf(end, markdown.indexOf(start) + start.length) : undefined); + +test("CHANGELOG.md, the page's data and the GitHub body hold the same entries in the order of 2.7", () => { + const slate = outputs(path.join(FIXTURES, "slate")); + const release = slate.releases.find((candidate) => candidate.version === "0.2.0"); + const order = sectionsOf(release); + assert.deepEqual(order.map((part) => part.key), ["action", "deprecated", "added", "changed", "fixed"]); + const fromData = order.flatMap((part) => part.entries.map((entry) => entry.pr?.number)).filter(Boolean); + const markdown = section(slate.changelog, "## 0.2.0 - 2026-11-16", "## 0.1.0"); + assert.deepEqual(prsIn(markdown), fromData); + const headings = [...markdown.matchAll(/^### (.+)$/gm)].map((match) => match[1]); + assert.deepEqual(headings, ["Action needed", "Deprecated", "Added", "Changed", "Fixed"]); + const github = slate.github("0.2.0"); + assert.deepEqual(prsIn(github), fromData); + assert.deepEqual([...github.matchAll(/^##+ (.+)$/gm)].map((match) => match[1]), ["Action needed", "Changes", "Deprecated", "Added", "Changed", "Fixed"]); + assert.match(github, /^Before upgrading from 0\.1\.0, check these 4 changes\.$/m); + assert.match(github, /Full diff: \[v0\.1\.0\.\.\.v0\.2\.0\]\(https:\/\/github\.com\/example\/slate\/compare\/v0\.1\.0\.\.\.v0\.2\.0\)/); + // Every section name the outputs use is one of the page's fixed words. + for (const heading of headings) assert.ok(Object.values(SECTION_NAMES).includes(heading)); +}); + +test("a product's release with a headline: no upgrade line, the notes first, and the list in the same order", () => { + const harbor = outputs(path.join(FIXTURES, "harbor")); + const markdown = section(harbor.changelog, "## 2.0.0 - 2026-12-07", "## 1.4.1"); + assert.doesNotMatch(markdown, /Before upgrading/); + assert.deepEqual([...markdown.matchAll(/^### (.+)$/gm)].map((match) => match[1]), ["For admins", "Action needed", "Added", "Fixed"]); + assert.match(markdown, /^\*\*Responders sign in with their own account\*\*$/m); +}); + +test("a replaced pre-release is in no output, and its entries are each in one place", () => { + const harbor = outputs(path.join(FIXTURES, "harbor")); + assert.deepEqual(harbor.releases.map((release) => release.version), ["2.0.0", "1.4.1", "1.4.0", "1.3.1", "1.3.0"]); + assert.doesNotMatch(harbor.changelog, /rc\.[12]/); + for (const pr of [140, 141, 142]) assert.equal(prsIn(harbor.changelog).filter((number) => number === pr).length, 1, `#${pr} once`); + assert.throws(() => harbor.github("2.0.0-rc.1"), /not a drawn release/); + assert.deepEqual(harbor.releases[0].replaces, ["2.0.0-rc.1", "2.0.0-rc.2"]); + // Before the stable version shipped, its candidates were drawn as releases of their own, each with what it added. + const records = readRecords(path.join(FIXTURES, "harbor")).filter((record) => record.version !== "2.0.0"); + const before = pageReleases(path.join(FIXTURES, "harbor"), { records, pending: [] }); + assert.deepEqual(before.slice(0, 2).map((release) => [release.version, release.entries.map((entry) => entry.id)]), [["2.0.0-rc.2", ["pr142-1"]], ["2.0.0-rc.1", ["pr140-1", "pr141-1"]]]); +}); + +test("Unreleased is the pending files that no pre-release record holds", () => { + const root = path.join(FIXTURES, "harbor"); + const config = loadConfig(root); + const records = readRecords(root).filter((record) => record.version !== "2.0.0"); + const pending = [ + readEntry("---\ntype: removed\narea: Sign-in\npr: 140\naction: true\n---\nRemoved sign-in with a shared room code\n", ".changes/pr140-1.md", config), + readEntry("---\ntype: fixed\narea: Rooms\npr: 143\n---\nFixed the room list scrolling to the top when a new room opened\n", ".changes/pr143-1.md", config), + ]; + const releases = pageReleases(root, { config, records, pending }); + assert.equal(releases[0].version, "Unreleased"); + assert.deepEqual(releases[0].entries.map((entry) => entry.id), ["pr143-1"]); + assert.equal(releases[0].entries[0].commit, undefined, "an unreleased entry has no commit"); +}); + +test("rebuilding with no git and no network gives the same bytes", () => { + for (const name of ["slate", "harbor"]) { + const copy = path.join(tempDir(), name); + fs.cpSync(path.join(FIXTURES, name), copy, { recursive: true }); + fs.rmSync(path.join(copy, "CHANGELOG.md")); + // No git on the PATH at all: the build reads files and nothing else. + execFileSync(process.execPath, [BUILD, "--root", copy], { env: { PATH: "" } }); + execFileSync(process.execPath, [BUILD, "--root", copy, "--json", path.join(copy, "out.json")], { env: { PATH: "" } }); + assert.equal(fs.readFileSync(path.join(copy, "CHANGELOG.md"), "utf8"), fs.readFileSync(path.join(FIXTURES, name, "CHANGELOG.md"), "utf8"), name); + assert.equal(fs.readFileSync(path.join(copy, "out.json"), "utf8"), fs.readFileSync(path.join(FIXTURES, name, "releases.json"), "utf8"), name); + } +}); + +test("a changed config does not change a frozen release", () => { + const copy = path.join(tempDir(), "slate"); + fs.cpSync(path.join(FIXTURES, "slate"), copy, { recursive: true }); + const before = outputs(copy).releases.filter((release) => !release.unreleased); + const config = JSON.parse(fs.readFileSync(path.join(copy, "changelog.config.json"), "utf8")); + config.repository = "https://git.example/elsewhere/slate"; + config.trackers = config.trackers.map((tracker) => ({ ...tracker, url: tracker.url ? "https://tracker.example/{id}" : undefined, show: tracker.show === "none" ? "link" : tracker.show, ...(tracker.show === "none" ? { url: "https://tracker.example/{id}" } : {}) })); + config.people = {}; + fs.writeFileSync(path.join(copy, "changelog.config.json"), JSON.stringify(config)); + const after = outputs(copy).releases.filter((release) => !release.unreleased); + assert.deepEqual(after, before); +}); + +test("a hidden tracker's tickets are recorded and not published; a text tracker's are not linked", () => { + const root = path.join(FIXTURES, "slate"); + const record = readRecords(root).find((candidate) => candidate.version === "0.2.0"); + const frozen = record.entries.find((entry) => entry.id === "pr46-1"); + assert.deepEqual(frozen.tickets.map((ticket) => ticket.id), ["DS-27", "DS-31", "PRJ-90", "slate#45", "SL-131", "SUP-7"]); + const drawn = outputs(root).releases.find((release) => release.version === "0.2.0").entries.find((entry) => entry.id === "pr46-1"); + assert.deepEqual(drawn.tickets.map((ticket) => ticket.label), ["DS-27", "DS-31", "PRJ-90", "issue #45", "SL-131"]); + assert.equal(drawn.tickets.find((ticket) => ticket.label === "PRJ-90").href, undefined); + assert.doesNotMatch(outputs(root).changelog, /SUP-7/); +}); + +test("a record that differs from its tag's copy is found", () => { + const repo = repository(); + writeRecord(repo.dir, { version: "1.0.0", date: "2026-11-20", entries: [] }); + repo.commitAll("Release 1.0.0"); + repo.git("tag", "v1.0.0"); + assert.deepEqual(taggedDifferences(repo.dir), []); + writeRecord(repo.dir, { version: "1.0.0", date: "2026-11-21", entries: [] }); + assert.deepEqual(taggedDifferences(repo.dir), ["changelog/releases/1.0.0.json differs from the copy tagged v1.0.0; a published version is never edited"]); +}); + +test("the fixtures are what the tool writes, from their histories", () => { + for (const project of [SLATE, HARBOR]) { + const dir = buildRepository(project, tempDir(`changelog-${project.name}-`)); + const out = path.join(tempDir(), project.name); + copyOut(project, dir, out); + for (const file of ["CHANGELOG.md", "releases.json", ...fs.readdirSync(path.join(out, "changelog", "releases")).map((name) => path.join("changelog", "releases", name))]) { + assert.equal(fs.readFileSync(path.join(out, file), "utf8"), fs.readFileSync(path.join(FIXTURES, project.name, file), "utf8"), `${project.name}/${file}`); + } + assert.deepEqual(fs.readdirSync(path.join(out, "changelog", "releases")).sort(), fs.readdirSync(path.join(FIXTURES, project.name, "changelog", "releases")).sort()); + } +}); diff --git a/tools/changelog/test/release.test.mjs b/tools/changelog/test/release.test.mjs new file mode 100644 index 00000000..50258f24 --- /dev/null +++ b/tools/changelog/test/release.test.mjs @@ -0,0 +1,247 @@ +// DECISIONS 320, 1.1 and 3.4: the freeze. The bump in 0.x and from 1.0, the line, pre-releases, the commit that added each file, and what it +// refuses. Every repository here is a throwaway one with made-up entries. +import assert from "node:assert/strict"; +import { execFileSync } from "node:child_process"; +import fs from "node:fs"; +import path from "node:path"; +import { test } from "node:test"; + +import { pageReleases, readRecords } from "../records.mjs"; +import { freeze } from "../release.mjs"; +import { readConfig } from "../config.mjs"; +import { CONFIG, repository, stops, tempDir, writeRecord } from "./support.mjs"; + +const config = readConfig(CONFIG); +const released = (version, date, entries = []) => ({ version, date, entries }); +const fixed = (pr, n = 1) => [`pr${pr}-${n}`, { type: "fixed", area: "List", pr }]; + +test("from 1.0: a patch is refused for an Added entry, and the message says the least version", () => { + const repo = repository(); + writeRecord(repo.dir, released("1.4.0", "2026-11-20")); + repo.commitAll("Release 1.4.0"); + repo.entry("pr10-1", { type: "added", area: "Stepper", pr: 10 }, "Added `Stepper` with queued and running states"); + assert.equal(stops(() => freeze({ root: repo.dir, version: "1.4.1", date: "2026-11-23" })), "1.4.1 understates the release: from 1.4.0 it needs a minor (pr10-1), so at least 1.5.0"); + assert.equal(freeze({ root: repo.dir, version: "1.5.0", date: "2026-11-23" }).record.previous, "1.4.0"); +}); + +test("in 0.x the numbers move one place right: an addition rides a patch, and a breaking change needs the minor", () => { + const repo = repository(); + writeRecord(repo.dir, released("0.2.0", "2026-11-20")); + repo.commitAll("Release 0.2.0"); + repo.entry("pr11-1", { type: "added", area: "Stepper", pr: 11 }, "Added `Stepper` with queued and running states"); + assert.equal(freeze({ root: repo.dir, version: "0.2.1", date: "2026-11-21" }).record.entries[0].id, "pr11-1"); + repo.commitAll("Release 0.2.1"); + repo.entry("pr12-1", { type: "removed", area: "Banner", pr: 12, action: true }, "Removed `Banner`, so use `Notice` with the same props"); + assert.equal(stops(() => freeze({ root: repo.dir, version: "0.2.2", date: "2026-11-23" })), "0.2.2 understates the release: from 0.2.1 it needs a major (pr12-1), one place right in 0.x, so at least 0.3.0"); + assert.equal(freeze({ root: repo.dir, version: "0.3.0", date: "2026-11-23" }).record.previous, "0.2.1"); +}); + +test("a minor is accepted for a deprecation marked action: action raises nothing", () => { + const repo = repository(); + writeRecord(repo.dir, released("1.4.0", "2026-11-20")); + repo.commitAll("Release 1.4.0"); + repo.entry("pr13-1", { type: "deprecated", area: "Banner", pr: 13, action: true }, "Deprecated `Banner` in favor of `Notice`, removed in 2.0.0 no earlier than Mar 1, 2027"); + const { record } = freeze({ root: repo.dir, version: "1.5.0", date: "2026-11-23" }); + assert.deepEqual(record.entries.map((entry) => [entry.id, entry.bump, entry.action]), [["pr13-1", "minor", true]]); +}); + +test("a Changed entry with no bump, a bump below its floor and a major entry without action are refused", () => { + const cases = [ + [{ type: "changed", area: "Toast", pr: 14 }, /a changed entry states its bump/], + [{ type: "added", area: "Toast", pr: 14, bump: "patch" }, /an? added entry needs at least a minor/], + [{ type: "changed", area: "Toast", pr: 14, bump: "major" }, /a major entry is always "action: true"/], + ]; + for (const [head, message] of cases) { + const repo = repository(); + repo.entry("pr14-1", head, "Changed toasts to sit below the bar instead of above the tabs"); + assert.match(stops(() => freeze({ root: repo.dir, version: "1.0.0", date: "2026-11-23" })), message); + assert.deepEqual(fs.readdirSync(repo.dir).filter((name) => name === "changelog"), [], "nothing is written before every check passes"); + } +}); + +test("a version higher than the entries need is accepted: the version is the owner's to give", () => { + const repo = repository(); + writeRecord(repo.dir, released("1.4.0", "2026-11-20")); + repo.commitAll("Release 1.4.0"); + repo.entry(...fixed(15), "Fixed the list losing its place when a row was removed"); + assert.equal(freeze({ root: repo.dir, version: "2.0.0", date: "2026-11-23" }).record.previous, "1.4.0"); +}); + +test("the line: 1.4.1 is accepted after 2.0.0, 1.3.9 is refused after 1.4.0, and a version opening a line must top them all", () => { + const repo = repository(); + writeRecord(repo.dir, released("1.3.0", "2026-11-01")); + writeRecord(repo.dir, released("1.4.0", "2026-11-10")); + writeRecord(repo.dir, { ...released("2.0.0", "2026-11-20"), previous: "1.4.0" }); + repo.commitAll("Earlier releases"); + repo.entry(...fixed(16), "Fixed the list losing its place when a row was removed"); + assert.equal(stops(() => freeze({ root: repo.dir, version: "1.3.9", date: "2026-11-23" })), "1.3.9 is not higher than 1.4.0, released in its line (1.x.x)"); + assert.equal(stops(() => freeze({ root: repo.dir, version: "2.0.0", date: "2026-11-23" })), "2.0.0 is published, and a published version is never edited"); + const { record } = freeze({ root: repo.dir, version: "1.4.1", date: "2026-11-23" }); + assert.equal(record.previous, "1.4.0", "measured from the highest stable release below it in its own line"); + // 0.x lines are the minor: 0.3.0 opens a line and must be higher than every release there is. + const other = repository(); + writeRecord(other.dir, released("1.0.0", "2026-11-01")); + other.commitAll("Release 1.0.0"); + other.entry(...fixed(17), "Fixed the list losing its place when a row was removed"); + assert.equal(stops(() => freeze({ root: other.dir, version: "0.3.0", date: "2026-11-23" })), "0.3.0 opens a line, so it must be higher than every release; 1.0.0 is higher"); +}); + +test("two releases of one day are ordered by precedence, never by date", () => { + const repo = repository(); + writeRecord(repo.dir, released("1.4.0", "2026-11-23")); + repo.commitAll("Release 1.4.0"); + repo.entry(...fixed(18), "Fixed the list losing its place when a row was removed"); + freeze({ root: repo.dir, version: "1.4.1", date: "2026-11-23" }); + // A backport the same day to an older line: it sits below by precedence, though it was frozen last. + writeRecord(repo.dir, released("1.3.5", "2026-11-23")); + assert.deepEqual(pageReleases(repo.dir, { config }).map((release) => release.version), ["1.4.1", "1.4.0", "1.3.5"]); +}); + +test("pre-releases: a candidate's freeze removes nothing, the next holds only what is new, the stable version holds all under the same ids", () => { + const repo = repository(); + writeRecord(repo.dir, released("1.4.0", "2026-11-20")); + repo.commitAll("Release 1.4.0"); + repo.entry("pr20-1", { type: "removed", area: "Sign-in", pr: 20, action: true }, "Removed sign-in with a shared code, so each person signs in with their own account"); + repo.entry("pr21-1", { type: "added", area: "Sign-in", pr: 21 }, "Added single sign-on through your company's identity provider"); + const rc1 = freeze({ root: repo.dir, version: "2.0.0-rc.1", date: "2026-12-01" }); + assert.deepEqual(rc1.removed, []); + assert.deepEqual(repo.pending(), ["pr20-1.md", "pr21-1.md"], "every pending file stays"); + repo.commitAll("Release 2.0.0-rc.1"); + repo.entry("pr22-1", { type: "added", area: "Sign-in", pr: 22 }, "Added a sign-in page that names your identity provider"); + const rc2 = freeze({ root: repo.dir, version: "2.0.0-rc.2", date: "2026-12-03" }); + assert.deepEqual(rc2.record.entries.map((entry) => entry.id), ["pr22-1"]); + repo.commitAll("Release 2.0.0-rc.2"); + // The Unreleased section is what no candidate holds: nothing, here. + assert.equal(pageReleases(repo.dir, { config })[0].version, "2.0.0-rc.2"); + const stable = freeze({ root: repo.dir, version: "2.0.0", date: "2026-12-07" }); + assert.deepEqual(stable.record.entries.map((entry) => entry.id).sort(), ["pr20-1", "pr21-1", "pr22-1"]); + assert.deepEqual(stable.record.replaces, ["2.0.0-rc.1", "2.0.0-rc.2"]); + assert.equal(stable.record.previous, "1.4.0"); + // The same entry has the same commit in the candidate and in the stable release. + assert.equal(stable.record.entries.find((entry) => entry.id === "pr20-1").commit.sha, repo.record("2.0.0-rc.1").entries.find((entry) => entry.id === "pr20-1").commit.sha); + assert.deepEqual(repo.pending(), [], "the stable version takes every pending file"); + assert.deepEqual(pageReleases(repo.dir, { config }).map((release) => release.version), ["2.0.0", "1.4.0"], "a replaced candidate is not drawn"); +}); + +test("a canary has no freeze, and a pre-release is -beta.N or -rc.N", () => { + const repo = repository(); + repo.entry(...fixed(23), "Fixed the list losing its place when a row was removed"); + assert.match(stops(() => freeze({ root: repo.dir, version: "1.0.0-canary.20261123.1", date: "2026-11-23" })), /a canary is a build from the default branch, with no freeze/); + assert.match(stops(() => freeze({ root: repo.dir, version: "1.0.0-alpha.1", date: "2026-11-23" })), /-beta\.N or -rc\.N/); + assert.match(stops(() => freeze({ root: repo.dir, version: "1.0.0+9f3c1e2", date: "2026-11-23" })), /holds build metadata/); + assert.match(stops(() => freeze({ root: repo.dir, version: "2026.11.23.1", date: "2026-11-23" })), /not a SemVer version/); + assert.match(stops(() => freeze({ root: repo.dir, version: "1.0.0", date: "2026-11-31" })), /a calendar date/); +}); + +test("the commit is the first-parent commit that added the file: a merge, a squash and a rebase", () => { + const repo = repository(); + // A merge: the entry is committed on a branch and merged with a merge commit. The merge is the commit that put it on main. + repo.git("checkout", "-q", "-b", "feature"); + repo.entry("pr30-1", { type: "fixed", area: "List", pr: 30 }, "Fixed the list losing its place when a row was removed", "Fix the list"); + repo.git("checkout", "-q", "main"); + repo.git("merge", "-q", "--no-ff", "feature", "-m", "Merge pull request #30 from example/feature"); + const merge = repo.git("rev-parse", "HEAD"); + // A squash: one commit on main, its subject ending with the pull request. + const squash = repo.entry("pr31-1", { type: "fixed", area: "Sheet", pr: 31 }, "Fixed clipped focus rings at the top of a sheet's body", "Fix the sheet's rings (#31)"); + // A rebase: the branch's own commit, replayed onto main, with no number in its subject. + repo.git("checkout", "-q", "-b", "rebased"); + repo.entry("pr32-1", { type: "fixed", area: "Toast", pr: 32 }, "Fixed toasts stacking under the tab bar on phones", "Fix toasts under the tab bar"); + repo.git("checkout", "-q", "main"); + repo.git("rebase", "-q", "rebased"); + const rebased = repo.git("rev-parse", "HEAD"); + const { record } = freeze({ root: repo.dir, version: "1.0.0", date: "2026-11-23" }); + const sha = (id) => record.entries.find((entry) => entry.id === id).commit.sha; + assert.equal(sha("pr30-1"), merge); + assert.equal(sha("pr31-1"), squash); + assert.equal(sha("pr32-1"), rebased); + assert.equal(record.entries.find((entry) => entry.id === "pr31-1").commit.href, `https://github.com/example/repo/commit/${squash}`); +}); + +test("a commit whose subject names another pull request stops, showing both; an uncommitted entry stops", () => { + const repo = repository(); + repo.entry("pr33-1", { type: "fixed", area: "List", pr: 33 }, "Fixed the list losing its place when a row was removed", "Fix the list (#34)"); + assert.match(stops(() => freeze({ root: repo.dir, version: "1.0.0", date: "2026-11-23" })), /\.changes\/pr33-1\.md: says pull request 33, and the commit that added it \([0-9a-f]{8}\) is "Fix the list \(#34\)"/); + const fresh = repository(); + fresh.write("pr35-1", { type: "fixed", area: "List", pr: 35 }, "Fixed the list losing its place when a row was removed"); + assert.match(stops(() => freeze({ root: fresh.dir, version: "1.0.0", date: "2026-11-23" })), /no commit on this branch added it/); +}); + +test("a shallow clone is refused", () => { + const repo = repository(); + repo.entry(...fixed(36), "Fixed the list losing its place when a row was removed"); + repo.entry(...fixed(37), "Fixed the list losing its place when a row was added"); + const clone = path.join(tempDir(), "clone"); + execFileSync("git", ["clone", "-q", "--depth", "1", `file://${repo.dir}`, clone]); + assert.match(stops(() => freeze({ root: clone, version: "1.0.0", date: "2026-11-23" })), /this clone is shallow/); +}); + +test("a record is never overwritten, and a published version is never frozen again", () => { + const repo = repository(); + repo.entry(...fixed(38), "Fixed the list losing its place when a row was removed"); + freeze({ root: repo.dir, version: "1.0.0", date: "2026-11-23" }); + const before = fs.readFileSync(path.join(repo.dir, "changelog", "releases", "1.0.0.json"), "utf8"); + assert.equal(stops(() => freeze({ root: repo.dir, version: "1.0.0", date: "2026-11-24" })), "1.0.0 is published, and a published version is never edited"); + assert.equal(fs.readFileSync(path.join(repo.dir, "changelog", "releases", "1.0.0.json"), "utf8"), before); +}); + +test("covers is enforced: a paragraph naming no entry, or one this release does not hold, stops", () => { + const repo = repository(); + repo.entry("pr40-1", { type: "added", area: "Integrations", pr: 40 }, "Added webhook declarations so a monitor can open a room"); + repo.notes("---\ntitle: A monitor can open a room\n---\ncovers: [pr41-1]\nA monitor can open a room.\n"); + assert.match(stops(() => freeze({ root: repo.dir, version: "1.0.0", date: "2026-11-23" })), /covers "pr41-1", which is no entry/); + repo.notes("---\ntitle: A monitor can open a room\n---\ncovers: [pr40-1]\nA monitor can open a room.\n"); + const { record } = freeze({ root: repo.dir, version: "1.0.0", date: "2026-11-23" }); + assert.deepEqual(record.audiences, [{ text: "A monitor can open a room.", covers: ["pr40-1"] }]); + assert.equal(record.title, "A monitor can open a room"); +}); + +test("a release with no entries needs a summary; one of more than three needs a summary or paragraphs", () => { + const empty = repository(); + assert.match(stops(() => freeze({ root: empty.dir, version: "0.1.0", date: "2026-11-02" })), /has no entries, so it needs a summary/); + empty.notes("---\nsummary: The first version in this changelog. Earlier work is in the repository's history.\n---\n"); + assert.equal(freeze({ root: empty.dir, version: "0.1.0", date: "2026-11-02" }).record.entries.length, 0); + const many = repository(); + for (let pr = 50; pr < 54; pr++) many.entry(...fixed(pr), `Fixed the list losing its place in case ${pr}`); + assert.match(stops(() => freeze({ root: many.dir, version: "1.0.0", date: "2026-11-23" })), /has 4 changes, so it needs a summary/); +}); + +test("an unknown author is refused; an entry with no author is accepted and has no authors", () => { + const repo = repository(); + repo.entry("pr60-1", { type: "fixed", area: "List", pr: 60, author: "octocat" }, "Fixed the list losing its place when a row was removed"); + assert.match(stops(() => freeze({ root: repo.dir, version: "1.0.0", date: "2026-11-23" })), /author "octocat" is not a key/); + const ok = repository(); + ok.entry("pr61-1", { type: "fixed", area: "List", pr: 61, author: "sam" }, "Fixed the list losing its place when a row was removed"); + ok.entry("pr62-1", { type: "fixed", area: "List", pr: 62 }, "Fixed the list losing its place when a row was added"); + const { record } = freeze({ root: ok.dir, version: "1.0.0", date: "2026-11-23" }); + assert.deepEqual(record.entries.find((entry) => entry.id === "pr61-1").authors, ["Sam Rivera"]); + assert.equal("authors" in record.entries.find((entry) => entry.id === "pr62-1"), false); +}); + +test("an id held by two records that do not replace one another stops", () => { + const repo = repository(); + writeRecord(repo.dir, { ...released("1.4.0", "2026-11-20"), entries: [{ id: "pr70-1", type: "fixed", bump: "patch", text: "Fixed the list" }] }); + repo.commitAll("Release 1.4.0"); + // A backport that reuses the id instead of writing its own entry. + repo.entry("pr70-1", { type: "fixed", area: "List", pr: 70 }, "Fixed the list losing its place when a row was removed"); + assert.match(stops(() => freeze({ root: repo.dir, version: "1.4.1", date: "2026-11-23" })), /pr70-1\.md: the id is already held by 1\.4\.0; a backport writes its own entry/); + // Two records holding one id, neither replacing the other: reading them stops. + writeRecord(repo.dir, { ...released("2.0.0", "2026-11-21"), entries: [{ id: "pr70-1", type: "fixed", bump: "patch", text: "Fixed the list" }] }); + assert.match(stops(() => readRecords(repo.dir)), /the entry id "pr70-1" is held by 1\.4\.0 and 2\.0\.0/); + // A stable release and the candidate it replaces may share it. + fs.rmSync(path.join(repo.dir, "changelog", "releases", "2.0.0.json")); + writeRecord(repo.dir, { ...released("2.0.0-rc.1", "2026-11-21"), entries: [{ id: "pr71-1", type: "fixed", bump: "patch", text: "Fixed the list" }] }); + writeRecord(repo.dir, { ...released("2.0.0", "2026-11-22"), replaces: ["2.0.0-rc.1"], entries: [{ id: "pr71-1", type: "fixed", bump: "patch", text: "Fixed the list" }] }); + assert.equal(readRecords(repo.dir).length, 3); +}); + +test("a stable version removes the pending files and release.md, and regenerates CHANGELOG.md", () => { + const repo = repository(); + repo.entry("pr80-1", { type: "added", area: "Stepper", pr: 80, tickets: "[ENG-12, PROJ-4]" }, "Added `Stepper` with queued and running states"); + repo.notes("---\nsummary: Slate adds a stepper.\n---\n"); + const result = freeze({ root: repo.dir, version: "1.0.0", date: "2026-11-23" }); + assert.deepEqual(result.removed, [".changes/pr80-1.md", ".changes/release.md"]); + const changelog = fs.readFileSync(path.join(repo.dir, "CHANGELOG.md"), "utf8"); + assert.match(changelog, /^## 1\.0\.0 - 2026-11-23$/m); + assert.match(changelog, /^- Stepper: Added `Stepper` with queued and running states \(\[#80\]\(https:\/\/github\.com\/example\/repo\/pull\/80\), Linear \[ENG-12\]\(https:\/\/linear\.app\/example\/issue\/ENG-12\), Jira PROJ-4\)$/m); + assert.deepEqual(result.record.entries[0].tickets.map((ticket) => ticket.id), ["ENG-12", "PROJ-4"]); +}); diff --git a/tools/changelog/test/support.mjs b/tools/changelog/test/support.mjs new file mode 100644 index 00000000..5362a9fe --- /dev/null +++ b/tools/changelog/test/support.mjs @@ -0,0 +1,87 @@ +// Shared by the changelog tool's tests: a throwaway git repository with a config, entry files written and committed as a person would. +import { execFileSync } from "node:child_process"; +import fs from "node:fs"; +import os from "node:os"; +import path from "node:path"; +import { after } from "node:test"; + +const made = []; +after(() => { for (const dir of made) fs.rmSync(dir, { recursive: true, force: true }); }); + +/** A made-up config: Linear-like and Jira-like trackers and one person. Every value is invented. */ +export const CONFIG = { + product: "Example", + repository: "https://github.com/example/repo", + trackers: [ + { name: "Linear", pattern: "(?:ENG|DES)-[1-9][0-9]*", url: "https://linear.app/example/issue/{id}" }, + { name: "Jira", pattern: "PROJ-[1-9][0-9]*", url: "https://example.atlassian.net/browse/{id}", show: "text" }, + { name: "GitHub", pattern: "repo#(?[1-9][0-9]*)", url: "https://github.com/example/repo/issues/{n}", label: "issue #{n}" }, + ], + people: { sam: { name: "Sam Rivera" } }, +}; + +export function tempDir(prefix = "changelog-test-") { + const dir = fs.mkdtempSync(path.join(os.tmpdir(), prefix)); + made.push(dir); + return dir; +} + +/** An entry file's text from its head fields and sentence. */ +export function entryText(head, text = "Fixed the example list losing its place when a row was removed") { + const lines = ["---", ...Object.entries(head).map(([key, value]) => `${key}: ${Array.isArray(value) ? `[${value.join(", ")}]` : value}`), "---", text, ""]; + return lines.join("\n"); +} + +/** A repository with the config committed. `git(...)` runs in it; `entry(id, head, text, subject)` writes and commits one entry file. */ +export function repository(config = CONFIG) { + const dir = tempDir(); + let clock = Date.UTC(2026, 10, 1, 9); + const env = () => { + clock += 60_000; + const when = new Date(clock).toISOString(); + return { ...process.env, GIT_AUTHOR_NAME: "Example", GIT_AUTHOR_EMAIL: "example@example.com", GIT_COMMITTER_NAME: "Example", GIT_COMMITTER_EMAIL: "example@example.com", GIT_AUTHOR_DATE: when, GIT_COMMITTER_DATE: when }; + }; + const git = (...args) => execFileSync("git", args, { cwd: dir, env: env(), encoding: "utf8", stdio: ["ignore", "pipe", "pipe"] }).trim(); + git("init", "-q", "-b", "main"); + git("config", "commit.gpgsign", "false"); + fs.writeFileSync(path.join(dir, "changelog.config.json"), JSON.stringify(config, null, 2)); + git("add", "-A"); + git("commit", "-q", "-m", "Start"); + const write = (id, head, text) => { + fs.mkdirSync(path.join(dir, ".changes"), { recursive: true }); + fs.writeFileSync(path.join(dir, ".changes", `${id}.md`), entryText(head, text)); + }; + const entry = (id, head, text, subject = `Change ${id}${head.pr ? ` (#${head.pr})` : ""}`) => { + write(id, head, text); + git("add", "-A"); + git("commit", "-q", "-m", subject); + return git("rev-parse", "HEAD"); + }; + const notes = (source) => { + fs.mkdirSync(path.join(dir, ".changes"), { recursive: true }); + fs.writeFileSync(path.join(dir, ".changes", "release.md"), source); + git("add", "-A"); + git("commit", "-q", "-m", "Release notes"); + }; + const commitAll = (message) => { git("add", "-A"); git("commit", "-q", "-m", message); }; + const record = (version) => JSON.parse(fs.readFileSync(path.join(dir, "changelog", "releases", `${version}.json`), "utf8")); + const pending = () => (fs.existsSync(path.join(dir, ".changes")) ? fs.readdirSync(path.join(dir, ".changes")).sort() : []); + return { dir, git, write, entry, notes, commitAll, record, pending }; +} + +/** Write a record by hand (a release that happened before the test). */ +export function writeRecord(dir, record) { + const file = path.join(dir, "changelog", "releases", `${record.version}.json`); + fs.mkdirSync(path.dirname(file), { recursive: true }); + fs.writeFileSync(file, `${JSON.stringify(record, null, 2)}\n`); +} + +/** Run `fn` and return the message it stopped with, or fail when it did not stop. */ +export function stops(fn) { + try { + fn(); + } catch (error) { + return error.message; + } + throw new Error("expected it to stop, and it went on"); +} From 8196c5256c1e02716a6cbe1c073d35aa92e9c098 Mon Sep 17 00:00:00 2001 From: bailey <74082460+bmjcoding@users.noreply.github.com> Date: Mon, 23 Nov 2026 16:01:26 -0600 Subject: [PATCH 02/23] React: VersionLink, ReleaseNotes and ReleaseIndex (DECISIONS 320, 1.2 and 2) VersionLink is the version with its ship date, one link to the release notes: at the sidebar's foot (AppShell's new version prop), the number alone in the rail with the rail's tooltip, the last row of TabBarMore's sheet, and after the legal line in SiteFooter. ReleaseNotes draws a package's changelog or a product's release notes from the records the changelog tool writes: computed counts, Action needed, audience paragraphs, the folds, source lines with their Sources panel, Build details from the running build, and arrival at a release or an entry by its fragment. ReleaseIndex is the versions, a pane beside the page or a fold above it. The stream's arrival (useArrival) moves to arrival.ts, which both use; no pixel of the stream changes. Sizes recorded; VersionLink is 2,102 bytes and loads no tooltip of its own (AppShell hands it the one Nav uses). Co-Authored-By: Claude Opus 5.5 --- packages/react/src/app-shell.tsx | 23 +- packages/react/src/arrival.ts | 101 ++++ packages/react/src/index.ts | 7 + packages/react/src/release-date.ts | 18 + packages/react/src/release-index.tsx | 71 +++ packages/react/src/release-notes.tsx | 491 +++++++++++++++++++ packages/react/src/release-types.ts | 54 ++ packages/react/src/site-footer.tsx | 12 +- packages/react/src/stream.tsx | 97 +--- packages/react/src/styles/components.css | 215 ++++++++ packages/react/src/tab-bar.tsx | 11 +- packages/react/src/version-link.tsx | 72 +++ packages/react/src/version-place.ts | 20 + packages/react/test/bundle.test.mjs | 16 + packages/react/test/export-sizes.json | 27 +- packages/react/test/release-arrival.test.mjs | 157 ++++++ packages/react/test/release-fixture.mjs | 29 ++ packages/react/test/release-notes.test.mjs | 375 ++++++++++++++ packages/react/test/version-link.test.mjs | 232 +++++++++ 19 files changed, 1915 insertions(+), 113 deletions(-) create mode 100644 packages/react/src/arrival.ts create mode 100644 packages/react/src/release-date.ts create mode 100644 packages/react/src/release-index.tsx create mode 100644 packages/react/src/release-notes.tsx create mode 100644 packages/react/src/release-types.ts create mode 100644 packages/react/src/version-link.tsx create mode 100644 packages/react/src/version-place.ts create mode 100644 packages/react/test/release-arrival.test.mjs create mode 100644 packages/react/test/release-fixture.mjs create mode 100644 packages/react/test/release-notes.test.mjs create mode 100644 packages/react/test/version-link.test.mjs diff --git a/packages/react/src/app-shell.tsx b/packages/react/src/app-shell.tsx index 1ff9778c..11f195bc 100644 --- a/packages/react/src/app-shell.tsx +++ b/packages/react/src/app-shell.tsx @@ -1,13 +1,14 @@ import { breakpoint } from "@srasyndicate/basalt-tokens/breakpoints"; import * as React from "react"; -import { TooltipProvider } from "./display"; +import { Tooltip, TooltipProvider } from "./display"; import { DotLine } from "./dot-sep"; import { NavRailContext } from "./nav"; import { usePinnedEdges } from "./pinned-edges"; import { useScreenKeyboardLayout } from "./screen-keyboard"; import { useMediaQuery } from "./use-media"; import { join } from "./utils"; +import { RailTooltipContext, VersionContext, VersionPlaceContext } from "./version-place"; // The app shell (decisions 96): a sidebar at 1024 and up, the rail from 720 to 1023, the phone tab bar under 720, and one // header over the content column. The document is the scroller, never an inner pane (a page's own pane beside it is @@ -31,6 +32,11 @@ export interface AppShellProps extends Omit, "childr sidebar: React.ReactNode; /** Account items pinned to the sidebar's foot: a second `Nav` (named "Account", say) holding Settings, Profile and the like. */ account?: React.ReactNode; + /** + * The version this session runs, as a `VersionLink` to the release notes at that version. Drawn at the sidebar's foot under the account + * items, as the number alone in the rail (the date in its name and tooltip), and as the last row of `TabBarMore`'s sheet under 720. + */ + version?: React.ReactNode; /** The `AppHeader`: it spans the content column only, never the sidebar. */ header: React.ReactNode; /** The phone `TabBar`, for an app with three or more destinations. Content pads past it, and toasts sit above it. */ @@ -63,7 +69,7 @@ export interface AppShellProps extends Omit, "childr * content column and sticks to the document, which is what scrolls: set `scrollbar-gutter: stable` on the page (the shell * does for the document it is in), and give the viewport meta `viewport-fit=cover` so the safe-area insets work. */ -export function AppShell({ brand, brandLabel, homeHref = "/", brandMark, sidebar, account, header, tabBar, foot, mainProps, capped = false, className, children, ...props }: AppShellProps) { +export function AppShell({ brand, brandLabel, homeHref = "/", brandMark, sidebar, account, version, header, tabBar, foot, mainProps, capped = false, className, children, ...props }: AppShellProps) { const rail = useMediaQuery(`(width < ${breakpoint.lg}px)`); useScreenKeyboardLayout(); usePinnedEdges(foot != null); @@ -79,7 +85,16 @@ export function AppShell({ brand, brandLabel, homeHref = "/", brandMark, sidebar
{sidebar}
- {account ?
{account}
: null} + {account || version ? ( +
+ {account} + {version ? ( +
+ {version} +
+ ) : null} +
+ ) : null}
@@ -88,7 +103,7 @@ export function AppShell({ brand, brandLabel, homeHref = "/", brandMark, sidebar
{children}
{foot != null ?
{foot}
: null} - {tabBar} + {version ? {tabBar} : tabBar} ); } diff --git a/packages/react/src/arrival.ts b/packages/react/src/arrival.ts new file mode 100644 index 00000000..723a758d --- /dev/null +++ b/packages/react/src/arrival.ts @@ -0,0 +1,101 @@ +import * as React from "react"; + +import { useInShape } from "./in-shape"; + +// The entry a link, a search result or a notice opened (DECISIONS 266, and 320 for the release notes): scrolled to, focused with no ring (it is a +// place, not a control), and marked until the reader acts (a press, or a key that is not one that reads around it). Shared by the stream's entries +// and the release notes' releases and entries; each draws its own mark (the plate and the word "Linked"). Nothing runs when the module loads. + +/** Keys that read around the entry rather than act: they leave the mark where it is. A pattern, not a set, so loading the module builds nothing. */ +const reading = (key: string) => /^(Arrow(Up|Down|Left|Right)|Page(Up|Down)|Home|End| |Shift|Control|Alt|Meta|CapsLock)$/.test(key); + +export interface ArrivalProps { + /** This is the entry a link, a search result or a notice opened: it is scrolled to, focused and marked until the reader acts. */ + arrived?: boolean; + /** The word that says so, in the entry's head. Default "Linked"; an app says why in its own words ("Search result", "From your notice"). */ + arrivedLabel?: string; + /** The reader has acted, so the mark is going. Without it the part ends the mark itself; with it, the app may also clear `arrived`. */ + onArrivedEnd?: () => void; +} + +// One entry arrives at a time. The one placed last is the one the reader is at: placing another ends the one before (its `onArrivedEnd` is +// called). Assigned only while an entry is arrived, so loading this module does nothing. +let current: { end: () => void } | undefined; + +/** Whether the element has a box the reader can see: not under `display: none` (nor `content-visibility: hidden`). */ +const shown = (el: HTMLElement) => el.getClientRects().length > 0 && (typeof el.checkVisibility !== "function" || el.checkVisibility()); + +/** The nearest ancestor that scrolls the entry on the block axis, or null when it is the page. */ +function scrollerOf(el: HTMLElement): HTMLElement | null { + for (let at = el.parentElement; at && at !== document.body && at !== document.documentElement; at = at.parentElement) { + const { overflowY } = getComputedStyle(at); + if ((overflowY === "auto" || overflowY === "scroll") && at.scrollHeight > at.clientHeight) return at; + } + return null; +} + +/** + * The arrival's state: shown while `arrived` and the reader has not acted yet. Once the entry has a box (a pane it sits in may be hidden when it + * mounts) it is scrolled to and focused, once each time it turns on, and from then the reader's first act ends it. + */ +export function useArrival({ arrived = false, onArrivedEnd }: ArrivalProps) { + const inShape = useInShape(); + const ref = React.useRef(null); + const [ended, setEnded] = React.useState(false); + const [ever, setEver] = React.useState(false); + const [placed, setPlaced] = React.useState(false); + const end = React.useRef(onArrivedEnd); + end.current = onArrivedEnd; + React.useEffect(() => { if (arrived) setEnded(false); }, [arrived]); + const on = arrived && !ended && inShape === 0; + React.useEffect(() => { if (!on) setPlaced(false); }, [on]); + React.useLayoutEffect(() => { + if (!on || placed) return undefined; + const el = ref.current; + if (!el) return undefined; + const place = () => { + // A short entry is brought to the middle of what scrolls it; one taller than most of that (the pane's visible height, or the window's), to its top. + const scroller = scrollerOf(el); + const room = scroller ? scroller.clientHeight : window.innerHeight; + el.scrollIntoView({ block: el.getBoundingClientRect().height > room * 0.6 ? "start" : "center", inline: "nearest" }); + el.focus({ preventScroll: true }); + setEver(true); + setPlaced(true); + }; + if (shown(el)) { place(); return undefined; } + // Not laid out yet (a hidden tab or pane): wait until it has a box, then place it once. + const watch = new ResizeObserver(() => { if (shown(el)) { watch.disconnect(); place(); } }); + watch.observe(el); + return () => watch.disconnect(); + }, [on, placed]); + React.useEffect(() => { + if (!on || !placed) return undefined; + const finish = () => { setEnded(true); end.current?.(); }; + const self = { end: finish }; + if (current && current !== self) current.end(); + current = self; + const act = (event: Event) => { + if (event.type === "keydown") { + const key = (event as KeyboardEvent).key; + const inField = (event.target as Element | null)?.closest?.("input, textarea, select, [contenteditable='true'], [contenteditable='']"); + if (reading(key) && !(key === " " && inField)) return; + } + finish(); + }; + // From the next frame, so the press or key that opened the entry does not end its mark. + const frame = requestAnimationFrame(() => { + document.addEventListener("pointerdown", act, true); + document.addEventListener("keydown", act, true); + }); + return () => { + if (current === self) current = undefined; + cancelAnimationFrame(frame); + document.removeEventListener("pointerdown", act, true); + document.removeEventListener("keydown", act, true); + }; + }, [on, placed]); + // Once it has arrived the entry stays a focus target, so taking the mark away never drops the reader's focus. + const attrs = { ref, tabIndex: ever || on ? -1 : undefined, "data-arrival": ever || on ? "" : undefined, "data-arrived": on ? "" : undefined }; + return { on, ever: ever || on, attrs }; +} + diff --git a/packages/react/src/index.ts b/packages/react/src/index.ts index c6930b42..fecf5c91 100644 --- a/packages/react/src/index.ts +++ b/packages/react/src/index.ts @@ -129,6 +129,13 @@ export { EventLine, EventLog, EventLogRule, EventText, EventTime } from "./event export type { EventLineProps, EventLogProps, EventLogRuleProps, EventTextProps, EventTimeProps } from "./event-log"; export { Stream, StreamArrivedWord, StreamBlock, StreamEntry, StreamMessage, StreamNote, StreamQuote } from "./stream"; export type { ArrivalProps, StreamBlockProps, StreamEntryProps, StreamMessageProps, StreamNoteProps, StreamProps, StreamQuoteProps } from "./stream"; +// Versions and release notes (DECISIONS 320): each its own module, so an app that shows only the foot's link loads only that. +export { VersionLink } from "./version-link"; +export type { VersionLinkProps } from "./version-link"; +export { ReleaseNotes } from "./release-notes"; +export type { ReleaseAudience, ReleaseBuildRow, ReleaseBump, ReleaseEntryRecord, ReleaseEntryType, ReleaseNotesProps, ReleaseRecord, ReleaseWords } from "./release-notes"; +export { ReleaseIndex } from "./release-index"; +export type { ReleaseIndexProps } from "./release-index"; export { DisclosureRow } from "./disclosure-row"; export type { DisclosureRowProps } from "./disclosure-row"; export { ActivityList, ActivityStep } from "./activity-list"; diff --git a/packages/react/src/release-date.ts b/packages/react/src/release-date.ts new file mode 100644 index 00000000..abfbee3f --- /dev/null +++ b/packages/react/src/release-date.ts @@ -0,0 +1,18 @@ +// A release's ship date (DECISIONS 320, 1.1): a calendar date written once, `YYYY-MM-DD`, drawn "Nov 23, 2026" with its year always, and never +// moved by a reader's time zone, so it cannot show the day before. It draws nothing and holds no state; nothing runs when the module loads. + +/** The parts of an ISO calendar date, or null when it is not one. */ +export function calendarDate(iso: string): { year: number; month: number; day: number } | null { + const match = /^([0-9]{4})-([0-9]{2})-([0-9]{2})$/.exec(iso); + if (!match) return null; + const [year, month, day] = [Number(match[1]), Number(match[2]), Number(match[3])]; + const at = new Date(Date.UTC(year, month - 1, day)); + return at.getUTCFullYear() === year && at.getUTCMonth() === month - 1 && at.getUTCDate() === day ? { year, month, day } : null; +} + +/** "Nov 23, 2026" in `en-US`: the locale's short date with its year, read in UTC so the day never moves. A string that is not a date is returned as it is. */ +export function formatReleaseDate(iso: string, locale: string | string[] = "en-US"): string { + const date = calendarDate(iso); + if (!date) return iso; + return new Intl.DateTimeFormat(locale, { month: "short", day: "numeric", year: "numeric", timeZone: "UTC" }).format(new Date(Date.UTC(date.year, date.month - 1, date.day))); +} diff --git a/packages/react/src/release-index.tsx b/packages/react/src/release-index.tsx new file mode 100644 index 00000000..74ebec0e --- /dev/null +++ b/packages/react/src/release-index.tsx @@ -0,0 +1,71 @@ +import * as React from "react"; + +import { Accordion, AccordionItem } from "./feedback"; +import { formatReleaseDate } from "./release-date"; +import type { ReleaseRecord } from "./release-types"; +import { join } from "./utils"; + +// The versions (DECISIONS 320, 2.11): a `nav` named "Versions", one link a release, in the page's order: the number in mono and primary, the date +// at the row's end in tertiary, 13/18, 30 tall and 44 on touch; hover underlines the number. Beside the list it is `PaneLayout`'s pane, under a +// 13/18, 500 heading; where the pane would follow the page instead, it is a closed fold above the first release. A page draws both forms, the +// pane in `PaneLayout`'s pane and the fold before `ReleaseNotes`, and each shows only where it belongs: +// +// } paneLabel="Versions"> +// +// +// + +export interface ReleaseIndexProps extends Omit, "children"> { + releases: readonly Pick[]; + /** Default "Versions". */ + label?: string; + /** "pane" (default): the list under its heading, for `PaneLayout`'s pane. "fold": a closed fold above the first release, where the pane is not beside the page. */ + form?: "pane" | "fold"; + /** The dates' locale. Default "en-US". */ + locale?: string; + /** The word for the Unreleased row. Default "Unreleased". */ + unreleasedLabel?: string; +} + +/** The versions of a release page. See the module note. */ +export function ReleaseIndex({ releases, label = "Versions", form = "pane", locale = "en-US", unreleasedLabel = "Unreleased", className, ...props }: ReleaseIndexProps) { + const titleId = React.useId(); + // Without script the fold is open; once the page runs it starts closed. + const [open, setOpen] = React.useState(["versions"]); + const wired = React.useRef(false); + React.useLayoutEffect(() => { + if (wired.current || form !== "fold") return; + wired.current = true; + setOpen([]); + }, [form]); + const list = ( + + ); + if (form === "fold") { + return ( + + ); + } + return ( + + ); +} diff --git a/packages/react/src/release-notes.tsx b/packages/react/src/release-notes.tsx new file mode 100644 index 00000000..c51a6a2f --- /dev/null +++ b/packages/react/src/release-notes.tsx @@ -0,0 +1,491 @@ +import * as React from "react"; + +import { useArrival } from "./arrival"; +import { CopyButton } from "./copy-button"; +import { DescriptionItem, DescriptionList } from "./description-list"; +import { Badge } from "./display"; +import { DotLine, DotSep } from "./dot-sep"; +import { Accordion, AccordionItem, Callout, Popover, PopoverContent, PopoverTitle, PopoverTrigger } from "./feedback"; +import { Link } from "./navigation"; +import { formatReleaseDate } from "./release-date"; +import type { ReleaseEntryRecord, ReleaseEntryType, ReleaseRecord } from "./release-types"; +import { TextButton } from "./text-button"; +import { join } from "./utils"; + +export type { ReleaseAudience, ReleaseBump, ReleaseEntryRecord, ReleaseEntryType, ReleaseRecord } from "./release-types"; + +// A page of releases from their records (DECISIONS 320, section 2): a package's changelog ("reference") or a product's release notes ("notes"). +// Releases highest first, one column, each at most the words' measure plus space-6 plus the sidebar's width, space-10 apart with a divider +// between. A release is its header (the number and the date in one heading, the counts computed from its list, "Pre-release" and "Your version", +// Copy link), then a package's summary, "Action needed" (a warning callout, never folded), a product's paragraphs for each audience, then one line +// a change under Security, Deprecated, Removed, Added, Changed and Fixed. A product's list is one fold holding its summary: "All changes", or +// "Other changes" when action entries stand above it, counted by what it opens. A package's list is open and only Fixed folds (past 3, in a +// release of more than 10). Each entry's source line (the pull request and at most two tickets) is a quiet text button that opens "Sources"; +// from 640 of the release's own width it stands beside the words in one column down the list, under it below that. A release is `#v1.4.0`, an +// entry its permanent id; the one a link opens is the stream's arrival (the plate and "Linked"), with every fold that holds it opened. Build +// details is on the release this session runs, from the running build. Nothing on the page is typed twice: the order, the counts, the folds and +// the callout's opening line come from the record. Without script, and in print, every fold is open. + +/** The page's fixed words, for another language. Counted words are functions of their number. */ +export interface ReleaseWords { + unreleased: string; + actionNeeded: string; + sections: Record; + allChanges: string; + otherChanges: string; + buildDetails: string; + sources: string; + pullRequest: string; + ticket: string; + tickets: string; + commit: string; + author: string; + authors: string; + yourVersion: string; + preRelease: string; + linked: string; + copyLink: string; + /** The name of a release's Copy link: "Copy link to Basalt 0.2.0". */ + copyLinkTo: (release: string) => string; + copyLinkToChange: string; + copyBuildDetails: string; + copied: string; + linkCopied: string; + buildDetailsCopied: string; + more: (count: number) => string; + changes: (count: number) => string; + needAction: (count: number) => string; + /** "Before upgrading from 0.1.0, check these 4 changes." */ + beforeUpgrading: (previous: string, count: number) => string; +} + +const WORDS: ReleaseWords = { + unreleased: "Unreleased", + actionNeeded: "Action needed", + sections: { security: "Security", deprecated: "Deprecated", removed: "Removed", added: "Added", changed: "Changed", fixed: "Fixed" }, + allChanges: "All changes", + otherChanges: "Other changes", + buildDetails: "Build details", + sources: "Sources", + pullRequest: "Pull request", + ticket: "Ticket", + tickets: "Tickets", + commit: "Commit", + author: "Author", + authors: "Authors", + yourVersion: "Your version", + preRelease: "Pre-release", + linked: "Linked", + copyLink: "Copy link", + copyLinkTo: (release) => `Copy link to ${release}`, + copyLinkToChange: "Copy link to this change", + copyBuildDetails: "Copy build details", + copied: "Copied", + linkCopied: "Link copied", + buildDetailsCopied: "Build details copied", + more: (count) => `${count} more`, + changes: (count) => `${count} ${count === 1 ? "change" : "changes"}`, + needAction: (count) => `${count} ${count === 1 ? "needs action" : "need action"}`, + beforeUpgrading: (previous, count) => `Before upgrading from ${previous}, check ${count === 1 ? "this change" : `these ${count} changes`}.`, +}; + +export interface ReleaseBuildRow { + label: string; + value: string; + /** An identifier (a build, a commit): mono. */ + mono?: boolean; +} + +export interface ReleaseNotesProps extends Omit, "children"> { + releases: readonly ReleaseRecord[]; + /** "reference": the list open, Unreleased shown (a package). "notes": audience paragraphs lead and the list folds (a product). */ + form: "reference" | "notes"; + /** The product's name, for "Copy link to Basalt 0.2.0". */ + product: string; + /** The page's own address, for copied links. Default: the window's, read when a button is pressed. */ + baseHref?: string; + /** The version this session runs: that release carries "Your version". */ + running?: string; + /** The running build's own rows, from what the app's build wrote: Build details, on the release marked "Your version". Never read from a record. */ + runningBuild?: readonly ReleaseBuildRow[]; + /** The level of a release's heading. Default 2. */ + headingLevel?: 2 | 3; + /** The entry or release to mark as arrived, for an app with its own router. Default: the window's fragment, followed on hashchange. */ + arrived?: string | null; + onArrivedEnd?: () => void; + /** The page's fixed words, for another language. */ + words?: Partial; + /** The dates' locale. Default "en-US". */ + locale?: string; +} + +const ORDER: readonly ReleaseEntryType[] = ["security", "deprecated", "removed", "added", "changed", "fixed"]; +const RANK = { major: 0, minor: 1, patch: 2 } as const; +/** Fixed folds when the release holds more than this many changes, and Fixed more than `FOLD_FIXED`. */ +const FOLD_OVER = 10; +const FOLD_FIXED = 3; +/** The source line names the pull request and at most this many tickets. */ +const SHOWN_TICKETS = 2; + +/** A release's address: "v1.4.0", "unreleased". */ +export const releaseId = (release: Pick) => (release.unreleased ? "unreleased" : `v${release.version}`); + +/** Inside a section, entries stand by impact (the bump), then by area, then by id. */ +const byImpact = (a: ReleaseEntryRecord, b: ReleaseEntryRecord) => + RANK[a.bump] - RANK[b.bump] || (a.area ?? "").localeCompare(b.area ?? "", "en") || a.id.localeCompare(b.id, "en"); + +/** The sentence: backticks mark code, and nothing else is markup. */ +function Sentence({ text }: { text: string }) { + const parts = text.split(/`([^`]+)`/); + return <>{parts.map((part, index) => (index % 2 ? {part} : {part}))}; +} + +interface Section { type: ReleaseEntryType; entries: ReleaseEntryRecord[] } + +/** The release's parts, computed from its record. */ +function partsOf(release: ReleaseRecord, form: ReleaseNotesProps["form"]) { + const action = release.entries.filter((entry) => entry.action).sort(byImpact); + const sections: Section[] = ORDER.map((type) => ({ type, entries: release.entries.filter((entry) => !entry.action && entry.type === type).sort(byImpact) })).filter((section) => section.entries.length > 0); + const inside = sections.reduce((sum, section) => sum + section.entries.length, 0); + const leads = form === "notes" && Boolean(release.audiences?.length); + const folded = leads && inside > 0; + const fixedFolds = !folded && release.entries.length > FOLD_OVER && (sections.find((section) => section.type === "fixed")?.entries.length ?? 0) > FOLD_FIXED; + return { action, sections, inside, leads, folded, fixedFolds }; +} + +/** The keys of the folds a release has, and the fold that holds each entry. */ +function foldsOf(release: ReleaseRecord, form: ReleaseNotesProps["form"]) { + const id = releaseId(release); + const { folded, fixedFolds, sections } = partsOf(release, form); + const all: string[] = []; + const holding = new Map(); + if (folded) { + all.push(`${id}-all`); + for (const section of sections) for (const entry of section.entries) holding.set(entry.id, `${id}-all`); + } else if (fixedFolds) { + all.push(`${id}-fixed`); + for (const entry of sections.find((section) => section.type === "fixed")?.entries ?? []) holding.set(entry.id, `${id}-fixed`); + } + return { all, holding }; +} + +/** The page's own address with no fragment and no query: from the app, or the window's once the page is in a browser. */ +function useBase(baseHref: string | undefined) { + const [base, setBase] = React.useState(baseHref ?? ""); + React.useEffect(() => { + if (baseHref !== undefined) setBase(baseHref); + else setBase(`${window.location.origin}${window.location.pathname}`); + }, [baseHref]); + return base; +} + +/** The arrived target: the app's, or the window's fragment followed on hashchange. Each change is a fresh arrival. */ +function useTarget(arrived: string | null | undefined) { + const [fragment, setFragment] = React.useState(null); + React.useEffect(() => { + if (arrived !== undefined) return undefined; + let frame = 0; + const read = () => { + const raw = window.location.hash.slice(1); + let id = raw; + try { id = decodeURIComponent(raw); } catch { /* a fragment that is not valid percent-encoding is read as written */ } + // Turn it off first, then on, so the same target reached again (Back, then Forward) arrives again. + setFragment(null); + cancelAnimationFrame(frame); + frame = requestAnimationFrame(() => setFragment(id || null)); + }; + read(); + window.addEventListener("hashchange", read); + return () => { cancelAnimationFrame(frame); window.removeEventListener("hashchange", read); }; + }, [arrived]); + return arrived !== undefined ? arrived : fragment; +} + +interface Shared { + words: ReleaseWords; + base: string; + locale: string; + level: 2 | 3; + target: string | null; + onArrivedEnd?: () => void; + open: ReadonlySet; + setFold: (key: string, open: boolean) => void; +} + +/** The word "Linked", on a line above what arrived, kept in place once it has been shown so its going moves nothing. */ +function ArrivedWord({ on, ever, label }: { on: boolean; ever: boolean; label: string }) { + if (!ever) return null; + return {label}; +} + +function Heading({ level, ...props }: React.ComponentProps<"h2"> & { level: number }) { + return React.createElement(`h${Math.min(level, 6)}`, props); +} + +/** A fold: an accordion of one item whose heading holds the button. Closed panels stay in the document, so the browser's find opens them. */ +function Fold({ name, title, level, shared, className, children }: { name: string; title: React.ReactNode; level: number; shared: Shared; className?: string; children: React.ReactNode }) { + const value = shared.open.has(name) ? [name] : []; + return ( + shared.setFold(name, next.includes(name))} className={join("basalt-release-fold", className)}> + {children} + + ); +} + +/** A count after its name, `space-1` away: the space is read, the gap drawn. */ +const Count = ({ n }: { n: number }) => {n}; + +function SourceLine({ entry, textId, shared }: { entry: ReleaseEntryRecord; textId: string; shared: Shared }) { + const { words } = shared; + const tickets = entry.tickets ?? []; + const ids: string[] = []; + if (entry.pr) ids.push(`#${entry.pr.number}`); + for (const ticket of tickets.slice(0, SHOWN_TICKETS)) ids.push(ticket.label); + if (!entry.pr && !tickets.length && entry.commit) ids.push(entry.commit.sha.slice(0, 8)); + if (!ids.length) return null; + const more = tickets.length - SHOWN_TICKETS; + const shown = more > 0 ? [...ids, words.more(more)] : ids; + return ( + + + {words.sources}: + {shown.map((id, index) => ( + + {index > 0 ? : null} + {id} + + ))} + + )} + /> + + {words.sources} + + {entry.pr ? #{entry.pr.number} : null} + {tickets.length ? ( + ( + <>{ticket.tracker} {ticket.href ? {ticket.label} : {ticket.label}} + ))} + /> + ) : null} + {entry.commit ? ( + + {entry.commit.href ? {entry.commit.sha.slice(0, 8)} : entry.commit.sha.slice(0, 8)} + + ) : null} + {entry.authors?.length ? : null} + + {words.copyLinkToChange} + + + ); +} + +function Entry({ entry, shared }: { entry: ReleaseEntryRecord; shared: Shared }) { + const arrival = useArrival({ arrived: shared.target === entry.id, onArrivedEnd: shared.onArrivedEnd }); + const textId = `${entry.id}-words`; + return ( +
  • + +
    +

    + {entry.area ? <>{entry.area}:{" "} : null} + +

    + {entry.link ? {entry.link.label} : null} +
    + +
  • + ); +} + +const List = ({ entries, shared }: { entries: ReleaseEntryRecord[]; shared: Shared }) => ( +
      {entries.map((entry) => )}
    +); + +function Sections({ release, sections, level, foldFixed, shared }: { release: ReleaseRecord; sections: Section[]; level: number; foldFixed: boolean; shared: Shared }) { + const id = releaseId(release); + return ( + <> + {sections.map((section) => { + const title = <>{shared.words.sections[section.type]}; + if (section.type === "fixed" && foldFixed) { + return ( +
    + +
    + ); + } + return ( +
    + {title} + +
    + ); + })} + + ); +} + +function BuildDetails({ rows, shared }: { rows: readonly ReleaseBuildRow[]; shared: Shared }) { + return ( +
    + + + {rows.map((row) => {row.value})} + + `${row.label}: ${row.value}`).join("\n")} copiedLabel={shared.words.copied} statusLabel={shared.words.buildDetailsCopied}>{shared.words.copyBuildDetails} + +
    + ); +} + +function Release({ release, form, product, running, runningBuild, shared }: { release: ReleaseRecord; form: ReleaseNotesProps["form"]; product: string; running?: string; runningBuild?: readonly ReleaseBuildRow[]; shared: Shared }) { + const { words, level, locale } = shared; + const id = releaseId(release); + const arrival = useArrival({ arrived: shared.target === id, onArrivedEnd: shared.onArrivedEnd }); + const { action, sections, inside, leads, folded, fixedFolds } = partsOf(release, form); + const total = release.entries.length; + const day = release.date ? formatReleaseDate(release.date, locale) : null; + const yours = running !== undefined && !release.unreleased && running === release.version; + const pre = !release.unreleased && release.version.includes("-"); + const name = release.unreleased ? words.unreleased : `${product} ${release.version}`; + const date = release.date && day ? : null; + const counts = [ + total ? {words.changes(total)} : null, + action.length ? {words.needAction(action.length)} : null, + ]; + const badges = pre || yours ? ( + + {pre ? {words.preRelease} : null} + {yours ? {words.yourVersion} : null} + + ) : null; + const facts = counts.filter(Boolean); + const headingId = `${id}-heading`; + const heading = release.title ? ( + <> + + {release.version}{date} + : + {release.title} + + {facts.length || badges ?

    {facts}{badges}

    : null} + + ) : ( + <> + + {release.unreleased ? words.unreleased : release.version} + {date ? , {day} : null} + + {date || facts.length || badges ?

    {date}{facts}{badges}

    : null} + + ); + const summary = release.summary ?

    {release.summary}

    : null; + const actionBlock = action.length ? ( + {words.actionNeeded}} + > + {form === "reference" && release.previous ?

    {words.beforeUpgrading(release.previous, action.length)}

    : null} + +
    + ) : null; + return ( +
    +
    +
    + + {heading} +
    + + {words.copyLink} + +
    + {leads ? null : summary} + {actionBlock} + {leads ? release.audiences!.map((audience, index) => ( +
    + {audience.for ? {audience.for} : null} +

    {audience.text}

    +
    + )) : null} + {folded ? ( +
    + {action.length ? words.otherChanges : words.allChanges}}> + {summary} + + +
    + ) : ( + <> + {leads ? summary : null} + + + )} + {yours && runningBuild?.length ? : null} +
    + ); +} + +/** The releases from their records. See the module note. */ +export function ReleaseNotes({ releases, form, product, baseHref, running, runningBuild, headingLevel = 2, arrived, onArrivedEnd, words: wordsProp, locale = "en-US", className, ...props }: ReleaseNotesProps) { + const words = React.useMemo(() => ({ ...WORDS, ...wordsProp, sections: { ...WORDS.sections, ...wordsProp?.sections } }), [wordsProp]); + const drawn = React.useMemo(() => releases.filter((release) => !(form === "notes" && release.unreleased)), [releases, form]); + const base = useBase(baseHref); + const raw = useTarget(arrived); + // A version that a drawn release replaces opens that release. + const target = React.useMemo(() => { + if (!raw) return null; + const stable = drawn.find((release) => release.replaces?.some((version) => `v${version}` === raw)); + return stable ? releaseId(stable) : raw; + }, [raw, drawn]); + // Without script every fold is open; once the page runs, they start closed. + const [wired, setWired] = React.useState(false); + const [open, setOpen] = React.useState>(() => new Set()); + React.useLayoutEffect(() => setWired(true), []); + const folds = React.useMemo(() => { + const all: string[] = ["build"]; + const holding = new Map(); + for (const release of drawn) { + const own = foldsOf(release, form); + all.push(...own.all); + for (const [entry, fold] of own.holding) holding.set(entry, fold); + } + return { all, holding }; + }, [drawn, form]); + // The arrival opens every fold that holds its target. + React.useEffect(() => { + const fold = target ? folds.holding.get(target) : undefined; + if (fold) setOpen((now) => (now.has(fold) ? now : new Set([...now, fold]))); + }, [target, folds]); + const setFold = React.useCallback((key: string, next: boolean) => setOpen((now) => { + const copy = new Set(now); + if (next) copy.add(key); + else copy.delete(key); + return copy; + }), []); + const shared: Shared = { + words, + base, + locale, + level: headingLevel, + target, + onArrivedEnd, + open: wired ? open : new Set(folds.all), + setFold, + }; + const matches = running !== undefined && drawn.some((release) => !release.unreleased && release.version === running); + return ( +
    + {running !== undefined && !matches && runningBuild?.length ? : null} + {drawn.map((release) => )} +
    + ); +} diff --git a/packages/react/src/release-types.ts b/packages/react/src/release-types.ts new file mode 100644 index 00000000..84c9b49e --- /dev/null +++ b/packages/react/src/release-types.ts @@ -0,0 +1,54 @@ +// The record a release page is drawn from (DECISIONS 320, 3.4): what `tools/changelog` writes, one entry per change. Basalt's own types, so an app's +// type-check reads no tool's declarations. Types only: nothing here runs. + +/** The sections a change stands in, in the order every output draws them, under "Action needed". */ +export type ReleaseEntryType = "security" | "deprecated" | "removed" | "added" | "changed" | "fixed"; + +/** The least version bump a change needs. */ +export type ReleaseBump = "major" | "minor" | "patch"; + +export interface ReleaseEntryRecord { + /** Permanent: set when the entry is written and never changed or reused. The entry's address on the page ("#pr120-1"). */ + id: string; + type: ReleaseEntryType; + bump: ReleaseBump; + /** The component or page it concerns ("FormGrid", "Home"), drawn before the sentence at 500. */ + area?: string; + /** One sentence. Backticks mark code; nothing else in it is markup. */ + text: string; + /** Someone must do something: the entry stands under "Action needed" and nowhere else in its release. */ + action?: boolean; + /** Its migration note, drawn as a link on its own line under the sentence. */ + link?: { label: string; href: string }; + pr?: { number: number; href: string }; + commit?: { sha: string; href?: string }; + /** At most two are on the source line, then "3 more"; every one is in the sources panel. */ + tickets?: { tracker: string; label: string; href?: string }[]; + /** Who wrote the entry's words, or said they take authorship of them. Absent when nobody has: the panel then has no Author row. */ + authors?: string[]; +} + +export interface ReleaseAudience { + /** The group's own word ("For admins"), an `h3`. Absent for a paragraph for everyone. */ + for?: string; + text: string; + /** The entries the paragraph is about. */ + covers: string[]; +} + +export interface ReleaseRecord { + /** SemVer ("1.4.0", "2.0.0-rc.2"), or "Unreleased" with `unreleased`. */ + version: string; + /** The ship date, `YYYY-MM-DD`. Absent while unreleased. */ + date?: string; + unreleased?: boolean; + /** The release this one was checked against: "Before upgrading from 0.1.0". */ + previous?: string; + /** The pre-releases of this version, no longer drawn: their addresses open this release. */ + replaces?: string[]; + /** A product's headline: "A monitor can open an incident room". */ + title?: string; + summary?: string; + audiences?: ReleaseAudience[]; + entries: ReleaseEntryRecord[]; +} diff --git a/packages/react/src/site-footer.tsx b/packages/react/src/site-footer.tsx index c60456e9..e88bd3f3 100644 --- a/packages/react/src/site-footer.tsx +++ b/packages/react/src/site-footer.tsx @@ -7,6 +7,7 @@ import type { SiteHeaderLink } from "./site-nav"; import { ThemeChoiceControl } from "./theme-choice"; import type { ThemeChoiceWords } from "./theme-choice"; import { join } from "./utils"; +import { VersionPlaceContext } from "./version-place"; // The site footer (DECISIONS 146 A): the end of every site page, on the page at level 0 with no fill, rim or shadow. The brand, an optional sentence and social links; the // links, either one unlabelled line of up to six beside the brand or labelled groups; then the base: the legal line and the theme choice, both required. One 1px divider the @@ -33,6 +34,8 @@ export interface SiteFooterProps extends Omit, "c groups?: SiteFooterGroup[]; /** The legal line: required. At most `size-prose-width`, in tertiary ink. */ legal: React.ReactNode; + /** The version, as a `VersionLink` labelled with the product ("Basalt 0.2.0 · Nov 23, 2026"), on the legal line's row after it, at its 13/18. */ + version?: React.ReactNode; /** The links' landmark name. Default "Footer". */ navLabel?: string; /** The theme choice's words, for translation. The theme choice is always in the footer, since the site header has none. */ @@ -60,7 +63,7 @@ function Group({ group, id }: { group: SiteFooterGroup; id: string }) { * The site footer. Put it last on the page, after `main`, inside `SitePage` so a short page keeps it at the window's foot. The site's own: its words, which groups and * links, the note, the brand, the legal text and what the footer sits on (a mass). Basalt's: the order, the pill links at `sm`, the disclosures, the divider and the theme choice. */ -export function SiteFooter({ brand, note, social, links, groups, legal, navLabel = "Footer", themeWords, className, ...props }: SiteFooterProps) { +export function SiteFooter({ brand, note, social, links, groups, legal, version, navLabel = "Footer", themeWords, className, ...props }: SiteFooterProps) { const base = React.useId(); // Disclosures are drawn once script has run: without it every group is open and two a row. const [wired, setWired] = React.useState(false); @@ -92,7 +95,12 @@ export function SiteFooter({ brand, note, social, links, groups, legal, navLabel )}
    -

    {legal}

    + {version ? ( +
    +

    {legal}

    + {version} +
    + ) :

    {legal}

    }
    diff --git a/packages/react/src/stream.tsx b/packages/react/src/stream.tsx index d950d169..cf3e2766 100644 --- a/packages/react/src/stream.tsx +++ b/packages/react/src/stream.tsx @@ -2,10 +2,13 @@ import * as React from "react"; import { Avatar } from "./composition"; import { DotSep } from "./dot-sep"; -import { useInShape } from "./in-shape"; +import { useArrival } from "./arrival"; +import type { ArrivalProps } from "./arrival"; import { inLevel, usePanelLevel } from "./layers"; import { join } from "./utils"; +export type { ArrivalProps } from "./arrival"; + // ---- The stream ---- // A conversation or a timeline, oldest first: a support thread, a team chat, a document's comments, an agent's run, a project's history. One // column, one order. A message is an avatar, a name, a time and its words; consecutive messages from one author join (the app says which, since @@ -21,98 +24,6 @@ import { join } from "./utils"; // word stays. const DEFAULT_ARRIVED = "Linked"; -/** Keys that read around the entry rather than act: they leave the mark where it is. A pattern, not a set, so loading the module builds nothing. */ -const reading = (key: string) => /^(Arrow(Up|Down|Left|Right)|Page(Up|Down)|Home|End| |Shift|Control|Alt|Meta|CapsLock)$/.test(key); - -export interface ArrivalProps { - /** This is the entry a link, a search result or a notice opened: it is scrolled to, focused and marked until the reader acts. */ - arrived?: boolean; - /** The word that says so, in the entry's head. Default "Linked"; an app says why in its own words ("Search result", "From your notice"). */ - arrivedLabel?: string; - /** The reader has acted, so the mark is going. Without it the part ends the mark itself; with it, the app may also clear `arrived`. */ - onArrivedEnd?: () => void; -} - -// One entry arrives at a time. The one placed last is the one the reader is at: placing another ends the one before (its `onArrivedEnd` is -// called). Assigned only while an entry is arrived, so loading this module does nothing. -let current: { end: () => void } | undefined; - -/** Whether the element has a box the reader can see: not under `display: none` (nor `content-visibility: hidden`). */ -const shown = (el: HTMLElement) => el.getClientRects().length > 0 && (typeof el.checkVisibility !== "function" || el.checkVisibility()); - -/** The nearest ancestor that scrolls the entry on the block axis, or null when it is the page. */ -function scrollerOf(el: HTMLElement): HTMLElement | null { - for (let at = el.parentElement; at && at !== document.body && at !== document.documentElement; at = at.parentElement) { - const { overflowY } = getComputedStyle(at); - if ((overflowY === "auto" || overflowY === "scroll") && at.scrollHeight > at.clientHeight) return at; - } - return null; -} - -/** - * The arrival's state: shown while `arrived` and the reader has not acted yet. Once the entry has a box (a pane it sits in may be hidden when it - * mounts) it is scrolled to and focused, once each time it turns on, and from then the reader's first act ends it. - */ -function useArrival({ arrived = false, onArrivedEnd }: ArrivalProps) { - const inShape = useInShape(); - const ref = React.useRef(null); - const [ended, setEnded] = React.useState(false); - const [ever, setEver] = React.useState(false); - const [placed, setPlaced] = React.useState(false); - const end = React.useRef(onArrivedEnd); - end.current = onArrivedEnd; - React.useEffect(() => { if (arrived) setEnded(false); }, [arrived]); - const on = arrived && !ended && inShape === 0; - React.useEffect(() => { if (!on) setPlaced(false); }, [on]); - React.useLayoutEffect(() => { - if (!on || placed) return undefined; - const el = ref.current; - if (!el) return undefined; - const place = () => { - // A short entry is brought to the middle of what scrolls it; one taller than most of that (the pane's visible height, or the window's), to its top. - const scroller = scrollerOf(el); - const room = scroller ? scroller.clientHeight : window.innerHeight; - el.scrollIntoView({ block: el.getBoundingClientRect().height > room * 0.6 ? "start" : "center", inline: "nearest" }); - el.focus({ preventScroll: true }); - setEver(true); - setPlaced(true); - }; - if (shown(el)) { place(); return undefined; } - // Not laid out yet (a hidden tab or pane): wait until it has a box, then place it once. - const watch = new ResizeObserver(() => { if (shown(el)) { watch.disconnect(); place(); } }); - watch.observe(el); - return () => watch.disconnect(); - }, [on, placed]); - React.useEffect(() => { - if (!on || !placed) return undefined; - const finish = () => { setEnded(true); end.current?.(); }; - const self = { end: finish }; - if (current && current !== self) current.end(); - current = self; - const act = (event: Event) => { - if (event.type === "keydown") { - const key = (event as KeyboardEvent).key; - const inField = (event.target as Element | null)?.closest?.("input, textarea, select, [contenteditable='true'], [contenteditable='']"); - if (reading(key) && !(key === " " && inField)) return; - } - finish(); - }; - // From the next frame, so the press or key that opened the entry does not end its mark. - const frame = requestAnimationFrame(() => { - document.addEventListener("pointerdown", act, true); - document.addEventListener("keydown", act, true); - }); - return () => { - if (current === self) current = undefined; - cancelAnimationFrame(frame); - document.removeEventListener("pointerdown", act, true); - document.removeEventListener("keydown", act, true); - }; - }, [on, placed]); - // Once it has arrived the entry stays a focus target, so taking the mark away never drops the reader's focus. - const attrs = { ref, tabIndex: ever || on ? -1 : undefined, "data-arrival": ever || on ? "" : undefined, "data-arrived": on ? "" : undefined }; - return { on, ever: ever || on, attrs }; -} // A message's head shows the word when the message itself, or a block in it, is the one arrived, in the arriving entry's own words. A message with // no head drawn (joined) has no place for it: a block there draws its word itself. diff --git a/packages/react/src/styles/components.css b/packages/react/src/styles/components.css index b6b849cf..47c967f4 100644 --- a/packages/react/src/styles/components.css +++ b/packages/react/src/styles/components.css @@ -7152,6 +7152,221 @@ .basalt-stream-word { color: CanvasText; } } + /* ---- Versions and release notes (DECISIONS 320). ---- */ + /* The version with its date, one link (VersionLink). 12/16 Geist, tabular, secondary ink; hover lifts it to primary and underlines both parts. + Two parts that never break inside, the word with the number (joined by a no-break space) and the date: when they do not fit one line the + date goes under the number. The dot stands in the gap before the date, so a date that has gone under starts its line with no dot: the gap + is then left of the link's own box, which clips it on the inline axis. A version longer than the place wraps anywhere. */ + .basalt-version-link { + position: relative; + box-sizing: border-box; + display: inline-flex; + flex-wrap: wrap; + align-items: baseline; + column-gap: var(--basalt-space-3); + max-width: 100%; + overflow-x: clip; + padding-block: var(--basalt-space-1); + border-radius: var(--basalt-radius-xs); + color: var(--basalt-text-secondary); + font: var(--basalt-font-weight-regular) var(--basalt-text-xs-size) / var(--basalt-text-xs-line-height) var(--basalt-font-family-sans); + letter-spacing: var(--basalt-text-xs-tracking); + font-variant-numeric: tabular-nums; + text-decoration: none; + -webkit-tap-highlight-color: transparent; + transition: color var(--basalt-duration-fast) var(--basalt-ease-out); + } + .basalt-version-link-words, .basalt-version-link-date { position: relative; min-width: 0; overflow-wrap: anywhere; } + .basalt-version-link-date::before { content: "·"; content: "·" / ""; position: absolute; inset-inline-end: 100%; width: var(--basalt-space-3); text-align: center; } + .basalt-version-link-pre { display: inline-block; max-width: 100%; } + /* The number reserves its 600 width, so being the current page moves nothing. */ + .basalt-version-link-number { display: inline-flex; flex-direction: column; max-width: 100%; } + .basalt-version-link-number::after { content: attr(data-label); height: 0; overflow: hidden; visibility: hidden; font-weight: var(--basalt-font-weight-semibold); user-select: none; pointer-events: none; } + .basalt-version-link:hover { color: var(--basalt-text-primary); } + .basalt-version-link:hover :is(.basalt-version-link-words, .basalt-version-link-date > time) { text-decoration: underline; text-decoration-thickness: var(--basalt-size-hairline); text-underline-offset: var(--basalt-size-underline-offset); } + .basalt-version-link:focus-visible { outline: var(--basalt-size-focus-width) solid var(--basalt-border-focus); outline-offset: var(--basalt-size-focus-offset); } + .basalt-version-link[aria-current="page"] { color: var(--basalt-text-primary); } + .basalt-version-link[aria-current="page"] .basalt-version-link-number { font-weight: var(--basalt-font-weight-semibold); } + /* On touch a 44px hit box that moves nothing. */ + @media (pointer: coarse) { + .basalt-version-link::after { content: ""; position: absolute; inset-inline: 0; top: 50%; height: max(100%, var(--basalt-size-tap-min)); transform: translateY(-50%); } + } + /* At the sidebar's foot: under the account items, space-2 below them, the words on the nav glyphs' start edge (the nav's space-1-5 and the + pill's space-3 in from the sidebar's own padding). The foot's own space-4 is below. */ + .basalt-app-version { margin: var(--basalt-space-2) calc(var(--basalt-space-1-5) + var(--basalt-space-3)) 0; } + /* In the rail: the number alone, centred, breaking before a pre-release's hyphen if it must; the label and the date are in its name and its tooltip. */ + .basalt-version-link[data-place="rail"] { display: flex; justify-content: center; text-align: center; } + /* stylelint-disable-next-line unit-disallowed-list -- the 1px clip box of the visually-hidden pattern; it must be exactly 1px */ + .basalt-version-link[data-place="rail"] :is(.basalt-version-link-word, .basalt-version-link-date) { position: absolute; width: 1px; height: 1px; margin: -1px; padding: 0; overflow: hidden; clip: rect(0 0 0 0); white-space: nowrap; border: 0; } + /* stylelint-disable-next-line unit-disallowed-list -- size-breakpoint-md (720px) and size-breakpoint-lg (1024px): a media query cannot read a token; from 720 the rail, from 1024 the sidebar */ + @media (width >= 720px) and (width < 1024px) { + .basalt-app-version { margin-inline: var(--basalt-space-1-5); } + } + /* The last row of More's sheet: under a divider, space-2 below the list, 44 tall, at 13/18, on the nav glyphs' edge. */ + .basalt-tabbar-version { + box-sizing: border-box; + display: flex; + align-items: center; + min-height: var(--basalt-size-tap-min); + margin-top: var(--basalt-space-2); + padding-inline: calc(var(--basalt-space-1-5) + var(--basalt-space-3)); + border-top: var(--basalt-size-hairline) solid var(--basalt-border-divider); + } + .basalt-version-link:is([data-place="more"], [data-place="footer"]) { font-size: var(--basalt-text-sm-size); line-height: var(--basalt-text-sm-line-height); letter-spacing: var(--basalt-text-sm-tracking); } + /* A site's footer: after the legal line, on its row, space-4 apart, wrapping under it. */ + .basalt-site-footer-legal-row { display: flex; flex-wrap: wrap; align-items: baseline; gap: var(--basalt-space-1) var(--basalt-space-4); min-width: 0; } + + /* A release. One column, at most the words' measure, space-6 and room for a source line; space-10 apart with a divider between. Its own + container, so the source line goes under the words below 640 of the release's own width. */ + .basalt-release-notes { min-width: 0; font-family: var(--basalt-font-family-sans); color: var(--basalt-text-primary); } + .basalt-release { + container-type: inline-size; + max-width: calc(var(--basalt-size-prose-width) + var(--basalt-space-6) + var(--basalt-size-sidebar-width)); + padding-block: var(--basalt-space-10); + border-top: var(--basalt-size-hairline) solid var(--basalt-border-divider); + scroll-margin-top: calc(var(--basalt-sticky-offset) + var(--basalt-space-4)); + } + .basalt-release:first-of-type { padding-top: 0; border-top: 0; } + .basalt-release-notes > .basalt-release-build:first-child { max-width: calc(var(--basalt-size-prose-width) + var(--basalt-space-6) + var(--basalt-size-sidebar-width)); margin: 0 0 var(--basalt-space-6); } + .basalt-release:focus, .basalt-release-entry:focus { outline: none; } + .basalt-release-head { display: flex; align-items: flex-start; justify-content: space-between; gap: var(--basalt-space-4); } + .basalt-release-head-text { position: relative; isolation: isolate; display: grid; gap: var(--basalt-space-1); min-width: 0; } + .basalt-release-heading { display: grid; gap: var(--basalt-space-1); margin: 0; font: var(--basalt-font-weight-semibold) var(--basalt-text-2xl-size) / var(--basalt-text-2xl-line-height) var(--basalt-font-family-sans); letter-spacing: var(--basalt-text-2xl-tracking); text-wrap: balance; overflow-wrap: break-word; } + /* The number standing alone is mono; in a line with its date (a headline's meta line) it is Geist, as at the foot. */ + .basalt-release-version { font-family: var(--basalt-font-family-mono); letter-spacing: 0; font-variant-numeric: tabular-nums; overflow-wrap: anywhere; } + .basalt-release-version[data-words] { font-family: var(--basalt-font-family-sans); letter-spacing: var(--basalt-text-2xl-tracking); } + .basalt-release-meta { margin: 0; color: var(--basalt-text-secondary); font: var(--basalt-font-weight-regular) var(--basalt-text-sm-size) / var(--basalt-text-sm-line-height) var(--basalt-font-family-sans); letter-spacing: var(--basalt-text-sm-tracking); font-variant-numeric: tabular-nums; } + .basalt-release-badges { display: inline-flex; gap: var(--basalt-space-2); margin-inline-start: var(--basalt-space-2); vertical-align: middle; } + .basalt-release-action-link { position: relative; color: inherit; text-decoration: underline; text-decoration-color: var(--basalt-border-input); text-decoration-thickness: var(--basalt-size-hairline); text-underline-offset: var(--basalt-size-underline-offset); border-radius: var(--basalt-radius-xs); } + .basalt-release-action-link:hover { color: var(--basalt-text-primary); text-decoration-color: currentColor; } + .basalt-release-action-link:focus-visible { outline: var(--basalt-size-focus-width) solid var(--basalt-border-focus); outline-offset: var(--basalt-size-focus-offset); } + .basalt-release-copy { flex: none; } + .basalt-release-summary, .basalt-release-paragraph { margin: 0; max-width: var(--basalt-size-prose-width); font-size: var(--basalt-text-md-size); line-height: var(--basalt-text-md-line-height); letter-spacing: var(--basalt-text-md-tracking); text-wrap: pretty; } + .basalt-release-summary { margin-top: var(--basalt-space-4); } + .basalt-release-audience { display: grid; gap: var(--basalt-space-1); margin-top: var(--basalt-space-4); } + .basalt-release-audience-title { margin: 0; font: var(--basalt-font-weight-semibold) var(--basalt-text-md-size) / var(--basalt-text-md-line-height) var(--basalt-font-family-sans); letter-spacing: var(--basalt-text-md-tracking); } + .basalt-release-action { margin-top: var(--basalt-space-6); } + .basalt-release-callout-title { margin: 0; font: inherit; letter-spacing: inherit; } + .basalt-release-action .basalt-callout-text { color: var(--basalt-text-primary); } + .basalt-release-upgrade { margin: 0 0 var(--basalt-space-2); color: var(--basalt-text-secondary); } + .basalt-release-section, .basalt-release-all { margin-top: var(--basalt-space-6); } + .basalt-release-section-title { margin: 0 0 var(--basalt-space-2); font: var(--basalt-font-weight-semibold) var(--basalt-text-md-size) / var(--basalt-text-md-line-height) var(--basalt-font-family-sans); letter-spacing: var(--basalt-text-md-tracking); } + .basalt-release-count { margin-inline-start: var(--basalt-space-1); color: var(--basalt-text-tertiary); font-weight: var(--basalt-font-weight-regular); font-variant-numeric: tabular-nums; } + .basalt-release-action .basalt-release-count { color: var(--basalt-text-secondary); } + /* Inside a product's fold: the summary first, space-2 under the fold's heading; the sections' headings a step smaller. Nothing folds again. */ + .basalt-release-all .basalt-release-summary { margin-top: var(--basalt-space-2); } + .basalt-release-all .basalt-release-section:first-child { margin-top: var(--basalt-space-2); } + .basalt-release-all .basalt-release-summary + .basalt-release-section { margin-top: var(--basalt-space-4); } + .basalt-release-all .basalt-release-section-title { font-size: var(--basalt-text-base-size); line-height: var(--basalt-text-base-line-height); letter-spacing: var(--basalt-text-base-tracking); } + /* A fold: its heading holds the button, at the section heading's size, the chevron at the release's end. */ + .basalt-release-fold .basalt-accordion-trigger { min-height: var(--basalt-text-md-line-height); padding: 0; font: var(--basalt-font-weight-semibold) var(--basalt-text-md-size) / var(--basalt-text-md-line-height) var(--basalt-font-family-sans); letter-spacing: var(--basalt-text-md-tracking); } + .basalt-release-fold .basalt-accordion-content { padding-bottom: 0; font: inherit; color: inherit; } + .basalt-release-section[data-folded] .basalt-accordion-content { padding-top: var(--basalt-space-2); } + /* Build details: at the release's foot, quieter than the fold above it (14/20, 400). */ + .basalt-release-build { margin-top: var(--basalt-space-2); } + .basalt-release-build .basalt-accordion-trigger { min-height: var(--basalt-size-control-xs); font: var(--basalt-font-weight-regular) var(--basalt-text-base-size) / var(--basalt-text-base-line-height) var(--basalt-font-family-sans); letter-spacing: var(--basalt-text-base-tracking); } + .basalt-release-build-list { margin-block: var(--basalt-space-3); } + + /* The list is a grid and each entry a subgrid of it: column one the words, at most the measure; column two the source lines, as wide as the + list's widest, space-6 away, starting on one edge. So the words keep one measure down a list. */ + .basalt-release-list { display: grid; grid-template-columns: minmax(0, var(--basalt-size-prose-width)) auto; justify-content: start; column-gap: var(--basalt-space-6); margin: 0; padding: 0; list-style: none; } + .basalt-release-entry { + position: relative; + display: grid; + grid-template-columns: subgrid; + grid-column: 1 / -1; + align-items: baseline; + padding-block: var(--basalt-space-1-5); + scroll-margin-top: calc(var(--basalt-sticky-offset) + var(--basalt-space-8)); + } + .basalt-release-word { grid-column: 1 / -1; } + .basalt-release-entry-words { grid-column: 1; display: grid; justify-items: start; gap: var(--basalt-space-1); min-width: 0; } + .basalt-release-entry-text { margin: 0; color: var(--basalt-text-primary); font-size: var(--basalt-text-base-size); line-height: var(--basalt-text-base-line-height); letter-spacing: var(--basalt-text-base-tracking); text-wrap: pretty; overflow-wrap: break-word; } + .basalt-release-area { font-weight: var(--basalt-font-weight-medium); } + .basalt-release-migrate { position: relative; font-size: var(--basalt-text-base-size); line-height: var(--basalt-text-base-line-height); } + .basalt-release-source-cell { grid-column: 2; justify-self: start; min-width: 0; } + .basalt-release-source-cell:empty { display: none; } + /* The source line: a quiet TextButton in Geist Mono at 13 on the entry's 20px line, its hit 24 tall on a fine pointer. Ids never break inside + (an id longer than the line breaks anywhere); beside the words the line does not wrap. */ + .basalt-text-button.basalt-release-source { display: inline; padding-block: var(--basalt-space-0-5); margin-block: calc(-1 * var(--basalt-space-0-5)); font-family: var(--basalt-font-family-mono); font-size: var(--basalt-text-sm-size); line-height: var(--basalt-text-base-line-height); letter-spacing: 0; white-space: nowrap; } + /* Each id carries the underline (an id never breaks inside, so it is a box of its own, which a label's underline would not reach). */ + .basalt-text-button.basalt-release-source > .basalt-text-button-label { text-decoration: none; } + .basalt-release-id { display: inline-block; max-width: 100%; overflow-wrap: anywhere; text-decoration: underline; text-decoration-color: var(--basalt-border-input); text-decoration-thickness: var(--basalt-size-hairline); text-underline-offset: var(--basalt-size-underline-offset); transition: text-decoration-color var(--basalt-duration-fast) var(--basalt-ease-out); } + .basalt-release-source:hover .basalt-release-id { text-decoration-color: currentColor; } + .basalt-release-action-link { white-space: nowrap; } + .basalt-release-sources { width: var(--basalt-size-popover-max); } + .basalt-release-sources-list { margin-block: var(--basalt-space-2) var(--basalt-space-4); } + .basalt-release-mono { font-family: var(--basalt-font-family-mono); font-size: var(--basalt-text-sm-size); } + /* Narrow (under 640 of the release's own width): the source line is its own line under the words, space-0-5 below, wrapping between ids. */ + /* stylelint-disable-next-line basalt/container-length -- size-breakpoint-container-lg (640px): a container query cannot read a custom property */ + @container (width < 640px) { + .basalt-release-list { grid-template-columns: minmax(0, 1fr); } + .basalt-release-entry { row-gap: var(--basalt-space-0-5); padding-block: var(--basalt-space-2); } + .basalt-release-source-cell { grid-column: 1; } + .basalt-text-button.basalt-release-source { padding-block: calc((var(--basalt-size-control-xs) - var(--basalt-text-sm-line-height)) / 2); margin-block: calc((var(--basalt-text-sm-line-height) - var(--basalt-size-control-xs)) / 2); line-height: var(--basalt-text-sm-line-height); white-space: normal; } + } + /* On touch every 44px box lies inside its own entry: an entry is space-3 above and below (a one-line entry is 44 tall), the source line keeps + the entry's 20px line, and "4 need action" and the migration link take the box too, with no change to layout. */ + @media (pointer: coarse) { + .basalt-release-entry { padding-block: var(--basalt-space-3); } + .basalt-text-button.basalt-release-source { line-height: var(--basalt-text-base-line-height); } + .basalt-text-button.basalt-release-source::before, + .basalt-release-action-link::after, + .basalt-release-migrate::after { content: ""; position: absolute; top: 50%; left: 50%; /* physical: it is centred, in either direction */ width: max(100%, var(--basalt-size-tap-min)); height: var(--basalt-size-tap-min); transform: translate(-50%, -50%); } + .basalt-release-fold .basalt-accordion-trigger { min-height: var(--basalt-size-tap-min); } + /* stylelint-disable-next-line basalt/container-length -- size-breakpoint-container-lg (640px): a container query cannot read a custom property */ + @container (width < 640px) { + .basalt-text-button.basalt-release-source { padding-block: calc((var(--basalt-size-control-xs) - var(--basalt-text-base-line-height)) / 2); margin-block: calc((var(--basalt-text-base-line-height) - var(--basalt-size-control-xs)) / 2); line-height: var(--basalt-text-base-line-height); } + /* A link with a source line under it: space-6 between the two (10 + 24 + 10, so the two boxes meet and do not overlap) and space-6 under + the entry, so the source line stays nearer its own entry than the next one. */ + .basalt-release-entry[data-link]:has(.basalt-release-source) { row-gap: var(--basalt-space-6); padding-bottom: var(--basalt-space-6); } + } + } + + /* The entry, or the release, a link opened: the stream's arrival (the plate and the word "Linked"). An entry takes the plate itself, a release + on its header. Tertiary words on the plate step to secondary; in forced colours the plate goes and the word stays. */ + .basalt-release-entry[data-arrival] { isolation: isolate; } + :is(.basalt-release-entry[data-arrival], .basalt-release[data-arrival] .basalt-release-head-text)::before { + content: ""; position: absolute; z-index: -1; inset: calc(-1 * var(--basalt-space-1)) calc(-1 * var(--basalt-space-2)); border-radius: var(--basalt-radius-md); pointer-events: none; + background-color: transparent; transition: background-color calc(var(--basalt-duration-slow) * 0.75) var(--basalt-ease-in); + } + :is(.basalt-release-entry[data-arrived], .basalt-release[data-arrived] .basalt-release-head-text)::before { background-color: var(--basalt-plate); transition-duration: var(--basalt-duration-instant); } + :is(.basalt-release-entry[data-arrived], .basalt-release[data-arrived] .basalt-release-head-text) .basalt-release-count { color: var(--basalt-text-secondary); } + @media (forced-colors: active) { + :is(.basalt-release-entry[data-arrival], .basalt-release[data-arrival] .basalt-release-head-text)::before { display: none; } + } + + /* The versions: a nav of links, the number in mono and primary, the date at the row's end in tertiary, 13/18, 30 tall and 44 on touch. + The pane form beside the page; the fold form above the first release where the pane would follow the page instead. */ + .basalt-release-index-title { margin: 0 0 var(--basalt-space-2); font: var(--basalt-font-weight-medium) var(--basalt-text-sm-size) / var(--basalt-text-sm-line-height) var(--basalt-font-family-sans); letter-spacing: var(--basalt-text-sm-tracking); } + .basalt-release-index-list { display: grid; margin: 0; padding: 0; list-style: none; } + .basalt-release-index-link { display: flex; align-items: baseline; justify-content: space-between; gap: var(--basalt-space-4); padding-block: var(--basalt-space-1-5); border-radius: var(--basalt-radius-xs); color: var(--basalt-text-secondary); font: var(--basalt-font-weight-regular) var(--basalt-text-sm-size) / var(--basalt-text-sm-line-height) var(--basalt-font-family-sans); font-variant-numeric: tabular-nums; text-decoration: none; } + .basalt-release-index-number { color: var(--basalt-text-primary); font-family: var(--basalt-font-family-mono); letter-spacing: 0; overflow-wrap: anywhere; } + .basalt-release-index-number[data-words] { font-family: var(--basalt-font-family-sans); } + .basalt-release-index-link time { flex: none; color: var(--basalt-text-tertiary); } + .basalt-release-index-link:hover .basalt-release-index-number { text-decoration: underline; text-decoration-thickness: var(--basalt-size-hairline); text-underline-offset: var(--basalt-size-underline-offset); } + .basalt-release-index-link:focus-visible { outline: var(--basalt-size-focus-width) solid var(--basalt-border-focus); outline-offset: var(--basalt-size-focus-offset); } + .basalt-release-index[data-form="fold"] { margin-bottom: var(--basalt-space-8); } + .basalt-release-index[data-form="fold"] .basalt-accordion-trigger { font: var(--basalt-font-weight-medium) var(--basalt-text-sm-size) / var(--basalt-text-sm-line-height) var(--basalt-font-family-sans); } + @media (pointer: coarse) { + .basalt-release-index-link { align-items: center; min-height: var(--basalt-size-tap-min); padding-block: 0; } + } + /* Where PaneLayout puts its pane beside the page the pane form shows; where the pane follows the page, the fold does, and the pane is not drawn. */ + .basalt-release-index[data-form="fold"] { display: none; } + /* stylelint-disable-next-line basalt/container-length -- size-sidebar-width (256px) + size-gutter (24px) + size-breakpoint-container-lg (640px), PaneLayout's own threshold; a container query cannot read a custom property */ + @container (width < 920px) { + .basalt-pane-layout .basalt-release-index[data-form="fold"] { display: block; } + .basalt-pane:has(> .basalt-release-index[data-form="pane"]) { display: none; } + } + + /* Print and no script: every fold is open (the parts draw them open until script runs); Copy buttons are not printed, and a source line prints as text. */ + @media print { + :is(.basalt-release-notes, .basalt-release-index) .basalt-accordion-panel { height: auto; overflow: visible; content-visibility: visible; } + :is(.basalt-release-notes, .basalt-release-index) .basalt-accordion-panel[hidden] { display: block; } + .basalt-release-copy, .basalt-release-notes .basalt-copy-button, .basalt-release-sources, .basalt-release-build .basalt-button { display: none; } + .basalt-release-id { text-decoration: none; } + } + /* ---- The disclosure row: a button on one line (cut while closed, wrapped when open), its mark, its meta and the core chevron, which morphs from right to down. Hover lifts the ink; there is no wash. Focus is the control ring at +2. 28 tall (44 on touch), text at 13. ---- */ .basalt-disclosure { min-width: 0; } diff --git a/packages/react/src/tab-bar.tsx b/packages/react/src/tab-bar.tsx index 62d30b4f..9bafbbcc 100644 --- a/packages/react/src/tab-bar.tsx +++ b/packages/react/src/tab-bar.tsx @@ -10,6 +10,7 @@ import type { IconComponent } from "./types"; import { useScreenKeyboardLayout } from "./screen-keyboard"; import { useKeysMark } from "./use-media"; import { join } from "./utils"; +import { VersionContext, VersionPlaceContext } from "./version-place"; // The phone tab bar (decisions 96): the destinations of an app under 720, always glyph over label. It is navigation, so a // `nav` of links with `aria-current="page"`, never a tablist. Solid `surface-page` with a hairline on top: the header is the @@ -96,9 +97,14 @@ export interface TabBarMoreProps { children: React.ReactNode; } -/** The last cell when there are more than five destinations: a button that opens the rest in a bottom `Sheet`. */ +/** + * The last cell when there are more than five destinations: a button that opens the rest in a bottom `Sheet`. Inside `AppShell` with a `version`, + * the sheet's last row is that version, under a divider (DECISIONS 320, 1.2). + */ export function TabBarMore({ icon = MoreNavGlyph, label = "More", current, dot, children }: TabBarMoreProps) { const [open, setOpen] = React.useState(false); + const version = React.useContext(VersionContext); + const closeOnLink = (event: React.MouseEvent) => { if ((event.target as Element).closest("a")) setOpen(false); }; const name = current ? `${label}, ${current}, current page` : label; return (
  • @@ -112,7 +118,8 @@ export function TabBarMore({ icon = MoreNavGlyph, label = "More", current, dot, {label} } /> - + + {version ?
    {version}
    : null}
  • diff --git a/packages/react/src/version-link.tsx b/packages/react/src/version-link.tsx new file mode 100644 index 00000000..ca5d41c6 --- /dev/null +++ b/packages/react/src/version-link.tsx @@ -0,0 +1,72 @@ +import * as React from "react"; + +import { DotSep } from "./dot-sep"; +import { formatReleaseDate } from "./release-date"; +import { join } from "./utils"; +import { RailTooltipContext, VersionPlaceContext } from "./version-place"; + +// The version with its ship date, as one link to the release notes at that version (DECISIONS 320, 1.2): "Version 1.4.0 · Nov 23, 2026". It +// shows the version this session runs. It is the only way to the release notes (there is no "What's new" item), and nothing marks a release as +// new. 12/16 Geist in secondary ink, tabular, lifting to primary with an underline on hover; on the release notes it is the current page, its +// number at 600 with its width reserved. Two parts never break inside, the word with the number and the date: when both do not fit one line the +// date goes under the number and the dot is not drawn. 24 tall on a fine pointer, a 44px hit box on touch that moves nothing. +// +// Its place decides its form, set by the part that holds it: at the sidebar's foot under the account items; in the rail (720 to 1023) the +// number alone, centred, the label and the date in its name and its tooltip; the last row of More's sheet on a phone, at 13/18; after the legal +// line in a site's footer, at 13/18, labelled with the product. An app whose tab bar has no More draws it on its account or settings page. + +export interface VersionLinkProps extends Omit, "children"> { + /** SemVer without build metadata: "1.4.0", "2.0.0-rc.2". */ + version: string; + /** The day it shipped, an ISO calendar date ("2026-11-23"). Drawn "Nov 23, 2026" and never moved by a time zone. */ + date: string; + /** The release notes at this version: "/release-notes#v1.4.0". */ + href: string; + /** The word before the number. Default "Version"; a site's footer gives the product ("Basalt"). */ + label?: string; + /** The end of the link's name. Default "release notes". */ + destinationLabel?: string; + /** This page is the release notes. */ + current?: boolean; + /** Default "en-US". */ + locale?: string; +} + +/** The number, with a pre-release's hyphen kept with what follows it, so where the line is short it breaks before the hyphen. */ +function VersionNumber({ version }: { version: string }) { + const at = version.indexOf("-"); + if (at < 0) return <>{version}; + return <>{version.slice(0, at)}{version.slice(at)}; +} + +/** The version with its ship date, one link to the release notes at that version. See the module note. */ +export function VersionLink({ version, date, href, label = "Version", destinationLabel = "release notes", current = false, locale = "en-US", className, ...props }: VersionLinkProps) { + const place = React.useContext(VersionPlaceContext); + const day = formatReleaseDate(date, locale); + const rail = place === "rail"; + const RailTooltip = React.useContext(RailTooltipContext); + const link = ( + + + {/* A no-break space: the word and the number are one part. */} + {label}{"\u00a0"} + + + {" "} + + + + + ); + if (!rail || !RailTooltip) return link; + return {label} {version}{day}} side="right">{link}; +} diff --git a/packages/react/src/version-place.ts b/packages/react/src/version-place.ts new file mode 100644 index 00000000..0e148b80 --- /dev/null +++ b/packages/react/src/version-place.ts @@ -0,0 +1,20 @@ +import * as React from "react"; + +import type { TooltipProps } from "./display"; + +// Where a `VersionLink` is drawn, set by the part that holds it (DECISIONS 320, 1.2): the sidebar's foot ("foot"), the rail from 720 to 1023 +// ("rail"), the last row of More's sheet ("more") and a site's footer ("footer"). Anywhere else (an account page) it is the plain line. +// `AppShell` also hands the version itself to `TabBarMore` through `VersionContext`, as it hands the rail to `Nav`. Nothing runs when it loads. + +export type VersionPlace = "foot" | "rail" | "more" | "footer"; + +export const VersionPlaceContext = /* @__PURE__ */ React.createContext(null); + +/** The app shell's `version`, for More's sheet to draw as its last row. */ +export const VersionContext = /* @__PURE__ */ React.createContext(null); + +/** + * The rail's tooltip, handed down by `AppShell`, which already carries it for `Nav`. So a `VersionLink` in a site's footer or on an account page + * loads no tooltip at all. + */ +export const RailTooltipContext = /* @__PURE__ */ React.createContext | null>(null); diff --git a/packages/react/test/bundle.test.mjs b/packages/react/test/bundle.test.mjs index 0783bd0a..174e33af 100644 --- a/packages/react/test/bundle.test.mjs +++ b/packages/react/test/bundle.test.mjs @@ -670,3 +670,19 @@ test("the imports plugin never rewrites a file that resolves another copy of Bas nodeFs.rmSync(root, { recursive: true, force: true }); } }); + +// DECISIONS 320, 2.15: the version link, the release notes and the versions are each a module of their own, so an app that shows only the foot's link +// loads only that (VersionLink takes the rail's tooltip from AppShell, which carries it for Nav, so it imports none). Measured with splitting: VersionLink +// 2,102, ReleaseIndex 31,035 (Base UI's accordion), ReleaseNotes 173,758 (the popover, the accordion, the callout, the copy and text buttons); +// each limit is the measurement rounded up to the next 50. +for (const [name, limit] of [["VersionLink", 2_150], ["ReleaseIndex", 31_050], ["ReleaseNotes", 173_800]]) { + test(`${name} alone, with splitting, loads only its own static graph (${limit} bytes at most)`, async () => { + const { bytes, chunks } = await graph(name); + assert.ok(bytes < limit, `${name}: ${bytes} bytes in ${chunks} chunks (limit ${limit})`); + }); +} + +test("VersionLink loads none of the release notes, the versions or the tooltip", async () => { + const { inputs } = await graph("VersionLink"); + assert.deepEqual(inputs.filter((input) => /release-notes|release-index|display\.js|@base-ui/.test(input)), []); +}); diff --git a/packages/react/test/export-sizes.json b/packages/react/test/export-sizes.json index 3e1a4eee..04c1fcfd 100644 --- a/packages/react/test/export-sizes.json +++ b/packages/react/test/export-sizes.json @@ -16,7 +16,7 @@ "AlertDialogTrigger": 69874, "AmbientMark": 569, "AppHeader": 1285, - "AppShell": 103887, + "AppShell": 115101, "AppTile": 1112, "ArchitectureDiagram": 67580, "ArrowDownGlyph": 2868, @@ -170,7 +170,7 @@ "MultiSelect": 150488, "Nav": 4774, "NavGroup": 538, - "NavItem": 110701, + "NavItem": 110693, "NoticeBar": 813, "NotificationCenter": 152005, "NotificationCentre": 152015, @@ -218,6 +218,8 @@ "Reflow": 6095, "ReflowItem": 470, "Refreshing": 1911, + "ReleaseIndex": 30827, + "ReleaseNotes": 173097, "Reserve": 441, "Reveal": 19500, "RoutesGlyph": 3009, @@ -259,7 +261,7 @@ "ShortcutList": 10032, "SingleKeysSwitch": 17082, "SiteBrand": 1302, - "SiteFooter": 14780, + "SiteFooter": 15010, "SiteHeader": 178924, "SiteLockupDefs": 694, "SiteMenu": 171246, @@ -287,10 +289,10 @@ "Stepper": 26713, "Stream": 283, "StreamArrivedWord": 470, - "StreamBlock": 2764, - "StreamEntry": 2583, - "StreamMessage": 14856, - "StreamNote": 2651, + "StreamBlock": 2788, + "StreamEntry": 2611, + "StreamMessage": 14883, + "StreamNote": 2679, "StreamQuote": 991, "Switch": 16297, "SwitchRow": 24811, @@ -304,7 +306,7 @@ "Tab": 40055, "TabBar": 3501, "TabBarItem": 1859, - "TabBarMore": 91228, + "TabBarMore": 91447, "Table": 8305, "TableBody": 143, "TableCall": 391, @@ -344,6 +346,7 @@ "Tray": 90410, "TrayRow": 502, "TrendsGlyph": 2924, + "VersionLink": 1968, "VisuallyHidden": 258, "WAIT_MIN_SHOWN_MS": 26, "WAIT_SHOW_AFTER_MS": 26, @@ -412,11 +415,11 @@ "useWaitMark": 303 }, "package": { - "bytes": 870189, - "gzip": 288896 + "bytes": 885382, + "gzip": 293729 }, "styles": { - "bytes": 382510, - "gzip": 49971 + "bytes": 398155, + "gzip": 51889 } } diff --git a/packages/react/test/release-arrival.test.mjs b/packages/react/test/release-arrival.test.mjs new file mode 100644 index 00000000..4608253d --- /dev/null +++ b/packages/react/test/release-arrival.test.mjs @@ -0,0 +1,157 @@ +// Arriving at a release or an entry (DECISIONS 320, 2.10): the fragment is looked up by id, every fold that holds the target is opened, the +// target is scrolled to and focused with no ring, and it takes the stream's mark (the plate and "Linked") until the reader presses or types. +// Driven in Chromium against the built package. The fixtures are made up (Slate, a package; Harbor, a product). +import assert from "node:assert/strict"; +import fs from "node:fs"; +import path from "node:path"; +import { after, before, describe, test } from "node:test"; + +import { HARBOR, HARBOR_BEFORE, RUNNING_BUILD, SLATE } from "./release-fixture.mjs"; +import { bundleFixture, launch, pkg, settle } from "./support.mjs"; + +let browser; +before(async () => { browser = await launch(); }); +after(async () => { await browser?.close(); }); + +const CSS = () => fs.readFileSync(path.join(pkg, "dist", "styles.css"), "utf8"); + +/** A page at a real address with a fragment, so arriving is a real fragment navigation and Back works. */ +async function arrive(fragment, { releases = "SLATE", form = "reference", product = "Slate", theme = "light", width = 1024, height = 700, ...options } = {}) { + const context = await browser.newContext({ viewport: { width, height }, ...options }); + const page = await context.newPage(); + page.context_ = context; + const errors = []; + page.on("pageerror", (error) => errors.push(error.message)); + page.errors = errors; + await page.route("https://example.test/**", (route) => route.fulfill({ contentType: "text/html", body: `
    ` })); + await page.goto(`https://example.test/changelog${fragment}`); + const data = `const SLATE = ${JSON.stringify(SLATE)}; const HARBOR = ${JSON.stringify(HARBOR)}; const HARBOR_BEFORE = ${JSON.stringify(HARBOR_BEFORE)}; const RUNNING_BUILD = ${JSON.stringify(RUNNING_BUILD)};`; + await page.addScriptTag({ content: await bundleFixture(`${data} createRoot(document.getElementById("root")).render();`) }); + await settle(page); + await page.waitForTimeout(50); + await settle(page); + return page; +} +const state = (page) => page.evaluate(() => { + const arrived = [...document.querySelectorAll("[data-arrived]")].map((el) => el.id); + const focused = document.activeElement?.id ?? null; + const word = document.querySelector("[data-arrived] .basalt-release-word[data-on]"); + return { arrived, focused, word: word ? word.textContent : null }; +}); +const inView = (page, id) => page.evaluate((target) => { + const r = document.getElementById(target).getBoundingClientRect(); + return r.top >= 0 && r.top < innerHeight; +}, id); + +describe("arriving", () => { + test("a fragment to a release marks its header, focuses it with no ring, and says Linked", async () => { + const page = await arrive("#v0.2.0"); + assert.deepEqual(await state(page), { arrived: ["v0.2.0"], focused: "v0.2.0", word: "Linked" }); + assert.ok(await inView(page, "v0.2.0")); + assert.equal(await page.locator('[id="v0.2.0"]').evaluate((el) => getComputedStyle(el).outlineStyle), "none"); + const plate = await page.locator('[id="v0.2.0"] .basalt-release-head-text').evaluate((el) => getComputedStyle(el, "::before").backgroundColor); + assert.notEqual(plate, "rgba(0, 0, 0, 0)", "the plate is on its header"); + await page.context_.close(); + }); + + test("a fragment to an entry: the entry takes the plate and the word", async () => { + const page = await arrive("#pr41-1"); + assert.deepEqual(await state(page), { arrived: ["pr41-1"], focused: "pr41-1", word: "Linked" }); + assert.ok(await inView(page, "pr41-1")); + assert.notEqual(await page.locator('[id="pr41-1"]').evaluate((el) => getComputedStyle(el, "::before").backgroundColor), "rgba(0, 0, 0, 0)"); + await page.context_.close(); + }); + + test("an entry in a closed fold: the fold opens and the entry is reached", async () => { + const page = await arrive("#pr49-1"); + assert.equal(await page.locator('[id="v0.2.0"] .basalt-release-section[data-folded] .basalt-accordion-trigger').getAttribute("aria-expanded"), "true"); + assert.equal(await page.locator('[id="pr49-1"]').isVisible(), true); + assert.deepEqual(await state(page), { arrived: ["pr49-1"], focused: "pr49-1", word: "Linked" }); + assert.ok(await inView(page, "pr49-1")); + await page.context_.close(); + }); + + test("an entry inside a product's All changes", async () => { + const page = await arrive("#pr131-1", { releases: "HARBOR", form: "notes", product: "Harbor" }); + assert.equal(await page.locator('[id="pr131-1"]').isVisible(), true); + assert.deepEqual(await state(page), { arrived: ["pr131-1"], focused: "pr131-1", word: "Linked" }); + await page.context_.close(); + }); + + test("a candidate's address while it is drawn, and the stable release once it replaces it; an entry's address is the same in both", async () => { + let page = await arrive("#v2.0.0-rc.2", { releases: "HARBOR_BEFORE", form: "notes", product: "Harbor" }); + assert.deepEqual((await state(page)).arrived, ["v2.0.0-rc.2"]); + await page.context_.close(); + page = await arrive("#v2.0.0-rc.2", { releases: "HARBOR", form: "notes", product: "Harbor" }); + assert.deepEqual((await state(page)).arrived, ["v2.0.0"]); + assert.equal((await state(page)).focused, "v2.0.0"); + await page.context_.close(); + for (const releases of ["HARBOR_BEFORE", "HARBOR"]) { + page = await arrive("#pr142-1", { releases, form: "notes", product: "Harbor" }); + assert.deepEqual((await state(page)).arrived, ["pr142-1"], releases); + await page.context_.close(); + } + }); + + test("an unknown fragment marks nothing and throws nothing; a dotted version is never read as a selector", async () => { + for (const fragment of ["#nothing-here", "#2026.11.23", "#v9.9.9", "#%E0%A4%A"]) { + const page = await arrive(fragment); + assert.deepEqual((await state(page)).arrived, []); + assert.deepEqual(page.errors, []); + await page.context_.close(); + } + }); + + test("in forced colours the plate goes and the word stays", async () => { + const page = await arrive("#pr41-1", { forcedColors: "active" }); + assert.equal(await page.locator('[id="pr41-1"]').evaluate((el) => getComputedStyle(el, "::before").display), "none"); + assert.equal((await state(page)).word, "Linked"); + assert.equal(await page.locator('[id="pr41-1"] .basalt-release-word').isVisible(), true); + await page.context_.close(); + }); +}); + +describe("the mark ends, and arriving again", () => { + test("an arrow key leaves the mark; a press ends it, and focus stays", async () => { + const page = await arrive("#pr41-1"); + await page.keyboard.press("ArrowDown"); + await settle(page); + assert.deepEqual((await state(page)).arrived, ["pr41-1"]); + await page.mouse.click(5, 5); + await settle(page); + assert.deepEqual((await state(page)).arrived, []); + assert.equal(await page.locator('[id="pr41-1"] .basalt-release-word').count(), 1, "the word keeps its room"); + await page.context_.close(); + }); + + test("a link on the page is a hashchange that arrives; Back arrives at the one before", async () => { + const page = await arrive("#v0.2.0"); + await page.evaluate(() => { location.hash = "#pr45-1"; }); + await settle(page); + await page.waitForTimeout(50); + assert.deepEqual((await state(page)).arrived, ["pr45-1"]); + await page.goBack(); + await settle(page); + await page.waitForTimeout(50); + assert.deepEqual((await state(page)).arrived, ["v0.2.0"]); + assert.equal((await state(page)).focused, "v0.2.0"); + // The versions' links are fragment links too. + await page.evaluate(() => { location.hash = "#v0.1.0"; }); + await page.waitForTimeout(50); + await settle(page); + assert.deepEqual((await state(page)).arrived, ["v0.1.0"]); + await page.context_.close(); + }); + + test("an app with its own router names the target; the window's fragment is then not read", async () => { + const context = await browser.newContext({ viewport: { width: 1024, height: 700 } }); + const page = await context.newPage(); + await page.route("https://example.test/**", (route) => route.fulfill({ contentType: "text/html", body: `
    ` })); + await page.goto("https://example.test/changelog#v0.1.0"); + await page.addScriptTag({ content: await bundleFixture(`const SLATE = ${JSON.stringify(SLATE)}; createRoot(document.getElementById("root")).render();`) }); + await settle(page); + await page.waitForTimeout(50); + assert.deepEqual((await state(page)).arrived, ["pr45-1"]); + await context.close(); + }); +}); diff --git a/packages/react/test/release-fixture.mjs b/packages/react/test/release-fixture.mjs new file mode 100644 index 00000000..b0ab8a7a --- /dev/null +++ b/packages/react/test/release-fixture.mjs @@ -0,0 +1,29 @@ +// The two made-up projects of tools/changelog/fixtures, as page data for the release tests: Slate (a package) and Harbor (a product). Every fact in +// them is invented. Read from the fixtures the tool writes, so the parts are drawn from what the tool produces. +import fs from "node:fs"; +import path from "node:path"; +import { fileURLToPath } from "node:url"; + +import { pageReleases, readRecords } from "../../../tools/changelog/records.mjs"; + +const FIXTURES = path.join(path.dirname(fileURLToPath(import.meta.url)), "..", "..", "..", "tools", "changelog", "fixtures"); +export const SLATE = JSON.parse(fs.readFileSync(path.join(FIXTURES, "slate", "releases.json"), "utf8")); +export const HARBOR = JSON.parse(fs.readFileSync(path.join(FIXTURES, "harbor", "releases.json"), "utf8")); +/** Harbor as it stood before 2.0.0 shipped: its two candidates drawn as releases of their own. */ +export const HARBOR_BEFORE = pageReleases(path.join(FIXTURES, "harbor"), { records: readRecords(path.join(FIXTURES, "harbor")).filter((record) => record.version !== "2.0.0"), pending: [] }); +/** What a running Harbor build says of itself (made up): never read from a release's record. */ +export const RUNNING_BUILD = [{ label: "Build", value: "1.4.0+9f3c1e2", mono: true }, { label: "Commit", value: "9f3c1e2a7d04", mono: true }, { label: "Basalt", value: "0.2.0", mono: true }]; + +/** A Harbor app shell with the version at its foot, the release notes as its page and More holding Settings (TSX for a fixture). */ +export const harborShell = ({ running = "1.4.0", date = "2026-11-23", releases = "HARBOR", extra = "" } = {}) => ` + const version = ; + return ( + Harbor} brandLabel="Harbor home" + sidebar={HomeIncidents} + account={Settings} + version={version} + header={} + tabBar={HomeIncidentsSettings}> + + + );`; diff --git a/packages/react/test/release-notes.test.mjs b/packages/react/test/release-notes.test.mjs new file mode 100644 index 00000000..510e70b8 --- /dev/null +++ b/packages/react/test/release-notes.test.mjs @@ -0,0 +1,375 @@ +// A page of releases (DECISIONS 320, section 2): ReleaseNotes in both forms from the made-up fixtures (Slate, a package; Harbor, a product), +// driven in Chromium against the built package with the real stylesheet. +import assert from "node:assert/strict"; +import fs from "node:fs"; +import { createRequire } from "node:module"; +import path from "node:path"; +import { after, before, describe, test } from "node:test"; + +import { HARBOR, RUNNING_BUILD, SLATE, harborShell } from "./release-fixture.mjs"; +import { bundleFixture, fixturePage, launch, pkg, settle } from "./support.mjs"; + +const axeSource = fs.readFileSync(createRequire(import.meta.url).resolve("axe-core/axe.min.js"), "utf8"); +let browser; +before(async () => { browser = await launch(); }); +after(async () => { await browser?.close(); }); + +const DATA = `const HARBOR = ${JSON.stringify(HARBOR)}; const SLATE = ${JSON.stringify(SLATE)}; const RUNNING_BUILD = ${JSON.stringify(RUNNING_BUILD)};`; +const app = (jsx) => `${DATA} document.body.style.margin = "0"; document.body.style.background = "var(--basalt-surface-page)"; document.body.style.color = "var(--basalt-text-primary)"; +function App() { ${jsx} } +createRoot(document.getElementById("root")).render();`; +/** Slate's changelog on a site page: the versions in the pane beside it, or in a fold above it. */ +const SLATE_PAGE = (more = "") => `return
    + } paneLabel="Versions">
    ;`; +const open = async (jsx, { theme = "light", width = 1440, height = 900, ...options } = {}) => { + const { page, errors } = await fixturePage(browser, app(jsx), { theme, viewport: { width, height }, standards: true, ...options }); + await settle(page); + page.errors = errors; + return page; +}; +const box = (locator) => locator.evaluate((el) => { const r = el.getBoundingClientRect(); return { x: r.x, y: r.y, width: r.width, height: r.height, right: r.right, bottom: r.bottom }; }); +/** What a part draws, as a reader sees it: the dots of DotSep as " · ", a count after its name, and nothing that is visually hidden. */ +const DRAWN = (el) => { + const copy = el.cloneNode(true); + copy.querySelectorAll(".basalt-visually-hidden").forEach((n) => n.remove()); + copy.querySelectorAll(".basalt-dot-sep").forEach((n) => n.replaceWith(" · ")); + copy.querySelectorAll(".basalt-release-count, .basalt-badge").forEach((n) => n.before(" ")); + return copy.textContent.replace(/\s+/g, " ").trim(); +}; +const words = (locator) => locator.evaluate(DRAWN); +const axe = async (page) => { + await page.evaluate(() => { document.title = "Basalt"; document.documentElement.lang = "en"; }); + await page.addScriptTag({ content: axeSource }); + return page.evaluate(async () => { + const options = { runOnly: { type: "tag", values: ["wcag2a", "wcag2aa", "wcag21a", "wcag21aa", "wcag22aa"] }, resultTypes: ["violations"] }; + const result = await globalThis.axe.run({ exclude: [["[data-base-ui-focus-guard]"]] }, options); + return result.violations.map((v) => `${v.id}: ${v.nodes.map((n) => n.target.join(" ")).join(" | ")}`); + }); +}; +/** Open every fold on the page (the releases' and the versions'). */ +const openAll = async (page) => { + for (let round = 0; round < 3; round++) { + const closed = page.locator(".basalt-release-notes .basalt-accordion-trigger:not([data-panel-open]), .basalt-release-index .basalt-accordion-trigger:not([data-panel-open])"); + const n = await closed.count(); + if (!n) break; + for (let i = 0; i < n; i++) await closed.first().evaluate((el) => el.click()); + await settle(page); + } +}; +/** An accessible name as Chrome computes it: a visually hidden comma or colon stands apart from the words before it ("0.2.0 , Nov 16"). */ +const named = (text) => new RegExp(`^${text.replace(/[.*+?^${}()|[\]\\]/g, "\\$&").replace(/([,:])/g, "\\s*$1")}$`); +const release = (page, id) => page.locator(`[id="${id}"]`); +const headings = (locator, level) => locator.locator(`h${level}`).evaluateAll((els, drawn) => els.map((el) => new Function(`return (${drawn})`)()(el)), DRAWN.toString()); + +describe("the two forms from one record", () => { + test("a heading holds the number and the date (and a product's headline), so a reader moving by headings hears which release and when", async () => { + const slate = await open(SLATE_PAGE()); + assert.equal(await slate.getByRole("heading", { name: named("0.2.0, Nov 16, 2026"), level: 2 }).count(), 1); + assert.equal(await slate.getByRole("heading", { name: named("0.2.1, Nov 16, 2026"), level: 2 }).count(), 1); + assert.equal(await slate.getByRole("heading", { name: "Unreleased", exact: true, level: 2 }).count(), 1); + const harbor = await open(harborShell()); + assert.equal(await harbor.getByRole("heading", { name: named("1.4.0, Nov 23, 2026: A monitor can open an incident room"), level: 2 }).count(), 1); + assert.equal(await harbor.getByRole("heading", { name: named("1.4.1, Dec 8, 2026"), level: 2 }).count(), 1); + // A product's page never shows Unreleased. + assert.equal(await harbor.getByRole("heading", { name: "Unreleased" }).count(), 0); + }); + + test("the counts are computed from the list, with their singulars", async () => { + const slate = await open(SLATE_PAGE()); + assert.equal(await words(release(slate, "v0.2.0").locator(".basalt-release-meta")), "Nov 16, 2026 · 14 changes · 4 need action"); + assert.equal(await words(release(slate, "v0.2.1").locator(".basalt-release-meta")), "Nov 16, 2026 · 1 change"); + assert.equal(await words(release(slate, "v0.1.0").locator(".basalt-release-meta")), "Nov 2, 2026"); + assert.equal(await release(slate, "v0.2.0").getByRole("link", { name: "4 need action" }).getAttribute("href"), "#v0.2.0-action"); + const harbor = await open(harborShell()); + assert.equal(await words(release(harbor, "v1.3.0").locator("p.basalt-release-meta")), "2 changes · 1 needs action"); + assert.equal(await words(release(harbor, "v1.4.0").locator("p.basalt-release-meta")), "5 changes Your version"); + // Releases highest first by precedence: a backport to 1.x sits under 2.0.0 though it shipped after it. + assert.deepEqual(await harbor.locator(".basalt-release").evaluateAll((els) => els.map((el) => el.id)), ["v2.0.0", "v1.4.1", "v1.4.0", "v1.3.1", "v1.3.0"]); + }); + + test("a package's order: the summary, Action needed opening with the upgrade line, then Deprecated, Added, Changed and Fixed", async () => { + const page = await open(SLATE_PAGE()); + const own = release(page, "v0.2.0"); + const order = await own.evaluate((el) => [...el.children].map((child) => child.className.split(" ").find((name) => name.startsWith("basalt-release-")) ?? child.className)); + assert.deepEqual(order, ["basalt-release-head", "basalt-release-summary", "basalt-release-action", "basalt-release-section", "basalt-release-section", "basalt-release-section", "basalt-release-section"]); + assert.deepEqual(await headings(own, 3), ["Action needed 4", "Deprecated 1", "Added 3", "Changed 1", "Fixed 5"]); + assert.equal(await words(own.locator(".basalt-release-upgrade")), "Before upgrading from 0.1.0, check these 4 changes."); + // An action entry stands there and nowhere else in its release. + assert.equal(await own.locator('[id="pr41-1"]').count(), 1); + assert.equal(await own.locator('.basalt-release-action [id="pr41-1"]').count(), 1); + // A release with no entries is its summary, never a heading over nothing. + assert.equal(await words(release(page, "v0.1.0").locator(".basalt-release-summary")), "The first version in this changelog. Earlier work is in the repository's history."); + }); + + test("a product's order: the header, Action needed, the paragraphs, then one fold holding the summary and the list", async () => { + const page = await open(harborShell()); + const own = release(page, "v1.4.0"); + const order = await own.evaluate((el) => [...el.children].map((child) => child.className.split(" ").find((name) => name.startsWith("basalt-release-")))); + assert.deepEqual(order, ["basalt-release-head", "basalt-release-audience", "basalt-release-audience", "basalt-release-audience", "basalt-release-all", "basalt-release-build"]); + assert.deepEqual(await headings(own, 3), ["For responders", "For admins", "All changes 5", "Build details"]); + // The summary is the first thing inside the fold. + await own.getByRole("button", { name: "All changes 5" }).click(); + await settle(page); + const inside = await own.locator(".basalt-release-all .basalt-accordion-content").evaluate((el) => [...el.children].map((child) => child.className)); + assert.equal(inside[0], "basalt-release-summary"); + assert.deepEqual(await headings(own.locator(".basalt-release-all"), 4), ["Added 2", "Changed 1", "Fixed 2"]); + const withAction = release(page, "v2.0.0"); + const order2 = await withAction.evaluate((el) => [...el.children].map((child) => child.className.split(" ").find((name) => name.startsWith("basalt-release-")))); + assert.deepEqual(order2, ["basalt-release-head", "basalt-release-action", "basalt-release-audience", "basalt-release-audience", "basalt-release-all"]); + }); + + test("the folds: Fixed past 3 in a release of more than 10, a product's list behind one fold, and Action needed never folded", async () => { + const slate = await open(SLATE_PAGE()); + const folds = await slate.locator(".basalt-release-notes .basalt-accordion-trigger").evaluateAll((els, drawn) => els.map((el) => new Function(`return (${drawn})`)()(el)), DRAWN.toString()); + assert.deepEqual(folds, ["Fixed 5"]); + assert.equal(await slate.locator('[id="pr49-1"]').isVisible(), false, "closed"); + assert.equal(await slate.locator(".basalt-release-action").isVisible(), true); + assert.equal(await slate.locator(".basalt-accordion-panel .basalt-release-action, .basalt-accordion-panel [id='pr41-1']").count(), 0, "no action entry in a fold"); + const harbor = await open(harborShell()); + assert.equal(await harbor.locator(".basalt-accordion-panel .basalt-release-action").count(), 0); + // A patch with no paragraphs shows its summary and its list open, even with four fixes. + assert.equal(await release(harbor, "v1.3.1").locator(".basalt-accordion-trigger").count(), 0); + }); + + test("the fold is named for what it opens: Other changes when actions stand above it, and its count is what it opens", async () => { + const page = await open(harborShell()); + for (const [id, name, count] of [["v1.4.0", "All changes", 5], ["v1.3.0", "Other changes", 1], ["v2.0.0", "Other changes", 3]]) { + const own = release(page, id); + const trigger = own.locator(".basalt-release-all .basalt-accordion-trigger"); + assert.equal(await words(trigger), `${name} ${count}`, id); + await trigger.click(); + await settle(page); + assert.equal(await own.locator(".basalt-release-all .basalt-release-entry").count(), count, `${id} opens ${count}`); + } + // The header keeps the release's totals. + assert.equal(await words(release(page, "v1.3.0").locator("p.basalt-release-meta")), "2 changes · 1 needs action"); + }); + + test("the number in a headline's meta line is Geist; standing alone it is mono", async () => { + const page = await open(harborShell()); + const family = (locator) => locator.evaluate((el) => getComputedStyle(el).fontFamily); + assert.doesNotMatch(await family(release(page, "v1.4.0").locator(".basalt-release-number-line")), /mono/i); + assert.match(await family(release(page, "v1.4.1").locator(".basalt-release-version")), /mono/i); + }); +}); + +describe("entries and their sources", () => { + test("at 1440 the words keep one measure down each list, and the sources start on one edge", async () => { + const page = await open(SLATE_PAGE()); + await openAll(page); + const lists = await page.locator(".basalt-release-notes .basalt-release-list").evaluateAll((els) => els.map((list) => { + const texts = [...list.querySelectorAll(":scope > .basalt-release-entry > .basalt-release-entry-words")].map((el) => Math.round(el.getBoundingClientRect().width)); + const sources = [...list.querySelectorAll(":scope > .basalt-release-entry > .basalt-release-source-cell")].map((el) => Math.round(el.getBoundingClientRect().left)); + return { texts: [...new Set(texts)], sources: [...new Set(sources)] }; + })); + for (const list of lists) { + assert.equal(list.texts.length, 1, `one measure: ${list.texts}`); + assert.equal(list.sources.length, 1, `one edge: ${list.sources}`); + } + }); + + test("at 390 the source line is its own line under the words, on their start edge", async () => { + const page = await open(SLATE_PAGE(), { width: 390, height: 844 }); + const entry = page.locator('[id="pr41-1"]'); + const text = await box(entry.locator(".basalt-release-entry-text")); + const source = await box(entry.locator(".basalt-release-source")); + assert.ok(source.y > text.y, "under the words"); + assert.equal(Math.round(source.x), Math.round(text.x)); + assert.ok(text.width > 280, `the words get the width: ${text.width}`); + }); + + test("the source line: the pull request, at most two tickets, then 3 more; its name is its text after Sources, described by the entry", async () => { + const page = await open(SLATE_PAGE()); + const tokens = page.locator('[id="pr46-1"] .basalt-release-source'); + assert.equal(await words(tokens), "#46 · DS-27 · DS-31 · 3 more"); + // The name is the visible words after a hidden "Sources: ", each dot read as a comma. + assert.equal(await page.getByRole("button", { name: named("Sources: #46, DS-27, DS-31, 3 more") }).count(), 1); + assert.equal(await tokens.getAttribute("aria-describedby"), "pr46-1-words"); + // An entry with no pull request leads with its commit; an unreleased one with nothing to show has no line. + assert.match(await words(page.locator('[id="docs-contrast-note"] .basalt-release-source')), /^[0-9a-f]{8}$/); + const family = await tokens.evaluate((el) => getComputedStyle(el).fontFamily); + assert.match(family, /mono/i); + }); + + test("the sources panel: Pull request, Tickets, Commit and Author when there is one; none of the rejected rows; Copy link to this change", async () => { + const page = await open(SLATE_PAGE()); + await page.locator('[id="pr41-1"] .basalt-release-source').click(); + let panel = page.locator(".basalt-release-sources"); + await panel.waitFor(); + await settle(page); + const terms = () => panel.locator("dt").evaluateAll((els) => els.map((el) => el.textContent)); + assert.deepEqual(await terms(), ["Pull request", "Tickets", "Commit", "Author"]); + assert.deepEqual(await panel.locator("dd").evaluateAll((els) => els.map((el) => el.textContent.replace(/\s+/g, " ").trim())).then((list) => list.slice(0, 3)), ["#41", "Linear SL-112", "Jira PRJ-88"]); + assert.equal(await panel.getByRole("link", { name: "SL-112" }).getAttribute("href"), "https://linear.app/example/issue/SL-112"); + assert.equal(await panel.getByRole("link", { name: "PRJ-88" }).count(), 0, "a text tracker is not linked"); + assert.match(await words(panel), /Sam Rivera/); + assert.doesNotMatch(await words(panel), /Built by|Code review|Edited by|Decision/); + assert.equal(await panel.getByRole("button", { name: "Copy link to this change" }).count(), 1); + // Focus moved into the panel; Escape returns it to the source line. + assert.equal(await page.evaluate(() => Boolean(document.activeElement?.closest(".basalt-release-sources"))), true); + await page.keyboard.press("Escape"); + await settle(page); + assert.equal(await page.evaluate(() => document.activeElement?.closest(".basalt-release-entry")?.id), "pr41-1"); + // An entry with no author has no Author row. + await page.locator('[id="pr42-1"] .basalt-release-source').click(); + panel = page.locator(".basalt-release-sources"); + await panel.waitFor(); + assert.deepEqual(await terms(), ["Pull request", "Commit"]); + }); + + test("copied addresses: the app's base, or the window's when a button is pressed, with no query", async () => { + const context = await browser.newContext({ viewport: { width: 1440, height: 900 }, permissions: ["clipboard-read", "clipboard-write"] }); + const page = await context.newPage(); + await page.route("https://slate.example/**", (route) => route.fulfill({ contentType: "text/html", body: "
    " })); + await page.goto("https://slate.example/changelog?from=menu"); + await page.addStyleTag({ content: fs.readFileSync(path.join(pkg, "dist", "styles.css"), "utf8") }); + await page.addScriptTag({ content: await bundleFixture(app(`return ;`)) }); + await settle(page); + await page.getByRole("button", { name: "Copy link to Slate 0.2.0" }).click(); + assert.equal(await page.evaluate(() => navigator.clipboard.readText()), "https://slate.example/changelog#v0.2.0"); + await page.getByRole("button", { name: "Copy link to Unreleased" }).click(); + assert.equal(await page.evaluate(() => navigator.clipboard.readText()), "https://slate.example/changelog#unreleased"); + await context.close(); + // An app that gives its address: that is what is copied, whatever the window's is. + const other = await open(harborShell()); + await other.evaluate(() => { window.copied = []; Object.defineProperty(navigator, "clipboard", { value: { writeText: async (text) => { window.copied.push(text); } }, configurable: true }); }); + await other.getByRole("button", { name: "Copy link to Harbor 1.4.0" }).click(); + await other.waitForFunction(() => window.copied.length === 1); + assert.deepEqual(await other.evaluate(() => window.copied), ["https://harbor.example/release-notes#v1.4.0"]); + }); +}); + +describe("Build details", () => { + test("on the release this session runs and no other, with the app's rows, and Copy build details", async () => { + const page = await open(harborShell()); + assert.equal(await page.locator(".basalt-release-build").count(), 1); + const own = release(page, "v1.4.0"); + assert.equal(await own.locator(".basalt-release-build").count(), 1); + await own.getByRole("button", { name: "Build details" }).click(); + await settle(page); + assert.deepEqual(await own.locator(".basalt-release-build dt").evaluateAll((els) => els.map((el) => el.textContent)), ["Build", "Commit", "Basalt"]); + assert.deepEqual(await own.locator(".basalt-release-build dd").evaluateAll((els) => els.map((el) => el.textContent)), ["1.4.0+9f3c1e2", "9f3c1e2a7d04", "0.2.0"]); + assert.equal(await own.getByRole("button", { name: "Copy build details" }).count(), 1); + assert.equal(await page.getByText("Your version").count(), 1); + }); + + test("a running build between two releases: Build details stands above the first release", async () => { + const page = await open(harborShell({ running: "1.4.2", date: "2026-12-09" })); + const first = await page.locator(".basalt-release-notes").evaluate((el) => el.firstElementChild.className); + assert.equal(first, "basalt-release-build"); + assert.equal(await page.locator(".basalt-release .basalt-release-build").count(), 0); + assert.equal(await page.getByText("Your version").count(), 0); + }); +}); + +describe("widths, modes and touch", () => { + for (const width of [390, 360, 320]) { + test(`no sideways scroll at ${width}, every fold open, plain and under WCAG 1.4.12 text spacing`, async () => { + for (const jsx of [SLATE_PAGE(), harborShell()]) { + const page = await open(jsx, { width, height: 800 }); + await openAll(page); + assert.equal(await page.evaluate(() => document.documentElement.scrollWidth), width); + await page.addStyleTag({ content: "* { line-height: 1.5 !important; letter-spacing: 0.12em !important; word-spacing: 0.16em !important; } p { margin-bottom: 2em !important; }" }); + await settle(page); + assert.equal(await page.evaluate(() => document.documentElement.scrollWidth), width, "under text spacing"); + const outside = await page.evaluate((w) => [...document.querySelectorAll(".basalt-release-notes *")].filter((el) => { const r = el.getBoundingClientRect(); return r.width && (r.right > w + 0.5) && getComputedStyle(el).visibility !== "hidden" && !el.closest(".basalt-visually-hidden"); }).map((el) => el.className).slice(0, 5), width); + assert.deepEqual(outside, []); + } + }); + } + + test("forced colours: the source line and links keep their underline", async () => { + const page = await open(SLATE_PAGE(), { forcedColors: "active" }); + assert.equal(await page.locator('[id="pr41-1"] .basalt-release-id').first().evaluate((el) => getComputedStyle(el).textDecorationLine), "underline"); + assert.equal(await page.locator('[id="pr41-1"] .basalt-release-migrate').evaluate((el) => getComputedStyle(el).textDecorationLine), "underline"); + }); + + test("print: every fold is open, Copy buttons are not printed, and a source line prints as text", async () => { + const page = await open(harborShell()); + await page.emulateMedia({ media: "print" }); + await settle(page); + assert.equal(await page.locator('[id="pr131-1"]').isVisible(), true, "inside All changes"); + assert.equal(await page.locator('[id="pr143-1"]').isVisible(), true); + assert.equal(await page.locator(".basalt-release-copy").first().isVisible(), false); + assert.equal(await page.locator(".basalt-release-id").first().evaluate((el) => getComputedStyle(el).textDecorationLine), "none"); + }); + + test("without script every fold is open: the server's markup has no closed panel", async () => { + const { renderToString } = createRequire(import.meta.url)("react-dom/server"); + const React = createRequire(import.meta.url)("react"); + const B = await import(path.join(pkg, "dist", "index.js")); + const html = renderToString(React.createElement(B.ReleaseNotes, { releases: HARBOR, form: "notes", product: "Harbor", running: "1.4.0", runningBuild: RUNNING_BUILD })); + assert.doesNotMatch(html, /hidden="until-found"|hidden=""/); + assert.match(html, /id="pr131-1"/); + }); + + for (const theme of ["light", "dark"]) { + test(`axe finds nothing on either page, folds open (${theme})`, async () => { + for (const jsx of [SLATE_PAGE(), harborShell()]) { + const page = await open(jsx, { theme }); + await openAll(page); + assert.deepEqual(await axe(page), []); + assert.deepEqual(page.errors, []); + } + }); + } + + // The probe of proofs/targets.mjs: for every control of the releases, on a touch screen, the rows of its own drawn words that a tap sends to + // another control, and its height to a finger. + const probe = (page) => page.evaluate(() => { + const label = (el) => (el.getAttribute("aria-label") || el.textContent).replace(/\s+/g, " ").trim().slice(0, 48); + const owner = (x, y) => document.elementFromPoint(x, y)?.closest("a, button") ?? null; + const controls = [...document.querySelectorAll(".basalt-release a, .basalt-release button")].filter((el) => el.offsetParent && !el.closest(".basalt-popover")); + const rows = []; + for (const el of controls) { + el.scrollIntoView({ block: "center" }); + const rects = []; + const walk = document.createTreeWalker(el, NodeFilter.SHOW_TEXT); + for (let n = walk.nextNode(); n; n = walk.nextNode()) { + if (!n.data.trim() || n.parentElement.closest(".basalt-visually-hidden, [hidden]")) continue; + const range = document.createRange(); + range.selectNodeContents(n); + for (const r of range.getClientRects()) if (r.width > 1 && r.height > 1) rects.push(r); + } + if (!rects.length) continue; + let stolen = 0; + const thieves = new Set(); + for (const r of rects) for (let y = Math.ceil(r.top); y < Math.floor(r.bottom); y++) { + let lost = false; + for (let x = Math.ceil(r.left) + 1; x < Math.floor(r.right); x += 3) { const o = owner(x, y + 0.5); if (o && o !== el) { lost = true; thieves.add(label(o)); } } + if (lost) stolen++; + } + const b = el.getBoundingClientRect(); + const cx = b.x + Math.min(b.width / 2, 20); + const cy = (rects[0].top + rects[rects.length - 1].bottom) / 2; + let top = cy; + let bottom = cy; + while (top > cy - 60 && owner(cx, top - 1) === el) top--; + while (bottom < cy + 60 && owner(cx, bottom + 1) === el) bottom++; + rows.push({ control: label(el), stolen, to: [...thieves], hit: owner(cx, cy) === el ? Math.round(bottom - top) + 1 : 0 }); + } + return rows; + }); + + for (const width of [390, 360, 820]) { + test(`on touch at ${width}: no control receives a tap on another's words, and every control is at least 44 tall to a finger`, async () => { + for (const jsx of [SLATE_PAGE(), harborShell()]) { + const page = await open(jsx, { width, height: 844, hasTouch: true }); + await openAll(page); + const rows = await probe(page); + assert.ok(rows.length > 10); + assert.deepEqual(rows.filter((row) => row.stolen > 0), []); + assert.deepEqual(rows.filter((row) => row.hit < 44).map((row) => `${row.control}: ${row.hit}`), []); + } + }); + } + + test("on touch at 390: a tap on the bottom edge of How to migrate reaches the link and not Sources", async () => { + const page = await open(SLATE_PAGE(), { width: 390, height: 844, hasTouch: true }); + const link = page.locator('[id="pr41-1"] .basalt-release-migrate'); + await link.scrollIntoViewIfNeeded(); + const words = await link.locator(".basalt-link-label").evaluate((el) => { const r = el.getBoundingClientRect(); return { x: r.left + r.width / 2, y: r.bottom - 1 }; }); + const hit = await page.evaluate(({ x, y }) => document.elementFromPoint(x, y)?.closest("a, button")?.className, words); + assert.match(hit, /basalt-release-migrate/); + }); +}); diff --git a/packages/react/test/version-link.test.mjs b/packages/react/test/version-link.test.mjs new file mode 100644 index 00000000..e86ad1c5 --- /dev/null +++ b/packages/react/test/version-link.test.mjs @@ -0,0 +1,232 @@ +// The version at the sidebar's foot (DECISIONS 320, 1.2): VersionLink, AppShell's `version`, More's last row and the site footer. Driven in +// Chromium against the built package with the real stylesheet. The product, its versions and dates are made up (Harbor). +import assert from "node:assert/strict"; +import fs from "node:fs"; +import { createRequire } from "node:module"; +import { after, before, describe, test } from "node:test"; + +import { HARBOR, RUNNING_BUILD, harborShell } from "./release-fixture.mjs"; +import { fixturePage, launch, settle } from "./support.mjs"; + +const axeSource = fs.readFileSync(createRequire(import.meta.url).resolve("axe-core/axe.min.js"), "utf8"); +let browser; +before(async () => { browser = await launch(); }); +after(async () => { await browser?.close(); }); + +const DATA = `const HARBOR = ${JSON.stringify(HARBOR)}; const RUNNING_BUILD = ${JSON.stringify(RUNNING_BUILD)};`; +const app = (jsx) => `${DATA} document.body.style.margin = "0"; document.body.style.background = "var(--basalt-surface-page)"; +function App() { ${jsx} } +createRoot(document.getElementById("root")).render();`; +const open = async (jsx, { theme = "light", width = 1440, height = 900, ...options } = {}) => { + const { page, errors } = await fixturePage(browser, app(jsx), { theme, viewport: { width, height }, standards: true, ...options }); + await settle(page); + page.errors = errors; + return page; +}; +const box = (locator) => locator.evaluate((el) => { const r = el.getBoundingClientRect(); return { x: r.x, y: r.y, width: r.width, height: r.height, right: r.right, bottom: r.bottom }; }); +/** How tall a control is to a tap: the run of points down its middle that land on it. */ +const hitHeight = (locator) => locator.evaluate((el) => { + const r = el.getBoundingClientRect(); + const x = r.left + Math.min(r.width / 2, 20); + const cy = r.top + r.height / 2; + const mine = (y) => document.elementFromPoint(x, y)?.closest("a, button") === el; + let top = cy; + let bottom = cy; + while (top > cy - 60 && mine(top - 1)) top--; + while (bottom < cy + 60 && mine(bottom + 1)) bottom++; + return Math.round(bottom - top) + 1; +}); +const axe = async (page) => { + await page.evaluate(() => { document.title = "Basalt"; document.documentElement.lang = "en"; }); + await page.addScriptTag({ content: axeSource }); + return page.evaluate(async () => { + const options = { runOnly: { type: "tag", values: ["wcag2a", "wcag2aa", "wcag21a", "wcag21aa", "wcag22aa"] }, resultTypes: ["violations"] }; + const result = await globalThis.axe.run({ exclude: [["[data-base-ui-focus-guard]"]] }, options); + return result.violations.map((v) => `${v.id}: ${v.nodes.map((n) => n.target.join(" ")).join(" | ")}`); + }); +}; +/** The shell with the version at its foot. */ +const FOOT = (version = "1.4.0") => harborShell({ running: version }); +/** The words a link draws: its text less what is hidden, and the dot where both parts share a line (the dot is drawn, never text). */ +const drawn = (locator) => locator.evaluate((el) => { + const shown = (part) => { + if (!part) return ""; + const out = []; + const walk = document.createTreeWalker(part, NodeFilter.SHOW_TEXT); + for (let n = walk.nextNode(); n; n = walk.nextNode()) { + let hidden = false; + for (let up = n.parentElement; up && up !== el; up = up.parentElement) if (up.getBoundingClientRect().width <= 1) hidden = true; + if (hidden) continue; + const range = document.createRange(); + range.selectNodeContents(n); + if ([...range.getClientRects()].some((r) => r.width > 1)) out.push(n.data); + } + return out.join("").replace(/\s+/g, " ").trim(); + }; + const words = shown(el.querySelector(".basalt-version-link-words")); + const dateEl = el.querySelector(".basalt-version-link-date"); + const date = shown(dateEl); + if (!date) return words; + const sameLine = Math.abs(dateEl.getBoundingClientRect().top - el.querySelector(".basalt-version-link-words").getBoundingClientRect().top) < 2; + return `${words}${sameLine ? " · " : " "}${date}`; +}); + +describe("the link", () => { + test("its name is the visible words in order, then where it goes; the date is a calendar date, never moved by a time zone", async () => { + const page = await open(FOOT(), { timezoneId: "Pacific/Honolulu" }); + const link = page.getByRole("link", { name: "Version 1.4.0, Nov 23, 2026, release notes", exact: true }); + assert.equal(await link.count(), 1); + assert.equal(await link.getAttribute("href"), "#v1.4.0"); + assert.equal(await drawn(link), "Version 1.4.0 · Nov 23, 2026"); + assert.equal(await page.locator(".basalt-app-sidebar time").getAttribute("datetime"), "2026-11-23"); + const style = await link.first().evaluate((el) => { const s = getComputedStyle(el); return { size: s.fontSize, line: s.lineHeight, family: s.fontFamily, numeric: s.fontVariantNumeric }; }); + assert.deepEqual([style.size, style.line, style.numeric], ["12px", "16px", "tabular-nums"]); + assert.doesNotMatch(style.family, /mono/i, "Geist, not mono"); + }); + + test("it fits the foot's 195px on one line; the room is the sidebar less its edge and the nav glyphs' inset each side", async () => { + const page = await open(FOOT()); + const link = page.locator(".basalt-app-sidebar .basalt-version-link"); + const room = await page.locator(".basalt-app-version").evaluate((el) => el.getBoundingClientRect().width); + assert.ok(room >= 194 && room <= 196, `room ${room}`); + const words = await box(page.locator(".basalt-version-link-words")); + const date = await box(page.locator(".basalt-version-link-date")); + assert.equal(Math.round(words.y), Math.round(date.y), "one line"); + assert.equal(Math.round((await box(link)).x), Math.round((await box(page.locator(".basalt-app-version"))).x)); + }); + + test("a canary that does not fit: the date goes under the number, with no leading dot, and nothing is wider than the foot", async () => { + const page = await open(FOOT("1.5.0-canary.20261123.1")); + const link = await box(page.locator(".basalt-app-sidebar .basalt-version-link")); + const words = await box(page.locator(".basalt-app-sidebar .basalt-version-link-words")); + const date = await box(page.locator(".basalt-app-sidebar .basalt-version-link-date")); + assert.ok(date.y >= words.bottom - 1, "the date is on a line of its own, under the number"); + assert.equal(Math.round(date.x), Math.round(link.x), "it starts the line"); + // The dot stands in the gap before the date: left of the link's own box, which clips it. + const dot = await page.locator(".basalt-app-sidebar .basalt-version-link-date").evaluate((el) => { + const s = getComputedStyle(el, "::before"); + return { right: el.getBoundingClientRect().left, clip: getComputedStyle(el.closest("a")).overflowX, content: s.content }; + }); + assert.equal(dot.clip, "clip"); + assert.ok(dot.right <= link.x + 0.5, "the dot is outside the link's box"); + assert.ok(link.width <= 195.5, `the link is ${link.width} wide`); + // On one line, the dot is drawn between the parts. + const page2 = await open(FOOT()); + const one = await page2.locator(".basalt-app-sidebar .basalt-version-link-date").evaluate((el) => el.getBoundingClientRect().left - el.closest("a").getBoundingClientRect().left); + assert.ok(one > 12, "the date follows the number, with the dot in the gap"); + }); + + test("on the release notes it is the current page: aria-current, primary ink, the number at 600, and no change of width", async () => { + const page = await open(`return
    ;`); + const rest = page.getByTestId("rest"); + const current = page.getByTestId("current"); + assert.equal(await current.getAttribute("aria-current"), "page"); + assert.equal(await rest.getAttribute("aria-current"), null); + assert.equal((await box(rest)).width, (await box(current)).width); + const weight = (locator) => locator.locator(".basalt-version-link-number").evaluate((el) => getComputedStyle(el).fontWeight); + assert.equal(await weight(current), "600"); + assert.equal(await weight(rest), "400"); + const ink = (locator) => locator.evaluate((el) => getComputedStyle(el).color); + const primary = await page.evaluate(() => { const i = document.createElement("i"); i.style.color = "var(--basalt-text-primary)"; document.body.append(i); const c = getComputedStyle(i).color; i.remove(); return c; }); + assert.equal(await ink(current), primary); + assert.notEqual(await ink(rest), primary); + await rest.hover(); + await settle(page); + assert.equal(await ink(rest), primary, "hover lifts it to primary"); + assert.equal(await rest.locator(".basalt-version-link-words").evaluate((el) => getComputedStyle(el).textDecorationLine), "underline"); + }); + + test("24 tall on a fine pointer, and a 44px hit box on touch that moves nothing", async () => { + const fine = await open(FOOT()); + const at = (page) => page.locator(".basalt-app-sidebar .basalt-version-link"); + assert.equal((await box(at(fine))).height, 24); + assert.equal(await hitHeight(at(fine)), 24); + const touch = await open(FOOT(), { hasTouch: true }); + assert.equal((await box(at(touch))).height, 24); + assert.ok(await hitHeight(at(touch)) >= 44); + }); +}); + +describe("its places", () => { + test("at the sidebar's foot: under the account items, space-2 below them, the words on the nav glyphs' start edge", async () => { + const page = await open(harborShell()); + const link = page.locator(".basalt-app-sidebar .basalt-version-link"); + const glyph = await box(page.locator(".basalt-app-account .basalt-nav-item .basalt-icon").first()); + const account = await box(page.locator(".basalt-app-account .basalt-nav")); + const own = await box(link); + assert.equal(Math.round(own.x), Math.round(glyph.x), "on the glyphs' start edge"); + assert.equal(Math.round(own.y - account.bottom), 8, "space-2 under the account items"); + assert.equal(await link.getAttribute("aria-current"), "page"); + // There is no "What's new" item, and nothing marks a release as new. + assert.equal(await page.getByText(/what's new/i).count(), 0); + assert.equal(await page.locator(".basalt-nav-dot, .basalt-tabbar-dot").count(), 0); + }); + + test("in the rail: the number alone, centred, the label and the date in its name and its tooltip", async () => { + const page = await open(harborShell(), { width: 820 }); + const link = page.locator(".basalt-app-sidebar .basalt-version-link"); + assert.equal(await drawn(link), "1.4.0"); + assert.equal(await page.getByRole("link", { name: "Version 1.4.0, Nov 23, 2026, release notes" }).count(), 1); + const rail = await box(page.locator(".basalt-app-sidebar")); + const number = await box(link.locator(".basalt-version-link-number")); + assert.ok(Math.abs((number.x + number.width / 2) - (rail.x + rail.width / 2)) <= 1.5, "centred in the rail"); + await link.hover(); + const tip = page.getByRole("tooltip"); + await tip.waitFor(); + // The tooltip says the whole line: the dot is DotSep's, drawn as a dot and read as a comma. + assert.equal(await tip.evaluate((el) => [...el.childNodes].map((n) => (n.nodeType === 3 ? n.data : n.classList?.contains("basalt-dot-sep") ? " · " : n.textContent)).join("").replace(/\s+/g, " ").trim()), "Version 1.4.0 · Nov 23, 2026"); + }); + + test("in the rail a release candidate breaks before its hyphen, and nothing is wider than the rail", async () => { + const page = await open(harborShell({ running: "2.0.0-rc.2", date: "2026-12-03" }), { width: 820 }); + const link = page.locator(".basalt-app-sidebar .basalt-version-link"); + const lines = await link.locator(".basalt-version-link-number > span").evaluate((el) => [...el.getClientRects()].length > 1 || el.getBoundingClientRect().height > 20); + assert.ok(lines, "two lines"); + const pre = await box(link.locator(".basalt-version-link-pre")); + const rail = await box(page.locator(".basalt-app-sidebar")); + assert.ok(pre.right <= rail.right, "inside the rail"); + assert.equal(await link.locator(".basalt-version-link-pre").evaluate((el) => el.textContent), "-rc.2"); + }); + + test("on a phone: the last row of More's sheet, under a divider, 44 tall, at 13/18, on the nav glyphs' edge", async () => { + const page = await open(harborShell(), { width: 390, height: 844 }); + await page.getByRole("button", { name: "More, Release notes, current page" }).click(); + await settle(page); + const row = page.locator(".basalt-tabbar-version"); + await row.waitFor(); + const link = row.locator(".basalt-version-link"); + assert.equal(await drawn(link), "Version 1.4.0 · Nov 23, 2026"); + const style = await row.evaluate((el) => ({ height: el.getBoundingClientRect().height, border: getComputedStyle(el).borderTopWidth, last: el === el.parentElement.lastElementChild || !el.nextElementSibling })); + assert.ok(style.height >= 44); + assert.equal(style.border, "1px"); + assert.ok(style.last, "the last row"); + assert.deepEqual(await link.evaluate((el) => [getComputedStyle(el).fontSize, getComputedStyle(el).lineHeight]), ["13px", "18px"]); + const glyph = await box(page.locator(".basalt-tabbar-sheet .basalt-nav-item .basalt-icon").first()); + assert.equal(Math.round((await box(link)).x), Math.round(glyph.x)); + }); + + test("in a site's footer: after the legal line, on its row, at its 13/18, labelled with the product", async () => { + const page = await open(`return
    } />;`); + const link = page.getByRole("link", { name: "Slate 0.2.1, Nov 16, 2026, release notes" }); + assert.equal(await link.count(), 1); + const legal = await box(page.locator(".basalt-site-footer-legal")); + const own = await box(link); + assert.ok(own.x > legal.right, "after the legal line"); + assert.ok(Math.abs(own.y + own.height / 2 - (legal.y + legal.height / 2)) < 6, "on its row"); + assert.deepEqual(await link.evaluate((el) => [getComputedStyle(el).fontSize, getComputedStyle(el).lineHeight]), ["13px", "18px"]); + }); + + for (const theme of ["light", "dark"]) { + test(`axe finds nothing at the foot, in the rail and in More (${theme})`, async () => { + for (const width of [1440, 820]) { + const page = await open(harborShell(), { theme, width }); + assert.deepEqual(await axe(page), [], `${width}`); + assert.deepEqual(page.errors, []); + } + const phone = await open(harborShell(), { theme, width: 390, height: 844 }); + await phone.getByRole("button", { name: /^More/ }).click(); + await settle(phone); + assert.deepEqual(await axe(phone), []); + }); + } +}); From 096422b1bd03c748123408dd327aeb39a4797dd8 Mon Sep 17 00:00:00 2001 From: bailey <74082460+bmjcoding@users.noreply.github.com> Date: Mon, 23 Nov 2026 16:22:32 -0600 Subject: [PATCH 03/23] HTML skill: the release module and the version link (DECISIONS 320, 2.15) The release module draws a package's changelog or a product's release notes as React's ReleaseNotes and ReleaseIndex do; tools/changelog/ skill-body.mjs writes its markup from the records. Folds are written open and closed by the script to hidden="until-found", so without script and in print everything shows; arriving at a release or an entry opens its folds, focuses it and marks it Linked. .version-link joins the topbar module, with its place at the sidebar's foot (app-shell, the rail's tooltip from the script) and as More's last row (tab-bar). parity-16 compares both against React from the same records; release.test pins the behaviour. Budgets raised for what the decision adds: SKILL.md 12650 to 12800 (one index line, one trigger), topbar 17700 to 19900, app-shell 4300 to 5200, tab-bar 4850 to 5200, and the three usage caps; the release module is 15900. React's footer and More forms now key on their container, and inline code in an entry keeps the 20px line, as the skill's does. Co-Authored-By: Claude Opus 5.5 --- .agent/skills/basalt-html/SKILL.md | 3 +- .agent/skills/basalt-html/parts/app-shell.css | 2 +- .agent/skills/basalt-html/parts/app-shell.js | 2 +- .agent/skills/basalt-html/parts/manifest.json | 90 +++++++-- .agent/skills/basalt-html/parts/release.css | 1 + .agent/skills/basalt-html/parts/release.js | 1 + .agent/skills/basalt-html/parts/tab-bar.css | 2 +- .agent/skills/basalt-html/parts/topbar.css | 2 +- .../basalt-html/parts/usage/app-shell.md | 1 + .../skills/basalt-html/parts/usage/release.md | 20 ++ .../skills/basalt-html/parts/usage/tab-bar.md | 1 + .../skills/basalt-html/parts/usage/topbar.md | 1 + packages/react/src/styles/components.css | 4 +- tools/changelog/skill-body.mjs | 159 ++++++++++++++++ tools/html-skill/README.md | 2 + tools/html-skill/src/modules.json | 90 +++++++-- tools/html-skill/src/modules/app-shell.css | 10 + tools/html-skill/src/modules/app-shell.js | 13 ++ tools/html-skill/src/modules/release.css | 175 ++++++++++++++++++ tools/html-skill/src/modules/release.js | 110 +++++++++++ tools/html-skill/src/modules/tab-bar.css | 4 + tools/html-skill/src/modules/topbar.css | 41 ++++ tools/html-skill/src/usage/app-shell.md | 1 + tools/html-skill/src/usage/release.md | 20 ++ tools/html-skill/src/usage/tab-bar.md | 1 + tools/html-skill/src/usage/topbar.md | 1 + tools/html-skill/test/parity-16.test.mjs | 146 +++++++++++++++ tools/html-skill/test/release.test.mjs | 157 ++++++++++++++++ 28 files changed, 1030 insertions(+), 30 deletions(-) create mode 100644 .agent/skills/basalt-html/parts/release.css create mode 100644 .agent/skills/basalt-html/parts/release.js create mode 100644 .agent/skills/basalt-html/parts/usage/release.md create mode 100644 tools/changelog/skill-body.mjs create mode 100644 tools/html-skill/src/modules/release.css create mode 100644 tools/html-skill/src/modules/release.js create mode 100644 tools/html-skill/src/usage/release.md create mode 100644 tools/html-skill/test/parity-16.test.mjs create mode 100644 tools/html-skill/test/release.test.mjs diff --git a/.agent/skills/basalt-html/SKILL.md b/.agent/skills/basalt-html/SKILL.md index 6f9b321a..50e61f51 100644 --- a/.agent/skills/basalt-html/SKILL.md +++ b/.agent/skills/basalt-html/SKILL.md @@ -22,7 +22,7 @@ Markup built only at run time (a `.row` your script writes) won't be seen: add ` - **core** `.page`, `.stack`, `.panel`, `.card`, `.btn`: always in; print its usage with your modules. - **glyph** `data-glyph`: Basalt's own glyph by name, never drawn by hand; filled inside `aria-current`. -- **topbar** `.topbar`, `.site-footer`: once per page; never restyle it; no danger button; no second blurred layer. +- **topbar** `.topbar`, `.site-footer`, `.version-link`: once per page; never restyle it; no danger button or second blur. - **kbd** `data-kbd`, `.kbd`: only a real shortcut the page binds, never on the primary fill; `data-doc` for keys in prose. - **segment** `.segment`: `button[aria-pressed]`, one true; a click doesn't switch it, your script does. - **forms** `.field`, `.input`, ``, `