@gaulatti/bleecker 0.1.41 → 0.1.44

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 (73) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +116 -1
  3. package/dist/components/alert-dialog.js +7 -42
  4. package/dist/components/alert.js +0 -7
  5. package/dist/components/breadcrumb.js +1 -1
  6. package/dist/components/button.js +2 -2
  7. package/dist/components/chart-theme.d.ts +1 -1
  8. package/dist/components/command-spotlight.d.ts +2 -1
  9. package/dist/components/command-spotlight.js +35 -62
  10. package/dist/components/context-menu.d.ts +1 -1
  11. package/dist/components/context-menu.js +8 -2
  12. package/dist/components/dashboard-grid.d.ts +1 -1
  13. package/dist/components/dashboard-section.d.ts +1 -1
  14. package/dist/components/data-list.d.ts +1 -1
  15. package/dist/components/data-table-filters.d.ts +1 -1
  16. package/dist/components/data-table-toolbar.d.ts +1 -1
  17. package/dist/components/data-table.js +1 -1
  18. package/dist/components/drawer.js +2 -2
  19. package/dist/components/dropdown-menu.d.ts +1 -1
  20. package/dist/components/dropdown-menu.js +13 -3
  21. package/dist/components/error-state.d.ts +1 -1
  22. package/dist/components/eyebrow.d.ts +1 -1
  23. package/dist/components/feed-item.js +4 -11
  24. package/dist/components/icon-badge.d.ts +1 -1
  25. package/dist/components/icon-button.js +1 -1
  26. package/dist/components/input.js +1 -1
  27. package/dist/components/label.d.ts +1 -1
  28. package/dist/components/label.js +1 -1
  29. package/dist/components/loading-overlay.d.ts +1 -1
  30. package/dist/components/media-library.js +2 -4
  31. package/dist/components/metric.d.ts +1 -1
  32. package/dist/components/metric.js +1 -1
  33. package/dist/components/modal.js +7 -57
  34. package/dist/components/page-header.d.ts +1 -1
  35. package/dist/components/popover.js +3 -1
  36. package/dist/components/progress.js +2 -1
  37. package/dist/components/sankey-chart.js +1 -1
  38. package/dist/components/search-input.d.ts +1 -1
  39. package/dist/components/search-input.js +1 -1
  40. package/dist/components/select.js +4 -2
  41. package/dist/components/sheet.js +2 -2
  42. package/dist/components/sidebar.d.ts +1 -1
  43. package/dist/components/sidebar.js +1 -1
  44. package/dist/components/skeleton.d.ts +1 -1
  45. package/dist/components/stat-card.d.ts +1 -1
  46. package/dist/components/sunburst-chart.js +1 -1
  47. package/dist/components/table.js +3 -16
  48. package/dist/components/textarea.js +1 -1
  49. package/dist/components/timeline.d.ts +1 -1
  50. package/dist/components/tooltip.js +3 -1
  51. package/dist/index.d.ts +2 -2
  52. package/dist/index.js +2 -2
  53. package/dist/layout/admin-shell.d.ts +1 -1
  54. package/dist/layout/auth-shell.d.ts +8 -1
  55. package/dist/layout/auth-shell.js +8 -1
  56. package/dist/layout/panel-layout.js +0 -4
  57. package/dist/styles.css +1 -1
  58. package/dist/theme/theme-provider.d.ts +2 -2
  59. package/dist/theme/theme-provider.js +16 -20
  60. package/dist/theme/theme-script.d.ts +1 -1
  61. package/dist/theme/theme-script.js +1 -1
  62. package/dist/theme/types.d.ts +11 -0
  63. package/dist/utils/attention-color.js +4 -4
  64. package/dist/utils/avatar-initial.d.ts +1 -0
  65. package/dist/utils/avatar-initial.js +3 -0
  66. package/dist/utils/clamp-percent.d.ts +1 -0
  67. package/dist/utils/clamp-percent.js +3 -0
  68. package/dist/utils/format.js +17 -14
  69. package/dist/utils/hooks.d.ts +14 -3
  70. package/dist/utils/hooks.js +209 -43
  71. package/dist/utils/source-label.d.ts +1 -0
  72. package/dist/utils/source-label.js +9 -0
  73. package/package.json +14 -5
@@ -1,4 +1,4 @@
1
- import type { ThemeMode, ThemeProviderProps } from './types';
1
+ import type { ThemeMode, ThemeProviderOptions } from './types';
2
2
  interface ThemeContextValue {
3
3
  theme: ThemeMode;
4
4
  resolvedTheme: 'light' | 'dark';
@@ -6,6 +6,6 @@ interface ThemeContextValue {
6
6
  cycleTheme: () => void;
7
7
  storageKey: string;
8
8
  }
9
- export declare function ThemeProvider({ children, defaultTheme, storageKey }: ThemeProviderProps): import("react/jsx-runtime").JSX.Element;
9
+ export declare function ThemeProvider(props: ThemeProviderOptions): import("react/jsx-runtime").JSX.Element;
10
10
  export declare function useTheme(): ThemeContextValue;
11
11
  export {};
@@ -13,38 +13,32 @@ function nextTheme(theme) {
13
13
  return 'light';
14
14
  }
15
15
  function getSystemPreference() {
16
- if (typeof window === 'undefined') {
17
- return false;
18
- }
19
16
  return window.matchMedia('(prefers-color-scheme: dark)').matches;
20
17
  }
21
18
  function readStoredTheme(storageKey, fallback) {
22
- if (typeof window === 'undefined') {
23
- return fallback;
24
- }
25
19
  const saved = window.localStorage.getItem(storageKey);
26
20
  return saved === 'light' || saved === 'dark' || saved === 'system' ? saved : fallback;
27
21
  }
28
22
  function applyDocumentTheme(theme) {
29
- if (typeof document === 'undefined') {
30
- return resolveTheme(theme, false);
31
- }
32
23
  const resolved = resolveTheme(theme, getSystemPreference());
33
24
  document.documentElement.classList.toggle('dark', resolved === 'dark');
34
25
  return resolved;
35
26
  }
36
- export function ThemeProvider({ children, defaultTheme = 'system', storageKey = 'theme' }) {
37
- const [theme, setThemeState] = React.useState(defaultTheme);
38
- const [resolvedTheme, setResolvedTheme] = React.useState(() => resolveTheme(defaultTheme, false));
27
+ export function ThemeProvider(props) {
28
+ const { children, defaultTheme = 'system', storageKey = 'theme' } = props;
29
+ const isControlled = props.theme !== undefined;
30
+ const [storedTheme, setThemeState] = React.useState(defaultTheme);
31
+ const theme = props.theme ?? storedTheme;
32
+ const [resolvedTheme, setResolvedTheme] = React.useState(() => resolveTheme(theme, false));
39
33
  React.useEffect(() => {
34
+ if (isControlled) {
35
+ return;
36
+ }
40
37
  const initialTheme = readStoredTheme(storageKey, defaultTheme);
41
38
  setThemeState(initialTheme);
42
39
  setResolvedTheme(applyDocumentTheme(initialTheme));
43
- }, [defaultTheme, storageKey]);
40
+ }, [isControlled, defaultTheme, storageKey]);
44
41
  React.useEffect(() => {
45
- if (typeof window === 'undefined') {
46
- return undefined;
47
- }
48
42
  const mediaQuery = window.matchMedia('(prefers-color-scheme: dark)');
49
43
  const sync = () => setResolvedTheme(applyDocumentTheme(theme));
50
44
  sync();
@@ -52,12 +46,14 @@ export function ThemeProvider({ children, defaultTheme = 'system', storageKey =
52
46
  return () => mediaQuery.removeEventListener('change', sync);
53
47
  }, [theme]);
54
48
  const setTheme = React.useCallback((value) => {
49
+ if (props.theme !== undefined) {
50
+ props.onThemeChange(value);
51
+ return;
52
+ }
55
53
  setThemeState(value);
56
54
  setResolvedTheme(applyDocumentTheme(value));
57
- if (typeof window !== 'undefined') {
58
- window.localStorage.setItem(storageKey, value);
59
- }
60
- }, [storageKey]);
55
+ window.localStorage.setItem(storageKey, value);
56
+ }, [props.theme, props.onThemeChange, storageKey]);
61
57
  const cycleTheme = React.useCallback(() => {
62
58
  setTheme(nextTheme(theme));
63
59
  }, [setTheme, theme]);
@@ -1,4 +1,4 @@
1
- export { resolveTheme } from '../core';
1
+ export { resolveTheme } from '../core/index';
2
2
  export declare function getThemeScript(storageKey?: string): string;
3
3
  export declare function BleeckerThemeScript({ storageKey }: {
4
4
  storageKey?: string;
@@ -1,5 +1,5 @@
1
1
  import { jsx as _jsx } from "react/jsx-runtime";
2
- export { resolveTheme } from '../core.js';
2
+ export { resolveTheme } from '../core/index.js';
3
3
  export function getThemeScript(storageKey = 'theme') {
4
4
  return `(function(){try{var key=${JSON.stringify(storageKey)};var saved=localStorage.getItem(key);var theme=(saved==="light"||saved==="dark"||saved==="system")?saved:"system";var dark=theme==="dark"||(theme==="system"&&window.matchMedia("(prefers-color-scheme: dark)").matches);document.documentElement.classList.toggle("dark",dark);}catch(e){}})();`;
5
5
  }
@@ -6,3 +6,14 @@ export interface ThemeProviderProps {
6
6
  defaultTheme?: ThemeMode;
7
7
  storageKey?: string;
8
8
  }
9
+ export interface ControlledThemeProviderProps {
10
+ children: ReactNode;
11
+ theme: ThemeMode;
12
+ onThemeChange: (theme: ThemeMode) => void;
13
+ defaultTheme?: never;
14
+ storageKey?: never;
15
+ }
16
+ export type ThemeProviderOptions = (ThemeProviderProps & {
17
+ theme?: never;
18
+ onThemeChange?: never;
19
+ }) | ControlledThemeProviderProps;
@@ -1,4 +1,4 @@
1
- function clamp(value, min, max) {
1
+ function clampNumber(value, min, max) {
2
2
  return Math.min(max, Math.max(min, value));
3
3
  }
4
4
  /**
@@ -8,12 +8,12 @@ function clamp(value, min, max) {
8
8
  */
9
9
  export function createAttentionColor({ hue, intensity: rawIntensity }) {
10
10
  const normalizedHue = ((Math.round(Number.isFinite(hue) ? hue : 210) % 360) + 360) % 360;
11
- const intensity = clamp(Number.isFinite(rawIntensity) ? rawIntensity : 0, 0, 10);
11
+ const intensity = clampNumber(Number.isFinite(rawIntensity) ? rawIntensity : 0, 0, 10);
12
12
  const redMix = Math.round(intensity * 10);
13
- const categoryMix = 100 - redMix;
13
+ const categoryShare = 100 - redMix;
14
14
  const coverage = 24 + intensity * 7.2;
15
15
  const colorStrength = Math.round(10 + intensity * 6.2);
16
- const accent = `color-mix(in oklab, hsl(${normalizedHue} 66% 52%) ${categoryMix}%, hsl(6 78% 56%) ${redMix}%)`;
16
+ const accent = `color-mix(in oklab, hsl(${normalizedHue} 66% 52%) ${categoryShare}%, hsl(6 78% 56%) ${redMix}%)`;
17
17
  return {
18
18
  accent,
19
19
  coverage,
@@ -0,0 +1 @@
1
+ export declare function avatarInitial(author: string, init?: string): string;
@@ -0,0 +1,3 @@
1
+ export function avatarInitial(author, init) {
2
+ return init || (author.trim().slice(0, 1) || '?').toUpperCase();
3
+ }
@@ -0,0 +1 @@
1
+ export declare function clampPercent(value: number, max: number): number;
@@ -0,0 +1,3 @@
1
+ export function clampPercent(value, max) {
2
+ return Math.min(100, Math.max(0, (value / max) * 100));
3
+ }
@@ -4,8 +4,8 @@
4
4
  export function formatNumber(value, options = {}) {
5
5
  if (value === undefined || value === null || Number.isNaN(value))
6
6
  return '';
7
- const { locale, ...intlOptions } = options;
8
- return new Intl.NumberFormat(locale, intlOptions).format(value);
7
+ const { locale, ...numberOptions } = options;
8
+ return new Intl.NumberFormat(locale, numberOptions).format(value);
9
9
  }
10
10
  export function formatCurrency(value, currency = 'USD', options = {}) {
11
11
  if (value === undefined || value === null || Number.isNaN(value))
@@ -22,10 +22,13 @@ export function formatPercent(value, options = {}) {
22
22
  return '';
23
23
  return new Intl.NumberFormat(options.locale, { style: 'percent', minimumFractionDigits: 1, maximumFractionDigits: 1, ...options }).format(value);
24
24
  }
25
+ function toDate(value) {
26
+ return typeof value === 'string' || typeof value === 'number' ? new Date(value) : value;
27
+ }
25
28
  export function formatDate(value, options = {}) {
26
29
  if (value === undefined || value === null)
27
30
  return '';
28
- const date = typeof value === 'string' || typeof value === 'number' ? new Date(value) : value;
31
+ const date = toDate(value);
29
32
  if (Number.isNaN(date.getTime()))
30
33
  return '';
31
34
  const { locale, dateStyle = 'medium', ...intlOptions } = options;
@@ -34,30 +37,30 @@ export function formatDate(value, options = {}) {
34
37
  export function formatDateTime(value, options = {}) {
35
38
  if (value === undefined || value === null)
36
39
  return '';
37
- const date = typeof value === 'string' || typeof value === 'number' ? new Date(value) : value;
40
+ const date = toDate(value);
38
41
  if (Number.isNaN(date.getTime()))
39
42
  return '';
40
- const { locale, ...intlOptions } = options;
41
- return new Intl.DateTimeFormat(locale, { dateStyle: 'short', timeStyle: 'short', ...intlOptions }).format(date);
43
+ const { locale, ...dateTimeOptions } = options;
44
+ return new Intl.DateTimeFormat(locale, { dateStyle: 'short', timeStyle: 'short', ...dateTimeOptions }).format(date);
42
45
  }
43
46
  export function formatRelativeTime(value, locale = 'en-US') {
44
47
  if (value === undefined || value === null)
45
48
  return '';
46
- const date = typeof value === 'string' || typeof value === 'number' ? new Date(value) : value;
49
+ const date = toDate(value);
47
50
  if (Number.isNaN(date.getTime()))
48
51
  return '';
49
52
  const now = Date.now();
50
- const diff = date.getTime() - now;
51
- const seconds = Math.round(diff / 1000);
53
+ const delta = date.getTime() - now;
54
+ const seconds = Math.round(delta / 1000);
52
55
  const minutes = Math.round(seconds / 60);
53
56
  const hours = Math.round(minutes / 60);
54
57
  const days = Math.round(hours / 24);
55
- const rtf = new Intl.RelativeTimeFormat(locale, { numeric: 'auto' });
58
+ const relativeFormatter = new Intl.RelativeTimeFormat(locale, { numeric: 'auto' });
56
59
  if (Math.abs(seconds) < 60)
57
- return rtf.format(seconds, 'second');
60
+ return relativeFormatter.format(seconds, 'second');
58
61
  if (Math.abs(minutes) < 60)
59
- return rtf.format(minutes, 'minute');
62
+ return relativeFormatter.format(minutes, 'minute');
60
63
  if (Math.abs(hours) < 24)
61
- return rtf.format(hours, 'hour');
62
- return rtf.format(days, 'day');
64
+ return relativeFormatter.format(hours, 'hour');
65
+ return relativeFormatter.format(days, 'day');
63
66
  }
@@ -1,4 +1,4 @@
1
- import * as React from 'react';
1
+ import React from 'react';
2
2
  /**
3
3
  * Returns true once the component has mounted. Useful for avoiding SSR
4
4
  * hydration mismatches in components that read from `window`/`document`.
@@ -29,8 +29,19 @@ export declare function usePresence(open: boolean, exitDuration?: number): {
29
29
  * without causing effect re-runs.
30
30
  */
31
31
  export declare function useEventCallback<T extends (...args: any[]) => any>(callback?: T): T;
32
+ interface ModalScope {
33
+ ref: React.RefObject<HTMLElement | null>;
34
+ }
35
+ /** Preserves logical modal ancestry across React portals. */
36
+ export declare function ModalLayerScope({ layerRef, children }: {
37
+ layerRef: React.RefObject<HTMLElement | null>;
38
+ children: React.ReactNode;
39
+ }): React.FunctionComponentElement<React.ProviderProps<ModalScope[]>>;
40
+ /** Attach to a portaled widget owned by the nearest modal. */
41
+ export declare function useModalBranch<T extends HTMLElement>(): (element: T | null) => void;
32
42
  /**
33
- * Supplies the focus, Escape, and scroll-lock behavior expected of custom
34
- * modal surfaces such as sheets and drawers.
43
+ * All Bleecker modal surfaces share attachment, ancestry, focus, keyboard, and
44
+ * scroll ownership. The returned object ref remains the public hook contract.
35
45
  */
36
46
  export declare function useModalLayer<T extends HTMLElement>(open: boolean, onDismiss: () => void): React.RefObject<T | null>;
47
+ export {};
@@ -1,5 +1,5 @@
1
1
  'use client';
2
- import * as React from 'react';
2
+ import React from 'react';
3
3
  /**
4
4
  * Returns true once the component has mounted. Useful for avoiding SSR
5
5
  * hydration mismatches in components that read from `window`/`document`.
@@ -15,8 +15,6 @@ export function useMounted() {
15
15
  export function useMediaQuery(query) {
16
16
  const [matches, setMatches] = React.useState(false);
17
17
  React.useEffect(() => {
18
- if (typeof window === 'undefined')
19
- return undefined;
20
18
  const media = window.matchMedia(query);
21
19
  const update = () => setMatches(media.matches);
22
20
  update();
@@ -70,11 +68,9 @@ export function usePresence(open, exitDuration = 150) {
70
68
  React.useLayoutEffect(() => {
71
69
  if (!open || !present)
72
70
  return;
73
- enterTimerRef.current = setTimeout(() => setVisible(true), 20);
74
- return () => {
75
- if (enterTimerRef.current)
76
- clearTimeout(enterTimerRef.current);
77
- };
71
+ const timer = setTimeout(() => setVisible(true), 20);
72
+ enterTimerRef.current = timer;
73
+ return () => clearTimeout(timer);
78
74
  }, [open, present]);
79
75
  React.useEffect(() => {
80
76
  return () => {
@@ -97,33 +93,169 @@ export function useEventCallback(callback) {
97
93
  }, [callback]);
98
94
  return React.useCallback((...args) => ref.current?.(...args), []);
99
95
  }
100
- const focusableSelector = [
101
- 'a[href]',
102
- 'button:not([disabled])',
103
- 'input:not([disabled])',
104
- 'select:not([disabled])',
105
- 'textarea:not([disabled])',
106
- '[tabindex]:not([tabindex="-1"])'
107
- ].join(',');
96
+ const ModalContext = React.createContext([]);
97
+ /** Preserves logical modal ancestry across React portals. */
98
+ export function ModalLayerScope({ layerRef, children }) {
99
+ const ancestors = React.useContext(ModalContext);
100
+ const value = React.useMemo(() => [...ancestors, { ref: layerRef }], [ancestors, layerRef]);
101
+ return React.createElement(ModalContext.Provider, { value }, children);
102
+ }
103
+ const modalBranches = new WeakMap();
104
+ /** Attach to a portaled widget owned by the nearest modal. */
105
+ export function useModalBranch() {
106
+ const ancestors = React.useContext(ModalContext);
107
+ const ownerRef = ancestors.at(-1)?.ref;
108
+ const [node, setNode] = React.useState(null);
109
+ const ref = React.useCallback((element) => {
110
+ if (ownerRef)
111
+ setNode(element);
112
+ }, [ownerRef]);
113
+ React.useLayoutEffect(() => {
114
+ const owner = ownerRef?.current;
115
+ if (!owner || !node)
116
+ return;
117
+ const branches = modalBranches.get(owner) ?? new Set();
118
+ branches.add(node);
119
+ modalBranches.set(owner, branches);
120
+ node.inert = owner.inert;
121
+ const overlay = owner.closest('[data-bleecker-modal-overlay]');
122
+ const surface = node.closest('[data-radix-popper-content-wrapper]') ?? node;
123
+ if (overlay)
124
+ surface.style.zIndex = String(Number(overlay.style.zIndex) + 1);
125
+ const stack = modalStacks.get(owner.ownerDocument);
126
+ if (stack)
127
+ updateModalStack(stack);
128
+ return () => {
129
+ branches.delete(node);
130
+ const current = modalStacks.get(owner.ownerDocument);
131
+ if (current)
132
+ updateModalStack(current);
133
+ };
134
+ }, [node, ownerRef]);
135
+ return ref;
136
+ }
137
+ function focusableElements(layer) {
138
+ const doc = layer.ownerDocument;
139
+ const view = doc.defaultView;
140
+ if (!view)
141
+ return [];
142
+ const roots = [layer, ...modalBranches.get(layer) ?? []];
143
+ const candidates = roots.flatMap((root) => Array.from(root.querySelectorAll('*'))).filter((element) => {
144
+ const editableHost = element.isContentEditable && !element.parentElement?.isContentEditable;
145
+ const sequential = element.tabIndex >= 0 || (editableHost && !element.hasAttribute('tabindex'));
146
+ return sequential && !element.matches(':disabled') &&
147
+ !element.closest('[hidden], [inert], [aria-hidden="true"]') &&
148
+ element.getClientRects().length > 0 && view.getComputedStyle(element).visibility === 'visible';
149
+ });
150
+ return [...new Set(candidates)].filter((element) => {
151
+ if (!element.matches('input[type="radio"]') || !element.name)
152
+ return true;
153
+ const input = element;
154
+ const group = candidates.filter((candidate) => candidate.matches('input[type="radio"]') &&
155
+ candidate.name === input.name && candidate.form === input.form);
156
+ return input === (group.find((radio) => radio.checked) ?? group[0]);
157
+ }).sort((a, b) => {
158
+ const aIndex = a.tabIndex > 0 ? a.tabIndex : Infinity;
159
+ const bIndex = b.tabIndex > 0 ? b.tabIndex : Infinity;
160
+ if (aIndex !== bIndex)
161
+ return aIndex < bIndex ? -1 : 1;
162
+ return a.compareDocumentPosition(b) & view.Node.DOCUMENT_POSITION_FOLLOWING ? -1 : 1;
163
+ });
164
+ }
165
+ const modalStacks = new WeakMap();
166
+ function rootEntry(entry, stack) {
167
+ return entry.ancestors.map((scope) => stack.entries.find((candidate) => scope.ref.current === candidate.layer)).find((candidate) => candidate !== undefined) ?? entry;
168
+ }
169
+ function updateModalStack(stack) {
170
+ for (const [element, inert] of stack.background)
171
+ element.inert = inert;
172
+ stack.background.clear();
173
+ stack.entries.sort((a, b) => rootEntry(a, stack).order - rootEntry(b, stack).order || a.ancestors.length - b.ancestors.length || a.order - b.order);
174
+ const active = stack.entries.at(-1) ?? null;
175
+ for (const [index, entry] of stack.entries.entries()) {
176
+ entry.layer.inert = entry !== active;
177
+ const overlay = entry.layer.closest('[data-bleecker-modal-overlay]');
178
+ if (overlay)
179
+ overlay.style.zIndex = String(50 + index);
180
+ for (const branch of modalBranches.get(entry.layer) ?? []) {
181
+ branch.inert = entry !== active;
182
+ const surface = branch.closest('[data-radix-popper-content-wrapper]') ?? branch;
183
+ surface.style.zIndex = String(51 + index);
184
+ }
185
+ }
186
+ stack.active = active;
187
+ if (active) {
188
+ const roots = [active.layer.closest('[data-bleecker-modal-overlay]') ?? active.layer,
189
+ ...Array.from(modalBranches.get(active.layer) ?? []).map((branch) => branch.closest('[data-radix-popper-content-wrapper]') ?? branch)];
190
+ for (const child of Array.from(stack.doc.body.children)) {
191
+ const allowed = roots.some((root) => child === root || child.contains(root));
192
+ if (!allowed)
193
+ stack.background.set(child, child.inert);
194
+ child.inert = !allowed;
195
+ }
196
+ }
197
+ }
198
+ function containsModalTarget(layer, target) {
199
+ return layer.contains(target) || Array.from(modalBranches.get(layer) ?? []).some((branch) => branch.contains(target));
200
+ }
201
+ function focusFirst(entry) {
202
+ (focusableElements(entry.layer)[0] ?? entry.layer).focus({ preventScroll: true });
203
+ }
108
204
  /**
109
- * Supplies the focus, Escape, and scroll-lock behavior expected of custom
110
- * modal surfaces such as sheets and drawers.
205
+ * All Bleecker modal surfaces share attachment, ancestry, focus, keyboard, and
206
+ * scroll ownership. The returned object ref remains the public hook contract.
111
207
  */
112
208
  export function useModalLayer(open, onDismiss) {
209
+ const [layer, setLayer] = React.useState(null);
113
210
  const layerRef = React.useRef(null);
211
+ const ancestors = React.useContext(ModalContext);
212
+ const snapshot = React.useRef({ layer: null, open: false, focus: null });
114
213
  const dismiss = useEventCallback(onDismiss);
214
+ React.useLayoutEffect(() => {
215
+ const node = layerRef.current;
216
+ if (node && open && (!snapshot.current.open || snapshot.current.layer !== node)) {
217
+ const active = node.ownerDocument.activeElement;
218
+ const constructor = node.ownerDocument.defaultView?.HTMLElement;
219
+ snapshot.current.focus = constructor && active instanceof constructor ? active : null;
220
+ }
221
+ snapshot.current.layer = node;
222
+ snapshot.current.open = open;
223
+ if (node) {
224
+ if (!open)
225
+ node.inert = true;
226
+ const stack = modalStacks.get(node.ownerDocument);
227
+ if (stack && open)
228
+ updateModalStack(stack);
229
+ }
230
+ setLayer(node);
231
+ });
115
232
  React.useEffect(() => {
116
- if (!open || typeof document === 'undefined')
117
- return undefined;
118
- const layer = layerRef.current;
119
- if (!layer)
120
- return undefined;
121
- const previouslyFocused = document.activeElement instanceof HTMLElement ? document.activeElement : null;
122
- const previousOverflow = document.body.style.overflow;
123
- document.body.style.overflow = 'hidden';
124
- const focusable = Array.from(layer.querySelectorAll(focusableSelector));
125
- (focusable[0] ?? layer).focus({ preventScroll: true });
233
+ if (!open || !layer)
234
+ return;
235
+ const doc = layer.ownerDocument;
236
+ let stack = modalStacks.get(doc);
237
+ if (!stack) {
238
+ stack = { doc, entries: [], overflow: doc.body.style.overflow, active: null, sequence: 0, background: new Map(), observer: null };
239
+ modalStacks.set(doc, stack);
240
+ doc.body.style.overflow = 'hidden';
241
+ const observer = doc.defaultView?.MutationObserver;
242
+ if (observer) {
243
+ const currentStack = stack;
244
+ stack.observer = new observer(() => { updateModalStack(currentStack); });
245
+ stack.observer.observe(doc.body, { childList: true });
246
+ }
247
+ }
248
+ const entry = { layer, ancestors, previousFocus: snapshot.current.focus, order: ++stack.sequence };
249
+ stack.entries.push(entry);
250
+ updateModalStack(stack);
251
+ // All simultaneously mounted descendants register before focus is chosen.
252
+ queueMicrotask(() => {
253
+ if (modalStacks.get(doc) === stack && stack.active === entry)
254
+ focusFirst(entry);
255
+ });
126
256
  const handleKeyDown = (event) => {
257
+ if (stack.active !== entry || event.defaultPrevented)
258
+ return;
127
259
  if (event.key === 'Escape') {
128
260
  event.preventDefault();
129
261
  dismiss();
@@ -131,29 +263,63 @@ export function useModalLayer(open, onDismiss) {
131
263
  }
132
264
  if (event.key !== 'Tab')
133
265
  return;
134
- const currentFocusable = Array.from(layer.querySelectorAll(focusableSelector));
135
- if (currentFocusable.length === 0) {
266
+ const focusable = focusableElements(layer);
267
+ const first = focusable[0];
268
+ const last = focusable.at(-1);
269
+ if (!first || !last) {
136
270
  event.preventDefault();
137
- layer.focus();
138
- return;
271
+ layer.focus({ preventScroll: true });
139
272
  }
140
- const first = currentFocusable[0];
141
- const last = currentFocusable[currentFocusable.length - 1];
142
- if (event.shiftKey && document.activeElement === first) {
273
+ else if (!focusable.includes(doc.activeElement)) {
143
274
  event.preventDefault();
144
- last.focus();
275
+ (event.shiftKey ? last : first).focus({ preventScroll: true });
145
276
  }
146
- else if (!event.shiftKey && document.activeElement === last) {
277
+ else if (event.shiftKey && doc.activeElement === first) {
147
278
  event.preventDefault();
148
- first.focus();
279
+ last.focus({ preventScroll: true });
280
+ }
281
+ else if (!event.shiftKey && doc.activeElement === last) {
282
+ event.preventDefault();
283
+ first.focus({ preventScroll: true });
284
+ }
285
+ else {
286
+ // Positive tabindex participates in the document's global order. Move
287
+ // through the modal's sequential order so background stops are skipped.
288
+ event.preventDefault();
289
+ const index = focusable.indexOf(doc.activeElement);
290
+ focusable[index + (event.shiftKey ? -1 : 1)].focus({ preventScroll: true });
149
291
  }
150
292
  };
151
- document.addEventListener('keydown', handleKeyDown);
293
+ doc.addEventListener('keydown', handleKeyDown);
152
294
  return () => {
153
- document.removeEventListener('keydown', handleKeyDown);
154
- document.body.style.overflow = previousOverflow;
155
- previouslyFocused?.focus({ preventScroll: true });
295
+ doc.removeEventListener('keydown', handleKeyDown);
296
+ const wasActive = stack.active === entry;
297
+ for (const successor of stack.entries) {
298
+ if (successor.previousFocus && containsModalTarget(layer, successor.previousFocus))
299
+ successor.previousFocus = entry.previousFocus;
300
+ }
301
+ stack.entries.splice(stack.entries.indexOf(entry), 1);
302
+ layer.inert = true;
303
+ updateModalStack(stack);
304
+ const parent = stack.active;
305
+ if (!parent) {
306
+ stack.observer?.disconnect();
307
+ doc.body.style.overflow = stack.overflow;
308
+ modalStacks.delete(doc);
309
+ }
310
+ const overlay = layer.closest('[data-bleecker-modal-overlay]');
311
+ if (overlay)
312
+ overlay.inert = true;
313
+ if (!wasActive)
314
+ return;
315
+ const previous = entry.previousFocus;
316
+ if (previous?.isConnected && !previous.closest('[inert]') && (!parent || containsModalTarget(parent.layer, previous))) {
317
+ previous.focus({ preventScroll: true });
318
+ }
319
+ else if (parent) {
320
+ focusFirst(parent);
321
+ }
156
322
  };
157
- }, [dismiss, open]);
323
+ }, [ancestors, dismiss, layer, open]);
158
324
  return layerRef;
159
325
  }
@@ -0,0 +1 @@
1
+ export declare function describeSource(sourceUrl: string): string;
@@ -0,0 +1,9 @@
1
+ export function describeSource(sourceUrl) {
2
+ try {
3
+ const parsed = new URL(sourceUrl);
4
+ return parsed.hostname;
5
+ }
6
+ catch {
7
+ return 'Source article';
8
+ }
9
+ }
package/package.json CHANGED
@@ -1,6 +1,7 @@
1
1
  {
2
2
  "name": "@gaulatti/bleecker",
3
- "version": "0.1.41",
3
+ "version": "0.1.44",
4
+ "license": "MIT",
4
5
  "repository": {
5
6
  "type": "git",
6
7
  "url": "https://github.com/gaulatti/bleecker"
@@ -59,15 +60,21 @@
59
60
  "clean": "node -e \"require('node:fs').rmSync('dist',{recursive:true,force:true})\"",
60
61
  "build:tokens": "node scripts/generate-token-css.mjs",
61
62
  "check:tokens": "node scripts/generate-token-css.mjs --check",
63
+ "check:kolibri-toggle": "npm --prefix conformance/kolibri-toggle test",
62
64
  "build:css": "npm run build:tokens && node -e \"require('node:fs').mkdirSync('dist',{recursive:true})\" && tailwindcss -i src/styles/global.css -o dist/styles.css --minify",
63
- "build": "npm run clean && npm run check:exports-stories && npm run build:css && tsc && node scripts/fix-esm-imports.mjs",
65
+ "build": "npm run clean && npm run check:exports-stories && npm run check:kolibri-toggle && npm run build:css && tsc && node scripts/fix-esm-imports.mjs && npm run check:runtime",
64
66
  "storybook": "npm run build:css && storybook dev -p 6006",
65
67
  "test": "vitest run",
66
- "build-storybook": "npm run check:exports-stories && npm run build:css && storybook build",
68
+ "test:coverage": "vitest run --coverage.enabled --coverage.provider=v8 --coverage.reporter=json --coverage.reportsDirectory=coverage \"--coverage.include=src/**/*.{ts,tsx}\"",
69
+ "build-storybook": "npm run check:exports-stories && npm run check:kolibri-toggle && npm run build:css && storybook build",
67
70
  "typecheck": "tsc --noEmit -p tsconfig.json",
68
71
  "check:exports-stories": "node scripts/check-exports-and-stories.mjs",
69
- "check": "npm run check:tokens && npm run typecheck && npm run check:exports-stories && npm test",
70
- "prepack": "npm run build"
72
+ "check": "npm run check:tokens && npm run typecheck && npm run check:exports-stories && npm run check:kolibri-toggle && npm run test:select-reset && npm run typecheck:theme && npm run test:theme && npm test",
73
+ "test:select-reset": "node --test tests/select-controlled-reset.test.mjs",
74
+ "prepack": "npm run build",
75
+ "check:runtime": "node scripts/check-package-runtime.mjs",
76
+ "test:theme": "node --test tests/theme-provider.test.mjs",
77
+ "typecheck:theme": "tsc --noEmit -p tests/tsconfig.theme.json"
71
78
  },
72
79
  "peerDependencies": {
73
80
  "react": "^18.2.0 || ^19.0.0",
@@ -75,6 +82,7 @@
75
82
  },
76
83
  "dependencies": {
77
84
  "@radix-ui/react-collapsible": "^1.1.14",
85
+ "@radix-ui/react-compose-refs": "1.1.2",
78
86
  "@radix-ui/react-context-menu": "^2.2.16",
79
87
  "@radix-ui/react-dropdown-menu": "^2.1.18",
80
88
  "@radix-ui/react-label": "^2.1.10",
@@ -101,6 +109,7 @@
101
109
  "@types/react-dom": "^19.2.3",
102
110
  "@vitest/browser-playwright": "^4.0.18",
103
111
  "@vitest/coverage-v8": "^4.0.18",
112
+ "jsdom": "30.1.2",
104
113
  "playwright": "^1.58.2",
105
114
  "storybook": "^10.2.16",
106
115
  "tailwindcss": "^4.2.1",