Skip to content

Commit

Permalink
Handle some edge cases and simplify code
Browse files Browse the repository at this point in the history
  • Loading branch information
chrisronline committed Nov 13, 2017
1 parent 2a8b4cf commit 2d14aec
Showing 1 changed file with 17 additions and 20 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -14,35 +14,32 @@ module.directive('appendWildcard', function () {
return {
require: 'ngModel',
link: function ($scope, $elem, $attrs, $ctrl) {
$scope.appendedWildcard = false;
$elem.on('keydown', (e) => {
// https://developer.mozilla.org/en-US/docs/Web/API/KeyboardEvent/keyCode
// is not recommended so we need to rely on `key` but browser support
// is still spotty (https://developer.mozilla.org/en-US/docs/Web/API/KeyboardEvent/key)
// so just bail if it's not supported
if (!e.key) {
return;
}

function setElementValue(val, event, setCursorBackOneCharacter = false) {
event.preventDefault();
$elem.val(val);
if (setCursorBackOneCharacter) {
$elem[0].setSelectionRange(1, 1);
if (!/[a-z0-9]/i.test(e.key)) {
return;
}
}

$elem.on('keydown', (e) => {
const charStr = String.fromCharCode(e.keyCode);
if (!/[a-z0-9]/i.test(charStr)) {
// If the user is holdinng down ctrl/cmd, they are performing some shortcut
// and do not interpret literally
if (e.metaKey) {
return;
}

let indexPatternName = $elem.val() + e.key;

if (indexPatternName && indexPatternName.length === 1) {
if (indexPatternName === '*') {
if ($scope.appendedWildcard) {
indexPatternName = '';
setElementValue(indexPatternName, e);
$scope.appendedWildcard = false;
}
} else {
if (indexPatternName !== '*') {
indexPatternName += '*';
$scope.appendedWildcard = true;
setElementValue(indexPatternName, e, true);
e.preventDefault();
$elem.val(indexPatternName);
$elem[0].setSelectionRange(1, 1);
}
}

Expand Down

0 comments on commit 2d14aec

Please sign in to comment.