summaryrefslogtreecommitdiffstatshomepage
path: root/core/modules/toolbar/js/toolbar.es6.js
blob: 83ce811cdd885efa3ccd0526de29b987a53b1792 (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
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
/**
 * @file
 * Defines the behavior of the Drupal administration toolbar.
 */

(function ($, Drupal, drupalSettings) {
  // Merge run-time settings with the defaults.
  const options = $.extend(
    {
      breakpoints: {
        'toolbar.narrow': '',
        'toolbar.standard': '',
        'toolbar.wide': '',
      },
    },
    drupalSettings.toolbar,
    // Merge strings on top of drupalSettings so that they are not mutable.
    {
      strings: {
        horizontal: Drupal.t('Horizontal orientation'),
        vertical: Drupal.t('Vertical orientation'),
      },
    },
  );

  /**
   * Registers tabs with the toolbar.
   *
   * The Drupal toolbar allows modules to register top-level tabs. These may
   * point directly to a resource or toggle the visibility of a tray.
   *
   * Modules register tabs with hook_toolbar().
   *
   * @type {Drupal~behavior}
   *
   * @prop {Drupal~behaviorAttach} attach
   *   Attaches the toolbar rendering functionality to the toolbar element.
   */
  Drupal.behaviors.toolbar = {
    attach(context) {
      // Verify that the user agent understands media queries. Complex admin
      // toolbar layouts require media query support.
      if (!window.matchMedia('only screen').matches) {
        return;
      }
      // Process the administrative toolbar.
      $(context)
        .find('#toolbar-administration')
        .once('toolbar')
        .each(function () {
          // Establish the toolbar models and views.
          const model = new Drupal.toolbar.ToolbarModel({
            locked: JSON.parse(
              localStorage.getItem('Drupal.toolbar.trayVerticalLocked'),
            ),
            activeTab: document.getElementById(
              JSON.parse(localStorage.getItem('Drupal.toolbar.activeTabID')),
            ),
            height: $('#toolbar-administration').outerHeight(),
          });

          Drupal.toolbar.models.toolbarModel = model;

          // Attach a listener to the configured media query breakpoints.
          // Executes it before Drupal.toolbar.views to avoid extra rendering.
          Object.keys(options.breakpoints).forEach((label) => {
            const mq = options.breakpoints[label];
            const mql = window.matchMedia(mq);
            Drupal.toolbar.mql[label] = mql;
            // Curry the model and the label of the media query breakpoint to
            // the mediaQueryChangeHandler function.
            mql.addListener(
              Drupal.toolbar.mediaQueryChangeHandler.bind(null, model, label),
            );
            // Fire the mediaQueryChangeHandler for each configured breakpoint
            // so that they process once.
            Drupal.toolbar.mediaQueryChangeHandler.call(
              null,
              model,
              label,
              mql,
            );
          });

          Drupal.toolbar.views.toolbarVisualView = new Drupal.toolbar.ToolbarVisualView(
            {
              el: this,
              model,
              strings: options.strings,
            },
          );
          Drupal.toolbar.views.toolbarAuralView = new Drupal.toolbar.ToolbarAuralView(
            {
              el: this,
              model,
              strings: options.strings,
            },
          );
          Drupal.toolbar.views.bodyVisualView = new Drupal.toolbar.BodyVisualView(
            {
              el: this,
              model,
            },
          );

          // Force layout render to fix mobile view. Only needed on load, not
          // for every media query match.
          model.trigger('change:isFixed', model, model.get('isFixed'));
          model.trigger('change:activeTray', model, model.get('activeTray'));

          // Render collapsible menus.
          const menuModel = new Drupal.toolbar.MenuModel();
          Drupal.toolbar.models.menuModel = menuModel;
          Drupal.toolbar.views.menuVisualView = new Drupal.toolbar.MenuVisualView(
            {
              el: $(this).find('.toolbar-menu-administration').get(0),
              model: menuModel,
              strings: options.strings,
            },
          );

          // Handle the resolution of Drupal.toolbar.setSubtrees.
          // This is handled with a deferred so that the function may be invoked
          // asynchronously.
          Drupal.toolbar.setSubtrees.done((subtrees) => {
            menuModel.set('subtrees', subtrees);
            const theme = drupalSettings.ajaxPageState.theme;
            localStorage.setItem(
              `Drupal.toolbar.subtrees.${theme}`,
              JSON.stringify(subtrees),
            );
            // Indicate on the toolbarModel that subtrees are now loaded.
            model.set('areSubtreesLoaded', true);
          });

          // Trigger an initial attempt to load menu subitems. This first attempt
          // is made after the media query handlers have had an opportunity to
          // process. The toolbar starts in the vertical orientation by default,
          // unless the viewport is wide enough to accommodate a horizontal
          // orientation. Thus we give the Toolbar a chance to determine if it
          // should be set to horizontal orientation before attempting to load
          // menu subtrees.
          Drupal.toolbar.views.toolbarVisualView.loadSubtrees();

          $(document)
            // Update the model when the viewport offset changes.
            .on('drupalViewportOffsetChange.toolbar', (event, offsets) => {
              model.set('offsets', offsets);
            });

          // Broadcast model changes to other modules.
          model
            .on('change:orientation', (model, orientation) => {
              $(document).trigger(
                'drupalToolbarOrientationChange',
                orientation,
              );
            })
            .on('change:activeTab', (model, tab) => {
              $(document).trigger('drupalToolbarTabChange', tab);
            })
            .on('change:activeTray', (model, tray) => {
              $(document).trigger('drupalToolbarTrayChange', tray);
            });

          // If the toolbar's orientation is horizontal and no active tab is
          // defined then show the tray of the first toolbar tab by default (but
          // not the first 'Home' toolbar tab).
          if (
            Drupal.toolbar.models.toolbarModel.get('orientation') ===
              'horizontal' &&
            Drupal.toolbar.models.toolbarModel.get('activeTab') === null
          ) {
            Drupal.toolbar.models.toolbarModel.set({
              activeTab: $(
                '.toolbar-bar .toolbar-tab:not(.home-toolbar-tab) a',
              ).get(0),
            });
          }

          $(window).on({
            'dialog:aftercreate': (event, dialog, $element, settings) => {
              const $toolbar = $('#toolbar-bar');
              $toolbar.css('margin-top', '0');

              // When off-canvas is positioned in top, toolbar has to be moved down.
              if (settings.drupalOffCanvasPosition === 'top') {
                const height = Drupal.offCanvas
                  .getContainer($element)
                  .outerHeight();
                $toolbar.css('margin-top', `${height}px`);

                $element.on('dialogContentResize.off-canvas', () => {
                  const newHeight = Drupal.offCanvas
                    .getContainer($element)
                    .outerHeight();
                  $toolbar.css('margin-top', `${newHeight}px`);
                });
              }
            },
            'dialog:beforeclose': () => {
              $('#toolbar-bar').css('margin-top', '0');
            },
          });
        });
    },
  };

  /**
   * Toolbar methods of Backbone objects.
   *
   * @namespace
   */
  Drupal.toolbar = {
    /**
     * A hash of View instances.
     *
     * @type {object.<string, Backbone.View>}
     */
    views: {},

    /**
     * A hash of Model instances.
     *
     * @type {object.<string, Backbone.Model>}
     */
    models: {},

    /**
     * A hash of MediaQueryList objects tracked by the toolbar.
     *
     * @type {object.<string, object>}
     */
    mql: {},

    /**
     * Accepts a list of subtree menu elements.
     *
     * A deferred object that is resolved by an inlined JavaScript callback.
     *
     * @type {jQuery.Deferred}
     *
     * @see toolbar_subtrees_jsonp().
     */
    setSubtrees: new $.Deferred(),

    /**
     * Respond to configured narrow media query changes.
     *
     * @param {Drupal.toolbar.ToolbarModel} model
     *   A toolbar model
     * @param {string} label
     *   Media query label.
     * @param {object} mql
     *   A MediaQueryList object.
     */
    mediaQueryChangeHandler(model, label, mql) {
      switch (label) {
        case 'toolbar.narrow':
          model.set({
            isOriented: mql.matches,
            isTrayToggleVisible: false,
          });
          // If the toolbar doesn't have an explicit orientation yet, or if the
          // narrow media query doesn't match then set the orientation to
          // vertical.
          if (!mql.matches || !model.get('orientation')) {
            model.set({ orientation: 'vertical' }, { validate: true });
          }
          break;

        case 'toolbar.standard':
          model.set({
            isFixed: mql.matches,
          });
          break;

        case 'toolbar.wide':
          model.set(
            {
              orientation:
                mql.matches && !model.get('locked') ? 'horizontal' : 'vertical',
            },
            { validate: true },
          );
          // The tray orientation toggle visibility does not need to be
          // validated.
          model.set({
            isTrayToggleVisible: mql.matches,
          });
          break;

        default:
          break;
      }
    },
  };

  /**
   * A toggle is an interactive element often bound to a click handler.
   *
   * @return {string}
   *   A string representing a DOM fragment.
   */
  Drupal.theme.toolbarOrientationToggle = function () {
    return (
      '<div class="toolbar-toggle-orientation"><div class="toolbar-lining">' +
      '<button class="toolbar-icon" type="button"></button>' +
      '</div></div>'
    );
  };

  /**
   * Ajax command to set the toolbar subtrees.
   *
   * @param {Drupal.Ajax} ajax
   *   {@link Drupal.Ajax} object created by {@link Drupal.ajax}.
   * @param {object} response
   *   JSON response from the Ajax request.
   * @param {number} [status]
   *   XMLHttpRequest status.
   */
  Drupal.AjaxCommands.prototype.setToolbarSubtrees = function (
    ajax,
    response,
    status,
  ) {
    Drupal.toolbar.setSubtrees.resolve(response.subtrees);
  };
})(jQuery, Drupal, drupalSettings);