@jobber/components 8.20.2 → 8.21.0

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 (55) hide show
  1. package/dist/BottomSheet-cjs.js +9 -58
  2. package/dist/BottomSheet-es.js +2 -47
  3. package/dist/Card/index.cjs +4 -0
  4. package/dist/Card/index.mjs +4 -0
  5. package/dist/ComboboxChipRemove-cjs.js +3418 -0
  6. package/dist/ComboboxChipRemove-es.js +3366 -0
  7. package/dist/ComboboxPrimitive-cjs.js +170 -0
  8. package/dist/ComboboxPrimitive-es.js +168 -0
  9. package/dist/DataDump/index.cjs +4 -0
  10. package/dist/DataDump/index.mjs +4 -0
  11. package/dist/InputNumberExperimental-cjs.js +45 -44
  12. package/dist/InputNumberExperimental-es.js +3 -2
  13. package/dist/InternalBackdrop-cjs.js +4278 -0
  14. package/dist/InternalBackdrop-es.js +4204 -0
  15. package/dist/Menu/index.cjs +4 -0
  16. package/dist/Menu/index.mjs +4 -0
  17. package/dist/Menu-cjs.js +9 -8
  18. package/dist/Menu-es.js +2 -1
  19. package/dist/MenuSubmenuTrigger-cjs.js +208 -1969
  20. package/dist/MenuSubmenuTrigger-es.js +7 -1759
  21. package/dist/NumberFieldInput-cjs.js +56 -439
  22. package/dist/NumberFieldInput-es.js +6 -376
  23. package/dist/Page/index.cjs +4 -0
  24. package/dist/Page/index.mjs +4 -0
  25. package/dist/ScrollAreaViewport-cjs.js +108 -4356
  26. package/dist/ScrollAreaViewport-es.js +6 -4201
  27. package/dist/buttonRenderAdapter-cjs.js +56 -0
  28. package/dist/buttonRenderAdapter-es.js +51 -0
  29. package/dist/clamp-cjs.js +0 -1194
  30. package/dist/clamp-es.js +1 -1091
  31. package/dist/docs/empty-states/empty-states.md +29 -0
  32. package/dist/index.cjs +4 -0
  33. package/dist/index.mjs +4 -0
  34. package/dist/primitives/BottomSheet/index.cjs +5 -2
  35. package/dist/primitives/BottomSheet/index.mjs +5 -2
  36. package/dist/primitives/ComboboxPrimitive/ComboboxPrimitive.d.ts +32 -0
  37. package/dist/primitives/ComboboxPrimitive/ComboboxPrimitive.types.d.ts +30 -0
  38. package/dist/primitives/ComboboxPrimitive/index.cjs +28 -0
  39. package/dist/primitives/ComboboxPrimitive/index.d.ts +2 -0
  40. package/dist/primitives/ComboboxPrimitive/index.mjs +22 -0
  41. package/dist/primitives/InputNumberExperimental/index.cjs +4 -2
  42. package/dist/primitives/InputNumberExperimental/index.mjs +4 -2
  43. package/dist/primitives/index.cjs +11 -2
  44. package/dist/primitives/index.d.ts +1 -0
  45. package/dist/primitives/index.mjs +10 -2
  46. package/dist/styles.css +767 -0
  47. package/dist/unstyledPrimitives/index.cjs +237 -3588
  48. package/dist/unstyledPrimitives/index.mjs +96 -3447
  49. package/dist/useButton-cjs.js +1196 -0
  50. package/dist/useButton-es.js +1091 -0
  51. package/dist/useCompositeListItem-cjs.js +1792 -0
  52. package/dist/useCompositeListItem-es.js +1762 -0
  53. package/dist/useLabel-cjs.js +411 -0
  54. package/dist/useLabel-es.js +378 -0
  55. package/package.json +2 -2
package/dist/clamp-es.js CHANGED
@@ -1,1095 +1,5 @@
1
- import * as React from 'react';
2
- import { a as useRefWithInit, E as EMPTY_OBJECT, f as formatErrorMessage, m as mergeProps, c as makeEventPreventable } from './useRenderElement-es.js';
3
- import { i as isShadowRoot, b as isElement, a as isHTMLElement } from './floating-ui.utils.dom-es.js';
4
- import * as ReactDOM from 'react-dom';
5
-
6
- // https://github.com/mui/material-ui/issues/41190#issuecomment-2040873379
7
- const useInsertionEffect = React[`useInsertionEffect${Math.random().toFixed(1)}`.slice(0, -3)];
8
- const useSafeInsertionEffect =
9
- // React 17 doesn't have useInsertionEffect.
10
- useInsertionEffect &&
11
- // Preact replaces useInsertionEffect with useLayoutEffect and fires too late.
12
- useInsertionEffect !== React.useLayoutEffect ? useInsertionEffect : fn => fn();
13
- /**
14
- * Stabilizes the function passed so it's always the same between renders.
15
- *
16
- * The function becomes non-reactive to any values it captures.
17
- * It can safely be passed as a dependency of `React.useMemo` and `React.useEffect` without re-triggering them if its captured values change.
18
- *
19
- * The function must only be called inside effects and event handlers, never during render (which throws an error).
20
- *
21
- * This hook is a more permissive version of React 19.2's `React.useEffectEvent` in that it can be passed through contexts and called in event handler props, not just effects.
22
- */
23
- function useStableCallback(callback) {
24
- const stable = useRefWithInit(createStableCallback).current;
25
- stable.next = callback;
26
- useSafeInsertionEffect(stable.effect);
27
- return stable.trampoline;
28
- }
29
- function createStableCallback() {
30
- const stable = {
31
- next: undefined,
32
- callback: assertNotCalled,
33
- trampoline: (...args) => stable.callback?.(...args),
34
- effect: () => {
35
- stable.callback = stable.next;
36
- }
37
- };
38
- return stable;
39
- }
40
- function assertNotCalled() {
41
- if (process.env.NODE_ENV !== 'production') {
42
- throw /* minify-error-disabled */new Error('Base UI: Cannot call an event handler while rendering.');
43
- }
44
- }
45
-
46
- function useControlled({
47
- controlled,
48
- default: defaultProp,
49
- name,
50
- state = 'value'
51
- }) {
52
- // isControlled is ignored in the hook dependency lists as it should never change.
53
- const {
54
- current: isControlled
55
- } = React.useRef(controlled !== undefined);
56
- const [valueState, setValue] = React.useState(defaultProp);
57
- const value = isControlled ? controlled : valueState;
58
- if (process.env.NODE_ENV !== 'production') {
59
- React.useEffect(() => {
60
- if (isControlled !== (controlled !== undefined)) {
61
- console.error([`Base UI: A component is changing the ${isControlled ? '' : 'un'}controlled ${state} state of ${name} to be ${isControlled ? 'un' : ''}controlled.`, 'Elements should not switch from uncontrolled to controlled (or vice versa).', `Decide between using a controlled or uncontrolled ${name} ` + 'element for the lifetime of the component.', "The nature of the state is determined during the first render. It's considered controlled if the value is not `undefined`.", 'More info: https://fb.me/react-controlled-components'].join('\n'));
62
- }
63
- }, [state, name, controlled]);
64
- const {
65
- current: defaultValue
66
- } = React.useRef(defaultProp);
67
- React.useEffect(() => {
68
- // See https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/is for more details.
69
- if (!isControlled && JSON.stringify(defaultValue) !== JSON.stringify(defaultProp)) {
70
- console.error([`Base UI: A component is changing the default ${state} state of an uncontrolled ${name} after being initialized. ` + `To suppress this warning opt to use a controlled ${name}.`].join('\n'));
71
- }
72
- }, [JSON.stringify(defaultProp)]);
73
- }
74
- const setValueIfUncontrolled = React.useCallback(newValue => {
75
- if (!isControlled) {
76
- setValue(newValue);
77
- }
78
- }, []);
79
- return [value, setValueIfUncontrolled];
80
- }
81
-
82
- const noop = () => {};
83
- const useIsoLayoutEffect = typeof document !== 'undefined' ? React.useLayoutEffect : noop;
84
-
85
- const visuallyHiddenBase = {
86
- clipPath: 'inset(50%)',
87
- overflow: 'hidden',
88
- whiteSpace: 'nowrap',
89
- border: 0,
90
- padding: 0,
91
- width: 1,
92
- height: 1,
93
- margin: -1
94
- };
95
- const visuallyHidden = {
96
- ...visuallyHiddenBase,
97
- position: 'fixed',
98
- top: 0,
99
- left: 0
100
- };
101
- const visuallyHiddenInput = {
102
- ...visuallyHiddenBase,
103
- position: 'absolute'
104
- };
105
-
106
- const EMPTY$2 = [];
107
-
108
- /**
109
- * A React.useEffect equivalent that runs once, when the component is mounted.
110
- */
111
- function useOnMount(fn) {
112
- // TODO: uncomment once we enable eslint-plugin-react-compiler // eslint-disable-next-line react-compiler/react-compiler -- no need to put `fn` in the dependency array
113
- /* eslint-disable react-hooks/exhaustive-deps */
114
- React.useEffect(fn, EMPTY$2);
115
- /* eslint-enable react-hooks/exhaustive-deps */
116
- }
117
-
118
- /** Unlike `setTimeout`, rAF doesn't guarantee a positive integer return value, so we can't have
119
- * a monomorphic `uint` type with `0` meaning empty.
120
- * See warning note at:
121
- * https://developer.mozilla.org/en-US/docs/Web/API/Window/requestAnimationFrame#return_value */
122
- const EMPTY$1 = null;
123
- let LAST_RAF = globalThis.requestAnimationFrame;
124
- class Scheduler {
125
- /* This implementation uses an array as a backing data-structure for frame callbacks.
126
- * It allows `O(1)` callback cancelling by inserting a `null` in the array, though it
127
- * never calls the native `cancelAnimationFrame` if there are no frames left. This can
128
- * be much more efficient if there is a call pattern that alterns as
129
- * "request-cancel-request-cancel-…".
130
- * But in the case of "request-request-…-cancel-cancel-…", it leaves the final animation
131
- * frame to run anyway. We turn that frame into a `O(1)` no-op via `callbacksCount`. */
132
-
133
- callbacks = [];
134
- callbacksCount = 0;
135
- nextId = 1;
136
- startId = 1;
137
- isScheduled = false;
138
- tick = timestamp => {
139
- this.isScheduled = false;
140
- const currentCallbacks = this.callbacks;
141
- const currentCallbacksCount = this.callbacksCount;
142
-
143
- // Update these before iterating, callbacks could call `requestAnimationFrame` again.
144
- this.callbacks = [];
145
- this.callbacksCount = 0;
146
- this.startId = this.nextId;
147
- if (currentCallbacksCount > 0) {
148
- for (let i = 0; i < currentCallbacks.length; i += 1) {
149
- currentCallbacks[i]?.(timestamp);
150
- }
151
- }
152
- };
153
- request(fn) {
154
- const id = this.nextId;
155
- this.nextId += 1;
156
- this.callbacks.push(fn);
157
- this.callbacksCount += 1;
158
-
159
- /* In a test environment with fake timers, a fake `requestAnimationFrame` can be called
160
- * but there's no guarantee that the animation frame will actually run before the fake
161
- * timers are teared, which leaves `isScheduled` set, but won't run our `tick()`. */
162
- const didRAFChange = process.env.NODE_ENV !== 'production' && LAST_RAF !== requestAnimationFrame && (LAST_RAF = requestAnimationFrame, true);
163
- if (!this.isScheduled || didRAFChange) {
164
- requestAnimationFrame(this.tick);
165
- this.isScheduled = true;
166
- }
167
- return id;
168
- }
169
- cancel(id) {
170
- const index = id - this.startId;
171
- if (index < 0 || index >= this.callbacks.length) {
172
- return;
173
- }
174
- this.callbacks[index] = null;
175
- this.callbacksCount -= 1;
176
- }
177
- }
178
- const scheduler = new Scheduler();
179
- class AnimationFrame {
180
- static create() {
181
- return new AnimationFrame();
182
- }
183
- static request(fn) {
184
- return scheduler.request(fn);
185
- }
186
- static cancel(id) {
187
- return scheduler.cancel(id);
188
- }
189
- currentId = EMPTY$1;
190
-
191
- /**
192
- * Executes `fn` after `delay`, clearing any previously scheduled call.
193
- */
194
- request(fn) {
195
- this.cancel();
196
- this.currentId = scheduler.request(() => {
197
- this.currentId = EMPTY$1;
198
- fn();
199
- });
200
- }
201
- cancel = () => {
202
- if (this.currentId !== EMPTY$1) {
203
- scheduler.cancel(this.currentId);
204
- this.currentId = EMPTY$1;
205
- }
206
- };
207
- disposeEffect = () => {
208
- return this.cancel;
209
- };
210
- }
211
-
212
- /**
213
- * A `requestAnimationFrame` with automatic cleanup and guard.
214
- */
215
- function useAnimationFrame() {
216
- const timeout = useRefWithInit(AnimationFrame.create).current;
217
- useOnMount(timeout.disposeEffect);
218
- return timeout;
219
- }
220
-
221
- const EMPTY = 0;
222
- class Timeout {
223
- static create() {
224
- return new Timeout();
225
- }
226
- currentId = EMPTY;
227
-
228
- /**
229
- * Executes `fn` after `delay`, clearing any previously scheduled call.
230
- */
231
- start(delay, fn) {
232
- this.clear();
233
- this.currentId = setTimeout(() => {
234
- this.currentId = EMPTY;
235
- fn();
236
- }, delay); /* Node.js types are enabled in development */
237
- }
238
- isStarted() {
239
- return this.currentId !== EMPTY;
240
- }
241
- clear = () => {
242
- if (this.currentId !== EMPTY) {
243
- clearTimeout(this.currentId);
244
- this.currentId = EMPTY;
245
- }
246
- };
247
- disposeEffect = () => {
248
- return this.clear;
249
- };
250
- }
251
-
252
- /**
253
- * A `setTimeout` with automatic cleanup and guard.
254
- */
255
- function useTimeout() {
256
- const timeout = useRefWithInit(Timeout.create).current;
257
- useOnMount(timeout.disposeEffect);
258
- return timeout;
259
- }
260
-
261
- /**
262
- * Untracks the provided value by turning it into a ref to remove its reactivity.
263
- *
264
- * Used to access the passed value inside `React.useEffect` without causing the effect to re-run when the value changes.
265
- */
266
- function useValueAsRef(value) {
267
- const latest = useRefWithInit(createLatestRef, value).current;
268
- latest.next = value;
269
-
270
- // eslint-disable-next-line react-hooks/exhaustive-deps
271
- useIsoLayoutEffect(latest.effect);
272
- return latest;
273
- }
274
- function createLatestRef(value) {
275
- const latest = {
276
- current: value,
277
- next: value,
278
- effect: () => {
279
- latest.current = latest.next;
280
- }
281
- };
282
- return latest;
283
- }
284
-
285
- const hasNavigator = typeof navigator !== 'undefined';
286
- const nav = getNavigatorData();
287
- const platform = getPlatform();
288
- const userAgent = getUserAgent();
289
- const isWebKit = typeof CSS === 'undefined' || !CSS.supports ? false : CSS.supports('-webkit-backdrop-filter:none');
290
- const isIOS =
291
- // iPads can claim to be MacIntel
292
- nav.platform === 'MacIntel' && nav.maxTouchPoints > 1 ? true : /iP(hone|ad|od)|iOS/.test(nav.platform);
293
- const isFirefox = hasNavigator && /firefox/i.test(userAgent);
294
- const isSafari = hasNavigator && /apple/i.test(navigator.vendor);
295
- const isAndroid = hasNavigator && /android/i.test(platform) || /android/i.test(userAgent);
296
- const isMac = hasNavigator && platform.toLowerCase().startsWith('mac') && !navigator.maxTouchPoints;
297
- const isJSDOM = userAgent.includes('jsdom/');
298
-
299
- // Avoid Chrome DevTools blue warning.
300
- function getNavigatorData() {
301
- if (!hasNavigator) {
302
- return {
303
- platform: '',
304
- maxTouchPoints: -1
305
- };
306
- }
307
- const uaData = navigator.userAgentData;
308
- if (uaData?.platform) {
309
- return {
310
- platform: uaData.platform,
311
- maxTouchPoints: navigator.maxTouchPoints
312
- };
313
- }
314
- return {
315
- platform: navigator.platform ?? '',
316
- maxTouchPoints: navigator.maxTouchPoints ?? -1
317
- };
318
- }
319
- function getUserAgent() {
320
- if (!hasNavigator) {
321
- return '';
322
- }
323
- const uaData = navigator.userAgentData;
324
- if (uaData && Array.isArray(uaData.brands)) {
325
- return uaData.brands.map(({
326
- brand,
327
- version
328
- }) => `${brand}/${version}`).join(' ');
329
- }
330
- return navigator.userAgent;
331
- }
332
- function getPlatform() {
333
- if (!hasNavigator) {
334
- return '';
335
- }
336
- const uaData = navigator.userAgentData;
337
- if (uaData?.platform) {
338
- return uaData.platform;
339
- }
340
- return navigator.platform ?? '';
341
- }
342
-
343
- const FOCUSABLE_ATTRIBUTE = 'data-base-ui-focusable';
344
- const ACTIVE_KEY = 'active';
345
- const SELECTED_KEY = 'selected';
346
- const TYPEABLE_SELECTOR = "input:not([type='hidden']):not([disabled])," + "[contenteditable]:not([contenteditable='false']),textarea:not([disabled])";
347
- const ARROW_LEFT = 'ArrowLeft';
348
- const ARROW_RIGHT = 'ArrowRight';
349
- const ARROW_UP = 'ArrowUp';
350
- const ARROW_DOWN = 'ArrowDown';
351
-
352
- function activeElement(doc) {
353
- let element = doc.activeElement;
354
- while (element?.shadowRoot?.activeElement != null) {
355
- element = element.shadowRoot.activeElement;
356
- }
357
- return element;
358
- }
359
- function contains(parent, child) {
360
- if (!parent || !child) {
361
- return false;
362
- }
363
- const rootNode = child.getRootNode?.();
364
-
365
- // First, attempt with faster native method
366
- if (parent.contains(child)) {
367
- return true;
368
- }
369
-
370
- // then fallback to custom implementation with Shadow DOM support
371
- if (rootNode && isShadowRoot(rootNode)) {
372
- let next = child;
373
- while (next) {
374
- if (parent === next) {
375
- return true;
376
- }
377
- next = next.parentNode || next.host;
378
- }
379
- }
380
-
381
- // Give up, the result is false
382
- return false;
383
- }
384
- function isTargetInsideEnabledTrigger(target, triggerElements) {
385
- if (!isElement(target)) {
386
- return false;
387
- }
388
- const targetElement = target;
389
- if (triggerElements.hasElement(targetElement)) {
390
- return !targetElement.hasAttribute('data-trigger-disabled');
391
- }
392
- for (const [, trigger] of triggerElements.entries()) {
393
- if (contains(trigger, targetElement)) {
394
- return !trigger.hasAttribute('data-trigger-disabled');
395
- }
396
- }
397
- return false;
398
- }
399
- function getTarget(event) {
400
- if ('composedPath' in event) {
401
- return event.composedPath()[0];
402
- }
403
-
404
- // TS thinks `event` is of type never as it assumes all browsers support
405
- // `composedPath()`, but browsers without shadow DOM don't.
406
- return event.target;
407
- }
408
- function isEventTargetWithin(event, node) {
409
- if (node == null) {
410
- return false;
411
- }
412
- if ('composedPath' in event) {
413
- return event.composedPath().includes(node);
414
- }
415
-
416
- // TS thinks `event` is of type never as it assumes all browsers support composedPath, but browsers without shadow dom don't
417
- const eventAgain = event;
418
- return eventAgain.target != null && node.contains(eventAgain.target);
419
- }
420
- function isRootElement(element) {
421
- return element.matches('html,body');
422
- }
423
- function isTypeableElement(element) {
424
- return isHTMLElement(element) && element.matches(TYPEABLE_SELECTOR);
425
- }
426
- function isTypeableCombobox(element) {
427
- if (!element) {
428
- return false;
429
- }
430
- return element.getAttribute('role') === 'combobox' && isTypeableElement(element);
431
- }
432
- function matchesFocusVisible(element) {
433
- // We don't want to block focus from working with `visibleOnly`
434
- // (JSDOM doesn't match `:focus-visible` when the element has `:focus`)
435
- if (!element || isJSDOM) {
436
- return true;
437
- }
438
- try {
439
- return element.matches(':focus-visible');
440
- } catch (_e) {
441
- return true;
442
- }
443
- }
444
- function getFloatingFocusElement(floatingElement) {
445
- if (!floatingElement) {
446
- return null;
447
- }
448
- // Try to find the element that has `{...getFloatingProps()}` spread on it.
449
- // This indicates the floating element is acting as a positioning wrapper, and
450
- // so focus should be managed on the child element with the event handlers and
451
- // aria props.
452
- return floatingElement.hasAttribute(FOCUSABLE_ATTRIBUTE) ? floatingElement : floatingElement.querySelector(`[${FOCUSABLE_ATTRIBUTE}]`) || floatingElement;
453
- }
454
-
455
- function stopEvent(event) {
456
- event.preventDefault();
457
- event.stopPropagation();
458
- }
459
- function isReactEvent(event) {
460
- return 'nativeEvent' in event;
461
- }
462
-
463
- // License: https://github.com/adobe/react-spectrum/blob/main/packages/@react-aria/utils/src/isVirtualEvent.ts
464
- function isVirtualClick(event) {
465
- if (event.pointerType === '' && event.isTrusted) {
466
- return true;
467
- }
468
- if (isAndroid && event.pointerType) {
469
- return event.type === 'click' && event.buttons === 1;
470
- }
471
- return event.detail === 0 && !event.pointerType;
472
- }
473
- function isVirtualPointerEvent(event) {
474
- if (isJSDOM) {
475
- return false;
476
- }
477
- return !isAndroid && event.width === 0 && event.height === 0 || isAndroid && event.width === 1 && event.height === 1 && event.pressure === 0 && event.detail === 0 && event.pointerType === 'mouse' ||
478
- // iOS VoiceOver returns 0.333• for width/height.
479
- event.width < 1 && event.height < 1 && event.pressure === 0 && event.detail === 0 && event.pointerType === 'touch';
480
- }
481
- function isMouseLikePointerType(pointerType, strict) {
482
- // On some Linux machines with Chromium, mouse inputs return a `pointerType`
483
- // of "pen": https://github.com/floating-ui/floating-ui/issues/2015
484
- const values = ['mouse', 'pen'];
485
- if (!strict) {
486
- values.push('', undefined);
487
- }
488
- return values.includes(pointerType);
489
- }
490
- function isClickLikeEvent(event) {
491
- const type = event.type;
492
- return type === 'click' || type === 'mousedown' || type === 'keydown' || type === 'keyup';
493
- }
494
-
495
- function ownerDocument(node) {
496
- return node?.ownerDocument || document;
497
- }
498
-
499
- const none = 'none';
500
- const triggerPress = 'trigger-press';
501
- const triggerHover = 'trigger-hover';
502
- const triggerFocus = 'trigger-focus';
503
- const outsidePress = 'outside-press';
504
- const itemPress = 'item-press';
505
- const closePress = 'close-press';
506
- const clearPress = 'clear-press';
507
- const chipRemovePress = 'chip-remove-press';
508
- const incrementPress = 'increment-press';
509
- const decrementPress = 'decrement-press';
510
- const inputChange = 'input-change';
511
- const inputClear = 'input-clear';
512
- const inputBlur = 'input-blur';
513
- const inputPaste = 'input-paste';
514
- const inputPress = 'input-press';
515
- const focusOut = 'focus-out';
516
- const escapeKey = 'escape-key';
517
- const closeWatcher = 'close-watcher';
518
- const listNavigation = 'list-navigation';
519
- const keyboard = 'keyboard';
520
- const pointer = 'pointer';
521
- const scrub = 'scrub';
522
- const cancelOpen = 'cancel-open';
523
- const siblingOpen = 'sibling-open';
524
- const imperativeAction = 'imperative-action';
525
- const swipe = 'swipe';
526
-
527
- /**
528
- * Maps a change `reason` string to the corresponding native event type.
529
- */
530
-
531
- /**
532
- * Details of custom change events emitted by Base UI components.
533
- */
534
-
535
- /**
536
- * Details of custom generic events emitted by Base UI components.
537
- */
538
-
539
- /**
540
- * Creates a Base UI event details object with the given reason and utilities
541
- * for preventing Base UI's internal event handling.
542
- */
543
- function createChangeEventDetails(reason, event, trigger, customProperties) {
544
- let canceled = false;
545
- let allowPropagation = false;
546
- const custom = customProperties ?? EMPTY_OBJECT;
547
- const details = {
548
- reason,
549
- event: event ?? new Event('base-ui'),
550
- cancel() {
551
- canceled = true;
552
- },
553
- allowPropagation() {
554
- allowPropagation = true;
555
- },
556
- get isCanceled() {
557
- return canceled;
558
- },
559
- get isPropagationAllowed() {
560
- return allowPropagation;
561
- },
562
- trigger,
563
- ...custom
564
- };
565
- return details;
566
- }
567
- function createGenericEventDetails(reason, event, customProperties) {
568
- const custom = customProperties ?? EMPTY_OBJECT;
569
- const details = {
570
- reason,
571
- event: event ?? new Event('base-ui'),
572
- ...custom
573
- };
574
- return details;
575
- }
576
-
577
- // https://github.com/mui/material-ui/issues/41190#issuecomment-2040873379
578
- const SafeReact = {
579
- ...React
580
- };
581
-
582
- let globalId = 0;
583
-
584
- // TODO React 17: Remove `useGlobalId` once React 17 support is removed
585
- function useGlobalId(idOverride, prefix = 'mui') {
586
- const [defaultId, setDefaultId] = React.useState(idOverride);
587
- const id = idOverride || defaultId;
588
- React.useEffect(() => {
589
- if (defaultId == null) {
590
- // Fallback to this default id when possible.
591
- // Use the incrementing value for client-side rendering only.
592
- // We can't use it server-side.
593
- // If you want to use random values please consider the Birthday Problem: https://en.wikipedia.org/wiki/Birthday_problem
594
- globalId += 1;
595
- setDefaultId(`${prefix}-${globalId}`);
596
- }
597
- }, [defaultId, prefix]);
598
- return id;
599
- }
600
- const maybeReactUseId = SafeReact.useId;
601
-
602
- /**
603
- *
604
- * @example <div id={useId()} />
605
- * @param idOverride
606
- * @returns {string}
607
- */
608
- function useId(idOverride, prefix) {
609
- // React.useId() is only available from React 17.0.0.
610
- if (maybeReactUseId !== undefined) {
611
- const reactId = maybeReactUseId();
612
- return idOverride ?? (prefix ? `${prefix}-${reactId}` : reactId);
613
- }
614
-
615
- // TODO: uncomment once we enable eslint-plugin-react-compiler // eslint-disable-next-line react-compiler/react-compiler
616
- // eslint-disable-next-line react-hooks/rules-of-hooks -- `React.useId` is invariant at runtime.
617
- return useGlobalId(idOverride, prefix);
618
- }
619
-
620
- /**
621
- * If the provided argument is a ref object, returns its `current` value.
622
- * Otherwise, returns the argument itself.
623
- */
624
- function resolveRef(maybeRef) {
625
- if (maybeRef == null) {
626
- return maybeRef;
627
- }
628
- return 'current' in maybeRef ? maybeRef.current : maybeRef;
629
- }
630
-
631
- /**
632
- * Provides a status string for CSS animations.
633
- * @param open - a boolean that determines if the element is open.
634
- * @param enableIdleState - a boolean that enables the `'idle'` state between `'starting'` and `'ending'`
635
- */
636
- function useTransitionStatus(open, enableIdleState = false, deferEndingState = false) {
637
- const [transitionStatus, setTransitionStatus] = React.useState(open && enableIdleState ? 'idle' : undefined);
638
- const [mounted, setMounted] = React.useState(open);
639
- if (open && !mounted) {
640
- setMounted(true);
641
- setTransitionStatus('starting');
642
- }
643
- if (!open && mounted && transitionStatus !== 'ending' && !deferEndingState) {
644
- setTransitionStatus('ending');
645
- }
646
- if (!open && !mounted && transitionStatus === 'ending') {
647
- setTransitionStatus(undefined);
648
- }
649
- useIsoLayoutEffect(() => {
650
- if (!open && mounted && transitionStatus !== 'ending' && deferEndingState) {
651
- const frame = AnimationFrame.request(() => {
652
- setTransitionStatus('ending');
653
- });
654
- return () => {
655
- AnimationFrame.cancel(frame);
656
- };
657
- }
658
- return undefined;
659
- }, [open, mounted, transitionStatus, deferEndingState]);
660
- useIsoLayoutEffect(() => {
661
- if (!open || enableIdleState) {
662
- return undefined;
663
- }
664
- const frame = AnimationFrame.request(() => {
665
- // Avoid `flushSync` here due to Firefox.
666
- // See https://github.com/mui/base-ui/pull/3424
667
- setTransitionStatus(undefined);
668
- });
669
- return () => {
670
- AnimationFrame.cancel(frame);
671
- };
672
- }, [enableIdleState, open]);
673
- useIsoLayoutEffect(() => {
674
- if (!open || !enableIdleState) {
675
- return undefined;
676
- }
677
- if (open && mounted && transitionStatus !== 'idle') {
678
- setTransitionStatus('starting');
679
- }
680
- const frame = AnimationFrame.request(() => {
681
- setTransitionStatus('idle');
682
- });
683
- return () => {
684
- AnimationFrame.cancel(frame);
685
- };
686
- }, [enableIdleState, open, mounted, setTransitionStatus, transitionStatus]);
687
- return React.useMemo(() => ({
688
- mounted,
689
- setMounted,
690
- transitionStatus
691
- }), [mounted, transitionStatus]);
692
- }
693
-
694
- let TransitionStatusDataAttributes = /*#__PURE__*/function (TransitionStatusDataAttributes) {
695
- /**
696
- * Present when the component is animating in.
697
- */
698
- TransitionStatusDataAttributes["startingStyle"] = "data-starting-style";
699
- /**
700
- * Present when the component is animating out.
701
- */
702
- TransitionStatusDataAttributes["endingStyle"] = "data-ending-style";
703
- return TransitionStatusDataAttributes;
704
- }({});
705
- const STARTING_HOOK = {
706
- [TransitionStatusDataAttributes.startingStyle]: ''
707
- };
708
- const ENDING_HOOK = {
709
- [TransitionStatusDataAttributes.endingStyle]: ''
710
- };
711
- const transitionStatusMapping = {
712
- transitionStatus(value) {
713
- if (value === 'starting') {
714
- return STARTING_HOOK;
715
- }
716
- if (value === 'ending') {
717
- return ENDING_HOOK;
718
- }
719
- return null;
720
- }
721
- };
722
-
723
- /**
724
- * Executes a function once all animations have finished on the provided element.
725
- * @param elementOrRef - The element to watch for animations.
726
- * @param waitForStartingStyleRemoved - Whether to wait for [data-starting-style] to be removed before checking for animations.
727
- * @param treatAbortedAsFinished - Whether to treat aborted animations as finished. If `false`, and there are aborted animations,
728
- * the function will check again if any new animations have started and wait for them to finish.
729
- * @returns A function that takes a callback to execute once all animations have finished, and an optional AbortSignal to abort the callback
730
- */
731
- function useAnimationsFinished(elementOrRef, waitForStartingStyleRemoved = false, treatAbortedAsFinished = true) {
732
- const frame = useAnimationFrame();
733
- return useStableCallback((fnToExecute,
734
- /**
735
- * An optional [AbortSignal](https://developer.mozilla.org/en-US/docs/Web/API/AbortSignal) that
736
- * can be used to abort `fnToExecute` before all the animations have finished.
737
- * @default null
738
- */
739
- signal = null) => {
740
- frame.cancel();
741
- function done() {
742
- // Synchronously flush the unmounting of the component so that the browser doesn't
743
- // paint: https://github.com/mui/base-ui/issues/979
744
- ReactDOM.flushSync(fnToExecute);
745
- }
746
- const element = resolveRef(elementOrRef);
747
- if (element == null) {
748
- return;
749
- }
750
- const resolvedElement = element;
751
- if (typeof resolvedElement.getAnimations !== 'function' || globalThis.BASE_UI_ANIMATIONS_DISABLED) {
752
- fnToExecute();
753
- } else {
754
- function execWaitForStartingStyleRemoved() {
755
- const startingStyleAttribute = TransitionStatusDataAttributes.startingStyle;
756
-
757
- // If `[data-starting-style]` isn't present, fall back to waiting one more frame
758
- // to give "open" animations a chance to be registered.
759
- if (!resolvedElement.hasAttribute(startingStyleAttribute)) {
760
- frame.request(exec);
761
- return;
762
- }
763
-
764
- // Wait for `[data-starting-style]` to have been removed.
765
- const attributeObserver = new MutationObserver(() => {
766
- if (!resolvedElement.hasAttribute(startingStyleAttribute)) {
767
- attributeObserver.disconnect();
768
- exec();
769
- }
770
- });
771
- attributeObserver.observe(resolvedElement, {
772
- attributes: true,
773
- attributeFilter: [startingStyleAttribute]
774
- });
775
- signal?.addEventListener('abort', () => attributeObserver.disconnect(), {
776
- once: true
777
- });
778
- }
779
- function exec() {
780
- Promise.all(resolvedElement.getAnimations().map(anim => anim.finished)).then(() => {
781
- if (signal?.aborted) {
782
- return;
783
- }
784
- done();
785
- }).catch(() => {
786
- const currentAnimations = resolvedElement.getAnimations();
787
- if (treatAbortedAsFinished) {
788
- if (signal?.aborted) {
789
- return;
790
- }
791
- done();
792
- } else if (currentAnimations.length > 0 && currentAnimations.some(anim => anim.pending || anim.playState !== 'finished')) {
793
- // Sometimes animations can be aborted because a property they depend on changes while the animation plays.
794
- // In such cases, we need to re-check if any new animations have started.
795
- exec();
796
- }
797
- });
798
- }
799
- if (waitForStartingStyleRemoved) {
800
- execWaitForStartingStyleRemoved();
801
- return;
802
- }
803
- frame.request(exec);
804
- }
805
- });
806
- }
807
-
808
- /**
809
- * Calls the provided function when the CSS open/close animation or transition completes.
810
- */
811
- function useOpenChangeComplete(parameters) {
812
- const {
813
- enabled = true,
814
- open,
815
- ref,
816
- onComplete: onCompleteParam
817
- } = parameters;
818
- const onComplete = useStableCallback(onCompleteParam);
819
- const runOnceAnimationsFinish = useAnimationsFinished(ref, open, false);
820
- React.useEffect(() => {
821
- if (!enabled) {
822
- return undefined;
823
- }
824
- const abortController = new AbortController();
825
- runOnceAnimationsFinish(onComplete, abortController.signal);
826
- return () => {
827
- abortController.abort();
828
- };
829
- }, [enabled, open, onComplete, runOnceAnimationsFinish]);
830
- }
831
-
832
- /**
833
- * Wraps `useId` and prefixes generated `id`s with `base-ui-`
834
- * @param {string | undefined} idOverride overrides the generated id when provided
835
- * @returns {string | undefined}
836
- */
837
- function useBaseUiId(idOverride) {
838
- return useId(idOverride, 'base-ui');
839
- }
840
-
841
- function useValueChanged(value, onChange) {
842
- const valueRef = React.useRef(value);
843
- const onChangeCallback = useStableCallback(onChange);
844
- useIsoLayoutEffect(() => {
845
- if (valueRef.current === value) {
846
- return;
847
- }
848
- onChangeCallback(valueRef.current);
849
- }, [value, onChangeCallback]);
850
- useIsoLayoutEffect(() => {
851
- valueRef.current = value;
852
- }, [value]);
853
- }
854
-
855
- let set;
856
- if (process.env.NODE_ENV !== 'production') {
857
- set = new Set();
858
- }
859
- function error(...messages) {
860
- if (process.env.NODE_ENV !== 'production') {
861
- const messageKey = messages.join(' ');
862
- if (!set.has(messageKey)) {
863
- set.add(messageKey);
864
- console.error(`Base UI: ${messageKey}`);
865
- }
866
- }
867
- }
868
-
869
- const CompositeRootContext = /*#__PURE__*/React.createContext(undefined);
870
- if (process.env.NODE_ENV !== "production") CompositeRootContext.displayName = "CompositeRootContext";
871
- function useCompositeRootContext(optional = false) {
872
- const context = React.useContext(CompositeRootContext);
873
- if (context === undefined && !optional) {
874
- throw new Error(process.env.NODE_ENV !== "production" ? 'Base UI: CompositeRootContext is missing. Composite parts must be placed within <Composite.Root>.' : formatErrorMessage(16));
875
- }
876
- return context;
877
- }
878
-
879
- function useFocusableWhenDisabled(parameters) {
880
- const {
881
- focusableWhenDisabled,
882
- disabled,
883
- composite = false,
884
- tabIndex: tabIndexProp = 0,
885
- isNativeButton
886
- } = parameters;
887
- const isFocusableComposite = composite && focusableWhenDisabled !== false;
888
- const isNonFocusableComposite = composite && focusableWhenDisabled === false;
889
-
890
- // we can't explicitly assign `undefined` to any of these props because it
891
- // would otherwise prevent subsequently merged props from setting them
892
- const props = React.useMemo(() => {
893
- const additionalProps = {
894
- // allow Tabbing away from focusableWhenDisabled elements
895
- onKeyDown(event) {
896
- if (disabled && focusableWhenDisabled && event.key !== 'Tab') {
897
- event.preventDefault();
898
- }
899
- }
900
- };
901
- if (!composite) {
902
- additionalProps.tabIndex = tabIndexProp;
903
- if (!isNativeButton && disabled) {
904
- additionalProps.tabIndex = focusableWhenDisabled ? tabIndexProp : -1;
905
- }
906
- }
907
- if (isNativeButton && (focusableWhenDisabled || isFocusableComposite) || !isNativeButton && disabled) {
908
- additionalProps['aria-disabled'] = disabled;
909
- }
910
- if (isNativeButton && (!focusableWhenDisabled || isNonFocusableComposite)) {
911
- additionalProps.disabled = disabled;
912
- }
913
- return additionalProps;
914
- }, [composite, disabled, focusableWhenDisabled, isFocusableComposite, isNonFocusableComposite, isNativeButton, tabIndexProp]);
915
- return {
916
- props
917
- };
918
- }
919
-
920
- function useButton(parameters = {}) {
921
- const {
922
- disabled = false,
923
- focusableWhenDisabled,
924
- tabIndex = 0,
925
- native: isNativeButton = true,
926
- composite: compositeProp
927
- } = parameters;
928
- const elementRef = React.useRef(null);
929
- const compositeRootContext = useCompositeRootContext(true);
930
- const isCompositeItem = compositeProp ?? compositeRootContext !== undefined;
931
- const {
932
- props: focusableWhenDisabledProps
933
- } = useFocusableWhenDisabled({
934
- focusableWhenDisabled,
935
- disabled,
936
- composite: isCompositeItem,
937
- tabIndex,
938
- isNativeButton
939
- });
940
- if (process.env.NODE_ENV !== 'production') {
941
- // eslint-disable-next-line react-hooks/rules-of-hooks
942
- React.useEffect(() => {
943
- if (!elementRef.current) {
944
- return;
945
- }
946
- const isButtonTag = isButtonElement(elementRef.current);
947
- if (isNativeButton) {
948
- if (!isButtonTag) {
949
- const ownerStackMessage = SafeReact.captureOwnerStack?.() || '';
950
- const message = 'A component that acts as a button expected a native <button> because the ' + '`nativeButton` prop is true. Rendering a non-<button> removes native button ' + 'semantics, which can impact forms and accessibility. Use a real <button> in the ' + '`render` prop, or set `nativeButton` to `false`.';
951
- error(`${message}${ownerStackMessage}`);
952
- }
953
- } else if (isButtonTag) {
954
- const ownerStackMessage = SafeReact.captureOwnerStack?.() || '';
955
- const message = 'A component that acts as a button expected a non-<button> because the `nativeButton` ' + 'prop is false. Rendering a <button> keeps native behavior while Base UI applies ' + 'non-native attributes and handlers, which can add unintended extra attributes (such ' + 'as `role` or `aria-disabled`). Use a non-<button> in the `render` prop, or set ' + '`nativeButton` to `true`.';
956
- error(`${message}${ownerStackMessage}`);
957
- }
958
- }, [isNativeButton]);
959
- }
960
-
961
- // handles a disabled composite button rendering another button, e.g.
962
- // <Toolbar.Button disabled render={<Menu.Trigger />} />
963
- // the `disabled` prop needs to pass through 2 `useButton`s then finally
964
- // delete the `disabled` attribute from DOM
965
- const updateDisabled = React.useCallback(() => {
966
- const element = elementRef.current;
967
- if (!isButtonElement(element)) {
968
- return;
969
- }
970
- if (isCompositeItem && disabled && focusableWhenDisabledProps.disabled === undefined && element.disabled) {
971
- element.disabled = false;
972
- }
973
- }, [disabled, focusableWhenDisabledProps.disabled, isCompositeItem]);
974
- useIsoLayoutEffect(updateDisabled, [updateDisabled]);
975
- const getButtonProps = React.useCallback((externalProps = {}) => {
976
- const {
977
- onClick: externalOnClick,
978
- onMouseDown: externalOnMouseDown,
979
- onKeyUp: externalOnKeyUp,
980
- onKeyDown: externalOnKeyDown,
981
- onPointerDown: externalOnPointerDown,
982
- ...otherExternalProps
983
- } = externalProps;
984
- const type = isNativeButton ? 'button' : undefined;
985
- return mergeProps({
986
- type,
987
- onClick(event) {
988
- if (disabled) {
989
- event.preventDefault();
990
- return;
991
- }
992
- externalOnClick?.(event);
993
- },
994
- onMouseDown(event) {
995
- if (!disabled) {
996
- externalOnMouseDown?.(event);
997
- }
998
- },
999
- onKeyDown(event) {
1000
- if (disabled) {
1001
- return;
1002
- }
1003
- makeEventPreventable(event);
1004
- externalOnKeyDown?.(event);
1005
- if (event.baseUIHandlerPrevented) {
1006
- return;
1007
- }
1008
- const isCurrentTarget = event.target === event.currentTarget;
1009
- const currentTarget = event.currentTarget;
1010
- const isButton = isButtonElement(currentTarget);
1011
- const isLink = !isNativeButton && isValidLinkElement(currentTarget);
1012
- const shouldClick = isCurrentTarget && (isNativeButton ? isButton : !isLink);
1013
- const isEnterKey = event.key === 'Enter';
1014
- const isSpaceKey = event.key === ' ';
1015
- const role = currentTarget.getAttribute('role');
1016
- const isTextNavigationRole = role?.startsWith('menuitem') || role === 'option' || role === 'gridcell';
1017
- if (isCurrentTarget && isCompositeItem && isSpaceKey) {
1018
- if (event.defaultPrevented && isTextNavigationRole) {
1019
- return;
1020
- }
1021
- event.preventDefault();
1022
- if (isLink || isNativeButton && isButton) {
1023
- currentTarget.click();
1024
- event.preventBaseUIHandler();
1025
- } else if (shouldClick) {
1026
- externalOnClick?.(event);
1027
- event.preventBaseUIHandler();
1028
- }
1029
- return;
1030
- }
1031
-
1032
- // Keyboard accessibility for native and non-native elements.
1033
- if (shouldClick) {
1034
- if (!isNativeButton && (isSpaceKey || isEnterKey)) {
1035
- event.preventDefault();
1036
- }
1037
- if (!isNativeButton && isEnterKey) {
1038
- externalOnClick?.(event);
1039
- }
1040
- }
1041
- },
1042
- onKeyUp(event) {
1043
- if (disabled) {
1044
- return;
1045
- }
1046
-
1047
- // calling preventDefault in keyUp on a <button> will not dispatch a click event if Space is pressed
1048
- // https://codesandbox.io/p/sandbox/button-keyup-preventdefault-dn7f0
1049
- makeEventPreventable(event);
1050
- externalOnKeyUp?.(event);
1051
- if (event.target === event.currentTarget && isNativeButton && isCompositeItem && isButtonElement(event.currentTarget) && event.key === ' ') {
1052
- event.preventDefault();
1053
- return;
1054
- }
1055
- if (event.baseUIHandlerPrevented) {
1056
- return;
1057
- }
1058
-
1059
- // Keyboard accessibility for non interactive elements
1060
- if (event.target === event.currentTarget && !isNativeButton && !isCompositeItem && event.key === ' ') {
1061
- externalOnClick?.(event);
1062
- }
1063
- },
1064
- onPointerDown(event) {
1065
- if (disabled) {
1066
- event.preventDefault();
1067
- return;
1068
- }
1069
- externalOnPointerDown?.(event);
1070
- }
1071
- }, !isNativeButton ? {
1072
- role: 'button'
1073
- } : undefined, focusableWhenDisabledProps, otherExternalProps);
1074
- }, [disabled, focusableWhenDisabledProps, isCompositeItem, isNativeButton]);
1075
- const buttonRef = useStableCallback(element => {
1076
- elementRef.current = element;
1077
- updateDisabled();
1078
- });
1079
- return {
1080
- getButtonProps,
1081
- buttonRef
1082
- };
1083
- }
1084
- function isButtonElement(elem) {
1085
- return isHTMLElement(elem) && elem.tagName === 'BUTTON';
1086
- }
1087
- function isValidLinkElement(elem) {
1088
- return Boolean(elem?.tagName === 'A' && elem?.href);
1089
- }
1090
-
1091
1
  function clamp(val, min = Number.MIN_SAFE_INTEGER, max = Number.MAX_SAFE_INTEGER) {
1092
2
  return Math.max(min, Math.min(val, max));
1093
3
  }
1094
4
 
1095
- export { isVirtualClick as $, useButton as A, useValueChanged as B, stopEvent as C, keyboard as D, isMouseLikePointerType as E, useId as F, isTypeableElement as G, matchesFocusVisible as H, isTargetInsideEnabledTrigger as I, triggerFocus as J, activeElement as K, contains as L, isMac as M, isSafari as N, triggerPress as O, escapeKey as P, TYPEABLE_SELECTOR as Q, triggerHover as R, SafeReact as S, Timeout as T, getFloatingFocusElement as U, isTypeableCombobox as V, listNavigation as W, ARROW_DOWN as X, ARROW_LEFT as Y, ARROW_RIGHT as Z, focusOut as _, useStableCallback as a, isVirtualPointerEvent as a0, ARROW_UP as a1, closePress as a2, itemPress as a3, outsidePress as a4, useAnimationsFinished as a5, siblingOpen as a6, imperativeAction as a7, useCompositeRootContext as a8, cancelOpen as a9, useAnimationFrame as aa, resolveRef as ab, isWebKit as ac, isClickLikeEvent as ad, isReactEvent as ae, isEventTargetWithin as af, isRootElement as ag, FOCUSABLE_ATTRIBUTE as ah, ACTIVE_KEY as ai, SELECTED_KEY as aj, TransitionStatusDataAttributes as ak, AnimationFrame as al, isAndroid as am, closeWatcher as an, inputPress as ao, pointer as ap, isFirefox as aq, clearPress as ar, swipe as as, chipRemovePress as at, scrub as au, useTimeout as b, useTransitionStatus as c, useIsoLayoutEffect as d, error as e, useOpenChangeComplete as f, getTarget as g, useOnMount as h, clamp as i, useControlled as j, useValueAsRef as k, isIOS as l, createChangeEventDetails as m, none as n, ownerDocument as o, visuallyHidden as p, inputChange as q, inputClear as r, inputBlur as s, transitionStatusMapping as t, useBaseUiId as u, visuallyHiddenInput as v, inputPaste as w, createGenericEventDetails as x, incrementPress as y, decrementPress as z };
5
+ export { clamp as c };