UNPKG

@theia/core

Version:

Theia is a cloud & desktop IDE framework implemented in TypeScript.

478 lines • 17.9 kB
// ***************************************************************************** // Copyright (C) 2017 TypeFox and others. // // This program and the accompanying materials are made available under the // terms of the Eclipse Public License v. 2.0 which is available at // http://www.eclipse.org/legal/epl-2.0. // // This Source Code may also be made available under the following Secondary // Licenses when the conditions for such availability set forth in the Eclipse // Public License v. 2.0 are satisfied: GNU General Public License, version 2 // with the GNU Classpath Exception which is available at // https://www.gnu.org/software/classpath/license.html. // // SPDX-License-Identifier: EPL-2.0 OR GPL-2.0-only WITH Classpath-exception-2.0 // ***************************************************************************** var DialogOverlayService_1; import { __decorate, __param } from "tslib"; import { injectable, inject, unmanaged } from 'inversify'; import { Disposable, CancellationTokenSource, nls } from '../common/index.js'; import { Key } from './keyboard/keys.js'; import { Widget, BaseWidget, addKeyListener, codiconArray } from './widgets/widget.js'; let DialogProps = class DialogProps { }; DialogProps = __decorate([ injectable() ], DialogProps); export { DialogProps }; export var DialogError; (function (DialogError) { function getResult(error) { if (typeof error === 'string') { return !error.length; } if (typeof error === 'boolean') { return error; } return error.result; } DialogError.getResult = getResult; function getMessage(error) { if (typeof error === 'string') { return error; } if (typeof error === 'boolean') { return ''; } return error.message; } DialogError.getMessage = getMessage; })(DialogError || (DialogError = {})); export var Dialog; (function (Dialog) { Dialog.YES = nls.localizeByDefault('Yes'); Dialog.NO = nls.localizeByDefault('No'); Dialog.OK = nls.localizeByDefault('OK'); Dialog.CANCEL = nls.localizeByDefault('Cancel'); })(Dialog || (Dialog = {})); let DialogOverlayService = class DialogOverlayService { static { DialogOverlayService_1 = this; } static get() { return DialogOverlayService_1.INSTANCE; } constructor() { // eslint-disable-next-line @typescript-eslint/no-explicit-any this.dialogs = []; this.documents = []; } initialize() { DialogOverlayService_1.INSTANCE = this; } // eslint-disable-next-line @typescript-eslint/no-explicit-any get currentDialog() { return this.dialogs[0]; } // eslint-disable-next-line @typescript-eslint/no-explicit-any push(dialog) { this.ensureKeyListeners(dialog.node.ownerDocument); this.dialogs.unshift(dialog); return Disposable.create(() => { const index = this.dialogs.indexOf(dialog); if (index > -1) { this.dialogs.splice(index, 1); } }); } /** Add the key listeners for `ownerDocument`, unless they are there already. */ ensureKeyListeners(ownerDocument) { if (this.documents.indexOf(ownerDocument) < 0) { addKeyListener(ownerDocument.body, Key.ENTER, e => this.handleEnter(e)); addKeyListener(ownerDocument.body, Key.ESCAPE, e => this.handleEscape(e)); this.documents.push(ownerDocument); } } handleEscape(event) { const dialog = this.currentDialog; if (dialog) { return dialog['handleEscape'](event); } return false; } handleEnter(event) { const dialog = this.currentDialog; if (dialog) { return dialog['handleEnter'](event); } return false; } }; DialogOverlayService = DialogOverlayService_1 = __decorate([ injectable() ], DialogOverlayService); export { DialogOverlayService }; let AbstractDialog = class AbstractDialog extends BaseWidget { constructor(props, options) { if (props.targetWindow && !options?.node) { options = { ...options, node: props.targetWindow.document.createElement('div') }; } super(options); this.props = props; this.validateCancellationSource = new CancellationTokenSource(); this.acceptCancellationSource = new CancellationTokenSource(); this.id = 'theia-dialog-shell'; this.addClass('dialogOverlay'); this.toDispose.push(Disposable.create(() => { if (this.reject) { Widget.detach(this); } })); const container = this.node.ownerDocument.createElement('div'); container.classList.add('dialogBlock'); if (props.maxWidth === undefined) { container.setAttribute('style', 'max-width: none'); } else if (props.maxWidth < 400) { container.setAttribute('style', `max-width: ${props.maxWidth}px; min-width: 0px`); } else { container.setAttribute('style', `max-width: ${props.maxWidth}px`); } this.node.appendChild(container); const titleContentNode = this.node.ownerDocument.createElement('div'); titleContentNode.classList.add('dialogTitle'); container.appendChild(titleContentNode); this.titleNode = this.node.ownerDocument.createElement('div'); this.titleNode.textContent = props.title; titleContentNode.appendChild(this.titleNode); this.closeCrossNode = this.node.ownerDocument.createElement('i'); this.closeCrossNode.classList.add(...codiconArray('close', true)); this.closeCrossNode.classList.add('closeButton'); titleContentNode.appendChild(this.closeCrossNode); this.contentNode = this.node.ownerDocument.createElement('div'); this.contentNode.classList.add('dialogContent'); if (props.wordWrap !== undefined) { this.contentNode.setAttribute('style', `word-wrap: ${props.wordWrap}`); } container.appendChild(this.contentNode); this.controlPanel = this.node.ownerDocument.createElement('div'); this.controlPanel.classList.add('dialogControl'); container.appendChild(this.controlPanel); this.errorMessageNode = this.node.ownerDocument.createElement('div'); this.errorMessageNode.classList.add('error'); this.errorMessageNode.setAttribute('style', 'flex: 2'); this.controlPanel.appendChild(this.errorMessageNode); this.update(); } appendCloseButton(text = Dialog.CANCEL) { return this.closeButton = this.appendButton(text, false); } appendAcceptButton(text = Dialog.OK) { return this.acceptButton = this.appendButton(text, true); } appendButton(text, primary) { const button = this.createButton(text); this.controlPanel.appendChild(button); button.classList.add(primary ? 'main' : 'secondary'); return button; } createButton(text) { const button = this.node.ownerDocument.createElement('button'); button.classList.add('theia-button'); button.textContent = text; return button; } onAfterAttach(msg) { super.onAfterAttach(msg); if (this.closeButton) { this.addCloseAction(this.closeButton, 'click'); } if (this.acceptButton) { this.addAcceptAction(this.acceptButton, 'click'); } this.addCloseAction(this.closeCrossNode, 'click'); this.toDisposeOnDetach.push(this.preventTabbingOutsideDialog()); // TODO: use DI always to create dialog instances this.toDisposeOnDetach.push(DialogOverlayService.get().push(this)); } /** * This prevents tabbing outside the dialog by marking elements as inert, i.e., non-clickable and non-focussable. * * @param elements the elements for which we disable tabbing. By default all elements within the body element are considered. * Please note that this may also include other popups such as the suggestion overlay, the notification center or quick picks. * @returns a disposable that will restore the previous tabbing behavior */ preventTabbingOutsideDialog(elements = Array.from(this.node.ownerDocument.body.children)) { const inertBlacklist = ['select-component-container']; // IDs of elements that should remain interactive const nonInertElements = elements.filter(child => child !== this.node && !(child.hasAttribute('inert')) && !inertBlacklist.includes(child.id)); nonInertElements.forEach(child => child.setAttribute('inert', '')); return Disposable.create(() => nonInertElements.forEach(child => child.removeAttribute('inert'))); } handleEscape(event) { this.close(); } handleEnter(event) { if (event.target instanceof HTMLTextAreaElement) { return false; } this.accept(); } onActivateRequest(msg) { super.onActivateRequest(msg); if (this.acceptButton) { this.acceptButton.focus(); } } open(disposeOnResolve = true) { if (this.resolve) { return Promise.reject(new Error('The dialog is already opened.')); } this.activeElement = this.node.ownerDocument.activeElement; return new Promise((resolve, reject) => { this.resolve = value => { resolve(value); }; this.reject = reject; this.toDisposeOnDetach.push(Disposable.create(() => { this.resolve = undefined; this.reject = undefined; })); Widget.attach(this, this.node.ownerDocument.body); this.activate(); }).finally(() => { if (disposeOnResolve) { this.dispose(); } }); } onCloseRequest(msg) { // super.onCloseRequest() would automatically dispose the dialog, which we don't want because we're reusing it if (this.parent) { // eslint-disable-next-line no-null/no-null this.parent = null; } else if (this.isAttached) { Widget.detach(this); } } close() { if (this.resolve) { if (this.activeElement) { this.activeElement.focus({ preventScroll: true }); } this.resolve(undefined); } this.activeElement = undefined; super.close(); } onUpdateRequest(msg) { super.onUpdateRequest(msg); this.validate(); } async validate() { if (!this.resolve) { return; } this.validateCancellationSource.cancel(); this.validateCancellationSource = new CancellationTokenSource(); const token = this.validateCancellationSource.token; const value = this.value; const error = await this.isValid(value, 'preview'); if (token.isCancellationRequested) { return; } this.setErrorMessage(error); } async accept() { if (!this.resolve) { return; } this.acceptCancellationSource.cancel(); this.acceptCancellationSource = new CancellationTokenSource(); const token = this.acceptCancellationSource.token; const value = this.value; const error = await this.isValid(value, 'open'); if (token.isCancellationRequested) { return; } if (!DialogError.getResult(error)) { this.setErrorMessage(error); } else { this.resolve(value); Widget.detach(this); } } /** * Return a string of zero-length or true if valid. */ isValid(value, mode) { return ''; } setErrorMessage(error) { if (this.acceptButton) { this.acceptButton.disabled = !DialogError.getResult(error); } this.errorMessageNode.innerText = DialogError.getMessage(error); } addAction(element, callback, ...additionalEventTypes) { this.addKeyListener(element, Key.ENTER, callback, ...additionalEventTypes); } addCloseAction(element, ...additionalEventTypes) { this.addAction(element, () => this.close(), ...additionalEventTypes); } addAcceptAction(element, ...additionalEventTypes) { this.addAction(element, () => this.accept(), ...additionalEventTypes); } }; AbstractDialog = __decorate([ injectable(), __param(0, unmanaged()), __param(1, unmanaged()) ], AbstractDialog); export { AbstractDialog }; let MessageDialogProps = class MessageDialogProps extends DialogProps { }; MessageDialogProps = __decorate([ injectable() ], MessageDialogProps); export { MessageDialogProps }; let ConfirmDialogProps = class ConfirmDialogProps extends MessageDialogProps { }; ConfirmDialogProps = __decorate([ injectable() ], ConfirmDialogProps); export { ConfirmDialogProps }; let ConfirmDialog = class ConfirmDialog extends AbstractDialog { constructor(props, options) { super(props, options); this.props = props; this.confirmed = true; this.contentNode.appendChild(this.createMessageNode(this.props.msg)); this.appendCloseButton(props.cancel); this.appendAcceptButton(props.ok); } onCloseRequest(msg) { super.onCloseRequest(msg); this.confirmed = false; this.accept(); } get value() { return this.confirmed; } createMessageNode(msg) { if (typeof msg === 'string') { const messageNode = this.node.ownerDocument.createElement('div'); messageNode.textContent = msg; return messageNode; } return msg; } }; ConfirmDialog = __decorate([ __param(0, inject(ConfirmDialogProps)), __param(1, unmanaged()) ], ConfirmDialog); export { ConfirmDialog }; export async function confirmExit() { const safeToExit = await new ConfirmDialog({ title: nls.localizeByDefault('Are you sure you want to quit?'), msg: nls.localize('theia/core/quitMessage', 'Any unsaved changes will not be saved.'), ok: Dialog.YES, cancel: Dialog.NO, }).open(); return safeToExit === true; } export class ConfirmSaveDialogProps extends MessageDialogProps { } // Dialog prompting the user to confirm whether they wish to save changes or not let ConfirmSaveDialog = class ConfirmSaveDialog extends AbstractDialog { constructor(props) { super(props); this.props = props; this.result = false; // Append message and buttons to the dialog this.contentNode.appendChild(this.createMessageNode(this.props.msg)); this.closeButton = this.appendButtonAndSetResult(props.cancel, false); this.appendButtonAndSetResult(props.dontSave, false, false); this.acceptButton = this.appendButtonAndSetResult(props.save, true, true); } get value() { return this.result; } createMessageNode(msg) { if (typeof msg === 'string') { const messageNode = this.node.ownerDocument.createElement('div'); messageNode.textContent = msg; return messageNode; } return msg; } appendButtonAndSetResult(text, primary, result) { const button = this.appendButton(text, primary); button.addEventListener('click', () => { this.result = result; this.accept(); }); return button; } }; ConfirmSaveDialog = __decorate([ __param(0, inject(ConfirmSaveDialogProps)) ], ConfirmSaveDialog); export { ConfirmSaveDialog }; let SingleTextInputDialogProps = class SingleTextInputDialogProps extends DialogProps { }; SingleTextInputDialogProps = __decorate([ injectable() ], SingleTextInputDialogProps); export { SingleTextInputDialogProps }; let SingleTextInputDialog = class SingleTextInputDialog extends AbstractDialog { constructor(props) { super(props); this.props = props; this.inputField = this.node.ownerDocument.createElement('input'); this.inputField.type = 'text'; this.inputField.className = 'theia-input'; this.inputField.spellcheck = false; this.inputField.setAttribute('style', 'flex: 0;'); this.inputField.placeholder = props.placeholder || ''; this.inputField.value = props.initialValue || ''; if (props.initialSelectionRange) { this.inputField.setSelectionRange(props.initialSelectionRange.start, props.initialSelectionRange.end, props.initialSelectionRange.direction); } else { this.inputField.select(); } this.contentNode.appendChild(this.inputField); this.controlPanel.removeChild(this.errorMessageNode); this.contentNode.appendChild(this.errorMessageNode); this.appendAcceptButton(props.confirmButtonLabel); } get value() { return this.inputField.value; } isValid(value, mode) { if (this.props.validate) { return this.props.validate(value, mode); } return super.isValid(value, mode); } onAfterAttach(msg) { super.onAfterAttach(msg); this.addUpdateListener(this.inputField, 'input'); } onActivateRequest(msg) { this.inputField.focus(); } handleEnter(event) { if (event.target instanceof HTMLInputElement) { return super.handleEnter(event); } return false; } }; SingleTextInputDialog = __decorate([ __param(0, inject(SingleTextInputDialogProps)) ], SingleTextInputDialog); export { SingleTextInputDialog }; //# sourceMappingURL=dialogs.js.map