dropdown.js 16.2 KB
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 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494
function ownKeys(object, enumerableOnly) { var keys = Object.keys(object); if (Object.getOwnPropertySymbols) { var symbols = Object.getOwnPropertySymbols(object); enumerableOnly && (symbols = symbols.filter(function (sym) { return Object.getOwnPropertyDescriptor(object, sym).enumerable; })), keys.push.apply(keys, symbols); } return keys; }

function _objectSpread(target) { for (var i = 1; i < arguments.length; i++) { var source = null != arguments[i] ? arguments[i] : {}; i % 2 ? ownKeys(Object(source), !0).forEach(function (key) { _defineProperty(target, key, source[key]); }) : Object.getOwnPropertyDescriptors ? Object.defineProperties(target, Object.getOwnPropertyDescriptors(source)) : ownKeys(Object(source)).forEach(function (key) { Object.defineProperty(target, key, Object.getOwnPropertyDescriptor(source, key)); }); } return target; }

function _defineProperty(obj, key, value) { if (key in obj) { Object.defineProperty(obj, key, { value: value, enumerable: true, configurable: true, writable: true }); } else { obj[key] = value; } return obj; }

import Popper from 'popper.js';
import { extend } from '../vue';
import { NAME_DROPDOWN } from '../constants/components';
import { HAS_TOUCH_SUPPORT } from '../constants/env';
import { EVENT_NAME_CLICK, EVENT_NAME_HIDDEN, EVENT_NAME_HIDE, EVENT_NAME_SHOW, EVENT_NAME_SHOWN, EVENT_NAME_TOGGLE } from '../constants/events';
import { CODE_DOWN, CODE_ENTER, CODE_ESC, CODE_SPACE, CODE_UP } from '../constants/key-codes';
import { PLACEMENT_TOP_START, PLACEMENT_TOP_END, PLACEMENT_BOTTOM_START, PLACEMENT_BOTTOM_END, PLACEMENT_RIGHT_START, PLACEMENT_LEFT_START } from '../constants/popper';
import { PROP_TYPE_BOOLEAN, PROP_TYPE_NUMBER_STRING, PROP_TYPE_OBJECT, PROP_TYPE_STRING } from '../constants/props';
import { HTMLElement } from '../constants/safe-types';
import { BvEvent } from '../utils/bv-event.class';
import { attemptFocus, closest, contains, isVisible, requestAF, selectAll } from '../utils/dom';
import { getRootEventName, stopEvent } from '../utils/events';
import { isNull } from '../utils/inspect';
import { mergeDeep, sortKeys } from '../utils/object';
import { makeProp, makePropsConfigurable } from '../utils/props';
import { warn } from '../utils/warn';
import { clickOutMixin } from './click-out';
import { focusInMixin } from './focus-in';
import { idMixin, props as idProps } from './id';
import { listenOnRootMixin } from './listen-on-root';
import { registerElementToInstance, removeElementToInstance } from '../utils/element-to-vue-instance-registry'; // --- Constants ---

var ROOT_EVENT_NAME_SHOWN = getRootEventName(NAME_DROPDOWN, EVENT_NAME_SHOWN);
var ROOT_EVENT_NAME_HIDDEN = getRootEventName(NAME_DROPDOWN, EVENT_NAME_HIDDEN); // CSS selectors

var SELECTOR_FORM_CHILD = '.dropdown form';
var SELECTOR_ITEM = ['.dropdown-item', '.b-dropdown-form'].map(function (selector) {
  return "".concat(selector, ":not(.disabled):not([disabled])");
}).join(', '); // --- Helper methods ---
// Return an array of visible items

var filterVisibles = function filterVisibles(els) {
  return (els || []).filter(isVisible);
}; // --- Props ---


export var props = makePropsConfigurable(sortKeys(_objectSpread(_objectSpread({}, idProps), {}, {
  // String: `scrollParent`, `window` or `viewport`
  // HTMLElement: HTML Element reference
  boundary: makeProp([HTMLElement, PROP_TYPE_STRING], 'scrollParent'),
  disabled: makeProp(PROP_TYPE_BOOLEAN, false),
  // Place left if possible
  dropleft: makeProp(PROP_TYPE_BOOLEAN, false),
  // Place right if possible
  dropright: makeProp(PROP_TYPE_BOOLEAN, false),
  // Place on top if possible
  dropup: makeProp(PROP_TYPE_BOOLEAN, false),
  // Disable auto-flipping of menu from bottom <=> top
  noFlip: makeProp(PROP_TYPE_BOOLEAN, false),
  // Number of pixels or a CSS unit value to offset menu
  // (i.e. `1px`, `1rem`, etc.)
  offset: makeProp(PROP_TYPE_NUMBER_STRING, 0),
  popperOpts: makeProp(PROP_TYPE_OBJECT, {}),
  // Right align menu (default is left align)
  right: makeProp(PROP_TYPE_BOOLEAN, false)
})), NAME_DROPDOWN); // --- Mixin ---
// @vue/component

export var dropdownMixin = extend({
  mixins: [idMixin, listenOnRootMixin, clickOutMixin, focusInMixin],
  provide: function provide() {
    var _this = this;

    return {
      getBvDropdown: function getBvDropdown() {
        return _this;
      }
    };
  },
  inject: {
    getBvNavbar: {
      default: function _default() {
        return function () {
          return null;
        };
      }
    }
  },
  props: props,
  data: function data() {
    return {
      visible: false,
      visibleChangePrevented: false
    };
  },
  computed: {
    bvNavbar: function bvNavbar() {
      return this.getBvNavbar();
    },
    inNavbar: function inNavbar() {
      return !isNull(this.bvNavbar);
    },
    toggler: function toggler() {
      var toggle = this.$refs.toggle;
      return toggle ? toggle.$el || toggle : null;
    },
    directionClass: function directionClass() {
      if (this.dropup) {
        return 'dropup';
      } else if (this.dropright) {
        return 'dropright';
      } else if (this.dropleft) {
        return 'dropleft';
      }

      return '';
    },
    boundaryClass: function boundaryClass() {
      // Position `static` is needed to allow menu to "breakout" of the `scrollParent`
      // boundaries when boundary is anything other than `scrollParent`
      // See: https://github.com/twbs/bootstrap/issues/24251#issuecomment-341413786
      return this.boundary !== 'scrollParent' && !this.inNavbar ? 'position-static' : '';
    },
    hideDelay: function hideDelay() {
      return this.inNavbar ? HAS_TOUCH_SUPPORT ? 300 : 50 : 0;
    }
  },
  watch: {
    visible: function visible(newValue, oldValue) {
      if (this.visibleChangePrevented) {
        this.visibleChangePrevented = false;
        return;
      }

      if (newValue !== oldValue) {
        var eventName = newValue ? EVENT_NAME_SHOW : EVENT_NAME_HIDE;
        var bvEvent = new BvEvent(eventName, {
          cancelable: true,
          vueTarget: this,
          target: this.$refs.menu,
          relatedTarget: null,
          componentId: this.safeId ? this.safeId() : this.id || null
        });
        this.emitEvent(bvEvent);

        if (bvEvent.defaultPrevented) {
          // Reset value and exit if canceled
          this.visibleChangePrevented = true;
          this.visible = oldValue; // Just in case a child element triggered `this.hide(true)`

          this.$off(EVENT_NAME_HIDDEN, this.focusToggler);
          return;
        }

        if (newValue) {
          this.showMenu();
        } else {
          this.hideMenu();
        }
      }
    },
    disabled: function disabled(newValue, oldValue) {
      if (newValue !== oldValue && newValue && this.visible) {
        // Hide dropdown if disabled changes to true
        this.visible = false;
      }
    }
  },
  created: function created() {
    // Create private non-reactive props
    this.$_popper = null;
    this.$_hideTimeout = null;
  },

  /* istanbul ignore next */
  deactivated: function deactivated() {
    // In case we are inside a `<keep-alive>`
    this.visible = false;
    this.whileOpenListen(false);
    this.destroyPopper();
  },
  mounted: function mounted() {
    registerElementToInstance(this.$el, this);
  },
  beforeDestroy: function beforeDestroy() {
    this.visible = false;
    this.whileOpenListen(false);
    this.destroyPopper();
    this.clearHideTimeout();
    removeElementToInstance(this.$el);
  },
  methods: {
    // Event emitter
    emitEvent: function emitEvent(bvEvent) {
      var type = bvEvent.type;
      this.emitOnRoot(getRootEventName(NAME_DROPDOWN, type), bvEvent);
      this.$emit(type, bvEvent);
    },
    showMenu: function showMenu() {
      var _this2 = this;

      if (this.disabled) {
        /* istanbul ignore next */
        return;
      } // Only instantiate Popper.js when dropdown is not in `<b-navbar>`


      if (!this.inNavbar) {
        if (typeof Popper === 'undefined') {
          /* istanbul ignore next */
          warn('Popper.js not found. Falling back to CSS positioning', NAME_DROPDOWN);
        } else {
          // For dropup with alignment we use the parent element as popper container
          var el = this.dropup && this.right || this.split ? this.$el : this.$refs.toggle; // Make sure we have a reference to an element, not a component!

          el = el.$el || el; // Instantiate Popper.js

          this.createPopper(el);
        }
      } // Ensure other menus are closed


      this.emitOnRoot(ROOT_EVENT_NAME_SHOWN, this); // Enable listeners

      this.whileOpenListen(true); // Wrap in `$nextTick()` to ensure menu is fully rendered/shown

      this.$nextTick(function () {
        // Focus on the menu container on show
        _this2.focusMenu(); // Emit the shown event


        _this2.$emit(EVENT_NAME_SHOWN);
      });
    },
    hideMenu: function hideMenu() {
      this.whileOpenListen(false);
      this.emitOnRoot(ROOT_EVENT_NAME_HIDDEN, this);
      this.$emit(EVENT_NAME_HIDDEN);
      this.destroyPopper();
    },
    createPopper: function createPopper(element) {
      this.destroyPopper();
      this.$_popper = new Popper(element, this.$refs.menu, this.getPopperConfig());
    },
    // Ensure popper event listeners are removed cleanly
    destroyPopper: function destroyPopper() {
      this.$_popper && this.$_popper.destroy();
      this.$_popper = null;
    },
    // Instructs popper to re-computes the dropdown position
    // useful if the content changes size
    updatePopper: function updatePopper() {
      try {
        this.$_popper.scheduleUpdate();
      } catch (_unused) {}
    },
    clearHideTimeout: function clearHideTimeout() {
      clearTimeout(this.$_hideTimeout);
      this.$_hideTimeout = null;
    },
    getPopperConfig: function getPopperConfig() {
      var placement = PLACEMENT_BOTTOM_START;

      if (this.dropup) {
        placement = this.right ? PLACEMENT_TOP_END : PLACEMENT_TOP_START;
      } else if (this.dropright) {
        placement = PLACEMENT_RIGHT_START;
      } else if (this.dropleft) {
        placement = PLACEMENT_LEFT_START;
      } else if (this.right) {
        placement = PLACEMENT_BOTTOM_END;
      }

      var popperConfig = {
        placement: placement,
        modifiers: {
          offset: {
            offset: this.offset || 0
          },
          flip: {
            enabled: !this.noFlip
          }
        }
      };
      var boundariesElement = this.boundary;

      if (boundariesElement) {
        popperConfig.modifiers.preventOverflow = {
          boundariesElement: boundariesElement
        };
      }

      return mergeDeep(popperConfig, this.popperOpts || {});
    },
    // Turn listeners on/off while open
    whileOpenListen: function whileOpenListen(isOpen) {
      // Hide the dropdown when clicked outside
      this.listenForClickOut = isOpen; // Hide the dropdown when it loses focus

      this.listenForFocusIn = isOpen; // Hide the dropdown when another dropdown is opened

      var method = isOpen ? 'listenOnRoot' : 'listenOffRoot';
      this[method](ROOT_EVENT_NAME_SHOWN, this.rootCloseListener);
    },
    rootCloseListener: function rootCloseListener(vm) {
      if (vm !== this) {
        this.visible = false;
      }
    },
    // Public method to show dropdown
    show: function show() {
      var _this3 = this;

      if (this.disabled) {
        return;
      } // Wrap in a `requestAF()` to allow any previous
      // click handling to occur first


      requestAF(function () {
        _this3.visible = true;
      });
    },
    // Public method to hide dropdown
    hide: function hide() {
      var refocus = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : false;

      /* istanbul ignore next */
      if (this.disabled) {
        return;
      }

      this.visible = false;

      if (refocus) {
        // Child element is closing the dropdown on click
        this.$once(EVENT_NAME_HIDDEN, this.focusToggler);
      }
    },
    // Called only by a button that toggles the menu
    toggle: function toggle(event) {
      event = event || {}; // Early exit when not a click event or ENTER, SPACE or DOWN were pressed

      var _event = event,
          type = _event.type,
          keyCode = _event.keyCode;

      if (type !== 'click' && !(type === 'keydown' && [CODE_ENTER, CODE_SPACE, CODE_DOWN].indexOf(keyCode) !== -1)) {
        /* istanbul ignore next */
        return;
      }
      /* istanbul ignore next */


      if (this.disabled) {
        this.visible = false;
        return;
      }

      this.$emit(EVENT_NAME_TOGGLE, event);
      stopEvent(event); // Toggle visibility

      if (this.visible) {
        this.hide(true);
      } else {
        this.show();
      }
    },
    // Mousedown handler for the toggle

    /* istanbul ignore next */
    onMousedown: function onMousedown(event) {
      // We prevent the 'mousedown' event for the toggle to stop the
      // 'focusin' event from being fired
      // The event would otherwise be picked up by the global 'focusin'
      // listener and there is no cross-browser solution to detect it
      // relates to the toggle click
      // The 'click' event will still be fired and we handle closing
      // other dropdowns there too
      // See https://github.com/bootstrap-vue/bootstrap-vue/issues/4328
      stopEvent(event, {
        propagation: false
      });
    },
    // Called from dropdown menu context
    onKeydown: function onKeydown(event) {
      var keyCode = event.keyCode;

      if (keyCode === CODE_ESC) {
        // Close on ESC
        this.onEsc(event);
      } else if (keyCode === CODE_DOWN) {
        // Down Arrow
        this.focusNext(event, false);
      } else if (keyCode === CODE_UP) {
        // Up Arrow
        this.focusNext(event, true);
      }
    },
    // If user presses ESC, close the menu
    onEsc: function onEsc(event) {
      if (this.visible) {
        this.visible = false;
        stopEvent(event); // Return focus to original trigger button

        this.$once(EVENT_NAME_HIDDEN, this.focusToggler);
      }
    },
    // Called only in split button mode, for the split button
    onSplitClick: function onSplitClick(event) {
      /* istanbul ignore next */
      if (this.disabled) {
        this.visible = false;
        return;
      }

      this.$emit(EVENT_NAME_CLICK, event);
    },
    // Shared hide handler between click-out and focus-in events
    hideHandler: function hideHandler(event) {
      var _this4 = this;

      var target = event.target;

      if (this.visible && !contains(this.$refs.menu, target) && !contains(this.toggler, target)) {
        this.clearHideTimeout();
        this.$_hideTimeout = setTimeout(function () {
          return _this4.hide();
        }, this.hideDelay);
      }
    },
    // Document click-out listener
    clickOutHandler: function clickOutHandler(event) {
      this.hideHandler(event);
    },
    // Document focus-in listener
    focusInHandler: function focusInHandler(event) {
      this.hideHandler(event);
    },
    // Keyboard nav
    focusNext: function focusNext(event, up) {
      var _this5 = this;

      // Ignore key up/down on form elements
      var target = event.target;

      if (!this.visible || event && closest(SELECTOR_FORM_CHILD, target)) {
        /* istanbul ignore next: should never happen */
        return;
      }

      stopEvent(event);
      this.$nextTick(function () {
        var items = _this5.getItems();

        if (items.length < 1) {
          /* istanbul ignore next: should never happen */
          return;
        }

        var index = items.indexOf(target);

        if (up && index > 0) {
          index--;
        } else if (!up && index < items.length - 1) {
          index++;
        }

        if (index < 0) {
          /* istanbul ignore next: should never happen */
          index = 0;
        }

        _this5.focusItem(index, items);
      });
    },
    focusItem: function focusItem(index, items) {
      var el = items.find(function (el, i) {
        return i === index;
      });
      attemptFocus(el);
    },
    getItems: function getItems() {
      // Get all items
      return filterVisibles(selectAll(SELECTOR_ITEM, this.$refs.menu));
    },
    focusMenu: function focusMenu() {
      attemptFocus(this.$refs.menu);
    },
    focusToggler: function focusToggler() {
      var _this6 = this;

      this.$nextTick(function () {
        attemptFocus(_this6.toggler);
      });
    }
  }
});