@jobber/components 8.27.0 → 8.27.2

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.
@@ -2,18 +2,18 @@ import * as React from 'react';
2
2
  import { A as useCoreFilter, B as AriaCombobox, D as useComboboxInputValueContext, e as ComboboxTrigger, d as ComboboxInputGroup, p as ComboboxItem, l as ComboboxArrow, i as ComboboxBackdrop, x as ComboboxClear, v as ComboboxCollection, w as ComboboxEmpty, n as ComboboxGroup, o as ComboboxGroupLabel, m as ComboboxIcon, c as ComboboxInput, f as ComboboxList, k as ComboboxPopup, h as ComboboxPortal, j as ComboboxPositioner, u as ComboboxRow, g as ComboboxStatus, z as useFilteredItems, s as ComboboxChip, t as ComboboxChipRemove, r as ComboboxChips, q as ComboboxItemIndicator, a as ComboboxLabel, C as ComboboxRoot, b as ComboboxValue, y as useComboboxFilter } from '../ComboboxChipRemove-es.js';
3
3
  import { a as stringifyAsLabel, l as getDefaultLabelId } from '../resolveAriaLabelledBy-es.js';
4
4
  import { jsx, jsxs } from 'react/jsx-runtime';
5
- import { af as pointer, a as useIsoLayoutEffect, b as useStableCallback, o as ownerDocument, q as contains, g as getTarget, h as useTimeout, u as useBaseUiId, d as createChangeEventDetails, ag as swipe, n as useAnimationFrame, B as addEventListener, p as activeElement, ad as TransitionStatusDataAttributes, z as useControlled, V as itemPress, k as useTransitionStatus, f as useOpenChangeComplete, a2 as useAnimationsFinished, ah as scrub, J as createGenericEventDetails, t as transitionStatusMapping } from '../useButton-es.js';
5
+ import { ag as pointer, a as useIsoLayoutEffect, b as useStableCallback, h as useTimeout, u as useBaseUiId, d as createChangeEventDetails, a6 as swipe, n as useAnimationFrame, o as ownerDocument, B as addEventListener, p as activeElement, q as contains, g as getTarget, z as useControlled, V as itemPress, k as useTransitionStatus, f as useOpenChangeComplete, a0 as useAnimationsFinished, ah as scrub, J as createGenericEventDetails, t as transitionStatusMapping } from '../useButton-es.js';
6
6
  import { S as Separator } from '../Separator-es.js';
7
- import { a as DialogBackdrop, d as DialogDescription, f as DialogHandle, c as DialogPopup, b as DialogViewport, e as createDialogHandle, D as DrawerDescription } from '../DrawerDescription-es.js';
7
+ import { a as DialogBackdrop, c as DialogDescription, e as DialogHandle, b as DialogPopup, d as createDialogHandle, D as DrawerDescription } from '../DrawerDescription-es.js';
8
8
  import { c as DialogClose, b as DialogTitle, a as DrawerClose, D as DrawerTitle } from '../DrawerTitle-es.js';
9
- import { i as DialogPortal, g as DialogRoot, h as DialogTrigger, m as useDrawerProviderContext, n as DrawerBackdropCssVars, o as DrawerPopupCssVars, q as DrawerProviderContext, u as useDialogRootContext, r as useDrawerRootContext, s as DrawerPopupDataAttributes, t as useDrawerSnapPoints, v as getSnapPointSwipeMovement, w as DrawerViewportContext, x as DRAWER_CONTENT_ATTRIBUTE, c as DrawerBackdrop, f as DrawerContent, d as DrawerPopup, b as DrawerPortal, a as DrawerRoot, D as DrawerTrigger, y as useScrollAreaRootContext, z as getOffset, A as ScrollAreaRootCssVars, B as scrollAreaStateAttributesMapping, C as useScrollAreaViewportContext, S as ScrollAreaRoot, e as ScrollAreaViewport } from '../ScrollAreaViewport-es.js';
10
- import { u as useRenderElement, m as mergeProps, f as formatErrorMessage, N as NOOP, E as EMPTY_OBJECT } from '../useRenderElement-es.js';
11
- import { i as isHTMLElement, d as isLastTraversableNode, e as getParentNode, f as getComputedStyle, o as getWindow, b as isElement } from '../floating-ui.utils.dom-es.js';
9
+ import { l as DialogPortal, j as DialogRoot, k as DialogTrigger, m as DialogViewport, o as useDrawerProviderContext, q as DrawerBackdropCssVars, r as DrawerPopupCssVars, s as DrawerProviderContext, u as useDialogRootContext, t as useDrawerRootContext, v as useSwipeDismiss, w as getDisplacement, x as DrawerPopupDataAttributes, y as getElementTransform, z as DrawerVirtualKeyboardContext, A as getElementAtPoint, B as findScrollableTouchTarget, c as DrawerBackdrop, g as DrawerContent, e as DrawerPopup, b as DrawerPortal, a as DrawerRoot, D as DrawerTrigger, d as DrawerViewport, C as useScrollAreaRootContext, E as getOffset, F as ScrollAreaRootCssVars, G as scrollAreaStateAttributesMapping, H as useScrollAreaViewportContext, S as ScrollAreaRoot, f as ScrollAreaViewport } from '../ScrollAreaViewport-es.js';
10
+ import { u as useRenderElement, f as formatErrorMessage, N as NOOP, E as EMPTY_OBJECT } from '../useRenderElement-es.js';
11
+ import { C as CommonPopupDataAttributes, ae as useTriggerRegistration, Q as isInteractiveElement, p as popupStateMapping, r as useDirection, G as inertValue, K as mergeCleanups, am as gecko, J as webkit, w as useStore, af as triggerOpenStateMapping } from '../useScrollLock-es.js';
12
+ import { o as getWindow, f as getComputedStyle, i as isHTMLElement, e as getParentNode } from '../floating-ui.utils.dom-es.js';
12
13
  import { c as clamp } from '../clamp-es.js';
13
- import { C as CommonPopupDataAttributes, aj as useTriggerRegistration, am as BASE_UI_SWIPE_IGNORE_SELECTOR, a0 as isInteractiveElement, p as popupStateMapping, r as useDirection, G as inertValue, X as mergeCleanups, al as gecko, J as webkit, w as useStore, W as triggerOpenStateMapping } from '../useScrollLock-es.js';
14
- import * as ReactDOM from 'react-dom';
15
14
  import { u as useMenuRootContext, o as useMenuPositionerContext, p as useMenuItem, R as REGULAR_ITEM, q as itemMapping, r as MenuStore, h as MenuBackdrop, l as MenuGroup, n as MenuGroupLabel, b as MenuItem, a as MenuLinkItem, j as MenuPopup, g as MenuPortal, i as MenuPositioner, k as MenuRadioGroup, c as MenuRadioItem, d as MenuRadioItemIndicator, f as MenuRoot, m as MenuSubmenuRoot, e as MenuSubmenuTrigger, M as MenuTrigger } from '../MenuSubmenuTrigger-es.js';
16
15
  import { h as useCompositeListItem } from '../useCompositeListItem-es.js';
16
+ import * as ReactDOM from 'react-dom';
17
17
  import { u as usePreviousValue, l as useSelectRootContext, s as selectors, m as useSelectPositionerContext, j as SelectGroup, k as SelectGroupLabel, g as SelectItem, i as SelectItemIndicator, h as SelectItemText, f as SelectList, e as SelectPopup, a as SelectPortal, d as SelectPositioner, S as SelectRoot, b as SelectTrigger, c as SelectValue } from '../SelectGroupLabel-es.js';
18
18
  import { v as round } from '../floating-ui.utils-es.js';
19
19
  import { u as useNumberFieldRootContext, s as stateAttributesMapping$6, d as NumberFieldDecrement, a as NumberFieldGroup, c as NumberFieldIncrement, b as NumberFieldInput, N as NumberFieldRoot } from '../NumberFieldInput-es.js';
@@ -398,1191 +398,181 @@ function createVisualStateStore() {
398
398
  };
399
399
  }
400
400
 
401
- function isScrollable(element, axis,
402
- // When true, a container that overflows only once extra space is added (e.g. drawer
403
- // keyboard scroll slack) still counts, as long as it has layout size on the axis.
404
- allowOverflowIntent = false) {
405
- const style = getComputedStyle(element);
406
- if (axis === 'vertical') {
407
- const overflowY = style.overflowY;
408
- if (overflowY !== 'auto' && overflowY !== 'scroll') {
409
- return false;
410
- }
411
- return allowOverflowIntent ? element.clientHeight > 0 : element.scrollHeight > element.clientHeight;
412
- }
413
- const overflowX = style.overflowX;
414
- if (overflowX !== 'auto' && overflowX !== 'scroll') {
415
- return false;
416
- }
417
- return allowOverflowIntent ? element.clientWidth > 0 : element.scrollWidth > element.clientWidth;
418
- }
419
- function hasScrollableAncestor(target, root, axes) {
420
- // `getParentNode` crosses shadow boundaries (and slots), so a target inside a shadow root
421
- // still walks up to scrollable ancestors in the light DOM.
422
- let node = target;
423
- while (isHTMLElement(node) && node !== root && !isLastTraversableNode(node)) {
424
- for (const axis of axes) {
425
- if (isScrollable(node, axis)) {
426
- return true;
427
- }
428
- }
429
- node = getParentNode(node);
430
- }
431
- return false;
432
- }
433
- function findScrollableTouchTarget(target, root, axis = 'vertical', allowOverflowIntent = false) {
434
- // `getParentNode` crosses shadow boundaries (and slots), so a target inside a shadow root
435
- // still reaches a scrollable ancestor in the light DOM.
436
- let node = isHTMLElement(target) ? target : null;
437
- while (isHTMLElement(node) && node !== root && !isLastTraversableNode(node)) {
438
- if (isScrollable(node, axis, allowOverflowIntent)) {
439
- return node;
440
- }
441
- node = getParentNode(node);
442
- }
443
- return isScrollable(root, axis, allowOverflowIntent) ? root : null;
444
- }
445
-
446
- function getElementAtPoint(doc, x, y) {
447
- return typeof doc?.elementFromPoint === 'function' ? doc.elementFromPoint(x, y) : null;
448
- }
401
+ let DrawerSwipeAreaDataAttributes = function (DrawerSwipeAreaDataAttributes) {
402
+ /**
403
+ * Present when the drawer is open.
404
+ */
405
+ DrawerSwipeAreaDataAttributes[DrawerSwipeAreaDataAttributes["open"] = CommonPopupDataAttributes.open] = "open";
406
+ /**
407
+ * Present when the drawer is closed.
408
+ */
409
+ DrawerSwipeAreaDataAttributes[DrawerSwipeAreaDataAttributes["closed"] = CommonPopupDataAttributes.closed] = "closed";
410
+ /**
411
+ * Present when the swipe area is disabled.
412
+ */
413
+ DrawerSwipeAreaDataAttributes["disabled"] = "data-disabled";
414
+ /**
415
+ * Indicates the swipe direction.
416
+ * @type {'up' | 'down' | 'left' | 'right'}
417
+ */
418
+ DrawerSwipeAreaDataAttributes["swipeDirection"] = "data-swipe-direction";
419
+ /**
420
+ * Present when the drawer is being swiped.
421
+ */
422
+ DrawerSwipeAreaDataAttributes["swiping"] = "data-swiping";
423
+ return DrawerSwipeAreaDataAttributes;
424
+ }({});
449
425
 
450
- const DEFAULT_SWIPE_THRESHOLD = 40;
451
- const REVERSE_CANCEL_THRESHOLD = 10;
452
- const MIN_DRAG_THRESHOLD = 1;
453
- const MIN_VELOCITY_DURATION_MS = 50;
454
- const MIN_RELEASE_VELOCITY_DURATION_MS = 16;
455
- const MAX_RELEASE_VELOCITY_AGE_MS = 80;
456
- const DEFAULT_IGNORE_SELECTOR = 'button,a,input,select,textarea,label,[role="button"]';
457
- function getDisplacement(direction, deltaX, deltaY) {
458
- switch (direction) {
459
- case 'up':
460
- return -deltaY;
461
- case 'down':
462
- return deltaY;
463
- case 'left':
464
- return -deltaX;
465
- case 'right':
466
- return deltaX;
467
- default:
468
- return 0;
469
- }
470
- }
471
- function getElementTransform(element) {
472
- const computedStyle = getWindow(element).getComputedStyle(element);
473
- const transform = computedStyle.transform;
474
- let translateX = 0;
475
- let translateY = 0;
476
- let scale = 1;
477
- if (transform && transform !== 'none') {
478
- const matrix = transform.match(/matrix(?:3d)?\(([^)]+)\)/);
479
- if (matrix) {
480
- const values = matrix[1].split(', ').map(parseFloat);
481
- if (values.length === 6) {
482
- translateX = values[4];
483
- translateY = values[5];
484
- scale = Math.sqrt(values[0] * values[0] + values[1] * values[1]);
485
- } else if (values.length === 16) {
486
- translateX = values[12];
487
- translateY = values[13];
488
- scale = values[0];
489
- }
490
- }
491
- }
492
- return {
493
- x: translateX,
494
- y: translateY,
495
- scale
496
- };
497
- }
498
- function getValidTimeStamp(timeStamp) {
499
- return Number.isFinite(timeStamp) && timeStamp > 0 ? timeStamp : null;
500
- }
501
- function getDragTransform(dragOffset, scale) {
502
- return `translate3d(${dragOffset.x}px,${dragOffset.y}px,0) scale(${scale})`;
503
- }
504
- function hasPrimaryMouseButton(buttons) {
505
- return buttons % 2 === 1;
506
- }
507
- function safelyChangePointerCapture(element, pointerId, method) {
508
- const pointerCaptureMethod = element[method];
509
- if (typeof pointerCaptureMethod !== 'function') {
510
- return;
511
- }
512
- try {
513
- pointerCaptureMethod.call(element, pointerId);
514
- } catch (error) {
515
- if (error && typeof error === 'object' && 'name' in error && error.name === 'NotFoundError') {
516
- return;
517
- }
518
- throw error;
426
+ const DEFAULT_SWIPE_OPEN_RATIO = 0.5;
427
+ const MIN_SWIPE_START_DISTANCE = 1;
428
+ const VELOCITY_THRESHOLD = 0.1;
429
+ const FALLBACK_SWIPE_OPEN_THRESHOLD = 40;
430
+ const SWIPE_AREA_OPEN_HOOK = {
431
+ [DrawerSwipeAreaDataAttributes.open]: ''
432
+ };
433
+ const SWIPE_AREA_CLOSED_HOOK = {
434
+ [DrawerSwipeAreaDataAttributes.closed]: ''
435
+ };
436
+ const SWIPE_AREA_SWIPING_HOOK = {
437
+ [DrawerSwipeAreaDataAttributes.swiping]: ''
438
+ };
439
+ const SWIPE_AREA_DISABLED_HOOK = {
440
+ [DrawerSwipeAreaDataAttributes.disabled]: ''
441
+ };
442
+ const stateAttributesMapping$3 = {
443
+ open(value) {
444
+ return value ? SWIPE_AREA_OPEN_HOOK : SWIPE_AREA_CLOSED_HOOK;
445
+ },
446
+ swiping(value) {
447
+ return value ? SWIPE_AREA_SWIPING_HOOK : null;
448
+ },
449
+ swipeDirection(value) {
450
+ return value ? {
451
+ [DrawerSwipeAreaDataAttributes.swipeDirection]: value
452
+ } : null;
453
+ },
454
+ disabled(value) {
455
+ return value ? SWIPE_AREA_DISABLED_HOOK : null;
519
456
  }
457
+ };
458
+ const oppositeSwipeDirection = {
459
+ up: 'down',
460
+ down: 'up',
461
+ left: 'right',
462
+ right: 'left'
463
+ };
464
+ function resolveTouchAction(direction) {
465
+ return direction === 'left' || direction === 'right' ? 'pan-y' : 'pan-x';
520
466
  }
521
- function useSwipeDismiss(options) {
467
+
468
+ /**
469
+ * An invisible area that listens for swipe gestures to open the drawer.
470
+ * Renders a `<div>` element.
471
+ *
472
+ * Documentation: [Base UI Drawer](https://base-ui.com/react/components/drawer)
473
+ */
474
+ const DrawerSwipeArea = /*#__PURE__*/React.forwardRef(function DrawerSwipeArea(componentProps, forwardedRef) {
522
475
  const {
523
- enabled,
524
- directions,
525
- elementRef,
526
- movementCssVars,
527
- canStart,
528
- ignoreSelectorWhenTouch = true,
529
- ignoreScrollableAncestors = false,
530
- swipeThreshold: swipeThresholdProp,
531
- onDismiss,
532
- onProgress,
533
- onCancel,
534
- onSwipeStart,
535
- onRelease,
536
- onSwipingChange,
537
- trackDrag = true
538
- } = options;
539
- const ignoreSelector = DEFAULT_IGNORE_SELECTOR;
540
- const primaryDirection = directions.length === 1 ? directions[0] : undefined;
541
- const swipeThresholdDefault = Math.max(0, typeof swipeThresholdProp === 'number' ? swipeThresholdProp : DEFAULT_SWIPE_THRESHOLD);
542
- const allowLeft = directions.includes('left');
543
- const allowRight = directions.includes('right');
544
- const allowUp = directions.includes('up');
545
- const allowDown = directions.includes('down');
546
- const hasHorizontal = allowLeft || allowRight;
547
- const hasVertical = allowUp || allowDown;
548
- const scrollAxes = React.useMemo(() => {
549
- const axes = [];
550
- if (hasVertical) {
551
- axes.push('vertical');
552
- }
553
- if (hasHorizontal) {
554
- axes.push('horizontal');
555
- }
556
- return axes;
557
- }, [hasHorizontal, hasVertical]);
558
- const [currentSwipeDirection, setCurrentSwipeDirection] = React.useState(undefined);
559
- const [isSwiping, setIsSwiping] = React.useState(false);
560
- const [dragDismissed, setDragDismissed] = React.useState(false);
561
- const dragStartPosRef = React.useRef({
562
- x: 0,
563
- y: 0
564
- });
565
- const dragOffsetRef = React.useRef({
566
- x: 0,
567
- y: 0
568
- });
569
- const lastMovePosRef = React.useRef(null);
570
- const initialTransformRef = React.useRef({
571
- x: 0,
572
- y: 0,
573
- scale: 1
574
- });
575
- const intendedSwipeDirectionRef = React.useRef(undefined);
576
- const maxSwipeDisplacementRef = React.useRef(0);
577
- const cancelledSwipeRef = React.useRef(false);
578
- const swipeCancelBaselineRef = React.useRef({
579
- x: 0,
580
- y: 0
581
- });
582
- const lockedDirectionRef = React.useRef(null);
583
- const isFirstPointerMoveRef = React.useRef(false);
584
- const pendingSwipeRef = React.useRef(false);
585
- const pendingSwipeStartPosRef = React.useRef(null);
586
- const swipeFromScrollableRef = React.useRef(false);
587
- const sawPrimaryButtonsOnMoveRef = React.useRef(false);
588
- const elementSizeRef = React.useRef({
589
- width: 0,
590
- height: 0
591
- });
592
- const swipeProgressRef = React.useRef(0);
593
- const swipeThresholdRef = React.useRef(swipeThresholdDefault);
594
- const swipeStartTimeRef = React.useRef(null);
595
- const lastDragSampleRef = React.useRef(null);
596
- const lastDragVelocityRef = React.useRef({
476
+ render,
477
+ className,
478
+ style,
479
+ disabled = false,
480
+ swipeDirection: swipeDirectionProp,
481
+ ...elementProps
482
+ } = componentProps;
483
+ const {
484
+ store
485
+ } = useDialogRootContext();
486
+ const {
487
+ swipeDirection,
488
+ frontmostHeight
489
+ } = useDrawerRootContext();
490
+ const providerContext = useDrawerProviderContext();
491
+ const [swipeActive, setSwipeActive] = React.useState(false);
492
+ const releaseDismissTimeout = useTimeout();
493
+ const swipeAreaRef = React.useRef(null);
494
+ const swipeStartEventRef = React.useRef(null);
495
+ const openedBySwipeRef = React.useRef(false);
496
+ const dragDeltaRef = React.useRef({
597
497
  x: 0,
598
498
  y: 0
599
499
  });
600
- const lastProgressDetailsRef = React.useRef(null);
601
- const isSwipingRef = React.useRef(false);
602
- const dragStyleSnapshotRef = React.useRef(null);
603
- const setSwiping = useStableCallback(nextSwiping => {
604
- if (isSwipingRef.current === nextSwiping) {
605
- return;
606
- }
607
- isSwipingRef.current = nextSwiping;
608
- setIsSwiping(nextSwiping);
609
- onSwipingChange?.(nextSwiping);
500
+ const closedOffsetRef = React.useRef(null);
501
+ const appliedSwipeStylesRef = React.useRef(false);
502
+ const popupTransitionRef = React.useRef(null);
503
+ const swipeAreaId = useBaseUiId(componentProps.id);
504
+ const registerTrigger = useTriggerRegistration(swipeAreaId, store);
505
+ const open = store.useState('open');
506
+ const resetDragDelta = useStableCallback(() => {
507
+ dragDeltaRef.current.x = 0;
508
+ dragDeltaRef.current.y = 0;
610
509
  });
611
- function resolveSwipeThreshold(direction) {
612
- if (!direction) {
613
- return;
614
- }
615
- if (typeof swipeThresholdProp !== 'function') {
616
- swipeThresholdRef.current = swipeThresholdDefault;
617
- return;
618
- }
619
- const element = elementRef.current;
620
- if (!element) {
621
- return;
622
- }
623
- const value = swipeThresholdProp({
624
- element,
625
- direction
510
+ const resolvedSwipeDirection = swipeDirectionProp ?? oppositeSwipeDirection[swipeDirection];
511
+ const dismissDirection = oppositeSwipeDirection[resolvedSwipeDirection];
512
+ const enabled = !disabled && (!open || swipeActive);
513
+ function disableDismissForSwipe() {
514
+ releaseDismissTimeout.clear();
515
+ store.context.outsidePressEnabledRef.current = false;
516
+ }
517
+ function enableDismissAfterRelease() {
518
+ // Safari can dispatch outside-press for the same swipe-open gesture
519
+ // after release, so defer re-enabling dismissal to the next macrotask.
520
+ releaseDismissTimeout.start(0, () => {
521
+ store.context.outsidePressEnabledRef.current = true;
626
522
  });
627
- swipeThresholdRef.current = Math.max(0, value);
628
523
  }
629
- const updateSwipeProgress = useStableCallback((progress, details) => {
630
- const nextProgress = Number.isFinite(progress) ? clamp(progress, 0, 1) : 0;
631
- const progressChanged = nextProgress !== swipeProgressRef.current;
632
- let detailsChanged = false;
633
- if (details) {
634
- const lastDetails = lastProgressDetailsRef.current;
635
- detailsChanged = !lastDetails || lastDetails.deltaX !== details.deltaX || lastDetails.deltaY !== details.deltaY || lastDetails.direction !== details.direction;
636
- }
637
- if (!progressChanged && !detailsChanged) {
638
- return;
639
- }
640
- swipeProgressRef.current = nextProgress;
641
- if (details) {
642
- lastProgressDetailsRef.current = details;
643
- } else if (progressChanged) {
644
- lastProgressDetailsRef.current = null;
645
- }
646
- onProgress?.(nextProgress, details);
647
- });
648
- const syncDragStyles = useStableCallback(swiping => {
649
- const element = elementRef.current;
650
- if (!trackDrag || !element) {
651
- if (!swiping) {
652
- dragStyleSnapshotRef.current = null;
653
- }
654
- return;
655
- }
656
- const style = element.style;
657
- const dragStyleSnapshot = dragStyleSnapshotRef.current;
658
- if (swiping) {
659
- if (!dragStyleSnapshot) {
660
- dragStyleSnapshotRef.current = [style.transition, style.transform];
661
- }
662
- style.transition = 'none';
663
- } else if (dragStyleSnapshot) {
664
- [style.transition, style.transform] = dragStyleSnapshot;
665
- dragStyleSnapshotRef.current = null;
666
- }
667
- const dragOffset = dragOffsetRef.current;
668
- const initialTransform = initialTransformRef.current;
669
- const deltaX = dragOffset.x - initialTransform.x;
670
- const deltaY = dragOffset.y - initialTransform.y;
671
- if (swiping) {
672
- style.transform = getDragTransform(dragOffset, initialTransform.scale);
673
- }
674
- style.setProperty(movementCssVars.x, `${deltaX}px`);
675
- style.setProperty(movementCssVars.y, `${deltaY}px`);
676
- });
677
- function recordDragSample(offset, timeStamp) {
678
- if (timeStamp === null) {
679
- return;
524
+ function resolvePopupSize() {
525
+ const popupElement = store.context.popupRef.current;
526
+ if (!popupElement) {
527
+ return null;
680
528
  }
681
- const lastSample = lastDragSampleRef.current;
682
- if (lastSample && timeStamp > lastSample.time) {
683
- const durationMs = Math.max(timeStamp - lastSample.time, MIN_RELEASE_VELOCITY_DURATION_MS);
684
- lastDragVelocityRef.current = {
685
- x: (offset.x - lastSample.x) / durationMs,
686
- y: (offset.y - lastSample.y) / durationMs
687
- };
529
+ const isHorizontal = dismissDirection === 'left' || dismissDirection === 'right';
530
+ const size = isHorizontal ? popupElement.offsetWidth : popupElement.offsetHeight;
531
+ if (size <= 0) {
532
+ return null;
688
533
  }
689
- lastDragSampleRef.current = {
690
- x: offset.x,
691
- y: offset.y,
692
- time: timeStamp
693
- };
534
+ return size;
694
535
  }
695
- const reset = React.useCallback(() => {
696
- setCurrentSwipeDirection(undefined);
697
- setSwiping(false);
698
- setDragDismissed(false);
699
- updateSwipeProgress(0);
700
- swipeThresholdRef.current = swipeThresholdDefault;
701
- dragStartPosRef.current = {
702
- x: 0,
703
- y: 0
704
- };
705
- dragOffsetRef.current = {
706
- x: 0,
707
- y: 0
708
- };
709
- initialTransformRef.current = {
710
- x: 0,
711
- y: 0,
712
- scale: 1
713
- };
714
- intendedSwipeDirectionRef.current = undefined;
715
- maxSwipeDisplacementRef.current = 0;
716
- cancelledSwipeRef.current = false;
717
- swipeCancelBaselineRef.current = {
718
- x: 0,
719
- y: 0
720
- };
721
- lockedDirectionRef.current = null;
722
- isFirstPointerMoveRef.current = false;
723
- lastMovePosRef.current = null;
724
- pendingSwipeRef.current = false;
725
- pendingSwipeStartPosRef.current = null;
726
- swipeFromScrollableRef.current = false;
727
- sawPrimaryButtonsOnMoveRef.current = false;
728
- elementSizeRef.current = {
729
- width: 0,
730
- height: 0
731
- };
732
- swipeStartTimeRef.current = null;
733
- lastDragSampleRef.current = null;
734
- lastDragVelocityRef.current = {
735
- x: 0,
736
- y: 0
737
- };
738
- lastProgressDetailsRef.current = null;
739
- syncDragStyles(false);
740
- }, [setSwiping, swipeThresholdDefault, syncDragStyles, updateSwipeProgress]);
741
- React.useEffect(() => {
742
- if (typeof swipeThresholdProp !== 'function') {
743
- swipeThresholdRef.current = swipeThresholdDefault;
536
+ function resolveClosedOffset() {
537
+ const offset = resolvePopupSize();
538
+ if (offset == null) {
539
+ return null;
744
540
  }
745
- }, [swipeThresholdDefault, swipeThresholdProp]);
746
- function getPrimaryPointerPosition(event) {
747
- if ('touches' in event) {
748
- const touch = event.touches[0];
749
- return touch ? {
750
- x: touch.clientX,
751
- y: touch.clientY
752
- } : null;
541
+ const popupElement = store.context.popupRef.current;
542
+ if (!popupElement) {
543
+ return offset;
753
544
  }
754
- return {
755
- x: event.clientX,
756
- y: event.clientY
757
- };
758
- }
759
- function isTouchLikeEvent(event) {
760
- if ('touches' in event) {
761
- return true;
545
+ const isHorizontal = dismissDirection === 'left' || dismissDirection === 'right';
546
+ const transform = getElementTransform(popupElement);
547
+ const transformOffset = isHorizontal ? transform.x : transform.y;
548
+ if (Number.isFinite(transformOffset) && Math.abs(transformOffset) > 0.5) {
549
+ return Math.min(offset, Math.abs(transformOffset));
762
550
  }
763
- return event.pointerType === 'touch';
764
- }
765
- function getTargetAtPoint(position, nativeEvent) {
766
- const doc = ownerDocument(elementRef.current);
767
- const elementAtPoint = getElementAtPoint(doc, position.x, position.y);
768
- const target = elementAtPoint ?? getTarget(nativeEvent);
769
- return target;
551
+ return offset;
770
552
  }
771
- function findGestureScrollableTouchTarget(target, root) {
772
- if (hasHorizontal && !hasVertical) {
773
- return findScrollableTouchTarget(target, root, 'horizontal');
774
- }
775
- if (hasVertical && !hasHorizontal) {
776
- return findScrollableTouchTarget(target, root, 'vertical');
553
+ function resolveSwipeOpenThreshold() {
554
+ const popupSize = resolvePopupSize();
555
+ if (popupSize == null) {
556
+ return FALLBACK_SWIPE_OPEN_THRESHOLD;
777
557
  }
778
- return findScrollableTouchTarget(target, root, 'vertical') ?? findScrollableTouchTarget(target, root, 'horizontal');
558
+ return popupSize * DEFAULT_SWIPE_OPEN_RATIO;
779
559
  }
780
- function startSwipeAtPosition(event, position, startOptions) {
781
- swipeFromScrollableRef.current = false;
782
- const touchLike = isTouchLikeEvent(event);
783
- const target = getTargetAtPoint(position, event.nativeEvent);
784
- const doc = ownerDocument(elementRef.current);
785
- const body = doc.body;
786
- const scrollableTarget = touchLike && body ? findGestureScrollableTouchTarget(target, body) : null;
787
- const ignoreScrollableTarget = startOptions?.ignoreScrollableTarget ?? false;
788
- if (scrollableTarget && !ignoreScrollableTarget) {
789
- return false;
560
+ function applySwipeMovement() {
561
+ if (!swipeActive) {
562
+ return;
790
563
  }
791
- swipeFromScrollableRef.current = Boolean(scrollableTarget && ignoreScrollableTarget);
792
- const isInteractiveElement = target ? target.closest(ignoreSelector) : false;
793
- if (isInteractiveElement && (!touchLike || ignoreSelectorWhenTouch)) {
794
- return false;
564
+ const popupElement = store.context.popupRef.current;
565
+ if (!popupElement) {
566
+ return;
795
567
  }
796
- const element = elementRef.current;
797
- if (ignoreScrollableAncestors && element && target && scrollAxes.length > 0) {
798
- const ignoreAncestors = startOptions?.ignoreScrollableAncestors ?? false;
799
- if (!ignoreAncestors && hasScrollableAncestor(target, element, scrollAxes)) {
800
- return false;
801
- }
568
+ if (!store.select('open') || !store.select('mounted')) {
569
+ return;
802
570
  }
803
- cancelledSwipeRef.current = false;
804
- intendedSwipeDirectionRef.current = undefined;
805
- maxSwipeDisplacementRef.current = 0;
806
- dragStartPosRef.current = position;
807
- swipeStartTimeRef.current = getValidTimeStamp(event.timeStamp);
808
- swipeCancelBaselineRef.current = position;
809
- lastMovePosRef.current = position;
810
- if (element) {
811
- elementSizeRef.current = {
812
- width: element.offsetWidth,
813
- height: element.offsetHeight
814
- };
815
- resolveSwipeThreshold(primaryDirection);
816
- const transform = getElementTransform(element);
817
- initialTransformRef.current = transform;
818
- dragOffsetRef.current = {
819
- x: transform.x,
820
- y: transform.y
821
- };
822
- recordDragSample({
823
- x: transform.x,
824
- y: transform.y
825
- }, swipeStartTimeRef.current);
826
- if (!('touches' in event)) {
827
- safelyChangePointerCapture(element, event.pointerId, 'setPointerCapture');
828
- }
571
+ if (closedOffsetRef.current == null) {
572
+ closedOffsetRef.current = resolveClosedOffset();
829
573
  }
830
- onSwipeStart?.(event.nativeEvent);
831
- setSwiping(true);
832
- lockedDirectionRef.current = null;
833
- isFirstPointerMoveRef.current = true;
834
- updateSwipeProgress(0);
835
- syncDragStyles(true);
836
- return true;
837
- }
838
- function resetPendingSwipeState() {
839
- clearPendingSwipeStartState();
840
- swipeFromScrollableRef.current = false;
841
- lastMovePosRef.current = null;
842
- }
843
- function clearPendingSwipeStartState() {
844
- pendingSwipeRef.current = false;
845
- pendingSwipeStartPosRef.current = null;
846
- }
847
- function cancelSwipeInteraction(event) {
848
- resetPendingSwipeState();
849
- if (!isSwipingRef.current) {
850
- return;
851
- }
852
- setSwiping(false);
853
- lockedDirectionRef.current = null;
854
- const resolvedInitialTransform = initialTransformRef.current;
855
- dragOffsetRef.current = {
856
- x: resolvedInitialTransform.x,
857
- y: resolvedInitialTransform.y
858
- };
859
- setCurrentSwipeDirection(undefined);
860
- sawPrimaryButtonsOnMoveRef.current = false;
861
- syncDragStyles(false);
862
- const element = elementRef.current;
863
- if (element) {
864
- safelyChangePointerCapture(element, event.pointerId, 'releasePointerCapture');
865
- }
866
- updateSwipeProgress(0, {
867
- deltaX: 0,
868
- deltaY: 0,
869
- direction: undefined
870
- });
871
- onCancel?.(event.nativeEvent);
872
- }
873
- function applyDirectionalDamping(deltaX, deltaY) {
874
- const exponent = value => value >= 0 ? value ** 0.5 : -(Math.abs(value) ** 0.5);
875
- const dampAxis = (delta, allowNegative, allowPositive) => {
876
- if (!allowNegative && delta < 0) {
877
- return exponent(delta);
878
- }
879
- if (!allowPositive && delta > 0) {
880
- return exponent(delta);
881
- }
882
- return delta;
883
- };
884
- const newDeltaX = hasHorizontal ? dampAxis(deltaX, allowLeft, allowRight) : exponent(deltaX);
885
- const newDeltaY = hasVertical ? dampAxis(deltaY, allowUp, allowDown) : exponent(deltaY);
886
- return {
887
- x: newDeltaX,
888
- y: newDeltaY
889
- };
890
- }
891
- function canSwipeFromScrollEdgeOnPendingMove(scrollTarget, deltaX, deltaY) {
892
- const absDeltaX = Math.abs(deltaX);
893
- const absDeltaY = Math.abs(deltaY);
894
- const useVerticalAxis = hasVertical && deltaY !== 0 && (!hasHorizontal || absDeltaY >= absDeltaX);
895
- if (useVerticalAxis) {
896
- const maxScrollTop = Math.max(0, scrollTarget.scrollHeight - scrollTarget.clientHeight);
897
- const atTop = scrollTarget.scrollTop <= 0;
898
- const atBottom = scrollTarget.scrollTop >= maxScrollTop;
899
- const movingDown = deltaY > 0;
900
- const movingUp = deltaY < 0;
901
- const canSwipeDown = movingDown && atTop && allowDown;
902
- const canSwipeUp = movingUp && atBottom && allowUp;
903
- return canSwipeDown || canSwipeUp;
904
- }
905
- const useHorizontalAxis = hasHorizontal && deltaX !== 0 && (!hasVertical || absDeltaX > absDeltaY);
906
- if (useHorizontalAxis) {
907
- const maxScrollLeft = Math.max(0, scrollTarget.scrollWidth - scrollTarget.clientWidth);
908
- const atLeft = scrollTarget.scrollLeft <= 0;
909
- const atRight = scrollTarget.scrollLeft >= maxScrollLeft;
910
- const movingRight = deltaX > 0;
911
- const movingLeft = deltaX < 0;
912
- const canSwipeRight = movingRight && atLeft && allowRight;
913
- const canSwipeLeft = movingLeft && atRight && allowLeft;
914
- return canSwipeRight || canSwipeLeft;
915
- }
916
- return null;
917
- }
918
- const handleStart = useStableCallback(event => {
919
- if (!enabled) {
920
- return;
921
- }
922
- if (event.defaultPrevented || event.nativeEvent.defaultPrevented) {
923
- return;
924
- }
925
- if (!('touches' in event) && event.button !== 0) {
926
- return;
927
- }
928
- const startPos = getPrimaryPointerPosition(event);
929
- if (!startPos) {
930
- return;
931
- }
932
- pendingSwipeRef.current = true;
933
- pendingSwipeStartPosRef.current = startPos;
934
- swipeFromScrollableRef.current = false;
935
- sawPrimaryButtonsOnMoveRef.current = false;
936
- const allowedToStart = canStart ? canStart(startPos, {
937
- nativeEvent: event.nativeEvent,
938
- direction: primaryDirection
939
- }) : true;
940
- if (!allowedToStart) {
941
- return;
942
- }
943
- if (startSwipeAtPosition(event, startPos)) {
944
- clearPendingSwipeStartState();
945
- }
946
- });
947
- function handleMoveCore(event, position, movement) {
948
- if (!enabled || !isSwipingRef.current) {
949
- return;
950
- }
951
- const target = getTarget(event.nativeEvent);
952
- if (isTouchLikeEvent(event) && !swipeFromScrollableRef.current) {
953
- const boundaryElement = event.currentTarget;
954
- if (findGestureScrollableTouchTarget(target, boundaryElement)) {
955
- return;
956
- }
957
- }
958
- if (!('touches' in event)) {
959
- // Prevent text selection on Safari
960
- event.preventDefault();
961
- }
962
- if (isFirstPointerMoveRef.current) {
963
- // Adjust the starting position to the current position on the first move
964
- // to account for the delay between pointerdown and the first pointermove on iOS.
965
- dragStartPosRef.current = position;
966
- const moveTime = getValidTimeStamp(event.timeStamp);
967
- if (moveTime !== null) {
968
- swipeStartTimeRef.current = moveTime;
969
- }
970
- isFirstPointerMoveRef.current = false;
971
- }
972
- const clientX = position.x;
973
- const clientY = position.y;
974
- const movementX = movement.x;
975
- const movementY = movement.y;
976
- if (movementY < 0 && clientY > swipeCancelBaselineRef.current.y || movementY > 0 && clientY < swipeCancelBaselineRef.current.y) {
977
- swipeCancelBaselineRef.current = {
978
- x: swipeCancelBaselineRef.current.x,
979
- y: clientY
980
- };
981
- }
982
- if (movementX < 0 && clientX > swipeCancelBaselineRef.current.x || movementX > 0 && clientX < swipeCancelBaselineRef.current.x) {
983
- swipeCancelBaselineRef.current = {
984
- x: clientX,
985
- y: swipeCancelBaselineRef.current.y
986
- };
987
- }
988
- const deltaX = clientX - dragStartPosRef.current.x;
989
- const deltaY = clientY - dragStartPosRef.current.y;
990
- const cancelDeltaY = clientY - swipeCancelBaselineRef.current.y;
991
- const cancelDeltaX = clientX - swipeCancelBaselineRef.current.x;
992
- let lockedDirection = lockedDirectionRef.current;
993
- if (lockedDirection === null && hasHorizontal && hasVertical) {
994
- const movementDistance = Math.sqrt(deltaX * deltaX + deltaY * deltaY);
995
- if (movementDistance >= MIN_DRAG_THRESHOLD) {
996
- lockedDirection = Math.abs(deltaX) > Math.abs(deltaY) ? 'horizontal' : 'vertical';
997
- lockedDirectionRef.current = lockedDirection;
998
- }
999
- }
1000
- let candidate;
1001
- if (!intendedSwipeDirectionRef.current) {
1002
- if (lockedDirection === 'vertical') {
1003
- if (deltaY > 0) {
1004
- candidate = 'down';
1005
- } else if (deltaY < 0) {
1006
- candidate = 'up';
1007
- }
1008
- } else if (lockedDirection === 'horizontal') {
1009
- if (deltaX > 0) {
1010
- candidate = 'right';
1011
- } else if (deltaX < 0) {
1012
- candidate = 'left';
1013
- }
1014
- } else if (Math.abs(deltaX) >= Math.abs(deltaY)) {
1015
- candidate = deltaX > 0 ? 'right' : 'left';
1016
- } else {
1017
- candidate = deltaY > 0 ? 'down' : 'up';
1018
- }
1019
- if (candidate) {
1020
- const isAllowed = candidate === 'left' && allowLeft || candidate === 'right' && allowRight || candidate === 'up' && allowUp || candidate === 'down' && allowDown;
1021
- if (isAllowed) {
1022
- intendedSwipeDirectionRef.current = candidate;
1023
- maxSwipeDisplacementRef.current = getDisplacement(candidate, deltaX, deltaY);
1024
- setCurrentSwipeDirection(candidate);
1025
- resolveSwipeThreshold(candidate);
1026
- }
1027
- }
1028
- } else {
1029
- const direction = intendedSwipeDirectionRef.current;
1030
- const currentDisplacement = getDisplacement(direction, cancelDeltaX, cancelDeltaY);
1031
- if (currentDisplacement > swipeThresholdRef.current) {
1032
- cancelledSwipeRef.current = false;
1033
- setCurrentSwipeDirection(direction);
1034
- } else if (!(allowLeft && allowRight) && !(allowUp && allowDown) && maxSwipeDisplacementRef.current - currentDisplacement >= REVERSE_CANCEL_THRESHOLD) {
1035
- // Mark that a change-of-mind has occurred
1036
- cancelledSwipeRef.current = true;
1037
- }
1038
- }
1039
- const dampedDelta = applyDirectionalDamping(deltaX, deltaY);
1040
- let newOffsetX = initialTransformRef.current.x;
1041
- let newOffsetY = initialTransformRef.current.y;
1042
- if (lockedDirection === 'horizontal') {
1043
- if (hasHorizontal) {
1044
- newOffsetX += dampedDelta.x;
1045
- }
1046
- } else if (lockedDirection === 'vertical') {
1047
- if (hasVertical) {
1048
- newOffsetY += dampedDelta.y;
1049
- }
1050
- } else {
1051
- if (hasHorizontal) {
1052
- newOffsetX += dampedDelta.x;
1053
- }
1054
- if (hasVertical) {
1055
- newOffsetY += dampedDelta.y;
1056
- }
1057
- }
1058
- dragOffsetRef.current = {
1059
- x: newOffsetX,
1060
- y: newOffsetY
1061
- };
1062
- syncDragStyles(true);
1063
- recordDragSample({
1064
- x: newOffsetX,
1065
- y: newOffsetY
1066
- }, getValidTimeStamp(event.timeStamp));
1067
- const dragDeltaX = newOffsetX - initialTransformRef.current.x;
1068
- const dragDeltaY = newOffsetY - initialTransformRef.current.y;
1069
- const swipeDirectionDetails = intendedSwipeDirectionRef.current;
1070
- const progressDirection = primaryDirection ?? intendedSwipeDirectionRef.current;
1071
- if (!progressDirection) {
1072
- updateSwipeProgress(0, {
1073
- deltaX: dragDeltaX,
1074
- deltaY: dragDeltaY,
1075
- direction: swipeDirectionDetails
1076
- });
1077
- return;
1078
- }
1079
- const size = progressDirection === 'left' || progressDirection === 'right' ? elementSizeRef.current.width : elementSizeRef.current.height;
1080
- const scale = initialTransformRef.current.scale || 1;
1081
- if (size <= 0 || scale <= 0) {
1082
- updateSwipeProgress(0, {
1083
- deltaX: dragDeltaX,
1084
- deltaY: dragDeltaY,
1085
- direction: swipeDirectionDetails
1086
- });
1087
- return;
1088
- }
1089
- const progressDisplacement = getDisplacement(progressDirection, newOffsetX - initialTransformRef.current.x, newOffsetY - initialTransformRef.current.y);
1090
- if (progressDisplacement <= 0) {
1091
- updateSwipeProgress(0, {
1092
- deltaX: dragDeltaX,
1093
- deltaY: dragDeltaY,
1094
- direction: swipeDirectionDetails
1095
- });
1096
- return;
1097
- }
1098
- updateSwipeProgress(progressDisplacement / (size * scale), {
1099
- deltaX: dragDeltaX,
1100
- deltaY: dragDeltaY,
1101
- direction: swipeDirectionDetails
1102
- });
1103
- }
1104
- const handleEnd = useStableCallback(event => {
1105
- if (!enabled) {
1106
- return;
1107
- }
1108
- const resolvedDragOffset = dragOffsetRef.current;
1109
- const resolvedInitialTransform = initialTransformRef.current;
1110
- const releaseDeltaX = resolvedDragOffset.x - resolvedInitialTransform.x;
1111
- const releaseDeltaY = resolvedDragOffset.y - resolvedInitialTransform.y;
1112
- const progressDetails = {
1113
- deltaX: releaseDeltaX,
1114
- deltaY: releaseDeltaY,
1115
- direction: intendedSwipeDirectionRef.current
1116
- };
1117
- if (!isSwipingRef.current) {
1118
- resetPendingSwipeState();
1119
- updateSwipeProgress(0, progressDetails);
1120
- return;
1121
- }
1122
- setSwiping(false);
1123
- lockedDirectionRef.current = null;
1124
- resetPendingSwipeState();
1125
- sawPrimaryButtonsOnMoveRef.current = false;
1126
- const element = elementRef.current;
1127
- if (element) {
1128
- if (!('touches' in event)) {
1129
- safelyChangePointerCapture(element, event.pointerId, 'releasePointerCapture');
1130
- }
1131
- }
1132
- const deltaX = releaseDeltaX;
1133
- const deltaY = releaseDeltaY;
1134
- const startTime = swipeStartTimeRef.current;
1135
- const endTime = getValidTimeStamp(event.timeStamp);
1136
- const durationMs = startTime !== null && endTime !== null && endTime > startTime ? endTime - startTime : 0;
1137
- const velocityDurationMs = durationMs > 0 ? Math.max(durationMs, MIN_VELOCITY_DURATION_MS) : 0;
1138
- const velocityX = velocityDurationMs > 0 ? deltaX / velocityDurationMs : 0;
1139
- const velocityY = velocityDurationMs > 0 ? deltaY / velocityDurationMs : 0;
1140
- let releaseVelocityX = lastDragVelocityRef.current.x;
1141
- let releaseVelocityY = lastDragVelocityRef.current.y;
1142
- const lastSample = lastDragSampleRef.current;
1143
- if (lastSample && endTime !== null && endTime >= lastSample.time) {
1144
- const ageMs = endTime - lastSample.time;
1145
- if (ageMs <= MAX_RELEASE_VELOCITY_AGE_MS) {
1146
- const sampleDurationMs = Math.max(ageMs, MIN_RELEASE_VELOCITY_DURATION_MS);
1147
- const deltaFromLastSampleX = resolvedDragOffset.x - lastSample.x;
1148
- const deltaFromLastSampleY = resolvedDragOffset.y - lastSample.y;
1149
- const sampleVelocityX = deltaFromLastSampleX / sampleDurationMs;
1150
- const sampleVelocityY = deltaFromLastSampleY / sampleDurationMs;
1151
- if (sampleVelocityX !== 0) {
1152
- releaseVelocityX = sampleVelocityX;
1153
- }
1154
- if (sampleVelocityY !== 0) {
1155
- releaseVelocityY = sampleVelocityY;
1156
- }
1157
- } else {
1158
- releaseVelocityX = 0;
1159
- releaseVelocityY = 0;
1160
- }
1161
- }
1162
- const releaseDecision = onRelease?.({
1163
- event: event.nativeEvent,
1164
- direction: intendedSwipeDirectionRef.current,
1165
- deltaX,
1166
- deltaY,
1167
- velocityX,
1168
- velocityY,
1169
- releaseVelocityX,
1170
- releaseVelocityY
1171
- });
1172
- const hasReleaseDecision = typeof releaseDecision === 'boolean';
1173
- if (cancelledSwipeRef.current && !hasReleaseDecision) {
1174
- dragOffsetRef.current = {
1175
- x: resolvedInitialTransform.x,
1176
- y: resolvedInitialTransform.y
1177
- };
1178
- setCurrentSwipeDirection(undefined);
1179
- syncDragStyles(false);
1180
- updateSwipeProgress(0, progressDetails);
1181
- return;
1182
- }
1183
- let shouldClose = false;
1184
- let dismissDirection;
1185
- if (hasReleaseDecision) {
1186
- shouldClose = releaseDecision;
1187
- dismissDirection = intendedSwipeDirectionRef.current ?? primaryDirection;
1188
- } else {
1189
- for (const direction of directions) {
1190
- switch (direction) {
1191
- case 'right':
1192
- if (deltaX > swipeThresholdRef.current) {
1193
- shouldClose = true;
1194
- dismissDirection = 'right';
1195
- }
1196
- break;
1197
- case 'left':
1198
- if (deltaX < -swipeThresholdRef.current) {
1199
- shouldClose = true;
1200
- dismissDirection = 'left';
1201
- }
1202
- break;
1203
- case 'down':
1204
- if (deltaY > swipeThresholdRef.current) {
1205
- shouldClose = true;
1206
- dismissDirection = 'down';
1207
- }
1208
- break;
1209
- case 'up':
1210
- if (deltaY < -swipeThresholdRef.current) {
1211
- shouldClose = true;
1212
- dismissDirection = 'up';
1213
- }
1214
- break;
1215
- }
1216
- if (shouldClose) {
1217
- break;
1218
- }
1219
- }
1220
- }
1221
- if (shouldClose && dismissDirection) {
1222
- setCurrentSwipeDirection(dismissDirection);
1223
- setDragDismissed(true);
1224
- syncDragStyles(false);
1225
- onDismiss?.(event.nativeEvent, {
1226
- direction: dismissDirection
1227
- });
1228
- } else {
1229
- dragOffsetRef.current = {
1230
- x: resolvedInitialTransform.x,
1231
- y: resolvedInitialTransform.y
1232
- };
1233
- setCurrentSwipeDirection(undefined);
1234
- syncDragStyles(false);
1235
- updateSwipeProgress(0, progressDetails);
1236
- }
1237
- });
1238
- const handleMove = useStableCallback(event => {
1239
- const currentPos = getPrimaryPointerPosition(event);
1240
- if (!currentPos) {
1241
- return;
1242
- }
1243
- let endAfterMove = false;
1244
- if (!('touches' in event)) {
1245
- const hasPrimaryButton = hasPrimaryMouseButton(event.buttons);
1246
- if (hasPrimaryButton) {
1247
- sawPrimaryButtonsOnMoveRef.current = true;
1248
- }
1249
-
1250
- // Cancel the swipe if a non-primary button takes over the interaction.
1251
- // This handles cases where a right-click interrupts dragging.
1252
- if (event.buttons !== 0 && !hasPrimaryButton) {
1253
- cancelSwipeInteraction(event);
1254
- return;
1255
- }
1256
-
1257
- // A `buttons: 0` pointermove means the primary button was already released, so the gesture is
1258
- // over even if no pointerup reached us. On fast trackpad flicks this trailing move is
1259
- // dispatched just before pointerup; treat it as the release (mirroring touchend) instead of
1260
- // cancelling and snapping the element back.
1261
- if (event.buttons === 0 && sawPrimaryButtonsOnMoveRef.current) {
1262
- if (!isSwipingRef.current) {
1263
- // The gesture never activated — discard it.
1264
- handleEnd(event);
1265
- return;
1266
- }
1267
- // This release move can itself carry the threshold-crossing displacement (and the peak
1268
- // release velocity), so let it flow through `handleMoveCore` below to update the drag
1269
- // offset / velocity sample, then commit the release afterwards.
1270
- endAfterMove = true;
1271
- }
1272
- }
1273
- if (!isSwiping && pendingSwipeRef.current) {
1274
- if (!isTouchLikeEvent(event) && (event.defaultPrevented || event.nativeEvent.defaultPrevented)) {
1275
- resetPendingSwipeState();
1276
- return;
1277
- }
1278
- const allowedToStart = canStart ? canStart(currentPos, {
1279
- nativeEvent: event.nativeEvent,
1280
- direction: primaryDirection
1281
- }) : true;
1282
- if (allowedToStart) {
1283
- const pendingStartPos = pendingSwipeStartPosRef.current;
1284
- let ignoreScrollableOnStart = false;
1285
- if (isTouchLikeEvent(event)) {
1286
- const element = elementRef.current;
1287
- if (pendingStartPos && element) {
1288
- const target = getTargetAtPoint(currentPos, event.nativeEvent);
1289
- const doc = ownerDocument(element);
1290
- const body = doc.body;
1291
- const scrollTarget = body ? findGestureScrollableTouchTarget(target, body) : null;
1292
- if (scrollTarget && (contains(element, scrollTarget) || contains(scrollTarget, element))) {
1293
- const deltaX = currentPos.x - pendingStartPos.x;
1294
- const deltaY = currentPos.y - pendingStartPos.y;
1295
- const canSwipeFromEdge = canSwipeFromScrollEdgeOnPendingMove(scrollTarget, deltaX, deltaY);
1296
- if (canSwipeFromEdge === false) {
1297
- return;
1298
- }
1299
- if (canSwipeFromEdge === true) {
1300
- ignoreScrollableOnStart = true;
1301
- }
1302
- }
1303
- }
1304
- }
1305
- const started = startSwipeAtPosition(event, currentPos, {
1306
- ignoreScrollableTarget: ignoreScrollableOnStart,
1307
- ignoreScrollableAncestors: ignoreScrollableOnStart
1308
- });
1309
- if (started) {
1310
- if (pendingStartPos && ignoreScrollableOnStart) {
1311
- // Preserve displacement between touchstart and the move that activates swipe from
1312
- // a scroll-edge so quick flicks can dismiss.
1313
- clearPendingSwipeStartState();
1314
- dragStartPosRef.current = pendingStartPos;
1315
- swipeCancelBaselineRef.current = pendingStartPos;
1316
- lastMovePosRef.current = pendingStartPos;
1317
- isFirstPointerMoveRef.current = false;
1318
- } else {
1319
- // Start from the current in-bounds position without dropping follow-up move
1320
- // displacement; this avoids jumps when entering from outside the element while
1321
- // keeping swipe tracking responsive on the next move.
1322
- clearPendingSwipeStartState();
1323
- swipeFromScrollableRef.current = false;
1324
- }
1325
- }
1326
- }
1327
- }
1328
- const previousPos = lastMovePosRef.current;
1329
- const movement = previousPos === null ? {
1330
- x: 0,
1331
- y: 0
1332
- } : {
1333
- x: currentPos.x - previousPos.x,
1334
- y: currentPos.y - previousPos.y
1335
- };
1336
- lastMovePosRef.current = currentPos;
1337
- handleMoveCore(event, currentPos, movement);
1338
-
1339
- // `endAfterMove` is only set in the non-touch branch above; the `'touches'` guard re-narrows the
1340
- // event type for `handleEnd` after the shared move handling has run.
1341
- if (endAfterMove && !('touches' in event)) {
1342
- handleEnd(event);
1343
- }
1344
- });
1345
-
1346
- // Feeds a native touchmove into the swipe pipeline. Used by consumers that claim the gesture
1347
- // in a capture-phase listener and stop it from reaching React's delegated touch handlers.
1348
- const moveNative = useStableCallback((nativeEvent, currentTarget) => {
1349
- handleMove({
1350
- touches: nativeEvent.touches,
1351
- currentTarget,
1352
- nativeEvent,
1353
- defaultPrevented: nativeEvent.defaultPrevented,
1354
- timeStamp: nativeEvent.timeStamp
1355
- });
1356
- });
1357
- const getDragStyles = React.useCallback(() => {
1358
- const dragOffset = dragOffsetRef.current;
1359
- const initialTransform = initialTransformRef.current;
1360
- const deltaX = dragOffset.x - initialTransform.x;
1361
- const deltaY = dragOffset.y - initialTransform.y;
1362
- if (!isSwiping && deltaX === 0 && deltaY === 0 && !dragDismissed) {
1363
- return {
1364
- [movementCssVars.x]: '0px',
1365
- [movementCssVars.y]: '0px'
1366
- };
1367
- }
1368
- return {
1369
- transition: isSwiping ? 'none' : undefined,
1370
- // While swiping, freeze the element at its current visual transform so it doesn't snap to the
1371
- // end position.
1372
- transform: isSwiping ? getDragTransform(dragOffset, initialTransform.scale) : undefined,
1373
- [movementCssVars.x]: `${deltaX}px`,
1374
- [movementCssVars.y]: `${deltaY}px`
1375
- };
1376
- }, [dragDismissed, isSwiping, movementCssVars]);
1377
- const getPointerProps = React.useCallback(() => {
1378
- if (!enabled) {
1379
- return {};
1380
- }
1381
- return {
1382
- onPointerDown: handleStart,
1383
- onPointerMove: handleMove,
1384
- onPointerUp: handleEnd,
1385
- onPointerCancel: handleEnd
1386
- };
1387
- }, [enabled, handleEnd, handleMove, handleStart]);
1388
- const getTouchProps = React.useCallback(() => {
1389
- if (!enabled) {
1390
- return {};
1391
- }
1392
- return {
1393
- onTouchStart: handleStart,
1394
- onTouchMove: handleMove,
1395
- onTouchEnd: handleEnd,
1396
- onTouchCancel: handleEnd
1397
- };
1398
- }, [enabled, handleEnd, handleMove, handleStart]);
1399
- return {
1400
- swiping: isSwiping,
1401
- swipeDirection: currentSwipeDirection,
1402
- dragDismissed,
1403
- getPointerProps,
1404
- getTouchProps,
1405
- moveNative,
1406
- getDragStyles,
1407
- reset
1408
- };
1409
- }
1410
-
1411
- let DrawerSwipeAreaDataAttributes = function (DrawerSwipeAreaDataAttributes) {
1412
- /**
1413
- * Present when the drawer is open.
1414
- */
1415
- DrawerSwipeAreaDataAttributes[DrawerSwipeAreaDataAttributes["open"] = CommonPopupDataAttributes.open] = "open";
1416
- /**
1417
- * Present when the drawer is closed.
1418
- */
1419
- DrawerSwipeAreaDataAttributes[DrawerSwipeAreaDataAttributes["closed"] = CommonPopupDataAttributes.closed] = "closed";
1420
- /**
1421
- * Present when the swipe area is disabled.
1422
- */
1423
- DrawerSwipeAreaDataAttributes["disabled"] = "data-disabled";
1424
- /**
1425
- * Indicates the swipe direction.
1426
- * @type {'up' | 'down' | 'left' | 'right'}
1427
- */
1428
- DrawerSwipeAreaDataAttributes["swipeDirection"] = "data-swipe-direction";
1429
- /**
1430
- * Present when the drawer is being swiped.
1431
- */
1432
- DrawerSwipeAreaDataAttributes["swiping"] = "data-swiping";
1433
- return DrawerSwipeAreaDataAttributes;
1434
- }({});
1435
-
1436
- const DEFAULT_SWIPE_OPEN_RATIO = 0.5;
1437
- const MIN_SWIPE_START_DISTANCE = 1;
1438
- const VELOCITY_THRESHOLD = 0.1;
1439
- const FALLBACK_SWIPE_OPEN_THRESHOLD = 40;
1440
- const SWIPE_AREA_OPEN_HOOK = {
1441
- [DrawerSwipeAreaDataAttributes.open]: ''
1442
- };
1443
- const SWIPE_AREA_CLOSED_HOOK = {
1444
- [DrawerSwipeAreaDataAttributes.closed]: ''
1445
- };
1446
- const SWIPE_AREA_SWIPING_HOOK = {
1447
- [DrawerSwipeAreaDataAttributes.swiping]: ''
1448
- };
1449
- const SWIPE_AREA_DISABLED_HOOK = {
1450
- [DrawerSwipeAreaDataAttributes.disabled]: ''
1451
- };
1452
- const stateAttributesMapping$3 = {
1453
- open(value) {
1454
- return value ? SWIPE_AREA_OPEN_HOOK : SWIPE_AREA_CLOSED_HOOK;
1455
- },
1456
- swiping(value) {
1457
- return value ? SWIPE_AREA_SWIPING_HOOK : null;
1458
- },
1459
- swipeDirection(value) {
1460
- return value ? {
1461
- [DrawerSwipeAreaDataAttributes.swipeDirection]: value
1462
- } : null;
1463
- },
1464
- disabled(value) {
1465
- return value ? SWIPE_AREA_DISABLED_HOOK : null;
1466
- }
1467
- };
1468
- const oppositeSwipeDirection = {
1469
- up: 'down',
1470
- down: 'up',
1471
- left: 'right',
1472
- right: 'left'
1473
- };
1474
- function resolveTouchAction(direction) {
1475
- return direction === 'left' || direction === 'right' ? 'pan-y' : 'pan-x';
1476
- }
1477
-
1478
- /**
1479
- * An invisible area that listens for swipe gestures to open the drawer.
1480
- * Renders a `<div>` element.
1481
- *
1482
- * Documentation: [Base UI Drawer](https://base-ui.com/react/components/drawer)
1483
- */
1484
- const DrawerSwipeArea = /*#__PURE__*/React.forwardRef(function DrawerSwipeArea(componentProps, forwardedRef) {
1485
- const {
1486
- render,
1487
- className,
1488
- style,
1489
- disabled = false,
1490
- swipeDirection: swipeDirectionProp,
1491
- ...elementProps
1492
- } = componentProps;
1493
- const {
1494
- store
1495
- } = useDialogRootContext();
1496
- const {
1497
- swipeDirection,
1498
- frontmostHeight
1499
- } = useDrawerRootContext();
1500
- const providerContext = useDrawerProviderContext();
1501
- const [swipeActive, setSwipeActive] = React.useState(false);
1502
- const releaseDismissTimeout = useTimeout();
1503
- const swipeAreaRef = React.useRef(null);
1504
- const swipeStartEventRef = React.useRef(null);
1505
- const openedBySwipeRef = React.useRef(false);
1506
- const dragDeltaRef = React.useRef({
1507
- x: 0,
1508
- y: 0
1509
- });
1510
- const closedOffsetRef = React.useRef(null);
1511
- const appliedSwipeStylesRef = React.useRef(false);
1512
- const popupTransitionRef = React.useRef(null);
1513
- const swipeAreaId = useBaseUiId(componentProps.id);
1514
- const registerTrigger = useTriggerRegistration(swipeAreaId, store);
1515
- const open = store.useState('open');
1516
- const resetDragDelta = useStableCallback(() => {
1517
- dragDeltaRef.current.x = 0;
1518
- dragDeltaRef.current.y = 0;
1519
- });
1520
- const resolvedSwipeDirection = swipeDirectionProp ?? oppositeSwipeDirection[swipeDirection];
1521
- const dismissDirection = oppositeSwipeDirection[resolvedSwipeDirection];
1522
- const enabled = !disabled && (!open || swipeActive);
1523
- function disableDismissForSwipe() {
1524
- releaseDismissTimeout.clear();
1525
- store.context.outsidePressEnabledRef.current = false;
1526
- }
1527
- function enableDismissAfterRelease() {
1528
- // Safari can dispatch outside-press for the same swipe-open gesture
1529
- // after release, so defer re-enabling dismissal to the next macrotask.
1530
- releaseDismissTimeout.start(0, () => {
1531
- store.context.outsidePressEnabledRef.current = true;
1532
- });
1533
- }
1534
- function resolvePopupSize() {
1535
- const popupElement = store.context.popupRef.current;
1536
- if (!popupElement) {
1537
- return null;
1538
- }
1539
- const isHorizontal = dismissDirection === 'left' || dismissDirection === 'right';
1540
- const size = isHorizontal ? popupElement.offsetWidth : popupElement.offsetHeight;
1541
- if (size <= 0) {
1542
- return null;
1543
- }
1544
- return size;
1545
- }
1546
- function resolveClosedOffset() {
1547
- const offset = resolvePopupSize();
1548
- if (offset == null) {
1549
- return null;
1550
- }
1551
- const popupElement = store.context.popupRef.current;
1552
- if (!popupElement) {
1553
- return offset;
1554
- }
1555
- const isHorizontal = dismissDirection === 'left' || dismissDirection === 'right';
1556
- const transform = getElementTransform(popupElement);
1557
- const transformOffset = isHorizontal ? transform.x : transform.y;
1558
- if (Number.isFinite(transformOffset) && Math.abs(transformOffset) > 0.5) {
1559
- return Math.min(offset, Math.abs(transformOffset));
1560
- }
1561
- return offset;
1562
- }
1563
- function resolveSwipeOpenThreshold() {
1564
- const popupSize = resolvePopupSize();
1565
- if (popupSize == null) {
1566
- return FALLBACK_SWIPE_OPEN_THRESHOLD;
1567
- }
1568
- return popupSize * DEFAULT_SWIPE_OPEN_RATIO;
1569
- }
1570
- function applySwipeMovement() {
1571
- if (!swipeActive) {
1572
- return;
1573
- }
1574
- const popupElement = store.context.popupRef.current;
1575
- if (!popupElement) {
1576
- return;
1577
- }
1578
- if (!store.select('open') || !store.select('mounted')) {
1579
- return;
1580
- }
1581
- if (closedOffsetRef.current == null) {
1582
- closedOffsetRef.current = resolveClosedOffset();
1583
- }
1584
- const closedOffset = closedOffsetRef.current;
1585
- if (!closedOffset || !Number.isFinite(closedOffset) || closedOffset <= 0) {
574
+ const closedOffset = closedOffsetRef.current;
575
+ if (!closedOffset || !Number.isFinite(closedOffset) || closedOffset <= 0) {
1586
576
  return;
1587
577
  }
1588
578
  const {
@@ -1685,865 +675,98 @@ const DrawerSwipeArea = /*#__PURE__*/React.forwardRef(function DrawerSwipeArea(c
1685
675
  swipeStartEventRef.current = event;
1686
676
  openedBySwipeRef.current = false;
1687
677
  setSwipeActive(true);
1688
- resetDragDelta();
1689
- },
1690
- onProgress(_progress, details) {
1691
- if (!details) {
1692
- return;
1693
- }
1694
- if (!swipeStartEventRef.current) {
1695
- return;
1696
- }
1697
- dragDeltaRef.current.x = details.deltaX;
1698
- dragDeltaRef.current.y = details.deltaY;
1699
- if (details.direction !== resolvedSwipeDirection) {
1700
- return;
1701
- }
1702
- const displacement = getDisplacement(resolvedSwipeDirection, details.deltaX, details.deltaY);
1703
- if (displacement < MIN_SWIPE_START_DISTANCE && !openedBySwipeRef.current) {
1704
- return;
1705
- }
1706
- if (!openedBySwipeRef.current) {
1707
- openDrawer(swipeStartEventRef.current);
1708
- }
1709
- applySwipeMovement();
1710
- },
1711
- onRelease({
1712
- event,
1713
- direction,
1714
- deltaX,
1715
- deltaY,
1716
- releaseVelocityX,
1717
- releaseVelocityY
1718
- }) {
1719
- const displacement = getDisplacement(resolvedSwipeDirection, deltaX, deltaY);
1720
- const releaseVelocity = getDisplacement(resolvedSwipeDirection, releaseVelocityX, releaseVelocityY);
1721
- const threshold = resolveSwipeOpenThreshold();
1722
- const hasEnoughDistance = threshold != null && displacement >= threshold;
1723
- const hasEnoughVelocity = releaseVelocity >= VELOCITY_THRESHOLD;
1724
- const shouldOpen = threshold != null && direction === resolvedSwipeDirection && (hasEnoughDistance || hasEnoughVelocity) && !disabled;
1725
- if (shouldOpen) {
1726
- if (!store.select('open')) {
1727
- openDrawer(event);
1728
- }
1729
- } else if (openedBySwipeRef.current) {
1730
- closeDrawer(event);
1731
- }
1732
- finishSwipeInteraction();
1733
- return false;
1734
- },
1735
- onCancel: finishSwipeInteraction
1736
- });
1737
- const swipePointerProps = swipe$1.getPointerProps();
1738
- const swipeTouchProps = swipe$1.getTouchProps();
1739
- const resetSwipe = swipe$1.reset;
1740
- React.useEffect(() => {
1741
- if (!enabled) {
1742
- resetSwipe();
1743
- resetDragDelta();
1744
- clearSwipeStyles();
1745
- resetSwipeInteractionState();
1746
- }
1747
- }, [clearSwipeStyles, enabled, resetDragDelta, resetSwipe]);
1748
- React.useEffect(() => {
1749
- return () => {
1750
- store.context.outsidePressEnabledRef.current = true;
1751
- };
1752
- }, [store]);
1753
- const state = {
1754
- open,
1755
- swiping: swipe$1.swiping,
1756
- swipeDirection: resolvedSwipeDirection,
1757
- disabled
1758
- };
1759
- return useRenderElement('div', componentProps, {
1760
- state,
1761
- ref: [forwardedRef, swipeAreaRef, registerTrigger],
1762
- stateAttributesMapping: stateAttributesMapping$3,
1763
- props: [{
1764
- role: 'presentation',
1765
- 'aria-hidden': true,
1766
- style: {
1767
- pointerEvents: !enabled ? 'none' : undefined,
1768
- touchAction: resolveTouchAction(resolvedSwipeDirection)
1769
- },
1770
- onPointerDown(event) {
1771
- if (event.pointerType === 'touch') {
1772
- return;
1773
- }
1774
- swipePointerProps.onPointerDown?.(event);
1775
-
1776
- // Prevent native text selection/drag gestures from competing with swipe-open dragging.
1777
- if (event.cancelable) {
1778
- event.preventDefault();
1779
- }
1780
- },
1781
- onPointerMove(event) {
1782
- if (event.pointerType === 'touch') {
1783
- return;
1784
- }
1785
- swipePointerProps.onPointerMove?.(event);
1786
- },
1787
- onPointerUp(event) {
1788
- if (event.pointerType === 'touch') {
1789
- return;
1790
- }
1791
- swipePointerProps.onPointerUp?.(event);
1792
- },
1793
- onPointerCancel(event) {
1794
- if (event.pointerType === 'touch') {
1795
- return;
1796
- }
1797
- swipePointerProps.onPointerCancel?.(event);
1798
- }
1799
- }, swipeTouchProps, swipeAreaId ? {
1800
- id: swipeAreaId
1801
- } : undefined, elementProps]
1802
- });
1803
- });
1804
- if (process.env.NODE_ENV !== "production") DrawerSwipeArea.displayName = "DrawerSwipeArea";
1805
-
1806
- const DrawerVirtualKeyboardContext = /*#__PURE__*/React.createContext(undefined);
1807
- if (process.env.NODE_ENV !== "production") DrawerVirtualKeyboardContext.displayName = "DrawerVirtualKeyboardContext";
1808
- function useDrawerVirtualKeyboardContext() {
1809
- return React.useContext(DrawerVirtualKeyboardContext);
1810
- }
1811
-
1812
- const MIN_SWIPE_THRESHOLD = 10;
1813
- const FAST_SWIPE_VELOCITY = 0.5;
1814
- const SNAP_VELOCITY_THRESHOLD = 0.5;
1815
- const SNAP_VELOCITY_MULTIPLIER = 300;
1816
- const MAX_SNAP_VELOCITY = 4;
1817
- const MIN_SWIPE_RELEASE_VELOCITY = 0.2;
1818
- const MAX_SWIPE_RELEASE_VELOCITY = 4;
1819
- const MIN_SWIPE_RELEASE_DURATION_MS = 80;
1820
- const MAX_SWIPE_RELEASE_DURATION_MS = 360;
1821
- const MIN_SWIPE_RELEASE_SCALAR = 0.1;
1822
- const MAX_SWIPE_RELEASE_SCALAR = 1;
1823
- const DRAWER_CONTENT_SELECTOR = `[${DRAWER_CONTENT_ATTRIBUTE}]`;
1824
- /**
1825
- * A positioning container for the drawer popup that can be made scrollable.
1826
- * Renders a `<div>` element.
1827
- *
1828
- * Documentation: [Base UI Drawer](https://base-ui.com/react/components/drawer)
1829
- */
1830
- const DrawerViewport = /*#__PURE__*/React.forwardRef(function DrawerViewport(props, forwardedRef) {
1831
- const {
1832
- render,
1833
- className,
1834
- style,
1835
- children,
1836
- ...elementProps
1837
- } = props;
1838
- const {
1839
- store
1840
- } = useDialogRootContext();
1841
- const popupRef = store.context.popupRef;
1842
- const backdropRef = store.context.backdropRef;
1843
- const {
1844
- swipeDirection,
1845
- notifyParentSwipingChange,
1846
- notifyParentSwipeProgressChange,
1847
- frontmostHeight,
1848
- snapToSequentialPoints
1849
- } = useDrawerRootContext();
1850
- const providerContext = useDrawerProviderContext();
1851
- const {
1852
- snapPoints,
1853
- resolvedSnapPoints,
1854
- activeSnapPoint,
1855
- activeSnapPointOffset,
1856
- setActiveSnapPoint,
1857
- popupHeight
1858
- } = useDrawerSnapPoints();
1859
- const open = store.useState('open');
1860
- const mounted = store.useState('mounted');
1861
- const nested = store.useState('nested');
1862
- const nestedOpenDrawerCount = store.useState('nestedOpenDrawerCount');
1863
- const viewportElement = store.useState('viewportElement');
1864
- const popupElementState = store.useState('popupElement');
1865
- const visualStateStore = providerContext?.visualStateStore;
1866
- const nestedDrawerOpen = nestedOpenDrawerCount > 0;
1867
- const scrollAxis = swipeDirection === 'left' || swipeDirection === 'right' ? 'horizontal' : 'vertical';
1868
- const isVerticalScrollAxis = scrollAxis === 'vertical';
1869
- const crossScrollAxis = isVerticalScrollAxis ? 'horizontal' : 'vertical';
1870
- const [swipeRelease, setSwipeRelease] = React.useState(null);
1871
- const pendingSwipeCloseSnapPointRef = React.useRef(undefined);
1872
- const resetSwipeRef = React.useRef(null);
1873
- const controlledDismissFrame = useAnimationFrame();
1874
- const swipingRef = React.useRef(false);
1875
- const nestedSwipeActiveRef = React.useRef(false);
1876
- const lastPointerTypeRef = React.useRef('');
1877
- const ignoreNextTouchStartFromPenRef = React.useRef(false);
1878
- const ignoreTouchSwipeRef = React.useRef(false);
1879
- const touchScrollStateRef = React.useRef(null);
1880
- const virtualKeyboard = useDrawerVirtualKeyboardContext();
1881
- const snapPointRange = React.useMemo(() => {
1882
- if (!snapPoints || snapPoints.length < 2) {
1883
- return null;
1884
- }
1885
- if (swipeDirection !== 'down' && swipeDirection !== 'up') {
1886
- return null;
1887
- }
1888
- if (resolvedSnapPoints.length < 2) {
1889
- return null;
1890
- }
1891
- const offsets = resolvedSnapPoints.map(point => point.offset).filter(offset => Number.isFinite(offset)).sort((a, b) => a - b);
1892
- if (offsets.length < 2) {
1893
- return null;
1894
- }
1895
- const minOffset = offsets[0];
1896
- const nextOffset = offsets[1];
1897
- const maxOffset = offsets[offsets.length - 1];
1898
- let range = nextOffset - minOffset;
1899
- if (!Number.isFinite(range) || range <= 0) {
1900
- const fallbackRange = maxOffset - minOffset;
1901
- if (!Number.isFinite(fallbackRange) || fallbackRange <= 0) {
1902
- return null;
1903
- }
1904
- range = fallbackRange;
1905
- }
1906
- return {
1907
- minOffset,
1908
- range
1909
- };
1910
- }, [resolvedSnapPoints, snapPoints, swipeDirection]);
1911
- const snapPointProgress = React.useMemo(() => {
1912
- if (!snapPointRange || activeSnapPointOffset === null) {
1913
- return null;
1914
- }
1915
- return clamp((activeSnapPointOffset - snapPointRange.minOffset) / snapPointRange.range, 0, 1);
1916
- }, [activeSnapPointOffset, snapPointRange]);
1917
- const swipeDirections = React.useMemo(() => {
1918
- if (snapPoints && snapPoints.length > 0 && (swipeDirection === 'down' || swipeDirection === 'up')) {
1919
- return swipeDirection === 'down' ? ['down', 'up'] : ['up', 'down'];
1920
- }
1921
- return [swipeDirection];
1922
- }, [snapPoints, swipeDirection]);
1923
- const setSwipeDismissed = useStableCallback(dismissed => {
1924
- setSwipeDismissedElements(popupRef.current, backdropRef.current, dismissed);
1925
- });
1926
- const clearSwipeRelease = useStableCallback(() => {
1927
- setSwipeDismissed(false);
1928
- popupRef.current?.removeAttribute(TransitionStatusDataAttributes.endingStyle);
1929
- setSwipeRelease(null);
1930
- });
1931
- const finishNestedSwipe = useStableCallback(() => {
1932
- if (!nestedSwipeActiveRef.current) {
1933
- return;
1934
- }
1935
- nestedSwipeActiveRef.current = false;
1936
- notifyParentSwipingChange?.(false);
1937
- });
1938
- const applySwipeProgress = useStableCallback(({
1939
- resolvedProgress,
1940
- shouldTrackProgress,
1941
- notifyParent
1942
- }) => {
1943
- const isActive = open && !nested && shouldTrackProgress;
1944
- const swipeProgress = isActive ? resolvedProgress : 0;
1945
- const nestedSwipeProgress = open && shouldTrackProgress ? resolvedProgress : 0;
1946
- if (notifyParent && notifyParentSwipeProgressChange) {
1947
- notifyParentSwipeProgressChange(nestedSwipeProgress);
1948
- if (nestedSwipeProgress <= 0) {
1949
- finishNestedSwipe();
1950
- }
1951
- }
1952
- visualStateStore?.set({
1953
- swipeProgress,
1954
- frontmostHeight: swipeProgress > 0 ? frontmostHeight : 0
1955
- });
1956
- const backdropElement = backdropRef.current;
1957
- if (!backdropElement) {
1958
- return;
1959
- }
1960
- if (!isActive || swipeProgress <= 0) {
1961
- backdropElement.style.setProperty(DrawerBackdropCssVars.swipeProgress, '0');
1962
- backdropElement.style.removeProperty(DrawerPopupCssVars.height);
1963
- return;
1964
- }
1965
- backdropElement.style.setProperty(DrawerBackdropCssVars.swipeProgress, `${swipeProgress}`);
1966
- if (frontmostHeight > 0) {
1967
- backdropElement.style.setProperty(DrawerPopupCssVars.height, `${frontmostHeight}px`);
1968
- } else {
1969
- backdropElement.style.removeProperty(DrawerPopupCssVars.height);
1970
- }
1971
- });
1972
- function resolveSwipeRelease({
1973
- direction,
1974
- deltaX,
1975
- deltaY,
1976
- velocityX,
1977
- velocityY,
1978
- releaseVelocityX,
1979
- releaseVelocityY
1980
- }) {
1981
- if (!direction) {
1982
- return null;
1983
- }
1984
- const popupElement = store.context.popupRef.current;
1985
- if (!popupElement) {
1986
- return null;
1987
- }
1988
- const size = direction === 'left' || direction === 'right' ? popupElement.offsetWidth : popupElement.offsetHeight;
1989
- if (!Number.isFinite(size) || size <= 0) {
1990
- return null;
1991
- }
1992
- const axisDelta = direction === 'left' || direction === 'right' ? deltaX : deltaY;
1993
- const snapPointBaseOffset = snapPoints && snapPoints.length > 0 ? activeSnapPointOffset ?? 0 : 0;
1994
- let baseOffset = 0;
1995
- if (direction === 'down') {
1996
- baseOffset = snapPointBaseOffset;
1997
- } else if (direction === 'up') {
1998
- baseOffset = -snapPointBaseOffset;
1999
- }
2000
- const translation = baseOffset + axisDelta;
2001
- const translationAlongDirection = direction === 'left' || direction === 'up' ? -translation : translation;
2002
- const remainingDistance = Math.max(0, size - translationAlongDirection);
2003
- if (!Number.isFinite(remainingDistance) || remainingDistance <= 0) {
2004
- return null;
2005
- }
2006
- const axisVelocity = direction === 'left' || direction === 'right' ? releaseVelocityX : releaseVelocityY;
2007
- const fallbackVelocity = direction === 'left' || direction === 'right' ? velocityX : velocityY;
2008
- const resolvedVelocity = Math.abs(axisVelocity) > 0 && Number.isFinite(axisVelocity) ? axisVelocity : fallbackVelocity;
2009
- const directionalVelocity = direction === 'left' || direction === 'up' ? -resolvedVelocity : resolvedVelocity;
2010
- if (!Number.isFinite(directionalVelocity) || directionalVelocity <= MIN_SWIPE_RELEASE_VELOCITY) {
2011
- return null;
2012
- }
2013
- const clampedVelocity = clamp(directionalVelocity, MIN_SWIPE_RELEASE_VELOCITY, MAX_SWIPE_RELEASE_VELOCITY);
2014
- const durationMs = clamp(remainingDistance / clampedVelocity, MIN_SWIPE_RELEASE_DURATION_MS, MAX_SWIPE_RELEASE_DURATION_MS);
2015
- if (!Number.isFinite(durationMs)) {
2016
- return null;
2017
- }
2018
- const normalizedDuration = (durationMs - MIN_SWIPE_RELEASE_DURATION_MS) / (MAX_SWIPE_RELEASE_DURATION_MS - MIN_SWIPE_RELEASE_DURATION_MS);
2019
- const durationScalar = clamp(MIN_SWIPE_RELEASE_SCALAR + normalizedDuration * (MAX_SWIPE_RELEASE_SCALAR - MIN_SWIPE_RELEASE_SCALAR), MIN_SWIPE_RELEASE_SCALAR, MAX_SWIPE_RELEASE_SCALAR);
2020
- if (!Number.isFinite(durationScalar) || durationScalar <= 0) {
2021
- return null;
2022
- }
2023
- return durationScalar;
2024
- }
2025
- function updateNestedSwipeActive(details) {
2026
- if (nestedSwipeActiveRef.current || !details) {
2027
- return;
2028
- }
2029
- const direction = details.direction ?? swipeDirection;
2030
- const delta = direction === 'left' || direction === 'right' ? details.deltaX : details.deltaY;
2031
- if (!Number.isFinite(delta) || Math.abs(delta) < MIN_SWIPE_THRESHOLD) {
2032
- return;
2033
- }
2034
- nestedSwipeActiveRef.current = true;
2035
- notifyParentSwipingChange?.(true);
2036
- }
2037
- const swipe$1 = useSwipeDismiss({
2038
- enabled: mounted && !nestedDrawerOpen,
2039
- directions: swipeDirections,
2040
- elementRef: store.context.popupRef,
2041
- ignoreSelectorWhenTouch: false,
2042
- ignoreScrollableAncestors: true,
2043
- movementCssVars: {
2044
- x: DrawerPopupCssVars.swipeMovementX,
2045
- y: DrawerPopupCssVars.swipeMovementY
2046
- },
2047
- onSwipeStart(event) {
2048
- if ('touches' in event || 'pointerType' in event && event.pointerType === 'touch') {
2049
- return;
2050
- }
2051
- const popupElement = popupRef.current;
2052
- if (!popupElement) {
2053
- return;
2054
- }
2055
- const doc = ownerDocument(popupElement);
2056
- const selection = doc.getSelection?.();
2057
- if (!selection || selection.isCollapsed) {
2058
- return;
2059
- }
2060
- const anchorElement = isElement(selection.anchorNode) ? selection.anchorNode : selection.anchorNode?.parentElement;
2061
- const focusElement = isElement(selection.focusNode) ? selection.focusNode : selection.focusNode?.parentElement;
2062
- if (!contains(popupElement, anchorElement) && !contains(popupElement, focusElement)) {
2063
- return;
2064
- }
2065
- selection.removeAllRanges();
2066
- },
2067
- onSwipingChange(swiping) {
2068
- swipingRef.current = swiping;
2069
- setBackdropSwipingAttribute(store.context.backdropRef.current, swiping);
2070
- if (!swiping && !notifyParentSwipeProgressChange) {
2071
- finishNestedSwipe();
2072
- }
2073
- },
2074
- swipeThreshold({
2075
- element,
2076
- direction
2077
- }) {
2078
- return getBaseSwipeThreshold(element, direction);
2079
- },
2080
- canStart(position, details) {
2081
- const popupElement = store.context.popupRef.current;
2082
- if (!popupElement) {
2083
- return false;
2084
- }
2085
- const doc = popupElement.ownerDocument;
2086
- const elementAtPoint = getElementAtPoint(doc, position.x, position.y);
2087
- if (!elementAtPoint || !contains(popupElement, elementAtPoint)) {
2088
- return false;
678
+ resetDragDelta();
679
+ },
680
+ onProgress(_progress, details) {
681
+ if (!details) {
682
+ return;
2089
683
  }
2090
- const nativeEvent = details.nativeEvent;
2091
- const touchLike = 'touches' in nativeEvent || 'pointerType' in nativeEvent && nativeEvent.pointerType === 'touch';
2092
- if (touchLike && shouldIgnoreSwipeForTextSelection(doc, popupElement)) {
2093
- return false;
684
+ if (!swipeStartEventRef.current) {
685
+ return;
2094
686
  }
2095
- if (nativeEvent.type === 'touchstart' && isSwipeIgnoredTarget(elementAtPoint)) {
2096
- return false;
687
+ dragDeltaRef.current.x = details.deltaX;
688
+ dragDeltaRef.current.y = details.deltaY;
689
+ if (details.direction !== resolvedSwipeDirection) {
690
+ return;
2097
691
  }
2098
- return true;
2099
- },
2100
- onProgress(progress, details) {
2101
- updateNestedSwipeActive(details);
2102
- const hasSnapPoints = Boolean(snapPoints && snapPoints.length > 0);
2103
- if (swipingRef.current && swipeDirection === 'down' && hasSnapPoints && details && Number.isFinite(details.deltaY)) {
2104
- const popupElement = store.context.popupRef.current;
2105
- if (popupElement) {
2106
- popupElement.style.removeProperty('transform');
2107
- popupElement.style.setProperty(DrawerPopupCssVars.swipeMovementY, `${getSnapPointSwipeMovement(activeSnapPointOffset ?? 0, details.deltaY)}px`);
2108
- }
692
+ const displacement = getDisplacement(resolvedSwipeDirection, details.deltaX, details.deltaY);
693
+ if (displacement < MIN_SWIPE_START_DISTANCE && !openedBySwipeRef.current) {
694
+ return;
2109
695
  }
2110
- const currentDirection = details?.direction ?? swipe$1.swipeDirection;
2111
- const isDismissSwipe = currentDirection === undefined || currentDirection === swipeDirection;
2112
- const isVerticalSwipe = swipeDirection === 'down' || swipeDirection === 'up';
2113
- const shouldTrackProgress = hasSnapPoints && isVerticalSwipe || !hasSnapPoints || swipeDirection === 'left' || swipeDirection === 'right' || isDismissSwipe;
2114
- let resolvedProgress = progress;
2115
- if (snapPointRange && popupHeight > 0) {
2116
- if (details && Number.isFinite(details.deltaY)) {
2117
- const baseOffset = activeSnapPointOffset ?? snapPointRange.minOffset;
2118
- const nextOffset = clamp(baseOffset + details.deltaY, 0, popupHeight);
2119
- resolvedProgress = clamp((nextOffset - snapPointRange.minOffset) / snapPointRange.range, 0, 1);
2120
- } else if (snapPointProgress !== null) {
2121
- resolvedProgress = snapPointProgress;
2122
- } else if (currentDirection === 'down' || currentDirection === 'up') {
2123
- const displacement = progress * popupHeight;
2124
- const baseOffset = activeSnapPointOffset ?? snapPointRange.minOffset;
2125
- const nextOffset = currentDirection === 'down' ? baseOffset + displacement : baseOffset - displacement;
2126
- resolvedProgress = clamp((nextOffset - snapPointRange.minOffset) / snapPointRange.range, 0, 1);
2127
- }
696
+ if (!openedBySwipeRef.current) {
697
+ openDrawer(swipeStartEventRef.current);
2128
698
  }
2129
- applySwipeProgress({
2130
- resolvedProgress,
2131
- shouldTrackProgress,
2132
- notifyParent: true
2133
- });
699
+ applySwipeMovement();
2134
700
  },
2135
701
  onRelease({
2136
702
  event,
703
+ direction,
2137
704
  deltaX,
2138
705
  deltaY,
2139
- direction,
2140
- velocityX,
2141
- velocityY,
2142
706
  releaseVelocityX,
2143
707
  releaseVelocityY
2144
708
  }) {
2145
- const swipeReleasePayload = {
2146
- deltaX,
2147
- deltaY,
2148
- velocityX,
2149
- velocityY,
2150
- releaseVelocityX,
2151
- releaseVelocityY
2152
- };
2153
- function startSwipeRelease(resolvedDirection) {
2154
- // Start ending transition styles earlier and synchronously to prevent a period where
2155
- // the popup appears stuck on release before the actual closing animation starts.
2156
- const popupElement = store.context.popupRef.current;
2157
- if (!popupElement) {
2158
- return;
2159
- }
2160
- finishNestedSwipe();
2161
- setSwipeDismissed(true);
2162
- popupElement.style.removeProperty('transition');
2163
- popupElement.setAttribute(TransitionStatusDataAttributes.endingStyle, '');
2164
- ReactDOM.flushSync(() => {
2165
- setSwipeRelease(resolveSwipeRelease({
2166
- direction: resolvedDirection,
2167
- ...swipeReleasePayload
2168
- }));
2169
- });
2170
- }
2171
- if (!snapPoints || snapPoints.length === 0) {
2172
- if (!direction) {
2173
- clearSwipeRelease();
2174
- return undefined;
2175
- }
2176
- const element = store.context.popupRef.current;
2177
- if (!element) {
2178
- clearSwipeRelease();
2179
- return undefined;
2180
- }
2181
- const baseThreshold = getBaseSwipeThreshold(element, direction);
2182
- const delta = direction === 'left' || direction === 'right' ? deltaX : deltaY;
2183
- if (!Number.isFinite(delta)) {
2184
- clearSwipeRelease();
2185
- return undefined;
2186
- }
2187
- const directionalDelta = direction === 'left' || direction === 'up' ? -delta : delta;
2188
- if (directionalDelta <= 0) {
2189
- clearSwipeRelease();
2190
- return false;
2191
- }
2192
- const velocity = direction === 'left' || direction === 'right' ? velocityX : velocityY;
2193
- const directionalVelocity = direction === 'left' || direction === 'up' ? -velocity : velocity;
2194
- if (directionalVelocity >= FAST_SWIPE_VELOCITY && directionalDelta > 0) {
2195
- startSwipeRelease(direction);
2196
- return true;
2197
- }
2198
- const shouldClose = directionalDelta > baseThreshold;
2199
- if (shouldClose) {
2200
- startSwipeRelease(direction);
2201
- } else {
2202
- clearSwipeRelease();
2203
- }
2204
- return shouldClose;
2205
- }
2206
- if (swipeDirection !== 'down' && swipeDirection !== 'up') {
2207
- clearSwipeRelease();
2208
- return undefined;
2209
- }
2210
- if (!popupHeight || resolvedSnapPoints.length === 0) {
2211
- clearSwipeRelease();
2212
- return undefined;
2213
- }
2214
- const dragDelta = swipeDirection === 'down' ? deltaY : -deltaY;
2215
- if (!Number.isFinite(dragDelta)) {
2216
- clearSwipeRelease();
2217
- return undefined;
2218
- }
2219
- const dragDirection = Math.sign(dragDelta);
2220
- const releaseDirectionalVelocity = swipeDirection === 'down' ? releaseVelocityY : -releaseVelocityY;
2221
- const fallbackDirectionalVelocity = swipeDirection === 'down' ? velocityY : -velocityY;
2222
- let resolvedDirectionalVelocity = Number.isFinite(releaseDirectionalVelocity) ? releaseDirectionalVelocity : fallbackDirectionalVelocity;
2223
- if (dragDirection !== 0 && Math.abs(dragDelta) >= MIN_SWIPE_THRESHOLD && Number.isFinite(resolvedDirectionalVelocity)) {
2224
- const velocityDirection = Math.sign(resolvedDirectionalVelocity);
2225
- if (velocityDirection !== 0 && velocityDirection !== dragDirection) {
2226
- // Ignore touch reversals that would otherwise flip the snap decision.
2227
- resolvedDirectionalVelocity = fallbackDirectionalVelocity;
2228
- }
2229
- }
2230
- const currentOffset = activeSnapPointOffset ?? 0;
2231
- const dragTargetOffset = clamp(currentOffset + dragDelta, 0, popupHeight);
2232
- const velocityOffset = Number.isFinite(resolvedDirectionalVelocity) && Math.abs(resolvedDirectionalVelocity) >= SNAP_VELOCITY_THRESHOLD ? clamp(resolvedDirectionalVelocity, -MAX_SNAP_VELOCITY, MAX_SNAP_VELOCITY) * SNAP_VELOCITY_MULTIPLIER : 0;
2233
- const targetOffset = snapToSequentialPoints ? dragTargetOffset : clamp(dragTargetOffset + velocityOffset, 0, popupHeight);
2234
- const snapPointEventDetails = createChangeEventDetails(swipe, event);
2235
- const closeFromSnapPoints = () => {
2236
- pendingSwipeCloseSnapPointRef.current = activeSnapPoint;
2237
- setActiveSnapPoint?.(null, snapPointEventDetails);
2238
- startSwipeRelease(swipeDirection);
2239
- return true;
2240
- };
2241
- if (snapToSequentialPoints) {
2242
- const orderedSnapPoints = [...resolvedSnapPoints].sort((first, second) => first.offset - second.offset);
2243
- if (orderedSnapPoints.length === 0) {
2244
- clearSwipeRelease();
2245
- return false;
2246
- }
2247
- let currentIndex = 0;
2248
- let closestDistance = Math.abs(currentOffset - orderedSnapPoints[0].offset);
2249
- for (let index = 1; index < orderedSnapPoints.length; index += 1) {
2250
- const distance = Math.abs(currentOffset - orderedSnapPoints[index].offset);
2251
- if (distance < closestDistance) {
2252
- closestDistance = distance;
2253
- currentIndex = index;
2254
- }
2255
- }
2256
- let targetSnapPoint = orderedSnapPoints[0];
2257
- closestDistance = Math.abs(targetOffset - targetSnapPoint.offset);
2258
- for (const snapPoint of orderedSnapPoints) {
2259
- const distance = Math.abs(targetOffset - snapPoint.offset);
2260
- if (distance < closestDistance) {
2261
- closestDistance = distance;
2262
- targetSnapPoint = snapPoint;
2263
- }
2264
- }
2265
- const velocityDirection = Math.sign(resolvedDirectionalVelocity);
2266
- const shouldAdvance = dragDirection !== 0 && velocityDirection !== 0 && velocityDirection === dragDirection && Math.abs(resolvedDirectionalVelocity) >= SNAP_VELOCITY_THRESHOLD;
2267
- let effectiveTargetOffset = targetOffset;
2268
- if (shouldAdvance) {
2269
- const adjacentIndex = clamp(currentIndex + dragDirection, 0, orderedSnapPoints.length - 1);
2270
- if (adjacentIndex !== currentIndex) {
2271
- const adjacentPoint = orderedSnapPoints[adjacentIndex];
2272
- const shouldForceAdjacent = dragDirection > 0 ? targetOffset < adjacentPoint.offset : targetOffset > adjacentPoint.offset;
2273
- if (shouldForceAdjacent) {
2274
- targetSnapPoint = adjacentPoint;
2275
- effectiveTargetOffset = adjacentPoint.offset;
2276
- }
2277
- } else if (dragDirection > 0) {
2278
- return closeFromSnapPoints();
2279
- }
2280
- }
2281
- const closeOffset = popupHeight;
2282
- const closeDistance = Math.abs(effectiveTargetOffset - closeOffset);
2283
- const snapDistance = Math.abs(effectiveTargetOffset - targetSnapPoint.offset);
2284
- if (closeDistance < snapDistance) {
2285
- return closeFromSnapPoints();
2286
- }
2287
- setActiveSnapPoint?.(targetSnapPoint.value, snapPointEventDetails);
2288
- clearSwipeRelease();
2289
- return false;
2290
- }
2291
- if (resolvedDirectionalVelocity >= FAST_SWIPE_VELOCITY && dragDelta > 0) {
2292
- return closeFromSnapPoints();
2293
- }
2294
- let closestSnapPoint = resolvedSnapPoints[0];
2295
- let closestDistance = Math.abs(targetOffset - closestSnapPoint.offset);
2296
- for (const snapPoint of resolvedSnapPoints) {
2297
- const distance = Math.abs(targetOffset - snapPoint.offset);
2298
- if (distance < closestDistance) {
2299
- closestDistance = distance;
2300
- closestSnapPoint = snapPoint;
709
+ const displacement = getDisplacement(resolvedSwipeDirection, deltaX, deltaY);
710
+ const releaseVelocity = getDisplacement(resolvedSwipeDirection, releaseVelocityX, releaseVelocityY);
711
+ const threshold = resolveSwipeOpenThreshold();
712
+ const hasEnoughDistance = threshold != null && displacement >= threshold;
713
+ const hasEnoughVelocity = releaseVelocity >= VELOCITY_THRESHOLD;
714
+ const shouldOpen = threshold != null && direction === resolvedSwipeDirection && (hasEnoughDistance || hasEnoughVelocity) && !disabled;
715
+ if (shouldOpen) {
716
+ if (!store.select('open')) {
717
+ openDrawer(event);
2301
718
  }
719
+ } else if (openedBySwipeRef.current) {
720
+ closeDrawer(event);
2302
721
  }
2303
- const closeOffset = popupHeight;
2304
- const closeDistance = Math.abs(targetOffset - closeOffset);
2305
- if (closeDistance < closestDistance) {
2306
- return closeFromSnapPoints();
2307
- }
2308
- setActiveSnapPoint?.(closestSnapPoint.value, snapPointEventDetails);
2309
- clearSwipeRelease();
722
+ finishSwipeInteraction();
2310
723
  return false;
2311
724
  },
2312
- onDismiss(event) {
2313
- visualStateStore?.set({
2314
- swipeProgress: 0,
2315
- frontmostHeight: 0
2316
- });
2317
- const backdropElement = store.context.backdropRef.current;
2318
- if (backdropElement) {
2319
- backdropElement.style.setProperty(DrawerBackdropCssVars.swipeProgress, '0');
2320
- backdropElement.style.removeProperty(DrawerPopupCssVars.height);
2321
- }
2322
- const dismissEventDetails = createChangeEventDetails(swipe, event);
2323
- store.setOpen(false, dismissEventDetails);
2324
- if (dismissEventDetails.isCanceled) {
2325
- const pendingSnapPoint = pendingSwipeCloseSnapPointRef.current;
2326
- if (pendingSnapPoint !== undefined) {
2327
- setActiveSnapPoint?.(pendingSnapPoint, createChangeEventDetails(swipe, event));
2328
- }
2329
- pendingSwipeCloseSnapPointRef.current = undefined;
2330
- resetSwipeRef.current?.();
2331
- clearSwipeRelease();
2332
- return;
2333
- }
2334
-
2335
- // In controlled mode, the effective open state may not have changed yet
2336
- // (openProp takes precedence over state.open). Proceed optimistically with the
2337
- // dismiss animation — React's Scheduler flushes before the next rAF, so we can
2338
- // reliably check whether the parent accepted or rejected the close.
2339
- // Note: if onOpenChange is asynchronous (e.g., closes the drawer after a network
2340
- // call), the rAF check will see open === true, revert the animation, and the
2341
- // drawer will close without animation when the parent eventually sets open={false}.
2342
- if (store.select('open')) {
2343
- const savedEvent = event;
2344
- controlledDismissFrame.request(() => {
2345
- if (store.select('open')) {
2346
- // Parent rejected: revert animation and restore snap point.
2347
- const pendingSnapPoint = pendingSwipeCloseSnapPointRef.current;
2348
- if (pendingSnapPoint !== undefined) {
2349
- setActiveSnapPoint?.(pendingSnapPoint, createChangeEventDetails(swipe, savedEvent));
2350
- }
2351
- pendingSwipeCloseSnapPointRef.current = undefined;
2352
- clearSwipeRelease();
2353
- resetSwipeRef.current?.();
2354
- } else {
2355
- // Parent accepted: clean up the ref.
2356
- pendingSwipeCloseSnapPointRef.current = undefined;
2357
- }
2358
- });
2359
- return;
2360
- }
2361
- pendingSwipeCloseSnapPointRef.current = undefined;
2362
- setSwipeDismissed(true);
2363
- }
725
+ onCancel: finishSwipeInteraction
2364
726
  });
2365
727
  const swipePointerProps = swipe$1.getPointerProps();
2366
728
  const swipeTouchProps = swipe$1.getTouchProps();
2367
- const {
2368
- moveNative: moveSwipeNative,
2369
- reset: resetSwipe
2370
- } = swipe$1;
2371
- resetSwipeRef.current = resetSwipe;
2372
- React.useEffect(() => {
2373
- const rootElement = viewportElement ?? popupElementState;
2374
- if (!rootElement) {
2375
- return undefined;
2376
- }
2377
- const resolvedRootElement = rootElement;
2378
- const doc = ownerDocument(resolvedRootElement);
2379
- const win = getWindow(doc);
2380
- function handleNativeTouchMove(event) {
2381
- // The virtual keyboard provider observes the move to tell a tap apart from a drag.
2382
- // It must run even when the swipe gesture below claims the event with
2383
- // `stopPropagation()`, which would otherwise prevent React's delegated handlers
2384
- // (and the provider) from ever seeing the move.
2385
- virtualKeyboard?.onTouchMove(event);
2386
- if (ignoreTouchSwipeRef.current) {
2387
- return;
2388
- }
2389
- const touchState = touchScrollStateRef.current;
2390
- const touch = event.touches[0];
2391
- if (!touch || !touchState) {
2392
- return;
2393
- }
2394
- const drawerAxisDelta = isVerticalScrollAxis ? touch.clientY - touchState.lastY : touch.clientX - touchState.lastX;
2395
-
2396
- // Preserve native range interaction by never locking touchmove for range inputs.
2397
- if (isEventOnRangeInput(event, win)) {
2398
- touchState.allowSwipe = false;
2399
- updateTouchScrollPosition(touchState, touch);
2400
- return;
2401
- }
2402
-
2403
- // Avoid blocking pinch zoom or text selection adjustments on iOS Safari.
2404
- if (event.touches.length === 2) {
2405
- updateTouchScrollPosition(touchState, touch);
2406
- return;
2407
- }
2408
- const allowTouchMove = shouldIgnoreSwipeForTextSelection(doc, resolvedRootElement);
2409
- if (allowTouchMove || !open || !mounted || nestedDrawerOpen) {
2410
- updateTouchScrollPosition(touchState, touch);
2411
- return;
2412
- }
2413
- if (preserveNativeCrossAxisScrollOnMove(touchState, touch, isVerticalScrollAxis)) {
2414
- updateTouchScrollPosition(touchState, touch);
2415
- return;
2416
- }
2417
- const scrollTarget = touchState.scrollTarget;
2418
- if (!scrollTarget || scrollTarget === doc.documentElement || scrollTarget === doc.body) {
2419
- if (event.cancelable) {
2420
- event.preventDefault();
2421
- }
2422
- // Claim the gesture before React's delegated touch handlers see it; dispatching the
2423
- // move through React re-rasterizes the popup content on every frame.
2424
- event.stopPropagation();
2425
- moveSwipeNative(event, resolvedRootElement);
2426
- updateTouchScrollPosition(touchState, touch);
2427
- return;
2428
- }
2429
- const hasScrollableContent = hasScrollableContentOnAxis(scrollTarget, scrollAxis);
2430
- if (!hasScrollableContent) {
2431
- // If the scroll container doesn't overflow on the drawer axis, prevent the window from
2432
- // scrolling instead.
2433
- if (event.cancelable) {
2434
- event.preventDefault();
2435
- }
2436
- event.stopPropagation();
2437
- updateTouchScrollPosition(touchState, touch);
2438
- return;
2439
- }
2440
- const delta = drawerAxisDelta;
2441
- if (delta !== 0) {
2442
- const canSwipeFromScrollEdge = canSwipeFromScrollEdgeOnMove(scrollTarget, scrollAxis, swipeDirection, delta);
2443
- if (!touchState.allowSwipe) {
2444
- if (!event.cancelable) {
2445
- touchState.allowSwipe = false;
2446
- } else if (canSwipeFromScrollEdge) {
2447
- touchState.allowSwipe = true;
2448
- event.preventDefault();
2449
- } else {
2450
- touchState.allowSwipe = false;
2451
- }
2452
- } else if (event.cancelable) {
2453
- event.preventDefault();
2454
- }
2455
- }
2456
- if (touchState.allowSwipe === true) {
2457
- event.stopPropagation();
2458
- moveSwipeNative(event, resolvedRootElement);
2459
- }
2460
- updateTouchScrollPosition(touchState, touch);
2461
- }
2462
- return addEventListener(doc, 'touchmove', handleNativeTouchMove, {
2463
- passive: false,
2464
- capture: true
2465
- });
2466
- }, [mounted, nestedDrawerOpen, open, popupElementState, isVerticalScrollAxis, scrollAxis, swipeDirection, moveSwipeNative, viewportElement, virtualKeyboard]);
2467
- React.useEffect(() => {
2468
- if (!snapPointRange || swipe$1.swiping) {
2469
- return;
2470
- }
2471
- const resolvedProgress = !open || nested ? 0 : snapPointProgress ?? 0;
2472
- applySwipeProgress({
2473
- resolvedProgress,
2474
- shouldTrackProgress: true,
2475
- notifyParent: false
2476
- });
2477
- }, [applySwipeProgress, frontmostHeight, nested, notifyParentSwipeProgressChange, open, snapPointProgress, snapPointRange, swipe$1.swiping, store, visualStateStore]);
2478
- React.useEffect(() => {
2479
- if (!notifyParentSwipeProgressChange) {
2480
- return undefined;
2481
- }
2482
- if (!open) {
2483
- notifyParentSwipeProgressChange(0);
2484
- }
2485
- return () => {
2486
- notifyParentSwipeProgressChange(0);
2487
- };
2488
- }, [notifyParentSwipeProgressChange, open]);
729
+ const resetSwipe = swipe$1.reset;
2489
730
  React.useEffect(() => {
2490
- if (open) {
731
+ if (!enabled) {
2491
732
  resetSwipe();
2492
- clearSwipeRelease();
733
+ resetDragDelta();
734
+ clearSwipeStyles();
735
+ resetSwipeInteractionState();
2493
736
  }
2494
- }, [clearSwipeRelease, open, resetSwipe]);
737
+ }, [clearSwipeStyles, enabled, resetDragDelta, resetSwipe]);
2495
738
  React.useEffect(() => {
2496
- const backdropElement = backdropRef.current;
2497
739
  return () => {
2498
- visualStateStore?.set({
2499
- swipeProgress: 0,
2500
- frontmostHeight: 0
2501
- });
2502
- setBackdropSwipingAttribute(backdropElement, false);
2503
- // `data-swiping` is set on whichever backdrop is current when a swipe starts, which can
2504
- // differ from the captured element if the backdrop mounted late or changed identity.
2505
- // Reading the live ref here is intentional so the current backdrop is cleared too.
2506
- // eslint-disable-next-line react-hooks/exhaustive-deps
2507
- const currentBackdrop = backdropRef.current;
2508
- if (currentBackdrop !== backdropElement) {
2509
- setBackdropSwipingAttribute(currentBackdrop, false);
2510
- }
2511
- finishNestedSwipe();
740
+ store.context.outsidePressEnabledRef.current = true;
2512
741
  };
2513
- }, [backdropRef, finishNestedSwipe, visualStateStore]);
2514
- const swipeProviderValue = React.useMemo(() => ({
742
+ }, [store]);
743
+ const state = {
744
+ open,
2515
745
  swiping: swipe$1.swiping,
2516
- getDragStyles: swipe$1.getDragStyles,
2517
- swipeStrength: swipeRelease ?? null,
2518
- setSwipeDismissed
2519
- }), [setSwipeDismissed, swipe$1.getDragStyles, swipe$1.swiping, swipeRelease]);
2520
- function resetTouchTrackingState() {
2521
- ignoreTouchSwipeRef.current = false;
2522
- touchScrollStateRef.current = null;
2523
- lastPointerTypeRef.current = '';
2524
- ignoreNextTouchStartFromPenRef.current = false;
2525
- }
2526
- return /*#__PURE__*/jsx(DialogViewport, {
2527
- ref: forwardedRef,
2528
- className: className,
2529
- style: style,
2530
- render: render,
2531
- ...mergeProps(elementProps, {
746
+ swipeDirection: resolvedSwipeDirection,
747
+ disabled
748
+ };
749
+ return useRenderElement('div', componentProps, {
750
+ state,
751
+ ref: [forwardedRef, swipeAreaRef, registerTrigger],
752
+ stateAttributesMapping: stateAttributesMapping$3,
753
+ props: [{
754
+ role: 'presentation',
755
+ 'aria-hidden': true,
756
+ style: {
757
+ pointerEvents: !enabled ? 'none' : undefined,
758
+ touchAction: resolveTouchAction(resolvedSwipeDirection)
759
+ },
2532
760
  onPointerDown(event) {
2533
- lastPointerTypeRef.current = event.pointerType;
2534
- ignoreNextTouchStartFromPenRef.current = event.pointerType === 'pen';
2535
- if (!open || !mounted || nestedDrawerOpen) {
2536
- return;
2537
- }
2538
- const doc = ownerDocument(event.currentTarget);
2539
- const elementAtPoint = getElementAtPoint(doc, event.clientX, event.clientY);
2540
- if (isSwipeIgnoredTarget(elementAtPoint) || isDrawerContentTarget(elementAtPoint)) {
2541
- return;
2542
- }
2543
761
  if (event.pointerType === 'touch') {
2544
762
  return;
2545
763
  }
2546
764
  swipePointerProps.onPointerDown?.(event);
765
+
766
+ // Prevent native text selection/drag gestures from competing with swipe-open dragging.
767
+ if (event.cancelable) {
768
+ event.preventDefault();
769
+ }
2547
770
  },
2548
771
  onPointerMove(event) {
2549
772
  if (event.pointerType === 'touch') {
@@ -2552,258 +775,23 @@ const DrawerViewport = /*#__PURE__*/React.forwardRef(function DrawerViewport(pro
2552
775
  swipePointerProps.onPointerMove?.(event);
2553
776
  },
2554
777
  onPointerUp(event) {
2555
- if (lastPointerTypeRef.current === event.pointerType) {
2556
- lastPointerTypeRef.current = '';
2557
- }
2558
778
  if (event.pointerType === 'touch') {
2559
779
  return;
2560
780
  }
2561
781
  swipePointerProps.onPointerUp?.(event);
2562
782
  },
2563
783
  onPointerCancel(event) {
2564
- if (lastPointerTypeRef.current === event.pointerType) {
2565
- lastPointerTypeRef.current = '';
2566
- }
2567
784
  if (event.pointerType === 'touch') {
2568
785
  return;
2569
786
  }
2570
787
  swipePointerProps.onPointerCancel?.(event);
2571
- },
2572
- onTouchStart(event) {
2573
- const startedFromPenPointerDown = lastPointerTypeRef.current === 'pen' && ignoreNextTouchStartFromPenRef.current;
2574
- if (startedFromPenPointerDown) {
2575
- ignoreNextTouchStartFromPenRef.current = false;
2576
- ignoreTouchSwipeRef.current = false;
2577
- touchScrollStateRef.current = null;
2578
- return;
2579
- }
2580
- if (!open || !mounted || nestedDrawerOpen) {
2581
- ignoreTouchSwipeRef.current = false;
2582
- touchScrollStateRef.current = null;
2583
- return;
2584
- }
2585
- const touch = event.touches[0];
2586
- if (!touch) {
2587
- return;
2588
- }
2589
- if (isReactTouchEventOnRangeInput(event)) {
2590
- ignoreTouchSwipeRef.current = false;
2591
- touchScrollStateRef.current = null;
2592
- return;
2593
- }
2594
- const doc = ownerDocument(event.currentTarget);
2595
- const elementAtPoint = getElementAtPoint(doc, touch.clientX, touch.clientY);
2596
- const rootElement = viewportElement ?? popupElementState;
2597
- const eventTarget = getTarget(event.nativeEvent);
2598
- const target = isElement(eventTarget) ? eventTarget : null;
2599
- if (rootElement && target && !contains(rootElement, target)) {
2600
- ignoreTouchSwipeRef.current = true;
2601
- touchScrollStateRef.current = null;
2602
- return;
2603
- }
2604
- virtualKeyboard?.onTouchStart(event);
2605
- ignoreTouchSwipeRef.current = isSwipeIgnoredTarget(elementAtPoint);
2606
- if (ignoreTouchSwipeRef.current) {
2607
- touchScrollStateRef.current = null;
2608
- return;
2609
- }
2610
- let scrollTarget = null;
2611
- let hasCrossAxisScrollableContent = false;
2612
- if (rootElement && target) {
2613
- scrollTarget = findScrollableTouchTarget(target, rootElement, scrollAxis);
2614
- hasCrossAxisScrollableContent = findScrollableTouchTarget(target, rootElement, crossScrollAxis) != null;
2615
- }
2616
- let allowSwipe = null;
2617
- if (scrollTarget) {
2618
- const canSwipeFromEdge = isAtSwipeStartEdge(scrollTarget, scrollAxis, swipeDirection);
2619
- allowSwipe = canSwipeFromEdge ? null : false;
2620
- }
2621
- touchScrollStateRef.current = {
2622
- startX: touch.clientX,
2623
- startY: touch.clientY,
2624
- lastX: touch.clientX,
2625
- lastY: touch.clientY,
2626
- scrollTarget,
2627
- hasCrossAxisScrollableContent,
2628
- allowSwipe,
2629
- preserveNativeCrossAxisScroll: false
2630
- };
2631
- swipeTouchProps.onTouchStart?.(event);
2632
- },
2633
- onTouchEnd(event) {
2634
- virtualKeyboard?.onTouchEnd(event);
2635
- resetTouchTrackingState();
2636
- swipeTouchProps.onTouchEnd?.(event);
2637
- },
2638
- onTouchCancel(event) {
2639
- virtualKeyboard?.onTouchCancel();
2640
- resetTouchTrackingState();
2641
- swipeTouchProps.onTouchCancel?.(event);
2642
- },
2643
- // Drawer popups use drawer-specific nested state attributes.
2644
- // Suppress DialogViewport's generic nested dialog attribute.
2645
- ['data-nested-dialog-open']: undefined
2646
- }),
2647
- children: /*#__PURE__*/jsx(DrawerViewportContext.Provider, {
2648
- value: swipeProviderValue,
2649
- children: children
2650
- })
788
+ }
789
+ }, swipeTouchProps, swipeAreaId ? {
790
+ id: swipeAreaId
791
+ } : undefined, elementProps]
2651
792
  });
2652
793
  });
2653
- if (process.env.NODE_ENV !== "production") DrawerViewport.displayName = "DrawerViewport";
2654
- function setSwipeDismissedElements(popupElement, backdropElement, dismissed) {
2655
- if (dismissed) {
2656
- popupElement?.setAttribute(DrawerPopupDataAttributes.swipeDismiss, '');
2657
- backdropElement?.setAttribute(DrawerPopupDataAttributes.swipeDismiss, '');
2658
- return;
2659
- }
2660
- popupElement?.removeAttribute(DrawerPopupDataAttributes.swipeDismiss);
2661
- backdropElement?.removeAttribute(DrawerPopupDataAttributes.swipeDismiss);
2662
- }
2663
- function setBackdropSwipingAttribute(backdropElement, swiping) {
2664
- if (!backdropElement) {
2665
- return;
2666
- }
2667
- if (swiping) {
2668
- backdropElement.setAttribute(DrawerPopupDataAttributes.swiping, '');
2669
- return;
2670
- }
2671
- backdropElement.removeAttribute(DrawerPopupDataAttributes.swiping);
2672
- }
2673
- function isSwipeIgnoredTarget(target) {
2674
- return Boolean(target?.closest(BASE_UI_SWIPE_IGNORE_SELECTOR));
2675
- }
2676
- function isDrawerContentTarget(target) {
2677
- return Boolean(target?.closest(DRAWER_CONTENT_SELECTOR));
2678
- }
2679
- function getBaseSwipeThreshold(element, direction) {
2680
- const size = direction === 'left' || direction === 'right' ? element.offsetWidth : element.offsetHeight;
2681
- return Math.max(size * 0.5, MIN_SWIPE_THRESHOLD);
2682
- }
2683
- function isRangeInput(target, win) {
2684
- return target instanceof win.HTMLInputElement && target.type === 'range';
2685
- }
2686
- function isTextSelectionControl(target) {
2687
- if (!isElement(target)) {
2688
- return false;
2689
- }
2690
- return target.tagName === 'INPUT' || target.tagName === 'TEXTAREA';
2691
- }
2692
- function hasExpandedSelectionWithinTarget(selection, target) {
2693
- const anchorElement = isElement(selection.anchorNode) ? selection.anchorNode : selection.anchorNode?.parentElement;
2694
- const focusElement = isElement(selection.focusNode) ? selection.focusNode : selection.focusNode?.parentElement;
2695
- return selection.containsNode(target, true) || contains(target, anchorElement) || contains(target, focusElement);
2696
- }
2697
- function shouldIgnoreSwipeForTextSelection(doc, rootElement) {
2698
- const activeEl = activeElement(doc);
2699
- const activeElementWithinRoot = Boolean(activeEl && contains(rootElement, activeEl));
2700
- if (activeElementWithinRoot && isTextSelectionControl(activeEl)) {
2701
- const {
2702
- selectionStart,
2703
- selectionEnd
2704
- } = activeEl;
2705
- if (selectionStart != null && selectionEnd != null && selectionStart < selectionEnd) {
2706
- return true;
2707
- }
2708
- }
2709
- const selection = doc.getSelection?.();
2710
- if (!selection || selection.isCollapsed) {
2711
- return false;
2712
- }
2713
- return hasExpandedSelectionWithinTarget(selection, rootElement);
2714
- }
2715
- function isEventOnRangeInput(event, win) {
2716
- const composedPath = event.composedPath();
2717
- if (composedPath) {
2718
- return composedPath.some(pathTarget => isRangeInput(pathTarget, win));
2719
- }
2720
- return isRangeInput(getTarget(event), win);
2721
- }
2722
- function isReactTouchEventOnRangeInput(event) {
2723
- return isEventOnRangeInput(event.nativeEvent, getWindow(event.currentTarget));
2724
- }
2725
- function updateTouchScrollPosition(touchState, touch) {
2726
- touchState.lastX = touch.clientX;
2727
- touchState.lastY = touch.clientY;
2728
- }
2729
- function preserveNativeCrossAxisScrollOnMove(touchState, touch, isVerticalScrollAxis) {
2730
- if (touchState.preserveNativeCrossAxisScroll) {
2731
- return true;
2732
- }
2733
- if (touchState.allowSwipe === true || !touchState.hasCrossAxisScrollableContent) {
2734
- return false;
2735
- }
2736
- const drawerAxisGestureDelta = isVerticalScrollAxis ? touch.clientY - touchState.startY : touch.clientX - touchState.startX;
2737
- const crossAxisGestureDelta = isVerticalScrollAxis ? touch.clientX - touchState.startX : touch.clientY - touchState.startY;
2738
- const absDrawerAxisGestureDelta = Math.abs(drawerAxisGestureDelta);
2739
- const absCrossAxisGestureDelta = Math.abs(crossAxisGestureDelta);
2740
- if (absCrossAxisGestureDelta < 6 || absCrossAxisGestureDelta <= absDrawerAxisGestureDelta + 2) {
2741
- return false;
2742
- }
2743
- touchState.preserveNativeCrossAxisScroll = true;
2744
- return true;
2745
- }
2746
- function hasScrollableContentOnAxis(scrollTarget, axis) {
2747
- return axis === 'vertical' ? scrollTarget.scrollHeight > scrollTarget.clientHeight : scrollTarget.scrollWidth > scrollTarget.clientWidth;
2748
- }
2749
- function getScrollMetrics(scrollTarget, axis) {
2750
- if (axis === 'vertical') {
2751
- const max = Math.max(0, scrollTarget.scrollHeight - scrollTarget.clientHeight);
2752
- return {
2753
- offset: scrollTarget.scrollTop,
2754
- max
2755
- };
2756
- }
2757
- const max = Math.max(0, scrollTarget.scrollWidth - scrollTarget.clientWidth);
2758
- return {
2759
- offset: scrollTarget.scrollLeft,
2760
- max
2761
- };
2762
- }
2763
- function isAtSwipeStartEdge(scrollTarget, axis, direction) {
2764
- const {
2765
- offset,
2766
- max
2767
- } = getScrollMetrics(scrollTarget, axis);
2768
- const dismissFromStartEdge = shouldDismissFromStartEdge(direction, axis);
2769
- if (dismissFromStartEdge === null) {
2770
- return false;
2771
- }
2772
- return dismissFromStartEdge ? offset <= 0 : offset >= max;
2773
- }
2774
- function canSwipeFromScrollEdgeOnMove(scrollTarget, axis, direction, delta) {
2775
- const {
2776
- offset,
2777
- max
2778
- } = getScrollMetrics(scrollTarget, axis);
2779
- const dismissFromStartEdge = shouldDismissFromStartEdge(direction, axis);
2780
- if (dismissFromStartEdge === null) {
2781
- return false;
2782
- }
2783
- const movingTowardDismiss = dismissFromStartEdge ? delta > 0 : delta < 0;
2784
- if (!movingTowardDismiss) {
2785
- return false;
2786
- }
2787
- return dismissFromStartEdge ? offset <= 0 : offset >= max;
2788
- }
2789
- function shouldDismissFromStartEdge(direction, axis) {
2790
- if (axis === 'vertical') {
2791
- if (direction === 'down') {
2792
- return true;
2793
- }
2794
- if (direction === 'up') {
2795
- return false;
2796
- }
2797
- return null;
2798
- }
2799
- if (direction === 'right') {
2800
- return true;
2801
- }
2802
- if (direction === 'left') {
2803
- return false;
2804
- }
2805
- return null;
2806
- }
794
+ if (process.env.NODE_ENV !== "production") DrawerSwipeArea.displayName = "DrawerSwipeArea";
2807
795
 
2808
796
  let DrawerViewportCssVars = /*#__PURE__*/function (DrawerViewportCssVars) {
2809
797
  /**