feat: publish ColorSwatchPicker and shared swatch picker parts

This commit is contained in:
maoyingjie
2026-10-27 14:42:29 +08:00
parent fa4146ee0b
commit 8d9adda8da
38 changed files with 3232 additions and 9 deletions
@@ -0,0 +1,383 @@
<script setup lang="ts">
import {
computed,
mergeProps,
provide,
shallowRef,
useAttrs,
watch,
} from "vue";
import { colorSwatchPickerVariants } from "@heroui-vue/styles";
import { useConfig } from "../../providers/context";
import { useColorState } from "../color/model";
import { parseColor, type Color, type ColorValue } from "../color/value";
import { useCollectionRegistry } from "../collection/registry";
import {
colorSwatchPickerKey,
type ColorSwatchPickerKey,
type ColorSwatchPickerMember,
} from "./context";
import { createColorSwatchPickerDelegate } from "./navigation";
import type {
ColorSwatchPickerLayout,
ColorSwatchPickerRenderProps,
ColorSwatchPickerShape,
ColorSwatchPickerSize,
ColorSwatchPickerSlots,
} from "./types";
defineOptions({ inheritAttrs: false, name: "ColorSwatchPicker" });
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; defaults to `#000000` like the fixed source. */
defaultValue?: ColorValue | null;
layout?: ColorSwatchPickerLayout;
size?: ColorSwatchPickerSize;
variant?: ColorSwatchPickerShape;
isDisabled?: boolean;
/** Alias for `isDisabled`. */
disabled?: boolean;
/** Library extension: blocks selection without leaving the tab order. */
isReadOnly?: boolean;
dir?: "ltr" | "rtl";
/** Render a different root element; corresponds to the upstream render prop. */
as?: string;
}>(),
{
modelValue: undefined,
value: undefined,
defaultValue: undefined,
layout: "grid",
size: "md",
variant: "circle",
isDisabled: false,
disabled: false,
isReadOnly: false,
dir: undefined,
as: "div",
},
);
defineSlots<ColorSwatchPickerSlots>();
const emit = defineEmits<{
"update:modelValue": [value: Color];
change: [value: Color];
}>();
const attrs = useAttrs();
const config = useConfig();
const locale = computed(() => config?.locale.value ?? "en-US");
const dir = computed<"ltr" | "rtl">(
() => props.dir ?? config?.dir.value ?? "ltr",
);
const state = useColorState(props, {
fallback: () => parseColor("#000000"),
inherit: true,
provide: true,
change: (value) => {
if (!value) return;
emit("update:modelValue", value);
emit("change", value);
},
});
const registry = useCollectionRegistry<ColorSwatchPickerMember>();
let sequence = 0;
const nextKey = () => ++sequence;
const ordered = () => registry.ordered();
const enabled = () => registry.available();
const rootElement = shallowRef<HTMLElement>();
const focused = shallowRef<ColorSwatchPickerKey>();
const within = shallowRef(false);
const focusVisible = shallowRef(false);
const pressed = shallowRef<ColorSwatchPickerKey>();
/**
* Selection compares derived hexa keys like the fixed source. The accepted
* value keeps its own space and precision and is never rewritten to match.
*/
const acceptedKey = computed(() =>
state.value.value ? state.value.value.toString("hexa") : undefined,
);
const selected = (color: Color) =>
acceptedKey.value !== undefined &&
color.toString("hexa") === acceptedKey.value;
const itemDisabled = (key: ColorSwatchPickerKey) =>
state.disabled.value ||
!!ordered().find((member) => member.key() === key)?.disabled();
const delegate = createColorSwatchPickerDelegate({
container: () => rootElement.value,
members: () => enabled(),
layout: () => props.layout,
dir: () => dir.value,
locale: () => locale.value,
});
function focusItem(key: ColorSwatchPickerKey) {
const member = enabled().find((item) => item.key() === key);
if (!member) return;
focused.value = key;
const element = member.element();
element?.focus({ preventScroll: true });
element?.scrollIntoView?.({ block: "nearest" });
}
function activate(key: ColorSwatchPickerKey, event: Event) {
if (event.defaultPrevented) return;
if (state.disabled.value || state.readOnly.value) return;
const member = ordered().find((item) => item.key() === key);
if (!member || member.disabled()) return;
const color = member.color();
// The fixed source emits nothing when the selection key does not change.
if (selected(color)) return;
state.request(color);
}
function entryKey(from: Element | null | undefined) {
const items = enabled();
if (!items.length) return undefined;
const backward = !!(
from &&
rootElement.value &&
rootElement.value.compareDocumentPosition(from) &
Node.DOCUMENT_POSITION_FOLLOWING
);
const selectedKeys = items
.filter((item) => selected(item.color()))
.map((item) => item.key());
return (
(backward ? selectedKeys.at(-1) : selectedKeys[0]) ??
(backward ? items.at(-1)?.key() : items[0]?.key())
);
}
function matchesFocusVisible(target: EventTarget | null) {
try {
return (
target instanceof Element && target.matches(":focus-visible")
);
} catch {
return false;
}
}
function onRootFocus(event: FocusEvent) {
within.value = true;
focusVisible.value = matchesFocusVisible(event.target);
if (event.target !== rootElement.value) return;
const key =
focused.value ?? entryKey(event.relatedTarget as Element | null);
if (key !== undefined) focusItem(key);
}
function onRootFocusout(event: FocusEvent) {
if (rootElement.value?.contains(event.relatedTarget as Node | null)) return;
within.value = false;
focusVisible.value = false;
pressed.value = undefined;
}
let search = "";
let lastSearch = 0;
function onRootKeydown(event: KeyboardEvent) {
if (event.defaultPrevented || event.isComposing || event.keyCode === 229)
return;
if (state.disabled.value) return;
if (!enabled().length) return;
const current = focused.value;
const step = (forward: boolean) => {
if (current === undefined)
return forward ? delegate.firstKey() : delegate.lastKey();
return forward ? delegate.keyBelow(current) : delegate.keyAbove(current);
};
let target: ColorSwatchPickerKey | undefined;
switch (event.key) {
case "Home":
case "End":
target = event.key === "Home" ? delegate.firstKey() : delegate.lastKey();
if (target !== undefined) {
event.preventDefault();
focusItem(target);
}
return;
case "ArrowDown":
case "ArrowUp":
target = step(event.key === "ArrowDown");
break;
case "ArrowRight":
case "ArrowLeft": {
if (current === undefined) {
const first = delegate.firstKey();
if (first !== undefined) {
event.preventDefault();
focusItem(first);
}
return;
}
target =
event.key === "ArrowRight"
? delegate.keyRightOf(current)
: delegate.keyLeftOf(current);
break;
}
case "PageDown":
case "PageUp":
target =
current === undefined
? undefined
: delegate.pageKey(current, event.key === "PageDown");
break;
case "Enter":
case " ":
if (event.repeat) {
event.preventDefault();
return;
}
if (current !== undefined) activate(current, event);
event.preventDefault();
return;
default:
target = undefined;
}
if (target !== undefined) {
event.preventDefault();
focusItem(target);
return;
}
if (event.ctrlKey || event.metaKey || event.altKey) return;
if (event.key.length !== 1 || event.key === " ") return;
const now = Date.now();
search = now - lastSearch > 1000 ? event.key : search + event.key;
lastSearch = now;
const query = [...search].every((character) => character === search[0])
? search[0]!
: search;
const match = delegate.keyForSearch(query, current);
if (match !== undefined) {
event.preventDefault();
focusItem(match);
}
}
// A removed or disabled item cannot stay focused; focus falls back to the
// listbox entry so it is not lost to the document.
watch(
() => registry.ordered(),
() => {
if (focused.value === undefined) return;
const member = enabled().find((item) => item.key() === focused.value);
if (member) return;
focused.value = undefined;
if (rootElement.value?.contains(document.activeElement))
rootElement.value.focus();
},
);
const classes = computed(() =>
colorSwatchPickerVariants({
layout: props.layout,
size: props.size,
variant: props.variant,
}),
);
const slotState = computed<ColorSwatchPickerRenderProps>(() => ({
color: state.value.value,
isEmpty: ordered().length === 0,
isDisabled: state.disabled.value,
isReadOnly: state.readOnly.value,
isFocused: within.value,
layout: props.layout,
}));
function defaultLabel() {
return locale.value.toLowerCase().startsWith("zh")
? "颜色色块选择器"
: "Color swatch picker";
}
function rootAttrs() {
return mergeProps(attrs, {
role: "listbox",
"data-slot": "color-swatch-picker",
class: [classes.value.base(), attrs.class],
dir: dir.value,
tabindex: state.disabled.value || focused.value !== undefined ? -1 : 0,
"aria-label": attrs["aria-label"] ?? defaultLabel(),
"aria-orientation": "vertical",
"aria-disabled": state.disabled.value || undefined,
"aria-readonly": state.readOnly.value || undefined,
"data-disabled": state.disabled.value || undefined,
"data-readonly": state.readOnly.value || undefined,
"data-focused": within.value || undefined,
"data-focus-visible": (within.value && focusVisible.value) || undefined,
onFocusin: onRootFocus,
onFocusout: onRootFocusout,
onKeydown: onRootKeydown,
onMousedown: () => {
focusVisible.value = false;
},
onKeyupCapture: () => {
pressed.value = undefined;
},
ref: (node: unknown) => {
rootElement.value =
node instanceof HTMLElement
? node
: ((node as { $el?: HTMLElement } | null)?.$el ?? undefined);
},
} as Record<string, unknown>);
}
provide(colorSwatchPickerKey, {
state,
classes,
layout: computed(() => props.layout),
dir,
disabled: computed(() => state.disabled.value),
nextKey,
register: registry.register,
selected,
itemDisabled,
focused,
focusWithin: within,
focusVisible,
pressed,
noteFocus: (key) => {
focused.value = key;
},
noteBlur: (key) => {
if (focused.value !== key) return;
focusVisible.value = false;
pressed.value = undefined;
},
focusItem,
activate,
});
defineExpose({
element: rootElement,
focus: () => {
const key = focused.value ?? entryKey(undefined);
if (key !== undefined) focusItem(key);
else rootElement.value?.focus();
},
});
</script>
<template>
<component :is="as" v-bind="rootAttrs()">
<slot v-bind="slotState" />
</component>
</template>
@@ -0,0 +1,66 @@
<script setup lang="ts">
import { computed, inject, mergeProps, useAttrs } from "vue";
import {
colorSwatchPickerKey,
useColorSwatchPickerItem,
} from "./context";
import type { ColorSwatchPickerIndicatorSlots } from "./types";
defineOptions({ inheritAttrs: false, name: "ColorSwatchPickerIndicator" });
const props = withDefaults(
defineProps<{
/** Render a different root element; corresponds to the upstream render prop. */
as?: string;
}>(),
{ as: "span" },
);
defineSlots<ColorSwatchPickerIndicatorSlots>();
const item = useColorSwatchPickerItem();
const picker = inject(colorSwatchPickerKey, undefined);
const attrs = useAttrs();
const state = item.state;
/** Relative luminance over 0.5 means a light swatch needs the dark checkmark. */
const isLightColor = computed(() => {
const rgb = item.state.value.color.toFormat("rgb");
return (
(0.2126 * rgb.getChannelValue("red") +
0.7152 * rgb.getChannelValue("green") +
0.0722 * rgb.getChannelValue("blue")) /
255 >
0.5
);
});
function indicatorAttrs() {
return mergeProps(attrs, {
"aria-hidden": "true",
"data-slot": "color-swatch-picker-indicator",
"data-light-color": isLightColor.value ? "true" : undefined,
class: [picker?.classes.value.indicator(), attrs.class],
} as Record<string, unknown>);
}
</script>
<template>
<component :is="as" v-bind="indicatorAttrs()">
<slot v-bind="state">
<svg
aria-hidden="true"
data-slot="color-swatch-picker-checkmark"
fill="none"
role="presentation"
stroke="currentColor"
stroke-linecap="round"
stroke-linejoin="round"
stroke-width="1.5"
viewBox="0 0 12 12"
>
<polyline points="2.5 6 5 8.5 9.5 3" />
</svg>
</slot>
</component>
</template>
@@ -0,0 +1,158 @@
<script setup lang="ts">
import {
computed,
mergeProps,
provide,
shallowRef,
useAttrs,
useId,
} from "vue";
import { useConfig } from "../../providers/context";
import {
colorSwatchPickerItemKey,
useColorSwatchPicker,
} from "./context";
import { copyColor, parseColor, type Color, type ColorValue } from "../color/value";
import type {
ColorSwatchPickerItemRenderProps,
ColorSwatchPickerItemSlots,
} from "./types";
defineOptions({ inheritAttrs: false, name: "ColorSwatchPickerItem" });
const props = withDefaults(
defineProps<{
/** Candidate color; omitted or empty renders the transparent swatch. */
color?: ColorValue | null;
isDisabled?: boolean;
/** Render a different root element; corresponds to the upstream render prop. */
as?: string;
}>(),
{
color: undefined,
isDisabled: false,
as: "div",
},
);
defineSlots<ColorSwatchPickerItemSlots>();
const picker = useColorSwatchPicker();
const attrs = useAttrs();
const config = useConfig();
const generatedId = useId();
const element = shallowRef<HTMLElement>();
const hovered = shallowRef(false);
const key = picker.nextKey();
const TRANSPARENT = parseColor("#0000");
const itemColor = computed<Color>(
() =>
(props.color == null || props.color === ""
? null
: copyColor(props.color)) ?? TRANSPARENT,
);
function isZh() {
return (config?.locale.value ?? "en-US").toLowerCase().startsWith("zh");
}
function accessibleName() {
const explicit = attrs["aria-label"];
if (explicit != null) return String(explicit);
const color = itemColor.value;
if (color.getChannelValue("alpha") === 0) return isZh() ? "透明" : "transparent";
return color.toString(
color.getChannelValue("alpha") === 1 ? "hex" : "hexa",
);
}
picker.register({
key: () => key,
element: () => element.value,
color: () => itemColor.value,
textValue: () => accessibleName(),
disabled: () => !!props.isDisabled,
});
const state = computed<ColorSwatchPickerItemRenderProps>(() => {
const isDisabled = picker.itemDisabled(key);
const isFocused = picker.focusWithin.value && picker.focused.value === key;
return {
color: itemColor.value,
isSelected: picker.selected(itemColor.value),
isDisabled,
isFocused,
isFocusVisible: isFocused && picker.focusVisible.value,
isPressed: picker.pressed.value === key,
isHovered: hovered.value,
};
});
provide(colorSwatchPickerItemKey, { key, state });
function onMousedown(event: MouseEvent) {
if (state.value.isDisabled) {
// Keep focus from moving onto a disabled option.
event.preventDefault();
return;
}
picker.pressed.value = key;
picker.activate(key, event);
element.value?.focus({ preventScroll: true });
picker.noteFocus(key);
}
function itemAttrs() {
return mergeProps(attrs, {
role: "option",
id: attrs.id == null ? generatedId : String(attrs.id),
tabindex: state.value.isDisabled
? undefined
: picker.focused.value === key
? 0
: -1,
"aria-selected": state.value.isSelected,
"aria-disabled": state.value.isDisabled || undefined,
"aria-label": accessibleName(),
"data-slot": "color-swatch-picker-item",
"data-selected": state.value.isSelected || undefined,
"data-disabled": state.value.isDisabled || undefined,
"data-hovered": state.value.isHovered || undefined,
"data-focused": state.value.isFocused || undefined,
"data-focus-visible": state.value.isFocusVisible || undefined,
"data-pressed": state.value.isPressed || undefined,
class: [picker.classes.value.item(), attrs.class],
style: [
{
"--color-swatch-current": itemColor.value.toString("css"),
},
attrs.style,
],
ref: (node: unknown) => {
element.value =
node instanceof HTMLElement
? node
: ((node as { $el?: HTMLElement } | null)?.$el ?? undefined);
},
onFocus: () => picker.noteFocus(key),
onBlur: () => picker.noteBlur(key),
onMousedown,
onMouseenter: () => {
hovered.value = true;
},
onMouseleave: () => {
hovered.value = false;
picker.pressed.value = undefined;
},
} as Record<string, unknown>);
}
defineExpose({ element });
</script>
<template>
<component :is="as" v-bind="itemAttrs()">
<slot v-bind="state" />
</component>
</template>
@@ -0,0 +1,67 @@
<script setup lang="ts">
import { computed, inject, mergeProps, useAttrs } from "vue";
import {
colorSwatchPickerKey,
useColorSwatchPickerItem,
} from "./context";
import { copyColor, type Color, type ColorValue } from "../color/value";
defineOptions({ inheritAttrs: false, name: "ColorSwatchPickerSwatch" });
const props = withDefaults(
defineProps<{
/** Defaults to the enclosing item's color. */
color?: ColorValue | null;
/** Localized accessible color name; overrides the generated description. */
colorName?: string;
as?: string;
}>(),
{
color: undefined,
colorName: undefined,
as: "div",
},
);
const item = useColorSwatchPickerItem();
const picker = inject(colorSwatchPickerKey, undefined);
const attrs = useAttrs();
const resolved = computed<Color>(() => {
const raw = props.color;
if (raw != null && raw !== "") return copyColor(raw)!;
return item.state.value.color;
});
function autoName() {
const color = resolved.value;
if (color.getChannelValue("alpha") === 0) return "transparent";
return color.toString(
color.getChannelValue("alpha") === 1 ? "hex" : "hexa",
);
}
function swatchAttrs() {
const css = resolved.value.toString("css");
return mergeProps(attrs, {
role: "img",
"data-slot": "color-swatch-picker-swatch",
"aria-label": [props.colorName ?? autoName(), attrs["aria-label"] ?? ""]
.filter(Boolean)
.join(", "),
class: [picker?.classes.value.swatch(), attrs.class],
style: [
{
backgroundColor: css,
forcedColorAdjust: "none",
"--color-swatch-current": css,
} as Record<string, string>,
attrs.style,
],
} as Record<string, unknown>);
}
</script>
<template>
<component :is="as" v-bind="swatchAttrs()" />
</template>
@@ -0,0 +1,83 @@
import {
inject,
type ComputedRef,
type InjectionKey,
type Ref,
} from "vue";
import type { ColorState } from "../color/model";
import type { Color } from "../color/value";
import type { ColorSwatchPickerLayout } from "./types";
/**
* Structural item identity. Candidate colors may repeat or be equivalent, so a
* color string is never the key and items are never merged.
*/
export type ColorSwatchPickerKey = number;
export interface ColorSwatchPickerMember {
key: () => ColorSwatchPickerKey;
element: () => HTMLElement | undefined;
color: () => Color;
/** Accessible name used for type-to-select matching. */
textValue: () => string;
disabled: () => boolean;
}
/** Slot class names resolved once on the root. */
export interface ColorSwatchPickerClasses {
base: () => string;
item: () => string;
swatch: () => string;
indicator: () => string;
}
export interface ColorSwatchPickerContext {
/** The single accepted color source; items never own one. */
state: ColorState;
classes: ComputedRef<ColorSwatchPickerClasses>;
layout: ComputedRef<ColorSwatchPickerLayout>;
dir: ComputedRef<"ltr" | "rtl">;
disabled: ComputedRef<boolean>;
nextKey: () => ColorSwatchPickerKey;
register: (member: ColorSwatchPickerMember) => () => void;
/** Selection compares derived hexa keys; the accepted value is never rewritten. */
selected: (color: Color) => boolean;
itemDisabled: (key: ColorSwatchPickerKey) => boolean;
focused: Ref<ColorSwatchPickerKey | undefined>;
focusWithin: Ref<boolean>;
focusVisible: Ref<boolean>;
pressed: Ref<ColorSwatchPickerKey | undefined>;
noteFocus: (key: ColorSwatchPickerKey) => void;
noteBlur: (key: ColorSwatchPickerKey) => void;
focusItem: (key: ColorSwatchPickerKey) => void;
/** Pointer press selection; cancelable native events are honoured. */
activate: (key: ColorSwatchPickerKey, event: Event) => void;
}
export const colorSwatchPickerKey: InjectionKey<ColorSwatchPickerContext> =
Symbol("hv-color-swatch-picker");
export interface ColorSwatchPickerItemContext {
key: ColorSwatchPickerKey;
state: ComputedRef<import("./types").ColorSwatchPickerItemRenderProps>;
}
export const colorSwatchPickerItemKey: InjectionKey<ColorSwatchPickerItemContext> =
Symbol("hv-color-swatch-picker-item");
export function useColorSwatchPicker() {
const context = inject(colorSwatchPickerKey, undefined);
if (!context)
throw new Error("ColorSwatchPickerItem requires ColorSwatchPicker.");
return context;
}
/** Item parts read the nearest item; no metadata is probed from wrappers. */
export function useColorSwatchPickerItem() {
const context = inject(colorSwatchPickerItemKey, undefined);
if (!context)
throw new Error(
"ColorSwatchPickerSwatch and ColorSwatchPickerIndicator require ColorSwatchPickerItem.",
);
return context;
}
@@ -0,0 +1,189 @@
import type {
ColorSwatchPickerKey,
ColorSwatchPickerMember,
} from "./context";
interface Rect {
x: number;
y: number;
width: number;
height: number;
}
/** Container-relative item geometry, matching the fixed source delegate. */
export function relativeRect(
container: HTMLElement,
item: HTMLElement,
): Rect {
const containerRect = container.getBoundingClientRect();
const rect = item.getBoundingClientRect();
return {
x: rect.left - containerRect.left - container.clientLeft + container.scrollLeft,
y: rect.top - containerRect.top - container.clientTop + container.scrollTop,
width: rect.width,
height: rect.height,
};
}
function isScrollable(element: HTMLElement) {
return (
element.scrollHeight > element.clientHeight + 1 ||
element.scrollWidth > element.clientWidth + 1
);
}
export interface ColorSwatchPickerDelegateOptions {
container: () => HTMLElement | undefined;
/** Enabled members in DOM order. */
members: () => readonly ColorSwatchPickerMember[];
layout: () => "grid" | "stack";
dir: () => "ltr" | "rtl";
locale: () => string;
}
/**
* Fixed-source keyboard delegate: order movement along the row, geometry
* movement across wrapped grid rows, no focus wrapping at the boundaries.
*/
export function createColorSwatchPickerDelegate(
options: ColorSwatchPickerDelegateOptions,
) {
const rectOf = (key: ColorSwatchPickerKey) => {
const container = options.container();
const member = options.members().find((item) => item.key() === key);
const element = member?.element();
if (!container || !container.isConnected || !element) return undefined;
return relativeRect(container, element);
};
const order = () => options.members().map((item) => item.key());
const indexOf = (key: ColorSwatchPickerKey) => order().indexOf(key);
const nextKey = (key: ColorSwatchPickerKey) => {
const keys = order();
return keys[indexOf(key) + 1];
};
const previousKey = (key: ColorSwatchPickerKey) => {
const keys = order();
return keys[indexOf(key) - 1];
};
/** Skip while the candidate shares the row or misses the column. */
const isSameRow = (start: Rect, candidate: Rect) =>
start.y === candidate.y || start.x !== candidate.x;
const isSameColumn = (start: Rect, candidate: Rect) =>
start.x === candidate.x || start.y !== candidate.y;
function findKey(
key: ColorSwatchPickerKey,
next: (key: ColorSwatchPickerKey) => ColorSwatchPickerKey | undefined,
shouldSkip: (start: Rect, candidate: Rect) => boolean,
) {
const start = rectOf(key);
if (!start) return undefined;
let current = next(key);
while (current !== undefined) {
const candidate = rectOf(current);
if (!candidate) return undefined;
if (!shouldSkip(start, candidate)) return current;
current = next(current);
}
return undefined;
}
/** Column-reverse containers move in reverse document order. */
function isReversed(key: ColorSwatchPickerKey) {
const current = rectOf(key);
if (!current) return false;
const next = nextKey(key);
if (next !== undefined) {
const nextRect = rectOf(next);
return !!nextRect && current.y > nextRect.y;
}
const previous = previousKey(key);
if (previous !== undefined) {
const previousRect = rectOf(previous);
return !!previousRect && previousRect.y > current.y;
}
return false;
}
function keyBelow(key: ColorSwatchPickerKey) {
if (options.layout() === "grid")
return findKey(key, nextKey, isSameRow);
return isReversed(key) ? previousKey(key) : nextKey(key);
}
function keyAbove(key: ColorSwatchPickerKey) {
if (options.layout() === "grid")
return findKey(key, previousKey, isSameRow);
return isReversed(key) ? nextKey(key) : previousKey(key);
}
function keyRightOf(key: ColorSwatchPickerKey) {
if (options.layout() !== "grid") return undefined;
return options.dir() === "rtl" ? previousKey(key) : nextKey(key);
}
function keyLeftOf(key: ColorSwatchPickerKey) {
if (options.layout() !== "grid") return undefined;
return options.dir() === "ltr" ? previousKey(key) : nextKey(key);
}
function firstKey() {
return order()[0];
}
function lastKey() {
return order().at(-1);
}
function pageKey(key: ColorSwatchPickerKey, forward: boolean) {
const container = options.container();
const start = rectOf(key);
if (!container || !start) return undefined;
if (!isScrollable(container)) return forward ? lastKey() : firstKey();
const visible = {
height: container.clientHeight,
};
const contentHeight = container.scrollHeight;
const pageY = forward
? Math.min(contentHeight, start.y - start.height + visible.height)
: Math.max(0, start.y + start.height - visible.height);
let current: ColorSwatchPickerKey | undefined = key;
let currentRect: Rect | undefined = start;
while (
current !== undefined &&
currentRect &&
(forward ? currentRect.y < pageY : currentRect.y > pageY)
) {
current = forward ? keyBelow(current) : keyAbove(current);
currentRect = current === undefined ? undefined : rectOf(current);
}
return current ?? (forward ? lastKey() : firstKey());
}
function keyForSearch(search: string, fromKey?: ColorSwatchPickerKey) {
const keys = order();
const collator = new Intl.Collator(options.locale(), {
usage: "search",
sensitivity: "base",
});
let index =
fromKey === undefined ? 0 : Math.max(0, keys.indexOf(fromKey));
while (index < keys.length) {
const member = options.members().find((item) => item.key() === keys[index]);
const text = member?.textValue() ?? "";
if (
text &&
collator.compare(text.slice(0, search.length), search) === 0
)
return keys[index];
index++;
}
return undefined;
}
return {
keyBelow,
keyAbove,
keyLeftOf,
keyRightOf,
firstKey,
lastKey,
pageKey,
keyForSearch,
};
}
@@ -0,0 +1,59 @@
import type { VNodeChild } from "vue";
import type { Color } from "../color/value";
import type ColorSwatchPicker from "./ColorSwatchPicker.vue";
import type ColorSwatchPickerItem from "./ColorSwatchPickerItem.vue";
/** Visual arrangement only; the listbox orientation stays vertical. */
export type ColorSwatchPickerLayout = "grid" | "stack";
export type ColorSwatchPickerSize = "xs" | "sm" | "md" | "lg" | "xl";
export type ColorSwatchPickerShape = "circle" | "square";
/**
* Scoped slot state of ColorSwatchPickerItem and ColorSwatchPickerIndicator.
* Selection is the accepted color state; focus is separate item state.
*/
export interface ColorSwatchPickerItemRenderProps {
/** The candidate color of this item. */
color: Color;
/** Whether this item's color matches the accepted color. */
isSelected: boolean;
isDisabled: boolean;
isFocused: boolean;
isFocusVisible: boolean;
isPressed: boolean;
isHovered: boolean;
}
/** Scoped slot state of the ColorSwatchPicker root. */
export interface ColorSwatchPickerRenderProps {
/** Accepted color; `null` only when a controlled value explicitly clears it. */
color: Color | null;
isEmpty: boolean;
isDisabled: boolean;
isReadOnly: boolean;
isFocused: boolean;
layout: ColorSwatchPickerLayout;
}
export interface ColorSwatchPickerSlots {
default?: (state: ColorSwatchPickerRenderProps) => VNodeChild;
}
export interface ColorSwatchPickerItemSlots {
default?: (state: ColorSwatchPickerItemRenderProps) => VNodeChild;
}
export interface ColorSwatchPickerIndicatorSlots {
default?: (state: ColorSwatchPickerItemRenderProps) => VNodeChild;
}
/** Root instance surface; no owner or transaction state is exposed. */
export type ColorSwatchPickerExpose = Pick<
InstanceType<typeof ColorSwatchPicker>,
"element" | "focus"
>;
export type ColorSwatchPickerItemExpose = Pick<
InstanceType<typeof ColorSwatchPickerItem>,
"element"
>;