feat: establish shared color channel and text input protocols
This commit is contained in:
@@ -0,0 +1,63 @@
|
||||
import { computed } from "vue";
|
||||
import { useConfig } from "../../providers/context";
|
||||
import { Color, type ColorChannel, type ColorSpace } from "./value";
|
||||
import type { ColorState } from "./model";
|
||||
|
||||
export interface ColorChannelOptions {
|
||||
channel: ColorChannel;
|
||||
colorSpace?: ColorSpace;
|
||||
locale?: string;
|
||||
}
|
||||
/** Resolve a channel once for fields and sliders, without an optimistic color cache. */
|
||||
export function colorChannel(
|
||||
color: Color,
|
||||
channel: ColorChannel,
|
||||
space?: ColorSpace,
|
||||
) {
|
||||
const required: Partial<Record<ColorChannel, ColorSpace>> = {
|
||||
red: "rgb",
|
||||
green: "rgb",
|
||||
blue: "rgb",
|
||||
lightness: "hsl",
|
||||
brightness: "hsb",
|
||||
};
|
||||
const working =
|
||||
channel === "alpha"
|
||||
? color.getColorSpace()
|
||||
: (required[channel] ??
|
||||
(space === "rgb"
|
||||
? "hsl"
|
||||
: (space ??
|
||||
(color.getColorSpace() === "rgb"
|
||||
? "hsl"
|
||||
: color.getColorSpace()))));
|
||||
const value = color.toFormat(working);
|
||||
return {
|
||||
color: value,
|
||||
channel,
|
||||
range: value.getChannelRange(channel),
|
||||
value: value.getChannelValue(channel),
|
||||
};
|
||||
}
|
||||
export function useColorChannel(state: ColorState, props: ColorChannelOptions) {
|
||||
const config = useConfig();
|
||||
const locale = computed(
|
||||
() => props.locale ?? config?.locale.value ?? "en-US",
|
||||
);
|
||||
const descriptor = computed(() =>
|
||||
colorChannel(
|
||||
state.value.value ??
|
||||
new Color({ space: "hsl", h: 0, s: 100, l: 50, alpha: 1 }),
|
||||
props.channel,
|
||||
props.colorSpace,
|
||||
),
|
||||
);
|
||||
const value = computed(() => descriptor.value.value);
|
||||
const range = computed(() => descriptor.value.range);
|
||||
const label = computed(() =>
|
||||
descriptor.value.color.formatChannelValue(props.channel, locale.value),
|
||||
);
|
||||
const withValue = (next: number) =>
|
||||
descriptor.value.color.withChannelValue(props.channel, next);
|
||||
return { descriptor, value, range, label, locale, withValue };
|
||||
}
|
||||
@@ -0,0 +1,147 @@
|
||||
import { nextTick, onBeforeUnmount, watch, type ShallowRef } from "vue";
|
||||
import { useChoiceForm } from "../choice/shared";
|
||||
import { useConfig } from "../../providers/context";
|
||||
import { useColorChannel, type ColorChannelOptions } from "./channel";
|
||||
import type { ColorState } from "./model";
|
||||
|
||||
/** Native range/AT bridge. A public custom track must supply its own geometry adapter. */
|
||||
export function useColorNativeChannel(
|
||||
state: ColorState,
|
||||
props: ColorChannelOptions & {
|
||||
dir?: "ltr" | "rtl";
|
||||
},
|
||||
input: ShallowRef<HTMLInputElement | undefined>,
|
||||
) {
|
||||
const channel = useColorChannel(state, props);
|
||||
const config = useConfig();
|
||||
const token = Symbol("color-native-channel");
|
||||
const keys = new Set<string>();
|
||||
let ownerWindow: Window | null | undefined;
|
||||
const windowBlur = () => stop();
|
||||
const restore = () => {
|
||||
if (input.value) input.value.value = String(channel.value.value);
|
||||
};
|
||||
function stop(commit = false) {
|
||||
ownerWindow?.removeEventListener("blur", windowBlur);
|
||||
ownerWindow = undefined;
|
||||
keys.clear();
|
||||
if (commit) state.end(token);
|
||||
else state.cancel(token);
|
||||
void nextTick(restore);
|
||||
}
|
||||
function begin() {
|
||||
const started = state.active.value === token || state.begin(token);
|
||||
if (started && !ownerWindow) {
|
||||
ownerWindow = input.value?.ownerDocument.defaultView;
|
||||
ownerWindow?.addEventListener("blur", windowBlur);
|
||||
}
|
||||
return started;
|
||||
}
|
||||
function propose(next: number) {
|
||||
if (Number.isFinite(next) && begin())
|
||||
state.request(channel.withValue(next), token);
|
||||
void nextTick(restore);
|
||||
}
|
||||
function onInput(event: Event) {
|
||||
if (!event.defaultPrevented)
|
||||
propose(Number((event.target as HTMLInputElement).value));
|
||||
else void nextTick(restore);
|
||||
}
|
||||
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;
|
||||
}
|
||||
const { minValue, maxValue, step, pageSize } = channel.range.value;
|
||||
const sign = (props.dir ?? config?.dir.value) === "rtl" ? -1 : 1;
|
||||
const delta = event.shiftKey ? pageSize : step;
|
||||
let next = channel.value.value;
|
||||
switch (event.key) {
|
||||
case "ArrowRight":
|
||||
next += delta * sign;
|
||||
break;
|
||||
case "ArrowLeft":
|
||||
next -= delta * sign;
|
||||
break;
|
||||
case "ArrowUp":
|
||||
next += delta;
|
||||
break;
|
||||
case "ArrowDown":
|
||||
next -= delta;
|
||||
break;
|
||||
case "PageUp":
|
||||
next += pageSize;
|
||||
break;
|
||||
case "PageDown":
|
||||
next -= pageSize;
|
||||
break;
|
||||
case "Home":
|
||||
next = minValue;
|
||||
break;
|
||||
case "End":
|
||||
next = maxValue;
|
||||
break;
|
||||
default:
|
||||
return;
|
||||
}
|
||||
event.preventDefault();
|
||||
keys.add(event.key);
|
||||
propose(Number(next.toFixed(12)));
|
||||
}
|
||||
function keyup(event: KeyboardEvent) {
|
||||
if (!keys.delete(event.key)) return;
|
||||
if (event.defaultPrevented) stop();
|
||||
else if (!keys.size) stop(true);
|
||||
}
|
||||
watch(
|
||||
[
|
||||
state.disabled,
|
||||
state.readOnly,
|
||||
() => props.channel,
|
||||
() => props.colorSpace,
|
||||
() => props.dir,
|
||||
() => config?.dir.value,
|
||||
input,
|
||||
],
|
||||
() => stop(),
|
||||
{ flush: "sync" },
|
||||
);
|
||||
watch(state.active, (active) => {
|
||||
if (active !== token) {
|
||||
ownerWindow?.removeEventListener("blur", windowBlur);
|
||||
ownerWindow = undefined;
|
||||
keys.clear();
|
||||
void nextTick(restore);
|
||||
}
|
||||
});
|
||||
useChoiceForm(
|
||||
input,
|
||||
() => {
|
||||
stop();
|
||||
state.reset();
|
||||
},
|
||||
restore,
|
||||
);
|
||||
onBeforeUnmount(() => stop());
|
||||
return {
|
||||
...channel,
|
||||
input: onInput,
|
||||
keydown,
|
||||
keyup,
|
||||
commit: () => stop(true),
|
||||
cancel: () => stop(),
|
||||
};
|
||||
}
|
||||
@@ -0,0 +1,290 @@
|
||||
import {
|
||||
computed,
|
||||
nextTick,
|
||||
onBeforeUnmount,
|
||||
shallowRef,
|
||||
watch,
|
||||
type ShallowRef,
|
||||
} from "vue";
|
||||
import { useConfig } from "../../providers/context";
|
||||
import { useChoiceForm } from "../choice/shared";
|
||||
import { colorChannel } from "./channel";
|
||||
import {
|
||||
colorKey,
|
||||
parseColor,
|
||||
type ColorChannel,
|
||||
type ColorSpace,
|
||||
} from "./value";
|
||||
import type { ColorState } from "./model";
|
||||
|
||||
export interface ColorTextOptions {
|
||||
channel?: ColorChannel;
|
||||
colorSpace?: ColorSpace;
|
||||
locale?: string;
|
||||
}
|
||||
/** Strict localized decimal parsing; grouping, exponents and trailing garbage are rejected. */
|
||||
export function parseColorNumber(
|
||||
text: string,
|
||||
locale: string,
|
||||
channel: ColorChannel,
|
||||
): number | 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++)
|
||||
raw = raw.split(formatter.format(i)).join(String(i));
|
||||
const decimal =
|
||||
formatter.formatToParts(1.1).find((p) => p.type === "decimal")?.value ??
|
||||
".";
|
||||
const minus =
|
||||
formatter.formatToParts(-1).find((p) => p.type === "minusSign")?.value ??
|
||||
"-";
|
||||
if (decimal !== "." && raw.includes(".")) return;
|
||||
raw = raw.split(decimal).join(".").split(minus).join("-");
|
||||
const percent = /[%\u066a]$/.test(raw);
|
||||
if (percent) {
|
||||
if (!["alpha", "saturation", "lightness", "brightness"].includes(channel))
|
||||
return;
|
||||
raw = raw.slice(0, -1).trim();
|
||||
}
|
||||
if (channel === "hue") raw = raw.replace(/°$/, "").trim();
|
||||
if (!/^[+-]?(?:\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)
|
||||
? channel === "alpha"
|
||||
? value / 100
|
||||
: value
|
||||
: undefined;
|
||||
}
|
||||
|
||||
/** Drafts are text only. The shared owner remains the sole accepted color model. */
|
||||
export function useColorText(
|
||||
state: ColorState,
|
||||
props: ColorTextOptions,
|
||||
input: ShallowRef<HTMLInputElement | undefined>,
|
||||
options: {
|
||||
edit?: () => void;
|
||||
reset?: () => void;
|
||||
} = {},
|
||||
) {
|
||||
const config = useConfig();
|
||||
const locale = computed(
|
||||
() => props.locale ?? config?.locale.value ?? "en-US",
|
||||
);
|
||||
const descriptor = computed(() =>
|
||||
props.channel && state.value.value
|
||||
? colorChannel(state.value.value, props.channel, props.colorSpace)
|
||||
: undefined,
|
||||
);
|
||||
const formatted = computed(() => {
|
||||
if (!state.value.value) return "";
|
||||
if (!props.channel) return state.value.value.toString("hex");
|
||||
const value =
|
||||
descriptor.value!.value * (props.channel === "alpha" ? 100 : 1);
|
||||
return new Intl.NumberFormat(locale.value, {
|
||||
useGrouping: false,
|
||||
maximumFractionDigits: 10,
|
||||
}).format(value);
|
||||
});
|
||||
const draft = shallowRef(formatted.value);
|
||||
const composing = shallowRef(false);
|
||||
const token = Symbol("color-text");
|
||||
let compositionRevision = 0;
|
||||
function restore() {
|
||||
draft.value = formatted.value;
|
||||
if (input.value) input.value.value = draft.value;
|
||||
}
|
||||
function cancel() {
|
||||
state.cancel(token);
|
||||
composing.value = false;
|
||||
compositionRevision++;
|
||||
restore();
|
||||
}
|
||||
function parse() {
|
||||
const text = draft.value.trim();
|
||||
if (!text) return null;
|
||||
if (!props.channel) {
|
||||
if (!/^#?(?:[\da-f]{3}|[\da-f]{6})$/i.test(text)) return undefined;
|
||||
return parseColor(text.startsWith("#") ? text : `#${text}`);
|
||||
}
|
||||
if (text === formatted.value && state.value.value)
|
||||
return state.value.value.clone();
|
||||
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);
|
||||
}
|
||||
function commit(event?: Event) {
|
||||
if (composing.value) return;
|
||||
if (
|
||||
!event?.defaultPrevented &&
|
||||
!state.disabled.value &&
|
||||
!state.readOnly.value
|
||||
) {
|
||||
const next = parse();
|
||||
if (next !== undefined && state.begin(token)) {
|
||||
// Typing the same hex must not erase a gray hue or an existing alpha.
|
||||
if (!(
|
||||
next &&
|
||||
state.value.value &&
|
||||
!props.channel &&
|
||||
next.toString("hex") === state.value.value.toString("hex")
|
||||
))
|
||||
state.request(next, token);
|
||||
state.end(token);
|
||||
}
|
||||
}
|
||||
restore();
|
||||
void nextTick(restore);
|
||||
}
|
||||
function onInput(event: Event) {
|
||||
if (
|
||||
event.defaultPrevented ||
|
||||
state.disabled.value ||
|
||||
state.readOnly.value
|
||||
) {
|
||||
restore();
|
||||
return;
|
||||
}
|
||||
draft.value = (event.target as HTMLInputElement).value;
|
||||
options.edit?.();
|
||||
}
|
||||
function keydown(event: KeyboardEvent) {
|
||||
if (
|
||||
event.defaultPrevented ||
|
||||
event.isComposing ||
|
||||
composing.value ||
|
||||
event.ctrlKey ||
|
||||
event.metaKey ||
|
||||
event.altKey ||
|
||||
state.disabled.value ||
|
||||
state.readOnly.value
|
||||
)
|
||||
return;
|
||||
if (event.key === "Enter") {
|
||||
event.preventDefault();
|
||||
commit();
|
||||
return;
|
||||
}
|
||||
if (event.key === "Escape") {
|
||||
event.preventDefault();
|
||||
cancel();
|
||||
return;
|
||||
}
|
||||
const direction =
|
||||
event.key === "ArrowUp" || event.key === "PageUp"
|
||||
? 1
|
||||
: event.key === "ArrowDown" || event.key === "PageDown"
|
||||
? -1
|
||||
: 0;
|
||||
if (!direction && event.key !== "Home" && event.key !== "End") return;
|
||||
event.preventDefault();
|
||||
const parsed = parse();
|
||||
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"
|
||||
? d.range.minValue
|
||||
: event.key === "End"
|
||||
? d.range.maxValue
|
||||
: d.value + direction * step;
|
||||
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 int =
|
||||
event.key === "Home"
|
||||
? 0
|
||||
: event.key === "End"
|
||||
? 0xffffff
|
||||
: Math.min(0xffffff, Math.max(0, value + direction * step));
|
||||
next = parseColor(`#${int.toString(16).padStart(6, "0")}`);
|
||||
}
|
||||
options.edit?.();
|
||||
if (state.begin(token)) {
|
||||
state.request(next, token);
|
||||
state.end(token);
|
||||
}
|
||||
restore();
|
||||
void nextTick(restore);
|
||||
}
|
||||
function compositionstart() {
|
||||
composing.value = true;
|
||||
compositionRevision++;
|
||||
}
|
||||
function compositionend() {
|
||||
const revision = ++compositionRevision;
|
||||
// The Enter used to select an IME candidate must not also submit/commit.
|
||||
void nextTick(() => {
|
||||
if (revision === compositionRevision) composing.value = false;
|
||||
});
|
||||
}
|
||||
watch(
|
||||
() => colorKey(state.value.value),
|
||||
() => {
|
||||
composing.value = false;
|
||||
compositionRevision++;
|
||||
restore();
|
||||
},
|
||||
{ flush: "sync" },
|
||||
);
|
||||
watch(
|
||||
[
|
||||
() => props.channel,
|
||||
() => props.colorSpace,
|
||||
locale,
|
||||
state.disabled,
|
||||
state.readOnly,
|
||||
],
|
||||
cancel,
|
||||
{ flush: "sync" },
|
||||
);
|
||||
useChoiceForm(
|
||||
input,
|
||||
() => {
|
||||
cancel();
|
||||
state.reset();
|
||||
options.reset?.();
|
||||
},
|
||||
restore,
|
||||
);
|
||||
onBeforeUnmount(() => {
|
||||
state.cancel(token);
|
||||
compositionRevision++;
|
||||
});
|
||||
const submission = computed(() =>
|
||||
!state.value.value
|
||||
? ""
|
||||
: props.channel
|
||||
? String(descriptor.value!.value)
|
||||
: state.value.value.toString("hex"),
|
||||
);
|
||||
return {
|
||||
draft,
|
||||
formatted,
|
||||
submission,
|
||||
descriptor,
|
||||
locale,
|
||||
composing,
|
||||
input: onInput,
|
||||
commit,
|
||||
blur: (event?: Event) => {
|
||||
if (composing.value) cancel();
|
||||
else commit(event);
|
||||
},
|
||||
cancel,
|
||||
keydown,
|
||||
compositionstart,
|
||||
compositionend,
|
||||
};
|
||||
}
|
||||
Reference in New Issue
Block a user