'use strict'; var config = require('./config'); /** * Creates a text-button with text/settings provided. * @param {String} text - text to be shown inside the button * @param {Object} settings */ function TextButton(id, text, settings, isActive) { fabric.Group.call(this); var __active = isActive || false; var _callback = null; var _rect = null; var _text = null; var _id = id; var width = settings.rect ? settings.rect.width : 0; var height = settings.rect ? settings.rect.height : 0; var _rectSettings = $.extend({}, config.textButton.rect(width, height), settings.rect); var _textSettings = $.extend({}, config.textButton.text, settings.text, { text: Array.isArray(text) ? text[0] : text, textActive: Array.isArray(text) ? text[1] : text, }); // Make sure we're interactive this.selectable = true; this.hoverCursor = config.textButton.cursor; // Initialize text and rectangle _text = new fabric.Text('', _textSettings); _rect = new fabric.Rect(_rectSettings); this.addWithUpdate(_rect).addWithUpdate(_text); /** * @param {String} text * @return {TextButton} */ this.setText = function(text) { _text.setText((text || '').toString()).setCoords(); if (_rectSettings.dynamicW) { this.width = _rect.width = _text.width + config.textButton.padding; } if (_rectSettings.dynamicH) { this.height = _rect.height = _text.height + config.textButton.padding; } return this.setCoords(); }; this.getId = function() { return _id; } /** * @return {Boolean} */ this.isActive = function() { return this.__active; }; function handleMouseDown(e) { toggleActiveStyle.call(this); _callback.call(this, e); if (this.__group) { this.__group.render(); } } function toggleActiveStyle() { _rect.setFill(_rectSettings[this.isActive() ? 'activeFill' : 'fill']); _text.setFill(_textSettings[this.isActive() ? 'activeFill' : 'fill']); this.setText(_textSettings[this.isActive() ? 'textActive' : 'text']); } this.onClick = function(callback) { _callback = callback || function() {}; this.on('mousedown', function (e) { // As inactive buttons are still clickable, we first check if the button is 'selectable'. // Only then we should do stuff. if (this.selectable) { this.__active = !this.__active; handleMouseDown.call(this, e); } }.bind(this)); return this; }; this.setActive = function (isActive) { this.__active = typeof isActive === 'undefined' ? true : !!isActive; toggleActiveStyle.call(this); }; if (_textSettings.text) { this.setText(_textSettings.text); } } TextButton.prototype = Object.create(fabric.Group.prototype); TextButton.prototype.constructor = TextButton; module.exports = TextButton;