feat: establish color slider geometry and picker composition
This commit is contained in:
@@ -1,4 +1,10 @@
|
||||
import { nextTick, onBeforeUnmount, watch, type ShallowRef } from "vue";
|
||||
import {
|
||||
computed,
|
||||
nextTick,
|
||||
onBeforeUnmount,
|
||||
watch,
|
||||
type ShallowRef,
|
||||
} from "vue";
|
||||
import { useChoiceForm } from "../choice/shared";
|
||||
import { useConfig } from "../../providers/context";
|
||||
import { useColorChannel, type ColorChannelOptions } from "./channel";
|
||||
@@ -9,6 +15,7 @@ export function useColorNativeChannel(
|
||||
state: ColorState,
|
||||
props: ColorChannelOptions & {
|
||||
dir?: "ltr" | "rtl";
|
||||
orientation?: "horizontal" | "vertical";
|
||||
},
|
||||
input: ShallowRef<HTMLInputElement | undefined>,
|
||||
) {
|
||||
@@ -66,7 +73,11 @@ export function useColorNativeChannel(
|
||||
return;
|
||||
}
|
||||
const { minValue, maxValue, step, pageSize } = channel.range.value;
|
||||
const sign = (props.dir ?? config?.dir.value) === "rtl" ? -1 : 1;
|
||||
const sign =
|
||||
(props.dir ?? config?.dir.value) === "rtl" &&
|
||||
props.orientation !== "vertical"
|
||||
? -1
|
||||
: 1;
|
||||
const delta = event.shiftKey ? pageSize : step;
|
||||
let next = channel.value.value;
|
||||
switch (event.key) {
|
||||
@@ -113,6 +124,7 @@ export function useColorNativeChannel(
|
||||
() => props.channel,
|
||||
() => props.colorSpace,
|
||||
() => props.dir,
|
||||
() => props.orientation,
|
||||
() => config?.dir.value,
|
||||
input,
|
||||
],
|
||||
@@ -143,5 +155,11 @@ export function useColorNativeChannel(
|
||||
keyup,
|
||||
commit: () => stop(true),
|
||||
cancel: () => stop(),
|
||||
// Private custom-track bridge; keyboard, native AT and pointer share one token.
|
||||
transaction: {
|
||||
begin,
|
||||
propose,
|
||||
active: computed(() => state.active.value === token),
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
@@ -0,0 +1,55 @@
|
||||
import { colorChannel } from "./channel";
|
||||
import { Color, type ColorChannel, type ColorSpace } from "./value";
|
||||
export function colorSliderDisplay(
|
||||
color: Color,
|
||||
channel: ColorChannel,
|
||||
space?: ColorSpace,
|
||||
) {
|
||||
const native = colorChannel(color, channel, space).color;
|
||||
return channel === "hue"
|
||||
? new Color({
|
||||
space: "hsl",
|
||||
h: native.getChannelValue("hue"),
|
||||
s: 100,
|
||||
l: 50,
|
||||
alpha: 1,
|
||||
})
|
||||
: channel === "alpha"
|
||||
? native
|
||||
: native.withAlpha(1);
|
||||
}
|
||||
/** Exact piecewise sRGB ramps; HSL lightness needs its chromatic midpoint. */
|
||||
export function colorSliderBackground(
|
||||
color: Color,
|
||||
channel: ColorChannel,
|
||||
space?: ColorSpace,
|
||||
orientation: "horizontal" | "vertical" = "horizontal",
|
||||
dir: "ltr" | "rtl" = "ltr",
|
||||
) {
|
||||
const d = colorChannel(
|
||||
colorSliderDisplay(color, channel, space),
|
||||
channel,
|
||||
space,
|
||||
),
|
||||
max = d.range.maxValue;
|
||||
const values =
|
||||
channel === "hue"
|
||||
? [0, 60, 120, 180, 240, 300, 360]
|
||||
: channel === "lightness"
|
||||
? [0, 50, 100]
|
||||
: [0, max];
|
||||
const css = (value: number) =>
|
||||
d.color.withChannelValue(channel, value).toString("css");
|
||||
const direction =
|
||||
orientation === "vertical"
|
||||
? "to top"
|
||||
: dir === "rtl"
|
||||
? "to left"
|
||||
: "to right";
|
||||
const ramp = `linear-gradient(${direction}, ${values.map((value) => `${css(value)} ${(value / max) * 100}%`).join(", ")})`;
|
||||
return {
|
||||
background: `${ramp}, repeating-conic-gradient(#efefef 0% 25%, #f7f7f7 0% 50%) 50% / 16px 16px`,
|
||||
"--track-start-color": css(0),
|
||||
"--track-end-color": css(max),
|
||||
};
|
||||
}
|
||||
@@ -0,0 +1,190 @@
|
||||
import {
|
||||
computed,
|
||||
onBeforeUnmount,
|
||||
shallowRef,
|
||||
watch,
|
||||
type ShallowRef,
|
||||
} from "vue";
|
||||
import { useConfig } from "../../providers/context";
|
||||
import { useColorNativeChannel } from "./native-channel";
|
||||
import type { ColorChannelOptions } from "./channel";
|
||||
import type { ColorState } from "./model";
|
||||
|
||||
export interface ColorSliderOptions extends ColorChannelOptions {
|
||||
dir?: "ltr" | "rtl";
|
||||
orientation?: "horizontal" | "vertical";
|
||||
}
|
||||
/** One native input plus a stable custom track; all edits share the native channel token. */
|
||||
export function useColorSlider(
|
||||
state: ColorState,
|
||||
props: ColorSliderOptions,
|
||||
elements: {
|
||||
track: ShallowRef<HTMLElement | undefined>;
|
||||
thumb: ShallowRef<HTMLElement | undefined>;
|
||||
input: ShallowRef<HTMLInputElement | undefined>;
|
||||
},
|
||||
) {
|
||||
const control = useColorNativeChannel(state, props, elements.input);
|
||||
const config = useConfig();
|
||||
const dir = computed(() => props.dir ?? config?.dir.value ?? "ltr");
|
||||
const orientation = computed(() => props.orientation ?? "horizontal");
|
||||
const vertical = computed(() => orientation.value === "vertical");
|
||||
const percent = computed(() => {
|
||||
const r = control.range.value;
|
||||
return (control.value.value - r.minValue) / (r.maxValue - r.minValue);
|
||||
});
|
||||
const position = computed(() =>
|
||||
vertical.value
|
||||
? { left: "50%", top: `${(1 - percent.value) * 100}%` }
|
||||
: {
|
||||
left: `${(dir.value === "rtl" ? 1 - percent.value : percent.value) * 100}%`,
|
||||
top: "50%",
|
||||
},
|
||||
);
|
||||
const dragging = shallowRef(false);
|
||||
let pointer: number | undefined,
|
||||
owner: HTMLElement | undefined,
|
||||
grab = 0,
|
||||
last: number | undefined;
|
||||
function stop(commit = false) {
|
||||
const id = pointer,
|
||||
node = owner;
|
||||
pointer = undefined;
|
||||
owner = undefined;
|
||||
dragging.value = false;
|
||||
grab = 0;
|
||||
last = undefined;
|
||||
if (id !== undefined && node?.hasPointerCapture?.(id))
|
||||
node.releasePointerCapture(id);
|
||||
if (commit) control.commit();
|
||||
else control.cancel();
|
||||
}
|
||||
function local(event: PointerEvent) {
|
||||
const node = elements.track.value;
|
||||
if (!node) return;
|
||||
const rect = node.getBoundingClientRect(),
|
||||
css = getComputedStyle(node);
|
||||
const length = vertical.value ? rect.height : rect.width;
|
||||
const scale =
|
||||
length / (vertical.value ? node.offsetHeight : node.offsetWidth) || 1;
|
||||
const before =
|
||||
(parseFloat(vertical.value ? css.borderTopWidth : css.borderLeftWidth) ||
|
||||
0) * scale;
|
||||
const after =
|
||||
(parseFloat(
|
||||
vertical.value ? css.borderBottomWidth : css.borderRightWidth,
|
||||
) || 0) * scale;
|
||||
const size = length - before - after;
|
||||
if (size <= 0) return;
|
||||
let p =
|
||||
((vertical.value ? event.clientY - rect.top : event.clientX - rect.left) -
|
||||
before) /
|
||||
size;
|
||||
if (vertical.value || dir.value === "rtl") p = 1 - p;
|
||||
const range = control.range.value;
|
||||
return range.minValue + p * (range.maxValue - range.minValue);
|
||||
}
|
||||
function update(raw: number) {
|
||||
const { minValue, maxValue, step } = control.range.value;
|
||||
const next = Math.min(
|
||||
maxValue,
|
||||
Math.max(
|
||||
minValue,
|
||||
Number(
|
||||
(
|
||||
Math.round((raw - grab - minValue) / step) * step +
|
||||
minValue
|
||||
).toFixed(12),
|
||||
),
|
||||
),
|
||||
);
|
||||
if (next === last) return;
|
||||
last = next;
|
||||
control.transaction.propose(next);
|
||||
}
|
||||
function pointerdown(event: PointerEvent) {
|
||||
if (
|
||||
event.defaultPrevented ||
|
||||
event.button !== 0 ||
|
||||
event.isPrimary === false ||
|
||||
pointer !== undefined ||
|
||||
state.disabled.value ||
|
||||
state.readOnly.value ||
|
||||
(event.pointerType === "mouse" &&
|
||||
(event.ctrlKey || event.metaKey || event.altKey))
|
||||
)
|
||||
return;
|
||||
const point = local(event),
|
||||
track = elements.track.value;
|
||||
if (point === undefined || !track || !elements.input.value) return;
|
||||
stop();
|
||||
if (!control.transaction.begin()) return;
|
||||
pointer = event.pointerId;
|
||||
owner = track;
|
||||
dragging.value = true;
|
||||
const hit = elements.thumb.value?.contains(event.target as Node);
|
||||
grab = hit ? point - control.value.value : 0;
|
||||
event.preventDefault();
|
||||
elements.input.value.focus({ preventScroll: true });
|
||||
owner.setPointerCapture?.(event.pointerId);
|
||||
if (!hit) update(point);
|
||||
}
|
||||
function pointermove(event: PointerEvent) {
|
||||
if (event.defaultPrevented || event.pointerId !== pointer) return;
|
||||
const point = local(event);
|
||||
if (point === undefined) return;
|
||||
event.preventDefault();
|
||||
update(point);
|
||||
}
|
||||
function pointerup(event: PointerEvent) {
|
||||
if (event.pointerId !== pointer) return;
|
||||
if (!event.defaultPrevented) {
|
||||
const point = local(event);
|
||||
if (point !== undefined) update(point);
|
||||
}
|
||||
stop(!event.defaultPrevented);
|
||||
}
|
||||
function cancel(event?: PointerEvent) {
|
||||
if (!event || event.pointerId === pointer) stop();
|
||||
}
|
||||
watch(
|
||||
[
|
||||
state.disabled,
|
||||
state.readOnly,
|
||||
dir,
|
||||
orientation,
|
||||
() => props.channel,
|
||||
() => props.colorSpace,
|
||||
elements.track,
|
||||
elements.thumb,
|
||||
elements.input,
|
||||
],
|
||||
() => stop(),
|
||||
{ flush: "sync" },
|
||||
);
|
||||
watch(
|
||||
control.transaction.active,
|
||||
(active) => {
|
||||
if (!active && pointer !== undefined) stop();
|
||||
},
|
||||
{ flush: "sync" },
|
||||
);
|
||||
onBeforeUnmount(() => stop());
|
||||
return {
|
||||
...control,
|
||||
dir,
|
||||
orientation,
|
||||
percent,
|
||||
position,
|
||||
dragging,
|
||||
pointerdown,
|
||||
pointermove,
|
||||
pointerup,
|
||||
cancel,
|
||||
commit: () => stop(true),
|
||||
keydown: (event: KeyboardEvent) => {
|
||||
if (pointer !== undefined && event.key !== "Escape") return;
|
||||
control.keydown(event);
|
||||
},
|
||||
};
|
||||
}
|
||||
@@ -0,0 +1,28 @@
|
||||
import type { Color } from "./value";
|
||||
/** Full JS numeric precision, expanded so the strict functional parser can round-trip exponents. */
|
||||
function decimal(value: number) {
|
||||
const text = String(value),
|
||||
parts = text.split("e");
|
||||
if (parts.length === 1) return text;
|
||||
const coefficient = parts[0]!,
|
||||
exponent = Number(parts[1]);
|
||||
const dot = coefficient.indexOf(".");
|
||||
const digits = coefficient.replace(".", "");
|
||||
const point = (dot === -1 ? digits.length : dot) + exponent;
|
||||
if (point <= 0) return `0.${"0".repeat(-point)}${digits}`;
|
||||
if (point >= digits.length) return digits + "0".repeat(point - digits.length);
|
||||
return `${digits.slice(0, point)}.${digits.slice(point)}`;
|
||||
}
|
||||
/** Private owner serialization proof, separate from display CSS and final public field formats. */
|
||||
export function serializeColorValue(color: Color | null) {
|
||||
if (!color) return "";
|
||||
const space = color.getColorSpace();
|
||||
const channels = color
|
||||
.getChannels()
|
||||
.map(
|
||||
(channel, index) =>
|
||||
decimal(color.getChannelValue(channel)) +
|
||||
(space !== "rgb" && index > 0 ? "%" : ""),
|
||||
);
|
||||
return `${space}a(${channels.join(", ")}, ${decimal(color.getChannelValue("alpha"))})`;
|
||||
}
|
||||
@@ -171,8 +171,10 @@ export function useColorText(
|
||||
return;
|
||||
}
|
||||
if (event.key === "Escape") {
|
||||
event.preventDefault();
|
||||
cancel();
|
||||
if (draft.value !== formatted.value) {
|
||||
event.preventDefault();
|
||||
cancel();
|
||||
}
|
||||
return;
|
||||
}
|
||||
const direction =
|
||||
|
||||
@@ -0,0 +1,19 @@
|
||||
import { defineComponent, watch } from "vue";
|
||||
import { usePopover } from "../../src/components/popover/context";
|
||||
import { useColorStateContext } from "../../src/components/color/model";
|
||||
/** Observe accepted overlay state, never its potentially rejected close proposal. */
|
||||
export default defineComponent({
|
||||
name: "ColorPickerBoundary",
|
||||
setup(_, { slots }) {
|
||||
const overlay = usePopover(),
|
||||
color = useColorStateContext()!;
|
||||
watch(
|
||||
overlay.state.isOpen,
|
||||
(open) => {
|
||||
if (!open) color.cancel();
|
||||
},
|
||||
{ flush: "sync" },
|
||||
);
|
||||
return () => slots.default?.();
|
||||
},
|
||||
});
|
||||
@@ -0,0 +1,123 @@
|
||||
<script setup lang="ts">
|
||||
import { computed, shallowRef } from "vue";
|
||||
import {
|
||||
useColorState,
|
||||
type ColorModelProps,
|
||||
} from "../../src/components/color/model";
|
||||
import { serializeColorValue } from "../../src/components/color/submission";
|
||||
import { useChoiceForm } from "../../src/components/choice/shared";
|
||||
import { parseColor, type Color } from "../../src/components/color/value";
|
||||
import {
|
||||
Button,
|
||||
Popover,
|
||||
PopoverTrigger,
|
||||
PopoverContent,
|
||||
PopoverDialog,
|
||||
} from "../../src/index";
|
||||
import Boundary from "./ColorPickerBoundary";
|
||||
import Area from "./ColorAreaFoundation.vue";
|
||||
import Slider from "./ColorSliderFoundation.vue";
|
||||
import Input from "./ColorInputFoundation.vue";
|
||||
const props = withDefaults(
|
||||
defineProps<
|
||||
ColorModelProps & {
|
||||
name?: string;
|
||||
form?: string;
|
||||
open?: boolean;
|
||||
defaultOpen?: boolean;
|
||||
}
|
||||
>(),
|
||||
{ open: undefined },
|
||||
);
|
||||
const emit = defineEmits<{
|
||||
"update:modelValue": [Color | null];
|
||||
change: [Color | null];
|
||||
changeEnd: [Color | null];
|
||||
"update:open": [boolean];
|
||||
}>();
|
||||
const state = useColorState(props, {
|
||||
provide: true,
|
||||
fallback: () => parseColor("hsb(270,0%,50%,.123456789)"),
|
||||
change: (value) => {
|
||||
emit("update:modelValue", value);
|
||||
emit("change", value);
|
||||
},
|
||||
changeEnd: (value) => emit("changeEnd", value),
|
||||
});
|
||||
const native = shallowRef<HTMLInputElement>();
|
||||
const value = state.value,
|
||||
disabled = state.disabled;
|
||||
const serialized = computed(() => serializeColorValue(value.value));
|
||||
useChoiceForm(native, state.reset, () => {
|
||||
if (native.value) native.value.value = serialized.value;
|
||||
});
|
||||
defineExpose({ state });
|
||||
</script>
|
||||
<template>
|
||||
<div data-color-picker-composition>
|
||||
<Popover
|
||||
:open="open"
|
||||
:default-open="defaultOpen"
|
||||
@update:open="emit('update:open', $event)"
|
||||
>
|
||||
<Boundary>
|
||||
<PopoverTrigger as-child>
|
||||
<Button
|
||||
:is-disabled="disabled"
|
||||
variant="secondary"
|
||||
data-color-picker-trigger
|
||||
>
|
||||
<span
|
||||
:style="{
|
||||
width: '20px',
|
||||
height: '20px',
|
||||
borderRadius: '6px',
|
||||
background: value?.toString('css'),
|
||||
}"
|
||||
/>
|
||||
选择颜色
|
||||
</Button>
|
||||
</PopoverTrigger>
|
||||
<PopoverContent
|
||||
placement="bottom start"
|
||||
:style="{ width: '256px' }"
|
||||
data-color-picker-panel
|
||||
>
|
||||
<PopoverDialog
|
||||
aria-label="选择颜色"
|
||||
class="color-picker-composition-panel"
|
||||
>
|
||||
<Area aria-label="Color area" />
|
||||
<Slider channel="hue" aria-label="Color hue" />
|
||||
<Slider channel="alpha" aria-label="Color alpha" />
|
||||
<Input channel="alpha" aria-label="Color alpha text" />
|
||||
<Input aria-label="Color hex text" />
|
||||
</PopoverDialog>
|
||||
</PopoverContent>
|
||||
</Boundary>
|
||||
</Popover>
|
||||
<input
|
||||
ref="native"
|
||||
type="hidden"
|
||||
:name="name"
|
||||
:form="form"
|
||||
:disabled="disabled"
|
||||
:value="serialized"
|
||||
/>
|
||||
<output data-color-picker-accepted>{{ serialized }}</output>
|
||||
</div>
|
||||
</template>
|
||||
<style>
|
||||
.color-picker-composition-panel {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
gap: 16px;
|
||||
}
|
||||
.color-picker-composition-panel [data-color-input] {
|
||||
width: 100%;
|
||||
padding: 8px 12px;
|
||||
border: 1px solid var(--border);
|
||||
border-radius: 12px;
|
||||
background: var(--field-background);
|
||||
}
|
||||
</style>
|
||||
@@ -0,0 +1,134 @@
|
||||
<script setup lang="ts">
|
||||
import { computed, ref, shallowRef, useAttrs } from "vue";
|
||||
import {
|
||||
useColorState,
|
||||
type ColorModelProps,
|
||||
} from "../../src/components/color/model";
|
||||
import {
|
||||
useColorSlider,
|
||||
type ColorSliderOptions,
|
||||
} from "../../src/components/color/slider";
|
||||
import {
|
||||
colorSliderBackground,
|
||||
colorSliderDisplay,
|
||||
} from "../../src/components/color/slider-gradient";
|
||||
import { parseColor, type Color } from "../../src/components/color/value";
|
||||
defineOptions({ inheritAttrs: false });
|
||||
const props = defineProps<
|
||||
ColorModelProps &
|
||||
ColorSliderOptions & { name?: string; form?: string; trackKey?: string }
|
||||
>();
|
||||
const emit = defineEmits<{
|
||||
"update:modelValue": [Color | null];
|
||||
change: [Color | null];
|
||||
changeEnd: [Color | null];
|
||||
}>();
|
||||
const attrs = useAttrs();
|
||||
const state = useColorState(props, {
|
||||
inherit: true,
|
||||
fallback: () => parseColor("hsb(240,50%,50%)"),
|
||||
change: (value) => {
|
||||
emit("update:modelValue", value);
|
||||
emit("change", value);
|
||||
},
|
||||
changeEnd: (value) => emit("changeEnd", value),
|
||||
});
|
||||
const track = shallowRef<HTMLElement>(),
|
||||
thumb = shallowRef<HTMLElement>(),
|
||||
input = shallowRef<HTMLInputElement>();
|
||||
const control = useColorSlider(state, props, { track, thumb, input });
|
||||
const { dir, orientation, value, range, label, position, dragging } = control;
|
||||
const disabled = state.disabled,
|
||||
readonly = state.readOnly;
|
||||
const focusVisible = ref(false);
|
||||
const background = computed(() =>
|
||||
colorSliderBackground(
|
||||
control.descriptor.value.color,
|
||||
props.channel,
|
||||
props.colorSpace,
|
||||
orientation.value,
|
||||
dir.value,
|
||||
),
|
||||
);
|
||||
const hidden = {
|
||||
position: "absolute" as const,
|
||||
width: "1px",
|
||||
height: "1px",
|
||||
clipPath: "inset(50%)",
|
||||
overflow: "hidden",
|
||||
};
|
||||
function focused(event: FocusEvent) {
|
||||
focusVisible.value = (event.target as HTMLElement).matches(":focus-visible");
|
||||
}
|
||||
defineExpose({ state });
|
||||
</script>
|
||||
<template>
|
||||
<div
|
||||
class="hv-color-slider"
|
||||
data-color-slider-foundation
|
||||
:data-orientation="orientation"
|
||||
:dir="dir"
|
||||
:data-disabled="disabled || undefined"
|
||||
>
|
||||
<output class="hv-color-slider__output">{{ label }}</output>
|
||||
<div
|
||||
:key="trackKey"
|
||||
ref="track"
|
||||
data-color-slider-track
|
||||
class="hv-color-slider__track"
|
||||
:style="{ ...background, touchAction: 'none', forcedColorAdjust: 'none' }"
|
||||
@pointerdown="control.pointerdown"
|
||||
@pointermove="control.pointermove"
|
||||
@pointerup="control.pointerup"
|
||||
@pointercancel="control.cancel"
|
||||
@lostpointercapture="control.cancel"
|
||||
>
|
||||
<div
|
||||
ref="thumb"
|
||||
data-color-slider-thumb
|
||||
class="hv-color-slider__thumb"
|
||||
:data-disabled="disabled || undefined"
|
||||
:data-dragging="dragging || undefined"
|
||||
:data-focus-visible="focusVisible || undefined"
|
||||
:style="{
|
||||
...position,
|
||||
transform: 'translate(-50%, -50%)',
|
||||
backgroundColor: disabled
|
||||
? undefined
|
||||
: colorSliderDisplay(
|
||||
control.descriptor.value.color,
|
||||
channel,
|
||||
colorSpace,
|
||||
).toString('css'),
|
||||
}"
|
||||
>
|
||||
<input
|
||||
ref="input"
|
||||
data-color-slider-input
|
||||
v-bind="attrs"
|
||||
type="range"
|
||||
:style="hidden"
|
||||
:min="range.minValue"
|
||||
:max="range.maxValue"
|
||||
step="any"
|
||||
:value="value"
|
||||
:name="name"
|
||||
:form="form"
|
||||
:disabled="disabled"
|
||||
:aria-readonly="readonly || undefined"
|
||||
:aria-orientation="orientation"
|
||||
:aria-valuetext="label"
|
||||
@input="control.input"
|
||||
@change="control.commit"
|
||||
@keydown="control.keydown"
|
||||
@keyup="control.keyup"
|
||||
@focus="focused"
|
||||
@blur="
|
||||
focusVisible = false;
|
||||
control.commit();
|
||||
"
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</template>
|
||||
Reference in New Issue
Block a user