본문으로 바로가기 본문 바로가기
WIKI 기술 지식 베이스

useInputColor - 색상 선택 상태와 채널 슬라이더를 관리하는 훅

원문 보기 위키 갱신

useInputColor는 색상 선택 상태, 2D 영역 상호작용, 채널 슬라이더, 그리고 접근 가능한 색상 입력 동작을 관리하는 헤드리스 훅이에요. 2D 그라디언트 영역과 채널 슬라이더, 텍스트 입력, EyeDropper 버튼을 갖춘 완전한 커스텀 컬러 피커를 만들 때 필요한 props를 모두 돌려줘요.

출처: 문서

본문

사용법 (Usage)

import { parseColor, useInputColor } from '@primereact/headless/inputcolor';
const inputColor = useInputColor({ defaultValue: parseColor('#ff0000') });

<div {...inputColor.rootProps}>
    <div {...inputColor.areaProps}>
        <div {...inputColor.areaHandleProps}></div>
    </div>
    <div {...inputColor.swatchProps}></div>
    <button {...inputColor.eyeDropperProps}></button>
    <input {...inputColor.getInputProps({ channel: 'hex' })} />
</div>;

useInputColor는 2D 그라디언트 영역, 채널 슬라이더, 텍스트 입력, 그리고 EyeDropper 버튼을 갖춘 완전한 컬러 피커를 관리해요. 컴포넌트 기반 API는 Primitive 문서를 확인하세요.

기능 (Features)

  • 완전한 피커 표면 (Complete picker surface), root, area, areaHandle, swatch, eyeDropper, sliderHandle을 위한 펼쳐 쓸 준비가 된 props를 돌려줘요
  • 동적 채널 props (Dynamic channel props), getSliderProps와 getInputProps가 어떤 개별 색상 채널이든 props를 만들어 줘요
  • 2D 영역 상호작용 (2D area interaction), 부드러운 드래그를 위한 포인터 캡처와 채도/밝기 전반의 화살표 키 내비게이션을 지원해요
  • 여러 색상 공간 (Multiple color spaces), hsba, hsla, rgba, oklcha 형식을 공유 ColorInstance 값 타입으로 지원해요
  • CSS 커스텀 속성 (CSS custom properties), 스타일 객체가 그라디언트와 핸들 위치를 노출해 렌더링을 온전히 CSS로 구동할 수 있어요
  • 색상 파싱 (Color parsing), 함께 제공되는 parseColor 유틸리티가 hex 문자열로 ColorInstance 값을 만들어요

콜백 다루기 (Working with callbacks)

제어되는 색상 (Controlled color)

value와 onValueChange를 넘기면 선택된 색상을 외부에서 소유할 수 있어요. 폼 상태나 원격 데이터와 동기화할 때 필요해요.

const [color, setColor] = React.useState(parseColor('#276def'));

useInputColor({
    value: color,
    onValueChange: (e) => setColor(e.value)
});

상호작용 종료 시 커밋 (Commit on interaction end)

onValueChangeEnd는 포인터 상호작용이 멈출 때(영역 해제, 슬라이더 드롭, 입력 커밋) 발생해요. 서버에 저장하는 것 같은 무거운 작업에 써요.

useInputColor({
    defaultValue: parseColor('#276def'),
    onValueChangeEnd: (e) => saveColor(e.color)
});

useSlider로 채널 슬라이더 만들기 (Channel sliders via useSlider)

getSliderProps는 useSlider에 넘길 수 있는 옵션을 돌려줘 어떤 채널이든 슬라이더를 그릴 수 있어요. 영역 옆에 슬라이더를 세로로 배치하려면 orientation: 'vertical'을 설정하세요.

const { style, ...sliderOptions } = inputColor.getSliderProps({ channel: 'hue' });
const slider = useSlider(sliderOptions);

채널 입력 (Channel inputs)

getInputProps는 특정 채널에 묶인 텍스트 또는 숫자 입력을 위한 props를 만들어 줘요. RGB 필드 옆에 hex 입력을 둘 때 유용해요.

<input {...inputColor.getInputProps({ channel: 'hex' })} />
<input {...inputColor.getInputProps({ channel: 'red' })} />
<input {...inputColor.getInputProps({ channel: 'alpha' })} />

EyeDropper 통합 (EyeDropper integration)

버튼에 eyeDropperProps를 펼쳐 쓰면 네이티브 브라우저 EyeDropper API가 열리고, 선택된 색상은 자동으로 커밋돼요.

<button {...inputColor.eyeDropperProps}>Pick color</button>

실시간 상태 읽기 (Reading live state)

state.value는 현재 ColorInstance를, state.isAreaDragging은 드래그 중 UI를 렌더링하게 해 줘요.

<span>{inputColor.state.value.toString('hex')}</span>;
{
    inputColor.state.isAreaDragging && <span>Dragging...</span>;
}

데이터 속성으로 스타일링 (Styling with data attributes)

areaProps.style, getSliderProps().style, swatchProps.style는 그라디언트와 핸들 위치를 위한 CSS 커스텀 속성을 노출해요.

Variable Source Description
--area-background areaProps.style Solid hue background of the area
--area-gradient areaProps.style Combined saturation/brightness gradient overlay
--handle-background areaProps.style Current color for the area handle
--handle-position-top areaProps.style Vertical position of the area handle
--handle-position-left areaProps.style Horizontal position of the area handle
--slider-background getSliderProps().style Channel gradient for the slider track
--slider-handle-background getSliderProps().style Current channel color for the slider handle
--swatch-background swatchProps.style Current color for the swatch

data-disabled나 data-dragging 같은 상태 기반 속성은 관련 파트에 방출돼요.

[data-scope='inputcolor'][data-part='area'] {
    background: var(--area-background);
}

[data-part='area-handle'] {
    top: var(--px-handle-position-top);
    left: var(--px-handle-position-left);
    background: var(--px-handle-background);
}

.slider-track {
    background: var(--px-slider-background);
}

.slider-handle {
    background: var(--px-slider-handle-background);
}

[data-part='swatch'] {
    background: var(--px-swatch-background);
}

[data-disabled] {
    opacity: 0.5;
    pointer-events: none;
}

[data-dragging] {
    cursor: grabbing;
}

API

useInputColor

접근성 (Accessibility)

Space로 피커를 열고, 화살표 키로 색상 그리드를 이동하며, Enter로 선택을 확인해요. 전체 WAI-ARIA 준수 상세는 Primitive 문서를 확인하세요.

더 알아보기 (Learn more)