@fe6/water-pro
Version:
An enterprise-class UI design language and Vue-based implementation
1,044 lines (817 loc) • 34 kB
JavaScript
function _toConsumableArray(arr) { return _arrayWithoutHoles(arr) || _iterableToArray(arr) || _unsupportedIterableToArray(arr) || _nonIterableSpread(); }
function _nonIterableSpread() { throw new TypeError("Invalid attempt to spread non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method."); }
function _iterableToArray(iter) { if (typeof Symbol !== "undefined" && iter[Symbol.iterator] != null || iter["@@iterator"] != null) return Array.from(iter); }
function _arrayWithoutHoles(arr) { if (Array.isArray(arr)) return _arrayLikeToArray(arr); }
function _createForOfIteratorHelper(o, allowArrayLike) { var it = typeof Symbol !== "undefined" && o[Symbol.iterator] || o["@@iterator"]; if (!it) { if (Array.isArray(o) || (it = _unsupportedIterableToArray(o)) || allowArrayLike && o && typeof o.length === "number") { if (it) o = it; var i = 0; var F = function F() {}; return { s: F, n: function n() { if (i >= o.length) return { done: true }; return { done: false, value: o[i++] }; }, e: function e(_e2) { throw _e2; }, f: F }; } throw new TypeError("Invalid attempt to iterate non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method."); } var normalCompletion = true, didErr = false, err; return { s: function s() { it = it.call(o); }, n: function n() { var step = it.next(); normalCompletion = step.done; return step; }, e: function e(_e3) { didErr = true; err = _e3; }, f: function f() { try { if (!normalCompletion && it.return != null) it.return(); } finally { if (didErr) throw err; } } }; }
function _slicedToArray(arr, i) { return _arrayWithHoles(arr) || _iterableToArrayLimit(arr, i) || _unsupportedIterableToArray(arr, i) || _nonIterableRest(); }
function _nonIterableRest() { throw new TypeError("Invalid attempt to destructure non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method."); }
function _unsupportedIterableToArray(o, minLen) { if (!o) return; if (typeof o === "string") return _arrayLikeToArray(o, minLen); var n = Object.prototype.toString.call(o).slice(8, -1); if (n === "Object" && o.constructor) n = o.constructor.name; if (n === "Map" || n === "Set") return Array.from(o); if (n === "Arguments" || /^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n)) return _arrayLikeToArray(o, minLen); }
function _arrayLikeToArray(arr, len) { if (len == null || len > arr.length) len = arr.length; for (var i = 0, arr2 = new Array(len); i < len; i++) { arr2[i] = arr[i]; } return arr2; }
function _iterableToArrayLimit(arr, i) { var _i = arr == null ? null : typeof Symbol !== "undefined" && arr[Symbol.iterator] || arr["@@iterator"]; if (_i == null) return; var _arr = []; var _n = true; var _d = false; var _s, _e; try { for (_i = _i.call(arr); !(_n = (_s = _i.next()).done); _n = true) { _arr.push(_s.value); if (i && _arr.length === i) break; } } catch (err) { _d = true; _e = err; } finally { try { if (!_n && _i["return"] != null) _i["return"](); } finally { if (_d) throw _e; } } return _arr; }
function _arrayWithHoles(arr) { if (Array.isArray(arr)) return arr; }
function _extends() { _extends = Object.assign || function (target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i]; for (var key in source) { if (Object.prototype.hasOwnProperty.call(source, key)) { target[key] = source[key]; } } } return target; }; return _extends.apply(this, arguments); }
function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
function _defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } }
function _createClass(Constructor, protoProps, staticProps) { if (protoProps) _defineProperties(Constructor.prototype, protoProps); if (staticProps) _defineProperties(Constructor, staticProps); return Constructor; }
import * as _ from './utils/utils';
import { parseToHSVA } from './utils/color';
import { HSVaColor } from './utils/hsvacolor';
import Moveable from './libs/moveable';
import Selectable from './libs/selectable';
import buildPickr from './template';
import { createPopper } from 'nanopop';
var Pickr = /*#__PURE__*/function () {
function Pickr(opt) {
var _this = this;
_classCallCheck(this, Pickr);
// Will be used to prevent specific actions during initilization
this._initializingActive = true; // If the current color value should be recalculated
this._recalc = true; // Positioning engine and DOM-Tree
this._nanopop = null;
this._root = null; // Current and last color for comparison
this._color = HSVaColor();
this._lastColor = HSVaColor();
this._swatchColors = []; // Animation frame used for setup.
// Will be cancelled in case of destruction.
this._setupAnimationFrame = null; // Evenlistener name: [callbacks]
this._eventListener = {
init: [],
save: [],
hide: [],
show: [],
clear: [],
change: [],
changestop: [],
cancel: [],
swatchselect: []
}; // Assign default values
this.options = opt = _extends(_extends({}, Pickr.DEFAULT_OPTIONS), opt);
var _opt = opt,
swatches = _opt.swatches,
components = _opt.components,
theme = _opt.theme,
sliders = _opt.sliders,
lockOpacity = _opt.lockOpacity,
padding = _opt.padding;
if (['nano', 'monolith'].includes(theme) && !sliders) {
opt.sliders = 'h';
} // Check interaction section
if (!components.interaction) {
components.interaction = {};
} // Overwrite palette if preview, opacity or hue are true
var preview = components.preview,
opacity = components.opacity,
hue = components.hue,
palette = components.palette;
components.opacity = !lockOpacity && opacity;
components.palette = palette || preview || opacity || hue; // Initialize picker
this._preBuild();
this._buildComponents();
this._bindEvents();
this._finalBuild(); // Append pre-defined swatch colors
if (swatches && swatches.length) {
swatches.forEach(function (color) {
return _this.addSwatch(color);
});
} // Initialize positioning engine
var _this$_root = this._root,
button = _this$_root.button,
app = _this$_root.app;
this._nanopop = createPopper(button, app, {
margin: padding
}); // Initialize accessibility
button.setAttribute('role', 'button');
button.setAttribute('aria-label', this._t('btn:toggle')); // Initilization is finish, pickr is visible and ready for usage
var that = this;
this._setupAnimationFrame = requestAnimationFrame(function cb() {
// TODO: Performance issue due to high call-rate?
if (!app.offsetWidth) {
return requestAnimationFrame(cb);
} // Apply default color
that.setColor(opt.default);
that._rePositioningPicker(); // Initialize color representation
if (opt.defaultRepresentation) {
that._representation = opt.defaultRepresentation;
that.setColorRepresentation(that._representation);
} // Show pickr if locked
if (opt.showAlways) {
that.show();
} // Initialization is done - pickr is usable, fire init event
that._initializingActive = false;
that._emit('init');
});
} // Does only the absolutly basic thing to initialize the components
_createClass(Pickr, [{
key: "_preBuild",
value: function _preBuild() {
var options = this.options; // Resolve elements
for (var _i = 0, _arr = ['el', 'container']; _i < _arr.length; _i++) {
var type = _arr[_i];
options[type] = _.resolveElement(options[type]);
} // Create element and append it to body to
// Prevent initialization errors
this._root = buildPickr(this); // Check if a custom button is used
if (options.useAsButton) {
this._root.button = options.el; // Replace button with customized button
}
options.container.appendChild(this._root.root);
}
}, {
key: "_finalBuild",
value: function _finalBuild() {
var opt = this.options;
var root = this._root; // Remove from body
opt.container.removeChild(root.root);
if (opt.inline) {
var parent = opt.el.parentElement;
if (opt.el.nextSibling) {
parent.insertBefore(root.app, opt.el.nextSibling);
} else {
parent.appendChild(root.app);
}
} else {
opt.container.appendChild(root.app);
} // Don't replace the the element if a custom button is used
if (!opt.useAsButton) {
// Replace element with actual color-picker
opt.el.parentNode.replaceChild(root.root, opt.el);
} else if (opt.inline) {
opt.el.remove();
} // Check if it should be immediatly disabled
if (opt.disabled) {
this.disable();
} // Check if color comparison is disabled, if yes - remove transitions so everything keeps smoothly
if (!opt.comparison) {
root.button.style.transition = 'none';
if (!opt.useAsButton) {
root.preview.lastColor.style.transition = 'none';
}
}
this.hide();
}
}, {
key: "_buildComponents",
value: function _buildComponents() {
var _this2 = this;
// Instance reference
var inst = this;
var cs = this.options.components;
var sliders = (inst.options.sliders || 'v').repeat(2);
var _ref = sliders.match(/^[vh]+$/g) ? sliders : [],
_ref2 = _slicedToArray(_ref, 2),
so = _ref2[0],
sh = _ref2[1]; // Re-assign if null
var getColor = function getColor() {
return _this2._color || (_this2._color = _this2._lastColor.clone());
};
var components = {
palette: Moveable({
element: inst._root.palette.picker,
wrapper: inst._root.palette.palette,
onstop: function onstop() {
return inst._emit('changestop', 'slider', inst);
},
onchange: function onchange(x, y) {
if (!cs.palette) {
return;
}
var color = getColor();
var _root = inst._root,
options = inst.options;
var _root$preview = _root.preview,
lastColor = _root$preview.lastColor,
currentColor = _root$preview.currentColor; // Update the input field only if the user is currently not typing
if (inst._recalc) {
// Calculate saturation based on the position
color.s = x * 100; // Calculate the value
color.v = 100 - y * 100; // Prevent falling under zero
color.v < 0 ? color.v = 0 : 0;
inst._updateOutput('slider');
} // Set picker and gradient color
var cssRGBaString = color.toRGBA().toString(0);
this.element.style.background = cssRGBaString;
this.wrapper.style.background = "\n linear-gradient(to top, rgba(0, 0, 0, ".concat(color.a, "), transparent),\n linear-gradient(to left, hsla(").concat(color.h, ", 100%, 50%, ").concat(color.a, "), rgba(255, 255, 255, ").concat(color.a, "))\n "); // Check if color is locked
if (!options.comparison) {
_root.button.style.color = cssRGBaString; // If the user changes the color, remove the cleared icon
_root.button.classList.remove('clear');
} else if (!options.useAsButton && !inst._lastColor) {
// Apply color to both the last and current color since the current state is cleared
lastColor.style.setProperty('--pcr-color', cssRGBaString);
} // Check if there's a swatch which color matches the current one
var hexa = color.toHEXA().toString();
var _iterator = _createForOfIteratorHelper(inst._swatchColors),
_step;
try {
for (_iterator.s(); !(_step = _iterator.n()).done;) {
var _step$value = _step.value,
el = _step$value.el,
_color2 = _step$value.color;
el.classList[hexa === _color2.toHEXA().toString() ? 'add' : 'remove']('pcr-active');
} // Change current color
} catch (err) {
_iterator.e(err);
} finally {
_iterator.f();
}
currentColor.style.setProperty('--pcr-color', cssRGBaString);
}
}),
hue: Moveable({
lock: sh === 'v' ? 'h' : 'v',
element: inst._root.hue.picker,
wrapper: inst._root.hue.slider,
onstop: function onstop() {
return inst._emit('changestop', 'slider', inst);
},
onchange: function onchange(v) {
if (!cs.hue || !cs.palette) {
return;
}
var color = getColor(); // Calculate hue
if (inst._recalc) {
color.h = v * 360;
} // Update color
this.element.style.backgroundColor = "hsl(".concat(color.h, ", 100%, 50%)");
components.palette.trigger();
}
}),
opacity: Moveable({
lock: so === 'v' ? 'h' : 'v',
element: inst._root.opacity.picker,
wrapper: inst._root.opacity.slider,
onstop: function onstop() {
return inst._emit('changestop', 'slider', inst);
},
onchange: function onchange(v) {
if (!cs.opacity || !cs.palette) {
return;
}
var color = getColor(); // Calculate opacity
if (inst._recalc) {
color.a = Math.round(v * 1e2) / 100;
} // Update color
this.element.style.background = "rgba(0, 0, 0, ".concat(color.a, ")");
components.palette.trigger();
}
}),
selectable: Selectable({
elements: inst._root.interaction.options,
className: 'active',
onchange: function onchange(e) {
inst._representation = e.target.getAttribute('data-type').toUpperCase();
inst._recalc && inst._updateOutput('swatch');
}
})
};
this._components = components;
}
}, {
key: "_bindEvents",
value: function _bindEvents() {
var _this3 = this;
var _root = this._root,
options = this.options;
var eventBindings = [// Clear color
_.on(_root.interaction.clear, 'click', function () {
return _this3._clearColor();
}), // Select last color on click
_.on([_root.interaction.cancel, _root.preview.lastColor], 'click', function () {
_this3.setHSVA.apply(_this3, _toConsumableArray((_this3._lastColor || _this3._color).toHSVA()).concat([true]));
_this3._emit('cancel');
}), // Save color
_.on(_root.interaction.save, 'click', function () {
!_this3.applyColor() && !options.showAlways && _this3.hide();
}), // User input
_.on(_root.interaction.result, ['keyup', 'input'], function (e) {
// Fire listener if initialization is finish and changed color was valid
if (_this3.setColor(e.target.value, true) && !_this3._initializingActive) {
_this3._emit('change', _this3._color, 'input', _this3);
_this3._emit('changestop', 'input', _this3);
}
e.stopImmediatePropagation();
}), // Detect user input and disable auto-recalculation
_.on(_root.interaction.result, ['focus', 'blur'], function (e) {
_this3._recalc = e.type === 'blur';
_this3._recalc && _this3._updateOutput(null);
}), // Cancel input detection on color change
_.on([_root.palette.palette, _root.palette.picker, _root.hue.slider, _root.hue.picker, _root.opacity.slider, _root.opacity.picker], ['mousedown', 'touchstart'], function () {
return _this3._recalc = true;
}, {
passive: true
})]; // Provide hiding / showing abilities only if showAlways is false
if (!options.showAlways) {
var ck = options.closeWithKey;
eventBindings.push( // Save and hide / show picker
_.on(_root.button, 'click', function () {
return _this3.isOpen() ? _this3.hide() : _this3.show();
}), // Close with escape key
_.on(document, 'keyup', function (e) {
return _this3.isOpen() && (e.key === ck || e.code === ck) && _this3.hide();
}), // Cancel selecting if the user taps behind the color picker
_.on(document, ['touchstart', 'mousedown'], function (e) {
if (_this3.isOpen() && !_.eventPath(e).some(function (el) {
return el === _root.app || el === _root.button;
})) {
_this3.hide();
}
}, {
capture: true
}));
} // Make input adjustable if enabled
if (options.adjustableNumbers) {
var ranges = {
rgba: [255, 255, 255, 1],
hsva: [360, 100, 100, 1],
hsla: [360, 100, 100, 1],
cmyk: [100, 100, 100, 100]
};
_.adjustableInputNumbers(_root.interaction.result, function (o, step, index) {
var range = ranges[_this3.getColorRepresentation().toLowerCase()];
if (range) {
var max = range[index]; // Calculate next reasonable number
var nv = o + (max >= 100 ? step * 1000 : step); // Apply range of zero up to max, fix floating-point issues
return nv <= 0 ? 0 : Number((nv < max ? nv : max).toPrecision(3));
}
return o;
});
}
if (options.autoReposition && !options.inline) {
var timeout = null;
var that = this; // Re-calc position on window resize, scroll and wheel
eventBindings.push(_.on(window, ['scroll', 'resize'], function () {
if (that.isOpen()) {
if (options.closeOnScroll) {
that.hide();
}
if (timeout === null) {
timeout = setTimeout(function () {
return timeout = null;
}, 100); // Update position on every frame
requestAnimationFrame(function rs() {
that._rePositioningPicker();
timeout !== null && requestAnimationFrame(rs);
});
} else {
clearTimeout(timeout);
timeout = setTimeout(function () {
return timeout = null;
}, 100);
}
}
}, {
capture: true
}));
} // Save bindings
this._eventBindings = eventBindings;
}
}, {
key: "_rePositioningPicker",
value: function _rePositioningPicker() {
var options = this.options; // No repositioning needed if inline
if (!options.inline) {
var success = this._nanopop.update({
container: document.body.getBoundingClientRect(),
position: options.position
});
if (!success) {
var el = this._root.app;
var eb = el.getBoundingClientRect();
el.style.top = "".concat((window.innerHeight - eb.height) / 2, "px");
el.style.left = "".concat((window.innerWidth - eb.width) / 2, "px");
}
}
}
}, {
key: "_updateOutput",
value: function _updateOutput(eventSource) {
var _root = this._root,
_color = this._color,
options = this.options; // Check if component is present
if (_root.interaction.type()) {
// Construct function name and call if present
var method = "to".concat(_root.interaction.type().getAttribute('data-type'));
_root.interaction.result.value = typeof _color[method] === 'function' ? _color[method]().toString(options.outputPrecision) : '';
} // Fire listener if initialization is finish
if (!this._initializingActive && this._recalc) {
this._emit('change', _color, eventSource, this);
}
}
}, {
key: "_clearColor",
value: function _clearColor() {
var silent = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : false;
var _root = this._root,
options = this.options; // Change only the button color if it isn't customized
if (!options.useAsButton) {
_root.button.style.color = 'rgba(0, 0, 0, 0.15)';
}
_root.button.classList.add('clear');
if (!options.showAlways) {
this.hide();
}
this._lastColor = null;
if (!this._initializingActive && !silent) {
// Fire listener
this._emit('save', null);
this._emit('clear');
}
}
}, {
key: "_parseLocalColor",
value: function _parseLocalColor(str) {
var _parseToHSVA = parseToHSVA(str),
values = _parseToHSVA.values,
type = _parseToHSVA.type,
a = _parseToHSVA.a;
var lockOpacity = this.options.lockOpacity;
var alphaMakesAChange = a !== undefined && a !== 1; // If no opacity is applied, add undefined at the very end which gets
// Set to 1 in setHSVA
if (values && values.length === 3) {
values[3] = undefined;
}
return {
values: !values || lockOpacity && alphaMakesAChange ? null : values,
type: type
};
}
}, {
key: "_t",
value: function _t(key) {
return this.options.i18n[key] || Pickr.I18N_DEFAULTS[key];
}
}, {
key: "_emit",
value: function _emit(event) {
var _this4 = this;
for (var _len = arguments.length, args = new Array(_len > 1 ? _len - 1 : 0), _key = 1; _key < _len; _key++) {
args[_key - 1] = arguments[_key];
}
this._eventListener[event].forEach(function (cb) {
return cb.apply(void 0, args.concat([_this4]));
});
}
}, {
key: "on",
value: function on(event, cb) {
this._eventListener[event].push(cb);
return this;
}
}, {
key: "off",
value: function off(event, cb) {
var callBacks = this._eventListener[event] || [];
var index = callBacks.indexOf(cb);
if (~index) {
callBacks.splice(index, 1);
}
return this;
}
/**
* Appends a color to the swatch palette
* @param color
* @returns {boolean}
*/
}, {
key: "addSwatch",
value: function addSwatch(color) {
var _this5 = this;
var _this$_parseLocalColo = this._parseLocalColor(color),
values = _this$_parseLocalColo.values;
if (values) {
var _swatchColors = this._swatchColors,
_root = this._root;
var _color3 = HSVaColor.apply(void 0, _toConsumableArray(values)); // Create new swatch HTMLElement
var el = _.createElementFromString("<button type=\"button\" style=\"--pcr-color: ".concat(_color3.toRGBA().toString(0), "\" aria-label=\"").concat(this._t('btn:swatch'), "\"/>")); // Append element and save swatch data
_root.swatches.appendChild(el);
_swatchColors.push({
el: el,
color: _color3
}); // Bind event
this._eventBindings.push(_.on(el, 'click', function () {
_this5.setHSVA.apply(_this5, _toConsumableArray(_color3.toHSVA()).concat([true]));
_this5._emit('swatchselect', _color3);
_this5._emit('change', _color3, 'swatch', _this5);
}));
return true;
}
return false;
}
/**
* Removes a swatch color by it's index
* @param index
* @returns {boolean}
*/
}, {
key: "removeSwatch",
value: function removeSwatch(index) {
var swatchColor = this._swatchColors[index]; // Check swatch data
if (swatchColor) {
var el = swatchColor.el; // Remove HTML child and swatch data
this._root.swatches.removeChild(el);
this._swatchColors.splice(index, 1);
return true;
}
return false;
}
}, {
key: "applyColor",
value: function applyColor() {
var silent = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : false;
var _this$_root2 = this._root,
preview = _this$_root2.preview,
button = _this$_root2.button; // Change preview and current color
var cssRGBaString = this._color.toRGBA().toString(0);
preview.lastColor.style.setProperty('--pcr-color', cssRGBaString); // Change only the button color if it isn't customized
if (!this.options.useAsButton) {
button.style.setProperty('--pcr-color', cssRGBaString);
} // User changed the color so remove the clear clas
button.classList.remove('clear'); // Save last color
this._lastColor = this._color.clone(); // Fire listener
if (!this._initializingActive && !silent) {
this._emit('save', this._color);
}
return this;
}
/**
* Destroy's all functionalitys
*/
}, {
key: "destroy",
value: function destroy() {
var _this6 = this;
// Cancel setup-frame if set
cancelAnimationFrame(this._setupAnimationFrame); // Unbind events
this._eventBindings.forEach(function (args) {
return _.off.apply(_, _toConsumableArray(args));
}); // Destroy sub-components
Object.keys(this._components).forEach(function (key) {
return _this6._components[key].destroy();
});
}
/**
* Destroy's all functionalitys and removes
* the pickr element.
*/
}, {
key: "destroyAndRemove",
value: function destroyAndRemove() {
var _this7 = this;
this.destroy();
var _this$_root3 = this._root,
root = _this$_root3.root,
app = _this$_root3.app; // Remove element
if (root.parentElement) {
root.parentElement.removeChild(root);
} // Remove .pcr-app
app.parentElement.removeChild(app); // There are references to various DOM elements stored in the pickr instance
// This cleans all of them to avoid detached DOMs
Object.keys(this).forEach(function (key) {
return _this7[key] = null;
});
}
/**
* Hides the color-picker ui.
*/
}, {
key: "hide",
value: function hide() {
if (this.isOpen()) {
this._root.app.classList.remove('visible');
this._emit('hide');
return true;
}
return false;
}
/**
* Shows the color-picker ui.
*/
}, {
key: "show",
value: function show() {
if (!this.options.disabled && !this.isOpen()) {
this._root.app.classList.add('visible');
this._rePositioningPicker();
this._emit('show', this._color);
return this;
}
return false;
}
/**
* @return {boolean} If the color picker is currently open
*/
}, {
key: "isOpen",
value: function isOpen() {
return this._root.app.classList.contains('visible');
}
/**
* Set a specific color.
* @param h Hue
* @param s Saturation
* @param v Value
* @param a Alpha channel (0 - 1)
* @param silent If the button should not change the color
* @return boolean if the color has been accepted
*/
}, {
key: "setHSVA",
value: function setHSVA() {
var h = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : 360;
var s = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : 0;
var v = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : 0;
var a = arguments.length > 3 && arguments[3] !== undefined ? arguments[3] : 1;
var silent = arguments.length > 4 && arguments[4] !== undefined ? arguments[4] : false;
// Deactivate color calculation
var recalc = this._recalc; // Save state
this._recalc = false; // Validate input
if (h < 0 || h > 360 || s < 0 || s > 100 || v < 0 || v > 100 || a < 0 || a > 1) {
return false;
} // Override current color and re-active color calculation
this._color = HSVaColor(h, s, v, a); // Update slider and palette
var _this$_components = this._components,
hue = _this$_components.hue,
opacity = _this$_components.opacity,
palette = _this$_components.palette;
hue.update(h / 360);
opacity.update(a);
palette.update(s / 100, 1 - v / 100); // Check if call is silent
if (!silent) {
this.applyColor();
} // Update output if recalculation is enabled
if (recalc) {
this._updateOutput();
} // Restore old state
this._recalc = recalc;
return true;
}
/**
* Tries to parse a string which represents a color.
* Examples: #fff
* rgb 10 10 200
* hsva 10 20 5 0.5
* @param string
* @param silent
*/
}, {
key: "setColor",
value: function setColor(string) {
var silent = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : false;
// Check if null
if (string === null) {
this._clearColor(silent);
return true;
}
var _this$_parseLocalColo2 = this._parseLocalColor(string),
values = _this$_parseLocalColo2.values,
type = _this$_parseLocalColo2.type; // Check if color is ok
if (values) {
// Change selected color format
var utype = type.toUpperCase();
var options = this._root.interaction.options;
var target = options.find(function (el) {
return el.getAttribute('data-type') === utype;
}); // Auto select only if not hidden
if (target && !target.hidden) {
var _iterator2 = _createForOfIteratorHelper(options),
_step2;
try {
for (_iterator2.s(); !(_step2 = _iterator2.n()).done;) {
var el = _step2.value;
el.classList[el === target ? 'add' : 'remove']('active');
}
} catch (err) {
_iterator2.e(err);
} finally {
_iterator2.f();
}
} // Update color (fires 'save' event if silent is 'false')
if (!this.setHSVA.apply(this, _toConsumableArray(values).concat([silent]))) {
return false;
} // Update representation (fires 'change' event)
return this.setColorRepresentation(utype);
}
return false;
}
/**
* Changes the color _representation.
* Allowed values are HEX, RGB, HSV, HSL and CMYK
* @param type
* @returns {boolean} if the selected type was valid.
*/
}, {
key: "setColorRepresentation",
value: function setColorRepresentation(type) {
// Force uppercase to allow a case-sensitiv comparison
type = type.toUpperCase(); // Find button with given type and trigger click event
return !!this._root.interaction.options.find(function (v) {
return v.getAttribute('data-type').startsWith(type) && !v.click();
});
}
/**
* Returns the current color representaion. See setColorRepresentation
* @returns {*}
*/
}, {
key: "getColorRepresentation",
value: function getColorRepresentation() {
return this._representation;
}
/**
* @returns HSVaColor Current HSVaColor object.
*/
}, {
key: "getColor",
value: function getColor() {
return this._color;
}
/**
* Returns the currently selected color.
* @returns {{a, toHSVA, toHEXA, s, v, h, clone, toCMYK, toHSLA, toRGBA}}
*/
}, {
key: "getSelectedColor",
value: function getSelectedColor() {
return this._lastColor;
}
/**
* @returns The root HTMLElement with all his components.
*/
}, {
key: "getRoot",
value: function getRoot() {
return this._root;
}
/**
* Disable pickr
*/
}, {
key: "disable",
value: function disable() {
this.hide();
this.options.disabled = true;
this._root.button.classList.add('disabled');
return this;
}
/**
* Enable pickr
*/
}, {
key: "enable",
value: function enable() {
this.options.disabled = false;
this._root.button.classList.remove('disabled');
return this;
}
}]);
return Pickr;
}(); // Expose pickr utils
Pickr.utils = _; // Assign version and export
Pickr.version = '1.0.0'; // Default strings
Pickr.I18N_DEFAULTS = {
// Strings visible in the UI
'ui:dialog': 'color picker dialog',
'btn:toggle': 'toggle color picker dialog',
'btn:swatch': 'color swatch',
'btn:last-color': 'use previous color',
'btn:save': 'Save',
'btn:cancel': 'Cancel',
'btn:clear': 'Clear',
// Strings used for aria-labels
'aria:btn:save': 'save and close',
'aria:btn:cancel': 'cancel and close',
'aria:btn:clear': 'clear and close',
'aria:input': 'color input field',
'aria:palette': 'color selection area',
'aria:hue': 'hue selection slider',
'aria:opacity': 'selection slider'
}; // Default options
Pickr.DEFAULT_OPTIONS = {
appClass: null,
theme: 'classic',
useAsButton: false,
padding: 8,
disabled: false,
comparison: true,
closeOnScroll: false,
outputPrecision: 0,
lockOpacity: false,
autoReposition: true,
container: 'body',
components: {
interaction: {}
},
i18n: {},
swatches: null,
inline: false,
sliders: null,
default: '#42445a',
defaultRepresentation: null,
position: 'bottom-middle',
adjustableNumbers: true,
showAlways: false,
closeWithKey: 'Escape'
}; // Create instance via method
Pickr.create = function (options) {
return new Pickr(options);
};
export default Pickr;