diff --git a/.github/workflows/docs.yml b/.github/workflows/docs.yml index 3b6b386..a0f6883 100644 --- a/.github/workflows/docs.yml +++ b/.github/workflows/docs.yml @@ -8,21 +8,24 @@ name: Documentation on: pull_request: branches: [ master ] - paths: &docs_paths + push: + branches: [ master ] + paths: - 'docs/**' - 'zensical.toml' - 'README.md' - 'pom.xml' + - 'mvnw' + - '.mvn/**' - '.github/workflows/docs.yml' + - 'src/main/resources/application.properties' + - 'src/main/resources/application-test.properties' - 'src/main/java/xyz/subho/clone/twitter/config/OpenApiConfig.java' - 'src/main/java/xyz/subho/clone/twitter/constant/**' - 'src/main/java/xyz/subho/clone/twitter/controller/**' - 'src/main/java/xyz/subho/clone/twitter/model/**' - 'src/main/java/xyz/subho/clone/twitter/security/SecurityConfig.java' - 'src/test/java/xyz/subho/clone/twitter/OpenApiDocumentationTest.java' - push: - branches: [ master ] - paths: *docs_paths workflow_dispatch: permissions: @@ -39,42 +42,81 @@ jobs: steps: - name: Checkout code uses: actions/checkout@v7 + with: + fetch-depth: 0 + - name: Detect documentation changes + if: github.event_name == 'pull_request' + id: documentation + env: + BASE_SHA: ${{ github.event.pull_request.base.sha }} + HEAD_SHA: ${{ github.event.pull_request.head.sha }} + run: | + changed_paths="$(mktemp)" + trap 'rm -f "$changed_paths"' EXIT + if ! git diff --no-renames --name-only -z "$BASE_SHA...$HEAD_SHA" > "$changed_paths"; then + echo '::error::Unable to compute the pull-request diff' + exit 1 + fi + if grep -zEq '^(docs/|zensical\.toml$|README\.md$|pom\.xml$|mvnw$|\.mvn/|\.github/workflows/docs\.yml$|src/main/resources/application(-test)?\.properties$|src/main/java/xyz/subho/clone/twitter/(config/OpenApiConfig\.java$|constant/|controller/|model/|security/SecurityConfig\.java$)|src/test/java/xyz/subho/clone/twitter/OpenApiDocumentationTest\.java$)' "$changed_paths"; then + echo 'affected=true' >> "$GITHUB_OUTPUT" + else + grep_status=$? + if [ "$grep_status" -eq 1 ]; then + echo 'affected=false' >> "$GITHUB_OUTPUT" + else + echo '::error::Unable to match changed documentation paths' + exit 1 + fi + fi - name: Set up Microsoft JDK 25 + if: github.event_name != 'pull_request' || steps.documentation.outputs.affected == 'true' uses: actions/setup-java@v6 with: distribution: 'microsoft' java-version: '25' cache: 'maven' - name: Export OpenAPI + if: github.event_name != 'pull_request' || steps.documentation.outputs.affected == 'true' run: ./mvnw -B -Dtest=OpenApiDocumentationTest test - name: Set up Python + if: github.event_name != 'pull_request' || steps.documentation.outputs.affected == 'true' uses: actions/setup-python@v6 with: python-version: '3.13' cache: 'pip' cache-dependency-path: docs/tooling/requirements.txt - name: Install Zensical + if: github.event_name != 'pull_request' || steps.documentation.outputs.affected == 'true' run: 'pip install --require-hashes --only-binary :all: -r docs/tooling/requirements.txt' - name: Set up Node.js + if: github.event_name != 'pull_request' || steps.documentation.outputs.affected == 'true' uses: actions/setup-node@v6 with: node-version: '22' cache: 'npm' cache-dependency-path: docs/tooling/package-lock.json - name: Install API documentation tooling + if: github.event_name != 'pull_request' || steps.documentation.outputs.affected == 'true' run: npm --prefix docs/tooling ci --ignore-scripts - name: Build Markdown site + if: github.event_name != 'pull_request' || steps.documentation.outputs.affected == 'true' run: zensical build --clean --strict - name: Validate and build API reference + if: github.event_name != 'pull_request' || steps.documentation.outputs.affected == 'true' run: | npm --prefix docs/tooling run api:lint npm --prefix docs/tooling run api:build cp target/generated-docs/openapi.json site/api/openapi.json env: REDOCLY_TELEMETRY: off + - name: Check mobile layout + if: github.event_name != 'pull_request' || steps.documentation.outputs.affected == 'true' + run: npm --prefix docs/tooling run site:mobile-check - name: Configure GitHub Pages + if: github.event_name != 'pull_request' || steps.documentation.outputs.affected == 'true' uses: actions/configure-pages@v6 - name: Upload GitHub Pages artifact + if: github.event_name != 'pull_request' || steps.documentation.outputs.affected == 'true' uses: actions/upload-pages-artifact@v5 with: path: site diff --git a/docs/styles.css b/docs/styles.css new file mode 100644 index 0000000..88e08bf --- /dev/null +++ b/docs/styles.css @@ -0,0 +1,10 @@ +@media screen and (max-width: 44.984375rem) { + .md-typeset__scrollwrap, + .md-typeset details .md-typeset__scrollwrap { + margin-inline: 0; + } + + .md-typeset__table { + width: 100%; + } +} diff --git a/docs/tooling/check-mobile-layout.mjs b/docs/tooling/check-mobile-layout.mjs new file mode 100644 index 0000000..8cfc917 --- /dev/null +++ b/docs/tooling/check-mobile-layout.mjs @@ -0,0 +1,160 @@ +import { execFileSync, spawn } from "node:child_process"; +import { mkdtemp, readFile, rm } from "node:fs/promises"; +import { tmpdir } from "node:os"; +import { join } from "node:path"; + +const chrome = process.env.CHROME_PATH ?? findChrome(); + +function findChrome() { + if (process.platform === "darwin") { + return "/Applications/Google Chrome.app/Contents/MacOS/Google Chrome"; + } + for (const command of ["google-chrome", "google-chrome-stable", "chromium", "chromium-browser"]) { + try { + return execFileSync("which", [command], { encoding: "utf8" }).trim(); + } catch {} + } + throw new Error("No supported Chrome or Chromium executable was found"); +} +const profile = await mkdtemp(join(tmpdir(), "moo-docs-chrome-")); +const server = spawn("python3", ["-m", "http.server", "4173", "-d", "../../site"], { + cwd: import.meta.dirname, + stdio: "ignore", +}); +for (let attempt = 0; attempt < 50; attempt++) { + try { + const response = await fetch("http://127.0.0.1:4173/"); + if (response.ok) break; + } catch {} + await new Promise((resolve) => setTimeout(resolve, 100)); +} +const browser = spawn( + chrome, + [ + "--headless=new", + "--no-sandbox", + "--disable-dev-shm-usage", + "--remote-debugging-port=0", + `--user-data-dir=${profile}`, + "http://127.0.0.1:4173/", + ], + { stdio: ["ignore", "ignore", "pipe"] }, +); +let browserError = ""; +browser.stderr.on("data", (data) => { + browserError += data.toString(); +}); +browser.on("error", (error) => { + browserError += `${error.message}\n`; +}); +const browserExit = new Promise((resolve) => browser.once("close", resolve)); +const serverExit = new Promise((resolve) => server.once("close", resolve)); + +const waitForTabs = async () => { + for (let attempt = 0; attempt < 300; attempt++) { + if (browser.exitCode !== null || browser.signalCode !== null) { + throw new Error(`Chrome did not start${browserError ? `: ${browserError.trim()}` : ""}`); + } + try { + const [port] = (await readFile(join(profile, "DevToolsActivePort"), "utf8")).split("\n"); + const response = await fetch(`http://127.0.0.1:${port}/json`); + if (response.ok) return response.json(); + } catch {} + await new Promise((resolve) => setTimeout(resolve, 100)); + } + throw new Error(`Chrome did not start${browserError ? `: ${browserError.trim()}` : ""}`); +}; + +try { + const tabs = await waitForTabs(); + const tab = tabs.find(({ type }) => type === "page"); + const socket = new WebSocket(tab.webSocketDebuggerUrl); + const pending = new Map(); + let requestId = 0; + let loadReject; + socket.onmessage = ({ data }) => { + const message = JSON.parse(data); + if (message.method === "Page.loadEventFired") { + pending.get("load")?.(); + pending.delete("load"); + } + pending.get(message.id)?.resolve(message); + pending.delete(message.id); + }; + socket.addEventListener("close", () => { + const error = new Error("Chrome DevTools connection closed"); + loadReject?.(error); + for (const pendingCall of pending.values()) pendingCall.reject?.(error); + pending.clear(); + }); + await new Promise((resolve) => (socket.onopen = resolve)); + const call = (method, params = {}) => + new Promise((resolve, reject) => { + const id = ++requestId; + pending.set(id, { resolve, reject }); + socket.send(JSON.stringify({ id, method, params })); + }); + await call("Page.enable"); + + for (const width of [320, 375]) { + await call("Emulation.setDeviceMetricsOverride", { + width, + height: 812, + deviceScaleFactor: 1, + mobile: true, + }); + const loaded = new Promise((resolve, reject) => { + const timeout = setTimeout(() => { + loadReject = undefined; + pending.delete("load"); + reject(new Error(`Page did not load at ${width}px`)); + }, 10_000); + loadReject = (error) => { + clearTimeout(timeout); + loadReject = undefined; + pending.delete("load"); + reject(error); + }; + pending.set("load", () => { + clearTimeout(timeout); + loadReject = undefined; + resolve(); + }); + }); + await Promise.race([call("Page.reload"), loaded]); + await loaded; + let layout; + for (let attempt = 0; attempt < 50 && !layout; attempt++) { + const result = await call("Runtime.evaluate", { + expression: `(() => { + const root = document.documentElement; + const article = document.querySelector("article"); + if (!article) return null; + const bounds = article.getBoundingClientRect(); + const clipped = [...article.querySelectorAll("*")] + .filter((element) => { + const rect = element.getBoundingClientRect(); + return !element.closest("pre") && rect.width > 0 && (rect.left < bounds.left - 1 || rect.right > bounds.right + 1); + }) + .map((element) => element.tagName + "." + element.className) + .slice(0, 5); + return { rootFits: root.scrollWidth <= root.clientWidth, clipped }; + })()`, + returnByValue: true, + }); + layout = result.result.result.value; + if (!layout) await new Promise((resolve) => setTimeout(resolve, 100)); + } + if (!layout) throw new Error(`${width}px layout did not load`); + if (!layout.rootFits || layout.clipped.length) { + throw new Error(`${width}px layout overflows: ${layout.clipped.join(", ")}`); + } + } + socket.close(); + console.log("Mobile layout fits at 320px and 375px"); +} finally { + browser.kill(); + server.kill(); + await Promise.all([browserExit, serverExit]); + await rm(profile, { recursive: true, force: true, maxRetries: 5, retryDelay: 100 }); +} diff --git a/docs/tooling/finalize-api-reference.mjs b/docs/tooling/finalize-api-reference.mjs new file mode 100644 index 0000000..4d51006 --- /dev/null +++ b/docs/tooling/finalize-api-reference.mjs @@ -0,0 +1,32 @@ +import { copyFile, mkdir, readFile, writeFile } from "node:fs/promises"; + +const output = new URL("../../site/api/reference/index.html", import.meta.url); +const basePath = "/twitter-backend-java/api/reference"; +const canonicalUrl = `https://subho.xyz${basePath}/`; +const description = "Interactive OpenAPI reference for the Moo Twitter Backend."; +const routes = ["authentication", "hashtags", "models", "posts", "search", "users"]; +let html = await readFile(output, "utf8"); +const scriptStart = html.indexOf('