@996-design/996-fast-color 1.0.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,579 @@
1
+ "use strict";
2
+
3
+ Object.defineProperty(exports, "__esModule", {
4
+ value: true
5
+ });
6
+ exports.FastColor = void 0;
7
+ var _presetColors = _interopRequireDefault(require("./presetColors"));
8
+ function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
9
+ const round = Math.round;
10
+
11
+ /**
12
+ * Support format, alpha unit will check the % mark:
13
+ * - rgba(102, 204, 255, .5) -> [102, 204, 255, 0.5]
14
+ * - rgb(102 204 255 / .5) -> [102, 204, 255, 0.5]
15
+ * - rgb(100%, 50%, 0% / 50%) -> [255, 128, 0, 0.5]
16
+ * - hsl(270, 60, 40, .5) -> [270, 60, 40, 0.5]
17
+ * - hsl(270deg 60% 40% / 50%) -> [270, 60, 40, 0.5]
18
+ *
19
+ * When `base` is provided, the percentage value will be divided by `base`.
20
+ */
21
+ function splitColorStr(str, parseNum) {
22
+ const match = str
23
+ // Remove str before `(`
24
+ .replace(/^[^(]*\((.*)/, '$1')
25
+ // Remove str after `)`
26
+ .replace(/\).*/, '').match(/\d*\.?\d+%?/g) || [];
27
+ const numList = match.map(item => parseFloat(item));
28
+ for (let i = 0; i < 3; i += 1) {
29
+ numList[i] = parseNum(numList[i] || 0, match[i] || '', i);
30
+ }
31
+
32
+ // For alpha. 50% should be 0.5
33
+ if (match[3]) {
34
+ numList[3] = match[3].includes('%') ? numList[3] / 100 : numList[3];
35
+ } else {
36
+ // By default, alpha is 1
37
+ numList[3] = 1;
38
+ }
39
+ return numList;
40
+ }
41
+ const parseHSVorHSL = (num, _, index) => index === 0 ? num : num / 100;
42
+
43
+ /** round and limit number to integer between 0-255 */
44
+ function limitRange(value, max) {
45
+ const mergedMax = max || 255;
46
+ if (value > mergedMax) {
47
+ return mergedMax;
48
+ }
49
+ if (value < 0) {
50
+ return 0;
51
+ }
52
+ return value;
53
+ }
54
+ class FastColor {
55
+ /**
56
+ * All FastColor objects are valid. So isValid is always true. This property is kept to be compatible with TinyColor.
57
+ */
58
+ isValid = true;
59
+
60
+ /**
61
+ * Red, R in RGB
62
+ */
63
+ r = 0;
64
+
65
+ /**
66
+ * Green, G in RGB
67
+ */
68
+ g = 0;
69
+
70
+ /**
71
+ * Blue, B in RGB
72
+ */
73
+ b = 0;
74
+
75
+ /**
76
+ * Alpha/Opacity, A in RGBA/HSLA
77
+ */
78
+ a = 1;
79
+
80
+ // HSV privates
81
+ _h;
82
+ _hsl_s;
83
+ _hsv_s;
84
+ _l;
85
+ _v;
86
+
87
+ // intermediate variables to calculate HSL/HSV
88
+ _max;
89
+ _min;
90
+ _brightness;
91
+ constructor(input) {
92
+ /**
93
+ * Always check 3 char in the object to determine the format.
94
+ * We not use function in check to save bundle size.
95
+ * e.g. 'rgb' -> { r: 0, g: 0, b: 0 }.
96
+ */
97
+ function matchFormat(str) {
98
+ return str[0] in input && str[1] in input && str[2] in input;
99
+ }
100
+ if (!input) {
101
+ // Do nothing since already initialized
102
+ } else if (typeof input === 'string') {
103
+ const trimStr = input.trim();
104
+ function matchPrefix(prefix) {
105
+ return trimStr.startsWith(prefix);
106
+ }
107
+ if (/^#?[A-F\d]{3,8}$/i.test(trimStr)) {
108
+ this.fromHexString(trimStr);
109
+ } else if (matchPrefix('rgb')) {
110
+ this.fromRgbString(trimStr);
111
+ } else if (matchPrefix('hsl')) {
112
+ this.fromHslString(trimStr);
113
+ } else if (matchPrefix('hsv') || matchPrefix('hsb')) {
114
+ this.fromHsvString(trimStr);
115
+ } else {
116
+ // From preset color
117
+ const presetColor = _presetColors.default[trimStr.toLowerCase()];
118
+ if (presetColor) {
119
+ this.fromHexString(
120
+ // Convert 36 hex to 16 hex
121
+ parseInt(presetColor, 36).toString(16).padStart(6, '0'));
122
+ }
123
+ }
124
+ } else if (input instanceof FastColor) {
125
+ this.r = input.r;
126
+ this.g = input.g;
127
+ this.b = input.b;
128
+ this.a = input.a;
129
+ this._h = input._h;
130
+ this._hsl_s = input._hsl_s;
131
+ this._hsv_s = input._hsv_s;
132
+ this._l = input._l;
133
+ this._v = input._v;
134
+ } else if (matchFormat('rgb')) {
135
+ this.r = limitRange(input.r);
136
+ this.g = limitRange(input.g);
137
+ this.b = limitRange(input.b);
138
+ this.a = typeof input.a === 'number' ? limitRange(input.a, 1) : 1;
139
+ } else if (matchFormat('hsl')) {
140
+ this.fromHsl(input);
141
+ } else if (matchFormat('hsv')) {
142
+ this.fromHsv(input);
143
+ } else {
144
+ throw new Error('@996-design/996-fast-color: unsupported input ' + JSON.stringify(input));
145
+ }
146
+ }
147
+
148
+ // ======================= Setter =======================
149
+
150
+ setR(value) {
151
+ return this._sc('r', value);
152
+ }
153
+ setG(value) {
154
+ return this._sc('g', value);
155
+ }
156
+ setB(value) {
157
+ return this._sc('b', value);
158
+ }
159
+ setA(value) {
160
+ return this._sc('a', value, 1);
161
+ }
162
+ setHue(value) {
163
+ const hsv = this.toHsv();
164
+ hsv.h = value;
165
+ return this._c(hsv);
166
+ }
167
+
168
+ // ======================= Getter =======================
169
+ /**
170
+ * Returns the perceived luminance of a color, from 0-1.
171
+ * @see http://www.w3.org/TR/2008/REC-WCAG20-20081211/#relativeluminancedef
172
+ */
173
+ getLuminance() {
174
+ function adjustGamma(raw) {
175
+ const val = raw / 255;
176
+ return val <= 0.03928 ? val / 12.92 : Math.pow((val + 0.055) / 1.055, 2.4);
177
+ }
178
+ const R = adjustGamma(this.r);
179
+ const G = adjustGamma(this.g);
180
+ const B = adjustGamma(this.b);
181
+ return 0.2126 * R + 0.7152 * G + 0.0722 * B;
182
+ }
183
+ getHue() {
184
+ if (typeof this._h === 'undefined') {
185
+ const delta = this.getMax() - this.getMin();
186
+ if (delta === 0) {
187
+ this._h = 0;
188
+ } else {
189
+ this._h = round(60 * (this.r === this.getMax() ? (this.g - this.b) / delta + (this.g < this.b ? 6 : 0) : this.g === this.getMax() ? (this.b - this.r) / delta + 2 : (this.r - this.g) / delta + 4));
190
+ }
191
+ }
192
+ return this._h;
193
+ }
194
+
195
+ /**
196
+ * @deprecated should use getHSVSaturation or getHSLSaturation instead
197
+ */
198
+ getSaturation() {
199
+ return this.getHSVSaturation();
200
+ }
201
+ getHSVSaturation() {
202
+ if (typeof this._hsv_s === 'undefined') {
203
+ const delta = this.getMax() - this.getMin();
204
+ if (delta === 0) {
205
+ this._hsv_s = 0;
206
+ } else {
207
+ this._hsv_s = delta / this.getMax();
208
+ }
209
+ }
210
+ return this._hsv_s;
211
+ }
212
+ getHSLSaturation() {
213
+ if (typeof this._hsl_s === 'undefined') {
214
+ const delta = this.getMax() - this.getMin();
215
+ if (delta === 0) {
216
+ this._hsl_s = 0;
217
+ } else {
218
+ const l = this.getLightness();
219
+ this._hsl_s = delta / 255 / (1 - Math.abs(2 * l - 1));
220
+ }
221
+ }
222
+ return this._hsl_s;
223
+ }
224
+ getLightness() {
225
+ if (typeof this._l === 'undefined') {
226
+ this._l = (this.getMax() + this.getMin()) / 510;
227
+ }
228
+ return this._l;
229
+ }
230
+ getValue() {
231
+ if (typeof this._v === 'undefined') {
232
+ this._v = this.getMax() / 255;
233
+ }
234
+ return this._v;
235
+ }
236
+
237
+ /**
238
+ * Returns the perceived brightness of the color, from 0-255.
239
+ * Note: this is not the b of HSB
240
+ * @see http://www.w3.org/TR/AERT#color-contrast
241
+ */
242
+ getBrightness() {
243
+ if (typeof this._brightness === 'undefined') {
244
+ this._brightness = (this.r * 299 + this.g * 587 + this.b * 114) / 1000;
245
+ }
246
+ return this._brightness;
247
+ }
248
+
249
+ // ======================== Func ========================
250
+
251
+ darken(amount = 10) {
252
+ const h = this.getHue();
253
+ const s = this.getSaturation();
254
+ let l = this.getLightness() - amount / 100;
255
+ if (l < 0) {
256
+ l = 0;
257
+ }
258
+ return this._c({
259
+ h,
260
+ s,
261
+ l,
262
+ a: this.a
263
+ });
264
+ }
265
+ lighten(amount = 10) {
266
+ const h = this.getHue();
267
+ const s = this.getSaturation();
268
+ let l = this.getLightness() + amount / 100;
269
+ if (l > 1) {
270
+ l = 1;
271
+ }
272
+ return this._c({
273
+ h,
274
+ s,
275
+ l,
276
+ a: this.a
277
+ });
278
+ }
279
+
280
+ /**
281
+ * Mix the current color a given amount with another color, from 0 to 100.
282
+ * 0 means no mixing (return current color).
283
+ */
284
+ mix(input, amount = 50) {
285
+ const color = this._c(input);
286
+ const p = amount / 100;
287
+ const calc = key => (color[key] - this[key]) * p + this[key];
288
+ const rgba = {
289
+ r: round(calc('r')),
290
+ g: round(calc('g')),
291
+ b: round(calc('b')),
292
+ a: round(calc('a') * 100) / 100
293
+ };
294
+ return this._c(rgba);
295
+ }
296
+
297
+ /**
298
+ * Mix the color with pure white, from 0 to 100.
299
+ * Providing 0 will do nothing, providing 100 will always return white.
300
+ */
301
+ tint(amount = 10) {
302
+ return this.mix({
303
+ r: 255,
304
+ g: 255,
305
+ b: 255,
306
+ a: 1
307
+ }, amount);
308
+ }
309
+
310
+ /**
311
+ * Mix the color with pure black, from 0 to 100.
312
+ * Providing 0 will do nothing, providing 100 will always return black.
313
+ */
314
+ shade(amount = 10) {
315
+ return this.mix({
316
+ r: 0,
317
+ g: 0,
318
+ b: 0,
319
+ a: 1
320
+ }, amount);
321
+ }
322
+ onBackground(background) {
323
+ const bg = this._c(background);
324
+ const alpha = this.a + bg.a * (1 - this.a);
325
+ const calc = key => {
326
+ return round((this[key] * this.a + bg[key] * bg.a * (1 - this.a)) / alpha);
327
+ };
328
+ return this._c({
329
+ r: calc('r'),
330
+ g: calc('g'),
331
+ b: calc('b'),
332
+ a: alpha
333
+ });
334
+ }
335
+
336
+ // ======================= Status =======================
337
+ isDark() {
338
+ return this.getBrightness() < 128;
339
+ }
340
+ isLight() {
341
+ return this.getBrightness() >= 128;
342
+ }
343
+
344
+ // ======================== MISC ========================
345
+ equals(other) {
346
+ return this.r === other.r && this.g === other.g && this.b === other.b && this.a === other.a;
347
+ }
348
+ clone() {
349
+ return this._c(this);
350
+ }
351
+
352
+ // ======================= Format =======================
353
+ toHexString() {
354
+ let hex = '#';
355
+ const rHex = (this.r || 0).toString(16);
356
+ hex += rHex.length === 2 ? rHex : '0' + rHex;
357
+ const gHex = (this.g || 0).toString(16);
358
+ hex += gHex.length === 2 ? gHex : '0' + gHex;
359
+ const bHex = (this.b || 0).toString(16);
360
+ hex += bHex.length === 2 ? bHex : '0' + bHex;
361
+ if (typeof this.a === 'number' && this.a >= 0 && this.a < 1) {
362
+ const aHex = round(this.a * 255).toString(16);
363
+ hex += aHex.length === 2 ? aHex : '0' + aHex;
364
+ }
365
+ return hex;
366
+ }
367
+
368
+ /** CSS support color pattern */
369
+ toHsl() {
370
+ return {
371
+ h: this.getHue(),
372
+ s: this.getHSLSaturation(),
373
+ l: this.getLightness(),
374
+ a: this.a
375
+ };
376
+ }
377
+
378
+ /** CSS support color pattern */
379
+ toHslString() {
380
+ const h = this.getHue();
381
+ const s = round(this.getHSLSaturation() * 100);
382
+ const l = round(this.getLightness() * 100);
383
+ return this.a !== 1 ? `hsla(${h},${s}%,${l}%,${this.a})` : `hsl(${h},${s}%,${l}%)`;
384
+ }
385
+
386
+ /** Same as toHsb */
387
+ toHsv() {
388
+ return {
389
+ h: this.getHue(),
390
+ s: this.getHSVSaturation(),
391
+ v: this.getValue(),
392
+ a: this.a
393
+ };
394
+ }
395
+ toRgb() {
396
+ return {
397
+ r: this.r,
398
+ g: this.g,
399
+ b: this.b,
400
+ a: this.a
401
+ };
402
+ }
403
+ toRgbString() {
404
+ return this.a !== 1 ? `rgba(${this.r},${this.g},${this.b},${this.a})` : `rgb(${this.r},${this.g},${this.b})`;
405
+ }
406
+ toString() {
407
+ return this.toRgbString();
408
+ }
409
+
410
+ // ====================== Privates ======================
411
+ /** Return a new FastColor object with one channel changed */
412
+ _sc(rgb, value, max) {
413
+ const clone = this.clone();
414
+ clone[rgb] = limitRange(value, max);
415
+ return clone;
416
+ }
417
+ _c(input) {
418
+ return new this.constructor(input);
419
+ }
420
+ getMax() {
421
+ if (typeof this._max === 'undefined') {
422
+ this._max = Math.max(this.r, this.g, this.b);
423
+ }
424
+ return this._max;
425
+ }
426
+ getMin() {
427
+ if (typeof this._min === 'undefined') {
428
+ this._min = Math.min(this.r, this.g, this.b);
429
+ }
430
+ return this._min;
431
+ }
432
+ fromHexString(trimStr) {
433
+ const withoutPrefix = trimStr.replace('#', '');
434
+ function connectNum(index1, index2) {
435
+ return parseInt(withoutPrefix[index1] + withoutPrefix[index2 || index1], 16);
436
+ }
437
+ if (withoutPrefix.length < 6) {
438
+ // #rgb or #rgba
439
+ this.r = connectNum(0);
440
+ this.g = connectNum(1);
441
+ this.b = connectNum(2);
442
+ this.a = withoutPrefix[3] ? connectNum(3) / 255 : 1;
443
+ } else {
444
+ // #rrggbb or #rrggbbaa
445
+ this.r = connectNum(0, 1);
446
+ this.g = connectNum(2, 3);
447
+ this.b = connectNum(4, 5);
448
+ this.a = withoutPrefix[6] ? connectNum(6, 7) / 255 : 1;
449
+ }
450
+ }
451
+ fromHsl({
452
+ h: _h,
453
+ s,
454
+ l,
455
+ a
456
+ }) {
457
+ const h = (_h % 360 + 360) % 360;
458
+ this._h = h;
459
+ this._hsl_s = s;
460
+ this._l = l;
461
+ this.a = typeof a === 'number' ? a : 1;
462
+ if (s <= 0) {
463
+ const rgb = round(l * 255);
464
+ this.r = rgb;
465
+ this.g = rgb;
466
+ this.b = rgb;
467
+ return;
468
+ }
469
+ let r = 0,
470
+ g = 0,
471
+ b = 0;
472
+ const huePrime = h / 60;
473
+ const chroma = (1 - Math.abs(2 * l - 1)) * s;
474
+ const secondComponent = chroma * (1 - Math.abs(huePrime % 2 - 1));
475
+ if (huePrime >= 0 && huePrime < 1) {
476
+ r = chroma;
477
+ g = secondComponent;
478
+ } else if (huePrime >= 1 && huePrime < 2) {
479
+ r = secondComponent;
480
+ g = chroma;
481
+ } else if (huePrime >= 2 && huePrime < 3) {
482
+ g = chroma;
483
+ b = secondComponent;
484
+ } else if (huePrime >= 3 && huePrime < 4) {
485
+ g = secondComponent;
486
+ b = chroma;
487
+ } else if (huePrime >= 4 && huePrime < 5) {
488
+ r = secondComponent;
489
+ b = chroma;
490
+ } else if (huePrime >= 5 && huePrime < 6) {
491
+ r = chroma;
492
+ b = secondComponent;
493
+ }
494
+ const lightnessModification = l - chroma / 2;
495
+ this.r = round((r + lightnessModification) * 255);
496
+ this.g = round((g + lightnessModification) * 255);
497
+ this.b = round((b + lightnessModification) * 255);
498
+ }
499
+ fromHsv({
500
+ h: _h,
501
+ s,
502
+ v,
503
+ a
504
+ }) {
505
+ const h = (_h % 360 + 360) % 360;
506
+ this._h = h;
507
+ this._hsv_s = s;
508
+ this._v = v;
509
+ this.a = typeof a === 'number' ? a : 1;
510
+ const vv = round(v * 255);
511
+ this.r = vv;
512
+ this.g = vv;
513
+ this.b = vv;
514
+ if (s <= 0) {
515
+ return;
516
+ }
517
+ const hh = h / 60;
518
+ const i = Math.floor(hh);
519
+ const ff = hh - i;
520
+ const p = round(v * (1.0 - s) * 255);
521
+ const q = round(v * (1.0 - s * ff) * 255);
522
+ const t = round(v * (1.0 - s * (1.0 - ff)) * 255);
523
+ switch (i) {
524
+ case 0:
525
+ this.g = t;
526
+ this.b = p;
527
+ break;
528
+ case 1:
529
+ this.r = q;
530
+ this.b = p;
531
+ break;
532
+ case 2:
533
+ this.r = p;
534
+ this.b = t;
535
+ break;
536
+ case 3:
537
+ this.r = p;
538
+ this.g = q;
539
+ break;
540
+ case 4:
541
+ this.r = t;
542
+ this.g = p;
543
+ break;
544
+ case 5:
545
+ default:
546
+ this.g = p;
547
+ this.b = q;
548
+ break;
549
+ }
550
+ }
551
+ fromHsvString(trimStr) {
552
+ const cells = splitColorStr(trimStr, parseHSVorHSL);
553
+ this.fromHsv({
554
+ h: cells[0],
555
+ s: cells[1],
556
+ v: cells[2],
557
+ a: cells[3]
558
+ });
559
+ }
560
+ fromHslString(trimStr) {
561
+ const cells = splitColorStr(trimStr, parseHSVorHSL);
562
+ this.fromHsl({
563
+ h: cells[0],
564
+ s: cells[1],
565
+ l: cells[2],
566
+ a: cells[3]
567
+ });
568
+ }
569
+ fromRgbString(trimStr) {
570
+ const cells = splitColorStr(trimStr, (num, txt) =>
571
+ // Convert percentage to number. e.g. 50% -> 128
572
+ txt.includes('%') ? round(num / 100 * 255) : num);
573
+ this.r = cells[0];
574
+ this.g = cells[1];
575
+ this.b = cells[2];
576
+ this.a = cells[3];
577
+ }
578
+ }
579
+ exports.FastColor = FastColor;
package/lib/index.d.ts ADDED
@@ -0,0 +1,2 @@
1
+ export * from './FastColor';
2
+ export * from './types';
package/lib/index.js ADDED
@@ -0,0 +1,27 @@
1
+ "use strict";
2
+
3
+ Object.defineProperty(exports, "__esModule", {
4
+ value: true
5
+ });
6
+ var _FastColor = require("./FastColor");
7
+ Object.keys(_FastColor).forEach(function (key) {
8
+ if (key === "default" || key === "__esModule") return;
9
+ if (key in exports && exports[key] === _FastColor[key]) return;
10
+ Object.defineProperty(exports, key, {
11
+ enumerable: true,
12
+ get: function () {
13
+ return _FastColor[key];
14
+ }
15
+ });
16
+ });
17
+ var _types = require("./types");
18
+ Object.keys(_types).forEach(function (key) {
19
+ if (key === "default" || key === "__esModule") return;
20
+ if (key in exports && exports[key] === _types[key]) return;
21
+ Object.defineProperty(exports, key, {
22
+ enumerable: true,
23
+ get: function () {
24
+ return _types[key];
25
+ }
26
+ });
27
+ });