feat: migrate AlertDialog and Drawer with reviewed overlay lifecycles
This commit is contained in:
@@ -0,0 +1,281 @@
|
||||
/**
|
||||
* Drawer drag-to-dismiss — thresholds match the fixed HeroUI baseline:
|
||||
* activate after 8px, dismiss at >30% dimension or >0.5px/ms velocity.
|
||||
* Drag originates from handle/header/footer; body is excluded to avoid scroll conflicts.
|
||||
*/
|
||||
import { nextTick, onBeforeUnmount, ref, watch, type Ref } from "vue";
|
||||
import type { DrawerPlacement } from "./context";
|
||||
|
||||
const DRAG_THRESHOLD = 8;
|
||||
const DISMISS_FRACTION = 0.3;
|
||||
const VELOCITY_THRESHOLD = 0.5;
|
||||
const SNAP_BACK_TRANSITION = "transform 300ms cubic-bezier(0.32, 0.72, 0, 1)";
|
||||
|
||||
type GesturePhase = "idle" | "dragging" | "dismissed";
|
||||
|
||||
function isDrawerDragTargetOwnedBy(
|
||||
target: HTMLElement,
|
||||
dialog: HTMLElement,
|
||||
): boolean {
|
||||
return target.closest('[data-slot="drawer-dialog"]') === dialog;
|
||||
}
|
||||
|
||||
export function useDrawerDrag(
|
||||
placement: Ref<DrawerPlacement>,
|
||||
isDismissable: Ref<boolean>,
|
||||
isOpen: Ref<boolean>,
|
||||
onDismiss: () => void,
|
||||
) {
|
||||
const dialogRef = ref<HTMLElement | null>(null);
|
||||
let phase: GesturePhase = "idle";
|
||||
let isActive = false;
|
||||
let activePointerId: number | null = null;
|
||||
let startPos = 0;
|
||||
let currentOffset = 0;
|
||||
let velocity = 0;
|
||||
let lastTime = 0;
|
||||
let lastPos = 0;
|
||||
|
||||
function isVertical() {
|
||||
return placement.value === "top" || placement.value === "bottom";
|
||||
}
|
||||
|
||||
function getPos(event: PointerEvent) {
|
||||
return isVertical() ? event.clientY : event.clientX;
|
||||
}
|
||||
|
||||
function clamp(delta: number) {
|
||||
switch (placement.value) {
|
||||
case "bottom":
|
||||
case "right":
|
||||
return Math.max(0, delta);
|
||||
case "top":
|
||||
case "left":
|
||||
return Math.min(0, delta);
|
||||
default:
|
||||
return delta;
|
||||
}
|
||||
}
|
||||
|
||||
function prefersReducedMotion() {
|
||||
return Boolean(
|
||||
dialogRef.value?.ownerDocument.defaultView?.matchMedia?.(
|
||||
"(prefers-reduced-motion: reduce)",
|
||||
).matches,
|
||||
);
|
||||
}
|
||||
|
||||
function clearStyles(el: HTMLElement | null) {
|
||||
if (!el) return;
|
||||
el.style.transform = "";
|
||||
el.style.transition = "";
|
||||
}
|
||||
|
||||
function snapBack(el: HTMLElement) {
|
||||
el.style.transition = prefersReducedMotion()
|
||||
? "none"
|
||||
: SNAP_BACK_TRANSITION;
|
||||
el.style.transform = "";
|
||||
const cleanup = () => {
|
||||
el.style.transition = "";
|
||||
};
|
||||
el.addEventListener("transitionend", cleanup, { once: true });
|
||||
}
|
||||
|
||||
function releaseCapture(pointerId: number | null, el = dialogRef.value) {
|
||||
if (pointerId === null) return;
|
||||
try {
|
||||
el?.releasePointerCapture(pointerId);
|
||||
} catch {
|
||||
// already released
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Cancel an in-flight gesture. When `preserveOffset` is true the inline
|
||||
* transform is kept so an accepted exit continues from the dragged position.
|
||||
*/
|
||||
function endGesture(
|
||||
options: { preserveOffset?: boolean } = {},
|
||||
el = dialogRef.value,
|
||||
) {
|
||||
const pointerId = activePointerId;
|
||||
phase = "idle";
|
||||
isActive = false;
|
||||
activePointerId = null;
|
||||
currentOffset = 0;
|
||||
velocity = 0;
|
||||
releaseCapture(pointerId, el);
|
||||
if (!options.preserveOffset) clearStyles(el);
|
||||
}
|
||||
|
||||
function onPointerDown(event: Event) {
|
||||
const pointerEvent = event as PointerEvent;
|
||||
if (pointerEvent.defaultPrevented) return;
|
||||
// Do not start gestures on a closing / closed panel.
|
||||
if (!isDismissable.value || !isOpen.value) return;
|
||||
if (pointerEvent.button !== 0) return;
|
||||
if (phase !== "idle" || activePointerId !== null) return;
|
||||
const target = pointerEvent.target as HTMLElement;
|
||||
const currentTarget = pointerEvent.currentTarget as HTMLElement;
|
||||
if (!target || !currentTarget) return;
|
||||
if (!isDrawerDragTargetOwnedBy(target, currentTarget)) return;
|
||||
if (
|
||||
target.closest(
|
||||
"input, textarea, button, [role='button'], select, a, [data-slot='drawer-body']",
|
||||
)
|
||||
) {
|
||||
return;
|
||||
}
|
||||
phase = "dragging";
|
||||
isActive = false;
|
||||
activePointerId = pointerEvent.pointerId;
|
||||
startPos = getPos(pointerEvent);
|
||||
lastPos = startPos;
|
||||
lastTime = Date.now();
|
||||
currentOffset = 0;
|
||||
velocity = 0;
|
||||
}
|
||||
|
||||
function onPointerMove(event: Event) {
|
||||
const pointerEvent = event as PointerEvent;
|
||||
if (phase !== "dragging" || !dialogRef.value) return;
|
||||
if (pointerEvent.pointerId !== activePointerId) return;
|
||||
// A retained exit node must not keep accepting drag updates.
|
||||
if (!isOpen.value) return;
|
||||
const pos = getPos(pointerEvent);
|
||||
const rawDelta = pos - startPos;
|
||||
const delta = clamp(rawDelta);
|
||||
if (!isActive) {
|
||||
if (Math.abs(rawDelta) < DRAG_THRESHOLD) return;
|
||||
isActive = true;
|
||||
dialogRef.value.style.transition = "none";
|
||||
try {
|
||||
dialogRef.value.setPointerCapture(pointerEvent.pointerId);
|
||||
} catch {
|
||||
// jsdom / browsers may already have released capture
|
||||
}
|
||||
}
|
||||
currentOffset = delta;
|
||||
const now = Date.now();
|
||||
const dt = now - lastTime;
|
||||
if (dt > 0) {
|
||||
velocity = (pos - lastPos) / dt;
|
||||
lastTime = now;
|
||||
lastPos = pos;
|
||||
}
|
||||
const axis = isVertical() ? "Y" : "X";
|
||||
dialogRef.value.style.transform = `translate${axis}(${delta}px)`;
|
||||
}
|
||||
|
||||
function onPointerUp(event: Event) {
|
||||
const pointerEvent = event as PointerEvent;
|
||||
if (phase !== "dragging" || pointerEvent.pointerId !== activePointerId) {
|
||||
return;
|
||||
}
|
||||
const el = dialogRef.value;
|
||||
const wasActive = isActive;
|
||||
const pointerId = activePointerId;
|
||||
phase = "idle";
|
||||
isActive = false;
|
||||
activePointerId = null;
|
||||
if (!el || !wasActive) {
|
||||
currentOffset = 0;
|
||||
velocity = 0;
|
||||
releaseCapture(pointerId);
|
||||
return;
|
||||
}
|
||||
releaseCapture(pointerId);
|
||||
const dimension = isVertical() ? el.offsetHeight : el.offsetWidth;
|
||||
const absOffset = Math.abs(currentOffset);
|
||||
const absVelocity = Math.abs(velocity);
|
||||
const shouldDismiss =
|
||||
absOffset > dimension * DISMISS_FRACTION ||
|
||||
absVelocity > VELOCITY_THRESHOLD;
|
||||
if (shouldDismiss) {
|
||||
// Keep the inline transform so exit continues from the dragged position.
|
||||
// Mark dismissed so a later lostpointercapture does not clear the offset.
|
||||
phase = "dismissed";
|
||||
onDismiss();
|
||||
void nextTick(() => {
|
||||
if (isOpen.value && dialogRef.value === el) {
|
||||
// Controlled parent rejected the close request — restore the panel.
|
||||
phase = "idle";
|
||||
snapBack(el);
|
||||
} else {
|
||||
phase = "idle";
|
||||
}
|
||||
});
|
||||
} else {
|
||||
snapBack(el);
|
||||
}
|
||||
currentOffset = 0;
|
||||
velocity = 0;
|
||||
}
|
||||
|
||||
function onPointerCancel(event: Event) {
|
||||
const pointerEvent = event as PointerEvent;
|
||||
// A normal capture release after an accepted dismiss must not jump the
|
||||
// panel back — only cancel gestures that are still in flight.
|
||||
if (phase === "dismissed") return;
|
||||
if (phase !== "dragging") return;
|
||||
if (
|
||||
activePointerId !== null &&
|
||||
pointerEvent.pointerId !== undefined &&
|
||||
pointerEvent.pointerId !== activePointerId
|
||||
) {
|
||||
return;
|
||||
}
|
||||
endGesture();
|
||||
}
|
||||
|
||||
function bind(el: HTMLElement | null) {
|
||||
el?.addEventListener("pointerdown", onPointerDown);
|
||||
el?.addEventListener("pointermove", onPointerMove);
|
||||
el?.addEventListener("pointerup", onPointerUp);
|
||||
el?.addEventListener("pointercancel", onPointerCancel);
|
||||
el?.addEventListener("lostpointercapture", onPointerCancel);
|
||||
}
|
||||
|
||||
function unbind(el: HTMLElement | null) {
|
||||
el?.removeEventListener("pointerdown", onPointerDown);
|
||||
el?.removeEventListener("pointermove", onPointerMove);
|
||||
el?.removeEventListener("pointerup", onPointerUp);
|
||||
el?.removeEventListener("pointercancel", onPointerCancel);
|
||||
el?.removeEventListener("lostpointercapture", onPointerCancel);
|
||||
}
|
||||
|
||||
// Config changes mid-gesture cancel it; an accepted programmatic close
|
||||
// stops further updates but keeps whatever offset is already applied.
|
||||
watch([isDismissable, placement], () => {
|
||||
if (phase === "dragging") endGesture();
|
||||
});
|
||||
|
||||
watch(isOpen, (open) => {
|
||||
if (open) {
|
||||
// Presence may reuse the exiting node on a quick reopen.
|
||||
endGesture();
|
||||
} else if (phase === "dragging") {
|
||||
// Programmatic close during a drag: stop the gesture without jumping.
|
||||
endGesture({ preserveOffset: true });
|
||||
}
|
||||
});
|
||||
|
||||
watch(dialogRef, (el, prev) => {
|
||||
if (prev) {
|
||||
// Clean up the previous node (capture + any in-flight style).
|
||||
endGesture({}, prev);
|
||||
unbind(prev);
|
||||
}
|
||||
bind(el);
|
||||
});
|
||||
|
||||
onBeforeUnmount(() => {
|
||||
endGesture();
|
||||
unbind(dialogRef.value);
|
||||
});
|
||||
|
||||
return {
|
||||
dialogRef,
|
||||
};
|
||||
}
|
||||
Reference in New Issue
Block a user