2
0
mirror of https://github.com/tenrok/vue-select.git synced 2026-05-17 02:29:37 +03:00

refactor: apply eslint fixes (#1469)

This commit is contained in:
Jeff Sagal
2021-08-01 12:30:50 -07:00
committed by GitHub
parent a64ffc32d0
commit dd281aa8c6
85 changed files with 3616 additions and 3208 deletions
+14 -17
View File
@@ -1,17 +1,14 @@
const path = require('path');
const webpack = require('webpack');
const VueLoaderPlugin = require('vue-loader').VueLoaderPlugin;
const MiniCssExtractPlugin = require('mini-css-extract-plugin');
const path = require('path')
const webpack = require('webpack')
const VueLoaderPlugin = require('vue-loader').VueLoaderPlugin
const MiniCssExtractPlugin = require('mini-css-extract-plugin')
const env = process.env.NODE_ENV === 'production'
? 'production'
: 'development';
const env = process.env.NODE_ENV === 'production' ? 'production' : 'development'
const devtool = env === 'production' ? 'source-map' : 'eval-source-map';
const devtool = env === 'production' ? 'source-map' : 'eval-source-map'
const extractOrInjectStyles = env !== 'production'
? 'vue-style-loader'
: MiniCssExtractPlugin.loader;
const extractOrInjectStyles =
env !== 'production' ? 'vue-style-loader' : MiniCssExtractPlugin.loader
module.exports = {
mode: env,
@@ -24,11 +21,11 @@ module.exports = {
resolve: {
extensions: ['.js', '.vue'],
alias: {
'src': path.resolve(__dirname, '../src'),
'assets': path.resolve(__dirname, '../docs/assets'),
'mixins': path.resolve(__dirname, '../src/mixins'),
'components': path.resolve(__dirname, '../src/components'),
'vue$': 'vue/dist/vue.esm.js',
src: path.resolve(__dirname, '../src'),
assets: path.resolve(__dirname, '../docs/assets'),
mixins: path.resolve(__dirname, '../src/mixins'),
components: path.resolve(__dirname, '../src/components'),
vue$: 'vue/dist/vue.esm.js',
},
},
module: {
@@ -67,4 +64,4 @@ module.exports = {
children: false,
modules: false,
},
};
}
+9 -11
View File
@@ -1,7 +1,7 @@
const merge = require('webpack-merge');
const chokidar = require('chokidar');
const HtmlWebpackPlugin = require('html-webpack-plugin');
const baseWebpackConfig = require('./webpack.base.conf');
const merge = require('webpack-merge')
const chokidar = require('chokidar')
const HtmlWebpackPlugin = require('html-webpack-plugin')
const baseWebpackConfig = require('./webpack.base.conf')
/**
*
@@ -28,12 +28,10 @@ module.exports = merge(baseWebpackConfig, {
chunks: false,
},
port: 8080,
before (app, server) {
chokidar.watch([
'./**/*.html',
]).on('all', function () {
server.sockWrite(server.sockets, 'content-changed');
});
before(app, server) {
chokidar.watch(['./**/*.html']).on('all', function () {
server.sockWrite(server.sockets, 'content-changed')
})
},
},
});
})
+6 -6
View File
@@ -1,6 +1,6 @@
const TerserPlugin = require('terser-webpack-plugin');
const merge = require('webpack-merge');
const baseWebpackConfig = require('./webpack.base.conf');
const TerserPlugin = require('terser-webpack-plugin')
const merge = require('webpack-merge')
const baseWebpackConfig = require('./webpack.base.conf')
module.exports = merge(baseWebpackConfig, {
entry: './src/index.js',
@@ -8,7 +8,7 @@ module.exports = merge(baseWebpackConfig, {
filename: 'vue-select.js',
library: 'VueSelect',
libraryTarget: 'umd',
globalObject: 'typeof self !== \'undefined\' ? self : this',
globalObject: "typeof self !== 'undefined' ? self : this",
},
optimization: {
minimizer: [
@@ -16,5 +16,5 @@ module.exports = merge(baseWebpackConfig, {
sourceMap: true,
}),
],
}
});
},
})
+7 -7
View File
@@ -5,19 +5,19 @@
</template>
<script>
import vSelect from "../src/components/Select";
import countries from "../docs/.vuepress/data/countryCodes";
import books from "../docs/.vuepress/data/books";
import vSelect from '../src/components/Select'
import countries from '../docs/.vuepress/data/countryCodes'
import books from '../docs/.vuepress/data/books'
export default {
components: { vSelect },
data: () => ({
selected: null,
config: {
options: countries
}
})
};
options: countries,
},
}),
}
</script>
<style>
+5 -5
View File
@@ -1,8 +1,8 @@
import Vue from "vue";
import Dev from "./Dev.vue";
import Vue from 'vue'
import Dev from './Dev.vue'
Vue.config.productionTip = false;
Vue.config.productionTip = false
new Vue({
render: h => h(Dev)
}).$mount("#app");
render: (h) => h(Dev),
}).$mount('#app')
@@ -2,9 +2,10 @@
<v-select>
<template v-slot:no-options="{ search, searching }">
<template v-if="searching">
No results found for <em>{{ search }}</em>.
No results found for <em>{{ search }}</em
>.
</template>
<em style="opacity: 0.5;" v-else>Start typing to search for a country.</em>
<em v-else style="opacity: 0.5">Start typing to search for a country.</em>
</template>
</v-select>
</template>
@@ -12,5 +13,5 @@
<script>
export default {
name: 'BetterNoOptions',
};
}
</script>
@@ -1,10 +1,10 @@
<template>
<div>
<v-select
placeholder="choose a country"
v-model="selected"
:components="{Deselect}"
:options="['Canada', 'United States']"
v-model="selected"
placeholder="choose a country"
:components="{ Deselect }"
:options="['Canada', 'United States']"
/>
</div>
</template>
@@ -14,8 +14,8 @@ export default {
data: () => ({
selected: 'Canada',
Deselect: {
render: createElement => createElement('span', '❌'),
render: (createElement) => createElement('span', '❌'),
},
}),
};
}
</script>
+15 -13
View File
@@ -1,15 +1,16 @@
<template>
<p :data-height="height"
data-theme-id="32252"
:data-slug-hash="url"
data-default-tab="result"
data-user="sagalbot"
class="codepen">
</p>
<p
:data-height="height"
data-theme-id="32252"
:data-slug-hash="url"
data-default-tab="result"
data-user="sagalbot"
class="codepen"
></p>
</template>
<script>
import mountCodePen from '../utils/codePen';
import mountCodePen from '../utils/codePen'
export default {
props: {
@@ -18,11 +19,12 @@ export default {
required: true,
},
height: {
default: 250
}
type: [String, Number],
default: 250,
},
},
mounted () {
mountCodePen();
mounted() {
mountCodePen()
},
};
}
</script>
+10 -9
View File
@@ -1,14 +1,15 @@
<template>
<ul>
<li v-for="{ login, avatar_url, html_url, contributions } in contributors">
<li
v-for="{ login, avatar_url, html_url, contributions } in contributors"
:key="login"
>
<img :src="`${avatar_url}&s=75`" :alt="`${login}'s Avatar`" />
<div>
<a :href="html_url">@{{ login }}</a>
<br /><a
class="contributions-link"
:href="
`https://github.com/sagalbot/vue-select/commits?author=${login}`
"
:href="`https://github.com/sagalbot/vue-select/commits?author=${login}`"
>{{ contributions }} contributions</a
>
</div>
@@ -17,15 +18,15 @@
</template>
<script>
import { CONTRIBUTORS } from "@dynamic/constants";
import { CONTRIBUTORS } from '@dynamic/constants'
export default {
data: () => ({
contributors: CONTRIBUTORS.filter(
({ login }) => login !== "semantic-release-bot"
)
})
};
({ login }) => login !== 'semantic-release-bot'
),
}),
}
</script>
<style scoped>
+3 -5
View File
@@ -3,16 +3,14 @@
</template>
<script>
import countryCodes from '../data/countryCodes';
import countryCodes from '../data/countryCodes'
export default {
name: 'CountrySelect',
data: () => ({
options: countryCodes,
}),
};
}
</script>
<style scoped>
</style>
<style scoped></style>
+13 -13
View File
@@ -9,18 +9,18 @@
</template>
<style>
.style-chooser .vs__search::placeholder,
.style-chooser .vs__dropdown-toggle,
.style-chooser .vs__dropdown-menu {
background: #dfe5fb;
border: none;
color: #394066;
text-transform: lowercase;
font-variant: small-caps;
}
.style-chooser .vs__search::placeholder,
.style-chooser .vs__dropdown-toggle,
.style-chooser .vs__dropdown-menu {
background: #dfe5fb;
border: none;
color: #394066;
text-transform: lowercase;
font-variant: small-caps;
}
.style-chooser .vs__clear,
.style-chooser .vs__open-indicator {
fill: #394066;
}
.style-chooser .vs__clear,
.style-chooser .vs__open-indicator {
fill: #394066;
}
</style>
@@ -1,7 +1,7 @@
<template>
<v-select
:options="['Vue.js', 'React', 'Angular']"
:components="{Deselect, OpenIndicator}"
:options="['Vue.js', 'React', 'Angular']"
:components="{ Deselect, OpenIndicator }"
/>
</template>
@@ -9,11 +9,11 @@
export default {
data: () => ({
Deselect: {
render: createElement => createElement('span', '❌'),
render: (createElement) => createElement('span', '❌'),
},
OpenIndicator: {
render: createElement => createElement('span', '🔽'),
render: (createElement) => createElement('span', '🔽'),
},
}),
};
}
</script>
+11 -10
View File
@@ -1,10 +1,10 @@
<template>
<v-select
taggable
multiple
no-drop
:map-keydown="handlers"
placeholder="enter an email"
taggable
multiple
no-drop
:map-keydown="handlers"
placeholder="enter an email"
/>
</template>
@@ -13,13 +13,14 @@ export default {
name: 'CustomHandlers',
methods: {
handlers: (map, vm) => ({
...map, 50: e => {
e.preventDefault();
if( e.key === '@' && vm.search.length > 0 ) {
vm.search = `${vm.search}@gmail.com`;
...map,
50: (e) => {
e.preventDefault()
if (e.key === '@' && vm.search.length > 0) {
vm.search = `${vm.search}@gmail.com`
}
},
}),
},
};
}
</script>
+15 -11
View File
@@ -1,5 +1,9 @@
<template>
<v-select :filter="fuseSearch" :options="books" :getOptionLabel="option => option.title">
<v-select
:filter="fuseSearch"
:options="books"
:get-option-label="(option) => option.title"
>
<template #option="{ author, title }">
{{ title }}
<br />
@@ -9,23 +13,23 @@
</template>
<script>
import Fuse from "fuse.js";
import books from "../data/books";
import Fuse from 'fuse.js'
import books from '../data/books'
export default {
computed: {
books: () => books
books: () => books,
},
methods: {
fuseSearch(options, search) {
const fuse = new Fuse(options, {
keys: ["title", "author.firstName", "author.lastName"],
shouldSort: true
});
keys: ['title', 'author.firstName', 'author.lastName'],
shouldSort: true,
})
return search.length
? fuse.search(search).map(({ item }) => item)
: fuse.list;
}
}
};
: fuse.list
},
},
}
</script>
+34 -34
View File
@@ -4,10 +4,10 @@
:filterable="false"
@open="onOpen"
@close="onClose"
@search="query => search = query"
@search="(query) => (search = query)"
>
<template #list-footer>
<li ref="load" class="loader" v-show="hasNextPage">
<li v-show="hasNextPage" ref="load" class="loader">
Loading more options...
</li>
</template>
@@ -15,60 +15,60 @@
</template>
<script>
import countries from '../data/countries';
import countries from '../data/countries'
export default {
name: "InfiniteScroll",
name: 'InfiniteScroll',
data: () => ({
observer: null,
limit: 10,
search: ''
search: '',
}),
mounted () {
computed: {
filtered() {
return countries.filter((country) => country.includes(this.search))
},
paginated() {
return this.filtered.slice(0, this.limit)
},
hasNextPage() {
return this.paginated.length < this.filtered.length
},
},
mounted() {
/**
* You could do this directly in data(), but since these docs
* are server side rendered, IntersectionObserver doesn't exist
* in that environment, so we need to do it in mounted() instead.
*/
this.observer = new IntersectionObserver(this.infiniteScroll);
},
computed: {
filtered () {
return countries.filter(country => country.includes(this.search));
},
paginated () {
return this.filtered.slice(0, this.limit);
},
hasNextPage () {
return this.paginated.length < this.filtered.length;
},
this.observer = new IntersectionObserver(this.infiniteScroll)
},
methods: {
async onOpen () {
async onOpen() {
if (this.hasNextPage) {
await this.$nextTick();
await this.$nextTick()
this.observer.observe(this.$refs.load)
}
},
onClose () {
this.observer.disconnect();
onClose() {
this.observer.disconnect()
},
async infiniteScroll ([{isIntersecting, target}]) {
async infiniteScroll([{ isIntersecting, target }]) {
if (isIntersecting) {
const ul = target.offsetParent;
const scrollTop = target.offsetParent.scrollTop;
this.limit += 10;
await this.$nextTick();
ul.scrollTop = scrollTop;
const ul = target.offsetParent
const scrollTop = target.offsetParent.scrollTop
this.limit += 10
await this.$nextTick()
ul.scrollTop = scrollTop
}
}
}
},
},
}
</script>
<style scoped>
.loader {
text-align: center;
color: #bbbbbb;
}
.loader {
text-align: center;
color: #bbbbbb;
}
</style>
@@ -1,21 +1,21 @@
<template>
<v-select
v-model="selected"
multiple
placeholder="Choose up to 3 books!"
label="title"
v-model="selected"
:options="books"
:selectable="() => selected.length < 3"
/>
</template>
<script>
import books from '../data/books';
import books from '../data/books'
export default {
data() {
return { selected: [] }
},
computed: {
books: () => books,
}
},
}
</script>
+17 -14
View File
@@ -4,13 +4,13 @@
<th>Name</th>
<th>Country</th>
</tr>
<tr v-for="person in people">
<tr v-for="person in people" :key="person.name">
<td>{{ person.name }}</td>
<td>
<v-select
:options="options"
:value="person.country"
@input="country => updateCountry(person, country)"
@input="(country) => updateCountry(person, country)"
/>
</td>
</tr>
@@ -18,26 +18,29 @@
</template>
<script>
import countries from '../data/countries';
import countries from '../data/countries'
export default {
data: () => ({
people: [{name: 'John', country: ''}, {name: 'Jane', country: ''}],
people: [
{ name: 'John', country: '' },
{ name: 'Jane', country: '' },
],
}),
methods: {
updateCountry (person, country) {
person.country = country;
},
},
computed: {
options: () => countries,
},
};
methods: {
updateCountry(person, country) {
person.country = country
},
},
}
</script>
<style scoped>
table {
display: table;
width: 100%;
}
table {
display: table;
width: 100%;
}
</style>
@@ -1,10 +1,10 @@
<template>
<div>
<v-select
multiple
v-model="selected"
:options="['Canada', 'United States']"
:components="{Deselect}"
v-model="selected"
multiple
:options="['Canada', 'United States']"
:components="{ Deselect }"
/>
</div>
</template>
@@ -14,8 +14,8 @@ export default {
data: () => ({
selected: ['Canada'],
Deselect: {
render: createElement => createElement('span', '❌'),
render: (createElement) => createElement('span', '❌'),
},
}),
};
}
</script>
@@ -1,8 +1,8 @@
<template>
<div>
<v-select
:options="['Canada', 'United States']"
:components="{OpenIndicator}"
:options="['Canada', 'United States']"
:components="{ OpenIndicator }"
/>
</div>
</template>
@@ -11,8 +11,8 @@
export default {
data: () => ({
OpenIndicator: {
render: createElement => createElement('span', '🔽'),
render: (createElement) => createElement('span', '🔽'),
},
}),
};
}
</script>
+34 -26
View File
@@ -1,14 +1,18 @@
<template>
<v-select :options="paginated" @search="query => search = query" :filterable="false">
<v-select
:options="paginated"
:filterable="false"
@search="(query) => (search = query)"
>
<li slot="list-footer" class="pagination">
<button @click="offset -= 10" :disabled="!hasPrevPage">Prev</button>
<button @click="offset += 10" :disabled="!hasNextPage">Next</button>
<button :disabled="!hasPrevPage" @click="offset -= 10">Prev</button>
<button :disabled="!hasNextPage" @click="offset += 10">Next</button>
</li>
</v-select>
</template>
<script>
import countries from '../data/countries';
import countries from '../data/countries'
export default {
data: () => ({
countries,
@@ -17,33 +21,37 @@ export default {
limit: 10,
}),
computed: {
filtered () {
return this.countries.filter(country => country.includes(this.search));
filtered() {
return this.countries.filter((country) => country.includes(this.search))
},
paginated () {
return this.filtered.slice(this.offset, this.limit + this.offset);
paginated() {
return this.filtered.slice(this.offset, this.limit + this.offset)
},
hasNextPage () {
const nextOffset = this.offset + 10;
return Boolean(this.filtered.slice(nextOffset, this.limit + nextOffset).length);
hasNextPage() {
const nextOffset = this.offset + 10
return Boolean(
this.filtered.slice(nextOffset, this.limit + nextOffset).length
)
},
hasPrevPage() {
const prevOffset = this.offset - 10
return Boolean(
this.filtered.slice(prevOffset, this.limit + prevOffset).length
)
},
hasPrevPage () {
const prevOffset = this.offset - 10;
return Boolean(this.filtered.slice(prevOffset, this.limit + prevOffset).length);
}
},
};
}
</script>
<style scoped>
.pagination {
display: flex;
margin: .25rem .25rem 0;
}
.pagination button {
flex-grow: 1;
}
.pagination button:hover {
cursor: pointer;
}
.pagination {
display: flex;
margin: 0.25rem 0.25rem 0;
}
.pagination button {
flex-grow: 1;
}
.pagination button:hover {
cursor: pointer;
}
</style>
@@ -1,15 +1,19 @@
<template>
<div>
<v-select :options="countries" append-to-body :calculate-position="withPopper" />
<v-select
:options="countries"
append-to-body
:calculate-position="withPopper"
/>
<label for="position" style="display: block; margin: 1rem 0;">
<label for="position" style="display: block; margin: 1rem 0">
<input
type="checkbox"
id="position"
v-model="placement"
type="checkbox"
true-value="top"
false-value="bottom"
>
/>
Position dropdown above
</label>
</div>
@@ -17,17 +21,17 @@
<script>
import countries from '../data/countries'
import { createPopper } from '@popperjs/core';
import { createPopper } from '@popperjs/core'
export default {
data: () => ({countries, placement: 'top'}),
data: () => ({ countries, placement: 'top' }),
methods: {
withPopper (dropdownList, component, {width}) {
withPopper(dropdownList, component, { width }) {
/**
* We need to explicitly define the dropdown width since
* it is usually inherited from the parent with CSS.
*/
dropdownList.style.width = width;
dropdownList.style.width = width
/**
* Here we position the dropdownList relative to the $refs.toggle Element.
@@ -43,41 +47,46 @@ export default {
placement: this.placement,
modifiers: [
{
name: 'offset', options: {
offset: [0, -1]
}
name: 'offset',
options: {
offset: [0, -1],
},
},
{
name: 'toggleClass',
enabled: true,
phase: 'write',
fn ({state}) {
component.$el.classList.toggle('drop-up', state.placement === 'top')
fn({ state }) {
component.$el.classList.toggle(
'drop-up',
state.placement === 'top'
)
},
}]
});
},
],
})
/**
* To prevent memory leaks Popper needs to be destroyed.
* If you return function, it will be called just before dropdown is removed from DOM.
*/
return () => popper.destroy();
}
}
};
return () => popper.destroy()
},
},
}
</script>
<style>
.v-select.drop-up.vs--open .vs__dropdown-toggle {
border-radius: 0 0 4px 4px;
border-top-color: transparent;
border-bottom-color: rgba(60, 60, 60, 0.26);
}
.v-select.drop-up.vs--open .vs__dropdown-toggle {
border-radius: 0 0 4px 4px;
border-top-color: transparent;
border-bottom-color: rgba(60, 60, 60, 0.26);
}
[data-popper-placement='top'] {
border-radius: 4px 4px 0 0;
border-top-style: solid;
border-bottom-style: none;
box-shadow: 0 -3px 6px rgba(0, 0, 0, 0.15)
}
[data-popper-placement='top'] {
border-radius: 4px 4px 0 0;
border-top-style: solid;
border-bottom-style: none;
box-shadow: 0 -3px 6px rgba(0, 0, 0, 0.15);
}
</style>
@@ -2,10 +2,10 @@
<div class="flex">
<div>
<v-select
label="country"
v-model="selected"
:reduce="opt => opt.meta.id"
:options="options"
v-model="selected"
label="country"
:reduce="(opt) => opt.meta.id"
:options="options"
/>
</div>
<div>
@@ -26,35 +26,36 @@ export default {
id: '1',
code: 'ca',
},
}],
},
],
}),
};
}
</script>
<style scoped>
.flex {
margin-bottom: 2rem;
border: 1px solid #eaecef;
/*padding: 1rem;*/
display: flex;
justify-content: center;
align-items: center;
}
.flex {
margin-bottom: 2rem;
border: 1px solid #eaecef;
/*padding: 1rem;*/
display: flex;
justify-content: center;
align-items: center;
}
.flex > div {
flex-grow: 1;
width: 50%;
padding: 0 1rem;
}
.flex > div {
flex-grow: 1;
width: 50%;
padding: 0 1rem;
}
pre {
margin: 0;
background: #fff;
}
pre {
margin: 0;
background: #fff;
}
code {
color: #635762 !important;
color: #5b2d2d !important;
/*color: #7ec699 !important;*/
}
code {
color: #635762 !important;
color: #5b2d2d !important;
/*color: #7ec699 !important;*/
}
</style>
+205 -106
View File
@@ -1,49 +1,85 @@
<template>
<div id="sandbox-wrap">
<div id="config">
<div class="list-item" v-if="!hideHelp">
<p>Use the controls below to adjust the props used
by the vue-select components.</p>
<p>The API provides
more props than are shown here, these are some
commonly adjusted settings.</p>
<div v-if="!hideHelp" class="list-item">
<p>
Use the controls below to adjust the props used by the vue-select
components.
</p>
<p>
The API provides more props than are shown here, these are some
commonly adjusted settings.
</p>
</div>
<h5 class="list-item">Basic Features</h5>
<div class="list-item">
<label for="multiple">
<input id="multiple" type="checkbox" v-model="configuration.multiple">
<code>:multiple="{{ configuration.multiple ? 'true' : 'false' }}"</code>
<input
id="multiple"
v-model="configuration.multiple"
type="checkbox"
/>
<code
>:multiple="{{ configuration.multiple ? 'true' : 'false' }}"</code
>
</label>
</div>
<div class="list-item">
<label for="disabled">
<input id="disabled" type="checkbox" v-model="configuration.disabled">
<code>:disabled="{{ configuration.disabled ? 'true' : 'false' }}"</code>
<input
id="disabled"
v-model="configuration.disabled"
type="checkbox"
/>
<code
>:disabled="{{ configuration.disabled ? 'true' : 'false' }}"</code
>
</label>
</div>
<div class="list-item">
<label for="clearable">
<input id="clearable" type="checkbox" v-model="configuration.clearable">
<code>:clearable="{{ configuration.clearable ? 'true' : 'false' }}"</code>
<input
id="clearable"
v-model="configuration.clearable"
type="checkbox"
/>
<code
>:clearable="{{ configuration.clearable ? 'true' : 'false' }}"</code
>
</label>
</div>
<div class="list-item">
<label for="searchable">
<input id="searchable" type="checkbox" v-model="configuration.searchable">
<code>:searchable="{{ configuration.searchable ? 'true' : 'false' }}"</code>
<input
id="searchable"
v-model="configuration.searchable"
type="checkbox"
/>
<code
>:searchable="{{
configuration.searchable ? 'true' : 'false'
}}"</code
>
</label>
</div>
<div class="list-item">
<label for="filterable">
<input id="filterable" type="checkbox" v-model="configuration.filterable">
<code>:filterable="{{ configuration.searchable ? 'true' : 'false' }}"</code>
<input
id="filterable"
v-model="configuration.filterable"
type="checkbox"
/>
<code
>:filterable="{{
configuration.searchable ? 'true' : 'false'
}}"</code
>
</label>
</div>
@@ -51,22 +87,34 @@
<div class="list-item">
<label for="taggable">
<input id="taggable" type="checkbox" v-model="configuration.taggable">
<code>:taggable="{{ configuration.taggable ? 'true' : 'false' }}"</code>
<input
id="taggable"
v-model="configuration.taggable"
type="checkbox"
/>
<code
>:taggable="{{ configuration.taggable ? 'true' : 'false' }}"</code
>
</label>
</div>
<div class="list-item">
<label for="noDrop">
<input id="noDrop" type="checkbox" v-model="configuration.noDrop">
<input id="noDrop" v-model="configuration.noDrop" type="checkbox" />
<code>:no-drop="{{ configuration.noDrop ? 'true' : 'false' }}"</code>
</label>
</div>
<div class="list-item">
<label for="pushTags">
<input id="pushTags" type="checkbox" v-model="configuration.pushTags">
<code>:push-tags="{{ configuration.pushTags ? 'true' : 'false' }}"</code>
<input
id="pushTags"
v-model="configuration.pushTags"
type="checkbox"
/>
<code
>:push-tags="{{ configuration.pushTags ? 'true' : 'false' }}"</code
>
</label>
</div>
@@ -74,15 +122,31 @@
<div class="list-item">
<label for="selectOnTab">
<input id="selectOnTab" type="checkbox" v-model="configuration.selectOnTab">
<code>:select-on-tab="{{ configuration.selectOnTab ? 'true' : 'false' }}"</code>
<input
id="selectOnTab"
v-model="configuration.selectOnTab"
type="checkbox"
/>
<code
>:select-on-tab="{{
configuration.selectOnTab ? 'true' : 'false'
}}"</code
>
</label>
</div>
<div class="list-item">
<label for="closeOnSelect">
<input id="closeOnSelect" type="checkbox" v-model="configuration.closeOnSelect">
<code>:close-on-select="{{ configuration.closeOnSelect ? 'true' : 'false' }}"</code>
<input
id="closeOnSelect"
v-model="configuration.closeOnSelect"
type="checkbox"
/>
<code
>:close-on-select="{{
configuration.closeOnSelect ? 'true' : 'false'
}}"</code
>
</label>
</div>
@@ -90,11 +154,21 @@
<div class="list-item">
<label for="rtl">
<input id="rtl" type="radio" v-model="configuration.dir" value="rtl">
<input
id="rtl"
v-model="configuration.dir"
type="radio"
value="rtl"
/>
<code>dir="rtl"</code>
</label>
<label for="ltr">
<input id="ltr" type="radio" v-model="configuration.dir" value="ltr">
<input
id="ltr"
v-model="configuration.dir"
type="radio"
value="ltr"
/>
<code>dir="ltr"</code>
</label>
</div>
@@ -103,22 +177,32 @@
<div id="sandbox">
<slot v-bind="configuration">
<div class="example">
<v-select v-bind="configuration" placeholder="country objects"></v-select>
<v-select
v-bind="configuration"
placeholder="country objects"
></v-select>
</div>
<div class="example">
<v-select v-bind="configuration" placeholder="country objects, using option scoped slots">
<template slot="selected-option" slot-scope="{ label, value }">
{{ label }} -- {{ value }}
<v-select
v-bind="configuration"
placeholder="country objects, using option scoped slots"
>
<template slot="selected-option" slot-scope="option">
{{ option.label }} -- {{ option.value }}
</template>
<template slot="option" slot-scope="{ label, value }">
{{ label }} ({{ value }})
<template slot="option" slot-scope="option">
{{ option.label }} ({{ option.value }})
</template>
</v-select>
</div>
<div class="example">
<v-select v-bind="configuration" :options="['cat', 'dog', 'bear']" placeholder="string options, option slots">
<v-select
v-bind="configuration"
:options="['cat', 'dog', 'bear']"
placeholder="string options, option slots"
>
<template slot="selected-option" slot-scope="{ label }">
{{ label }}
</template>
@@ -129,32 +213,48 @@
</div>
<div class="example">
<v-select v-bind="configuration" :options="[1,5,10]" placeholder="options=[1,5,10]"></v-select>
<v-select
v-bind="configuration"
:options="[1, 5, 10]"
placeholder="options=[1,5,10]"
></v-select>
</div>
<div class="example">
<v-select v-bind="configuration" label="title" :options="optionDataSets.books" :filter="fuseSearch"
placeholder="advanced filtering w/ fuse.js + scoped slots">
<v-select
v-bind="configuration"
label="title"
:options="optionDataSets.books"
:filter="fuseSearch"
placeholder="advanced filtering w/ fuse.js + scoped slots"
>
<template slot="option" slot-scope="option">
<strong>{{ option.title }}</strong><br>
<em>{{ `${option.author.firstName} ${option.author.lastName}` }}</em>
<strong>{{ option.title }}</strong
><br />
<em>{{
`${option.author.firstName} ${option.author.lastName}`
}}</em>
</template>
</v-select>
</div>
<div class="example">
<v-select
v-bind="configuration"
placeholder="search github repositories.."
label="full_name"
@search="search"
:options="ajaxRes"
v-bind="configuration"
placeholder="search github repositories.."
label="full_name"
:options="ajaxRes"
@search="search"
>
</v-select>
</div>
<div class="example">
<v-select v-bind="configuration" :options="[]" placeholder="options=[]"></v-select>
<v-select
v-bind="configuration"
:options="[]"
placeholder="options=[]"
></v-select>
</div>
</slot>
</div>
@@ -162,11 +262,11 @@
</template>
<script>
import Fuse from 'fuse.js';
import debounce from 'lodash/debounce';
import vSelect from '../../../src/components/Select.vue';
import countries from '../data/countryCodes';
import books from '../data/books';
import Fuse from 'fuse.js'
import debounce from 'lodash/debounce'
import vSelect from '../../../src/components/Select.vue'
import countries from '../data/countryCodes'
import books from '../data/books'
const defaultConfig = () => ({
options: countries,
@@ -180,17 +280,17 @@ const defaultConfig = () => ({
disabled: false,
selectOntab: false,
placeholder: 'Select a Country...',
});
})
export default {
components: { vSelect },
props: {
hideHelp: {
type: Boolean,
default: false,
},
},
components: {vSelect},
data () {
data() {
return {
configuration: defaultConfig(),
value: null,
@@ -201,76 +301,75 @@ export default {
countries,
books,
},
};
}
},
methods: {
search (search, loading) {
loading(true);
this.getRepositories(search, loading, this);
search(search, loading) {
loading(true)
this.getRepositories(search, loading, this)
},
searchPeople (search, loading) {
loading(true);
this.getPeople(loading, this);
searchPeople(search, loading) {
loading(true)
this.getPeople(loading, this)
},
getPeople: debounce((loading, vm) => {
vm.$http.get(`https://reqres.in/api/users?per_page=10`).then(res => {
vm.people = res.data.data;
loading(false);
});
vm.$http.get(`https://reqres.in/api/users?per_page=10`).then((res) => {
vm.people = res.data.data
loading(false)
})
}, 250),
getRepositories: debounce((search, loading, vm) => {
vm.$http
.get(`https://api.github.com/search/repositories?q=${search}`)
.then(res => {
vm.ajaxRes = res.data.items;
loading(false);
});
.then((res) => {
vm.ajaxRes = res.data.items
loading(false)
})
}, 250),
},
};
}
</script>
<style scoped>
#sandbox-wrap {
min-height: 100%;
display: grid;
grid-template-columns: auto 75%;
grid-template-rows: auto;
grid-template-areas:
"sidebar component"
}
#sandbox-wrap {
min-height: 100%;
display: grid;
grid-template-columns: auto 75%;
grid-template-rows: auto;
grid-template-areas: 'sidebar component';
}
#config {
grid-area: sidebar;
border-right: 1px solid #eaecef;
display: flex;
flex-direction: column;
justify-content: center;
}
#config {
grid-area: sidebar;
border-right: 1px solid #eaecef;
display: flex;
flex-direction: column;
justify-content: center;
}
#sandbox {
grid-area: component;
display: flex;
flex-direction: column;
justify-content: center;
align-items: center;
}
#sandbox {
grid-area: component;
display: flex;
flex-direction: column;
justify-content: center;
align-items: center;
}
.list-item {
margin-top: 0;
margin-bottom: 1rem;
padding: 1rem 1rem 0;
}
.list-item {
margin-top: 0;
margin-bottom: 1rem;
padding: 1rem 1rem 0;
}
.list-item:not(:first-child) {
border-top: 1px solid #eaecef;
}
.list-item:not(:first-child) {
border-top: 1px solid #eaecef;
}
.example {
margin-bottom: 2rem;
}
.example {
margin-bottom: 2rem;
}
.v-select {
width: 25em;
}
.v-select {
width: 25em;
}
</style>
+3 -1
View File
@@ -1,7 +1,9 @@
<template>
<v-select append-to-body>
<template #footer>
<div style="opacity: .8">Bottom of the component, in the footer slot!</div>
<div style="opacity: 0.8">
Bottom of the component, in the footer slot!
</div>
</template>
</v-select>
</template>
+1 -1
View File
@@ -1,7 +1,7 @@
<template>
<v-select>
<template #header>
<div style="opacity: .8">Top of the component, in the header slot!</div>
<div style="opacity: 0.8">Top of the component, in the header slot!</div>
</template>
</v-select>
</template>
@@ -1,5 +1,6 @@
<template>
<v-select>
<!-- eslint-disable-next-line vue/no-unused-vars -->
<template #no-options="{ search, searching, loading }">
This is the no options slot.
</template>
+6 -6
View File
@@ -14,11 +14,11 @@ export default {
{
title: "Old Man's War",
author: {
firstName: "John",
lastName: "Scalzi"
}
}
]
})
firstName: 'John',
lastName: 'Scalzi',
},
},
],
}),
}
</script>
+1 -1
View File
@@ -6,7 +6,7 @@
class="vs__search"
v-bind="attributes"
v-on="events"
>
/>
</template>
</v-select>
</template>
@@ -1,9 +1,11 @@
<template>
<v-select v-model="selected" :options="books" label="title">
<template #selected-option="{ title, author }">
<div style="display: flex; align-items: baseline;">
<strong>{{ title }}</strong>
<em style="margin-left: .5rem;">by {{ author.firstName }} {{ author.lastName }}</em>
<div style="display: flex; align-items: baseline">
<strong>{{ title }}</strong>
<em style="margin-left: 0.5rem"
>by {{ author.firstName }} {{ author.lastName }}</em
>
</div>
</template>
</v-select>
@@ -13,14 +15,14 @@
const book = {
title: "Old Man's War",
author: {
firstName: "John",
lastName: "Scalzi"
}
};
firstName: 'John',
lastName: 'Scalzi',
},
}
export default {
data: () => ({
books: [book],
selected: book
})
selected: book,
}),
}
</script>
@@ -1,6 +1,9 @@
<template>
<!-- eslint-disable vue/no-unused-vars -->
<v-select :options="books" label="title">
<template #selected-option-container="{ option, deselect, multiple, disabled }">
<template
#selected-option-container="{ option, deselect, multiple, disabled }"
>
<div class="vs__selected">{{ option.title }}</div>
</template>
</v-select>
@@ -13,11 +16,11 @@ export default {
{
title: "Old Man's War",
author: {
firstName: "John",
lastName: "Scalzi"
}
}
]
})
firstName: 'John',
lastName: 'Scalzi',
},
},
],
}),
}
</script>
+5 -1
View File
@@ -1,7 +1,11 @@
<template>
<v-select :loading="true">
<template #spinner="{ loading }">
<div v-if="loading" style="border-left-color: rgba(88,151,251,0.71)" class="vs__spinner">
<div
v-if="loading"
style="border-left-color: rgba(88, 151, 251, 0.71)"
class="vs__spinner"
>
The .vs__spinner class will hide the text for me.
</div>
</template>
+1 -1
View File
@@ -20,6 +20,6 @@
color: #8492a4;
}
p a {
color: #48BB78;
color: #48bb78;
}
</style>
+6 -2
View File
@@ -9,7 +9,7 @@
</a>
</div>
<div class="cta">
<p style="font-size: 1.2rem; font-weight: 600;">
<p style="font-size: 1.2rem; font-weight: 600">
Hi! I'm Jeff Sagal, the author of Vue Select.
</p>
<p>
@@ -35,7 +35,11 @@
</svg>
Sponsor Vue Select!
</a>
<a href="https://twitter.com/sagalbot" target="_blank" class="social-link">
<a
href="https://twitter.com/sagalbot"
target="_blank"
class="social-link"
>
<svg viewBox="0 0 24 24" xmlns="http://www.w3.org/2000/svg">
<path
d="M23.954 4.569a10 10 0 01-2.825.775 4.958 4.958 0 002.163-2.723c-.951.555-2.005.959-3.127 1.184a4.92 4.92 0 00-8.384 4.482C7.691 8.094 4.066 6.13 1.64 3.161a4.822 4.822 0 00-.666 2.475c0 1.71.87 3.213 2.188 4.096a4.904 4.904 0 01-2.228-.616v.061a4.923 4.923 0 003.946 4.827 4.996 4.996 0 01-2.212.085 4.937 4.937 0 004.604 3.417 9.868 9.868 0 01-6.102 2.105c-.39 0-.779-.023-1.17-.067a13.995 13.995 0 007.557 2.209c9.054 0 13.999-7.496 13.999-13.986 0-.209 0-.42-.015-.63a9.936 9.936 0 002.46-2.548l-.047-.02z"
+7 -7
View File
@@ -1,6 +1,6 @@
<template>
<ul>
<li v-for="{ createdAt, login, avatarUrl } in sponsors">
<li v-for="{ createdAt, login, avatarUrl } in sponsors" :key="login">
<img :src="avatarUrl + '&s=150'" :alt="`@${login}'s avatar`" />
<p>
<a :href="`https://github.com/${login}`">@{{ login }}</a> <br />
@@ -11,17 +11,17 @@
</template>
<script>
import { SPONSORS } from "@dynamic/constants";
import { format } from "date-fns";
import { SPONSORS } from '@dynamic/constants'
import { format } from 'date-fns'
export default {
data: () => ({
sponsors: SPONSORS.map(({ createdAt, sponsorEntity }) => ({
createdAt: format(new Date(createdAt), "LLL yyyy"),
...sponsorEntity
}))
createdAt: format(new Date(createdAt), 'LLL yyyy'),
...sponsorEntity,
})),
}),
};
}
</script>
<style scoped>
@@ -3,14 +3,14 @@
placeholder="Choose a book to read"
label="title"
:options="books"
:selectable="option => ! option.author.lastName.includes('Woodhouse')"
:selectable="(option) => !option.author.lastName.includes('Woodhouse')"
/>
</template>
<script>
import books from '../data/books';
import books from '../data/books'
export default {
computed: {
books: () => books,
}
},
}
</script>
@@ -1,7 +1,7 @@
<template>
<form @submit.stop="onSubmit">
<v-select :options="books" label="title" v-model="selected">
<template #search="{attributes, events}">
<v-select v-model="selected" :options="books" label="title">
<template #search="{ attributes, events }">
<input
:required="!selected"
class="vs__search"
@@ -11,7 +11,7 @@
</template>
</v-select>
<input type="submit">
<input type="submit" />
</form>
</template>
@@ -24,28 +24,28 @@ export default {
}),
methods: {
onSubmit() {
alert('Submitted!');
}
}
};
alert('Submitted!')
},
},
}
</script>
<style scoped>
form {
display: flex;
align-items: stretch;
}
form {
display: flex;
align-items: stretch;
}
.v-select {
width: 75%;
}
.v-select {
width: 75%;
}
input[type="submit"] {
margin-left: 1rem;
background: #44ae7d;
border: none;
border-radius: 3px;
color: #fff;
width: 20%;
}
input[type='submit'] {
margin-left: 1rem;
background: #44ae7d;
border: none;
border-radius: 3px;
color: #fff;
width: 20%;
}
</style>
+5 -6
View File
@@ -1,7 +1,7 @@
const {description} = require('./config/meta');
const head = require('./config/head');
const plugins = require('./config/plugins');
const themeConfig = require('./config/themeConfig');
const { description } = require('./config/meta')
const head = require('./config/head')
const plugins = require('./config/plugins')
const themeConfig = require('./config/themeConfig')
module.exports = {
title: 'Vue Select',
@@ -9,5 +9,4 @@ module.exports = {
head,
plugins,
themeConfig,
};
}
+40 -30
View File
@@ -1,57 +1,67 @@
const isDeployPreview = require('./isDeployPreview');
const meta = require('./meta');
const isDeployPreview = require('./isDeployPreview')
const meta = require('./meta')
const head = [
[
'link',
{
href: '//fonts.googleapis.com/css?family=Source+Sans+Pro:400,600|Roboto Mono',
href:
'//fonts.googleapis.com/css?family=Source+Sans+Pro:400,600|Roboto Mono',
rel: 'stylesheet',
type: 'text/css',
}],
},
],
[
'link',
{
href: '//fonts.googleapis.com/css?family=Dosis:300&amp;text=Vue Select',
rel: 'stylesheet',
type: 'text/css',
}],
['link', {rel: 'icon', href: `/vue-logo.png`}],
['meta', {name: 'theme-color', content: '#3eaf7c'}],
['meta', {name: 'apple-mobile-web-app-capable', content: 'yes'}],
['meta', {name: 'apple-mobile-web-app-status-bar-style', content: 'black'}],
},
],
['link', { rel: 'icon', href: `/vue-logo.png` }],
['meta', { name: 'theme-color', content: '#3eaf7c' }],
['meta', { name: 'apple-mobile-web-app-capable', content: 'yes' }],
['meta', { name: 'apple-mobile-web-app-status-bar-style', content: 'black' }],
[
'link',
{rel: 'apple-touch-icon', href: `/icons/apple-touch-icon-152x152.png`}],
{ rel: 'apple-touch-icon', href: `/icons/apple-touch-icon-152x152.png` },
],
[
'link',
{rel: 'mask-icon', href: '/icons/safari-pinned-tab.svg', color: '#3eaf7c'}],
{
rel: 'mask-icon',
href: '/icons/safari-pinned-tab.svg',
color: '#3eaf7c',
},
],
[
'meta',
{
name: 'msapplication-TileImage',
content: '/icons/msapplication-icon-144x144.png',
}],
['meta', {name: 'msapplication-TileColor', content: '#000000'}],
['meta', {name: 'title', content: meta.title}],
['meta', {name: 'description', content: meta.description}],
['link', {rel: 'icon', href: meta.icon, type: 'image/png'}],
['meta', {property: 'og:image', content: meta.icon}],
['meta', {property: 'twitter:image', content: meta.icon}],
['meta', {name: 'description', content: meta.description}],
['meta', {property: 'og:description', content: ''}],
['meta', {property: 'twitter:description', content: meta.description}],
['meta', {property: 'twitter:title', content: meta.title}],
['meta', {property: 'og:title', content: meta.title}],
['meta', {property: 'og:site_name', content: meta.title}],
['meta', {property: 'og:url', content: meta.url}],
];
},
],
['meta', { name: 'msapplication-TileColor', content: '#000000' }],
['meta', { name: 'title', content: meta.title }],
['meta', { name: 'description', content: meta.description }],
['link', { rel: 'icon', href: meta.icon, type: 'image/png' }],
['meta', { property: 'og:image', content: meta.icon }],
['meta', { property: 'twitter:image', content: meta.icon }],
['meta', { name: 'description', content: meta.description }],
['meta', { property: 'og:description', content: '' }],
['meta', { property: 'twitter:description', content: meta.description }],
['meta', { property: 'twitter:title', content: meta.title }],
['meta', { property: 'og:title', content: meta.title }],
['meta', { property: 'og:site_name', content: meta.title }],
['meta', { property: 'og:url', content: meta.url }],
]
if (isDeployPreview) {
head.push(
['meta', {name: 'robots', content: 'noindex'}],
['meta', {name: 'googlebot', content: 'noindex'}],
);
['meta', { name: 'robots', content: 'noindex' }],
['meta', { name: 'googlebot', content: 'noindex' }]
)
}
module.exports = head;
module.exports = head
+1 -1
View File
@@ -1 +1 @@
module.exports = process.env.hasOwnProperty('DEPLOY_PREVIEW');
module.exports = process.env.hasOwnProperty('DEPLOY_PREVIEW')
+4 -3
View File
@@ -1,6 +1,7 @@
module.exports = {
title: 'Vue Select | VueJS Select2/Chosen Component',
description: 'Everything you wish the HTML select element could do, wrapped up into a lightweight, extensible Vue component.',
description:
'Everything you wish the HTML select element could do, wrapped up into a lightweight, extensible Vue component.',
url: 'https://vue-select.org',
icon: '/vue-logo.png'
};
icon: '/vue-logo.png',
}
+13 -13
View File
@@ -1,22 +1,22 @@
const isDeployPreview = require("./isDeployPreview");
const isDeployPreview = require('./isDeployPreview')
module.exports = [
[
"@vuepress/google-analytics",
'@vuepress/google-analytics',
{
ga: isDeployPreview ? "" : "UA-12818324-8"
}
ga: isDeployPreview ? '' : 'UA-12818324-8',
},
],
[
"@vuepress/pwa",
'@vuepress/pwa',
{
serviceWorker: false,
updatePopup: true
}
updatePopup: true,
},
],
"@vuepress/plugin-register-components",
"@vuepress/plugin-active-header-links",
"@vuepress/plugin-search",
"@vuepress/plugin-nprogress",
require('../github/index')
];
'@vuepress/plugin-register-components',
'@vuepress/plugin-active-header-links',
'@vuepress/plugin-search',
'@vuepress/plugin-nprogress',
require('../github/index'),
]
+2 -4
View File
@@ -2,9 +2,7 @@ module.exports = {
repo: 'sagalbot/vue-select',
editLinks: true,
docsDir: 'docs',
nav: [
{text: 'Sandbox', link: '/sandbox'},
],
nav: [{ text: 'Sandbox', link: '/sandbox' }],
sidebar: {
'/': [
{
@@ -75,4 +73,4 @@ module.exports = {
},
],
},
};
}
+8 -9
View File
@@ -1,20 +1,19 @@
import vSelect from '../../src/components/Select';
import vSelect from '../../src/components/Select'
export default ({Vue, options, router, siteData}) => {
Vue.component('v-select', vSelect);
export default ({ Vue, options, router, siteData }) => {
Vue.component('v-select', vSelect)
/**
* Remove service workers.
*/
if (typeof navigator !== 'undefined' && 'serviceWorker' in navigator) {
navigator.serviceWorker.getRegistrations().then(registrations => {
registrations.forEach(registration => {
navigator.serviceWorker.getRegistrations().then((registrations) => {
registrations.forEach((registration) => {
registration
.unregister()
.then(() => console.log('Service worker unregistered.'))
.catch(() => console.log('Error unregistering service worker.'));
});
});
.catch(() => console.log('Error unregistering service worker.'))
})
})
}
}
+16 -16
View File
@@ -1,14 +1,14 @@
require("dotenv").config();
const axios = require("axios");
const { graphql } = require("@octokit/graphql");
require('dotenv').config()
const axios = require('axios')
const { graphql } = require('@octokit/graphql')
module.exports = async () => ({
name: "constants.js",
name: 'constants.js',
content: `
export const SPONSORS = ${JSON.stringify(await getSponsors())};
export const CONTRIBUTORS = ${JSON.stringify(await getContributors())};
`
});
`,
})
/**
* Get a list of vue select contributors.
@@ -16,10 +16,10 @@ module.exports = async () => ({
*/
async function getContributors() {
const { data } = await axios.get(
"https://api.github.com/repos/sagalbot/vue-select/contributors?per_page=100"
);
'https://api.github.com/repos/sagalbot/vue-select/contributors?per_page=100'
)
return data;
return data
}
/**
@@ -49,17 +49,17 @@ async function getSponsors() {
}
}
}
`;
`
try {
const { user } = await graphql(query, {
headers: {
authorization: `token ${process.env.GITHUB_TOKEN || ""}`
}
});
return user.sponsorshipsAsMaintainer.nodes;
authorization: `token ${process.env.GITHUB_TOKEN || ''}`,
},
})
return user.sponsorshipsAsMaintainer.nodes
} catch (e) {
console.log(`${e.status} ${e.name} - Couldn't fetch sponsor data.`);
return [];
console.log(`${e.status} ${e.name} - Couldn't fetch sponsor data.`)
return []
}
}
+2 -2
View File
@@ -1,5 +1,5 @@
const clientDynamicModules = require('./clientDynamicModules');
const clientDynamicModules = require('./clientDynamicModules')
module.exports = {
clientDynamicModules: async () => await clientDynamicModules(),
};
}
+27 -27
View File
@@ -3,19 +3,6 @@
* @see https://ethical-ad-client.readthedocs.io/en/latest/
*/
export default {
render(h) {
return h("div", {
attrs: {
id: "ads",
"data-ea-publisher": "vue-select",
"data-ea-type": "image"
},
class: "flat horizontal"
});
},
mounted() {
this.load();
},
watch: {
$route(to, from) {
if (
@@ -23,24 +10,37 @@ export default {
// Only reload if the ad has been loaded
// otherwise it's possible that the script is appended but
// the ads are not loaded yet. This would result in duplicated ads.
[...this.$el.classList].includes("loaded")
[...this.$el.classList].includes('loaded')
) {
this.$el.innerHTML = "";
this.$el.classList.remove("loaded");
this.load();
this.$el.innerHTML = ''
this.$el.classList.remove('loaded')
this.load()
}
}
},
},
mounted() {
this.load()
},
methods: {
load() {
const s = document.createElement("script");
s.id = "_ads_js";
s.src = `https://media.ethicalads.io/media/client/ethicalads.min.js`;
s.async = "async";
this.$el.appendChild(s);
}
}
};
const s = document.createElement('script')
s.id = '_ads_js'
s.src = `https://media.ethicalads.io/media/client/ethicalads.min.js`
s.async = 'async'
this.$el.appendChild(s)
},
},
render(h) {
return h('div', {
attrs: {
id: 'ads',
'data-ea-publisher': 'vue-select',
'data-ea-type': 'image',
},
class: 'flat horizontal',
})
},
}
</script>
<style scoped>
@@ -51,4 +51,4 @@ export default {
width: 100%;
min-height: 264px;
}
</style>
</style>
+1 -1
View File
@@ -1,3 +1,3 @@
module.exports = {
extend: '@vuepress/theme-default',
};
}
+3 -3
View File
@@ -3,13 +3,13 @@
</template>
<script>
import ParentLayout from "@parent-theme/layouts/Layout.vue";
import ParentLayout from '@parent-theme/layouts/Layout.vue'
export default {
components: {
ParentLayout,
}
};
},
}
</script>
<style>
+162 -98
View File
@@ -1,111 +1,175 @@
export default () => {
document.getElementsByClassName ||
(document.getElementsByClassName = function (e) {
var n,
t,
r,
a = document,
o = []
if (a.querySelectorAll) return a.querySelectorAll('.' + e)
if (a.evaluate)
for (
t = ".//*[contains(concat(' ', @class, ' '), ' " + e + " ')]",
n = a.evaluate(t, a, null, 0, null);
(r = n.iterateNext());
document.getElementsByClassName || (document.getElementsByClassName = function (e) {
var n, t, r, a = document, o = [];
if (a.querySelectorAll) return a.querySelectorAll('.' + e);
if (a.evaluate) for (t = './/*[contains(concat(\' \', @class, \' \'), \' ' + e + ' \')]', n = a.evaluate(t, a,
null, 0,
null); r = n.iterateNext();) o.push(r); else for (n = a.getElementsByTagName('*'), t = new RegExp(
'(^|\\s)' + e + '(\\s|$)'), r = 0; r < n.length; r++) t.test(n[r].className) && o.push(n[r]);
return o;
}), function () {
function e () {
function e () {
for (var e = document.getElementsByClassName('codepen'), t = e.length - 1; t > -1; t--) {
var u = a(e[t]);
if (0 !== Object.keys(u).length && (u = o(u), u.user = n(u, e[t]), r(u))) {
var c = i(u), l = s(u, c);
f(e[t], l);
)
o.push(r)
else
for (
n = a.getElementsByTagName('*'),
t = new RegExp('(^|\\s)' + e + '(\\s|$)'),
r = 0;
r < n.length;
r++
)
t.test(n[r].className) && o.push(n[r])
return o
}),
(function () {
function e() {
function e() {
for (
var e = document.getElementsByClassName('codepen'),
t = e.length - 1;
t > -1;
t--
) {
var u = a(e[t])
if (
0 !== Object.keys(u).length &&
((u = o(u)), (u.user = n(u, e[t])), r(u))
) {
var c = i(u),
l = s(u, c)
f(e[t], l)
}
}
m()
}
m();
}
function n (e, n) {
if ('string' == typeof e.user) return e.user;
for (var t = 0, r = n.children.length; t < r; t++) {
var a = n.children[t], o = a.href || '', i = o.match(/codepen\.(io|dev)\/(\w+)\/pen\//i);
if (i) return i[2];
function n(e, n) {
if ('string' == typeof e.user) return e.user
for (var t = 0, r = n.children.length; t < r; t++) {
var a = n.children[t],
o = a.href || '',
i = o.match(/codepen\.(io|dev)\/(\w+)\/pen\//i)
if (i) return i[2]
}
return 'anon'
}
return 'anon';
}
function r (e) {return e['slug-hash'];}
function a (e) {
for (var n = {}, t = e.attributes, r = 0, a = t.length; r < a; r++) {
var o = t[r].name;
0 === o.indexOf('data-') && (n[o.replace('data-', '')] = t[r].value);
function r(e) {
return e['slug-hash']
}
return n;
function a(e) {
for (var n = {}, t = e.attributes, r = 0, a = t.length; r < a; r++) {
var o = t[r].name
0 === o.indexOf('data-') && (n[o.replace('data-', '')] = t[r].value)
}
return n
}
function o(e) {
return (
e.href && (e['slug-hash'] = e.href),
e.type && (e['default-tab'] = e.type),
e.safe &&
('true' === e.safe
? (e.animations = 'run')
: (e.animations = 'stop-after-5')),
e
)
}
function i(e) {
var n = u(e),
t = e.user ? e.user : 'anon',
r = '?' + l(e),
a = e.preview && 'true' === e.preview ? 'embed/preview' : 'embed',
o = [n, t, a, e['slug-hash'] + r].join('/')
return o.replace(/\/\//g, '//')
}
function u(e) {
return e.host
? c(e.host)
: 'file:' === document.location.protocol
? 'https://codepen.io'
: '//codepen.io'
}
function c(e) {
return e.match(/^\/\//) || !e.match(/https?:/)
? document.location.protocol + '//' + e
: e
}
function l(e) {
var n = ''
for (var t in e)
'' !== n && (n += '&'), (n += t + '=' + encodeURIComponent(e[t]))
return n
}
function s(e, n) {
var r
e['pen-title']
? (r = e['pen-title'])
: ((r = 'CodePen Embed ' + t), t++)
var a = {
id: 'cp_embed_' + e['slug-hash'].replace('/', '_'),
src: n,
scrolling: 'no',
frameborder: '0',
height: d(e),
allowTransparency: 'true',
allowfullscreen: 'true',
allowpaymentrequest: 'true',
name: 'CodePen Embed',
title: r,
class: 'cp_embed_iframe ' + (e['class'] ? e['class'] : ''),
style: 'width: ' + p + '; overflow: hidden;',
},
o = '<iframe '
for (var i in a) o += i + '="' + a[i] + '" '
return (o += '></iframe>')
}
function d(e) {
return e.height ? e.height : 300
}
function f(e, n) {
if (e.parentNode) {
var t = document.createElement('div')
;(t.className = 'cp_embed_wrapper'),
(t.innerHTML = n),
e.parentNode.replaceChild(t, e)
} else e.innerHTML = n
}
function m() {
'function' == typeof __CodePenIFrameAddedToPage &&
__CodePenIFrameAddedToPage()
}
var p = '100%'
e()
}
function o (e) {
return e.href && (e['slug-hash'] = e.href), e.type && (e['default-tab'] = e.type), e.safe &&
('true' === e.safe ? e.animations = 'run' : e.animations = 'stop-after-5'), e;
function n(e) {
;/in/.test(document.readyState)
? setTimeout('window.__cp_domReady(' + e + ')', 9)
: e()
}
function i (e) {
var n = u(e), t = e.user ? e.user : 'anon', r = '?' + l(e),
a = e.preview && 'true' === e.preview ? 'embed/preview' : 'embed',
o = [n, t, a, e['slug-hash'] + r].join('/');
return o.replace(/\/\//g, '//');
}
function u (e) {
return e.host ? c(e.host) : 'file:' === document.location.protocol
? 'https://codepen.io'
: '//codepen.io';
}
function c (e) {return e.match(/^\/\//) || !e.match(/https?:/) ? document.location.protocol + '//' + e : e;}
function l (e) {
var n = '';
for (var t in e) '' !== n && (n += '&'), n += t + '=' + encodeURIComponent(e[t]);
return n;
}
function s (e, n) {
var r;
e['pen-title'] ? r = e['pen-title'] : (r = 'CodePen Embed ' + t, t++);
var a = {
id: 'cp_embed_' + e['slug-hash'].replace('/', '_'),
src: n,
scrolling: 'no',
frameborder: '0',
height: d(e),
allowTransparency: 'true',
allowfullscreen: 'true',
allowpaymentrequest: 'true',
name: 'CodePen Embed',
title: r,
'class': 'cp_embed_iframe ' + (e['class'] ? e['class'] : ''),
style: 'width: ' + p + '; overflow: hidden;',
}, o = '<iframe ';
for (var i in a) o += i + '="' + a[i] + '" ';
return o += '></iframe>';
}
function d (e) {return e.height ? e.height : 300;}
function f (e, n) {
if (e.parentNode) {
var t = document.createElement('div');
t.className = 'cp_embed_wrapper', t.innerHTML = n, e.parentNode.replaceChild(t, e);
} else e.innerHTML = n;
}
function m () {'function' == typeof __CodePenIFrameAddedToPage && __CodePenIFrameAddedToPage();}
var p = '100%';
e();
}
function n (e) {/in/.test(document.readyState) ? setTimeout('window.__cp_domReady(' + e + ')', 9) : e();}
var t = 1;
window.__cp_domReady = n, window.__CPEmbed = e, n(function () {new __CPEmbed;});
}();
var t = 1
;(window.__cp_domReady = n),
(window.__CPEmbed = e),
n(function () {
new __CPEmbed()
})
})()
}
+1 -1
View File
@@ -5,4 +5,4 @@ module.exports = {
preset: 'default',
}),
],
};
}
+14 -14
View File
@@ -1,23 +1,23 @@
module.exports = {
release: {
branch: "master"
branch: 'master',
},
plugins: [
"@semantic-release/npm",
"@semantic-release/commit-analyzer",
"@semantic-release/release-notes-generator",
'@semantic-release/npm',
'@semantic-release/commit-analyzer',
'@semantic-release/release-notes-generator',
[
"@semantic-release/github",
'@semantic-release/github',
{
assets: ["dist/**"]
}
assets: ['dist/**'],
},
],
[
"@semantic-release/git",
'@semantic-release/git',
{
assets: ["package.json"],
message: "chore(🚀): ${nextRelease.version}"
}
]
]
};
assets: ['package.json'],
message: 'chore(🚀): ${nextRelease.version}',
},
],
],
}
+3 -1
View File
@@ -1,5 +1,7 @@
<template>
<svg xmlns="http://www.w3.org/2000/svg" width="10" height="10">
<path d="M6.895455 5l2.842897-2.842898c.348864-.348863.348864-.914488 0-1.263636L9.106534.261648c-.348864-.348864-.914489-.348864-1.263636 0L5 3.104545 2.157102.261648c-.348863-.348864-.914488-.348864-1.263636 0L.261648.893466c-.348864.348864-.348864.914489 0 1.263636L3.104545 5 .261648 7.842898c-.348864.348863-.348864.914488 0 1.263636l.631818.631818c.348864.348864.914773.348864 1.263636 0L5 6.895455l2.842898 2.842897c.348863.348864.914772.348864 1.263636 0l.631818-.631818c.348864-.348864.348864-.914489 0-1.263636L6.895455 5z"/>
<path
d="M6.895455 5l2.842897-2.842898c.348864-.348863.348864-.914488 0-1.263636L9.106534.261648c-.348864-.348864-.914489-.348864-1.263636 0L5 3.104545 2.157102.261648c-.348863-.348864-.914488-.348864-1.263636 0L.261648.893466c-.348864.348864-.348864.914489 0 1.263636L3.104545 5 .261648 7.842898c-.348864.348863-.348864.914488 0 1.263636l.631818.631818c.348864.348864.914773.348864 1.263636 0L5 6.895455l2.842898 2.842897c.348863.348864.914772.348864 1.263636 0l.631818-.631818c.348864-.348864.348864-.914489 0-1.263636L6.895455 5z"
/>
</svg>
</template>
+3 -1
View File
@@ -1,5 +1,7 @@
<template>
<svg xmlns="http://www.w3.org/2000/svg" width="14" height="10">
<path d="M9.211364 7.59931l4.48338-4.867229c.407008-.441854.407008-1.158247 0-1.60046l-.73712-.80023c-.407008-.441854-1.066904-.441854-1.474243 0L7 5.198617 2.51662.33139c-.407008-.441853-1.066904-.441853-1.474243 0l-.737121.80023c-.407008.441854-.407008 1.158248 0 1.600461l4.48338 4.867228L7 10l2.211364-2.40069z"/>
<path
d="M9.211364 7.59931l4.48338-4.867229c.407008-.441854.407008-1.158247 0-1.60046l-.73712-.80023c-.407008-.441854-1.066904-.441854-1.474243 0L7 5.198617 2.51662.33139c-.407008-.441853-1.066904-.441853-1.474243 0l-.737121.80023c-.407008.441854-.407008 1.158248 0 1.600461l4.48338 4.867228L7 10l2.211364-2.40069z"
/>
</svg>
</template>
+1199 -1100
View File
File diff suppressed because it is too large Load Diff
+3 -3
View File
@@ -1,7 +1,7 @@
import Deselect from './Deselect';
import OpenIndicator from './OpenIndicator';
import Deselect from './Deselect'
import OpenIndicator from './OpenIndicator'
export default {
Deselect,
OpenIndicator
OpenIndicator,
}
+31 -24
View File
@@ -1,27 +1,34 @@
export default {
inserted (el, bindings, {context}) {
if (context.appendToBody) {
const {height, top, left, width} = context.$refs.toggle.getBoundingClientRect();
let scrollX = window.scrollX || window.pageXOffset;
let scrollY = window.scrollY || window.pageYOffset;
el.unbindPosition = context.calculatePosition(el, context, {
width: width + 'px',
left: (scrollX + left) + 'px',
top: (scrollY + top + height) + 'px',
});
document.body.appendChild(el);
}
},
inserted(el, bindings, { context }) {
if (context.appendToBody) {
const {
height,
top,
left,
width,
} = context.$refs.toggle.getBoundingClientRect()
unbind (el, bindings, {context}) {
if (context.appendToBody) {
if (el.unbindPosition && typeof el.unbindPosition === 'function') {
el.unbindPosition();
}
if (el.parentNode) {
el.parentNode.removeChild(el);
}
}
},
let scrollX = window.scrollX || window.pageXOffset
let scrollY = window.scrollY || window.pageYOffset
el.unbindPosition = context.calculatePosition(el, context, {
width: width + 'px',
left: scrollX + left + 'px',
top: scrollY + top + height + 'px',
})
document.body.appendChild(el)
}
},
unbind(el, bindings, { context }) {
if (context.appendToBody) {
if (el.unbindPosition && typeof el.unbindPosition === 'function') {
el.unbindPosition()
}
if (el.parentNode) {
el.parentNode.removeChild(el)
}
}
},
}
+10 -10
View File
@@ -11,10 +11,10 @@ export default {
},
},
data () {
data() {
return {
mutableLoading: false,
};
}
},
watch: {
@@ -27,8 +27,8 @@ export default {
*
* @emits search
*/
search () {
this.$emit('search', this.search, this.toggleLoading);
search() {
this.$emit('search', this.search, this.toggleLoading)
},
/**
@@ -36,8 +36,8 @@ export default {
* mutable loading value.
* @param val
*/
loading (val) {
this.mutableLoading = val;
loading(val) {
this.mutableLoading = val
},
},
@@ -49,11 +49,11 @@ export default {
* @param toggle Boolean
* @returns {*}
*/
toggleLoading (toggle = null) {
toggleLoading(toggle = null) {
if (toggle == null) {
return (this.mutableLoading = !this.mutableLoading);
return (this.mutableLoading = !this.mutableLoading)
}
return (this.mutableLoading = toggle);
return (this.mutableLoading = toggle)
},
},
};
}
+13 -13
View File
@@ -2,14 +2,14 @@ export default {
props: {
autoscroll: {
type: Boolean,
default: true
}
default: true,
},
},
watch: {
typeAheadPointer() {
if (this.autoscroll) {
this.maybeAdjustScroll();
this.maybeAdjustScroll()
}
},
},
@@ -23,17 +23,17 @@ export default {
*/
maybeAdjustScroll() {
const optionEl =
this.$refs.dropdownMenu?.children[this.typeAheadPointer] || false;
this.$refs.dropdownMenu?.children[this.typeAheadPointer] || false
if (optionEl) {
const bounds = this.getDropdownViewport();
const { top, bottom, height } = optionEl.getBoundingClientRect();
const bounds = this.getDropdownViewport()
const { top, bottom, height } = optionEl.getBoundingClientRect()
if (top < bounds.top) {
return (this.$refs.dropdownMenu.scrollTop = optionEl.offsetTop);
return (this.$refs.dropdownMenu.scrollTop = optionEl.offsetTop)
} else if (bottom > bounds.bottom) {
return (this.$refs.dropdownMenu.scrollTop =
optionEl.offsetTop - (bounds.height - height));
optionEl.offsetTop - (bounds.height - height))
}
}
},
@@ -48,8 +48,8 @@ export default {
: {
height: 0,
top: 0,
bottom: 0
};
}
}
};
bottom: 0,
}
},
},
}
+17 -13
View File
@@ -1,7 +1,7 @@
export default {
data() {
return {
typeAheadPointer: -1
typeAheadPointer: -1,
}
},
@@ -9,11 +9,11 @@ export default {
filteredOptions() {
for (let i = 0; i < this.filteredOptions.length; i++) {
if (this.selectable(this.filteredOptions[i])) {
this.typeAheadPointer = i;
break;
this.typeAheadPointer = i
break
}
}
}
},
},
methods: {
@@ -25,8 +25,8 @@ export default {
typeAheadUp() {
for (let i = this.typeAheadPointer - 1; i >= 0; i--) {
if (this.selectable(this.filteredOptions[i])) {
this.typeAheadPointer = i;
break;
this.typeAheadPointer = i
break
}
}
},
@@ -37,10 +37,14 @@ export default {
* @return {void}
*/
typeAheadDown() {
for (let i = this.typeAheadPointer + 1; i < this.filteredOptions.length; i++) {
for (
let i = this.typeAheadPointer + 1;
i < this.filteredOptions.length;
i++
) {
if (this.selectable(this.filteredOptions[i])) {
this.typeAheadPointer = i;
break;
this.typeAheadPointer = i
break
}
}
},
@@ -51,11 +55,11 @@ export default {
* @return {void}
*/
typeAheadSelect() {
const typeAheadOption = this.filteredOptions[this.typeAheadPointer];
const typeAheadOption = this.filteredOptions[this.typeAheadPointer]
if (typeAheadOption) {
this.select(typeAheadOption);
this.select(typeAheadOption)
}
}
}
},
},
}
+8 -6
View File
@@ -3,13 +3,15 @@
* @return {string}
*/
function sortAndStringify(sortable) {
const ordered = {};
const ordered = {}
Object.keys(sortable).sort().forEach(key => {
ordered[key] = sortable[key];
});
Object.keys(sortable)
.sort()
.forEach((key) => {
ordered[key] = sortable[key]
})
return JSON.stringify(ordered);
return JSON.stringify(ordered)
}
export default sortAndStringify;
export default sortAndStringify
+3 -3
View File
@@ -1,4 +1,4 @@
let idCount = 0;
let idCount = 0
/**
* Dead simple unique ID implementation.
@@ -6,7 +6,7 @@ let idCount = 0;
* @return {number}
*/
function uniqueId() {
return ++idCount;
return ++idCount
}
export default uniqueId;
export default uniqueId
+26 -26
View File
@@ -1,6 +1,6 @@
import { shallowMount } from "@vue/test-utils";
import VueSelect from "../src/components/Select.vue";
import Vue from 'vue';
import { shallowMount } from '@vue/test-utils'
import VueSelect from '../src/components/Select.vue'
import Vue from 'vue'
/**
* Trigger a submit event on the search
@@ -11,10 +11,10 @@ import Vue from 'vue';
*/
export const searchSubmit = (Wrapper, searchText = false) => {
if (searchText) {
Wrapper.vm.search = searchText;
Wrapper.vm.search = searchText
}
Wrapper.find({ ref: "search" }).trigger("keydown.enter")
};
Wrapper.find({ ref: 'search' }).trigger('keydown.enter')
}
/**
* Focus the input, enter some search text, hit return.
@@ -23,15 +23,15 @@ export const searchSubmit = (Wrapper, searchText = false) => {
* @return {Promise<void>}
*/
export const selectTag = async (Wrapper, searchText) => {
Wrapper.vm.$refs.search.focus();
await Wrapper.vm.$nextTick();
Wrapper.vm.$refs.search.focus()
await Wrapper.vm.$nextTick()
Wrapper.vm.search = searchText;
await Wrapper.vm.$nextTick();
Wrapper.vm.search = searchText
await Wrapper.vm.$nextTick()
Wrapper.find({ ref: "search" }).trigger("keydown.enter");
await Wrapper.vm.$nextTick();
};
Wrapper.find({ ref: 'search' }).trigger('keydown.enter')
await Wrapper.vm.$nextTick()
}
/**
* Create a new VueSelect instance with
@@ -40,8 +40,8 @@ export const selectTag = async (Wrapper, searchText) => {
* @returns {Wrapper<Vue>}
*/
export const selectWithProps = (propsData = {}) => {
return shallowMount(VueSelect, { propsData });
};
return shallowMount(VueSelect, { propsData })
}
/**
* Returns a Wrapper with a v-select component.
@@ -56,9 +56,8 @@ export const mountDefault = (props = {}, options = {}) => {
...props,
},
...options,
});
};
})
}
/**
* Returns a v-select component directly.
@@ -68,11 +67,12 @@ export const mountDefault = (props = {}, options = {}) => {
*/
export const mountWithoutTestUtils = (props = {}, options = {}) => {
return new Vue({
render: createEl => createEl('vue-select', {
ref: 'select',
props: {options: ['one', 'two', 'three'], ...props},
...options
}),
components: {VueSelect},
}).$mount().$refs.select;
};
components: { VueSelect },
render: (createEl) =>
createEl('vue-select', {
ref: 'select',
props: { options: ['one', 'two', 'three'], ...props },
...options,
}),
}).$mount().$refs.select
}
+4 -4
View File
@@ -1,8 +1,8 @@
module.exports = {
env: {
jest: true
jest: true,
},
rules: {
'import/no-extraneous-dependencies': 'off'
}
}
'import/no-extraneous-dependencies': 'off',
},
}
+21 -21
View File
@@ -1,35 +1,35 @@
import { mountDefault } from "../helpers";
import { mountDefault } from '../helpers'
describe("Search Slot Scope", () => {
describe('Search Slot Scope', () => {
/**
* @see https://www.w3.org/WAI/PF/aria/states_and_properties#aria-activedescendant
*/
describe("aria-activedescendant", () => {
it("adds the active descendant attribute only when the dropdown is open and there is a typeAheadPointer value", async () => {
const Select = mountDefault();
describe('aria-activedescendant', () => {
it('adds the active descendant attribute only when the dropdown is open and there is a typeAheadPointer value', async () => {
const Select = mountDefault()
expect(
Select.vm.scope.search.attributes["aria-activedescendant"]
).toEqual(undefined);
Select.vm.scope.search.attributes['aria-activedescendant']
).toEqual(undefined)
Select.vm.open = true;
await Select.vm.$nextTick();
Select.vm.open = true
await Select.vm.$nextTick()
expect(
Select.vm.scope.search.attributes["aria-activedescendant"]
).toEqual(undefined);
});
Select.vm.scope.search.attributes['aria-activedescendant']
).toEqual(undefined)
})
it("adds the active descendant attribute when there's a typeahead value and an open dropdown", async () => {
const Select = mountDefault();
const Select = mountDefault()
Select.vm.open = true;
Select.vm.typeAheadPointer = 1;
await Select.vm.$nextTick();
Select.vm.open = true
Select.vm.typeAheadPointer = 1
await Select.vm.$nextTick()
expect(
Select.vm.scope.search.attributes["aria-activedescendant"]
).toEqual(`vs${Select.vm.uid}__option-1`);
});
});
});
Select.vm.scope.search.attributes['aria-activedescendant']
).toEqual(`vs${Select.vm.uid}__option-1`)
})
})
})
+42 -42
View File
@@ -1,65 +1,65 @@
import { selectWithProps } from "../helpers";
import { shallowMount } from '@vue/test-utils';
import vSelect from '../../src/components/Select';
import { selectWithProps } from '../helpers'
import { shallowMount } from '@vue/test-utils'
import vSelect from '../../src/components/Select'
describe("Asynchronous Loading", () => {
it("can toggle the loading class", () => {
const Select = selectWithProps();
describe('Asynchronous Loading', () => {
it('can toggle the loading class', () => {
const Select = selectWithProps()
Select.vm.toggleLoading();
expect(Select.vm.mutableLoading).toEqual(true);
Select.vm.toggleLoading()
expect(Select.vm.mutableLoading).toEqual(true)
Select.vm.toggleLoading(true);
expect(Select.vm.mutableLoading).toEqual(true);
});
Select.vm.toggleLoading(true)
expect(Select.vm.mutableLoading).toEqual(true)
})
it("should trigger the search event when the search text changes", async () => {
const Select = selectWithProps();
it('should trigger the search event when the search text changes', async () => {
const Select = selectWithProps()
Select.vm.search = "foo";
await Select.vm.$nextTick();
Select.vm.search = 'foo'
await Select.vm.$nextTick()
const events = Select.emitted("search");
const events = Select.emitted('search')
expect(events).toContainEqual(["foo", Select.vm.toggleLoading]);
expect(events.length).toEqual(1);
});
expect(events).toContainEqual(['foo', Select.vm.toggleLoading])
expect(events.length).toEqual(1)
})
it("should trigger the search event if the search text is empty", async () => {
const Select = selectWithProps();
it('should trigger the search event if the search text is empty', async () => {
const Select = selectWithProps()
Select.vm.search = "foo";
await Select.vm.$nextTick();
Select.vm.search = "";
await Select.vm.$nextTick();
Select.vm.search = 'foo'
await Select.vm.$nextTick()
Select.vm.search = ''
await Select.vm.$nextTick()
const events = Select.emitted("search");
const events = Select.emitted('search')
expect(events).toContainEqual(["", Select.vm.toggleLoading]);
expect(events.length).toEqual(2);
});
expect(events).toContainEqual(['', Select.vm.toggleLoading])
expect(events.length).toEqual(2)
})
it("can set loading to false from the @search event callback", async () => {
it('can set loading to false from the @search event callback', async () => {
const Select = shallowMount(vSelect, {
listeners: {
search: (search, loading) => {
loading(false)
},
},
});
})
Select.vm.mutableLoading = true;
Select.vm.search = 'foo';
await Select.vm.$nextTick();
Select.vm.mutableLoading = true
Select.vm.search = 'foo'
await Select.vm.$nextTick()
expect(Select.vm.mutableLoading).toEqual(false);
});
expect(Select.vm.mutableLoading).toEqual(false)
})
it('will sync mutable loading with the loading prop', async () => {
const Select = selectWithProps({ loading: false });
Select.setProps({ loading: true });
await Select.vm.$nextTick();
const Select = selectWithProps({ loading: false })
Select.setProps({ loading: true })
await Select.vm.$nextTick()
expect(Select.vm.mutableLoading).toEqual(true);
});
});
expect(Select.vm.mutableLoading).toEqual(true)
})
})
+36 -36
View File
@@ -1,61 +1,61 @@
import { mountDefault } from "../helpers";
import { mountDefault } from '../helpers'
describe("Automatic Scrolling", () => {
it("should check if the scroll position needs to be adjusted on up arrow keyUp", async () => {
describe('Automatic Scrolling', () => {
it('should check if the scroll position needs to be adjusted on up arrow keyUp', async () => {
// Given
const Select = mountDefault();
const spy = jest.spyOn(Select.vm, "maybeAdjustScroll");
Select.vm.typeAheadPointer = 1;
const Select = mountDefault()
const spy = jest.spyOn(Select.vm, 'maybeAdjustScroll')
Select.vm.typeAheadPointer = 1
// When
Select.find({ ref: "search" }).trigger("keydown.up");
await Select.vm.$nextTick();
Select.find({ ref: 'search' }).trigger('keydown.up')
await Select.vm.$nextTick()
// Then
expect(spy).toHaveBeenCalled();
});
expect(spy).toHaveBeenCalled()
})
it("should check if the scroll position needs to be adjusted on down arrow keyUp", async () => {
it('should check if the scroll position needs to be adjusted on down arrow keyUp', async () => {
// Given
const Select = mountDefault();
const spy = jest.spyOn(Select.vm, "maybeAdjustScroll");
Select.vm.typeAheadPointer = 1;
const Select = mountDefault()
const spy = jest.spyOn(Select.vm, 'maybeAdjustScroll')
Select.vm.typeAheadPointer = 1
// When
Select.find({ ref: "search" }).trigger("keydown.down");
await Select.vm.$nextTick();
Select.find({ ref: 'search' }).trigger('keydown.down')
await Select.vm.$nextTick()
// Then
expect(spy).toHaveBeenCalled();
});
expect(spy).toHaveBeenCalled()
})
it("should check if the scroll position needs to be adjusted when filtered options changes", async () => {
it('should check if the scroll position needs to be adjusted when filtered options changes', async () => {
// Given
const Select = mountDefault();
const spy = jest.spyOn(Select.vm, "maybeAdjustScroll");
Select.vm.typeAheadPointer = 1;
const Select = mountDefault()
const spy = jest.spyOn(Select.vm, 'maybeAdjustScroll')
Select.vm.typeAheadPointer = 1
// When
Select.vm.search = "two";
await Select.vm.$nextTick();
Select.vm.search = 'two'
await Select.vm.$nextTick()
// Then
expect(spy).toHaveBeenCalled();
});
expect(spy).toHaveBeenCalled()
})
it("should not adjust scroll position when autoscroll is false", async () => {
it('should not adjust scroll position when autoscroll is false', async () => {
// Given
const Select = mountDefault({
autoscroll: false
});
const spy = jest.spyOn(Select.vm, "maybeAdjustScroll");
Select.vm.typeAheadPointer = 1;
autoscroll: false,
})
const spy = jest.spyOn(Select.vm, 'maybeAdjustScroll')
Select.vm.typeAheadPointer = 1
// When
Select.vm.search = "two";
await Select.vm.$nextTick();
Select.vm.search = 'two'
await Select.vm.$nextTick()
// Then
expect(spy).toHaveBeenCalledTimes(0);
});
});
expect(spy).toHaveBeenCalledTimes(0)
})
})
+15 -17
View File
@@ -1,30 +1,28 @@
import Vue from 'vue';
import { selectWithProps } from '../helpers';
import Vue from 'vue'
import { selectWithProps } from '../helpers'
describe('Components API', () => {
it('swap the Deselect component', () => {
const Deselect = Vue.component('Deselect', {
render (createElement) {
return createElement('button', 'remove');
render(createElement) {
return createElement('button', 'remove')
},
});
})
const Select = selectWithProps({components: {Deselect}});
const Select = selectWithProps({ components: { Deselect } })
expect(Select.contains(Deselect)).toBeTruthy();
});
expect(Select.contains(Deselect)).toBeTruthy()
})
it('swap the OpenIndicator component', () => {
const OpenIndicator = Vue.component('OpenIndicator', {
render (createElement) {
return createElement('i', '^');
render(createElement) {
return createElement('i', '^')
},
});
})
const Select = selectWithProps({components: {OpenIndicator}});
const Select = selectWithProps({ components: { OpenIndicator } })
expect(Select.contains(OpenIndicator)).toBeTruthy();
});
});
expect(Select.contains(OpenIndicator)).toBeTruthy()
})
})
+17 -17
View File
@@ -1,30 +1,30 @@
import { searchSubmit, selectTag, selectWithProps } from "../helpers";
import { searchSubmit, selectTag, selectWithProps } from '../helpers'
describe("CreateOption When Tagging Is Enabled", () => {
it("can select the current search text as a string", async () => {
describe('CreateOption When Tagging Is Enabled', () => {
it('can select the current search text as a string', async () => {
const Select = selectWithProps({
taggable: true,
multiple: true,
options: ["one", "two"],
createOption: option => "four"
});
options: ['one', 'two'],
createOption: (option) => 'four',
})
await selectTag(Select, "three");
expect(Select.vm.selectedValue).toEqual(["four"]);
});
await selectTag(Select, 'three')
expect(Select.vm.selectedValue).toEqual(['four'])
})
it("can select the current search text as an object", async () => {
it('can select the current search text as an object', async () => {
const Select = selectWithProps({
taggable: true,
multiple: false,
value: null,
options: [],
label: "name",
createOption: title => ({ name: title })
});
label: 'name',
createOption: (title) => ({ name: title }),
})
await selectTag(Select, "two");
await selectTag(Select, 'two')
expect(Select.emitted("input")[0]).toEqual([{ name: "two" }]);
});
});
expect(Select.emitted('input')[0]).toEqual([{ name: 'two' }])
})
})
+74 -74
View File
@@ -1,107 +1,107 @@
import { mountDefault, selectWithProps } from '../helpers';
import { mountDefault, selectWithProps } from '../helpers'
describe("Removing values", () => {
it("can remove the given tag when its close icon is clicked", async () => {
const Select = selectWithProps({ multiple: true });
Select.vm.$data._value = 'one';
await Select.vm.$nextTick();
describe('Removing values', () => {
it('can remove the given tag when its close icon is clicked', async () => {
const Select = selectWithProps({ multiple: true })
Select.vm.$data._value = 'one'
await Select.vm.$nextTick()
Select.find(".vs__deselect").trigger("click");
expect(Select.emitted().input).toEqual([[[]]]);
expect(Select.vm.selectedValue).toEqual([]);
});
Select.find('.vs__deselect').trigger('click')
expect(Select.emitted().input).toEqual([[[]]])
expect(Select.vm.selectedValue).toEqual([])
})
it("should not remove tag when close icon is clicked and component is disabled", () => {
it('should not remove tag when close icon is clicked and component is disabled', () => {
const Select = selectWithProps({
value: ["one"],
options: ["one", "two", "three"],
value: ['one'],
options: ['one', 'two', 'three'],
multiple: true,
disabled: true
});
disabled: true,
})
Select.find(".vs__deselect").trigger("click");
expect(Select.vm.selectedValue).toEqual(["one"]);
});
Select.find('.vs__deselect').trigger('click')
expect(Select.vm.selectedValue).toEqual(['one'])
})
it("should remove the last item in the value array on delete keypress when multiple is true", () => {
it('should remove the last item in the value array on delete keypress when multiple is true', () => {
const Select = selectWithProps({
multiple: true,
options: ["one", "two", "three"]
});
options: ['one', 'two', 'three'],
})
Select.vm.$data._value = ["one", "two"];
Select.vm.$data._value = ['one', 'two']
Select.find('.vs__search').trigger('keydown.backspace')
expect(Select.emitted().input).toEqual([[['one']]]);
expect(Select.vm.selectedValue).toEqual(["one"]);
});
expect(Select.emitted().input).toEqual([[['one']]])
expect(Select.vm.selectedValue).toEqual(['one'])
})
it("should set value to null on delete keypress when multiple is false", () => {
it('should set value to null on delete keypress when multiple is false', () => {
const Select = selectWithProps({
options: ["one", "two", "three"]
});
options: ['one', 'two', 'three'],
})
Select.vm.$data._value = 'one';
Select.vm.$data._value = 'one'
Select.vm.maybeDeleteValue();
expect(Select.vm.selectedValue).toEqual([]);
});
Select.vm.maybeDeleteValue()
expect(Select.vm.selectedValue).toEqual([])
})
it('will not emit input event if value has not changed with backspace', () => {
const Select = mountDefault();
Select.vm.$data._value = 'one';
Select.find({ ref: 'search' }).trigger('keydown.backspace');
expect(Select.emitted().input.length).toBe(1);
const Select = mountDefault()
Select.vm.$data._value = 'one'
Select.find({ ref: 'search' }).trigger('keydown.backspace')
expect(Select.emitted().input.length).toBe(1)
Select.find({ ref: 'search' }).trigger('keydown.backspace');
Select.find({ ref: 'search' }).trigger('keydown.backspace');
expect(Select.emitted().input.length).toBe(1);
});
Select.find({ ref: 'search' }).trigger('keydown.backspace')
Select.find({ ref: 'search' }).trigger('keydown.backspace')
expect(Select.emitted().input.length).toBe(1)
})
describe("Clear button", () => {
it("should be displayed on single select when value is selected", () => {
describe('Clear button', () => {
it('should be displayed on single select when value is selected', () => {
const Select = selectWithProps({
options: ["foo", "bar"],
value: "foo"
});
options: ['foo', 'bar'],
value: 'foo',
})
expect(Select.vm.showClearButton).toEqual(true);
});
expect(Select.vm.showClearButton).toEqual(true)
})
it("should not be displayed on multiple select", () => {
it('should not be displayed on multiple select', () => {
const Select = selectWithProps({
options: ["foo", "bar"],
value: "foo",
multiple: true
});
options: ['foo', 'bar'],
value: 'foo',
multiple: true,
})
expect(Select.vm.showClearButton).toEqual(false);
});
expect(Select.vm.showClearButton).toEqual(false)
})
it("should remove selected value when clicked", () => {
it('should remove selected value when clicked', () => {
const Select = selectWithProps({
options: ["foo", "bar"],
});
Select.vm.$data._value = 'foo';
options: ['foo', 'bar'],
})
Select.vm.$data._value = 'foo'
expect(Select.vm.selectedValue).toEqual(["foo"]);
Select.find("button.vs__clear").trigger("click");
expect(Select.vm.selectedValue).toEqual(['foo'])
Select.find('button.vs__clear').trigger('click')
expect(Select.emitted().input).toEqual([[null]]);
expect(Select.vm.selectedValue).toEqual([]);
});
expect(Select.emitted().input).toEqual([[null]])
expect(Select.vm.selectedValue).toEqual([])
})
it("should be disabled when component is disabled", () => {
it('should be disabled when component is disabled', () => {
const Select = selectWithProps({
options: ["foo", "bar"],
value: "foo",
disabled: true
});
options: ['foo', 'bar'],
value: 'foo',
disabled: true,
})
expect(Select.find("button.vs__clear").attributes().disabled).toEqual(
"disabled"
);
});
});
});
expect(Select.find('button.vs__clear').attributes().disabled).toEqual(
'disabled'
)
})
})
})
+147 -147
View File
@@ -1,201 +1,201 @@
import { selectWithProps } from "../helpers";
import OpenIndicator from "../../src/components/OpenIndicator";
import { selectWithProps } from '../helpers'
import OpenIndicator from '../../src/components/OpenIndicator'
const preventDefault = jest.fn()
function clickEvent (currentTarget) {
function clickEvent(currentTarget) {
return { currentTarget, preventDefault }
}
describe("Toggling Dropdown", () => {
it("should not open the dropdown when the el is clicked but the component is disabled", () => {
const Select = selectWithProps({ disabled: true });
Select.vm.toggleDropdown(clickEvent(Select.vm.$refs.search));
expect(Select.vm.open).toEqual(false);
});
it("should open the dropdown when the el is clicked", () => {
const Select = selectWithProps({
value: [{ label: "one" }],
options: [{ label: "one" }]
});
Select.vm.toggleDropdown(clickEvent(Select.vm.$refs.search));
expect(Select.vm.open).toEqual(true);
});
it("should not close the dropdown when the el is clicked and enableMouseInputSearch is set to true", () => {
const Select = selectWithProps({
value: [{ label: "one" }],
options: [{ label: "one" }],
enableMouseSearchInput: true
});
Select.vm.toggleDropdown(clickEvent(Select.vm.$refs.search));
expect(Select.vm.open).toEqual(true);
Select.vm.toggleDropdown(clickEvent(Select.vm.$el));
describe('Toggling Dropdown', () => {
it('should not open the dropdown when the el is clicked but the component is disabled', () => {
const Select = selectWithProps({ disabled: true })
Select.vm.toggleDropdown(clickEvent(Select.vm.$refs.search))
expect(Select.vm.open).toEqual(false)
});
})
it("should open the dropdown when the selected tag is clicked", () => {
it('should open the dropdown when the el is clicked', () => {
const Select = selectWithProps({
value: [{ label: "one" }],
options: [{ label: "one" }]
});
value: [{ label: 'one' }],
options: [{ label: 'one' }],
})
const selectedTag = Select.find(".vs__selected").element;
Select.vm.toggleDropdown(clickEvent(Select.vm.$refs.search))
expect(Select.vm.open).toEqual(true)
})
Select.vm.toggleDropdown(clickEvent(selectedTag));
expect(Select.vm.open).toEqual(true);
});
it('should not close the dropdown when the el is clicked and enableMouseInputSearch is set to true', () => {
const Select = selectWithProps({
value: [{ label: 'one' }],
options: [{ label: 'one' }],
enableMouseSearchInput: true,
})
it("can close the dropdown when the el is clicked", () => {
const Select = selectWithProps();
const spy = jest.spyOn(Select.vm.$refs.search, "blur");
Select.vm.toggleDropdown(clickEvent(Select.vm.$refs.search))
expect(Select.vm.open).toEqual(true)
Select.vm.toggleDropdown(clickEvent(Select.vm.$el))
expect(Select.vm.open).toEqual(false)
})
Select.vm.open = true;
Select.vm.toggleDropdown(clickEvent(Select.vm.$el));
it('should open the dropdown when the selected tag is clicked', () => {
const Select = selectWithProps({
value: [{ label: 'one' }],
options: [{ label: 'one' }],
})
expect(spy).toHaveBeenCalled();
});
const selectedTag = Select.find('.vs__selected').element
it("closes the dropdown when an option is selected, multiple is true, and closeOnSelect option is true", () => {
Select.vm.toggleDropdown(clickEvent(selectedTag))
expect(Select.vm.open).toEqual(true)
})
it('can close the dropdown when the el is clicked', () => {
const Select = selectWithProps()
const spy = jest.spyOn(Select.vm.$refs.search, 'blur')
Select.vm.open = true
Select.vm.toggleDropdown(clickEvent(Select.vm.$el))
expect(spy).toHaveBeenCalled()
})
it('closes the dropdown when an option is selected, multiple is true, and closeOnSelect option is true', () => {
const Select = selectWithProps({
value: [],
options: ["one", "two", "three"],
multiple: true
});
Select.vm.open = true;
Select.vm.select("one");
expect(Select.vm.open).toEqual(false);
});
it("does not close the dropdown when the el is clicked, multiple is true, and closeOnSelect option is false", () => {
const Select = selectWithProps({
value: [],
options: ["one", "two", "three"],
options: ['one', 'two', 'three'],
multiple: true,
closeOnSelect: false
});
})
Select.vm.open = true;
Select.vm.select("one");
Select.vm.open = true
Select.vm.select('one')
expect(Select.vm.open).toEqual(true);
});
expect(Select.vm.open).toEqual(false)
})
it("should close the dropdown on search blur", () => {
it('does not close the dropdown when the el is clicked, multiple is true, and closeOnSelect option is false', () => {
const Select = selectWithProps({
options: [{ label: "one" }]
});
value: [],
options: ['one', 'two', 'three'],
multiple: true,
closeOnSelect: false,
})
Select.vm.open = true;
Select.find({ ref: "search" }).trigger("blur");
Select.vm.open = true
Select.vm.select('one')
expect(Select.vm.open).toEqual(false);
});
expect(Select.vm.open).toEqual(true)
})
it("will close the dropdown and emit the search:blur event from onSearchBlur", () => {
const Select = selectWithProps();
const spy = jest.spyOn(Select.vm, "$emit");
Select.vm.open = true;
Select.vm.onSearchBlur();
expect(Select.vm.open).toEqual(false);
expect(spy).toHaveBeenCalledWith("search:blur");
});
it("will open the dropdown and emit the search:focus event from onSearchFocus", () => {
const Select = selectWithProps();
const spy = jest.spyOn(Select.vm, "$emit");
Select.vm.onSearchFocus();
expect(Select.vm.open).toEqual(true);
expect(spy).toHaveBeenCalledWith("search:focus");
});
it("will close the dropdown on escape, if search is empty", () => {
const Select = selectWithProps();
const spy = jest.spyOn(Select.vm.$refs.search, "blur");
Select.vm.open = true;
Select.vm.onEscape();
expect(spy).toHaveBeenCalled();
});
it("should remove existing search text on escape keydown", () => {
it('should close the dropdown on search blur', () => {
const Select = selectWithProps({
value: [{ label: "one" }],
options: [{ label: "one" }]
});
options: [{ label: 'one' }],
})
Select.vm.search = "foo";
Select.vm.open = true
Select.find({ ref: 'search' }).trigger('blur')
expect(Select.vm.open).toEqual(false)
})
it('will close the dropdown and emit the search:blur event from onSearchBlur', () => {
const Select = selectWithProps()
const spy = jest.spyOn(Select.vm, '$emit')
Select.vm.open = true
Select.vm.onSearchBlur()
expect(Select.vm.open).toEqual(false)
expect(spy).toHaveBeenCalledWith('search:blur')
})
it('will open the dropdown and emit the search:focus event from onSearchFocus', () => {
const Select = selectWithProps()
const spy = jest.spyOn(Select.vm, '$emit')
Select.vm.onSearchFocus()
expect(Select.vm.open).toEqual(true)
expect(spy).toHaveBeenCalledWith('search:focus')
})
it('will close the dropdown on escape, if search is empty', () => {
const Select = selectWithProps()
const spy = jest.spyOn(Select.vm.$refs.search, 'blur')
Select.vm.open = true
Select.vm.onEscape()
expect(spy).toHaveBeenCalled()
})
it('should remove existing search text on escape keydown', () => {
const Select = selectWithProps({
value: [{ label: 'one' }],
options: [{ label: 'one' }],
})
Select.vm.search = 'foo'
Select.find('.vs__search').trigger('keydown.esc')
expect(Select.vm.search).toEqual("");
});
expect(Select.vm.search).toEqual('')
})
it("should have an open class when dropdown is active", () => {
const Select = selectWithProps();
it('should have an open class when dropdown is active', () => {
const Select = selectWithProps()
expect(Select.vm.stateClasses['vs--open']).toEqual(false);
expect(Select.vm.stateClasses['vs--open']).toEqual(false)
Select.vm.open = true;
expect(Select.vm.stateClasses['vs--open']).toEqual(true);
});
Select.vm.open = true
expect(Select.vm.stateClasses['vs--open']).toEqual(true)
})
it("should not display the dropdown if noDrop is true", async () => {
it('should not display the dropdown if noDrop is true', async () => {
const Select = selectWithProps({
noDrop: true,
});
})
Select.vm.toggleDropdown(clickEvent(Select.vm.$refs.search));
Select.vm.toggleDropdown(clickEvent(Select.vm.$refs.search))
expect(Select.vm.open).toEqual(true);
await Select.vm.$nextTick();
expect(Select.vm.open).toEqual(true)
await Select.vm.$nextTick()
expect(Select.contains('.vs__dropdown-menu')).toBeFalsy();
expect(Select.contains('.vs__dropdown-option')).toBeFalsy();
expect(Select.contains('.vs__no-options')).toBeFalsy();
expect(Select.vm.stateClasses['vs--open']).toBeFalsy();
});
expect(Select.contains('.vs__dropdown-menu')).toBeFalsy()
expect(Select.contains('.vs__dropdown-option')).toBeFalsy()
expect(Select.contains('.vs__no-options')).toBeFalsy()
expect(Select.vm.stateClasses['vs--open']).toBeFalsy()
})
it("should hide the open indicator if noDrop is true", () => {
it('should hide the open indicator if noDrop is true', () => {
const Select = selectWithProps({
noDrop: true,
});
expect(Select.contains(OpenIndicator)).toBeFalsy();
});
})
expect(Select.contains(OpenIndicator)).toBeFalsy()
})
it("should not add the searchable state class when noDrop is true", () => {
it('should not add the searchable state class when noDrop is true', () => {
const Select = selectWithProps({
noDrop: true,
});
expect(Select.classes('vs--searchable')).toBeFalsy();
});
})
expect(Select.classes('vs--searchable')).toBeFalsy()
})
it("should not add the searching state class when noDrop is true", () => {
it('should not add the searching state class when noDrop is true', () => {
const Select = selectWithProps({
noDrop: true,
});
})
Select.vm.search = 'Canada';
Select.vm.search = 'Canada'
expect(Select.classes('vs--searching')).toBeFalsy();
});
expect(Select.classes('vs--searching')).toBeFalsy()
})
it("can be opened with dropdownShouldOpen", () => {
it('can be opened with dropdownShouldOpen', () => {
const Select = selectWithProps({
noDrop: true,
dropdownShouldOpen: () => true,
options: ['one']
});
options: ['one'],
})
expect(Select.classes('vs--open')).toBeTruthy();
expect(Select.find('.vs__dropdown-menu li')).toBeTruthy();
expect(Select.classes('vs--open')).toBeTruthy()
expect(Select.find('.vs__dropdown-menu li')).toBeTruthy()
})
});
})
+60 -60
View File
@@ -1,86 +1,86 @@
import { shallowMount } from "@vue/test-utils";
import VueSelect from "../../src/components/Select";
import { shallowMount } from '@vue/test-utils'
import VueSelect from '../../src/components/Select'
describe("Filtering Options", () => {
describe('Filtering Options', () => {
it("should update the search value when the input element receives the 'input' event", () => {
const Select = shallowMount(VueSelect, {
propsData: { options: ["foo", "bar", "baz"] }
});
const input = Select.find('.vs__search');
propsData: { options: ['foo', 'bar', 'baz'] },
})
const input = Select.find('.vs__search')
input.element.value = 'a'
input.trigger('input')
expect(Select.vm.search).toEqual('a');
});
expect(Select.vm.search).toEqual('a')
})
it("should filter an array of strings", () => {
it('should filter an array of strings', () => {
const Select = shallowMount(VueSelect, {
propsData: { options: ["foo", "bar", "baz"] }
});
Select.vm.search = "ba";
expect(Select.vm.filteredOptions).toEqual(["bar", "baz"]);
});
propsData: { options: ['foo', 'bar', 'baz'] },
})
Select.vm.search = 'ba'
expect(Select.vm.filteredOptions).toEqual(['bar', 'baz'])
})
it("should not filter the array of strings if filterable is false", () => {
it('should not filter the array of strings if filterable is false', () => {
const Select = shallowMount(VueSelect, {
propsData: { options: ["foo", "bar", "baz"], filterable: false }
});
Select.vm.search = "ba";
expect(Select.vm.filteredOptions).toEqual(["foo", "bar", "baz"]);
});
propsData: { options: ['foo', 'bar', 'baz'], filterable: false },
})
Select.vm.search = 'ba'
expect(Select.vm.filteredOptions).toEqual(['foo', 'bar', 'baz'])
})
it("should filter without case-sensitivity", () => {
it('should filter without case-sensitivity', () => {
const Select = shallowMount(VueSelect, {
propsData: { options: ["Foo", "Bar", "Baz"] }
});
Select.vm.search = "ba";
expect(Select.vm.filteredOptions).toEqual(["Bar", "Baz"]);
});
propsData: { options: ['Foo', 'Bar', 'Baz'] },
})
Select.vm.search = 'ba'
expect(Select.vm.filteredOptions).toEqual(['Bar', 'Baz'])
})
it("can filter an array of objects based on the objects label key", () => {
it('can filter an array of objects based on the objects label key', () => {
const Select = shallowMount(VueSelect, {
propsData: {
options: [{ label: "Foo" }, { label: "Bar" }, { label: "Baz" }]
}
});
Select.vm.search = "ba";
options: [{ label: 'Foo' }, { label: 'Bar' }, { label: 'Baz' }],
},
})
Select.vm.search = 'ba'
expect(Select.vm.filteredOptions).toEqual([
{ label: "Bar" },
{ label: "Baz" }
]);
});
{ label: 'Bar' },
{ label: 'Baz' },
])
})
it("can determine if a given option should match the current search text", () => {
it('can determine if a given option should match the current search text', () => {
const Select = shallowMount(VueSelect, {
propsData: {
options: [{ label: "Aoo" }, { label: "Bar" }, { label: "Baz" }],
options: [{ label: 'Aoo' }, { label: 'Bar' }, { label: 'Baz' }],
filterBy: (option, label, search) =>
label.match(new RegExp("^" + search, "i"))
}
});
label.match(new RegExp('^' + search, 'i')),
},
})
Select.vm.search = "a";
expect(Select.vm.filteredOptions).toEqual([{ label: "Aoo" }]);
});
Select.vm.search = 'a'
expect(Select.vm.filteredOptions).toEqual([{ label: 'Aoo' }])
})
it("can use a custom filtering method", () => {
it('can use a custom filtering method', () => {
const Select = shallowMount(VueSelect, {
propsData: {
options: ["foo", "bar", "baz"],
filterBy: (option, label) => label.includes("o")
}
});
Select.vm.search = "a";
expect(Select.vm.filteredOptions).toEqual(["foo"]);
});
options: ['foo', 'bar', 'baz'],
filterBy: (option, label) => label.includes('o'),
},
})
Select.vm.search = 'a'
expect(Select.vm.filteredOptions).toEqual(['foo'])
})
it("can filter arrays of numbers", () => {
it('can filter arrays of numbers', () => {
const Select = shallowMount(VueSelect, {
propsData: {
options: [1, 5, 10]
}
});
Select.vm.search = "1";
expect(Select.vm.filteredOptions).toEqual([1, 10]);
});
});
options: [1, 5, 10],
},
})
Select.vm.search = '1'
expect(Select.vm.filteredOptions).toEqual([1, 10])
})
})
+39 -43
View File
@@ -1,74 +1,70 @@
import { mountDefault } from '../helpers';
import { mountDefault } from '../helpers'
describe('Custom Keydown Handlers', () => {
it('can use the map-keydown prop to trigger custom behaviour', () => {
const onKeyDown = jest.fn();
const onKeyDown = jest.fn()
const Select = mountDefault({
mapKeydown: (defaults, vm) => ({ ...defaults, 32: onKeyDown }),
});
})
Select.find({ ref: 'search' }).trigger('keydown.space');
Select.find({ ref: 'search' }).trigger('keydown.space')
expect(onKeyDown.mock.calls.length).toBe(1);
});
expect(onKeyDown.mock.calls.length).toBe(1)
})
it('selectOnKeyCodes should trigger a selection for custom keycodes', () => {
const Select = mountDefault({
selectOnKeyCodes: [32],
});
})
const spy = jest.spyOn(Select.vm, 'typeAheadSelect');
const spy = jest.spyOn(Select.vm, 'typeAheadSelect')
Select.find({ ref: 'search' }).trigger('keydown.space');
Select.find({ ref: 'search' }).trigger('keydown.space')
expect(spy).toHaveBeenCalledTimes(1);
});
expect(spy).toHaveBeenCalledTimes(1)
})
it('even works when combining selectOnKeyCodes with map-keydown', () => {
const onKeyDown = jest.fn();
const onKeyDown = jest.fn()
const Select = mountDefault({
mapKeydown: (defaults, vm) => ({ ...defaults, 32: onKeyDown }),
selectOnKeyCodes: [9],
});
})
const spy = jest.spyOn(Select.vm, 'typeAheadSelect');
const spy = jest.spyOn(Select.vm, 'typeAheadSelect')
Select.find({ ref: 'search' }).trigger('keydown.space');
expect(onKeyDown.mock.calls.length).toBe(1);
Select.find({ ref: 'search' }).trigger('keydown.space')
expect(onKeyDown.mock.calls.length).toBe(1)
Select.find({ ref: 'search' }).trigger('keydown.tab');
expect(spy).toHaveBeenCalledTimes(1);
});
Select.find({ ref: 'search' }).trigger('keydown.tab')
expect(spy).toHaveBeenCalledTimes(1)
})
describe('CompositionEvent support', () => {
it('will not select a value with enter if the user is composing', () => {
const Select = mountDefault();
const spy = jest.spyOn(Select.vm, 'typeAheadSelect');
const Select = mountDefault()
const spy = jest.spyOn(Select.vm, 'typeAheadSelect')
Select.find({ ref: 'search' }).trigger('compositionstart');
Select.find({ ref: 'search' }).trigger('keydown.enter');
expect(spy).toHaveBeenCalledTimes(0);
Select.find({ ref: 'search' }).trigger('compositionstart')
Select.find({ ref: 'search' }).trigger('keydown.enter')
expect(spy).toHaveBeenCalledTimes(0)
Select.find({ ref: 'search' }).trigger('compositionend');
Select.find({ ref: 'search' }).trigger('keydown.enter');
expect(spy).toHaveBeenCalledTimes(1);
});
Select.find({ ref: 'search' }).trigger('compositionend')
Select.find({ ref: 'search' }).trigger('keydown.enter')
expect(spy).toHaveBeenCalledTimes(1)
})
it('will not select a value with tab if the user is composing', () => {
const Select = mountDefault({ selectOnTab: true });
const spy = jest.spyOn(Select.vm, 'typeAheadSelect');
const Select = mountDefault({ selectOnTab: true })
const spy = jest.spyOn(Select.vm, 'typeAheadSelect')
Select.find({ ref: 'search' }).trigger('compositionstart');
Select.find({ ref: 'search' }).trigger('keydown.tab');
expect(spy).toHaveBeenCalledTimes(0);
Select.find({ ref: 'search' }).trigger('compositionstart')
Select.find({ ref: 'search' }).trigger('keydown.tab')
expect(spy).toHaveBeenCalledTimes(0)
Select.find({ ref: 'search' }).trigger('compositionend');
Select.find({ ref: 'search' }).trigger('keydown.tab');
expect(spy).toHaveBeenCalledTimes(1);
});
});
});
Select.find({ ref: 'search' }).trigger('compositionend')
Select.find({ ref: 'search' }).trigger('keydown.tab')
expect(spy).toHaveBeenCalledTimes(1)
})
})
})
+49 -45
View File
@@ -1,57 +1,61 @@
import VueSelect from "../../src/components/Select";
import { shallowMount } from "@vue/test-utils";
import { selectWithProps } from "../helpers";
import VueSelect from '../../src/components/Select'
import { shallowMount } from '@vue/test-utils'
import { selectWithProps } from '../helpers'
describe("Labels", () => {
it("can generate labels using a custom label key", () => {
describe('Labels', () => {
it('can generate labels using a custom label key', () => {
const Select = selectWithProps({
options: [{ name: "Foo" }],
label: "name",
value: { name: "Foo" }
});
expect(Select.find(".vs__selected").text()).toBe("Foo");
});
options: [{ name: 'Foo' }],
label: 'name',
value: { name: 'Foo' },
})
expect(Select.find('.vs__selected').text()).toBe('Foo')
})
it("will console.warn when options contain objects without a valid label key", async () => {
const spy = jest.spyOn(console, "warn").mockImplementation(() => {});
it('will console.warn when options contain objects without a valid label key', async () => {
const spy = jest.spyOn(console, 'warn').mockImplementation(() => {})
const Select = selectWithProps({
options: [{}]
});
options: [{}],
})
Select.vm.open = true;
await Select.vm.$nextTick();
Select.vm.open = true
await Select.vm.$nextTick()
expect(spy).toHaveBeenCalledWith(
'[vue-select warn]: Label key "option.label" does not exist in options object {}.' +
"\nhttps://vue-select.org/api/props.html#getoptionlabel"
);
});
'\nhttps://vue-select.org/api/props.html#getoptionlabel'
)
})
it("should display a placeholder if the value is empty", () => {
it('should display a placeholder if the value is empty', () => {
const Select = shallowMount(VueSelect, {
propsData: {
options: ["one"]
options: ['one'],
},
attrs: {
placeholder: "foo"
}
});
placeholder: 'foo',
},
})
expect(Select.vm.searchPlaceholder).toEqual("foo");
Select.vm.$data._value = "one";
expect(Select.vm.searchPlaceholder).not.toBeDefined();
});
expect(Select.vm.searchPlaceholder).toEqual('foo')
Select.vm.$data._value = 'one'
expect(Select.vm.searchPlaceholder).not.toBeDefined()
})
describe('getOptionLabel', () => {
it('will return undefined if the option lacks the label key', () => {
const getOptionLabel = VueSelect.props.getOptionLabel.default.bind({ label: 'label' });
expect(getOptionLabel({name: 'vue'})).toEqual(undefined);
});
const getOptionLabel = VueSelect.props.getOptionLabel.default.bind({
label: 'label',
})
expect(getOptionLabel({ name: 'vue' })).toEqual(undefined)
})
it('will return a string value for a valid key', () => {
const getOptionLabel = VueSelect.props.getOptionLabel.default.bind({ label: 'label' });
expect(getOptionLabel({label: 'vue'})).toEqual('vue');
});
const getOptionLabel = VueSelect.props.getOptionLabel.default.bind({
label: 'label',
})
expect(getOptionLabel({ label: 'vue' })).toEqual('vue')
})
/**
* this test fails because of a bug where Vue executes the default contents
@@ -60,22 +64,22 @@ describe("Labels", () => {
* @see https://github.com/vuejs/vue/pull/10229
*/
xit('will not call getOptionLabel if both scoped option slots are used and a filter is provided', () => {
const spy = spyOn(VueSelect.props.getOptionLabel, 'default');
const spy = spyOn(VueSelect.props.getOptionLabel, 'default')
const Select = shallowMount(VueSelect, {
propsData: {
options: [{name: 'one'}],
options: [{ name: 'one' }],
filter: () => {},
},
scopedSlots: {
'option': '<span class="option">{{ props.name }}</span>',
option: '<span class="option">{{ props.name }}</span>',
'selected-option': '<span class="selected">{{ props.name }}</span>',
},
});
})
Select.vm.select({name: 'one'});
Select.vm.select({ name: 'one' })
expect(spy).toHaveBeenCalledTimes(0);
expect(Select.find('.selected').exists()).toBeTruthy();
});
});
});
expect(spy).toHaveBeenCalledTimes(0)
expect(Select.find('.selected').exists()).toBeTruthy()
})
})
})
+22 -22
View File
@@ -1,30 +1,30 @@
import { shallowMount } from "@vue/test-utils";
import VueSelect from "../../src/components/Select";
import { shallowMount } from '@vue/test-utils'
import VueSelect from '../../src/components/Select'
describe("Single value options", () => {
it("should reset the search input on focus lost", () => {
const Select = shallowMount(VueSelect);
Select.vm.open = true;
describe('Single value options', () => {
it('should reset the search input on focus lost', () => {
const Select = shallowMount(VueSelect)
Select.vm.open = true
Select.vm.search = "t";
expect(Select.vm.search).toEqual("t");
Select.vm.search = 't'
expect(Select.vm.search).toEqual('t')
Select.vm.onSearchBlur();
expect(Select.vm.search).toEqual("");
});
Select.vm.onSearchBlur()
expect(Select.vm.search).toEqual('')
})
it("should not reset the search input on focus lost when clearSearchOnSelect is false", () => {
it('should not reset the search input on focus lost when clearSearchOnSelect is false', () => {
const Select = shallowMount(VueSelect, {
propsData: { value: "foo", clearSearchOnSelect: false }
});
propsData: { value: 'foo', clearSearchOnSelect: false },
})
expect(Select.vm.clearSearchOnSelect).toEqual(false);
expect(Select.vm.clearSearchOnSelect).toEqual(false)
Select.vm.open = true;
Select.vm.search = "t";
expect(Select.vm.search).toEqual("t");
Select.vm.open = true
Select.vm.search = 't'
expect(Select.vm.search).toEqual('t')
Select.vm.onSearchBlur();
expect(Select.vm.search).toEqual("t");
});
});
Select.vm.onSearchBlur()
expect(Select.vm.search).toEqual('t')
})
})
+19 -18
View File
@@ -1,31 +1,32 @@
import Select from '../../src/components/Select';
import Select from '../../src/components/Select'
describe('Comparing Options', () => {
const comparator = Select.methods.optionComparator.bind({
getOptionKey: Select.props.getOptionKey.default,
});
})
it('can compare numbers', () => {
expect(comparator(1, 2)).toBeFalsy();
expect(comparator(1, 1)).toBeTruthy();
});
expect(comparator(1, 2)).toBeFalsy()
expect(comparator(1, 1)).toBeTruthy()
})
it('can compare strings', () => {
expect(comparator('one', 'one')).toBeTruthy();
expect(comparator('one', 'two')).toBeFalsy();
});
expect(comparator('one', 'one')).toBeTruthy()
expect(comparator('one', 'two')).toBeFalsy()
})
it('can compare objects', () => {
// compare ID keys
expect(comparator({label: 'halo', id: 1}, {label: 'halo', id: 2}))
.toBeFalsy();
expect(
comparator({ label: 'halo', id: 1 }, { label: 'halo', id: 2 })
).toBeFalsy()
// compare objects
expect(comparator({label: 'halo', value: 1}, {label: 'halo', value: 1}))
.toBeTruthy();
expect(
comparator({ label: 'halo', value: 1 }, { label: 'halo', value: 1 })
).toBeTruthy()
// compare objects with different orders
expect(comparator({value: 1, label: 'halo'}, {label: 'halo', value: 1}))
.toBeTruthy();
});
});
expect(
comparator({ value: 1, label: 'halo' }, { label: 'halo', value: 1 })
).toBeTruthy()
})
})
+15 -15
View File
@@ -1,25 +1,25 @@
import Select from '../../src/components/Select.vue';
import Select from '../../src/components/Select.vue'
describe('Serializing Option Keys', () => {
const getOptionKey = Select.props.getOptionKey.default;
const getOptionKey = Select.props.getOptionKey.default
it('can serialize strings to a key', () => {
expect(getOptionKey('vue')).toBe('vue');
});
expect(getOptionKey('vue')).toBe('vue')
})
it('can serialize integers to a key', () => {
expect(getOptionKey(1)).toBe(1);
});
expect(getOptionKey(1)).toBe(1)
})
it('can serialize objects to a key', () => {
expect(getOptionKey({label: 'vue'})).toBe('{"label":"vue"}');
});
expect(getOptionKey({ label: 'vue' })).toBe('{"label":"vue"}')
})
it('will use an ID property if the object contains one', () => {
expect(getOptionKey({id: 1})).toBe(1);
expect(getOptionKey({id: 'one'})).toBe('one');
expect(getOptionKey({id: {im: 'a nested object'}}))
.toEqual({im: 'a nested object'});
});
});
expect(getOptionKey({ id: 1 })).toBe(1)
expect(getOptionKey({ id: 'one' })).toBe('one')
expect(getOptionKey({ id: { im: 'a nested object' } })).toEqual({
im: 'a nested object',
})
})
})
+113 -91
View File
@@ -1,141 +1,163 @@
import { mount, shallowMount } from '@vue/test-utils';
import VueSelect from "../../src/components/Select";
import { mountDefault } from '../helpers';
import { mount, shallowMount } from '@vue/test-utils'
import VueSelect from '../../src/components/Select'
import { mountDefault } from '../helpers'
describe("Reset on options change", () => {
it("should not reset the selected value by default when the options property changes", () => {
describe('Reset on options change', () => {
it('should not reset the selected value by default when the options property changes', () => {
const Select = shallowMount(VueSelect, {
propsData: { options: ["one"] }
});
propsData: { options: ['one'] },
})
Select.vm.$data._value = 'one';
Select.vm.$data._value = 'one'
Select.setProps({options: ["four", "five", "six"]});
expect(Select.vm.selectedValue).toEqual(["one"]);
});
Select.setProps({ options: ['four', 'five', 'six'] })
expect(Select.vm.selectedValue).toEqual(['one'])
})
describe('resetOnOptionsChange as a function', () => {
it('will yell at you if resetOnOptionsChange is not a function or boolean', () => {
const spy = jest.spyOn(console, 'error').mockImplementation(() => {});
const spy = jest.spyOn(console, 'error').mockImplementation(() => {})
mountDefault({resetOnOptionsChange: 1});
expect(spy.mock.calls[0][0]).toContain('Invalid prop: custom validator check failed for prop "resetOnOptionsChange"')
mountDefault({ resetOnOptionsChange: 1 })
expect(spy.mock.calls[0][0]).toContain(
'Invalid prop: custom validator check failed for prop "resetOnOptionsChange"'
)
mountDefault({resetOnOptionsChange: 'one'});
expect(spy.mock.calls[1][0]).toContain('Invalid prop: custom validator check failed for prop "resetOnOptionsChange"')
mountDefault({ resetOnOptionsChange: 'one' })
expect(spy.mock.calls[1][0]).toContain(
'Invalid prop: custom validator check failed for prop "resetOnOptionsChange"'
)
mountDefault({resetOnOptionsChange: []});
expect(spy.mock.calls[2][0]).toContain('Invalid prop: custom validator check failed for prop "resetOnOptionsChange"')
mountDefault({ resetOnOptionsChange: [] })
expect(spy.mock.calls[2][0]).toContain(
'Invalid prop: custom validator check failed for prop "resetOnOptionsChange"'
)
mountDefault({resetOnOptionsChange: {}});
expect(spy.mock.calls[3][0]).toContain('Invalid prop: custom validator check failed for prop "resetOnOptionsChange"')
});
mountDefault({ resetOnOptionsChange: {} })
expect(spy.mock.calls[3][0]).toContain(
'Invalid prop: custom validator check failed for prop "resetOnOptionsChange"'
)
})
it('should receive the new options, old options, and current value', async () => {
let resetOnOptionsChange = jest.fn(option => option);
const Select = mountDefault(
{resetOnOptionsChange, options: ['bear'], value: 'selected'},
);
let resetOnOptionsChange = jest.fn((option) => option)
const Select = mountDefault({
resetOnOptionsChange,
options: ['bear'],
value: 'selected',
})
Select.setProps({options: ['lake', 'kite']});
await Select.vm.$nextTick();
Select.setProps({ options: ['lake', 'kite'] })
await Select.vm.$nextTick()
expect(resetOnOptionsChange).toHaveBeenCalledTimes(1);
expect(resetOnOptionsChange)
.toHaveBeenCalledWith(['lake', 'kite'], ['bear'], ['selected']);
});
expect(resetOnOptionsChange).toHaveBeenCalledTimes(1)
expect(resetOnOptionsChange).toHaveBeenCalledWith(
['lake', 'kite'],
['bear'],
['selected']
)
})
it('should allow resetOnOptionsChange to be a function that returns true', async () => {
let resetOnOptionsChange = () => true;
let resetOnOptionsChange = () => true
const Select = shallowMount(VueSelect, {
propsData: {resetOnOptionsChange, options: ['one'], value: 'one'},
});
const spy = jest.spyOn(Select.vm, 'clearSelection');
propsData: { resetOnOptionsChange, options: ['one'], value: 'one' },
})
const spy = jest.spyOn(Select.vm, 'clearSelection')
Select.setProps({options: ['one', 'two']});
await Select.vm.$nextTick();
Select.setProps({ options: ['one', 'two'] })
await Select.vm.$nextTick()
expect(spy).toHaveBeenCalledTimes(1);
});
expect(spy).toHaveBeenCalledTimes(1)
})
it('should allow resetOnOptionsChange to be a function that returns false', () => {
let resetOnOptionsChange = () => false;
let resetOnOptionsChange = () => false
const Select = shallowMount(VueSelect, {
propsData: {resetOnOptionsChange, options: ['one'], value: 'one'},
});
const spy = jest.spyOn(Select.vm, 'clearSelection');
propsData: { resetOnOptionsChange, options: ['one'], value: 'one' },
})
const spy = jest.spyOn(Select.vm, 'clearSelection')
Select.setProps({options: ['one', 'two']});
expect(spy).not.toHaveBeenCalled();
});
Select.setProps({ options: ['one', 'two'] })
expect(spy).not.toHaveBeenCalled()
})
it('should reset the options if the selectedValue does not exist in the new options', async () => {
let resetOnOptionsChange = (options, old, val) => val.some(val => options.includes(val));
let resetOnOptionsChange = (options, old, val) =>
val.some((val) => options.includes(val))
const Select = shallowMount(VueSelect, {
propsData: {resetOnOptionsChange, options: ['one'], value: 'one'},
});
const spy = jest.spyOn(Select.vm, 'clearSelection');
propsData: { resetOnOptionsChange, options: ['one'], value: 'one' },
})
const spy = jest.spyOn(Select.vm, 'clearSelection')
Select.setProps({options: ['one', 'two']});
await Select.vm.$nextTick();
Select.setProps({ options: ['one', 'two'] })
await Select.vm.$nextTick()
expect(Select.vm.selectedValue).toEqual(['one']);
expect(Select.vm.selectedValue).toEqual(['one'])
Select.setProps({options: ['two']});
await Select.vm.$nextTick();
Select.setProps({ options: ['two'] })
await Select.vm.$nextTick()
expect(spy).toHaveBeenCalledTimes(1);
});
});
expect(spy).toHaveBeenCalledTimes(1)
})
})
it("should reset the selected value when the options property changes", async () => {
it('should reset the selected value when the options property changes', async () => {
const Select = shallowMount(VueSelect, {
propsData: { resetOnOptionsChange: true, options: ["one"] }
});
propsData: { resetOnOptionsChange: true, options: ['one'] },
})
Select.vm.$data._value = 'one';
Select.vm.$data._value = 'one'
Select.setProps({options: ["four", "five", "six"]});
await Select.vm.$nextTick();
Select.setProps({ options: ['four', 'five', 'six'] })
await Select.vm.$nextTick()
expect(Select.vm.selectedValue).toEqual([]);
});
expect(Select.vm.selectedValue).toEqual([])
})
it("should return correct selected value when the options property changes and a new option matches", async () => {
it('should return correct selected value when the options property changes and a new option matches', async () => {
const Select = shallowMount(VueSelect, {
propsData: { value: "one", options: [], reduce(option) { return option.value } }
});
propsData: {
value: 'one',
options: [],
reduce(option) {
return option.value
},
},
})
Select.setProps({options: [{ label: "oneLabel", value: "one" }]});
await Select.vm.$nextTick();
Select.setProps({ options: [{ label: 'oneLabel', value: 'one' }] })
await Select.vm.$nextTick()
expect(Select.vm.selectedValue).toEqual([{ label: "oneLabel", value: "one" }]);
});
expect(Select.vm.selectedValue).toEqual([
{ label: 'oneLabel', value: 'one' },
])
})
it('clearSearchOnBlur returns false when multiple is true', () => {
const Select = mountDefault({});
let clearSearchOnBlur = jest.spyOn(Select.vm, 'clearSearchOnBlur');
Select.find({ref: 'search'}).trigger('click');
Select.setData({search: 'one'});
Select.find({ref: 'search'}).trigger('blur');
const Select = mountDefault({})
let clearSearchOnBlur = jest.spyOn(Select.vm, 'clearSearchOnBlur')
Select.find({ ref: 'search' }).trigger('click')
Select.setData({ search: 'one' })
Select.find({ ref: 'search' }).trigger('blur')
expect(clearSearchOnBlur).toHaveBeenCalledTimes(1);
expect(clearSearchOnBlur).toHaveBeenCalledTimes(1)
expect(clearSearchOnBlur).toHaveBeenCalledWith({
clearSearchOnSelect: true,
multiple: false,
});
expect(Select.vm.search).toBe('');
});
})
expect(Select.vm.search).toBe('')
})
it('clearSearchOnBlur accepts a function', () => {
let clearSearchOnBlur = jest.fn(() => false);
const Select = mountDefault({clearSearchOnBlur});
let clearSearchOnBlur = jest.fn(() => false)
const Select = mountDefault({ clearSearchOnBlur })
Select.find({ref: 'search'}).trigger('click');
Select.setData({search: 'one'});
Select.find({ref: 'search'}).trigger('blur');
Select.find({ ref: 'search' }).trigger('click')
Select.setData({ search: 'one' })
Select.find({ ref: 'search' }).trigger('blur')
expect(clearSearchOnBlur).toHaveBeenCalledTimes(1);
expect(Select.vm.search).toBe('one');
});
});
expect(clearSearchOnBlur).toHaveBeenCalledTimes(1)
expect(Select.vm.search).toBe('one')
})
})
+185 -171
View File
@@ -1,127 +1,133 @@
import { mount, shallowMount } from "@vue/test-utils";
import VueSelect from "../../src/components/Select";
import { mount, shallowMount } from '@vue/test-utils'
import VueSelect from '../../src/components/Select'
describe("When reduce prop is defined", () => {
it("can accept an array of objects and pre-selected value (single)", () => {
describe('When reduce prop is defined', () => {
it('can accept an array of objects and pre-selected value (single)', () => {
const Select = shallowMount(VueSelect, {
propsData: {
reduce: option => option.value,
value: "foo",
options: [{ label: "This is Foo", value: "foo" }]
}
});
expect(Select.vm.selectedValue).toEqual([{ label: "This is Foo", value: "foo" }]);
});
reduce: (option) => option.value,
value: 'foo',
options: [{ label: 'This is Foo', value: 'foo' }],
},
})
expect(Select.vm.selectedValue).toEqual([
{ label: 'This is Foo', value: 'foo' },
])
})
it("can determine if an object is pre-selected", () => {
it('can determine if an object is pre-selected', () => {
const Select = shallowMount(VueSelect, {
propsData: {
reduce: option => option.id,
value: "foo",
reduce: (option) => option.id,
value: 'foo',
options: [
{
id: "foo",
label: "This is Foo"
}
]
}
});
id: 'foo',
label: 'This is Foo',
},
],
},
})
expect(
Select.vm.isOptionSelected({
id: "foo",
label: "This is Foo"
id: 'foo',
label: 'This is Foo',
})
).toEqual(true);
});
).toEqual(true)
})
it('can determine if an object is selected after its been chosen', () => {
const Select = shallowMount(VueSelect, {
propsData: {
reduce: option => option.id,
options: [{id: 'foo', label: 'FooBar'}],
},
});
const Select = shallowMount(VueSelect, {
propsData: {
reduce: (option) => option.id,
options: [{ id: 'foo', label: 'FooBar' }],
},
})
Select.vm.select({id: 'foo', label: 'FooBar'});
Select.vm.select({ id: 'foo', label: 'FooBar' })
expect(Select.vm.isOptionSelected({
expect(
Select.vm.isOptionSelected({
id: 'foo',
label: 'This is FooBar',
})).toEqual(true);
});
})
).toEqual(true)
})
it("can accept an array of objects and pre-selected values (multiple)", () => {
it('can accept an array of objects and pre-selected values (multiple)', () => {
const Select = shallowMount(VueSelect, {
propsData: {
multiple: true,
reduce: option => option.value,
value: ["foo"],
reduce: (option) => option.value,
value: ['foo'],
options: [
{ label: "This is Foo", value: "foo" },
{ label: "This is Bar", value: "bar" }
]
}
});
{ label: 'This is Foo', value: 'foo' },
{ label: 'This is Bar', value: 'bar' },
],
},
})
expect(Select.vm.selectedValue).toEqual([{ label: "This is Foo", value: "foo" }]);
});
expect(Select.vm.selectedValue).toEqual([
{ label: 'This is Foo', value: 'foo' },
])
})
it("can deselect a pre-selected object", () => {
it('can deselect a pre-selected object', () => {
const Select = shallowMount(VueSelect, {
propsData: {
multiple: true,
reduce: option => option.value,
reduce: (option) => option.value,
options: [
{ label: "This is Foo", value: "foo" },
{ label: "This is Bar", value: "bar" }
]
}
});
{ label: 'This is Foo', value: 'foo' },
{ label: 'This is Bar', value: 'bar' },
],
},
})
Select.vm.$data._value = ['foo', 'bar'];
Select.vm.$data._value = ['foo', 'bar']
Select.vm.deselect("foo");
expect(Select.vm.selectedValue).toEqual(["bar"]);
});
Select.vm.deselect('foo')
expect(Select.vm.selectedValue).toEqual(['bar'])
})
it("can deselect an option when multiple is false", () => {
it('can deselect an option when multiple is false', () => {
const Select = shallowMount(VueSelect, {
propsData: {
reduce: option => option.value,
reduce: (option) => option.value,
options: [
{ label: "This is Foo", value: "foo" },
{ label: "This is Bar", value: "bar" }
]
}
});
{ label: 'This is Foo', value: 'foo' },
{ label: 'This is Bar', value: 'bar' },
],
},
})
Select.vm.deselect("foo");
expect(Select.vm.selectedValue).toEqual([]);
});
Select.vm.deselect('foo')
expect(Select.vm.selectedValue).toEqual([])
})
it("can use v-model syntax for a two way binding to a parent component", async () => {
it('can use v-model syntax for a two way binding to a parent component', async () => {
const Parent = mount({
data: () => ({
reduce: option => option.value,
current: "foo",
reduce: (option) => option.value,
current: 'foo',
options: [
{ label: "This is Foo", value: "foo" },
{ label: "This is Bar", value: "bar" },
{ label: "This is Baz", value: "baz" }
]
{ label: 'This is Foo', value: 'foo' },
{ label: 'This is Bar', value: 'bar' },
{ label: 'This is Baz', value: 'baz' },
],
}),
components: { "v-select": VueSelect },
components: { 'v-select': VueSelect },
computed: {
value: {
get() {
return this.current;
return this.current
},
set(value) {
if (value == 'baz') return;
this.current = value;
}
}
if (value == 'baz') return
this.current = value
},
},
},
template: `
<v-select
@@ -129,133 +135,141 @@ describe("When reduce prop is defined", () => {
:reduce="option => option.value"
:options="options"
/>
`
});
const Select = Parent.vm.$children[0];
`,
})
const Select = Parent.vm.$children[0]
expect(Select.value).toEqual("foo");
expect(Select.selectedValue).toEqual([{ label: "This is Foo", value: "foo" }]);
expect(Select.value).toEqual('foo')
expect(Select.selectedValue).toEqual([
{ label: 'This is Foo', value: 'foo' },
])
Select.select({ label: "This is Bar", value: "bar" });
await Select.$nextTick();
expect(Parent.vm.value).toEqual("bar");
expect(Select.selectedValue).toEqual([{ label: "This is Bar", value: "bar" }]);
Select.select({ label: 'This is Bar', value: 'bar' })
await Select.$nextTick()
expect(Parent.vm.value).toEqual('bar')
expect(Select.selectedValue).toEqual([
{ label: 'This is Bar', value: 'bar' },
])
// Parent denies to set baz
Select.select({ label: "This is Baz", value: "baz" });
await Select.$nextTick();
expect(Select.selectedValue).toEqual([{ label: "This is Bar", value: "bar" }]);
expect(Parent.vm.value).toEqual('bar');
});
Select.select({ label: 'This is Baz', value: 'baz' })
await Select.$nextTick()
expect(Select.selectedValue).toEqual([
{ label: 'This is Bar', value: 'bar' },
])
expect(Parent.vm.value).toEqual('bar')
})
it("can generate labels using a custom label key", () => {
it('can generate labels using a custom label key', () => {
const Select = shallowMount(VueSelect, {
propsData: {
multiple: true,
reduce: option => option.value,
value: ["CA"],
label: "name",
options: [{ value: "CA", name: "Canada" }, { value: "US", name: "United States" }]
}
});
reduce: (option) => option.value,
value: ['CA'],
label: 'name',
options: [
{ value: 'CA', name: 'Canada' },
{ value: 'US', name: 'United States' },
],
},
})
expect(Select.find(".vs__selected").text()).toContain("Canada");
});
expect(Select.find('.vs__selected').text()).toContain('Canada')
})
it("can find the original option within this.options", () => {
const optionToFind = { id: 1, label: "Foo" };
it('can find the original option within this.options', () => {
const optionToFind = { id: 1, label: 'Foo' }
const Select = shallowMount(VueSelect, {
propsData: {
reduce: option => option.id,
options: [optionToFind, { id: 2, label: "Bar" }]
}
});
reduce: (option) => option.id,
options: [optionToFind, { id: 2, label: 'Bar' }],
},
})
expect(Select.vm.findOptionFromReducedValue(1)).toEqual(optionToFind);
expect(Select.vm.findOptionFromReducedValue(1)).toEqual(optionToFind)
expect(Select.vm.findOptionFromReducedValue(optionToFind)).toEqual(
optionToFind
);
});
)
})
it('can work with falsey values', () => {
const option = {value: 0, label: 'No'};
const option = { value: 0, label: 'No' }
const Select = shallowMount(VueSelect, {
propsData: {
reduce: option => option.value,
options: [option, {value: 1, label: 'Yes'}],
reduce: (option) => option.value,
options: [option, { value: 1, label: 'Yes' }],
value: 0,
},
});
})
expect(Select.vm.findOptionFromReducedValue(option)).toEqual(option);
expect(Select.vm.selectedValue).toEqual([option]);
});
expect(Select.vm.findOptionFromReducedValue(option)).toEqual(option)
expect(Select.vm.selectedValue).toEqual([option])
})
it('works with null values', () => {
const option = {value: null, label: 'No'};
const option = { value: null, label: 'No' }
const Select = shallowMount(VueSelect, {
propsData: {
reduce: option => option.value,
options: [option, {value: 1, label: 'Yes'}],
reduce: (option) => option.value,
options: [option, { value: 1, label: 'Yes' }],
value: null,
},
});
})
expect(Select.vm.findOptionFromReducedValue(option)).toEqual(option);
expect(Select.vm.selectedValue).toEqual([option]);
});
expect(Select.vm.findOptionFromReducedValue(option)).toEqual(option)
expect(Select.vm.selectedValue).toEqual([option])
})
describe("And when a reduced option is a nested object", () => {
it("can determine if an object is pre-selected", () => {
const nestedOption = { value: { nested: true }, label: "foo" };
describe('And when a reduced option is a nested object', () => {
it('can determine if an object is pre-selected', () => {
const nestedOption = { value: { nested: true }, label: 'foo' }
const Select = shallowMount(VueSelect, {
propsData: {
reduce: option => option.value,
reduce: (option) => option.value,
value: {
nested: true
nested: true,
},
options: [nestedOption]
}
});
options: [nestedOption],
},
})
expect(Select.vm.selectedValue).toEqual([nestedOption]);
});
expect(Select.vm.selectedValue).toEqual([nestedOption])
})
it("can determine if an object is selected after it is chosen", () => {
const nestedOption = { value: { nested: true }, label: "foo" };
it('can determine if an object is selected after it is chosen', () => {
const nestedOption = { value: { nested: true }, label: 'foo' }
const Select = shallowMount(VueSelect, {
propsData: {
reduce: option => option.value,
options: [nestedOption]
}
});
reduce: (option) => option.value,
options: [nestedOption],
},
})
Select.vm.select(nestedOption);
expect(Select.vm.isOptionSelected(nestedOption)).toEqual(true);
});
Select.vm.select(nestedOption)
expect(Select.vm.isOptionSelected(nestedOption)).toEqual(true)
})
})
});
it("reacts correctly when value property changes", async () => {
const optionToChangeTo = { id: 1, label: "Foo" };
it('reacts correctly when value property changes', async () => {
const optionToChangeTo = { id: 1, label: 'Foo' }
const Select = shallowMount(VueSelect, {
propsData: {
value: 2,
reduce: option => option.id,
options: [optionToChangeTo, { id: 2, label: "Bar" }]
}
});
reduce: (option) => option.id,
options: [optionToChangeTo, { id: 2, label: 'Bar' }],
},
})
Select.setProps({ value: optionToChangeTo.id });
await Select.vm.$nextTick();
Select.setProps({ value: optionToChangeTo.id })
await Select.vm.$nextTick()
expect(Select.vm.selectedValue).toEqual([optionToChangeTo]);
});
expect(Select.vm.selectedValue).toEqual([optionToChangeTo])
})
describe('Reducing Tags', () => {
it('tracks values that have been created by the user', async () => {
const Parent = mount({
data: () => ({selected: null, options: []}),
data: () => ({ selected: null, options: [] }),
template: `
<v-select
v-model="selected"
@@ -265,24 +279,24 @@ describe("When reduce prop is defined", () => {
:create-option="label => ({ label, value: -1 })"
/>
`,
components: {'v-select': VueSelect},
});
const Select = Parent.vm.$children[0];
components: { 'v-select': VueSelect },
})
const Select = Parent.vm.$children[0]
// When
Select.$refs.search.focus();
await Select.$nextTick();
Select.$refs.search.focus()
await Select.$nextTick()
Select.search = 'hello';
await Select.$nextTick();
Select.search = 'hello'
await Select.$nextTick()
Select.typeAheadSelect();
await Select.$nextTick();
Select.typeAheadSelect()
await Select.$nextTick()
// Then
expect(Select.selectedValue).toEqual([{label: 'hello', value: -1}]);
expect(Select.$refs.selectedOptions.textContent.trim()).toEqual('hello');
expect(Parent.vm.selected).toEqual(-1);
});
});
});
expect(Select.selectedValue).toEqual([{ label: 'hello', value: -1 }])
expect(Select.$refs.selectedOptions.textContent.trim()).toEqual('hello')
expect(Parent.vm.selected).toEqual(-1)
})
})
})
+40 -40
View File
@@ -1,59 +1,59 @@
import { selectWithProps } from "../helpers";
import { selectWithProps } from '../helpers'
describe("Selectable prop", () => {
it("should select selectable option if clicked", async () => {
describe('Selectable prop', () => {
it('should select selectable option if clicked', async () => {
const Select = selectWithProps({
options: ["one", "two", "three"],
selectable: (option) => option === "one"
});
options: ['one', 'two', 'three'],
selectable: (option) => option === 'one',
})
Select.vm.$data.open = true;
await Select.vm.$nextTick();
Select.vm.$data.open = true
await Select.vm.$nextTick()
Select.find(".vs__dropdown-menu li:first-child").trigger("mousedown");
Select.find('.vs__dropdown-menu li:first-child').trigger('mousedown')
await Select.vm.$nextTick();
expect(Select.vm.selectedValue).toEqual(["one"]);
await Select.vm.$nextTick()
expect(Select.vm.selectedValue).toEqual(['one'])
})
it("should not select not selectable option if clicked", async () => {
it('should not select not selectable option if clicked', async () => {
const Select = selectWithProps({
options: ["one", "two", "three"],
selectable: (option) => option === "one"
});
options: ['one', 'two', 'three'],
selectable: (option) => option === 'one',
})
Select.vm.$data.open = true;
await Select.vm.$nextTick();
Select.vm.$data.open = true
await Select.vm.$nextTick()
Select.find(".vs__dropdown-menu li:last-child").trigger("mousedown");
await Select.vm.$nextTick();
Select.find('.vs__dropdown-menu li:last-child').trigger('mousedown')
await Select.vm.$nextTick()
expect(Select.vm.selectedValue).toEqual([]);
});
it("should skip non-selectable option on down arrow keyDown", () => {
const Select = selectWithProps({
options: ["one", "two", "three"],
selectable: (option) => option !== "two"
});
Select.vm.typeAheadPointer = 1;
Select.find({ ref: "search" }).trigger("keydown.down");
expect(Select.vm.typeAheadPointer).toEqual(2);
expect(Select.vm.selectedValue).toEqual([])
})
it("should skip non-selectable option on up arrow keyDown", () => {
it('should skip non-selectable option on down arrow keyDown', () => {
const Select = selectWithProps({
options: ["one", "two", "three"],
selectable: (option) => option !== "two"
});
options: ['one', 'two', 'three'],
selectable: (option) => option !== 'two',
})
Select.vm.typeAheadPointer = 2;
Select.vm.typeAheadPointer = 1
Select.find({ ref: "search" }).trigger("keydown.up");
Select.find({ ref: 'search' }).trigger('keydown.down')
expect(Select.vm.typeAheadPointer).toEqual(0);
expect(Select.vm.typeAheadPointer).toEqual(2)
})
it('should skip non-selectable option on up arrow keyDown', () => {
const Select = selectWithProps({
options: ['one', 'two', 'three'],
selectable: (option) => option !== 'two',
})
Select.vm.typeAheadPointer = 2
Select.find({ ref: 'search' }).trigger('keydown.up')
expect(Select.vm.typeAheadPointer).toEqual(0)
})
})
+224 -205
View File
@@ -1,303 +1,322 @@
import { mount, shallowMount } from "@vue/test-utils";
import VueSelect from "../../src/components/Select.vue";
import { mountDefault } from '../helpers';
import { mount, shallowMount } from '@vue/test-utils'
import VueSelect from '../../src/components/Select.vue'
import { mountDefault } from '../helpers'
describe("VS - Selecting Values", () => {
let defaultProps;
describe('VS - Selecting Values', () => {
let defaultProps
beforeEach(() => {
defaultProps = {
value: "one",
options: ["one", "two", "three"]
};
});
value: 'one',
options: ['one', 'two', 'three'],
}
})
it("can accept an array with pre-selected values", () => {
it('can accept an array with pre-selected values', () => {
const Select = shallowMount(VueSelect, {
propsData: defaultProps
});
expect(Select.selectedValue).toEqual(Select.value);
});
propsData: defaultProps,
})
expect(Select.selectedValue).toEqual(Select.value)
})
it("can accept an array of objects and pre-selected value (single)", () => {
it('can accept an array of objects and pre-selected value (single)', () => {
const Select = shallowMount(VueSelect, {
propsData: {
value: { label: "This is Foo", value: "foo" },
value: { label: 'This is Foo', value: 'foo' },
options: [
{ label: "This is Foo", value: "foo" },
{ label: "This is Bar", value: "bar" }
]
}
});
expect(Select.selectedValue).toEqual(Select.value);
});
{ label: 'This is Foo', value: 'foo' },
{ label: 'This is Bar', value: 'bar' },
],
},
})
expect(Select.selectedValue).toEqual(Select.value)
})
it("can accept an array of objects and pre-selected values (multiple)", () => {
it('can accept an array of objects and pre-selected values (multiple)', () => {
const Select = shallowMount(VueSelect, {
propsData: {
value: [
{ label: "This is Foo", value: "foo" },
{ label: "This is Bar", value: "bar" }
{ label: 'This is Foo', value: 'foo' },
{ label: 'This is Bar', value: 'bar' },
],
options: [
{ label: "This is Foo", value: "foo" },
{ label: "This is Bar", value: "bar" }
]
{ label: 'This is Foo', value: 'foo' },
{ label: 'This is Bar', value: 'bar' },
],
},
multiple: true
});
multiple: true,
})
expect(Select.selectedValue).toEqual(Select.value);
});
expect(Select.selectedValue).toEqual(Select.value)
})
it("can select an option on tab", () => {
it('can select an option on tab', () => {
const Select = shallowMount(VueSelect, {
propsData: {
selectOnTab: true
}
});
selectOnTab: true,
},
})
const spy = jest.spyOn(Select.vm, "typeAheadSelect");
const spy = jest.spyOn(Select.vm, 'typeAheadSelect')
Select.find({ ref: "search" }).trigger("keydown.tab");
Select.find({ ref: 'search' }).trigger('keydown.tab')
expect(spy).toHaveBeenCalledWith();
});
expect(spy).toHaveBeenCalledWith()
})
it("can deselect a pre-selected object", () => {
it('can deselect a pre-selected object', () => {
const Select = shallowMount(VueSelect, {
propsData: {
multiple: true,
options: [
{ label: "This is Foo", value: "foo" },
{ label: "This is Bar", value: "bar" }
]
}
});
{ label: 'This is Foo', value: 'foo' },
{ label: 'This is Bar', value: 'bar' },
],
},
})
Select.vm.$data._value = [
{ label: "This is Foo", value: "foo" },
{ label: "This is Bar", value: "bar" }
];
{ label: 'This is Foo', value: 'foo' },
{ label: 'This is Bar', value: 'bar' },
]
Select.vm.deselect({ label: "This is Foo", value: "foo" });
expect(Select.vm.selectedValue).toEqual([{ label: "This is Bar", value: "bar" }]);
});
Select.vm.deselect({ label: 'This is Foo', value: 'foo' })
expect(Select.vm.selectedValue).toEqual([
{ label: 'This is Bar', value: 'bar' },
])
})
it("can deselect a pre-selected string", () => {
it('can deselect a pre-selected string', () => {
const Select = shallowMount(VueSelect, {
propsData: {
multiple: true,
options: ["foo", "bar"]
}
});
options: ['foo', 'bar'],
},
})
Select.vm.$data._value = "foo";
Select.vm.$data._value = 'foo'
Select.vm.deselect("foo");
expect(Select.vm.selectedValue).toEqual([]);
});
Select.vm.deselect('foo')
expect(Select.vm.selectedValue).toEqual([])
})
it("can deselect an option when multiple is false", () => {
const Select = shallowMount(VueSelect);
it('can deselect an option when multiple is false', () => {
const Select = shallowMount(VueSelect)
Select.vm.$data._value = "foo";
Select.vm.$data._value = 'foo'
Select.vm.deselect("foo");
expect(Select.vm.selectedValue).toEqual([]);
});
Select.vm.deselect('foo')
expect(Select.vm.selectedValue).toEqual([])
})
it("can determine if the value prop is empty", () => {
it('can determine if the value prop is empty', () => {
const Select = shallowMount(VueSelect, {
propsData: {
options: ["one", "two", "three"]
}
});
options: ['one', 'two', 'three'],
},
})
const select = Select.vm;
expect(select.isValueEmpty).toEqual(true);
const select = Select.vm
expect(select.isValueEmpty).toEqual(true)
select.select(["one"]);
expect(select.isValueEmpty).toEqual(false);
select.select(['one'])
expect(select.isValueEmpty).toEqual(false)
select.select("one");
expect(select.isValueEmpty).toEqual(false);
select.select('one')
expect(select.isValueEmpty).toEqual(false)
select.select({ label: "foo", value: "foo" });
expect(select.isValueEmpty).toEqual(false);
select.select({ label: 'foo', value: 'foo' })
expect(select.isValueEmpty).toEqual(false)
select.select("");
expect(select.isValueEmpty).toEqual(true);
select.select('')
expect(select.isValueEmpty).toEqual(true)
select.select(null);
expect(select.isValueEmpty).toEqual(true);
});
select.select(null)
expect(select.isValueEmpty).toEqual(true)
})
it("should reset the selected values when the multiple property changes", () => {
it('should reset the selected values when the multiple property changes', () => {
const Select = shallowMount(VueSelect, {
propsData: {
multiple: true,
options: ["one", "two", "three"]
}
});
options: ['one', 'two', 'three'],
},
})
Select.setProps({ multiple: false });
expect(Select.vm.selectedValue).toEqual([]);
Select.setProps({ multiple: false })
expect(Select.vm.selectedValue).toEqual([])
Select.setProps({ multiple: true });
expect(Select.vm.selectedValue).toEqual([]);
});
Select.setProps({ multiple: true })
expect(Select.vm.selectedValue).toEqual([])
})
it("can retain values present in a new array of options", () => {
it('can retain values present in a new array of options', () => {
const Select = shallowMount(VueSelect, {
propsData: {
value: ["one"],
options: ["one", "two", "three"]
}
});
value: ['one'],
options: ['one', 'two', 'three'],
},
})
Select.setProps({ options: ["one", "five", "six"] });
expect(Select.vm.selectedValue).toEqual(["one"]);
});
Select.setProps({ options: ['one', 'five', 'six'] })
expect(Select.vm.selectedValue).toEqual(['one'])
})
it("can determine if an object is already selected", () => {
it('can determine if an object is already selected', () => {
const Select = shallowMount(VueSelect, {
propsData: {
value: [{ label: "one" }],
options: [{ label: "one" }]
}
});
value: [{ label: 'one' }],
options: [{ label: 'one' }],
},
})
expect(Select.vm.isOptionSelected({ label: "one" })).toEqual(true);
});
expect(Select.vm.isOptionSelected({ label: 'one' })).toEqual(true)
})
it("can use v-model syntax for a two way binding to a parent component", () => {
it('can use v-model syntax for a two way binding to a parent component', () => {
const Parent = mount({
data: () => ({ value: "foo", options: ["foo", "bar", "baz"] }),
data: () => ({ value: 'foo', options: ['foo', 'bar', 'baz'] }),
template: `<div><v-select :options="options" v-model="value" /></div>`,
components: { "v-select": VueSelect }
});
const Select = Parent.vm.$children[0];
components: { 'v-select': VueSelect },
})
const Select = Parent.vm.$children[0]
expect(Select.value).toEqual("foo");
expect(Select.selectedValue).toEqual(["foo"]);
expect(Select.value).toEqual('foo')
expect(Select.selectedValue).toEqual(['foo'])
Select.select("bar");
expect(Parent.vm.value).toEqual("bar");
});
Select.select('bar')
expect(Parent.vm.value).toEqual('bar')
})
it("can check if a string value is selected when the value is an object and multiple is true", () => {
it('can check if a string value is selected when the value is an object and multiple is true', () => {
const Select = shallowMount(VueSelect, {
propsData: {
multiple: true,
value: [{ label: "foo", value: "bar" }]
}
});
expect(Select.vm.isOptionSelected({ label: "foo", value: "bar" })).toEqual(true);
});
value: [{ label: 'foo', value: 'bar' }],
},
})
expect(Select.vm.isOptionSelected({ label: 'foo', value: 'bar' })).toEqual(
true
)
})
it('can select two options with the same label', () => {
const options = [{label: 'one', id: 1}, {label: 'one', id: 2}];
const Select = mountDefault({options, multiple: true});
const options = [
{ label: 'one', id: 1 },
{ label: 'one', id: 2 },
]
const Select = mountDefault({ options, multiple: true })
Select.vm.select({label: 'one', id: 1});
Select.vm.select({label: 'one', id: 2});
Select.vm.select({ label: 'one', id: 1 })
Select.vm.select({ label: 'one', id: 2 })
expect(Select.vm.selectedValue).toEqual(options);
});
expect(Select.vm.selectedValue).toEqual(options)
})
describe("input Event", () => {
it("will trigger the input event when the selection changes", () => {
const Select = shallowMount(VueSelect);
Select.vm.select("bar");
expect(Select.emitted("input")[0]).toEqual(["bar"]);
});
describe('input Event', () => {
it('will trigger the input event when the selection changes', () => {
const Select = shallowMount(VueSelect)
Select.vm.select('bar')
expect(Select.emitted('input')[0]).toEqual(['bar'])
})
it("will trigger the input event when the selection changes and multiple is true", () => {
it('will trigger the input event when the selection changes and multiple is true', () => {
const Select = shallowMount(VueSelect, {
propsData: { multiple: true, value: ["foo"], options: ["foo", "bar"] }
});
Select.vm.select("bar");
expect(Select.emitted("input")[0]).toEqual([["foo", "bar"]]);
});
propsData: { multiple: true, value: ['foo'], options: ['foo', 'bar'] },
})
Select.vm.select('bar')
expect(Select.emitted('input')[0]).toEqual([['foo', 'bar']])
})
it("will not trigger the input event when multiple is true and selection is repeated", () => {
it('will not trigger the input event when multiple is true and selection is repeated', () => {
const Select = shallowMount(VueSelect, {
propsData: { multiple: true, value: ["foo ", "bar"], options: ["foo", "bar", "baz"] }
});
propsData: {
multiple: true,
value: ['foo ', 'bar'],
options: ['foo', 'bar', 'baz'],
},
})
Select.vm.select("bar");
expect(Select.emitted("input")).toBeFalsy();
});
});
Select.vm.select('bar')
expect(Select.emitted('input')).toBeFalsy()
})
})
describe("option:selecting Event", () => {
it("will trigger the option:selecting event when an option is selected", () => {
const Select = shallowMount(VueSelect);
Select.vm.select("bar");
expect(Select.emitted("option:selecting")[0]).toEqual(["bar"]);
});
describe('option:selecting Event', () => {
it('will trigger the option:selecting event when an option is selected', () => {
const Select = shallowMount(VueSelect)
Select.vm.select('bar')
expect(Select.emitted('option:selecting')[0]).toEqual(['bar'])
})
it("will trigger the option:selecting event regardless of current value", () => {
it('will trigger the option:selecting event regardless of current value', () => {
const Select = shallowMount(VueSelect, {
propsData: { value: ["foo"], options: ["foo", "bar"] }
});
Select.vm.select("foo");
Select.vm.select("bar");
expect(Select.emitted("option:selecting")).toEqual([["foo"], ["bar"]]);
});
propsData: { value: ['foo'], options: ['foo', 'bar'] },
})
Select.vm.select('foo')
Select.vm.select('bar')
expect(Select.emitted('option:selecting')).toEqual([['foo'], ['bar']])
})
it("will trigger the option:selecting event with current selected item when multiple is true", () => {
it('will trigger the option:selecting event with current selected item when multiple is true', () => {
const Select = shallowMount(VueSelect, {
propsData: { multiple: true, value: ["foo"], options: ["foo", "bar"] }
});
Select.vm.select("bar");
expect(Select.emitted("option:selecting")[0]).toEqual(["bar"]);
});
propsData: { multiple: true, value: ['foo'], options: ['foo', 'bar'] },
})
Select.vm.select('bar')
expect(Select.emitted('option:selecting')[0]).toEqual(['bar'])
})
it("will trigger the option:selecting event regardless of current value when multiple is true", () => {
it('will trigger the option:selecting event regardless of current value when multiple is true', () => {
const Select = shallowMount(VueSelect, {
propsData: { multiple: true, value: ["foo", "bar"], options: ["foo", "bar"] }
});
Select.vm.select("bar");
Select.vm.select("bar");
expect(Select.emitted("option:selecting")).toEqual([["bar"], ["bar"]]);
});
});
propsData: {
multiple: true,
value: ['foo', 'bar'],
options: ['foo', 'bar'],
},
})
Select.vm.select('bar')
Select.vm.select('bar')
expect(Select.emitted('option:selecting')).toEqual([['bar'], ['bar']])
})
})
describe("option:deselected Event", () => {
it("will trigger the option:deselected event when an option is deselected", () => {
describe('option:deselected Event', () => {
it('will trigger the option:deselected event when an option is deselected', () => {
const Select = shallowMount(VueSelect, {
propsData: { value: ["foo"], options: ["foo", "bar"] }
});
Select.vm.deselect("foo");
expect(Select.emitted("option:deselected")[0]).toEqual(["foo"]);
});
propsData: { value: ['foo'], options: ['foo', 'bar'] },
})
Select.vm.deselect('foo')
expect(Select.emitted('option:deselected')[0]).toEqual(['foo'])
})
it("will trigger the option:deselected event regardless of current value", () => {
it('will trigger the option:deselected event regardless of current value', () => {
const Select = shallowMount(VueSelect, {
propsData: { value: ["foo"], options: ["foo", "bar"] }
});
Select.vm.deselect("foo");
Select.vm.deselect("bar");
expect(Select.emitted("option:deselected")).toEqual([["foo"], ["bar"]]);
});
propsData: { value: ['foo'], options: ['foo', 'bar'] },
})
Select.vm.deselect('foo')
Select.vm.deselect('bar')
expect(Select.emitted('option:deselected')).toEqual([['foo'], ['bar']])
})
it("will trigger the option:selected event with current selected item when multiple is true", () => {
it('will trigger the option:selected event with current selected item when multiple is true', () => {
const Select = shallowMount(VueSelect, {
propsData: { multiple: true, value: ["foo"], options: ["foo", "bar"] }
});
Select.vm.deselect("bar");
expect(Select.emitted("option:deselected")[0]).toEqual(["bar"]);
});
propsData: { multiple: true, value: ['foo'], options: ['foo', 'bar'] },
})
Select.vm.deselect('bar')
expect(Select.emitted('option:deselected')[0]).toEqual(['bar'])
})
it("will trigger the option:selected event regardless of current value when multiple is true", () => {
it('will trigger the option:selected event regardless of current value when multiple is true', () => {
const Select = shallowMount(VueSelect, {
propsData: { multiple: true, value: ["foo", "bar"], options: ["foo", "bar"] }
});
Select.vm.deselect("bar");
Select.vm.deselect("bar");
expect(Select.emitted("option:deselected")).toEqual([["bar"], ["bar"]]);
});
});
});
propsData: {
multiple: true,
value: ['foo', 'bar'],
options: ['foo', 'bar'],
},
})
Select.vm.deselect('bar')
Select.vm.deselect('bar')
expect(Select.emitted('option:deselected')).toEqual([['bar'], ['bar']])
})
})
})
+107 -76
View File
@@ -1,122 +1,153 @@
import { mountDefault } from '../helpers';
import { mountDefault } from '../helpers'
describe('Scoped Slots', () => {
it('receives an option object to the selected-option-container slot', () => {
const Select = mountDefault(
{value: 'one'},
{ value: 'one' },
{
scopedSlots: {
'selected-option-container': `<span slot="selected-option-container" slot-scope="{option}">{{ option.label }}</span>`,
},
});
}
)
expect(Select.find({ref: 'selectedOptions'}).text()).toEqual('one');
});
expect(Select.find({ ref: 'selectedOptions' }).text()).toEqual('one')
})
describe('Slot: selected-option', () => {
it('receives an option object to the selected-option slot', () => {
const Select = mountDefault(
{value: 'one'},
{ value: 'one' },
{
scopedSlots: {
'selected-option': `<span slot="selected-option" slot-scope="option">{{ option.label }}</span>`,
},
});
}
)
expect(Select.find('.vs__selected').text()).toEqual('one');
});
expect(Select.find('.vs__selected').text()).toEqual('one')
})
it('opens the dropdown when clicking an option in selected-option slot',
() => {
const Select = mountDefault(
{value: 'one'},
{
scopedSlots: {
'selected-option': `<span class="my-option" slot-scope="option">{{ option.label }}</span>`,
},
});
Select.find('.my-option').trigger('mousedown');
expect(Select.vm.open).toEqual(true);
});
});
it('receives an option object to the option slot in the dropdown menu',
async () => {
it('opens the dropdown when clicking an option in selected-option slot', () => {
const Select = mountDefault(
{value: 'one'},
{ value: 'one' },
{
scopedSlots: {
'option': `<span slot="option" slot-scope="option">{{ option.label }}</span>`,
'selected-option': `<span class="my-option" slot-scope="option">{{ option.label }}</span>`,
},
});
}
)
Select.vm.open = true;
await Select.vm.$nextTick();
Select.find('.my-option').trigger('mousedown')
expect(Select.vm.open).toEqual(true)
})
})
expect(Select.find({ref: 'dropdownMenu'}).text()).toEqual('onetwothree');
});
it('receives an option object to the option slot in the dropdown menu', async () => {
const Select = mountDefault(
{ value: 'one' },
{
scopedSlots: {
option: `<span slot="option" slot-scope="option">{{ option.label }}</span>`,
},
}
)
Select.vm.open = true
await Select.vm.$nextTick()
expect(Select.find({ ref: 'dropdownMenu' }).text()).toEqual('onetwothree')
})
it('noOptions slot receives the current search text', async () => {
const noOptions = jest.fn();
const Select = mountDefault({}, {
scopedSlots: {'no-options': noOptions},
});
const noOptions = jest.fn()
const Select = mountDefault(
{},
{
scopedSlots: { 'no-options': noOptions },
}
)
Select.vm.search = 'something not there';
Select.vm.open = true;
await Select.vm.$nextTick();
Select.vm.search = 'something not there'
Select.vm.open = true
await Select.vm.$nextTick()
expect(noOptions).toHaveBeenCalledWith({
loading: false,
search: 'something not there',
searching: true,
})
});
})
test('header slot props', async () => {
const header = jest.fn();
const Select = mountDefault({}, {
scopedSlots: {header: header},
});
await Select.vm.$nextTick();
const header = jest.fn()
const Select = mountDefault(
{},
{
scopedSlots: { header: header },
}
)
await Select.vm.$nextTick()
expect(Object.keys(header.mock.calls[0][0])).toEqual([
'search', 'loading', 'searching', 'filteredOptions', 'deselect',
]);
});
'search',
'loading',
'searching',
'filteredOptions',
'deselect',
])
})
test('footer slot props', async () => {
const footer = jest.fn();
const Select = mountDefault({}, {
scopedSlots: {footer: footer},
});
await Select.vm.$nextTick();
const footer = jest.fn()
const Select = mountDefault(
{},
{
scopedSlots: { footer: footer },
}
)
await Select.vm.$nextTick()
expect(Object.keys(footer.mock.calls[0][0])).toEqual([
'search', 'loading', 'searching', 'filteredOptions', 'deselect',
]);
});
'search',
'loading',
'searching',
'filteredOptions',
'deselect',
])
})
test('list-header slot props', async () => {
const header = jest.fn();
const Select = mountDefault({}, {
scopedSlots: {'list-header': header},
});
Select.vm.open = true;
await Select.vm.$nextTick();
const header = jest.fn()
const Select = mountDefault(
{},
{
scopedSlots: { 'list-header': header },
}
)
Select.vm.open = true
await Select.vm.$nextTick()
expect(Object.keys(header.mock.calls[0][0])).toEqual([
'search', 'loading', 'searching', 'filteredOptions',
]);
});
'search',
'loading',
'searching',
'filteredOptions',
])
})
test('list-footer slot props', async () => {
const footer = jest.fn();
const Select = mountDefault({}, {
scopedSlots: {'list-footer': footer},
});
Select.vm.open = true;
await Select.vm.$nextTick();
const footer = jest.fn()
const Select = mountDefault(
{},
{
scopedSlots: { 'list-footer': footer },
}
)
Select.vm.open = true
await Select.vm.$nextTick()
expect(Object.keys(footer.mock.calls[0][0])).toEqual([
'search', 'loading', 'searching', 'filteredOptions',
]);
});
});
'search',
'loading',
'searching',
'filteredOptions',
])
})
})
+156 -159
View File
@@ -3,261 +3,258 @@ import {
searchSubmit,
selectTag,
selectWithProps,
} from '../helpers';
import Select from '../../src/components/Select';
} from '../helpers'
import Select from '../../src/components/Select'
describe("When Tagging Is Enabled", () => {
describe('When Tagging Is Enabled', () => {
it('can determine if a given option string already exists', () => {
const Select = selectWithProps({ taggable: true, options: ['one', 'two'] })
expect(Select.vm.optionExists('one')).toEqual(true)
expect(Select.vm.optionExists('three')).toEqual(false)
})
it("can determine if a given option string already exists", () => {
const Select = selectWithProps({ taggable: true, options: ["one", "two"] });
expect(Select.vm.optionExists("one")).toEqual(true);
expect(Select.vm.optionExists("three")).toEqual(false);
});
it("can determine if a given option object already exists", () => {
it('can determine if a given option object already exists', () => {
const Select = selectWithProps({
taggable: true,
options: [{ label: "one" }, { label: "two" }]
});
options: [{ label: 'one' }, { label: 'two' }],
})
expect(Select.vm.optionExists({label: "one"})).toEqual(true);
expect(Select.vm.optionExists({label: "three"})).toEqual(false);
});
expect(Select.vm.optionExists({ label: 'one' })).toEqual(true)
expect(Select.vm.optionExists({ label: 'three' })).toEqual(false)
})
it("can determine if a given option object already exists when using custom labels", () => {
it('can determine if a given option object already exists when using custom labels', () => {
const Select = selectWithProps({
taggable: true,
options: [{ foo: "one" }, { foo: "two" }],
label: "foo"
});
options: [{ foo: 'one' }, { foo: 'two' }],
label: 'foo',
})
const createOption = (text) => Select.vm.createOption(text);
const createOption = (text) => Select.vm.createOption(text)
expect(Select.vm.optionExists(createOption("one"))).toEqual(true);
expect(Select.vm.optionExists(createOption("three"))).toEqual(false);
});
expect(Select.vm.optionExists(createOption('one'))).toEqual(true)
expect(Select.vm.optionExists(createOption('three'))).toEqual(false)
})
it("can add the current search text as the first item in the options list", async () => {
it('can add the current search text as the first item in the options list', async () => {
const Select = selectWithProps({
taggable: true,
multiple: true,
value: ["one"],
options: ["one", "two"]
});
value: ['one'],
options: ['one', 'two'],
})
Select.vm.search = "three";
await Select.vm.$nextTick();
expect(Select.vm.filteredOptions).toEqual(["three"]);
});
Select.vm.search = 'three'
await Select.vm.$nextTick()
expect(Select.vm.filteredOptions).toEqual(['three'])
})
it("can select the current search text as a string", async () => {
it('can select the current search text as a string', async () => {
const Select = selectWithProps({
taggable: true,
multiple: true,
options: ["one", "two"]
});
options: ['one', 'two'],
})
await selectTag(Select, "three");
await selectTag(Select, 'three')
expect(Select.vm.selectedValue).toEqual(["three"]);
});
expect(Select.vm.selectedValue).toEqual(['three'])
})
it("can select the current search text as an object", async () => {
it('can select the current search text as an object', async () => {
const Select = selectWithProps({
taggable: true,
multiple: true,
options: [{ label: "one" }]
});
options: [{ label: 'one' }],
})
await selectTag(Select, "two");
await selectTag(Select, 'two')
expect(Select.vm.selectedValue).toEqual([
{ label: "two" }
]);
});
expect(Select.vm.selectedValue).toEqual([{ label: 'two' }])
})
it("should add a freshly created option/tag to the options list when pushTags is true", async () => {
it('should add a freshly created option/tag to the options list when pushTags is true', async () => {
const Select = selectWithProps({
pushTags: true,
taggable: true,
multiple: true,
value: ["one"],
options: ["one", "two"]
});
value: ['one'],
options: ['one', 'two'],
})
await selectTag(Select, "three");
expect(Select.vm.pushedTags).toEqual(["three"]);
expect(Select.vm.optionList).toEqual(["one", "two", "three"]);
});
await selectTag(Select, 'three')
expect(Select.vm.pushedTags).toEqual(['three'])
expect(Select.vm.optionList).toEqual(['one', 'two', 'three'])
})
it("should pushTags even if the consumer has defined a createOption callback", async () => {
it('should pushTags even if the consumer has defined a createOption callback', async () => {
const Select = selectWithProps({
pushTags: true,
taggable: true,
createOption: option => option,
options: ["one", "two"]
});
createOption: (option) => option,
options: ['one', 'two'],
})
await selectTag(Select, "three");
await selectTag(Select, 'three')
expect(Select.vm.pushedTags).toEqual(["three"]);
expect(Select.vm.optionList).toEqual(["one", "two", "three"]);
});
expect(Select.vm.pushedTags).toEqual(['three'])
expect(Select.vm.optionList).toEqual(['one', 'two', 'three'])
})
it("should add a freshly created option/tag to the options list when pushTags is true and filterable is false", async () => {
it('should add a freshly created option/tag to the options list when pushTags is true and filterable is false', async () => {
const Select = selectWithProps({
filterable: false,
pushTags: true,
taggable: true,
multiple: true,
value: ["one"],
options: ["one", "two"]
});
value: ['one'],
options: ['one', 'two'],
})
await selectTag(Select, "three");
expect(Select.vm.pushedTags).toEqual(["three"]);
expect(Select.vm.optionList).toEqual(["one", "two", "three"]);
expect(Select.vm.filteredOptions).toEqual(["one", "two", "three"]);
});
await selectTag(Select, 'three')
expect(Select.vm.pushedTags).toEqual(['three'])
expect(Select.vm.optionList).toEqual(['one', 'two', 'three'])
expect(Select.vm.filteredOptions).toEqual(['one', 'two', 'three'])
})
it("wont add a freshly created option/tag to the options list when pushTags is false", async () => {
it('wont add a freshly created option/tag to the options list when pushTags is false', async () => {
const Select = selectWithProps({
pushTags: false,
taggable: true,
multiple: true,
value: ["one"],
options: ["one", "two"]
});
value: ['one'],
options: ['one', 'two'],
})
await selectTag(Select, "three");
expect(Select.vm.optionList).toEqual(["one", "two"]);
});
await selectTag(Select, 'three')
expect(Select.vm.optionList).toEqual(['one', 'two'])
})
it("wont add a freshly created option/tag to the options list when pushTags is false and filterable is false", async () => {
it('wont add a freshly created option/tag to the options list when pushTags is false and filterable is false', async () => {
const Select = selectWithProps({
filterable: false,
pushTags: false,
taggable: true,
multiple: true,
value: ["one"],
options: ["one", "two"]
});
value: ['one'],
options: ['one', 'two'],
})
await selectTag(Select, "three");
expect(Select.vm.optionList).toEqual(["one", "two"]);
expect(Select.vm.filteredOptions).toEqual(["one", "two"]);
});
await selectTag(Select, 'three')
expect(Select.vm.optionList).toEqual(['one', 'two'])
expect(Select.vm.filteredOptions).toEqual(['one', 'two'])
})
it("should select an existing option if the search string matches a string from options", async () => {
let two = "two";
it('should select an existing option if the search string matches a string from options', async () => {
let two = 'two'
const Select = selectWithProps({
taggable: true,
multiple: true,
options: ["one", two]
});
options: ['one', two],
})
await selectTag(Select, "two");
await selectTag(Select, 'two')
expect(Select.vm.selectedValue).toEqual([two]);
});
expect(Select.vm.selectedValue).toEqual([two])
})
it("should select an existing option if the search string matches an objects label from options", async () => {
let two = { label: "two" };
it('should select an existing option if the search string matches an objects label from options', async () => {
let two = { label: 'two' }
const Select = selectWithProps({
taggable: true,
options: [{ label: "one" }, two]
});
options: [{ label: 'one' }, two],
})
Select.vm.search = "two";
await Select.vm.$nextTick();
Select.vm.search = 'two'
await Select.vm.$nextTick()
searchSubmit(Select);
expect(Select.vm.selectedValue).toEqual([two]);
});
searchSubmit(Select)
expect(Select.vm.selectedValue).toEqual([two])
})
it("should select an existing option if the search string matches an objects label from options when filter-options is false", async () => {
let two = { label: "two" };
it('should select an existing option if the search string matches an objects label from options when filter-options is false', async () => {
let two = { label: 'two' }
const Select = selectWithProps({
taggable: true,
filterable: false,
options: [{ label: "one" }, two]
});
options: [{ label: 'one' }, two],
})
Select.vm.search = "two";
await Select.vm.$nextTick();
Select.vm.search = 'two'
await Select.vm.$nextTick()
searchSubmit(Select);
expect(Select.vm.selectedValue).toEqual([two]);
});
searchSubmit(Select)
expect(Select.vm.selectedValue).toEqual([two])
})
it("should not reset the selected value when the options property changes", () => {
it('should not reset the selected value when the options property changes', () => {
const Select = selectWithProps({
taggable: true,
multiple: true,
value: [{ label: "one" }],
options: [{ label: "one" }]
});
value: [{ label: 'one' }],
options: [{ label: 'one' }],
})
Select.setProps({ options: [{ label: "two" }] });
expect(Select.vm.selectedValue).toEqual([{ label: "one" }]);
});
Select.setProps({ options: [{ label: 'two' }] })
expect(Select.vm.selectedValue).toEqual([{ label: 'one' }])
})
it("should not reset the selected value when the options property changes when filterable is false", () => {
it('should not reset the selected value when the options property changes when filterable is false', () => {
const Select = selectWithProps({
taggable: true,
multiple: true,
filterable: false,
value: [{ label: "one" }],
options: [{ label: "one" }]
});
value: [{ label: 'one' }],
options: [{ label: 'one' }],
})
Select.setProps({ options: [{ label: "two" }] });
expect(Select.vm.selectedValue).toEqual([{ label: "one" }]);
});
Select.setProps({ options: [{ label: 'two' }] })
expect(Select.vm.selectedValue).toEqual([{ label: 'one' }])
})
it("should not allow duplicate tags when using string options", async () => {
const Select = selectWithProps({
taggable: true,
multiple: true
});
await selectTag(Select, "one");
expect(Select.vm.selectedValue).toEqual(["one"]);
expect(Select.vm.search).toEqual("");
await selectTag(Select, "one");
expect(Select.vm.selectedValue).toEqual(["one"]);
expect(Select.vm.search).toEqual("");
});
it("should not allow duplicate tags when using object options", async () => {
it('should not allow duplicate tags when using string options', async () => {
const Select = selectWithProps({
taggable: true,
multiple: true,
options: [{ label: "two" }]
});
const spy = jest.spyOn(Select.vm, 'select');
})
await selectTag(Select, "one");
expect(Select.vm.selectedValue).toEqual([{ label: "one" }]);
expect(spy).lastCalledWith({label: 'one'});
expect(Select.vm.search).toEqual("");
await selectTag(Select, 'one')
expect(Select.vm.selectedValue).toEqual(['one'])
expect(Select.vm.search).toEqual('')
await selectTag(Select, "one");
expect(Select.vm.selectedValue).toEqual([{ label: "one" }]);
expect(Select.vm.search).toEqual("");
});
await selectTag(Select, 'one')
expect(Select.vm.selectedValue).toEqual(['one'])
expect(Select.vm.search).toEqual('')
})
it("will select an existing option on tab", async () => {
it('should not allow duplicate tags when using object options', async () => {
const Select = selectWithProps({
taggable: true,
multiple: true,
options: [{ label: 'two' }],
})
const spy = jest.spyOn(Select.vm, 'select')
await selectTag(Select, 'one')
expect(Select.vm.selectedValue).toEqual([{ label: 'one' }])
expect(spy).lastCalledWith({ label: 'one' })
expect(Select.vm.search).toEqual('')
await selectTag(Select, 'one')
expect(Select.vm.selectedValue).toEqual([{ label: 'one' }])
expect(Select.vm.search).toEqual('')
})
it('will select an existing option on tab', async () => {
const Select = mountDefault({
taggable: true,
selectOnTab: true
});
selectOnTab: true,
})
Select.vm.typeAheadPointer = 0;
Select.find({ ref: "search" }).trigger("keydown.tab");
Select.vm.typeAheadPointer = 0
Select.find({ ref: 'search' }).trigger('keydown.tab')
await Select.vm.$nextTick();
expect(Select.vm.selectedValue).toEqual(['one']);
await Select.vm.$nextTick()
expect(Select.vm.selectedValue).toEqual(['one'])
})
});
})
+33 -33
View File
@@ -1,47 +1,47 @@
import { shallowMount } from "@vue/test-utils";
import VueSelect from "../../src/components/Select";
import { mountDefault, mountWithoutTestUtils } from "../helpers";
import typeAheadMixin from "../../src/mixins/typeAheadPointer";
import Vue from "vue";
import { shallowMount } from '@vue/test-utils'
import VueSelect from '../../src/components/Select'
import { mountDefault, mountWithoutTestUtils } from '../helpers'
import typeAheadMixin from '../../src/mixins/typeAheadPointer'
import Vue from 'vue'
describe("Moving the Typeahead Pointer", () => {
it("should set the pointer to zero when the filteredOptions watcher is called", async () => {
describe('Moving the Typeahead Pointer', () => {
it('should set the pointer to zero when the filteredOptions watcher is called', async () => {
const Select = shallowMount(VueSelect, {
propsData: { options: ["one", "two", "three"] },
sync: false
});
propsData: { options: ['one', 'two', 'three'] },
sync: false,
})
Select.vm.search = "one";
Select.vm.search = 'one'
await Select.vm.$nextTick();
expect(Select.vm.typeAheadPointer).toEqual(0);
});
await Select.vm.$nextTick()
expect(Select.vm.typeAheadPointer).toEqual(0)
})
it("should move the pointer visually up the list on up arrow keyUp", () => {
const Select = mountDefault();
it('should move the pointer visually up the list on up arrow keyUp', () => {
const Select = mountDefault()
Select.vm.typeAheadPointer = 1;
Select.vm.typeAheadPointer = 1
Select.find({ ref: "search" }).trigger("keydown.up");
Select.find({ ref: 'search' }).trigger('keydown.up')
expect(Select.vm.typeAheadPointer).toEqual(0);
});
expect(Select.vm.typeAheadPointer).toEqual(0)
})
it("should move the pointer visually down the list on down arrow keyUp", () => {
const Select = mountDefault();
it('should move the pointer visually down the list on down arrow keyUp', () => {
const Select = mountDefault()
Select.vm.typeAheadPointer = 1;
Select.vm.typeAheadPointer = 1
Select.find({ ref: "search" }).trigger("keydown.down");
Select.find({ ref: 'search' }).trigger('keydown.down')
expect(Select.vm.typeAheadPointer).toEqual(2);
});
expect(Select.vm.typeAheadPointer).toEqual(2)
})
it("should not move the pointer past the end of the list", () => {
const Select = mountDefault();
it('should not move the pointer past the end of the list', () => {
const Select = mountDefault()
Select.vm.typeAheadPointer = 2;
Select.vm.typeAheadDown();
expect(Select.vm.typeAheadPointer).toEqual(2);
});
});
Select.vm.typeAheadPointer = 2
Select.vm.typeAheadDown()
expect(Select.vm.typeAheadPointer).toEqual(2)
})
})
+9 -8
View File
@@ -1,14 +1,15 @@
import sortAndStringify from '../../../src/utility/sortAndStringify';
import sortAndStringify from '../../../src/utility/sortAndStringify'
test('it will stringify an object', () => {
expect(sortAndStringify({hello: 'world'})).toEqual('{"hello":"world"}');
});
expect(sortAndStringify({ hello: 'world' })).toEqual('{"hello":"world"}')
})
test('it will sort attributes alphabetically', () => {
expect(sortAndStringify({b: 'b', a: 'a'})).toEqual('{"a":"a","b":"b"}');
});
expect(sortAndStringify({ b: 'b', a: 'a' })).toEqual('{"a":"a","b":"b"}')
})
test('comparing two objects with unsorted keys', () => {
expect(sortAndStringify({b: 'b', a: 'a'}))
.toEqual(sortAndStringify({a: 'a', b: 'b'}))
});
expect(sortAndStringify({ b: 'b', a: 'a' })).toEqual(
sortAndStringify({ a: 'a', b: 'b' })
)
})
+3 -3
View File
@@ -1,5 +1,5 @@
import uniqueId from '../../../src/utility/uniqueId';
import uniqueId from '../../../src/utility/uniqueId'
test('it generates a unique number', () => {
expect(uniqueId()).not.toEqual(uniqueId());
});
expect(uniqueId()).not.toEqual(uniqueId())
})