Skip to content

Commit

Permalink
Typeahead behavior for listbox
Browse files Browse the repository at this point in the history
  • Loading branch information
tatermelon committed Oct 14, 2017
1 parent 424facf commit 531f2ee
Show file tree
Hide file tree
Showing 2 changed files with 60 additions and 3 deletions.
3 changes: 0 additions & 3 deletions examples/listbox/js/listbox-rearrangeable.js
Original file line number Diff line number Diff line change
Expand Up @@ -23,7 +23,4 @@ window.addEventListener('load', function () {

ex2ImportantListbox.setupDelete(document.getElementById('ex2-add'), ex2UnimportantListbox);
ex2UnimportantListbox.setupDelete(document.getElementById('ex2-delete'), ex2ImportantListbox);

var ex3 = document.getElementById('ex3');
var ex3Listbox = new aria.Listbox(document.getElementById('ss_elem_list'));
});
60 changes: 60 additions & 0 deletions examples/listbox/js/listbox.js
Original file line number Diff line number Diff line change
Expand Up @@ -21,6 +21,7 @@ aria.Listbox = function (listboxNode) {
this.upButton = null;
this.downButton = null;
this.deleteButton = null;
this.keysSoFar = '';

this.registerEvents();
};
Expand Down Expand Up @@ -149,7 +150,66 @@ aria.Listbox.prototype.checkKeyPress = function (evt) {
this.focusItem(nextItem);
}
break;
default:
var itemToFocus = this.findItemToFocus(key);
if (itemToFocus) {
this.focusItem(itemToFocus);
}
break;
}
};

aria.Listbox.prototype.findItemToFocus = function (key) {
var itemList = this.listboxNode.querySelectorAll('[role="option"]');
var character = String.fromCharCode(key);

if (!this.keysSoFar) {
for (var i = 0; i < itemList.length; i++) {
if (itemList[i].getAttribute('id') == this.activeDescendant) {
this.searchIndex = i;
}
}
}
this.keysSoFar += character;
this.clearKeysSoFarAfterDelay();

var nextMatch = this.findMatchInRange(
itemList,
this.searchIndex + 1,
itemList.length
);
if (!nextMatch) {
nextMatch = this.findMatchInRange(
itemList,
0,
this.searchIndex
);
}

return nextMatch || itemList[this.searchIndex];
};

aria.Listbox.prototype.clearKeysSoFarAfterDelay = function () {
if (this.keyClear) {
clearTimeout(this.keyClear);
this.keyClear = null;
}
this.keyClear = setTimeout((function () {
this.keysSoFar = '';
this.keyClear = null;
}).bind(this), 500);
};

aria.Listbox.prototype.findMatchInRange = function (list, startIndex, endIndex) {
// Find the first item starting with the keysSoFar substring, searching in
// the specified range of items
for (var n = startIndex; n < endIndex; n++) {
var label = list[n].innerText;
if (label && label.toUpperCase().indexOf(this.keysSoFar) === 0) {
return list[n];
}
}
return null;
};

/**
Expand Down

0 comments on commit 531f2ee

Please sign in to comment.