feat(docs): add custom color picker built on vue-color

Replace the native color input in the icon customizers with a dropdown
built on vue-color's ChromePicker: a saturation area, hue and alpha
sliders, and an eyedropper button where the browser supports it.

- Knobs use the same 20px size, shadow and hover/active rings as the
  customizer's range slider thumbs
- The panel is teleported to the body and positioned with floating-ui,
  so the sidebar's scroll container doesn't clip it
- vue-color is loaded lazily when the picker is about to open
- Keyboard: Tab moves through the panel and on to the hex field,
  Shift+Tab goes back, Escape closes and returns focus to the swatch.
  vue-color's sliders prevent the default of every key, so Tab is
  handled by hand
- Colors are emitted as hex, with 8 digits when alpha is below 100%

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01G9u8FhybXR7xuDECHDUz2n
This commit is contained in:
Claude 2026-11-12 07:10:06 +00:00
parent 03eae6069e
commit 0462c92d9b
No known key found for this signature in database
4 changed files with 485 additions and 25 deletions

View file

@ -1,5 +1,7 @@
<script setup lang="ts">
import { computed } from 'vue';
import { computed, defineAsyncComponent, nextTick, ref } from 'vue';
import { autoUpdate, flip, offset, shift, useFloating } from '@floating-ui/vue';
import { onClickOutside, useEventListener, useMounted } from '@vueuse/core';
const props = defineProps<{
modelValue: string;
@ -26,20 +28,129 @@ const value = computed({
},
set: (val) => emit('update:modelValue', limitHexInput(val)),
});
// vue-color is only loaded once the picker is about to open
const loadColorPickerPanel = () => import('./ColorPickerPanel.vue');
const ColorPickerPanel = defineAsyncComponent(loadColorPickerPanel);
// The server renders the default colour, match it on the first client render
const isMounted = useMounted();
const swatchColor = computed(() => {
if (!isMounted.value || !value.value || !CSS.supports('color', value.value)) {
return 'currentColor';
}
return value.value;
});
const isOpen = ref(false);
const swatchRef = ref<HTMLButtonElement | null>(null);
const textInputRef = ref<HTMLInputElement | null>(null);
const floatingRef = ref<HTMLElement | null>(null);
const panelId = computed(() => `${props.id}-panel`);
const { floatingStyles } = useFloating(swatchRef, floatingRef, {
placement: 'bottom-start',
middleware: [offset(8), flip({ padding: 16 }), shift({ padding: 16 })],
whileElementsMounted: autoUpdate,
// Position with top/left, so the open transition can use transform
transform: false,
});
function close({ focusSwatch = false } = {}) {
isOpen.value = false;
if (focusSwatch) {
swatchRef.value?.focus();
}
}
onClickOutside(floatingRef, () => close(), { ignore: [swatchRef] });
const openDocument = () => (isOpen.value ? document : null);
useEventListener(openDocument, 'keydown', (event: KeyboardEvent) => {
if (event.key === 'Escape') {
close({ focusSwatch: true });
}
});
// Close when focus moves somewhere else, for example with Shift+Tab from the swatch
useEventListener(openDocument, 'focusin', (event: FocusEvent) => {
const target = event.target as Node;
if (!swatchRef.value?.contains(target) && !floatingRef.value?.contains(target)) {
close();
}
});
function getPanelFocusables() {
return Array.from(
floatingRef.value?.querySelectorAll<HTMLElement>(
'button:not([disabled]), [tabindex]:not([tabindex="-1"])',
) ?? [],
);
}
// The panel lives at the end of the body, so Tab from the swatch has to move into it by hand
async function onSwatchKeydown(event: KeyboardEvent) {
if (event.key !== 'Tab' || event.shiftKey || !isOpen.value) {
return;
}
event.preventDefault();
await nextTick();
(getPanelFocusables()[0] ?? floatingRef.value)?.focus();
}
/*
* Tab through the panel by hand. vue-color's sliders prevent the default of every key, so the
* browser won't move focus away from them. Leaving the panel continues where the swatch is.
*/
function onPanelKeydown(event: KeyboardEvent) {
if (event.key !== 'Tab') {
return;
}
event.preventDefault();
event.stopPropagation();
const focusables = getPanelFocusables();
const index = focusables.indexOf(document.activeElement as HTMLElement);
const next = focusables[index + (event.shiftKey ? -1 : 1)];
if (next) {
next.focus();
} else if (event.shiftKey) {
swatchRef.value?.focus();
} else {
close();
textInputRef.value?.focus();
}
}
</script>
<template>
<div class="color-picker">
<div class="color-input-wrapper">
<input
type="color"
:id="id"
:name="id"
class="color-input"
v-model="value"
/>
</div>
<div
class="color-picker"
@pointerenter="loadColorPickerPanel"
@focusin="loadColorPickerPanel"
>
<button
ref="swatchRef"
type="button"
:id="id"
class="color-swatch"
aria-label="Open color picker"
aria-haspopup="dialog"
:aria-expanded="String(isOpen)"
:aria-controls="isOpen ? panelId : undefined"
:style="{ '--swatch-color': swatchColor }"
@click="isOpen = !isOpen"
@keydown="onSwatchKeydown"
/>
<input
ref="textInputRef"
type="text"
:id="`${id}-input`"
:name="`${id}-input`"
@ -49,25 +160,51 @@ const value = computed({
maxlength="9"
placeholder="[default]"
/>
<!-- Teleported, so the sidebar's scroll container doesn't clip it -->
<Teleport to="body">
<Transition name="color-picker-popover">
<div
v-if="isOpen"
ref="floatingRef"
:id="panelId"
class="color-picker-popover"
role="dialog"
aria-label="Color picker"
tabindex="-1"
:style="floatingStyles"
@keydown.capture="onPanelKeydown"
>
<ColorPickerPanel v-model="value" />
</div>
</Transition>
</Teleport>
</div>
</template>
<style scoped>
.color-input {
width: 34px;
height: 34px;
position: absolute;
top: -5px;
left: -5px;
.color-swatch {
position: relative;
flex-shrink: 0;
width: 24px;
height: 24px;
border-radius: 4px;
color: var(--vp-c-text-1);
/* The colour on top of a checkerboard, so transparent colours are visible */
background:
linear-gradient(var(--swatch-color), var(--swatch-color)),
repeating-conic-gradient(#e6e6e6 0% 25%, #fff 0% 50%) 0 0 / 8px 8px;
box-shadow: inset 0 0 0 1px rgba(0, 0, 0, 0.1);
cursor: pointer;
transition: box-shadow 0.25s;
}
.color-input-wrapper {
height: 24px;
width: 24px;
overflow: hidden;
position: relative;
border-radius: 4px;
flex-shrink: 0;
.color-swatch:focus-visible,
.color-swatch[aria-expanded='true'] {
outline: none;
box-shadow:
inset 0 0 0 1px rgba(0, 0, 0, 0.1),
0 0 0 2px var(--vp-c-bg),
0 0 0 4px var(--vp-c-brand);
}
.color-picker {
@ -115,6 +252,28 @@ const value = computed({
background-color: var(--vp-c-bg);
}
.color-input[value='currentColor'] {
.color-picker-popover {
z-index: 100;
box-sizing: border-box;
width: 256px;
min-height: 248px;
border: 1px solid var(--vp-c-divider);
border-radius: 16px;
background-color: var(--vp-c-bg-elv);
box-shadow: var(--vp-shadow-3);
outline: none;
}
.color-picker-popover-enter-active,
.color-picker-popover-leave-active {
transition:
opacity 0.15s ease,
transform 0.15s ease;
}
.color-picker-popover-enter-from,
.color-picker-popover-leave-to {
opacity: 0;
transform: translateY(-4px);
}
</style>

View file

@ -0,0 +1,281 @@
<script setup lang="ts">
import { computed, ref, shallowRef, watch } from 'vue';
import { ChromePicker, tinycolor } from 'vue-color';
import 'vue-color/style.css';
import { useEyeDropper } from '@vueuse/core';
import Icon from '@lucide/vue/src/Icon';
import { pipette } from '../../../data/iconNodes';
const props = defineProps<{
modelValue: string | null;
}>();
const emit = defineEmits<{
'update:modelValue': [value: string];
}>();
// Icons default to `currentColor`, which is the body text colour. Start from that colour when no
// custom colour is set, without its alpha so the alpha slider starts at 100%.
const defaultColor =
typeof document === 'undefined' ? '#000000' : getComputedStyle(document.body).color;
function parseColor(value: string | null) {
const color = tinycolor(value ?? '');
return color.isValid() ? color : tinycolor(defaultColor).setAlpha(1);
}
function toHex(color: tinycolor.Instance) {
return color.getAlpha() < 1 ? color.toHex8String() : color.toHexString();
}
/*
* Keep the picker's own full precision colour, and only emit hex. Feeding the rounded hex value
* back into the picker would make the hue and saturation knobs jump on low saturated colours.
*/
const color = shallowRef(parseColor(props.modelValue));
let lastEmittedValue: string | null = null;
watch(
() => props.modelValue,
(value) => {
if (value !== lastEmittedValue) {
color.value = parseColor(value);
}
},
);
const tinyColor = computed({
get: () => color.value,
set: (newColor: tinycolor.Instance) => {
color.value = newColor;
lastEmittedValue = toHex(newColor);
emit('update:modelValue', lastEmittedValue);
},
});
// Greys have no hue (it reads as 0), keep the last one so the hue knob doesn't turn red.
const hue = ref(0);
watch(
color,
(newColor) => {
const { h } = newColor.toHsl();
if (h !== 0 || hue.value === 0) {
hue.value = h;
}
},
{ immediate: true },
);
const knobColors = computed(() => ({
'--picker-color': color.value.clone().setAlpha(1).toRgbString(),
'--picker-color-alpha': color.value.toRgbString(),
'--picker-hue': `hsl(${hue.value} 100% 50%)`,
}));
const { isSupported: isEyeDropperSupported, open: openEyeDropper } = useEyeDropper();
async function pickColorFromScreen() {
try {
const result = await openEyeDropper();
if (result?.sRGBHex) {
tinyColor.value = tinycolor(result.sRGBHex);
}
} catch {
// The user cancelled picking with Escape
}
}
</script>
<template>
<div
class="color-picker-panel"
:class="{ 'has-eye-dropper': isEyeDropperSupported }"
:style="knobColors"
>
<ChromePicker
v-model:tinyColor="tinyColor"
disable-fields
/>
<button
v-if="isEyeDropperSupported"
type="button"
class="eye-dropper-button"
aria-label="Pick a color from the screen"
@click="pickColorFromScreen"
>
<Icon
:iconNode="pipette"
name="pipette"
:size="20"
aria-hidden="true"
/>
</button>
</div>
</template>
<style scoped>
.color-picker-panel {
--knob-size: 20px;
--bar-height: 12px;
--eye-dropper-size: 40px;
position: relative;
padding: 16px;
}
/* Reset the Chrome picker frame, the panel around it is the card */
.color-picker-panel :deep(.vc-chrome-picker) {
width: 100%;
box-sizing: border-box;
border-radius: 0;
box-shadow: none;
background: transparent;
font-family: inherit;
}
.color-picker-panel :deep(.body) {
padding: 16px 0 0;
background: transparent;
}
/* Saturation and brightness area. Not clipped, so the knob can reach the edges */
.color-picker-panel :deep(.saturation) {
padding-bottom: 68%;
overflow: visible;
border-radius: 10px;
}
.color-picker-panel :deep(.saturation .bg) {
border-radius: 10px;
}
.color-picker-panel :deep(.saturation .bg.black) {
box-shadow: inset 0 0 0 1px var(--vp-c-divider);
}
/* Eye dropper on the left, hue and alpha sliders on the right */
.color-picker-panel :deep(.controls) {
gap: 12px;
align-items: center;
}
.color-picker-panel :deep(.color-wrap) {
display: none;
}
.color-picker-panel.has-eye-dropper :deep(.controls) {
min-height: var(--eye-dropper-size);
}
/* Keeps the room for the eye dropper button, which is placed on top of it */
.color-picker-panel.has-eye-dropper :deep(.color-wrap) {
display: block;
flex-shrink: 0;
width: var(--eye-dropper-size);
height: var(--eye-dropper-size);
visibility: hidden;
}
.color-picker-panel :deep(.hue-wrap),
.color-picker-panel :deep(.alpha-wrap) {
height: var(--bar-height);
}
.color-picker-panel :deep(.hue-wrap) {
margin-bottom: 10px;
}
.color-picker-panel :deep(.vc-base-slider .background),
.color-picker-panel :deep(.vc-base-slider .gradient),
.color-picker-panel :deep(.vc-base-slider .vc-checkerboard) {
border-radius: calc(var(--bar-height) / 2);
}
.color-picker-panel :deep(.vc-base-slider .slider) {
outline: none;
}
/* Knobs, the same size and interaction as the customizer slider thumbs (RangeSlider.vue) */
.color-picker-panel :deep(.saturation .picker),
.color-picker-panel :deep(.vc-base-slider .picker) {
box-sizing: border-box;
width: var(--knob-size);
height: var(--knob-size);
margin: 0;
border: 3px solid #fff;
border-radius: 50%;
box-shadow: var(--vp-shadow-2);
cursor: pointer;
transition:
transform 0.2s ease,
box-shadow 0.2s ease;
}
.color-picker-panel :deep(.saturation .picker) {
--knob-translate: translate(-50%, -50%);
background: var(--picker-color);
transform: var(--knob-translate);
}
.color-picker-panel :deep(.vc-base-slider .picker) {
--knob-translate: translate(-50%, calc((var(--bar-height) - var(--knob-size)) / 2));
transform: var(--knob-translate);
}
.color-picker-panel :deep(.hue-wrap .picker) {
background: var(--picker-hue);
}
.color-picker-panel :deep(.alpha-wrap .picker) {
background: var(--picker-color-alpha);
}
.color-picker-panel :deep(.saturation .picker-wrap:hover .picker),
.color-picker-panel :deep(.saturation .picker-wrap:focus-visible .picker),
.color-picker-panel :deep(.vc-base-slider .slider:hover .picker),
.color-picker-panel :deep(.vc-base-slider .slider:focus-visible .picker) {
transform: var(--knob-translate) scale(1.1);
box-shadow:
var(--vp-shadow-2),
0 0 0 5px color-mix(in srgb, var(--vp-c-brand) 25%, transparent);
}
.color-picker-panel :deep(.saturation .vc-saturation-slider:active .picker),
.color-picker-panel :deep(.vc-base-slider .slider:active .picker) {
transform: var(--knob-translate) scale(1.2);
box-shadow:
var(--vp-shadow-2),
0 0 0 7px color-mix(in srgb, var(--vp-c-brand) 25%, transparent);
}
.eye-dropper-button {
position: absolute;
left: 16px;
bottom: 16px;
display: flex;
align-items: center;
justify-content: center;
width: var(--eye-dropper-size);
height: var(--eye-dropper-size);
border: 1px solid var(--vp-c-divider);
border-radius: 10px;
background: var(--vp-c-bg-alt);
color: var(--vp-c-text-2);
cursor: pointer;
transition:
color 0.25s,
border-color 0.25s,
box-shadow 0.25s;
}
.eye-dropper-button:hover,
.eye-dropper-button:focus-visible {
outline: none;
color: var(--vp-c-text-1);
border-color: var(--vp-c-brand);
box-shadow: 0 0 0 3px color-mix(in srgb, var(--vp-c-brand) 15%, transparent);
}
</style>

View file

@ -78,6 +78,7 @@
"react-dom": "19.3.1",
"sandpack-vue3": "3.1.12",
"vue": "^3.5.44",
"vue-color": "^3.3.3",
"vue-sonner": "^2.0.9"
}
}

View file

@ -212,6 +212,9 @@ importers:
vue:
specifier: ^3.5.44
version: 3.5.44(typescript@6.0.3)
vue-color:
specifier: ^3.3.3
version: 3.3.3(vue@3.5.44(typescript@6.0.3))
vue-sonner:
specifier: ^2.0.9
version: 2.0.9
@ -9996,6 +9999,9 @@ packages:
resolution: {integrity: sha512-MqIQVVkz+uGEHi3TsHx/czcxxCbRIL7sv5K5DnYw/tI+apY54IbPefV/cmgxp6LoJSEx/TqcHdLs/298afG5QQ==}
engines: {node: '>=6'}
material-colors@1.2.6:
resolution: {integrity: sha512-6qE4B9deFBIa9YSpOc9O0Sgc43zTeVYbgDT5veRKSlB2+ZuHNoVVxA1L/ckMUayV9Ay9y7Z/SZCLcGteW9i7bg==}
math-intrinsics@1.1.0:
resolution: {integrity: sha512-/IXtbwEk5HTPyEwyKX6hGkYXxM9nbj64B+ilVJnC/R6B0pH5G4V3b0pVbL7DBj4tkhBAppbQUlf6F6Xl9LHu1g==}
engines: {node: '>= 0.4'}
@ -13309,6 +13315,11 @@ packages:
vue-bundle-renderer@2.4.0:
resolution: {integrity: sha512-IxHopQZgzTGBiuGERrQrAS7Lr3dCv+qxvgirEgCUFGAD4gYNfiaGYzC1DDojeZmJAmehp9gG8+17PGuVP6Ab2Q==}
vue-color@3.3.3:
resolution: {integrity: sha512-FW/9JXFbCHfFEGv6SFUuK/SE+K61pHoL7lxJMQXcU+Zt7s36Ui1/tMDc3vzGXPrxxRBB+NSzFt+71nEaUJ29dQ==}
peerDependencies:
vue: '>=2.7.0 <4.0.0'
vue-component-type-helpers@3.3.13:
resolution: {integrity: sha512-02KCxSmKDhIITjKyJ4QT5csP6L0WoRborLqY/34a40+S9uvMvdNgMV0yVjO3p2Gkz3ZoPmFz/0JsGHacwJYTxw==}
@ -22836,6 +22847,8 @@ snapshots:
markdown-title@1.0.2: {}
material-colors@1.2.6: {}
math-intrinsics@1.1.0: {}
mdast-util-from-markdown@2.0.3(supports-color@10.2.2):
@ -27045,6 +27058,12 @@ snapshots:
dependencies:
ufo: 1.6.4
vue-color@3.3.3(vue@3.5.44(typescript@6.0.3)):
dependencies:
material-colors: 1.2.6
tinycolor2: 1.6.0
vue: 3.5.44(typescript@6.0.3)
vue-component-type-helpers@3.3.13: {}
vue-devtools-stub@0.1.0: {}