# ew-color-picker 完整文档 / Full Documentation > 事件驱动 + 插件化的现代颜色选择器。Event-driven, plugin-based color picker. > 站点 / Site: https://eveningwater.github.io/ew-color-picker/ --- # English Docs ## Callbacks Source: https://eveningwater.github.io/ew-color-picker/api/callbacks # Callbacks Callbacks are functions passed through options. Unlike events, they are bound to a specific plugin or the core. ## Core callbacks | Callback | Signature | Triggered by | | --- | --- | --- | | `changeColor` | `(color: string) => void` | `core.setColor()` | | `sure` | `(color: string, picker) => void` | Sure button | | `clear` | `(picker) => void` | Clear button | | `togglePicker` | `(isOpen: boolean) => void` | `showPanel()` / `hidePanel()` | ```ts const picker = new ewColorPicker({ el: '#app', changeColor: (color) => console.log(color), sure: (color, instance) => console.log(color, instance.getColor()), clear: (instance) => console.log('cleared', instance.getColor()), togglePicker: (open) => console.log(open ? 'open' : 'closed'), }) ``` ::: tip Callback vs event `changeColor` runs **inside** `setColor()` in addition to the `change` event. `sure` / `clear` are invoked by the Button plugin with arguments, while `core.emit('sure')` invokes them without arguments. ::: ## Plugin-level callbacks ### Box | Callback | Signature | Notes | | --- | --- | --- | | `onClick` | `(boxPlugin) => void` | After the panel toggle; blocked when `disabled` / `readonly` | | `onMouseEnter` | `(boxPlugin) => void` | Mouse enter | | `onMouseLeave` | `(boxPlugin) => void` | Mouse leave | ```ts new ewColorPicker({ el: '#app', onClick: (box) => console.log('box clicked', box.hasBox), }) ``` ### Input | Callback | Signature | Notes | | --- | --- | --- | | `changeColor` | `(rgba: string) => void` | Valid input parsed and applied | ```ts new ewColorPicker({ el: '#app', hasInput: true, changeColor: (rgba) => console.log('input applied', rgba), }) ``` ### InputNumber | Callback | Signature | Notes | | --- | --- | --- | | `onChange` | `(value: number) => void` | Debounced 300ms; not called on construction | | `onBlur` | `(value: number) => void` | Input blurred | | `onFocus` | `(event: FocusEvent) => void` | Input focused | ```ts import { InputNumber } from '@ew-color-picker/input-number' new InputNumber({ value: 50, min: 0, max: 100, onChange: (v) => console.log(v), onBlur: (v) => console.log('blur', v), onFocus: (e) => console.log('focus', e), }) ``` ### Predefine | Callback | Signature | Notes | | --- | --- | --- | | `changeColor` | `(rgba: string) => void` | Swatch clicked and applied | ### ColorMode | Callback | Signature | Notes | | --- | --- | --- | | `changeMode` | `(mode, picker) => void` | After switching to `'hex' \| 'rgb' \| 'hsl'` | ```ts new ewColorPicker({ el: '#app', changeMode: (mode, instance) => console.log(mode, instance.getColor()), }) ``` ### Button | Callback | Signature | Notes | | --- | --- | --- | | `clear` | `(picker) => void` | Clear clicked | | `sure` | `(color, picker) => void` | Sure clicked | ## Callback vs event | Aspect | Callback | Event | | --- | --- | --- | | Registration | Options object | `on()` / `once()` | | Multiple handlers | One per option | Many | | Removal | `updateOptions({ changeColor: noop })` | `off()` | | Return value effect | Ignored | `true` stops propagation | | Access to plugin instance | Usually provided | Only via payload | Prefer events for analytics or multiple consumers; prefer callbacks for a single owner of the behavior. ## Next steps - [Events](./events.md) - [Options](./options.md) - [Plugin overview](../plugins/index.md) ## Events Source: https://eveningwater.github.io/ew-color-picker/api/events # Events Every instance has its own event bus. The following types are registered: ```ts ['destroy', 'change', 'sure', 'clear', 'toggle', 'options-update', 'mode-change'] ``` Using an unknown type logs a warning; it does not throw. ## Summary | Event | Payload | Emitted when | | --- | --- | --- | | `change` | `(color: string)` | `setColor()` is called | | `toggle` | `(isOpen: boolean)` | Panel opened/closed | | `sure` | `(color: string, picker)` | Sure button clicked | | `clear` | `()` | Clear button clicked | | `options-update` | `(options)` | `updateOptions()` finished | | `mode-change` | `(mode: 'hex' \| 'rgb' \| 'hsl')` | Color mode switched | | `destroy` | `()` | `destroy()` finished | ## change ```ts picker.on('change', (color) => console.log(color)) ``` Emitted synchronously by `setColor()`, after `currentColor` and `hsvaColor` are updated. Every UI plugin listens to this event to stay in sync. Calling `setColor('')` also emits `change('')` (used when clearing). ## toggle ```ts picker.on('toggle', (isOpen) => console.log(isOpen)) ``` Emitted after the open/close animation promise resolves. `pickerFlag` is already updated when listeners run. ## sure ```ts picker.on('sure', (color, picker) => console.log(color)) ``` Emitted by the Button plugin after `options.sure(color, picker)`. The panel closes afterwards. ## clear ```ts picker.on('clear', () => console.log('cleared')) ``` Emitted by the Button plugin after `options.clear(picker)`. The panel closes afterwards. ## options-update ```ts picker.on('options-update', (options) => console.log(options)) ``` Emitted at the end of `updateOptions()`, after plugins have re-rendered. ## mode-change ```ts picker.on('mode-change', (mode) => console.log(mode)) ``` Emitted by the ColorMode plugin. `mode` is `'hex'`, `'rgb'` or `'hsl'`. ## destroy ```ts picker.on('destroy', () => console.log('destroyed')) ``` Emitted at the very end of `destroy()`, after plugin cleanup and DOM removal. ## Listener rules ### once ```ts picker.once('change', (color) => console.log('first change only', color)) ``` ### off ```ts const handler = (color: string) => console.log(color) picker.on('change', handler) picker.off('change', handler) picker.off('change') // remove all change listeners picker.off() // remove everything ``` ### Stopping propagation Return `true` from a listener to stop the remaining listeners of the same event: ```ts picker.on('change', (color) => { if (color === '#000000') return true // stop here }) ``` ### trigger vs emit | Method | Calls listeners | Calls option callbacks | | --- | --- | --- | | `trigger(type, ...args)` | Yes | No | | `emit(type, ...args)` | Yes | Yes, for `clear` / `sure` / `toggle` | `emit('clear')` invokes `options.clear()` with no arguments; `emit('sure')` invokes `options.sure()` with no arguments; `emit('toggle', isOpen)` forwards `isOpen` to `options.togglePicker`. ## Next steps - [Callbacks](./callbacks.md) - [Methods](./methods.md) ## Methods Source: https://eveningwater.github.io/ew-color-picker/api/methods # Methods ## Constructor ```ts new ewColorPicker(options) new ewColorPicker(el) new ewColorPicker(el, options) ``` | Form | Example | | --- | --- | | Options object | `new ewColorPicker({ el: '#app', defaultColor: '#f00' })` | | Selector + options | `new ewColorPicker('#app', { size: 'large' })` | | Element + options | `new ewColorPicker(document.querySelector('#app')!, { size: 'large' })` | If `el` (or the first argument) is provided, `mount()` is called automatically. ## createEwColorPicker The aggregate package `@ew-color-picker/ew-color-picker` and the unscoped `ew-color-picker` entry also export a factory. It is exactly `new ewColorPicker(options)` without the `new` keyword: ```ts import { createEwColorPicker } from 'ew-color-picker' const picker = createEwColorPicker({ el: '#picker', defaultColor: '#6366f1', }) picker.setColor('#f00') ``` | Parameter | Type | Description | | --- | --- | --- | | `options` | `string \| HTMLElement \| ewColorPickerOptions` | Same as the first constructor argument | | Returns | `ewColorPicker` | A mounted instance ready for instance methods | When using the on-demand core package (`@ew-color-picker/core`), call `new ewColorPicker(options)` directly — the factory is only shipped by the aggregate package. ## Static methods ### use ```ts static use(ctor: ewColorPickerPluginCtor): typeof ewColorPicker ``` Registers a plugin class. Requires `static pluginName`. Idempotent and chainable. ```ts ewColorPicker.use(MyPlugin).use(AnotherPlugin) ``` ## Mounting ### mount ```ts mount(el?: string | HTMLElement): ewColorPicker ``` Creates `root` and `panelContainer`, then applies plugins. If `el` is omitted, uses `options.el` or `document.body`. Returns `this`. ### getMountPoint ```ts getMountPoint(name: 'root' | 'panelContainer'): HTMLElement | undefined ``` Returns `undefined` after destruction. ### getContainer ```ts getContainer(): HTMLElement ``` Returns the current mount container. ## Panel control ### showPanel ```ts showPanel(animationType?: string, duration?: number): void ``` - If there is no current color, uses `defaultColor` or falls back to red and syncs plugins. - Resolves animation, then sets `pickerFlag = true`, emits `toggle(true)`, calls `options.togglePicker(true)`, calls `syncAllPlugins`, then auto-positions the panel and binds the outside-click handler. ### hidePanel ```ts hidePanel(animationType?: string, duration?: number): void ``` Resolves animation, resets auto-placement styles, sets `pickerFlag = false`, emits `toggle(false)`, calls `options.togglePicker(false)`, and unbinds the outside-click handler. ### openPicker / closePicker ```ts openPicker(): void // alias of showPanel() closePicker(): void // alias of hidePanel() ``` ## Color ### setColor ```ts setColor(color: string): void ``` The only supported way to change color: 1. Stores `currentColor`; 2. Converts to rgba → hsva and updates `hsvaColor` (invalid color falls back to `{h:0,s:100,v:100,a:1}`); 3. Emits `change(color)`; 4. Calls `options.changeColor(color)`. Does nothing special for empty strings: `setColor('')` clears `currentColor` and emits `change('')`. ### getColor ```ts getColor(): string ``` Returns `currentColor` (may be `''` when no color is selected). ### getHsvaColor / setHsvaColor ```ts getHsvaColor(): HsvaColor // copy setHsvaColor(hsva: HsvaColor): void // does NOT emit change ``` `setHsvaColor` only mutates internal state; call `setColor()` afterwards if the UI must update. ## Options ### getOptions ```ts getOptions(): ewColorPickerMergeOptionsData ``` Returns the live options object. ### updateOptions ```ts updateOptions(newOptions: Record): void ``` 1. Merges new options; 2. If `defaultColor` is present and valid, calls `setColor(defaultColor)`; invalid values warn and keep the current color; 3. Re-applies plugins so plugin `updateOptions()` can refresh; 4. Emits `options-update(options)`. ```ts picker.updateOptions({ size: 'small', disabled: true }) ``` ### syncAllPlugins ```ts syncAllPlugins(color: string): void ``` Calls each plugin's `syncColor(color)` when it exists. Useful after external state changes. ## Events ```ts on(type, fn, context?): this once(type, fn, context?): this off(type?, fn?): this | undefined trigger(type, ...args): void emit(type, ...args): void ``` | Method | Notes | | --- | --- | | `on` | Add listener | | `once` | One-shot listener | | `off` | Remove a specific listener, all of a type, or all | | `trigger` | Runs listeners only; returning `true` from one stops the rest | | `emit` | Runs listeners **and** invokes `options.clear` / `options.sure` / `options.togglePicker` | ## Instance plugin use ```ts use(plugin: ewColorPickerPlugin): ewColorPicker ``` Calls `plugin.install(this)` if present and returns `this`. ## Lifecycle ### destroy ```ts destroy(): void ``` 1. Marks the instance destroyed; 2. Unbinds the document `mousedown` listener; 3. Calls `destroy()` on every plugin instance; 4. Removes all mount points and the wrapper; 5. Clears plugin references; 6. Emits `destroy`. Subsequent calls are no-ops. ### getDestroyedStatus ```ts getDestroyedStatus(): boolean ``` ## Instance properties | Property | Type | Description | | --- | --- | --- | | `options` | `ewColorPickerMergeOptionsData` | Merged options | | `wrapper` | `HTMLElement` | Root `.ew-color-picker` element | | `plugins` | `Record` | Plugin instances | | `currentColor` | `string` | Current color | | `hsvaColor` | `HsvaColor` | Current HSVA | | `currentMode` | `'Hex' \| 'RGB' \| 'HSV'` | Core mode field | | `pickerFlag` | `boolean` | Panel open state | | `panelWidth` / `panelHeight` | `number` | Panel size | | `panelLeft` / `panelTop` | `number` | Panel position | ## Next steps - [Events](./events.md) - [Callbacks](./callbacks.md) - [Options](./options.md) ## Options Source: https://eveningwater.github.io/ew-color-picker/api/options # Options Every option below can be passed to the constructor. Defaults come from `defaultConfig` in the core. ## Overview | Group | Options | | --- | --- | | Core | `el`, `disabled`, `defaultColor`, `size`, `predefineColor`, `isClickOutside` | | Layout | `hueDirection`, `alphaDirection`, `autoPanelPosition`, `panelPlacement`, `appendTo`, `boundary`, `prefix` | | Labels | `clearText`, `sureText` | | Animation | `togglePickerAnimation`, `pickerAnimationTime` | | Plugin switches | `hasBox`, `hasPanel`, `hasInput`, `hasClear`, `hasSure`, `hue`, `alpha`, `showButton`, `showColorMode`, `showInputNumber`, `showEyedropper`, `showCopyColor` | | Eyedropper | `eyedropperText`, `onEyedropperPick` | | CopyColor | `copyColorText`, `copiedText`, `onCopyColor` | | Plugin config objects | `ewColorPickerPanel`, `ewColorPickerColorMode` | | Box extras | `boxNoColorIcon`, `boxHasColorIcon`, `readonly`, `className`, `style` | | Callbacks | `changeColor`, `sure`, `clear`, `togglePicker` | | Color mode | `defaultMode`, `changeMode` | ## Core options ### el | Type | Default | Description | | --- | --- | --- | | `string \| HTMLElement` | `document.body` | Mount container. A selector or element. Providing it auto-mounts. | ```ts new ewColorPicker({ el: '#app' }) new ewColorPicker(document.getElementById('app')!) ``` ### disabled | Type | Default | Description | | --- | --- | --- | | `boolean` | `false` | Disables the box, panel drag, hue/alpha sliders, inputs and buttons. | ```ts new ewColorPicker({ el: '#app', disabled: true }) ``` ### defaultColor | Type | Default | Description | | --- | --- | --- | | `string` | `''` | Initial color; also the color restored by the Clear button. | - With the Alpha plugin registered, a hex value is converted to `rgba()`. - Without Alpha, a `rgba()` value is converted to hex. - Invalid values produce a warning and keep the current color when passed to `updateOptions`. ### size | Type | Default | Description | | --- | --- | --- | | `'mini' \| 'small' \| 'normal' \| 'medium' \| 'large' \| number \| { width, height } \| string` | `'normal'` | Box size | | Preset | Size | Icon | | --- | --- | --- | | `mini` | 20px | 12px | | `small` | 24px | 14px | | `normal` | 32px | 16px | | `medium` | 36px | 18px | | `large` | 40px | 20px | Numbers are treated as pixels; objects accept `width`/`height`; CSS strings are used verbatim. ### predefineColor | Option | Type | Default | Description | | --- | --- | --- | --- | | `predefineColor` | `(string \| { color: string; disabled?: boolean })[]` | `[]` | Predefined swatches. Empty array renders nothing. Clicking a swatch calls the top-level `changeColor` callback. | ```ts predefineColor: ['#ef4444', '#22c55e', { color: '#0f172a', disabled: true }] ``` ### isClickOutside | Type | Default | Description | | --- | --- | --- | | `boolean` | `true` | Clicking outside the picker closes the panel. | ## Layout options ### hueDirection / alphaDirection | Type | Default | | --- | --- | | `'horizontal' \| 'vertical'` | `'vertical'` | Controls slider orientation. When both are horizontal, the panel width becomes 320px. ### autoPanelPosition | Type | Default | Description | | --- | --- | --- | | `boolean` | `false` | Position the panel relative to the box automatically. Requires the Box plugin with `hasBox: true`. | ### appendTo | Type | Default | Description | | --- | --- | --- | | `string \| HTMLElement` | `undefined` | Mount the panel container into an external container (e.g. `document.body`) so it is not clipped by `overflow` of dialogs or scroll containers. The panel switches to viewport-relative (`position: fixed`) placement, still follows `panelPlacement`, and re-positions on scroll or resize. | ```ts new ewColorPicker({ el: '#picker', appendTo: document.body, panelPlacement: 'bottom', }) ``` ### boundary | Type | Default | Description | | --- | --- | --- | | `string \| HTMLElement \| null` | `null` | Clamp the panel inside a container's visible area instead of the whole viewport. Useful when the picker sits in a drawer, modal, or scroll panel. The element's `getBoundingClientRect()` is intersected with the viewport; pass a selector string or an element. `null` (default) keeps the original viewport-only behavior. | When `autoPanelPosition` is on, the panel is positioned against the box, then clamped into the boundary, and finally converted back to the panel's `offsetParent` coordinates — so it stays aligned even when an ancestor has `transform` / `filter`. Works with or without `appendTo`. ```ts new ewColorPicker({ el: '#picker', autoPanelPosition: true, boundary: '.el-drawer__body', }) ``` ### prefix | Type | Default | Description | | --- | --- | --- | | `string` | `'ew-'` | Prefix of every generated CSS class name. Override it when embedding the picker in another library to avoid style collisions. | ```ts new ewColorPicker({ el: '#picker', prefix: 'my-' }) ``` > The JS option must match the prefix used when compiling the styles, otherwise the class names won't line up and CSS won't apply. When compiling the SCSS sources yourself, override `$prefix`: ```scss @use "@ew-color-picker/style/src/index.scss" with ( $prefix: "my-" ); ``` The prebuilt `dist/index.css` always uses the `ew-` prefix; keep the default `prefix` option when using it. ### panelPlacement | Type | Default | Values | | --- | --- | --- | | `string` | `'bottom'` | `top-start` `top` `top-end` `left-start` `left` `left-end` `right-start` `right` `right-end` `bottom-start` `bottom` `bottom-end` | Gap is 5px; out-of-viewport positions are adjusted automatically. ## Labels | Option | Type | Default | | --- | --- | --- | | `clearText` | `string` | `'清空'` | | `sureText` | `string` | `'确定'` | Change them for i18n: ```ts new ewColorPicker({ clearText: 'Reset', sureText: 'Apply' }) ``` ## Animation ### togglePickerAnimation | Type | Default | Values | | --- | --- | --- | | `string` | `'default'` | `'default'`, `'height'`, `'opacity'` | Only `height` and `opacity` are animated; `default` toggles instantly. ### pickerAnimationTime | Type | Default | Range | | --- | --- | --- | | `number` | `200` | 0–10000 (ms) | Values above 10000 are clamped. ## Plugin switches | Option | Type | Default | Effect | | --- | --- | --- | --- | | `hasBox` | `boolean` | `true` | Hide the trigger swatch | | `hasPanel` | `boolean` | `true` | Hide the 2D panel | | `hasInput` | `boolean` | `true` | Hide the text input | | `hasClear` | `boolean` | `true` | Hide the Clear button | | `hasSure` | `boolean` | `true` | Hide the Sure button | | `hue` | `boolean` | `true` | Hide the hue slider | | `alpha` | `boolean` | `true` | Hide the alpha slider | | `showButton` | `boolean` | `true` | Hide clear + sure buttons at once | | `showColorMode` | `boolean` | `true` | Hide the Hex/RGB/HSL switcher | | `showInputNumber` | `boolean` | `true` | Skip the InputNumber plugin's own numeric input; ColorMode channel inputs are unaffected | | `showEyedropper` | `boolean` | `true` | Hide the screen picker button; unsupported browsers never render it | | `showCopyColor` | `boolean` | `true` | Hide the copy-to-clipboard button | ```ts new ewColorPicker({ el: '#app', hasPanel: false, hue: false, alpha: false, hasInput: false, hasClear: false, hasSure: false, }) ``` ## Eyedropper | Option | Type | Default | Description | | --- | --- | --- | --- | | `eyedropperText` | `string` | `undefined` | Accessible label and tooltip; when set, also rendered as visible text | | `onEyedropperPick` | `(color: string) => void` | — | Called with the picked `sRGBHex` value | See [Eyedropper plugin](../plugins/eyedropper.md) for browser support and cancellation behaviour. ## CopyColor | Option | Type | Default | Description | | --- | --- | --- | --- | | `copyColorText` | `string` | `'复制颜色到剪贴板'` | Accessible label and tooltip | | `copiedText` | `string` | `'已复制'` | Temporary tooltip after a successful copy | | `onCopyColor` | `(color: string) => void` | — | Called with the copied color value | See [CopyColor plugin](../plugins/copy-color.md) for clipboard fallback and click behaviour. ## Plugin config objects | Option | Type | Notes | | --- | --- | --- | | `ewColorPickerPanel` | `boolean` | `false` disables the panel (same as `hasPanel: false`) | | `ewColorPickerColorMode` | `boolean \| object` | `false` disables mode switching; object merges color-mode options | ## Box extras | Option | Type | Default | Description | | --- | --- | --- | --- | | `boxNoColorIcon` | `string` | `''` | Custom HTML for the "no color" icon | | `boxHasColorIcon` | `string` | `''` | Custom HTML for the "has color" icon | | `readonly` | `boolean` | `false` | Prevents clicking the box | | `className` | `string` | `''` | Extra class on `.ew-color-picker-box` | | `style` | `string \| Record` | `''` | Inline styles for the box | ## Color mode | Option | Type | Default | Description | | --- | --- | --- | --- | | `defaultMode` | `'hex' \| 'rgb' \| 'hsl'` | `'rgb'` with Alpha, otherwise `'hex'` | Initial mode | | `changeMode` | `(mode, picker) => void` | — | Mode change callback | ## Callbacks | Callback | Signature | When | | --- | --- | --- | | `changeColor` | `(color: string) => void` | Color changed | | `sure` | `(color: string, picker) => void` | Sure button clicked | | `clear` | `(picker) => void` | Clear button clicked | | `togglePicker` | `(isOpen: boolean) => void` | Panel toggled | ## Complete example ```ts const picker = new ewColorPicker({ el: '#app', defaultColor: 'rgba(99, 102, 241, 0.8)', size: 'large', predefineColor: ['#ef4444', '#22c55e', '#3b82f6', { color: '#0f172a', disabled: true }], hueDirection: 'horizontal', alphaDirection: 'horizontal', clearText: 'Reset', sureText: 'Apply', togglePickerAnimation: 'height', pickerAnimationTime: 250, autoPanelPosition: true, panelPlacement: 'bottom-start', defaultMode: 'rgb', changeColor: (color) => console.log(color), sure: (color) => console.log('sure', color), }) ``` ## Next steps - [Methods](../api/methods.md) - [Events](../api/events.md) - [Callbacks](../api/callbacks.md) ## Styles & Classes Source: https://eveningwater.github.io/ew-color-picker/api/styles # Styles & Classes ## Stylesheet entries | File | Required | Contents | | --- | --- | --- | | `@ew-color-picker/style/dist/index.css` | Yes | Picker, box, panel, sliders, buttons, mode switcher, predefine | | `@ew-color-picker/style/dist/input-number.css` | Yes for numeric inputs | InputNumber component | | `@ew-color-picker/style/dist/select.css` | Only when using Select | Select dropdown component | ```ts import '@ew-color-picker/style/dist/index.css' import '@ew-color-picker/style/dist/input-number.css' ``` ::: warning Importing only `index.css` leaves RGB/HSL numeric inputs unstyled. Add `select.css` only when you use the Select component. ::: ## Class prefix All class names start with `ew-` by default (e.g. `.ew-color-picker-box`, `.ew-input-number`). Change the JS-side prefix with the [`prefix`](./options#prefix) constructor option and mirror it in the stylesheet through the SCSS `$prefix` variable: ```scss @use "@ew-color-picker/style/src/index.scss" with ($prefix: "my-"); @use "@ew-color-picker/style/src/input-number.scss" with ($prefix: "my-"); ``` The prebuilt `dist/*.css` files always use the `ew-` prefix; keep the default `prefix` option when using them. ## CSS variables | Variable | Set on | Default | Description | | --- | --- | --- | --- | | `--panel-width` | `.ew-color-picker-panel` | computed (285/302/320px) | Panel width | | `--panel-height` | `.ew-color-picker-panel` | `180px` | Panel height | Override them after importing the styles: ```css .ew-color-picker .ew-color-picker-panel { --panel-width: 320px; --panel-height: 200px; } ``` ## Class reference ### Container | Class | Description | | --- | --- | | `.ew-color-picker` | Root container | | `.ew-color-picker-panel-container` | Panel container (absolute) | | `.ew-color-picker-panel-container-hidden` | Hidden state | | `.ew-color-picker-bottom-row` | Bottom row that hosts inputs and buttons | | `.ew-color-picker-extra-row` | Toolbar row above the bottom row (eyedropper / copy buttons) | ### Box | Class | Description | | --- | --- | | `.ew-color-picker-box` | Trigger swatch | | `.ew-color-picker-box-arrow-icon` | Default "has color" icon | | `.ew-color-picker-box-close-icon` | Default "no color" icon | | `.is-disabled` / `.is-readonly` | States | ### Panel | Class | Description | | --- | --- | | `.ew-color-picker-panel` | 2D panel | | `.ew-color-picker-panel-dynamic-size` | Dynamic size marker | | `.ew-color-picker-white-panel` / `.ew-color-picker-black-panel` | Gradient layers | | `.ew-color-picker-panel-cursor` | Drag cursor | ### Sliders | Class | Description | | --- | --- | | `.ew-color-picker-slider` | Hue slider root | | `.ew-color-picker-is-horizontal` / `.ew-color-picker-is-vertical` | Orientation | | `.ew-color-picker-slider-bar` | Hue gradient bar | | `.ew-color-picker-slider-thumb` | Hue thumb | | `.ew-color-picker-slider.ew-alpha` | Alpha slider root | | `.ew-color-picker-alpha-slider-wrapper` | Checkerboard + gradient wrapper | | `.ew-color-picker-alpha-slider-bg` / `.ew-color-picker-alpha-slider-bar` | Layers | | `.ew-color-picker-alpha-slider-thumb` | Alpha thumb | ### Input & buttons | Class | Description | | --- | --- | | `.ew-color-picker-input-container` / `-flex` | Text input container | | `.ew-color-picker-input` | Text input | | `.ew-color-picker-input-default` | Default (hex) input | | `.ew-input-disabled` | Disabled text input | | `.ew-color-picker-drop-btn-group` / `-multi` / `-single` | Button group | | `.ew-color-picker-clear-btn` | Clear button | | `.ew-color-picker-sure-btn` | Sure button | | `.ew-color-picker-drop-btn` | Shared button style | | `.ew-color-picker-eyedropper-btn` | Eyedropper button | | `.ew-color-picker-copy-btn` | Copy color button | | `.ew-color-picker-copy-tip` | Copy success toast bubble | ### Color mode | Class | Description | | --- | --- | | `.ew-color-picker-mode-container` | Mode switcher | | `.ew-color-picker-mode-up-btn` / `-down-btn` | Arrows | | `.ew-color-picker-mode-text` | Current mode label | | `.ew-color-picker-inputs-group` | Channel group | | `.ew-color-picker-inputs-col` | One channel column | | `.ew-color-picker-input-label` | Channel label | ### Predefine | Class | Description | | --- | --- | | `.ew-color-picker-predefine-container` | Swatch container | | `.ew-color-picker-predefine-color` | Swatch wrapper | | `.ew-color-picker-predefine-color-item` | Color fill | | `.ew-color-picker-predefine-color-disabled` | Disabled swatch | | `.ew-color-picker-predefine-color-active` | Selected swatch | ### InputNumber | Class | Description | | --- | --- | | `.ew-input-number` | Root | | `.ew-input-number--small` / `--default` / `--large` | Sizes | | `.ew-input-number--focused` / `--disabled` | States | | `.ew-input-number__input` | Input | | `.ew-input-number__buttons` | Stepper container | | `.ew-input-number__button--up` / `--down` | Steppers | ### Select | Class | Description | | --- | --- | | `.ew-select` | Root | | `.ew-select--small` / `--default` / `--large` | Sizes | | `.ew-select--open` / `--disabled` | States | | `.ew-select__trigger` | Trigger button | | `.ew-select__value` / `--placeholder` | Current value text | | `.ew-select__clear` / `--hidden` / `-icon` | Clear button and its visibility state | | `.ew-select__arrow` / `-icon` | Arrow indicator | | `.ew-select__dropdown` | Dropdown layer | | `.ew-select__option` | One option | | `.ew-select__option--selected` / `--active` / `--disabled` | Option states | ## Theming example ```css /* Brand buttons */ .ew-color-picker-sure-btn { background: linear-gradient(135deg, #6366f1, #8b5cf6); border: none; color: #fff; } /* Rounded trigger */ .ew-color-picker-box { border-radius: 12px; } /* Bigger panel */ .ew-color-picker-panel { --panel-width: 340px; --panel-height: 200px; } ``` ## Multi-instance isolation Class names are global. If you need per-instance styling, pass a `className` (Box) or scope styles to a wrapper: ```html
``` ```css .theme-dark .ew-color-picker-panel { background: #111827; } ``` ## Next steps - [Options](./options.md) - [Box plugin](../plugins/box.md) - [InputNumber plugin](../plugins/input-number.md) ## Live Demo Source: https://eveningwater.github.io/ew-color-picker/examples/demo # Live Demo The page below loads real build artifacts: a full picker, a current-color preview, and an event log. ::: tip Where do the assets come from? `docs/scripts/prepare-demo.mjs` copies these before `dev` / `build`: - `packages/ew-color-picker/dist/index.min.js` - `packages/style/dist/index.css` - `packages/style/dist/input-number.css` If the iframe is blank, run `pnpm run build:all` in the repository root first. ::: ## What the demo shows | Area | Description | | --- | --- | | Picker | `defaultColor: '#6366f1'`, presets and mode switching enabled | | Color card | Updates live from `change` | | Event log | Listens to `change` / `toggle` / `sure` / `clear` / `mode-change` / `destroy` | ## Run locally ```bash pnpm run build:all pnpm run docs:dev ``` ## Related - [Examples](./index.md) - [Quick start](../guide/getting-started.md) ## Examples Source: https://eveningwater.github.io/ew-color-picker/examples/ # Examples Fifteen minimal recipes. Runnable HTML files live in the repository's `examples/` directory. ## 1. Basic ```html
``` ## 2. Layout & orientation ```ts new ewColorPicker({ el: '#app', hueDirection: 'horizontal', alphaDirection: 'horizontal', size: 'large', }) ``` ## 3. Predefined colors ```ts new ewColorPicker({ el: '#app', predefineColor: ['#ef4444', '#22c55e', '#3b82f6', { color: '#0f172a', disabled: true }], }) ``` ## 4. Buttons ```ts new ewColorPicker({ el: '#app', hasClear: false, sureText: 'Apply color', sure: (color) => console.log(color), }) ``` ## 5. Events & callbacks ```ts const picker = new ewColorPicker({ el: '#app', changeColor: (color) => console.log('callback', color), }) picker.once('change', (color) => console.log('once', color)) picker.on('sure', (color) => console.log('sure', color)) picker.on('clear', () => console.log('clear')) picker.on('toggle', (open) => console.log(open)) ``` ## 6. Auto panel placement ```ts new ewColorPicker({ el: '#app', autoPanelPosition: true, panelPlacement: 'top-end', }) ``` ## 7. Toggle animation ```ts new ewColorPicker({ el: '#app', togglePickerAnimation: 'height', pickerAnimationTime: 300, }) ``` Available: `default`, `height`, `opacity`. Maximum duration is 10000ms. ## 8. Disabled & readonly ```ts new ewColorPicker({ el: '#app', disabled: true }) new ewColorPicker({ el: '#app', readonly: true, defaultColor: '#84cc16' }) ``` ## 9. Color modes ```ts new ewColorPicker({ el: '#app', defaultMode: 'rgb', showColorMode: true, changeMode: (mode) => console.log(mode), }) ``` ## 10. Instance API ```ts const picker = new ewColorPicker({ el: '#app', defaultColor: '#f43f5e' }) console.log(picker.getColor()) console.log(picker.getHsvaColor()) picker.setColor('#22c55e') picker.updateOptions({ size: 'large' }) picker.showPanel() picker.hidePanel() picker.destroy() ``` ## 11. Numeric input ```ts import { InputNumber } from '@ew-color-picker/input-number' import '@ew-color-picker/style/dist/input-number.css' const num = new InputNumber({ value: 50, min: 0, max: 100, onChange: console.log }) document.body.appendChild(num.getElement()) ``` ## 12. Multiple instances ```ts [...document.querySelectorAll('.picker')].forEach((el) => { new ewColorPicker({ el, defaultColor: '#a855f7' }) }) ``` ::: warning No NodeList The constructor does not accept a NodeList or array. Instantiate one by one. Events, mount points and inputs are isolated per instance. ::: ## 13. Eyedropper ```ts new ewColorPicker({ el: '#app', showEyedropper: true, onEyedropperPick: (color) => console.log(color), }) ``` The button sits in its own toolbar row above the color value input and only renders in browsers supporting the EyeDropper API. See the [Eyedropper plugin](../plugins/eyedropper.md). ## 14. Copy color ```ts new ewColorPicker({ el: '#app', showCopyColor: true, copyColorText: 'Copy color to clipboard', copiedText: 'Copied', onCopyColor: (color) => console.log(color), }) ``` The copy button sits in its own toolbar row above the color value input, is filled with the current color, and shows a short success toast. See the [CopyColor plugin](../plugins/copy-color.md). ## 15. Select dropdown ```ts import '@ew-color-picker/style/dist/select.css' new ewColorPicker({ el: '#app', selectItems: [ { label: 'Linear', value: 'linear' }, { label: 'Radial', value: 'radial' }, ], selectValue: 'linear', onSelectChange: (value) => console.log(value), onSelectClear: () => console.log('cleared'), }) ``` The dropdown only renders when `selectItems` is not empty. Once a value is selected, a clear icon appears; clicking it resets the selection. See the [Select plugin](../plugins/select.md). ## Related - [Live demo](./demo.md) - [Options](../api/options.md) · [Methods](../api/methods.md) · [Events](../api/events.md) ## Changelog Source: https://eveningwater.github.io/ew-color-picker/guide/changelog # Changelog ## 2.0.9 ### Fixes - Fixed the vertical hue slider being out of sync with the colour panel: the stylesheet gradient increases hue from top to bottom (`linear-gradient(180deg, ...)`), but the thumb position and click/drag mapping used the inverted `1 - hue / 360` formula. The thumb now sits on the matching colour, and clicking or dragging picks the hue you actually see - Fixed the alpha slider having no colour: the background layer only showed the transparency checkerboard, so the alpha track gave no visual feedback. It now renders a gradient from the fully opaque current colour to transparent, following the horizontal or vertical direction, and updates whenever the colour changes - Fixed the console banner printing a stale version (`2.0.7`). The version is now injected from `package.json` at build time, so it can no longer drift from the published release ### Tests - Added regression tests for the vertical hue thumb position and click mapping, the alpha gradient direction in both orientations, and the console banner version ## 2.0.8 ### Fixes - Fixed arrow and close icon positioning for users who load the static CSS via ``: the icon rules were only injected at runtime by the core entry, so the SCSS build (`@ew-color-picker/style`) was missing them and the arrow rendered off-center. The rules are now in the SCSS source as well - Arrow icon `fill` changed from hard-coded `#666666` to `currentColor`, so icons inherit the theme text color - Fixed the empty root container taking up `line-height` height when `hasBox: false` is used together with `appendTo`: the `.ew-color-picker` shell is now hidden via `:empty { display: none }` and reappears automatically once the box is rendered - Fixed panel positioning when `hasBox: false`: the panel anchor now falls back from the box to the user-supplied `el` container (and only then to the root element), so the panel is no longer positioned against a 0-size empty shell - Fixed `showPanel`/`hidePanel` not being idempotent: calling `showPanel` while the panel was already open re-ran the open animation, which briefly reset the panel height to `0` and made it look like the panel closed. Both methods now return early when the panel is already in the target state ### Docs - Added npm version, downloads, license, build, TypeScript and stars badges to both READMEs - Added a live demo screenshot to both READMEs ## 2.0.7 ### Fixes - Fixed the picker panel being covered by overlay masks in Element Plus Dialog and similar layered containers: the panel `z-index` was fixed at `1000` in the stylesheet while overlay libraries start at `2000` and increase on every open. The panel now raises its inline `z-index` to one above the highest ancestor level each time it opens, leaves normal pages to the stylesheet default, and falls back silently if reading or writing styles fails ### Tests - Added regression tests for automatic `z-index` elevation inside layered containers, recomputation on repeated opens, and the untouched inline style on normal pages ## 2.0.6 ### Fixes - Fixed `colorRgbaToHsva` turning a valid alpha of `0` into `1` (`parseFloat(...) || 1` treated `0` as falsy), which made fully transparent colors opaque once hue or saturation/value was adjusted and made `getHsvaColor()` return `a: 1` - Fixed `colorRgbaToHsla` returning `colorObj.h` on the internal `0-6` scale instead of degrees, which broke the round trip through `colorHslaToRgba` (e.g. green `rgba(0, 202, 136, 1)` came back as `rgba(204, 10, 0, 1)`) ### Tests - Added regression tests for the `rgba(..., 0)` round trip, the unparseable-alpha fallback and the HSL hue / round trip ### Release - Added a GitHub Actions CI workflow running dependency install, the full test suite and a full package build on pushes and pull requests to `master` - Declared `rimraf` as a dev dependency of `utils` and `core` so clean builds work under pnpm's strict `node_modules` layout ## 2.0.5 ### Fixes - Fixed panel positioning inside drawers, modals and scroll containers: new `boundary` option accepts a CSS selector or HTMLElement, clamping the panel within that container's visible area instead of only the viewport - Fixed `document.mousedown` listener leaking after `destroy()` when the panel show timer fired after destruction; the callback now bails out if the instance is already destroyed - Fixed root `build:xxx` shortcuts silently doing nothing (`pnpm -r build:xxx` matched no package scripts); replaced with `pnpm --filter build` and added missing shortcuts for gradient, select, checkbox, copy-color and input-number ### Refactor - Consolidated drag logic into `utils/drag.ts`: new `getRatio`, `bindMouseDrag` and `bindTouchDrag` utilities, reused by hue, alpha, panel and gradient; eliminates ~10 `as EventListener` casts - Extracted `DEFAULT_PANEL_WIDTH` / `DEFAULT_PANEL_HEIGHT` constants, replacing 7 hard-coded `285 / 180` occurrences across panel and gradient - Unified on utility functions: `isString` / `isObject` / `isBoolean` / `isNumber` replace raw `typeof` checks; `$` and `getRect` replace direct `querySelector` / `getBoundingClientRect` calls - Removed `as any` casts in plugin options initialization; `install(core: any)` aligned to `install(core: ewColorPicker)` across all plugins - `getPrefix` now uses `isString` and accepts `ewColorPicker` instance type instead of `any` - Removed unused `eventType` dead code from utils - Documented the implicit `applyOrder` sorting convention: plugins without `applyOrder` default to 0 and run before all `Post` plugins ### Docs - Added `boundary` option documentation (English and Chinese) with usage examples - Added example page `18-panel-boundary.html` demonstrating container-bound panel positioning - Fixed docs site footer friend links showing Chinese text on the English version - Added missing example navigation links (15-18) to the examples index ### Release - Added `prepublishOnly: "npm run build"` to all packages so dist is rebuilt before every publish ## 2.0.4 ### Features - New `@ew-color-picker/select` component and plugin: custom option lists with placeholder, sizes, keyboard navigation, click-outside closing and ARIA support, an optional clear icon via `selectClearable`, and `selectItems` / `selectValue` / `selectPlaceholder` / `onSelectChange` / `onSelectClear` options. Renders only when `selectItems` is non-empty - New `@ew-color-picker/gradient` plugin: a gradient editor with draggable stops, linear/radial/conic types, repeating gradients, angle and position controls, double-position stops, and interpolation hints (`srgb`, `srgb-linear`, `hsl`, `oklab`, `oklch`). CSS strings round-trip through `parseGradient` / `serializeGradient`, and the editor is hidden unless `showGradient: true` or `gradient` / `gradientStops` is provided - New `@ew-color-picker/checkbox` component and plugin: replaces the native checkbox visual with a themed box while keeping the underlying native input for semantics and keyboard support. The plugin renders in the bottom row when `checkboxLabel` is provided and supports `showCheckbox` / `checkboxChecked` / `checkboxDisabled` / `onCheckboxChange` - The aggregate package now exports a `createEwColorPicker(options)` factory, and the `ew-color-picker` compat entry exposes the same factory ### Fixes - Fixed `defaultColor` handling: instance plugins are not created yet at that point, so the check now reads the static plugin registry to see whether the alpha plugin is registered; without alpha, an rgba default correctly falls back to hex - Fixed the hue bar background, panel cursor and hue / alpha thumb positions being wrong when the panel opens without an initial color (or with a color set later): everything is re-synced against the current color once the panel is shown - Fixed the panel width calculation for different hue / alpha direction combinations, which pushed same-row elements onto a new line and misaligned the edges - Fixed `colorRgbaToHsva` only accepting rgba strings; it now also handles hex / rgb / color keywords - Fixed the gradient editor stop-row layout: number inputs clipped their values and the Remove / Add buttons were pushed onto a new line; inputs are now wider with compact steppers and tighter gaps so everything fits on one row ## 2.0.3 > This release has been published to npm and the docs site has been updated. ### Features - New `@ew-color-picker/eyedropper` plugin: sample colors from anywhere on screen through the native EyeDropper API. It detects browser support, writes the result with `core.setColor()`, supports `showEyedropper` / `eyedropperText` / `onEyedropperPick`, and silently ignores `AbortError` when the user cancels - New `@ew-color-picker/copy-color` plugin: copy the current color to the clipboard with one click. The button is filled with the current color and uses contrast-aware icons, prefers the async Clipboard API with a `execCommand` fallback, shows a short built-in success toast, and supports `showCopyColor` / `copyColorText` / `copiedText` / `onCopyColor` - The eyedropper and copy buttons now live in their own toolbar row above the color value input, instead of sharing the row with the Clear / Sure buttons ### Fixes - Fixed the InputNumber stepper arrows: they now carry the correct icon class and render at 10px, staying centered inside the button instead of overflowing and being clipped by the divider - Fixed RGB / HSL channel inputs resetting to `0` on the first stepper click; internal values are now synced with the current color so increment/decrement starts from the current channel value ## 2.0.2 ### Fixes - Published package manifests now reference the matching release version (`^2.0.2`) for internal dependencies instead of the stale `^2.0.0` range. This prevents mixed installs where a 2.0.1 plugin resolved an older `@ew-color-picker/utils` that did not export `getPrefix` ## 2.0.1 > These changes have been published to npm and are reflected in the docs site. ### Fixes - Fixed plugin switches being overridden: `ewColorPickerPanel: false` and `ewColorPickerColorMode: false` (or an object config) were replaced by defaults and did not take effect - Panel container now declares `box-sizing: content-box`, no longer relying on the host global `box-sizing` reset - Removed viewport media queries (`max-width: 768px`) that hard-coded panel, input and preset sizes; inner sizes are now driven solely by `--panel-width` / `--panel-height` - Predefined swatches now use flex wrapping; removed the hard-coded "10 per row" rule that caused wrong wrapping when the swatch count or container width changed - `use()` now deduplicates by `pluginName`, preventing duplicate registration under HMR, repeated imports or multiple entry points - Plugin constructor errors are now reported through `console.warn` with the plugin name and error details instead of being silently swallowed, making custom plugin debugging easier ### Features - New `appendTo` option: mount the panel container into `document.body` or any container to avoid `overflow` clipping by dialogs, drawers and scroll containers. The panel then uses viewport-relative positioning, still honors `panelPlacement` with boundary flipping, and re-positions on scroll or resize - New `prefix` option: customize the prefix of every CSS class name (default `ew-`) to avoid style collisions when embedding the picker in another library. The SCSS build exposes a matching `$prefix` variable that must stay in sync with the JS option - `ApplyOrder` changed from `const enum` to a regular enum, so it can be imported at runtime from `@ew-color-picker/utils` without hand-writing `'pre'` / `'post'` strings ### Documentation - Corrected predefined swatch and number input class names to match the source - Removed the non-existent nested `ewColorPickerBox` config in favor of top-level options - Corrected the prerequisites of `autoPanelPosition` - Added `appendTo` documentation (Chinese and English) - Added `prefix` documentation (Chinese and English) with a custom SCSS build example - Added `applyOrder` execution-order documentation and examples (Chinese and English) - The docs site now defaults to English; Chinese docs moved under `/zh/`, and the README defaults to English ## 2.0.0 First stable release: core + plugin architecture, 14 packages (13 scoped packages plus the unscoped `ew-color-picker` entry package), bilingual docs site and live demo. ## Comparison & Positioning Source: https://eveningwater.github.io/ew-color-picker/guide/comparison # Comparison & Positioning Choosing a color picker is rarely about feature count — it is about whether the component fits your UI system. This page states the positioning first, then compares the mainstream options, and finally explains when each one is the right call. ## Positioning in one sentence ew-color-picker is not a ready-made skin. It is an **assemblable color picker foundation**: the core only keeps color state and events, and every UI element is an independent plugin. Teams keep what they need, replace what they do not, or write their own UI on the same plugin contract. Good fit: admin dashboards, low-code platforms, component libraries, and products that must merge deeply with an existing design system. Poor fit: a one-off color input where customization is unnecessary — the native `input[type=color]` or Coloris is simpler. ## Side-by-side comparison The numbers below come from the npm registry (`unpackedSize` and last publish date, collected on 2026-10-30) and are only a sense of package size. Feature columns follow each project's public documentation. | Option | Shape | Framework lock-in | Extension model | Unpacked size | Last publish | | --- | --- | --- | --- | --- | --- | | **ew-color-picker** | Aggregate package + 14 plugin packages (plus the `ew-color-picker` compat entry) | None (plain DOM) | Plugin registration / custom plugins | Aggregate 84.6 KB + styles 36.1 KB (120.7 KB total); `core.min` 11.9 KB (gzip 3.9 KB) | 2026-10 | | [Pickr](https://github.com/Simonwep/pickr) | Single package (UMD/ESM) | None | Themes (classic/monolith/nano) + options | 280.3 KB | 2026-09 | | [iro.js](https://github.com/jaames/iro.js) | Single package | None | Options + component composition | 231.4 KB | 2021-07 | | [Coloris](https://github.com/melloware/coloris) | Single package + CSS | None | CSS variables + options | 152.2 KB | 2026-10 | | [react-colorful](https://github.com/omgovich/react-colorful) | React components | React | Compose components | 398.4 KB | 2026-09 | | [react-color](https://github.com/casesandberg/react-color) | React component set | React | Pick a picker component | 436.3 KB | 2020-10 | | [vue-color](https://github.com/linx4200/vue-color) | Vue component set | Vue | Pick a picker component | 391.5 KB | 2025-10 | | [@uiw/react-color](https://github.com/uiwjs/react-color) | React component set | React | Import per component | 210.8 KB | 2026-05 | | Native `input[type=color]` | Built into browsers | None | None (styling is not controllable) | 0 | with browser updates | | Spectrum | jQuery plugin | jQuery | Options | 1804.2 KB | 2020-05 | One caveat: unpacked size is not runtime cost. The aggregate package ships two artifacts (UMD.min and ESM) plus `.d.ts` declarations. The smallest runtime you can ship is `index.min.js` at **81.8 KB (gzip 19.4 KB)**, or **11.9 KB (gzip 3.9 KB)** when using the core alone. Add the two style sheets (about 3.7 KB gzipped) for the full out-of-the-box footprint — roughly 29 KB of tarballs in total. ## Where ew-color-picker stands out ### 1. Structural replaceability, not just theming Most alternatives let you restyle the widget via themes, CSS variables or options while the structure stays fixed. ew-color-picker splits the trigger box, saturation panel, hue slider, alpha slider, text input, number input, buttons, predefined swatches and mode switcher into separate plugins. You decide which ones are registered, in what order, and whether your own plugin replaces them. ```ts import ewColorPicker from '@ew-color-picker/core' import Panel from '@ew-color-picker/panel' import Hue from '@ew-color-picker/hue' // register only what you need ewColorPicker.use(Panel).use(Hue) ``` ### 2. Framework agnostic The core touches plain DOM and events only — no React, Vue or jQuery runtime. The same plugin contract can back React, Vue, Angular or low-code wrappers without maintaining a separate implementation per framework. ### 3. Single source of truth with per-instance events Every plugin changes color through `core.setColor()`, and the `change` event keeps the rest in sync, so there is never a second copy of the color state. Each instance owns its event bus, DOM and plugin instances, so multi-instance pages do not leak into each other. ### 4. Complete out of the box The aggregate package (or the `ew-color-picker` compat entry) ships Hex / RGB / HSL mode switching, alpha adjustment, predefined swatches, clear/confirm buttons and input validation — things you would otherwise assemble by hand on top of react-colorful. ### 5. TypeScript types everywhere Every package emits `.d.ts`; plugins extend the core options via `declare module`, so custom plugins keep type inference too. ### 6. Documentation as part of the product Bilingual documentation, per-API references, one page per plugin, plus `llms.txt` / `llms-full.txt` so both people and AI can look things up. ## Limitations to be honest about - **Small ecosystem**: download counts, community tutorials and issue history cannot match Pickr or react-color; unusual problems mean reading the source. - **No official framework wrappers**: React / Vue / Angular / Solid integration is covered in [Framework Integration](./framework-integration); controlled components and SSR need a thin wrapper of your own (around 20 lines). - **Gradients and screen sampling are optional plugins**: linear / radial / conic gradient editing ships as the optional `@ew-color-picker/gradient` plugin, and screen sampling as `@ew-color-picker/eyedropper` (Chromium-based browsers). For heavier color-space math and visualization work, iro.js is still the better fit. - **The plugin model only matters when you customize**: installing the aggregate package or `npm i ew-color-picker` works out of the box; you only need to understand core + plugins when replacing part of the UI or wiring your own plugins. - **Shrinking further means installing sub-packages**: the aggregate is 84.6 KB plus 36.1 KB of styles, already in Coloris territory; if you use a single piece, install plugin packages and trim down to the 11.9 KB core. ## Choosing the right tool | Your situation | Recommendation | | --- | --- | | A plain color input; styling does not matter | Native `input[type=color]` | | Lightweight, dependency-free, themeable without structural changes | Coloris or Pickr | | React project that only needs a panel or slider | react-colorful | | Vue project that wants ready-made components | vue-color or @uiw/react-color | | Sample colors from anywhere on screen | **ew-color-picker** (optional Eyedropper plugin, Chromium-based browsers) | | Gradients, color-space work, games or visualizations | iro.js | | Admin / low-code / component library needing deep design-system integration, partial UI replacement and instance isolation | **ew-color-picker** | | Embedding color selection into your own plugin system or runtime | **ew-color-picker** (11.9 KB core, keep the core and write your own plugins) | ## See also - [Introduction](./) — design principles and package layout - [Core Concepts](./concepts) — mount points, plugin order and events - [Writing a Plugin](./plugin-dev) — replace the built-in UI with your own ## Core Concepts Source: https://eveningwater.github.io/ew-color-picker/guide/concepts # Core Concepts ## Instance-level event bus Every instance extends `EventEmitter` and registers exactly these event types: ```ts ['destroy', 'change', 'sure', 'clear', 'toggle', 'options-update', 'mode-change'] ``` `on` / `once` / `off` / `trigger` / `emit` are available on the instance. Unknown event names log a warning instead of throwing. | Method | Behaviour | | --- | --- | | `on(type, fn)` | Add a listener | | `once(type, fn)` | Add a one-shot listener | | `off(type?, fn?)` | Remove one listener, all listeners of a type, or everything | | `trigger(type, ...args)` | Run listeners directly; `return true` from a listener stops the rest | | `emit(type, ...args)` | Like `trigger`, but also invokes the matching `options` callback (`clear`, `sure`, `togglePicker`) | ## Mount points When mounting, the core creates: ```html
…
``` | Mount point | Access | Used by | | --- | --- | --- | | `root` | `core.getMountPoint('root')` | Box | | `panelContainer` | `core.getMountPoint('panelContainer')` | Panel, Hue, Alpha, Input, InputNumber, Button, Predefine, ColorMode | The panel container is hidden with the `-hidden` class and revealed when the panel opens. ## Plugin apply order | Value | Meaning | | --- | --- | | `ApplyOrder.Pre` (`-1`) | Runs before the core's default logic | | `ApplyOrder.Post` (`1`) | Runs after the core's default logic | | not set | Runs in registration order | All built-in UI plugins use `Post`. ## Single color entry `core.setColor(color)` is the only supported way to change color. It: 1. Normalises the color (hex ↔ rgba depending on the Alpha plugin); 2. Updates `currentColor` and `hsvaColor`; 3. Emits `change`; 4. Calls `options.changeColor(color)`. Plugins must subscribe to `change` instead of polling `currentColor`. ## Plugin registry ```ts ewColorPicker.plugins // array of registered { name, applyOrder, ctor } ewColorPicker.pluginsMap // { [pluginName]: true } core.plugins // instance map: { [pluginName]: instance } ``` `core.plugins.ewColorPickerPanel`, `core.plugins.ewColorPickerAlpha`, etc. expose each plugin instance. ## Instance isolation Each instance gets: - its own event bus, - its own `data-uid`, - its own DOM subtree, - its own plugin instances. That is why multiple instances never share colors. Always scope DOM queries to the current wrapper. ## Lifecycle ```text new ewColorPicker(options) → normalize options → init state (currentColor, hsvaColor, mode) → mount(el) if el provided → create root + panelContainer → apply plugins (Pre → default → Post) → sync hue/alpha picker.destroy() → emit destroy → plugin.destroy() → remove DOM and listeners → mark instance as destroyed ``` ## Next steps - [Write a plugin](./plugin-dev.md) - [Events](../api/events.md) - [Methods](../api/methods.md) ## Framework Integration Source: https://eveningwater.github.io/ew-color-picker/guide/framework-integration # Framework Integration ew-color-picker depends only on plain DOM and events — no framework runtime — so the same approach works everywhere: **create the instance on mount, call `destroy()` on unmount, and sync controlled values through `setColor()`**. Below are minimal, copy-paste wrappers for four frameworks. No official framework packages are published; the reasoning is covered in [Comparison & Positioning](./comparison). ## Common rules 1. **One instance per mount point**: `el` accepts either a selector string or a DOM element; prefer the element reference so multiple pickers never collide on selectors. 2. **Always call `destroy()` on unmount**: the instance registers a `document` click listener. Leaking it breaks other instances by toggling their panels. 3. **Guard controlled sync against loops**: call `setColor()` when the external value changes, but `setColor()` fires `change` again — compare the incoming value first. 4. **Import both stylesheets**: `index.css` and `input-number.css` (the number input styles ship in a separate file). 5. **SSR safety**: create the instance only in browser-side lifecycle hooks (`useEffect` / `onMounted` / `ngAfterViewInit` / `onMount`). ```ts import ewColorPicker from '@ew-color-picker/ew-color-picker' import '@ew-color-picker/style/dist/index.css' import '@ew-color-picker/style/dist/input-number.css' ``` ## React ```tsx import { useEffect, useRef } from 'react' import ewColorPicker from '@ew-color-picker/ew-color-picker' import '@ew-color-picker/style/dist/index.css' import '@ew-color-picker/style/dist/input-number.css' interface Props { value: string onChange: (color: string) => void } export function ColorField({ value, onChange }: Props) { const hostRef = useRef(null) const pickerRef = useRef(null) useEffect(() => { const picker = new ewColorPicker({ el: hostRef.current!, defaultColor: value, }) picker.on('change', (color: string) => onChange(color)) pickerRef.current = picker return () => { picker.destroy() pickerRef.current = null } }, []) useEffect(() => { pickerRef.current?.setColor(value) }, [value]) return
} ``` React 19 StrictMode mounts effects twice; the `return () => picker.destroy()` cleanup above prevents leftover instances. ## Vue 3 ```vue ``` Usage is the standard `v-model`: ```vue ``` ## Angular ```ts import { AfterViewInit, Component, ElementRef, EventEmitter, Input, OnDestroy, Output, ViewChild, } from '@angular/core' import ewColorPicker from '@ew-color-picker/ew-color-picker' @Component({ selector: 'ew-color-field', standalone: true, template: '
', }) export class ColorFieldComponent implements AfterViewInit, OnDestroy { @ViewChild('host', { static: true }) host!: ElementRef @Input() value = '#ffffff' @Output() valueChange = new EventEmitter() private picker?: ewColorPicker ngAfterViewInit(): void { this.picker = new ewColorPicker({ el: this.host.nativeElement, defaultColor: this.value, changeColor: (color: string) => this.valueChange.emit(color), }) } ngOnDestroy(): void { this.picker?.destroy() } } ``` Use it with two-way binding: ```html ``` ## Solid ```tsx import { onCleanup, onMount } from 'solid-js' import ewColorPicker from '@ew-color-picker/ew-color-picker' import '@ew-color-picker/style/dist/index.css' import '@ew-color-picker/style/dist/input-number.css' export function ColorField(props: { value: string; onChange: (color: string) => void }) { let host!: HTMLDivElement let picker: ewColorPicker | undefined onMount(() => { picker = new ewColorPicker({ el: host, defaultColor: props.value }) picker.on('change', (color: string) => props.onChange(color)) }) onCleanup(() => picker?.destroy()) return
} ``` Solid's fine-grained reactivity needs no extra plumbing: call `setColor()` inside a `createEffect` that reads `props.value`. ## FAQ **Can I pass a selector string?** Yes, `el: '#picker'` works. Inside a framework, prefer the element reference so duplicate ids cannot clash. **Why did another picker close my panel?** An instance was not destroyed on unmount, so its leftover `document` click listener toggles panels everywhere. **Does the `change` event loop forever?** Only when you write the value back to the component and the component writes it back with `setColor()`. Compare old and new values to break the loop. **Do I need official wrapper packages?** The code above is the complete wrapper. If a project uses it in several places, extract these twenty lines into your own component rather than depending on a third-party package. ## Quick Start Source: https://eveningwater.github.io/ew-color-picker/guide/getting-started # Quick Start ## 1. Prepare a container ```html
``` ```ts import ewColorPicker from '@ew-color-picker/ew-color-picker' import '@ew-color-picker/style/dist/index.css' import '@ew-color-picker/style/dist/input-number.css' ``` ## 2. Create an instance There are three equivalent ways to pass the container: ```ts // Selector new ewColorPicker({ el: '#picker', defaultColor: '#6366f1' }) // DOM element const el = document.getElementById('picker')! new ewColorPicker(el, { defaultColor: '#6366f1' }) // Element in options object (same as the first form) new ewColorPicker({ el, defaultColor: '#6366f1' }) ``` Or use the `createEwColorPicker` factory, which is exactly `new ewColorPicker(options)` under the hood: ```ts import { createEwColorPicker } from '@ew-color-picker/ew-color-picker' // also available from the unscoped entry: import { createEwColorPicker } from 'ew-color-picker' const picker = createEwColorPicker({ el: '#picker', defaultColor: '#6366f1' }) ``` If `el` is provided, the picker **mounts automatically**. Without `el`, call `mount()` yourself later. ## 3. Listen for changes ```ts const picker = new ewColorPicker({ el: '#picker', defaultColor: '#6366f1', }) picker.on('change', (color) => { console.log('Current color:', color) }) picker.on('sure', (color) => { console.log('Confirmed:', color) }) ``` ## 4. A fuller example ```ts const picker = new ewColorPicker({ el: '#picker', defaultColor: '#6366f1', size: 'large', hueDirection: 'horizontal', alphaDirection: 'horizontal', predefineColor: ['#ef4444', '#22c55e', '#3b82f6', '#a855f7'], clearText: 'Reset', sureText: 'Apply', autoPanelPosition: true, panelPlacement: 'bottom-start', togglePickerAnimation: 'height', pickerAnimationTime: 250, }) picker.on('change', (color) => console.log('change', color)) picker.on('toggle', (open) => console.log('panel', open ? 'open' : 'closed')) picker.on('mode-change', (mode) => console.log('mode', mode)) ``` ## 5. Methods ```ts picker.getColor() // current color string picker.getHsvaColor() // { h, s, v, a } picker.setColor('#22c55e') // programmatic change (emits change) picker.showPanel() picker.hidePanel() picker.updateOptions({ size: 'small' }) ``` Full reference: [Methods](../api/methods.md). ## 6. Cleanup ```ts picker.destroy() ``` `destroy()` removes DOM, unbinds DOM events, clears listeners, and emits `destroy`. After destruction, most methods become no-ops; check `picker.getDestroyedStatus()`. ## Next steps - [Core concepts](./concepts.md) - [Options](../api/options.md) - [Plugin overview](../plugins/index.md) ## Introduction Source: https://eveningwater.github.io/ew-color-picker/guide/ # Introduction ew-color-picker is a modern color picker built around two ideas: 1. **Event-driven** — every action becomes an event (`change`, `sure`, `clear`, `toggle`, `mode-change`, `options-update`, `destroy`). 2. **Plugin-based** — the core owns color state and mount points; every piece of UI is a plugin. ```text Core (@ew-color-picker/core) ├─ color state: currentColor + hsvaColor ├─ event bus: on / once / off / trigger / emit ├─ mount points: root + panelContainer └─ plugins: can be registered, replaced, or extended ``` ## Why a plugin architecture? | Benefit | What it means | | --- | --- | | Small bundles | Install only the plugins you use | | Replaceable UI | Swap the panel, input, or buttons for your own implementation | | Testable | Each plugin can be tested in isolation | | Extensible | Add features without touching the core | ## The 17 packages | Package | Responsibility | | --- | --- | | `@ew-color-picker/core` | Color state, event bus, mount points, plugin registry | | `@ew-color-picker/utils` | DOM/color/animation helpers, `EventEmitter`, `Console` plugin | | `@ew-color-picker/style` | CSS (`index.css` + `input-number.css`) | | `@ew-color-picker/ew-color-picker` | All-in-one bundle: registers all plugins and re-exports the core | | `ew-color-picker` | Unscoped compat entry for v1 users; forwards the aggregate package and styles | | `@ew-color-picker/box` | Trigger swatch that opens/closes the panel | | `@ew-color-picker/panel` | Saturation/value 2D panel | | `@ew-color-picker/hue` | Hue slider (0–360°) | | `@ew-color-picker/alpha` | Alpha slider (0–1) | | `@ew-color-picker/input` | Text color input with validation | | `@ew-color-picker/input-number` | Numeric input component + plugin | | `@ew-color-picker/select` | Dropdown select component + plugin | | `@ew-color-picker/button` | Clear / Sure buttons | | `@ew-color-picker/predefine` | Predefined color swatches | | `@ew-color-picker/color-mode` | Hex / RGB / HSL mode switching | | `@ew-color-picker/eyedropper` | Screen color picker via the native EyeDropper API (Chromium) | | `@ew-color-picker/copy-color` | Copy the current color to the clipboard | ## Data flow ```text User interaction (Box / Panel / Hue / Alpha / Input / Predefine / Button) │ ▼ core.setColor(color) ← the only way to change color │ ├─► emit('change', color) │ ├─ Panel sync background + cursor │ ├─ Hue sync thumb │ ├─ Alpha sync thumb │ ├─ Input sync text │ ├─ ColorMode sync R/G/B or H/S/L inputs │ └─ Box sync background + icon color │ └─► options.changeColor(color) ``` ## Design principles | Principle | Detail | | --- | --- | | Single source of truth | Only `core.setColor()` changes color; plugins never call each other directly | | Instance isolation | Each instance has its own event bus, DOM and plugin instances | | No global pollution | CSS is scoped by class names; the only global is the UMD `window.ewColorPicker` | | Progressive disclosure | Defaults work out of the box; every plugin exposes options and methods when you need them | ## Next steps - [Installation](./installation.md) - [Quick start](./getting-started.md) - [Core concepts](./concepts.md) - [Write a plugin](./plugin-dev.md) ## Installation Source: https://eveningwater.github.io/ew-color-picker/guide/installation # Installation ## Requirements | Item | Requirement | | --- | --- | | Node.js | 20.10+ (for building and running the docs) | | Package manager | pnpm (workspace) / npm / yarn | | Browser | Any modern browser (ES2019+) | ## All-in-one bundle ```bash pnpm add @ew-color-picker/ew-color-picker @ew-color-picker/style ``` ```ts import ewColorPicker from '@ew-color-picker/ew-color-picker' import '@ew-color-picker/style/dist/index.css' import '@ew-color-picker/style/dist/input-number.css' const picker = new ewColorPicker({ el: '#app' }) ``` ::: warning Two stylesheets `index.css` covers the picker. `input-number.css` is required for the numeric inputs used by RGB/HSL modes. Import both. The optional `select.css` is only needed for the Select component. ::: To keep the v1 package name, install the unscoped entry package instead — it is equivalent: ```bash npm install ew-color-picker ``` ::: tip About the package name `ew-color-picker` is a thin compatibility entry for v2. It only forwards to `@ew-color-picker/ew-color-picker` and `@ew-color-picker/style`; it contains no implementation code. ::: ## Upgrading from v1 v2 is a breaking rewrite; v1 and v2 APIs cannot be mixed: - **Architecture**: v1 was a single configurable package; v2 splits into 16 packages plus a compat entry where every UI part is a plugin, composable via `Core.use(Plugin)` - **Package name**: `ew-color-picker` remains the entry, but now points to `@ew-color-picker/ew-color-picker` - **Styles**: both `index.css` and `input-number.css` must be imported explicitly - **Options and events**: plugin options such as `hasAlpha` and `hasBox` differ from v1; re-integrate against the live demo on this site To stay on the old version, pin `ew-color-picker@1`; the v1 source is preserved on the `v1` branch. ## Per-package imports The core has no UI. Register only what you need: ```bash pnpm add @ew-color-picker/core @ew-color-picker/style \ @ew-color-picker/box @ew-color-picker/panel @ew-color-picker/hue \ @ew-color-picker/input @ew-color-picker/button ``` ```ts import ewColorPicker from '@ew-color-picker/core' import Box from '@ew-color-picker/box' import Panel from '@ew-color-picker/panel' import Hue from '@ew-color-picker/hue' import Input from '@ew-color-picker/input' import Button from '@ew-color-picker/button' ewColorPicker.use(Box).use(Panel).use(Hue).use(Input).use(Button) new ewColorPicker({ el: '#app' }) ``` `use()` returns the class itself, so calls can be chained. It is idempotent — registering the same constructor twice does nothing. ## UMD via ` ``` The UMD build exposes `window.ewColorPicker`. ## TypeScript All packages ship declaration files. Types are exported from the core and from each plugin package: ```ts import type { ewColorPickerOptions, ewColorPickerConstructorOptions } from '@ew-color-picker/core' import type { InputNumberOptions } from '@ew-color-picker/input-number' const options: ewColorPickerConstructorOptions = { el: '#app', defaultColor: '#6366f1', } ``` ## Repository development ```bash pnpm install # install workspace dependencies pnpm run build:all # build every package + styles pnpm run dev:preview# live-reload example server pnpm run test:run # run the full vitest suite pnpm run docs:dev # start the documentation site ``` ## Next steps - [Quick start](./getting-started.md) - [Core concepts](./concepts.md) - [Options reference](../api/options.md) ## Writing a Plugin Source: https://eveningwater.github.io/ew-color-picker/guide/plugin-dev # Writing a Plugin A plugin is a plain class. The core only requires two static properties and a constructor. ## Minimal template ```ts import type ewColorPicker from '@ew-color-picker/core' import { ApplyOrder, create, addClass, insertNode, isFunction } from '@ew-color-picker/utils' export default class MyBadgePlugin { static pluginName = 'myBadge' static applyOrder = ApplyOrder.Post el: HTMLElement | null = null constructor(public ewColorPicker: ewColorPicker) { this.run() if (isFunction(this.ewColorPicker.on)) { this.ewColorPicker.on('change', this.handleChange) } } run() { const panelContainer = this.ewColorPicker.getMountPoint('panelContainer') if (!panelContainer) return this.el = create('span') addClass(this.el, 'my-badge') insertNode(panelContainer, this.el) this.renderColor(this.ewColorPicker.getColor()) } handleChange = (color: string) => { this.renderColor(color) } renderColor(color?: string) { if (this.el) this.el.textContent = color || 'no color' } destroy() { if (isFunction(this.ewColorPicker.off)) { this.ewColorPicker.off('change', this.handleChange) } this.el?.parentNode?.removeChild(this.el) this.el = null } } ``` ## Register it ```ts import ewColorPicker from '@ew-color-picker/core' import MyBadgePlugin from './my-badge' ewColorPicker.use(MyBadgePlugin) new ewColorPicker({ el: '#app' }) ``` `use()` is chainable and idempotent. ## Contract | Member | Required | Notes | | --- | --- | --- | | `static pluginName` | Yes | Unique key in `core.plugins`; missing name logs a warning | | `static applyOrder` | No | `ApplyOrder.Pre` (first) / unset (registration order) / `ApplyOrder.Post` (last) | | `constructor(core)` | Yes | Receives the instance; render + subscribe here | | `destroy()` | No | Unbind DOM events and listeners | | `install(core)` | No | Support manual `plugin.install(core)` usage | | `updateOptions()` | No | Called when `core.updateOptions()` broadcasts `options-update` | ## Rules 1. Change colors only via `core.setColor()`. 2. Subscribe to `change` rather than reading state in loops. 3. Render only into `root` or `panelContainer`. 4. Scope DOM queries to your own wrapper. 5. Clean up everything in `destroy()`. ## Execution order (`applyOrder`) `static applyOrder` is optional and controls construction order. Values come from the `ApplyOrder` enum in `@ew-color-picker/utils` (compiled as a regular runtime enum): | Value | Weight | When to use | | --- | --- | --- | | `ApplyOrder.Pre` | `-1` | Create shared nodes, containers or global state before other plugins | | unset | `0` | Default; runs in `ewColorPicker.use()` registration order | | `ApplyOrder.Post` | `1` | Read DOM already rendered by other plugins | Plugins with the same weight run in registration order, so the default behavior stays deterministic. `applyOrder` only affects construction time, not event callback order. ```ts import { ApplyOrder } from '@ew-color-picker/utils' export default class MyOverlayPlugin { static pluginName = 'myOverlay' static applyOrder = ApplyOrder.Pre // build the overlay container first // ... } ``` Omit `applyOrder` when your plugin only subscribes to events and doesn't depend on other plugins' DOM. ## Type augmentation Declare your options on the core's `CustomOptions` interface: ```ts declare module '@ew-color-picker/core' { interface CustomOptions { myBadge?: { label?: string } } } ``` Now `new ewColorPicker({ myBadge: { label: 'Hi' } })` type-checks. ## Lifecycle summary ```text Core.use(Plugin) → registered statically new ewColorPicker → creates instance, calls constructor mount(el) → mount points exist, plugins render updateOptions() → updateOptions() + options-update event destroy() → destroy() called, DOM removed ``` ## Next steps - [Plugin overview](../plugins/index.md) - [Core concepts](./concepts.md) - [Events](../api/events.md) ## Plugin Architecture Source: https://eveningwater.github.io/ew-color-picker/

Try it now

A real, running color picker rendered directly from the built artifacts.

Minimal example

One container, one stylesheet, one constructor call.

```html
``` ## Alpha Plugin Source: https://eveningwater.github.io/ew-color-picker/plugins/alpha # Alpha `ewColorPickerAlpha` adds an alpha slider (0–1). Registering it changes how the core normalizes colors: - **Registered**: hex `defaultColor` becomes `rgba()` - **Not registered**: `rgba()` `defaultColor` becomes hex | Item | Value | | --- | --- | | Package | `@ew-color-picker/alpha` | | `pluginName` | `ewColorPickerAlpha` | | `applyOrder` | `Post` | | Mount point | `panelContainer` | | Instance | `core.plugins.ewColorPickerAlpha` | ## Options | Option | Type | Default | Description | | --- | --- | --- | --- | | `alpha` | `boolean` | `true` | `false` hides the slider | | `alphaDirection` | `'horizontal' \| 'vertical'` | `'vertical'` | Orientation | | `disabled` | `boolean` | `false` | Blocks interaction | ## Methods | Method / property | Signature | Description | | --- | --- | --- | | `enableAlpha` | `(enable = true) => void` | Show/hide | | `updateAlpha` | `(alpha: number) => void` | Apply alpha (0–1) via `setColor()` | | `updateAlphaThumbPosition` | `(alpha: number) => void` | Move thumb only | | `hasAlpha` | `boolean` getter/setter | Re-renders on change | | `alphaBar` / `alphaThumb` | `HTMLElement \| null` | DOM | | `isHorizontal` | `boolean` | Orientation flag | `updateAlpha` also syncs ColorMode inputs when the current mode is not `hex`. ## Behaviour | Action | Result | | --- | --- | | Click | Alpha computed from position (horizontal: right → left increases) | | Drag | Throttled 16ms | | External change | Thumb syncs | Return early when no current color exists. ## Events ```ts picker.on('change', (color) => console.log(color)) // rgba(...) ``` ## DOM ```html
``` ## Example ```ts const picker = new ewColorPicker({ el: '#app', defaultColor: 'rgba(99, 102, 241, 0.6)', alphaDirection: 'horizontal', }) picker.plugins.ewColorPickerAlpha.updateAlpha(0.5) ``` ## Related - [Hue](./hue.md) · [ColorMode](./color-mode.md) ## Box Plugin Source: https://eveningwater.github.io/ew-color-picker/plugins/box # Box `ewColorPickerBox` is the square trigger showing the current color. | Item | Value | | --- | --- | | Package | `@ew-color-picker/box` | | `pluginName` | `ewColorPickerBox` | | `applyOrder` | not declared | | Mount point | `root` | | Instance | `core.plugins.ewColorPickerBox` | ## Options | Option | Type | Default | Description | | --- | --- | --- | --- | | `defaultColor` | `string` | `''` | Initial color / clear target | | `size` | string, number, object | `'normal'` | Swatch size | | `disabled` | `boolean` | `false` | Blocks clicks | | `readonly` | `boolean` | `false` | Blocks clicks, keeps styles | | `hasBox` | `boolean` | `true` | Hide the swatch | | `boxNoColorIcon` | `string` | `''` | Custom "no color" icon HTML | | `boxHasColorIcon` | `string` | `''` | Custom "has color" icon HTML | | `className` | `string` | `''` | Extra class | | `style` | `string \| object` | `''` | Inline styles | | `onClick` | `(box) => void` | — | Click callback | | `onMouseEnter` / `onMouseLeave` | `(box) => void` | — | Hover callbacks | ### size | Form | Result | | --- | --- | | `mini` / `small` / `normal` / `medium` / `large` | 20 / 24 / 32 / 36 / 40px | | `48` | 48px | | `{ width: '60px', height: '36px' }` | custom | | `'5rem'` | verbatim | Icon sizes: `mini` 12px, `small` 14px, `normal` 16px, `medium` 18px, `large` 20px; numbers/objects use 50% of the shorter side. ### Icon contrast - Luminance > 0.5 → `#333333` - otherwise → `#ffffff` - translucent colors are blended over white first ## Methods | Method | Signature | Description | | --- | --- | --- | | `enableBox` | `(enable = true) => void` | Show/hide | | `update` | `(keys?: string[]) => void` | Refresh selected keys | | `updateChildren` | `() => void` | Recompute icon | | `setBoxSize` | `() => void` | Reapply size | | `setBoxBgColor` | `(color?: string) => void` | Set background | | `clearBoxBgColor` | `() => void` | Reset background | | `setBoxState` | `() => void` | Sync state classes | | `setDisabled` | `(disabled: boolean) => void` | Toggle disabled | | `bindMouseEvents` | `(onEnter?, onLeave?) => void` | Bind hover | | `unbindHandler` | `() => void` | Unbind DOM events | | `destroy` | `() => void` | Remove | Properties: `hasBox` (getter/setter), `box` (`HTMLElement | null`). ## Behaviour Clicking calls `showPanel()` or `hidePanel()` with `togglePickerAnimation` / `pickerAnimationTime`, then `onClick(boxPlugin)`. With `disabled` or `readonly`, the click is prevented. ```ts picker.on('toggle', (open) => console.log(open)) picker.on('change', (color) => console.log(color)) ``` ## DOM ```html
``` | Class | Meaning | | --- | --- | | `.ew-color-picker-box` | Root | | `.ew-color-picker-box-arrow-icon` | Has-color icon | | `.ew-color-picker-box-close-icon` | No-color icon | | `.is-disabled` / `.is-readonly` | States | ## Example ```ts new ewColorPicker({ el: '#app', defaultColor: '#6366f1', size: 'large', onClick: (box) => console.log('clicked', box.hasBox), }) ``` ## Related - [Panel](./panel.md) · [Options · size](../api/options.md#size) ## Button Plugin Source: https://eveningwater.github.io/ew-color-picker/plugins/button # Button `ewColorPickerButton` renders the Clear and Sure buttons. Clear restores the default color and closes the panel; Sure submits the current color and closes the panel. | Item | Value | | --- | --- | | Package | `@ew-color-picker/button` | | `pluginName` | `ewColorPickerButton` | | `applyOrder` | `Post` | | Mount point | `panelContainer` → `.ew-color-picker-bottom-row` | | Instance | `core.plugins.ewColorPickerButton` | ## Options | Option | Type | Default | Description | | --- | --- | --- | --- | | `showButton` | `boolean` | `true` | Hide both buttons | | `hasClear` | `boolean` | `true` | Hide Clear | | `hasSure` | `boolean` | `true` | Hide Sure | | `clearText` | `string` | `'清空'` | Clear label | | `sureText` | `string` | `'确定'` | Sure label | | `disabled` | `boolean` | `false` | Disable both | `hasClear` / `hasSure` apply at construction; use `enableClear` / `enableSure` / `enableButtons` at runtime. ## Methods | Method / property | Signature | Description | | --- | --- | --- | | `enableClear` | `(enable = true) => void` | Show/hide Clear | | `enableSure` | `(enable = true) => void` | Show/hide Sure | | `enableButtons` | `(enable = true) => void` | Both | | `hasClear` / `hasSure` | `boolean` getter/setter | Re-render | | `setClearText` | `(text: string) => void` | Change label | | `setSureText` | `(text: string) => void` | Change label | | `setDisabled` | `(disabled: boolean) => void` | Toggle `disabled` | | `updateOptions` | `() => void` | Re-read and redraw (deferred one frame) | | `onClearColor` | `() => void` | Clear logic (100ms debounce) | | `onSureColor` | `() => void` | Sure logic (100ms debounce) | | `clearButton` / `sureButton` | `HTMLButtonElement \| null` | DOM | ## Click behaviour ### Clear 1. Restore `defaultColor`, or clear if absent; 2. Sync `hsvaColor` (reset to `{h:0,s:100,v:100,a:1}` when empty); 3. `core.setColor(resetColor)`; 4. `core.syncAllPlugins(resetColor)`; 5. `core.hidePanel()`; 6. `options.clear?.(picker)`; 7. `core.trigger('clear')`. ### Sure 1. `options.sure?.(color, picker)`; 2. `core.trigger('sure', color, picker)`; 3. `core.hidePanel()`. ## Events & callbacks | Source | Signature | | --- | --- | | `options.clear` | `(picker) => void` | | `options.sure` | `(color, picker) => void` | | event `clear` | `()` | | event `sure` | `(color, picker)` | ## DOM ```html
``` ## Example ```ts const picker = new ewColorPicker({ el: '#app', defaultColor: '#8b5cf6', clearText: 'Reset', sureText: 'Use this color', clear: (instance) => console.log('after clear', instance.getColor()), sure: (color) => console.log('confirmed', color), }) ``` ## Related - [Events · clear / sure](../api/events.md) · [Options · clearText](../api/options.md#labels) ## Checkbox Plugin Source: https://eveningwater.github.io/ew-color-picker/plugins/checkbox # Checkbox `@ew-color-picker/checkbox` has two parts: 1. **Plugin** `ewColorPickerCheckbox` — renders a checkbox in the bottom row when `checkboxLabel` is provided; 2. **Component** `Checkbox` — a standalone controlled checkbox built on a native input for semantics and keyboard support, with a custom visual box. | Item | Value | | --- | --- | | Package | `@ew-color-picker/checkbox` | | `pluginName` | `ewColorPickerCheckbox` | | `applyOrder` | `Post` | | Mount point | `panelContainer` → `.ew-color-picker-bottom-row` (renders only when `checkboxLabel` is set) | | Access instance | `core.plugins.ewColorPickerCheckbox` | ::: warning Additional styles required ```ts import '@ew-color-picker/style/dist/checkbox.css' ``` Without it the checkbox has no visual. ::: ## Options | Option | Type | Default | Description | | --- | --- | --- | --- | | `showCheckbox` | `boolean` | `true` | Set to `false` to hide the checkbox | | `checkboxLabel` | `string` | `undefined` | Label text; nothing renders when empty | | `checkboxChecked` | `boolean` | `false` | Initial checked state | | `checkboxDisabled` | `boolean` | `false` | Disable interaction | | `onCheckboxChange` | `(checked: boolean) => void` | - | Fired after the user toggles the checkbox | ```ts import ewColorPicker from '@ew-color-picker/core' import Checkbox from '@ew-color-picker/checkbox' ewColorPicker.use(Checkbox) new ewColorPicker({ el: '#app', checkboxLabel: 'Repeating', checkboxChecked: true, onCheckboxChange: (checked) => console.log(checked), }) ``` ## Plugin methods | Method | Signature | Description | | --- | --- | --- | | `createCheckbox` | `(options) => Checkbox` | Create a component instance | | `updateOptions` | `() => void` | Re-read options and re-render | | `run` | `() => void` | Render the checkbox when a label is present | | `destroy` | `() => void` | Remove the checkbox and release events | ## Checkbox component ```ts import { Checkbox } from '@ew-color-picker/checkbox' ``` ### Options | Option | Type | Default | | --- | --- | --- | | `checked` | `boolean` | `false` | | `label` | `string` | `''` | | `disabled` | `boolean` | `false` | | `size` | `'small' \| 'default' \| 'large'` | `'default'` | | `prefix` | `string` | `'ew-'` | | `onChange` | `(checked: boolean) => void` | - | ### Methods | Method | Signature | Description | | --- | --- | --- | | `isChecked` | `() => boolean` | Current checked state | | `setChecked` | `(checked, triggerChange?) => void` | Set state; pass `false` to skip `onChange` | | `setLabel` | `(label) => void` | Replace the label text | | `setDisabled` | `(disabled) => void` | Toggle the disabled state | | `getElement` | `() => HTMLLabelElement` | Root node | | `destroy` | `() => void` | Unbind events and remove the node | ## Accessibility The component keeps a native `` visually hidden inside a `