MultiStepWizard.ts 16.3 KB
Newer Older
1
2
3
4
5
6
7
8
9
10
11
12
13
14
/*
 * This file is part of the TYPO3 CMS project.
 *
 * It is free software; you can redistribute it and/or modify it under
 * the terms of the GNU General Public License, either version 2
 * of the License, or any later version.
 *
 * For the full copyright and license information, please read the
 * LICENSE.txt file that was distributed with this source code.
 *
 * The TYPO3 project - inspiring people to share!
 */

import {SeverityEnum} from './Enum/Severity';
15
import $ from 'jquery';
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
import Modal = require('./Modal');
import Severity = require('./Severity');
import Icons = require('./Icons');


interface MultiStepWizardSettings {
  [key: string]: any;
}

interface MultiStepWizardSetup {
  slides: Array<any>;
  settings: MultiStepWizardSettings;
  forceSelection: boolean;
  $carousel: JQuery;
}

interface Slide {
  identifier: string;
  title: string;
  progressBarTitle: string;
  content: string|JQuery;
  severity: SeverityEnum;
  callback?: Function;
}

/**
 * Module: TYPO3/CMS/Backend/MultiStepWizard
 * Multi step wizard within a modal
 * @exports TYPO3/CMS/Backend/MultiStepWizard
 */
class MultiStepWizard {
  private setup: MultiStepWizardSetup;
  private readonly originalSetup: MultiStepWizardSetup;

  constructor() {
    this.setup = {
      slides: [],
      settings: {},
      forceSelection: true,
      $carousel: null,
    };
    this.originalSetup = $.extend(true, {}, this.setup);
  }

  /**
   * @param {string} key
   * @param {any} value
   * @returns {MultiStepWizard}
   */
  public set(key: string, value: any): MultiStepWizard {
    this.setup.settings[key] = value;
    return this;
  }

  /**
   * Add a slide item to carousel as an additional step
   *
   * @param {string} identifier
   * @param {string} title
   * @param {string} progressBarTitle
   * @param {string} content
   * @param {SeverityEnum} severity
   * @param {Function} callback
   * @returns {MultiStepWizard}
   */
  public addSlide(
    identifier: string,
    title: string,
    content: string = '',
    severity: SeverityEnum = SeverityEnum.info,
    progressBarTitle: string,
    callback?: Function,
  ): MultiStepWizard {
    const slide: Slide = {
      identifier: identifier,
      title: title,
      content: content,
      severity: severity,
      progressBarTitle: progressBarTitle,
      callback: callback,
    };
    this.setup.slides.push(slide);
    return this;
  }

  /**
   * Add the final processing slide as the last step
   *
   * @param {Function} callback
105
   * @returns {Promise<string>}
106
   */
107
  public addFinalProcessingSlide(callback?: Function): Promise<void> {
108
109
110
111
112
113
    if (!callback) {
      callback = (): void => {
        this.dismiss();
      };
    }

114
    return Icons.getIcon('spinner-circle', Icons.sizes.default, null, null).then((markup: string) => {
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
      let $processingSlide = $('<div />', {class: 'text-center'}).append(markup);
      this.addSlide(
        'final-processing-slide', top.TYPO3.lang['wizard.processing.title'],
        $processingSlide[0].outerHTML,
        Severity.info,
        null,
        callback,
      );
    });
  }

  /**
   * Create wizard with modal, buttons, progress bar and carousel
   */
  public show(): void {
    let $slides = this.generateSlides();
    let firstSlide = this.setup.slides[0];

    Modal.confirm(
      firstSlide.title,
      $slides,
      firstSlide.severity,
      [{
        text: top.TYPO3.lang['wizard.button.cancel'],
        active: true,
        btnClass: 'btn-default pull-left',
        name: 'cancel',
        trigger: (): void => {
          this.getComponent().trigger('wizard-dismiss');
        },
      }, {
        text: top.TYPO3.lang['wizard.button.prev'],
        btnClass: 'btn-' + Severity.getCssClass(firstSlide.severity),
        name: 'prev',
      }, {
        text: top.TYPO3.lang['wizard.button.next'],
        btnClass: 'btn-' + Severity.getCssClass(firstSlide.severity),
        name: 'next',
      }],
      ['modal-multi-step-wizard'],
    );

    this.addButtonContainer();
    this.addProgressBar();
    this.initializeEvents();

    this.getComponent().on('wizard-visible', (): void => {
      this.runSlideCallback(firstSlide, this.setup.$carousel.find('.item').first());
    }).on('wizard-dismissed', (): void => {
      this.setup = $.extend(true, {}, this.originalSetup);
    });
  }

  /**
   * @returns {JQuery}
   */
  public getComponent(): JQuery {
    if (this.setup.$carousel === null) {
      this.generateSlides();
    }
    return this.setup.$carousel;
  }

  /**
   * Close the modal / wizard
   */
  public dismiss(): void {
    Modal.dismiss();
  }

  /**
   * Lock the button for the next step
   *
   * @returns {JQuery}
   */
  public lockNextStep(): JQuery {
    let $button = this.setup.$carousel.closest('.modal').find('button[name="next"]');
    $button.prop('disabled', true);
    return $button;
  }

  /**
   * Unlock the button for the next step
   *
   * @returns {JQuery}
   */
  public unlockNextStep(): JQuery {
    let $button = this.setup.$carousel.closest('.modal').find('button[name="next"]');
    $button.prop('disabled', false);
    return $button;
  }

  /**
   * Lock the button for the prev step
   *
   * @returns {JQuery}
   */
  public lockPrevStep(): JQuery {
    let $button = this.setup.$carousel.closest('.modal').find('button[name="prev"]');
    $button.prop('disabled', true);
    return $button;
  }

  /**
   * Unlock the button for the prev step
   *
   * @returns {JQuery}
   */
  public unlockPrevStep(): JQuery {
    let $button = this.setup.$carousel.closest('.modal').find('button[name="prev"]');
    $button.prop('disabled', false);
    return $button;
  }

229
230
231
232
233
234
235
236
237
238
239
240
241
242
  /**
   * Trigger a step button (prev or next)
   *
   * @param {string} direction
   * @returns {JQuery}
   */
  public triggerStepButton(direction: string): JQuery {
    let $button = this.setup.$carousel.closest('.modal').find('button[name="' + direction + '"]');
    if ($button.length > 0 && $button.prop('disabled') !== true) {
      $button.trigger('click');
    }
    return $button;
  }

243
244
245
246
247
248
249
  /**
   * Blur the button for the cancel step
   *
   * @returns {JQuery}
   */
  public blurCancelStep(): JQuery {
    let $button = this.setup.$carousel.closest('.modal').find('button[name="cancel"]');
250
    $button.trigger('blur');
251
252
253
254
255
256
257
258
259
260
    return $button;
  }

  /**
   * Register all events
   *
   * @private
   */
  private initializeEvents(): void {
    let $modal = this.setup.$carousel.closest('.modal');
261
262
    this.initializeSlideNextEvent($modal);
    this.initializeSlidePrevEvent($modal);
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294

    // Event fires when the slide transition is invoked
    this.setup.$carousel.on('slide.bs.carousel', (evt: any): void => {
      if (evt.direction === 'left') {
        this.nextSlideChanges($modal);
      } else {
        this.prevSlideChanges($modal);
      }
    })
      // Event is fired when the carousel has completed its slide transition
      .on('slid.bs.carousel', (evt: JQueryEventObject): void => {
        let currentIndex = this.setup.$carousel.data('currentIndex');
        let slide = this.setup.slides[currentIndex];

        this.runSlideCallback(slide, $(evt.relatedTarget));

        if (this.setup.forceSelection) {
          this.lockNextStep();
        }
      });

    // Custom event, closes the wizard
    let cmp = this.getComponent();
    cmp.on('wizard-dismiss', this.dismiss);

    Modal.currentModal.on('hidden.bs.modal', (): void => {
      cmp.trigger('wizard-dismissed');
    }).on('shown.bs.modal', (): void => {
      cmp.trigger('wizard-visible');
    });
  }

295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
  private initializeSlideNextEvent($modal: JQuery) {
    let $modalFooter = $modal.find('.modal-footer');
    let $nextButton = $modalFooter.find('button[name="next"]');
    $nextButton.off().on('click', (): void => {
      this.setup.$carousel.carousel('next');
    });
  }

  private initializeSlidePrevEvent($modal: JQuery) {
    let $modalFooter = $modal.find('.modal-footer');
    let $prevButton = $modalFooter.find('button[name="prev"]');
    $prevButton.off().on('click', (): void => {
      this.setup.$carousel.carousel('prev');
    });
  }

311
312
313
314
315
316
317
  /**
   * All changes after applying the next-button
   *
   * @param {JQuery} $modal
   * @private
   */
  private nextSlideChanges($modal: JQuery): void {
318
319
    this.initializeSlideNextEvent($modal);

320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
    let $modalTitle = $modal.find('.modal-title');
    let $modalFooter = $modal.find('.modal-footer');
    let $modalButtonGroup = $modal.find('.modal-btn-group');
    let $nextButton = $modalFooter.find('button[name="next"]');
    let nextSlideNumber = this.setup.$carousel.data('currentSlide') + 1;
    let currentIndex = this.setup.$carousel.data('currentIndex') + 1;

    $modalTitle.text(this.setup.slides[currentIndex].title);

    this.setup.$carousel.data('currentSlide', nextSlideNumber);
    this.setup.$carousel.data('currentIndex', currentIndex);

    // Last wizard step
    if (nextSlideNumber >= this.setup.$carousel.data('realSlideCount')) {
      $nextButton.text(this.getProgressBarTitle(this.setup.$carousel.data('currentIndex')));

      $modalFooter.find('.progress-bar.first-step')
        .width('100%')
        .text(this.getProgressBarTitle(this.setup.$carousel.data('currentIndex')));

      $modalFooter.find('.progress-bar.last-step')
        .width('0%')
        .text('');

      this.setup.forceSelection = false;
    } else {
      $modalFooter.find('.progress-bar.first-step')
        .width(this.setup.$carousel.data('initialStep') * nextSlideNumber + '%')
        .text(this.getProgressBarTitle(currentIndex));

      $modalFooter.find('.progress-bar.step')
        .width('0%')
        .text('');

      $modalButtonGroup.slideDown();
    }

    $nextButton
      .removeClass('btn-' + Severity.getCssClass(this.setup.slides[currentIndex - 1].severity))
      .addClass('btn-' + Severity.getCssClass(this.setup.slides[currentIndex].severity));

    $modal
      .removeClass('modal-severity-' + Severity.getCssClass(this.setup.slides[currentIndex - 1].severity))
      .addClass('modal-severity-' + Severity.getCssClass(this.setup.slides[currentIndex].severity));
  }

  /**
   * All changes after applying the prev-button
   *
   * @param {JQuery} $modal
   * @private
   */
  private prevSlideChanges($modal: JQuery): void {
373
374
    this.initializeSlidePrevEvent($modal);

375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
    let $modalTitle = $modal.find('.modal-title');
    let $modalFooter = $modal.find('.modal-footer');
    let $modalButtonGroup = $modal.find('.modal-btn-group');
    let $nextButton = $modalFooter.find('button[name="next"]');
    let nextSlideNumber = this.setup.$carousel.data('currentSlide') - 1;
    let currentIndex = this.setup.$carousel.data('currentIndex') - 1;

    this.setup.$carousel.data('currentSlide', nextSlideNumber);
    this.setup.$carousel.data('currentIndex', currentIndex);

    $modalTitle.text(this.setup.slides[currentIndex].title);

    $modalFooter.find('.progress-bar.last-step')
      .width(this.setup.$carousel.data('initialStep') + '%')
      .text(this.getProgressBarTitle(this.setup.$carousel.data('slideCount') - 1));

    $nextButton.text(top.TYPO3.lang['wizard.button.next']);

    // First wizard step
    if (nextSlideNumber === 1) {
      $modalFooter.find('.progress-bar.first-step')
        .width(this.setup.$carousel.data('initialStep') * nextSlideNumber + '%')
        .text(this.getProgressBarTitle(0));

      $modalFooter.find('.progress-bar.step')
        .width(this.setup.$carousel.data('initialStep') + '%')
        .text(this.getProgressBarTitle(currentIndex + 1));

      $modalButtonGroup.slideUp();
    } else {
      $modalFooter.find('.progress-bar.first-step')
        .width(this.setup.$carousel.data('initialStep') * nextSlideNumber + '%')
        .text(this.getProgressBarTitle(currentIndex));

      this.setup.forceSelection = true;
    }
  }

  /**
   * get custom progress bar label of current slide
   * or fallback label
   *
   * @private
   */
  private getProgressBarTitle(slideIndex: number): string {
    let progessBarTitle;

    if (this.setup.slides[slideIndex].progressBarTitle === null) {
      if (slideIndex === 0) {
        progessBarTitle = top.TYPO3.lang['wizard.progressStep.start'];
      } else if (slideIndex >= this.setup.$carousel.data('slideCount') - 1) {
        progessBarTitle = top.TYPO3.lang['wizard.progressStep.finish'];
      } else {
        progessBarTitle = top.TYPO3.lang['wizard.progressStep'] + String(slideIndex + 1);
      }
    } else {
      progessBarTitle = this.setup.slides[slideIndex].progressBarTitle;
    }

    return progessBarTitle;
  }

  /**
   * @param {Slide} slide
   * @param {JQuery} $slide
   * @private
   */
  private runSlideCallback(slide: Slide, $slide: JQuery): void {
    if (typeof slide.callback === 'function') {
      slide.callback($slide, this.setup.settings, slide.identifier);
    }
  }

  /**
   * Create the progress bar within the modal footer
   *
   * @private
   */
  private addProgressBar(): void {
    let realSlideCount = this.setup.$carousel.find('.item').length - 1;
    let slideCount = Math.max(1, realSlideCount);
    let initialStep;
    let $modal = this.setup.$carousel.closest('.modal');
    let $modalFooter = $modal.find('.modal-footer');

    initialStep = Math.round(100 / slideCount);

    this.setup.$carousel
      .data('initialStep', initialStep)
      .data('slideCount', slideCount)
      .data('realSlideCount', realSlideCount)
      .data('currentIndex', 0)
      .data('currentSlide', 1);

    // Append progress bar to modal footer
    if (slideCount > 1) {
      $modalFooter.prepend($('<div />', {class: 'progress'}));
      for (let i = 0; i < this.setup.slides.length; ++i) {
        let classes;
        if (i === 0) {
          classes = 'progress-bar first-step';
        } else if (i === this.setup.$carousel.data('slideCount') - 1) {
          classes = 'progress-bar last-step inactive';
        } else {
          classes = 'progress-bar step inactive';
        }
        $modalFooter.find('.progress')
          .append(
            $('<div />', {
              role: 'progressbar',
              class: classes,
              'aria-valuemin': 0,
              'aria-valuenow': initialStep,
              'aria-valuemax': 100,
            })
              .width(initialStep + '%')
              .text(this.getProgressBarTitle(i))
          );
      }
    }
  }

  /**
   * Wrap all the buttons of modal footer
   *
   * @private
   */
  private addButtonContainer(): void {
    let $modal = this.setup.$carousel.closest('.modal');
    let $modalFooterButtons = $modal.find('.modal-footer .btn');

    $modalFooterButtons.wrapAll('<div class="modal-btn-group" />');
  }

  /**
   * Generate slides of carousel
   *
   * @returns {JQuery}
   * @private
   */
  private generateSlides(): JQuery {
    // Check whether the slides were already generated
    if (this.setup.$carousel !== null) {
      return this.setup.$carousel;
    }

521
    let slides = '<div class="carousel slide" data-bs-ride="carousel" data-bs-interval="false">'
522
523
524
525
526
527
528
529
530
      + '<div class="carousel-inner" role="listbox">';

    for (let i = 0; i < this.setup.slides.length; ++i) {
      let currentSlide: Slide = this.setup.slides[i];
      let slideContent = currentSlide.content;

      if (typeof slideContent === 'object') {
        slideContent = slideContent.html();
      }
531
      slides += '<div class="item" data-bs-slide="' + currentSlide.identifier + '" data-step="' + i + '">' + slideContent + '</div>';
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
    }

    slides += '</div></div>';

    this.setup.$carousel = $(slides);
    this.setup.$carousel.find('.item').first().addClass('active');

    return this.setup.$carousel;
  }
}

let multistepWizardObject;
try {
  // fetch from opening window
  if (window.opener && window.opener.TYPO3 && window.opener.TYPO3.MultiStepWizard) {
    multistepWizardObject = window.opener.TYPO3.MultiStepWizard;
  }

  // fetch from parent
  if (parent && parent.window.TYPO3 && parent.window.TYPO3.MultiStepWizard) {
    multistepWizardObject = parent.window.TYPO3.MultiStepWizard;
  }

  // fetch object from outer frame
  if (top && top.TYPO3 && top.TYPO3.MultiStepWizard) {
    multistepWizardObject = top.TYPO3.MultiStepWizard;
  }
} catch (e) {
  // This only happens if the opener, parent or top is some other url (eg a local file)
  // which loaded the current window. Then the browser's cross domain policy jumps in
  // and raises an exception.
  // For this case we are safe and we can create our global object below.
}

if (!multistepWizardObject) {
  multistepWizardObject = new MultiStepWizard();

  // attach to global frame
  if (typeof TYPO3 !== 'undefined') {
    TYPO3.MultiStepWizard = multistepWizardObject;
  }
}

export = multistepWizardObject;