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,215 @@
/* Adapted from HeroUI ce90ea3, Apache-2.0. See third-party/HEROUI-LICENSE. */
/* Base scroll-shadow component */
.hv-scroll-shadow {
@apply relative;
--scroll-shadow-size: 40px;
--scroll-shadow-scrollbar-size: 10px;
--scroll-shadow-offset: 0px;
}
/* Fade sizes for the scroll-driven variant below. They stay at 0px whenever the scroll
timeline is inactive, which is exactly the state of a container without overflow. */
@property --scroll-shadow-start-fade {
syntax: "<length>";
inherits: false;
initial-value: 0px;
}
@property --scroll-shadow-end-fade {
syntax: "<length>";
inherits: false;
initial-value: 0px;
}
@keyframes hv-scroll-shadow-start-fade {
from {
--scroll-shadow-start-fade: 0px;
}
to {
--scroll-shadow-start-fade: var(--scroll-shadow-size);
}
}
@keyframes hv-scroll-shadow-end-fade {
from {
--scroll-shadow-end-fade: var(--scroll-shadow-size);
}
to {
--scroll-shadow-end-fade: 0px;
}
}
/* Orientation: Vertical */
.hv-scroll-shadow--vertical {
@apply scrollbar overflow-y-auto;
}
/* Orientation: Horizontal */
.hv-scroll-shadow--horizontal {
@apply scrollbar overflow-x-auto;
}
/* Variant: Fade - Vertical */
.hv-scroll-shadow--fade.hv-scroll-shadow--vertical {
/* `[data-scroll-shadow-mode="auto"]` lets the scroll-driven variant below reuse this
plumbing. It only paints once `--scroll-linear-gradient` is set, since an undefined
variable makes `mask-image` invalid at computed-value time, which resolves to `none`. */
&:where(
[data-top-scroll="true"],
[data-bottom-scroll="true"],
[data-top-bottom-scroll="true"],
[data-scroll-shadow-mode="auto"]
) {
mask-image:
linear-gradient(var(--scroll-linear-gradient)),
linear-gradient(#000, #000);
mask-position:
left top,
right top;
mask-repeat: no-repeat;
mask-size:
calc(100% - var(--scroll-shadow-scrollbar-size)) 100%,
var(--scroll-shadow-scrollbar-size) 100%;
-webkit-mask-image:
linear-gradient(var(--scroll-linear-gradient)),
linear-gradient(#000, #000);
-webkit-mask-position:
left top,
right top;
-webkit-mask-repeat: no-repeat;
-webkit-mask-size:
calc(100% - var(--scroll-shadow-scrollbar-size)) 100%,
var(--scroll-shadow-scrollbar-size) 100%;
}
&[data-top-scroll="true"] {
--scroll-linear-gradient:
0deg, #000 calc(100% - var(--scroll-shadow-size)), transparent;
}
&[data-bottom-scroll="true"] {
--scroll-linear-gradient:
180deg, #000 calc(100% - var(--scroll-shadow-size)), transparent;
}
&[data-top-bottom-scroll="true"] {
--scroll-linear-gradient:
#000, #000, transparent 0, #000 var(--scroll-shadow-size),
#000 calc(100% - var(--scroll-shadow-size)), transparent;
}
}
/* Variant: Fade - Horizontal */
.hv-scroll-shadow--fade.hv-scroll-shadow--horizontal {
&:where(
[data-left-scroll="true"],
[data-right-scroll="true"],
[data-left-right-scroll="true"],
[data-scroll-shadow-mode="auto"]
) {
mask-image:
linear-gradient(var(--scroll-linear-gradient)),
linear-gradient(#000, #000);
mask-position:
left top,
left bottom;
mask-repeat: no-repeat;
mask-size:
100% calc(100% - var(--scroll-shadow-scrollbar-size)),
100% var(--scroll-shadow-scrollbar-size);
-webkit-mask-image:
linear-gradient(var(--scroll-linear-gradient)),
linear-gradient(#000, #000);
-webkit-mask-position:
left top,
left bottom;
-webkit-mask-repeat: no-repeat;
-webkit-mask-size:
100% calc(100% - var(--scroll-shadow-scrollbar-size)),
100% var(--scroll-shadow-scrollbar-size);
}
/* `left`/`right` data attributes are logical (before/end of scroll). In RTL the
start edge is on the right, so the physical fade direction must be swapped. */
&[data-left-scroll="true"] {
--scroll-linear-gradient:
270deg, #000 calc(100% - var(--scroll-shadow-size)), transparent;
&:dir(rtl) {
--scroll-linear-gradient:
90deg, #000 calc(100% - var(--scroll-shadow-size)), transparent;
}
}
&[data-right-scroll="true"] {
--scroll-linear-gradient:
90deg, #000 calc(100% - var(--scroll-shadow-size)), transparent;
&:dir(rtl) {
--scroll-linear-gradient:
270deg, #000 calc(100% - var(--scroll-shadow-size)), transparent;
}
}
&[data-left-right-scroll="true"] {
--scroll-linear-gradient:
to right, #000, #000, transparent 0, #000 var(--scroll-shadow-size),
#000 calc(100% - var(--scroll-shadow-size)), transparent;
}
}
.hv-scroll-shadow--hide-scrollbar {
@apply scrollbar-none;
--scroll-shadow-scrollbar-size: 0px;
}
/* Variant: Fade - scroll-driven
Where scroll timelines are available the fade is derived from the real scroll state,
so it is already correct on the first paint and needs no measurement or hydration.
A container without overflow has an inactive timeline, which leaves both fades at 0px
and collapses the mask to a no-op. The attribute-driven rules above remain the
fallback for engines without scroll timelines, and keep serving controlled mode.
Two consequences of deriving the mask from CSS alone:
- Auto mode always resolves a `mask-image`, even with nothing to scroll, so the root is
always a stacking context and a containing block for fixed descendants. Gating that on
overflow would need a measurement, which is the flicker this variant exists to avoid.
- The `animation` shorthand here lives in the components layer, so an `animate-*` utility
on the root replaces it and pins both fades at 0px, leaving no fade at all. */
@supports (animation-timeline: scroll(self)) {
/* `.scroll-shadow` is repeated so these rules outrank the attribute-driven gradients
above on specificity rather than on source order, which a re-ordering could break. */
.hv-scroll-shadow.hv-scroll-shadow--fade[data-scroll-shadow-mode="auto"] {
animation:
hv-scroll-shadow-start-fade linear both,
hv-scroll-shadow-end-fade linear both;
animation-range:
var(--scroll-shadow-offset)
calc(var(--scroll-shadow-offset) + var(--scroll-shadow-size)),
calc(100% - var(--scroll-shadow-size) - var(--scroll-shadow-offset))
calc(100% - var(--scroll-shadow-offset));
}
/* The orientation rules also outrank the `animation` shorthand above, which resets
`animation-timeline` to `auto`, so the timeline survives regardless of order. */
.hv-scroll-shadow.hv-scroll-shadow--fade.hv-scroll-shadow--vertical[data-scroll-shadow-mode="auto"] {
animation-timeline: scroll(self block), scroll(self block);
--scroll-linear-gradient:
180deg, transparent 0, #000 var(--scroll-shadow-start-fade),
#000 calc(100% - var(--scroll-shadow-end-fade)), transparent 100%;
}
.hv-scroll-shadow.hv-scroll-shadow--fade.hv-scroll-shadow--horizontal[data-scroll-shadow-mode="auto"] {
animation-timeline: scroll(self inline), scroll(self inline);
--scroll-linear-gradient:
90deg, transparent 0, #000 var(--scroll-shadow-start-fade),
#000 calc(100% - var(--scroll-shadow-end-fade)), transparent 100%;
/* Inline-axis progress starts at the right edge in RTL, so flip the physical direction */
&:dir(rtl) {
--scroll-linear-gradient:
270deg, transparent 0, #000 var(--scroll-shadow-start-fade),
#000 calc(100% - var(--scroll-shadow-end-fade)), transparent 100%;
}
}
}
+303
View File
@@ -0,0 +1,303 @@
/* Adapted from HeroUI ce90ea3, Apache-2.0. See third-party/HEROUI-LICENSE. */
/* Base tabs component */
.hv-tabs {
@apply flex gap-2;
/* Orientation styles */
&[data-orientation="horizontal"] {
@apply flex-col;
}
&[data-orientation="vertical"] {
@apply flex-row;
}
}
/* Tab list container */
.hv-tabs__list-container {
@apply relative bg-default;
border-radius: calc(var(--radius) * 2.5);
/* Vertical scroller fills the container height so overflow detection
engages when the wrapper height is constrained (e.g. h-[240px]) */
> .hv-tabs__list-container__scroller[data-orientation="vertical"] {
@apply h-full;
}
/* Overflow chevron buttons */
> .hv-tabs__list-container__scroll-prev,
> .hv-tabs__list-container__scroll-next {
@apply absolute z-2 hidden size-4 cursor-(--cursor-interactive) items-center justify-center rounded-full border-0 bg-transparent p-0 text-foreground outline-none;
/**
* Transitions
* CRITICAL: motion-reduce must be AFTER transition for correct override specificity
*/
transition: opacity 150ms var(--ease-smooth);
@apply motion-reduce:transition-none;
@media (hover: hover) {
&:hover {
@apply opacity-70;
}
}
&:focus-visible {
@apply status-focused;
}
}
/* Chevron position - horizontal orientation */
&:has([data-orientation="horizontal"]) {
> .hv-tabs__list-container__scroll-prev {
@apply start-1 top-1/2 -translate-y-1/2;
}
> .hv-tabs__list-container__scroll-next {
@apply end-1 top-1/2 -translate-y-1/2;
}
> .hv-tabs__list-container__scroll-prev,
> .hv-tabs__list-container__scroll-next {
@apply rtl:rotate-180;
}
}
/* Chevron position - vertical orientation */
&:has([data-orientation="vertical"]) {
> .hv-tabs__list-container__scroll-prev {
@apply top-1 left-1/2 -translate-x-1/2;
}
> .hv-tabs__list-container__scroll-next {
@apply bottom-1 left-1/2 -translate-x-1/2;
}
}
/* Show chevrons only when ScrollShadow reports scrolling is possible */
&:has(
> :is(
[data-left-scroll="true"],
[data-left-right-scroll="true"],
[data-top-scroll="true"],
[data-top-bottom-scroll="true"]
)
)
> .hv-tabs__list-container__scroll-prev {
@apply inline-flex;
}
&:has(
> :is(
[data-right-scroll="true"],
[data-left-right-scroll="true"],
[data-bottom-scroll="true"],
[data-top-bottom-scroll="true"]
)
)
> .hv-tabs__list-container__scroll-next {
@apply inline-flex;
}
}
/* Tab list */
.hv-tabs__list {
@apply inline-flex p-1;
/* Horizontal orientation - grow with content so ScrollShadow can detect overflow */
&[data-orientation="horizontal"] {
@apply w-max min-w-full flex-row;
}
/* Vertical orientation */
&[data-orientation="vertical"] {
@apply flex-col gap-1;
.hv-tabs__tab {
@apply min-w-20;
}
}
}
/* Individual tab */
.hv-tabs__tab {
@apply relative flex h-8 w-full items-center justify-center rounded-3xl px-4 text-center text-sm font-medium text-muted outline-none no-highlight;
z-index: 1;
cursor: var(--cursor-interactive);
/**
* Transitions
* CRITICAL: motion-reduce must be AFTER transition for correct override specificity
*/
transition:
color 150ms var(--ease-smooth),
background-color 150ms var(--ease-smooth),
box-shadow 150ms var(--ease-out),
opacity 150ms var(--ease-smooth);
@apply motion-reduce:transition-none;
/* Selected state */
&[data-selected="true"] {
@apply text-segment-foreground;
/* Hide separator on the selected tab and the one following it */
.hv-tabs__separator,
& + .hv-tabs__tab .hv-tabs__separator {
@apply opacity-0;
}
}
/* Disabled state */
&:disabled,
&[data-disabled],
&[aria-disabled="true"] {
@apply status-disabled;
}
/* Hover states - both approaches for compatibility */
@media (hover: hover) {
&:not([data-selected="true"]):not([data-disabled]):hover,
&[data-hovered="true"]:not([data-selected="true"]):not([data-disabled]) {
@apply opacity-70;
}
}
/* Focus states - comprehensive fallback */
&:focus-visible:not([data-focused]),
&[data-focus-visible="true"] {
@apply status-focused;
}
}
/* Tab content alignment - center is the default, handled by .hv-tabs__tab.
Scoped to the direct child holding the tab list (the list container, or the
list itself when Tabs.ListContainer is omitted) so a nested Tabs inside a
panel keeps its own alignment. */
.hv-tabs--align-start
> :is(.hv-tabs__list-container, .hv-tabs__list)
.hv-tabs__tab {
@apply justify-start text-start;
}
.hv-tabs--align-end
> :is(.hv-tabs__list-container, .hv-tabs__list)
.hv-tabs__tab {
@apply justify-end text-end;
}
/* Tab separator */
.hv-tabs__separator {
@apply pointer-events-none absolute rounded-sm bg-muted/25;
/**
* Transitions
* CRITICAL: motion-reduce must be AFTER transition for correct override specificity
*/
transition: opacity 150ms var(--ease-smooth);
@apply motion-reduce:transition-none;
/* Horizontal tabs - vertical separator */
.hv-tabs__list[data-orientation="horizontal"] & {
@apply start-0 top-1/4 h-1/2 w-px;
}
/* Vertical tabs - horizontal separator */
.hv-tabs__list[data-orientation="vertical"] & {
@apply start-[5%] top-0 h-px w-[90%];
}
}
/* Tab panel */
.hv-tabs__panel {
@apply w-full p-2 outline-none;
/* Exiting animations */
&[data-exiting="true"] {
@apply absolute start-0 top-0 w-full;
}
/* Orientation spacing */
&[data-orientation="horizontal"] {
@apply mt-4;
}
&[data-orientation="vertical"] {
@apply ms-4;
}
}
/* Tab indicator - React Aria's SelectionIndicator */
.hv-tabs__indicator {
@apply absolute start-0 top-0 size-full rounded-3xl bg-segment shadow-surface;
z-index: -1;
/**
* Transitions
* CRITICAL: motion-reduce must be AFTER transition for correct override specificity
*/
transition-duration: 250ms;
transition-property: translate, width, height;
transition-timing-function: var(--ease-out-fluid);
@apply motion-reduce:transition-none;
}
/* ==========================================================================
Secondary Variant
========================================================================== */
.hv-tabs--secondary {
/* Container - flat, no pill. Underline on container (not list) so it stays
stable when the inner list scrolls horizontally inside the ScrollShadow. */
> .hv-tabs__list-container {
@apply rounded-none bg-transparent;
/* Tab list - remove padding */
.hv-tabs__list {
@apply p-0;
}
/* Hide separators in secondary variant */
.hv-tabs__separator {
@apply hidden;
}
/* Tab - adjust for secondary variant */
.hv-tabs__tab {
@apply rounded-none;
/* Selected state - use text-foreground */
&[data-selected="true"] {
@apply text-foreground;
}
}
/* Tab indicator - line style */
.hv-tabs__indicator {
@apply rounded-none bg-accent shadow-none;
}
}
/* Horizontal orientation - bottom border + bottom line indicator */
&[data-orientation="horizontal"] > .hv-tabs__list-container {
@apply border-b border-border;
.hv-tabs__indicator {
@apply top-auto bottom-0 h-0.5;
}
}
/* Vertical orientation - left border + left line indicator */
&[data-orientation="vertical"] > .hv-tabs__list-container {
@apply border-s border-border;
.hv-tabs__indicator {
@apply start-0 top-0 h-full w-0.5;
}
}
}
/* Reka roving-focus navigation requires an empty data-disabled marker.
* Match its presence instead of changing it to RAC boolean strings. */
+3
View File
@@ -127,3 +127,6 @@
@import "./components/popover.css" layer(components);
@import "./components/tooltip.css" layer(components);
@import "./components/scroll-shadow.css";
@import "./components/tabs.css";
+78
View File
@@ -978,3 +978,81 @@ export const tooltipVariants = tv({
});
export type TooltipVariants = VariantProps<typeof tooltipVariants>;
export const scrollShadowVariants = tv({
defaultVariants: {
hideScrollBar: false,
orientation: "vertical",
variant: "fade",
},
slots: {
base: "hv-scroll-shadow",
},
variants: {
hideScrollBar: {
false: {},
true: {
base: "hv-scroll-shadow--hide-scrollbar",
},
},
orientation: {
horizontal: {
base: "hv-scroll-shadow--horizontal",
},
vertical: {
base: "hv-scroll-shadow--vertical",
},
},
variant: {
fade: {
base: "hv-scroll-shadow--fade",
},
},
},
});
export type ScrollShadowVariants = VariantProps<typeof scrollShadowVariants>;
export const tabsVariants = tv({
defaultVariants: {
align: "center",
variant: "primary",
},
slots: {
base: "hv-tabs",
scrollNext: "hv-tabs__list-container__scroll-next",
scrollPrev: "hv-tabs__list-container__scroll-prev",
scroller: "hv-tabs__list-container__scroller",
separator: "hv-tabs__separator",
tab: "hv-tabs__tab",
tabIndicator: "hv-tabs__indicator",
tabList: "hv-tabs__list",
tabListContainer: "hv-tabs__list-container",
tabPanel: "hv-tabs__panel",
},
variants: {
align: {
center: {}, // No class as the base already centers tab content
end: {
base: "hv-tabs--align-end",
},
start: {
base: "hv-tabs--align-start",
},
},
variant: {
primary: {},
secondary: {
base: "hv-tabs--secondary",
},
},
},
});
// Render props that should be excluded from TabsVariants (framework-specific)
type TabsRenderPropsKeys = "selectedKey";
export type TabsVariants = Omit<
VariantProps<typeof tabsVariants>,
TabsRenderPropsKeys
>;
+1
View File
@@ -20,6 +20,7 @@
},
"dependencies": {
"@heroui-vue/styles": "workspace:*",
"@vueuse/core": "14.4.0",
"reka-ui": "^2.11.0"
},
"peerDependencies": {
@@ -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}`;
}
+33
View File
@@ -466,3 +466,36 @@ export type { TooltipArrowProps } from "./types";
export { tooltipVariants, type TooltipVariants } from "@heroui-vue/styles";
export type { OverlayPlacement } from "./components/overlay/placement";
export { default as ScrollShadow } from "./components/scroll-shadow/ScrollShadow.vue";
export type { ScrollShadowVisibility } from "./components/scroll-shadow/types";
export {
scrollShadowVariants,
tabsVariants,
type ScrollShadowVariants,
type TabsVariants,
} from "@heroui-vue/styles";
export { default as Tabs } from "./components/tabs/Tabs";
export { default as TabsListContainer } from "./components/tabs/TabsListContainer.vue";
export { default as TabsList } from "./components/tabs/TabsList.vue";
export { default as TabsTab } from "./components/tabs/TabsTab.vue";
export { default as TabsPanel } from "./components/tabs/TabsPanel.vue";
export { default as TabsIndicator } from "./components/tabs/TabsIndicator.vue";
export { default as TabsSeparator } from "./components/tabs/TabsSeparator.vue";
export type { TabsKey } from "./components/tabs/context";
export {
useScrollShadow,
type UseScrollShadowProps,
} from "./components/scroll-shadow/useScrollShadow";
export type {
ScrollShadowProps,
TabsProps,
TabsListContainerProps,
TabsListProps,
TabsTabProps,
TabsPanelProps,
TabsIndicatorProps,
TabsSeparatorProps,
} from "./types";
+26
View File
@@ -348,3 +348,29 @@ export type TooltipContentProps = InstanceType<typeof TooltipContent>["$props"];
import type TooltipArrow from "./components/tooltip/TooltipArrow.vue";
export type TooltipArrowProps = InstanceType<typeof TooltipArrow>["$props"];
import type ScrollShadow from "./components/scroll-shadow/ScrollShadow.vue";
export type ScrollShadowProps = InstanceType<typeof ScrollShadow>["$props"];
import type Tabs from "./components/tabs/Tabs";
export type TabsProps = InstanceType<typeof Tabs>["$props"];
import type TabsListContainer from "./components/tabs/TabsListContainer.vue";
export type TabsListContainerProps = InstanceType<
typeof TabsListContainer
>["$props"];
import type TabsList from "./components/tabs/TabsList.vue";
export type TabsListProps = InstanceType<typeof TabsList>["$props"];
import type TabsTab from "./components/tabs/TabsTab.vue";
export type TabsTabProps = InstanceType<typeof TabsTab>["$props"];
import type TabsPanel from "./components/tabs/TabsPanel.vue";
export type TabsPanelProps = InstanceType<typeof TabsPanel>["$props"];
import type TabsIndicator from "./components/tabs/TabsIndicator.vue";
export type TabsIndicatorProps = InstanceType<typeof TabsIndicator>["$props"];
import type TabsSeparator from "./components/tabs/TabsSeparator.vue";
export type TabsSeparatorProps = InstanceType<typeof TabsSeparator>["$props"];
+3 -1
View File
@@ -13,6 +13,8 @@ export default defineConfig({
],
build: {
lib: { entry: "src/index.ts", formats: ["es"], fileName: "index" },
rollupOptions: { external: ["vue", "reka-ui", "@heroui-vue/styles"] },
rollupOptions: {
external: ["vue", "reka-ui", "@heroui-vue/styles", "@vueuse/core"],
},
},
});