feat: add public ColorArea components, docs, and package contract

This commit is contained in:
maoyingjie
2026-10-26 23:51:31 +08:00
parent 01882160e6
commit ae364578ce
33 changed files with 2201 additions and 151 deletions
+2 -1
View File
@@ -173,9 +173,10 @@
@import "./components/calendar-year-picker.css" layer(components);
/* Private color interaction foundation; public components are not exported yet. */
/* Public ColorArea (COLOR-AREA). */
@import "./components/color-area.css" layer(components);
/* Private color interaction foundation; remaining color families are not public. */
@import "./components/color-slider.css" layer(components);
@import "./components/color-field.css" layer(components);
+21
View File
@@ -1828,6 +1828,27 @@ export const colorSwatchVariants = tv({
export type ColorSwatchVariants = VariantProps<typeof colorSwatchVariants>;
/** HeroUI 3.2.6 / ce90ea3, Apache-2.0; hv namespace only. */
export const colorAreaVariants = tv({
defaultVariants: {
showDots: false,
},
slots: {
base: "hv-color-area",
thumb: "hv-color-area__thumb",
},
variants: {
showDots: {
false: {},
true: {
base: "hv-color-area--show-dots",
},
},
},
});
export type ColorAreaVariants = VariantProps<typeof colorAreaVariants>;
/** HeroUI 3.2.6 / ce90ea3, Apache-2.0; hv namespace only. */
export const timeFieldVariants = tv({
base: "hv-time-field",
@@ -0,0 +1,243 @@
<script setup lang="ts">
import {
computed,
provide,
shallowRef,
useAttrs,
watch,
type CSSProperties,
type StyleValue,
} from "vue";
import { Primitive, useForwardExpose } from "reka-ui";
import { colorAreaVariants } from "@heroui-vue/styles";
import { useColorState } from "../color/model";
import { useColorArea } from "../color/area";
import { colorAreaBackground } from "../color/gradient";
import {
parseColor,
type Color,
type ColorAxisChannel,
type ColorSpace,
type ColorValue,
} from "../color/value";
import { colorAreaKey, type ColorAreaElements } from "./context";
import { colorAreaLabel } from "./labels";
import type {
ColorAreaRenderProps,
ColorAreaSlots,
ColorAreaStyle,
ColorAreaStyleFn,
} from "./types";
defineOptions({ inheritAttrs: false, name: "ColorArea" });
const props = withDefaults(
defineProps<{
/** Accepted color; the Vue `v-model` value. Omitted inherits the nearest owner. */
modelValue?: ColorValue | null;
/** Lower-priority alias for `modelValue`, matching the shared color model. */
value?: ColorValue | null;
/** Initial color for uncontrolled use. */
defaultValue?: ColorValue | null;
colorSpace?: ColorSpace;
xChannel?: ColorAxisChannel;
yChannel?: ColorAxisChannel;
xName?: string;
yName?: string;
form?: string;
isDisabled?: boolean;
/** Alias for `isDisabled`. */
disabled?: boolean;
/** Library extension: blocks edits without removing the area from the tab order. */
isReadOnly?: boolean;
showDots?: boolean;
locale?: string;
dir?: "ltr" | "rtl";
/** Render a different root element; corresponds to the upstream render prop. */
as?: string;
/** Merge the area attributes and handlers onto the single default-slot root. */
asChild?: boolean;
/** Vue style binding or upstream style function, merged after base styles. */
style?: ColorAreaStyle;
/** Template-friendly alias for the style function; receives render props. */
styleFn?: ColorAreaStyleFn;
}>(),
{
colorSpace: undefined,
xChannel: undefined,
yChannel: undefined,
xName: undefined,
yName: undefined,
form: undefined,
isDisabled: false,
disabled: false,
isReadOnly: false,
showDots: false,
locale: undefined,
dir: undefined,
as: "div",
asChild: false,
style: undefined,
styleFn: undefined,
},
);
defineSlots<ColorAreaSlots>();
const emit = defineEmits<{
"update:modelValue": [value: Color | null];
change: [value: Color | null];
changeEnd: [value: Color | null];
}>();
const attrs = useAttrs();
const state = useColorState(props, {
fallback: () => parseColor("#ffffff"),
inherit: true,
change: (value) => {
emit("update:modelValue", value);
emit("change", value);
},
changeEnd: (value) => emit("changeEnd", value),
});
const elements: ColorAreaElements = {
root: shallowRef<HTMLElement>(),
thumb: shallowRef<HTMLElement>(),
focusX: shallowRef<HTMLInputElement>(),
focusY: shallowRef<HTMLInputElement>(),
};
const control = useColorArea(state, props, elements);
const { axes, dir, focusedAxis, locale } = control;
const disabled = state.disabled;
const readOnly = state.readOnly;
const focusVisible = shallowRef(false);
const styles = computed(() => colorAreaVariants({ showDots: props.showDots }));
const background = computed(() =>
colorAreaBackground(
axes.value.color,
axes.value.space,
axes.value.x,
axes.value.y,
dir.value,
),
);
const baseStyle = computed<CSSProperties>(() => {
const paint = background.value;
return {
"--color-area-background": [paint.backgroundImage, paint.backgroundColor]
.filter(Boolean)
.join(", "),
backgroundBlendMode: paint.backgroundBlendMode,
touchAction: disabled.value || readOnly.value ? "auto" : "none",
} as CSSProperties;
});
const renderProps = computed<ColorAreaRenderProps>(() => ({
color: axes.value.color,
space: axes.value.space,
x: axes.value.x,
y: axes.value.y,
}));
const ordinaryStyle = computed<StyleValue | undefined>(() => {
const value = props.style;
return typeof value === "function" ? value(renderProps.value) : value;
});
const computedStyle = computed<StyleValue | undefined>(() =>
props.styleFn?.(renderProps.value),
);
const label = computed(() => {
const explicit = attrs["aria-label"];
if (explicit != null) return String(explicit);
if (attrs["aria-labelledby"] != null) return undefined;
return colorAreaLabel(locale.value);
});
// Expose before `useForwardExpose` so the forwarded `$el` getter and these
// getters coexist on the public instance.
defineExpose({
element: elements.root,
color: computed<Color | null>(() => state.value.value),
});
const { forwardRef, currentElement } = useForwardExpose();
watch(
currentElement,
(element) => {
elements.root.value = (element as HTMLElement | null) ?? undefined;
},
{ immediate: true, flush: "sync" },
);
provide(colorAreaKey, {
elements,
state,
control,
styles,
focusVisible,
disabled,
readOnly,
locale,
dir,
options: props,
});
function axis(event: Event) {
const value = (event.target as HTMLElement | null)?.getAttribute?.(
"data-axis",
);
return value === "x" || value === "y" ? value : undefined;
}
function onKeydown(event: KeyboardEvent) {
if (axis(event)) control.keydown(event);
}
function onInput(event: Event) {
const channel = axis(event);
if (channel) control.input(channel, event);
}
function onFocusin(event: FocusEvent) {
const target = event.target as HTMLElement | null;
if (!target) return;
focusVisible.value = target.matches(":focus-visible");
const channel = target.getAttribute("data-axis");
if (channel === "x" || channel === "y") focusedAxis.value = channel;
}
function onFocusout(event: FocusEvent) {
const next = event.relatedTarget as Node | null;
if (!elements.root.value?.contains(next)) {
focusVisible.value = false;
control.blur();
}
}
</script>
<template>
<Primitive
:ref="forwardRef"
:as="as"
:as-child="asChild"
v-bind="attrs"
:class="styles.base()"
:style="[baseStyle, ordinaryStyle, computedStyle]"
role="group"
data-slot="color-area"
:dir="dir"
:aria-label="label"
:data-disabled="disabled || undefined"
:data-readonly="readOnly || undefined"
@keydown="onKeydown"
@keyup="control.keyup"
@input="onInput"
@change="control.commit"
@focusin="onFocusin"
@focusout="onFocusout"
@pointerdown="control.pointerdown"
@pointermove="control.pointermove"
@pointerup="control.pointerup"
@pointercancel="control.cancel"
@lostpointercapture="control.cancel"
>
<slot />
</Primitive>
</template>
@@ -0,0 +1,155 @@
<script setup lang="ts">
import { computed, watch, type CSSProperties, type StyleValue } from "vue";
import { Primitive, useForwardExpose } from "reka-ui";
import { useColorAreaContext } from "./context";
import { colorChannelLabel } from "./labels";
import type {
ColorAreaThumbRenderProps,
ColorAreaThumbStyle,
ColorAreaThumbStyleFn,
} from "./types";
defineOptions({ inheritAttrs: false, name: "ColorAreaThumb" });
const props = withDefaults(
defineProps<{
/** Render a different thumb element; corresponds to the upstream render prop. */
as?: string;
/** Vue style binding or upstream style function, merged after base styles. */
style?: ColorAreaThumbStyle;
/** Template-friendly alias for the style function; receives render props. */
styleFn?: ColorAreaThumbStyleFn;
}>(),
{
as: "div",
style: undefined,
styleFn: undefined,
},
);
const {
elements,
control,
styles,
focusVisible,
disabled,
readOnly,
locale,
dir,
options,
} = useColorAreaContext();
const { axes, percent, dragging, focusedAxis, x, y } = control;
const xInput = elements.focusX;
const yInput = elements.focusY;
defineExpose({ element: elements.thumb });
const { forwardRef, currentElement } = useForwardExpose();
watch(
currentElement,
(element) => {
elements.thumb.value = (element as HTMLElement | null) ?? undefined;
},
{ immediate: true, flush: "sync" },
);
const xLabel = computed(() => colorChannelLabel(axes.value.x, locale.value));
const yLabel = computed(() => colorChannelLabel(axes.value.y, locale.value));
const xValueText = computed(() =>
axes.value.color.formatChannelValue(axes.value.x, locale.value),
);
const yValueText = computed(() =>
axes.value.color.formatChannelValue(axes.value.y, locale.value),
);
const xMax = computed(
() => axes.value.color.getChannelRange(axes.value.x).maxValue,
);
const yMax = computed(
() => axes.value.color.getChannelRange(axes.value.y).maxValue,
);
const baseStyle = computed<CSSProperties>(() => ({
position: "absolute",
left: `${(dir.value === "rtl" ? 1 - percent.value.x : percent.value.x) * 100}%`,
top: `${(1 - percent.value.y) * 100}%`,
transform: "translate(-50%, -50%)",
"--color-area-thumb-color": axes.value.color.toString("css"),
}));
const renderProps = computed<ColorAreaThumbRenderProps>(() => ({
color: axes.value.color,
space: axes.value.space,
x: axes.value.x,
y: axes.value.y,
percent: { ...percent.value },
isDragging: dragging.value,
isDisabled: disabled.value,
isReadOnly: readOnly.value,
}));
const ordinaryStyle = computed<StyleValue | undefined>(() => {
const value = props.style;
return typeof value === "function" ? value(renderProps.value) : value;
});
const computedStyle = computed<StyleValue | undefined>(() =>
props.styleFn?.(renderProps.value),
);
const hiddenStyle: CSSProperties = {
position: "absolute",
width: "1px",
height: "1px",
overflow: "hidden",
clipPath: "inset(50%)",
};
</script>
<template>
<Primitive
:ref="forwardRef"
:as="as"
v-bind="$attrs"
:class="styles.thumb()"
:style="[baseStyle, ordinaryStyle, computedStyle]"
data-slot="color-area-thumb"
:data-dragging="dragging || undefined"
:data-focus-visible="focusVisible || undefined"
:data-disabled="disabled || undefined"
:data-readonly="readOnly || undefined"
>
<input
ref="xInput"
type="range"
step="any"
data-axis="x"
:tabindex="focusedAxis === 'x' ? 0 : -1"
:name="options.xName"
:form="options.form"
:aria-label="xLabel"
:aria-valuetext="xValueText"
:min="0"
:max="xMax"
:value="x"
:disabled="disabled"
:aria-readonly="readOnly || undefined"
:style="hiddenStyle"
/>
<input
ref="yInput"
type="range"
step="any"
data-axis="y"
aria-orientation="vertical"
:tabindex="focusedAxis === 'y' ? 0 : -1"
:name="options.yName"
:form="options.form"
:aria-label="yLabel"
:aria-valuetext="yValueText"
:min="0"
:max="yMax"
:value="y"
:disabled="disabled"
:aria-readonly="readOnly || undefined"
:style="hiddenStyle"
/>
</Primitive>
</template>
@@ -0,0 +1,43 @@
import {
inject,
type ComputedRef,
type InjectionKey,
type ShallowRef,
} from "vue";
import type { ColorState } from "../color/model";
import type { ColorAreaControl, ColorAreaOptions } from "../color/area";
export interface ColorAreaElements {
root: ShallowRef<HTMLElement | undefined>;
thumb: ShallowRef<HTMLElement | undefined>;
focusX: ShallowRef<HTMLInputElement | undefined>;
focusY: ShallowRef<HTMLInputElement | undefined>;
}
export interface ColorAreaStyles {
base: () => string;
thumb: () => string;
}
export interface ColorAreaContext {
elements: ColorAreaElements;
state: ColorState;
control: ColorAreaControl;
styles: ComputedRef<ColorAreaStyles>;
focusVisible: ShallowRef<boolean>;
disabled: ComputedRef<boolean>;
readOnly: ComputedRef<boolean>;
locale: ComputedRef<string>;
dir: ComputedRef<"ltr" | "rtl">;
options: ColorAreaOptions;
}
export const colorAreaKey: InjectionKey<ColorAreaContext> =
Symbol("hv-color-area");
export function useColorAreaContext() {
const context = inject(colorAreaKey, undefined);
if (!context)
throw new Error("ColorAreaThumb must be rendered inside ColorArea.");
return context;
}
@@ -0,0 +1,35 @@
import type { ColorAxisChannel } from "../color/value";
const english: Record<ColorAxisChannel, string> = {
red: "Red",
green: "Green",
blue: "Blue",
hue: "Hue",
saturation: "Saturation",
lightness: "Lightness",
brightness: "Brightness",
};
const chinese: Record<ColorAxisChannel, string> = {
red: "红色",
green: "绿色",
blue: "蓝色",
hue: "色相",
saturation: "饱和度",
lightness: "亮度",
brightness: "明度",
};
function isChinese(locale: string) {
return locale.toLowerCase().startsWith("zh");
}
/** Localized native axis name; other locales fall back to the English term. */
export function colorChannelLabel(channel: ColorAxisChannel, locale: string) {
return (isChinese(locale) ? chinese : english)[channel];
}
/** Default group name used when the consumer does not supply a label. */
export function colorAreaLabel(locale: string) {
return isChinese(locale) ? "颜色区域" : "Color area";
}
@@ -0,0 +1,51 @@
import type { StyleValue, VNodeChild } from "vue";
import type { Color, ColorAxisChannel, ColorSpace } from "../color/value";
/** Values shared by the public style functions and render state. */
export interface ColorAreaRenderProps {
/** Display color for the current space; defaults to the accepted value. */
color: Color;
space: ColorSpace;
x: ColorAxisChannel;
y: ColorAxisChannel;
}
export interface ColorAreaThumbRenderProps extends ColorAreaRenderProps {
/** Accepted axis positions in the 0–1 content box, before RTL mapping. */
percent: { x: number; y: number };
isDragging: boolean;
isDisabled: boolean;
isReadOnly: boolean;
}
/**
* Function form of the upstream `style` render prop. Vue's template compiler
* reserves `style` for ordinary bindings, so templates pass the function
* through `styleFn`; render functions may pass it directly.
*/
export type ColorAreaStyleFn = (
renderProps: ColorAreaRenderProps,
) => StyleValue | undefined;
/** Vue style binding (object/array/string) or the upstream style function. */
export type ColorAreaStyle = StyleValue | ColorAreaStyleFn;
export type ColorAreaThumbStyleFn = (
renderProps: ColorAreaThumbRenderProps,
) => StyleValue | undefined;
export type ColorAreaThumbStyle = StyleValue | ColorAreaThumbStyleFn;
/** Default slot; render one ColorAreaThumb per area. */
export interface ColorAreaSlots {
default?: () => VNodeChild;
}
/**
* State exposed by the root instance. Refs are unwrapped on the public
* instance proxy, matching the ColorSwatch `element` convention.
*/
export interface ColorAreaExpose {
element: HTMLElement | null;
color: Color | null;
}
+3 -1
View File
@@ -47,7 +47,7 @@ export function useColorArea(
const axes = computed(() =>
colorAxes(
state.value.value ??
new Color({ space: "hsb", h: 0, s: 100, b: 100, alpha: 1 }),
new Color({ space: "rgb", r: 255, g: 255, b: 255, alpha: 1 }),
props.colorSpace,
props.xChannel,
props.yChannel,
@@ -156,6 +156,7 @@ export function useColorArea(
// Capture the stable area, never the transient child that received pointerdown.
owner.setPointerCapture?.(event.pointerId);
event.preventDefault();
focusedAxis.value = "x";
thumb.value?.focus({ preventScroll: true });
if (!inThumb) update(point);
}
@@ -323,3 +324,4 @@ export function useColorArea(
blur: () => stop(true),
};
}
export type ColorAreaControl = ReturnType<typeof useColorArea>;
+8 -25
View File
@@ -311,33 +311,16 @@ export function colorAxes(
x?: ColorAxisChannel,
y?: ColorAxisChannel,
) {
const working =
space ??
(x === "red" ||
x === "green" ||
x === "blue" ||
y === "red" ||
y === "green" ||
y === "blue"
? "rgb"
: x === "lightness" || y === "lightness"
? "hsl"
: x === "brightness" || y === "brightness"
? "hsb"
: color.getColorSpace() === "rgb"
? "hsb"
: color.getColorSpace());
// Matches the fixed source: the value's own space wins when `colorSpace` is
// omitted, and an omitted axis takes the first remaining channel in that
// space (RGB red/green, HSL/HSB hue/saturation).
const working = space ?? color.getColorSpace();
const native = channels[working];
const xChannel = x ?? (working === "rgb" ? "red" : "saturation");
const yChannel =
y ??
native.find(
(c) =>
c !== xChannel &&
(c === "brightness" || c === "lightness" || c === "green"),
) ??
native.find((c) => c !== xChannel)!;
const xChannel = x ?? native.find((channel) => channel !== y);
const yChannel = y ?? native.find((channel) => channel !== xChannel);
if (
!xChannel ||
!yChannel ||
xChannel === yChannel ||
!native.includes(xChannel) ||
!native.includes(yChannel)
+20
View File
@@ -1136,6 +1136,26 @@ export {
type AutocompleteVariants,
} from "@heroui-vue/styles";
export { default as ColorArea } from "./components/color-area/ColorArea.vue";
export { default as ColorAreaRoot } from "./components/color-area/ColorArea.vue";
export { default as ColorAreaThumb } from "./components/color-area/ColorAreaThumb.vue";
export { colorAreaVariants, type ColorAreaVariants } from "@heroui-vue/styles";
export type {
ColorAreaExpose,
ColorAreaRenderProps,
ColorAreaSlots,
ColorAreaStyle,
ColorAreaStyleFn,
ColorAreaThumbRenderProps,
ColorAreaThumbStyle,
ColorAreaThumbStyleFn,
} from "./components/color-area/types";
export type {
ColorAreaProps,
ColorAreaRootProps,
ColorAreaThumbProps,
} from "./types";
export { default as ColorSwatch } from "./components/color-swatch/ColorSwatch.vue";
export { default as ColorSwatchRoot } from "./components/color-swatch/ColorSwatch.vue";
export {
+5
View File
@@ -911,6 +911,11 @@ export type AutocompleteFilterProps = InstanceType<
import type ColorSwatch from "./components/color-swatch/ColorSwatch.vue";
export type ColorSwatchProps = InstanceType<typeof ColorSwatch>["$props"];
export type ColorSwatchRootProps = ColorSwatchProps;
import type ColorArea from "./components/color-area/ColorArea.vue";
import type ColorAreaThumb from "./components/color-area/ColorAreaThumb.vue";
export type ColorAreaProps = InstanceType<typeof ColorArea>["$props"];
export type ColorAreaRootProps = ColorAreaProps;
export type ColorAreaThumbProps = InstanceType<typeof ColorAreaThumb>["$props"];
export type {
ColorSwatchRenderProps,
ColorSwatchSlots,
+6 -1
View File
@@ -11,7 +11,12 @@ import {
import { colorAreaBackground } from "../../src/components/color/gradient";
import { parseColor, type Color } from "../../src/components/color/value";
defineOptions({ inheritAttrs: false });
const props = defineProps<ColorModelProps & ColorAreaOptions>();
const props = withDefaults(defineProps<ColorModelProps & ColorAreaOptions>(), {
// The private picker proof uses the common saturation × brightness square;
// public ColorArea inference follows the fixed source's channel order.
xChannel: "saturation",
yChannel: "brightness",
});
const emit = defineEmits<{
"update:modelValue": [Color | null];
change: [Color | null];