salix/front/core/directives/zoom-image.js

61 lines
1.7 KiB
JavaScript
Raw Normal View History

2018-02-13 12:15:03 +00:00
import ngModule from '../module';
import './zoom-image.scss';
2018-02-13 12:15:03 +00:00
export function directive($timeout) {
let container;
2018-03-01 18:35:32 +00:00
let keyDownHandler;
2018-02-13 12:15:03 +00:00
function createContainers(src) {
2018-03-01 18:35:32 +00:00
destroyContainers();
2018-02-13 12:15:03 +00:00
2018-03-01 18:35:32 +00:00
container = document.createElement('div');
container.className = 'vn-zoom-image';
container.addEventListener('click', destroyContainers);
2018-02-13 12:15:03 +00:00
2018-03-01 18:35:32 +00:00
let wrapper = document.createElement('div');
container.appendChild(wrapper);
2018-02-13 12:15:03 +00:00
2018-03-01 18:35:32 +00:00
let background = document.createElement('img');
background.src = src;
wrapper.appendChild(background);
2018-02-13 12:15:03 +00:00
2018-03-01 18:35:32 +00:00
document.body.appendChild(container);
keyDownHandler = e => onKeyDown(e);
document.addEventListener('keydown', keyDownHandler);
2018-02-13 12:15:03 +00:00
}
2018-03-01 18:35:32 +00:00
function onKeyDown(event) {
if (event.key === 'Escape')
2018-02-13 12:15:03 +00:00
destroyContainers();
}
function destroyContainers() {
2018-03-01 18:35:32 +00:00
if (!container) return;
2018-02-13 12:15:03 +00:00
2018-03-01 18:35:32 +00:00
container.removeEventListener('click', destroyContainers);
container.parentNode.removeChild(container);
2018-02-13 12:15:03 +00:00
container = undefined;
2018-03-01 18:35:32 +00:00
document.removeEventListener('keydown', keyDownHandler);
keyDownHandler = undefined;
2018-02-13 12:15:03 +00:00
}
return {
restrict: 'A',
link: function($scope, $element, $attrs) {
$element.on('click', function(event) {
2019-10-24 08:17:32 +00:00
if (event.defaultPrevented) return;
2018-03-01 18:35:32 +00:00
2018-02-13 12:15:03 +00:00
let src = $attrs.zoomImage || $attrs.src;
if (src)
2018-02-13 12:15:03 +00:00
createContainers(src);
else
2018-02-13 12:15:03 +00:00
throw new Error('No image source detected');
});
}
};
}
directive.$inject = ['$timeout'];
ngModule.directive('zoomImage', directive);