Dialog
<et2-dialog> | Et2Dialog
Overview
A common dialog widget that makes it easy to inform users or prompt for information.
<et2-dialog title="Dialog" class="dialog-overview" buttons="0">
This is the dialog
</et2-dialog>
<sl-button>Open Dialog</sl-button>
<script>
const dialog = document.querySelector(".dialog-overview");
const button = dialog.nextElementSibling;
// Our dialogs always open on their own, not so good for docs
dialog.open=false;
button.addEventListener('click', () => dialog.show());
</script>
While most widgets are expected to be used via .XET files, Et2Dialog is primarily used via javascript, and
usually with Et2Dialog.show_dialog(). Et2Dialog extends
SlDialog.
// All parameters are optional
const dialog = Et2Dialog.show_dialog(
/* callback (button, value) => {} or null if you're using the promise*/ null,
/* Message */ "Would you like to do the thing?",
/* Title */ "Dialog title",
/* Value */ {/* Passed to callback */},
/* Buttons */ Et2Dialog.BUTTONS_OK_CANCEL
);
// Wait for user
let [button, value] = await dialog.getComplete();
// Do stuff
// or
dialog.getComplete().then(([button, value]) =>
{
// Do stuff
});
In your callback or after the getComplete() Promise resolves, you should check which button was
pressed.
let callback = function (button_id)
{
if (button_id == Et2Dialog.YES_BUTTON)
{
// Do stuff
}
else if (button_id == Et2Dialog.NO_BUTTON)
{
// Other stuff
}
else if (button_id == Et2Dialog.CANCEL_BUTTON)
{
// Abort
}
};
dialog = Et2Dialog.show_dialog(
callback, "Erase the entire database?", "Break things", {}, // value
Et2Dialog.BUTTONS_YES_NO_CANCEL, Et2Dialog.WARNING_MESSAGE
);
The parameters for the Et2Dialog.show_dialog() are all optional.
- callback - function called when the dialog closes, or false/null. The ID of the button will be passed. Button ID will be one of the Et2Dialog.*_BUTTON constants. The callback is not called if the user closes the dialog with the X in the corner, or presses ESC.
- message - (plain) text to display
- title - Dialog title
- value (for prompt)
- buttons - Et2Dialog BUTTONS_* constant, or an array of button settings. Use DialogButton interface.
- dialog_type - Et2Dialog *_MESSAGE constant
- icon - name of icon
Note that these methods will not block program flow while waiting for user input.
Examples
Pre-defined dialogs
We have several pre-defined dialogs that can be easily used from javascript for specific purposes.
Et2Dialog.alert(message, title), Et2Dialog.prompt(message, title) and
Et2Dialog.confirm(message, title)
<et2-hbox>
<et2-button class="alert">Alert</et2-button>
<et2-button class="prompt">Prompt</et2-button>
<et2-button class="confirm">Confirm</et2-button>
</et2-hbox>
<script>
const alertButton = document.querySelector(".alert");
alertButton.addEventListener("click", () => {
Et2Dialog.alert("Alert dialog message", "Alert title");
});
const promptButton = document.querySelector(".prompt");
promptButton.addEventListener("click", () => {
Et2Dialog.show_prompt((button, value) => {
Et2Dialog.alert("Button: " + button+ " You entered " + value, "Prompt value");
},
"Please enter your name", "Prompt dialog"
);});
const confirmButton = document.querySelector(".confirm");
confirmButton.addEventListener("click", () => {
Et2Dialog.confirm(/* senders? */null, "Are you sure you want to delete this?", "Confirm title");
});
</script>
Template
You can define a dialog inside your template, and use it as needed in your app:
<template id="dialog_example">
<!-- The rest of the application template goes here -->
<!-- destroyOnClose="false" because we intend to re-use the dialog -->
<et2-dialog id="change_owner" destroyOnClose="false" buttons="1">
<et2-select-account id="new_owner" label="New owner"></et2-select-account>
<!-- Anything can go here -->
</et2-dialog>
</template>
async function changeOwner(entry : { owner : number })
{
const dialog = document.querySelector("#change_owner");
dialog.show();
// Wait for answer
let [button, value] = await dialog.getComplete();
if(button)
{
entry.owner = value.new_owner;
}
}
Or more commonly, load a template inside the dialog with the template attribute:
<template id="dialog_contents">
<et2-select-account id="owner" label="Set owner"></et2-select-account>
</template>
async function changeOwner(entry : { owner : number })
{
// Pass egw in the constructor
let dialog = new Et2Dialog(this.egw);
dialog.transformAttributes({
template: "my_app/templates/default/dialog_contents.xet",
value: {owner: entry.owner}
});
// Add to DOM, dialog will auto-open
document.body.appendChild(dialog);
// Wait for answer
let [button, value] = await dialog.getComplete();
if(button)
{
entry.owner = value.new_owner;
}
}
Buttons
The easiest way to put buttons on the dialog is to use one of the button constants:
Et2Dialog.BUTTONS_OK, Et2Dialog.BUTTONS_OK_CANCEL,
Et2Dialog.BUTTONS_YES_NO, Et2Dialog.BUTTONS_YES_NO_CANCEL. This also ensures
consistancy across all dialogs.
<et2-hbox class="button-constants">
<et2-button class="OK">BUTTONS_OK</et2-button>
<et2-button class="OK_CANCEL">BUTTONS_OK_CANCEL</et2-button>
<et2-button class="YES_NO">BUTTONS_YES_NO</et2-button>
<et2-button class="YES_NO_CANCEL">BUTTONS_YES_NO_CANCEL</et2-button>
</et2-hbox>
<script>
const buttonBox = document.querySelector(".button-constants");
Array.from(buttonBox.children).forEach(button => {
button.addEventListener("click", () => {
Et2Dialog.show_dialog(null, button.textContent.trim() + " = " + Et2Dialog[button.textContent.trim()], "Button constant", null, Et2Dialog[button.textContent.trim()]);
});
});
</script>
Custom buttons
Sometimes the pre-defined buttons are insufficient. You can provide your own list of buttons, following the
DialogButton interface.
<et2-button class="custom-buttons">Custom buttons</et2-button>
<script>
const button = document.querySelector(".custom-buttons");
const customButtons /* : DialogButton[] */ = [
// These buttons will use the callback or getComplete() Promise, just like normal.
{label: "OK", id: "OK", default: true},
{label: "Yes", id: "Yes"},
{label: "Sure", id: "Sure", disabled: true},
{label: "Maybe", click: function() {
// If you override the click handler, 'this' will be the dialog.
// Things get more complicated, so doing this is not recommended
}
},
{label: "Negative choice", id:"No", align: "right"}
];
button.addEventListener("click", () => {
let dialog = Et2Dialog.show_dialog(null, "Custom buttons", "Custom buttons", null, customButtons);
});
</script>
// Pass egw in the constructor
let dialog = new Et2Dialog(my_egw_reference);
// Set attributes. They can be set in any way, but this is convenient.
dialog.transformAttributes({
// If you use a template, the second parameter will be the value of the template, as if it were submitted.
callback: function(button_id, value) {...}, // return false to prevent dialog closing
buttons: [
// These ones will use the callback, just like normal. Use DialogButton interface.
{label: egw.lang("OK"), id: "OK", default: true},
{label: egw.lang("Yes"), id: "Yes"},
{label: egw.lang("Sure"), id: "Sure"},
{
label: egw.lang("Maybe"), click: function()
{
// If you override, 'this' will be the dialog DOMNode.
// Things get more complicated.
// Do what you like here
}
},
],
title: 'Why would you want to do this?',
template: "/egroupware/addressbook/templates/default/edit.xet",
value: {content: {...default values}, sel_options: {...}...}
});
// Add to DOM, dialog will auto-open
document.body.appendChild(dialog);
// If you want, wait for close
let result = await dialog.getComplete();
Slots
| Name | Description |
|---|---|
| (default) | The dialog’s main content |
label
|
The dialog’s title. Alternatively, you can use the title attribute. |
header-actions
|
Optional actions to add to the header. Works best with |
footer
|
The dialog’s footer, where we put the buttons. |
Learn more about using slots.
Properties
| Name | Description | Reflects | Type | Default |
|---|---|---|---|---|
buttons
|
Pre-defined group of buttons, one of the BUTTONS_* |
Number
|
- | |
callback
|
Function called when the dialog is closed Wait for dialog.getComplete() instead |
Function
|
- | |
destroyOnClose
|
Automatically destroy the dialog when it closes. Set to false to keep the dialog around. |
boolean
|
true
|
|
dialog_type
|
Pre-defined dialog styles |
number
|
- | |
eTemplate
|
The loaded etemplate2 object. Only available if template is set |
- | - | |
hideOnEscape
|
When it’s set to false dialog won’t get closed by hitting Esc |
boolean
|
- | |
icon
|
Include an icon on the dialog |
string
|
- | |
isModal
|
Allow other controls to be accessed while the dialog is visible while not conflicting with internal attribute |
|
boolean
|
false
|
message
|
Message to show to user |
string
|
- | |
noCloseButton
|
When set to true it removes the close button from dialog’s header |
|
boolean
|
- |
PLAIN_MESSAGE
|
Types |
number
|
0
|
|
template
|
Getter for template name. Historically this returned the etemplate2 widget, but this was incorrect
and has been fixed. Use eTemplate instead of template to access the
etemplate2 widget.
|
- | - | |
title
|
Title for the dialog, goes in the header |
string
|
- | |
value
|
Returns the values of any widgets in the dialog. This does not include the buttons, which are only supplied for the callback. |
Object
|
- |
Learn more about attributes and properties.
Inherited properties (24)
Et2Widget
| Name | Description |
|---|---|
accesskey |
Accesskey provides a hint for generating a keyboard shortcut for the current element. The attribute value must consist of a single printable character. |
actions |
Set Actions on the widget Each action is defined as an object: move: { type: “drop”, acceptedTypes: “mail”, icon: “move”, caption: “Move to” onExecute: javascript:mail_move” } This will turn the widget into a drop target for “mail” drag types. When “mail” drag types are dropped, the global function mail_move(egwAction action, egwActionObject sender) will be called. The ID of the dragged “mail” will be in sender.id, some information about the sender will be in sender.context. The etemplate2 widget involved can typically be found in action.parent.data.widget, so your handler can operate in the widget context easily. The location varies depending on your action though. It might be action.parent.parent.data.widget To customise how the actions are handled for a particular widget, override _link_actions(). It handles the more widget-specific parts. |
align |
Used by Et2Box to determine alignment. Allowed values are left, right |
class |
CSS Class. This class is applied to the outside, on the web component itself. Due to how WebComponents work, this might not change anything inside the component. |
data |
Set the dataset from a CSV |
deferredProperties |
Any attribute that refers to row content cannot be resolved immediately, but some like booleans cannot stay a string because it’s a boolean attribute. We store them for later, and parse when they’re fully in their row. If you are creating a widget that can go in a nextmatch row, and it has boolean attributes that can change for each row, add those attributes into deferredProperties |
disabled |
Defines whether this widget is visibly disabled. The widget is still visible, but clearly cannot be interacted with. Widgets disabled in the template will not return a value to the application code, even if re-enabled via javascript before submitting. To allow a disabled widget to be re-enabled and return a value, disable via javascript in the app’s et2_ready() instead of an attribute in the template file. |
dom_id |
Get the actual DOM ID, which has been prefixed to make sure it’s unique. |
full |
Take every column of a layout, the same as span="all". Boolean rather than a bare
marker so it can be driven from content the way the rest of the template can -
full="@is_wide" resolves through the array manager like any other boolean attribute.
That does mean it needs a value: write full="true", since an empty
full="" resolves to false and removes the attribute again. Reflects for the same
reason grow does.
|
grow |
How much of a layout’s leftover space this widget should take. Only means anything inside a
container that has a layout (see Et2LayoutController): a bare grow or
grow="1" takes an equal share of whatever the non-growing children left over,
grow="2" takes twice what a grow="1" sibling does. It has to reflect.
The layout stylesheet matches the [grow] attribute - CSS cannot see a property - and
transformAttributes() only calls setAttribute() for an attribute the element already carries or a
property declared as reflecting. Widgets built from a .xet are created with
document.createElement() and handed their attributes as an object, so they carry none at that
point: without this declaration grow="1" lands as an inert JS property and nothing in
the layout ever matches it.
|
hidden |
The widget is not visible. As far as the user is concerned, the widget does not exist. Widgets hidden with an attribute in the template may not be created in the DOM, and will not return a value. Widgets can be hidden after creation, and they may return a value if hidden this way. |
id |
Get the ID of the widget |
label |
The label of the widget This is usually displayed in some way. It’s also important for accessability. This is defined in the parent somewhere, and re-defining it causes labels to disappear |
noLang |
Disable any translations for the widget |
parentId |
Parent is different than what is specified in the template / hierarchy. Widget ID of another node to insert this node into instead of the normal location |
span |
How many of a layout’s columns this widget should take.
span="all" is every column wherever the widget landed, span="end" /
span="*" is from its own column to the end of its line. Only means anything inside a
container that has a layout, and only for the column layouts -
stack gives every child the full width anyway. The same name is also read straight
off the XML node by the legacy <grid> widget, for the unrelated job of counting
table cells to merge; that path never looks at the widget, so declaring it here does not disturb
it. Reflecting it does mean a legacy grid’s span="all" cells now carry the attribute
too, which matches nothing outside a layout. Reflects for the same reason grow does.
|
statustext |
Tooltip which is shown for this element on hover |
styles |
WebComponent * |
options |
Get property-values as object |
supportedWidgetClasses |
et2_widget compatability |
SlDialog (Shoelace)
| Name | Description |
|---|---|
modal |
Exposes the internal modal utility that controls focus trapping. To temporarily disable focus
trapping and allow third-party modals spawned from an active Shoelace modal, call
modal.activateExternal() when the third-party modal opens. Upon closing, call
modal.deactivateExternal() to restore Shoelace’s focus trapping.
|
noHeader |
Disables the header. This will also remove the default close button, so please ensure you provide an easy, accessible way for users to dismiss the dialog. |
open |
Indicates whether or not the dialog is open. You can toggle this attribute to show and hide the
dialog, or you can use the show() and hide() methods and this attribute
will reflect the dialog’s open state.
|
LitElement
| Name | Description |
|---|---|
updateComplete |
A read-only promise that resolves when the component has finished updating. |
Events
| Name | Description | Event Detail |
|---|---|---|
open |
Emitted when the dialog opens |
Event
|
close |
Emitted when the dialog closes |
Event
|
before-load |
Emitted before the dialog opens |
CustomEvent
|
sl-request-close |
Missing description |
CustomEvent
|
Learn more about events.
Methods
| Name | Description | Arguments |
|---|---|---|
alert()
|
Show an alert message with OK button |
_message: string, _title: string, _type: integer
|
close()
|
Hide the dialog. Depending on destroyOnClose, it may be removed as well N.B. We can’t have open() because it conflicts with SlDialog. Use show() instead. | - |
confirm()
|
Method to build a confirmation dialog only with YES OR NO buttons and submit content back to server |
_senders: widget, _dialogMsg: string, _titleMsg: string, _postSubmit: boolean
|
confirm_file()
|
Show a dialog to confirm overwriting an existing file or suggest a new name |
etemplate_exec_id: string, path: string, filename: string, mimetype: string, noConfirm: boolean,
_egw_or_appname: string | IegwAppLocal, egw: string|IegwAppLocal
|
long_task()
|
Show a dialog for a long-running, multi-part task Given a server url and a list of parameters, this will open a dialog with a progress bar, asynchronously call the url with each parameter, and update the progress bar. Any output from the server will be displayed in a box. When all tasks are done, the callback will be called with boolean true. It will also be called if the user clicks a button (OK or CANCEL), so be sure to check to avoid executing more than intended. |
_callback: function, _message: string, _title: string, _item_callback: string|function, _list:
Array[], _egw_or_appname: string|egw
|
show_dialog()
|
Show a confirmation dialog |
_callback: function, _message: string, _title: string, _value: object, _buttons: integer|array,
_type: integer, _icon: string, _egw_or_appname: string|egw
|
show_prompt()
|
Show a prompt dialog |
_callback: function, _message: string, _title: string, _value: string, _buttons: integer|array,
_egw_or_appname: string|egw
|
_adoptTemplateButtons()
|
Search for buttons in the template, and try to slot them We don’t want to just grab them all, as there may be other buttons. | - |
_noteEnterKeyDown()
|
Keep the keydown half of an Enter around so its keyup can ask what became of it, see handleKeyUp() |
event: KeyboardEvent
|
_onButtonClick()
|
Only internally do our onClick on buttons in the footer This calls _onClose() when the dialog is closed |
ev: MouseEvent
|
_onMoveResize()
|
Handle moving and resizing |
event: InteractEvent
|
_setApiInstance()
|
Inject application specific egw object with loaded translations into the dialog |
_egw_or_appname: string|egw
|
_setDefaultAutofocus()
|
Set autofocus on first input element if nothing has autofocus | - |
_setInitialSize()
|
Give the dialog an explicit pixel size, once, when it opens. Children that size themselves against the dialog (eg. a tabbox with tabsize=auto) need a definite size to work from, so we freeze whatever the content came out to. The measurement is taken with any size we set before removed again: measuring a panel that already carries an inline width/height would just write back an earlier - possibly premature - value, and the dialog would keep a size its content never fit into. Only the first call does anything, so a re-render (or the user resizing) does not reset the dialog to its content’s size. | - |
_shieldInteraction()
|
Keep the page out of the way while the user drags or resizes the dialog. Pointer events over an
<iframe> go to the iframe’s document, not ours, so as soon as the pointer leaves
the dialog and crosses one - eg. the Collabora editor, which fills the whole window - we stop
getting pointermove and never get the pointerup. The drag then appears to do nothing and leaves the
interaction hanging. Ignoring the pointer on every iframe for the duration of the interaction keeps
all of the events in our own document. Suppressing text selection goes with it: now that the pointer
sweeps over real content instead of an iframe, dragging the dialog would otherwise select whatever
it passes over.
|
_shield: boolean
|
Learn more about methods.
Inherited methods (23)
Et2Widget
| Name | Description |
|---|---|
checkCreateNamespace() |
Checks whether a namespace exists for this element in the content array. If yes, an own perspective of the content array is created. If not, the parent content manager is used. Constructor attributes are passed in case a child needs to make decisions |
clone() |
Creates a copy of this widget. |
createElementFromNode() |
Create a et2_widget from an XML node. First the type and attributes are read from the node. Then the readonly & modifications arrays are checked for changes specific to the loaded data. Then the appropriate constructor is called. After the constructor returns, the widget has a chance to further initialize itself from the XML node when the widget’s loadFromXML() method is called with the node. |
getArrayMgr() |
Returns the array manager object for the given part |
getArrayMgrs() |
Returns an associative array containing the top-most array managers. |
getChildren() |
Get child widgets Use |
getInstanceManager() |
Returns the instance manager |
getPath() |
Returns the path into the data array. By default, array manager takes care of this, but some extensions need to override this |
getRoot() |
Returns the base widget Usually this is the same as getInstanceManager().widgetContainer |
loadFromXML() |
Loads the widget tree from an XML node |
loadingFinished() |
Needed for legacy compatability. |
parseXMLAttrs() |
The parseXMLAttrs function takes an XML DOM attributes object and adds the given attributes to the _target associative array. This function also parses the legacyOptions. N.B. This is only used for legacy widgets. WebComponents use transformAttributes() and do their own handling of attributes. |
set_label() |
NOT the setter, since we cannot add to the DOM before connectedCallback() TODO: This is not best practice. Should just set property, DOM modification should be done in render https://lit-element.polymer-project.org/guide/templates#design-a-performant-template |
setArrayMgr() |
Sets the array manager for the given part |
setArrayMgrs() |
Sets all array manager objects - this function can be used to set the root array managers of the container object. |
setInstanceManager() |
Set the instance manager Normally this is not needed as it’s set on the top-level container, and we just return that reference |
_handleClick() |
Click handler calling custom handler set via onclick attribute to this.onclick |
destroy() |
et2_widget compatability |
set_class() |
Set the widget class |
set_disabled() |
Wrapper on this.disabled because legacy had it. |
set_statustext() |
supports legacy set_statustext |
SlDialog (Shoelace)
| Name | Description |
|---|---|
hide() |
Hides the dialog |
show() |
Shows the dialog. |
Related
These widgets are related by naming but not by inheritance or sub-widget composition.