-
Notifications
You must be signed in to change notification settings - Fork 1
/
BasicPicker.js
522 lines (455 loc) 路 14.7 KB
/
BasicPicker.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
import React from 'react'
import { ColorExtractor } from 'react-color-extractor'
import generateColors from 'randomcolor'
import { TinyColor } from '@ctrl/tinycolor'
import Values from 'values.js'
import PropTypes from 'prop-types'
import styled from 'react-emotion'
import clipboard from 'clipboard-polyfill'
import ColorInput from '../components/ColorInputField'
import ColorBlock from '../components/ColorBlock'
import Container from '../components/Container'
import Image from '../components/Image'
import Swatches from '../components/Swatches'
import Triangle from '../components/Triangle'
import ColorFormatPicker from '../components/ColorFormatPicker'
import { AdvanceTools, BasicTools } from '../components/Tools'
import { Provider as ColorProvider } from '../utils/context'
import {
DEFAULT_SWATCHES,
DEFAULT_COLOR,
COLOR_CONTAINER_WIDTH,
MAX_COLORS
} from '../utils/constants'
import getThemeVariants from '../utils/theme'
const StyledList = styled('ul')`
display: grid;
justify-content: center;
grid-template-columns: 1fr;
grid-gap: 15px;
list-style: none;
margin-left: -28px;
`
const ToolsContainer = styled('div')`
display: grid;
grid-template-columns: ${props =>
`repeat(${props.columns || 6}, ${props.size || '1fr'})`};
grid-gap: ${props => props.gap || '5px'};
margin-right: -20px;
margin-top: 20px;
`
export default class BasicPicker extends React.PureComponent {
// Image upload icon
imageIcon = null
// Hidden input element for uploading an image
uploadElement = null
// Clipboard icon
clipboardIcon = null
state = {
// Current block, active and input field color (or hue)
color: new TinyColor(this.props.color),
// Current swatches to be displayed in picker
swatches: this.props.swatches,
// Image from which colors are extracted
image: null,
// Shades are the hue darkened with black
shades: [],
// Tints are the hue lightend with white
tints: [],
// Should display the shades swatches
showShades: false,
// Should display the tint swatches
showTints: false,
// Current color format selected
currentFormat: 'HEX',
// Color format options
formats: ['HEX', 'HSV', 'RGB', 'HSL'],
// Color manipulation values
// Brightens the currently selected color by an amount
brighten: 0,
// Darkens the currently selected color by an amount
darken: 0,
// spin operation spins (changes) the current hue
spin: 0,
// desaturation makes a color more muted (with black or grey)
desaturate: 0,
// saturation controls the intensity (or purity) of a color
saturate: 0,
// Show or hide color copied msg
showMsg: false
}
static defaultProps = {
color: DEFAULT_COLOR,
swatches: DEFAULT_SWATCHES,
// Max amount of colors from which palettes will be generated (from the image)
maxColors: MAX_COLORS,
triangle: true,
theme: 'light',
// Color tools are disabled by default
showTools: false
}
static propTypes = {
color: PropTypes.string,
/* eslint-disable react/require-default-props */
onChange: PropTypes.func,
onSwatchHover: PropTypes.func,
swatches: PropTypes.arrayOf(PropTypes.string),
maxColors: PropTypes.number,
triangle: PropTypes.bool,
theme: PropTypes.oneOf(['light', 'dark']),
showTools: PropTypes.bool
}
// Instance properties are used to store the color state on
// which the color operations will be applied.
brightenColor = null
darkenColor = null
spinColor = null
desaturateColor = null
saturateColor = null
componentDidMount() {
this.uploadElement = document.getElementById('uploader')
this.imageIcon = document.getElementById('image-icon')
this.clipboardIcon = document.getElementById('clipboard')
this.imageIcon &&
this.imageIcon.addEventListener('click', this.simulateClick)
this.clipboardIcon &&
this.clipboardIcon.addEventListener('mouseleave', this.hideMsg)
this.clipboardIcon &&
this.clipboardIcon.addEventListener('blur', this.hideMsg)
// Attach a listener for deleting the image (if any) from the color block
document.addEventListener('keydown', this.updateKey)
}
componentDidUpdate(prevProps) {
if (prevProps.color !== this.props.color) {
const color = new TinyColor(this.props.color)
// Check if its a valid hex and then update the color
// on changing the color input field, it only updates the color block if the hex code is valid
if (color.isValid) {
this.setState({ color })
}
}
}
componentWillUnmount() {
this.imageIcon &&
this.imageIcon.removeEventListener('click', this.simulateClick)
this.clipboardIcon &&
this.clipboardIcon.removeEventListener('mouseleave', this.hideMsg)
this.clipboardIcon &&
this.clipboardIcon.removeEventListener('blur', this.hideMsg)
document.removeEventListener('keydown', this.updateKey)
}
hideMsg = () => this.setState({ showMsg: false })
// default onChange handler for color input field
defaultOnChange = color => {
const newColor = new TinyColor(color)
if (newColor.isValid) {
this.setState({ color: newColor })
}
}
updateColorState = (value, color, operation) => {
const newValue = parseInt(value)
const newColor = new TinyColor(color)[operation](newValue)
this.props.onChange && this.props.onChange(newColor.toHexString())
this.setState({ [operation]: newValue, color: newColor })
}
clearAllColorBuffers = () => {
this.spinColor = null
this.saturateColor = null
this.desaturateColor = null
this.darkenColor = null
this.brightenColor = null
}
/**
* Below methods are used to handle color operations. Whenever an
* operation is performed on a color, it mutates the original state
* of the color. So we use instance properties to clear and set the
* currently active color state, and then apply the color operations
* w.r.t to the instance property (or current color value)
*
* TODO: Refactor this mess
*/
handleSpin = e => {
if (this.spinColor === null) {
this.spinColor = this.state.color.originalInput
}
this.saturateColor = null
this.desaturateColor = null
this.brightenColor = null
this.darkenColor = null
this.updateColorState(e.target.value, this.spinColor, 'spin')
}
handleSaturate = e => {
if (this.saturateColor === null) {
this.saturateColor = this.state.color.originalInput
}
this.spinColor = null
this.desaturateColor = null
this.brightenColor = null
this.darkenColor = null
this.updateColorState(e.target.value, this.saturateColor, 'saturate')
}
handleDesaturate = e => {
if (this.desaturateColor === null) {
this.desaturateColor = this.state.color.originalInput
}
this.saturateColor = null
this.spinColor = null
this.brightenColor = null
this.darkenColor = null
this.updateColorState(e.target.value, this.desaturateColor, 'desaturate')
}
handleBrighten = e => {
if (this.brightenColor === null) {
this.brightenColor = this.state.color.originalInput
}
this.saturateColor = null
this.desaturateColor = null
this.spinColor = null
this.darkenColor = null
this.updateColorState(e.target.value, this.brightenColor, 'brighten')
}
handleDarken = e => {
if (this.darkenColor === null) {
this.darkenColor = this.state.color.originalInput
}
this.saturateColor = null
this.desaturateColor = null
this.brightenColor = null
this.spinColor = null
this.updateColorState(e.target.value, this.darkenColor, 'darken')
}
// outputs the color according to the color format
getColor = color => ({
HSL: color.toHslString(),
HEX: color.toHexString(),
RGB: color.toRgbString(),
HSV: color.toHsvString()
})
// This handler is used to update the image state. After the colors
// are extracted from the image, a image can be removed from the color block.
updateKey = e => {
if (e.which === 8) {
// Remove the image from color block
this.setState({ image: null })
}
}
simulateClick = e => {
if (this.uploadElement) {
this.uploadElement.click()
}
e.preventDefault()
}
// Randomly generate new swatches
generateSwatches = () => {
let i = 0
// Each swatch should be different
const newColors = new Set()
while (i < 12) {
newColors.add(generateColors())
i += 1
}
const swatches = Array.from(newColors)
// Hide shades and tints when new swatches are added
this.setState({
swatches: [...swatches],
showShades: false,
showTints: false,
tints: [],
shades: []
})
}
uploadImage = e =>
this.setState({ image: window.URL.createObjectURL(e.target.files[0]) })
// Updates the hue state
updateSwatch = color => {
// If tools are active, then reset color instance properties.
if (this.props.showTools) {
this.clearAllColorBuffers()
this.setState({
color: new TinyColor(color),
// Reset all the values for the newly selected swatch
spin: 0,
saturate: 0,
desaturate: 0,
darken: 0,
brighten: 0
})
} else {
this.setState({
color: new TinyColor(color)
})
}
this.props.onChange && this.props.onChange(color)
}
// Handler to update swatches when colors are extracted from an image
updateSwatches = swatches =>
this.setState({
swatches: [...swatches],
// Also update the current color
color: new TinyColor(swatches[0]),
// Hide the shades and tints
showShades: false,
showTints: false,
tints: [],
shades: []
})
// Generates shades or tints from the currently selected hue (color)
generateSwatchesFromHue = (term, showShades, showTints) => {
const colorBuffer = []
const color = new Values(this.state.color.toHexString())
color[term]().forEach(c => colorBuffer.push(c.hexString()))
this.setState({
[term]: [...colorBuffer],
showShades,
showTints
})
}
// Shades - A hue lightened with white
generateShades = () => this.generateSwatchesFromHue('shades', true, false)
// Tints - A hue darkened with black
generateTints = () => this.generateSwatchesFromHue('tints', false, true)
// Update the color format (hsv, rgb, hex, or hsl)
changeFormat = e => this.setState({ currentFormat: e.target.value })
// Reset the shades and tints, and displays the previous swatches
resetColors = () =>
this.setState({
shades: [],
tints: [],
showShades: false,
showTints: false
})
copyColor = () => {
const { color, currentFormat } = this.state
const activeColor = this.getColor(color)[currentFormat]
clipboard.writeText(activeColor)
this.setState({ showMsg: true })
}
render() {
const {
image,
swatches,
shades,
showShades,
showTints,
tints,
currentFormat,
darken,
brighten,
spin,
desaturate,
saturate,
formats
} = this.state
// Get the color string with a specified color format
const color = this.getColor(this.state.color)[currentFormat]
const { bg, iconColor } = getThemeVariants(this.props.theme)
return (
<Container background={bg} width={COLOR_CONTAINER_WIDTH}>
{/* eslint-disable operator-linebreak */}
{/* eslint-disable indent */}
{this.props.triangle &&
image === null && <Triangle color={this.state.color.toHexString()} />}
{image === null ? (
<ColorBlock
colorState={this.state.color}
color={color}
currentFormat={currentFormat}
/>
) : (
<Image src={image} />
)}
{image && (
<ColorExtractor
maxColors={this.props.maxColors}
src={image}
getColors={this.updateSwatches}
/>
)}
<div style={{ padding: 10 }}>
{showShades ? (
<Swatches
swatches={shades}
updateSwatch={this.updateSwatch}
onSwatchHover={this.props.onSwatchHover}
/>
) : showTints ? (
<Swatches
swatches={tints}
updateSwatch={this.updateSwatch}
onSwatchHover={this.props.onSwatchHover}
/>
) : (
<Swatches
swatches={swatches}
updateSwatch={this.updateSwatch}
onSwatchHover={this.props.onSwatchHover}
/>
)}
<ColorInput
value={color}
onChange={this.props.onChange || this.defaultOnChange}
/>
<ColorFormatPicker
changeFormat={this.changeFormat}
formats={formats}
/>
<ColorProvider value={iconColor}>
<ToolsContainer>
<BasicTools.ImagePicker uploadImage={this.uploadImage} />
<BasicTools.PaletteGenerator
generateSwatches={this.generateSwatches}
/>
<BasicTools.TintsGenerator generateTints={this.generateTints} />
<BasicTools.ShadesGenerator
generateShades={this.generateShades}
/>
<BasicTools.Clipboard
copyColor={this.copyColor}
showMsg={this.state.showMsg}
/>
<BasicTools.Reset resetColors={this.resetColors} />
</ToolsContainer>
</ColorProvider>
{this.props.showTools ? (
<div>
<ColorProvider value={iconColor}>
<StyledList>
<li>
<AdvanceTools.ColorSpinner
value={spin}
onChange={this.handleSpin}
/>
</li>
<li>
<AdvanceTools.ColorSaturator
value={saturate}
onChange={this.handleSaturate}
/>
</li>
<li>
<AdvanceTools.ColorDesaturator
value={desaturate}
onChange={this.handleDesaturate}
/>
</li>
<li>
<AdvanceTools.ColorDarkener
value={darken}
onChange={this.handleDarken}
/>
</li>
<li>
<AdvanceTools.ColorBrightener
value={brighten}
onChange={this.handleBrighten}
/>
</li>
</StyledList>
</ColorProvider>
</div>
) : null}
</div>
</Container>
)
}
}