5185c2ac0230b865a93f7efe2e75d42005ce1209d8fdcdff9acd828873ecc67be4e0b98bd02e4cd6ca0e54d2e83db1aa809d842b9b24559ada7db6b2bc6b32 2.2 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091
  1. import { TinyColor } from '@ctrl/tinycolor';
  2. import { hasOwn } from '@vue/shared';
  3. class Color {
  4. constructor(options = {}) {
  5. this._hue = 0;
  6. this._saturation = 100;
  7. this._value = 100;
  8. this._alpha = 100;
  9. this._tiny = new TinyColor();
  10. this._isValid = false;
  11. this.enableAlpha = false;
  12. this.format = "";
  13. this.value = "";
  14. for (const option in options) {
  15. if (hasOwn(options, option)) {
  16. this[option] = options[option];
  17. }
  18. }
  19. if (options.value) {
  20. this.fromString(options.value);
  21. } else {
  22. this.doOnChange();
  23. }
  24. }
  25. set(prop, value) {
  26. if (arguments.length === 1 && typeof prop === "object") {
  27. for (const p in prop) {
  28. if (hasOwn(prop, p)) {
  29. this.set(p, prop[p]);
  30. }
  31. }
  32. return;
  33. }
  34. this[`_${prop}`] = value;
  35. this._isValid = true;
  36. this.doOnChange();
  37. }
  38. get(prop) {
  39. if (["hue", "saturation", "value", "alpha"].includes(prop)) {
  40. return Math.round(this[`_${prop}`]);
  41. }
  42. return this[`_${prop}`];
  43. }
  44. toRgb() {
  45. return this._isValid ? this._tiny.toRgb() : { r: 255, g: 255, b: 255, a: 0 };
  46. }
  47. fromString(value) {
  48. const color = new TinyColor(value);
  49. this._isValid = color.isValid;
  50. if (color.isValid) {
  51. const { h, s, v, a } = color.toHsv();
  52. this._hue = h;
  53. this._saturation = s * 100;
  54. this._value = v * 100;
  55. this._alpha = a * 100;
  56. } else {
  57. this._hue = 0;
  58. this._saturation = 100;
  59. this._value = 100;
  60. this._alpha = 100;
  61. }
  62. this.doOnChange();
  63. }
  64. compare(color) {
  65. const compareColor = new TinyColor({
  66. h: color._hue,
  67. s: color._saturation / 100,
  68. v: color._value / 100,
  69. a: color._alpha / 100
  70. });
  71. return this._tiny.equals(compareColor);
  72. }
  73. doOnChange() {
  74. const { _hue, _saturation, _value, _alpha, format, enableAlpha } = this;
  75. let _format = format || (enableAlpha ? "rgb" : "hex");
  76. if (format === "hex" && enableAlpha) {
  77. _format = "hex8";
  78. }
  79. this._tiny = new TinyColor({
  80. h: _hue,
  81. s: _saturation / 100,
  82. v: _value / 100,
  83. a: _alpha / 100
  84. });
  85. this.value = this._isValid ? this._tiny.toString(_format) : "";
  86. }
  87. }
  88. export { Color as default };
  89. //# sourceMappingURL=color.mjs.map