@writedocs/generator 0.21.1 → 0.22.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/astro.config.mjs CHANGED
@@ -36,12 +36,15 @@ import { iconDataFromFile } from './src/lib/icon-data-dev.js';
36
36
  import { canonicalPath } from './src/lib/canonical-path.js';
37
37
  import { withBase, withoutBase } from './src/lib/base-path.js';
38
38
  import { folderAddresses } from './src/lib/folder-redirects.js';
39
+ import { pageTags, TAGS_PATH } from './src/lib/tags.js';
39
40
  import { report } from './packages/components/src/lib/cli-report.js';
40
41
  import { publishProjectFiles, generatedRobotsTxt } from './src/lib/project-files-integration.js';
41
42
  import { frontmatterNoindex, canonicalIsElsewhere } from './src/lib/seo-tags.js';
42
43
  import { readMovedApiPages } from './src/lib/moved-api-pages.js';
43
44
  import { rehypeImageLoading } from './src/lib/rehype-image-loading.js';
44
45
  import { rehypeBasePath } from './src/lib/rehype-base-path.js';
46
+ import { rehypeTaskLists } from './src/lib/rehype-task-lists.js';
47
+ import { rehypeTableScroll } from './src/lib/rehype-table-scroll.js';
45
48
  import { gitLastModified, newestDate } from './src/lib/last-modified.js';
46
49
  import { readSpecPaths } from './src/lib/project-files.js';
47
50
  import { protectedPages } from './src/lib/protected-sections.js';
@@ -171,6 +174,8 @@ function collectNoindexIds(rootContentDir) {
171
174
  // redirect-only route [...slug].astro synthesizes (noindex, pointing at
172
175
  // the first page) - which doesn't belong in the sitemap either.
173
176
  let rootIsPage = false;
177
+ // Whether a page has `tags` - see the folders below.
178
+ let hasTags = false;
174
179
  const pageIds = [];
175
180
  // When each page last changed, for <lastmod> - see lib/last-modified.js.
176
181
  const fileDates = gitLastModified(rootContentDir);
@@ -186,6 +191,7 @@ function collectNoindexIds(rootContentDir) {
186
191
  const { data } = matter(fs.readFileSync(file, 'utf-8'));
187
192
  const pageId = normalizeEntryId(data?.slug ?? relativeId.replace(/\.mdx?$/i, '').replace(/\/index$/, ''));
188
193
  if (pageId === 'index') rootIsPage = true;
194
+ if (pageTags(data?.tags).length > 0) hasTags = true;
189
195
  pageIds.push(pageId);
190
196
  const changed = fileDates?.get(relativeId.split(path.sep).join('/'));
191
197
  if (changed) lastModifiedById.set(pageId, changed);
@@ -218,7 +224,12 @@ function collectNoindexIds(rootContentDir) {
218
224
  if (!rootIsPage) ids.add('index');
219
225
  // Folder addresses with no page of their own redirect to one under them
220
226
  // (lib/folder-redirects.js) - redirects, so not in the sitemap either.
221
- for (const folder of folderAddresses(pageIds)) ids.add(folder);
227
+ // Except /tags/ on a site with tags, where it's the list of tags
228
+ // (lib/tags.js) - [...slug].astro makes no folder redirect there. Read
229
+ // from the frontmatter alone: a site whose only tagged pages are
230
+ // protected or hidden has no list of tags (lib/tag-index.ts), and its
231
+ // /tags/ redirect - if it has pages under tags/ - is then in the sitemap.
232
+ for (const folder of folderAddresses(pageIds)) if (!(hasTags && folder === TAGS_PATH)) ids.add(folder);
222
233
  return ids;
223
234
  }
224
235
 
@@ -528,10 +539,15 @@ export default defineConfig({
528
539
  // neither plugin's output is visible to the other.
529
540
  // rehypeImageLoading: lazy loading and sizes for content images - see
530
541
  // lib/rehype-image-loading.js.
542
+ // rehypeTaskLists: `- [ ] item` boxes a reader can tick - see
543
+ // lib/rehype-task-lists.js.
544
+ // rehypeTableScroll: every table in a scrolling wrapper, so a wide one
545
+ // scrolls sideways instead of spilling over the table of contents -
546
+ // see lib/rehype-table-scroll.js.
531
547
  // rehypeBasePath: the basePath in front of the content's own links and
532
548
  // pictures (lib/rehype-base-path.js) - last, since rehypeImageLoading
533
549
  // finds an image's file by the address as written.
534
- rehypePlugins: [rehypeMermaid, rehypeKatex, [rehypeImageLoading, { contentDir }], [rehypeBasePath, { base: basePath }]],
550
+ rehypePlugins: [rehypeMermaid, rehypeKatex, [rehypeImageLoading, { contentDir }], rehypeTaskLists, rehypeTableScroll, [rehypeBasePath, { base: basePath }]],
535
551
  }),
536
552
  shikiConfig: {
537
553
  themes: codeblockTheme,
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@writedocs/generator",
3
- "version": "0.21.1",
3
+ "version": "0.22.1",
4
4
  "description": "Static site generator for docs — a writedocs.json + MDX folder in, a static site out.",
5
5
  "type": "module",
6
6
  "bin": {
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@writedocs/components",
3
- "version": "0.1.0",
3
+ "version": "0.1.1",
4
4
  "description": "The writedocs documentation components (Callout, Card, Tabs, CodeBlock, ...) as Astro components, for any Astro project",
5
5
  "type": "module",
6
6
  "exports": {
@@ -5,13 +5,14 @@ import { extraClasses } from './class-names';
5
5
  // that live-filters rows by their own text content - "let users filter
6
6
  // the content inside the wrapper" per the request that spawned this.
7
7
  //
8
- // A markdown table always lands as a *direct* child of .wd-article
9
- // (see [...slug].astro's own comment on this at its `<style is:global>`
8
+ // A markdown table normally lands at the top level of .wd-article (in
9
+ // the writedocs generator, inside a .wd-table-wrap scroll box - see
10
+ // [...slug].astro's own comment on this at its `<style is:global>`
10
11
  // block), which is what its own global table CSS rule
11
- // (`.wd-article > table`) deliberately targets - once wrapped in this
12
- // component's own .wd-searchbar-content div, that table is no longer a
13
- // direct child of .wd-article, so that rule's ">" combinator stops
14
- // matching it. Rather than loosening that combinator sitewide (it's
12
+ // (`.wd-article > .wd-table-wrap > table`) deliberately targets - once
13
+ // wrapped in this component's own .wd-searchbar-content div, that table is
14
+ // no longer at the top level of .wd-article, so that rule's ">" combinators
15
+ // stop matching it. Rather than loosening that combinator sitewide (it's
15
16
  // intentionally direct-child-only - see its own comment for why), the
16
17
  // exact same declarations are duplicated here, scoped to
17
18
  // .wd-searchbar-content instead, so a wrapped table still renders
@@ -81,8 +82,9 @@ const { placeholder = "Search..." } = Astro.props as Props;
81
82
  outline: none;
82
83
  border-color: var(--wd-primary);
83
84
  }
84
- /* Matches .wd-article > table's own global styling exactly (see this
85
- file's own top comment for why it has to be duplicated here rather
85
+ /* Matches .wd-article > .wd-table-wrap > table's own global styling
86
+ exactly (see this file's own top comment for why it has to be
87
+ duplicated here rather
86
88
  than reused directly) - width/border-collapse/font-size on the
87
89
  table itself, cell padding/border/alignment on th and td, and the
88
90
  muted uppercase treatment on th. :global() throughout since slot
@@ -1,8 +1,18 @@
1
- // A string prop rendered with the small subset of inline Markdown Mintlify
2
- // allows in some component props (Tile's `title`, Prompt's `description`,
3
- // Color.Row's `title`): `code`, **bold**, and *italic* / _italic_. The
4
- // input is HTML-escaped first, so this is always safe to hand to set:html -
5
- // nothing in a prop value can produce markup other than these three.
1
+ // A string rendered with the small subset of inline Markdown Mintlify allows
2
+ // in some component props (Tile's `title`, Prompt's `description`,
3
+ // Color.Row's `title`) - and that writedocs allows in a page's frontmatter
4
+ // `title`: `code`, **bold**, and *italic* / _italic_. The input is
5
+ // HTML-escaped first, so this is always safe to hand to set:html - nothing
6
+ // in a value can produce markup other than these three.
7
+ //
8
+ // Emphasis follows CommonMark's flanking rule closely enough for titles: the
9
+ // marker has to touch the text it wraps - `*x*` is italic, `2 * 3 * 4` and
10
+ // `*args and **kwargs` stay as written - and `_` only counts at a word's
11
+ // edge, so `snake_case_name` and `__init__` stay too.
12
+ //
13
+ // inlineMarkdownText() is the same value as plain text - the markers gone,
14
+ // nothing escaped - for wherever no markup can go: a page's <title>, its
15
+ // sidebar entry, search results.
6
16
 
7
17
  function escapeHtml(value) {
8
18
  return value
@@ -13,6 +23,15 @@ function escapeHtml(value) {
13
23
  .replace(/'/g, '&#39;');
14
24
  }
15
25
 
26
+ function unescapeHtml(value) {
27
+ return value
28
+ .replace(/&lt;/g, '<')
29
+ .replace(/&gt;/g, '>')
30
+ .replace(/&quot;/g, '"')
31
+ .replace(/&#39;/g, "'")
32
+ .replace(/&amp;/g, '&');
33
+ }
34
+
16
35
  export function inlineMarkdown(value) {
17
36
  if (!value) return '';
18
37
  // Code spans first, and set aside, so ** or _ inside them stay literal.
@@ -22,8 +41,15 @@ export function inlineMarkdown(value) {
22
41
  return `\u0000${codeSpans.length - 1}\u0000`;
23
42
  });
24
43
  html = html
25
- .replace(/\*\*([^*]+)\*\*/g, '<strong>$1</strong>')
26
- .replace(/(^|[^\w*])\*([^*]+)\*(?!\w)/g, '$1<em>$2</em>')
27
- .replace(/(^|[^\w])_([^_]+)_(?!\w)/g, '$1<em>$2</em>');
44
+ .replace(/\*\*(?=[^\s*])([^*]*?[^\s*])\*\*/g, '<strong>$1</strong>')
45
+ .replace(/(^|[^\w*])\*(?=[^\s*])([^*]*?[^\s*])\*(?![\w*])/g, '$1<em>$2</em>')
46
+ .replace(/(^|[^\w])_(?=[^\s_])([^_]*?[^\s_])_(?!\w)/g, '$1<em>$2</em>');
28
47
  return html.replace(/\u0000(\d+)\u0000/g, (_, i) => codeSpans[Number(i)]);
29
48
  }
49
+
50
+ /** The same value as plain text: what inlineMarkdown() shows, without the
51
+ * markup. A value with no Markdown in it comes back as it is. */
52
+ export function inlineMarkdownText(value) {
53
+ if (!value) return '';
54
+ return unescapeHtml(inlineMarkdown(value).replace(/<\/?(?:code|strong|em)>/g, ''));
55
+ }
@@ -848,6 +848,7 @@ const fontExtraCss = [fontFaceCss, fontFallbackCss, fontWeightCss].filter(Boolea
848
848
  <script>
849
849
  import { initBanner } from "../scripts/banner";
850
850
  import { initTopbarOffset } from "../scripts/topbar-offset";
851
+ import { initTaskLists } from "../scripts/task-lists";
851
852
 
852
853
  initBanner(document);
853
854
  document.addEventListener("astro:page-load", () => initBanner(document));
@@ -857,6 +858,11 @@ const fontExtraCss = [fontFaceCss, fontFallbackCss, fontWeightCss].filter(Boolea
857
858
  // why that's live-measured rather than a fixed CSS value.
858
859
  initTopbarOffset();
859
860
  document.addEventListener("astro:page-load", () => initTopbarOffset());
861
+
862
+ // Remembers what a reader ticked in the page's task lists - see
863
+ // task-lists.ts. Again after a swap: the new page has its own boxes.
864
+ initTaskLists(document);
865
+ document.addEventListener("astro:page-load", () => initTaskLists(document));
860
866
  </script>
861
867
  {
862
868
  /* writedocs.json's `scripts.body` - see scriptEntrySchema in lib/config.ts.
@@ -297,3 +297,105 @@ pre {
297
297
  scrollbar-color: var(--wd-scrollbar-thumb-near) transparent;
298
298
  }
299
299
  }
300
+
301
+ /* Task lists - `- [ ] item` (lib/rehype-task-lists.js makes the boxes
302
+ tickable, scripts/task-lists.ts remembers them). In a bulleted list a task
303
+ item has no bullet: its box sits where the bullet was, so the text lines
304
+ up with the list's other items. A numbered list keeps its numbers, with
305
+ the box after. The label is the box and the item's text - clicking either
306
+ ticks it. */
307
+ .wd-article ul > li.task-list-item {
308
+ list-style: none;
309
+ }
310
+ .wd-article li.task-list-item input[type="checkbox"] {
311
+ width: 1rem;
312
+ height: 1rem;
313
+ /* A little room after a numbered list's number; a bulleted list's box
314
+ moves into the bullet's place (below). */
315
+ margin: 0 0.4rem 0 0.25rem;
316
+ vertical-align: -0.15em;
317
+ accent-color: var(--wd-primary);
318
+ cursor: pointer;
319
+ }
320
+ .wd-article ul > li.task-list-item > label > input[type="checkbox"],
321
+ .wd-article ul > li.task-list-item > p > label > input[type="checkbox"] {
322
+ margin-left: -1.4rem;
323
+ }
324
+ .wd-article label.wd-task {
325
+ cursor: pointer;
326
+ transition: color 0.15s ease;
327
+ }
328
+ /* A ticked item's text is muted - what's done steps back from what's left.
329
+ Bold and code in it follow (their own color is the heading's); a link
330
+ keeps its color, to still read as one. :has() works without the script,
331
+ for a tick a reader makes or one remembered (task-lists.ts). Dimmed
332
+ from the text's own color toward the page's, not --wd-text-muted: in dark
333
+ mode the body text already is that color. */
334
+ .wd-article label.wd-task:has(> input:checked) {
335
+ color: color-mix(in srgb, currentColor 55%, var(--wd-background));
336
+ }
337
+ .wd-article label.wd-task:has(> input:checked) :is(strong, b, em, code) {
338
+ color: inherit;
339
+ }
340
+
341
+ /* Page tags - frontmatter `tags` (lib/tags.js): the row under a page
342
+ ([...slug].astro) and the list of tags (src/pages/tags/[...tag].astro).
343
+ A tag with a page is a link; one without (lib/tag-index.ts) is the same
344
+ pill, not clickable. */
345
+ .wd-page-tags {
346
+ display: flex;
347
+ flex-wrap: wrap;
348
+ align-items: baseline;
349
+ gap: 0.5rem 0.75rem;
350
+ margin: 2.5rem 0 0;
351
+ }
352
+ .wd-page-tags-label {
353
+ font-size: 0.85rem;
354
+ font-weight: 600;
355
+ color: var(--wd-text-muted);
356
+ }
357
+ .wd-page-tags-list {
358
+ display: flex;
359
+ flex-wrap: wrap;
360
+ gap: 0.4rem;
361
+ margin: 0;
362
+ padding: 0;
363
+ list-style: none;
364
+ }
365
+ .wd-article .wd-page-tags-list > li {
366
+ margin: 0;
367
+ }
368
+ .wd-tag {
369
+ display: inline-flex;
370
+ align-items: center;
371
+ padding: 0.2rem 0.65rem;
372
+ border: 1px solid var(--wd-border);
373
+ border-radius: 999px;
374
+ font-size: 0.82rem;
375
+ line-height: 1.4;
376
+ color: var(--wd-text);
377
+ text-decoration: none;
378
+ background: var(--wd-surface);
379
+ }
380
+ a.wd-tag {
381
+ transition: border-color 0.15s ease, color 0.15s ease;
382
+ }
383
+ /* Not the underline of a link in an article's list ([...slug].astro's
384
+ `.wd-article li a`). */
385
+ .wd-article a.wd-tag {
386
+ text-decoration: none;
387
+ }
388
+ a.wd-tag:hover,
389
+ a.wd-tag:focus-visible {
390
+ border-color: var(--wd-primary);
391
+ color: var(--wd-primary);
392
+ }
393
+
394
+ /* `code` in a page's title (frontmatter `title`'s inline Markdown -
395
+ [...slug].astro): a little smaller than the heading's letters, and a title
396
+ that wraps gives each line its own complete box. */
397
+ .wd-article-header h1 code {
398
+ font-size: 0.88em;
399
+ -webkit-box-decoration-break: clone;
400
+ box-decoration-break: clone;
401
+ }
@@ -3,6 +3,7 @@ import { findNodeAtLocation, parseTree, visit } from "jsonc-parser";
3
3
  import { BASE_PATH_FIELD_PATTERN } from "./base-path.js";
4
4
  import { stripBom } from "./bom.js";
5
5
  import { scalarGroups, scalarPathPrefix, scalarRootPathMessage } from "./scalar-path.js";
6
+ import { inlineMarkdownText } from "../../packages/components/src/lib/inline-markdown.js";
6
7
  const navPageSchema = z.string();
7
8
  const navGroupPagesSchema = z.lazy(
8
9
  () => z.object({
@@ -438,6 +439,17 @@ function mergeSeo(site, page = {}) {
438
439
  };
439
440
  }
440
441
  const MINTLIFY_MODE_ALIASES = { center: "frame", assistant: "default" };
442
+ function withPlainTitles(data) {
443
+ const title = inlineMarkdownText(data.title);
444
+ const sidebarTitle = data.sidebarTitle === void 0 ? void 0 : inlineMarkdownText(data.sidebarTitle);
445
+ if (title === data.title && sidebarTitle === data.sidebarTitle) return data;
446
+ return {
447
+ ...data,
448
+ title,
449
+ ...sidebarTitle === void 0 ? {} : { sidebarTitle },
450
+ ...title === data.title ? {} : { titleMarkdown: data.title }
451
+ };
452
+ }
441
453
  const pageFrontmatterSchema = z.object({
442
454
  title: z.string(),
443
455
  description: z.string().optional(),
@@ -547,6 +559,12 @@ const pageFrontmatterSchema = z.object({
547
559
  url: z.string().optional(),
548
560
  hideFooterPagination: z.boolean().optional(),
549
561
  hideApiMarker: z.boolean().optional(),
562
+ // Docusaurus' page tags: shown at the bottom of the page, each linking to
563
+ // a page listing every page with it (`/tags/<tag>/`; `/tags/` lists them
564
+ // all). A tag is a name, or Docusaurus' `{ label, permalink }` - the
565
+ // permalink sets its address. Not `tag` above, Mintlify's sidebar label.
566
+ // See lib/tags.js and lib/tag-index.ts.
567
+ tags: z.array(z.union([z.string(), z.object({ label: z.string(), permalink: z.string().optional() })])).optional(),
550
568
  // Docusaurus' key: a draft isn't part of the site `writedocs build`
551
569
  // makes - no route, no navigation entry, not in search, the sitemap,
552
570
  // llms.txt or the MCP index (lib/drafts.js). `writedocs dev` and
@@ -581,7 +599,7 @@ const pageFrontmatterSchema = z.object({
581
599
  seo.robots = "noindex, nofollow";
582
600
  changed = true;
583
601
  }
584
- return changed ? { ...data, seo } : data;
602
+ return withPlainTitles(changed ? { ...data, seo } : data);
585
603
  }
586
604
  );
587
605
  const apiSchema = z.object({
@@ -42,6 +42,9 @@ import { stripBom } from './bom.js';
42
42
  // Where a "scalar" OpenAPI group's reference may go, worded as the build
43
43
  // words it - lib/scalar-path.js. Plain JS with no `node:` import too.
44
44
  import { scalarGroups, scalarPathPrefix, scalarRootPathMessage } from './scalar-path.js';
45
+ // A page title's inline Markdown, as plain text - the components package's
46
+ // lib/inline-markdown.js. Plain JS with no import at all.
47
+ import { inlineMarkdownText } from '../../packages/components/src/lib/inline-markdown.js';
45
48
 
46
49
  // ---------------------------------------------------------------------
47
50
  // Pages & groups - the leaf content any container ultimately bottoms out
@@ -829,6 +832,26 @@ export function mergeSeo(site: SeoFields, page: SeoFields = {}): SeoFields {
829
832
 
830
833
  const MINTLIFY_MODE_ALIASES: Record<string, string> = { center: 'frame', assistant: 'default' };
831
834
 
835
+ /** A page's `title` may have inline Markdown - `code`, **bold**, *italic*
836
+ * (lib/inline-markdown.js in the components package). Only the page's <h1>
837
+ * shows it ([...slug].astro, from `titleMarkdown`); everywhere else - the
838
+ * sidebar, <title>, search, breadcrumbs, prev/next, link previews,
839
+ * llms.txt, the tag pages - reads `title`, which is made plain text here,
840
+ * once, so none of them has to. `sidebarTitle` is only ever shown plain,
841
+ * so it's made plain text too. `titleMarkdown` is only there when the
842
+ * title has Markdown in it. */
843
+ function withPlainTitles<T extends { title: string; sidebarTitle?: string }>(data: T): T & { titleMarkdown?: string } {
844
+ const title = inlineMarkdownText(data.title);
845
+ const sidebarTitle = data.sidebarTitle === undefined ? undefined : inlineMarkdownText(data.sidebarTitle);
846
+ if (title === data.title && sidebarTitle === data.sidebarTitle) return data;
847
+ return {
848
+ ...data,
849
+ title,
850
+ ...(sidebarTitle === undefined ? {} : { sidebarTitle }),
851
+ ...(title === data.title ? {} : { titleMarkdown: data.title }),
852
+ };
853
+ }
854
+
832
855
  /** A page's own frontmatter - the `pages` and `generatedDocs` content
833
856
  * collections' schema (content.config.ts), and what `writedocs validate`
834
857
  * checks every page against. */
@@ -943,6 +966,14 @@ export const pageFrontmatterSchema = z.object({
943
966
  url: z.string().optional(),
944
967
  hideFooterPagination: z.boolean().optional(),
945
968
  hideApiMarker: z.boolean().optional(),
969
+ // Docusaurus' page tags: shown at the bottom of the page, each linking to
970
+ // a page listing every page with it (`/tags/<tag>/`; `/tags/` lists them
971
+ // all). A tag is a name, or Docusaurus' `{ label, permalink }` - the
972
+ // permalink sets its address. Not `tag` above, Mintlify's sidebar label.
973
+ // See lib/tags.js and lib/tag-index.ts.
974
+ tags: z
975
+ .array(z.union([z.string(), z.object({ label: z.string(), permalink: z.string().optional() })]))
976
+ .optional(),
946
977
  // Docusaurus' key: a draft isn't part of the site `writedocs build`
947
978
  // makes - no route, no navigation entry, not in search, the sitemap,
948
979
  // llms.txt or the MCP index (lib/drafts.js). `writedocs dev` and
@@ -986,7 +1017,7 @@ export const pageFrontmatterSchema = z.object({
986
1017
  seo.robots = 'noindex, nofollow';
987
1018
  changed = true;
988
1019
  }
989
- return changed ? { ...data, seo } : data;
1020
+ return withPlainTitles(changed ? { ...data, seo } : data);
990
1021
  },
991
1022
  );
992
1023
 
@@ -44,6 +44,7 @@ import { isPublishedFile, readSpecPaths } from './project-files.js';
44
44
  import { projectIgnore } from './project-ignore.js';
45
45
  import { readMovedApiPages } from './moved-api-pages.js';
46
46
  import { consentOptions, CONSENT_SETTINGS_ANCHOR } from './consent.js';
47
+ import { pageTags, tagHref } from './tags.js';
47
48
 
48
49
  // The same github-slugger Astro builds page URLs and heading ids with -
49
50
  // resolved through Astro itself, so the two can't drift apart.
@@ -321,7 +322,14 @@ export async function checkLinks(contentDir, configText) {
321
322
  // With the consent banner on, #cookie-settings opens it from any page.
322
323
  const pageWideAnchors = new Set(consentOptions(config.integrations?.consent) ? [CONSENT_SETTINGS_ANCHOR] : []);
323
324
  if (config.domain) ['/sitemap.xml', '/sitemap-index.xml'].forEach((p) => special.add(p));
324
- const knownUrls = [...pages.keys(), ...generated, ...redirects];
325
+ // The tag pages (lib/tags.js): `/tags/` and one per tag a page has. Every
326
+ // tag counts, though one only on pages behind sign-in or in hidden
327
+ // sections gets no page (lib/tag-index.ts) - this doesn't read the
328
+ // navigation that closely, and a link to it is left alone.
329
+ const tagUrls = new Set();
330
+ for (const page of pages.values()) for (const tag of pageTags(page.scan?.data?.tags)) tagUrls.add(tagHref(tag.slug));
331
+ if (tagUrls.size > 0) tagUrls.add(tagHref());
332
+ const knownUrls = [...pages.keys(), ...generated, ...redirects, ...tagUrls];
325
333
  // Folder addresses with no page of their own redirect to one under them
326
334
  // (lib/folder-redirects.js), so a link to one isn't broken.
327
335
  const folders = new Set(
@@ -430,7 +438,7 @@ export async function checkLinks(contentDir, configText) {
430
438
  return;
431
439
  }
432
440
  // "/" always exists: the home page, or a redirect to the first page.
433
- if (pageKey === '/' || generated.has(pageKey) || redirects.has(pageKey) || folders.has(pageKey) || special.has(pageKey.replace(/\/$/, '') || '/')) return;
441
+ if (pageKey === '/' || generated.has(pageKey) || redirects.has(pageKey) || folders.has(pageKey) || tagUrls.has(pageKey) || special.has(pageKey.replace(/\/$/, '') || '/')) return;
434
442
  if (special.has(pathname)) return;
435
443
  if (drafts.has(pageKey)) {
436
444
  report(`${value} - ${pageKey} is a draft (draft: true in ${drafts.get(pageKey)}), so it isn't published.`);
@@ -0,0 +1,35 @@
1
+ // Wide tables scroll sideways inside their own box.
2
+ //
3
+ // A <table> can't scroll by itself without losing its table layout (with
4
+ // `display: block` it stops filling the column), and left alone a table wider
5
+ // than the article spills out over the table of contents beside it. So every
6
+ // table in a page is wrapped in `<div class="wd-table-wrap">`, which has
7
+ // `overflow-x: auto` ([...slug].astro's global styles): a table that fits
8
+ // still fills the column, one that doesn't scrolls inside the wrapper.
9
+ //
10
+ // Both kinds of table are wrapped: a Markdown one (a hast `table` element) and
11
+ // one written as JSX in an .mdx page (`<table>` - an `mdxJsxFlowElement`).
12
+ // A table already directly inside a wrapper isn't wrapped again.
13
+
14
+ export const TABLE_WRAP_CLASS = 'wd-table-wrap';
15
+
16
+ const isTable = (node) =>
17
+ (node?.type === 'element' && node.tagName === 'table') ||
18
+ (node?.type === 'mdxJsxFlowElement' && node.name === 'table');
19
+
20
+ const isWrap = (node) =>
21
+ node?.type === 'element' && node.tagName === 'div' && [].concat(node.properties?.className ?? []).includes(TABLE_WRAP_CLASS);
22
+
23
+ export function rehypeTableScroll() {
24
+ return (tree) => {
25
+ const visit = (node) => {
26
+ if (!Array.isArray(node.children)) return;
27
+ node.children = node.children.map((child) => {
28
+ visit(child);
29
+ if (!isTable(child) || isWrap(node)) return child;
30
+ return { type: 'element', tagName: 'div', properties: { className: [TABLE_WRAP_CLASS] }, children: [child] };
31
+ });
32
+ };
33
+ visit(tree);
34
+ };
35
+ }
@@ -0,0 +1,62 @@
1
+ // Task lists - `- [ ] item` / `- [x] item` - as checklists a reader can tick.
2
+ //
3
+ // GFM turns each such item into `<li class="task-list-item">` holding a
4
+ // disabled `<input type="checkbox">` and the item's text. This plugin:
5
+ //
6
+ // - drops `disabled`, so the box can be ticked;
7
+ // - wraps the box and the item's own text (up to its first block - a nested
8
+ // list, a second paragraph) in `<label class="wd-task">`, so clicking the
9
+ // text ticks it too (the box alone is a small target on a phone) and the
10
+ // box gets the text as its accessible name. In a loose list (blank lines
11
+ // between items) the box is inside the item's first <p>, and the label
12
+ // goes inside that <p>.
13
+ //
14
+ // What a reader ticks is remembered per page in their browser - that's
15
+ // src/scripts/task-lists.ts, which finds these boxes by
16
+ // `li.task-list-item input[type="checkbox"]`. The bullet is hidden in base.css.
17
+ //
18
+ // Only Markdown task items are touched: a list written as HTML/JSX in an .mdx
19
+ // page (`<li className="task-list-item">`) is the author's own markup.
20
+
21
+ const BLOCK_TAGS = new Set([
22
+ 'ul', 'ol', 'p', 'div', 'pre', 'table', 'blockquote', 'figure', 'hr',
23
+ 'h1', 'h2', 'h3', 'h4', 'h5', 'h6', 'details', 'dl', 'section',
24
+ ]);
25
+
26
+ const isElement = (node, tag) => node?.type === 'element' && (!tag || node.tagName === tag);
27
+
28
+ const isTaskItem = (node) => isElement(node, 'li') && [].concat(node.properties?.className ?? []).includes('task-list-item');
29
+
30
+ const isCheckbox = (node) => isElement(node, 'input') && node.properties?.type === 'checkbox';
31
+
32
+ const isBlock = (node) => (isElement(node) && BLOCK_TAGS.has(node.tagName)) || node.type === 'mdxJsxFlowElement';
33
+
34
+ const isBlank = (node) => node.type === 'text' && !node.value.trim();
35
+
36
+ function makeTickable(li) {
37
+ // The box is the item's first thing - or, in a loose list, its first <p>'s.
38
+ const first = li.children.find((child) => !isBlank(child));
39
+ const container = isElement(first, 'p') ? first : li;
40
+ const start = container.children.findIndex((child) => !isBlank(child));
41
+ if (start === -1 || !isCheckbox(container.children[start])) return;
42
+
43
+ let end = start + 1;
44
+ while (end < container.children.length && !isBlock(container.children[end])) end++;
45
+ // The line break before a nested list stays outside the label.
46
+ while (end > start + 1 && isBlank(container.children[end - 1])) end--;
47
+
48
+ const box = container.children[start];
49
+ delete box.properties.disabled;
50
+ const label = { type: 'element', tagName: 'label', properties: { className: ['wd-task'] }, children: container.children.slice(start, end) };
51
+ container.children.splice(start, end - start, label);
52
+ }
53
+
54
+ export function rehypeTaskLists() {
55
+ return (tree) => {
56
+ const visit = (node) => {
57
+ if (isTaskItem(node)) makeTickable(node);
58
+ if (Array.isArray(node.children)) node.children.forEach(visit);
59
+ };
60
+ visit(tree);
61
+ };
62
+ }
@@ -0,0 +1,203 @@
1
+ // The site's tags (frontmatter `tags` - see lib/tags.js): which pages each
2
+ // tag page lists, which tag pages are made, and the topbar they show. Used by
3
+ // src/pages/tags/[...tag].astro (the tag pages) and src/pages/[...slug].astro
4
+ // (the tags under a page, and the folder redirects, which keep off the tag
5
+ // pages' addresses). Once per build (oncePerBuild()).
6
+ //
7
+ // A tag page is public and lists only what anyone can find in the
8
+ // navigation's public part - a page is left out when it's:
9
+ // - behind sign-in (`access` - lib/protected-sections.js);
10
+ // - only in hidden sections (lib/hidden-sections.js) - "nothing lists one";
11
+ // - `hidden` (out of the sidebar), a `url` page (a link to another site), or
12
+ // a Scalar group's operation page (lib/scalar-reference.js).
13
+ // Its tags still show on the page itself, linked when the tag has a page
14
+ // (other pages have the tag), plain when it hasn't.
15
+ //
16
+ // A page that isn't in the navigation at all is listed: it's a page of the
17
+ // site like any other, just without a sidebar. A draft is only there when
18
+ // drafts are built (`writedocs dev`, `build --drafts`) - lib/drafts.js.
19
+ import { getCollection, type CollectionEntry } from "astro:content";
20
+ import fs from "node:fs";
21
+ import path from "node:path";
22
+ import {
23
+ loadDocsConfig,
24
+ resolveSections,
25
+ resolveLandings,
26
+ resolveGlobalDropdowns,
27
+ buildSelectors,
28
+ buildGlobalDropdowns,
29
+ flattenNav,
30
+ fileIdForEntry,
31
+ normalizeEntryId,
32
+ findAllPages,
33
+ type Selector,
34
+ type GlobalDropdownView,
35
+ } from "./config";
36
+ import { writedocsTempDir } from "./writedocs-temp-dir.js";
37
+ import { protectedPages } from "./protected-sections.js";
38
+ import { spaceOf } from "./hidden-sections.js";
39
+ import { itemLabel } from "./item-pages.js";
40
+ import { readScalarReferences, scalarOperationTargets } from "./scalar-reference.js";
41
+ import { oncePerBuild } from "./build-memo.js";
42
+ import { pageTags, collectTags, tagRoutes, TAGS_PATH } from "./tags.js";
43
+
44
+ type DocsEntry = CollectionEntry<"pages"> | CollectionEntry<"generatedDocs">;
45
+
46
+ export interface TaggedPage {
47
+ title: string;
48
+ description?: string;
49
+ href: string;
50
+ // The page's tab/version/language/... names, when the site has more than
51
+ // one section - so two pages with the same title (a page in two versions)
52
+ // can be told apart. Empty otherwise.
53
+ where: string[];
54
+ tags: { label: string; slug: string }[];
55
+ }
56
+ export interface Tag {
57
+ slug: string;
58
+ label: string;
59
+ pages: TaggedPage[];
60
+ }
61
+ export interface TagIndex {
62
+ // Every tag of a listed page, in name order.
63
+ tags: Tag[];
64
+ // The tags that get a page (`/tags/<slug>/`), and whether `/tags/` is made.
65
+ routed: Tag[];
66
+ index: boolean;
67
+ // Addresses a tag page would have had, kept by a page or redirect there.
68
+ skipped: string[];
69
+ // The slugs of `routed` - a page's tag links only to one of these.
70
+ linked: Set<string>;
71
+ // Every tag page's address, without slashes - the folder redirects keep
72
+ // off them ([...slug].astro).
73
+ addresses: Set<string>;
74
+ }
75
+
76
+ async function docsEntries(contentDir: string): Promise<DocsEntry[]> {
77
+ const hasGeneratedDocs = fs.existsSync(path.join(writedocsTempDir(contentDir), "generated-docs"));
78
+ const hasPages = findAllPages(contentDir).length > 0;
79
+ const [pages, generated] = await Promise.all([
80
+ hasPages ? getCollection("pages") : Promise.resolve([]),
81
+ hasGeneratedDocs ? getCollection("generatedDocs") : Promise.resolve([]),
82
+ ]);
83
+ return [...pages, ...generated];
84
+ }
85
+
86
+ const hrefOf = (entry: DocsEntry) => {
87
+ const id = normalizeEntryId(entry.id);
88
+ return id === "index" ? "/" : `/${id}/`;
89
+ };
90
+
91
+ async function computeTagIndex(): Promise<TagIndex> {
92
+ const contentDir = process.env.WRITEDOCS_CONTENT_DIR || process.cwd();
93
+ const packageRoot = process.env.WRITEDOCS_PACKAGE_ROOT || process.cwd();
94
+ const config = loadDocsConfig(contentDir);
95
+ const entries = await docsEntries(contentDir);
96
+ const sections = resolveSections(config.navigation);
97
+ const landings = resolveLandings(config.navigation);
98
+ const protectedRules = protectedPages(config.navigation);
99
+ const scalarTargets = scalarOperationTargets(readScalarReferences(contentDir));
100
+
101
+ // Where each page is in the navigation: the paths of the sections whose
102
+ // sidebar lists it and of the items it's the own page of.
103
+ const pathsOf = new Map<string, (typeof sections)[number]["path"][]>();
104
+ const addPath = (fileId: string, p: (typeof sections)[number]["path"]) => {
105
+ if (!pathsOf.has(fileId)) pathsOf.set(fileId, []);
106
+ pathsOf.get(fileId)!.push(p);
107
+ };
108
+ for (const section of sections) for (const { slug } of flattenNav(section.pages)) addPath(slug, section.path);
109
+ for (const landing of landings) addPath(landing.slug, landing.path);
110
+ const manySections = sections.length > 1;
111
+
112
+ const pages: TaggedPage[] = [];
113
+ for (const entry of entries) {
114
+ const tags = pageTags((entry.data as { tags?: unknown }).tags);
115
+ if (tags.length === 0) continue;
116
+ const fileId = fileIdForEntry(contentDir, packageRoot, entry);
117
+ const data = entry.data;
118
+ if (data.hidden || data.url || scalarTargets.has(fileId) || protectedRules.has(fileId)) continue;
119
+ const paths = pathsOf.get(fileId);
120
+ // In the navigation: only where a public (not hidden) section has it.
121
+ const publicPath = paths ? paths.find((p) => spaceOf(p) === null) : [];
122
+ if (!publicPath) continue;
123
+ pages.push({
124
+ title: data.title,
125
+ description: data.description,
126
+ href: hrefOf(entry),
127
+ where: manySections ? publicPath.map((segment) => itemLabel(segment.items[segment.index])) : [],
128
+ tags,
129
+ });
130
+ }
131
+
132
+ const tags = collectTags(pages) as Tag[];
133
+ // What's already at an address: every page (listed or not) and every
134
+ // redirect of writedocs.json.
135
+ const taken = new Set<string>([
136
+ ...entries.map((entry) => normalizeEntryId(entry.id)),
137
+ ...(config.redirects ?? []).map((r) => r.source.replace(/^\/+|\/+$/g, "")),
138
+ ]);
139
+ const routes = tagRoutes(tags, taken);
140
+ return {
141
+ tags,
142
+ routed: routes.tags,
143
+ index: routes.index,
144
+ skipped: routes.skipped,
145
+ linked: new Set(routes.tags.map((tag: Tag) => tag.slug)),
146
+ addresses: new Set([
147
+ ...(routes.index ? [TAGS_PATH] : []),
148
+ ...routes.tags.map((tag: Tag) => `${TAGS_PATH}/${tag.slug}`),
149
+ ]),
150
+ };
151
+ }
152
+
153
+ /** The site's tags - once per build. */
154
+ export function tagIndex(): Promise<TagIndex> {
155
+ return oncePerBuild("tags:index", computeTagIndex);
156
+ }
157
+
158
+ const SWITCHER_PLACEHOLDER: Record<Selector["kind"], string> = {
159
+ tab: "Tabs",
160
+ version: "Version",
161
+ language: "Language",
162
+ dropdown: "Menu",
163
+ product: "Products",
164
+ };
165
+
166
+ /** The topbar of a tag page: the navigation's first level (the tabs, say)
167
+ * with none chosen - a tag page belongs to none of them - and the global
168
+ * dropdowns. */
169
+ export async function tagPageChrome(): Promise<{ selectors: Selector[]; globalDropdowns: GlobalDropdownView[] }> {
170
+ const contentDir = process.env.WRITEDOCS_CONTENT_DIR || process.cwd();
171
+ const packageRoot = process.env.WRITEDOCS_PACKAGE_ROOT || process.cwd();
172
+ const config = loadDocsConfig(contentDir);
173
+ const entries = await docsEntries(contentDir);
174
+ const entryByFileId = new Map(entries.map((e) => [fileIdForEntry(contentDir, packageRoot, e), e]));
175
+ const hrefForSlug = (slug: string) => {
176
+ const entry = entryByFileId.get(slug);
177
+ const id = normalizeEntryId(entry?.id ?? slug);
178
+ return id === "index" ? "/" : `/${id}/`;
179
+ };
180
+ const titleForSlug = (slug: string) => {
181
+ const data = entryByFileId.get(slug)?.data;
182
+ return data?.sidebarTitle ?? data?.title ?? slug;
183
+ };
184
+ const first = resolveSections(config.navigation)[0];
185
+ const selectors = first?.path.length
186
+ ? buildSelectors(first.path.slice(0, 1), hrefForSlug).map((selector) => ({
187
+ ...selector,
188
+ hidden: false,
189
+ // What a switcher (versions, languages, products) shows with nothing
190
+ // chosen - tabs show none.
191
+ placeholder: { label: SWITCHER_PLACEHOLDER[selector.kind] },
192
+ options: selector.options.map((option) => ({ ...option, active: false })),
193
+ }))
194
+ : [];
195
+ const globalDropdowns = buildGlobalDropdowns(
196
+ resolveGlobalDropdowns(config.navigation),
197
+ "",
198
+ titleForSlug,
199
+ hrefForSlug,
200
+ (slug) => entryByFileId.get(slug)?.data,
201
+ );
202
+ return { selectors, globalDropdowns };
203
+ }
@@ -0,0 +1,103 @@
1
+ // Page tags - `tags: ["billing", "webhooks"]` in a page's frontmatter, as in
2
+ // Docusaurus. A page shows its tags at the bottom, each linking to the tag's
3
+ // own page (`/tags/<tag>/`), which lists every page with that tag; `/tags/`
4
+ // lists every tag.
5
+ //
6
+ // This file is the plain part - what a tag is called and where it lives, and
7
+ // the lists the tag pages show - so scripts/tags.test.js can check it. Which
8
+ // pages a tag page may list is decided from the navigation in
9
+ // lib/tag-index.ts; the pages themselves are src/pages/tags/[...tag].astro,
10
+ // and the tags under a page are in src/pages/[...slug].astro.
11
+ //
12
+ // - A tag is a string, or Docusaurus' `{ label, permalink }` object. Its
13
+ // address comes from its name - lower case, accents dropped, anything
14
+ // that isn't a letter or digit a single "-" ("Pão de queijo" ->
15
+ // "pao-de-queijo") - or from `permalink` when it has one.
16
+ // - Two spellings with the same address ("Queijo", "queijo") are one tag,
17
+ // shown with the spelling met first.
18
+ // - A tag page is only made where nothing else is: a page, a redirect, or
19
+ // another tag page already at that address keeps it, and the tag is left
20
+ // without a page (its name is still shown on its pages, not linked).
21
+
22
+ /** The folder the tag pages are in: `/tags/`, `/tags/<tag>/`. */
23
+ export const TAGS_PATH = 'tags';
24
+
25
+ /** A tag's address from its name or permalink - "" when nothing is left. */
26
+ export function tagSlug(text) {
27
+ return String(text ?? '')
28
+ .normalize('NFKD')
29
+ .replace(/\p{M}+/gu, '')
30
+ .toLowerCase()
31
+ .replace(/[^\p{L}\p{N}]+/gu, '-')
32
+ .replace(/^-+|-+$/g, '');
33
+ }
34
+
35
+ /** A page's `tags` frontmatter as `{ label, slug }`s, in its order: strings
36
+ * and `{ label, permalink }` objects; empty ones and repeats (by address)
37
+ * left out. Anything that isn't a list is no tags. */
38
+ export function pageTags(value) {
39
+ if (!Array.isArray(value)) return [];
40
+ const seen = new Set();
41
+ const tags = [];
42
+ for (const item of value) {
43
+ let label;
44
+ let slug;
45
+ if (typeof item === 'string') {
46
+ label = item.trim();
47
+ slug = tagSlug(label);
48
+ } else if (item && typeof item === 'object' && typeof item.label === 'string') {
49
+ label = item.label.trim();
50
+ slug = tagSlug(typeof item.permalink === 'string' && item.permalink.trim() ? item.permalink : label);
51
+ } else {
52
+ continue;
53
+ }
54
+ if (!label || !slug || seen.has(slug)) continue;
55
+ seen.add(slug);
56
+ tags.push({ label, slug });
57
+ }
58
+ return tags;
59
+ }
60
+
61
+ /** The address of a tag's page, or of the list of tags (no slug) - without
62
+ * slashes, the way routes are written. */
63
+ export const tagAddress = (slug) => (slug ? `${TAGS_PATH}/${slug}` : TAGS_PATH);
64
+
65
+ /** The link to a tag's page, or to the list of tags (no slug). */
66
+ export const tagHref = (slug) => `/${tagAddress(slug)}/`;
67
+
68
+ const collator = new Intl.Collator(undefined, { sensitivity: 'base', numeric: true });
69
+
70
+ /** Every tag of the listed pages, with its pages: `[{ slug, label, pages }]`,
71
+ * tags in name order, each tag's pages in title order. `pages` are
72
+ * `{ tags, ...anything }` - `tags` from pageTags(); the rest (title, href,
73
+ * description, where) is passed through for the tag page to show. */
74
+ export function collectTags(pages) {
75
+ const bySlug = new Map();
76
+ for (const page of pages) {
77
+ for (const { label, slug } of page.tags ?? []) {
78
+ if (!bySlug.has(slug)) bySlug.set(slug, { slug, label, pages: [] });
79
+ bySlug.get(slug).pages.push(page);
80
+ }
81
+ }
82
+ const tags = [...bySlug.values()];
83
+ for (const tag of tags) tag.pages.sort((a, b) => collator.compare(a.title ?? '', b.title ?? ''));
84
+ return tags.sort((a, b) => collator.compare(a.label, b.label) || collator.compare(a.slug, b.slug));
85
+ }
86
+
87
+ /** Which tag pages are made, given the addresses already taken (pages,
88
+ * redirects - without slashes, "index" for "/"): `{ index, tags, skipped }`
89
+ * - `index` is whether `/tags/` is made, `tags` the tags that get a page,
90
+ * `skipped` the addresses left to what's there. No tags, no pages at all. */
91
+ export function tagRoutes(tags, taken) {
92
+ if (tags.length === 0) return { index: false, tags: [], skipped: [] };
93
+ const skipped = [];
94
+ const index = !taken.has(TAGS_PATH);
95
+ if (!index) skipped.push(TAGS_PATH);
96
+ const made = [];
97
+ for (const tag of tags) {
98
+ const address = tagAddress(tag.slug);
99
+ if (taken.has(address)) skipped.push(address);
100
+ else made.push(tag);
101
+ }
102
+ return { index, tags: made, skipped };
103
+ }
@@ -0,0 +1,78 @@
1
+ // What src/scripts/task-lists.ts remembers about a page's task lists, and
2
+ // under which name. Plain JavaScript, so scripts/task-lists.test.js can check
3
+ // it. (The boxes themselves are made tickable at build time -
4
+ // lib/rehype-task-lists.js.)
5
+ //
6
+ // One localStorage entry per page: `wd-tasks:<path>`, holding
7
+ // `{ "<item key>": true|false }`.
8
+ //
9
+ // - An item's key is its text, whitespace collapsed - not its position - so
10
+ // adding, removing or moving another item doesn't move what a reader
11
+ // ticked onto a different line. Two items with the same text on one page
12
+ // are told apart by order: the second is "<text>\n2" (a newline can't be
13
+ // in a collapsed text, so it can't clash with another item's own text).
14
+ // - Only the items whose state differs from the page's own (`[ ]` / `[x]`)
15
+ // are stored. A page the reader has put back as written has no entry at
16
+ // all, and an item whose text was edited or removed is dropped from the
17
+ // entry on the next tick.
18
+
19
+ const PREFIX = 'wd-tasks:';
20
+
21
+ /** The text an item is known by: whitespace collapsed and trimmed. */
22
+ export const taskText = (text) => String(text ?? '').replace(/\s+/g, ' ').trim();
23
+
24
+ /** One key per item, in page order, from the items' texts. */
25
+ export function taskKeys(texts) {
26
+ const seen = new Map();
27
+ return texts.map((text) => {
28
+ const key = taskText(text);
29
+ const count = (seen.get(key) ?? 0) + 1;
30
+ seen.set(key, count);
31
+ return count === 1 ? key : `${key}\n${count}`;
32
+ });
33
+ }
34
+
35
+ /** The localStorage name for the page at `pathname`. `/a/b`, `/a/b/` and
36
+ * `/a/b/index.html` are the same page; so are `/a/b.html` and `/a/b`. */
37
+ export function taskStorageKey(pathname) {
38
+ let path = String(pathname || '/');
39
+ path = path.replace(/\/index\.html$/, '/').replace(/\.html$/, '');
40
+ if (path.length > 1) path = path.replace(/\/+$/, '');
41
+ return PREFIX + (path || '/');
42
+ }
43
+
44
+ /** The saved states from a stored value - an object of key -> boolean, with
45
+ * no prototype (so an item called "constructor" is just a key). Anything
46
+ * unreadable - missing, not JSON, not an object - is no saved states. */
47
+ export function readTaskStates(raw) {
48
+ const states = Object.create(null);
49
+ if (typeof raw !== 'string') return states;
50
+ let parsed;
51
+ try {
52
+ parsed = JSON.parse(raw);
53
+ } catch {
54
+ return states;
55
+ }
56
+ if (!parsed || typeof parsed !== 'object' || Array.isArray(parsed)) return states;
57
+ for (const [key, value] of Object.entries(parsed)) {
58
+ if (typeof value === 'boolean') states[key] = value;
59
+ }
60
+ return states;
61
+ }
62
+
63
+ /** Whether `key` has a saved state. */
64
+ export const hasTaskState = (states, key) => Object.prototype.hasOwnProperty.call(states, key);
65
+
66
+ /** What to store for a page's items (`{ key, checked, defaultChecked }`, in
67
+ * page order): the ones that differ from the page as written, or null when
68
+ * none do - then the entry is removed. */
69
+ export function taskStatesToStore(items) {
70
+ const states = {};
71
+ let any = false;
72
+ for (const { key, checked, defaultChecked } of items) {
73
+ if (Boolean(checked) === Boolean(defaultChecked)) continue;
74
+ states[key] = Boolean(checked);
75
+ any = true;
76
+ }
77
+ return any ? states : null;
78
+ }
@@ -95,6 +95,9 @@ import { folderRedirects } from "../lib/folder-redirects.js";
95
95
  import { readMovedApiPages, protectedMovedApiPages } from "../lib/moved-api-pages.js";
96
96
  import { DRAFT_BANNER_HTML } from "../lib/drafts.js";
97
97
  import { oncePerBuild } from "../lib/build-memo.js";
98
+ import { tagIndex } from "../lib/tag-index";
99
+ import { pageTags, tagHref } from "../lib/tags.js";
100
+ import { inlineMarkdown } from "../../packages/components/src/lib/inline-markdown.js";
98
101
  // writedocs.json's `basePath` - the addresses below stay site addresses
99
102
  // ("/guides/a/"); the base goes in where one is written (the components package's lib/site-base.ts).
100
103
  import { siteHref } from "../../packages/components/src/lib/site-base";
@@ -362,7 +365,11 @@ export async function getStaticPaths() {
362
365
  .sort((a, b) => orderOf(a) - orderOf(b))
363
366
  .map(slugOf),
364
367
  ];
368
+ // The tag pages (src/pages/tags/[...tag].astro, lib/tag-index.ts) are
369
+ // taken too: a folder redirect at /tags/ would clash with the list of tags.
370
+ const tagAddresses = (await tagIndex()).addresses;
365
371
  const takenAddresses = new Set([
372
+ ...tagAddresses,
366
373
  ...[...pageRoutes, ...landingRoutes, ...hiddenRoutes].map(slugOf),
367
374
  ...(config.redirects ?? []).map((r) => r.source.replace(/^\/+|\/+$/g, "")),
368
375
  ]);
@@ -457,6 +464,13 @@ const activeSection = landing
457
464
  : (sections[sectionIndex] ?? { pages: [], path: [] });
458
465
 
459
466
  const { Content, headings } = await render(entry);
467
+ // The page's <h1>: its title with its inline Markdown (`code`, **bold**,
468
+ // *italic*), escaped otherwise. `title` itself is plain text - the schema
469
+ // keeps the Markdown in `titleMarkdown` (withPlainTitles(), lib/config-schema.ts).
470
+ const titleHtml = inlineMarkdown(entry.data.titleMarkdown ?? entry.data.title);
471
+ // The page's tags, shown under it, and which of them have a page.
472
+ const pageTagList = pageTags(entry.data.tags);
473
+ const pageTagIndex = await tagIndex();
460
474
  const tocHeadings = headings.filter((h) => h.depth === 2 || h.depth === 3);
461
475
 
462
476
  // The lookup tables below are the same for every page, so a build makes
@@ -821,13 +835,14 @@ const components = {
821
835
  {
822
836
  // Frontmatter `deprecated` puts a label beside the <h1>, not in
823
837
  // it - the <h1>'s text is the search index's page title.
838
+ // The title's inline Markdown shows here only (titleHtml below).
824
839
  entry.data.deprecated ? (
825
840
  <div class="wd-article-title">
826
- <h1 data-pagefind-meta="title">{entry.data.title}</h1>
841
+ <h1 data-pagefind-meta="title" set:html={titleHtml} />
827
842
  <span class="wd-deprecated-badge">Deprecated</span>
828
843
  </div>
829
844
  ) : (
830
- <h1 data-pagefind-meta="title">{entry.data.title}</h1>
845
+ <h1 data-pagefind-meta="title" set:html={titleHtml} />
831
846
  )
832
847
  }
833
848
  {showCopyPageMenu && (
@@ -853,6 +868,29 @@ const components = {
853
868
  >
854
869
  {pageSectionTrail && <span data-pagefind-meta="section">{pageSectionTrail}</span>}
855
870
  </div>
871
+ {
872
+ // Frontmatter `tags` (lib/tags.js): each links to its tag's page
873
+ // when it has one (lib/tag-index.ts). Searchable - a search for a
874
+ // tag finds its pages - but not the "Tags" label.
875
+ pageTagList.length > 0 && (
876
+ <div class="wd-page-tags" data-markdown-ignore>
877
+ <span class="wd-page-tags-label" data-pagefind-ignore>Tags</span>
878
+ <ul class="wd-page-tags-list">
879
+ {pageTagList.map((tag) => (
880
+ <li>
881
+ {pageTagIndex.linked.has(tag.slug) ? (
882
+ <a class="wd-tag" href={siteHref(tagHref(tag.slug))}>
883
+ {tag.label}
884
+ </a>
885
+ ) : (
886
+ <span class="wd-tag">{tag.label}</span>
887
+ )}
888
+ </li>
889
+ ))}
890
+ </ul>
891
+ </div>
892
+ )
893
+ }
856
894
  {!entry.data.hideFooterPagination && (
857
895
  <nav class="wd-prevnext" data-pagefind-ignore data-markdown-ignore>
858
896
  {prev && (
@@ -1402,10 +1440,22 @@ const components = {
1402
1440
  .wd-article blockquote p {
1403
1441
  margin: 0.7rem 0;
1404
1442
  }
1405
- .wd-article > table {
1443
+ /* Every table in a page sits in a .wd-table-wrap (lib/rehype-table-
1444
+ scroll.js): a table wider than the column scrolls sideways inside it
1445
+ instead of spilling over the table of contents. A table that fits still
1446
+ fills the column (width: 100%). Only the wrapper of a top-level table
1447
+ gets the spacing and the table styles - a table inside a component
1448
+ keeps that component's own (Searchbar's, for one). */
1449
+ .wd-article .wd-table-wrap {
1450
+ max-width: 100%;
1451
+ overflow-x: auto;
1452
+ }
1453
+ .wd-article > .wd-table-wrap {
1454
+ margin: 1.25rem 0;
1455
+ }
1456
+ .wd-article > .wd-table-wrap > table {
1406
1457
  width: 100%;
1407
1458
  border-collapse: collapse;
1408
- margin: 1.25rem 0;
1409
1459
  font-size: 0.9rem;
1410
1460
  }
1411
1461
  .wd-article th,
@@ -0,0 +1,189 @@
1
+ ---
2
+ // The tag pages (frontmatter `tags` - lib/tags.js): `/tags/` lists every tag,
3
+ // `/tags/<tag>/` every page with that tag. What they list, and which are made,
4
+ // is lib/tag-index.ts.
5
+ //
6
+ // A route of its own, in the shape of 404.astro (BaseLayout in "frame" mode:
7
+ // the topbar, no sidebar - a tag page belongs to no section), rather than
8
+ // another kind of route in [...slug].astro, which renders a page's content
9
+ // throughout. That makes this route outrank [...slug] for an address under
10
+ // /tags/ - so the two must never make the same address (Astro warns of a
11
+ // conflict): tagRoutes() leaves an address to a page or redirect already
12
+ // there, and [...slug].astro's folder redirects keep off the tag pages'.
13
+ //
14
+ // Not in search (no data-pagefind-body - a list of titles would only repeat
15
+ // the pages' own results), and not in llms.txt or the MCP index, which list
16
+ // pages. In the sitemap like any page.
17
+ import { loadDocsConfig, mergeSeo } from "../../lib/config";
18
+ import { tagIndex, tagPageChrome, type Tag } from "../../lib/tag-index";
19
+ import { tagHref } from "../../lib/tags.js";
20
+ import BaseLayout from "../../layout/BaseLayout.astro";
21
+ import { siteHref } from "../../../packages/components/src/lib/site-base";
22
+
23
+ export async function getStaticPaths() {
24
+ const index = await tagIndex();
25
+ return [
26
+ ...(index.index ? [{ params: { tag: undefined }, props: { tag: null } }] : []),
27
+ ...index.routed.map((tag) => ({ params: { tag: tag.slug }, props: { tag } })),
28
+ ];
29
+ }
30
+
31
+ interface Props {
32
+ // The tag whose page this is; null for the list of tags.
33
+ tag: Tag | null;
34
+ }
35
+ const { tag } = Astro.props as Props;
36
+
37
+ const contentDir = process.env.WRITEDOCS_CONTENT_DIR || process.cwd();
38
+ const config = loadDocsConfig(contentDir);
39
+ const index = await tagIndex();
40
+ const { selectors, globalDropdowns } = await tagPageChrome();
41
+
42
+ const pageCount = (n: number) => (n === 1 ? "1 page" : `${n} pages`);
43
+ const title = tag ? `Tagged “${tag.label}”` : "Tags";
44
+ const description = tag
45
+ ? `${pageCount(tag.pages.length)} tagged “${tag.label}”.`
46
+ : `Every tag of ${config.name}, with the pages under each.`;
47
+ // The list of tags links only to tags that have a page.
48
+ const listed = index.tags.filter((t) => index.linked.has(t.slug));
49
+ ---
50
+
51
+ <BaseLayout
52
+ config={config}
53
+ title={title}
54
+ description={description}
55
+ path={tagHref(tag?.slug)}
56
+ seo={mergeSeo(config.seo, undefined)}
57
+ selectors={selectors}
58
+ globalDropdowns={globalDropdowns}
59
+ mode="frame"
60
+ >
61
+ <div class="wd-tags-page">
62
+ {
63
+ tag ? (
64
+ <>
65
+ <p class="wd-tags-eyebrow">Tag</p>
66
+ <h1>{tag.label}</h1>
67
+ <p class="wd-tags-count">
68
+ {pageCount(tag.pages.length)}
69
+ {index.index && (
70
+ <>
71
+ {" · "}
72
+ <a href={siteHref(tagHref())}>All tags</a>
73
+ </>
74
+ )}
75
+ </p>
76
+ <ul class="wd-tags-pages">
77
+ {tag.pages.map((page) => (
78
+ <li>
79
+ <a class="wd-tags-page-link" href={siteHref(page.href)}>
80
+ {page.where.length > 0 && <span class="wd-tags-page-where">{page.where.join(" › ")}</span>}
81
+ <span class="wd-tags-page-title">{page.title}</span>
82
+ {page.description && <span class="wd-tags-page-description">{page.description}</span>}
83
+ </a>
84
+ </li>
85
+ ))}
86
+ </ul>
87
+ </>
88
+ ) : (
89
+ <>
90
+ <h1>Tags</h1>
91
+ <ul class="wd-tags-list">
92
+ {listed.map((t) => (
93
+ <li>
94
+ <a class="wd-tag" href={siteHref(tagHref(t.slug))}>
95
+ {t.label}
96
+ <span class="wd-tag-count" aria-label={pageCount(t.pages.length)}>
97
+ {t.pages.length}
98
+ </span>
99
+ </a>
100
+ </li>
101
+ ))}
102
+ </ul>
103
+ </>
104
+ )
105
+ }
106
+ </div>
107
+ </BaseLayout>
108
+
109
+ <style>
110
+ .wd-tags-page {
111
+ max-width: 760px;
112
+ margin: 0 auto;
113
+ padding: 2.5rem 1.5rem 5rem;
114
+ }
115
+ .wd-tags-page h1 {
116
+ margin: 0 0 0.5rem;
117
+ font-size: 1.9rem;
118
+ line-height: 1.2;
119
+ overflow-wrap: anywhere;
120
+ color: var(--wd-heading);
121
+ }
122
+ .wd-tags-eyebrow {
123
+ margin: 0 0 0.35rem;
124
+ font-size: 0.8rem;
125
+ font-weight: 600;
126
+ letter-spacing: 0.08em;
127
+ text-transform: uppercase;
128
+ color: var(--wd-primary);
129
+ }
130
+ .wd-tags-count {
131
+ margin: 0 0 1.75rem;
132
+ color: var(--wd-text-muted);
133
+ }
134
+ .wd-tags-count a {
135
+ color: var(--wd-primary);
136
+ text-decoration: none;
137
+ font-weight: 500;
138
+ }
139
+ .wd-tags-count a:hover {
140
+ text-decoration: underline;
141
+ }
142
+ .wd-tags-pages {
143
+ list-style: none;
144
+ margin: 0;
145
+ padding: 0;
146
+ display: grid;
147
+ gap: 0.75rem;
148
+ }
149
+ .wd-tags-page-link {
150
+ display: flex;
151
+ flex-direction: column;
152
+ gap: 0.25rem;
153
+ padding: 0.9rem 1.1rem;
154
+ border: 1px solid var(--wd-border);
155
+ border-radius: 0.6rem;
156
+ color: inherit;
157
+ text-decoration: none;
158
+ transition: border-color 0.15s ease;
159
+ }
160
+ .wd-tags-page-link:hover,
161
+ .wd-tags-page-link:focus-visible {
162
+ border-color: var(--wd-primary);
163
+ }
164
+ .wd-tags-page-where {
165
+ font-size: 0.78rem;
166
+ color: var(--wd-text-muted);
167
+ }
168
+ .wd-tags-page-title {
169
+ font-weight: 600;
170
+ color: var(--wd-heading);
171
+ }
172
+ .wd-tags-page-description {
173
+ font-size: 0.92rem;
174
+ color: var(--wd-text-muted);
175
+ }
176
+ .wd-tags-list {
177
+ list-style: none;
178
+ margin: 1.5rem 0 0;
179
+ padding: 0;
180
+ display: flex;
181
+ flex-wrap: wrap;
182
+ gap: 0.5rem;
183
+ }
184
+ .wd-tag-count {
185
+ margin-left: 0.4rem;
186
+ font-size: 0.75rem;
187
+ color: var(--wd-text-muted);
188
+ }
189
+ </style>
@@ -0,0 +1,60 @@
1
+ // Remembers what a reader ticked in a page's task lists (`- [ ] item`), in
2
+ // their browser's localStorage - so a checklist (a recipe's ingredients, an
3
+ // install's steps) is still ticked when they come back to the page. Started
4
+ // from BaseLayout.astro, on load and after every view-transition swap.
5
+ //
6
+ // The boxes come out of the build already tickable (lib/rehype-task-lists.js);
7
+ // without this script they still tick, they just aren't remembered. What's
8
+ // stored, and under which name, is lib/task-lists.js. localStorage being
9
+ // unavailable (blocked, private mode, full) only means nothing is remembered.
10
+ import { taskKeys, taskStorageKey, readTaskStates, hasTaskState, taskStatesToStore } from '../lib/task-lists.js';
11
+
12
+ const BOX_SELECTOR = '.wd-article li.task-list-item input[type="checkbox"]';
13
+
14
+ /** The item's own text: its label (the box and the text up to any nested
15
+ * list - see rehype-task-lists.js), or the item without its nested lists. */
16
+ function itemText(box: HTMLInputElement): string {
17
+ const label = box.closest('label');
18
+ if (label) return label.textContent ?? '';
19
+ const li = box.closest('li');
20
+ if (!li) return '';
21
+ const copy = li.cloneNode(true) as HTMLElement;
22
+ copy.querySelectorAll('ul, ol').forEach((list) => list.remove());
23
+ return copy.textContent ?? '';
24
+ }
25
+
26
+ export function initTaskLists(root: ParentNode) {
27
+ const boxes = Array.from(root.querySelectorAll<HTMLInputElement>(BOX_SELECTOR));
28
+ if (!boxes.length) return;
29
+ const keys = taskKeys(boxes.map(itemText));
30
+ const storageKey = taskStorageKey(location.pathname);
31
+
32
+ let saved = readTaskStates(null);
33
+ try {
34
+ saved = readTaskStates(localStorage.getItem(storageKey));
35
+ } catch {
36
+ // localStorage unavailable - the page's own states stand
37
+ }
38
+
39
+ const save = () => {
40
+ const states = taskStatesToStore(
41
+ boxes.map((box, i) => ({ key: keys[i], checked: box.checked, defaultChecked: box.defaultChecked })),
42
+ );
43
+ try {
44
+ if (states) localStorage.setItem(storageKey, JSON.stringify(states));
45
+ else localStorage.removeItem(storageKey);
46
+ } catch {
47
+ // localStorage unavailable - the tick still shows, it just isn't kept
48
+ }
49
+ };
50
+
51
+ boxes.forEach((box, i) => {
52
+ // Set either way, not only when something was saved: a browser that
53
+ // restores form state on reload (Firefox) could otherwise show a tick
54
+ // that isn't stored anywhere.
55
+ box.checked = hasTaskState(saved, keys[i]) ? saved[keys[i]] : box.defaultChecked;
56
+ if (box.dataset.wdInit) return;
57
+ box.dataset.wdInit = 'true';
58
+ box.addEventListener('change', save);
59
+ });
60
+ }