feat: migrate public ColorSlider with docs and tests

This commit is contained in:
maoyingjie
2026-10-27 09:16:32 +08:00
parent e487bcc8ec
commit ce6c43eb47
31 changed files with 3386 additions and 122 deletions
+301
View File
@@ -0,0 +1,301 @@
import { afterEach, describe, expect, it } from "vitest";
import { mount, flushPromises } from "@vue/test-utils";
import { readFileSync } from "node:fs";
import { ColorSlider, parseColor } from "../packages/vue/src";
import Basic from "../apps/docs/demos/color-slider-basic.vue";
import Disabled from "../apps/docs/demos/color-slider-disabled.vue";
import Vertical from "../apps/docs/demos/color-slider-vertical.vue";
import Controlled from "../apps/docs/demos/color-slider-controlled.vue";
import Channels from "../apps/docs/demos/color-slider-channels.vue";
import AlphaChannel from "../apps/docs/demos/color-slider-alpha-channel.vue";
import RgbChannels from "../apps/docs/demos/color-slider-rgb-channels.vue";
import RenderFunction from "../apps/docs/demos/color-slider-render-function.vue";
import CustomStyles from "../apps/docs/demos/color-slider-custom-styles.vue";
const mounted: ReturnType<typeof mount>[] = [];
function render(component: Parameters<typeof mount>[0]) {
const w = mount(component, { attachTo: document.body });
mounted.push(w);
return w;
}
afterEach(() => {
mounted.splice(0).forEach((w) => w.unmount());
document.body.innerHTML = "";
});
const previews = [
"basic",
"disabled",
"vertical",
"controlled",
"channels",
"alpha-channel",
"rgb-channels",
"render-function",
"custom-styles",
];
const roots = (w: ReturnType<typeof mount>) =>
w.findAll<HTMLElement>("[data-slot=color-slider]");
const root = (w: ReturnType<typeof mount>) => roots(w)[0]!;
const outputs = (w: ReturnType<typeof mount>) =>
w.findAll("[data-slot=color-slider-output]").map((node) => node.text());
const inputs = (w: ReturnType<typeof mount>) =>
w.findAll<HTMLInputElement>(
"[data-slot=color-slider-thumb] input[type=range]",
);
const thumbs = (w: ReturnType<typeof mount>) =>
w.findAll<HTMLElement>("[data-slot=color-slider-thumb]");
const tracks = (w: ReturnType<typeof mount>) =>
w.findAll<HTMLElement>("[data-slot=color-slider-track]");
describe("ColorSlider documentation demos", () => {
it("keeps the nine pinned previews in the upstream order", () => {
const document = readFileSync(
"apps/docs/components/color-slider.md",
"utf8",
);
const names = [
...document.matchAll(/<ComponentPreview name="color-slider-([^"]+)"/g),
].map((match) => match[1]);
expect(names).toEqual(previews);
for (const name of previews) {
const source = readFileSync(
`apps/docs/demos/color-slider-${name}.vue`,
"utf8",
);
expect(source).toContain("<template>");
expect(source).toContain('from "@heroui-vue/components"');
expect(source).not.toContain("className");
}
});
it("renders the basic example with Label, Output, Track and Thumb", () => {
const w = render(Basic);
expect(roots(w)).toHaveLength(1);
expect(root(w).classes()).toContain("hv-color-slider");
expect(root(w).attributes("data-orientation")).toBe("horizontal");
expect(outputs(w)).toEqual(["0°"]);
expect(inputs(w)).toHaveLength(1);
expect(inputs(w)[0]!.element.value).toBe("0");
expect(inputs(w)[0]!.attributes("aria-valuetext")).toBe("0°");
expect(w.get("label[data-slot=label]").text()).toBe("色相");
expect(inputs(w)[0]!.attributes("id")).toBe(
w.get("label[data-slot=label]").attributes("for"),
);
expect(thumbs(w)[0]!.element.style.left).toBe("0%");
expect(
tracks(w)[0]!.element.style.getPropertyValue("--track-background"),
).toContain("linear-gradient");
expect(
tracks(w)[0]!.element.style.getPropertyValue("--track-start-color"),
).toBe("rgb(255, 0, 0)");
});
it("renders the disabled example without editable input", async () => {
const w = render(Disabled);
expect(root(w).attributes("data-disabled")).toBe("true");
expect(thumbs(w)[0]!.attributes("data-disabled")).toBe("true");
expect(inputs(w)[0]!.element.disabled).toBe(true);
expect(thumbs(w)[0]!.element.style.backgroundColor).toBe("");
await inputs(w)[0]!.trigger("keydown", { key: "ArrowRight" });
await inputs(w)[0]!.trigger("keyup", { key: "ArrowRight" });
expect(inputs(w)[0]!.element.value).toBe("200");
expect(w.findComponent(ColorSlider).emitted("change")).toBeUndefined();
});
it("renders three vertical sliders with localized accessible names", () => {
const w = render(Vertical);
expect(roots(w)).toHaveLength(3);
for (const node of roots(w)) {
expect(node.attributes("data-orientation")).toBe("vertical");
}
expect(inputs(w).map((input) => input.attributes("aria-label"))).toEqual([
"色相",
"饱和度",
"明度",
]);
expect(
inputs(w).map((input) => input.attributes("aria-orientation")),
).toEqual(["vertical", "vertical", "vertical"]);
expect(thumbs(w).map((thumb) => thumb.element.style.top)).toEqual([
"100%",
"0%",
"50%",
]);
expect(
tracks(w).map((track) =>
track.element.style.getPropertyValue("--track-background"),
),
).toEqual([
expect.stringContaining("to top"),
expect.stringContaining("to top"),
expect.stringContaining("to top"),
]);
});
it("keeps the controlled slider and swatch in sync", async () => {
const w = render(Controlled);
const swatch = w.get<HTMLElement>("[data-slot=color-swatch]");
expect(swatch.element.style.backgroundColor).toBe(
parseColor("hsl(200, 100%, 50%)").toString("css"),
);
expect(w.text()).toContain("hsl(200, 100%, 50%)");
expect(outputs(w)).toEqual(["200°"]);
await inputs(w)[0]!.trigger("keydown", { key: "ArrowRight" });
await inputs(w)[0]!.trigger("keyup", { key: "ArrowRight" });
await flushPromises();
expect(inputs(w)[0]!.element.value).toBe("201");
expect(outputs(w)).toEqual(["201°"]);
expect(w.text()).toContain("hsl(201, 100%, 50%)");
expect(swatch.element.style.backgroundColor).toBe(
parseColor("hsl(201, 100%, 50%)").toString("css"),
);
});
it("shares one color across the HSL channel sliders", async () => {
const w = render(Channels);
expect(roots(w)).toHaveLength(3);
expect(outputs(w)).toEqual(["0°", "100%", "50%"]);
expect(inputs(w).map((input) => input.element.value)).toEqual([
"0",
"100",
"50",
]);
await inputs(w)[1]!.trigger("keydown", { key: "ArrowDown" });
await inputs(w)[1]!.trigger("keyup", { key: "ArrowDown" });
await flushPromises();
expect(outputs(w)).toEqual(["0°", "99%", "50%"]);
expect(w.text()).toContain("hsl(0, 99%, 50%)");
expect(inputs(w)[1]!.element.value).toBe("99");
const swatch = w.get<HTMLElement>("[data-slot=color-swatch]");
expect(swatch.element.style.backgroundColor).toBe(
parseColor("hsl(0, 99%, 50%)").toString("css"),
);
});
it("renders the alpha channel with a checkerboard and percent output", () => {
const w = render(AlphaChannel);
expect(inputs(w)[0]!.attributes("min")).toBe("0");
expect(inputs(w)[0]!.attributes("max")).toBe("1");
expect(inputs(w)[0]!.element.value).toBe("0.5");
expect(outputs(w)).toEqual(["50%"]);
expect(
tracks(w)[0]!.element.style.getPropertyValue("--track-background"),
).toContain("repeating-conic-gradient");
expect(
tracks(w)[0]!.element.style.getPropertyValue("--track-start-color"),
).toBe("rgba(255, 0, 0, 0)");
expect(
tracks(w)[0]!.element.style.getPropertyValue("--track-end-color"),
).toBe("rgb(255, 0, 0)");
});
it("shares one RGB color across red, green and blue sliders", async () => {
const w = render(RgbChannels);
expect(outputs(w)).toEqual(["255", "100", "50"]);
expect(inputs(w).map((input) => input.attributes("max"))).toEqual([
"255",
"255",
"255",
]);
await inputs(w)[0]!.trigger("keydown", { key: "ArrowLeft" });
await inputs(w)[0]!.trigger("keyup", { key: "ArrowLeft" });
await flushPromises();
expect(outputs(w)).toEqual(["254", "100", "50"]);
expect(w.text()).toContain("rgb(254, 100, 50)");
const swatch = w.get<HTMLElement>("[data-slot=color-swatch]");
expect(swatch.element.style.backgroundColor).toBe(
parseColor("rgb(254, 100, 50)").toString("css"),
);
});
it("maps the render-function example to asChild and keeps interaction", async () => {
const w = render(RenderFunction);
const node = root(w);
expect(node.attributes("data-custom")).toBe("foo");
expect(node.element.tagName).toBe("DIV");
expect(node.classes()).toContain("hv-color-slider");
expect(outputs(w)).toEqual(["0°"]);
await inputs(w)[0]!.trigger("keydown", { key: "ArrowRight" });
await inputs(w)[0]!.trigger("keyup", { key: "ArrowRight" });
await flushPromises();
expect(outputs(w)).toEqual(["1°"]);
});
it("merges the custom style example classes onto real parts", () => {
const w = render(CustomStyles);
expect(root(w).classes()).toContain("hv-color-slider");
const output = w.get("[data-slot=color-slider-output]");
for (const name of [
"text-muted",
"tabular-nums",
"hv-color-slider__output",
]) {
expect(output.classes()).toContain(name);
}
const track = tracks(w)[0]!;
for (const name of [
"h-4!",
"rounded-none!",
"ring-1",
"ring-border",
"hv-color-slider__track",
]) {
expect(track.classes()).toContain(name);
}
const thumb = thumbs(w)[0]!;
for (const name of [
"size-4",
"rounded-sm!",
"border-2",
"border-background",
"shadow-md",
"hv-color-slider__thumb",
]) {
expect(thumb.classes()).toContain(name);
}
const label = w.get("label[data-slot=label]");
expect(label.text()).toBe("色相");
expect(label.classes()).toContain("font-medium");
});
it("documents the Vue API, channels and related state", () => {
const document = readFileSync(
"apps/docs/components/color-slider.md",
"utf8",
);
expect(document).toContain("title: ColorSlider 颜色滑块");
expect(document).toContain("ColorSliderOutput");
expect(document).toContain("ColorSliderTrack");
expect(document).toContain("ColorSliderThumb");
expect(document).toContain("`channel`");
expect(document).toContain("`colorSpace`");
expect(document).toContain("`orientation`");
expect(document).toContain("`name`");
expect(document).toContain("`form`");
expect(document).toContain("`asChild`");
expect(document).toContain("`styleFn`");
expect(document).toContain("`isReadOnly`");
expect(document).toContain("ColorSliderThumbRenderProps");
expect(document).toContain("changeEnd");
expect(document).toContain("`modelValue`/`value` 或 `defaultValue`");
expect(document).not.toMatch(/\|\s*`className`\s*\|/);
expect(document).not.toContain("### ColorSlider.Output");
expect(document).toContain("ColorField");
expect(document).toContain("仍为私有颜色协议");
});
it("adds ColorSlider to the shared navigation between Area and Swatch", () => {
const navigation = readFileSync(
"apps/docs/.vitepress/theme/navigation.ts",
"utf8",
);
const area = navigation.indexOf("ColorArea 颜色区域");
const slider = navigation.indexOf("ColorSlider 颜色滑块");
const swatch = navigation.indexOf("ColorSwatch 颜色色块");
expect(area).toBeGreaterThan(-1);
expect(slider).toBeGreaterThan(area);
expect(swatch).toBeGreaterThan(slider);
expect(navigation).toContain('url: "/components/color-slider"');
});
});
File diff suppressed because it is too large Load Diff
+36
View File
@@ -162,6 +162,42 @@ for (const id of process.argv.slice(2)) {
"ColorSwatch declarations leak Reka types",
);
}
if (id === "color-slider") {
assert(lib.ColorSlider === lib.ColorSliderRoot);
assert(lib.ColorSliderOutput);
assert(lib.ColorSliderTrack);
assert(lib.ColorSliderThumb);
assert(
lib.colorSliderVariants().base() === "hv-color-slider",
"ColorSlider base class must stay in the baseline namespace",
);
assert(
lib.colorSliderVariants().track() === "hv-color-slider__track",
"ColorSlider track class must stay in the baseline namespace",
);
const sliderDts = readFileSync(
new URL(
"./node_modules/@heroui-vue/components/dist/components/color-slider/ColorSlider.vue.d.ts",
import.meta.url,
),
"utf8",
);
const thumbDts = readFileSync(
new URL(
"./node_modules/@heroui-vue/components/dist/components/color-slider/ColorSliderThumb.vue.d.ts",
import.meta.url,
),
"utf8",
);
assert(
!sliderDts.includes("reka-ui"),
"ColorSlider declarations leak Reka types",
);
assert(
!thumbDts.includes("reka-ui"),
"ColorSliderThumb declarations leak Reka types",
);
}
if (id === "b03-tag-error-message") {
assert(/\.hv-tag-group\s*\[data-slot=["']?error-message/.test(css));
assert(lib.tagVariants({ size: "sm" }).base().includes("hv-tag--sm"));
+24 -4
View File
@@ -137,12 +137,12 @@
".hv-color-input-group__prefix",
".hv-color-input-group__suffix"
],
"absent": ["ColorSlider", "ColorField", "ColorInputGroup", "ColorPicker"]
"absent": ["ColorField", "ColorInputGroup", "ColorPicker"]
},
"color-foundation": {
"exports": [],
"css": [".hv-color-area", ".hv-color-area__thumb"],
"absent": ["ColorSlider", "ColorField", "ColorInputGroup", "ColorPicker"]
"absent": ["ColorField", "ColorInputGroup", "ColorPicker"]
},
"color-picker-protocol": {
"exports": [],
@@ -151,7 +151,7 @@
".hv-color-picker__trigger",
".hv-color-picker__popover"
],
"absent": ["ColorSlider", "ColorField", "ColorInputGroup", "ColorPicker"]
"absent": ["ColorField", "ColorInputGroup", "ColorPicker"]
},
"color-slider-foundation": {
"exports": [],
@@ -165,7 +165,7 @@
"max-height:inherit",
"overscroll-behavior:contain"
],
"absent": ["ColorSlider", "ColorField", "ColorInputGroup", "ColorPicker"]
"absent": ["ColorField", "ColorInputGroup", "ColorPicker"]
},
"date-field": {
"exports": [
@@ -442,5 +442,25 @@
"data-exiting",
"data-endpoint"
]
},
"color-slider": {
"exports": [
"ColorSlider",
"ColorSliderRoot",
"ColorSliderOutput",
"ColorSliderTrack",
"ColorSliderThumb",
"colorSliderVariants",
"Color",
"parseColor"
],
"css": [
".hv-color-slider",
".hv-color-slider__output",
".hv-color-slider__track",
".hv-color-slider__thumb",
"--track-start-color",
"--track-end-color"
]
}
}
+234
View File
@@ -0,0 +1,234 @@
import {
ColorSlider,
ColorSliderOutput,
ColorSliderRoot,
ColorSliderThumb,
ColorSliderTrack,
colorSliderVariants,
parseColor,
type AlphaChannel,
type Color,
type ColorChannel,
type ColorSliderBaseProps,
type ColorSliderChannelProps,
type ColorSliderExpose,
type ColorSliderOutputProps,
type ColorSliderOutputRenderProps,
type ColorSliderOutputSlots,
type ColorSliderOutputStyle,
type ColorSliderOutputStyleFn,
type ColorSliderProps,
type ColorSliderRenderProps,
type ColorSliderRootProps,
type ColorSliderSlots,
type ColorSliderStyle,
type ColorSliderStyleFn,
type ColorSliderThumbProps,
type ColorSliderThumbRenderProps,
type ColorSliderThumbSlots,
type ColorSliderThumbStyle,
type ColorSliderThumbStyleFn,
type ColorSliderTrackProps,
type ColorSliderTrackRenderProps,
type ColorSliderTrackSlots,
type ColorSliderTrackStyle,
type ColorSliderTrackStyleFn,
type ColorSliderVariants,
type ColorSpace,
type ColorValue,
type HSLChannel,
type HSLHSBSharedChannel,
type HSBChannel,
type RGBChannel,
} from "@heroui-vue/components";
const color = parseColor("#9B80FF");
const value: ColorValue = color;
const channel: ColorChannel = "hue";
const space: ColorSpace = "hsb";
const hslChannel: HSLChannel = "lightness";
const hsbChannel: HSBChannel = "brightness";
const rgbChannel: RGBChannel = "red";
const sharedChannel: HSLHSBSharedChannel = "saturation";
const alphaChannel: AlphaChannel = "alpha";
const style: ColorSliderStyle = { outline: "1px solid black" };
const styleFn: ColorSliderStyleFn = ({ color: current }) => ({
outline: `1px solid ${current.toString("hex")}`,
});
const styleRender: ColorSliderStyle = ({ channel: active }) => ({
opacity: active ? 0.8 : 1,
});
const outputStyle: ColorSliderOutputStyle = {
fontVariantNumeric: "tabular-nums",
};
const outputStyleFn: ColorSliderOutputStyleFn = ({ label }) => ({
width: `${label.length}ch`,
});
const trackStyle: ColorSliderTrackStyle = { borderColor: "black" };
const trackStyleFn: ColorSliderTrackStyleFn = ({ percent }) => ({
opacity: percent,
});
const thumbStyle: ColorSliderThumbStyle = { cursor: "grab" };
const thumbStyleFn: ColorSliderThumbStyleFn = ({ isDragging }) => ({
width: isDragging ? "20px" : "16px",
});
const base: ColorSliderBaseProps = {
modelValue: color,
value,
defaultValue: "hsb(240, 50%, 50%)",
orientation: "vertical",
name: "hue",
form: "color-form",
isDisabled: false,
disabled: false,
isReadOnly: false,
locale: "zh-CN",
dir: "rtl",
as: "div",
asChild: false,
style,
styleFn,
id: "hue-slider",
};
const channelProps: ColorSliderChannelProps = {
channel: "hue",
colorSpace: "hsb",
};
const props: ColorSliderProps = { ...base, ...channelProps };
const rootProps: ColorSliderRootProps = props;
const outputProps: ColorSliderOutputProps = {
as: "output",
style: outputStyle,
styleFn: outputStyleFn,
};
const trackProps: ColorSliderTrackProps = {
as: "div",
style: trackStyle,
styleFn: trackStyleFn,
};
const thumbProps: ColorSliderThumbProps = {
as: "span",
style: thumbStyle,
styleFn: thumbStyleFn,
};
const render: ColorSliderRenderProps = {
color,
channel: "hue",
colorSpace: "hsb",
orientation: "vertical",
isDisabled: false,
isReadOnly: false,
};
const outputRender: ColorSliderOutputRenderProps = {
...render,
value: 240,
label: "240°",
};
const trackRender: ColorSliderTrackRenderProps = { ...render, percent: 0.5 };
const thumbRender: ColorSliderThumbRenderProps = {
...trackRender,
isDragging: true,
};
const slots: ColorSliderSlots = { default: () => null };
const outputSlots: ColorSliderOutputSlots = { default: () => null };
const trackSlots: ColorSliderTrackSlots = { default: () => null };
const thumbSlots: ColorSliderThumbSlots = { default: () => null };
const variants: ColorSliderVariants = {};
const exposed: ColorSliderExpose = {
element: null,
color: null,
focus: () => {},
};
const typedColor: Color = color;
// @ts-expect-error red requires the rgb color space
const badRed: ColorSliderProps = { channel: "red", colorSpace: "hsl" };
// @ts-expect-error hue is not available in the rgb color space
const badHue: ColorSliderProps = { channel: "hue", colorSpace: "rgb" };
// @ts-expect-error brightness requires the hsb color space
const badBrightness: ColorSliderProps = {
channel: "brightness",
colorSpace: "hsl",
};
// @ts-expect-error lightness requires the hsl color space
const badLightness: ColorSliderProps = {
channel: "lightness",
colorSpace: "hsb",
};
// @ts-expect-error blue requires the rgb color space
const badBlue: ColorSliderProps = { channel: "blue", colorSpace: "hsb" };
// @ts-expect-error channel is required
const badMissing: ColorSliderProps = {};
// @ts-expect-error the public channel set is finite
const badChannel: ColorSliderProps = { channel: "cyan" };
// @ts-expect-error the public space set is rgb | hsl | hsb
const badSpace: ColorSliderProps = { channel: "alpha", colorSpace: "lab" };
const badRender: ColorSliderRenderProps = {
// @ts-expect-error render props require a Color instance
color: "#fff",
channel: "hue",
colorSpace: "hsl",
orientation: "horizontal",
isDisabled: false,
isReadOnly: false,
};
const badThumb: ColorSliderThumbRenderProps = {
...render,
// @ts-expect-error percent is a 0–1 number, not a string
percent: "50%",
isDragging: false,
};
const badExpose: ColorSliderExpose = {
element: null,
color: null,
focus: () => {},
// @ts-expect-error channel is not part of the exposed instance
channel: "hue",
};
// @ts-expect-error style functions return Vue style values, not numbers
const badStyle: ColorSliderStyleFn = () => 1;
void [
ColorSlider,
ColorSliderRoot,
ColorSliderOutput,
ColorSliderTrack,
ColorSliderThumb,
colorSliderVariants,
value,
channel,
space,
hslChannel,
hsbChannel,
rgbChannel,
sharedChannel,
alphaChannel,
styleRender,
props,
rootProps,
outputProps,
trackProps,
thumbProps,
outputRender,
trackRender,
thumbRender,
slots,
outputSlots,
trackSlots,
thumbSlots,
variants,
exposed,
typedColor,
badRed,
badHue,
badBrightness,
badLightness,
badBlue,
badMissing,
badChannel,
badSpace,
badRender,
badThumb,
badExpose,
badStyle,
];