@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.
- package/README.md +24 -6
- package/dist/index.d.ts +13 -0
- package/dist/index.d.ts.map +1 -1
- package/dist/index.js +20 -2
- package/dist/index.js.map +1 -1
- package/dist/native.d.ts +19 -5
- package/dist/native.d.ts.map +1 -1
- package/dist/native.js +194 -89
- package/dist/native.js.map +1 -1
- package/dist/web.css +28 -0
- package/dist/web.css.d.ts +1 -0
- package/dist/web.d.ts +3 -3
- package/dist/web.d.ts.map +1 -1
- package/dist/web.js +47 -42
- package/dist/web.js.map +1 -1
- package/package.json +10 -5
- package/src/index.test.ts +226 -0
- package/src/index.ts +189 -0
- package/src/native.browser.test.tsx +183 -0
- package/src/native.test.tsx +833 -0
- package/src/native.tsx +970 -0
- package/src/use-navigation-state.ts +34 -0
- package/src/web-css.d.ts +4 -0
- package/src/web.browser.test.tsx +460 -0
- package/src/web.css +257 -0
- package/src/web.css.d.ts +1 -0
- package/src/web.test.tsx +483 -0
- package/src/web.tsx +618 -0
package/src/index.ts
ADDED
|
@@ -0,0 +1,189 @@
|
|
|
1
|
+
import { getLayoutMode } from '@baukit/ui-tokens';
|
|
2
|
+
import type { ReactNode } from 'react';
|
|
3
|
+
|
|
4
|
+
export interface NavigationSubItem<Icon = unknown> {
|
|
5
|
+
readonly id: string;
|
|
6
|
+
readonly label: string;
|
|
7
|
+
readonly href: string;
|
|
8
|
+
readonly icon?: Icon;
|
|
9
|
+
readonly matches?: (pathname: string) => boolean;
|
|
10
|
+
}
|
|
11
|
+
|
|
12
|
+
export interface NavigationItem<Icon = unknown> extends NavigationSubItem<Icon> {
|
|
13
|
+
readonly icon: Icon;
|
|
14
|
+
readonly children?: readonly NavigationSubItem<Icon>[];
|
|
15
|
+
}
|
|
16
|
+
|
|
17
|
+
export type NavigationProfileMenuEntry = {
|
|
18
|
+
readonly id: string;
|
|
19
|
+
readonly label: string;
|
|
20
|
+
readonly disabled?: boolean;
|
|
21
|
+
} & (
|
|
22
|
+
| {
|
|
23
|
+
readonly href: string;
|
|
24
|
+
readonly matches?: (pathname: string) => boolean;
|
|
25
|
+
readonly onSelect?: never;
|
|
26
|
+
}
|
|
27
|
+
| { readonly onSelect: () => void; readonly href?: never }
|
|
28
|
+
);
|
|
29
|
+
|
|
30
|
+
export interface NavigationAvatarState {
|
|
31
|
+
readonly active: boolean;
|
|
32
|
+
readonly size: number;
|
|
33
|
+
}
|
|
34
|
+
|
|
35
|
+
export type NavigationProfile = {
|
|
36
|
+
readonly label: string;
|
|
37
|
+
readonly subtitle?: string;
|
|
38
|
+
readonly initials: string;
|
|
39
|
+
readonly imageUrl?: string;
|
|
40
|
+
readonly renderAvatar?: (state: NavigationAvatarState) => ReactNode;
|
|
41
|
+
} & (
|
|
42
|
+
| { readonly href: string; readonly menu?: never }
|
|
43
|
+
| { readonly menu: readonly NavigationProfileMenuEntry[]; readonly href?: never }
|
|
44
|
+
);
|
|
45
|
+
|
|
46
|
+
export function getNavigationProfileLabel(profile: NavigationProfile): string {
|
|
47
|
+
return profile.subtitle === undefined || profile.subtitle.trim() === ''
|
|
48
|
+
? profile.label
|
|
49
|
+
: `${profile.label}, ${profile.subtitle}`;
|
|
50
|
+
}
|
|
51
|
+
|
|
52
|
+
export interface ActiveNavigation<Icon = unknown> {
|
|
53
|
+
readonly item: NavigationItem<Icon> | null;
|
|
54
|
+
readonly subItem: NavigationSubItem<Icon> | null;
|
|
55
|
+
}
|
|
56
|
+
|
|
57
|
+
export const NAVIGATION_DIMENSIONS = {
|
|
58
|
+
avatar: 28,
|
|
59
|
+
rail: 280,
|
|
60
|
+
collapsedRail: 76,
|
|
61
|
+
bar: 64,
|
|
62
|
+
target: 44,
|
|
63
|
+
androidTarget: 48,
|
|
64
|
+
} as const;
|
|
65
|
+
|
|
66
|
+
export function getNavigationBarHeight(fontScale = 1, bottomInset = 0): number {
|
|
67
|
+
return NAVIGATION_DIMENSIONS.bar * Math.max(1, fontScale) + bottomInset;
|
|
68
|
+
}
|
|
69
|
+
|
|
70
|
+
export function getNavigationLayout(width: number): 'bar' | 'rail' {
|
|
71
|
+
return getLayoutMode(width, { medium: 600, expanded: 1024 }) === 'expanded' ? 'rail' : 'bar';
|
|
72
|
+
}
|
|
73
|
+
|
|
74
|
+
function routePath(href: string): string {
|
|
75
|
+
return href.split(/[?#]/, 1)[0] ?? href;
|
|
76
|
+
}
|
|
77
|
+
|
|
78
|
+
export function navigationMatches(item: NavigationSubItem, pathname: string): boolean {
|
|
79
|
+
if (item.matches !== undefined) return item.matches(pathname);
|
|
80
|
+
const path = routePath(pathname);
|
|
81
|
+
const href = routePath(item.href);
|
|
82
|
+
return path === href || (href !== '/' && path.startsWith(`${href}/`));
|
|
83
|
+
}
|
|
84
|
+
|
|
85
|
+
function bestMatch<Item extends NavigationSubItem>(
|
|
86
|
+
items: readonly Item[],
|
|
87
|
+
pathname: string,
|
|
88
|
+
): Item | null {
|
|
89
|
+
return items.reduce<Item | null>((best, item) => {
|
|
90
|
+
if (!navigationMatches(item, pathname)) return best;
|
|
91
|
+
return best === null || routePath(item.href).length > routePath(best.href).length ? item : best;
|
|
92
|
+
}, null);
|
|
93
|
+
}
|
|
94
|
+
|
|
95
|
+
export function resolveActiveMenuEntry(
|
|
96
|
+
entries: readonly NavigationProfileMenuEntry[],
|
|
97
|
+
pathname: string,
|
|
98
|
+
): NavigationProfileMenuEntry | null {
|
|
99
|
+
return bestMatch(
|
|
100
|
+
entries.filter((entry) => entry.href !== undefined),
|
|
101
|
+
pathname,
|
|
102
|
+
);
|
|
103
|
+
}
|
|
104
|
+
|
|
105
|
+
export function resolveActiveNavigation<Icon>(
|
|
106
|
+
items: readonly NavigationItem<Icon>[],
|
|
107
|
+
pathname: string,
|
|
108
|
+
): ActiveNavigation<Icon> {
|
|
109
|
+
const subItem = bestMatch(
|
|
110
|
+
items.flatMap((item) => item.children ?? []),
|
|
111
|
+
pathname,
|
|
112
|
+
);
|
|
113
|
+
const item =
|
|
114
|
+
subItem === null
|
|
115
|
+
? bestMatch(items, pathname)
|
|
116
|
+
: (items.find((parent) => parent.children?.includes(subItem)) ?? null);
|
|
117
|
+
return { item, subItem };
|
|
118
|
+
}
|
|
119
|
+
|
|
120
|
+
export function nextSectionHref(item: NavigationItem, pathname: string): string {
|
|
121
|
+
const routes = item.children ?? [];
|
|
122
|
+
if (routes.length === 0) return item.href;
|
|
123
|
+
const current = bestMatch(routes, pathname);
|
|
124
|
+
const index = current === null ? -1 : routes.indexOf(current);
|
|
125
|
+
return routes[(index + 1) % routes.length]?.href ?? item.href;
|
|
126
|
+
}
|
|
127
|
+
|
|
128
|
+
export interface NavigationState {
|
|
129
|
+
readonly collapsed: boolean;
|
|
130
|
+
readonly openIds: readonly string[];
|
|
131
|
+
}
|
|
132
|
+
|
|
133
|
+
export type NavigationAction =
|
|
134
|
+
| { readonly type: 'set-collapsed'; readonly collapsed: boolean }
|
|
135
|
+
| { readonly type: 'toggle-group'; readonly id: string; readonly collapsed?: boolean }
|
|
136
|
+
| { readonly type: 'enter-section'; readonly id: string | null };
|
|
137
|
+
|
|
138
|
+
export function navigationReducer(
|
|
139
|
+
state: NavigationState,
|
|
140
|
+
action: NavigationAction,
|
|
141
|
+
): NavigationState {
|
|
142
|
+
if (action.type === 'set-collapsed') return { ...state, collapsed: action.collapsed };
|
|
143
|
+
if (action.type === 'enter-section') {
|
|
144
|
+
return action.id === null || state.openIds.includes(action.id)
|
|
145
|
+
? state
|
|
146
|
+
: { ...state, openIds: [...state.openIds, action.id] };
|
|
147
|
+
}
|
|
148
|
+
const open = state.openIds.includes(action.id);
|
|
149
|
+
const collapsed = action.collapsed ?? state.collapsed;
|
|
150
|
+
return {
|
|
151
|
+
collapsed: false,
|
|
152
|
+
openIds:
|
|
153
|
+
open && !collapsed
|
|
154
|
+
? state.openIds.filter((id) => id !== action.id)
|
|
155
|
+
: open
|
|
156
|
+
? state.openIds
|
|
157
|
+
: [...state.openIds, action.id],
|
|
158
|
+
};
|
|
159
|
+
}
|
|
160
|
+
|
|
161
|
+
export function validateNavigation(
|
|
162
|
+
items: readonly NavigationItem[],
|
|
163
|
+
profile?: NavigationProfile,
|
|
164
|
+
): void {
|
|
165
|
+
if (items.length > 5)
|
|
166
|
+
throw new RangeError('Navigation supports at most five main items plus profile.');
|
|
167
|
+
const ids = new Set<string>();
|
|
168
|
+
for (const item of items.flatMap((parent) => [parent, ...(parent.children ?? [])])) {
|
|
169
|
+
if (item.id.trim() === '' || ids.has(item.id))
|
|
170
|
+
throw new Error(`Duplicate or empty navigation id: ${item.id}`);
|
|
171
|
+
ids.add(item.id);
|
|
172
|
+
if (item.label.trim() === '') throw new Error(`Navigation label is empty: ${item.id}`);
|
|
173
|
+
if (item.href.trim() === '') throw new Error(`Navigation href is empty: ${item.id}`);
|
|
174
|
+
}
|
|
175
|
+
if (profile === undefined) return;
|
|
176
|
+
if (profile.label.trim() === '' || profile.initials.trim() === '')
|
|
177
|
+
throw new Error('Profile needs a label and initials.');
|
|
178
|
+
if (profile.href?.trim() === '') throw new Error('Profile href is empty.');
|
|
179
|
+
if (profile.menu !== undefined) {
|
|
180
|
+
if (profile.menu.length === 0) throw new Error('Profile menu is empty.');
|
|
181
|
+
for (const entry of profile.menu) {
|
|
182
|
+
if (entry.id.trim() === '' || ids.has(entry.id))
|
|
183
|
+
throw new Error(`Duplicate or empty navigation id: ${entry.id}`);
|
|
184
|
+
ids.add(entry.id);
|
|
185
|
+
if (entry.label.trim() === '' || entry.href?.trim() === '')
|
|
186
|
+
throw new Error(`Profile entry is empty: ${entry.id}`);
|
|
187
|
+
}
|
|
188
|
+
}
|
|
189
|
+
}
|
|
@@ -0,0 +1,183 @@
|
|
|
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 } from 'react';
|
|
5
|
+
import { Text, View } from 'react-native';
|
|
6
|
+
import { AppNavigation, SectionPicker, type NavigationTheme } from './native.js';
|
|
7
|
+
|
|
8
|
+
Object.assign(globalThis, { IS_REACT_ACT_ENVIRONMENT: true });
|
|
9
|
+
const theme: NavigationTheme = {
|
|
10
|
+
background: '#fff',
|
|
11
|
+
text: '#111',
|
|
12
|
+
muted: '#595959',
|
|
13
|
+
activeBackground: '#dbe9f8',
|
|
14
|
+
activeText: '#005fcc',
|
|
15
|
+
ancestorText: '#004799',
|
|
16
|
+
border: '#767676',
|
|
17
|
+
focus: '#005fcc',
|
|
18
|
+
radius: 4,
|
|
19
|
+
spacing: 8,
|
|
20
|
+
};
|
|
21
|
+
const icon = () => <Text>●</Text>;
|
|
22
|
+
let root: Root | undefined;
|
|
23
|
+
let host: HTMLDivElement | undefined;
|
|
24
|
+
afterEach(async () => {
|
|
25
|
+
await act(() => {
|
|
26
|
+
root?.unmount();
|
|
27
|
+
return Promise.resolve();
|
|
28
|
+
});
|
|
29
|
+
host?.remove();
|
|
30
|
+
});
|
|
31
|
+
async function mount(children: React.ReactNode) {
|
|
32
|
+
await page.viewport(320, 568);
|
|
33
|
+
host = document.createElement('div');
|
|
34
|
+
document.body.append(host);
|
|
35
|
+
root = createRoot(host);
|
|
36
|
+
await act(() => {
|
|
37
|
+
root?.render(children);
|
|
38
|
+
return Promise.resolve();
|
|
39
|
+
});
|
|
40
|
+
}
|
|
41
|
+
async function click(target: Parameters<typeof userEvent.click>[0]) {
|
|
42
|
+
await act(async () => {
|
|
43
|
+
await userEvent.click(target);
|
|
44
|
+
await new Promise<void>((resolve) => {
|
|
45
|
+
requestAnimationFrame(() =>
|
|
46
|
+
requestAnimationFrame(() => {
|
|
47
|
+
resolve();
|
|
48
|
+
}),
|
|
49
|
+
);
|
|
50
|
+
});
|
|
51
|
+
});
|
|
52
|
+
}
|
|
53
|
+
function expectVisibleMenu() {
|
|
54
|
+
const menu = page.getByRole('menu').element();
|
|
55
|
+
const rect = menu.getBoundingClientRect();
|
|
56
|
+
expect(rect.width).toBeGreaterThan(200);
|
|
57
|
+
expect(rect.left).toBeGreaterThanOrEqual(0);
|
|
58
|
+
expect(rect.right).toBeLessThanOrEqual(320);
|
|
59
|
+
expect(rect.top).toBeGreaterThanOrEqual(0);
|
|
60
|
+
expect(rect.bottom).toBeLessThanOrEqual(568);
|
|
61
|
+
expect(host?.contains(menu)).toBe(false);
|
|
62
|
+
for (const entry of menu.querySelectorAll('[role="menuitem"], [role="button"]')) {
|
|
63
|
+
const bounds = entry.getBoundingClientRect();
|
|
64
|
+
const hit = document.elementFromPoint(
|
|
65
|
+
bounds.left + bounds.width / 2,
|
|
66
|
+
bounds.top + bounds.height / 2,
|
|
67
|
+
);
|
|
68
|
+
expect(hit !== null && entry.contains(hit)).toBe(true);
|
|
69
|
+
}
|
|
70
|
+
}
|
|
71
|
+
it('presents an unclipped compact profile menu at 320 px', async () => {
|
|
72
|
+
const navigate = vi.fn();
|
|
73
|
+
await mount(
|
|
74
|
+
<View style={{ height: 568, overflow: 'hidden', justifyContent: 'flex-end' }}>
|
|
75
|
+
<AppNavigation
|
|
76
|
+
items={[{ id: 'home', label: 'Home', href: '/', icon }]}
|
|
77
|
+
label="Primary"
|
|
78
|
+
collapseLabel="Collapse"
|
|
79
|
+
expandLabel="Expand"
|
|
80
|
+
closeLabel="Close"
|
|
81
|
+
width={320}
|
|
82
|
+
pathname="/settings/profile"
|
|
83
|
+
theme={theme}
|
|
84
|
+
onNavigate={navigate}
|
|
85
|
+
profile={{
|
|
86
|
+
label: 'Account',
|
|
87
|
+
initials: 'AB',
|
|
88
|
+
menu: [
|
|
89
|
+
{ id: 'settings', label: 'App settings', href: '/settings' },
|
|
90
|
+
{ id: 'profile', label: 'Profile and data', href: '/settings/profile' },
|
|
91
|
+
],
|
|
92
|
+
}}
|
|
93
|
+
/>
|
|
94
|
+
</View>,
|
|
95
|
+
);
|
|
96
|
+
await click(page.getByRole('button', { name: 'Account' }));
|
|
97
|
+
await expect.element(page.getByRole('menu')).toBeInTheDocument();
|
|
98
|
+
expectVisibleMenu();
|
|
99
|
+
await expect.element(page.getByRole('menuitem', { name: 'Profile and data' })).toHaveFocus();
|
|
100
|
+
await click(page.getByRole('menuitem', { name: 'App settings' }));
|
|
101
|
+
expect(navigate).toHaveBeenCalledWith('/settings');
|
|
102
|
+
await expect.element(page.getByRole('button', { name: 'Account' })).toHaveFocus();
|
|
103
|
+
});
|
|
104
|
+
it('presents an unclipped section picker and focuses its selected child at 320 px', async () => {
|
|
105
|
+
const navigate = vi.fn();
|
|
106
|
+
await mount(
|
|
107
|
+
<View style={{ height: 568, overflow: 'hidden' }}>
|
|
108
|
+
<SectionPicker
|
|
109
|
+
closeLabel="Close"
|
|
110
|
+
theme={theme}
|
|
111
|
+
pathname="/progress/history"
|
|
112
|
+
onNavigate={navigate}
|
|
113
|
+
item={{
|
|
114
|
+
id: 'progress',
|
|
115
|
+
label: 'Progress',
|
|
116
|
+
href: '/progress',
|
|
117
|
+
icon,
|
|
118
|
+
children: [
|
|
119
|
+
{ id: 'overview', label: 'Overview', href: '/progress' },
|
|
120
|
+
{ id: 'history', label: 'History', href: '/progress/history' },
|
|
121
|
+
],
|
|
122
|
+
}}
|
|
123
|
+
/>
|
|
124
|
+
</View>,
|
|
125
|
+
);
|
|
126
|
+
await click(page.getByRole('button', { name: 'Progress, History' }));
|
|
127
|
+
await expect.element(page.getByRole('menu')).toBeInTheDocument();
|
|
128
|
+
expectVisibleMenu();
|
|
129
|
+
await expect.element(page.getByRole('menuitem', { name: 'History' })).toHaveFocus();
|
|
130
|
+
await click(page.getByRole('menuitem', { name: 'Overview' }));
|
|
131
|
+
expect(navigate).toHaveBeenCalledWith('/progress');
|
|
132
|
+
await expect.element(page.getByRole('button', { name: 'Progress, History' })).toHaveFocus();
|
|
133
|
+
});
|
|
134
|
+
|
|
135
|
+
it('keeps a custom native avatar decorative with subtitle, typography and menu focus', async () => {
|
|
136
|
+
await mount(
|
|
137
|
+
<AppNavigation
|
|
138
|
+
label="Primary"
|
|
139
|
+
collapseLabel="Collapse"
|
|
140
|
+
expandLabel="Expand"
|
|
141
|
+
closeLabel="Close"
|
|
142
|
+
items={[{ id: 'home', label: 'Home', href: '/', icon }]}
|
|
143
|
+
width={320}
|
|
144
|
+
pathname="/"
|
|
145
|
+
theme={{ ...theme, typography: { fontFamily: 'monospace', fontSize: 18, barFontSize: 12 } }}
|
|
146
|
+
onNavigate={vi.fn()}
|
|
147
|
+
profile={{
|
|
148
|
+
label: 'Account',
|
|
149
|
+
subtitle: 'Ada, synced',
|
|
150
|
+
initials: 'AD',
|
|
151
|
+
renderAvatar: ({ size }) => (
|
|
152
|
+
<Text
|
|
153
|
+
accessibilityRole="image"
|
|
154
|
+
accessibilityLabel="Product glyph"
|
|
155
|
+
testID="profile-glyph"
|
|
156
|
+
style={{ width: size, height: size }}
|
|
157
|
+
>
|
|
158
|
+
A
|
|
159
|
+
</Text>
|
|
160
|
+
),
|
|
161
|
+
menu: [{ id: 'settings', label: 'Settings', href: '/settings' }],
|
|
162
|
+
}}
|
|
163
|
+
/>,
|
|
164
|
+
);
|
|
165
|
+
const trigger = page.getByRole('button', { name: 'Account, Ada, synced' });
|
|
166
|
+
await expect.element(trigger).toBeVisible();
|
|
167
|
+
await expect.element(page.getByTestId('profile-glyph')).toBeVisible();
|
|
168
|
+
await expect.element(page.getByRole('img', { name: 'Product glyph' })).not.toBeInTheDocument();
|
|
169
|
+
await expect.element(page.getByText('Ada, synced', { exact: true })).not.toBeInTheDocument();
|
|
170
|
+
await click(trigger);
|
|
171
|
+
const menu = page.getByRole('menu', { name: 'Account, Ada, synced' });
|
|
172
|
+
await expect.element(menu.getByText('Ada, synced', { exact: true })).toBeVisible();
|
|
173
|
+
const settings = document.querySelector<HTMLElement>('[role="menuitem"]');
|
|
174
|
+
expect(settings).not.toBeNull();
|
|
175
|
+
const text = settings?.querySelector<HTMLElement>('[dir="auto"]');
|
|
176
|
+
expect(text).not.toBeNull();
|
|
177
|
+
if (text === null || text === undefined) throw new Error('Settings text is missing');
|
|
178
|
+
expect(getComputedStyle(text).fontFamily).toContain('monospace');
|
|
179
|
+
expect(getComputedStyle(text).fontSize).toBe('18px');
|
|
180
|
+
await expect.element(page.getByRole('menuitem', { name: 'Settings' })).toHaveFocus();
|
|
181
|
+
await click(page.getByRole('button', { name: 'Close' }));
|
|
182
|
+
await expect.element(trigger).toHaveFocus();
|
|
183
|
+
});
|