salix/front/core/directives/focus.js

44 lines
990 B
JavaScript
Raw Normal View History

2018-02-10 15:18:01 +00:00
import ngModule from '../module';
import isMobile from '../lib/is-mobile';
2019-10-15 14:19:35 +00:00
2020-04-01 14:05:43 +00:00
export function focus($timeout, input) {
2019-10-15 14:19:35 +00:00
if (isMobile) return;
const element = input;
2020-04-01 14:05:43 +00:00
const selector = 'input, textarea, button, submit';
2019-02-22 11:27:56 +00:00
if (!input.matches(selector))
input = input.querySelector(selector);
if (!input) {
const focusEvent = new MouseEvent('focus', {
bubbles: true,
cancelable: true,
view: window
});
element.dispatchEvent(focusEvent);
2019-02-22 11:27:56 +00:00
return;
}
2020-04-01 14:05:43 +00:00
$timeout(() => {
input.focus();
if (input.select)
2019-10-30 15:57:14 +00:00
input.select();
2020-04-01 14:05:43 +00:00
});
2019-02-22 11:27:56 +00:00
}
2020-04-01 14:05:43 +00:00
/*
2018-02-10 15:18:01 +00:00
* Sets the focus and selects the text on the input.
*/
2020-04-01 14:05:43 +00:00
export function directive($timeout) {
return {
restrict: 'A',
2019-02-22 11:27:56 +00:00
link: function($scope, $element) {
2020-04-01 14:05:43 +00:00
$scope.$watch('', () => focus($timeout, $element[0]));
}
};
}
2020-04-01 14:05:43 +00:00
directive.$inject = ['$timeout'];
2018-02-10 15:18:01 +00:00
ngModule.directive('vnFocus', directive);