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

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,37 @@
1
+ export interface AnchorItem {
2
+ /** "#id" of the section (or any link). */
3
+ href: string;
4
+ /** What the row says. */
5
+ label: string;
6
+ /** 1 for a top-level section, 2 for one inside it, and so on. Defaults to 1. */
7
+ level?: number;
8
+ }
9
+ export declare const ANCHOR_ROW = 28;
10
+ export declare const ANCHOR_INDENT = 12;
11
+ export interface AnchorRail {
12
+ /** The path, in units (1 unit = 1px at the default text size). */
13
+ d: string;
14
+ width: number;
15
+ height: number;
16
+ /** The whole path's length. */
17
+ length: number;
18
+ /** Each row's stretch along the path: [start, end]. */
19
+ spans: [number, number][];
20
+ }
21
+ /** The rail for rows at these levels. */
22
+ export declare function anchorRail(levels: number[]): AnchorRail;
23
+ /** The dash that lights row `i`'s stretch: stroke-dasharray and stroke-dashoffset. */
24
+ export declare function anchorDash(rail: AnchorRail, i: number): {
25
+ dasharray: string;
26
+ dashoffset: number;
27
+ };
28
+ /** The id an "#id" href points at, or null for other links. */
29
+ export declare const anchorTarget: (href: string) => string | null;
30
+ /**
31
+ * Which row is in view: the last section whose top has passed `offset` pixels
32
+ * below the top of the scroll area (the first one before any has), and the
33
+ * last one once the area is scrolled to its end.
34
+ */
35
+ export declare function anchorActive(items: AnchorItem[], offset: number, scrollRoot?: Element | null): number;
36
+ /** Scrolls a section into view (smoothly unless people asked for less motion) and moves focus to it. */
37
+ export declare function anchorGo(href: string, updateHash: boolean): boolean;
@@ -0,0 +1,30 @@
1
+ import React from 'react';
2
+ import { AnchorItem } from '../../anchor';
3
+ export type { AnchorItem };
4
+ export interface AnchorProps extends Omit<React.HTMLAttributes<HTMLElement>, 'title'> {
5
+ /** The sections, in page order: each an "#id" href, a label and a level (1, 2…). */
6
+ items: AnchorItem[];
7
+ /** The heading above the list. */
8
+ title?: string;
9
+ /** Prefix for the ids inside (the title is "<id>-title"). Defaults to "anchor". */
10
+ id?: string;
11
+ /** How far below the top a section's heading must be scrolled to count as "in view", in pixels (room for a sticky header). */
12
+ offset?: number;
13
+ /** The section in view, set by you (its href). Left out, the Anchor follows the scrolling itself. */
14
+ current?: string;
15
+ /** Scroll-spy inside this element instead of the page: an element or a CSS selector. */
16
+ scrollRoot?: Element | string;
17
+ /** Writes the section's #id in the address bar when one is picked. Turn off for hash routers. */
18
+ updateHash?: boolean;
19
+ /** Called when a row is picked, with its href. Call event.preventDefault() to handle it yourself. */
20
+ onNavigate?: (href: string, event: React.MouseEvent<HTMLAnchorElement>) => void;
21
+ /** Custom class name. */
22
+ className?: string;
23
+ }
24
+ /**
25
+ * "On this page": the sections of a long page, the one being read marked as
26
+ * you scroll. A rail runs down beside the rows, bending in and out with the
27
+ * nesting, and a highlight slides along it to the section in view. Picking a
28
+ * row scrolls to the section and moves focus there.
29
+ */
30
+ export default function Anchor({ items, title, id, offset, current, scrollRoot, updateHash, onNavigate, className, ...restProps }: AnchorProps): React.ReactElement;
@@ -0,0 +1,31 @@
1
+ import React from 'react';
2
+ import { ButtonSize, ButtonType } from '../Button/Button';
3
+ import { MenuItem, MenuSection } from '../Menu/Menu';
4
+ export interface DropdownProps extends Omit<React.HTMLAttributes<HTMLDivElement>, 'onSelect'> {
5
+ /** What the button says (text, or an Icon with a label for an icon-only button). */
6
+ label: React.ReactNode;
7
+ /** The actions, in groups (each may have a title). */
8
+ sections?: MenuSection[];
9
+ /** Or the actions as one flat list. */
10
+ items?: MenuItem[];
11
+ /** Which edge of the button the menu lines up with. */
12
+ align?: 'start' | 'end';
13
+ /** The button's look. Defaults to secondary. */
14
+ type?: ButtonType;
15
+ /** The button's size. */
16
+ size?: ButtonSize;
17
+ /** Stops the button working. */
18
+ disabled?: boolean;
19
+ /** Names the button and the menu ("<id>-button", "<id>-menu"). */
20
+ id: string;
21
+ /** Custom class name. */
22
+ className?: string;
23
+ }
24
+ /**
25
+ * A button that opens a menu of actions (the WAI-ARIA menu button pattern).
26
+ * A click, Enter, Space or ↓ opens it on its first item, ↑ on its last; inside,
27
+ * the Menu's keys work (↑ ↓ Home End, type a letter); choosing an action runs
28
+ * it, closes the menu and puts focus back on the button; Esc does the same
29
+ * without choosing; Tab or a click outside closes it.
30
+ */
31
+ export default function Dropdown({ label, sections, items, align, type, size, disabled, id, className, ...restProps }: DropdownProps): React.ReactElement;
@@ -43,6 +43,13 @@ export interface MenuProps extends Omit<React.HTMLAttributes<HTMLElement>, 'onTo
43
43
  onToggle?: (id: string, open: boolean) => void;
44
44
  /** Navigation: called when any link is clicked, with its href (e.g. to close a drawer). */
45
45
  onNavigate?: (href: string, event: React.MouseEvent<HTMLAnchorElement>) => void;
46
+ /**
47
+ * Navigation: where each section's chevron sits. 'start' (the default): before
48
+ * the title, pointing right when closed and down when open, with a guide line
49
+ * down the open section's items (as Material UI draws it). 'end': after the
50
+ * title, down when closed and up when open.
51
+ */
52
+ chevron?: 'start' | 'end';
46
53
  /** Tree: the rows, each with optional child `items`. */
47
54
  items?: TreeItem[];
48
55
  /** Tree: the picked row as a path of indexes, e.g. [2, 0] = the first child of the third row. */
@@ -55,7 +62,7 @@ export interface MenuProps extends Omit<React.HTMLAttributes<HTMLElement>, 'onTo
55
62
  maxIndentDepth?: number;
56
63
  /** What screen readers call the menu ("Pages", "Actions", "Layers"). */
57
64
  label?: string;
58
- /** Prefix for the ids inside (each toggle names its list). Defaults to "menu". */
65
+ /** Prefix for the ids inside (each toggle names its list). Defaults to "menu". A menu of actions also carries it (so a button can point at it with aria-controls). */
59
66
  id?: string;
60
67
  /** Custom class name. */
61
68
  className?: string;
@@ -0,0 +1,9 @@
1
+ /** The menu's items, in order. */
2
+ export declare const menuItems: (root: HTMLElement) => HTMLElement[];
3
+ /** Moves focus to the first or last item (and makes it the menu's Tab stop). */
4
+ export declare function focusItem(root: HTMLElement, which: 'first' | 'last'): void;
5
+ /**
6
+ * Keys on the button: ↓ (or Enter / Space, which click it) opens the menu on
7
+ * its first item, ↑ on its last. Returns which item to focus, or null.
8
+ */
9
+ export declare function triggerKey(event: KeyboardEvent): 'first' | 'last' | null;
@@ -66,6 +66,7 @@ declare const DEFS: {
66
66
  link: IconNode[];
67
67
  sun: IconNode[];
68
68
  moon: IconNode[];
69
+ contrast: IconNode[];
69
70
  palette: IconNode[];
70
71
  sparkles: IconNode[];
71
72
  zap: IconNode[];
@@ -26,6 +26,10 @@ export { default as Loader } from './components/Loader/Loader';
26
26
  export type { LoaderProps } from './components/Loader/Loader';
27
27
  export { default as Tree } from './components/Tree/Tree';
28
28
  export type { TreeProps, TreeItem } from './components/Tree/Tree';
29
+ export { default as Anchor } from './components/Anchor/Anchor';
30
+ export type { AnchorProps, AnchorItem } from './components/Anchor/Anchor';
31
+ export { default as Dropdown } from './components/Dropdown/Dropdown';
32
+ export type { DropdownProps } from './components/Dropdown/Dropdown';
29
33
  export { default as Menu } from './components/Menu/Menu';
30
34
  export type { MenuProps, MenuListProps, MenuTreeProps, MenuItem, MenuSection, MenuKind } from './components/Menu/Menu';
31
35
  export { default as Select } from './components/Select/Select';
@@ -0,0 +1,28 @@
1
+ import { AnchorItem } from '../anchor';
2
+ import { ElementProps } from './spawn';
3
+ import { NurvusElement } from './update';
4
+ export type { AnchorItem };
5
+ export interface AnchorProps extends ElementProps {
6
+ /** The sections, in page order: each an "#id" href, a label and a level (1, 2…). */
7
+ items: AnchorItem[];
8
+ /** The heading above the list. */
9
+ title?: string;
10
+ /** Prefix for the ids inside (the title is "<id>-title"). Defaults to "anchor". */
11
+ id?: string;
12
+ /** How far below the top a section's heading must be scrolled to count as "in view", in pixels. */
13
+ offset?: number;
14
+ /** The section in view, set by you (its href). Left out, the Anchor follows the scrolling itself. */
15
+ current?: string;
16
+ /** Scroll-spy inside this element instead of the page: an element or a CSS selector. */
17
+ scrollRoot?: Element | string;
18
+ /** Writes the section's #id in the address bar when one is picked. Turn off for hash routers. */
19
+ updateHash?: boolean;
20
+ /** Called when a row is picked, with its href. Call event.preventDefault() to handle it yourself. */
21
+ onNavigate?: (href: string, event: MouseEvent) => void;
22
+ }
23
+ /**
24
+ * "On this page", the same markup as the React Anchor: the rail bends with the
25
+ * nesting and its highlight slides to the section in view, in place (the
26
+ * element stays the same while you scroll).
27
+ */
28
+ export default function Anchor(props: AnchorProps): NurvusElement<HTMLElement, AnchorProps>;
@@ -0,0 +1,27 @@
1
+ import { ButtonSize, ButtonType } from './Button';
2
+ import { MenuItem, MenuSection } from './Menu';
3
+ import { Child, ElementProps } from './spawn';
4
+ import { NurvusElement } from './update';
5
+ export interface DropdownProps extends ElementProps {
6
+ /** What the button says (text, or an Icon with a label for an icon-only button). */
7
+ label: Child;
8
+ /** The actions, in groups (each may have a title). */
9
+ sections?: MenuSection[];
10
+ /** Or the actions as one flat list. */
11
+ items?: MenuItem[];
12
+ /** Which edge of the button the menu lines up with. */
13
+ align?: 'start' | 'end';
14
+ /** The button's look. Defaults to secondary. */
15
+ type?: ButtonType;
16
+ /** The button's size. */
17
+ size?: ButtonSize;
18
+ /** Stops the button working. */
19
+ disabled?: boolean;
20
+ /** Names the button and the menu ("<id>-button", "<id>-menu"). */
21
+ id: string;
22
+ }
23
+ /**
24
+ * A button that opens a menu of actions, the same markup and keys as the React
25
+ * Dropdown. Opening and closing change it in place (the element stays the same).
26
+ */
27
+ export default function Dropdown(props: DropdownProps): NurvusElement<HTMLDivElement, DropdownProps>;
@@ -41,6 +41,8 @@ interface MenuBaseProps extends ElementProps {
41
41
  label?: string;
42
42
  /** Prefix for the ids inside (each toggle names its list). Defaults to "menu". */
43
43
  id?: string;
44
+ /** Navigation: the chevron before the title ('start', the default: right when closed, down when open, a guide line down the items) or after it ('end'). */
45
+ chevron?: 'start' | 'end';
44
46
  }
45
47
  export interface MenuProps extends MenuBaseProps {
46
48
  /** What the menu is: 'nav' (links), 'actions' (commands) or 'tree' (rows to pick from, with Tree's props). Left out, it follows the props. */
@@ -29,6 +29,10 @@ export { BREAKPOINTS, isAtLeast } from '../breakpoints';
29
29
  export type { Breakpoint, Responsive } from '../breakpoints';
30
30
  export { default as Loader } from './Loader';
31
31
  export type { LoaderProps } from './Loader';
32
+ export { default as Anchor } from './Anchor';
33
+ export type { AnchorProps, AnchorItem } from './Anchor';
34
+ export { default as Dropdown } from './Dropdown';
35
+ export type { DropdownProps } from './Dropdown';
32
36
  export { default as Menu } from './Menu';
33
37
  export type { MenuProps, MenuListProps, MenuTreeProps, MenuItem, MenuSection, MenuKind } from './Menu';
34
38
  export { default as Select } from './Select';
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@nurvus/ui",
3
- "version": "0.1.0-alpha.16",
3
+ "version": "0.1.0-alpha.17",
4
4
  "description": "NURVUS Design System",
5
5
  "main": "dist/index.js",
6
6
  "types": "dist/types/index.d.ts",
package/src/anchor.ts ADDED
@@ -0,0 +1,127 @@
1
+ // Anchor rules shared by the React and the Respawn Anchor (no React here):
2
+ // the rail's drawing and which section is in view.
3
+ //
4
+ // The rail is drawn from the items alone (no measuring), so it is the same on
5
+ // the server, in React and in Respawn: every row is 1.75rem (28 units at the
6
+ // default 16px), each level indents 0.75rem (12 units), and between rows at
7
+ // different levels the line bends with a short S-curve. The highlight is the
8
+ // same path with a dash over the active row's stretch; moving the dash slides
9
+ // it along the curves.
10
+
11
+ export interface AnchorItem {
12
+ /** "#id" of the section (or any link). */
13
+ href: string;
14
+ /** What the row says. */
15
+ label: string;
16
+ /** 1 for a top-level section, 2 for one inside it, and so on. Defaults to 1. */
17
+ level?: number;
18
+ }
19
+
20
+ export const ANCHOR_ROW = 28;
21
+ export const ANCHOR_INDENT = 12;
22
+ const X0 = 1.5; // the line's x at level 1 (inside a 3-unit gutter)
23
+ const BEND = 7; // half the height of an S-curve
24
+ const END = 5; // the line stops this far inside the first and last rows
25
+
26
+ const xAt = (level: number) => X0 + (Math.max(1, level) - 1) * ANCHOR_INDENT;
27
+
28
+ /** Length of a cubic Bézier, by sampling (deterministic). */
29
+ function cubicLength(p0: number[], p1: number[], p2: number[], p3: number[]): number {
30
+ let len = 0;
31
+ let prev = p0;
32
+ for (let i = 1; i <= 24; i += 1) {
33
+ const t = i / 24; const u = 1 - t;
34
+ const pt = [0, 1].map((k) => u * u * u * p0[k] + 3 * u * u * t * p1[k] + 3 * u * t * t * p2[k] + t * t * t * p3[k]);
35
+ len += Math.hypot(pt[0] - prev[0], pt[1] - prev[1]);
36
+ prev = pt;
37
+ }
38
+ return len;
39
+ }
40
+
41
+ const round = (n: number) => Math.round(n * 100) / 100;
42
+
43
+ export interface AnchorRail {
44
+ /** The path, in units (1 unit = 1px at the default text size). */
45
+ d: string;
46
+ width: number;
47
+ height: number;
48
+ /** The whole path's length. */
49
+ length: number;
50
+ /** Each row's stretch along the path: [start, end]. */
51
+ spans: [number, number][];
52
+ }
53
+
54
+ /** The rail for rows at these levels. */
55
+ export function anchorRail(levels: number[]): AnchorRail {
56
+ const n = levels.length;
57
+ if (!n) return { d: '', width: 0, height: 0, length: 0, spans: [] };
58
+ const x = levels.map(xAt);
59
+ const parts: string[] = [];
60
+ const spans: [number, number][] = [];
61
+ let length = 0;
62
+ let y = END;
63
+ parts.push(`M${round(x[0])} ${y}`);
64
+ for (let i = 0; i < n; i += 1) {
65
+ const bottom = (i + 1) * ANCHOR_ROW;
66
+ const bendsBelow = i < n - 1 && x[i + 1] !== x[i];
67
+ const straightEnd = i === n - 1 ? bottom - END : bendsBelow ? bottom - BEND : bottom;
68
+ const start = length;
69
+ length += straightEnd - y;
70
+ parts.push(`L${round(x[i])} ${straightEnd}`);
71
+ spans.push([round(start), round(length)]);
72
+ y = straightEnd;
73
+ if (bendsBelow) {
74
+ const p0 = [x[i], bottom - BEND]; const p1 = [x[i], bottom]; const p2 = [x[i + 1], bottom]; const p3 = [x[i + 1], bottom + BEND];
75
+ parts.push(`C${round(x[i])} ${bottom} ${round(x[i + 1])} ${bottom} ${round(x[i + 1])} ${bottom + BEND}`);
76
+ length += cubicLength(p0, p1, p2, p3);
77
+ y = bottom + BEND;
78
+ }
79
+ }
80
+ const width = Math.max(...x) + X0;
81
+ return { d: parts.join(''), width: round(width), height: n * ANCHOR_ROW, length: round(length), spans };
82
+ }
83
+
84
+ /** The dash that lights row `i`'s stretch: stroke-dasharray and stroke-dashoffset. */
85
+ export function anchorDash(rail: AnchorRail, i: number): { dasharray: string; dashoffset: number } {
86
+ const span = rail.spans[i];
87
+ if (!span) return { dasharray: `0 ${rail.length + 1}`, dashoffset: 0 };
88
+ return { dasharray: `${round(span[1] - span[0])} ${round(rail.length + 1)}`, dashoffset: -span[0] };
89
+ }
90
+
91
+ /** The id an "#id" href points at, or null for other links. */
92
+ export const anchorTarget = (href: string): string | null => (href.startsWith('#') && href.length > 1 ? decodeURIComponent(href.slice(1)) : null);
93
+
94
+ /**
95
+ * Which row is in view: the last section whose top has passed `offset` pixels
96
+ * below the top of the scroll area (the first one before any has), and the
97
+ * last one once the area is scrolled to its end.
98
+ */
99
+ export function anchorActive(items: AnchorItem[], offset: number, scrollRoot?: Element | null): number {
100
+ const ids = items.map((item) => anchorTarget(item.href));
101
+ const top = scrollRoot ? scrollRoot.getBoundingClientRect().top : 0;
102
+ const atEnd = scrollRoot
103
+ ? scrollRoot.scrollTop + scrollRoot.clientHeight >= scrollRoot.scrollHeight - 2
104
+ : window.innerHeight + window.scrollY >= document.documentElement.scrollHeight - 2;
105
+ let active = 0;
106
+ ids.forEach((id, i) => {
107
+ const el = id ? document.getElementById(id) : null;
108
+ if (el && el.getBoundingClientRect().top - top <= offset) active = i;
109
+ });
110
+ if (atEnd) {
111
+ for (let i = ids.length - 1; i >= 0; i -= 1) if (ids[i] && document.getElementById(ids[i] as string)) return i;
112
+ }
113
+ return active;
114
+ }
115
+
116
+ /** Scrolls a section into view (smoothly unless people asked for less motion) and moves focus to it. */
117
+ export function anchorGo(href: string, updateHash: boolean): boolean {
118
+ const id = anchorTarget(href);
119
+ const target = id ? document.getElementById(id) : null;
120
+ if (!target) return false;
121
+ const still = typeof window.matchMedia === 'function' && window.matchMedia('(prefers-reduced-motion: reduce)').matches;
122
+ target.scrollIntoView({ behavior: still ? 'auto' : 'smooth', block: 'start' });
123
+ if (!target.hasAttribute('tabindex')) target.setAttribute('tabindex', '-1');
124
+ target.focus({ preventScroll: true });
125
+ if (updateHash && typeof history !== 'undefined') history.replaceState(null, '', href);
126
+ return true;
127
+ }
@@ -0,0 +1,59 @@
1
+ Use it beside a long page, at the top right. Rows are links (`<nav>`, "On this page"), so Tab reaches each one and Enter goes there: the page scrolls to the section and focus moves to it. The row being read carries `aria-current="location"`, and the highlight slides to it as you scroll (instantly when the system asks for less motion). Long labels end in "…": the full label is the row's tooltip.
2
+
3
+ Scroll the box on the left: the highlight follows, bending in and out with the levels. Click a row to jump.
4
+ ```jsx
5
+ import { Anchor, Text, Title } from '@nurvus/ui';
6
+
7
+ const SECTIONS = [
8
+ { id: 'demo-preview', label: 'Preview', level: 1 },
9
+ { id: 'demo-install', label: 'Installation', level: 1 },
10
+ { id: 'demo-usage', label: 'Usage', level: 1 },
11
+ { id: 'demo-anatomy', label: 'Anatomy', level: 2 },
12
+ { id: 'demo-examples', label: 'Examples', level: 1 },
13
+ { id: 'demo-basic', label: 'Basic', level: 2 },
14
+ { id: 'demo-rail', label: 'Icon rail', level: 2 },
15
+ { id: 'demo-phone', label: 'On a phone', level: 3 },
16
+ { id: 'demo-api', label: 'API reference', level: 1 },
17
+ ];
18
+
19
+ <div style={ { display: 'grid', gridTemplateColumns: 'minmax(0, 1fr) 12rem', gap: 24 } }>
20
+ <div id="anchor-demo-box" style={ { height: 280, overflow: 'auto', padding: '0 16px', border: '1px solid var(--nv-border)', borderRadius: 12 } }>
21
+ { SECTIONS.map((s) => (
22
+ <section key={ s.id } style={ { minHeight: 160, paddingTop: 12 } }>
23
+ <Title level={ s.level + 2 } id={ s.id } style={ { scrollMarginTop: 8 } }>{ s.label }</Title>
24
+ <Text tone="muted">The { s.label.toLowerCase() } section.</Text>
25
+ </section>
26
+ )) }
27
+ </div>
28
+ <Anchor
29
+ id="anchor-demo"
30
+ scrollRoot="#anchor-demo-box"
31
+ offset={ 24 }
32
+ updateHash={ false }
33
+ items={ SECTIONS.map((s) => ({ href: `#${s.id}`, label: s.label, level: s.level })) }
34
+ />
35
+ </div>
36
+ ```
37
+
38
+ Set the section yourself with `current` (for a page that tracks it already, or a demo).
39
+ ```jsx
40
+ import { Anchor, Button, Layout } from '@nurvus/ui';
41
+
42
+ const ITEMS = [
43
+ { href: '#a', label: 'Overview' },
44
+ { href: '#b', label: 'Install', level: 2 },
45
+ { href: '#c', label: 'Configure', level: 2 },
46
+ { href: '#d', label: 'Deploy' },
47
+ ];
48
+
49
+ const Controlled = () => {
50
+ const [at, setAt] = React.useState(0);
51
+ return (
52
+ <Layout display="flex" itemSpacing={ 32 } alignItems="flex-start">
53
+ <Anchor id="anchor-set" current={ ITEMS[at].href } items={ ITEMS } onNavigate={ (href, event) => { event.preventDefault(); setAt(ITEMS.findIndex((i) => i.href === href)); } } />
54
+ <Button size="small" type="secondary" onClick={ () => setAt((at + 1) % ITEMS.length) }>Next section</Button>
55
+ </Layout>
56
+ );
57
+ };
58
+ <Controlled />
59
+ ```
@@ -0,0 +1,65 @@
1
+ // Styles for Anchor (React and Respawn: same markup). Rows are exactly 1.75rem
2
+ // tall so the rail (drawn from the items, src/anchor.ts) lines up with them.
3
+ @import "../../styles/variables.scss";
4
+
5
+ .#{$cls-prefix}.anchor {
6
+ font-size: 0.8125rem;
7
+ line-height: 1.25rem;
8
+
9
+ .anchor-title {
10
+ margin: 0 0 var(--space--8);
11
+ color: var(--nv-text);
12
+ font-size: 0.8125rem;
13
+ font-weight: 600;
14
+ }
15
+
16
+ .anchor-body { position: relative; }
17
+
18
+ .anchor-rail {
19
+ position: absolute;
20
+ top: 0;
21
+ left: 0;
22
+ overflow: visible;
23
+ fill: none;
24
+ stroke-linecap: round;
25
+ }
26
+
27
+ .anchor-track { stroke: var(--nv-border-strong); stroke-width: 1; }
28
+
29
+ // The highlight: the same path, a dash over the section in view, sliding.
30
+ .anchor-thumb {
31
+ stroke: var(--nv-accent);
32
+ stroke-width: 2;
33
+ transition: stroke-dasharray 0.35s cubic-bezier(0.4, 0, 0.2, 1), stroke-dashoffset 0.35s cubic-bezier(0.4, 0, 0.2, 1);
34
+ }
35
+
36
+ .anchor-list {
37
+ margin: 0;
38
+ padding: 0;
39
+ list-style: none;
40
+ }
41
+
42
+ li { padding-left: calc(var(--anchor-level, 0) * 0.75rem + 1rem); }
43
+
44
+ .anchor-link {
45
+ display: block;
46
+ height: 1.75rem;
47
+ overflow: hidden;
48
+ border-radius: 0.25rem;
49
+ color: var(--nv-text-muted);
50
+ line-height: 1.75rem;
51
+ text-decoration: none;
52
+ text-overflow: ellipsis;
53
+ white-space: nowrap;
54
+ transition: color 0.2s ease;
55
+
56
+ &:hover { color: var(--nv-text); }
57
+ &:focus-visible { outline: 2px solid var(--nv-accent); outline-offset: -2px; }
58
+ &[data-active="true"] { color: var(--nv-text); font-weight: 500; }
59
+ }
60
+ }
61
+
62
+ @media (prefers-reduced-motion: reduce) {
63
+ .#{$cls-prefix}.anchor .anchor-thumb,
64
+ .#{$cls-prefix}.anchor .anchor-link { transition: none; }
65
+ }
@@ -0,0 +1,105 @@
1
+ import React from 'react';
2
+ import classNames from 'classnames';
3
+ import CONSTANT from '../../constants';
4
+ import { AnchorItem, anchorRail, anchorDash, anchorActive, anchorGo } from '../../anchor';
5
+ import './Anchor.scss';
6
+
7
+ export type { AnchorItem };
8
+
9
+ export interface AnchorProps extends Omit<React.HTMLAttributes<HTMLElement>, 'title'> {
10
+ /** The sections, in page order: each an "#id" href, a label and a level (1, 2…). */
11
+ items: AnchorItem[];
12
+ /** The heading above the list. */
13
+ title?: string;
14
+ /** Prefix for the ids inside (the title is "<id>-title"). Defaults to "anchor". */
15
+ id?: string;
16
+ /** How far below the top a section's heading must be scrolled to count as "in view", in pixels (room for a sticky header). */
17
+ offset?: number;
18
+ /** The section in view, set by you (its href). Left out, the Anchor follows the scrolling itself. */
19
+ current?: string;
20
+ /** Scroll-spy inside this element instead of the page: an element or a CSS selector. */
21
+ scrollRoot?: Element | string;
22
+ /** Writes the section's #id in the address bar when one is picked. Turn off for hash routers. */
23
+ updateHash?: boolean;
24
+ /** Called when a row is picked, with its href. Call event.preventDefault() to handle it yourself. */
25
+ onNavigate?: (href: string, event: React.MouseEvent<HTMLAnchorElement>) => void;
26
+ /** Custom class name. */
27
+ className?: string;
28
+ }
29
+
30
+ const rootOf = (scrollRoot?: Element | string): Element | null => (typeof scrollRoot === 'string' ? document.querySelector(scrollRoot) : scrollRoot || null);
31
+
32
+ /**
33
+ * "On this page": the sections of a long page, the one being read marked as
34
+ * you scroll. A rail runs down beside the rows, bending in and out with the
35
+ * nesting, and a highlight slides along it to the section in view. Picking a
36
+ * row scrolls to the section and moves focus there.
37
+ */
38
+ export default function Anchor({
39
+ items,
40
+ title = 'On this page',
41
+ id = 'anchor',
42
+ offset = 96,
43
+ current,
44
+ scrollRoot,
45
+ updateHash = true,
46
+ onNavigate,
47
+ className,
48
+ ...restProps
49
+ }: AnchorProps) {
50
+ const [spied, setSpied] = React.useState(0);
51
+ const controlled = current !== undefined;
52
+ const active = controlled ? Math.max(0, items.findIndex((item) => item.href === current)) : spied;
53
+ const rail = anchorRail(items.map((item) => item.level || 1));
54
+ const dash = anchorDash(rail, active);
55
+
56
+ // Follow the scrolling (unless the section in view is set from outside).
57
+ const list = React.useRef(items);
58
+ list.current = items;
59
+ const hrefs = items.map((item) => item.href).join(' ');
60
+ React.useEffect(() => {
61
+ if (controlled || typeof window === 'undefined') return undefined;
62
+ const root = rootOf(scrollRoot);
63
+ let frame = 0;
64
+ const update = () => { cancelAnimationFrame(frame); frame = requestAnimationFrame(() => setSpied(anchorActive(list.current, offset, root))); };
65
+ update();
66
+ const target: EventTarget = root || window;
67
+ target.addEventListener('scroll', update, { passive: true });
68
+ window.addEventListener('resize', update);
69
+ return () => { cancelAnimationFrame(frame); target.removeEventListener('scroll', update); window.removeEventListener('resize', update); };
70
+ }, [controlled, hrefs, offset, scrollRoot]);
71
+
72
+ const go = (href: string, i: number) => (event: React.MouseEvent<HTMLAnchorElement>) => {
73
+ if (onNavigate) onNavigate(href, event);
74
+ if (event.defaultPrevented) return;
75
+ if (anchorGo(href, updateHash)) { event.preventDefault(); if (!controlled) setSpied(i); }
76
+ };
77
+
78
+ return (
79
+ <nav className={ classNames(className, 'anchor', CONSTANT.CLASS_PREFIX) } aria-labelledby={ `${id}-title` } { ...restProps }>
80
+ <p className="anchor-title" id={ `${id}-title` }>{ title }</p>
81
+ <div className="anchor-body">
82
+ <svg className="anchor-rail" viewBox={ `0 0 ${rail.width} ${rail.height}` } style={ { width: `${rail.width / 16}rem`, height: `${rail.height / 16}rem` } } aria-hidden="true" focusable="false">
83
+ <path className="anchor-track" d={ rail.d } />
84
+ <path className="anchor-thumb" d={ rail.d } style={ { strokeDasharray: dash.dasharray, strokeDashoffset: dash.dashoffset } } />
85
+ </svg>
86
+ <ul className="anchor-list">
87
+ { items.map((item, i) => (
88
+ <li key={ item.href } style={ { '--anchor-level': String((item.level || 1) - 1) } as React.CSSProperties }>
89
+ <a
90
+ className="anchor-link"
91
+ href={ item.href }
92
+ title={ item.label }
93
+ data-active={ i === active }
94
+ aria-current={ i === active ? 'location' : undefined }
95
+ onClick={ go(item.href, i) }
96
+ >
97
+ { item.label }
98
+ </a>
99
+ </li>
100
+ )) }
101
+ </ul>
102
+ </div>
103
+ </nav>
104
+ );
105
+ }
@@ -0,0 +1,48 @@
1
+ Screen readers hear "Actions, menu button, collapsed"; once it opens, the menu and its items ("Duplicate, menu item"). A disabled action stays in the list, so people still find it, but does nothing.
2
+
3
+ ```jsx
4
+ import { Dropdown, Text } from '@nurvus/ui';
5
+
6
+ const Demo = () => {
7
+ const [done, setDone] = React.useState('Nothing yet');
8
+ const run = (what) => () => setDone(what);
9
+ return (
10
+ <div style={ { display: 'flex', alignItems: 'center', gap: 16 } }>
11
+ <Dropdown
12
+ id="file-actions"
13
+ label="Actions"
14
+ sections={ [
15
+ { title: 'File', items: [
16
+ { label: 'Duplicate', onSelect: run('Duplicated') },
17
+ { label: 'Rename', onSelect: run('Renamed') },
18
+ { label: 'Move to…', onSelect: run('Moved'), disabled: true },
19
+ ] },
20
+ { items: [{ label: 'Delete', onSelect: run('Deleted') }] },
21
+ ] }
22
+ />
23
+ <Text tone="muted">{ done }</Text>
24
+ </div>
25
+ );
26
+ };
27
+ <Demo />
28
+ ```
29
+
30
+ A flat list with `items`, lined up with the button's right edge (`align="end"`), and an icon-only button: give the icon a `label` so the button has a name.
31
+ ```jsx
32
+ import { Dropdown, Icon } from '@nurvus/ui';
33
+
34
+ <div style={ { display: 'flex', justifyContent: 'flex-end' } }>
35
+ <Dropdown
36
+ id="row-actions"
37
+ label={ <Icon name="more-horizontal" label="More actions" size="1.25em" /> }
38
+ align="end"
39
+ type="secondary"
40
+ size="small"
41
+ items={ [
42
+ { label: 'Share', onSelect: () => {} },
43
+ { label: 'Download', onSelect: () => {} },
44
+ { label: 'Archive', onSelect: () => {} },
45
+ ] }
46
+ />
47
+ </div>
48
+ ```