From 613ab8e91ba83b4d26df65b27f42df005f9606ec Mon Sep 17 00:00:00 2001 From: hlaelissalt Date: Wed, 11 Nov 2026 14:17:15 +0100 Subject: [PATCH 1/8] feat: preview in Docker, page links and alerts, and a navigation by version compose.yaml serves the site with the development server and reads the products from clones on the machine, with preview.refs.json to read branches that are not merged yet. The synchronisation writes only what changed and deletes what is stale, so the server reloads without noise. Pages may use the alerts of GitHub and page: links that stay in the version and language of the reader. A front matter that is not valid YAML is reported as an error of that page. The navigation has one group for each version, with the sections translated. --- .dockerignore | 5 +++ .gitignore | 3 ++ README.md | 20 ++++++++++++ astro.config.ts | 26 +++++++++++++-- compose.yaml | 41 +++++++++++++++++++++++ preview.refs.example.json | 6 ++++ src/i18n/en.json | 6 +++- src/i18n/es.json | 6 +++- tools/lib/markdown.test.ts | 54 +++++++++++++++++++++++++++++++ tools/lib/markdown.ts | 53 ++++++++++++++++++++++++++++++ tools/lib/resolve.test.ts | 14 ++++++++ tools/lib/resolve.ts | 18 ++++++++--- tools/lib/source.test.ts | 14 ++++++++ tools/lib/source.ts | 20 ++++++++++-- tools/sync.ts | 66 +++++++++++++++++++++++++++++++------- 15 files changed, 330 insertions(+), 22 deletions(-) create mode 100644 .dockerignore create mode 100644 compose.yaml create mode 100644 preview.refs.example.json create mode 100644 tools/lib/markdown.test.ts create mode 100644 tools/lib/markdown.ts diff --git a/.dockerignore b/.dockerignore new file mode 100644 index 0000000..c9a1e55 --- /dev/null +++ b/.dockerignore @@ -0,0 +1,5 @@ +node_modules +dist +.astro +.cache +.git diff --git a/.gitignore b/.gitignore index c4e513b..6a758fe 100644 --- a/.gitignore +++ b/.gitignore @@ -7,3 +7,6 @@ dist/ /src/content/docs/*/plugins/ /src/content/docs/*/packages/ /src/data/products.generated.json + +# What the previews of a developer need; see compose.yaml. +/preview.refs.json diff --git a/README.md b/README.md index e1a3975..8547c10 100644 --- a/README.md +++ b/README.md @@ -54,6 +54,26 @@ Node 22.23 or later is required. To try the site with clones you already have, w DOCS_SOURCES=/path/to/clones DOCS_NO_FETCH=1 npm run build ``` +## Seeing it while you work + +```bash +docker compose up # then open http://localhost:4321/ +docker compose logs -f site +docker compose down +``` + +The site runs in a container with the development server of Astro. The products are read from clones on your machine (the folder above this repository by default, or `DOCS_SOURCES_DIR`), not from GitHub, so what you have committed locally shows up before it is pushed. The documentation is read again every few seconds and the page reloads by itself. + +To see branches that are not merged yet, copy `preview.refs.example.json` to `preview.refs.json` and list there, for each product, the branch to read for each line. Anything the synchronisation finds wrong in the documentation is in the log. + +## Writing a page + +A page is `docs//.md` in the repository of the product, with a front matter of `title`, `summary` and `order`. A value with a colon must be in quotes (`summary: "Two things: a and b"`); the build says which page breaks it. + +- **Alerts:** write the ones of GitHub (`> [!NOTE]`, `> [!TIP]`, `> [!IMPORTANT]`, `> [!WARNING]`, `> [!CAUTION]`). They read well on GitHub and become asides on the site. +- **Links to other pages of the product:** `[text](page:guides/install)` or `[text](page:guides/install#step-2)`. The link stays in the version and language the reader is in. +- **Hide a page** a later version inherits: a file at the same path with `hidden: true` and a `reason`. + ## Adding a product 1. In its repository, add `docs/docs.json` on `main`, and the pages under `docs/en/` and `docs/es/`. diff --git a/astro.config.ts b/astro.config.ts index 6fdbde9..6f27c73 100644 --- a/astro.config.ts +++ b/astro.config.ts @@ -1,6 +1,8 @@ import {existsSync, readFileSync} from 'node:fs'; +import {join} from 'node:path'; import {defineConfig} from 'astro/config'; import starlight from '@astrojs/starlight'; +import type {StarlightUserConfig} from '@astrojs/starlight/types'; interface Language { code: string; @@ -13,6 +15,7 @@ interface Product { slug: string; kind: 'plugin' | 'package'; title: Record; + lines: Array<{id: string; label: string; latest: boolean; sections: string[]}>; } const json = (path: string, fallback: T): T => (existsSync(path) ? (JSON.parse(readFileSync(path, 'utf8')) as T) : fallback); @@ -25,12 +28,17 @@ const locales = Object.fromEntries(languages.map((language) => [language.code, { const products = json<{products: Product[]}>('./src/data/products.generated.json', {products: []}).products; const translated = (texts: Record) => Object.fromEntries(languages.map((language) => [language.code, texts[language.code] ?? texts.en])); +// A text of the interface in each language (src/i18n/.json); what a language lacks is taken from English. +const dictionaries = Object.fromEntries(languages.map((language) => [language.code, json>(join('./src/i18n', `${language.code}.json`), {})])); +const uiText = (key: string, fallback: string): Record => Object.fromEntries(languages.map((language) => [language.code, dictionaries[language.code][key] ?? dictionaries.en?.[key] ?? fallback])); +const titleCase = (name: string): string => name.replace(/-/g, ' ').replace(/^./, (first) => first.toUpperCase()); + const kinds = [ {kind: 'plugin', label: 'Plugins', es: 'Plugins', dir: 'plugins'}, {kind: 'package', label: 'Packages', es: 'Paquetes', dir: 'packages'}, ] as const; -const sidebar = kinds +const sidebar: NonNullable = kinds .filter(({kind}) => products.some((product) => product.kind === kind)) .map(({kind, label, es, dir}) => ({ label, @@ -41,7 +49,19 @@ const sidebar = kinds label: product.title.en, translations: translated(product.title), collapsed: true, - items: [{autogenerate: {directory: `${dir}/${product.slug}`, collapsed: true}}], + // One group for each version, newest first, so the navigation stays in the version the reader is in. + items: [...product.lines].reverse().map((line) => ({ + label: line.label, + collapsed: !line.latest, + items: [ + {label: uiText('overview', 'Overview').en, translations: uiText('overview', 'Overview'), slug: `${dir}/${product.slug}/${line.id}`}, + ...line.sections.map((section) => ({ + label: uiText(`section.${section}`, titleCase(section)).en, + translations: uiText(`section.${section}`, titleCase(section)), + items: [{autogenerate: {directory: `${dir}/${product.slug}/${line.id}/${section}`}}], + })), + ], + })), })), })); @@ -49,6 +69,8 @@ export default defineConfig({ site: 'https://docs.didactika.org', trailingSlash: 'always', build: {format: 'directory'}, + // In Docker the files change on the other side of a mount, where the system does not tell the watcher; polling does the same job. + vite: {server: {watch: {usePolling: process.env.DOCS_POLL === '1'}}}, integrations: [ starlight({ title: {en: 'Didactika Docs', es: 'Documentación de Didactika'}, diff --git a/compose.yaml b/compose.yaml new file mode 100644 index 0000000..9243a33 --- /dev/null +++ b/compose.yaml @@ -0,0 +1,41 @@ +# The site, served for development: the portal of Didactika Docs with the documentation of the products that are in manifest.json. +# +# docker compose up then open http://localhost:4321/ +# docker compose logs -f site to see what the synchronisation reports +# +# The products are read from clones on this machine (DOCS_SOURCES_DIR, by default the folder above this repository), not from GitHub, so +# what you have committed locally shows up before it is pushed. To preview branches that are not merged, list them in preview.refs.json +# (copy preview.refs.example.json). The documentation is read again every few seconds and the site reloads by itself. +name: didactika-docs + +services: + site: + image: node:22 + working_dir: /app + ports: + - '4321:4321' + environment: + DOCS_SOURCES: /sources + DOCS_NO_FETCH: '1' + DOCS_POLL: '1' + ASTRO_TELEMETRY_DISABLED: '1' + # The clones belong to another user than the one in the container, and git refuses them unless it is told they are fine. + GIT_CONFIG_COUNT: '1' + GIT_CONFIG_KEY_0: safe.directory + GIT_CONFIG_VALUE_0: '*' + volumes: + - .:/app + # The dependencies are installed for Linux inside the container; the ones of this machine are not used. + - node_modules:/app/node_modules + - ${DOCS_SOURCES_DIR:-..}:/sources:ro + command: + - sh + - -c + - | + npm ci --no-audit --no-fund + node tools/sync.ts || true + (while true; do sleep 5; node tools/sync.ts > /tmp/sync.log 2>&1 || true; done) & + exec npx astro dev --host 0.0.0.0 --port 4321 + +volumes: + node_modules: diff --git a/preview.refs.example.json b/preview.refs.example.json new file mode 100644 index 0000000..7a82df1 --- /dev/null +++ b/preview.refs.example.json @@ -0,0 +1,6 @@ +{ + "didactika/moodle-local_delegateaccount": { + "main": "docs/portal-503", + "MOODLE_405_STABLE": "docs/portal-405" + } +} diff --git a/src/i18n/en.json b/src/i18n/en.json index c231eda..56a8c96 100644 --- a/src/i18n/en.json +++ b/src/i18n/en.json @@ -6,5 +6,9 @@ "name": "Name", "summary": "Summary", "translationMissing": "This page is not available in {language} yet. You are reading the English version.", - "translationOutdated": "The {language} version of this page is older than the English one, so the English version is shown." + "translationOutdated": "The {language} version of this page is older than the English one, so the English version is shown.", + "overview": "Overview", + "section.getting-started": "Getting started", + "section.guides": "Guides", + "section.reference": "Reference" } diff --git a/src/i18n/es.json b/src/i18n/es.json index e40c8ad..4f39e73 100644 --- a/src/i18n/es.json +++ b/src/i18n/es.json @@ -6,5 +6,9 @@ "name": "Nombre", "summary": "Resumen", "translationMissing": "Esta página aún no está disponible en {language}. Estás leyendo la versión en inglés.", - "translationOutdated": "La versión en {language} de esta página es anterior a la inglesa, así que se muestra la versión en inglés." + "translationOutdated": "La versión en {language} de esta página es anterior a la inglesa, así que se muestra la versión en inglés.", + "overview": "Visión general", + "section.getting-started": "Primeros pasos", + "section.guides": "Guías", + "section.reference": "Referencia" } diff --git a/tools/lib/markdown.test.ts b/tools/lib/markdown.test.ts new file mode 100644 index 0000000..be3290d --- /dev/null +++ b/tools/lib/markdown.test.ts @@ -0,0 +1,54 @@ +import assert from 'node:assert/strict'; +import {describe, it} from 'node:test'; +import {alertsToAsides, resolvePageLinks, transformBody} from './markdown.ts'; + +describe('alertsToAsides', () => { + it('turns an alert of GitHub into an aside of Starlight', () => { + assert.equal(alertsToAsides('> [!NOTE]\n> It never stores passwords.\n\nAfter.'), ':::note\nIt never stores passwords.\n:::\n\nAfter.'); + }); + + it('keeps every quoted line of the alert, and the blank lines inside it', () => { + assert.equal(alertsToAsides('> [!TIP]\n> First.\n>\n> Second.\n'), ':::tip\nFirst.\n\nSecond.\n:::\n'); + }); + + it('maps each kind to the aside that is closest in weight', () => { + const kinds = ['NOTE', 'TIP', 'IMPORTANT', 'WARNING', 'CAUTION'].map((kind) => alertsToAsides(`> [!${kind}]\n> x`).split('\n')[0]); + assert.deepEqual(kinds, [':::note', ':::tip', ':::caution', ':::caution', ':::danger']); + }); + + it('leaves an ordinary quote alone', () => { + assert.equal(alertsToAsides('> Just a quote.\n> Two lines.'), '> Just a quote.\n> Two lines.'); + }); + + it('does not touch fenced code', () => { + const code = '```md\n> [!NOTE]\n> Inside.\n```'; + assert.equal(alertsToAsides(code), code); + }); +}); + +describe('resolvePageLinks', () => { + const base = '/en/plugins/local-demo/m503'; + + it('points a page link into the same version and language', () => { + assert.equal(resolvePageLinks('See [install](page:getting-started/installation).', base), 'See [install](/en/plugins/local-demo/m503/getting-started/installation/).'); + }); + + it('keeps the anchor', () => { + assert.equal(resolvePageLinks('[x](page:guides/a#step-2)', base), '[x](/en/plugins/local-demo/m503/guides/a/#step-2)'); + }); + + it('links the index to the root of the product', () => { + assert.equal(resolvePageLinks('[home](page:index)', base), '[home](/en/plugins/local-demo/m503/)'); + }); + + it('does not touch ordinary links or fenced code', () => { + const text = '[a](https://example.org) and\n```\n[b](page:guides/a)\n```'; + assert.equal(resolvePageLinks(text, base), text); + }); +}); + +describe('transformBody', () => { + it('does both', () => { + assert.equal(transformBody('> [!WARNING]\n> See [roles](page:getting-started/give-permission).', '/es/plugins/x/m405'), ':::caution\nSee [roles](/es/plugins/x/m405/getting-started/give-permission/).\n:::'); + }); +}); diff --git a/tools/lib/markdown.ts b/tools/lib/markdown.ts new file mode 100644 index 0000000..1308ec4 --- /dev/null +++ b/tools/lib/markdown.ts @@ -0,0 +1,53 @@ +/** + * What the portal does to the Markdown of a page on its way into the site. + * + * Two things, so that a page reads well on GitHub and on the portal without being written twice: + * + * - The alerts of GitHub (`> [!NOTE]`) become the asides of Starlight (`:::note`). + * - A link to another page of the same product, `[text](page:guides/install)`, becomes the address of that page in the same version + * and language, so a link never leaves the version the reader is in. An anchor may follow: `page:guides/install#step-2`. + * + * Fenced code is left as it is. + * + * @license GPL-3.0-or-later + */ + +const ASIDES: Record = {NOTE: 'note', TIP: 'tip', IMPORTANT: 'caution', WARNING: 'caution', CAUTION: 'danger'}; + +/** Applies `change` to the text outside fenced code blocks and keeps the code as it is. */ +function outsideFences(markdown: string, change: (text: string) => string): string { + const parts = markdown.split(/(^(?:```|~~~)[^\n]*\n[\s\S]*?^(?:```|~~~)[ \t]*$)/m); + return parts.map((part, index) => (index % 2 === 1 ? part : change(part))).join(''); +} + +/** `> [!WARNING]` and the quoted lines that follow become `:::caution` … `:::`. */ +export function alertsToAsides(markdown: string): string { + return outsideFences(markdown, (text) => { + const lines = text.split('\n'); + const out: string[] = []; + for (let index = 0; index < lines.length; index++) { + const alert = /^>\s*\[!(NOTE|TIP|IMPORTANT|WARNING|CAUTION)\]\s*$/.exec(lines[index]); + if (!alert) { + out.push(lines[index]); + continue; + } + const body: string[] = []; + while (index + 1 < lines.length && /^>/.test(lines[index + 1])) { + body.push(lines[++index].replace(/^>\s?/, '')); + } + out.push(`:::${ASIDES[alert[1]]}`, ...body, ':::'); + } + return out.join('\n'); + }); +} + +/** `page:` links, written as the address of the page inside `base` (`/en/plugins/local-demo/m503`). */ +export function resolvePageLinks(markdown: string, base: string): string { + return outsideFences(markdown, (text) => + text.replace(/\]\(page:([^)#\s]+)(#[^)\s]*)?\)/g, (_, id: string, anchor: string | undefined) => `](${base}${id === 'index' ? '/' : `/${id}/`}${anchor ?? ''})`), + ); +} + +export function transformBody(markdown: string, base: string): string { + return resolvePageLinks(alertsToAsides(markdown), base); +} diff --git a/tools/lib/resolve.test.ts b/tools/lib/resolve.test.ts index 088d8c1..1a0248a 100644 --- a/tools/lib/resolve.test.ts +++ b/tools/lib/resolve.test.ts @@ -27,6 +27,12 @@ describe('parseFrontmatter', () => { assert.equal(data.title, 'Hello'); }); + it('says why a front matter is not valid, instead of failing', () => { + const {data, error} = parseFrontmatter('---\ntitle: A\nsummary: One: two\n---\nText\n'); + assert.deepEqual(data, {}); + assert.match(error!, /Nested mappings/); + }); + it('returns no data for a page without front matter', () => { assert.deepEqual(parseFrontmatter('Just text').data, {}); }); @@ -204,6 +210,14 @@ describe('languages', () => { }); describe('files and lines', () => { + it('reports a page whose front matter is not valid, and goes on', () => { + const result = resolveProduct([line('m405', null, {'en/a.md': '---\ntitle: A\nsummary: One: two\n---\n', 'en/b.md': page('B')})], [EN]); + const issue = result.issues.find((candidate) => candidate.code === 'invalid-frontmatter')!; + assert.equal(issue.level, 'error'); + assert.equal(issue.path, 'en/a.md'); + assert.equal(lineOf(result, 'm405').pages.length, 2); + }); + it('rejects the same page as .md and .mdx in one line', () => { const result = resolveProduct([line('m405', null, {'en/a.md': page('A'), 'en/a.mdx': page('A')})], [EN]); assert.ok(codes(result).includes('error:duplicate-page')); diff --git a/tools/lib/resolve.ts b/tools/lib/resolve.ts index c714c7f..347ee4a 100644 --- a/tools/lib/resolve.ts +++ b/tools/lib/resolve.ts @@ -101,14 +101,20 @@ const PAGE = /^([A-Za-z][A-Za-z0-9_-]*)\/(.+)(\.mdx?)$/; const ASSETS = '_assets/'; /** Reads the front matter of a page. */ -export function parseFrontmatter(raw: string): {data: Record; body: string} { +export function parseFrontmatter(raw: string): {data: Record; body: string; error?: string} { const text = raw.replace(/^/, '').replace(/\r\n/g, '\n'); const match = /^---\n([\s\S]*?)\n---(?:\n|$)/.exec(text); if (!match) { return {data: {}, body: text}; } - const data = parseYaml(match[1]); - return {data: data && typeof data === 'object' && !Array.isArray(data) ? (data as Record) : {}, body: text.slice(match[0].length)}; + const body = text.slice(match[0].length); + try { + const data = parseYaml(match[1]); + return {data: data && typeof data === 'object' && !Array.isArray(data) ? (data as Record) : {}, body}; + } catch (error) { + // A front matter that is not valid YAML gives no data; the caller reports why. + return {data: {}, body, error: (error instanceof Error ? error.message : String(error)).split('\n')[0]}; + } } const normalise = (content: string): string => content.replace(/^/, '').replace(/\r\n/g, '\n').trimEnd(); @@ -181,7 +187,11 @@ export function resolveProduct(lines: LineInput[], languages: LanguageDef[]): Re issues.push({level: 'error', code: 'duplicate-page', line: line.id, path, message: `${key} exists as .md and .mdx in the same line.`}); continue; } - pages.set(key, {lang, id, ext: ext as '.md' | '.mdx', line: line.id, path, content, data: parseFrontmatter(content).data}); + const parsed = parseFrontmatter(content); + if (parsed.error) { + issues.push({level: 'error', code: 'invalid-frontmatter', line: line.id, path, message: `The front matter of ${path} is not valid YAML: ${parsed.error} A value with a colon must be in quotes.`}); + } + pages.set(key, {lang, id, ext: ext as '.md' | '.mdx', line: line.id, path, content, data: parsed.data}); } pagesOf.set(line.id, pages); assetsOf.set(line.id, assets); diff --git a/tools/lib/source.test.ts b/tools/lib/source.test.ts index 01d2ac4..f8cdb49 100644 --- a/tools/lib/source.test.ts +++ b/tools/lib/source.test.ts @@ -80,6 +80,20 @@ describe('a repository with two lines', () => { assert.ok(!base.files.has('en/guides/new.md')); }); + it('reads a line from another ref, to preview what is not merged yet', () => { + git('checkout', '-q', '-b', 'preview', 'main'); + write('docs/en/index.md', '---\ntitle: Preview\n---\n'); + git('add', '-A'); + git('commit', '-q', '-m', 'preview'); + git('checkout', '-q', 'main'); + const preview = readProduct(repo, {refs: {main: 'preview'}}); + assert.equal(preview.lines[1].branch, 'main'); + assert.ok(preview.lines[1].files.get('en/index.md')!.includes('Preview')); + assert.ok(!readProduct(repo).lines[1].files.get('en/index.md')!.includes('Preview')); + assert.throws(() => readProduct(repo, {refs: {main: 'does-not-exist'}}), /is not a ref/); + assert.throws(() => readProduct(repo, {refs: {feature: 'preview'}}), /is not a branch that is a line/); + }); + it('keeps a binary asset byte for byte', () => { const asset = readProduct(repo).lines[0].files.get('_assets/shot.png')!; assert.equal(Buffer.from(asset, 'latin1').toString('hex'), '89504e470d0a1a0a00ff'); diff --git a/tools/lib/source.ts b/tools/lib/source.ts index 50033f4..2afb2cb 100644 --- a/tools/lib/source.ts +++ b/tools/lib/source.ts @@ -74,8 +74,13 @@ export function readVersionPhp(php: string): {id: string; release: string; low: return {id: `m${id}`, release, low: Number(supported[1]), high: Number(supported[2])}; } +export interface ReadOptions { + /** Reads a line from another ref than its own branch, to see what is not merged yet: `{main: 'docs/portal-503'}`. */ + refs?: Record; +} + /** Local branches and the ones of `origin`, by branch name; `origin` wins because it is what is published. */ -function branches(repo: string): Map { +function branches(repo: string, overrides: Record = {}): Map { const refs = git(repo, ['for-each-ref', '--format=%(refname)', 'refs/heads', 'refs/remotes/origin']).split('\n').filter(Boolean); const found = new Map(); for (const ref of refs) { @@ -86,6 +91,15 @@ function branches(repo: string): Map { found.set(name, ref); } } + for (const [name, ref] of Object.entries(overrides)) { + if (!LINE_BRANCH.test(name)) { + throw new Error(`${name} is not a branch that is a line (main or MOODLE__STABLE).`); + } + if (tryGit(repo, ['rev-parse', '--verify', '--quiet', `${ref}^{commit}`]) === undefined) { + throw new Error(`${ref}, given for ${name}, is not a ref of ${repo}.`); + } + found.set(name, ref); + } return found; } @@ -106,9 +120,9 @@ function filesOf(repo: string, ref: string): Map { } /** Reads the product documented by the repository in `repo`. */ -export function readProduct(repo: string): SourceProduct { +export function readProduct(repo: string, options: ReadOptions = {}): SourceProduct { const issues: Issue[] = []; - const found = branches(repo); + const found = branches(repo, options.refs); const defaultRef = found.get(DEFAULT_BRANCH); const docsRaw = defaultRef ? tryGit(repo, ['show', `${defaultRef}:docs/docs.json`]) : undefined; const docs = docsRaw ? (JSON.parse(docsRaw) as DocsJson) : null; diff --git a/tools/sync.ts b/tools/sync.ts index c6d3e46..a2e47dd 100644 --- a/tools/sync.ts +++ b/tools/sync.ts @@ -14,14 +14,18 @@ * DOCS_SOURCES folder that holds a clone of each repository, named like it. Default: .cache/sources, cloned from GitHub. * DOCS_NO_FETCH use the clones as they are, without fetching. * DOCS_MANIFEST another manifest than manifest.json, for trying the site with a repository of examples. + * DOCS_REFS JSON that reads a line from another ref than its branch, to preview what is not merged yet: + * {"didactika/moodle-local_x": {"main": "docs/portal", "MOODLE_405_STABLE": "docs/portal-405"}} + * The same JSON in preview.refs.json (ignored by git) is read when the variable is not set. * * @license GPL-3.0-or-later */ import {execFileSync} from 'node:child_process'; -import {existsSync, mkdirSync, readFileSync, rmSync, writeFileSync} from 'node:fs'; +import {existsSync, mkdirSync, readdirSync, readFileSync, rmdirSync, rmSync, writeFileSync} from 'node:fs'; import {dirname, join, resolve} from 'node:path'; import {stringify} from 'yaml'; +import {transformBody} from './lib/markdown.ts'; import {parseFrontmatter, resolveProduct, type Issue, type LanguageDef} from './lib/resolve.ts'; import {readProduct, type DocsJson} from './lib/source.ts'; @@ -70,11 +74,41 @@ function sourceOf(repo: string): string { return folder; } +// Everything written in this run. A file that is already as it should be is not touched, so a watching dev server does not rebuild for nothing, +// and the files of an earlier run that were not written again are deleted at the end. +const written = new Set(); + function write(path: string, text: string): void { + written.add(path); + if (existsSync(path) && readFileSync(path, 'utf8') === text) { + return; + } mkdirSync(dirname(path), {recursive: true}); writeFileSync(path, text); } +/** Deletes what an earlier run generated and this one did not, and the folders that are left empty. */ +function removeStale(folder: string): void { + if (!existsSync(folder)) { + return; + } + for (const name of readdirSync(folder, {withFileTypes: true})) { + const path = join(folder, name.name); + if (name.isDirectory()) { + removeStale(path); + } else if (!written.has(path)) { + rmSync(path); + } + } + if (readdirSync(folder).length === 0) { + rmdirSync(folder); + } +} + +// Refs to preview instead of the branches of a line: from DOCS_REFS, or from preview.refs.json (see preview.refs.example.json). +const previewFile = join(root, 'preview.refs.json'); +const previews = (process.env.DOCS_REFS ? JSON.parse(process.env.DOCS_REFS) : existsSync(previewFile) ? JSON.parse(readFileSync(previewFile, 'utf8')) : {}) as Record>; + /** The front matter Starlight understands, made from the one authors write (title, summary, order). */ function frontmatter(data: Record, extra: Record): string { const { title, summary, description, order, hidden, reason, source, ...rest } = data; @@ -93,17 +127,19 @@ function frontmatter(data: Record, extra: Record + [...new Set(ids.filter((id) => id.includes('/')).map((id) => id.split('/')[0]))].sort((a, b) => { + const rank = (name: string): number => (USUAL_SECTIONS.includes(name) ? USUAL_SECTIONS.indexOf(name) : USUAL_SECTIONS.length); + return rank(a) - rank(b) || a.localeCompare(b); + }); const issues: Array = []; const products: Array> = []; for (const entry of manifest.products) { - const product = readProduct(sourceOf(entry.repo)); + const product = readProduct(sourceOf(entry.repo), {refs: previews[entry.repo]}); const label = entry.repo; issues.push(...product.issues.map((issue) => ({...issue, product: label}))); @@ -141,11 +177,13 @@ for (const entry of manifest.products) { provenance: page.provenance, provenanceFrom: page.provenanceFrom, shownLang: page.shown.lang, - }) + body; + }); const base = join(content, page.lang, kindDir, docs.slug); - write(join(base, line.id, `${page.id}${page.shown.ext}`), text); + const address = `/${page.lang}/${kindDir}/${docs.slug}`; + write(join(base, line.id, `${page.id}${page.shown.ext}`), text + transformBody(body, `${address}/${line.id}`)); + // The address without a version shows the newest one, and its links stay in that address. if (line.id === newest.id) { - write(join(base, `${page.id}${page.shown.ext}`), text); + write(join(base, `${page.id}${page.shown.ext}`), text + transformBody(body, address)); } } } @@ -160,7 +198,7 @@ for (const entry of manifest.products) { translations: docs.translations ?? {source: 'l10n'}, lines: resolution.lines.map((line) => { const info = product.lines.find((candidate) => candidate.id === line.id)!; - return {id: line.id, label: info.label, branch: info.branch, release: info.release, extends: info.extends, latest: line.id === newest.id, coverage: line.coverage, pages: line.pages.filter((page) => page.lang === sourceCode).length}; + return {id: line.id, label: info.label, branch: info.branch, release: info.release, extends: info.extends, latest: line.id === newest.id, coverage: line.coverage, pages: line.pages.filter((page) => page.lang === sourceCode).length, sections: sectionsOf(line.pages.filter((page) => page.lang === sourceCode).map((page) => page.id))}; }), }); } @@ -184,6 +222,12 @@ for (const language of languages) { } } +for (const language of languages) { + for (const dir of Object.values(KIND_DIR)) { + removeStale(join(content, language.code, dir)); + } +} + write(join(root, 'src', 'data', 'products.generated.json'), JSON.stringify({languages: languages.map(({code, name, dir}) => ({code, name, dir: dir ?? 'ltr'})), products}, null, 2) + '\n'); for (const issue of issues) { From b0820a2174d24e18fe71061a64e134d48ad57187 Mon Sep 17 00:00:00 2001 From: hlaelissalt Date: Wed, 11 Nov 2026 17:00:47 +0100 Subject: [PATCH 2/8] feat: the look of Didactika, a home, the status of the Moodle directory and a site served as it is deployed The site takes the design system of Didactika (its palette, IBM Plex Sans, Space Grotesk and IBM Plex Mono) with the Material Symbols icons: a header with the product and the version selector, a search that works with the built site, a title for each page with its provenance, a footer with the previous and next pages, and a home that is a dashboard of the documented products. The navigation shows only the product and the version the reader is in. The synchronisation brings the images and the icon of each product, tells whether a plugin is in the Moodle directory from the API of Moodle, lists what is documented next and lets the pages of MDX use the components of the site without importing them. docker compose now builds the site and serves it as Pages will, building it again when the documentation changes. --- .github/workflows/ci.yml | 1 + .gitignore | 2 + astro.config.ts | 12 +- compose.yaml | 21 +- package-lock.json | 46 +++ package.json | 8 +- roadmap.json | 42 +++ src/components/DirectoryChip.astro | 29 ++ src/components/Feature.astro | 29 ++ src/components/FeatureGrid.astro | 11 + src/components/Footer.astro | 46 +++ src/components/Header.astro | 11 + src/components/MIcon.astro | 35 ++ src/components/PageTitle.astro | 121 +++++++ src/components/ProductCard.astro | 79 +++++ src/components/Screenshot.astro | 23 ++ src/components/Sidebar.astro | 45 +++ src/components/SiteFooter.astro | 46 +++ src/components/SiteHeader.astro | 100 ++++++ src/components/SiteSearch.astro | 134 ++++++++ src/content/docs/en/index.mdx | 11 - src/content/docs/es/index.mdx | 11 - src/i18n/en.json | 79 ++++- src/i18n/es.json | 79 ++++- src/layouts/Landing.astro | 55 ++++ src/lib/site.ts | 102 ++++++ src/pages/[lang]/index.astro | 144 +++++++++ src/pages/[lang]/plugins/index.astro | 32 ++ src/pages/index.astro | 21 ++ src/styles/didactika.css | 458 ++++++++++++++++++++++++++- tools/check-icons.ts | 44 +++ tools/lib/directory.test.ts | 53 ++++ tools/lib/directory.ts | 64 ++++ tools/lib/markdown.test.ts | 59 +++- tools/lib/markdown.ts | 55 +++- tools/lib/source.test.ts | 7 +- tools/lib/source.ts | 12 +- tools/serve.ts | 87 +++++ tools/sync.ts | 155 ++++++--- tools/to-webp.ts | 31 ++ 40 files changed, 2287 insertions(+), 113 deletions(-) create mode 100644 roadmap.json create mode 100644 src/components/DirectoryChip.astro create mode 100644 src/components/Feature.astro create mode 100644 src/components/FeatureGrid.astro create mode 100644 src/components/Footer.astro create mode 100644 src/components/Header.astro create mode 100644 src/components/MIcon.astro create mode 100644 src/components/PageTitle.astro create mode 100644 src/components/ProductCard.astro create mode 100644 src/components/Screenshot.astro create mode 100644 src/components/Sidebar.astro create mode 100644 src/components/SiteFooter.astro create mode 100644 src/components/SiteHeader.astro create mode 100644 src/components/SiteSearch.astro delete mode 100644 src/content/docs/en/index.mdx delete mode 100644 src/content/docs/es/index.mdx create mode 100644 src/layouts/Landing.astro create mode 100644 src/lib/site.ts create mode 100644 src/pages/[lang]/index.astro create mode 100644 src/pages/[lang]/plugins/index.astro create mode 100644 src/pages/index.astro create mode 100644 tools/check-icons.ts create mode 100644 tools/lib/directory.test.ts create mode 100644 tools/lib/directory.ts create mode 100644 tools/serve.ts create mode 100644 tools/to-webp.ts diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index d1428df..fc9b238 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -28,6 +28,7 @@ jobs: - run: npm ci - run: npm run typecheck - run: npm test + - run: npm run icons - run: npm run build - uses: actions/upload-artifact@v4 with: diff --git a/.gitignore b/.gitignore index 6a758fe..e8fb741 100644 --- a/.gitignore +++ b/.gitignore @@ -10,3 +10,5 @@ dist/ # What the previews of a developer need; see compose.yaml. /preview.refs.json +/public/docs-assets/ +/public/product-icons/ diff --git a/astro.config.ts b/astro.config.ts index 6f27c73..6523558 100644 --- a/astro.config.ts +++ b/astro.config.ts @@ -77,9 +77,19 @@ export default defineConfig({ description: 'The documentation of the Moodle plugins and the npm packages of Didactika.', defaultLocale: 'en', locales, - logo: {src: './src/assets/didactika-logo.png', alt: 'Didactika'}, + // The header, the title of a page, the navigation and the foot are drawn by the components of Didactika (src/components). + components: { + Header: './src/components/Header.astro', + PageTitle: './src/components/PageTitle.astro', + Sidebar: './src/components/Sidebar.astro', + Footer: './src/components/Footer.astro', + }, favicon: '/brand/favicon.ico', head: [ + { + tag: 'script', + content: "(function(){var a=new URLSearchParams(location.search).get('mode');if(a==='dark'||a==='light'){try{localStorage.setItem('starlight-theme',a);}catch(e){}document.documentElement.dataset.theme=a;}})();", + }, {tag: 'link', attrs: {rel: 'icon', href: '/brand/favicon.svg', type: 'image/svg+xml'}}, {tag: 'link', attrs: {rel: 'icon', href: '/brand/favicon-32x32.png', sizes: '32x32', type: 'image/png'}}, {tag: 'link', attrs: {rel: 'icon', href: '/brand/favicon-16x16.png', sizes: '16x16', type: 'image/png'}}, diff --git a/compose.yaml b/compose.yaml index 9243a33..eac3f52 100644 --- a/compose.yaml +++ b/compose.yaml @@ -1,11 +1,13 @@ -# The site, served for development: the portal of Didactika Docs with the documentation of the products that are in manifest.json. +# The site, served as it will be deployed: the portal of Didactika Docs with the documentation of the products that are in manifest.json. # -# docker compose up then open http://localhost:4321/ -# docker compose logs -f site to see what the synchronisation reports +# docker compose up -d then open http://localhost:4321/ +# docker compose logs -f site to see the builds and what the synchronisation reports +# docker compose down to stop it # # The products are read from clones on this machine (DOCS_SOURCES_DIR, by default the folder above this repository), not from GitHub, so # what you have committed locally shows up before it is pushed. To preview branches that are not merged, list them in preview.refs.json -# (copy preview.refs.example.json). The documentation is read again every few seconds and the site reloads by itself. +# (copy preview.refs.example.json). The documentation is read again every few seconds and the site is built again when it changes, so what +# you see, search included, is what Pages publishes. `npm run dev` gives the development server instead, with hot reload and no search. name: didactika-docs services: @@ -17,8 +19,8 @@ services: environment: DOCS_SOURCES: /sources DOCS_NO_FETCH: '1' - DOCS_POLL: '1' ASTRO_TELEMETRY_DISABLED: '1' + PORT: '4321' # The clones belong to another user than the one in the container, and git refuses them unless it is told they are fine. GIT_CONFIG_COUNT: '1' GIT_CONFIG_KEY_0: safe.directory @@ -28,14 +30,7 @@ services: # The dependencies are installed for Linux inside the container; the ones of this machine are not used. - node_modules:/app/node_modules - ${DOCS_SOURCES_DIR:-..}:/sources:ro - command: - - sh - - -c - - | - npm ci --no-audit --no-fund - node tools/sync.ts || true - (while true; do sleep 5; node tools/sync.ts > /tmp/sync.log 2>&1 || true; done) & - exec npx astro dev --host 0.0.0.0 --port 4321 + command: sh -c "npm ci --no-audit --no-fund && node tools/serve.ts" volumes: node_modules: diff --git a/package-lock.json b/package-lock.json index f036467..90e4bd4 100644 --- a/package-lock.json +++ b/package-lock.json @@ -10,6 +10,10 @@ "license": "GPL-3.0-or-later", "dependencies": { "@astrojs/starlight": "^0.42.10", + "@fontsource/ibm-plex-mono": "^5.3.0", + "@fontsource/ibm-plex-sans": "^5.3.0", + "@fontsource/space-grotesk": "^5.3.0", + "@iconify-json/material-symbols": "^1.2.98", "astro": "^7.4.10", "yaml": "^2.8.0" }, @@ -909,6 +913,48 @@ "@expressive-code/core": "^0.44.3" } }, + "node_modules/@fontsource/ibm-plex-mono": { + "version": "5.3.0", + "resolved": "https://registry.npmjs.org/@fontsource/ibm-plex-mono/-/ibm-plex-mono-5.3.0.tgz", + "integrity": "sha512-eTgnZjZEGk1QtD3ZstF+Vclo2HLAni8YMy34/DxllwZvyz1lR/1RF/xTiAquOBO7MvqBx8D2Ig2WCPMVfdZu7Q==", + "license": "OFL-1.1", + "funding": { + "url": "https://github.com/sponsors/ayuhito" + } + }, + "node_modules/@fontsource/ibm-plex-sans": { + "version": "5.3.0", + "resolved": "https://registry.npmjs.org/@fontsource/ibm-plex-sans/-/ibm-plex-sans-5.3.0.tgz", + "integrity": "sha512-CbE4CbbEEZJX860XyUiRpsksXIQR8Rp2XDva2VO53NJox9tVNtusrysd2x5YkUEY3ErQ66W1IiiQL8/wihhw5w==", + "license": "OFL-1.1", + "funding": { + "url": "https://github.com/sponsors/ayuhito" + } + }, + "node_modules/@fontsource/space-grotesk": { + "version": "5.3.0", + "resolved": "https://registry.npmjs.org/@fontsource/space-grotesk/-/space-grotesk-5.3.0.tgz", + "integrity": "sha512-ksnGizDPXIDuvqcTYTSrmZ+evx9sDlS8rp7+42BQ7wU+spt3twEoXfbJz672C+5CLg6VeUQwRy5RXshWb67LcQ==", + "license": "OFL-1.1", + "funding": { + "url": "https://github.com/sponsors/ayuhito" + } + }, + "node_modules/@iconify-json/material-symbols": { + "version": "1.2.98", + "resolved": "https://registry.npmjs.org/@iconify-json/material-symbols/-/material-symbols-1.2.98.tgz", + "integrity": "sha512-ycgn080/EGstyYcJFu+HN0TYI+ts/KFPb+An0dzpwZit4M/BoFO9U54BwBmrS2Qo/3g9NYV4Y/g1BT425tNgEw==", + "license": "Apache-2.0", + "dependencies": { + "@iconify/types": "*" + } + }, + "node_modules/@iconify/types": { + "version": "2.0.0", + "resolved": "https://registry.npmjs.org/@iconify/types/-/types-2.0.0.tgz", + "integrity": "sha512-+wluvCrRhXrhyOmRDJ3q8mux9JkKy5SJ/v8ol2tu4FVjyYvtEzkc/3pK15ET6RKg4b4w4BmTk1+gsCUhf21Ykg==", + "license": "MIT" + }, "node_modules/@img/colour": { "version": "1.1.0", "resolved": "https://registry.npmjs.org/@img/colour/-/colour-1.1.0.tgz", diff --git a/package.json b/package.json index cca377d..46f2295 100644 --- a/package.json +++ b/package.json @@ -13,12 +13,18 @@ "dev": "node tools/sync.ts && astro dev", "build": "node tools/sync.ts && astro build", "preview": "astro preview", + "serve": "node tools/serve.ts", "brand": "node tools/build-brand.ts", "test": "node --test \"tools/**/*.test.ts\"", - "typecheck": "astro sync && tsc --noEmit" + "typecheck": "astro sync && tsc --noEmit", + "icons": "node tools/check-icons.ts" }, "dependencies": { "@astrojs/starlight": "^0.42.10", + "@fontsource/ibm-plex-mono": "^5.3.0", + "@fontsource/ibm-plex-sans": "^5.3.0", + "@fontsource/space-grotesk": "^5.3.0", + "@iconify-json/material-symbols": "^1.2.98", "astro": "^7.4.10", "yaml": "^2.8.0" }, diff --git a/roadmap.json b/roadmap.json new file mode 100644 index 0000000..eb22e36 --- /dev/null +++ b/roadmap.json @@ -0,0 +1,42 @@ +[ + { + "component": "tool_openapi", "repo": "didactika/moodle-tool_openapi", + "title": {"en": "OpenAPI", "es": "OpenAPI"}, + "summary": {"en": "Publishes the web service catalog of the site as an OpenAPI 3.1 document, with a bundled Swagger UI viewer and four independent ways to control who may read it.", "es": "Publica el catálogo de servicios web del sitio como un documento OpenAPI 3.1, con un visor Swagger UI incluido y cuatro formas independientes de controlar quién puede leerlo."} + }, + { + "component": "local_servicemanager", "repo": "didactika/moodle-local_servicemanager", + "title": {"en": "Service manager", "es": "Gestor de servicios"}, + "summary": {"en": "Provisions and manages web services from version-controlled YAML schemas: it creates the service user, role, capabilities, external service and token.", "es": "Aprovisiona y gestiona servicios web a partir de esquemas YAML versionados: crea el usuario del servicio, el rol, las capacidades, el servicio externo y el token."} + }, + { + "component": "local_iconrestyle", "repo": "didactika/moodle-local_iconrestyle", + "title": {"en": "Icon restyle", "es": "Estilo de iconos"}, + "summary": {"en": "Restyles the icons of the whole site, a category, a course or an activity from one visual designer, with no theme changes and no code.", "es": "Cambia el estilo de los iconos de todo el sitio, de una categoría, un curso o una actividad desde un único diseñador visual, sin tocar el tema ni escribir código."} + }, + { + "component": "local_autograder", "repo": "didactika/moodle-local_autograder", + "title": {"en": "Autograder", "es": "Autocalificador"}, + "summary": {"en": "Automatically grades the completed activities that a teacher has not graded after the deadline.", "es": "Califica automáticamente las actividades completadas que el docente no ha calificado pasada la fecha límite."} + }, + { + "component": "report_autograder", "repo": "didactika/moodle-report_autograder", + "title": {"en": "Autograder report", "es": "Informe del autocalificador"}, + "summary": {"en": "Reviews what the Autograder graded, what is pending and what failed, per activity, course or site.", "es": "Revisa lo que calificó el Autocalificador, lo que está pendiente y lo que falló, por actividad, curso o sitio."} + }, + { + "component": "local_filebank", "repo": "didactika/moodle-local_filebank", + "title": {"en": "FileBank", "es": "FileBank"}, + "summary": {"en": "Organises the public files of related courses into a reusable library, with profiles that say which courses belong together.", "es": "Organiza los archivos públicos de cursos relacionados en una biblioteca reutilizable, con perfiles que indican qué cursos van juntos."} + }, + { + "component": "repository_filebank", "repo": "didactika/moodle-repository_filebank", + "title": {"en": "FileBank repository", "es": "Repositorio FileBank"}, + "summary": {"en": "Offers the FileBank library inside the file picker, so teachers can pick files and whole folders from related courses.", "es": "Ofrece la biblioteca de FileBank dentro del selector de archivos, para que los docentes elijan archivos y carpetas enteras de cursos relacionados."} + }, + { + "component": "repository_multipicker", "repo": "didactika/moodle-repository_multipicker", + "title": {"en": "Multi-picker", "es": "Selector múltiple"}, + "summary": {"en": "Adds multiple selection of files and folders, with a review before the import, to the Server files repository.", "es": "Añade la selección múltiple de archivos y carpetas, con una revisión antes de importar, al repositorio de archivos del servidor."} + } +] diff --git a/src/components/DirectoryChip.astro b/src/components/DirectoryChip.astro new file mode 100644 index 0000000..277bb2b --- /dev/null +++ b/src/components/DirectoryChip.astro @@ -0,0 +1,29 @@ +--- +/** Says whether a plugin is in the Moodle plugins directory, from what the directory itself answers (see tools/lib/directory.ts). */ +import MIcon from './MIcon.astro'; +import {t, type DirectoryData} from '../lib/site'; + +interface Props { + lang: string; + directory: DirectoryData; +} + +const {lang, directory} = Astro.props; +--- + +{ + directory.published === true && ( + `Moodle ${entry.branch}: ${entry.release}`).join(' · ')}> + + {t(lang, 'published')} + + ) +} +{ + directory.published === false && ( + + + {t(lang, 'githubOnly')} + + ) +} diff --git a/src/components/Feature.astro b/src/components/Feature.astro new file mode 100644 index 0000000..f2d0bfa --- /dev/null +++ b/src/components/Feature.astro @@ -0,0 +1,29 @@ +--- +/** + * A card of a feature or of a path through the documentation, with a Material icon. Use it inside a FeatureGrid in a page (`.mdx`): + * + * + * A start, an end and revocation. + * Your first delegation. + * + * + * With `href` the whole card is a link, and `page:` points at another page of the product in the version the reader is in. + */ +import MIcon from './MIcon.astro'; + +interface Props { + icon: string; + title: string; + href?: string; +} + +const {icon, title, href} = Astro.props; +const Tag = href ? 'a' : 'div'; +--- + + + +

{title}

+

+ {href && } +
diff --git a/src/components/FeatureGrid.astro b/src/components/FeatureGrid.astro new file mode 100644 index 0000000..2932351 --- /dev/null +++ b/src/components/FeatureGrid.astro @@ -0,0 +1,11 @@ +--- +/** The grid that holds the Feature cards of a page. */ +interface Props { + /** How many columns at most; the cards wrap on a narrow screen. */ + columns?: 2 | 3 | 4; +} + +const {columns = 3} = Astro.props; +--- + +
diff --git a/src/components/Footer.astro b/src/components/Footer.astro new file mode 100644 index 0000000..75fbbae --- /dev/null +++ b/src/components/Footer.astro @@ -0,0 +1,46 @@ +--- +/** + * The foot of a page of the documentation: the previous and next pages as cards, the link to edit the page and the licence. + * The pages follow the navigation of the version (see Sidebar.astro). + */ +import MIcon from './MIcon.astro'; +import {t} from '../lib/site'; + +const route = Astro.locals.starlightRoute; +const lang = route.lang; +const {prev, next} = route.pagination; +const editUrl = route.editUrl; +--- + + diff --git a/src/components/Header.astro b/src/components/Header.astro new file mode 100644 index 0000000..8a2129c --- /dev/null +++ b/src/components/Header.astro @@ -0,0 +1,11 @@ +--- +// Replaces the header of Starlight with the one of Didactika (see SiteHeader.astro). +import {pageIdOf} from '../lib/site'; +import SiteHeader from './SiteHeader.astro'; + +const route = Astro.locals.starlightRoute; +const data = route.entry.data as {product?: string; line?: string}; +const pageId = data.product && data.line ? pageIdOf(route.id, data.product, data.line) : undefined; +--- + + diff --git a/src/components/MIcon.astro b/src/components/MIcon.astro new file mode 100644 index 0000000..b47ecd9 --- /dev/null +++ b/src/components/MIcon.astro @@ -0,0 +1,35 @@ +--- +/** + * An icon of Material Symbols (the rounded set), drawn inline so it takes the colour and the size of the text around it. + * Use the name as Iconify spells it, e.g. `shield-person-rounded`; every icon of the site is looked up here, and one that does not + * exist stops the build instead of leaving a hole in a page. + */ +import set from '@iconify-json/material-symbols/icons.json'; + +interface Props { + name: string; + /** A text for people who cannot see the icon. Without it the icon is decoration and is hidden from them. */ + label?: string; + class?: string; +} + +const {name, label, class: className} = Astro.props; +const icons = set.icons as Record; +const aliases = (set as {aliases?: Record}).aliases ?? {}; +const icon = icons[name] ?? icons[aliases[name]?.parent ?? '']; +if (!icon) { + throw new Error(`The Material icon "${name}" does not exist.`); +} +const size = icon.width ?? set.width ?? 24; +--- + + diff --git a/src/components/PageTitle.astro b/src/components/PageTitle.astro new file mode 100644 index 0000000..ba66fb5 --- /dev/null +++ b/src/components/PageTitle.astro @@ -0,0 +1,121 @@ +--- +/** + * The head of a page of the documentation: where the page is (product, section), the title and the lead, and what is worth knowing about it + * in the version the reader is in. The first page of a product also shows what the product is. + */ +import DirectoryChip from './DirectoryChip.astro'; +import MIcon from './MIcon.astro'; +import {localised, pageIdOf, productUrl, site, t} from '../lib/site'; + +const route = Astro.locals.starlightRoute; +const data = route.entry.data as {title: string; description?: string; product?: string; line?: string; provenance?: string; provenanceFrom?: string}; +const lang = route.lang; +const product = site().products.find((candidate) => candidate.slug === data.product); +const line = product?.lines.find((candidate) => candidate.id === data.line); + +const pageId = product && line ? pageIdOf(route.id, product.slug, line.id) : undefined; +const section = pageId?.includes('/') ? pageId.split('/')[0] : undefined; +const isHome = pageId === 'index'; +const lineLabel = (id?: string): string => product?.lines.find((candidate) => candidate.id === id)?.label ?? id ?? ''; +const compared = product !== undefined && product.lines.length > 1; +const kindLabel = product?.kind === 'plugin' ? t(lang, 'plugins') : t(lang, 'packages'); +--- + +
+ { + product && line && ( + <> +
diff --git a/src/components/ProductCard.astro b/src/components/ProductCard.astro new file mode 100644 index 0000000..6ee51ca --- /dev/null +++ b/src/components/ProductCard.astro @@ -0,0 +1,79 @@ +--- +/** A product as a card: its icon, name, summary, the versions and languages it is documented in, and whether it is in the Moodle directory. */ +import DirectoryChip from './DirectoryChip.astro'; +import MIcon from './MIcon.astro'; +import {localised, productUrl, site, t, type ProductData} from '../lib/site'; + +interface Soon { + component: string; + repo: string; + title: Record; + summary: Record; + published: boolean | null; +} + +interface Props { + lang: string; + product?: ProductData; + /** A product that is not documented yet. */ + soon?: Soon; +} + +const {lang, product, soon} = Astro.props; +const title = localised((product ?? soon!).title, lang); +const summary = localised((product ?? soon!).summary, lang); +const href = product ? productUrl(lang, product) : undefined; +const Tag = href ? 'a' : 'div'; +const code = product ? (product.component ?? product.slug) : soon!.component; +const languages = site().languages.map((language) => language.code); +--- + + +
+ + {product?.icon ? : } + +
+

{title}

+ {code} +
+
+

{summary}

+ { + product && ( + <> +
+ {t(lang, 'versions')} + {[...product.lines].reverse().map((line) => ( + {line.label} + ))} +
+
+ {t(lang, 'languages')} + {languages.map((code) => ( + + + {code.toUpperCase()} + + ))} + +
+
+ {t(lang, 'openDocs')} + +
+ + ) + } + { + soon && ( +
+ + + {t(lang, 'comingTitle')} + + +
+ ) + } +
diff --git a/src/components/Screenshot.astro b/src/components/Screenshot.astro new file mode 100644 index 0000000..92ede5d --- /dev/null +++ b/src/components/Screenshot.astro @@ -0,0 +1,23 @@ +--- +/** + * A screen of the plugin in a window, with an optional address and caption. Use it in a page of the documentation (`.mdx`): + * + * + * + * `asset:` is the file in the `_assets` folder of the documentation, in the version the reader is in. + */ +interface Props { + src: string; + alt: string; + caption?: string; + url?: string; +} + +const {src, alt, caption, url} = Astro.props; +--- + +
+
{url && {url}}
+ {alt} + {caption &&
{caption}
} +
diff --git a/src/components/Sidebar.astro b/src/components/Sidebar.astro new file mode 100644 index 0000000..2db22e6 --- /dev/null +++ b/src/components/Sidebar.astro @@ -0,0 +1,45 @@ +--- +/** + * The navigation of a page of a product shows only that product, in the version the reader is in: its overview and its sections. The + * previous and next pages follow the same list, so a reader never ends up in another version by turning the page. + */ +import Default from '@astrojs/starlight/components/Sidebar.astro'; +import {productUrl, site} from '../lib/site'; + +const route = Astro.locals.starlightRoute; +const data = route.entry.data as {product?: string; line?: string}; +const product = site().products.find((candidate) => candidate.slug === data.product); + +type Entry = (typeof route.sidebar)[number]; + +/** The entries of the group that holds the overview of the version: that group is the navigation of the version. */ +function groupOf(entries: Entry[], overview: string): Entry[] | undefined { + for (const entry of entries) { + if (entry.type !== 'group') { + continue; + } + if (entry.entries.some((child) => child.type === 'link' && child.href === overview)) { + return entry.entries; + } + const inner = groupOf(entry.entries, overview); + if (inner) { + return inner; + } + } + return undefined; +} + +const links = (entries: Entry[]): Array> => entries.flatMap((entry) => (entry.type === 'link' ? [entry] : links(entry.entries))); + +if (product && data.line) { + const own = groupOf(route.sidebar, productUrl(route.lang, product, data.line)); + if (own) { + route.sidebar = own; + const all = links(own); + const here = all.findIndex((link) => link.isCurrent); + route.pagination = {prev: here > 0 ? all[here - 1] : undefined, next: here >= 0 ? all[here + 1] : undefined}; + } +} +--- + + diff --git a/src/components/SiteFooter.astro b/src/components/SiteFooter.astro new file mode 100644 index 0000000..5592b2b --- /dev/null +++ b/src/components/SiteFooter.astro @@ -0,0 +1,46 @@ +--- +// The foot of the home and of the catalog. +import MIcon from './MIcon.astro'; +import {localised, productUrl, site, t} from '../lib/site'; + +interface Props { + lang: string; +} + +const {lang} = Astro.props; +const products = site().products; +--- + + diff --git a/src/components/SiteHeader.astro b/src/components/SiteHeader.astro new file mode 100644 index 0000000..493782b --- /dev/null +++ b/src/components/SiteHeader.astro @@ -0,0 +1,100 @@ +--- +/** + * The header of the site, the same on the home, on the catalog and on every page of the documentation: the mark of Didactika, the product + * and version the reader is in, the search, the language, the colour theme and the repository of the organisation. + */ +import MIcon from './MIcon.astro'; +import SiteSearch from './SiteSearch.astro'; +import {localised, productUrl, site, t} from '../lib/site'; + +interface Props { + lang: string; + /** The address of the page, to offer the same page in another language. */ + path: string; + productSlug?: string; + /** The version of the page. */ + line?: string; + /** The page inside its version (`guides/install`, or `index`), to offer the same page in another version. */ + pageId?: string; +} + +const {lang, path, productSlug, line, pageId} = Astro.props; +const data = site(); +const product = data.products.find((candidate) => candidate.slug === productSlug); +const current = product?.lines.find((candidate) => candidate.id === line); + +/** The same page in another language: the first segment of the address is the language. */ +const inLanguage = (code: string): string => path.replace(/^\/[^/]+/, `/${code}`); + +/** The same page in another version when it exists there, and the overview of that version when it does not. */ +const inVersion = (id: string): string => { + const target = product!.lines.find((candidate) => candidate.id === id)!; + const exists = !pageId || pageId === 'index' || target.pageIds.includes(pageId); + return productUrl(lang, product!, id) + (exists && pageId && pageId !== 'index' ? `${pageId}/` : ''); +}; + +const logo = '/brand/didactika-logo.png'; +--- + +
+ + + Didactika Docs{t(lang, 'brandBy')} + + +
+ { + product && ( + + + {localised(product.title, lang)} + + ) + } + { + product && current && ( +
+ + + {current.label} + + +
+ {[...product.lines].reverse().map((candidate) => ( + + {candidate.label} + {candidate.latest ? t(lang, 'latest') : candidate.release} + + ))} +
+
+ ) + } +
+ +
+ + + + + + +
+
+ + diff --git a/src/components/SiteSearch.astro b/src/components/SiteSearch.astro new file mode 100644 index 0000000..9b79e07 --- /dev/null +++ b/src/components/SiteSearch.astro @@ -0,0 +1,134 @@ +--- +/** + * The search of the site: a button that looks like the one of the design system and a dialog with the results of Pagefind, which Starlight + * indexes when the site is built. It only searches the version the reader is in (or the newest, outside a product) so a page that two + * versions share does not come up twice. + */ +import MIcon from './MIcon.astro'; +import {t} from '../lib/site'; + +interface Props { + lang: string; + /** The version of the page, when it is not the newest: the search is limited to it. */ + line?: string; +} + +const {lang, line} = Astro.props; +--- + + + + +
+ + + +
+

{t(lang, 'searchHint')}

+
+ + diff --git a/src/content/docs/en/index.mdx b/src/content/docs/en/index.mdx deleted file mode 100644 index 3a9654c..0000000 --- a/src/content/docs/en/index.mdx +++ /dev/null @@ -1,11 +0,0 @@ ---- -title: Didactika Docs -description: The documentation of the Moodle plugins and the npm packages of Didactika. -template: splash -hero: - tagline: The documentation of the Moodle plugins and the npm packages of Didactika, by version and language. - actions: - - text: Plugins - link: /en/plugins/ - icon: right-arrow ---- diff --git a/src/content/docs/es/index.mdx b/src/content/docs/es/index.mdx deleted file mode 100644 index afae317..0000000 --- a/src/content/docs/es/index.mdx +++ /dev/null @@ -1,11 +0,0 @@ ---- -title: Documentación de Didactika -description: La documentación de los plugins de Moodle y de los paquetes npm de Didactika. -template: splash -hero: - tagline: La documentación de los plugins de Moodle y de los paquetes npm de Didactika, por versión y por idioma. - actions: - - text: Plugins - link: /es/plugins/ - icon: right-arrow ---- diff --git a/src/i18n/en.json b/src/i18n/en.json index 56a8c96..9fe4096 100644 --- a/src/i18n/en.json +++ b/src/i18n/en.json @@ -9,6 +9,83 @@ "translationOutdated": "The {language} version of this page is older than the English one, so the English version is shown.", "overview": "Overview", "section.getting-started": "Getting started", + "section.concepts": "Concepts", "section.guides": "Guides", - "section.reference": "Reference" + "section.reference": "Reference", + + "brandBy": "by Didactika", + "home": "Home", + "search": "Find a page", + "searchLabel": "Search the documentation", + "searchPlaceholder": "Search guides, concepts and reference…", + "searchEmpty": "Nothing found for “{q}”.", + "searchHint": "Type at least two letters.", + "searchBuilt": "Search works in the built site.", + "close": "Close", + "language": "Language", + "theme": "Colour theme", + "themeLight": "Light", + "themeDark": "Dark", + "themeAuto": "Automatic", + "version": "Version", + "latest": "Latest", + "menu": "Menu", + "github": "GitHub", + "designSystem": "Design system", + + "heroEyebrow": "Open source · GPL-3.0", + "heroTitleA": "Documentation for every", + "heroTitleB": "Didactika plugin", + "heroLead": "Guides, concepts and reference for the Moodle plugins and the npm packages of Didactika, for each version and in your language.", + "heroCta": "Explore the plugins", + "heroCtaSecondary": "How it is organised", + "statProducts": "Documented products", + "statVersions": "Versions", + "statLanguages": "Languages", + "statPages": "Pages", + "productsTitle": "Documented products", + "productsLead": "Pick a product to read how to install it, use it and integrate it.", + "published": "In the Moodle directory", + "githubOnly": "GitHub only", + "versions": "Versions", + "languages": "Languages", + "openDocs": "Open the documentation", + "comingTitle": "Coming next", + "comingLead": "The plugins below are documented next, in this order.", + "organisedTitle": "How the documentation is organised", + "organisedLead": "Every product follows the same structure, so what you learn in one place works in all of them.", + "orgStartTitle": "Getting started", + "orgStartText": "Install the plugin, give people the permission it needs and complete a first task in minutes.", + "orgConceptsTitle": "Concepts", + "orgConceptsText": "Why it works the way it does: the model, the lifecycle and the limits, without the clicks.", + "orgGuidesTitle": "Guides", + "orgGuidesText": "One task per page, with the screens you will see and the result you should get.", + "orgReferenceTitle": "Reference", + "orgReferenceText": "Every setting, capability, event and web-service function, exactly as the plugin defines it.", + "versionsTitle": "Pick the version you run", + "versionsText": "Each plugin has one documentation for every line of Moodle it supports. A newer line keeps what it shares with the older one and changes only what differs, and the version selector of the header moves you between them.", + "languagesTitle": "In your language", + "languagesText": "English and Spanish are complete for every page. More languages can be added without touching the site.", + "browseAll": "Browse all {kind}", + "noProducts": "There are no products here yet.", + + "inheritedFrom": "Inherited from {line}", + "addedIn": "New in {line}", + "changedIn": "Changed in {line}", + "inThisVersion": "In this version", + "onThisPage": "On this page", + "editPage": "Edit this page", + "previous": "Previous", + "next": "Next", + "notInVersion": "This page does not exist in {line}. You were taken to its overview.", + "footerLicence": "Documentation under GPL-3.0-or-later, as Moodle.", + "footerSource": "Source of this site", + "footerProducts": "Products", + "footerOrg": "Didactika", + "footerDesign": "Design system", + "footerOrgLink": "Organisation on GitHub", + "release": "Release", + "requires": "Moodle", + "directoryOpen": "View in the Moodle directory", + "repository": "Repository" } diff --git a/src/i18n/es.json b/src/i18n/es.json index 4f39e73..94fb10d 100644 --- a/src/i18n/es.json +++ b/src/i18n/es.json @@ -9,6 +9,83 @@ "translationOutdated": "La versión en {language} de esta página es anterior a la inglesa, así que se muestra la versión en inglés.", "overview": "Visión general", "section.getting-started": "Primeros pasos", + "section.concepts": "Conceptos", "section.guides": "Guías", - "section.reference": "Referencia" + "section.reference": "Referencia", + + "brandBy": "de Didactika", + "home": "Inicio", + "search": "Buscar una página", + "searchLabel": "Buscar en la documentación", + "searchPlaceholder": "Busca guías, conceptos y referencia…", + "searchEmpty": "No se ha encontrado nada para «{q}».", + "searchHint": "Escribe al menos dos letras.", + "searchBuilt": "La búsqueda funciona en el sitio ya construido.", + "close": "Cerrar", + "language": "Idioma", + "theme": "Tema de color", + "themeLight": "Claro", + "themeDark": "Oscuro", + "themeAuto": "Automático", + "version": "Versión", + "latest": "Última", + "menu": "Menú", + "github": "GitHub", + "designSystem": "Sistema de diseño", + + "heroEyebrow": "Código abierto · GPL-3.0", + "heroTitleA": "La documentación de cada", + "heroTitleB": "plugin de Didactika", + "heroLead": "Guías, conceptos y referencia de los plugins de Moodle y de los paquetes npm de Didactika, para cada versión y en tu idioma.", + "heroCta": "Explorar los plugins", + "heroCtaSecondary": "Cómo está organizada", + "statProducts": "Productos documentados", + "statVersions": "Versiones", + "statLanguages": "Idiomas", + "statPages": "Páginas", + "productsTitle": "Productos documentados", + "productsLead": "Elige un producto para ver cómo instalarlo, usarlo e integrarlo.", + "published": "En el directorio de Moodle", + "githubOnly": "Solo en GitHub", + "versions": "Versiones", + "languages": "Idiomas", + "openDocs": "Abrir la documentación", + "comingTitle": "Próximamente", + "comingLead": "Los plugins siguientes se documentan a continuación, en este orden.", + "organisedTitle": "Cómo está organizada la documentación", + "organisedLead": "Todos los productos siguen la misma estructura, así que lo que aprendes en uno sirve en todos.", + "orgStartTitle": "Primeros pasos", + "orgStartText": "Instala el plugin, da a las personas el permiso que necesita y completa una primera tarea en minutos.", + "orgConceptsTitle": "Conceptos", + "orgConceptsText": "Por qué funciona como funciona: el modelo, el ciclo de vida y los límites, sin los clics.", + "orgGuidesTitle": "Guías", + "orgGuidesText": "Una tarea por página, con las pantallas que verás y el resultado que debes obtener.", + "orgReferenceTitle": "Referencia", + "orgReferenceText": "Cada ajuste, capacidad, evento y función del servicio web, tal como los define el plugin.", + "versionsTitle": "Elige la versión que usas", + "versionsText": "Cada plugin tiene una documentación para cada línea de Moodle que soporta. Una línea más nueva conserva lo que comparte con la anterior y cambia solo lo que difiere, y el selector de versión de la cabecera te mueve entre ellas.", + "languagesTitle": "En tu idioma", + "languagesText": "El inglés y el español están completos en todas las páginas. Se pueden añadir más idiomas sin tocar el sitio.", + "browseAll": "Ver todos los {kind}", + "noProducts": "Todavía no hay productos aquí.", + + "inheritedFrom": "Heredada de {line}", + "addedIn": "Nueva en {line}", + "changedIn": "Modificada en {line}", + "inThisVersion": "En esta versión", + "onThisPage": "En esta página", + "editPage": "Editar esta página", + "previous": "Anterior", + "next": "Siguiente", + "notInVersion": "Esta página no existe en {line}. Te hemos llevado a su visión general.", + "footerLicence": "Documentación bajo GPL-3.0-or-later, como Moodle.", + "footerSource": "Código de este sitio", + "footerProducts": "Productos", + "footerOrg": "Didactika", + "footerDesign": "Sistema de diseño", + "footerOrgLink": "La organización en GitHub", + "release": "Versión publicada", + "requires": "Moodle", + "directoryOpen": "Ver en el directorio de Moodle", + "repository": "Repositorio" } diff --git a/src/layouts/Landing.astro b/src/layouts/Landing.astro new file mode 100644 index 0000000..7798805 --- /dev/null +++ b/src/layouts/Landing.astro @@ -0,0 +1,55 @@ +--- +/** + * The layout of the pages that are not documentation (the home and the catalog): the same header, colours and fonts as the documentation, + * without the navigation of a product. + */ +import '../styles/didactika.css'; +import SiteFooter from '../components/SiteFooter.astro'; +import SiteHeader from '../components/SiteHeader.astro'; +import {site, t} from '../lib/site'; + +interface Props { + lang: string; + title: string; + description: string; +} + +const {lang, title, description} = Astro.props; +const language = site().languages.find((candidate) => candidate.code === lang); +--- + + + + + + + {title} + + + + + + + + {site().languages.map((candidate) => )} + + + +
+ {t(lang, 'home')} +
+
+ +
+ + diff --git a/src/lib/site.ts b/src/lib/site.ts new file mode 100644 index 0000000..2fd869c --- /dev/null +++ b/src/lib/site.ts @@ -0,0 +1,102 @@ +/** + * What every component of the site needs to know about the products and the languages, read once from what tools/sync.ts wrote. + * + * It reads the file with fs and not with an import, because the file is generated: it does not exist when the types are checked. + */ + +import {existsSync, readFileSync} from 'node:fs'; +import {join} from 'node:path'; + +export interface LineData { + id: string; + label: string; + branch: string; + release: string; + extends: string | null; + latest: boolean; + coverage: Record; + pages: number; + sections: string[]; + /** Page ids of the version, to link a page to the same page of another version only when it exists there. */ + pageIds: string[]; +} + +export interface DirectoryData { + published: boolean | null; + url: string | null; + /** The release the directory offers for a branch of Moodle, as `{branch: '5.3', release: '1.1.0-m503'}`. */ + releases: Array<{branch: string; release: string}>; +} + +export interface ProductData { + slug: string; + kind: 'plugin' | 'package'; + repo: string; + component: string | null; + title: Record; + summary: Record; + /** Address of the icon of the product, or null when it has none. */ + icon: string | null; + directory: DirectoryData; + lines: LineData[]; +} + +export interface LanguageData { + code: string; + name: string; + dir: 'ltr' | 'rtl'; +} + +/** A product that is not documented yet, from roadmap.json, with what the Moodle directory says about it. */ +export interface SoonData { + component: string; + repo: string; + title: Record; + summary: Record; + published: boolean | null; +} + +export interface SiteData { + languages: LanguageData[]; + products: ProductData[]; + coming: SoonData[]; +} + +const file = join(process.cwd(), 'src', 'data', 'products.generated.json'); + +let cached: SiteData | undefined; + +export function site(): SiteData { + cached ??= existsSync(file) ? (JSON.parse(readFileSync(file, 'utf8')) as SiteData) : {languages: [], products: [], coming: []}; + return cached; +} + +const dictionaries = import.meta.glob>('../i18n/*.json', {eager: true, import: 'default'}); + +const dictionary = (code: string): Record => dictionaries[`../i18n/${code}.json`] ?? {}; + +/** A text of the interface in a language; what that language lacks is taken from English. */ +export function t(lang: string, key: string, values: Record = {}): string { + const text = dictionary(lang)[key] ?? dictionary('en')[key] ?? key; + return text.replace(/\{(\w+)\}/g, (_, name: string) => values[name] ?? ''); +} + +/** A text of a product (title, summary) in a language, or in English when it has none in that language. */ +export const localised = (texts: Record, lang: string): string => texts[lang] ?? texts.en ?? ''; + +/** + * The page inside its version (`guides/install`, or `index`), from the identifier Starlight gives the page: `en/plugins///guides/install`, + * or the same without the line for the address without a version. + */ +export function pageIdOf(routeId: string, slug: string, line?: string): string { + const withoutLanguage = routeId.replace(/^[a-z]{2,3}(?:-[A-Za-z0-9]+)?\//, ''); + return withoutLanguage.replace(new RegExp(`^(?:plugins|packages)/${slug}(?:/${line ?? ''})?(?:/|$)`), '') || 'index'; +} + +export const productsOf =(kind: ProductData['kind']): ProductData[] => site().products.filter((product) => product.kind === kind); + +export const latestLine = (product: ProductData): LineData => product.lines.find((line) => line.latest) ?? product.lines[product.lines.length - 1]; + +/** The address of a product in a language, and in one version of it when a line is given. */ +export const productUrl = (lang: string, product: ProductData, line?: string): string => + `/${lang}/${product.kind === 'plugin' ? 'plugins' : 'packages'}/${product.slug}/${line ? `${line}/` : ''}`; diff --git a/src/pages/[lang]/index.astro b/src/pages/[lang]/index.astro new file mode 100644 index 0000000..c9c9713 --- /dev/null +++ b/src/pages/[lang]/index.astro @@ -0,0 +1,144 @@ +--- +/** The home of the portal: what it is, what is documented and how every documentation is organised. */ +import MIcon from '../../components/MIcon.astro'; +import ProductCard from '../../components/ProductCard.astro'; +import DirectoryChip from '../../components/DirectoryChip.astro'; +import Landing from '../../layouts/Landing.astro'; +import {latestLine, localised, productUrl, site, t} from '../../lib/site'; + +export function getStaticPaths() { + return site().languages.map((language) => ({params: {lang: language.code}})); +} + +const {lang} = Astro.params as {lang: string}; +const data = site(); +const featured = data.products[0]; +const stats = { + products: data.products.length, + versions: data.products.reduce((sum, product) => sum + product.lines.length, 0), + languages: data.languages.length, + pages: data.products.reduce((sum, product) => sum + product.lines.reduce((total, line) => total + line.pages, 0), 0) * data.languages.length, +}; + +const organised = [ + {icon: 'rocket-launch-rounded', title: 'orgStartTitle', text: 'orgStartText'}, + {icon: 'lightbulb-rounded', title: 'orgConceptsTitle', text: 'orgConceptsText'}, + {icon: 'task-alt-rounded', title: 'orgGuidesTitle', text: 'orgGuidesText'}, + {icon: 'menu-book-rounded', title: 'orgReferenceTitle', text: 'orgReferenceText'}, +]; +--- + + +
+
+
+ {t(lang, 'heroEyebrow')} +

{t(lang, 'heroTitleA')} {t(lang, 'heroTitleB')}

+

{t(lang, 'heroLead')}

+ +
+ +
+
+ +
+
+
{stats.products}{t(lang, 'statProducts')}
+
{stats.versions}{t(lang, 'statVersions')}
+
{stats.languages}{t(lang, 'statLanguages')}
+
{stats.pages}{t(lang, 'statPages')}
+
+
+ +
+
+

{t(lang, 'productsTitle')}

+

{t(lang, 'productsLead')}

+
+ {data.products.map((product) => )} +
+
+
+ + { + data.coming.length > 0 && ( +
+
+

{t(lang, 'comingTitle')}

+

{t(lang, 'comingLead')}

+
+ {data.coming.map((soon) => )} +
+
+
+ ) + } + +
+
+

{t(lang, 'organisedTitle')}

+

{t(lang, 'organisedLead')}

+
+ { + organised.map((card) => ( +
+ +

{t(lang, card.title)}

+

{t(lang, card.text)}

+
+ )) + } +
+
+
+ +
+
+
+

{t(lang, 'versionsTitle')}

+

{t(lang, 'versionsText')}

+ { + featured && ( +
+ {[...featured.lines].reverse().map((line) => ( + + + {line.label} + {line.release} + + ))} +
+ ) + } +
+
+

{t(lang, 'languagesTitle')}

+

{t(lang, 'languagesText')}

+
+ {data.languages.map((language) => ( + + + {language.name} + {language.code.toUpperCase()} + + ))} +
+
+
+
+
diff --git a/src/pages/[lang]/plugins/index.astro b/src/pages/[lang]/plugins/index.astro new file mode 100644 index 0000000..bb93a85 --- /dev/null +++ b/src/pages/[lang]/plugins/index.astro @@ -0,0 +1,32 @@ +--- +/** The catalog of the plugins of Didactika. */ +import MIcon from '../../../components/MIcon.astro'; +import ProductCard from '../../../components/ProductCard.astro'; +import Landing from '../../../layouts/Landing.astro'; +import {productsOf, site, t} from '../../../lib/site'; + +export function getStaticPaths() { + return site().languages.map((language) => ({params: {lang: language.code}})); +} + +const {lang} = Astro.params as {lang: string}; +const plugins = productsOf('plugin'); +--- + + +
+
+ +

{t(lang, 'plugins')}

+

{t(lang, 'pluginsDescription')} {t(lang, 'productsLead')}

+
+ {plugins.map((product) => )} + {site().coming.map((soon) => )} +
+
+
+
diff --git a/src/pages/index.astro b/src/pages/index.astro new file mode 100644 index 0000000..0ed7fb1 --- /dev/null +++ b/src/pages/index.astro @@ -0,0 +1,21 @@ +--- +// The address without a language: the reader goes to the language of the browser if the site has it, and to English if not. +import {site} from '../lib/site'; + +const codes = site().languages.map((language) => language.code); +--- + + + + + + Didactika Docs + + + + + + diff --git a/src/styles/didactika.css b/src/styles/didactika.css index b7c2edc..893c582 100644 --- a/src/styles/didactika.css +++ b/src/styles/didactika.css @@ -1,22 +1,456 @@ /* - * The colours of Didactika, from the design system (moodle-design-system, src/data/brand.json), in the variables Starlight reads. - * Light mode takes the primary teal for accents; dark mode takes a lighter teal so the contrast holds. + * The look of Didactika, taken from the design system (moodle-design-system, src/styles/site.css): the same palette on a cool slate and on + * the dark teal, IBM Plex Sans for text, Space Grotesk for titles and IBM Plex Mono for the small labels, with the icons of Material Symbols. + * Starlight draws the structure of a page; this file gives it the look, and the components of src/components give it the header, the + * title of a page, the footer and the home. */ + +@import '@fontsource/ibm-plex-sans/latin-400.css'; +@import '@fontsource/ibm-plex-sans/latin-500.css'; +@import '@fontsource/ibm-plex-sans/latin-600.css'; +@import '@fontsource/ibm-plex-sans/latin-700.css'; +@import '@fontsource/ibm-plex-mono/latin-400.css'; +@import '@fontsource/ibm-plex-mono/latin-500.css'; +@import '@fontsource/space-grotesk/latin-500.css'; +@import '@fontsource/space-grotesk/latin-600.css'; +@import '@fontsource/space-grotesk/latin-700.css'; + +/* ---------------------------------------------------------------- tokens ---- */ + :root { - --sl-font: 'Noto Sans', system-ui, -apple-system, 'Segoe UI', Roboto, sans-serif; + --bg: #f8fafc; + --panel: #ffffff; + --panel-2: #f1f5f9; + --line: #e2e8f0; + --ink: #0f172a; + --muted: #475569; + --accent: #0f766e; + --accent-ink: #ffffff; + --accent-soft: #e6f6f4; + --accent-strong: #00555a; + --code: #f1f5f9; + --ok: #15803d; + --ok-soft: #e7f5ec; + --no: #b3261e; + --no-soft: #fdecea; + --warn: #8a5a00; + --warn-soft: #fdf3dc; + --shadow: 0 1px 2px rgb(15 23 42 / 6%), 0 8px 24px rgb(15 23 42 / 7%); + --glow: radial-gradient(60% 70% at 70% 20%, rgb(20 184 166 / 18%), transparent 70%), radial-gradient(50% 60% at 10% 0%, rgb(0 85 90 / 10%), transparent 70%); + --dot: #cfd8e3; + --font: 'IBM Plex Sans', 'Segoe UI', system-ui, sans-serif; + --display: 'Space Grotesk', 'IBM Plex Sans', system-ui, sans-serif; + --mono: 'IBM Plex Mono', ui-monospace, SFMono-Regular, Menlo, Consolas, monospace; + --radius: 14px; + --radius-lg: 20px; + --head-h: 3.75rem; +} + +:root[data-theme='dark'] { + --bg: #0a1113; + --panel: #0f191c; + --panel-2: #15222a; + --line: #1f3036; + --ink: #e8f1f2; + --muted: #93a8ad; + --accent: #2dd4bf; + --accent-ink: #042f2e; + --accent-soft: #11302f; + --accent-strong: #5eead4; + --code: #0c1619; + --ok: #6cc584; + --ok-soft: #12301f; + --no: #ff8a80; + --no-soft: #3a1714; + --warn: #e3b25c; + --warn-soft: #33260c; + --shadow: 0 1px 2px rgb(0 0 0 / 40%), 0 8px 28px rgb(0 0 0 / 40%); + --glow: radial-gradient(60% 70% at 70% 20%, rgb(45 212 191 / 14%), transparent 70%), radial-gradient(50% 60% at 10% 0%, rgb(0 85 90 / 30%), transparent 70%); + --dot: #1b2c32; + color-scheme: dark; +} - --sl-color-accent-low: #ccfbf1; - --sl-color-accent: #0f766e; - --sl-color-accent-high: #134e4a; +/* The variables of Starlight, from the tokens above. */ +:root, +:root[data-theme='light'] { + --sl-font: var(--font); + --sl-font-mono: var(--mono); + --sl-color-white: var(--ink); + --sl-color-gray-1: #1e293b; + --sl-color-gray-2: #334155; + --sl-color-gray-3: var(--muted); + --sl-color-gray-4: #64748b; + --sl-color-gray-5: var(--line); + --sl-color-gray-6: var(--panel-2); + --sl-color-gray-7: var(--bg); + --sl-color-black: var(--panel); + --sl-color-accent-low: var(--accent-soft); + --sl-color-accent: var(--accent); + --sl-color-accent-high: var(--accent-strong); + --sl-color-bg: var(--bg); + --sl-color-bg-nav: var(--panel); + --sl-color-bg-sidebar: var(--bg); + --sl-color-bg-inline-code: var(--code); + --sl-color-text: var(--ink); + --sl-color-text-accent: var(--accent); + --sl-color-hairline: var(--line); + --sl-color-hairline-light: var(--line); + --sl-color-hairline-shade: var(--line); + --sl-nav-height: var(--head-h); + --sl-nav-pad-x: 0; + --sl-nav-pad-y: 0; + --sl-sidebar-width: 17.5rem; + --sl-content-width: 46rem; + --sl-text-body: 0.9375rem; + --sl-line-height: 1.65; } :root[data-theme='dark'] { - --sl-color-accent-low: #042f2e; - --sl-color-accent: #2dd4bf; - --sl-color-accent-high: #99f6e4; + --sl-color-gray-1: #dbe7e9; + --sl-color-gray-2: #b5c7cb; + --sl-color-gray-4: #5f767c; +} + +*, *::before, *::after { box-sizing: border-box; } +html, body { margin: 0; } +html { scroll-padding-top: calc(var(--head-h) + 1rem); } +body { background: var(--bg); color: var(--ink); font-family: var(--font); -webkit-font-smoothing: antialiased; } +a { text-underline-offset: 0.2em; } +::selection { background: var(--accent-soft); color: var(--ink); } +:focus-visible { outline: 2px solid var(--accent); outline-offset: 2px; } + +.mi { width: 1.25em; height: 1.25em; flex: none; vertical-align: -0.25em; } + +/* ------------------------------------------------------------------ header ---- */ + +.header { background: var(--panel); border-bottom: 1px solid var(--line); } + +.d-head { + display: flex; align-items: center; gap: 0.75rem; width: 100%; height: 100%; padding-inline: 1rem; +} +.d-brand { display: inline-flex; align-items: center; gap: 0.65rem; color: var(--ink); text-decoration: none; white-space: nowrap; } +.d-brand img { width: 2.2rem; height: 2.2rem; border-radius: 10px; } +.d-brand .d-wordmark { display: grid; line-height: 1.05; } +.d-brand .d-wordmark b { font: 700 1.05rem/1.1 var(--display); letter-spacing: -0.01em; } +.d-brand .d-wordmark small { font: 500 0.72rem/1.2 var(--font); color: var(--accent); } +.d-head-tools { display: flex; align-items: center; gap: 0.5rem; margin-inline-start: auto; } +.d-head-mid { display: flex; align-items: center; gap: 0.6rem; margin-inline-start: 0.5rem; } + +.d-iconbtn { + display: inline-grid; place-items: center; width: 2.25rem; height: 2.25rem; border: 1px solid var(--line); border-radius: 10px; + background: var(--panel); color: var(--muted); cursor: pointer; font-size: 1.1rem; text-decoration: none; +} +.d-iconbtn:hover { color: var(--ink); background: var(--panel-2); } + +.d-seg { display: inline-flex; align-items: center; padding: 3px; gap: 2px; border: 1px solid var(--line); border-radius: 12px; background: var(--panel-2); } +.d-seg a { + display: inline-grid; place-items: center; min-width: 2rem; height: 1.9rem; padding: 0 0.55rem; border-radius: 9px; color: var(--muted); + font: 600 0.75rem/1 var(--font); letter-spacing: 0.02em; text-decoration: none; text-transform: uppercase; +} +.d-seg a:hover { color: var(--ink); } +.d-seg a[aria-current='true'] { background: var(--panel); color: var(--accent); box-shadow: 0 1px 3px rgb(15 23 42 / 18%); } + +.d-theme .d-seg-light, .d-theme .d-seg-dark { display: none; } +:root[data-theme='light'] .d-theme .d-seg-light { display: inline-grid; } +:root[data-theme='dark'] .d-theme .d-seg-dark { display: inline-grid; } + +.d-dd { position: relative; } +.d-dd > summary { + list-style: none; display: inline-flex; align-items: center; gap: 0.5rem; height: 2.25rem; padding: 0 0.75rem; border: 1px solid var(--line); + border-radius: 12px; background: var(--panel); color: var(--ink); font: 600 0.8125rem/1 var(--font); cursor: pointer; white-space: nowrap; +} +.d-dd > summary::-webkit-details-marker { display: none; } +.d-dd > summary:hover { background: var(--panel-2); } +.d-dd > summary .mi:first-child { color: var(--accent); } +.d-dd-menu { + position: absolute; top: calc(100% + 0.4rem); inset-inline-start: 0; z-index: 60; min-width: 15rem; padding: 0.4rem; + border: 1px solid var(--line); border-radius: var(--radius); background: var(--panel); box-shadow: var(--shadow); display: grid; gap: 2px; +} +.d-dd-menu a { + display: flex; align-items: center; justify-content: space-between; gap: 0.75rem; padding: 0.55rem 0.7rem; border-radius: 9px; color: var(--ink); + text-decoration: none; font-size: 0.875rem; +} +.d-dd-menu a:hover { background: var(--panel-2); } +.d-dd-menu a[aria-current='true'] { background: var(--accent-soft); color: var(--accent); font-weight: 600; } +.d-dd-menu small { color: var(--muted); font-size: 0.72rem; } + +.d-search-btn { + display: inline-flex; align-items: center; gap: 0.6rem; min-width: 14rem; height: 2.25rem; padding: 0 0.6rem 0 0.75rem; border: 1px solid var(--line); + border-radius: 12px; background: var(--panel-2); color: var(--muted); font: 400 0.875rem var(--font); cursor: pointer; +} +.d-search-btn:hover { color: var(--ink); border-color: color-mix(in srgb, var(--accent) 40%, var(--line)); } +.d-search-btn span { flex: 1; text-align: start; } +.d-kbd { + padding: 0.1rem 0.4rem; border: 1px solid var(--line); border-radius: 6px; background: var(--panel); font: 500 0.7rem var(--mono); color: var(--muted); +} + +dialog.d-search { + width: min(40rem, calc(100vw - 2rem)); max-height: min(34rem, calc(100vh - 6rem)); margin: 5rem auto auto; padding: 0; border: 1px solid var(--line); + border-radius: var(--radius-lg); background: var(--panel); color: var(--ink); box-shadow: var(--shadow); overflow: hidden; +} +dialog.d-search::backdrop { background: rgb(2 8 10 / 60%); backdrop-filter: blur(3px); } +.d-search-field { display: flex; align-items: center; gap: 0.6rem; padding: 0.85rem 1rem; border-bottom: 1px solid var(--line); } +.d-search-field input { flex: 1; border: 0; outline: 0; background: transparent; color: var(--ink); font: 400 1rem var(--font); } +.d-search-field .mi { color: var(--accent); font-size: 1.4rem; } +.d-search-body { max-height: 24rem; overflow: auto; padding: 0.5rem; } +.d-search-note { padding: 1.2rem 0.8rem; color: var(--muted); font-size: 0.9rem; } +.d-search-hit { display: block; padding: 0.65rem 0.8rem; border-radius: 12px; text-decoration: none; color: var(--ink); } +.d-search-hit:hover, .d-search-hit:focus-visible { background: var(--accent-soft); outline: 0; } +.d-search-hit b { display: block; font: 600 0.95rem var(--display); } +.d-search-hit span { display: block; margin-top: 0.15rem; color: var(--muted); font-size: 0.82rem; } +.d-search-hit mark { background: transparent; color: var(--accent); font-weight: 600; } +.d-search-hit em { font: 500 0.7rem var(--mono); color: var(--accent); font-style: normal; text-transform: uppercase; letter-spacing: 0.04em; } + +/* Starlight shows its own search and theme controls; the header of Didactika draws them. */ +@media (max-width: 72rem) { .d-search-btn { min-width: 0; } .d-search-btn span, .d-search-btn .d-kbd { display: none; } } +@media (max-width: 62rem) { .d-hide-md { display: none !important; } } + +/* ------------------------------------------------------------------ sidebar ---- */ + +.sidebar-pane { border-inline-end: 1px solid var(--line); background: var(--bg); } +.sidebar-content { gap: 0.75rem; } +.sidebar-content .top-level > li > details > summary, +.sidebar-content .top-level > li > a.large { font-family: var(--font); } +.sidebar-content summary .large, .sidebar-content a .large { + font: 700 0.75rem/1.2 var(--font); letter-spacing: 0.07em; text-transform: uppercase; color: var(--ink); +} +.sidebar-content details details summary .large { text-transform: none; letter-spacing: 0; font-weight: 600; font-size: 0.875rem; } +.sidebar-content a { border-radius: 9px; padding: 0.38rem 0.7rem; color: var(--muted); font-size: 0.875rem; } +.sidebar-content a:hover { background: var(--panel-2); color: var(--ink); } +.sidebar-content a[aria-current='page'] { + background: var(--accent-soft); color: var(--accent); font-weight: 600; box-shadow: inset 3px 0 0 var(--accent); +} +.sidebar-content ul ul { border-inline-start: 1px solid var(--line); margin-inline-start: 0.7rem; padding-inline-start: 0.25rem; } + +/* ----------------------------------------------------------- page content ---- */ + +.sl-container { max-width: none; } +.sl-markdown-content { font-size: 0.9375rem; line-height: 1.7; } +.sl-markdown-content :not(a, strong, em, del, span, input, code, br, svg, path):not(:where(.not-content *)) + :not(a, strong, em, del, span, input, code, br, svg, path, :where(.not-content *)) { margin-top: 1.1rem; } +.sl-markdown-content .sl-heading-wrapper.level-h2 { margin-top: 2.6rem; padding-top: 1.4rem; border-top: 1px solid var(--line); } +.sl-markdown-content h2 { margin-top: 0; font: 700 1.55rem/1.25 var(--display); letter-spacing: -0.015em; } +.sl-markdown-content h3 { margin-top: 1.9rem; font: 600 1.15rem/1.3 var(--display); } +.sl-markdown-content h2 a, .sl-markdown-content h3 a { color: inherit; } +.sl-markdown-content strong { color: var(--ink); } +.sl-markdown-content a:not(.not-content a) { color: var(--accent); text-decoration-thickness: 1px; } + +.sl-markdown-content code:not(pre code, .not-content code) { + padding: 0.12em 0.4em; border: 1px solid var(--line); border-radius: 6px; background: var(--code); color: var(--accent-strong); font-size: 0.86em; +} +:root[data-theme='dark'] .sl-markdown-content code:not(pre code, .not-content code) { color: var(--accent-strong); } + +.expressive-code .frame { border-radius: var(--radius); box-shadow: none; } +.expressive-code .frame pre { border-color: var(--line) !important; background: var(--code) !important; border-radius: var(--radius) !important; } +.expressive-code .frame .header { background: var(--panel-2) !important; } + +.sl-markdown-content table { display: table; width: 100%; border: 1px solid var(--line); border-radius: var(--radius); border-collapse: separate; border-spacing: 0; overflow: hidden; font-size: 0.875rem; } +.sl-markdown-content :is(th, td) { padding: 0.65rem 0.85rem; border: 0; border-bottom: 1px solid var(--line); text-align: start; vertical-align: top; } +.sl-markdown-content tr:last-child td { border-bottom: 0; } +.sl-markdown-content th { background: var(--panel-2); color: var(--muted); font: 600 0.72rem/1.2 var(--font); letter-spacing: 0.06em; text-transform: uppercase; } +.sl-markdown-content tbody tr:hover td { background: color-mix(in srgb, var(--accent) 5%, transparent); } + +.sl-markdown-content img { border-radius: var(--radius); border: 1px solid var(--line); box-shadow: var(--shadow); } +.sl-markdown-content blockquote { border-inline-start: 3px solid var(--accent); background: var(--panel); border-radius: 0 var(--radius) var(--radius) 0; padding: 0.7rem 1rem; color: var(--muted); } + +/* The callouts: a card with a coloured top edge, as in the design system. */ +.starlight-aside { + padding: 1rem 1.1rem 1.05rem; border: 1px solid var(--line); border-top: 3px solid var(--aside-color, var(--accent)); border-radius: var(--radius); + background: var(--panel); box-shadow: none; +} +.starlight-aside--note { --aside-color: var(--accent); } +.starlight-aside--tip { --aside-color: var(--ok); } +.starlight-aside--caution { --aside-color: var(--warn); } +.starlight-aside--danger { --aside-color: var(--no); } +.starlight-aside__title { color: var(--aside-color) !important; font: 700 0.72rem/1.2 var(--font); letter-spacing: 0.08em; text-transform: uppercase; } +.starlight-aside__content { color: var(--ink); font-size: 0.9rem; } + +/* Steps, cards, tabs and badges of Starlight, in the look of the site. */ +.sl-steps > li::before { background: var(--accent-soft); color: var(--accent); border: 1px solid color-mix(in srgb, var(--accent) 35%, var(--line)); font-family: var(--display); font-weight: 700; } +.sl-steps > li::after { background: var(--line); } +.sl-markdown-content .card, .sl-link-card { border: 1px solid var(--line); border-radius: var(--radius); background: var(--panel); box-shadow: none; } +.sl-link-card:hover { border-color: color-mix(in srgb, var(--accent) 50%, var(--line)); background: var(--panel); } +.sl-markdown-content .card .title { font-family: var(--display); font-weight: 600; } +starlight-tabs .tab > [role='tab'] { font-family: var(--font); font-weight: 600; } +.sl-badge { border-radius: 999px; font: 600 0.7rem/1.2 var(--font); letter-spacing: 0.03em; } + +/* ------------------------------------------------------- title of a page ---- */ + +.d-title { margin-bottom: 0.5rem; } +.d-eyebrow { display: flex; flex-wrap: wrap; align-items: center; gap: 0.35rem; font: 500 0.78rem/1.4 var(--mono); color: var(--accent); } +.d-eyebrow a { color: var(--accent); text-decoration: none; } +.d-eyebrow a:hover { text-decoration: underline; } +.d-eyebrow .mi { width: 1em; height: 1em; opacity: 0.7; } +.d-title h1 { margin: 0.5rem 0 0; font: 700 clamp(2rem, 4.2vw, 2.7rem)/1.1 var(--display); letter-spacing: -0.025em; color: var(--ink); } +.d-lead { margin: 0.8rem 0 0; color: var(--muted); font-size: 1.1rem; line-height: 1.55; max-width: 38rem; } +.d-meta { display: flex; flex-wrap: wrap; gap: 0.45rem; margin-top: 1rem; } + +.d-chip { + display: inline-flex; align-items: center; gap: 0.35rem; padding: 0.2rem 0.6rem; border: 1px solid var(--line); border-radius: 999px; background: var(--panel-2); + color: var(--muted); font: 600 0.72rem/1.3 var(--font); white-space: nowrap; text-decoration: none; } +.d-chip .mi { width: 1.1em; height: 1.1em; } +.d-chip.accent { background: var(--accent-soft); color: var(--accent); border-color: color-mix(in srgb, var(--accent) 30%, var(--line)); } +.d-chip.ok { background: var(--ok-soft); color: var(--ok); border-color: color-mix(in srgb, var(--ok) 30%, var(--line)); } +.d-chip.warn { background: var(--warn-soft); color: var(--warn); border-color: color-mix(in srgb, var(--warn) 30%, var(--line)); } +a.d-chip:hover { color: var(--ink); } + +/* ----------------------------------------------------------------- footer ---- */ -/* The notice of a page that is not available in the language of the reader. */ -.sl-banner { - --__sl-banner-text: var(--sl-color-accent-high); +.d-pagefoot { margin-top: 3.5rem; padding-top: 1.6rem; border-top: 1px solid var(--line); } +.d-pager { display: grid; grid-template-columns: 1fr 1fr; gap: 1rem; } +.d-pager-link { + display: grid; gap: 0.3rem; padding: 1rem 1.2rem; border: 1px solid var(--line); border-radius: var(--radius); background: var(--panel); + color: var(--ink); text-decoration: none; transition: border-color 0.15s; +} +.d-pager-link:hover { border-color: color-mix(in srgb, var(--accent) 55%, var(--line)); } +.d-pager-link.next { text-align: end; grid-column: 2; } +.d-pager-dir { display: flex; align-items: center; gap: 0.35rem; color: var(--muted); font: 600 0.72rem var(--font); letter-spacing: 0.06em; text-transform: uppercase; } +.d-pager-link.next .d-pager-dir { justify-content: flex-end; } +.d-pager-link b { font: 600 1.05rem var(--display); color: var(--accent); } +.d-pagefoot-meta { display: flex; flex-wrap: wrap; align-items: center; justify-content: space-between; gap: 0.8rem; margin-top: 1.4rem; color: var(--muted); font-size: 0.82rem; } +.d-pagefoot-meta a { display: inline-flex; align-items: center; gap: 0.4rem; color: var(--muted); text-decoration: none; } +.d-pagefoot-meta a:hover { color: var(--accent); } + +.d-foot { margin-top: 3rem; border-top: 1px solid var(--line); background: var(--panel); } +.d-foot-in { display: grid; grid-template-columns: 1.4fr repeat(3, 1fr); gap: 2rem; width: min(72rem, 100%); margin: 0 auto; padding: 2.2rem 1.25rem; } +.d-foot h4 { margin: 0 0 0.7rem; font: 700 0.72rem/1.2 var(--font); letter-spacing: 0.08em; text-transform: uppercase; color: var(--ink); } +.d-foot ul { display: grid; gap: 0.4rem; margin: 0; padding: 0; list-style: none; } +.d-foot a { color: var(--muted); text-decoration: none; font-size: 0.875rem; } +.d-foot a:hover { color: var(--accent); } +.d-foot p { margin: 0.7rem 0 0; color: var(--muted); font-size: 0.85rem; max-width: 22rem; } +.d-foot-bar { border-top: 1px solid var(--line); padding: 0.9rem 1.25rem; text-align: center; color: var(--muted); font-size: 0.78rem; } +@media (max-width: 52rem) { .d-foot-in { grid-template-columns: 1fr 1fr; } } + +/* -------------------------------------------------------------- screenshots ---- */ + +.d-shot { margin: 1.6rem 0; border: 1px solid var(--line); border-radius: var(--radius-lg); background: var(--panel); box-shadow: var(--shadow); overflow: hidden; } +.d-shot-bar { display: flex; align-items: center; gap: 0.35rem; padding: 0.55rem 0.8rem; border-bottom: 1px solid var(--line); background: var(--panel-2); } +.d-shot-bar i { width: 0.6rem; height: 0.6rem; border-radius: 50%; background: var(--line); } +.d-shot-bar i:nth-child(1) { background: #ff6b6b; opacity: 0.85; } +.d-shot-bar i:nth-child(2) { background: #f4c150; opacity: 0.85; } +.d-shot-bar i:nth-child(3) { background: #4cc38a; opacity: 0.85; } +.d-shot-bar span { margin-inline-start: 0.6rem; font: 500 0.72rem var(--mono); color: var(--muted); } +.d-shot img { display: block; width: 100%; height: auto; border: 0; border-radius: 0; box-shadow: none; background: #fff; } +.d-shot figcaption { padding: 0.7rem 1rem; border-top: 1px solid var(--line); color: var(--muted); font-size: 0.85rem; } + +/* ------------------------------------------------------------------- home ---- */ + +.d-page { min-height: 100vh; display: flex; flex-direction: column; background: var(--bg); } +.d-top { position: sticky; top: 0; z-index: 40; height: var(--head-h); background: var(--panel); border-bottom: 1px solid var(--line); } +.d-main { flex: 1; } +.d-wrap { width: min(72rem, 100%); margin: 0 auto; padding-inline: 1.25rem; } + +.d-hero { + position: relative; overflow: hidden; border-bottom: 1px solid var(--line); background: var(--glow), radial-gradient(var(--dot) 1px, transparent 1px) 0 0 / 22px 22px; +} +.d-hero-in { display: grid; grid-template-columns: minmax(0, 1.15fr) minmax(0, 0.85fr); gap: 3rem; align-items: center; padding-block: 5rem 4.5rem; } +.d-eyebrow-pill { + display: inline-flex; align-items: center; gap: 0.4rem; padding: 0.3rem 0.7rem; border: 1px solid var(--line); border-radius: 999px; background: var(--panel); + font: 500 0.75rem var(--mono); color: var(--ink); +} +.d-eyebrow-pill .mi { color: var(--accent); } +.d-h1 { margin: 1.3rem 0 0; font: 700 clamp(2.5rem, 5.4vw, 4rem)/1.04 var(--display); letter-spacing: -0.035em; } +.d-h1 em { display: block; font-style: normal; color: var(--accent); } +.d-hero-lead { margin: 1.3rem 0 0; max-width: 36rem; color: var(--muted); font-size: 1.15rem; line-height: 1.6; } +.d-actions { display: flex; flex-wrap: wrap; gap: 0.8rem; margin-top: 2rem; } +.d-btn { + display: inline-flex; align-items: center; gap: 0.6rem; height: 3rem; padding: 0 1.3rem; border: 1px solid transparent; border-radius: 12px; background: var(--accent); + color: var(--accent-ink); font: 600 0.95rem var(--font); text-decoration: none; box-shadow: 0 8px 24px color-mix(in srgb, var(--accent) 30%, transparent); cursor: pointer; } +.d-btn:hover { filter: brightness(1.06); } +.d-btn.ghost { background: transparent; color: var(--ink); box-shadow: none; border-color: transparent; padding-inline: 0.4rem; } +.d-btn.ghost:hover { color: var(--accent); } + +.d-hero-card { + position: relative; padding: 1.4rem; border: 1px solid var(--line); border-radius: var(--radius-lg); background: color-mix(in srgb, var(--panel) 85%, transparent); + box-shadow: var(--shadow); backdrop-filter: blur(6px); +} +.d-hero-card .d-mono { font: 500 0.72rem var(--mono); color: var(--muted); } +.d-hero-tile { display: grid; place-items: center; margin: 1rem auto; width: 9rem; height: 9rem; border-radius: 28px; background: #fff; box-shadow: var(--shadow); } +.d-hero-tile img { width: 6.4rem; height: auto; } +.d-hero-chips { display: flex; flex-wrap: wrap; justify-content: center; gap: 0.45rem; } + +.d-stats { display: grid; grid-template-columns: repeat(4, 1fr); gap: 1px; margin-top: -2.2rem; position: relative; border: 1px solid var(--line); border-radius: var(--radius-lg); background: var(--line); overflow: hidden; box-shadow: var(--shadow); } +.d-stat { padding: 1.2rem 1.4rem; background: var(--panel); } +.d-stat b { display: block; font: 700 2rem/1.1 var(--display); letter-spacing: -0.02em; } +.d-stat span { display: flex; align-items: center; gap: 0.4rem; margin-top: 0.25rem; color: var(--muted); font-size: 0.82rem; } +.d-stat .mi { color: var(--accent); } + +.d-section { padding-block: 4rem 0; } +.d-section h2 { margin: 0; font: 700 1.9rem/1.2 var(--display); letter-spacing: -0.02em; } +.d-section > .d-wrap > p, .d-lead2 { margin: 0.6rem 0 0; color: var(--muted); max-width: 40rem; } + +.d-grid { display: grid; grid-template-columns: repeat(auto-fill, minmax(21rem, 1fr)); gap: 1.1rem; margin-top: 1.8rem; } +.d-product { + position: relative; display: flex; flex-direction: column; gap: 0.9rem; padding: 1.4rem; border: 1px solid var(--line); border-radius: var(--radius-lg); + background: var(--panel); color: var(--ink); text-decoration: none; transition: transform 0.15s, border-color 0.15s, box-shadow 0.15s; +} +.d-product:hover { transform: translateY(-2px); border-color: color-mix(in srgb, var(--accent) 55%, var(--line)); box-shadow: var(--shadow); } +.d-product-top { display: flex; align-items: center; gap: 0.9rem; } +.d-tile { display: grid; place-items: center; flex: none; width: 3.2rem; height: 3.2rem; border-radius: 14px; background: #fff; border: 1px solid var(--line); } +.d-tile img { width: 2.1rem; height: 2.1rem; } +.d-tile .mi { width: 1.7rem; height: 1.7rem; color: var(--accent); } +.d-tile.soft { background: var(--accent-soft); border-color: color-mix(in srgb, var(--accent) 25%, var(--line)); } +.d-product h3 { margin: 0; font: 700 1.2rem/1.2 var(--display); letter-spacing: -0.01em; } +.d-product code { font: 500 0.72rem var(--mono); color: var(--muted); } +.d-product p { margin: 0; color: var(--muted); font-size: 0.92rem; line-height: 1.55; flex: 1; } +.d-row { display: flex; flex-wrap: wrap; align-items: center; gap: 0.4rem; } +.d-row-label { margin-inline-end: 0.2rem; font: 600 0.68rem var(--font); letter-spacing: 0.07em; text-transform: uppercase; color: var(--muted); } +.d-product-cta { display: flex; align-items: center; justify-content: space-between; padding-top: 0.9rem; border-top: 1px solid var(--line); color: var(--accent); font-weight: 600; font-size: 0.9rem; } +.d-product.soon { opacity: 0.72; } +.d-product.soon:hover { transform: none; border-color: var(--line); box-shadow: none; } + +.d-cards { display: grid; grid-template-columns: repeat(auto-fit, minmax(15rem, 1fr)); gap: 1.1rem; margin-top: 1.8rem; } +.d-card { padding: 1.4rem; border: 1px solid var(--line); border-radius: var(--radius-lg); background: var(--panel); } +.d-card .d-tile { margin-bottom: 1rem; } +.d-card h3 { margin: 0; font: 700 1.1rem/1.25 var(--display); } +.d-card p { margin: 0.5rem 0 0; color: var(--muted); font-size: 0.9rem; line-height: 1.6; } + +.d-band { margin-top: 4rem; border-block: 1px solid var(--line); background: var(--panel); } +.d-band-in { display: grid; grid-template-columns: 1fr 1fr; gap: 3rem; padding-block: 3.2rem; } +.d-band h2 { margin: 0 0 0.6rem; font: 700 1.6rem/1.2 var(--display); } +.d-band p { margin: 0; color: var(--muted); line-height: 1.65; } +.d-pillrow { display: flex; flex-wrap: wrap; gap: 0.6rem; margin-top: 1.2rem; } +.d-pill { display: inline-flex; align-items: center; gap: 0.5rem; padding: 0.55rem 0.9rem; border: 1px solid var(--line); border-radius: 12px; background: var(--bg); font-weight: 600; font-size: 0.88rem; } +.d-pill small { color: var(--muted); font-weight: 400; } +.d-pill .mi { color: var(--accent); } + +@media (max-width: 62rem) { + .d-hero-in, .d-band-in { grid-template-columns: 1fr; gap: 2rem; } + .d-hero-card { display: none; } + .d-stats { grid-template-columns: repeat(2, 1fr); } +} + +/* --------------------------------------------------------------- the product ---- */ + +.d-facts { display: grid; grid-template-columns: repeat(auto-fit, minmax(11rem, 1fr)); gap: 0.8rem; margin: 1.4rem 0 0; } +.d-fact { padding: 0.8rem 1rem; border: 1px solid var(--line); border-radius: var(--radius); background: var(--panel); } +.d-fact span { display: block; font: 600 0.66rem var(--font); letter-spacing: 0.08em; text-transform: uppercase; color: var(--muted); } +.d-fact b { display: flex; align-items: center; gap: 0.4rem; margin-top: 0.2rem; font: 600 0.95rem var(--display); } +.d-fact .mi { color: var(--accent); } +.d-product-head { display: flex; align-items: center; gap: 1.1rem; margin-top: 0.4rem; } +.d-product-head .d-tile { width: 4.2rem; height: 4.2rem; border-radius: 18px; } +.d-product-head .d-tile img { width: 2.8rem; height: 2.8rem; } + +@media print { .d-head, .d-foot { display: none; } } + +.d-foot-line { margin: 0; color: var(--muted); font-size: 0.8rem; } +.d-skip { position: absolute; left: -999px; top: 0.5rem; z-index: 100; padding: 0.5rem 0.75rem; background: var(--accent); color: var(--accent-ink); border-radius: 8px; } +.d-skip:focus { left: 0.5rem; } + +/* -------------------------------------------------- features inside a page ---- */ + +.d-features { display: grid; gap: 1rem; margin: 1.6rem 0; grid-template-columns: repeat(auto-fit, minmax(14rem, 1fr)); } +.d-features[data-columns='2'] { grid-template-columns: repeat(auto-fit, minmax(20rem, 1fr)); } +.d-feature { + position: relative; display: block; padding: 1.2rem 1.25rem 1.3rem; border: 1px solid var(--line); border-radius: var(--radius-lg); background: var(--panel); + color: var(--ink); text-decoration: none; transition: border-color 0.15s, transform 0.15s; +} +a.d-feature:hover { border-color: color-mix(in srgb, var(--accent) 55%, var(--line)); transform: translateY(-2px); } +.d-feature .d-tile { width: 2.7rem; height: 2.7rem; margin-bottom: 0.9rem; border-radius: 12px; } +.d-feature .d-tile .mi { width: 1.45rem; height: 1.45rem; } +.d-feature h3 { margin: 0; font: 700 1.02rem/1.3 var(--display); color: var(--ink); } +.d-feature p { margin: 0.45rem 0 0; color: var(--muted); font-size: 0.88rem; line-height: 1.6; } +.d-feature-go { position: absolute; top: 1.2rem; inset-inline-end: 1.1rem; color: var(--accent); opacity: 0.8; } + +.d-fact b a { color: var(--accent); text-decoration: none; font: 500 0.8rem var(--mono); overflow-wrap: anywhere; } diff --git a/tools/check-icons.ts b/tools/check-icons.ts new file mode 100644 index 0000000..2b8a8d4 --- /dev/null +++ b/tools/check-icons.ts @@ -0,0 +1,44 @@ +/** + * Checks that every Material icon the site uses exists in the set, before the build finds out one page at a time. + * Run with `npm run icons`. An icon is any `name-rounded` written in src/ or in the pages of a product. + * + * @license GPL-3.0-or-later + */ + +import {readdirSync, readFileSync} from 'node:fs'; +import {join, resolve} from 'node:path'; + +const root = resolve(import.meta.dirname, '..'); +const set = JSON.parse(readFileSync(join(root, 'node_modules', '@iconify-json', 'material-symbols', 'icons.json'), 'utf8')) as { + icons: Record; + aliases?: Record; +}; + +function* files(folder: string): Generator { + for (const entry of readdirSync(folder, {withFileTypes: true})) { + const path = join(folder, entry.name); + if (entry.isDirectory()) { + if (!['node_modules', 'content', 'data', 'assets'].includes(entry.name)) { + yield* files(path); + } + } else if (/\.(?:astro|ts|css|mdx?)$/.test(entry.name)) { + yield path; + } + } +} + +const missing = new Map(); +for (const file of files(join(root, 'src'))) { + for (const match of readFileSync(file, 'utf8').matchAll(/['"]([a-z0-9]+(?:-[a-z0-9]+)*-rounded)['"]/g)) { + const name = match[1]; + if (!(name in set.icons) && !(set.aliases && name in set.aliases)) { + missing.set(name, file.slice(root.length + 1)); + } + } +} + +for (const [name, file] of missing) { + console.error(`missing ${name} (${file})`); +} +console.log(missing.size === 0 ? 'Every Material icon exists.' : `${missing.size} icon(s) do not exist.`); +process.exit(missing.size === 0 ? 0 : 1); diff --git a/tools/lib/directory.test.ts b/tools/lib/directory.test.ts new file mode 100644 index 0000000..9b503c9 --- /dev/null +++ b/tools/lib/directory.test.ts @@ -0,0 +1,53 @@ +import assert from 'node:assert/strict'; +import {describe, it} from 'node:test'; +import {branchesOf, checkDirectory, directoryPage} from './directory.ts'; + +/** A directory that has the plugin for the branches given and answers 404 for the others. */ +const directory = (has: Record, failing = false): typeof fetch => + (async (input: string | URL | Request) => { + if (failing) { + throw new Error('offline'); + } + const branch = new URL(String(input)).searchParams.get('branch') ?? ''; + return has[branch] + ? new Response(JSON.stringify({status: 'OK', pluginfo: {component: 'local_demo', version: {release: has[branch]}}}), {status: 200}) + : new Response('', {status: 404}); + }) as typeof fetch; + +describe('branchesOf', () => { + it('names the two ends of each range once', () => { + assert.deepEqual(branchesOf([{low: 405, high: 502}, {low: 503, high: 503}]), ['4.5', '5.2', '5.3']); + }); +}); + +describe('checkDirectory', () => { + it('is published when a branch has a release, and lists the releases', async () => { + const answer = await checkDirectory('local_demo', ['4.5', '5.3'], undefined, directory({'4.5': '1.0.0-m405', '5.3': '1.0.0-m503'})); + assert.equal(answer.published, true); + assert.deepEqual(answer.releases, [{branch: '4.5', release: '1.0.0-m405'}, {branch: '5.3', release: '1.0.0-m503'}]); + assert.ok(answer.checked); + }); + + it('is published even when only one of its branches has a release', async () => { + assert.equal((await checkDirectory('local_demo', ['4.5', '5.3'], undefined, directory({'5.3': '1.0.0-m503'}))).published, true); + }); + + it('is not published when no branch has a release', async () => { + const answer = await checkDirectory('local_demo', ['4.5', '5.3'], undefined, directory({})); + assert.equal(answer.published, false); + assert.deepEqual(answer.releases, []); + }); + + it('keeps the last answer when the directory cannot be reached', async () => { + const previous = {published: true, releases: [{branch: '5.3', release: '1.0.0-m503'}], checked: '2026-11-10T00:00:00.000Z'}; + assert.deepEqual(await checkDirectory('local_demo', ['5.3'], previous, directory({}, true)), previous); + }); + + it('says it does not know when there is no last answer either', async () => { + assert.deepEqual(await checkDirectory('local_demo', ['5.3'], undefined, directory({}, true)), {published: null, releases: [], checked: null}); + }); +}); + +it('links the page of a plugin in the directory', () => { + assert.equal(directoryPage('local_demo'), 'https://moodle.org/plugins/local_demo'); +}); diff --git a/tools/lib/directory.ts b/tools/lib/directory.ts new file mode 100644 index 0000000..011424e --- /dev/null +++ b/tools/lib/directory.ts @@ -0,0 +1,64 @@ +/** + * Whether a plugin is in the Moodle plugins directory, asked to the same service Moodle itself uses to look for updates: + * + * https://download.moodle.org/api/1.3/pluginfo.php?plugin=&format=json&minversion=0&branch= + * + * It answers 200 with the release the directory offers for a branch of Moodle, and 404 when there is none. A plugin is published when any + * of the branches it supports has a release. When the directory cannot be reached the last answer is kept, and when there is none the + * answer is "unknown" (null), never a guess. + * + * @license GPL-3.0-or-later + */ + +export interface DirectoryAnswer { + published: boolean | null; + releases: Array<{branch: string; release: string}>; + /** When the directory was asked, in ISO format. */ + checked: string | null; +} + +export type Cache = Record; + +const ENDPOINT = 'https://download.moodle.org/api/1.3/pluginfo.php'; + +export const directoryPage = (component: string): string => `https://moodle.org/plugins/${component}`; + +/** The branches of Moodle to ask for, from the range a line supports (405 and 502 give 4.5 and 5.2). */ +export function branchesOf(ranges: Array<{low: number; high: number}>): string[] { + const name = (code: number): string => `${Math.floor(code / 100)}.${code % 100}`; + return [...new Set(ranges.flatMap((range) => [name(range.low), name(range.high)]))]; +} + +/** Asks the directory about one branch: the release, `null` when there is none, and an error when it could not be asked. */ +async function ask(component: string, branch: string, fetcher: typeof fetch): Promise { + const url = `${ENDPOINT}?plugin=${encodeURIComponent(component)}&format=json&minversion=0&branch=${branch}`; + const response = await fetcher(url, {signal: AbortSignal.timeout(10_000)}); + if (response.status === 404) { + return null; + } + if (!response.ok) { + throw new Error(`The directory answered ${response.status}.`); + } + // The release is inside `pluginfo.version`; a plugin that answers without one is still published. + const body = (await response.json()) as {pluginfo?: {version?: {release?: string}}}; + return body.pluginfo ? (body.pluginfo.version?.release ?? '') : null; +} + +/** + * The answer of the directory for a plugin. `previous` is what was known before and is returned, unchanged, when the directory + * cannot be reached. + */ +export async function checkDirectory(component: string, branches: string[], previous?: DirectoryAnswer, fetcher: typeof fetch = fetch): Promise { + try { + const releases: DirectoryAnswer['releases'] = []; + for (const branch of branches) { + const release = await ask(component, branch, fetcher); + if (release !== null) { + releases.push({branch, release}); + } + } + return {published: releases.length > 0, releases, checked: new Date().toISOString()}; + } catch { + return previous ?? {published: null, releases: [], checked: null}; + } +} diff --git a/tools/lib/markdown.test.ts b/tools/lib/markdown.test.ts index be3290d..ab458a9 100644 --- a/tools/lib/markdown.test.ts +++ b/tools/lib/markdown.test.ts @@ -1,6 +1,6 @@ import assert from 'node:assert/strict'; import {describe, it} from 'node:test'; -import {alertsToAsides, resolvePageLinks, transformBody} from './markdown.ts'; +import {addComponentImports, alertsToAsides, resolveAssetLinks, resolvePageLinks, transformBody} from './markdown.ts'; describe('alertsToAsides', () => { it('turns an alert of GitHub into an aside of Starlight', () => { @@ -41,14 +41,67 @@ describe('resolvePageLinks', () => { assert.equal(resolvePageLinks('[home](page:index)', base), '[home](/en/plugins/local-demo/m503/)'); }); + it('points the href of a component at the page too', () => { + assert.equal(resolvePageLinks('', base), ''); + assert.equal(resolvePageLinks("", base), ""); + }); + it('does not touch ordinary links or fenced code', () => { const text = '[a](https://example.org) and\n```\n[b](page:guides/a)\n```'; assert.equal(resolvePageLinks(text, base), text); }); }); +describe('resolveAssetLinks', () => { + const base = '/docs-assets/plugins/local-demo/m405'; + + it('points an image, a link and an attribute at the file of the version', () => { + assert.equal( + resolveAssetLinks('![A](asset:a.png) [b](asset:files/b.pdf) ', base), + `![A](${base}/a.png) [b](${base}/files/b.pdf) `, + ); + }); + + it('does not touch fenced code', () => { + const code = '```md\n![A](asset:a.png)\n```'; + assert.equal(resolveAssetLinks(code, base), code); + }); +}); + +describe('addComponentImports', () => { + it('imports the components of Starlight a page uses, together and only those', () => { + const out = addComponentImports('---\ntitle: A\n---\n\n\n1. One\n\n\n\n'); + assert.ok(out.includes("import {Steps, Card, CardGrid} from '@astrojs/starlight/components';")); + assert.ok(!out.includes('Tabs')); + }); + + it('puts the imports after the front matter, not before it', () => { + const out = addComponentImports('---\ntitle: A\n---\n\nx\n'); + assert.ok(out.startsWith('---\ntitle: A\n---\n')); + assert.ok(out.indexOf('import') > out.indexOf('title: A')); + }); + + it('imports the components of the site by their default export', () => { + const out = addComponentImports(' '); + assert.ok(out.includes("import MIcon from '/src/components/MIcon.astro';")); + assert.ok(out.includes("import Screenshot from '/src/components/Screenshot.astro';")); + }); + + it('leaves a page that uses none as it is, and ignores a component named inside code', () => { + const plain = '---\ntitle: A\n---\nText\n```mdx\n\n```\n'; + assert.equal(addComponentImports(plain), plain); + }); +}); + describe('transformBody', () => { - it('does both', () => { - assert.equal(transformBody('> [!WARNING]\n> See [roles](page:getting-started/give-permission).', '/es/plugins/x/m405'), ':::caution\nSee [roles](/es/plugins/x/m405/getting-started/give-permission/).\n:::'); + it('does the alerts and the page links', () => { + assert.equal( + transformBody('> [!WARNING]\n> See [roles](page:getting-started/give-permission).', '/es/plugins/x/m405'), + ':::caution\nSee [roles](/es/plugins/x/m405/getting-started/give-permission/).\n:::', + ); + }); + + it('resolves the assets when it is given where they are', () => { + assert.equal(transformBody('![A](asset:a.png)', '/en/p/m1', '/docs-assets/p/m1'), '![A](/docs-assets/p/m1/a.png)'); }); }); diff --git a/tools/lib/markdown.ts b/tools/lib/markdown.ts index 1308ec4..9eaf869 100644 --- a/tools/lib/markdown.ts +++ b/tools/lib/markdown.ts @@ -1,11 +1,12 @@ /** - * What the portal does to the Markdown of a page on its way into the site. - * - * Two things, so that a page reads well on GitHub and on the portal without being written twice: + * What the portal does to the Markdown of a page on its way into the site, so that a page reads well on GitHub and on the portal + * without being written twice: * * - The alerts of GitHub (`> [!NOTE]`) become the asides of Starlight (`:::note`). * - A link to another page of the same product, `[text](page:guides/install)`, becomes the address of that page in the same version * and language, so a link never leaves the version the reader is in. An anchor may follow: `page:guides/install#step-2`. + * - A file of the documentation, `asset:shot.png` (in the `_assets` folder), becomes its address in the version the reader is in. + * - A page written in MDX uses the components of the site without importing them: the imports it needs are added. * * Fenced code is left as it is. * @@ -43,11 +44,53 @@ export function alertsToAsides(markdown: string): string { /** `page:` links, written as the address of the page inside `base` (`/en/plugins/local-demo/m503`). */ export function resolvePageLinks(markdown: string, base: string): string { + const address = (id: string, anchor: string | undefined): string => `${base}${id === 'index' ? '/' : `/${id}/`}${anchor ?? ''}`; return outsideFences(markdown, (text) => - text.replace(/\]\(page:([^)#\s]+)(#[^)\s]*)?\)/g, (_, id: string, anchor: string | undefined) => `](${base}${id === 'index' ? '/' : `/${id}/`}${anchor ?? ''})`), + text + // A link of Markdown: [text](page:guides/install#step-2) + .replace(/\]\(page:([^)#\s]+)(#[^)\s]*)?\)/g, (_, id: string, anchor: string | undefined) => `](${address(id, anchor)})`) + // An attribute of a component: href="page:guides/install" + .replace(/(=\s*)(["'])page:([^"'#\s]+)(#[^"'\s]*)?\2/g, (_, equals: string, quote: string, id: string, anchor: string | undefined) => `${equals}${quote}${address(id, anchor)}${quote}`), ); } -export function transformBody(markdown: string, base: string): string { - return resolvePageLinks(alertsToAsides(markdown), base); +/** `asset:name.png` becomes `/name.png`, in an image, a link or an attribute of a component. */ +export function resolveAssetLinks(markdown: string, assetBase: string): string { + return outsideFences(markdown, (text) => text.replace(/asset:([A-Za-z0-9_./-]+)/g, (_, path: string) => `${assetBase}/${path}`)); +} + +/** The components an MDX page may use without importing them, where each comes from, and whether it is a default export. */ +const COMPONENTS: Array<{names: string[]; from: string; named: boolean}> = [ + {names: ['Steps', 'Card', 'CardGrid', 'LinkCard', 'Tabs', 'TabItem', 'Badge', 'FileTree'], from: '@astrojs/starlight/components', named: true}, + {names: ['MIcon'], from: '/src/components/MIcon.astro', named: false}, + {names: ['Screenshot'], from: '/src/components/Screenshot.astro', named: false}, + {names: ['FeatureGrid'], from: '/src/components/FeatureGrid.astro', named: false}, + {names: ['Feature'], from: '/src/components/Feature.astro', named: false}, +]; + +/** Adds, before the content of an MDX page, the imports of the components it uses. */ +export function addComponentImports(mdx: string): string { + const imports: string[] = []; + outsideFences(mdx, (text) => { + for (const {names, from, named} of COMPONENTS) { + const used = names.filter((name) => new RegExp(`<${name}[\\s/>]`).test(text)); + if (used.length === 0) { + continue; + } + // A component of the site is imported by itself; the ones of Starlight, together. + imports.push(...(named ? [`import {${used.join(', ')}} from '${from}';`] : used.map((name) => `import ${name} from '${from}';`))); + } + return text; + }); + if (imports.length === 0) { + return mdx; + } + // The imports go after the front matter, where MDX reads them. + const front = /^---\n[\s\S]*?\n---\n/.exec(mdx)?.[0] ?? ''; + return `${front}\n${imports.join('\n')}\n${mdx.slice(front.length)}`; +} + +export function transformBody(markdown: string, base: string, assetBase?: string): string { + const linked = resolvePageLinks(alertsToAsides(markdown), base); + return assetBase ? resolveAssetLinks(linked, assetBase) : linked; } diff --git a/tools/lib/source.test.ts b/tools/lib/source.test.ts index f8cdb49..0851c7c 100644 --- a/tools/lib/source.test.ts +++ b/tools/lib/source.test.ts @@ -4,7 +4,7 @@ import {mkdirSync, mkdtempSync, rmSync, writeFileSync} from 'node:fs'; import {tmpdir} from 'node:os'; import {dirname, join} from 'node:path'; import {after, before, describe, it} from 'node:test'; -import {lineLabel, moodleVersion, readProduct, readVersionPhp} from './source.ts'; +import {lineLabel, moodleVersion, readComponent, readProduct, readVersionPhp} from './source.ts'; const versionPhp = (release: string, low: number, high: number): string => `version = 2026110700;\n$plugin->release = '${release}';\n$plugin->supported = [${low}, ${high}];\n`; @@ -19,6 +19,11 @@ describe('version.php', () => { assert.equal(readVersionPhp("release = '1.0.0-m405';\n"), undefined); }); + it('reads the component of the plugin', () => { + assert.equal(readComponent("component = 'local_demo';\n"), 'local_demo'); + assert.equal(readComponent(' { assert.equal(moodleVersion(405), '4.5'); assert.equal(lineLabel(405, 502), 'Moodle 4.5 – 5.2'); diff --git a/tools/lib/source.ts b/tools/lib/source.ts index 2afb2cb..df4e2cd 100644 --- a/tools/lib/source.ts +++ b/tools/lib/source.ts @@ -38,6 +38,10 @@ export interface SourceLine extends LineInput { export interface SourceProduct { docs: DocsJson | null; + /** The component of Moodle (`local_delegateaccount`), from the `version.php` of the default branch. */ + component: string | null; + /** The icon of the plugin (`pix/icon.svg` of the default branch), when it has one. */ + iconSvg: string | null; lines: SourceLine[]; issues: Issue[]; } @@ -64,6 +68,9 @@ export const lineLabel = (low: number, high: number): string => low === high ? `Moodle ${moodleVersion(low)}` : `Moodle ${moodleVersion(low)} – ${moodleVersion(high)}`; /** Reads the identity of a line from the `version.php` of its branch. */ +/** The component of a plugin, from its `version.php`. */ +export const readComponent = (php: string): string | null => /\$plugin->component\s*=\s*['"]([^'"]+)['"]/.exec(php)?.[1] ?? null; + export function readVersionPhp(php: string): {id: string; release: string; low: number; high: number} | undefined { const release = /\$plugin->release\s*=\s*['"]([^'"]+)['"]/.exec(php)?.[1]; const id = release ? /-m(\d+)$/.exec(release)?.[1] : undefined; @@ -159,5 +166,8 @@ export function readProduct(repo: string, options: ReadOptions = {}): SourceProd line.extends = declared && 'extends' in declared ? (declared.extends ?? null) : index === 0 ? null : lines[index - 1].id; }); - return {docs, lines, issues}; + const defaultPhp = defaultRef ? tryGit(repo, ['show', `${defaultRef}:version.php`]) : undefined; + const iconSvg = defaultRef ? (tryGit(repo, ['show', `${defaultRef}:pix/icon.svg`]) ?? null) : null; + + return {docs, component: defaultPhp ? readComponent(defaultPhp) : null, iconSvg, lines, issues}; } diff --git a/tools/serve.ts b/tools/serve.ts new file mode 100644 index 0000000..98967c9 --- /dev/null +++ b/tools/serve.ts @@ -0,0 +1,87 @@ +/** + * Serves the site as it will be deployed: it builds it, serves what it built and builds it again when the documentation of a product or + * the site itself changes. It is what `docker compose up` runs, so what you see there is what Pages publishes (including the search, + * which only exists in a built site). + * + * Every few seconds it synchronises the products (tools/sync.ts, which only writes what changed) and compares a fingerprint of the + * content and of the code of the site with the one of the last build. + * + * @license GPL-3.0-or-later + */ + +import {spawn, spawnSync} from 'node:child_process'; +import {createHash} from 'node:crypto'; +import {existsSync, readdirSync, readFileSync, statSync} from 'node:fs'; +import {join, relative, resolve} from 'node:path'; + +const root = resolve(import.meta.dirname, '..'); +const every = Number(process.env.DOCS_EVERY ?? 5) * 1000; +const port = process.env.PORT ?? '4321'; + +/** The files that make up the site and are not generated, by path, size and time. */ +function codeSignature(): string { + const hash = createHash('sha256'); + const walk = (folder: string): void => { + for (const entry of readdirSync(folder, {withFileTypes: true})) { + const path = join(folder, entry.name); + const rel = relative(root, path).replaceAll('\\', '/'); + if (/^src\/content\/docs\/[^/]+\/(?:plugins|packages)(?:\/|$)/.test(rel) || rel === 'src/data/products.generated.json') { + continue; + } + if (entry.isDirectory()) { + walk(path); + } else { + const stat = statSync(path); + hash.update(`${rel}:${stat.size}:${Math.floor(stat.mtimeMs)}\n`); + } + } + }; + walk(join(root, 'src')); + for (const file of ['astro.config.ts', 'languages.json', 'roadmap.json', 'manifest.json']) { + if (existsSync(join(root, file))) { + hash.update(`${file}:${statSync(join(root, file)).mtimeMs}\n`); + } + } + return hash.digest('hex'); +} + +const run = (script: string, args: string[]): number => spawnSync('node', [join(root, script), ...args], {cwd: root, stdio: 'inherit'}).status ?? 1; + +function sync(): void { + const status = spawnSync('node', [join(root, 'tools', 'sync.ts')], {cwd: root, encoding: 'utf8'}); + // Only a problem is worth the log of a loop that runs every few seconds. + if (status.status !== 0 || process.env.DOCS_VERBOSE) { + process.stdout.write(status.stdout + status.stderr); + } +} + +function build(): boolean { + console.log(`[serve] building the site (${new Date().toLocaleTimeString()})`); + const result = spawnSync('npx', ['astro', 'build'], {cwd: root, stdio: 'inherit', shell: process.platform === 'win32'}); + console.log(result.status === 0 ? '[serve] built' : '[serve] the build failed; the last good site stays'); + return result.status === 0; +} + +const fingerprint = (): string => `${codeSignature()}|${existsSync(join(root, '.cache', 'sync.hash')) ? readFileSync(join(root, '.cache', 'sync.hash'), 'utf8') : ''}`; + +run('tools/sync.ts', []); +let built = fingerprint(); +build(); + +spawn('npx', ['astro', 'preview', '--host', '0.0.0.0', '--port', port], {cwd: root, stdio: 'inherit', shell: process.platform === 'win32'}); +console.log(`[serve] http://localhost:${port}/ (the documentation is read again every ${every / 1000} s)`); + +let building = false; +setInterval(() => { + if (building) { + return; + } + sync(); + const now = fingerprint(); + if (now !== built) { + building = true; + built = now; + build(); + building = false; + } +}, every); diff --git a/tools/sync.ts b/tools/sync.ts index a2e47dd..37e9663 100644 --- a/tools/sync.ts +++ b/tools/sync.ts @@ -1,18 +1,21 @@ /** * Brings the documentation of every product of manifest.json into the site. * - * For each product it reads its repository (lib/source.ts), resolves every version and language (lib/resolve.ts) and writes the - * pages Starlight builds: + * For each product it reads its repository (lib/source.ts), resolves every version and language (lib/resolve.ts) and writes what the + * site is built from: * * src/content/docs///// one tree for each version * src/content/docs//// the same as the newest version, the address without a version - * src/data/products.generated.json what the components of the site need to know + * public/docs-assets////... the images and files of each version + * public/product-icons/.svg the icon of the product + * src/data/products.generated.json what the components of the site need to know * * Everything it writes is generated and ignored by git; the pages are never edited here. * * Environment: * DOCS_SOURCES folder that holds a clone of each repository, named like it. Default: .cache/sources, cloned from GitHub. * DOCS_NO_FETCH use the clones as they are, without fetching. + * DOCS_OFFLINE do not ask the Moodle directory whether the plugins are published: use the last answer, or "unknown". * DOCS_MANIFEST another manifest than manifest.json, for trying the site with a repository of examples. * DOCS_REFS JSON that reads a line from another ref than its branch, to preview what is not merged yet: * {"didactika/moodle-local_x": {"main": "docs/portal", "MOODLE_405_STABLE": "docs/portal-405"}} @@ -22,10 +25,12 @@ */ import {execFileSync} from 'node:child_process'; +import {createHash} from 'node:crypto'; import {existsSync, mkdirSync, readdirSync, readFileSync, rmdirSync, rmSync, writeFileSync} from 'node:fs'; import {dirname, join, resolve} from 'node:path'; import {stringify} from 'yaml'; -import {transformBody} from './lib/markdown.ts'; +import {branchesOf, checkDirectory, directoryPage, type Cache, type DirectoryAnswer} from './lib/directory.ts'; +import {addComponentImports, transformBody} from './lib/markdown.ts'; import {parseFrontmatter, resolveProduct, type Issue, type LanguageDef} from './lib/resolve.ts'; import {readProduct, type DocsJson} from './lib/source.ts'; @@ -40,14 +45,23 @@ interface ManifestProduct { kind: 'plugin' | 'package'; } +interface RoadmapItem { + component: string; + repo: string; + title: Record; + summary: Record; +} + const root = resolve(import.meta.dirname, '..'); const sources = process.env.DOCS_SOURCES ? resolve(process.env.DOCS_SOURCES) : join(root, '.cache', 'sources'); const content = join(root, 'src', 'content', 'docs'); +const publicDir = join(root, 'public'); const KIND_DIR = {plugin: 'plugins', package: 'packages'} as const; const readJson = (path: string): T => JSON.parse(readFileSync(path, 'utf8')) as T; const languages = readJson(join(root, 'languages.json')).filter((language) => language.enabled); const manifest = readJson<{products: ManifestProduct[]}>(process.env.DOCS_MANIFEST ? resolve(process.env.DOCS_MANIFEST) : join(root, 'manifest.json')); +const roadmap = existsSync(join(root, 'roadmap.json')) ? readJson(join(root, 'roadmap.json')) : []; /** A text of the interface in a language; what that language does not have is taken from the source language. */ const sourceCode = languages.find((language) => language.source)!.code; @@ -60,8 +74,6 @@ const ui = (code: string, key: string, values: Record = {}): str return text.replace(/\{(\w+)\}/g, (_, name: string) => values[name] ?? ''); }; -const localised = (texts: Record | undefined, code: string, fallback: string): string => texts?.[code] ?? texts?.[sourceCode] ?? fallback; - function sourceOf(repo: string): string { const name = repo.split('/')[1]; const folder = join(sources, name); @@ -74,17 +86,20 @@ function sourceOf(repo: string): string { return folder; } -// Everything written in this run. A file that is already as it should be is not touched, so a watching dev server does not rebuild for nothing, -// and the files of an earlier run that were not written again are deleted at the end. +// Everything written in this run. A file that is already as it should be is not touched, so a watcher does not rebuild for nothing, and +// the files of an earlier run that were not written again are deleted at the end. const written = new Set(); +const fingerprint = createHash('sha256'); -function write(path: string, text: string): void { +function write(path: string, data: string | Buffer): void { written.add(path); - if (existsSync(path) && readFileSync(path, 'utf8') === text) { + fingerprint.update(path).update(data); + const same = existsSync(path) && readFileSync(path).equals(typeof data === 'string' ? Buffer.from(data) : data); + if (same) { return; } mkdirSync(dirname(path), {recursive: true}); - writeFileSync(path, text); + writeFileSync(path, data); } /** Deletes what an earlier run generated and this one did not, and the folders that are left empty. */ @@ -92,9 +107,9 @@ function removeStale(folder: string): void { if (!existsSync(folder)) { return; } - for (const name of readdirSync(folder, {withFileTypes: true})) { - const path = join(folder, name.name); - if (name.isDirectory()) { + for (const entry of readdirSync(folder, {withFileTypes: true})) { + const path = join(folder, entry.name); + if (entry.isDirectory()) { removeStale(path); } else if (!written.has(path)) { rmSync(path); @@ -109,9 +124,28 @@ function removeStale(folder: string): void { const previewFile = join(root, 'preview.refs.json'); const previews = (process.env.DOCS_REFS ? JSON.parse(process.env.DOCS_REFS) : existsSync(previewFile) ? JSON.parse(readFileSync(previewFile, 'utf8')) : {}) as Record>; +// What the Moodle directory said the last time, so a build without network keeps showing it. +const cacheFile = join(root, '.cache', 'directory.json'); +const directoryCache: Cache = existsSync(cacheFile) ? readJson(cacheFile) : {}; + +async function directoryOf(component: string | null, branches: string[], forced: boolean | 'auto' | undefined): Promise { + if (typeof forced === 'boolean') { + return {published: forced, releases: [], checked: null}; + } + if (!component) { + return {published: null, releases: [], checked: null}; + } + // The directory is asked at most every six hours, so a loop that synchronises often does not call it every time. + const known = directoryCache[component]; + const fresh = known?.checked !== null && known?.checked !== undefined && Date.now() - Date.parse(known.checked) < 6 * 3600 * 1000; + const answer = process.env.DOCS_OFFLINE || fresh ? (known ?? {published: null, releases: [], checked: null}) : await checkDirectory(component, branches, known); + directoryCache[component] = answer; + return answer; +} + /** The front matter Starlight understands, made from the one authors write (title, summary, order). */ function frontmatter(data: Record, extra: Record): string { - const { title, summary, description, order, hidden, reason, source, ...rest } = data; + const {title, summary, description, order, hidden: _hidden, reason: _reason, source: _source, ...rest} = data; const out: Record = { title: title ?? 'Untitled', description: summary ?? description, @@ -128,15 +162,18 @@ function frontmatter(data: Record, extra: Record [...new Set(ids.filter((id) => id.includes('/')).map((id) => id.split('/')[0]))].sort((a, b) => { const rank = (name: string): number => (USUAL_SECTIONS.includes(name) ? USUAL_SECTIONS.indexOf(name) : USUAL_SECTIONS.length); return rank(a) - rank(b) || a.localeCompare(b); }); +const isText = (path: string): boolean => /\.(?:md|mdx|svg|txt|json)$/.test(path); + const issues: Array = []; const products: Array> = []; +const documented = new Set(); for (const entry of manifest.products) { const product = readProduct(sourceOf(entry.repo), {refs: previews[entry.repo]}); @@ -159,67 +196,74 @@ for (const entry of manifest.products) { const newest = product.lines[product.lines.length - 1]; const kindDir = KIND_DIR[docs.kind]; const branchOf = new Map(product.lines.map((line) => [line.id, line.branch])); + if (product.component) { + documented.add(product.component); + } for (const line of resolution.lines) { + const assetBase = `/docs-assets/${kindDir}/${docs.slug}/${line.id}`; + for (const [path, asset] of line.assets) { + write(join(publicDir, 'docs-assets', kindDir, docs.slug, line.id, path.replace(/^_assets\//, '')), Buffer.from(asset.content, isText(path) ? 'utf8' : 'latin1')); + } + for (const page of line.pages) { const {data, body} = parseFrontmatter(page.shown.content); const note = page.status === 'missing' || page.status === 'outdated' ? {content: ui(page.lang, page.status === 'missing' ? 'translationMissing' : 'translationOutdated', {language: languages.find((l) => l.code === page.lang)!.name})} : undefined; - const text = - frontmatter(data, { - editUrl: `https://github.com/${entry.repo}/edit/${branchOf.get(page.shown.line)}/docs/${page.shown.path}`, - banner: note, - product: docs.slug, - line: line.id, - status: page.status, - provenance: page.provenance, - provenanceFrom: page.provenanceFrom, - shownLang: page.shown.lang, - }); + const extra = { + editUrl: `https://github.com/${entry.repo}/edit/${branchOf.get(page.shown.line)}/docs/${page.shown.path}`, + banner: note, + product: docs.slug, + line: line.id, + status: page.status, + provenance: page.provenance, + provenanceFrom: page.provenanceFrom, + shownLang: page.shown.lang, + }; const base = join(content, page.lang, kindDir, docs.slug); const address = `/${page.lang}/${kindDir}/${docs.slug}`; - write(join(base, line.id, `${page.id}${page.shown.ext}`), text + transformBody(body, `${address}/${line.id}`)); - // The address without a version shows the newest one, and its links stay in that address. + const finish = (text: string): string => (page.shown.ext === '.mdx' ? addComponentImports(text) : text); + write(join(base, line.id, `${page.id}${page.shown.ext}`), finish(frontmatter(data, extra) + transformBody(body, `${address}/${line.id}`, assetBase))); + // The address without a version shows the newest one, its links stay in that address and the search does not index it twice. if (line.id === newest.id) { - write(join(base, `${page.id}${page.shown.ext}`), text + transformBody(body, address)); + write(join(base, `${page.id}${page.shown.ext}`), finish(frontmatter(data, {...extra, pagefind: false}) + transformBody(body, address, assetBase))); } } } + let icon: string | null = null; + if (product.iconSvg) { + icon = `/product-icons/${docs.slug}.svg`; + write(join(publicDir, 'product-icons', `${docs.slug}.svg`), product.iconSvg); + } + + const answer = await directoryOf(product.component, branchesOf(product.lines), docs.directory?.published); + products.push({ slug: docs.slug, kind: docs.kind, repo: entry.repo, + component: product.component, title: docs.title, summary: docs.summary, - directory: docs.directory ?? {published: 'auto', url: null}, + icon, + directory: {published: answer.published, url: answer.published ? (docs.directory?.url ?? (product.component ? directoryPage(product.component) : null)) : null, releases: answer.releases}, translations: docs.translations ?? {source: 'l10n'}, lines: resolution.lines.map((line) => { const info = product.lines.find((candidate) => candidate.id === line.id)!; - return {id: line.id, label: info.label, branch: info.branch, release: info.release, extends: info.extends, latest: line.id === newest.id, coverage: line.coverage, pages: line.pages.filter((page) => page.lang === sourceCode).length, sections: sectionsOf(line.pages.filter((page) => page.lang === sourceCode).map((page) => page.id))}; + const ids = line.pages.filter((page) => page.lang === sourceCode).map((page) => page.id); + return {id: line.id, label: info.label, branch: info.branch, release: info.release, extends: info.extends, latest: line.id === newest.id, coverage: line.coverage, pages: ids.length, sections: sectionsOf(ids), pageIds: ids}; }), }); } -// One catalog page for each kind and language that has products. -for (const language of languages) { - for (const [kind, dir] of Object.entries(KIND_DIR)) { - const own = products.filter((product) => product.kind === kind); - if (own.length === 0) { - continue; - } - const rows = own.map((product) => { - const title = localised(product.title as Record, language.code, String(product.slug)); - const summary = localised(product.summary as Record, language.code, ''); - return `| [${title}](/${language.code}/${dir}/${product.slug}/) | ${summary} |`; - }); - write( - join(content, language.code, dir, 'index.md'), - `---\ntitle: ${ui(language.code, dir)}\ndescription: ${ui(language.code, `${dir}Description`)}\n---\n\n| ${ui(language.code, 'name')} | ${ui(language.code, 'summary')} |\n| --- | --- |\n${rows.join('\n')}\n`, - ); - } +// The products that are not documented yet, with what the Moodle directory says about each. +const coming: Array> = []; +for (const item of roadmap.filter((candidate) => !documented.has(candidate.component))) { + const answer = await directoryOf(item.component, ['4.5', '5.3'], undefined); + coming.push({...item, published: answer.published}); } for (const language of languages) { @@ -227,13 +271,22 @@ for (const language of languages) { removeStale(join(content, language.code, dir)); } } +removeStale(join(publicDir, 'docs-assets')); +removeStale(join(publicDir, 'product-icons')); + +mkdirSync(dirname(cacheFile), {recursive: true}); +writeFileSync(cacheFile, JSON.stringify(directoryCache, null, 2) + '\n'); + +write(join(root, 'src', 'data', 'products.generated.json'), JSON.stringify({languages: languages.map(({code, name, dir}) => ({code, name, dir: dir ?? 'ltr'})), products, coming}, null, 2) + '\n'); -write(join(root, 'src', 'data', 'products.generated.json'), JSON.stringify({languages: languages.map(({code, name, dir}) => ({code, name, dir: dir ?? 'ltr'})), products}, null, 2) + '\n'); +// A short fingerprint of everything written, so a loop that serves the site knows when to build it again. +writeFileSync(join(root, '.cache', 'sync.hash'), fingerprint.digest('hex').slice(0, 16)); for (const issue of issues) { const where = [issue.line, issue.path].filter(Boolean).join(' '); (issue.level === 'error' ? console.error : console.warn)(`${issue.level.padEnd(7)} ${issue.product}${where ? ` [${where}]` : ''} ${issue.code}: ${issue.message}`); } const errors = issues.filter((issue) => issue.level === 'error').length; -console.log(`${products.length} product(s) synced, ${errors} error(s), ${issues.length - errors} warning(s).`); +const published = products.filter((product) => (product.directory as {published: boolean | null}).published).length; +console.log(`${products.length} product(s) synced (${published} in the Moodle directory), ${coming.length} coming, ${errors} error(s), ${issues.length - errors} warning(s).`); process.exit(errors > 0 ? 1 : 0); diff --git a/tools/to-webp.ts b/tools/to-webp.ts new file mode 100644 index 0000000..b066870 --- /dev/null +++ b/tools/to-webp.ts @@ -0,0 +1,31 @@ +/** + * Converts the screenshots of a folder to WebP, which weighs a fraction of a PNG and looks the same for a screen of an interface. + * usage: node tools/to-webp.ts [name...] + * + * @license GPL-3.0-or-later + */ + +import {mkdirSync, readdirSync, statSync} from 'node:fs'; +import {basename, join, resolve} from 'node:path'; +import sharp from 'sharp'; + +const [from, to, ...only] = process.argv.slice(2); +if (!from || !to) { + throw new Error('usage: node tools/to-webp.ts [name...]'); +} +mkdirSync(resolve(to), {recursive: true}); + +let before = 0; +let after = 0; +for (const file of readdirSync(resolve(from)).filter((name) => name.endsWith('.png'))) { + const name = basename(file, '.png'); + if (only.length > 0 && !only.includes(name)) { + continue; + } + const target = join(resolve(to), `${name}.webp`); + await sharp(join(resolve(from), file)).webp({quality: 86, effort: 6}).toFile(target); + before += statSync(join(resolve(from), file)).size; + after += statSync(target).size; + console.log(`${name}.webp`); +} +console.log(`${Math.round(before / 1024)} KB of PNG became ${Math.round(after / 1024)} KB of WebP`); From dbe4b2769010d3b83b233903daa5e46cdea68ed5 Mon Sep 17 00:00:00 2001 From: hlaelissalt Date: Wed, 11 Nov 2026 21:35:36 +0100 Subject: [PATCH 3/8] feat: footer with people and support, language menu, route guides and the Didactika theme for technical docs The footer is the one of the design system (co-founders, collaborators and funding from GitHub), the language menu filters and scrolls so it can grow, the previous/next pager is gone, the home mark is the one of Didactika Docs, and a Path component gives each reader a guided route. rup/didactika.theme.json holds the colours for the diagrams of the technical documentation. --- .gitignore | 1 + astro.config.ts | 2 + package.json | 4 +- rup/didactika.theme.json | 17 +++ src/components/Footer.astro | 46 ++------ src/components/LanguageMenu.astro | 75 +++++++++++++ src/components/Logo.astro | 16 +++ src/components/PageFrame.astro | 17 +++ src/components/Path.astro | 71 ++++++++++++ src/components/ProjectFoot.astro | 100 +++++++++++++++++ src/components/SiteFooter.astro | 46 -------- src/components/SiteHeader.astro | 23 ++-- src/i18n/en.json | 20 ++-- src/i18n/es.json | 20 ++-- src/layouts/Landing.astro | 4 +- src/lib/site.ts | 30 ++++++ src/pages/[lang]/index.astro | 23 ++-- src/scripts/people.ts | 43 ++++++++ src/styles/didactika.css | 134 ++++++++++++++++++----- tools/lib/markdown.test.ts | 3 +- tools/lib/markdown.ts | 1 + tools/project.ts | 174 ++++++++++++++++++++++++++++++ 22 files changed, 721 insertions(+), 149 deletions(-) create mode 100644 rup/didactika.theme.json create mode 100644 src/components/LanguageMenu.astro create mode 100644 src/components/Logo.astro create mode 100644 src/components/PageFrame.astro create mode 100644 src/components/Path.astro create mode 100644 src/components/ProjectFoot.astro delete mode 100644 src/components/SiteFooter.astro create mode 100644 src/scripts/people.ts create mode 100644 tools/project.ts diff --git a/.gitignore b/.gitignore index e8fb741..e12fc00 100644 --- a/.gitignore +++ b/.gitignore @@ -7,6 +7,7 @@ dist/ /src/content/docs/*/plugins/ /src/content/docs/*/packages/ /src/data/products.generated.json +/src/data/project.generated.json # What the previews of a developer need; see compose.yaml. /preview.refs.json diff --git a/astro.config.ts b/astro.config.ts index 6523558..f0ff6c0 100644 --- a/astro.config.ts +++ b/astro.config.ts @@ -83,6 +83,7 @@ export default defineConfig({ PageTitle: './src/components/PageTitle.astro', Sidebar: './src/components/Sidebar.astro', Footer: './src/components/Footer.astro', + PageFrame: './src/components/PageFrame.astro', }, favicon: '/brand/favicon.ico', head: [ @@ -98,6 +99,7 @@ export default defineConfig({ ], social: [{icon: 'github', label: 'GitHub', href: 'https://github.com/didactika'}], customCss: ['./src/styles/didactika.css'], + pagination: false, sidebar, }), ], diff --git a/package.json b/package.json index 46f2295..ade3c39 100644 --- a/package.json +++ b/package.json @@ -10,8 +10,8 @@ }, "scripts": { "sync": "node tools/sync.ts", - "dev": "node tools/sync.ts && astro dev", - "build": "node tools/sync.ts && astro build", + "dev": "node tools/sync.ts && node tools/project.ts && astro dev", + "build": "node tools/sync.ts && node tools/project.ts && astro build", "preview": "astro preview", "serve": "node tools/serve.ts", "brand": "node tools/build-brand.ts", diff --git a/rup/didactika.theme.json b/rup/didactika.theme.json new file mode 100644 index 0000000..7794dd4 --- /dev/null +++ b/rup/didactika.theme.json @@ -0,0 +1,17 @@ +{ + "preset": "default", + "colors": { + "background": "#FFFFFF", + "text": "#0F172A", + "line": "#475569", + "border": "#00555A", + "primary": "#E6F6F4", + "secondary": "#F1F5F9", + "accent": "#0F766E", + "note": "#FDF3DC", + "levels": ["#A7DDD5", "#C8EEE9", "#E6F6F4", "#F4FBFA"] + }, + "font": "IBM Plex Sans", + "fontSize": 14, + "roundCorner": 8 +} diff --git a/src/components/Footer.astro b/src/components/Footer.astro index 75fbbae..1c88e05 100644 --- a/src/components/Footer.astro +++ b/src/components/Footer.astro @@ -1,46 +1,22 @@ --- /** - * The foot of a page of the documentation: the previous and next pages as cards, the link to edit the page and the licence. - * The pages follow the navigation of the version (see Sidebar.astro). + * The foot of a page of the documentation: the link to edit the page, and the foot of the site (see ProjectFoot.astro). There is no + * "previous / next" here: the way through the documentation is the guide of each product, not the order of its files. */ import MIcon from './MIcon.astro'; import {t} from '../lib/site'; const route = Astro.locals.starlightRoute; const lang = route.lang; -const {prev, next} = route.pagination; const editUrl = route.editUrl; --- - +{ + editUrl && ( + + ) +} diff --git a/src/components/LanguageMenu.astro b/src/components/LanguageMenu.astro new file mode 100644 index 0000000..fa2e8e0 --- /dev/null +++ b/src/components/LanguageMenu.astro @@ -0,0 +1,75 @@ +--- +/** + * The language of the reader. It is a menu with a filter and not a row of buttons, because the languages are data (languages.json) and the + * list will grow: it scrolls, it can be filtered by name or by code, and it says how complete each language is. + */ +import MIcon from './MIcon.astro'; +import {site, t} from '../lib/site'; + +interface Props { + lang: string; + /** The address of the page, to offer the same page in another language. */ + path: string; + /** How complete each language is for the product the reader is in, as a share from 0 to 100. */ + coverage?: Record; +} + +const {lang, path, coverage = {}} = Astro.props; +const languages = site().languages; +const current = languages.find((language) => language.code === lang); +const inLanguage = (code: string): string => path.replace(/^\/[^/]+/, `/${code}`); +const filterable = languages.length > 6; +--- + +
+ + + {lang.toUpperCase()} + + +
+

{t(lang, 'language')} {current?.name}

+ { + filterable && ( + + ) + } + + +
+
+ + diff --git a/src/components/Logo.astro b/src/components/Logo.astro new file mode 100644 index 0000000..41a9acd --- /dev/null +++ b/src/components/Logo.astro @@ -0,0 +1,16 @@ +--- +/** + * The mark of Didactika Docs, built as the one of the design system: the book of Didactika on a white tile, with the handles of a selection + * on its corners and a teal pill that says what the site is ("DOC", where the design system says "UI"). + */ +interface Props { + size?: 'sm' | 'lg' | 'xl'; +} +const {size = 'sm'} = Astro.props; +--- + + diff --git a/src/components/PageFrame.astro b/src/components/PageFrame.astro new file mode 100644 index 0000000..b7f4c53 --- /dev/null +++ b/src/components/PageFrame.astro @@ -0,0 +1,17 @@ +--- +/** + * The frame of a page of the documentation: Starlight's own, with the foot of the site added after the content, so it takes the whole width + * of the page and not the column of the text (see ProjectFoot.astro). + */ +import Default from '@astrojs/starlight/components/PageFrame.astro'; +import ProjectFoot from './ProjectFoot.astro'; + +const lang = Astro.locals.starlightRoute.lang; +--- + + + + + + + diff --git a/src/components/Path.astro b/src/components/Path.astro new file mode 100644 index 0000000..257f8da --- /dev/null +++ b/src/components/Path.astro @@ -0,0 +1,71 @@ +--- +/** + * A route through the documentation for one kind of reader: the pages to read, in order, each with its title and what it is for. The pages + * are named by their identifier inside the version (`getting-started/installation`), so the route follows the version the reader is in. + * + * + */ +import {getCollection} from 'astro:content'; +import MIcon from './MIcon.astro'; +import {pageIdOf, productUrl, site, t} from '../lib/site'; + +interface Props { + title: string; + icon?: string; + /** How long the route takes, as text ("15 min"). */ + time?: string; + /** What the reader is after. */ + goal?: string; + pages: string[]; +} + +const {title, icon = 'route-rounded', time, goal, pages} = Astro.props; +const route = Astro.locals.starlightRoute; +const data = route.entry.data as {product?: string; line?: string}; +const product = site().products.find((candidate) => candidate.slug === data.product); +const line = product?.lines.find((candidate) => candidate.id === data.line); +const lang = route.lang; + +const entries = await getCollection('docs'); +const steps = pages.flatMap((page) => { + if (!product || !line) { + return []; + } + const wanted = (code: string) => `${code}/${product.kind === 'plugin' ? 'plugins' : 'packages'}/${product.slug}/${line.id}/${page}`; + const entry = entries.find((candidate) => candidate.id === wanted(lang)) ?? entries.find((candidate) => candidate.id === wanted('en')); + if (!entry) { + return []; + } + const summary = (entry.data as {description?: string}).description ?? ''; + return [{href: `${productUrl(lang, product, line.id)}${page}/`, title: entry.data.title, summary, id: pageIdOf(entry.id, product.slug, line.id)}]; +}); +--- + +{ + steps.length > 0 && ( +
+
+ +
+

{title}

+ {goal &&

{goal}

} +
+ {time && {time}} +
+
    + { + steps.map((step) => ( +
  1. + + {step.title} + {step.summary && {step.summary}} + + +
  2. + )) + } +
+
{t(lang, 'pathHint')}
+
+ ) +} diff --git a/src/components/ProjectFoot.astro b/src/components/ProjectFoot.astro new file mode 100644 index 0000000..34653fd --- /dev/null +++ b/src/components/ProjectFoot.astro @@ -0,0 +1,100 @@ +--- +/** + * The foot of every page, the same as the one of the design system: what Didactika is, its co-founders, its collaborators, where to find it + * and how to support it. It stays one row however much the project grows: the collaborators are cut at a maximum and the rest is a "+ n" + * that leads to the full list. Everything comes from GitHub (tools/project.ts). + */ +import Logo from './Logo.astro'; +import MIcon from './MIcon.astro'; +import {project, t} from '../lib/site'; + +interface Props { + lang: string; +} + +const {lang} = Astro.props; +const {organisation, founders, contributors, funding} = project(); +const max = 8; +const cofounders = new Set(founders.map((person) => person.login.toLowerCase())); +const seed = contributors.filter((person) => !cofounders.has(person.login.toLowerCase())); +const shown = seed.slice(0, max); +const host = organisation.website ? new URL(organisation.website).host : null; +const avatar = (url: string): string => `${url}${url.includes('?') ? '&' : '?'}s=64`; +--- + + + + + + diff --git a/src/components/SiteFooter.astro b/src/components/SiteFooter.astro deleted file mode 100644 index 5592b2b..0000000 --- a/src/components/SiteFooter.astro +++ /dev/null @@ -1,46 +0,0 @@ ---- -// The foot of the home and of the catalog. -import MIcon from './MIcon.astro'; -import {localised, productUrl, site, t} from '../lib/site'; - -interface Props { - lang: string; -} - -const {lang} = Astro.props; -const products = site().products; ---- - - diff --git a/src/components/SiteHeader.astro b/src/components/SiteHeader.astro index 493782b..5e54442 100644 --- a/src/components/SiteHeader.astro +++ b/src/components/SiteHeader.astro @@ -3,9 +3,11 @@ * The header of the site, the same on the home, on the catalog and on every page of the documentation: the mark of Didactika, the product * and version the reader is in, the search, the language, the colour theme and the repository of the organisation. */ +import LanguageMenu from './LanguageMenu.astro'; +import Logo from './Logo.astro'; import MIcon from './MIcon.astro'; import SiteSearch from './SiteSearch.astro'; -import {localised, productUrl, site, t} from '../lib/site'; +import {localised, productUrl, project, site, t} from '../lib/site'; interface Props { lang: string; @@ -23,8 +25,7 @@ const data = site(); const product = data.products.find((candidate) => candidate.slug === productSlug); const current = product?.lines.find((candidate) => candidate.id === line); -/** The same page in another language: the first segment of the address is the language. */ -const inLanguage = (code: string): string => path.replace(/^\/[^/]+/, `/${code}`); +const funding = project().funding; /** The same page in another version when it exists there, and the overview of that version when it does not. */ const inVersion = (id: string): string => { @@ -38,7 +39,7 @@ const logo = '/brand/didactika-logo.png';
- + Didactika Docs{t(lang, 'brandBy')} @@ -74,13 +75,15 @@ const logo = '/brand/didactika-logo.png';
- + ) + }
diff --git a/src/lib/site.ts b/src/lib/site.ts index 2fd869c..370d1bd 100644 --- a/src/lib/site.ts +++ b/src/lib/site.ts @@ -71,6 +71,36 @@ export function site(): SiteData { return cached; } +export interface PersonData { + login: string; + name: string | null; + url: string; + avatar: string; + contributions: number; +} + +/** What the footer says about Didactika: its people and how to support it (tools/project.ts). */ +export interface ProjectData { + organisation: {login: string; name: string; website: string | null; avatar: string | null; url: string; repositoriesUrl: string; peopleUrl: string}; + founders: PersonData[]; + contributors: PersonData[]; + funding: {platform: string; url: string} | null; +} + +const projectFile = join(process.cwd(), 'src', 'data', 'project.generated.json'); +const emptyProject: ProjectData = { + organisation: {login: 'didactika', name: 'Didactika', website: 'https://didactika.org', avatar: null, url: 'https://github.com/didactika', repositoriesUrl: 'https://github.com/orgs/didactika/repositories', peopleUrl: 'https://github.com/orgs/didactika/people'}, + founders: [], + contributors: [], + funding: {platform: 'Ko-fi', url: 'https://ko-fi.com/didactika'}, +}; +let project_: ProjectData | undefined; + +export function project(): ProjectData { + project_ ??= existsSync(projectFile) ? (JSON.parse(readFileSync(projectFile, 'utf8')) as ProjectData) : emptyProject; + return project_; +} + const dictionaries = import.meta.glob>('../i18n/*.json', {eager: true, import: 'default'}); const dictionary = (code: string): Record => dictionaries[`../i18n/${code}.json`] ?? {}; diff --git a/src/pages/[lang]/index.astro b/src/pages/[lang]/index.astro index c9c9713..6958f83 100644 --- a/src/pages/[lang]/index.astro +++ b/src/pages/[lang]/index.astro @@ -2,7 +2,7 @@ /** The home of the portal: what it is, what is documented and how every documentation is organised. */ import MIcon from '../../components/MIcon.astro'; import ProductCard from '../../components/ProductCard.astro'; -import DirectoryChip from '../../components/DirectoryChip.astro'; +import Logo from '../../components/Logo.astro'; import Landing from '../../layouts/Landing.astro'; import {latestLine, localised, productUrl, site, t} from '../../lib/site'; @@ -41,17 +41,16 @@ const organised = [
diff --git a/src/scripts/people.ts b/src/scripts/people.ts new file mode 100644 index 0000000..fb02db9 --- /dev/null +++ b/src/scripts/people.ts @@ -0,0 +1,43 @@ +// The collaborators of the footer: the people who contributed to any repository of the organisation (rendered when the site was built) plus the +// public members of the organisation on GitHub, read when the page opens and kept for half an hour so a visit does not spend the limit GitHub puts +// on anonymous requests. If the members cannot be read, the footer keeps what the build rendered. +/** A person of the footer: a GitHub login with the address of the profile and of the avatar. */ +interface Person { login: string; url: string; avatar: string } +interface GitHubUser { login: string; html_url: string; avatar_url: string } +interface Cached { org: string; at: number; list: Person[] } + +const KEY = 'd-people'; +const TTL = 30 * 60 * 1000; +const entities: Record = {'&': '&', '<': '<', '>': '>', '"': '"'}; +const esc = (s: unknown): string => String(s).replace(/[&<>"]/g, (c) => entities[c]); + +const members = async(org: string): Promise => { + try { + const cached = JSON.parse(sessionStorage.getItem(KEY) ?? 'null') as Cached | null; + if (cached && cached.org === org && Date.now() - cached.at < TTL) { return cached.list; } + } catch (error) { /* no storage: ask every time */ } + const response = await fetch(`https://api.github.com/orgs/${org}/public_members?per_page=100`, {headers: {Accept: 'application/vnd.github+json'}}); + if (!response.ok) { throw new Error(String(response.status)); } + const list = ((await response.json()) as GitHubUser[]).map((u) => ({login: u.login, url: u.html_url, avatar: u.avatar_url})); + try { sessionStorage.setItem(KEY, JSON.stringify({org, at: Date.now(), list})); } catch (error) { /* optional */ } + return list; +}; + +document.querySelectorAll('[data-people]').forEach(async(box) => { + const stack = box.querySelector('[data-people-list]'); + if (!stack) { return; } + const skip = (box.dataset.exclude || '').toLowerCase().split(',').filter(Boolean); + const max = Number(box.dataset.max) || 8; + let seed: Person[] = []; + try { seed = JSON.parse(box.dataset.seed || '[]') as Person[]; } catch (error) { /* nothing rendered by the build */ } + try { + const live = await members(box.dataset.org ?? ''); + const known = new Set(seed.map((p) => p.login.toLowerCase())); + const people = [...seed, ...live.filter((p) => !known.has(p.login.toLowerCase()))].filter((p) => p.avatar && !skip.includes(p.login.toLowerCase())); + stack.innerHTML = people.slice(0, max).map((p) => ``).join('') + + (people.length > max ? `+${people.length - max}` : ''); + box.classList.toggle('has-people', people.length > 0); + } catch (error) { + /* the members are not available: what the build rendered stays */ + } +}); diff --git a/src/styles/didactika.css b/src/styles/didactika.css index 893c582..ea37806 100644 --- a/src/styles/didactika.css +++ b/src/styles/didactika.css @@ -129,7 +129,6 @@ a { text-underline-offset: 0.2em; } display: flex; align-items: center; gap: 0.75rem; width: 100%; height: 100%; padding-inline: 1rem; } .d-brand { display: inline-flex; align-items: center; gap: 0.65rem; color: var(--ink); text-decoration: none; white-space: nowrap; } -.d-brand img { width: 2.2rem; height: 2.2rem; border-radius: 10px; } .d-brand .d-wordmark { display: grid; line-height: 1.05; } .d-brand .d-wordmark b { font: 700 1.05rem/1.1 var(--display); letter-spacing: -0.01em; } .d-brand .d-wordmark small { font: 500 0.72rem/1.2 var(--font); color: var(--accent); } @@ -296,30 +295,74 @@ a.d-chip:hover { color: var(--ink); } /* ----------------------------------------------------------------- footer ---- */ -.d-pagefoot { margin-top: 3.5rem; padding-top: 1.6rem; border-top: 1px solid var(--line); } -.d-pager { display: grid; grid-template-columns: 1fr 1fr; gap: 1rem; } -.d-pager-link { - display: grid; gap: 0.3rem; padding: 1rem 1.2rem; border: 1px solid var(--line); border-radius: var(--radius); background: var(--panel); - color: var(--ink); text-decoration: none; transition: border-color 0.15s; -} -.d-pager-link:hover { border-color: color-mix(in srgb, var(--accent) 55%, var(--line)); } -.d-pager-link.next { text-align: end; grid-column: 2; } -.d-pager-dir { display: flex; align-items: center; gap: 0.35rem; color: var(--muted); font: 600 0.72rem var(--font); letter-spacing: 0.06em; text-transform: uppercase; } -.d-pager-link.next .d-pager-dir { justify-content: flex-end; } -.d-pager-link b { font: 600 1.05rem var(--display); color: var(--accent); } -.d-pagefoot-meta { display: flex; flex-wrap: wrap; align-items: center; justify-content: space-between; gap: 0.8rem; margin-top: 1.4rem; color: var(--muted); font-size: 0.82rem; } -.d-pagefoot-meta a { display: inline-flex; align-items: center; gap: 0.4rem; color: var(--muted); text-decoration: none; } -.d-pagefoot-meta a:hover { color: var(--accent); } - -.d-foot { margin-top: 3rem; border-top: 1px solid var(--line); background: var(--panel); } -.d-foot-in { display: grid; grid-template-columns: 1.4fr repeat(3, 1fr); gap: 2rem; width: min(72rem, 100%); margin: 0 auto; padding: 2.2rem 1.25rem; } -.d-foot h4 { margin: 0 0 0.7rem; font: 700 0.72rem/1.2 var(--font); letter-spacing: 0.08em; text-transform: uppercase; color: var(--ink); } -.d-foot ul { display: grid; gap: 0.4rem; margin: 0; padding: 0; list-style: none; } -.d-foot a { color: var(--muted); text-decoration: none; font-size: 0.875rem; } -.d-foot a:hover { color: var(--accent); } -.d-foot p { margin: 0.7rem 0 0; color: var(--muted); font-size: 0.85rem; max-width: 22rem; } -.d-foot-bar { border-top: 1px solid var(--line); padding: 0.9rem 1.25rem; text-align: center; color: var(--muted); font-size: 0.78rem; } -@media (max-width: 52rem) { .d-foot-in { grid-template-columns: 1fr 1fr; } } +.d-pagefoot { display: flex; justify-content: flex-end; margin-top: 3rem; padding-top: 1.2rem; border-top: 1px solid var(--line); font-size: 0.85rem; } +.d-pagefoot a { display: inline-flex; align-items: center; gap: 0.4rem; color: var(--muted); text-decoration: none; } +.d-pagefoot a:hover { color: var(--accent); } + +.d-footer { position: relative; z-index: 31; margin-top: 3rem; border-top: 1px solid var(--line); background: var(--panel); } +.d-footer-in { display: grid; gap: 1.1rem; max-width: 76rem; margin: 0 auto; padding: 1.5rem 1.25rem 1rem; } +.d-foot-row { display: flex; flex-wrap: wrap; align-items: center; justify-content: space-between; gap: 1.1rem 2rem; } +.d-foot-brand { display: flex; align-items: center; gap: 0.85rem; min-width: 0; max-width: 22rem; color: var(--ink); text-decoration: none; } +.d-foot-brand b { display: block; font: 700 0.98rem/1.2 var(--display); } +.d-foot-brand span span { display: block; margin-top: 0.15rem; color: var(--muted); font-size: 0.8rem; line-height: 1.4; } +.d-foot-people { display: flex; flex-wrap: wrap; align-items: center; gap: 0.9rem 1.6rem; } +.d-founders { display: flex; flex-wrap: wrap; gap: 0.5rem; margin: 0; padding: 0; list-style: none; } +.d-founder { display: flex; align-items: center; gap: 0.55rem; padding: 0.28rem 0.85rem 0.28rem 0.28rem; border: 1px solid var(--line); border-radius: 999px; background: var(--panel-2); color: var(--ink); text-decoration: none; } +.d-founder:hover { border-color: color-mix(in srgb, var(--accent) 55%, var(--line)); background: var(--accent-soft); } +.d-founder img { width: 2rem; height: 2rem; border-radius: 50%; object-fit: cover; } +.d-founder b { display: block; font: 600 0.82rem/1.15 var(--font); } +.d-founder small { display: block; color: var(--muted); font-size: 0.68rem; } +.d-collabs { display: flex; align-items: center; gap: 0.6rem; } +.d-collabs-label { display: none; color: var(--muted); font: 600 0.68rem/1 var(--font); letter-spacing: 0.08em; text-transform: uppercase; } +.d-collabs.has-people .d-collabs-label { display: inline; } +.d-stack { display: flex; align-items: center; padding-inline-start: 0.4rem; } +.d-stack a { display: grid; place-items: center; width: 2rem; height: 2rem; margin-inline-start: -0.4rem; border-radius: 50%; background: var(--panel-2); box-shadow: 0 0 0 2px var(--panel); color: var(--muted); font: 700 0.68rem var(--font); text-decoration: none; transition: transform 0.12s ease; } +.d-stack a:hover { transform: translateY(-2px); z-index: 1; } +.d-stack img { width: 100%; height: 100%; border-radius: 50%; object-fit: cover; } +.d-collab-add { display: grid; place-items: center; width: 2rem; height: 2rem; border: 1.5px dashed color-mix(in srgb, var(--muted) 60%, var(--line)); border-radius: 50%; color: var(--muted); text-decoration: none; } +.d-collab-add:hover { border-color: var(--accent); color: var(--accent); background: var(--accent-soft); } +.d-foot-links { display: flex; flex-wrap: wrap; gap: 0.4rem; } +.d-foot-links a { display: inline-flex; align-items: center; gap: 0.5rem; height: 2.2rem; padding: 0 0.85rem; border: 1px solid var(--line); border-radius: 10px; color: var(--ink); font: 600 0.8rem/1 var(--font); text-decoration: none; } +.d-foot-links a:hover { border-color: color-mix(in srgb, var(--accent) 55%, var(--line)); background: var(--accent-soft); } +.d-foot-links .mi { color: var(--muted); } +.d-footer-bar { display: flex; flex-wrap: wrap; align-items: center; justify-content: space-between; gap: 0.4rem 1.25rem; padding-top: 0.9rem; border-top: 1px solid var(--line); color: var(--muted); font-size: 0.78rem; } +.d-support-link { display: inline-flex; align-items: center; gap: 0.4rem; color: var(--muted); text-decoration: none; } +.d-support-link .mi { color: #e11d48; } +.d-support-link:hover { color: var(--ink); } +@media (max-width: 760px) { .d-foot-people { width: 100%; } } + +/* The mark: the book on a white tile, the handles of a selection and the pill of what the site is. */ +.d-logo { position: relative; display: grid; place-items: center; width: 2.25rem; height: 2.25rem; border-radius: 11px; background: #fff; box-shadow: 0 0 0 1px var(--line), 0 2px 8px rgb(0 85 90 / 18%); flex: none; } +.d-logo img { width: 74%; height: 74%; display: block; border-radius: 0; } +.d-logo .h { position: absolute; width: 0.3rem; height: 0.3rem; border-radius: 1.5px; background: #fff; border: 1.2px solid #0f766e; } +.d-logo .h1 { left: -2px; top: -2px; } .d-logo .h2 { right: -2px; top: -2px; } .d-logo .h3 { left: -2px; bottom: -2px; } +.d-logo-tag { position: absolute; right: -0.55rem; bottom: -0.4rem; padding: 0.14rem 0.3rem; border-radius: 6px; background: #0f766e; color: #fff; font: 700 0.46rem/1 var(--display); letter-spacing: 0.03em; box-shadow: 0 0 0 2px var(--panel); } +.d-logo.is-lg { width: 2.9rem; height: 2.9rem; border-radius: 13px; } +.d-logo.is-lg .d-logo-tag { font-size: 0.54rem; right: -0.6rem; bottom: -0.45rem; } +.d-logo.is-xl { width: clamp(5.5rem, 11vw, 8.25rem); height: clamp(5.5rem, 11vw, 8.25rem); border-radius: clamp(1.2rem, 2.4vw, 1.9rem); box-shadow: 0 8px 28px rgb(0 85 90 / 18%); } +.d-logo.is-xl .h { width: 0.55rem; height: 0.55rem; border-width: 1.6px; } +.d-logo.is-xl .h1 { left: -3px; top: -3px; } .d-logo.is-xl .h2 { right: -3px; top: -3px; } .d-logo.is-xl .h3 { left: -3px; bottom: -3px; } +.d-logo.is-xl .d-logo-tag { font-size: clamp(0.7rem, 1.5vw, 1.05rem); right: -0.9rem; bottom: -0.7rem; padding: 0.22rem 0.6rem; border-radius: 10px; box-shadow: 0 0 0 3px #fff; } +.d-brand .d-logo { border-radius: 11px; } + +/* The language menu and the support button of the header. */ +.d-sep { width: 1px; height: 1.6rem; background: var(--line); } +.d-heart .mi { color: #e11d48; } +.d-heart:hover { border-color: #fda4af; background: color-mix(in srgb, #e11d48 10%, var(--panel)); } +.d-dd > summary .d-code { font: 600 0.78rem var(--mono); } +.d-lang .d-dd-menu { inset-inline-start: auto; inset-inline-end: 0; width: 17rem; max-width: calc(100vw - 2rem); } +.d-menu-title { display: flex; align-items: baseline; justify-content: space-between; margin: 0; padding: 0.35rem 0.7rem 0.2rem; color: var(--muted); font: 600 0.68rem var(--font); letter-spacing: 0.08em; text-transform: uppercase; } +.d-menu-title small { font-size: 0.72rem; letter-spacing: 0; text-transform: none; } +.d-lang-filter { display: flex; align-items: center; gap: 0.5rem; margin: 0.3rem 0.3rem 0.2rem; padding: 0 0.65rem; border: 1px solid var(--line); border-radius: 10px; background: var(--panel-2); color: var(--muted); } +.d-lang-filter:focus-within { border-color: var(--accent); } +.d-lang-filter input { flex: 1; min-width: 0; height: 2.1rem; border: 0; outline: 0; background: transparent; color: var(--ink); font: 400 0.875rem var(--font); } +.d-lang-list { display: grid; gap: 2px; max-height: 18rem; margin: 0; padding: 0.2rem 0 0; overflow-y: auto; list-style: none; } +.d-lang-list li[hidden] { display: none; } +.d-lang-list a { justify-content: flex-start; } +.d-lang-code { display: inline-grid; place-items: center; min-width: 2rem; height: 1.5rem; border-radius: 6px; background: var(--panel-2); color: var(--muted); font: 600 0.68rem var(--mono); text-transform: uppercase; } +.d-lang-list a[aria-current='true'] .d-lang-code { background: var(--accent); color: var(--accent-ink); } +.d-lang-name { flex: 1; } +.d-lang-empty { margin: 0; padding: 0.8rem; color: var(--muted); font-size: 0.85rem; } /* -------------------------------------------------------------- screenshots ---- */ @@ -366,8 +409,11 @@ a.d-chip:hover { color: var(--ink); } box-shadow: var(--shadow); backdrop-filter: blur(6px); } .d-hero-card .d-mono { font: 500 0.72rem var(--mono); color: var(--muted); } -.d-hero-tile { display: grid; place-items: center; margin: 1rem auto; width: 9rem; height: 9rem; border-radius: 28px; background: #fff; box-shadow: var(--shadow); } -.d-hero-tile img { width: 6.4rem; height: auto; } +.d-hero-mark { display: grid; place-items: center; margin: 1.6rem auto 1.8rem; } +.d-hero-products { display: flex; flex-wrap: wrap; justify-content: center; gap: 0.6rem; margin-bottom: 1rem; } +.d-hero-products .d-tile { width: 2.6rem; height: 2.6rem; border-radius: 12px; } +.d-hero-products .d-tile img { width: 1.6rem; height: 1.6rem; } +.d-hero-products .d-tile.ghost { background: transparent; border: 1.5px dashed var(--line); color: var(--muted); box-shadow: none; } .d-hero-chips { display: flex; flex-wrap: wrap; justify-content: center; gap: 0.45rem; } .d-stats { display: grid; grid-template-columns: repeat(4, 1fr); gap: 1px; margin-top: -2.2rem; position: relative; border: 1px solid var(--line); border-radius: var(--radius-lg); background: var(--line); overflow: hidden; box-shadow: var(--shadow); } @@ -432,9 +478,8 @@ a.d-chip:hover { color: var(--ink); } .d-product-head .d-tile { width: 4.2rem; height: 4.2rem; border-radius: 18px; } .d-product-head .d-tile img { width: 2.8rem; height: 2.8rem; } -@media print { .d-head, .d-foot { display: none; } } +@media print { .d-head, .d-footer { display: none; } } -.d-foot-line { margin: 0; color: var(--muted); font-size: 0.8rem; } .d-skip { position: absolute; left: -999px; top: 0.5rem; z-index: 100; padding: 0.5rem 0.75rem; background: var(--accent); color: var(--accent-ink); border-radius: 8px; } .d-skip:focus { left: 0.5rem; } @@ -454,3 +499,34 @@ a.d-feature:hover { border-color: color-mix(in srgb, var(--accent) 55%, var(--li .d-feature-go { position: absolute; top: 1.2rem; inset-inline-end: 1.1rem; color: var(--accent); opacity: 0.8; } .d-fact b a { color: var(--accent); text-decoration: none; font: 500 0.8rem var(--mono); overflow-wrap: anywhere; } + +/* -------------------------------------------------------- routes and sections ---- */ + +.d-path { margin: 1.4rem 0; border: 1px solid var(--line); border-radius: var(--radius-lg); background: var(--panel); overflow: hidden; } +.d-path > header { display: flex; align-items: center; gap: 0.9rem; padding: 1rem 1.2rem; border-bottom: 1px solid var(--line); background: var(--panel-2); } +.d-path > header > div { flex: 1; min-width: 0; } +.d-path h3 { margin: 0; font: 700 1.05rem/1.3 var(--display); } +.d-path header p { margin: 0.15rem 0 0; color: var(--muted); font-size: 0.85rem; } +.d-path ol { margin: 0; padding: 0.5rem 0; list-style: none; counter-reset: step; } +.d-path li { position: relative; display: flex; align-items: center; gap: 0.9rem; padding: 0.7rem 1.2rem 0.7rem 3.6rem; counter-increment: step; } +.d-path li::before { + content: counter(step); position: absolute; inset-inline-start: 1.2rem; top: 50%; display: grid; place-items: center; width: 1.7rem; height: 1.7rem; margin-top: -0.85rem; + border-radius: 50%; background: var(--accent-soft); color: var(--accent); font: 700 0.8rem var(--display); z-index: 1; +} +.d-path li::after { content: ''; position: absolute; inset-inline-start: calc(1.2rem + 0.85rem - 1px); top: 0; bottom: 0; width: 2px; background: var(--line); } +.d-path li:first-child::after { top: 50%; } +.d-path li:last-child::after { bottom: 50%; } +.d-path li:only-child::after { display: none; } +.d-path li a { flex: 1; display: grid; gap: 0.1rem; color: var(--ink); text-decoration: none; } +.d-path li a b { font: 600 0.95rem var(--font); } +.d-path li a span { color: var(--muted); font-size: 0.84rem; } +.d-path li a:hover b { color: var(--accent); } +.d-path li > .mi { color: var(--muted); } +.d-path li:hover { background: var(--panel-2); } +.d-path > footer { padding: 0.7rem 1.2rem; border-top: 1px solid var(--line); color: var(--muted); font-size: 0.8rem; } +.d-paths { display: grid; gap: 1.2rem; grid-template-columns: repeat(auto-fit, minmax(22rem, 1fr)); align-items: start; margin: 1.4rem 0; } +.d-paths .d-path { margin: 0; } + +/* The table of contents gives way to the foot (see ProjectFoot.astro). */ +.right-sidebar { height: calc(100vh - var(--sl-nav-height, 3.75rem) - var(--d-foot-overlap, 0px)); } +.d-footer { margin-top: 4rem; } diff --git a/tools/lib/markdown.test.ts b/tools/lib/markdown.test.ts index ab458a9..f78fef9 100644 --- a/tools/lib/markdown.test.ts +++ b/tools/lib/markdown.test.ts @@ -82,9 +82,10 @@ describe('addComponentImports', () => { }); it('imports the components of the site by their default export', () => { - const out = addComponentImports(' '); + const out = addComponentImports(' '); assert.ok(out.includes("import MIcon from '/src/components/MIcon.astro';")); assert.ok(out.includes("import Screenshot from '/src/components/Screenshot.astro';")); + assert.ok(out.includes("import Path from '/src/components/Path.astro';")); }); it('leaves a page that uses none as it is, and ignores a component named inside code', () => { diff --git a/tools/lib/markdown.ts b/tools/lib/markdown.ts index 9eaf869..0ec62d0 100644 --- a/tools/lib/markdown.ts +++ b/tools/lib/markdown.ts @@ -66,6 +66,7 @@ const COMPONENTS: Array<{names: string[]; from: string; named: boolean}> = [ {names: ['Screenshot'], from: '/src/components/Screenshot.astro', named: false}, {names: ['FeatureGrid'], from: '/src/components/FeatureGrid.astro', named: false}, {names: ['Feature'], from: '/src/components/Feature.astro', named: false}, + {names: ['Path'], from: '/src/components/Path.astro', named: false}, ]; /** Adds, before the content of an MDX page, the imports of the components it uses. */ diff --git a/tools/project.ts b/tools/project.ts new file mode 100644 index 0000000..eea6c9e --- /dev/null +++ b/tools/project.ts @@ -0,0 +1,174 @@ +/** + * Collects from GitHub what the footer says about Didactika, so no list of people has to be kept by hand, and writes it to + * src/data/project.generated.json (not committed): + * + * - the organisation: name, website, avatar and the addresses of its repositories and people; + * - the co-founders, who are the only people named here, with the name each one has on GitHub; + * - the collaborators: everyone who contributed to a public repository of the organisation; + * - the funding: what the FUNDING.yml of this repository, or of the `.github` repository of the organisation, says (it is also what + * GitHub uses for its Sponsor button). + * + * It runs before every build and the Pages workflow builds every day, so the site follows GitHub. When GitHub does not answer, the file of + * the last build is kept and the build does not fail because of it. DOCS_NO_FETCH=1 skips it (the Docker preview). + * + * usage: node tools/project.ts + * + * @license GPL-3.0-or-later + */ + +import {execSync} from 'node:child_process'; +import {existsSync, mkdirSync, readFileSync, writeFileSync} from 'node:fs'; +import {dirname, join, resolve} from 'node:path'; + +export interface Person { + login: string; + name: string | null; + url: string; + avatar: string; + contributions: number; +} + +export interface Funding { + platform: string; + url: string; +} + +export interface Project { + at: string | null; + organisation: {login: string; name: string; website: string | null; avatar: string | null; url: string; repositoriesUrl: string; peopleUrl: string}; + founders: Person[]; + contributors: Person[]; + funding: Funding | null; +} + +/** The co-founders of Didactika. Everyone else is a collaborator and comes from GitHub. */ +export const COFOUNDERS = ['E2RD0', 'hector-ae21']; +const ORG = 'didactika'; + +interface ApiUser { + login: string; + name?: string | null; + html_url: string; + avatar_url: string; + type: string; + contributions?: number; +} +interface ApiRepo { + name: string; + fork: boolean; + archived: boolean; +} + +const run = (command: string): string => { + try { + return execSync(command, {encoding: 'utf8', stdio: ['ignore', 'pipe', 'ignore']}).trim(); + } catch { + return ''; + } +}; + +const token = (): string => process.env.GH_TOKEN || process.env.GITHUB_TOKEN || run('gh auth token'); + +const github = async (path: string): Promise => { + const headers: Record = {Accept: 'application/vnd.github+json', 'User-Agent': 'didactika-docs'}; + const key = token(); + if (key) { + headers.Authorization = `Bearer ${key}`; + } + const response = await fetch(`https://api.github.com${path}`, {headers}); + if (!response.ok) { + throw new Error(`${response.status} ${path}`); + } + return response.json() as Promise; +}; + +/** The first way to support the project that a FUNDING.yml names. */ +const PLATFORMS: Array<[string, string, (handle: string) => string]> = [ + ['ko_fi', 'Ko-fi', (handle) => `https://ko-fi.com/${handle}`], + ['patreon', 'Patreon', (handle) => `https://www.patreon.com/${handle}`], + ['open_collective', 'Open Collective', (handle) => `https://opencollective.com/${handle}`], + ['buy_me_a_coffee', 'Buy Me a Coffee', (handle) => `https://buymeacoffee.com/${handle}`], + ['liberapay', 'Liberapay', (handle) => `https://liberapay.com/${handle}`], + ['github', 'GitHub Sponsors', (handle) => `https://github.com/sponsors/${handle}`], +]; + +export function parseFunding(yaml: string): Funding | null { + for (const [key, platform, url] of PLATFORMS) { + const hit = yaml.match(new RegExp(`^\\s*${key}\\s*:\\s*\\[?\\s*["']?([^"'\\]\\s,]+)`, 'm')); + if (hit?.[1]) { + return {platform, url: url(hit[1])}; + } + } + return null; +} + +const fundingOf = async (repo: string, path: string): Promise => { + const file = await github<{content: string; encoding: string}>(`/repos/${ORG}/${repo}/contents/${path}`).catch(() => null); + return file ? parseFunding(Buffer.from(file.content, file.encoding as BufferEncoding).toString('utf8')) : null; +}; + +const empty = (): Project => ({ + at: null, + organisation: {login: ORG, name: 'Didactika', website: 'https://didactika.org', avatar: null, url: `https://github.com/${ORG}`, repositoriesUrl: `https://github.com/orgs/${ORG}/repositories`, peopleUrl: `https://github.com/orgs/${ORG}/people`}, + founders: [], + contributors: [], + funding: {platform: 'Ko-fi', url: `https://ko-fi.com/${ORG}`}, +}); + +export async function collect(): Promise { + const org = await github<{login: string; name: string | null; blog: string | null; avatar_url: string; html_url: string}>(`/orgs/${ORG}`); + const repos = (await github(`/orgs/${ORG}/repos?type=public&per_page=100`)).filter((repo) => !repo.fork && !repo.archived); + + const founders: Person[] = []; + for (const login of COFOUNDERS) { + const user = await github(`/users/${login}`); + founders.push({login: user.login, name: user.name ?? null, url: user.html_url, avatar: user.avatar_url, contributions: 0}); + } + + const totals = new Map(); + for (const repo of repos) { + const users = await github(`/repos/${ORG}/${repo.name}/contributors?per_page=100`).catch(() => [] as ApiUser[]); + for (const user of users) { + if (user.type !== 'User') { + continue; + } + const known = totals.get(user.login) ?? {login: user.login, name: null, url: user.html_url, avatar: user.avatar_url, contributions: 0}; + known.contributions += user.contributions ?? 0; + totals.set(user.login, known); + } + } + + const funding = (await fundingOf('docs', '.github/FUNDING.yml')) ?? (await fundingOf('.github', '.github/FUNDING.yml')) ?? (await fundingOf('.github', 'FUNDING.yml')) ?? empty().funding; + + return { + at: new Date().toISOString(), + organisation: {...empty().organisation, login: org.login, name: org.name ?? org.login, website: org.blog || null, avatar: org.avatar_url, url: org.html_url}, + founders, + contributors: [...totals.values()].sort((a, b) => b.contributions - a.contributions), + funding, + }; +} + +if (import.meta.main) { + const root = resolve(import.meta.dirname, '..'); + const out = join(root, 'src', 'data', 'project.generated.json'); + mkdirSync(dirname(out), {recursive: true}); + if (process.env.DOCS_NO_FETCH) { + if (!existsSync(out)) { + writeFileSync(out, JSON.stringify(empty(), null, 1) + '\n'); + } + console.log('project: not fetched (DOCS_NO_FETCH)'); + } else { + try { + const project = await collect(); + writeFileSync(out, JSON.stringify(project, null, 1) + '\n'); + console.log(`project: ${project.founders.length} founders, ${project.contributors.length} collaborators${project.funding ? `, funding on ${project.funding.platform}` : ''}`); + } catch (error) { + if (!existsSync(out)) { + writeFileSync(out, JSON.stringify(empty(), null, 1) + '\n'); + } + console.log(`project: kept the last data (${error instanceof Error ? error.message : String(error)})`); + } + } + JSON.parse(readFileSync(out, 'utf8')); +} From a3af4d43176a2784da636cbb4ea8096486c97c69 Mon Sep 17 00:00:00 2001 From: hlaelissalt Date: Wed, 11 Nov 2026 21:45:50 +0100 Subject: [PATCH 4/8] feat: technical documentation in the portal, routes for each reader, collapsed sections and the notice to deploy The synchronisation reads the technical documentation of a product (README as the index of a folder, diagrams and tables next to a page, relative links, the first heading as the title), the sidebar orders it as the method does, the home invites to support the project and credits rup-flow Pro, and the workflows give the build the token the footer needs. --- .github/workflows/ci.yml | 3 ++ .github/workflows/pages.yml | 5 ++- README.md | 18 +++++++++ astro.config.ts | 24 +++++++++++- src/components/Path.astro | 5 ++- src/components/Sidebar.astro | 24 ++++++++++-- src/i18n/en.json | 15 +++++++- src/i18n/es.json | 15 +++++++- src/pages/[lang]/index.astro | 21 ++++++++++- src/styles/didactika.css | 11 ++++++ tools/lib/markdown.test.ts | 31 +++++++++++++++- tools/lib/markdown.ts | 72 +++++++++++++++++++++++++++++++++++- tools/lib/resolve.ts | 10 ++++- tools/lib/source.ts | 2 +- tools/sync.ts | 27 +++++++++++--- 15 files changed, 262 insertions(+), 21 deletions(-) diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index fc9b238..74d631f 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -30,6 +30,9 @@ jobs: - run: npm test - run: npm run icons - run: npm run build + env: + # The foot of the site reads the people and the funding of the organisation from GitHub (tools/project.ts). + GITHUB_TOKEN: ${{ github.token }} - uses: actions/upload-artifact@v4 with: name: site diff --git a/.github/workflows/pages.yml b/.github/workflows/pages.yml index 61d7c81..3b139b3 100644 --- a/.github/workflows/pages.yml +++ b/.github/workflows/pages.yml @@ -6,7 +6,7 @@ on: # Every day, so a change in the documentation of a product that did not notify this repository still reaches the site. schedule: - cron: '23 5 * * *' - # A product repository tells this one when its docs/ changes (see the plan, docs-notify). + # A product repository tells this one when its docs/ changes (the reusable workflow docs-notify of didactika/.github). repository_dispatch: types: [docs-changed] workflow_dispatch: @@ -38,6 +38,9 @@ jobs: - run: npm ci - run: npm test - run: npm run build + env: + # The foot of the site reads the people and the funding of the organisation from GitHub (tools/project.ts). + GITHUB_TOKEN: ${{ github.token }} - uses: actions/upload-pages-artifact@v3 with: path: dist diff --git a/README.md b/README.md index 8547c10..1681fb2 100644 --- a/README.md +++ b/README.md @@ -83,3 +83,21 @@ A page is `docs//.md` in the repository of the product, with a f ## Licence GPL-3.0-or-later, as Moodle. + +## Technical documentation + +The technical documentation of a product (domain model, requirements, use cases, analysis, design, code map) lives in `docs//technical/` of its repository and is written with the **rup-flow Pro** skill ([where to get it](https://www.agensi.io/skills/rup-flow-pro-complete-rup-workflow-both-ways)). The portal shows it as the "Technical documentation" section of the product: the `README.md` of a folder is its index, the diagrams (`.svg`) and tables (`.csv`) next to a page are published with it, and links between files keep working. The colours of the diagrams are `rup/didactika.theme.json`; copy it into the `theme` key of the `rup.config.json` of the product. + +## Publishing + +The site is built and deployed by `.github/workflows/pages.yml` to on every push to `main`, every day, and when a product repository sends the event `docs-changed`. A product repository sends it with the reusable workflow `docs-notify` of `didactika/.github`, which needs the organisation secret `DOCS_DISPATCH_TOKEN` (a fine-grained token with "Contents: read and write" on this repository). + +Turning it on once, by an administrator: + +```bash +gh repo edit didactika/docs --visibility public --accept-visibility-change-consequences +gh api -X POST repos/didactika/docs/pages -f build_type=workflow +gh api -X PUT repos/didactika/docs/pages -f cname=docs.didactika.org -F https_enforced=true +``` + +and a `CNAME` record `docs` that points to `didactika.github.io` in the DNS of didactika.org. diff --git a/astro.config.ts b/astro.config.ts index f0ff6c0..a9335f7 100644 --- a/astro.config.ts +++ b/astro.config.ts @@ -15,7 +15,7 @@ interface Product { slug: string; kind: 'plugin' | 'package'; title: Record; - lines: Array<{id: string; label: string; latest: boolean; sections: string[]}>; + lines: Array<{id: string; label: string; latest: boolean; sections: string[]; pageIds: string[]}>; } const json = (path: string, fallback: T): T => (existsSync(path) ? (JSON.parse(readFileSync(path, 'utf8')) as T) : fallback); @@ -38,6 +38,21 @@ const kinds = [ {kind: 'package', label: 'Packages', es: 'Paquetes', dir: 'packages'}, ] as const; +/** + * The technical documentation of a product, in the order of the method (RUP): what the product models, what it must do, how it is analysed and + * designed, and where it lives in the code. The folders come from the tool that writes the model, which names them in its own way, so the + * order is set here and the names come from the dictionaries. + */ +const DISCIPLINES = ['domain', 'requirements', 'analysis', 'design', 'implementation', 'quality']; +const technicalItems = (directory: string, pageIds: string[]) => [ + {label: uiText('overview', 'Overview').en, translations: uiText('overview', 'Overview'), slug: directory}, + ...DISCIPLINES.filter((discipline) => pageIds.some((id) => id.startsWith(`technical/${discipline}/`))).map((discipline) => ({ + label: uiText(`tech.${discipline}`, titleCase(discipline)).en, + translations: uiText(`tech.${discipline}`, titleCase(discipline)), + items: [{autogenerate: {directory: `${directory}/${discipline}`}}], + })), +]; + const sidebar: NonNullable = kinds .filter(({kind}) => products.some((product) => product.kind === kind)) .map(({kind, label, es, dir}) => ({ @@ -58,7 +73,12 @@ const sidebar: NonNullable = kinds ...line.sections.map((section) => ({ label: uiText(`section.${section}`, titleCase(section)).en, translations: uiText(`section.${section}`, titleCase(section)), - items: [{autogenerate: {directory: `${dir}/${product.slug}/${line.id}/${section}`}}], + // Only the section of the page the reader is on is open, so the whole map of the product fits in view. + collapsed: true, + items: + section === 'technical' + ? technicalItems(`${dir}/${product.slug}/${line.id}/technical`, line.pageIds) + : [{autogenerate: {directory: `${dir}/${product.slug}/${line.id}/${section}`}}], })), ], })), diff --git a/src/components/Path.astro b/src/components/Path.astro index 257f8da..bbfa300 100644 --- a/src/components/Path.astro +++ b/src/components/Path.astro @@ -31,13 +31,14 @@ const steps = pages.flatMap((page) => { if (!product || !line) { return []; } - const wanted = (code: string) => `${code}/${product.kind === 'plugin' ? 'plugins' : 'packages'}/${product.slug}/${line.id}/${page}`; + const slug = page === 'index' ? '' : page.replace(/\/index$/, ''); + const wanted = (code: string) => `${code}/${product.kind === "plugin" ? "plugins" : "packages"}/${product.slug}/${line.id}${slug ? `/${slug}` : ""}`; const entry = entries.find((candidate) => candidate.id === wanted(lang)) ?? entries.find((candidate) => candidate.id === wanted('en')); if (!entry) { return []; } const summary = (entry.data as {description?: string}).description ?? ''; - return [{href: `${productUrl(lang, product, line.id)}${page}/`, title: entry.data.title, summary, id: pageIdOf(entry.id, product.slug, line.id)}]; + return [{href: `${productUrl(lang, product, line.id)}${slug ? `${slug}/` : ""}`, title: entry.data.title, summary, id: pageIdOf(entry.id, product.slug, line.id)}]; }); --- diff --git a/src/components/Sidebar.astro b/src/components/Sidebar.astro index 2db22e6..309733d 100644 --- a/src/components/Sidebar.astro +++ b/src/components/Sidebar.astro @@ -4,7 +4,7 @@ * previous and next pages follow the same list, so a reader never ends up in another version by turning the page. */ import Default from '@astrojs/starlight/components/Sidebar.astro'; -import {productUrl, site} from '../lib/site'; +import {productUrl, site, t} from '../lib/site'; const route = Astro.locals.starlightRoute; const data = route.entry.data as {product?: string; line?: string}; @@ -29,13 +29,31 @@ function groupOf(entries: Entry[], overview: string): Entry[] | undefined { return undefined; } +/** + * A folder of the technical documentation that holds only one page (the card of a use case) is that page, and the folder of the cards is + * named in the language of the reader, not by the name of the folder. + */ +function tidy(entries: Entry[]): Entry[] { + return entries.map((entry) => { + if (entry.type !== 'group') { + return entry; + } + const inner = tidy(entry.entries); + if (inner.length === 1 && inner[0].type === 'link') { + return inner[0]; + } + const key = `tech.${entry.label}`; + return {...entry, label: t(route.lang, key) !== key ? t(route.lang, key) : entry.label, entries: inner}; + }); +} + const links = (entries: Entry[]): Array> => entries.flatMap((entry) => (entry.type === 'link' ? [entry] : links(entry.entries))); if (product && data.line) { const own = groupOf(route.sidebar, productUrl(route.lang, product, data.line)); if (own) { - route.sidebar = own; - const all = links(own); + route.sidebar = tidy(own); + const all = links(route.sidebar); const here = all.findIndex((link) => link.isCurrent); route.pagination = {prev: here > 0 ? all[here - 1] : undefined, next: here >= 0 ? all[here + 1] : undefined}; } diff --git a/src/i18n/en.json b/src/i18n/en.json index 3cebded..f81ccf4 100644 --- a/src/i18n/en.json +++ b/src/i18n/en.json @@ -95,5 +95,18 @@ "languageFilter": "Find a language", "languageNone": "No language matches.", "pathHint": "Read them in this order; each one builds on the one before.", - "section.technical": "Technical documentation" + "section.technical": "Technical documentation", + "tech.domain": "Domain model", + "tech.requirements": "Requirements", + "tech.analysis": "Analysis", + "tech.design": "Design", + "tech.implementation": "Implementation", + "tech.quality": "Quality", + "tech.use-cases": "Use cases", + "orgTechTitle": "Technical documentation", + "orgTechText": "How each product is built: domain model, use cases, analysis, design and a map to the code, drawn in the colours of Didactika.", + "orgTechLink": "Written with rup-flow Pro", + "orgSupportTitle": "Support Didactika", + "orgSupportText": "Didactika is open source. If its plugins and this documentation help you, you can support the people who maintain them.", + "orgSupportCta": "Support the project" } diff --git a/src/i18n/es.json b/src/i18n/es.json index 3fd1534..d11ab8f 100644 --- a/src/i18n/es.json +++ b/src/i18n/es.json @@ -95,5 +95,18 @@ "languageFilter": "Buscar un idioma", "languageNone": "Ningún idioma coincide.", "pathHint": "Léelas en este orden; cada una se apoya en la anterior.", - "section.technical": "Documentación técnica" + "section.technical": "Documentación técnica", + "tech.domain": "Modelo de dominio", + "tech.requirements": "Requisitos", + "tech.analysis": "Análisis", + "tech.design": "Diseño", + "tech.implementation": "Implementación", + "tech.quality": "Calidad", + "tech.use-cases": "Casos de uso", + "orgTechTitle": "Documentación técnica", + "orgTechText": "Cómo está construido cada producto: modelo de dominio, casos de uso, análisis, diseño y un mapa hacia el código, dibujados con los colores de Didactika.", + "orgTechLink": "Escrita con rup-flow Pro", + "orgSupportTitle": "Apoya a Didactika", + "orgSupportText": "Didactika es de código abierto. Si sus plugins y esta documentación te ayudan, puedes apoyar a quienes los mantienen.", + "orgSupportCta": "Apoyar el proyecto" } diff --git a/src/pages/[lang]/index.astro b/src/pages/[lang]/index.astro index 6958f83..5c878b1 100644 --- a/src/pages/[lang]/index.astro +++ b/src/pages/[lang]/index.astro @@ -4,7 +4,7 @@ import MIcon from '../../components/MIcon.astro'; import ProductCard from '../../components/ProductCard.astro'; import Logo from '../../components/Logo.astro'; import Landing from '../../layouts/Landing.astro'; -import {latestLine, localised, productUrl, site, t} from '../../lib/site'; +import {latestLine, localised, productUrl, project, site, t} from '../../lib/site'; export function getStaticPaths() { return site().languages.map((language) => ({params: {lang: language.code}})); @@ -12,6 +12,7 @@ export function getStaticPaths() { const {lang} = Astro.params as {lang: string}; const data = site(); +const funding = project().funding; const featured = data.products[0]; const stats = { products: data.products.length, @@ -25,6 +26,7 @@ const organised = [ {icon: 'lightbulb-rounded', title: 'orgConceptsTitle', text: 'orgConceptsText'}, {icon: 'task-alt-rounded', title: 'orgGuidesTitle', text: 'orgGuidesText'}, {icon: 'menu-book-rounded', title: 'orgReferenceTitle', text: 'orgReferenceText'}, + {icon: 'schema-rounded', title: 'orgTechTitle', text: 'orgTechText', href: 'https://www.agensi.io/skills/rup-flow-pro-complete-rup-workflow-both-ways', link: 'orgTechLink'}, ]; --- @@ -99,6 +101,7 @@ const organised = [

{t(lang, card.title)}

{t(lang, card.text)}

+ {card.href && {t(lang, card.link!)} } )) } @@ -140,4 +143,20 @@ const organised = [ + { + funding && ( +
+
+
+ +
+

{t(lang, 'orgSupportTitle')}

+

{t(lang, 'orgSupportText')}

+
+ {t(lang, 'orgSupportCta')} +
+
+
+ ) + } diff --git a/src/styles/didactika.css b/src/styles/didactika.css index ea37806..9e48602 100644 --- a/src/styles/didactika.css +++ b/src/styles/didactika.css @@ -530,3 +530,14 @@ a.d-feature:hover { border-color: color-mix(in srgb, var(--accent) 55%, var(--li /* The table of contents gives way to the foot (see ProjectFoot.astro). */ .right-sidebar { height: calc(100vh - var(--sl-nav-height, 3.75rem) - var(--d-foot-overlap, 0px)); } .d-footer { margin-top: 4rem; } + +.d-cardlink { display: inline-flex; align-items: center; gap: 0.3rem; margin-top: 0.7rem; color: var(--accent); font: 600 0.85rem var(--font); text-decoration: none; } +.d-cardlink:hover { text-decoration: underline; } + +/* The invitation to support the project, at the foot of the home. */ +.d-support { display: grid; grid-template-columns: auto 1fr auto; align-items: center; gap: 1.2rem; padding: 1.4rem 1.6rem; border: 1px solid var(--line); border-radius: var(--radius-lg); background: var(--panel); box-shadow: var(--shadow); } +.d-support .d-tile { width: 3.2rem; height: 3.2rem; background: color-mix(in srgb, #e11d48 10%, var(--panel)); border-color: color-mix(in srgb, #e11d48 30%, var(--line)); } +.d-support .d-tile .mi { color: #e11d48; } +.d-support h2 { margin: 0; font: 700 1.25rem/1.3 var(--display); } +.d-support p { margin: 0.25rem 0 0; color: var(--muted); font-size: 0.92rem; } +@media (max-width: 40rem) { .d-support { grid-template-columns: auto 1fr; } .d-support .d-btn { grid-column: 1 / -1; justify-content: center; } } diff --git a/tools/lib/markdown.test.ts b/tools/lib/markdown.test.ts index f78fef9..6f1a4ef 100644 --- a/tools/lib/markdown.test.ts +++ b/tools/lib/markdown.test.ts @@ -1,6 +1,6 @@ import assert from 'node:assert/strict'; import {describe, it} from 'node:test'; -import {addComponentImports, alertsToAsides, resolveAssetLinks, resolvePageLinks, transformBody} from './markdown.ts'; +import {addComponentImports, alertsToAsides, resolveAssetLinks, resolvePageLinks, transformBody, resolveRelativeLinks, takeHeading, firstParagraph} from './markdown.ts'; describe('alertsToAsides', () => { it('turns an alert of GitHub into an aside of Starlight', () => { @@ -106,3 +106,32 @@ describe('transformBody', () => { assert.equal(transformBody('![A](asset:a.png)', '/en/p/m1', '/docs-assets/p/m1'), '![A](/docs-assets/p/m1/a.png)'); }); }); + +describe('the pages of a technical model', () => { + const base = '/en/plugins/local-demo/m405'; + const assets = '/docs-assets/plugins/local-demo/m405'; + + it('turns a link to another page into its address and a link to a diagram into its asset', () => { + const out = resolveRelativeLinks('[card](../../design/use-cases/a/README.md#tests) ![d](./domain-model.svg) [t](traceability.csv)', 'technical/domain/index', 'en', base, assets); + assert.equal(out, `[card](${base}/design/use-cases/a/#tests) ![d](${assets}/en/technical/domain/domain-model.svg) [t](${assets}/en/technical/domain/traceability.csv)`); + }); + + it('leaves absolute links, anchors, schemes and code as they are', () => { + const text = '[a](https://x.org) [b](#top) [c](/en/x/) [d](page:guides/x)\n```\n[e](./f.md)\n```\n'; + assert.equal(resolveRelativeLinks(text, 'technical/index', 'en', base, assets), text); + }); + + it('gives the README of a folder the address of the folder', () => { + assert.equal(resolveRelativeLinks('[x](./use-cases/a/README.md)', 'technical/requirements/index', 'en', base, assets), `[x](${base}/technical/requirements/use-cases/a/)`); + }); + + it('takes the first heading as the title and out of the body', () => { + assert.deepEqual(takeHeading('\n# UC-001 Create `delegations`\n\nText'), {title: 'UC-001 Create delegations', body: 'Text'}); + assert.deepEqual(takeHeading('Text first\n# Later'), {body: 'Text first\n# Later'}); + }); + + it('describes a page by its first paragraph of prose', () => { + assert.equal(firstParagraph('| a | b |\n| - | - |\n\nHow it is [built](x.md). Second sentence.'), 'How it is built. Second sentence.'); + assert.equal(firstParagraph('| a |\n'), undefined); + }); +}); diff --git a/tools/lib/markdown.ts b/tools/lib/markdown.ts index 0ec62d0..454b573 100644 --- a/tools/lib/markdown.ts +++ b/tools/lib/markdown.ts @@ -44,7 +44,10 @@ export function alertsToAsides(markdown: string): string { /** `page:` links, written as the address of the page inside `base` (`/en/plugins/local-demo/m503`). */ export function resolvePageLinks(markdown: string, base: string): string { - const address = (id: string, anchor: string | undefined): string => `${base}${id === 'index' ? '/' : `/${id}/`}${anchor ?? ''}`; + const address = (id: string, anchor: string | undefined): string => { + const clean = id === 'index' ? '' : id.replace(/\/index$/, ''); + return `${base}${clean ? `/${clean}/` : '/'}${anchor ?? ''}`; + }; return outsideFences(markdown, (text) => text // A link of Markdown: [text](page:guides/install#step-2) @@ -91,6 +94,73 @@ export function addComponentImports(mdx: string): string { return `${front}\n${imports.join('\n')}\n${mdx.slice(front.length)}`; } +/** + * The links of a page that point at a file next to it (`../design/README.md`, `./domain-model.svg`), as the tools that write the + * documentation of a technical model produce them. A page becomes the address of that page in the same version and language, and a + * diagram or a table becomes its address among the assets of the version. + * + * `pageId` is the page inside its version (`technical/domain/index`), which says where its folder is. + */ +export function resolveRelativeLinks(markdown: string, pageId: string, lang: string, base: string, assetBase: string): string { + const folder = pageId.includes('/') ? pageId.slice(0, pageId.lastIndexOf('/')).split('/') : []; + return outsideFences(markdown, (text) => + text.replace(/\]\(([^)\s]+)\)/g, (whole: string, target: string) => { + if (/^(?:[a-z][a-z0-9+.-]*:|\/|#)/i.test(target)) { + return whole; + } + const [file, anchor] = [target.split('#')[0], target.includes('#') ? `#${target.split('#').slice(1).join('#')}` : '']; + const parts = [...folder]; + for (const part of file.split('/')) { + if (part === '..') { + if (parts.length === 0) { + return whole; + } + parts.pop(); + } else if (part !== '.' && part !== '') { + parts.push(part); + } + } + const path = parts.join('/'); + if (/\.mdx?$/.test(path)) { + const id = path.replace(/\.mdx?$/, '').replace(/(^|\/)README$/, '$1index').replace(/(^|\/)index$/, ''); + return `](${base}${id ? `/${id}` : ''}/${anchor})`; + } + return `](${assetBase}/${lang}/${path}${anchor})`; + }), + ); +} + +/** + * The first heading of a page, when the page starts with one. It is the title of the page and is taken out of the body, because the + * portal draws the title itself; the pages of a technical model (a use-case card, a README) have it and no front matter title, or + * one that does not tell the three cards of a use case apart. + */ +export function takeHeading(body: string): {title?: string; body: string} { + const match = /^\s*#\s+(.+?)\s*\n/.exec(body.replace(/\r\n/g, '\n')); + if (!match) { + return {body}; + } + return {title: match[1].replace(/`/g, ''), body: body.replace(/\r\n/g, '\n').slice(match[0].length).replace(/^\n+/, '')}; +} + +/** A short description for a page that has none: its first paragraph of prose, without Markdown, cut at a sentence. */ +export function firstParagraph(body: string, limit = 180): string | undefined { + for (const block of body.replace(/\r\n/g, '\n').split(/\n{2,}/)) { + const text = block.trim(); + if (text === '' || /^(?:[|#>!<\-*+`:]|\d+\.|---)/.test(text)) { + continue; + } + const plain = text.replace(/\[([^\]]+)\]\([^)]*\)/g, '$1').replace(/[*_`]/g, '').replace(/\s+/g, ' '); + if (plain.length <= limit) { + return plain; + } + const cut = plain.slice(0, limit); + const stop = cut.lastIndexOf('. '); + return stop > 60 ? cut.slice(0, stop + 1) : `${cut.slice(0, cut.lastIndexOf(' '))}…`; + } + return undefined; +} + export function transformBody(markdown: string, base: string, assetBase?: string): string { const linked = resolvePageLinks(alertsToAsides(markdown), base); return assetBase ? resolveAssetLinks(linked, assetBase) : linked; diff --git a/tools/lib/resolve.ts b/tools/lib/resolve.ts index 347ee4a..2367ead 100644 --- a/tools/lib/resolve.ts +++ b/tools/lib/resolve.ts @@ -99,6 +99,8 @@ export interface Resolution { const PAGE = /^([A-Za-z][A-Za-z0-9_-]*)\/(.+)(\.mdx?)$/; const ASSETS = '_assets/'; +/** What may sit next to a page inside a language folder: its diagrams, images and tables. */ +const MEDIA = /^[A-Za-z][A-Za-z0-9_-]*\/.+\.(?:svg|png|webp|jpe?g|gif|csv|puml)$/; /** Reads the front matter of a page. */ export function parseFrontmatter(raw: string): {data: Record; body: string; error?: string} { @@ -175,9 +177,15 @@ export function resolveProduct(lines: LineInput[], languages: LanguageDef[]): Re } const match = PAGE.exec(path); if (!match) { + // The diagrams and tables that a page of the technical documentation shows sit next to it. + if (MEDIA.test(path)) { + assets.set(path, content); + } continue; } - const [, lang, id, ext] = match; + const [, lang, rawId, ext] = match; + // The README of a folder is its index, as on GitHub. + const id = rawId.replace(/(^|\/)README$/, '$1index'); if (!known.has(lang)) { issues.push({level: 'warning', code: 'unknown-language', line: line.id, path, message: `${path} is in the language ${lang}, which is not in the registry of languages. It is ignored.`}); continue; diff --git a/tools/lib/source.ts b/tools/lib/source.ts index df4e2cd..dca32a0 100644 --- a/tools/lib/source.ts +++ b/tools/lib/source.ts @@ -120,7 +120,7 @@ function filesOf(repo: string, ref: string): Map { continue; } // Binary files are kept as Latin-1 text, which is lossless, and written back the same way. - const binary = path.startsWith('_assets/') && !/\.(?:md|mdx|svg|txt|json)$/.test(path); + const binary = !/\.(?:md|mdx|svg|txt|json|csv|puml)$/.test(path); files.set(path, git(repo, ['show', `${ref}:${name}`], binary ? 'latin1' : 'utf8')); } return files; diff --git a/tools/sync.ts b/tools/sync.ts index 37e9663..f367c71 100644 --- a/tools/sync.ts +++ b/tools/sync.ts @@ -30,7 +30,7 @@ import {existsSync, mkdirSync, readdirSync, readFileSync, rmdirSync, rmSync, wri import {dirname, join, resolve} from 'node:path'; import {stringify} from 'yaml'; import {branchesOf, checkDirectory, directoryPage, type Cache, type DirectoryAnswer} from './lib/directory.ts'; -import {addComponentImports, transformBody} from './lib/markdown.ts'; +import {addComponentImports, firstParagraph, resolveRelativeLinks, takeHeading, transformBody} from './lib/markdown.ts'; import {parseFrontmatter, resolveProduct, type Issue, type LanguageDef} from './lib/resolve.ts'; import {readProduct, type DocsJson} from './lib/source.ts'; @@ -162,14 +162,14 @@ function frontmatter(data: Record, extra: Record [...new Set(ids.filter((id) => id.includes('/')).map((id) => id.split('/')[0]))].sort((a, b) => { const rank = (name: string): number => (USUAL_SECTIONS.includes(name) ? USUAL_SECTIONS.indexOf(name) : USUAL_SECTIONS.length); return rank(a) - rank(b) || a.localeCompare(b); }); -const isText = (path: string): boolean => /\.(?:md|mdx|svg|txt|json)$/.test(path); +const isText = (path: string): boolean => /\.(?:md|mdx|svg|txt|json|csv|puml)$/.test(path); const issues: Array = []; const products: Array> = []; @@ -207,7 +207,22 @@ for (const entry of manifest.products) { } for (const page of line.pages) { - const {data, body} = parseFrontmatter(page.shown.content); + const parsed = parseFrontmatter(page.shown.content); + // A page that starts with a heading (a README, a card of a technical model) is titled by it. + const heading = takeHeading(parsed.body); + const data: Record = {...parsed.data, ...(heading.title ? {title: heading.title} : {})}; + if (!data.description) { + const described = firstParagraph(heading.body); + if (described) { + data.description = described; + } + } + // The keys the tools of a technical model put in the front matter are theirs; one of them (id) would rename the page. + for (const key of ['id', 'name', 'actor', 'package', 'origin', 'sourceOfTruth', 'requirement', 'includes', 'extends']) { + delete data[key]; + } + const body = heading.body; + const rewrite = (text: string, to: string): string => resolveRelativeLinks(transformBody(text, to, assetBase), page.id, page.shown.lang, to, assetBase); const note = page.status === 'missing' || page.status === 'outdated' ? {content: ui(page.lang, page.status === 'missing' ? 'translationMissing' : 'translationOutdated', {language: languages.find((l) => l.code === page.lang)!.name})} @@ -225,10 +240,10 @@ for (const entry of manifest.products) { const base = join(content, page.lang, kindDir, docs.slug); const address = `/${page.lang}/${kindDir}/${docs.slug}`; const finish = (text: string): string => (page.shown.ext === '.mdx' ? addComponentImports(text) : text); - write(join(base, line.id, `${page.id}${page.shown.ext}`), finish(frontmatter(data, extra) + transformBody(body, `${address}/${line.id}`, assetBase))); + write(join(base, line.id, `${page.id}${page.shown.ext}`), finish(frontmatter(data, extra) + rewrite(body, `${address}/${line.id}`))); // The address without a version shows the newest one, its links stay in that address and the search does not index it twice. if (line.id === newest.id) { - write(join(base, `${page.id}${page.shown.ext}`), finish(frontmatter(data, {...extra, pagefind: false}) + transformBody(body, address, assetBase))); + write(join(base, `${page.id}${page.shown.ext}`), finish(frontmatter(data, {...extra, pagefind: false}) + rewrite(body, address))); } } } From 639a401969c4a82a978a0fd0b933428e15c4789e Mon Sep 17 00:00:00 2001 From: hlaelissalt Date: Wed, 11 Nov 2026 21:47:15 +0100 Subject: [PATCH 5/8] feat: a home text for users of any Didactika product, plugin or library --- astro.config.ts | 2 +- src/i18n/en.json | 22 +++++++++++----------- src/i18n/es.json | 20 ++++++++++---------- src/pages/[lang]/index.astro | 2 +- 4 files changed, 23 insertions(+), 23 deletions(-) diff --git a/astro.config.ts b/astro.config.ts index a9335f7..1c3c556 100644 --- a/astro.config.ts +++ b/astro.config.ts @@ -94,7 +94,7 @@ export default defineConfig({ integrations: [ starlight({ title: {en: 'Didactika Docs', es: 'Documentación de Didactika'}, - description: 'The documentation of the Moodle plugins and the npm packages of Didactika.', + description: 'Official documentation for the plugins and libraries of Didactika.', defaultLocale: 'en', locales, // The header, the title of a page, the navigation and the foot are drawn by the components of Didactika (src/components). diff --git a/src/i18n/en.json b/src/i18n/en.json index f81ccf4..88dbb44 100644 --- a/src/i18n/en.json +++ b/src/i18n/en.json @@ -1,8 +1,8 @@ { "plugins": "Plugins", - "pluginsDescription": "The Moodle plugins of Didactika.", + "pluginsDescription": "Moodle plugins developed by Didactika.", "packages": "Packages", - "packagesDescription": "The npm packages of Didactika.", + "packagesDescription": "Libraries and npm packages developed by Didactika.", "name": "Name", "summary": "Summary", "translationMissing": "This page is not available in {language} yet. You are reading the English version.", @@ -32,17 +32,17 @@ "github": "GitHub", "designSystem": "Design system", "heroEyebrow": "Open source · GPL-3.0", - "heroTitleA": "Documentation for every", - "heroTitleB": "Didactika plugin", - "heroLead": "Guides, concepts and reference for the Moodle plugins and the npm packages of Didactika, for each version and in your language.", - "heroCta": "Explore the plugins", - "heroCtaSecondary": "How it is organised", - "statProducts": "Documented products", + "heroTitleA": "Everything you need to work with", + "heroTitleB": "Didactika", + "heroLead": "Installation guides, user manuals and technical reference for Didactika plugins and libraries, available for every supported version and in several languages.", + "heroCta": "Browse the documentation", + "heroCtaSecondary": "How the documentation is organised", + "statProducts": "Products documented", "statVersions": "Versions", "statLanguages": "Languages", "statPages": "Pages", "productsTitle": "Documented products", - "productsLead": "Pick a product to read how to install it, use it and integrate it.", + "productsLead": "Select a product to learn how to install it, use it and integrate it.", "published": "In the Moodle directory", "githubOnly": "GitHub only", "versions": "Versions", @@ -51,7 +51,7 @@ "comingTitle": "Coming next", "comingLead": "The plugins below are documented next, in this order.", "organisedTitle": "How the documentation is organised", - "organisedLead": "Every product follows the same structure, so what you learn in one place works in all of them.", + "organisedLead": "Every product follows the same structure, so finding information in one is just as easy in any other.", "orgStartTitle": "Getting started", "orgStartText": "Install the plugin, give people the permission it needs and complete a first task in minutes.", "orgConceptsTitle": "Concepts", @@ -83,7 +83,7 @@ "requires": "Moodle", "directoryOpen": "View in the Moodle directory", "repository": "Repository", - "footAbout": "The documentation of the Moodle plugins and npm packages of Didactika, by version and in your language.", + "footAbout": "Official documentation for the plugins and libraries of Didactika, by version and language.", "cofounders": "Co-founders", "cofounder": "Co-founder", "collaborators": "Collaborators", diff --git a/src/i18n/es.json b/src/i18n/es.json index d11ab8f..40fccdc 100644 --- a/src/i18n/es.json +++ b/src/i18n/es.json @@ -1,8 +1,8 @@ { "plugins": "Plugins", - "pluginsDescription": "Los plugins de Moodle de Didactika.", + "pluginsDescription": "Plugins de Moodle desarrollados por Didactika.", "packages": "Paquetes", - "packagesDescription": "Los paquetes npm de Didactika.", + "packagesDescription": "Librerías y paquetes npm desarrollados por Didactika.", "name": "Nombre", "summary": "Resumen", "translationMissing": "Esta página aún no está disponible en {language}. Estás leyendo la versión en inglés.", @@ -32,17 +32,17 @@ "github": "GitHub", "designSystem": "Sistema de diseño", "heroEyebrow": "Código abierto · GPL-3.0", - "heroTitleA": "La documentación de cada", - "heroTitleB": "plugin de Didactika", - "heroLead": "Guías, conceptos y referencia de los plugins de Moodle y de los paquetes npm de Didactika, para cada versión y en tu idioma.", - "heroCta": "Explorar los plugins", - "heroCtaSecondary": "Cómo está organizada", + "heroTitleA": "Todo lo que necesita para trabajar con", + "heroTitleB": "Didactika", + "heroLead": "Guías de instalación, manuales de uso y referencia técnica de los plugins y las librerías de Didactika, disponibles para cada versión compatible y en varios idiomas.", + "heroCta": "Explorar la documentación", + "heroCtaSecondary": "Cómo se organiza la documentación", "statProducts": "Productos documentados", "statVersions": "Versiones", "statLanguages": "Idiomas", "statPages": "Páginas", "productsTitle": "Productos documentados", - "productsLead": "Elige un producto para ver cómo instalarlo, usarlo e integrarlo.", + "productsLead": "Seleccione un producto para aprender a instalarlo, utilizarlo e integrarlo.", "published": "En el directorio de Moodle", "githubOnly": "Solo en GitHub", "versions": "Versiones", @@ -51,7 +51,7 @@ "comingTitle": "Próximamente", "comingLead": "Los plugins siguientes se documentan a continuación, en este orden.", "organisedTitle": "Cómo está organizada la documentación", - "organisedLead": "Todos los productos siguen la misma estructura, así que lo que aprendes en uno sirve en todos.", + "organisedLead": "Todos los productos siguen la misma estructura, de modo que encontrar información en uno es tan sencillo como en cualquier otro.", "orgStartTitle": "Primeros pasos", "orgStartText": "Instala el plugin, da a las personas el permiso que necesita y completa una primera tarea en minutos.", "orgConceptsTitle": "Conceptos", @@ -83,7 +83,7 @@ "requires": "Moodle", "directoryOpen": "Ver en el directorio de Moodle", "repository": "Repositorio", - "footAbout": "La documentación de los plugins de Moodle y los paquetes npm de Didactika, por versión y en tu idioma.", + "footAbout": "Documentación oficial de los plugins y las librerías de Didactika, por versión e idioma.", "cofounders": "Cofundadores", "cofounder": "Cofundador", "collaborators": "Colaboradores", diff --git a/src/pages/[lang]/index.astro b/src/pages/[lang]/index.astro index 5c878b1..b39e382 100644 --- a/src/pages/[lang]/index.astro +++ b/src/pages/[lang]/index.astro @@ -30,7 +30,7 @@ const organised = [ ]; --- - +
From 04e6b07aa81b31894afab02c08b4b26d489a26be Mon Sep 17 00:00:00 2001 From: hlaelissalt Date: Wed, 11 Nov 2026 21:49:33 +0100 Subject: [PATCH 6/8] feat: leave the authoring tool out of the portal --- README.md | 2 +- src/i18n/en.json | 3 +-- src/i18n/es.json | 3 +-- src/pages/[lang]/index.astro | 3 +-- 4 files changed, 4 insertions(+), 7 deletions(-) diff --git a/README.md b/README.md index 1681fb2..7b52ae0 100644 --- a/README.md +++ b/README.md @@ -86,7 +86,7 @@ GPL-3.0-or-later, as Moodle. ## Technical documentation -The technical documentation of a product (domain model, requirements, use cases, analysis, design, code map) lives in `docs//technical/` of its repository and is written with the **rup-flow Pro** skill ([where to get it](https://www.agensi.io/skills/rup-flow-pro-complete-rup-workflow-both-ways)). The portal shows it as the "Technical documentation" section of the product: the `README.md` of a folder is its index, the diagrams (`.svg`) and tables (`.csv`) next to a page are published with it, and links between files keep working. The colours of the diagrams are `rup/didactika.theme.json`; copy it into the `theme` key of the `rup.config.json` of the product. +The technical documentation of a product (domain model, requirements, use cases, analysis, design, code map) lives in `docs//technical/` of its repository. The portal shows it as the "Technical documentation" section of the product: the `README.md` of a folder is its index, the diagrams (`.svg`) and tables (`.csv`) next to a page are published with it, and links between files keep working. The colours of the diagrams are `rup/didactika.theme.json`; copy it into the `theme` key of the `rup.config.json` of the product. ## Publishing diff --git a/src/i18n/en.json b/src/i18n/en.json index 88dbb44..dbb8bc0 100644 --- a/src/i18n/en.json +++ b/src/i18n/en.json @@ -91,7 +91,7 @@ "join": "See everything we build and contribute", "support": "Support Didactika", "supportLink": "Support Didactika", - "credits": "Built with Starlight · Icons by Material Symbols · Technical documentation with rup-flow Pro", + "credits": "Built with Starlight · Icons by Material Symbols", "languageFilter": "Find a language", "languageNone": "No language matches.", "pathHint": "Read them in this order; each one builds on the one before.", @@ -105,7 +105,6 @@ "tech.use-cases": "Use cases", "orgTechTitle": "Technical documentation", "orgTechText": "How each product is built: domain model, use cases, analysis, design and a map to the code, drawn in the colours of Didactika.", - "orgTechLink": "Written with rup-flow Pro", "orgSupportTitle": "Support Didactika", "orgSupportText": "Didactika is open source. If its plugins and this documentation help you, you can support the people who maintain them.", "orgSupportCta": "Support the project" diff --git a/src/i18n/es.json b/src/i18n/es.json index 40fccdc..91d0255 100644 --- a/src/i18n/es.json +++ b/src/i18n/es.json @@ -91,7 +91,7 @@ "join": "Ver todo lo que construimos y aportamos", "support": "Apoya a Didactika", "supportLink": "Apoya a Didactika", - "credits": "Hecho con Starlight · Iconos de Material Symbols · Documentación técnica con rup-flow Pro", + "credits": "Hecho con Starlight · Iconos de Material Symbols", "languageFilter": "Buscar un idioma", "languageNone": "Ningún idioma coincide.", "pathHint": "Léelas en este orden; cada una se apoya en la anterior.", @@ -105,7 +105,6 @@ "tech.use-cases": "Casos de uso", "orgTechTitle": "Documentación técnica", "orgTechText": "Cómo está construido cada producto: modelo de dominio, casos de uso, análisis, diseño y un mapa hacia el código, dibujados con los colores de Didactika.", - "orgTechLink": "Escrita con rup-flow Pro", "orgSupportTitle": "Apoya a Didactika", "orgSupportText": "Didactika es de código abierto. Si sus plugins y esta documentación te ayudan, puedes apoyar a quienes los mantienen.", "orgSupportCta": "Apoyar el proyecto" diff --git a/src/pages/[lang]/index.astro b/src/pages/[lang]/index.astro index b39e382..4ce4834 100644 --- a/src/pages/[lang]/index.astro +++ b/src/pages/[lang]/index.astro @@ -26,7 +26,7 @@ const organised = [ {icon: 'lightbulb-rounded', title: 'orgConceptsTitle', text: 'orgConceptsText'}, {icon: 'task-alt-rounded', title: 'orgGuidesTitle', text: 'orgGuidesText'}, {icon: 'menu-book-rounded', title: 'orgReferenceTitle', text: 'orgReferenceText'}, - {icon: 'schema-rounded', title: 'orgTechTitle', text: 'orgTechText', href: 'https://www.agensi.io/skills/rup-flow-pro-complete-rup-workflow-both-ways', link: 'orgTechLink'}, + {icon: 'schema-rounded', title: 'orgTechTitle', text: 'orgTechText'}, ]; --- @@ -101,7 +101,6 @@ const organised = [

{t(lang, card.title)}

{t(lang, card.text)}

- {card.href && {t(lang, card.link!)} }
)) } From a9753c443ff44ba50c2dbbf6c5a4daefed8aec78 Mon Sep 17 00:00:00 2001 From: hlaelissalt Date: Wed, 11 Nov 2026 22:12:32 +0100 Subject: [PATCH 7/8] feat: search beside the versions, a layout for small screens, three products on the home and a page of resources The search sits after the product and the version as in the design system and the menu of a small screen opens with the product and its versions. The home shows the three products that changed last with a link to the whole catalog, leaves room for the libraries and no longer talks about languages; the foot links to the list of resources of didactika.org. The quality section of the technical documentation is gone. --- astro.config.ts | 2 +- src/components/ProductCard.astro | 12 +-- src/components/ProjectFoot.astro | 2 +- src/components/Sidebar.astro | 21 ++++- src/components/SiteHeader.astro | 5 +- src/i18n/en.json | 16 ++-- src/i18n/es.json | 16 ++-- src/lib/site.ts | 2 + src/pages/[lang]/index.astro | 119 ++++++++++++++------------ src/pages/[lang]/packages/index.astro | 43 ++++++++++ src/styles/didactika.css | 47 +++++++++- tools/lib/source.ts | 6 +- tools/sync.ts | 1 + 13 files changed, 205 insertions(+), 87 deletions(-) create mode 100644 src/pages/[lang]/packages/index.astro diff --git a/astro.config.ts b/astro.config.ts index 1c3c556..bf0daa5 100644 --- a/astro.config.ts +++ b/astro.config.ts @@ -43,7 +43,7 @@ const kinds = [ * designed, and where it lives in the code. The folders come from the tool that writes the model, which names them in its own way, so the * order is set here and the names come from the dictionaries. */ -const DISCIPLINES = ['domain', 'requirements', 'analysis', 'design', 'implementation', 'quality']; +const DISCIPLINES = ['domain', 'requirements', 'analysis', 'design', 'implementation']; const technicalItems = (directory: string, pageIds: string[]) => [ {label: uiText('overview', 'Overview').en, translations: uiText('overview', 'Overview'), slug: directory}, ...DISCIPLINES.filter((discipline) => pageIds.some((id) => id.startsWith(`technical/${discipline}/`))).map((discipline) => ({ diff --git a/src/components/ProductCard.astro b/src/components/ProductCard.astro index 6ee51ca..1301b46 100644 --- a/src/components/ProductCard.astro +++ b/src/components/ProductCard.astro @@ -1,8 +1,8 @@ --- -/** A product as a card: its icon, name, summary, the versions and languages it is documented in, and whether it is in the Moodle directory. */ +/** A product as a card: its icon, name, summary, the versions it is documented in, and whether it is in the Moodle directory. */ import DirectoryChip from './DirectoryChip.astro'; import MIcon from './MIcon.astro'; -import {localised, productUrl, site, t, type ProductData} from '../lib/site'; +import {localised, productUrl, t, type ProductData} from '../lib/site'; interface Soon { component: string; @@ -25,7 +25,6 @@ const summary = localised((product ?? soon!).summary, lang); const href = product ? productUrl(lang, product) : undefined; const Tag = href ? 'a' : 'div'; const code = product ? (product.component ?? product.slug) : soon!.component; -const languages = site().languages.map((language) => language.code); --- @@ -49,13 +48,6 @@ const languages = site().languages.map((language) => language.code); ))}
- {t(lang, 'languages')} - {languages.map((code) => ( - - - {code.toUpperCase()} - - ))}
diff --git a/src/components/ProjectFoot.astro b/src/components/ProjectFoot.astro index 34653fd..95a4f95 100644 --- a/src/components/ProjectFoot.astro +++ b/src/components/ProjectFoot.astro @@ -61,7 +61,7 @@ const avatar = (url: string): string => `${url}${url.includes('?') ? '&' : '?'}s github.com/{organisation.login} - {t(lang, 'designSystem')} + {t(lang, 'resources')}
diff --git a/src/components/Sidebar.astro b/src/components/Sidebar.astro index 309733d..4eff290 100644 --- a/src/components/Sidebar.astro +++ b/src/components/Sidebar.astro @@ -4,7 +4,8 @@ * previous and next pages follow the same list, so a reader never ends up in another version by turning the page. */ import Default from '@astrojs/starlight/components/Sidebar.astro'; -import {productUrl, site, t} from '../lib/site'; +import MIcon from './MIcon.astro'; +import {localised, productUrl, site, t} from '../lib/site'; const route = Astro.locals.starlightRoute; const data = route.entry.data as {product?: string; line?: string}; @@ -60,4 +61,22 @@ if (product && data.line) { } --- +{ + product && data.line && ( +
+ + + {localised(product.title, route.lang)} + +
+ {[...product.lines].reverse().map((candidate) => ( + + + {candidate.label} + + ))} +
+
+ ) +} diff --git a/src/components/SiteHeader.astro b/src/components/SiteHeader.astro index 5e54442..e8ad6d8 100644 --- a/src/components/SiteHeader.astro +++ b/src/components/SiteHeader.astro @@ -73,8 +73,11 @@ const logo = '/brand/didactika-logo.png'; } -
+ + +
{ diff --git a/src/i18n/en.json b/src/i18n/en.json index dbb8bc0..85bb880 100644 --- a/src/i18n/en.json +++ b/src/i18n/en.json @@ -39,7 +39,6 @@ "heroCtaSecondary": "How the documentation is organised", "statProducts": "Products documented", "statVersions": "Versions", - "statLanguages": "Languages", "statPages": "Pages", "productsTitle": "Documented products", "productsLead": "Select a product to learn how to install it, use it and integrate it.", @@ -62,8 +61,6 @@ "orgReferenceText": "Every setting, capability, event and web-service function, exactly as the plugin defines it.", "versionsTitle": "Pick the version you run", "versionsText": "Each plugin has one documentation for every line of Moodle it supports. A newer line keeps what it shares with the older one and changes only what differs, and the version selector of the header moves you between them.", - "languagesTitle": "In your language", - "languagesText": "English and Spanish are complete for every page. More languages can be added without touching the site.", "browseAll": "Browse all {kind}", "noProducts": "There are no products here yet.", "inheritedFrom": "Inherited from {line}", @@ -77,7 +74,6 @@ "footerSource": "Source of this site", "footerProducts": "Products", "footerOrg": "Didactika", - "footerDesign": "Design system", "footerOrgLink": "Organisation on GitHub", "release": "Release", "requires": "Moodle", @@ -105,7 +101,13 @@ "tech.use-cases": "Use cases", "orgTechTitle": "Technical documentation", "orgTechText": "How each product is built: domain model, use cases, analysis, design and a map to the code, drawn in the colours of Didactika.", - "orgSupportTitle": "Support Didactika", - "orgSupportText": "Didactika is open source. If its plugins and this documentation help you, you can support the people who maintain them.", - "orgSupportCta": "Support the project" + "pluginsLead": "Moodle plugins, ordered by the most recent change.", + "packagesLead": "Libraries and npm packages for developers.", + "viewAll": "View all", + "packagesEmptyTitle": "Libraries are coming", + "packagesEmptyText": "The documentation of the npm packages of Didactika will be published here, with the same structure as the plugins.", + "moreTitle": "More about Didactika", + "moreText": "Every site, repository and service of Didactika, in one list.", + "moreCta": "See all resources", + "resources": "Resources" } diff --git a/src/i18n/es.json b/src/i18n/es.json index 91d0255..45d9132 100644 --- a/src/i18n/es.json +++ b/src/i18n/es.json @@ -39,7 +39,6 @@ "heroCtaSecondary": "Cómo se organiza la documentación", "statProducts": "Productos documentados", "statVersions": "Versiones", - "statLanguages": "Idiomas", "statPages": "Páginas", "productsTitle": "Productos documentados", "productsLead": "Seleccione un producto para aprender a instalarlo, utilizarlo e integrarlo.", @@ -62,8 +61,6 @@ "orgReferenceText": "Cada ajuste, capacidad, evento y función del servicio web, tal como los define el plugin.", "versionsTitle": "Elige la versión que usas", "versionsText": "Cada plugin tiene una documentación para cada línea de Moodle que soporta. Una línea más nueva conserva lo que comparte con la anterior y cambia solo lo que difiere, y el selector de versión de la cabecera te mueve entre ellas.", - "languagesTitle": "En tu idioma", - "languagesText": "El inglés y el español están completos en todas las páginas. Se pueden añadir más idiomas sin tocar el sitio.", "browseAll": "Ver todos los {kind}", "noProducts": "Todavía no hay productos aquí.", "inheritedFrom": "Heredada de {line}", @@ -77,7 +74,6 @@ "footerSource": "Código de este sitio", "footerProducts": "Productos", "footerOrg": "Didactika", - "footerDesign": "Sistema de diseño", "footerOrgLink": "La organización en GitHub", "release": "Versión publicada", "requires": "Moodle", @@ -105,7 +101,13 @@ "tech.use-cases": "Casos de uso", "orgTechTitle": "Documentación técnica", "orgTechText": "Cómo está construido cada producto: modelo de dominio, casos de uso, análisis, diseño y un mapa hacia el código, dibujados con los colores de Didactika.", - "orgSupportTitle": "Apoya a Didactika", - "orgSupportText": "Didactika es de código abierto. Si sus plugins y esta documentación te ayudan, puedes apoyar a quienes los mantienen.", - "orgSupportCta": "Apoyar el proyecto" + "pluginsLead": "Plugins de Moodle, ordenados por el cambio más reciente.", + "packagesLead": "Librerías y paquetes npm para desarrolladores.", + "viewAll": "Ver todos", + "packagesEmptyTitle": "Las librerías llegarán pronto", + "packagesEmptyText": "La documentación de los paquetes npm de Didactika se publicará aquí, con la misma estructura que los plugins.", + "moreTitle": "Más sobre Didactika", + "moreText": "Todos los sitios, repositorios y servicios de Didactika, en un único listado.", + "moreCta": "Ver todos los recursos", + "resources": "Recursos" } diff --git a/src/lib/site.ts b/src/lib/site.ts index 370d1bd..52103a3 100644 --- a/src/lib/site.ts +++ b/src/lib/site.ts @@ -38,6 +38,8 @@ export interface ProductData { /** Address of the icon of the product, or null when it has none. */ icon: string | null; directory: DirectoryData; + /** When the code of the product last changed, in seconds. */ + updated?: number; lines: LineData[]; } diff --git a/src/pages/[lang]/index.astro b/src/pages/[lang]/index.astro index 4ce4834..ff49543 100644 --- a/src/pages/[lang]/index.astro +++ b/src/pages/[lang]/index.astro @@ -1,10 +1,10 @@ --- -/** The home of the portal: what it is, what is documented and how every documentation is organised. */ +/** The home of the portal: what it is, the products that changed last, and how every documentation is organised. */ +import Logo from '../../components/Logo.astro'; import MIcon from '../../components/MIcon.astro'; import ProductCard from '../../components/ProductCard.astro'; -import Logo from '../../components/Logo.astro'; import Landing from '../../layouts/Landing.astro'; -import {latestLine, localised, productUrl, project, site, t} from '../../lib/site'; +import {localised, productUrl, productsOf, site, t} from '../../lib/site'; export function getStaticPaths() { return site().languages.map((language) => ({params: {lang: language.code}})); @@ -12,14 +12,19 @@ export function getStaticPaths() { const {lang} = Astro.params as {lang: string}; const data = site(); -const funding = project().funding; + +/** What the home shows of each family of products before it sends the reader to the whole catalog. */ +const SHOWN = 3; +const byChange = (a: {updated?: number}, b: {updated?: number}): number => (b.updated ?? 0) - (a.updated ?? 0); +const plugins = productsOf('plugin').sort(byChange); +const packages = productsOf('package').sort(byChange); const featured = data.products[0]; const stats = { products: data.products.length, versions: data.products.reduce((sum, product) => sum + product.lines.length, 0), - languages: data.languages.length, - pages: data.products.reduce((sum, product) => sum + product.lines.reduce((total, line) => total + line.pages, 0), 0) * data.languages.length, + pages: data.products.reduce((sum, product) => sum + product.lines.reduce((total, line) => total + line.pages, 0), 0), }; +const pluginsTotal = plugins.length + data.coming.length; const organised = [ {icon: 'rocket-launch-rounded', title: 'orgStartTitle', text: 'orgStartText'}, @@ -38,7 +43,7 @@ const organised = [

{t(lang, 'heroTitleA')} {t(lang, 'heroTitleB')}

{t(lang, 'heroLead')}

@@ -46,49 +51,67 @@ const organised = [ Didactika Docs / {t(lang, 'plugins')} · {t(lang, 'packages')}
- {data.products.map((product) => {product.icon ? : })} - {data.coming.slice(0, 4).map(() => )} + {data.products.slice(0, 4).map((product) => {product.icon ? : })} +
- {stats.versions} {t(lang, 'statVersions')} - {data.languages.map((language) => {language.code.toUpperCase()})} + {t(lang, 'plugins')} + {t(lang, 'packages')}
-
+
{stats.products}{t(lang, 'statProducts')}
{stats.versions}{t(lang, 'statVersions')}
-
{stats.languages}{t(lang, 'statLanguages')}
{stats.pages}{t(lang, 'statPages')}
-
+
-

{t(lang, 'productsTitle')}

-

{t(lang, 'productsLead')}

+
+
+

{t(lang, 'plugins')}

+

{t(lang, 'pluginsLead')}

+
+ {pluginsTotal > SHOWN && {t(lang, 'viewAll')} } +
- {data.products.map((product) => )} + {plugins.slice(0, SHOWN).map((product) => )} + {data.coming.slice(0, Math.max(0, SHOWN - plugins.length)).map((soon) => )}
- { - data.coming.length > 0 && ( -
-
-

{t(lang, 'comingTitle')}

-

{t(lang, 'comingLead')}

+
+
+
+
+

{t(lang, 'packages')}

+

{t(lang, 'packagesLead')}

+
+ {packages.length > SHOWN && {t(lang, 'viewAll')} } +
+ { + packages.length > 0 ? (
- {data.coming.map((soon) => )} + {packages.slice(0, SHOWN).map((product) => )}
-
-
- ) - } + ) : ( +
+ +
+

{t(lang, 'packagesEmptyTitle')}

+

{t(lang, 'packagesEmptyText')}

+
+
+ ) + } +
+
@@ -109,7 +132,7 @@ const organised = [
-
+

{t(lang, 'versionsTitle')}

{t(lang, 'versionsText')}

@@ -127,35 +150,19 @@ const organised = [ ) }
-
-

{t(lang, 'languagesTitle')}

-

{t(lang, 'languagesText')}

-
- {data.languages.map((language) => ( - - - {language.name} - {language.code.toUpperCase()} - - ))} +
+
+ +
+
+
+ +
+

{t(lang, 'moreTitle')}

+

{t(lang, 'moreText')}

+ {t(lang, 'moreCta')}
- { - funding && ( -
-
-
- -
-

{t(lang, 'orgSupportTitle')}

-

{t(lang, 'orgSupportText')}

-
- {t(lang, 'orgSupportCta')} -
-
-
- ) - } diff --git a/src/pages/[lang]/packages/index.astro b/src/pages/[lang]/packages/index.astro new file mode 100644 index 0000000..a6f3349 --- /dev/null +++ b/src/pages/[lang]/packages/index.astro @@ -0,0 +1,43 @@ +--- +/** The catalog of the libraries and npm packages of Didactika. */ +import MIcon from '../../../components/MIcon.astro'; +import ProductCard from '../../../components/ProductCard.astro'; +import Landing from '../../../layouts/Landing.astro'; +import {productsOf, site, t} from '../../../lib/site'; + +export function getStaticPaths() { + return site().languages.map((language) => ({params: {lang: language.code}})); +} + +const {lang} = Astro.params as {lang: string}; +const packages = productsOf('package'); +--- + + +
+
+ +

{t(lang, 'packages')}

+

{t(lang, 'packagesDescription')}

+ { + packages.length > 0 ? ( +
+ {packages.map((product) => )} +
+ ) : ( +
+ +
+

{t(lang, 'packagesEmptyTitle')}

+

{t(lang, 'packagesEmptyText')}

+
+
+ ) + } +
+
+
diff --git a/src/styles/didactika.css b/src/styles/didactika.css index 9e48602..ccde43b 100644 --- a/src/styles/didactika.css +++ b/src/styles/didactika.css @@ -201,7 +201,6 @@ dialog.d-search::backdrop { background: rgb(2 8 10 / 60%); backdrop-filter: blur .d-search-hit em { font: 500 0.7rem var(--mono); color: var(--accent); font-style: normal; text-transform: uppercase; letter-spacing: 0.04em; } /* Starlight shows its own search and theme controls; the header of Didactika draws them. */ -@media (max-width: 72rem) { .d-search-btn { min-width: 0; } .d-search-btn span, .d-search-btn .d-kbd { display: none; } } @media (max-width: 62rem) { .d-hide-md { display: none !important; } } /* ------------------------------------------------------------------ sidebar ---- */ @@ -528,7 +527,7 @@ a.d-feature:hover { border-color: color-mix(in srgb, var(--accent) 55%, var(--li .d-paths .d-path { margin: 0; } /* The table of contents gives way to the foot (see ProjectFoot.astro). */ -.right-sidebar { height: calc(100vh - var(--sl-nav-height, 3.75rem) - var(--d-foot-overlap, 0px)); } +@media (min-width: 72rem) { .right-sidebar { height: calc(100vh - var(--sl-nav-height, 3.75rem) - var(--d-foot-overlap, 0px)); } } .d-footer { margin-top: 4rem; } .d-cardlink { display: inline-flex; align-items: center; gap: 0.3rem; margin-top: 0.7rem; color: var(--accent); font: 600 0.85rem var(--font); text-decoration: none; } @@ -541,3 +540,47 @@ a.d-feature:hover { border-color: color-mix(in srgb, var(--accent) 55%, var(--li .d-support h2 { margin: 0; font: 700 1.25rem/1.3 var(--display); } .d-support p { margin: 0.25rem 0 0; color: var(--muted); font-size: 0.92rem; } @media (max-width: 40rem) { .d-support { grid-template-columns: auto 1fr; } .d-support .d-btn { grid-column: 1 / -1; justify-content: center; } } + +/* The search sits after the product and the version, as in the design system, and takes the room that is left. */ +.d-head-search { flex: 1 1 14rem; max-width: 30rem; min-width: 0; margin-inline-start: 0.5rem; } +.d-head-search .d-search-btn { width: 100%; min-width: 0; } +.d-head-tools { margin-inline-start: auto; } + +/* Small screens: the mark alone, the search as a button, the colour and the language, and room for the button of the menu of Starlight. */ +@media (max-width: 62rem) { + .d-head { gap: 0.5rem; padding-inline: 0.75rem 3.9rem; } + .d-head-search { flex: 0 0 auto; max-width: none; margin-inline-start: auto; } + .d-head-search .d-search-btn { width: 2.25rem; padding: 0; justify-content: center; } + .d-head-search .d-search-btn span, .d-head-search .d-search-btn .d-kbd { display: none; } + .d-head-tools { margin-inline-start: 0; gap: 0.35rem; } + .d-brand .d-wordmark { display: none; } + .d-head-tools .d-heart, .d-head-tools .d-sep { display: none; } +} +@media (max-width: 26rem) { + .d-dd > summary .d-code { display: none; } +} + +/* On a small screen the header has no room for the product and its versions, so the menu opens with them. */ +.d-side-ctx { display: none; } +@media (max-width: 62rem) { + .d-side-ctx { display: grid; gap: 0.6rem; margin-bottom: 1rem; padding-bottom: 1rem; border-bottom: 1px solid var(--line); } + .d-side-ctx > b { display: flex; align-items: center; gap: 0.4rem; font: 700 1rem var(--display); } + .d-side-ctx > b .mi { color: var(--accent); } + .d-side-ctx .d-pill[aria-current='true'] { border-color: var(--accent); background: var(--accent-soft); color: var(--accent); } +} + +/* ----------------------------------------------------- home: sections and lists ---- */ + +.d-section-head { display: flex; align-items: flex-end; justify-content: space-between; gap: 1rem; flex-wrap: wrap; } +.d-section-head p { margin-bottom: 0; } +.d-stats-3 { grid-template-columns: repeat(3, 1fr); } +.d-band-in.single { grid-template-columns: 1fr; } +.d-empty, .d-more { display: grid; grid-template-columns: auto 1fr auto; align-items: center; gap: 1.2rem; margin-top: 1.4rem; padding: 1.4rem 1.6rem; border: 1px dashed var(--line); border-radius: var(--radius-lg); background: var(--panel); } +.d-empty h3, .d-more h2 { margin: 0; font: 700 1.1rem/1.3 var(--display); } +.d-more { margin-top: 0; border-style: solid; box-shadow: var(--shadow); } +.d-empty p, .d-more p { margin: 0.25rem 0 0; color: var(--muted); font-size: 0.92rem; } +@media (max-width: 40rem) { .d-stats-3 { grid-template-columns: 1fr; } .d-empty, .d-more { grid-template-columns: auto 1fr; } .d-more .d-btn { grid-column: 1 / -1; justify-content: center; } } + +/* The header already has the colour and the language, so the menu of a small screen does not repeat them. */ +.mobile-preferences { display: none; } +.d-pill { text-decoration: none; color: var(--ink); } diff --git a/tools/lib/source.ts b/tools/lib/source.ts index dca32a0..672f1df 100644 --- a/tools/lib/source.ts +++ b/tools/lib/source.ts @@ -42,6 +42,8 @@ export interface SourceProduct { component: string | null; /** The icon of the plugin (`pix/icon.svg` of the default branch), when it has one. */ iconSvg: string | null; + /** When the code of the product last changed, in seconds, on any of its lines. 0 when it is not known. */ + updated: number; lines: SourceLine[]; issues: Issue[]; } @@ -169,5 +171,7 @@ export function readProduct(repo: string, options: ReadOptions = {}): SourceProd const defaultPhp = defaultRef ? tryGit(repo, ['show', `${defaultRef}:version.php`]) : undefined; const iconSvg = defaultRef ? (tryGit(repo, ['show', `${defaultRef}:pix/icon.svg`]) ?? null) : null; - return {docs, component: defaultPhp ? readComponent(defaultPhp) : null, iconSvg, lines, issues}; + const updated = Math.max(0, ...[...found.values()].map((ref) => Number(tryGit(repo, ['log', '-1', '--format=%ct', ref])?.trim()) || 0)); + + return {docs, component: defaultPhp ? readComponent(defaultPhp) : null, iconSvg, updated, lines, issues}; } diff --git a/tools/sync.ts b/tools/sync.ts index f367c71..ac00e03 100644 --- a/tools/sync.ts +++ b/tools/sync.ts @@ -266,6 +266,7 @@ for (const entry of manifest.products) { icon, directory: {published: answer.published, url: answer.published ? (docs.directory?.url ?? (product.component ? directoryPage(product.component) : null)) : null, releases: answer.releases}, translations: docs.translations ?? {source: 'l10n'}, + updated: product.updated, lines: resolution.lines.map((line) => { const info = product.lines.find((candidate) => candidate.id === line.id)!; const ids = line.pages.filter((page) => page.lang === sourceCode).map((page) => page.id); From 51b283f3df30156d911760301e4303f2f6c04f7a Mon Sep 17 00:00:00 2001 From: hlaelissalt Date: Wed, 11 Nov 2026 22:46:10 +0100 Subject: [PATCH 8/8] feat: wording for plugins and libraries, not tied to one ecosystem --- src/i18n/en.json | 10 +++++----- src/i18n/es.json | 10 +++++----- 2 files changed, 10 insertions(+), 10 deletions(-) diff --git a/src/i18n/en.json b/src/i18n/en.json index 85bb880..a322315 100644 --- a/src/i18n/en.json +++ b/src/i18n/en.json @@ -1,8 +1,8 @@ { "plugins": "Plugins", - "pluginsDescription": "Moodle plugins developed by Didactika.", + "pluginsDescription": "Plugins developed by Didactika.", "packages": "Packages", - "packagesDescription": "Libraries and npm packages developed by Didactika.", + "packagesDescription": "Libraries and packages developed by Didactika.", "name": "Name", "summary": "Summary", "translationMissing": "This page is not available in {language} yet. You are reading the English version.", @@ -101,11 +101,11 @@ "tech.use-cases": "Use cases", "orgTechTitle": "Technical documentation", "orgTechText": "How each product is built: domain model, use cases, analysis, design and a map to the code, drawn in the colours of Didactika.", - "pluginsLead": "Moodle plugins, ordered by the most recent change.", - "packagesLead": "Libraries and npm packages for developers.", + "pluginsLead": "Ordered by the most recent change.", + "packagesLead": "Libraries and packages for developers.", "viewAll": "View all", "packagesEmptyTitle": "Libraries are coming", - "packagesEmptyText": "The documentation of the npm packages of Didactika will be published here, with the same structure as the plugins.", + "packagesEmptyText": "The documentation of the libraries of Didactika will be published here, with the same structure as the plugins.", "moreTitle": "More about Didactika", "moreText": "Every site, repository and service of Didactika, in one list.", "moreCta": "See all resources", diff --git a/src/i18n/es.json b/src/i18n/es.json index 45d9132..d10406e 100644 --- a/src/i18n/es.json +++ b/src/i18n/es.json @@ -1,8 +1,8 @@ { "plugins": "Plugins", - "pluginsDescription": "Plugins de Moodle desarrollados por Didactika.", + "pluginsDescription": "Plugins desarrollados por Didactika.", "packages": "Paquetes", - "packagesDescription": "Librerías y paquetes npm desarrollados por Didactika.", + "packagesDescription": "Librerías y paquetes desarrollados por Didactika.", "name": "Nombre", "summary": "Resumen", "translationMissing": "Esta página aún no está disponible en {language}. Estás leyendo la versión en inglés.", @@ -101,11 +101,11 @@ "tech.use-cases": "Casos de uso", "orgTechTitle": "Documentación técnica", "orgTechText": "Cómo está construido cada producto: modelo de dominio, casos de uso, análisis, diseño y un mapa hacia el código, dibujados con los colores de Didactika.", - "pluginsLead": "Plugins de Moodle, ordenados por el cambio más reciente.", - "packagesLead": "Librerías y paquetes npm para desarrolladores.", + "pluginsLead": "Ordenados por el cambio más reciente.", + "packagesLead": "Librerías y paquetes para desarrolladores.", "viewAll": "Ver todos", "packagesEmptyTitle": "Las librerías llegarán pronto", - "packagesEmptyText": "La documentación de los paquetes npm de Didactika se publicará aquí, con la misma estructura que los plugins.", + "packagesEmptyText": "La documentación de las librerías de Didactika se publicará aquí, con la misma estructura que los plugins.", "moreTitle": "Más sobre Didactika", "moreText": "Todos los sitios, repositorios y servicios de Didactika, en un único listado.", "moreCta": "Ver todos los recursos",