Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion package.json
Original file line number Diff line number Diff line change
Expand Up @@ -26,7 +26,7 @@
"quality:readability": "node scripts/quality/readability.mjs",
"quality:fix": "node scripts/quality/fix-loop.mjs",
"slack:sync": "node scripts/sync-team-slack-map.mjs",
"test:scripts": "bash scripts/test-slugify.sh && bash scripts/test-heading-skip.sh && bash scripts/test-md-extension-autofix.sh && node --test scripts/test-set-blob-metadata.mjs && node scripts/test-set-blob-metadata-integration.mjs && node --test scripts/claude/test-log-summary.mjs && node --test scripts/test-vale-local.mjs && node --test scripts/test-resolve-path-labels.mjs && node --test scripts/test-sync-team-slack-map.mjs && node --test scripts/test-preserve-content.mjs && node --test scripts/test-seo.mjs && node --test scripts/test-vale-scope.mjs && node --test src/plugins/robotsTxt.test.mjs && node --test src/plugins/llmsTxt.test.mjs && node --test src/utils/markdownSource.test.mjs && node --test src/config/docVariables.test.mjs && node --test src/config/products.test.mjs && node scripts/quality/gen-lint-digest.mjs --check",
"test:scripts": "bash scripts/test-slugify.sh && bash scripts/test-heading-skip.sh && bash scripts/test-md-extension-autofix.sh && node --test scripts/test-set-blob-metadata.mjs && node scripts/test-set-blob-metadata-integration.mjs && node --test scripts/claude/test-log-summary.mjs && node --test scripts/test-vale-local.mjs && node --test scripts/test-resolve-path-labels.mjs && node --test scripts/test-sync-team-slack-map.mjs && node --test scripts/test-preserve-content.mjs && node --test scripts/test-seo.mjs && node --test scripts/test-vale-scope.mjs && node --test src/plugins/robotsTxt.test.mjs && node --test src/plugins/llmsTxt.test.mjs && node --test src/utils/markdownSource.test.mjs && node --test src/utils/renderMarkdownSource.test.mjs && node --test src/utils/aiProviders.test.mjs && node --test src/config/docVariables.test.mjs && node --test src/config/products.test.mjs && node scripts/quality/gen-lint-digest.mjs --check",
"prepare": "node scripts/hooks/install.mjs"
},
"dependencies": {
Expand Down
79 changes: 63 additions & 16 deletions src/plugins/markdownSource.js
Original file line number Diff line number Diff line change
@@ -1,7 +1,9 @@
import {cpSync, existsSync, statSync} from 'fs';
import {join, relative, sep} from 'path';
import {existsSync, mkdirSync, readdirSync, readFileSync, writeFileSync} from 'fs';
import {createRequire} from 'module';
import {dirname, join, relative, resolve, sep} from 'path';
import {getActiveProducts} from '../config/products.js';
import {MD_SOURCE_BASE} from '../utils/markdownSource.js';
import {renderMarkdownSource} from '../utils/renderMarkdownSource.js';

// Copied KB articles (docs/<product>[/<version>]/kb) are gitignored duplicates of docs/kb.
const COPIED_KB = /^[^/]+\/(?:[^/]+\/)?kb(?:\/|$)/;
Expand All @@ -18,32 +20,77 @@ export function isServedSource(relPath, isDirectory) {
return isDirectory || /\.mdx?$/.test(posix);
}

/** Yields the served Markdown files under `dir` (absolute paths). */
function* servedFiles(docsDir, dir) {
for (const entry of readdirSync(dir, {withFileTypes: true})) {
const path = join(dir, entry.name);
if (!isServedSource(relative(docsDir, path), entry.isDirectory())) continue;
if (entry.isDirectory()) yield* servedFiles(docsDir, path);
else yield path;
}
}

/** The dev server's own source-map middleware, which setupMiddlewares below would replace. */
function loadEvalSourceMapMiddleware() {
try {
const mod = createRequire(import.meta.url)('@docusaurus/core/lib/commands/utils/legacy/evalSourceMapMiddleware');
return mod.default ?? mod;
} catch {
return null; // only affects the error overlay's source lookup
}
}

/**
* Serves each doc's Markdown source from the site itself at /md-source/<path under docs/>,
* so the Rendered/Markdown toggle and crawlers read the same version of the page the site
* so the Page/Markdown toggle and AI tools read the same version of the page the site
* renders: dev server, preview and production. Nothing is stale and nothing 404s on a new page.
* Partials are inlined and doc variables replaced (see renderMarkdownSource).
*/
export default function markdownSourcePlugin(context) {
const docsDir = join(context.siteDir, 'docs');
const render = (file) => renderMarkdownSource(readFileSync(file, 'utf8'), file, context.siteDir);

return {
name: 'markdown-source',
configureWebpack() {
return {devServer: {static: [{directory: docsDir, publicPath: MD_SOURCE_BASE, watch: false, serveIndex: false}]}};
const evalSourceMap = loadEvalSourceMapMiddleware();
return {
devServer: {
setupMiddlewares(middlewares, devServer) {
if (evalSourceMap) middlewares.unshift(evalSourceMap(devServer));
middlewares.unshift((req, res, next) => {
const url = (req.url || '').split('?')[0];
if (!url.startsWith(`${MD_SOURCE_BASE}/`)) return next();
let file;
try {
file = resolve(docsDir, decodeURIComponent(url.slice(MD_SOURCE_BASE.length + 1)));
} catch {
return next();
}
const rel = relative(docsDir, file);
if (rel.startsWith('..') || !isServedSource(rel, false) || !existsSync(file)) {
res.statusCode = 404;
return res.end('Not found');
}
res.setHeader('Content-Type', 'text/markdown; charset=utf-8');
return res.end(render(file));
});
return middlewares;
},
},
};
},
async postBuild({outDir}) {
// Copy only what the site renders: the active products (which leaves out devOnly
// Write only what the site renders: the active products (which leaves out devOnly
// products on production) and the KB. Nothing else under docs/ is published.
const dirs = [...getActiveProducts().map((p) => relative(docsDir, join(context.siteDir, p.path))), 'kb'];
for (const sub of dirs) {
const src = join(docsDir, sub);
if (!existsSync(src)) continue;
cpSync(src, join(outDir, MD_SOURCE_BASE, sub), {
recursive: true,
filter: (path) => {
const rel = relative(docsDir, path);
return rel === '' || isServedSource(rel, statSync(path).isDirectory());
},
});
const dirs = [...getActiveProducts().map((p) => join(context.siteDir, p.path)), join(docsDir, 'kb')];
for (const dir of dirs) {
if (!existsSync(dir)) continue;
for (const file of servedFiles(docsDir, dir)) {
const dest = join(outDir, MD_SOURCE_BASE, relative(docsDir, file));
mkdirSync(dirname(dest), {recursive: true});
writeFileSync(dest, render(file));
}
}
},
};
Expand Down
129 changes: 102 additions & 27 deletions src/theme/DocItem/Content/index.js
Original file line number Diff line number Diff line change
@@ -1,22 +1,31 @@
import React, {useEffect, useState} from 'react';
import React, {useCallback, useEffect, useRef, useState} from 'react';
import Content from '@theme-original/DocItem/Content';
import {useDoc} from '@docusaurus/plugin-content-docs/client';
import useBaseUrl from '@docusaurus/useBaseUrl';
import {markdownSourcePath} from '../../../utils/markdownSource';
import {AI_PROVIDERS, aiProviderHref} from '../../../utils/aiProviders';
import styles from './styles.module.css';

// Fetches the page's Markdown source once the reader switches to the Markdown view.
const cache = new Map(); // markdown URL -> text

// Fetches a page's Markdown source. The dev server answers unknown paths with index.html
// and a 200, so an HTML response counts as a failure.
async function fetchMarkdown(url) {
if (cache.has(url)) return cache.get(url);
const res = await fetch(url);
const isHtml = (res.headers.get('content-type') || '').includes('text/html');
if (!res.ok || isHtml) throw new Error(String(res.status));
const text = await res.text();
cache.set(url, text);
return text;
}

function useMarkdown(url, enabled) {
const [state, setState] = useState({url: null, status: 'idle', text: ''});
useEffect(() => {
if (!enabled || !url) return undefined;
let cancelled = false;
fetch(url)
.then((res) => {
// The dev server answers unknown paths with index.html and a 200.
const isHtml = (res.headers.get('content-type') || '').includes('text/html');
return res.ok && !isHtml ? res.text() : Promise.reject(new Error(String(res.status)));
})
fetchMarkdown(url)
.then((text) => !cancelled && setState({url, status: 'done', text}))
.catch(() => !cancelled && setState({url, status: 'error', text: ''}));
return () => {
Expand All @@ -27,13 +36,77 @@ function useMarkdown(url, enabled) {
return state.url === url ? state : {url, status: 'loading', text: ''};
}

function CopyButton({url}) {
const [label, setLabel] = useState('Copy page');
const copy = useCallback(async () => {
try {
await navigator.clipboard.writeText(await fetchMarkdown(url));
setLabel('Copied!');
} catch {
setLabel('Copy failed');
}
setTimeout(() => setLabel('Copy page'), 2000);
}, [url]);
return (
<button type="button" className="button button--secondary button--sm" onClick={copy}>
{label}
</button>
);
}

function OpenInMenu({pageUrl, markdownUrl}) {
const [open, setOpen] = useState(false);
const ref = useRef(null);
useEffect(() => {
if (!open) return undefined;
const onDown = (e) => ref.current && !ref.current.contains(e.target) && setOpen(false);
const onKey = (e) => e.key === 'Escape' && setOpen(false);
document.addEventListener('mousedown', onDown);
document.addEventListener('keydown', onKey);
return () => {
document.removeEventListener('mousedown', onDown);
document.removeEventListener('keydown', onKey);
};
}, [open]);
return (
<div ref={ref} className={`dropdown dropdown--right ${open ? 'dropdown--show' : ''}`}>
<button
type="button"
className="button button--secondary button--sm"
aria-haspopup="menu"
aria-expanded={open}
onClick={() => setOpen(!open)}>
Open in…
</button>
<ul className="dropdown__menu" role="menu">
{AI_PROVIDERS.map((provider) => (
<li key={provider.id} role="none">
<a
className="dropdown__link"
role="menuitem"
href={aiProviderHref(provider, {pageUrl, markdownUrl})}
target="_blank"
rel="noopener noreferrer"
onClick={() => setOpen(false)}>
{provider.label}
</a>
</li>
))}
</ul>
</div>
);
}

export default function ContentWrapper(props) {
const {metadata} = useDoc();
const path = markdownSourcePath(metadata.editUrl);
const markdownUrl = useBaseUrl(path || '/');
const [view, setView] = useState('rendered');
// Start each page on the rendered view.
useEffect(() => setView('rendered'), [metadata.permalink]);
const absoluteMarkdownUrl = useBaseUrl(path || '/', {absolute: true});
const pageUrl = useBaseUrl(metadata.permalink, {absolute: true});
// The view belongs to a page: following a link starts the next page on the Page tab.
const [viewState, setViewState] = useState({permalink: metadata.permalink, view: 'page'});
const view = viewState.permalink === metadata.permalink ? viewState.view : 'page';
const setView = (next) => setViewState({permalink: metadata.permalink, view: next});
const {status, text} = useMarkdown(markdownUrl, view === 'markdown');

if (!path) return <Content {...props} />;
Expand All @@ -57,24 +130,26 @@ export default function ContentWrapper(props) {

return (
<>
<ul role="tablist" className={`tabs ${styles.toggle}`}>
{tab('rendered', 'Page')}
{tab('markdown', 'Markdown')}
</ul>
{view === 'rendered' ? (
<div className={styles.bar}>
<ul role="tablist" className={`tabs ${styles.tabs}`}>
{tab('page', 'Page')}
{tab('markdown', 'Markdown')}
</ul>
<div className={styles.actions}>
<CopyButton url={markdownUrl} />
<OpenInMenu pageUrl={pageUrl} markdownUrl={absoluteMarkdownUrl} />
</div>
</div>
{view === 'page' ? (
<Content {...props} />
) : status === 'error' ? (
<p>The Markdown source could not be loaded.</p>
) : status === 'done' ? (
<pre className={styles.source}>
<code>{text}</code>
</pre>
) : (
<div>
{status === 'error' ? (
<p>The Markdown source could not be loaded.</p>
) : status === 'done' ? (
<pre className={styles.source}>
<code>{text}</code>
</pre>
) : (
<p>Loading…</p>
)}
</div>
<p>Loading…</p>
)}
</>
);
Expand Down
16 changes: 15 additions & 1 deletion src/theme/DocItem/Content/styles.module.css
Original file line number Diff line number Diff line change
@@ -1,7 +1,21 @@
.toggle {
.bar {
display: flex;
flex-wrap: wrap;
align-items: center;
justify-content: space-between;
gap: 0.5rem 1rem;
margin-bottom: 1rem;
}

.tabs {
margin-bottom: 0;
}

.actions {
display: flex;
gap: 0.5rem;
}

.source {
white-space: pre-wrap;
overflow-wrap: anywhere;
Expand Down
20 changes: 20 additions & 0 deletions src/utils/aiProviders.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,20 @@
/**
* "Open in …" targets. `context` picks which URL the assistant gets in its prompt:
* 'markdown' is the page's Markdown source (ChatGPT and Claude fetch a given URL live);
* 'page' is the HTML page (Gemini and Perplexity answer from their search index).
*/
export const AI_PROVIDERS = [
{id: 'chatgpt', label: 'Open in ChatGPT', url: 'https://chatgpt.com/?hints=search&q={prompt}', context: 'markdown'},
{id: 'claude', label: 'Open in Claude', url: 'https://claude.ai/new?q={prompt}', context: 'markdown'},
{id: 'gemini', label: 'Open in Gemini', url: 'https://www.google.com/search?udm=50&q={prompt}', context: 'page'},
{id: 'perplexity', label: 'Open in Perplexity', url: 'https://www.perplexity.ai/search/new?q={prompt}', context: 'page'},
];

export const AI_PROMPT = 'Read from {url} so I can ask questions about it.';

/** Link that opens `provider` with the prompt filled in for the given page and Markdown URLs. */
export function aiProviderHref(provider, {pageUrl, markdownUrl}) {
const url = provider.context === 'markdown' ? markdownUrl : pageUrl;
const prompt = AI_PROMPT.split('{url}').join(url);
return provider.url.split('{prompt}').join(encodeURIComponent(prompt));
}
17 changes: 17 additions & 0 deletions src/utils/aiProviders.test.mjs
Original file line number Diff line number Diff line change
@@ -0,0 +1,17 @@
import assert from 'node:assert/strict';
import {test} from 'node:test';
import {AI_PROVIDERS, aiProviderHref} from './aiProviders.js';

const urls = {pageUrl: 'https://docs.example.com/docs/a/1/x', markdownUrl: 'https://docs.example.com/md-source/a/1.0/x.md'};
const href = (id) => aiProviderHref(AI_PROVIDERS.find((p) => p.id === id), urls);

test('ChatGPT and Claude get the Markdown URL, the others the page URL', () => {
assert.ok(decodeURIComponent(href('chatgpt')).includes(urls.markdownUrl));
assert.ok(decodeURIComponent(href('claude')).includes(urls.markdownUrl));
assert.ok(decodeURIComponent(href('gemini')).includes(urls.pageUrl));
assert.ok(decodeURIComponent(href('perplexity')).includes(urls.pageUrl));
});

test('the prompt is URL-encoded into the provider link', () => {
assert.match(href('claude'), /^https:\/\/claude\.ai\/new\?q=Read%20from%20https%3A%2F%2F/);
});
Loading
Loading