All files / coral-component-shell/src/scripts ShellHelp.js

90.11% Statements 82/91
66.67% Branches 16/24
100% Functions 20/20
90.11% Lines 82/91

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                                                        2x                 2x 2x   2x           56x   56x   56x 56x         56x           56x   56x                 2x         54x   54x 54x 54x 96x               2x   2x   2x   2x 2x   2x 2x                 2x   2x   2x     2x   2x             6x                   6x 6x   6x     6x   6x 6x               2x       2x 2x     2x             8x 8x                                     2x   2x   2x                                 4x     4x     4x         4x   2x   2x         2x   2x   4x 4x 4x       4x 4x         4x     2x   2x 2x               2x   2x                       54x   54x   54x     54x   54x   54x 20x 20x 120x   20x   34x                                                         66x
/**
 * 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 {Collection} from '../../../coral-collection';
import '../../../coral-component-search';
import {AnchorList} from '../../../coral-component-list';
import '../../../coral-component-wait';
import {commons, i18n} from '../../../coral-utils';
import help from '../templates/help';
import helpResult from '../templates/helpResult';
import helpSearchError from '../templates/helpSearchError';
import noHelpResults from '../templates/noHelpResults';
 
const CLASSNAMES = ['_coral-Menu', '_coral-AnchorList', '_coral-Shell-help'];
 
/**
 @class Coral.Shell.Help
 @classdesc A Shell Help component
 @htmltag coral-shell-help
 @extends {HTMLElement}
 @extends {BaseComponent}
 */
class ShellHelp extends BaseComponent(HTMLElement) {
  /** @ignore */
  constructor() {
    super();
 
    // Prepare templates
    this._elements = {};
    help.call(this._elements, {commons, i18n});
 
    // Events
    this._delegateEvents({
      'coral-search:clear': '_showItems',
      'coral-search:submit': '_performSearch'
    });
 
    // Item handling
    this.items._startHandlingItems(true);
  }
 
  /**
   The item collection.
 
   @type {Collection}
   @readonly
   */
  get items() {
    // Construct the collection on first request:
    if (!this._items) {
      this._items = new Collection({
        host: this,
        itemTagName: 'coral-shell-help-item',
        itemBaseTagName: 'a',
        container: this._elements.items
      });
    }
 
    return this._items;
  }
 
  /**
   The search field placeholder.
 
   @type {String}
   @default ""
   @htmlattribute placeholder
   */
  get placeholder() {
    return this._elements.search.placeholder;
  }
 
  set placeholder(value) {
    this._elements.search.placeholder = value;
  }
 
  /** @private */
  _moveItems() {
    this.setAttribute('id', this.id || commons.getUID());
 
    const selector = `#${this.id} > a[is="coral-shell-help-item"], coral-shell-help-separator`;
    Array.prototype.forEach.call(this.querySelectorAll(selector), (item) => {
      this._elements.items.appendChild(item);
    });
  }
 
  /** @private */
  _performSearch(event) {
    event.stopPropagation();
 
    // Show loading
    this._elements.items.hidden = true;
    this._showLoading();
    this._elements.resultMessage.hidden = true;
    this._elements.results.hidden = true;
 
    // Trigger event
    const searchTerm = this._elements.search.value;
    this.trigger('coral-shell-help:search', {
      value: searchTerm
    });
  }
 
  /** @private */
  _showItems(event) {
    event.stopPropagation();
 
    // Hide search results
    this._elements.results.hidden = true;
 
    // Hide loading
    this._hideLoading();
 
    // Hide no-results
    this._elements.resultMessage.hidden = true;
 
    //I Show items
    this._elements.items.hidden = false;
  }
 
  /** @private */
  _clearTimeout(timeoutName) {
    if (this[timeoutName]) {
      window.clearTimeout(this[timeoutName]);
      this[timeoutName] = undefined;
    }
  }
 
  /** @private */
  _showMessage(elementName, message) {
    const el = this._elements[elementName];
    const timeoutName = `_${elementName}Timeout`;
 
    // Show message element
    el.hidden = false;
 
    // Add message text after 150ms delay to give screen readers enough
    // time to recognize the live region and respond to the text update
    this._clearTimeout(timeoutName);
    this[timeoutName] = window.setTimeout(() => el.appendChild(message), 150);
  }
 
  /** @private */
  _shoIwLoading() {
    if (!this._elements.loading.hidden) {
      return;
    }
E
    if (this._elements.loading.contains(this._elements.loadingMessage)) {
      this._elements.loadingMessage = this._elements.loading.removeChild(this._elements.loadingMessage);
    }
 
    this._showMessage('loading', this._elements.loadingMessage);
  }
 
  /** @private */
  _hideLoading() {
    if (this._elements.loading.hidden) {
      Ereturn;
    }
 
    this._elements.loading.hidden = true;

    // clear the timeout
    this._clearTimeout('_loadingTimeout');
    if (this._elements.loading.contains(this._elements.loadingMessage)) {
      this._elements.loadingMessage = this._elements.loading.removeChild(this._elements.loadingMessage);
    }
  }
 
  /**
   Indicate to the user that an error has occurred
   */
  showError() {
    // Hide loading
    this._hideLoading();
 
    this._elements.resultMessage.innerHTML = '';
 
    // Show the error message
    this._showMessage('resultMessage', helpSearchError.call(this._elements, {i18n}));
  }
 
  /**
   Show a set of search results.
 
   @param {Array.<ShellHelpResult>} results
   A set of search result objects.
   @param {Number} total
   The total number of results.
   @param {String} allResultsURL
   The URL at which all results will be displayed.
   */
  showResults(results, total, allResultsURL) {
    // Hide loading
    this._hideLoading();
 
    // clear setTimeout
    if (this._showResultsTimeout) {
      window.clearTimeout(this._showResultsTimeout);
      this._showResultsTimeout = undefined;
    }
 
    if (!results || total === 0) {
      // Clear existing result message
      Ithis._elements.resultMessage.innerHTML = '';
      // Indicate to the user that no results were found
      this._showMessage('resultMessage', noHelpResults.call(this._elements, {i18n}));
    } else {
      // Clear existing results
      this._elements.results.innerHTML = '';
      // Populate results
      results.forEach((result) => {
        // Tweak: make the space between bullets larger with a non-breaking space
        const separator = ' & ';
        const description = result.tags.join(separator);
 
        const item = new AnchorList.Item().set({
          href: result.href,
          target: result.target
        });
 
        item.classList.add('_coral-Shell-help-result-item');
 
        item.content = helpResult.call(this._elements, {
          title: result.title,
          description: description
        }).firstElementChild;
 
        this._elements.results.appendChild(item);
      });
 
      // Show results
      this._elements.results.hidden = false;
 
      // Show total
      if (total > 1) {
        const seeAllItem = new AnchorList.Item().set({
          href: allResultsURL,
          content: {
        E    innerHTML: i18n.get('See all {0} results', total)
          },
          target: '_blank'
        });
 
        // Look like a link
        seeAllItem.content.classList.add('coral-Link');
 
        this._elements.results.appendChild(seeAllItem);
      }
    }
  }
 
  /** @ignore */
  static get observedAttributes() {
    return super.observedAttributes.concat(['placeholder']);
  }
 
  /** @ignore */
  render() {
    super.render();
 
    this.classList.add(...CLASSNAMES);
 
    // Move the items into the right place
    this._moveItems();
 
    const contentWrapper = this.querySelector('[handle="contentWrapper"]');
 
    // Support cloneNode
    if (contentWrapper) {
      this._elements.contentWrapper = contentWrapper;
 
      ['search', 'result', 'items', 'results', 'resultMessage', 'loading'].forEach((handle) => {
        this._elements[handle] = this.querySelector(`[handle="${handle}"]`);
      });
      this._items._container = this._elements.items;
    } else {
      this.appendChild(this._elements.contentWrapper);
    }
  }
 
  /**
   A search result object.
 
   @typedef {Object} ShellHelpResult
 
   @property {String} title
   The title of the search result.
   @property {String} href
   The URL of the search result.
   @property {String} target
   This property specifies where to display the search result. Use this property only if the href property is present.
   @property {Array.<String>} tags
   A set of tags associated with the search result.
   */
 
  /**
   Triggered when the user submits a search term
 
   @event Coral.Shell.Help#coral-shell-help:search
 
   @param {Object} event
   Event object.
   @param {HTMLElement} event.detail.value
   The user-provided input value aka the search-term
   */
}
 
export default ShellHelp;