Files
heroui-vue/packages/vue/src/components/tabs/TabsListContainer.vue
T

94 lines
2.8 KiB
Vue

<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>