• Home
  • Features
  • Pricing
  • Docs
  • Announcements
  • Sign In

divio / django-cms / #29891

26 Aug 2025 01:24AM UTC coverage: 75.132% (+0.07%) from 75.059%
#29891

push

travis-ci

web-flow
Merge 09573ad01 into de255061d

1079 of 1626 branches covered (66.36%)

2568 of 3418 relevant lines covered (75.13%)

26.22 hits per line

Source File
Press 'n' to go to next uncovered line, 'b' for previous

96.62
/cms/static/cms/js/modules/cms.modal.js
1
/*
2
 * Copyright https://github.com/divio/django-cms
3
 */
4

5
import ChangeTracker from './cms.changetracker';
6
import keyboard from './keyboard';
7

8
import $ from 'jquery';
9
import './jquery.transition';
10
import './jquery.trap';
11

12
import { Helpers, KEYS } from './cms.base';
13
import { showLoader, hideLoader } from './loader';
14

15
var previousKeyboardContext;
16
var previouslyFocusedElement;
17

18
/**
19
 * The modal is triggered via API calls from the backend either
20
 * through the toolbar navigation or from plugins. The APIs allow to
21
 * open content from a url (iframe) or inject html directly.
22
 *
23
 * @class Modal
24
 * @namespace CMS
25
 */
26
class Modal {
27
    constructor(options) {
28
        this.options = $.extend(true, {}, Modal.options, options);
163✔
29

30
        // elements
31
        this._setupUI();
163✔
32

33
        // states and events
34
        this.click = 'click.cms.modal';
163✔
35
        this.pointerDown = 'pointerdown.cms.modal contextmenu.cms.modal';
163✔
36
        this.pointerUp = 'pointerup.cms.modal pointercancel.cms.modal';
163✔
37
        this.pointerMove = 'pointermove.cms.modal';
163✔
38
        this.doubleClick = 'dblclick.cms.modal';
163✔
39
        this.touchEnd = 'touchend.cms.modal';
163✔
40
        this.keyUp = 'keyup.cms.modal';
163✔
41
        this.maximized = false;
163✔
42
        this.minimized = false;
163✔
43
        this.triggerMaximized = false;
163✔
44
        this.saved = false;
163✔
45

46
        this._beforeUnloadHandler = this._beforeUnloadHandler.bind(this);
163✔
47
    }
48

49
    /**
50
     * Stores all jQuery references within `this.ui`.
51
     *
52
     * @method _setupUI
53
     * @private
54
     */
55
    _setupUI() {
56
        var modal = $('.cms-modal');
163✔
57

58
        this.ui = {
163✔
59
            modal: modal,
60
            body: $('html'),
61
            window: $(window),
62
            toolbarLeftPart: $('.cms-toolbar-left'),
63
            minimizeButton: modal.find('.cms-modal-minimize'),
64
            maximizeButton: modal.find('.cms-modal-maximize'),
65
            title: modal.find('.cms-modal-title'),
66
            titlePrefix: modal.find('.cms-modal-title-prefix'),
67
            titleSuffix: modal.find('.cms-modal-title-suffix'),
68
            resize: modal.find('.cms-modal-resize'),
69
            breadcrumb: modal.find('.cms-modal-breadcrumb'),
70
            closeAndCancel: modal.find('.cms-modal-close, .cms-modal-cancel'),
71
            modalButtons: modal.find('.cms-modal-buttons'),
72
            modalBody: modal.find('.cms-modal-body'),
73
            frame: modal.find('.cms-modal-frame'),
74
            shim: modal.find('.cms-modal-shim')
75
        };
76
    }
77

78
    /**
79
     * Sets up all the event handlers, such as maximize/minimize and resizing.
80
     *
81
     * @method _events
82
     * @private
83
     */
84
    _events() {
85
        var that = this;
34✔
86

87
        // modal behaviours
88
        this.ui.minimizeButton
34✔
89
            .off(this.click + ' ' + this.touchEnd + ' ' + this.keyUp)
90
            .on(this.click + ' ' + this.touchEnd + ' ' + this.keyUp, function(e) {
91
                if (e.type !== 'keyup' || (e.type === 'keyup' && e.keyCode === KEYS.ENTER)) {
4!
92
                    e.preventDefault();
4✔
93
                    that.minimize();
4✔
94
                }
95
            });
96
        this.ui.maximizeButton
34✔
97
            .off(this.click + ' ' + this.touchEnd + ' ' + this.keyUp)
98
            .on(this.click + ' ' + this.touchEnd + ' ' + this.keyUp, function(e) {
99
                if (e.type !== 'keyup' || (e.type === 'keyup' && e.keyCode === KEYS.ENTER)) {
4!
100
                    e.preventDefault();
4✔
101
                    that.maximize();
4✔
102
                }
103
            });
104

105
        this.ui.title.off(this.pointerDown).on(this.pointerDown, function(e) {
34✔
106
            e.preventDefault();
4✔
107
            that._startMove(e);
4✔
108
        });
109
        this.ui.title.off(this.doubleClick).on(this.doubleClick, function() {
34✔
110
            that.maximize();
2✔
111
        });
112

113
        this.ui.resize.off(this.pointerDown).on(this.pointerDown, function(e) {
34✔
114
            e.preventDefault();
4✔
115
            that._startResize(e);
4✔
116
        });
117

118
        this.ui.closeAndCancel
34✔
119
            .off(this.click + ' ' + this.touchEnd + ' ' + this.keyUp)
120
            .on(this.click + ' ' + this.touchEnd + ' ' + this.keyUp, function(e) {
121
                if (e.type !== 'keyup' || (e.type === 'keyup' && e.keyCode === KEYS.ENTER)) {
4!
122
                    e.preventDefault();
4✔
123
                    that._cancelHandler();
4✔
124
                }
125
            });
126

127
        // elements within the window
128
        this.ui.breadcrumb.off(this.click, 'a').on(this.click, 'a', function(e) {
34✔
129
            e.preventDefault();
2✔
130
            that._changeIframe($(this));
2✔
131
        });
132
    }
133

134
    /**
135
     * Opens the modal either in an iframe or renders markup.
136
     *
137
     * @method open
138
     * @chainable
139
     * @param {Object} opts either `opts.url` or `opts.html` are required
140
     * @param {Object[]} [opts.breadcrumbs] collection of breadcrumb items
141
     * @param {String|HTMLNode|jQuery} [opts.html] html markup to render
142
     * @param {String} [opts.title] modal window main title (bold)
143
     * @param {String} [opts.subtitle] modal window secondary title (normal)
144
     * @param {String} [opts.url] url to render iframe, takes precedence over `opts.html`
145
     * @param {Number} [opts.width] sets the width of the modal
146
     * @param {Number} [opts.height] sets the height of the modal
147
     * @returns {Class} this
148
     */
149
    open(opts) {
150
        // setup internals
151
        if (!((opts && opts.url) || (opts && opts.html))) {
35✔
152
            throw new Error('The arguments passed to "open" were invalid.');
4✔
153
        }
154

155
        // We have to rebind events every time we open a modal
156
        // because the event handlers contain references to the instance
157
        // and since we reuse the same markup we need to update
158
        // that instance reference every time.
159
        this._events();
31✔
160

161
        Helpers.dispatchEvent('modal-load', { instance: this });
31✔
162
        // // trigger the event also on the dom element,
163
        // // because if we load another modal while one is already open
164
        // // the older instance won't receive any updates
165
        // this.ui.modal.trigger('cms.modal.load');
166

167
        // common elements state
168
        this.ui.resize.toggle(this.options.resizable);
31✔
169
        this.ui.minimizeButton.toggle(this.options.minimizable);
31✔
170
        this.ui.maximizeButton.toggle(this.options.maximizable);
31✔
171

172
        const position = this._calculateNewPosition(opts);
31✔
173

174
        this.ui.maximizeButton.removeClass('cms-modal-maximize-active');
31✔
175
        this.maximized = false;
31✔
176

177
        // because a new instance is called, we have to ensure minimized state is removed #3620
178
        if (this.ui.body.hasClass('cms-modal-minimized')) {
31✔
179
            this.minimized = true;
1✔
180
            this.minimize();
1✔
181
        }
182

183
        // clear elements
184
        this.ui.modalButtons.empty();
31✔
185
        this.ui.breadcrumb.empty();
31✔
186

187
        // remove class from modal when no breadcrumbs is rendered
188
        this.ui.modal.removeClass('cms-modal-has-breadcrumb');
31✔
189

190
        // hide tooltip
191
        CMS.API.Tooltip.hide();
31✔
192

193
        // redirect to iframe rendering if url is provided
194
        if (opts.url) {
31✔
195
            this._loadIframe({
1✔
196
                url: opts.url,
197
                title: opts.title,
198
                breadcrumbs: opts.breadcrumbs
199
            });
200
        } else {
201
            // if url is not provided we go for html
202
            this._loadMarkup({
30✔
203
                html: opts.html,
204
                title: opts.title,
205
                subtitle: opts.subtitle
206
            });
207
        }
208

209
        Helpers.dispatchEvent('modal-loaded', { instance: this });
31✔
210

211
        var currentContext = keyboard.getContext();
31✔
212

213
        if (currentContext !== 'modal') {
31✔
214
            previousKeyboardContext = keyboard.getContext();
9✔
215
            previouslyFocusedElement = $(document.activeElement);
9✔
216
        }
217

218
        // display modal
219
        this._show(
31✔
220
            $.extend(
221
                {
222
                    duration: this.options.modalDuration
223
                },
224
                position
225
            )
226
        );
227

228
        keyboard.setContext('modal');
31✔
229
        this.ui.modal.trap();
31✔
230

231
        return this;
31✔
232
    }
233

234
    /**
235
     * Calculates coordinates and dimensions for modal placement
236
     *
237
     * @method _calculateNewPosition
238
     * @private
239
     * @param {Object} [opts]
240
     * @param {Number} [opts.width] desired width of the modal
241
     * @param {Number} [opts.height] desired height of the modal
242
     * @returns {Object}
243
     */
244
    // eslint-disable-next-line complexity
245
    _calculateNewPosition(opts) {
246
        // lets set the modal width and height to the size of the browser
247
        var widthOffset = 300; // adds margin left and right
48✔
248
        var heightOffset = 300; // adds margin top and bottom;
48✔
249
        var screenWidth = this.ui.window.width();
48✔
250
        var screenHeight = this.ui.window.height();
48✔
251
        var modalWidth = opts.width || this.options.minWidth;
48✔
252
        var modalHeight = opts.height || this.options.minHeight;
48✔
253
        // screen width and height calculation, WC = width
254
        var screenWidthCalc = screenWidth >= modalWidth + widthOffset;
48✔
255
        var screenHeightCalc = screenHeight >= modalHeight + heightOffset;
48✔
256

257
        var width = screenWidthCalc && !opts.width ? screenWidth - widthOffset : modalWidth;
48✔
258
        var height = screenHeightCalc && !opts.height ? screenHeight - heightOffset : modalHeight;
48✔
259

260
        var currentLeft = this.ui.modal.css('left');
48✔
261
        var currentTop = this.ui.modal.css('top');
48✔
262
        var newLeft;
263
        var newTop;
264

265
        // jquery made me do it
266
        if (currentLeft === '50%') {
48✔
267
            currentLeft = screenWidth / 2;
27✔
268
        }
269
        if (currentTop === '50%') {
48✔
270
            currentTop = screenHeight / 2;
27✔
271
        }
272

273
        currentTop = parseInt(currentTop, 10);
48✔
274
        currentLeft = parseInt(currentLeft, 10);
48✔
275

276
        // if new width/height go out of the screen - reset position to center of screen
277
        if (
48✔
278
            width / 2 + currentLeft > screenWidth ||
174✔
279
            height / 2 + currentTop > screenHeight ||
280
            currentLeft - width / 2 < 0 ||
281
            currentTop - height / 2 < 0
282
        ) {
283
            newLeft = screenWidth / 2;
13✔
284
            newTop = screenHeight / 2;
13✔
285
        }
286

287
        // in case, the modal is larger than the window, we trigger fullscreen mode
288
        if (width >= screenWidth || height >= screenHeight) {
48✔
289
            this.triggerMaximized = true;
3✔
290
        }
291

292
        return {
48✔
293
            width: width,
294
            height: height,
295
            top: newTop,
296
            left: newLeft
297
        };
298
    }
299

300
    /**
301
     * Animation helper for opening the sideframe.
302
     *
303
     * @method _show
304
     * @private
305
     * @param {Object} opts
306
     * @param {Number} opts.width width of the modal
307
     * @param {Number} opts.height height of the modal
308
     * @param {Number} opts.left left in px of the center of the modal
309
     * @param {Number} opts.top top in px of the center of the modal
310
     * @param {Number} opts.duration speed of opening, ms (not really used yet)
311
     */
312
    _show(opts) {
313
        // we need to position the modal in the center
314
        var that = this;
41✔
315
        var width = opts.width;
41✔
316
        var height = opts.height;
41✔
317
        var speed = opts.duration;
41✔
318
        var top = opts.top;
41✔
319
        var left = opts.left;
41✔
320

321
        if (this.ui.modal.hasClass('cms-modal-open')) {
41✔
322
            this.ui.modal.addClass('cms-modal-morphing');
1✔
323
        }
324

325
        this.ui.modal.css({
41✔
326
            display: 'block',
327
            width: width,
328
            height: height,
329
            top: top,
330
            left: left,
331
            'margin-left': -(width / 2),
332
            'margin-top': -(height / 2)
333
        });
334
        // setImmediate is required to go into the next frame
335
        setTimeout(function() {
41✔
336
            that.ui.modal.addClass('cms-modal-open');
41✔
337
        }, 0);
338

339
        this.ui.modal
41✔
340
            .one('cmsTransitionEnd', function() {
341
                that.ui.modal.removeClass('cms-modal-morphing');
37✔
342
                that.ui.modal.css({
37✔
343
                    'margin-left': -(width / 2),
344
                    'margin-top': -(height / 2)
345
                });
346

347
                // check if we should maximize
348
                if (that.triggerMaximized) {
37✔
349
                    that.maximize();
1✔
350
                }
351

352
                // changed locked status to allow other modals again
353
                CMS.API.locked = false;
37✔
354
                Helpers.dispatchEvent('modal-shown', { instance: that });
37✔
355
            })
356
            .emulateTransitionEnd(speed);
357

358
        // add esc close event
359
        this.ui.body.off('keydown.cms.close').on('keydown.cms.close', function(e) {
41✔
360
            if (e.keyCode === KEYS.ESC && that.options.closeOnEsc) {
6✔
361
                e.stopPropagation();
3✔
362
                if (that._confirmDirtyEscCancel()) {
3✔
363
                    that._cancelHandler();
2✔
364
                }
365
            }
366
        });
367

368
        // set focus to modal
369
        this.ui.modal.focus();
41✔
370
    }
371

372
    /**
373
     * Closes the current instance.
374
     *
375
     * @method close
376
     * @returns {Boolean|void}
377
     */
378
    close() {
379
        var event = Helpers.dispatchEvent('modal-close', { instance: this });
10✔
380

381
        if (event.isDefaultPrevented()) {
10✔
382
            return false;
1✔
383
        }
384

385
        Helpers._getWindow().removeEventListener('beforeunload', this._beforeUnloadHandler);
9✔
386

387
        // handle refresh option
388
        if (this.options.onClose) {
9✔
389
            Helpers.reloadBrowser(this.options.onClose, false);
1✔
390
        }
391

392
        this._hide({
9✔
393
            duration: this.options.modalDuration / 2
394
        });
395

396
        this.ui.modal.untrap();
9✔
397
        keyboard.setContext(previousKeyboardContext);
9✔
398
        try {
9✔
399
            previouslyFocusedElement.focus();
9✔
400
        } catch (e) {}
401
    }
402

403
    /**
404
     * Animation helper for closing the iframe.
405
     *
406
     * @method _hide
407
     * @private
408
     * @param {Object} opts
409
     * @param {Number} [opts.duration=this.options.modalDuration] animation duration
410
     */
411
    _hide(opts) {
412
        var that = this;
16✔
413
        var duration = this.options.modalDuration;
16✔
414

415
        if (opts && opts.duration) {
16✔
416
            duration = opts.duration;
9✔
417
        }
418

419
        this.ui.frame.empty();
16✔
420
        this.ui.modalBody.removeClass('cms-loader');
16✔
421
        this.ui.modal.removeClass('cms-modal-open');
16✔
422
        this.ui.modal
16✔
423
            .one('cmsTransitionEnd', function() {
424
                that.ui.modal.css('display', 'none');
9✔
425
            })
426
            .emulateTransitionEnd(duration);
427

428
        // reset maximize or minimize states for #3111
429
        setTimeout(function() {
16✔
430
            if (that.minimized) {
13✔
431
                that.minimize();
1✔
432
            }
433
            if (that.maximized) {
13✔
434
                that.maximize();
1✔
435
            }
436
            hideLoader();
13✔
437
            Helpers.dispatchEvent('modal-closed', { instance: that });
13✔
438
        }, this.options.duration);
439

440
        this.ui.body.off('keydown.cms.close');
16✔
441
    }
442

443
    /**
444
     * Minimizes the modal onto the toolbar.
445
     *
446
     * @method minimize
447
     * @returns {Boolean|void}
448
     */
449
    minimize() {
450
        var MINIMIZED_OFFSET = 50;
11✔
451

452
        // cancel action if maximized
453
        if (this.maximized) {
11✔
454
            return false;
1✔
455
        }
456

457
        if (this.minimized === false) {
10✔
458
            // save initial state
459
            this.ui.modal.data('css', this.ui.modal.css(['left', 'top', 'margin-left', 'margin-top']));
5✔
460

461
            // minimize
462
            this.ui.body.addClass('cms-modal-minimized');
5✔
463
            this.ui.modal.css({
5✔
464
                left: this.ui.toolbarLeftPart.outerWidth(true) + MINIMIZED_OFFSET
465
            });
466

467
            this.minimized = true;
5✔
468
        } else {
469
            // maximize
470
            this.ui.body.removeClass('cms-modal-minimized');
5✔
471
            this.ui.modal.css(this.ui.modal.data('css'));
5✔
472

473
            this.minimized = false;
5✔
474
        }
475
    }
476

477
    /**
478
     * Maximizes the window according to the browser size.
479
     *
480
     * @method maximize
481
     * @returns {Boolean|void}
482
     */
483
    maximize() {
484
        // cancel action when minimized
485
        if (this.minimized) {
11✔
486
            return false;
1✔
487
        }
488

489
        if (this.maximized === false) {
10✔
490
            // save initial state
491
            this.ui.modal.data(
5✔
492
                'css',
493
                this.ui.modal.css(['left', 'top', 'margin-left', 'margin-top', 'width', 'height'])
494
            );
495

496
            this.ui.body.addClass('cms-modal-maximized');
5✔
497

498
            this.maximized = true;
5✔
499
            Helpers.dispatchEvent('modal-maximized', { instance: this });
5✔
500
        } else {
501
            // minimize
502
            this.ui.body.removeClass('cms-modal-maximized');
5✔
503
            this.ui.modal.css(this.ui.modal.data('css'));
5✔
504

505
            this.maximized = false;
5✔
506
            Helpers.dispatchEvent('modal-restored', { instance: this });
5✔
507
        }
508
    }
509

510
    /**
511
     * Initiates the start move event from `_events`.
512
     *
513
     * @method _startMove
514
     * @private
515
     * @param {Object} pointerEvent passes starting event
516
     * @returns {Boolean|void}
517
     */
518
    _startMove(pointerEvent) {
519
        // cancel if maximized or minimized
520
        if (this.maximized || this.minimized) {
9✔
521
            return false;
2✔
522
        }
523

524
        var that = this;
7✔
525
        var position = this.ui.modal.position();
7✔
526
        var left;
527
        var top;
528

529
        this.ui.shim.show();
7✔
530

531
        // create event for stopping
532
        this.ui.body.on(this.pointerUp, function(e) {
7✔
533
            that._stopMove(e);
2✔
534
        });
535

536
        this.ui.body
7✔
537
            .on(this.pointerMove, function(e) {
538
                left = position.left - (pointerEvent.originalEvent.pageX - e.originalEvent.pageX);
1✔
539
                top = position.top - (pointerEvent.originalEvent.pageY - e.originalEvent.pageY);
1✔
540

541
                that.ui.modal.css({
1✔
542
                    left: left,
543
                    top: top
544
                });
545
            })
546
            .attr('data-touch-action', 'none');
547
    }
548

549
    /**
550
     * Initiates the stop move event from `_startMove`.
551
     *
552
     * @method _stopMove
553
     * @private
554
     */
555
    _stopMove() {
556
        this.ui.shim.hide();
3✔
557
        this.ui.body.off(this.pointerMove + ' ' + this.pointerUp).removeAttr('data-touch-action');
3✔
558
    }
559

560
    /**
561
     * Initiates the start resize event from `_events`.
562
     *
563
     * @method _startResize
564
     * @private
565
     * @param {Object} pointerEvent passes starting event
566
     * @returns {Boolean|void}
567
     */
568
    _startResize(pointerEvent) {
569
        // cancel if in fullscreen
570
        if (this.maximized) {
9✔
571
            return false;
1✔
572
        }
573
        // continue
574
        var that = this;
8✔
575
        var width = this.ui.modal.width();
8✔
576
        var height = this.ui.modal.height();
8✔
577
        var modalLeft = this.ui.modal.position().left;
8✔
578
        var modalTop = this.ui.modal.position().top;
8✔
579
        var resizeDir = this.ui.resize.css('direction') === 'rtl' ? -1 : +1;
8!
580

581
        // create event for stopping
582
        this.ui.body.on(this.pointerUp, function(e) {
8✔
583
            that._stopResize(e);
2✔
584
        });
585

586
        this.ui.shim.show();
8✔
587

588
        this.ui.body
8✔
589
            .on(this.pointerMove, function(e) {
590
                var mvX = pointerEvent.originalEvent.pageX - e.originalEvent.pageX;
3✔
591
                var mvY = pointerEvent.originalEvent.pageY - e.originalEvent.pageY;
3✔
592
                var w = width - resizeDir * mvX * 2;
3✔
593
                var h = height - mvY * 2;
3✔
594
                var wMin = that.options.minWidth;
3✔
595
                var hMin = that.options.minHeight;
3✔
596
                var left = resizeDir * mvX + modalLeft;
3✔
597
                var top = mvY + modalTop;
3✔
598

599
                // add some limits
600
                if (w <= wMin) {
3✔
601
                    w = wMin;
1✔
602
                    left = modalLeft + width / 2 - w / 2;
1✔
603
                }
604
                if (h <= hMin) {
3✔
605
                    h = hMin;
1✔
606
                    top = modalTop + height / 2 - h / 2;
1✔
607
                }
608

609
                // set centered animation
610
                that.ui.modal.css({
3✔
611
                    width: w,
612
                    height: h,
613
                    left: left,
614
                    top: top
615
                });
616
            })
617
            .attr('data-touch-action', 'none');
618
    }
619

620
    /**
621
     * Initiates the stop resize event from `_startResize`.
622
     *
623
     * @method _stopResize
624
     * @private
625
     */
626
    _stopResize() {
627
        this.ui.shim.hide();
3✔
628
        this.ui.body.off(this.pointerMove + ' ' + this.pointerUp).removeAttr('data-touch-action');
3✔
629
    }
630

631
    /**
632
     * Sets the breadcrumb inside the modal.
633
     *
634
     * @method _setBreadcrumb
635
     * @private
636
     * @param {Object[]} breadcrumbs renderes breadcrumb on modal
637
     * @returns {Boolean|void}
638
     */
639
    _setBreadcrumb(breadcrumbs) {
640
        var crumb = '';
11✔
641
        var template = '<a href="{1}" class="{2}"><span>{3}</span></a>';
11✔
642

643
        // cancel if there is no breadcrumbs)
644
        if (!breadcrumbs || breadcrumbs.length <= 1) {
11✔
645
            return false;
3✔
646
        }
647
        if (!breadcrumbs[0].title) {
8✔
648
            return false;
1✔
649
        }
650

651
        // add class to modal
652
        this.ui.modal.addClass('cms-modal-has-breadcrumb');
7✔
653

654
        // load breadcrumbs
655
        $.each(breadcrumbs, function(index, item) {
7✔
656
            // check if the item is the last one
657
            var last = index >= breadcrumbs.length - 1 ? 'active' : '';
21✔
658

659
            // render breadcrumbs
660
            crumb += template.replace('{1}', item.url).replace('{2}', last).replace('{3}', item.title);
21✔
661
        });
662

663
        // attach elements
664
        this.ui.breadcrumb.html(crumb);
7✔
665
    }
666

667
    /**
668
     * Sets the buttons inside the modal.
669
     *
670
     * @method _setButtons
671
     * @private
672
     * @param {jQuery} iframe loaded iframe element
673
     */
674
    _setButtons(iframe) {
675
        var djangoSuit = iframe.contents().find('.suit-columns').length > 0;
4✔
676
        var that = this;
4✔
677
        var group = $('<div class="cms-modal-item-buttons"></div>');
4✔
678
        var render = $('<div class="cms-modal-buttons-inner"></div>');
4✔
679
        var cancel = $('<a href="#" class="cms-btn">' + CMS.config.lang.cancel + '</a>');
4✔
680
        var row;
681
        var tmp;
682

683
        // istanbul ignore if
684
        if (djangoSuit) {
4✔
685
            row = iframe.contents().find('.save-box:eq(0)');
686
        } else {
687
            row = iframe.contents().find('.submit-row:eq(0)');
4✔
688
        }
689
        var form = iframe.contents().find('form');
4✔
690

691
        // avoids conflict between the browser's form validation and Django's validation
692
        form.on('submit', function() {
4✔
693
            // default submit button was clicked
694
            // meaning, if you have save - it should close the iframe,
695
            // if you hit save and continue editing it should be default form behaviour
696
            if (that.hideFrame) {
3✔
697
                that.ui.modal.find('.cms-modal-frame iframe').hide();
2✔
698
                // page has been saved, run checkup
699
                that.saved = true;
2✔
700
            }
701
        });
702
        var buttons = row.find('input, a, button');
4✔
703

704
        // these are the buttons _inside_ the iframe
705
        // we need to listen to this click event to support submitting
706
        // a form by pressing enter inside of a field
707
        // click is actually triggered by submit
708
        buttons.on('click', function() {
4✔
709
            if ($(this).hasClass('default')) {
2✔
710
                that.hideFrame = true;
1✔
711
            }
712
        });
713

714
        // hide all submit-rows
715
        iframe.contents().find('.submit-row').hide();
4✔
716

717
        // if there are no given buttons within the submit-row area
718
        // scan deeper within the form itself
719
        // istanbul ignore next
720
        if (!buttons.length) {
721
            row = iframe.contents().find('body:not(.change-list) #content form:eq(0)');
722
            buttons = row.find('input[type="submit"], button[type="submit"]');
723
            buttons.addClass('deletelink').hide();
724
        }
725

726
        // loop over input buttons
727
        buttons.each(function(index, btn) {
4✔
728
            var item = $(btn);
16✔
729

730
            item.attr('data-rel', '_' + index);
16✔
731

732
            // cancel if item is a hidden input
733
            if (item.attr('type') === 'hidden') {
16✔
734
                return false;
3✔
735
            }
736

737
            var title = item.attr('value') || item.text();
13✔
738
            var cls = 'cms-btn';
13✔
739

740
            if (item.is('button')) {
13✔
741
                title = item.text();
4✔
742
            }
743

744
            // set additional special css classes
745
            if (item.hasClass('default')) {
13✔
746
                cls = 'cms-btn cms-btn-action';
4✔
747
            }
748
            if (item.hasClass('deletelink')) {
13✔
749
                cls = 'cms-btn cms-btn-caution';
3✔
750
            }
751

752
            var el = $('<a href="#" class="' + cls + ' ' + item.attr('class') + '">' + title + '</a>');
13✔
753

754
            // eslint-disable-next-line complexity
755
            el.on(that.click + ' ' + that.touchEnd, function(e) {
13✔
756
                e.preventDefault();
5✔
757

758
                if (item.is('a')) {
5✔
759
                    that._loadIframe({
2✔
760
                        url: Helpers.updateUrlWithPath(item.prop('href')),
761
                        name: title
762
                    });
763
                }
764

765
                // trigger only when blue action buttons are triggered
766
                if (item.hasClass('default') || item.hasClass('deletelink')) {
5✔
767
                    // hide iframe when using buttons other than submit
768
                    if (item.hasClass('default')) {
3✔
769
                        // submit button uses the form's submit event
770
                        that.hideFrame = true;
2✔
771
                    } else {
772
                        that.ui.modal.find('.cms-modal-frame iframe').hide();
1✔
773
                        // page has been saved or deleted, run checkup
774
                        that.saved = true;
1✔
775
                    }
776
                }
777

778
                if (item.is('input') || item.is('button')) {
5✔
779
                    that.ui.modalBody.addClass('cms-loader');
3✔
780
                    var frm = item[0].form;
3✔
781

782
                    // In Firefox with 1Password extension installed (FF 45 1password 4.5.6 at least)
783
                    // the item[0].click() doesn't work, which notably breaks
784
                    // deletion of the plugin. Workaround is that if the clicked button
785
                    // is the only button in the form - submit a form, otherwise
786
                    // click on the button
787
                    if (frm.querySelectorAll('button, input[type="button"], input[type="submit"]').length > 1) {
3✔
788
                        // we need to use native `.click()` event specifically
789
                        // as we are inside an iframe and magic is happening
790
                        item[0].click();
2✔
791
                    } else {
792
                        // have to dispatch native submit event so all the submit handlers
793
                        // can be fired, see #5590
794
                        var evt = new CustomEvent('submit', { bubbles: false, cancelable: true });
1✔
795

796
                        if (frm.dispatchEvent(evt)) {
1!
797
                            // triggering submit event in webkit based browsers won't
798
                            // actually submit the form, while in Gecko-based ones it
799
                            // will and calling frm.submit() would throw NS_ERROR_UNEXPECTED
800
                            try {
×
801
                                frm.submit();
×
802
                            } catch (err) {}
803
                        }
804
                    }
805
                }
806
            });
807
            el.wrap(group);
13✔
808

809
            // append element
810
            render.append(el.parent());
13✔
811
        });
812

813
        // manually add cancel button at the end
814
        cancel.on(that.click, function(e) {
4✔
815
            e.preventDefault();
1✔
816
            that._cancelHandler();
1✔
817
        });
818
        cancel.wrap(group);
4✔
819
        render.append(cancel.parent());
4✔
820

821
        // prepare groups
822
        render.find('.cms-btn-group').unwrap();
4✔
823
        tmp = render.find('.cms-btn-group').clone(true, true);
4✔
824
        render.find('.cms-btn-group').remove();
4✔
825
        render.append(tmp.wrapAll(group.clone().addClass('cms-modal-item-buttons-left')).parent());
4✔
826

827
        // render buttons
828
        this.ui.modalButtons.html(render);
4✔
829
    }
830

831
    /**
832
     * Version where the modal loads an iframe.
833
     *
834
     * @method _loadIframe
835
     * @private
836
     * @param {Object} opts
837
     * @param {String} opts.url url to render iframe, takes presedence over opts.html
838
     * @param {Object[]} [opts.breadcrumbs] collection of breadcrumb items
839
     * @param {String} [opts.title] modal window main title (bold)
840
     */
841
    _loadIframe(opts) {
842
        var that = this;
30✔
843
        const SHOW_LOADER_TIMEOUT = 500;
30✔
844

845
        opts.url = Helpers.makeURL(opts.url);
30✔
846
        opts.title = opts.title || '';
30✔
847
        opts.breadcrumbs = opts.breadcrumbs || '';
30✔
848

849
        showLoader();
30✔
850

851
        // set classes
852
        this.ui.modal.removeClass('cms-modal-markup');
30✔
853
        this.ui.modal.addClass('cms-modal-iframe');
30✔
854

855
        // we need to render the breadcrumb
856
        this._setBreadcrumb(opts.breadcrumbs);
30✔
857

858
        // now refresh the content
859
        var holder = this.ui.frame;
30✔
860
        var iframe = $('<iframe tabindex="0" src="' + opts.url + '" class="" frameborder="0" />');
30✔
861

862
        // set correct title
863
        var titlePrefix = this.ui.titlePrefix;
30✔
864
        var titleSuffix = this.ui.titleSuffix;
30✔
865

866
        iframe.css('visibility', 'hidden');
30✔
867
        titlePrefix.text(opts.title || '');
30✔
868
        titleSuffix.text('');
30✔
869

870
        // ensure previous iframe is hidden
871
        holder.find('iframe').css('visibility', 'hidden');
30✔
872
        const loaderTimeout = setTimeout(() => that.ui.modalBody.addClass('cms-loader'), SHOW_LOADER_TIMEOUT);
30✔
873

874
        // attach load event for iframe to prevent flicker effects
875
        // eslint-disable-next-line complexity
876
        iframe.on('load', function() {
30✔
877
            clearTimeout(loaderTimeout);
27✔
878
            var messages;
879
            var messageList;
880
            var contents;
881
            var body;
882
            var innerTitle;
883
            var bc;
884

885
            // check if iframe can be accessed
886
            try {
27✔
887
                contents = iframe.contents();
27✔
888
                body = contents.find('body');
26✔
889
            } catch (error) {
890
                CMS.API.Messages.open({
1✔
891
                    message: '<strong>' + CMS.config.lang.errorLoadingEditForm + '</strong>',
892
                    error: true,
893
                    delay: 0
894
                });
895
                that.close();
1✔
896
                return;
1✔
897
            }
898

899
            // check if we are redirected - should only happen after successful form submission
900
            const redirect = body.find('a.cms-view-new-object').attr('href');
26✔
901

902
            if (redirect) {
26!
903
                Helpers.reloadBrowser(redirect, false);
×
904
                return true;
×
905
            }
906

907
            // If the response contains the close-frame (and potentially the data bridge),
908
            // the form was saved successfully
909
            that.saved = that.saved || body.hasClass('cms-close-frame');
26✔
910

911
            // tabindex is required for keyboard navigation
912
            // body.attr('tabindex', '0');
913
            iframe.on('focus', function() {
26✔
914
                if (this.contentWindow) {
1!
915
                    this.contentWindow.focus();
1✔
916
                }
917
            });
918

919
            Modal._setupCtrlEnterSave(document);
26✔
920
            // istanbul ignore else
921
            if (iframe[0].contentWindow && iframe[0].contentWindow.document) {
26✔
922
                Modal._setupCtrlEnterSave(iframe[0].contentWindow.document);
26✔
923
            }
924
            // for ckeditor we need to go deeper
925
            // istanbul ignore next
926
            if (iframe[0].contentWindow && iframe[0].contentWindow.CMS && iframe[0].contentWindow.CMS.CKEditor) {
927
                $(iframe[0].contentWindow.document).ready(function() {
928
                    // setTimeout is required to battle CKEditor initialisation
929
                    setTimeout(function() {
930
                        var editor = iframe[0].contentWindow.CMS.CKEditor.editor;
931

932
                        if (editor) {
933
                            editor.on('instanceReady', function(e) {
934
                                Modal._setupCtrlEnterSave(
935
                                    $(e.editor.container.$).find('iframe')[0].contentWindow.document
936
                                );
937
                            });
938
                        }
939
                    }, 100); // eslint-disable-line
940
                });
941
            }
942

943
            var saveSuccess = Boolean(contents.find('.messagelist :not(".error")').length);
26✔
944

945
            // in case message didn't appear, assume that admin page is actually a success
946
            // istanbul ignore if
947
            if (!saveSuccess) {
26✔
948
                saveSuccess =
949
                    Boolean(contents.find('.dashboard #content-main').length) &&
950
                    !contents.find('.messagelist .error').length;
951
            }
952

953
            // show messages in toolbar if provided
954
            messageList = contents.find('.messagelist');
26✔
955
            messages = messageList.find('li');
26✔
956
            if (messages.length) {
26✔
957
                CMS.API.Messages.open({
10✔
958
                    message: messages.eq(0).html()
959
                });
960
            }
961
            messageList.remove();
26✔
962

963
            // inject css class
964
            body.addClass('cms-admin cms-admin-modal');
26✔
965

966
            // hide loaders
967
            that.ui.modalBody.removeClass('cms-loader');
26✔
968
            hideLoader();
26✔
969

970
            // determine if we should close the modal or reload
971
            if (messages.length && that.enforceReload) {
26!
972
                that.ui.modalBody.addClass('cms-loader');
×
973
                showLoader();
×
974
                Helpers.reloadBrowser();
×
975
            }
976
            if (messages.length && that.enforceClose) {
26✔
977
                that.close();
1✔
978
                return false;
1✔
979
            }
980

981
            // adding django hacks
982
            contents.find('.viewsitelink').attr('target', '_top');
25✔
983

984
            // set modal buttons
985
            that._setButtons($(this));
25✔
986

987
            // when an error occurs, reset the saved status so the form can be checked and validated again
988
            if (
25✔
989
                contents.find('.errornote').length ||
74✔
990
                contents.find('.errorlist').length ||
991
                (that.saved && !saveSuccess)
992
            ) {
993
                that.saved = false;
3✔
994
            }
995

996
            // when the window has been changed pressing the blue or red button, we need to run a reload check
997
            // also check that no delete-confirmation is required
998
            if (that.saved && saveSuccess && !contents.find('.delete-confirmation').length) {
25✔
999
                that.ui.modalBody.addClass('cms-loader');
1✔
1000
                if (that.options.onClose) {
1!
1001
                    showLoader();
×
1002
                    Helpers.reloadBrowser(
×
1003
                        that.options.onClose ? that.options.onClose : window.location.href,
×
1004
                        false,
1005
                        true
1006
                    );
1007
                } else {
1008
                    // hello ckeditor
1009
                    Helpers.removeEventListener('modal-close.text-plugin');
1✔
1010
                    that.close();
1✔
1011
                    // Serve the data bridge:
1012
                    // We have a special case here cause the CMS namespace
1013
                    // can be either inside the current window or the parent
1014
                    const dataBridge = body[0].querySelector('script#data-bridge');
1✔
1015

1016
                    if (dataBridge) {
1!
1017
                        // the dataBridge is used to access plugin information from different resources
1018
                        // Do NOT move this!!!
1019
                        try {
×
1020
                            CMS.API.Helpers.dataBridge = JSON.parse(dataBridge.textContent);
×
1021
                            CMS.API.Helpers.onPluginSave();
×
1022
                        } catch (e) {
1023
                            // istanbul ignore next
1024
                            Helpers.reloadBrowser();
1025
                        }
1026
                    }
1027
                }
1028
            } else {
1029
                if (that.ui.modal.hasClass('cms-modal-open')) {
24!
1030
                    // show modal if hidden
1031
                    that.ui.modal.show();
×
1032
                }
1033
                iframe.show();
24✔
1034
                // set title of not provided
1035
                innerTitle = contents.find('#content h1:eq(0)');
24✔
1036

1037
                // case when there is no prefix
1038
                // istanbul ignore next: never happens
1039
                if (opts.title === undefined && that.ui.titlePrefix.text() === '') {
1040
                    bc = contents.find('.breadcrumbs').contents();
1041
                    that.ui.titlePrefix.text(bc.eq(bc.length - 1).text().replace('›', '').trim());
1042
                }
1043

1044
                if (titlePrefix.text().trim() === '') {
24✔
1045
                    titlePrefix.text(innerTitle.text());
23✔
1046
                } else {
1047
                    titleSuffix.text(innerTitle.text());
1✔
1048
                }
1049
                innerTitle.remove();
24✔
1050

1051
                // than show
1052
                iframe.css('visibility', 'visible');
24✔
1053

1054
                // append ready state
1055
                iframe.data('ready', true);
24✔
1056

1057
                // attach close event
1058
                body.on('keydown.cms', function(e) {
24✔
1059
                    if (e.keyCode === KEYS.ESC && that.options.closeOnEsc) {
3✔
1060
                        e.stopPropagation();
2✔
1061
                        if (that._confirmDirtyEscCancel()) {
2✔
1062
                            that._cancelHandler();
1✔
1063
                        }
1064
                    }
1065
                });
1066

1067
                // figure out if .object-tools is available
1068
                if (contents.find('.object-tools').length) {
24✔
1069
                    contents.find('#content').css('padding-top', 38); // eslint-disable-line
8✔
1070
                }
1071

1072
                // this is required for IE11. we assume that when the modal is opened the user is going to interact
1073
                // with it. if we don't focus the body directly the next time the user clicks on a field inside
1074
                // the iframe the focus will be stolen by body thus requiring two clicks. this immediately focuses the
1075
                // iframe body on load except if something is already focused there
1076
                // (django tries to focus first field by default)
1077
                setTimeout(() => {
24✔
1078
                    if (!iframe[0] || !iframe[0].contentDocument || !iframe[0].contentDocument.documentElement) {
23✔
1079
                        return;
22✔
1080
                    }
1081
                    if ($(iframe[0].contentDocument.documentElement).find(':focus').length) {
1!
1082
                        return;
×
1083
                    }
1084
                    iframe.trigger('focus');
1✔
1085
                }, 0); // eslint-disable-line
1086
            }
1087

1088
            that._attachContentPreservingHandlers(iframe);
25✔
1089
        });
1090

1091
        // inject
1092
        holder.html(iframe);
30✔
1093
    }
1094

1095
    /**
1096
     * Adds handlers to prevent accidental refresh / modal close
1097
     * that could lead to loss of data.
1098
     *
1099
     * @method _attachContentPreservingHandlers
1100
     * @private
1101
     * @param {jQuery} iframe
1102
     */
1103
    _attachContentPreservingHandlers(iframe) {
1104
        var that = this;
26✔
1105

1106
        that.tracker = new ChangeTracker(iframe);
26✔
1107

1108
        Helpers._getWindow().addEventListener('beforeunload', this._beforeUnloadHandler);
26✔
1109
    }
1110

1111
    /**
1112
     * @method _beforeUnloadHandler
1113
     * @private
1114
     * @param {Event} e
1115
     * @returns {String|void}
1116
     */
1117
    _beforeUnloadHandler(e) {
1118
        if (this.tracker.isFormChanged()) {
3✔
1119
            e.returnValue = CMS.config.lang.confirmDirty;
2✔
1120
            return e.returnValue;
2✔
1121
        }
1122
    }
1123

1124
    /**
1125
     * Similar functionality as in `_attachContentPreservingHandlers` but for canceling
1126
     * the modal with the ESC button.
1127
     *
1128
     * @method _confirmDirtyEscCancel
1129
     * @private
1130
     * @returns {Boolean}
1131
     */
1132
    _confirmDirtyEscCancel() {
1133
        if (this.tracker && this.tracker.isFormChanged()) {
6✔
1134
            return Helpers.secureConfirm(CMS.config.lang.confirmDirty + '\n\n' + CMS.config.lang.confirmDirtyESC);
2✔
1135
        }
1136
        return true;
4✔
1137
    }
1138

1139
    /**
1140
     * Version where the modal loads an url within an iframe.
1141
     *
1142
     * @method _changeIframe
1143
     * @private
1144
     * @param {jQuery} el originated element
1145
     * @returns {Boolean|void}
1146
     */
1147
    _changeIframe(el) {
1148
        if (el.hasClass('active')) {
4✔
1149
            return false;
1✔
1150
        }
1151

1152
        var parents = el.parent().find('a');
3✔
1153

1154
        parents.removeClass('active');
3✔
1155
        el.addClass('active');
3✔
1156
        this._loadIframe({
3✔
1157
            url: el.attr('href')
1158
        });
1159
        this.ui.titlePrefix.text(el.text());
3✔
1160
    }
1161

1162
    /**
1163
     * Version where the modal loads html markup.
1164
     *
1165
     * @method _loadMarkup
1166
     * @private
1167
     * @param {Object} opts
1168
     * @param {String|HTMLNode|jQuery} opts.html html markup to render
1169
     * @param {String} opts.title modal window main title (bold)
1170
     * @param {String} [opts.subtitle] modal window secondary title (normal)
1171
     */
1172
    _loadMarkup(opts) {
1173
        this.ui.modal.removeClass('cms-modal-iframe');
30✔
1174
        this.ui.modal.addClass('cms-modal-markup');
30✔
1175
        this.ui.modalBody.removeClass('cms-loader');
30✔
1176

1177
        // set content
1178
        // empty to remove events, append to keep events
1179
        this.ui.frame.empty().append(opts.html);
30✔
1180
        this.ui.titlePrefix.text(opts.title || '');
30✔
1181
        this.ui.titleSuffix.text(opts.subtitle || '');
30✔
1182
    }
1183

1184
    /**
1185
     * Called whenever default modal action is canceled.
1186
     *
1187
     * @method _cancelHandler
1188
     * @private
1189
     */
1190
    _cancelHandler() {
1191
        this.options.onClose = null;
8✔
1192
        this.close();
8✔
1193
    }
1194

1195
    /**
1196
     * Sets up keyup/keydown listeners so you're able to save whatever you're
1197
     * editing inside of an iframe by pressing `ctrl + enter` on windows and `cmd + enter` on mac.
1198
     *
1199
     * It only works with default button (e.g. action), not the `delete` button,
1200
     * even though sometimes it's the only actionable button in the modal.
1201
     *
1202
     * @method _setupCtrlEnterSave
1203
     * @private
1204
     * @static
1205
     * @param {HTMLElement} doc document element (iframe or parent window);
1206
     */
1207
    static _setupCtrlEnterSave(doc) {
1208
        var cmdPressed = false;
6✔
1209
        var mac = navigator.platform.toLowerCase().indexOf('mac') + 1;
6✔
1210

1211
        $(doc)
6✔
1212
            .on('keydown.cms.submit', function(e) {
1213
                if (e.ctrlKey && e.keyCode === KEYS.ENTER && !mac) {
22✔
1214
                    $('.cms-modal-buttons .cms-btn-action:first').trigger('click');
1✔
1215
                }
1216

1217
                if (mac) {
22✔
1218
                    if (e.keyCode === KEYS.CMD_LEFT || e.keyCode === KEYS.CMD_RIGHT || e.keyCode === KEYS.CMD_FIREFOX) {
14✔
1219
                        cmdPressed = true;
6✔
1220
                    }
1221

1222
                    if (e.keyCode === KEYS.ENTER && cmdPressed) {
14✔
1223
                        $('.cms-modal-buttons .cms-btn-action:first').trigger('click');
3✔
1224
                    }
1225
                }
1226
            })
1227
            .on('keyup.cms.submit', function(e) {
1228
                if (mac) {
22✔
1229
                    if (e.keyCode === KEYS.CMD_LEFT || e.keyCode === KEYS.CMD_RIGHT || e.keyCode === KEYS.CMD_FIREFOX) {
14✔
1230
                        cmdPressed = false;
6✔
1231
                    }
1232
                }
1233
            });
1234
    }
1235
}
1236

1237
Modal.options = {
1✔
1238
    onClose: false,
1239
    closeOnEsc: true,
1240
    minHeight: 400,
1241
    minWidth: 800,
1242
    modalDuration: 200,
1243
    resizable: true,
1244
    maximizable: true,
1245
    minimizable: true
1246
};
1247

1248
export default Modal;
STATUS · Troubleshooting · Open an Issue · Sales · Support · CAREERS · ENTERPRISE · START FREE · SCHEDULE DEMO
ANNOUNCEMENTS · TWITTER · TOS & SLA · Supported CI Services · What's a CI service? · Automated Testing

© 2025 Coveralls, Inc