@nurvus/ui 0.1.0-alpha.15 → 0.1.0-alpha.16

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 (71) hide show
  1. package/README.md +11 -1
  2. package/dist/icons.svg +73 -0
  3. package/dist/index.js +1 -1
  4. package/dist/nurvus.css +13 -10
  5. package/dist/respawn.js +1 -1
  6. package/dist/types/breakpoints.d.ts +14 -0
  7. package/dist/types/components/FullPageModal/FullPageModal.d.ts +11 -2
  8. package/dist/types/components/Grid/Grid.d.ts +26 -0
  9. package/dist/types/components/Loader/Loader.d.ts +21 -0
  10. package/dist/types/components/Menu/Menu.d.ts +54 -19
  11. package/dist/types/components/Progress/Progress.d.ts +19 -5
  12. package/dist/types/components/Stack/Stack.d.ts +26 -0
  13. package/dist/types/dialog.d.ts +12 -0
  14. package/dist/types/icons.d.ts +28 -0
  15. package/dist/types/index.d.ts +9 -1
  16. package/dist/types/loader.d.ts +28 -0
  17. package/dist/types/logo.d.ts +5 -0
  18. package/dist/types/menu.d.ts +43 -14
  19. package/dist/types/progress.d.ts +11 -0
  20. package/dist/types/respawn/FullPageModal.d.ts +7 -1
  21. package/dist/types/respawn/Grid.d.ts +21 -0
  22. package/dist/types/respawn/Loader.d.ts +18 -0
  23. package/dist/types/respawn/Menu.d.ts +45 -15
  24. package/dist/types/respawn/Progress.d.ts +18 -6
  25. package/dist/types/respawn/Stack.d.ts +21 -0
  26. package/dist/types/respawn/index.d.ts +9 -1
  27. package/package.json +1 -3
  28. package/src/breakpoints.ts +28 -0
  29. package/src/components/Button/Button.scss +20 -20
  30. package/src/components/FullPageModal/FullPageModal.md +20 -17
  31. package/src/components/FullPageModal/FullPageModal.scss +5 -0
  32. package/src/components/FullPageModal/FullPageModal.tsx +37 -3
  33. package/src/components/Grid/Grid.md +37 -0
  34. package/src/components/Grid/Grid.scss +37 -0
  35. package/src/components/Grid/Grid.tsx +54 -0
  36. package/src/components/HistoryList/HistoryList.scss +2 -2
  37. package/src/components/Loader/Loader.md +30 -0
  38. package/src/components/Loader/Loader.scss +42 -0
  39. package/src/components/Loader/Loader.tsx +68 -0
  40. package/src/components/Menu/Menu.md +67 -3
  41. package/src/components/Menu/Menu.scss +48 -18
  42. package/src/components/Menu/Menu.tsx +146 -39
  43. package/src/components/Progress/Progress.md +27 -26
  44. package/src/components/Progress/Progress.scss +41 -36
  45. package/src/components/Progress/Progress.tsx +50 -6
  46. package/src/components/Select/Select.scss +20 -19
  47. package/src/components/Stack/Stack.md +43 -0
  48. package/src/components/Stack/Stack.scss +36 -0
  49. package/src/components/Stack/Stack.tsx +52 -0
  50. package/src/components/Table/Table.scss +1 -1
  51. package/src/components/Tag/Tag.scss +2 -2
  52. package/src/components/Title/Title.scss +6 -6
  53. package/src/components/Tree/Tree.md +1 -1
  54. package/src/css.ts +3 -0
  55. package/src/dialog.ts +47 -0
  56. package/src/icons.ts +29 -0
  57. package/src/index.ts +9 -1
  58. package/src/loader.ts +43 -0
  59. package/src/logo.ts +12 -0
  60. package/src/menu.ts +91 -21
  61. package/src/progress.ts +21 -0
  62. package/src/respawn/FullPageModal.ts +30 -3
  63. package/src/respawn/Grid.ts +41 -0
  64. package/src/respawn/Loader.ts +77 -0
  65. package/src/respawn/Menu.ts +138 -34
  66. package/src/respawn/Progress.ts +56 -13
  67. package/src/respawn/Stack.ts +37 -0
  68. package/src/respawn/index.ts +9 -1
  69. package/src/styles/breakpoints.scss +3 -0
  70. package/src/styles/theme.scss +55 -55
  71. package/src/styles/type.json +9 -9
package/src/menu.ts CHANGED
@@ -1,37 +1,107 @@
1
- // Menu rules shared by the React and the Respawn Menu (no React here): the
2
- // section ids, which sections start open, and the arrow keys.
1
+ // Menu rules shared by the React and the Respawn Menu (no React here): which
2
+ // kind of menu the props make, the section ids, which sections start open,
3
+ // and the keys.
4
+
5
+ /**
6
+ * What a Menu is, and so what screen readers hear:
7
+ * - 'nav': navigation. A <nav> landmark of links ("link", "current page");
8
+ * an item without an href is a button in it ("button").
9
+ * - 'actions': a menu of commands (the WAI-ARIA menu pattern): role="menu",
10
+ * each item a "menu item"; one Tab stop, the arrow keys move.
11
+ * - 'tree': a tree to pick from (the WAI-ARIA tree pattern), like layers:
12
+ * "tree", each row "level 2, 3 of 5, selected". Drawn by Tree.
13
+ */
14
+ export type MenuKind = 'nav' | 'actions' | 'tree';
15
+
16
+ interface KindProps {
17
+ kind?: MenuKind;
18
+ sections?: { href?: string; items?: { href?: string }[] }[];
19
+ items?: unknown;
20
+ activePath?: unknown;
21
+ }
22
+
23
+ /**
24
+ * The kind to draw: `kind` when given; else a tree for Tree's props (items,
25
+ * activePath), navigation when any item is a link, a menu of actions when
26
+ * none is.
27
+ */
28
+ export function menuKind(props: KindProps): MenuKind {
29
+ if (props.kind) return props.kind;
30
+ if (!props.sections && (props.items !== undefined || props.activePath !== undefined)) return 'tree';
31
+ const sections = props.sections || [];
32
+ const links = sections.some((s) => s.href !== undefined || (s.items || []).some((item) => item.href !== undefined));
33
+ return links || !sections.length ? 'nav' : 'actions';
34
+ }
3
35
 
4
36
  /** A section's id: its own, or its title as a slug ("Get started" -> "get-started"). */
5
- export const sectionId = (section: { id?: string; title: unknown }): string =>
6
- section.id || String(section.title).toLowerCase().replace(/[^a-z0-9]+/g, '-').replace(/^-|-$/g, '');
37
+ export const sectionId = (section: { id?: string; title?: unknown }): string =>
38
+ section.id || String(section.title ?? 'section').toLowerCase().replace(/[^a-z0-9]+/g, '-').replace(/^-|-$/g, '');
7
39
 
8
40
  /** Whether a section starts open: true / false for all, or a map of id -> open (missing = open). */
9
41
  export const startsOpen = (defaultOpen: boolean | Record<string, boolean> | undefined, id: string): boolean =>
10
42
  typeof defaultOpen === 'boolean' ? defaultOpen : !defaultOpen || defaultOpen[id] !== false;
11
43
 
12
- let warnedOldProps = false;
13
- /** Menu used to be the nested, selectable list that is Tree now: say so once. */
14
- export function warnOldMenuProps(props: { sections?: unknown; items?: unknown; activePath?: unknown }): boolean {
15
- const old = !props.sections && (props.items !== undefined || props.activePath !== undefined);
16
- if (old && !warnedOldProps && typeof console !== 'undefined') {
17
- warnedOldProps = true;
18
- console.warn('[@nurvus/ui] Menu is site navigation now (sections of links). The nested, selectable list it used to be is Tree: import { Tree } from \'@nurvus/ui\'. Drawing a Tree for now.');
19
- }
20
- return old;
44
+ /** Makes `row` the one item of an actions menu that Tab reaches (roving tabindex). */
45
+ export function roveTo(menu: HTMLElement, row: HTMLElement): void {
46
+ menu.querySelectorAll<HTMLElement>('[role="menuitem"]').forEach((item) => item.setAttribute('tabindex', item === row ? '0' : '-1'));
47
+ }
48
+
49
+ /** Focus moved onto an item of an actions menu (a click, say): it becomes the Tab stop. */
50
+ export function menuFocus(event: FocusEvent, menu: HTMLElement): void {
51
+ const row = (event.target as HTMLElement).closest<HTMLElement>('[role="menuitem"]');
52
+ if (row && menu.getAttribute('role') === 'menu') roveTo(menu, row);
21
53
  }
22
54
 
23
55
  /**
24
- * The arrow keys on a Menu (the WAI-ARIA disclosure navigation pattern's
25
- * optional keys). Tab still goes link by link; on top of that:
26
- * - Up / Down: the previous / next row (section titles and the links in open
27
- * sections), going round at the ends;
28
- * - Home / End: the first / last row;
29
- * - Right on a section: opens it, or (when open) goes to its first link;
30
- * - Left on a section: closes it; Left on a link: goes up to its section.
56
+ * The keys on a Menu. Up / Down move to the previous / next item (going round
57
+ * at the ends) and Home / End to the first / last, in every kind.
58
+ * - Navigation (the WAI-ARIA disclosure navigation pattern, with its
59
+ * optional keys): Tab still goes link by link. The rows are the section
60
+ * titles and the links in open sections; Right on a section opens it, or
61
+ * goes to its first link; Left closes it, or goes from a link up to its
62
+ * section. Enter follows a link; Enter or Space opens a section.
63
+ * - Actions (the WAI-ARIA menu pattern): one Tab stop that follows the
64
+ * focus; typing a letter goes to the next item starting with it; Enter or
65
+ * Space runs the item.
31
66
  * Returns true when it used the key.
32
67
  */
33
68
  export function menuKeydown(event: KeyboardEvent, nav: HTMLElement): boolean {
34
- if (event.altKey || event.ctrlKey || event.metaKey || event.shiftKey) return false;
69
+ if (event.altKey || event.ctrlKey || event.metaKey) return false;
70
+ return nav.getAttribute('role') === 'menu' ? actionsKeydown(event, nav) : navKeydown(event, nav);
71
+ }
72
+
73
+ function actionsKeydown(event: KeyboardEvent, menu: HTMLElement): boolean {
74
+ const rows = Array.from(menu.querySelectorAll<HTMLElement>('[role="menuitem"]'));
75
+ const target = (event.target as HTMLElement).closest<HTMLElement>('[role="menuitem"]');
76
+ if (!rows.length || !target) return false;
77
+ const at = rows.indexOf(target);
78
+ let next: HTMLElement | undefined;
79
+ switch (event.key) {
80
+ case 'ArrowDown': next = rows[(at + 1) % rows.length]; break;
81
+ case 'ArrowUp': next = rows[at <= 0 ? rows.length - 1 : at - 1]; break;
82
+ case 'Home': next = rows[0]; break;
83
+ case 'End': next = rows[rows.length - 1]; break;
84
+ default:
85
+ // Type to find: the next item whose text starts with the letter.
86
+ if (event.key.length === 1 && !event.shiftKey && /\S/.test(event.key)) {
87
+ const key = event.key.toLowerCase();
88
+ for (let i = 1; i <= rows.length; i += 1) {
89
+ const row = rows[(at + i) % rows.length];
90
+ if ((row.textContent || '').trim().toLowerCase().startsWith(key)) { next = row; break; }
91
+ }
92
+ if (!next) return false;
93
+ break;
94
+ }
95
+ return false;
96
+ }
97
+ event.preventDefault();
98
+ roveTo(menu, next);
99
+ next.focus();
100
+ return true;
101
+ }
102
+
103
+ function navKeydown(event: KeyboardEvent, nav: HTMLElement): boolean {
104
+ if (event.shiftKey) return false;
35
105
  const target = event.target as HTMLElement;
36
106
  const rows = Array.from(nav.querySelectorAll<HTMLElement>('.menu-title, .menu-item'))
37
107
  .filter((row) => !row.closest('.menu-section[data-open="false"] .menu-items'));
@@ -0,0 +1,21 @@
1
+ // Progress rules shared by the React and the Respawn Progress (no React here).
2
+ import type { IconName } from './icons';
3
+
4
+ export type ProgressStatus = 'active' | 'success' | 'warning' | 'critical';
5
+
6
+ /** What each status means, in words and as an icon, so it never rests on color alone (WCAG 1.4.1). */
7
+ export const PROGRESS_STATUS: Record<ProgressStatus, { word: string; icon?: IconName }> = {
8
+ active: { word: '' },
9
+ success: { word: 'Done', icon: 'check' },
10
+ warning: { word: 'Needs attention', icon: 'warning' },
11
+ critical: { word: 'Failed', icon: 'error' },
12
+ };
13
+
14
+ /** 0 to 100, whole numbers; anything else (NaN, -5, 140) is pulled into range. */
15
+ export const clampPercent = (percent: number): number => (Number.isFinite(percent) ? Math.round(Math.min(100, Math.max(0, percent))) : 0);
16
+
17
+ /** What screen readers say for the value: "40%", or "100%, Done". */
18
+ export const progressValueText = (percent: number, status: ProgressStatus): string => {
19
+ const word = (PROGRESS_STATUS[status] || PROGRESS_STATUS.active).word;
20
+ return word ? `${clampPercent(percent)}%, ${word}` : `${clampPercent(percent)}%`;
21
+ };
@@ -4,6 +4,7 @@ import { spawn, Child, ElementProps } from './spawn';
4
4
  import { NurvusElement } from './update';
5
5
  import Layout from './Layout';
6
6
  import Title from './Title';
7
+ import { dialogKeydown, focusDialog, restoreFocus } from '../dialog';
7
8
  import '../components/FullPageModal/FullPageModal.scss';
8
9
 
9
10
  export interface FullPageModalProps extends ElementProps {
@@ -17,10 +18,16 @@ export interface FullPageModalProps extends ElementProps {
17
18
  children?: Child;
18
19
  /** Appends the modal to this element when it is made, e.g. document.body. */
19
20
  mountEl?: Element;
21
+ /** Called when someone presses Esc. Close the modal in it: modal.update({ visible: false }). */
22
+ onClose?: () => void;
23
+ /** Names the modal and its title: the title gets the id "<id>-title", and the modal is labelled by it. */
24
+ id?: string;
20
25
  }
21
26
 
22
27
  /**
23
- * Shows content over the whole screen. Returns the modal's outer element
28
+ * Shows content over the whole screen: a modal dialog, like the React one
29
+ * (focus moves in when it opens and back when it closes, Tab stays inside,
30
+ * Esc calls onClose). Returns the modal's outer element
24
31
  * (`<div class="portal nurvus">`, the one React puts into `<body>` itself):
25
32
  * mount it on document.body, or pass `mountEl: document.body`.
26
33
  *
@@ -42,6 +49,7 @@ export default function FullPageModal(props: FullPageModalProps = {}): NurvusEle
42
49
  // The React component's two states.
43
50
  let isVisible = Boolean(current.visible);
44
51
  let animationState = '';
52
+ let opener: Element | null = null;
45
53
 
46
54
  const portal = spawn<HTMLDivElement>({ className: `portal ${CONSTANT.CLASS_PREFIX}` }) as NurvusElement<HTMLDivElement, FullPageModalProps>;
47
55
  let mask: HTMLElement | null = null;
@@ -80,10 +88,24 @@ export default function FullPageModal(props: FullPageModalProps = {}): NurvusEle
80
88
  };
81
89
 
82
90
  const buildModal = () => {
83
- const { children, className, headerActions, title, visible: _visible, mountEl: _mountEl, ...rest } = current;
91
+ const { children, className, headerActions, title, visible: _visible, mountEl: _mountEl, onClose, id, events, ...rest } = current;
92
+ const titleId = id && title ? `${id}-title` : undefined;
84
93
  const el = spawn({
85
94
  className: classNames(className, 'modal', CONSTANT.CLASS_PREFIX),
95
+ role: 'dialog',
96
+ 'aria-modal': 'true',
97
+ 'aria-labelledby': titleId,
98
+ 'aria-label': !id && typeof title === 'string' ? title : undefined,
99
+ tabindex: -1,
100
+ id,
86
101
  ...rest,
102
+ events: {
103
+ ...(events as object),
104
+ keydown: (event: KeyboardEvent, node: HTMLElement) => {
105
+ dialogKeydown(event, node, current.onClose);
106
+ if (events && (events as any).keydown) (events as any).keydown(event, node);
107
+ },
108
+ },
87
109
  tag: 'div',
88
110
  children: [
89
111
  spawn({
@@ -92,7 +114,7 @@ export default function FullPageModal(props: FullPageModalProps = {}): NurvusEle
92
114
  display: 'flex',
93
115
  alignItems: 'center',
94
116
  justifyContent: 'space-between',
95
- children: [Title({ children: title }), spawn({ className: 'header-actions', children: headerActions })],
117
+ children: [Title({ id: titleId, children: title }), spawn({ className: 'header-actions', children: headerActions })],
96
118
  }),
97
119
  }),
98
120
  children,
@@ -117,9 +139,14 @@ export default function FullPageModal(props: FullPageModalProps = {}): NurvusEle
117
139
  const visible = Boolean(current.visible);
118
140
  if (visible !== was) start(visible);
119
141
  sync();
142
+ // Focus in on open; back to the opener on close.
143
+ if (visible && !was) { opener = document.activeElement; focusDialog(modal); }
144
+ if (!visible && was) { restoreFocus(opener); opener = null; }
120
145
  return portal;
121
146
  };
122
147
 
123
148
  if (mountEl) mountEl.appendChild(portal);
149
+ // Open from the start: focus goes in once it is on the page.
150
+ if (current.visible) { opener = document.activeElement; focusDialog(modal); }
124
151
  return portal;
125
152
  }
@@ -0,0 +1,41 @@
1
+ import classNames from 'classnames';
2
+ import CONSTANT from '../constants';
3
+ import { Spacing } from '../spacing';
4
+ import { Responsive, responsiveData } from '../breakpoints';
5
+ import { spawn, Child, ElementProps, Style } from './spawn';
6
+ import { updatable, NurvusElement } from './update';
7
+ import '../components/Grid/Grid.scss';
8
+
9
+ export type GridColumns = 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | 10 | 11 | 12;
10
+
11
+ export interface GridProps extends ElementProps {
12
+ /** How many equal columns: 1 to 12. Can change with the width: { base: 1, md: 2, lg: 3 }. */
13
+ columns?: Responsive<GridColumns>;
14
+ /** Instead of a count: as many columns as fit, each at least this wide (e.g. "15rem" or 240). They fill the row. */
15
+ minItemWidth?: string | number;
16
+ /** Space between cells, from the 4px grid: 0, 2, 4, 8, 12, 16, 24, 32, 48 or 64. */
17
+ gap?: Spacing;
18
+ /** Space between rows when it differs from gap. */
19
+ rowGap?: Spacing;
20
+ /** How cells line up in their row. Defaults to stretch (equal heights). */
21
+ align?: 'start' | 'center' | 'end' | 'stretch';
22
+ /** What to lay out. */
23
+ children?: Child;
24
+ }
25
+
26
+ /** Columns: a count that changes at the breakpoints, or as many as fit. The same markup as the React Grid. */
27
+ export default function Grid(props: GridProps = {}): NurvusElement<HTMLDivElement, GridProps> {
28
+ return updatable(({ columns, minItemWidth, gap = 16, rowGap, align, className, style, ...rest }: GridProps) => {
29
+ const fit = minItemWidth !== undefined;
30
+ const min = typeof minItemWidth === 'number' ? `${minItemWidth}px` : minItemWidth;
31
+ return spawn<HTMLDivElement>({
32
+ className: classNames(className, 'grid', CONSTANT.CLASS_PREFIX),
33
+ ...(fit ? { 'data-fit': true } : responsiveData('columns', columns === undefined ? 1 : columns)),
34
+ 'data-gap': gap,
35
+ 'data-row-gap': rowGap,
36
+ 'data-align': align,
37
+ style: fit ? { '--nurvus-grid-min': min, ...(typeof style === 'object' ? style : {}) } as Style : style,
38
+ ...rest,
39
+ });
40
+ }, props);
41
+ }
@@ -0,0 +1,77 @@
1
+ import classNames from 'classnames';
2
+ import CONSTANT from '../constants';
3
+ import { loaderRings, LOGO_VIEWBOX, LoaderSegment } from '../loader';
4
+ import { spawn, ElementProps } from './spawn';
5
+ import { updatable, NurvusElement } from './update';
6
+ import '../components/Loader/Loader.scss';
7
+
8
+ const SVG = 'http://www.w3.org/2000/svg';
9
+
10
+ export interface LoaderProps extends ElementProps {
11
+ /** Width and height of the mark. Defaults to 2em (twice the text size). A number is pixels. */
12
+ size?: number | string;
13
+ /** What is loading, for screen readers ("Loading photos"). Defaults to "Loading". */
14
+ label?: string;
15
+ /** Shows the label beside the mark, not only to screen readers. */
16
+ showLabel?: boolean;
17
+ /** Fills the segments with the logo's gradients (for big loaders); their ids start with this. Without it, one color each. */
18
+ id?: string;
19
+ }
20
+
21
+ /**
22
+ * Shows that something is loading: the NURVUS mark with a light running round
23
+ * it, the same markup as the React Loader. Screen readers hear the label once
24
+ * (role="status"). Remove it when the thing has loaded.
25
+ */
26
+ export default function Loader(props: LoaderProps = {}): NurvusElement<HTMLDivElement, LoaderProps> {
27
+ return updatable(({ size = '2em', label = 'Loading', showLabel = false, id, className, ...rest }: LoaderProps) => {
28
+ const { inner, outer, gradients } = loaderRings(id);
29
+ const ring = (cls: string, segments: LoaderSegment[]) => spawn<any>({
30
+ tag: 'g',
31
+ namespace: SVG,
32
+ className: `loader-ring ${cls}`,
33
+ children: segments.map((s) => spawn<any>({
34
+ tag: 'path', namespace: SVG, className: 'loader-seg', d: s.d, fill: s.fill, style: { '--nurvus-loader-at': String(s.angle) },
35
+ })),
36
+ });
37
+ return spawn<HTMLDivElement>({
38
+ className: classNames(className, 'loader', CONSTANT.CLASS_PREFIX),
39
+ role: 'status',
40
+ 'data-label': showLabel ? 'shown' : 'hidden',
41
+ id,
42
+ ...rest,
43
+ children: [
44
+ spawn<any>({
45
+ tag: 'svg',
46
+ namespace: SVG,
47
+ className: 'loader-mark',
48
+ viewBox: LOGO_VIEWBOX,
49
+ width: size,
50
+ height: size,
51
+ 'aria-hidden': true,
52
+ focusable: 'false',
53
+ children: [
54
+ gradients.length ? spawn<any>({
55
+ tag: 'defs',
56
+ namespace: SVG,
57
+ children: gradients.map((g) => spawn<any>({
58
+ tag: 'linearGradient',
59
+ namespace: SVG,
60
+ id: g.id,
61
+ gradientUnits: 'userSpaceOnUse',
62
+ x1: g.x1, y1: g.y1, x2: g.x2, y2: g.y2,
63
+ children: [
64
+ spawn<any>({ tag: 'stop', namespace: SVG, 'stop-color': g.from }),
65
+ spawn<any>({ tag: 'stop', namespace: SVG, offset: '1', 'stop-color': g.to }),
66
+ ],
67
+ })),
68
+ }) : null,
69
+ ring('loader-inner', inner),
70
+ ring('loader-outer', outer),
71
+ ],
72
+ }),
73
+ spawn({ tag: 'span', className: 'loader-label', children: label }),
74
+ ],
75
+ });
76
+ }, props);
77
+ }
@@ -1,16 +1,22 @@
1
1
  import classNames from 'classnames';
2
2
  import CONSTANT from '../constants';
3
- import { sectionId, startsOpen, menuKeydown, warnOldMenuProps } from '../menu';
4
- import Tree from './Tree';
3
+ import { sectionId, startsOpen, menuKeydown, menuFocus, menuKind, MenuKind } from '../menu';
4
+ import Tree, { TreeProps } from './Tree';
5
5
  import { spawn, Child, ElementProps } from './spawn';
6
6
  import { updatable, NurvusElement } from './update';
7
7
  import '../components/Menu/Menu.scss';
8
8
 
9
+ export type { MenuKind };
10
+
9
11
  export interface MenuItem {
10
- /** What the link says. */
12
+ /** What the item says. */
11
13
  label: Child;
12
- /** Where it goes. The item whose href equals `current` is marked as the current page. */
13
- href: string;
14
+ /** Makes the item a link to this address. The item whose href equals `current` is marked as the current page. */
15
+ href?: string;
16
+ /** Makes the item a button that calls this (an action: "Duplicate", "Sign out"). */
17
+ onSelect?: (event: MouseEvent) => void;
18
+ /** Shows the item but stops it working (actions only). */
19
+ disabled?: boolean;
14
20
  /** Draws a hairline above this item, to split a section into groups. */
15
21
  divider?: boolean;
16
22
  }
@@ -18,17 +24,18 @@ export interface MenuItem {
18
24
  export interface MenuSection {
19
25
  /** Stable id: names the section's open state and links its toggle to its list. Defaults to the title. */
20
26
  id?: string;
21
- /** The section heading. */
22
- title: string;
27
+ /** The section heading. Optional for actions. */
28
+ title?: string;
23
29
  /** Makes the heading a link too (e.g. to the section's overview page). */
24
30
  href?: string;
25
- /** The section's links. */
31
+ /** The section's items. */
26
32
  items: MenuItem[];
27
33
  }
28
34
 
29
- export interface MenuProps extends ElementProps {
30
- /** The sections, in order. */
31
- sections: MenuSection[];
35
+ /** What navigation and actions take. */
36
+ interface MenuBaseProps extends ElementProps {
37
+ /** Navigation and actions: the sections, in order. */
38
+ sections?: MenuSection[];
32
39
  /** The href of the page being shown: its link is marked, and its section opens. */
33
40
  current?: string;
34
41
  /** Which sections start open: true (all), false (none) or a map of section id -> open. Defaults to all. */
@@ -37,27 +44,53 @@ export interface MenuProps extends ElementProps {
37
44
  onToggle?: (id: string, open: boolean) => void;
38
45
  /** Called when any link is clicked, with its href (e.g. to close a drawer). */
39
46
  onNavigate?: (href: string, event: MouseEvent) => void;
40
- /** Accessible name of the navigation landmark. */
47
+ /** What screen readers call the menu ("Pages", "Actions"). */
41
48
  label?: string;
42
- /** Prefix for the ids that link each toggle to its list. Defaults to "menu". */
49
+ /** Prefix for the ids inside (each toggle names its list). Defaults to "menu". */
43
50
  id?: string;
44
51
  }
45
52
 
53
+ export interface MenuProps extends MenuBaseProps {
54
+ /** What the menu is: 'nav' (links), 'actions' (commands) or 'tree' (rows to pick from, with Tree's props). Left out, it follows the props. */
55
+ kind?: MenuKind;
56
+ /** Tree: the rows, each with optional child `items`. */
57
+ items?: TreeProps['items'];
58
+ /** Tree: the picked row as a path of indexes. */
59
+ activePath?: number[];
60
+ /** Tree: draws a row's content instead of its label. */
61
+ itemRenderer?: TreeProps['itemRenderer'];
62
+ /** Tree: the deepest level that still indents. */
63
+ maxIndentDepth?: number;
64
+ }
65
+
66
+ /** Menu's props for navigation and actions. */
67
+ export interface MenuListProps extends MenuBaseProps {
68
+ /** 'nav' or 'actions'; left out, it follows the items. */
69
+ kind?: 'nav' | 'actions';
70
+ }
71
+ /** Menu kind: 'tree': Tree's props. */
72
+ export type MenuTreeProps = TreeProps & { kind: 'tree' };
73
+
46
74
  /**
47
- * Site navigation: sections of links that open and close (an accordion, with
48
- * a smooth animation), and the current page marked by a bar beside it. A
49
- * click on a toggle opens or closes its section in place (the element stays
50
- * the same); update({ current }) marks another page and opens its section.
75
+ * One component for lists of things to go to, do or pick, the same markup as
76
+ * the React Menu. The items decide what it is, and screen readers hear it so:
77
+ * links make navigation (sections open and close in place; update({ current })
78
+ * marks another page), actions make a menu of commands (one Tab stop, the
79
+ * arrow keys move), kind: 'tree' makes a Tree.
51
80
  */
52
81
  export default function Menu(props: MenuProps = { sections: [] }): NurvusElement<HTMLElement, MenuProps> {
53
- // The props Menu took before it was navigation (Tree's) still draw a Tree, with a warning.
54
- if (warnOldMenuProps(props || {})) return Tree(props as any) as any;
55
- return updatable(({
56
- sections = [], current, defaultOpen = true, onToggle, onNavigate, label = 'Pages', id = 'menu', className, ...rest
57
- }: MenuProps, keep) => {
82
+ const kind = menuKind(props || {});
83
+ if (kind === 'tree') {
84
+ const { kind: _kind, sections: _s, current: _c, defaultOpen: _d, onToggle: _t, onNavigate: _n, ...tree } = props;
85
+ return Tree(tree as TreeProps) as any;
86
+ }
87
+ if (kind === 'actions') return MenuActions(props as MenuListProps) as any;
88
+ return updatable<HTMLElement, MenuListProps>(({
89
+ kind: _kind, sections = [], current, defaultOpen = true, onToggle, onNavigate, label = 'Pages', id = 'menu', className, ...rest
90
+ }: MenuListProps, keep) => {
58
91
  const open: Record<string, boolean> = Object.fromEntries(sections.map((s) => [sectionId(s), startsOpen(defaultOpen, sectionId(s))]));
59
92
  // The current page's section always starts open, as in React.
60
- const home = sections.find((s) => s.items.some((item) => item.href === current));
93
+ const home = sections.find((s) => s.items.some((item) => item.href !== undefined && item.href === current));
61
94
  if (home) open[sectionId(home)] = true;
62
95
 
63
96
  const navigate = (href: string) => ({ click: (event: MouseEvent) => { if (onNavigate) onNavigate(href, event); } });
@@ -72,7 +105,7 @@ export default function Menu(props: MenuProps = { sections: [] }): NurvusElement
72
105
  el.setAttribute('data-open', String(open[sid]));
73
106
  toggles.forEach((t) => {
74
107
  t.setAttribute('aria-expanded', String(open[sid]));
75
- if (t.hasAttribute('aria-label')) t.setAttribute('aria-label', `${open[sid] ? 'Hide' : 'Show'} ${section.title}`);
108
+ if (t.hasAttribute('aria-label')) t.setAttribute('aria-label', `${open[sid] ? 'Hide' : 'Show'} ${String(section.title)}`);
76
109
  });
77
110
  if (onToggle) onToggle(sid, open[sid]);
78
111
  };
@@ -82,7 +115,7 @@ export default function Menu(props: MenuProps = { sections: [] }): NurvusElement
82
115
  const heading = section.href
83
116
  ? [
84
117
  spawn({ tag: 'a', className: 'menu-title', href: section.href, 'data-active': current === section.href, events: navigate(section.href), children: section.title }),
85
- spawn(toggleProps({ className: 'menu-toggle', 'aria-label': `${open[sid] ? 'Hide' : 'Show'} ${section.title}` })),
118
+ spawn(toggleProps({ className: 'menu-toggle', 'aria-label': `${open[sid] ? 'Hide' : 'Show'} ${String(section.title)}` })),
86
119
  ]
87
120
  : [spawn(toggleProps({ className: 'menu-title menu-toggle', children: section.title }))];
88
121
  heading.forEach((h) => { if (h.tagName === 'BUTTON') toggles.push(h); });
@@ -101,15 +134,24 @@ export default function Menu(props: MenuProps = { sections: [] }): NurvusElement
101
134
  children: section.items.map((item) => spawn({
102
135
  tag: 'li',
103
136
  'data-divider': item.divider || undefined,
104
- children: spawn({
105
- tag: 'a',
106
- className: 'menu-item',
107
- href: item.href,
108
- 'data-active': current === item.href,
109
- 'aria-current': current === item.href ? 'page' : undefined,
110
- events: navigate(item.href),
111
- children: item.label,
112
- }),
137
+ children: item.href !== undefined
138
+ ? spawn({
139
+ tag: 'a',
140
+ className: 'menu-item',
141
+ href: item.href,
142
+ 'data-active': current === item.href,
143
+ 'aria-current': current === item.href ? 'page' : undefined,
144
+ events: navigate(item.href),
145
+ children: item.label,
146
+ })
147
+ : spawn({
148
+ tag: 'button',
149
+ type: 'button',
150
+ className: 'menu-item',
151
+ disabled: item.disabled,
152
+ events: { click: (event: MouseEvent) => { if (item.onSelect) item.onSelect(event); } },
153
+ children: item.label,
154
+ }),
113
155
  })),
114
156
  }),
115
157
  }),
@@ -123,6 +165,7 @@ export default function Menu(props: MenuProps = { sections: [] }): NurvusElement
123
165
  tag: 'nav',
124
166
  className: classNames(className, 'menu', CONSTANT.CLASS_PREFIX),
125
167
  'aria-label': label,
168
+ 'data-kind': 'nav',
126
169
  ...others,
127
170
  events: {
128
171
  ...events,
@@ -133,5 +176,66 @@ export default function Menu(props: MenuProps = { sections: [] }): NurvusElement
133
176
  },
134
177
  children: sections.map(renderSection),
135
178
  });
179
+ }, props as MenuListProps) as any;
180
+ }
181
+
182
+ /** A menu of actions (role="menu"): one Tab stop that follows the focus, arrow keys, type to find. */
183
+ function MenuActions(props: MenuListProps): NurvusElement<HTMLElement, MenuListProps> {
184
+ return updatable(({
185
+ kind: _kind, sections = [], label = 'Actions', id = 'menu', className, current: _c, defaultOpen: _d, onToggle: _t, onNavigate: _n, ...rest
186
+ }: MenuListProps) => {
187
+ let first = true;
188
+ const { events, ...others } = rest;
189
+ return spawn<HTMLElement>({
190
+ className: classNames(className, 'menu', CONSTANT.CLASS_PREFIX),
191
+ role: 'menu',
192
+ 'aria-label': label,
193
+ 'data-kind': 'actions',
194
+ ...others,
195
+ events: {
196
+ ...events,
197
+ keydown: (event: KeyboardEvent, el: HTMLElement) => { menuKeydown(event, el); if (events && events.keydown) events.keydown(event, el); },
198
+ focusin: (event: FocusEvent, el: HTMLElement) => { menuFocus(event, el); if (events && events.focusin) events.focusin(event, el); },
199
+ },
200
+ children: sections.map((section, s) => {
201
+ const sid = sectionId({ id: section.id, title: section.title ?? `section-${s + 1}` });
202
+ const titleId = `${id}-${sid}-title`;
203
+ return spawn({
204
+ className: 'menu-section',
205
+ 'data-section': sid,
206
+ role: 'group',
207
+ 'aria-labelledby': section.title ? titleId : undefined,
208
+ children: [
209
+ section.title ? spawn({ className: 'menu-heading', children: spawn({ tag: 'span', className: 'menu-title', id: titleId, children: section.title }) }) : null,
210
+ spawn({
211
+ className: 'menu-items',
212
+ children: spawn({
213
+ tag: 'ul',
214
+ role: 'none',
215
+ children: section.items.map((item) => {
216
+ const tabindex = first ? 0 : -1;
217
+ first = false;
218
+ return spawn({
219
+ tag: 'li',
220
+ role: 'none',
221
+ 'data-divider': item.divider || undefined,
222
+ children: spawn({
223
+ tag: 'button',
224
+ type: 'button',
225
+ role: 'menuitem',
226
+ className: 'menu-item',
227
+ tabindex,
228
+ 'aria-disabled': item.disabled || undefined,
229
+ events: { click: (event: MouseEvent) => { if (!item.disabled && item.onSelect) item.onSelect(event); } },
230
+ children: item.label,
231
+ }),
232
+ });
233
+ }),
234
+ }),
235
+ }),
236
+ ],
237
+ });
238
+ }),
239
+ });
136
240
  }, props);
137
241
  }