all files / montage/ui/button.reel/ button.js

70.97% Statements 66/93
50% Branches 28/56
72% Functions 18/25
70.97% Lines 66/93
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480                                                                                                                                                                                                                    10×                 10×   10×     10×                                                                                                                           60× 25× 25×     60×                   23× 23×   23×           23× 23×   23×                 23× 23× 23×                                                                                                                                                                         20×                                                                                                                                                                                                                                                            
 /*global require, exports*/
 
/**
    @module "montage/ui/native/button.reel"
*/
var Control = require("ui/control").Control,
    KeyComposer = require("composer/key-composer").KeyComposer,
    PressComposer = require("composer/press-composer").PressComposer;
 
// TODO migrate away from using undefinedGet and undefinedSet
 
/**
    Wraps a native <code>&lt;button></code> or <code>&lt;input[type="button"]></code> HTML element. The element's standard attributes are exposed as bindable properties.
    @class module:"montage/ui/native/button.reel".Button
    @extends module:montage/ui/control.Control
    @fires action
    @fires hold
    @example
<caption>JavaScript example</caption>
var b1 = new Button();
b1.element = document.querySelector("btnElement");
b1.addEventListener("action", function(event) {
    console.log("Got event 'action' event");
});
    @example
<caption>Serialized example</caption>
{
    "aButton": {
        "prototype": "montage/ui/native/button.reel",
        "properties": {
            "element": {"#": "btnElement"}
        },
        "listeners": [
            {
                "type": "action",
                "listener": {"@": "appListener"}
            }
        ]
    },
    "listener": {
        "prototype": "appListener"
    }
}
&lt;button data-montage-id="btnElement"></button>
*/
 
var Button = exports.Button = Control.specialize(/** @lends module:"montage/ui/native/button.reel".Button# */ {
 
    /**
        Dispatched when the button is activated through a mouse click, finger tap,
        or when focused and the spacebar is pressed.
 
        @event action
        @memberof module:"montage/ui/native/button.reel".Button
        @param {Event} event
    */
 
    /**
        Dispatched when the button is pressed for a period of time, set by
        {@link holdThreshold}.
 
        @event hold
        @memberof module:"montage/ui/native/button.reel".Button
        @param {Event} event
    */
 
    standardElementTagName: {
        value: "BUTTON"
    },
 
    /* TODO: remove when adding template capability */
    hasTemplate: {
        value: false
    },
 
    drawsFocusOnPointerActivation : {
        value: true
    },
 
    /**
        converter
        A Montage converter object used to convert or format the label displayed by the Button instance. When a new value is assigned to <code>label</code>, the converter object's <code>convert()</code> method is invoked, passing it the newly assigned label value.
        @type {Property}
        @default null
    */
 
    /**
      Stores the node that contains this button's value. Only used for
      non-`<input>` elements.
      @private
    */
    _labelNode: {value:undefined, enumerable: false},
 
    _label: { value: undefined, enumerable: false },
    _emptyLabel: { value: "", enumerable: false },
 
    /**
        The displayed text on the button. In an &lt;input> element this is taken from the element's <code>value</code> attribute. On any other element (including &lt;button>) this is the first child node which is a text node. If one isn't found then it will be created.
 
        If the button has a non-null <code>converter</code> property, the converter object's <code>convert()</code> method is called on the value before being assigned to the button instance.
 
        @type {string}
        @default undefined
    */
    label: {
        get: function () {
            return this._label;
        },
        set: function (value) {
            if (typeof value !== "undefined" && this.converter) {
                try {
                    value = this.converter.convert(value);
                    Iif (this.error) {
                        this.error = null;
                    }
                } catch(e) {
                    // unable to convert - maybe error
                    this.error = e;
                }
            }
 
            this._label = String(value);
 
            if (this.isInputElement) {
                this._value = value;
            }
 
            this.needsDraw = true;
        }
    },
 
    // setLabelInitialValue: {
    //     value: function(value) {
    //         if (this._label === undefined) {
    //                 this._label = value;
    //             }
    //     }
    // },
 
    _promise: {
        value: undefined
    },
 
    promise: {
        get: function () {
            return this._promise;
        },
        set: function (value) {
            var self = this;
            var test = function promiseResolved(){
                            if (promiseResolved.promise === self._promise){
                                self.classList.remove('montage--pending');
                                self._promise = undefined;
                            }
                        };
 
            if (this._promise !== value) {
                this._promise = value;
 
                if (this._promise){
                    this.classList.add('montage--pending')
                    test.promise = value;
                    this._promise.then(test);
                }
            }
        }
    },
 
    /**
        The amount of time in milliseconds the user must press and hold the button a <code>hold</code> event is dispatched. The default is 1 second.
        @type {number}
        @default 1000
    */
    holdThreshold: {
        get: function () {
            return this._pressComposer.longPressThreshold;
        },
        set: function (value) {
            this._pressComposer.longPressThreshold = value;
        }
    },
 
    __pressComposer: {
        enumerable: false,
        value: null
    },
 
    _pressComposer: {
        enumerable: false,
        get: function () {
            if (!this.__pressComposer) {
                this.__pressComposer = new PressComposer();
                this.addComposer(this.__pressComposer);
            }
 
            return this.__pressComposer;
        }
    },
 
    __spaceKeyComposer: {
        value: null
    },
 
    _spaceKeyComposer: {
        get: function () {
            Eif (!this.__spaceKeyComposer) {
                this.__spaceKeyComposer = KeyComposer.createKey(this, "space", "space");
            }
            return this.__spaceKeyComposer;
        }
    },
 
    _enterKeyComposer: {
        get: function () {
            Eif (!this.__enterKeyComposer) {
                this.__enterKeyComposer = KeyComposer.createKey(this, "enter", "enter");
            }
            return this.__enterKeyComposer;
        }
    },
 
    // HTMLInputElement/HTMLButtonElement methods
    // click() deliberately omitted (it isn't available on <button> anyways)
 
    prepareForActivationEvents: {
        value: function () {
            this._pressComposer.addEventListener("pressStart", this, false);
            this._spaceKeyComposer.addEventListener("keyPress", this, false);
            this._enterKeyComposer.addEventListener("keyPress", this, false);
        }
    },
 
    handleKeyPress: {
        value: function (mutableEvent) {
            // when focused action event on spacebar & enter
            // FIXME - property identifier is not set on the mutable event
            if (mutableEvent._event.identifier === "space" ||
                mutableEvent._event.identifier === "enter") {
                this.active = false;
                this._dispatchActionEvent();
            }
        }
    },
 
    // Optimisation
    addEventListener: {
        value: function (type, listener, useCapture) {
            Control.prototype.addEventListener.call(this, type, listener, useCapture);
            if (type === "longAction") {
                this._pressComposer.addEventListener("longPress", this, false);
            }
        }
    },
 
    _addEventListeners: {
        value: function () {
            this._pressComposer.addEventListener("press", this, false);
            this._pressComposer.addEventListener("pressCancel", this, false);
 
            //fixme: @benoit: we should maybe have a flag for this kind of event.
            // can be tricky with the event delegation for example if we don't add it.
            // same issue for: the pressComposer and the translate composer.
            this._pressComposer.addEventListener("longPress", this, false);
        }
    },
 
    _removeEventListeners: {
        value: function () {
            this._pressComposer.removeEventListener("press", this, false);
            this._pressComposer.removeEventListener("pressCancel", this, false);
            this._pressComposer.removeEventListener("longPress", this, false);
        }
    },
 
    // Handlers
 
    /**
    Called when the user starts interacting with the component.
    */
    handlePressStart: {
        value: function (event) {
            Eif (!this._promise){
                this.active = true;
                this._addEventListeners();
            }
        }
    },
 
    /**
    Called when the user has interacted with the button.
    */
    handlePress: {
        value: function (event) {
            Eif (!this._promise){
                this.active = false;
                this._dispatchActionEvent();
                this._removeEventListeners();
            }
        }
    },
 
    handleLongPress: {
        value: function(event) {
            Eif (!this._promise){
                // When we fire the "hold" event we don't want to fire the
                // "action" event as well.
                this._pressComposer.cancelPress();
                this._removeEventListeners();
 
                var longActionEvent = document.createEvent("CustomEvent");
                longActionEvent.initCustomEvent("longAction", true, true, null);
                this.dispatchEvent(longActionEvent);
            }
        }
    },
 
    /**
    Called when all interaction is over.
    @private
    */
    handlePressCancel: {
        value: function(event) {
            this.active = false;
            this._removeEventListeners();
        }
    },
 
    /**
    If this is an input element then the label is handled differently.
    @private
    */
    _isInputElement: {
        value: undefined,
        enumerable: false
    },
    isInputElement: {
        get: function() {
            return this._isInputElement !== undefined ? this._isInputElement : (this._isInputElement = (this.element ? (this.element.tagName === "INPUT") : false));
        },
        enumerable: false
    },
 
    enterDocument: {
        value: function (firstDraw) {
            Iif (Control.prototype.enterDocument) {
                Control.prototype.enterDocument.apply(this, arguments);
            }
 
            Eif (firstDraw) {
                // Only take the value from the element if it hasn't been set
                // elsewhere (i.e. in the serialization)
                Eif (this.isInputElement) {
                    // NOTE: This might not be the best way to do this
                    // With an input element value and label are one and the same
                    Object.defineProperty(this, "value", {
                        get: function() {
                            return this._label;
                        },
                        set: function(value) {
                            this.label = value;
                        }
                    });
 
                    Eif (this._label === undefined) {
                        this.label = this.originalElement.value;
                    }
                    //<button> && Custom
                } else {
                    if(!this.originalElement !== this.element && this._label === undefined) {
                        this._label = this.originalElement.data;
                    }
                    if (!this.element.firstChild) {
                        this.element.appendChild(document.createTextNode(""));
                    }
                    this._labelNode = this.element.firstChild;
                    // this.setLabelInitialValue(this._labelNode.data)
                    // if (this._label === undefined) {
                    //     this._label = this._labelNode.data;
                    // }
                }
 
                //this.classList.add("montage-Button");
                this.element.setAttribute("role", "button");
                this.element.addEventListener("keyup", this, false);
            }
        }
    },
 
    /**
    Draws the label to the DOM.
    @function
    @private
    */
    _drawLabel: {
        enumerable: false,
        value: function (value) {
            if(typeof value !== "string") {
                value = this._emptyLabel;
            }
            if (this.isInputElement) {
                this._element.value = value;
            } else Iif (this._labelNode) {
                this._labelNode.data = value;
            }
        }
    },
 
 
    draw: {
        value: function () {
            this.super();
            this._drawLabel(this._label);
        }
    }
 
});
 
Button.addAttributes( /** @lends module:"montage/ui/native/button.reel".Button# */{
 
/**
    The URL to which the form data will be sumbitted.
    @type {string}
    @default null
*/
    formaction: null,
 
/**
    The content type used to submit the form to the server.
    @type {string}
    @default null
*/
    formenctype: null,
 
/**
    The HTTP method used to submit the form.
    @type {string}
    @default null
*/
    formmethod: null,
 
/**
    Indicates if the form should be validated upon submission.
    @type {boolean}
    @default null
*/
    formnovalidate: {dataType: 'boolean'},
 
/**
    The target frame or window in which the form output should be rendered.
    @type string}
    @default null
*/
    formtarget: null,
 
/**
    A string indicating the input type of the component's element.
    @type {string}
    @default "button"
*/
    type: {value: 'button'},
 
/**
    The name associated with the component's DOM element.
    @type {string}
    @default null
*/
    name: null,
 
/**
    <strong>Use <code>label</code> to set the displayed text on the button</strong>
    The value associated with the element. This sets the value attribute of
    the button that gets sent when the form is submitted.
    @type {string}
    @default null
    @see label
*/
    value: null
 
});