salix/front/core/directives/focus.js

46 lines
998 B
JavaScript

import ngModule from '../module';
import isMobile from '../lib/is-mobile';
export function focus($scope, 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) {
$scope.$applyAsync(() => {
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($scope, $element[0]));
}
};
}
ngModule.directive('vnFocus', directive);