feat: add Surface, Link and Spinner components

This commit is contained in:
maoyingjie
2026-10-21 13:04:06 +08:00
parent 9d40dc0ecb
commit 630963c652
52 changed files with 2683 additions and 162 deletions
@@ -3,6 +3,7 @@ import { computed, ref, watch } from "vue";
import { Primitive } from "reka-ui";
import type { ButtonHTMLAttributes } from "vue";
import { buttonVariants, type ButtonVariants } from "@heroui-vue/styles";
import Spinner from "../spinner/Spinner.vue";
defineOptions({ inheritAttrs: false });
const props = withDefaults(
defineProps<{
@@ -80,7 +81,12 @@ function focus(e: FocusEvent) {
pressed = false;
"
>
<span v-if="loading && !asChild" class="hv-spinner" aria-hidden="true" />
<Spinner
v-if="loading && !asChild"
aria-hidden="true"
color="current"
size="sm"
/>
<slot
:is-pending="Boolean(pending)"
:is-disabled="Boolean(disabled)"
+286
View File
@@ -0,0 +1,286 @@
<script setup lang="ts">
import {
provide,
ref,
computed,
useAttrs,
onMounted,
onBeforeUnmount,
} from "vue";
import { Primitive } from "reka-ui";
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: "_self",
isDisabled: false,
asChild: false,
},
);
const slots = linkVariants();
provide(linkContextKey, { slots });
const attrs = useAttrs();
const hovered = ref(false),
pressed = ref(false),
focused = ref(false),
focusVisible = ref(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 (props.isDisabled) {
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 (props.isDisabled && isActivationKey(ke)) {
ke.preventDefault();
ke.stopImmediatePropagation();
return;
}
callHandlers(parent, e);
}
function guardKeydownBubble(e: Event, parent: MaybeHandlers) {
const ke = e as KeyboardEvent;
if (props.isDisabled && isActivationKey(ke)) {
ke.preventDefault();
ke.stopImmediatePropagation();
return;
}
callHandlers(parent, e);
if (
!props.asChild ||
props.isDisabled ||
!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 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("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("click", onRootClickCapture, true);
el.addEventListener("click", onRootClickBubble, false);
el.addEventListener("keydown", onRootKeydownCapture, true);
el.addEventListener("keydown", onRootKeydownBubble, false);
el.addEventListener("keyup", onRootKeyup, false);
}
function setRoot(raw: unknown) {
const el = resolveElement(raw);
element.value = el;
if (el) bindRoot(el);
else unbindRoot();
}
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>
<Primitive
:ref="setRoot"
as="a"
:as-child="asChild"
v-bind="passthroughAttrs"
:href="href"
:target="target"
:rel="rel"
:download="downloadAttr"
:class="slots.base()"
:role="asChild ? 'link' : undefined"
:tabindex="asChild ? 0 : undefined"
:aria-disabled="isDisabled || undefined"
:data-hovered="(!isDisabled && hovered) || undefined"
:data-pressed="(!isDisabled && pressed) || undefined"
:data-focused="focused || undefined"
:data-focus-visible="focusVisible || undefined"
data-slot="link"
@pointerenter="hovered = !isDisabled"
@pointerleave="
hovered = false;
pressed = false;
"
@pointerdown="pressed = !isDisabled"
@pointerup="pressed = false"
@focus="focus"
@blur="
focused = false;
focusVisible = false;
pressed = false;
"
>
<slot
:is-disabled="isDisabled"
:is-hovered="hovered"
:is-pressed="pressed"
:is-focused="focused"
:is-focus-visible="focusVisible"
/>
</Primitive>
</template>
@@ -0,0 +1,40 @@
<script setup lang="ts">
import { inject, useAttrs, useSlots, computed } from "vue";
import { linkContextKey } from "./context";
defineOptions({ inheritAttrs: false });
const attrs = useAttrs();
const slots = useSlots();
const ctx = inject(linkContextKey, undefined);
const iconClass = computed(() => ctx?.slots.icon() ?? "hv-link__icon");
const hasDefaultIcon = computed(() => !slots.default);
</script>
<template>
<span
v-bind="attrs"
:class="iconClass"
:data-default-icon="hasDefaultIcon || undefined"
data-slot="link-icon"
>
<slot>
<!-- Default external-link mark from the fixed baseline ExternalLinkIcon. -->
<svg
aria-hidden="true"
fill="none"
height="9"
role="presentation"
viewBox="0 0 7 7"
width="9"
data-slot="link-default-icon"
xmlns="http://www.w3.org/2000/svg"
>
<path
d="M1.20592 6.84333L0.379822 6.01723L4.52594 1.8672H1.37819L1.38601 0.731812H6.48742V5.83714H5.34421L5.35203 2.6933L1.20592 6.84333Z"
fill="currentColor"
/>
</svg>
</slot>
</span>
</template>
@@ -0,0 +1,9 @@
import type { InjectionKey } from "vue";
import type { linkVariants } from "@heroui-vue/styles";
export interface LinkContext {
slots: ReturnType<typeof linkVariants>;
}
export const linkContextKey: InjectionKey<LinkContext> =
Symbol("HeroUIVue.Link");
@@ -0,0 +1,76 @@
<script setup lang="ts">
import { useAttrs, useId, computed } from "vue";
import { spinnerVariants, type SpinnerVariants } from "@heroui-vue/styles";
defineOptions({ inheritAttrs: false });
const props = defineProps<{
color?: SpinnerVariants["color"];
size?: SpinnerVariants["size"];
}>();
const attrs = useAttrs();
const gradientId = useId();
const ariaLabel = computed(() =>
typeof attrs["aria-label"] === "string" ? attrs["aria-label"] : "Loading",
);
const role = computed(() =>
typeof attrs.role === "string" ? attrs.role : "status",
);
</script>
<template>
<span
v-bind="attrs"
:class="spinnerVariants({ color, size })"
:aria-label="ariaLabel"
:role="role"
data-slot="spinner"
>
<svg
aria-hidden="true"
data-slot="spinner-icon"
viewBox="0 0 24 24"
width="100%"
height="100%"
>
<defs>
<linearGradient
:id="`hv-spinner-grad-a-${gradientId}`"
x1="50%"
x2="50%"
y1="5.271%"
y2="91.793%"
>
<stop offset="0%" stop-color="currentColor" />
<stop offset="100%" stop-color="currentColor" stop-opacity="0.55" />
</linearGradient>
<linearGradient
:id="`hv-spinner-grad-b-${gradientId}`"
x1="50%"
x2="50%"
y1="15.24%"
y2="87.15%"
>
<stop offset="0%" stop-color="currentColor" stop-opacity="0" />
<stop offset="100%" stop-color="currentColor" stop-opacity="0.55" />
</linearGradient>
</defs>
<g fill="none">
<path
d="m12.593 23.258l-.011.002l-.071.035l-.02.004l-.014-.004l-.071-.035q-.016-.005-.024.005l-.004.01l-.017.428l.005.02l.01.013l.104.074l.015.004l.012-.004l.104-.074l.012-.016l.004-.017l-.017-.427q-.004-.016-.017-.018m.265-.113l-.013.002l-.185.093l-.01.01l-.003.011l.018.43l.005.012l.008.007l.201.093q.019.005.029-.008l.004-.014l-.034-.614q-.005-.018-.02-.022m-.715.002a.02.02 0 0 0-.027.006l-.006.014l-.034.614q.001.018.017.024l.015-.002l.201-.093l.01-.008l.004-.011l.017-.43l-.003-.012l-.01-.01z"
/>
<path
d="M8.749.021a1.5 1.5 0 0 1 .497 2.958A7.5 7.5 0 0 0 3 10.375a7.5 7.5 0 0 0 7.5 7.5v3c-5.799 0-10.5-4.7-10.5-10.5C0 5.23 3.726.865 8.749.021"
:fill="`url(#hv-spinner-grad-a-${gradientId})`"
transform="translate(1.5 1.625)"
/>
<path
d="M15.392 2.673a1.5 1.5 0 0 1 2.119-.115A10.48 10.48 0 0 1 21 10.375c0 5.8-4.701 10.5-10.5 10.5v-3a7.5 7.5 0 0 0 5.007-13.084a1.5 1.5 0 0 1-.115-2.118"
:fill="`url(#hv-spinner-grad-b-${gradientId})`"
transform="translate(1.5 1.625)"
/>
</g>
</svg>
</span>
</template>
@@ -0,0 +1,25 @@
<script setup lang="ts">
import { provide, computed, useAttrs } from "vue";
import { surfaceVariants, type SurfaceVariants } from "@heroui-vue/styles";
import { surfaceContextKey } from "./context";
defineOptions({ inheritAttrs: false });
const props = withDefaults(
defineProps<{
variant?: SurfaceVariants["variant"];
}>(),
{ variant: "default" },
);
const attrs = useAttrs();
const variant = computed(() => props.variant ?? "default");
provide(surfaceContextKey, { variant });
</script>
<template>
<div v-bind="attrs" :class="surfaceVariants({ variant })" data-slot="surface">
<slot />
</div>
</template>
@@ -0,0 +1,9 @@
import type { ComputedRef, InjectionKey } from "vue";
import type { SurfaceVariants } from "@heroui-vue/styles";
export interface SurfaceContext {
variant: ComputedRef<SurfaceVariants["variant"]>;
}
export const surfaceContextKey: InjectionKey<SurfaceContext> =
Symbol("HeroUIVue.Surface");
@@ -0,0 +1,79 @@
<script setup lang="ts">
import {
computed,
ref,
onMounted,
onBeforeUnmount,
nextTick,
useAttrs,
} from "vue";
import { textAreaVariants, type TextAreaVariants } from "@heroui-vue/styles";
defineOptions({ inheritAttrs: false });
const props = defineProps<{
modelValue?: string;
defaultValue?: string;
invalid?: boolean;
variant?: TextAreaVariants["variant"];
fullWidth?: boolean;
}>();
const attrs = useAttrs();
const invalidState = computed(
() =>
props.invalid ||
attrs["aria-invalid"] === true ||
attrs["aria-invalid"] === "true",
);
const emit = defineEmits<{ "update:modelValue": [value: string] }>();
const internal = ref(props.defaultValue ?? "");
const value = computed(() => props.modelValue ?? internal.value);
const element = ref<HTMLTextAreaElement>();
function update(event: Event) {
const next = (event.target as HTMLTextAreaElement).value;
internal.value = next;
emit("update:modelValue", next);
void nextTick(() => {
if (element.value && element.value.value !== value.value)
element.value.value = value.value;
});
}
function reset(event: Event) {
void nextTick(() => {
if (event.defaultPrevented) return;
internal.value = props.defaultValue ?? "";
if (element.value) element.value.value = value.value;
});
}
let form: HTMLFormElement | null = null;
onMounted(() => {
form = element.value?.form ?? null;
form?.addEventListener("reset", reset);
});
onBeforeUnmount(() => form?.removeEventListener("reset", reset));
defineExpose({ focus: () => element.value?.focus(), element });
</script>
<template>
<textarea
ref="element"
v-bind="$attrs"
:value="value"
:class="textAreaVariants({ variant, fullWidth })"
:data-invalid="invalidState || undefined"
:aria-invalid="invalidState || undefined"
:aria-readonly="
$attrs.readonly === '' ||
$attrs.readonly === true ||
$attrs.readOnly === true ||
undefined
"
data-slot="textarea"
@input="update"
/>
</template>