@writedocs/generator 0.10.1 → 0.10.3

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.
@@ -0,0 +1,71 @@
1
+ // An item's own page: a tab, version, language, dropdown or product with a
2
+ // `page` opens that page when it's chosen, in place of its first page - an
3
+ // overview of what's in it.
4
+ //
5
+ // - The page is also in a sidebar: it's shown there, like any page.
6
+ // - It isn't: it's shown inside the item. The item is the current one on its
7
+ // level, the level under it (when the item holds tabs, products, ...) lists
8
+ // its options with none chosen, and the sidebar is the item's own `pages`,
9
+ // when it has them (landingSelectors() in lib/config.ts, landingRoutes in
10
+ // src/pages/[...slug].astro).
11
+ //
12
+ // Plain JavaScript, so scripts/item-pages.test.js can import it.
13
+
14
+ /** Each kind of list an item can hold, with the field naming its items. */
15
+ export const CHILD_KINDS = [
16
+ ['tabs', 'tab'],
17
+ ['versions', 'version'],
18
+ ['languages', 'language'],
19
+ ['dropdowns', 'dropdown'],
20
+ ['products', 'product'],
21
+ ];
22
+
23
+ /** The item's own page id, or null - an `href` item is a link, with none. */
24
+ export function itemPage(item) {
25
+ if (!item || typeof item !== 'object' || 'href' in item) return null;
26
+ return typeof item.page === 'string' ? item.page : null;
27
+ }
28
+
29
+ /** The list of items an item holds - `{ kind, items }` - or null when it
30
+ * holds `pages` (a sidebar) or is a link. */
31
+ export function childLevel(item) {
32
+ if (!item || typeof item !== 'object') return null;
33
+ for (const [key, kind] of CHILD_KINDS) {
34
+ if (Array.isArray(item[key])) return { kind, items: item[key] };
35
+ }
36
+ return null;
37
+ }
38
+
39
+ /** The name an item shows: a version's or language's `label` when it has one. */
40
+ export function itemLabel(item) {
41
+ if ('tab' in item) return item.tab;
42
+ if ('version' in item) return item.label ?? item.version;
43
+ if ('language' in item) return item.label ?? item.language;
44
+ if ('dropdown' in item) return item.dropdown;
45
+ return item.product;
46
+ }
47
+
48
+ /** Every item with a page of its own, in navigation order:
49
+ * `{ slug, path, pages, item }`, where `path` is the levels down to the item
50
+ * (the same `{ kind, items, index }` segments resolveSections() builds),
51
+ * and `pages` the item's own sidebar - empty when it holds a list instead.
52
+ * When two items name the same page, the first one keeps it. */
53
+ export function resolveLandings(navigation) {
54
+ const out = [];
55
+ const seen = new Set();
56
+ const walk = (node, path) => {
57
+ const level = childLevel(node);
58
+ if (!level) return;
59
+ level.items.forEach((item, index) => {
60
+ const itemPath = [...path, { kind: level.kind, items: level.items, index }];
61
+ const slug = itemPage(item);
62
+ if (slug !== null && !seen.has(slug)) {
63
+ seen.add(slug);
64
+ out.push({ slug, path: itemPath, pages: Array.isArray(item.pages) ? item.pages : [], item });
65
+ }
66
+ walk(item, itemPath);
67
+ });
68
+ };
69
+ if (navigation && !Array.isArray(navigation)) walk(navigation, []);
70
+ return out;
71
+ }
@@ -12,7 +12,7 @@ const CHILDREN = {
12
12
  tabs: 'Tabs inside this one.',
13
13
  versions: 'Versions inside this one - a version picker in the sidebar.',
14
14
  languages: 'Languages inside this one - a language picker.',
15
- dropdowns: 'Dropdowns inside this one - a menu of sections in the sidebar.',
15
+ dropdowns: 'Dropdowns inside this one. Inside a tab they are its menu, and inside one of those a flyout beside its entry - two levels at most; elsewhere, a switcher.',
16
16
  products: 'Products inside this one - a product picker.',
17
17
  href: 'Makes this a link to another address instead of a section with pages of its own.',
18
18
  };
@@ -46,6 +46,7 @@ const CONTAINERS = {
46
46
  const HIDDEN = {
47
47
  hidden: 'Reachable only by its address: no tab, switcher or menu lists it, and inside it this level isn\'t shown. Its pages search only among themselves.',
48
48
  searchPublic: 'For a hidden item: its search also finds the site\'s public pages.',
49
+ page: 'A page of its own - an overview - that choosing this item opens, in place of its first page. Shown inside the item; in a sidebar too, it opens there.',
49
50
  };
50
51
 
51
52
  const containerEntries = Object.entries(CONTAINERS).flatMap(([type, fields]) => [
package/src/lib/llms.js CHANGED
@@ -73,7 +73,10 @@ export function buildLlmsTree(navigation, pageFor, unlisted = []) {
73
73
  .filter((child) => child && typeof child === 'object' && !('href' in child))
74
74
  .map((child) => {
75
75
  const label = labelKey === 'version' || labelKey === 'language' ? child.label ?? child[labelKey] : child[labelKey];
76
- return { label: String(label), ...fromContainer(child) };
76
+ // An item's own `page` (an overview) comes first, like a group's.
77
+ const own = typeof child.page === 'string' ? page(child.page) : null;
78
+ const inner = fromContainer(child);
79
+ return { label: String(label), ...inner, items: own ? [own, ...inner.items] : inner.items };
77
80
  })
78
81
  .filter(prune);
79
82
  return { items: [], sections };
@@ -14,6 +14,7 @@ import {
14
14
  resolveSiteUrl,
15
15
  fileIdForEntry,
16
16
  resolveSections,
17
+ resolveLandings,
17
18
  flattenNav,
18
19
  } from './config';
19
20
  import { pageMarkdown } from './openapi-markdown';
@@ -53,9 +54,13 @@ export async function mcpIndex(): Promise<McpIndex> {
53
54
 
54
55
  // The version and language each page sits under, from its section's path
55
56
  // through the navigation (tabs > versions > languages > ...).
57
+ // An item's own page that no sidebar lists sits under that item.
56
58
  const sections = resolveSections(config.navigation);
59
+ const landings = resolveLandings(config.navigation);
57
60
  const placeOf = (fileId: string) => {
58
- const section = sections.find((s) => flattenNav(s.pages).some((e) => e.slug === fileId));
61
+ const section =
62
+ sections.find((s) => flattenNav(s.pages).some((e) => e.slug === fileId)) ??
63
+ landings.find((landing) => landing.slug === fileId);
59
64
  const place = { version: '', language: '' };
60
65
  for (const segment of section?.path ?? []) {
61
66
  const item = segment.items[segment.index] as { version?: string; language?: string };
@@ -3,6 +3,8 @@
3
3
  //
4
4
  // 'tabs' a row of tabs in the top bar (a second row for tabs inside tabs)
5
5
  // 'tab-menu' the menu of the tab it sits in (dropdowns directly inside a tab)
6
+ // 'tab-submenu' a flyout beside its entry in that menu (dropdowns inside a
7
+ // 'tab-menu' dropdown - SelectorOption.submenu in lib/config.ts)
6
8
  // 'sidebar' the top of the sidebar: products inside a tab or a dropdown,
7
9
  // like Mintlify's - they pick what the sidebar shows
8
10
  // 'topbar' a switcher next to the site name (everything else)
@@ -14,14 +16,20 @@
14
16
  // either way.
15
17
 
16
18
  export function selectorPlacements(selectors, { sidebar = true } = {}) {
17
- return selectors.map((sel, i) => {
18
- if (sel.hidden) return 'none';
19
+ const placements = [];
20
+ selectors.forEach((sel, i) => {
19
21
  const parent = selectors[i - 1]?.kind;
20
- if (sel.kind === 'tab') return 'tabs';
21
- if (sel.kind === 'dropdown' && parent === 'tab') return 'tab-menu';
22
- if (sel.kind === 'product' && (parent === 'tab' || parent === 'dropdown')) return sidebar ? 'sidebar' : 'topbar';
23
- return 'topbar';
22
+ const placement = (() => {
23
+ if (sel.hidden) return 'none';
24
+ if (sel.kind === 'tab') return 'tabs';
25
+ if (sel.kind === 'dropdown' && parent === 'tab') return 'tab-menu';
26
+ if (sel.kind === 'dropdown' && placements[i - 1] === 'tab-menu') return 'tab-submenu';
27
+ if (sel.kind === 'product' && (parent === 'tab' || parent === 'dropdown')) return sidebar ? 'sidebar' : 'topbar';
28
+ return 'topbar';
29
+ })();
30
+ placements.push(placement);
24
31
  });
32
+ return placements;
25
33
  }
26
34
 
27
35
  /** Whether a page gets the mobile menu (its button in the top bar, and the
@@ -31,3 +39,11 @@ export function selectorPlacements(selectors, { sidebar = true } = {}) {
31
39
  export function hasMobileMenu({ sidebar, selectors = [], globalDropdowns = [] }) {
32
40
  return sidebar || selectors.some((sel) => !sel.hidden) || globalDropdowns.length > 0;
33
41
  }
42
+
43
+ /** What a switcher's button shows: the chosen option - or, on the level
44
+ * under an item whose own page the reader is on, where none is chosen, the
45
+ * selector's `placeholder` (the item's name - landingSelectors() in
46
+ * lib/config.ts). Falls back to the first option. */
47
+ export function currentOption(selector) {
48
+ return selector.options.find((option) => option.active) ?? selector.placeholder ?? selector.options[0];
49
+ }
@@ -19,6 +19,8 @@ import {
19
19
  contextMenuOptions,
20
20
  resolveSiteUrl,
21
21
  findAllPages,
22
+ resolveLandings,
23
+ landingSelectors,
22
24
  } from "../lib/config";
23
25
  import { writedocsTempDir } from "../lib/writedocs-temp-dir.js";
24
26
  import { parseOpenApiRef } from "../lib/openapi-ref.js";
@@ -72,6 +74,7 @@ import ApiReferencePanel from "../components/ApiReferencePanel.astro";
72
74
  import { searchScope, sectionTrail, ALL_SCOPES } from "../lib/search-scope.js";
73
75
  import { selectorPlacements } from "../lib/selector-placement.js";
74
76
  import { spaceOf } from "../lib/hidden-sections.js";
77
+ import { navigationPageOrder } from "../lib/pages.js";
75
78
  import { folderRedirects } from "../lib/folder-redirects.js";
76
79
 
77
80
  // A page is hand-written (the `pages` collection, sourced from anywhere
@@ -231,6 +234,36 @@ export async function getStaticPaths() {
231
234
  });
232
235
  });
233
236
 
237
+ // An item's own page (a tab's, a dropdown's, ... `page` - resolveLandings()
238
+ // in lib/config.ts) that no sidebar lists: shown inside its item. One the
239
+ // sidebar does list was routed above, in its sidebar. Its Next is the
240
+ // item's first sidebar page, if the item has a sidebar of its own.
241
+ const landings = resolveLandings(config.navigation);
242
+ const landingRoutes = landings.flatMap((landing, landingIndex) => {
243
+ if (claimedFileIds.has(landing.slug)) return [];
244
+ const entry = entryByFileId.get(landing.slug);
245
+ if (!entry) {
246
+ const last = landing.path[landing.path.length - 1];
247
+ const item = landing.item as Record<string, unknown>;
248
+ const name = (item.tab ?? item.version ?? item.language ?? item.dropdown ?? item.product) as string;
249
+ throw new Error(
250
+ `[writedocs] writedocs.json's ${last.kind} "${name}" names page "${landing.slug}" as its own page,` +
251
+ ` but no matching file was found`,
252
+ );
253
+ }
254
+ claimedFileIds.add(landing.slug);
255
+ const next =
256
+ flattenNav(landing.pages).find((e) => {
257
+ const data = entryByFileId.get(e.slug)?.data;
258
+ return Boolean(data) && !data!.hidden && !data!.url;
259
+ }) ?? null;
260
+ const urlSlug = normalizeEntryId(entry.id);
261
+ if (entry.data.url) {
262
+ return [{ params: { slug: urlSlug === "index" ? undefined : urlSlug }, props: { redirectTo: entry.data.url } }];
263
+ }
264
+ return [{ params: { slug: urlSlug === "index" ? undefined : urlSlug }, props: { entry, prev: null, next, landingIndex } }];
265
+ });
266
+
234
267
  // "Hidden" pages: any file the `pages`/`generatedDocs` collections
235
268
  // picked up that writedocs.json's navigation never references (see
236
269
  // claimedFileIds above) still gets a real route here - just with no
@@ -264,13 +297,24 @@ export async function getStaticPaths() {
264
297
  const slugOf = (route: { params: { slug?: string } }) => route.params.slug ?? "index";
265
298
  const inHiddenSection = sections.map((section) => spaceOf(section.path) !== null);
266
299
  const contentRoutes = pageRoutes.filter((route) => !("redirectTo" in route.props));
300
+ // An item's own page counts where the navigation names it: before the
301
+ // item's sidebar (navigationPageOrder()), so `/guides/` opens the Guides
302
+ // tab's own page rather than its first sidebar page.
303
+ type ContentRoute = { params: { slug?: string }; props: { entry?: DocsEntry; sectionIndex?: number; landingIndex?: number } };
304
+ const navOrder = new Map(navigationPageOrder(config.navigation).map((id, i) => [id, i]));
305
+ const orderOf = (route: ContentRoute) => navOrder.get(fileIdForEntry(contentDir, packageRoot, route.props.entry!)) ?? Infinity;
306
+ const inHiddenItem = (route: ContentRoute) =>
307
+ route.props.landingIndex !== undefined
308
+ ? spaceOf(landings[route.props.landingIndex].path) !== null
309
+ : inHiddenSection[route.props.sectionIndex!];
310
+ const navContent = [...contentRoutes, ...landingRoutes.filter((route) => !("redirectTo" in route.props))] as ContentRoute[];
267
311
  const folderTargets = [
268
- ...contentRoutes.filter((route) => !inHiddenSection[(route.props as { sectionIndex: number }).sectionIndex]).map(slugOf),
269
- ...contentRoutes.filter((route) => inHiddenSection[(route.props as { sectionIndex: number }).sectionIndex]).map(slugOf),
312
+ ...navContent.filter((route) => !inHiddenItem(route)).sort((a, b) => orderOf(a) - orderOf(b)).map(slugOf),
313
+ ...navContent.filter(inHiddenItem).sort((a, b) => orderOf(a) - orderOf(b)).map(slugOf),
270
314
  ...hiddenRoutes.map(slugOf),
271
315
  ];
272
316
  const takenAddresses = new Set([
273
- ...[...pageRoutes, ...hiddenRoutes].map(slugOf),
317
+ ...[...pageRoutes, ...landingRoutes, ...hiddenRoutes].map(slugOf),
274
318
  ...(config.redirects ?? []).map((r) => r.source.replace(/^\/+|\/+$/g, "")),
275
319
  ]);
276
320
  const folderRoutes = [...folderRedirects(folderTargets, takenAddresses)].map(([folder, target]) => ({
@@ -278,7 +322,7 @@ export async function getStaticPaths() {
278
322
  props: { redirectTo: `/${target}/`, temporary: true },
279
323
  }));
280
324
 
281
- return [...rootRedirect, ...pageRoutes, ...hiddenRoutes, ...folderRoutes];
325
+ return [...rootRedirect, ...pageRoutes, ...landingRoutes, ...hiddenRoutes, ...folderRoutes];
282
326
  }
283
327
 
284
328
  interface Props {
@@ -296,6 +340,9 @@ interface Props {
296
340
  // section's sidebar contents, which would misleadingly suggest the page
297
341
  // belongs there.
298
342
  isHidden?: boolean;
343
+ // Set by landingRoutes in getStaticPaths above - an item's own page that
344
+ // no sidebar lists, shown inside that item (index into resolveLandings()).
345
+ landingIndex?: number;
299
346
  }
300
347
 
301
348
  const rawProps = Astro.props as Props;
@@ -316,6 +363,7 @@ const {
316
363
  next = null,
317
364
  sectionIndex = 0,
318
365
  isHidden = false,
366
+ landingIndex,
319
367
  } = rawProps as Required<Props>;
320
368
 
321
369
  const contentDir = process.env.WRITEDOCS_CONTENT_DIR || process.cwd();
@@ -327,7 +375,10 @@ const sections = resolveSections(config.navigation);
327
375
  // getStaticPaths above) on a site whose writedocs.json has no navigation
328
376
  // sections at all, which previously could never produce a route to
329
377
  // render in the first place.
330
- const activeSection = sections[sectionIndex] ?? { pages: [], path: [] };
378
+ // An item's own page shown inside its item (landingRoutes above): the item's
379
+ // path, and its own sidebar if it has one.
380
+ const landing = landingIndex === undefined ? undefined : resolveLandings(config.navigation)[landingIndex];
381
+ const activeSection = landing ? { pages: landing.pages, path: landing.path } : sections[sectionIndex] ?? { pages: [], path: [] };
331
382
 
332
383
  const { Content, headings } = await render(entry);
333
384
  const tocHeadings = headings.filter((h) => h.depth === 2 || h.depth === 3);
@@ -401,7 +452,8 @@ const activePagePosition = flattenNav(activeSection.pages).findIndex((e) => e.sl
401
452
  // versions, languages, products, or a dropdown nested partway down),
402
453
  // plus the always-visible global dropdown list - see BaseLayout.astro
403
454
  // for how each renders.
404
- const selectors = buildSelectors(activeSection.path, hrefForSlug, activePagePosition);
455
+ // An item's own page also gets the level under the item, with nothing chosen.
456
+ const selectors = landing ? landingSelectors(landing, hrefForSlug) : buildSelectors(activeSection.path, hrefForSlug, activePagePosition);
405
457
  // <html lang>: the `language` of the navigation level this page sits under,
406
458
  // if any. A hidden page has no level of its own (activeSection is only a
407
459
  // fallback for its chrome), so it keeps the default.
@@ -445,7 +497,13 @@ const currentPath = hrefForSlug(currentFileId);
445
497
  // the sidebar (and ToC) while keeping the topbar and normal article
446
498
  // styling. Only a *default*: a hidden page's own frontmatter mode, if
447
499
  // it set one explicitly, still wins.
448
- const pageMode = isHidden && entry.data.mode === "default" ? "frame" : entry.data.mode;
500
+ // An item's own page with nothing for a sidebar - the item holds tabs, or
501
+ // versions, ... that switch elsewhere - is laid out the same way.
502
+ const landingWithoutSidebar =
503
+ landing !== undefined &&
504
+ flattenNav(landing.pages).length === 0 &&
505
+ !selectorPlacements(selectors, { sidebar: true }).includes("sidebar");
506
+ const pageMode = (isHidden || landingWithoutSidebar) && entry.data.mode === "default" ? "frame" : entry.data.mode;
449
507
  const showSidebar = pageMode === "default" || pageMode === "wide";
450
508
  // Products inside a tab or dropdown switch at the top of the sidebar, not in
451
509
  // the top bar (lib/selector-placement.js - TopBar.astro applies the same rule).
@@ -15,14 +15,49 @@
15
15
  // move between its options (Home/End jump to the ends); Escape closes it
16
16
  // and puts focus back on its button; tabbing out of it closes it.
17
17
  //
18
+ // A tab menu's entry can hold a flyout (`.wd-submenu`, TopBar.astro): it opens
19
+ // on hover, on a click on its arrow - or on the entry itself, when the entry
20
+ // has no page to open - and from the keyboard with Right. In the flyout,
21
+ // Down/Up move between its links, and Left or Escape close it, back on its
22
+ // entry.
23
+ //
18
24
  // The document-level listeners are bound once per page load, and act on
19
25
  // whichever dropdowns are open at the time - so they keep working for the
20
26
  // ones a client-side navigation brings in.
21
27
  let globalListenersBound = false;
22
28
 
23
29
  const triggerOf = (dropdown: Element) => dropdown.querySelector<HTMLElement>('.wd-dropdown-trigger');
30
+ // The list's own options - not a flyout's links, and not a flyout's arrow
31
+ // button (Right opens the flyout from its entry instead).
24
32
  const optionsOf = (dropdown: Element) =>
25
- Array.from(dropdown.querySelectorAll<HTMLElement>('.wd-dropdown-menu a[href], .wd-dropdown-menu button'));
33
+ Array.from(dropdown.querySelectorAll<HTMLElement>('.wd-dropdown-menu a[href], .wd-dropdown-menu button')).filter(
34
+ (el) => !el.closest('.wd-submenu-panel') && !el.classList.contains('wd-submenu-arrow')
35
+ );
36
+ const flyoutLinksOf = (submenu: Element) =>
37
+ Array.from(submenu.querySelectorAll<HTMLElement>('.wd-submenu-panel a[href]'));
38
+ const entryOf = (submenu: Element) => submenu.querySelector<HTMLElement>('.wd-submenu-entry');
39
+
40
+ function setSubmenu(submenu: Element, isOpen: boolean) {
41
+ submenu.classList.toggle('open', isOpen);
42
+ submenu.querySelectorAll('.wd-submenu-toggle').forEach((toggle) => toggle.setAttribute('aria-expanded', String(isOpen)));
43
+ }
44
+
45
+ function closeSubmenus(dropdown: Element, except?: Element) {
46
+ dropdown.querySelectorAll('.wd-submenu.open').forEach((submenu) => {
47
+ if (submenu !== except) setSubmenu(submenu, false);
48
+ });
49
+ }
50
+
51
+ /** Moves focus within `options` for an arrow/Home/End key. */
52
+ function moveFocus(options: HTMLElement[], key: string) {
53
+ const at = options.indexOf(document.activeElement as HTMLElement);
54
+ let next: number;
55
+ if (key === 'Home') next = 0;
56
+ else if (key === 'End') next = options.length - 1;
57
+ else if (at === -1) next = key === 'ArrowUp' ? options.length - 1 : 0;
58
+ else next = Math.min(Math.max(at + (key === 'ArrowDown' ? 1 : -1), 0), options.length - 1);
59
+ options[next]?.focus();
60
+ }
26
61
 
27
62
  function open(dropdown: Element) {
28
63
  closeAll(dropdown);
@@ -31,6 +66,7 @@ function open(dropdown: Element) {
31
66
  }
32
67
 
33
68
  function close(dropdown: Element) {
69
+ closeSubmenus(dropdown);
34
70
  dropdown.classList.remove('open');
35
71
  triggerOf(dropdown)?.setAttribute('aria-expanded', 'false');
36
72
  // Focus on an option that just got hidden would drop to the top of the
@@ -57,27 +93,68 @@ export function initDropdowns(root: ParentNode) {
57
93
  else open(dropdown);
58
94
  });
59
95
 
96
+ // Flyouts: a click on an entry's toggle opens or closes its flyout and
97
+ // keeps the menu open; pointing at another entry closes the others.
98
+ dropdown.querySelectorAll<HTMLElement>('.wd-submenu').forEach((submenu) => {
99
+ submenu.querySelectorAll<HTMLElement>('.wd-submenu-toggle').forEach((toggle) => {
100
+ toggle.addEventListener('click', (e) => {
101
+ e.stopPropagation();
102
+ const isOpen = !submenu.classList.contains('open');
103
+ closeSubmenus(dropdown, submenu);
104
+ setSubmenu(submenu, isOpen);
105
+ });
106
+ });
107
+ });
108
+ dropdown.querySelectorAll<HTMLElement>('.wd-dropdown-menu-panel > a, .wd-dropdown-menu-panel > .wd-submenu').forEach((entry) => {
109
+ entry.addEventListener('pointerenter', () => closeSubmenus(dropdown, entry));
110
+ });
111
+
60
112
  dropdown.addEventListener('keydown', (e) => {
113
+ const target = e.target as HTMLElement;
114
+ const submenu = target.closest('.wd-submenu');
115
+ // Inside a flyout.
116
+ if (submenu && target.closest('.wd-submenu-panel')) {
117
+ if (['ArrowDown', 'ArrowUp', 'Home', 'End'].includes(e.key)) {
118
+ e.preventDefault();
119
+ moveFocus(flyoutLinksOf(submenu), e.key);
120
+ } else if (e.key === 'ArrowLeft' || e.key === 'Escape') {
121
+ e.preventDefault();
122
+ e.stopPropagation();
123
+ setSubmenu(submenu, false);
124
+ entryOf(submenu)?.focus();
125
+ }
126
+ return;
127
+ }
128
+ // On an entry with a flyout: Right opens it, on its first link.
129
+ if (submenu && e.key === 'ArrowRight') {
130
+ e.preventDefault();
131
+ closeSubmenus(dropdown, submenu);
132
+ setSubmenu(submenu, true);
133
+ flyoutLinksOf(submenu)[0]?.focus();
134
+ return;
135
+ }
61
136
  if (!['ArrowDown', 'ArrowUp', 'Home', 'End'].includes(e.key)) return;
62
137
  const options = optionsOf(dropdown);
63
138
  if (options.length === 0) return;
64
139
  e.preventDefault();
65
140
  if (!dropdown.classList.contains('open')) open(dropdown);
66
- const at = options.indexOf(document.activeElement as HTMLElement);
67
- let next: number;
68
- if (e.key === 'Home') next = 0;
69
- else if (e.key === 'End') next = options.length - 1;
70
- else if (at === -1) next = e.key === 'ArrowUp' ? options.length - 1 : 0;
71
- else next = Math.min(Math.max(at + (e.key === 'ArrowDown' ? 1 : -1), 0), options.length - 1);
72
- options[next].focus();
141
+ closeSubmenus(dropdown);
142
+ moveFocus(options, e.key);
73
143
  });
74
144
 
75
145
  // Focus moving somewhere outside the dropdown (Tab, Shift+Tab) closes
76
146
  // it. No `relatedTarget` means focus went nowhere in particular - a
77
147
  // click on the page, which the click-outside listener already handles.
148
+ // Focus moving to another entry closes the flyouts it isn't in.
149
+ dropdown.addEventListener('focusin', (e) => {
150
+ const into = (e.target as HTMLElement).closest('.wd-submenu') ?? undefined;
151
+ closeSubmenus(dropdown, into);
152
+ });
153
+
78
154
  dropdown.addEventListener('focusout', (e) => {
79
155
  const to = e.relatedTarget as Node | null;
80
156
  if (to && !dropdown.contains(to) && dropdown.classList.contains('open')) {
157
+ closeSubmenus(dropdown);
81
158
  dropdown.classList.remove('open');
82
159
  trigger.setAttribute('aria-expanded', 'false');
83
160
  }
@@ -162,6 +162,29 @@ function initStrip(strip: HTMLElement) {
162
162
  dropdown.addEventListener('focusin', place);
163
163
  });
164
164
 
165
+ // A flyout beside a menu entry (TopBar.astro) is cut off the same way past
166
+ // the row's right end - it opens to the left of its menu there, when that
167
+ // side has more room.
168
+ track.querySelectorAll<HTMLElement>('.wd-submenu').forEach((submenu) => {
169
+ const panel = submenu.querySelector<HTMLElement>('.wd-submenu-panel');
170
+ if (!panel) return;
171
+ const place = () => {
172
+ const shown = panel.style.display;
173
+ panel.style.visibility = 'hidden';
174
+ panel.style.display = 'block';
175
+ const width = panel.offsetWidth;
176
+ panel.style.display = shown;
177
+ panel.style.visibility = '';
178
+ const entry = submenu.getBoundingClientRect();
179
+ const row = viewport.getBoundingClientRect();
180
+ const roomRight = row.right - entry.right;
181
+ const roomLeft = entry.left - row.left;
182
+ submenu.classList.toggle('wd-submenu-left', roomRight < width && roomLeft > roomRight);
183
+ };
184
+ submenu.addEventListener('pointerenter', place);
185
+ submenu.addEventListener('focusin', place);
186
+ });
187
+
165
188
  // Tabs change width as fonts load, and the space changes with the window.
166
189
  const resized = () => (readerMoved ? apply() : settle());
167
190
  new ResizeObserver(resized).observe(viewport);