all files / modules/ember-ticketfly-accordion/components/ tf-accordion.js

64.15% Statements 34/53
48.39% Branches 15/31
83.33% Functions 10/12
64.15% Lines 34/53
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                                                                                                                                                                                                                                                                                                                                                    13×                           10×   10× 10×                                                                                                                           11× 11× 11× 11×                     22×                     22×                               13×   13×       13× 13×                             11× 11× 11× 11×   11×   11×   11×                                   11×                                   11× 11×   11×                                
import Ember from 'ember';
import Component from 'ember-component';
import layout from '../templates/components/tf-accordion';
import get from 'ember-metal/get';
import set from 'ember-metal/set';
import computed, { notEmpty, bool } from 'ember-computed';
import { A } from 'ember-array/utils';
import { scheduleOnce } from 'ember-runloop';
import { log, warn } from 'ember-debug';
import { animatePanelOpen, animatePanelClosed } from 'ember-ticketfly-accordion/utils/accordion-panel-animation';
import unsetPanelComponentMotion from 'ember-ticketfly-accordion/utils/unset-panel-component-motion';
 
/**
 * @module tf-accordion
 */
 
const { K: noop } = Ember;
 
/**
 * @class TFAccordionComponent
 * @namespace TFAccordion
 * @extends Ember.Component
 */
export default Component.extend({
  layout,
  classNames: ['tfa-accordion'],
  attributeBindings: ['aria-multiselectable'],
 
  /**
   * Bound to the `role` attribute of the `tf-accordion` component's element.
   *
   * See http://www.w3.org/TR/wai-aria/roles#tablist
   *
   * @property ariaRole
   * @type String
   * @default 'tablist'
   */
  ariaRole: 'tablist',
 
  /**
   * Bound to the `aria-multiselectable` attribute on the `tf-accordion` component's element.
   * The current WAI-ARIA spec states that this should be "true" for accordions
   *
   * @see {@link https://www.w3.org/TR/wai-aria-practices-1.1/#accordion}
   * @see {@link https://github.com/BrianSipple/why-am-i-doing-this/blob/master/ember/aria-attribute-binding-in-components.md}
   * @property aria-multiselectable
   * @type String
   * @default 'true'
   */
  'aria-multiselectable': 'true',
 
  // TODO: Remove from component (possibly make a util)
  KEYCODE_LEFT: 37,
  KEYCODE_UP: 38,
  KEYCODE_RIGHT: 39,
  KEYCODE_DOWN: 40,
 
  /**
   * The index within the array of this accordion's panels
   * corresponding to which panel -- if any -- has focus in
   * the DOM.
   *
   * @property focusedIndex
   * @type Integer
   * @default -1
   */
  focusedIndex: -1,
 
  /* ---------- API ---------- */
 
  /**
   * Whether or not all panels can be expanded at once.
   *
   * Default "accordion" behavior consists of collapsing all
   * but the most-recently expanded panel
   */
  multiExpand: false,
 
  /**
   * Whether or not focus should cycle around the panel during
   * arrow-key navigation.
   *
   * For example, when the last panel is focused and the down arrow
   * is pressed, cycling focus will focus the first panel. Otherwise, the
   * last panel will remain focused.
   *
   * @property cycleFocus
   * @type boolean
   * @default true
   */
  cycleFocus: true,
 
  /**
   * Whether or not animation is enabled for expanding/collapsing a panel
   *
   * @property animatable
   * @type boolean
   * @default true
   */
  animatable: true,
 
  /**
   * Function to execute when animating the panel closed.
   *
   * Defaults to our `animatePanelOpen` utility.
   *
   * @property animatePanelOpen
   * @type Function
   */
  animatePanelOpen,
 
  /**
   * Function to execute when animating the panel closed.
   * Defaults to our `animatePanelClosed` utility.
   *
   * @property animatePanelClosed
   * @type Function
   */
  animatePanelClosed,
 
  /**
   * If the default opening animation is used, this callback
   * will be called when it completes -- passing in the component
   * object of the panel that was animated.
   *
   * @property onPanelAnimatedOpen
   * @type Function
   */
  onPanelAnimatedOpen: unsetPanelComponentMotion,
 
  /**
   * If the default closing animation is used, this callback
   * will be executed when it completes -- passing in the component
   * object of the panel that was animated.
   *
   * @property onPanelAnimatedClosed
   * @type Function
   */
  onPanelAnimatedClosed: unsetPanelComponentMotion,
 
  /**
   * Function for the `onPanelTabFocusIn` action
   *
   * @property onPanelTabFocusIn
   * @type Function
   */
  onPanelTabFocusIn: noop,
 
  /**
   * Function for the `onPanelTabFocusOut` action
   *
   * @property onPanelTabFocusOut
   * @type Function
   */
  onPanelTabFocusOut: noop,
 
  /**
   * Function for the `onPanelExpandChanged` action
   *
   * @property onPanelExpandChanged
   * @type Function
   */
  onPanelExpandChanged: noop,
 
  /**
   * The array of all `tf-accordion-panel` instances within the `tf-accordion` component.
   *
   * @property tabs
   * @type Array | TFAccordion.TFAccordionPanelComponent
   */
  panels: computed(function() {
    return A();
  }),
 
  /* ---------- COMPUTEDS ---------- */
 
  isAnimatable: bool('animatable'),
  hasPanels: notEmpty('panels'),
 
  /* ---------- LIFECYCLE ---------- */
 
  /**
   * @override
   */
  willDestroyElement() {
    this._super(...arguments);
 
    scheduleOnce('actions', this, function () {
      set(this, 'panels', null);
    });
  },
 
  /* ---------- COMPONENT ELEMENT EVENT LISTENERS ---------- */
 
  keyDown(event) {
    const keyCode = event.keyCode || event.which;
 
    if (keyCode === this.KEYCODE_LEFT || keyCode === this.KEYCODE_UP) {
      event.preventDefault();
      this.incrementPanelFocus(-1);
    }
 
    if (keyCode === this.KEYCODE_RIGHT || keyCode === this.KEYCODE_DOWN) {
      event.preventDefault();
      this.incrementPanelFocus(1);
    }
  },
 
  /* ---------- PUBLIC METHODS ---------- */
 
  /**
   * @method incrementPanelFocus
   * @type Function
   * @param {Integer} increment - a numeric value to indicate the "direction"
   *        of the increment (based upon whether it's positive or negative)
   */
  incrementPanelFocus(increment) {
    const cycleFocus = get(this, 'cycleFocus');
    const focusedIndex = get(this, 'focusedIndex');
    const numPanels = get(this, 'panels.length');
    const { max, min } = Math;
 
    let nextIndex;
 
    if (cycleFocus) {
      nextIndex = (focusedIndex + increment + numPanels) % numPanels;
 
    } else {
      nextIndex = increment > 0 ?
        min(numPanels - 1, focusedIndex + 1)
        :
        max(0, focusedIndex -1);
    }
 
    const panelToFocus = get(this, 'panels').objectAt(nextIndex);
 
    scheduleOnce('afterRender', this, 'setFocusOnPanel', panelToFocus, nextIndex);
  },
 
  /**
   * Sets the document's focus on the tab element of a panel component,
   * while updating this component's `focusedIndex` accordingly.
   *
   * @method setFocusOnPanel
   * @param {TFAccordion.TFAccordionPanelTabComponent} panel - the panel
   *        component containing the tab element to focus
   * @param {Integer} index - the index within this component's
   *        array of panels corresponding to the new focus position
   */
  setFocusOnPanel(panel, index) {
    set(this, 'focusedIndex', index);
    get(this, 'panels').setEach('isFocused', false);
    set(panel, 'isFocused', true);
    get(panel, 'tab.element').focus();
  },
 
  /**
   * Adds a panel from the `panels` array
   *
   * @method registerPanel
   * @param {TFAccordion.TFAccordionPanelComponent} panel
   * @public
   */
  registerPanel(panel) {
    get(this, 'panels').addObject(panel);
  },
 
  /**
   * Removes a panel from the `panels` array
   *
   * @method unRegisterPanel
   * @param {TFAccordion.TFAccordionPanelComponent} panel
   * @public
   */
  unRegisterPanel(panel) {
    get(this, 'panels').removeObject(panel);
  },
 
  /**
   * Calls an action corresponding to a panel event that we
   * exposed callbacks to -- passing in the corresponding
   * `panel` and `event` properties as arguments.
   *
   * @method handlePanelEvent
   * @param {String} eventName - the name of the event that `tf-accordion`
   *        expects an action to be bound to.
   * @param {TFAccordion.TFAccordionPanelComponent} panel
   * @param {Object} event - jQuery event from the current action
   * @public
   */
  handlePanelEvent(eventName, panel, event) {
    const actionFn = get(this, eventName);
 
    Iif (typeof actionFn === 'string') {
      warn(`tf-accordion: You must use the action helper for all actions. The try: ${actionFn}=(action "${actionFn}") in your template`, false, {id: 'tf-accordion-string-action'});
    }
 
    log(`tf-accordion: firing action function to handle the ${eventName} event`);
    actionFn(panel, event);
  },
 
  /* ---------- ACTIONS ---------- */
 
  actions: {
 
    /**
     * When a panel is selected, this function handles further
     * animation and expansion operations
     *
     * @param {TFAccordion.TFAccordionPanelComponent} panel
     * @private
     */
    _onPanelSelection(panel) {
      const panels = get(this, 'panels');
      const indexOfSelected = panels.indexOf(panel);
      const shouldExpand = !get(panel, 'isExpanded');
      const isAnimatable = get(this, 'isAnimatable');
 
      this._handleMultiExpandOnPanelSelect(indexOfSelected, panels, isAnimatable);
 
      scheduleOnce('afterRender', this, 'setFocusOnPanel', panel, indexOfSelected);
 
      if (isAnimatable && !get(panel, 'isInMotion')) {
        const animationFunc = shouldExpand ? 'animatePanelOpen' : 'animatePanelClosed';
        const animationCompleteCallback = shouldExpand ? 'onPanelAnimatedOpen' : 'onPanelAnimatedClosed';
 
        set(panel, 'isInMotion', true);
        get(this, animationFunc)(panel, get(this, animationCompleteCallback));
 
      } else {
        set(panel, 'isExpanded', shouldExpand);
      }
    },
 
    /**
     * Private handler for panel body components to send an action to when
     * their expansion state changes
     *
     * @method _panelBodyExpansionWasChanged
     * @param {TFAccordion.TFAccordionPanelComponent} panel - the instance object
     *        of the component for which the body expansion was changed
     * @param {boolean} isExpanded - the new value of the expansion state.
     * @private
     */
    _panelBodyExpansionWasChanged(/* panelComponent, isExpanded */) {
      get(this, 'onPanelExpandChanged')(...arguments);
    }
  },
 
  /* ---------- PRIVATE HELPER METHODS ---------- */
 
  /**
   * If we're not in multi-expand mode, and a different panel was
   * selected than the one currently open, we need to close it
   *
   * @method
   * @private
   * @param {Integer} indexOfSelected
   * @param {Array} panels - An array containing this component's
   *        child panel components
   * @param {boolean} useAnimation
   */
  _handleMultiExpandOnPanelSelect(indexOfSelected, panels, useAnimation) {
    const currentlyFocusedIndex = get(this, 'focusedIndex');
    const multiExpand = get(this, 'multiExpand');
 
    if (
      !multiExpand &&
      (
        currentlyFocusedIndex >= 0 &&
        indexOfSelected !== currentlyFocusedIndex
      )
    ) {
      const currentlyExpandedPanel = panels.objectAt(currentlyFocusedIndex);
 
      Iif (useAnimation) {
        get(this, 'animatePanelClosed')(currentlyExpandedPanel);
 
      } else {
        set(currentlyExpandedPanel, 'isExpanded', false);
      }
    }
  }
});