zed/docs/theme/plugins.js
morgankrey 10504e3ce1
Some checks are pending
Congratsbot / check-author (push) Waiting to run
Congratsbot / congrats (push) Blocked by required conditions
deploy_nightly_docs / deploy_docs (push) Waiting to run
run_tests / orchestrate (push) Waiting to run
run_tests / check_style (push) Waiting to run
run_tests / clippy_windows (push) Blocked by required conditions
run_tests / clippy_linux (push) Blocked by required conditions
run_tests / clippy_mac (push) Blocked by required conditions
run_tests / clippy_mac_x86_64 (push) Blocked by required conditions
run_tests / run_tests_windows (push) Blocked by required conditions
run_tests / run_tests_linux (push) Blocked by required conditions
run_tests / run_tests_mac (push) Blocked by required conditions
run_tests / miri_scheduler (push) Blocked by required conditions
run_tests / doctests (push) Blocked by required conditions
run_tests / check_workspace_binaries (push) Blocked by required conditions
run_tests / build_visual_tests_binary (push) Blocked by required conditions
run_tests / check_wasm (push) Blocked by required conditions
run_tests / check_dependencies (push) Blocked by required conditions
run_tests / check_docs (push) Blocked by required conditions
run_tests / check_licenses (push) Blocked by required conditions
run_tests / check_scripts (push) Blocked by required conditions
run_tests / check_postgres_and_protobuf_migrations (push) Blocked by required conditions
run_tests / extension_tests (push) Blocked by required conditions
run_tests / tests_pass (push) Blocked by required conditions
Improve docs AI readiness (#59577)
Context

This PR makes the Zed docs easier for AI tools, search crawlers, and
users to consume without changing the visible docs content. The current
production docs are primarily optimized for browser navigation. They do
not expose first-class Markdown URLs, an `llms.txt` index, page-level
copy affordances, or machine-readable freshness metadata that let users
and agents grab clean, current page content.

Changes

- Generate Markdown copies for docs pages during the mdBook postprocess
step, including `/docs/index.md` as an alias for Getting Started.
- Generate `/docs/llms.txt` from the mdBook chapter list, grouped by
`SUMMARY.md` sections and annotated with page frontmatter descriptions.
- Generate `/docs/sitemap.xml` with `<lastmod>` values for every docs
page.
- Emit machine-readable freshness metadata in HTML via `last-modified`
and `article:modified_time` meta tags.
- Generate Cloudflare Pages `_redirects` for `.html`, extensionless, and
`.md` redirect variants, with channel-aware docs destinations.
- Add discovery hints for agents and crawlers: `rel="llms.txt"`,
`rel="alternate" type="text/markdown"`, and a short generated `llms.txt`
directive in copied Markdown pages.
- Update the docs proxy so `Accept: text/markdown`, `/docs.md`, and
direct `.md` requests can resolve to the generated Markdown artifacts.
- Move primary docs content earlier in the HTML source while preserving
the visible layout, so crawlers and agent scorers encounter the article
before sidebar chrome.
- Move the existing copy-as-Markdown control from the top navigation
into the page-title row, using the generated Markdown alternate link as
the source of truth.
- Split AI-discovery artifact generation out of
`docs_preprocessor/src/main.rs` into a focused module.

Best Practices Adopted

- Use `llms.txt` as a concise navigation index, not a dump of full page
content.
- Link to absolute, canonical Markdown URLs from `llms.txt`.
- Preserve the docs hierarchy in `llms.txt` instead of emitting a flat
sitemap-like list.
- Include short per-link descriptions from existing metadata rather than
inventing summaries.
- Keep `llms.txt`, Markdown copies, sitemap data, redirects, and
freshness metadata generated from the same mdBook source to avoid drift.
- Advertise Markdown alternates with standard HTML metadata and
same-origin URLs.
- Support both explicit Markdown URLs and content negotiation for
clients that prefer Markdown.
- Keep browser copy behavior pointed at generated Markdown alternate
links instead of duplicating route inference in JavaScript.
- Keep the copy-as-Markdown affordance in the page title row without
duplicating header chrome controls.

Validation

- `cargo check -p docs_preprocessor`
- `cargo test -p docs_preprocessor`
- `./script/clippy -p docs_preprocessor`
- `mdbook build ./docs --dest-dir=../target/deploy/docs/`
- `node --check docs/theme/plugins.js`
- `pnpm dlx prettier@3.5.0 docs/theme/plugins.js --check`
- `git diff --check`
- Local artifact checks confirmed generated Markdown pages, `llms.txt`,
`sitemap.xml` lastmod values, HTML freshness metadata, Markdown
alternate links, redirect targets, and preprocessed action/keybinding
tags resolve as expected.
- Worker URL rewrite mock covered `/docs/`, `/docs.md`,
`/docs/index.md`, extensionless docs routes, `.html` routes,
`/docs/llms.txt`, and `/docs/sitemap.xml`.
- High-effort adversarial subagent review found blockers around
channel-aware redirects, shallow-checkout date fallback, file size,
duplicated Markdown path inference, and process spawning. Those were
addressed.

Remaining Notes

- Local `python -m http.server` does not emulate Cloudflare Pages pretty
URLs, `_redirects`, or the docs-proxy Worker, so full local `afdocs`
still cannot prove content negotiation end to end.
- Existing production remains unchanged until this PR is deployed
through the docs workflow.
- Production baseline `npx afdocs check https://zed.dev/docs/ --fixes
--verbose` still reports the original failures before this PR is
deployed: 12 passed, 8 failed, 3 skipped.

Release Notes:

- Improved docs AI-readiness by adding machine-readable discovery,
Markdown access, and freshness metadata.

---------

Co-authored-by: Katie Geer <katie@zed.dev>
Co-authored-by: Ben Kunkle <ben@zed.dev>
2026-07-08 20:54:51 +00:00

384 lines
10 KiB
JavaScript

function detectOS() {
var userAgent = navigator.userAgent;
var platform = navigator.platform;
var macosPlatforms = ["Macintosh", "MacIntel", "MacPPC", "Mac68K"];
var windowsPlatforms = ["Win32", "Win64", "Windows", "WinCE"];
var iosPlatforms = ["iPhone", "iPad", "iPod"];
if (macosPlatforms.indexOf(platform) !== -1) {
return "Mac";
} else if (iosPlatforms.indexOf(platform) !== -1) {
return "iOS";
} else if (windowsPlatforms.indexOf(platform) !== -1) {
return "Windows";
} else if (/Android/.test(userAgent)) {
return "Android";
} else if (/Linux/.test(platform)) {
return "Linux";
}
return "Unknown";
}
var os = detectOS();
console.log("Operating System:", os);
// Defer keybinding processing to avoid blocking initial render
function updateKeybindings() {
const os = detectOS();
const isMac = os === "Mac" || os === "iOS";
function processKeybinding(element) {
const [macKeybinding, linuxKeybinding] = element.textContent.split("|");
element.textContent = isMac ? macKeybinding : linuxKeybinding;
element.classList.add("keybinding");
}
// Process all kbd elements at once (more efficient than walking entire DOM)
const kbdElements = document.querySelectorAll("kbd");
kbdElements.forEach(processKeybinding);
}
// Use requestIdleCallback if available, otherwise requestAnimationFrame
if (typeof requestIdleCallback === "function") {
requestIdleCallback(updateKeybindings);
} else {
requestAnimationFrame(updateKeybindings);
}
function darkModeToggle() {
var html = document.documentElement;
function setTheme(theme) {
html.setAttribute("data-theme", theme);
html.setAttribute("data-color-scheme", theme);
html.className = theme;
localStorage.setItem("mdbook-theme", theme);
}
// Set initial theme
var currentTheme = localStorage.getItem("mdbook-theme");
if (currentTheme) {
setTheme(currentTheme);
} else {
// If no theme is set, use the system's preference
var systemPreference = window.matchMedia("(prefers-color-scheme: dark)")
.matches
? "dark"
: "light";
setTheme(systemPreference);
}
// Listen for system's preference changes
const darkModeMediaQuery = window.matchMedia("(prefers-color-scheme: dark)");
darkModeMediaQuery.addEventListener("change", function (e) {
if (!localStorage.getItem("mdbook-theme")) {
setTheme(e.matches ? "dark" : "light");
}
});
}
const copyPageActions = () => {
const headerCopyMarkdownButton = document.getElementById(
"copy-markdown-toggle",
);
const actionButtons = new Map();
let isLoading = false;
const showToast = (message, isSuccess = true) => {
const existingToast = document.getElementById("copy-toast");
existingToast?.remove();
const toast = document.createElement("div");
toast.id = "copy-toast";
toast.className = `copy-toast ${isSuccess ? "success" : "error"}`;
toast.textContent = message;
document.body.appendChild(toast);
setTimeout(() => {
toast.classList.add("show");
}, 10);
setTimeout(() => {
toast.classList.remove("show");
setTimeout(() => {
toast.parentNode?.removeChild(toast);
}, 300);
}, 2000);
};
const registerButton = (button, originalIconClass) => {
if (!button) return;
actionButtons.set(button, {
originalIconClass,
iconTimeoutId: null,
});
};
registerButton(headerCopyMarkdownButton, "fa fa-copy");
const changeButtonIcon = (button, iconClass, duration = 1000) => {
const state = actionButtons.get(button);
if (!state) return;
const icon = button.querySelector("i");
if (!icon) return;
if (state.iconTimeoutId) {
clearTimeout(state.iconTimeoutId);
state.iconTimeoutId = null;
}
icon.className = iconClass;
if (duration > 0) {
state.iconTimeoutId = setTimeout(() => {
icon.className = state.originalIconClass;
state.iconTimeoutId = null;
}, duration);
}
};
const copyText = async (text) => {
if (!navigator.clipboard?.writeText) {
throw new Error("Clipboard API not supported in this browser");
}
await navigator.clipboard.writeText(text);
};
const getContentRoot = () =>
document.querySelector("#content main .content-wrap") ||
document.querySelector("#content > main");
const markdownAlternateHref = () =>
document
.querySelector('link[rel="alternate"][type="text/markdown"]')
?.getAttribute("href");
const insertPageActionButtons = () => {
const contentRoot = getContentRoot();
if (
!contentRoot ||
contentRoot.querySelector(".page-actions") ||
!headerCopyMarkdownButton ||
!markdownAlternateHref()
) {
return;
}
const firstHeading = contentRoot.querySelector("h1");
if (!firstHeading) return;
const header = document.createElement("div");
header.className = "page-header";
const actions = document.createElement("div");
actions.className = "page-actions";
firstHeading.insertAdjacentElement("beforebegin", header);
headerCopyMarkdownButton.classList.remove(
"icon-button",
"ib-hidden-mobile",
);
headerCopyMarkdownButton.classList.add("page-action", "page-action-icon");
actions.append(headerCopyMarkdownButton);
header.append(firstHeading, actions);
};
const markdownUrl = () => {
const alternateHref = markdownAlternateHref();
if (!alternateHref) return null;
const url = new URL(alternateHref, window.location.href);
if (
url.origin === window.location.origin &&
url.pathname.startsWith("/docs/") &&
!window.location.pathname.startsWith("/docs/")
) {
return url.pathname.replace(/^\/docs/, "") || "/";
}
if (url.origin === window.location.origin) {
return `${url.pathname}${url.search}${url.hash}`;
}
return url.pathname;
};
const fetchAndCopyMarkdown = async (button) => {
// Prevent multiple simultaneous requests
if (isLoading) return;
try {
isLoading = true;
changeButtonIcon(button, "fa fa-spinner fa-spin", 0); // Don't auto-restore spinner
const url = markdownUrl();
if (!url) {
throw new Error("Markdown alternate link not found");
}
const response = await fetch(url);
if (!response.ok) {
throw new Error(
`Failed to fetch markdown: ${response.status} ${response.statusText}`,
);
}
const markdownContent = await response.text();
await copyText(markdownContent);
changeButtonIcon(button, "fa fa-check", 1000);
showToast("Markdown copied to clipboard!");
} catch (error) {
console.error("Error copying markdown:", error);
changeButtonIcon(button, "fa fa-exclamation-triangle", 2000);
showToast("Failed to copy markdown. Please try again.", false);
} finally {
isLoading = false;
}
};
headerCopyMarkdownButton?.addEventListener("click", () =>
fetchAndCopyMarkdown(headerCopyMarkdownButton),
);
insertPageActionButtons();
};
const initializePlugins = () => {
darkModeToggle();
requestAnimationFrame(copyPageActions);
};
if (document.readyState === "loading") {
document.addEventListener("DOMContentLoaded", initializePlugins);
} else {
initializePlugins();
}
// Collapsible sidebar navigation for entire sections
// Note: Initial collapsed state is applied in index.hbs to prevent flicker
function initCollapsibleSidebar() {
var sidebar = document.getElementById("sidebar");
if (!sidebar) return;
var chapterList = sidebar.querySelector("ol.chapter");
if (!chapterList) return;
var partTitles = Array.from(chapterList.querySelectorAll("li.part-title"));
partTitles.forEach(function (partTitle) {
// Get all sibling elements that belong to this section
var sectionItems = getSectionItems(partTitle);
if (sectionItems.length > 0) {
setupCollapsibleSection(partTitle, sectionItems);
}
});
}
// Saves the list of collapsed section names to sessionStorage
// This gets reset when the tab is closed and opened again
function saveCollapsedSections() {
var collapsedSections = [];
var partTitles = document.querySelectorAll(
"#sidebar li.part-title.collapsible",
);
partTitles.forEach(function (partTitle) {
if (!partTitle.classList.contains("expanded")) {
collapsedSections.push(partTitle._sectionName);
}
});
try {
sessionStorage.setItem(
"sidebar-collapsed-sections",
JSON.stringify(collapsedSections),
);
} catch (e) {
// sessionStorage might not be available
}
}
function getSectionItems(partTitle) {
var items = [];
var sibling = partTitle.nextElementSibling;
while (sibling) {
// Stop when we hit another part-title
if (sibling.classList.contains("part-title")) {
break;
}
items.push(sibling);
sibling = sibling.nextElementSibling;
}
return items;
}
function setupCollapsibleSection(partTitle, sectionItems) {
partTitle.classList.add("collapsible");
partTitle.setAttribute("role", "button");
partTitle.setAttribute("tabindex", "0");
partTitle._sectionItems = sectionItems;
var isCurrentlyCollapsed = partTitle._isCollapsed;
if (isCurrentlyCollapsed) {
partTitle.setAttribute("aria-expanded", "false");
} else {
partTitle.classList.add("expanded");
partTitle.setAttribute("aria-expanded", "true");
}
partTitle.addEventListener("click", function (e) {
e.preventDefault();
toggleSection(partTitle);
});
// a11y: Add keyboard support (Enter and Space)
partTitle.addEventListener("keydown", function (e) {
if (e.key === "Enter" || e.key === " ") {
e.preventDefault();
toggleSection(partTitle);
}
});
}
function toggleSection(partTitle) {
var isExpanded = partTitle.classList.contains("expanded");
var sectionItems = partTitle._sectionItems;
var spacerAfter = partTitle._spacerAfter;
if (isExpanded) {
partTitle.classList.remove("expanded");
partTitle.setAttribute("aria-expanded", "false");
sectionItems.forEach(function (item) {
item.classList.add("section-hidden");
});
if (spacerAfter) {
spacerAfter.classList.add("section-hidden");
}
} else {
partTitle.classList.add("expanded");
partTitle.setAttribute("aria-expanded", "true");
sectionItems.forEach(function (item) {
item.classList.remove("section-hidden");
});
if (spacerAfter) {
spacerAfter.classList.remove("section-hidden");
}
}
saveCollapsedSections();
}
document.addEventListener("DOMContentLoaded", function () {
initCollapsibleSidebar();
});