Updated to Drupal 8.5. Core Media not yet in use.
[yaffs-website] / web / core / modules / toolbar / js / toolbar.es6.js
1 /**
2  * @file
3  * Defines the behavior of the Drupal administration toolbar.
4  */
5
6 (function ($, Drupal, drupalSettings) {
7   // Merge run-time settings with the defaults.
8   const options = $.extend(
9     {
10       breakpoints: {
11         'toolbar.narrow': '',
12         'toolbar.standard': '',
13         'toolbar.wide': '',
14       },
15     },
16     drupalSettings.toolbar,
17     // Merge strings on top of drupalSettings so that they are not mutable.
18     {
19       strings: {
20         horizontal: Drupal.t('Horizontal orientation'),
21         vertical: Drupal.t('Vertical orientation'),
22       },
23     },
24   );
25
26   /**
27    * Registers tabs with the toolbar.
28    *
29    * The Drupal toolbar allows modules to register top-level tabs. These may
30    * point directly to a resource or toggle the visibility of a tray.
31    *
32    * Modules register tabs with hook_toolbar().
33    *
34    * @type {Drupal~behavior}
35    *
36    * @prop {Drupal~behaviorAttach} attach
37    *   Attaches the toolbar rendering functionality to the toolbar element.
38    */
39   Drupal.behaviors.toolbar = {
40     attach(context) {
41       // Verify that the user agent understands media queries. Complex admin
42       // toolbar layouts require media query support.
43       if (!window.matchMedia('only screen').matches) {
44         return;
45       }
46       // Process the administrative toolbar.
47       $(context).find('#toolbar-administration').once('toolbar').each(function () {
48         // Establish the toolbar models and views.
49         const model = new Drupal.toolbar.ToolbarModel({
50           locked: JSON.parse(localStorage.getItem('Drupal.toolbar.trayVerticalLocked')),
51           activeTab: document.getElementById(JSON.parse(localStorage.getItem('Drupal.toolbar.activeTabID'))),
52           height: $('#toolbar-administration').outerHeight(),
53         });
54
55         Drupal.toolbar.models.toolbarModel = model;
56
57         // Attach a listener to the configured media query breakpoints.
58         // Executes it before Drupal.toolbar.views to avoid extra rendering.
59         Object.keys(options.breakpoints).forEach((label) => {
60           const mq = options.breakpoints[label];
61           const mql = window.matchMedia(mq);
62           Drupal.toolbar.mql[label] = mql;
63           // Curry the model and the label of the media query breakpoint to
64           // the mediaQueryChangeHandler function.
65           mql.addListener(Drupal.toolbar.mediaQueryChangeHandler.bind(null, model, label));
66           // Fire the mediaQueryChangeHandler for each configured breakpoint
67           // so that they process once.
68           Drupal.toolbar.mediaQueryChangeHandler.call(null, model, label, mql);
69         });
70
71         Drupal.toolbar.views.toolbarVisualView = new Drupal.toolbar.ToolbarVisualView({
72           el: this,
73           model,
74           strings: options.strings,
75         });
76         Drupal.toolbar.views.toolbarAuralView = new Drupal.toolbar.ToolbarAuralView({
77           el: this,
78           model,
79           strings: options.strings,
80         });
81         Drupal.toolbar.views.bodyVisualView = new Drupal.toolbar.BodyVisualView({
82           el: this,
83           model,
84         });
85
86         // Force layout render to fix mobile view. Only needed on load, not
87         // for every media query match.
88         model.trigger('change:isFixed', model, model.get('isFixed'));
89         model.trigger('change:activeTray', model, model.get('activeTray'));
90
91         // Render collapsible menus.
92         const menuModel = new Drupal.toolbar.MenuModel();
93         Drupal.toolbar.models.menuModel = menuModel;
94         Drupal.toolbar.views.menuVisualView = new Drupal.toolbar.MenuVisualView({
95           el: $(this).find('.toolbar-menu-administration').get(0),
96           model: menuModel,
97           strings: options.strings,
98         });
99
100         // Handle the resolution of Drupal.toolbar.setSubtrees.
101         // This is handled with a deferred so that the function may be invoked
102         // asynchronously.
103         Drupal.toolbar.setSubtrees.done((subtrees) => {
104           menuModel.set('subtrees', subtrees);
105           const theme = drupalSettings.ajaxPageState.theme;
106           localStorage.setItem(`Drupal.toolbar.subtrees.${theme}`, JSON.stringify(subtrees));
107           // Indicate on the toolbarModel that subtrees are now loaded.
108           model.set('areSubtreesLoaded', true);
109         });
110
111         // Trigger an initial attempt to load menu subitems. This first attempt
112         // is made after the media query handlers have had an opportunity to
113         // process. The toolbar starts in the vertical orientation by default,
114         // unless the viewport is wide enough to accommodate a horizontal
115         // orientation. Thus we give the Toolbar a chance to determine if it
116         // should be set to horizontal orientation before attempting to load
117         // menu subtrees.
118         Drupal.toolbar.views.toolbarVisualView.loadSubtrees();
119
120         $(document)
121           // Update the model when the viewport offset changes.
122           .on('drupalViewportOffsetChange.toolbar', (event, offsets) => {
123             model.set('offsets', offsets);
124           });
125
126         // Broadcast model changes to other modules.
127         model
128           .on('change:orientation', (model, orientation) => {
129             $(document).trigger('drupalToolbarOrientationChange', orientation);
130           })
131           .on('change:activeTab', (model, tab) => {
132             $(document).trigger('drupalToolbarTabChange', tab);
133           })
134           .on('change:activeTray', (model, tray) => {
135             $(document).trigger('drupalToolbarTrayChange', tray);
136           });
137
138         // If the toolbar's orientation is horizontal and no active tab is
139         // defined then show the tray of the first toolbar tab by default (but
140         // not the first 'Home' toolbar tab).
141         if (Drupal.toolbar.models.toolbarModel.get('orientation') === 'horizontal' && Drupal.toolbar.models.toolbarModel.get('activeTab') === null) {
142           Drupal.toolbar.models.toolbarModel.set({
143             activeTab: $('.toolbar-bar .toolbar-tab:not(.home-toolbar-tab) a').get(0),
144           });
145         }
146       });
147     },
148   };
149
150   /**
151    * Toolbar methods of Backbone objects.
152    *
153    * @namespace
154    */
155   Drupal.toolbar = {
156
157     /**
158      * A hash of View instances.
159      *
160      * @type {object.<string, Backbone.View>}
161      */
162     views: {},
163
164     /**
165      * A hash of Model instances.
166      *
167      * @type {object.<string, Backbone.Model>}
168      */
169     models: {},
170
171     /**
172      * A hash of MediaQueryList objects tracked by the toolbar.
173      *
174      * @type {object.<string, object>}
175      */
176     mql: {},
177
178     /**
179      * Accepts a list of subtree menu elements.
180      *
181      * A deferred object that is resolved by an inlined JavaScript callback.
182      *
183      * @type {jQuery.Deferred}
184      *
185      * @see toolbar_subtrees_jsonp().
186      */
187     setSubtrees: new $.Deferred(),
188
189     /**
190      * Respond to configured narrow media query changes.
191      *
192      * @param {Drupal.toolbar.ToolbarModel} model
193      *   A toolbar model
194      * @param {string} label
195      *   Media query label.
196      * @param {object} mql
197      *   A MediaQueryList object.
198      */
199     mediaQueryChangeHandler(model, label, mql) {
200       switch (label) {
201         case 'toolbar.narrow':
202           model.set({
203             isOriented: mql.matches,
204             isTrayToggleVisible: false,
205           });
206           // If the toolbar doesn't have an explicit orientation yet, or if the
207           // narrow media query doesn't match then set the orientation to
208           // vertical.
209           if (!mql.matches || !model.get('orientation')) {
210             model.set({ orientation: 'vertical' }, { validate: true });
211           }
212           break;
213
214         case 'toolbar.standard':
215           model.set({
216             isFixed: mql.matches,
217           });
218           break;
219
220         case 'toolbar.wide':
221           model.set({
222             orientation: ((mql.matches && !model.get('locked')) ? 'horizontal' : 'vertical'),
223           }, { validate: true });
224           // The tray orientation toggle visibility does not need to be
225           // validated.
226           model.set({
227             isTrayToggleVisible: mql.matches,
228           });
229           break;
230
231         default:
232           break;
233       }
234     },
235   };
236
237   /**
238    * A toggle is an interactive element often bound to a click handler.
239    *
240    * @return {string}
241    *   A string representing a DOM fragment.
242    */
243   Drupal.theme.toolbarOrientationToggle = function () {
244     return '<div class="toolbar-toggle-orientation"><div class="toolbar-lining">' +
245       '<button class="toolbar-icon" type="button"></button>' +
246       '</div></div>';
247   };
248
249   /**
250    * Ajax command to set the toolbar subtrees.
251    *
252    * @param {Drupal.Ajax} ajax
253    *   {@link Drupal.Ajax} object created by {@link Drupal.ajax}.
254    * @param {object} response
255    *   JSON response from the Ajax request.
256    * @param {number} [status]
257    *   XMLHttpRequest status.
258    */
259   Drupal.AjaxCommands.prototype.setToolbarSubtrees = function (ajax, response, status) {
260     Drupal.toolbar.setSubtrees.resolve(response.subtrees);
261   };
262 }(jQuery, Drupal, drupalSettings));