@kumix/ui 0.4.1 → 0.4.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.
- package/README.md +37 -30
- package/dist/{cascader-types-DVT-znZ-.d.ts → cascader-types-zhnUQ4sP.d.ts} +11 -3
- package/dist/cascader-types-zhnUQ4sP.d.ts.map +1 -0
- package/dist/components/agents/agent-code.js +1 -1
- package/dist/components/charts/candlestick-chart/context.d.ts.map +1 -1
- package/dist/components/charts/donut-chart/context.d.ts.map +1 -1
- package/dist/components/charts/liquidity-heatmap.d.ts.map +1 -1
- package/dist/components/charts/order-book.d.ts.map +1 -1
- package/dist/components/charts/treemap.d.ts.map +1 -1
- package/dist/components/charts/volume-profile.d.ts.map +1 -1
- package/dist/components/motion/action-swap.d.ts +1 -1
- package/dist/components/motion/action-swap.d.ts.map +1 -1
- package/dist/components/motion/action-swap.js +43 -20
- package/dist/components/motion/action-swap.js.map +1 -1
- package/dist/components/motion/animated-badge.d.ts +1 -1
- package/dist/components/motion/animated-badge.d.ts.map +1 -1
- package/dist/components/motion/animated-badge.js +60 -101
- package/dist/components/motion/animated-badge.js.map +1 -1
- package/dist/components/motion/animated-sidebar.js +1 -1
- package/dist/components/motion/animated-toast-stack.js +1 -1
- package/dist/components/motion/attachment-upload.js +1 -1
- package/dist/components/motion/availability-scheduler/copy-menu.js +1 -1
- package/dist/components/motion/availability-scheduler/day-row.js +1 -1
- package/dist/components/motion/availability-scheduler/index.js +1 -1
- package/dist/components/motion/bloom-menu.d.ts.map +1 -1
- package/dist/components/motion/bloom-menu.js +73 -8
- package/dist/components/motion/bloom-menu.js.map +1 -1
- package/dist/components/motion/bottom-sheet.d.ts.map +1 -1
- package/dist/components/motion/bottom-sheet.js +6 -10
- package/dist/components/motion/bottom-sheet.js.map +1 -1
- package/dist/components/motion/bouncy-accordion.d.ts.map +1 -1
- package/dist/components/motion/bouncy-accordion.js +35 -22
- package/dist/components/motion/bouncy-accordion.js.map +1 -1
- package/dist/components/motion/center-morph-modal.js +1 -1
- package/dist/components/motion/color-picker.d.ts.map +1 -1
- package/dist/components/motion/command-palette.js +1 -1
- package/dist/components/motion/context-menu.js +1 -1
- package/dist/components/motion/date-range-picker.d.ts.map +1 -1
- package/dist/components/motion/drawer.d.ts +1 -1
- package/dist/components/motion/drawer.d.ts.map +1 -1
- package/dist/components/motion/drawer.js +10 -10
- package/dist/components/motion/drawer.js.map +1 -1
- package/dist/components/motion/expandable-action-bar.d.ts.map +1 -1
- package/dist/components/motion/feedback-widget.js +4 -1
- package/dist/components/motion/feedback-widget.js.map +1 -1
- package/dist/components/motion/morphing-lightbox.d.ts.map +1 -1
- package/dist/components/motion/morphing-lightbox.js +1 -1
- package/dist/components/motion/morphing-modal.d.ts +6 -1
- package/dist/components/motion/morphing-modal.d.ts.map +1 -1
- package/dist/components/motion/morphing-modal.js +37 -5
- package/dist/components/motion/morphing-modal.js.map +1 -1
- package/dist/components/motion/morphing-search.js +1 -1
- package/dist/components/motion/morphing-tabs.js +1 -1
- package/dist/components/motion/otp-input.js +19 -11
- package/dist/components/motion/otp-input.js.map +1 -1
- package/dist/components/motion/popover-morph.d.ts +4 -3
- package/dist/components/motion/popover-morph.d.ts.map +1 -1
- package/dist/components/motion/popover-morph.js +47 -55
- package/dist/components/motion/popover-morph.js.map +1 -1
- package/dist/components/motion/popover.js +7 -1
- package/dist/components/motion/popover.js.map +1 -1
- package/dist/components/motion/prediction-market-card.js +1 -1
- package/dist/components/motion/prediction-market.js +1 -1
- package/dist/components/motion/project-folder.js +1 -1
- package/dist/components/motion/radio.d.ts +5 -1
- package/dist/components/motion/radio.d.ts.map +1 -1
- package/dist/components/motion/radio.js +53 -5
- package/dist/components/motion/radio.js.map +1 -1
- package/dist/components/motion/select-morph.d.ts +1 -1
- package/dist/components/motion/select-morph.d.ts.map +1 -1
- package/dist/components/motion/select-morph.js +89 -21
- package/dist/components/motion/select-morph.js.map +1 -1
- package/dist/components/motion/select.d.ts.map +1 -1
- package/dist/components/motion/select.js +153 -135
- package/dist/components/motion/select.js.map +1 -1
- package/dist/components/motion/shader-background.d.ts +3 -2
- package/dist/components/motion/shader-background.d.ts.map +1 -1
- package/dist/components/motion/shader-background.js +9 -3
- package/dist/components/motion/shader-background.js.map +1 -1
- package/dist/components/motion/shared-layout-bg.d.ts.map +1 -1
- package/dist/components/motion/shared-layout-bg.js +17 -3
- package/dist/components/motion/shared-layout-bg.js.map +1 -1
- package/dist/components/motion/swipeable-list.d.ts.map +1 -1
- package/dist/components/motion/swipeable-list.js +61 -4
- package/dist/components/motion/swipeable-list.js.map +1 -1
- package/dist/components/motion/table/row-handle.js +1 -1
- package/dist/components/motion/table/table-header.js +1 -1
- package/dist/components/motion/tabs.d.ts +12 -3
- package/dist/components/motion/tabs.d.ts.map +1 -1
- package/dist/components/motion/tabs.js +248 -26
- package/dist/components/motion/tabs.js.map +1 -1
- package/dist/components/motion/theme-toggle.js +1 -1
- package/dist/components/reui/alert.d.ts +1 -1
- package/dist/components/reui/autocomplete.d.ts +1 -1
- package/dist/components/reui/autocomplete.d.ts.map +1 -1
- package/dist/components/reui/autocomplete.js +1 -1
- package/dist/components/reui/autocomplete.js.map +1 -1
- package/dist/components/reui/badge.d.ts +2 -2
- package/dist/components/reui/cascader/cascader-async.d.ts +21 -5
- package/dist/components/reui/cascader/cascader-async.d.ts.map +1 -1
- package/dist/components/reui/cascader/cascader-async.js +61 -34
- package/dist/components/reui/cascader/cascader-async.js.map +1 -1
- package/dist/components/reui/cascader/cascader-columns.d.ts.map +1 -1
- package/dist/components/reui/cascader/cascader-columns.js +5 -2
- package/dist/components/reui/cascader/cascader-columns.js.map +1 -1
- package/dist/components/reui/cascader/cascader-context.d.ts +3 -1
- package/dist/components/reui/cascader/cascader-context.d.ts.map +1 -1
- package/dist/components/reui/cascader/cascader-context.js.map +1 -1
- package/dist/components/reui/cascader/cascader-i18n.d.ts +1 -1
- package/dist/components/reui/cascader/cascader-item.d.ts +1 -1
- package/dist/components/reui/cascader/cascader-lib.d.ts +34 -8
- package/dist/components/reui/cascader/cascader-lib.d.ts.map +1 -1
- package/dist/components/reui/cascader/cascader-lib.js +145 -29
- package/dist/components/reui/cascader/cascader-lib.js.map +1 -1
- package/dist/components/reui/cascader/cascader-nav.d.ts +1 -1
- package/dist/components/reui/cascader/cascader-types.d.ts +1 -1
- package/dist/components/reui/cascader/cascader.d.ts +13 -8
- package/dist/components/reui/cascader/cascader.d.ts.map +1 -1
- package/dist/components/reui/cascader/cascader.js +31 -16
- package/dist/components/reui/cascader/cascader.js.map +1 -1
- package/dist/components/reui/code-block/code-block.d.ts.map +1 -1
- package/dist/components/reui/color-picker.js +1 -1
- package/dist/components/reui/data-grid/data-grid-cell-selection.d.ts.map +1 -1
- package/dist/components/reui/data-grid/data-grid-cell-selection.js +1 -0
- package/dist/components/reui/data-grid/data-grid-cell-selection.js.map +1 -1
- package/dist/components/reui/data-grid/data-grid-column-filter.d.ts.map +1 -1
- package/dist/components/reui/data-grid/data-grid-column-filter.js +1 -0
- package/dist/components/reui/data-grid/data-grid-column-filter.js.map +1 -1
- package/dist/components/reui/data-grid/data-grid-column-header.d.ts +6 -8
- package/dist/components/reui/data-grid/data-grid-column-header.d.ts.map +1 -1
- package/dist/components/reui/data-grid/data-grid-column-header.js +7 -8
- package/dist/components/reui/data-grid/data-grid-column-header.js.map +1 -1
- package/dist/components/reui/data-grid/data-grid-column-visibility.d.ts.map +1 -1
- package/dist/components/reui/data-grid/data-grid-column-visibility.js +1 -0
- package/dist/components/reui/data-grid/data-grid-column-visibility.js.map +1 -1
- package/dist/components/reui/data-grid/data-grid-pagination.d.ts.map +1 -1
- package/dist/components/reui/data-grid/data-grid-pagination.js +1 -0
- package/dist/components/reui/data-grid/data-grid-pagination.js.map +1 -1
- package/dist/components/reui/data-grid/data-grid-scroll-area.d.ts.map +1 -1
- package/dist/components/reui/data-grid/data-grid-scroll-area.js +1 -0
- package/dist/components/reui/data-grid/data-grid-scroll-area.js.map +1 -1
- package/dist/components/reui/data-grid/data-grid-table-dnd-rows.d.ts.map +1 -1
- package/dist/components/reui/data-grid/data-grid-table-dnd-rows.js +3 -2
- package/dist/components/reui/data-grid/data-grid-table-dnd-rows.js.map +1 -1
- package/dist/components/reui/data-grid/data-grid-table-dnd.d.ts.map +1 -1
- package/dist/components/reui/data-grid/data-grid-table-dnd.js +2 -1
- package/dist/components/reui/data-grid/data-grid-table-dnd.js.map +1 -1
- package/dist/components/reui/data-grid/data-grid-table-virtual.d.ts.map +1 -1
- package/dist/components/reui/data-grid/data-grid-table-virtual.js +2 -1
- package/dist/components/reui/data-grid/data-grid-table-virtual.js.map +1 -1
- package/dist/components/reui/data-grid/data-grid-table.d.ts +6 -11
- package/dist/components/reui/data-grid/data-grid-table.d.ts.map +1 -1
- package/dist/components/reui/data-grid/data-grid-table.js +22 -22
- package/dist/components/reui/data-grid/data-grid-table.js.map +1 -1
- package/dist/components/reui/data-grid/data-grid.d.ts +16 -1
- package/dist/components/reui/data-grid/data-grid.d.ts.map +1 -1
- package/dist/components/reui/data-grid/data-grid.js +80 -22
- package/dist/components/reui/data-grid/data-grid.js.map +1 -1
- package/dist/components/reui/date-selector.d.ts.map +1 -1
- package/dist/components/reui/date-selector.js +21 -15
- package/dist/components/reui/date-selector.js.map +1 -1
- package/dist/components/reui/event-calendar/event-calendar-agenda-view.js +3 -5
- package/dist/components/reui/event-calendar/event-calendar-agenda-view.js.map +1 -1
- package/dist/components/reui/event-calendar/event-calendar-nav.d.ts.map +1 -1
- package/dist/components/reui/event-calendar/event-calendar-nav.js +2 -2
- package/dist/components/reui/event-calendar/event-calendar-nav.js.map +1 -1
- package/dist/components/reui/event-calendar/event-calendar.d.ts.map +1 -1
- package/dist/components/reui/event-calendar/event-calendar.js +34 -31
- package/dist/components/reui/event-calendar/event-calendar.js.map +1 -1
- package/dist/components/reui/file-type.d.ts +302 -6
- package/dist/components/reui/file-type.d.ts.map +1 -1
- package/dist/components/reui/file-type.js +416 -13
- package/dist/components/reui/file-type.js.map +1 -1
- package/dist/components/reui/filters/filters-builder.d.ts +1 -1
- package/dist/components/reui/filters/filters-lib.d.ts +1 -1
- package/dist/components/reui/frame.d.ts +1 -1
- package/dist/components/reui/gantt/gantt-nav.d.ts.map +1 -1
- package/dist/components/reui/gantt/gantt-nav.js +2 -2
- package/dist/components/reui/gantt/gantt-nav.js.map +1 -1
- package/dist/components/reui/gantt/gantt.d.ts.map +1 -1
- package/dist/components/reui/gantt/gantt.js +5 -2
- package/dist/components/reui/gantt/gantt.js.map +1 -1
- package/dist/components/reui/icon-tile.d.ts +2 -2
- package/dist/components/reui/number-field.d.ts +3 -3
- package/dist/components/reui/phone-input.js +30 -27
- package/dist/components/reui/phone-input.js.map +1 -1
- package/dist/components/reui/rating.d.ts +1 -1
- package/dist/components/reui/time-picker.js +1 -1
- package/dist/components/ui/attachment.d.ts +2 -2
- package/dist/components/ui/badge.d.ts +1 -1
- package/dist/components/ui/bubble.d.ts +1 -1
- package/dist/components/ui/button.d.ts +2 -2
- package/dist/components/ui/chart.d.ts.map +1 -1
- package/dist/components/ui/code-block.d.ts +29 -0
- package/dist/components/ui/code-block.d.ts.map +1 -0
- package/dist/components/ui/code-block.js +124 -0
- package/dist/components/ui/code-block.js.map +1 -0
- package/dist/components/ui/empty.d.ts +1 -1
- package/dist/components/ui/item.d.ts +2 -2
- package/dist/components/ui/marker.d.ts +1 -1
- package/dist/components/ui/sidebar.d.ts +1 -1
- package/dist/components/ui/toggle.d.ts +1 -1
- package/dist/components/ui/trace.d.ts +21 -0
- package/dist/components/ui/trace.d.ts.map +1 -0
- package/dist/components/ui/trace.js +77 -0
- package/dist/components/ui/trace.js.map +1 -0
- package/dist/context-BYXeJQnz.d.ts.map +1 -1
- package/dist/{copy-menu-BXUh52bu.js → copy-menu-DOg9Jh-U.js} +2 -2
- package/dist/{copy-menu-BXUh52bu.js.map → copy-menu-DOg9Jh-U.js.map} +1 -1
- package/dist/hooks/use-focus-trap.d.ts +22 -0
- package/dist/hooks/use-focus-trap.d.ts.map +1 -0
- package/dist/hooks/use-focus-trap.js +80 -0
- package/dist/hooks/use-focus-trap.js.map +1 -0
- package/dist/hooks/use-highlighted-code.d.ts +5 -0
- package/dist/hooks/use-highlighted-code.d.ts.map +1 -0
- package/dist/hooks/use-highlighted-code.js +128 -0
- package/dist/hooks/use-highlighted-code.js.map +1 -0
- package/dist/hooks/use-listbox.d.ts +29 -0
- package/dist/hooks/use-listbox.d.ts.map +1 -0
- package/dist/hooks/use-listbox.js +75 -0
- package/dist/hooks/use-listbox.js.map +1 -0
- package/dist/tooltip-C01qUgsW.d.ts.map +1 -1
- package/package.json +8 -8
- package/dist/cascader-types-DVT-znZ-.d.ts.map +0 -1
|
@@ -7,8 +7,13 @@ export interface MorphingModalProps {
|
|
|
7
7
|
children: ReactNode;
|
|
8
8
|
/** "bottom" anchors to the viewport bottom (mobile-like). "center" centers vertically. */
|
|
9
9
|
placement?: "bottom" | "center";
|
|
10
|
+
/**
|
|
11
|
+
* Accessible name for the dialog. Without it, the dialog is named by the
|
|
12
|
+
* first heading in the current view.
|
|
13
|
+
*/
|
|
14
|
+
ariaLabel?: string;
|
|
10
15
|
className?: string;
|
|
11
16
|
}
|
|
12
|
-
export declare function MorphingModal({ viewId, onClose, children, placement, className }: MorphingModalProps): import("react").JSX.Element;
|
|
17
|
+
export declare function MorphingModal({ viewId, onClose, children, placement, ariaLabel, className }: MorphingModalProps): import("react").JSX.Element;
|
|
13
18
|
//#endregion
|
|
14
19
|
//# sourceMappingURL=morphing-modal.d.ts.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"morphing-modal.d.ts","names":[],"sources":["../../../src/components/motion/morphing-modal.tsx"],"mappings":";;
|
|
1
|
+
{"version":3,"file":"morphing-modal.d.ts","names":[],"sources":["../../../src/components/motion/morphing-modal.tsx"],"mappings":";;iBAUiB;;EAEf;EACA;EACA,UAAU;;EAEV;;;;;EAKA;EACA;;wBAGc,gBACd,QACA,SACA,UACA,WACA,WACA,aACC,qCAAkB,IAAA"}
|
|
@@ -1,14 +1,37 @@
|
|
|
1
1
|
"use client";
|
|
2
|
+
import { focusablesIn, useFocusTrap } from "../../hooks/use-focus-trap.js";
|
|
2
3
|
import { EASE_OUT, SPRING_PANEL } from "../../lib/ease.js";
|
|
3
4
|
import { t as PresenceGate } from "../../presence-gate-BekdC4Bo.js";
|
|
4
|
-
import { useEffect } from "react";
|
|
5
|
+
import { useEffect, useId, useLayoutEffect, useRef, useState } from "react";
|
|
5
6
|
import { cn } from "@kumix/utils";
|
|
6
7
|
import { jsx, jsxs } from "react/jsx-runtime";
|
|
7
8
|
import { AnimatePresence, motion, useReducedMotion } from "motion/react";
|
|
8
9
|
//#region src/components/motion/morphing-modal.tsx
|
|
9
|
-
function MorphingModal({ viewId, onClose, children, placement = "bottom", className }) {
|
|
10
|
+
function MorphingModal({ viewId, onClose, children, placement = "bottom", ariaLabel, className }) {
|
|
10
11
|
const open = viewId !== null;
|
|
11
12
|
const reduce = useReducedMotion();
|
|
13
|
+
const panelRef = useRef(null);
|
|
14
|
+
const uid = useId();
|
|
15
|
+
const [headingId, setHeadingId] = useState();
|
|
16
|
+
useFocusTrap(open, panelRef, { onEscape: onClose });
|
|
17
|
+
const currentView = () => Array.from(panelRef.current?.querySelectorAll("[data-view]") ?? []).find((element) => element.dataset.view === viewId);
|
|
18
|
+
useLayoutEffect(() => {
|
|
19
|
+
if (!viewId || ariaLabel) return;
|
|
20
|
+
const heading = currentView()?.querySelector("h1, h2, h3, h4, h5, h6");
|
|
21
|
+
if (heading && !heading.id) heading.id = `${uid}-${viewId}-title`;
|
|
22
|
+
setHeadingId(heading?.id);
|
|
23
|
+
});
|
|
24
|
+
const shownView = useRef(viewId);
|
|
25
|
+
useEffect(() => {
|
|
26
|
+
const previous = shownView.current;
|
|
27
|
+
shownView.current = viewId;
|
|
28
|
+
if (!viewId || !previous || previous === viewId) return;
|
|
29
|
+
const panel = panelRef.current;
|
|
30
|
+
const active = document.activeElement;
|
|
31
|
+
if (!panel || active && active !== document.body && !panel.contains(active)) return;
|
|
32
|
+
const view = currentView();
|
|
33
|
+
(focusablesIn(view ?? null)[0] ?? panel).focus({ preventScroll: true });
|
|
34
|
+
});
|
|
12
35
|
const enterY = reduce ? 0 : placement === "bottom" ? 40 : 20;
|
|
13
36
|
const enterScale = reduce ? 1 : .97;
|
|
14
37
|
useEffect(() => {
|
|
@@ -24,6 +47,7 @@ function MorphingModal({ viewId, onClose, children, placement = "bottom", classN
|
|
|
24
47
|
children: [open ? /* @__PURE__ */ jsx(PresenceGate, { children: ({ gate }) => /* @__PURE__ */ jsx(motion.button, {
|
|
25
48
|
type: "button",
|
|
26
49
|
"aria-label": "Close modal",
|
|
50
|
+
tabIndex: -1,
|
|
27
51
|
initial: { opacity: 0 },
|
|
28
52
|
animate: { opacity: 1 },
|
|
29
53
|
exit: { opacity: 0 },
|
|
@@ -38,6 +62,12 @@ function MorphingModal({ viewId, onClose, children, placement = "bottom", classN
|
|
|
38
62
|
inert: !isPresent,
|
|
39
63
|
className: cn("pointer-events-none fixed inset-4 z-80 flex justify-center", placement === "bottom" ? "items-end pb-4" : "items-center"),
|
|
40
64
|
children: /* @__PURE__ */ jsx(motion.div, {
|
|
65
|
+
ref: panelRef,
|
|
66
|
+
role: "dialog",
|
|
67
|
+
"aria-modal": "true",
|
|
68
|
+
"aria-label": ariaLabel,
|
|
69
|
+
"aria-labelledby": ariaLabel ? void 0 : headingId,
|
|
70
|
+
tabIndex: -1,
|
|
41
71
|
layout: true,
|
|
42
72
|
initial: {
|
|
43
73
|
opacity: 0,
|
|
@@ -60,14 +90,16 @@ function MorphingModal({ viewId, onClose, children, placement = "bottom", classN
|
|
|
60
90
|
},
|
|
61
91
|
transition: SPRING_PANEL,
|
|
62
92
|
...gate,
|
|
63
|
-
className: cn("pointer-events-auto relative w-full max-w-sm overflow-hidden rounded-3xl border border-border bg-background shadow-2xl will-change-transform", className),
|
|
93
|
+
className: cn("pointer-events-auto relative w-full max-w-sm overflow-hidden rounded-3xl border border-border bg-background shadow-2xl outline-none will-change-transform", className),
|
|
64
94
|
children: /* @__PURE__ */ jsx(motion.div, {
|
|
65
95
|
layout: "position",
|
|
66
96
|
className: "p-5",
|
|
67
97
|
children: /* @__PURE__ */ jsx(AnimatePresence, {
|
|
68
98
|
mode: "popLayout",
|
|
69
99
|
initial: false,
|
|
70
|
-
children: /* @__PURE__ */ jsx(motion.div, {
|
|
100
|
+
children: /* @__PURE__ */ jsx(PresenceGate, { children: ({ isPresent: viewPresent }) => /* @__PURE__ */ jsx(motion.div, {
|
|
101
|
+
inert: !viewPresent,
|
|
102
|
+
"data-view": viewId,
|
|
71
103
|
initial: reduce ? { opacity: 0 } : {
|
|
72
104
|
opacity: 0,
|
|
73
105
|
y: 8,
|
|
@@ -104,7 +136,7 @@ function MorphingModal({ viewId, onClose, children, placement = "bottom", classN
|
|
|
104
136
|
}
|
|
105
137
|
},
|
|
106
138
|
children
|
|
107
|
-
}, viewId)
|
|
139
|
+
}) }, viewId)
|
|
108
140
|
})
|
|
109
141
|
})
|
|
110
142
|
}, "panel")
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"morphing-modal.js","names":[],"sources":["../../../src/components/motion/morphing-modal.tsx"],"sourcesContent":["\"use client\";\n\nimport { type ReactNode, useEffect } from \"react\";\nimport { AnimatePresence, motion, useReducedMotion } from \"motion/react\";\n\nimport { cn } from \"@kumix/utils\";\nimport { EASE_OUT, SPRING_PANEL } from \"../../lib/ease\";\nimport { PresenceGate } from \"../../lib/presence-gate\";\n\nexport interface MorphingModalProps {\n /** Which view is currently shown. `null` closes the modal. */\n viewId: string | null;\n onClose: () => void;\n children: ReactNode;\n /** \"bottom\" anchors to the viewport bottom (mobile-like). \"center\" centers vertically. */\n placement?: \"bottom\" | \"center\";\n className?: string;\n}\n\nexport function MorphingModal({\n viewId,\n onClose,\n children,\n placement = \"bottom\",\n className,\n}: MorphingModalProps) {\n const open = viewId !== null;\n const reduce = useReducedMotion();\n const enterY = reduce ? 0 : placement === \"bottom\" ? 40 : 20;\n const enterScale = reduce ? 1 : 0.97;\n\n useEffect(() => {\n if (!open) return;\n const prev = document.body.style.overflow;\n document.body.style.overflow = \"hidden\";\n return () => {\n document.body.style.overflow = prev;\n };\n }, [open]);\n\n // Mounted only while open, and while open the chrome is two fixed siblings\n // rather than one wrapper: the backdrop spans the viewport edges but carries\n // the scrim colour, and the layer positioning the panel sits inset off every\n // edge (`inset-4`, with the bottom placement's `pb-4` on top of it). Both hang\n // off `PresenceGate`, so interaction releases in the same commit that starts\n // the exit rather than when it ends — `open` is already false for those\n // frames.\n return (\n <AnimatePresence initial={false}>\n {open ? (\n <PresenceGate key=\"backdrop\">\n {({ gate }) => (\n <motion.button\n type=\"button\"\n aria-label=\"Close modal\"\n initial={{ opacity: 0 }}\n animate={{ opacity: 1 }}\n exit={{ opacity: 0 }}\n transition={{ duration: 0.2, ease: EASE_OUT }}\n {...gate}\n onClick={onClose}\n className=\"pointer-events-auto fixed inset-0 z-80 bg-background/5 [-webkit-backdrop-filter:blur(14px)_saturate(140%)] [backdrop-filter:blur(14px)_saturate(140%)]\"\n />\n )}\n </PresenceGate>\n ) : null}\n\n {open ? (\n <PresenceGate key=\"panel-layer\">\n {({ isPresent, gate }) => (\n // The layer itself never takes pointer events, so it carries\n // `inert` alone rather than the gate's pointer-events value.\n <div\n inert={!isPresent}\n className={cn(\n \"pointer-events-none fixed inset-4 z-80 flex justify-center\",\n placement === \"bottom\" ? \"items-end pb-4\" : \"items-center\",\n )}\n >\n <motion.div\n key=\"panel\"\n layout\n initial={{ opacity: 0, y: enterY, scale: enterScale }}\n animate={{ opacity: 1, y: 0, scale: 1 }}\n exit={{\n opacity: 0,\n y: enterY,\n scale: reduce ? 1 : 0.98,\n transition: { duration: 0.18, ease: EASE_OUT },\n }}\n transition={SPRING_PANEL}\n {...gate}\n className={cn(\n \"pointer-events-auto relative w-full max-w-sm overflow-hidden rounded-3xl border border-border bg-background shadow-2xl will-change-transform\",\n className,\n )}\n >\n <motion.div layout=\"position\" className=\"p-5\">\n <AnimatePresence mode=\"popLayout\" initial={false}>\n <motion.div\n key={viewId}\n initial={reduce ? { opacity: 0 } : { opacity: 0, y: 8, filter: \"blur(4px)\" }}\n animate={\n reduce\n ? {\n opacity: 1,\n transition: {\n duration: 0.18,\n ease: EASE_OUT,\n },\n }\n : {\n opacity: 1,\n y: 0,\n filter: \"blur(0px)\",\n transition: {\n duration: 0.24,\n ease: EASE_OUT,\n },\n }\n }\n exit={\n reduce\n ? {\n opacity: 0,\n transition: {\n duration: 0.14,\n ease: EASE_OUT,\n },\n }\n : {\n opacity: 0,\n y: -8,\n filter: \"blur(4px)\",\n transition: {\n duration: 0.16,\n ease: EASE_OUT,\n },\n }\n }\n >\n {children}\n </motion.div>\n </AnimatePresence>\n </motion.div>\n </motion.div>\n </div>\n )}\n </PresenceGate>\n ) : null}\n </AnimatePresence>\n );\n}\n"],"mappings":";;;;;;;;AAmBA,SAAgB,cAAc,EAC5B,QACA,SACA,UACA,YAAY,UACZ,aACqB;CACrB,MAAM,OAAO,WAAW;CACxB,MAAM,SAAS,iBAAiB;CAChC,MAAM,SAAS,SAAS,IAAI,cAAc,WAAW,KAAK;CAC1D,MAAM,aAAa,SAAS,IAAI;CAEhC,gBAAgB;EACd,IAAI,CAAC,MAAM;EACX,MAAM,OAAO,SAAS,KAAK,MAAM;EACjC,SAAS,KAAK,MAAM,WAAW;EAC/B,aAAa;GACX,SAAS,KAAK,MAAM,WAAW;EACjC;CACF,GAAG,CAAC,IAAI,CAAC;CAST,OACE,qBAAC,iBAAD;EAAiB,SAAS;EAA1B,UAAA,CACG,OACC,oBAAC,cAAD,EAAA,WACI,EAAE,WACF,oBAAC,OAAO,QAAR;GACE,MAAK;GACL,cAAW;GACX,SAAS,EAAE,SAAS,EAAE;GACtB,SAAS,EAAE,SAAS,EAAE;GACtB,MAAM,EAAE,SAAS,EAAE;GACnB,YAAY;IAAE,UAAU;IAAK,MAAM;GAAS;GAC5C,GAAI;GACJ,SAAS;GACT,WAAU;EACX,CAAA,EAES,GAdI,UAcJ,IACZ,MAEH,OACC,oBAAC,cAAD,EAAA,WACI,EAAE,WAAW,WAGb,oBAAC,OAAD;GACE,OAAO,CAAC;GACR,WAAW,GACT,8DACA,cAAc,WAAW,mBAAmB,cAC9C;GAEA,UAAA,oBAAC,OAAO,KAAR;IAEE,QAAA;IACA,SAAS;KAAE,SAAS;KAAG,GAAG;KAAQ,OAAO;IAAW;IACpD,SAAS;KAAE,SAAS;KAAG,GAAG;KAAG,OAAO;IAAE;IACtC,MAAM;KACJ,SAAS;KACT,GAAG;KACH,OAAO,SAAS,IAAI;KACpB,YAAY;MAAE,UAAU;MAAM,MAAM;KAAS;IAC/C;IACA,YAAY;IACZ,GAAI;IACJ,WAAW,GACT,gJACA,SACF;IAEA,UAAA,oBAAC,OAAO,KAAR;KAAY,QAAO;KAAW,WAAU;KACtC,UAAA,oBAAC,iBAAD;MAAiB,MAAK;MAAY,SAAS;MACzC,UAAA,oBAAC,OAAO,KAAR;OAEE,SAAS,SAAS,EAAE,SAAS,EAAE,IAAI;QAAE,SAAS;QAAG,GAAG;QAAG,QAAQ;OAAY;OAC3E,SACE,SACI;QACE,SAAS;QACT,YAAY;SACV,UAAU;SACV,MAAM;QACR;OACF,IACA;QACE,SAAS;QACT,GAAG;QACH,QAAQ;QACR,YAAY;SACV,UAAU;SACV,MAAM;QACR;OACF;OAEN,MACE,SACI;QACE,SAAS;QACT,YAAY;SACV,UAAU;SACV,MAAM;QACR;OACF,IACA;QACE,SAAS;QACT,GAAG;QACH,QAAQ;QACR,YAAY;SACV,UAAU;SACV,MAAM;QACR;OACF;OAGL;MACS,GA1CL,MA0CK;KACG,CAAA;IACP,CAAA;GACF,GAjEN,OAiEM;EACT,CAAA,EAEK,GAhFI,aAgFJ,IACZ,IACW;;AAErB"}
|
|
1
|
+
{"version":3,"file":"morphing-modal.js","names":[],"sources":["../../../src/components/motion/morphing-modal.tsx"],"sourcesContent":["\"use client\";\n\nimport { type ReactNode, useEffect, useId, useLayoutEffect, useRef, useState } from \"react\";\nimport { AnimatePresence, motion, useReducedMotion } from \"motion/react\";\n\nimport { cn } from \"@kumix/utils\";\nimport { focusablesIn, useFocusTrap } from \"../../hooks/use-focus-trap\";\nimport { EASE_OUT, SPRING_PANEL } from \"../../lib/ease\";\nimport { PresenceGate } from \"../../lib/presence-gate\";\n\nexport interface MorphingModalProps {\n /** Which view is currently shown. `null` closes the modal. */\n viewId: string | null;\n onClose: () => void;\n children: ReactNode;\n /** \"bottom\" anchors to the viewport bottom (mobile-like). \"center\" centers vertically. */\n placement?: \"bottom\" | \"center\";\n /**\n * Accessible name for the dialog. Without it, the dialog is named by the\n * first heading in the current view.\n */\n ariaLabel?: string;\n className?: string;\n}\n\nexport function MorphingModal({\n viewId,\n onClose,\n children,\n placement = \"bottom\",\n ariaLabel,\n className,\n}: MorphingModalProps) {\n const open = viewId !== null;\n const reduce = useReducedMotion();\n const panelRef = useRef<HTMLDivElement>(null);\n const uid = useId();\n const [headingId, setHeadingId] = useState<string>();\n\n // Focus moves into the panel on open, Tab stays inside it, Escape closes,\n // and focus returns to the opener on close.\n useFocusTrap(open, panelRef, { onEscape: onClose });\n\n // The current view, not the one still fading out under it.\n const currentView = () =>\n Array.from(panelRef.current?.querySelectorAll<HTMLElement>(\"[data-view]\") ?? []).find(\n (element) => element.dataset.view === viewId,\n );\n\n // Name the dialog by the current view's first heading unless a label is set.\n useLayoutEffect(() => {\n if (!viewId || ariaLabel) return;\n const heading = currentView()?.querySelector<HTMLElement>(\"h1, h2, h3, h4, h5, h6\");\n if (heading && !heading.id) heading.id = `${uid}-${viewId}-title`;\n setHeadingId(heading?.id);\n });\n\n // The focused control leaves with the old view, so a view change hands focus\n // to the first control of the new one.\n const shownView = useRef(viewId);\n useEffect(() => {\n const previous = shownView.current;\n shownView.current = viewId;\n if (!viewId || !previous || previous === viewId) return;\n const panel = panelRef.current;\n const active = document.activeElement;\n if (!panel || (active && active !== document.body && !panel.contains(active))) return;\n const view = currentView();\n (focusablesIn(view ?? null)[0] ?? panel).focus({ preventScroll: true });\n });\n const enterY = reduce ? 0 : placement === \"bottom\" ? 40 : 20;\n const enterScale = reduce ? 1 : 0.97;\n\n useEffect(() => {\n if (!open) return;\n const prev = document.body.style.overflow;\n document.body.style.overflow = \"hidden\";\n return () => {\n document.body.style.overflow = prev;\n };\n }, [open]);\n\n // Mounted only while open, and while open the chrome is two fixed siblings\n // rather than one wrapper: the backdrop spans the viewport edges but carries\n // the scrim colour, and the layer positioning the panel sits inset off every\n // edge (`inset-4`, with the bottom placement's `pb-4` on top of it). Both hang\n // off `PresenceGate`, so interaction releases in the same commit that starts\n // the exit rather than when it ends — `open` is already false for those\n // frames.\n return (\n <AnimatePresence initial={false}>\n {open ? (\n <PresenceGate key=\"backdrop\">\n {({ gate }) => (\n <motion.button\n type=\"button\"\n aria-label=\"Close modal\"\n // Outside the panel, so the focus trap never lands on it; it is\n // a pointer target, and Escape closes from the keyboard.\n tabIndex={-1}\n initial={{ opacity: 0 }}\n animate={{ opacity: 1 }}\n exit={{ opacity: 0 }}\n transition={{ duration: 0.2, ease: EASE_OUT }}\n {...gate}\n onClick={onClose}\n className=\"pointer-events-auto fixed inset-0 z-80 bg-background/5 [-webkit-backdrop-filter:blur(14px)_saturate(140%)] [backdrop-filter:blur(14px)_saturate(140%)]\"\n />\n )}\n </PresenceGate>\n ) : null}\n\n {open ? (\n <PresenceGate key=\"panel-layer\">\n {({ isPresent, gate }) => (\n // The layer itself never takes pointer events, so it carries\n // `inert` alone rather than the gate's pointer-events value.\n <div\n inert={!isPresent}\n className={cn(\n \"pointer-events-none fixed inset-4 z-80 flex justify-center\",\n placement === \"bottom\" ? \"items-end pb-4\" : \"items-center\",\n )}\n >\n <motion.div\n key=\"panel\"\n ref={panelRef}\n role=\"dialog\"\n aria-modal=\"true\"\n aria-label={ariaLabel}\n aria-labelledby={ariaLabel ? undefined : headingId}\n tabIndex={-1}\n layout\n initial={{ opacity: 0, y: enterY, scale: enterScale }}\n animate={{ opacity: 1, y: 0, scale: 1 }}\n exit={{\n opacity: 0,\n y: enterY,\n scale: reduce ? 1 : 0.98,\n transition: { duration: 0.18, ease: EASE_OUT },\n }}\n transition={SPRING_PANEL}\n {...gate}\n className={cn(\n \"pointer-events-auto relative w-full max-w-sm overflow-hidden rounded-3xl border border-border bg-background shadow-2xl outline-none will-change-transform\",\n className,\n )}\n >\n <motion.div layout=\"position\" className=\"p-5\">\n <AnimatePresence mode=\"popLayout\" initial={false}>\n <PresenceGate key={viewId}>\n {({ isPresent: viewPresent }) => (\n <motion.div\n // The outgoing view stays for its exit; inert keeps the\n // trap and assistive technology on the incoming one.\n inert={!viewPresent}\n data-view={viewId}\n initial={\n reduce ? { opacity: 0 } : { opacity: 0, y: 8, filter: \"blur(4px)\" }\n }\n animate={\n reduce\n ? {\n opacity: 1,\n transition: {\n duration: 0.18,\n ease: EASE_OUT,\n },\n }\n : {\n opacity: 1,\n y: 0,\n filter: \"blur(0px)\",\n transition: {\n duration: 0.24,\n ease: EASE_OUT,\n },\n }\n }\n exit={\n reduce\n ? {\n opacity: 0,\n transition: {\n duration: 0.14,\n ease: EASE_OUT,\n },\n }\n : {\n opacity: 0,\n y: -8,\n filter: \"blur(4px)\",\n transition: {\n duration: 0.16,\n ease: EASE_OUT,\n },\n }\n }\n >\n {children}\n </motion.div>\n )}\n </PresenceGate>\n </AnimatePresence>\n </motion.div>\n </motion.div>\n </div>\n )}\n </PresenceGate>\n ) : null}\n </AnimatePresence>\n );\n}\n"],"mappings":";;;;;;;;;AAyBA,SAAgB,cAAc,EAC5B,QACA,SACA,UACA,YAAY,UACZ,WACA,aACqB;CACrB,MAAM,OAAO,WAAW;CACxB,MAAM,SAAS,iBAAiB;CAChC,MAAM,WAAW,OAAuB,IAAI;CAC5C,MAAM,MAAM,MAAM;CAClB,MAAM,CAAC,WAAW,gBAAgB,SAAiB;CAInD,aAAa,MAAM,UAAU,E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AAU;SACV,MAAM;QACR;OACF;OAGL;MACS,CAAA,EAEF,GApDK,MAoDL;KACC,CAAA;IACP,CAAA;GACF,GAhFN,OAgFM;EACT,CAAA,EAEK,GA/FI,aA+FJ,IACZ,IACW;;AAErB"}
|
|
@@ -6,8 +6,8 @@ import { useCallback, useEffect, useId, useLayoutEffect, useMemo, useRef, useSta
|
|
|
6
6
|
import { cn } from "@kumix/utils";
|
|
7
7
|
import { Fragment as Fragment$1, jsx, jsxs } from "react/jsx-runtime";
|
|
8
8
|
import { AnimatePresence, LayoutGroup, motion, useReducedMotion } from "motion/react";
|
|
9
|
-
import { Search } from "lucide-react";
|
|
10
9
|
import { createPortal } from "react-dom";
|
|
10
|
+
import { Search } from "lucide-react";
|
|
11
11
|
//#region src/components/motion/morphing-search.tsx
|
|
12
12
|
const SEARCH_MORPH = {
|
|
13
13
|
type: "spring",
|
|
@@ -5,8 +5,8 @@ import { useCallback, useEffect, useId, useLayoutEffect, useMemo, useRef, useSta
|
|
|
5
5
|
import { cn } from "@kumix/utils";
|
|
6
6
|
import { Fragment as Fragment$1, jsx, jsxs } from "react/jsx-runtime";
|
|
7
7
|
import { AnimatePresence, animate, motion, useMotionValue, useReducedMotion, useSpring, useTransform } from "motion/react";
|
|
8
|
-
import { X } from "lucide-react";
|
|
9
8
|
import { createPortal } from "react-dom";
|
|
9
|
+
import { X } from "lucide-react";
|
|
10
10
|
//#region src/components/motion/morphing-tabs.tsx
|
|
11
11
|
const DRAG_THRESHOLD = 5;
|
|
12
12
|
const MAX_TAB_WIDTH = 176;
|
|
@@ -14,6 +14,9 @@ function OTPInput({ length = 6, value: controlledValue, defaultValue = "", onCha
|
|
|
14
14
|
const [slots, setSlots] = useState(() => toSlots(controlled ? controlledValue : defaultValue, length));
|
|
15
15
|
const [focused, setFocused] = useState(false);
|
|
16
16
|
const [active, setActive] = useState(0);
|
|
17
|
+
const [announcement, setAnnouncement] = useState("");
|
|
18
|
+
const announce = (text) => setAnnouncement((previous) => previous === text ? `${text}\u00a0` : text);
|
|
19
|
+
const spokenSlot = (char) => char ? mask ? "Filled" : char : "Empty";
|
|
17
20
|
const joined = slots.join("");
|
|
18
21
|
const joinedRef = useRef(joined);
|
|
19
22
|
useEffect(() => {
|
|
@@ -30,6 +33,12 @@ function OTPInput({ length = 6, value: controlledValue, defaultValue = "", onCha
|
|
|
30
33
|
]);
|
|
31
34
|
const commit = (next) => {
|
|
32
35
|
const wasComplete = slots.every((c) => c !== "");
|
|
36
|
+
const changed = next.flatMap((c, i) => c !== slots[i] ? [i] : []);
|
|
37
|
+
const progress = `${next.filter(Boolean).length} of ${length} digits entered.`;
|
|
38
|
+
if (changed.length === 1) {
|
|
39
|
+
const char = next[changed[0]];
|
|
40
|
+
announce(char ? `${mask ? "Digit" : char}. ${progress}` : `Deleted. ${progress}`);
|
|
41
|
+
} else if (changed.length > 1) announce(progress);
|
|
33
42
|
setSlots(next);
|
|
34
43
|
const str = next.join("");
|
|
35
44
|
onChange?.(str);
|
|
@@ -75,18 +84,11 @@ function OTPInput({ length = 6, value: controlledValue, defaultValue = "", onCha
|
|
|
75
84
|
} else if (k === "Delete") {
|
|
76
85
|
e.preventDefault();
|
|
77
86
|
clearSlot(active);
|
|
78
|
-
} else if (k === "ArrowLeft") {
|
|
87
|
+
} else if (k === "ArrowLeft" || k === "ArrowRight" || k === "Home" || k === "End") {
|
|
79
88
|
e.preventDefault();
|
|
80
|
-
|
|
81
|
-
|
|
82
|
-
|
|
83
|
-
setActive((a) => Math.min(a + 1, length - 1));
|
|
84
|
-
} else if (k === "Home") {
|
|
85
|
-
e.preventDefault();
|
|
86
|
-
setActive(0);
|
|
87
|
-
} else if (k === "End") {
|
|
88
|
-
e.preventDefault();
|
|
89
|
-
setActive(length - 1);
|
|
89
|
+
const to = k === "ArrowLeft" ? Math.max(active - 1, 0) : k === "ArrowRight" ? Math.min(active + 1, length - 1) : k === "Home" ? 0 : length - 1;
|
|
90
|
+
setActive(to);
|
|
91
|
+
announce(`${spokenSlot(slots[to] ?? "")}, digit ${to + 1} of ${length}.`);
|
|
90
92
|
}
|
|
91
93
|
};
|
|
92
94
|
const onPaste = (e) => {
|
|
@@ -251,6 +253,12 @@ function OTPInput({ length = 6, value: controlledValue, defaultValue = "", onCha
|
|
|
251
253
|
}) : null })
|
|
252
254
|
]
|
|
253
255
|
}),
|
|
256
|
+
/* @__PURE__ */ jsx("span", {
|
|
257
|
+
"aria-live": "polite",
|
|
258
|
+
"aria-atomic": "true",
|
|
259
|
+
className: "sr-only",
|
|
260
|
+
children: announcement
|
|
261
|
+
}),
|
|
254
262
|
message ? /* @__PURE__ */ jsx("p", {
|
|
255
263
|
"aria-live": "polite",
|
|
256
264
|
className: cn("text-sm", showSuccess ? "text-emerald-500" : status === "error" ? "text-destructive" : "text-muted-foreground"),
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"otp-input.js","names":[],"sources":["../../../src/components/motion/otp-input.tsx"],"sourcesContent":["\"use client\";\n\nimport { useEffect, useId, useRef, useState } from \"react\";\nimport { AnimatePresence, animate, motion, useReducedMotion } from \"motion/react\";\n\nimport { cn } from \"@kumix/utils\";\nimport { EASE_OUT } from \"../../lib/ease\";\n\nexport type OTPStatus = \"idle\" | \"error\" | \"success\";\n\nexport interface OTPInputProps {\n /** Number of slots. Default 6. */\n length?: number;\n value?: string;\n defaultValue?: string;\n onChange?: (value: string) => void;\n /** Fires once every slot is filled. */\n onComplete?: (value: string) => void;\n /** Optional label rendered above the slots. */\n label?: string;\n /** Helper text shown below the slots while idle. */\n hint?: string;\n /** Message shown below the slots when status is \"success\". */\n successMessage?: string;\n /** Message shown below the slots when status is \"error\". */\n errorMessage?: string;\n /** External validation feedback. \"error\" shakes, \"success\" draws a check. */\n status?: OTPStatus;\n /** Render dots instead of the typed digits. */\n mask?: boolean;\n disabled?: boolean;\n autoFocus?: boolean;\n /** Accessible label for the underlying input. */\n \"aria-label\"?: string;\n className?: string;\n}\n\nexport function OTPInput({\n length = 6,\n value: controlledValue,\n defaultValue = \"\",\n onChange,\n onComplete,\n label,\n hint,\n successMessage,\n errorMessage,\n status = \"idle\",\n mask = false,\n disabled = false,\n autoFocus = false,\n \"aria-label\": ariaLabel = \"One-time passcode\",\n className,\n}: OTPInputProps) {\n const uid = useId();\n const reduce = useReducedMotion();\n const inputRef = useRef<HTMLInputElement>(null);\n const slotsRef = useRef<HTMLDivElement>(null);\n\n const controlled = controlledValue !== undefined;\n\n // Source of truth is a fixed-length array, so a cleared middle slot stays an\n // in-place hole instead of collapsing the digits after it to the left.\n const [slots, setSlots] = useState<string[]>(() =>\n toSlots(controlled ? controlledValue : defaultValue, length),\n );\n const [focused, setFocused] = useState(false);\n const [active, setActive] = useState(0);\n\n const joined = slots.join(\"\");\n const joinedRef = useRef(joined);\n\n useEffect(() => {\n joinedRef.current = joined;\n }, [joined]);\n\n // Pull in external value changes; skip when the parent is just echoing our own\n // onChange, so internal holes survive the controlled round-trip.\n useEffect(() => {\n if (!controlled) return;\n const incoming = sanitize(controlledValue, length);\n if (incoming !== joinedRef.current) setSlots(toSlots(incoming, length));\n }, [controlled, controlledValue, length]);\n\n const commit = (next: string[]) => {\n const wasComplete = slots.every((c) => c !== \"\");\n setSlots(next);\n const str = next.join(\"\");\n onChange?.(str);\n // Fire only on the empty→full transition, not on every edit of a full code.\n if (!wasComplete && next.every((c) => c !== \"\")) onComplete?.(str);\n };\n\n const clearSlot = (idx: number) => {\n const next = [...slots];\n next[idx] = \"\";\n commit(next);\n };\n\n const slotFromClientX = (clientX: number) => {\n const els = slotsRef.current?.children;\n if (!els) return 0;\n for (let i = 0; i < els.length; i++) {\n if (clientX < els[i].getBoundingClientRect().right) return i;\n }\n return length - 1;\n };\n\n // Single insertion path: one digit overwrites the active slot and advances; a\n // multi-digit chunk (paste / SMS autofill) fills forward from the active slot.\n const insert = (raw: string, from = active) => {\n const digits = raw.replace(/\\D/g, \"\");\n if (!digits) return;\n const next = [...slots];\n let i = from;\n for (const ch of digits) {\n if (i >= length) break;\n next[i] = ch;\n i++;\n }\n commit(next);\n setActive(Math.min(i, length - 1));\n };\n\n // The keyboard is the single source of truth: preventDefault on keydown\n // reliably blocks native insertion (unlike beforeinput in React), so the hidden\n // input never accumulates a competing string and slot holes survive.\n const onKeyDown = (e: React.KeyboardEvent<HTMLInputElement>) => {\n if (disabled || e.metaKey || e.ctrlKey || e.altKey) return;\n const k = e.key;\n if (/^[0-9]$/.test(k)) {\n e.preventDefault();\n insert(k);\n } else if (k === \"Backspace\") {\n e.preventDefault();\n // A filled slot clears in place; an empty slot steps back and clears there.\n if (slots[active]) {\n clearSlot(active);\n } else if (active > 0) {\n clearSlot(active - 1);\n setActive((current) => Math.max(current - 1, 0));\n }\n } else if (k === \"Delete\") {\n e.preventDefault();\n clearSlot(active);\n } else if (k === \"ArrowLeft\") {\n e.preventDefault();\n setActive((a) => Math.max(a - 1, 0));\n } else if (k === \"ArrowRight\") {\n e.preventDefault();\n setActive((a) => Math.min(a + 1, length - 1));\n } else if (k === \"Home\") {\n e.preventDefault();\n setActive(0);\n } else if (k === \"End\") {\n e.preventDefault();\n setActive(length - 1);\n }\n };\n\n const onPaste = (e: React.ClipboardEvent<HTMLInputElement>) => {\n if (disabled) return;\n // preventDefault suppresses the duplicate onChange, keeping that path autofill-only.\n e.preventDefault();\n insert(e.clipboardData.getData(\"text\"), active);\n };\n\n // Autofill path: SMS one-time-code arrives as a whole value in one shot.\n // Keystrokes go through onKeyDown and paste through onPaste, so only autofill\n // reaches here — spread it across the slots from the start.\n const onChangeNative = (e: React.ChangeEvent<HTMLInputElement>) => {\n const digits = sanitize(e.target.value, length);\n if (!digits) return;\n commit(toSlots(digits, length));\n setActive(Math.min(digits.length, length - 1));\n };\n\n // Error shake — imperative so it replays on every transition into \"error\".\n useEffect(() => {\n if (status !== \"error\" || reduce || !slotsRef.current) return;\n animate(slotsRef.current, { x: [0, -5, 5, -3, 3, -1, 0] }, { duration: 0.45, ease: EASE_OUT });\n }, [status, reduce]);\n\n const showSuccess = status === \"success\";\n const activeIndex = focused ? active : -1;\n const message = showSuccess ? successMessage : status === \"error\" ? errorMessage : hint;\n\n return (\n <div className={cn(\"inline-flex flex-col gap-2\", className)}>\n {label ? (\n <label htmlFor={`${uid}-input`} className=\"font-medium text-foreground text-sm\">\n {label}\n </label>\n ) : null}\n <fieldset\n className=\"relative m-0 inline-flex w-max border-0 p-0\"\n onMouseDown={(e) => {\n if (disabled) return;\n // Suppress the native click-caret; we drive the active slot ourselves.\n e.preventDefault();\n // Clamp to the first empty slot so a click can't jump ahead of progress.\n const firstEmpty = slots.indexOf(\"\");\n const cap = firstEmpty === -1 ? length - 1 : firstEmpty;\n setActive(Math.min(slotFromClientX(e.clientX), cap));\n inputRef.current?.focus();\n }}\n >\n <input\n ref={inputRef}\n id={`${uid}-input`}\n inputMode=\"numeric\"\n autoComplete=\"one-time-code\"\n autoFocus={autoFocus}\n disabled={disabled}\n aria-label={ariaLabel}\n aria-invalid={status === \"error\"}\n // Kept empty on purpose — our state owns the digits, native holds none.\n value=\"\"\n maxLength={length}\n onKeyDown={onKeyDown}\n onChange={onChangeNative}\n onPaste={onPaste}\n onFocus={() => setFocused(true)}\n onBlur={() => setFocused(false)}\n // Transparent overlay owns focus, the soft keyboard, paste and autofill;\n // the slots below are purely presentational.\n className=\"absolute inset-0 z-20 h-full w-full cursor-text bg-transparent text-transparent caret-transparent opacity-0 outline-none disabled:cursor-not-allowed\"\n />\n\n <div ref={slotsRef} className=\"flex items-center gap-2\">\n {Array.from({ length }, (_, i) => {\n const char = slots[i] ?? \"\";\n const isActive = i === activeIndex;\n return (\n <div\n key={`${uid}-${i}`}\n data-active={isActive}\n data-filled={char !== \"\"}\n className={cn(\n \"relative grid h-14 w-12 place-items-center overflow-hidden rounded-xl border font-semibold text-xl tabular-nums transition-colors duration-200\",\n showSuccess\n ? \"border-emerald-500/60 text-foreground\"\n : status === \"error\"\n ? \"border-destructive/60 text-foreground\"\n : char\n ? \"border-border-strong text-foreground\"\n : \"border-border text-muted-foreground\",\n // Active slot reads stronger; twMerge lets this win the border.\n isActive && !showSuccess && status !== \"error\" && \"border-foreground\",\n disabled && \"opacity-50\",\n )}\n >\n {/* Blinking caret marks the active slot — centered when empty,\n trailing the digit when the slot is already filled. */}\n {isActive && !showSuccess ? (\n <motion.span\n aria-hidden\n animate={reduce ? undefined : { opacity: [1, 1, 0, 0] }}\n transition={\n reduce\n ? undefined\n : { duration: 1, repeat: Number.POSITIVE_INFINITY, ease: \"linear\" }\n }\n className={cn(\n \"pointer-events-none absolute top-1/2 h-6 w-px -translate-y-1/2 bg-foreground\",\n char ? \"right-3\" : \"left-1/2 -translate-x-1/2\",\n )}\n />\n ) : null}\n\n {/* Digits roll vertically. Each is absolutely centered so enter and\n exit overlap in place — no in-flow reflow, no sideways drift. */}\n <AnimatePresence initial={false}>\n {char ? (\n <motion.span\n key={char}\n initial={reduce ? { opacity: 0 } : { y: 14, opacity: 0, filter: \"blur(4px)\" }}\n animate={reduce ? { opacity: 1 } : { y: 0, opacity: 1, filter: \"blur(0px)\" }}\n exit={reduce ? { opacity: 0 } : { y: -14, opacity: 0, filter: \"blur(4px)\" }}\n transition={reduce ? { duration: 0 } : { duration: 0.22, ease: EASE_OUT }}\n className=\"absolute inset-0 grid place-items-center leading-none\"\n >\n {mask ? \"•\" : char}\n </motion.span>\n ) : null}\n </AnimatePresence>\n </div>\n );\n })}\n </div>\n\n <AnimatePresence>\n {showSuccess ? (\n <motion.span\n initial={reduce ? { opacity: 0 } : { scale: 0.6, opacity: 0 }}\n animate={reduce ? { opacity: 1 } : { scale: 1, opacity: 1 }}\n exit={reduce ? { opacity: 0 } : { scale: 0.6, opacity: 0 }}\n transition={\n reduce ? { duration: 0 } : { type: \"spring\", stiffness: 500, damping: 28 }\n }\n className=\"pointer-events-none absolute top-1/2 -right-7 -translate-y-1/2 text-emerald-500\"\n aria-hidden\n >\n <svg\n width=\"20\"\n height=\"20\"\n viewBox=\"0 0 24 24\"\n fill=\"none\"\n stroke=\"currentColor\"\n strokeWidth={3}\n strokeLinecap=\"round\"\n strokeLinejoin=\"round\"\n >\n <title>Verified</title>\n <motion.path\n d=\"M5 13l4 4L19 7\"\n initial={reduce ? { pathLength: 1 } : { pathLength: 0 }}\n animate={{ pathLength: 1 }}\n transition={\n reduce ? { duration: 0 } : { duration: 0.35, ease: EASE_OUT, delay: 0.1 }\n }\n />\n </svg>\n </motion.span>\n ) : null}\n </AnimatePresence>\n </fieldset>\n\n {message ? (\n <p\n aria-live=\"polite\"\n className={cn(\n \"text-sm\",\n showSuccess\n ? \"text-emerald-500\"\n : status === \"error\"\n ? \"text-destructive\"\n : \"text-muted-foreground\",\n )}\n >\n {message}\n </p>\n ) : null}\n </div>\n );\n}\n\nfunction sanitize(raw: string, length: number) {\n return raw.replace(/\\D/g, \"\").slice(0, length);\n}\n\nfunction toSlots(raw: string, length: number) {\n const digits = sanitize(raw, length);\n return Array.from({ length }, (_, i) => digits[i] ?? \"\");\n}\n"],"mappings":";;;;;;;AAqCA,SAAgB,SAAS,EACvB,SAAS,GACT,OAAO,iBACP,eAAe,IACf,UACA,YACA,OACA,MACA,gBACA,cACA,SAAS,QACT,OAAO,OACP,WAAW,OACX,YAAY,OACZ,cAAc,YAAY,qBAC1B,aACgB;CAChB,MAAM,MAAM,MAAM;CAClB,MAAM,SAAS,iBAAiB;CAChC,MAAM,WAAW,OAAyB,IAAI;CAC9C,MAAM,WAAW,OAAuB,IAAI;CAE5C,MAAM,aAAa,oBAAoB,KAAA;CAIvC,MAAM,CAAC,OAAO,YAAY,eACxB,QAAQ,aAAa,kBAAkB,cAAc,MAAM,CAC7D;CACA,MAAM,CAAC,SAAS,cAAc,SAAS,KAAK;CAC5C,MAAM,CAAC,QAAQ,aAAa,SAAS,CAAC;CAEtC,MAAM,SAAS,MAAM,KAAK,EAAE;CAC5B,MAAM,YAAY,OAAO,MAAM;CAE/B,gBAAgB;EACd,UAAU,UAAU;CACtB,GAAG,CAAC,MAAM,CAAC;CAIX,gBAAgB;EAC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Y,EAAE;QACtD,SAAS,EAAE,YAAY,EAAE;QACzB,YACE,SAAS,EAAE,UAAU,EAAE,IAAI;SAAE,UAAU;SAAM,MAAM;SAAU,OAAO;QAAI;OAE3E,CAAA,CACE;;KACM,CAAA,IACX,KACW,CAAA;IACT;;GAET,UACC,oBAAC,KAAD;IACE,aAAU;IACV,WAAW,GACT,WACA,cACI,qBACA,WAAW,UACT,qBACA,uBACR;IAEC,UAAA;GACA,CAAA,IACD;EACD;;AAET;AAEA,SAAS,SAAS,KAAa,QAAgB;CAC7C,OAAO,IAAI,QAAQ,OAAO,EAAE,CAAC,CAAC,MAAM,GAAG,MAAM;AAC/C;AAEA,SAAS,QAAQ,KAAa,QAAgB;CAC5C,MAAM,SAAS,SAAS,KAAK,MAAM;CACnC,OAAO,MAAM,KAAK,EAAE,OAAO,IAAI,GAAG,MAAM,OAAO,MAAM,EAAE;AACzD"}
|
|
1
|
+
{"version":3,"file":"otp-input.js","names":[],"sources":["../../../src/components/motion/otp-input.tsx"],"sourcesContent":["\"use client\";\n\nimport { useEffect, useId, useRef, useState } from \"react\";\nimport { AnimatePresence, animate, motion, useReducedMotion } from \"motion/react\";\n\nimport { cn } from \"@kumix/utils\";\nimport { EASE_OUT } from \"../../lib/ease\";\n\nexport type OTPStatus = \"idle\" | \"error\" | \"success\";\n\nexport interface OTPInputProps {\n /** Number of slots. Default 6. */\n length?: number;\n value?: string;\n defaultValue?: string;\n onChange?: (value: string) => void;\n /** Fires once every slot is filled. */\n onComplete?: (value: string) => void;\n /** Optional label rendered above the slots. */\n label?: string;\n /** Helper text shown below the slots while idle. */\n hint?: string;\n /** Message shown below the slots when status is \"success\". */\n successMessage?: string;\n /** Message shown below the slots when status is \"error\". */\n errorMessage?: string;\n /** External validation feedback. \"error\" shakes, \"success\" draws a check. */\n status?: OTPStatus;\n /** Render dots instead of the typed digits. */\n mask?: boolean;\n disabled?: boolean;\n autoFocus?: boolean;\n /** Accessible label for the underlying input. */\n \"aria-label\"?: string;\n className?: string;\n}\n\nexport function OTPInput({\n length = 6,\n value: controlledValue,\n defaultValue = \"\",\n onChange,\n onComplete,\n label,\n hint,\n successMessage,\n errorMessage,\n status = \"idle\",\n mask = false,\n disabled = false,\n autoFocus = false,\n \"aria-label\": ariaLabel = \"One-time passcode\",\n className,\n}: OTPInputProps) {\n const uid = useId();\n const reduce = useReducedMotion();\n const inputRef = useRef<HTMLInputElement>(null);\n const slotsRef = useRef<HTMLDivElement>(null);\n\n const controlled = controlledValue !== undefined;\n\n // Source of truth is a fixed-length array, so a cleared middle slot stays an\n // in-place hole instead of collapsing the digits after it to the left.\n const [slots, setSlots] = useState<string[]>(() =>\n toSlots(controlled ? controlledValue : defaultValue, length),\n );\n const [focused, setFocused] = useState(false);\n const [active, setActive] = useState(0);\n // The native input holds no value, so screen readers cannot echo what was\n // typed. This polite region speaks each change instead; the alternating\n // trailing space makes a repeated phrase count as new text.\n const [announcement, setAnnouncement] = useState(\"\");\n const announce = (text: string) =>\n setAnnouncement((previous) => (previous === text ? `${text}\\u00a0` : text));\n const spokenSlot = (char: string) => (char ? (mask ? \"Filled\" : char) : \"Empty\");\n\n const joined = slots.join(\"\");\n const joinedRef = useRef(joined);\n\n useEffect(() => {\n joinedRef.current = joined;\n }, [joined]);\n\n // Pull in external value changes; skip when the parent is just echoing our own\n // onChange, so internal holes survive the controlled round-trip.\n useEffect(() => {\n if (!controlled) return;\n const incoming = sanitize(controlledValue, length);\n if (incoming !== joinedRef.current) setSlots(toSlots(incoming, length));\n }, [controlled, controlledValue, length]);\n\n const commit = (next: string[]) => {\n const wasComplete = slots.every((c) => c !== \"\");\n const changed = next.flatMap((c, i) => (c !== slots[i] ? [i] : []));\n const progress = `${next.filter(Boolean).length} of ${length} digits entered.`;\n if (changed.length === 1) {\n const char = next[changed[0]];\n announce(char ? `${mask ? \"Digit\" : char}. ${progress}` : `Deleted. ${progress}`);\n } else if (changed.length > 1) {\n announce(progress);\n }\n setSlots(next);\n const str = next.join(\"\");\n onChange?.(str);\n // Fire only on the empty→full transition, not on every edit of a full code.\n if (!wasComplete && next.every((c) => c !== \"\")) onComplete?.(str);\n };\n\n const clearSlot = (idx: number) => {\n const next = [...slots];\n next[idx] = \"\";\n commit(next);\n };\n\n const slotFromClientX = (clientX: number) => {\n const els = slotsRef.current?.children;\n if (!els) return 0;\n for (let i = 0; i < els.length; i++) {\n if (clientX < els[i].getBoundingClientRect().right) return i;\n }\n return length - 1;\n };\n\n // Single insertion path: one digit overwrites the active slot and advances; a\n // multi-digit chunk (paste / SMS autofill) fills forward from the active slot.\n const insert = (raw: string, from = active) => {\n const digits = raw.replace(/\\D/g, \"\");\n if (!digits) return;\n const next = [...slots];\n let i = from;\n for (const ch of digits) {\n if (i >= length) break;\n next[i] = ch;\n i++;\n }\n commit(next);\n setActive(Math.min(i, length - 1));\n };\n\n // The keyboard is the single source of truth: preventDefault on keydown\n // reliably blocks native insertion (unlike beforeinput in React), so the hidden\n // input never accumulates a competing string and slot holes survive.\n const onKeyDown = (e: React.KeyboardEvent<HTMLInputElement>) => {\n if (disabled || e.metaKey || e.ctrlKey || e.altKey) return;\n const k = e.key;\n if (/^[0-9]$/.test(k)) {\n e.preventDefault();\n insert(k);\n } else if (k === \"Backspace\") {\n e.preventDefault();\n // A filled slot clears in place; an empty slot steps back and clears there.\n if (slots[active]) {\n clearSlot(active);\n } else if (active > 0) {\n clearSlot(active - 1);\n setActive((current) => Math.max(current - 1, 0));\n }\n } else if (k === \"Delete\") {\n e.preventDefault();\n clearSlot(active);\n } else if (k === \"ArrowLeft\" || k === \"ArrowRight\" || k === \"Home\" || k === \"End\") {\n e.preventDefault();\n const to =\n k === \"ArrowLeft\"\n ? Math.max(active - 1, 0)\n : k === \"ArrowRight\"\n ? Math.min(active + 1, length - 1)\n : k === \"Home\"\n ? 0\n : length - 1;\n setActive(to);\n announce(`${spokenSlot(slots[to] ?? \"\")}, digit ${to + 1} of ${length}.`);\n }\n };\n\n const onPaste = (e: React.ClipboardEvent<HTMLInputElement>) => {\n if (disabled) return;\n // preventDefault suppresses the duplicate onChange, keeping that path autofill-only.\n e.preventDefault();\n insert(e.clipboardData.getData(\"text\"), active);\n };\n\n // Autofill path: SMS one-time-code arrives as a whole value in one shot.\n // Keystrokes go through onKeyDown and paste through onPaste, so only autofill\n // reaches here — spread it across the slots from the start.\n const onChangeNative = (e: React.ChangeEvent<HTMLInputElement>) => {\n const digits = sanitize(e.target.value, length);\n if (!digits) return;\n commit(toSlots(digits, length));\n setActive(Math.min(digits.length, length - 1));\n };\n\n // Error shake — imperative so it replays on every transition into \"error\".\n useEffect(() => {\n if (status !== \"error\" || reduce || !slotsRef.current) return;\n animate(slotsRef.current, { x: [0, -5, 5, -3, 3, -1, 0] }, { duration: 0.45, ease: EASE_OUT });\n }, [status, reduce]);\n\n const showSuccess = status === \"success\";\n const activeIndex = focused ? active : -1;\n const message = showSuccess ? successMessage : status === \"error\" ? errorMessage : hint;\n\n return (\n <div className={cn(\"inline-flex flex-col gap-2\", className)}>\n {label ? (\n <label htmlFor={`${uid}-input`} className=\"font-medium text-foreground text-sm\">\n {label}\n </label>\n ) : null}\n <fieldset\n className=\"relative m-0 inline-flex w-max border-0 p-0\"\n onMouseDown={(e) => {\n if (disabled) return;\n // Suppress the native click-caret; we drive the active slot ourselves.\n e.preventDefault();\n // Clamp to the first empty slot so a click can't jump ahead of progress.\n const firstEmpty = slots.indexOf(\"\");\n const cap = firstEmpty === -1 ? length - 1 : firstEmpty;\n setActive(Math.min(slotFromClientX(e.clientX), cap));\n inputRef.current?.focus();\n }}\n >\n <input\n ref={inputRef}\n id={`${uid}-input`}\n inputMode=\"numeric\"\n autoComplete=\"one-time-code\"\n autoFocus={autoFocus}\n disabled={disabled}\n aria-label={ariaLabel}\n aria-invalid={status === \"error\"}\n // Kept empty on purpose — our state owns the digits, native holds none.\n value=\"\"\n maxLength={length}\n onKeyDown={onKeyDown}\n onChange={onChangeNative}\n onPaste={onPaste}\n onFocus={() => setFocused(true)}\n onBlur={() => setFocused(false)}\n // Transparent overlay owns focus, the soft keyboard, paste and autofill;\n // the slots below are purely presentational.\n className=\"absolute inset-0 z-20 h-full w-full cursor-text bg-transparent text-transparent caret-transparent opacity-0 outline-none disabled:cursor-not-allowed\"\n />\n\n <div ref={slotsRef} className=\"flex items-center gap-2\">\n {Array.from({ length }, (_, i) => {\n const char = slots[i] ?? \"\";\n const isActive = i === activeIndex;\n return (\n <div\n key={`${uid}-${i}`}\n data-active={isActive}\n data-filled={char !== \"\"}\n className={cn(\n \"relative grid h-14 w-12 place-items-center overflow-hidden rounded-xl border font-semibold text-xl tabular-nums transition-colors duration-200\",\n showSuccess\n ? \"border-emerald-500/60 text-foreground\"\n : status === \"error\"\n ? \"border-destructive/60 text-foreground\"\n : char\n ? \"border-border-strong text-foreground\"\n : \"border-border text-muted-foreground\",\n // Active slot reads stronger; twMerge lets this win the border.\n isActive && !showSuccess && status !== \"error\" && \"border-foreground\",\n disabled && \"opacity-50\",\n )}\n >\n {/* Blinking caret marks the active slot — centered when empty,\n trailing the digit when the slot is already filled. */}\n {isActive && !showSuccess ? (\n <motion.span\n aria-hidden\n animate={reduce ? undefined : { opacity: [1, 1, 0, 0] }}\n transition={\n reduce\n ? undefined\n : { duration: 1, repeat: Number.POSITIVE_INFINITY, ease: \"linear\" }\n }\n className={cn(\n \"pointer-events-none absolute top-1/2 h-6 w-px -translate-y-1/2 bg-foreground\",\n char ? \"right-3\" : \"left-1/2 -translate-x-1/2\",\n )}\n />\n ) : null}\n\n {/* Digits roll vertically. Each is absolutely centered so enter and\n exit overlap in place — no in-flow reflow, no sideways drift. */}\n <AnimatePresence initial={false}>\n {char ? (\n <motion.span\n key={char}\n initial={reduce ? { opacity: 0 } : { y: 14, opacity: 0, filter: \"blur(4px)\" }}\n animate={reduce ? { opacity: 1 } : { y: 0, opacity: 1, filter: \"blur(0px)\" }}\n exit={reduce ? { opacity: 0 } : { y: -14, opacity: 0, filter: \"blur(4px)\" }}\n transition={reduce ? { duration: 0 } : { duration: 0.22, ease: EASE_OUT }}\n className=\"absolute inset-0 grid place-items-center leading-none\"\n >\n {mask ? \"•\" : char}\n </motion.span>\n ) : null}\n </AnimatePresence>\n </div>\n );\n })}\n </div>\n\n <AnimatePresence>\n {showSuccess ? (\n <motion.span\n initial={reduce ? { opacity: 0 } : { scale: 0.6, opacity: 0 }}\n animate={reduce ? { opacity: 1 } : { scale: 1, opacity: 1 }}\n exit={reduce ? { opacity: 0 } : { scale: 0.6, opacity: 0 }}\n transition={\n reduce ? { duration: 0 } : { type: \"spring\", stiffness: 500, damping: 28 }\n }\n className=\"pointer-events-none absolute top-1/2 -right-7 -translate-y-1/2 text-emerald-500\"\n aria-hidden\n >\n <svg\n width=\"20\"\n height=\"20\"\n viewBox=\"0 0 24 24\"\n fill=\"none\"\n stroke=\"currentColor\"\n strokeWidth={3}\n strokeLinecap=\"round\"\n strokeLinejoin=\"round\"\n >\n <title>Verified</title>\n <motion.path\n d=\"M5 13l4 4L19 7\"\n initial={reduce ? { pathLength: 1 } : { pathLength: 0 }}\n animate={{ pathLength: 1 }}\n transition={\n reduce ? { duration: 0 } : { duration: 0.35, ease: EASE_OUT, delay: 0.1 }\n }\n />\n </svg>\n </motion.span>\n ) : null}\n </AnimatePresence>\n </fieldset>\n\n <span aria-live=\"polite\" aria-atomic=\"true\" className=\"sr-only\">\n {announcement}\n </span>\n\n {message ? (\n <p\n aria-live=\"polite\"\n className={cn(\n \"text-sm\",\n showSuccess\n ? \"text-emerald-500\"\n : status === \"error\"\n ? \"text-destructive\"\n : \"text-muted-foreground\",\n )}\n >\n {message}\n </p>\n ) : null}\n </div>\n );\n}\n\nfunction sanitize(raw: string, length: number) {\n return raw.replace(/\\D/g, \"\").slice(0, length);\n}\n\nfunction toSlots(raw: string, length: number) {\n const digits = sanitize(raw, length);\n return Array.from({ length }, (_, i) => digits[i] ?? \"\");\n}\n"],"mappings":";;;;;;;AAqCA,SAAgB,SAAS,EACvB,SAAS,GACT,OAAO,iBACP,eAAe,IACf,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GAEV,oBAAC,QAAD;IAAM,aAAU;IAAS,eAAY;IAAO,WAAU;IACnD,UAAA;GACG,CAAA;GAEL,UACC,oBAAC,KAAD;IACE,aAAU;IACV,WAAW,GACT,WACA,cACI,qBACA,WAAW,UACT,qBACA,uBACR;IAEC,UAAA;GACA,CAAA,IACD;EACD;;AAET;AAEA,SAAS,SAAS,KAAa,QAAgB;CAC7C,OAAO,IAAI,QAAQ,OAAO,EAAE,CAAC,CAAC,MAAM,GAAG,MAAM;AAC/C;AAEA,SAAS,QAAQ,KAAa,QAAgB;CAC5C,MAAM,SAAS,SAAS,KAAK,MAAM;CACnC,OAAO,MAAM,KAAK,EAAE,OAAO,IAAI,GAAG,MAAM,OAAO,MAAM,EAAE;AACzD"}
|
|
@@ -12,9 +12,10 @@ export interface MorphPopoverProps {
|
|
|
12
12
|
className?: string;
|
|
13
13
|
}
|
|
14
14
|
/**
|
|
15
|
-
* A popover whose panel
|
|
16
|
-
*
|
|
17
|
-
*
|
|
15
|
+
* A popover whose full-size panel reveals from the corner nearest the trigger
|
|
16
|
+
* on one spring, then retraces the same clip on close. Content and surface
|
|
17
|
+
* edges keep their size throughout. Closes on outside pointer / Escape.
|
|
18
|
+
* Controlled or uncontrolled.
|
|
18
19
|
*/
|
|
19
20
|
export declare function MorphPopover({ children, open: controlledOpen, defaultOpen, onOpenChange, className }: MorphPopoverProps): import("react").JSX.Element;
|
|
20
21
|
export interface MorphPopoverTriggerProps {
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"popover-morph.d.ts","names":[],"sources":["../../../src/components/motion/popover-morph.tsx"],"mappings":";;
|
|
1
|
+
{"version":3,"file":"popover-morph.d.ts","names":[],"sources":["../../../src/components/motion/popover-morph.tsx"],"mappings":";;KAiCK;KACA;iBAsBY;EACf,UAAU;;EAEV;;EAEA;EACA,gBAAgB;EAChB;;;;;;;;wBASc,eACd,UACA,MAAM,gBACN,aACA,cACA,aACC,oCAAiB,IAAA;iBAoFH;EACf,UAAU;;;wBAcI,sBAAsB,YAAY,2BAAwB,aAAA,kDAAA;iBAuCzD;EACf,UAAU;EACV,OAAO;EACP,QAAQ;;EAER;;EAEA;;EAEA;;EAEA,mBAAmB,SAAS;EAC5B;;wBAGc,oBAAoB,OAAO,2CAAwB"}
|
|
@@ -1,10 +1,10 @@
|
|
|
1
1
|
"use client";
|
|
2
|
-
import { EASE_OUT
|
|
2
|
+
import { EASE_OUT } from "../../lib/ease.js";
|
|
3
3
|
import { t as usePopoverPortalPosition } from "../../popover-position-BUqYCq8X.js";
|
|
4
|
-
import { cloneElement, createContext, isValidElement, useCallback, useContext, useEffect, useId, useMemo, useRef, useState } from "react";
|
|
4
|
+
import { cloneElement, createContext, isValidElement, useCallback, useContext, useEffect, useId, useLayoutEffect, useMemo, useRef, useState } from "react";
|
|
5
5
|
import { cn } from "@kumix/utils";
|
|
6
6
|
import { jsx } from "react/jsx-runtime";
|
|
7
|
-
import { AnimatePresence, animate, motion, useMotionValue, usePresence, useReducedMotion } from "motion/react";
|
|
7
|
+
import { AnimatePresence, animate, motion, useMotionValue, usePresence, useReducedMotion, useTransform } from "motion/react";
|
|
8
8
|
import { createPortal } from "react-dom";
|
|
9
9
|
//#region src/components/motion/popover-morph.tsx
|
|
10
10
|
const MorphContext = createContext(null);
|
|
@@ -14,9 +14,10 @@ function useMorphContext(component) {
|
|
|
14
14
|
return ctx;
|
|
15
15
|
}
|
|
16
16
|
/**
|
|
17
|
-
* A popover whose panel
|
|
18
|
-
*
|
|
19
|
-
*
|
|
17
|
+
* A popover whose full-size panel reveals from the corner nearest the trigger
|
|
18
|
+
* on one spring, then retraces the same clip on close. Content and surface
|
|
19
|
+
* edges keep their size throughout. Closes on outside pointer / Escape.
|
|
20
|
+
* Controlled or uncontrolled.
|
|
20
21
|
*/
|
|
21
22
|
function MorphPopover({ children, open: controlledOpen, defaultOpen = false, onOpenChange, className }) {
|
|
22
23
|
const baseId = useId();
|
|
@@ -111,16 +112,18 @@ function MorphPopoverTrigger({ children }) {
|
|
|
111
112
|
"aria-controls": ctx.open ? ctx.contentId : void 0
|
|
112
113
|
});
|
|
113
114
|
}
|
|
114
|
-
const
|
|
115
|
-
|
|
116
|
-
|
|
117
|
-
|
|
118
|
-
|
|
119
|
-
|
|
120
|
-
|
|
121
|
-
duration: .32,
|
|
115
|
+
const MORPH_ENTER = {
|
|
116
|
+
type: "spring",
|
|
117
|
+
duration: .26,
|
|
118
|
+
bounce: 0
|
|
119
|
+
};
|
|
120
|
+
const MORPH_EXIT = {
|
|
121
|
+
duration: .2,
|
|
122
122
|
ease: EASE_OUT
|
|
123
123
|
};
|
|
124
|
+
function clipAt(side, align, radius, inset) {
|
|
125
|
+
return `inset(${side === "top" ? inset : 0}% ${align === "start" ? inset : 0}% ${side === "bottom" ? inset : 0}% ${align === "end" ? inset : 0}% round ${radius}px)`;
|
|
126
|
+
}
|
|
124
127
|
function MorphPopoverContent(props) {
|
|
125
128
|
const ctx = useMorphContext("MorphPopoverContent");
|
|
126
129
|
const [portalReady, setPortalReady] = useState(false);
|
|
@@ -143,27 +146,10 @@ function MorphPopoverSurface({ children, side = "bottom", align = "end", sideOff
|
|
|
143
146
|
const availableHeight = resolvedSide === "bottom" ? below : above;
|
|
144
147
|
const left = layout ? Math.max(gutter, Math.min(preferredLeft, window.innerWidth - layout.content.width - gutter)) : 0;
|
|
145
148
|
const top = layout ? resolvedSide === "bottom" ? layout.trigger.top + layout.trigger.height + sideOffset : Math.max(gutter, layout.trigger.top - layout.content.height - sideOffset) : 0;
|
|
146
|
-
const
|
|
147
|
-
|
|
148
|
-
|
|
149
|
-
|
|
150
|
-
},
|
|
151
|
-
show: {
|
|
152
|
-
scale: 1,
|
|
153
|
-
transition: SPRING_PANEL
|
|
154
|
-
}
|
|
155
|
-
};
|
|
156
|
-
const clip = reduce ? void 0 : {
|
|
157
|
-
hidden: {
|
|
158
|
-
clipPath: clipAt(resolvedSide, align, radius, 92),
|
|
159
|
-
transition: MORPH_CLIP_TRANSITION
|
|
160
|
-
},
|
|
161
|
-
show: {
|
|
162
|
-
clipPath: clipAt(resolvedSide, align, radius, 0),
|
|
163
|
-
transition: MORPH_CLIP_TRANSITION
|
|
164
|
-
}
|
|
165
|
-
};
|
|
166
|
-
const opacity = useMotionValue(0);
|
|
149
|
+
const progress = useMotionValue(0);
|
|
150
|
+
const clipPath = useTransform(progress, (p) => clipAt(resolvedSide, align, radius, 92 * (1 - p)));
|
|
151
|
+
const surfaceOpacity = useTransform(progress, [0, .15], [0, 1]);
|
|
152
|
+
const fade = useMotionValue(reduce ? 0 : 1);
|
|
167
153
|
const ready = layout !== null;
|
|
168
154
|
const focusedOnOpen = useRef(false);
|
|
169
155
|
useEffect(() => {
|
|
@@ -176,39 +162,47 @@ function MorphPopoverSurface({ children, side = "bottom", align = "end", sideOff
|
|
|
176
162
|
ctx.contentRef,
|
|
177
163
|
onOpenAutoFocus
|
|
178
164
|
]);
|
|
165
|
+
const safeToRemoveRef = useRef(safeToRemove);
|
|
166
|
+
useLayoutEffect(() => {
|
|
167
|
+
safeToRemoveRef.current = safeToRemove;
|
|
168
|
+
});
|
|
179
169
|
useEffect(() => {
|
|
180
170
|
if (!ready) {
|
|
181
|
-
if (!isPresent)
|
|
171
|
+
if (!isPresent) safeToRemoveRef.current?.();
|
|
182
172
|
return;
|
|
183
173
|
}
|
|
184
|
-
const
|
|
185
|
-
|
|
186
|
-
|
|
187
|
-
|
|
188
|
-
|
|
174
|
+
const settle = () => {
|
|
175
|
+
if (!isPresent) safeToRemoveRef.current?.();
|
|
176
|
+
};
|
|
177
|
+
if (reduce) {
|
|
178
|
+
progress.jump(1);
|
|
179
|
+
const animation = animate(fade, isPresent ? 1 : 0, {
|
|
180
|
+
duration: .12,
|
|
181
|
+
onComplete: settle
|
|
182
|
+
});
|
|
183
|
+
return () => animation.stop();
|
|
184
|
+
}
|
|
185
|
+
const animation = animate(progress, isPresent ? 1 : 0, {
|
|
186
|
+
...isPresent ? MORPH_ENTER : MORPH_EXIT,
|
|
187
|
+
onComplete: settle
|
|
189
188
|
});
|
|
190
189
|
return () => animation.stop();
|
|
191
190
|
}, [
|
|
192
|
-
|
|
191
|
+
fade,
|
|
192
|
+
progress,
|
|
193
193
|
ready,
|
|
194
194
|
isPresent,
|
|
195
|
-
reduce
|
|
196
|
-
safeToRemove
|
|
195
|
+
reduce
|
|
197
196
|
]);
|
|
198
197
|
return /* @__PURE__ */ jsx(motion.div, {
|
|
199
198
|
"data-morph-popover-portal": "",
|
|
200
199
|
inert: !isPresent,
|
|
201
|
-
variants: wrap,
|
|
202
|
-
initial: "hidden",
|
|
203
|
-
animate: layout ? "show" : "hidden",
|
|
204
|
-
exit: "hidden",
|
|
205
200
|
style: {
|
|
206
201
|
left,
|
|
207
202
|
top,
|
|
208
|
-
opacity,
|
|
203
|
+
opacity: reduce ? fade : surfaceOpacity,
|
|
209
204
|
pointerEvents: isPresent ? "auto" : "none",
|
|
210
|
-
visibility: layout ? "visible" : "hidden"
|
|
211
|
-
transformOrigin: originFor(resolvedSide, align)
|
|
205
|
+
visibility: layout ? "visible" : "hidden"
|
|
212
206
|
},
|
|
213
207
|
className: cn("fixed z-9999", shadow && "filter-[drop-shadow(0_10px_18px_rgba(0,0,0,0.14))]"),
|
|
214
208
|
children: /* @__PURE__ */ jsx(motion.div, {
|
|
@@ -216,13 +210,11 @@ function MorphPopoverSurface({ children, side = "bottom", align = "end", sideOff
|
|
|
216
210
|
id: ctx.contentId,
|
|
217
211
|
role: "dialog",
|
|
218
212
|
"aria-labelledby": ctx.triggerId,
|
|
219
|
-
variants: clip,
|
|
220
|
-
initial: "hidden",
|
|
221
|
-
animate: layout ? "show" : "hidden",
|
|
222
|
-
exit: "hidden",
|
|
223
213
|
style: {
|
|
214
|
+
clipPath: reduce ? void 0 : clipPath,
|
|
224
215
|
borderRadius: radius,
|
|
225
216
|
maxHeight: layout ? availableHeight : void 0,
|
|
217
|
+
overflowX: "hidden",
|
|
226
218
|
overflowY: "auto"
|
|
227
219
|
},
|
|
228
220
|
className: cn("overflow-hidden border border-border bg-background", className),
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"popover-morph.js","names":[],"sources":["../../../src/components/motion/popover-morph.tsx"],"sourcesContent":["\"use client\";\n\nimport {\n cloneElement,\n createContext,\n isValidElement,\n type ReactElement,\n type ReactNode,\n type Ref,\n useCallback,\n useContext,\n useEffect,\n useId,\n useMemo,\n useRef,\n useState,\n} from \"react\";\nimport {\n AnimatePresence,\n animate,\n motion,\n useMotionValue,\n usePresence,\n useReducedMotion,\n} from \"motion/react\";\nimport { createPortal } from \"react-dom\";\n\nimport { cn } from \"@kumix/utils\";\nimport { EASE_OUT, SPRING_PANEL } from \"../../lib/ease\";\nimport { usePopoverPortalPosition } from \"./popover-position\";\n\ntype Side = \"top\" | \"bottom\";\ntype Align = \"start\" | \"end\";\n\ntype MorphContextValue = {\n open: boolean;\n setOpen: (open: boolean) => void;\n toggle: () => void;\n triggerId: string;\n contentId: string;\n /** The element the panel measures against — see `registerTrigger`. */\n triggerRef: React.MutableRefObject<HTMLElement | null>;\n registerTrigger: (node: HTMLElement | null) => void;\n contentRef: React.MutableRefObject<HTMLDivElement | null>;\n};\n\nconst MorphContext = createContext<MorphContextValue | null>(null);\n\nfunction useMorphContext(component: string) {\n const ctx = useContext(MorphContext);\n if (!ctx) throw new Error(`${component} must be used within <MorphPopover>`);\n return ctx;\n}\n\nexport interface MorphPopoverProps {\n children: ReactNode;\n /** Controlled open state. */\n open?: boolean;\n /** Uncontrolled initial open state. */\n defaultOpen?: boolean;\n onOpenChange?: (open: boolean) => void;\n className?: string;\n}\n\n/**\n * A popover whose panel morphs open from the trigger corner: it's laid out at\n * full size but clipped to the corner nearest the trigger, then unclips as one\n * piece. Closes on outside pointer / Escape. Controlled or uncontrolled.\n */\nexport function MorphPopover({\n children,\n open: controlledOpen,\n defaultOpen = false,\n onOpenChange,\n className,\n}: MorphPopoverProps) {\n const baseId = useId();\n const [root, setRoot] = useState<HTMLDivElement | null>(null);\n const [trigger, setTrigger] = useState<HTMLElement | null>(null);\n const contentRef = useRef<HTMLDivElement | null>(null);\n const [internalOpen, setInternalOpen] = useState(defaultOpen);\n const controlled = controlledOpen !== undefined;\n const open = controlled ? controlledOpen : internalOpen;\n\n const setOpen = useCallback(\n (next: boolean) => {\n if (!controlled) setInternalOpen(next);\n onOpenChange?.(next);\n },\n [controlled, onOpenChange],\n );\n const toggle = useCallback(() => setOpen(!open), [setOpen, open]);\n\n // A trigger normally registers itself through MorphPopoverTrigger. It can't\n // when something else already clones the element — a Tooltip wrapping the\n // button, say — and an unregistered trigger leaves the panel with nothing to\n // measure against, so it renders permanently invisible. The root boxes the\n // trigger exactly (the content portals out of it), so it stands in until a\n // real trigger registers, and stands in again if that one unmounts. Both are\n // state, so a trigger arriving while the panel is open re-anchors it.\n const anchorRef = useMemo<React.MutableRefObject<HTMLElement | null>>(\n () => ({ current: trigger ?? root }),\n [root, trigger],\n );\n\n // The panel is a `role=\"dialog\"` and goes inert the moment it closes, so\n // focus cannot be left sitting inside it: a dismissal hands it back to the\n // trigger, the way the ARIA dialog pattern asks. A pointer dismissal takes\n // the focus onward itself when it lands on something focusable — this only\n // catches the case where it would otherwise be stranded. When no trigger has\n // registered, the root anchor stands in only if it can actually hold focus;\n // there is nowhere better than where the keyboard already is, so leave it.\n const close = useCallback(() => {\n setOpen(false);\n const focused = document.activeElement;\n const inPanel = focused instanceof HTMLElement && contentRef.current?.contains(focused);\n if (!inPanel) return;\n const restore = trigger ?? (root && root.tabIndex >= 0 ? root : null);\n restore?.focus();\n }, [root, setOpen, trigger]);\n\n useEffect(() => {\n if (!open) return;\n const onKey = (e: KeyboardEvent) => e.key === \"Escape\" && close();\n const onPointer = (e: PointerEvent) => {\n const target = e.target as Node;\n if (root && !root.contains(target) && !contentRef.current?.contains(target)) close();\n };\n window.addEventListener(\"keydown\", onKey);\n window.addEventListener(\"pointerdown\", onPointer);\n return () => {\n window.removeEventListener(\"keydown\", onKey);\n window.removeEventListener(\"pointerdown\", onPointer);\n };\n }, [open, root, close]);\n\n const ctx = useMemo<MorphContextValue>(\n () => ({\n open,\n setOpen,\n toggle,\n triggerId: `${baseId}-trigger`,\n contentId: `${baseId}-content`,\n triggerRef: anchorRef,\n registerTrigger: setTrigger,\n contentRef,\n }),\n [open, setOpen, toggle, baseId, anchorRef],\n );\n\n return (\n <MorphContext.Provider value={ctx}>\n <div ref={setRoot} className={cn(\"relative inline-flex\", className)}>\n {children}\n </div>\n </MorphContext.Provider>\n );\n}\n\nexport interface MorphPopoverTriggerProps {\n children: ReactElement;\n}\n\nfunction mergeRefs<T>(...refs: Array<Ref<T> | undefined>) {\n return (node: T | null) => {\n for (const ref of refs) {\n if (typeof ref === \"function\") ref(node);\n else if (ref && typeof ref === \"object\")\n (ref as React.MutableRefObject<T | null>).current = node;\n }\n };\n}\n\n/** Wraps a single element, toggling the popover on click. */\nexport function MorphPopoverTrigger({ children }: MorphPopoverTriggerProps) {\n const ctx = useMorphContext(\"MorphPopoverTrigger\");\n const child = children as ReactElement<Record<string, unknown>>;\n const childOnClick = child?.props?.onClick as ((e: unknown) => void) | undefined;\n const childRef = (child?.props as { ref?: Ref<HTMLElement> } | undefined)?.ref;\n // Register once per actual ref change, not once per open-state render.\n const mergedRef = useMemo(\n () => mergeRefs(childRef, ctx.registerTrigger),\n [childRef, ctx.registerTrigger],\n );\n if (!isValidElement(children)) return children;\n\n return cloneElement(child, {\n id: ctx.triggerId,\n ref: mergedRef,\n onClick: (e: unknown) => {\n childOnClick?.(e);\n ctx.toggle();\n },\n \"aria-haspopup\": \"dialog\",\n \"aria-expanded\": ctx.open,\n \"aria-controls\": ctx.open ? ctx.contentId : undefined,\n });\n}\n\nconst originFor = (side: Side, align: Align) =>\n `${side === \"bottom\" ? \"top\" : \"bottom\"} ${align === \"end\" ? \"right\" : \"left\"}`;\n\n// A clip that hides everything but the corner nearest the trigger, so the\n// panel appears to grow out of it. inset(top right bottom left).\nfunction clipAt(side: Side, align: Align, radius: number, inset: number) {\n const top = side === \"bottom\" ? \"0%\" : `${inset}%`;\n const bottom = side === \"bottom\" ? `${inset}%` : \"0%\";\n const right = align === \"end\" ? \"0%\" : `${inset}%`;\n const left = align === \"end\" ? `${inset}%` : \"0%\";\n return `inset(${top} ${right} ${bottom} ${left} round ${radius}px)`;\n}\n\n// Preserve the original spring character on the wrapper, but tween the complex\n// clip-path so it cannot snap when the spring resolves its final distance.\nconst MORPH_CLIP_TRANSITION = { duration: 0.32, ease: EASE_OUT } as const;\n\nexport interface MorphPopoverContentProps {\n children: ReactNode;\n side?: Side;\n align?: Align;\n /** Gap between trigger and panel, in px. Default 8. */\n sideOffset?: number;\n /** Panel corner radius, in px. Default 16. */\n radius?: number;\n /** Draw the surface shadow. Default true. */\n shadow?: boolean;\n /** Runs after the portalled surface is positioned and visible. */\n onOpenAutoFocus?: (content: HTMLDivElement) => void;\n className?: string;\n}\n\nexport function MorphPopoverContent(props: MorphPopoverContentProps) {\n const ctx = useMorphContext(\"MorphPopoverContent\");\n const [portalReady, setPortalReady] = useState(false);\n useEffect(() => setPortalReady(true), []);\n if (!portalReady) return null;\n return createPortal(\n <AnimatePresence>{ctx.open && <MorphPopoverSurface {...props} />}</AnimatePresence>,\n document.body,\n );\n}\n\n// Measurement belongs to the mounted portal session: reopening must not start\n// an entrance at the previous session's coordinates before measuring this one.\nfunction MorphPopoverSurface({\n children,\n side = \"bottom\",\n align = \"end\",\n sideOffset = 8,\n radius = 16,\n shadow = true,\n onOpenAutoFocus,\n className,\n}: MorphPopoverContentProps) {\n const ctx = useMorphContext(\"MorphPopoverContent\");\n const reduce = useReducedMotion() ?? false;\n const [isPresent, safeToRemove] = usePresence();\n const layout = usePopoverPortalPosition(ctx.triggerRef, ctx.contentRef, isPresent);\n\n const preferredLeft = layout\n ? align === \"end\"\n ? layout.trigger.left + layout.trigger.width - layout.content.width\n : layout.trigger.left\n : 0;\n // Keep larger compositions, such as calendars, inside the viewport. Prefer\n // the requested side, then use the roomier side when it cannot fit there.\n const gutter = 12;\n const below = layout\n ? Math.max(\n 0,\n window.innerHeight - layout.trigger.top - layout.trigger.height - sideOffset - gutter,\n )\n : 0;\n const above = layout ? Math.max(0, layout.trigger.top - sideOffset - gutter) : 0;\n const requestedSpace = side === \"bottom\" ? below : above;\n const otherSpace = side === \"bottom\" ? above : below;\n const resolvedSide =\n layout && layout.content.height > requestedSpace && otherSpace > requestedSpace\n ? side === \"bottom\"\n ? \"top\"\n : \"bottom\"\n : side;\n const availableHeight = resolvedSide === \"bottom\" ? below : above;\n const left = layout\n ? Math.max(gutter, Math.min(preferredLeft, window.innerWidth - layout.content.width - gutter))\n : 0;\n const top = layout\n ? resolvedSide === \"bottom\"\n ? layout.trigger.top + layout.trigger.height + sideOffset\n : Math.max(gutter, layout.trigger.top - layout.content.height - sideOffset)\n : 0;\n\n // Both directions travel between the exact same hidden/show states. Exit\n // targets \"hidden\" directly instead of introducing separate choreography.\n const wrap = reduce\n ? undefined\n : {\n hidden: { scale: 0.96, transition: SPRING_PANEL },\n show: { scale: 1, transition: SPRING_PANEL },\n };\n const clip = reduce\n ? undefined\n : {\n hidden: {\n clipPath: clipAt(resolvedSide, align, radius, 92),\n transition: MORPH_CLIP_TRANSITION,\n },\n show: {\n clipPath: clipAt(resolvedSide, align, radius, 0),\n transition: MORPH_CLIP_TRANSITION,\n },\n };\n // Animate the value directly so opacity stays in the inline style throughout\n // the entrance. A native opacity animation can expose the initial inline 0\n // for a frame when it finishes, before Motion writes the final value.\n const opacity = useMotionValue(0);\n const ready = layout !== null;\n const focusedOnOpen = useRef(false);\n useEffect(() => {\n if (!ready || !isPresent || focusedOnOpen.current || !ctx.contentRef.current) return;\n focusedOnOpen.current = true;\n onOpenAutoFocus?.(ctx.contentRef.current);\n }, [ready, isPresent, ctx.contentRef, onOpenAutoFocus]);\n useEffect(() => {\n if (!ready) {\n if (!isPresent) safeToRemove?.();\n return;\n }\n const animation = animate(opacity, isPresent ? 1 : 0, {\n ...(reduce ? { duration: 0.12 } : SPRING_PANEL),\n onComplete: () => {\n if (!isPresent) safeToRemove?.();\n },\n });\n return () => animation.stop();\n }, [opacity, ready, isPresent, reduce, safeToRemove]);\n\n return (\n <motion.div\n data-morph-popover-portal=\"\"\n inert={!isPresent}\n // Wrapper carries the shadow as a drop-shadow filter, which hugs the\n // clipped shape below (box-shadow would just get clipped away).\n variants={wrap}\n initial=\"hidden\"\n animate={layout ? \"show\" : \"hidden\"}\n exit=\"hidden\"\n style={{\n left,\n top,\n opacity,\n pointerEvents: isPresent ? \"auto\" : \"none\",\n visibility: layout ? \"visible\" : \"hidden\",\n transformOrigin: originFor(resolvedSide, align),\n }}\n className={cn(\"fixed z-9999\", shadow && \"filter-[drop-shadow(0_10px_18px_rgba(0,0,0,0.14))]\")}\n >\n <motion.div\n ref={ctx.contentRef}\n id={ctx.contentId}\n role=\"dialog\"\n aria-labelledby={ctx.triggerId}\n // Own states rather than inherited ones: reopening during the close\n // cancels the exit per element, and only an element that owns its\n // target returns to it. Inherited, the clip stayed at its hidden corner.\n variants={clip}\n initial=\"hidden\"\n animate={layout ? \"show\" : \"hidden\"}\n exit=\"hidden\"\n style={{\n borderRadius: radius,\n maxHeight: layout ? availableHeight : undefined,\n overflowY: \"auto\",\n }}\n className={cn(\"overflow-hidden border border-border bg-background\", className)}\n >\n {children}\n </motion.div>\n </motion.div>\n );\n}\n"],"mappings":";;;;;;;;;AA8CA,MAAM,eAAe,cAAwC,IAAI;AAEjE,SAAS,gBAAgB,WAAmB;CAC1C,MAAM,MAAM,WAAW,YAAY;CACnC,IAAI,CAAC,KAAK,MAAM,IAAI,MAAM,GAAG,UAAU,oCAAoC;CAC3E,OAAO;AACT;;;;;;AAiBA,SAAgB,aAAa,EAC3B,UACA,MAAM,gBACN,cAAc,OACd,cACA,aACoB;CACpB,MAAM,SAAS,MAAM;CACrB,MAAM,CAAC,MAAM,WAAW,SAAgC,IAAI;CAC5D,MAAM,CAAC,SAAS,cAAc,SAA6B,IAAI;CAC/D,MAA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,eAAe,YAAY,SAAS;GACpC,YAAY,SAAS,YAAY;GACjC,iBAAiB,UAAU,cAAc,KAAK;EAChD;EACA,WAAW,GAAG,gBAAgB,UAAU,oDAAoD;EAE5F,UAAA,oBAAC,OAAO,KAAR;GACE,KAAK,IAAI;GACT,IAAI,IAAI;GACR,MAAK;GACL,mBAAiB,IAAI;GAIrB,UAAU;GACV,SAAQ;GACR,SAAS,SAAS,SAAS;GAC3B,MAAK;GACL,OAAO;IACL,cAAc;IACd,WAAW,SAAS,kBAAkB,KAAA;IACtC,WAAW;GACb;GACA,WAAW,GAAG,sDAAsD,SAAS;GAE5E;EACS,CAAA;CACF,CAAA;AAEhB"}
|
|
1
|
+
{"version":3,"file":"popover-morph.js","names":[],"sources":["../../../src/components/motion/popover-morph.tsx"],"sourcesContent":["\"use client\";\n\nimport {\n cloneElement,\n createContext,\n isValidElement,\n type ReactElement,\n type ReactNode,\n type Ref,\n useCallback,\n useContext,\n useEffect,\n useId,\n useLayoutEffect,\n useMemo,\n useRef,\n useState,\n} from \"react\";\nimport {\n AnimatePresence,\n animate,\n motion,\n useMotionValue,\n usePresence,\n useReducedMotion,\n useTransform,\n} from \"motion/react\";\nimport { createPortal } from \"react-dom\";\n\nimport { cn } from \"@kumix/utils\";\nimport { EASE_OUT } from \"../../lib/ease\";\nimport { usePopoverPortalPosition } from \"./popover-position\";\n\ntype Side = \"top\" | \"bottom\";\ntype Align = \"start\" | \"end\";\n\ntype MorphContextValue = {\n open: boolean;\n setOpen: (open: boolean) => void;\n toggle: () => void;\n triggerId: string;\n contentId: string;\n /** The element the panel measures against — see `registerTrigger`. */\n triggerRef: React.MutableRefObject<HTMLElement | null>;\n registerTrigger: (node: HTMLElement | null) => void;\n contentRef: React.MutableRefObject<HTMLDivElement | null>;\n};\n\nconst MorphContext = createContext<MorphContextValue | null>(null);\n\nfunction useMorphContext(component: string) {\n const ctx = useContext(MorphContext);\n if (!ctx) throw new Error(`${component} must be used within <MorphPopover>`);\n return ctx;\n}\n\nexport interface MorphPopoverProps {\n children: ReactNode;\n /** Controlled open state. */\n open?: boolean;\n /** Uncontrolled initial open state. */\n defaultOpen?: boolean;\n onOpenChange?: (open: boolean) => void;\n className?: string;\n}\n\n/**\n * A popover whose full-size panel reveals from the corner nearest the trigger\n * on one spring, then retraces the same clip on close. Content and surface\n * edges keep their size throughout. Closes on outside pointer / Escape.\n * Controlled or uncontrolled.\n */\nexport function MorphPopover({\n children,\n open: controlledOpen,\n defaultOpen = false,\n onOpenChange,\n className,\n}: MorphPopoverProps) {\n const baseId = useId();\n const [root, setRoot] = useState<HTMLDivElement | null>(null);\n const [trigger, setTrigger] = useState<HTMLElement | null>(null);\n const contentRef = useRef<HTMLDivElement | null>(null);\n const [internalOpen, setInternalOpen] = useState(defaultOpen);\n const controlled = controlledOpen !== undefined;\n const open = controlled ? controlledOpen : internalOpen;\n\n const setOpen = useCallback(\n (next: boolean) => {\n if (!controlled) setInternalOpen(next);\n onOpenChange?.(next);\n },\n [controlled, onOpenChange],\n );\n const toggle = useCallback(() => setOpen(!open), [setOpen, open]);\n\n // A trigger normally registers itself through MorphPopoverTrigger. It can't\n // when something else already clones the element — a Tooltip wrapping the\n // button, say — and an unregistered trigger leaves the panel with nothing to\n // measure against, so it renders permanently invisible. The root boxes the\n // trigger exactly (the content portals out of it), so it stands in until a\n // real trigger registers, and stands in again if that one unmounts. Both are\n // state, so a trigger arriving while the panel is open re-anchors it.\n const anchorRef = useMemo<React.MutableRefObject<HTMLElement | null>>(\n () => ({ current: trigger ?? root }),\n [root, trigger],\n );\n\n // The panel is a `role=\"dialog\"` and goes inert the moment it closes, so\n // focus cannot be left sitting inside it: a dismissal hands it back to the\n // trigger, the way the ARIA dialog pattern asks. A pointer dismissal takes\n // the focus onward itself when it lands on something focusable — this only\n // catches the case where it would otherwise be stranded. When no trigger has\n // registered, the root anchor stands in only if it can actually hold focus;\n // there is nowhere better than where the keyboard already is, so leave it.\n const close = useCallback(() => {\n setOpen(false);\n const focused = document.activeElement;\n const inPanel = focused instanceof HTMLElement && contentRef.current?.contains(focused);\n if (!inPanel) return;\n const restore = trigger ?? (root && root.tabIndex >= 0 ? root : null);\n restore?.focus();\n }, [root, setOpen, trigger]);\n\n useEffect(() => {\n if (!open) return;\n const onKey = (e: KeyboardEvent) => e.key === \"Escape\" && close();\n const onPointer = (e: PointerEvent) => {\n const target = e.target as Node;\n if (root && !root.contains(target) && !contentRef.current?.contains(target)) close();\n };\n window.addEventListener(\"keydown\", onKey);\n window.addEventListener(\"pointerdown\", onPointer);\n return () => {\n window.removeEventListener(\"keydown\", onKey);\n window.removeEventListener(\"pointerdown\", onPointer);\n };\n }, [open, root, close]);\n\n const ctx = useMemo<MorphContextValue>(\n () => ({\n open,\n setOpen,\n toggle,\n triggerId: `${baseId}-trigger`,\n contentId: `${baseId}-content`,\n triggerRef: anchorRef,\n registerTrigger: setTrigger,\n contentRef,\n }),\n [open, setOpen, toggle, baseId, anchorRef],\n );\n\n return (\n <MorphContext.Provider value={ctx}>\n <div ref={setRoot} className={cn(\"relative inline-flex\", className)}>\n {children}\n </div>\n </MorphContext.Provider>\n );\n}\n\nexport interface MorphPopoverTriggerProps {\n children: ReactElement;\n}\n\nfunction mergeRefs<T>(...refs: Array<Ref<T> | undefined>) {\n return (node: T | null) => {\n for (const ref of refs) {\n if (typeof ref === \"function\") ref(node);\n else if (ref && typeof ref === \"object\")\n (ref as React.MutableRefObject<T | null>).current = node;\n }\n };\n}\n\n/** Wraps a single element, toggling the popover on click. */\nexport function MorphPopoverTrigger({ children }: MorphPopoverTriggerProps) {\n const ctx = useMorphContext(\"MorphPopoverTrigger\");\n const child = children as ReactElement<Record<string, unknown>>;\n const childOnClick = child?.props?.onClick as ((e: unknown) => void) | undefined;\n const childRef = (child?.props as { ref?: Ref<HTMLElement> } | undefined)?.ref;\n // Register once per actual ref change, not once per open-state render.\n const mergedRef = useMemo(\n () => mergeRefs(childRef, ctx.registerTrigger),\n [childRef, ctx.registerTrigger],\n );\n if (!isValidElement(children)) return children;\n\n return cloneElement(child, {\n id: ctx.triggerId,\n ref: mergedRef,\n onClick: (e: unknown) => {\n childOnClick?.(e);\n ctx.toggle();\n },\n \"aria-haspopup\": \"dialog\",\n \"aria-expanded\": ctx.open,\n \"aria-controls\": ctx.open ? ctx.contentId : undefined,\n });\n}\n\n// Full-distance clip travel needs a shorter curve than SPRING_PANEL's slow\n// overdamped tail. A non-bouncing spring reaches its rest within 260 ms.\nconst MORPH_ENTER = { type: \"spring\", duration: 0.26, bounce: 0 } as const;\nconst MORPH_EXIT = { duration: 0.2, ease: EASE_OUT } as const;\n\n// Keep the panel and content at their final size. An inset clip reveals the\n// nearest corner without scaling borders, shadows or keyboard-focus geometry.\n// A full-size clip keeps content at its final coordinates without box-to-box\n// scale correction. One progress value keeps clip and opacity synchronized;\n// clip-path and the shadow may paint, so this is not a compositor-only morph.\nfunction clipAt(side: Side, align: Align, radius: number, inset: number) {\n return `inset(${side === \"top\" ? inset : 0}% ${align === \"start\" ? inset : 0}% ${side === \"bottom\" ? inset : 0}% ${align === \"end\" ? inset : 0}% round ${radius}px)`;\n}\n\nexport interface MorphPopoverContentProps {\n children: ReactNode;\n side?: Side;\n align?: Align;\n /** Gap between trigger and panel, in px. Default 8. */\n sideOffset?: number;\n /** Panel corner radius, in px. Default 16. */\n radius?: number;\n /** Draw the surface shadow. Default true. */\n shadow?: boolean;\n /** Runs after the portalled surface is positioned and visible. */\n onOpenAutoFocus?: (content: HTMLDivElement) => void;\n className?: string;\n}\n\nexport function MorphPopoverContent(props: MorphPopoverContentProps) {\n const ctx = useMorphContext(\"MorphPopoverContent\");\n const [portalReady, setPortalReady] = useState(false);\n useEffect(() => setPortalReady(true), []);\n if (!portalReady) return null;\n return createPortal(\n <AnimatePresence>{ctx.open && <MorphPopoverSurface {...props} />}</AnimatePresence>,\n document.body,\n );\n}\n\n// Measurement belongs to the mounted portal session: reopening must not start\n// an entrance at the previous session's coordinates before measuring this one.\nfunction MorphPopoverSurface({\n children,\n side = \"bottom\",\n align = \"end\",\n sideOffset = 8,\n radius = 16,\n shadow = true,\n onOpenAutoFocus,\n className,\n}: MorphPopoverContentProps) {\n const ctx = useMorphContext(\"MorphPopoverContent\");\n const reduce = useReducedMotion() ?? false;\n const [isPresent, safeToRemove] = usePresence();\n const layout = usePopoverPortalPosition(ctx.triggerRef, ctx.contentRef, isPresent);\n\n const preferredLeft = layout\n ? align === \"end\"\n ? layout.trigger.left + layout.trigger.width - layout.content.width\n : layout.trigger.left\n : 0;\n // Keep larger compositions, such as calendars, inside the viewport. Prefer\n // the requested side, then use the roomier side when it cannot fit there.\n const gutter = 12;\n const below = layout\n ? Math.max(\n 0,\n window.innerHeight - layout.trigger.top - layout.trigger.height - sideOffset - gutter,\n )\n : 0;\n const above = layout ? Math.max(0, layout.trigger.top - sideOffset - gutter) : 0;\n const requestedSpace = side === \"bottom\" ? below : above;\n const otherSpace = side === \"bottom\" ? above : below;\n const resolvedSide =\n layout && layout.content.height > requestedSpace && otherSpace > requestedSpace\n ? side === \"bottom\"\n ? \"top\"\n : \"bottom\"\n : side;\n const availableHeight = resolvedSide === \"bottom\" ? below : above;\n const left = layout\n ? Math.max(gutter, Math.min(preferredLeft, window.innerWidth - layout.content.width - gutter))\n : 0;\n const top = layout\n ? resolvedSide === \"bottom\"\n ? layout.trigger.top + layout.trigger.height + sideOffset\n : Math.max(gutter, layout.trigger.top - layout.content.height - sideOffset)\n : 0;\n\n const progress = useMotionValue(0);\n const clipPath = useTransform(progress, (p) => clipAt(resolvedSide, align, radius, 92 * (1 - p)));\n const surfaceOpacity = useTransform(progress, [0, 0.15], [0, 1]);\n // Reduced motion has no travel, so a short fade carries the whole entrance\n // and exit on its own.\n const fade = useMotionValue(reduce ? 0 : 1);\n const ready = layout !== null;\n const focusedOnOpen = useRef(false);\n useEffect(() => {\n if (!ready || !isPresent || focusedOnOpen.current || !ctx.contentRef.current) return;\n focusedOnOpen.current = true;\n onOpenAutoFocus?.(ctx.contentRef.current);\n }, [ready, isPresent, ctx.contentRef, onOpenAutoFocus]);\n // `safeToRemove` is a new function on every render: AnimatePresence\n // rebuilds its context each time its parent renders. Read it through a ref\n // so a render during the exit (a consumer's state change, a list streaming\n // in) does not restart the exit from where it got to — restarted every\n // render, it would close in ever smaller steps and never report completion,\n // leaving an inert, invisible panel mounted for good.\n const safeToRemoveRef = useRef(safeToRemove);\n useLayoutEffect(() => {\n safeToRemoveRef.current = safeToRemove;\n });\n useEffect(() => {\n if (!ready) {\n if (!isPresent) safeToRemoveRef.current?.();\n return;\n }\n const settle = () => {\n if (!isPresent) safeToRemoveRef.current?.();\n };\n if (reduce) {\n progress.jump(1);\n const animation = animate(fade, isPresent ? 1 : 0, {\n duration: 0.12,\n onComplete: settle,\n });\n return () => animation.stop();\n }\n const animation = animate(progress, isPresent ? 1 : 0, {\n ...(isPresent ? MORPH_ENTER : MORPH_EXIT),\n onComplete: settle,\n });\n return () => animation.stop();\n }, [fade, progress, ready, isPresent, reduce]);\n\n return (\n <motion.div\n data-morph-popover-portal=\"\"\n inert={!isPresent}\n style={{\n left,\n top,\n opacity: reduce ? fade : surfaceOpacity,\n pointerEvents: isPresent ? \"auto\" : \"none\",\n visibility: layout ? \"visible\" : \"hidden\",\n }}\n // A drop-shadow follows the clipped surface; box-shadow would be cut\n // off by its own clip. Caller surface classes retain their old target.\n className={cn(\"fixed z-9999\", shadow && \"filter-[drop-shadow(0_10px_18px_rgba(0,0,0,0.14))]\")}\n >\n <motion.div\n ref={ctx.contentRef}\n id={ctx.contentId}\n role=\"dialog\"\n aria-labelledby={ctx.triggerId}\n style={{\n clipPath: reduce ? undefined : clipPath,\n borderRadius: radius,\n maxHeight: layout ? availableHeight : undefined,\n overflowX: \"hidden\",\n overflowY: \"auto\",\n }}\n className={cn(\"overflow-hidden border border-border bg-background\", className)}\n >\n {children}\n </motion.div>\n </motion.div>\n );\n}\n"],"mappings":";;;;;;;;;AAgDA,MAAM,eAAe,cAAwC,IAAI;AAEjE,SAAS,gBAAgB,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