All files / coral-component-checkbox/src/scripts Checkbox.js

85.98% Statements 92/107
83.05% Branches 49/59
86.84% Functions 33/38
85.98% Lines 92/107

Press n or j to go to the next uncovered block, b, p or k for the previous block.

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                                                    2x 2x                   2x 2x   2x           2238x   2238x   2238x           2238x       2238x           2238x   2238x   2238x                 2238x                       2x         20x     20x     20x   20x   20x   20x           20x                         54x             54x 36x 36x 36x     54x                                                 5840x   5840x   5840x 5840x                 2x                 6x             2092x   2092x   2092x 2092x   2092x 2092x 2092x 2092x   2092x 224x     2092x 672x   672x   42x     630x         2092x   2092x   2092x     2092x         2256x     480x   480x   480x                         134x     250x   250x   250x 250x   250x                     50x     2094x       2094x                             50x     68x   68x                       28x     24x                         318x     98x   98x   98x 98x 98x                         2x                                       2x                                 5590x     106x   106x                 5706x     1544x   1544x                   44x       8x  
/**
 * Copyright 2019 Adobe. All rights reserved.
 * This file is licensed to you under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License. You may obtain a copy
 * of the License at http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software distributed under
 * the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR REPRESENTATIONS
 * OF ANY KIND, either express or implied. See the License for the specific language
 * governing permissions and limitations under the License.
 */
 
import {BaseComponent} from '../../../coral-base-component';
import {BaseFormField} from '../../../coral-base-formfield';
import {Icon} from '../../../coral-component-icon';
import base from '../templates/base';
import {transform, commons, i18n} from '../../../coral-utils';
import {Decorator} from '../../../coral-decorator';
 
const IS_IE_OR_EDGE = navigator.userAgent.indexOf('MSIE') !== -1 || navigator.appVersion.indexOf('Trident/') > 0 ||
  window.navigator.userAgent.indexOf('Edge') !== -1;
 
const CLASSNAME = '_coral-Checkbox';
 
/**
 @class Coral.Checkbox
 @classdesc A Checkbox component to be used as a form field.
 @htmltag coral-checkbox
 @extends {HTMLElement}
 @extends {BaseComponent}
 @extends {BaseFormField}
 */
const Checkbox = Decorator(class extends BaseFormField(BaseComponent(HTMLElement)) {
  /** @ignore */
  constructor() {
    super();
 
    // @polyfill ie
    this._delegateEvents(commons.extend(this._events, {
      click: '_onClick',
      mousedown: '_onMouseDown'
    }));
 
    // Prepare templates
    this._elements = {
      // Try to find the label content zone or create one
      label: this.querySelector('coral-checkbox-label') || document.createElement('coral-checkbox-label')
    };
    base.call(this._elements, {commons, i18n, Icon});
 
    // Pre-define labellable element
    this._labellableElement = this._elements.input;
 
    // Check if the label is empty whenever we get a mutation
    this._observer = new MutationObserver(this._hideLabelIfEmpty.bind(this));
 
    // Watch for changes to the label element's children
    this._observer.observe(this._elements.labelWrapper, {
      // Catch changes to childList
      childList: true,
      // Catch changes to textContent
      characterData: true,
      // Monitor any child node
      subtree: true
    });
  }
 
  /**
   Checked state for the checkbox.
 
   @type {Boolean}
   @default false
   @htmlattribute checked
   @htmlattributereflected
   @emits {change}
   */
  get checked() {
    return this._checked || false;
  }
 
  set checked(value) {
    this._checked = transform.booleanAttr(value);
    this._reflectAttribute('checked', this._checked);
 
    this._elements.input.checked = this._checked;
  }
 
  /**
   Indicates that the checkbox is neither on nor off.
 
   @type {Boolean}
   @default false
   @htmlattribute indeterminate
   @htmlattributereflected
   */
  get indeterminate() {
    return this._indeterminate || false;
  }
 
  set indeterminate(value) {
    this._indeterminate = transform.booleanAttr(value);
    this._reflectAttribute('indeterminate', this._indeterminate);
 
    this.classList.toggle('is-indeterminate', this._indeterminate);
    this._elements.input.indeterminate = this._indeterminate;
    this._elements.input[this._indeterminate ? 'setAttribute' : 'removeAttribute']('aria-checked', 'mixed');
  }E
 
  /**I
   The checkbox's label element.

   @type {CheckboxLabel}
   @contentzone
   */
  get label() {
    return this._getContentZone(this._elements.label);
  }
 
  set label(value) {
    this._setContentZone('label', value, {
      handle: 'label',
      tagName: 'coral-checkbox-label',
      insert: function (label) {
        this._elements.labelWrapper.appendChild(label);
      }
    });
  }
I
  /**
   Name used to submit the data in a form.
   @type {String}
   @default ""
   @htmlattribute name
   @htmlattributereflected
   */
  get name() {
    return this._elements.input.name;
  }
 
  set name(value) {
    this._reflectAttribute('name', value);
 
    this._elements.input.name = value;
  }
 
  /**
   The value that will be submitted when the checkbox is checked. Changing this value will not trigger an event.
 
   @type {String}
   @default "on"
   @htmlattribute value
   */
  get value() {
    return this._elements.input.value || 'on';
  }
 
  set value(value) {
    this._elements.input.value = value;
  }
 
  /**
   Whether this field is disabled or not.
   @type {Boolean}
   @default false
   @htmlattribute disabled
   @htmlattributereflected
   */
  get disabled() {
    return this._disabled || false;
  }
 
  set disabled(value) {
    this._disabled = transform.booleanAttr(value);
    this._reflectAttribute('disabled', this._disabled);
 
    this[this._disabled ? 'setAttribute' : 'removeAttribute']('aria-disabled', this._disabled);
    this.classList.toggle('is-disabled', this._disabled);
    this._elements.input.disabled = this._disabled;
  }
 
  /**
   Whether this field is required or not.
   @type {Boolean}
   @default false
   @htmlattribute required
   @htmlattributereflected
   */
  get required() {
    return this._required || false;
  }
 
  set required(value) {
    this._required = transform.booleanAttr(value);
    this._reflectAttribute('required', this._required);
 
    this._elements.input.required = this._required;
  }
 
  /**
   Whether this field is readOnly or not. Indicating that the user cannot modify the value of the control.
   @type {Boolean}
   @default false
   @htmlattribute readonly
   @htmlattributereflected
   */
  get readOnly() {
    return this._readOnly || false;
  }
 
  set readOnly(value) {
    this._readOnly = transform.booleanAttr(value);
    this._reflectAttribute('readonly', this._readOnly);
 
    this.classList.toggle('is-readOnly', this._readOnly);
    this._elements.input.tabIndex = this._readOnly ? -1 : 0;
  }
 
  /**
   Inherited from {@link BaseFormField#labelled}.
   */
  get labelled() {
    return super.labelled;
  }
 
  set labelled(value) {
    super.labelled = value;
 
    this._hideLabelIfEmpty();
  }
 
  /**
   Inherited from {@link BaseFormField#labelledBy}.
   */
  get labelledBy() {
    return super.labelledBy;
  }
 
  set labelledBy(value) {
    super.labelledBy = value;
 
    this._hideLabelIfEmpty();
  }
 
  /**
   Inherited from {@link BaseComponent#trackingElement}.
   */
  get trackingElement() {
    // it uses the name as the first fallback since it is not localized, otherwise it uses the label
    return typeof this._trackingElement === 'undefined' ?
      // keep spaces to only 1 max and trim. this mimics native html behaviors
      (this.name ? `${this.name}=${this.value}` : '') || (this.label || this).textContent.replace(/\s{2,}/g, ' ').trim() :
      this._trackingElement;
  }
 
  set trackingElement(value) {
    super.trackingElement = value;
  }
 
  /*
   Indicates to the formField that the 'checked' property needs to be set in this component.
 
   @protected
   */
  get _componentTargetProperty() {
    return 'checked';
  }
 
  /*
   Indicates to the formField that the 'checked' property has to be extracted from the event.
 
   @protected
   */
  get _eventTargetProperty() {
    return 'checked';
  }
 
  /** @private */
  _onInputChange(event) {
    // stops the current event
    event.stopPropagation();
 
    /** @ignore */
    this[this._componentTargetProperty] = event.target[this._eventTargetProperty];
 
    // resets the indeterminate state after user interaction
    this.indeterminate = false;
 
    // Explicitly re-emit the change event after the property has been set
    if (this._triggerChangeEvent) {
      // @polyfill ie/edge
      if (IS_IE_OR_EDGE) {
        // We need 1 additional frame in case the indeterminate state is set manually on change event
        window.requestAnimationFrame(() => {
          this.trigger('change');
        });
      } else {
        this.trigger('change');
      }
    }
  }
 
  /**
   @private
   @polyfill ie/edge
   */
  _onClick(event) {
    // Force the check/uncheck and trigger the change event since IE won't.
    if (IS_IE_OR_EDGE && this.indeterminate) {
      // Other browsers like Chrome and Firefox will trigger the change event and set indeterminate = false. So we
      // verify if indeterminate was changed and if not, we manually check/uncheck and trigger the change event.
      this.checked = !this.checked;
      this._onInputChange(event);
    }
    // Handle the click() just like the native checkbox
    else if (event.target === this) {
      this.indeterminate = false;
      this.checked = !this.checked;
      this.trigger('change');
    }
 
    this._trackEvent(this.checked ? 'checked' : 'unchecked', 'coral-checkbox', event);
  }
 
  /**
   Forces checkbox to receive focus on mousedown
   @ignore
   */
  _onMouseDown() {
    const target = this._elements.input;
    window.requestAnimationFrame(() => {
      if (target !== document.activeElement) {
        target.focus();
      }
    });
  }
 
  /**
   Hide the label if it's empty
   @ignore
   */
  _hideLabelIfEmpty() {
    const label = this._elements.label;
 
    // If it's empty and has no non-textnode children, hide the label
    const hiddenValue = !(label.children.length === 0 && label.textContent.replace(/\s*/g, '') === '');
 
    // Toggle the screen reader text
    this._elements.labelWrapper.style.margin = !hiddenValue ? '0' : '';
    this._elements.screenReaderOnly.hidden = !!hiddenValue || !!this.labelledBy || !!this.labelled;
  }
 
  /**
   Inherited from {@link BaseFormField#clear}.
   */
  clear() {
    this.checked = false;
  }

  /**
   Inherited from {@link BaseFormField#reset}.
   */
  reset() {
    this.checked = this._initialCheckedState;
  }
 
  get _contentZones() {
    return {'coral-checkbox-label': 'label'};
  }
 
  /** @ignore */
  static get observedAttributes() {
    return super.observedAttributes.concat(['indeterminate', 'checked']);
  }
 
  /** @ignore */
  render() {
    super.render();

    this.classList.add(CLASSNAME);

    // Create a fragment
    const frag = document.createDocumentFragment();

    const templateHandleNames = ['input', 'checkbox', 'labelWrapper'];
 
    // Render the main template
    frag.appendChild(this._elements.input);
    frag.appendChild(this._elements.checkbox);
    frag.appendChild(this._elements.labelWrapper);
 
    const label = this._elements.label;
 
    // Remove it so we can process children
    if (label.parentNode) {
      label.parentNode.removeChild(label);
    }
 
    while (this.firstChild) {
      const child = this.firstChild;
      if (child.nodeType === Node.TEXT_NODE ||
        child.nodeType === Node.ELEMENT_NODE && templateHandleNames.indexOf(child.getAttribute('handle')) === -1) {
        // Add non-template elements to the label
        label.appendChild(child);
      } else {
        // Remove anything else (e.g labelWrapper)
        this.removeChild(child);
      }
    }
 
    // Add the frag to the component
    this.appendChild(frag);
 
    // Assign the content zones, moving them into place in the process
    this.label = label;
 
    // Cache the initial checked state of the checkbox (in order to implement reset)
    this._initialCheckedState = this.checked;
 
    // Check if we need to hide the label
    // We must do this because IE does not catch mutations when nodes are not in the DOM
    this._hideLabelIfEmpty();
  }
});
 
export default Checkbox;