'use strict'; /* global ComponentUtils */ window.GaiaSwitch = (function(win) { // Extend from the HTMLElement prototype var proto = Object.create(HTMLElement.prototype); // Allow baseurl to be overridden (used for demo page) var baseurl = window.GaiaSwitchBaseurl || '/shared/elements/gaia_switch/'; proto.createdCallback = function() { var shadow = this.createShadowRoot(); this._template = template.content.cloneNode(true); this._input = this._template.querySelector('input[type="checkbox"]'); var checked = this.getAttribute('checked'); if (checked !== null) { this._input.checked = true; } var wrapper = this._template.getElementById('switch'); wrapper.addEventListener('click', this.handleClick.bind(this)); shadow.appendChild(this._template); ComponentUtils.style.call(this, baseurl); // Proxy RTL changes to the shadow root so we can style for RTL. var dirObserver = new MutationObserver(this.updateInternalDir.bind(this)); dirObserver.observe(document.documentElement, { attributeFilter: ['dir'], attributes: true }); this.updateInternalDir(); }; proto.updateInternalDir = function() { var internal = this.shadowRoot.firstElementChild; if (document.documentElement.dir === 'rtl') { internal.setAttribute('dir', 'rtl'); } else { internal.removeAttribute('dir'); } }; proto.handleClick = function(e) { // If user clicked the (optional) link, do not toggle gaia-switch. if (e && e.target.tagName === 'A') { return; } e && e.preventDefault(); e && e.stopImmediatePropagation(); // Dispatch a click event. var event = new MouseEvent('click', { view: window, bubbles: true, cancelable: true }); this.dispatchEvent(event); if (!event.defaultPrevented) { this.checked = !this.checked; } // Dispatch a change event for the gaia-switch. this.dispatchEvent(new CustomEvent('change', { bubbles: true, cancelable: false })); }; /** * Allows users to simulate clicking through javascript. */ proto.click = function() { this.handleClick(); }; /** * Proxy the checked property to the input element. */ Object.defineProperty( proto, 'checked', { get: function() { return this._input.checked; }, set: function(value) { this._input.checked = value; } }); /** * Disabled setter */ Object.defineProperty( proto, 'disabled', { get: function() { return this.hasAttribute('disabled'); }, set: function(value) { if (value) { this.setAttribute('disabled', true); } else { this.removeAttribute('disabled'); } } }); /** * Proxy the name property to the input element. */ Object.defineProperty( proto, 'name', { get: function() { return this.getAttribute('name'); }, set: function(value) { this.setAttribute('name', value); } }); /** * Proxy the input type. */ Object.defineProperty( proto, 'type', { get: function() { return 'gaia-switch'; } }); // HACK: Create a