feat: migrate ColorSwatch and public color boundary

This commit is contained in:
maoyingjie
2026-10-26 13:25:21 +08:00
parent 60af6ee40b
commit 270dea5cff
29 changed files with 1427 additions and 18 deletions
@@ -0,0 +1,165 @@
<script setup lang="ts">
import {
computed,
getCurrentInstance,
onBeforeUpdate,
shallowRef,
useAttrs,
useId,
type CSSProperties,
type StyleValue,
} from "vue";
import { Primitive } from "reka-ui";
import {
colorSwatchVariants,
type ColorSwatchVariants,
} from "@heroui-vue/styles";
import { useColorStateContext } from "../color/model";
import { copyColor, parseColor, type ColorValue } from "../color/value";
import { useConfig } from "../../providers/context";
import type {
ColorSwatchSlots,
ColorSwatchStyle,
ColorSwatchStyleFn,
} from "./types";
defineOptions({ inheritAttrs: false, name: "ColorSwatch" });
const props = withDefaults(
defineProps<{
/** Color string or library Color. Omitted inherits the nearest color owner. */
color?: ColorValue | null;
/** Localized accessible color name; overrides the automatic description. */
colorName?: string;
shape?: ColorSwatchVariants["shape"];
size?: ColorSwatchVariants["size"];
/** Render a different root element; corresponds to the upstream render prop. */
as?: string;
/** Merge swatch attributes onto the single default-slot root. */
asChild?: boolean;
/** Vue style binding or upstream style function, merged after base styles. */
style?: ColorSwatchStyle;
/** Template-friendly alias for the style function; receives the color. */
styleFn?: ColorSwatchStyleFn;
}>(),
{
color: undefined,
colorName: undefined,
shape: "circle",
size: "md",
as: "div",
asChild: false,
style: undefined,
styleFn: undefined,
},
);
defineSlots<ColorSwatchSlots>();
const attrs = useAttrs();
const instance = getCurrentInstance()!;
const owner = useColorStateContext();
const config = useConfig();
const generatedId = useId();
const element = shallowRef<HTMLElement>();
const TRANSPARENT = parseColor("#fff0");
function presentsColor() {
const raw = instance.vnode.props ?? {};
// `undefined` behaves as omitted so spread bindings can inherit; an explicit
// null or empty string clears the owner and renders the transparent swatch.
return Object.hasOwn(raw, "color") && raw.color !== undefined;
}
const hasOwnColor = shallowRef(presentsColor());
onBeforeUpdate(() => {
hasOwnColor.value = presentsColor();
});
const resolvedColor = computed(() => {
const candidate = hasOwnColor.value ? props.color : owner?.value.value;
return candidate == null || candidate === "" ? null : copyColor(candidate);
});
const displayColor = computed(() => resolvedColor.value ?? TRANSPARENT);
const renderProps = computed(() => ({ color: displayColor.value }));
const classes = computed(() =>
colorSwatchVariants({ shape: props.shape, size: props.size }),
);
const locale = computed(() => config?.locale.value ?? "en-US");
const baseStyle = computed<CSSProperties>(() => {
const css = displayColor.value.toString("css");
return {
backgroundColor: css,
forcedColorAdjust: "none",
"--color-swatch-current": css,
} as CSSProperties;
});
const userStyle = computed<StyleValue | undefined>(() => {
if (props.styleFn) return props.styleFn({ color: displayColor.value });
return typeof props.style === "function"
? props.style({ color: displayColor.value })
: props.style;
});
function accessibleName() {
if (props.colorName) return props.colorName;
if (displayColor.value.getChannelValue("alpha") === 0)
return locale.value.toLowerCase().startsWith("zh") ? "透明" : "transparent";
return displayColor.value.toString(
displayColor.value.getChannelValue("alpha") === 1 ? "hex" : "hexa",
);
}
function resolvedId() {
return attrs.id == null ? generatedId : String(attrs.id);
}
function ariaLabel() {
const explicit = attrs["aria-label"];
return [accessibleName(), explicit == null ? "" : String(explicit)]
.filter(Boolean)
.join(", ");
}
function ariaLabelledBy() {
const labelled = attrs["aria-labelledby"];
return labelled ? `${resolvedId()} ${String(labelled)}` : undefined;
}
function roleDescription() {
return locale.value.toLowerCase().startsWith("zh")
? "颜色色板"
: "color swatch";
}
function setRoot(node: unknown) {
const next =
node instanceof HTMLElement
? node
: ((node as { $el?: HTMLElement } | null)?.$el ?? undefined);
if (element.value !== next) element.value = next;
}
defineExpose({ element });
</script>
<template>
<Primitive
:ref="setRoot"
v-bind="attrs"
:as="as"
:as-child="asChild"
:class="[classes, attrs.class]"
:style="[baseStyle, attrs.style, userStyle]"
:id="resolvedId()"
role="img"
:aria-roledescription="roleDescription()"
:aria-label="ariaLabel()"
:aria-labelledby="ariaLabelledBy()"
data-slot="color-swatch"
>
<slot v-bind="renderProps" />
</Primitive>
</template>
@@ -0,0 +1,24 @@
import type { StyleValue, VNodeChild } from "vue";
import type { Color } from "../color/value";
/** Render values shared by the style function and the default scoped slot. */
export interface ColorSwatchRenderProps {
color: Color;
}
/**
* Function form of the upstream `style` render prop. Vue's template compiler
* reserves `style` and normalizes function values away, so templates pass the
* render function through `styleFn`; render functions may pass it directly.
*/
export type ColorSwatchStyleFn = (
renderProps: ColorSwatchRenderProps,
) => StyleValue | undefined;
/** Vue style binding (object/array/string) or the upstream style function. */
export type ColorSwatchStyle = StyleValue | ColorSwatchStyleFn;
/** Default scoped slot; `asChild` merges swatch semantics onto its root. */
export interface ColorSwatchSlots {
default?: (renderProps: ColorSwatchRenderProps) => VNodeChild;
}
+38 -8
View File
@@ -3,11 +3,41 @@ import {
convertToHsl,
convertToHsb,
parseColor as parseWireColor,
type Color as WireColor,
type ColorSpace,
type ColorChannel,
} from "reka-ui";
export type { ColorSpace, ColorChannel } from "reka-ui";
/** Library color spaces; structurally identical to the Reka boundary. */
export type ColorSpace = "rgb" | "hsl" | "hsb";
export type ColorChannel =
| "red"
| "green"
| "blue"
| "hue"
| "saturation"
| "lightness"
| "brightness"
| "alpha";
export interface RGBColor {
space: "rgb";
r: number;
g: number;
b: number;
alpha: number;
}
export interface HSLColor {
space: "hsl";
h: number;
s: number;
l: number;
alpha: number;
}
export interface HSBColor {
space: "hsb";
h: number;
s: number;
b: number;
alpha: number;
}
/** Structural input accepted by the public Color constructor. */
export type ColorInput = RGBColor | HSLColor | HSBColor;
export type ColorFormat =
ColorSpace | "css" | "hex" | "hexa" | "rgba" | "hsla" | "hsba";
export type ColorAxisChannel = Exclude<ColorChannel, "alpha">;
@@ -36,8 +66,8 @@ const clamp = (value: number, max: number) =>
const round = (value: number) => Math.round(value * 100) / 100;
/** Immutable library color boundary; accepted state is never serialized through hex. */
export class Color {
readonly #value: WireColor;
constructor(value: WireColor) {
readonly #value: ColorInput;
constructor(value: ColorInput) {
const alpha = clamp(value.alpha, 1);
if (value.space === "rgb")
this.#value = {
@@ -99,7 +129,7 @@ export class Color {
);
}
/** Internal conversion bridge, omitted from the public Color instance type. */
static toWire(value: Color): WireColor {
static toWire(value: Color): ColorInput {
return { ...value.#value };
}
toFormat(space: ColorSpace): Color {
@@ -191,7 +221,7 @@ export class Color {
const alpha = this.#value.alpha;
if (format === "hex" || format === "hexa") {
const v = this.toFormat("rgb").#value as Extract<
WireColor,
ColorInput,
{ space: "rgb" }
>;
const hex = (n: number) =>
+28
View File
@@ -1083,3 +1083,31 @@ export {
autocompleteVariants,
type AutocompleteVariants,
} from "@heroui-vue/styles";
export { default as ColorSwatch } from "./components/color-swatch/ColorSwatch.vue";
export { default as ColorSwatchRoot } from "./components/color-swatch/ColorSwatch.vue";
export {
colorSwatchVariants,
type ColorSwatchVariants,
} from "@heroui-vue/styles";
export {
Color,
parseColor,
type ColorAxisChannel,
type ColorChannel,
type ColorFormat,
type ColorInput,
type ColorSpace,
type ColorValue,
type HSLColor,
type HSBColor,
type RGBColor,
} from "./components/color/value";
export type {
ColorSwatchProps,
ColorSwatchRenderProps,
ColorSwatchRootProps,
ColorSwatchSlots,
ColorSwatchStyle,
ColorSwatchStyleFn,
} from "./types";
+10
View File
@@ -869,3 +869,13 @@ import type AutocompleteFilter from "./components/autocomplete/AutocompleteFilte
export type AutocompleteFilterProps = InstanceType<
typeof AutocompleteFilter
>["$props"];
import type ColorSwatch from "./components/color-swatch/ColorSwatch.vue";
export type ColorSwatchProps = InstanceType<typeof ColorSwatch>["$props"];
export type ColorSwatchRootProps = ColorSwatchProps;
export type {
ColorSwatchRenderProps,
ColorSwatchSlots,
ColorSwatchStyle,
ColorSwatchStyleFn,
} from "./components/color-swatch/types";