import iro from "@jaames/iro"; import { CocoComponent } from "@assets/js/base/coco"; import { isValidHex, formatHex } from "@helpers/color"; import { getComponent } from "@helpers/alpine"; export default CocoComponent("colorPicker", ({ selected }) => { return { selectedColor: selected, display: selected, updating: false, invalid: false, colorWheel: { show: false, instance: null, interacting: false, }, getColorWheelToggle() { return getComponent(this.$refs.display.querySelector(".coco-button")); }, init() { this.initColorWheel(); this.$watch("display", (value) => { if (!this.updating) { if (isValidHex(value)) { this.invalid = false; this.selectedColor = formatHex(value); } else { this.invalid = true; } } }); this.$watch("selectedColor", (value) => { const hex = formatHex(value); this.updating = true; this.display = hex; if (this.colorWheel.instance) { this.colorWheel.instance.color.hexString = hex; } this.$dispatch("color-picker:select", { selectedColor: this.selectedColor, }); this.$nextTick(() => (this.updating = false)); }); }, setSelectedColor(color) { this.selectedColor = color; this.invalid = false; }, toggleAdvancedView() { this.colorWheel.show = !this.colorWheel.show; }, initColorWheel() { this.cleanupColorWheel(); const colorWheel = new iro.ColorPicker(this.$refs.colorWheel, { width: this.$refs.swatches.clientWidth, color: this.selectedColor, }); colorWheel.on("input:end", (color) => { if (!this.updating) { this.selectedColor = color.hexString; this.invalid = false; } }); this.colorWheel.instance = colorWheel; }, onResize() { if (this.colorWheel.instance) { this.colorWheel.instance.resize(this.$refs.swatches.clientWidth); } }, toggleColorWheel() { this.colorWheel.show = !this.colorWheel.show; }, cleanupColorWheel() { this.colorWheel.instance = null; this.$refs.colorWheel.innerHTML = ""; }, destroy() { this.getColorWheelToggle().resetState(); this.cleanupColorWheel(); }, }; });