tweakpane-plugin-color-plus
v0.7.3
Published
Advanced color handling for Tweakpane.
Downloads
4,701
Maintainers
Readme
tweakpane-plugin-color-plus

Advanced color handling for Tweakpane.
Overview
The Color Plus plugin adds support for handling wide color and many additional color formats to the Tweakpane UI library.
The plugin supports all CSS Color Module Level 4 formats and color spaces, along with color values stored as tuples or arrays, named-color strings, and several additional object formats. It also subtly extends the color-picker interface to accommodate wide-gamut colors.
Its API surface is a clean superset of Tweakpane's built-in color input, so it can work as a minimally-invasive drop-in replacement in existing projects that need support for modern color.
I originally developed this for the benefit of Svelte Tweakpane UI and Tweakpane CSS, but I've found myself reaching for it in vanilla Tweakpane projects as well.
Getting started
Dependencies
The plugin requires Tweakpane 4.
If you're using the "lite" build of the plugin without a bundler, you'll need to provide the @tweakpane/core library as well.
If you're using Svelte 4 or 5 as a front-end library, take a look at Svelte Tweakpane UI, which wraps Tweakpane in a set of Svelte-friendly components, including the <ColorPlus> control from this plugin.
Installation
NPM
npm install tweakpane-plugin-color-plusCDN
The package is published as an ES module, so import it from a module script (see the complete example below):
<script type="module">
import * as TweakpanePluginColorPlus from 'https://cdn.jsdelivr.net/npm/tweakpane-plugin-color-plus'
</script>Usage
Import and register the plugin, then pass view: 'color-plus' in the params of each addBinding call that should use it.
Note that the plugin does not automatically take over color values, you must pass view explicitly on the bindings you'd like to control with Color Plus.
From NPM
import { Pane } from 'tweakpane'
import * as TweakpanePluginColorPlus from 'tweakpane-plugin-color-plus'
const params = {
color: 'oklch(65% 0.26 357deg)',
}
const pane = new Pane()
pane.registerPlugin(TweakpanePluginColorPlus)
pane.addBinding(params, 'color', { view: 'color-plus' })
pane.on('change', () => {
document.documentElement.style.backgroundColor = params.color
})From CDN
<!doctype html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<title>Tweakpane Plugin Color Plus Demo</title>
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<script type="importmap">
{
"imports": {
"tweakpane": "https://cdn.jsdelivr.net/npm/tweakpane",
"tweakpane-plugin-color-plus": "https://cdn.jsdelivr.net/npm/tweakpane-plugin-color-plus"
}
}
</script>
<script type="module">
import { Pane } from 'tweakpane'
import * as TweakpanePluginColorPlus from 'tweakpane-plugin-color-plus'
const params = {
color: 'oklch(65% 0.26 357deg)',
}
const pane = new Pane()
pane.registerPlugin(TweakpanePluginColorPlus)
pane.addBinding(params, 'color', { view: 'color-plus' })
pane.on('change', () => {
document.documentElement.style.backgroundColor = params.color
})
</script>
</head>
<body></body>
</html>Options
In addition to Tweakpane's standard binding options, Color Plus accepts the options below. As with Tweakpane's built-in inputs, an unrecognized option value makes the plugin decline the binding, which surfaces as Tweakpane's No matching controller error.
Built-in color options
These options mirror Tweakpane's built-in color input, and behave the same way here.
color.alpha
For number values only: treat the number as carrying an alpha component in its lowest byte (e.g. 0xff00667f). Default false.
pane.addBinding(params, 'color', { view: 'color-plus', color: { alpha: true } })color.type
For object and tuple / array values only: whether channels are integers from 0–255 ('int', the default) or floats from 0–1 ('float'). (The built-in input only applies this to objects; tuple / array support is a Color Plus extension.)
pane.addBinding(params, 'color', { view: 'color-plus', color: { type: 'float' } })expanded
Start with the picker expanded. Default false.
picker
Where the picker appears: 'popup' (default) or 'inline'.
Color Plus options
These options are added by the plugin.
color.formatLocked
By default (true), any valid color entered in the widget's text field is converted back to the bound value's original format. Set to false to let a typed value switch the binding's format to match what was typed. (Experimental!)
A typed value can only move between formats that share the bound value's shape: a string binding can switch between hex, rgb(), oklch(), and so on, but a switch that would change the value's type or shape (a string to an object or array, a tuple gaining an alpha slot, an object's keys changing) keeps the current format and logs a console warning, so the control always shows a value in the shape your code bound. The picker's alpha slider is decided when the binding is created, so after a switch to an alpha-bearing string format the alpha can only be changed by typing it.
constrain
Keep the color inside the widest configured gamut (see gamuts): picks on the palette plane snap to the in-gamut frontier, while slider moves, typed text, and externally bound values shed chroma (at constant lightness and hue) to fit. Set to false to allow out-of-gamut colors. Default true.
Colors already inside the gamut are never changed. Because lightness and hue stay exact, constrained colors can differ from a browser's CSS gamut mapping, which may shift the hue slightly. This shows most around sRGB blue: oklch(45% 0.4 264) constrains to #0032e2 here, while CSS gamut mapping gives #0500ff.
gamuts
The RGB gamuts whose boundaries the OKLCH picker draws on the palette plane, as an array of ids. Both colorjs ids and their CSS aliases are accepted: 'srgb', 'p3' / 'display-p3', 'a98rgb' / 'a98-rgb', 'rec2020', and 'prophoto' / 'prophoto-rgb'.
Adaptive default: ['srgb', 'p3'] when the bound color uses a wide or perceptual model, ['srgb'] when it uses an sRGB-bound model.
pane.addBinding(params, 'color', { view: 'color-plus', gamuts: ['srgb', 'p3', 'rec2020'] })gamutLabel
Draw the name of the narrowest configured gamut that holds the current color in the picker plane's bottom-left corner. There are some contrast and legibility issues with this to be resolved in a future version.
The label tests the color itself, so it can disagree with the boundary lines at sRGB blue. At blue's exact hue, sRGB holds chroma up to about 85% of blue's, then nothing until blue itself, which it reaches only along the black-to-blue edge of the RGB cube. The boundary line traces the wider part, so #0000ff and the darker blues on that edge, such as navy, are labeled sRGB while their markers sit past the sRGB line. For about 0.15° past blue's hue, that edge widens into a thin sliver of sRGB colors detached from the rest, and the line there can follow either part. Rounding moves a color off that edge: oklch(0.452 0.313 264), blue rounded to three decimals, is outside sRGB.
Hex values can only describe sRGB, so a color outside sRGB is shown as a nearby sRGB hex value, and several colors can share one. With P3 configured, the plane's top-right corner at blue's hue is P3's brighter blue: it also reads #0000ff, but is labeled P3.
Adaptive default: true when the bound color uses a wide or perceptual model, false when it's sRGB-bound.
gamutLines
Which configured gamut boundaries are stroked over the picker plane:
| Value | Behavior |
| ------------------- | ------------------------------------------------------------------------------------ |
| 'inner' (default) | Draws the narrower gamuts' lines. |
| 'outer' | Draws the widest gamut's line (otherwise redundant with the drawn plane's own edge). |
| 'all' | Draws both. |
| 'none' | Hides every line. |
paletteChannels
Which OKLCH channels map to the picker plane's axes and the slider, as [X][Y]_[slider]: one of 'CL_H' (default), 'LC_H', 'LH_C', 'HL_C', 'HC_L', or 'CH_L'. All permutations are currently included, but this option will likely be abstracted away into curated choices in a 1.0 release.
paletteProjection
How the picker plane projects the gamut volume onto its rectangle:
| Value | Behavior |
| ------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| 'okhsv' (default) | Uses an OKHSV saturation / value projection on lightness × chroma layouts (the vivid cusp lands in the corner), falling back to 'stretch' on other layouts. This is the most similar to Tweakpane's built-in color palette. |
| 'perceptual' | Keeps absolute OKLCH spacing — the gamut sits as an irregular region within the plane. This is the most similar to the oklch.com graphs. |
| 'stretch' | Fills the plane with the widest gamut, row by row. |
swatchFallback
The active color swatch is split along its diagonal: the upper-left triangle shows the color as your browser renders it, and the lower-right triangle shows the color's sRGB fallback. swatchFallback controls how an out-of-gamut color is forced into sRGB for that fallback triangle. It only affects the swatch preview, never the color value itself.
| Value | Behavior |
| ------------------ | ----------------------------------------------------------------------------------------------------------------------------------------------------------- |
| 'clip' (default) | Clamps each channel to its range — the same thing browsers do when painting an out-of-gamut color, so the fallback matches what you actually see on screen. |
| 'css' | Applies the CSS Color 4 gamut-mapping algorithm (chroma reduction at constant lightness and hue). |
pane.addBinding(params, 'color', { view: 'color-plus', swatchFallback: 'clip' })Why two methods, and why 'clip' is the default: the two algorithms resolve out-of-gamut colors differently, and they can disagree dramatically. The CSS algorithm preserves lightness and hue while reducing chroma, so a vivid color at full lightness like oklch(100% 0.439 13) maps to white — at lightness 1.0 the OKLCH gamut tapers to a single point, and the only in-gamut color is white. Browsers don't run that algorithm when painting; they clip the channels instead, which keeps the color vivid (a saturated magenta, in this example) at the cost of silently shifting its lightness. Because 'clip' mirrors the browser, it's the default so the fallback swatch matches on-screen rendering. Choose 'css' if you'd rather see the colorimetrically faithful gamut mapping that CSS specifies (but that no browser actually performs on screen).
textFields
Show the color model drop-down and per-channel text inputs below the picker palette. Set to false to hide them for a more compact, pointer-only picker. (The alpha slider's text input, if present, is unaffected.) Default true.
pane.addBinding(params, 'color', { view: 'color-plus', textFields: false })Adaptive defaults
Rather than shipping one global set of default option values, Color Plus resolves several defaults from the format of the initially bound value. The goal is to do the right thing with as little configuration as possible: binding '#ff0066' gets a simple sRGB picker with no wide-gamut chrome it can't use, while binding 'oklch(65% 0.26 357deg)' gets Display P3 boundaries and a gamut label without any setup.
The bound value drives three defaults: The gamuts array, the gamutLabel state, and which mode the picker's text fields open in. It also determines which color.* options apply at all:
| Initial value | Gamut reach | gamuts | gamutLabel | Text fields open in | Applicable color.* options |
| -------------------------------------------------------------------------- | ----------- | ---------------- | ------------ | -------------------- | ---------------------------- |
| Hex string '#ff0066' | sRGB-bound | ['srgb'] | false | hex | formatLocked |
| Named color 'rebeccapurple' | sRGB-bound | ['srgb'] | false | hex | formatLocked |
| sRGB-model string 'rgb(…)', 'hsl(…)', 'hwb(…)' | sRGB-bound | ['srgb'] | false | srgb, hsl, hsv | formatLocked |
| Wide / perceptual string 'oklch(…)', 'lab(…)', 'color(display-p3 …)' | wide | ['srgb', 'p3'] | true | oklch | formatLocked |
| Number 0xff0066 | sRGB-bound | ['srgb'] | false | hex | alpha, formatLocked |
| sRGB-model object {r, g, b}, {h, s, l}, … | sRGB-bound | ['srgb'] | false | srgb, hsl, hsv | type, formatLocked |
| Wide / perceptual object {l, a, b}, {l, c, h} | wide | ['srgb', 'p3'] | true | oklch | type, formatLocked |
| Tuple / array [255, 0, 102] | sRGB-bound | ['srgb'] | false | srgb | type, formatLocked |
The "gamut reach" grouping follows the bound color's model, not its value type: models that can't leave the sRGB gamut (hex, named colors, rgb(), hsl(), hwb(), HSV, sRGB Linear, and the matching objects and tuples) get the simple sRGB picker, while wide and perceptual models (Oklch, Oklab, Lab, LCH, Display P3, Rec. 2020, and friends) get the full wide-gamut treatment.
The text fields open in the mode matching the bound model when the drop-down offers one (srgb, hsl, hsv, okhsv, oklch); other models fall back to hsv (sRGB-bound) or oklch (wide), and hex, named-color, and number values always open in hex.
A couple of behaviors follow the value rather than an option: an alpha slider appears whenever the value itself carries alpha ('#ff00667f', {r, g, b, a}, a 4-tuple, 'transparent', … — numbers use color.alpha instead), and a named-color binding posterizes the picker plane into named-color patches (see String formats).
These are only defaults: gamuts and gamutLabel accept explicit overrides, and the text-fields mode is just the drop-down's starting selection. Options passed for a value type that doesn't support them (color.alpha on a string, color.type on a number) are ignored with a console warning.
Color spaces
As a trade-off between bundle size and flexibility, Color Plus only supports "predefined" color spaces included in the CSS 4 color specification, with the sole addition of HSV for parity with the built-in Tweakpane color input implementation.
Supported spaces / color functions include:
- Adobe RGB (1998)
- HSL
- HSV (for parity with Tweakpane's built-in color input)
- HWB
- Lab D65
- Lab (a.k.a. Lab D50)
- LCH
- Oklab
- Oklch
- Display P3
- ProPhoto RGB
- Rec. 2020
- sRGB
- sRGB Linear
- XYZ D50
- XYZ D65 (a.k.a. XYZ)
Color formats
The Color Plus plugin supports a wide range of parameter values formats beyond those of the built-in Tweakpane color input. The plugin remembers the original format of the input value, and will always transform any valid color input value entered in the text field of the Tweakpane UI widget into that format.
String formats
Hexadecimal string values with or without alpha components are supported:
const hexStrings = {
hexString: '#ff0066',
hexStringAlpha: '#ff00667f',
}0x-prefixed hex strings like '0xff0066' are also supported, but will be normalized to #-prefixed representation.
Any CSS <named-color> string like rebeccapurple works both in the widget's text field and as an initial parameter value:
const namedColors = {
namedColor: 'rebeccapurple',
namedColorTransparent: 'transparent',
}A named-color binding always writes a name back: when the current color doesn't exactly match one of the 148 named colors, the perceptually-nearest name (by distance in OKLab) is written instead, while the widget keeps full precision internally. Exact ties resolve to the first name in the CSS named-color table (aqua over cyan, fuchsia over magenta, gray over grey). To make the snapping visible, the picker plane for a named-color binding is posterized into patches of the named colors — clicking anywhere inside a patch writes that patch's name, and the swatch and text fields snap live to that name's exact color while you drag. Only the plane's reticle stays continuous, tracking the pointer freely within a patch, so the picked position (and the widget's internal precision) is never lost to the snap.
transparent is supported too: a binding initialized with transparent gains an alpha slider, and writes transparent back only when alpha is exactly 0 (a translucent color writes the nearest opaque name, since names can't carry alpha).
Number formats
Numeric values with or without alpha components are supported:
const numbers = {
number: 0xff_00_66,
numberAlpha: 0xff_00_66_7f,
}Decimal representations like 16711782 are also supported, but will be normalized to 0x-prefixed representation in the widget's text field.
Object formats
The Color Plus plugin should "just work" with a range of color object keys, including any combination of long keys like red and short keys like r and g.
The plugin will infer the desired representation from the keys.
Float values are supported via the color: { type: 'float' } binding option (see color.type):
const objects = {
object: { r: 255, g: 0, b: 102 },
objectAlpha: { r: 255, g: 0, b: 102, a: 0.5 },
objectFloat: { r: 1, g: 0, b: 0.4 },
objectFloatAlpha: { r: 1, g: 0, b: 0.4, a: 0.5 },
objectLongKeys: { red: 255, green: 0, blue: 102 },
objectLongKeysAlpha: { red: 255, green: 0, blue: 102, alpha: 0.5 },
objectMixedKeys: { r: 255, green: 0, b: 102 },
objectHsl: { h: 336, s: 100, l: 50 },
objectHsv: { h: 336, s: 100, v: 100 },
objectHwb: { h: 336, w: 0, b: 0 },
objectLab: { l: 55, a: 83, b: 21 },
objectLch: { l: 55, c: 85, h: 14 },
}Tuple / array formats
Tuple color representations can be useful for interoperability with libraries like three.js.
Numeric tuple / array values with or without alpha components are supported. Alpha values must be between 0.0 and 1.0.
Float values are supported via the color: { type: 'float' } binding option (see color.type):
const tuples = {
tuple: [255, 0, 102],
tupleAlpha: [255, 0, 102, 0.5],
tupleFloat: [1, 0, 0.4],
tupleFloatAlpha: [1, 0, 0.4, 0.5],
}Generic CSS color() function
The Color Plus plugin supports all CSS 4 color() function strings for the supported color spaces:
Browsers will consider some of these formats to be invalid as noted below.
const functions = {
// Browser-compatible CSS color() strings
colorA98Rgb: 'color(a98-rgb 0.86 0 0.39)',
colorDisplayP3: 'color(display-p3 0.92 0.2 0.41)',
colorProphotoRgb: 'color(prophoto-rgb 0.72 0.28 0.33)',
colorRec2020: 'color(rec2020 0.8 0.23 0.35)',
colorSrgb: 'color(srgb 1 0% 40%)',
colorSrgbLinear: 'color(srgb-linear 1 0 0.13)',
colorXyz: 'color(xyz 0.44 0.22 0.15)',
colorXyzD50: 'color(xyz-d50 0.46 0.23 0.11)',
colorXyzD65: 'color(xyz-d65 0.44 0.22 0.15)',
// Plugin-compatible color() string
// (Works in plugin, but invalid in CSS:
// use dedicated color functions instead)
colorPrefixHsv: 'color(--hsv 336deg 100% 100)',
colorHsl: 'color(hsl 336 100% 50%)',
colorHwb: 'color(hwb 336 0% 0%)',
colorLab: 'color(lab 55 66% 16%)',
colorLabD65: 'color(lab-d65 54 66% 15%)',
colorLch: 'color(lch 55 56% 4%)',
colorOklab: 'color(oklab 0.64 0.25 0.05)',
colorOklch: 'color(oklch 60% 0.24 13deg)',
}Space-specific functions
You may use the modern /-separated format for alpha components, or the legacy ,-separated format.
const functions = {
// hsl() strings (Tweakpane built-in)
funcHslLegacy: 'hsl(336, 100%, 50%)',
funcHsl: 'hsl(336 100% 50%)',
funcHslAlpha: 'hsl(336 100% 50% / 0.5)',
funcHslLegacyNoUnits: 'hsl(336, 100, 50)',
funcHslFancyUnits: 'hsl(336deg 100% 50% / .5)',
// hsla() strings (Tweakpane built-in)
funcHslaLegacy: 'hsla(336, 100%, 50%, 0.5)',
funcHsla: 'hsla(336 100% 50% / 0.5)',
funcHslaLegacyNoUnits: 'hsla(336, 100, 50, 0.5)',
funcHslaFancyUnits: 'hsla(336deg 100% 50% / 0.5)',
// hwb() strings
funcHwbLegacy: 'hwb(336, 0%, 0%)',
funcHwb: 'hwb(336 0% 0%)',
funcHwbAlpha: 'hwb(336 0% 0% / 0.5)',
// lab() strings
funcLabLegacy: 'lab(55%, 83, 21)',
funcLab: 'lab(55% 83 21)',
funcLabAlpha: 'lab(55% 83 21 / 0.5)',
// lch() strings
funcLchLegacy: 'lch(55, 85, 14)',
funcLch: 'lch(55 85 14)',
funcLchAlpha: 'lch(55 85 14 / 0.5)',
// oklab() strings
funcOklabLegacy: 'oklab(0.64, 0.25, 0.05)',
funcOklab: 'oklab(0.64 0.25 0.05)',
funcOklabAlpha: 'oklab(0.64 0.25 0.05 / 0.5)',
// oklch() strings
funcOklchLegacy: 'oklch(60%, 0.26, 11deg)',
funcOklch: 'oklch(60% 0.26 11deg)',
funcOklchAlpha: 'oklch(60% 0.26 11deg / 0.5)',
// rgb() strings (Tweakpane built-in)
funcRgbLegacy: 'rgb(255, 0, 102)',
funcRgb: 'rgb(255 0 102)',
funcRgbAlpha: 'rgb(255 0 102 / 0.5)',
// rgba() strings (Tweakpane built-in)
funcRgbaLegacy: 'rgba(255, 0, 102, 0.5)',
funcRgba: 'rgba(255 0 102 / 0.5)',
}Implementation notes
Color.js v0.7.x
The plugin uses Color.js' procedural API and only imports a subset of available color spaces in the interest of performance and bundle size optimization.
This dependency is bundled and tree-shaken, so there are no external third-party dependencies in the plugin (except Tweakpane itself).
Other JavaScript color libraries
I investigated a number of libraries to back the internal color representation in the Color Plus plugin. Color.js was selected because it offers "round trip" continuity of per-coordinate string formatting style, but there are a number of great libraries out there with robust support for modern color spaces and formats. Here are a few:
The "lite" plugin build
The Rollup configuration provided in the Tweakpane plugin template does not externalize @tweakpane/core as a production dependency.
Instead, it gets built into the single-file plugin artifact, which is typically what's published to NPM and imported by plugin consumers. This makes it easy to import as an ES module from a URL, but means that larger projects importing multiple Tweakpane plugins end up with duplicate bundled copies of the @tweakpane/core code, adding about ~100 Kb to the final minified build for each plugin after the first.
To avoid this size penalty, Color Plus includes a "lite" version of the build, which is configured to externalize the @tweakpane/core dependency. This allows multiple Tweakpane plugins to share a single instance of the @tweakpane/core. (I also maintain forks of a number of popular Tweakpane plugins with the @tweakpane/core dependency externalization optimization.)
You can import the "lite" version like this:
import * as TweakpanePluginColorPlus from 'tweakpane-plugin-color-plus/lite'If you're not using a bundler, direct ESM imports from URLs can still work by defining the @tweakpane/core dependency manually in an importmap.
Or, if you're just using a single plugin and would rather not think about it, a "classic" all-inclusive build is exported by default to match the typical behavior of a Tweakpane plugin:
import * as TweakpanePluginColorPlus from 'tweakpane-plugin-color-plus'You can see the effect of externalization on the minified library's size below:
| File | Original | Gzip | Brotli | | --------------------------------------- | -------- | ----- | ------ | | tweakpane-plugin-color-plus.min.js | 130 kB | 42 kB | 37 kB | | tweakpane-plugin-color-plus.lite.min.js | 112 kB | 38 kB | 33 kB |
Maintainers
Acknowledgments
Thank you to Hiroki Kokubun for creating and maintaining the excellent Tweakpane library.
Thanks also to Lea Verou and contributors for creating the Color.js library.
Ryan Kiley's recent tweakpane-plugin-wide-gamut inspired me to finally get around to updating the view layer of this plugin to handle wide color. Ultimately, the OKLCH Color Picker & Converter informed the revised view implementation, in combination with Björn Ottosson's color picker comparison and accompanying blog post.
Contributing
Issues are welcome and appreciated.
Please open an issue to discuss changes before submitting a pull request. Unsolicited PRs are unlikely to be merged.
This repository uses ksc to handle linting and formatting with the usual tools, plus mdat for readme placeholder expansion, and chagent to maintain the changelog.
