62b13513cf2c1a7fdedc35adf92e44cc18331b0c
[Packages/TYPO3.CMS.git] / typo3 / sysext / backend / Resources / Private / TypeScript / Modal.ts
1 /*
2 * This file is part of the TYPO3 CMS project.
3 *
4 * It is free software; you can redistribute it and/or modify it under
5 * the terms of the GNU General Public License, either version 2
6 * of the License, or any later version.
7 *
8 * For the full copyright and license information, please read the
9 * LICENSE.txt file that was distributed with this source code.
10 *
11 * The TYPO3 project - inspiring people to share!
12 */
13
14 import {SeverityEnum} from './Enum/Severity';
15 import 'bootstrap';
16 import * as $ from 'jquery';
17 import Icons = require('./Icons');
18 import Severity = require('./Severity');
19
20 enum Identifiers {
21 modal = '.t3js-modal',
22 content = '.t3js-modal-content',
23 title = '.t3js-modal-title',
24 close = '.t3js-modal-close',
25 body = '.t3js-modal-body',
26 footer = '.t3js-modal-footer',
27 iframe = '.t3js-modal-iframe',
28 iconPlaceholder = '.t3js-modal-icon-placeholder'
29 }
30
31 enum Sizes {
32 small = 'small',
33 default = 'default',
34 medium = 'medium',
35 large = 'large',
36 full = 'full'
37 }
38
39 enum Styles {
40 default = 'default',
41 light = 'light',
42 dark = 'dark'
43 }
44
45 enum Types {
46 default = 'default',
47 ajax = 'ajax',
48 iframe = 'iframe'
49 }
50
51 interface Button {
52 text: string;
53 active: boolean;
54 btnClass: string;
55 name: string;
56 trigger: (e: JQueryEventObject) => {};
57 dataAttributes: { [key: string]: string };
58 icon: string;
59 }
60
61 interface Configuration {
62 type: Types;
63 title: string;
64 content: string | JQuery;
65 severity: SeverityEnum;
66 buttons: Array<Button>;
67 style: string;
68 size: string;
69 additionalCssClasses: Array<string>;
70 callback: Function;
71 ajaxCallback: Function;
72 ajaxTarget: string;
73 }
74
75 /**
76 * Module: TYPO3/CMS/Backend/Modal
77 * API for modal windows powered by Twitter Bootstrap.
78 */
79 class Modal {
80 public readonly sizes: any = Sizes;
81 public readonly styles: any = Styles;
82 public readonly types: any = Types;
83 public currentModal: JQuery = null;
84 private instances: Array<JQuery> = [];
85 private readonly $template: JQuery = $(
86 '<div class="t3js-modal modal fade">' +
87 '<div class="modal-dialog">' +
88 '<div class="t3js-modal-content modal-content">' +
89 '<div class="modal-header">' +
90 '<button class="t3js-modal-close close">' +
91 '<span aria-hidden="true">' +
92 '<span class="t3js-modal-icon-placeholder" data-icon="actions-close"></span>' +
93 '</span>' +
94 '<span class="sr-only"></span>' +
95 '</button>' +
96 '<h4 class="t3js-modal-title modal-title"></h4>' +
97 '</div>' +
98 '<div class="t3js-modal-body modal-body"></div>' +
99 '<div class="t3js-modal-footer modal-footer"></div>' +
100 '</div>' +
101 '</div>' +
102 '</div>'
103 );
104
105 private defaultConfiguration: Configuration = {
106 type: Types.default,
107 title: 'Information',
108 content: 'No content provided, please check your <code>Modal</code> configuration.',
109 severity: SeverityEnum.notice,
110 buttons: [],
111 style: Styles.default,
112 size: Sizes.default,
113 additionalCssClasses: [],
114 callback: $.noop(),
115 ajaxCallback: $.noop(),
116 ajaxTarget: null
117 };
118
119 constructor() {
120 $(document).on('modal-dismiss', this.dismiss);
121 this.initializeMarkupTrigger(document);
122 }
123
124 /**
125 * Close the current open modal
126 */
127 public dismiss(): void {
128 if (this.currentModal) {
129 this.currentModal.modal('hide');
130 }
131 }
132
133 /**
134 * Shows a confirmation dialog
135 * Events:
136 * - button.clicked
137 * - confirm.button.cancel
138 * - confirm.button.ok
139 *
140 * @param {string} title The title for the confirm modal
141 * @param {string | JQuery} content The content for the conform modal, e.g. the main question
142 * @param {SeverityEnum} severity Default SeverityEnum.warning
143 * @param {Array<Button>} buttons An array with buttons, default no buttons
144 * @param {Array<string>} additionalCssClasses Additional css classes to add to the modal
145 * @returns {JQuery}
146 */
147 public confirm(title: string,
148 content: string | JQuery,
149 severity: SeverityEnum = SeverityEnum.warning,
150 buttons: Array<Object> = [],
151 additionalCssClasses?: Array<string>): JQuery {
152 if (buttons.length === 0) {
153 buttons.push(
154 {
155 text: $(this).data('button-close-text') || TYPO3.lang['button.cancel'] || 'Cancel',
156 active: true,
157 btnClass: 'btn-default',
158 name: 'cancel'
159 },
160 {
161 text: $(this).data('button-ok-text') || TYPO3.lang['button.ok'] || 'OK',
162 btnClass: 'btn-' + Severity.getCssClass(severity),
163 name: 'ok'
164 }
165 );
166 }
167
168 return this.advanced({
169 title,
170 content,
171 severity,
172 buttons,
173 additionalCssClasses,
174 callback: (currentModal: JQuery): void => {
175 currentModal.on('button.clicked', (e: JQueryEventObject): void => {
176 if (e.target.getAttribute('name') === 'cancel') {
177 $(e.currentTarget).trigger('confirm.button.cancel');
178 } else if (e.target.getAttribute('name') === 'ok') {
179 $(e.currentTarget).trigger('confirm.button.ok');
180 }
181 });
182 }
183 });
184 }
185
186 /**
187 * Load URL with AJAX, append the content to the modal-body
188 * and trigger the callback
189 *
190 * @param {string} title
191 * @param {SeverityEnum} severity
192 * @param {Array<Button>} buttons
193 * @param {string} url
194 * @param {Function} callback
195 * @param {string} target
196 * @returns {JQuery}
197 */
198 public loadUrl(title: string,
199 severity: SeverityEnum = SeverityEnum.info,
200 buttons: Array<Object>,
201 url: string,
202 callback: Function,
203 target: string
204 ): JQuery {
205 return this.advanced({
206 type: Types.ajax,
207 title,
208 severity,
209 buttons,
210 ajaxCallback: callback,
211 ajaxTarget: target
212 });
213 }
214
215 /**
216 * Shows a dialog
217 *
218 * @param {string} title
219 * @param {string | JQuery} content
220 * @param {number} severity
221 * @param {Array<Object>} buttons
222 * @param {Array<string>} additionalCssClasses
223 * @returns {JQuery}
224 */
225 public show(title: string,
226 content: string | JQuery,
227 severity: SeverityEnum = SeverityEnum.info,
228 buttons?: Array<Object>,
229 additionalCssClasses?: Array<string>): JQuery {
230 return this.advanced({
231 type: Types.default,
232 title,
233 content,
234 buttons,
235 additionalCssClasses
236 });
237 }
238
239 /**
240 * Loads modal by configuration
241 *
242 * @param {object} configuration configuration for the modal
243 */
244 public advanced(configuration: { [key: string]: any }): JQuery {
245 // Validation of configuration
246 configuration.type = typeof configuration.type === 'string' && configuration.type in Types
247 ? configuration.type
248 : this.defaultConfiguration.type;
249 configuration.title = typeof configuration.title === 'string'
250 ? configuration.title
251 : this.defaultConfiguration.title;
252 configuration.content = typeof configuration.content === 'string' || typeof configuration.content === 'object'
253 ? configuration.content
254 : this.defaultConfiguration.content;
255 configuration.severity = typeof configuration.severity !== 'undefined'
256 ? configuration.severity
257 : this.defaultConfiguration.severity;
258 configuration.buttons = <Array<Button>>configuration.buttons || this.defaultConfiguration.buttons;
259 configuration.size = typeof configuration.size === 'string' && configuration.size in Sizes
260 ? configuration.size
261 : this.defaultConfiguration.size;
262 configuration.style = typeof configuration.style === 'string' && configuration.style in Styles
263 ? configuration.style
264 : this.defaultConfiguration.style;
265 configuration.additionalCssClasses = configuration.additionalCssClasses || this.defaultConfiguration.additionalCssClasses;
266 configuration.callback = typeof configuration.callback === 'function' ? configuration.callback : this.defaultConfiguration.callback;
267 configuration.ajaxCallback = typeof configuration.ajaxCallback === 'function'
268 ? configuration.ajaxCallback
269 : this.defaultConfiguration.ajaxCallback;
270 configuration.ajaxTarget = typeof configuration.ajaxTarget === 'string'
271 ? configuration.ajaxTarget
272 : this.defaultConfiguration.ajaxTarget;
273
274 return this.generate(<Configuration>configuration);
275 }
276
277 /**
278 * Initialize markup with data attributes
279 *
280 * @param {HTMLDocument} theDocument
281 */
282 private initializeMarkupTrigger(theDocument: HTMLDocument): void {
283 $(theDocument).on('click', '.t3js-modal-trigger', (evt: JQueryEventObject): void => {
284 evt.preventDefault();
285 const $element = $(evt.currentTarget);
286 const content = $element.data('content') || 'Are you sure?';
287 const severity = typeof SeverityEnum[$element.data('severity')] !== 'undefined'
288 ? SeverityEnum[$element.data('severity')]
289 : SeverityEnum.info;
290 let url = $element.data('url') || null;
291 if (url !== null) {
292 const separator = (url.indexOf('?') > -1) ? '&' : '?';
293 const params = $.param({data: $element.data()});
294 url = url + separator + params;
295 }
296 this.advanced({
297 type: url !== null ? Types.ajax : Types.default,
298 title: $element.data('title') || 'Alert',
299 content: url !== null ? url : content,
300 severity,
301 buttons: [
302 {
303 text: $element.data('button-close-text') || 'Close',
304 active: true,
305 btnClass: 'btn-default',
306 trigger: (): void => {
307 this.currentModal.trigger('modal-dismiss');
308 }
309 },
310 {
311 text: $element.data('button-ok-text') || 'OK',
312 btnClass: 'btn-' + Severity.getCssClass(severity),
313 trigger: (): void => {
314 this.currentModal.trigger('modal-dismiss');
315 evt.target.ownerDocument.location.href = $element.data('href') || $element.attr('href');
316 }
317 }
318 ],
319 });
320 });
321 }
322
323 /**
324 * @param {Configuration} configuration
325 */
326 private generate(configuration: Configuration): JQuery {
327 const currentModal = this.$template.clone();
328 if (configuration.additionalCssClasses.length > 0) {
329 for (let additionalClass of configuration.additionalCssClasses) {
330 currentModal.addClass(additionalClass);
331 }
332 }
333 currentModal.addClass('modal-type-' + configuration.type);
334 currentModal.addClass('modal-severity-' + Severity.getCssClass(configuration.severity));
335 currentModal.addClass('modal-style-' + configuration.style);
336 currentModal.addClass('modal-size-' + configuration.size);
337 currentModal.attr('tabindex', '-1');
338 currentModal.find(Identifiers.title).text(configuration.title);
339 currentModal.find(Identifiers.close).on('click', (): void => {
340 currentModal.modal('hide');
341 });
342
343 if (configuration.type === 'ajax') {
344 $.get(
345 <string>configuration.content,
346 (response: string): void => {
347 this.currentModal.find(configuration.ajaxTarget ? configuration.ajaxTarget : Identifiers.body).empty().append(response);
348 if (configuration.ajaxCallback) {
349 configuration.ajaxCallback();
350 }
351 this.currentModal.trigger('modal-loaded');
352 },
353 'html'
354 );
355 Icons.getIcon('spinner-circle', Icons.sizes.default, null, null, Icons.markupIdentifiers.inline).done((icon: string): void => {
356 currentModal.find(Identifiers.body).html('<div class="modal-loading">' + icon + '</div>');
357 });
358 } else if (configuration.type === 'iframe') {
359 currentModal.find(Identifiers.body).append(
360 $('<iframe />', {
361 src: configuration.content,
362 'name': 'modal_frame',
363 'class': 'modal-iframe t3js-modal-iframe'
364 })
365 );
366 currentModal.find(Identifiers.iframe).on('load', (): void => {
367 currentModal.find(Identifiers.title).text(
368 (<HTMLIFrameElement>currentModal.find(Identifiers.iframe).get(0)).contentDocument.title
369 );
370 });
371 } else {
372 if (typeof configuration.content === 'string') {
373 // we need html, check if we have to wrap content in <p>
374 if (!/^<[a-z][\s\S]*>/i.test(configuration.content)) {
375 configuration.content = $('<p />').html(configuration.content);
376 }
377 }
378 currentModal.find(Identifiers.body).append(configuration.content);
379 }
380
381 // Add buttons
382 if (configuration.buttons.length > 0) {
383 for (let i = 0; i < configuration.buttons.length; i++) {
384 const button = configuration.buttons[i];
385 const $button = $('<button />', {'class': 'btn'});
386 $button.html('<span>' + button.text + '</span>');
387 if (button.active) {
388 $button.addClass('t3js-active');
389 }
390 if (button.btnClass !== '') {
391 $button.addClass(button.btnClass);
392 }
393 if (button.name !== '') {
394 $button.attr('name', button.name);
395 }
396 if (button.trigger) {
397 $button.on('click', button.trigger);
398 }
399 if (button.dataAttributes) {
400 if (Object.keys(button.dataAttributes).length > 0) {
401 Object.keys(button.dataAttributes).map((value: string): any => {
402 $button.attr('data-' + value, button.dataAttributes[value]);
403 });
404 }
405 }
406 if (button.icon) {
407 $button.prepend('<span class="t3js-modal-icon-placeholder" data-icon="' + button.icon + '"></span>');
408 }
409 currentModal.find(Identifiers.footer).append($button);
410 }
411 currentModal
412 .find(Identifiers.footer).find('button')
413 .on('click', (e: JQueryEventObject): void => {
414 $(e.currentTarget).trigger('button.clicked');
415 });
416 } else {
417 currentModal.find(Identifiers.footer).remove();
418 }
419
420 currentModal.on('shown.bs.modal', (e: JQueryEventObject): void => {
421 const $me = $(e.currentTarget);
422 // focus the button which was configured as active button
423 $me.find(Identifiers.footer).find('.t3js-active').first().focus();
424 // Get Icons
425 $me.find(Identifiers.iconPlaceholder).each((index: number, elem: Element): void => {
426 Icons.getIcon($(elem).data('icon'), Icons.sizes.small, null, null, Icons.markupIdentifiers.inline).done((icon: string): void => {
427 this.currentModal.find(Identifiers.iconPlaceholder + '[data-icon=' + $(icon).data('identifier') + ']').replaceWith(icon);
428 });
429 });
430 });
431
432 // Remove modal from Modal.instances when hidden
433 currentModal.on('hidden.bs.modal', (e: JQueryEventObject): void => {
434 if (this.instances.length > 0) {
435 const lastIndex = this.instances.length - 1;
436 this.instances.splice(lastIndex, 1);
437 this.currentModal = this.instances[lastIndex - 1];
438 }
439 currentModal.trigger('modal-destroyed');
440 $(e.currentTarget).remove();
441 // Keep class modal-open on body tag as long as open modals exist
442 if (this.instances.length > 0) {
443 $('body').addClass('modal-open');
444 }
445 });
446
447 // When modal is opened/shown add it to Modal.instances and make it Modal.currentModal
448 currentModal.on('show.bs.modal', (e: JQueryEventObject): void => {
449 this.currentModal = $(e.currentTarget);
450 this.instances.push(this.currentModal);
451 });
452 currentModal.on('modal-dismiss', (e: JQueryEventObject): void => {
453 // Hide modal, the bs.modal events will clean up Modal.instances
454 $(e.currentTarget).modal('hide');
455 });
456
457 if (configuration.callback) {
458 configuration.callback(currentModal);
459 }
460
461 return currentModal.modal();
462 }
463 }
464
465 let modalObject: Modal = null;
466 try {
467 if (parent && parent.window.TYPO3 && parent.window.TYPO3.Modal) {
468 // fetch from parent
469 // we need to trigger the event capturing again, in order to make sure this works inside iframes
470 parent.window.TYPO3.Modal.initializeMarkupTrigger(document);
471 modalObject = parent.window.TYPO3.Modal;
472 } else if (top && top.TYPO3.Modal) {
473 // fetch object from outer frame
474 // we need to trigger the event capturing again, in order to make sure this works inside iframes
475 top.TYPO3.Modal.initializeMarkupTrigger(document);
476 modalObject = top.TYPO3.Modal;
477 }
478 } catch (e) {
479 // This only happens if the opener, parent or top is some other url (eg a local file)
480 // which loaded the current window. Then the browser's cross domain policy jumps in
481 // and raises an exception.
482 // For this case we are safe and we can create our global object below.
483 }
484
485 if (!modalObject) {
486 modalObject = new Modal();
487
488 // expose as global object
489 TYPO3.Modal = modalObject;
490 }
491
492 export = modalObject;