Commit 51c19691 authored by Filipa Lacerda's avatar Filipa Lacerda

Merge branch 'kp-add-vue-input-autofocus-directive' into 'master'

Add `autofocusonshow` directive for input elements

See merge request gitlab-org/gitlab-ce!31584
parents a2d470d2 6f198583
/**
* Input/Textarea Autofocus Directive for Vue
*/
export default {
/**
* Set focus when element is rendered, but
* is not visible, using IntersectionObserver
*
* @param {Element} el Target element
*/
inserted(el) {
if ('IntersectionObserver' in window) {
// Element visibility is dynamic, so we attach observer
el.visibilityObserver = new IntersectionObserver(entries => {
entries.forEach(entry => {
// Combining `intersectionRatio > 0` and
// element's `offsetParent` presence will
// deteremine if element is truely visible
if (entry.intersectionRatio > 0 && entry.target.offsetParent) {
entry.target.focus();
}
});
});
// Bind the observer.
el.visibilityObserver.observe(el, { root: document.documentElement });
}
},
/**
* Detach observer on unbind hook.
*
* @param {Element} el Target element
*/
unbind(el) {
if (el.visibilityObserver) {
el.visibilityObserver.disconnect();
}
},
};
import autofocusonshow from '~/vue_shared/directives/autofocusonshow';
/**
* We're testing this directive's hooks as pure functions
* since behaviour of this directive is highly-dependent
* on underlying DOM methods.
*/
describe('AutofocusOnShow directive', () => {
describe('with input invisible on component render', () => {
let el;
beforeAll(() => {
setFixtures('<div id="container" style="display: none;"><input id="inputel"/></div>');
el = document.querySelector('#inputel');
});
it('should bind IntersectionObserver on input element', () => {
spyOn(el, 'focus');
autofocusonshow.inserted(el);
expect(el.visibilityObserver).toBeDefined();
expect(el.focus).not.toHaveBeenCalled();
});
it('should stop IntersectionObserver on input element on unbind hook', () => {
el.visibilityObserver = {
disconnect: () => {},
};
spyOn(el.visibilityObserver, 'disconnect');
autofocusonshow.unbind(el);
expect(el.visibilityObserver).toBeDefined();
expect(el.visibilityObserver.disconnect).toHaveBeenCalled();
});
});
});
Markdown is supported
0%
or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment