summaryrefslogtreecommitdiffstatshomepage
path: root/core/modules/tour/js/tour.es6.js
blob: 52fe8d7dae6545fad750a40dbefe1945bd5ca930 (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
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
105
106
107
108
109
110
111
112
113
114
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
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
/**
 * @file
 * Attaches behaviors for the Tour module's toolbar tab.
 */

(function ($, Backbone, Drupal, document) {
  const queryString = decodeURI(window.location.search);

  /**
   * Attaches the tour's toolbar tab behavior.
   *
   * It uses the query string for:
   * - tour: When ?tour=1 is present, the tour will start automatically after
   *   the page has loaded.
   * - tips: Pass ?tips=class in the url to filter the available tips to the
   *   subset which match the given class.
   *
   * @example
   * http://example.com/foo?tour=1&tips=bar
   *
   * @type {Drupal~behavior}
   *
   * @prop {Drupal~behaviorAttach} attach
   *   Attach tour functionality on `tour` events.
   */
  Drupal.behaviors.tour = {
    attach(context) {
      $('body')
        .once('tour')
        .each(() => {
          const model = new Drupal.tour.models.StateModel();
          new Drupal.tour.views.ToggleTourView({
            el: $(context).find('#toolbar-tab-tour'),
            model,
          });

          model
            // Allow other scripts to respond to tour events.
            .on('change:isActive', (model, isActive) => {
              $(document).trigger(
                isActive ? 'drupalTourStarted' : 'drupalTourStopped',
              );
            })
            // Initialization: check whether a tour is available on the current
            // page.
            .set('tour', $(context).find('ol#tour'));

          // Start the tour immediately if toggled via query string.
          if (/tour=?/i.test(queryString)) {
            model.set('isActive', true);
          }
        });
    },
  };

  /**
   * @namespace
   */
  Drupal.tour = Drupal.tour || {
    /**
     * @namespace Drupal.tour.models
     */
    models: {},

    /**
     * @namespace Drupal.tour.views
     */
    views: {},
  };

  /**
   * Backbone Model for tours.
   *
   * @constructor
   *
   * @augments Backbone.Model
   */
  Drupal.tour.models.StateModel = Backbone.Model.extend(
    /** @lends Drupal.tour.models.StateModel# */ {
      /**
       * @type {object}
       */
      defaults: /** @lends Drupal.tour.models.StateModel# */ {
        /**
         * Indicates whether the Drupal root window has a tour.
         *
         * @type {Array}
         */
        tour: [],

        /**
         * Indicates whether the tour is currently running.
         *
         * @type {bool}
         */
        isActive: false,

        /**
         * Indicates which tour is the active one (necessary to cleanly stop).
         *
         * @type {Array}
         */
        activeTour: [],
      },
    },
  );

  Drupal.tour.views.ToggleTourView = Backbone.View.extend(
    /** @lends Drupal.tour.views.ToggleTourView# */ {
      /**
       * @type {object}
       */
      events: { click: 'onClick' },

      /**
       * Handles edit mode toggle interactions.
       *
       * @constructs
       *
       * @augments Backbone.View
       */
      initialize() {
        this.listenTo(this.model, 'change:tour change:isActive', this.render);
        this.listenTo(this.model, 'change:isActive', this.toggleTour);
      },

      /**
       * {@inheritdoc}
       *
       * @return {Drupal.tour.views.ToggleTourView}
       *   The `ToggleTourView` view.
       */
      render() {
        // Render the visibility.
        this.$el.toggleClass('hidden', this._getTour().length === 0);
        // Render the state.
        const isActive = this.model.get('isActive');
        this.$el
          .find('button')
          .toggleClass('is-active', isActive)
          .prop('aria-pressed', isActive);
        return this;
      },

      /**
       * Model change handler; starts or stops the tour.
       */
      toggleTour() {
        if (this.model.get('isActive')) {
          const $tour = this._getTour();
          this._removeIrrelevantTourItems($tour, this._getDocument());
          const that = this;
          const close = Drupal.t('Close');
          if ($tour.find('li').length) {
            $tour.joyride({
              autoStart: true,
              postRideCallback() {
                that.model.set('isActive', false);
              },
              // HTML segments for tip layout.
              template: {
                link: `<a href="#close" class="joyride-close-tip" aria-label="${close}">&times;</a>`,
                button:
                  '<a href="#" class="button button--primary joyride-next-tip"></a>',
              },
            });
            this.model.set({ isActive: true, activeTour: $tour });
          }
        } else {
          this.model.get('activeTour').joyride('destroy');
          this.model.set({ isActive: false, activeTour: [] });
        }
      },

      /**
       * Toolbar tab click event handler; toggles isActive.
       *
       * @param {jQuery.Event} event
       *   The click event.
       */
      onClick(event) {
        this.model.set('isActive', !this.model.get('isActive'));
        event.preventDefault();
        event.stopPropagation();
      },

      /**
       * Gets the tour.
       *
       * @return {jQuery}
       *   A jQuery element pointing to a `<ol>` containing tour items.
       */
      _getTour() {
        return this.model.get('tour');
      },

      /**
       * Gets the relevant document as a jQuery element.
       *
       * @return {jQuery}
       *   A jQuery element pointing to the document within which a tour would be
       *   started given the current state.
       */
      _getDocument() {
        return $(document);
      },

      /**
       * Removes tour items for elements that don't have matching page elements.
       *
       * Or that are explicitly filtered out via the 'tips' query string.
       *
       * @example
       * <caption>This will filter out tips that do not have a matching
       * page element or don't have the "bar" class.</caption>
       * http://example.com/foo?tips=bar
       *
       * @param {jQuery} $tour
       *   A jQuery element pointing to a `<ol>` containing tour items.
       * @param {jQuery} $document
       *   A jQuery element pointing to the document within which the elements
       *   should be sought.
       *
       * @see Drupal.tour.views.ToggleTourView#_getDocument
       */
      _removeIrrelevantTourItems($tour, $document) {
        let removals = false;
        const tips = /tips=([^&]+)/.exec(queryString);
        $tour.find('li').each(function () {
          const $this = $(this);
          const itemId = $this.attr('data-id');
          const itemClass = $this.attr('data-class');
          // If the query parameter 'tips' is set, remove all tips that don't
          // have the matching class.
          if (tips && !$(this).hasClass(tips[1])) {
            removals = true;
            $this.remove();
            return;
          }
          // Remove tip from the DOM if there is no corresponding page element.
          if (
            (!itemId && !itemClass) ||
            (itemId && $document.find(`#${itemId}`).length) ||
            (itemClass && $document.find(`.${itemClass}`).length)
          ) {
            return;
          }
          removals = true;
          $this.remove();
        });

        // If there were removals, we'll have to do some clean-up.
        if (removals) {
          const total = $tour.find('li').length;
          if (!total) {
            this.model.set({ tour: [] });
          }

          $tour
            .find('li')
            // Rebuild the progress data.
            .each(function (index) {
              const progress = Drupal.t('!tour_item of !total', {
                '!tour_item': index + 1,
                '!total': total,
              });
              $(this).find('.tour-progress').text(progress);
            })
            // Update the last item to have "End tour" as the button.
            .eq(-1)
            .attr('data-text', Drupal.t('End tour'));
        }
      },
    },
  );
})(jQuery, Backbone, Drupal, document);