Refactoring

This commit is contained in:
Josh Johnson 2017-08-03 11:22:21 +01:00
parent a75e7c6a03
commit ad476c2480
2 changed files with 234 additions and 243 deletions

View file

@ -1420,11 +1420,11 @@ class Choices {
result.placeholder result.placeholder
); );
} }
if (this.isSelectOneElement) {
this._selectPlaceholderChoice();
}
}); });
if (this.isSelectOneElement) {
this._selectPlaceholderChoice();
}
} else { } else {
// No results, remove loading state // No results, remove loading state
this._handleLoadingState(false); this._handleLoadingState(false);
@ -2792,11 +2792,12 @@ class Choices {
// If there is a selected choice already or the choice is not // If there is a selected choice already or the choice is not
// the first in the array, add each choice normally // the first in the array, add each choice normally
// Otherwise pre-select the first choice in the array // Otherwise pre-select the first choice in the array
const shouldPreselect = (hasSelectedChoice || (!hasSelectedChoice && index > 0));
this._addChoice( this._addChoice(
choice.value, choice.value,
choice.label, choice.label,
(hasSelectedChoice || index > 0) ? choice.selected : true, (shouldPreselect) ? choice.selected : true,
(hasSelectedChoice || index > 0) ? choice.disabled : false, (shouldPreselect) ? choice.disabled : false,
undefined, undefined,
choice.customProperties, choice.customProperties,
choice.placeholder choice.placeholder

View file

@ -53,7 +53,7 @@
</p> </p>
<hr> <hr>
<!-- <h2>Text inputs</h2> <h2>Text inputs</h2>
<label for="choices-text-remove-button">Limited to 5 values with remove button</label> <label for="choices-text-remove-button">Limited to 5 values with remove button</label>
<input class="form-control" id="choices-text-remove-button" type="text" value="preset-1,preset-2" placeholder="Enter something"> <input class="form-control" id="choices-text-remove-button" type="text" value="preset-1,preset-2" placeholder="Enter something">
@ -165,10 +165,14 @@
<p><small>If the following two examples do not load, the Discogs rate limit has probably been reached. Try again later!</small></p> <p><small>If the following two examples do not load, the Discogs rate limit has probably been reached. Try again later!</small></p>
<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>
<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">
<option placeholder>Pick an Arctic Monkeys' record</option>
</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>
<select class="form-control" name="choices-single-remove-xhr" id="choices-single-remove-xhr" placeholder="Pick a Smiths record"></select> <select class="form-control" name="choices-single-remove-xhr" id="choices-single-remove-xhr">
<option placeholder>Pick a Smiths' record</option>
</select>
<label for="choices-single-groups">Option groups</label> <label for="choices-single-groups">Option groups</label>
<select class="form-control" data-trigger name="choices-single-groups" id="choices-single-groups" placeholder="This is a placeholder"> <select class="form-control" data-trigger name="choices-single-groups" id="choices-single-groups" placeholder="This is a placeholder">
@ -272,273 +276,259 @@
<option value="Manhattan">Manhattan</option> <option value="Manhattan">Manhattan</option>
<option value="Queens">Queens</option> <option value="Queens">Queens</option>
<option value="Staten Island">Staten Island</option> <option value="Staten Island">Staten Island</option>
</select> -->
<select class="form-control" name="test" id="test" placeholder="Choose a borough">
<option selected placeholder>Placeholder</option>
<option value="The Bronx">The Bronx</option>
<option value="Brooklyn">Brooklyn</option>
<option value="Manhattan">Manhattan</option>
<option value="Queens">Queens</option>
<option value="Staten Island">Staten Island</option>
</select> </select>
</div> </div>
</div> </div>
<script> <script>
document.addEventListener('DOMContentLoaded', function () { document.addEventListener('DOMContentLoaded', function() {
var test = new Choices('.form-control', { var textRemove = new Choices(document.getElementById('choices-text-remove-button'), {
removeItemButton: true delimiter: ',',
editItems: true,
maxItemCount: 5,
removeItemButton: true,
}); });
// var textRemove = new Choices(document.getElementById('choices-text-remove-button'), { var textUniqueVals = new Choices('#choices-text-unique-values', {
// delimiter: ',', paste: false,
// editItems: true, duplicateItems: false,
// maxItemCount: 5, editItems: true,
// removeItemButton: true, });
// });
// var textUniqueVals = new Choices('#choices-text-unique-values', { var texti18n = new Choices('#choices-text-i18n', {
// paste: false, paste: false,
// duplicateItems: false, duplicateItems: false,
// editItems: true, editItems: true,
// }); maxItemCount: 5,
addItemText: function(value) {
return 'Appuyez sur Entrée pour ajouter <b>"' + String(value) + '"</b>';
},
maxItemText: function(maxItemCount) {
return String(maxItemCount) + 'valeurs peuvent être ajoutées';
},
uniqueItemText: 'Cette valeur est déjà présente',
});
// var texti18n = new Choices('#choices-text-i18n', { var textEmailFilter = new Choices('#choices-text-email-filter', {
// paste: false, editItems: true,
// duplicateItems: false, 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,}))$/,
// editItems: true, }).setValue(['joe@bloggs.com']);
// maxItemCount: 5,
// addItemText: function (value) {
// return 'Appuyez sur Entrée pour ajouter <b>"' + String(value) + '"</b>';
// },
// maxItemText: function (maxItemCount) {
// return String(maxItemCount) + 'valeurs peuvent être ajoutées';
// },
// uniqueItemText: 'Cette valeur est déjà présente',
// });
// var textEmailFilter = new Choices('#choices-text-email-filter', { var textDisabled = new Choices('#choices-text-disabled', {
// editItems: true, addItems: false,
// 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,}))$/, removeItems: false,
// }).setValue(['joe@bloggs.com']); }).disable();
// var textDisabled = new Choices('#choices-text-disabled', { var textPrependAppendVal = new Choices('#choices-text-prepend-append-value', {
// addItems: false, prependValue: 'item-',
// removeItems: false, appendValue: '-' + Date.now(),
// }).disable(); }).removeActiveItems();
// var textPrependAppendVal = new Choices('#choices-text-prepend-append-value', { var textPresetVal = new Choices('#choices-text-preset-values', {
// prependValue: 'item-', items: ['Josh Johnson', {
// appendValue: '-' + Date.now(), value: 'joe@bloggs.co.uk',
// }).removeActiveItems(); label: 'Joe Bloggs',
customProperties: {
description: 'Joe Blogg is such a generic name'
}
}],
});
// var textPresetVal = new Choices('#choices-text-preset-values', { var multipleDefault = new Choices(document.getElementById('choices-multiple-groups'));
// items: ['Josh Johnson', {
// value: 'joe@bloggs.co.uk',
// label: 'Joe Bloggs',
// customProperties: {
// description: 'Joe Blogg is such a generic name'
// }
// }],
// });
// var multipleDefault = new Choices(document.getElementById('choices-multiple-groups')); var multipleFetch = new Choices('#choices-multiple-remote-fetch', {
placeholder: true,
placeholderValue: 'Pick an Strokes record',
maxItemCount: 5,
}).ajax(function(callback) {
fetch('https://api.discogs.com/artists/55980/releases?token=QBRmstCkwXEvCjTclCpumbtNwvVkEzGAdELXyRyW')
.then(function(response) {
response.json().then(function(data) {
callback(data.releases, 'title', 'title');
});
})
.catch(function(error) {
console.error(error);
});
});
// var multipleFetch = new Choices('#choices-multiple-remote-fetch', { var multipleCancelButton = new Choices('#choices-multiple-remove-button', {
// placeholder: true, removeItemButton: true,
// placeholderValue: 'Pick an Strokes record', });
// maxItemCount: 5,
// }).ajax(function (callback) {
// fetch('https://api.discogs.com/artists/55980/releases?token=QBRmstCkwXEvCjTclCpumbtNwvVkEzGAdELXyRyW')
// .then(function (response) {
// response.json().then(function (data) {
// callback(data.releases, 'title', 'title');
// });
// })
// .catch(function (error) {
// console.error(error);
// });
// });
// var multipleCancelButton = new Choices('#choices-multiple-remove-button', { /* Use label on event */
// removeItemButton: true, var choicesSelect = new Choices('#choices-multiple-labels', {
// }); removeItemButton: true,
choices: [
{ value: 'One', label: 'Label One' },
{ value: 'Two', label: 'Label Two', disabled: true },
{ value: 'Three', label: 'Label Three' },
],
}).setChoices([
{ value: 'Four', label: 'Label Four', disabled: true },
{ value: 'Five', label: 'Label Five' },
{ value: 'Six', label: 'Label Six', selected: true },
], 'value', 'label', false);
// /* Use label on event */ choicesSelect.passedElement.addEventListener('addItem', function(event) {
// var choicesSelect = new Choices('#choices-multiple-labels', { document.getElementById('message').innerHTML = 'You just added "' + event.detail.label + '"';
// removeItemButton: true, });
// choices: [
// { value: 'One', label: 'Label One' },
// { value: 'Two', label: 'Label Two', disabled: true },
// { value: 'Three', label: 'Label Three' },
// ],
// }).setChoices([
// { value: 'Four', label: 'Label Four', disabled: true },
// { value: 'Five', label: 'Label Five' },
// { value: 'Six', label: 'Label Six', selected: true },
// ], 'value', 'label', false);
// choicesSelect.passedElement.addEventListener('addItem', function (event) { choicesSelect.passedElement.addEventListener('removeItem', function(event) {
// document.getElementById('message').innerHTML = 'You just added "' + event.detail.label + '"'; document.getElementById('message').innerHTML = 'You just removed "' + event.detail.label + '"';
// }); });
// choicesSelect.passedElement.addEventListener('removeItem', function (event) { var singleFetch = new Choices('#choices-single-remote-fetch', {
// document.getElementById('message').innerHTML = 'You just removed "' + event.detail.label + '"'; searchPlaceholderValue: 'Search for an Arctic Monkeys record',
// }); }).ajax(function(callback) {
fetch('https://api.discogs.com/artists/391170/releases?token=QBRmstCkwXEvCjTclCpumbtNwvVkEzGAdELXyRyW')
.then(function(response) {
response.json().then(function(data) {
callback(data.releases, 'title', 'title');
singleFetch.setValueByChoice('Fake Tales Of San Francisco');
});
})
.catch(function(error) {
console.error(error);
});
});
// var singleFetch = new Choices('#choices-single-remote-fetch', { var singleXhrRemove = new Choices('#choices-single-remove-xhr', {
// placeholder: true, removeItemButton: true,
// placeholderValue: 'Pick an Arctic Monkeys record', searchPlaceholderValue: 'Search for a Smiths\' record'
// searchPlaceholderValue: 'Search for an Arctic Monkeys record', }).ajax(function(callback) {
// }).ajax(function (callback) { var request = new XMLHttpRequest();
// fetch('https://api.discogs.com/artists/391170/releases?token=QBRmstCkwXEvCjTclCpumbtNwvVkEzGAdELXyRyW') request.open('get', 'https://api.discogs.com/artists/83080/releases?token=QBRmstCkwXEvCjTclCpumbtNwvVkEzGAdELXyRyW', true);
// .then(function (response) { request.onreadystatechange = function() {
// response.json().then(function (data) { var status;
// callback(data.releases, 'title', 'title'); var data;
// singleFetch.setValueByChoice('Fake Tales Of San Francisco'); if (request.readyState === 4) {
// }); status = request.status;
// }) if (status === 200) {
// .catch(function (error) { data = JSON.parse(request.responseText);
// console.error(error); callback(data.releases, 'title', 'title');
// }); singleXhrRemove.setValueByChoice('How Soon Is Now?');
// }); } else {
console.error(status);
}
}
}
request.send();
});
// var singleXhrRemove = new Choices('#choices-single-remove-xhr', { var genericExamples = new Choices('[data-trigger]', {
// removeItemButton: true, placeholderValue: 'This is a placeholder set in the config',
// }).ajax(function (callback) { searchPlaceholderValue: 'This is a search placeholder'
// var request = new XMLHttpRequest(); });
// request.open('get', 'https://api.discogs.com/artists/83080/releases?token=QBRmstCkwXEvCjTclCpumbtNwvVkEzGAdELXyRyW', true);
// request.onreadystatechange = function () {
// var status;
// var data;
// if (request.readyState === 4) {
// status = request.status;
// if (status === 200) {
// data = JSON.parse(request.responseText);
// callback(data.releases, 'title', 'title');
// singleXhrRemove.setValueByChoice('How Soon Is Now?');
// } else {
// console.error(status);
// }
// }
// }
// request.send();
// });
// var genericExamples = new Choices('[data-trigger]', { var singleNoSearch = new Choices('#choices-single-no-search', {
// placeholderValue: 'This is a placeholder set in the config', searchEnabled: false,
// searchPlaceholderValue: 'This is a search placeholder' removeItemButton: true,
// }); choices: [
{ value: 'One', label: 'Label One' },
{ value: 'Two', label: 'Label Two', disabled: true },
{ value: 'Three', label: 'Label Three' },
],
}).setChoices([
{ value: 'Four', label: 'Label Four', disabled: true },
{ value: 'Five', label: 'Label Five' },
{ value: 'Six', label: 'Label Six', selected: true },
], 'value', 'label', false);
// var singleNoSearch = new Choices('#choices-single-no-search', { var singlePresetOpts = new Choices('#choices-single-preset-options', {
// searchEnabled: false, placeholder: true,
// removeItemButton: true, }).setChoices([{
// choices: [ label: 'Group one',
// { value: 'One', label: 'Label One' }, id: 1,
// { value: 'Two', label: 'Label Two', disabled: true }, disabled: false,
// { value: 'Three', label: 'Label Three' }, choices: [
// ], { value: 'Child One', label: 'Child One', selected: true },
// }).setChoices([ { value: 'Child Two', label: 'Child Two', disabled: true },
// { value: 'Four', label: 'Label Four', disabled: true }, { value: 'Child Three', label: 'Child Three' },
// { value: 'Five', label: 'Label Five' }, ]
// { value: 'Six', label: 'Label Six', selected: true }, },
// ], 'value', 'label', false); {
label: 'Group two',
id: 2,
disabled: false,
choices: [
{ value: 'Child Four', label: 'Child Four', disabled: true },
{ value: 'Child Five', label: 'Child Five' },
{ value: 'Child Six', label: 'Child Six' },
]
}], 'value', 'label');
// var singlePresetOpts = new Choices('#choices-single-preset-options', { var singleSelectedOpt = new Choices('#choices-single-selected-option', {
// placeholder: true, searchFields: ['label', 'value', 'customProperties.description'],
// }).setChoices([{ choices: [
// label: 'Group one', { value: 'One', label: 'Label One', selected: true },
// id: 1, { value: 'Two', label: 'Label Two', disabled: true },
// disabled: false, {
// choices: [ value: 'Three', label: 'Label Three', customProperties: {
// { value: 'Child One', label: 'Child One', selected: true }, description: 'This option is fantastic'
// { value: 'Child Two', label: 'Child Two', disabled: true }, }
// { value: 'Child Three', label: 'Child Three' }, },
// ] ],
// }, }).setValueByChoice('Two');
// {
// label: 'Group two',
// id: 2,
// disabled: false,
// choices: [
// { value: 'Child Four', label: 'Child Four', disabled: true },
// { value: 'Child Five', label: 'Child Five' },
// { value: 'Child Six', label: 'Child Six' },
// ]
// }], 'value', 'label');
// var singleSelectedOpt = new Choices('#choices-single-selected-option', { var singleNoSorting = new Choices('#choices-single-no-sorting', {
// searchFields: ['label', 'value', 'customProperties.description'], shouldSort: false,
// choices: [ });
// { value: 'One', label: 'Label One', selected: true },
// { value: 'Two', label: 'Label Two', disabled: true },
// {
// value: 'Three', label: 'Label Three', customProperties: {
// description: 'This option is fantastic'
// }
// },
// ],
// }).setValueByChoice('Two');
// var singleNoSorting = new Choices('#choices-single-no-sorting', { var states = new Choices(document.getElementById('states'));
// shouldSort: false,
// });
// var states = new Choices(document.getElementById('states')); states.passedElement.addEventListener('change', function(e) {
if (e.detail.value === 'New York') {
boroughs.enable();
} else {
boroughs.disable();
}
});
// states.passedElement.addEventListener('change', function (e) { var customTemplates = new Choices(document.getElementById('choices-single-custom-templates'), {
// if (e.detail.value === 'New York') { callbackOnCreateTemplates: function(strToEl) {
// boroughs.enable(); var classNames = this.config.classNames;
// } else { var itemSelectText = this.config.itemSelectText;
// boroughs.disable(); return {
// } item: function(data) {
// }); return strToEl('\
<div\
class="'+ String(classNames.item) + ' ' + String(data.highlighted ? classNames.highlightedState : classNames.itemSelectable) + '"\
data-item\
data-id="'+ String(data.id) + '"\
data-value="'+ String(data.value) + '"\
'+ String(data.active ? 'aria-selected="true"' : '') + '\
'+ String(data.disabled ? 'aria-disabled="true"' : '') + '\
>\
<span style="margin-right:10px;">🎉</span> ' + String(data.label) + '\
</div>\
');
},
choice: function(data) {
return strToEl('\
<div\
class="'+ String(classNames.item) + ' ' + String(classNames.itemChoice) + ' ' + String(data.disabled ? classNames.itemDisabled : classNames.itemSelectable) + '"\
data-select-text="'+ String(itemSelectText) + '"\
data-choice \
'+ String(data.disabled ? 'data-choice-disabled aria-disabled="true"' : 'data-choice-selectable') + '\
data-id="'+ String(data.id) + '"\
data-value="'+ String(data.value) + '"\
'+ String(data.groupId > 0 ? 'role="treeitem"' : 'role="option"') + '\
>\
<span style="margin-right:10px;">👉🏽</span> ' + String(data.label) + '\
</div>\
');
},
};
}
});
// var customTemplates = new Choices(document.getElementById('choices-single-custom-templates'), { var boroughs = new Choices(document.getElementById('boroughs')).disable();
// callbackOnCreateTemplates: function (strToEl) {
// var classNames = this.config.classNames;
// var itemSelectText = this.config.itemSelectText;
// return {
// item: function (data) {
// return strToEl('\
// <div\
// class="'+ String(classNames.item) + ' ' + String(data.highlighted ? classNames.highlightedState : classNames.itemSelectable) + '"\
// data-item\
// data-id="'+ String(data.id) + '"\
// data-value="'+ String(data.value) + '"\
// '+ String(data.active ? 'aria-selected="true"' : '') + '\
// '+ String(data.disabled ? 'aria-disabled="true"' : '') + '\
// >\
// <span style="margin-right:10px;">🎉</span> ' + String(data.label) + '\
// </div>\
// ');
// },
// choice: function (data) {
// return strToEl('\
// <div\
// class="'+ String(classNames.item) + ' ' + String(classNames.itemChoice) + ' ' + String(data.disabled ? classNames.itemDisabled : classNames.itemSelectable) + '"\
// data-select-text="'+ String(itemSelectText) + '"\
// data-choice \
// '+ String(data.disabled ? 'data-choice-disabled aria-disabled="true"' : 'data-choice-selectable') + '\
// data-id="'+ String(data.id) + '"\
// data-value="'+ String(data.value) + '"\
// '+ String(data.groupId > 0 ? 'role="treeitem"' : 'role="option"') + '\
// >\
// <span style="margin-right:10px;">👉🏽</span> ' + String(data.label) + '\
// </div>\
// ');
// },
// };
// }
// });
// var boroughs = new Choices(document.getElementById('boroughs')).disable();
}); });
</script> </script>
<!-- Google Analytics - Ignore me --> <!-- Google Analytics - Ignore me -->
<script> <script>
window.ga = window.ga || function () { (ga.q = ga.q || []).push(arguments) }; ga.l = +new Date; window.ga = window.ga || function() { (ga.q = ga.q || []).push(arguments) }; ga.l = +new Date;
ga('create', 'UA-31575166-1', 'auto'); ga('create', 'UA-31575166-1', 'auto');
ga('send', 'pageview'); ga('send', 'pageview');
</script> </script>