feat: migrate ScrollShadow and Tabs with docs and keyboard support

This commit is contained in:
maoyingjie
2026-10-23 00:25:45 +08:00
parent 2b4ac04df1
commit 99df0f1c91
55 changed files with 3290 additions and 5 deletions
@@ -0,0 +1,65 @@
<script setup lang="ts">
import { ref } from "vue";
import { useScrollShadow } from "./useScrollShadow";
import { scrollShadowVariants } from "@heroui-vue/styles";
import type { ScrollShadowVisibility } from "./types";
defineOptions({ inheritAttrs: false });
const props = withDefaults(
defineProps<{
orientation?: "vertical" | "horizontal";
variant?: "fade";
hideScrollBar?: boolean;
size?: number;
offset?: number;
visibility?: ScrollShadowVisibility;
isEnabled?: boolean;
}>(),
{
orientation: "vertical",
variant: "fade",
hideScrollBar: false,
size: 40,
offset: 0,
visibility: "auto",
isEnabled: true,
},
);
const emit = defineEmits<{
visibilityChange: [visibility: ScrollShadowVisibility];
}>();
const element = ref<HTMLElement>();
const { attributes: states, update: measure } = useScrollShadow({
containerRef: element,
orientation: () => props.orientation,
visibility: () => props.visibility,
offset: () => props.offset,
isEnabled: () => props.isEnabled,
onVisibilityChange: (value) => emit("visibilityChange", value),
});
defineExpose({
element,
update: measure,
scrollTo: (options: ScrollToOptions) => element.value?.scrollTo(options),
});
</script>
<template>
<div
ref="element"
:class="
scrollShadowVariants({ orientation, variant, hideScrollBar }).base()
"
:style="{
'--scroll-shadow-size': `${size}px`,
'--scroll-shadow-offset': `${offset}px`,
}"
v-bind="{ ...$attrs, ...states }"
:data-orientation="orientation"
:data-scroll-shadow-mode="
isEnabled && visibility === 'auto' ? 'auto' : 'manual'
"
:data-scroll-shadow-size="size"
data-slot="scroll-shadow"
>
<slot />
</div>
</template>
@@ -0,0 +1,2 @@
export type ScrollShadowVisibility =
"auto" | "both" | "top" | "bottom" | "left" | "right" | "none";
@@ -0,0 +1,119 @@
import {
computed,
ref,
watch,
onScopeDispose,
toValue,
type MaybeRefOrGetter,
} from "vue";
import {
useEventListener,
useMutationObserver,
useResizeObserver,
} from "@vueuse/core";
import type { ScrollShadowVisibility } from "./types";
export interface UseScrollShadowProps {
containerRef: MaybeRefOrGetter<HTMLElement | null | undefined>;
orientation?: MaybeRefOrGetter<"vertical" | "horizontal">;
visibility?: MaybeRefOrGetter<ScrollShadowVisibility>;
offset?: MaybeRefOrGetter<number>;
isEnabled?: MaybeRefOrGetter<boolean>;
onVisibilityChange?: (visibility: ScrollShadowVisibility) => void;
}
/** Vue counterpart of the fixed HeroUI scroll measurement hook; bind attributes to the scroll root. */
export function useScrollShadow(options: UseScrollShadowProps) {
const element = computed(() => toValue(options.containerRef));
const orientation = computed(
() => toValue(options.orientation) ?? "vertical",
);
const visibility = computed(() => toValue(options.visibility) ?? "auto");
const offset = computed(() => toValue(options.offset) ?? 0);
const isEnabled = computed(() => toValue(options.isEnabled) ?? true);
const detected = ref<ScrollShadowVisibility>("none");
const current = computed(() =>
visibility.value !== "auto"
? visibility.value
: isEnabled.value
? detected.value
: "none",
);
let frame: number | undefined;
let previous: ScrollShadowVisibility | undefined;
function measure() {
if (
frame !== undefined ||
!element.value ||
!isEnabled.value ||
visibility.value !== "auto"
)
return;
frame = requestAnimationFrame(() => {
frame = undefined;
const el = element.value;
if (!el || !isEnabled.value || visibility.value !== "auto") return;
const vertical = orientation.value === "vertical";
const start = vertical ? el.scrollTop : Math.abs(el.scrollLeft);
const before = start > offset.value;
const after =
start + (vertical ? el.clientHeight : el.clientWidth) + offset.value <
(vertical ? el.scrollHeight : el.scrollWidth) - 1;
const value =
before && after
? "both"
: before
? vertical
? "top"
: "left"
: after
? vertical
? "bottom"
: "right"
: "none";
detected.value = value;
if (value !== previous) {
previous = value;
options.onVisibilityChange?.(value);
}
});
}
watch(
() => [orientation.value, visibility.value, isEnabled.value, offset.value],
() => {
if (frame !== undefined) cancelAnimationFrame(frame);
frame = undefined;
previous = undefined;
detected.value = "none";
measure();
},
{ flush: "post" },
);
useEventListener(element, "scroll", measure, { passive: true });
useEventListener(element, "load", measure, { capture: true });
useResizeObserver(element, measure);
useMutationObserver(element, measure, {
attributes: true,
attributeFilter: ["class", "style", "dir"],
childList: true,
characterData: true,
subtree: true,
});
watch(element, measure, { flush: "post" });
onScopeDispose(() => {
if (frame !== undefined) cancelAnimationFrame(frame);
});
const states = computed(() => {
const v = current.value;
return {
"data-top-scroll": v === "top" ? "true" : undefined,
"data-bottom-scroll": v === "bottom" ? "true" : undefined,
"data-left-scroll": v === "left" ? "true" : undefined,
"data-right-scroll": v === "right" ? "true" : undefined,
"data-top-bottom-scroll":
v === "both" && orientation.value === "vertical" ? "true" : undefined,
"data-left-right-scroll":
v === "both" && orientation.value === "horizontal" ? "true" : undefined,
};
});
return { visibility: current, attributes: states, update: measure };
}
+256
View File
@@ -0,0 +1,256 @@
import {
computed,
defineComponent,
h,
provide,
ref,
shallowRef,
shallowReactive,
useId,
watch,
onBeforeUnmount,
type PropType,
type VNode,
Fragment,
isVNode,
mergeProps,
} from "vue";
import { TabsRoot } from "reka-ui";
import { useMutationObserver, useResizeObserver } from "@vueuse/core";
import { tabsVariants } from "@heroui-vue/styles";
import { useConfig } from "../../providers/context";
import { tabsKey, tabsWireKey, type TabsKey, type TabBox } from "./context";
function members(
nodes: VNode[],
output: { tabs: { key: TabsKey; disabled: boolean }[]; panels: Set<TabsKey> },
) {
for (const node of nodes) {
if (!isVNode(node)) continue;
const name =
typeof node.type === "object"
? ((node.type as { name?: string; __name?: string }).name ??
(node.type as { __name?: string }).__name)
: "";
if (name === "Tabs") continue;
const key = node.props?.value ?? node.props?.id;
if (name === "TabsTab" && key !== undefined)
output.tabs.push({
key,
disabled:
node.props?.isDisabled === "" ||
node.props?.["is-disabled"] === "" ||
!!node.props?.["is-disabled"] ||
!!node.props?.isDisabled ||
!!node.props?.disabled,
});
if (name === "TabsPanel" && key !== undefined) output.panels.add(key);
if (Array.isArray(node.children))
members(node.children.filter(isVNode), output);
else if (
["TabsListContainer", "TabsList"].includes(name || "") &&
node.children &&
typeof node.children === "object" &&
"default" in node.children
) {
const slot = node.children.default;
if (typeof slot === "function") members(slot(), output);
}
}
}
export default defineComponent({
name: "Tabs",
inheritAttrs: false,
props: {
modelValue: [String, Number] as PropType<TabsKey>,
selectedKey: [String, Number] as PropType<TabsKey>,
defaultValue: [String, Number] as PropType<TabsKey>,
defaultSelectedKey: [String, Number] as PropType<TabsKey>,
orientation: {
type: String as PropType<"horizontal" | "vertical">,
default: "horizontal",
},
variant: {
type: String as PropType<"primary" | "secondary">,
default: "primary",
},
align: {
type: String as PropType<"start" | "center" | "end">,
default: "center",
},
keyboardActivation: {
type: String as PropType<"automatic" | "manual">,
default: "automatic",
},
disabledKeys: {
type: Array as PropType<readonly TabsKey[]>,
default: () => [],
},
isDisabled: Boolean,
dir: String as PropType<"ltr" | "rtl">,
as: { type: String, default: "div" },
},
emits: {
"update:modelValue": (key: TabsKey) =>
typeof key === "string" || typeof key === "number",
"update:selectedKey": (key: TabsKey) =>
typeof key === "string" || typeof key === "number",
selectionChange: (key: TabsKey) =>
typeof key === "string" || typeof key === "number",
},
setup(props, { attrs, slots, emit }) {
const config = useConfig(),
base = useId();
const local = ref<TabsKey | undefined>(
props.defaultValue ?? props.defaultSelectedKey,
);
const options = shallowRef<{ key: TabsKey; disabled: boolean }[]>([]);
const panels = shallowRef(new Set<TabsKey>());
const disabled = (key: TabsKey) =>
props.isDisabled ||
props.disabledKeys.includes(key) ||
!!options.value.find((t) => t.key === key)?.disabled;
const selected = computed(
() =>
props.modelValue ??
props.selectedKey ??
(local.value !== undefined &&
(!options.value.length ||
options.value.some((t) => t.key === local.value && !disabled(t.key)))
? local.value
: options.value.find((t) => !disabled(t.key))?.key),
);
// Persist a reconciliation so re-enabling a removed/disabled default tab
// does not resurrect a selection the user already lost.
watch(
() => [options.value, ...props.disabledKeys, props.isDisabled],
() => {
if (props.modelValue !== undefined || props.selectedKey !== undefined)
return;
if (
!options.value.some((t) => t.key === local.value && !disabled(t.key))
)
local.value = options.value.find((t) => !disabled(t.key))?.key;
},
{ flush: "sync" },
);
const dir = computed(() => props.dir ?? config?.dir.value ?? "ltr");
function select(key: TabsKey) {
if (disabled(key) || key === selected.value) return;
if (props.modelValue === undefined && props.selectedKey === undefined)
local.value = key;
emit("update:modelValue", key);
emit("update:selectedKey", key);
emit("selectionChange", key);
}
const list = ref<HTMLElement>();
const elements = shallowReactive(new Map<TabsKey, HTMLElement>());
const boxes = shallowRef(new Map<TabsKey, TabBox>());
const ready = ref(false);
let frame: number | undefined;
function measure() {
const next = new Map<TabsKey, TabBox>();
for (const [key, el] of elements)
if (el.isConnected) {
// Layout coordinates remain stable while an ancestor Modal is scaling.
next.set(key, {
x: el.offsetLeft,
y: el.offsetTop,
width: el.offsetWidth,
height: el.offsetHeight,
});
}
if (
next.size !== boxes.value.size ||
[...next].some(([key, b]) => {
const old = boxes.value.get(key);
return (
!old ||
old.x !== b.x ||
old.y !== b.y ||
old.width !== b.width ||
old.height !== b.height
);
})
)
boxes.value = next;
if (!ready.value && next.size && frame === undefined)
frame = requestAnimationFrame(() => {
frame = undefined;
ready.value = true;
});
}
useResizeObserver(
computed(() =>
[list.value, ...elements.values()].filter(
(el): el is HTMLElement => !!el,
),
),
measure,
);
useMutationObserver(list, measure, {
childList: true,
subtree: true,
characterData: true,
attributes: true,
attributeFilter: ["class", "dir"],
});
watch(() => [props.orientation, dir.value], measure, { flush: "post" });
onBeforeUnmount(() => {
if (frame !== undefined) cancelAnimationFrame(frame);
});
provide(tabsKey, {
selected,
keyboardActivation: computed(() => props.keyboardActivation),
select,
orientation: computed(() => props.orientation),
variant: computed(() => props.variant),
dir,
disabled,
domId: (kind, key) =>
`hv-tabs-${base}-${kind}-${typeof key}-${encodeURIComponent(String(key))}`,
panels,
list,
elements,
boxes,
ready,
measure,
});
return () => {
const nodes = slots.default?.({ selectedKey: selected.value }) ?? [];
const found = {
tabs: [] as { key: TabsKey; disabled: boolean }[],
panels: new Set<TabsKey>(),
};
members(nodes, found);
if (JSON.stringify(found.tabs) !== JSON.stringify(options.value))
options.value = found.tabs;
if (
found.panels.size !== panels.value.size ||
[...found.panels].some((key) => !panels.value.has(key))
)
panels.value = found.panels;
return h(
TabsRoot,
mergeProps(attrs, {
as: props.as,
modelValue: tabsWireKey(selected.value),
"onUpdate:modelValue": (key: string | number) => {
if (typeof key !== "string") return;
if (key.startsWith("n:")) select(Number(key.slice(2)));
else if (key.startsWith("s:")) select(key.slice(2));
},
orientation: props.orientation,
activationMode: "manual",
unmountOnHide: false,
dir: dir.value,
class: tabsVariants({
variant: props.variant,
align: props.align,
}).base(),
"data-slot": "tabs",
}),
{ default: () => nodes },
);
};
},
});
@@ -0,0 +1,41 @@
<script setup lang="ts">
import { computed } from "vue";
import { useTabs, useTabKey } from "./context";
defineOptions({ inheritAttrs: false });
withDefaults(defineProps<{ as?: string }>(), { as: "span" });
const ctx = useTabs(),
key = useTabKey();
const selected = computed(() => ctx.selected.value === key.value);
const style = computed(() => {
const active =
ctx.selected.value === undefined
? undefined
: ctx.boxes.value.get(ctx.selected.value);
const own = ctx.boxes.value.get(key.value);
const secondary = ctx.variant.value === "secondary",
vertical = ctx.orientation.value === "vertical";
return {
visibility: selected.value ? ("visible" as const) : ("hidden" as const),
transition: ctx.ready.value ? undefined : "none",
...(active && own
? {
translate: `${ctx.dir.value === "rtl" ? active.x + active.width - own.x - own.width : active.x - own.x}px ${active.y - own.y}px`,
width: secondary && vertical ? undefined : `${active.width}px`,
height: secondary && !vertical ? undefined : `${active.height}px`,
}
: {}),
};
});
</script>
<template>
<component
:is="as"
v-bind="$attrs"
class="hv-tabs__indicator"
data-slot="tabs-indicator"
aria-hidden="true"
:style="style"
>
<slot />
</component>
</template>
@@ -0,0 +1,36 @@
<script setup lang="ts">
import { watch, onBeforeUnmount } from "vue";
import { TabsList as RekaList, useForwardExpose } from "reka-ui";
import { useTabs } from "./context";
defineOptions({ inheritAttrs: false });
withDefaults(defineProps<{ as?: string; loop?: boolean }>(), {
as: "div",
loop: true,
});
const ctx = useTabs();
const { forwardRef, currentElement } = useForwardExpose();
watch(
currentElement,
(el) => {
ctx.list.value = el;
ctx.measure();
},
{ flush: "post" },
);
onBeforeUnmount(() => {
ctx.list.value = undefined;
});
</script>
<template>
<RekaList
:ref="forwardRef"
v-bind="$attrs"
:as="as"
:loop="loop"
class="hv-tabs__list"
data-slot="tabs-list"
:data-orientation="ctx.orientation.value"
>
<slot />
</RekaList>
</template>
@@ -0,0 +1,93 @@
<script setup lang="ts">
import { computed, ref, watch, nextTick } from "vue";
import ScrollShadow from "../scroll-shadow/ScrollShadow.vue";
import { useTabs } from "./context";
import TabsScrollIcon from "./TabsScrollIcon.vue";
defineOptions({ inheritAttrs: false });
withDefaults(defineProps<{ as?: string }>(), { as: "div" });
const ctx = useTabs();
const scroller = ref<InstanceType<typeof ScrollShadow>>();
const vertical = computed(() => ctx.orientation.value === "vertical");
function scroll(direction: 1 | -1) {
const el = scroller.value?.element;
if (!el) return;
const size = vertical.value ? el.clientHeight : el.clientWidth;
const max = Math.max(
0,
(vertical.value ? el.scrollHeight : el.scrollWidth) - size,
);
const rtl = !vertical.value && getComputedStyle(el).direction === "rtl";
const current = vertical.value ? el.scrollTop : el.scrollLeft;
const target = Math.min(
rtl ? 0 : max,
Math.max(rtl ? -max : 0, current + direction * size * 0.8 * (rtl ? -1 : 1)),
);
const reduce = el.ownerDocument.defaultView?.matchMedia?.(
"(prefers-reduced-motion: reduce)",
).matches;
el.scrollTo({
behavior: reduce ? "instant" : "smooth",
[vertical.value ? "top" : "left"]: target,
});
}
watch(ctx.selected, async (key) => {
await nextTick();
const el = scroller.value?.element;
const tab = key === undefined ? undefined : ctx.elements.get(key);
if (!el || !tab) return;
const box = el.getBoundingClientRect(),
target = tab.getBoundingClientRect();
const delta = vertical.value
? target.top < box.top
? target.top - box.top
: target.bottom > box.bottom
? target.bottom - box.bottom
: 0
: target.left < box.left
? target.left - box.left
: target.right > box.right
? target.right - box.right
: 0;
if (delta)
el.scrollBy({
[vertical.value ? "top" : "left"]: delta,
behavior: "instant",
});
});
</script>
<template>
<component
:is="as"
v-bind="$attrs"
class="hv-tabs__list-container"
data-slot="tabs-list-container"
>
<ScrollShadow
ref="scroller"
hide-scroll-bar
:size="64"
:orientation="ctx.orientation.value"
class="hv-tabs__list-container__scroller"
>
<slot />
</ScrollShadow>
<button
type="button"
tabindex="-1"
:aria-label="vertical ? 'Scroll tabs up' : 'Scroll tabs left'"
class="hv-tabs__list-container__scroll-prev"
@click="scroll(-1)"
>
<TabsScrollIcon :direction="vertical ? 'up' : 'left'" />
</button>
<button
type="button"
tabindex="-1"
:aria-label="vertical ? 'Scroll tabs down' : 'Scroll tabs right'"
class="hv-tabs__list-container__scroll-next"
@click="scroll(1)"
>
<TabsScrollIcon :direction="vertical ? 'down' : 'right'" />
</button>
</component>
</template>
@@ -0,0 +1,53 @@
<script setup lang="ts">
import { computed } from "vue";
import { TabsContent, useForwardExpose } from "reka-ui";
import { useTabs, tabsWireKey, type TabsKey } from "./context";
defineOptions({ inheritAttrs: false });
const props = withDefaults(
defineProps<{
value?: TabsKey;
id?: TabsKey;
as?: string;
shouldForceMount?: boolean;
}>(),
{ as: "div", shouldForceMount: false },
);
const ctx = useTabs();
const value = computed(() => {
const v = props.value ?? props.id;
if (v === undefined)
throw new Error("TabsPanel requires value (or id alias).");
return v;
});
const { forwardRef } = useForwardExpose();
</script>
<template>
<TabsContent
:ref="forwardRef"
v-bind="$attrs"
:value="tabsWireKey(value)"
as-child
:as="as"
:force-mount="shouldForceMount"
:hidden="ctx.selected.value !== value"
class="hv-tabs__panel"
data-slot="tabs-panel"
:data-orientation="ctx.orientation.value"
>
<component
:is="as"
:id="ctx.domId('panel', value)"
:hidden="ctx.selected.value !== value"
:aria-labelledby="
'aria-labelledby' in $attrs
? ($attrs['aria-labelledby'] as string)
: ctx.domId('tab', value)
"
>
<slot
v-if="shouldForceMount || ctx.selected.value === value"
:is-selected="ctx.selected.value === value"
/>
</component>
</TabsContent>
</template>
@@ -0,0 +1,28 @@
<script setup lang="ts">
/* Chevron paths from HeroUI ce90ea3 icons.tsx, Apache-2.0. */
defineProps<{ direction: "up" | "down" | "left" | "right" }>();
const paths = {
up: "M13.03 10.53a.75.75 0 0 1-1.06 0L8 6.56l-3.97 3.97a.75.75 0 0 1-1.06-1.06l4.5-4.5a.75.75 0 0 1 1.06 0l4.5 4.5a.75.75 0 0 1 0 1.06",
down: "M2.97 5.47a.75.75 0 0 1 1.06 0L8 9.44l3.97-3.97a.75.75 0 1 1 1.06 1.06l-4.5 4.5a.75.75 0 0 1-1.06 0l-4.5-4.5a.75.75 0 0 1 0-1.06",
left: "M10.53 2.97a.75.75 0 0 1 0 1.06L6.56 8l3.97 3.97a.75.75 0 1 1-1.06 1.06l-4.5-4.5a.75.75 0 0 1 0-1.06l4.5-4.5a.75.75 0 0 1 1.06 0",
right:
"M5.47 2.97a.75.75 0 0 1 1.06 0l4.5 4.5a.75.75 0 0 1 0 1.06l-4.5 4.5a.75.75 0 1 1-1.06-1.06L9.44 8 5.47 4.03a.75.75 0 0 1 0-1.06Z",
};
</script>
<template>
<svg
aria-hidden="true"
role="presentation"
fill="none"
width="16"
height="16"
viewBox="0 0 16 16"
>
<path
:d="paths[direction]"
fill="currentColor"
fill-rule="evenodd"
clip-rule="evenodd"
/>
</svg>
</template>
@@ -0,0 +1,15 @@
<script setup lang="ts">
defineOptions({ inheritAttrs: false });
withDefaults(defineProps<{ as?: string }>(), { as: "span" });
</script>
<template>
<component
:is="as"
v-bind="$attrs"
class="hv-tabs__separator"
data-slot="tabs-separator"
aria-hidden="true"
>
<slot />
</component>
</template>
@@ -0,0 +1,126 @@
<script setup lang="ts">
import { computed, onMounted, onBeforeUnmount, provide, ref, watch } from "vue";
import { TabsTrigger, useForwardExpose } from "reka-ui";
import { useTabs, tabsWireKey, tabKey, type TabsKey } from "./context";
defineOptions({ inheritAttrs: false });
const props = withDefaults(
defineProps<{
value?: TabsKey;
id?: TabsKey;
isDisabled?: boolean;
disabled?: boolean;
as?: string;
href?: string;
}>(),
{ isDisabled: false, disabled: false },
);
const ctx = useTabs();
const value = computed(() => {
const key = props.value ?? props.id;
if (key === undefined)
throw new Error("TabsTab requires value (or the compatibility id alias).");
return key;
});
provide(tabKey, value);
const disabled = computed(
() => props.isDisabled || props.disabled || ctx.disabled(value.value),
);
const selected = computed(() => ctx.selected.value === value.value);
const { forwardRef, currentElement } = useForwardExpose();
const hovered = ref(false),
pressed = ref(false),
focusVisible = ref(false);
let registered: TabsKey | undefined;
watch(
[currentElement, value],
([el, key]) => {
if (registered !== undefined) ctx.elements.delete(registered);
if (el) {
ctx.elements.set(key, el);
registered = key;
}
ctx.measure();
},
{ flush: "post" },
);
onMounted(ctx.measure);
onBeforeUnmount(() => {
if (registered !== undefined) ctx.elements.delete(registered);
ctx.measure();
});
// Reka owns pointer/key activation. Handle automatic focus here so a parent
// rejecting an update receives one request for a complete pointer/key gesture.
let pointerGesture = false,
keyboardGesture = false;
function pointerStart() {
pointerGesture = true;
}
function keyStart(event: KeyboardEvent) {
if (event.key === "Enter" || event.key === " ") keyboardGesture = true;
}
function click(event: MouseEvent) {
const handled = pointerGesture || keyboardGesture;
pointerGesture = false;
keyboardGesture = false;
if (disabled.value) event.preventDefault();
else if (!handled && !event.defaultPrevented) ctx.select(value.value);
}
function focus(event: FocusEvent) {
if (
ctx.keyboardActivation.value === "automatic" &&
!pointerGesture &&
!disabled.value
)
ctx.select(value.value);
focusVisible.value = (event.target as HTMLElement).matches(":focus-visible");
}
</script>
<template>
<TabsTrigger
:ref="forwardRef"
v-bind="$attrs"
:value="tabsWireKey(value)"
as-child
:as="as ?? (href ? 'a' : 'button')"
:href="disabled ? undefined : href"
:disabled="disabled"
:aria-disabled="disabled || undefined"
class="hv-tabs__tab"
data-slot="tabs-tab"
:data-selected="selected || undefined"
:data-disabled="disabled ? '' : undefined"
:data-hovered="(!disabled && hovered) || undefined"
:data-pressed="(!disabled && pressed) || undefined"
:data-focus-visible="focusVisible || undefined"
@mousedown="pointerStart"
@keydown="keyStart"
@pointerenter="hovered = true"
@pointerleave="
hovered = false;
pressed = false;
"
@pointerdown="pressed = true"
@pointerup="pressed = false"
@focus="focus"
@blur="
focusVisible = false;
pressed = false;
"
@click="click"
>
<component
:is="as ?? (href ? 'a' : 'button')"
:id="ctx.domId('tab', value)"
:data-disabled="disabled ? '' : undefined"
:aria-controls="
'aria-controls' in $attrs
? ($attrs['aria-controls'] as string)
: ctx.panels.value.has(value)
? ctx.domId('panel', value)
: undefined
"
>
<slot :is-selected="selected" :is-disabled="disabled" />
</component>
</TabsTrigger>
</template>
@@ -0,0 +1,44 @@
import { inject, type InjectionKey, type Ref, type ComputedRef } from "vue";
export type TabsKey = string | number;
export interface TabBox {
x: number;
y: number;
width: number;
height: number;
}
export interface TabsContext {
selected: ComputedRef<TabsKey | undefined>;
keyboardActivation: ComputedRef<"automatic" | "manual">;
select: (value: TabsKey) => void;
orientation: ComputedRef<"horizontal" | "vertical">;
variant: ComputedRef<"primary" | "secondary">;
dir: ComputedRef<"ltr" | "rtl">;
disabled: (key: TabsKey) => boolean;
domId: (kind: "tab" | "panel", key: TabsKey) => string;
panels: Ref<Set<TabsKey>>;
list: Ref<HTMLElement | undefined>;
elements: Map<TabsKey, HTMLElement>;
boxes: Ref<Map<TabsKey, TabBox>>;
ready: Ref<boolean>;
measure: () => void;
}
export const tabsKey: InjectionKey<TabsContext> = Symbol("hv-tabs");
export function useTabs() {
const ctx = inject(tabsKey);
if (!ctx) throw new Error("Tabs parts require Tabs.");
return ctx;
}
export const tabKey: InjectionKey<ComputedRef<TabsKey>> = Symbol("hv-tab");
export function useTabKey() {
const value = inject(tabKey);
if (!value) throw new Error("TabsIndicator requires TabsTab.");
return value;
}
// An empty string is reserved for no selection. Encode user keys so Reka is
// always controlled, even when an empty/disabled collection initially has no key.
export function tabsWireKey(key: TabsKey | undefined): string {
return key === undefined
? ""
: `${typeof key === "number" ? "n" : "s"}:${key}`;
}