Files
dragonroll/tests/docs.test.js
Gitea OpenCode Agent 9aad484fe9
All checks were successful
Test / test (push) Successful in 2s
Fix issue #85: Style corrections on /docs
2026-10-15 20:55:08 +00:00

450 lines
19 KiB
JavaScript

// Tests for the documentation under /docs (Syndria98/dragonroll#79): the markdown pages are the
// documentation, so what has to stay right is (1) the pages are well formed — a title, a slug, a
// numbered group, translations for the group's label, and no link pointing at a page that does not
// exist, (2) the page about an integration really documents what that integration offers, which is
// checked against the sources that define it: the slash commands of discord-bot/src/commands.js and
// the commands the Obsidian plugin registers, and (3) the routes: /docs and /docs/<slug> render the
// documentation and every other address still opens the window app.
//
// `frontend/app/services/DocsMarkdown.js` is the pure part of the docs (headings, slugs, titles) and
// is loaded straight from source, the way the other tests load the frontend services; it imports
// nothing, so the repository root's no-dependencies rule holds. `Docs.js` itself is not loaded: it
// reads the markdown through `import.meta.glob`, which only Vite can answer.
//
// Run with `npm test` from the repository root, or `node --test tests/`.
const { test } = require("node:test");
const assert = require("node:assert/strict");
const fs = require("node:fs");
const path = require("node:path");
const vm = require("node:vm");
function readRepoFile(...parts) {
return fs.readFileSync(path.join(__dirname, "..", ...parts), "utf8");
}
function loadDocsMarkdown() {
const source = readRepoFile("frontend", "app", "services", "DocsMarkdown.js");
return vm.compileFunction(source.replace("export {", "return {") , [], {
parsingContext: vm.createContext({}),
})();
}
const docs = loadDocsMarkdown();
// The documentation pages, as the folder layout defines them.
const docsRoot = path.join(__dirname, "..", "frontend", "app", "content", "docs");
const docPages = fs.readdirSync(docsRoot, { withFileTypes: true })
.filter((entry) => entry.isDirectory())
.sort((left, right) => left.name.localeCompare(right.name))
.flatMap((group) => fs.readdirSync(path.join(docsRoot, group.name))
.filter((file) => file.endsWith(".md"))
.sort()
.map((file) => ({
group: group.name.replace(/^\d+-/, ""),
slug: file.replace(/^\d+-/, "").replace(/\.md$/, ""),
markdown: fs.readFileSync(path.join(docsRoot, group.name, file), "utf8"),
}))
);
const slugs = new Set(docPages.map((page) => page.slug));
const groups = [...new Set(docPages.map((page) => page.group))];
const pageAbout = (slug) => docPages.find((page) => page.slug === slug);
// --- The heading helpers the sidebar and the anchors are built from ---
test("a heading's slug comes out of its words, whatever form they arrive in", () => {
assert.equal(docs.Slugify("Link a world"), "link-a-world");
assert.equal(docs.Slugify(" Auto-sync, and one actor "), "auto-sync-and-one-actor");
assert.equal(docs.Slugify("Dragonroll: Force Sync!"), "dragonroll-force-sync");
});
test("the anchor built from a heading's markdown is the one built from its HTML", () => {
// The sidebar slugs the markdown source and the renderer slugs what marked produced, so the two
// have to land on the same anchor for a sidebar link to land on its section.
const pairs = [
["**Link** a `world`", "<strong>Link</strong> a <code>world</code>"],
["Commands & characters", "Commands &amp; characters"],
["[Foundry](/docs/foundry) worlds", '<a href="/docs/foundry">Foundry</a> worlds'],
["It's here", "It&#39;s here"],
];
for (const [markdown, html] of pairs) {
assert.equal(docs.Slugify(markdown), docs.Slugify(html), `slug of ${markdown}`);
}
});
test("repeated headings get distinct anchors, in the order they are written", () => {
const slug = docs.CreateHeadingSlugger();
assert.equal(slug("Setup"), "setup");
assert.equal(slug("setup"), "setup-1");
assert.equal(slug("Setup"), "setup-2");
});
test("the headings of a page are listed in order, with their anchors", () => {
const headings = docs.HeadingsFromMarkdown([
"# Connecting a service",
"",
"## How a connection works",
"text",
"### What it allows",
"```sh",
"# not a heading",
"```",
"## Next",
].join("\n"));
// The service is loaded from another realm, so the values are copied out before being compared.
assert.deepEqual(
JSON.parse(JSON.stringify(headings.map(({ depth, text, slug }) => ({ depth, text, slug })))),
[
{ depth: 1, text: "Connecting a service", slug: "connecting-a-service" },
{ depth: 2, text: "How a connection works", slug: "how-a-connection-works" },
{ depth: 3, text: "What it allows", slug: "what-it-allows" },
{ depth: 2, text: "Next", slug: "next" },
]
);
});
test("a page takes its title from its first heading", () => {
assert.equal(docs.TitleFromMarkdown("# Your first campaign\n\n## Signing in"), "Your first campaign");
assert.equal(docs.TitleFromMarkdown("no heading here"), "");
});
// --- The pages themselves ---
test("the documentation has pages, in numbered groups", () => {
assert.ok(docPages.length >= 5, `expected several documentation pages, found ${docPages.length}`);
for (const page of docPages) {
const folder = `${page.group}`;
assert.ok(folder.length > 0, `${page.slug} sits in an oddly named folder`);
assert.match(page.slug, /^[a-z0-9]+(-[a-z0-9]+)*$/, `${page.slug} is not a url-friendly slug`);
}
});
test("every page has a title, and no two pages share a slug", () => {
const seen = new Set();
for (const page of docPages) {
const title = docs.TitleFromMarkdown(page.markdown);
assert.ok(title, `${page.slug} has no heading to title it`);
assert.ok(!seen.has(page.slug), `${page.slug} is published twice`);
seen.add(page.slug);
}
assert.equal(seen.size, docPages.length);
});
test("every page has sections, which is what the sidebar lists beside it", () => {
for (const page of docPages) {
const sections = docs.HeadingsFromMarkdown(page.markdown).filter((heading) => heading.depth > 1);
assert.ok(sections.length, `${page.slug} has no section headings to list`);
}
});
test("every group has a sidebar label in every locale", () => {
const labels = ["en", "es", "ca"].map((locale) =>
JSON.parse(readRepoFile("frontend", "i18n", "locales", locale, "docs.json"))
);
assert.ok(labels.every((label) => label.groups), "each docs.json namespace needs a `groups` object");
for (const group of groups) {
for (const label of labels) {
const text = label.groups[group];
assert.ok(text, `the "${group}" group has no label in its docs.json`);
assert.notEqual(text, group, `the "${group}" label is untranslated`);
}
}
});
test("the pages only link to pages that are published", () => {
for (const page of docPages) {
for (const link of page.markdown.matchAll(/\]\((\/docs\/?[a-z0-9-]*)\)/g)) {
const target = link[1].replace("/docs/", "");
if (!target) continue; // /docs itself
assert.ok(slugs.has(target), `${page.slug} links to ${link[1]}, which is not published`);
}
}
});
test("the three integrations each have their own page", () => {
for (const slug of ["discord", "foundry", "obsidian"]) {
assert.ok(pageAbout(slug), `${slug} has no documentation page`);
}
assert.ok(pageAbout("connecting-a-service"), "the shared way of connecting a service is undocumented");
});
// --- The integrations pages describe what the integrations actually offer ---
// discord-bot/src/commands.js builds the slash commands with discord.js, which the repository root
// does not install: the builder is stubbed by one that records the names it is given.
function loadSlashCommands() {
const registered = [];
class Builder {
constructor() {
this.name = "";
this.parent = null;
this.children = [];
this.optionNames = [];
}
setName(name) { this.name = name; return this; }
setDescription() { return this; }
setContexts() { return this; }
setRequired() { return this; }
setMaxLength() { return this; }
setAutocomplete() { return this; }
addChoices() { return this; }
addStringOption(configure) { configure(new Builder()); return this; }
addBooleanOption(configure) { configure(new Builder()); return this; }
addSubcommand(configure) {
const sub = new Builder();
sub.parent = this;
configure(sub);
this.children.push(sub);
return this;
}
}
class SlashCommandBuilder extends Builder {
constructor() {
super();
registered.push(this);
}
}
const moduleStub = { exports: {} };
vm.compileFunction(readRepoFile("discord-bot", "src", "commands.js"), ["require", "module", "exports"])(
(id) => {
if (id === "discord.js") return { InteractionContextType: { Guild: 0 }, SlashCommandBuilder };
throw new Error(`require("${id}") is not stubbed`);
},
moduleStub,
moduleStub.exports
);
const names = [];
for (const command of registered) {
names.push(command.name);
for (const sub of command.children) names.push(`${command.name} ${sub.name}`);
}
return names;
}
test("the Discord page lists every command the bot declares", () => {
const about = pageAbout("discord");
const commands = loadSlashCommands();
// Sanity check on the stub before it is trusted to list anything.
assert.ok(commands.includes("characters"), `expected the bot's commands, got ${commands.join(", ")}`);
assert.ok(commands.includes("dragonroll connect"));
for (const command of commands) {
assert.ok(
about.markdown.includes("`/" + command),
`the Discord page does not document /${command}`
);
}
});
// The Obsidian plugin registers each command palette entry with `this.addCommand({ id, name, … })`.
function loadObsidianCommands() {
const source = readRepoFile("obsidian-plugin", "main.js");
const commands = [...source.matchAll(
/this\.addCommand\(\{\s*id:\s*["']([^"']+)["'],\s*name:\s*["']([^"']+)["']/g
)].map((match) => ({ id: match[1], name: match[2] }));
// Sanity check on the extraction before it is trusted to list anything.
assert.ok(commands.length >= 2, `expected the plugin's commands, got ${commands.length}`);
return commands;
}
test("the Obsidian page lists the commands the plugin registers", () => {
const about = pageAbout("obsidian");
for (const command of loadObsidianCommands()) {
assert.ok(
about.markdown.includes(`**${command.name}**`),
`the Obsidian page does not document "${command.name}" (${command.id})`
);
}
});
test("the Foundry page covers what the world and the campaign do with each other", () => {
const about = pageAbout("foundry").markdown;
for (const topic of ["Auto-sync", "Force Sync", "item directory", "Pairing Status"]) {
assert.ok(about.includes(topic), `the Foundry page never mentions ${topic}`);
}
});
// --- The routes ---
test("the app renders whichever page the address asks for", () => {
const root = readRepoFile("frontend", "app", "app.vue");
assert.match(root, /<NuxtPage\s*\/?>/, "app.vue has to render the matched page");
assert.doesNotMatch(root, /CreateWindow/, "the window app boots from AppShell, not from app.vue");
});
test("the documentation has a route of its own, and the app keeps the rest", () => {
const pages = path.join("frontend", "app", "pages");
const docsRoutes = ["docs/index.vue", "docs/[slug].vue"];
for (const route of docsRoutes) {
assert.match(
readRepoFile(pages, route),
/<DocsView\s*\/?>/,
`${route} has to render the documentation`
);
}
for (const route of ["index.vue", "[...all].vue"]) {
assert.match(
readRepoFile(pages, route),
/<AppShell\s*\/?>/,
`${route} has to open the window app`
);
}
// The catch-all is what keeps /link/authorize, and every path a service already links to, alive.
const shell = readRepoFile("frontend", "app", "components", "views", "AppShell.vue");
assert.ok(shell.includes("/link/authorize"), "the service link screen has to stay reachable");
assert.ok(shell.includes("/discord/authorize"), "the legacy Discord link has to stay reachable");
});
test("the main menu points at the documentation", () => {
const menu = readRepoFile("frontend", "app", "components", "windows", "MainMenuWindow.vue");
assert.match(menu, /href="\/docs"/, "the main menu has to link to /docs");
assert.match(menu, /main-menu\.documentation/);
for (const locale of ["en", "es", "ca"]) {
const strings = JSON.parse(readRepoFile("frontend", "i18n", "locales", locale, "main-menu.json"));
assert.ok(strings.documentation, `${locale} has no label for the documentation link`);
}
});
// --- How the documentation is laid out (Syndria98/dragonroll#85) ---
// The `<style>` of DocsView.vue read as `{ selector, media, declarations }` rules: the block is
// flat — every rule is a top level selector and the only nesting is the media queries — so pairing
// braces is enough, and the test does not need a stylesheet parser the repository root lacks.
function DocsStyleRules() {
const source = readRepoFile("frontend", "app", "components", "views", "DocsView.vue");
const css = source
.slice(source.indexOf(">", source.indexOf("<style")) + 1, source.indexOf("</style>"))
.replace(/\/\*[\s\S]*?\*\//g, "");
const rules = [];
function scan(text, media) {
let index = 0;
for (;;) {
const brace = text.indexOf("{", index);
if (brace === -1) return rules;
const selector = text.slice(index, brace).trim();
let depth = 1;
let cursor = brace + 1;
while (cursor < text.length && depth > 0) {
if (text[cursor] === "{") depth += 1;
else if (text[cursor] === "}") depth -= 1;
cursor += 1;
}
const body = text.slice(brace + 1, cursor - 1);
if (selector.startsWith("@")) scan(body, selector);
else rules.push({ selector, media, declarations: body });
index = cursor;
}
}
return scan(css, null);
}
const styleRules = DocsStyleRules();
// The rules that name a class, with `media` null for the plain ones and "min-width" / "max-width"
// for the ones a media query switches on. The last one wins where they overlap, as in a stylesheet.
function RulesFor(className, media = null) {
return styleRules.filter((rule) =>
rule.selector.split(",").some((name) => name.trim() === className) &&
(media === null ? rule.media === null : Boolean(rule.media) && rule.media.includes(media))
);
}
// A `padding:` shorthand spread over its four sides, the way the browser reads it.
function PaddingOf(rule) {
const shorthand = rule.declarations.match(/(?:^|[;\s])padding:\s*([^;]+)/);
assert.ok(shorthand, `the ${rule.selector} rule sets no padding to compare`);
const values = shorthand[1].trim().split(/\s+/).map((value) => parseFloat(value));
assert.ok(
values.length <= 4 && values.every((value) => Number.isFinite(value)),
`only px padding is compared here, ${rule.selector} has "${shorthand[1].trim()}"`
);
return {
top: values[0],
right: values[1] ?? values[0],
bottom: values[2] ?? values[0],
left: values[3] ?? values[1] ?? values[0],
};
}
test("the two asides are as tall as the page they stand beside", () => {
for (const className of [".docs-sidebar", ".docs-sections"]) {
const aside = RulesFor(className).find((rule) => /position:\s*sticky/.test(rule.declarations));
assert.ok(aside, `${className} has to stay beside the text while the page scrolls`);
assert.match(aside.declarations, /height:\s*100vh/, `${className} has to fill the page, not just its own contents`);
assert.doesNotMatch(aside.declarations, /max-height/, `${className} is capped at a screen height by 'height'`);
}
});
test("a narrow window stacks the columns and lets each one be its own height", () => {
const stacked = RulesFor(".docs-sidebar", "max-width");
assert.equal(stacked.length, 1, "the stacked layout is set by one rule");
assert.match(stacked[0].declarations, /position:\s*static/, "a stacked sidebar does not follow the scroll");
assert.match(stacked[0].declarations, /height:\s*auto/, "…and it is not held at a screen height either");
});
test("the reading column is centred in the space left beside the sidebar", () => {
const reading = RulesFor(".docs-article").find((rule) => /max-width:/.test(rule.declarations));
assert.ok(reading, "the text has to be capped in width to be readable");
assert.match(reading.declarations, /margin-inline:\s*auto/, "…and centred in the space left beside the sidebar");
assert.match(reading.selector, /\.docs-pager/, "the pager under the text follows the same column");
});
test("a very wide window keeps the sections next to the text, not at the edge of the screen", () => {
const centred = RulesFor(".docs", "min-width");
assert.equal(centred.length, 1, "one wide window rule centres the documentation");
assert.match(centred[0].declarations, /justify-content:\s*center/);
const wider = Number(centred[0].media.match(/min-width:\s*(\d+)/)[1]);
assert.ok(wider >= 1400, `${wider}px is not a wide window: the layout breaks before that`);
const main = RulesFor(".docs-main", "min-width");
assert.equal(main.length, 1, "the main column is capped once the window is wide");
assert.match(main[0].declarations, /flex:\s*0 1 \d+px/, "…so it stops growing and the sections sit next to it");
});
test("the sections aside has more room around its links than the sidebar has", () => {
const shared = RulesFor(".docs-sidebar").find((rule) => /padding:/.test(rule.declarations));
const sections = RulesFor(".docs-sections").filter((rule) => /padding:/.test(rule.declarations)).pop();
assert.ok(sections && sections !== shared, "the sections aside sets its own padding");
const room = PaddingOf(sections);
const sidebar = PaddingOf(shared);
for (const side of ["top", "right", "bottom", "left"]) {
assert.ok(room[side] >= sidebar[side], `the sections aside is tighter than the sidebar on the ${side}`);
}
assert.ok(
["top", "right", "bottom", "left"].some((side) => room[side] > sidebar[side]),
"the sections aside asks for more padding than the two asides share"
);
});