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 | 1x 1x 1x 1x 8x 19x 19x 19x 19x 19x 539x 19x 19x 19x 19x 80x 80x 15x 15x 10x 10x 10x 5x 5x 470x 611x 5x 8x 8x 8x 80x 80x 80x 3132x 290x 174x 174x 5510x 2958x 138x 80x 119x 119x 119x 119x 99x 99x 99x 99x 99x 99x 99x 99x 99x 99x 109x 109x 109x 109x 109x 109x 1133x 1133x 605x 594x 594x 33x 33x 33x 33x 33x 88x 33x 33x 33x 561x 561x 5x 5x 5x 3x 5x 5x 2x 1x 1x 3x 61x 4x 24x 2x 5x 5x 4x 1x 11x 11x 11x 11x 1x 2x 2x 2x 2x 3x 3x 3x 2x 376x 8x 8x 5x 2x 3x 2x 14x 14x 14x 10x 10x 1x 1815x 80x 38x 34x 10x 10x 24x 857x 33x 13x 20x 1048x 19x | <template> <div class="v-select" :class="[{ 'is-focused': focused }, { 'is-open': open }, { 'is-mobile': isMobile() }, direction]" :style="variables" 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="onToggle($event, true)" @keydown.esc="onEscape()" @focus="focused = true" @blur="focused = false"> <div ref="label" class="label" v-html="label || placeholder" @click="onToggle()"></div> <div ref="options" class="options" style="animation-duration: 0s;"> <template v-for="opt in list"> <component v-if="opt.state.group" :is="optgroup" :group="opt"></component> <component v-else :is="option" :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 Vue from 'vue' import { debounce } from 'debounce' import VOptgroup from './select/components/optgroup.vue' import VOption from './select/components/option.vue' export default { name: 'VSelect', props: { options: { type: Array, default: () => [] }, option: { type: Object, default: () => VOption }, optgroup: { type: Object, default: () => VOptgroup }, size: { type: Number, default: 400 }, native: { type: Boolean, 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) => { this.open = false }) // 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() if(this.open && event.target != this.$refs.options) 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){ this.highlightIndex = this.selection.state.index I }else if(this.selected !== null){ const option = this.getAvailableOptions().find(o => o.value == this.selected) if(option){ option.selected = true this.highlightIndex = option.state.index } } }, mounted: function(){ this.calcDimensions() this.calcPosition() }, updated: function(){ this.calcDimensions() this.calcPosition() }, watch: { open: function(is_open){ this.$refs.options.style.animationDuration = '' if(is_open){ this.calcPosition() this.$nextTick(this.scrollToHighlighted) this.$emit('open') }else{ this.$emit('close') this.hoverIndex = -1 } }, 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) }, focused: function(is_focused){ I if(!is_focused){ this.onToggle(null, false) } }, selection: function(new_selection){ const value = new_selection ? new_selection.value : '' this.$emit('input', value) this.$emit('change', value) } }, methods: { getOptionsHtml: function(){ let html = '' let grouped = false this.list.forEach((item) => { if(item.state.group){ if(grouped) html += '</optgroup>' grouped = true html += `<optgroup label="${item.label}" ${item.disabled ? 'disabled' : ''}>` }else{ if(grouped && item.state.groups.length == 0) html += '</optgroup>' html += `<option value="${item.value}" ${item.disabled ? 'disabled' : ''} ${item.selected ? 'selected' : ''}>${item.label}</option>` } }) 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 }, getRepairedItem: function(option, depth, attrs){ // Set a default depth of zero if(!depth) depth = 0 // Ensure any extra attributes is an object, even if empty 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 = { depth: depth, index: this.counter++, groups: [] } 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 attrs.state = Object.assign(state, { group_id: this.groups.length, group: true }, attrs.state || {}) const group = Object.assign({ label: '', disabled: false }, option, attrs) // Add our new group the groups array this.groups.push(group) // const groupParams = { state: { groups: Array.apply(null, { length: this.groups.length }).map(Number.call, Number) } } // If the group itself is disabled, force all children to be disabled as well I 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 }, attrs.state || {}) 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.selectImpliedOption() this.open = false }, onToggle: function(event, override){ if(event) event.preventDefault() this.open = override == undefined ? !this.open : override }, /** * 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 }, 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 has a hover state flag. If no option is hovered, * fall back to the currently highlighted option, if any. * If no options with either hover or highlight state, does nothing */ selectImpliedOption: function(){ if(this.hoverIndex > -1){ this.onClickOption(this.hoverIndex, true) }else if(this.highlightIndex > -1){ this.onClickOption(this.highlightIndex, true) } }, scrollToHighlighted: function(){ const highlighted = this.$refs.options.querySelector('.is-highlighted') const options = this.$refs.options if(highlighted){ I if((highlighted.offsetTop + highlighted.offsetHeight) - options.scrollTop > options.clientHeight){ options.scrollTop = (highlighted.offsetTop + highlighted.offsetHeight) - options.clientHeight I }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(){ return /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: { 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(){ if(this.open){ let space = this.getAvailableSpace() return space.bottom >= space.top ? 'is-down' : 'is-up' } return '' }, 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 } } } </script> <style lang="scss" scoped> .v-select { display: inline-block; min-width: 10px; max-width: 100%; box-sizing: border-box; text-align: left; position: relative; background: #fff; outline: none; &.is-open .options { 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); user-select: none; cursor: pointer; font-weight: normal; font-size: 16px; } .options { overflow: auto; 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; //margin-top: 10px; //min-width: 500px; //margin-left: calc(-250px + var(--width) / 2); } .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> |