All files select.vue

73.03% Statements 130/178
59.38% Branches 76/128
80% Functions 48/60
73.45% Lines 130/177
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 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629                            1x 1x   1x             14x       23x       23x                                                   23x                 23x               23x 459x     23x       23x                         23x 23x 23x     88x 88x 88x 88x             17x   17x 11x 11x 11x   6x 6x       7x 1x             376x     517x     6x 6x   6x 6x                   88x 88x   88x 2244x             2244x       2244x     88x 88x     122x 122x 122x   122x     111x 111x 111x 111x 111x 111x 111x 111x 111x 111x       122x 122x   122x       122x 122x     122x               918x     918x       468x     459x   459x                                                           459x 459x         5x 5x     5x 3x         5x   5x   2x   1x     1x     3x   55x   4x     24x   2x         5x   5x   4x     1x       11x 11x   11x                                 11x     1x     3x 3x   3x 3x       1x 1x     1x     4x 4x     3x 3x                         282x 6x 6x                                   4x 1x 3x 1x       15x 15x   15x 8x 8x   8x 8x             1x     1404x     52x     52x                     52x                   46x               23x     561x     35x 11x   24x     730x       23x                                                                                                                                                                                                                                                                                                                                            
<template>
  <div class="v-select" :class="classes" :style="variables" role="listbox" tabindex="0" @click.stop @keydown="onFilter($event)" @keydown.enter="onEnter()" @keydown.tab="onTab($event)" @keydown.up="onArrowPress($event, -1)" @keydown.down="onArrowPress($event, 1)" @keydown.left="onArrowPress($event, -1)" @keydown.right="onArrowPress($event, 1)" @keydown.space.prevent="onToggle(true)" @keydown.esc="onEscape()" @focus="onToggleFocus(true)" @blur="onToggleFocus(false)">
    <div ref="label" class="label" v-html="label || placeholder" @click.prevent="onToggle()"></div>
    <div ref="options" class="options" style="animation-duration: 0s;" :aria-hidden="!open">
      <template v-for="opt in list">
        <component v-if="opt.state.group" :key="opt.state.index" :is="optgroup" :group="opt"></component>
        <component v-else :is="option" :key="opt.state.index" :option="opt" @click.native.stop="onClickOption(opt.state.index)" @mouseover.native="onHover($event, opt.state.index)"></component>
      </template>
    </div>
    <select ref="select" class="select" tabindex="-1" v-html="getOptionsHtml()" @change="onSelectChanged($event)"></select>
  </div>
</template>
 
<script type="text/javascript">
import VOptgroup from './optgroup.vue'
import VOption from './option.vue'
 
import { debounce } from 'debounce'
 
export default {
  name: 'VSelect',
  props: {
    options: {
      type: Array,
      default: () => []
    },
    option: {
      type: Object,
      default: () => VOption
    },
    optgroup: {
      type: Object,
      default: () => VOptgroup
    },
    size: {
      type: Number,
      default: 400
    },
    disabled: {
      type: Boolean,
      default: false
    },
    native: {
      type: [Boolean, Function],
      default: true
    },
    placeholder: {
      type: String,
      default: ''
    },
    selected: {
      type: [String, Number],
      default: null
    }
  },
  created: function(){
    // When clicked anywhere, close the dropdown
    // This event is prevented if the click occurs on the dropdown itself
    document.addEventListener('click', (event) => {
      if(!this.$el.contains(event.target)){
        this.onClickOutside()
      }
    })
 
    // When a scroll event occurs anywhere except the dropdown itself,
    // close the dropdown, but continue to re-position it as it scrolls
    // The re-positioning is to take into account longer transition-out animations
    window.addEventListener('scroll', (event) => {
      this.calcPosition()
      this.calcDirection()
      if(this.open && !this.$el.contains(event.target)) this.open = false
    }, true)
 
    // Set the complete list of option/optgroup data by "repairing"
    // each provided option hash with the required/needed data
    this.list = this.options.reduce((options, o) => {
      return options.concat(this.getRepairedItem(o))
    }, [])
 
I    if(this.selection){
      // One of the enabled options in the input json was selected
      // Set the current highlight index to the selected options index
      this.highlightIndex = this.selection.state.index
I    }else if(this.selected !== null){
      // If the selected prop was provided, try and find the selected option
      // in the list of enabled options
      const option = this.getAvailableOptions().find(o => o.value == this.selected)
 
      if(option){
        // A match was found, so set it as the selected & highlighted option
        option.selected = true
        this.highlightIndex = option.state.index
      }
    }
  },
  mounted: function(){
    this.calcPosition()
    this.calcDirection()
    this.calcDimensions()
  },
  updated: function(){
    this.$nextTick(() => {
      this.calcPosition()
      this.calcDirection()
      this.calcDimensions()
    })
  },
  watch: {
    open: function(is_open){
      // Unset the animation duration override, allow
      // the written animation to take place
      this.$refs.options.style.animationDuration = ''
 
      if(is_open){
        this.calcPosition()
        this.$nextTick(this.scrollToHighlighted)
        this.$emit('open')
      }else{
        this.$emit('close')
        this.hoverIndex = -1
      }
    },
    focused: function(is_focused){
      if(!is_focused){
        this.onToggle(false)
      }
    },
    direction: function(){
      this.$refs.options.style.animationDuration = '0s'
    },
    hoverIndex: function(new_index){
      this.getAvailableOptions().forEach(o => o.state.hovered = o.state.index == new_index)
    },
    highlightIndex: function(new_index){
      this.getAvailableOptions().forEach(o => o.state.highlighted = o.state.index == new_index)
    },
    selection: function(new_selection){
E      if(this.selections === undefined){
        const value = new_selection ? new_selection.value : ''
 
        this.$emit('input', value)
        this.$emit('change', value)
      }
    }
  },
  methods: {
    /**
     * Generates the native select elements inner html options
     * This is only used if on a mobile device and +this.native+ is true
     */
    getOptionsHtml: function(){
      let html = ''
      let grouped = false
 
      this.list.forEach((item) => {
I        if(item.state.group){
          if(grouped){
            html += '</optgroup>'
          }
          grouped = true
          html += `<optgroup label="${item.label}" ${item.disabled ? 'disabled' : ''}>`
        }else{
I          if(grouped && item.state.groups.length == 0){
            html += '</optgroup>'
            grouped = false
          }
          html += `<option value="${item.value}" ${item.disabled ? 'disabled' : ''} ${item.selected ? 'selected' : ''}>${item.label}</option>`
        }
      })
I      if(grouped) html += '</optgroup>'
      return html
    },
    getAvailableSpace: function(){
      const location = this.$el.getBoundingClientRect()
      const top = location.y
      const bottom = window.innerHeight - (location.y + location.height)
 
      return { top: top, bottom: bottom }
    },
    calcDimensions: function(){
E      if(this.$refs.options){
        const initialDisplay = this.$refs.options.style.display
        const initialMinWidth = this.$refs.options.style.minWidth
        this.$refs.options.style.minWidth = '0'
        this.$refs.options.style.position = 'absolute'
        this.$refs.options.style.display = 'inline-block'
        this.width = this.$refs.options.offsetWidth
        this.$refs.options.style.display = initialDisplay
        this.$refs.options.style.minWidth = initialMinWidth
        this.$refs.options.style.position = ''
      }
    },
    calcPosition: function(){
      const location = this.$el.getBoundingClientRect()
      const space = this.getAvailableSpace()
 
I      if(space.bottom >= space.top){
        this.height = Math.min(space.bottom, this.size + 30) - 30
        this.top = location.top
      }else{
        this.height = Math.min(space.top, this.size + 30) - 30
        this.top = location.top - this.$refs.label.offsetHeight - this.height
      }
 
      this.left = location.left
    },
    calcDirection: debounce(function(){
      const space = this.getAvailableSpace()
      this.delta = space.bottom - space.top
    }, 200),
    getRepairedItem: function(option, depth, attrs){
      // Set a default depth of zero
E      if(!depth) depth = 0
 
      // Ensure any extra attributes is an object, even if empty
E      if(!attrs) attrs = {}
 
      // Initialize the counter that will be incremented to track
      // the index of each option or optgroup
      if(isNaN(this.counter)) this.counter = 0
 
      // Begin with a common set of state attributes
      const state = Object.assign({ groups: [] }, attrs.state || {}, { depth: depth, index: this.counter++ })
 
I      if(option.options){
        // Our "option" has it's own set of options: therefore it's actually an optgroup
 
        // Give our group an id (really just the index in the groups array)
        // and a flag indicating it's an option group
        const group = Object.assign({ label: '', disabled: false }, option, attrs, { state: Object.assign(state, { group_id: this.groups.length, group: true }) })
 
        // Add our new group the groups array
        this.groups.push(group)
 
        // Update the list of group ids this option/group belongs to, it will be passed to every child option/group
        const groupParams = { state: { groups: state.groups.concat([this.groups.length - 1]) } }
 
        // If the group itself is disabled, force all children to be disabled as well
        if(group.disabled) groupParams.disabled = true
 
        // Get an array of child "options", flattened
        // This array may also contain other option groups
        const options = group.options.reduce((options, o) => options.concat(this.getRepairedItem(o, depth + 1, groupParams)), [])
 
        // Delete the original reference to options from our input data
        delete group.options
 
        // Place the optgroup before it's children
        options.unshift(group)
 
        return options
      }else{
        // Our option is just an option, merge in some default state attributes
        // and normalize the rest of the data
        attrs.state = Object.assign(state, { highlighted: false, hovered: false })
        return Object.assign({ value: '', label: '', item: option.label || '', selected: false, disabled: false }, option, attrs)
      }
    },
    onArrowPress: function(event, offset){
      // Don't propagate (may cause things like scrolling down the page)
      event.preventDefault()
      event.stopPropagation()
 
      // If not seeking, add the class
      if(!this.$el.classList.contains('is-seeking')){
        this.$el.classList.add('is-seeking')
      }
 
      // `resetHover` uses `debounce`, so it only is called after 100ms
      // Each call to `resetHover` actually resets the clock
      this.resetHover()
 
      if(this.highlightIndex < 0){
        // Nothing is yet highlighted, so highlight the first available option
        if(this.highlightIndex < 0 && this.hoverIndex >= 0){
          // If hovering over an option, that option should be highlighted
          this.highlightIndex = this.hoverIndex
        }else{
          // Highlight the first available option
          this.highlightIndex = this.hasAvailableOptions() ? this.getAvailableOptions()[0].state.index : -1
        }
      }else{
        if(offset < 0){
          // Moving up the list
          let candidates = this.list.slice(0, this.highlightIndex).filter(o => !o.state.group && !o.disabled)
          // If any options to move to, move to the closest (last) one in the list
E          if(candidates.length) this.highlightIndex = candidates.pop().state.index
        }else{
          // Moving down the list
          let candidates = this.list.slice(this.highlightIndex + 1, this.list.length - 1).filter(o => !o.state.group && !o.disabled)
          // If any options to move to, move to the closest (first) one in the list
E          if(candidates.length) this.highlightIndex = candidates.shift().state.index
        }
      }
 
      // Consider that highlighting in this context is the same as hovering
      this.hoverIndex = this.highlightIndex
 
      if(this.open){
        // Dropdown is open, so make sure our newly highlighted option is in view
        this.$nextTick(this.scrollToHighlighted)
      }else{
        // Dropdown is closed, so we actually mean to change the selection
        this.onClickOption(this.highlightIndex)
      }
    },
    onFilter: function(event){
      const code = event.keyCode || event.which
      const char = String.fromCharCode(code)
 
I      if(/[a-z0-9-_]/i.test(char)){
        this.filter += char
 
        const match = new RegExp(`^${this.filter}`, 'i')
        const tmp = document.createElement('DIV')
 
        const result = this.list.filter(o => !o.state.group && !o.disabled).find((o) => {
          tmp.innerHTML = o.item || o.label
          let text = (tmp.textContent || tmp.innerText || o.label).replace(/^\s+/, '')
          return match.test(text)
        })
 
        if(result){
          this.onClickOption(result.state.index)
        }
      }
 
      this.resetFilter()
    },
    onHover: function(event, idx){
      this.hoverIndex = idx
    },
    onTab: function(event){
E      if(this.open && this.focused){
        event.preventDefault()
 
        this.selectImpliedOption()
        this.open = false
      }
    },
    onEnter: function(){
      this.selectImpliedOption()
      this.open = false
    },
    onEscape: function(){
      this.open = false
    },
    onToggle: function(override){
I      if(this.disabled) return
      this.open = override == undefined ? !this.open : override
    },
    onToggleFocus: function(state){
I      if(this.disabled) return
      this.focused = state
    },
    onClickOutside: function(){
      // If already closed, lose focus also
      if(!this.open) this.focused = false
      this.open = false
    },
    /**
     * Set the current selected option to the given index,
     * and highlight it as well. The second parameter can be a truthy/falsy
     * indicating whether or not to close the dropdown after selecting
     */
    onClickOption: function(idx, close){
      this.getAvailableOptions().forEach(o => o.selected = o.state.index == idx)
      this.highlightIndex = idx
      this.open = !!close
    },
    /**
     * When the native select input value changes,
     * find the index of the option from the value
     * and update the selected option in the data +list+
     */
    onSelectChanged: function(event){
      const option = this.getAvailableOptions().find(o => o.value == event.target.value)
      if(option) this.onClickOption(option.state.index)
    },
    /**
     * Implied option is first and foremost the option that
     * currently is highlighted. If no option is highlighted,
     * fall back to the currently hovered option, if any.
     * If no options with either hover or highlight state, does nothing
     */
    selectImpliedOption: function(){
      if(this.highlightIndex > -1){
        this.onClickOption(this.highlightIndex, true)
      }else if(this.hoverIndex > -1){
        this.onClickOption(this.hoverIndex, true)
      }
    },
    scrollToHighlighted: function(){
      const highlighted = this.$refs.options.querySelector('.is-highlighted')
      const options = this.$refs.scroll || this.$refs.options
 
      if(highlighted){
        const optionBottom = (highlighted.offsetTop - options.offsetHeight) + highlighted.offsetHeight + options.offsetHeight
        const scrollBottom = options.scrollTop + options.offsetHeight
 
E        if(optionBottom >= scrollBottom){
          options.scrollTop = highlighted.offsetTop - options.offsetHeight + highlighted.offsetHeight
        }else if(highlighted.offsetTop < options.scrollTop){
          options.scrollTop = highlighted.offsetTop
        }
      }
    },
    hasAvailableOptions: function(){
      return this.getAvailableOptions().length > 0
    },
    getAvailableOptions: function(){
      return this.list.filter(o => !o.state.group && !o.disabled)
    },
    isMobile: function(){
I      if(this.native instanceof Function){
        return this.native(navigator.userAgent)
      }
      return this.native && /Android|webOS|iPhone|iPad|iPod|BlackBerry|IEMobile|Opera Mini/i.test(navigator.userAgent)
    },
    resetFilter: debounce(function(){
      this.filter = ''
    }, 500),
    resetHover: debounce(function(){
      this.$el.classList.remove('is-seeking')
    }, 100)
  },
  computed: {
    classes: function(){
      return [
        { 'is-focused': this.focused },
        { 'is-disabled': this.disabled },
        { 'is-open': this.open },
        { 'is-mobile': this.isMobile() },
        { 'is-placeholding': !this.selection },
        this.direction
      ]
    },
    variables: function(){
      return {
        '--height': `${this.height}px`,
        '--width': this.width == 'auto' ? 'auto' : `${this.width}px`,
        '--top': `${this.top + (this.$refs.label ? this.$refs.label.offsetHeight : 0)}px`,
        '--left': `${this.left}px`
      }
    },
    direction: function(){
      return this.delta >= 0 ? 'is-down' : 'is-up'
    },
    selection: function(){
      return this.list.find(o => !o.state.group && !o.disabled && o.selected)
    },
    label: function(){
      if(this.highlighted){
        return this.highlighted.label
      }
      return null
    },
    highlighted: function(){
      return this.list.find(o => o.state.highlighted)
    }
  },
  data: function(){
    return {
      open: false,
      focused: false,
      width: 'auto',
      list: [],
      groups: [],
      hoverIndex: -1,
      highlightIndex: -1,
      filter: '',
      top: 0,
      left: 0,
      height: this.size,
      delta: 0
    }
  }
}
</script>
 
<style lang="scss" scoped>
.v-select {
  display: inline-block;
  min-width: 10px;
  box-sizing: border-box;
  text-align: left;
  position: relative;
  background: #fff;
  outline: none;
 
  &.is-disabled .label {
    cursor: default;
  }
 
  &.is-open .options {
    z-index: 1;
    animation: show 150ms ease-out;
    animation-fill-mode: forwards;
  }
 
  /**
   * Prevent the hover event from being triggered while seeking
   * through the dropdown using up/down arrow keys
   * This class is removed after 100ms, after the hover event would
   * have normally been triggered
   */
  &.is-seeking .v-option {
    pointer-events: none;
  }
 
  /**
   * If on a mobile browser, make the native select input
   * 0% opacity, but overlay the entire clickable area, so
   * it will be invoked instead when clicked on
   */
  &.is-mobile .select {
    opacity: 0;
    display: block;
    width: 100%;
    height: 100%;
    position: absolute;
    left: 0;
    top: 0;
  }
}
 
/**
 * @see https://ghinda.net/article/mimic-native-focus-css/
 */
.v-select.is-focused .label {
  outline-width: 2px;
  outline-style: solid;
  outline-color: Highlight;
}
 
@media (-webkit-min-device-pixel-ratio:0) {
  .v-select.is-focused .label {
    outline-color: -webkit-focus-ring-color;
    outline-style: auto;
  }
}
 
.v-select * {
  box-sizing: border-box;
}
 
.label {
  display: block;
  border: 1px solid #e5e5e5;
  padding: 6px 10px;
  width: var(--width);
  max-width: 100%;
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
  user-select: none;
  cursor: pointer;
  font-weight: normal;
  font-size: 16px;
  line-height: 1.4;
 
  /**
   * Trick to enforce the height of the element
   * when it has no content, so it doesn't collapse
   */
  &:empty::after {
    content: '.';
    visibility: hidden;
  }
}
 
.options {
  overflow: auto;
  z-index: 0;
  border: 1px solid #e5e5e5;
  max-height: var(--height);
  background: inherit;
  position: fixed;
  top: var(--top);
  left: var(--left);
  width: var(--width);
  animation: hide 150ms ease-out;
  animation-fill-mode: forwards;
}
 
.select {
  cursor: pointer;
  display: none;
}
 
@keyframes hide {
  0% {
    display: block;
    opacity: 1;
  }
  99% {
    display: block;
    transform: scale(1);
  }
  100% {
    display: none;
    transform: scale(0);
    opacity: 0;
  }
}
 
@keyframes show {
  0% {
    display: none;
    opacity: 0;
  }
  1% {
    display: block;
    opacity: 0;
  }
  100% {
    display: block;
    opacity: 1;
  }
}
</style>
 
<style lang="scss">
.v-option {
  display: flex;
  align-items: center;
  cursor: pointer;
}
</style>