fix: preserve ColorSwatch asChild ids and merged styles

This commit is contained in:
maoyingjie
2026-10-26 13:38:15 +08:00
parent 270dea5cff
commit b18949c071
6 changed files with 167 additions and 35 deletions
@@ -1,13 +1,21 @@
<script setup lang="ts">
import {
Comment,
Fragment,
Text,
computed,
getCurrentInstance,
h,
isVNode,
onBeforeUpdate,
shallowRef,
useAttrs,
useId,
useSlots,
type CSSProperties,
type StyleValue,
type VNode,
type VNodeChild,
} from "vue";
import { Primitive } from "reka-ui";
import {
@@ -57,6 +65,7 @@ const props = withDefaults(
defineSlots<ColorSwatchSlots>();
const attrs = useAttrs();
const slots = useSlots();
const instance = getCurrentInstance()!;
const owner = useColorStateContext();
const config = useConfig();
@@ -64,6 +73,30 @@ const generatedId = useId();
const element = shallowRef<HTMLElement>();
const TRANSPARENT = parseColor("#fff0");
function meaningfulVNodes(children: unknown): VNode[] {
const out: VNode[] = [];
const walk = (nodes: unknown[]) => {
for (const node of nodes) {
if (node == null || node === false || node === true) continue;
if (Array.isArray(node)) {
walk(node);
continue;
}
if (!isVNode(node)) continue;
if (node.type === Fragment) {
walk(Array.isArray(node.children) ? node.children : []);
continue;
}
if (node.type === Comment) continue;
if (node.type === Text && String(node.children ?? "").trim() === "")
continue;
out.push(node);
}
};
walk([children]);
return out;
}
function presentsColor() {
const raw = instance.vnode.props ?? {};
// `undefined` behaves as omitted so spread bindings can inherit; an explicit
@@ -81,7 +114,6 @@ const resolvedColor = computed(() => {
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 }),
);
@@ -96,12 +128,15 @@ const baseStyle = computed<CSSProperties>(() => {
} 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;
const ordinaryStyle = computed<StyleValue | undefined>(() => {
const value = props.style;
return typeof value === "function"
? value({ color: displayColor.value })
: value;
});
const computedStyle = computed<StyleValue | undefined>(() =>
props.styleFn?.({ color: displayColor.value }),
);
function accessibleName() {
if (props.colorName) return props.colorName;
@@ -112,10 +147,6 @@ function accessibleName() {
);
}
function resolvedId() {
return attrs.id == null ? generatedId : String(attrs.id);
}
function ariaLabel() {
const explicit = attrs["aria-label"];
return [accessibleName(), explicit == null ? "" : String(explicit)]
@@ -123,17 +154,19 @@ function ariaLabel() {
.join(", ");
}
function ariaLabelledBy() {
const labelled = attrs["aria-labelledby"];
return labelled ? `${resolvedId()} ${String(labelled)}` : undefined;
}
function roleDescription() {
return locale.value.toLowerCase().startsWith("zh")
? "颜色色板"
: "color swatch";
}
/** Reka Slot keeps a child's own ID over merged attrs; mirror that root ID. */
function asChildRootId(children: VNodeChild) {
const root = meaningfulVNodes(children)[0];
const id = root?.props?.id;
return id == null ? undefined : String(id);
}
function setRoot(node: unknown) {
const next =
node instanceof HTMLElement
@@ -142,24 +175,41 @@ function setRoot(node: unknown) {
if (element.value !== next) element.value = next;
}
/** Functional render layer so the default slot is read once per render. */
const Render = () => {
const children = slots.default?.({ color: displayColor.value }) as
VNodeChild | undefined;
const childId = props.asChild ? asChildRootId(children) : undefined;
const effectiveId =
childId ?? (attrs.id == null ? generatedId : String(attrs.id));
const labelledBy = attrs["aria-labelledby"];
return h(
Primitive,
{
...attrs,
as: props.as,
asChild: props.asChild,
id: effectiveId,
role: "img",
"aria-roledescription": roleDescription(),
"aria-label": ariaLabel(),
"aria-labelledby": labelledBy
? `${effectiveId} ${String(labelledBy)}`
: undefined,
// Ordinary styles remain; styleFn is the computed override layer.
class: [classes.value, attrs.class],
style: [baseStyle.value, ordinaryStyle.value, computedStyle.value],
"data-slot": "color-swatch",
ref: setRoot,
},
{ default: () => children },
);
};
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>
<component :is="Render" />
</template>
+1 -1
View File
@@ -128,7 +128,7 @@ export class Color {
: raw,
);
}
/** Internal conversion bridge, omitted from the public Color instance type. */
/** @internal Conversion bridge for library keying and tests. */
static toWire(value: Color): ColorInput {
return { ...value.#value };
}