MediaWiki:Common.js

From Disaster Risk Gateway
Revision as of 13:24, 13 October 2025 by Myriad-admin (talk | contribs)

Note: After publishing, you may have to bypass your browser's cache to see the changes.

  • Firefox / Safari: Hold Shift while clicking Reload, or press either Ctrl-F5 or Ctrl-R (⌘-R on a Mac)
  • Google Chrome: Press Ctrl-Shift-R (⌘-Shift-R on a Mac)
  • Internet Explorer / Edge: Hold Ctrl while clicking Refresh, or press Ctrl-F5
  • Opera: Press Ctrl-F5.
mw.loader.using(['mediawiki.util', 'mediawiki.searchSuggest'], function () {
  $(function () {
    if ($('#drg-navbar').length) return;

    // ===== Helpers =====
    function htmlFromPortlet(selector) {
      // Return array of <li>...</li> HTML for all anchors in a portlet list (if present)
      return $(selector).find('li a').map(function () {
        return '<li>' + $(this).prop('outerHTML') + '</li>';
      }).get();
    }

    function setBodyTopPaddingToNavbar() {
      var h = $('#drg-navbar').outerHeight() || 60;
      $('body').css('padding-top', h + 'px');
    }

    // ===== Logo =====
    const logoSrc = $('.mw-logo-icon').attr('src') || '/images/3/3f/Myriad_logo_icon_transparent.png';
    const logoHtml = `
      <a href="${mw.util.getUrl('Main_Page')}" class="drg-navbar-logo">
        <img src="${logoSrc}" alt="MYRIAD Logo">
      </a>`;

    // ===== Build left-side links in order: About, Navigation, Contribute =====
    const aboutHtml = `<a href="${mw.util.getUrl('Disaster_Risk_Gateway')}" class="flat-link">About</a>`;

    const navItems = [
      { title: 'Catalogue',   url: mw.util.getUrl('Catalogue') },
      { title: 'Definitions', url: mw.util.getUrl('Definitions') },
      { title: 'Resources',   url: mw.util.getUrl('Resources') }
    ];
    const navHtml = `
      <div class="drg-nav">
        <span>Navigation</span>
        <ul class="drg-nav-dropdown">
          ${navItems.map(i => `<li><a href="${i.url}">${i.title}</a></li>`).join('')}
        </ul>
      </div>`;

    const contributeHtml = `<a href="${mw.util.getUrl('Contribute')}" class="flat-link">Contribute</a>`;

    // ===== Search (with autocomplete) =====
    const searchDropdownHtml = `
      <div id="drg-search-dropdown" class="drg-search-dropdown-wrapper" style="position: relative; display: inline-block;">
        <span id="drg-search-toggle" class="flat-link" style="cursor:pointer;">Search</span>
        <form class="drg-search" id="drg-search-form" action="${mw.util.getUrl('Special:Search')}" method="get"
              style="display:none; position: absolute; top: 100%; left: 0; background: white; padding: 8px; box-shadow: 0 4px 8px rgba(0,0,0,0.1); z-index: 100;">
          <input type="search" name="search" placeholder="Search..." class="mw-searchInput" autocapitalize="off" autocomplete="off">
          <input type="submit" value="Search">
        </form>
      </div>`;

    // ===== User dropdown =====
    // We restore Echo (alerts/notices) + Watchlist inside the dropdown.
    let userHtml;
    if (mw.config.get('wgUserName')) {
      const items = [];

      // --- Echo notifications (ensure visible labels) ---
      function cloneWithLabel($a, fallback) {
        if (!$a || !$a.length) return null;
        const $c = $a.clone(); // keep original intact
        const hasText = ($c.text() || '').trim().length > 0;

        if (!hasText) {
          // Prefer a label from title (strip trailing counts), else fallback
          let fromTitle = ($c.attr('title') || '').trim();
          // Remove common trailing counters like " (3)" or " – 2"
          fromTitle = fromTitle.replace(/\s*[\-–—]?\s*\(?\d+\)?\s*$/, '').trim();
          // If still empty, use fallback
          const label = fromTitle || fallback;
          // Append a plain text node so the icon remains first
          $c.append(document.createTextNode(' ' + label));
        }
        return $c;
      }

      const alertA  = $('#pt-notifications-alert a').first();
      const noticeA = $('#pt-notifications-notice a').first();

      const alertC  = cloneWithLabel(alertA,  'Your Alerts');
      const noticeC = cloneWithLabel(noticeA, 'Your Notices');

      if (alertC)  items.push(`<li>${alertC.prop('outerHTML')}</li>`);
      if (noticeC) items.push(`<li>${noticeC.prop('outerHTML')}</li>`);

      // --- Personal tools (except duplicate logout at the end) ---
      $('#p-personal ul li').each(function () {
        const $a = $(this).find('a');
        const href = ($a.attr('href') || '');
        const titleText = ($a.text() || '').trim();

        // Skip Echo items we already copied
        if (href.includes('Notifications') || href.includes('Echo')) return;

        // Keep Watchlist
        if (href.match(/Watchlist/i)) {
          items.push(`<li>${$a.prop('outerHTML')}</li>`);
          return;
        }

        // Skip Logout (we add a clean one at the end)
        if (titleText.match(/^log ?out$/i)) return;

        // Include everyone else (Preferences, Contributions, etc.)
        items.push(`<li>${$a.prop('outerHTML')}</li>`);
      });

      // Add a divider then Logout
      items.push('<li class="drg-menu-divider"></li>');
      items.push(`<li><a href="${mw.util.getUrl('Special:UserLogout')}">Logout</a></li>`);

      userHtml = `
        <div class="drg-user">
          <span>Welcome, ${mw.config.get('wgUserName')}</span>
          <ul class="drg-user-dropdown">${items.join('')}</ul>
        </div>`;
    } else {
      userHtml = `<a class="drg-button" href="${mw.util.getUrl('Special:UserLogin')}">Login</a>`;
    }

    // ===== Tools dropdown (merge Actions + General like production) =====
    // Actions: #p-cactions; General: #p-tb (Toolbox + extensions)
    const actionsLis = htmlFromPortlet('#p-cactions');  // Actions
    let   generalLis = htmlFromPortlet('#p-tb');        // General (What links here, Upload, Special pages, etc.)

    // Fallback: also look for toolbox under Vector-2022 portlet structure if needed
    if (generalLis.length === 0) {
      generalLis = htmlFromPortlet('#vector-page-tools, #p-tb-list, .vector-page-tools .vector-menu-content');
    }

    const toolsHtml = `
      <div class="drg-tools">
        <span>Tools</span>
        <ul class="drg-tools-dropdown">
          ${actionsLis.length ? `<li class="drg-menu-header">Actions</li>${actionsLis.join('')}` : ''}
          ${actionsLis.length && generalLis.length ? '<li class="drg-menu-divider"></li>' : ''}
          ${generalLis.length ? `<li class="drg-menu-header">General</li>${generalLis.join('')}` : ''}
        </ul>
      </div>`;

    // ===== Inject Navbar =====
    $('body').prepend(`
      <div id="drg-navbar">
        <div class="drg-navbar-container">
          ${logoHtml}
          ${aboutHtml}
          ${navHtml}
          ${contributeHtml}
          ${searchDropdownHtml}
          <div class="drg-navbar-actions">
            ${userHtml}
            ${toolsHtml}
          </div>
        </div>
      </div>
    `);

    // ===== Toggle search input visibility + autocomplete focus =====
    $('#drg-search-toggle').on('click', function (e) {
      e.preventDefault();
      e.stopPropagation();
      $('#drg-search-form').toggle();
      $('#drg-search-form input[type="search"]').trigger('focus');
    });

    // Close search dropdown when clicking outside
    $(document).on('click', function () { $('#drg-search-form').hide(); });
    $('#drg-search-form').on('click', function (e) { e.stopPropagation(); });

    // Make sure body top padding matches navbar height (since it can wrap)
    setBodyTopPaddingToNavbar();
    $(window).on('load resize', setBodyTopPaddingToNavbar);

    // ===== Footer =====
    function insertFooter() {
      const icons = document.getElementById('footer-icons');
      if (!icons) return setTimeout(insertFooter, 100);

      icons.insertAdjacentHTML('beforebegin', `
        <footer id="drg-footer">
          <div class="drg-footer-inner">
            <div class="drg-columns">
              <div class="drg-column drg-column-left">
                <a href="/index.php/Disaster_Risk_Gateway">About</a>
                <a href="/index.php/Disaster_Risk_Gateway:Privacy_Notice">Privacy Notice</a>
                <a href="/index.php/Disaster_Risk_Gateway:Terms_of_Use">Terms of Use</a>
                <a href="mailto:DisasterRiskGateway@bgs.ac.uk"><strong>Contact Us</strong></a>
              </div>
              <div class="drg-column drg-column-center">
                <div class="drg-eu-flag">
                  <img src="/images/e/e3/Normal-reproduction-high-resolution_2.jpg" alt="EU logo">
                </div>
                <div class="drg-eu-text">
                  MYRIAD-EU project has received funding from the European Union’s Horizon 2020 Research and Innovation Programme under Grant Agreement No. 101003276.
                </div>
              </div>
              <div class="drg-column drg-column-right">
                <a href="https://www.myriadproject.eu" target="_blank">MYRIAD-EU</a>
                <a href="https://be.linkedin.com/company/myriad-eu-project" target="_blank">LinkedIn</a>
                <a href="#" target="_blank">MYRIAD-EU dashboard</a>
              </div>
            </div>
            <div class="drg-disclaimer-wrapper">
              <div class="drg-disclaimer">
                This site is hosted by the British Geological Survey but responsibility for the content of the site lies with the 
                <a href="https://www.myriadproject.eu" target="_blank" rel="noopener noreferrer">MYRIAD-EU project</a>.<br>
                Questions or comments: <a href="mailto:DisasterRiskGateway@bgs.ac.uk">DisasterRiskGateway@bgs.ac.uk</a>
              </div>
            </div>
          </div>
        </footer>
      `);
    }
    insertFooter();
  });
});