UNPKG

@gleb.askerko/componentkit-js

Version:

Lightweight, framework-agnostic JavaScript component library with progress gift components

120 lines (97 loc) 2.7 kB
export class Button { constructor(options = {}) { this.options = { text: 'Button', variant: 'primary', size: 'medium', disabled: false, onClick: null, className: '', ...options }; this.element = null; this.container = null; } render(selector) { this.container = typeof selector === 'string' ? document.querySelector(selector) : selector; if (!this.container) { throw new Error(`Container not found: ${selector}`); } this.element = this.createElement(); this.container.appendChild(this.element); this.bindEvents(); return this; } createElement() { const button = document.createElement('button'); button.textContent = this.options.text; button.className = this.getButtonClasses(); button.disabled = this.options.disabled; return button; } getButtonClasses() { const baseClasses = 'ck-button'; const variantClasses = { primary: 'ck-button--primary', secondary: 'ck-button--secondary', outline: 'ck-button--outline' }; const sizeClasses = { small: 'ck-button--small', medium: 'ck-button--medium', large: 'ck-button--large' }; return [ baseClasses, variantClasses[this.options.variant] || variantClasses.primary, sizeClasses[this.options.size] || sizeClasses.medium, this.options.disabled ? 'ck-button--disabled' : '', this.options.className ].filter(Boolean).join(' '); } bindEvents() { if (this.element && this.options.onClick) { this.element.addEventListener('click', this.options.onClick); } } update(newOptions) { this.options = { ...this.options, ...newOptions }; if (this.element) { this.element.textContent = this.options.text; this.element.className = this.getButtonClasses(); this.element.disabled = this.options.disabled; // Rebind events this.unbindEvents(); this.bindEvents(); } return this; } unbindEvents() { if (this.element && this.options.onClick) { this.element.removeEventListener('click', this.options.onClick); } } destroy() { this.unbindEvents(); if (this.element && this.element.parentNode) { this.element.parentNode.removeChild(this.element); } this.element = null; this.container = null; } // Utility methods enable() { return this.update({ disabled: false }); } disable() { return this.update({ disabled: true }); } setText(text) { return this.update({ text }); } setVariant(variant) { return this.update({ variant }); } }