import {module} from '../module'; import Component from '../lib/component'; import './style.scss'; /** * Dialog component. */ export default class Dialog extends Component { /** * Contructor. */ constructor($element) { super($element); $element.addClass('vn-dialog'); this.dialog = $element[0].firstChild; this.element.addEventListener('mousedown', event => this.onBackgroundMouseDown(event)); } /** * Displays the dialog to the user. */ show() { let style = this.dialog.style; let screenMargin = 20; let window = this.window; let innerWidth = window.innerWidth; let innerHeight = window.innerHeight; let width = this.dialog.offsetWidth; let height = this.dialog.offsetHeight; if(width + screenMargin > innerWidth) { width = innerWidth - dblMargin; style.width = width +'px'; } if(height + screenMargin > innerHeight) { height = innerHeight - dblMargin; style.height = height +'px'; } this.keypressHandler = event => this.onKeypress(event); this.document.addEventListener('keypress', this.keypressHandler); this.element.style.display = 'block'; if(this.onOpen) this.onOpen(); } /** * Hides the dialog calling the response handler. */ hide() { this.fireResponse(); this.realHide(); } /** * Calls the response handler. */ fireResponse(response) { let cancel = false; if(this.onResponse) cancel = this.onResponse({response: response}); return cancel; } realHide() { this.element.style.display = 'none'; this.document.removeEventListener('keypress', this.keypressHandler); this.lastEvent = null; } onButtonClick(event) { let buttonBar = this.element.querySelector('.button-bar'); let buttons = buttonBar.querySelector('buttons'); let node = event.target; while(node.parentNode != buttons) { if(node == buttonBar) return; node = node.parentNode; } let response = node.getAttribute('response'); let cancel = this.fireResponse(response); if(cancel !== false) this.realHide(); } onDialogMouseDown(event) { this.lastEvent = event; } onBackgroundMouseDown(event) { if (event != this.lastEvent) this.hide(); } onKeypress(event) { if(event.keyCode == 27) // Esc this.hide(); } } Dialog.$inject = ['$element']; module.component('vnDialog', { template: require('./index.html'), transclude: { dbody: 'dbody', buttons: 'buttons' }, bindings: { onOpen: '&', onResponse: '&' }, controller: Dialog });