@gaulatti/bleecker 0.1.40 → 0.1.42

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.
@@ -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
  }
@@ -0,0 +1,25 @@
1
+ import type { CSSProperties } from 'react';
2
+ export interface AttentionColorOptions {
3
+ /** The category or column hue, expressed as a CSS hue angle. */
4
+ hue: number;
5
+ /** Semantic urgency on a continuous 0–10 scale. */
6
+ intensity: number;
7
+ }
8
+ export interface AttentionColorResult {
9
+ /** The mixed category-to-danger color used for markers and labels. */
10
+ accent: string;
11
+ /** Percentage of the surface traversed by the gradient. */
12
+ coverage: number;
13
+ /** Clamped 0–10 intensity. */
14
+ intensity: number;
15
+ /** Percentage of red in the accent color. */
16
+ redMix: number;
17
+ /** Ready-to-apply surface styles. */
18
+ style: CSSProperties;
19
+ }
20
+ /**
21
+ * Builds a calm-to-urgent surface treatment without erasing category identity.
22
+ * An intensity of 2 mixes 80% category hue with 20% red; an intensity of 8
23
+ * mixes 20% category hue with 80% red. Gradient coverage grows continuously.
24
+ */
25
+ export declare function createAttentionColor({ hue, intensity: rawIntensity }: AttentionColorOptions): AttentionColorResult;
@@ -0,0 +1,27 @@
1
+ function clamp(value, min, max) {
2
+ return Math.min(max, Math.max(min, value));
3
+ }
4
+ /**
5
+ * Builds a calm-to-urgent surface treatment without erasing category identity.
6
+ * An intensity of 2 mixes 80% category hue with 20% red; an intensity of 8
7
+ * mixes 20% category hue with 80% red. Gradient coverage grows continuously.
8
+ */
9
+ export function createAttentionColor({ hue, intensity: rawIntensity }) {
10
+ const normalizedHue = ((Math.round(Number.isFinite(hue) ? hue : 210) % 360) + 360) % 360;
11
+ const intensity = clamp(Number.isFinite(rawIntensity) ? rawIntensity : 0, 0, 10);
12
+ const redMix = Math.round(intensity * 10);
13
+ const categoryMix = 100 - redMix;
14
+ const coverage = 24 + intensity * 7.2;
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}%)`;
17
+ return {
18
+ accent,
19
+ coverage,
20
+ intensity,
21
+ redMix,
22
+ style: {
23
+ background: `linear-gradient(45deg, color-mix(in oklab, ${accent} ${colorStrength}%, rgba(17, 30, 41, 0.94)) 0%, color-mix(in oklab, ${accent} ${Math.round(colorStrength * 0.66)}%, rgba(17, 30, 41, 0.94)) ${(coverage * 0.58).toFixed(1)}%, rgba(17, 30, 41, 0.94) ${coverage.toFixed(1)}%)`,
24
+ borderColor: `color-mix(in oklab, ${accent} ${Math.round(12 + intensity * 2.4)}%, rgba(255, 255, 255, 0.06))`
25
+ }
26
+ };
27
+ }
@@ -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 {};
@@ -97,33 +97,169 @@ export function useEventCallback(callback) {
97
97
  }, [callback]);
98
98
  return React.useCallback((...args) => ref.current?.(...args), []);
99
99
  }
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(',');
100
+ const ModalContext = React.createContext([]);
101
+ /** Preserves logical modal ancestry across React portals. */
102
+ export function ModalLayerScope({ layerRef, children }) {
103
+ const ancestors = React.useContext(ModalContext);
104
+ const value = React.useMemo(() => [...ancestors, { ref: layerRef }], [ancestors, layerRef]);
105
+ return React.createElement(ModalContext.Provider, { value }, children);
106
+ }
107
+ const modalBranches = new WeakMap();
108
+ /** Attach to a portaled widget owned by the nearest modal. */
109
+ export function useModalBranch() {
110
+ const ancestors = React.useContext(ModalContext);
111
+ const ownerRef = ancestors.at(-1)?.ref;
112
+ const [node, setNode] = React.useState(null);
113
+ const ref = React.useCallback((element) => {
114
+ if (ownerRef)
115
+ setNode(element);
116
+ }, [ownerRef]);
117
+ React.useLayoutEffect(() => {
118
+ const owner = ownerRef?.current;
119
+ if (!owner || !node)
120
+ return;
121
+ const branches = modalBranches.get(owner) ?? new Set();
122
+ branches.add(node);
123
+ modalBranches.set(owner, branches);
124
+ node.inert = owner.inert;
125
+ const overlay = owner.closest('[data-bleecker-modal-overlay]');
126
+ const surface = node.closest('[data-radix-popper-content-wrapper]') ?? node;
127
+ if (overlay)
128
+ surface.style.zIndex = String(Number(overlay.style.zIndex) + 1);
129
+ const stack = modalStacks.get(owner.ownerDocument);
130
+ if (stack)
131
+ updateModalStack(stack);
132
+ return () => {
133
+ branches.delete(node);
134
+ const current = modalStacks.get(owner.ownerDocument);
135
+ if (current)
136
+ updateModalStack(current);
137
+ };
138
+ }, [node, ownerRef]);
139
+ return ref;
140
+ }
141
+ function focusableElements(layer) {
142
+ const doc = layer.ownerDocument;
143
+ const view = doc.defaultView;
144
+ if (!view)
145
+ return [];
146
+ const roots = [layer, ...modalBranches.get(layer) ?? []];
147
+ const candidates = roots.flatMap((root) => Array.from(root.querySelectorAll('*'))).filter((element) => {
148
+ const editableHost = element.isContentEditable && !element.parentElement?.isContentEditable;
149
+ const sequential = element.tabIndex >= 0 || (editableHost && !element.hasAttribute('tabindex'));
150
+ return sequential && !element.matches(':disabled') &&
151
+ !element.closest('[hidden], [inert], [aria-hidden="true"]') &&
152
+ element.getClientRects().length > 0 && view.getComputedStyle(element).visibility === 'visible';
153
+ });
154
+ return [...new Set(candidates)].filter((element) => {
155
+ if (!element.matches('input[type="radio"]') || !element.name)
156
+ return true;
157
+ const input = element;
158
+ const group = candidates.filter((candidate) => candidate.matches('input[type="radio"]') &&
159
+ candidate.name === input.name && candidate.form === input.form);
160
+ return input === (group.find((radio) => radio.checked) ?? group[0]);
161
+ }).sort((a, b) => {
162
+ const aIndex = a.tabIndex > 0 ? a.tabIndex : Infinity;
163
+ const bIndex = b.tabIndex > 0 ? b.tabIndex : Infinity;
164
+ if (aIndex !== bIndex)
165
+ return aIndex < bIndex ? -1 : 1;
166
+ return a.compareDocumentPosition(b) & view.Node.DOCUMENT_POSITION_FOLLOWING ? -1 : 1;
167
+ });
168
+ }
169
+ const modalStacks = new WeakMap();
170
+ function rootEntry(entry, stack) {
171
+ return entry.ancestors.map((scope) => stack.entries.find((candidate) => scope.ref.current === candidate.layer)).find((candidate) => candidate !== undefined) ?? entry;
172
+ }
173
+ function updateModalStack(stack) {
174
+ for (const [element, inert] of stack.background)
175
+ element.inert = inert;
176
+ stack.background.clear();
177
+ stack.entries.sort((a, b) => rootEntry(a, stack).order - rootEntry(b, stack).order || a.ancestors.length - b.ancestors.length || a.order - b.order);
178
+ const active = stack.entries.at(-1) ?? null;
179
+ for (const [index, entry] of stack.entries.entries()) {
180
+ entry.layer.inert = entry !== active;
181
+ const overlay = entry.layer.closest('[data-bleecker-modal-overlay]');
182
+ if (overlay)
183
+ overlay.style.zIndex = String(50 + index);
184
+ for (const branch of modalBranches.get(entry.layer) ?? []) {
185
+ branch.inert = entry !== active;
186
+ const surface = branch.closest('[data-radix-popper-content-wrapper]') ?? branch;
187
+ surface.style.zIndex = String(51 + index);
188
+ }
189
+ }
190
+ stack.active = active;
191
+ if (active) {
192
+ const roots = [active.layer.closest('[data-bleecker-modal-overlay]') ?? active.layer,
193
+ ...Array.from(modalBranches.get(active.layer) ?? []).map((branch) => branch.closest('[data-radix-popper-content-wrapper]') ?? branch)];
194
+ for (const child of Array.from(stack.doc.body.children)) {
195
+ const allowed = roots.some((root) => child === root || child.contains(root));
196
+ if (!allowed)
197
+ stack.background.set(child, child.inert);
198
+ child.inert = !allowed;
199
+ }
200
+ }
201
+ }
202
+ function containsModalTarget(layer, target) {
203
+ return layer.contains(target) || Array.from(modalBranches.get(layer) ?? []).some((branch) => branch.contains(target));
204
+ }
205
+ function focusFirst(entry) {
206
+ (focusableElements(entry.layer)[0] ?? entry.layer).focus({ preventScroll: true });
207
+ }
108
208
  /**
109
- * Supplies the focus, Escape, and scroll-lock behavior expected of custom
110
- * modal surfaces such as sheets and drawers.
209
+ * All Bleecker modal surfaces share attachment, ancestry, focus, keyboard, and
210
+ * scroll ownership. The returned object ref remains the public hook contract.
111
211
  */
112
212
  export function useModalLayer(open, onDismiss) {
213
+ const [layer, setLayer] = React.useState(null);
113
214
  const layerRef = React.useRef(null);
215
+ const ancestors = React.useContext(ModalContext);
216
+ const snapshot = React.useRef({ layer: null, open: false, focus: null });
114
217
  const dismiss = useEventCallback(onDismiss);
218
+ React.useLayoutEffect(() => {
219
+ const node = layerRef.current;
220
+ if (node && open && (!snapshot.current.open || snapshot.current.layer !== node)) {
221
+ const active = node.ownerDocument.activeElement;
222
+ const constructor = node.ownerDocument.defaultView?.HTMLElement;
223
+ snapshot.current.focus = constructor && active instanceof constructor ? active : null;
224
+ }
225
+ snapshot.current.layer = node;
226
+ snapshot.current.open = open;
227
+ if (node) {
228
+ if (!open)
229
+ node.inert = true;
230
+ const stack = modalStacks.get(node.ownerDocument);
231
+ if (stack && open)
232
+ updateModalStack(stack);
233
+ }
234
+ setLayer(node);
235
+ });
115
236
  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 });
237
+ if (!open || !layer)
238
+ return;
239
+ const doc = layer.ownerDocument;
240
+ let stack = modalStacks.get(doc);
241
+ if (!stack) {
242
+ stack = { doc, entries: [], overflow: doc.body.style.overflow, active: null, sequence: 0, background: new Map(), observer: null };
243
+ modalStacks.set(doc, stack);
244
+ doc.body.style.overflow = 'hidden';
245
+ const observer = doc.defaultView?.MutationObserver;
246
+ if (observer) {
247
+ const currentStack = stack;
248
+ stack.observer = new observer(() => { updateModalStack(currentStack); });
249
+ stack.observer.observe(doc.body, { childList: true });
250
+ }
251
+ }
252
+ const entry = { layer, ancestors, previousFocus: snapshot.current.focus, order: ++stack.sequence };
253
+ stack.entries.push(entry);
254
+ updateModalStack(stack);
255
+ // All simultaneously mounted descendants register before focus is chosen.
256
+ queueMicrotask(() => {
257
+ if (modalStacks.get(doc) === stack && stack.active === entry)
258
+ focusFirst(entry);
259
+ });
126
260
  const handleKeyDown = (event) => {
261
+ if (stack.active !== entry || event.defaultPrevented)
262
+ return;
127
263
  if (event.key === 'Escape') {
128
264
  event.preventDefault();
129
265
  dismiss();
@@ -131,29 +267,63 @@ export function useModalLayer(open, onDismiss) {
131
267
  }
132
268
  if (event.key !== 'Tab')
133
269
  return;
134
- const currentFocusable = Array.from(layer.querySelectorAll(focusableSelector));
135
- if (currentFocusable.length === 0) {
270
+ const focusable = focusableElements(layer);
271
+ const first = focusable[0];
272
+ const last = focusable.at(-1);
273
+ if (!first || !last) {
136
274
  event.preventDefault();
137
- layer.focus();
138
- return;
275
+ layer.focus({ preventScroll: true });
276
+ }
277
+ else if (!focusable.includes(doc.activeElement)) {
278
+ event.preventDefault();
279
+ (event.shiftKey ? last : first).focus({ preventScroll: true });
280
+ }
281
+ else if (event.shiftKey && doc.activeElement === first) {
282
+ event.preventDefault();
283
+ last.focus({ preventScroll: true });
139
284
  }
140
- const first = currentFocusable[0];
141
- const last = currentFocusable[currentFocusable.length - 1];
142
- if (event.shiftKey && document.activeElement === first) {
285
+ else if (!event.shiftKey && doc.activeElement === last) {
143
286
  event.preventDefault();
144
- last.focus();
287
+ first.focus({ preventScroll: true });
145
288
  }
146
- else if (!event.shiftKey && document.activeElement === last) {
289
+ else {
290
+ // Positive tabindex participates in the document's global order. Move
291
+ // through the modal's sequential order so background stops are skipped.
147
292
  event.preventDefault();
148
- first.focus();
293
+ const index = focusable.indexOf(doc.activeElement);
294
+ focusable[index + (event.shiftKey ? -1 : 1)].focus({ preventScroll: true });
149
295
  }
150
296
  };
151
- document.addEventListener('keydown', handleKeyDown);
297
+ doc.addEventListener('keydown', handleKeyDown);
152
298
  return () => {
153
- document.removeEventListener('keydown', handleKeyDown);
154
- document.body.style.overflow = previousOverflow;
155
- previouslyFocused?.focus({ preventScroll: true });
299
+ doc.removeEventListener('keydown', handleKeyDown);
300
+ const wasActive = stack.active === entry;
301
+ for (const successor of stack.entries) {
302
+ if (successor.previousFocus && containsModalTarget(layer, successor.previousFocus))
303
+ successor.previousFocus = entry.previousFocus;
304
+ }
305
+ stack.entries.splice(stack.entries.indexOf(entry), 1);
306
+ layer.inert = true;
307
+ updateModalStack(stack);
308
+ const parent = stack.active;
309
+ if (!parent) {
310
+ stack.observer?.disconnect();
311
+ doc.body.style.overflow = stack.overflow;
312
+ modalStacks.delete(doc);
313
+ }
314
+ const overlay = layer.closest('[data-bleecker-modal-overlay]');
315
+ if (overlay)
316
+ overlay.inert = true;
317
+ if (!wasActive)
318
+ return;
319
+ const previous = entry.previousFocus;
320
+ if (previous?.isConnected && !previous.closest('[inert]') && (!parent || containsModalTarget(parent.layer, previous))) {
321
+ previous.focus({ preventScroll: true });
322
+ }
323
+ else if (parent) {
324
+ focusFirst(parent);
325
+ }
156
326
  };
157
- }, [dismiss, open]);
327
+ }, [ancestors, dismiss, layer, open]);
158
328
  return layerRef;
159
329
  }
package/package.json CHANGED
@@ -1,6 +1,7 @@
1
1
  {
2
2
  "name": "@gaulatti/bleecker",
3
- "version": "0.1.40",
3
+ "version": "0.1.42",
4
+ "license": "MIT",
4
5
  "repository": {
5
6
  "type": "git",
6
7
  "url": "https://github.com/gaulatti/bleecker"
@@ -59,15 +60,17 @@
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
+ "build-storybook": "npm run check:exports-stories && npm run check:kolibri-toggle && npm run build:css && storybook build",
67
69
  "typecheck": "tsc --noEmit -p tsconfig.json",
68
70
  "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"
71
+ "check": "npm run check:tokens && npm run typecheck && npm run check:exports-stories && npm run check:kolibri-toggle && npm test",
72
+ "prepack": "npm run build",
73
+ "check:runtime": "node scripts/check-package-runtime.mjs"
71
74
  },
72
75
  "peerDependencies": {
73
76
  "react": "^18.2.0 || ^19.0.0",
@@ -75,6 +78,7 @@
75
78
  },
76
79
  "dependencies": {
77
80
  "@radix-ui/react-collapsible": "^1.1.14",
81
+ "@radix-ui/react-compose-refs": "1.1.2",
78
82
  "@radix-ui/react-context-menu": "^2.2.16",
79
83
  "@radix-ui/react-dropdown-menu": "^2.1.18",
80
84
  "@radix-ui/react-label": "^2.1.10",