3144d13dc1b33788ae60aefdf1df786fa55fb794
[yaffs-website] / web / core / modules / menu_ui / menu_ui.admin.es6.js
1 /**
2  * @file
3  * Menu UI admin behaviors.
4  */
5
6 (function ($, Drupal) {
7   /**
8    *
9    * @type {Drupal~behavior}
10    */
11   Drupal.behaviors.menuUiChangeParentItems = {
12     attach(context, settings) {
13       const $menu = $('#edit-menu').once('menu-parent');
14       if ($menu.length) {
15         // Update the list of available parent menu items to match the initial
16         // available menus.
17         Drupal.menuUiUpdateParentList();
18
19         // Update list of available parent menu items.
20         $menu.on('change', 'input', Drupal.menuUiUpdateParentList);
21       }
22     },
23   };
24
25   /**
26    * Function to set the options of the menu parent item dropdown.
27    */
28   Drupal.menuUiUpdateParentList = function () {
29     const $menu = $('#edit-menu');
30     const values = [];
31
32     $menu.find('input:checked').each(function () {
33       // Get the names of all checked menus.
34       values.push(Drupal.checkPlain($.trim($(this).val())));
35     });
36
37     $.ajax({
38       url: `${location.protocol}//${location.host}${Drupal.url('admin/structure/menu/parents')}`,
39       type: 'POST',
40       data: { 'menus[]': values },
41       dataType: 'json',
42       success(options) {
43         const $select = $('#edit-menu-parent');
44         // Save key of last selected element.
45         const selected = $select.val();
46         // Remove all existing options from dropdown.
47         $select.children().remove();
48         // Add new options to dropdown. Keep a count of options for testing later.
49         let totalOptions = 0;
50         Object.keys(options || {}).forEach((machineName) => {
51           $select.append(
52             $(`<option ${machineName === selected ? ' selected="selected"' : ''}></option>`).val(machineName).text(options[machineName]),
53           );
54           totalOptions++;
55         });
56
57         // Hide the parent options if there are no options for it.
58         $select.closest('div').toggle(totalOptions > 0).attr('hidden', totalOptions === 0);
59       },
60     });
61   };
62 }(jQuery, Drupal));