Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions packages/components/CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@
### Bug Fixes

- `ContentEditableControl`: Associate the label with the `contentEditable` field via `aria-labelledby` instead of an invalid `label[for]`, which triggered Chrome console errors ([#80344](https://github.com/WordPress/gutenberg/pull/80344)).
- `ColorPicker`: Keep the visual picker in native HSVA so gradient/controlled HSLA echoes no longer jitter the saturation pointer, and preserve the black-edge saturation coordinate without leaving white at a chromatic position ([#80205](https://github.com/WordPress/gutenberg/pull/80205)).

## 37.0.0 (2026-07-14)

Expand Down
42 changes: 23 additions & 19 deletions packages/components/src/color-picker/component.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -98,42 +98,40 @@ const UnconnectedColorPicker = (
// distinguish our own updates from external prop changes.
const lastProducedHexRef = useRef( safeColordColor.toHex() );

// While the user is dragging the visual picker, ignore color-prop sync
// so delayed/stale controlled echoes cannot overwrite internalHSLA mid-drag.
const isPickerInteractingRef = useRef( false );

// Sync internalHSLA when the color prop changes externally (e.g.
// parent passes a new color that wasn't produced by our onChange).
useEffect( () => {
const incomingHex = safeColordColor.toHex();
if ( isPickerInteractingRef.current ) {
return;
}

// If this hex matches what we last produced, it's our own
// update arriving back — skip the sync to avoid overwriting
// internalHSLA with lossy round-tripped values.
if ( incomingHex === lastProducedHexRef.current ) {
// Compare by color equality, not hex string — rgb()/rgba()
// round-trips can differ in string form for the same color.
if ( safeColordColor.isEqual( lastProducedHexRef.current ) ) {
return;
}

// Genuinely external change — sync internalHSLA.
lastProducedHexRef.current = incomingHex;
lastProducedHexRef.current = safeColordColor.toHex();
const externalHSLA = safeColordColor.toHsl();
setInternalHSLA( ( prev ) => mergeHSLA( externalHSLA, prev ) );
}, [ safeColordColor ] );

// Handler for HSL-aware components (Picker, HSL inputs) that
// provide raw HSLA values without information loss.
// Uses direct setColor (not debounced) to prevent race conditions
// where a stale debounced hex would overwrite newer internalHSLA.
// This is safe performance-wise because react-colorful internally
// throttles its onChange callbacks using requestAnimationFrame.

// Handler for HSL inputs (and the HSVA picker after it converts to HSLA).
// Apply the user's HSLA, then notify the parent only when the color
// actually changes. setColor must not run inside setInternalHSLA
// (state updaters must be pure). Uses direct setColor (not debounced)
// to avoid races with hex/RGB's debouncedSetColor.
const handleHSLAChange = useCallback(
( nextHSLA: HslaColor ) => {
// No mergeHSLA here — this handler receives the user's explicit
// choice from the picker or HSL inputs, with no lossy conversion.
setInternalHSLA( nextHSLA );
const previousHex = lastProducedHexRef.current;
const nextHex = colord( nextHSLA ).toHex();
// Only notify parent when the hex actually changes. This
// avoids firing onChange for H/S changes on achromatic
// colors (e.g. adjusting hue on pure white).
if ( nextHex !== previousHex ) {
if ( ! colord( nextHex ).isEqual( previousHex ) ) {
lastProducedHexRef.current = nextHex;
setColor( nextHex );
}
Expand Down Expand Up @@ -213,6 +211,12 @@ const UnconnectedColorPicker = (
onChange={ handleHSLAChange }
hsla={ internalHSLA }
enableAlpha={ enableAlpha }
onInteractionStart={ () => {
isPickerInteractingRef.current = true;
} }
onInteractionEnd={ () => {
isPickerInteractingRef.current = false;
} }
/>
<AuxiliaryColorArtefactWrapper>
<AuxiliaryColorArtefactHStackHeader justify="space-between">
Expand Down
165 changes: 144 additions & 21 deletions packages/components/src/color-picker/picker.tsx
Original file line number Diff line number Diff line change
@@ -1,42 +1,165 @@
/**
* External dependencies
*/
import { HslColorPicker, HslaColorPicker } from 'react-colorful';
import type { PointerEvent } from 'react';
import { useEffect, useRef, useState } from '@wordpress/element';
import { HsvColorPicker, HsvaColorPicker } from 'react-colorful';
import { colord } from 'colord';
import type { HslaColor, HsvaColor } from 'react-colorful';

/**
* Internal dependencies
*/
import type { PickerProps } from './types';

// Pointer capture fortifies drag gestures so that they continue to work
// while dragging outside the component over objects like iframes. If a
// newer version of react-colorful begins to employ pointer capture this
// will be redundant and should be removed.
const pointerCaptureProps = {
onPointerDown( { currentTarget, pointerId }: React.PointerEvent ) {
currentTarget.setPointerCapture( pointerId );
},
onPointerUp( { currentTarget, pointerId }: React.PointerEvent ) {
currentTarget.releasePointerCapture( pointerId );
},
};
function toHsva( hsla: PickerProps[ 'hsla' ] ): HsvaColor {
return {
...colord( hsla ).toHsv(),
// HSL and HSV share the hue angle. Color conversion collapses achromatic
// hue to 0, but HSLA retains the user's latent hue.
h: hsla.h,
a: hsla.a,
};
}

function isSameHsla( a: HslaColor, b: HslaColor ): boolean {
return a.h === b.h && a.s === b.s && a.l === b.l && a.a === b.a;
}

/**
* Convert parent HSLA into HSVA for prop sync.
*
* At black, RGB round-trips collapse saturation to 0. Preserve the native
* HSVA saturation coordinate unless the HSL saturation channel itself
* changed (sibling hue/alpha edits must not snap the pointer).
*
* At white, only `v: 100, s: 0` is visually white — preserving a prior
* chromatic saturation would leave the pointer at the top-right and make
* the first keyboard step jump from white to a saturated color.
*/
function toHsvaFromHsla(
hsla: HslaColor,
prevHsva: HsvaColor,
prevHsla: HslaColor | null
): HsvaColor {
const converted = toHsva( hsla );

// White and chromatic colors use the converted value as-is.
if ( hsla.l !== 0 ) {
return converted;
}

const saturationChanged = prevHsla !== null && prevHsla.s !== hsla.s;

return {
h: hsla.h,
s: saturationChanged ? hsla.s : prevHsva.s,
v: 0,
a: hsla.a,
};
}

/**
* Visual color surface.
*
* Uses HSVA (react-colorful's native model) and keeps that value in local
* state so HSLA↔hex round-trips cannot move the pointer
* Parent ColorPicker still speaks HSLA for
* inputs and controlled value sync; conversion happens only at the boundary.
*
* Prop sync from parent HSLA is suppressed for:
* - pointer/touch drags (interaction flag), and
* - any picker-originated update including keyboard (HSLA origin token).
*
* Achromatic HSL sibling edits (hue/alpha while at black) preserve native
* HSVA saturation unless saturation itself changed. White always syncs to
* the converted `s: 0` visual coordinate.
*/
export const Picker = ( {
hsla,
enableAlpha,
onChange,
onInteractionStart,
onInteractionEnd,
}: PickerProps ) => {
const [ hsva, setHsva ] = useState< HsvaColor >( () => toHsva( hsla ) );
// Last HSLA emitted by this picker — skip echoing it back into HSVA.
const pickerOriginHslaRef = useRef< HslaColor | null >( null );
// Previous parent HSLA — detect which channel changed on achromatic sync.
const prevHslaRef = useRef< HslaColor >( hsla );
// Pointer/touch drag: never sync from HSLA mid-gesture (origin match alone
// can fail across rapid frames when parent gradient state re-renders).
const isPointerInteractingRef = useRef( false );

useEffect( () => {
if ( isPointerInteractingRef.current ) {
// Keep prevHsla in lockstep with parent updates during the gesture
// so a post-drag HSL sibling edit is not compared against pre-drag
// HSLA and mistaken for a saturation change.
prevHslaRef.current = hsla;
return;
}
if (
pickerOriginHslaRef.current &&
isSameHsla( pickerOriginHslaRef.current, hsla )
) {
prevHslaRef.current = hsla;
return;
}
pickerOriginHslaRef.current = null;
setHsva( ( prev ) =>
toHsvaFromHsla( hsla, prev, prevHslaRef.current )
);
prevHslaRef.current = hsla;
}, [ hsla ] );

// Inline handlers so refs are not passed into a helper during render
// (react-hooks/refs). Pointer capture also keeps drag working over iframes.
const pointerCaptureProps = {
onPointerDown( { currentTarget, pointerId }: PointerEvent ) {
isPointerInteractingRef.current = true;
onInteractionStart?.();
currentTarget.setPointerCapture( pointerId );
},
onPointerUp( { currentTarget, pointerId }: PointerEvent ) {
currentTarget.releasePointerCapture( pointerId );
isPointerInteractingRef.current = false;
onInteractionEnd?.();
},
onPointerCancel( { currentTarget, pointerId }: PointerEvent ) {
currentTarget.releasePointerCapture( pointerId );
isPointerInteractingRef.current = false;
onInteractionEnd?.();
},
};

const handleChange = ( next: HsvaColor ) => {
setHsva( next );
const nextHsla: HslaColor = { ...colord( next ).toHsl(), a: next.a };
pickerOriginHslaRef.current = nextHsla;
onChange( nextHsla );
};

export const Picker = ( { hsla, enableAlpha, onChange }: PickerProps ) => {
if ( enableAlpha ) {
return (
<HslaColorPicker
color={ hsla }
onChange={ onChange }
<HsvaColorPicker
color={ hsva }
onChange={ handleChange }
{ ...pointerCaptureProps }
/>
);
}

// HsvColorPicker's equality checks enumerate own keys — never pass `a`,
// or every parent re-render looks like an external color change and the
// pointer jitters while dragging.
const hsv = { h: hsva.h, s: hsva.s, v: hsva.v };

return (
<HslColorPicker
color={ hsla }
onChange={ ( nextColor ) => {
onChange( { ...nextColor, a: hsla.a } );
<HsvColorPicker
color={ hsv }
onChange={ ( next ) => {
handleChange( { ...next, a: hsva.a } );
} }
{ ...pointerCaptureProps }
/>
Expand Down
Loading
Loading