@baukit/navigation 0.7.1 → 0.7.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,34 @@
1
+ import { useEffect, useReducer } from 'react';
2
+ import { navigationReducer, resolveActiveNavigation, type NavigationItem } from './index.js';
3
+
4
+ export interface CollapseProps {
5
+ readonly collapsed?: boolean;
6
+ readonly defaultCollapsed?: boolean;
7
+ readonly onCollapsedChange?: (collapsed: boolean) => void;
8
+ }
9
+
10
+ export function useNavigationState<Icon>(
11
+ items: readonly NavigationItem<Icon>[],
12
+ pathname: string,
13
+ props: CollapseProps,
14
+ ) {
15
+ const active = resolveActiveNavigation(items, pathname);
16
+ const activeId = active.item?.children?.length ? active.item.id : null;
17
+ const [state, dispatch] = useReducer(navigationReducer, {
18
+ collapsed: props.defaultCollapsed ?? false,
19
+ openIds: activeId === null ? [] : [activeId],
20
+ });
21
+ useEffect(() => {
22
+ dispatch({ type: 'enter-section', id: activeId });
23
+ }, [activeId]);
24
+ const collapsed = props.collapsed ?? state.collapsed;
25
+ function setCollapsed(value: boolean) {
26
+ dispatch({ type: 'set-collapsed', collapsed: value });
27
+ props.onCollapsedChange?.(value);
28
+ }
29
+ function toggleGroup(id: string) {
30
+ if (collapsed) setCollapsed(false);
31
+ dispatch({ type: 'toggle-group', id, collapsed });
32
+ }
33
+ return { active, collapsed, openIds: state.openIds, setCollapsed, toggleGroup };
34
+ }
@@ -0,0 +1,4 @@
1
+ declare module '*.css?raw' {
2
+ const stylesheet: string;
3
+ export default stylesheet;
4
+ }
@@ -0,0 +1,460 @@
1
+ import { afterEach, expect, it, vi } from 'vitest';
2
+ import { page, userEvent } from 'vitest/browser';
3
+ import { createRoot, type Root } from 'react-dom/client';
4
+ import { act, useState } from 'react';
5
+ import axe from 'axe-core';
6
+ import { exampleTokens, toCssVariables } from '@baukit/ui-tokens';
7
+ import { useReducedMotionPreference } from '@baukit/a11y-core/web';
8
+ import { AppNavigation, SectionPicker, type NavigationIcon } from './web.js';
9
+ import stylesheet from './web.css?raw';
10
+ Object.assign(globalThis, { IS_REACT_ACT_ENVIRONMENT: true });
11
+
12
+ const labels = {
13
+ label: 'Primary',
14
+ collapseLabel: 'Collapse navigation',
15
+ expandLabel: 'Expand navigation',
16
+ closeLabel: 'Close',
17
+ };
18
+
19
+ const icon: NavigationIcon = () => (
20
+ <svg width="24" height="24" viewBox="0 0 24 24">
21
+ <path d="M4 4h16v16H4z" fill="currentColor" />
22
+ </svg>
23
+ );
24
+ const section = {
25
+ id: 'progress',
26
+ label: 'Progress',
27
+ href: '/progress',
28
+ icon,
29
+ children: [
30
+ { id: 'overview', label: 'Overview', href: '/progress' },
31
+ { id: 'history', label: 'History', href: '/progress/history' },
32
+ ],
33
+ };
34
+ const items = [{ id: 'home', label: 'Home', href: '/', icon }, section];
35
+ let root: Root | undefined;
36
+ let host: HTMLDivElement | undefined;
37
+ let styles: HTMLStyleElement | undefined;
38
+ function Fixture() {
39
+ const [collapsed, setCollapsed] = useState(false);
40
+ const { reducedMotion, resolved } = useReducedMotionPreference();
41
+ return (
42
+ <div>
43
+ <AppNavigation
44
+ {...labels}
45
+ items={items}
46
+ pathname="/progress/history"
47
+ collapsed={collapsed}
48
+ onCollapsedChange={setCollapsed}
49
+ profile={{ label: 'Account', initials: 'AB', href: '/profile' }}
50
+ />
51
+ <main
52
+ style={{
53
+ padding: '8px',
54
+ marginLeft: window.innerWidth >= 1024 ? (collapsed ? 76 : 280) : 0,
55
+ transition:
56
+ resolved && !reducedMotion
57
+ ? 'margin-left var(--bk-motion-duration-normal) var(--bk-motion-easing-standard)'
58
+ : undefined,
59
+ paddingBottom: 80,
60
+ }}
61
+ >
62
+ <h1>Navigation fixture</h1>
63
+ <SectionPicker item={section} pathname="/progress/history" />
64
+ <button type="button" style={{ minWidth: 44, minHeight: 44 }}>
65
+ Primary action
66
+ </button>
67
+ </main>
68
+ </div>
69
+ );
70
+ }
71
+ afterEach(async () => {
72
+ await act(() => {
73
+ root?.unmount();
74
+ return Promise.resolve();
75
+ });
76
+ host?.remove();
77
+ styles?.remove();
78
+ delete document.documentElement.dataset['theme'];
79
+ vi.restoreAllMocks();
80
+ });
81
+ it.each(
82
+ [320, 1023, 1024].flatMap((width) =>
83
+ [568, 720].flatMap((height) => ['light', 'dark'].map((theme) => ({ width, height, theme }))),
84
+ ),
85
+ )(
86
+ 'lays out accessible $theme navigation at $width by $height',
87
+ async ({ width, height, theme }) => {
88
+ const errors: unknown[][] = [];
89
+ vi.spyOn(console, 'warn').mockImplementation((...args: unknown[]) => {
90
+ errors.push(args);
91
+ });
92
+ vi.spyOn(console, 'error').mockImplementation((...args: unknown[]) => {
93
+ errors.push(args);
94
+ });
95
+ await page.viewport(width, height);
96
+ document.documentElement.lang = 'en';
97
+ document.title = 'Navigation fixture';
98
+ document.documentElement.dataset['theme'] = theme;
99
+ styles = document.createElement('style');
100
+ styles.textContent = `${toCssVariables(exampleTokens)} ${stylesheet} body {margin:0;background:var(--bk-color-background-primary);color:var(--bk-color-text-primary);} *{box-sizing:border-box;}`;
101
+ document.head.append(styles);
102
+ host = document.createElement('div');
103
+ document.body.append(host);
104
+ root = createRoot(host);
105
+ await act(() => {
106
+ root?.render(<Fixture />);
107
+ return Promise.resolve();
108
+ });
109
+ const navigation = document.querySelector<HTMLElement>('.bk-navigation');
110
+ if (navigation === null) throw new Error('Navigation did not render');
111
+ expect(navigation.dataset['layout']).toBe(width >= 1024 ? 'rail' : 'bar');
112
+ expect(document.documentElement.scrollWidth).toBeLessThanOrEqual(width);
113
+ const activeLink = page
114
+ .getByRole('link', { name: width >= 1024 ? 'History' : 'Progress' })
115
+ .element();
116
+ function filledRows() {
117
+ return Array.from(
118
+ navigation?.querySelectorAll<HTMLElement>('.bk-navigation-item') ?? [],
119
+ ).filter(
120
+ (item) =>
121
+ item.closest('[hidden]') === null &&
122
+ getComputedStyle(item).backgroundColor !== 'rgba(0, 0, 0, 0)',
123
+ );
124
+ }
125
+ expect(filledRows()).toEqual([activeLink]);
126
+ expect(activeLink.getAttribute('data-active')).toBe('page');
127
+ expect(getComputedStyle(activeLink).borderWidth).toBe('0px');
128
+ expect(getComputedStyle(activeLink).fontWeight).toBe('700');
129
+ await act(async () => {
130
+ await userEvent.tab();
131
+ activeLink.focus();
132
+ });
133
+ expect(activeLink.matches(':focus-visible')).toBe(true);
134
+ const focusedStyle = getComputedStyle(activeLink);
135
+ expect(focusedStyle.outlineColor).not.toBe(focusedStyle.backgroundColor);
136
+ expect(Number.parseFloat(focusedStyle.outlineWidth)).toBeGreaterThanOrEqual(3);
137
+ expect(Number.parseFloat(focusedStyle.outlineOffset)).toBe(2);
138
+ const profile = page.getByRole('link', { name: 'Account' }).element().getBoundingClientRect();
139
+ const navBox = navigation.getBoundingClientRect();
140
+ if (width >= 1024) {
141
+ expect(navBox.width).toBe(280);
142
+ expect(profile.bottom).toBeGreaterThan(height - 60);
143
+ const parent = page.getByRole('button', { name: 'Progress' }).element();
144
+ expect(parent.getAttribute('data-active')).toBe('ancestor');
145
+ expect(getComputedStyle(parent).backgroundColor).toBe('rgba(0, 0, 0, 0)');
146
+ expect(getComputedStyle(parent).color).toBe(getComputedStyle(activeLink).color);
147
+ const group = parent.nextElementSibling;
148
+ expect(group?.getAttribute('role')).toBe('group');
149
+ const history = page.getByRole('link', { name: 'History' }).element().getBoundingClientRect();
150
+ expect(history.top).toBeGreaterThanOrEqual(parent.getBoundingClientRect().bottom);
151
+ expect(history.left).toBeGreaterThan(parent.getBoundingClientRect().left);
152
+ await act(async () => {
153
+ await page.getByRole('button', { name: 'Collapse navigation' }).click();
154
+ });
155
+ expect(
156
+ page.getByRole('button', { name: 'Primary action' }).element().getBoundingClientRect().left,
157
+ ).toBeGreaterThanOrEqual(navigation.getBoundingClientRect().right);
158
+ await expect.poll(() => navigation.getBoundingClientRect().width).toBe(76);
159
+ await act(async () => {
160
+ await userEvent.tab();
161
+ parent.focus();
162
+ });
163
+ expect(parent.matches(':focus-visible')).toBe(true);
164
+ const parentStyle = getComputedStyle(parent);
165
+ expect(Number.parseFloat(parentStyle.outlineOffset)).toBe(2);
166
+ const ringExtent = Number.parseFloat(parentStyle.outlineWidth) + 2;
167
+ const parentBox = parent.getBoundingClientRect();
168
+ const scrollBox = navigation.querySelector('.bk-navigation-items')?.getBoundingClientRect();
169
+ if (scrollBox === undefined) throw new Error('Navigation scroll container did not render');
170
+ expect(parentBox.left - ringExtent).toBeGreaterThanOrEqual(scrollBox.left);
171
+ expect(parentBox.right + ringExtent).toBeLessThanOrEqual(scrollBox.right);
172
+ expect(parentBox.top - ringExtent).toBeGreaterThanOrEqual(scrollBox.top);
173
+ expect(filledRows()).toEqual([parent]);
174
+ expect(parent.getAttribute('data-active')).toBe('page');
175
+ expect(page.getByRole('button', { name: 'Progress' }).element().getAttribute('title')).toBe(
176
+ 'Progress',
177
+ );
178
+ } else {
179
+ const progress = page
180
+ .getByRole('link', { name: 'Progress' })
181
+ .element()
182
+ .getBoundingClientRect();
183
+ expect(profile.left).toBeGreaterThanOrEqual(progress.right);
184
+ expect(navBox.bottom).toBe(height);
185
+ }
186
+ const action = page
187
+ .getByRole('button', { name: 'Primary action' })
188
+ .element()
189
+ .getBoundingClientRect();
190
+ expect(
191
+ width >= 1024
192
+ ? action.left >= navigation.getBoundingClientRect().right
193
+ : action.bottom <= navBox.top,
194
+ ).toBe(true);
195
+ for (const target of host.querySelectorAll<HTMLElement>('a, button')) {
196
+ if (target.closest('[hidden]') !== null) continue;
197
+ const box = target.getBoundingClientRect();
198
+ expect(box.width).toBeGreaterThanOrEqual(44);
199
+ expect(box.height).toBeGreaterThanOrEqual(44);
200
+ expect(box.left).toBeGreaterThanOrEqual(0);
201
+ expect(box.right).toBeLessThanOrEqual(width);
202
+ }
203
+ expect((await axe.run(host)).violations).toEqual([]);
204
+ expect(errors).toEqual([]);
205
+ },
206
+ );
207
+
208
+ it('keeps a long compact section menu between its picker and the bottom bar', async () => {
209
+ await page.viewport(320, 568);
210
+ const cost = {
211
+ id: 'cost',
212
+ label: 'Cost',
213
+ href: '/cost',
214
+ icon,
215
+ children: Array.from({ length: 14 }, (_, index) => ({
216
+ id: `cost-${String(index + 1)}`,
217
+ label: `Cost page ${String(index + 1)}`,
218
+ href: `/cost/${String(index + 1)}`,
219
+ })),
220
+ };
221
+ styles = document.createElement('style');
222
+ styles.textContent = `${toCssVariables(exampleTokens)} ${stylesheet} body{margin:0} *{box-sizing:border-box}`;
223
+ document.head.append(styles);
224
+ host = document.createElement('div');
225
+ document.body.append(host);
226
+ root = createRoot(host);
227
+ await act(() => {
228
+ root?.render(
229
+ <>
230
+ <AppNavigation
231
+ {...labels}
232
+ items={[cost]}
233
+ pathname="/cost/1"
234
+ profile={{ label: 'Account', initials: 'AB', href: '/profile' }}
235
+ />
236
+ <main style={{ padding: 8, paddingTop: 200 }}>
237
+ <SectionPicker item={cost} pathname="/cost/1" />
238
+ </main>
239
+ </>,
240
+ );
241
+ return Promise.resolve();
242
+ });
243
+ const trigger = page.getByRole('button', { name: 'Cost, Cost page 1' });
244
+ await act(async () => trigger.click());
245
+ const menu = page.getByRole('menu', { name: 'Cost' }).element();
246
+ const navigation = document.querySelector('.bk-navigation');
247
+ if (navigation === null) throw new Error('Bottom navigation did not render');
248
+ function expectBounds() {
249
+ const menuBox = menu.getBoundingClientRect();
250
+ expect(menuBox.top).toBeGreaterThanOrEqual(
251
+ trigger.element().getBoundingClientRect().bottom + 8,
252
+ );
253
+ expect(menuBox.bottom).toBeLessThanOrEqual(navigation?.getBoundingClientRect().top ?? 0);
254
+ expect(menu.scrollHeight).toBeGreaterThan(menu.clientHeight);
255
+ expect(getComputedStyle(menu).overflowY).toBe('auto');
256
+ }
257
+ expectBounds();
258
+ await act(async () => userEvent.keyboard('{End}'));
259
+ const last = page.getByRole('menuitem', { name: 'Cost page 14' }).element();
260
+ expect(document.activeElement).toBe(last);
261
+ expect(last.getBoundingClientRect().bottom).toBeLessThanOrEqual(
262
+ menu.getBoundingClientRect().bottom,
263
+ );
264
+ expect(menu.scrollTop).toBeGreaterThan(0);
265
+ await act(async () => {
266
+ await page.viewport(320, 480);
267
+ await new Promise<void>((resolve) =>
268
+ requestAnimationFrame(() => {
269
+ requestAnimationFrame(() => {
270
+ resolve();
271
+ });
272
+ }),
273
+ );
274
+ });
275
+ await expect
276
+ .poll(() => menu.getBoundingClientRect().bottom <= navigation.getBoundingClientRect().top)
277
+ .toBe(true);
278
+ expectBounds();
279
+ const main = host.querySelector('main');
280
+ if (main === null) throw new Error('Main content did not render');
281
+ await act(async () => {
282
+ main.style.paddingTop = '240px';
283
+ await new Promise<void>((resolve) =>
284
+ requestAnimationFrame(() => {
285
+ requestAnimationFrame(() => {
286
+ resolve();
287
+ });
288
+ }),
289
+ );
290
+ });
291
+ await expect
292
+ .poll(() => menu.getBoundingClientRect().bottom <= navigation.getBoundingClientRect().top)
293
+ .toBe(true);
294
+ expectBounds();
295
+ });
296
+
297
+ it('ellipsizes long labels inside all six compact targets at 320 pixels', async () => {
298
+ await page.viewport(320, 568);
299
+ styles = document.createElement('style');
300
+ styles.textContent = `${toCssVariables(exampleTokens)} ${stylesheet} body{margin:0}`;
301
+ document.head.append(styles);
302
+ host = document.createElement('div');
303
+ document.body.append(host);
304
+ root = createRoot(host);
305
+ await act(() => {
306
+ root?.render(
307
+ <AppNavigation
308
+ {...labels}
309
+ items={Array.from({ length: 5 }, (_, index) => ({
310
+ id: `section-${String(index)}`,
311
+ label: `Arbeitsbereich mit langem Namen ${String(index)}`,
312
+ href: `/section/${String(index)}`,
313
+ icon,
314
+ }))}
315
+ pathname="/section/0"
316
+ profile={{ label: 'Profil und persönliche Daten', initials: 'AB', href: '/profile' }}
317
+ />,
318
+ );
319
+ return Promise.resolve();
320
+ });
321
+ const targets = host.querySelectorAll<HTMLElement>('.bk-navigation-item');
322
+ expect(targets).toHaveLength(6);
323
+ for (const target of targets) {
324
+ const label = target.querySelector<HTMLElement>('.bk-navigation-label');
325
+ if (label === null) throw new Error('Target label did not render');
326
+ const box = target.getBoundingClientRect();
327
+ const labelBox = label.getBoundingClientRect();
328
+ expect(box.width).toBeGreaterThanOrEqual(44);
329
+ expect(box.height).toBeGreaterThanOrEqual(44);
330
+ expect(labelBox.left).toBeGreaterThanOrEqual(box.left);
331
+ expect(labelBox.right).toBeLessThanOrEqual(box.right);
332
+ expect(label.scrollWidth).toBeGreaterThan(label.clientWidth);
333
+ expect(getComputedStyle(label).textOverflow).toBe('ellipsis');
334
+ expect(getComputedStyle(label).overflow).toBe('hidden');
335
+ expect(target.getAttribute('aria-label')).toBe(label.textContent);
336
+ }
337
+ expect(document.documentElement.scrollWidth).toBeLessThanOrEqual(320);
338
+ });
339
+
340
+ it('keeps custom profile avatars decorative and preserves subtitles and menu focus', async () => {
341
+ const errors: unknown[][] = [];
342
+ vi.spyOn(console, 'error').mockImplementation((...args: unknown[]) => {
343
+ errors.push(args);
344
+ });
345
+ vi.spyOn(console, 'warn').mockImplementation((...args: unknown[]) => {
346
+ errors.push(args);
347
+ });
348
+ await page.viewport(1024, 720);
349
+ styles = document.createElement('style');
350
+ styles.textContent = `${toCssVariables(exampleTokens)} ${stylesheet}`;
351
+ document.head.append(styles);
352
+ host = document.createElement('div');
353
+ document.body.append(host);
354
+ root = createRoot(host);
355
+ await act(() => {
356
+ root?.render(
357
+ <AppNavigation
358
+ {...labels}
359
+ items={items}
360
+ pathname="/"
361
+ width={1024}
362
+ profile={{
363
+ label: 'Account',
364
+ subtitle: 'Ada, synced',
365
+ initials: 'AD',
366
+ renderAvatar: ({ size }) => (
367
+ <span
368
+ role="img"
369
+ aria-label="Product glyph"
370
+ tabIndex={0}
371
+ data-testid="profile-glyph"
372
+ style={{ width: size, height: size, border: '2px solid currentColor' }}
373
+ >
374
+ A
375
+ </span>
376
+ ),
377
+ menu: [{ id: 'settings', label: 'Settings', href: '/settings' }],
378
+ }}
379
+ />,
380
+ );
381
+ return Promise.resolve();
382
+ });
383
+ const subtitle = page.getByText('Ada, synced', { exact: true });
384
+ await expect.element(subtitle).toBeVisible();
385
+ await act(async () => {
386
+ await userEvent.click(page.getByRole('button', { name: 'Collapse navigation' }));
387
+ });
388
+ await expect.element(subtitle).not.toBeVisible();
389
+ const trigger = page.getByRole('button', { name: 'Account, Ada, synced' });
390
+ await expect.element(trigger).toBeVisible();
391
+ await expect.element(page.getByTestId('profile-glyph')).toBeVisible();
392
+ await expect.element(page.getByRole('img', { name: 'Product glyph' })).not.toBeInTheDocument();
393
+ act(() => {
394
+ trigger.element().focus();
395
+ page.getByTestId('profile-glyph').element().focus();
396
+ });
397
+ await expect.element(trigger).toHaveFocus();
398
+ const avatar = page.getByTestId('profile-glyph').element().parentElement;
399
+ expect(avatar).not.toBeNull();
400
+ if (avatar === null) throw new Error('Avatar wrapper is missing');
401
+ expect(getComputedStyle(avatar).backgroundColor).toBe('rgba(0, 0, 0, 0)');
402
+ await act(async () => {
403
+ await userEvent.click(trigger);
404
+ });
405
+ await expect
406
+ .element(
407
+ page
408
+ .getByRole('menu', { name: 'Account, Ada, synced' })
409
+ .getByText('Ada, synced', { exact: true }),
410
+ )
411
+ .toBeVisible();
412
+ await expect.element(page.getByRole('menuitem', { name: 'Settings' })).toHaveFocus();
413
+ await act(async () => {
414
+ await userEvent.keyboard('{Escape}');
415
+ });
416
+ await expect.element(trigger).toHaveFocus();
417
+ expect(errors).toEqual([]);
418
+ });
419
+
420
+ it.each([600, 1024])('tabs into a visible Insights parent at width %s', async (width) => {
421
+ await page.viewport(width, 720);
422
+ host = document.createElement('div');
423
+ document.body.append(host);
424
+ root = createRoot(host);
425
+ const insights = {
426
+ id: 'insights',
427
+ label: 'Insights',
428
+ href: '/insights',
429
+ icon,
430
+ children: [{ id: 'charts', label: 'Charts', href: '/insights/charts' }],
431
+ };
432
+ await act(() => {
433
+ root?.render(
434
+ <>
435
+ <button type="button">Before navigation</button>
436
+ <AppNavigation
437
+ {...labels}
438
+ width={width}
439
+ defaultCollapsed
440
+ items={[{ id: 'home', label: 'Home', href: '/', icon }, insights]}
441
+ pathname="/insights/charts?range=4w"
442
+ />
443
+ </>,
444
+ );
445
+ return Promise.resolve();
446
+ });
447
+ page.getByRole('button', { name: 'Before navigation' }).element().focus();
448
+ await act(async () => {
449
+ await userEvent.keyboard('{Tab}');
450
+ });
451
+ if (width === 1024) {
452
+ await expect.element(page.getByRole('button', { name: 'Expand navigation' })).toHaveFocus();
453
+ await act(async () => {
454
+ await userEvent.keyboard('{Tab}');
455
+ });
456
+ }
457
+ await expect
458
+ .element(page.getByRole(width === 1024 ? 'button' : 'link', { name: 'Insights' }))
459
+ .toHaveFocus();
460
+ });