salix/front/core/directives/focus.js

45 lines
1014 B
JavaScript

import ngModule from '../module';
const regex = /Android|webOS|iPhone|iPad|iPod|BlackBerry|Windows Phone/i;
export const isMobile = regex.test(navigator.userAgent);
export function focus(input) {
if (isMobile) return;
const element = input;
let selector = 'input, textarea, button, submit';
if (!input.matches(selector))
input = input.querySelector(selector);
if (!input) {
const focusEvent = new MouseEvent('focus', {
bubbles: true,
cancelable: true,
view: window
});
element.dispatchEvent(focusEvent);
return;
}
input.focus();
if (input.select)
input.select();
}
/**
* Sets the focus and selects the text on the input.
*
* @return {Object} The directive
*/
export function directive() {
return {
restrict: 'A',
link: function($scope, $element) {
$scope.$watch('', () => focus($element[0]));
}
};
}
ngModule.directive('vnFocus', directive);