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
+28
View File
@@ -0,0 +1,28 @@
<script setup lang="ts">
import {
Tabs,
TabsListContainer,
TabsList,
TabsTab,
TabsPanel,
TabsIndicator,
} from "@heroui-vue/components";
</script>
<template>
<Tabs default-value="overview">
<TabsListContainer>
<TabsList aria-label="选项">
<TabsTab value="overview">
概览
<TabsIndicator />
</TabsTab>
<TabsTab value="analytics">
分析
<TabsIndicator />
</TabsTab>
</TabsList>
</TabsListContainer>
<TabsPanel value="overview">概览内容</TabsPanel>
<TabsPanel value="analytics">分析内容</TabsPanel>
</Tabs>
</template>
+355
View File
@@ -0,0 +1,355 @@
import { afterEach, beforeEach, expect, it, vi } from "vitest";
import { mount, flushPromises } from "@vue/test-utils";
import { defineComponent, nextTick, ref, type Component } from "vue";
import * as library from "../packages/vue/src";
import ScrollShadow from "../packages/vue/src/components/scroll-shadow/ScrollShadow.vue";
import BasicTabs from "../apps/docs/demos/tabs-basic.vue";
import { readFileSync } from "node:fs";
const wrappers: ReturnType<typeof mount>[] = [];
beforeEach(() => {
vi.stubGlobal(
"ResizeObserver",
class {
observe() {}
unobserve() {}
disconnect() {}
},
);
});
afterEach(async () => {
wrappers.splice(0).forEach((w) => w.unmount());
await flushPromises();
vi.unstubAllGlobals();
document.body.innerHTML = "";
vi.restoreAllMocks();
});
function attach(component: Component) {
const w = mount(component, { attachTo: document.body });
wrappers.push(w);
return w;
}
function fixture(template: string, setup = () => ({})) {
return attach(
defineComponent({
components: {
Tabs: library.Tabs,
TabsList: library.TabsList,
TabsTab: library.TabsTab,
TabsPanel: library.TabsPanel,
TabsIndicator: library.TabsIndicator,
},
template,
setup,
}),
);
}
async function settle() {
await flushPromises();
await nextTick();
await new Promise((resolve) => setTimeout(resolve, 25));
await nextTick();
}
function metrics(el: Element, values: Record<string, number>) {
for (const [key, value] of Object.entries(values))
Object.defineProperty(el, key, {
configurable: true,
value,
writable: true,
});
}
it("detects vertical edges with offset/tolerance, does not repeat callbacks, and clears disabled state", async () => {
const w = attach(ScrollShadow);
metrics(w.element, { scrollHeight: 500, clientHeight: 100, scrollTop: 0 });
await w.trigger("scroll");
await settle();
expect(w.attributes("data-bottom-scroll")).toBe("true");
expect(w.emitted("visibilityChange")?.at(-1)).toEqual(["bottom"]);
await w.trigger("scroll");
await settle();
expect(w.emitted("visibilityChange")).toHaveLength(1);
metrics(w.element, { scrollTop: 100 });
await w.trigger("scroll");
await settle();
expect(w.attributes("data-top-bottom-scroll")).toBe("true");
metrics(w.element, { scrollTop: 399 });
await w.trigger("scroll");
await settle();
expect(w.attributes("data-top-scroll")).toBe("true");
expect(w.attributes("data-bottom-scroll")).toBeUndefined();
await w.setProps({ isEnabled: false });
await settle();
expect(w.attributes("data-top-scroll")).toBeUndefined();
expect(w.attributes("data-scroll-shadow-mode")).toBe("manual");
await w.setProps({ visibility: "both" });
expect(w.attributes("data-top-bottom-scroll")).toBe("true");
});
it("normalizes horizontal negative RTL scroll and updates when content changes", async () => {
const w = mount(ScrollShadow, {
props: { orientation: "horizontal", offset: 10 },
attrs: { dir: "rtl" },
attachTo: document.body,
});
wrappers.push(w);
metrics(w.element, { scrollWidth: 300, clientWidth: 100, scrollLeft: -10 });
await w.trigger("scroll");
await settle();
expect(w.attributes("data-right-scroll")).toBe("true");
metrics(w.element, { scrollLeft: -50 });
await w.trigger("scroll");
await settle();
expect(w.attributes("data-left-right-scroll")).toBe("true");
metrics(w.element, { scrollWidth: 100, scrollLeft: 0 });
w.element.appendChild(document.createTextNode("changed"));
await settle();
expect(w.emitted("visibilityChange")?.at(-1)).toEqual(["none"]);
expect(w.attributes("data-left-right-scroll")).toBeUndefined();
});
it("keeps controlled visibility and caller attrs/styles on the actual scroll element", async () => {
const w = mount(ScrollShadow, {
props: { visibility: "top", isEnabled: false, size: 80 },
attrs: {
class: "caller",
"aria-label": "region",
style: { "--scroll-shadow-size": "55px" },
},
attachTo: document.body,
});
wrappers.push(w);
await settle();
expect(w.attributes("data-top-scroll")).toBe("true");
expect(w.attributes("aria-label")).toBe("region");
expect(w.classes()).toContain("caller");
expect(
(w.element as HTMLElement).style.getPropertyValue("--scroll-shadow-size"),
).toBe("55px");
expect(w.emitted("visibilityChange")).toBeUndefined();
await w.setProps({ orientation: "horizontal", visibility: "both" });
expect(w.attributes("data-top-scroll")).toBeUndefined();
expect(w.attributes("data-left-right-scroll")).toBe("true");
});
it("selects the first enabled tab, keeps unique ARIA links, switches content, and avoids form submission", async () => {
const w = attach(BasicTabs);
await settle();
const tabs = w.findAll("[role=tab]");
expect(tabs[0].attributes("aria-selected")).toBe("true");
for (const tab of tabs) {
expect(tab.attributes("type")).toBe("button");
const controls = tab.attributes("aria-controls");
if (!controls) throw new Error("Missing panel control ID");
const panel = document.getElementById(controls);
expect(panel).not.toBeNull();
expect(panel?.getAttribute("aria-labelledby")).toBe(tab.attributes("id"));
}
await tabs[1].trigger("mousedown", { button: 0, ctrlKey: false });
await settle();
expect(tabs[1].attributes("aria-selected")).toBe("true");
expect(w.text()).toContain("跟踪指标");
expect(w.text()).not.toContain("查看项目概览");
const indicators = w.findAll("[data-slot=tabs-indicator]");
expect(
indicators.filter(
(el) => (el.element as HTMLElement).style.visibility === "visible",
),
).toHaveLength(1);
});
it("supports controlled rejection and default aliases with number/string identity", async () => {
const selected = ref<string | number>("1");
const changed = vi.fn();
const w = fixture(
'<Tabs :model-value="selected" @selection-change="changed"><TabsList aria-label="keys"><TabsTab :value="1">number<TabsIndicator /></TabsTab><TabsTab value="1">string<TabsIndicator /></TabsTab></TabsList><TabsPanel :value="1">N</TabsPanel><TabsPanel value="1">S</TabsPanel></Tabs>',
() => ({ selected, changed }),
);
await settle();
const tabs = w.findAll("[role=tab]");
expect(tabs[0].attributes("id")).not.toBe(tabs[1].attributes("id"));
await tabs[0].trigger("mousedown", { button: 0, ctrlKey: false });
await settle();
expect(changed).toHaveBeenCalledWith(1);
expect(tabs[1].attributes("aria-selected")).toBe("true");
selected.value = 1;
await settle();
expect(tabs[0].attributes("aria-selected")).toBe("true");
});
it("moves focus by arrow/Home/End, skips disabled tabs, and supports manual activation", async () => {
const w = fixture(
'<Tabs keyboard-activation="manual"><TabsList aria-label="navigation"><TabsTab value="a">A</TabsTab><TabsTab value="b" is-disabled>B</TabsTab><TabsTab value="c">C</TabsTab></TabsList><TabsPanel value="a">Alpha</TabsPanel><TabsPanel value="c">Charlie</TabsPanel></Tabs>',
);
await settle();
const tabs = w.findAll("[role=tab]");
(tabs[0].element as HTMLElement).focus();
await tabs[0].trigger("keydown", { key: "ArrowRight" });
await settle();
expect(document.activeElement).toBe(tabs[2].element);
expect(tabs[0].attributes("aria-selected")).toBe("true");
await tabs[2].trigger("keydown", { key: "Enter" });
await settle();
expect(tabs[2].attributes("aria-selected")).toBe("true");
await tabs[2].trigger("keydown", { key: "Home" });
await settle();
expect(document.activeElement).toBe(tabs[0].element);
});
it("isolates nested instances and reconciles dynamic removed/disabled selected members", async () => {
const show = ref(true),
disabled = ref(false);
const w = fixture(
'<Tabs default-value="b"><TabsList aria-label="outer"><TabsTab value="a">A</TabsTab><TabsTab v-if="show" value="b" :is-disabled="disabled">B</TabsTab></TabsList><TabsPanel value="a"><Tabs><TabsList aria-label="inner"><TabsTab value="x">X</TabsTab></TabsList><TabsPanel value="x">Inner</TabsPanel></Tabs></TabsPanel><TabsPanel v-if="show" value="b">Beta</TabsPanel></Tabs>',
() => ({ show, disabled }),
);
await settle();
expect(w.find("[data-selected]").text()).toBe("B");
disabled.value = true;
await settle();
expect(w.findAll("[aria-selected=true]")).toHaveLength(2);
disabled.value = false;
await settle();
expect(w.find("[aria-selected=true]").text()).toBe("A");
show.value = false;
await settle();
expect(w.text()).not.toContain("Beta");
expect(w.findAll("[aria-selected=true]")).toHaveLength(2);
});
it("does not select or navigate a disabled link tab", async () => {
const w = fixture(
'<Tabs><TabsList><TabsTab value="a">A</TabsTab><TabsTab value="b" href="/bad" is-disabled>B</TabsTab></TabsList></Tabs>',
);
await settle();
const link = w.find("a");
expect(link.attributes("href")).toBeUndefined();
expect(link.attributes("aria-disabled")).toBe("true");
await link.trigger("mousedown", { button: 0, ctrlKey: false });
await link.trigger("click");
expect(w.find("[aria-selected=true]").text()).toBe("A");
});
const demos = import.meta.glob(
"../apps/docs/demos/{scroll-shadow,tabs}-*.vue",
{ eager: true, import: "default" },
);
import Structure from "./fixtures/tabs-structure.vue";
it("matches all 7/10 fixed baseline previews and mounts every shared SFC without warnings", async () => {
const warn = vi.spyOn(console, "warn").mockImplementation(() => {}),
error = vi.spyOn(console, "error").mockImplementation(() => {});
for (const [family, group, count] of [
["scroll-shadow", "utilities", 7],
["tabs", "navigation", 10],
] as const) {
const baseline = readFileSync(
`../heroui/apps/docs/content/docs/cn/react/components/(${group})/${family}.mdx`,
"utf8",
);
const current = readFileSync(`apps/docs/components/${family}.md`, "utf8");
const names = (s: string) =>
[
...s.matchAll(/<ComponentPreview\s+(?:isBgSolid\s+)?name="([^"]+)"/g),
].map((m) => m[1]);
expect(names(current)).toEqual(names(baseline));
expect(names(current)).toHaveLength(count);
for (const name of names(current)) {
const w = mount(demos[`../apps/docs/demos/${name}.vue`] as Component, {
attachTo: document.body,
});
await flushPromises();
w.unmount();
await flushPromises();
}
}
const w = mount(Structure, { attachTo: document.body });
await flushPromises();
w.unmount();
await flushPromises();
expect(warn.mock.calls).toEqual([]);
expect(error.mock.calls).toEqual([]);
});
it("hydrates initial IDs without mismatches and updates the actual linked panel", async () => {
const { createSSRApp } = await import("vue");
const { renderToString } = await import("@vue/server-renderer");
const html = await renderToString(createSSRApp(BasicTabs));
const root = document.createElement("div");
root.innerHTML = html;
document.body.appendChild(root);
const before = Array.from(root.querySelectorAll("[role=tab]")).map(
(el) => el.id,
);
const warn = vi.spyOn(console, "warn").mockImplementation(() => {}),
error = vi.spyOn(console, "error").mockImplementation(() => {});
const app = createSSRApp(BasicTabs);
app.mount(root);
await settle();
try {
expect(
Array.from(root.querySelectorAll("[role=tab]")).map((el) => el.id),
).toEqual(before);
expect(warn.mock.calls).toEqual([]);
expect(error.mock.calls).toEqual([]);
const last = root.querySelectorAll("[role=tab]")[2] as HTMLElement;
last.dispatchEvent(
new MouseEvent("mousedown", { bubbles: true, button: 0 }),
);
await settle();
expect(
document.getElementById(last.getAttribute("aria-controls")!)?.hidden,
).toBe(false);
} finally {
app.unmount();
}
});
it("preserves dynamic caller ARIA through the native slot boundary", async () => {
const controls = ref("external"),
label = ref("label-one");
const w = fixture(
'<Tabs><TabsList><TabsTab value="a" :aria-controls="controls">A</TabsTab></TabsList><TabsPanel value="a" :aria-labelledby="label">Content</TabsPanel></Tabs>',
() => ({ controls, label }),
);
await settle();
expect(w.get("[role=tab]").attributes("aria-controls")).toBe("external");
expect(w.get("[role=tabpanel]").attributes("aria-labelledby")).toBe(
"label-one",
);
controls.value = "changed";
label.value = "label-two";
await settle();
expect(w.get("[role=tab]").attributes("aria-controls")).toBe("changed");
expect(w.get("[role=tabpanel]").attributes("aria-labelledby")).toBe(
"label-two",
);
});
it("requests one controlled update per complete pointer gesture when the parent rejects it", async () => {
const change = vi.fn();
const w = fixture(
'<Tabs model-value="a" @selection-change="change"><TabsList><TabsTab value="a">A</TabsTab><TabsTab value="b">B</TabsTab></TabsList></Tabs>',
() => ({ change }),
);
await settle();
const second = w.findAll("[role=tab]")[1];
await second.trigger("mousedown", { button: 0, ctrlKey: false });
(second.element as HTMLElement).focus();
await second.trigger("mouseup");
await second.trigger("click");
await settle();
expect(change.mock.calls).toEqual([["b"]]);
expect(w.get("[aria-selected=true]").text()).toBe("A");
});
it("stays controlled after starting with an entirely disabled collection", async () => {
const selected = ref<string | undefined>(),
disabled = ref(["a", "b"]);
const change = vi.fn();
const w = fixture(
'<Tabs :model-value="selected" :disabled-keys="disabled" @selection-change="change"><TabsList><TabsTab value="a">A</TabsTab><TabsTab value="b">B</TabsTab></TabsList><TabsPanel value="a">Alpha</TabsPanel><TabsPanel value="b">Beta</TabsPanel></Tabs>',
() => ({ selected, disabled, change }),
);
await settle();
expect(w.find("[aria-selected=true]").exists()).toBe(false);
selected.value = "a";
disabled.value = [];
await settle();
await w
.findAll("[role=tab]")[1]
.trigger("mousedown", { button: 0, ctrlKey: false });
await settle();
expect(change).toHaveBeenCalledWith("b");
expect(w.get("[aria-selected=true]").text()).toBe("A");
expect(w.get("[data-selected]").text()).toBe("A");
});
+27
View File
@@ -432,3 +432,30 @@ it("renders public Modal Popover and Tooltip roots without browser globals", asy
expect(html).not.toContain('role="dialog"');
expect(html).not.toContain('role="tooltip"');
});
it("renders ScrollShadow and Tabs without browser globals and resolves initial panel IDs", async () => {
const { ScrollShadow, Tabs, TabsList, TabsTab, TabsPanel, TabsIndicator } =
await import("../packages/vue/src");
const html = await renderToString(
createSSRApp({
render: () =>
h(Tabs, {}, () => [
h(TabsList, { "aria-label": "SSR tabs" }, () => [
h(TabsTab, { value: "a" }, () => ["A", h(TabsIndicator)]),
h(TabsTab, { value: "b" }, () => ["B", h(TabsIndicator)]),
]),
h(TabsPanel, { value: "a" }, () =>
h(ScrollShadow, { visibility: "bottom" }, () => "SSR content"),
),
h(TabsPanel, { value: "b" }, () => "not selected"),
]),
}),
);
expect(html).toContain('aria-selected="true"');
expect(html).toContain('data-bottom-scroll="true"');
expect(html).toContain("SSR content");
expect(html).not.toContain("not selected");
const controls = html.match(/aria-controls="([^"]+)"/)?.[1];
expect(controls).toBeTruthy();
expect(html).toContain(`id="${controls}"`);
});
+52
View File
@@ -0,0 +1,52 @@
import { ref } from "vue";
import {
useScrollShadow,
type ScrollShadowProps,
type TabsProps,
type TabsTabProps,
type TabsPanelProps,
} from "../../packages/vue/src";
const shadow: ScrollShadowProps = {
orientation: "horizontal",
visibility: "both",
onVisibilityChange: (_value) => {},
};
const tabs: TabsProps = {
modelValue: 1,
keyboardActivation: "manual",
variant: "secondary",
disabledKeys: [1, "1"],
};
const tab: TabsTabProps = { value: "a", href: "/guide", isDisabled: true };
const panel: TabsPanelProps = { value: 1, shouldForceMount: true };
// @ts-expect-error variant is a fixed union
const badShadow: ScrollShadowProps = { variant: "shadow" };
// @ts-expect-error unsupported orientation
const badTabs: TabsProps = { orientation: "diagonal" };
// @ts-expect-error keys are not objects
const badTab: TabsTabProps = { value: { id: 1 } };
const badCallback: TabsProps = {
// @ts-expect-error controlled callback key remains string | number
"onUpdate:modelValue": (_value: boolean) => {},
};
function hookContract() {
const el = ref<HTMLElement>();
const state = useScrollShadow({
containerRef: el,
orientation: () => "horizontal",
});
// @ts-expect-error detection is readonly
state.visibility.value = "both";
return state;
}
void [
shadow,
tabs,
tab,
panel,
badShadow,
badTabs,
badTab,
badCallback,
hookContract,
];