(() => {
const tagName = 'field-string-app-color-pickr-pro';
const pickrJsCdn = 'https://cdn.jsdelivr.net/npm/@simonwep/pickr/dist/pickr.min.js';
const html = `
<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/@simonwep/pickr/dist/themes/classic.min.css"/>
<div class="pickr-container"></div>`;
class StringColorPickerFlat extends HTMLElement {
constructor() {
super();
}
connectedCallback() {
this.innerHTML = html;
this.connector.loadScript('Pickr', pickrJsCdn, () => { this.initPick() });
}
disconnectedCallback() {
if (this.pickr) this.pickr.destroyAndRemove();
}
initPick() {
this.pickr = new Pickr({
el: '.pickr-container',
theme: 'classic',
default: this.connector.data.value || null,
defaultRepresentation: 'HEXA',
swatches: this.getSwatches(),
components: {
preview: true,
opacity: true,
hue: true,
interaction: {
hex: true,
rgba: true,
hsla: true,
hsva: true,
cmyk: true,
input: true,
cancel: true,
clear: true,
save: true,
},
},
});
this.cleared = !this.connector.data.value;
this.pickr.on('change', (color, instance) => this.applyColor(instance));
this.pickr.on('changestop', (instance) => this.applyColor(instance));
this.pickr.on('swatchselect', (color, instance) => this.applyColor(instance));
this.pickr.on('save', (color,instance) => instance.hide());
this.pickr.on('hide', (instance) => this.update(instance));
this.pickr.on('clear', (instance) => {
this.cleared = true;
this.update();
});
}
applyColor(instance) {
this.cleared = false;
instance.applyColor(true);
}
update(instance) {
if (this.cleared) {
return this.updateIfChanged(null);
}
var color = instance.getColor();
if (color) color = color.toHEXA().toString();
this.updateIfChanged(color);
}
updateIfChanged(value) {
var data = this.connector.data;
if (data.value === '' && value == null) return;
if (data.value === value) return;
data.update(value);
}
getSwatches() {
var swatches = this.connector.field.settings.Swatches;
if (!swatches) return [];
return swatches.split('\n').map((colorLine) => {
var withLabel = colorLine.trim().split(' ');
return withLabel[0];
});
}
}
if (!customElements.get(tagName)) customElements.define(tagName, StringColorPickerFlat);
})();