Files
heroui-vue/packages/vue/src/components/link/Link.vue
T

315 lines
8.4 KiB
Vue

<script setup lang="ts">
import { useInheritedDisabled } from "../field/disabled";
import {
provide,
ref,
computed,
useAttrs,
onMounted,
watch,
onBeforeUnmount,
onUpdated,
} from "vue";
import LinkPrimitive from "./LinkPrimitive";
import { linkVariants } from "@heroui-vue/styles";
import { linkContextKey } from "./context";
defineOptions({ inheritAttrs: false });
const props = withDefaults(
defineProps<{
href?: string;
target?: string;
rel?: string;
download?: boolean | string;
isDisabled?: boolean;
asChild?: boolean;
autoFocus?: boolean;
}>(),
{
target: undefined,
isDisabled: false,
asChild: false,
},
);
const disabled = useInheritedDisabled(() => props.isDisabled);
const slots = linkVariants();
provide(linkContextKey, { slots });
const attrs = useAttrs();
const hovered = ref(false),
pressed = ref(false),
focused = ref(false),
focusVisible = ref(false);
watch(disabled, (value) => {
if (value) {
hovered.value = false;
pressed.value = false;
}
});
const element = ref<HTMLElement>();
function resolveElement(raw: unknown): HTMLElement | undefined {
if (raw instanceof HTMLElement) return raw;
if (raw && typeof raw === "object") {
const el = (raw as { $el?: unknown }).$el;
if (el instanceof HTMLElement) return el;
}
return undefined;
}
type MaybeHandlers =
((e: Event) => void) | Array<(e: Event) => void> | undefined | null;
const immediateStopped = new WeakSet<Event>();
function wasImmediateStopped(e: Event) {
return immediateStopped.has(e);
}
/** Invoke caller handlers (fn or Vue-merged array), honoring stopImmediatePropagation. */
function callHandlers(handlers: MaybeHandlers, e: Event) {
const original = e.stopImmediatePropagation;
e.stopImmediatePropagation = function stopImmediatePropagationPatched(
this: Event,
) {
immediateStopped.add(e);
original.call(e);
};
try {
if (typeof handlers === "function") {
handlers(e);
return;
}
if (Array.isArray(handlers)) {
for (const handler of handlers) {
if (wasImmediateStopped(e)) break;
if (typeof handler === "function") handler(e);
}
}
} finally {
e.stopImmediatePropagation = original;
}
}
function isActivationKey(e: KeyboardEvent) {
return e.key === "Enter" || e.key === " " || e.key === "Spacebar";
}
function isEnterKey(e: KeyboardEvent) {
return e.key === "Enter" || e.code === "Enter" || e.keyCode === 13;
}
function isNativeLinkTarget(el: EventTarget | null) {
if (!(el instanceof HTMLElement)) return false;
const tag = el.tagName;
return (
tag === "A" ||
tag === "BUTTON" ||
tag === "INPUT" ||
tag === "TEXTAREA" ||
tag === "SELECT" ||
el.isContentEditable === true
);
}
function liveAttr(name: string): MaybeHandlers {
return (attrs as Record<string, unknown>)[name] as MaybeHandlers;
}
function guardClick(e: Event, parent: MaybeHandlers) {
if (disabled.value) {
e.preventDefault();
e.stopImmediatePropagation();
return;
}
callHandlers(parent, e);
}
/** Disabled-only gate for key events that must not synthesize activation. */
function guardKeyPassthrough(e: Event, parent: MaybeHandlers) {
const ke = e as KeyboardEvent;
if (disabled.value && isActivationKey(ke)) {
ke.preventDefault();
ke.stopImmediatePropagation();
return;
}
callHandlers(parent, e);
}
function guardKeydownBubble(e: Event, parent: MaybeHandlers) {
const ke = e as KeyboardEvent;
if (disabled.value && isActivationKey(ke)) {
ke.preventDefault();
ke.stopImmediatePropagation();
return;
}
callHandlers(parent, e);
if (
!props.asChild ||
disabled.value ||
!isEnterKey(ke) ||
ke.defaultPrevented ||
wasImmediateStopped(e)
) {
return;
}
const el =
element.value ??
(e.currentTarget instanceof HTMLElement ? e.currentTarget : undefined);
if (!el || isNativeLinkTarget(el)) return;
ke.preventDefault();
// Real DOM click (target/currentTarget, slot + ancestor propagation).
// Vue invokers skip events when e._vts <= invoker.attached, and invokers
// created in the same turn share one timestamp — which drops later listeners
// on a nested dispatch. Seed a strictly later _vts so every Vue handler runs.
const clickEvent = new MouseEvent("click", {
bubbles: true,
cancelable: true,
});
(clickEvent as unknown as { _vts: number })._vts = Date.now() + 1;
el.dispatchEvent(clickEvent);
}
// Non-event attrs only; click/keydown are bound natively so nested
// el.click() during keydown still runs capture and bubble listeners.
const passthroughAttrs = computed(() => {
const {
onClick: _onClick,
onClickCapture: _onClickCapture,
onKeydown: _onKeydown,
onKeydownCapture: _onKeydownCapture,
onKeyup: _onKeyup,
...rest
} = attrs as Record<string, unknown>;
return rest;
});
const onRootAuxClickCapture = (e: Event) => guardClick(e, undefined);
const onRootClickCapture = (e: Event) =>
guardClick(e, liveAttr("onClickCapture"));
const onRootClickBubble = (e: Event) => guardClick(e, liveAttr("onClick"));
const onRootKeydownCapture = (e: Event) =>
guardKeyPassthrough(e, liveAttr("onKeydownCapture"));
const onRootKeydownBubble = (e: Event) =>
guardKeydownBubble(e, liveAttr("onKeydown"));
const onRootKeyup = (e: Event) => guardKeyPassthrough(e, liveAttr("onKeyup"));
let bound: HTMLElement | null = null;
function unbindRoot() {
if (!bound) return;
bound.removeEventListener("auxclick", onRootAuxClickCapture, true);
bound.removeEventListener("click", onRootClickCapture, true);
bound.removeEventListener("click", onRootClickBubble, false);
bound.removeEventListener("keydown", onRootKeydownCapture, true);
bound.removeEventListener("keydown", onRootKeydownBubble, false);
bound.removeEventListener("keyup", onRootKeyup, false);
bound = null;
}
function bindRoot(el: HTMLElement) {
if (bound === el) return;
unbindRoot();
bound = el;
el.addEventListener("auxclick", onRootAuxClickCapture, true);
el.addEventListener("click", onRootClickCapture, true);
el.addEventListener("click", onRootClickBubble, false);
el.addEventListener("keydown", onRootKeydownCapture, true);
el.addEventListener("keydown", onRootKeydownBubble, false);
el.addEventListener("keyup", onRootKeyup, false);
}
let rootInstance: unknown;
function setRoot(raw: unknown) {
rootInstance = raw;
const el = resolveElement(raw);
element.value = el;
if (el) bindRoot(el);
else unbindRoot();
}
onUpdated(() => {
const el = resolveElement(rootInstance);
if (el !== element.value) setRoot(rootInstance);
});
function focus(e: FocusEvent) {
focused.value = true;
focusVisible.value = (e.target as HTMLElement).matches(":focus-visible");
}
const downloadAttr = computed(() => {
if (props.download === undefined || props.download === false)
return undefined;
return props.download === true ? "" : props.download;
});
onMounted(() => {
if (element.value) bindRoot(element.value);
if (props.autoFocus) element.value?.focus();
});
onBeforeUnmount(() => {
unbindRoot();
});
defineExpose({
element,
focus: () => element.value?.focus(),
});
</script>
<template>
<LinkPrimitive
:ref="setRoot"
:is-disabled="disabled"
:as-child="asChild"
v-bind="passthroughAttrs"
:href="disabled ? undefined : href"
:target="!disabled && href ? target : undefined"
:rel="rel"
:download="disabled ? undefined : downloadAttr"
:class="slots.base()"
:role="
(attrs.role as string | undefined) ??
(asChild || disabled ? 'link' : undefined)
"
:tabindex="
disabled
? -1
: ((attrs.tabindex as number | undefined) ?? (asChild ? 0 : undefined))
"
:aria-disabled="disabled || undefined"
:data-hovered="(!disabled && hovered) || undefined"
:data-pressed="(!disabled && pressed) || undefined"
:data-focused="focused || undefined"
:data-focus-visible="focusVisible || undefined"
data-slot="link"
@pointerenter="hovered = !disabled"
@pointerleave="
hovered = false;
pressed = false;
"
@pointerdown="pressed = !disabled"
@pointerup="pressed = false"
@focus="focus"
@blur="
focused = false;
focusVisible = false;
pressed = false;
"
>
<slot
:is-disabled="Boolean(disabled)"
:is-hovered="hovered"
:is-pressed="pressed"
:is-focused="focused"
:is-focus-visible="focusVisible"
/>
</LinkPrimitive>
</template>