├── .babelrc ├── .editorconfig ├── .eslintignore ├── .eslintrc.js ├── .gitignore ├── .npmignore ├── .postcssrc.js ├── .travis.yml ├── LICENSE ├── README.md ├── build ├── build.js ├── check-versions.js ├── dev-client.js ├── dev-server.js ├── utils.js ├── vue-loader.conf.js ├── webpack.base.conf.js ├── webpack.dev.conf.js ├── webpack.prod.conf.js └── webpack.test.conf.js ├── config ├── dev.env.js ├── index.js ├── prod.env.js └── test.env.js ├── index.html ├── package.json ├── src ├── Demo.vue ├── assets │ ├── close.svg │ ├── loading.svg │ └── search.svg ├── components │ └── Autocomplete.vue └── main.js ├── static └── .gitkeep ├── test └── unit │ ├── .eslintrc │ ├── jest.conf.js │ ├── setup.js │ └── specs │ ├── DomRendering.spec.js │ ├── ResultsInteraction.spec.js │ ├── SearchResultsArrayLikeSource.spec.js │ └── SearchResultsResourceSearch.spec.js └── yarn.lock /.babelrc: -------------------------------------------------------------------------------- 1 | { 2 | "presets": [ 3 | ["env", { "modules": false }], 4 | "stage-2" 5 | ], 6 | "plugins": ["transform-runtime"], 7 | "env": { 8 | "test": { 9 | "presets": ["env", "stage-2"], 10 | "plugins": [ "istanbul" ] 11 | } 12 | } 13 | } 14 | -------------------------------------------------------------------------------- /.editorconfig: -------------------------------------------------------------------------------- 1 | root = true 2 | 3 | [*] 4 | charset = utf-8 5 | indent_style = space 6 | indent_size = 2 7 | end_of_line = lf 8 | insert_final_newline = true 9 | trim_trailing_whitespace = true 10 | -------------------------------------------------------------------------------- /.eslintignore: -------------------------------------------------------------------------------- 1 | build/*.js 2 | config/*.js 3 | -------------------------------------------------------------------------------- /.eslintrc.js: -------------------------------------------------------------------------------- 1 | // http://eslint.org/docs/user-guide/configuring 2 | 3 | module.exports = { 4 | root: true, 5 | parser: 'babel-eslint', 6 | parserOptions: { 7 | sourceType: 'module' 8 | }, 9 | env: { 10 | browser: true, 11 | }, 12 | // https://github.com/feross/standard/blob/master/RULES.md#javascript-standard-style 13 | extends: 'standard', 14 | // required to lint *.vue files 15 | plugins: [ 16 | 'html' 17 | ], 18 | // add your custom rules here 19 | 'rules': { 20 | // allow paren-less arrow functions 21 | 'arrow-parens': 0, 22 | // allow async-await 23 | 'generator-star-spacing': 0, 24 | // allow debugger during development 25 | 'no-debugger': process.env.NODE_ENV === 'production' ? 2 : 0 26 | } 27 | } 28 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | .DS_Store 2 | node_modules/ 3 | dist/ 4 | npm-debug.log* 5 | yarn-debug.log* 6 | yarn-error.log* 7 | test/unit/coverage 8 | package-lock.json 9 | -------------------------------------------------------------------------------- /.npmignore: -------------------------------------------------------------------------------- 1 | .DS_Store 2 | node_modules/ 3 | npm-debug.log* 4 | yarn-debug.log* 5 | yarn-error.log* 6 | test/unit/coverage 7 | -------------------------------------------------------------------------------- /.postcssrc.js: -------------------------------------------------------------------------------- 1 | // https://github.com/michael-ciniawsky/postcss-load-config 2 | 3 | module.exports = { 4 | "plugins": { 5 | // to edit target browsers: use "browserlist" field in package.json 6 | "autoprefixer": {} 7 | } 8 | } 9 | -------------------------------------------------------------------------------- /.travis.yml: -------------------------------------------------------------------------------- 1 | language: node_js 2 | node_js: 3 | - "8" 4 | after_script: "cat ./test/unit/coverage/lcov.info | ./node_modules/coveralls/bin/coveralls.js" 5 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | MIT License 2 | 3 | Copyright (c) 2017 Charlie Kassel 4 | 5 | Permission is hereby granted, free of charge, to any person obtaining a copy 6 | of this software and associated documentation files (the "Software"), to deal 7 | in the Software without restriction, including without limitation the rights 8 | to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 9 | copies of the Software, and to permit persons to whom the Software is 10 | furnished to do so, subject to the following conditions: 11 | 12 | The above copyright notice and this permission notice shall be included in all 13 | copies or substantial portions of the Software. 14 | 15 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 16 | IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 17 | FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 18 | AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 19 | LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 20 | OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE 21 | SOFTWARE. 22 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # vuejs-auto-complete 2 | 3 | [![Travis Build](https://img.shields.io/travis/charliekassel/vuejs-autocomplete.svg?branch=master)](https://travis-ci.org/charliekassel/vuejs-autocomplete?branch=master) 4 | [![Version](https://img.shields.io/npm/v/vuejs-auto-complete.svg)](https://www.npmjs.com/package/vuejs-auto-complete) 5 | [![Coveralls github](https://img.shields.io/coveralls/github/charliekassel/vuejs-autocomplete.svg)](https://coveralls.io/github/charliekassel/vuejs-autocomplete?branch=master) 6 | [![Downloads](https://img.shields.io/npm/dm/vuejs-auto-complete.svg)](https://www.npmjs.com/package/vuejs-auto-complete) 7 | 8 | > A Vue autocomplete component 9 | 10 | `npm install vuejs-auto-complete --save` 11 | 12 | ## Usage 13 | 14 | Installation, add autocomplete component into your app 15 | 16 | ```javascript 17 | import Vue from 'vue' 18 | import Autocomplete from 'vuejs-auto-complete' 19 | 20 | new Vue({ 21 | //... 22 | components: { 23 | Autocomplete, 24 | }, 25 | //... 26 | }) 27 | ``` 28 | 29 | Api data source 30 | ``` html 31 | 35 | 36 | ``` 37 | 38 | Object data source 39 | ``` html 40 | 42 | 43 | ``` 44 | 45 | Full featured example 46 | ``` html 47 | 56 | 57 | ``` 58 | ``` javascript 59 | // parent component 60 | computed: { 61 | authHeaders () { 62 | return { 63 | 'Authorization': 'Bearer eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1Ni....' 64 | } 65 | }, 66 | }, 67 | methods: { 68 | distributionGroupsEndpoint (input) { 69 | return process.env.API + '/distribution/search?query=' + input 70 | }, 71 | addDistributionGroup (group) { 72 | this.group = group 73 | // access the autocomplete component methods from the parent 74 | this.$refs.autocomplete.clear() 75 | }, 76 | authHeaders () { 77 | return { 78 | 'Authorization': 'Bearer eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1Ni....' 79 | } 80 | }, 81 | formattedDisplay (result) { 82 | return result.name + ' [' + result.groupId + ']' 83 | } 84 | } 85 | ``` 86 | ## Available props 87 | 88 | | Prop | Type | Required | Default | Description | 89 | |-----------------------|-----------------------------|----------|-----------|-------------| 90 | | source | String\|Function\|Object\|Array | | true | data source for the results| 91 | | method | String | | 'get' | http method for api requests| 92 | | placeholder | String | | 'Search' | input placeholder| 93 | | initialValue | String\|Number | | | starting value| 94 | | initialDisplay | String | | | starting display value| 95 | | inputClass | String\|Object | | | css class for the input div| 96 | | disableInput | Boolean | | | to disable the input| 97 | | name | String | | | name attribute for the `value` input| 98 | | resultsFormatter | Function | | | Function to format the server data. Should return an array of objects with id and name properties | 99 | | resultsProperty | String | | | property api results are keyed under| 100 | | resultsValue | String | | 'id' | property to use for the `value`| 101 | | resultsDisplay | String\|Function | | 'name' | property to use for the `display` or custom function| 102 | | requestHeaders | Object | | | extra headers appended to the request| 103 | | showNoResults | Boolean | | true | To show a message that no results were found| 104 | | clearButtonIcon | String | | | Optionally provide an icon css class| 105 | | maxlength | Number | | | Optional max input length| 106 | 107 | ## Available events 108 | 109 | | Event | Output | Description | 110 | |----------|----------------|-------------| 111 | | results | Object | Results returned from a search | 112 | | noResults| Object | When no results are returned | 113 | | selected | Object | When an item is selected | 114 | | input | String\|Number | The value when an item is selected | 115 | | clear | | When selected results are cleared | 116 | | close | | When the options list is closed | 117 | | enter | String | Emits the input value when enter is pressed | 118 | | nothingSelected | String | Emits the input value when enter is pressed and nothing was selected | 119 | 120 | ## Available Slots 121 | 122 | | Slot | Description | 123 | |-------------|-------------| 124 | | firstResult | list item placed before all results | 125 | | lastResult | list item placed at the end of the results | 126 | | noResults | list item shown when no results are present | 127 | -------------------------------------------------------------------------------- /build/build.js: -------------------------------------------------------------------------------- 1 | require('./check-versions')() 2 | 3 | process.env.NODE_ENV = 'production' 4 | 5 | var ora = require('ora') 6 | var rm = require('rimraf') 7 | var path = require('path') 8 | var chalk = require('chalk') 9 | var webpack = require('webpack') 10 | var config = require('../config') 11 | var webpackConfig = require('./webpack.prod.conf') 12 | 13 | var spinner = ora('building for production...') 14 | spinner.start() 15 | 16 | rm(path.join(config.build.assetsRoot, config.build.assetsSubDirectory), err => { 17 | if (err) throw err 18 | webpack(webpackConfig, function (err, stats) { 19 | spinner.stop() 20 | if (err) throw err 21 | process.stdout.write(stats.toString({ 22 | colors: true, 23 | modules: false, 24 | children: false, 25 | chunks: false, 26 | chunkModules: false 27 | }) + '\n\n') 28 | 29 | console.log(chalk.cyan(' Build complete.\n')) 30 | console.log(chalk.yellow( 31 | ' Tip: built files are meant to be served over an HTTP server.\n' + 32 | ' Opening index.html over file:// won\'t work.\n' 33 | )) 34 | }) 35 | }) 36 | -------------------------------------------------------------------------------- /build/check-versions.js: -------------------------------------------------------------------------------- 1 | var chalk = require('chalk') 2 | var semver = require('semver') 3 | var packageConfig = require('../package.json') 4 | var shell = require('shelljs') 5 | function exec (cmd) { 6 | return require('child_process').execSync(cmd).toString().trim() 7 | } 8 | 9 | var versionRequirements = [ 10 | { 11 | name: 'node', 12 | currentVersion: semver.clean(process.version), 13 | versionRequirement: packageConfig.engines.node 14 | }, 15 | ] 16 | 17 | if (shell.which('npm')) { 18 | versionRequirements.push({ 19 | name: 'npm', 20 | currentVersion: exec('npm --version'), 21 | versionRequirement: packageConfig.engines.npm 22 | }) 23 | } 24 | 25 | module.exports = function () { 26 | var warnings = [] 27 | for (var i = 0; i < versionRequirements.length; i++) { 28 | var mod = versionRequirements[i] 29 | if (!semver.satisfies(mod.currentVersion, mod.versionRequirement)) { 30 | warnings.push(mod.name + ': ' + 31 | chalk.red(mod.currentVersion) + ' should be ' + 32 | chalk.green(mod.versionRequirement) 33 | ) 34 | } 35 | } 36 | 37 | if (warnings.length) { 38 | console.log('') 39 | console.log(chalk.yellow('To use this template, you must update following to modules:')) 40 | console.log() 41 | for (var i = 0; i < warnings.length; i++) { 42 | var warning = warnings[i] 43 | console.log(' ' + warning) 44 | } 45 | console.log() 46 | process.exit(1) 47 | } 48 | } 49 | -------------------------------------------------------------------------------- /build/dev-client.js: -------------------------------------------------------------------------------- 1 | /* eslint-disable */ 2 | require('eventsource-polyfill') 3 | var hotClient = require('webpack-hot-middleware/client?noInfo=true&reload=true') 4 | 5 | hotClient.subscribe(function (event) { 6 | if (event.action === 'reload') { 7 | window.location.reload() 8 | } 9 | }) 10 | -------------------------------------------------------------------------------- /build/dev-server.js: -------------------------------------------------------------------------------- 1 | require('./check-versions')() 2 | 3 | var config = require('../config') 4 | if (!process.env.NODE_ENV) { 5 | process.env.NODE_ENV = JSON.parse(config.dev.env.NODE_ENV) 6 | } 7 | 8 | var opn = require('opn') 9 | var path = require('path') 10 | var express = require('express') 11 | var webpack = require('webpack') 12 | var proxyMiddleware = require('http-proxy-middleware') 13 | var webpackConfig = process.env.NODE_ENV === 'testing' 14 | ? require('./webpack.prod.conf') 15 | : require('./webpack.dev.conf') 16 | 17 | // default port where dev server listens for incoming traffic 18 | var port = process.env.PORT || config.dev.port 19 | // automatically open browser, if not set will be false 20 | var autoOpenBrowser = !!config.dev.autoOpenBrowser 21 | // Define HTTP proxies to your custom API backend 22 | // https://github.com/chimurai/http-proxy-middleware 23 | var proxyTable = config.dev.proxyTable 24 | 25 | var app = express() 26 | var compiler = webpack(webpackConfig) 27 | 28 | var devMiddleware = require('webpack-dev-middleware')(compiler, { 29 | publicPath: webpackConfig.output.publicPath, 30 | quiet: true 31 | }) 32 | 33 | var hotMiddleware = require('webpack-hot-middleware')(compiler, { 34 | log: () => {} 35 | }) 36 | // force page reload when html-webpack-plugin template changes 37 | compiler.plugin('compilation', function (compilation) { 38 | compilation.plugin('html-webpack-plugin-after-emit', function (data, cb) { 39 | hotMiddleware.publish({ action: 'reload' }) 40 | cb() 41 | }) 42 | }) 43 | 44 | // proxy api requests 45 | Object.keys(proxyTable).forEach(function (context) { 46 | var options = proxyTable[context] 47 | if (typeof options === 'string') { 48 | options = { target: options } 49 | } 50 | app.use(proxyMiddleware(options.filter || context, options)) 51 | }) 52 | 53 | // handle fallback for HTML5 history API 54 | app.use(require('connect-history-api-fallback')()) 55 | 56 | // serve webpack bundle output 57 | app.use(devMiddleware) 58 | 59 | // enable hot-reload and state-preserving 60 | // compilation error display 61 | app.use(hotMiddleware) 62 | 63 | // serve pure static assets 64 | var staticPath = path.posix.join(config.dev.assetsPublicPath, config.dev.assetsSubDirectory) 65 | app.use(staticPath, express.static('./static')) 66 | 67 | var uri = 'http://localhost:' + port 68 | 69 | var _resolve 70 | var readyPromise = new Promise(resolve => { 71 | _resolve = resolve 72 | }) 73 | 74 | console.log('> Starting dev server...') 75 | devMiddleware.waitUntilValid(() => { 76 | console.log('> Listening at ' + uri + '\n') 77 | // when env is testing, don't need open it 78 | if (autoOpenBrowser && process.env.NODE_ENV !== 'testing') { 79 | opn(uri) 80 | } 81 | _resolve() 82 | }) 83 | 84 | var server = app.listen(port) 85 | 86 | module.exports = { 87 | ready: readyPromise, 88 | close: () => { 89 | server.close() 90 | } 91 | } 92 | -------------------------------------------------------------------------------- /build/utils.js: -------------------------------------------------------------------------------- 1 | var path = require('path') 2 | var config = require('../config') 3 | var ExtractTextPlugin = require('extract-text-webpack-plugin') 4 | 5 | exports.assetsPath = function (_path) { 6 | var assetsSubDirectory = process.env.NODE_ENV === 'production' 7 | ? config.build.assetsSubDirectory 8 | : config.dev.assetsSubDirectory 9 | return path.posix.join(assetsSubDirectory, _path) 10 | } 11 | 12 | exports.cssLoaders = function (options) { 13 | options = options || {} 14 | 15 | var cssLoader = { 16 | loader: 'css-loader', 17 | options: { 18 | minimize: process.env.NODE_ENV === 'production', 19 | sourceMap: options.sourceMap 20 | } 21 | } 22 | 23 | // generate loader string to be used with extract text plugin 24 | function generateLoaders (loader, loaderOptions) { 25 | var loaders = [cssLoader] 26 | if (loader) { 27 | loaders.push({ 28 | loader: loader + '-loader', 29 | options: Object.assign({}, loaderOptions, { 30 | sourceMap: options.sourceMap 31 | }) 32 | }) 33 | } 34 | 35 | // Extract CSS when that option is specified 36 | // (which is the case during production build) 37 | if (options.extract) { 38 | return ExtractTextPlugin.extract({ 39 | use: loaders, 40 | fallback: 'vue-style-loader' 41 | }) 42 | } else { 43 | return ['vue-style-loader'].concat(loaders) 44 | } 45 | } 46 | 47 | // https://vue-loader.vuejs.org/en/configurations/extract-css.html 48 | return { 49 | css: generateLoaders(), 50 | postcss: generateLoaders(), 51 | less: generateLoaders('less'), 52 | sass: generateLoaders('sass', { indentedSyntax: true }), 53 | scss: generateLoaders('sass'), 54 | stylus: generateLoaders('stylus'), 55 | styl: generateLoaders('stylus') 56 | } 57 | } 58 | 59 | // Generate loaders for standalone style files (outside of .vue) 60 | exports.styleLoaders = function (options) { 61 | var output = [] 62 | var loaders = exports.cssLoaders(options) 63 | for (var extension in loaders) { 64 | var loader = loaders[extension] 65 | output.push({ 66 | test: new RegExp('\\.' + extension + '$'), 67 | use: loader 68 | }) 69 | } 70 | return output 71 | } 72 | -------------------------------------------------------------------------------- /build/vue-loader.conf.js: -------------------------------------------------------------------------------- 1 | var utils = require('./utils') 2 | var config = require('../config') 3 | var isProduction = process.env.NODE_ENV === 'production' 4 | 5 | module.exports = { 6 | loaders: utils.cssLoaders({ 7 | sourceMap: isProduction 8 | ? config.build.productionSourceMap 9 | : config.dev.cssSourceMap, 10 | extract: false 11 | }) 12 | } 13 | -------------------------------------------------------------------------------- /build/webpack.base.conf.js: -------------------------------------------------------------------------------- 1 | var path = require('path') 2 | var utils = require('./utils') 3 | var config = require('../config') 4 | var vueLoaderConfig = require('./vue-loader.conf') 5 | 6 | function resolve (dir) { 7 | return path.join(__dirname, '..', dir) 8 | } 9 | 10 | module.exports = { 11 | entry: { 12 | app: './src/main.js' 13 | }, 14 | output: { 15 | path: config.build.assetsRoot, 16 | filename: '[name].js', 17 | publicPath: process.env.NODE_ENV === 'production' 18 | ? config.build.assetsPublicPath 19 | : config.dev.assetsPublicPath 20 | }, 21 | resolve: { 22 | extensions: ['.js', '.vue', '.json'], 23 | alias: { 24 | '@': resolve('src') 25 | } 26 | }, 27 | module: { 28 | rules: [ 29 | { 30 | test: /\.(js|vue)$/, 31 | loader: 'eslint-loader', 32 | enforce: 'pre', 33 | include: [resolve('src'), resolve('test')], 34 | options: { 35 | formatter: require('eslint-friendly-formatter') 36 | } 37 | }, 38 | { 39 | test: /\.vue$/, 40 | loader: 'vue-loader', 41 | options: vueLoaderConfig 42 | }, 43 | { 44 | test: /\.js$/, 45 | loader: 'babel-loader', 46 | include: [resolve('src'), resolve('test')] 47 | }, 48 | { 49 | test: /\.(png|jpe?g|gif|svg)(\?.*)?$/, 50 | loader: 'url-loader', 51 | options: { 52 | limit: 10000, 53 | name: utils.assetsPath('img/[name].[hash:7].[ext]') 54 | } 55 | }, 56 | { 57 | test: /\.(woff2?|eot|ttf|otf)(\?.*)?$/, 58 | loader: 'url-loader', 59 | options: { 60 | limit: 10000, 61 | name: utils.assetsPath('fonts/[name].[hash:7].[ext]') 62 | } 63 | } 64 | ] 65 | } 66 | } 67 | -------------------------------------------------------------------------------- /build/webpack.dev.conf.js: -------------------------------------------------------------------------------- 1 | var utils = require('./utils') 2 | var webpack = require('webpack') 3 | var config = require('../config') 4 | var merge = require('webpack-merge') 5 | var baseWebpackConfig = require('./webpack.base.conf') 6 | var HtmlWebpackPlugin = require('html-webpack-plugin') 7 | var FriendlyErrorsPlugin = require('friendly-errors-webpack-plugin') 8 | 9 | // add hot-reload related code to entry chunks 10 | Object.keys(baseWebpackConfig.entry).forEach(function (name) { 11 | baseWebpackConfig.entry[name] = ['./build/dev-client'].concat(baseWebpackConfig.entry[name]) 12 | }) 13 | 14 | module.exports = merge(baseWebpackConfig, { 15 | module: { 16 | rules: utils.styleLoaders({ sourceMap: config.dev.cssSourceMap }) 17 | }, 18 | // cheap-module-eval-source-map is faster for development 19 | devtool: '#cheap-module-eval-source-map', 20 | plugins: [ 21 | new webpack.DefinePlugin({ 22 | 'process.env': config.dev.env 23 | }), 24 | // https://github.com/glenjamin/webpack-hot-middleware#installation--usage 25 | new webpack.HotModuleReplacementPlugin(), 26 | new webpack.NoEmitOnErrorsPlugin(), 27 | // https://github.com/ampedandwired/html-webpack-plugin 28 | new HtmlWebpackPlugin({ 29 | filename: 'index.html', 30 | template: 'index.html', 31 | inject: true 32 | }), 33 | new FriendlyErrorsPlugin() 34 | ] 35 | }) 36 | -------------------------------------------------------------------------------- /build/webpack.prod.conf.js: -------------------------------------------------------------------------------- 1 | var utils = require('./utils') 2 | var webpack = require('webpack') 3 | var config = require('../config') 4 | var merge = require('webpack-merge') 5 | var baseWebpackConfig = require('./webpack.base.conf') 6 | var OptimizeCSSPlugin = require('optimize-css-assets-webpack-plugin') 7 | 8 | var env = process.env.NODE_ENV === 'testing' 9 | ? require('../config/test.env') 10 | : config.build.env 11 | 12 | var webpackConfig = merge(baseWebpackConfig, { 13 | module: { 14 | rules: utils.styleLoaders({ 15 | sourceMap: config.build.productionSourceMap, 16 | extract: true 17 | }) 18 | }, 19 | devtool: config.build.productionSourceMap ? '#source-map' : false, 20 | entry: '@/components/Autocomplete.vue', 21 | externals: { 22 | vue: 'vue', 23 | lodash: 'lodash' 24 | }, 25 | output: { 26 | path: config.build.assetsRoot, 27 | filename: 'build.js', 28 | library: 'vuejs-autocomplete', 29 | libraryTarget: 'umd' 30 | }, 31 | plugins: [ 32 | // http://vuejs.github.io/vue-loader/en/workflow/production.html 33 | new webpack.DefinePlugin({ 34 | 'process.env': env 35 | }), 36 | new webpack.optimize.UglifyJsPlugin({ 37 | compress: { 38 | warnings: false 39 | }, 40 | sourceMap: config.build.productionSourceMap 41 | }), 42 | // Compress extracted CSS. We are using this plugin so that possible 43 | // duplicated CSS from different components can be deduped. 44 | new OptimizeCSSPlugin({ 45 | cssProcessorOptions: { 46 | safe: true 47 | } 48 | }) 49 | ] 50 | }) 51 | 52 | module.exports = webpackConfig 53 | -------------------------------------------------------------------------------- /build/webpack.test.conf.js: -------------------------------------------------------------------------------- 1 | // This is the webpack config used for unit tests. 2 | 3 | var utils = require('./utils') 4 | var webpack = require('webpack') 5 | var merge = require('webpack-merge') 6 | var baseConfig = require('./webpack.base.conf') 7 | 8 | var webpackConfig = merge(baseConfig, { 9 | // use inline sourcemap for karma-sourcemap-loader 10 | module: { 11 | rules: utils.styleLoaders() 12 | }, 13 | devtool: '#inline-source-map', 14 | resolveLoader: { 15 | alias: { 16 | // necessary to to make lang="scss" work in test when using vue-loader's ?inject option 17 | // see discussion at https://github.com/vuejs/vue-loader/issues/724 18 | 'scss-loader': 'sass-loader' 19 | } 20 | }, 21 | plugins: [ 22 | new webpack.DefinePlugin({ 23 | 'process.env': require('../config/test.env') 24 | }) 25 | ] 26 | }) 27 | 28 | // no need for app entry during tests 29 | delete webpackConfig.entry 30 | 31 | module.exports = webpackConfig 32 | -------------------------------------------------------------------------------- /config/dev.env.js: -------------------------------------------------------------------------------- 1 | var merge = require('webpack-merge') 2 | var prodEnv = require('./prod.env') 3 | 4 | module.exports = merge(prodEnv, { 5 | NODE_ENV: '"development"' 6 | }) 7 | -------------------------------------------------------------------------------- /config/index.js: -------------------------------------------------------------------------------- 1 | // see http://vuejs-templates.github.io/webpack for documentation. 2 | var path = require('path') 3 | 4 | module.exports = { 5 | build: { 6 | env: require('./prod.env'), 7 | index: path.resolve(__dirname, '../dist/index.html'), 8 | assetsRoot: path.resolve(__dirname, '../dist'), 9 | assetsSubDirectory: 'static', 10 | assetsPublicPath: '/', 11 | productionSourceMap: false, 12 | // Gzip off by default as many popular static hosts such as 13 | // Surge or Netlify already gzip all static assets for you. 14 | // Before setting to `true`, make sure to: 15 | // npm install --save-dev compression-webpack-plugin 16 | productionGzip: false, 17 | productionGzipExtensions: ['js', 'css'], 18 | // Run the build command with an extra argument to 19 | // View the bundle analyzer report after build finishes: 20 | // `npm run build --report` 21 | // Set to `true` or `false` to always turn it on or off 22 | bundleAnalyzerReport: process.env.npm_config_report 23 | }, 24 | dev: { 25 | env: require('./dev.env'), 26 | port: 8080, 27 | autoOpenBrowser: true, 28 | assetsSubDirectory: 'static', 29 | assetsPublicPath: '/', 30 | proxyTable: {}, 31 | // CSS Sourcemaps off by default because relative paths are "buggy" 32 | // with this option, according to the CSS-Loader README 33 | // (https://github.com/webpack/css-loader#sourcemaps) 34 | // In our experience, they generally work as expected, 35 | // just be aware of this issue when enabling this option. 36 | cssSourceMap: false 37 | } 38 | } 39 | -------------------------------------------------------------------------------- /config/prod.env.js: -------------------------------------------------------------------------------- 1 | module.exports = { 2 | NODE_ENV: '"production"' 3 | } 4 | -------------------------------------------------------------------------------- /config/test.env.js: -------------------------------------------------------------------------------- 1 | var merge = require('webpack-merge') 2 | var devEnv = require('./dev.env') 3 | 4 | module.exports = merge(devEnv, { 5 | NODE_ENV: '"testing"' 6 | }) 7 | -------------------------------------------------------------------------------- /index.html: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | vuejs-autocomplete 6 | 7 | 8 |
9 | 10 | 11 | 12 | -------------------------------------------------------------------------------- /package.json: -------------------------------------------------------------------------------- 1 | { 2 | "name": "vuejs-auto-complete", 3 | "version": "0.9.0", 4 | "description": "A Vue autocomplete component", 5 | "keywords": [ 6 | "vue", 7 | "autocomplete", 8 | "typeahead" 9 | ], 10 | "author": "Charlie Kassel ", 11 | "private": false, 12 | "license": "MIT", 13 | "main": "dist/build.js", 14 | "files": [ 15 | "dist/build.js", 16 | "dist/build.js.map" 17 | ], 18 | "scripts": { 19 | "dev": "node build/dev-server.js", 20 | "start": "node build/dev-server.js", 21 | "build": "node build/build.js", 22 | "unit": "jest --config test/unit/jest.conf.js --coverage", 23 | "test": "npm run unit", 24 | "lint": "eslint --ext .js,.vue src test/unit/specs", 25 | "prepublish": "npm run build" 26 | }, 27 | "repository": { 28 | "type": "git", 29 | "url": "https://github.com/charliekassel/vuejs-autocomplete" 30 | }, 31 | "bugs": { 32 | "url": "https://github.com/charliekassel/vuejs-autocomplete/issues" 33 | }, 34 | "dependencies": {}, 35 | "devDependencies": { 36 | "@vue/test-utils": "^1.0.0-beta.12", 37 | "autoprefixer": "^6.7.2", 38 | "babel-core": "^6.22.1", 39 | "babel-eslint": "^7.1.1", 40 | "babel-jest": "^22.4.1", 41 | "babel-loader": "^6.2.10", 42 | "babel-plugin-transform-runtime": "^6.22.0", 43 | "babel-preset-env": "^1.3.2", 44 | "babel-preset-stage-2": "^6.22.0", 45 | "babel-register": "^6.22.0", 46 | "chai": "^3.5.0", 47 | "chalk": "^1.1.3", 48 | "connect-history-api-fallback": "^1.3.0", 49 | "copy-webpack-plugin": "^4.0.1", 50 | "coveralls": "^3.0.0", 51 | "cross-env": "^4.0.0", 52 | "css-loader": "^0.28.0", 53 | "eslint": "^3.19.0", 54 | "eslint-config-standard": "^6.2.1", 55 | "eslint-friendly-formatter": "^2.0.7", 56 | "eslint-loader": "^1.7.1", 57 | "eslint-plugin-html": "^2.0.0", 58 | "eslint-plugin-promise": "^3.4.0", 59 | "eslint-plugin-standard": "^2.0.1", 60 | "eslint-plugin-vue": "^4.3.0", 61 | "eventsource-polyfill": "^0.9.6", 62 | "express": "^4.14.1", 63 | "extract-text-webpack-plugin": "^2.0.0", 64 | "file-loader": "^0.11.1", 65 | "friendly-errors-webpack-plugin": "^1.1.3", 66 | "html-webpack-plugin": "^2.28.0", 67 | "http-proxy-middleware": "^0.17.3", 68 | "inject-loader": "^3.0.0", 69 | "jest": "^22.4.2", 70 | "jest-fetch-mock": "^1.4.2", 71 | "jest-serializer-vue": "^0.3.0", 72 | "lodash": "^4.17.5", 73 | "lolex": "^1.5.2", 74 | "opn": "^4.0.2", 75 | "optimize-css-assets-webpack-plugin": "^1.3.0", 76 | "ora": "^1.2.0", 77 | "phantomjs-prebuilt": "^2.1.14", 78 | "rimraf": "^2.6.0", 79 | "semver": "^5.3.0", 80 | "shelljs": "^0.7.6", 81 | "sinon": "^2.1.0", 82 | "sinon-chai": "^2.8.0", 83 | "stylus": "^0.54.5", 84 | "stylus-loader": "^3.0.1", 85 | "url-loader": "^0.5.8", 86 | "vue": "^2.5.13", 87 | "vue-jest": "^2.1.0", 88 | "vue-loader": "^12.1.0", 89 | "vue-server-renderer": "^2.5.13", 90 | "vue-style-loader": "^3.0.1", 91 | "vue-template-compiler": "^2.3.3", 92 | "webpack": "^2.6.1", 93 | "webpack-bundle-analyzer": "^2.2.1", 94 | "webpack-dev-middleware": "^1.10.0", 95 | "webpack-hot-middleware": "^2.18.0", 96 | "webpack-merge": "^4.1.0" 97 | }, 98 | "engines": { 99 | "node": ">= 4.0.0", 100 | "npm": ">= 3.0.0" 101 | }, 102 | "browserslist": [ 103 | "> 1%", 104 | "last 2 versions", 105 | "not ie <= 8" 106 | ] 107 | } 108 | -------------------------------------------------------------------------------- /src/Demo.vue: -------------------------------------------------------------------------------- 1 | 203 | 204 | 245 | 246 | 307 | -------------------------------------------------------------------------------- /src/assets/close.svg: -------------------------------------------------------------------------------- 1 | 3 | 4 | 9 | 10 | 11 | -------------------------------------------------------------------------------- /src/assets/loading.svg: -------------------------------------------------------------------------------- 1 | 3 | 4 | 6 | 8 | 10 | 12 | 14 | 16 | 18 | 20 | 21 | 22 | -------------------------------------------------------------------------------- /src/assets/search.svg: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 7 | -------------------------------------------------------------------------------- /src/components/Autocomplete.vue: -------------------------------------------------------------------------------- 1 | 63 | 64 | 533 | 534 | 604 | -------------------------------------------------------------------------------- /src/main.js: -------------------------------------------------------------------------------- 1 | import Vue from 'vue' 2 | import Demo from './Demo' 3 | 4 | Vue.config.productionTip = false 5 | 6 | /* eslint-disable no-new */ 7 | new Vue({ 8 | el: '#app', 9 | render: h => h(Demo) 10 | }) 11 | -------------------------------------------------------------------------------- /static/.gitkeep: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/charliekassel/vuejs-autocomplete/6feca77fcfce372d27b5380670fe22aaa2a2bada/static/.gitkeep -------------------------------------------------------------------------------- /test/unit/.eslintrc: -------------------------------------------------------------------------------- 1 | { 2 | "env": { 3 | "jest": true 4 | }, 5 | "globals": { 6 | } 7 | } 8 | -------------------------------------------------------------------------------- /test/unit/jest.conf.js: -------------------------------------------------------------------------------- 1 | const path = require('path') 2 | 3 | module.exports = { 4 | rootDir: path.resolve(__dirname, '../../'), 5 | moduleFileExtensions: [ 6 | 'js', 7 | 'json', 8 | 'vue' 9 | ], 10 | moduleNameMapper: { 11 | '^@/(.*)$': '/src/$1' 12 | }, 13 | transform: { 14 | '^.+\\.js$': '/node_modules/babel-jest', 15 | '.*\\.(vue)$': '/node_modules/vue-jest' 16 | }, 17 | snapshotSerializers: ['/node_modules/jest-serializer-vue'], 18 | setupFiles: ['/test/unit/setup'], 19 | coverageDirectory: '/test/unit/coverage', 20 | collectCoverageFrom: [ 21 | 'src/**/*.{js,vue}', 22 | '!src/main.js', 23 | '!src/Demo.vue', 24 | '!**/node_modules/**' 25 | ], 26 | testURL : 'http://localhost/' 27 | } 28 | -------------------------------------------------------------------------------- /test/unit/setup.js: -------------------------------------------------------------------------------- 1 | import Vue from 'vue' 2 | 3 | Vue.config.productionTip = false 4 | -------------------------------------------------------------------------------- /test/unit/specs/DomRendering.spec.js: -------------------------------------------------------------------------------- 1 | import Autocomplete from '@/components/Autocomplete' 2 | import {shallow} from '@vue/test-utils' 3 | 4 | describe('Renders correct DOM', () => { 5 | let wrapper 6 | beforeEach(() => { 7 | wrapper = shallow(Autocomplete, { 8 | propsData: { 9 | source: 'localhost' 10 | } 11 | }) 12 | }) 13 | 14 | it('Has inputs', () => { 15 | expect(wrapper.find('input')).toBeTruthy() 16 | expect(wrapper.findAll('input')).toHaveLength(2) 17 | }) 18 | 19 | it('renders a result list', () => { 20 | wrapper.setData({ 21 | results: [ 22 | {id: 1, name: 'a'}, 23 | {id: 2, name: 'b'} 24 | ] 25 | }) 26 | expect(wrapper.findAll('.autocomplete__results__item')).toHaveLength(2) 27 | }) 28 | 29 | it('renders a result list with a display function', () => { 30 | wrapper.setProps({ 31 | resultsDisplay: obj => obj.city 32 | }) 33 | wrapper.setData({ 34 | results: [ 35 | {id: 1, city: 'London'}, 36 | {id: 2, city: 'New York'} 37 | ] 38 | }) 39 | const items = wrapper.findAll('.autocomplete__results__item') 40 | expect(items.at(0).text()).toEqual('London') 41 | expect(items.at(1).text()).toEqual('New York') 42 | }) 43 | 44 | it('throws when results do not contain expected property', () => { 45 | const results = [ 46 | {id: 1, city: 'London'}, 47 | {id: 2, city: 'New York'} 48 | ] 49 | expect(() => { 50 | wrapper.vm.formatDisplay(results) 51 | }).toThrowError(Error) 52 | }) 53 | 54 | it('throws when formatDisplay is not expected type', () => { 55 | wrapper.setProps({ 56 | resultsDisplay: {} 57 | }) 58 | expect(() => { 59 | wrapper.vm.formatDisplay([]) 60 | }).toThrowError(TypeError) 61 | }) 62 | 63 | it('sets isFocussed property when the input is in focus', () => { 64 | wrapper.find('input').trigger('focus') 65 | expect(wrapper.vm.isFocussed).toEqual(true) 66 | }) 67 | 68 | it('sets isFocussed property to false when the input is blurred', () => { 69 | wrapper.setData({ 70 | isFocussed: true 71 | }) 72 | wrapper.find('input').trigger('blur') 73 | expect(wrapper.vm.isFocussed).toEqual(false) 74 | }) 75 | 76 | it('setEventListener returns true when setting', () => { 77 | expect(wrapper.vm.setEventListener()).toEqual(true) 78 | }) 79 | 80 | it('setEventListener returns true when already set', () => { 81 | wrapper.vm.setEventListener() 82 | expect(wrapper.vm.setEventListener()).toEqual(false) 83 | }) 84 | 85 | it('closes results list when clicked outside the component', () => { 86 | wrapper.setProps({ 87 | source: [ 88 | {id: 1, name: 'abc'}, 89 | {id: 2, name: 'def'} 90 | ] 91 | }) 92 | wrapper.setData({ 93 | display: 'abc' 94 | }) 95 | wrapper.vm.search() 96 | expect(wrapper.vm.results).toHaveLength(1) 97 | document.body.click() 98 | expect(wrapper.vm.results).toBeFalsy() 99 | }) 100 | 101 | it('clears display value when closing results', () => { 102 | wrapper.setProps({ 103 | source: [ 104 | {id: 1, name: 'abc'}, 105 | {id: 2, name: 'def'} 106 | ] 107 | }) 108 | wrapper.setData({ 109 | display: 'abc' 110 | }) 111 | wrapper.vm.search() 112 | document.body.click() 113 | expect(wrapper.vm.display).toBeNull() 114 | expect(wrapper.vm.value).toBeNull() 115 | }) 116 | 117 | it('retains initialValue when closing results list', () => { 118 | wrapper = shallow(Autocomplete, { 119 | propsData: { 120 | source: [ 121 | {id: 1, name: 'abc'}, 122 | {id: 2, name: 'def'} 123 | ], 124 | initialDisplay: 'def', 125 | initialValue: 2 126 | } 127 | }) 128 | wrapper.setData({ 129 | display: 'abc' 130 | }) 131 | wrapper.vm.search() 132 | document.body.click() 133 | expect(wrapper.vm.display).toEqual('def') 134 | expect(wrapper.vm.value).toEqual(2) 135 | }) 136 | }) 137 | -------------------------------------------------------------------------------- /test/unit/specs/ResultsInteraction.spec.js: -------------------------------------------------------------------------------- 1 | import Autocomplete from '@/components/Autocomplete' 2 | import {shallow} from '@vue/test-utils' 3 | 4 | describe('Results interaction', () => { 5 | let wrapper 6 | beforeEach(() => { 7 | wrapper = shallow(Autocomplete, { 8 | propsData: { 9 | source: 'localhost' 10 | } 11 | }) 12 | }) 13 | 14 | it('should format results with default properties', () => { 15 | let display = wrapper.vm.formatDisplay({id: 1, name: 'abc'}) 16 | expect(display).toEqual('abc') 17 | }) 18 | 19 | it('should format results using a custom property', () => { 20 | wrapper.setProps({ 21 | resultsDisplay: 'city' 22 | }) 23 | let display = wrapper.vm.formatDisplay({id: 1, name: 'abc', city: 'London'}) 24 | expect(display).toEqual('London') 25 | }) 26 | 27 | it('should format results using a function', () => { 28 | wrapper.setProps({ 29 | resultsDisplay: (result) => `${result.id}: ${result.custom}` 30 | }) 31 | let display = wrapper.vm.formatDisplay({id: 1, name: 'abc', custom: 'bananas'}) 32 | expect(display).toEqual('1: bananas') 33 | }) 34 | 35 | it('should navigate through the results list', () => { 36 | wrapper.setData({ 37 | results: [ 38 | {id: 1, name: 'abc'}, 39 | {id: 2, name: 'def'}, 40 | {id: 3, name: 'ghi'} 41 | ] 42 | }) 43 | wrapper.vm.down() 44 | expect(wrapper.vm.results[wrapper.vm.selectedIndex].id).toEqual(1) 45 | wrapper.vm.down() 46 | expect(wrapper.vm.results[wrapper.vm.selectedIndex].id).toEqual(2) 47 | wrapper.vm.down() 48 | wrapper.vm.down() 49 | expect(wrapper.vm.results[wrapper.vm.selectedIndex].id).toEqual(1) 50 | wrapper.vm.up() 51 | expect(wrapper.vm.results[wrapper.vm.selectedIndex].id).toEqual(3) 52 | }) 53 | 54 | it('should navigate through the results list via keydown', () => { 55 | wrapper.setData({ 56 | results: [ 57 | {id: 1, name: 'abc'}, 58 | {id: 2, name: 'def'}, 59 | {id: 3, name: 'ghi'} 60 | ] 61 | }) 62 | const input = wrapper.find('input') 63 | input.trigger('keydown.down') 64 | expect(wrapper.vm.results[wrapper.vm.selectedIndex].id).toEqual(1) 65 | input.trigger('keydown.up') 66 | expect(wrapper.vm.results[wrapper.vm.selectedIndex].id).toEqual(3) 67 | }) 68 | 69 | it('should focus on the last results when initial calling up', () => { 70 | wrapper.setData({ 71 | results: [ 72 | {id: 1, name: 'abc'}, 73 | {id: 2, name: 'def'}, 74 | {id: 3, name: 'ghi'} 75 | ] 76 | }) 77 | wrapper.vm.up() 78 | expect(wrapper.vm.results[wrapper.vm.selectedIndex].id).toEqual(3) 79 | }) 80 | 81 | it('clears results', () => { 82 | wrapper.setProps({ 83 | source: [ 84 | {id: 1, name: 'abc'}, 85 | {id: 2, name: 'def'}, 86 | {id: 3, name: 'ghi'} 87 | ] 88 | }) 89 | wrapper.setData({ 90 | display: 'abc' 91 | }) 92 | wrapper.vm.search() 93 | wrapper.vm.clear() 94 | expect(wrapper.vm.display).toBeNull() 95 | expect(wrapper.vm.value).toBeNull() 96 | expect(wrapper.vm.results).toBeNull() 97 | expect(wrapper.vm.error).toBeNull() 98 | expect(wrapper.emitted().clear).toBeTruthy() 99 | }) 100 | 101 | it('selects a result', () => { 102 | wrapper.vm.select({id: 1, name: 'abc'}) 103 | expect(wrapper.vm.value).toEqual(1) 104 | expect(wrapper.vm.display).toEqual('abc') 105 | expect(wrapper.vm.selectedDisplay).toEqual('abc') 106 | expect(wrapper.emitted().selected).toBeTruthy() 107 | expect(wrapper.emitted().selected[0][0].value).toEqual(1) 108 | expect(wrapper.emitted().selected[0][0].display).toEqual('abc') 109 | }) 110 | 111 | it('does not select nothing', () => { 112 | expect(wrapper.vm.select()).toBeFalsy 113 | }) 114 | 115 | it('selects when enter is pressed', () => { 116 | wrapper.setData({ 117 | results: [ 118 | {id: 1, name: 'abc'}, 119 | {id: 2, name: 'def'}, 120 | {id: 3, name: 'ghi'} 121 | ] 122 | }) 123 | const input = wrapper.find('input') 124 | input.trigger('keydown.down') 125 | input.trigger('keydown.enter') 126 | expect(wrapper.vm.value).toEqual(1) 127 | expect(wrapper.emitted().enter[0][0]).toEqual('abc') 128 | }) 129 | 130 | it('emits an event when nothing is selected', () => { 131 | const input = wrapper.find('input') 132 | input.trigger('keydown.enter') 133 | expect(wrapper.emitted().nothingSelected).toBeTruthy() 134 | }) 135 | }) 136 | -------------------------------------------------------------------------------- /test/unit/specs/SearchResultsArrayLikeSource.spec.js: -------------------------------------------------------------------------------- 1 | import Autocomplete from '@/components/Autocomplete' 2 | import {shallow} from '@vue/test-utils' 3 | 4 | describe('Search Results - Array Like', () => { 5 | let wrapper 6 | beforeEach(() => { 7 | wrapper = shallow(Autocomplete, { 8 | propsData: { 9 | source: [ 10 | {id: 1, name: 'abc'}, 11 | {id: 2, name: 'def'} 12 | ] 13 | } 14 | }) 15 | }) 16 | 17 | it('data source can be an array', () => { 18 | wrapper.setData({ 19 | display: 'abc' 20 | }) 21 | wrapper.vm.search() 22 | wrapper.update() 23 | 24 | const items = wrapper.findAll('.autocomplete__results__item') 25 | expect(items).toHaveLength(1) 26 | expect(items.at(0).text()).toEqual('abc') 27 | }) 28 | 29 | it('shows all results when data source is an array and search is empty', () => { 30 | wrapper.setData({ 31 | display: '' 32 | }) 33 | wrapper.vm.search() 34 | wrapper.update() 35 | 36 | const items = wrapper.findAll('.autocomplete__results__item') 37 | expect(items).toHaveLength(2) 38 | }) 39 | 40 | it('emits results', () => { 41 | wrapper.vm.search() 42 | expect(wrapper.emitted().results).toBeTruthy() 43 | }) 44 | }) 45 | -------------------------------------------------------------------------------- /test/unit/specs/SearchResultsResourceSearch.spec.js: -------------------------------------------------------------------------------- 1 | import Autocomplete from '@/components/Autocomplete' 2 | import {shallow} from '@vue/test-utils' 3 | import sinon from 'sinon' 4 | import fetchMock from 'jest-fetch-mock' 5 | 6 | global.fetch = fetchMock 7 | 8 | describe('Search Results - Resource', () => { 9 | let wrapper 10 | beforeEach(() => { 11 | wrapper = shallow(Autocomplete, { 12 | propsData: { 13 | source: 'localhost', 14 | resultsProperty: 'data' 15 | } 16 | }) 17 | }) 18 | 19 | it('should debounce a resource search', () => { 20 | wrapper.setData({ 21 | display: 'abc' 22 | }) 23 | const clock = sinon.useFakeTimers() 24 | const spy = jest.spyOn(wrapper.vm, 'request') 25 | wrapper.vm.search() 26 | expect(spy).toHaveBeenCalledTimes(0) 27 | clock.tick(500) 28 | wrapper.update() 29 | expect(spy).toHaveBeenCalledTimes(1) 30 | }) 31 | 32 | it('should not search without display data', () => { 33 | wrapper.vm.search() 34 | const spy = jest.spyOn(wrapper.vm, 'resourceSearch') 35 | expect(spy).toHaveBeenCalledTimes(0) 36 | }) 37 | 38 | it('should not search without display data - function source', () => { 39 | wrapper.setProps({ 40 | source: (query) => `localhost/search?my-query-param=${query}` 41 | }) 42 | wrapper.vm.search() 43 | const spy = jest.spyOn(wrapper.vm, 'resourceSearch') 44 | expect(spy).toHaveBeenCalledTimes(0) 45 | }) 46 | 47 | it('should handle results returned as an array', async () => { 48 | wrapper.setProps({ 49 | resultsProperty: null 50 | }) 51 | fetch.mockResponse(JSON.stringify([{id: 1, name: 'abc'}, {id: 2, name: 'def'}])) 52 | await wrapper.vm.request('localhost') 53 | expect(wrapper.vm.results).toHaveLength(2) 54 | expect(wrapper.emitted().results).toBeTruthy() 55 | const items = wrapper.findAll('.autocomplete__results__item') 56 | expect(items).toHaveLength(2) 57 | }) 58 | 59 | it('should handle set results as an array with unexpected response', async () => { 60 | fetch.mockResponse(JSON.stringify(1)) 61 | await wrapper.vm.request('localhost') 62 | expect(wrapper.vm.results).toHaveLength(0) 63 | expect(wrapper.emitted().noResults).toBeTruthy() 64 | const items = wrapper.findAll('.autocomplete__results__item') 65 | expect(items).toHaveLength(0) 66 | }) 67 | 68 | it('should show results', async () => { 69 | fetch.mockResponse(JSON.stringify({data: [{id: 1, name: 'abc'}, {id: 2, name: 'def'}]})) 70 | await wrapper.vm.request('localhost') 71 | expect(wrapper.vm.results).toHaveLength(2) 72 | expect(wrapper.emitted().results).toBeTruthy() 73 | const items = wrapper.findAll('.autocomplete__results__item') 74 | expect(items).toHaveLength(2) 75 | }) 76 | 77 | it('should show no results', async () => { 78 | fetch.mockResponse(JSON.stringify({data: []})) 79 | wrapper.vm.focus() 80 | await wrapper.vm.request('localhost') 81 | expect(wrapper.vm.results).toHaveLength(0) 82 | expect(wrapper.emitted().noResults).toBeTruthy() 83 | expect(wrapper.find('.autocomplete__no-results')).toBeDefined() 84 | expect(wrapper.find('.autocomplete__no-results').text()).toEqual('No Results.') 85 | }) 86 | 87 | it('should construct the source url from a function', () => { 88 | fetch.mockResponse(JSON.stringify({data: [{id: 1, name: 'abc'}]})) 89 | const spy = jest.spyOn(wrapper.vm, 'resourceSearch') 90 | wrapper.setProps({ 91 | source: (query) => `localhost/search?my-query-param=${query}` 92 | }) 93 | wrapper.setData({ 94 | display: 'abc' 95 | }) 96 | wrapper.vm.search() 97 | expect(spy).toHaveBeenCalledTimes(1) 98 | expect(spy).toHaveBeenCalledWith('localhost/search?my-query-param=abc') 99 | }) 100 | 101 | it('should throw when source is not an expected type', () => { 102 | wrapper.setProps({ 103 | source: {} 104 | }) 105 | expect(() => wrapper.vm.search()).toThrowError(TypeError) 106 | }) 107 | 108 | it('should set custom headers', () => { 109 | wrapper.setProps({ 110 | requestHeaders: { 111 | 'x-my-custom-header': 'foobar' 112 | } 113 | }) 114 | expect(wrapper.vm.getHeaders()).toBeInstanceOf(Headers) 115 | expect(wrapper.vm.getHeaders().get('x-my-custom-header')).toEqual('foobar') 116 | }) 117 | 118 | it('sets results with a custom formatter', async () => { 119 | wrapper.setProps({ 120 | resultsProperty: null, 121 | resultsFormatter: response => response.map(data => ({id: data.id, name: data.item.name})) 122 | }) 123 | fetch.mockResponse(JSON.stringify([{id: 1, item: {name: 'abc'}}, {id: 2, item: {name: 'def'}}])) 124 | await wrapper.vm.request('localhost') 125 | expect(wrapper.vm.results).toHaveLength(2) 126 | expect(wrapper.vm.results[0].name).toEqual('abc') 127 | expect(wrapper.vm.results[1].name).toEqual('def') 128 | }) 129 | }) 130 | --------------------------------------------------------------------------------