@writedocs/generator 0.14.0 → 0.16.0

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.
Files changed (120) hide show
  1. package/astro.config.mjs +31 -69
  2. package/package.json +4 -2
  3. package/packages/components/package.json +53 -0
  4. package/{src → packages/components/src}/components/Accordion.astro +2 -2
  5. package/{src → packages/components/src}/components/AppIcon.astro +3 -3
  6. package/{src → packages/components/src}/components/Callout.astro +3 -3
  7. package/{src → packages/components/src}/components/CodeBlock.astro +8 -27
  8. package/{src → packages/components/src}/components/CodeGroup.astro +9 -9
  9. package/{src → packages/components/src}/components/Image.astro +7 -9
  10. package/{src → packages/components/src}/components/compound.ts +1 -1
  11. package/packages/components/src/host.js +24 -0
  12. package/packages/components/src/index.ts +59 -0
  13. package/packages/components/src/integration.js +151 -0
  14. package/packages/components/src/lib/base-path.js +39 -0
  15. package/{src → packages/components/src}/lib/code-line-numbers.js +1 -1
  16. package/packages/components/src/lib/code-transformers.js +45 -0
  17. package/{src → packages/components/src}/lib/icons.js +13 -7
  18. package/{src → packages/components/src}/lib/shiki-code-block.js +9 -9
  19. package/{src → packages/components/src}/lib/site-base.ts +9 -6
  20. package/packages/components/src/scripts/code-block.ts +62 -0
  21. package/packages/components/src/styles/components.css +373 -0
  22. package/packages/components/src/styles/theme.css +63 -0
  23. package/src/cli/build.js +1 -1
  24. package/src/cli/rewrite-redirect-pages.js +8 -6
  25. package/src/cli/run-astro.js +1 -1
  26. package/src/cli/write-mcp-files.js +4 -1
  27. package/src/cli/write-redirects-file.js +4 -3
  28. package/src/components/ApiPlayground.astro +2 -2
  29. package/src/components/ApiSchemaField.astro +1 -1
  30. package/src/components/CopyPageMenu.astro +2 -2
  31. package/src/content.config.ts +21 -1
  32. package/src/icons/README.md +1 -1
  33. package/src/layout/BaseLayout.astro +45 -51
  34. package/src/layout/components/AnalyticsScripts.astro +2 -2
  35. package/src/layout/components/Breadcrumbs.astro +1 -1
  36. package/src/layout/components/ConsentBanner.astro +1 -1
  37. package/src/layout/components/MobileMenu.astro +11 -7
  38. package/src/layout/components/NavTree.astro +2 -2
  39. package/src/layout/components/Sidebar.astro +2 -2
  40. package/src/layout/components/SiteFooter.astro +2 -2
  41. package/src/layout/components/TopBar.astro +10 -6
  42. package/src/layout/styles/base.css +4 -37
  43. package/src/lib/a11y-check.js +1 -1
  44. package/src/lib/appearance.js +64 -0
  45. package/src/lib/asset-dimensions.js +2 -1
  46. package/src/lib/base-path.js +4 -25
  47. package/src/lib/bom.js +20 -0
  48. package/src/lib/color.js +1 -1
  49. package/src/lib/components-host.ts +21 -0
  50. package/src/lib/config-file.js +21 -8
  51. package/src/lib/config-schema.js +14 -7
  52. package/src/lib/config-schema.ts +19 -12
  53. package/src/lib/config.ts +4 -3
  54. package/src/lib/content-check.js +38 -3
  55. package/src/lib/content-store-prune.js +44 -0
  56. package/src/lib/json-schema-descriptions.js +4 -1
  57. package/src/lib/link-check.js +2 -2
  58. package/src/lib/mdx-inject-builtins.js +2 -2
  59. package/src/lib/mdx-inline-react.js +1 -1
  60. package/src/lib/mdx-title-anchor-ids.js +2 -2
  61. package/src/lib/mdx-unknown-components.js +1 -1
  62. package/src/lib/mintlify-convert.js +13 -3
  63. package/src/lib/openapi-reload-integration.js +1 -1
  64. package/src/lib/pages.js +6 -4
  65. package/src/lib/project-files-integration.js +1 -1
  66. package/src/lib/rehype-base-path.js +1 -1
  67. package/src/lib/wdignore-cases.json +9 -2
  68. package/src/lib/wdignore.js +5 -0
  69. package/src/lib/writedocs-legacy-convert.js +2 -2
  70. package/src/pages/404.astro +1 -1
  71. package/src/pages/[...slug].astro +53 -416
  72. package/src/pages/llms-full.txt.ts +6 -3
  73. package/src/pages/llms.txt.ts +4 -4
  74. package/writedocs.schema.json +23 -0
  75. package/src/components/index.ts +0 -62
  76. /package/{src → packages/components/src}/components/AccordionGroup.astro +0 -0
  77. /package/{src → packages/components/src}/components/Badge.astro +0 -0
  78. /package/{src → packages/components/src}/components/Card.astro +0 -0
  79. /package/{src → packages/components/src}/components/CardGroup.astro +0 -0
  80. /package/{src → packages/components/src}/components/Check.astro +0 -0
  81. /package/{src → packages/components/src}/components/Color.astro +0 -0
  82. /package/{src → packages/components/src}/components/ColorItem.astro +0 -0
  83. /package/{src → packages/components/src}/components/ColorRow.astro +0 -0
  84. /package/{src → packages/components/src}/components/Column.astro +0 -0
  85. /package/{src → packages/components/src}/components/Columns.astro +0 -0
  86. /package/{src → packages/components/src}/components/Danger.astro +0 -0
  87. /package/{src → packages/components/src}/components/Expandable.astro +0 -0
  88. /package/{src → packages/components/src}/components/Frame.astro +0 -0
  89. /package/{src → packages/components/src}/components/GitHubRepo.astro +0 -0
  90. /package/{src → packages/components/src}/components/Hint.astro +0 -0
  91. /package/{src → packages/components/src}/components/Icon.astro +0 -0
  92. /package/{src → packages/components/src}/components/Info.astro +0 -0
  93. /package/{src → packages/components/src}/components/Note.astro +0 -0
  94. /package/{src → packages/components/src}/components/Panel.astro +0 -0
  95. /package/{src → packages/components/src}/components/ParamField.astro +0 -0
  96. /package/{src → packages/components/src}/components/Parameter.astro +0 -0
  97. /package/{src → packages/components/src}/components/Prompt.astro +0 -0
  98. /package/{src → packages/components/src}/components/RequestExample.astro +0 -0
  99. /package/{src → packages/components/src}/components/ResponseExample.astro +0 -0
  100. /package/{src → packages/components/src}/components/ResponseField.astro +0 -0
  101. /package/{src → packages/components/src}/components/Searchbar.astro +0 -0
  102. /package/{src → packages/components/src}/components/Step.astro +0 -0
  103. /package/{src → packages/components/src}/components/Steps.astro +0 -0
  104. /package/{src → packages/components/src}/components/Tab.astro +0 -0
  105. /package/{src → packages/components/src}/components/Tabs.astro +0 -0
  106. /package/{src → packages/components/src}/components/Tile.astro +0 -0
  107. /package/{src → packages/components/src}/components/Tip.astro +0 -0
  108. /package/{src → packages/components/src}/components/Tooltip.astro +0 -0
  109. /package/{src → packages/components/src}/components/Tree.astro +0 -0
  110. /package/{src → packages/components/src}/components/TreeFile.astro +0 -0
  111. /package/{src → packages/components/src}/components/TreeFolder.astro +0 -0
  112. /package/{src → packages/components/src}/components/Update.astro +0 -0
  113. /package/{src → packages/components/src}/components/Video.astro +0 -0
  114. /package/{src → packages/components/src}/components/View.astro +0 -0
  115. /package/{src → packages/components/src}/components/Visibility.astro +0 -0
  116. /package/{src → packages/components/src}/components/Warning.astro +0 -0
  117. /package/{src → packages/components/src}/components/class-names.ts +0 -0
  118. /package/{src → packages/components/src}/lib/cli-report.js +0 -0
  119. /package/{src → packages/components/src}/lib/inline-markdown.js +0 -0
  120. /package/{src → packages/components/src}/lib/plain-text.js +0 -0
@@ -0,0 +1,151 @@
1
+ // The Astro integration that sets a project up for the components:
2
+ //
3
+ // // astro.config.mjs
4
+ // import writedocsComponents from '@writedocs/components/integration';
5
+ // export default defineConfig({ integrations: [writedocsComponents()] });
6
+ //
7
+ // What it adds, each one an option that's on unless turned off:
8
+ // - icons: astro-icon, which renders every icon (<Icon>, a Card's icon,
9
+ // ...), with the @iconify-json/* collections this package depends on.
10
+ // astro-icon itself only loads the collections the project's own
11
+ // package.json lists, so a plugin here adds the others to its
12
+ // `virtual:astro-icon` module (iconSetsPlugin()). Off when the project
13
+ // registers astro-icon itself - and then it lists the collections it uses.
14
+ // - styles: theme.css (the --wd-* variables and their defaults) and
15
+ // components.css (code blocks, Shiki's dark theme, image icons) on every
16
+ // page.
17
+ // - scripts: the code blocks' copy and Show more buttons on every page
18
+ // (scripts/code-block.ts). Each component's own <script> comes with it.
19
+ // - markdown: the project's own ``` fences (in .md/.mdx, and so inside a
20
+ // <CodeGroup>) through the same Shiki transformers as <CodeBlock>
21
+ // (lib/code-transformers.js), so they get the code-block frame, title and
22
+ // copy button - and, when the project hasn't picked Shiki themes of its
23
+ // own, the light and dark pair <CodeBlock> uses by default, which
24
+ // components.css swaps between with data-theme.
25
+ // And two that are off unless given:
26
+ // - host: a module that answers what the components ask of the site - the
27
+ // code theme, image sizes (host.js has the default and the functions it
28
+ // exports). A path, relative to the project's root unless absolute. The
29
+ // generator passes its own (src/lib/components-host.ts).
30
+ // - base: the base the site is served under ("/docs"), put in front of the
31
+ // addresses the components write (lib/site-base.ts). The generator defines
32
+ // it itself, from writedocs.json's basePath.
33
+ //
34
+ // The writedocs generator uses this too (astro.config.mjs), with icons,
35
+ // styles, scripts and markdown off: it has its own of each.
36
+ import fs from 'node:fs';
37
+ import path from 'node:path';
38
+ import { fileURLToPath } from 'node:url';
39
+ import { codeTransformers } from './lib/code-transformers.js';
40
+ import { loadIconCollection } from './lib/icons.js';
41
+ import { codeblockTheme } from './host.js';
42
+
43
+ const HERE = path.dirname(fileURLToPath(import.meta.url));
44
+ const DEFAULT_HOST = path.join(HERE, 'host.js');
45
+
46
+ /** The icon collections this package depends on ("lucide", "mdi", ...). */
47
+ function iconSetNames() {
48
+ const { dependencies = {} } = JSON.parse(fs.readFileSync(path.join(HERE, '..', 'package.json'), 'utf8'));
49
+ return Object.keys(dependencies)
50
+ .filter((name) => name.startsWith('@iconify-json/'))
51
+ .map((name) => name.slice('@iconify-json/'.length));
52
+ }
53
+
54
+ /** A Vite plugin that adds this package's icon collections to astro-icon's
55
+ * module - `export default <collections>;\nexport const config = <json>`,
56
+ * the shape the generator's src/lib/icon-data-dev.js reads too - when the
57
+ * project's package.json doesn't list them. A module of another shape (a
58
+ * new astro-icon) is left as it is. */
59
+ function iconSetsPlugin() {
60
+ return {
61
+ name: '@writedocs/components:icon-sets',
62
+ transform(code, id) {
63
+ if (id !== '\0virtual:astro-icon') return null;
64
+ const match = /^export default (\{[\s\S]*\});\nexport const config = (\{[\s\S]*\})\s*$/.exec(code);
65
+ if (!match) return null;
66
+ const collections = JSON.parse(match[1]);
67
+ const missing = iconSetNames().filter((name) => !collections[name]);
68
+ for (const name of missing) {
69
+ const data = loadIconCollection(name);
70
+ if (data) collections[name] = data;
71
+ }
72
+ if (!missing.length) return null;
73
+ return { code: `export default ${JSON.stringify(collections)};\nexport const config = ${match[2]}`, map: null };
74
+ },
75
+ };
76
+ }
77
+
78
+ /** The same file, however Vite or Windows spells it: separators, a drive
79
+ * letter's case, a ?query - or a link to it (pnpm's node_modules, or Vite's
80
+ * preserveSymlinks, give the package's path through a link, while Node
81
+ * loaded this file from its real path). */
82
+ function sameFile(a, b) {
83
+ const norm = (p) => {
84
+ const file = p.split('?')[0];
85
+ let real = file;
86
+ try {
87
+ real = fs.realpathSync(file);
88
+ } catch {
89
+ // Not a file on disk (a virtual id) - compared as it is.
90
+ }
91
+ return path.normalize(real).toLowerCase();
92
+ };
93
+ return norm(a) === norm(b);
94
+ }
95
+
96
+ /** A Vite plugin that puts `hostFile` where the components import the
97
+ * default host.js from. */
98
+ function hostPlugin(hostFile) {
99
+ const id = path.resolve(hostFile).split(path.sep).join('/');
100
+ return {
101
+ name: '@writedocs/components:host',
102
+ enforce: 'pre',
103
+ async resolveId(source, importer, options) {
104
+ if (!importer || !/(^|\/)host\.js$/.test(source)) return null;
105
+ const resolved = await this.resolve(source, importer, { ...options, skipSelf: true });
106
+ return resolved && sameFile(resolved.id, DEFAULT_HOST) ? id : null;
107
+ },
108
+ };
109
+ }
110
+
111
+ export default function writedocsComponents({ host, base, icons = true, styles = true, scripts = true, markdown = true } = {}) {
112
+ return {
113
+ name: '@writedocs/components',
114
+ hooks: {
115
+ 'astro:config:setup': async ({ config, updateConfig, injectScript }) => {
116
+ const integrations = [];
117
+ if (icons) {
118
+ const { default: icon } = await import('astro-icon');
119
+ integrations.push(icon());
120
+ }
121
+ // Astro's own default is a single theme and no `themes`; a project
122
+ // that set `themes` keeps them.
123
+ const ownThemes = Object.keys(config.markdown?.shikiConfig?.themes ?? {}).length > 0;
124
+ updateConfig({
125
+ ...(integrations.length ? { integrations } : {}),
126
+ ...(markdown
127
+ ? { markdown: { shikiConfig: { transformers: codeTransformers(), ...(ownThemes ? {} : { themes: codeblockTheme() }) } } }
128
+ : {}),
129
+ vite: {
130
+ plugins: [...(host ? [hostPlugin(path.resolve(fileURLToPath(config.root), host))] : []), ...(icons ? [iconSetsPlugin()] : [])],
131
+ ...(base !== undefined ? { define: { __WD_BASE__: JSON.stringify(base) } } : {}),
132
+ },
133
+ });
134
+ if (styles) {
135
+ injectScript('page-ssr', "import '@writedocs/components/styles/theme.css';\nimport '@writedocs/components/styles/components.css';");
136
+ }
137
+ if (scripts) {
138
+ injectScript(
139
+ 'page',
140
+ [
141
+ "import { initCodeCopyButtons, initCodeExpandButtons } from '@writedocs/components/scripts/code-block';",
142
+ 'const init = () => { initCodeCopyButtons(document); initCodeExpandButtons(document); };',
143
+ 'init();',
144
+ "document.addEventListener('astro:page-load', init);",
145
+ ].join('\n')
146
+ );
147
+ }
148
+ },
149
+ },
150
+ };
151
+ }
@@ -0,0 +1,39 @@
1
+ // The base a site is served under ("" or "/docs" - writedocs.json's
2
+ // `basePath` in the generator) and the addresses that take it. Addresses come
3
+ // in two kinds, and only one of them takes the base:
4
+ // - site addresses: "/guides/a/", "/images/x.png" - a path in the site.
5
+ // withBase() prefixes them, once, where the final address is written -
6
+ // never twice: a page can live at "/docs/..." inside a site whose base is
7
+ // "/docs", so "already starts with the base" can't tell whether an address
8
+ // has been prefixed.
9
+ // - everything else - "https://...", "#a", "mailto:", "//cdn...", a relative
10
+ // "../a" - is left as it is.
11
+ //
12
+ // The generator's src/lib/base-path.js re-exports these, next to the parts
13
+ // only the generator needs (the field's pattern, withoutBase(), site URLs).
14
+
15
+ /** Whether `url` is a site address: a path from the site's root ("/a/b"),
16
+ * not a protocol-relative "//host/a". */
17
+ export function isSiteAddress(url) {
18
+ return typeof url === 'string' && url.startsWith('/') && !url.startsWith('//');
19
+ }
20
+
21
+ /** `url` with the base in front, if it's a site address - "/a/" -> "/docs/a/",
22
+ * "/" -> "/docs/". Anything else, and everything when there's no base,
23
+ * comes back as it is. */
24
+ export function withBase(base, url) {
25
+ if (!base || !isSiteAddress(url)) return url;
26
+ return base + url;
27
+ }
28
+
29
+ /** A `srcset` with the base in front of each site address in it. */
30
+ export function srcsetWithBase(base, srcset) {
31
+ if (!base || typeof srcset !== 'string') return srcset;
32
+ return srcset
33
+ .split(',')
34
+ .map((candidate) => {
35
+ const [url, ...descriptor] = candidate.trim().split(/\s+/);
36
+ return [withBase(base, url), ...descriptor].join(' ');
37
+ })
38
+ .join(', ');
39
+ }
@@ -1,6 +1,6 @@
1
1
  // The width of a ```js lines block's number column, in digits: as many as
2
2
  // its last line number has. The column is that many `ch` wide (see
3
- // .wd-code-lines in [...slug].astro), so a block of under ten lines starts
3
+ // .wd-code-lines in styles/components.css), so a block of under ten lines starts
4
4
  // its numbers at the panel's padding, like Mintlify's, instead of inside a
5
5
  // fixed-width box sized for two or three digits.
6
6
  //
@@ -0,0 +1,45 @@
1
+ // The Shiki transformers every code block goes through - a ``` fence in the
2
+ // generator's Markdown (its astro.config.mjs passes this to
3
+ // markdown.shikiConfig) and a <CodeBlock> - so both look and behave the same.
4
+ // The official @shikijs/transformers annotation transformers, enabled for
5
+ // every block without per-page opt-in:
6
+ // ```js {1,3-5} -> transformerMetaHighlight
7
+ // ```js /someWord/ -> transformerMetaWordHighlight
8
+ // // [!code highlight] -> transformerNotationHighlight
9
+ // // [!code word:someWord] -> transformerNotationWordHighlight
10
+ // // [!code focus] -> transformerNotationFocus
11
+ // // [!code ++] / // [!code --] -> transformerNotationDiff
12
+ // // [!code error] / [!code warning] -> transformerNotationErrorLevel
13
+ // (comment syntax adapts to the language - # for Python/bash, // for JS/etc -
14
+ // see each transformer's own docs at shiki.style). Plus codeBlockTransformer,
15
+ // writedocs' own, for the copy button, an optional title bar, and the
16
+ // wrap/lines/expandable meta flags - see shiki-code-block.js. It runs last so
17
+ // its `root` hook wraps the <pre> only after every class the transformers
18
+ // above added to it is already in place - though in practice this doesn't
19
+ // matter, since all `pre`/`line` hooks across every transformer run to
20
+ // completion before any `root` hook runs at all (two separate passes, not
21
+ // interleaved).
22
+ import {
23
+ transformerMetaHighlight,
24
+ transformerMetaWordHighlight,
25
+ transformerNotationHighlight,
26
+ transformerNotationWordHighlight,
27
+ transformerNotationFocus,
28
+ transformerNotationDiff,
29
+ transformerNotationErrorLevel,
30
+ } from '@shikijs/transformers';
31
+ import { codeBlockTransformer } from './shiki-code-block.js';
32
+
33
+ /** A new list of the transformers, in the order they run. */
34
+ export function codeTransformers() {
35
+ return [
36
+ transformerMetaHighlight(),
37
+ transformerMetaWordHighlight(),
38
+ transformerNotationHighlight(),
39
+ transformerNotationWordHighlight(),
40
+ transformerNotationFocus(),
41
+ transformerNotationDiff(),
42
+ transformerNotationErrorLevel(),
43
+ codeBlockTransformer(),
44
+ ];
45
+ }
@@ -9,8 +9,9 @@
9
9
  // Plain JavaScript, not TypeScript, on purpose: `writedocs validate` loads
10
10
  // this with plain Node to check icon names, and Node refuses to strip types
11
11
  // from any file under node_modules - so a .ts version would work from the
12
- // checkout and fail for everyone who installs the package. lib/config.ts
13
- // re-exports these for everything that runs inside Astro.
12
+ // checkout and fail for everyone who installs the package. The generator's
13
+ // plain-Node checks import this file directly, and its lib/config.ts
14
+ // re-exports these for everything that runs inside its Astro.
14
15
  import path from 'node:path';
15
16
  import { createRequire } from 'node:module';
16
17
 
@@ -24,12 +25,17 @@ const DEFAULT_ICON_COLLECTION = 'lucide';
24
25
  const BARE_ICON_COLLECTIONS = [DEFAULT_ICON_COLLECTION, 'fa6-solid', 'fa6-brands'];
25
26
 
26
27
  // Loaded lazily, once per collection, from the installed @iconify-json/*
27
- // packages (the same data astro-icon itself renders from). Resolved
28
- // against this package, not the site being built - WRITEDOCS_PACKAGE_ROOT
29
- // is set by run-astro.js; outside that subprocess, this file's own URL
30
- // still sits inside the package.
28
+ // packages (the same data astro-icon itself renders from). Under the
29
+ // writedocs generator they're resolved against the generator, not the site
30
+ // being built - WRITEDOCS_PACKAGE_ROOT is set by its run-astro.js. Anywhere
31
+ // else (a project that installs @writedocs/components) from this file's own
32
+ // URL, which is inside that project's node_modules, where the collections
33
+ // this package depends on are installed. Exported for the integration, which
34
+ // hands the same sets to astro-icon.
31
35
  const iconCollections = new Map();
32
- function loadIconCollection(collection) {
36
+ /** An installed @iconify-json collection's data ("lucide" -> its
37
+ * icons.json), or null when it isn't installed. */
38
+ export function loadIconCollection(collection) {
33
39
  if (!iconCollections.has(collection)) {
34
40
  const packageRoot = process.env.WRITEDOCS_PACKAGE_ROOT;
35
41
  const require = createRequire(packageRoot ? path.join(packageRoot, 'package.json') : import.meta.url);
@@ -5,23 +5,23 @@
5
5
  // handful of writedocs-specific meta flags off the fence's info string
6
6
  // (the part after the language, e.g. ```js title="foo.js" wrap lines
7
7
  // expandable) to add a title bar and toggle wrap/line-numbers/
8
- // expandable behavior. Registered in astro.config.mjs's
9
- // markdown.shikiConfig.transformers, alongside the official
10
- // @shikijs/transformers notation/meta-highlight transformers that
11
- // handle the actual line/word annotation classes.
8
+ // expandable behavior. Last in codeTransformers() (code-transformers.js),
9
+ // after the official @shikijs/transformers notation/meta-highlight
10
+ // transformers that handle the actual line/word annotation classes -
11
+ // the list the generator's markdown.shikiConfig and CodeBlock.astro share.
12
12
  //
13
13
  // Everything here only produces static HAST/HTML at build time - the
14
14
  // click behavior for the copy and expand/collapse buttons lives in
15
- // [...slug].astro's client script instead, and the CSS for all of this
16
- // (including the classes the @shikijs/transformers transformers add)
17
- // lives there too.
15
+ // ../scripts/code-block.ts, and the CSS for all of this (including the
16
+ // classes the @shikijs/transformers transformers add) in
17
+ // ../styles/components.css.
18
18
  //
19
19
  // Deliberately NOT used by ApiPlayground/ApiReferencePanel's <Code/>
20
20
  // usages - per Astro's docs, <Code/> doesn't inherit markdown.shikiConfig
21
21
  // at all, so this only ever touches genuine ```-fenced MDX content and
22
22
  // never collides with the API playground's own bespoke copy buttons.
23
23
 
24
- import { iconSvg } from './config.ts';
24
+ import { iconSvg } from './icons.js';
25
25
  import { lineNumberDigits } from './code-line-numbers.js';
26
26
 
27
27
  // The fence's info string after the language, split into tokens: a
@@ -131,7 +131,7 @@ export function codeBlockTransformer() {
131
131
  return node;
132
132
  },
133
133
  // Same classes transformerNotationFocus (`// [!code focus]`) adds, so
134
- // `focus={...}` reuses [...slug].astro's existing dimming CSS.
134
+ // `focus={...}` reuses the existing dimming CSS (styles/components.css).
135
135
  pre(node) {
136
136
  if (this.options.meta?.__wdMeta?.focus.length) this.addClassToHast(node, 'has-focused');
137
137
  return node;
@@ -1,8 +1,11 @@
1
1
  // The site's base (writedocs.json `basePath`) for components and page
2
- // scripts - lib/base-path.js explains the base and which addresses take it.
3
- // __WD_BASE__ is "" or "/docs", set by astro.config.mjs (vite.define), so
4
- // the same import works in a component's frontmatter and in a <script>; with
5
- // no base, siteHref() returns its argument and the built pages don't change.
2
+ // scripts - base-path.js explains the base and which addresses take it.
3
+ // __WD_BASE__ is "" or "/docs", set with vite.define - by the generator's
4
+ // astro.config.mjs, or by this package's integration when it's given a
5
+ // `base` - so the same import works in a component's frontmatter and in a
6
+ // <script>; with no base, siteHref() returns its argument and the built
7
+ // pages don't change. A project that defines neither gets "": `typeof`
8
+ // doesn't throw on a name that was never declared.
6
9
  //
7
10
  // The rule: logic keeps site addresses as they are ("/guides/a/"); the base
8
11
  // goes in where the address is written - an href, a src, a url() - with
@@ -10,10 +13,10 @@
10
13
  // twice.
11
14
  import { withBase, srcsetWithBase } from './base-path.js';
12
15
 
13
- declare const __WD_BASE__: string;
16
+ declare const __WD_BASE__: string | undefined;
14
17
 
15
18
  /** "" or "/docs". */
16
- export const BASE: string = __WD_BASE__;
19
+ export const BASE: string = typeof __WD_BASE__ === 'string' ? __WD_BASE__ : '';
17
20
 
18
21
  /** A site address with the base in front ("/a/" -> "/docs/a/"); anything
19
22
  * else - a full URL, "#x", a relative path - as it is. */
@@ -0,0 +1,62 @@
1
+ // What a code block's buttons do in the browser. The buttons themselves are
2
+ // emitted at build time by codeBlockTransformer (lib/shiki-code-block.js),
3
+ // which wraps each <pre> in a .wd-code-block container; this wires up their
4
+ // clicks. Each function marks what it has set up (data-wd-init), so calling
5
+ // it again - on every `astro:page-load`, or from two scripts on one page -
6
+ // sets up only what's new. The generator calls these from [...slug].astro's
7
+ // page script; the integration calls them on every page of any other project.
8
+
9
+ /** The copy-to-clipboard button on every code block under `root`. */
10
+ export function initCodeCopyButtons(root: ParentNode) {
11
+ root.querySelectorAll<HTMLButtonElement>(".wd-code-copy-btn").forEach((btn) => {
12
+ if (btn.dataset.wdInit) return;
13
+ btn.dataset.wdInit = "true";
14
+ btn.addEventListener("click", async () => {
15
+ const pre = btn.closest(".wd-code-block")?.querySelector("pre");
16
+ if (!pre) return;
17
+ try {
18
+ await navigator.clipboard.writeText(pre.textContent ?? "");
19
+ } catch {
20
+ return; // clipboard unavailable (e.g. insecure context) - fail silently
21
+ }
22
+ btn.textContent = "✓";
23
+ btn.classList.add("wd-code-copied");
24
+ window.setTimeout(() => {
25
+ btn.textContent = "⧉";
26
+ btn.classList.remove("wd-code-copied");
27
+ }, 1500);
28
+ });
29
+ });
30
+ }
31
+
32
+ /** The Show more/less toggle of every ```js expandable code block under
33
+ * `root` - codeBlockTransformer only adds this button when the fence's meta
34
+ * string contains the `expandable` keyword. */
35
+ export function initCodeExpandButtons(root: ParentNode) {
36
+ root.querySelectorAll<HTMLButtonElement>(".wd-code-expand-btn").forEach((btn) => {
37
+ if (btn.dataset.wdInit) return;
38
+ btn.dataset.wdInit = "true";
39
+ const block = btn.closest<HTMLElement>(".wd-code-expandable");
40
+ if (!block) return;
41
+ // A block no taller than the collapsed height has nothing to show
42
+ // more of: .wd-code-fits drops the fade and the button. Only when
43
+ // it can be measured - a block in a hidden CodeGroup tab or a
44
+ // closed accordion has no height yet, and keeps its button.
45
+ const pre = block.querySelector("pre");
46
+ // The collapsed height shows 12 lines and hides only the bottom
47
+ // padding, so that padding doesn't count against fitting.
48
+ const padBottom = pre ? parseFloat(getComputedStyle(pre).paddingBottom) || 0 : 0;
49
+ if (pre && pre.clientHeight > 0 && pre.scrollHeight - padBottom <= pre.clientHeight + 1) {
50
+ block.classList.add("wd-code-fits");
51
+ return;
52
+ }
53
+ btn.addEventListener("click", () => {
54
+ const expanded = block.classList.toggle("wd-code-expanded");
55
+ btn.textContent = expanded ? "Show less" : "Show more";
56
+ btn.setAttribute("aria-expanded", String(expanded));
57
+ // Collapsing a long block can leave the reader below it: bring
58
+ // it back into view.
59
+ if (!expanded) block.scrollIntoView({ block: "nearest" });
60
+ });
61
+ });
62
+ }