@atlassian/aui
Version:
Atlassian User Interface library
91 lines (75 loc) • 2.67 kB
JavaScript
/**
* @typedef {Object} Suggestion
* @property {string|number} id
*/
/**
* @typedef {Object} SuggestionsModelType
* @property {(oldSuggestions: Suggestion[]) => void} onChange
* @property {() => void} onHighlightChange
* @property {(index: number) => Suggestion|undefined} get
* @property {(suggestions?: Suggestion[]) => SuggestionsModelType} set
* @property {() => number} getNumberOfResults
* @property {(toHighlight?: Suggestion) => SuggestionsModelType} setHighlighted
* @property {(index: number) => SuggestionsModelType} highlight
* @property {() => SuggestionsModelType} highlightPrevious
* @property {() => SuggestionsModelType} highlightNext
* @property {() => Suggestion|undefined} highlighted
* @property {() => number} highlightedIndex
*/
/**
* @returns {SuggestionsModelType}
*/
function SuggestionsModel() {
return {
_suggestions: [],
_activeIndex: -1,
onChange: function () {},
onHighlightChange: function () {},
get: function (index) {
return this._suggestions[index];
},
set: function (suggestions) {
var oldSuggestions = this._suggestions;
this._suggestions = suggestions || [];
this.onChange(oldSuggestions);
return this;
},
getNumberOfResults: function () {
return this._suggestions.length;
},
setHighlighted: function (toHighlight) {
if (toHighlight) {
for (var i = 0; i < this._suggestions.length; i++) {
if (this._suggestions[i].id === toHighlight.id) {
this.highlight(i);
}
}
}
return this;
},
highlight: function (index) {
this._activeIndex = index;
this.onHighlightChange();
return this;
},
highlightPrevious: function () {
const current = this._activeIndex;
const previousActiveIndex = current === 0 ? this._suggestions.length - 1 : current - 1;
this.highlight(previousActiveIndex);
return this;
},
highlightNext: function () {
const current = this._activeIndex;
const nextActiveIndex = current === this._suggestions.length - 1 ? 0 : current + 1;
this.highlight(nextActiveIndex);
return this;
},
highlighted: function () {
return this.get(this._activeIndex);
},
highlightedIndex: function () {
return this._activeIndex;
},
};
}
export default SuggestionsModel;