clickoutsidehandler.js 1.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445
  1. /**
  2. * @license Copyright (c) 2003-2020, CKSource - Frederico Knabben. All rights reserved.
  3. * For licensing, see LICENSE.md or https://ckeditor.com/legal/ckeditor-oss-license
  4. */
  5. /**
  6. * @module ui/bindings/clickoutsidehandler
  7. */
  8. /* global document */
  9. /**
  10. * Handles clicking **outside** of a specified set of elements, then fires an action.
  11. *
  12. * **Note**: Actually, the action is executed upon `mousedown`, not `click`. It prevents
  13. * certain issues when the user keeps holding the mouse button and the UI cannot react
  14. * properly.
  15. *
  16. * @param {Object} options Configuration options.
  17. * @param {module:utils/dom/emittermixin~Emitter} options.emitter The emitter to which this behavior
  18. * should be added.
  19. * @param {Function} options.activator Function returning a `Boolean`, to determine whether the handler is active.
  20. * @param {Array.<HTMLElement>} options.contextElements HTML elements that determine the scope of the
  21. * handler. Clicking any of them or their descendants will **not** fire the callback.
  22. * @param {Function} options.callback An action executed by the handler.
  23. */
  24. export default function clickOutsideHandler( { emitter, activator, callback, contextElements } ) {
  25. emitter.listenTo( document, 'mousedown', ( evt, domEvt ) => {
  26. if ( !activator() ) {
  27. return;
  28. }
  29. // Check if `composedPath` is `undefined` in case the browser does not support native shadow DOM.
  30. // Can be removed when all supported browsers support native shadow DOM.
  31. const path = typeof domEvt.composedPath == 'function' ? domEvt.composedPath() : [];
  32. for ( const contextElement of contextElements ) {
  33. if ( contextElement.contains( domEvt.target ) || path.includes( contextElement ) ) {
  34. return;
  35. }
  36. }
  37. callback();
  38. } );
  39. }