or run

npx @tessl/cli init
Log in

Version

Tile

Overview

Evals

Files

Files

docs

building-blocks.mdcolor-pickers.mdcolor-utilities.mdindex.md

color-utilities.mddocs/

0

# Color Utilities

1

2

Helper functions for color validation, conversion, and manipulation. These utilities provide the underlying functionality used by color picker components and can be used independently for color operations.

3

4

Core imports for helper functions:

5

6

```javascript

7

// Color helper functions

8

import {

9

simpleCheckForValidColor,

10

toState,

11

isValidHex,

12

getContrastingColor,

13

red,

14

isvalidColorString

15

} from 'react-color/lib/helpers/color';

16

17

// Checkboard utilities

18

import { render, get } from 'react-color/lib/helpers/checkboard';

19

20

// Alternative: Import all helpers

21

import * as colorHelpers from 'react-color/lib/helpers';

22

```

23

24

## Capabilities

25

26

### Color Validation

27

28

Functions for validating color data and format strings.

29

30

#### simpleCheckForValidColor

31

32

Validates color data object to ensure all provided color properties are valid numbers or percentage strings.

33

34

```javascript { .api }

35

/**

36

* Validates color data object

37

* @param data - Color data object with properties like r, g, b, a, h, s, l, v

38

* @returns Validated data object or false if invalid

39

*/

40

function simpleCheckForValidColor(data: ColorData): ColorData | false;

41

42

interface ColorData {

43

r?: number;

44

g?: number;

45

b?: number;

46

a?: number;

47

h?: number;

48

s?: number | string; // Accepts percentage strings like "50%"

49

l?: number | string; // Accepts percentage strings like "50%"

50

v?: number;

51

hex?: string;

52

}

53

```

54

55

**Usage Example:**

56

57

```javascript

58

import { simpleCheckForValidColor } from 'react-color/lib/helpers/color';

59

60

const validColor = simpleCheckForValidColor({ r: 255, g: 0, b: 0, a: 1 });

61

// Returns: { r: 255, g: 0, b: 0, a: 1 }

62

63

const invalidColor = simpleCheckForValidColor({ r: 'invalid', g: 0, b: 0 });

64

// Returns: false

65

```

66

67

#### isValidHex

68

69

Validates hex color string format, supporting both 3 and 6 character hex codes as well as the special "transparent" value.

70

71

```javascript { .api }

72

/**

73

* Validates hex color string

74

* @param hex - Hex color string (with or without # prefix)

75

* @returns True if valid hex color

76

*/

77

function isValidHex(hex: string): boolean;

78

```

79

80

**Usage Example:**

81

82

```javascript

83

import { isValidHex } from 'react-color/lib/helpers/color';

84

85

console.log(isValidHex('#ff0000')); // true

86

console.log(isValidHex('ff0000')); // true

87

console.log(isValidHex('#f00')); // true

88

console.log(isValidHex('transparent')); // true

89

console.log(isValidHex('#gggggg')); // false

90

```

91

92

#### isvalidColorString

93

94

Validates color string for specific color format types.

95

96

```javascript { .api }

97

/**

98

* Validates color string for specific type

99

* @param string - Color value string

100

* @param type - Color type identifier

101

* @returns True if valid color string for the given type

102

*/

103

function isvalidColorString(string: string, type: string): boolean;

104

```

105

106

**Usage Example:**

107

108

```javascript

109

import { isvalidColorString } from 'react-color/lib/helpers/color';

110

111

console.log(isvalidColorString('180', 'hsl')); // true

112

console.log(isvalidColorString('360°', 'hsl')); // true (degree symbol removed)

113

```

114

115

### Color Conversion

116

117

Functions for converting between different color formats and creating normalized color state objects.

118

119

#### toState

120

121

Converts color data to a normalized state object containing all color format representations (HSL, RGB, HSV, hex).

122

123

```javascript { .api }

124

/**

125

* Converts color data to normalized state object

126

* @param data - Color data in any supported format

127

* @param oldHue - Previous hue value to preserve when saturation is 0

128

* @returns Normalized color state with all format representations

129

*/

130

function toState(data: ColorData | string, oldHue?: number): ColorState;

131

132

interface ColorState {

133

/** HSL color representation */

134

hsl: { h: number; s: number; l: number; a: number };

135

/** Hex color string (with # prefix) */

136

hex: string;

137

/** RGB color representation */

138

rgb: { r: number; g: number; b: number; a: number };

139

/** HSV color representation */

140

hsv: { h: number; s: number; v: number; a: number };

141

/** Previous hue value */

142

oldHue: number;

143

/** Source of the color data */

144

source?: string;

145

}

146

```

147

148

**Usage Example:**

149

150

```javascript

151

import { toState } from 'react-color/lib/helpers/color';

152

153

// From hex string

154

const state1 = toState('#ff0000');

155

console.log(state1.rgb); // { r: 255, g: 0, b: 0, a: 1 }

156

console.log(state1.hsl); // { h: 0, s: 1, l: 0.5, a: 1 }

157

158

// From RGB object

159

const state2 = toState({ r: 0, g: 255, b: 0 });

160

console.log(state2.hex); // "#00ff00"

161

162

// From HSL with preserved hue

163

const state3 = toState({ h: 0, s: 0, l: 0.5 }, 180);

164

console.log(state3.oldHue); // 180 (preserved when saturation is 0)

165

```

166

167

### Color Analysis

168

169

Functions for analyzing color properties and determining appropriate contrast colors.

170

171

#### getContrastingColor

172

173

Determines the best contrasting color (black or white) for text displayed over a given background color using YIQ color space calculations.

174

175

```javascript { .api }

176

/**

177

* Returns contrasting color (black/white) for given color

178

* @param data - Color data to analyze

179

* @returns "#000" for light colors, "#fff" for dark colors, or rgba for transparent

180

*/

181

function getContrastingColor(data: ColorData): string;

182

```

183

184

**Usage Example:**

185

186

```javascript

187

import { getContrastingColor } from 'react-color/lib/helpers/color';

188

189

const lightBg = getContrastingColor({ r: 255, g: 255, b: 255 });

190

console.log(lightBg); // "#000" (black text on white background)

191

192

const darkBg = getContrastingColor({ r: 0, g: 0, b: 0 });

193

console.log(darkBg); // "#fff" (white text on black background)

194

195

const transparentBg = getContrastingColor({ hex: 'transparent' });

196

console.log(transparentBg); // "rgba(0,0,0,0.4)"

197

```

198

199

### Color Constants

200

201

Pre-defined color objects for common use cases.

202

203

#### red

204

205

Pre-defined red color object containing all color format representations.

206

207

```javascript { .api }

208

/**

209

* Predefined red color constant

210

*/

211

const red: {

212

hsl: { a: 1; h: 0; l: 0.5; s: 1 };

213

hex: '#ff0000';

214

rgb: { r: 255; g: 0; b: 0; a: 1 };

215

hsv: { h: 0; s: 1; v: 1; a: 1 };

216

};

217

```

218

219

**Usage Example:**

220

221

```javascript

222

import { red } from 'react-color/lib/helpers/color';

223

224

console.log(red.hex); // "#ff0000"

225

console.log(red.rgb); // { r: 255, g: 0, b: 0, a: 1 }

226

```

227

228

### Checkboard Utilities

229

230

Functions for generating transparent background checkboard patterns used to visualize alpha transparency in color pickers.

231

232

#### render

233

234

Renders a checkboard pattern to a canvas and returns a data URL representation.

235

236

```javascript { .api }

237

/**

238

* Renders checkboard pattern to canvas

239

* @param c1 - First color (typically white)

240

* @param c2 - Second color (typically light gray)

241

* @param size - Size of each checkboard square in pixels

242

* @param serverCanvas - Optional server-side canvas implementation

243

* @returns Data URL string of the checkboard pattern

244

*/

245

function render(c1: string, c2: string, size: number, serverCanvas?: any): string | null;

246

```

247

248

**Usage Example:**

249

250

```javascript

251

import { render } from 'react-color/lib/helpers/checkboard';

252

253

const checkboardDataUrl = render('#ffffff', '#e6e6e6', 8);

254

// Returns: "data:image/png;base64,..." (base64 encoded checkboard pattern)

255

```

256

257

#### get

258

259

Gets a cached checkboard pattern or generates a new one if not cached.

260

261

```javascript { .api }

262

/**

263

* Gets cached checkboard pattern or generates new one

264

* @param c1 - First color (typically white)

265

* @param c2 - Second color (typically light gray)

266

* @param size - Size of each checkboard square in pixels

267

* @param serverCanvas - Optional server-side canvas implementation

268

* @returns Cached data URL string of the checkboard pattern

269

*/

270

function get(c1: string, c2: string, size: number, serverCanvas?: any): string | null;

271

```

272

273

**Usage Example:**

274

275

```javascript

276

import { get } from 'react-color/lib/helpers/checkboard';

277

278

// First call generates and caches the pattern

279

const pattern1 = get('#ffffff', '#e6e6e6', 8);

280

// Subsequent calls with same parameters return cached result

281

const pattern2 = get('#ffffff', '#e6e6e6', 8); // Same as pattern1 (cached)

282

```

283

284

## Helper Usage Patterns

285

286

### Validating User Input

287

288

```javascript

289

import { isValidHex, simpleCheckForValidColor } from 'react-color/lib/helpers/color';

290

291

function handleColorInput(userInput) {

292

// Check if it's a valid hex string

293

if (typeof userInput === 'string' && isValidHex(userInput)) {

294

return { hex: userInput };

295

}

296

297

// Check if it's valid color data object

298

const validatedColor = simpleCheckForValidColor(userInput);

299

if (validatedColor) {

300

return validatedColor;

301

}

302

303

// Invalid input

304

return null;

305

}

306

```

307

308

### Converting Between Formats

309

310

```javascript

311

import { toState } from 'react-color/lib/helpers/color';

312

313

function convertColor(input, outputFormat) {

314

const colorState = toState(input);

315

316

switch (outputFormat) {

317

case 'hex':

318

return colorState.hex;

319

case 'rgb':

320

return `rgb(${colorState.rgb.r}, ${colorState.rgb.g}, ${colorState.rgb.b})`;

321

case 'hsl':

322

return `hsl(${Math.round(colorState.hsl.h)}, ${Math.round(colorState.hsl.s * 100)}%, ${Math.round(colorState.hsl.l * 100)}%)`;

323

default:

324

return colorState;

325

}

326

}

327

```

328

329

### Accessible Color Combinations

330

331

```javascript

332

import { getContrastingColor, toState } from 'react-color/lib/helpers/color';

333

334

function createAccessiblePair(backgroundColor) {

335

const bgState = toState(backgroundColor);

336

const textColor = getContrastingColor(bgState);

337

338

return {

339

backgroundColor: bgState.hex,

340

color: textColor,

341

// These colors provide sufficient contrast for accessibility

342

};

343

}

344

```

345

346

## Type Definitions

347

348

```javascript { .api }

349

interface ColorData {

350

hex?: string;

351

r?: number;

352

g?: number;

353

b?: number;

354

a?: number;

355

h?: number;

356

s?: number | string;

357

l?: number | string;

358

v?: number;

359

source?: string;

360

}

361

362

interface ColorState {

363

hsl: { h: number; s: number; l: number; a: number };

364

hex: string;

365

rgb: { r: number; g: number; b: number; a: number };

366

hsv: { h: number; s: number; v: number; a: number };

367

oldHue: number;

368

source?: string;

369

}

370

```