ExamplesPlaygroundReference Source

coral-spectrum/coral-component-cyclebutton/src/scripts/CycleButton.js

  1. /**
  2. * Copyright 2019 Adobe. All rights reserved.
  3. * This file is licensed to you under the Apache License, Version 2.0 (the "License");
  4. * you may not use this file except in compliance with the License. You may obtain a copy
  5. * of the License at http://www.apache.org/licenses/LICENSE-2.0
  6. *
  7. * Unless required by applicable law or agreed to in writing, software distributed under
  8. * the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR REPRESENTATIONS
  9. * OF ANY KIND, either express or implied. See the License for the specific language
  10. * governing permissions and limitations under the License.
  11. */
  12.  
  13. import {BaseComponent} from '../../../coral-base-component';
  14. import '../../../coral-component-popover';
  15. import '../../../coral-component-button';
  16. import CycleButtonItem from './CycleButtonItem';
  17. import {Icon} from '../../../coral-component-icon';
  18. import {ButtonList, SelectList} from '../../../coral-component-list';
  19. import {SelectableCollection} from '../../../coral-collection';
  20. import base from '../templates/base';
  21. import {transform, validate, commons} from '../../../coral-utils';
  22. import {Decorator} from '../../../coral-decorator';
  23.  
  24. /**
  25. Enumeration for {@link CycleButton} display options.
  26.  
  27. @typedef {Object} CycleButtonDisplayModeEnum
  28.  
  29. @property {String} ICON
  30. Icon display mode.
  31. @property {String} TEXT
  32. Text display mode.
  33. @property {String} ICON_TEXT
  34. Icon and text display mode.
  35. */
  36. const displayMode = {
  37. ICON: 'icon',
  38. TEXT: 'text',
  39. ICON_TEXT: 'icontext'
  40. };
  41.  
  42. /**
  43. Regex used to remove whitespace from selectedItem label for use as an aria-label for accessibility.
  44.  
  45. @ignore
  46. */
  47. const WHITESPACE_REGEX = /[\t\n\r ]+/g;
  48.  
  49. /** @ignore */
  50. const ACTION_TAG_NAME = 'coral-cyclebutton-action';
  51.  
  52. const CLASSNAME = '_coral-CycleSelect';
  53.  
  54. /**
  55. @class Coral.CycleButton
  56. @classdesc A CycleButton component is a simple multi-state toggle button that toggles between the possible items below
  57. a certain threshold, and shows them in a popover selector when above.
  58. @htmltag coral-cyclebutton
  59. @extends {HTMLElement}
  60. @extends {BaseComponent}
  61. */
  62. const CycleButton = Decorator(class extends BaseComponent(HTMLElement) {
  63. /** @ignore */
  64. constructor() {
  65. super();
  66.  
  67. this._id = this.id || commons.getUID();
  68.  
  69. // Templates
  70. this._elements = {};
  71. base.call(this._elements, {Icon, commons, id: this._id});
  72.  
  73. const events = {
  74. 'click button[is="coral-button"]': '_onMouseDown',
  75. 'click ._coral-CycleSelect-button': '_onItemClick',
  76. 'click coral-cyclebutton-item': '_onItemClick',
  77. 'key:down ._coral-CycleSelect-button[aria-expanded=false]': '_onItemClick',
  78.  
  79. // private
  80. 'coral-cyclebutton-item:_selectedchanged': '_onItemSelectedChanged',
  81. 'coral-cyclebutton-item:_validateselection': '_onValidateSelection',
  82. 'coral-cyclebutton-item:_iconchanged coral-cyclebutton-item[selected]': '_onSelectedItemPropertyChange',
  83. 'coral-cyclebutton-item:_displaymodechanged coral-cyclebutton-item[selected]': '_onSelectedItemPropertyChange',
  84.  
  85. 'key:pageup coral-selectlist-item, [coral-list-item]': '_onFocusPreviousItem',
  86. 'key:left coral-selectlist-item, [coral-list-item]': '_onFocusPreviousItem',
  87. 'key:up coral-selectlist-item, [coral-list-item]': '_onFocusPreviousItem',
  88. 'key:pagedown coral-selectlist-item, [coral-list-item]': '_onFocusNextItem',
  89. 'key:right coral-selectlist-item, [coral-list-item]': '_onFocusNextItem',
  90. 'key:down coral-selectlist-item, [coral-list-item]': '_onFocusNextItem',
  91. 'key:home coral-selectlist-item, [coral-list-item]': '_onFocusFirstItem',
  92. 'key:end coral-selectlist-item, [coral-list-item]': '_onFocusLastItem',
  93.  
  94. 'capture:focus coral-selectlist-item, [coral-list-item]': '_onItemFocus',
  95. 'capture:blur coral-selectlist-item, [coral-list-item]': '_onItemBlur',
  96.  
  97. 'coral-overlay:open': '_onOverlayOpen',
  98. 'coral-overlay:close': '_onOverlayClose'
  99. };
  100.  
  101. const overlay = this._elements.overlay;
  102. const overlayId = overlay.id;
  103.  
  104. // Overlay
  105. events[`global:capture:click #${overlayId} button[is="coral-buttonlist-item"]`] = '_onActionClick';
  106. events[`global:capture:coral-selectlist:beforechange #${overlayId}`] = '_onSelectListBeforeChange';
  107. events[`global:capture:coral-selectlist:change #${overlayId}`] = '_onSelectListChange';
  108. // Keyboard interaction
  109. events[`global:keypress #${overlayId}`] = '_onOverlayKeyPress';
  110.  
  111. // Attach events
  112. this._delegateEvents(events);
  113.  
  114. // Used for eventing
  115. this._oldSelection = null;
  116.  
  117. // Init the collection mutation observer
  118. this.items._startHandlingItems(true);
  119. this.actions._startHandlingItems(true);
  120. }
  121.  
  122. /**
  123. Returns the inner overlay to allow customization.
  124.  
  125. @type {Popover}
  126. @readonly
  127. */
  128. get overlay() {
  129. return this._elements.overlay;
  130. }
  131.  
  132. /**
  133. The Collection Interface that allows interacting with the items that the component contains.
  134.  
  135. @type {SelectableCollection}
  136. @readonly
  137. */
  138. get items() {
  139. // just init on demand
  140. if (!this._items) {
  141. this._items = new SelectableCollection({
  142. host: this,
  143. itemTagName: 'coral-cyclebutton-item',
  144. onItemAdded: this._onItemAdded,
  145. onItemRemoved: this._onItemRemoved
  146. });
  147. }
  148. return this._items;
  149. }
  150.  
  151. /**
  152. The selected item in the CycleButton.
  153.  
  154. @type {HTMLElement}
  155. @readonly
  156. */
  157. get selectedItem() {
  158. return this.items._getLastSelected();
  159. }
  160.  
  161. /**
  162. General icon of the CycleButton. The icon will be displayed no matter the selection. If the selected item has
  163. its own icon, it will be overwritten.
  164.  
  165. @type {String}
  166. @default ""
  167. @htmlattribute icon
  168. @htmlattributereflected
  169. */
  170. get icon() {
  171. return this._icon || '';
  172. }
  173.  
  174. set icon(value) {
  175. this._icon = transform.string(value);
  176. this._reflectAttribute('icon', this._icon);
  177.  
  178. const selectedItem = this.selectedItem;
  179. if (selectedItem) {
  180. this._renderSelectedItem(selectedItem);
  181. }
  182. }
  183.  
  184. /**
  185. Number of items that can be directly cycled through before collapsing. If <code>0</code> is used, the items
  186. will never be collapsed.
  187.  
  188. @type {Number}
  189. @default 3
  190. @htmlattribute threshold
  191. @htmlattributereflected
  192. */
  193. get threshold() {
  194. return typeof this._threshold === 'number' ? this._threshold : 3;
  195. }
  196.  
  197. set threshold(value) {
  198. value = transform.number(value);
  199. if (value > -1) {
  200. this._threshold = value;
  201. this._checkExtended();
  202. }
  203. }
  204.  
  205. /**
  206. The Collection Interface that allows interaction with the {@link CycleButtonAction} elements.
  207.  
  208. @type {SelectableCollection}
  209. @readonly
  210. */
  211. get actions() {
  212. if (!this._actions) {
  213. this._actions = new SelectableCollection({
  214. host: this,
  215. itemTagName: ACTION_TAG_NAME,
  216. itemSelector: ACTION_TAG_NAME,
  217. onCollectionChange: this._checkExtended
  218. });
  219. }
  220. return this._actions;
  221. }
  222.  
  223. /**
  224. The CycleButton's displayMode. This defines how the selected item is displayed. If the selected item does not
  225. have the necessary icon or text information then fallback to show whichever is available. The appearance of
  226. collapsed items in the popover are not affected by this property. The displayMode property can be set on an
  227. item to override the component level value when that item is selected.
  228. See {@link CycleButtonDisplayModeEnum}.
  229.  
  230. @type {String}
  231. @default CycleButtonDisplayModeEnum.ICON
  232. @htmlattribute displaymode
  233. @htmlattributereflected
  234. */
  235. get displayMode() {
  236. return this._displayMode || displayMode.ICON;
  237. }
  238.  
  239. set displayMode(value) {
  240. value = transform.string(value).toLowerCase();
  241. this._displayMode = validate.enumeration(displayMode)(value) && value || displayMode.ICON;
  242. this._reflectAttribute('displaymode', this._displayMode);
  243.  
  244. const selectedItem = this.selectedItem;
  245. if (selectedItem) {
  246. this._renderSelectedItem(selectedItem);
  247. }
  248. }
  249.  
  250. /** @private */
  251. _hasMenuItemRadioGroup() {
  252. return this.items.getAll().length > 0 && this.actions.getAll().length > 0;
  253. }
  254.  
  255. /** @private */
  256. _onItemAdded(item) {
  257. if (!this.selectedItem) {
  258. item.setAttribute('selected', '');
  259. }
  260. else {
  261. this._validateSelection(item);
  262. }
  263.  
  264. this._checkExtended();
  265. }
  266.  
  267. /** @private */
  268. _onItemRemoved() {
  269. if (!this.selectedItem) {
  270. this._selectFirstItem();
  271. }
  272.  
  273. this._checkExtended();
  274. }
  275.  
  276. /** @private */
  277. _onItemSelectedChanged(event) {
  278. event.stopImmediatePropagation();
  279.  
  280. this._validateSelection(event.target);
  281. }
  282.  
  283. /** @private */
  284. _onValidateSelection(event) {
  285. event.stopImmediatePropagation();
  286.  
  287. this._validateSelection();
  288. }
  289.  
  290. /** @private */
  291. _selectFirstItem() {
  292. const item = this.items._getFirstSelectable();
  293. if (item) {
  294. item.setAttribute('selected', '');
  295. }
  296. }
  297.  
  298. /** @private */
  299. _validateSelection(item) {
  300. const selectedItems = this.items._getAllSelected();
  301.  
  302. if (item) {
  303. // Deselected item
  304. if (!item.hasAttribute('selected') && !selectedItems.length) {
  305. const siblingItem = this.items._getNextSelectable(item);
  306. // Next selectable item is forced to be selected if selection is cleared
  307. if (item !== siblingItem) {
  308. siblingItem.setAttribute('selected', '');
  309. }
  310. }
  311. // Selected item
  312. else if (item.hasAttribute('selected') && selectedItems.length > 1) {
  313. selectedItems.forEach((selectedItem) => {
  314. if (selectedItem !== item) {
  315. // Don't trigger change events
  316. this._preventTriggeringEvents = true;
  317. selectedItem.removeAttribute('selected');
  318. }
  319. });
  320.  
  321. // We can trigger change events again
  322. this._preventTriggeringEvents = false;
  323. }
  324. }
  325. else if (selectedItems.length > 1) {
  326. // If multiple items are selected, the last one wins
  327. item = selectedItems[selectedItems.length - 1];
  328.  
  329. selectedItems.forEach((selectedItem) => {
  330. if (selectedItem !== item) {
  331. // Don't trigger change events
  332. this._preventTriggeringEvents = true;
  333. selectedItem.removeAttribute('selected');
  334. }
  335. });
  336.  
  337. // We can trigger change events again
  338. this._preventTriggeringEvents = false;
  339. }
  340. // First selectable item is forced to be selected if no selection at all
  341. else if (!selectedItems.length) {
  342. this._selectFirstItem();
  343. }
  344.  
  345. this._renderSelectedItem(this.selectedItem);
  346.  
  347. this._triggerChangeEvent();
  348. }
  349.  
  350. /** @private */
  351. _triggerChangeEvent() {
  352. const selectedItem = this.selectedItem;
  353. const oldSelection = this._oldSelection;
  354.  
  355. if (!this._preventTriggeringEvents && selectedItem !== oldSelection) {
  356. this.trigger('coral-cyclebutton:change', {
  357. oldSelection: oldSelection,
  358. selection: selectedItem
  359. });
  360.  
  361. this._oldSelection = selectedItem;
  362. }
  363. }
  364.  
  365. _onMouseDown(event) {
  366. event.preventDefault();
  367. event.stopPropagation();
  368. this._trackEvent('click', 'coral-cyclebutton', event);
  369. }
  370.  
  371. /** @private */
  372. _onItemClick(event) {
  373. event.preventDefault();
  374.  
  375. const items = this.items.getAll();
  376. const itemCount = items.length;
  377.  
  378. // When we have more than a specified number of items, use the overlay selection. If threshold is 0, then we never
  379. // show the popover. If there are actions, we always show the popover.
  380. if (this._isExtended()) {
  381. // we toggle the overlay if it was already open
  382. this[this._elements.overlay.classList.contains('is-open') ? '_hideOverlay' : '_showOverlay']();
  383. }
  384. // Unless this is the only item we have, select the next item in line:
  385. else if (itemCount > 1) {
  386. const neighbor = this.selectedItem.nextElementSibling;
  387. const nextItem = neighbor.nodeName === 'CORAL-CYCLEBUTTON-ITEM' ? neighbor : items[0];
  388.  
  389. this._selectCycleItem(nextItem);
  390. this._focusItem(this._elements.button);
  391. }
  392. }
  393.  
  394. /**
  395. Render the provided item as selected according to resolved icon and displayMode properties.
  396.  
  397. @private
  398. */
  399. _renderSelectedItem(item) {
  400. if (!item || !item.content) {
  401. return;
  402. }
  403.  
  404. // resolve effective values by checking for item and component level properties
  405. let effectiveDisplayMode = this.displayMode;
  406. const effectiveIcon = item.icon || this.icon || '';
  407.  
  408. if (item.displayMode !== CycleButtonItem.displayMode.INHERIT) {
  409. effectiveDisplayMode = item.displayMode;
  410. }
  411. if (!item.content.textContent.trim() || !effectiveIcon.trim()) {
  412. // if icon or text missing then we fallback to showing whichever is available
  413. effectiveDisplayMode = displayMode.ICON_TEXT;
  414. }
  415.  
  416. // manipulate button sub-component depending on display mode
  417. if (effectiveDisplayMode === displayMode.ICON) {
  418. this._elements.button.icon = effectiveIcon;
  419. this._elements.button.label.innerHTML = '';
  420.  
  421. // @a11y
  422. const ariaLabel = item.content.textContent.replace(WHITESPACE_REGEX, ' ');
  423. this._elements.button.setAttribute('aria-label', ariaLabel);
  424. this._elements.button.setAttribute('title', ariaLabel);
  425. if (ariaLabel && effectiveIcon !== '' && this._elements.button._elements.icon) {
  426. this._elements.button._elements.icon.setAttribute('aria-hidden', true);
  427. }
  428. }
  429. else {
  430. // handle display modes that include text
  431. if (effectiveDisplayMode === displayMode.TEXT) {
  432. this._elements.button.icon = '';
  433. }
  434. if (effectiveDisplayMode === displayMode.ICON_TEXT) {
  435. this._elements.button.icon = effectiveIcon;
  436. if (effectiveIcon !== '' && this._elements.button._elements.icon) {
  437. this._elements.button._elements.icon.setAttribute('aria-hidden', true);
  438. }
  439. }
  440. this._elements.button.label.innerHTML = item.content.innerHTML;
  441.  
  442. // @a11y we do not require aria attributes since we already show text
  443. this._elements.button.removeAttribute('aria-label');
  444. this._elements.button.removeAttribute('title');
  445. }
  446. }
  447.  
  448. /**
  449. Update currently selected item if it's <code>icon</code> or <code>displayMode</code> properties have changed.
  450.  
  451. @private
  452. */
  453. _onSelectedItemPropertyChange(event) {
  454. // stops propagation because the event is internal to the component
  455. event.stopImmediatePropagation();
  456. this._renderSelectedItem(event.target);
  457. }
  458.  
  459. /** @private */
  460. _onSelectListBeforeChange(event) {
  461. if (event.detail.item.selected) {
  462. event.preventDefault();
  463. if (!this._isPopulatingLists) {
  464. // Hide the overlay, cleanup will be done before overlay.show()
  465. this._hideOverlay();
  466. }
  467. }
  468. }
  469.  
  470. /** @private */
  471. _onSelectListChange(event) {
  472. event.stopImmediatePropagation();
  473. event.preventDefault();
  474.  
  475. let origNode;
  476. const selectListItem = event.detail.selection;
  477. if (selectListItem) {
  478. origNode = selectListItem._originalItem;
  479.  
  480. this._selectCycleItem(origNode);
  481.  
  482. if (!this._isPopulatingLists) {
  483. // Hide the overlay, cleanup will be done before overlay.show()
  484. this._hideOverlay();
  485. }
  486. }
  487.  
  488. this._trackEvent('selected', 'coral-cyclebutton-item', event, origNode);
  489. }
  490.  
  491. _onOverlayKeyPress(event) {
  492. // Focus on item which text starts with pressed keys
  493. this._elements.selectList._onKeyPress(event);
  494. }
  495.  
  496. /** @private */
  497. _onActionClick(event) {
  498. event.stopPropagation();
  499.  
  500. const item = event.matchedTarget;
  501. const proxyEvent = item._originalItem.trigger('click');
  502.  
  503. if (!proxyEvent.defaultPrevented) {
  504. this._hideOverlay();
  505. }
  506.  
  507. this._trackEvent('selected', 'coral-cyclebutton-action', event, item);
  508. }
  509.  
  510. /** @private */
  511. _isExtended() {
  512. const hasActions = this.actions.getAll().length > 0;
  513. return this.threshold > 0 && this.items.getAll().length >= this.threshold || hasActions;
  514. }
  515.  
  516. /** @private */
  517. _checkExtended() {
  518. const isExtended = this._isExtended();
  519. this.classList.toggle(`${CLASSNAME}--extended`, isExtended);
  520.  
  521. // @a11y
  522. if (isExtended) {
  523. this._elements.button.setAttribute('aria-controls', this._elements.overlay.id);
  524. this._elements.button.setAttribute('aria-haspopup', true);
  525. this._elements.button.setAttribute('aria-expanded', false);
  526.  
  527. // Assign the button as the target for the overlay
  528. this._elements.overlay.target = this._elements.button;
  529. this._elements.overlay.hidden = false;
  530.  
  531. // Regions within the overlay should have role=presentation
  532. this._elements.overlay.content.setAttribute('role', 'presentation');
  533. }
  534. else {
  535. this._elements.button.removeAttribute('aria-controls');
  536. this._elements.button.removeAttribute('aria-haspopup');
  537. this._elements.button.removeAttribute('aria-expanded');
  538.  
  539. // Remove target and hide overlay
  540. this._elements.overlay.target = null;
  541. this._elements.overlay.hidden = true;
  542. }
  543. }
  544.  
  545. /** @ignore */
  546. _focusItem(item) {
  547. if (item) {
  548. item.focus();
  549. }
  550. }
  551.  
  552. /** @private */
  553. _onFocusPreviousItem(event) {
  554. event.preventDefault();
  555. const items = this._getSelectableItems();
  556. if (items.length > 1) {
  557. const el = event.matchedTarget;
  558. const index = items.indexOf(el);
  559. if (index > 0) {
  560. this._focusItem(items[index - 1]);
  561. }
  562. else if (document.activeElement !== el) {
  563. // make sure ButtonList doesn't wrap focus
  564. this._focusItem(el);
  565. }
  566. }
  567. }
  568.  
  569. /** @private */
  570. _onFocusNextItem(event) {
  571. event.preventDefault();
  572. const items = this._getSelectableItems();
  573. if (items.length > 1) {
  574. const el = event.matchedTarget;
  575. const index = items.indexOf(el);
  576. if (index < items.length - 1) {
  577. this._focusItem(items[index + 1]);
  578. }
  579. else if (document.activeElement !== el) {
  580. // make sure ButtonList doesn't wrap focus
  581. this._focusItem(el);
  582. }
  583. }
  584. }
  585.  
  586. /** @private */
  587. _onFocusFirstItem(event) {
  588. event.preventDefault();
  589. this._focusItem(this._getSelectableItems()[0]);
  590. }
  591.  
  592. /** @private */
  593. _onFocusLastItem(event) {
  594. event.preventDefault();
  595. const items = this._getSelectableItems();
  596. this._focusItem(items[items.length - 1]);
  597. }
  598.  
  599. /** @private */
  600. _getSelectableItems() {
  601. const items = this.items.getAll();
  602. const actions = this.actions.getAll();
  603. return items
  604. .concat(actions)
  605. .map(item => item._selectListItem || item._buttonListItem)
  606. .filter(item => {
  607. !item.hasAttribute('hidden') &&
  608. !item.hasAttribute('disabled') &&
  609. item.offsetParent !== null &&
  610. (item.offsetWidth > 0 || item.offsetHeight > 0);
  611. });
  612. }
  613.  
  614. /** @private */
  615. _onItemFocus(event) {
  616. this._elements.selectList.classList.toggle('is-focused', true);
  617. event.matchedTarget.classList.toggle('focus-ring', true);
  618. }
  619.  
  620. /** @private */
  621. _onItemBlur(event) {
  622. this._elements.selectList.classList.toggle('is-focused', false);
  623. event.matchedTarget.classList.toggle('focus-ring', false);
  624. }
  625.  
  626. _onOverlayClose() {
  627. // @a11y
  628. this._elements.button.setAttribute('aria-expanded', false);
  629. }
  630.  
  631. _onOverlayOpen() {
  632. // @a11y
  633. this._elements.button.setAttribute('aria-expanded', true);
  634. }
  635.  
  636. /** @ignore */
  637. _hideOverlay() {
  638. this._elements.overlay.hide();
  639. }
  640.  
  641. /** @ignore */
  642. _getSelectListItem(item) {
  643. const selectListItem = new SelectList.Item();
  644.  
  645. // Needs to be reflected on the generated Item.
  646. selectListItem.trackingElement = item.trackingElement;
  647.  
  648. // We do first the content, so that the icon is not destroyed
  649. const selectListItemContent = new SelectList.Item.Content();
  650. selectListItemContent.innerHTML = item.content.innerHTML;
  651. selectListItem.content = selectListItemContent;
  652.  
  653. // Specify the icon
  654. if (item.icon) {
  655. selectListItem.icon = item.icon;
  656. }
  657.  
  658. selectListItem.disabled = item.disabled;
  659. selectListItem.selected = item.selected;
  660. selectListItem.setAttribute('role', item.getAttribute('role'));
  661. selectListItem.setAttribute('aria-checked', item.selected);
  662.  
  663. selectListItem._originalItem = item;
  664. item._selectListItem = selectListItem;
  665.  
  666. return selectListItem;
  667. }
  668.  
  669. /** @ignore */
  670. _getActionListItem(action) {
  671. const actionListItem = new ButtonList.Item();
  672.  
  673. actionListItem.icon = action.icon;
  674. actionListItem.disabled = action.disabled;
  675. actionListItem.setAttribute('role', action.getAttribute('role'));
  676. actionListItem.tabIndex = action.tabIndex;
  677.  
  678. // Needs to be reflected on the generated Action.
  679. actionListItem.trackingElement = action.trackingElement;
  680. actionListItem.content.innerHTML = action.content.innerHTML;
  681.  
  682. actionListItem._originalItem = action;
  683. action._buttonListItem = actionListItem;
  684.  
  685. return actionListItem;
  686. }
  687.  
  688. /** @ignore */
  689. _populateLists() {
  690. const selectList = this._elements.selectList;
  691. const actionList = this._elements.actionList;
  692. const items = this.items.getAll();
  693. const actions = this.actions.getAll();
  694. const itemCount = items.length;
  695. const actionCount = actions.length;
  696. let selectListItem;
  697. let actionListItem;
  698.  
  699. this._isPopulatingLists = true;
  700.  
  701. // we empty the existing items before populating the lists again
  702. selectList.items.clear();
  703. actionList.items.clear();
  704.  
  705. // adds the items to the selectList
  706. for (let i = 0 ; i < itemCount ; i++) {
  707. const item = items[i];
  708. selectListItem = this._getSelectListItem(item);
  709.  
  710. selectListItem.icon = item.icon;
  711. selectListItem.setAttribute('aria-checked', item.selected);
  712. selectListItem._elements.icon.setAttribute('aria-hidden', true);
  713.  
  714. selectListItem.set({
  715. disabled: item.disabled,
  716. selected: item.selected
  717. }, true);
  718.  
  719. selectList.items.add(selectListItem);
  720. }
  721.  
  722. // adds any additional actions to the actions buttonList
  723. if (actionCount > 0) {
  724. for (let j = 0 ; j < actionCount ; j++) {
  725. const action = actions[j];
  726.  
  727. actionListItem = this._getActionListItem(action);
  728. actionListItem.disabled = action.disabled;
  729. actionListItem.icon = action.icon;
  730. actionListItem._elements.icon.setAttribute('aria-hidden', true);
  731.  
  732. actionList.items.add(actionListItem);
  733. }
  734.  
  735. this._elements.actionList.removeAttribute('hidden');
  736.  
  737. if (itemCount > 0) {
  738. this._elements.separator.removeAttribute('hidden');
  739. }
  740. }
  741. else {
  742. this._elements.actionList.setAttribute('hidden', '');
  743. this._elements.separator.setAttribute('hidden', '');
  744. }
  745.  
  746. commons.nextFrame(() => {
  747. this._isPopulatingLists = false;
  748. });
  749. }
  750.  
  751. /** @private */
  752. _selectCycleItem(item) {
  753. item.setAttribute('selected', '');
  754. }
  755.  
  756. /** @ignore */
  757. _showOverlay() {
  758. this._populateLists();
  759.  
  760. this._elements.overlay.show();
  761. }
  762.  
  763. /**
  764. Returns {@link CycleButton} display options.
  765.  
  766. @return {CycleButtonDisplayModeEnum}
  767. */
  768. static get displayMode() {
  769. return displayMode;
  770. }
  771.  
  772. static get _attributePropertyMap() {
  773. return commons.extend(super._attributePropertyMap, {
  774. displaymode: 'displayMode'
  775. });
  776. }
  777.  
  778. /** @ignore */
  779. static get observedAttributes() {
  780. return super.observedAttributes.concat(['icon', 'threshold', 'displaymode', 'aria-label', 'aria-labelledby']);
  781. }
  782.  
  783. /** @ignore */
  784. attributeChangedCallback(name, oldValue, value) {
  785. // The accessibility name for the button element
  786. if (name === 'aria-label') {
  787. const hasMenuItemRadioGroup = this._hasMenuItemRadioGroup();
  788.  
  789. // aria-labelledby takes precedence over aria-label
  790. if (this.getAttribute('aria-labelledby')) {
  791. // Button should be labeled by the container and the button, with the selected value, itself
  792. this._elements.button.setAttribute('aria-labelledby', `${this.id} ${this._elements.button.id}`);
  793.  
  794. // Overlay should be labeled by the container with aria-label
  795. this._elements.overlay.setAttribute('aria-labelledby', this.id);
  796.  
  797. // With both items and actions, the items should be grouped and the group should be labeled
  798. // SelectList menuitemradio group should be labeled by the container with aria-label,
  799. // Otherwise the selectList should not be labeled independantly from the menu
  800. this._elements.selectList[hasMenuItemRadioGroup ? 'setAttribute' : 'removeAttribute']('aria-labelledby', this.id);
  801. }
  802. else {
  803. // With no aria-label, clean up aria-labelledby on _elements
  804. this._elements.button.removeAttribute('aria-labelledby');
  805. this._elements.overlay.setAttribute('aria-labelledby', this._elements.button.id);
  806.  
  807. // With both items and actions, the items should be grouped and the group should be labeled
  808. // SelectList menuitemradio group should be labeled by the button, with the selected value, itself,
  809. // Otherwise the selectList should not be labeled independantly from the menu
  810. this._elements.selectList[hasMenuItemRadioGroup ? 'setAttribute' : 'removeAttribute']('aria-labelledby', this._elements.button.id);
  811. }
  812. }
  813. // The id reference for an HTML element that labels the button element accessibility name for the button element
  814. else if (name === 'aria-labelledby') {
  815. if (value || !this.getAttribute('aria-label')) {
  816. this._elements.button.setAttribute('aria-labelledby', `${value} ${this._elements.button.id}`);
  817. this._elements.overlay.setAttribute('aria-labelledby', value || this._elements.button.id);
  818. this._elements.selectList[this._hasMenuItemRadioGroup() ? 'setAttribute' : 'removeAttribute']('aria-labelledby', value || this._elements.button.id);
  819. }
  820. }
  821. else {
  822. super.attributeChangedCallback(name, oldValue, value);
  823. }
  824. }
  825.  
  826. /** @ignore */
  827. connectedCallback() {
  828. super.connectedCallback();
  829.  
  830. const overlay = this._elements.overlay;
  831. // Cannot be open by default when rendered
  832. overlay.removeAttribute('open');
  833. // Restore in DOM
  834. if (overlay._parent) {
  835. overlay._parent.appendChild(overlay);
  836. }
  837. }
  838.  
  839. /** @ignore */
  840. render() {
  841. super.render();
  842.  
  843. if (!this.id) {
  844. this.id = this._id;
  845. }
  846.  
  847. this.classList.add(CLASSNAME);
  848.  
  849. // Default reflected attributes
  850. if (typeof this._threshold === 'undefined') {
  851. this.threshold = 3;
  852. }
  853. if (!this._displayMode) {
  854. this.displayMode = displayMode.ICON;
  855. }
  856.  
  857. // checks the component's extended mode
  858. this._checkExtended();
  859.  
  860. ['button', 'overlay'].forEach((handleName) => {
  861. const handle = this.querySelector(`[handle="${handleName}"]`);
  862. if (handle) {
  863. handle.remove();
  864. }
  865. });
  866.  
  867. const frag = document.createDocumentFragment();
  868.  
  869. // Render the base layout
  870. frag.appendChild(this._elements.button);
  871. frag.appendChild(this._elements.overlay);
  872.  
  873. // Inserting the template before the items
  874. this.appendChild(frag);
  875.  
  876. // Don't trigger events once connected
  877. this._preventTriggeringEvents = true;
  878. this._validateSelection();
  879. this._preventTriggeringEvents = false;
  880.  
  881. this._oldSelection = this.selectedItem;
  882. }
  883.  
  884. /** @ignore */
  885. disconnectedCallback() {
  886. super.disconnectedCallback();
  887.  
  888. const overlay = this._elements.overlay;
  889. // In case it was moved out don't forget to remove it
  890. if (!this.contains(overlay)) {
  891. overlay._parent = overlay._repositioned ? document.body : this;
  892. overlay.remove();
  893. }
  894. }
  895.  
  896. /**
  897. Triggered when the {@link CycleButton} selected item has changed.
  898.  
  899. @typedef {CustomEvent} coral-cyclebutton:change
  900.  
  901. @property {CycleButtonItem} detail.oldSelection
  902. The prior selected item(s).
  903. @property {CycleButtonItem} detail.selection
  904. The newly selected item(s).
  905. */
  906. });
  907.  
  908. export default CycleButton;