@writedocs/generator 0.11.1 → 0.13.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.
- package/astro.config.mjs +12 -1
- package/package.json +1 -1
- package/src/cli/build.js +203 -177
- package/src/cli/dev.js +268 -261
- package/src/cli/generate-api-pages.js +121 -36
- package/src/cli/og-image-worker.js +20 -0
- package/src/cli/og-images.js +70 -0
- package/src/cli/run-astro.js +97 -93
- package/src/components/ApiReferencePanel.astro +1792 -1792
- package/src/content.config.ts +203 -189
- package/src/layout/BaseLayout.astro +1 -3
- package/src/layout/components/MobileMenu.astro +9 -13
- package/src/layout/components/NavTree.astro +21 -6
- package/src/layout/components/Sidebar.astro +4 -4
- package/src/layout/styles/base.css +326 -327
- package/src/layout/styles/mobile-menu.css +285 -285
- package/src/lib/cli-report.js +22 -20
- package/src/lib/content-store-reload-integration.js +101 -0
- package/src/lib/icon-data-dev.js +53 -0
- package/src/lib/moved-api-pages.js +49 -54
- package/src/lib/og-cards.js +33 -0
- package/src/lib/og-image.js +235 -168
- package/src/lib/openapi-dev-status.js +80 -0
- package/src/lib/openapi-reload-integration.js +193 -0
- package/src/pages/[...slug].astro +4 -0
- package/src/pages/og/[...slug].png.ts +63 -64
- package/src/scripts/mobile-menu.ts +80 -55
- package/src/scripts/sidebar-scroll.ts +61 -65
|
@@ -0,0 +1,193 @@
|
|
|
1
|
+
// `writedocs dev`: an edit to an OpenAPI spec shows up in the preview.
|
|
2
|
+
// generateApiPages() runs once before the preview starts (cli/dev.js); this
|
|
3
|
+
// watches every file it read - each spec writedocs.json's navigation mounts,
|
|
4
|
+
// each spec a page names (Mintlify's "spec.json GET /x") and each file a $ref
|
|
5
|
+
// points into - and runs it again when one of them changes, or when an edit
|
|
6
|
+
// to writedocs.json changes which spec is mounted where.
|
|
7
|
+
//
|
|
8
|
+
// A regeneration writes in two steps (writeInTwoSteps()), so the navigation
|
|
9
|
+
// never names a page Astro doesn't have yet. The navigation comes from the
|
|
10
|
+
// manifest, read on every request; a page is an entry in Astro's content
|
|
11
|
+
// store, which only changes when the generated-docs/ collection is synced
|
|
12
|
+
// again (refreshContent() - content.config.ts doesn't give that collection
|
|
13
|
+
// a watcher of its own, so nothing syncs it halfway). First the pages added
|
|
14
|
+
// or changed, then a sync; then the manifest, the operation JSON and the
|
|
15
|
+
// removal of what went, and a sync if pages went.
|
|
16
|
+
//
|
|
17
|
+
// What reloads the open tab: when pages were added, changed or removed, once
|
|
18
|
+
// the last sync is done this hands Astro its store's change event
|
|
19
|
+
// (contentStoreChanged(), lib/content-store-reload-integration.js) - Astro
|
|
20
|
+
// re-reads the store, clears its routes and reloads the tab. Left to the
|
|
21
|
+
// file watcher, that event came at the first save of the store, which can
|
|
22
|
+
// be before the sync ends: the tab reloaded halfway, and nothing reloaded it
|
|
23
|
+
// again. When only what pages read as they render changed - the operation
|
|
24
|
+
// JSON, the manifest - there's nothing for Astro to re-read: this sends the
|
|
25
|
+
// reload.
|
|
26
|
+
//
|
|
27
|
+
// A spec that doesn't parse leaves the last pages that worked in place
|
|
28
|
+
// (nothing is written then): the error goes to the terminal, and every page
|
|
29
|
+
// shows it until the spec parses again - see lib/openapi-dev-status.js.
|
|
30
|
+
import path from 'node:path';
|
|
31
|
+
import { planApiPages, writeGeneratedFiles } from '../cli/generate-api-pages.js';
|
|
32
|
+
import { collectOpenApiGroups } from './openapi-spec.js';
|
|
33
|
+
import { readConfigText } from './config-file.js';
|
|
34
|
+
import { writedocsTempDir } from './writedocs-temp-dir.js';
|
|
35
|
+
import { report } from './cli-report.js';
|
|
36
|
+
import { readDevOpenApiState, writeDevOpenApiState, specProblem } from './openapi-dev-status.js';
|
|
37
|
+
import { contentStoreChanged } from './content-store-reload-integration.js';
|
|
38
|
+
|
|
39
|
+
/** Wait this long after the last change before regenerating - an editor's
|
|
40
|
+
* save can arrive as more than one write. */
|
|
41
|
+
export const REGENERATE_DELAY_MS = 200;
|
|
42
|
+
|
|
43
|
+
/** Which spec writedocs.json mounts at which path, as one string - null when
|
|
44
|
+
* the file doesn't parse (the preview reports that itself). */
|
|
45
|
+
export function openApiMounts(configText) {
|
|
46
|
+
try {
|
|
47
|
+
const groups = collectOpenApiGroups(JSON.parse(configText).navigation);
|
|
48
|
+
return JSON.stringify(groups.map((group) => [group.openapi.src, group.openapi.path]));
|
|
49
|
+
} catch {
|
|
50
|
+
return null;
|
|
51
|
+
}
|
|
52
|
+
}
|
|
53
|
+
|
|
54
|
+
function mountedSpecs(contentDir) {
|
|
55
|
+
try {
|
|
56
|
+
return collectOpenApiGroups(JSON.parse(readConfigText(contentDir)).navigation).map((group) => path.resolve(contentDir, group.openapi.src));
|
|
57
|
+
} catch {
|
|
58
|
+
return [];
|
|
59
|
+
}
|
|
60
|
+
}
|
|
61
|
+
|
|
62
|
+
const sameFileKey = (file) => (process.platform === 'win32' ? path.resolve(file).toLowerCase() : path.resolve(file));
|
|
63
|
+
|
|
64
|
+
/** The watching itself, apart from Vite. `changed(file)` is called for every
|
|
65
|
+
* file that changed; when it's a watched spec, or writedocs.json with
|
|
66
|
+
* different mounts, `regenerate()` runs after `delayMs` - one run at a time,
|
|
67
|
+
* and once more if something changed during one. `onDone({ ok, result })`
|
|
68
|
+
* or `onDone({ ok: false, error })` follows each run. `files()` is what to
|
|
69
|
+
* watch: the specs generateApiPages() last read (`sources` at first), and
|
|
70
|
+
* the specs writedocs.json mounts even when they don't parse. */
|
|
71
|
+
export function createSpecWatch({ contentDir, sources = [], regenerate, onDone, delayMs = REGENERATE_DELAY_MS }) {
|
|
72
|
+
const configKey = sameFileKey(path.join(contentDir, 'writedocs.json'));
|
|
73
|
+
let watched = new Map();
|
|
74
|
+
const watch = (files) => {
|
|
75
|
+
watched = new Map([...files, ...mountedSpecs(contentDir)].map((file) => [sameFileKey(file), path.resolve(file)]));
|
|
76
|
+
};
|
|
77
|
+
watch(sources);
|
|
78
|
+
let mounts = openApiMounts(readConfigTextOrEmpty(contentDir));
|
|
79
|
+
let timer = null;
|
|
80
|
+
let running = null;
|
|
81
|
+
let again = false;
|
|
82
|
+
|
|
83
|
+
async function run() {
|
|
84
|
+
timer = null;
|
|
85
|
+
if (running) {
|
|
86
|
+
again = true;
|
|
87
|
+
return;
|
|
88
|
+
}
|
|
89
|
+
running = (async () => {
|
|
90
|
+
try {
|
|
91
|
+
const result = await regenerate();
|
|
92
|
+
watch(result.sources);
|
|
93
|
+
await onDone({ ok: true, result });
|
|
94
|
+
} catch (error) {
|
|
95
|
+
watch([...watched.values(), ...(typeof error?.source === 'string' ? [error.source] : [])]);
|
|
96
|
+
await onDone({ ok: false, error });
|
|
97
|
+
}
|
|
98
|
+
})();
|
|
99
|
+
await running;
|
|
100
|
+
running = null;
|
|
101
|
+
if (again) {
|
|
102
|
+
again = false;
|
|
103
|
+
schedule();
|
|
104
|
+
}
|
|
105
|
+
}
|
|
106
|
+
function schedule() {
|
|
107
|
+
clearTimeout(timer);
|
|
108
|
+
timer = setTimeout(run, delayMs);
|
|
109
|
+
}
|
|
110
|
+
return {
|
|
111
|
+
files: () => [...watched.values()],
|
|
112
|
+
changed(file) {
|
|
113
|
+
const key = sameFileKey(file);
|
|
114
|
+
if (key === configKey) {
|
|
115
|
+
const next = openApiMounts(readConfigTextOrEmpty(contentDir));
|
|
116
|
+
if (next === null || next === mounts) return false;
|
|
117
|
+
mounts = next;
|
|
118
|
+
} else if (!watched.has(key)) {
|
|
119
|
+
return false;
|
|
120
|
+
}
|
|
121
|
+
schedule();
|
|
122
|
+
return true;
|
|
123
|
+
},
|
|
124
|
+
/** Resolves when no run is waiting or under way (for tests). */
|
|
125
|
+
async idle() {
|
|
126
|
+
while (timer || running) await (running ?? new Promise((r) => setTimeout(r, delayMs)));
|
|
127
|
+
},
|
|
128
|
+
close() {
|
|
129
|
+
clearTimeout(timer);
|
|
130
|
+
timer = null;
|
|
131
|
+
},
|
|
132
|
+
};
|
|
133
|
+
}
|
|
134
|
+
|
|
135
|
+
function readConfigTextOrEmpty(contentDir) {
|
|
136
|
+
try {
|
|
137
|
+
return readConfigText(contentDir);
|
|
138
|
+
} catch {
|
|
139
|
+
return '';
|
|
140
|
+
}
|
|
141
|
+
}
|
|
142
|
+
|
|
143
|
+
/** generateApiPages() for a running preview: the same files, written in two
|
|
144
|
+
* steps with `refresh()` - a sync of the generated-docs/ collection - after
|
|
145
|
+
* each step that changed pages (see the top of this file). Returns what
|
|
146
|
+
* generateApiPages() returns. */
|
|
147
|
+
export async function writeInTwoSteps({ contentDir, refresh }) {
|
|
148
|
+
const { summary, files, roots } = await planApiPages({ contentDir });
|
|
149
|
+
const isPage = (file) => file.startsWith(roots[0] + path.sep);
|
|
150
|
+
const pages = files && new Map([...files].filter(([file]) => isPage(file)));
|
|
151
|
+
const first = writeGeneratedFiles([], pages);
|
|
152
|
+
if (first.written.length) await refresh();
|
|
153
|
+
const second = writeGeneratedFiles(roots, files, { keepEmptyFolders: true });
|
|
154
|
+
if (second.removed.some(isPage)) await refresh();
|
|
155
|
+
return { ...summary, written: [...first.written, ...second.written], removed: second.removed };
|
|
156
|
+
}
|
|
157
|
+
|
|
158
|
+
export function openapiReload({ contentDir, packageRoot }) {
|
|
159
|
+
return {
|
|
160
|
+
name: 'writedocs-openapi-reload',
|
|
161
|
+
hooks: {
|
|
162
|
+
'astro:server:setup': ({ server, refreshContent }) => {
|
|
163
|
+
const generatedDocsDir = path.join(writedocsTempDir(contentDir), 'generated-docs');
|
|
164
|
+
const isPage = (file) => file.startsWith(generatedDocsDir + path.sep);
|
|
165
|
+
const reload = () => server.ws.send({ type: 'full-reload', path: '*' });
|
|
166
|
+
// The loader's name: content.config.ts's generatedDocs collection.
|
|
167
|
+
const refresh = () => refreshContent?.({ loaders: ['glob-loader'] });
|
|
168
|
+
const watch = createSpecWatch({
|
|
169
|
+
contentDir,
|
|
170
|
+
sources: readDevOpenApiState(contentDir).sources,
|
|
171
|
+
regenerate: () => writeInTwoSteps({ contentDir, refresh }),
|
|
172
|
+
onDone: async ({ ok, result, error }) => {
|
|
173
|
+
for (const file of watch.files()) server.watcher.add(file);
|
|
174
|
+
if (!ok) {
|
|
175
|
+
const problem = specProblem(error, contentDir);
|
|
176
|
+
writeDevOpenApiState(contentDir, { sources: watch.files(), problem });
|
|
177
|
+
report('error', problem.message, problem.where);
|
|
178
|
+
reload();
|
|
179
|
+
return;
|
|
180
|
+
}
|
|
181
|
+
writeDevOpenApiState(contentDir, { sources: result.sources, problem: null });
|
|
182
|
+
result.warnings.forEach((message) => report('warn', message));
|
|
183
|
+
if ([...result.written, ...result.removed].some(isPage)) contentStoreChanged(server, packageRoot);
|
|
184
|
+
else reload();
|
|
185
|
+
},
|
|
186
|
+
});
|
|
187
|
+
for (const file of watch.files()) server.watcher.add(file);
|
|
188
|
+
for (const event of ['add', 'change', 'unlink']) server.watcher.on(event, (file) => watch.changed(file));
|
|
189
|
+
server.httpServer?.once('close', () => watch.close());
|
|
190
|
+
},
|
|
191
|
+
},
|
|
192
|
+
};
|
|
193
|
+
}
|
|
@@ -23,6 +23,7 @@ import {
|
|
|
23
23
|
landingSelectors,
|
|
24
24
|
} from "../lib/config";
|
|
25
25
|
import { writedocsTempDir } from "../lib/writedocs-temp-dir.js";
|
|
26
|
+
import { throwIfOpenApiProblem } from "../lib/openapi-dev-status.js";
|
|
26
27
|
import { parseOpenApiRef } from "../lib/openapi-ref.js";
|
|
27
28
|
import { languageAlternates } from "../lib/item-pages.js";
|
|
28
29
|
import { wantsGeneratedCard, ogImagePath } from "../lib/og-image.js";
|
|
@@ -374,6 +375,9 @@ const {
|
|
|
374
375
|
|
|
375
376
|
const contentDir = process.env.WRITEDOCS_CONTENT_DIR || process.cwd();
|
|
376
377
|
const packageRoot = process.env.WRITEDOCS_PACKAGE_ROOT || process.cwd();
|
|
378
|
+
// `writedocs dev`, with an OpenAPI spec that stopped parsing: the error
|
|
379
|
+
// instead of the page, until it parses again (lib/openapi-dev-status.js).
|
|
380
|
+
throwIfOpenApiProblem(contentDir);
|
|
377
381
|
const config = loadDocsConfig(contentDir);
|
|
378
382
|
// Once per build, like the lookup tables further down.
|
|
379
383
|
const sections = oncePerBuild("slug:sections", () => resolveSections(config.navigation));
|
|
@@ -1,64 +1,63 @@
|
|
|
1
|
-
import { getCollection, type CollectionEntry } from 'astro:content';
|
|
2
|
-
import fs from 'node:fs';
|
|
3
|
-
import path from 'node:path';
|
|
4
|
-
import type { APIRoute } from 'astro';
|
|
5
|
-
import { loadDocsConfig, normalizeEntryId, findAllPages, mergeSeo } from '../../lib/config';
|
|
6
|
-
import { writedocsTempDir } from '../../lib/writedocs-temp-dir.js';
|
|
7
|
-
import { ogImagePng
|
|
8
|
-
import {
|
|
9
|
-
|
|
10
|
-
// /og/<page>.png - the picture a link to a page shows when it's shared, for
|
|
11
|
-
// every page with no `seo.ogImage` of its own: the site's logo, the page's
|
|
12
|
-
// title and description, the site's primary color (lib/og-image.js).
|
|
13
|
-
//
|
|
14
|
-
//
|
|
15
|
-
//
|
|
16
|
-
//
|
|
17
|
-
//
|
|
18
|
-
//
|
|
19
|
-
//
|
|
20
|
-
|
|
21
|
-
|
|
22
|
-
|
|
23
|
-
|
|
24
|
-
|
|
25
|
-
|
|
26
|
-
|
|
27
|
-
|
|
28
|
-
|
|
29
|
-
|
|
30
|
-
|
|
31
|
-
|
|
32
|
-
const
|
|
33
|
-
|
|
34
|
-
|
|
35
|
-
|
|
36
|
-
|
|
37
|
-
const
|
|
38
|
-
|
|
39
|
-
|
|
40
|
-
|
|
41
|
-
.map((entry) => ({
|
|
42
|
-
|
|
43
|
-
|
|
44
|
-
|
|
45
|
-
|
|
46
|
-
|
|
47
|
-
|
|
48
|
-
|
|
49
|
-
|
|
50
|
-
|
|
51
|
-
|
|
52
|
-
|
|
53
|
-
|
|
54
|
-
|
|
55
|
-
|
|
56
|
-
|
|
57
|
-
|
|
58
|
-
|
|
59
|
-
|
|
60
|
-
|
|
61
|
-
|
|
62
|
-
|
|
63
|
-
|
|
64
|
-
};
|
|
1
|
+
import { getCollection, type CollectionEntry } from 'astro:content';
|
|
2
|
+
import fs from 'node:fs';
|
|
3
|
+
import path from 'node:path';
|
|
4
|
+
import type { APIRoute } from 'astro';
|
|
5
|
+
import { loadDocsConfig, normalizeEntryId, findAllPages, mergeSeo } from '../../lib/config';
|
|
6
|
+
import { writedocsTempDir } from '../../lib/writedocs-temp-dir.js';
|
|
7
|
+
import { ogImagePng } from '../../lib/og-image.js';
|
|
8
|
+
import { ogCardSet, ogCardOptions } from '../../lib/og-cards.js';
|
|
9
|
+
|
|
10
|
+
// /og/<page>.png - the picture a link to a page shows when it's shared, for
|
|
11
|
+
// every page with no `seo.ogImage` of its own: the site's logo, the page's
|
|
12
|
+
// title and description, the site's primary color (lib/og-image.js).
|
|
13
|
+
// Which pages, and what's on each card, is lib/og-cards.js's - the build's
|
|
14
|
+
// own step draws from the same list. [...slug].astro points the page's
|
|
15
|
+
// og:image here under the same condition (wantsGeneratedCard()), so a card is
|
|
16
|
+
// only built for a page that uses it - a site with `seo.ogImage` in
|
|
17
|
+
// writedocs.json builds none at all, and neither does one with
|
|
18
|
+
// `"seo": { "generatedOgImage": false }`.
|
|
19
|
+
//
|
|
20
|
+
// In `writedocs dev`, a static route like [...slug].md.ts next to it, built
|
|
21
|
+
// on request. In `writedocs build` it renders nothing: build.js names a file
|
|
22
|
+
// in WRITEDOCS_OG_CARDS_FILE, the list goes there, and the build draws every
|
|
23
|
+
// card after Astro, in parallel (src/cli/og-images.js) - inside Astro they
|
|
24
|
+
// were drawn one at a time, on one core.
|
|
25
|
+
|
|
26
|
+
type DocsEntry = CollectionEntry<'pages'> | CollectionEntry<'generatedDocs'>;
|
|
27
|
+
|
|
28
|
+
export async function getStaticPaths() {
|
|
29
|
+
const contentDir = process.env.WRITEDOCS_CONTENT_DIR || process.cwd();
|
|
30
|
+
const config = loadDocsConfig(contentDir);
|
|
31
|
+
const hasGeneratedDocs = fs.existsSync(path.join(writedocsTempDir(contentDir), 'generated-docs'));
|
|
32
|
+
const hasPages = findAllPages(contentDir).length > 0;
|
|
33
|
+
const [pagesEntries, generatedDocsEntries] = await Promise.all([
|
|
34
|
+
hasPages ? getCollection('pages') : Promise.resolve([]),
|
|
35
|
+
hasGeneratedDocs ? getCollection('generatedDocs') : Promise.resolve([]),
|
|
36
|
+
]);
|
|
37
|
+
const entries: DocsEntry[] = [...pagesEntries, ...generatedDocsEntries];
|
|
38
|
+
|
|
39
|
+
const set = ogCardSet(
|
|
40
|
+
config,
|
|
41
|
+
entries.map((entry) => ({ id: normalizeEntryId(entry.id), data: entry.data, seo: mergeSeo(config.seo, entry.data.seo) })),
|
|
42
|
+
contentDir
|
|
43
|
+
);
|
|
44
|
+
const listFile = process.env.WRITEDOCS_OG_CARDS_FILE;
|
|
45
|
+
if (listFile) {
|
|
46
|
+
fs.writeFileSync(listFile, JSON.stringify(set));
|
|
47
|
+
return [];
|
|
48
|
+
}
|
|
49
|
+
return set.cards.map((card) => ({ params: { slug: card.slug }, props: ogCardOptions(set, card) }));
|
|
50
|
+
}
|
|
51
|
+
|
|
52
|
+
interface Props {
|
|
53
|
+
title: string;
|
|
54
|
+
description?: string;
|
|
55
|
+
siteName: string;
|
|
56
|
+
primary: string;
|
|
57
|
+
logo: { src: string; width: number; height: number } | null;
|
|
58
|
+
}
|
|
59
|
+
|
|
60
|
+
export const GET: APIRoute = async ({ props }) => {
|
|
61
|
+
const png = await ogImagePng(props as Props);
|
|
62
|
+
return new Response(png, { headers: { 'Content-Type': 'image/png' } });
|
|
63
|
+
};
|
|
@@ -1,55 +1,80 @@
|
|
|
1
|
-
// The <= 860px hamburger menu (MobileMenu.astro's own toggle button +
|
|
2
|
-
// overlay panel). The accordion rows inside the panel need no JS of their
|
|
3
|
-
// own - they're plain <details name="wd-mobile-accordion"> elements, which
|
|
4
|
-
// get native click/keyboard toggling and (in browsers supporting the
|
|
5
|
-
// `name` attribute's exclusive-accordion behavior) mutual exclusion for
|
|
6
|
-
// free, same as NavTree.astro's own collapsible groups already rely on
|
|
7
|
-
// <details> for. This function only owns the panel itself: open/close, the
|
|
8
|
-
// backdrop, Escape, and body scroll locking while it's open - same pattern
|
|
9
|
-
// initSearch() uses for its own modal.
|
|
10
|
-
|
|
11
|
-
|
|
12
|
-
|
|
13
|
-
|
|
14
|
-
|
|
15
|
-
|
|
16
|
-
|
|
17
|
-
|
|
18
|
-
|
|
19
|
-
|
|
20
|
-
|
|
21
|
-
|
|
22
|
-
|
|
23
|
-
|
|
24
|
-
|
|
25
|
-
|
|
26
|
-
|
|
27
|
-
|
|
28
|
-
|
|
29
|
-
|
|
30
|
-
|
|
31
|
-
|
|
32
|
-
|
|
33
|
-
|
|
34
|
-
|
|
35
|
-
|
|
36
|
-
|
|
37
|
-
|
|
38
|
-
|
|
39
|
-
|
|
40
|
-
|
|
41
|
-
|
|
42
|
-
|
|
43
|
-
|
|
44
|
-
|
|
45
|
-
|
|
46
|
-
|
|
47
|
-
|
|
48
|
-
|
|
49
|
-
|
|
50
|
-
|
|
51
|
-
|
|
52
|
-
|
|
53
|
-
|
|
54
|
-
}
|
|
55
|
-
|
|
1
|
+
// The <= 860px hamburger menu (MobileMenu.astro's own toggle button +
|
|
2
|
+
// overlay panel). The accordion rows inside the panel need no JS of their
|
|
3
|
+
// own - they're plain <details name="wd-mobile-accordion"> elements, which
|
|
4
|
+
// get native click/keyboard toggling and (in browsers supporting the
|
|
5
|
+
// `name` attribute's exclusive-accordion behavior) mutual exclusion for
|
|
6
|
+
// free, same as NavTree.astro's own collapsible groups already rely on
|
|
7
|
+
// <details> for. This function only owns the panel itself: open/close, the
|
|
8
|
+
// backdrop, Escape, and body scroll locking while it's open - same pattern
|
|
9
|
+
// initSearch() uses for its own modal.
|
|
10
|
+
//
|
|
11
|
+
// And the sidebar inside it: the page has one, in BaseLayout's
|
|
12
|
+
// `.wd-sidebar-col` (hidden at this width). Opening the menu moves it into
|
|
13
|
+
// the panel's `.wd-mobile-menu-sidebar`, where it stays while the menu
|
|
14
|
+
// closes (the panel slides out with it) and opens again; widening the window
|
|
15
|
+
// past 860px moves it back. Moved rather than drawn there by CSS: the panel
|
|
16
|
+
// scrolls its switchers and the sidebar as one list, under its own header,
|
|
17
|
+
// and a second box laid over it couldn't. Moving is also what keeps the
|
|
18
|
+
// styles exactly those of the copy the panel used to get (MobileMenu.astro):
|
|
19
|
+
// the same nodes under the same containers. Without JavaScript the menu
|
|
20
|
+
// doesn't open, so nothing is lost there. ClientRouter replaces the whole
|
|
21
|
+
// <body> on every navigation, so each page starts with the sidebar in its
|
|
22
|
+
// column again.
|
|
23
|
+
export function initMobileMenu(root: ParentNode) {
|
|
24
|
+
const trigger = root.querySelector<HTMLButtonElement>('[data-mobile-menu-trigger]');
|
|
25
|
+
const menu = root.querySelector<HTMLElement>('#wd-mobile-menu');
|
|
26
|
+
const backdrop = menu?.querySelector<HTMLElement>('[data-mobile-menu-backdrop]');
|
|
27
|
+
// The panel's own close button (.wd-mobile-menu-header, next to its
|
|
28
|
+
// replica of the topbar brand) - the real hamburger-turned-X trigger up
|
|
29
|
+
// in the topbar is covered by the panel itself once open, so this is the
|
|
30
|
+
// only reachable way to close via click besides the backdrop.
|
|
31
|
+
const closeBtn = menu?.querySelector<HTMLButtonElement>('[data-mobile-menu-close]');
|
|
32
|
+
if (!trigger || !menu || !backdrop || trigger.dataset.wdInit) return;
|
|
33
|
+
trigger.dataset.wdInit = 'true';
|
|
34
|
+
const column = root.querySelector<HTMLElement>('.wd-sidebar-col');
|
|
35
|
+
const drawerSidebar = menu.querySelector<HTMLElement>('.wd-mobile-menu-sidebar');
|
|
36
|
+
const narrow = window.matchMedia('(max-width: 860px)');
|
|
37
|
+
// Every child, not just .wd-sidebar: whatever the page put in the sidebar slot.
|
|
38
|
+
const moveSidebar = (from: HTMLElement | null, to: HTMLElement | null) => {
|
|
39
|
+
if (from && to) to.append(...from.childNodes);
|
|
40
|
+
};
|
|
41
|
+
|
|
42
|
+
function open() {
|
|
43
|
+
// Only at the width where the column is hidden.
|
|
44
|
+
if (narrow.matches) moveSidebar(column, drawerSidebar);
|
|
45
|
+
menu!.classList.add('open');
|
|
46
|
+
// `inert` (not just visibility/pointer-events, which only affect
|
|
47
|
+
// vision/mouse) is what keeps the closed panel's links out of Tab
|
|
48
|
+
// order and off a screen reader's radar - removed while open so its
|
|
49
|
+
// content becomes reachable again.
|
|
50
|
+
menu!.removeAttribute('inert');
|
|
51
|
+
trigger!.classList.add('open');
|
|
52
|
+
trigger!.setAttribute('aria-expanded', 'true');
|
|
53
|
+
document.body.style.overflow = 'hidden';
|
|
54
|
+
}
|
|
55
|
+
function close() {
|
|
56
|
+
menu!.classList.remove('open');
|
|
57
|
+
menu!.setAttribute('inert', '');
|
|
58
|
+
trigger!.classList.remove('open');
|
|
59
|
+
trigger!.setAttribute('aria-expanded', 'false');
|
|
60
|
+
document.body.style.overflow = '';
|
|
61
|
+
}
|
|
62
|
+
|
|
63
|
+
trigger.addEventListener('click', () => (menu.classList.contains('open') ? close() : open()));
|
|
64
|
+
backdrop.addEventListener('click', close);
|
|
65
|
+
closeBtn?.addEventListener('click', close);
|
|
66
|
+
document.addEventListener('keydown', (e) => {
|
|
67
|
+
if (e.key === 'Escape' && menu.classList.contains('open')) close();
|
|
68
|
+
});
|
|
69
|
+
// Resizing past the breakpoint while open (rotating a tablet, or
|
|
70
|
+
// widening a desktop browser window) - the panel/backdrop are already
|
|
71
|
+
// hard-hidden above 860px via CSS regardless, but without this the body
|
|
72
|
+
// scroll lock and the trigger's own "open" state would stick around with
|
|
73
|
+
// no visible panel left to close them.
|
|
74
|
+
// Wide again, the sidebar goes back to its column whether or not the menu
|
|
75
|
+
// was still open.
|
|
76
|
+
window.matchMedia('(min-width: 861px)').addEventListener('change', (e) => {
|
|
77
|
+
if (e.matches && menu.classList.contains('open')) close();
|
|
78
|
+
if (e.matches) moveSidebar(drawerSidebar, column);
|
|
79
|
+
});
|
|
80
|
+
}
|
|
@@ -1,65 +1,61 @@
|
|
|
1
|
-
// ClientRouter swaps <body> (and everything in it) on every navigation -
|
|
2
|
-
// [...slug].astro re-renders Sidebar.astro/NavTree.astro fresh per page,
|
|
3
|
-
// since the active-link highlight and each collapsible group's open/closed
|
|
4
|
-
// state are computed server-side from the *new* URL (see NavTree.astro's
|
|
5
|
-
// own comment on `open = isActive || navTreeContainsSlug(...)`). That's
|
|
6
|
-
// exactly the behavior a reader wants for highlighting/auto-expanding the
|
|
7
|
-
// right branch - but it also means .wd-sidebar is a brand-new DOM node on
|
|
8
|
-
// every navigation, with its own independent scroll position (it's
|
|
9
|
-
// `overflow-y: auto`, not the window) starting back at 0, same as a full
|
|
10
|
-
// page reload would. For a page nested deep in a long nav tree, that reads
|
|
11
|
-
// as the sidebar "jumping back to the top" on every click - disorienting,
|
|
12
|
-
// since the reader loses their place in the tree they were navigating.
|
|
13
|
-
// This module carries the old sidebar's scroll offset across the swap and
|
|
14
|
-
// re-applies it to the new one, without touching anything about how the
|
|
15
|
-
// highlight/expand state itself is computed (that server-rendered-per-page
|
|
16
|
-
// behavior stays exactly as it is - only the scroll position is preserved).
|
|
17
|
-
//
|
|
18
|
-
// A module-scoped variable (not sessionStorage) is enough: this script's
|
|
19
|
-
// own module graph is loaded once and never re-evaluated by a ClientRouter
|
|
20
|
-
// swap (only <body>'s content is replaced), so the value naturally
|
|
21
|
-
// survives from one navigation to the next without needing to serialize it
|
|
22
|
-
// anywhere. It deliberately does NOT survive a real full-page reload
|
|
23
|
-
// (Cmd+R/F5) - resetting to the top on an actual reload is ordinary,
|
|
24
|
-
// expected browser behavior, not something this needs to fight.
|
|
25
|
-
let savedScrollTop: number | null = null;
|
|
26
|
-
|
|
27
|
-
/** The sidebar
|
|
28
|
-
*
|
|
29
|
-
*
|
|
30
|
-
*
|
|
31
|
-
*
|
|
32
|
-
*
|
|
33
|
-
|
|
34
|
-
|
|
35
|
-
|
|
36
|
-
|
|
37
|
-
|
|
38
|
-
|
|
39
|
-
|
|
40
|
-
|
|
41
|
-
|
|
42
|
-
|
|
43
|
-
|
|
44
|
-
|
|
45
|
-
|
|
46
|
-
|
|
47
|
-
|
|
48
|
-
|
|
49
|
-
|
|
50
|
-
|
|
51
|
-
|
|
52
|
-
|
|
53
|
-
|
|
54
|
-
|
|
55
|
-
*
|
|
56
|
-
|
|
57
|
-
|
|
58
|
-
|
|
59
|
-
|
|
60
|
-
|
|
61
|
-
|
|
62
|
-
const sidebar = visibleSidebar();
|
|
63
|
-
if (sidebar) sidebar.scrollTop = savedScrollTop;
|
|
64
|
-
savedScrollTop = null;
|
|
65
|
-
}
|
|
1
|
+
// ClientRouter swaps <body> (and everything in it) on every navigation -
|
|
2
|
+
// [...slug].astro re-renders Sidebar.astro/NavTree.astro fresh per page,
|
|
3
|
+
// since the active-link highlight and each collapsible group's open/closed
|
|
4
|
+
// state are computed server-side from the *new* URL (see NavTree.astro's
|
|
5
|
+
// own comment on `open = isActive || navTreeContainsSlug(...)`). That's
|
|
6
|
+
// exactly the behavior a reader wants for highlighting/auto-expanding the
|
|
7
|
+
// right branch - but it also means .wd-sidebar is a brand-new DOM node on
|
|
8
|
+
// every navigation, with its own independent scroll position (it's
|
|
9
|
+
// `overflow-y: auto`, not the window) starting back at 0, same as a full
|
|
10
|
+
// page reload would. For a page nested deep in a long nav tree, that reads
|
|
11
|
+
// as the sidebar "jumping back to the top" on every click - disorienting,
|
|
12
|
+
// since the reader loses their place in the tree they were navigating.
|
|
13
|
+
// This module carries the old sidebar's scroll offset across the swap and
|
|
14
|
+
// re-applies it to the new one, without touching anything about how the
|
|
15
|
+
// highlight/expand state itself is computed (that server-rendered-per-page
|
|
16
|
+
// behavior stays exactly as it is - only the scroll position is preserved).
|
|
17
|
+
//
|
|
18
|
+
// A module-scoped variable (not sessionStorage) is enough: this script's
|
|
19
|
+
// own module graph is loaded once and never re-evaluated by a ClientRouter
|
|
20
|
+
// swap (only <body>'s content is replaced), so the value naturally
|
|
21
|
+
// survives from one navigation to the next without needing to serialize it
|
|
22
|
+
// anywhere. It deliberately does NOT survive a real full-page reload
|
|
23
|
+
// (Cmd+R/F5) - resetting to the top on an actual reload is ordinary,
|
|
24
|
+
// expected browser behavior, not something this needs to fight.
|
|
25
|
+
let savedScrollTop: number | null = null;
|
|
26
|
+
|
|
27
|
+
/** The page's one `.wd-sidebar` - in `.wd-sidebar-col` on desktop, or
|
|
28
|
+
* moved into MobileMenu.astro's drawer once that has been opened at phone
|
|
29
|
+
* width (src/scripts/mobile-menu.ts) - when it has a real layout box: in
|
|
30
|
+
* the column at phone width it's hidden, and there's no scroll position to
|
|
31
|
+
* carry. Returns null then, and on a page with no sidebar at all (`mode:
|
|
32
|
+
* custom`/`blank`, see BaseLayout.astro). */
|
|
33
|
+
function visibleSidebar(): HTMLElement | null {
|
|
34
|
+
const candidates = document.querySelectorAll<HTMLElement>('.wd-sidebar');
|
|
35
|
+
for (const el of candidates) {
|
|
36
|
+
if (el.offsetWidth > 0 || el.offsetHeight > 0) return el;
|
|
37
|
+
}
|
|
38
|
+
return null;
|
|
39
|
+
}
|
|
40
|
+
|
|
41
|
+
/** Reads the current scroll offset right before ClientRouter tears down
|
|
42
|
+
* the old page's DOM - `astro:before-swap` is the last moment the old
|
|
43
|
+
* `.wd-sidebar` is still attached and its `scrollTop` still means
|
|
44
|
+
* anything. */
|
|
45
|
+
export function saveSidebarScroll() {
|
|
46
|
+
const sidebar = visibleSidebar();
|
|
47
|
+
savedScrollTop = sidebar ? sidebar.scrollTop : null;
|
|
48
|
+
}
|
|
49
|
+
|
|
50
|
+
/** Re-applies the saved offset onto the new page's own `.wd-sidebar`.
|
|
51
|
+
* Bound to `astro:after-swap` (fires synchronously right after the swap,
|
|
52
|
+
* before the browser's next paint - see BaseLayout.astro's own
|
|
53
|
+
* `wdApplyStoredPreferences` for the identical timing rationale) rather
|
|
54
|
+
* than the later `astro:page-load`, so the sidebar never visibly flashes
|
|
55
|
+
* at the top before jumping to the preserved position. */
|
|
56
|
+
export function restoreSidebarScroll() {
|
|
57
|
+
if (savedScrollTop === null) return;
|
|
58
|
+
const sidebar = visibleSidebar();
|
|
59
|
+
if (sidebar) sidebar.scrollTop = savedScrollTop;
|
|
60
|
+
savedScrollTop = null;
|
|
61
|
+
}
|