feat: migrate Modal Popover and Tooltip with shared overlay foundation
This commit is contained in:
@@ -0,0 +1,195 @@
|
||||
import {
|
||||
Comment,
|
||||
Fragment,
|
||||
Text,
|
||||
cloneVNode,
|
||||
defineComponent,
|
||||
h,
|
||||
isVNode,
|
||||
ref,
|
||||
type VNode,
|
||||
type PropType,
|
||||
} from "vue";
|
||||
import { useForwardExpose } from "reka-ui";
|
||||
import { useInheritedDisabled } from "../field/disabled";
|
||||
|
||||
export function overlayNodes(children: unknown): VNode[] {
|
||||
const result: VNode[] = [];
|
||||
for (const child of Array.isArray(children) ? children : [children]) {
|
||||
if (Array.isArray(child)) result.push(...overlayNodes(child));
|
||||
else if (isVNode(child)) {
|
||||
if (child.type === Fragment) result.push(...overlayNodes(child.children));
|
||||
else if (
|
||||
child.type !== Comment &&
|
||||
!(child.type === Text && !String(child.children).trim())
|
||||
)
|
||||
result.push(child);
|
||||
}
|
||||
}
|
||||
return result;
|
||||
}
|
||||
export function overlayComponentName(node: VNode): string {
|
||||
const type = node.type as { name?: string; __name?: string };
|
||||
return typeof node.type === "object" ? (type.name ?? type.__name ?? "") : "";
|
||||
}
|
||||
function handlers(value: unknown): ((event: Event) => void)[] {
|
||||
if (Array.isArray(value)) return value.flatMap(handlers);
|
||||
return typeof value === "function" ? [value as (event: Event) => void] : [];
|
||||
}
|
||||
|
||||
/** Native DOM listener arrays keep cancel/stop semantics. No synthetic emit or invoker internals. */
|
||||
export default defineComponent({
|
||||
name: "OverlayAction",
|
||||
inheritAttrs: false,
|
||||
props: {
|
||||
as: { type: String, default: "button" },
|
||||
asChild: Boolean,
|
||||
isDisabled: Boolean,
|
||||
activate: { type: Function as PropType<() => void>, required: true },
|
||||
},
|
||||
setup(props, { attrs, slots }) {
|
||||
const inherited = useInheritedDisabled(() => props.isDisabled);
|
||||
const { forwardRef } = useForwardExpose();
|
||||
const spaceDown = ref(false);
|
||||
return () => {
|
||||
const children = slots.default?.();
|
||||
const nodes = overlayNodes(children);
|
||||
if (
|
||||
props.asChild &&
|
||||
(nodes.length !== 1 || typeof nodes[0]?.type === "symbol")
|
||||
)
|
||||
throw new Error(
|
||||
"Overlay trigger asChild requires one element or component root.",
|
||||
);
|
||||
const child = props.asChild ? nodes[0]! : undefined;
|
||||
const original = child?.props ?? {};
|
||||
const disabled = () =>
|
||||
inherited.value ||
|
||||
original.isDisabled === true ||
|
||||
original.disabled === true ||
|
||||
original.isPending === true ||
|
||||
original.loading === true ||
|
||||
attrs.disabled === true;
|
||||
const guard = (event: Event) => {
|
||||
if (disabled()) {
|
||||
event.preventDefault();
|
||||
event.stopImmediatePropagation();
|
||||
spaceDown.value = false;
|
||||
}
|
||||
};
|
||||
const native = (el: EventTarget | null) =>
|
||||
el instanceof HTMLElement &&
|
||||
(el.tagName === "BUTTON" ||
|
||||
el.tagName === "INPUT" ||
|
||||
(el.tagName === "A" && el.hasAttribute("href")));
|
||||
const keyboardDown = (event: KeyboardEvent) => {
|
||||
if (
|
||||
event.defaultPrevented ||
|
||||
event.repeat ||
|
||||
event.isComposing ||
|
||||
native(event.currentTarget)
|
||||
)
|
||||
return;
|
||||
if (event.key === "Enter") {
|
||||
event.preventDefault();
|
||||
(event.currentTarget as HTMLElement).click();
|
||||
}
|
||||
if (event.key === " ") {
|
||||
event.preventDefault();
|
||||
spaceDown.value = true;
|
||||
}
|
||||
};
|
||||
const keyboardUp = (event: KeyboardEvent) => {
|
||||
const pressed = spaceDown.value;
|
||||
spaceDown.value = false;
|
||||
if (
|
||||
event.key === " " &&
|
||||
pressed &&
|
||||
!event.defaultPrevented &&
|
||||
!native(event.currentTarget)
|
||||
) {
|
||||
event.preventDefault();
|
||||
(event.currentTarget as HTMLElement).click();
|
||||
}
|
||||
};
|
||||
const tag = child
|
||||
? typeof child.type === "string"
|
||||
? child.type
|
||||
: undefined
|
||||
: props.as;
|
||||
const custom =
|
||||
tag &&
|
||||
!["button", "input"].includes(tag) &&
|
||||
!(tag === "a" && (original.href ?? attrs.href));
|
||||
const merged = {
|
||||
...attrs,
|
||||
type:
|
||||
attrs.type ??
|
||||
(props.as === "button" || child?.type === "button"
|
||||
? "button"
|
||||
: undefined),
|
||||
role: attrs.role ?? original.role ?? (custom ? "button" : undefined),
|
||||
tabindex:
|
||||
attrs.tabindex ??
|
||||
original.tabindex ??
|
||||
(custom ? (disabled() ? -1 : 0) : undefined),
|
||||
disabled: disabled() || undefined,
|
||||
"aria-disabled": disabled() || undefined,
|
||||
onClickCapture: [
|
||||
guard,
|
||||
...handlers(attrs.onClickCapture),
|
||||
...handlers(original.onClickCapture),
|
||||
],
|
||||
onKeydownCapture: [
|
||||
guard,
|
||||
...handlers(attrs.onKeydownCapture),
|
||||
...handlers(original.onKeydownCapture),
|
||||
],
|
||||
onKeyupCapture: [
|
||||
guard,
|
||||
...handlers(attrs.onKeyupCapture),
|
||||
...handlers(original.onKeyupCapture),
|
||||
],
|
||||
onClick: [
|
||||
...handlers(original.onClick),
|
||||
...handlers(attrs.onClick),
|
||||
(event: Event) => {
|
||||
if (!event.defaultPrevented && !disabled()) props.activate();
|
||||
},
|
||||
],
|
||||
onKeydown: [
|
||||
...handlers(original.onKeydown),
|
||||
...handlers(attrs.onKeydown),
|
||||
keyboardDown,
|
||||
],
|
||||
onKeyup: [
|
||||
...handlers(original.onKeyup),
|
||||
...handlers(attrs.onKeyup),
|
||||
keyboardUp,
|
||||
],
|
||||
onBlur: [
|
||||
...handlers(original.onBlur),
|
||||
...handlers(attrs.onBlur),
|
||||
() => {
|
||||
spaceDown.value = false;
|
||||
},
|
||||
],
|
||||
ref: forwardRef,
|
||||
};
|
||||
if (!child) return h(props.as, merged, children);
|
||||
const copy = cloneVNode(child);
|
||||
copy.props = { ...original };
|
||||
for (const event of [
|
||||
"onClick",
|
||||
"onClickCapture",
|
||||
"onKeydown",
|
||||
"onKeyup",
|
||||
"onKeydownCapture",
|
||||
"onKeyupCapture",
|
||||
"onBlur",
|
||||
])
|
||||
delete copy.props[event];
|
||||
return cloneVNode(copy, merged, true);
|
||||
};
|
||||
},
|
||||
});
|
||||
@@ -0,0 +1,30 @@
|
||||
import { cloneVNode, defineComponent, h } from "vue";
|
||||
import { overlayNodes } from "./OverlayAction";
|
||||
/** Canonical arrow path from HeroUI ce90ea3 (Apache-2.0); custom SVGs keep the styling slot. */
|
||||
export default defineComponent({
|
||||
inheritAttrs: false,
|
||||
props: { marker: { type: String, required: true } },
|
||||
setup(props, { attrs, slots }) {
|
||||
return () => {
|
||||
const nodes = overlayNodes(slots.default?.());
|
||||
if (nodes.length > 1)
|
||||
throw new Error("Overlay arrow requires one custom SVG root.");
|
||||
return nodes[0]
|
||||
? cloneVNode(nodes[0], { ...attrs, "data-slot": props.marker })
|
||||
: h(
|
||||
"svg",
|
||||
{
|
||||
...attrs,
|
||||
"aria-hidden": true,
|
||||
"data-slot": props.marker,
|
||||
fill: "none",
|
||||
width: 12,
|
||||
height: 12,
|
||||
viewBox: "0 0 12 12",
|
||||
xmlns: "http://www.w3.org/2000/svg",
|
||||
},
|
||||
[h("path", { d: "M0 0C5.48483 8 6.5 8 12 0Z" })],
|
||||
);
|
||||
};
|
||||
},
|
||||
});
|
||||
@@ -0,0 +1,13 @@
|
||||
<script setup lang="ts">
|
||||
import { DialogOverlay, useForwardExpose } from "reka-ui";
|
||||
import { useOverlayDialog } from "./context";
|
||||
defineOptions({ inheritAttrs: false });
|
||||
withDefaults(defineProps<{ as?: string }>(), { as: "div" });
|
||||
useOverlayDialog();
|
||||
const { forwardRef } = useForwardExpose();
|
||||
</script>
|
||||
<template>
|
||||
<DialogOverlay :ref="forwardRef" :as="as" v-bind="$attrs">
|
||||
<slot />
|
||||
</DialogOverlay>
|
||||
</template>
|
||||
@@ -0,0 +1,56 @@
|
||||
<script setup lang="ts">
|
||||
import {
|
||||
DialogContent,
|
||||
injectDialogRootContext,
|
||||
useForwardExpose,
|
||||
type DialogContentEmits,
|
||||
} from "reka-ui";
|
||||
import { useId } from "vue";
|
||||
import { useConfig } from "../../providers/context";
|
||||
import { useOverlayDialog } from "./context";
|
||||
|
||||
defineOptions({ inheritAttrs: false });
|
||||
const props = withDefaults(
|
||||
defineProps<{
|
||||
as?: string;
|
||||
isDismissable?: boolean;
|
||||
isKeyboardDismissDisabled?: boolean;
|
||||
}>(),
|
||||
{ as: "div", isDismissable: true, isKeyboardDismissDisabled: false },
|
||||
);
|
||||
const emit = defineEmits<DialogContentEmits>();
|
||||
const context = useOverlayDialog();
|
||||
const config = useConfig();
|
||||
const generatedId = useId();
|
||||
// Programmatic dialogs may have no Trigger to allocate a content ID.
|
||||
const dialog = injectDialogRootContext();
|
||||
dialog.contentId ||= `hv-overlay-${generatedId}`;
|
||||
const { forwardRef } = useForwardExpose();
|
||||
|
||||
function onEscape(event: KeyboardEvent) {
|
||||
emit("escapeKeyDown", event);
|
||||
if (props.isKeyboardDismissDisabled) event.preventDefault();
|
||||
}
|
||||
function onOutside(event: DialogContentEmits["interactOutside"][0]) {
|
||||
emit("interactOutside", event);
|
||||
if (!props.isDismissable) event.preventDefault();
|
||||
}
|
||||
</script>
|
||||
<template>
|
||||
<DialogContent
|
||||
:ref="forwardRef"
|
||||
:as="as"
|
||||
v-bind="$attrs"
|
||||
:dir="($attrs.dir as string | undefined) ?? config?.dir.value"
|
||||
:lang="($attrs.lang as string | undefined) ?? config?.locale.value"
|
||||
:aria-modal="context.modal.value ? true : undefined"
|
||||
@escape-key-down="onEscape"
|
||||
@interact-outside="onOutside"
|
||||
@pointer-down-outside="emit('pointerDownOutside', $event)"
|
||||
@focus-outside="emit('focusOutside', $event)"
|
||||
@open-auto-focus="emit('openAutoFocus', $event)"
|
||||
@close-auto-focus="emit('closeAutoFocus', $event)"
|
||||
>
|
||||
<slot />
|
||||
</DialogContent>
|
||||
</template>
|
||||
@@ -0,0 +1,49 @@
|
||||
<script setup lang="ts">
|
||||
import { computed, provide, toValue } from "vue";
|
||||
import { DialogRoot } from "reka-ui";
|
||||
import {
|
||||
useOverlayState,
|
||||
type OverlayState,
|
||||
} from "../../composables/useOverlayState";
|
||||
import { overlayDialogKey } from "./context";
|
||||
|
||||
defineOptions({ inheritAttrs: false });
|
||||
const props = withDefaults(
|
||||
defineProps<{
|
||||
open?: boolean;
|
||||
defaultOpen?: boolean;
|
||||
state?: OverlayState;
|
||||
modal?: boolean;
|
||||
}>(),
|
||||
{ open: undefined, defaultOpen: false, modal: true },
|
||||
);
|
||||
const emit = defineEmits<{
|
||||
"update:open": [open: boolean];
|
||||
openChange: [open: boolean];
|
||||
}>();
|
||||
const state = useOverlayState({
|
||||
isOpen: () => (props.state ? toValue(props.state.isOpen) : props.open),
|
||||
defaultOpen: props.defaultOpen,
|
||||
onOpenChange(value) {
|
||||
props.state?.setOpen(value);
|
||||
emit("update:open", value);
|
||||
emit("openChange", value);
|
||||
},
|
||||
});
|
||||
provide(overlayDialogKey, { state, modal: computed(() => props.modal) });
|
||||
defineExpose({ open: state.open, close: state.close, toggle: state.toggle });
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<DialogRoot
|
||||
:open="state.isOpen.value"
|
||||
:modal="modal"
|
||||
@update:open="state.setOpen"
|
||||
>
|
||||
<slot
|
||||
:is-open="state.isOpen.value"
|
||||
:close="state.close"
|
||||
:open="state.open"
|
||||
/>
|
||||
</DialogRoot>
|
||||
</template>
|
||||
@@ -0,0 +1,14 @@
|
||||
<script setup lang="ts">
|
||||
import { DialogPortal } from "reka-ui";
|
||||
defineOptions({ inheritAttrs: false });
|
||||
defineProps<{
|
||||
to?: string | HTMLElement;
|
||||
disabled?: boolean;
|
||||
defer?: boolean;
|
||||
}>();
|
||||
</script>
|
||||
<template>
|
||||
<DialogPortal :to="to" :disabled="disabled" :defer="defer">
|
||||
<slot />
|
||||
</DialogPortal>
|
||||
</template>
|
||||
@@ -0,0 +1,63 @@
|
||||
import { computed, nextTick, ref, watch, type Ref } from "vue";
|
||||
/** Phase markers drive source keyframes; Reka Presence still owns exit unmounting. */
|
||||
export function useOverlayAnimation(
|
||||
open: Ref<boolean>,
|
||||
element?: Ref<HTMLElement | null | undefined>,
|
||||
floating = false,
|
||||
) {
|
||||
const entering = ref(open.value);
|
||||
watch(
|
||||
open,
|
||||
(value) => {
|
||||
entering.value = value;
|
||||
},
|
||||
{ flush: "sync" },
|
||||
);
|
||||
function onAnimationEnd(event: AnimationEvent) {
|
||||
if (event.target !== event.currentTarget || !open.value) return;
|
||||
const names = getComputedStyle(event.currentTarget as HTMLElement)
|
||||
.animationName.split(",")
|
||||
.map((s) => s.trim());
|
||||
if (names.includes(event.animationName)) entering.value = false;
|
||||
}
|
||||
if (element)
|
||||
watch(
|
||||
[element, open],
|
||||
([el], _, onCleanup) => {
|
||||
if (!el) return;
|
||||
let stale = false;
|
||||
const wrapper = el.parentElement;
|
||||
const check = () => {
|
||||
if (stale || !open.value || !entering.value) return;
|
||||
// Floating UI briefly suppresses animation while measuring. Wait for placement.
|
||||
if (
|
||||
floating &&
|
||||
wrapper?.hasAttribute("data-reka-popper-content-wrapper") &&
|
||||
/translate\(0(?:px)?,\s*-200%\)/.test(wrapper.style.transform)
|
||||
)
|
||||
return;
|
||||
const animation = getComputedStyle(el).animationName;
|
||||
if (!animation || animation === "none") entering.value = false;
|
||||
};
|
||||
const observer = new MutationObserver(check);
|
||||
observer.observe(el, { attributes: true, attributeFilter: ["style"] });
|
||||
if (floating && wrapper)
|
||||
observer.observe(wrapper, {
|
||||
attributes: true,
|
||||
attributeFilter: ["style"],
|
||||
});
|
||||
const media = el.ownerDocument.defaultView?.matchMedia?.(
|
||||
"(prefers-reduced-motion: reduce)",
|
||||
);
|
||||
media?.addEventListener("change", check);
|
||||
void nextTick(check);
|
||||
onCleanup(() => {
|
||||
stale = true;
|
||||
observer.disconnect();
|
||||
media?.removeEventListener("change", check);
|
||||
});
|
||||
},
|
||||
{ flush: "post" },
|
||||
);
|
||||
return { entering, exiting: computed(() => !open.value), onAnimationEnd };
|
||||
}
|
||||
@@ -0,0 +1,15 @@
|
||||
import { inject, type ComputedRef, type InjectionKey } from "vue";
|
||||
import type { OverlayState } from "../../composables/useOverlayState";
|
||||
|
||||
export interface OverlayDialogContext {
|
||||
state: OverlayState;
|
||||
modal: ComputedRef<boolean>;
|
||||
}
|
||||
export const overlayDialogKey: InjectionKey<OverlayDialogContext> =
|
||||
Symbol("hv-overlay-dialog");
|
||||
export function useOverlayDialog() {
|
||||
const context = inject(overlayDialogKey);
|
||||
if (!context)
|
||||
throw new Error("Overlay dialog parts require OverlayDialogRoot.");
|
||||
return context;
|
||||
}
|
||||
@@ -0,0 +1,29 @@
|
||||
export type OverlaySide = "top" | "bottom" | "left" | "right";
|
||||
export type OverlayPlacement =
|
||||
| OverlaySide
|
||||
| "start"
|
||||
| "end"
|
||||
| `${"top" | "bottom"} ${"start" | "end" | "left" | "right"}`
|
||||
| `${"left" | "right" | "start" | "end"} ${"top" | "bottom"}`;
|
||||
export function resolvePlacement(
|
||||
value: OverlayPlacement,
|
||||
dir: "ltr" | "rtl" = "ltr",
|
||||
) {
|
||||
const [base, edge] = value.split(" ");
|
||||
const side: OverlaySide =
|
||||
base === "start"
|
||||
? dir === "rtl"
|
||||
? "right"
|
||||
: "left"
|
||||
: base === "end"
|
||||
? dir === "rtl"
|
||||
? "left"
|
||||
: "right"
|
||||
: (base as OverlaySide);
|
||||
let align: "start" | "center" | "end" = "center";
|
||||
if (edge === "start" || edge === "top") align = "start";
|
||||
else if (edge === "end" || edge === "bottom") align = "end";
|
||||
else if (edge === "left") align = dir === "rtl" ? "end" : "start";
|
||||
else if (edge === "right") align = dir === "rtl" ? "start" : "end";
|
||||
return { side, align };
|
||||
}
|
||||
@@ -0,0 +1,11 @@
|
||||
/** Private primitive bridge, not a public HeroUI-compatible component API. */
|
||||
export {
|
||||
DialogTrigger,
|
||||
DialogClose,
|
||||
DialogTitle,
|
||||
DialogDescription,
|
||||
PopoverRoot,
|
||||
PopoverTrigger,
|
||||
PopoverPortal,
|
||||
PopoverContent,
|
||||
} from "reka-ui";
|
||||
@@ -0,0 +1,18 @@
|
||||
import { onMounted, onBeforeUnmount, ref } from "vue";
|
||||
/** CSS fallback works before mount; use the visual viewport while the keyboard is visible. */
|
||||
export function useOverlayViewport() {
|
||||
const height = ref("100dvh");
|
||||
const update = () => {
|
||||
height.value = `${window.visualViewport?.height ?? window.innerHeight}px`;
|
||||
};
|
||||
onMounted(() => {
|
||||
update();
|
||||
window.addEventListener("resize", update);
|
||||
window.visualViewport?.addEventListener("resize", update);
|
||||
});
|
||||
onBeforeUnmount(() => {
|
||||
window.removeEventListener("resize", update);
|
||||
window.visualViewport?.removeEventListener("resize", update);
|
||||
});
|
||||
return height;
|
||||
}
|
||||
Reference in New Issue
Block a user