import { CocoComponent } from "@js/coco.js"; import { getComponent } from "@helpers/alpine"; import { createSingleton } from "@libs/tippy"; export default CocoComponent("appButtonGroup", () => { return { options: ["collapsible"], ready: false, containerWidth: 0, contentWidth: 0, collapsed: false, singletonTooltip: null, tooltipInstances: [], get collapsible() { return this.$options.collapsible !== false; }, get buttons() { const buttonElements = this.$el.querySelectorAll( "[data-component='app-button']" ); return Array.from(buttonElements).map((el) => getComponent(el)); }, get parent() { return this.$root.parentElement; }, init() { this.$nextTick(() => { if (!this.collapsible) return; this.ready = true; this.onResize(); this.createSingletonTooltip(); }); this.$watch("collapsed", (value) => { this.buttons.forEach((button) => { button.isCollapsed = value; }); this.$nextTick(() => this.createSingletonTooltip()); }); }, createSingletonTooltip() { this.destroySingletonTooltip(); this.tooltipInstances = this.buttons .map((button) => button.shouldShowTooltip() && button.tippyInstance) .filter((t) => t); this.singletonTooltip = createSingleton(this.tooltipInstances, { theme: "coco-tooltip", delay: 100, moveTransition: "transform 0.1s ease-out", }); }, destroySingletonTooltip() { if (this.singletonTooltip && this.singletonTooltip.destroy) { this.singletonTooltip.destroy(); this.singletonTooltip = null; this.tooltipInstances.forEach((tooltip) => tooltip.destroy()); this.tooltipInstances = []; } }, onResize() { if (!this.collapsible) return; this.containerWidth = Math.ceil(this.parent.offsetWidth); if (this.collapsed) { if (this.containerWidth > this.contentWidth) { this.collapsed = false; } } else { if (this.containerWidth < this.contentWidth) { this.collapsed = true; } else { const contentWidth = Math.ceil(this.$refs.buttons.scrollWidth); this.contentWidth = contentWidth; } } }, destroy() { if (this.singletonTooltip) { this.singletonTooltip.destroy(); this.singletonTooltip = null; } }, }; });