MediaWiki:Common.js: Difference between revisions

added JS support for dynamic locale-based date format
(I broke the collapsible table code, probably by deleting a block of code that was labeled "experimental", but let's try the newest code from Wikipedia before restoring that)
(added JS support for dynamic locale-based date format)
 
Line 203: Line 203:
$(initHoverGIFs);
$(initHoverGIFs);


/***** autosort_sortable ********
/***** Auto-sorting tables ********
  * Auto-sorts sortable tables by a given column (why is this not built-in?!)
  * Auto-sorts sortable tables by a given column (why is this not built-in?!)
  * You must opt into this feature by placing "autosort" in the list of
  * You must opt into this feature by placing "autosort" in the list of
Line 278: Line 278:
}
}
$(sortTimer);
$(sortTimer);
/***** Auto-formatting dates ********
* Re-formats a date placed by [[Template:LocaleDate]] to match the
* month/day order of the user's locale.
*
*  Maintainers: [[User:Iritscen]]
*/
function getLang()
{
  if (navigator.languages !== undefined)
    return navigator.languages[0];
  return navigator.language;
}
/* Because CSS variables didn't seem to work for changing the .date-[day/month]::before rules,
  this function manually trawls the stylesheets until it finds those rules and changes them */
function changeDateSeparator(component, separator)
{
  const styleSheets = document.styleSheets;
  var ruleIndex;
 
  for (var i = 0; i < styleSheets.length; i++)
  {
    const rules = styleSheets[i].cssRules || styleSheets[i].rules;
    for (var j = 0; j < rules.length; j++)
    {
      if (rules[j].selectorText === '.mw-parser-output .date-'+component+'::before')
      {
        ruleIndex = j;
        break;
      }
    }
    if (ruleIndex !== undefined)
    {
      // Update the content of the existing rule
      styleSheets[i].deleteRule(ruleIndex);
      styleSheets[i].insertRule('.date-'+component+'::before{content:"'+separator+'";}', ruleIndex);
      break;
    }
  }
}
function localizeDates()
{
  const lang = getLang();
  const root = document.querySelector(':root');
  if (root == undefined || lang == undefined)
    return;
  if (lang != "en-US") // Template:LocaleDate prints dates in U.S.-style by default
  {
    root.style.setProperty('--month-order', '2');
    root.style.setProperty('--day-order', '1');
    changeDateSeparator('month', '/');
    changeDateSeparator('day', '');
  }
}
$(localizeDates);