/**
* SPDX-FileCopyrightText: 2018 Nextcloud GmbH and Nextcloud contributors
* SPDX-License-Identifier: AGPL-3.0-or-later
*/
import $ from 'jquery'
import { createFocusTrap } from 'focus-trap'
import { isA11yActivation } from '../Util/a11y.js'
$.widget('oc.ocdialog', {
options: {
width: 'auto',
height: 'auto',
closeButton: true,
closeOnEscape: true,
closeCallback: null,
modal: false,
},
_create() {
const self = this
this.originalCss = {
display: this.element[0].style.display,
width: this.element[0].style.width,
height: this.element[0].style.height,
}
this.originalTitle = this.element.attr('title')
this.options.title = this.options.title || this.originalTitle
this.$dialog = $('
')
.attr({
// Setting tabIndex makes the div focusable
tabIndex: -1,
role: 'dialog',
'aria-modal': true,
})
.insertBefore(this.element)
this.$dialog.append(this.element.detach())
this.element.removeAttr('title').addClass('oc-dialog-content').appendTo(this.$dialog)
// Activate the primary button on enter if there is a single input
if (self.element.find('input').length === 1) {
const $input = self.element.find('input')
$input.on('keydown', function(event) {
if (isA11yActivation(event)) {
if (self.$buttonrow) {
const $button = self.$buttonrow.find('button.primary')
if ($button && !$button.prop('disabled')) {
$button.click()
}
}
}
})
}
this.$dialog.css({
display: 'inline-block',
position: 'fixed',
})
this.enterCallback = null
$(document).on('keydown keyup', function(event) {
if (
event.target !== self.$dialog.get(0)
&& self.$dialog.find($(event.target)).length === 0
) {
return
}
// Escape
if (
event.keyCode === 27
&& event.type === 'keydown'
&& self.options.closeOnEscape
) {
event.stopImmediatePropagation()
self.close()
return false
}
// Enter
if (event.keyCode === 13) {
event.stopImmediatePropagation()
if (self.enterCallback !== null) {
self.enterCallback()
event.preventDefault()
return false
}
if (event.type === 'keyup') {
event.preventDefault()
return false
}
return false
}
})
this._setOptions(this.options)
this._createOverlay()
this._useFocusTrap()
},
_init() {
this._trigger('open')
},
_setOption(key, value) {
const self = this
switch (key) {
case 'title':
if (this.$title) {
this.$title.text(value)
} else {
const $title = $(''
+ value
+ '
')
this.$title = $title.prependTo(this.$dialog)
}
this._setSizes()
break
case 'buttons':
if (this.$buttonrow) {
this.$buttonrow.empty()
} else {
const $buttonrow = $('')
this.$buttonrow = $buttonrow.appendTo(this.$dialog)
}
if (value.length === 1) {
this.$buttonrow.addClass('onebutton')
} else if (value.length === 2) {
this.$buttonrow.addClass('twobuttons')
} else if (value.length === 3) {
this.$buttonrow.addClass('threebuttons')
}
$.each(value, function(idx, val) {
const $button = $('