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: ',', delimiter: ',',
paste: true, paste: true,
search: true, search: true,
searchFloor: 1,
flip: true, flip: true,
regexFilter: null, regexFilter: null,
shouldSort: true, shouldSort: true,
@ -86,13 +87,13 @@ A vanilla, lightweight (~15kb gzipped 🎉), configurable select box/text input
flippedState: 'is-flipped', flippedState: 'is-flipped',
loadingState: 'is-loading', loadingState: 'is-loading',
}, },
callbackOnInit: () => {}, callbackOnInit: null,
callbackOnAddItem: (id, value, passedInput) => {}, callbackOnAddItem: null,
callbackOnRemoveItem: (id, value, passedInput) => {}, callbackOnRemoveItem: null,
callbackOnHighlightItem: (id, value, passedInput) => {}, callbackOnHighlightItem: null,
callbackOnUnhighlightItem: (id, value, passedInput) => {}, callbackOnUnhighlightItem: null,
callbackOnChange: (value, passedInput) => {}, callbackOnChange: null,
callbackOnItemSearch: (value, fn, passedInput) => {}, callbackOnSearch: null,
}); });
</script> </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. **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 ### flip
**Type:** `Boolean` **Default:** `true` **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. **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 ### callbackOnInit
**Type:** `Function` **Default:** `() => {}` **Type:** `Function` **Default:** `null`
**Input types affected:** `text`, `select-one`, `select-multiple` **Input types affected:** `text`, `select-one`, `select-multiple`
**Usage:** Function to run once Choices initialises. **Usage:** Function to run once Choices initialises.
### callbackOnAddItem ### callbackOnAddItem
**Type:** `Function` **Default:** `(id, value, passedInput) => {}` **Type:** `Function` **Default:** `null` **Arguments:** `id, value, passedInput`
**Input types affected:** `text`, `select-one`, `select-multiple` **Input types affected:** `text`, `select-one`, `select-multiple`
**Usage:** Function to run each time an item is added (programmatically or by the user). **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 ### callbackOnRemoveItem
**Type:** `Function` **Default:** `(id, value, passedInput) => {}` **Type:** `Function` **Default:** `null` **Arguments:** `id, value, passedInput`
**Input types affected:** `text`, `select-one`, `select-multiple` **Input types affected:** `text`, `select-one`, `select-multiple`
**Usage:** Function to run each time an item is removed (programmatically or by the user). **Usage:** Function to run each time an item is removed (programmatically or by the user).
### callbackOnHighlightItem ### callbackOnHighlightItem
**Type:** `Function` **Default:** `(id, value, passedInput) => {}` **Type:** `Function` **Default:** `null` **Arguments:** `id, value, passedInput`
**Input types affected:** `text`, `select-multiple` **Input types affected:** `text`, `select-multiple`
**Usage:** Function to run each time an item is highlighted. **Usage:** Function to run each time an item is highlighted.
### callbackOnUnhighlightItem ### callbackOnUnhighlightItem
**Type:** `Function` **Default:** `(id, value, passedInput) => {}` **Type:** `Function` **Default:** `null` **Arguments:** `id, value, passedInput`
**Input types affected:** `text`, `select-multiple` **Input types affected:** `text`, `select-multiple`
**Usage:** Function to run each time an item is unhighlighted. **Usage:** Function to run each time an item is unhighlighted.
### callbackOnChange ### callbackOnChange
**Type:** `Function` **Default:** `(value, passedInput) => {}` **Type:** `Function` **Default:** `null` **Arguments:** `value, passedInput`
**Input types affected:** `text`, `select-one`, `select-multiple` **Input types affected:** `text`, `select-one`, `select-multiple`

View file

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

View file

@ -29,6 +29,9 @@ label {
font-weight: 500; font-weight: 500;
cursor: pointer; } cursor: pointer; }
p {
margin-top: 0; }
hr { hr {
display: block; display: block;
margin: 36px 0; 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

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

View file

@ -22,274 +22,274 @@ $choices-button-dimension: 8px !default;
$choices-button-offset: 8px !default; $choices-button-offset: 8px !default;
.#{$choices-selector} { .#{$choices-selector} {
position: relative; position: relative;
margin-bottom: $choices-guttering; margin-bottom: $choices-guttering;
font-size: $choices-font-size-lg; font-size: $choices-font-size-lg;
&:focus { outline: none; } &:focus { outline: none; }
&:last-child { margin-bottom: 0; } &:last-child { margin-bottom: 0; }
&.is-disabled { &.is-disabled {
.#{$choices-selector}__inner, .#{$choices-selector}__input { .#{$choices-selector}__inner, .#{$choices-selector}__input {
background-color: $choices-bg-color-disabled; background-color: $choices-bg-color-disabled;
cursor: not-allowed; cursor: not-allowed;
user-select: none; user-select: none;
}
.#{$choices-selector}__item { cursor: not-allowed; }
} }
.#{$choices-selector}__item { cursor: not-allowed; }
}
} }
.#{$choices-selector}[data-type*="select-one"] { .#{$choices-selector}[data-type*="select-one"] {
cursor: pointer; cursor: pointer;
.#{$choices-selector}__inner { padding-bottom: 7.5px; } .#{$choices-selector}__inner { padding-bottom: 7.5px; }
.#{$choices-selector}__input { .#{$choices-selector}__input {
display: block; display: block;
width: 100%; width: 100%;
padding: 10px; padding: 10px;
border-bottom: 1px solid $choices-keyline-color; border-bottom: 1px solid $choices-keyline-color;
background-color: #FFFFFF; background-color: #FFFFFF;
margin: 0; margin: 0;
}
.#{$choices-selector}__button {
background-image: url($choices-button-icon-path + '/cross-inverse.svg');
padding: 0;
background-size: 8px;
height: 100%;
position: absolute;
top: 50%;
right: 0;
margin-top: -10px;
margin-right: 25px;
height: 20px;
width: 20px;
border-radius: 10em;
opacity: .5;
&:hover, &:focus { opacity: 1; }
&:focus { box-shadow: 0px 0px 0px 2px $choices-highlight-color; }
}
&:after {
content: "";
height: 0;
width: 0;
border-style: solid;
border-color: $choices-text-color transparent transparent transparent;
border-width: 5px;
position: absolute;
right: 11.5px;
top: 50%;
margin-top: -2.5px;
pointer-events: none;
}
&.is-open:after {
border-color: transparent transparent $choices-text-color transparent;
margin-top: -7.5px;
}
&[dir="rtl"] {
&:after {
left: 11.5px;
right: auto;
} }
.#{$choices-selector}__button { .#{$choices-selector}__button {
background-image: url($choices-button-icon-path + '/cross-inverse.svg'); right: auto;
padding: 0; left: 0;
background-size: 8px; margin-left: 25px;
height: 100%; margin-right: 0;
position: absolute;
top: 50%;
right: 0;
margin-top: -10px;
margin-right: 25px;
height: 20px;
width: 20px;
border-radius: 10em;
opacity: .5;
&:hover, &:focus { opacity: 1; }
&:focus { box-shadow: 0px 0px 0px 2px $choices-highlight-color; }
}
&:after {
content: "";
height: 0;
width: 0;
border-style: solid;
border-color: $choices-text-color transparent transparent transparent;
border-width: 5px;
position: absolute;
right: 11.5px;
top: 50%;
margin-top: -2.5px;
pointer-events: none;
}
&.is-open:after {
border-color: transparent transparent $choices-text-color transparent;
margin-top: -7.5px;
}
&[dir="rtl"] {
&:after {
left: 11.5px;
right: auto;
}
.#{$choices-selector}__button {
right: auto;
left: 0;
margin-left: 25px;
margin-right: 0;
}
} }
}
} }
.#{$choices-selector}[data-type*="select-multiple"], .#{$choices-selector}[data-type*="text"] { .#{$choices-selector}[data-type*="select-multiple"], .#{$choices-selector}[data-type*="text"] {
.#{$choices-selector}__inner { cursor: text; } .#{$choices-selector}__inner { cursor: text; }
.#{$choices-selector}__button { .#{$choices-selector}__button {
position: relative; position: relative;
display: inline-block; display: inline-block;
margin-top: 0; margin-top: 0;
margin-right: -$choices-button-offset/2; margin-right: -$choices-button-offset/2;
margin-bottom: 0; margin-bottom: 0;
margin-left: $choices-button-offset; margin-left: $choices-button-offset;
padding-left: $choices-button-offset*2; padding-left: $choices-button-offset*2;
border-left: 1px solid darken($choices-primary-color, 10%); border-left: 1px solid darken($choices-primary-color, 10%);
background-image: url($choices-button-icon-path + '/cross.svg'); background-image: url($choices-button-icon-path + '/cross.svg');
background-size: $choices-button-dimension; background-size: $choices-button-dimension;
width: $choices-button-dimension; width: $choices-button-dimension;
line-height: 1; line-height: 1;
opacity: .75; opacity: .75;
&:hover, &:focus { opacity: 1; } &:hover, &:focus { opacity: 1; }
} }
} }
.#{$choices-selector}__inner { .#{$choices-selector}__inner {
display: inline-block; display: inline-block;
vertical-align: top; vertical-align: top;
width: 100%; width: 100%;
background-color: $choices-bg-color; background-color: $choices-bg-color;
padding: 7.5px 7.5px 3.75px; padding: 7.5px 7.5px 3.75px;
border: 1px solid $choices-keyline-color; border: 1px solid $choices-keyline-color;
border-radius: $choices-border-radius; border-radius: $choices-border-radius;
font-size: $choices-font-size-md; font-size: $choices-font-size-md;
min-height: 44px; min-height: 44px;
overflow: hidden; overflow: hidden;
.is-focused &, .is-open & { border-color: darken($choices-keyline-color, 15%); } .is-focused &, .is-open & { border-color: darken($choices-keyline-color, 15%); }
.is-open & { border-radius: $choices-border-radius $choices-border-radius 0 0; } .is-open & { border-radius: $choices-border-radius $choices-border-radius 0 0; }
.is-flipped.is-open & { border-radius: 0 0 $choices-border-radius $choices-border-radius; } .is-flipped.is-open & { border-radius: 0 0 $choices-border-radius $choices-border-radius; }
} }
.#{$choices-selector}__list { .#{$choices-selector}__list {
margin: 0; margin: 0;
padding-left: 0; padding-left: 0;
list-style-type: none; list-style-type: none;
} }
.#{$choices-selector}__list--single { .#{$choices-selector}__list--single {
display: inline-block; display: inline-block;
padding: 4px 16px 4px 4px; padding: 4px 16px 4px 4px;
width: 100%; width: 100%;
[dir="rtl"] & { [dir="rtl"] & {
padding-right: 4px; padding-right: 4px;
padding-left: 16px; padding-left: 16px;
} }
.#{$choices-selector}__item { width: 100%; } .#{$choices-selector}__item { width: 100%; }
} }
.#{$choices-selector}__list--multiple { .#{$choices-selector}__list--multiple {
display: inline; display: inline;
.#{$choices-selector}__item { .#{$choices-selector}__item {
display: inline-block; display: inline-block;
vertical-align: middle; vertical-align: middle;
border-radius: $choices-border-radius-item; border-radius: $choices-border-radius-item;
padding: 4px 10px; padding: 4px 10px;
font-size: $choices-font-size-sm; font-size: $choices-font-size-sm;
font-weight: 500; font-weight: 500;
margin-right: 3.75px; margin-right: 3.75px;
margin-bottom: 3.75px; margin-bottom: 3.75px;
background-color: $choices-primary-color; background-color: $choices-primary-color;
border: 1px solid darken($choices-primary-color, 5%); border: 1px solid darken($choices-primary-color, 5%);
color: #FFFFFF; color: #FFFFFF;
word-break: break-all; word-break: break-all;
&[data-deletable] { padding-right: 5px; } &[data-deletable] { padding-right: 5px; }
[dir="rtl"] & { [dir="rtl"] & {
margin-right: 0; margin-right: 0;
margin-left: 3.75px; margin-left: 3.75px;
}
&.is-highlighted {
background-color: darken($choices-primary-color, 5%);
border: 1px solid darken($choices-primary-color, 10%);
}
.is-disabled & {
background-color: darken($choices-disabled-color, 25%);
border: 1px solid darken($choices-disabled-color, 35%);
}
} }
&.is-highlighted {
background-color: darken($choices-primary-color, 5%);
border: 1px solid darken($choices-primary-color, 10%);
}
.is-disabled & {
background-color: darken($choices-disabled-color, 25%);
border: 1px solid darken($choices-disabled-color, 35%);
}
}
} }
.#{$choices-selector}__list--dropdown { .#{$choices-selector}__list--dropdown {
display: none; display: none;
z-index: 1; z-index: 1;
position: absolute; position: absolute;
width: 100%; width: 100%;
background-color: $choices-bg-color-dropdown; background-color: $choices-bg-color-dropdown;
border: 1px solid $choices-keyline-color; border: 1px solid $choices-keyline-color;
top: 100%; top: 100%;
margin-top: -1px; margin-top: -1px;
border-bottom-left-radius: $choices-border-radius; border-bottom-left-radius: $choices-border-radius;
border-bottom-right-radius: $choices-border-radius; border-bottom-right-radius: $choices-border-radius;
overflow: hidden; overflow: hidden;
&.is-active { display: block; } &.is-active { display: block; }
.is-open & { border-color: darken($choices-keyline-color, 15%); } .is-open & { border-color: darken($choices-keyline-color, 15%); }
.is-flipped & { .is-flipped & {
top: auto; top: auto;
bottom: 100%; bottom: 100%;
margin-top: 0; margin-top: 0;
margin-bottom: -1px; margin-bottom: -1px;
border-radius: .25rem .25rem 0 0; border-radius: .25rem .25rem 0 0;
} }
.#{$choices-selector}__list { .#{$choices-selector}__list {
position: relative; position: relative;
max-height: 300px; max-height: 300px;
overflow: auto; overflow: auto;
-webkit-overflow-scrolling: touch; -webkit-overflow-scrolling: touch;
will-change: scroll-position; will-change: scroll-position;
} }
.#{$choices-selector}__item { .#{$choices-selector}__item {
position: relative; position: relative;
padding: 10px; padding: 10px;
font-size: $choices-font-size-md; font-size: $choices-font-size-md;
[dir="rtl"] & { text-align: right; } [dir="rtl"] & { text-align: right; }
} }
.#{$choices-selector}__item--selectable { .#{$choices-selector}__item--selectable {
@media (min-width: 640px) { @media (min-width: 640px) {
padding-right: 100px; padding-right: 100px;
&:after { &:after {
content: attr(data-select-text); content: attr(data-select-text);
font-size: $choices-font-size-sm; font-size: $choices-font-size-sm;
opacity: 0; opacity: 0;
position: absolute; position: absolute;
right: 10px; right: 10px;
top: 50%; top: 50%;
transform: translateY(-50%); transform: translateY(-50%);
} }
[dir="rtl"] & { [dir="rtl"] & {
text-align: right; text-align: right;
padding-left: 100px; padding-left: 100px;
padding-right: 10px; padding-right: 10px;
&:after { &:after {
right: auto; right: auto;
left: 10px; left: 10px;
}
}
}
&.is-highlighted {
background-color: mix(#000000, #FFFFFF, 5%);
&:after { opacity: .5; }
} }
}
} }
&.is-highlighted {
background-color: mix(#000000, #FFFFFF, 5%);
&:after { opacity: .5; }
}
}
} }
.#{$choices-selector}__item { cursor: default; } .#{$choices-selector}__item { cursor: default; }
.#{$choices-selector}__item--selectable { cursor: pointer; } .#{$choices-selector}__item--selectable { cursor: pointer; }
.#{$choices-selector}__item--disabled { .#{$choices-selector}__item--disabled {
cursor: not-allowed; cursor: not-allowed;
user-select: none; user-select: none;
opacity: .5; opacity: .5;
} }
.#{$choices-selector}__group { .#{$choices-selector}__group {
.#{$choices-selector}__heading { .#{$choices-selector}__heading {
font-weight: 600; font-weight: 600;
font-size: $choices-font-size-sm; font-size: $choices-font-size-sm;
padding: 10px; padding: 10px;
border-bottom: 1px solid lighten($choices-keyline-color, 10%); border-bottom: 1px solid lighten($choices-keyline-color, 10%);
color: lighten(#333, 30%); color: lighten(#333, 30%);
} }
} }
.#{$choices-selector}__button { .#{$choices-selector}__button {
text-indent: -9999px; text-indent: -9999px;
-webkit-appearance: none; -webkit-appearance: none;
appearance: none; appearance: none;
border: 0; border: 0;
background-color: transparent; background-color: transparent;
background-repeat: no-repeat; background-repeat: no-repeat;
background-position: center; background-position: center;
cursor: pointer; cursor: pointer;
&:focus { outline: none; } &:focus { outline: none; }
} }
.#{$choices-selector}__input { .#{$choices-selector}__input {
display: inline-block; display: inline-block;
vertical-align: baseline; vertical-align: baseline;
background-color: mix(#000000, #FFFFFF, 2.5%); background-color: mix(#000000, #FFFFFF, 2.5%);
font-size: $choices-font-size-md; font-size: $choices-font-size-md;
margin-bottom: 5px; margin-bottom: 5px;
border: 0; border: 0;
border-radius: 0; border-radius: 0;
max-width: 100%; max-width: 100%;
padding: 4px 0 4px 2px; padding: 4px 0 4px 2px;
&:focus { outline: 0; } &:focus { outline: 0; }
[dir="rtl"] & { [dir="rtl"] & {
padding-right: 2px; padding-right: 2px;
padding-left: 0; padding-left: 0;
} }
} }
.#{$choices-selector}__placeholder { opacity: .5; } .#{$choices-selector}__placeholder { opacity: .5; }
/*===== End of Choices ======*/ /*===== End of Choices ======*/

View file

@ -122,9 +122,6 @@
<option value="Dropdown item 4" disabled>Dropdown item 4</option> <option value="Dropdown item 4" disabled>Dropdown item 4</option>
</select> </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> <hr>
<h2>Single select input</h2> <h2>Single select input</h2>
@ -137,6 +134,7 @@
</select> </select>
<label for="choices-single-remote-fetch">Options from remote source (Fetch API)</label> <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> <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> <label for="choices-single-remove-xhr">Options from remote source (XHR) &amp; remove button</label>
@ -239,7 +237,7 @@
</div> </div>
<script> <script>
document.addEventListener('DOMContentLoaded', function() { 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: ',', delimiter: ',',
editItems: true, editItems: true,
maxItemCount: 5, maxItemCount: 5,
@ -252,32 +250,32 @@
}, },
}); });
var example2 = new Choices('#choices-text-unique-values', { var textUniqueVals = new Choices('#choices-text-unique-values', {
paste: false, paste: false,
duplicateItems: false, duplicateItems: false,
editItems: true, editItems: true,
}); });
var example3 = new Choices('#choices-text-email-filter', { var textEmailFilter = new Choices('#choices-text-email-filter', {
editItems: true, 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,}))$/, 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, addItems: false,
removeItems: false, removeItems: false,
}).disable(); }).disable();
var example5 = new Choices('#choices-text-prepend-append-value', { var textPrependAppendVal = new Choices('#choices-text-prepend-append-value', {
prependValue: 'item-', prependValue: 'item-',
appendValue: '-' + Date.now(), appendValue: '-' + Date.now(),
}).removeActiveItems(); }).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' } ], 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, placeholder: true,
placeholderValue: 'Pick an Strokes record', placeholderValue: 'Pick an Strokes record',
maxItemCount: 5, maxItemCount: 5,
@ -294,7 +292,7 @@
}); });
}); });
var example10 = new Choices('#choices-single-remote-fetch', { var singleFetch = new Choices('#choices-single-remote-fetch', {
placeholder: true, placeholder: true,
placeholderValue: 'Pick an Arctic Monkeys record' placeholderValue: 'Pick an Arctic Monkeys record'
}).ajax(function(callback) { }).ajax(function(callback) {
@ -302,7 +300,7 @@
.then(function(response) { .then(function(response) {
response.json().then(function(data) { response.json().then(function(data) {
callback(data.releases, 'title', 'title'); callback(data.releases, 'title', 'title');
example10.setValueByChoice('Fake Tales Of San Francisco'); singleFetch.setValueByChoice('Fake Tales Of San Francisco');
}); });
}) })
.catch(function(error) { .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, removeItemButton: true,
}).ajax(function(callback) { }).ajax(function(callback) {
var request = new XMLHttpRequest(); var request = new XMLHttpRequest();
@ -323,7 +321,7 @@
if (status === 200) { if (status === 200) {
data = JSON.parse(request.responseText); data = JSON.parse(request.responseText);
callback(data.releases, 'title', 'title'); callback(data.releases, 'title', 'title');
example11.setValueByChoice('How Soon Is Now?'); singleXhrRemove.setValueByChoice('How Soon Is Now?');
} else { } else {
console.error(status); console.error(status);
} }
@ -332,35 +330,12 @@
request.send(); request.send();
}); });
var example12 = new Choices('#choices-multiple-xhr-search', { var genericExamples = new Choices('[data-choice]', {
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]', {
placeholderValue: 'This is a placeholder set in the config', placeholderValue: 'This is a placeholder set in the config',
removeButton: true, removeButton: true,
}); });
var example14 = new Choices('#choices-single-no-search', { var singleNoSearch = new Choices('#choices-single-no-search', {
search: false, search: false,
removeItemButton: true, removeItemButton: true,
choices: [ choices: [
@ -374,7 +349,7 @@
{value: 'Six', label: 'Label Six', selected: true}, {value: 'Six', label: 'Label Six', selected: true},
], 'value', 'label'); ], 'value', 'label');
var example15 = new Choices('#choices-single-preset-options', { var singlePresetOpts = new Choices('#choices-single-preset-options', {
placeholder: true, placeholder: true,
}).setChoices([{ }).setChoices([{
label: 'Group one', label: 'Group one',
@ -397,7 +372,7 @@
] ]
}], 'value', 'label'); }], 'value', 'label');
var example16 = new Choices('#choices-single-selected-option', { var singleSelectedOpt = new Choices('#choices-single-selected-option', {
choices: [ choices: [
{value: 'One', label: 'Label One', selected: true}, {value: 'One', label: 'Label One', selected: true},
{value: 'Two', label: 'Label Two', disabled: true}, {value: 'Two', label: 'Label Two', disabled: true},
@ -405,7 +380,7 @@
], ],
}).setValueByChoice('Two'); }).setValueByChoice('Two');
var example17 = new Choices('#choices-single-no-sorting', { var singleNoSorting = new Choices('#choices-single-no-sorting', {
shouldSort: false, shouldSort: false,
}); });