Skip to content

armgit / Pulse

Public Imported from GitHub
0

Real-time monitoring dashboard for Proxmox VE, PBS, Docker, Kubernetes, TrueNAS and vSphere. Self-hosted, with alerts for failed backups, full disks, unhealthy containers and offline nodes.

Render shipped documentation in-app instead of serving raw markdown

rcourtman29b9b324d941
diff --git a/frontend-modern/browser-verification.json b/frontend-modern/browser-verification.json
index 4e0ade11bb..eebd5659c9 100644
--- a/frontend-modern/browser-verification.json
+++ b/frontend-modern/browser-verification.json
@@ -1,23 +1,30 @@
{
"version": 1,
- "base_sha": "6bd382173bd802dbb0dbceb9c618ee01f645c55f",
- "verified_at": "2026-08-03T17:22:38Z",
+ "base_sha": "aac7acc6baf6d2f5544bbe2e682ad484631dd7b8",
+ "verified_at": "2026-08-03T17:57:38Z",
"result": "passed",
"changed_paths": [
- "frontend-modern/src/components/shared/FilterBar/FilterBar.tsx",
- "frontend-modern/src/features/kubernetes/KubernetesPageSurface.tsx",
- "frontend-modern/src/features/platformPage/sharedPlatformPage.tsx"
+ "frontend-modern/src/App.tsx",
+ "frontend-modern/src/features/docs/docMarkdown.ts",
+ "frontend-modern/src/pages/Docs.tsx",
+ "frontend-modern/src/utils/docsLinks.ts"
],
"content_sha256": {
- "frontend-modern/src/components/shared/FilterBar/FilterBar.tsx": "53162c174225e4e72dfbe5a9e6033357f649e8db2e0e160af8c20984e65917a8",
- "frontend-modern/src/features/kubernetes/KubernetesPageSurface.tsx": "0a8974f2f174914aa91658fee2016ee5e3f332ee18b8e8b1a0be8155960f8a6e",
- "frontend-modern/src/features/platformPage/sharedPlatformPage.tsx": "21163d3e2e3894139a51d3bec2a971928efc1cdb38a172c4272a696b1d7131c8"
+ "frontend-modern/src/App.tsx": "5cc14f31f3c84a843210897de1c1bd5f43da2e03fdbcb2e9e72781dc28cfa810",
+ "frontend-modern/src/features/docs/docMarkdown.ts": "2336e751c306d53f4702240be077f4a102de8598a8bf7bd75f4054940dce4cf2",
+ "frontend-modern/src/pages/Docs.tsx": "367abd0b3fdd1f7f35359b0e2edad5b9e388835bc95d2059d14fdafa49c9e892",
+ "frontend-modern/src/utils/docsLinks.ts": "a05d17c158823d9c9db07ae92c2b1ef7c81150805e2aff64593f9e6aa712e26e"
},
- "routes": ["/kubernetes/overview", "/kubernetes/workloads"],
+ "routes": [
+ "/docs/README",
+ "/docs/INSTALL",
+ "/docs/CONFIGURATION",
+ "/docs/ARCHITECTURE"
+ ],
"viewports": [
{
"width": 1280,
- "height": 720
+ "height": 900
},
{
"width": 390,
@@ -25,19 +32,21 @@
}
],
"states": [
- "Desktop Kubernetes Overview with three clusters, nineteen degraded workloads, and the compact workload-attention control aligned in the inventory toolbar",
- "Desktop Kubernetes Overview with routine workload degradation and no page-wide Kubernetes attention banner",
- "Phone-width Kubernetes Overview with the filter body collapsed and workload attention retained as visible leading context",
- "Phone-width Kubernetes Overview with the filter body expanded and workload attention composed into the canonical action rail",
- "Kubernetes Workloads destination after following the compact Review action",
- "Kubernetes empty-inventory state after the local runtime data reset"
+ "Desktop documentation index rendered from markdown with headings, lists, bold text and links instead of raw source",
+ "Desktop Installation Guide with nine fenced code blocks, two tables, blockquote and inline code all rendered",
+ "Desktop Configuration Guide with the full three-column table legible at 1280 pixels",
+ "Not-shipped document state for a path with no corresponding asset, showing an explanation and a route back to the index",
+ "Phone-width Configuration Guide with the wide table scrolling inside its own container and no page-level horizontal scroll",
+ "Phone-width document header with the back link above the rendered body"
],
"interactions": [
- "Confirmed routine pending and under-replicated workload counts render beside Review rather than in the page-wide attention summary",
- "Confirmed Review navigates directly to /kubernetes/workloads and marks Workloads as the active section",
- "Collapsed and expanded the 390-pixel filter body and confirmed leading workload context remains available while lower-priority trailing controls follow the collapsed rail",
- "Confirmed the workload status and Review action remain within the filter container with no page-level horizontal overflow",
- "Confirmed unavailable-node and critical-signal cases remain covered by the prominent attention summary while zero-value metrics are omitted",
- "Reloaded the final local build in Chrome and confirmed the Kubernetes empty-inventory fallback remained intact after the seeded runtime data reset"
+ "Loaded /docs/README and confirmed 52 intra-documentation links were rewritten to viewer routes, including nested i18n/de/README",
+ "Clicked the Installation Guide link and confirmed it navigated in-app to /docs/INSTALL, rendered the document, updated the tab title and revealed the All documentation back link",
+ "Confirmed ../SECURITY.md clamps to /docs/SECURITY rather than dangling above the shipped docs root",
+ "Requested /docs/ARCHITECTURE, which is not shipped, and confirmed the not-shipped state rather than an indefinite loading state or index.html rendered as markdown",
+ "Measured document scroll width against client width at 390 pixels and confirmed no page-level horizontal scrolling, with the table and pre blocks each scrolling inside their own container",
+ "Confirmed inline code no longer renders the typography plugin's literal backticks, which read as unrendered markdown",
+ "Queried the rendered article for script tags and inline event handlers after rendering a document containing both and confirmed neither survived sanitisation",
+ "Read the browser console after exercising every route and confirmed no errors"
]
}
diff --git a/frontend-modern/src/App.tsx b/frontend-modern/src/App.tsx
index 7e5d0dc2bc..f173ba52d2 100644
--- a/frontend-modern/src/App.tsx
+++ b/frontend-modern/src/App.tsx
@@ -76,7 +76,16 @@ import type { Resource } from '@/types/resource';
function isPublicRoutePath(pathname: string): boolean {
// Public routes must be viewable without authentication.
// Keep the list small and explicit.
- return pathname === '/pricing' || pathname === '/preview/setup-complete';
+ //
+ // Shipped documentation is included because the underlying markdown is
+ // already served unauthenticated at /docs/<name>.md. Gating the rendered
+ // view would make the readable form less reachable than its own source.
+ return (
+ pathname === '/pricing' ||
+ pathname === '/preview/setup-complete' ||
+ pathname === '/docs' ||
+ pathname.startsWith('/docs/')
+ );
}
function isWorkspaceEntryRoutePath(pathname: string): boolean {
@@ -101,6 +110,7 @@ const AIIntelligencePage = lazy(() =>
import('./pages/AIIntelligence').then((module) => ({ default: module.AIIntelligence })),
);
const NotFoundPage = lazy(() => import('./pages/NotFound'));
+const DocsPage = lazy(() => import('./pages/Docs'));
const PricingHandoffPage = lazy(() => import('./pages/PricingHandoff'));
const SetupCompletionPreviewPage = lazy(() =>
import('./components/SetupWizard/SetupCompletionPreview').then((module) => ({
@@ -596,6 +606,8 @@ function App() {
<Route path="/actions/*" component={ActionsPage} />
<Route path={`${ROOT_PATROL_PATH}/*`} component={AIIntelligencePage} />
<Route path="/settings/*" component={SettingsRoute} />
+ <Route path="/docs" component={DocsPage} />
+ <Route path="/docs/*docPath" component={DocsPage} />
<Route path="*all" component={NotFoundPage} />
</Router>
);
diff --git a/frontend-modern/src/components/Settings/__tests__/SecurityOverviewPanel.test.tsx b/frontend-modern/src/components/Settings/__tests__/SecurityOverviewPanel.test.tsx
index 00003d05e7..16b68b4802 100644
--- a/frontend-modern/src/components/Settings/__tests__/SecurityOverviewPanel.test.tsx
+++ b/frontend-modern/src/components/Settings/__tests__/SecurityOverviewPanel.test.tsx
@@ -29,7 +29,7 @@ describe('SecurityOverviewPanel', () => {
'href',
'/settings/security/api',
);
- expect(screen.getByText('Open security guide')).toHaveAttribute('href', '/docs/SECURITY.md');
+ expect(screen.getByText('Open security guide')).toHaveAttribute('href', '/docs/SECURITY');
expect(screen.getAllByText('Recommended')).toHaveLength(2);
});
diff --git a/frontend-modern/src/components/SetupWizard/__tests__/WelcomeStep.test.tsx b/frontend-modern/src/components/SetupWizard/__tests__/WelcomeStep.test.tsx
index 4f690303a8..cc8b4e33aa 100644
--- a/frontend-modern/src/components/SetupWizard/__tests__/WelcomeStep.test.tsx
+++ b/frontend-modern/src/components/SetupWizard/__tests__/WelcomeStep.test.tsx
@@ -77,7 +77,7 @@ describe('WelcomeStep', () => {
).toBeInTheDocument();
expect(screen.getByRole('link', { name: 'Full details' })).toHaveAttribute(
'href',
- '/docs/PRIVACY.md',
+ '/docs/PRIVACY',
);
expect(screen.getByText('What this token does')).toBeInTheDocument();
expect(
diff --git a/frontend-modern/src/components/__tests__/SecurityWarning.test.tsx b/frontend-modern/src/components/__tests__/SecurityWarning.test.tsx
index 569e4fecf7..8307d91a0b 100644
--- a/frontend-modern/src/components/__tests__/SecurityWarning.test.tsx
+++ b/frontend-modern/src/components/__tests__/SecurityWarning.test.tsx
@@ -84,7 +84,7 @@ describe('SecurityWarning', () => {
expect(banner).not.toHaveClass('fixed');
expect(screen.getByRole('link', { name: 'Learn More' })).toHaveAttribute(
'href',
- '/docs/SECURITY.md',
+ '/docs/SECURITY',
);
});
diff --git a/frontend-modern/src/components/__tests__/WhatsNewCard.test.tsx b/frontend-modern/src/components/__tests__/WhatsNewCard.test.tsx
index 63ab18b7bc..177d4959bc 100644
--- a/frontend-modern/src/components/__tests__/WhatsNewCard.test.tsx
+++ b/frontend-modern/src/components/__tests__/WhatsNewCard.test.tsx
@@ -73,7 +73,7 @@ describe('WhatsNewCard', () => {
expect(screen.getByRole('button', { name: 'Disable telemetry' })).toBeInTheDocument();
expect(screen.getByRole('link', { name: 'Privacy details' })).toHaveAttribute(
'href',
- '/docs/PRIVACY.md',
+ '/docs/PRIVACY',
);
});
diff --git a/frontend-modern/src/features/docs/__tests__/docMarkdown.test.ts b/frontend-modern/src/features/docs/__tests__/docMarkdown.test.ts
new file mode 100644
index 0000000000..448db4cc38
--- /dev/null
+++ b/frontend-modern/src/features/docs/__tests__/docMarkdown.test.ts
@@ -0,0 +1,155 @@
+import { describe, expect, it } from 'vitest';
+import {
+ docAssetUrlForPath,
+ docRouteForPath,
+ extractDocTitle,
+ normalizeDocPath,
+ renderDocMarkdown,
+ resolveDocLink,
+ stripLeadingTitle,
+ wrapTables,
+} from '../docMarkdown';
+
+describe('normalizeDocPath', () => {
+ it('strips the docs prefix, leading slashes, and the .md suffix', () => {
+ expect(normalizeDocPath('/docs/INSTALL.md')).toBe('INSTALL');
+ expect(normalizeDocPath('docs/i18n/de/README.md')).toBe('i18n/de/README');
+ expect(normalizeDocPath('INSTALL')).toBe('INSTALL');
+ expect(normalizeDocPath(' /FAQ.md ')).toBe('FAQ');
+ });
+});
+
+describe('doc URLs', () => {
+ it('separates the viewer route from the raw asset', () => {
+ expect(docRouteForPath('INSTALL.md')).toBe('/docs/INSTALL');
+ expect(docAssetUrlForPath('INSTALL')).toBe('/docs/INSTALL.md');
+ expect(docAssetUrlForPath('i18n/de/README.md')).toBe('/docs/i18n/de/README.md');
+ });
+});
+
+describe('resolveDocLink', () => {
+ it('resolves sibling documents', () => {
+ expect(resolveDocLink('README', 'INSTALL.md')).toBe('/docs/INSTALL');
+ expect(resolveDocLink('README', './FAQ.md')).toBe('/docs/FAQ');
+ });
+
+ it('resolves relative to the containing document', () => {
+ expect(resolveDocLink('i18n/de/README', '../README.md')).toBe('/docs/i18n/README');
+ expect(resolveDocLink('i18n/de/README', 'CONFIGURATION.md')).toBe(
+ '/docs/i18n/de/CONFIGURATION',
+ );
+ });
+
+ // Repo docs are authored for GitHub, where docs/ sits inside the repository,
+ // so they climb out of the docs directory. Under the shipped root there is
+ // nothing above it and those files ship flat, so the climb clamps.
+ it('clamps links that climb above the docs root', () => {
+ expect(resolveDocLink('README', '../SECURITY.md')).toBe('/docs/SECURITY');
+ expect(resolveDocLink('README', '../../TERMS.md')).toBe('/docs/TERMS');
+ });
+
+ it('preserves fragments', () => {
+ expect(resolveDocLink('README', 'CONFIGURATION.md#api-tokens')).toBe(
+ '/docs/CONFIGURATION#api-tokens',
+ );
+ });
+
+ it('ignores anything that is not an intra-doc markdown link', () => {
+ expect(resolveDocLink('README', 'https://example.com/page.md')).toBeNull();
+ expect(resolveDocLink('README', 'https://github.com/rcourtman/Pulse')).toBeNull();
+ expect(resolveDocLink('README', '#section')).toBeNull();
+ expect(resolveDocLink('README', 'mailto:[email protected]')).toBeNull();
+ });
+});
+
+describe('renderDocMarkdown', () => {
+ it('does not turn hard-wrapped prose into visible line breaks', () => {
+ // The AI chat renderer sets breaks: true, which would put a <br> between
+ // these two lines. Documentation is hard-wrapped, so that would break
+ // every paragraph in the shipped set.
+ const html = renderDocMarkdown('A wrapped\nparagraph.', 'README');
+ expect(html).not.toContain('<br');
+ expect(html).toContain('A wrapped\nparagraph.');
+ });
+
+ it('renders standard markdown structure', () => {
+ const html = renderDocMarkdown('# Title\n\n- one\n- two\n', 'README');
+ expect(html).toContain('<h1');
+ expect(html).toContain('<li>one</li>');
+ });
+
+ it('points intra-doc links at the viewer and marks them for routing', () => {
+ const html = renderDocMarkdown('[Install](INSTALL.md)', 'README');
+ expect(html).toContain('href="/docs/INSTALL"');
+ expect(html).toContain('data-doc-link');
+ expect(html).not.toContain('target="_blank"');
+ });
+
+ it('opens external links in a new tab', () => {
+ const html = renderDocMarkdown('[Site](https://example.com)', 'README');
+ expect(html).toContain('target="_blank"');
+ expect(html).toContain('rel="noopener noreferrer"');
+ });
+
+ it('strips scripts and event handlers', () => {
+ const html = renderDocMarkdown(
+ '<script>alert(1)</script>\n\n<img src=x onerror="alert(1)">\n\n[x](javascript:alert(1))',
+ 'README',
+ );
+ expect(html).not.toContain('<script');
+ expect(html).not.toContain('onerror');
+ expect(html).not.toContain('javascript:');
+ });
+});
+
+describe('wrapTables', () => {
+ // Making the table itself display:block; overflow-x:auto is not enough, its
+ // rows still lay out past the block box and push the page into horizontal
+ // scrolling on a phone. A wrapping element is what contains the overflow.
+ it('gives each table its own scroll container', () => {
+ const container = window.document.createElement('div');
+ container.innerHTML = '<table><tbody><tr><td>a</td></tr></tbody></table>';
+ wrapTables(container);
+ const wrapper = container.querySelector('[data-doc-table-scroll]');
+ expect(wrapper).not.toBeNull();
+ expect(wrapper?.className).toContain('overflow-x-auto');
+ expect(wrapper?.querySelector('table')).not.toBeNull();
+ });
+
+ it('does not wrap a table twice', () => {
+ const container = window.document.createElement('div');
+ container.innerHTML = '<table><tbody><tr><td>a</td></tr></tbody></table>';
+ wrapTables(container);
+ wrapTables(container);
+ expect(container.querySelectorAll('[data-doc-table-scroll]').length).toBe(1);
+ });
+});
+
+describe('stripLeadingTitle', () => {
+ it('removes the title the viewer promotes into the page header', () => {
+ expect(stripLeadingTitle('# Title\n\nBody text')).toBe('Body text');
+ });
+
+ it('leaves a level-one heading that is not the document title', () => {
+ const markdown = 'Intro paragraph\n\n# Later heading\n';
+ expect(stripLeadingTitle(markdown)).toBe(markdown);
+ });
+
+ it('leaves documents with no heading untouched', () => {
+ expect(stripLeadingTitle('Just body')).toBe('Just body');
+ });
+});
+
+describe('extractDocTitle', () => {
+ it('uses the first level-one heading', () => {
+ expect(extractDocTitle('# Installation Guide\n\nBody', 'fallback')).toBe('Installation Guide');
+ });
+
+ it('falls back when there is no heading', () => {
+ expect(extractDocTitle('Body only', 'INSTALL')).toBe('INSTALL');
+ });
+
+ it('does not treat a mid-document heading as the title', () => {
+ expect(extractDocTitle('Intro\n\n# Later heading', 'FAQ')).toBe('FAQ');
+ });
+});
diff --git a/frontend-modern/src/features/docs/docMarkdown.ts b/frontend-modern/src/features/docs/docMarkdown.ts
new file mode 100644
index 0000000000..2007a645f3
--- /dev/null
+++ b/frontend-modern/src/features/docs/docMarkdown.ts
@@ -0,0 +1,204 @@
+import { marked } from 'marked';
+import DOMPurify from 'dompurify';
+
+// Shipped documentation lives at /docs/<path>.md as a static asset. The
+// rendered viewer is the same path without the .md suffix, which cannot
+// collide because every shipped file ends in .md and anything else falls
+// through to the SPA.
+export const DOC_ROUTE_PREFIX = '/docs';
+
+export const docRouteForPath = (docPath: string): string =>
+ `${DOC_ROUTE_PREFIX}/${normalizeDocPath(docPath)}`;
+
+export const docAssetUrlForPath = (docPath: string): string =>
+ `${DOC_ROUTE_PREFIX}/${normalizeDocPath(docPath)}.md`;
+
+/** Strips a leading slash, a docs prefix, and a trailing .md suffix. */
+export function normalizeDocPath(raw: string): string {
+ let value = (raw ?? '').trim();
+ value = value.replace(/^\/+/, '');
+ if (value.toLowerCase().startsWith('docs/')) value = value.slice('docs/'.length);
+ value = value.replace(/\.md$/i, '');
+ value = value.replace(/^\/+|\/+$/g, '');
+ return value;
+}
+
+/**
+ * Resolves a relative markdown link against the document containing it.
+ *
+ * Repo docs are written for GitHub, where docs/ sits inside the repository, so
+ * they contain links such as `../SECURITY.md` that climb above the docs root.
+ * Under the shipped /docs root there is nothing above, and those files are
+ * shipped flat alongside the rest, so a climb that escapes the root is clamped
+ * to it rather than left dangling.
+ */
+export function resolveDocLink(currentDocPath: string, href: string): string | null {
+ const trimmed = (href ?? '').trim();
+ if (!trimmed || !/\.md(?:[?#].*)?$/i.test(trimmed)) return null;
+ if (/^[a-z][a-z0-9+.-]*:/i.test(trimmed)) return null; // absolute URL, not ours
+
+ const [pathPart, fragment = ''] = splitFragment(trimmed);
+ const baseSegments = normalizeDocPath(currentDocPath).split('/').slice(0, -1);
+ const segments = pathPart.startsWith('/') ? [] : [...baseSegments];
+
+ for (const segment of pathPart.replace(/^\/+/, '').split('/')) {
+ if (!segment || segment === '.') continue;
+ if (segment === '..') {
+ segments.pop();
+ continue;
+ }
+ segments.push(segment);
+ }
+
+ const resolved = normalizeDocPath(segments.join('/'));
+ if (!resolved) return null;
+ return `${docRouteForPath(resolved)}${fragment}`;
+}
+
+function splitFragment(value: string): [string, string] {
+ const index = value.search(/[?#]/);
+ if (index < 0) return [value, ''];
+ return [value.slice(0, index), value.slice(index)];
+}
+
+/**
+ * Renders shipped documentation markdown to sanitised HTML.
+ *
+ * Deliberately not the AI chat's renderMarkdown: that one sets `breaks: true`
+ * globally, which turns every hard-wrapped line in a normal document into a
+ * visible break, and pins hrefs to http/https/mailto, which strips the
+ * relative links that hold the documentation set together. Options are passed
+ * per parse call here so neither renderer can disturb the other.
+ */
+export function renderDocMarkdown(markdown: string, currentDocPath: string): string {
+ const source = typeof markdown === 'string' ? markdown : '';
+ const rawHtml = marked.parse(source, { gfm: true, breaks: false, async: false }) as string;
+
+ const sanitized = DOMPurify.sanitize(rawHtml, {
+ ALLOWED_TAGS: [
+ 'p',
+ 'br',
+ 'strong',
+ 'em',
+ 'b',
+ 'i',
+ 'u',
+ 'del',
+ 'code',
+ 'pre',
+ 'blockquote',
+ 'ul',
+ 'ol',
+ 'li',
+ 'h1',
+ 'h2',
+ 'h3',
+ 'h4',
+ 'h5',
+ 'h6',
+ 'a',
+ 'hr',
+ 'table',
+ 'thead',
+ 'tbody',
+ 'tr',
+ 'th',
+ 'td',
+ 'span',
+ 'div',
+ 'img',
+ 'details',
+ 'summary',
+ ],
+ // Relative hrefs must survive so intra-document links keep working; they
+ // are rewritten to viewer routes below. 'class' stays out for the same
+ // UI-redressing reason the chat renderer excludes it.
+ ALLOWED_ATTR: ['href', 'src', 'alt', 'title', 'id', 'align'],
+ ALLOWED_URI_REGEXP: /^(?:https?:|mailto:|[^a-z0-9+.-]|[^:]*$)/i,
+ });
+
+ return rewriteDocLinks(sanitized, currentDocPath);
+}
+
+/**
+ * Wraps tables in their own horizontal scroll container.
+ *
+ * Making the table itself `display: block; overflow-x: auto` is not enough:
+ * its rows still lay out past the block box, so a wide table pushes the whole
+ * page into horizontal scrolling on a phone. A wrapping element is what
+ * actually contains the overflow.
+ */
+export function wrapTables(container: HTMLElement): void {
+ container.querySelectorAll('table').forEach((table) => {
+ const parent = table.parentElement;
+ if (parent?.dataset?.docTableScroll !== undefined) return;
+ const wrapper = window.document.createElement('div');
+ wrapper.dataset.docTableScroll = '';
+ wrapper.className = 'max-w-full overflow-x-auto';
+ table.replaceWith(wrapper);
+ wrapper.appendChild(table);
+ });
+}
+
+/**
+ * Points intra-documentation links at the viewer instead of the raw asset, so
+ * following one renders the next document rather than downloading its source.
+ */
+export function rewriteDocLinks(html: string, currentDocPath: string): string {
+ if (typeof document === 'undefined') return html;
+ const container = document.createElement('div');
+ container.innerHTML = html;
+ wrapTables(container);
+
+ container.querySelectorAll('a[href]').forEach((anchor) => {
+ const href = anchor.getAttribute('href') ?? '';
+ const resolved = resolveDocLink(currentDocPath, href);
+ if (resolved) {
+ anchor.setAttribute('href', resolved);
+ anchor.setAttribute('data-doc-link', '');
+ anchor.removeAttribute('target');
+ anchor.removeAttribute('rel');
+ return;
+ }
+ if (/^https?:/i.test(href)) {
+ anchor.setAttribute('target', '_blank');
+ anchor.setAttribute('rel', 'noopener noreferrer');
+ }
+ });
+
+ return container.innerHTML;
+}
+
+/** First level-one heading, used as the document title. */
+export function extractDocTitle(markdown: string, fallback: string): string {
+ const index = leadingTitleLineIndex(markdown);
+ if (index < 0) return fallback;
+ return /^#\s+(.+?)\s*$/.exec((markdown ?? '').split('\n')[index])![1].trim();
+}
+
+/**
+ * Removes the leading level-one heading, which the viewer promotes into the
+ * page header. Leaving it in renders the document title twice.
+ */
+export function stripLeadingTitle(markdown: string): string {
+ const lines = (markdown ?? '').split('\n');
+ const index = leadingTitleLineIndex(markdown);
+ if (index < 0) return markdown ?? '';
+ lines.splice(index, 1);
+ while (lines.length && lines[0].trim() === '') lines.shift();
+ return lines.join('\n');
+}
+
+/**
+ * Index of the document's own title line, meaning a level-one heading that
+ * appears before any other content. A `# ` further down belongs to the body.
+ */
+function leadingTitleLineIndex(markdown: string): number {
+ const lines = (markdown ?? '').split('\n');
+ for (let index = 0; index < lines.length; index += 1) {
+ const line = lines[index];
+ if (line.trim() === '') continue;
+ return /^#\s+.+/.test(line) ? index : -1;
+ }
+ return -1;
+}
diff --git a/frontend-modern/src/pages/Docs.tsx b/frontend-modern/src/pages/Docs.tsx
new file mode 100644
index 0000000000..b0d9867e91
--- /dev/null
+++ b/frontend-modern/src/pages/Docs.tsx
@@ -0,0 +1,130 @@
+import { useNavigate, useParams } from '@solidjs/router';
+import { Show, createMemo, createResource } from 'solid-js';
+import { PageHeader } from '@/components/shared/PageHeader';
+import {
+ docAssetUrlForPath,
+ docRouteForPath,
+ extractDocTitle,
+ normalizeDocPath,
+ renderDocMarkdown,
+ stripLeadingTitle,
+} from '@/features/docs/docMarkdown';
+
+const DOCS_INDEX_PATH = 'README';
+
+async function fetchDoc(docPath: string): Promise<string> {
+ const response = await fetch(docAssetUrlForPath(docPath), {
+ headers: { Accept: 'text/markdown, text/plain' },
+ });
+ if (!response.ok) {
+ throw new Error(String(response.status));
+ }
+ // A document that is not shipped does not 404. Both the Go static handler
+ // and the dev server fall back to index.html for any unmatched non-API
+ // path, including one ending in .md, so the only reliable signal that the
+ // asset is missing is getting HTML back instead of markdown.
+ if (isHtmlResponse(response)) {
+ throw new Error('not-shipped');
+ }
+ return response.text();
+}
+
+export function isHtmlResponse(response: Pick<Response, 'headers'>): boolean {
+ const contentType = response.headers.get('content-type') ?? '';
+ return contentType.toLowerCase().includes('text/html');
+}
+
+export default function Docs() {
+ const params = useParams<{ docPath?: string }>();
+ const navigate = useNavigate();
+
+ const docPath = createMemo(() => normalizeDocPath(params.docPath ?? '') || DOCS_INDEX_PATH);
+ const [document] = createResource(docPath, fetchDoc);
+
+ // Reading a resource that rejected re-throws, so the error has to be checked
+ // before the accessor is touched or the failure escapes the memo instead of
+ // reaching the error branch below.
+ const markdown = createMemo(() => (document.error ? undefined : document()));
+
+ const title = createMemo(() => {
+ const fallback = docPath().split('/').pop() ?? 'Documentation';
+ const source = markdown();
+ return source ? extractDocTitle(source, fallback) : fallback;
+ });
+
+ const html = createMemo(() => {
+ const source = markdown();
+ // The leading heading is promoted into the page header above.
+ return source ? renderDocMarkdown(stripLeadingTitle(source), docPath()) : '';
+ });
+
+ // Intra-documentation links are rewritten to viewer routes by the renderer.
+ // Delegate their clicks to the router so following one does not reload the
+ // application shell.
+ const handleClick = (event: MouseEvent) => {
+ if (event.defaultPrevented || event.button !== 0) return;
+ if (event.metaKey || event.ctrlKey || event.shiftKey || event.altKey) return;
+ const anchor = (event.target as Element | null)?.closest?.('a[data-doc-link]');
+ const href = anchor?.getAttribute('href');
+ if (!href) return;
+ event.preventDefault();
+ navigate(href);
+ };
+
+ return (
+ <div class="mx-auto w-full max-w-4xl space-y-4">
+ <PageHeader
+ title={title()}
+ description="Documentation shipped with this Pulse installation."
+ />
+
+ <Show when={docPath() !== DOCS_INDEX_PATH}>
+ <a
+ href={docRouteForPath(DOCS_INDEX_PATH)}
+ data-doc-link=""
+ onClick={handleClick}
+ class="inline-flex items-center gap-1 text-sm text-blue-600 hover:underline dark:text-blue-400"
+ >
+ &larr; All documentation
+ </a>
+ </Show>
+
+ <Show
+ when={!document.loading}
+ fallback={<p class="text-sm text-muted">Loading documentation&hellip;</p>}
+ >
+ <Show
+ when={!document.error}
+ fallback={
+ <div class="space-y-2">
+ <p class="text-sm text-muted">
+ That document is not part of this installation's shipped documentation set.
+ </p>
+ <a
+ href={docRouteForPath(DOCS_INDEX_PATH)}
+ data-doc-link=""
+ onClick={handleClick}
+ class="text-sm text-blue-600 hover:underline dark:text-blue-400"
+ >
+ Back to the documentation index
+ </a>
+ </div>
+ }
+ >
+ <article
+ // Typography renders inline code wrapped in literal backticks by
+ // default, which reads as unrendered markdown. Tables get their
+ // scroll container from wrapTables rather than prose utilities.
+ // Inline code must be able to break, because a long unbreakable
+ // URL in one otherwise pushes the whole page into horizontal
+ // scrolling on a phone; code inside pre keeps its own scrollbar.
+ class="prose prose-sm max-w-none dark:prose-invert prose-pre:overflow-x-auto prose-code:before:content-none prose-code:after:content-none [&_:not(pre)>code]:break-words"
+ onClick={handleClick}
+ // eslint-disable-next-line solid/no-innerhtml -- renderDocMarkdown sanitises with DOMPurify
+ innerHTML={html()}
+ />
+ </Show>
+ </Show>
+ </div>
+ );
+}
diff --git a/frontend-modern/src/pages/__tests__/Docs.test.ts b/frontend-modern/src/pages/__tests__/Docs.test.ts
new file mode 100644
index 0000000000..28c969ae20
--- /dev/null
+++ b/frontend-modern/src/pages/__tests__/Docs.test.ts
@@ -0,0 +1,25 @@
+import { describe, expect, it } from 'vitest';
+import { isHtmlResponse } from '../Docs';
+
+// A document that is not shipped does not 404. The Go static handler and the
+// dev server both fall back to index.html for any unmatched non-API path,
+// including one ending in .md, so response.ok stays true and the only signal
+// that the asset is missing is the content type.
+describe('isHtmlResponse', () => {
+ const withContentType = (value: string | null) => ({
+ headers: { get: () => value } as unknown as Headers,
+ });
+
+ it('detects the SPA fallback that stands in for a missing document', () => {
+ expect(isHtmlResponse(withContentType('text/html'))).toBe(true);
+ expect(isHtmlResponse(withContentType('text/html; charset=utf-8'))).toBe(true);
+ expect(isHtmlResponse(withContentType('TEXT/HTML'))).toBe(true);
+ });
+
+ it('accepts the content types the shipped docs are actually served with', () => {
+ // text/plain from the Go static handler, text/markdown from vite.
+ expect(isHtmlResponse(withContentType('text/plain; charset=utf-8'))).toBe(false);
+ expect(isHtmlResponse(withContentType('text/markdown'))).toBe(false);
+ expect(isHtmlResponse(withContentType(null))).toBe(false);
+ });
+});
diff --git a/frontend-modern/src/stores/__tests__/systemSettings.test.ts b/frontend-modern/src/stores/__tests__/systemSettings.test.ts
index 0643356ad3..f2a8dcd814 100644
--- a/frontend-modern/src/stores/__tests__/systemSettings.test.ts
+++ b/frontend-modern/src/stores/__tests__/systemSettings.test.ts
@@ -87,7 +87,7 @@ describe('systemSettings store', () => {
});
it('keeps the telemetry disclosure on the shipped local privacy doc', () => {
- expect(PRIVACY_DOC_URL).toBe('/docs/PRIVACY.md');
+ expect(PRIVACY_DOC_URL).toBe('/docs/PRIVACY');
});
it('keeps the telemetry disclosure in user-facing product language', () => {
diff --git a/frontend-modern/src/utils/__tests__/docsLinks.test.ts b/frontend-modern/src/utils/__tests__/docsLinks.test.ts
index 5e7b01243a..332725dd60 100644
--- a/frontend-modern/src/utils/__tests__/docsLinks.test.ts
+++ b/frontend-modern/src/utils/__tests__/docsLinks.test.ts
@@ -60,17 +60,20 @@ function getRuntimeSourceFiles(dir: string): string[] {
}
describe('docsLinks', () => {
+ // These now resolve to the in-app viewer route rather than the raw asset.
+ // The raw file is still served at the same path plus .md, which is what the
+ // viewer fetches, so the source remains reachable.
it('returns canonical shipped doc URLs', () => {
expect(SHIPPED_DOCS_ROOT).toBe('/docs');
- expect(getShippedDocUrl('PRIVACY.md')).toBe('/docs/PRIVACY.md');
- expect(PRIVACY_DOC_URL).toBe('/docs/PRIVACY.md');
- expect(README_DOC_URL).toBe('/docs/README.md');
- expect(MIGRATION_GUIDE_DOC_URL).toBe('/docs/MIGRATION_UNIFIED_NAV.md');
- expect(CONFIGURATION_DOC_URL).toBe('/docs/CONFIGURATION.md');
- expect(PROXY_AUTH_DOC_URL).toBe('/docs/PROXY_AUTH.md');
- expect(SECURITY_DOC_URL).toBe('/docs/SECURITY.md');
- expect(TERMS_DOC_URL).toBe('/docs/TERMS.md');
- expect(API_TOKEN_SCOPES_DOC_URL).toBe('/docs/CONFIGURATION.md');
+ expect(getShippedDocUrl('PRIVACY.md')).toBe('/docs/PRIVACY');
+ expect(PRIVACY_DOC_URL).toBe('/docs/PRIVACY');
+ expect(README_DOC_URL).toBe('/docs/README');
+ expect(MIGRATION_GUIDE_DOC_URL).toBe('/docs/MIGRATION_UNIFIED_NAV');
+ expect(CONFIGURATION_DOC_URL).toBe('/docs/CONFIGURATION');
+ expect(PROXY_AUTH_DOC_URL).toBe('/docs/PROXY_AUTH');
+ expect(SECURITY_DOC_URL).toBe('/docs/SECURITY');
+ expect(TERMS_DOC_URL).toBe('/docs/TERMS');
+ expect(API_TOKEN_SCOPES_DOC_URL).toBe('/docs/CONFIGURATION');
});
it('keeps shipped docs content synced with repo docs', () => {
diff --git a/frontend-modern/src/utils/docsLinks.ts b/frontend-modern/src/utils/docsLinks.ts
index 1db950cc9a..2e9130be82 100644
--- a/frontend-modern/src/utils/docsLinks.ts
+++ b/frontend-modern/src/utils/docsLinks.ts
@@ -1,7 +1,14 @@
+import { docRouteForPath } from '@/features/docs/docMarkdown';
+
export const SHIPPED_DOCS_ROOT = '/docs';
+/**
+ * URL for a shipped document. This resolves to the in-app viewer route, which
+ * renders the markdown. The raw source stays served at `/docs/<name>.md` for
+ * anyone who wants the file itself.
+ */
export function getShippedDocUrl(filename: string): string {
- return `${SHIPPED_DOCS_ROOT}/${filename}`;
+ return docRouteForPath(filename);
}
export const README_DOC_URL = getShippedDocUrl('README.md');