Keep search callback + improvements but remove ajax search for now

This commit is contained in:
Josh Johnson 2016-09-27 20:07:32 +01:00
parent a990206cef
commit 9d5a6cc41e
7 changed files with 375 additions and 380 deletions

View file

@ -48,6 +48,7 @@ A vanilla, lightweight (~15kb gzipped 🎉), configurable select box/text input
delimiter: ',',
paste: true,
search: true,
searchFloor: 1,
flip: true,
regexFilter: null,
shouldSort: true,
@ -86,13 +87,13 @@ A vanilla, lightweight (~15kb gzipped 🎉), configurable select box/text input
flippedState: 'is-flipped',
loadingState: 'is-loading',
},
callbackOnInit: () => {},
callbackOnAddItem: (id, value, passedInput) => {},
callbackOnRemoveItem: (id, value, passedInput) => {},
callbackOnHighlightItem: (id, value, passedInput) => {},
callbackOnUnhighlightItem: (id, value, passedInput) => {},
callbackOnChange: (value, passedInput) => {},
callbackOnItemSearch: (value, fn, passedInput) => {},
callbackOnInit: null,
callbackOnAddItem: null,
callbackOnRemoveItem: null,
callbackOnHighlightItem: null,
callbackOnUnhighlightItem: null,
callbackOnChange: null,
callbackOnSearch: null,
});
</script>
```
@ -223,6 +224,13 @@ Pass an array of objects:
**Usage:** Whether a user should be allowed to search avaiable choices. Note that multiple select boxes will always show search inputs.
### searchFloor
**Type:** `Number` **Default:** `1`
**Input types affected:** `select-one`, `select-multiple`
**Usage:** The minimum length a search value should be before choices are searched.
### flip
**Type:** `Boolean` **Default:** `true`
@ -361,42 +369,52 @@ classNames: {
**Usage:** Classes added to HTML generated by Choices. By default classnames follow the [BEM](http://csswizardry.com/2013/01/mindbemding-getting-your-head-round-bem-syntax/) notation.
### callbackOnInit
**Type:** `Function` **Default:** `() => {}`
**Type:** `Function` **Default:** `null`
**Input types affected:** `text`, `select-one`, `select-multiple`
**Usage:** Function to run once Choices initialises.
### callbackOnAddItem
**Type:** `Function` **Default:** `(id, value, passedInput) => {}`
**Type:** `Function` **Default:** `null` **Arguments:** `id, value, passedInput`
**Input types affected:** `text`, `select-one`, `select-multiple`
**Usage:** Function to run each time an item is added (programmatically or by the user).
**Example:**
```js
const example = new Choices(element, {
callbackOnAddItem: (id, value, passedInput) => {
// do something creative here...
},
};
```
### callbackOnRemoveItem
**Type:** `Function` **Default:** `(id, value, passedInput) => {}`
**Type:** `Function` **Default:** `null` **Arguments:** `id, value, passedInput`
**Input types affected:** `text`, `select-one`, `select-multiple`
**Usage:** Function to run each time an item is removed (programmatically or by the user).
### callbackOnHighlightItem
**Type:** `Function` **Default:** `(id, value, passedInput) => {}`
**Type:** `Function` **Default:** `null` **Arguments:** `id, value, passedInput`
**Input types affected:** `text`, `select-multiple`
**Usage:** Function to run each time an item is highlighted.
### callbackOnUnhighlightItem
**Type:** `Function` **Default:** `(id, value, passedInput) => {}`
**Type:** `Function` **Default:** `null` **Arguments:** `id, value, passedInput`
**Input types affected:** `text`, `select-multiple`
**Usage:** Function to run each time an item is unhighlighted.
### callbackOnChange
**Type:** `Function` **Default:** `(value, passedInput) => {}`
**Type:** `Function` **Default:** `null` **Arguments:** `value, passedInput`
**Input types affected:** `text`, `select-one`, `select-multiple`

View file

@ -57,6 +57,7 @@ export default class Choices {
delimiter: ',',
paste: true,
search: true,
searchFloor: 1,
flip: true,
regexFilter: null,
shouldSort: true,
@ -96,13 +97,13 @@ export default class Choices {
flippedState: 'is-flipped',
loadingState: 'is-loading',
},
callbackOnInit: () => {},
callbackOnAddItem: (id, value, passedInput) => {},
callbackOnRemoveItem: (id, value, passedInput) => {},
callbackOnHighlightItem: (id, value, passedInput) => {},
callbackOnUnhighlightItem: (id, value, passedInput) => {},
callbackOnChange: (value, passedInput) => {},
callbackOnItemSearch: null,
callbackOnInit: null,
callbackOnAddItem: null,
callbackOnRemoveItem: null,
callbackOnHighlightItem: null,
callbackOnUnhighlightItem: null,
callbackOnChange: null,
callbackOnSearch: null,
};
// Merge options with user options
@ -162,8 +163,8 @@ export default class Choices {
this.wasTap = true;
// Cutting the mustard
const cuttingTheMustard = 'querySelector' in document && 'addEventListener' in document && 'classList' in document.createElement(
'div');
const cuttingTheMustard = 'querySelector' in document && 'addEventListener' in document
&& 'classList' in document.createElement('div');
if (!cuttingTheMustard) console.error('Choices: Your browser doesn\'t support Choices');
// Input type check
@ -268,7 +269,6 @@ export default class Choices {
if (this.passedElement.type === 'select-one') {
return choice.groupId === group.id;
}
return choice.groupId === group.id && !choice.selected;
});
@ -834,7 +834,8 @@ export default class Choices {
if (this.passedElement.type === 'select-one' || this.passedElement.type === 'select-multiple') {
// Show loading text
this._handleLoadingState();
fn(this._getAjaxCallback());
// Run callback
fn(this._ajaxCallback());
}
}
return this;
@ -1068,17 +1069,19 @@ export default class Choices {
/**
* Retrieve the callback used to populate component's choices in an async way.
* @returns {function(*=, *=, *)} the callback as a function.
* @returns {Function} The callback as a function.
* @private
*/
_getAjaxCallback() {
_ajaxCallback() {
return (results, value, label) => {
if (!isType('Array', results) || !value) return;
if (results && results.length) {
if (!results || !value) return;
const parsedResults = isType('Object', results) ? [results] : results;
if (parsedResults && isType('Array', parsedResults) && parsedResults.length) {
// Remove loading states/text
this._handleLoadingState(false);
// Add each result as a choice
results.forEach((result) => {
parsedResults.forEach((result) => {
this._addChoice(false, false, result[value], result[label]);
});
}
@ -1092,7 +1095,7 @@ export default class Choices {
* @return
* @private
*/
_filterChoices(value) {
_searchChoices(value) {
const newValue = isType('String', value) ? value.trim() : value;
const currentValue = isType('String', this.currentValue) ? this.currentValue.trim() : this.currentValue;
@ -1122,30 +1125,24 @@ export default class Choices {
*/
_handleSearch(value) {
if (!value) return;
// Run callback if it is a function
if (this.input === document.activeElement) {
// If a custom callback has been provided, use it
if (this.config.callbackOnItemSearch) {
const callback = this.config.callbackOnItemSearch;
if (isType('Function', callback)) {
if(this.passedElement.type !== 'text') {
// Reset choices
this._clearChoices();
// Reset loading state/text
this._handleLoadingState();
}
// Run callback
callback(value, this._getAjaxCallback(), this.passedElement);
} else {
console.error('callbackOnOnItemSearch: Callback is not a function');
}
} else {
const choices = this.store.getChoices();
const hasUnactiveChoices = choices.some((option) => option.active !== true);
// Run callback if it is a function
if (this.input === document.activeElement) {
// Check that we have a value to search and the input was an alphanumeric character
if (value && value.length > 1) {
if (value && value.length > this.config.searchFloor) {
// Filter available choices
this._filterChoices(value);
this._searchChoices(value);
// Run callback if it is a function
if (this.config.callbackOnSearch) {
const callback = this.config.callbackOnSearch;
if (isType('Function', callback)) {
callback(value, this.passedElement);
} else {
console.error('callbackOnSearch: Callback is not a function');
}
}
} else if (hasUnactiveChoices) {
// Otherwise reset choices to active
this.isSearching = false;
@ -1153,7 +1150,6 @@ export default class Choices {
}
}
}
}
/**
* Trigger event listeners
@ -1331,6 +1327,7 @@ export default class Choices {
// If backspace or delete key is pressed and the input has no value
if (hasFocusedInput && !e.target.value && this.passedElement.type !== 'select-one') {
this._handleBackspace(activeItems);
this._handleLoadingState();
e.preventDefault();
}
};

View file

@ -29,6 +29,9 @@ label {
font-weight: 500;
cursor: pointer; }
p {
margin-top: 0; }
hr {
display: block;
margin: 36px 0;

View file

@ -1 +1 @@
*{-webkit-font-smoothing:antialiased;-moz-osx-font-smoothing:grayscale}*,:after,:before{box-sizing:border-box}body,html{position:relative;margin:0;width:100%;height:100%}body{font-family:"Helvetica Neue",Helvetica,Arial,"Lucida Grande",sans-serif;font-size:16px;line-height:1.4;color:#fff;background-color:#333;overflow-x:hidden}hr,label{display:block}label{margin-bottom:8px;font-size:14px;font-weight:500;cursor:pointer}hr{margin:36px 0;border:0;border-bottom:1px solid #eaeaea;height:1px}h1,h2,h3,h4,h5,h6{margin-top:0;margin-bottom:12px;font-weight:400;line-height:1.2}a,a:focus,a:visited{color:#fff;text-decoration:none;font-weight:600}.form-control{display:block;width:100%;background-color:#f9f9f9;padding:12px;border:1px solid #ddd;border-radius:2.5px;font-size:14px;-webkit-appearance:none;-moz-appearance:none;appearance:none;margin-bottom:24px}.h1,h1{font-size:32px}.h2,h2{font-size:24px}.h3,h3{font-size:20px}.h4,h4{font-size:18px}.h5,h5{font-size:16px}.h6,h6{font-size:14px}.container{display:block;margin:auto;max-width:40em;padding:48px}@media (max-width:620px){.container{padding:0}}.section{background-color:#fff;padding:24px;color:#333}.section a,.section a:focus,.section a:visited{color:#00bcd4}.logo{width:100%;height:auto;display:inline-block;max-width:100%;vertical-align:top;padding:6px 0}.visible-ie{display:none}
*{-webkit-font-smoothing:antialiased;-moz-osx-font-smoothing:grayscale}*,:after,:before{box-sizing:border-box}body,html{position:relative;margin:0;width:100%;height:100%}body{font-family:"Helvetica Neue",Helvetica,Arial,"Lucida Grande",sans-serif;font-size:16px;line-height:1.4;color:#fff;background-color:#333;overflow-x:hidden}hr,label{display:block}label{margin-bottom:8px;font-size:14px;font-weight:500;cursor:pointer}p{margin-top:0}hr{margin:36px 0;border:0;border-bottom:1px solid #eaeaea;height:1px}h1,h2,h3,h4,h5,h6{margin-top:0;margin-bottom:12px;font-weight:400;line-height:1.2}a,a:focus,a:visited{color:#fff;text-decoration:none;font-weight:600}.form-control{display:block;width:100%;background-color:#f9f9f9;padding:12px;border:1px solid #ddd;border-radius:2.5px;font-size:14px;-webkit-appearance:none;-moz-appearance:none;appearance:none;margin-bottom:24px}.h1,h1{font-size:32px}.h2,h2{font-size:24px}.h3,h3{font-size:20px}.h4,h4{font-size:18px}.h5,h5{font-size:16px}.h6,h6{font-size:14px}.container{display:block;margin:auto;max-width:40em;padding:48px}@media (max-width:620px){.container{padding:0}}.section{background-color:#fff;padding:24px;color:#333}.section a,.section a:focus,.section a:visited{color:#00bcd4}.logo{width:100%;height:auto;display:inline-block;max-width:100%;vertical-align:top;padding:6px 0}.visible-ie{display:none}

View file

@ -45,6 +45,8 @@ label {
cursor: pointer;
}
p { margin-top: 0; }
hr {
display: block;
margin: $global-guttering*1.5 0;

View file

@ -122,9 +122,6 @@
<option value="Dropdown item 4" disabled>Dropdown item 4</option>
</select>
<label for="choices-multiple-xhr-search">Search among choices fetched from an URL</label>
<select class="form-control" name="choices-multiple-xhr-search" id="choices-multiple-xhr-search" placeholder="Search music" multiple></select>
<hr>
<h2>Single select input</h2>
@ -137,6 +134,7 @@
</select>
<label for="choices-single-remote-fetch">Options from remote source (Fetch API)</label>
<p><small>If this doesn't work, the Discogs rate limit has probably been reached. Try again later!</small></p>
<select class="form-control" name="choices-single-remote-fetch" id="choices-single-remote-fetch" placeholder="Pick an Arctic Monkeys record"></select>
<label for="choices-single-remove-xhr">Options from remote source (XHR) &amp; remove button</label>
@ -239,7 +237,7 @@
</div>
<script>
document.addEventListener('DOMContentLoaded', function() {
var example1 = new Choices(document.getElementById('choices-text-remove-button'), {
var textRemove = new Choices(document.getElementById('choices-text-remove-button'), {
delimiter: ',',
editItems: true,
maxItemCount: 5,
@ -252,32 +250,32 @@
},
});
var example2 = new Choices('#choices-text-unique-values', {
var textUniqueVals = new Choices('#choices-text-unique-values', {
paste: false,
duplicateItems: false,
editItems: true,
});
var example3 = new Choices('#choices-text-email-filter', {
var textEmailFilter = new Choices('#choices-text-email-filter', {
editItems: true,
regexFilter: /^(([^<>()\[\]\\.,;:\s@"]+(\.[^<>()\[\]\\.,;:\s@"]+)*)|(".+"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/,
});
var example4 = new Choices('#choices-text-disabled', {
var textDisabled = new Choices('#choices-text-disabled', {
addItems: false,
removeItems: false,
}).disable();
var example5 = new Choices('#choices-text-prepend-append-value', {
var textPrependAppendVal = new Choices('#choices-text-prepend-append-value', {
prependValue: 'item-',
appendValue: '-' + Date.now(),
}).removeActiveItems();
var example7 = new Choices('#choices-text-preset-values', {
var textPresetVal = new Choices('#choices-text-preset-values', {
items: ['josh@joshuajohnson.co.uk', { value: 'joe@bloggs.co.uk', label: 'Joe Bloggs' } ],
});
var example9 = new Choices('#choices-multiple-remote-fetch', {
var multipleFetch = new Choices('#choices-multiple-remote-fetch', {
placeholder: true,
placeholderValue: 'Pick an Strokes record',
maxItemCount: 5,
@ -294,7 +292,7 @@
});
});
var example10 = new Choices('#choices-single-remote-fetch', {
var singleFetch = new Choices('#choices-single-remote-fetch', {
placeholder: true,
placeholderValue: 'Pick an Arctic Monkeys record'
}).ajax(function(callback) {
@ -302,7 +300,7 @@
.then(function(response) {
response.json().then(function(data) {
callback(data.releases, 'title', 'title');
example10.setValueByChoice('Fake Tales Of San Francisco');
singleFetch.setValueByChoice('Fake Tales Of San Francisco');
});
})
.catch(function(error) {
@ -310,7 +308,7 @@
});
});
var example11 = new Choices('#choices-single-remove-xhr', {
var singleXhrRemove = new Choices('#choices-single-remove-xhr', {
removeItemButton: true,
}).ajax(function(callback) {
var request = new XMLHttpRequest();
@ -323,7 +321,7 @@
if (status === 200) {
data = JSON.parse(request.responseText);
callback(data.releases, 'title', 'title');
example11.setValueByChoice('How Soon Is Now?');
singleXhrRemove.setValueByChoice('How Soon Is Now?');
} else {
console.error(status);
}
@ -332,35 +330,12 @@
request.send();
});
var example12 = new Choices('#choices-multiple-xhr-search', {
removeItemButton: true,
callbackOnItemSearch: function (value, fn, passedInput) {
var request = new XMLHttpRequest();
var url = 'https://api.discogs.com/database/search?token=QBRmstCkwXEvCjTclCpumbtNwvVkEzGAdELXyRyW&type=artist?q=' + value;
request.open('get', url, true);
request.onreadystatechange = function() {
var status;
var data;
if (request.readyState === 4) {
status = request.status;
if (status === 200) {
data = JSON.parse(request.responseText);
fn(data.results, 'id', 'title');
} else {
console.error(status);
}
}
};
request.send();
}
});
var example13 = new Choices('[data-choice]', {
var genericExamples = new Choices('[data-choice]', {
placeholderValue: 'This is a placeholder set in the config',
removeButton: true,
});
var example14 = new Choices('#choices-single-no-search', {
var singleNoSearch = new Choices('#choices-single-no-search', {
search: false,
removeItemButton: true,
choices: [
@ -374,7 +349,7 @@
{value: 'Six', label: 'Label Six', selected: true},
], 'value', 'label');
var example15 = new Choices('#choices-single-preset-options', {
var singlePresetOpts = new Choices('#choices-single-preset-options', {
placeholder: true,
}).setChoices([{
label: 'Group one',
@ -397,7 +372,7 @@
]
}], 'value', 'label');
var example16 = new Choices('#choices-single-selected-option', {
var singleSelectedOpt = new Choices('#choices-single-selected-option', {
choices: [
{value: 'One', label: 'Label One', selected: true},
{value: 'Two', label: 'Label Two', disabled: true},
@ -405,7 +380,7 @@
],
}).setValueByChoice('Two');
var example17 = new Choices('#choices-single-no-sorting', {
var singleNoSorting = new Choices('#choices-single-no-sorting', {
shouldSort: false,
});