ExamplesPlaygroundReference Source

coral-spectrum/coral-base-overlay/src/scripts/BaseOverlay.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 base from '../templates/base';
  14. import Vent from '@adobe/vent';
  15. import {validate, transform, commons} from '../../../coral-utils';
  16. import {trapFocus, returnFocus, focusOnShow, scrollOnFocus, FADETIME} from './enums';
  17.  
  18. const CLASSNAME = '_coral-BaseOverlay';
  19.  
  20. // Includes overlay itself
  21. const COMPONENTS_WITH_OVERLAY = `
  22. coral-actionbar,
  23. coral-autocomplete,
  24. coral-colorinput,
  25. coral-cyclebutton,
  26. coral-datepicker,
  27. coral-dialog,
  28. coral-overlay,
  29. coral-popover,
  30. coral-quickactions,
  31. coral-select,
  32. coral-tooltip
  33. `;
  34.  
  35. // The tab capture element that lives at the top of the body
  36. let topTabCaptureEl;
  37. let bottomTabCaptureEl;
  38.  
  39. // A reference to the backdrop element
  40. let backdropEl;
  41.  
  42. // The starting zIndex for overlays
  43. const startZIndex = 10000;
  44.  
  45. // Tab keycode
  46. const TAB_KEY = 9;
  47.  
  48. // A stack interface for overlays
  49. const overlayStack = [];
  50. let OverlayManager = {};
  51.  
  52. /**
  53. Return focus option
  54. */
  55. function preventScroll(instance) {
  56. return {preventScroll: instance.scrollOnFocus === scrollOnFocus.OFF};
  57. }
  58.  
  59. /**
  60. Cancel the backdrop hide mid-animation.
  61. */
  62. let fadeTimeout;
  63.  
  64. function cancelBackdropHide() {
  65. window.clearTimeout(fadeTimeout);
  66. }
  67.  
  68. /**
  69. Set aria-hidden on every immediate child except the one passed, which should not be hidden.
  70. */
  71. function hideEverythingBut(instance) {
  72. // ARIA: Hide all the things
  73. const children = document.body.children;
  74. for (let i = 0 ; i < children.length ; i++) {
  75. const child = children[i];
  76.  
  77. // If it's not a parent of or not the instance itself, it needs to be hidden
  78. if (child !== instance && child.contains && !child.contains(instance)) {
  79. const currentAriaHidden = child.getAttribute('aria-hidden');
  80. if (currentAriaHidden) {
  81. // Store the previous value of aria-hidden if present
  82. // Don't blow away the previously stored value
  83. child._previousAriaHidden = child._previousAriaHidden || currentAriaHidden;
  84. if (currentAriaHidden === 'true') {
  85. // It's already true, don't bother setting
  86. continue;
  87. }
  88. } else {
  89. // Nothing is hidden by default, store that
  90. child._previousAriaHidden = 'false';
  91. }
  92.  
  93. // Hide it
  94. child.setAttribute('aria-hidden', 'true');
  95. }
  96. }
  97.  
  98. // Always show ourselves
  99. instance.setAttribute('aria-hidden', 'false');
  100. }
  101.  
  102. /**
  103. Actually reposition the backdrop to be under the topmost overlay.
  104. */
  105. function doRepositionBackdrop() {
  106. // Position under the topmost overlay
  107. const top = OverlayManager.top();
  108.  
  109. if (top) {
  110. // The backdrop, if shown, should be positioned under the topmost overlay that does have a backdrop
  111. for (let i = overlayStack.length - 1 ; i > -1 ; i--) {
  112. if (overlayStack[i].backdrop) {
  113. backdropEl.style.zIndex = overlayStack[i].zIndex - 1;
  114. break;
  115. }
  116. }
  117.  
  118. // ARIA: Set hidden properly
  119. hideEverythingBut(top.instance);
  120. }
  121. }
  122.  
  123. OverlayManager = {
  124. pop(instance) {
  125. // Get overlay index
  126. const index = this.indexOf(instance);
  127.  
  128. if (index === -1) {
  129. return null;
  130. }
  131.  
  132. // Get the overlay
  133. const overlay = overlayStack[index];
  134.  
  135. // Remove from the stack
  136. overlayStack.splice(index, 1);
  137.  
  138. // Return the passed overlay or the found overlay
  139. return overlay;
  140. },
  141.  
  142. push(instance) {
  143. // Pop overlay
  144. const overlay = this.pop(instance) || {instance};
  145.  
  146. // Get the new highest zIndex
  147. const zIndex = this.getHighestZIndex() + 10;
  148.  
  149. // Store the zIndex
  150. overlay.zIndex = zIndex;
  151. instance.style.zIndex = zIndex;
  152.  
  153. // Push it
  154. overlayStack.push(overlay);
  155.  
  156. if (overlay.backdrop) {
  157. // If the backdrop is shown, we'll need to reposition it
  158. // Generally, a component will not call _pushOverlay unnecessarily
  159. // However, attachedCallback is asynchronous in polyfilld environments,
  160. // so _pushOverlay will be called when shown and when attached
  161. doRepositionBackdrop();
  162. }
  163.  
  164. return overlay;
  165. },
  166.  
  167. indexOf(instance) {
  168. // Loop over stack
  169. // Find overlay
  170. // Return index
  171. for (let i = 0 ; i < overlayStack.length ; i++) {
  172. if (overlayStack[i].instance === instance) {
  173. return i;
  174. }
  175. }
  176. return -1;
  177. },
  178.  
  179. get(instance) {
  180. // Get overlay index
  181. const index = this.indexOf(instance);
  182.  
  183. // Return overlay
  184. return index === -1 ? null : overlayStack[index];
  185. },
  186.  
  187. top() {
  188. const length = overlayStack.length;
  189. return length === 0 ? null : overlayStack[length - 1];
  190. },
  191.  
  192. getHighestZIndex() {
  193. const overlay = this.top();
  194. return overlay ? overlay.zIndex : startZIndex;
  195. },
  196.  
  197. some(...args) {
  198. return overlayStack.some(...args);
  199. },
  200.  
  201. forEach(...args) {
  202. return overlayStack.forEach(...args);
  203. }
  204. };
  205.  
  206. /**
  207. Create the global tab capture element.
  208. */
  209. function createDocumentTabCaptureEls() {
  210. if (!topTabCaptureEl) {
  211. topTabCaptureEl = document.createElement('div');
  212. topTabCaptureEl.setAttribute('coral-tabcapture', '');
  213. topTabCaptureEl.setAttribute('role', 'presentation');
  214. topTabCaptureEl.tabIndex = 0;
  215. document.body.insertBefore(topTabCaptureEl, document.body.firstChild);
  216. topTabCaptureEl.addEventListener('focus', () => {
  217. const top = OverlayManager.top();
  218. if (top && top.instance.trapFocus === trapFocus.ON) {
  219. // Focus on the first tabbable element of the top overlay
  220. Array.prototype.some.call(top.instance.querySelectorAll(commons.TABBABLE_ELEMENT_SELECTOR), (item) => {
  221. if (item.offsetParent !== null && !item.hasAttribute('coral-tabcapture')) {
  222. item.focus(preventScroll(top));
  223. return true;
  224. }
  225.  
  226. return false;
  227. });
  228. }
  229. });
  230.  
  231. bottomTabCaptureEl = document.createElement('div');
  232. bottomTabCaptureEl.setAttribute('coral-tabcapture', '');
  233. bottomTabCaptureEl.setAttribute('role', 'presentation');
  234. bottomTabCaptureEl.tabIndex = 0;
  235. document.body.appendChild(bottomTabCaptureEl);
  236. bottomTabCaptureEl.addEventListener('focus', () => {
  237. const top = OverlayManager.top();
  238. if (top && top.instance.trapFocus === trapFocus.ON) {
  239. const tabbableElement = Array.prototype.filter.call(top.instance.querySelectorAll(commons.TABBABLE_ELEMENT_SELECTOR), (item) => item.offsetParent !== null && !item.hasAttribute('coral-tabcapture')).pop();
  240.  
  241. // Focus on the last tabbable element of the top overlay
  242. if (tabbableElement) {
  243. tabbableElement.focus(preventScroll(top));
  244. }
  245. }
  246. });
  247. } else {
  248. if (document.body.firstElementChild !== topTabCaptureEl) {
  249. // Make sure we stay at the very top
  250. document.body.insertBefore(topTabCaptureEl, document.body.firstChild);
  251. }
  252.  
  253. if (document.body.lastElementChild !== bottomTabCaptureEl) {
  254. // Make sure we stay at the very bottom
  255. document.body.appendChild(bottomTabCaptureEl);
  256. }
  257. }
  258.  
  259. // Make sure the tab capture elemenst are shown
  260. topTabCaptureEl.style.display = 'inline';
  261. bottomTabCaptureEl.style.display = 'inline';
  262. }
  263.  
  264. /**
  265. Called after all overlays are hidden and we shouldn't capture the first tab into the page.
  266. */
  267. function hideDocumentTabCaptureEls() {
  268. if (topTabCaptureEl) {
  269. topTabCaptureEl.style.display = 'none';
  270. bottomTabCaptureEl.style.display = 'none';
  271. }
  272. }
  273.  
  274. /**
  275. Show or restore the aria-hidden state of every child of body.
  276. */
  277. function showEverything() {
  278. // ARIA: Show all the things
  279. const children = document.body.children;
  280. for (let i = 0 ; i < children.length ; i++) {
  281. const child = children[i];
  282. // Restore the previous aria-hidden value
  283. child.setAttribute('aria-hidden', child._previousAriaHidden || 'false');
  284. }
  285. }
  286.  
  287. /**
  288. Actually hide the backdrop.
  289. */
  290. function doBackdropHide() {
  291. document.body.classList.remove('u-coral-noscroll');
  292.  
  293. // Start animation
  294. window.requestAnimationFrame(() => {
  295. backdropEl.classList.remove('is-open');
  296.  
  297. cancelBackdropHide();
  298. fadeTimeout = window.setTimeout(() => {
  299. backdropEl.style.display = 'none';
  300. }, FADETIME);
  301. });
  302.  
  303. // Set flag for testing
  304. backdropEl._isOpen = false;
  305.  
  306. // Wait for animation to complete
  307. showEverything();
  308. }
  309.  
  310. /**
  311. Hide the backdrop if no overlays are using it.
  312. */
  313. function hideOrRepositionBackdrop() {
  314. if (!backdropEl || !backdropEl._isOpen) {
  315. // Do nothing if the backdrop isn't shown
  316. return;
  317. }
  318.  
  319. // Loop over all overlays
  320. const keepBackdrop = OverlayManager.some((overlay) => {
  321. // Check for backdrop usage
  322. return !!overlay.backdrop;
  323. });
  324.  
  325. if (!keepBackdrop) {
  326. // Hide the backdrop
  327. doBackdropHide();
  328. } else {
  329. // Reposition the backdrop
  330. doRepositionBackdrop();
  331. }
  332.  
  333. // Hide/create the document-level tab capture element as necessary
  334. // This only applies to modal overlays (those that have backdrops)
  335. const top = OverlayManager.top();
  336. if (!top || !(top.instance.trapFocus === trapFocus.ON && top.instance._requestedBackdrop)) {
  337. hideDocumentTabCaptureEls();
  338. } else if (top && top.instance.trapFocus === trapFocus.ON && top.instance._requestedBackdrop) {
  339. createDocumentTabCaptureEls();
  340. }
  341. }
  342.  
  343. /**
  344. Handles clicks to the backdrop, calling backdropClickedCallback for every overlay
  345. */
  346. function handleBackdropClick(event) {
  347. OverlayManager.forEach((overlay) => {
  348. if (typeof overlay.instance.backdropClickedCallback === 'function') {
  349. overlay.instance.backdropClickedCallback(event);
  350. }
  351. });
  352. }
  353.  
  354. /**
  355. Actually show the backdrop.
  356. */
  357. function doBackdropShow(zIndex, instance) {
  358. document.body.classList.add('u-coral-noscroll');
  359.  
  360. if (!backdropEl) {
  361. backdropEl = document.createElement('div');
  362. backdropEl.className = '_coral-Underlay';
  363. document.body.appendChild(backdropEl);
  364.  
  365. backdropEl.addEventListener('click', handleBackdropClick);
  366. }
  367.  
  368. // Show just under the provided zIndex
  369. // Since we always increment by 10, this will never collide
  370. backdropEl.style.zIndex = zIndex - 1;
  371.  
  372. // Set flag for testing
  373. backdropEl._isOpen = true;
  374.  
  375. // Start animation
  376. backdropEl.style.display = '';
  377. window.requestAnimationFrame(() => {
  378. // Add the class on the next animation frame so backdrop has time to exist
  379. // Otherwise, the animation for opacity will not work.
  380. backdropEl.classList.add('is-open');
  381.  
  382. cancelBackdropHide();
  383. });
  384.  
  385. hideEverythingBut(instance);
  386. }
  387.  
  388. /**
  389. @base BaseOverlay
  390. @classdesc The base element for Overlay components
  391. */
  392. class BaseOverlay extends superClass {
  393. /** @ignore */
  394. constructor() {
  395. super();
  396.  
  397. // Templates
  398. this._elements = {};
  399. base.call(this._elements);
  400. }
  401.  
  402. /**
  403. Whether to trap tabs and keep them within the overlay. See {@link OverlayTrapFocusEnum}.
  404.  
  405. @type {String}
  406. @default OverlayTrapFocusEnum.OFF
  407. @htmlattribute trapfocus
  408. */
  409. get trapFocus() {
  410. return this._trapFocus || trapFocus.OFF;
  411. }
  412.  
  413. set trapFocus(value) {
  414. value = transform.string(value).toLowerCase();
  415. this._trapFocus = validate.enumeration(trapFocus)(value) && value || trapFocus.OFF;
  416.  
  417. if (this._trapFocus === trapFocus.ON) {
  418. // Give ourselves tabIndex if we are not focusable
  419. if (this.tabIndex < 0) {
  420. /** @ignore */
  421. this.tabIndex = 0;
  422. }
  423.  
  424. // Insert elements
  425. this.insertBefore(this._elements.topTabCapture, this.firstElementChild);
  426. this.appendChild(this._elements.intermediateTabCapture);
  427. this.appendChild(this._elements.bottomTabCapture);
  428.  
  429. // Add listeners
  430. this._handleTabCaptureFocus = this._handleTabCaptureFocus.bind(this);
  431. this._handleRootKeypress = this._handleRootKeypress.bind(this);
  432. this._vent.on('keydown', this._handleRootKeypress);
  433. this._vent.on('focus', '[coral-tabcapture]', this._handleTabCaptureFocus);
  434.  
  435. } else if (this._trapFocus === trapFocus.OFF) {
  436. // Remove elements
  437. this._elements.topTabCapture && this._elements.topTabCapture.remove();
  438. this._elements.intermediateTabCapture && this._elements.intermediateTabCapture.remove();
  439. this._elements.bottomTabCapture && this._elements.bottomTabCapture.remove();
  440.  
  441. // Remove listeners
  442. this._vent.off('keydown', this._handleRootKeypress);
  443. this._vent.off('focus', '[coral-tabcapture]', this._handleTabCaptureFocus);
  444. }
  445. }
  446.  
  447. /**
  448. Whether to return focus to the previously focused element when closed. See {@link OverlayReturnFocusEnum}.
  449.  
  450. @type {String}
  451. @default OverlayReturnFocusEnum.OFF
  452. @htmlattribute returnfocus
  453. */
  454. get returnFocus() {
  455. return this._returnFocus || returnFocus.OFF;
  456. }
  457.  
  458. set returnFocus(value) {
  459. value = transform.string(value).toLowerCase();
  460. this._returnFocus = validate.enumeration(returnFocus)(value) && value || returnFocus.OFF;
  461. }
  462.  
  463. /**
  464. returns element that will receive focus when overlay is closed
  465. @returns {HTMLElement}element passed via returnFocusTo()
  466. */
  467. get returnFocusToElement() {
  468. return this._returnFocusToElement;
  469. }
  470.  
  471. /**
  472. returns element that will receive focus when overlay is hidden
  473. @returns {HTMLElement} element cached
  474. */
  475. get elementToFocusWhenHidden() {
  476. return this._elementToFocusWhenHidden;
  477. }
  478.  
  479. /**
  480. Whether the browser should scroll the document to bring the newly-focused element into view. See {@link OverlayScrollOnFocusEnum}.
  481.  
  482. @type {String}
  483. @default OverlayScrollOnFocusEnum.ON
  484. @htmlattribute scrollonfocus
  485. */
  486. get scrollOnFocus() {
  487. return this._scrollOnFocus || scrollOnFocus.ON;
  488. }
  489.  
  490. set scrollOnFocus(value) {
  491. value = transform.string(value).toLowerCase();
  492. this._scrollOnFocus = validate.enumeration(scrollOnFocus)(value) && value || scrollOnFocus.ON;
  493. }
  494.  
  495. /**
  496. Whether to focus the overlay, when opened or not. By default the overlay itself will get the focus. It also accepts
  497. an instance of HTMLElement or a selector like ':first-child' or 'button:last-of-type'. If the selector returns
  498. multiple elements, it will focus the first element inside the overlay that matches the selector.
  499. See {@link OverlayFocusOnShowEnum}.
  500.  
  501. @type {HTMLElement|String}
  502. @default OverlayFocusOnShowEnum.ON
  503. @htmlattribute focusonshow
  504. */
  505. get focusOnShow() {
  506. return this._focusOnShow || focusOnShow.ON;
  507. }
  508.  
  509. set focusOnShow(value) {
  510. if (typeof value === 'string' || value instanceof HTMLElement) {
  511. this._focusOnShow = value;
  512. }
  513. }
  514.  
  515. /**
  516. Whether this overlay is open or not.
  517.  
  518. @type {Boolean}
  519. @default false
  520. @htmlattribute open
  521. @htmlattributereflected
  522. @emits {coral-overlay:open}
  523. @emits {coral-overlay:close}
  524. @emits {coral-overlay:beforeopen}
  525. @emits {coral-overlay:beforeclose}
  526. */
  527. get open() {
  528. return this._open || false;
  529. }
  530.  
  531. set open(value) {
  532. const silenced = this._silenced;
  533.  
  534. value = transform.booleanAttr(value);
  535.  
  536. // Used for global animations
  537. this.trigger('coral-overlay:_animate');
  538.  
  539. const beforeEvent = this.trigger(value ? 'coral-overlay:beforeopen' : 'coral-overlay:beforeclose');
  540.  
  541. if (!beforeEvent.defaultPrevented) {
  542. const open = this._open = value;
  543. this._reflectAttribute('open', open);
  544.  
  545. // Remove aria-hidden attribute before we show.
  546. // Otherwise, screen readers will not announce
  547. // Doesn't matter when we set aria-hidden true (nothing being announced)
  548. if (open) {
  549. this.removeAttribute('aria-hidden');
  550. } else {
  551. this.setAttribute('aria-hidden', !open);
  552. }
  553.  
  554. // Don't do anything if we're not in the DOM yet
  555. // This prevents errors related to allocating a zIndex we don't need
  556. if (this.parentNode) {
  557. // Do this check afterwards as we may have been appended inside of _show()
  558. if (open) {
  559. // Set z-index
  560. this._pushOverlay();
  561.  
  562. if (this.returnFocus === returnFocus.ON) {
  563. this._elementToFocusWhenHidden =
  564. // cached element
  565. this._elementToFocusWhenHidden ||
  566. // element passed via returnFocusTo()
  567. this._returnFocusToElement ||
  568. // element that had focus before opening the overlay
  569. (document.activeElement === document.body ? null : document.activeElement);
  570. }
  571. } else {
  572. // Release zIndex
  573. this._popOverlay();
  574. }
  575. }
  576.  
  577. // Don't force reflow
  578. window.requestAnimationFrame(() => {
  579. // Keep it silenced
  580. this._silenced = silenced;
  581.  
  582. if (open) {
  583. if (this.trapFocus === trapFocus.ON) {
  584. // Make sure tab capture elements are positioned correctly
  585. if (
  586. // Tab capture elements are no longer at the bottom
  587. this._elements.topTabCapture !== this.firstElementChild ||
  588. this._elements.bottomTabCapture !== this.lastElementChild ||
  589. // Tab capture elements have been separated
  590. this._elements.bottomTabCapture.previousElementSibling !== this._elements.intermediateTabCapture
  591. ) {
  592. this.insertBefore(this._elements.intermediateTabCapture, this.firstElementChild);
  593. this.appendChild(this._elements.intermediateTabCapture);
  594. this.appendChild(this._elements.bottomTabCapture);
  595. }
  596. }
  597.  
  598. // visibility should revert to whatever is specified in CSS, so that transition renders.
  599. this.style.visibility = '';
  600.  
  601. // The default style should be display: none for overlays
  602. // Show ourselves first for centering calculations etc
  603. this.style.display = '';
  604.  
  605. // Do it in the next frame to make the animation happen
  606. window.requestAnimationFrame(() => {
  607. this.classList.add('is-open');
  608. });
  609.  
  610. const openComplete = () => {
  611. if (this.open) {
  612. this._debounce(() => {
  613. // handles the focus behavior based on accessibility recommendations
  614. this._handleFocus();
  615.  
  616. this.trigger('coral-overlay:open');
  617. this._silenced = false;
  618. });
  619. }
  620. };
  621.  
  622. if (this._overlayAnimationTime) {
  623. // Wait for animation to complete
  624. commons.transitionEnd(this, openComplete);
  625. } else {
  626. // Execute immediately
  627. openComplete();
  628. }
  629. } else {
  630. // Fade out
  631. this.classList.remove('is-open');
  632.  
  633. const closeComplete = () => {
  634. if (!this.open) {
  635.  
  636. // When the CSS transition has finished, set visibility to browser default, `visibility: visible`,
  637. // to ensure that the overlay will be included in accessibility name or description
  638. // of an element that references it using `aria-labelledby` or `aria-describedby`.
  639. this.style.visibility = 'visible';
  640.  
  641. // makes sure the focus is returned per accessibility recommendations
  642. this._handleReturnFocus();
  643.  
  644. // Hide self
  645. this.style.display = 'none';
  646.  
  647. this._debounce(() => {
  648. // Inform child overlays that we're closing
  649. this._closeChildOverlays();
  650.  
  651. this.trigger('coral-overlay:close');
  652. this._silenced = false;
  653. });
  654. }
  655. };
  656.  
  657. if (this._overlayAnimationTime) {
  658. // Wait for animation to complete
  659. commons.transitionEnd(this, closeComplete);
  660. } else {
  661. // Execute immediately
  662. closeComplete();
  663. }
  664. }
  665. });
  666. }
  667. }
  668.  
  669. _closeChildOverlays() {
  670. const components = this.querySelectorAll(COMPONENTS_WITH_OVERLAY);
  671.  
  672. // Close all children overlays and components with overlays
  673. for (let i = 0 ; i < components.length ; i++) {
  674. const component = components[i];
  675.  
  676. // Overlay component
  677. if (component.hasAttribute('open')) {
  678. component.removeAttribute('open');
  679. }
  680. // Component that uses an overlay
  681. else if (component._elements && component._elements.overlay && component._elements.overlay.hasAttribute('open')) {
  682. component._elements.overlay.removeAttribute('open');
  683. }
  684. }
  685. }
  686.  
  687. /** @private */
  688. _debounce(f) {
  689. // Used to avoid triggering open/close event continuously
  690. window.clearTimeout(this._debounceId);
  691. this._debounceId = window.setTimeout(() => {
  692. f();
  693. }, 10);
  694. }
  695.  
  696. /**
  697. Check if this overlay is the topmost.
  698.  
  699. @protected
  700. */
  701. _isTopOverlay() {
  702. const top = OverlayManager.top();
  703. return top && top.instance === this;
  704. }
  705.  
  706. /**
  707. Push the overlay to the top of the stack.
  708.  
  709. @protected
  710. */
  711. _pushOverlay() {
  712. OverlayManager.push(this);
  713. }
  714.  
  715. /**
  716. Remove the overlay from the stack.
  717.  
  718. @protected
  719. */
  720. _popOverlay() {
  721. OverlayManager.pop(this);
  722.  
  723. // Automatically hide the backdrop if required
  724. hideOrRepositionBackdrop();
  725. }
  726.  
  727. /**
  728. Show the backdrop.
  729.  
  730. @protected
  731. */
  732. _showBackdrop() {
  733. const overlay = OverlayManager.get(this);
  734.  
  735. // Overlay is not tracked unless the component is in the DOM
  736. // Hence, we need to check
  737. if (overlay) {
  738. overlay.backdrop = true;
  739. doBackdropShow(overlay.zIndex, this);
  740. }
  741.  
  742. // Mark on the instance that the backdrop has been requested for this overlay
  743. this._requestedBackdrop = true;
  744.  
  745. // Mark that the backdrop was requested when not attached to the DOM
  746. // This allows us to know whether to push the overlay when the component is attached
  747. if (!this.parentNode) {
  748. this._showBackdropOnAttached = true;
  749. }
  750.  
  751. if (this.trapFocus === trapFocus.ON) {
  752. createDocumentTabCaptureEls();
  753. }
  754. }
  755.  
  756. /**
  757. Show the backdrop.
  758.  
  759. @protected
  760. */
  761. _hideBackdrop() {
  762. const overlay = OverlayManager.get(this);
  763.  
  764. if (overlay) {
  765. overlay.backdrop = false;
  766.  
  767. // If that was the last overlay using the backdrop, hide it
  768. hideOrRepositionBackdrop();
  769. }
  770.  
  771. // Mark on the instance that the backdrop is no longer needed
  772. this._requestedBackdrop = false;
  773. }
  774.  
  775. /**
  776. Handles keypresses on the root of the overlay and marshalls focus accordingly.
  777.  
  778. @protected
  779. */
  780. _handleRootKeypress(event) {
  781. if (event.target === this && event.keyCode === TAB_KEY) {
  782. // Skip the top tabcapture and focus on the first focusable element
  783. this._focusOn('first');
  784.  
  785. // Stop the normal tab behavior
  786. event.preventDefault();
  787. }
  788. }
  789.  
  790. /**
  791. Handles focus events on tab capture elements.
  792.  
  793. @protected
  794. */
  795. _handleTabCaptureFocus(event) {
  796. // Avoid moving around if we're trying to focus on coral-tabcapture
  797. if (this._ignoreTabCapture) {
  798. this._ignoreTabCapture = false;
  799. return;
  800. }
  801.  
  802. // Focus on the correct tabbable element
  803. const target = event.target;
  804. const which = target === this._elements.intermediateTabCapture ? 'first' : 'last';
  805.  
  806. this._focusOn(which);
  807. }
  808.  
  809. /**
  810. Handles the focus behavior. When "on" is specified it would try to find the first tababble descendent in the
  811. content and if there are no valid candidates it will focus the element itself.
  812.  
  813. @protected
  814. */
  815. _handleFocus() {
  816. // ON handles the focusing per accessibility recommendations
  817. if (this.focusOnShow === focusOnShow.ON) {
  818. this._focusOn('first');
  819. } else if (this.focusOnShow instanceof HTMLElement) {
  820. this.focusOnShow.focus(preventScroll(this));
  821. } else if (typeof this.focusOnShow === 'string' && this.focusOnShow !== focusOnShow.OFF) {
  822. // we need to add :not([coral-tabcapture]) to avoid selecting the tab captures
  823. const selectedElement = this.querySelector(`${this.focusOnShow}:not([coral-tabcapture])`);
  824.  
  825. if (selectedElement) {
  826. selectedElement.focus(preventScroll(this));
  827. }
  828. // in case the selector does not match, it should fallback to the default behavior
  829. else {
  830. this._focusOn('first');
  831. }
  832. }
  833. }
  834.  
  835. /**
  836. @protected
  837. */
  838. _handleReturnFocus() {
  839. if (this.returnFocus === returnFocus.ON && this._elementToFocusWhenHidden) {
  840. if (document.activeElement && !this.contains(document.activeElement)) {
  841. // Don't return focus if the user focused outside of the overlay
  842. return;
  843. }
  844.  
  845. // Return focus, ignoring tab capture if it is an overlay
  846. this._elementToFocusWhenHidden._ignoreTabCapture = true;
  847. this._elementToFocusWhenHidden.focus(preventScroll(this));
  848. this._elementToFocusWhenHidden._ignoreTabCapture = false;
  849.  
  850. // Drop the reference to avoid memory leaks
  851. this._elementToFocusWhenHidden = null;
  852. }
  853. }
  854.  
  855. /**
  856. Focus on the first or last element.
  857.  
  858. @param {String} which
  859. one of "first" or "last"
  860. @protected
  861. */
  862. _focusOn(which) {
  863. const focusableTarget = this._getFocusableElement(which);
  864.  
  865. // if we found a focusing target we focus it
  866. if (focusableTarget) {
  867. focusableTarget.focus(preventScroll(this));
  868. }
  869. // otherwise the element itself should get focus
  870. else {
  871. this.focus(preventScroll(this));
  872. }
  873. }
  874.  
  875. _getFocusableElements() {
  876. return Array.prototype.filter.call(this.querySelectorAll(commons.FOCUSABLE_ELEMENT_SELECTOR), item => item.offsetParent !== null && !item.hasAttribute('coral-tabcapture'));
  877. }
  878.  
  879. _getFocusableElement(which) {
  880. let focusableTarget;
  881.  
  882. if (which === 'first' || which === 'last') {
  883. const focusableElements = this._getFocusableElements();
  884. focusableTarget = focusableElements[which === 'first' ? 'shift' : 'pop']();
  885. }
  886.  
  887. return focusableTarget;
  888. }
  889.  
  890. /**
  891. Open the overlay and set the z-index accordingly.
  892.  
  893. @returns {BaseOverlay} this, chainable
  894. */
  895. show() {
  896. this.open = true;
  897.  
  898. return this;
  899. }
  900.  
  901. /**
  902. Close the overlay.
  903.  
  904. @returns {BaseOverlay} this, chainable
  905. */
  906. hide() {
  907. this.open = false;
  908.  
  909. return this;
  910. }
  911.  
  912. /**
  913. Set the element that focus should be returned to when the overlay is hidden.
  914.  
  915. @param {HTMLElement} element
  916. The element to return focus to. This must be a DOM element, not a jQuery object or selector.
  917.  
  918. @returns {BaseOverlay} this, chainable
  919. */
  920. returnFocusTo(element) {
  921. if (this.returnFocus === returnFocus.OFF) {
  922. // Switch on returning focus if it's off
  923. this.returnFocus = returnFocus.ON;
  924. }
  925.  
  926. // If the element is not focusable,
  927. if (!element.matches(commons.FOCUSABLE_ELEMENT_SELECTOR)) {
  928. // add tabindex so that it is programmatically focusable.
  929. element.setAttribute('tabindex', -1);
  930.  
  931. // On blur, restore element to its prior, not-focusable state
  932. const tempVent = new Vent(element);
  933. tempVent.on('blur.afterFocus', (event) => {
  934. // Wait a frame before testing whether focus has moved to an open overlay or to some other element.
  935. window.requestAnimationFrame(() => {
  936. // If overlay remains open, don't remove tabindex event handler until after it has been closed
  937. const top = OverlayManager.top();
  938. if (top && top.instance.contains(document.activeElement)) {
  939. return;
  940. }
  941. tempVent.off('blur.afterFocus');
  942. event.matchedTarget.removeAttribute('tabindex');
  943. });
  944. }, true);
  945. }
  946.  
  947. this._returnFocusToElement = element;
  948. return this;
  949. }
  950.  
  951. static get _OverlayManager() {
  952. return OverlayManager;
  953. }
  954.  
  955. /**
  956. Returns {@link BaseOverlay} trap focus options.
  957.  
  958. @return {OverlayTrapFocusEnum}
  959. */
  960. static get trapFocus() {
  961. return trapFocus;
  962. }
  963.  
  964. /**
  965. Returns {@link BaseOverlay} return focus options.
  966.  
  967. @return {OverlayReturnFocusEnum}
  968. */
  969. static get returnFocus() {
  970. return returnFocus;
  971. }
  972.  
  973. /**
  974. Returns {@link BaseOverlay} scroll focus options.
  975.  
  976. @return {OverlayScrollOnFocusEnum}
  977. */
  978. static get scrollOnFocus() {
  979. return scrollOnFocus;
  980. }
  981.  
  982. /**
  983. Returns {@link BaseOverlay} focus on show options.
  984.  
  985. @return {OverlayFocusOnShowEnum}
  986. */
  987. static get focusOnShow() {
  988. return focusOnShow;
  989. }
  990.  
  991. /**
  992. Returns {@link BaseOverlay} fadetime in milliseconds.
  993.  
  994. @return {Number}
  995. */
  996. static get FADETIME() {
  997. return FADETIME;
  998. }
  999.  
  1000. static get _attributePropertyMap() {
  1001. return commons.extend(super._attributePropertyMap, {
  1002. trapfocus: 'trapFocus',
  1003. returnfocus: 'returnFocus',
  1004. focusonshow: 'focusOnShow',
  1005. });
  1006. }
  1007.  
  1008. /** @ignore */
  1009. static get observedAttributes() {
  1010. return super.observedAttributes.concat([
  1011. 'trapfocus',
  1012. 'returnfocus',
  1013. 'focusonshow',
  1014. 'open'
  1015. ]);
  1016. }
  1017.  
  1018. /** @ignore */
  1019. connectedCallback() {
  1020. super.connectedCallback();
  1021.  
  1022. if (!this.hasAttribute('trapfocus')) {
  1023. this.trapFocus = this.trapFocus;
  1024. }
  1025. if (!this.hasAttribute('returnfocus')) {
  1026. this.returnFocus = this.returnFocus;
  1027. }
  1028. if (!this.hasAttribute('focusonshow')) {
  1029. this.focusOnShow = this.focusOnShow;
  1030. }
  1031. if (!this.hasAttribute('scrollonfocus')) {
  1032. this.scrollOnFocus = this.scrollOnFocus;
  1033. }
  1034.  
  1035. if (this.open) {
  1036. this._pushOverlay();
  1037.  
  1038. if (this._showBackdropOnAttached) {
  1039. // Show the backdrop again
  1040. this._showBackdrop();
  1041. }
  1042. } else {
  1043. // If overlay is closed, make sure that it is hidden with `display: none`,
  1044. // but set `visibility: visible` to ensure that the overlay will be included in accessibility name or description
  1045. // of an element that references it using `aria-labelledby` or `aria-describedby`.
  1046. this.style.display = 'none';
  1047. this.style.visibility = 'visible';
  1048. }
  1049. }
  1050.  
  1051. /** @ignore */
  1052. render() {
  1053. super.render();
  1054.  
  1055. this.classList.add(CLASSNAME);
  1056. }
  1057.  
  1058. /** @ignore */
  1059. disconnectedCallback() {
  1060. super.disconnectedCallback();
  1061.  
  1062. if (this.open) {
  1063. // Release zIndex as we're not in the DOM any longer
  1064. // When we're re-added, we'll get a new zIndex
  1065. this._popOverlay();
  1066.  
  1067. if (this._requestedBackdrop) {
  1068. // Mark that we'll need to show the backdrop when attached
  1069. this._showBackdropOnAttached = true;
  1070. }
  1071. }
  1072. }
  1073.  
  1074. /**
  1075. Called when the {@link BaseOverlay} is clicked.
  1076.  
  1077. @function backdropClickedCallback
  1078. @protected
  1079. */
  1080.  
  1081. /**
  1082. Triggered before the {@link BaseOverlay} is opened with <code>show()</code> or <code>instance.open = true</code>.
  1083.  
  1084. @typedef {CustomEvent} coral-overlay:beforeopen
  1085.  
  1086. @property {function} preventDefault
  1087. Call to stop the overlay from opening.
  1088. */
  1089.  
  1090. /**
  1091. Triggered after the {@link BaseOverlay} is opened with <code>show()</code> or <code>instance.open = true</code>
  1092.  
  1093. @typedef {CustomEvent} coral-overlay:open
  1094. */
  1095.  
  1096. /**
  1097. Triggered before the {@link BaseOverlay} is closed with <code>hide()</code> or <code>instance.open = false</code>.
  1098.  
  1099. @typedef {CustomEvent} coral-overlay:beforeclose
  1100.  
  1101. @property {function} preventDefault
  1102. Call to stop the overlay from closing.
  1103. */
  1104.  
  1105. /**
  1106. Triggered after the {@link BaseOverlay} is closed with <code>hide()</code> or <code>instance.open = false</code>
  1107.  
  1108. @typedef {CustomEvent} coral-overlay:close
  1109. */
  1110. };
  1111.  
  1112. export default BaseOverlay;