feat: establish composed color field and input group protocols

This commit is contained in:
maoyingjie
2026-10-25 15:20:02 +08:00
parent a41517aa76
commit db18d0d3da
31 changed files with 1859 additions and 39 deletions
+4 -1
View File
@@ -85,7 +85,7 @@ export function useChoiceField<T>(
props: ChoiceFieldProps,
attrs: Record<string, unknown>,
options: {
kind: "group" | "toggle";
kind: "text" | "group" | "toggle";
value: ComputedRef<T>;
validate?: (value: T) => ValidateResult;
satisfied: () => boolean;
@@ -271,6 +271,9 @@ export function useChoiceField<T>(
reset,
invalidEvent,
validity,
commitValidation: () => {
touched.value = true;
},
prepare,
};
}
@@ -0,0 +1,117 @@
<script setup lang="ts">
import {
computed,
defineComponent,
shallowRef,
useAttrs,
type VNodeChild,
type VNode,
} from "vue";
import { useColorField } from "./useColorField";
import type { ColorFieldProps, ColorFieldRenderState } from "./context";
import type { Color } from "../color/value";
defineOptions({ inheritAttrs: false });
defineSlots<{ default?: (state: ColorFieldRenderState) => VNode[] }>();
const props = withDefaults(defineProps<ColorFieldProps>(), { as: "div" });
const emit = defineEmits<{
"update:modelValue": [Color | null];
change: [Color | null];
}>();
const attrs = useAttrs();
const control = useColorField(props, attrs, (value) => {
emit("update:modelValue", value);
emit("change", value);
});
const root = shallowRef<HTMLElement>();
const focused = shallowRef(false),
focusWithin = shallowRef(false),
focusVisible = shallowRef(false);
const disabled = control.state.disabled,
readonly = control.state.readOnly,
invalid = control.field.field.invalid,
required = control.field.field.required;
const state = computed(() => ({
value: control.state.value.value,
isDisabled: disabled.value,
isReadOnly: readonly.value,
isInvalid: invalid.value,
isRequired: required.value,
isFocused: focused.value,
isFocusWithin: focusWithin.value,
isFocusVisible: focusVisible.value,
validationErrors: control.field.field.errors.value,
}));
const rendered = defineComponent({
props: ["nodes"],
setup: (p) => () => p.nodes as VNodeChild,
});
const nativeEvents = new Set([
"aria-label",
"aria-labelledby",
"aria-describedby",
"aria-invalid",
"aria-required",
"aria-readonly",
"aria-disabled",
"onBeforeinput",
"onKeydown",
"onKeyup",
"onInput",
"onBlur",
"onFocus",
"onWheel",
"onCompositionstart",
"onCompositionend",
"onPaste",
]);
const rootAttrs = () =>
Object.fromEntries(
Object.entries(attrs).filter(([key]) => !nativeEvents.has(key)),
);
function focusin(event: FocusEvent) {
focusWithin.value = true;
focused.value = event.target === control.input.value;
focusVisible.value = (event.target as HTMLElement).matches(":focus-visible");
}
function focusout(event: FocusEvent) {
if (!root.value?.contains(event.relatedTarget as Node | null)) {
focusWithin.value = false;
focused.value = false;
focusVisible.value = false;
}
}
defineExpose({
focus: () => control.input.value?.focus(),
element: control.input,
});
</script>
<template>
<component
:is="as"
ref="root"
v-bind="rootAttrs()"
class="hv-color-field"
:class="{ 'hv-color-field--full-width': fullWidth }"
data-slot="color-field"
:data-channel="channel ?? 'hex'"
:data-disabled="disabled || undefined"
:data-readonly="readonly || undefined"
:data-required="required || undefined"
:data-invalid="invalid || undefined"
@focusin="focusin"
@focusout="focusout"
>
<component
:is="rendered"
:nodes="control.prepare($slots.default?.(state) ?? [], state)"
/>
<input
v-if="channel && control.name.value"
type="hidden"
:name="control.name.value"
:form="control.form.value"
:disabled="disabled"
:value="control.text.submission.value"
/>
</component>
</template>
@@ -0,0 +1,78 @@
<script setup lang="ts">
import { computed, inject, shallowRef, useAttrs } from "vue";
import { useColorFieldContext } from "./context";
import { useInheritedDisabled } from "../field/disabled";
import { textFieldContextKey } from "../textfield/context";
defineOptions({ inheritAttrs: false });
const props = withDefaults(
defineProps<{
variant?: "primary" | "secondary";
fullWidth?: boolean;
as?: string;
role?: string;
}>(),
{ variant: "primary", as: "div" },
);
const attrs = useAttrs(),
field = useColorFieldContext(),
text = inject(textFieldContextKey, undefined);
const root = shallowRef<HTMLElement>(),
hovered = shallowRef(false),
focused = shallowRef(false);
const disabled = useInheritedDisabled(
() => field?.state.disabled.value || text?.disabled.value,
);
const invalid = computed(
() =>
field?.field.field.invalid.value ||
text?.invalid.value ||
attrs["aria-invalid"] === true ||
attrs["aria-invalid"] === "true",
);
function click(event: MouseEvent) {
if (event.defaultPrevented || disabled.value) return;
const target = event.target as HTMLElement;
if (target.closest("button,a,input,textarea,select,[role=button],[tabindex]"))
return;
root.value
?.querySelector<HTMLInputElement>(
'input[data-slot="color-input-group-input"]',
)
?.focus();
}
function blur(event: FocusEvent) {
if (!root.value?.contains(event.relatedTarget as Node | null))
focused.value = false;
}
</script>
<template>
<component
:is="as"
ref="root"
v-bind="attrs"
class="hv-color-input-group"
:class="[
`hv-color-input-group--${variant}`,
{ 'hv-color-input-group--full-width': fullWidth },
]"
:role="role ?? (field ? 'presentation' : 'group')"
data-slot="color-input-group"
:data-disabled="disabled || undefined"
:aria-disabled="disabled || undefined"
:data-invalid="invalid || undefined"
:data-hovered="hovered || undefined"
:data-focus-within="focused || undefined"
@click="click"
@pointerenter="hovered = true"
@pointerleave="hovered = false"
@focusin="focused = true"
@focusout="blur"
>
<slot
:is-disabled="disabled"
:is-invalid="invalid"
:is-focus-within="focused"
:is-hovered="hovered"
/>
</component>
</template>
@@ -0,0 +1,127 @@
<script setup lang="ts">
import {
mergeProps,
computed,
onBeforeUnmount,
onBeforeUpdate,
onMounted,
shallowRef,
useAttrs,
watch,
} from "vue";
import { useColorFieldContext } from "./context";
import { useTextControl } from "../field/useTextControl";
import { mergeIds } from "../field/context";
defineOptions({ inheritAttrs: false });
const props = defineProps<{
modelValue?: string;
defaultValue?: string;
invalid?: boolean;
}>();
const emit = defineEmits<{ "update:modelValue": [string] }>();
const attrs = useAttrs();
const field = useColorFieldContext();
const standalone = field ? undefined : useTextControl(props, attrs, emit);
const element = shallowRef<HTMLInputElement>();
const token = Symbol("color-field-input");
if (field) {
field.register(token, attrs);
onBeforeUpdate(() => field.register(token, attrs));
watch(element, (node) => field.connect(token, node), { flush: "sync" });
onBeforeUnmount(() => field.unregister(token));
} else
watch(
element,
(node) => {
standalone!.element.value = node;
},
{ flush: "sync" },
);
const value = computed(() =>
field ? field.text.draft.value : standalone!.value.value,
);
const disabled = computed(() =>
field ? field.state.disabled.value : standalone!.disabled(),
);
const readonly = computed(() =>
field ? field.state.readOnly.value : standalone!.readOnly(),
);
function inputAttrs() {
if (!field)
return {
...standalone!.inheritedAttrs(),
...attrs,
id: standalone!.id(),
name: standalone!.name(),
disabled: disabled.value,
readonly: readonly.value,
required: standalone!.required(),
"aria-invalid": standalone!.invalid() || undefined,
"aria-describedby": standalone!.describedBy(),
};
return {
...mergeProps(field.nativeAttrs(attrs), attrs),
id: field.id.value,
name: field.channel.value ? undefined : field.name.value,
form: field.form.value,
disabled: disabled.value,
readonly: readonly.value,
required:
field.field.behavior.value === "native" &&
!readonly.value &&
field.field.field.required.value,
"aria-invalid":
field.field.field.invalid.value || props.invalid || undefined,
"aria-required":
(field.field.behavior.value === "aria" &&
field.field.field.required.value) ||
undefined,
"aria-describedby": mergeIds(
attrs["aria-describedby"] as string | undefined,
field.field.describedBy(),
),
"aria-labelledby": mergeIds(
attrs["aria-labelledby"] as string | undefined,
field.field.labelledBy(),
),
inputmode: field.channel.value ? ("decimal" as const) : undefined,
autocomplete: field.autoComplete.value,
autocorrect: "off",
spellcheck: false,
};
}
function input(event: Event) {
if (field) field.text.input(event);
else standalone!.update(event);
}
onMounted(() => {
if (field?.autoFocus.value && !disabled.value) element.value?.focus();
});
defineExpose({
element,
focus: () => element.value?.focus(),
select: () => element.value?.select(),
});
</script>
<template>
<input
ref="element"
v-bind="inputAttrs()"
:type="field ? 'text' : String(attrs.type ?? 'text')"
:value="value"
class="hv-color-input-group__input"
data-slot="color-input-group-input"
@input="input"
@beforeinput="field?.text.beforeinput($event)"
@keydown="field?.text.keydown($event)"
@blur="field?.text.blur($event)"
@wheel="field?.wheel($event)"
@compositionstart="field?.text.compositionstart()"
@compositionend="field?.text.compositionend()"
@invalid="
field
? field.field.invalidEvent($event, () => element?.focus())
: standalone?.onInvalid($event)
"
/>
</template>
@@ -0,0 +1,12 @@
<script setup lang="ts">
withDefaults(defineProps<{ as?: string }>(), { as: "div" });
</script>
<template>
<component
:is="as"
class="hv-color-input-group__prefix"
data-slot="color-input-group-prefix"
>
<slot />
</component>
</template>
@@ -0,0 +1,12 @@
<script setup lang="ts">
withDefaults(defineProps<{ as?: string }>(), { as: "div" });
</script>
<template>
<component
:is="as"
class="hv-color-input-group__suffix"
data-slot="color-input-group-suffix"
>
<slot />
</component>
</template>
@@ -0,0 +1,53 @@
import {
inject,
type ComputedRef,
type InjectionKey,
type ShallowRef,
} from "vue";
import type { useChoiceField, ChoiceFieldProps } from "../choice/shared";
import type { ColorModelProps, ColorState } from "../color/model";
import type { ColorTextOptions, useColorText } from "../color/text";
import type { Color } from "../color/value";
import type { ValidateResult } from "../field/context";
export interface ColorFieldProps
extends ColorModelProps, ColorTextOptions, ChoiceFieldProps {
as?: string;
fullWidth?: boolean;
autoFocus?: boolean;
autoComplete?: string;
isWheelDisabled?: boolean;
validate?: (value: Color | null) => ValidateResult;
}
export interface ColorFieldRenderState {
value: Color | null;
isDisabled: boolean;
isReadOnly: boolean;
isRequired: boolean;
isInvalid: boolean;
isFocused: boolean;
isFocusWithin: boolean;
isFocusVisible: boolean;
validationErrors: string[];
}
export interface ColorFieldContext {
state: ColorState;
field: ReturnType<typeof useChoiceField<Color | null>>;
text: ReturnType<typeof useColorText>;
input: ShallowRef<HTMLInputElement | undefined>;
channel: ComputedRef<ColorTextOptions["channel"]>;
id: ComputedRef<string>;
name: ComputedRef<string | undefined>;
form: ComputedRef<string | undefined>;
autoFocus: ComputedRef<boolean>;
autoComplete: ComputedRef<string>;
register: (token: symbol, attrs: Record<string, unknown>) => void;
unregister: (token: symbol) => void;
connect: (token: symbol, input: HTMLInputElement | undefined) => void;
nativeAttrs: (attrs: Record<string, unknown>) => Record<string, unknown>;
wheel: (event: WheelEvent) => void;
}
export const colorFieldKey: InjectionKey<ColorFieldContext> =
Symbol("hv-color-field");
export function useColorFieldContext() {
return inject(colorFieldKey, undefined);
}
@@ -0,0 +1,82 @@
import {
cloneVNode,
Fragment,
isVNode,
type VNodeChild,
type VNode,
} from "vue";
const metadata = [
"id",
"name",
"form",
"disabled",
"readonly",
"readOnly",
"required",
"autofocus",
"autoFocus",
"autocomplete",
"autoComplete",
"aria-invalid",
] as const;
export function colorInputMetadata(props: Record<string, unknown>) {
return Object.fromEntries(
metadata.filter((key) => key in props).map((key) => [key, props[key]]),
);
}
/** Plan initial input metadata through known Group slots without mounting components. */
export function prepareColorFieldTree(
nodes: VNodeChild[],
state: Record<string, unknown>,
) {
let input: Record<string, unknown> | undefined;
let hasLabel = false;
function walk(children: VNodeChild[]): VNodeChild[] {
return children.map((node) => {
if (!isVNode(node)) return node;
const type = node.type as { name?: string; __name?: string };
const name = type.name ?? type.__name;
if (name === "Label") hasLabel = true;
if (name === "ColorInputGroupInput")
input = colorInputMetadata(node.props ?? {});
if (name === "ColorInputGroup" || name === "ColorInputGroupRoot") {
const slots = node.children as
| {
default?: (
state: Record<string, unknown>,
) => VNodeChild | VNodeChild[];
}
| undefined;
if (slots?.default) {
const initial = {
isDisabled: state.isDisabled,
isInvalid: state.isInvalid,
isFocusWithin: false,
isHovered: false,
};
const raw = slots.default(initial);
walk(Array.isArray(raw) ? raw : [raw]);
const clone = cloneVNode(node);
// Keep the real Group's reactive render state; a metadata preview is not its UI.
clone.children = {
...slots,
default: (groupState: Record<string, unknown>) =>
slots.default!(groupState),
};
return clone;
}
}
if (
(node.type === Fragment || typeof node.type === "string") &&
Array.isArray(node.children)
) {
const clone = cloneVNode(node);
clone.children = walk(node.children as VNodeChild[]) as VNode[];
return clone;
}
return node;
});
}
const prepared = walk(nodes);
return { nodes: prepared, input, hasLabel };
}
@@ -0,0 +1,213 @@
import {
computed,
onBeforeUpdate,
provide,
reactive,
shallowRef,
toRefs,
watchEffect,
type VNodeChild,
} from "vue";
import { useColorState } from "../color/model";
import { useColorText } from "../color/text";
import { useChoiceField } from "../choice/shared";
import { disabledContextKey } from "../field/disabled";
import {
colorFieldKey,
type ColorFieldProps,
type ColorFieldContext,
} from "./context";
import { colorInputMetadata, prepareColorFieldTree } from "./tree";
import type { Color } from "../color/value";
import { useConfig } from "../../providers/context";
const bool = (value: unknown) => value != null && value !== false;
/** Shared field owner and one connected input, with no second form/reset model. */
export function useColorField(
props: ColorFieldProps,
attrs: Record<string, unknown>,
change: (value: Color | null) => void,
) {
const planned = shallowRef<Record<string, unknown>>({}),
registered = shallowRef<Record<string, unknown>>({});
const nativeEvents = new Set([
"onBeforeinput",
"onKeydown",
"onKeyup",
"onInput",
"onBlur",
"onFocus",
"onWheel",
"onCompositionstart",
"onCompositionend",
"onPaste",
]);
const pickNative = () =>
Object.fromEntries(
Object.entries(attrs).filter(
([key]) => key.startsWith("aria-") || nativeEvents.has(key),
),
);
const rootNative = shallowRef(pickNative());
onBeforeUpdate(() => {
const next = pickNative(),
previous = rootNative.value;
if (
Object.keys(next).length !== Object.keys(previous).length ||
Object.keys(next).some((key) => next[key] !== previous[key])
)
rootNative.value = next;
});
const leaf = computed(() => ({ ...planned.value, ...registered.value }));
let owner: symbol | undefined;
const input = shallowRef<HTMLInputElement>();
const hasLabel = shallowRef(false),
config = useConfig();
const metadata = reactive({
...toRefs(props),
isDisabled: computed(
() => !!props.isDisabled || !!props.disabled || bool(leaf.value.disabled),
),
isReadOnly: computed(
() =>
!!props.isReadOnly || bool(leaf.value.readonly ?? leaf.value.readOnly),
),
});
const state = useColorState(metadata, {
fallback: () => null,
inherit: true,
provide: true,
change,
});
const effective = reactive({
...toRefs(props),
id: computed(() =>
typeof leaf.value.id === "string" ? leaf.value.id : props.id,
),
name: computed(() =>
typeof leaf.value.name === "string" ? leaf.value.name : props.name,
),
form: computed(() =>
typeof leaf.value.form === "string" ? leaf.value.form : props.form,
),
isRequired: computed(() => !!props.isRequired || bool(leaf.value.required)),
isDisabled: state.disabled,
isReadOnly: state.readOnly,
isInvalid: computed(
() =>
!!props.isInvalid ||
rootNative.value["aria-invalid"] === true ||
rootNative.value["aria-invalid"] === "true" ||
leaf.value["aria-invalid"] === true ||
leaf.value["aria-invalid"] === "true",
),
});
const field = useChoiceField(effective, attrs, {
kind: "text",
value: state.value,
satisfied: () => state.value.value !== null,
requiredMessage: "请选择颜色。",
validate: (value) => props.validate?.(value),
});
const text = useColorText(state, props, input, {
channelFormat: "unit",
submitOnEnter: true,
edit: field.edit,
reset: field.reset,
commitValidation: field.commitValidation,
});
const context: ColorFieldContext = {
state,
field,
text,
input,
channel: computed(() => props.channel),
id: field.field.controlId,
name: computed(() => effective.name),
form: computed(() => effective.form),
autoFocus: computed(
() =>
!!props.autoFocus || bool(leaf.value.autofocus ?? leaf.value.autoFocus),
),
autoComplete: computed(() =>
String(
leaf.value.autocomplete ??
leaf.value.autoComplete ??
props.autoComplete ??
"off",
),
),
register(token, attrs) {
if (owner && owner !== token)
throw new Error("ColorField supports one ColorInputGroupInput.");
owner = token;
const next = colorInputMetadata(attrs);
if (JSON.stringify(next) !== JSON.stringify(registered.value))
registered.value = next;
},
unregister(token) {
if (owner !== token) return;
owner = undefined;
input.value = undefined;
registered.value = {};
text.cancel();
},
connect(token, node) {
if (owner === token) input.value = node;
},
nativeAttrs(own) {
const forwarded = rootNative.value;
const names: Record<string, string> = {
hue: "色相",
saturation: "饱和度",
lightness: "明度",
brightness: "亮度",
red: "红色",
green: "绿色",
blue: "蓝色",
alpha: "透明度",
};
const locale = props.locale ?? config?.locale.value ?? "en-US";
return {
...forwarded,
"aria-label":
own["aria-label"] ??
attrs["aria-label"] ??
(!hasLabel.value &&
!own["aria-labelledby"] &&
!attrs["aria-labelledby"] &&
props.channel
? locale.startsWith("zh")
? names[props.channel]
: props.channel
: undefined),
};
},
wheel,
};
provide(colorFieldKey, context);
provide(disabledContextKey, state.disabled);
watchEffect(() => field.validity(input.value), { flush: "sync" });
function prepare(nodes: VNodeChild[], slotState: Record<string, unknown>) {
const tree = prepareColorFieldTree(nodes, slotState);
hasLabel.value = tree.hasLabel;
const next = tree.input ?? {};
if (JSON.stringify(next) !== JSON.stringify(planned.value))
planned.value = next;
return field.prepare(tree.nodes);
}
function wheel(event: WheelEvent) {
if (
event.defaultPrevented ||
!input.value ||
props.isWheelDisabled ||
state.disabled.value ||
state.readOnly.value ||
input.value?.ownerDocument.activeElement !== input.value ||
Math.abs(event.deltaY) <= Math.abs(event.deltaX)
)
return;
event.preventDefault();
text.adjust(event.deltaY > 0 ? 1 : -1);
}
return { ...context, prepare, wheel };
}
+122 -24
View File
@@ -23,11 +23,11 @@ export interface ColorTextOptions {
locale?: string;
}
/** Strict localized decimal parsing; grouping, exponents and trailing garbage are rejected. */
export function parseColorNumber(
function colorNumberText(
text: string,
locale: string,
channel: ColorChannel,
): number | undefined {
): string | undefined {
const formatter = new Intl.NumberFormat(locale, { useGrouping: false });
let raw = text.trim().replace(/[\u061c\u200e\u200f]/g, "");
for (let i = 0; i < 10; i++)
@@ -47,7 +47,15 @@ export function parseColorNumber(
raw = raw.slice(0, -1).trim();
}
if (channel === "hue") raw = raw.replace(/°$/, "").trim();
if (!/^[+-]?(?:\d+(?:\.\d*)?|\.\d+)$/.test(raw)) return;
return raw;
}
export function parseColorNumber(
text: string,
locale: string,
channel: ColorChannel,
): number | undefined {
const raw = colorNumberText(text, locale, channel);
if (raw === undefined || !/^[+-]?(?:\d+(?:\.\d*)?|\.\d+)$/.test(raw)) return;
const value = Number(raw);
// Channel text displays alpha on the familiar 0–100 scale, independent of model alpha 0–1.
return Number.isFinite(value)
@@ -65,6 +73,9 @@ export function useColorText(
options: {
edit?: () => void;
reset?: () => void;
channelFormat?: "plain" | "unit";
submitOnEnter?: boolean;
commitValidation?: () => void;
} = {},
) {
const config = useConfig();
@@ -76,9 +87,20 @@ export function useColorText(
? colorChannel(state.value.value, props.channel, props.colorSpace)
: undefined,
);
const nativeChannelValue = computed(() => {
const d = descriptor.value;
if (!d) return undefined;
return options.channelFormat === "unit"
? Number((Math.round(d.value / d.range.step) * d.range.step).toFixed(12))
: d.value;
});
const formatted = computed(() => {
if (!state.value.value) return "";
if (!props.channel) return state.value.value.toString("hex");
if (options.channelFormat === "unit")
return descriptor
.value!.color.withChannelValue(props.channel, nativeChannelValue.value!)
.formatChannelValue(props.channel, locale.value);
const value =
descriptor.value!.value * (props.channel === "alpha" ? 100 : 1);
return new Intl.NumberFormat(locale.value, {
@@ -90,6 +112,28 @@ export function useColorText(
const composing = shallowRef(false);
const token = Symbol("color-text");
let compositionRevision = 0;
let compositionDraft = draft.value;
function validDraft(text: string) {
if (!props.channel) return /^#?[\da-f]{0,6}$/i.test(text);
const raw = colorNumberText(text, locale.value, props.channel);
return raw !== undefined && /^[+-]?\d*(?:\.\d*)?$/.test(raw);
}
function beforeinput(event: InputEvent) {
if (
event.defaultPrevented ||
event.isComposing ||
composing.value ||
options.channelFormat !== "unit" ||
event.data == null
)
return;
const target = event.target as HTMLInputElement;
const next =
target.value.slice(0, target.selectionStart ?? target.value.length) +
event.data +
target.value.slice(target.selectionEnd ?? target.value.length);
if (!validDraft(next)) event.preventDefault();
}
function restore() {
draft.value = formatted.value;
if (input.value) input.value.value = draft.value;
@@ -100,7 +144,7 @@ export function useColorText(
compositionRevision++;
restore();
}
function parse() {
function parse(snap = true) {
const text = draft.value.trim();
if (!text) return null;
if (!props.channel) {
@@ -112,11 +156,16 @@ export function useColorText(
const value = parseColorNumber(text, locale.value, props.channel);
if (value === undefined) return undefined;
const base = state.value.value ?? parseColor("#000000");
return colorChannel(
base,
props.channel,
props.colorSpace,
).color.withChannelValue(props.channel, value);
const native = colorChannel(base, props.channel, props.colorSpace);
const number =
options.channelFormat === "unit" && snap
? Number(
(Math.round(value / native.range.step) * native.range.step).toFixed(
12,
),
)
: value;
return native.color.withChannelValue(props.channel, number);
}
function commit(event?: Event) {
if (composing.value) return;
@@ -150,7 +199,16 @@ export function useColorText(
restore();
return;
}
draft.value = (event.target as HTMLInputElement).value;
const target = event.target as HTMLInputElement;
if (
options.channelFormat === "unit" &&
!composing.value &&
!validDraft(target.value)
) {
target.value = draft.value;
return;
}
draft.value = target.value;
options.edit?.();
}
function keydown(event: KeyboardEvent) {
@@ -166,8 +224,9 @@ export function useColorText(
)
return;
if (event.key === "Enter") {
event.preventDefault();
if (!options.submitOnEnter) event.preventDefault();
commit();
options.commitValidation?.();
return;
}
if (event.key === "Escape") {
@@ -185,29 +244,52 @@ export function useColorText(
: 0;
if (!direction && event.key !== "Home" && event.key !== "End") return;
event.preventDefault();
const parsed = parse();
adjust(
direction,
event.shiftKey || event.key.startsWith("Page"),
event.key === "Home" ? "min" : event.key === "End" ? "max" : undefined,
);
}
function adjust(direction: number, page = false, boundary?: "min" | "max") {
if (state.disabled.value || state.readOnly.value || composing.value) return;
const parsed = parse(false);
const base = parsed ?? state.value.value ?? parseColor("#000000");
let next;
if (props.channel) {
const d = colorChannel(base, props.channel, props.colorSpace);
const step =
event.shiftKey || event.key.startsWith("Page")
? d.range.pageSize
: d.range.step;
const value =
event.key === "Home"
if (
options.channelFormat === "unit" &&
draft.value.trim() === formatted.value
)
d.value = nativeChannelValue.value ?? d.value;
const step = page ? d.range.pageSize : d.range.step;
let value =
boundary === "min"
? d.range.minValue
: event.key === "End"
: boundary === "max"
? d.range.maxValue
: d.value + direction * step;
if (options.channelFormat === "unit" && !boundary) {
const snapped = Number((Math.round(d.value / step) * step).toFixed(12));
value =
direction > 0
? snapped > d.value
? snapped
: snapped + step
: snapped < d.value
? snapped
: snapped - step;
if (!state.value.value && !draft.value.trim())
value = direction > 0 ? d.range.minValue : d.range.maxValue;
}
next = d.color.withChannelValue(props.channel, Number(value.toFixed(12)));
} else {
const value = Number.parseInt(base.toString("hex").slice(1), 16);
const step = event.shiftKey || event.key.startsWith("Page") ? 10 : 1;
const step = page ? 10 : 1;
const int =
event.key === "Home"
boundary === "min"
? 0
: event.key === "End"
: boundary === "max"
? 0xffffff
: Math.min(0xffffff, Math.max(0, value + direction * step));
next = parseColor(`#${int.toString(16).padStart(6, "0")}`);
@@ -219,8 +301,10 @@ export function useColorText(
}
restore();
void nextTick(restore);
options.commitValidation?.();
}
function compositionstart() {
compositionDraft = draft.value;
composing.value = true;
compositionRevision++;
}
@@ -228,7 +312,13 @@ export function useColorText(
const revision = ++compositionRevision;
// The Enter used to select an IME candidate must not also submit/commit.
void nextTick(() => {
if (revision === compositionRevision) composing.value = false;
if (revision === compositionRevision) {
composing.value = false;
if (options.channelFormat === "unit" && !validDraft(draft.value)) {
draft.value = compositionDraft;
if (input.value) input.value.value = draft.value;
}
}
});
}
watch(
@@ -268,7 +358,13 @@ export function useColorText(
!state.value.value
? ""
: props.channel
? String(descriptor.value!.value)
? String(
nativeChannelValue.value! /
(options.channelFormat === "unit" &&
["saturation", "lightness", "brightness"].includes(props.channel)
? 100
: 1),
)
: state.value.value.toString("hex"),
);
return {
@@ -279,6 +375,7 @@ export function useColorText(
locale,
composing,
input: onInput,
beforeinput,
commit,
blur: (event?: Event) => {
if (composing.value) cancel();
@@ -286,6 +383,7 @@ export function useColorText(
},
cancel,
keydown,
adjust,
compositionstart,
compositionend,
};
@@ -72,7 +72,7 @@ export function useTextControl(
watch(element, (next) => field?.setControl(next), { flush: "post" });
function update(event: Event) {
const next = (event.target as HTMLInputElement).value;
if (!disabled() && !readOnly()) {
if (!event.defaultPrevented && !disabled() && !readOnly()) {
internal.value = next;
field?.setValue(next);
emit("update:modelValue", next);