탐색

v2.1.0
폼

색상 선택기

영역에서 명도와 채도를 고르고 색상과 불투명도를 조절하거나, 색을 직접 입력할 수 있습니다.

이 페이지의 내용

색상 선택기는 어떤 색이든 고를 수 있습니다. 명도와 채도는 하나의 손잡이로 영역 위에서 고르고, 색상(hue)과 불투명도는 두 개의 슬라이더로 고르며, 색 자체는 hex, rgb(), oklch() 형식의 텍스트로 직접 입력할 수 있습니다. 테마의 모든 색이 작성되는 색 공간인 OKLCH에서 색을 고르므로, 명도를 한 단계 바꾸면 어떤 색상에서든 같은 정도로 바뀐 것처럼 보입니다. 영역은 표면에 박혀 있는 그림이고, 손잡이는 진주빛 링 안에 담긴 현재 색이며, 트랙은 네이티브 range 입력 요소입니다. color-picker 동작은 이 구성 요소들이 서로 맞물려 움직이도록 합니다.

색상 선택기

<div class="sheet p-md">  <div class="color-picker" style="--color-picker-lightness: .62; --color-picker-chroma: .19; --color-picker-hue: 260">    <div class="color-picker-area">      <div class="color-picker-thumb" role="slider" tabindex="0" aria-label="Lightness and chroma" aria-valuemin="0" aria-valuemax="100" aria-valuenow="62" aria-valuetext="Lightness 62%, chroma 0.19"></div>    </div>    <span class="swatch swatch-lg color-picker-swatch"></span>    <input type="range" class="slider color-picker-hue" min="0" max="360" value="260" aria-label="Hue">    <input type="range" class="slider color-picker-alpha" min="0" max="100" value="100" aria-label="Opacity">    <div class="color-picker-fields">      <select class="select select-sm color-picker-format" aria-label="Format">        <option value="hex">Hex</option>        <option value="rgb">RGB</option>        <option value="oklch" selected>OKLCH</option>      </select>      <input class="input input-sm color-picker-text" name="accent" value="oklch(62% 0.19 260)" aria-label="Accent color" spellcheck="false" autocomplete="off">    </div>  </div></div><script type="module">  import { attach } from '@master/ui/behaviors'  attach()</script>
import { useEffect, useRef } from 'react'import { attach } from '@master/ui/behaviors'export function Example() {  const root = useRef<HTMLDivElement>(null)  useEffect(() => attach(root.current!), [])  return (    <div ref={root} className="sheet p-md">      <div className="color-picker" style={{ '--color-picker-lightness': '.62', '--color-picker-chroma': '.19', '--color-picker-hue': '260' } as React.CSSProperties}>        <div className="color-picker-area">          <div className="color-picker-thumb" role="slider" tabIndex={0} aria-label="Lightness and chroma" aria-valuemin={0} aria-valuemax={100} aria-valuenow={62} aria-valuetext="Lightness 62%, chroma 0.19"></div>        </div>        <span className="swatch swatch-lg color-picker-swatch"></span>        <input type="range" className="slider color-picker-hue" min="0" max="360" defaultValue="260" aria-label="Hue" />        <input type="range" className="slider color-picker-alpha" min="0" max="100" defaultValue="100" aria-label="Opacity" />        <div className="color-picker-fields">          <select className="select select-sm color-picker-format" aria-label="Format" defaultValue="oklch">            <option value="hex">Hex</option>            <option value="rgb">RGB</option>            <option value="oklch">OKLCH</option>          </select>          <input className="input input-sm color-picker-text" name="accent" defaultValue="oklch(62% 0.19 260)" aria-label="Accent color" spellCheck="false" autoComplete="off" />        </div>      </div>    </div>  )}
<script>  import { attach } from '@master/ui/behaviors'</script><div class="sheet p-md" {@attach attach}>  <div class="color-picker" style="--color-picker-lightness: .62; --color-picker-chroma: .19; --color-picker-hue: 260">    <div class="color-picker-area">      <div class="color-picker-thumb" role="slider" tabindex="0" aria-label="Lightness and chroma" aria-valuemin="0" aria-valuemax="100" aria-valuenow="62" aria-valuetext="Lightness 62%, chroma 0.19"></div>    </div>    <span class="swatch swatch-lg color-picker-swatch"></span>    <input type="range" class="slider color-picker-hue" min="0" max="360" value="260" aria-label="Hue">    <input type="range" class="slider color-picker-alpha" min="0" max="100" value="100" aria-label="Opacity">    <div class="color-picker-fields">      <select class="select select-sm color-picker-format" aria-label="Format">        <option value="hex">Hex</option>        <option value="rgb">RGB</option>        <option value="oklch" selected>OKLCH</option>      </select>      <input class="input input-sm color-picker-text" name="accent" value="oklch(62% 0.19 260)" aria-label="Accent color" spellcheck="false" autocomplete="off">    </div>  </div></div>
<script setup>import { onMounted, onUnmounted, ref } from 'vue'import { attach } from '@master/ui/behaviors'const root = ref(null)let detachonMounted(() => { detach = attach(root.value) })onUnmounted(() => detach?.())</script><template>  <div ref="root" class="sheet p-md">    <div class="color-picker" style="--color-picker-lightness: .62; --color-picker-chroma: .19; --color-picker-hue: 260">      <div class="color-picker-area">        <div class="color-picker-thumb" role="slider" tabindex="0" aria-label="Lightness and chroma" aria-valuemin="0" aria-valuemax="100" aria-valuenow="62" aria-valuetext="Lightness 62%, chroma 0.19"></div>      </div>      <span class="swatch swatch-lg color-picker-swatch"></span>      <input type="range" class="slider color-picker-hue" min="0" max="360" value="260" aria-label="Hue">      <input type="range" class="slider color-picker-alpha" min="0" max="100" value="100" aria-label="Opacity">      <div class="color-picker-fields">        <select class="select select-sm color-picker-format" aria-label="Format">          <option value="hex">Hex</option>          <option value="rgb">RGB</option>          <option value="oklch" selected>OKLCH</option>        </select>        <input class="input input-sm color-picker-text" name="accent" value="oklch(62% 0.19 260)" aria-label="Accent color" spellcheck="false" autocomplete="off">      </div>    </div>  </div></template>
영역 위에서 드래그하거나 손잡이에서 방향키를 사용하거나, 색상 슬라이더를 움직이거나, 형식을 바꾸거나 #e5484d 같은 색을 입력해 보세요.

#버튼으로 열기

대개 색은 여러 설정 중 하나이므로, 선택기는 그 색을 보여 주는 버튼에서 열립니다. 루트 안에 버튼과 color-picker-popover가 있는 팝오버를 두세요. 팝오버가 세로 열이 되며, 버튼과 팝오버 모두 색을 담고 있는 루트 안에 있으므로 버튼 안의 color-picker-swatch 견본이 선택기가 닫혀 있는 동안에도 색을 보여 줍니다. 팝오버를 열고, 배치하고, 닫는 일은 브라우저가 처리하며, 동작은 동일합니다.

버튼으로 열기

<div class="color-picker" style="--color-picker-lightness: .6256; --color-picker-chroma: .1933; --color-picker-hue: 23.03">  <button type="button" class="btn" popovertarget="brand-picker">    <span class="swatch swatch-sm color-picker-swatch"></span> Brand color  </button>  <div id="brand-picker" popover class="popover color-picker-popover">    <div class="color-picker-area">      <div class="color-picker-thumb" role="slider" tabindex="0" aria-label="Lightness and chroma" aria-valuemin="0" aria-valuemax="100" aria-valuenow="62.6" aria-valuetext="Lightness 62.6%, chroma 0.193"></div>    </div>    <span class="swatch swatch-lg color-picker-swatch"></span>    <input type="range" class="slider color-picker-hue" min="0" max="360" value="23" aria-label="Hue">    <input type="range" class="slider color-picker-alpha" min="0" max="100" value="100" aria-label="Opacity">    <div class="color-picker-fields">      <select class="select select-sm color-picker-format" aria-label="Format">        <option value="hex" selected>Hex</option>        <option value="rgb">RGB</option>        <option value="oklch">OKLCH</option>      </select>      <input class="input input-sm color-picker-text" name="brand" value="#e5484d" aria-label="Brand color" spellcheck="false" autocomplete="off">    </div>  </div></div><script type="module">  import { attach } from '@master/ui/behaviors'  attach()</script>
import { useEffect, useRef } from 'react'import { attach } from '@master/ui/behaviors'export function Example() {  const root = useRef<HTMLDivElement>(null)  useEffect(() => attach(root.current!), [])  return (    <div ref={root} className="color-picker" style={{ '--color-picker-lightness': '.6256', '--color-picker-chroma': '.1933', '--color-picker-hue': '23.03' } as React.CSSProperties}>      <button type="button" className="btn" popoverTarget="brand-picker">        <span className="swatch swatch-sm color-picker-swatch"></span> Brand color      </button>      <div id="brand-picker" popover="" className="popover color-picker-popover">        <div className="color-picker-area">          <div className="color-picker-thumb" role="slider" tabIndex={0} aria-label="Lightness and chroma" aria-valuemin={0} aria-valuemax={100} aria-valuenow={62.6} aria-valuetext="Lightness 62.6%, chroma 0.193"></div>        </div>        <span className="swatch swatch-lg color-picker-swatch"></span>        <input type="range" className="slider color-picker-hue" min="0" max="360" defaultValue="23" aria-label="Hue" />        <input type="range" className="slider color-picker-alpha" min="0" max="100" defaultValue="100" aria-label="Opacity" />        <div className="color-picker-fields">          <select className="select select-sm color-picker-format" aria-label="Format" defaultValue="hex">            <option value="hex">Hex</option>            <option value="rgb">RGB</option>            <option value="oklch">OKLCH</option>          </select>          <input className="input input-sm color-picker-text" name="brand" defaultValue="#e5484d" aria-label="Brand color" spellCheck="false" autoComplete="off" />        </div>      </div>    </div>  )}
<script>  import { attach } from '@master/ui/behaviors'</script><div class="color-picker" style="--color-picker-lightness: .6256; --color-picker-chroma: .1933; --color-picker-hue: 23.03" {@attach attach}>  <button type="button" class="btn" popovertarget="brand-picker">    <span class="swatch swatch-sm color-picker-swatch"></span> Brand color  </button>  <div id="brand-picker" popover class="popover color-picker-popover">    <div class="color-picker-area">      <div class="color-picker-thumb" role="slider" tabindex="0" aria-label="Lightness and chroma" aria-valuemin="0" aria-valuemax="100" aria-valuenow="62.6" aria-valuetext="Lightness 62.6%, chroma 0.193"></div>    </div>    <span class="swatch swatch-lg color-picker-swatch"></span>    <input type="range" class="slider color-picker-hue" min="0" max="360" value="23" aria-label="Hue">    <input type="range" class="slider color-picker-alpha" min="0" max="100" value="100" aria-label="Opacity">    <div class="color-picker-fields">      <select class="select select-sm color-picker-format" aria-label="Format">        <option value="hex" selected>Hex</option>        <option value="rgb">RGB</option>        <option value="oklch">OKLCH</option>      </select>      <input class="input input-sm color-picker-text" name="brand" value="#e5484d" aria-label="Brand color" spellcheck="false" autocomplete="off">    </div>  </div></div>
<script setup>import { onMounted, onUnmounted, ref } from 'vue'import { attach } from '@master/ui/behaviors'const root = ref(null)let detachonMounted(() => { detach = attach(root.value) })onUnmounted(() => detach?.())</script><template>  <div ref="root" class="color-picker" style="--color-picker-lightness: .6256; --color-picker-chroma: .1933; --color-picker-hue: 23.03">    <button type="button" class="btn" popovertarget="brand-picker">      <span class="swatch swatch-sm color-picker-swatch"></span> Brand color    </button>    <div id="brand-picker" popover class="popover color-picker-popover">      <div class="color-picker-area">        <div class="color-picker-thumb" role="slider" tabindex="0" aria-label="Lightness and chroma" aria-valuemin="0" aria-valuemax="100" aria-valuenow="62.6" aria-valuetext="Lightness 62.6%, chroma 0.193"></div>      </div>      <span class="swatch swatch-lg color-picker-swatch"></span>      <input type="range" class="slider color-picker-hue" min="0" max="360" value="23" aria-label="Hue">      <input type="range" class="slider color-picker-alpha" min="0" max="100" value="100" aria-label="Opacity">      <div class="color-picker-fields">        <select class="select select-sm color-picker-format" aria-label="Format">          <option value="hex" selected>Hex</option>          <option value="rgb">RGB</option>          <option value="oklch">OKLCH</option>        </select>        <input class="input input-sm color-picker-text" name="brand" value="#e5484d" aria-label="Brand color" spellcheck="false" autocomplete="off">      </div>    </div>  </div></template>
선택기를 열고 색을 바꿔 보세요. 버튼 안의 견본이 그 색을 따라갑니다.

인쇄되는 브랜드 색처럼 불투명해야 하는 색이라면 color-picker-alpha를 빼세요. 그러면 견본이 색상 슬라이더 옆에만 놓이고, 불투명도를 포함해 입력한 색은 불투명도 없이 적용됩니다. 견본까지 빼면 트랙이 전체 너비를 차지합니다.

#OKLCH를 사용하는 이유

영역을 대부분의 선택기가 그리는 사각형인 포화도(saturation)와 밝기(value)로 구성할 수도 있습니다. 이 사각형은 sRGB에 흰색과 검은색을 섞은 것에 불과하므로 그리기 쉽습니다. 하지만 팔레트를 고르기에는 좋지 않은 영역입니다. 같은 밝기 값이 어두운 파란색이 되기도 하고 눈부신 노란색이 되기도 하며, 같은 포화도에서 색상을 옮기면 색이 밝아 보이는 정도가 달라집니다. OKLCH는 같은 간격이 같게 보이도록 설계되었습니다. 그래서 테마는 색을 OKLCH로 작성하며, 테마에 쓸 색을 고르는 선택기도 OKLCH로 골라야 합니다.

  • 명도(lightness) 는 영역의 위쪽 100%에서 아래쪽 0까지 이어지며, 어떤 색상에서든 같은 명도입니다.
  • 채도(chroma) 는 영역의 시작 쪽에서 채도가 없는 회색으로 시작해 끝쪽에서 Display P3가 표현할 수 있는 한계인 .37까지 이어집니다. 색이 항상 채도가 요구하는 만큼 선명하지는 않습니다. 화면은 표시할 수 있는 가장 가까운 색을 보여 주며, 영역과 손잡이도 같은 규칙에 따라 그렇게 합니다.
  • 색상(hue) 은 별도의 슬라이더에서 원을 따라 한 바퀴 돌며, 모든 색상을 구별할 수 있도록 하나의 명도와 채도로 그려집니다.

값은 셀렉트가 가리키는 형식으로 작성됩니다. oklch()는 보관된 값 그대로 작성됩니다. hex와 rgb()는 sRGB만 담을 수 있으므로, sRGB를 벗어난 색은 CSS Color 4가 색을 화면에 맞추는 방식으로 맞춥니다. 즉 명도와 색상은 그대로 둔 채, sRGB로 작성할 수 있는 색과의 차이가 겨우 알아챌 수 있는 수준 이내가 될 때까지 채도를 줄입니다. 형식을 바꿔도 보관된 색은 바뀌지 않으므로, 색을 hex에서 oklch()로 바꿨다가 다시 hex로 돌려도 같은 hex 값이 됩니다.

그레이디언트는 한 축으로만 이어지므로 영역은 행 단위로 그려집니다. 각 행은 자기 명도에서 회색부터 .37까지 이어지는 그레이디언트로, 그 선 위에서는 정확합니다. 그리고 행과 행 사이 중간 지점의 행들이 한 행에서 다음 행으로 흐려지는 마스크를 통해 다른 행들 위에 겹쳐집니다. 색은 동작이 게시하는 색상 값의 함수인 테마의 믹스인이므로, 컴포넌트는 자체 색을 하나도 작성하지 않습니다.

#동작

colorPicker는 color-picker 클래스가 있는 루트 요소를 받아, 연결한 동작을 해제하는 함수를 반환합니다.

app.js
import { colorPicker } from '@master/ui/behaviors/color-picker.js'const accent = colorPicker(document.querySelector('.color-picker'))accent.value // 'oklch(62% 0.19 260)'accent.value = '#e5484d' // choose a color, and hex as its format
  • 색은 세 가지 형식 중 어느 것으로든 작성된 텍스트 필드의 값에서 시작하며, 형식도 그 값을 따릅니다. 동작은 색을 루트에 --color-picker-lightness, --color-picker-chroma, --color-picker-hue, --color-picker-alpha의 네 숫자로 작성하며, 이 숫자들이 손잡이의 위치를 정하고 영역, 트랙, 견본을 칠합니다. 스크립트가 실행되기 전에도 영역이 올바르게 보이도록 첫 색의 숫자를 루트의 style에도 작성하세요.
  • 영역. 누르면 손잡이가 포인터 아래로 오고 포커스를 받습니다. 드래그하면 손잡이가 포인터를 따라갑니다. 포인터가 영역 밖으로 나가도 드래그가 계속되며, 선택되는 색은 영역 가장자리의 값으로 제한됩니다. 키 조작은 아래 표에 있습니다.
  • 텍스트. 입력한 내용이 색이 되는 즉시 그 색을 적용하며, 텍스트는 입력한 그대로 둡니다. Enter 키를 누르거나 필드를 벗어나 입력을 확정하면 선택한 형식으로 색을 다시 작성합니다. 색이 아닌 텍스트는 이전 값으로 되돌립니다.
  • 이벤트. 손잡이는 색이 움직이는 동안 input을 발생시키고, 드래그가 끝나거나 키로 색을 옮겼을 때 change를 발생시킵니다. 슬라이더, 셀렉트, 텍스트 필드는 각자의 이벤트를 발생시킵니다. 루트에서 이벤트를 수신할 때는 이벤트를 발생시킨 요소에서 새 value를 읽습니다.
  • 손잡이의 문구. 손잡이의 aria-valuetext는 Lightness 62%, chroma 0.19라고 말합니다. 페이지 언어로 말하게 하려면 valueText: (lightness, chroma) => …를 전달하세요.

동작을 연결하지 않으면 영역은 마크업에 작성된 색을 보여 주며, 슬라이더, 셀렉트, 텍스트 필드는 서로를 따라 움직이지 않는 일반 컨트롤입니다.

#키보드

키동작
ArrowUp, ArrowDown영역의 손잡이에서 명도를 1%씩 높이거나 낮춰 색을 밝게 또는 어둡게 합니다.
ArrowRight, ArrowLeft영역의 손잡이에서 채도를 .005씩 높이면 인라인 끝 쪽으로, 낮추면 인라인 시작 쪽으로 이동합니다. 오른쪽에서 왼쪽으로 쓰는 레이아웃에서는 좌우 방향이 반대입니다.
Shift with an arrow영역의 손잡이에서 10배 단위로 조절합니다. 명도는 10%, 채도는 .05씩 바뀝니다.
PageUp, PageDown영역의 손잡이에서 명도를 10%씩 높이거나 낮춰 색을 밝게 또는 어둡게 합니다.
Home, End영역의 손잡이에서 채도를 0(회색)으로 만들거나 영역의 끝으로 옮깁니다.
ArrowLeft, ArrowRight, ArrowUp, ArrowDown, Home, End, PageUp, PageDown색상과 불투명도 슬라이더에서는 네이티브 range 입력과 같이 동작합니다.
Enter텍스트 필드에서는 입력한 값을 적용합니다. 필드는 선택한 형식으로 다시 기록되며, 색이 아니면 이전 값으로 되돌아갑니다.

#접근성

  • 영역의 손잡이는 하나의 슬라이더입니다. ArrowUp과 ArrowDown 키로 명도를 움직이므로 손잡이의 값은 명도이며, aria-valuetext가 명도와 채도를 함께 알려 주므로 어느 쪽이 움직이든 스크린 리더는 둘 다 읽어 줍니다. "명도와 채도"처럼 무엇을 고르는지를 이름으로 지정하세요.
  • 텍스트 필드는 영역을 쓰지 않고 정확한 색을 지정하는 방법이며, 텍스트 필드에는 "브랜드 색상"처럼 어떤 색을 지정하는지 나타내는 이름을 붙입니다. 폼을 제출하면 텍스트 필드의 값이 name에 지정한 이름으로 전송됩니다.
  • 색상 슬라이더, 불투명도 슬라이더, 형식 셀렉트에 이름을 지정하세요. 이들의 키 조작은 플랫폼 기본 동작을 따릅니다.
  • 강제 색상 모드에서도 영역의 색은 유지됩니다. 사용자가 보러 온 것이 바로 그 색이기 때문입니다. 영역의 테두리와 손잡이의 포커스 표시는 시스템 색으로 그려집니다.

#React, Svelte, Vue

color-picker 컴포넌트는 루트의 네 숫자를 포함해 첫 값을 첫 렌더링에 그려 넣고 동작을 연결하며, 그 뒤로는 동작이 모든 구성 요소를 움직입니다. 값은 선택한 형식으로 된 색 텍스트이며, 바뀔 때마다 외부로 전달됩니다. 페이지의 버튼에서 선택기를 열려면 trigger(Svelte에서는 snippet, Vue에서는 slot)를 지정하세요. npx master-ui add color-picker 명령을 실행해 프로젝트에 복사하세요. 컴포넌트의 구성과 사용 방법은 React, Svelte, Vue에서 확인할 수 있습니다.

ui/color-picker.tsx
'use client'import { Fragment, useId, useState, type ComponentProps, type CSSProperties, type ElementType, type ReactNode } from 'react'import { colorPicker, colorPickerState } from '@master/ui/behaviors/color-picker.js'import { useBehavior } from './use-behavior'export interface ColorPickerLabels {  /** The field's thumb. `Lightness and chroma` by default. */  field?: string  /** `Hue` by default. */  hue?: string  /** `Opacity` by default. */  alpha?: string  /** The select of the format. `Format` by default. */  format?: string}export interface ColorPickerProps extends Omit<ComponentProps<'div'>, 'defaultValue' | 'children' | 'ref'> {  /** The color, in hex, rgb() or oklch(); the format it is written in is the one the picker writes. */  value?: string  defaultValue?: string  onValueChange?: (value: string) => void  /** What the color is: the name of the text field. */  label: string  /** The name the text field submits with a form. */  name?: string  /** An opacity slider. Without it the color is opaque. True by default. */  alpha?: boolean  disabled?: boolean  /**   * The button that opens the picker in a popover: spread what it is given on a button of your own, and put a   * `swatch color-picker-swatch` in it to show the color. Leave it out and the picker stands inline.   */  trigger?: (attributes: { popoverTarget: string }) => ReactNode  /** What the controls are called, in the page's words. */  labels?: ColorPickerLabels  /** What the field's thumb says it holds, from the lightness in percent and the chroma. */  valueText?: (lightness: number, chroma: number) => string}/** * A color picker. The behavior holds the color and moves every part; this component draws the first value * into the first render and passes the value in and out. */export function ColorPicker({ value, defaultValue, onValueChange, label, name, alpha = true, disabled, trigger, labels = {}, valueText, className, style, ...root }: ColorPickerProps) {  const id = useId()  // The first value is drawn into the first render; after that the behavior writes every part.  const [first] = useState(() => colorPickerState(value ?? defaultValue ?? '', { valueText, opaque: !alpha }) ?? colorPickerState('#000000')!)  const ref = useBehavior(colorPicker, { valueText }, { value, defaultValue, onValueChange })  // Opened from a button, the parts stand in a popover beside it; inline, they stand in the root.  const Column = (trigger ? 'div' : Fragment) as ElementType  const column = trigger ? { id: `${id}popover`, popover: 'auto', className: 'popover color-picker-popover' } : {}  return (    <div className={className ? `color-picker ${className}` : 'color-picker'} ref={ref} style={{ ...first.properties, ...style } as CSSProperties} {...root}>      {trigger?.({ popoverTarget: `${id}popover` })}      <Column {...column}>        <div className="color-picker-area">          <div className="color-picker-thumb" role="slider" tabIndex={disabled ? -1 : 0} aria-label={labels.field ?? 'Lightness and chroma'} aria-valuemin={0} aria-valuemax={100} aria-valuenow={first.valueNow} aria-valuetext={first.valueText} aria-disabled={disabled || undefined} />        </div>        <span className="swatch swatch-lg color-picker-swatch" />        <input type="range" className="slider color-picker-hue" min={0} max={360} defaultValue={first.hue} aria-label={labels.hue ?? 'Hue'} disabled={disabled} />        {alpha && <input type="range" className="slider color-picker-alpha" min={0} max={100} defaultValue={first.alpha * 100} aria-label={labels.alpha ?? 'Opacity'} disabled={disabled} />}        <div className="color-picker-fields">          <select className="select select-sm color-picker-format" defaultValue={first.format} aria-label={labels.format ?? 'Format'} disabled={disabled}>            <option value="hex">Hex</option>            <option value="rgb">RGB</option>            <option value="oklch">OKLCH</option>          </select>          <input className="input input-sm color-picker-text" name={name} defaultValue={first.value} aria-label={label} spellCheck={false} autoComplete="off" disabled={disabled} />        </div>      </Column>    </div>  )}
ui/ColorPicker.svelte
<script lang="ts" module>  import type { Snippet } from 'svelte'  import type { HTMLAttributes } from 'svelte/elements'  export interface ColorPickerLabels {    /** The field's thumb. `Lightness and chroma` by default. */    field?: string    /** `Hue` by default. */    hue?: string    /** `Opacity` by default. */    alpha?: string    /** The select of the format. `Format` by default. */    format?: string  }  export interface ColorPickerProps extends Omit<HTMLAttributes<HTMLDivElement>, 'children'> {    /** The color, in hex, rgb() or oklch(); the format it is written in is the one the picker writes. Bind it, or leave it out. */    value?: string    onValueChange?: (value: string) => void    /** What the color is: the name of the text field. */    label: string    /** The name the text field submits with a form. */    name?: string    /** An opacity slider. Without it the color is opaque. True by default. */    alpha?: boolean    disabled?: boolean    /**     * The button that opens the picker in a popover: spread what it is given on a button of your own, and put     * a `swatch color-picker-swatch` in it to show the color. Leave it out and the picker stands inline.     */    trigger?: Snippet<[{ popovertarget: string }]>    /** What the controls are called, in the page's words. */    labels?: ColorPickerLabels    /** What the field's thumb says it holds, from the lightness in percent and the chroma. */    valueText?: (lightness: number, chroma: number) => string  }</script><script lang="ts">  import { untrack } from 'svelte'  import { colorPicker, colorPickerState } from '@master/ui/behaviors/color-picker.js'  import { behavior } from './behavior.svelte.js'  let { value = $bindable(), onValueChange, label, name, alpha = true, disabled, trigger, labels = {}, valueText, class: className, ...root }: ColorPickerProps = $props()  const id = $props.id()  // The first value is drawn into the first render; after that the behavior writes every part.  const first = untrack(() => colorPickerState(value ?? '', { valueText, opaque: !alpha }) ?? colorPickerState('#000000')!)  // Svelte writes a style again whenever its owner changes it, so it writes the numbers the behavior holds.  let element = $state<HTMLDivElement>()  let held = $state(first.properties)  const read = () => {    if (element) held = Object.fromEntries(Object.entries(held).map(([property, number]) => [property, element!.style.getPropertyValue(property) || number]))  }  const attach = behavior(colorPicker, () => ({ valueText }), {    value: () => value,    change: (next) => { value = next; onValueChange?.(next) },    settled: read,    on: { input: read },  })</script>{#snippet panel()}  <div class="color-picker-area">    <div class="color-picker-thumb" role="slider" tabindex={disabled ? -1 : 0} aria-label={labels.field ?? 'Lightness and chroma'} aria-valuemin={0} aria-valuemax={100} aria-valuenow={first.valueNow} aria-valuetext={first.valueText} aria-disabled={disabled || undefined}></div>  </div>  <span class="swatch swatch-lg color-picker-swatch"></span>  <input type="range" class="slider color-picker-hue" min="0" max="360" value={first.hue} aria-label={labels.hue ?? 'Hue'} {disabled} />  {#if alpha}    <input type="range" class="slider color-picker-alpha" min="0" max="100" value={first.alpha * 100} aria-label={labels.alpha ?? 'Opacity'} {disabled} />  {/if}  <div class="color-picker-fields">    <select class="select select-sm color-picker-format" aria-label={labels.format ?? 'Format'} {disabled}>      <option value="hex" selected={first.format === 'hex'}>Hex</option>      <option value="rgb" selected={first.format === 'rgb'}>RGB</option>      <option value="oklch" selected={first.format === 'oklch'}>OKLCH</option>    </select>    <input class="input input-sm color-picker-text" {name} value={first.value} aria-label={label} spellcheck="false" autocomplete="off" {disabled} />  </div>{/snippet}<!--  @component  A color picker. The behavior holds the color and moves every part; this component draws the first value  into the first render and passes the value in and out.--><div  class={['color-picker', className]}  style:--color-picker-lightness={held['--color-picker-lightness']}  style:--color-picker-chroma={held['--color-picker-chroma']}  style:--color-picker-hue={held['--color-picker-hue']}  style:--color-picker-alpha={held['--color-picker-alpha']}  bind:this={element}  {@attach attach}  {...root}>  {#if trigger}    {@render trigger({ popovertarget: `${id}-popover` })}    <div id="{id}-popover" popover="auto" class="popover color-picker-popover">{@render panel()}</div>  {:else}    {@render panel()}  {/if}</div>
ui/ColorPicker.vue
<script setup lang="ts">import { useId, useTemplateRef } from 'vue'import { colorPicker, colorPickerState } from '@master/ui/behaviors/color-picker.js'import { useBehavior } from './use-behavior'defineOptions({ inheritAttrs: false })const { alpha = true, labels = {}, valueText } = defineProps<{  /** What the color is: the name of the text field. */  label: string  /** The name the text field submits with a form. */  name?: string  /** An opacity slider. Without it the color is opaque. True by default. */  alpha?: boolean  disabled?: boolean  /** What the controls are called, in the page's words: `field` (the thumb), `hue`, `alpha` and `format`. */  labels?: { field?: string, hue?: string, alpha?: string, format?: string }  /** What the field's thumb says it holds, from the lightness in percent and the chroma. */  valueText?: (lightness: number, chroma: number) => string}>()/** The color, in hex, rgb() or oklch(): `v-model`. The format it is written in is the one the picker writes. */const model = defineModel<string>()const slots = defineSlots<{  /**   * The button that opens the picker in a popover: bind what it is given on a button of your own, and put a   * `swatch color-picker-swatch` in it to show the color. Leave it out and the picker stands inline.   */  trigger?: (attributes: { popovertarget: string }) => unknown}>()/* * A color picker. The behavior holds the color and moves every part; this component draws the first value * into the first render and passes the value in and out. */const id = useId()// The first value is drawn into the first render; after that the behavior writes every part.const first = colorPickerState(model.value ?? '', { valueText, opaque: !alpha }) ?? colorPickerState('#000000')!const root = useTemplateRef<HTMLDivElement>('root')// Vue writes a style again each time it renders, so it writes the numbers the behavior holds, not the first ones.const properties = () => Object.fromEntries(Object.entries(first.properties).map(([property, number]) => [property, root.value?.style.getPropertyValue(property) || number]))useBehavior(root, colorPicker, () => ({ valueText }), model)</script><template>  <div class="color-picker" ref="root" v-bind="$attrs" :style="properties()">    <template v-if="slots.trigger">      <slot name="trigger" v-bind="{ popovertarget: `${id}-popover` }" />      <div :id="`${id}-popover`" popover="auto" class="popover color-picker-popover">        <div class="color-picker-area">          <div class="color-picker-thumb" role="slider" :tabindex="disabled ? -1 : 0" :aria-label="labels.field ?? 'Lightness and chroma'" aria-valuemin="0" aria-valuemax="100" :aria-valuenow="first.valueNow" :aria-valuetext="first.valueText" :aria-disabled="disabled || undefined" />        </div>        <span class="swatch swatch-lg color-picker-swatch" />        <input type="range" class="slider color-picker-hue" min="0" max="360" :value.attr="first.hue" :aria-label="labels.hue ?? 'Hue'" :disabled="disabled">        <input v-if="alpha" type="range" class="slider color-picker-alpha" min="0" max="100" :value.attr="first.alpha * 100" :aria-label="labels.alpha ?? 'Opacity'" :disabled="disabled">        <div class="color-picker-fields">          <select class="select select-sm color-picker-format" :aria-label="labels.format ?? 'Format'" :disabled="disabled">            <option value="hex" :selected="first.format === 'hex'">Hex</option>            <option value="rgb" :selected="first.format === 'rgb'">RGB</option>            <option value="oklch" :selected="first.format === 'oklch'">OKLCH</option>          </select>          <input class="input input-sm color-picker-text" :name="name" :value.attr="first.value" :aria-label="label" spellcheck="false" autocomplete="off" :disabled="disabled">        </div>      </div>    </template>    <!-- Inline, the same parts stand in the root's column. -->    <template v-else>      <div class="color-picker-area">        <div class="color-picker-thumb" role="slider" :tabindex="disabled ? -1 : 0" :aria-label="labels.field ?? 'Lightness and chroma'" aria-valuemin="0" aria-valuemax="100" :aria-valuenow="first.valueNow" :aria-valuetext="first.valueText" :aria-disabled="disabled || undefined" />      </div>      <span class="swatch swatch-lg color-picker-swatch" />      <input type="range" class="slider color-picker-hue" min="0" max="360" :value.attr="first.hue" :aria-label="labels.hue ?? 'Hue'" :disabled="disabled">      <input v-if="alpha" type="range" class="slider color-picker-alpha" min="0" max="100" :value.attr="first.alpha * 100" :aria-label="labels.alpha ?? 'Opacity'" :disabled="disabled">      <div class="color-picker-fields">        <select class="select select-sm color-picker-format" :aria-label="labels.format ?? 'Format'" :disabled="disabled">          <option value="hex" :selected="first.format === 'hex'">Hex</option>          <option value="rgb" :selected="first.format === 'rgb'">RGB</option>          <option value="oklch" :selected="first.format === 'oklch'">OKLCH</option>        </select>        <input class="input input-sm color-picker-text" :name="name" :value.attr="first.value" :aria-label="label" spellcheck="false" autocomplete="off" :disabled="disabled">      </div>    </template>  </div></template>

#클래스

클래스설명
color-picker선택기입니다. 영역, 트랙, 텍스트를 담은 너비 16rem의 열입니다. color-picker-popover를 담을 때는 버튼과 팝오버만 담고, 열은 팝오버가 맡습니다.
color-picker-area현재 색상각에서 명도는 위쪽 100%부터 아래쪽 0까지, 채도는 인라인 시작 쪽의 0부터 끝 쪽의 .37까지 변하는 영역입니다. 손잡이를 담고 포인터 입력을 받습니다.
color-picker-thumb영역의 유일한 손잡이로, 루트의 숫자 값에 따라 배치됩니다. 값은 명도이고 aria-valuetext로 명도와 채도를 알리는 슬라이더입니다.
color-picker-hue0부터 360까지의 슬라이더에 적용합니다. 색상환으로 칠한 트랙에서 색상을 조절합니다.
color-picker-alpha0부터 100까지의 슬라이더에 적용합니다. 체커보드 위로 색이 점점 진해지는 트랙에서 불투명도를 조절합니다. 불투명한 색에는 생략하세요.
color-picker-swatch색상 견본에 적용합니다. 체커보드 위에 현재 색을 표시합니다. 열 안에서는 두 트랙의 시작 쪽에 놓이고, 팝오버를 여는 버튼 안에서는 선택기가 닫혀 있는 동안 색을 보여 줍니다.
color-picker-fields형식 선택과 텍스트 필드를 담은 행
color-picker-format작은 select에 적용합니다. 텍스트를 기록할 형식으로, hex, rgb, oklch 옵션을 가집니다.
color-picker-text작은 텍스트 필드에 적용합니다. 선택한 형식으로 색을 기록합니다. 세 형식 중 어느 것으로 입력한 색이든 받아들이며, 폼이 제출하는 name을 가집니다.
color-picker-popover루트 안의 팝오버에 적용합니다. 옆에 있는 버튼에서 여는 열이며, 버튼의 색상 견본이 색을 보여 줍니다.

#사용자 지정 속성

속성기본값설명
--color-picker-width16rem열의 너비
--color-picker-lightness0색의 명도로, 0부터 1까지입니다. 동작이 루트에 기록하며, 첫 값은 마크업의 style에 적으세요.
--color-picker-chroma0색의 채도로, 0부터 시작합니다. 영역은 .37까지입니다.
--color-picker-hue0색상각을 도 단위의 숫자로 나타냅니다. 단위 기호는 붙이지 않습니다.
--color-picker-alpha1색의 불투명도로, 0부터 1까지입니다.
--color-picker-color네 숫자로 만든 현재 색입니다. 루트 안에서 색을 표시하는 다른 요소에서 이 값을 읽으세요.

#소스

@master/ui/components/color-picker.css
/* * Color picker: a color chosen in OKLCH, the space the theme's own colors are written in. A field of the hue held, * lightness from top to bottom and chroma from start to end, under one thumb; the hue and the opacity on two * sliders; a swatch of the color; and the color as text in hex, rgb() or oklch(), beside the select that picks * which. Its behavior publishes the color as four numbers on the root (--color-picker-lightness, -chroma, -hue * and -alpha); the stylesheet places the thumb from them and the theme's mixins turn them into colors. * * Material: the field is a picture set into the surface, with a control's corner and a half-pixel ring of the * line on color inside its edge, so a white field reads on a white sheet. The thumb is the color itself in a * ring of pearl, as large as a slider's thumb, with the same fading shadow. The two tracks are sliders twice as * thick, one painted with the hues, the other with the color fading in over a checker. Inline, the root is a * column 16rem wide; opened from a button, the root holds the button and a popover, and the popover is the column. * * Without the script the field shows the color the markup was written with, and the sliders and the text field * are plain controls that do not follow one another. */@layer components.ui {  .color-picker {    --color-picker-width: 16rem;    --color-picker-lightness: 0;    --color-picker-chroma: 0;    --color-picker-hue: 0;    --color-picker-alpha: 1;    /* Which way chroma and hue run: toward the end of the line. */    --color-picker-run: 90deg;    /* The ground under a color that is not opaque. */    /* The checker's tone is the gradient's, so a picker inside a gradient shows one checkerboard, not two. */    --color-picker-checker: repeating-conic-gradient(color-mix(in oklab, var(--color-text-strong) 9%, transparent) 0 25%, transparent 0 50%) 0 0 / .5rem .5rem;    @apply --color-picker-color;    display: grid;    grid-template-columns: minmax(0, 1fr);    gap: .75rem;    inline-size: var(--color-picker-width);    max-inline-size: 100%;    &:dir(rtl) {      --color-picker-run: 270deg;    }    /* A swatch in the column stands at the start of the two sliders. */    &:has(.color-picker-swatch) {      grid-template-columns: auto minmax(0, 1fr);    }    /* Opened from a button: the root only holds the button, and the popover is the column. */    &:has(.color-picker-popover) {      display: inline-block;      inline-size: auto;      max-inline-size: none;    }  }  .color-picker-popover {    --popover-padding: .75rem;    grid-template-columns: minmax(0, 1fr);    gap: .75rem;    box-sizing: content-box;    width: var(--color-picker-width);    /* The holder's corner is the field's corner plus the padding between them, so the two curves are concentric. */    border-radius: calc(var(--radius-control) * var(--corner-scale) + var(--popover-padding));    /* The thumb and its focus ring stand half outside the field at its edges. */    overflow: visible;    &:popover-open {      display: grid;    }    &:has(.color-picker-swatch) {      grid-template-columns: auto minmax(0, 1fr);    }  }  /*   * The field. Its rows are the theme's: nine on the element, and the eight between them on a layer above,   * whose mask is whole on each of its rows and gone on the rows around it, so one row fades into the next.   */  .color-picker-area {    position: relative;    /* The thumb stands over the field's edge within the field, never over the page around it. */    isolation: isolate;    grid-column: 1 / -1;    aspect-ratio: 3 / 2;    border-radius: calc(var(--radius-control) * var(--corner-scale));    corner-shape: var(--corner-shape);    @apply --color-picker-field;    cursor: crosshair;    touch-action: none;    -webkit-user-select: none;    user-select: none;    -webkit-tap-highlight-color: transparent;    /* The colors are what the reader came for: forced colors keep them. */    forced-color-adjust: none;    &::before {      content: '';      position: absolute;      inset: 0;      border-radius: inherit;      corner-shape: inherit;      @apply --color-picker-field-between;      mask: repeating-linear-gradient(transparent, black 6.25%, transparent 12.5%);      pointer-events: none;    }    /* The edge, over both layers of rows. */    &::after {      content: '';      position: absolute;      inset: 0;      border-radius: inherit;      corner-shape: inherit;      box-shadow: inset 0 0 0 .5px var(--color-line-on-color);      pointer-events: none;    }    &:has(.color-picker-thumb[aria-disabled="true"]) {      opacity: .5;      cursor: not-allowed;    }    @media (forced-colors: active) {      outline: 1px solid CanvasText;      &:has(.color-picker-thumb[aria-disabled="true"]) {        outline-color: GrayText;      }    }  }  /*   * The thumb: placed by its middle, from the numbers on the root. Chroma past the end of the field (a color   * typed with more than .37) stands at the end.   */  .color-picker-thumb {    --color-picker-thumb: 1.125rem;    position: absolute;    z-index: 1;    inset-inline-start: calc(clamp(0, var(--color-picker-chroma) / .37, 1) * 100%);    top: calc((1 - clamp(0, var(--color-picker-lightness), 1)) * 100%);    box-sizing: border-box;    width: var(--color-picker-thumb);    height: var(--color-picker-thumb);    margin-block-start: calc(var(--color-picker-thumb) / -2);    margin-inline-start: calc(var(--color-picker-thumb) / -2);    border-radius: 999px;    corner-shape: round;    background: var(--color-picker-solid);    box-shadow:      inset 0 0 0 3px var(--color-thumb-high), inset 0 0 0 3.5px var(--color-line-on-color),      0 0 0 .5px var(--color-line-strong), 0 1px 2px -.5px var(--color-shade-1), 0 2px 4px -1px var(--color-shade-2), 0 4px 8px -4px var(--color-shade-3);    transition: scale var(--duration-quick) var(--easing-glide);    &:focus-visible {      @apply --focus-ring;    }    /* On touch the target reaches 44px around the thumb, which keeps its size. */    @media (pointer: coarse) {      &::after {        @apply --touch-target;      }    }    @media (forced-colors: active) {      &:focus-visible {        outline-color: Highlight;      }    }  }  /* Held, the thumb grows a little under the finger, as a slider's does. */  .color-picker-area:active .color-picker-thumb:not([aria-disabled="true"]) {    scale: 1.08;    @media (prefers-reduced-motion: reduce) {      scale: none;    }  }  /* The two tracks: sliders twice as thick, painted with what they choose, with no fill over it. */  .color-picker-hue,  .color-picker-alpha {    --slider-track: .75rem;    --slider-color: transparent;    grid-column: -2;    @media (forced-colors: active) {      &::-webkit-slider-runnable-track {        background: var(--slider-background);        box-shadow: inset 0 0 0 1px CanvasText;      }      &::-moz-range-track {        background: var(--slider-background);      }      /* A disabled slider fills with the system's disabled ink; these tracks have no fill to draw. */      &:disabled {        --slider-color: transparent;      }    }  }  .color-picker-hue {    @apply --color-picker-hues;  }  .color-picker-alpha {    --slider-background: linear-gradient(var(--color-picker-run), transparent, var(--color-picker-solid)), var(--color-picker-checker), var(--color-surface-raised);  }  /* The swatch: the color over the checker, so an opacity under 100% shows. In the column it spans both tracks. */  .color-picker-swatch {    --swatch: linear-gradient(var(--color-picker-color) 0 0), var(--color-picker-checker), var(--color-surface-raised);    grid-row: span 2;    align-self: center;  }  .color-picker:not(:has(.color-picker-alpha)) .color-picker-swatch {    grid-row: auto;  }  /* The text: the format, then the color written in it. */  .color-picker-fields {    display: flex;    grid-column: 1 / -1;    align-items: center;    gap: .5rem;    min-width: 0;  }  .color-picker-format {    flex: none;    width: auto;  }  .color-picker-text {    flex: 1;    min-width: 0;    font-variant-numeric: tabular-nums;  }}