feat: establish shared color state and area interaction foundation
This commit is contained in:
@@ -0,0 +1,85 @@
|
||||
/* Adapted from HeroUI ce90ea3, Apache-2.0; see third-party/HEROUI-LICENSE. */
|
||||
/* ==========================================================================
|
||||
ColorArea - 2D color picker for selecting colors from a gradient area
|
||||
========================================================================== */
|
||||
|
||||
/* Base styles */
|
||||
.hv-color-area {
|
||||
@apply relative w-full max-w-56 shrink-0 rounded-2xl no-highlight;
|
||||
|
||||
/* Square aspect ratio */
|
||||
aspect-ratio: 1 / 1;
|
||||
|
||||
/* Color gradient background from React Aria */
|
||||
background: var(--color-area-background);
|
||||
|
||||
/* Inner shadow for depth */
|
||||
box-shadow: inset 0 0 0 1px rgba(0, 0, 0, 0.1);
|
||||
|
||||
/* Disabled state */
|
||||
&[data-disabled="true"] {
|
||||
@apply status-disabled;
|
||||
}
|
||||
}
|
||||
|
||||
/* ==========================================================================
|
||||
Dots overlay variant
|
||||
========================================================================== */
|
||||
|
||||
.hv-color-area--show-dots {
|
||||
/* Dot pattern overlay using radial gradient */
|
||||
&::after {
|
||||
content: "";
|
||||
@apply pointer-events-none absolute inset-0 rounded-[inherit];
|
||||
|
||||
background-image: radial-gradient(
|
||||
circle,
|
||||
rgba(255, 255, 255, 0.2) 1px,
|
||||
transparent 1px
|
||||
);
|
||||
background-size: 8px 8px;
|
||||
}
|
||||
}
|
||||
|
||||
/* ==========================================================================
|
||||
Thumb element
|
||||
========================================================================== */
|
||||
|
||||
.hv-color-area__thumb {
|
||||
@apply size-4 rounded-xl will-change-[width,height];
|
||||
|
||||
/* Current color from React Aria */
|
||||
background-color: var(--color-area-thumb-color);
|
||||
|
||||
/* White border for visibility */
|
||||
border: 3px solid white;
|
||||
|
||||
/* Inner shadow for depth */
|
||||
box-shadow:
|
||||
0 0 0 1px rgba(0, 0, 0, 0.1),
|
||||
inset 0 0 0 1px rgba(0, 0, 0, 0.1);
|
||||
|
||||
/**
|
||||
* Transitions
|
||||
* CRITICAL: motion-reduce must be AFTER transition for correct override specificity
|
||||
*/
|
||||
transition:
|
||||
width 150ms var(--ease-out),
|
||||
height 150ms var(--ease-out);
|
||||
@apply motion-reduce:transition-none;
|
||||
|
||||
/* Focus state */
|
||||
&[data-focus-visible="true"] {
|
||||
@apply status-focused;
|
||||
}
|
||||
|
||||
/* Dragging state */
|
||||
&[data-dragging="true"] {
|
||||
@apply size-5;
|
||||
}
|
||||
|
||||
/* Disabled state */
|
||||
&[data-disabled="true"] {
|
||||
@apply status-disabled;
|
||||
}
|
||||
}
|
||||
@@ -160,3 +160,6 @@
|
||||
@import "./components/range-calendar.css" layer(components);
|
||||
|
||||
@import "./components/calendar-year-picker.css" layer(components);
|
||||
|
||||
/* Private color interaction foundation; public components are not exported yet. */
|
||||
@import "./components/color-area.css" layer(components);
|
||||
|
||||
@@ -0,0 +1,325 @@
|
||||
import {
|
||||
computed,
|
||||
nextTick,
|
||||
onBeforeUnmount,
|
||||
shallowRef,
|
||||
watch,
|
||||
type ShallowRef,
|
||||
} from "vue";
|
||||
import {
|
||||
Color,
|
||||
colorAxes,
|
||||
type ColorAxisChannel,
|
||||
type ColorSpace,
|
||||
} from "./value";
|
||||
import type { ColorState } from "./model";
|
||||
import { useChoiceForm } from "../choice/shared";
|
||||
import { useConfig } from "../../providers/context";
|
||||
export interface ColorAreaOptions {
|
||||
colorSpace?: ColorSpace;
|
||||
xChannel?: ColorAxisChannel;
|
||||
yChannel?: ColorAxisChannel;
|
||||
dir?: "ltr" | "rtl";
|
||||
locale?: string;
|
||||
xName?: string;
|
||||
yName?: string;
|
||||
form?: string;
|
||||
}
|
||||
const clamp = (v: number) => Math.max(0, Math.min(1, v));
|
||||
/** Private two-axis controller; it never stores optimistic channel coordinates. */
|
||||
export function useColorArea(
|
||||
state: ColorState,
|
||||
props: ColorAreaOptions,
|
||||
elements: {
|
||||
root: ShallowRef<HTMLElement | undefined>;
|
||||
focusX: ShallowRef<HTMLInputElement | undefined>;
|
||||
focusY: ShallowRef<HTMLInputElement | undefined>;
|
||||
thumb?: ShallowRef<HTMLElement | undefined>;
|
||||
},
|
||||
) {
|
||||
const { root, focusX: thumb, focusY, thumb: handle } = elements;
|
||||
const focusedAxis = shallowRef<"x" | "y">("x");
|
||||
const config = useConfig();
|
||||
const locale = computed(
|
||||
() => props.locale ?? config?.locale.value ?? "en-US",
|
||||
);
|
||||
const dir = computed(() => props.dir ?? config?.dir.value ?? "ltr");
|
||||
const axes = computed(() =>
|
||||
colorAxes(
|
||||
state.value.value ??
|
||||
new Color({ space: "hsb", h: 0, s: 100, b: 100, alpha: 1 }),
|
||||
props.colorSpace,
|
||||
props.xChannel,
|
||||
props.yChannel,
|
||||
),
|
||||
);
|
||||
const x = computed(() => axes.value.color.getChannelValue(axes.value.x)),
|
||||
y = computed(() => axes.value.color.getChannelValue(axes.value.y));
|
||||
const xr = computed(() => axes.value.color.getChannelRange(axes.value.x)),
|
||||
yr = computed(() => axes.value.color.getChannelRange(axes.value.y));
|
||||
const percent = computed(() => ({
|
||||
x: x.value / xr.value.maxValue,
|
||||
y: y.value / yr.value.maxValue,
|
||||
}));
|
||||
const dragging = shallowRef(false);
|
||||
let pointer: number | undefined;
|
||||
let owner: HTMLElement | undefined;
|
||||
let pointerWindow: Window | null | undefined;
|
||||
function windowBlur() {
|
||||
stop();
|
||||
}
|
||||
let grab = { x: 0, y: 0 };
|
||||
const token = Symbol("color-area");
|
||||
const keys = new Set<string>();
|
||||
let lastPoint: string | undefined;
|
||||
function stop(commit = false) {
|
||||
pointerWindow?.removeEventListener("blur", windowBlur);
|
||||
pointerWindow = undefined;
|
||||
const target = owner,
|
||||
id = pointer;
|
||||
pointer = undefined;
|
||||
owner = undefined;
|
||||
dragging.value = false;
|
||||
keys.clear();
|
||||
lastPoint = undefined;
|
||||
if (id !== undefined && target?.hasPointerCapture?.(id))
|
||||
target.releasePointerCapture(id);
|
||||
if (commit) state.end(token);
|
||||
else state.cancel(token);
|
||||
}
|
||||
function local(event: PointerEvent) {
|
||||
const node = root.value;
|
||||
if (!node) return;
|
||||
const rect = node.getBoundingClientRect(),
|
||||
css = getComputedStyle(node);
|
||||
const sx = rect.width / node.offsetWidth || 1,
|
||||
sy = rect.height / node.offsetHeight || 1;
|
||||
const left = (parseFloat(css.borderLeftWidth) || 0) * sx,
|
||||
right = (parseFloat(css.borderRightWidth) || 0) * sx;
|
||||
const top = (parseFloat(css.borderTopWidth) || 0) * sy,
|
||||
bottom = (parseFloat(css.borderBottomWidth) || 0) * sy;
|
||||
const width = rect.width - left - right,
|
||||
height = rect.height - top - bottom;
|
||||
if (width <= 0 || height <= 0) return;
|
||||
return {
|
||||
x: (event.clientX - rect.left - left) / width,
|
||||
y: (event.clientY - rect.top - top) / height,
|
||||
};
|
||||
}
|
||||
function update(point: { x: number; y: number }) {
|
||||
let px = clamp(point.x - grab.x),
|
||||
py = clamp(point.y - grab.y);
|
||||
if (dir.value === "rtl") px = 1 - px;
|
||||
const { color, x: xc, y: yc } = axes.value;
|
||||
const pointKey = `${px}:${py}`;
|
||||
if (pointKey === lastPoint) return;
|
||||
lastPoint = pointKey;
|
||||
state.request(
|
||||
color
|
||||
.withChannelValue(xc, px * xr.value.maxValue)
|
||||
.withChannelValue(yc, (1 - py) * yr.value.maxValue),
|
||||
token,
|
||||
);
|
||||
}
|
||||
function pointerdown(event: PointerEvent) {
|
||||
if (
|
||||
event.defaultPrevented ||
|
||||
event.button !== 0 ||
|
||||
(event.pointerType === "mouse" &&
|
||||
(event.ctrlKey || event.altKey || event.metaKey)) ||
|
||||
event.isPrimary === false ||
|
||||
pointer !== undefined ||
|
||||
state.disabled.value ||
|
||||
state.readOnly.value
|
||||
)
|
||||
return;
|
||||
const point = local(event);
|
||||
if (!point || !root.value) return;
|
||||
stop();
|
||||
if (!state.begin(token)) return;
|
||||
pointer = event.pointerId;
|
||||
owner = root.value;
|
||||
pointerWindow = owner.ownerDocument.defaultView;
|
||||
pointerWindow?.addEventListener("blur", windowBlur);
|
||||
dragging.value = true;
|
||||
const inThumb = !!(handle?.value ?? thumb.value)?.contains(
|
||||
event.target as Node,
|
||||
);
|
||||
grab = inThumb
|
||||
? {
|
||||
x:
|
||||
point.x -
|
||||
(dir.value === "rtl" ? 1 - percent.value.x : percent.value.x),
|
||||
y: point.y - (1 - percent.value.y),
|
||||
}
|
||||
: { x: 0, y: 0 };
|
||||
// Capture the stable area, never the transient child that received pointerdown.
|
||||
owner.setPointerCapture?.(event.pointerId);
|
||||
event.preventDefault();
|
||||
thumb.value?.focus({ preventScroll: true });
|
||||
if (!inThumb) update(point);
|
||||
}
|
||||
function pointermove(event: PointerEvent) {
|
||||
if (
|
||||
event.defaultPrevented ||
|
||||
event.pointerId !== pointer ||
|
||||
!dragging.value
|
||||
)
|
||||
return;
|
||||
const point = local(event);
|
||||
if (point) {
|
||||
event.preventDefault();
|
||||
update(point);
|
||||
}
|
||||
}
|
||||
function pointerup(event: PointerEvent) {
|
||||
if (event.pointerId !== pointer) return;
|
||||
if (!event.defaultPrevented) {
|
||||
const point = local(event);
|
||||
if (point) update(point);
|
||||
}
|
||||
stop(!event.defaultPrevented);
|
||||
}
|
||||
function cancel(event?: PointerEvent) {
|
||||
if (!event || event.pointerId === pointer) stop();
|
||||
}
|
||||
function keydown(event: KeyboardEvent) {
|
||||
if (
|
||||
event.defaultPrevented ||
|
||||
event.isComposing ||
|
||||
event.ctrlKey ||
|
||||
event.metaKey ||
|
||||
event.altKey ||
|
||||
state.disabled.value ||
|
||||
state.readOnly.value
|
||||
)
|
||||
return;
|
||||
if (event.key === "Escape") {
|
||||
if (state.active.value === token) {
|
||||
event.preventDefault();
|
||||
stop();
|
||||
}
|
||||
return;
|
||||
}
|
||||
if (
|
||||
![
|
||||
"ArrowLeft",
|
||||
"ArrowRight",
|
||||
"ArrowUp",
|
||||
"ArrowDown",
|
||||
"Home",
|
||||
"End",
|
||||
"PageUp",
|
||||
"PageDown",
|
||||
].includes(event.key)
|
||||
)
|
||||
return;
|
||||
if (pointer !== undefined) return;
|
||||
const { color, x: xc, y: yc } = axes.value;
|
||||
let xx = x.value,
|
||||
yy = y.value;
|
||||
const xStep = event.shiftKey ? xr.value.pageSize : xr.value.step;
|
||||
const yStep = event.shiftKey ? yr.value.pageSize : yr.value.step;
|
||||
const sign = dir.value === "rtl" ? -1 : 1;
|
||||
if (event.key === "ArrowLeft") xx -= xStep * sign;
|
||||
if (event.key === "ArrowRight") xx += xStep * sign;
|
||||
if (event.key === "ArrowUp") yy += yStep;
|
||||
if (event.key === "ArrowDown") yy -= yStep;
|
||||
if (event.key === "PageUp") yy += yr.value.pageSize;
|
||||
if (event.key === "PageDown") yy -= yr.value.pageSize;
|
||||
if (event.key === "Home") xx -= xr.value.pageSize * sign;
|
||||
if (event.key === "End") xx += xr.value.pageSize * sign;
|
||||
if (state.active.value !== token && !state.begin(token)) return;
|
||||
keys.add(event.key);
|
||||
event.preventDefault();
|
||||
focusedAxis.value = ["ArrowUp", "ArrowDown", "PageUp", "PageDown"].includes(
|
||||
event.key,
|
||||
)
|
||||
? "y"
|
||||
: "x";
|
||||
(focusedAxis.value === "y" ? focusY.value : thumb.value)?.focus({
|
||||
preventScroll: true,
|
||||
});
|
||||
state.request(
|
||||
color.withChannelValue(xc, xx).withChannelValue(yc, yy),
|
||||
token,
|
||||
);
|
||||
}
|
||||
function keyup(event: KeyboardEvent) {
|
||||
if (!keys.has(event.key)) return;
|
||||
keys.delete(event.key);
|
||||
if (event.defaultPrevented) stop();
|
||||
else if (!keys.size) stop(true);
|
||||
}
|
||||
function input(axis: "x" | "y", event: Event) {
|
||||
const target = event.target as HTMLInputElement;
|
||||
if (
|
||||
!event.defaultPrevented &&
|
||||
!state.disabled.value &&
|
||||
!state.readOnly.value &&
|
||||
state.begin(token)
|
||||
) {
|
||||
const value = Number(target.value);
|
||||
if (Number.isFinite(value))
|
||||
state.request(
|
||||
axes.value.color.withChannelValue(axes.value[axis], value),
|
||||
token,
|
||||
);
|
||||
}
|
||||
void nextTick(() => {
|
||||
target.value = String(axis === "x" ? x.value : y.value);
|
||||
});
|
||||
}
|
||||
watch(
|
||||
[
|
||||
state.disabled,
|
||||
state.readOnly,
|
||||
() =>
|
||||
[props.colorSpace, props.xChannel, props.yChannel, dir.value].join("|"),
|
||||
root,
|
||||
thumb,
|
||||
focusY,
|
||||
() => handle?.value,
|
||||
],
|
||||
() => stop(),
|
||||
{ flush: "sync" },
|
||||
);
|
||||
watch(
|
||||
state.active,
|
||||
(value) => {
|
||||
if (value !== token && (pointer !== undefined || keys.size)) stop();
|
||||
},
|
||||
{ flush: "sync" },
|
||||
);
|
||||
useChoiceForm(
|
||||
thumb,
|
||||
() => {
|
||||
stop();
|
||||
state.reset();
|
||||
},
|
||||
() => {
|
||||
if (thumb.value) thumb.value.value = String(x.value);
|
||||
if (focusY.value) focusY.value.value = String(y.value);
|
||||
},
|
||||
);
|
||||
onBeforeUnmount(() => stop());
|
||||
return {
|
||||
axes,
|
||||
dir,
|
||||
focusedAxis,
|
||||
locale,
|
||||
x,
|
||||
y,
|
||||
percent,
|
||||
dragging,
|
||||
pointerdown,
|
||||
pointermove,
|
||||
pointerup,
|
||||
cancel,
|
||||
keydown,
|
||||
keyup,
|
||||
input,
|
||||
commit: () => stop(true),
|
||||
blur: () => stop(true),
|
||||
};
|
||||
}
|
||||
@@ -0,0 +1,68 @@
|
||||
import {
|
||||
colorAxes,
|
||||
Color,
|
||||
type ColorAxisChannel,
|
||||
type ColorSpace,
|
||||
} from "./value";
|
||||
/** All six ordered channel pairs per space, including swapped axes and RTL.
|
||||
* Layers follow the same numerical channel mapping as the pointer controller. */
|
||||
export function colorAreaBackground(
|
||||
value: Color,
|
||||
space?: ColorSpace,
|
||||
x?: ColorAxisChannel,
|
||||
y?: ColorAxisChannel,
|
||||
dir: "ltr" | "rtl" = "ltr",
|
||||
) {
|
||||
const a = colorAxes(value, space, x, y),
|
||||
c = a.color.withAlpha(1),
|
||||
xd = dir === "rtl" ? "to left" : "to right";
|
||||
const direction = (channel: ColorAxisChannel) =>
|
||||
a.x === channel ? xd : "to top";
|
||||
if (a.space === "rgb") {
|
||||
const z = c
|
||||
.getChannels()
|
||||
.find((channel) => channel !== a.x && channel !== a.y)!;
|
||||
const black = new Color({ space: "rgb", r: 0, g: 0, b: 0, alpha: 1 });
|
||||
const background = black
|
||||
.withChannelValue(z, c.getChannelValue(z))
|
||||
.toString("css");
|
||||
const layer = (channel: ColorAxisChannel) =>
|
||||
`linear-gradient(${direction(channel)}, #000000, ${black.withChannelValue(channel, 255).toString("css")})`;
|
||||
return {
|
||||
backgroundColor: background,
|
||||
backgroundImage: `${layer(a.y)}, ${layer(a.x)}`,
|
||||
backgroundBlendMode: "screen",
|
||||
};
|
||||
}
|
||||
const channels = [a.x, a.y];
|
||||
const hueAxis = channels.includes("hue");
|
||||
const level = a.space === "hsb" ? "brightness" : "lightness";
|
||||
const levelAxis = channels.includes(level);
|
||||
const satAxis = channels.includes("saturation");
|
||||
let base = c;
|
||||
if (levelAxis)
|
||||
base = base.withChannelValue(level, a.space === "hsb" ? 100 : 50);
|
||||
if (satAxis) base = base.withChannelValue("saturation", 100);
|
||||
const layers: string[] = [];
|
||||
if (levelAxis)
|
||||
layers.push(
|
||||
a.space === "hsb"
|
||||
? `linear-gradient(${direction(level)}, #000000, transparent)`
|
||||
: `linear-gradient(${direction(level)}, #000000, transparent 50%, #ffffff)`,
|
||||
);
|
||||
if (satAxis) {
|
||||
const gray = base.withChannelValue("saturation", 0).toString("css");
|
||||
layers.push(
|
||||
`linear-gradient(${direction("saturation")}, ${gray}, transparent)`,
|
||||
);
|
||||
}
|
||||
if (hueAxis)
|
||||
layers.push(
|
||||
`linear-gradient(${direction("hue")}, ${[0, 60, 120, 180, 240, 300, 360].map((h) => base.withChannelValue("hue", h).toString("css")).join(", ")})`,
|
||||
);
|
||||
return {
|
||||
backgroundColor: base.toString("css"),
|
||||
backgroundImage: layers.join(", "),
|
||||
backgroundBlendMode: "normal",
|
||||
};
|
||||
}
|
||||
@@ -0,0 +1,202 @@
|
||||
import {
|
||||
computed,
|
||||
getCurrentInstance,
|
||||
inject,
|
||||
onBeforeUnmount,
|
||||
onBeforeUpdate,
|
||||
provide,
|
||||
shallowRef,
|
||||
watch,
|
||||
type ComputedRef,
|
||||
type InjectionKey,
|
||||
} from "vue";
|
||||
import { useChoiceValue } from "../choice/shared";
|
||||
import { useInheritedDisabled } from "../field/disabled";
|
||||
import { Color, copyColor, colorKey, type ColorValue } from "./value";
|
||||
export interface ColorModelProps {
|
||||
modelValue?: ColorValue | null;
|
||||
value?: ColorValue | null;
|
||||
defaultValue?: ColorValue | null;
|
||||
isDisabled?: boolean;
|
||||
disabled?: boolean;
|
||||
isReadOnly?: boolean;
|
||||
}
|
||||
export interface ColorState {
|
||||
value: ComputedRef<Color | null>;
|
||||
disabled: ComputedRef<boolean>;
|
||||
readOnly: ComputedRef<boolean>;
|
||||
active: ComputedRef<symbol | undefined>;
|
||||
begin: (source: symbol) => boolean;
|
||||
request: (value: Color | null, source?: symbol) => boolean;
|
||||
end: (source: symbol) => void;
|
||||
cancel: (source?: symbol) => void;
|
||||
reset: () => void;
|
||||
}
|
||||
const colorStateKey: InjectionKey<ColorState> = Symbol("hv-color-state");
|
||||
/** Read-only display parts may consume the nearest owner without creating one. */
|
||||
export function useColorStateContext() {
|
||||
return inject(colorStateKey, undefined);
|
||||
}
|
||||
/** A single accepted color owner. Children inherit only when they omit all own values. */
|
||||
export function useColorState(
|
||||
props: ColorModelProps,
|
||||
options: {
|
||||
fallback: () => Color | null;
|
||||
inherit?: boolean;
|
||||
provide?: boolean;
|
||||
change: (value: Color | null) => void;
|
||||
changeEnd?: (value: Color | null) => void;
|
||||
},
|
||||
): ColorState {
|
||||
const instance = getCurrentInstance()!;
|
||||
const own = () =>
|
||||
[
|
||||
"modelValue",
|
||||
"model-value",
|
||||
"value",
|
||||
"defaultValue",
|
||||
"default-value",
|
||||
].some((k) => Object.hasOwn(instance.vnode.props ?? {}, k));
|
||||
const ownValue = shallowRef(own());
|
||||
onBeforeUpdate(() => {
|
||||
ownValue.value = own();
|
||||
});
|
||||
const parent = useColorStateContext();
|
||||
const localDisabled = useInheritedDisabled(
|
||||
() => props.isDisabled || props.disabled,
|
||||
);
|
||||
const disabled = computed(
|
||||
() => localDisabled.value || !!(options.inherit && parent?.disabled.value),
|
||||
);
|
||||
const readOnly = computed(
|
||||
() => !!props.isReadOnly || !!(options.inherit && parent?.readOnly.value),
|
||||
);
|
||||
const has = (key: string) => Object.hasOwn(instance.vnode.props ?? {}, key);
|
||||
const model = useChoiceValue<Color | null>(
|
||||
() =>
|
||||
copyColor(
|
||||
has("modelValue") || has("model-value")
|
||||
? props.modelValue
|
||||
: props.value,
|
||||
),
|
||||
() =>
|
||||
copyColor(
|
||||
props.defaultValue === undefined
|
||||
? options.fallback()
|
||||
: props.defaultValue,
|
||||
),
|
||||
["modelValue", "model-value", "value"],
|
||||
(value) => options.change(copyColor(value)),
|
||||
);
|
||||
const source = shallowRef<symbol>();
|
||||
let proposal: Color | null | undefined;
|
||||
const inherited = computed(
|
||||
() => !!(options.inherit && parent && !ownValue.value),
|
||||
);
|
||||
const value = computed(() =>
|
||||
copyColor(inherited.value ? parent!.value.value : model.value.value),
|
||||
);
|
||||
const active = computed(() =>
|
||||
inherited.value ? parent!.active.value : source.value,
|
||||
);
|
||||
const delegated = new Map<symbol, ColorState>();
|
||||
function clearDelegated() {
|
||||
for (const [token, owner] of delegated) {
|
||||
delegated.delete(token);
|
||||
owner.cancel(token);
|
||||
}
|
||||
}
|
||||
const state: ColorState = {
|
||||
value,
|
||||
disabled,
|
||||
readOnly,
|
||||
active,
|
||||
begin(token) {
|
||||
if (disabled.value || readOnly.value) return false;
|
||||
if (inherited.value) {
|
||||
if (!parent!.begin(token)) return false;
|
||||
delegated.set(token, parent!);
|
||||
return true;
|
||||
}
|
||||
source.value = token;
|
||||
proposal = undefined;
|
||||
return true;
|
||||
},
|
||||
request(next, token) {
|
||||
if (disabled.value || readOnly.value || (token && active.value !== token))
|
||||
return false;
|
||||
const copied = copyColor(next);
|
||||
if (inherited.value) return parent!.request(copied, token);
|
||||
if (!token) state.cancel();
|
||||
if (colorKey(model.value.value) === colorKey(copied)) return false;
|
||||
if (token) proposal = copyColor(copied);
|
||||
model.request(copyColor(copied));
|
||||
return true;
|
||||
},
|
||||
end(token) {
|
||||
const owner = delegated.get(token);
|
||||
if (owner) {
|
||||
delegated.delete(token);
|
||||
owner.end(token);
|
||||
return;
|
||||
}
|
||||
if (inherited.value) return;
|
||||
if (source.value !== token) return;
|
||||
const last = copyColor(proposal);
|
||||
const changed = proposal !== undefined;
|
||||
source.value = undefined;
|
||||
proposal = undefined;
|
||||
if (changed && !disabled.value && !readOnly.value)
|
||||
options.changeEnd?.(last);
|
||||
},
|
||||
cancel(token) {
|
||||
if (token) {
|
||||
const owner = delegated.get(token);
|
||||
if (owner) {
|
||||
delegated.delete(token);
|
||||
owner.cancel(token);
|
||||
return;
|
||||
}
|
||||
} else clearDelegated();
|
||||
if (inherited.value) return;
|
||||
if (token && source.value !== token) return;
|
||||
source.value = undefined;
|
||||
proposal = undefined;
|
||||
},
|
||||
reset() {
|
||||
if (inherited.value) return;
|
||||
state.cancel();
|
||||
model.reset();
|
||||
},
|
||||
};
|
||||
// Parent acceptance is allowed during an interaction; unrelated replacements abort it.
|
||||
watch(
|
||||
() => colorKey(model.value.value),
|
||||
(key) => {
|
||||
if (source.value && key !== colorKey(proposal)) state.cancel();
|
||||
},
|
||||
{ flush: "sync" },
|
||||
);
|
||||
watch(
|
||||
[disabled, readOnly],
|
||||
([off, ro]) => {
|
||||
if (off || ro) state.cancel();
|
||||
},
|
||||
{ flush: "sync" },
|
||||
);
|
||||
watch(
|
||||
inherited,
|
||||
() => {
|
||||
clearDelegated();
|
||||
source.value = undefined;
|
||||
proposal = undefined;
|
||||
},
|
||||
{ flush: "sync" },
|
||||
);
|
||||
onBeforeUnmount(() => {
|
||||
clearDelegated();
|
||||
if (!inherited.value) state.cancel();
|
||||
});
|
||||
if (options.provide) provide(colorStateKey, state);
|
||||
return state;
|
||||
}
|
||||
@@ -0,0 +1,324 @@
|
||||
import {
|
||||
convertToRgb,
|
||||
convertToHsl,
|
||||
convertToHsb,
|
||||
parseColor as parseWireColor,
|
||||
type Color as WireColor,
|
||||
type ColorSpace,
|
||||
type ColorChannel,
|
||||
} from "reka-ui";
|
||||
export type { ColorSpace, ColorChannel } from "reka-ui";
|
||||
export type ColorFormat =
|
||||
ColorSpace | "css" | "hex" | "hexa" | "rgba" | "hsla" | "hsba";
|
||||
export type ColorAxisChannel = Exclude<ColorChannel, "alpha">;
|
||||
const channels: Record<ColorSpace, readonly ColorAxisChannel[]> = {
|
||||
rgb: ["red", "green", "blue"],
|
||||
hsl: ["hue", "saturation", "lightness"],
|
||||
hsb: ["hue", "saturation", "brightness"],
|
||||
};
|
||||
const keys = {
|
||||
red: "r",
|
||||
green: "g",
|
||||
blue: "b",
|
||||
hue: "h",
|
||||
saturation: "s",
|
||||
lightness: "l",
|
||||
brightness: "b",
|
||||
alpha: "alpha",
|
||||
} as const;
|
||||
function finite(value: number) {
|
||||
if (!Number.isFinite(value))
|
||||
throw new RangeError("Color channels must be finite.");
|
||||
return value;
|
||||
}
|
||||
const clamp = (value: number, max: number) =>
|
||||
Math.min(max, Math.max(0, finite(value)));
|
||||
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) {
|
||||
const alpha = clamp(value.alpha, 1);
|
||||
if (value.space === "rgb")
|
||||
this.#value = {
|
||||
space: "rgb",
|
||||
r: clamp(value.r, 255),
|
||||
g: clamp(value.g, 255),
|
||||
b: clamp(value.b, 255),
|
||||
alpha,
|
||||
};
|
||||
else if (value.space === "hsl")
|
||||
this.#value = {
|
||||
space: "hsl",
|
||||
h: clamp(value.h, 360),
|
||||
s: clamp(value.s, 100),
|
||||
l: clamp(value.l, 100),
|
||||
alpha,
|
||||
};
|
||||
else if (value.space === "hsb")
|
||||
this.#value = {
|
||||
space: "hsb",
|
||||
h: clamp(value.h, 360),
|
||||
s: clamp(value.s, 100),
|
||||
b: clamp(value.b, 100),
|
||||
alpha,
|
||||
};
|
||||
else throw new RangeError("Unknown color space.");
|
||||
Object.freeze(this);
|
||||
}
|
||||
clone() {
|
||||
return new Color(this.#value);
|
||||
}
|
||||
getColorSpace() {
|
||||
return this.#value.space;
|
||||
}
|
||||
getChannels() {
|
||||
return [...channels[this.#value.space]];
|
||||
}
|
||||
getColorChannels() {
|
||||
return this.getChannels();
|
||||
}
|
||||
getChannelFormatOptions(channel: ColorChannel): Intl.NumberFormatOptions {
|
||||
this.getChannelRange(channel);
|
||||
return channel === "hue"
|
||||
? { style: "unit", unit: "degree", unitDisplay: "narrow" }
|
||||
: channel === "alpha" ||
|
||||
["saturation", "lightness", "brightness"].includes(channel)
|
||||
? { style: "percent" }
|
||||
: { style: "decimal" };
|
||||
}
|
||||
formatChannelValue(channel: ColorChannel, locale: string) {
|
||||
const raw = this.getChannelValue(channel);
|
||||
return new Intl.NumberFormat(
|
||||
locale,
|
||||
this.getChannelFormatOptions(channel),
|
||||
).format(
|
||||
["saturation", "lightness", "brightness"].includes(channel)
|
||||
? raw / 100
|
||||
: raw,
|
||||
);
|
||||
}
|
||||
/** Internal conversion bridge, omitted from the public Color instance type. */
|
||||
static toWire(value: Color): WireColor {
|
||||
return { ...value.#value };
|
||||
}
|
||||
toFormat(space: ColorSpace): Color {
|
||||
const v = this.#value;
|
||||
if (space === v.space) return this.clone();
|
||||
// Direct polar conversion retains the hue even at black/white/gray.
|
||||
if (v.space === "hsb" && space === "hsl") {
|
||||
const b = v.b / 100,
|
||||
s = v.s / 100,
|
||||
l = b * (1 - s / 2);
|
||||
return new Color({
|
||||
space: "hsl",
|
||||
h: v.h,
|
||||
s: l === 0 || l === 1 ? 0 : ((b - l) / Math.min(l, 1 - l)) * 100,
|
||||
l: l * 100,
|
||||
alpha: v.alpha,
|
||||
});
|
||||
}
|
||||
if (v.space === "hsl" && space === "hsb") {
|
||||
const l = v.l / 100,
|
||||
b = l + (v.s / 100) * Math.min(l, 1 - l);
|
||||
return new Color({
|
||||
space: "hsb",
|
||||
h: v.h,
|
||||
s: b === 0 ? 0 : 2 * (1 - l / b) * 100,
|
||||
b: b * 100,
|
||||
alpha: v.alpha,
|
||||
});
|
||||
}
|
||||
return new Color(
|
||||
space === "rgb"
|
||||
? convertToRgb(v)
|
||||
: space === "hsl"
|
||||
? convertToHsl(v)
|
||||
: space === "hsb"
|
||||
? convertToHsb(v)
|
||||
: (() => {
|
||||
throw new RangeError("Unknown color space.");
|
||||
})(),
|
||||
);
|
||||
}
|
||||
getChannelRange(channel: ColorChannel) {
|
||||
if (channel === "alpha")
|
||||
return { minValue: 0, maxValue: 1, step: 0.01, pageSize: 0.1 };
|
||||
if (!this.getChannels().includes(channel))
|
||||
throw new RangeError(
|
||||
`Channel ${channel} is not in ${this.getColorSpace()}.`,
|
||||
);
|
||||
return {
|
||||
minValue: 0,
|
||||
maxValue:
|
||||
channel === "hue" ? 360 : this.#value.space === "rgb" ? 255 : 100,
|
||||
step: 1,
|
||||
pageSize: channel === "hue" ? 15 : this.#value.space === "rgb" ? 17 : 10,
|
||||
};
|
||||
}
|
||||
getChannelValue(channel: ColorChannel): number {
|
||||
this.getChannelRange(channel);
|
||||
return (this.#value as unknown as Record<string, number>)[keys[channel]]!;
|
||||
}
|
||||
withChannelValue(channel: ColorChannel, value: number): Color {
|
||||
const range = this.getChannelRange(channel);
|
||||
return new Color({
|
||||
...this.#value,
|
||||
[keys[channel]]: clamp(value, range.maxValue),
|
||||
});
|
||||
}
|
||||
withAlpha(value: number) {
|
||||
return this.withChannelValue("alpha", value);
|
||||
}
|
||||
equals(other: Color) {
|
||||
return colorKey(this) === colorKey(other);
|
||||
}
|
||||
toString(format: ColorFormat = "css"): string {
|
||||
if (
|
||||
![
|
||||
"rgb",
|
||||
"hsl",
|
||||
"hsb",
|
||||
"css",
|
||||
"hex",
|
||||
"hexa",
|
||||
"rgba",
|
||||
"hsla",
|
||||
"hsba",
|
||||
].includes(format)
|
||||
)
|
||||
throw new RangeError("Unknown color format.");
|
||||
const alpha = this.#value.alpha;
|
||||
if (format === "hex" || format === "hexa") {
|
||||
const v = this.toFormat("rgb").#value as Extract<
|
||||
WireColor,
|
||||
{ space: "rgb" }
|
||||
>;
|
||||
const hex = (n: number) =>
|
||||
Math.round(n).toString(16).padStart(2, "0").toUpperCase();
|
||||
return `#${hex(v.r)}${hex(v.g)}${hex(v.b)}${format === "hexa" ? hex(alpha * 255) : ""}`;
|
||||
}
|
||||
const space: ColorSpace = format.startsWith("hsl")
|
||||
? "hsl"
|
||||
: format.startsWith("hsb")
|
||||
? "hsb"
|
||||
: "rgb";
|
||||
const value = this.toFormat(space);
|
||||
const values = value
|
||||
.getChannels()
|
||||
.map((c) => round(value.getChannelValue(c)));
|
||||
const withAlpha =
|
||||
(format === "css" && alpha !== 1) ||
|
||||
["rgba", "hsla", "hsba"].includes(format);
|
||||
const suffix = withAlpha ? `, ${alpha}` : "";
|
||||
if (space === "rgb")
|
||||
return `rgb${withAlpha ? "a" : ""}(${values.map(Math.round).join(", ")}${suffix})`;
|
||||
return `${space}${withAlpha ? "a" : ""}(${values[0]}, ${values[1]}%, ${values[2]}%${suffix})`;
|
||||
}
|
||||
}
|
||||
export function colorKey(color: Color | null | undefined) {
|
||||
return color ? JSON.stringify(Color.toWire(color)) : "empty";
|
||||
}
|
||||
export type ColorValue = string | Color;
|
||||
export function parseColor(value: string): Color {
|
||||
let text = value.trim();
|
||||
if (/^#[\da-f]{4}$/i.test(text))
|
||||
text = "#" + [...text.slice(1)].map((c) => c + c).join("");
|
||||
if (text.startsWith("#")) return new Color(parseWireColor(text));
|
||||
const match = /^(rgba?|hsla?|hsba?|hsva?)\((.*)\)$/i.exec(text);
|
||||
if (!match) throw new RangeError(`Unsupported color: ${value}`);
|
||||
if (
|
||||
/,,|\/\s*\/|,\s*\)|^\s*[,\/]/.test(match[2]!) ||
|
||||
(match[2]!.match(/\//g)?.length ?? 0) > 1
|
||||
)
|
||||
throw new RangeError(`Invalid color: ${value}`);
|
||||
const name = match[1]!.toLowerCase();
|
||||
// Comma forms and CSS space/slash forms are normalized before the public Reka parser.
|
||||
const parts = match[2]!.trim().split(/[\s,\/]+/);
|
||||
if (
|
||||
parts.length < 3 ||
|
||||
parts.length > 4 ||
|
||||
parts.some((p) => !/^[-+]?(?:\d+\.?\d*|\.\d+)%?$/.test(p))
|
||||
)
|
||||
throw new RangeError(`Invalid color: ${value}`);
|
||||
const rgb = name.startsWith("rgb");
|
||||
const nums = parts.map((p, i) => {
|
||||
const n = finite(Number.parseFloat(p));
|
||||
return p.endsWith("%")
|
||||
? i === 3
|
||||
? n / 100
|
||||
: rgb
|
||||
? (n * 255) / 100
|
||||
: n
|
||||
: n;
|
||||
});
|
||||
if (!rgb && nums[0] !== 360) nums[0] = ((nums[0]! % 360) + 360) % 360;
|
||||
const alpha = nums[3] ?? 1;
|
||||
if (rgb)
|
||||
return new Color({
|
||||
space: "rgb",
|
||||
r: nums[0]!,
|
||||
g: nums[1]!,
|
||||
b: nums[2]!,
|
||||
alpha,
|
||||
});
|
||||
return new Color(
|
||||
name.startsWith("hsl")
|
||||
? { space: "hsl", h: nums[0]!, s: nums[1]!, l: nums[2]!, alpha }
|
||||
: { space: "hsb", h: nums[0]!, s: nums[1]!, b: nums[2]!, alpha },
|
||||
);
|
||||
}
|
||||
export function copyColor(value: ColorValue | null | undefined): Color | null {
|
||||
if (value == null) return null;
|
||||
if (typeof value === "string") return parseColor(value);
|
||||
if (!(value instanceof Color))
|
||||
throw new TypeError("Expected a color string or library Color.");
|
||||
return value.clone();
|
||||
}
|
||||
export function colorAxes(
|
||||
color: Color,
|
||||
space?: ColorSpace,
|
||||
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());
|
||||
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)!;
|
||||
if (
|
||||
xChannel === yChannel ||
|
||||
!native.includes(xChannel) ||
|
||||
!native.includes(yChannel)
|
||||
)
|
||||
throw new RangeError(
|
||||
"ColorArea requires two different channels in the chosen color space.",
|
||||
);
|
||||
return {
|
||||
space: working,
|
||||
x: xChannel,
|
||||
y: yChannel,
|
||||
color: color.toFormat(working),
|
||||
};
|
||||
}
|
||||
+164
@@ -0,0 +1,164 @@
|
||||
<script setup lang="ts">
|
||||
import { computed, shallowRef, ref, useAttrs, useId } from "vue";
|
||||
import {
|
||||
useColorState,
|
||||
type ColorModelProps,
|
||||
} from "../../src/components/color/model";
|
||||
import {
|
||||
useColorArea,
|
||||
type ColorAreaOptions,
|
||||
} from "../../src/components/color/area";
|
||||
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 emit = defineEmits<{
|
||||
"update:modelValue": [Color | null];
|
||||
change: [Color | null];
|
||||
changeEnd: [Color | null];
|
||||
}>();
|
||||
const attrs = useAttrs();
|
||||
const state = useColorState(props, {
|
||||
fallback: () => parseColor("hsb(240, 50%, 50%)"),
|
||||
inherit: true,
|
||||
change: (value) => {
|
||||
emit("update:modelValue", value);
|
||||
emit("change", value);
|
||||
},
|
||||
changeEnd: (value) => emit("changeEnd", value),
|
||||
});
|
||||
const root = shallowRef<HTMLElement>(),
|
||||
thumb = shallowRef<HTMLInputElement>(),
|
||||
handle = shallowRef<HTMLElement>(),
|
||||
focusY = shallowRef<HTMLInputElement>();
|
||||
const control = useColorArea(state, props, {
|
||||
root,
|
||||
focusX: thumb,
|
||||
focusY,
|
||||
thumb: handle,
|
||||
});
|
||||
const { axes, x, y, percent, dragging, dir, focusedAxis, locale } = control;
|
||||
const background = computed(() =>
|
||||
colorAreaBackground(
|
||||
axes.value.color,
|
||||
axes.value.space,
|
||||
axes.value.x,
|
||||
axes.value.y,
|
||||
dir.value,
|
||||
),
|
||||
);
|
||||
const disabled = state.disabled,
|
||||
readonly = state.readOnly;
|
||||
const id = useId();
|
||||
const hidden = {
|
||||
position: "absolute" as const,
|
||||
width: "1px",
|
||||
height: "1px",
|
||||
overflow: "hidden",
|
||||
clipPath: "inset(50%)",
|
||||
};
|
||||
const focusVisible = ref(false);
|
||||
function onFocusin(event: FocusEvent) {
|
||||
focusVisible.value = (event.target as HTMLElement).matches(":focus-visible");
|
||||
}
|
||||
function onFocusout(event: FocusEvent) {
|
||||
if (!root.value?.contains(event.relatedTarget as Node | null)) {
|
||||
focusVisible.value = false;
|
||||
control.blur();
|
||||
}
|
||||
}
|
||||
function axis(event: Event) {
|
||||
const value = (event.target as HTMLElement).getAttribute("data-axis");
|
||||
return value === "x" || value === "y" ? value : undefined;
|
||||
}
|
||||
function onKeydown(event: KeyboardEvent) {
|
||||
const channel = axis(event);
|
||||
if (channel) control.keydown(event);
|
||||
}
|
||||
function onInput(event: Event) {
|
||||
const channel = axis(event);
|
||||
if (channel) control.input(channel, event);
|
||||
}
|
||||
defineExpose({ state, control });
|
||||
</script>
|
||||
<template>
|
||||
<div
|
||||
ref="root"
|
||||
v-bind="attrs"
|
||||
class="hv-color-area"
|
||||
data-color-area
|
||||
role="group"
|
||||
:dir="dir"
|
||||
:aria-label="(attrs['aria-label'] as string) ?? 'Color area'"
|
||||
:data-disabled="disabled || undefined"
|
||||
:style="{
|
||||
...background,
|
||||
touchAction: disabled || readonly ? 'auto' : 'none',
|
||||
}"
|
||||
@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"
|
||||
>
|
||||
<div
|
||||
ref="handle"
|
||||
class="hv-color-area__thumb"
|
||||
data-color-thumb
|
||||
:data-dragging="dragging || undefined"
|
||||
:data-focus-visible="focusVisible || undefined"
|
||||
:data-disabled="disabled || undefined"
|
||||
:style="{
|
||||
position: 'absolute',
|
||||
left: `${(dir === 'rtl' ? 1 - percent.x : percent.x) * 100}%`,
|
||||
top: `${(1 - percent.y) * 100}%`,
|
||||
transform: 'translate(-50%,-50%)',
|
||||
'--color-area-thumb-color': axes.color.toString('css'),
|
||||
}"
|
||||
>
|
||||
<input
|
||||
:id="`color-${id}-x`"
|
||||
ref="thumb"
|
||||
type="range"
|
||||
step="any"
|
||||
data-axis="x"
|
||||
:tabindex="focusedAxis === 'x' ? 0 : -1"
|
||||
:name="xName"
|
||||
:form="form"
|
||||
:aria-label="axes.x"
|
||||
:aria-valuetext="axes.color.formatChannelValue(axes.x, locale)"
|
||||
:min="0"
|
||||
:max="axes.color.getChannelRange(axes.x).maxValue"
|
||||
:value="x"
|
||||
:disabled="disabled"
|
||||
:aria-readonly="readonly || undefined"
|
||||
:style="hidden"
|
||||
/>
|
||||
<input
|
||||
:id="`color-${id}-y`"
|
||||
type="range"
|
||||
step="any"
|
||||
data-axis="y"
|
||||
ref="focusY"
|
||||
:tabindex="focusedAxis === 'y' ? 0 : -1"
|
||||
:name="yName"
|
||||
:form="form"
|
||||
:aria-label="axes.y"
|
||||
:aria-valuetext="axes.color.formatChannelValue(axes.y, locale)"
|
||||
aria-orientation="vertical"
|
||||
:min="0"
|
||||
:max="axes.color.getChannelRange(axes.y).maxValue"
|
||||
:value="y"
|
||||
:disabled="disabled"
|
||||
:aria-readonly="readonly || undefined"
|
||||
:style="hidden"
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
</template>
|
||||
@@ -0,0 +1,125 @@
|
||||
<script setup lang="ts">
|
||||
import { computed, ref, watch } from "vue";
|
||||
import {
|
||||
useColorState,
|
||||
type ColorModelProps,
|
||||
} from "../../src/components/color/model";
|
||||
import { Color, parseColor, colorKey } from "../../src/components/color/value";
|
||||
import { useChoiceForm } from "../../src/components/choice/shared";
|
||||
import Area from "./ColorAreaFoundation.vue";
|
||||
const props = defineProps<ColorModelProps & { name?: string; form?: string }>();
|
||||
const emit = defineEmits<{
|
||||
"update:modelValue": [Color | null];
|
||||
change: [Color | null];
|
||||
changeEnd: [Color | null];
|
||||
}>();
|
||||
const state = useColorState(props, {
|
||||
fallback: () => parseColor("hsb(240,50%,50%)"),
|
||||
provide: true,
|
||||
change: (value) => {
|
||||
emit("update:modelValue", value);
|
||||
emit("change", value);
|
||||
},
|
||||
changeEnd: (value) => emit("changeEnd", value),
|
||||
});
|
||||
const value = state.value,
|
||||
disabled = state.disabled,
|
||||
readOnly = state.readOnly;
|
||||
const text = ref(value.value?.toString("hexa") ?? ""),
|
||||
native = ref<HTMLInputElement>();
|
||||
const serialized = computed(() => value.value?.toString("hexa") ?? "");
|
||||
useChoiceForm(native, state.reset, () => {});
|
||||
watch(
|
||||
() => colorKey(value.value),
|
||||
() => {
|
||||
text.value = value.value?.toString("hexa") ?? "";
|
||||
},
|
||||
);
|
||||
const edit = Symbol("color-text");
|
||||
function commit(event: Event) {
|
||||
const input = event.currentTarget as HTMLInputElement;
|
||||
try {
|
||||
if (state.begin(edit)) {
|
||||
state.request(input.value.trim() ? parseColor(input.value) : null, edit);
|
||||
state.end(edit);
|
||||
}
|
||||
} catch {
|
||||
state.cancel(edit);
|
||||
}
|
||||
text.value = value.value?.toString("hexa") ?? "";
|
||||
input.value = text.value;
|
||||
}
|
||||
const hue = Symbol("color-hue");
|
||||
function setHue(event: Event) {
|
||||
const input = event.currentTarget as HTMLInputElement;
|
||||
if (state.begin(hue))
|
||||
state.request(
|
||||
(value.value ?? parseColor("#ff0000"))
|
||||
.toFormat("hsb")
|
||||
.withChannelValue("hue", Number(input.value)),
|
||||
hue,
|
||||
);
|
||||
input.value = String(
|
||||
value.value?.toFormat("hsb").getChannelValue("hue") ?? 0,
|
||||
);
|
||||
}
|
||||
defineExpose({ state });
|
||||
</script>
|
||||
<template>
|
||||
<div data-color-picker-foundation>
|
||||
<slot :value="value">
|
||||
<Area
|
||||
aria-label="Shared HSB area"
|
||||
color-space="hsb"
|
||||
x-channel="saturation"
|
||||
y-channel="brightness"
|
||||
/>
|
||||
<input
|
||||
data-color-hue
|
||||
type="range"
|
||||
step="any"
|
||||
min="0"
|
||||
max="360"
|
||||
:value="value?.toFormat('hsb').getChannelValue('hue') ?? 0"
|
||||
aria-label="Hue"
|
||||
:disabled="disabled"
|
||||
:aria-readonly="readOnly || undefined"
|
||||
@input="setHue"
|
||||
@change="state.end(hue)"
|
||||
@pointercancel="state.cancel(hue)"
|
||||
@blur="state.end(hue)"
|
||||
/>
|
||||
<input
|
||||
data-color-text
|
||||
aria-label="Hex color"
|
||||
:value="text"
|
||||
:disabled="disabled"
|
||||
:readonly="readOnly"
|
||||
@change="commit"
|
||||
/>
|
||||
<output data-color-output>
|
||||
{{
|
||||
value?.toString(
|
||||
value.getChannelValue("alpha") === 1 ? "hsb" : "hsba",
|
||||
) ?? "empty"
|
||||
}}
|
||||
</output>
|
||||
<div
|
||||
data-color-swatch
|
||||
:style="{
|
||||
width: '32px',
|
||||
height: '32px',
|
||||
background: value?.toString('css'),
|
||||
}"
|
||||
/>
|
||||
</slot>
|
||||
<input
|
||||
ref="native"
|
||||
type="hidden"
|
||||
:name="name"
|
||||
:form="form"
|
||||
:disabled="disabled"
|
||||
:value="serialized"
|
||||
/>
|
||||
</div>
|
||||
</template>
|
||||
+10
@@ -0,0 +1,10 @@
|
||||
// Installed-version probes use only public exports, resolved from the component package.
|
||||
export {
|
||||
ColorAreaRoot,
|
||||
ColorAreaArea,
|
||||
ColorAreaThumb,
|
||||
parseColor,
|
||||
getChannelRange,
|
||||
getChannelValue,
|
||||
getAreaBackgroundStyle,
|
||||
} from "reka-ui";
|
||||
Reference in New Issue
Block a user